download_wagon_images.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. """从 Wikimedia Commons 采集铁路货车车型图片(CC/公共领域授权)。
  2. 用途:为正面吊车型识别补充多车型样本(C70/C64K/C70E/C80 敞车、X70/NX70 平车)。
  3. 只下载 Commons 上的自由授权图片,逐张记录作者与许可到 LICENSES.csv。
  4. 用法:
  5. python scripts/download_wagon_images.py [--out DIR] [--max-per-type N] [--dry-run]
  6. 依赖:仅标准库(urllib / json / csv / re)。
  7. """
  8. from __future__ import annotations
  9. import argparse
  10. import csv
  11. import html
  12. import json
  13. import os
  14. import re
  15. import sys
  16. import time
  17. import urllib.parse
  18. import urllib.request
  19. API = "https://commons.wikimedia.org/w/api.php"
  20. UA = "PortCV-WagonDataCollector/1.0 (research; contact: local)"
  21. ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  22. # 车型 → Wikimedia Commons 分类(这些分类下的图片按文件名前缀再细分车型)
  23. CATEGORIES = [
  24. "Category:Open railway wagons of China",
  25. "Category:Container railway wagons of China",
  26. "Category:Flat railway wagons of China",
  27. "Category:Covered railway wagons of China", # 棚车 P62/P64 → 状态0负样本
  28. "Category:Chawu Railway Station", # 更多 C80B / X70 现场图
  29. ]
  30. # 从文件名提取车型标签(按优先级匹配,先匹配到的为准)
  31. # 业务映射:敞车(C*)→状态1,平车(X*/NX*)→状态2,棚车(P*)→状态0负样本
  32. TYPE_PATTERNS = [
  33. ("C70E", re.compile(r"\bC70E\b", re.I)),
  34. ("C70H", re.compile(r"\bC70H\b", re.I)),
  35. ("C70", re.compile(r"\bC70\b", re.I)),
  36. ("C64K", re.compile(r"\bC64K\b", re.I)),
  37. ("C64", re.compile(r"\bC64\b", re.I)),
  38. ("C80", re.compile(r"\bC80[A-Z]?\b", re.I)),
  39. ("NX70", re.compile(r"\bNX70[A-Z]?\b", re.I)),
  40. ("NX17", re.compile(r"\bNX17[A-Z]?\b", re.I)),
  41. ("X70", re.compile(r"\bX70\b", re.I)),
  42. ("X160", re.compile(r"\bX160[A-Z]?\b", re.I)),
  43. ("P62", re.compile(r"\bP62[A-Z]?\b", re.I)), # 棚车负样本
  44. ("P64", re.compile(r"\bP64[A-Z]?\b", re.I)), # 棚车负样本
  45. ]
  46. def api_get(params: dict, retries: int = 3):
  47. params = dict(params)
  48. params["format"] = "json"
  49. url = API + "?" + urllib.parse.urlencode(params)
  50. last = None
  51. for i in range(retries):
  52. try:
  53. req = urllib.request.Request(url, headers={"User-Agent": UA})
  54. with urllib.request.urlopen(req, timeout=30) as r:
  55. return json.load(r)
  56. except Exception as exc: # pragma: no cover
  57. last = exc
  58. time.sleep(1.5 * (i + 1))
  59. raise RuntimeError("API 请求失败: %s" % last)
  60. def category_files(category: str):
  61. """返回分类下所有 File: 页面标题(处理续页)。"""
  62. out, cont = [], {}
  63. while True:
  64. params = {
  65. "action": "query",
  66. "list": "categorymembers",
  67. "cmtitle": category,
  68. "cmtype": "file",
  69. "cmlimit": "200",
  70. }
  71. params.update(cont)
  72. data = api_get(params)
  73. out.extend(m["title"] for m in data.get("query", {}).get("categorymembers", []))
  74. if "continue" not in data:
  75. break
  76. cont = data["continue"]
  77. return out
  78. def file_info(titles):
  79. """批量取图片原图 URL + 授权元数据(每批 50 个)。"""
  80. out = []
  81. for i in range(0, len(titles), 50):
  82. batch = titles[i : i + 50]
  83. data = api_get(
  84. {
  85. "action": "query",
  86. "titles": "|".join(batch),
  87. "prop": "imageinfo",
  88. "iiprop": "url|extmetadata",
  89. "iiurlwidth": "1280", # Commons 允许的缩略图宽度,原图直链会被 429
  90. }
  91. )
  92. for page in data.get("query", {}).get("pages", {}).values():
  93. ii = (page.get("imageinfo") or [{}])[0]
  94. out.append((page.get("title", ""), ii))
  95. return out
  96. def strip_html(s: str) -> str:
  97. s = html.unescape(s or "")
  98. return re.sub(r"<[^>]+>", "", s).strip()
  99. def meta_value(ii: dict, key: str) -> str:
  100. return strip_html((ii.get("extmetadata", {}).get(key, {}) or {}).get("value", ""))
  101. def classify(title: str):
  102. name = title[5:] if title.lower().startswith("file:") else title
  103. for label, pat in TYPE_PATTERNS:
  104. if pat.search(name):
  105. return label
  106. return "other"
  107. def safe_name(title: str) -> str:
  108. name = title[5:] if title.lower().startswith("file:") else title
  109. return re.sub(r'[\\/:*?"<>|]', "_", name)
  110. def main() -> int:
  111. ap = argparse.ArgumentParser()
  112. ap.add_argument("--out", default=os.path.join(ROOT, "dataset", "web_cc"))
  113. ap.add_argument("--max-per-type", type=int, default=30)
  114. ap.add_argument("--dry-run", action="store_true")
  115. args = ap.parse_args()
  116. titles = []
  117. for cat in CATEGORIES:
  118. print("category:", cat, file=sys.stderr)
  119. titles.extend(category_files(cat))
  120. titles = list(dict.fromkeys(titles))
  121. print("total files:", len(titles), file=sys.stderr)
  122. records = file_info(titles)
  123. counts: dict = {}
  124. rows = []
  125. for title, ii in records:
  126. label = classify(title)
  127. if label == "other":
  128. continue
  129. if counts.get(label, 0) >= args.max_per_type:
  130. continue
  131. # 优先用缩略图 URL(thumburl),Commons 对它不限流;没有则用原图
  132. url = ii.get("thumburl") or ii.get("url")
  133. if not url:
  134. continue
  135. license_name = meta_value(ii, "LicenseShortName")
  136. author = meta_value(ii, "Artist")
  137. counts[label] = counts.get(label, 0) + 1
  138. rows.append(
  139. {
  140. "type": label,
  141. "title": title,
  142. "url": url, # 实际下载的是缩略图 URL
  143. "source_page": ii.get("descriptionurl", ""),
  144. "license": license_name,
  145. "author": author[:200],
  146. }
  147. )
  148. print("selected:", len(rows), "by type:", counts, file=sys.stderr)
  149. if args.dry_run:
  150. for r in rows:
  151. print("%-8s %-12s %s" % (r["type"], r["license"], r["title"]))
  152. return 0
  153. os.makedirs(args.out, exist_ok=True)
  154. with open(os.path.join(args.out, "LICENSES.csv"), "w", newline="", encoding="utf-8-sig") as fh:
  155. w = csv.DictWriter(fh, fieldnames=["type", "title", "url", "source_page", "license", "author"])
  156. w.writeheader()
  157. for r in rows:
  158. folder = os.path.join(args.out, r["type"])
  159. os.makedirs(folder, exist_ok=True)
  160. path = os.path.join(folder, safe_name(r["title"]))
  161. if not os.path.exists(path):
  162. ok = False
  163. for attempt in range(3):
  164. try:
  165. req = urllib.request.Request(url=r["url"], headers={"User-Agent": UA})
  166. with urllib.request.urlopen(req, timeout=60) as resp, open(path, "wb") as out:
  167. out.write(resp.read())
  168. print("saved", r["type"], os.path.basename(path), file=sys.stderr)
  169. ok = True
  170. break
  171. except Exception as exc: # pragma: no cover
  172. print("retry %d" % attempt, r["title"], exc, file=sys.stderr)
  173. time.sleep(2 * (attempt + 1))
  174. if not ok:
  175. continue
  176. w.writerow(r)
  177. time.sleep(1.0) # 限速,避免再次触发 429
  178. print("done. output:", args.out, file=sys.stderr)
  179. return 0
  180. if __name__ == "__main__":
  181. raise SystemExit(main())