Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,6 +1,7 @@
|
|
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,15 +15,12 @@ import json
|
|
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()
|
@@ -36,9 +34,9 @@ class DocumentRetrievalAndGeneration:
|
|
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
|
40 |
return all_splits
|
41 |
-
|
42 |
def encode_texts(self, texts):
|
43 |
encoded_input = self.embedding_tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors='pt')
|
44 |
with torch.no_grad():
|
@@ -54,29 +52,28 @@ class DocumentRetrievalAndGeneration:
|
|
54 |
|
55 |
def create_faiss_index(self):
|
56 |
all_texts = [split.page_content for split in self.all_splits]
|
57 |
-
|
58 |
-
batch_size =
|
59 |
all_embeddings = []
|
60 |
-
|
61 |
for i in range(0, len(all_texts), batch_size):
|
62 |
batch_texts = all_texts[i:i+batch_size]
|
63 |
batch_embeddings = self.encode_texts(batch_texts)
|
64 |
all_embeddings.append(batch_embeddings)
|
65 |
print(f"Processed batch {i//batch_size + 1}/{(len(all_texts) + batch_size - 1)//batch_size}")
|
66 |
-
|
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("
|
77 |
return gpu_index
|
78 |
else:
|
79 |
-
print("
|
80 |
return index
|
81 |
except Exception as e:
|
82 |
print(f"GPU FAISS failed: {e}, using CPU")
|
@@ -89,17 +86,15 @@ class DocumentRetrievalAndGeneration:
|
|
89 |
bnb_4bit_quant_type="nf4",
|
90 |
bnb_4bit_compute_dtype=torch.bfloat16
|
91 |
)
|
92 |
-
|
93 |
-
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,11 +102,9 @@ class DocumentRetrievalAndGeneration:
|
|
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=
|
115 |
try:
|
116 |
streamer = TextIteratorStreamer(self.tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
|
117 |
generate_kwargs = dict(
|
@@ -122,149 +115,121 @@ class DocumentRetrievalAndGeneration:
|
|
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 |
-
|
130 |
thread = Thread(target=self.model.generate, kwargs=generate_kwargs)
|
131 |
thread.start()
|
132 |
-
|
133 |
generated_text = ""
|
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
|
141 |
return "Text generation process encountered an error"
|
142 |
|
143 |
def query_and_generate_response(self, query):
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
179 |
-
|
180 |
-
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
196 |
|
197 |
def qa_infer_gradio(self, query):
|
198 |
response = self.query_and_generate_response(query)
|
199 |
return response
|
200 |
|
201 |
-
|
202 |
-
|
|
|
|
|
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 |
-
|
235 |
-
|
236 |
-
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
|
241 |
-
|
242 |
-
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
|
247 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
248 |
|
249 |
-
|
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)
|
|
|
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 |
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 |
hf_token = os.getenv('HF_TOKEN')
|
|
|
|
|
24 |
self.embedding_tokenizer = AutoTokenizer.from_pretrained(embedding_model_name, token=hf_token)
|
25 |
self.embedding_model = AutoModel.from_pretrained(embedding_model_name, token=hf_token)
|
26 |
self.gpu_index = self.create_faiss_index()
|
|
|
34 |
print('Length of documents:', len(documents))
|
35 |
print("LEN of all_splits", len(all_splits))
|
36 |
for i in range(min(3, len(all_splits))):
|
37 |
+
print(all_splits[i].page_content)
|
38 |
return all_splits
|
39 |
+
|
40 |
def encode_texts(self, texts):
|
41 |
encoded_input = self.embedding_tokenizer(texts, padding=True, truncation=True, max_length=512, return_tensors='pt')
|
42 |
with torch.no_grad():
|
|
|
52 |
|
53 |
def create_faiss_index(self):
|
54 |
all_texts = [split.page_content for split in self.all_splits]
|
55 |
+
|
56 |
+
batch_size = 256
|
57 |
all_embeddings = []
|
58 |
+
|
59 |
for i in range(0, len(all_texts), batch_size):
|
60 |
batch_texts = all_texts[i:i+batch_size]
|
61 |
batch_embeddings = self.encode_texts(batch_texts)
|
62 |
all_embeddings.append(batch_embeddings)
|
63 |
print(f"Processed batch {i//batch_size + 1}/{(len(all_texts) + batch_size - 1)//batch_size}")
|
64 |
+
|
65 |
embeddings = np.vstack(all_embeddings)
|
66 |
index = faiss.IndexFlatL2(embeddings.shape[1])
|
67 |
index.add(embeddings)
|
68 |
+
|
|
|
69 |
try:
|
70 |
if torch.cuda.is_available():
|
71 |
gpu_resource = faiss.StandardGpuResources()
|
72 |
gpu_index = faiss.index_cpu_to_gpu(gpu_resource, 0, index)
|
73 |
+
print("Using GPU for FAISS")
|
74 |
return gpu_index
|
75 |
else:
|
76 |
+
print("Using CPU for FAISS")
|
77 |
return index
|
78 |
except Exception as e:
|
79 |
print(f"GPU FAISS failed: {e}, using CPU")
|
|
|
86 |
bnb_4bit_quant_type="nf4",
|
87 |
bnb_4bit_compute_dtype=torch.bfloat16
|
88 |
)
|
89 |
+
hf_token = "replace_your_token_here"
|
90 |
+
print(f"Token found: {hf_token is not None}")
|
91 |
+
print(f"LLM Token found: {hf_token is not None}")
|
92 |
+
print(f"Token starts with: {hf_token[:10] if hf_token else 'None'}...")
|
|
|
93 |
tokenizer = AutoTokenizer.from_pretrained(model_id, token=hf_token)
|
94 |
+
|
|
|
95 |
if tokenizer.pad_token is None:
|
96 |
tokenizer.pad_token = tokenizer.eos_token
|
97 |
+
|
98 |
model = AutoModelForCausalLM.from_pretrained(
|
99 |
model_id,
|
100 |
torch_dtype=torch.bfloat16,
|
|
|
102 |
quantization_config=quantization_config,
|
103 |
token=hf_token
|
104 |
)
|
|
|
|
|
105 |
return tokenizer, model
|
106 |
|
107 |
+
def generate_response_with_timeout(self, input_ids, max_new_tokens=1000):
|
108 |
try:
|
109 |
streamer = TextIteratorStreamer(self.tokenizer, timeout=60.0, skip_prompt=True, skip_special_tokens=True)
|
110 |
generate_kwargs = dict(
|
|
|
115 |
top_k=20,
|
116 |
temperature=0.8,
|
117 |
repetition_penalty=1.2,
|
118 |
+
pad_token_id=self.tokenizer.eos_token_id,
|
119 |
+
eos_token_id=self.tokenizer.eos_token_id,
|
120 |
streamer=streamer,
|
121 |
)
|
122 |
+
|
123 |
thread = Thread(target=self.model.generate, kwargs=generate_kwargs)
|
124 |
thread.start()
|
125 |
+
|
126 |
generated_text = ""
|
127 |
for new_text in streamer:
|
128 |
generated_text += new_text
|
129 |
+
|
130 |
+
thread.join()
|
131 |
return generated_text
|
132 |
except Exception as e:
|
133 |
+
print(f"Error in generate_response_with_timeout: {str(e)}")
|
134 |
return "Text generation process encountered an error"
|
135 |
|
136 |
def query_and_generate_response(self, query):
|
137 |
+
similarityThreshold = 1
|
138 |
+
query_embedding = self.encode_texts([query])[0]
|
139 |
+
distances, indices = self.gpu_index.search(np.array([query_embedding]), k=3)
|
140 |
+
print("Distance", distances, "indices", indices)
|
141 |
+
content = ""
|
142 |
+
filtered_results = []
|
143 |
+
for idx, distance in zip(indices[0], distances[0]):
|
144 |
+
if distance <= similarityThreshold:
|
145 |
+
filtered_results.append(idx)
|
146 |
+
for i in filtered_results:
|
147 |
+
print(self.all_splits[i].page_content)
|
148 |
+
content += "-" * 50 + "\n"
|
149 |
+
content += self.all_splits[idx].page_content + "\n"
|
150 |
+
print("CHUNK", idx)
|
151 |
+
print("Distance:", distance)
|
152 |
+
print("indices:", indices)
|
153 |
+
print(self.all_splits[idx].page_content)
|
154 |
+
print("############################")
|
155 |
+
|
156 |
+
conversation = [
|
157 |
+
{"role": "system", "content": "You are a knowledgeable assistant with access to a comprehensive database."},
|
158 |
+
{"role": "user", "content": f"""
|
159 |
+
I need you to answer my question and provide related information in a specific format.
|
160 |
+
I have provided five relatable json files {content}, choose the most suitable chunks for answering the query.
|
161 |
+
RETURN ONLY SOLUTION without additional comments, sign-offs, retrived chunks, refrence to any Ticket or extra phrases. Be direct and to the point.
|
162 |
+
IF THERE IS NO ANSWER RELATABLE IN RETRIEVED CHUNKS, RETURN "NO SOLUTION AVAILABLE".
|
163 |
+
DO NOT GIVE REFRENCE TO ANY CHUNKS OR TICKETS,BE ON POINT.
|
164 |
+
|
165 |
+
Here's my question:
|
166 |
+
Query: {query}
|
167 |
+
Solution==>
|
168 |
+
"""}
|
169 |
+
]
|
170 |
+
|
171 |
+
input_ids = self.tokenizer.apply_chat_template(conversation, return_tensors="pt").to(self.model.device)
|
172 |
+
|
173 |
+
start_time = datetime.now()
|
174 |
+
generated_response = self.generate_response_with_timeout(input_ids)
|
175 |
+
elapsed_time = datetime.now() - start_time
|
176 |
+
|
177 |
+
print("Generated response:", generated_response)
|
178 |
+
print("Time elapsed:", elapsed_time)
|
179 |
+
print("Device in use:", self.model.device)
|
180 |
+
|
181 |
+
solution_text = generated_response.strip()
|
182 |
+
if "Solution:" in solution_text:
|
183 |
+
solution_text = solution_text.split("Solution:", 1)[1].strip()
|
184 |
+
|
185 |
+
solution_text = re.sub(r'^assistant\s*', '', solution_text, flags=re.IGNORECASE)
|
186 |
+
solution_text = solution_text.strip()
|
187 |
+
|
188 |
+
return solution_text, content
|
189 |
|
190 |
def qa_infer_gradio(self, query):
|
191 |
response = self.query_and_generate_response(query)
|
192 |
return response
|
193 |
|
194 |
+
if __name__ == "__main__":
|
195 |
+
embedding_model_name = 'sentence-transformers/all-MiniLM-L6-v2'
|
196 |
+
lm_model_id = "meta-llama/Meta-Llama-3.1-8B-Instruct"
|
197 |
+
data_folder = 'sample_embedding_folder2'
|
198 |
|
|
|
|
|
|
|
|
|
|
|
199 |
doc_retrieval_gen = DocumentRetrievalAndGeneration(embedding_model_name, lm_model_id, data_folder)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
200 |
|
201 |
+
def launch_interface():
|
202 |
+
css_code = """
|
203 |
+
.gradio-container {
|
204 |
+
background-color: #daccdb;
|
205 |
+
}
|
206 |
+
button {
|
207 |
+
background-color: #927fc7;
|
208 |
+
color: black;
|
209 |
+
border: 1px solid black;
|
210 |
+
padding: 10px;
|
211 |
+
margin-right: 10px;
|
212 |
+
font-size: 16px;
|
213 |
+
font-weight: bold;
|
214 |
+
}
|
215 |
+
"""
|
216 |
+
EXAMPLES = [
|
217 |
+
"On which devices can the VIP and CSI2 modules operate simultaneously?",
|
218 |
+
"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?",
|
219 |
+
"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?"
|
220 |
+
]
|
221 |
+
|
222 |
+
interface = gr.Interface(
|
223 |
+
fn=doc_retrieval_gen.qa_infer_gradio,
|
224 |
+
inputs=[gr.Textbox(label="QUERY", placeholder="Enter your query here")],
|
225 |
+
allow_flagging='never',
|
226 |
+
examples=EXAMPLES,
|
227 |
+
cache_examples=False,
|
228 |
+
outputs=[gr.Textbox(label="RESPONSE"), gr.Textbox(label="RELATED QUERIES")],
|
229 |
+
css=css_code,
|
230 |
+
title="TI E2E FORUM"
|
231 |
+
)
|
232 |
+
|
233 |
+
interface.launch(debug=True)
|
234 |
|
235 |
+
launch_interface()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|