ngocdang83 commited on
Commit
2894b2a
·
verified ·
1 Parent(s): 884ebd7

feat(chunk): paragraph mode giu xuong dong - line_restore.py

Browse files
Files changed (1) hide show
  1. src/line_restore.py +229 -0
src/line_restore.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Khôi phục xuống dòng cho chế độ dịch "Theo đoạn".
2
+
3
+ Khi gom nhiều dòng gốc thành 1 chunk để model có thêm ngữ cảnh, Marian/CT2
4
+ nuốt ký tự xuống dòng → output thành một khối liền. Module này phân bổ lại bản
5
+ dịch về ĐÚNG số dòng gốc theo tỉ lệ (số câu / số ký tự), giữ nguyên bố cục dòng.
6
+
7
+ Thuật toán port từ Space đã chạy thật `DanVP/MoxhiMT-30-demo` (chế độ "Per chunk"):
8
+ chain heading-aware → sentence-proportional → char-proportional (fallback), mỗi
9
+ bước trả về đúng `len(source_lines)` dòng để ghép 1:1 với dòng gốc.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import re
15
+
16
+ # Câu tiếng Việt: nuốt tới dấu kết câu (kèm dấu đóng ngoặc kép) hoặc hết chuỗi.
17
+ VI_SENTENCE_RE = re.compile(r".+?(?:[.!?…]+[”’\"']*|$)", re.S)
18
+ # Ký tự được coi là ranh giới ngắt hợp lệ khi canh theo ký tự.
19
+ VI_BREAK_CHARS = set(".!?…。!?;;,:,、”’\"'")
20
+ # Dòng tiêu đề chương: "第N章/节/回/卷/部/篇".
21
+ HEADING_RE = re.compile(r"^第[0-9零〇一二三四五六七八九十百千万两]+[章节回卷部篇]")
22
+
23
+
24
+ def is_heading_line(line: str) -> bool:
25
+ """Dòng tiêu đề chương ngắn (giữ riêng 1 dòng, không gộp vào đoạn)."""
26
+ stripped = (line or "").strip()
27
+ if not stripped or "\n" in stripped:
28
+ return False
29
+ if len(stripped) > 24:
30
+ return False
31
+ if re.search(r"[。!?!?;;,,::\"“”]", stripped):
32
+ return False
33
+ return bool(HEADING_RE.match(stripped))
34
+
35
+
36
+ def split_vi_sentences(text: str) -> list[str]:
37
+ """Tách bản dịch tiếng Việt thành danh sách câu (gọn khoảng trắng)."""
38
+ units = [
39
+ re.sub(r"\s+", " ", m.group(0)).strip()
40
+ for m in VI_SENTENCE_RE.finditer(text or "")
41
+ ]
42
+ return [u for u in units if u]
43
+
44
+
45
+ def restore_line_breaks_by_sentences(
46
+ source_text: str, target_text: str
47
+ ) -> tuple[str | None, str]:
48
+ """Phân bổ câu bản dịch về các dòng gốc theo tỉ lệ độ dài ký tự nguồn.
49
+
50
+ Trả (None, lý do) khi số câu đích < số dòng gốc (không đủ để chia) → caller
51
+ rơi sang canh-theo-ký-tự.
52
+ """
53
+ source_lines = source_text.splitlines()
54
+ nonblank = [line.strip() for line in source_lines if line.strip()]
55
+ if len(nonblank) <= 1:
56
+ return target_text.strip(), "single-line"
57
+
58
+ target_units = split_vi_sentences(target_text)
59
+ if len(target_units) < len(nonblank):
60
+ return None, "too-few-target-sentences"
61
+
62
+ total_source_chars = max(sum(len(line) for line in nonblank), 1)
63
+ total_target_units = len(target_units)
64
+ remaining_lines = len(nonblank)
65
+ source_seen = 0
66
+ target_cursor = 0
67
+ restored: list[str] = []
68
+
69
+ for line in source_lines:
70
+ stripped = line.strip()
71
+ if not stripped:
72
+ restored.append("")
73
+ continue
74
+
75
+ source_seen += len(stripped)
76
+ remaining_lines -= 1
77
+ ideal_end = round(source_seen / total_source_chars * total_target_units)
78
+ min_end = target_cursor + 1
79
+ max_end = total_target_units - remaining_lines
80
+ end = min(max(ideal_end, min_end), max_end)
81
+ restored.append(" ".join(target_units[target_cursor:end]).strip())
82
+ target_cursor = end
83
+
84
+ if target_cursor < total_target_units:
85
+ for i in range(len(restored) - 1, -1, -1):
86
+ if restored[i].strip():
87
+ restored[i] = (
88
+ restored[i] + " " + " ".join(target_units[target_cursor:])
89
+ ).strip()
90
+ break
91
+ return "\n".join(restored).strip(), "sentence-proportional"
92
+
93
+
94
+ def find_nearest_break(text: str, desired: int, min_pos: int, max_pos: int) -> int:
95
+ """Tìm vị trí ngắt gần `desired` nhất rơi vào ranh giới câu/khoảng trắng."""
96
+ desired = min(max(desired, min_pos), max_pos)
97
+ window_start = max(min_pos, desired - 80)
98
+ window_end = min(max_pos, desired + 80)
99
+ best_idx, best_score = desired, float("inf")
100
+
101
+ for idx in range(window_start, window_end + 1):
102
+ prev = text[idx - 1] if idx > 0 else ""
103
+ cur = text[idx] if idx < len(text) else ""
104
+ if prev in VI_BREAK_CHARS or cur.isspace():
105
+ score = abs(idx - desired)
106
+ if prev in ".!?…。!?":
107
+ score -= 8
108
+ if score < best_score:
109
+ best_idx, best_score = idx, score
110
+ return best_idx
111
+
112
+
113
+ def restore_line_breaks_by_chars(
114
+ source_text: str, target_text: str
115
+ ) -> tuple[str, str]:
116
+ """Fallback: chia bản dịch theo tỉ lệ ký tự, ngắt tại ranh giới gần nhất."""
117
+ source_lines = source_text.splitlines()
118
+ nonblank = [line.strip() for line in source_lines if line.strip()]
119
+ if len(nonblank) <= 1:
120
+ return target_text.strip(), "single-line"
121
+
122
+ compact_target = re.sub(r"\s+", " ", target_text or "").strip()
123
+ if not compact_target:
124
+ return "", "char-proportional"
125
+ total_source_chars = max(sum(len(line) for line in nonblank), 1)
126
+ target_len = len(compact_target)
127
+ source_seen = 0
128
+ last_pos = 0
129
+ parts: list[str] = []
130
+
131
+ for line in nonblank[:-1]:
132
+ source_seen += len(line)
133
+ desired = round(source_seen / total_source_chars * target_len)
134
+ remaining_parts = len(nonblank) - len(parts) - 1
135
+ min_pos = min(last_pos + 1, target_len)
136
+ max_pos = min(target_len, max(min_pos, target_len - remaining_parts))
137
+ pos = find_nearest_break(compact_target, desired, min_pos, max_pos)
138
+ parts.append(compact_target[last_pos:pos].strip())
139
+ last_pos = pos
140
+ parts.append(compact_target[last_pos:].strip())
141
+
142
+ restored: list[str] = []
143
+ part_cursor = 0
144
+ for line in source_lines:
145
+ if line.strip():
146
+ restored.append(parts[part_cursor] if part_cursor < len(parts) else "")
147
+ part_cursor += 1
148
+ else:
149
+ restored.append("")
150
+ return "\n".join(restored).strip(), "char-proportional"
151
+
152
+
153
+ def assemble_paragraph_output(
154
+ source_text: str,
155
+ chunks: list[str],
156
+ translations: list[str],
157
+ ) -> tuple[list[tuple[int, str, str]], str]:
158
+ """Ghép kết quả chế độ "Theo đoạn" rồi khôi phục bố cục dòng.
159
+
160
+ Trả `(rows, full_text)` trong đó `full_text` có ĐÚNG số dòng (kể cả dòng
161
+ trống) như văn bản nguồn, và `rows` ghép 1:1 từng dòng-gốc-không-rỗng với
162
+ dòng-dịch tương ứng (để bảng đối chiếu khớp với bản tải về).
163
+
164
+ Quy trình khớp Space `translate_per_chunk`: nối các chunk dịch (tiêu đề chèn
165
+ \\n để tách riêng), gọn khoảng trắng, rồi `restore_line_breaks`.
166
+ """
167
+ parts: list[str] = []
168
+ for source_chunk, translated_chunk in zip(chunks, translations):
169
+ translated_chunk = (translated_chunk or "").strip()
170
+ if not translated_chunk:
171
+ continue
172
+ if is_heading_line(source_chunk):
173
+ parts.append(f"\n{translated_chunk}\n")
174
+ else:
175
+ parts.append(translated_chunk)
176
+ raw_output = " ".join(parts)
177
+ raw_output = re.sub(r"[ \t]+", " ", raw_output)
178
+ raw_output = re.sub(r" *\n *", "\n", raw_output).strip()
179
+
180
+ full_text, _mode = restore_line_breaks(source_text, raw_output)
181
+
182
+ # rows: ghép từng dòng gốc không rỗng với dòng dịch cùng vị trí.
183
+ source_nonblank = [line.strip() for line in source_text.splitlines() if line.strip()]
184
+ target_nonblank = [line.strip() for line in full_text.splitlines() if line.strip()]
185
+ rows: list[tuple[int, str, str]] = []
186
+ for index, source_line in enumerate(source_nonblank, start=1):
187
+ translated = target_nonblank[index - 1] if index - 1 < len(target_nonblank) else ""
188
+ rows.append((index, source_line, translated))
189
+ return rows, full_text
190
+
191
+
192
+ def restore_line_breaks(source_text: str, target_text: str) -> tuple[str, str]:
193
+ """Khôi phục bố cục dòng của bản dịch khớp với văn bản nguồn.
194
+
195
+ Orchestrator: nếu dòng đầu là tiêu đề chương thì tách riêng nó rồi xử lý phần
196
+ thân; còn lại thử canh-theo-câu trước, không được thì canh-theo-ký-tự. Luôn
197
+ trả về chuỗi có đúng bố cục dòng (kể cả dòng trống) của nguồn.
198
+ """
199
+ source_lines = source_text.splitlines()
200
+ first_nonblank = next(
201
+ (i for i, line in enumerate(source_lines) if line.strip()), None
202
+ )
203
+ target_lines = [line.strip() for line in (target_text or "").splitlines()]
204
+ target_lines = [line for line in target_lines if line]
205
+
206
+ if (
207
+ first_nonblank is not None
208
+ and len(target_lines) > 1
209
+ and is_heading_line(source_lines[first_nonblank])
210
+ ):
211
+ body_start = first_nonblank + 1
212
+ blank_after_heading = 0
213
+ while body_start < len(source_lines) and not source_lines[body_start].strip():
214
+ blank_after_heading += 1
215
+ body_start += 1
216
+ body_source = "\n".join(source_lines[body_start:])
217
+ body_target = "\n".join(target_lines[1:])
218
+ restored_body, body_mode = restore_line_breaks(body_source, body_target)
219
+ restored = [""] * first_nonblank
220
+ restored.append(target_lines[0])
221
+ restored.extend([""] * blank_after_heading)
222
+ if restored_body:
223
+ restored.append(restored_body)
224
+ return "\n".join(restored).strip(), f"heading+{body_mode}"
225
+
226
+ restored, mode = restore_line_breaks_by_sentences(source_text, target_text)
227
+ if restored is not None:
228
+ return restored, mode
229
+ return restore_line_breaks_by_chars(source_text, target_text)