68 lines
3.4 KiB
Python
Executable File
68 lines
3.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
# charset — detect a file's encoding (UTF-8/16/32, latin-1, ASCII) with a confidence note and a binary verdict.
|
|
# Usage: charset [--verbose] file [...]
|
|
"""charset: encoding detection with reasons, not just a guess. It checks BOMs,
|
|
null-byte patterns (UTF-16/32), strict UTF-8 validity, and the share of
|
|
high-bit bytes — then reports the encoding, a confidence (high/medium/low),
|
|
and whether the file looks binary at all."""
|
|
import argparse, os, sys
|
|
|
|
def detect(data):
|
|
if not data: return "empty", "high", "empty file"
|
|
if data.startswith(b"\xef\xbb\xbf"): return "UTF-8 (BOM)", "high", "UTF-8 BOM present"
|
|
if data.startswith(b"\xff\xfe\x00\x00"): return "UTF-32LE", "high", "UTF-32LE BOM present"
|
|
if data.startswith(b"\x00\x00\xfe\xff"): return "UTF-32BE", "high", "UTF-32BE BOM present"
|
|
if data.startswith(b"\xff\xfe"): return "UTF-16LE", "high", "UTF-16LE BOM present"
|
|
if data.startswith(b"\xfe\xff"): return "UTF-16BE", "high", "UTF-16BE BOM present"
|
|
if b"\x00" in data:
|
|
# nulls every 2nd byte -> UTF-16; every 4th -> UTF-32
|
|
sample = data[:4000]
|
|
if sample[1::2].count(0) > len(sample[1::2]) * 0.7: return "UTF-16LE (no BOM)", "medium", "nulls in odd positions"
|
|
if sample[0::2].count(0) > len(sample[0::2]) * 0.7: return "UTF-16BE (no BOM)", "medium", "nulls in even positions"
|
|
return "binary", "high", "contains NUL bytes, not valid text"
|
|
try:
|
|
data.decode("utf-8")
|
|
if all(b < 128 for b in data): return "ASCII", "high", "all bytes < 128"
|
|
return "UTF-8", "high", "valid UTF-8, has non-ASCII bytes"
|
|
except UnicodeDecodeError:
|
|
pass
|
|
high = sum(1 for b in data if b >= 128)
|
|
frac = high / len(data)
|
|
if frac > 0.3: return "binary", "medium", f"{frac:.0%} high bytes, invalid UTF-8"
|
|
return "latin-1 (ISO-8859-1)", "medium", "invalid UTF-8, low share of high bytes — latin-1 decodes anything"
|
|
|
|
def run(path, verbose=False):
|
|
try: data = open(path, "rb").read()
|
|
except OSError as e: print(f"charset: {path}: {e}", file=sys.stderr); return 1
|
|
enc, conf, why = detect(data)
|
|
print(f"{enc:<24} {conf:<6} {path}" + (f" ({why})" if verbose else ""))
|
|
return 0
|
|
|
|
def selftest():
|
|
import tempfile, os
|
|
with tempfile.TemporaryDirectory() as d:
|
|
cases = [("ascii.txt", b"plain ascii\n", "ASCII"),
|
|
("utf8.txt", "café ☕\n".encode(), "UTF-8"),
|
|
("utf16.txt", "hello\n".encode("utf-16"), "UTF-16"),
|
|
("latin.txt", b"caf\xe9\n", "latin-1"),
|
|
("bin.dat", bytes(range(256)), "binary")]
|
|
for name, data, want in cases:
|
|
p = os.path.join(d, name); open(p, "wb").write(data)
|
|
enc, _, _ = detect(data)
|
|
assert want in enc, f"{name}: got {enc}, want {want}"
|
|
assert run(p) == 0
|
|
print("charset selftest: PASS"); return 0
|
|
|
|
def main():
|
|
ap = argparse.ArgumentParser(description="Detect a file's encoding (UTF-8/16/32, latin-1, ASCII) with confidence and reason.")
|
|
ap.add_argument("files", nargs="*")
|
|
ap.add_argument("--verbose", "-v", action="store_true", help="show why each verdict was reached")
|
|
ap.add_argument("--selftest", action="store_true")
|
|
a = ap.parse_args()
|
|
if a.selftest: return selftest()
|
|
if not a.files: ap.error("need at least one file")
|
|
return max(run(p, a.verbose) for p in a.files)
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|