#!/usr/bin/env python3
# 大唐不夜城 参考图采集 v3：Bing/360 + 标题与来源过滤（只留真·大唐不夜城相关）
import os, re, json, hashlib, urllib.parse, io, csv, html, time
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from PIL import Image

ROOT = "/home/zyw/Downloads/dl-hub/101-大唐不夜城参考图"
RAW = f"{ROOT}/raw"
UAS = [
 "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36",
 "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15",
]
KW = ("大唐", "不夜城", "西安", "长安", "曲江", "大雁塔", "汉服", "唐装",
      "不倒翁", "盛唐", "唐风", "皮卡晨", "密盒")

QUERIES = [
    ("汉服美女", "大唐不夜城 汉服 小姐姐"),
    ("汉服美女", "大唐不夜城 唐装 美女"),
    ("汉服美女", "大唐不夜城 街拍"),
    ("汉服美女", "大唐不夜城 夜景 人像"),
    ("汉服美女", "西安 汉服 旅拍"),
    ("不倒翁小姐姐", "大唐不夜城 不倒翁 小姐姐"),
    ("不倒翁小姐姐", "皮卡晨 不倒翁"),
    ("演出", "大唐不夜城 盛唐密盒"),
    ("演出", "大唐不夜城 花车 巡游"),
    ("夜景建筑", "大唐不夜城 夜景"),
    ("夜景建筑", "大唐不夜城 灯会"),
    ("夜景建筑", "大唐不夜城 大雁塔"),
    ("夜景建筑", "大唐不夜城 航拍"),
    ("街拍游客", "大唐不夜城 人山人海"),
    ("街拍游客", "大唐不夜城 打卡"),
    ("街拍游客", "长安十二时辰 街区"),
]

def H():
    return {"User-Agent": UAS[int(time.time()) % len(UAS)],
            "Accept-Language": "zh-CN,zh;q=0.9"}

def bing(s, q, first=0):
    url = ("https://cn.bing.com/images/async?q=" + urllib.parse.quote(q) +
           f"&first={first}&count=35&mkt=zh-CN")
    txt = s.get(url, timeout=25, headers=H()).text
    out = []
    for blk in re.findall(r'm="(\{&quot;.*?\})"', txt):
        try:
            d = json.loads(html.unescape(blk))
        except Exception:
            continue
        u, t, p = d.get("murl", ""), d.get("t", ""), d.get("purl", "")
        if not u.startswith("http"):
            continue
        if any(k in (t + " " + p) for k in KW):
            out.append((u, t, p))
    return out

def so360(s, q, sn=0):
    url = f"https://image.so.com/j?q={urllib.parse.quote(q)}&src=srp&sn={sn}&pn=30"
    d = s.get(url, timeout=25, headers=H()).json()
    out = []
    for it in d.get("list", []):
        u = it.get("img") or it.get("thumb") or ""
        t = (it.get("title") or "") + " " + (it.get("link") or "") + " " + (it.get("site") or "")
        if u.startswith("http") and any(k in t for k in KW):
            out.append((u, it.get("title", ""), it.get("link", "")))
    return out

def gather(q):
    s = requests.Session(); items = []
    for first in (0, 35):
        try: items += bing(s, q, first)
        except Exception as e: print("  bing err", e, flush=True)
        time.sleep(2)
    for sn in (0, 30):
        try: items += so360(s, q, sn)
        except Exception as e: print("  360 err", e, flush=True)
        time.sleep(2)
    return items

def download(url):
    try:
        r = requests.get(url, timeout=20, headers=H())
        if r.status_code != 200: return None
        data = r.content
        if len(data) < 60_000: return None
        im = Image.open(io.BytesIO(data)); im.load()
        w, h = im.size
        if w < 600 or h < 600: return None
        if w * h < 700_000: return None
        return data, w, h, (im.format or "JPEG").lower()
    except Exception:
        return None

def main():
    os.makedirs(RAW, exist_ok=True)
    rows, hashes, seen = [], set(), set()
    for theme, q in QUERIES:
        items = gather(q)
        fresh = [(u, t, p) for (u, t, p) in items if u not in seen]
        for u, t, p in fresh: seen.add(u)
        print(f"[{theme}] {q} -> {len(fresh)}", flush=True)
        if not fresh: continue
        with ThreadPoolExecutor(max_workers=8) as ex:
            futs = {ex.submit(download, u): (u, t, p) for u, t, p in fresh[:50]}
            for f in as_completed(futs):
                u, t, p = futs[f]; res = f.result()
                if not res: continue
                data, w, h, fmt = res
                hh = hashlib.md5(data).hexdigest()
                if hh in hashes: continue
                hashes.add(hh)
                d = f"{RAW}/{theme}"; os.makedirs(d, exist_ok=True)
                ext = "jpg" if fmt == "jpeg" else fmt
                fn = f"{len(os.listdir(d))+1:03d}_{hh[:8]}.{ext}"
                open(f"{d}/{fn}", "wb").write(data)
                rows.append({"theme": theme, "file": f"{theme}/{fn}", "w": w, "h": h,
                             "query": q, "title": t[:120], "purl": p, "url": u})
        print(f"  total {len(rows)}", flush=True)
        time.sleep(1.5)
    with open(f"{ROOT}/manifest.csv", "w", newline="") as fh:
        w = csv.DictWriter(fh, fieldnames=["theme","file","w","h","query","title","purl","url"])
        w.writeheader(); w.writerows(rows)
    print("DONE", len(rows), flush=True)

if __name__ == "__main__":
    main()
