#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""把 OCR 文本解析成结构化提示词实例 → _data/instances.json

每组实例 = 一张幻灯片上的一段完整「五维参数」提示词（中文段 + 英文段对应）。
字段：主体与环境置景 / 美学调性 / 具体置景 / 摄影与镜头构图 / 色彩光影 / 后期特效
（英文段同构：Core Visuals / Tonal Style / Set Design / Camera & Framing / Lighting & Color / Post-VFX）
"""
import json, os, re, collections, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from classify import classify

BASE = "/home/zyw/Downloads/dl-hub/85-AI生图提示词知识库-桀克AIShotLab"
SRC = os.path.join(BASE, "_data/assembled.json")
OUT = os.path.join(BASE, "_data/instances.json")

# 中文字段切分。OCR 常把字段名断行（"色\n彩光影"）或吃掉换行，
# 因此所有字段名都编译成"字符间允许空白"的正则。
def flex(name):
    return r"\s*".join(re.escape(c) for c in name)


CN_NAMES = {
    "subject": ["画面主体与环境置景", "画面主体与置景", "主体与环境置景", "核心元素", "核心视觉"],
    "tone": ["美学调性"],
    "set": ["室外具体置景", "室内具体置景", "具体置景", "置景"],
    "camera": ["视听摄影与美学工业镜头构图", "视听摄影与美学工业", "视听摄影与光学系统",
               "摄影与镜头构图", "镜头与构图", "镜头构图"],
    "light": ["色彩光影"],
    "post": ["后期渲染特效", "后期特效"],
}
EN_NAMES = {
    "subject_en": ["Core Visuals", "Core Elements"],
    "tone_en": ["Tonal Style"],
    "set_en": ["Set Design"],
    "camera_en": ["Camera & Framing", "Camera and Framing"],
    "light_en": ["Lighting & Color", "Lighting and Color"],
    "post_en": ["Post-VFX", "Post VFX"],
}


def build_fields(names):
    out = []
    for key, alts in names.items():
        # 长名优先，避免"置景"抢在"具体置景"前面
        alts = sorted(alts, key=len, reverse=True)
        out.append((key, r"(?:" + "|".join(flex(a) for a in alts) + r")"))
    return out


CN_FIELDS = build_fields(CN_NAMES)
EN_FIELDS = build_fields(EN_NAMES)
ALL_FIELDS = CN_FIELDS + EN_FIELDS


def split_fields(text, fields):
    """按字段名锚点切段，返回 {field: value}。字段缺失则该键不存在。"""
    hits = []
    for key, pat in fields:
        for m in re.finditer(pat, text):
            hits.append((m.start(), m.end(), key))
    if not hits:
        return {}
    hits.sort()
    # 同一位置可能被多个模式命中（如 置景 命中 具体置景），保留最长的
    merged = []
    for h in hits:
        if merged and h[0] < merged[-1][1]:
            if (h[1] - h[0]) > (merged[-1][1] - merged[-1][0]):
                merged[-1] = h
            continue
        merged.append(h)
    out = collections.OrderedDict()
    for i, (s, e, key) in enumerate(merged):
        nxt = merged[i + 1][0] if i + 1 < len(merged) else len(text)
        val = strip_headers(text[e:nxt]).strip(" ：:，,。|\n")
        if val:
            out[key] = val
    return out


# 英文段落里的小标题不是内容，切分后会残留，统一清除
SECTION_HEADERS = [
    "Cinematic Elements & Setting", "Cinematic Elements and Setting",
    "Cinematic Photography & Tech Specification", "Cinematic Photography and Tech Specification",
    "Cinematic Photography & Technical Specification",
]


def strip_headers(v):
    for h in SECTION_HEADERS:
        v = v.replace(h, " ")
    return re.sub(r"\s{2,}", " ", v).strip(" /｜|，,。")


# 提示词正文的起始锚点（OCR 常在前面带一句"以下文字逐字提取"之类的元话语）
ANCHOR = re.compile(r"AI\s*生图提示词|【?\s*画面主体与(?:环境)?置景|【?\s*核心元素")
TONE_RE = re.compile(r"美\s*学\s*调\s*性|Tonal\s*Style")


def clean_all(t):
    t = re.sub(r"[□■●◆★☆]", "", t)
    # 裁掉正文之前的 OCR 元话语：取「美学调性」之前最后一个锚点
    mt = TONE_RE.search(t)
    if mt:
        anchors = [m for m in ANCHOR.finditer(t) if m.start() < mt.start()]
        if anchors and anchors[-1].start() > 0:
            t = t[anchors[-1].start():]
    t = re.sub(r"^(AI\s*生图提示词|AI生图|提示词)\s*[:：]?", "", t.strip())
    t = re.sub(r"\n{2,}", "\n", t)
    return t.strip()


def is_prompt(t):
    """判断这段 OCR 文本是否为一条提示词实例（而非纯说明/水印）"""
    return bool(re.search(r"美学调性|Tonal Style", t)) and len(t) > 120


def main():
    works = json.load(open(SRC, encoding="utf-8"))["works"]
    insts = []
    nofields = []
    for w in works:
        for s in w.get("slides") or []:
            t = clean_all(s.get("text") or "")
            if not t or not is_prompt(t):
                continue
            f = split_fields(t, ALL_FIELDS)
            n_cn = sum(1 for k, _ in CN_FIELDS if k in f)
            rec = {
                "aweme_id": w["aweme_id"], "episode": w["episode"],
                "series": w["series"], "film": w.get("film"),
                "title": w["title"], "url": w["url"],
                "slide": s["seq"], "slide_file": s["file"],
                "img": (w.get("file_first") or ""),
                "fields": f, "n_cn_fields": n_cn,
                "subject": f.get("subject", ""), "tone": f.get("tone", ""),
                "set": f.get("set", ""), "camera": f.get("camera", ""),
                "light": f.get("light", ""), "post": f.get("post", ""),
                "tone_en": f.get("tone_en", ""), "raw": t,
            }
            rec["cat"] = classify(rec.get("tone", ""), rec.get("subject", ""), rec.get("title", ""))
            insts.append(rec)
            if n_cn < 4:
                nofields.append(rec)

    json.dump({"count": len(insts), "instances": insts},
              open(OUT, "w", encoding="utf-8"), ensure_ascii=False, indent=1)

    print("提示词实例:", len(insts))
    print("字段完整度分布:", dict(sorted(collections.Counter(i["n_cn_fields"] for i in insts).items())))
    print("字段缺失较多(<4)的实例:", len(nofields))
    print("\n按系列:")
    for k, v in collections.Counter(i["series"] for i in insts).most_common():
        print("  %-22s %d" % (k, v))
    print("\n各类字段可解析条数:")
    for k, _ in ALL_FIELDS:
        print("  %-12s %d" % (k, sum(1 for i in insts if i["fields"].get(k))))
    print("\n=== 样例 3 条 ===")
    for i in insts[:3]:
        print("-" * 70)
        print("集%s 图集%02d %s" % (i["episode"], i["slide"], i["title"][:40]))
        for k in ("subject", "tone", "set", "camera", "light", "post"):
            v = i["fields"].get(k, "")
            print("  %-8s %s" % (k, v[:110]))
    print("→", OUT)


if __name__ == "__main__":
    main()
