TechKick's picture
Initial deployment
959c484
Raw
History Blame Contribute Delete
1.39 kB
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