misono commited on
Commit
d49e060
·
verified ·
1 Parent(s): 67ac4e6

Publish reviewed insttrans benchmark

Browse files

Reviewed dataset, reproducible evaluation code and release manifest. See RELEASE_REVIEW.md for changes and validation.

.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ data/test.jsonl filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .env
5
+ .env.*
6
+ outputs/
7
+ .cache/
LICENSE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)
2
+
3
+ Copyright 2026 IndexTeam
4
+
5
+ This dataset is licensed under the Creative Commons Attribution-NonCommercial
6
+ 4.0 International License. You may share and adapt the material for
7
+ non-commercial purposes, provided that you give appropriate credit, provide a
8
+ link to the license, and indicate if changes were made.
9
+
10
+ The full legal code is available at:
11
+ https://creativecommons.org/licenses/by-nc/4.0/legalcode
README.md ADDED
@@ -0,0 +1,389 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ pretty_name: Instruction-Following Translation Bench
3
+ license: cc-by-nc-4.0
4
+ language:
5
+ - zh
6
+ - en
7
+ - ja
8
+ - ko
9
+ - ar
10
+ - de
11
+ - es
12
+ - fil
13
+ - fr
14
+ - hi
15
+ - id
16
+ - it
17
+ - ms
18
+ - nl
19
+ - pl
20
+ - pt
21
+ - ro
22
+ - ru
23
+ - sv
24
+ - th
25
+ - tr
26
+ - vi
27
+ task_categories:
28
+ - translation
29
+ size_categories:
30
+ - 1K<n<10K
31
+ tags:
32
+ - evaluation
33
+ - benchmark
34
+ - instruction-following
35
+ - constrained-translation
36
+ - subtitle
37
+ - terminology
38
+ configs:
39
+ - config_name: default
40
+ data_files:
41
+ - split: test
42
+ path: data/test.jsonl
43
+ ---
44
+
45
+ # Instruction-Following Translation Bench
46
+
47
+ Instruction-Following Translation Bench measures whether a translation system can
48
+ **obey explicit production constraints while translating**. Real content pipelines
49
+ rarely want a free translation: a subtitle line has to fit the time it is on
50
+ screen, a glossary term has to come out exactly as the glossary says, a JSON
51
+ payload has to come back with its keys intact, and a hashtag has to survive
52
+ untranslated so it still links. A system that translates beautifully but breaks
53
+ the structure around the text cannot be shipped.
54
+
55
+ The benchmark contains **3,000 evaluation instances** across **10 constraint
56
+ types**, **10 content domains** and **61 language pairs**, built from Bilibili
57
+ production content: subtitles, comments, on-screen comments, posts, novels,
58
+ columns, books, web text and academic papers.
59
+
60
+ The benchmark is released as part of the **Index-Translate** model family and is
61
+ referred to as **InstTrans** in the Index-Translate technical report.
62
+ See [Citation](#citation) for how to refer to it.
63
+
64
+ ## Task and motivation
65
+
66
+ Each instance gives the model a source text plus a numbered list of constraints,
67
+ and asks for a translation that satisfies all of them. Constraints are not
68
+ suggestions: the scoring treats five of them as gates, so a single structural
69
+ break zeroes the instance no matter how good the prose is.
70
+
71
+ The benchmark separates two things that are usually conflated:
72
+
73
+ - **Instruction following** — did the output keep the JSON keys, hit the glossary,
74
+ preserve the hashtag, respect the syllable budget, keep the line breaks?
75
+ - **Translation quality** — is the translation itself accurate and fluent?
76
+
77
+ Both are reported. A system can score well on quality and badly on
78
+ instruction following, and that gap is the thing this benchmark exists to expose.
79
+
80
+ ## Constraint types
81
+
82
+ Ten constraint types, split by how they are scored. **Hard** constraints are
83
+ checked by deterministic rules and act as gates. **Soft** constraints are scored
84
+ 0 / 0.5 / 1 by an LLM Judge and average into a multiplier.
85
+
86
+ | Constraint | Type | Instances | What it requires |
87
+ | --- | --- | ---: | --- |
88
+ | `format_preserve` | hard | 2,098 | Keep JSON / HTML / Markdown / placeholder structure intact |
89
+ | `syllable_order` | hard | 601 | Shorter on-screen durations get fewer syllables in the translation |
90
+ | `term_compliance` | hard | 502 | Render each glossary term exactly as specified |
91
+ | `social_preserve` | hard | 316 | Leave hashtags, `@mentions` and emote codes untranslated |
92
+ | `layout_break` | hard | 266 | Preserve line breaks, indentation and table alignment |
93
+ | `style_consistency` | soft | 633 | Hold the requested register (casual / neutral / formal) |
94
+ | `term_cross_sentence` | soft | 508 | Use one rendering of a term throughout the document |
95
+ | `academic_format_preserve` | soft | 412 | Leave LaTeX and citation markers untranslated |
96
+ | `context_disambiguate` | soft | 42 | Resolve a stated ambiguity the way the instruction says |
97
+ | `coref_resolution` | soft | 24 | Keep pronoun reference consistent with the stated antecedent |
98
+
99
+ Instances carry 1–5 constraints each: 1,307 have one, 1,138 two, 426 three, 104
100
+ four, and 25 five. The 5,402 constraint annotations over 3,000 instances mean the
101
+ average instance is scored on 1.8 constraints at once, which is where systems
102
+ tend to fail — satisfying a glossary while also preserving JSON is harder than
103
+ either alone.
104
+
105
+ ### The syllable constraint
106
+
107
+ `syllable_order` is the least obvious of the ten, and it is the one subtitle
108
+ production actually needs. Each subtitle instance ships `duration_s`, the
109
+ on-screen duration of every line. The requirement is not an absolute syllable
110
+ count but the **ordering**: if line 6 is on screen longer than line 2, its
111
+ translation should not be shorter in syllables.
112
+
113
+ Scoring is pairwise. For every pair of lines with different durations, the pair is
114
+ an inversion if the duration ordering and the syllable-count ordering disagree.
115
+ Concordance is `1 - inversions / comparable_pairs`, and the constraint passes at
116
+ **concordance >= 0.9**. Pairs with equal syllable counts are not inversions, and
117
+ pairs with equal durations are not comparable. Syllable counting is
118
+ language-specific (see [`eval/syllable.py`](eval/syllable.py)) and handles
119
+ numbers, acronyms and mixed scripts.
120
+
121
+ ## Dataset statistics
122
+
123
+ | Item | Count |
124
+ | --- | ---: |
125
+ | Evaluation instances | 3,000 |
126
+ | Constraint types | 10 |
127
+ | Constraint annotations | 5,402 |
128
+ | Language pairs | 61 |
129
+ | Target languages | 22 |
130
+ | Content domains | 10 |
131
+
132
+ | Domain | Value in `domain` | Instances |
133
+ | --- | --- | ---: |
134
+ | Bilibili posts | `B站动态` | 320 |
135
+ | Novels | `小说` | 303 |
136
+ | OGV subtitles | `ogv字幕` | 302 |
137
+ | On-screen comments | `弹幕` | 302 |
138
+ | Comments | `评论` | 300 |
139
+ | Columns | `专栏文章` | 300 |
140
+ | Academic papers | `学术论文` | 299 |
141
+ | UGC subtitles | `UGC字幕` | 299 |
142
+ | Books | `书籍` | 293 |
143
+ | Web text | `网页文本` | 282 |
144
+
145
+ The dominant direction is Chinese into 21 other languages (2,419 instances), plus
146
+ 313 English-source instances and 14–15 instances from each of 19 other source
147
+ languages. `zh` is also the most common target (296 instances), from the
148
+ English-source and other-source material.
149
+
150
+ Domains do not carry every constraint. On-screen comments, comments and posts only
151
+ ever carry `format_preserve`, `social_preserve` and `term_compliance`;
152
+ `syllable_order` appears only on subtitles, since only subtitles have durations;
153
+ `academic_format_preserve` concentrates in papers. This is a property of the
154
+ content, not a sampling gap — a hashtag constraint on an academic paper would be
155
+ artificial.
156
+
157
+ ## Files and schema
158
+
159
+ ```text
160
+ README.md
161
+ manifest.json
162
+ LICENSE
163
+ requirements.txt
164
+ data/test.jsonl
165
+ prepare_inputs.py
166
+ evaluate.py
167
+ eval/
168
+ __init__.py
169
+ constraints.py
170
+ prompts.py
171
+ judge_client.py
172
+ metrics.py
173
+ syllable.py
174
+ ```
175
+
176
+ `manifest.json` records release statistics, prompt versions, the redaction policy
177
+ and the SHA-256 checksum of the data file.
178
+
179
+ | Field | Type | Description |
180
+ | --- | --- | --- |
181
+ | `case_id` | string | Unique instance identifier; use it to match predictions. |
182
+ | `prompt` | string | The complete instruction sent to the model, including source text and constraints. |
183
+ | `reference` | string | Reference translation satisfying the constraints. Used by the quality Judge, never sent to the model. |
184
+ | `source_lang` | string | Source language code. |
185
+ | `target_lang` | string | Target language code. |
186
+ | `source_text` | string | Source text alone, extracted from `prompt`. Convenience field for rule checking. |
187
+ | `constraints` | list of strings | The numbered constraint lines, verbatim from `prompt`. Aligned 1:1 with `constraint_ids`. |
188
+ | `constraint_ids` | list of strings | Machine-readable constraint types for this instance. |
189
+ | `scenario` | string | Coarse content grouping (7 values). |
190
+ | `domain` | string | Fine content grouping (10 values); several domains share one scenario. |
191
+ | `duration_s` | list of floats | Per-line on-screen duration in seconds. Present on the 601 subtitle instances with `syllable_order`. |
192
+ | `batch_size` | integer | Number of sentences in a multi-sentence instance. Present when applicable. |
193
+ | `style` | object | Requested register, e.g. `{"formality": "casual"}`. Present when the instance specifies one. |
194
+
195
+ `prompt` is the single source of truth for what the model sees. `source_text` and
196
+ `constraints` are derived from it with the same extraction the scorer uses, so
197
+ they cannot drift apart.
198
+
199
+ Source text retains its original informal spelling, punctuation, emote codes and
200
+ `@mentions`; the `social_preserve` constraint depends on those surviving
201
+ translation, so they are not masked. Provenance identifiers (video and post IDs,
202
+ internal file paths) and authorship fields were removed from the release;
203
+ `manifest.json` records exactly which.
204
+
205
+ Contact details that can reach a person or a group chat — phone numbers, email
206
+ addresses, QQ group numbers and WeChat IDs, mostly appearing in promotional spam
207
+ inside user-generated text — are replaced by bare uppercase tokens
208
+ (`PHONE_REDACTED`, `EMAIL_REDACTED`, `QQ_GROUP_REDACTED`, `WECHAT_ID_REDACTED`)
209
+ in `prompt`, `reference` and `source_text`. This touches 15 of the 3,000
210
+ instances. No constraint scores contact details, and the masks were chosen to
211
+ contain no regex-special characters so they cannot be mistaken for an HTML tag, a
212
+ placeholder or a Markdown link by the format checkers; scoring the references
213
+ gives the same IF_Score before and after masking, with zero per-constraint
214
+ verdict changes. URLs and `@mentions` are kept, since `format_preserve` and
215
+ `social_preserve` score them.
216
+
217
+ ## Loading the data
218
+
219
+ ```bash
220
+ pip install -r requirements.txt
221
+ ```
222
+
223
+ ```python
224
+ from datasets import load_dataset
225
+
226
+ dataset = load_dataset(
227
+ "IndexTeam/InstTrans-Bench", split="test"
228
+ )
229
+ print(len(dataset)) # 3000
230
+ print(dataset[0]["prompt"])
231
+ print(dataset[0]["constraint_ids"])
232
+ ```
233
+
234
+ ## Generating translations
235
+
236
+ Export the standard model inputs from the repository root:
237
+
238
+ ```bash
239
+ python prepare_inputs.py --output outputs/model_inputs.jsonl
240
+ ```
241
+
242
+ Each output row contains only `case_id` and a chat-format `messages` list. Send
243
+ **only `messages`** to the model; use `case_id` locally to associate the returned
244
+ translation with the instance. Do not send the complete dataset row, since it
245
+ contains the reference translation.
246
+
247
+ Use any inference engine, then save one translation per instance as JSONL:
248
+
249
+ ```python
250
+ import json
251
+
252
+ with open("outputs/model_inputs.jsonl", encoding="utf-8") as handle:
253
+ inputs = [json.loads(line) for line in handle]
254
+
255
+ translations = [...] # one string per input, aligned with the rows above
256
+ assert len(translations) == len(inputs)
257
+ with open("outputs/predictions.jsonl", "w", encoding="utf-8") as handle:
258
+ for row, translation in zip(inputs, translations):
259
+ handle.write(json.dumps({
260
+ "case_id": row["case_id"],
261
+ "prediction": translation,
262
+ }, ensure_ascii=False) + "\n")
263
+ ```
264
+
265
+ Predictions should be final translations without reasoning traces or commentary.
266
+ Many instances require the output to be a JSON object with the source's keys, so
267
+ any wrapper text around it will fail `format_preserve` on its own. Record the
268
+ model revision, inference engine, decoding parameters and reasoning setting with
269
+ reported results.
270
+
271
+ ## Evaluation protocol
272
+
273
+ Scoring has two independent dimensions.
274
+
275
+ **IF_Score** is the headline metric, on a 0–1 scale:
276
+
277
+ ```
278
+ IF_Score = product(hard_constraint_passed) x mean(soft_constraint_scores)
279
+ ```
280
+
281
+ Every hard constraint is a gate: one failure sets the product to 0 and the
282
+ instance scores 0 regardless of the soft scores. Soft constraints are scored
283
+ 0 / 0.5 / 1 by the Judge and averaged. An instance with no soft constraints uses a
284
+ multiplier of 1.0, so it scores either 1.0 or 0.0.
285
+
286
+ **Translation quality** is scored separately by an LLM Judge that sees the source,
287
+ the reference and the candidate, and is told to ignore format and constraints
288
+ entirely. It is reported alongside IF_Score, not folded into it.
289
+
290
+ | Score | Quality interpretation |
291
+ | --- | --- |
292
+ | 1 | Accurate and natural; no serious errors, minimal minor ones. |
293
+ | 0.5 | Minor errors only, or few serious ones (under 10% of sentences); readable overall. |
294
+ | 0 | Many serious errors (over 10% of sentences); quality badly affected. |
295
+
296
+ Hard constraints are checked by deterministic rules in
297
+ [`eval/constraints.py`](eval/constraints.py), so that part of the score is
298
+ reproducible without a Judge at all:
299
+
300
+ ```bash
301
+ python evaluate.py \
302
+ --predictions outputs/predictions.jsonl \
303
+ --output-dir outputs/evaluation \
304
+ --skip-judge
305
+ ```
306
+
307
+ The full run needs a Judge. The default is `gpt-5.6-sol`. Configure an endpoint
308
+ and credentials for a provider you have access to; none are bundled.
309
+
310
+ ```bash
311
+ export JUDGE_API_BASE="https://YOUR_PROVIDER/v1"
312
+ export JUDGE_API_KEY="YOUR_API_KEY"
313
+
314
+ python evaluate.py \
315
+ --predictions outputs/predictions.jsonl \
316
+ --output-dir outputs/evaluation \
317
+ --judge-model gpt-5.6-sol
318
+ ```
319
+
320
+ The client picks a request shape from the model name. A reasoning model
321
+ (`gpt-5*`, `gpt-6*`, `o1`/`o3`/`o4`) goes to `/responses` with a 4,096-token
322
+ output budget and reasoning effort `none`; every other model goes to
323
+ `/chat/completions` at temperature `0` with a 2,048-token limit. Reasoning is
324
+ disabled so the Judge scores rather than deliberates, and the response cache keys
325
+ on the endpoint and its parameters, so switching Judge models never serves a
326
+ verdict produced under a different configuration.
327
+
328
+ If your provider serves a reasoning model on `/chat/completions` instead, pass a
329
+ model name outside those prefixes, or adjust `uses_responses_endpoint` in
330
+ [`eval/judge_client.py`](eval/judge_client.py).
331
+
332
+ The evaluator writes per-instance scores (`scores.jsonl`), aggregate metrics
333
+ (`summary.json`) and a reusable response cache. The summary breaks results down by
334
+ constraint, scenario, domain and language pair, and reports per-constraint pass
335
+ rates so a low IF_Score can be traced to the constraint causing it. Missing or
336
+ empty predictions score 0 and stay in the denominator. Duplicate or unknown
337
+ `case_id`s are rejected. Provider failures and invalid or incomplete Judge scores abort the run rather
338
+ than silently becoming quality scores. This public release validates the exact
339
+ 0/0.5/1 verdict, including the soft-constraint entries; malformed verdicts are
340
+ not excluded from the denominator or treated as a passed instruction.
341
+
342
+ `--limit N` scores the first N instances as a smoke check and marks the summary as
343
+ non-formal. Subset and `--skip-judge` scores are not full-benchmark results.
344
+
345
+ Scores obtained with a different Judge model, provider or decoding configuration
346
+ are not comparable. Report the Judge configuration alongside any new numbers.
347
+
348
+ ## Links
349
+
350
+ - Technical report: [Index-Translate Technical Report](https://github.com/bilibili/Index-Translate)
351
+
352
+ ## Citation
353
+
354
+ ```bibtex
355
+ @misc{indextranslate2026insttransbench,
356
+ title = {Instruction-Following Translation Bench},
357
+ author = {{Index LLM Team}},
358
+ year = {2026},
359
+ howpublished = {Evaluation benchmark},
360
+ note = {InstTrans benchmark of the Index-Translate model family}
361
+ }
362
+ ```
363
+
364
+ Cite the technical report for the model family, the training recipe, and the full
365
+ evaluation suite:
366
+
367
+ ```bibtex
368
+ @misc{indextranslate2026,
369
+ title = {Index-Translate: Controllable Multilingual Translation for
370
+ Content Production},
371
+ subtitle = {Text, Speech, Controlled Dubbing, and Long-Document Translation},
372
+ author = {{Index LLM Team}},
373
+ year = {2026},
374
+ howpublished = {Technical report},
375
+ url = {https://github.com/bilibili/Index-Translate}
376
+ }
377
+ ```
378
+
379
+ ## License
380
+
381
+ This dataset is released under the **Creative Commons
382
+ Attribution–NonCommercial 4.0 International (CC BY-NC 4.0)** license. You may
383
+ share and adapt the dataset for non-commercial purposes with appropriate
384
+ attribution. See [LICENSE](LICENSE) and the
385
+ [full license text](https://creativecommons.org/licenses/by-nc/4.0/).
386
+
387
+ ## Benchmark collection
388
+
389
+ Part of the [Index-Translate Benchmarks collection](https://huggingface.co/collections/IndexTeam/index-translate-benchmarks-6ac16fee5057f40abd7d31b7).
RELEASE_REVIEW.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Public release review
2
+
3
+ Reviewed on 2026-10-04.
4
+
5
+ - Preserved data and model/Judge prompts
6
+ - Rejected invalid quality and missing soft-constraint Judge verdicts
7
+ - Corrected redaction-policy description
8
+
9
+ Validation checks cover dataset loading, input/reference separation, source hashes, IDs and offline scoring behavior. No paid Judge calls or full model inference were run. Historical leaderboard numbers are source-reported results, not remeasured in this release.
data/test.jsonl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fa47b65120a3c00e8c7e66bfdfe0dd75274de8d100dbd1ce0540d754bd5a4b63
3
+ size 28217329
eval/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Evaluation helpers for Instruction-Following Translation Bench."""
eval/constraints.py ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Rule-based checkers for the five hard constraints.
2
+
3
+ Ported unchanged from the internal scorer so published scores stay comparable.
4
+ Each checker returns ``{"is_valid": bool, ...}`` with diagnostic detail.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ from typing import Any
12
+
13
+ from .syllable import cal_syllable_count
14
+
15
+ HARD_CONSTRAINT_IDS = frozenset({
16
+ "format_preserve", "layout_break", "term_compliance",
17
+ "syllable_order", "social_preserve",
18
+ })
19
+ SOFT_CONSTRAINT_IDS = frozenset({
20
+ "style_consistency", "context_disambiguate", "coref_resolution",
21
+ "term_cross_sentence", "academic_format_preserve",
22
+ })
23
+
24
+
25
+ # ======================== Constraint text parsing ========================
26
+
27
+ def parse_term_targets(constraint_lines: list[str]) -> list[str]:
28
+ """Target-side renderings from a `专名/术语对照: X→Y、...` line."""
29
+ target_terms = []
30
+ for line in constraint_lines:
31
+ if "术语对照" not in line and "专名" not in line:
32
+ continue
33
+ match = re.search(r"(?:专名/?)?术语对照[::]\s*(.*)", line)
34
+ if not match:
35
+ continue
36
+ for pair in re.split(r"[、,,]", match.group(1)):
37
+ if "→" in pair:
38
+ target = pair.split("→", 1)[1].strip()
39
+ if target:
40
+ target_terms.append(target)
41
+ return target_terms
42
+
43
+
44
+ def parse_layout_features(constraint_lines: list[str]) -> list[str]:
45
+ features = []
46
+ for line in constraint_lines:
47
+ if "布局" not in line and "排版" not in line:
48
+ continue
49
+ if "换行" in line:
50
+ features.append("newlines")
51
+ if "缩进" in line:
52
+ features.append("indent")
53
+ if "表格" in line:
54
+ features.append("table_align")
55
+ return features if features else ["newlines", "indent"]
56
+
57
+
58
+ def parse_social_elements(constraint_lines: list[str]) -> list[str]:
59
+ elements = []
60
+ for line in constraint_lines:
61
+ if "社交元素" not in line:
62
+ continue
63
+ for sep in (":", ":"):
64
+ if sep in line:
65
+ raw = line.split(sep, 1)[1].strip()
66
+ elements.extend(p.strip() for p in re.split(r"[、,,]", raw) if p.strip())
67
+ break
68
+ return elements
69
+
70
+
71
+ def collect_soft_constraint_descs(
72
+ constraint_ids: list[str], constraint_lines: list[str]
73
+ ) -> dict[str, str]:
74
+ """Map each soft constraint id to the prompt line stating it."""
75
+ keyword_map = {
76
+ "style_consistency": ["语体", "风格"],
77
+ "context_disambiguate": ["歧义", "消歧"],
78
+ "coref_resolution": ["指代", "代词"],
79
+ "term_cross_sentence": ["跨句", "全文统一"],
80
+ "academic_format_preserve": ["学术", "LaTeX", "学术格式"],
81
+ }
82
+ soft_descs: dict[str, str] = {}
83
+ for cid in constraint_ids:
84
+ if cid not in SOFT_CONSTRAINT_IDS:
85
+ continue
86
+ for line in constraint_lines:
87
+ if any(kw in line for kw in keyword_map.get(cid, [])):
88
+ soft_descs[cid] = line
89
+ break
90
+ soft_descs.setdefault(cid, cid)
91
+ return soft_descs
92
+
93
+
94
+ # ======================== Rule-based checkers ========================
95
+
96
+ def _build_term_pattern(term: str) -> str:
97
+ escaped = re.escape(term)
98
+ # CJK has no word boundaries; \b would never match against them.
99
+ if any(("一" <= ch <= "鿿") or ("぀" <= ch <= "ヿ") for ch in term):
100
+ return escaped
101
+ return rf"(?<!\w){escaped}(?!\w)"
102
+
103
+
104
+ def check_glossary(target_text: str, required_terms: list[str]) -> dict[str, Any]:
105
+ missing = [t for t in required_terms
106
+ if not re.search(_build_term_pattern(t), target_text)]
107
+ return {"is_valid": not missing, "missing_terms": missing}
108
+
109
+
110
+ def check_json_preserved(source_text: str, target_text: str) -> dict[str, Any]:
111
+ def extract_keys(text: str) -> tuple[bool, list[str]]:
112
+ try:
113
+ parsed = json.loads(text)
114
+ except json.JSONDecodeError:
115
+ return False, []
116
+ keys: list[str] = []
117
+
118
+ def walk(obj: Any, path: str = "") -> None:
119
+ if isinstance(obj, dict):
120
+ for key, value in obj.items():
121
+ current = f"{path}.{key}" if path else key
122
+ keys.append(current)
123
+ walk(value, current)
124
+ elif isinstance(obj, list):
125
+ for index, element in enumerate(obj):
126
+ walk(element, f"{path}[{index}]")
127
+
128
+ walk(parsed)
129
+ return True, keys
130
+
131
+ src_valid, src_keys = extract_keys(source_text)
132
+ tgt_valid, tgt_keys = extract_keys(target_text)
133
+ if not src_valid:
134
+ return {"is_valid": False, "issues": ["源文不是有效JSON"]}
135
+ if not tgt_valid:
136
+ return {"is_valid": False, "issues": ["译文不是有效JSON"]}
137
+
138
+ issues = []
139
+ missing = set(src_keys) - set(tgt_keys)
140
+ extra = set(tgt_keys) - set(src_keys)
141
+ if missing:
142
+ issues.append(f"缺失key: {missing}")
143
+ if extra:
144
+ issues.append(f"多余key: {extra}")
145
+ return {"is_valid": not issues, "issues": issues}
146
+
147
+
148
+ def _extract_visible_text(html: str) -> str:
149
+ return re.sub(r"<[^>]+>", "", html).strip()
150
+
151
+
152
+ def _chinese_ratio(text: str) -> float:
153
+ text = re.sub(r"\s+", "", text)
154
+ if not text:
155
+ return 0.0
156
+ return sum(1 for ch in text if "一" <= ch <= "鿿") / len(text)
157
+
158
+
159
+ def check_html_preserved(
160
+ source_text: str, target_text: str,
161
+ src_lang: str | None = None, tgt_lang: str | None = None,
162
+ ) -> dict[str, Any]:
163
+ tag_pattern = re.compile(r"</?[a-z][a-z0-9]*\b[^>]*>", re.IGNORECASE)
164
+ src_tag_types = [re.sub(r"\s+.*?>", ">", t) for t in tag_pattern.findall(source_text)]
165
+ tgt_tag_types = [re.sub(r"\s+.*?>", ">", t) for t in tag_pattern.findall(target_text)]
166
+
167
+ issues = []
168
+ if src_tag_types != tgt_tag_types:
169
+ issues.append(f"标签不一致: 源文{len(src_tag_types)}个, 译文{len(tgt_tag_types)}个")
170
+
171
+ if src_lang == "zh" and tgt_lang not in ("ja", "zh"):
172
+ tgt_visible = _extract_visible_text(target_text)
173
+ if tgt_visible and _extract_visible_text(source_text):
174
+ ratio = _chinese_ratio(tgt_visible)
175
+ if ratio > 0.01:
176
+ issues.append(f"译文中残留中文(占比{ratio:.1%})")
177
+
178
+ return {"is_valid": not issues, "issues": issues}
179
+
180
+
181
+ def check_markdown_preserved(source_text: str, target_text: str) -> dict[str, Any]:
182
+ md_patterns = [
183
+ (r"^#{1,6}\s", "标题"), (r"\*\*[^*]+\*\*", "粗体"),
184
+ (r"\*[^*]+\*", "斜体"), (r"`[^`]+`", "行内代码"),
185
+ (r"```[\s\S]*?```", "代码块"), (r"^[-*+]\s", "列表项"),
186
+ (r"^\d+\.\s", "有序列表"), (r"\[.*?\]\(.*?\)", "链接"),
187
+ (r"!\[.*?\]\(.*?\)", "图片"), (r"^>\s", "引用"),
188
+ (r"\|.*\|", "表格"),
189
+ ]
190
+ issues = []
191
+ for pattern, name in md_patterns:
192
+ if re.search(pattern, source_text, re.MULTILINE) and not re.search(
193
+ pattern, target_text, re.MULTILINE
194
+ ):
195
+ issues.append(f"丢失{name}标记")
196
+ return {"is_valid": not issues, "issues": issues}
197
+
198
+
199
+ def check_placeholder_preserved(source_text: str, target_text: str) -> dict[str, Any]:
200
+ patterns = [
201
+ r"\{[a-zA-Z_][a-zA-Z0-9_]*\}",
202
+ r"%[dsf]",
203
+ r"\$\d+",
204
+ r"\{\{[a-zA-Z_][a-zA-Z0-9_]*\}\}",
205
+ ]
206
+ issues = []
207
+ for pattern in patterns:
208
+ missing = set(re.findall(pattern, source_text)) - set(re.findall(pattern, target_text))
209
+ if missing:
210
+ issues.append(f"丢失占位符: {missing}")
211
+ return {"is_valid": not issues, "issues": issues}
212
+
213
+
214
+ def check_format_preserve(
215
+ source_text: str, target_text: str,
216
+ src_lang: str | None = None, tgt_lang: str | None = None,
217
+ ) -> dict[str, Any]:
218
+ """Dispatch to whichever format checkers the source text actually triggers."""
219
+ results: dict[str, Any] = {}
220
+ issues: list[str] = []
221
+ stripped = source_text.strip()
222
+
223
+ if stripped[:1] in ("{", "["):
224
+ try:
225
+ json.loads(stripped)
226
+ is_json = True
227
+ except json.JSONDecodeError:
228
+ is_json = False
229
+ if is_json:
230
+ sub = check_json_preserved(stripped, target_text.strip())
231
+ results["json"] = sub
232
+ if not sub["is_valid"]:
233
+ issues.extend(sub.get("issues", []))
234
+
235
+ if re.search(r"</?[a-z][a-z0-9]*\b[^>]*>", source_text, re.IGNORECASE):
236
+ sub = check_html_preserved(source_text, target_text, src_lang=src_lang, tgt_lang=tgt_lang)
237
+ results["html"] = sub
238
+ if not sub["is_valid"]:
239
+ issues.extend(sub.get("issues", []))
240
+
241
+ if re.search(r"^#{1,6}\s|\*\*|`|^[-*+]\s|^>\s|\[.*?\]\(.*?\)", source_text, re.MULTILINE):
242
+ sub = check_markdown_preserved(source_text, target_text)
243
+ results["markdown"] = sub
244
+ if not sub["is_valid"]:
245
+ issues.extend(sub.get("issues", []))
246
+
247
+ if re.search(
248
+ r"\{[a-zA-Z_][a-zA-Z0-9_]*\}|%[dsf]|\$\d+|\{\{[a-zA-Z_][a-zA-Z0-9_]*\}\}", source_text
249
+ ):
250
+ sub = check_placeholder_preserved(source_text, target_text)
251
+ results["placeholder"] = sub
252
+ if not sub["is_valid"]:
253
+ issues.extend(sub.get("issues", []))
254
+
255
+ return {"is_valid": not issues, "issues": issues, "sub_results": results}
256
+
257
+
258
+ def check_layout_preserved(
259
+ source_text: str, target_text: str, layout_features: list[str] | None = None
260
+ ) -> dict[str, Any]:
261
+ layout_features = layout_features or ["newlines", "indent"]
262
+ issues = []
263
+
264
+ if "newlines" in layout_features:
265
+ src_nl, tgt_nl = source_text.count("\n"), target_text.count("\n")
266
+ if src_nl != tgt_nl:
267
+ issues.append(f"换行数不一致: 源文{src_nl}, 译文{tgt_nl}")
268
+
269
+ if "indent" in layout_features:
270
+ src_indent = len(source_text) - len(source_text.lstrip())
271
+ tgt_indent = len(target_text) - len(target_text.lstrip())
272
+ if (src_indent > 0) != (tgt_indent > 0):
273
+ issues.append("缩进风格不一致")
274
+
275
+ if "table_align" in layout_features:
276
+ src_has = any("|" in l and l.count("|") >= 2 for l in source_text.splitlines())
277
+ tgt_has = any("|" in l and l.count("|") >= 2 for l in target_text.splitlines())
278
+ if src_has and not tgt_has:
279
+ issues.append("源文含表格对齐结构但译文丢失")
280
+
281
+ return {"is_valid": not issues, "issues": issues}
282
+
283
+
284
+ def check_social_preserve(target_text: str, elements: list[str]) -> dict[str, Any]:
285
+ if not elements:
286
+ return {"is_valid": True, "note": "no elements to check"}
287
+ missing = [e for e in elements if e not in target_text]
288
+ return {"is_valid": not missing, "missing_elements": missing}
289
+
290
+
291
+ def check_syllable_order(
292
+ prediction: str, durations: list[float], tgt_lang: str
293
+ ) -> dict[str, Any]:
294
+ """Rank-correlate per-sentence duration against translated syllable count.
295
+
296
+ Passes at concordance >= 0.9. Pairs with equal durations, and pairs with equal
297
+ syllable counts, are not counted as inversions.
298
+ """
299
+ if not durations or not prediction:
300
+ return {"is_valid": True, "note": "no duration data"}
301
+
302
+ try:
303
+ output = json.loads(prediction)
304
+ except (json.JSONDecodeError, TypeError):
305
+ return {"is_valid": False, "note": "output is not valid JSON"}
306
+ if not isinstance(output, dict):
307
+ return {"is_valid": False, "note": "output is not a JSON object"}
308
+
309
+ syllables = [
310
+ cal_syllable_count(output.get(str(i), ""), tgt_lang)
311
+ for i in range(1, len(durations) + 1)
312
+ ]
313
+ if len(syllables) < 2:
314
+ return {"is_valid": True, "note": "too few sentences"}
315
+
316
+ inversions = total_pairs = 0
317
+ for i in range(len(durations)):
318
+ for j in range(i + 1, len(durations)):
319
+ if durations[i] == durations[j]:
320
+ continue
321
+ total_pairs += 1
322
+ if syllables[i] == syllables[j]:
323
+ continue
324
+ if (durations[i] > durations[j]) != (syllables[i] > syllables[j]):
325
+ inversions += 1
326
+
327
+ if total_pairs == 0:
328
+ return {"is_valid": True, "note": "all durations equal"}
329
+
330
+ concordance = 1.0 - inversions / total_pairs
331
+ return {
332
+ "is_valid": concordance >= 0.9,
333
+ "concordance": round(concordance, 3),
334
+ "inversions": inversions,
335
+ "total_pairs": total_pairs,
336
+ }
337
+
338
+
339
+ def check_hard_constraints(row: dict[str, Any], prediction: str) -> dict[str, Any]:
340
+ """Run every hard checker this instance is annotated for."""
341
+ if not prediction:
342
+ return {}
343
+
344
+ source_text = row["source_text"]
345
+ constraint_lines = row["constraints"]
346
+ results: dict[str, Any] = {}
347
+
348
+ for cid in row["constraint_ids"]:
349
+ if cid not in HARD_CONSTRAINT_IDS:
350
+ continue
351
+ if cid == "format_preserve":
352
+ results[cid] = check_format_preserve(
353
+ source_text, prediction,
354
+ src_lang=row["source_lang"], tgt_lang=row["target_lang"],
355
+ )
356
+ elif cid == "layout_break":
357
+ results[cid] = check_layout_preserved(
358
+ source_text, prediction, parse_layout_features(constraint_lines))
359
+ elif cid == "term_compliance":
360
+ terms = parse_term_targets(constraint_lines)
361
+ results[cid] = (check_glossary(prediction, terms) if terms
362
+ else {"is_valid": True, "note": "no terms to check"})
363
+ elif cid == "syllable_order":
364
+ results[cid] = check_syllable_order(
365
+ prediction, row.get("duration_s", []), row["target_lang"])
366
+ elif cid == "social_preserve":
367
+ results[cid] = check_social_preserve(
368
+ prediction, parse_social_elements(constraint_lines))
369
+
370
+ return results
eval/judge_client.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI-compatible Judge client with a durable append-only cache.
2
+
3
+ Two request shapes, chosen by model name. Reasoning models are served on
4
+ ``/responses`` instead of ``/chat/completions`` -- on the gateway this benchmark
5
+ was scored with, a ``gpt-5.x`` model has no chat/completions cluster at all, so
6
+ sending one there fails rather than falling back -- and they take an output-token
7
+ budget and a reasoning effort in place of a temperature. Everything else uses
8
+ ``/chat/completions``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import random
16
+ import threading
17
+ import time
18
+ from pathlib import Path
19
+
20
+ # Chat models: deterministic decoding.
21
+ JUDGE_TEMPERATURE = 0.0
22
+ JUDGE_MAX_TOKENS = 2048
23
+
24
+ # Reasoning models: no temperature knob. Thinking is disabled so the Judge is
25
+ # scoring rather than deliberating, and the token budget is higher because the
26
+ # reasoning envelope counts against it even at effort "none".
27
+ JUDGE_MAX_OUTPUT_TOKENS = 4096
28
+ JUDGE_REASONING_EFFORT = "none"
29
+
30
+
31
+ def uses_responses_endpoint(model: str) -> bool:
32
+ return model.startswith(("gpt-5", "gpt-6", "o1", "o3", "o4"))
33
+
34
+
35
+ class JudgeRequestError(RuntimeError):
36
+ pass
37
+
38
+
39
+ class JudgeClient:
40
+ def __init__(
41
+ self,
42
+ *,
43
+ api_key: str,
44
+ base_url: str,
45
+ model: str,
46
+ prompt_version: str,
47
+ cache_path: Path,
48
+ timeout: float = 360.0,
49
+ max_attempts: int = 6,
50
+ ) -> None:
51
+ if not api_key:
52
+ raise ValueError("JUDGE_API_KEY is required")
53
+ from openai import OpenAI
54
+
55
+ self.model = model
56
+ self.prompt_version = prompt_version
57
+ self.timeout = timeout
58
+ self.max_attempts = max_attempts
59
+ self._use_responses = uses_responses_endpoint(model)
60
+ self.cache_path = cache_path
61
+ self.cache_path.parent.mkdir(parents=True, exist_ok=True)
62
+ self._client = OpenAI(api_key=api_key, base_url=base_url, timeout=timeout)
63
+ self._lock = threading.Lock()
64
+ self._cache: dict[str, str] = {}
65
+ self._load_cache()
66
+
67
+ def _key(self, prompt: str) -> str:
68
+ # The decoding parameters belong in the key, and the two endpoints do not
69
+ # share a set: keying a /responses verdict on a temperature it never used
70
+ # would let a cached chat verdict answer a reasoning-model request.
71
+ if self._use_responses:
72
+ params: dict[str, object] = {
73
+ "endpoint": "responses",
74
+ "max_output_tokens": JUDGE_MAX_OUTPUT_TOKENS,
75
+ "reasoning_effort": JUDGE_REASONING_EFFORT,
76
+ }
77
+ else:
78
+ params = {
79
+ "endpoint": "chat.completions",
80
+ "temperature": JUDGE_TEMPERATURE,
81
+ "max_tokens": JUDGE_MAX_TOKENS,
82
+ }
83
+ payload = json.dumps(
84
+ {
85
+ "model": self.model,
86
+ "prompt_version": self.prompt_version,
87
+ "prompt": prompt,
88
+ **params,
89
+ },
90
+ ensure_ascii=False,
91
+ sort_keys=True,
92
+ separators=(",", ":"),
93
+ )
94
+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()
95
+
96
+ def _load_cache(self) -> None:
97
+ if not self.cache_path.is_file():
98
+ return
99
+ with self.cache_path.open(encoding="utf-8") as handle:
100
+ for line_number, line in enumerate(handle, 1):
101
+ if not line.strip():
102
+ continue
103
+ try:
104
+ record = json.loads(line)
105
+ self._cache[record["key"]] = record["response"]
106
+ except (json.JSONDecodeError, KeyError, TypeError):
107
+ # An interrupted final append must not destroy earlier cache entries.
108
+ if line_number > 1:
109
+ continue
110
+
111
+ def _cache_put(self, key: str, response: str) -> None:
112
+ with self._lock:
113
+ if key in self._cache:
114
+ return
115
+ self._cache[key] = response
116
+ with self.cache_path.open("a", encoding="utf-8") as handle:
117
+ handle.write(json.dumps({"key": key, "response": response}, ensure_ascii=False))
118
+ handle.write("\n")
119
+ handle.flush()
120
+
121
+ def _complete_via_chat(self, prompt: str) -> str:
122
+ response = self._client.chat.completions.create(
123
+ model=self.model,
124
+ messages=[{"role": "user", "content": prompt}],
125
+ temperature=JUDGE_TEMPERATURE,
126
+ max_tokens=JUDGE_MAX_TOKENS,
127
+ )
128
+ return response.choices[0].message.content or ""
129
+
130
+ def _complete_via_responses(self, prompt: str) -> str:
131
+ response = self._client.responses.create(
132
+ model=self.model,
133
+ input=prompt,
134
+ max_output_tokens=JUDGE_MAX_OUTPUT_TOKENS,
135
+ reasoning={"effort": JUDGE_REASONING_EFFORT},
136
+ )
137
+ # Walk the output blocks rather than reading output_text: with reasoning
138
+ # enabled the array also carries reasoning items, and a provider that
139
+ # ignores effort="none" would otherwise fold thinking into the verdict.
140
+ parts = []
141
+ for block in response.output or []:
142
+ if getattr(block, "type", None) != "message":
143
+ continue
144
+ for item in getattr(block, "content", None) or []:
145
+ if getattr(item, "type", None) == "output_text":
146
+ parts.append(getattr(item, "text", "") or "")
147
+ return "".join(parts)
148
+
149
+ def complete(self, prompt: str) -> tuple[str, bool]:
150
+ """Return (response_text, served_from_cache)."""
151
+ key = self._key(prompt)
152
+ with self._lock:
153
+ cached = self._cache.get(key)
154
+ if cached is not None:
155
+ return cached, True
156
+
157
+ error: BaseException | None = None
158
+ for attempt in range(self.max_attempts):
159
+ try:
160
+ content = (
161
+ self._complete_via_responses(prompt) if self._use_responses
162
+ else self._complete_via_chat(prompt)
163
+ )
164
+ self._cache_put(key, content)
165
+ return content, False
166
+ except BaseException as exc:
167
+ error = exc
168
+ status_code = getattr(exc, "status_code", None)
169
+ retryable = status_code == 429 or (
170
+ isinstance(status_code, int) and 500 <= status_code < 600
171
+ )
172
+ # Connection/transport failures usually have no HTTP status.
173
+ if status_code is None:
174
+ retryable = True
175
+ if retryable and attempt + 1 < self.max_attempts:
176
+ time.sleep(min(2 ** (attempt + 1), 60) + random.uniform(0, 1))
177
+ continue
178
+ break
179
+ raise JudgeRequestError(
180
+ f"Judge request failed after {self.max_attempts} attempts: {error}"
181
+ ) from error
182
+
183
+ @property
184
+ def cache_entries(self) -> int:
185
+ return len(self._cache)
eval/metrics.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Score parsing and aggregation.
2
+
3
+ The headline metric is IF_Score: ``product(hard_pass) x mean(soft_scores)``. A
4
+ single failed hard constraint zeroes the instance; soft constraints average into
5
+ a 0-1 multiplier. Instances with no soft constraints use a multiplier of 1.0, so
6
+ they score 1.0 or 0.0.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ from collections import Counter, defaultdict
14
+ from typing import Any
15
+
16
+ SCORES = (0.0, 0.5, 1.0)
17
+
18
+
19
+ def parse_quality_score(response: str) -> float | None:
20
+ """Parse a 0 / 0.5 / 1 quality verdict. Returns None if unparseable."""
21
+ text = (response or "").strip()
22
+ if text.startswith("[") and text.endswith("]"):
23
+ text = text[1:-1].strip()
24
+ if not re.fullmatch(r"(?:0(?:\.0+)?|0\.50*|1(?:\.0+)?)", text):
25
+ return None
26
+ return float(text)
27
+
28
+
29
+ def parse_soft_constraint_scores(
30
+ response: str, constraint_ids: list[str]
31
+ ) -> dict[str, dict[str, Any]]:
32
+ """Parse the soft-constraint Judge's JSON verdict, keyed by constraint id."""
33
+ unscored = {cid: {"score": None} for cid in constraint_ids}
34
+ if not response:
35
+ return unscored
36
+
37
+ data = None
38
+ try:
39
+ data = json.loads(response.strip())
40
+ except json.JSONDecodeError:
41
+ # The Judge sometimes wraps the object in prose or a code fence.
42
+ match = re.search(r"\{[\s\S]*\}", response)
43
+ if match:
44
+ try:
45
+ data = json.loads(match.group(0))
46
+ except json.JSONDecodeError:
47
+ pass
48
+
49
+ if not isinstance(data, dict):
50
+ return unscored
51
+
52
+ results: dict[str, dict[str, Any]] = {}
53
+ for cid in constraint_ids:
54
+ entry = data.get(cid)
55
+ if isinstance(entry, dict):
56
+ try:
57
+ score = float(entry.get("score"))
58
+ except (TypeError, ValueError):
59
+ score = None
60
+ if score in (0, 0.5, 1):
61
+ results[cid] = {"score": score, "note": entry.get("note", "")}
62
+ continue
63
+ results[cid] = {"score": None}
64
+ return results
65
+
66
+
67
+ def compute_if_score(
68
+ hard_results: dict[str, Any], soft_results: dict[str, Any]
69
+ ) -> float:
70
+ hard_pass = 1.0
71
+ for result in hard_results.values():
72
+ if not result.get("is_valid", True):
73
+ hard_pass = 0.0
74
+ break
75
+ soft_values = [r["score"] for r in soft_results.values() if r.get("score") is not None]
76
+ soft_mean = sum(soft_values) / len(soft_values) if soft_values else 1.0
77
+ return hard_pass * soft_mean
78
+
79
+
80
+ def _score_key(score: float) -> str:
81
+ return "0" if score == 0 else "0.5" if score == 0.5 else "1"
82
+
83
+
84
+ def aggregate_group(rows: list[dict[str, Any]]) -> dict[str, Any]:
85
+ total = len(rows)
86
+ covered = sum(row["prediction_status"] == "present" for row in rows)
87
+ if_scores = [float(row["if_score"]) for row in rows]
88
+ quality = [row["quality_score"] for row in rows if row["quality_score"] is not None]
89
+ return {
90
+ "total": total,
91
+ "prediction_coverage": covered,
92
+ "prediction_coverage_rate": covered / total if total else 0.0,
93
+ "if_score": sum(if_scores) / total if total else 0.0,
94
+ "translation_quality": sum(quality) / len(quality) if quality else None,
95
+ "quality_scored": len(quality),
96
+ "quality_distribution": {
97
+ _score_key(s): sum(1 for q in quality if q == s) for s in SCORES
98
+ },
99
+ }
100
+
101
+
102
+ def aggregate_constraints(rows: list[dict[str, Any]]) -> dict[str, Any]:
103
+ """Per-constraint pass rate (hard) or mean score (soft)."""
104
+ hard: dict[str, Counter] = defaultdict(Counter)
105
+ soft: dict[str, list[float]] = defaultdict(list)
106
+
107
+ for row in rows:
108
+ for cid, result in row["hard_constraint_results"].items():
109
+ hard[cid]["total"] += 1
110
+ if result.get("is_valid", True):
111
+ hard[cid]["pass"] += 1
112
+ for cid, result in row["soft_constraint_results"].items():
113
+ if result.get("score") is not None:
114
+ soft[cid].append(float(result["score"]))
115
+
116
+ out: dict[str, Any] = {}
117
+ for cid, counts in sorted(hard.items()):
118
+ total = counts["total"]
119
+ out[cid] = {
120
+ "type": "hard",
121
+ "total": total,
122
+ "pass": counts["pass"],
123
+ "pass_rate": counts["pass"] / total if total else None,
124
+ }
125
+ for cid, scores in sorted(soft.items()):
126
+ out[cid] = {
127
+ "type": "soft",
128
+ "total": len(scores),
129
+ "mean_score": sum(scores) / len(scores) if scores else None,
130
+ "score_distribution": {
131
+ _score_key(s): sum(1 for v in scores if v == s) for s in SCORES
132
+ },
133
+ }
134
+ return out
135
+
136
+
137
+ def compute_summary(rows: list[dict[str, Any]]) -> dict[str, Any]:
138
+ summary = aggregate_group(rows)
139
+ summary["by_constraint"] = aggregate_constraints(rows)
140
+
141
+ grouped: dict[str, dict[str, list[dict[str, Any]]]] = {
142
+ "scenario": defaultdict(list),
143
+ "domain": defaultdict(list),
144
+ "language_pair": defaultdict(list),
145
+ }
146
+ for row in rows:
147
+ grouped["scenario"][row["scenario"]].append(row)
148
+ grouped["domain"][row["domain"]].append(row)
149
+ grouped["language_pair"][f"{row['source_lang']}-{row['target_lang']}"].append(row)
150
+
151
+ summary["breakdowns"] = {
152
+ dimension: {key: aggregate_group(group) for key, group in sorted(groups.items())}
153
+ for dimension, groups in grouped.items()
154
+ }
155
+ return summary
eval/prompts.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Model input construction and Judge prompts.
2
+
3
+ The model prompt is the dataset's own ``prompt`` field, sent verbatim: it already
4
+ carries the task instruction, the source text and the numbered constraints, so
5
+ rewriting it here would change what the benchmark measures.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from typing import Any
11
+
12
+ MODEL_PROMPT_VERSION = "insttrans-inference-v1"
13
+ QUALITY_JUDGE_PROMPT_VERSION = "insttrans-quality-judge-v1"
14
+ SOFT_CONSTRAINT_JUDGE_PROMPT_VERSION = "insttrans-soft-constraint-judge-v1"
15
+
16
+ LANGUAGE_NAMES = {
17
+ "ar": "阿拉伯语", "de": "德语", "en": "英语", "es": "西班牙语",
18
+ "fil": "菲律宾语", "fr": "法语", "hi": "印地语", "id": "印尼语",
19
+ "it": "意大利语", "ja": "日语", "ko": "韩语", "ms": "马来语",
20
+ "nl": "荷兰语", "pl": "波兰语", "pt": "葡萄牙语", "ro": "罗马尼亚语",
21
+ "ru": "俄语", "sv": "瑞典语", "th": "泰语", "tr": "土耳其语",
22
+ "vi": "越南语", "zh": "中文",
23
+ }
24
+
25
+
26
+ def build_model_messages(row: dict[str, Any]) -> list[dict[str, str]]:
27
+ """Chat messages for the system under test. Sends `prompt` unchanged."""
28
+ return [{"role": "user", "content": row["prompt"]}]
29
+
30
+
31
+ def _lang_name(code: str) -> str:
32
+ return LANGUAGE_NAMES.get(code, code)
33
+
34
+
35
+ def build_quality_prompt(row: dict[str, Any], prediction: str) -> str:
36
+ """Translation-quality Judge prompt (0 / 0.5 / 1).
37
+
38
+ `web_html` instances get a variant that tells the Judge to score only the
39
+ visible text, because their source embeds HTML/JSON markup.
40
+ """
41
+ src_name = _lang_name(row["source_lang"])
42
+ tgt_name = _lang_name(row["target_lang"])
43
+ source_text = row["source_text"]
44
+ reference = row["reference"]
45
+
46
+ if row.get("scenario") == "web_html":
47
+ return f"""你是精通{src_name}和{tgt_name}的网页文本翻译质量评估专家。请仅从翻译准确性和流畅度角度评估以下<待评估译文>。
48
+ 注意:源文中包含HTML/JSON标签,这些标签是文本的一部分,评估时只关注可见文本的翻译质量。
49
+
50
+ # 评估维度
51
+
52
+ ## 翻译准确性
53
+ <严重错误>:
54
+ - 可见文本的核心语义发生变化、漏译或严重误译。
55
+ - 添加了原文中不存在的内容。
56
+
57
+ <轻度错误>:
58
+ - 专有名词翻译不准确。
59
+ - 部分表达语义有偏移。
60
+
61
+ ## 译文流畅度
62
+ <严重错误>:
63
+ - 可见文本不通顺,无法正常阅读理解。
64
+
65
+ <轻度错误>:
66
+ - 用词不够自然,有翻译腔。
67
+ - 语法有轻微瑕疵但不影响理解。
68
+
69
+ # 评分标准
70
+ 评分时请考虑文本长度:短文本(1-3句)和长文本(10句以上)应使用相同的质量密度标准,即关注错误占比而非错误绝对数量。
71
+ 1分: 翻译准确自然,无严重错误。轻度错误占比极低(不超过总句数的10%)。
72
+ 0.5分: 无严重错误,轻度错误占比适中(约10%-30%的句子有轻度错误),整体可读。
73
+ 0分: 有严重错误;或轻度错误占比过高(超过30%的句子有轻度错误),严重影响整体质量。
74
+
75
+ # 评估材料
76
+
77
+ <源文>:
78
+ {source_text}
79
+
80
+ <参考译文>:
81
+ {reference}
82
+
83
+ <待评估译文>:
84
+ {prediction}
85
+
86
+ 请将你的打分写在<输出>中,直接输出[0/0.5/1]中的数字,不要输出任何其他内容。
87
+ <输出>:"""
88
+
89
+ return f"""你是精通{src_name}和{tgt_name}的翻译质量评估专家。请仅从翻译准确性和流畅度角度评估以下<待评估译文>,不评估格式、约束等方面。
90
+
91
+ # 评估维度
92
+
93
+ ## 翻译准确性
94
+ <严重错误>:
95
+ - 核心语义发生变化,原文意思被曲解。
96
+ - 重要内容漏译或严重误译。
97
+ - 添加了原文中不存在的内容。
98
+
99
+ <轻度错误>:
100
+ - 专有名词翻译不准确。
101
+ - 部分表达语义有偏移。
102
+
103
+ ## 译文流畅度
104
+ <严重错误>:
105
+ - 译文不通顺,无法正常阅读理解。
106
+ - 出现目标语言中不自然的表达方式。
107
+
108
+ <轻度错误>:
109
+ - 用词不够自然,有翻译腔。
110
+ - 语法有轻微瑕疵但不影响理解。
111
+
112
+ # 评分标准
113
+ 评分时请考虑文本长度:短文本(1-3句)和长文本(10句以上)应使用相同的质量密度标准,即关注错误占比而非错误绝对数量。
114
+ 1分: 翻译准确自然,无严重错误,轻度错误极少。
115
+ 0.5分: 只有轻度错误,或仅有少量严重错误(不超过总句数的10%),整体可读。
116
+ 0分: 有大量严重错误(超过总句数的10%),严重影响整体质量。
117
+
118
+ # 评估材料
119
+
120
+ <源文>:
121
+ {source_text}
122
+
123
+ <参考译文>:
124
+ {reference}
125
+
126
+ <待评估译文>:
127
+ {prediction}
128
+
129
+ 请将你的打分写在<输出>中,直接输出[0/0.5/1]中的数字,不要输出任何其他内容。
130
+ <输出>:"""
131
+
132
+
133
+ SOFT_CONSTRAINT_JUDGE_TEMPLATE = """请评估译文对每条约束的满足程度。
134
+
135
+ 【源文】
136
+ {source_text}
137
+
138
+ 【译文】
139
+ {target_text}
140
+
141
+ 【约束列表】
142
+ {constraint_list}
143
+
144
+ 评分标准(每条约束三档):
145
+ - 1:完全满足
146
+ - 0.5:部分满足(有小瑕疵但不影响理解)
147
+ - 0:未满足或严重偏离
148
+
149
+ 如果译文中存在大���内容不断重复(同一句话或片段连续出现3次及以上),所有约束直接判0分。
150
+
151
+ 请输出JSON,以约束ID为key:
152
+ {{
153
+ "constraint_id": {{
154
+ "score": 0或0.5或1,
155
+ "note": "简短说明"
156
+ }}
157
+ }}
158
+
159
+ 只输出JSON,不要输出任何其他内容。"""
160
+
161
+
162
+ def build_soft_constraint_prompt(
163
+ row: dict[str, Any], prediction: str, soft_descs: dict[str, str]
164
+ ) -> str:
165
+ constraint_list = "\n".join(f"[{cid}] {desc}" for cid, desc in soft_descs.items())
166
+ return SOFT_CONSTRAINT_JUDGE_TEMPLATE.format(
167
+ source_text=row["source_text"],
168
+ target_text=prediction,
169
+ constraint_list=constraint_list,
170
+ )
eval/syllable.py ADDED
@@ -0,0 +1,1232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pyphen
2
+ import re
3
+ import threading
4
+ import fugashi
5
+ from num2words import num2words
6
+
7
+
8
+ # ========== 工具模块:Pyphen 缓存 ==========
9
+
10
+ class PyphenCache:
11
+ _instance = None
12
+ _cache = {}
13
+
14
+ def __new__(cls):
15
+ if cls._instance is None:
16
+ cls._instance = super().__new__(cls)
17
+ return cls._instance
18
+
19
+ def get_dictionary(self, lang_code):
20
+ if lang_code not in self._cache:
21
+ self._cache[lang_code] = pyphen.Pyphen(lang=lang_code)
22
+ return self._cache[lang_code]
23
+
24
+
25
+ _pyphen_cache = PyphenCache()
26
+
27
+
28
+ def _pyphen_syllable_count(word, pyphen_lang):
29
+ """使用 pyphen 计算音节数(带缓存,规范化处理)"""
30
+ # 规范化:去除尾部标点和连字符
31
+ clean_word = word.rstrip(".,;:!?()[]{}\"\'-")
32
+ normalized = clean_word.replace("-", "") # 避免连字符被算作音节分隔
33
+
34
+ # 检查西语词典
35
+ if pyphen_lang == 'es_ES' and normalized.lower() in _SPANISH_SYLLABLES:
36
+ return _SPANISH_SYLLABLES[normalized.lower()]
37
+
38
+ try:
39
+ dic = _pyphen_cache.get_dictionary(pyphen_lang)
40
+ hyphenated = dic.inserted(normalized)
41
+ return hyphenated.count("-") + 1
42
+ except Exception:
43
+ return _fallback_syllable_count(normalized)
44
+
45
+ def _fallback_syllable_count(word):
46
+ word = word.lower()
47
+ if len(word) <= 3:
48
+ return 1
49
+
50
+ count = 0
51
+ vowels = "aeiouy"
52
+
53
+ if word[0] in vowels:
54
+ count += 1
55
+
56
+ for i in range(1, len(word)):
57
+ if word[i] in vowels and word[i - 1] not in vowels:
58
+ count += 1
59
+
60
+ if word.endswith('e'):
61
+ count -= 1
62
+ if word.endswith('le') and len(word) > 2 and word[-3] not in vowels:
63
+ count += 1
64
+
65
+ return max(1, count)
66
+
67
+
68
+ # ========== 混合内容解析器 ==========
69
+
70
+ _SCRIPT_RANGES = [
71
+ (re.compile(r'[一-鿿㐀-䶿]'), 'han'),
72
+ (re.compile(r'[぀-ゟ゠-ヿ]'), 'kana'),
73
+ (re.compile(r'[ء-يٱ-ۓە-ۿ'
74
+ r'ݐ-ݿࢠ-ࣿ'
75
+ r'ﭐ-﷿ﹰ-]'), 'arabic'),
76
+ (re.compile(r'[ً-ٰٟٓ]'), 'arabic_diacritic'),
77
+ (re.compile(r'[a-zA-ZÀ-ÿŒœ]'), 'latin'), # 包含扩展拉丁字母(包括 Œ/œ)
78
+ (re.compile(r'[0-9٠-٩0-9]'), 'number'), # ASCII、阿拉伯语、全角数字
79
+ ]
80
+
81
+
82
+ def _detect_script(char):
83
+ for pattern, script in _SCRIPT_RANGES:
84
+ if pattern.match(char):
85
+ return script
86
+ return 'other'
87
+
88
+
89
+ def _parse_mixed_content(text):
90
+ if not text:
91
+ return []
92
+
93
+ segments = []
94
+ current_segment = ""
95
+ current_type = None
96
+
97
+ i = 0
98
+ while i < len(text):
99
+ char = text[i]
100
+ char_type = _detect_script(char)
101
+
102
+ # 处理数字相关的特殊格式
103
+ if char_type == 'number' or (char_type == 'other' and char in '.-/$'):
104
+ # 尝试匹配完整的数字格式(包括电话号码、小数、货币等)
105
+ number_match = re.match(r'[\d.,\-/$]+', text[i:])
106
+ if number_match:
107
+ number_str = number_match.group()
108
+ # 检查是否包含数字
109
+ if re.search(r'\d', number_str):
110
+ # 检查是否是 COVID-19 这类字母+连字符+数字
111
+ # 如果前面紧邻字母且以连字符开头,这是连字符词的一部分
112
+ if number_str.startswith('-') and i > 0 and text[i-1].isalpha():
113
+ # 这是连字符词的一部分,不单独处理
114
+ if current_type:
115
+ current_segment += char
116
+ else:
117
+ current_segment = char
118
+ current_type = 'other'
119
+ i += 1
120
+ continue
121
+
122
+ # 检查是否有序数后缀(st, nd, rd, th)
123
+ ordinal_suffix = ''
124
+ next_pos = i + len(number_str)
125
+ if next_pos + 2 <= len(text):
126
+ potential_suffix = text[next_pos:next_pos+2]
127
+ if potential_suffix.lower() in ('st', 'nd', 'rd', 'th'):
128
+ ordinal_suffix = potential_suffix
129
+
130
+ if current_segment and current_type:
131
+ segments.append((current_segment.strip(), current_type))
132
+
133
+ # 如果有序数后缀,合并到数字中
134
+ if ordinal_suffix:
135
+ segments.append((number_str + ordinal_suffix, 'number'))
136
+ i += len(number_str) + len(ordinal_suffix)
137
+ else:
138
+ segments.append((number_str, 'number'))
139
+ i += len(number_str)
140
+
141
+ current_segment = ""
142
+ current_type = None
143
+ continue
144
+
145
+ if char_type == 'other':
146
+ if char.isspace():
147
+ if current_type == 'latin':
148
+ current_segment += char
149
+ i += 1
150
+ continue
151
+ elif current_segment:
152
+ segments.append((current_segment.strip(), current_type))
153
+ current_segment = ""
154
+ current_type = None
155
+ i += 1
156
+ continue
157
+ if current_type:
158
+ current_segment += char
159
+ i += 1
160
+ continue
161
+
162
+ # arabic diacritics 归入 arabic
163
+ if char_type == 'arabic_diacritic':
164
+ char_type = 'arabic'
165
+
166
+ if char_type == current_type:
167
+ current_segment += char
168
+ else:
169
+ if current_segment:
170
+ segments.append((current_segment.strip(), current_type))
171
+ current_segment = char
172
+ current_type = char_type
173
+
174
+ i += 1
175
+
176
+ if current_segment and current_segment.strip():
177
+ segments.append((current_segment.strip(), current_type))
178
+
179
+ return segments
180
+
181
+
182
+ # ========== 数字展开模块 ==========
183
+
184
+ # num2words 语言代码映射
185
+ _NUM2WORDS_LANG_MAP = {
186
+ 'en': 'en',
187
+ 'zh': 'zh',
188
+ 'ja': 'ja',
189
+ 'de': 'de',
190
+ 'fr': 'fr',
191
+ 'es': 'es',
192
+ 'ar': 'ar',
193
+ }
194
+
195
+ # 英语字母发音音节数 (A=1, B=1, C=1, D=1, E=1, F=1, G=1, H=1, I=1,
196
+ # J=1, K=1, L=1, M=1, N=1, O=1, P=1, Q=1, R=1, S=1, T=1, U=1,
197
+ # V=1, W=3, X=1, Y=1, Z=1)
198
+ _LETTER_SYLLABLES_EN = {
199
+ 'A': 1, 'B': 1, 'C': 1, 'D': 1, 'E': 1, 'F': 1, 'G': 1, 'H': 1,
200
+ 'I': 1, 'J': 1, 'K': 1, 'L': 1, 'M': 1, 'N': 1, 'O': 1, 'P': 1,
201
+ 'Q': 1, 'R': 1, 'S': 1, 'T': 1, 'U': 1, 'V': 1, 'W': 3, 'X': 1,
202
+ 'Y': 1, 'Z': 1,
203
+ }
204
+
205
+
206
+ def _is_year_like(num_str):
207
+ """判断数字是否可能是年份(1000-2099)"""
208
+ # 如果包含逗号,不是年份(是带千分位的数字)
209
+ if ',' in num_str:
210
+ return False
211
+ try:
212
+ n = int(num_str)
213
+ return 1000 <= n <= 2099 and len(num_str) == 4
214
+ except ValueError:
215
+ return False
216
+
217
+
218
+ def _expand_year_en(year_str):
219
+ """英语年份特殊读法:2024 → twenty twenty-four"""
220
+ n = int(year_str)
221
+ if 2000 <= n <= 2009:
222
+ return num2words(n, lang='en')
223
+ if 2010 <= n <= 2099:
224
+ first = n // 100
225
+ second = n % 100
226
+ first_word = num2words(first, lang='en')
227
+ second_word = num2words(second, lang='en')
228
+ return f"{first_word} {second_word}"
229
+ # 1900-1999: nineteen ninety-nine
230
+ if 1000 <= n <= 1999:
231
+ first = n // 100
232
+ second = n % 100
233
+ first_word = num2words(first, lang='en')
234
+ if second == 0:
235
+ return f"{first_word} hundred"
236
+ second_word = num2words(second, lang='en')
237
+ return f"{first_word} {second_word}"
238
+ return num2words(n, lang='en')
239
+
240
+
241
+ def _expand_number(num_str, lang):
242
+ """将数字字符串展开为对应语言的文字"""
243
+ # 处理特殊格式
244
+
245
+ # 处理英文序数后缀
246
+ ordinal_suffix = ''
247
+ if lang == 'en' and len(num_str) > 2:
248
+ last_two = num_str[-2:].lower()
249
+ if last_two in ('st', 'nd', 'rd', 'th'):
250
+ ordinal_suffix = last_two
251
+ num_str = num_str[:-2]
252
+
253
+ # 去除货币符号
254
+ num_str = num_str.lstrip('$¥€£')
255
+
256
+ # 处理千位分隔符和小数点(根据语言)
257
+ if lang in ('es', 'fr', 'de'):
258
+ # 欧洲大陆:逗号是小数点,点是千位分隔符
259
+ # 先去除千位分隔符(点)
260
+ num_str_temp = num_str.replace('.', '')
261
+ # 将逗号替换为点(标准化为英语格式)
262
+ num_str_clean = num_str_temp.replace(',', '.')
263
+ else:
264
+ # 英语/中文/阿拉伯语:点是小数点,逗号是千位分隔符
265
+ # 去除千位分隔符(逗号)
266
+ num_str_clean = num_str.replace(',', '')
267
+
268
+ # 处理小数
269
+ if '.' in num_str_clean:
270
+ parts = num_str_clean.split('.')
271
+ if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
272
+ try:
273
+ n2w_lang = _NUM2WORDS_LANG_MAP.get(lang, 'en')
274
+ # 整数部分
275
+ result = num2words(int(parts[0]), lang=n2w_lang)
276
+ # 小数点的表达(根据语言)
277
+ if lang == 'zh':
278
+ result += '点'
279
+ elif lang == 'es':
280
+ result += ' coma'
281
+ elif lang == 'fr':
282
+ result += ' virgule'
283
+ elif lang == 'de':
284
+ result += ' Komma'
285
+ elif lang == 'ar':
286
+ result += ' فاصلة'
287
+ else:
288
+ result += ' point'
289
+ # 小数部分逐位读
290
+ for digit in parts[1]:
291
+ if lang == 'zh':
292
+ _ZH_DIGITS = '零一二三四五六七八九'
293
+ result += _ZH_DIGITS[int(digit)]
294
+ else:
295
+ result += ' ' + num2words(int(digit), lang=n2w_lang)
296
+ return result
297
+ except Exception:
298
+ pass
299
+
300
+ # 处理日期(三段斜杠数字)
301
+ if '/' in num_str_clean:
302
+ parts = num_str_clean.split('/')
303
+ # 检查是否是日期格式(三段数字)
304
+ if len(parts) == 3 and all(p.isdigit() for p in parts):
305
+ try:
306
+ n2w_lang = _NUM2WORDS_LANG_MAP.get(lang, 'en')
307
+ result_parts = []
308
+ for part in parts:
309
+ result_parts.append(num2words(int(part), lang=n2w_lang))
310
+ return ' '.join(result_parts)
311
+ except Exception:
312
+ pass
313
+
314
+ # 处理分数
315
+ if '/' in num_str_clean:
316
+ parts = num_str_clean.split('/')
317
+ if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
318
+ try:
319
+ n2w_lang = _NUM2WORDS_LANG_MAP.get(lang, 'en')
320
+ numerator_int = int(parts[0])
321
+ denominator_int = int(parts[1])
322
+
323
+ # 特殊处理常见分数
324
+ if lang == 'en':
325
+ if numerator_int == 1 and denominator_int == 2:
326
+ return "one half"
327
+ elif numerator_int == 1 and denominator_int == 4:
328
+ return "one quarter"
329
+ elif numerator_int == 3 and denominator_int == 4:
330
+ return "three quarters"
331
+
332
+ # 通用处理
333
+ numerator = num2words(numerator_int, lang=n2w_lang)
334
+ # 分母用序数
335
+ denominator = num2words(denominator_int, lang=n2w_lang, to='ordinal')
336
+ return f"{numerator} {denominator}"
337
+ except Exception:
338
+ pass
339
+
340
+ # 处理电话号码(连字符分隔的数字)
341
+ if '-' in num_str_clean and all(p.isdigit() for p in num_str_clean.split('-')):
342
+ # 电话号码逐位读
343
+ digits = num_str_clean.replace('-', '')
344
+ try:
345
+ n2w_lang = _NUM2WORDS_LANG_MAP.get(lang, 'en')
346
+ if lang == 'zh':
347
+ _ZH_DIGITS = '零一二三四五六七八九'
348
+ return ''.join(_ZH_DIGITS[int(d)] for d in digits)
349
+ else:
350
+ result = []
351
+ for digit in digits:
352
+ result.append(num2words(int(digit), lang=n2w_lang))
353
+ return ' '.join(result)
354
+ except Exception:
355
+ pass
356
+
357
+ # 处理纯整数
358
+ try:
359
+ n = int(num_str_clean)
360
+ except ValueError:
361
+ return num_str
362
+
363
+ # 检查是否是年份(使用原始字符串,包含逗号信息)
364
+ if lang == 'en' and _is_year_like(num_str):
365
+ return _expand_year_en(num_str_clean)
366
+
367
+ n2w_lang = _NUM2WORDS_LANG_MAP.get(lang, 'en')
368
+
369
+ # 中文:逐位读数字(如电话号码、年份等场景更常见)
370
+ if lang == 'zh':
371
+ _ZH_DIGITS = '零一二三四五六七八九'
372
+ return ''.join(_ZH_DIGITS[int(d)] for d in num_str_clean)
373
+
374
+ try:
375
+ return num2words(n, lang=n2w_lang)
376
+ except Exception:
377
+ return num2words(n, lang='en')
378
+
379
+
380
+ def _expand_decimal(text, lang):
381
+ """处理小数"""
382
+ n2w_lang = _NUM2WORDS_LANG_MAP.get(lang, 'en')
383
+ try:
384
+ n = float(text)
385
+ return num2words(n, lang=n2w_lang)
386
+ except Exception:
387
+ return text
388
+
389
+
390
+ # ========== 缩写识别模块 ==========
391
+
392
+ # 作为完整单词发音的缩写(不逐字母读)及其音节数
393
+ _WORD_ACRONYMS = {
394
+ 'NASA': 2, 'NATO': 2, 'ASAP': 4, 'IKEA': 3, 'OPEC': 2,
395
+ 'FIFA': 2, 'UNESCO': 3, 'UNICEF': 3, 'NAFTA': 2, 'SARS': 1,
396
+ 'AIDS': 1, 'RADAR': 2, 'LASER': 2, 'SCUBA': 2,
397
+ 'PIN': 1, 'SIM': 1, 'RAM': 1, 'ROM': 1,
398
+ 'LAN': 1, 'WAN': 1, 'JPEG': 2, 'GIF': 1,
399
+ 'COVID': 2, 'COV': 1, # COVID-19, SARS-CoV-2
400
+ }
401
+
402
+ # 已知缩写/品牌名的音节数
403
+ _KNOWN_ABBREVIATIONS = {
404
+ # 品牌名
405
+ 'iPhone': 2, 'iPad': 2, 'iPod': 2, 'iMac': 2,
406
+ 'macOS': 3, 'iOS': 3, 'YouTube': 2, 'WiFi': 2,
407
+ 'WhatsApp': 2, 'LinkedIn': 2, 'GitHub': 2, 'GitLab': 2,
408
+ 'JavaScript': 3, 'TypeScript': 2, 'PowerPoint': 3,
409
+ 'eBay': 2, 'PayPal': 2, 'FedEx': 2,
410
+
411
+ # 学位/职称缩写
412
+ 'PhD': 3, 'Ph.D.': 3, 'Ph.D': 3,
413
+ 'Dr': 2, 'Dr.': 2, # Doctor
414
+ 'Mr': 2, 'Mr.': 2, # Mister
415
+ 'Mrs': 2, 'Mrs.': 2, # Missus
416
+ 'Ms': 2, 'Ms.': 2,
417
+ 'Prof': 2, 'Prof.': 2, # Professor
418
+
419
+ # 技术缩写
420
+ 'LaTeX': 2, 'MySQL': 3, 'PostgreSQL': 4,
421
+ }
422
+
423
+
424
+ def _is_spelled_out_acronym(word):
425
+ """判断是否是逐字母拼读的缩写"""
426
+ # 检查是否在作为单词发音的缩写列表中
427
+ if word.upper() in _WORD_ACRONYMS:
428
+ return False
429
+
430
+ clean = word.replace('.', '')
431
+ if len(clean) < 2:
432
+ return False
433
+
434
+ # 全大写缩写:USA, FBI, MIT
435
+ if clean.isupper() and 2 <= len(clean) <= 6:
436
+ return True
437
+
438
+ # 带点的缩写:U.S.A., Ph.D., Dr.
439
+ if '.' in word and all(c.isupper() or c == '.' for c in word):
440
+ return True
441
+
442
+ # Mixed-case 缩写识别
443
+ # 规则:至少2个大写字母,且大写字母占比 >= 50%
444
+ upper_count = sum(1 for c in clean if c.isupper())
445
+ alpha_count = sum(1 for c in clean if c.isalpha())
446
+
447
+ if alpha_count >= 2 and upper_count >= 2:
448
+ # PhD, eBay, iOS, macOS 等
449
+ upper_ratio = upper_count / alpha_count
450
+ if upper_ratio >= 0.5:
451
+ return True
452
+
453
+ return False
454
+
455
+
456
+ def _abbreviation_syllable_count(word, lang='en'):
457
+ """计算缩写/品牌名的音节数"""
458
+ # 规范化:去除尾部标点
459
+ clean = word.rstrip('.,;:!?()[]{}"\'-')
460
+
461
+ # 先检查已知缩写词典(使用规范化后的 token)
462
+ if clean in _KNOWN_ABBREVIATIONS:
463
+ return _KNOWN_ABBREVIATIONS[clean]
464
+
465
+ # 作为单词发音的缩写(使用规范化后的 token)
466
+ upper = clean.upper()
467
+ if upper in _WORD_ACRONYMS:
468
+ return _WORD_ACRONYMS[upper]
469
+
470
+ # 逐字母拼读的缩写(使用规范化后的 token)
471
+ if _is_spelled_out_acronym(clean):
472
+ letters = [c for c in clean if c.isalpha()]
473
+ if lang == 'en':
474
+ return sum(_LETTER_SYLLABLES_EN.get(c.upper(), 1) for c in letters)
475
+ return len(letters)
476
+
477
+ return None
478
+
479
+
480
+ # ========== 阿拉伯语音节计数(从原版保留并改进) ==========
481
+
482
+ _AR_FATHA = 'َ'
483
+ _AR_DAMMA = 'ُ'
484
+ _AR_KASRA = 'ِ'
485
+ _AR_SHORT_VOWELS = {_AR_FATHA, _AR_DAMMA, _AR_KASRA}
486
+
487
+ _AR_FATHATAN = 'ً'
488
+ _AR_DAMMATAN = 'ٌ'
489
+ _AR_KASRATAN = 'ٍ'
490
+ _AR_TANWEEN = {_AR_FATHATAN, _AR_DAMMATAN, _AR_KASRATAN}
491
+
492
+ _AR_SUKUN = 'ْ'
493
+ _AR_SHADDA = 'ّ'
494
+ _AR_SUPERSCRIPT_ALEF = 'ٰ'
495
+
496
+ _AR_DIACRITICS_RE = re.compile(r'[ً-ٰٟٓ]')
497
+
498
+ _AR_ALEF = 'ا'
499
+ _AR_WAW = 'و'
500
+ _AR_YAA = 'ي'
501
+ _AR_ALEF_MAQSURA = 'ى'
502
+
503
+ _AR_ALEF_MADDA = 'آ'
504
+ _AR_TAA_MARBUTA = 'ة'
505
+ _AR_TATWEEL = 'ـ'
506
+
507
+ _AR_LETTER_RE = re.compile(
508
+ r'[ء-غف-ي'
509
+ r'ً-ٰٟ'
510
+ r'ٱ-ۓە-ۿ'
511
+ r'ݐ-ݿࢠ-ࣿ'
512
+ r'ﭐ-﷿ﹰ-]+'
513
+ )
514
+
515
+
516
+ def _ar_is_letter(ch):
517
+ cp = ord(ch)
518
+ return ((0x0621 <= cp <= 0x063A)
519
+ or (0x0641 <= cp <= 0x064A)
520
+ or (0x0671 <= cp <= 0x06D3)
521
+ or (0x06D5 <= cp <= 0x06FF))
522
+
523
+
524
+ def _ar_is_fully_vocalized(word):
525
+ consonant_count = 0
526
+ vocalized_count = 0
527
+ chars = list(word)
528
+ n = len(chars)
529
+
530
+ for i, ch in enumerate(chars):
531
+ if (_ar_is_letter(ch)
532
+ and ch not in (_AR_ALEF, _AR_WAW, _AR_YAA, _AR_ALEF_MAQSURA,
533
+ _AR_ALEF_MADDA, _AR_TAA_MARBUTA)):
534
+ consonant_count += 1
535
+ if i + 1 < n and _AR_DIACRITICS_RE.match(chars[i + 1]):
536
+ vocalized_count += 1
537
+
538
+ if consonant_count == 0:
539
+ return False
540
+ return vocalized_count / consonant_count > 0.5
541
+
542
+
543
+ def _ar_vocalized_syllables(word):
544
+ syllables = 0
545
+ covered = False
546
+
547
+ for i, ch in enumerate(word):
548
+ if ch in _AR_SHORT_VOWELS:
549
+ syllables += 1
550
+ covered = True
551
+ elif ch in _AR_TANWEEN:
552
+ syllables += 1
553
+ covered = True
554
+ elif ch == _AR_SUPERSCRIPT_ALEF:
555
+ if not covered:
556
+ syllables += 1
557
+ covered = False
558
+ elif ch == _AR_ALEF_MADDA:
559
+ syllables += 1
560
+ covered = False
561
+ elif ch in (_AR_ALEF, _AR_ALEF_MAQSURA):
562
+ if i > 0 and not covered:
563
+ syllables += 1
564
+ covered = False
565
+ elif _ar_is_letter(ch):
566
+ covered = False
567
+
568
+ return max(1, syllables)
569
+
570
+
571
+ def _ar_unvocalized_syllables(word):
572
+ clean = _AR_DIACRITICS_RE.sub('', word)
573
+ clean = clean.replace(_AR_TATWEEL, '')
574
+ if not clean:
575
+ return 0
576
+
577
+ letters = list(clean)
578
+ n = len(letters)
579
+
580
+ if n == 0:
581
+ return 0
582
+ if n <= 2:
583
+ return 1
584
+
585
+ skeleton = []
586
+ for i, ch in enumerate(letters):
587
+ is_first = (i == 0)
588
+
589
+ if ch == _AR_ALEF_MAQSURA:
590
+ skeleton.append('V')
591
+ elif ch == _AR_ALEF_MADDA:
592
+ skeleton.append('V')
593
+ elif ch == _AR_ALEF:
594
+ skeleton.append('C' if is_first else 'V')
595
+ elif ch == _AR_TAA_MARBUTA:
596
+ skeleton.append('V')
597
+ elif ch in (_AR_WAW, _AR_YAA):
598
+ if (ch == _AR_YAA
599
+ and i == n - 2
600
+ and i + 1 < n
601
+ and letters[i + 1] == _AR_TAA_MARBUTA):
602
+ skeleton.append('C')
603
+ elif (ch == _AR_WAW
604
+ and i == n - 2
605
+ and i + 1 < n
606
+ and letters[i + 1] == _AR_TAA_MARBUTA):
607
+ skeleton.append('C')
608
+ elif is_first:
609
+ skeleton.append('C')
610
+ elif skeleton and skeleton[-1] == 'C':
611
+ skeleton.append('V')
612
+ else:
613
+ skeleton.append('C')
614
+ else:
615
+ skeleton.append('C')
616
+
617
+ v_positions = [i for i, x in enumerate(skeleton) if x == 'V']
618
+
619
+ if not v_positions:
620
+ return max(1, (len(skeleton) + 1) // 2)
621
+
622
+ syllables = len(v_positions)
623
+ syllables += v_positions[0] // 2
624
+
625
+ for k in range(1, len(v_positions)):
626
+ gap = v_positions[k] - v_positions[k - 1] - 1
627
+ syllables += gap // 2
628
+
629
+ post_c = len(skeleton) - v_positions[-1] - 1
630
+ if (post_c == 1
631
+ and len(v_positions) == 1
632
+ and v_positions[0] == 1
633
+ and len(skeleton) == 3):
634
+ syllables += 1
635
+ else:
636
+ syllables += post_c // 2
637
+
638
+ return max(1, syllables)
639
+
640
+
641
+ def _arabic_word_syllables(word):
642
+ if not word:
643
+ return 0
644
+ if _AR_DIACRITICS_RE.search(word):
645
+ if _ar_is_fully_vocalized(word):
646
+ return _ar_vocalized_syllables(word)
647
+ return _ar_unvocalized_syllables(word)
648
+
649
+
650
+ # ========== 日语音节计数(从原版保留并改进) ==========
651
+
652
+ _DIGIT_TO_KANA = {
653
+ '0': 'ゼロ', '1': 'いち', '2': 'に', '3': 'さん', '4': 'よん',
654
+ '5': 'ご', '6': 'ろく', '7': 'なな', '8': 'はち', '9': 'きゅう'
655
+ }
656
+
657
+ # One Tagger per thread. MeCab keeps parse state on the Tagger, so sharing a
658
+ # single instance across the evaluator's thread pool corrupts Japanese mora
659
+ # counts nondeterministically -- only syllable_order reads them, so the symptom
660
+ # was zh->ja instances flipping between runs at the default concurrency.
661
+ _thread_state = threading.local()
662
+
663
+
664
+ def _get_tagger():
665
+ tagger = getattr(_thread_state, "tagger", None)
666
+ if tagger is None:
667
+ tagger = fugashi.Tagger()
668
+ _thread_state.tagger = tagger
669
+ return tagger
670
+
671
+
672
+ def _count_japanese_mora(token):
673
+ has_kana = any('぀' <= c <= 'ゟ' or '゠' <= c <= 'ヿ' for c in token)
674
+ if not has_kana:
675
+ return len(token)
676
+
677
+ mora_count = 0
678
+ i = 0
679
+ length = len(token)
680
+
681
+ while i < length:
682
+ char = token[i]
683
+ if i + 1 < length and token[i + 1] in 'ゃゅょャュョ':
684
+ mora_count += 1
685
+ i += 2
686
+ elif char in 'っッんンー':
687
+ mora_count += 1
688
+ i += 1
689
+ elif '぀' <= char <= 'ゟ' or '゠' <= char <= 'ヿ':
690
+ mora_count += 1
691
+ i += 1
692
+ else:
693
+ i += 1
694
+
695
+ return mora_count
696
+
697
+
698
+ def _japanese_syllable_count(text):
699
+ total_mora = 0
700
+ parsed_nodes = _get_tagger()(text)
701
+ for word in parsed_nodes:
702
+ reading = getattr(word.feature, 'kana', None)
703
+ if reading is None:
704
+ reading = getattr(word.feature, 'pronBase', None)
705
+ if reading is None:
706
+ reading = word.surface
707
+
708
+ word_mora = _count_japanese_mora(reading)
709
+ total_mora += word_mora
710
+
711
+ return total_mora
712
+
713
+
714
+ # ========== 各语言计算器 ==========
715
+
716
+
717
+ # 西语常见词音节词典(pyphen 不准确的词)
718
+ _SPANISH_SYLLABLES = {
719
+ 'país': 2, # pa-ís
720
+ 'río': 2, # rí-o
721
+ 'pingüino': 3, # pin-güi-no
722
+ 'día': 2, # dí-a
723
+ 'María': 3, # Ma-rí-a
724
+ 'había': 3, # ha-bí-a
725
+ 'tenía': 3, # te-ní-a
726
+ 'podía': 3, # po-dí-a
727
+ 'decía': 3, # de-cí-a
728
+ 'hacía': 3, # ha-cí-a
729
+ 'raíz': 2, # ra-íz
730
+ 'maíz': 2, # ma-íz
731
+ 'baúl': 2, # ba-úl
732
+ 'Raúl': 2, # Ra-úl
733
+ }
734
+
735
+ _PYPHEN_LANG_MAP = {
736
+ 'en': 'en_US',
737
+ 'de': 'de_DE',
738
+ 'fr': 'fr_FR',
739
+ 'es': 'es_ES',
740
+ }
741
+
742
+
743
+ def _count_european(text, lang):
744
+ """英、德、法、西等欧洲语言的音节计数"""
745
+ pyphen_lang = _PYPHEN_LANG_MAP.get(lang, 'en_US')
746
+
747
+ segments = _parse_mixed_content(text)
748
+ total = 0
749
+
750
+ for segment, script_type in segments:
751
+ if script_type == 'number':
752
+ expanded = _expand_number(segment, lang)
753
+ # 按空格和连字符分割
754
+ words = re.split(r'[\s\-]+', expanded)
755
+ for w in words:
756
+ clean_w = w.strip(',-')
757
+ if clean_w and clean_w.isalpha():
758
+ total += _pyphen_syllable_count(clean_w, pyphen_lang)
759
+ elif script_type == 'latin':
760
+ words = segment.split()
761
+ for w in words:
762
+ abbr_count = _abbreviation_syllable_count(w, lang)
763
+ if abbr_count is not None:
764
+ total += abbr_count
765
+ else:
766
+ total += _pyphen_syllable_count(w, pyphen_lang)
767
+ elif script_type == 'han':
768
+ # 只计算汉字,不包括标点
769
+ han_chars = re.findall(r'[一-鿿]', segment)
770
+ total += len(han_chars)
771
+ elif script_type == 'arabic':
772
+ # 混合内容中的阿拉伯语
773
+ ar_words = _AR_LETTER_RE.findall(segment)
774
+ for w in ar_words:
775
+ total += _arabic_word_syllables(w)
776
+ elif script_type == 'kana':
777
+ # 混合内容中的日语假名
778
+ total += _japanese_syllable_count(segment)
779
+
780
+ return total
781
+
782
+
783
+
784
+
785
+ def _expand_and_count_chinese(num_str):
786
+ """展开数字并计算中文音节数"""
787
+ # 处理小数
788
+ if '.' in num_str:
789
+ parts = num_str.split('.')
790
+ if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
791
+ count = 0
792
+ # 整数部分逐位读
793
+ for digit in parts[0]:
794
+ count += 1
795
+ # 小数点:"点"
796
+ count += 1
797
+ # 小数部分逐位读
798
+ for digit in parts[1]:
799
+ count += 1
800
+ return count
801
+
802
+ # 其他数字格式:逐位读
803
+ digits = re.findall(r'\d', num_str)
804
+ return len(digits)
805
+
806
+
807
+ def _count_chinese(text, lang='zh'):
808
+ """中文音节计数(改进版:处理数字和混合内容)"""
809
+ segments = _parse_mixed_content(text)
810
+ total = 0
811
+
812
+ for segment, script_type in segments:
813
+ if script_type == 'han':
814
+ # 只计算汉字,不包括标点
815
+ han_chars = re.findall(r'[一-鿿]', segment)
816
+ total += len(han_chars)
817
+ elif script_type == 'number':
818
+ # 统一使用 _expand_and_count_chinese 处理
819
+ total += _expand_and_count_chinese(segment)
820
+ elif script_type == 'latin':
821
+ words = segment.split()
822
+ for w in words:
823
+ abbr_count = _abbreviation_syllable_count(w, 'en')
824
+ if abbr_count is not None:
825
+ total += abbr_count
826
+ else:
827
+ total += _pyphen_syllable_count(w, 'en_US')
828
+ elif script_type == 'kana':
829
+ # 混合内容中的日语假名
830
+ total += _japanese_syllable_count(segment)
831
+ elif script_type == 'arabic':
832
+ # 混合内容中的阿拉伯语
833
+ ar_words = _AR_LETTER_RE.findall(segment)
834
+ for w in ar_words:
835
+ total += _arabic_word_syllables(w)
836
+
837
+ return total
838
+
839
+
840
+ def _count_arabic(text, lang='ar'):
841
+ """阿拉伯语音节计数(改进版:处理混合内容)"""
842
+ segments = _parse_mixed_content(text)
843
+ total = 0
844
+
845
+ for segment, script_type in segments:
846
+ if script_type == 'arabic':
847
+ words = _AR_LETTER_RE.findall(segment)
848
+ for w in words:
849
+ total += _arabic_word_syllables(w)
850
+ elif script_type == 'number':
851
+ expanded = _expand_number(segment, 'ar')
852
+ ar_words = _AR_LETTER_RE.findall(expanded)
853
+ if ar_words:
854
+ for w in ar_words:
855
+ total += _arabic_word_syllables(w)
856
+ else:
857
+ # num2words 可能返回拉丁字母,用英语计算
858
+ for w in expanded.split():
859
+ if w.isalpha():
860
+ total += _pyphen_syllable_count(w, 'en_US')
861
+ elif script_type == 'latin':
862
+ words = segment.split()
863
+ for w in words:
864
+ abbr_count = _abbreviation_syllable_count(w, 'en')
865
+ if abbr_count is not None:
866
+ total += abbr_count
867
+ else:
868
+ total += _pyphen_syllable_count(w, 'en_US')
869
+ elif script_type == 'han':
870
+ # 混合内容中的汉字
871
+ han_chars = re.findall(r'[一-鿿]', segment)
872
+ total += len(han_chars)
873
+ elif script_type == 'kana':
874
+ # 混合内容中的日语假名
875
+ total += _japanese_syllable_count(segment)
876
+
877
+ return total
878
+
879
+
880
+ def _count_japanese_v2(text, lang='ja'):
881
+ """日语音节计数(改进版:处理混合内容)"""
882
+ segments = _parse_mixed_content(text)
883
+
884
+ # 合并连续的 han 和 kana 段落,让 fugashi 整体处理
885
+ merged_segments = []
886
+ i = 0
887
+ while i < len(segments):
888
+ segment, script_type = segments[i]
889
+
890
+ if script_type in ('han', 'kana'):
891
+ # 收集连续的 han/kana 段落
892
+ japanese_text = segment
893
+ j = i + 1
894
+ while j < len(segments) and segments[j][1] in ('han', 'kana'):
895
+ japanese_text += segments[j][0]
896
+ j += 1
897
+ merged_segments.append((japanese_text, 'japanese'))
898
+ i = j
899
+ else:
900
+ merged_segments.append((segment, script_type))
901
+ i += 1
902
+
903
+ # 计算音节
904
+ total = 0
905
+ for segment, script_type in merged_segments:
906
+ if script_type == 'japanese':
907
+ total += _japanese_syllable_count(segment)
908
+ elif script_type == 'number':
909
+ # 日语中数字通过 fugashi 处理更准确
910
+ total += _japanese_syllable_count(segment)
911
+ elif script_type == 'latin':
912
+ words = segment.split()
913
+ for w in words:
914
+ abbr_count = _abbreviation_syllable_count(w, 'en')
915
+ if abbr_count is not None:
916
+ total += abbr_count
917
+ else:
918
+ total += _pyphen_syllable_count(w, 'en_US')
919
+
920
+ return total
921
+
922
+
923
+ # ========== 公共 API ==========
924
+
925
+ def cal_syllable_count(text, lang='en'):
926
+ if not text or not text.strip():
927
+ return 0
928
+
929
+ text = text.strip()
930
+
931
+ if lang.lower() == 'zh':
932
+ return _count_chinese(text)
933
+ elif lang.lower() == 'ja':
934
+ return _count_japanese_v2(text)
935
+ elif lang.lower() == 'ar':
936
+ return _count_arabic(text)
937
+ else:
938
+ return _count_european(text, lang.lower())
939
+
940
+
941
+ def cal_syllable_details(text, lang='en'):
942
+ """返回详细的音节分解信息"""
943
+ if not text or not text.strip():
944
+ return {
945
+ 'total_syllables': 0,
946
+ 'word_count': 0,
947
+ 'syllables_per_word': 0,
948
+ 'syllable_breakdown': []
949
+ }
950
+
951
+ text = text.strip()
952
+ total_syllables = cal_syllable_count(text, lang)
953
+
954
+ # 根据语言使用不同的分解策略
955
+ breakdown = []
956
+
957
+ if lang.lower() == 'zh':
958
+ # 中文:按混合内容分段
959
+ segments = _parse_mixed_content(text)
960
+ for segment, script_type in segments:
961
+ if script_type == 'han':
962
+ # 汉字逐个计数(只计算汉字,不包括标点)
963
+ han_chars = re.findall(r'[一-鿿]', segment)
964
+ for char in han_chars:
965
+ breakdown.append({'word': char, 'syllables': 1})
966
+ elif script_type == 'number':
967
+ # 使用统一的计数逻辑
968
+ syllables = _expand_and_count_chinese(segment)
969
+ breakdown.append({
970
+ 'word': segment,
971
+ 'syllables': syllables,
972
+ })
973
+ elif script_type == 'latin':
974
+ words = segment.split()
975
+ for w in words:
976
+ abbr_count = _abbreviation_syllable_count(w, 'en')
977
+ if abbr_count is not None:
978
+ syllables = abbr_count
979
+ else:
980
+ syllables = _pyphen_syllable_count(w, 'en_US')
981
+ breakdown.append({'word': w, 'syllables': syllables})
982
+ elif script_type == 'kana':
983
+ # 混合内容中的日语假名
984
+ syllables = _japanese_syllable_count(segment)
985
+ breakdown.append({'word': segment, 'syllables': syllables})
986
+ elif script_type == 'arabic':
987
+ # 混合内容中的阿拉伯语
988
+ ar_words = _AR_LETTER_RE.findall(segment)
989
+ for w in ar_words:
990
+ syllables = _arabic_word_syllables(w)
991
+ breakdown.append({'word': w, 'syllables': syllables})
992
+
993
+ elif lang.lower() == 'ja':
994
+ # 日语:使用 fugashi 分词
995
+ segments = _parse_mixed_content(text)
996
+
997
+ # 合并连续的 han 和 kana 段落
998
+ merged_segments = []
999
+ i = 0
1000
+ while i < len(segments):
1001
+ segment, script_type = segments[i]
1002
+ if script_type in ('han', 'kana'):
1003
+ japanese_text = segment
1004
+ j = i + 1
1005
+ while j < len(segments) and segments[j][1] in ('han', 'kana'):
1006
+ japanese_text += segments[j][0]
1007
+ j += 1
1008
+ merged_segments.append((japanese_text, 'japanese'))
1009
+ i = j
1010
+ else:
1011
+ merged_segments.append((segment, script_type))
1012
+ i += 1
1013
+
1014
+ # 对每个段落计算音节
1015
+ for segment, script_type in merged_segments:
1016
+ if script_type == 'japanese':
1017
+ syllables = _japanese_syllable_count(segment)
1018
+ breakdown.append({'word': segment, 'syllables': syllables})
1019
+ elif script_type == 'number':
1020
+ syllables = _japanese_syllable_count(segment)
1021
+ breakdown.append({'word': segment, 'syllables': syllables})
1022
+ elif script_type == 'latin':
1023
+ words = segment.split()
1024
+ for w in words:
1025
+ abbr_count = _abbreviation_syllable_count(w, 'en')
1026
+ if abbr_count is not None:
1027
+ syllables = abbr_count
1028
+ else:
1029
+ syllables = _pyphen_syllable_count(w, 'en_US')
1030
+ breakdown.append({'word': w, 'syllables': syllables})
1031
+ elif script_type == 'han':
1032
+ # 混合内容中的汉字
1033
+ han_chars = re.findall(r'[一-鿿]', segment)
1034
+ for char in han_chars:
1035
+ breakdown.append({'word': char, 'syllables': 1})
1036
+ elif script_type == 'kana':
1037
+ # 混合内容中的日语假名
1038
+ syllables = _japanese_syllable_count(segment)
1039
+ breakdown.append({'word': segment, 'syllables': syllables})
1040
+
1041
+ elif lang.lower() == 'ar':
1042
+ # 阿拉伯语
1043
+ segments = _parse_mixed_content(text)
1044
+ for segment, script_type in segments:
1045
+ if script_type == 'arabic':
1046
+ words = _AR_LETTER_RE.findall(segment)
1047
+ for w in words:
1048
+ syllables = _arabic_word_syllables(w)
1049
+ breakdown.append({'word': w, 'syllables': syllables})
1050
+ elif script_type == 'number':
1051
+ expanded = _expand_number(segment, 'ar')
1052
+ ar_words = _AR_LETTER_RE.findall(expanded)
1053
+ if ar_words:
1054
+ syllables = sum(_arabic_word_syllables(w) for w in ar_words)
1055
+ else:
1056
+ # 英语展开
1057
+ syllables = sum(_pyphen_syllable_count(w, 'en_US') for w in expanded.split() if w.isalpha())
1058
+ breakdown.append({
1059
+ 'word': segment,
1060
+ 'expanded': expanded,
1061
+ 'syllables': syllables,
1062
+ })
1063
+ elif script_type == 'latin':
1064
+ words = segment.split()
1065
+ for w in words:
1066
+ abbr_count = _abbreviation_syllable_count(w, 'en')
1067
+ if abbr_count is not None:
1068
+ syllables = abbr_count
1069
+ else:
1070
+ syllables = _pyphen_syllable_count(w, 'en_US')
1071
+ breakdown.append({'word': w, 'syllables': syllables})
1072
+ elif script_type == 'han':
1073
+ # 混合内容中的汉字
1074
+ han_chars = re.findall(r'[一-鿿]', segment)
1075
+ for char in han_chars:
1076
+ breakdown.append({'word': char, 'syllables': 1})
1077
+ elif script_type == 'kana':
1078
+ # 混合内容中的日语假名
1079
+ syllables = _japanese_syllable_count(segment)
1080
+ breakdown.append({'word': segment, 'syllables': syllables})
1081
+
1082
+ else:
1083
+ # 欧洲语言(英、德、法、西等)
1084
+ pyphen_lang = _PYPHEN_LANG_MAP.get(lang.lower(), 'en_US')
1085
+ segments = _parse_mixed_content(text)
1086
+
1087
+ for segment, script_type in segments:
1088
+ if script_type == 'number':
1089
+ expanded = _expand_number(segment, lang)
1090
+ words = re.split(r'[\s\-]+', expanded)
1091
+ syllables = 0
1092
+ for w in words:
1093
+ clean_w = w.strip(',-')
1094
+ if clean_w and clean_w.isalpha():
1095
+ syllables += _pyphen_syllable_count(clean_w, pyphen_lang)
1096
+ breakdown.append({
1097
+ 'word': segment,
1098
+ 'expanded': expanded,
1099
+ 'syllables': syllables,
1100
+ })
1101
+ elif script_type == 'latin':
1102
+ words = segment.split()
1103
+ for w in words:
1104
+ abbr_count = _abbreviation_syllable_count(w, lang)
1105
+ if abbr_count is not None:
1106
+ syllables = abbr_count
1107
+ else:
1108
+ syllables = _pyphen_syllable_count(w, pyphen_lang)
1109
+ breakdown.append({'word': w, 'syllables': syllables})
1110
+ elif script_type == 'han':
1111
+ # 混合内容中的汉字
1112
+ han_chars = re.findall(r'[一-鿿]', segment)
1113
+ for char in han_chars:
1114
+ breakdown.append({'word': char, 'syllables': 1})
1115
+ elif script_type == 'arabic':
1116
+ # 混合内容中的阿拉伯语
1117
+ ar_words = _AR_LETTER_RE.findall(segment)
1118
+ for w in ar_words:
1119
+ syllables = _arabic_word_syllables(w)
1120
+ breakdown.append({'word': w, 'syllables': syllables})
1121
+ elif script_type == 'kana':
1122
+ # 混合内容中的日语假名
1123
+ syllables = _japanese_syllable_count(segment)
1124
+ breakdown.append({'word': segment, 'syllables': syllables})
1125
+
1126
+ word_count = len(breakdown)
1127
+ avg_syllables = round(total_syllables / word_count, 2) if word_count > 0 else 0
1128
+
1129
+ return {
1130
+ 'total_syllables': total_syllables,
1131
+ 'word_count': word_count,
1132
+ 'syllables_per_word': avg_syllables,
1133
+ 'syllable_breakdown': breakdown,
1134
+ }
1135
+
1136
+
1137
+ # ========== 测试入口 ==========
1138
+
1139
+ if __name__ == "__main__":
1140
+ # 基础测试用例(和原版一致)
1141
+ test_cases = [
1142
+ ("你好世界 Hello World", "zh"),
1143
+ ("Hello World", "en"),
1144
+ ("The quick brown fox jumps over the lazy dog", "en"),
1145
+ ("Der schnelle braune Fuchs springt über den faulen Hund", "de"),
1146
+ ("Le renard brun rapide saute par-dessus le chien paresseux", "fr"),
1147
+ ("مرحبا بك في العالم", "ar"),
1148
+ ]
1149
+
1150
+ # 数字展开测试
1151
+ number_test_cases = [
1152
+ ("2024", "en"),
1153
+ ("100", "en"),
1154
+ ("I have 3 cats", "en"),
1155
+ ("2024年", "zh"),
1156
+ ("我有100个苹果", "zh"),
1157
+ ("123 مرحبا", "ar"),
1158
+ ]
1159
+
1160
+ # 缩写测试
1161
+ abbreviation_test_cases = [
1162
+ ("USA", "en"),
1163
+ ("BMW", "en"),
1164
+ ("NASA", "en"),
1165
+ ("iPhone", "en"),
1166
+ ("The CEO of IBM", "en"),
1167
+ ]
1168
+
1169
+ # 混合内容测试
1170
+ mixed_test_cases = [
1171
+ ("Hello世界2024年", "zh"),
1172
+ ("iPhone 15 Pro Max", "en"),
1173
+ ("مرحبا Hello 2024", "ar"),
1174
+ ]
1175
+
1176
+ # 日语测试
1177
+ japanese_test_cases = [
1178
+ ("こんにちは", "ja"),
1179
+ ("きょう", "ja"),
1180
+ ("きっと", "ja"),
1181
+ ("お母さん", "ja"),
1182
+ ("コーヒー", "ja"),
1183
+ ("東京", "ja"),
1184
+ ("123", "ja"),
1185
+ ("Hello世界", "ja"),
1186
+ ]
1187
+
1188
+ print("=" * 70)
1189
+ print("音节计数 V2 测试结果")
1190
+ print("=" * 70)
1191
+
1192
+ for text, lang in test_cases:
1193
+ count = cal_syllable_count(text, lang)
1194
+ print(f"[{lang}] '{text}' → {count} 音节")
1195
+
1196
+ print("\n" + "=" * 70)
1197
+ print("数字展开测试")
1198
+ print("=" * 70)
1199
+
1200
+ for text, lang in number_test_cases:
1201
+ count = cal_syllable_count(text, lang)
1202
+ print(f"[{lang}] '{text}' → {count} 音节")
1203
+
1204
+ print("\n" + "=" * 70)
1205
+ print("缩写识别测试")
1206
+ print("=" * 70)
1207
+
1208
+ for text, lang in abbreviation_test_cases:
1209
+ count = cal_syllable_count(text, lang)
1210
+ print(f"[{lang}] '{text}' → {count} 音节")
1211
+
1212
+ print("\n" + "=" * 70)
1213
+ print("混合内容测试")
1214
+ print("=" * 70)
1215
+
1216
+ for text, lang in mixed_test_cases:
1217
+ count = cal_syllable_count(text, lang)
1218
+ details = cal_syllable_details(text, lang)
1219
+ print(f"[{lang}] '{text}' → {count} 音节")
1220
+ for item in details['syllable_breakdown']:
1221
+ extra = f" (展开: {item['expanded']})" if 'expanded' in item else ""
1222
+ print(f" '{item['word']}': {item['syllables']} 音节{extra}")
1223
+
1224
+ print("\n" + "=" * 70)
1225
+ print("日语测试")
1226
+ print("=" * 70)
1227
+
1228
+ for text, lang in japanese_test_cases:
1229
+ count = cal_syllable_count(text, lang)
1230
+ print(f"[{lang}] '{text}' → {count} 音拍")
1231
+
1232
+ print("\n" + "=" * 70)
evaluate.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Score predictions for Instruction-Following Translation Bench.
3
+
4
+ Reads a JSONL of {"case_id", "prediction"} rows, checks the five hard constraints
5
+ with rules, scores the five soft constraints and translation quality with an LLM
6
+ Judge, and writes per-instance scores plus aggregate metrics.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import sys
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from eval.constraints import (
20
+ SOFT_CONSTRAINT_IDS,
21
+ check_hard_constraints,
22
+ collect_soft_constraint_descs,
23
+ )
24
+ from eval.judge_client import JudgeClient, JudgeRequestError
25
+ from eval.metrics import (
26
+ compute_if_score,
27
+ compute_summary,
28
+ parse_quality_score,
29
+ parse_soft_constraint_scores,
30
+ )
31
+ from eval.prompts import (
32
+ QUALITY_JUDGE_PROMPT_VERSION,
33
+ build_quality_prompt,
34
+ build_soft_constraint_prompt,
35
+ )
36
+
37
+ DEFAULT_DATA_FILE = Path(__file__).resolve().parent / "data/test.jsonl"
38
+ DEFAULT_JUDGE_MODEL = "gpt-5.6-sol"
39
+ DEFAULT_BASE_URL = "https://api.openai.com/v1"
40
+
41
+
42
+ def read_jsonl(path: Path) -> list[dict[str, Any]]:
43
+ rows = []
44
+ # split("\n"), not splitlines(): source text contains raw U+2028, which is
45
+ # legal inside a JSON string but is a line break to splitlines().
46
+ for line_number, line in enumerate(path.read_text(encoding="utf-8").split("\n"), 1):
47
+ if not line.strip():
48
+ continue
49
+ try:
50
+ rows.append(json.loads(line))
51
+ except json.JSONDecodeError as exc:
52
+ raise SystemExit(f"{path}:{line_number}: invalid JSON: {exc}") from exc
53
+ return rows
54
+
55
+
56
+ def load_predictions(path: Path, valid_ids: set[str]) -> dict[str, str]:
57
+ predictions: dict[str, str] = {}
58
+ for row in read_jsonl(path):
59
+ case_id = row.get("case_id")
60
+ if case_id is None:
61
+ raise SystemExit(f"{path}: a prediction row is missing 'case_id'")
62
+ if case_id in predictions:
63
+ raise SystemExit(f"{path}: duplicate prediction for {case_id}")
64
+ if case_id not in valid_ids:
65
+ raise SystemExit(f"{path}: unknown case_id {case_id}")
66
+ prediction = row.get("prediction")
67
+ predictions[case_id] = prediction if isinstance(prediction, str) else ""
68
+ return predictions
69
+
70
+
71
+ def score_row(
72
+ row: dict[str, Any], prediction: str, judge: JudgeClient | None
73
+ ) -> dict[str, Any]:
74
+ """Score one instance. Missing predictions score 0 without calling the Judge."""
75
+ present = bool(prediction.strip())
76
+
77
+ hard_results = check_hard_constraints(row, prediction) if present else {}
78
+
79
+ soft_results: dict[str, Any] = {}
80
+ soft_cids = [cid for cid in row["constraint_ids"] if cid in SOFT_CONSTRAINT_IDS]
81
+ if present and soft_cids and judge is not None:
82
+ soft_descs = collect_soft_constraint_descs(row["constraint_ids"], row["constraints"])
83
+ if soft_descs:
84
+ response, _ = judge.complete(
85
+ build_soft_constraint_prompt(row, prediction, soft_descs))
86
+ soft_results = parse_soft_constraint_scores(response, list(soft_descs))
87
+ if any(value["score"] is None for value in soft_results.values()):
88
+ raise ValueError("Judge returned incomplete or invalid soft-constraint scores")
89
+ elif present and soft_cids:
90
+ soft_results = {cid: {"score": None} for cid in soft_cids}
91
+
92
+ quality_score = None
93
+ if present and judge is not None:
94
+ response, _ = judge.complete(build_quality_prompt(row, prediction))
95
+ quality_score = parse_quality_score(response)
96
+ if quality_score is None:
97
+ raise ValueError("Judge quality response must be exactly 0, 0.5 or 1")
98
+
99
+ if_score = compute_if_score(hard_results, soft_results) if present else 0.0
100
+
101
+ return {
102
+ "case_id": row["case_id"],
103
+ "source_lang": row["source_lang"],
104
+ "target_lang": row["target_lang"],
105
+ "scenario": row["scenario"],
106
+ "domain": row["domain"],
107
+ "constraint_ids": row["constraint_ids"],
108
+ "prediction_status": "present" if present else "missing",
109
+ "if_score": if_score,
110
+ "quality_score": quality_score,
111
+ "hard_constraint_results": hard_results,
112
+ "soft_constraint_results": soft_results,
113
+ }
114
+
115
+
116
+ def main() -> None:
117
+ parser = argparse.ArgumentParser(description=__doc__)
118
+ parser.add_argument("--predictions", type=Path, required=True)
119
+ parser.add_argument("--output-dir", type=Path, required=True)
120
+ parser.add_argument("--data-file", type=Path, default=DEFAULT_DATA_FILE)
121
+ parser.add_argument("--judge-model", default=DEFAULT_JUDGE_MODEL)
122
+ parser.add_argument("--concurrency", type=int, default=8)
123
+ parser.add_argument("--limit", type=int, default=0,
124
+ help="score only the first N instances (smoke check, not a formal result)")
125
+ parser.add_argument("--skip-judge", action="store_true",
126
+ help="rule-only mode: hard constraints only, no Judge calls")
127
+ args = parser.parse_args()
128
+
129
+ rows = read_jsonl(args.data_file)
130
+ if args.limit:
131
+ rows = rows[: args.limit]
132
+
133
+ predictions = load_predictions(args.predictions, {row["case_id"] for row in rows})
134
+ missing = [row["case_id"] for row in rows if row["case_id"] not in predictions]
135
+ if missing and not args.limit:
136
+ print(f"warning: {len(missing)} instances have no prediction and will score 0",
137
+ file=sys.stderr)
138
+
139
+ judge = None
140
+ if not args.skip_judge:
141
+ judge = JudgeClient(
142
+ api_key=os.environ.get("JUDGE_API_KEY", ""),
143
+ base_url=os.environ.get("JUDGE_API_BASE", DEFAULT_BASE_URL),
144
+ model=args.judge_model,
145
+ prompt_version=QUALITY_JUDGE_PROMPT_VERSION,
146
+ cache_path=args.output_dir / "judge_cache.jsonl",
147
+ )
148
+
149
+ def work(row: dict[str, Any]) -> dict[str, Any]:
150
+ return score_row(row, predictions.get(row["case_id"], ""), judge)
151
+
152
+ try:
153
+ with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
154
+ scored = list(pool.map(work, rows))
155
+ except JudgeRequestError as exc:
156
+ # Aborting beats silently turning provider failures into quality scores.
157
+ raise SystemExit(f"judge failure, aborting: {exc}") from exc
158
+
159
+ summary = compute_summary(scored)
160
+ summary["config"] = {
161
+ "judge_model": None if args.skip_judge else args.judge_model,
162
+ "quality_judge_prompt_version": QUALITY_JUDGE_PROMPT_VERSION,
163
+ "data_file": str(args.data_file),
164
+ "instances_scored": len(scored),
165
+ "formal_run": not args.limit and not args.skip_judge,
166
+ }
167
+
168
+ args.output_dir.mkdir(parents=True, exist_ok=True)
169
+ with (args.output_dir / "scores.jsonl").open("w", encoding="utf-8") as handle:
170
+ for row in scored:
171
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
172
+ (args.output_dir / "summary.json").write_text(
173
+ json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
174
+
175
+ print(f"instances: {summary['total']}")
176
+ print(f"coverage: {summary['prediction_coverage']}/{summary['total']}")
177
+ print(f"IF_Score: {summary['if_score']:.4f}")
178
+ if summary["translation_quality"] is not None:
179
+ print(f"quality: {summary['translation_quality']:.4f}")
180
+ if not summary["config"]["formal_run"]:
181
+ print("note: subset or rule-only run, not a full-benchmark result")
182
+
183
+
184
+ if __name__ == "__main__":
185
+ main()
manifest.json ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": 1,
3
+ "name": "Instruction-Following Translation Bench",
4
+ "benchmark": "translation_instruction",
5
+ "benchmark_version": "v1",
6
+ "task": "translation",
7
+ "license": "cc-by-nc-4.0",
8
+ "splits": {
9
+ "test": 3000
10
+ },
11
+ "counts": {
12
+ "cases": 3000,
13
+ "source_languages": 21,
14
+ "target_languages": 22,
15
+ "language_pairs": 61,
16
+ "constraint_types": 10,
17
+ "constraint_annotations": 5402
18
+ },
19
+ "distributions": {
20
+ "constraint_id": {
21
+ "format_preserve": 2098,
22
+ "style_consistency": 633,
23
+ "syllable_order": 601,
24
+ "term_cross_sentence": 508,
25
+ "term_compliance": 502,
26
+ "academic_format_preserve": 412,
27
+ "social_preserve": 316,
28
+ "layout_break": 266,
29
+ "context_disambiguate": 42,
30
+ "coref_resolution": 24
31
+ },
32
+ "constraints_per_case": {
33
+ "1": 1307,
34
+ "2": 1138,
35
+ "3": 426,
36
+ "4": 104,
37
+ "5": 25
38
+ },
39
+ "scenario": {
40
+ "social": 922,
41
+ "doc_textbook": 575,
42
+ "novel": 303,
43
+ "pgc_subtitle": 302,
44
+ "column": 300,
45
+ "academic": 299,
46
+ "ugc_subtitle": 299
47
+ },
48
+ "domain": {
49
+ "B站动态": 320,
50
+ "小说": 303,
51
+ "ogv字幕": 302,
52
+ "弹幕": 302,
53
+ "评论": 300,
54
+ "专栏文章": 300,
55
+ "学术论文": 299,
56
+ "UGC字幕": 299,
57
+ "书籍": 293,
58
+ "网页文本": 282
59
+ },
60
+ "source_lang": {
61
+ "zh": 2419,
62
+ "en": 313,
63
+ "ja": 15,
64
+ "tr": 15,
65
+ "fil": 14,
66
+ "it": 14,
67
+ "nl": 14,
68
+ "hi": 14,
69
+ "de": 14,
70
+ "sv": 14,
71
+ "ar": 14,
72
+ "ko": 14,
73
+ "id": 14,
74
+ "fr": 14,
75
+ "es": 14,
76
+ "ro": 14,
77
+ "vi": 14,
78
+ "ru": 14,
79
+ "pl": 14,
80
+ "pt": 14,
81
+ "th": 14
82
+ },
83
+ "target_lang": {
84
+ "zh": 296,
85
+ "th": 132,
86
+ "pt": 132,
87
+ "tr": 131,
88
+ "it": 131,
89
+ "es": 130,
90
+ "ro": 130,
91
+ "vi": 130,
92
+ "ms": 130,
93
+ "de": 130,
94
+ "pl": 129,
95
+ "hi": 129,
96
+ "ru": 129,
97
+ "fr": 128,
98
+ "ko": 128,
99
+ "id": 128,
100
+ "sv": 128,
101
+ "ja": 128,
102
+ "nl": 128,
103
+ "fil": 128,
104
+ "ar": 127,
105
+ "en": 118
106
+ }
107
+ },
108
+ "constraint_taxonomy": {
109
+ "hard": [
110
+ "format_preserve",
111
+ "layout_break",
112
+ "term_compliance",
113
+ "syllable_order",
114
+ "social_preserve"
115
+ ],
116
+ "soft": [
117
+ "style_consistency",
118
+ "context_disambiguate",
119
+ "coref_resolution",
120
+ "term_cross_sentence",
121
+ "academic_format_preserve"
122
+ ]
123
+ },
124
+ "prompts": {
125
+ "model_prompt_version": "insttrans-inference-v1",
126
+ "quality_judge_prompt_version": "insttrans-quality-judge-v1",
127
+ "soft_constraint_judge_prompt_version": "insttrans-soft-constraint-judge-v1"
128
+ },
129
+ "files": {
130
+ "data/test.jsonl": {
131
+ "sha256": "fa47b65120a3c00e8c7e66bfdfe0dd75274de8d100dbd1ce0540d754bd5a4b63",
132
+ "rows": 3000
133
+ }
134
+ },
135
+ "redaction": {
136
+ "policy": "provenance identifiers and authorship removed; contact details in text masked with bare uppercase redaction tokens; everything the constraints score is left unchanged",
137
+ "removed_metadata_fields": [
138
+ "article_id",
139
+ "author",
140
+ "avid",
141
+ "batch_mode",
142
+ "book_name",
143
+ "book_title",
144
+ "category",
145
+ "chapter",
146
+ "chapter_name",
147
+ "cid",
148
+ "content_type",
149
+ "dynamic_id",
150
+ "dynm_url",
151
+ "file_path",
152
+ "language",
153
+ "mid",
154
+ "paper_title",
155
+ "pictures",
156
+ "pubtime_fans",
157
+ "raw",
158
+ "section_heading",
159
+ "section_index",
160
+ "summary",
161
+ "unique_key"
162
+ ],
163
+ "masked_in_text": {
164
+ "cases": 15,
165
+ "occurrences": {
166
+ "email": 12,
167
+ "phone": 40,
168
+ "qq_group": 3,
169
+ "wechat_id": 2
170
+ },
171
+ "placeholders": {
172
+ "phone": "PHONE_REDACTED",
173
+ "email": "EMAIL_REDACTED",
174
+ "qq_group": "QQ_GROUP_REDACTED",
175
+ "wechat_id": "WECHAT_ID_REDACTED"
176
+ },
177
+ "fields": [
178
+ "prompt",
179
+ "reference",
180
+ "source_text"
181
+ ]
182
+ },
183
+ "deliberately_kept": {
184
+ "mentions_and_hashtags": "scored by social_preserve; masking them would make the constraint unscoreable",
185
+ "urls": "inside the HTML that format_preserve scores; CDN filename digit runs were checked against source mid values, no overlap",
186
+ "bare_digit_runs": "timestamps, game ids and image dimensions are part of the text being translated",
187
+ "cases_with_mentions_in_source_text": 379
188
+ }
189
+ }
190
+ }
prepare_inputs.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Export model inputs without exposing the reference translation to the model."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import argparse
7
+ import json
8
+ from pathlib import Path
9
+
10
+ from eval.prompts import build_model_messages
11
+
12
+
13
+ def main() -> None:
14
+ parser = argparse.ArgumentParser(description=__doc__)
15
+ parser.add_argument("--data-file", type=Path,
16
+ default=Path(__file__).resolve().parent / "data/test.jsonl")
17
+ parser.add_argument("--output", type=Path, required=True)
18
+ args = parser.parse_args()
19
+ if args.output.resolve() == args.data_file.resolve():
20
+ parser.error("--output must differ from --data-file")
21
+
22
+ # split("\n"), not splitlines(): source text contains raw U+2028, which is
23
+ # legal inside a JSON string but is a line break to splitlines().
24
+ rows = [json.loads(line) for line
25
+ in args.data_file.read_text(encoding="utf-8").split("\n") if line.strip()]
26
+ args.output.parent.mkdir(parents=True, exist_ok=True)
27
+ with args.output.open("w", encoding="utf-8") as handle:
28
+ for row in rows:
29
+ handle.write(json.dumps({
30
+ "case_id": row["case_id"],
31
+ "messages": build_model_messages(row),
32
+ }, ensure_ascii=False) + "\n")
33
+ print(f"Wrote {len(rows)} model inputs to {args.output}")
34
+
35
+
36
+ if __name__ == "__main__":
37
+ main()
release_manifest.json ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "release_version": "public-v1",
3
+ "source_commit": "aa8b0b2473a712160d00c73460e065dbb93f2d78",
4
+ "changes": [
5
+ "Preserved data and model/Judge prompts",
6
+ "Rejected invalid quality and missing soft-constraint Judge verdicts",
7
+ "Corrected redaction-policy description"
8
+ ],
9
+ "files": {
10
+ ".gitignore": {
11
+ "size": 59,
12
+ "sha256": "b5c9e3ffb21c37794ca1a5be1feccf7c3bc647d32975dcd30e2cbd53d1342481"
13
+ },
14
+ "LICENSE": {
15
+ "size": 478,
16
+ "sha256": "b91bc996f6333ce709e87c822594cc869f7950089a2ea16034e213c465f27065"
17
+ },
18
+ "README.md": {
19
+ "size": 15750,
20
+ "sha256": "37f26b3e40781cd2256d2e74e0507d0bd5f21eae71dfdde5032d0cc2f10dc663"
21
+ },
22
+ "RELEASE_REVIEW.md": {
23
+ "size": 467,
24
+ "sha256": "5e6e41b5125d64af1fd4b31a2492e81b6ffa01374ff747bbef67418e32ab2e14"
25
+ },
26
+ "data/test.jsonl": {
27
+ "size": 28217329,
28
+ "sha256": "fa47b65120a3c00e8c7e66bfdfe0dd75274de8d100dbd1ce0540d754bd5a4b63"
29
+ },
30
+ "eval/__init__.py": {
31
+ "size": 70,
32
+ "sha256": "234ead7b864f2fa71729085b56bb7da890189d5b0e0735ae3a8e408c62ca693d"
33
+ },
34
+ "eval/constraints.py": {
35
+ "size": 13656,
36
+ "sha256": "00cd6f3bb140bfcfaebb1e281790331059aef9f9091b75213e33e67ecd3074e7"
37
+ },
38
+ "eval/judge_client.py": {
39
+ "size": 6974,
40
+ "sha256": "128a6e9d49059d9ccd184150a5b828857c401f4fa5c4ca6bb811a293d529cb8c"
41
+ },
42
+ "eval/metrics.py": {
43
+ "size": 5416,
44
+ "sha256": "0ea1a6f53161c5fe1e78dcd2185a9dc7dd1b486fbcfb37913b790e25efe114af"
45
+ },
46
+ "eval/prompts.py": {
47
+ "size": 5614,
48
+ "sha256": "31cb0335333c8a0bfebd2c12d078760468570a2548c03ef7296c307af24473a7"
49
+ },
50
+ "eval/syllable.py": {
51
+ "size": 40979,
52
+ "sha256": "aa0036d763fbce3db89225ab12f64f5f7dcdfb8fc5e40ab1d78ab5b4aea968f6"
53
+ },
54
+ "evaluate.py": {
55
+ "size": 7457,
56
+ "sha256": "519a021d16e2b42f8201f4f1e2a8d4782c568920573855eff8c58760f3d3e0f8"
57
+ },
58
+ "manifest.json": {
59
+ "size": 4414,
60
+ "sha256": "a96183a99e4b65b3dc7927262c65a18c2d9a69b298ecc1826264742e4b8196eb"
61
+ },
62
+ "prepare_inputs.py": {
63
+ "size": 1370,
64
+ "sha256": "3647aa8cec5442d645f5c6725ebda4bfcd51a16ab2135f5a898a2c190c909365"
65
+ },
66
+ "requirements.txt": {
67
+ "size": 148,
68
+ "sha256": "1331e4402ee21b315cda8a73a3d2f27a27c6fdf9def708f427cacdeeb95d78b4"
69
+ }
70
+ }
71
+ }
requirements.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ datasets>=3.0,<5
2
+ # >=1.66 for client.responses, which the Judge uses for reasoning models.
3
+ openai>=1.66,<3
4
+ pyphen>=0.14
5
+ fugashi>=1.3
6
+ num2words>=0.5