#!/usr/bin/env python3
# 大唐不夜城 参考图采集：Bing 图片 + 360 图片，按主题归档
import os, re, json, hashlib, urllib.parse, io, csv, html
import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
from PIL import Image

ROOT = "/home/zyw/Downloads/dl-hub/101-大唐不夜城参考图"
RAW = f"{ROOT}/raw"
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/124.0 Safari/537.36")

QUERIES = [
    ("夜景建筑", "大唐不夜城 夜景"),
    ("夜景建筑", "大唐不夜城 灯光 大雁塔"),
    ("夜景建筑", "大唐不夜城 航拍"),
    ("汉服美女", "大唐不夜城 汉服美女"),
    ("汉服美女", "大唐不夜城 唐装 小姐姐"),
    ("汉服美女", "大唐不夜城 美女 旅拍"),
    ("不倒翁小姐姐", "大唐不夜城 不倒翁小姐姐"),
    ("不倒翁小姐姐", "不倒翁小姐姐 冯佳晨"),
    ("街拍游客", "大唐不夜城 街拍"),
    ("街拍游客", "大唐不夜城 游客 打卡"),
    ("演出", "大唐不夜城 演出"),
    ("演出", "盛唐密盒 大唐不夜城"),
]

def session():
    s = requests.Session()
    s.headers.update({"User-Agent": UA, "Accept-Language": "zh-CN,zh;q=0.9"})
    return s

def bing_urls(s, q, pages=2):
    out = []
    for p in range(pages):
        url = ("https://www.bing.com/images/async?q=" + urllib.parse.quote(q) +
               f"&first={p*35}&count=35&mkt=zh-CN&qft=+filterui:photo-photo")
        try:
            r = s.get(url, timeout=20)
            txt = r.text
        except Exception:
            continue
        for m in re.finditer(r'murl&quot;:&quot;(.*?)&quot;', txt):
            u = html.unescape(m.group(1)).replace("\\/", "/")
            if u.startswith("http"):
                out.append(u)
    return out

def so_urls(s, q, pages=2):
    out = []
    for p in range(pages):
        url = f"https://image.so.com/j?q={urllib.parse.quote(q)}&src=srp&sn={p*30}&pn=30"
        try:
            d = s.get(url, timeout=20).json()
        except Exception:
            continue
        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 download(s, url, timeout=20):
    try:
        r = s.get(url, timeout=timeout, stream=True)
        if r.status_code != 200:
            return None
        ctype = r.headers.get("Content-Type", "")
        if "image" not in ctype:
            # 有些站点不返回 content-type，仍尝试
            if 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():
    s = session()
    os.makedirs(RAW, exist_ok=True)
    tasks = []
    seen_url = set()
    for theme, q in QUERIES:
        urls = bing_urls(s, q) + so_urls(s, q)
        uniq = []
        for u in urls:
            if u in seen_url:
                continue
            seen_url.add(u)
            uniq.append(u)
        print(f"[{theme}] {q} -> {len(uniq)} urls", flush=True)
        for u in uniq[:60]:
            tasks.append((theme, q, u))
    print("total candidates:", len(tasks), flush=True)

    rows, hashes = [], set()
    os.makedirs(RAW, exist_ok=True)
    with ThreadPoolExecutor(max_workers=10) as ex:
        futs = {ex.submit(download, s, u): (t, q, u) for t, q, u in tasks}
        for i, f in enumerate(as_completed(futs), 1):
            theme, q, u = 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 in ("jpeg",) else fmt
            fn = f"{len(os.listdir(d))+1:03d}_{hh[:8]}.{ext}"
            with open(f"{d}/{fn}", "wb") as fh:
                fh.write(data)
            rows.append({"theme": theme, "file": f"{theme}/{fn}", "w": w, "h": h,
                         "query": q, "url": u})
            if i % 20 == 0:
                print(f"  downloaded {len(rows)} / tried {i}", flush=True)
    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()
