Spaces:
Sleeping
Sleeping
Download app.py from Kummari0218/CourseMate-AI: direct link, hf CLI and curl.
- Browser
- Download file 2.15 kB
-
https://huggingface.co/spaces/Kummari0218/CourseMate-AI/resolve/main/app.py
- Command line
-
hf download hf://spaces/Kummari0218/CourseMate-AI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Kummari0218/CourseMate-AI/resolve/main/app.py
2.15 kB
| import gradio as gr | |
| from pypdf import PdfReader | |
| from sentence_transformers import SentenceTransformer | |
| import faiss | |
| import numpy as np | |
| embed_model = SentenceTransformer('all-MiniLM-L6-v2') | |
| index = None | |
| chunks = None | |
| def load_pdf(file): | |
| reader = PdfReader(file) | |
| text = "" | |
| for page in reader.pages: | |
| page_text = page.extract_text() | |
| if page_text: | |
| text += page_text | |
| return text | |
| def 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 index | |
| def retrieve(query, index, chunks): | |
| query_vec = embed_model.encode([query]) | |
| query_vec = np.array(query_vec).astype("float32") | |
| D, I = index.search(query_vec, 1) | |
| return chunks[I[0][0]] | |
| def answer_question(query): | |
| global index, chunks | |
| if index is None: | |
| return "β Upload and process PDF first." | |
| result = retrieve(query, index, chunks) | |
| return result[:500] | |
| def process_pdf(file): | |
| global index, chunks | |
| if 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)) # β correct | |
| return "", history | |
| with 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 version | |
| msg = 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) |