File size: 6,227 Bytes
0bf2389
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from copy import deepcopy
import unittest

from barbet_bgd.taiwan_usage import (
    audit_taiwan_usage, iter_taiwan_usage_audits, TaiwanUsageAccumulator,
)


def example(text="請使用軟體與伺服器,款項為新臺幣 1,280 元。"):
    return {
        "record_id": "usage-test", "primitive": "EDIT",
        "task_spec": {"instruction": "依據來源修正錯誤。", "query": "保留正確內容。"},
        "inputs": [{"id": "ref", "type": "reference_text", "units": [
            {"id": "ref:u1", "text": text}]}],
        "target": {"output_text": text, "action": {"tool": "EDIT", "arguments": {}}},
    }


class TaiwanUsageTests(unittest.TestCase):
    def test_native_terms_variants_names_codes_and_schema_are_allowed(self):
        row = example("台北市里長林台生透過 API 查詢軟體版本 v2.3.1,並以 JSON Schema 驗證資料。")
        row["inputs"][0]["units"][0]["code"] = "打印機.load(\"软件\")"
        row["task_spec"]["requested_schema"] = {"properties": {"软件": {"type": "string"}}}
        self.assertTrue(audit_taiwan_usage(row)["passed"])

    def test_unconverted_simplified_and_converted_mainland_terms_fail(self):
        for text, rule in [("请開啟檔案。", "SIMPLIFIED_FORM"), ("請登入服務器。", "TAIWAN_PREFERRED_TERM")]:
            with self.subTest(text=text):
                result = audit_taiwan_usage(example(text))
                self.assertFalse(result["passed"])
                self.assertIn(rule, {item["rule_id"] for item in result["findings"]})

    def test_query_constraints_and_nested_target_values_are_scanned(self):
        row = example()
        row["task_spec"]["query"] = "請掃描二維碼。"
        row["task_spec"]["constraints"] = {"desired_text": "開啟數據庫。"}
        row["target"]["fields"] = [{"value": "默認值"}]
        paths = {finding["path"] for finding in audit_taiwan_usage(row)["findings"]}
        self.assertIn("task_spec.query", paths)
        self.assertIn("task_spec.constraints.desired_text", paths)
        self.assertIn("target.fields[0].value", paths)

    def test_inline_code_mask_retains_exact_prose_offsets(self):
        text = "呼叫 `软件.load()` 後使用服務器。"
        result = audit_taiwan_usage(example(text))
        self.assertEqual({f["matched"] for f in result["findings"]}, {"服務器"})
        for finding in result["findings"]:
            start, end = finding["character_span"]
            self.assertEqual(text[start:end], finding["matched"])

    def test_candidate_is_audited_but_not_treated_as_positive_target(self):
        row = example()
        row["inputs"].append({"id": "hyp", "type": "asr_hypothesis", "units": [
            {"id": "hyp:u1", "text": "请使用软件。"}]})
        result = audit_taiwan_usage(row)
        self.assertTrue(result["passed"])
        self.assertGreater(result["exempt_count"], 0)
        row["target"]["output_text"] = "请使用软件。"
        self.assertFalse(audit_taiwan_usage(row)["passed"])

    def test_selected_candidate_never_inherits_negative_exemption(self):
        for primitive in ("MATCH", "RANK"):
            row = example()
            row["primitive"] = primitive
            row["inputs"].append({"id": "candidates", "type": "entity_candidates", "units": [
                {"id": "cand:a", "text": "服務器"}]})
            row["target"].update({"canonical_id": "cand:a", "ranking": ["cand:a"]})
            self.assertFalse(audit_taiwan_usage(row)["passed"])

    def test_faithful_copy_exemption_requires_exact_reconstruction(self):
        row = example("原文件寫著:请登入服務器。")
        row["primitive"] = "COPY"
        row["target"]["action"] = {"tool": "COPY", "arguments": {"source_units": ["ref:u1"]}}
        result = audit_taiwan_usage(row)
        self.assertTrue(result["passed"])
        self.assertGreater(result["exempt_count"], 0)
        row["target"]["output_text"] += "附註"
        self.assertFalse(audit_taiwan_usage(row)["passed"])

    def test_accept_action_checks_accepted_candidate_as_positive(self):
        row = example()
        row["inputs"].append({"id": "hyp", "type": "asr_hypothesis", "units": [
            {"id": "hyp:u1", "text": "服務器"}]})
        row["target"]["action"] = {"tool": "ACCEPT", "arguments": {"candidate_id": "hyp"}}
        self.assertFalse(audit_taiwan_usage(row)["passed"])

    def test_known_generator_naturalness_defects_are_rejected(self):
        for text in (
            "計畫將於2028 年 2 月 10 日伺服器。",
            "金額:2028 年 2 月 10 日。",
            "版本為第二點三點一。",
            "日期為2027 年 2 月 29 日。",
        ):
            with self.subTest(text=text):
                self.assertEqual(audit_taiwan_usage(example(text))["decision"], "REJECT")
        self.assertTrue(audit_taiwan_usage(example("日期為2028 年 2 月 29 日。"))["passed"])

    def test_synthetic_error_labels_are_not_excused_as_negative_examples(self):
        row = example()
        row["inputs"].append({"type": "ocr_candidates", "units": [
            {"id": "cand:a", "text": "金額:不符-amount-2-93。"}]})
        result = audit_taiwan_usage(row)
        self.assertEqual(result["decision"], "REJECT")

    def test_english_technical_prose_review_is_narrow(self):
        self.assertEqual(audit_taiwan_usage(example("請比對同一位 pseudo speaker。"))["decision"], "REVIEW")
        self.assertTrue(audit_taiwan_usage(example("GPU 使用率為 92.5%,保留 token ID。"))["passed"])

    def test_streaming_bounded_accumulator_does_not_modify_records(self):
        row = example("請登入服務器。")
        original = deepcopy(row)
        accumulator = TaiwanUsageAccumulator(example_limit=1)
        for verdict in iter_taiwan_usage_audits(row for _ in range(10)):
            accumulator.update(verdict)
        result = accumulator.report()
        self.assertEqual(result["records"], 10)
        self.assertEqual(result["decision_counts"], {"REJECT": 10})
        self.assertTrue(all(len(values) <= 1 for values in result["examples"].values()))
        self.assertEqual(row, original)


if __name__ == "__main__":
    unittest.main()