Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from pypdf import PdfReader
|
| 4 |
+
from sentence_transformers import SentenceTransformer
|
| 5 |
+
import faiss
|
| 6 |
+
import numpy as np
|
| 7 |
+
import requests
|
| 8 |
+
|
| 9 |
+
# Set your Groq API key and model
|
| 10 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY", "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")
|
| 11 |
+
GROQ_MODEL = "llama3-8b-8192"
|
| 12 |
+
|
| 13 |
+
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")
|
| 14 |
+
|
| 15 |
+
def extract_text_from_pdf(file):
|
| 16 |
+
reader = PdfReader(file)
|
| 17 |
+
return "\n".join(page.extract_text() or "" for page in reader.pages)
|
| 18 |
+
|
| 19 |
+
def embed_document(text, chunk_size=500):
|
| 20 |
+
chunks = [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
|
| 21 |
+
embeddings = embedding_model.encode(chunks)
|
| 22 |
+
index = faiss.IndexFlatL2(embeddings.shape[1])
|
| 23 |
+
index.add(np.array(embeddings))
|
| 24 |
+
return chunks, index
|
| 25 |
+
|
| 26 |
+
def query_groq(prompt):
|
| 27 |
+
url = "https://api.groq.com/openai/v1/chat/completions"
|
| 28 |
+
headers = {
|
| 29 |
+
"Authorization": f"Bearer {GROQ_API_KEY}",
|
| 30 |
+
"Content-Type": "application/json"
|
| 31 |
+
}
|
| 32 |
+
payload = {
|
| 33 |
+
"model": GROQ_MODEL,
|
| 34 |
+
"messages": [
|
| 35 |
+
{
|
| 36 |
+
"role": "system",
|
| 37 |
+
"content": (
|
| 38 |
+
"You are a helpful and knowledgeable AI assistant. A user has uploaded a document. "
|
| 39 |
+
"Your task is to analyze the content of the document and provide accurate, clear, and concise answers to any questions "
|
| 40 |
+
"the user asks based on that document. If the answer is not found in the document, politely state that the information is not available in the provided file."
|
| 41 |
+
)
|
| 42 |
+
},
|
| 43 |
+
{"role": "user", "content": prompt}
|
| 44 |
+
],
|
| 45 |
+
"temperature": 0.3
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
response = requests.post(url, headers=headers, json=payload)
|
| 49 |
+
try:
|
| 50 |
+
data = response.json()
|
| 51 |
+
if 'choices' in data:
|
| 52 |
+
return data['choices'][0]['message']['content']
|
| 53 |
+
elif 'error' in data:
|
| 54 |
+
return f"β API Error: {data['error']['message']}"
|
| 55 |
+
else:
|
| 56 |
+
return "β Unexpected API response:\n" + str(data)
|
| 57 |
+
except Exception as e:
|
| 58 |
+
return f"β Failed to parse response: {e}\nRaw: {response.text}"
|
| 59 |
+
|
| 60 |
+
doc_chunks = []
|
| 61 |
+
doc_index = None
|
| 62 |
+
|
| 63 |
+
def handle_upload(file):
|
| 64 |
+
global doc_chunks, doc_index
|
| 65 |
+
text = extract_text_from_pdf(file.name)
|
| 66 |
+
doc_chunks, doc_index = embed_document(text)
|
| 67 |
+
return "β
Document processed. You may now ask questions."
|
| 68 |
+
|
| 69 |
+
def answer_question(question):
|
| 70 |
+
if not doc_chunks or doc_index is None:
|
| 71 |
+
return "β οΈ Please upload a document first."
|
| 72 |
+
|
| 73 |
+
query_embedding = embedding_model.encode([question])
|
| 74 |
+
D, I = doc_index.search(np.array(query_embedding), k=5)
|
| 75 |
+
context = "\n\n".join([doc_chunks[i] for i in I[0]])
|
| 76 |
+
prompt = f"The user asked: '{question}'\n\nUse the following document content to answer:\n{context}"
|
| 77 |
+
return query_groq(prompt)
|
| 78 |
+
|
| 79 |
+
with gr.Blocks() as demo:
|
| 80 |
+
gr.Markdown("## π RAG App with Groq API (PDF-Based Q&A)")
|
| 81 |
+
with gr.Row():
|
| 82 |
+
file_input = gr.File(label="Upload PDF", file_types=[".pdf"])
|
| 83 |
+
upload_btn = gr.Button("Process Document")
|
| 84 |
+
upload_status = gr.Textbox(label="Status", interactive=False)
|
| 85 |
+
|
| 86 |
+
question = gr.Textbox(label="Ask a question about the document")
|
| 87 |
+
answer = gr.Textbox(label="Answer", lines=5)
|
| 88 |
+
|
| 89 |
+
upload_btn.click(fn=handle_upload, inputs=file_input, outputs=upload_status)
|
| 90 |
+
question.submit(fn=answer_question, inputs=question, outputs=answer)
|
| 91 |
+
|
| 92 |
+
demo.launch()
|