Spaces:
Sleeping
Sleeping
Update app.py
Browse files3 unmodified lines456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354551 unmodified line575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281293 unmodified linesimport faissimport numpy as np# -------------------------------# Load embedding model# -------------------------------embed_model = SentenceTransformer('all-MiniLM-L6-v2')# -------------------------------# Global variables# -------------------------------index = Nonechunks = None# -------------------------------# Load PDF# -------------------------------def load_pdf(file):reader = PdfReader(file)text = ""for page in reader.pages:page_text = page.extract_text()if page_text:text += page_textreturn text# -------------------------------# Split text# -------------------------------def split_text(text, chunk_size=500):return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]# -------------------------------# Create vector store# -------------------------------def create_vector_store(chunks):embeddings = embed_model.encode(chunks)embeddings = np.array(embeddings).astype("float32")index = faiss.IndexFlatL2(embeddings.shape[1])index.add(embeddings)return index# -------------------------------# Retrieve best chunk# -------------------------------def retrieve(query, index, chunks):query_vec = embed_model.encode([query])query_vec = np.array(query_vec).astype("float32")1 unmodified lineD, I = index.search(query_vec, 1)return chunks[I[0][0]]# -------------------------------# Answer function# -------------------------------def answer_question(query):global index, chunksif index is None:return "β Upload and process PDF first."result = retrieve(query, index, chunks)return result[:500]# -------------------------------# Process PDF# -------------------------------def process_pdf(file):global index, chunksif file is None:return "β Please upload a PDF."text = load_pdf(file)print("Text length:", len(text))if len(text) == 0:return "β PDF has no readable text (scanned)."chunks = split_text(text)index = create_vector_store(chunks)return "β PDF processed successfully!"# -------------------------------# Chat function (FIXED)# -------------------------------def respond(message, history):if history is None:history = []reply = answer_question(message)# β Correct format (dictionary)history.append({"role": "user", "content": message})history.append({"role": "assistant", "content": reply})return "", history# -------------------------------# UI (FIXED)# -------------------------------with gr.Blocks() as app:gr.Markdown("# π Course Material Chatbot")file_input = gr.File(label="Upload PDF")btn = gr.Button("Process PDF")status = gr.Textbox(label="Status")chatbot = gr.Chatbot(type="messages") # β IMPORTANTmsg = gr.Textbox(placeholder="Ask a question...")clear = gr.Button("Clear Chat")btn.click(process_pdf, inputs=file_input, outputs=status)msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])clear.click(lambda: [], None, chatbot)# -------------------------------# Launch# -------------------------------app.launch(server_name="0.0.0.0", server_port=7860)3 unmodified lines456789101112131415161718192021222324252627282930313233341 unmodified line36373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384853 unmodified linesimport faissimport numpy as npembed_model = SentenceTransformer('all-MiniLM-L6-v2')index = Nonechunks = Nonedef load_pdf(file):reader = PdfReader(file)text = ""for page in reader.pages:page_text = page.extract_text()if page_text:text += page_textreturn textdef split_text(text, chunk_size=500):return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]def create_vector_store(chunks):embeddings = embed_model.encode(chunks)embeddings = np.array(embeddings).astype("float32")index = faiss.IndexFlatL2(embeddings.shape[1])index.add(embeddings)return indexdef retrieve(query, index, chunks):query_vec = embed_model.encode([query])query_vec = np.array(query_vec).astype("float32")1 unmodified lineD, I = index.search(query_vec, 1)return chunks[I[0][0]]def answer_question(query):global index, chunksif index is None:return "β Upload and process PDF first."result = retrieve(query, index, chunks)return result[:500]def process_pdf(file):global index, chunksif file is None:return "β Upload PDF"text = load_pdf(file)if len(text) == 0:return "β PDF has no readable text"chunks = split_text(text)index = create_vector_store(chunks)return "β PDF processed!"def respond(message, history):if history is None:history = []reply = answer_question(message)history.append((message, reply)) # β correctreturn "", historywith gr.Blocks() as app:gr.Markdown("# π Course Chatbot")file_input = gr.File()btn = gr.Button("Process PDF")status = gr.Textbox()chatbot = gr.Chatbot() # β correct for your versionmsg = gr.Textbox()clear = gr.Button("Clear")btn.click(process_pdf, inputs=file_input, outputs=status)msg.submit(respond, inputs=[msg, chatbot], outputs=[msg, chatbot])clear.click(lambda: [], None, chatbot)app.launch(server_name="0.0.0.0", server_port=7860)
app.py+10-54