sreelakshmimukkizhi commited on
Commit
c4b7a63
·
verified ·
1 Parent(s): 9c44ba2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -63
app.py CHANGED
@@ -1,64 +1,113 @@
 
 
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()