arabic-fix 0.4.0__tar.gz
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-0.4.0/LICENSE +21 -0
- arabic_fix-0.4.0/PKG-INFO +101 -0
- arabic_fix-0.4.0/README.md +68 -0
- arabic_fix-0.4.0/arabic_fix/__init__.py +13 -0
- arabic_fix-0.4.0/arabic_fix/bidi.py +86 -0
- arabic_fix-0.4.0/arabic_fix/cli.py +161 -0
- arabic_fix-0.4.0/arabic_fix/fixer.py +163 -0
- arabic_fix-0.4.0/arabic_fix/normalize.py +83 -0
- arabic_fix-0.4.0/arabic_fix/py.typed +1 -0
- arabic_fix-0.4.0/arabic_fix/shaper.py +98 -0
- arabic_fix-0.4.0/arabic_fix.egg-info/PKG-INFO +101 -0
- arabic_fix-0.4.0/arabic_fix.egg-info/SOURCES.txt +29 -0
- arabic_fix-0.4.0/arabic_fix.egg-info/dependency_links.txt +1 -0
- arabic_fix-0.4.0/arabic_fix.egg-info/entry_points.txt +2 -0
- arabic_fix-0.4.0/arabic_fix.egg-info/requires.txt +7 -0
- arabic_fix-0.4.0/arabic_fix.egg-info/top_level.txt +7 -0
- arabic_fix-0.4.0/designs/validate_tokens.py +118 -0
- arabic_fix-0.4.0/examples/demo.py +72 -0
- arabic_fix-0.4.0/pyproject.toml +76 -0
- arabic_fix-0.4.0/setup.cfg +4 -0
- arabic_fix-0.4.0/tests/__init__.py +0 -0
- arabic_fix-0.4.0/tests/conftest.py +46 -0
- arabic_fix-0.4.0/tests/corpus/__init__.py +14 -0
- arabic_fix-0.4.0/tests/corpus/aljazeera_headlines.py +39 -0
- arabic_fix-0.4.0/tests/corpus/app_ui.py +90 -0
- arabic_fix-0.4.0/tests/corpus/edge_cases.py +113 -0
- arabic_fix-0.4.0/tests/corpus/quran.py +35 -0
- arabic_fix-0.4.0/tests/test_bidi.py +388 -0
- arabic_fix-0.4.0/tests/test_cli.py +488 -0
- arabic_fix-0.4.0/tests/test_fixer.py +511 -0
- arabic_fix-0.4.0/tests/test_shaper.py +337 -0
arabic_fix-0.4.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 arabic-fix contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: arabic-fix
|
|
3
|
+
Version: 0.4.0
|
|
4
|
+
Summary: Fix Arabic text rendering across code, AI agents, and designs.
|
|
5
|
+
Author: arabic-fix contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/your-org/arabic-fix
|
|
8
|
+
Project-URL: Issues, https://github.com/your-org/arabic-fix/issues
|
|
9
|
+
Keywords: arabic,rtl,bidirectional,reshaper,bidi,unicode,i18n,l10n
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Natural Language :: Arabic
|
|
14
|
+
Classifier: Natural Language :: English
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
21
|
+
Classifier: Topic :: Software Development :: Internationalization
|
|
22
|
+
Classifier: Topic :: Text Processing :: Markup
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: arabic-reshaper>=3.0.0
|
|
27
|
+
Requires-Dist: python-bidi>=0.4.2
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7.4; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-cov>=4.1; extra == "dev"
|
|
31
|
+
Requires-Dist: mypy>=1.7; extra == "dev"
|
|
32
|
+
Dynamic: license-file
|
|
33
|
+
|
|
34
|
+
# arabic-fix
|
|
35
|
+
|
|
36
|
+
> Fix Arabic text rendering across code, AI agents, and designs.
|
|
37
|
+
|
|
38
|
+
[](LICENSE)
|
|
39
|
+
[]()
|
|
40
|
+
[]()
|
|
41
|
+
|
|
42
|
+
**One library, one CLI, one system prompt.** Letter-shaping, BiDi reordering,
|
|
43
|
+
Unicode normalization, and a 3-section prompt template for any LLM. Arabic
|
|
44
|
+
flows through terminals, AI agents, log files, and PDFs the way it should.
|
|
45
|
+
|
|
46
|
+
```bash
|
|
47
|
+
pip install arabic-fix
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from arabic_fix import fix
|
|
52
|
+
print(fix("User 42 من الرياض at 09:30"))
|
|
53
|
+
# → a properly shaped, correctly ordered, NFC-normalized string
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
# CLI
|
|
58
|
+
cat arabic.txt | arabic-fix
|
|
59
|
+
arabic-fix --check file.txt # CI mode: exit non-zero if changes needed
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```text
|
|
63
|
+
# AI agent: paste one of the 3 sections from agents/system_prompt.md
|
|
64
|
+
# A · Read Arabic — for agents that parse / summarize / classify
|
|
65
|
+
# B · Write Arabic — for agents that emit to terminal / log / email
|
|
66
|
+
# C · Design Arabic — for HTML / CSS / Tailwind / design tokens
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Why
|
|
70
|
+
|
|
71
|
+
- **Letter shaping** — `ا ب ت` (isolated forms) become `اتصال` (connected) via
|
|
72
|
+
Unicode Presentation Forms-B.
|
|
73
|
+
- **BiDi order** — `User 42 من الرياض` ends up with `42` on the visual left
|
|
74
|
+
and Arabic letters in their connected form, per UAX #9.
|
|
75
|
+
- **Tashkeel preserved** — diacritics survive; `مَرْحَبًا` round-trips intact.
|
|
76
|
+
- **Logical CSS only** — `margin-inline-start`, never `margin-left`.
|
|
77
|
+
- **Real Arabic fonts** — Tajawal, IBM Plex Sans Arabic, Noto Naskh Arabic
|
|
78
|
+
in priority order; never Inter or Roboto.
|
|
79
|
+
|
|
80
|
+
## What's in the box
|
|
81
|
+
|
|
82
|
+
| Path | What it is |
|
|
83
|
+
|---|---|
|
|
84
|
+
| `arabic_fix/` | Python library: `fix()`, `shape()`, `reorder()`, `normalize()` |
|
|
85
|
+
| `agents/system_prompt.md` | 3 splice-in-able sections for any LLM |
|
|
86
|
+
| `agents/eval_cases.md` | 15 cases to verify the system prompt works |
|
|
87
|
+
| `designs/tokens.json` | 73 design tokens (W3C DTCG), CSS / Tailwind / Figma exports |
|
|
88
|
+
| `examples/sample-arabic-page.html` | 5 Arabic surfaces using the tokens |
|
|
89
|
+
| `docs/roadmap.md` | v0.2 → v0.6 milestones |
|
|
90
|
+
|
|
91
|
+
## Verify
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
pytest -q # 169 tests
|
|
95
|
+
mypy arabic_fix # strict, clean
|
|
96
|
+
python designs/validate_tokens.py # 73 token schema check
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
## License
|
|
100
|
+
|
|
101
|
+
MIT — see [LICENSE](LICENSE). The brand `arabic-fix` is locked until v1.0.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# arabic-fix
|
|
2
|
+
|
|
3
|
+
> Fix Arabic text rendering across code, AI agents, and designs.
|
|
4
|
+
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
[]()
|
|
7
|
+
[]()
|
|
8
|
+
|
|
9
|
+
**One library, one CLI, one system prompt.** Letter-shaping, BiDi reordering,
|
|
10
|
+
Unicode normalization, and a 3-section prompt template for any LLM. Arabic
|
|
11
|
+
flows through terminals, AI agents, log files, and PDFs the way it should.
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install arabic-fix
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from arabic_fix import fix
|
|
19
|
+
print(fix("User 42 من الرياض at 09:30"))
|
|
20
|
+
# → a properly shaped, correctly ordered, NFC-normalized string
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
# CLI
|
|
25
|
+
cat arabic.txt | arabic-fix
|
|
26
|
+
arabic-fix --check file.txt # CI mode: exit non-zero if changes needed
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```text
|
|
30
|
+
# AI agent: paste one of the 3 sections from agents/system_prompt.md
|
|
31
|
+
# A · Read Arabic — for agents that parse / summarize / classify
|
|
32
|
+
# B · Write Arabic — for agents that emit to terminal / log / email
|
|
33
|
+
# C · Design Arabic — for HTML / CSS / Tailwind / design tokens
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
## Why
|
|
37
|
+
|
|
38
|
+
- **Letter shaping** — `ا ب ت` (isolated forms) become `اتصال` (connected) via
|
|
39
|
+
Unicode Presentation Forms-B.
|
|
40
|
+
- **BiDi order** — `User 42 من الرياض` ends up with `42` on the visual left
|
|
41
|
+
and Arabic letters in their connected form, per UAX #9.
|
|
42
|
+
- **Tashkeel preserved** — diacritics survive; `مَرْحَبًا` round-trips intact.
|
|
43
|
+
- **Logical CSS only** — `margin-inline-start`, never `margin-left`.
|
|
44
|
+
- **Real Arabic fonts** — Tajawal, IBM Plex Sans Arabic, Noto Naskh Arabic
|
|
45
|
+
in priority order; never Inter or Roboto.
|
|
46
|
+
|
|
47
|
+
## What's in the box
|
|
48
|
+
|
|
49
|
+
| Path | What it is |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `arabic_fix/` | Python library: `fix()`, `shape()`, `reorder()`, `normalize()` |
|
|
52
|
+
| `agents/system_prompt.md` | 3 splice-in-able sections for any LLM |
|
|
53
|
+
| `agents/eval_cases.md` | 15 cases to verify the system prompt works |
|
|
54
|
+
| `designs/tokens.json` | 73 design tokens (W3C DTCG), CSS / Tailwind / Figma exports |
|
|
55
|
+
| `examples/sample-arabic-page.html` | 5 Arabic surfaces using the tokens |
|
|
56
|
+
| `docs/roadmap.md` | v0.2 → v0.6 milestones |
|
|
57
|
+
|
|
58
|
+
## Verify
|
|
59
|
+
|
|
60
|
+
```bash
|
|
61
|
+
pytest -q # 169 tests
|
|
62
|
+
mypy arabic_fix # strict, clean
|
|
63
|
+
python designs/validate_tokens.py # 73 token schema check
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## License
|
|
67
|
+
|
|
68
|
+
MIT — see [LICENSE](LICENSE). The brand `arabic-fix` is locked until v1.0.
|
|
@@ -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"
|
|
@@ -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"]
|
|
@@ -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())
|
|
@@ -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"]
|