"""Streaming Taiwan usage checks; finite mechanical rules, not human review. Rules are editorial policies for this corpus, not universal linguistic claims. No text is silently normalized. Candidate and faithful-copy exemptions retain evidence. Code, IDs and schema keys are not treated as natural-language text. """ from __future__ import annotations from collections import Counter from collections.abc import Iterable, Iterator, Mapping from dataclasses import dataclass from datetime import date import re from typing import Any TAIWAN_USAGE_VERSION = "barbet.taiwan-usage/1.0.0" REFERENCE_SOURCES = ( {"title": "數位發展部 ODF 文件 Web 應用元件伺服器佈署手冊", "url": "https://odf.moda.gov.tw/QA/public/document/25", "scope": "Positive examples: 軟體、伺服器、資料庫、記憶體、帳號、介面."}, {"title": "政府資料開放平臺:指引文件", "url": "https://data.gov.tw/about/doc?chapter=8&doc=4", "scope": "Metadata schema is rendered 詮釋資料綱要; JSON Schema is retained."}, {"title": "教育部《重編國語辭典修訂本》單字基本體例", "url": "https://dict.revised.moe.edu.tw/page.jsp?ID=18", "scope": "Variants exist; ambiguous 台/臺、里/裡 are not rejected."}, {"title": "中央銀行:我愛新臺幣", "url": "https://www.cbc.gov.tw/tw/lp-1084-1.html", "scope": "Positive currency spelling, not financial or factual certification."}, ) # Ambiguous 台、里、后、干、面、云、松 are deliberately not rejected. _SIMPLIFIED = frozenset( "这们为发现会说对从还让进过边开关问间种样点应当无并动产业东书车马门" "风气长乐见观觉学术语体国万亿网软线标数据处务别选择确认级类则导广" "场层块张头条项节录页图声转换获给结构复杂简将与仅请传统华汉湾医药" "银钱历区县乡镇际参报备责权资码库档盘记汇验适响隐审个" ) _SIMPLIFIED_RE = re.compile("[" + "".join(sorted(_SIMPLIFIED)) + "]") PREFERRED_TERMS = { "軟件": "軟體", "硬件": "硬體", "服務器": "伺服器", "數據庫": "資料庫", "內存": "記憶體", "硬盤": "硬碟", "鼠標": "滑鼠", "屏幕": "螢幕", "文件夾": "資料夾", "打印機": "印表機", "默認值": "預設值", "加載": "載入", "賬號": "帳號", "用戶名": "使用者名稱", "文檔": "文件", "網絡": "網路", "互聯網": "網際網路", "雲計算": "雲端運算", "網盤": "雲端硬碟", "二維碼": "QR Code", "短信": "簡訊", "視頻": "影片/視訊(依情境)", "音頻": "音訊", "公交車": "公車", "出租車": "計程車", "身份證": "身分證", } _HAN = re.compile(r"[\u3400-\u4dbf\u4e00-\u9fff\U00020000-\U0002fa1f]") _CODE_SPANS = re.compile(r"```[\s\S]*?```|`[^`\n]*`|https?://[^\s<>]+") _DATE = re.compile(r"(? Iterator[VisibleText]: if isinstance(value, str): if _HAN.search(value): yield VisibleText(path, value, scope, unit_id) elif isinstance(value, Mapping): for key, child in value.items(): if str(key).lower() not in _TECHNICAL_KEYS: yield from _walk_text(child, f"{path}.{key}", scope, unit_id) elif isinstance(value, list): for index, child in enumerate(value): yield from _walk_text(child, f"{path}[{index}]", scope, unit_id) def _faithful_copy_sources(record: Mapping[str, Any]) -> set[str]: """Only a fully reconstructible COPY is eligible for locale exemptions.""" target = record.get("target", {}) action = target.get("action", {}) if record.get("primitive") != "COPY" or action.get("tool") != "COPY": return set() ids = action.get("arguments", {}).get("source_units", target.get("copied_units", [])) if not isinstance(ids, list) or not ids or any(not isinstance(uid, str) for uid in ids): return set() units = { unit.get("id"): unit.get("text") for item in record.get("inputs", []) for unit in item.get("units", []) if isinstance(unit, Mapping) } if any(not isinstance(units.get(uid), str) for uid in ids): return set() if target.get("output_text") != "".join(units[uid] for uid in ids): return set() return set(ids) def iter_visible_text(record: Mapping[str, Any]) -> Iterator[VisibleText]: """Scan visible prose and Han-bearing values, not provenance or syntax.""" yield from _walk_text(record.get("task_spec", {}), "task_spec", "instruction") target = record.get("target", {}) selected: set[str] = set() if record.get("primitive") == "RANK" and target.get("ranking"): selected.add(target["ranking"][0]) if record.get("primitive") == "MATCH" and isinstance(target.get("canonical_id"), str): selected.add(target["canonical_id"]) action = target.get("action", {}) if action.get("tool") == "ACCEPT": candidate_id = action.get("arguments", {}).get("candidate_id") if isinstance(candidate_id, str): selected.add(candidate_id) copy_sources = _faithful_copy_sources(record) for index, item in enumerate(record.get("inputs", [])): descriptor = str(item.get("type", "")).lower() is_negative = item.get("is_intentional_negative") is True or any( marker in descriptor for marker in _NEGATIVE_TYPES ) if item.get("role") in {"reference", "gold", "clean", "positive"}: is_negative = False base_scope = "comparison_input" if is_negative else "source" yield from _walk_text( {key: value for key, value in item.items() if key != "units"}, f"inputs[{index}]", base_scope, item.get("id"), ) for offset, unit in enumerate(item.get("units", [])): uid = unit.get("id") scope = "selected_candidate" if uid in selected or item.get("id") in selected else base_scope if uid in copy_sources: scope = "faithful_copy_source" yield from _walk_text(unit, f"inputs[{index}].units[{offset}]", scope, uid) for key, value in target.items(): if key not in _TECHNICAL_KEYS: scope = "faithful_copy_output" if key == "output_text" and copy_sources else "target" yield from _walk_text(value, f"target.{key}", scope) def _mask_code(text: str) -> str: # Equal-length masking preserves character-span provenance. return _CODE_SPANS.sub(lambda match: " " * len(match.group()), text) def audit_taiwan_usage(record: Mapping[str, Any]) -> dict[str, Any]: """Return a per-record verdict without changing the input. BLOCK: finite rule found a positive-supervision defect. REVIEW: unresolved editorial choice. EXEMPT: exact occurrence and reason retained, no failure. Candidate exemptions never cover artificial synthetic negative markers. """ findings: list[dict[str, Any]] = [] scanned_fields = 0 scanned_han = 0 seen: set[tuple[str, str, str]] = set() def add(field: VisibleText, rule: str, start: int, end: int, replacement: str | None, severity: str = "BLOCK", *, locale_rule: bool = False) -> None: matched = field.text[start:end] dedupe_key = (field.path, rule, matched) if dedupe_key in seen: return seen.add(dedupe_key) exemption = None if rule != "ARTIFICIAL_NEGATIVE_PLACEHOLDER" and field.scope == "comparison_input": severity, exemption = "EXEMPT", "candidate_or_corrupted_input_not_positive_target" elif locale_rule and field.scope.startswith("faithful_copy_"): severity, exemption = "EXEMPT", "copy_source_ids_reconstruct_target_exactly" findings.append({ "rule_id": rule, "severity": severity, "path": field.path, "scope": field.scope, "unit_id": field.unit_id, "matched": matched, "character_span": [start, end], "suggestion": replacement, "exemption": exemption, }) for field in iter_visible_text(record): text = _mask_code(field.text) scanned_fields += 1 scanned_han += len(_HAN.findall(text)) for match in _SIMPLIFIED_RE.finditer(text): add(field, "SIMPLIFIED_FORM", match.start(), match.end(), None, locale_rule=True) for term, replacement in PREFERRED_TERMS.items(): offset = text.find(term) if offset >= 0: add(field, "TAIWAN_PREFERRED_TERM", offset, offset + len(term), replacement, locale_rule=True) for pattern, replacement in _REVIEW_PROSE: for match in pattern.finditer(text): add(field, "UNLOCALIZED_PROSE", match.start(), match.end(), replacement, "REVIEW") for rule, pattern, explanation in _NATURALNESS: for match in pattern.finditer(text): add(field, rule, match.start(), match.end(), explanation) for match in _DATE.finditer(text): try: date(*(int(part) for part in match.groups())) except ValueError: add(field, "INVALID_GREGORIAN_DATE", match.start(), match.end(), "請使用有效的西元日期。") counts = Counter(item["severity"] for item in findings) return { "record_id": record.get("record_id"), "ruleset_version": TAIWAN_USAGE_VERSION, "verification_scope": "finite_mechanical_taiwan_usage_rules_not_human_review", "passed": not counts["BLOCK"] and not counts["REVIEW"], "decision": "REJECT" if counts["BLOCK"] else "REVIEW" if counts["REVIEW"] else "PASS", "block_count": counts["BLOCK"], "review_count": counts["REVIEW"], "exempt_count": counts["EXEMPT"], "scanned_fields": scanned_fields, "scanned_han_characters": scanned_han, "findings": findings, } def iter_taiwan_usage_audits(records: Iterable[Mapping[str, Any]]) -> Iterator[dict[str, Any]]: for record in records: yield audit_taiwan_usage(record) class TaiwanUsageAccumulator: """Corpus counters; at most example_limit diagnostics per fixed rule.""" def __init__(self, example_limit: int = 3) -> None: if example_limit < 0: raise ValueError("example_limit must be non-negative") self.example_limit = example_limit self.records = 0 self.decisions: Counter[str] = Counter() self.rules: Counter[str] = Counter() self.examples: dict[str, list[dict[str, Any]]] = {} def update(self, verdict: Mapping[str, Any]) -> None: if verdict.get("ruleset_version") != TAIWAN_USAGE_VERSION: raise ValueError("Taiwan usage ruleset mismatch") self.records += 1 self.decisions[verdict["decision"]] += 1 for finding in verdict["findings"]: key = f"{finding['severity']}:{finding['rule_id']}" self.rules[key] += 1 examples = self.examples.setdefault(key, []) if len(examples) < self.example_limit: examples.append({"record_id": verdict["record_id"], **finding}) def report(self) -> dict[str, Any]: return { "ruleset_version": TAIWAN_USAGE_VERSION, "records": self.records, "passed": self.records > 0 and self.decisions["REJECT"] == 0 and self.decisions["REVIEW"] == 0, "decision_counts": dict(self.decisions), "finding_counts": dict(self.rules), "examples": self.examples, "human_reviewed": False, "limitations": "Finite mechanical checks do not establish fluency or factual correctness.", "reference_sources": list(REFERENCE_SOURCES), }