| """Parse all PDFs + PPTXs from balade/chatbot-assets dataset to markdown. |
| Runs on HF Jobs infra (better CPU than local laptop). |
| |
| Expected mount: /data (read-only, from balade/chatbot-assets dataset) |
| Uploads results back to the same dataset via API.""" |
|
|
| import os, sys, time, json, traceback |
| from pathlib import Path |
|
|
| HF_TOKEN = os.environ.get("HF_TOKEN") |
| if not HF_TOKEN: |
| print("FATAL: HF_TOKEN not set", flush=True) |
| sys.exit(1) |
|
|
| from huggingface_hub import HfApi |
|
|
| REPO = "balade/chatbot-assets" |
| DATA_DIR = Path("/data") |
| OUT_DIR = "parsed_assets" |
| api = HfApi(token=HF_TOKEN) |
|
|
| def log(msg): |
| print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True) |
|
|
| def upload_markdown(remote_path, md_content): |
| if remote_path.lower().endswith(".pdf"): |
| out_path = remote_path[:-4] + ".md" |
| elif remote_path.lower().endswith(".pptx"): |
| out_path = remote_path[:-5] + ".md" |
| else: |
| out_path = remote_path + ".md" |
| out_path = f"{OUT_DIR}/{out_path}" |
| api.upload_file( |
| repo_id=REPO, repo_type="dataset", |
| path_or_fileobj=md_content.encode("utf-8"), |
| path_in_repo=out_path, |
| ) |
| return out_path |
|
|
| def parse_text_pdf(pdf_path): |
| import pymupdf4llm |
| return pymupdf4llm.to_markdown(str(pdf_path)) |
|
|
| def parse_image_pdf(pdf_path): |
| import easyocr, fitz |
| reader = easyocr.Reader(["id"], gpu=False) |
| doc = fitz.open(pdf_path) |
| pages, total = [], doc.page_count |
| for i in range(total): |
| page = doc[i] |
| pix = page.get_pixmap(dpi=200) |
| img = pix.tobytes("png") |
| result = reader.readtext(img) |
| text = "\n".join([r[1] for r in result]) |
| pages.append(f"## Page {i+1}\n\n{text}\n") |
| if (i + 1) % 5 == 0 or i == total - 1: |
| log(f" OCR: {i+1}/{total} pages") |
| doc.close() |
| return "\n\n".join(pages) |
|
|
| def parse_pptx(pptx_path): |
| from pptx import Presentation |
| prs = Presentation(pptx_path) |
| pages = [] |
| for i, slide in enumerate(prs.slides, 1): |
| texts = [] |
| for shape in slide.shapes: |
| if shape.has_text_frame: |
| for para in shape.text_frame.paragraphs: |
| t = para.text.strip() |
| if t: |
| texts.append(t) |
| if shape.has_table: |
| rows = [] |
| for row in shape.table.rows: |
| cells = [cell.text.strip() for cell in row.cells] |
| rows.append(" | ".join(cells)) |
| texts.append("\n".join(rows)) |
| pages.append(f"## Slide {i}\n\n" + "\n\n".join(texts)) |
| return "\n\n".join(pages) |
|
|
| def classify_pdf(pdf_path): |
| import fitz |
| doc = fitz.open(pdf_path) |
| chars = sum(len(page.get_text()) for page in doc) |
| n = doc.page_count |
| doc.close() |
| return chars > 200, chars, n |
|
|
| def main(): |
| log("Starting parsing job on HF infra") |
| log(f"Data dir: {DATA_DIR} (exists: {DATA_DIR.exists()})") |
|
|
| if not DATA_DIR.exists(): |
| log(f"FATAL: {DATA_DIR} not mounted") |
| sys.exit(1) |
|
|
| |
| all_files = sorted(DATA_DIR.rglob("*")) |
| pdfs = [f for f in all_files if f.suffix.lower() == ".pdf"] |
| pptxs = [f for f in all_files if f.suffix.lower() == ".pptx"] |
| log(f"Found {len(pdfs)} PDFs + {len(pptxs)} PPTXs") |
|
|
| |
| try: |
| parsed_set = set() |
| for item in api.list_repo_tree(repo_id=REPO, repo_type="dataset", path=OUT_DIR, recursive=True): |
| parsed_set.add(item.path) |
| log(f"Already parsed: {len(parsed_set)} files") |
| except Exception as e: |
| log(f"No existing parsed files: {e}") |
| parsed_set = set() |
|
|
| results = {"text": 0, "image": 0, "pptx": 0, "errors": [], "skipped": 0} |
| timing = {"text": 0.0, "image": 0.0, "pptx": 0.0} |
|
|
| for local_path in pdfs + pptxs: |
| rel = str(local_path.relative_to(DATA_DIR)) |
| suf = local_path.suffix.lower() |
|
|
| if suf == ".pdf": |
| expected = f"{OUT_DIR}/{rel[:-4]}.md" |
| else: |
| expected = f"{OUT_DIR}/{rel[:-5]}.md" |
|
|
| if expected in parsed_set: |
| log(f"SKIP (exists): {rel}") |
| results["skipped"] += 1 |
| continue |
|
|
| log(f"\n{'='*60}") |
| log(f"Processing: {rel}") |
|
|
| t0 = time.time() |
| try: |
| if suf == ".pdf": |
| is_text, chars, pages = classify_pdf(local_path) |
| if is_text: |
| log(f" TYPE: text PDF ({pages} pg, {chars:,} chars)") |
| md = parse_text_pdf(local_path) |
| timing["text"] += time.time() - t0 |
| results["text"] += 1 |
| else: |
| log(f" TYPE: image PDF ({pages} pg) - OCR...") |
| md = parse_image_pdf(local_path) |
| timing["image"] += time.time() - t0 |
| results["image"] += 1 |
| else: |
| log(f" TYPE: PPTX") |
| md = parse_pptx(local_path) |
| timing["pptx"] += time.time() - t0 |
| results["pptx"] += 1 |
|
|
| out_path = upload_markdown(rel, md) |
| log(f" Done: {out_path} ({len(md):,} chars, {time.time()-t0:.1f}s)") |
|
|
| except Exception as e: |
| log(f" ERROR: {e}") |
| traceback.print_exc() |
| results["errors"].append(rel) |
|
|
| log(f"\n{'='*60}") |
| log(f"RESULTS") |
| log(f" Text PDFs: {results['text']}") |
| log(f" Image PDFs (OCR): {results['image']}") |
| log(f" PPTX: {results['pptx']}") |
| log(f" Skipped: {results['skipped']}") |
| log(f" Errors: {len(results['errors'])}") |
| for e in results["errors"]: |
| log(f" ✗ {e}") |
| log(f" Timing - text: {timing['text']:.1f}s, OCR: {timing['image']:.1f}s, PPTX: {timing['pptx']:.1f}s") |
|
|
| api.upload_file( |
| repo_id=REPO, repo_type="dataset", |
| path_or_fileobj=json.dumps({ |
| "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ"), **results |
| }, indent=2).encode(), |
| path_in_repo=f"{OUT_DIR}/_parse_report.json", |
| ) |
| log("Report uploaded. Done!") |
|
|
| if __name__ == "__main__": |
| main() |
|
|