| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212 |
- """从 Wikimedia Commons 采集铁路货车车型图片(CC/公共领域授权)。
- 用途:为正面吊车型识别补充多车型样本(C70/C64K/C70E/C80 敞车、X70/NX70 平车)。
- 只下载 Commons 上的自由授权图片,逐张记录作者与许可到 LICENSES.csv。
- 用法:
- python scripts/download_wagon_images.py [--out DIR] [--max-per-type N] [--dry-run]
- 依赖:仅标准库(urllib / json / csv / re)。
- """
- from __future__ import annotations
- import argparse
- import csv
- import html
- import json
- import os
- import re
- import sys
- import time
- import urllib.parse
- import urllib.request
- API = "https://commons.wikimedia.org/w/api.php"
- UA = "PortCV-WagonDataCollector/1.0 (research; contact: local)"
- ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- # 车型 → Wikimedia Commons 分类(这些分类下的图片按文件名前缀再细分车型)
- CATEGORIES = [
- "Category:Open railway wagons of China",
- "Category:Container railway wagons of China",
- "Category:Flat railway wagons of China",
- "Category:Covered railway wagons of China", # 棚车 P62/P64 → 状态0负样本
- "Category:Chawu Railway Station", # 更多 C80B / X70 现场图
- ]
- # 从文件名提取车型标签(按优先级匹配,先匹配到的为准)
- # 业务映射:敞车(C*)→状态1,平车(X*/NX*)→状态2,棚车(P*)→状态0负样本
- TYPE_PATTERNS = [
- ("C70E", re.compile(r"\bC70E\b", re.I)),
- ("C70H", re.compile(r"\bC70H\b", re.I)),
- ("C70", re.compile(r"\bC70\b", re.I)),
- ("C64K", re.compile(r"\bC64K\b", re.I)),
- ("C64", re.compile(r"\bC64\b", re.I)),
- ("C80", re.compile(r"\bC80[A-Z]?\b", re.I)),
- ("NX70", re.compile(r"\bNX70[A-Z]?\b", re.I)),
- ("NX17", re.compile(r"\bNX17[A-Z]?\b", re.I)),
- ("X70", re.compile(r"\bX70\b", re.I)),
- ("X160", re.compile(r"\bX160[A-Z]?\b", re.I)),
- ("P62", re.compile(r"\bP62[A-Z]?\b", re.I)), # 棚车负样本
- ("P64", re.compile(r"\bP64[A-Z]?\b", re.I)), # 棚车负样本
- ]
- def api_get(params: dict, retries: int = 3):
- params = dict(params)
- params["format"] = "json"
- url = API + "?" + urllib.parse.urlencode(params)
- last = None
- for i in range(retries):
- try:
- req = urllib.request.Request(url, headers={"User-Agent": UA})
- with urllib.request.urlopen(req, timeout=30) as r:
- return json.load(r)
- except Exception as exc: # pragma: no cover
- last = exc
- time.sleep(1.5 * (i + 1))
- raise RuntimeError("API 请求失败: %s" % last)
- def category_files(category: str):
- """返回分类下所有 File: 页面标题(处理续页)。"""
- out, cont = [], {}
- while True:
- params = {
- "action": "query",
- "list": "categorymembers",
- "cmtitle": category,
- "cmtype": "file",
- "cmlimit": "200",
- }
- params.update(cont)
- data = api_get(params)
- out.extend(m["title"] for m in data.get("query", {}).get("categorymembers", []))
- if "continue" not in data:
- break
- cont = data["continue"]
- return out
- def file_info(titles):
- """批量取图片原图 URL + 授权元数据(每批 50 个)。"""
- out = []
- for i in range(0, len(titles), 50):
- batch = titles[i : i + 50]
- data = api_get(
- {
- "action": "query",
- "titles": "|".join(batch),
- "prop": "imageinfo",
- "iiprop": "url|extmetadata",
- "iiurlwidth": "1280", # Commons 允许的缩略图宽度,原图直链会被 429
- }
- )
- for page in data.get("query", {}).get("pages", {}).values():
- ii = (page.get("imageinfo") or [{}])[0]
- out.append((page.get("title", ""), ii))
- return out
- def strip_html(s: str) -> str:
- s = html.unescape(s or "")
- return re.sub(r"<[^>]+>", "", s).strip()
- def meta_value(ii: dict, key: str) -> str:
- return strip_html((ii.get("extmetadata", {}).get(key, {}) or {}).get("value", ""))
- def classify(title: str):
- name = title[5:] if title.lower().startswith("file:") else title
- for label, pat in TYPE_PATTERNS:
- if pat.search(name):
- return label
- return "other"
- def safe_name(title: str) -> str:
- name = title[5:] if title.lower().startswith("file:") else title
- return re.sub(r'[\\/:*?"<>|]', "_", name)
- def main() -> int:
- ap = argparse.ArgumentParser()
- ap.add_argument("--out", default=os.path.join(ROOT, "dataset", "web_cc"))
- ap.add_argument("--max-per-type", type=int, default=30)
- ap.add_argument("--dry-run", action="store_true")
- args = ap.parse_args()
- titles = []
- for cat in CATEGORIES:
- print("category:", cat, file=sys.stderr)
- titles.extend(category_files(cat))
- titles = list(dict.fromkeys(titles))
- print("total files:", len(titles), file=sys.stderr)
- records = file_info(titles)
- counts: dict = {}
- rows = []
- for title, ii in records:
- label = classify(title)
- if label == "other":
- continue
- if counts.get(label, 0) >= args.max_per_type:
- continue
- # 优先用缩略图 URL(thumburl),Commons 对它不限流;没有则用原图
- url = ii.get("thumburl") or ii.get("url")
- if not url:
- continue
- license_name = meta_value(ii, "LicenseShortName")
- author = meta_value(ii, "Artist")
- counts[label] = counts.get(label, 0) + 1
- rows.append(
- {
- "type": label,
- "title": title,
- "url": url, # 实际下载的是缩略图 URL
- "source_page": ii.get("descriptionurl", ""),
- "license": license_name,
- "author": author[:200],
- }
- )
- print("selected:", len(rows), "by type:", counts, file=sys.stderr)
- if args.dry_run:
- for r in rows:
- print("%-8s %-12s %s" % (r["type"], r["license"], r["title"]))
- return 0
- os.makedirs(args.out, exist_ok=True)
- with open(os.path.join(args.out, "LICENSES.csv"), "w", newline="", encoding="utf-8-sig") as fh:
- w = csv.DictWriter(fh, fieldnames=["type", "title", "url", "source_page", "license", "author"])
- w.writeheader()
- for r in rows:
- folder = os.path.join(args.out, r["type"])
- os.makedirs(folder, exist_ok=True)
- path = os.path.join(folder, safe_name(r["title"]))
- if not os.path.exists(path):
- ok = False
- for attempt in range(3):
- try:
- req = urllib.request.Request(url=r["url"], headers={"User-Agent": UA})
- with urllib.request.urlopen(req, timeout=60) as resp, open(path, "wb") as out:
- out.write(resp.read())
- print("saved", r["type"], os.path.basename(path), file=sys.stderr)
- ok = True
- break
- except Exception as exc: # pragma: no cover
- print("retry %d" % attempt, r["title"], exc, file=sys.stderr)
- time.sleep(2 * (attempt + 1))
- if not ok:
- continue
- w.writerow(r)
- time.sleep(1.0) # 限速,避免再次触发 429
- print("done. output:", args.out, file=sys.stderr)
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|