Spaces:
Running
Running
| """ | |
| Extract images and text from a PDF into assets/imported/<pdf_basename>/ | |
| Requires: pip install PyPDF2 pillow pdfminer.six | |
| Usage: python import_from_pdf.py /path/to/file.pdf | |
| """ | |
| import sys | |
| from pathlib import Path | |
| import os | |
| try: | |
| from PyPDF2 import PdfReader | |
| except Exception: | |
| PdfReader = None | |
| def extract_text(pdf_path, out_dir): | |
| if PdfReader is None: | |
| raise RuntimeError('PyPDF2 not installed. pip install PyPDF2') | |
| reader = PdfReader(str(pdf_path)) | |
| texts = [] | |
| for i,page in enumerate(reader.pages): | |
| try: | |
| txt = page.extract_text() or '' | |
| texts.append(f"--- PAGE {i+1} ---\n"+txt) | |
| except Exception as e: | |
| texts.append(f"--- PAGE {i+1} ---\nERROR: {e}") | |
| out = out_dir / 'extracted_text.txt' | |
| out.write_text('\n\n'.join(texts), encoding='utf-8') | |
| print('Wrote', out) | |
| def main(): | |
| if len(sys.argv)<2: | |
| print('Usage: python import_from_pdf.py /path/to/file.pdf') | |
| return | |
| pdf = Path(sys.argv[1]) | |
| if not pdf.exists(): | |
| print('PDF not found:', pdf) | |
| return | |
| base = pdf.stem.replace(' ', '_') | |
| out_dir = Path(__file__).parent / 'imported' / base | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| try: | |
| extract_text(pdf, out_dir) | |
| except Exception as e: | |
| print('Text extraction failed:', e) | |
| print('Done. Review files in', out_dir) | |
| if __name__=='__main__': | |
| main() | |