# -*- coding: utf-8 -*-
# 提取 PDF 文本到 UTF-8 文件 (PyMuPDF), 并解码内嵌字体私有区数字
# 用法: python extract-pdf.py <pdf> <outdir> <起始页> <结束页(含)>
import fitz, sys, os

path, outdir = sys.argv[1], sys.argv[2]
start = int(sys.argv[3]); end = int(sys.argv[4])
doc = fitz.open(path)
os.makedirs(outdir, exist_ok=True)

# ONEBOT 手册: 数字被编码为私有区字符 0xF6B1(=0) ~ 0xF6BA(=9)
DIGITS = {0xF6B1 + i: str(i) for i in range(10)}
# 常见符号误提取 (按上下文谨慎映射)
SYMBOLS = {'÷': 'x', '⨯': 'x', '·': '-'}

def decode(t):
    out = []
    for ch in t:
        o = ord(ch)
        if o in DIGITS:
            out.append(DIGITS[o])
        elif ch in SYMBOLS:
            out.append(SYMBOLS[ch])
        else:
            out.append(ch)
    return ''.join(out)

for i in range(start - 1, min(end, len(doc))):
    text = decode(doc[i].get_text())
    fn = os.path.join(outdir, "page_%03d.txt" % (i + 1))
    with open(fn, "w", encoding="utf-8") as f:
        f.write(text)
print("total_pages", len(doc))
print("extracted", start, "to", min(end, len(doc)), "->", outdir)
