Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,113 @@
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
-
from
|
3 |
-
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
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 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
)
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import List, Optional
|
3 |
+
|
4 |
import gradio as gr
|
5 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
6 |
+
from langchain_community.vectorstores import Chroma
|
7 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
8 |
+
from langchain.document_loaders import TextLoader
|
9 |
+
from langchain.docstore.document import Document
|
10 |
+
from langchain.chains import RetrievalQA
|
11 |
+
from langchain.llms.base import LLM
|
12 |
+
from groq import Groq
|
13 |
+
import pypdf # PyMuPDF
|
14 |
+
|
15 |
+
|
16 |
+
# --- Custom LLM class using Groq ---
|
17 |
+
class GroqLLM(LLM):
|
18 |
+
model: str = "llama3-8b-8192"
|
19 |
+
api_key: str = "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" # <-- PUT YOUR GROQ API KEY HERE
|
20 |
+
temperature: float = 0.0
|
21 |
+
|
22 |
+
def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
|
23 |
+
client = Groq(api_key=self.api_key)
|
24 |
+
messages = [
|
25 |
+
{"role": "system", "content": "You are a helpful assistant."},
|
26 |
+
{"role": "user", "content": prompt}
|
27 |
+
]
|
28 |
+
response = client.chat.completions.create(
|
29 |
+
model=self.model,
|
30 |
+
messages=messages,
|
31 |
+
temperature=self.temperature,
|
32 |
+
)
|
33 |
+
return response.choices[0].message.content
|
34 |
+
|
35 |
+
@property
|
36 |
+
def _llm_type(self) -> str:
|
37 |
+
return "groq-llm"
|
38 |
+
|
39 |
+
|
40 |
+
# --- RAG Setup ---
|
41 |
+
retriever = None
|
42 |
+
qa_chain = None
|
43 |
+
|
44 |
+
|
45 |
+
def extract_text_from_pdf(file_path: str) -> str:
|
46 |
+
doc = fitz.open(file_path)
|
47 |
+
text = ""
|
48 |
+
for page in doc:
|
49 |
+
text += page.get_text()
|
50 |
+
doc.close()
|
51 |
+
return text
|
52 |
+
|
53 |
+
|
54 |
+
def process_file(file_obj):
|
55 |
+
global retriever, qa_chain
|
56 |
+
|
57 |
+
ext = os.path.splitext(file_obj.name)[1].lower()
|
58 |
+
try:
|
59 |
+
# Load content
|
60 |
+
if ext == ".pdf":
|
61 |
+
text = extract_text_from_pdf(file_obj.name)
|
62 |
+
elif ext == ".txt":
|
63 |
+
with open(file_obj.name, "r", encoding="utf-8") as f:
|
64 |
+
text = f.read()
|
65 |
+
else:
|
66 |
+
return "❌ Unsupported file format. Please upload a .txt or .pdf file."
|
67 |
+
|
68 |
+
# Create document chunks
|
69 |
+
document = Document(page_content=text)
|
70 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
71 |
+
docs = splitter.split_documents([document])
|
72 |
+
|
73 |
+
# Vectorstore with HuggingFace embeddings
|
74 |
+
embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
|
75 |
+
vectorstore = Chroma.from_documents(docs, embedding=embeddings, persist_directory="rag_store")
|
76 |
+
|
77 |
+
retriever = vectorstore.as_retriever()
|
78 |
+
qa_chain = RetrievalQA.from_chain_type(
|
79 |
+
llm=GroqLLM(),
|
80 |
+
retriever=retriever,
|
81 |
+
return_source_documents=True
|
82 |
+
)
|
83 |
+
|
84 |
+
return "✅ File processed successfully. You can now ask questions."
|
85 |
+
|
86 |
+
except Exception as e:
|
87 |
+
return f"❌ Error processing file: {e}"
|
88 |
+
|
89 |
+
|
90 |
+
def ask_question(query):
|
91 |
+
if qa_chain is None:
|
92 |
+
return "⚠ Please upload a file first."
|
93 |
+
result = qa_chain({"query": query})
|
94 |
+
return result["result"]
|
95 |
+
|
96 |
+
|
97 |
+
# --- Gradio UI ---
|
98 |
+
with gr.Blocks(title="RAG PDF & Text Chatbot") as demo:
|
99 |
+
gr.Markdown("## 🧠 RAG-powered Q&A Chatbot (Groq + LangChain)")
|
100 |
+
gr.Markdown("Upload a .pdf or .txt file and ask questions based on its content.")
|
101 |
+
|
102 |
+
file_input = gr.File(label="Upload PDF or Text File", file_types=[".pdf", ".txt"])
|
103 |
+
upload_status = gr.Textbox(label="Status", interactive=False)
|
104 |
+
|
105 |
+
file_input.change(fn=process_file, inputs=file_input, outputs=upload_status)
|
106 |
+
|
107 |
+
question_box = gr.Textbox(label="Ask your question")
|
108 |
+
answer_box = gr.Textbox(label="Answer", interactive=False)
|
109 |
+
|
110 |
+
submit_btn = gr.Button("Get Answer")
|
111 |
+
submit_btn.click(fn=ask_question, inputs=question_box, outputs=answer_box)
|
112 |
+
|
113 |
+
demo.launch()
|