#!/usr/bin/env python3
# 大唐不夜城 参考图采集 v2：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",
 "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0 Safari/537.36",
]
QUERIES = [
    ("汉服美女", "大唐不夜城 汉服 小姐姐"),
    ("汉服美女", "大唐不夜城 唐装 美女"),
    ("汉服美女", "大唐不夜城 街拍 美女"),
    ("汉服美女", "大唐不夜城 夜景 人像"),
    ("汉服美女", "西安 汉服 旅拍 大唐不夜城"),
    ("不倒翁小姐姐", "大唐不夜城 不倒翁 小姐姐"),
    ("不倒翁小姐姐", "不倒翁 皮卡晨"),
    ("演出", "大唐不夜城 盛唐密盒"),
    ("演出", "大唐不夜城 花车 巡游"),
    ("夜景建筑", "大唐不夜城 灯会"),
    ("夜景建筑", "大唐不夜城 大雁塔 喷泉"),
    ("夜景建筑", "大唐不夜城 唐风 建筑"),
    ("夜景建筑", "大唐不夜城 航拍 全景"),
    ("街拍游客", "大唐不夜城 游客 人山人海"),
    ("街拍游客", "大唐不夜城 旅游 打卡"),
    ("街拍游客", "长安十二时辰 主题街区"),
]

def head():
    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")
    r = s.get(url, timeout=25, headers=head())
    out = []
    for m in re.finditer(r'murl&quot;:&quot;(.*?)&quot;', r.text):
        u = html.unescape(m.group(1)).replace("\\/", "/")
        if u.startswith("http"):
            out.append(u)
    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=head()).json()
    out = []
    for it in d.get("list", []):
        u = it.get("img") or it.get("thumb") or ""
        if u.startswith("http"):
            out.append(u)
    return out

def gather(q):
    s = requests.Session()
    urls = []
    for attempt in range(2):
        try:
            urls += bing(s, q)
        except Exception as e:
            print("  bing err", e, flush=True)
        time.sleep(2.5)
        try:
            urls += so360(s, q)
        except Exception as e:
            print("  360 err", e, flush=True)
        time.sleep(2.5)
        if len(urls) >= 8:
            break
        print(f"  retry {q} (got {len(urls)})", flush=True)
        time.sleep(12)
    return urls

def download(s, url):
    try:
        r = s.get(url, timeout=20, stream=True, headers=head())
        if r.status_code != 200:
            return None
        ctype = r.headers.get("Content-Type", "")
        if "image" not in ctype and not re.search(r"\.(jpe?g|png|webp|gif)", url, re.I):
            return None
        data = r.content
        if len(data) < 50_000:
            return None
        im = Image.open(io.BytesIO(data)); im.load()
        w, h = im.size
        if w < 500 or h < 500:
            return None
        return data, w, h, (im.format or "JPEG").lower()
    except Exception:
        return None

def main():
    os.makedirs(RAW, exist_ok=True)
    rows = []
    if os.path.exists(f"{ROOT}/manifest.csv"):
        rows = list(csv.DictReader(open(f"{ROOT}/manifest.csv")))
    have = set()
    for r in rows:
        p = f"{RAW}/{r['file']}"
        if os.path.exists(p):
            have.add(hashlib.md5(open(p, "rb").read()).hexdigest())
    seen_url = {r["url"] for r in rows}
    print("existing:", len(rows), flush=True)

    for theme, q in QUERIES:
        urls = [u for u in gather(q) if u not in seen_url]
        seen_url.update(urls)
        print(f"[{theme}] {q} -> {len(urls)}", flush=True)
        if not urls:
            continue
        picked = urls[:45]
        with ThreadPoolExecutor(max_workers=8) as ex:
            futs = {ex.submit(download, requests.Session(), u): u for u in picked}
            for f in as_completed(futs):
                u = futs[f]; res = f.result()
                if not res:
                    continue
                data, w, h, fmt = res
                hh = hashlib.md5(data).hexdigest()
                if hh in have:
                    continue
                have.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, "url": u})
        print(f"  total now {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", "url"])
        w.writeheader(); w.writerows(rows)
    print("DONE", len(rows), flush=True)

if __name__ == "__main__":
    main()
