# -*- coding: utf-8 -*-
"""把 5 个关键词的搜索结果合并成语料清单：去重 + 相关性过滤 + 解析时长/点赞/作者"""
import glob, json, re, os, sys

sys.stdout.reconfigure(encoding="utf-8")
SRC = r"D:\Deepseek\tiktok_sea_corpus\_search"
OUT = r"D:\Deepseek\tiktok_sea_corpus"

REL = ["印尼", "tiktok", "tk", "东南亚", "跨境", "带货", "达人", "越南", "泰国", "马来", "菲律宾"]

items = {}
for fp in glob.glob(os.path.join(SRC, "*.json")):
    j = json.load(open(fp, encoding="utf-8"))
    kw = j.get("keyword", "")
    for it in j.get("items", []):
        if it["id"] in items:
            items[it["id"]]["keywords"].append(kw)
            continue
        t = it.get("txt", "")
        parts = [p.strip() for p in t.split("⏐")]
        dur = next((p for p in parts if re.fullmatch(r"\d{1,2}:\d{2}", p)), "")
        likes = next((p for p in parts if re.fullmatch(r"[\d.]+万?", p)), "")
        author = next((p for p in parts if p.startswith("@")), "").lstrip("@")
        desc = next((p for p in parts if p not in (dur, likes) and not p.startswith("@") and not p.startswith("·")), "")
        items[it["id"]] = {"id": it["id"], "desc": desc[:120], "author": author, "dur": dur,
                           "likes": likes, "keywords": [kw], "raw": t[:160]}

rows = [v for v in items.values() if any(k in (v["desc"] + v["raw"]).lower() for k in REL)]
print(f"搜索去重 {len(items)} 条，相关性过滤后 {len(rows)} 条")

from collections import Counter
print("按作者:", Counter(r["author"] for r in rows).most_common(12))

json.dump(rows, open(os.path.join(OUT, "_corpus_cards.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
print("已写入 _corpus_cards.json")
