| """Download UFO/UAP records from war.gov DOW UFO release.
|
|
|
| Bypasses Akamai TLS fingerprint check using curl_cffi browser impersonation.
|
| Reads metadata CSV, then downloads PDFs, images, thumbnails, and videos
|
| (via DVIDS API) in parallel.
|
| """
|
| from __future__ import annotations
|
|
|
| import csv
|
| import json
|
| import os
|
| import re
|
| import sys
|
| from concurrent.futures import ThreadPoolExecutor, as_completed
|
| from pathlib import Path
|
| from urllib.parse import urlparse
|
|
|
| from curl_cffi import requests
|
|
|
| ROOT = Path(__file__).parent / "ufo_data"
|
| CSV_URL = "https://www.war.gov/Portals/1/Interactive/2026/UFO/uap-csv.csv"
|
| DVIDS_API_KEY = "key-68bb60d16b35e"
|
| IMPERSONATE = "chrome120"
|
|
|
|
|
| def safe_name(s: str) -> str:
|
| s = s.strip().replace("/", "_")
|
| s = re.sub(r"[^A-Za-z0-9._-]+", "_", s)
|
| return s.strip("._-") or "file"
|
|
|
|
|
| def download(url: str, dest: Path, session: requests.Session) -> tuple[str, str]:
|
| if dest.exists() and dest.stat().st_size > 0:
|
| return ("skip", str(dest))
|
| dest.parent.mkdir(parents=True, exist_ok=True)
|
| try:
|
| r = session.get(url, impersonate=IMPERSONATE, timeout=120)
|
| if r.status_code != 200:
|
| return (f"err {r.status_code}", url)
|
| tmp = dest.with_suffix(dest.suffix + ".part")
|
| tmp.write_bytes(r.content)
|
| tmp.rename(dest)
|
| return ("ok", f"{dest.name} ({len(r.content):,}B)")
|
| except Exception as e:
|
| return ("exc", f"{url}: {e}")
|
|
|
|
|
| def fetch_csv() -> list[dict]:
|
| s = requests.Session()
|
| r = s.get(CSV_URL, impersonate=IMPERSONATE)
|
| r.raise_for_status()
|
| (ROOT / "csv").mkdir(parents=True, exist_ok=True)
|
| (ROOT / "csv" / "uap-csv.csv").write_bytes(r.content)
|
| text = r.content.decode("utf-8-sig")
|
| return list(csv.DictReader(text.splitlines()))
|
|
|
|
|
| _MP4_RE = re.compile(r'https?://[^"\'\s<>]+\.mp4[^"\'\s<>]*')
|
| _TITLE_RE = re.compile(r"<title>([^<]+)</title>")
|
|
|
|
|
| def get_dvids_video(video_id: str, session: requests.Session) -> dict | None:
|
| """Scrape the public DVIDS video page for the direct mp4 URL."""
|
| url = f"https://www.dvidshub.net/video/{video_id}"
|
| r = session.get(url, impersonate=IMPERSONATE, timeout=60)
|
| if r.status_code != 200:
|
| return None
|
| mp4 = _MP4_RE.search(r.text)
|
| title = _TITLE_RE.search(r.text)
|
| return {
|
| "id": video_id,
|
| "page": url,
|
| "title": title.group(1).strip() if title else "",
|
| "video": mp4.group(0) if mp4 else "",
|
| }
|
|
|
|
|
| def main() -> None:
|
| rows = fetch_csv()
|
| print(f"Records: {len(rows)}")
|
|
|
| pdf_dir = ROOT / "pdfs"
|
| img_dir = ROOT / "images"
|
| thumb_dir = ROOT / "thumbnails"
|
| vid_dir = ROOT / "videos"
|
| meta_dir = ROOT / "metadata"
|
| for d in (pdf_dir, img_dir, thumb_dir, vid_dir, meta_dir):
|
| d.mkdir(parents=True, exist_ok=True)
|
|
|
| jobs: list[tuple[str, Path]] = []
|
| video_rows: list[dict] = []
|
| manifest: list[dict] = []
|
|
|
| for row in rows:
|
| title = (row.get("Title") or "").strip()
|
| rtype = (row.get("Type") or "").strip()
|
| link = (row.get("PDF | Image Link") or "").strip()
|
| thumb = (row.get("Modal Image") or "").strip()
|
| dvid_id = (row.get("DVIDS Video ID") or "").strip()
|
| agency = (row.get("Agency") or "").strip()
|
|
|
| item = {
|
| "title": title,
|
| "type": rtype,
|
| "agency": agency,
|
| "incident_date": row.get("Incident Date", ""),
|
| "incident_location": row.get("Incident Location", ""),
|
| "description": row.get("Description Blurb", ""),
|
| "link": link,
|
| "thumbnail": thumb,
|
| "dvids_video_id": dvid_id,
|
| "files": [],
|
| }
|
|
|
| if link:
|
| ext = Path(urlparse(link).path).suffix or ".bin"
|
| sub = pdf_dir if rtype.startswith("PDF") else img_dir
|
| dest = sub / f"{safe_name(title)}{ext}"
|
| jobs.append((link, dest))
|
| item["files"].append(str(dest.relative_to(ROOT)))
|
|
|
| if thumb:
|
| ext = Path(urlparse(thumb).path).suffix or ".jpg"
|
| dest = thumb_dir / f"{safe_name(title)}{ext}"
|
| jobs.append((thumb, dest))
|
| item["files"].append(str(dest.relative_to(ROOT)))
|
|
|
| if rtype == "VID" and dvid_id:
|
| video_rows.append(row)
|
|
|
| manifest.append(item)
|
|
|
|
|
| print(f"Downloading {len(jobs)} files (PDFs/images/thumbnails)...")
|
| session = requests.Session()
|
| ok = err = skip = 0
|
| with ThreadPoolExecutor(max_workers=8) as ex:
|
| futs = {ex.submit(download, u, d, session): (u, d) for u, d in jobs}
|
| for i, fut in enumerate(as_completed(futs), 1):
|
| status, info = fut.result()
|
| if status == "ok":
|
| ok += 1
|
| elif status == "skip":
|
| skip += 1
|
| else:
|
| err += 1
|
| print(f" [{status}] {info}")
|
| if i % 25 == 0:
|
| print(f" progress: {i}/{len(jobs)} (ok={ok} skip={skip} err={err})")
|
| print(f"Static files: ok={ok} skip={skip} err={err}")
|
|
|
|
|
| print(f"Resolving {len(video_rows)} DVIDS videos...")
|
| video_meta = []
|
| video_jobs: list[tuple[str, Path]] = []
|
| for row in video_rows:
|
| vid = row["DVIDS Video ID"].strip()
|
| meta = get_dvids_video(vid, session)
|
| if not meta:
|
| print(f" [warn] no meta for video {vid}")
|
| continue
|
| video_meta.append({"row_title": row.get("Title", ""), "dvids": meta})
|
|
|
| video_url = meta.get("video") or meta.get("source") or ""
|
| if not video_url:
|
| continue
|
| title = safe_name(row.get("Title") or meta.get("title") or vid)
|
| ext = Path(urlparse(video_url).path).suffix or ".mp4"
|
| dest = vid_dir / f"{title}{ext}"
|
| video_jobs.append((video_url, dest))
|
|
|
| (meta_dir / "dvids_videos.json").write_text(json.dumps(video_meta, indent=2))
|
|
|
| print(f"Downloading {len(video_jobs)} videos...")
|
| ok = err = skip = 0
|
| with ThreadPoolExecutor(max_workers=4) as ex:
|
| futs = {ex.submit(download, u, d, session): (u, d) for u, d in video_jobs}
|
| for i, fut in enumerate(as_completed(futs), 1):
|
| status, info = fut.result()
|
| if status == "ok":
|
| ok += 1
|
| elif status == "skip":
|
| skip += 1
|
| else:
|
| err += 1
|
| print(f" [{status}] {info}")
|
| print(f" video {i}/{len(video_jobs)}: {status} {info}")
|
| print(f"Videos: ok={ok} skip={skip} err={err}")
|
|
|
| (meta_dir / "manifest.json").write_text(json.dumps(manifest, indent=2))
|
| print(f"Wrote manifest with {len(manifest)} records to {meta_dir/'manifest.json'}")
|
|
|
|
|
| if __name__ == "__main__":
|
| main()
|
|
|