hsilvosa commited on
Commit
ee21c21
·
verified ·
1 Parent(s): 337ee23

Upload model v1.0

Browse files
README.md CHANGED
@@ -5,6 +5,12 @@ base_model_relation: finetune
5
  language:
6
  - zh
7
  - en
 
 
 
 
 
 
8
  library_name: transformers
9
  pipeline_tag: translation
10
  tags:
@@ -12,27 +18,37 @@ tags:
12
  - chinese
13
  - english
14
  - web-novel
15
- - xianxia
16
  - wuxia
 
17
  - lora
18
  - hy-mt2
19
  ---
20
 
21
  # feishengmt
22
 
23
- Chinese-to-English translation of web novels (xianxia / wuxia), fine-tuned from
24
- [tencent/Hy-MT2-1.8B](https://huggingface.co/tencent/Hy-MT2-1.8B) with LoRA (merged into the weights). It learns the
25
- vocabulary and conventions of the genre: cultivation terms, honorifics (Senior / Junior Brother ...), recurring names.
 
 
 
 
 
 
 
 
 
26
 
27
- This is a **v0.1 preview** with a small evaluation. It is a modified version of Hy-MT2-1.8B and is not endorsed by
28
- Tencent. A quantized GGUF version (1.1 GB) is available at [hsilvosa/feishengmt-GGUF](https://huggingface.co/hsilvosa/feishengmt-GGUF).
 
29
 
30
  ## Use it with the included pipeline
31
 
32
- The model works best through the pipeline in the `pipeline/` folder of this repository. The raw model does not write
33
- quotation marks or final punctuation, and it follows the glossary conventions only when the glossary entries are in the
34
- prompt. The pipeline splits text at quotation marks and sentence ends, adds the glossary entries found in each piece, and
35
- rebuilds the text with quotes and punctuation.
36
 
37
  ```python
38
  import sys
@@ -40,63 +56,97 @@ from huggingface_hub import snapshot_download
40
 
41
  path = snapshot_download("hsilvosa/feishengmt")
42
  sys.path.insert(0, f"{path}/pipeline")
43
- from webnovel_mt.translate import hf_backend, translate_document
 
44
 
45
  backend = hf_backend(path) # needs transformers>=5.6 and torch
46
  chinese = open("chapter.txt", encoding="utf-8").read()
47
- print(translate_document(chinese, backend))
48
  ```
49
 
50
- Without the pipeline, use the prompt below. Glossary lines are optional; add them for the terms found in the text.
51
 
52
  ```
53
- 参考下面的翻译:
54
- 师弟 翻译成 Junior Brother
55
- 储物袋 翻译成 bag of holding
56
  将以下文本翻译为English,注意只需要输出翻译后的结果,不要额外解释:
57
 
58
- <Chinese text, at most ~250 characters>
59
  ```
60
 
61
- Keep inputs short (a sentence or a paragraph of up to about 250 characters). Translating a whole chapter in one
62
- generation is not reliable (repetition loops in 2 of 4 test chapters).
 
 
 
 
63
 
64
  ## Results
65
 
66
- Held-out sample of 150 sentences and 20 paragraphs, greedy decoding, one run. Full tables, confidence intervals and
67
- caveats are in [RESULTS.md](RESULTS.md); raw metrics are in `results/metrics.json`.
 
 
 
68
 
69
- | System | Sentences BLEU / chrF / COMET | Paragraphs BLEU / chrF / COMET |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  |---|---|---|
71
- | Hy-MT2-1.8B, zero-shot | 10.5 / 38.6 / 72.4 | 8.9 / 43.4 / 74.9 |
72
- | **This model + glossary prompt** | **22.9 / 47.9 / 75.8** | **16.1 / 47.1 / 75.5** |
73
- | This model, plain prompt | 21.5 / 46.4 / 75.1 | 15.7 / 47.0 / 75.5 |
 
 
 
74
 
75
- * Honorific and term renderings that follow the glossary convention: 97% with the glossary in the prompt, 78% without
76
- (119 checked segments; the honorific counts per term are 1-13).
77
- * Four held-out chapters through the pipeline: BLEU 31.8, chrF 65.7 (single pass: 19.6 / 55.9).
78
- * BLEU is depressed by the references, which follow their own conventions.
79
 
80
  ## Training
81
 
82
- * Base: Hy-MT2-1.8B. LoRA r=16, alpha=32, all attention and MLP projections, learning rate 2e-4, one epoch, bf16, one
83
- RTX 3060 (55 minutes).
84
- * Data: 20,000 sentence-level segments, 268 extra segments containing honorific terms, and 3,000 paragraph-level
85
- segments (100-400 characters) from a Chinese-English web-novel corpus. Examples sharing text with
86
- the evaluation sample were removed. The corpus is not redistributed.
87
- * The glossary (76 entries: honorifics, cultivation vocabulary, recurring names) is in the prompt during training, only
88
- for entries that the reference translation respects. School-relative terms (师兄, 师弟, 师姐, 师妹, 师叔) in the
89
- references were rewritten to the Senior/Junior convention.
 
 
 
 
90
 
91
  ## Limitations
92
 
93
- * In-domain only. The evaluation uses random held-out segments of the same corpus; generalization to unseen novels was
94
- not measured. The glossary encodes one convention (Senior/Junior); other translators use Martial Brother or Elder
95
- Brother.
96
- * Small evaluation (170 segments, 4 chapters, one run). Differences below about 1 chrF point are noise.
97
- * Known errors: omitted honorifics in short fragments, occasional literal renderings of titles, invented words for rare
98
- terms, and unit conversions for `时辰` only through the glossary rule.
99
- * Only Chinese to English.
 
 
 
 
 
 
100
 
101
  ## License and attribution
102
 
 
5
  language:
6
  - zh
7
  - en
8
+ - fr
9
+ - pt
10
+ - es
11
+ - id
12
+ - ja
13
+ - ko
14
  library_name: transformers
15
  pipeline_tag: translation
16
  tags:
 
18
  - chinese
19
  - english
20
  - web-novel
 
21
  - wuxia
22
+ - xianxia
23
  - lora
24
  - hy-mt2
25
  ---
26
 
27
  # feishengmt
28
 
29
+ Chinese-to-English translation of wuxia and xianxia fiction. The model is a fine-tune of
30
+ [tencent/Hy-MT2-1.8B](https://huggingface.co/tencent/Hy-MT2-1.8B) (LoRA, merged into the weights), trained on wuxia
31
+ text. It is built mainly for **English**; a short second stage adapted it so that it also answers in French,
32
+ Portuguese, Spanish, Indonesian, Japanese and Korean when one of them is asked for.
33
+
34
+ What it learned beyond the base model:
35
+
36
+ * The vocabulary and conventions of the genre: cultivation terms, honorifics (Senior / Junior Brother ...), recurring
37
+ names.
38
+ * To work on paragraphs, not on short pieces. It writes the quotation marks by itself, also when the Chinese uses
39
+ `「」` or Traditional characters, when a quote runs over several paragraphs, and when the input starts or ends in the
40
+ middle of a quote.
41
 
42
+ Version 1.0. It is a modified version of Hy-MT2-1.8B and is not endorsed by Tencent. A quantized GGUF version (1.1 GB) is
43
+ at [hsilvosa/feishengmt-GGUF](https://huggingface.co/hsilvosa/feishengmt-GGUF) and a WebGPU (ONNX) version for the browser is at
44
+ [hsilvosa/feishengmt-ONNX](https://huggingface.co/hsilvosa/feishengmt-ONNX).
45
 
46
  ## Use it with the included pipeline
47
 
48
+ The model works best through the pipeline in the `pipeline/` folder of this repository. It cuts the text into windows of
49
+ whole paragraphs (up to 400 characters, or one paragraph when it is longer), adds the glossary entries found in each
50
+ window, checks that the answer has the same paragraphs and the same quote marks as the source, and translates again in
51
+ smaller parts when it does not.
52
 
53
  ```python
54
  import sys
 
56
 
57
  path = snapshot_download("hsilvosa/feishengmt")
58
  sys.path.insert(0, f"{path}/pipeline")
59
+ from webnovel_mt.translate import hf_backend
60
+ from webnovel_mt.windows import translate_document_windows
61
 
62
  backend = hf_backend(path) # needs transformers>=5.6 and torch
63
  chinese = open("chapter.txt", encoding="utf-8").read()
64
+ print(translate_document_windows(chinese, backend))
65
  ```
66
 
67
+ Without the pipeline, use this prompt. The language name goes in Chinese or in English (`英语` or `English`).
68
 
69
  ```
 
 
 
70
  将以下文本翻译为English,注意只需要输出翻译后的结果,不要额外解释:
71
 
72
+ <Chinese text: one or more paragraphs, up to about 400 characters>
73
  ```
74
 
75
+ ## Other languages
76
+
77
+ Replace the language name in the prompt: `法语` (French), `葡萄牙语` (Portuguese), `西班牙语` (Spanish), `印尼语`
78
+ (Indonesian), `日语` (Japanese), `韩语` (Korean). The pipeline above is for English only: its checks of quote marks follow
79
+ English conventions and its glossary is English. For the other languages, send one paragraph or a short window at a time
80
+ and check the result yourself.
81
 
82
  ## Results
83
 
84
+ All numbers are one run with greedy decoding on windows of chapters that were held out from training. Reference
85
+ translations are from a human-made corpus; they follow their own conventions, so chrF is only a rough guide.
86
+
87
+ **Chinese to English (pipeline, windows mode)**, two held-out sets from different novels, chrF and the share of answers
88
+ whose quote marks are those of the reference. The variants perturb the Chinese source in the ways described above.
89
 
90
+ | Variant of the source | Set 1 (30 windows) chrF / quotes | Set 2 (40 windows, 28 for the split quote) chrF / quotes |
91
+ |---|---|---|
92
+ | Clean | 63.0 / 100 % | 47.9 / 97.5 % |
93
+ | Corner quotes `「」` | 62.9 / 100 % | 48.1 / 95 % |
94
+ | Quote cut across paragraphs | 63.8 / 100 % | 48.3 / 96 % |
95
+ | Traditional characters | 63.0 / 100 % | 47.1 / 97.5 % |
96
+ | Traditional and `「」` | 62.9 / 100 % | 47.1 / 95 % |
97
+
98
+ For comparison, the first version of this model (v0.1) with 250-character pieces scored chrF 44.8 on set 2, and
99
+ reproduced the quote marks of a quote split across paragraphs in none of the windows (against 96 % here). On a small check
100
+ with excerpts of older Chinese novels, 26 of 38 paragraphs with quotes came out with the same number of quote marks as
101
+ the original (19 for v0.1); most of the other 12 come from typos in the source and from book titles in `《》`.
102
+
103
+ **Other languages**, 60 windows (30 from the novels of the training corpus, 30 from older novels), no references, so only two things were measured: whether
104
+ the answer is in the requested language and whether it is as close in meaning to the source as the base model's answer
105
+ (LaBSE similarity).
106
+
107
+ | Language | Answer in the requested language (name given in Chinese) | (name given in English, 20 windows) |
108
  |---|---|---|
109
+ | French | 98 % | 100 % |
110
+ | Portuguese | 97 % | 95 % |
111
+ | Spanish | 97 % | 100 % |
112
+ | Indonesian | 97 % | 100 % |
113
+ | Japanese | 98 % | 85 % |
114
+ | Korean | 100 % | 100 % |
115
 
116
+ Before the second stage the figures were 48 to 92 % with the name in Chinese and 0 to 20 % with the name in English
117
+ (Spanish was not measured): the model answered in English or mixed languages. The LaBSE similarity is the same as the
118
+ base model's (differences of -0.02 to +0.01).
 
119
 
120
  ## Training
121
 
122
+ * Base: Hy-MT2-1.8B. LoRA r=16, alpha=32, all attention and MLP projections, bf16, one RTX 3060.
123
+ * **Stage 1, English.** About 23,000 examples (7.4 million tokens) of Chinese paragraph windows with their English
124
+ translation, from a Chinese-English wuxia and xianxia corpus. The Chinese side was perturbed at random (Traditional
125
+ characters, `「」` quotes, cut borders) while the English side kept clean double quotes, so that the model learns to
126
+ write the quotes by itself. A glossary (honorifics, cultivation vocabulary, recurring names) is in the
127
+ prompt during training. Learning rate 2e-4, one epoch, 715 steps, 2 h 12 min.
128
+ * **Stage 2, other languages.** About 1,000 examples in the six other languages, made by the stage 1 model itself from
129
+ Chinese training windows and kept only if they have the same paragraphs, are in the right language, have no English or
130
+ Chinese left over and have a LaBSE similarity of at least 0.72 with the source. Training continued from stage 1 with
131
+ these examples mixed with 1,500 English windows and 300 sentences, learning rate 1e-4, 99 steps (18 minutes).
132
+ The English results above are after this stage.
133
+ * The corpus and the generated examples are not redistributed.
134
 
135
  ## Limitations
136
 
137
+ * **English is the priority.** The other languages were only taught to follow the request, and their quality is about the
138
+ one of the base model: they were made by this model and filtered for form, not for meaning. Names and some terms come
139
+ out wrong or stay in English. Portuguese had the fewest training examples.
140
+ * Stage 2 cost a little in English: -0.4 chrF on average on set 1 and no change on set 2 (one run; the drop is within the
141
+ noise of such a run, but it is negative in all five variants of set 1).
142
+ * Domain: wuxia and xianxia. Modern text, technical text and literary or classical Chinese were not trained or measured,
143
+ apart from the small check above. The glossary encodes one convention (Senior/Junior); other translators use Martial Brother or
144
+ Elder Brother.
145
+ * Small evaluation (two sets of 30 and 40 windows, one run). Differences below about 1 chrF point are noise. The
146
+ non-English results have no reference translations.
147
+ * Known errors: dropped or repeated sentences in very long dialogues, characters left in Chinese when a name is rare,
148
+ and a quote mark that is lost or added when the source has a typo in its quotes.
149
+ * A model of 1.8 billion parameters: do not use it where an error matters.
150
 
151
  ## License and attribution
152
 
RESULTS.md DELETED
@@ -1,152 +0,0 @@
1
- # Results
2
-
3
- All numbers come from a single run per configuration (greedy decoding, no sampling), so differences below roughly 1 chrF
4
- point on this sample are within noise. Where a bootstrap confidence interval was computed it is given.
5
-
6
- ## Setup
7
-
8
- * Base model: `tencent/Hy-MT2-1.8B` (Apache-2.0). Fine-tuning: LoRA r=16, alpha=32, all attention and MLP projections,
9
- learning rate 2e-4, one epoch, bf16, RTX 3060 12 GB.
10
- * Training data: the training splits of a Chinese-English web-novel corpus (sentence-level
11
- segments, 100-400 character paragraphs). The corpus is not redistributed.
12
- * Evaluation sample: 150 sentences (10-150 characters) and 20 paragraphs (150-400 characters) drawn with a fixed seed
13
- from held-out splits, plus 4 held-out chapters (~3,200 Chinese characters each). `scripts/prepare/make_sample.py`
14
- regenerates the sample.
15
- * Leakage control: the paragraph-level data overlaps the sentence-level test split, so every training example sharing a
16
- 20-character source shingle with the evaluation sample or the evaluation chapters is dropped before sampling
17
- (`train_lora.py`). The 5k+1k model (`LoRA 5k sent + 1k para`) was trained with an earlier sentence-level filter only.
18
- * Metrics: SacreBLEU, chrF, and COMET (`Unbabel/wmt22-comet-da`, Chinese source). References have
19
- their own conventions and noise, which depresses BLEU; chrF and COMET are more reliable here.
20
-
21
- ## 1. Base models, zero-shot
22
-
23
- | Model | Sentences BLEU / chrF | Paragraphs BLEU / chrF | COMET sent. / para. |
24
- |---|---|---|---|
25
- | Qwen3.5-2B | 9.2 / 36.3 | 7.9 / 41.8 | 70.0 / 73.7 |
26
- | Gemma 4 E2B | 12.0 / 40.3 | 10.0 / 44.7 | 71.8 / 74.2 |
27
- | Hy-MT2-1.8B | 10.5 / 38.6 | 8.9 / 43.4 | 72.4 / 74.9 |
28
- | Index-Translate-2B | 10.6 / 41.0 | 10.5 / 45.2 | 73.6 / 75.0 |
29
-
30
- Paired bootstrap on sentence-level chrF (2,000 resamples): Index-Translate is better than Hy-MT2 with probability 99.6%,
31
- Hy-MT2 is better than Qwen3.5-2B with 99.9%, and Index-Translate versus Gemma 4 E2B is not distinguishable (75%).
32
- Qwen3.5-2B and Gemma 4 E2B leave Chinese characters untranslated in 10 of 150 sentences each, Hy-MT2 in 1.
33
- Gemma 4 E2B ran partly on CPU (6 GiB GPU cap), so its speed is not comparable. COMET for Qwen, Gemma and Index comes
34
- from an earlier run whose per-segment scores were not saved.
35
-
36
- Hy-MT2-1.8B was chosen as the base for the fine-tune because it is the smallest, has native terminology prompting and an
37
- Apache-2.0 license. Index-Translate-2B is slightly better zero-shot; it was not fine-tuned (without the optional `flash-linear-attention` and
38
- `causal_conv1d` kernels its Gated DeltaNet layers use slow reference code, and a short LoRA benchmark peaked at 14.9 GB,
39
- above the 12 GB card).
40
-
41
- ## 2. Data curve (LoRA on Hy-MT2-1.8B, plain prompt)
42
-
43
- | Training data | Sent. BLEU / chrF | Para. BLEU / chrF | COMET sent. / para. | Train time |
44
- |---|---|---|---|---|
45
- | none (base) | 10.5 / 38.6 | 8.9 / 43.4 | 72.4 / 74.9 | - |
46
- | 2k sent + 1k para | 18.0 / 43.3 | 12.6 / 45.0 | 74.4 / 74.8 | 8.5 min |
47
- | 5k sent + 1k para | 19.5 / 44.6 | 13.7 / 45.4 | 75.0 / 74.7 | 19 min |
48
- | 10k sent + 1k para | 21.5 / 46.4 | 15.1 / 45.7 | 75.5 / 74.9 | 18 min |
49
- | 20k sent + 1k para | 22.5 / 47.2 | 14.8 / 45.9 | 75.9 / 75.2 | 30 min |
50
- | 5k sent + 3k para | 20.8 / 45.9 | 15.3 / 46.7 | n/a | 23 min |
51
-
52
- Sentence-level chrF difference to the 5k+1k model (bootstrap 95% CI): 2k -1.5 [-2.6, -0.5]; 10k +1.6 [+0.3, +2.9];
53
- 20k +2.5 [+1.3, +3.7]; 20k versus 10k +0.9 [-0.2, +1.9] (not significant); 5k+3k paragraphs +0.5 [-0.7, +1.7] on
54
- sentences and +1.4 [+0.4, +2.3] on paragraphs. COMET gains flatten earlier than BLEU/chrF: base to final is +3.4
55
- [+2.3, +4.5] on sentences but only +0.6 [-0.2, +1.3] on paragraphs. Training times are for the RTX 3060.
56
-
57
- ## 3. Terminology and the glossary
58
-
59
- The corpus is inconsistent for school-relative address terms (`师兄`, `师弟`, `贤侄` ...). `docs/glossary_proposal.md`
60
- lists, for each curated term, what the training split does. The glossary (`webnovel_mt/data`, 76 entries: 44 curated
61
- terms and 32 names/titles) follows the Senior/Junior convention for those terms.
62
-
63
- Hy-MT2's native prompt `参考下面的翻译:X 翻译成 Y` makes the model follow the glossary without any retraining.
64
- Rate at which the output contains the glossary rendering (137 test segments, 119 with a checked term):
65
-
66
- | Term | n | 20k model, plain prompt | 20k model + glossary | Final, plain | Final + glossary |
67
- |---|---|---|---|---|---|
68
- | 前辈 Senior | 13 | 69% | 92% | 38% | 92% |
69
- | 晚辈 Junior | 3 | 0% | 33% | 0% | 67% |
70
- | 道友 Fellow Daoist | 3 | 100% | 100% | 67% | 100% |
71
- | 师兄 Senior Brother | 4 | 25% | 100% | 0% | 75% |
72
- | 师弟 Junior Brother | 4 | 0% | 100% | 0% | 100% |
73
- | 师姐 Senior Sister | 2 | 0% | 100% | 0% | 100% |
74
- | 贤侄 Junior | 1 | 0% | 100% | 0% | 100% |
75
- | 魔道, 蛊师, 蛊仙 | 89 | 97-100% | 100% | 93-100% | 100% |
76
- | **Total** | **119** | **85%** | **97%** | **78%** | **97%** |
77
-
78
- Honorific samples are tiny (1-13 per term). A model trained with glossary prompts is worse than the earlier one when the
79
- glossary is not injected (78% against 85%), so the glossary must always be injected at inference time. The `时辰` rule
80
- (`三个时辰` becomes "six hours") works in ordinary sentences but is ignored on very short fragments.
81
-
82
- ## 4. Final model
83
-
84
- 20k sentences + 268 honorific segments + 3k paragraphs, glossary in the prompt, school-term references rewritten to the
85
- Senior/Junior convention, 242 optimizer steps, 55 minutes.
86
-
87
- | System | Sent. BLEU / chrF | Para. BLEU / chrF | COMET sent. / para. |
88
- |---|---|---|---|
89
- | 20k+1k, plain prompt | 22.5 / 47.2 | 14.8 / 45.9 | 75.9 / 75.2 |
90
- | 20k+1k, glossary prompt | 22.6 / 46.9 | 15.0 / 46.1 | 75.7 / 75.5 |
91
- | **Final, glossary prompt** | **22.9 / 47.9** | **16.1 / 47.1** | 75.8 / 75.5 |
92
- | Final, plain prompt | 21.5 / 46.4 | 15.7 / 47.0 | 75.1 / 75.5 |
93
- | Final, GGUF Q4_K_M, glossary prompt | 22.1 / 47.0 | 15.2 / 46.9 | 75.5 / 75.9 |
94
-
95
- The final model is not significantly better than the 20k+1k model on chrF (+0.8 [-0.5, +2.1] sentences,
96
- +1.2 [-0.3, +2.6] paragraphs) or COMET (-0.08 [-0.65, +0.50]); part of the difference may come from the extra
97
- paragraphs rather than the glossary. Its value is terminology control.
98
-
99
- ## 5. Quantization
100
-
101
- | Version | Size | Sent. BLEU / chrF | Para. BLEU / chrF |
102
- |---|---|---|---|
103
- | bf16 (transformers), 5k+1k model | 3.6 GB | 19.5 / 44.6 | 13.7 / 45.4 |
104
- | GGUF F16 | 3.6 GB | 19.1 / 44.2 | 13.9 / 45.6 |
105
- | GGUF Q8_0 | 1.9 GB | 19.2 / 44.2 | 14.3 / 46.1 |
106
- | GGUF Q4_K_M | 1.1 GB | 19.0 / 44.1 | 12.8 / 45.2 |
107
-
108
- Q4_K_M costs -0.7 sentence chrF against bf16 (CI [-1.5, +0.2]) and -0.3 COMET on the final model (CI [-0.8, +0.2]);
109
- neither is distinguishable from noise. GGUF F16 is already 0.45 chrF below transformers bf16, so part of the gap is
110
- engine difference and not quantization.
111
-
112
- ## 6. Chapters (4 held-out chapters, ~3,200 characters each)
113
-
114
- | Mode | BLEU | chrF | Notes |
115
- |---|---|---|---|
116
- | Base model, 250-character windows | 18.5 | 57.7 | |
117
- | 5k+1k model, 250-character windows | 26.4 | 62.6 | |
118
- | Final, 250-character windows | 29.8 | 65.3 | dialogue quotes missing |
119
- | Final, windows split at quotation marks | 29.0 | 65.1 | quote marks match the source in all 4 chapters |
120
- | **Final, windows at quotes + punctuation restored** | **31.8** | **65.7** | `webnovel_mt.docmt` |
121
- | Final, whole chapter in one generation | 19.6 | 55.9 | 2 of 4 chapters loop; no quotes |
122
-
123
- The model was trained without quotation marks and without final punctuation, so `docmt.py` splits the source at
124
- quotation marks, translates dialogue and narration separately, and restores the marks and the final punctuation.
125
- Single-pass chapter translation is unreliable: 8-gram repetitions of 1,546 and 109 occurrences in two chapters, output up
126
- to 1.9x the expected length, and about 8x slower. Chapter-level scores are from 4 chapters only.
127
-
128
- ## 7. Resource use (GGUF Q4_K_M, 1.13 GB)
129
-
130
- Measured with llama.cpp (Vulkan build) on a Ryzen 7 5700X (8 cores / 16 threads), RTX 3060 and 32 GB RAM, translating
131
- whole chapters with the final pipeline (`scripts/eval/bench_chapter.py`).
132
-
133
- | Configuration | Time per chapter | Speed | Extra VRAM | Process RAM |
134
- |---|---|---|---|---|
135
- | GPU, 4 parallel requests (4 chapters) | 12.7 s | 207 tok/s | 1.9 GB | 2.7 GB |
136
- | GPU, 1 request (2 chapters) | 20.2 s | 131 tok/s | 1.7 GB | 2.2 GB |
137
- | CPU only, 8 threads, 4 parallel (1 chapter) | 56.9 s | 43 tok/s | 0 | 2.0 GB |
138
- | CPU only, 8 threads, 1 request (1 chapter) | 101.7 s | 24 tok/s | 0 | 1.7 GB |
139
-
140
- For comparison, the unquantized model in transformers needs 3.9 GB of VRAM and about 32 s per chapter. These are single
141
- measurements on one machine; weaker CPUs will be slower.
142
-
143
- ## Known limitations
144
-
145
- * Evaluation is small (170 segments, 4 chapters), single-seed, and in-domain. It does not measure generalization to
146
- novels absent from the training corpus; the corpus carries no novel identifiers, so a held-out-novel split could not be
147
- built.
148
- * The corpus mixes novels with different conventions; terms such as `师兄` have no single correct rendering.
149
- * The raw model neither writes quotation marks nor final punctuation; the `webnovel_mt` pipeline does.
150
- * Single-pass translation of chapter-length input is not supported.
151
- * Honorific compliance is measured on very few segments.
152
- * The GGUF was only exercised with `llama-server`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
SHA256SUMS CHANGED
@@ -1,21 +1,21 @@
1
- 193bfa0bafc40067192e96792ff24c55cc90c9613ce475132fc226be5d1737fd adapter/adapter_config.json
2
- 381ea2b5c200ffc3f8abc22967f7ef8daa57b4f9e4d73c06c8375297b6463979 adapter/adapter_model.safetensors
3
  b7491ec0e9c869dfce20f2176758099bf248d979dd05530ede99deb21698acee chat_template.jinja
4
  b61be37f9ad3b66bdb9c718ffdfb8cfb7d9016817599f853c186b49cffee6778 config.json
5
  776c3a198913887e695914cd270ee7c8574733148a360163fc00615ee3682e0e generation_config.json
6
  cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE
7
- 7b02197e42431b81fd17ba512c16a83bb23df4bdd8e51eae9e7f1f1862c215e2 model.safetensors
8
  4849d4af9c1afc9f1f6866acdb4645f7292fb99d77a23881794349c1c4440b20 NOTICE
9
  8c2c7b5c6728d75f80214e147593e162f6c754edce0d54d589c35bcfcc6c5c8c pipeline/webnovel_mt/__init__.py
10
- d6e1193ac7236e0f1c3853ade0a07fc9513b7a0dc13403f2c4bacf6d159a070f pipeline/webnovel_mt/config.py
11
  bf24184e8891135f6460f2d78e61170c3fe4e7a0e14006d082cfb514aa4c619d pipeline/webnovel_mt/data/glossary_auto_clean.json
12
  b60b157690a2bf199dc0162c444a586076da10518f075e8fa0d6bb666829662c pipeline/webnovel_mt/data/glossary_core.json
13
  898f3a86e3982ed36f4d1cc2523828b8e425717db14d6f0fed7f91ca46c14e3b pipeline/webnovel_mt/docmt.py
14
  7099d24ebb4991a4f398c8dd3888f377196c7a6edd579808e28782a8c19219c4 pipeline/webnovel_mt/glossary.py
15
- 728ad37d473c57d9b0dcd796570f6a4c7ad08bec323d77b1944b1054f2edec25 pipeline/webnovel_mt/translate.py
16
- 17501c7f9758134b6e7a91d912d354b3509754040f77b88f52347130c54f47c5 README.md
17
- b284752a36ce1024e1d0adacd774db764f09179424f88acd3a885f4c6854fdb8 results/metrics.json
18
- e38488ea7d521755083946dead73b17dd8029879ca67eb5480d0b12206c0efa4 RESULTS.md
19
  bb9f59990034dae326581b9c62471523975417869f78a244b7ae2ce8cbb085eb special_tokens_map.json
20
  b475bbef1b0b2fd57dcb865332b546475bd1ede2deb3bb91bafd0c047a8a530a tokenizer.json
21
  53bd8581b601a8ee9caefeb988207de50b3fc0b733295bdf5ad68dec4cc0b07c tokenizer_config.json
 
1
+ a15b91d7731f1e5a783a9c1f7131b94339a20dbfce4b1712e61fd696bf5ffc36 adapter/adapter_config.json
2
+ b20b70d66ab90a2b40d9ec32b2259f2d70709c88430a9b0d4066d0ef628c93d9 adapter/adapter_model.safetensors
3
  b7491ec0e9c869dfce20f2176758099bf248d979dd05530ede99deb21698acee chat_template.jinja
4
  b61be37f9ad3b66bdb9c718ffdfb8cfb7d9016817599f853c186b49cffee6778 config.json
5
  776c3a198913887e695914cd270ee7c8574733148a360163fc00615ee3682e0e generation_config.json
6
  cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30 LICENSE
7
+ 7aad1375446c7d38ba5fcb6ae4d7edc880cd14242ede893edff6e2fbf89d7bea model.safetensors
8
  4849d4af9c1afc9f1f6866acdb4645f7292fb99d77a23881794349c1c4440b20 NOTICE
9
  8c2c7b5c6728d75f80214e147593e162f6c754edce0d54d589c35bcfcc6c5c8c pipeline/webnovel_mt/__init__.py
10
+ fc2ab79b270b5e7a6c045d930f54883fd7bba4eee5b89c3165e5ba49a487ffdb pipeline/webnovel_mt/config.py
11
  bf24184e8891135f6460f2d78e61170c3fe4e7a0e14006d082cfb514aa4c619d pipeline/webnovel_mt/data/glossary_auto_clean.json
12
  b60b157690a2bf199dc0162c444a586076da10518f075e8fa0d6bb666829662c pipeline/webnovel_mt/data/glossary_core.json
13
  898f3a86e3982ed36f4d1cc2523828b8e425717db14d6f0fed7f91ca46c14e3b pipeline/webnovel_mt/docmt.py
14
  7099d24ebb4991a4f398c8dd3888f377196c7a6edd579808e28782a8c19219c4 pipeline/webnovel_mt/glossary.py
15
+ 2086b7e42b86d2ba6bcd09eaaada71c6f2657a46e28247baf7ea9da417ae299c pipeline/webnovel_mt/perturb.py
16
+ e5a9052a62418fa67703a0b3923ed8e3e4b7923557134804e568e586e1b39391 pipeline/webnovel_mt/translate.py
17
+ 2bca22517c58757afd1787fec1d1be9daafca93e8cdc452d143ed491e38685c4 pipeline/webnovel_mt/windows.py
18
+ edfae72db039009cca3f881346f039924e0607a95fed0b4f8a399cb5eaa852b1 README.md
19
  bb9f59990034dae326581b9c62471523975417869f78a244b7ae2ce8cbb085eb special_tokens_map.json
20
  b475bbef1b0b2fd57dcb865332b546475bd1ede2deb3bb91bafd0c047a8a530a tokenizer.json
21
  53bd8581b601a8ee9caefeb988207de50b3fc0b733295bdf5ad68dec4cc0b07c tokenizer_config.json
adapter/adapter_config.json CHANGED
@@ -32,13 +32,13 @@
32
  "rank_pattern": {},
33
  "revision": null,
34
  "target_modules": [
 
 
35
  "k_proj",
36
  "up_proj",
37
- "gate_proj",
38
- "v_proj",
39
- "o_proj",
40
  "q_proj",
41
- "down_proj"
42
  ],
43
  "target_parameters": null,
44
  "task_type": "CAUSAL_LM",
 
32
  "rank_pattern": {},
33
  "revision": null,
34
  "target_modules": [
35
+ "o_proj",
36
+ "v_proj",
37
  "k_proj",
38
  "up_proj",
39
+ "down_proj",
 
 
40
  "q_proj",
41
+ "gate_proj"
42
  ],
43
  "target_parameters": null,
44
  "task_type": "CAUSAL_LM",
adapter/adapter_model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:381ea2b5c200ffc3f8abc22967f7ef8daa57b4f9e4d73c06c8375297b6463979
3
  size 77654112
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b20b70d66ab90a2b40d9ec32b2259f2d70709c88430a9b0d4066d0ef628c93d9
3
  size 77654112
model.safetensors CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7b02197e42431b81fd17ba512c16a83bb23df4bdd8e51eae9e7f1f1862c215e2
3
  size 3582202056
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7aad1375446c7d38ba5fcb6ae4d7edc880cd14242ede893edff6e2fbf89d7bea
3
  size 3582202056
pipeline/webnovel_mt/config.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  WEBNOVEL_WORK working directory for adapters, merged weights, GGUF files and model outputs (default: ./work)
4
  WUXIA_CORPUS_ROOT the corpus' `processed_data` directory (only needed by training and evaluation scripts)
 
5
  LLAMA_CPP_BIN directory with llama-server / llama-quantize (default: look them up on PATH)
6
  """
7
  import os
@@ -19,6 +20,13 @@ def corpus_root() -> Path:
19
  return Path(root)
20
 
21
 
 
 
 
 
 
 
 
22
  def llama_bin(name: str) -> str:
23
  """Return the path of a llama.cpp executable (e.g. 'llama-server')."""
24
  folder = os.environ.get("LLAMA_CPP_BIN")
 
2
 
3
  WEBNOVEL_WORK working directory for adapters, merged weights, GGUF files and model outputs (default: ./work)
4
  WUXIA_CORPUS_ROOT the corpus' `processed_data` directory (only needed by training and evaluation scripts)
5
+ WUXIA_RAW_ROOT the corpus' `wuxia_corpus/data` directory (segmented chapters and alignments; only the block builder needs it)
6
  LLAMA_CPP_BIN directory with llama-server / llama-quantize (default: look them up on PATH)
7
  """
8
  import os
 
20
  return Path(root)
21
 
22
 
23
+ def raw_root() -> Path:
24
+ root = os.environ.get("WUXIA_RAW_ROOT")
25
+ if not root:
26
+ raise RuntimeError("Set WUXIA_RAW_ROOT to the corpus' wuxia_corpus/data directory (segmented chapters and alignments).")
27
+ return Path(root)
28
+
29
+
30
  def llama_bin(name: str) -> str:
31
  """Return the path of a llama.cpp executable (e.g. 'llama-server')."""
32
  folder = os.environ.get("LLAMA_CPP_BIN")
pipeline/webnovel_mt/perturb.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Text transformations used to build the training and evaluation windows.
2
+
3
+ Training targets always use one convention (curly double quotes, nested curly single quotes, the opening mark repeated in
4
+ every paragraph of a quote that continues). The Chinese source is what varies: script (simplified or traditional),
5
+ quotation style (curly, corner brackets), indentation, and a quote that continues over several paragraphs. These helpers
6
+ produce those variations from clean aligned text, so the model sees every form with the same English answer.
7
+ """
8
+ import random
9
+ import re
10
+
11
+ CJK = "\u3000-\u303f\u4e00-\u9fff\uff00-\uffef“”‘’"
12
+ _SPACE = re.compile(rf"(?<=[{CJK}])[ \t\u3000]+|[ \t\u3000]+(?=[{CJK}])")
13
+ _OPENERS = "([{—-“‘"
14
+ CORNER = str.maketrans({"“": "「", "”": "」", "‘": "『", "’": "』"})
15
+ MIXED = str.maketrans({"‘": "『", "’": "』"})
16
+ ASCII = str.maketrans({"“": '"', "”": '"', "‘": "'", "’": "'"})
17
+ ZH_QUOTE = re.compile(r"“([^“”‘’]*)”")
18
+ EN_QUOTE = re.compile(r"“([^“”‘’]*)”")
19
+ ZH_SENTENCES = re.compile(r"[^。!?…]*[。!?…]+|[^。!?…]+$")
20
+ EN_SENTENCES = re.compile(r"(?<=[.!?…])\s+")
21
+ SCRIPTS = ("s2t", "s2tw", "s2hk")
22
+ _converters = {}
23
+
24
+
25
+ def clean_zh(text):
26
+ """Remove the stray spaces the corpus leaves between Chinese characters and around quotation marks."""
27
+ return _SPACE.sub("", text).strip()
28
+
29
+
30
+ def smart_quotes(text):
31
+ """Turn straight quotes and apostrophes into the curly forms used by the targets."""
32
+ out = []
33
+ for i, c in enumerate(text):
34
+ prev = text[i - 1] if i else " "
35
+ nxt = text[i + 1] if i + 1 < len(text) else " "
36
+ opening = i == 0 or prev.isspace() or prev in _OPENERS
37
+ if c == '"':
38
+ out.append("“" if opening else "”")
39
+ elif c == "'":
40
+ if prev.isalnum() and nxt.isalnum():
41
+ out.append("’")
42
+ else:
43
+ out.append("‘" if opening else "’")
44
+ else:
45
+ out.append(c)
46
+ return "".join(out)
47
+
48
+
49
+ def quotes_consistent(zh, en):
50
+ """True when both sides have balanced double quotes and the same number of them."""
51
+ return zh.count("“") == zh.count("”") == en.count("“") == en.count("”")
52
+
53
+
54
+ def to_script(text, name):
55
+ if name not in _converters:
56
+ from opencc import OpenCC # pip install opencc-python-reimplemented
57
+
58
+ _converters[name] = OpenCC(name)
59
+ return _converters[name].convert(text)
60
+
61
+
62
+ def to_quote_style(text, style):
63
+ """`style`: 'corner' (「」『』), 'mixed' (curly double, corner single), 'ascii' (straight) or 'curly' (unchanged)."""
64
+ table = {"corner": CORNER, "mixed": MIXED, "ascii": ASCII}.get(style)
65
+ return text.translate(table) if table else text
66
+
67
+
68
+ def indent(paragraphs):
69
+ return ["\u3000\u3000" + p for p in paragraphs]
70
+
71
+
72
+ def split_quote(zh, en, rng, repeat_opener):
73
+ """Split the one quote of an aligned paragraph over two paragraphs, at a sentence boundary both sides share.
74
+
75
+ Returns ((zh1, zh2), (en1, en2)) or None when the paragraph holds no single quote with the same number (2 to 8) of
76
+ sentences in both languages. The English second paragraph always repeats the opening mark; the Chinese one does only
77
+ when `repeat_opener` is set, since both habits occur in real texts.
78
+ """
79
+ z, e = ZH_QUOTE.search(zh), EN_QUOTE.search(en)
80
+ if not z or not e or zh.count("“") != 1 or en.count("“") != 1:
81
+ return None
82
+ zs = [s for s in ZH_SENTENCES.findall(z[1]) if s.strip()]
83
+ es = [s for s in EN_SENTENCES.split(e[1].strip()) if s.strip()]
84
+ if "".join(zs) != z[1] or len(zs) != len(es) or not 2 <= len(zs) <= 8:
85
+ return None
86
+ k = rng.randint(1, len(zs) - 1)
87
+ zh1 = zh[:z.start()] + "“" + "".join(zs[:k])
88
+ zh2 = ("“" if repeat_opener else "") + "".join(zs[k:]) + "”" + zh[z.end():]
89
+ en1 = en[:e.start()] + "“" + " ".join(es[:k])
90
+ en2 = "“" + " ".join(es[k:]) + "”" + en[e.end():]
91
+ return (zh1, zh2), (en1, en2)
92
+
93
+
94
+ def make_windows(blocks, rng, lo=60, hi=600):
95
+ """Group consecutive blocks into windows. Each window gets its own size cap, drawn log-uniformly in [lo, hi] Chinese
96
+ characters, so training sees everything from a single short line to several paragraphs. A block is never cut."""
97
+ out, i = [], 0
98
+ while i < len(blocks):
99
+ cap = int(lo * (hi / lo) ** rng.random())
100
+ win, size = [], 0
101
+ while i < len(blocks) and (not win or size + len(blocks[i]["zh"]) <= cap):
102
+ win.append(blocks[i])
103
+ size += len(blocks[i]["zh"])
104
+ i += 1
105
+ out.append(win)
106
+ return out
107
+
108
+
109
+ def perturb_window(paras, rng, p_script=0.25, p_style=0.30, p_split=0.30, p_indent=0.15, force=None):
110
+ """Perturb the paragraphs of one window. `paras` is a list of (zh, en) pairs. Returns (zh_paragraphs, en_paragraphs,
111
+ tags). `force` is a dict that overrides the random choices: script, style, split (bool), indent (bool)."""
112
+ force = force or {}
113
+ tags, out = [], []
114
+ do_split = force.get("split")
115
+ for zh, en in paras:
116
+ if do_split is None:
117
+ take = rng.random() < p_split
118
+ else:
119
+ take = do_split
120
+ res = split_quote(zh, en, rng, rng.random() < 0.4) if take else None
121
+ if res:
122
+ tags.append("split")
123
+ out += list(zip(*res))
124
+ else:
125
+ out.append((zh, en))
126
+ zh_p = [z for z, _ in out]
127
+ en_p = [e for _, e in out]
128
+ script = force.get("script", rng.choice(SCRIPTS) if rng.random() < p_script else None)
129
+ style = force.get("style", rng.choices(["corner", "mixed", "ascii"], [0.6, 0.25, 0.15])[0] if rng.random() < p_style else None)
130
+ if style:
131
+ zh_p = [to_quote_style(z, style) for z in zh_p]
132
+ tags.append(style)
133
+ if script:
134
+ zh_p = [to_script(z, script) for z in zh_p]
135
+ tags.append(script)
136
+ if force.get("indent", rng.random() < p_indent):
137
+ zh_p = indent(zh_p)
138
+ tags.append("indent")
139
+ return zh_p, en_p, tags
140
+
141
+
142
+ if __name__ == "__main__":
143
+ rng = random.Random(1)
144
+ zh = "他淡淡道:“我不会走。你们回去吧。天亮前,我自会去见他。”"
145
+ en = "He said calmly, “I will not leave. You may go back. Before dawn, I will see him myself.”"
146
+ print(perturb_window([(zh, en)], rng, force={"split": True, "script": "s2t", "style": "corner"}))
pipeline/webnovel_mt/translate.py CHANGED
@@ -15,7 +15,7 @@ import sys
15
  import urllib.request
16
  from concurrent.futures import ThreadPoolExecutor
17
 
18
- from webnovel_mt import docmt, glossary
19
 
20
 
21
  def translate_document(text, translate_prompts, size=250, use_glossary=True):
@@ -92,7 +92,10 @@ def main(argv=None):
92
  ap.add_argument("--url", default="http://127.0.0.1:8080", help="llama-server base URL")
93
  ap.add_argument("--model", help="merged model directory or HF repo id (hf backend)")
94
  ap.add_argument("--workers", type=int, default=4, help="parallel requests (llama-server backend)")
95
- ap.add_argument("--window", type=int, default=250, help="maximum characters per translated piece")
 
 
 
96
  ap.add_argument("--no-glossary", action="store_true", help="do not inject glossary entries")
97
  args = ap.parse_args(argv)
98
 
@@ -103,7 +106,11 @@ def main(argv=None):
103
  backend = hf_backend(args.model)
104
  else:
105
  backend = llama_server_backend(args.url, args.workers)
106
- result = translate_document(text, backend, size=args.window, use_glossary=not args.no_glossary)
 
 
 
 
107
  if args.output:
108
  with open(args.output, "w", encoding="utf-8") as f:
109
  f.write(result + "\n")
 
15
  import urllib.request
16
  from concurrent.futures import ThreadPoolExecutor
17
 
18
+ from webnovel_mt import docmt, glossary, windows
19
 
20
 
21
  def translate_document(text, translate_prompts, size=250, use_glossary=True):
 
92
  ap.add_argument("--url", default="http://127.0.0.1:8080", help="llama-server base URL")
93
  ap.add_argument("--model", help="merged model directory or HF repo id (hf backend)")
94
  ap.add_argument("--workers", type=int, default=4, help="parallel requests (llama-server backend)")
95
+ ap.add_argument("--pipeline", choices=["windows", "pieces"], default="windows",
96
+ help="windows: paragraph windows (the v1.0 model); pieces: 250-character pieces (the v0.1 model)")
97
+ ap.add_argument("--window", type=int, default=None,
98
+ help="maximum characters per window (default 400) or per piece (default 250)")
99
  ap.add_argument("--no-glossary", action="store_true", help="do not inject glossary entries")
100
  args = ap.parse_args(argv)
101
 
 
106
  backend = hf_backend(args.model)
107
  else:
108
  backend = llama_server_backend(args.url, args.workers)
109
+ if args.pipeline == "windows":
110
+ result = windows.translate_document_windows(text, backend, cap=args.window or 400,
111
+ use_glossary=not args.no_glossary)
112
+ else:
113
+ result = translate_document(text, backend, size=args.window or 250, use_glossary=not args.no_glossary)
114
  if args.output:
115
  with open(args.output, "w", encoding="utf-8") as f:
116
  f.write(result + "\n")
pipeline/webnovel_mt/windows.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Paragraph-window translation for the model trained on paragraph windows (scripts/prepare/build_dataset.py).
2
+
3
+ The model sees several paragraphs at once and writes the quotation marks itself. The pipeline only guarantees the shape of
4
+ the input:
5
+
6
+ * paragraphs are grouped into windows of up to `cap` Chinese characters (a longer paragraph is cut at sentence ends);
7
+ * a window that starts inside a quote the previous window left open gets the opening mark put back in front of its first
8
+ paragraph, so the model knows it is in a quote (the English convention repeats the mark in every paragraph);
9
+ * each answer is checked (same number of paragraphs, same net quotes, no Chinese left, no runaway repetition); a window
10
+ that fails is split in two and translated again, down to one paragraph.
11
+ """
12
+ import re
13
+
14
+ from webnovel_mt import docmt, glossary, perturb
15
+
16
+ OPEN, CLOSE = "“「", "”」"
17
+ CJK = re.compile(r"[\u4e00-\u9fff]")
18
+ MAX_CARRY = 6 # a quote still open after this many paragraphs is taken for a typo and forgotten
19
+ _t2s = []
20
+
21
+
22
+ def simplify(text):
23
+ """Traditional to simplified, for the glossary lookup only (the glossary is simplified). Identity without OpenCC."""
24
+ if not _t2s:
25
+ try:
26
+ from opencc import OpenCC
27
+
28
+ _t2s.append(OpenCC("t2s").convert)
29
+ except ImportError:
30
+ _t2s.append(lambda s: s)
31
+ return _t2s[0](text)
32
+
33
+
34
+ def net_open(text):
35
+ """Quotes a text leaves open (opening marks minus closing marks, never below zero)."""
36
+ depth, straight = 0, False
37
+ for c in text:
38
+ if c in OPEN:
39
+ depth += 1
40
+ elif c in CLOSE:
41
+ depth = max(0, depth - 1)
42
+ elif c == '"':
43
+ straight = not straight
44
+ depth = depth + 1 if straight else max(0, depth - 1)
45
+ return depth
46
+
47
+
48
+ def delta(text):
49
+ """Opening minus closing quote marks of a text (can be negative: a paragraph that only closes a quote)."""
50
+ return sum(c in OPEN for c in text) - sum(c in CLOSE for c in text)
51
+
52
+
53
+ def plan(text, cap=400):
54
+ """Split a document into lines, units (one paragraph or one piece of a long paragraph) and windows of unit indexes."""
55
+ lines = text.split("\n")
56
+ units = []
57
+ for i, line in enumerate(lines):
58
+ t = line.replace("\u3000", " ").strip()
59
+ if not t:
60
+ continue
61
+ parts = [t] if len(t) <= cap else docmt._split_long(t, cap)
62
+ units += [{"line": i, "text": p, "cont": k > 0, "inject": ""} for k, p in enumerate(parts)]
63
+ windows, cur, size = [], [], 0
64
+ for j, u in enumerate(units):
65
+ if cur and size + len(u["text"]) > cap:
66
+ windows.append(cur)
67
+ cur, size = [], 0
68
+ cur.append(j)
69
+ size += len(u["text"])
70
+ if cur:
71
+ windows.append(cur)
72
+ # put back the opening mark of a quote that was left open before a window starts, but only when the quote really
73
+ # goes on: the next mark in the text is its closer. If the next mark is an opener at the start of a paragraph the
74
+ # Chinese repeats the mark (as some classical novels do) and nothing is left open; if no closer follows soon, it is a typo.
75
+ opener = "「" if "「" in text else "“"
76
+ depth = 0
77
+ first = {w[0] for w in windows}
78
+ for j, u in enumerate(units):
79
+ if depth and not continues(units, j):
80
+ depth = 0
81
+ if depth and j in first:
82
+ u["inject"] = opener
83
+ depth = max(0, depth + delta(u["text"]))
84
+ return lines, units, windows
85
+
86
+
87
+ def continues(units, j):
88
+ """Whether a quote left open before unit `j` is closed by a mark found within MAX_CARRY paragraphs."""
89
+ nested, paragraphs = 0, 0
90
+ for k in range(j, len(units)):
91
+ u = units[k]
92
+ paragraphs += not u["cont"]
93
+ if paragraphs > MAX_CARRY:
94
+ return False
95
+ for pos, ch in enumerate(u["text"]):
96
+ if ch in OPEN:
97
+ if nested == 0 and pos == 0 and not u["cont"]:
98
+ return False
99
+ nested += 1
100
+ elif ch in CLOSE:
101
+ if nested == 0:
102
+ return True
103
+ nested -= 1
104
+ return False
105
+
106
+
107
+ def window_source(units, idx):
108
+ """Prompt text of a window: one line per source line (injected opening mark included)."""
109
+ by_line = {}
110
+ for j in idx:
111
+ u = units[j]
112
+ by_line.setdefault(u["line"], []).append(u["inject"] + u["text"])
113
+ return "\n".join(" ".join(parts) for parts in by_line.values()), len(by_line)
114
+
115
+
116
+ def count_open(text):
117
+ """Primary opening marks in a text (curly, corner or a pair of straight quotes)."""
118
+ return sum(c in OPEN for c in text) + text.count('"') // 2
119
+
120
+
121
+ def count_close(text):
122
+ return sum(c in CLOSE for c in text) + text.count('"') // 2
123
+
124
+
125
+ def repeated_openers(src):
126
+ """Paragraphs of a window that start inside a quote without an opening mark. The English repeats the mark there."""
127
+ depth, extra = 0, 0
128
+ for line in src.split("\n"):
129
+ if depth and line[:1] not in OPEN:
130
+ extra += 1
131
+ depth = max(0, depth + delta(line))
132
+ return extra
133
+
134
+
135
+ def valid(src, n_lines, out):
136
+ lines = [x for x in out.split("\n") if x.strip()]
137
+ if len(lines) != n_lines or CJK.search(out) or len(out) > 7 * len(src) + 40:
138
+ return False
139
+ out = perturb.smart_quotes(out)
140
+ # no quote may be dropped or invented: same closing marks, and the opening marks of the source, plus the ones the
141
+ # English repeats at the start of paragraphs that continue a quote (the model may or may not repeat them)
142
+ opens = count_open(out)
143
+ if count_close(out) != count_close(src) or not count_open(src) <= opens <= count_open(src) + repeated_openers(src):
144
+ return False
145
+ words = out.split()
146
+ grams = {}
147
+ for i in range(len(words) - 5):
148
+ g = tuple(words[i:i + 6])
149
+ grams[g] = grams.get(g, 0) + 1
150
+ return not grams or max(grams.values()) < 4
151
+
152
+
153
+ def translate_documents_windows(texts, translate_prompts, cap=400, use_glossary=True):
154
+ """Translate several documents paragraph by paragraph in windows. Every round sends the pending windows of all the
155
+ documents in one call, so batches stay full. `translate_prompts` maps a list of prompts to their translations."""
156
+ plans = [plan(t, cap) for t in texts]
157
+ outs = [{} for _ in texts] # per document: unit index -> English
158
+ pending = [(d, w) for d, (_, _, wins) in enumerate(plans) for w in wins]
159
+ while pending:
160
+ srcs = [window_source(plans[d][1], w) for d, w in pending]
161
+ if use_glossary:
162
+ prompts = [glossary.build_prompt(s, glossary.entries_for(simplify(s))) for s, _ in srcs]
163
+ else:
164
+ prompts = [glossary.PLAIN.format(src=s) for s, _ in srcs]
165
+ retry = []
166
+ for (d, w), (src, n_lines), res in zip(pending, srcs, translate_prompts(prompts)):
167
+ if valid(src, n_lines, res) or len(w) == 1:
168
+ paras = [x for x in res.split("\n") if x.strip()] or [res.strip()]
169
+ if len(paras) != len(w): # only possible for an accepted failure: keep the text in the first unit
170
+ paras = [" ".join(paras)] + [""] * (len(w) - 1)
171
+ outs[d].update(dict(zip(w, (x.strip() for x in paras))))
172
+ else:
173
+ half = len(w) // 2
174
+ retry += [(d, w[:half]), (d, w[half:])]
175
+ pending = retry
176
+ return [assemble(lines, units, out) for (lines, units, _), out in zip(plans, outs)]
177
+
178
+
179
+ def assemble(lines, units, out):
180
+ result = list(lines)
181
+ by_line = {}
182
+ for j, u in enumerate(units):
183
+ t = out.get(j, "")
184
+ if u["inject"] and u["cont"] and t[:1] in "“\"": # the mark was only added for the model, mid-paragraph
185
+ t = t[1:]
186
+ by_line.setdefault(u["line"], []).append(t)
187
+ for i, parts in by_line.items():
188
+ result[i] = " ".join(p for p in parts if p)
189
+ return "\n".join(drop_closers_of_continued_quotes(lines, result))
190
+
191
+
192
+ def drop_closers_of_continued_quotes(src_lines, out_lines):
193
+ """English leaves a quote open at the end of a paragraph whose speech goes on in the next one (the next paragraph
194
+ opens it again). The model sometimes closes it anyway: take that last closing mark away."""
195
+ out = list(out_lines)
196
+ for i in range(len(out) - 1):
197
+ s, o = src_lines[i].strip(), out[i].rstrip()
198
+ nxt = next((x.strip() for x in src_lines[i + 1:] if x.strip()), "")
199
+ if nxt and net_open(s) > 0 and nxt[0] in OPEN and o[-1:] in ("”", '"') and count_close(o) > count_close(s):
200
+ out[i] = o[:-1].rstrip()
201
+ return out
202
+
203
+
204
+ def translate_document_windows(text, translate_prompts, cap=400, use_glossary=True):
205
+ """Translate `text` paragraph by paragraph in windows (see translate_documents_windows)."""
206
+ return translate_documents_windows([text], translate_prompts, cap, use_glossary)[0]
results/metrics.json DELETED
@@ -1,291 +0,0 @@
1
- {
2
- "gemma": {
3
- "label": "Gemma 4 E2B (base)",
4
- "gen_seconds": 1894.9,
5
- "gen_tokens": 7667,
6
- "sentence": {
7
- "n": 150,
8
- "bleu": 12.0,
9
- "chrf": 40.3,
10
- "untranslated_cjk": 10
11
- },
12
- "paragraph": {
13
- "n": 20,
14
- "bleu": 10.0,
15
- "chrf": 44.7,
16
- "untranslated_cjk": 1
17
- }
18
- },
19
- "gloss_q4g": {
20
- "label": "Final, GGUF Q4_K_M, glossary prompt",
21
- "gen_seconds": 34.1,
22
- "gen_tokens": 7212,
23
- "sentence": {
24
- "n": 150,
25
- "bleu": 22.1,
26
- "chrf": 47.0,
27
- "untranslated_cjk": 0
28
- },
29
- "paragraph": {
30
- "n": 20,
31
- "bleu": 15.2,
32
- "chrf": 46.9,
33
- "untranslated_cjk": 0
34
- }
35
- },
36
- "gloss_q4p": {
37
- "label": "Final, GGUF Q4_K_M, plain prompt",
38
- "gen_seconds": 32.7,
39
- "gen_tokens": 7143,
40
- "sentence": {
41
- "n": 150,
42
- "bleu": 20.8,
43
- "chrf": 46.1,
44
- "untranslated_cjk": 0
45
- },
46
- "paragraph": {
47
- "n": 20,
48
- "bleu": 15.4,
49
- "chrf": 46.1,
50
- "untranslated_cjk": 0
51
- }
52
- },
53
- "hy": {
54
- "label": "Hy-MT2-1.8B (base)",
55
- "gen_seconds": 112.7,
56
- "gen_tokens": 8151,
57
- "sentence": {
58
- "n": 150,
59
- "bleu": 10.5,
60
- "chrf": 38.6,
61
- "untranslated_cjk": 1
62
- },
63
- "paragraph": {
64
- "n": 20,
65
- "bleu": 8.9,
66
- "chrf": 43.4,
67
- "untranslated_cjk": 0
68
- }
69
- },
70
- "hy_ft": {
71
- "label": "LoRA 5k sent + 1k para",
72
- "gen_seconds": 96.1,
73
- "gen_tokens": 7230,
74
- "sentence": {
75
- "n": 150,
76
- "bleu": 19.5,
77
- "chrf": 44.6,
78
- "untranslated_cjk": 1
79
- },
80
- "paragraph": {
81
- "n": 20,
82
- "bleu": 13.7,
83
- "chrf": 45.4,
84
- "untranslated_cjk": 0
85
- }
86
- },
87
- "hy_gloss_g": {
88
- "label": "Final, glossary prompt",
89
- "gen_seconds": 97.0,
90
- "gen_tokens": 7202,
91
- "sentence": {
92
- "n": 150,
93
- "bleu": 22.9,
94
- "chrf": 47.9,
95
- "untranslated_cjk": 0
96
- },
97
- "paragraph": {
98
- "n": 20,
99
- "bleu": 16.1,
100
- "chrf": 47.1,
101
- "untranslated_cjk": 0
102
- }
103
- },
104
- "hy_gloss_p": {
105
- "label": "Final (20k + 3k, glossary-trained), plain prompt",
106
- "gen_seconds": 96.9,
107
- "gen_tokens": 7206,
108
- "sentence": {
109
- "n": 150,
110
- "bleu": 21.5,
111
- "chrf": 46.4,
112
- "untranslated_cjk": 0
113
- },
114
- "paragraph": {
115
- "n": 20,
116
- "bleu": 15.7,
117
- "chrf": 47.0,
118
- "untranslated_cjk": 0
119
- }
120
- },
121
- "hy_p3k": {
122
- "label": "LoRA 5k sent + 3k para",
123
- "gen_seconds": 98.2,
124
- "gen_tokens": 7164,
125
- "sentence": {
126
- "n": 150,
127
- "bleu": 20.8,
128
- "chrf": 45.9,
129
- "untranslated_cjk": 0
130
- },
131
- "paragraph": {
132
- "n": 20,
133
- "bleu": 15.3,
134
- "chrf": 46.7,
135
- "untranslated_cjk": 0
136
- }
137
- },
138
- "hy_s10k": {
139
- "label": "LoRA 10k sent + 1k para",
140
- "gen_seconds": 108.6,
141
- "gen_tokens": 7136,
142
- "sentence": {
143
- "n": 150,
144
- "bleu": 21.5,
145
- "chrf": 46.4,
146
- "untranslated_cjk": 0
147
- },
148
- "paragraph": {
149
- "n": 20,
150
- "bleu": 15.1,
151
- "chrf": 45.7,
152
- "untranslated_cjk": 0
153
- }
154
- },
155
- "hy_s20k": {
156
- "label": "LoRA 20k sent + 1k para",
157
- "gen_seconds": 92.6,
158
- "gen_tokens": 7140,
159
- "sentence": {
160
- "n": 150,
161
- "bleu": 22.5,
162
- "chrf": 47.2,
163
- "untranslated_cjk": 0
164
- },
165
- "paragraph": {
166
- "n": 20,
167
- "bleu": 14.8,
168
- "chrf": 45.9,
169
- "untranslated_cjk": 0
170
- }
171
- },
172
- "hy_s20k_g": {
173
- "label": "LoRA 20k + 1k, glossary prompt",
174
- "gen_seconds": 101.5,
175
- "gen_tokens": 7167,
176
- "sentence": {
177
- "n": 150,
178
- "bleu": 22.6,
179
- "chrf": 46.9,
180
- "untranslated_cjk": 0
181
- },
182
- "paragraph": {
183
- "n": 20,
184
- "bleu": 15.0,
185
- "chrf": 46.1,
186
- "untranslated_cjk": 0
187
- }
188
- },
189
- "hy_s2k": {
190
- "label": "LoRA 2k sent + 1k para",
191
- "gen_seconds": 100.4,
192
- "gen_tokens": 7240,
193
- "sentence": {
194
- "n": 150,
195
- "bleu": 18.0,
196
- "chrf": 43.3,
197
- "untranslated_cjk": 0
198
- },
199
- "paragraph": {
200
- "n": 20,
201
- "bleu": 12.6,
202
- "chrf": 45.0,
203
- "untranslated_cjk": 0
204
- }
205
- },
206
- "index": {
207
- "label": "Index-Translate-2B (base)",
208
- "gen_seconds": 108.3,
209
- "gen_tokens": 8186,
210
- "sentence": {
211
- "n": 150,
212
- "bleu": 10.6,
213
- "chrf": 41.0,
214
- "untranslated_cjk": 3
215
- },
216
- "paragraph": {
217
- "n": 20,
218
- "bleu": 10.5,
219
- "chrf": 45.2,
220
- "untranslated_cjk": 1
221
- }
222
- },
223
- "q_f16": {
224
- "label": "GGUF F16 (5k + 1k model)",
225
- "gen_seconds": 94.7,
226
- "gen_tokens": 7239,
227
- "sentence": {
228
- "n": 150,
229
- "bleu": 19.1,
230
- "chrf": 44.2,
231
- "untranslated_cjk": 1
232
- },
233
- "paragraph": {
234
- "n": 20,
235
- "bleu": 13.9,
236
- "chrf": 45.6,
237
- "untranslated_cjk": 0
238
- }
239
- },
240
- "q_Q4_K_M": {
241
- "label": "GGUF Q4_K_M (5k + 1k model)",
242
- "gen_seconds": 35.1,
243
- "gen_tokens": 7154,
244
- "sentence": {
245
- "n": 150,
246
- "bleu": 19.0,
247
- "chrf": 44.1,
248
- "untranslated_cjk": 0
249
- },
250
- "paragraph": {
251
- "n": 20,
252
- "bleu": 12.8,
253
- "chrf": 45.2,
254
- "untranslated_cjk": 0
255
- }
256
- },
257
- "q_Q8_0": {
258
- "label": "GGUF Q8_0 (5k + 1k model)",
259
- "gen_seconds": 41.8,
260
- "gen_tokens": 7251,
261
- "sentence": {
262
- "n": 150,
263
- "bleu": 19.2,
264
- "chrf": 44.2,
265
- "untranslated_cjk": 1
266
- },
267
- "paragraph": {
268
- "n": 20,
269
- "bleu": 14.3,
270
- "chrf": 46.1,
271
- "untranslated_cjk": 0
272
- }
273
- },
274
- "qwen": {
275
- "label": "Qwen3.5-2B (base)",
276
- "gen_seconds": 111.3,
277
- "gen_tokens": 7855,
278
- "sentence": {
279
- "n": 150,
280
- "bleu": 9.2,
281
- "chrf": 36.3,
282
- "untranslated_cjk": 10
283
- },
284
- "paragraph": {
285
- "n": 20,
286
- "bleu": 7.9,
287
- "chrf": 41.8,
288
- "untranslated_cjk": 3
289
- }
290
- }
291
- }