File size: 1,592 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 56 57 58 59 | import os
from pdf_parser import extract_text_from_pdf
from rag import RAG
from llm import ask_llm
from utils import save_uploaded_file, cleanup_temp_files
rag = RAG()
def upload_document(file):
if file is None:
return "⚠️ Please select a valid PDF document.", "No document indexed."
# 1. Save uploaded file to temp/
temp_path = save_uploaded_file(file)
if not temp_path or not os.path.exists(temp_path):
return "❌ Error saving uploaded file.", "Upload failed."
try:
# 2. Extract text from PDF
text = extract_text_from_pdf(temp_path)
if not text or not text.strip():
return "⚠️ No readable text found in PDF.", "Extraction empty."
# 3. Create FAISS vector index
rag.create_index(text)
chunk_count = len(rag.chunks)
filename = os.path.basename(temp_path)
return (
f"✅ **{filename}** indexed successfully ({chunk_count} text chunks ready).",
f"📄 Active: **{filename}** ({chunk_count} chunks)"
)
finally:
# 4. Clean up temporary folder
cleanup_temp_files()
def chat(question, history):
if history is None:
history = []
if not question or not question.strip():
return history
results = rag.search(question)
answer = ask_llm(results, question, history=history)
# Gradio 6 chatbot messages format
history.append({"role": "user", "content": question})
history.append({"role": "assistant", "content": answer})
return history
def clear_chat():
return []
|