mojifix 0.1.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.
- mojifix/__init__.py +10 -0
- mojifix/__main__.py +8 -0
- mojifix/cli.py +230 -0
- mojifix/core.py +125 -0
- mojifix/detect.py +52 -0
- mojifix/names.py +155 -0
- mojifix/paths.py +43 -0
- mojifix/py.typed +0 -0
- mojifix/repair.py +18 -0
- mojifix/score.py +206 -0
- mojifix/search.py +33 -0
- mojifix/zipnames.py +273 -0
- mojifix-0.1.0.dist-info/METADATA +235 -0
- mojifix-0.1.0.dist-info/RECORD +17 -0
- mojifix-0.1.0.dist-info/WHEEL +4 -0
- mojifix-0.1.0.dist-info/entry_points.txt +2 -0
- mojifix-0.1.0.dist-info/licenses/LICENSE +21 -0
mojifix/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# パッケージの入口。公開 API(fix / candidates / explain / looks_garbled / Candidate)を並べる。
|
|
2
|
+
# 依存は標準ライブラリだけ(INV-6)。ネットワークは使わない(INV-5)。
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from .core import Candidate, candidates, explain, fix
|
|
7
|
+
from .detect import looks_garbled
|
|
8
|
+
|
|
9
|
+
__all__ = ["Candidate", "candidates", "explain", "fix", "looks_garbled"]
|
|
10
|
+
__version__ = "0.1.0"
|
mojifix/__main__.py
ADDED
mojifix/cli.py
ADDED
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# コマンドライン: mojifix text / names / zip(§9.4)。終了コードは §9.5(0 成功・1 使い方・2 一部を飛ばした・
|
|
2
|
+
# 3 入力が読めない)。--json で機械が読める形を出す。出力の文字コードで表せない字は \uXXXX にして落ちない。
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import io
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
import zipfile
|
|
11
|
+
from collections.abc import Sequence
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, NoReturn
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .core import REPLACEMENT, best_fix, candidates, describe_path, explain
|
|
17
|
+
from .names import rename_all, scan, undo
|
|
18
|
+
from .score import score
|
|
19
|
+
from .zipnames import ExtractError, extract, read_names
|
|
20
|
+
|
|
21
|
+
OK, USAGE, SKIPPED, UNREADABLE = 0, 1, 2, 3
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class _Parser(argparse.ArgumentParser):
|
|
25
|
+
def error(self, message: str) -> NoReturn: # argparse の既定は 2。§9.5 の「使い方の誤り」は 1
|
|
26
|
+
self.print_usage(sys.stderr)
|
|
27
|
+
self.exit(USAGE, f"{self.prog}: error: {message}\n")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _setup_stdio() -> None:
|
|
31
|
+
for stream in (sys.stdout, sys.stderr):
|
|
32
|
+
if isinstance(stream, io.TextIOWrapper):
|
|
33
|
+
stream.reconfigure(errors="backslashreplace")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _utf8_stdout() -> bool:
|
|
37
|
+
enc = (getattr(sys.stdout, "encoding", None) or "").lower().replace("-", "").replace("_", "")
|
|
38
|
+
return enc in ("utf8", "utf8sig")
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _emit_json(obj: Any) -> None:
|
|
42
|
+
print(json.dumps(obj, ensure_ascii=not _utf8_stdout(), indent=2))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _path_json(path: tuple[tuple[str, str], ...]) -> list[list[str]]:
|
|
46
|
+
return [list(p) for p in path]
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def cmd_text(args: argparse.Namespace) -> int:
|
|
50
|
+
text: str = args.string
|
|
51
|
+
cs = candidates(text)
|
|
52
|
+
best = best_fix(text)
|
|
53
|
+
lost = REPLACEMENT in text
|
|
54
|
+
if args.json:
|
|
55
|
+
shown = cs if args.all else cs[:1]
|
|
56
|
+
_emit_json({
|
|
57
|
+
"input": text,
|
|
58
|
+
"output": best.text if best else text,
|
|
59
|
+
"changed": best is not None,
|
|
60
|
+
"input_score": round(score(text), 4),
|
|
61
|
+
"lost_bytes": lost,
|
|
62
|
+
"explain": {"ja": explain(text, "ja"), "en": explain(text, "en")},
|
|
63
|
+
"candidates": [{"text": c.text, "path": _path_json(c.path), "score": round(c.score, 4)}
|
|
64
|
+
for c in shown],
|
|
65
|
+
})
|
|
66
|
+
return OK
|
|
67
|
+
print(f"input: {text}")
|
|
68
|
+
if lost:
|
|
69
|
+
print(f"result: {explain(text, 'en')}")
|
|
70
|
+
return OK
|
|
71
|
+
if not cs:
|
|
72
|
+
print("result: no candidate (nothing to repair)")
|
|
73
|
+
return OK
|
|
74
|
+
top = cs[0]
|
|
75
|
+
print(f"output: {best.text if best else text}")
|
|
76
|
+
print(f"top: {top.text}")
|
|
77
|
+
print(f"path: {describe_path(top.path, 'en')}")
|
|
78
|
+
print(f"score: {score(text):.3f} -> {top.score:.3f}")
|
|
79
|
+
if best is None:
|
|
80
|
+
print("result: not replaced (the top candidate is not clearly better)")
|
|
81
|
+
if args.all:
|
|
82
|
+
print("candidates:")
|
|
83
|
+
for c in cs:
|
|
84
|
+
print(f" {c.score:7.3f} {c.text} [{' <- '.join(f'{w}->{r}' for w, r in c.path)}]")
|
|
85
|
+
return OK
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def cmd_names(args: argparse.Namespace) -> int:
|
|
89
|
+
if args.undo is not None:
|
|
90
|
+
if args.folder is not None or args.apply or args.log or args.recursive:
|
|
91
|
+
raise _UsageError("--undo cannot be combined with a folder, --apply, --log or --recursive")
|
|
92
|
+
log = Path(args.undo)
|
|
93
|
+
try:
|
|
94
|
+
outcomes = undo(log)
|
|
95
|
+
except (OSError, ValueError, KeyError) as e:
|
|
96
|
+
print(f"mojifix: cannot read the log: {e}", file=sys.stderr)
|
|
97
|
+
return UNREADABLE
|
|
98
|
+
skipped = [o for o in outcomes if not o.done]
|
|
99
|
+
if args.json:
|
|
100
|
+
_emit_json([{"from": str(o.old), "to": str(o.new) if o.new else None, "done": o.done,
|
|
101
|
+
"reason": o.reason} for o in outcomes])
|
|
102
|
+
else:
|
|
103
|
+
for o in outcomes:
|
|
104
|
+
mark = "restored" if o.done else f"skipped ({o.reason})"
|
|
105
|
+
print(f"{mark}: {o.old} -> {o.new}")
|
|
106
|
+
return SKIPPED if skipped else OK
|
|
107
|
+
if args.folder is None:
|
|
108
|
+
raise _UsageError("a folder (or --undo <log>) is required")
|
|
109
|
+
if args.log and not args.apply:
|
|
110
|
+
raise _UsageError("--log needs --apply")
|
|
111
|
+
folder = Path(args.folder)
|
|
112
|
+
try:
|
|
113
|
+
proposals = scan(folder, args.recursive)
|
|
114
|
+
except OSError as e:
|
|
115
|
+
print(f"mojifix: cannot read the folder: {e}", file=sys.stderr)
|
|
116
|
+
return UNREADABLE
|
|
117
|
+
try:
|
|
118
|
+
outcomes = rename_all(proposals, Path(args.log) if args.log else None) if args.apply else []
|
|
119
|
+
except FileExistsError: # ログは名前を変える前に作るので、ここでは何も変えていない
|
|
120
|
+
raise _UsageError(f"the log file already exists (choose a new name): {args.log}") from None
|
|
121
|
+
except OSError as e:
|
|
122
|
+
print(f"mojifix: cannot create the log (nothing was renamed): {e}", file=sys.stderr)
|
|
123
|
+
return UNREADABLE
|
|
124
|
+
result = {o.old: o for o in outcomes}
|
|
125
|
+
rows = []
|
|
126
|
+
for p in proposals:
|
|
127
|
+
res = result.get(p.path)
|
|
128
|
+
status = "unrecoverable" if p.new_name is None else ("proposed" if res is None else
|
|
129
|
+
"renamed" if res.done else "skipped")
|
|
130
|
+
rows.append({"path": p.path.relative_to(folder).as_posix(), "old": p.path.name, "new": p.new_name,
|
|
131
|
+
"status": status, "note": res.reason if (res and not res.done) else p.note})
|
|
132
|
+
if args.json:
|
|
133
|
+
_emit_json(rows)
|
|
134
|
+
else:
|
|
135
|
+
if not rows:
|
|
136
|
+
print("no garbled names found")
|
|
137
|
+
for r in rows:
|
|
138
|
+
new = r["new"] if r["new"] is not None else "(" + str(r["note"]) + ")"
|
|
139
|
+
line = f"{r['path']} -> {new}"
|
|
140
|
+
if r["status"] in ("renamed", "skipped"):
|
|
141
|
+
line += f" [{r['status']}" + (f": {r['note']}" if r["status"] == "skipped" else "") + "]"
|
|
142
|
+
print(line)
|
|
143
|
+
return SKIPPED if any(not o.done for o in outcomes) else OK
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def cmd_zip(args: argparse.Namespace) -> int:
|
|
147
|
+
zpath = Path(args.file)
|
|
148
|
+
try:
|
|
149
|
+
if args.extract is not None:
|
|
150
|
+
results = extract(zpath, Path(args.extract))
|
|
151
|
+
members = [e.member for e in results]
|
|
152
|
+
else:
|
|
153
|
+
results = []
|
|
154
|
+
members = read_names(zpath)
|
|
155
|
+
except ExtractError as e:
|
|
156
|
+
print(f"mojifix: {e}", file=sys.stderr)
|
|
157
|
+
return e.code
|
|
158
|
+
except (OSError, zipfile.BadZipFile, zipfile.LargeZipFile, NotImplementedError, EOFError) as e:
|
|
159
|
+
print(f"mojifix: cannot read the ZIP file: {e}", file=sys.stderr)
|
|
160
|
+
return UNREADABLE
|
|
161
|
+
status = {id(e.member): e for e in results}
|
|
162
|
+
rows = []
|
|
163
|
+
for m in members:
|
|
164
|
+
ex = status.get(id(m))
|
|
165
|
+
rows.append({
|
|
166
|
+
"name": m.shown, "fixed": m.fixed, "utf8_flag": m.utf8,
|
|
167
|
+
"path": _path_json(m.path), "unsafe": m.unsafe,
|
|
168
|
+
"extracted": (ex.done if ex else None), "note": (ex.reason if ex and not ex.done else None),
|
|
169
|
+
})
|
|
170
|
+
if args.json:
|
|
171
|
+
_emit_json(rows)
|
|
172
|
+
else:
|
|
173
|
+
for r in rows:
|
|
174
|
+
if r["utf8_flag"]:
|
|
175
|
+
line = f"{r['name']} [UTF-8 flag: not a target]"
|
|
176
|
+
elif r["fixed"] is not None:
|
|
177
|
+
line = f"{r['name']} -> {r['fixed']}"
|
|
178
|
+
else:
|
|
179
|
+
line = f"{r['name']}"
|
|
180
|
+
if r["unsafe"]:
|
|
181
|
+
line += f" [unsafe: {r['unsafe']}]"
|
|
182
|
+
if r["note"]:
|
|
183
|
+
line += f" [{r['note']}]"
|
|
184
|
+
print(line)
|
|
185
|
+
return SKIPPED if any(not r.done for r in results) else OK
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
class _UsageError(Exception):
|
|
189
|
+
pass
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
193
|
+
ap = _Parser(prog="mojifix", description="Repair Japanese mojibake strictly (text, file names, ZIP names).")
|
|
194
|
+
ap.add_argument("--version", action="version", version=f"mojifix {__version__}")
|
|
195
|
+
sub = ap.add_subparsers(dest="command", required=True)
|
|
196
|
+
|
|
197
|
+
t = sub.add_parser("text", help="repair a string")
|
|
198
|
+
t.add_argument("string")
|
|
199
|
+
t.add_argument("--all", action="store_true", help="show every candidate")
|
|
200
|
+
t.add_argument("--json", action="store_true")
|
|
201
|
+
t.set_defaults(func=cmd_text)
|
|
202
|
+
|
|
203
|
+
n = sub.add_parser("names", help="list (and with --apply, rename) garbled file and folder names")
|
|
204
|
+
n.add_argument("folder", nargs="?")
|
|
205
|
+
n.add_argument("--recursive", action="store_true")
|
|
206
|
+
n.add_argument("--apply", action="store_true", help="actually rename (default: list only)")
|
|
207
|
+
n.add_argument("--log", help="with --apply: write old/new names as JSON Lines")
|
|
208
|
+
n.add_argument("--undo", metavar="LOG", help="rename back as recorded in LOG")
|
|
209
|
+
n.add_argument("--json", action="store_true")
|
|
210
|
+
n.set_defaults(func=cmd_names)
|
|
211
|
+
|
|
212
|
+
z = sub.add_parser("zip", help="list (and with --extract, extract) ZIP members with repaired names")
|
|
213
|
+
z.add_argument("file")
|
|
214
|
+
z.add_argument("--extract", metavar="FOLDER", help="extract with the repaired names")
|
|
215
|
+
z.add_argument("--json", action="store_true")
|
|
216
|
+
z.set_defaults(func=cmd_zip)
|
|
217
|
+
return ap
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
221
|
+
_setup_stdio()
|
|
222
|
+
ap = build_parser()
|
|
223
|
+
args = ap.parse_args(argv)
|
|
224
|
+
try:
|
|
225
|
+
code: int = args.func(args)
|
|
226
|
+
except _UsageError as e:
|
|
227
|
+
ap.print_usage(sys.stderr)
|
|
228
|
+
print(f"mojifix: error: {e}", file=sys.stderr)
|
|
229
|
+
return USAGE
|
|
230
|
+
return code
|
mojifix/core.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
# 公開 API の本体: candidates / fix / explain。候補を点数で並べ、閾値で置き換えを決める。
|
|
2
|
+
# 置き換えない時は元の文字列をそのまま返す(INV-2)。U+FFFD を含む物は戻さない(FR-5)。
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import re
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from .paths import Path, display_name
|
|
10
|
+
from .score import GARBLED_THRESHOLD, SCORE_SAMPLE_CHARS, THRESHOLD, score, should_replace
|
|
11
|
+
from .search import MAX_DEPTH, search
|
|
12
|
+
|
|
13
|
+
REPLACEMENT = chr(0xFFFD) # U+FFFD REPLACEMENT CHARACTER
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Candidate:
|
|
18
|
+
"""修復の候補。path は ((誤って読んだ文字コード, 本来の文字コード), ...) で、適用した順。"""
|
|
19
|
+
|
|
20
|
+
text: str
|
|
21
|
+
path: tuple[Path, ...]
|
|
22
|
+
score: float
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _head(text: str) -> str:
|
|
26
|
+
return text[:SCORE_SAMPLE_CHARS]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def candidates(text: str, max_depth: int = MAX_DEPTH) -> list[Candidate]:
|
|
30
|
+
"""道を1段・2段で試し、厳密に戻せた候補を点数の高い順に返す(FR-1)。
|
|
31
|
+
|
|
32
|
+
同点なら段数の少ない方、同じ段数なら §9.2 の表の上の行が先。
|
|
33
|
+
U+FFFD を含む文字列は、失われたバイトがあるので空を返す(FR-5)。
|
|
34
|
+
長い文字列は先頭の SCORE_SAMPLE_CHARS 文字で点数をつける(§10)。
|
|
35
|
+
"""
|
|
36
|
+
if not text or REPLACEMENT in text:
|
|
37
|
+
return []
|
|
38
|
+
found = [Candidate(t, p, score(_head(t))) for t, p in search(text, max_depth)]
|
|
39
|
+
found.sort(key=lambda c: -c.score) # 安定ソート: 同点は search の順(短い道・表の順)
|
|
40
|
+
return found
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
# 半角カナと ASCII(と空白類)だけの文字列。
|
|
44
|
+
_HALF_KANA_ASCII = re.compile("[\t\n\r -~" + chr(0xFF61) + "-" + chr(0xFF9F) + "]*")
|
|
45
|
+
# 最上位の候補そのものが文字化けらしければ置き換えない(choose)。較正で効き目を測るための切り替え。
|
|
46
|
+
REJECT_GARBLED_TOP = True
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def fix_allowed(text: str, path: tuple[Path, ...]) -> bool:
|
|
50
|
+
"""fix() が採ってよい道か。採らない道の候補も candidates() には出す。
|
|
51
|
+
|
|
52
|
+
半角カナと ASCII だけの文字列を EUC-JP として読み直す道は採らない。「オオサカ・タナカ」の「・」(A5)「、」(A4)が
|
|
53
|
+
EUC-JP のかなの1バイト目になり、普通の名前が「亀散ダ填」のような文字列に変わるため(docs/calibration.md)。
|
|
54
|
+
"""
|
|
55
|
+
return not (path[0] == ("cp932", "euc_jp") and _HALF_KANA_ASCII.fullmatch(text) is not None)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def top_looks_garbled(text: str) -> bool:
|
|
59
|
+
"""候補そのものが文字化けらしいか(garbled_score が閾値以上)。"""
|
|
60
|
+
from .detect import garbled_score # detect は core を使うので、ここで読む
|
|
61
|
+
|
|
62
|
+
return garbled_score(text) >= GARBLED_THRESHOLD
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def choose(text: str, found: list[Candidate], threshold: float | None = None) -> Candidate | None:
|
|
66
|
+
"""点数の高い順の候補 found から、text を置き換える候補を選ぶ。置き換えない時は None。
|
|
67
|
+
|
|
68
|
+
最上位が元より threshold 以上・次点より AMBIG_MARGIN 以上高く(D-5)、最上位そのものが文字化けらしく
|
|
69
|
+
見えない時だけ。
|
|
70
|
+
"""
|
|
71
|
+
if threshold is None:
|
|
72
|
+
threshold = THRESHOLD
|
|
73
|
+
if not found or not should_replace(score(_head(text)), [c.score for c in found], threshold):
|
|
74
|
+
return None
|
|
75
|
+
if REJECT_GARBLED_TOP and top_looks_garbled(found[0].text):
|
|
76
|
+
return None
|
|
77
|
+
return found[0]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def best_fix(text: str, threshold: float | None = None) -> Candidate | None:
|
|
81
|
+
"""fix() が採る候補。置き換えない時は None。"""
|
|
82
|
+
return choose(text, [c for c in candidates(text) if fix_allowed(text, c.path)], threshold)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def fix(text: str, threshold: float | None = None) -> str:
|
|
86
|
+
"""最上位の候補の点数が元の文字列より threshold 以上高ければ候補を、そうでなければ text を返す(FR-2)。
|
|
87
|
+
|
|
88
|
+
threshold が None なら較正した既定値(score.THRESHOLD)。
|
|
89
|
+
"""
|
|
90
|
+
best = best_fix(text, threshold)
|
|
91
|
+
return text if best is None else best.text
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_LOST = {
|
|
95
|
+
"ja": "バイトが失われていて戻せない(U+FFFD を含む)",
|
|
96
|
+
"en": "Bytes were lost (contains U+FFFD); it cannot be restored",
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def describe_path(path: tuple[Path, ...], lang: str = "ja") -> str:
|
|
101
|
+
"""道の並びを短い文にする。2段なら、起きた順(元に近い方から)に並べる。"""
|
|
102
|
+
if lang not in ("ja", "en"):
|
|
103
|
+
raise ValueError(f"lang must be 'ja' or 'en': {lang!r}")
|
|
104
|
+
# path は戻す順。化けが起きた順はその逆。
|
|
105
|
+
steps = list(reversed(path))
|
|
106
|
+
if lang == "ja":
|
|
107
|
+
parts = [f"{display_name(r)} を {display_name(w)} として読" for w, r in steps]
|
|
108
|
+
return "み、その結果の ".join(parts) + "んだ文字化け"
|
|
109
|
+
parts = [f"{display_name(r)} bytes read as {display_name(w)}" for w, r in steps]
|
|
110
|
+
return "Mojibake: " + ", then ".join(parts)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def explain(text: str, lang: str = "ja") -> str | None:
|
|
114
|
+
"""fix() が採る候補の道を短い文で返す(FR-3)。置き換えない時は None。
|
|
115
|
+
|
|
116
|
+
U+FFFD を含む文字列には「バイトが失われていて戻せない」を返す(FR-5)。
|
|
117
|
+
"""
|
|
118
|
+
if lang not in ("ja", "en"):
|
|
119
|
+
raise ValueError(f"lang must be 'ja' or 'en': {lang!r}")
|
|
120
|
+
if REPLACEMENT in text:
|
|
121
|
+
return _LOST[lang]
|
|
122
|
+
best = best_fix(text)
|
|
123
|
+
if best is None:
|
|
124
|
+
return None
|
|
125
|
+
return describe_path(best.path, lang)
|
mojifix/detect.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
# looks_garbled(text): 文字化けらしさの判定。修復はしない(FR-4)。
|
|
2
|
+
# 厳密に戻せる物に加え、バイトが欠けて厳密には戻らない化け・一部だけ化けた物も拾うため、判定にだけ
|
|
3
|
+
# errors="replace" を使う。ここで作った文字列は返さない(修復は core.py の厳密な道だけ。INV-1)。
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import re
|
|
8
|
+
|
|
9
|
+
from .core import REPLACEMENT, best_fix, fix_allowed
|
|
10
|
+
from .paths import PATHS
|
|
11
|
+
from .score import GARBLED_THRESHOLD, SCORE_SAMPLE_CHARS, score
|
|
12
|
+
|
|
13
|
+
# 部分ごとに見る時の区切り: ASCII の空白・句読点・括弧(ファイル名の「_」「-」「.」を含む)。
|
|
14
|
+
_SPLIT = re.compile(r"[\s!-/:-@\[-`{-~]+")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _loose_gain(text: str) -> float:
|
|
18
|
+
"""1段の道で緩く読み直した文字列の点数が、元よりどれだけ上がるかの最大(上がらなければ 0)。"""
|
|
19
|
+
base = score(text)
|
|
20
|
+
best = 0.0
|
|
21
|
+
for wrong, right in PATHS:
|
|
22
|
+
if not fix_allowed(text, ((wrong, right),)): # fix() が採らない道は、化けの判定にも使わない
|
|
23
|
+
continue
|
|
24
|
+
try:
|
|
25
|
+
raw = text.encode(wrong, errors="strict")
|
|
26
|
+
except UnicodeEncodeError:
|
|
27
|
+
continue
|
|
28
|
+
loose = raw.decode(right, errors="replace") # 判定だけに使う(INV-1 の対象外)
|
|
29
|
+
if loose != text:
|
|
30
|
+
best = max(best, score(loose) - base)
|
|
31
|
+
return best
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def garbled_score(text: str) -> float:
|
|
35
|
+
"""文字化けらしさ。文字列全体と、区切りで割った各部分(2文字以上・ASCII 以外を含む)の _loose_gain の最大。
|
|
36
|
+
|
|
37
|
+
緩く読み直す時に出た U+FFFD は点数を下げる(区分 OTHER)ので、大半が読み違いで説明できる時だけ高くなる。
|
|
38
|
+
"""
|
|
39
|
+
head = text[:SCORE_SAMPLE_CHARS]
|
|
40
|
+
parts = [head, *(p for p in _SPLIT.split(head) if len(p) >= 2 and not p.isascii())]
|
|
41
|
+
return max(_loose_gain(p) for p in dict.fromkeys(parts))
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def looks_garbled(text: str) -> bool:
|
|
45
|
+
"""文字化けらしければ True。U+FFFD を含む物・fix() が直す物・garbled_score が閾値以上の物。"""
|
|
46
|
+
if not text or (text.isascii() and text.isprintable()):
|
|
47
|
+
return False
|
|
48
|
+
if REPLACEMENT in text:
|
|
49
|
+
return True
|
|
50
|
+
if best_fix(text) is not None:
|
|
51
|
+
return True
|
|
52
|
+
return garbled_score(text) >= GARBLED_THRESHOLD
|
mojifix/names.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# フォルダの中のファイル名・フォルダ名の文字化けを探し、直した名前の一覧を作る。既定では書かない(D-7)。
|
|
2
|
+
# rename_all は深い方から名前を変え、既にある名前・Windows で使えない名前・開いている物は1件ずつ飛ばす。
|
|
3
|
+
# 変えた名前は JSON Lines に残せ、undo でその通りに戻す(FR-9・FR-10)。
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
from collections.abc import Iterable
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .core import REPLACEMENT, best_fix, explain
|
|
15
|
+
from .detect import looks_garbled
|
|
16
|
+
|
|
17
|
+
_BAD_CHARS = re.compile(r'[\\/:*?"<>|\x00-\x1f]')
|
|
18
|
+
_RESERVED = re.compile(r"^(CON|PRN|AUX|NUL|COM[0-9¹²³]|LPT[0-9¹²³])(\..*)?$", re.IGNORECASE)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def invalid_name_reason(name: str) -> str | None:
|
|
22
|
+
"""Windows でファイル名に使えない理由。使えれば None。どの OS でも同じ規則で調べる。"""
|
|
23
|
+
if not name or name in (".", ".."):
|
|
24
|
+
return "empty or dot name"
|
|
25
|
+
m = _BAD_CHARS.search(name)
|
|
26
|
+
if m:
|
|
27
|
+
return f"contains a character not allowed on Windows: {m.group()!r}"
|
|
28
|
+
if _RESERVED.match(name.rstrip(" .")):
|
|
29
|
+
return "reserved name on Windows (CON, NUL, COM1, ...)"
|
|
30
|
+
if name[-1] in " .":
|
|
31
|
+
return "ends with a space or a dot"
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
@dataclass(frozen=True)
|
|
36
|
+
class Proposal:
|
|
37
|
+
"""文字化けらしい名前1つ。new_name が None なら戻せない(note に理由)。"""
|
|
38
|
+
|
|
39
|
+
path: Path
|
|
40
|
+
new_name: str | None
|
|
41
|
+
note: str
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def depth(self) -> int:
|
|
45
|
+
return len(self.path.parts)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _propose(path: Path) -> Proposal:
|
|
49
|
+
name = path.name
|
|
50
|
+
best = best_fix(name)
|
|
51
|
+
if best is not None:
|
|
52
|
+
return Proposal(path, best.text, explain(name, "en") or "")
|
|
53
|
+
if REPLACEMENT in name:
|
|
54
|
+
return Proposal(path, None, "cannot restore: bytes were lost (contains U+FFFD)")
|
|
55
|
+
return Proposal(path, None, "looks garbled, but no strict repair was found")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def scan(folder: Path, recursive: bool = False) -> list[Proposal]:
|
|
59
|
+
"""folder の下の名前のうち looks_garbled が真の物を、見つけた順に返す。何も書かない(INV-3)。"""
|
|
60
|
+
if not folder.is_dir():
|
|
61
|
+
raise NotADirectoryError(str(folder))
|
|
62
|
+
entries: Iterable[Path]
|
|
63
|
+
if recursive:
|
|
64
|
+
found: list[Path] = []
|
|
65
|
+
for root, dirs, files in os.walk(folder):
|
|
66
|
+
dirs.sort()
|
|
67
|
+
found.extend(Path(root) / n for n in sorted(dirs + files))
|
|
68
|
+
entries = found
|
|
69
|
+
else:
|
|
70
|
+
entries = sorted(folder.iterdir())
|
|
71
|
+
return [_propose(p) for p in entries if looks_garbled(p.name)]
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class Outcome:
|
|
76
|
+
old: Path
|
|
77
|
+
new: Path | None
|
|
78
|
+
done: bool
|
|
79
|
+
reason: str
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _rename_one(old: Path, new: Path) -> Outcome:
|
|
83
|
+
reason = invalid_name_reason(new.name)
|
|
84
|
+
if reason:
|
|
85
|
+
return Outcome(old, new, False, reason)
|
|
86
|
+
if not os.path.lexists(old):
|
|
87
|
+
return Outcome(old, new, False, "source no longer exists")
|
|
88
|
+
if os.path.lexists(new):
|
|
89
|
+
return Outcome(old, new, False, "a file or folder with the new name already exists")
|
|
90
|
+
try:
|
|
91
|
+
# os.rename は POSIX では既にある物を上書きするので、直前に lexists で確かめている。
|
|
92
|
+
# ponytail: 確かめてから変えるまでの間に別のプロセスが同じ名前を作れば上書きされうる(TOCTOU)。
|
|
93
|
+
os.rename(old, new)
|
|
94
|
+
except OSError as e: # 開いている(Windows の PermissionError)・権限が無い など
|
|
95
|
+
return Outcome(old, new, False, f"{type(e).__name__}: {e.strerror or e}")
|
|
96
|
+
return Outcome(old, new, True, "renamed")
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def rename_all(proposals: list[Proposal], log: Path | None = None) -> list[Outcome]:
|
|
100
|
+
"""直した名前がある物だけ、深い方から名前を変える(子より先に親を変えてパスがずれないように)。
|
|
101
|
+
|
|
102
|
+
log は名前を変える前に新しく作る。既にあれば FileExistsError、作れなければ OSError で、何も変えない。
|
|
103
|
+
ログには絶対パスを書く(別の作業フォルダから undo しても戻せるように)。
|
|
104
|
+
"""
|
|
105
|
+
todo = sorted((p for p in proposals if p.new_name is not None), key=lambda p: -p.depth)
|
|
106
|
+
outcomes: list[Outcome] = []
|
|
107
|
+
logf = log.open("x", encoding="utf-8") if log is not None else None
|
|
108
|
+
try:
|
|
109
|
+
for p in todo:
|
|
110
|
+
assert p.new_name is not None
|
|
111
|
+
# 深い方から変えるので、この時点で親はまだ元の名前のまま(絶対パスにできる)。
|
|
112
|
+
parent = p.path.parent.resolve()
|
|
113
|
+
o = _rename_one(p.path, p.path.with_name(p.new_name))
|
|
114
|
+
outcomes.append(o)
|
|
115
|
+
if o.done and logf is not None and o.new is not None:
|
|
116
|
+
rec = {"old": str(parent / o.old.name), "new": str(parent / o.new.name)}
|
|
117
|
+
logf.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
118
|
+
logf.flush()
|
|
119
|
+
finally:
|
|
120
|
+
if logf is not None:
|
|
121
|
+
logf.close()
|
|
122
|
+
return outcomes
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def undo(log: Path) -> list[Outcome]:
|
|
126
|
+
"""rename_all の残したログを後ろから読み、名前を元に戻す。元の名前が既にあればその1件を飛ばす。
|
|
127
|
+
|
|
128
|
+
形の違う行があれば、何も変えずに ValueError(行番号つき)。
|
|
129
|
+
"""
|
|
130
|
+
entries = []
|
|
131
|
+
for no, line in enumerate(log.read_text(encoding="utf-8").splitlines(), 1):
|
|
132
|
+
if not line.strip():
|
|
133
|
+
continue
|
|
134
|
+
try:
|
|
135
|
+
d = json.loads(line)
|
|
136
|
+
except ValueError as e:
|
|
137
|
+
raise ValueError(f"line {no}: not JSON ({e})") from None
|
|
138
|
+
if not (isinstance(d, dict) and isinstance(d.get("old"), str) and isinstance(d.get("new"), str)):
|
|
139
|
+
raise ValueError(f'line {no}: expected {{"old": "...", "new": "..."}}')
|
|
140
|
+
entries.append((Path(d["old"]), Path(d["new"])))
|
|
141
|
+
outcomes = []
|
|
142
|
+
for old, new in reversed(entries):
|
|
143
|
+
if not os.path.lexists(new):
|
|
144
|
+
outcomes.append(Outcome(new, old, False, "renamed file no longer exists"))
|
|
145
|
+
continue
|
|
146
|
+
if os.path.lexists(old):
|
|
147
|
+
outcomes.append(Outcome(new, old, False, "the original name already exists"))
|
|
148
|
+
continue
|
|
149
|
+
try:
|
|
150
|
+
os.rename(new, old)
|
|
151
|
+
except OSError as e:
|
|
152
|
+
outcomes.append(Outcome(new, old, False, f"{type(e).__name__}: {e.strerror or e}"))
|
|
153
|
+
continue
|
|
154
|
+
outcomes.append(Outcome(new, old, True, "restored"))
|
|
155
|
+
return outcomes
|
mojifix/paths.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# 読み違いの道(誤って読んだ文字コード, 本来の文字コード)の表。仕様書 §9.2 の順。
|
|
2
|
+
# 表の上の行ほど、同点の候補で優先される(§10)。
|
|
3
|
+
# 表に足すのは、見本で実際に起きた道だけ(D-1)。
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
Path = tuple[str, str]
|
|
8
|
+
|
|
9
|
+
# (wrong, right): 本来 right で符号化されたバイトを、wrong で復号してしまった。
|
|
10
|
+
PATHS: tuple[Path, ...] = (
|
|
11
|
+
("cp932", "utf-8"),
|
|
12
|
+
("latin-1", "utf-8"),
|
|
13
|
+
("cp1252", "utf-8"),
|
|
14
|
+
("latin-1", "cp932"),
|
|
15
|
+
("cp1252", "cp932"),
|
|
16
|
+
("cp437", "cp932"),
|
|
17
|
+
("cp437", "utf-8"),
|
|
18
|
+
("cp932", "euc_jp"),
|
|
19
|
+
("latin-1", "euc_jp"),
|
|
20
|
+
# エスケープ(ESC $B …)が文字として残った ISO-2022-JP を読み直す道(§9.2 の下の注)。
|
|
21
|
+
("ascii", "iso2022_jp"),
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
_NAMES = {
|
|
25
|
+
"cp932": "CP932",
|
|
26
|
+
"utf-8": "UTF-8",
|
|
27
|
+
"latin-1": "Latin-1",
|
|
28
|
+
"cp1252": "CP1252",
|
|
29
|
+
"cp437": "CP437",
|
|
30
|
+
"euc_jp": "EUC-JP",
|
|
31
|
+
"iso2022_jp": "ISO-2022-JP",
|
|
32
|
+
"ascii": "ASCII",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def display_name(codec: str) -> str:
|
|
37
|
+
"""codec 名を人が読む名前にする(例: "euc_jp" → "EUC-JP")。"""
|
|
38
|
+
return _NAMES.get(codec, codec)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def path_rank(path: Path) -> int:
|
|
42
|
+
"""表の中の行の番号(上ほど小さい)。"""
|
|
43
|
+
return PATHS.index(path)
|
mojifix/py.typed
ADDED
|
File without changes
|
mojifix/repair.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# 1段の修復: text.encode(誤, strict).decode(本来, strict)。失われたバイトは推測しない。
|
|
2
|
+
# 1バイトでも戻らなければ None を返す(D-2・INV-1)。errors="replace" 等は使わない。
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
from .paths import Path
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def repair(text: str, path: Path) -> str | None:
|
|
10
|
+
"""道 path で1段だけ戻す。厳密に戻らない時・何も変わらない時は None。"""
|
|
11
|
+
wrong, right = path
|
|
12
|
+
try:
|
|
13
|
+
result = text.encode(wrong, errors="strict").decode(right, errors="strict")
|
|
14
|
+
except (UnicodeEncodeError, UnicodeDecodeError):
|
|
15
|
+
return None
|
|
16
|
+
if result == text:
|
|
17
|
+
return None
|
|
18
|
+
return result
|