Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,7 +1,6 @@
|
|
1 |
import os
|
2 |
import multiprocessing
|
3 |
import concurrent.futures
|
4 |
-
# from langchain.document_loaders import TextLoader, DirectoryLoader
|
5 |
from langchain_community.document_loaders import TextLoader, DirectoryLoader
|
6 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
7 |
from transformers import AutoModel, AutoTokenizer
|
@@ -15,13 +14,17 @@ import json
|
|
15 |
import gradio as gr
|
16 |
import re
|
17 |
from threading import Thread
|
18 |
-
import os
|
19 |
|
20 |
class DocumentRetrievalAndGeneration:
|
21 |
def __init__(self, embedding_model_name, lm_model_id, data_folder):
|
22 |
self.all_splits = self.load_documents(data_folder)
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
25 |
self.gpu_index = self.create_faiss_index()
|
26 |
self.tokenizer, self.model = self.initialize_llm(lm_model_id)
|
27 |
|
@@ -32,8 +35,8 @@ class DocumentRetrievalAndGeneration:
|
|
32 |
all_splits = text_splitter.split_documents(documents)
|
33 |
print('Length of documents:', len(documents))
|
34 |
print("LEN of all_splits", len(all_splits))
|
35 |
-
for i in range(3):
|
36 |
-
print(all_splits[i].page_content)
|
37 |
return all_splits
|
38 |
|
39 |
def encode_texts(self, texts):
|
@@ -52,7 +55,7 @@ class DocumentRetrievalAndGeneration:
|
|
52 |
def create_faiss_index(self):
|
53 |
all_texts = [split.page_content for split in self.all_splits]
|
54 |
|
55 |
-
batch_size =
|
56 |
all_embeddings = []
|
57 |
|
58 |
for i in range(0, len(all_texts), batch_size):
|
@@ -64,9 +67,20 @@ class DocumentRetrievalAndGeneration:
|
|
64 |
embeddings = np.vstack(all_embeddings)
|
65 |
index = faiss.IndexFlatL2(embeddings.shape[1])
|
66 |
index.add(embeddings)
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
def initialize_llm(self, model_id):
|
72 |
quantization_config = BitsAndBytesConfig(
|
@@ -75,11 +89,17 @@ class DocumentRetrievalAndGeneration:
|
|
75 |
bnb_4bit_quant_type="nf4",
|
76 |
bnb_4bit_compute_dtype=torch.bfloat16
|
77 |
)
|
|
|
78 |
hf_token = os.getenv('HF_TOKEN')
|
79 |
-
print(f"Token found: {hf_token is not None}")
|
80 |
print(f"LLM Token found: {hf_token is not None}")
|
81 |
print(f"Token starts with: {hf_token[:10] if hf_token else 'None'}...")
|
|
|
82 |
tokenizer = AutoTokenizer.from_pretrained(model_id, token=hf_token)
|
|
|
|
|
|
|
|
|
|
|
83 |
model = AutoModelForCausalLM.from_pretrained(
|
84 |
model_id,
|
85 |
torch_dtype=torch.bfloat16,
|
@@ -87,9 +107,11 @@ class DocumentRetrievalAndGeneration:
|
|
87 |
quantization_config=quantization_config,
|
88 |
token=hf_token
|
89 |
)
|
|
|
|
|
90 |
return tokenizer, model
|
91 |
|
92 |
-
def generate_response_with_timeout(self, input_ids, max_new_tokens=
|
93 |
try:
|
94 |
streamer = TextIteratorStreamer(self.tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
|
95 |
generate_kwargs = dict(
|
@@ -100,7 +122,8 @@ class DocumentRetrievalAndGeneration:
|
|
100 |
top_k=20,
|
101 |
temperature=0.8,
|
102 |
repetition_penalty=1.2,
|
103 |
-
eos_token_id
|
|
|
104 |
streamer=streamer,
|
105 |
)
|
106 |
|
@@ -111,109 +134,137 @@ class DocumentRetrievalAndGeneration:
|
|
111 |
for new_text in streamer:
|
112 |
generated_text += new_text
|
113 |
|
|
|
114 |
return generated_text
|
115 |
except Exception as e:
|
116 |
-
print(f"Error in
|
117 |
return "Text generation process encountered an error"
|
118 |
|
119 |
def query_and_generate_response(self, query):
|
120 |
-
|
121 |
-
|
122 |
-
distances, indices = self.gpu_index.search(np.array([query_embedding]), k=3)
|
123 |
-
print("Distance", distances, "indices", indices)
|
124 |
-
content = ""
|
125 |
-
filtered_results = []
|
126 |
-
for idx, distance in zip(indices[0], distances[0]):
|
127 |
-
if distance <= similarityThreshold:
|
128 |
-
filtered_results.append(idx)
|
129 |
-
for i in filtered_results:
|
130 |
-
print(self.all_splits[i].page_content)
|
131 |
-
content += "-" * 50 + "\n"
|
132 |
-
content += self.all_splits[idx].page_content + "\n"
|
133 |
-
print("CHUNK", idx)
|
134 |
-
print("Distance:", distance)
|
135 |
-
print("indices:", indices)
|
136 |
-
print(self.all_splits[idx].page_content)
|
137 |
-
print("############################")
|
138 |
-
|
139 |
-
conversation = [
|
140 |
-
{"role": "system", "content": "You are a knowledgeable assistant with access to a comprehensive database."},
|
141 |
-
{"role": "user", "content": f"""
|
142 |
-
I need you to answer my question and provide related information in a specific format.
|
143 |
-
I have provided five relatable json files {content}, choose the most suitable chunks for answering the query.
|
144 |
-
RETURN ONLY SOLUTION without additional comments, sign-offs, retrived chunks, refrence to any Ticket or extra phrases. Be direct and to the point.
|
145 |
-
IF THERE IS NO ANSWER RELATABLE IN RETRIEVED CHUNKS, RETURN "NO SOLUTION AVAILABLE".
|
146 |
-
DO NOT GIVE REFRENCE TO ANY CHUNKS OR TICKETS,BE ON POINT.
|
147 |
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
|
160 |
-
|
161 |
-
|
162 |
-
print("Device in use:", self.model.device)
|
163 |
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
|
172 |
-
|
|
|
|
|
|
|
|
|
173 |
|
174 |
def qa_infer_gradio(self, query):
|
175 |
response = self.query_and_generate_response(query)
|
176 |
return response
|
177 |
|
178 |
-
|
179 |
-
|
180 |
-
lm_model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
181 |
-
data_folder = 'sample_embedding_folder2'
|
182 |
|
183 |
-
|
|
|
|
|
184 |
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
|
201 |
-
|
202 |
-
|
203 |
-
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
210 |
-
examples=EXAMPLES,
|
211 |
-
cache_examples=False,
|
212 |
-
outputs=[gr.Textbox(label="RESPONSE"), gr.Textbox(label="RELATED QUERIES")],
|
213 |
-
css=css_code,
|
214 |
-
title="TI E2E FORUM"
|
215 |
-
)
|
216 |
|
217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
218 |
|
219 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import multiprocessing
|
3 |
import concurrent.futures
|
|
|
4 |
from langchain_community.document_loaders import TextLoader, DirectoryLoader
|
5 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
6 |
from transformers import AutoModel, AutoTokenizer
|
|
|
14 |
import gradio as gr
|
15 |
import re
|
16 |
from threading import Thread
|
|
|
17 |
|
18 |
class DocumentRetrievalAndGeneration:
|
19 |
def __init__(self, embedding_model_name, lm_model_id, data_folder):
|
20 |
self.all_splits = self.load_documents(data_folder)
|
21 |
+
|
22 |
+
# Get token from HF Spaces environment
|
23 |
+
hf_token = os.getenv('HF_TOKEN')
|
24 |
+
print(f"Token found: {hf_token is not None}")
|
25 |
+
|
26 |
+
self.embedding_tokenizer = AutoTokenizer.from_pretrained(embedding_model_name, token=hf_token)
|
27 |
+
self.embedding_model = AutoModel.from_pretrained(embedding_model_name, token=hf_token)
|
28 |
self.gpu_index = self.create_faiss_index()
|
29 |
self.tokenizer, self.model = self.initialize_llm(lm_model_id)
|
30 |
|
|
|
35 |
all_splits = text_splitter.split_documents(documents)
|
36 |
print('Length of documents:', len(documents))
|
37 |
print("LEN of all_splits", len(all_splits))
|
38 |
+
for i in range(min(3, len(all_splits))):
|
39 |
+
print(all_splits[i].page_content[:200] + "...")
|
40 |
return all_splits
|
41 |
|
42 |
def encode_texts(self, texts):
|
|
|
55 |
def create_faiss_index(self):
|
56 |
all_texts = [split.page_content for split in self.all_splits]
|
57 |
|
58 |
+
batch_size = 512 # Reduced for Spaces
|
59 |
all_embeddings = []
|
60 |
|
61 |
for i in range(0, len(all_texts), batch_size):
|
|
|
67 |
embeddings = np.vstack(all_embeddings)
|
68 |
index = faiss.IndexFlatL2(embeddings.shape[1])
|
69 |
index.add(embeddings)
|
70 |
+
|
71 |
+
# Try GPU first, fallback to CPU if fails
|
72 |
+
try:
|
73 |
+
if torch.cuda.is_available():
|
74 |
+
gpu_resource = faiss.StandardGpuResources()
|
75 |
+
gpu_index = faiss.index_cpu_to_gpu(gpu_resource, 0, index)
|
76 |
+
print("🚀 Using GPU for FAISS")
|
77 |
+
return gpu_index
|
78 |
+
else:
|
79 |
+
print("💻 Using CPU for FAISS")
|
80 |
+
return index
|
81 |
+
except Exception as e:
|
82 |
+
print(f"GPU FAISS failed: {e}, using CPU")
|
83 |
+
return index
|
84 |
|
85 |
def initialize_llm(self, model_id):
|
86 |
quantization_config = BitsAndBytesConfig(
|
|
|
89 |
bnb_4bit_quant_type="nf4",
|
90 |
bnb_4bit_compute_dtype=torch.bfloat16
|
91 |
)
|
92 |
+
|
93 |
hf_token = os.getenv('HF_TOKEN')
|
|
|
94 |
print(f"LLM Token found: {hf_token is not None}")
|
95 |
print(f"Token starts with: {hf_token[:10] if hf_token else 'None'}...")
|
96 |
+
|
97 |
tokenizer = AutoTokenizer.from_pretrained(model_id, token=hf_token)
|
98 |
+
|
99 |
+
# Handle pad_token for latest transformers
|
100 |
+
if tokenizer.pad_token is None:
|
101 |
+
tokenizer.pad_token = tokenizer.eos_token
|
102 |
+
|
103 |
model = AutoModelForCausalLM.from_pretrained(
|
104 |
model_id,
|
105 |
torch_dtype=torch.bfloat16,
|
|
|
107 |
quantization_config=quantization_config,
|
108 |
token=hf_token
|
109 |
)
|
110 |
+
|
111 |
+
print(f"🦙 Model loaded on: {model.device}")
|
112 |
return tokenizer, model
|
113 |
|
114 |
+
def generate_response_with_timeout(self, input_ids, max_new_tokens=800):
|
115 |
try:
|
116 |
streamer = TextIteratorStreamer(self.tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
|
117 |
generate_kwargs = dict(
|
|
|
122 |
top_k=20,
|
123 |
temperature=0.8,
|
124 |
repetition_penalty=1.2,
|
125 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
126 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
127 |
streamer=streamer,
|
128 |
)
|
129 |
|
|
|
134 |
for new_text in streamer:
|
135 |
generated_text += new_text
|
136 |
|
137 |
+
thread.join()
|
138 |
return generated_text
|
139 |
except Exception as e:
|
140 |
+
print(f"Error in generation: {str(e)}")
|
141 |
return "Text generation process encountered an error"
|
142 |
|
143 |
def query_and_generate_response(self, query):
|
144 |
+
if not query.strip():
|
145 |
+
return "Please enter a valid query", ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
|
147 |
+
try:
|
148 |
+
similarityThreshold = 1.0
|
149 |
+
query_embedding = self.encode_texts([query])[0]
|
150 |
+
distances, indices = self.gpu_index.search(np.array([query_embedding]), k=3)
|
151 |
+
print("Distance", distances, "indices", indices)
|
152 |
+
|
153 |
+
content = ""
|
154 |
+
for idx, distance in zip(indices[0], distances[0]):
|
155 |
+
content += "-" * 50 + "\n"
|
156 |
+
content += self.all_splits[idx].page_content + "\n"
|
157 |
+
print(f"📄 Chunk {idx} (distance: {distance:.3f})")
|
158 |
+
|
159 |
+
conversation = [
|
160 |
+
{"role": "system", "content": "You are a knowledgeable assistant with access to a comprehensive database."},
|
161 |
+
{"role": "user", "content": f"""
|
162 |
+
I need you to answer my question and provide related information in a specific format.
|
163 |
+
I have provided five relatable json files {content}, choose the most suitable chunks for answering the query.
|
164 |
+
RETURN ONLY SOLUTION without additional comments, sign-offs, retrived chunks, refrence to any Ticket or extra phrases. Be direct and to the point.
|
165 |
+
IF THERE IS NO ANSWER RELATABLE IN RETRIEVED CHUNKS, RETURN "NO SOLUTION AVAILABLE".
|
166 |
+
DO NOT GIVE REFRENCE TO ANY CHUNKS OR TICKETS,BE ON POINT.
|
167 |
+
|
168 |
+
Here's my question:
|
169 |
+
Query: {query}
|
170 |
+
Solution==>
|
171 |
+
"""}
|
172 |
+
]
|
173 |
+
|
174 |
+
input_ids = self.tokenizer.apply_chat_template(conversation, return_tensors="pt").to(self.model.device)
|
175 |
+
|
176 |
+
start_time = datetime.now()
|
177 |
+
generated_response = self.generate_response_with_timeout(input_ids)
|
178 |
+
elapsed_time = datetime.now() - start_time
|
179 |
|
180 |
+
print("Generated response:", generated_response)
|
181 |
+
print("Time elapsed:", elapsed_time)
|
|
|
182 |
|
183 |
+
solution_text = generated_response.strip()
|
184 |
+
if "Solution:" in solution_text:
|
185 |
+
solution_text = solution_text.split("Solution:", 1)[1].strip()
|
186 |
|
187 |
+
# Post-processing to remove "assistant" prefix
|
188 |
+
solution_text = re.sub(r'^assistant\s*', '', solution_text, flags=re.IGNORECASE)
|
189 |
+
solution_text = solution_text.strip()
|
190 |
|
191 |
+
return solution_text, content[:1000] + "..." if len(content) > 1000 else content
|
192 |
+
|
193 |
+
except Exception as e:
|
194 |
+
print(f"Error in query processing: {e}")
|
195 |
+
return f"Error processing query: {str(e)}", ""
|
196 |
|
197 |
def qa_infer_gradio(self, query):
|
198 |
response = self.query_and_generate_response(query)
|
199 |
return response
|
200 |
|
201 |
+
# Initialize the system
|
202 |
+
print("Initializing TI E2E Forum Assistant...")
|
|
|
|
|
203 |
|
204 |
+
embedding_model_name = 'sentence-transformers/all-MiniLM-L6-v2' # More compatible model
|
205 |
+
lm_model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
206 |
+
data_folder = 'sample_embedding_folder2' # Make sure this folder exists
|
207 |
|
208 |
+
try:
|
209 |
+
doc_retrieval_gen = DocumentRetrievalAndGeneration(embedding_model_name, lm_model_id, data_folder)
|
210 |
+
print("System initialized successfully!")
|
211 |
+
|
212 |
+
# Your exact same CSS and examples
|
213 |
+
css_code = """
|
214 |
+
.gradio-container {
|
215 |
+
background-color: #daccdb;
|
216 |
+
}
|
217 |
+
button {
|
218 |
+
background-color: #927fc7;
|
219 |
+
color: black;
|
220 |
+
border: 1px solid black;
|
221 |
+
padding: 10px;
|
222 |
+
margin-right: 10px;
|
223 |
+
font-size: 16px;
|
224 |
+
font-weight: bold;
|
225 |
+
}
|
226 |
+
"""
|
227 |
+
|
228 |
+
EXAMPLES = [
|
229 |
+
"On which devices can the VIP and CSI2 modules operate simultaneously?",
|
230 |
+
"I'm using Code Composer Studio 5.4.0.00091 and enabled FPv4SPD16 floating point support for CortexM4 in TDA2. However, after building the project, the .asm file shows --float_support=vfplib instead of FPv4SPD16. Why is this happening?",
|
231 |
+
"Could you clarify the maximum number of cameras that can be connected simultaneously to the video input ports on the TDA2x SoC, considering it supports up to 10 multiplexed input ports and includes 3 dedicated video input modules?"
|
232 |
+
]
|
|
|
|
|
|
|
|
|
|
|
|
|
233 |
|
234 |
+
interface = gr.Interface(
|
235 |
+
fn=doc_retrieval_gen.qa_infer_gradio,
|
236 |
+
inputs=[gr.Textbox(label="QUERY", placeholder="Enter your query here", lines=3)],
|
237 |
+
allow_flagging='never',
|
238 |
+
examples=EXAMPLES,
|
239 |
+
cache_examples=False,
|
240 |
+
outputs=[
|
241 |
+
gr.Textbox(label="RESPONSE", lines=8),
|
242 |
+
gr.Textbox(label="RELATED QUERIES", lines=5)
|
243 |
+
],
|
244 |
+
css=css_code,
|
245 |
+
title="🤖 TI E2E FORUM",
|
246 |
+
description="Ask technical questions and get answers based on the TI E2E knowledge base"
|
247 |
+
)
|
248 |
|
249 |
+
# Launch with public link for Spaces
|
250 |
+
interface.launch(
|
251 |
+
server_name="0.0.0.0",
|
252 |
+
server_port=7860,
|
253 |
+
share=False
|
254 |
+
)
|
255 |
+
|
256 |
+
except Exception as e:
|
257 |
+
print(f"Failed to initialize: {e}")
|
258 |
+
|
259 |
+
# Fallback simple interface
|
260 |
+
def fallback_response(query):
|
261 |
+
return "System initialization failed. Please check the logs.", ""
|
262 |
+
|
263 |
+
fallback_interface = gr.Interface(
|
264 |
+
fn=fallback_response,
|
265 |
+
inputs=[gr.Textbox(label="QUERY")],
|
266 |
+
outputs=[gr.Textbox(label="ERROR"), gr.Textbox(label="INFO")],
|
267 |
+
title="TI E2E FORUM - Initialization Error"
|
268 |
+
)
|
269 |
+
|
270 |
+
fallback_interface.launch(server_name="0.0.0.0", server_port=7860)
|