arena/094f314c-aram
add-index-html-10623938925177053894 arena/094f314c-aram chatgpt-phase1b2-autopilot codex/adr-future-connectors-pi-v1 codex/aram-account-note-source-trace-20261031 codex/aram-actions-node24-maintenance-20261031 codex/aram-analyst-review-workbook-20261031 codex/aram-bs-candidate-statement-20261031 codex/aram-cash-flow-direct-candidate-20261031 codex/aram-clean-reference-year-integrity-20261030 codex/aram-cross-statement-controls-20261031 codex/aram-equity-changes-candidate-20261031 codex/aram-five-statement-cli-20261031 codex/aram-five-statement-integration-20261031 codex/aram-five-statement-orchestrator-20261031 codex/aram-gate3-coverage-target-guard-20261030 codex/aram-gate3-hidden-xlsx-guard-20261030 codex/aram-gate3-integration-validation-20261030 codex/aram-gate3-mapping-change-preview-20261030 codex/aram-gate3-stale-note-guard-20261030 codex/aram-income-statement-candidate-20261031 codex/aram-manifest-referential-integrity-20261031 codex/aram-mapping-source-parser-20261101 codex/aram-multidimensional-mapping-20261101 codex/aram-multistatement-mapping-20261031 codex/aram-pipeline-manifest-schema-20261031 codex/aram-readonly-mapping-coverage-20261031 codex/aram-reconciliation-review-gate-20261031 codex/aram-same-flush-fiscal-lock-20261030 codex/aram-synthetic-windows-demo-20261031 codex/aram-trial-balance-diagnostic-20261031 codex/aram-windows-background-detail-search-20261031 codex/aram-windows-detail-review-20261031 codex/aram-windows-five-statement-pilot-20261031 codex/aram-windows-statement-figures-20261031 codex/gate-2a-pilot-workbook codex/gate-2a-pilot-workbook-6864754244772568979 codex/gate3-authenticated-principal-boundary-20261030 codex/gate3-authored-draft-staging-20261030 codex/gate3-carry-forward-preview-20261023 codex/gate3-draft-staging-audit-20261030 codex/gate3-mapping-batch-freshness-20261030 codex/gate3-mapping-batch-review-20261030 codex/gate3-mapping-core codex/gate3-mapping-coverage-20261023 codex/gate3-mapping-excel-20261023 codex/gate3-note-mapping-review-20261023 codex/gate3-signed-year-scope-20261030 codex/gate3-unapproved-proposal-storage-20261030 codex/payvast-mapping-discovery-20261023 codex/phase-2a-backend-foundation codex/phase-2b-post-merge-record codex/phase-2b-source-registration codex/phase-2b-source-registration-12955190277775369594 codex/post-gate2a-control-reconciliation codex/post-pr18-acceptance-record codex/project-control-foundation codex/t1-repo-hygiene-20261023 codex/t2-ci-hardening-20261023 codex/t3-explicit-migrations-20261023 codex/t6a-readonly-diagnostics-20261023 codex/v1-01-safety-gate-hardening codex/v1-year-isolation-followup-20261023 codex/windows-native-pilot-shell-20261030 docs/aram-master-control-plan-20261111 docs/aram-roadmap-dashboard-20261030 docs/financial-statement-reconciliation-1402-1404-20261110 feat/gate3-governed-mapping-20261101 feat/gate3-package9-1-security-20261103 feat/gate3-package9-isolated-20261103 fix/password-unicode-validation-20261111 governance/aram-5-1-3-controls-20261030 governance/role-based-operating-model jules-1168663913887856558-73b8a885 jules-gate-2b-mapping-workflow-foundation-4137724387867065330 phase-1b1-audit-report-7365389436990903239 phase-2a-backend-foundation-10237597358138521261 phase1b2-postmerge-metadata-fix refactor/drg-parent-year-id-15088443704684163304 source-data-cleanup
py 114 lines 5 KB
Raw
1 """Single-source Persian normalization and exact cell decoding (P-03, P-04).
2
3 Every Persian text input passes through :func:`normalize_fa` (booklet P-04).
4 Account/note codes are always text and keep leading zeros and length (P-03);
5 they are never numerified. Excel floats become :class:`~decimal.Decimal` through
6 the shortest round-trip ``repr`` so no binary float artifact survives (D-04).
7
8 Evidence (read-only probe of data/source_ledgers/source_1404.xlsx, 252898 rows):
9 the canonical ``حساب`` and ``kol`` cells are stored as integers and there are no
10 fractional rial cells. The booklet D-04 default "raw numeric code -> explicit
11 error" is therefore refuted by the real data (section 17 rule 3, evidence wins):
12 integral numeric codes are accepted and converted to text exactly, text codes
13 keep their leading zeros, and only non-integral/ambiguous numeric codes raise.
14 """
15
16 from __future__ import annotations
17
18 from decimal import Decimal, InvalidOperation
19
20 # Arabic -> Persian letters and Persian/Arabic-Indic digits -> Latin (P-04, §8).
21 _TRANSLATION = {
22 0x064A: 0x06CC, # Arabic yeh ي -> Persian yeh ی
23 0x0643: 0x06A9, # Arabic kaf ك -> Persian kaf ک
24 0x0640: None, # tatweel / kashida ـ removed
25 0x00A0: None, # no-break space removed
26 0x200B: None, # zero-width space removed
27 0x200E: None, # left-to-right mark removed
28 0x200F: None, # right-to-left mark removed
29 0xFEFF: None, # zero-width no-break space / BOM removed
30 }
31 for _i in range(10):
32 _TRANSLATION[0x06F0 + _i] = 0x30 + _i # Persian digits ۰-۹
33 _TRANSLATION[0x0660 + _i] = 0x30 + _i # Arabic digits ٠-٩
34 # Control characters (except tab/newline which trim handles) are removed.
35 for _c in range(0x20):
36 if _c not in (0x09, 0x0A, 0x0D):
37 _TRANSLATION[_c] = None
38 _TRANSLATION[0x7F] = None
39
40 # Thousands separators that may appear inside numeric text cells.
41 _SEPARATORS = str.maketrans({",": None, "٬": None, "،": None, " ": None, "\u200c": None})
42
43
44 class NormalizationError(ValueError):
45 """Raised when a cell cannot be normalized safely (fail loud, P-09)."""
46
47
48 def normalize_fa(text: str) -> str:
49 """Normalize Persian text: letters, digits, invisible chars, trim (P-04).
50
51 Idempotent: ``normalize_fa(normalize_fa(x)) == normalize_fa(x)``. The
52 zero-width non-joiner (U+200C, the Persian half-space) is preserved because
53 it is linguistically meaningful; only invisible *format* controls are dropped.
54 """
55 cleaned = text.translate(_TRANSLATION)
56 return cleaned.strip()
57
58
59 def normalize_code(value: object, *, row: int, field: str) -> str:
60 """Return an account/note code as text, preserving leading zeros (P-03, D-04).
61
62 * ``str`` -> :func:`normalize_fa`, leading zeros and length preserved.
63 * ``int`` -> exact decimal text (the canonical ledger stores codes as int).
64 * integral ``float``/``Decimal`` -> exact integer text.
65 * non-integral numeric, ``bool``, ``None`` -> :class:`NormalizationError`.
66
67 A code is never silently truncated or numerified; ``'0101'`` stays ``'0101'``.
68 """
69 if value is None or isinstance(value, bool):
70 raise NormalizationError(f"row {row}: {field} is not a valid code")
71 if isinstance(value, str):
72 code = normalize_fa(value)
73 if not code:
74 raise NormalizationError(f"row {row}: {field} is empty")
75 return code
76 if isinstance(value, int):
77 return str(value)
78 if isinstance(value, (float, Decimal)):
79 number = decimal_from_cell(value, row=row, field=field)
80 if number != number.to_integral_value():
81 raise NormalizationError(f"row {row}: {field} must be an integer code, got {number}")
82 return str(int(number))
83 raise NormalizationError(f"row {row}: {field} is not a valid code")
84
85
86 def decimal_from_cell(value: object, *, row: int, field: str) -> Decimal:
87 """Decode a numeric cell to an exact :class:`Decimal` (D-04, §8).
88
89 Floats use the shortest round-trip ``repr`` (never ``str(float)`` artifacts
90 nor the exact binary expansion). Text is Persian-normalized and thousands
91 separators are removed before parsing. Non-finite or non-numeric values
92 raise :class:`NormalizationError`.
93 """
94 if value is None or isinstance(value, bool):
95 raise NormalizationError(f"row {row}: {field} is required and numeric")
96 if isinstance(value, Decimal):
97 parsed = value
98 elif isinstance(value, int):
99 parsed = Decimal(value)
100 elif isinstance(value, float):
101 parsed = Decimal(repr(value))
102 elif isinstance(value, str):
103 candidate = normalize_fa(value).translate(_SEPARATORS)
104 if not candidate:
105 raise NormalizationError(f"row {row}: {field} is required and numeric")
106 try:
107 parsed = Decimal(candidate)
108 except InvalidOperation as exc:
109 raise NormalizationError(f"row {row}: {field} is not numeric") from exc
110 else:
111 raise NormalizationError(f"row {row}: {field} is not numeric")
112 if not parsed.is_finite():
113 raise NormalizationError(f"row {row}: {field} must be finite")
114 return parsed