Rishitha3 commited on
Commit
2a6a2d5
·
verified ·
1 Parent(s): e3381ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +153 -65
app.py CHANGED
@@ -1,70 +1,158 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
-
5
- def respond(
6
- message,
7
- history: list[dict[str, str]],
8
- system_message,
9
- max_tokens,
10
- temperature,
11
- top_p,
12
- hf_token: gr.OAuthToken,
13
- ):
14
- """
15
- 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
16
- """
17
- client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")
18
-
19
- messages = [{"role": "system", "content": system_message}]
20
-
21
- messages.extend(history)
22
-
23
- messages.append({"role": "user", "content": message})
24
-
25
- response = ""
26
-
27
- for message in client.chat_completion(
28
- messages,
29
- max_tokens=max_tokens,
30
- stream=True,
31
- temperature=temperature,
32
- top_p=top_p,
33
- ):
34
- choices = message.choices
35
- token = ""
36
- if len(choices) and choices[0].delta.content:
37
- token = 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
- chatbot = gr.ChatInterface(
47
- respond,
48
- type="messages",
49
- additional_inputs=[
50
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
51
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
52
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
53
- gr.Slider(
54
- minimum=0.1,
55
- maximum=1.0,
56
- value=0.95,
57
- step=0.05,
58
- label="Top-p (nucleus sampling)",
59
- ),
60
- ],
61
- )
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  with gr.Blocks() as demo:
64
- with gr.Sidebar():
65
- gr.LoginButton()
66
- chatbot.render()
 
 
67
 
 
68
 
69
- if __name__ == "__main__":
70
- demo.launch()
 
1
  import gradio as gr
