File size: 10,577 Bytes
f66643d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import json
import re
from pathlib import Path
from unittest.mock import AsyncMock, patch

from pdf2zh.json_translator import (
    Gateway,
    TranslatorConfig,
    collect_translatables,
    glossary_block_for_chunk,
    is_equation_only,
    is_plain_text,
    segments_to_chunks,
    translate_document,
)

FIXTURE = Path(__file__).parent / "fixtures" / "mini_output.json"


def load_fixture() -> dict:
    return json.loads(FIXTURE.read_text(encoding="utf-8"))


def _mock_cfg() -> TranslatorConfig:
    return TranslatorConfig(
        source_language="English",
        target_language="Vietnamese",
        provider="openrouter",
        api_key="test-key",
        base_url="https://openrouter.ai/api/v1",
        model="google/gemini-2.5-flash-lite",
        concurrent=5,
        chunk_bytes=3000,
        glossary_enabled=False,
        retry=0,
        timeout=10,
    )


def _echo_translations(system: str, user: str, *, force_json: bool = False) -> str:
    """Side-effect for AsyncMock: echoes back each source text as <TR:source>."""
    match = re.search(r"```json\n(.*?)\n```", user, re.DOTALL)
    if not match:
        return "[]"
    chunk = json.loads(match.group(1))
    result = [{"id": k, "t": f"<TR:{v}>"} for k, v in chunk.items()]
    return json.dumps(result)


# ── 1. is_plain_text ────────────────────────────────────────────────────────────


def test_is_plain_text():
    assert is_plain_text("when a = b") is True
    assert is_plain_text("Introduction to Machine Learning") is True
    assert is_plain_text("a = b") is False  # no run of β‰₯2 letters
    assert is_plain_text("42.5") is False
    assert is_plain_text("<math>x</math>") is False
    assert is_plain_text("<math>x</math> where x is the count") is True
    assert is_plain_text("") is False


# ── 2. is_equation_only ─────────────────────────────────────────────────────────


def test_is_equation_only():
    assert is_equation_only("<math>P(x)</math> (1.1)") is True
    assert is_equation_only("<math>P(x)</math>") is True
    assert is_equation_only("<math>P(x)</math> where P is") is False
    assert is_equation_only("Some plain text") is False
    assert is_equation_only("") is True  # empty β†’ only whitespace after strip


# ── 3. segments_to_chunks ───────────────────────────────────────────────────────


def test_chunking():
    doc = load_fixture()
    tasks = collect_translatables(doc)
    chunks = segments_to_chunks(tasks, max_bytes=200)

    # Every task id appears in exactly one chunk
    all_ids_in_chunks: list[str] = []
    for chunk in chunks:
        all_ids_in_chunks.extend(chunk.keys())
    assert sorted(all_ids_in_chunks) == sorted(t.id for t in tasks)

    # No chunk exceeds budget (unless a single segment is oversized on its own)
    for chunk in chunks:
        if len(chunk) > 1:
            size = len(json.dumps(chunk, ensure_ascii=False).encode())
            assert size <= 200

    # IDs are stringified indices starting from "0"
    expected_ids = [str(i) for i in range(len(tasks))]
    assert all_ids_in_chunks == expected_ids


# ── 4. collect_translatables ─────────────────────────────────────────────────────


def test_collect_translatables_on_sample():
    doc = load_fixture()
    doc["pages"][0]["elements"][5]["cells"][3]["translated_text"] = "keep original"
    tasks = collect_translatables(doc)

    ids = [t.id for t in tasks]
    write_keys = [t.write_key for t in tasks]
    texts = [t.text for t in tasks]

    # Expected: 7 tasks
    # id=0: source_text of SectionHeader
    # id=1: source_text of Text element
    # id=2: source_text of Caption (BYPASS picture skipped, equation-only skipped)
    # id=3: latex of Caption ("Result table")
    # id=4: cells[0].source_text of Table ("Accuracy")
    # id=5: cells[2].source_text of Table ("Precision")
    #       (TABLE elem.source_text skipped; "42.5" + "" cells filtered)
    # id=6: source_text of page 1 Text
    assert len(tasks) == 7
    assert ids == ["0", "1", "2", "3", "4", "5", "6"]

    assert texts[0] == "Introduction to Machine Learning"
    assert write_keys[0] == "translated_text"

    assert texts[2] == "Table showing experimental results"
    assert write_keys[2] == "translated_text"

    assert texts[3] == "Result table"
    assert write_keys[3] == "translated_latex"

    assert texts[4] == "Accuracy"
    assert write_keys[4] == "translated_text"

    assert texts[5] == "Precision"
    assert write_keys[5] == "translated_text"

    assert texts[6] == "CeADAR is a research center located in Dublin Ireland."
    assert write_keys[6] == "translated_text"

    # BYPASS element source_text not included
    assert not any(t.text == "" for t in tasks)
    # Equation-only not included
    assert not any("<math>P(x)" in t.text for t in tasks)
    # "42.5" not included (is_plain_text β†’ False)
    assert not any(t.text == "42.5" for t in tasks)
    # TABLE elem.source_text (the joined " | " string) not translated directly
    assert not any(t.text == "Accuracy | 42.5 | Precision" for t in tasks)
    assert not any(t.text == "keep original" for t in tasks)


