# -*- coding: utf-8 -*-
"""画面文字提取：按 2 秒抽帧 + RapidOCR，连续相同文本合并为时间段
用法: python ocr.py [--limit N] [--only id] [--interval 2.0]
"""
import argparse, glob, json, os, re, time
import cv2
import numpy as np

ROOT = r"D:\Deepseek\douyin_fengdaquan"
VID = os.path.join(ROOT, "videos")
OUT = os.path.join(ROOT, "screen_text")
os.makedirs(OUT, exist_ok=True)


def ts(t):
    m, s = int(t // 60), int(t % 60)
    return f"{m:02d}:{s:02d}"


def norm(lines):
    """归一化文本集合，便于比较相邻帧"""
    return tuple(sorted({l.strip().replace(" ", "") for l in lines if l.strip()}))


CJK = re.compile(r"[\u4e00-\u9fff]")
MONEY = re.compile(r"[¥￥]\s?\d|佣金|结算|订单|流量|播放|点赞")


def keep(line):
    """过滤 UI 噪声：保留含中文且≥3字，或含金额/业务关键词的行"""
    s = line.strip()
    if len(s) < 2:
        return False
    if MONEY.search(s):
        return True
    cjk = len(CJK.findall(s))
    if cjk >= 3 and cjk / max(1, len(s)) >= 0.4:
        return True
    return False


def similarity(a, b):
    if not a and not b:
        return 1.0
    if not a or not b:
        return 0.0
    sa, sb = set(a), set(b)
    return len(sa & sb) / len(sa | sb)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--limit", type=int, default=0)
    ap.add_argument("--only", default="")
    ap.add_argument("--interval", type=float, default=3.0)
    ap.add_argument("--width", type=int, default=1280)
    args = ap.parse_args()

    from rapidocr_onnxruntime import RapidOCR
    t0 = time.time()
    print("初始化 RapidOCR ...", flush=True)
    ocr = RapidOCR()
    print(f"就绪 {time.time()-t0:.0f}s", flush=True)

    files = sorted(glob.glob(os.path.join(VID, "*.mp4")))
    if args.only:
        files = [f for f in files if args.only in f]
    if args.limit:
        files = files[: args.limit]

    for i, f in enumerate(files, 1):
        base = os.path.splitext(os.path.basename(f))[0]
        jf = os.path.join(OUT, base + ".json")
        if os.path.exists(jf):
            print(f"[{i}/{len(files)}] 跳过 {base}", flush=True)
            continue
        t1 = time.time()
        cap = cv2.VideoCapture(f)
        fps = cap.get(cv2.CAP_PROP_FPS) or 25
        total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT) or 0)
        step = max(1, int(round(fps * args.interval)))
        idx, frames = 0, 0
        groups = []  # [{start,end,lines}]
        while True:
            ok = cap.grab()
            if not ok:
                break
            if idx % step == 0:
                ok, frame = cap.retrieve()
                if not ok:
                    break
                t = idx / fps
                h, w = frame.shape[:2]
                if w > args.width:
                    frame = cv2.resize(frame, (args.width, int(h * args.width / w)))
                res, _ = ocr(frame)
                lines = [r[1] for r in (res or []) if r[2] >= 0.5]
                lines = [l for l in lines if keep(l)]
                cur = norm(lines)
                if groups and similarity(groups[-1]["_norm"], cur) >= 0.6:
                    groups[-1]["end"] = t
                    groups[-1]["_norm"] = norm(set(groups[-1]["_norm"]) | set(cur))
                else:
                    groups.append({"start": t, "end": t, "_norm": cur, "lines": list(cur)})
                frames += 1
            idx += 1
        cap.release()
        payload = {
            "file": os.path.basename(f),
            "fps": fps,
            "duration": round(total / fps, 1) if fps else 0,
            "sampled_frames": frames,
            "groups": [{"start": round(g["start"], 1), "end": round(g["end"], 1), "lines": g["lines"]}
                       for g in groups],
        }
        json.dump(payload, open(jf, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
        with open(os.path.join(OUT, base + ".txt"), "w", encoding="utf-8") as fp:
            for g in payload["groups"]:
                fp.write(f"[{ts(g['start'])}-{ts(g['end'])}] " + " / ".join(g["lines"]) + "\n")
        uniq = len({l for g in payload["groups"] for l in g["lines"]})
        print(f"[{i}/{len(files)}] {base} | 抽帧 {frames} 张, 文本段 {len(groups)}, 去重 {uniq} 行 | "
              f"耗时 {time.time()-t1:.0f}s", flush=True)
    print(f"\nOCR 全部完成, 总耗时 {time.time()-t0:.0f}s", flush=True)


if __name__ == "__main__":
    main()
