# -*- coding: utf-8 -*-
"""下载 comments_all 里的评论图片，并统计"""
import glob, json, os, requests

ROOT = r"D:\Deepseek\douyin_fengdaquan"
RAW = os.path.join(ROOT, "comments_all")
IMG = os.path.join(ROOT, "comments_images_all")
os.makedirs(IMG, exist_ok=True)

UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/158.0.0.0 Safari/537.36")
HEAD = {"User-Agent": UA, "Referer": "https://www.douyin.com/"}


def to_url(x):
    if x is None:
        return None
    if isinstance(x, str):
        return x if x.startswith("http") else None
    if isinstance(x, dict):
        for u in x.get("url_list") or []:
            if isinstance(u, str) and u.startswith("http"):
                return u
        return to_url(x.get("origin_url"))
    if isinstance(x, (list, tuple)):
        for i in x:
            u = to_url(i)
            if u:
                return u
    return None


def main():
    total_c = total_img = got = 0
    stats = {}
    for fp in sorted(glob.glob(os.path.join(RAW, "*.json"))):
        j = json.load(open(fp, encoding="utf-8"))
        aweme = j["aweme_id"]
        cs = j["comments"]
        imgs = [u for u in (to_url(x) for c in cs for x in c["images"]) if u]
        total_c += len(cs); total_img += len(imgs)
        outdir = os.path.join(IMG, aweme)
        if imgs:
            os.makedirs(outdir, exist_ok=True)
        for k, url in enumerate(imgs, 1):
            ext = ".webp" if ".webp" in url else (".png" if ".png" in url else ".jpg")
            dst = os.path.join(outdir, f"{k:02d}{ext}")
            if os.path.exists(dst) and os.path.getsize(dst) > 1000:
                got += 1; continue
            try:
                r = requests.get(url, headers=HEAD, timeout=30)
                if r.status_code == 200 and len(r.content) > 500:
                    open(dst, "wb").write(r.content); got += 1
            except Exception:
                pass
        stats[aweme] = {"comments": len(cs), "images": len(imgs), "total": j.get("total_comments", 0)}
    json.dump(stats, open(os.path.join(ROOT, "_comments_all_stats.json"), "w", encoding="utf-8"), ensure_ascii=False, indent=1)
    print(f"评论 {total_c} 条，图片 {total_img} 张，已下载 {got} 张")


if __name__ == "__main__":
    main()
