Spaces:
Build error
Build error
Download app.py from Aaryan1314/Bot: direct link, hf CLI and curl.
- Browser
- Download file 3.11 kB
-
https://huggingface.co/spaces/Aaryan1314/Bot/resolve/main/app.py
- Command line
-
hf download hf://spaces/Aaryan1314/Bot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Aaryan1314/Bot/resolve/main/app.py
3.11 kB
| import streamlit as st | |
| import faiss | |
| import numpy as np | |
| import pdfplumber | |
| import tiktoken | |
| from rank_bm25 import BM25Okapi | |
| from sentence_transformers import SentenceTransformer | |
| from transformers import pipeline | |
| # Load embedding model | |
| embedding_model = SentenceTransformer("all-MiniLM-L6-v2") | |
| # Load text-generation model (Replace "gpt2" with "meta-llama/Llama-2-13b-chat-hf" for better results) | |
| qa_model = pipeline("text-generation", model="gpt2") | |
| # Tokenizer for chunking | |
| tokenizer = tiktoken.get_encoding("cl100k_base") | |
| # Function to extract text from PDF | |
| def extract_text_from_pdf(pdf_file): | |
| text = "" | |
| with pdfplumber.open(pdf_file) as pdf: | |
| for page in pdf.pages: | |
| text += page.extract_text() + "\n" | |
| return text | |
| # Function to chunk text | |
| def chunk_text(text, chunk_size=1000, overlap=200): | |
| tokens = tokenizer.encode(text) | |
| chunks = [] | |
| for i in range(0, len(tokens), chunk_size - overlap): | |
| chunks.append(tokenizer.decode(tokens[i:i+chunk_size])) | |
| return chunks | |
| # Create FAISS Index | |
| def create_faiss_index(chunks): | |
| embeddings = np.array([embedding_model.encode(chunk) for chunk in chunks], dtype="float32") | |
| index = faiss.IndexFlatL2(embeddings.shape[1]) | |
| index.add(embeddings) | |
| return index | |
| # FAISS Search | |
| def search_faiss(query, index, chunks, top_k=5): | |
| query_embedding = np.array([embedding_model.encode(query)], dtype="float32") | |
| distances, indices = index.search(query_embedding, top_k) | |
| return [chunks[i] for i in indices[0]] | |
| # Create BM25 Index | |
| def create_bm25_index(chunks): | |
| tokenized_chunks = [chunk.split() for chunk in chunks] | |
| return BM25Okapi(tokenized_chunks), tokenized_chunks | |
| # BM25 Search | |
| def search_bm25(query, bm25, tokenized_chunks, top_k=5): | |
| return bm25.get_top_n(query.split(), tokenized_chunks, n=top_k) | |
| # Generate Answer | |
| def generate_answer(query, faiss_index, bm25, tokenized_chunks, chunks): | |
| faiss_results = search_faiss(query, faiss_index, chunks) | |
| bm25_results = search_bm25(query, bm25, tokenized_chunks) | |
| context = " ".join(faiss_results + bm25_results)[:4000] | |
| prompt = f"Context: {context}\n\nQuestion: {query}\n\nAnswer:" | |
| response = qa_model(prompt, max_length=200, do_sample=True) | |
| return response[0]["generated_text"] | |
| # Streamlit UI | |
| st.title("📜 AI-Powered PDF Q&A System") | |
| uploaded_file = st.file_uploader("Upload a PDF file", type=["pdf"]) | |
| if uploaded_file: | |
| with st.spinner("Processing PDF..."): | |
| text = extract_text_from_pdf(uploaded_file) | |
| chunks = chunk_text(text) | |
| faiss_index = create_faiss_index(chunks) | |
| bm25, tokenized_chunks = create_bm25_index(chunks) | |
| st.success("PDF processed successfully!") | |
| query = st.text_input("Ask a question about the document:") | |
| if st.button("Get Answer"): | |
| if query: | |
| with st.spinner("Generating answer..."): | |
| answer = generate_answer(query, faiss_index, bm25, tokenized_chunks, chunks) | |
| st.subheader("Answer:") | |
| st.write(answer) | |
| else: | |
| st.warning("Please enter a question.") | |