2
+ import fitz # PyMuPDF
3
+ import re
4
+ import numpy as np
5
+ import faiss
6
+ import os
7
+ from sentence_transformers import SentenceTransformer
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM
9
+ import torch
10
+ from huggingface_hub import login
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
+ # -----------------------------
13
+ # PDF Text Loader
14
+ # -----------------------------
15
+ def load_pdf_text(file_obj):
16
+ doc = fitz.open(stream=file_obj.read(), filetype="pdf")
17
+ text = ""
18
+ for page in doc:
19
+ text += page.get_text()
20
+ if not text.strip():
21
+ raise ValueError("No text found in PDF.")
22
+ return text
23
+
24
+ # -----------------------------
25
+ # Chunk Text
26
+ # -----------------------------
27
+ def chunk_text(text, max_tokens=200):
28
+ sentences = re.split(r'(?<=[.!?]) +', text)
29
+ chunks, current_chunk = [], []
30
+ current_len = 0
31
+ for sentence in sentences:
32
+ word_count = len(sentence.split())
33
+ if current_len + word_count > max_tokens:
34
+ chunks.append(" ".join(current_chunk))
35
+ current_chunk = [sentence]
36
+ current_len = word_count
37
+ else:
38
+ current_chunk.append(sentence)
39
+ current_len += word_count
40
+ if current_chunk:
41
+ chunks.append(" ".join(current_chunk))
42
+ return chunks
43
+
44
+ # -----------------------------
45
+ # Simple Vector Store
46
+ # -----------------------------
47
+ class SimpleVectorStore:
48
+ def __init__(self, dim):
49
+ self.dim = dim
50
+ self.vectors = []
51
+ self.metadata = []
52
+ self.index = None
53
+
54
+ def add(self, vectors, metas):
55
+ for v, m in zip(vectors, metas):
56
+ vec = np.array(v, dtype=np.float32)
57
+ self.vectors.append(vec)
58
+ self.metadata.append(m)
59
+ if self.vectors:
60
+ self.index = faiss.IndexFlatL2(self.dim)
61
+ self.index.add(np.stack(self.vectors))
62
+
63
+ def search(self, query_vector, k=5):
64
+ query_vector = np.array(query_vector, dtype=np.float32).reshape(1, -1)
65
+ D, I = self.index.search(query_vector, k)
66
+ results = [self.metadata[i] for i in I[0]]
67
+ return results
68
+
69
+ # -----------------------------
70
+ # Index PDF
71
+ # -----------------------------
72
+ def index_pdf(file_obj):
73
+ text = load_pdf_text(file_obj)
74
+ chunks = chunk_text(text)
75
+ embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
76
+ vectors = embed_model.encode(chunks)
77
+ store = SimpleVectorStore(dim=vectors.shape[1])
78
+ store.add(vectors, chunks)
79
+ return embed_model, store
80
+
81
+ # -----------------------------
82
+ # Load LLaMA Model
83
+ # -----------------------------
84
+ def load_llm():
85
+ model_id = "meta-llama/Llama-3.2-3b-instruct"
86
+ hf_token = os.getenv("HF_TOKEN")
87
+ if not hf_token:
88
+ raise ValueError("HF_TOKEN is not set. Please add it in Hugging Face Secrets.")
89
+ login(hf_token)
90
+
91
+ tokenizer = AutoTokenizer.from_pretrained(model_id, token=hf_token)
92
+ llm = AutoModelForCausalLM.from_pretrained(
93
+ model_id,
94
+ device_map="auto",
95
+ torch_dtype=torch.float16,
96
+ token=hf_token
97
+ )
98
+ return tokenizer, llm
99
+
100
+ # -----------------------------
101
+ # HyDE + Answer Query
102
+ # -----------------------------
103
+ def answer_query(file_obj, question):
104
+ try:
105
+ embed_model, store = index_pdf(file_obj)
106
+ tokenizer, llm = load_llm()
107
+
108
+ # ---- Step 1: HyDE hypothetical answer ----
109
+ hyde_prompt = f"""
110
+ [INST] Write a detailed hypothetical answer to this question:
111
+ {question}
112
+ Answer: [/INST]
113
+ """
114
+ inputs = tokenizer(hyde_prompt, return_tensors="pt").to(llm.device)
115
+ hyde_out = llm.generate(**inputs, max_new_tokens=200)
116
+ hypo_answer = tokenizer.decode(hyde_out[0], skip_special_tokens=True)
117
+
118
+ # ---- Step 2: Embed hypothetical answer ----
119
+ query_vec = embed_model.encode([hypo_answer])[0]
120
+
121
+ # ---- Step 3: Retrieve top chunks ----
122
+ relevant_chunks = store.search(query_vec, k=5)
123
+ context = "\n".join(relevant_chunks)
124
+
125
+ # ---- Step 4: Final Answer ----
126
+ final_prompt = f"""
127
+ [INST] You are a helpful tutor. Based only on the context below, answer the question.
128
+ If context does not have the info, say "I could not find this in the text."
129
+ Context:
130
+ {context}
131
+ Question: {question}
132
+ Answer: [/INST]
133
+ """
134
+ inputs = tokenizer(final_prompt, return_tensors="pt", truncation=True).to(llm.device)
135
+ outputs = llm.generate(**inputs, max_new_tokens=300, temperature=0.7, top_p=0.9, do_sample=True)
136
+ answer = tokenizer.decode(outputs[0], skip_special_tokens=True)
137
+
138
+ if "Answer:" in answer:
139
+ answer = answer.split("Answer:")[-1].strip()
140
+
141
+ return answer
142
+
143
+ except Exception as e:
144
+ return f"⚠️ Error: {e}"
145
+
146
+ # -----------------------------
147
+ # Gradio UI
148
+ # -----------------------------
149
  with gr.Blocks() as demo:
150
+ gr.Markdown("## 📚 HyDE RAG Chatbot (PDF Tutor)")
151
+ file_input = gr.File(label="Upload PDF", type="filepath")
152
+ question = gr.Textbox(label="Ask a Question")
153
+ answer = gr.Textbox(label="Answer", interactive=False)
154
+ btn = gr.Button("Get Answer")
155
 
156
+ btn.click(fn=answer_query, inputs=[file_input, question], outputs=answer)
157
 
158
+ demo.launch()