# ── 5. end-to-end with mocked Gateway.call ──────────────────────────────────────


def test_translate_document_end_to_end_mocked():
    doc = load_fixture()
    doc["pages"][0]["elements"][5]["cells"][3]["translated_text"] = "keep original"
    cfg = _mock_cfg()

    mock_call = AsyncMock(side_effect=_echo_translations)
    with patch.object(Gateway, "call", mock_call):
        out = translate_document(doc, cfg)

    pages = out["pages"]
    elems0 = pages[0]["elements"]
    elems1 = pages[1]["elements"]

    # Eligible source_text fields are translated
    assert elems0[0]["translated_text"] == "<TR:Introduction to Machine Learning>"
    assert (
        elems0[1]["translated_text"]
        == "<TR:This is a sample paragraph with enough text to be translatable.>"
    )
    assert elems0[4]["translated_text"] == "<TR:Table showing experimental results>"
    assert (
        elems1[0]["translated_text"]
        == "<TR:CeADAR is a research center located in Dublin Ireland.>"
    )

    # translated_latex added as new sibling
    assert elems0[4]["translated_latex"] == "<TR:Result table>"
    # Original latex unchanged
    assert elems0[4]["latex"] == "Result table"

    # TABLE element: cells get translated, elem.translated_text stays empty
    table = elems0[5]
    assert table["category"] == "TABLE"
    assert table["translated_text"] == ""
    assert table["cells"][0]["translated_text"] == "<TR:Accuracy>"
    assert table["cells"][0]["source_text"] == "Accuracy"
    assert table["cells"][1]["translated_text"] == ""  # "42.5" β€” not plain text
    assert table["cells"][2]["translated_text"] == "<TR:Precision>"
    assert table["cells"][3]["translated_text"] == "keep original"

    # BYPASS element unchanged
    bypass = elems0[2]
    assert bypass["category"] == "BYPASS"
    assert bypass["translated_text"] == ""

    # Equation-only element: translated_text not overwritten from ""
    eq = elems0[3]
    assert eq["translated_text"] == ""

    # Structural fields preserved verbatim
    assert out["pdf_path"] == "test.pdf"
    assert elems0[0]["bbox_pdf"] == [72, 720, 540, 740]
    assert elems0[0]["label"] == "SectionHeader"


# ── 6. length violation retry ────────────────────────────────────────────────────


def test_length_violation_retry():
    cfg = _mock_cfg()
    cfg.chunk_bytes = 10000
    cfg.length_tolerance = 0.15

    source = "This is a long enough source string for length checking"
    too_long = (
        source + " extra extra extra extra extra extra extra extra extra extra extra"
    )
    correct = "ĐÒy lΓ  mα»™t chuα»—i nguα»“n Δ‘α»§ dΓ i để kiểm tra Δ‘α»™ dΓ i"

    call_count = 0

    async def _side_effect(system: str, user: str, *, force_json: bool = False) -> str:
        nonlocal call_count
        call_count += 1
        match = re.search(r"```json\n(.*?)\n```", user, re.DOTALL)
        if not match:
            return "[]"
        chunk = json.loads(match.group(1))
        ids = list(chunk.keys())
        # First call returns over-long; subsequent calls return correct
        t = too_long if call_count == 1 else correct
        return json.dumps([{"id": k, "t": t} for k in ids])

    doc = {
        "source_language": "English",
        "target_language": "Vietnamese",
        "pdf_path": "t.pdf",
        "pages": [
            {
                "page_index": 0,
                "page_width": 612,
                "page_height": 792,
                "elements": [
                    {
                        "label": "Text",
                        "category": "TEXT",
                        "bbox_pdf": [0, 0, 100, 10],
                        "source_text": source,
                        "translated_text": "",
                        "latex": "",
                        "cells": [],
                    }
                ],
            }
        ],
    }

    mock_call = AsyncMock(side_effect=_side_effect)
    with patch.object(Gateway, "call", mock_call):
        out = translate_document(doc, cfg)

    assert out["pages"][0]["elements"][0]["translated_text"] == correct
    # 1 initial call + 1 length-violation retry
    assert call_count == 2


# ── 7. glossary injection ────────────────────────────────────────────────────────


def test_glossary_injection():
    glossary = {"ceadar": "CEADAR"}

    chunk_with = {"5": "CeADAR is a research center located in Dublin Ireland."}
    chunk_without = {"0": "Introduction to Machine Learning"}

    block_with = glossary_block_for_chunk(chunk_with, glossary)
    block_without = glossary_block_for_chunk(chunk_without, glossary)

    assert "ceadar" in block_with.lower()
    assert "CEADAR" in block_with
    assert block_without == ""