#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""批量 OCR：抖音图集幻灯片 → 逐字文本（DeepSeek-V4-Flash-Vision-Exp）

设计要点
- 按 **文件 sha256** 缓存：同一张图（跨作品重复）只调用一次，重跑零成本、可断点续跑。
- 并发 + 指数退避重试（429/5xx/超时）。
- 记录 usage，便于核算用量。
- 输出：cache/<sha2>/<sha>.json  ；汇总 ocr_all.jsonl

用法：
  python3 ocr_slides.py --root <图片目录> --cache <缓存目录> --out <汇总jsonl> [--workers 6] [--limit N] [--match 前缀]
"""
import argparse, base64, hashlib, json, os, sys, threading, time
import urllib.request, urllib.error
from concurrent.futures import ThreadPoolExecutor

API = "https://api.deepseek.com/v1/chat/completions"
MODEL = "deepseek-v4-flash-vision-exp"
KEY = os.environ.get("DS_VL_KEY", "sk-2af0093dfbac45359276d8aa85d83618")

PROMPT = (
    "这是一张 AI 教程/作品集图片（可能是幻灯片截图）。"
    "请把图中出现的所有文字**逐字原样**提取出来：中英文都要，保持原有顺序与分行，"
    "不要翻译、不要总结、不要改写、不要补全、不要遗漏。"
    "英文单词之间请保留空格。表格用 Markdown 竖线表还原。"
    "如果图中确实没有任何文字，只回答：无文字。"
)

_lock = threading.Lock()
_stats = {"hit": 0, "call": 0, "fail": 0, "no_text": 0, "trunc": 0, "ptok": 0, "ctok": 0}


def sha256_file(p):
    h = hashlib.sha256()
    with open(p, "rb") as f:
        for chunk in iter(lambda: f.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def cache_path(cache, sha):
    return os.path.join(cache, sha[:2], sha + ".json")


def call_api(data, ext, tries=4, timeout=180):
    b64 = base64.b64encode(data).decode()
    payload = {
        "model": MODEL,
        "messages": [{"role": "user", "content": [
            {"type": "image_url", "image_url": {"url": "data:image/%s;base64,%s" % (ext, b64)}},
            {"type": "text", "text": PROMPT},
        ]}],
        "max_tokens": 4000,
        "temperature": 0,
    }
    body = json.dumps(payload).encode()
    last = None
    for i in range(tries):
        try:
            req = urllib.request.Request(API, data=body, headers={
                "Authorization": "Bearer " + KEY, "Content-Type": "application/json"})
            with urllib.request.urlopen(req, timeout=timeout) as r:
                return json.loads(r.read())
        except urllib.error.HTTPError as e:
            last = "HTTP %s %s" % (e.code, e.read()[:200])
            if e.code in (429, 500, 502, 503, 504):
                time.sleep(2 ** i * 3)
                continue
            raise RuntimeError(last)
        except Exception as e:  # URLError / timeout
            last = repr(e)
            time.sleep(2 ** i * 3)
    raise RuntimeError("重试耗尽: " + str(last))


def process(path, cache, force=False):
    sha = sha256_file(path)
    cp = cache_path(cache, sha)
    if os.path.exists(cp) and not force:
        try:
            d = json.load(open(cp, encoding="utf-8"))
            if d.get("text"):
                with _lock:
                    _stats["hit"] += 1
                return d
        except Exception:
            pass
    ext = os.path.splitext(path)[1].lower().lstrip(".")
    if ext == "jpg":
        ext = "jpeg"
    if ext not in ("jpeg", "png", "webp", "gif"):
        ext = "jpeg"
    data = open(path, "rb").read()
    resp = call_api(data, ext)
    ch = (resp.get("choices") or [{}])[0]
    text = (ch.get("message") or {}).get("content") or ""
    text = text.strip()
    fin = ch.get("finish_reason")
    usage = resp.get("usage") or {}
    rec = {"sha256": sha, "file": os.path.basename(path), "text": text,
           "finish_reason": fin, "usage": usage, "ts": time.strftime("%Y-%m-%d %H:%M:%S")}
    os.makedirs(os.path.dirname(cp), exist_ok=True)
    tmp = cp + ".tmp"
    json.dump(rec, open(tmp, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    os.replace(tmp, cp)
    with _lock:
        _stats["call"] += 1
        _stats["ptok"] += usage.get("prompt_tokens", 0) or 0
        _stats["ctok"] += usage.get("completion_tokens", 0) or 0
        if not text or text == "无文字":
            _stats["no_text"] += 1
        if fin == "length":
            _stats["trunc"] += 1
    return rec


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--root", required=True)
    ap.add_argument("--cache", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--workers", type=int, default=6)
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--match", default="")
    ap.add_argument("--force", action="store_true")
    a = ap.parse_args()

    files = []
    for f in sorted(os.listdir(a.root)):
        if not f.lower().endswith((".webp", ".jpg", ".jpeg", ".png", ".gif")):
            continue
        if a.match and not f.startswith(a.match):
            continue
        files.append(os.path.join(a.root, f))
    if a.limit:
        files = files[:a.limit]
    print("待处理 %d 张，并发 %d" % (len(files), a.workers), flush=True)

    t0 = time.time()
    done = 0
    errs = []
    out = open(a.out, "a", encoding="utf-8")
    with ThreadPoolExecutor(max_workers=a.workers) as ex:
        futs = {ex.submit(process, p, a.cache, a.force): p for p in files}
        for fu in futs:
            p = futs[fu]
            try:
                rec = fu.result()
                out.write(json.dumps(rec, ensure_ascii=False) + "\n")
                out.flush()
            except Exception as e:
                with _lock:
                    _stats["fail"] += 1
                errs.append((os.path.basename(p), str(e)[:160]))
            done += 1
            if done % 25 == 0 or done == len(files):
                el = time.time() - t0
                print("[%d/%d] 用时%.0fs  新增调用%d 缓存命中%d 失败%d 无文字%d 截断%d"
                      % (done, len(files), el, _stats["call"], _stats["hit"], _stats["fail"],
                         _stats["no_text"], _stats["trunc"]), flush=True)
    out.close()
    print("完成：新增%d 命中缓存%d 失败%d ｜ tokens in=%d out=%d ｜ 总用时%.0fs"
          % (_stats["call"], _stats["hit"], _stats["fail"], _stats["ptok"], _stats["ctok"],
             time.time() - t0))
    for f, e in errs[:20]:
        print("  失败:", f, e)


if __name__ == "__main__":
    main()
