File size: 7,071 Bytes
772c0dc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
"""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"  # Same key the page uses publicly
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)

    # Download PDFs/images/thumbnails in parallel
    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}")

    # Resolve and download DVIDS videos
    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})
        # Pick highest-res mp4 from `video_files` if present
        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()