fassabilf commited on
Commit
4331e54
Β·
verified Β·
1 Parent(s): 7f42893

add extract_and_upload.py

Browse files
Files changed (1) hide show
  1. extract_and_upload.py +353 -0
extract_and_upload.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Stage 3 β€” Extract text dari PDF + upload ke HF Hub (bukan full PDF).
3
+
4
+ Jauh lebih kecil & cepat karena upload text aja.
5
+
6
+ Output:
7
+ texts_2025/{venue}/{idx}_{slug}.txt β€” extracted text
8
+ texts_2025/all_papers.jsonl β€” satu file metadata + full text
9
+
10
+ Usage:
11
+ python3 extract_and_upload.py
12
+ python3 extract_and_upload.py --workers 16
13
+ python3 extract_and_upload.py --skip-upload # extract aja, jangan upload
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import re
20
+ import sys
21
+ import threading
22
+ import time
23
+ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor, as_completed
24
+ from pathlib import Path
25
+
26
+ import fitz # PyMuPDF
27
+
28
+ try:
29
+ from huggingface_hub import create_repo, upload_file, repo_exists
30
+ HAS_HF = True
31
+ except ImportError:
32
+ HAS_HF = False
33
+
34
+ # ─── CONFIG ──────────────────────────────────────────────────────────────────
35
+
36
+ DEFAULT_PAPERS_DIR = Path("papers_2025")
37
+ DEFAULT_OUT_DIR = Path("texts_2025")
38
+ DEFAULT_REPO_ID = "fassabilf/ir2025-papers-text"
39
+ DEFAULT_WORKERS = 8
40
+ DEFAULT_STATE_FILE = Path(".extract_state.json")
41
+
42
+ print_lock = threading.Lock()
43
+
44
+
45
+ def log(msg: str):
46
+ with print_lock:
47
+ print(msg, flush=True)
48
+
49
+
50
+ # ─── STATE ───────────────────────────────────────────────────────────────────
51
+
52
+ def load_state(path: Path) -> set[str]:
53
+ if path.exists():
54
+ try:
55
+ return set(json.loads(path.read_text()))
56
+ except Exception:
57
+ return set()
58
+ return set()
59
+
60
+
61
+ def save_state(path: Path, done: set[str]):
62
+ path.write_text(json.dumps(sorted(done), ensure_ascii=False, indent=2))
63
+
64
+
65
+ # ─── EXTRACT ─────────────────────────────────────────────────────────────────
66
+
67
+ def clean_text(text: str) -> str:
68
+ """Bersihin whitespace berlebih tanpa merusak struktur paragraf."""
69
+ text = re.sub(r'\r\n|\r', '\n', text)
70
+ text = re.sub(r'\n{4,}', '\n\n\n', text)
71
+ text = re.sub(r' {3,}', ' ', text)
72
+ text = re.sub(r'(\S)\n(\S)', r'\1 \2', text) # gabung hyphenated word
73
+ return text.strip()
74
+
75
+
76
+ def _extract_worker(args) -> dict:
77
+ """
78
+ Worker function (module-level = bisa di-pickle untuk ProcessPoolExecutor).
79
+ args = (pdf_path_str, out_dir_str)
80
+ Return dict dengan hasil, BUKAN return value langsung (hindari pickle error).
81
+ """
82
+ pdf_path_str, out_dir_str = args
83
+ import re as _re
84
+
85
+ try:
86
+ doc = fitz.open(pdf_path_str)
87
+ text = ""
88
+ for page in doc:
89
+ text += page.get_text("text") + "\n"
90
+ doc.close()
91
+
92
+ # Clean text inline
93
+ text = _re.sub(r'\r\n|\r', '\n', text)
94
+ text = _re.sub(r'\n{4,}', '\n\n\n', text)
95
+ text = _re.sub(r' {3,}', ' ', text)
96
+ text = _re.sub(r'(\S)\n(\S)', r'\1 \2', text)
97
+ text = text.strip()
98
+
99
+ if not text or len(text) < 100:
100
+ return {"ok": False, "msg": f"text terlalu pendek ({len(text)} chars)", "text": ""}
101
+
102
+ # Save txt
103
+ out_dir = Path(out_dir_str)
104
+ rel = str(Path(pdf_path_str).relative_to(out_dir.parent / "papers_2025"))
105
+ txt_path = out_dir / Path(rel).with_suffix(".txt")
106
+ txt_path.parent.mkdir(parents=True, exist_ok=True)
107
+ txt_path.write_text(text, encoding="utf-8")
108
+
109
+ return {"ok": True, "msg": f"{len(text)} chars", "text": text}
110
+
111
+ except Exception as e:
112
+ return {"ok": False, "msg": f"{type(e).__name__}: {e}", "text": ""}
113
+
114
+
115
+ def extract_one(pdf_path: Path, out_dir: Path) -> tuple[bool, str, str]:
116
+ """Wrapper untuk backward compatibility."""
117
+ r = _extract_worker((str(pdf_path), str(out_dir)))
118
+ return r["ok"], r["msg"], r["text"]
119
+
120
+
121
+ def run_extraction(
122
+ pdf_files: list[Path],
123
+ out_dir: Path,
124
+ state_file: Path,
125
+ workers: int,
126
+ ) -> list[dict]:
127
+ """Extract parallel."""
128
+ done_set = load_state(state_file)
129
+ to_do = [p for p in pdf_files if str(p) not in done_set and p.exists()]
130
+ missing = len([p for p in pdf_files if str(p) not in done_set]) - len(to_do)
131
+
132
+ results = []
133
+ total = len(to_do)
134
+ if missing:
135
+ log(f"Skip {missing} file missing (gak kedownload)")
136
+
137
+ if not total:
138
+ log("Semua file sudah di-extract.")
139
+ return results
140
+
141
+ done = 0
142
+ # Gunakan ProcessPoolExecutor β€” segfault di PyMuPDF gak akan bunuh main process
143
+ with ProcessPoolExecutor(max_workers=workers) as ex:
144
+ future_map = {
145
+ ex.submit(_extract_worker, (str(p), str(out_dir))): p for p in to_do
146
+ }
147
+ for future in as_completed(future_map):
148
+ pdf_path = future_map[future]
149
+ try:
150
+ result = future.result(timeout=120) # timeout 2 menit per PDF
151
+ ok, msg, full_text = result["ok"], result["msg"], result["text"]
152
+ except Exception as e:
153
+ ok, msg, full_text = False, f"worker crash: {type(e).__name__}: {e}", ""
154
+
155
+ done += 1
156
+ venue = pdf_path.parent.name
157
+ fname = pdf_path.name[:55]
158
+ marker = "βœ“" if ok else "βœ—"
159
+ log(f" [{done:5d}/{total}] {marker} [{venue}] {fname}")
160
+ if not ok:
161
+ log(f" {msg}")
162
+
163
+ if ok:
164
+ done_set.add(str(pdf_path))
165
+ if done % 10 == 0:
166
+ save_state(state_file, done_set)
167
+
168
+ results.append({
169
+ "path": str(pdf_path),
170
+ "venue": venue,
171
+ "filename": pdf_path.name,
172
+ "ok": ok,
173
+ "msg": msg,
174
+ "text": full_text,
175
+ })
176
+
177
+ save_state(state_file, done_set)
178
+ return results
179
+
180
+
181
+ # ─── BUILD JSONL ─────────────────────────────────────────────────────────────
182
+
183
+ def build_jsonl(results: list[dict], out_dir: Path, metadata_map: dict):
184
+ """Buat satu file all_papers.jsonl dengan metadata + full text."""
185
+ jsonl_path = out_dir / "all_papers.jsonl"
186
+ count = 0
187
+
188
+ with open(jsonl_path, "w", encoding="utf-8") as f:
189
+ for r in results:
190
+ if not r["ok"] or not r["text"]:
191
+ continue
192
+ key = r["filename"] # cocokin pake filename
193
+ meta = metadata_map.get(key, {})
194
+ entry = {
195
+ "venue": r["venue"],
196
+ "filename": r["filename"],
197
+ "title": meta.get("title", ""),
198
+ "authors": meta.get("authors", []),
199
+ "year": meta.get("year", 2025),
200
+ "doi": meta.get("doi", ""),
201
+ "abstract": meta.get("abstract", ""),
202
+ "full_text": r["text"][:50000], # limit 50k char per paper
203
+ }
204
+ f.write(json.dumps(entry, ensure_ascii=False) + "\n")
205
+ count += 1
206
+
207
+ return jsonl_path, count
208
+
209
+
210
+ # ─── UPLOAD ──────────────────────────────────────────────────────────────────
211
+
212
+ def upload_text_files(out_dir: Path, repo_id: str, token: str, workers: int):
213
+ """Upload folder teks ke HF Hub dataset."""
214
+ if not HAS_HF:
215
+ log("[SKIP] huggingface_hub tidak terinstall.")
216
+ return
217
+
218
+ # Upload jsonl dulu (paling penting)
219
+ jsonl = out_dir / "all_papers.jsonl"
220
+ if jsonl.exists():
221
+ log(f"Upload {jsonl.name} ...")
222
+ upload_file(
223
+ path_or_fileobj=str(jsonl),
224
+ path_in_repo="all_papers.jsonl",
225
+ repo_id=repo_id,
226
+ repo_type="dataset",
227
+ token=token,
228
+ commit_message="add all_papers.jsonl",
229
+ )
230
+ log(" βœ“ all_papers.jsonl uploaded")
231
+
232
+ # Upload .txt per venue
233
+ txt_files = sorted(out_dir.rglob("*.txt"))
234
+ total = len(txt_files)
235
+ log(f"\nUpload {total} file teks ...")
236
+
237
+ done = 0
238
+ with ThreadPoolExecutor(max_workers=workers) as ex:
239
+ future_map = {}
240
+ for p in txt_files:
241
+ rel = str(p.relative_to(out_dir))
242
+ future_map[
243
+ ex.submit(
244
+ upload_file,
245
+ path_or_fileobj=str(p),
246
+ path_in_repo=rel,
247
+ repo_id=repo_id,
248
+ repo_type="dataset",
249
+ token=token,
250
+ commit_message=f"add {rel}",
251
+ )
252
+ ] = (p, rel)
253
+
254
+ for future in as_completed(future_map):
255
+ p, rel = future_map[future]
256
+ try:
257
+ future.result()
258
+ done += 1
259
+ if done % 50 == 0:
260
+ log(f" [{done}/{total}]")
261
+ except Exception as e:
262
+ log(f" βœ— {rel}: {e}")
263
+ done += 1
264
+
265
+ log(f"Upload selesai: {done}/{total}")
266
+
267
+
268
+ # ─── MAIN ────────────────────────────────────────────────────────────────────
269
+
270
+ def main():
271
+ parser = argparse.ArgumentParser(description="Extract text PDF + upload ke HF")
272
+ parser.add_argument("--papers-dir", default=str(DEFAULT_PAPERS_DIR))
273
+ parser.add_argument("--out-dir", default=str(DEFAULT_OUT_DIR))
274
+ parser.add_argument("--workers", type=int, default=DEFAULT_WORKERS)
275
+ parser.add_argument("--state-file", default=str(DEFAULT_STATE_FILE))
276
+ parser.add_argument("--repo-id", default=DEFAULT_REPO_ID)
277
+ parser.add_argument("--token-file", default=None)
278
+ parser.add_argument("--skip-upload", action="store_true")
279
+ parser.add_argument("--skip-extract", action="store_true")
280
+ args = parser.parse_args()
281
+
282
+ papers_dir = Path(args.papers_dir)
283
+ out_dir = Path(args.out_dir)
284
+ state_file = Path(args.state_file)
285
+
286
+ if not papers_dir.exists():
287
+ print(f"[ERROR] Folder tidak ditemukan: {papers_dir}")
288
+ sys.exit(1)
289
+
290
+ # Cari semua PDF
291
+ pdf_files = sorted(papers_dir.rglob("*.pdf"))
292
+ print(f"Total PDF : {len(pdf_files)}")
293
+
294
+ # Load metadata map untuk jsonl
295
+ metadata_map = {}
296
+ meta_json = papers_dir.parent / "papers_metadata.json"
297
+ if meta_json.exists():
298
+ with open(meta_json) as f:
299
+ all_meta = json.load(f)
300
+ for m in all_meta:
301
+ # buat key dari title (mirip safe_filename)
302
+ clean = "".join(c if c.isalnum() or c in " -_" else "" for c in m.get("title", ""))
303
+ slug = clean.strip().replace(" ", "_")[:60]
304
+ for i in range(1, 9999):
305
+ key = f"{i:03d}_{slug}.pdf"
306
+ if key not in metadata_map:
307
+ metadata_map[key] = m
308
+ break
309
+
310
+ # Extract
311
+ results = []
312
+ if not args.skip_extract:
313
+ print(f"Extract text β€” {args.workers} workers")
314
+ print(f"Output : {out_dir.resolve()}\n")
315
+ t0 = time.time()
316
+ results = run_extraction(pdf_files, out_dir, state_file, workers=args.workers)
317
+ elapsed = time.time() - t0
318
+
319
+ ok_n = sum(1 for r in results if r["ok"])
320
+ fail_n = len(results) - ok_n
321
+ print(f"\nExtract selesai: {ok_n}/{len(results)} ({elapsed:.0f}s)")
322
+
323
+ # Build JSONL
324
+ if ok_n > 0:
325
+ jsonl_path, count = build_jsonl(results, out_dir, metadata_map)
326
+ size_mb = jsonl_path.stat().st_size / (1024 * 1024)
327
+ print(f"JSONL : {count} papers, {size_mb:.1f} MB")
328
+ else:
329
+ print("[SKIP] Extract")
330
+
331
+ # Upload
332
+ if not args.skip_upload:
333
+ token = os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACE_HUB_TOKEN")
334
+ if args.token_file:
335
+ token = Path(args.token_file).read_text().strip()
336
+ if not token:
337
+ print("\n[ERROR] HF_TOKEN tidak ditemukan.")
338
+ sys.exit(1)
339
+
340
+ if not repo_exists(args.repo_id, repo_type="dataset", token=token):
341
+ create_repo(args.repo_id, repo_type="dataset", token=token)
342
+ print(f"Repo dibuat: https://huggingface.co/datasets/{args.repo_id}")
343
+ else:
344
+ print(f"Repo: https://huggingface.co/datasets/{args.repo_id}")
345
+
346
+ upload_text_files(out_dir, args.repo_id, token, workers=args.workers)
347
+ print(f"\nDone: https://huggingface.co/datasets/{args.repo_id}")
348
+ else:
349
+ print("[SKIP] Upload")
350
+
351
+
352
+ if __name__ == "__main__":
353
+ main()