File size: 1,392 Bytes
959c484 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | 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)
# 1. Save / Copy to temp/ directory
shutil.copy(file_path, temp_file_path)
try:
# 2. Extract text from temp PDF
extracted = extract_text_from_pdf(temp_file_path)
combined_text += f"\n--- Document: {filename} ---\n{extracted}\n"
finally:
# 3. Delete temporary file when session / extraction ends
if os.path.exists(temp_file_path):
os.remove(temp_file_path)
return combined_text
|