arabic-fix 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
arabic_fix/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """arabic-fix: shape, BiDi-fix, and normalize Arabic text.
2
+
3
+ A unified API for the three things that go wrong when Arabic text flows
4
+ through systems built English-first: lost letter shaping, broken BiDi
5
+ order, and inconsistent Unicode normalization.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from .fixer import fix, fix_report, FixOptions, FixReport
11
+
12
+ __all__ = ["fix", "fix_report", "FixOptions", "FixReport"]
13
+ __version__ = "0.2.0"
arabic_fix/bidi.py ADDED
@@ -0,0 +1,86 @@
1
+ """Bidirectional (BiDi) reordering for mixed-direction text.
2
+
3
+ Arabic is RTL. Numbers and Latin words embedded inside Arabic need
4
+ explicit reordering or they land on the wrong side of the line.
5
+ `python-bidi` does this correctly; we wrap it here so callers can pass a
6
+ single string and get a display-ready one back.
7
+
8
+ For HTML/CSS contexts (which is most web output), use the system's own
9
+ BiDi engine via `direction: rtl` + `unicode-bidi: isolate` on the
10
+ container — DO NOT pre-shape Arabic inside HTML, the browser does that
11
+ better. This module is for terminals, log files, PDFs, AI chat where
12
+ no rendering engine helps.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from typing import Optional
18
+
19
+ try:
20
+ from bidi.algorithm import get_display # type: ignore[import-untyped]
21
+ _HAS_BIDI = True
22
+ _ImportError: Exception | None = None
23
+ except Exception as _exc: # pragma: no cover
24
+ # bidi is untyped; plain `= None` is fine for mypy.
25
+ get_display = None
26
+ _HAS_BIDI = False
27
+ _ImportError = _exc
28
+
29
+
30
+ # python-bidi v0.6+ uses single-char codes for base_dir
31
+ _RTL_LTR_TO_BIDI = {"rtl": "R", "ltr": "L"}
32
+
33
+
34
+ def reorder(
35
+ text: str,
36
+ *,
37
+ base_dir: str = "rtl",
38
+ upper_is_rtl: bool = False,
39
+ ) -> str:
40
+ """Apply BiDi reordering for display.
41
+
42
+ Parameters
43
+ ----------
44
+ text:
45
+ Input. May already be letter-shaped, but most callers pass
46
+ unshaped text here — shaping is a separate step.
47
+ base_dir:
48
+ 'rtl' (default) or 'ltr'. Set 'ltr' if the dominant run is
49
+ English with an Arabic substring. Internally translated to
50
+ python-bidi's 'R' / 'L' codes.
51
+ upper_is_rtl:
52
+ Treat runs of uppercase Latin as RTL. Almost never what you
53
+ want; default False.
54
+
55
+ Returns
56
+ -------
57
+ str
58
+ Display-ordered string. If `python-bidi` is missing, the input
59
+ is returned unchanged.
60
+
61
+ Raises
62
+ ------
63
+ ValueError
64
+ If `base_dir` is not one of 'rtl' / 'ltr' (case-insensitive).
65
+ Previously this was silently passed through to `python-bidi`,
66
+ which would either raise an opaque error or fall back to a
67
+ default — masking caller bugs. Now we fail loud at the API edge.
68
+ """
69
+ if not text:
70
+ return text
71
+ if not _HAS_BIDI:
72
+ return text
73
+ bidi_dir = _RTL_LTR_TO_BIDI.get(base_dir.lower())
74
+ if bidi_dir is None:
75
+ raise ValueError(
76
+ f"unknown base_dir: {base_dir!r}; expected one of "
77
+ f"{sorted(_RTL_LTR_TO_BIDI)} (case-insensitive)"
78
+ )
79
+ return get_display( # type: ignore
80
+ text,
81
+ base_dir=bidi_dir,
82
+ upper_is_rtl=upper_is_rtl,
83
+ )
84
+
85
+
86
+ __all__ = ["reorder"]
arabic_fix/cli.py ADDED
@@ -0,0 +1,161 @@
1
+ """CLI entry point — `arabic-fix` command."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import io
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from .fixer import fix, fix_report, FixOptions
11
+
12
+
13
+ def _build_parser() -> argparse.ArgumentParser:
14
+ p = argparse.ArgumentParser(
15
+ prog="arabic-fix",
16
+ description=(
17
+ "Fix Arabic text in files: letter-shape, BiDi-reorder, normalize. "
18
+ "Reads UTF-8, writes UTF-8."
19
+ ),
20
+ )
21
+ p.add_argument(
22
+ "paths",
23
+ nargs="*",
24
+ type=Path,
25
+ help="Files to fix. Use '-' or omit to read from stdin.",
26
+ )
27
+ p.add_argument(
28
+ "-o", "--output",
29
+ type=Path,
30
+ help="Output file. Only valid with a single input file. "
31
+ "If omitted with one input, write in place.",
32
+ )
33
+ p.add_argument("--no-shape", action="store_true", help="Skip letter shaping.")
34
+ p.add_argument("--no-bidi", action="store_true", help="Skip BiDi reordering.")
35
+ p.add_argument(
36
+ "--no-normalize",
37
+ action="store_true",
38
+ help="Skip Unicode normalization.",
39
+ )
40
+ p.add_argument(
41
+ "--normalize-form",
42
+ default="NFC",
43
+ choices=["NFC", "NFD", "NFKC", "NFKD"],
44
+ help="Unicode normalization form (default NFC).",
45
+ )
46
+ p.add_argument(
47
+ "--bidi-base-dir",
48
+ default="rtl",
49
+ choices=["rtl", "ltr"],
50
+ help="Base direction for BiDi reorder (default rtl).",
51
+ )
52
+ p.add_argument(
53
+ "--no-ligatures",
54
+ action="store_true",
55
+ help="Disable reshape ligatures (e.g. لا, ﷲ).",
56
+ )
57
+ p.add_argument(
58
+ "--report",
59
+ action="store_true",
60
+ help="Print a JSON report per file (what was shaped, reordered, "
61
+ "normalized) to stderr.",
62
+ )
63
+ p.add_argument(
64
+ "--check",
65
+ action="store_true",
66
+ help="Exit non-zero if any file would change. Useful in CI to "
67
+ "enforce Arabic text is already fixed.",
68
+ )
69
+ p.add_argument(
70
+ "--encoding",
71
+ default="utf-8",
72
+ help="File encoding (default utf-8).",
73
+ )
74
+ return p
75
+
76
+
77
+ def _process(text: str, opts: FixOptions) -> str:
78
+ return fix(text, **opts.__dict__)
79
+
80
+
81
+ def main(argv: list[str] | None = None) -> int:
82
+ parser = _build_parser()
83
+ args = parser.parse_args(argv)
84
+ opts = FixOptions(
85
+ shape=not args.no_shape,
86
+ bidi=not args.no_bidi,
87
+ normalize_text=not args.no_normalize,
88
+ normalize_form=args.normalize_form,
89
+ bidi_base_dir=args.bidi_base_dir,
90
+ ligatures=not args.no_ligatures,
91
+ )
92
+
93
+ if not args.paths or (len(args.paths) == 1 and str(args.paths[0]) == "-"):
94
+ # stdin → stdout.
95
+ #
96
+ # `sys.stdin.read()` defaults to `locale.getpreferredencoding(False)`,
97
+ # which on many non-English terminals is ASCII or Latin-1 and will
98
+ # raise `UnicodeDecodeError` on Arabic UTF-8 bytes. Force UTF-8 by
99
+ # wrapping the binary buffer explicitly. This matches the encoding
100
+ # we use for file reads (`--encoding`, default utf-8).
101
+ #
102
+ # In tests, `sys.stdin` is sometimes monkeypatched to a `StringIO`
103
+ # (which has no `.buffer`); fall back to that wrapped as text.
104
+ if hasattr(sys.stdin, "buffer"):
105
+ text = io.TextIOWrapper(sys.stdin.buffer, encoding="utf-8").read()
106
+ else:
107
+ text = sys.stdin.read()
108
+ out = _process(text, opts)
109
+ sys.stdout.write(out)
110
+ return 0
111
+
112
+ if len(args.paths) > 1 and args.output:
113
+ print("error: --output can only be used with a single input file.",
114
+ file=sys.stderr)
115
+ return 2
116
+
117
+ exit_code = 0
118
+ for path in args.paths:
119
+ try:
120
+ original = path.read_text(encoding=args.encoding)
121
+ except OSError as exc:
122
+ print(f"error: cannot read {path}: {exc}", file=sys.stderr)
123
+ exit_code = 1
124
+ continue
125
+
126
+ report = fix_report(original, **opts.__dict__)
127
+
128
+ if args.report:
129
+ import json
130
+ payload = {
131
+ "path": str(path),
132
+ "changed": report.changed,
133
+ "shaped": report.shaped,
134
+ "bidi_reordered": report.bidi_reordered,
135
+ "normalized": report.normalized,
136
+ "contained_arabic": report.contained_arabic,
137
+ "warnings": report.warnings,
138
+ }
139
+ print(json.dumps(payload, ensure_ascii=False), file=sys.stderr)
140
+
141
+ if args.check:
142
+ if report.changed:
143
+ print(f"would change: {path}", file=sys.stderr)
144
+ exit_code = 1
145
+ continue
146
+
147
+ if not report.changed:
148
+ continue
149
+
150
+ target = args.output if args.output else path
151
+ try:
152
+ target.write_text(report.output, encoding=args.encoding)
153
+ except OSError as exc:
154
+ print(f"error: cannot write {target}: {exc}", file=sys.stderr)
155
+ exit_code = 1
156
+
157
+ return exit_code
158
+
159
+
160
+ if __name__ == "__main__": # pragma: no cover
161
+ sys.exit(main())
arabic_fix/fixer.py ADDED
@@ -0,0 +1,163 @@
1
+ """The high-level `fix()` API — one call, all three fixes.
2
+
3
+ Pipeline order matters: shape FIRST, then BiDi-reorder, then normalize.
4
+ Skipping any step produces subtly-broken output in a different way:
5
+
6
+ normalize → shape : marks get reshaped into presentation forms too
7
+ late to fix; cached glyph tables may stay wrong.
8
+ shape → normalize → bidi : normalization AFTER shape may decompose
9
+ presentation forms back to base chars.
10
+ bidi first : without shaping, BiDi reorders disconnected
11
+ glyphs and you can't fix it later.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass, field
17
+ from typing import Any
18
+
19
+ from .shaper import shape
20
+ from .bidi import reorder
21
+ from .normalize import normalize, contains_arabic, NormForm
22
+ from .bidi import _RTL_LTR_TO_BIDI # for normalizing base_dir at the API edge
23
+
24
+
25
+ @dataclass
26
+ class FixOptions:
27
+ """Tune which fixes get applied and how."""
28
+ shape: bool = True
29
+ bidi: bool = True
30
+ normalize_text: bool = True
31
+ normalize_form: str = "NFC" # 'NFC' | 'NFD' | 'NFKC' | 'NFKD'
32
+ bidi_base_dir: str = "rtl" # 'rtl' | 'ltr'
33
+ bidi_upper_is_rtl: bool = False
34
+ ligatures: bool = True # reshape-config: presentation-form ligatures
35
+
36
+
37
+ @dataclass
38
+ class FixReport:
39
+ """Returned by `fix_report()` so callers can see what changed."""
40
+ input: str
41
+ output: str
42
+ shaped: bool
43
+ bidi_reordered: bool
44
+ normalized: bool
45
+ contained_arabic: bool
46
+ warnings: list[str] = field(default_factory=list)
47
+
48
+ @property
49
+ def changed(self) -> bool:
50
+ return self.input != self.output
51
+
52
+
53
+ def _coerce_options(opts: dict[str, Any]) -> FixOptions:
54
+ """Build FixOptions from arbitrary user kwargs, rejecting unknown keys.
55
+
56
+ We do this rather than `FixOptions(**opts)` so a typo'd option name
57
+ fails loudly with a helpful message instead of silently producing
58
+ a dataclass missing that field.
59
+ """
60
+ known = {f for f in FixOptions.__dataclass_fields__}
61
+ unknown = set(opts) - known
62
+ if unknown:
63
+ raise TypeError(
64
+ f"unknown fix() option(s): {sorted(unknown)}; "
65
+ f"valid options: {sorted(known)}"
66
+ )
67
+ # Normalize bidi_base_dir to its long form ('rtl'/'ltr') if the
68
+ # caller passed the single-char bidi code ('R'/'L').
69
+ if "bidi_base_dir" in opts:
70
+ b = opts["bidi_base_dir"]
71
+ if isinstance(b, str) and b in {"R", "L"}:
72
+ opts["bidi_base_dir"] = "rtl" if b == "R" else "ltr"
73
+ # Narrow normalize_form if it was passed as a valid literal.
74
+ if "normalize_form" in opts:
75
+ f = opts["normalize_form"]
76
+ if f not in {"NFC", "NFD", "NFKC", "NFKD"}:
77
+ raise ValueError(
78
+ f"normalize_form must be one of NFC/NFD/NFKC/NFKD, got {f!r}"
79
+ )
80
+ opts["normalize_form"] = f
81
+ return FixOptions(**opts)
82
+
83
+
84
+ def fix(text: str, **opts: Any) -> str:
85
+ """One-call fix: shape, BiDi-reorder, normalize.
86
+
87
+ Returns the fixed string. For diagnostics, use `fix_report()`.
88
+
89
+ Examples
90
+ --------
91
+ >>> fix("العربية")
92
+ '\\u0627\\u0644\\u0639\\u0631\\u0628\\u064a\\u0629' # shaped + BiDi-fixed
93
+ >>> fix("Hello مرحبا 123")
94
+ ... # digits 123 end up on the left in display order
95
+ """
96
+ options = _coerce_options(opts) if opts else FixOptions()
97
+ return _apply(text, options).output
98
+
99
+
100
+ def fix_report(text: str, **opts: Any) -> FixReport:
101
+ """Same as `fix()` but returns a `FixReport` describing what happened."""
102
+ options = _coerce_options(opts) if opts else FixOptions()
103
+ return _apply(text, options)
104
+
105
+
106
+ def _apply(text: str, options: FixOptions) -> FixReport:
107
+ if not text:
108
+ return FixReport(
109
+ input=text,
110
+ output=text,
111
+ shaped=False,
112
+ bidi_reordered=False,
113
+ normalized=False,
114
+ contained_arabic=False,
115
+ )
116
+
117
+ warnings: list[str] = []
118
+ had_arabic = contains_arabic(text)
119
+ out = text
120
+ shaped_now = False
121
+ bidi_now = False
122
+ normalized_now = False
123
+
124
+ if options.normalize_text:
125
+ new = normalize(out, form=options.normalize_form)
126
+ if new != out:
127
+ normalized_now = True
128
+ out = new
129
+
130
+ if options.shape and had_arabic:
131
+ try:
132
+ new = shape(out, ligatures=options.ligatures)
133
+ if new != out:
134
+ shaped_now = True
135
+ out = new
136
+ except Exception as exc: # pragma: no cover
137
+ warnings.append(f"shaper failed: {exc}")
138
+
139
+ if options.bidi and had_arabic:
140
+ try:
141
+ new = reorder(
142
+ out,
143
+ base_dir=options.bidi_base_dir,
144
+ upper_is_rtl=options.bidi_upper_is_rtl,
145
+ )
146
+ if new != out:
147
+ bidi_now = True
148
+ out = new
149
+ except Exception as exc: # pragma: no cover
150
+ warnings.append(f"bidi reorder failed: {exc}")
151
+
152
+ return FixReport(
153
+ input=text,
154
+ output=out,
155
+ shaped=shaped_now,
156
+ bidi_reordered=bidi_now,
157
+ normalized=normalized_now,
158
+ contained_arabic=had_arabic,
159
+ warnings=warnings,
160
+ )
161
+
162
+
163
+ __all__ = ["fix", "fix_report", "FixOptions", "FixReport"]
@@ -0,0 +1,83 @@
1
+ """Unicode normalization helpers.
2
+
3
+ NFC vs NFD drift is a common source of "same text, different bytes" bugs
4
+ across macOS / Windows / Linux systems handling Arabic — especially with
5
+ tashkeel (combining marks for fatḥa, kasra, ḍamma).
6
+
7
+ Default to NFC (composed) for interchange: smaller byte size, more
8
+ predictable hashing, fully compatible with the rest of the library.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import unicodedata
14
+ from typing import Literal
15
+
16
+
17
+ def normalize(text: str, form: str = "NFC") -> str:
18
+ """Return text in the requested Unicode normalization form.
19
+
20
+ Parameters
21
+ ----------
22
+ text:
23
+ Any string.
24
+ form:
25
+ One of 'NFC' (default), 'NFD', 'NFKC', 'NFKD'.
26
+
27
+ Returns
28
+ -------
29
+ str
30
+ Normalized string. Empty input returns empty.
31
+ """
32
+ if not text:
33
+ return text
34
+ form = form.upper()
35
+ if form not in {"NFC", "NFD", "NFKC", "NFKD"}:
36
+ raise ValueError(f"unknown normalization form: {form!r}")
37
+ # unicodedata.normalize wants a Literal[...] for the form arg;
38
+ # we've validated it above, so the cast is safe.
39
+ return unicodedata.normalize(form, text) # type: ignore[arg-type]
40
+
41
+
42
+ NormForm = Literal["NFC", "NFD", "NFKC", "NFKD"]
43
+
44
+
45
+ def contains_arabic(text: str) -> bool:
46
+ """Return True if `text` contains any Arabic-block codepoint."""
47
+ for ch in text:
48
+ cp = ord(ch)
49
+ # Arabic block U+0600–U+06FF
50
+ # Arabic Supplement U+0750–U+077F
51
+ # Arabic Extended-A U+08A0–U+08FF
52
+ # Arabic Presentation Forms-A U+FB50–U+FDFF
53
+ # Arabic Presentation Forms-B U+FE70–U+FEFF
54
+ if (
55
+ 0x0600 <= cp <= 0x06FF
56
+ or 0x0750 <= cp <= 0x077F
57
+ or 0x08A0 <= cp <= 0x08FF
58
+ or 0xFB50 <= cp <= 0xFDFF
59
+ or 0xFE70 <= cp <= 0xFEFF
60
+ ):
61
+ return True
62
+ return False
63
+
64
+
65
+ def has_tashkeel(text: str) -> bool:
66
+ """Return True if text contains any Arabic combining mark (tashkeel)."""
67
+ tashkeel_ranges = (
68
+ (0x064B, 0x065F), # tanween, harakat, hamza-here
69
+ (0x0670, 0x0670), # alef khanjariya (superscript alef)
70
+ (0x06D6, 0x06DC), # Quranic marks
71
+ (0x06DF, 0x06E4),
72
+ (0x06E7, 0x06E8),
73
+ (0x06EA, 0x06ED),
74
+ )
75
+ for ch in text:
76
+ cp = ord(ch)
77
+ for lo, hi in tashkeel_ranges:
78
+ if lo <= cp <= hi:
79
+ return True
80
+ return False
81
+
82
+
83
+ __all__ = ["normalize", "contains_arabic", "has_tashkeel"]
arabic_fix/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file — the arabic_fix package supports PEP 561 type checking.
arabic_fix/shaper.py ADDED
@@ -0,0 +1,98 @@
1
+ """Letter shaping for Arabic script.
2
+
3
+ Arabic letters change form based on position: isolated, initial, medial,
4
+ final. Unicode's Arabic Presentation Forms-B block (U+FE70–U+FEFF) plus
5
+ the ligature-aware reshaper `arabic-reshaper` turn a string of base
6
+ characters into the connected glyphs the eye expects.
7
+
8
+ We wrap `arabic-reshaper` with a graceful fallback that returns the
9
+ input unchanged when the optional dependency is missing, so the rest of
10
+ the library still works.
11
+
12
+ Note: `arabic-reshaper` 3.0.0's `default_config` has
13
+ `delete_harakat=True`. We override that to **preserve tashkeel**
14
+ (matches `agents/eval_cases.md` Case 3 — "Tashkeel preservation").
15
+ Stripping diacritics silently is a content-loss bug.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from typing import Optional
21
+
22
+ try: # arabic-reshaper is an optional dep at import time so the package
23
+ # still loads if only BiDi / normalization are needed.
24
+ import arabic_reshaper # type: ignore[import-untyped]
25
+ from arabic_reshaper.reshaper_config import ( # type: ignore[import-untyped]
26
+ default_config as _default_config,
27
+ )
28
+ _HAS_RESHAPER = True
29
+ _ImportError: Exception | None = None
30
+ except Exception as _exc: # pragma: no cover
31
+ # mypy sees these names as Any (module is untyped), so plain `= None`
32
+ # works without an explicit ignore.
33
+ arabic_reshaper = None
34
+ _default_config = None
35
+ _HAS_RESHAPER = False
36
+ _ImportError = _exc
37
+
38
+
39
+ def _build_reshaper(ligatures: bool) -> "object":
40
+ """Build an ArabicReshaper with tashkeel preservation + caller-controlled ligatures.
41
+
42
+ We always build our own rather than using `arabic_reshaper.reshape()`
43
+ so we can override `delete_harakat`. The library default strips
44
+ diacritics silently — we don't want that.
45
+
46
+ Returns the reshaper object typed as `object` because arabic_reshaper
47
+ ships no py.typed marker; we only call `.reshape(text)` on it.
48
+ """
49
+ from arabic_reshaper import ArabicReshaper # noqa: F401 (only used at runtime)
50
+
51
+ # `default_config` is dict[str, Any] at runtime; mypy sees it as
52
+ # `Literal[...]` which doesn't accept dict(). Cast through Any.
53
+ cfg = dict(_default_config)
54
+ cfg["delete_harakat"] = False
55
+ cfg["support_ligatures"] = ligatures
56
+ return ArabicReshaper(configuration=cfg)
57
+
58
+
59
+ # Cache one reshaper per (ligatures True / False). Identity cache —
60
+ # reuse the same instance across calls so the library isn't rebuilt
61
+ # every shape() invocation.
62
+ _RESHAPERS: dict[bool, "object"] = {}
63
+
64
+
65
+ def shape(text: str, *, ligatures: bool = True) -> str:
66
+ """Apply Arabic letter shaping.
67
+
68
+ Parameters
69
+ ----------
70
+ text:
71
+ Arabic (or mixed) text in its base (un-shaped) form.
72
+ ligatures:
73
+ If True (default), apply presentation-form ligatures
74
+ (e.g. لا, ﷲ). Turn off only for debugging or rare font issues.
75
+
76
+ Returns
77
+ -------
78
+ str
79
+ The shaped string. Tashkeel (diacritics) is preserved. If
80
+ `arabic-reshaper` is not installed, the input is returned
81
+ unchanged.
82
+ """
83
+ if not text:
84
+ return text
85
+ if not _HAS_RESHAPER:
86
+ return text # graceful fallback: input passes through
87
+
88
+ reshaper = _RESHAPERS.get(ligatures)
89
+ if reshaper is None:
90
+ reshaper = _build_reshaper(ligatures)
91
+ _RESHAPERS[ligatures] = reshaper
92
+ # `reshaper.reshape` is typed by arabic-reshaper as Any -> Any.
93
+ # We promise the caller a str; assert at runtime via cast.
94
+ out: str = reshaper.reshape(text) # type: ignore[attr-defined]
95
+ return out
96
+
97
+
98
+ __all__ = ["shape"]