Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,122 +1,106 @@
|
|
| 1 |
import os
|
| 2 |
-
import requests
|
| 3 |
-
import torch
|
| 4 |
-
from transformers import AutoTokenizer, AutoModel
|
| 5 |
-
from PyPDF2 import PdfReader
|
| 6 |
-
from langchain.vectorstores import FAISS
|
| 7 |
-
from langchain.chains import RetrievalQA
|
| 8 |
-
from langchain.prompts import PromptTemplate
|
| 9 |
-
from langchain.llms.base import LLM
|
| 10 |
-
from pydantic import Field
|
| 11 |
-
from typing import Optional, List
|
| 12 |
import streamlit as st
|
| 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 |
-
llm = GroqLLM(api_key="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")
|
| 42 |
-
|
| 43 |
-
# Function to extract content from a public Google Drive PDF link
|
| 44 |
-
def extract_pdf_content(drive_url):
|
| 45 |
-
file_id = drive_url.split("/d/")[1].split("/view")[0]
|
| 46 |
-
download_url = f"https://drive.google.com/uc?export=download&id={file_id}"
|
| 47 |
-
response = requests.get(download_url)
|
| 48 |
-
if response.status_code != 200:
|
| 49 |
-
return None
|
| 50 |
-
|
| 51 |
-
with open("document.pdf", "wb") as f:
|
| 52 |
-
f.write(response.content)
|
| 53 |
-
|
| 54 |
-
reader = PdfReader("document.pdf")
|
| 55 |
-
text = ""
|
| 56 |
-
for page in reader.pages:
|
| 57 |
-
text += page.extract_text()
|
| 58 |
return text
|
| 59 |
|
| 60 |
-
# Function to
|
| 61 |
-
def
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
+
import requests
|
| 4 |
+
import PyPDF2
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
| 6 |
+
import faiss
|
| 7 |
+
import nltk
|
| 8 |
+
from groq import Groq
|
| 9 |
+
|
| 10 |
+
nltk.download('punkt')
|
| 11 |
+
|
| 12 |
+
# Initialize Groq client
|
| 13 |
+
client = Groq(api_key=os.getenv("GROQ_API_KEY"))
|
| 14 |
+
|
| 15 |
+
# Function to extract text from a PDF
|
| 16 |
+
def extract_text_from_pdf(pdf_url):
|
| 17 |
+
# Convert Google Drive shareable link to direct download link
|
| 18 |
+
direct_url = pdf_url.replace("/view?usp=sharing", "").replace("file/d/", "uc?id=")
|
| 19 |
+
response = requests.get(direct_url)
|
| 20 |
+
pdf_content = response.content
|
| 21 |
+
with open("temp.pdf", "wb") as f:
|
| 22 |
+
f.write(pdf_content)
|
| 23 |
+
|
| 24 |
+
# Read the PDF content
|
| 25 |
+
with open("temp.pdf", "rb") as f:
|
| 26 |
+
reader = PyPDF2.PdfReader(f)
|
| 27 |
+
text = ""
|
| 28 |
+
for page in reader.pages:
|
| 29 |
+
text += page.extract_text()
|
| 30 |
+
os.remove("temp.pdf")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
return text
|
| 32 |
|
| 33 |
+
# Function to chunk text
|
| 34 |
+
def chunk_text(text, chunk_size=300):
|
| 35 |
+
sentences = nltk.sent_tokenize(text)
|
| 36 |
+
chunks = []
|
| 37 |
+
current_chunk = []
|
| 38 |
+
current_length = 0
|
| 39 |
+
|
| 40 |
+
for sentence in sentences:
|
| 41 |
+
current_length += len(sentence.split())
|
| 42 |
+
if current_length <= chunk_size:
|
| 43 |
+
current_chunk.append(sentence)
|
| 44 |
+
else:
|
| 45 |
+
chunks.append(" ".join(current_chunk))
|
| 46 |
+
current_chunk = [sentence]
|
| 47 |
+
current_length = len(sentence.split())
|
| 48 |
+
|
| 49 |
+
if current_chunk:
|
| 50 |
+
chunks.append(" ".join(current_chunk))
|
| 51 |
+
return chunks
|
| 52 |
+
|
| 53 |
+
# Function to create embeddings and store them in FAISS
|
| 54 |
+
def create_faiss_index(chunks):
|
| 55 |
+
model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 56 |
+
embeddings = model.encode(chunks)
|
| 57 |
+
dimension = embeddings.shape[1]
|
| 58 |
+
index = faiss.IndexFlatL2(dimension)
|
| 59 |
+
index.add(embeddings)
|
| 60 |
+
return index, embeddings
|
| 61 |
+
|
| 62 |
+
# Function to query FAISS
|
| 63 |
+
def query_faiss(index, query, chunks, model):
|
| 64 |
+
query_vector = model.encode([query])
|
| 65 |
+
distances, indices = index.search(query_vector, k=3)
|
| 66 |
+
results = [chunks[i] for i in indices[0]]
|
| 67 |
+
return results
|
| 68 |
+
|
| 69 |
+
# Main Streamlit App
|
| 70 |
+
def main():
|
| 71 |
+
st.title("RAG-based Application")
|
| 72 |
+
st.write("Interact with your document using Groq-powered model.")
|
| 73 |
+
|
| 74 |
+
# Pre-defined document link
|
| 75 |
+
doc_link = "https://drive.google.com/file/d/1XvqA1OIssRs2gbmOtKFKj-02yQ5X2yg0/view?usp=sharing"
|
| 76 |
+
|
| 77 |
+
# Extract Document Content
|
| 78 |
+
if "document_text" not in st.session_state:
|
| 79 |
+
st.write("Extracting document content...")
|
| 80 |
+
text = extract_text_from_pdf(doc_link)
|
| 81 |
+
st.session_state['document_text'] = text
|
| 82 |
+
st.success("Document content extracted!")
|
| 83 |
+
|
| 84 |
+
# Process Document and Create FAISS Index
|
| 85 |
+
if 'document_text' in st.session_state and "faiss_index" not in st.session_state:
|
| 86 |
+
st.write("Processing document...")
|
| 87 |
+
chunks = chunk_text(st.session_state['document_text'])
|
| 88 |
+
index, embeddings = create_faiss_index(chunks)
|
| 89 |
+
st.session_state['faiss_index'] = index
|
| 90 |
+
st.session_state['chunks'] = chunks
|
| 91 |
+
st.session_state['model'] = SentenceTransformer("all-MiniLM-L6-v2")
|
| 92 |
+
st.success(f"Document processed into {len(chunks)} chunks!")
|
| 93 |
+
|
| 94 |
+
# Query the Document
|
| 95 |
+
if 'faiss_index' in st.session_state:
|
| 96 |
+
st.header("Ask Questions")
|
| 97 |
+
query = st.text_input("Enter your question here")
|
| 98 |
+
if st.button("Query Document"):
|
| 99 |
+
results = query_faiss(st.session_state['faiss_index'], query, st.session_state['chunks'], st.session_state['model'])
|
| 100 |
+
st.write("### Results from Document:")
|
| 101 |
+
for i, result in enumerate(results):
|
| 102 |
+
st.write(f"**Result {i+1}:** {result}")
|
| 103 |
+
|
| 104 |
+
# Use Groq API for additional insights
|
| 105 |
+
chat_completion = client.chat.completions.create(
|
| 106 |
+
messa
|