| import os |
| import shutil |
| import fitz |
|
|
| TEMP_DIR = os.path.join(os.path.dirname(__file__), "temp") |
|
|
|
|
| def extract_text_from_pdf(pdf_path): |
| doc = fitz.open(pdf_path) |
| text = "" |
|
|
| for page in doc: |
| text += page.get_text() |
|
|
| doc.close() |
| return text |
|
|
|
|
| def process_uploaded_pdfs(file_inputs): |
| """ |
| Saves uploaded PDF files to temp/, extracts text, |
| combines content, and cleans up temp files. |
| """ |
| os.makedirs(TEMP_DIR, exist_ok=True) |
|
|
| if file_inputs is None: |
| return "" |
|
|
| if isinstance(file_inputs, (str, bytes)): |
| file_inputs = [file_inputs] |
|
|
| combined_text = "" |
|
|
| for file_item in file_inputs: |
| file_path = getattr(file_item, "name", file_item) |
| if not file_path or not os.path.exists(file_path): |
| continue |
|
|
| filename = os.path.basename(file_path) |
| temp_file_path = os.path.join(TEMP_DIR, filename) |
|
|
| |
| shutil.copy(file_path, temp_file_path) |
|
|
| try: |
| |
| extracted = extract_text_from_pdf(temp_file_path) |
| combined_text += f"\n--- Document: {filename} ---\n{extracted}\n" |
| finally: |
| |
| if os.path.exists(temp_file_path): |
| os.remove(temp_file_path) |
|
|
| return combined_text |
|
|