fassabilf commited on
Commit
ea32f54
Β·
verified Β·
1 Parent(s): f92270b

add download.py

Browse files
Files changed (1) hide show
  1. download.py +286 -0
download.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 2 β€” Download PDF dari metadata yang dikumpulkan collect.py.
3
+
4
+ Fitur:
5
+ - Resumable: skip file yang sudah ada
6
+ - Parallel: ThreadPoolExecutor (configurable --workers)
7
+ - Retry: 3x dengan exponential backoff
8
+ - Validasi: cek magic bytes %PDF dan ukuran minimum
9
+ - Laporan: download_report.json
10
+
11
+ Usage:
12
+ python3 download.py
13
+ python3 download.py --workers 8 # lebih banyak thread
14
+ python3 download.py --input custom.json # JSON lain
15
+ python3 download.py --venues SIGIR ACL # venue tertentu saja
16
+ python3 download.py --limit 5 # max 5 paper per venue
17
+ """
18
+
19
+ import argparse
20
+ import json
21
+ import os
22
+ import threading
23
+ import time
24
+ from concurrent.futures import ThreadPoolExecutor, as_completed
25
+ from pathlib import Path
26
+
27
+ import requests
28
+
29
+ # ─── CONFIG ──────────────────────────────────────────────────────────────────
30
+
31
+ DEFAULT_INPUT = Path("papers_metadata.json")
32
+ DEFAULT_OUT_DIR = Path("papers_2025")
33
+ DEFAULT_WORKERS = 5
34
+ DEFAULT_REPORT = Path("download_report.json")
35
+ MIN_PDF_BYTES = 10_000
36
+
37
+ HEADERS = {"User-Agent": "IR-course-downloader/1.0 (academic research)"}
38
+
39
+ print_lock = threading.Lock()
40
+
41
+
42
+ def log(msg: str):
43
+ with print_lock:
44
+ print(msg, flush=True)
45
+
46
+
47
+ # ─── DOWNLOAD ────────────────────────────────────────────────────────────────
48
+
49
+ def safe_filename(title: str, idx: int) -> str:
50
+ clean = "".join(c if c.isalnum() or c in " -_" else "" for c in title)
51
+ slug = clean.strip().replace(" ", "_")[:60]
52
+ return f"{idx:03d}_{slug}.pdf"
53
+
54
+
55
+ def download_pdf(url: str, dest: Path, retries: int = 3) -> tuple[bool, str]:
56
+ """
57
+ Download satu PDF.
58
+ Return (sukses: bool, pesan: str)
59
+ """
60
+ for attempt in range(retries):
61
+ try:
62
+ resp = requests.get(url, headers=HEADERS, timeout=45, stream=True)
63
+ resp.raise_for_status()
64
+
65
+ dest.parent.mkdir(parents=True, exist_ok=True)
66
+ with open(dest, "wb") as f:
67
+ for chunk in resp.iter_content(8192):
68
+ f.write(chunk)
69
+
70
+ size = dest.stat().st_size
71
+ if size < MIN_PDF_BYTES:
72
+ dest.unlink(missing_ok=True)
73
+ return False, f"terlalu kecil ({size} bytes)"
74
+
75
+ # Validasi magic bytes %PDF
76
+ with open(dest, "rb") as f:
77
+ magic = f.read(4)
78
+ if magic != b"%PDF":
79
+ dest.unlink(missing_ok=True)
80
+ return False, f"bukan PDF (magic={magic!r})"
81
+
82
+ return True, f"{size // 1024} KB"
83
+
84
+ except requests.HTTPError as e:
85
+ code = e.response.status_code if e.response else 0
86
+ wait = 3 * (2 ** attempt)
87
+ if code == 429:
88
+ wait = max(wait, 30)
89
+ if attempt < retries - 1:
90
+ time.sleep(wait)
91
+ else:
92
+ dest.unlink(missing_ok=True)
93
+ return False, f"HTTP {code}"
94
+
95
+ except Exception as e:
96
+ dest.unlink(missing_ok=True)
97
+ if attempt < retries - 1:
98
+ time.sleep(3 * (attempt + 1))
99
+ else:
100
+ return False, f"{type(e).__name__}: {e}"
101
+
102
+ return False, "semua retry gagal"
103
+
104
+
105
+ # ─── TASK RUNNER ─────────────────────────────────────────────────────────────
106
+
107
+ def run_downloads(tasks: list[dict], workers: int) -> list[dict]:
108
+ """
109
+ Jalankan download secara paralel.
110
+ Setiap task: {idx, venue, title, pdf_url, dest}
111
+ Return list hasil: {... + ok, msg, size_kb}
112
+ """
113
+ results = []
114
+ total = len(tasks)
115
+
116
+ with ThreadPoolExecutor(max_workers=workers) as ex:
117
+ future_map = {
118
+ ex.submit(download_pdf, t["pdf_url"], Path(t["dest"])): t
119
+ for t in tasks
120
+ }
121
+
122
+ done = 0
123
+ for future in as_completed(future_map):
124
+ task = future_map[future]
125
+ ok, msg = future.result()
126
+ done += 1
127
+
128
+ venue = task["venue"]
129
+ title = task["title"][:55]
130
+ marker = "βœ“" if ok else "βœ—"
131
+ log(f" [{done:3d}/{total}] {marker} [{venue}] {title}")
132
+ if not ok:
133
+ log(f" Gagal: {msg}")
134
+
135
+ results.append({**task, "ok": ok, "msg": msg})
136
+
137
+ return results
138
+
139
+
140
+ # ─── MAIN ────────────────────────────────────────────────────────────────────
141
+
142
+ def main():
143
+ parser = argparse.ArgumentParser(description="Stage 2: Download PDF paper IR 2025")
144
+ parser.add_argument("--input", default=str(DEFAULT_INPUT),
145
+ help=f"File metadata JSON (default: {DEFAULT_INPUT})")
146
+ parser.add_argument("--out-dir", default=str(DEFAULT_OUT_DIR),
147
+ help=f"Folder output (default: {DEFAULT_OUT_DIR})")
148
+ parser.add_argument("--report", default=str(DEFAULT_REPORT),
149
+ help=f"File laporan JSON (default: {DEFAULT_REPORT})")
150
+ parser.add_argument("--workers", type=int, default=DEFAULT_WORKERS,
151
+ help=f"Jumlah thread paralel (default: {DEFAULT_WORKERS})")
152
+ parser.add_argument("--venues", nargs="+", default=None,
153
+ help="Filter venue tertentu (default: semua)")
154
+ parser.add_argument("--limit", type=int, default=None,
155
+ help="Batas paper per venue (default: semua)")
156
+ args = parser.parse_args()
157
+
158
+ input_path = Path(args.input)
159
+ out_dir = Path(args.out_dir)
160
+ report_path = Path(args.report)
161
+
162
+ # Baca metadata
163
+ if not input_path.exists():
164
+ print(f"[ERROR] File tidak ditemukan: {input_path}")
165
+ print("Jalankan collect.py terlebih dahulu.")
166
+ return
167
+
168
+ with open(input_path, encoding="utf-8") as f:
169
+ all_papers = json.load(f)
170
+
171
+ # Filter venue
172
+ if args.venues:
173
+ all_papers = [p for p in all_papers if p["venue"] in args.venues]
174
+
175
+ # Filter yang punya PDF URL
176
+ all_papers = [p for p in all_papers if p.get("pdf_url")]
177
+
178
+ # Grup per venue, terapkan limit
179
+ by_venue: dict[str, list] = {}
180
+ for p in all_papers:
181
+ by_venue.setdefault(p["venue"], []).append(p)
182
+
183
+ if args.limit:
184
+ for vk in by_venue:
185
+ by_venue[vk] = by_venue[vk][: args.limit]
186
+
187
+ # Susun task β€” skip yang sudah ada
188
+ tasks = []
189
+ skipped = 0
190
+ counters: dict[str, int] = {}
191
+
192
+ for venue_key, papers in by_venue.items():
193
+ counters[venue_key] = 0
194
+ for paper in papers:
195
+ counters[venue_key] += 1
196
+ idx = counters[venue_key]
197
+ filename = safe_filename(paper["title"], idx)
198
+ dest = out_dir / venue_key / filename
199
+
200
+ if dest.exists() and dest.stat().st_size >= MIN_PDF_BYTES:
201
+ skipped += 1
202
+ continue
203
+
204
+ tasks.append({
205
+ "idx": idx,
206
+ "venue": venue_key,
207
+ "title": paper["title"],
208
+ "pdf_url": paper["pdf_url"],
209
+ "dest": str(dest),
210
+ "doi": paper.get("doi", ""),
211
+ "source": paper.get("source", ""),
212
+ })
213
+
214
+ total_planned = sum(len(v) for v in by_venue.values())
215
+ print(f"Metadata : {len(all_papers)} paper")
216
+ print(f"Akan diunduh: {len(tasks)} | Sudah ada (skip): {skipped}")
217
+ print(f"Workers : {args.workers}")
218
+ print(f"Output : {out_dir.resolve()}\n")
219
+
220
+ if not tasks:
221
+ print("Tidak ada yang perlu diunduh.")
222
+ return
223
+
224
+ # Jalankan download
225
+ t0 = time.time()
226
+ results = run_downloads(tasks, workers=args.workers)
227
+ elapsed = time.time() - t0
228
+
229
+ # Hitung statistik
230
+ ok_list = [r for r in results if r["ok"]]
231
+ fail_list = [r for r in results if not r["ok"]]
232
+
233
+ by_venue_ok: dict[str, int] = {}
234
+ for r in ok_list:
235
+ by_venue_ok[r["venue"]] = by_venue_ok.get(r["venue"], 0) + 1
236
+
237
+ # Simpan laporan
238
+ report = {
239
+ "total_attempted": len(tasks),
240
+ "success": len(ok_list),
241
+ "failed": len(fail_list),
242
+ "skipped": skipped,
243
+ "elapsed_seconds": round(elapsed, 1),
244
+ "by_venue": {
245
+ vk: {
246
+ "attempted": len(papers),
247
+ "success": by_venue_ok.get(vk, 0),
248
+ }
249
+ for vk, papers in by_venue.items()
250
+ },
251
+ "failures": [
252
+ {"venue": r["venue"], "title": r["title"],
253
+ "pdf_url": r["pdf_url"], "error": r["msg"]}
254
+ for r in fail_list
255
+ ],
256
+ }
257
+ with open(report_path, "w", encoding="utf-8") as f:
258
+ json.dump(report, f, ensure_ascii=False, indent=2)
259
+
260
+ # Ringkasan akhir
261
+ print(f"\n{'='*60}")
262
+ print("RINGKASAN DOWNLOAD")
263
+ print(f"{'='*60}")
264
+ for vk, papers in by_venue.items():
265
+ ok_n = by_venue_ok.get(vk, 0)
266
+ all_n = len(papers)
267
+ bar = "β–ˆ" * ok_n + "β–‘" * (all_n - ok_n)
268
+ print(f" {vk:8s}: {ok_n:3d}/{all_n} {bar}")
269
+
270
+ print(f"\nBerhasil : {len(ok_list)}/{len(tasks)}")
271
+ print(f"Gagal : {len(fail_list)}")
272
+ print(f"Skip : {skipped} (sudah ada)")
273
+ print(f"Waktu : {elapsed:.1f} detik ({elapsed/60:.1f} menit)")
274
+ print(f"Laporan : {report_path}")
275
+ print(f"Folder PDF: {out_dir.resolve()}")
276
+
277
+ if fail_list:
278
+ print(f"\nGagal download ({len(fail_list)} paper):")
279
+ for r in fail_list[:10]:
280
+ print(f" [{r['venue']}] {r['title'][:60]} β€” {r['msg']}")
281
+ if len(fail_list) > 10:
282
+ print(f" ... (+{len(fail_list)-10} lagi, lihat {report_path})")
283
+
284
+
285
+ if __name__ == "__main__":
286
+ main()