Spaces:
Running
Running
feat(sentence): giu dong trong - token_chunker.py
Browse files- src/token_chunker.py +33 -0
src/token_chunker.py
CHANGED
|
@@ -107,6 +107,39 @@ def sentence_chunks(
|
|
| 107 |
return chunks
|
| 108 |
|
| 109 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
def split_for_translation(
|
| 111 |
tokenizer: PreTrainedTokenizerBase,
|
| 112 |
text: str,
|
|
|
|
| 107 |
return chunks
|
| 108 |
|
| 109 |
|
| 110 |
+
def _layout_lines(text: str) -> list[str]:
|
| 111 |
+
"""Tách dòng GIỮ dòng rỗng đầu/cuối, chuẩn hóa newline (cho plan-based)."""
|
| 112 |
+
return (text or "").replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def split_sentence_lines_with_plan(
|
| 116 |
+
tokenizer: PreTrainedTokenizerBase,
|
| 117 |
+
text: str,
|
| 118 |
+
*,
|
| 119 |
+
max_tokens: int,
|
| 120 |
+
) -> tuple[list[str], list[list[int] | None]]:
|
| 121 |
+
"""Chia "Theo câu" KÈM plan ánh xạ dòng-nguồn → chunk-index.
|
| 122 |
+
|
| 123 |
+
Trả `(chunks, plan)` với `plan` theo TỪNG dòng nguồn (giữ cả dòng trống):
|
| 124 |
+
`None` nếu dòng trống, hoặc danh sách index các chunk thuộc dòng đó (một dòng
|
| 125 |
+
dài vượt cap có thể tách thành nhiều chunk → nhiều index). Cho phép ghép lại
|
| 126 |
+
output theo đúng bố cục dòng nguồn (giữ dòng trống), điều mà `split_for_
|
| 127 |
+
translation` thường (trả phẳng list[str]) không làm được.
|
| 128 |
+
"""
|
| 129 |
+
chunks: list[str] = []
|
| 130 |
+
plan: list[list[int] | None] = []
|
| 131 |
+
for line in _layout_lines(text):
|
| 132 |
+
stripped = line.strip()
|
| 133 |
+
if not stripped:
|
| 134 |
+
plan.append(None)
|
| 135 |
+
continue
|
| 136 |
+
line_chunks = sentence_chunks(tokenizer, stripped, max_tokens=max_tokens)
|
| 137 |
+
indices = list(range(len(chunks), len(chunks) + len(line_chunks)))
|
| 138 |
+
chunks.extend(line_chunks)
|
| 139 |
+
plan.append(indices)
|
| 140 |
+
return chunks, plan
|
| 141 |
+
|
| 142 |
+
|
| 143 |
def split_for_translation(
|
| 144 |
tokenizer: PreTrainedTokenizerBase,
|
| 145 |
text: str,
|