aizanlabs commited on
Commit
bf1ced6
·
verified ·
1 Parent(s): 1c05250

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +271 -0
app.py ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "Single Thread"
2
+
3
+ import os
4
+ import multiprocessing
5
+ import concurrent.futures
6
+ from langchain.document_loaders import TextLoader, DirectoryLoader
7
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
8
+ from langchain.vectorstores import FAISS
9
+ from sentence_transformers import SentenceTransformer
10
+ import faiss
11
+ import torch
12
+ import numpy as np
13
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, BitsAndBytesConfig
14
+ from datetime import datetime
15
+ import json
16
+ import gradio as gr
17
+ import re
18
+
19
+ class DocumentRetrievalAndGeneration:
20
+ def __init__(self, embedding_model_name, lm_model_id, data_folder):
21
+ self.all_splits = self.load_documents(data_folder)
22
+ self.embeddings = SentenceTransformer(embedding_model_name)
23
+ self.gpu_index = self.create_faiss_index()
24
+ self.llm = self.initialize_llm(lm_model_id)
25
+
26
+ def load_documents(self, folder_path):
27
+ loader = DirectoryLoader(folder_path, loader_cls=TextLoader)
28
+ documents = loader.load()
29
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=250)
30
+ all_splits = text_splitter.split_documents(documents)
31
+ print('Length of documents:', len(documents))
32
+ print("LEN of all_splits", len(all_splits))
33
+ for i in range(5):
34
+ print(all_splits[i].page_content)
35
+ return all_splits
36
+
37
+ def create_faiss_index(self):
38
+ all_texts = [split.page_content for split in self.all_splits]
39
+ embeddings = self.embeddings.encode(all_texts, convert_to_tensor=True).cpu().numpy()
40
+ index = faiss.IndexFlatL2(embeddings.shape[1])
41
+ index.add(embeddings)
42
+ gpu_resource = faiss.StandardGpuResources()
43
+ gpu_index = faiss.index_cpu_to_gpu(gpu_resource, 0, index)
44
+ return gpu_index
45
+
46
+ def initialize_llm(self, model_id):
47
+ bnb_config = BitsAndBytesConfig(
48
+ load_in_4bit=True,
49
+ bnb_4bit_use_double_quant=True,
50
+ bnb_4bit_quant_type="nf4",
51
+ bnb_4bit_compute_dtype=torch.bfloat16
52
+ )
53
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
54
+ model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config)
55
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
56
+ generate_text = pipeline(
57
+ model=model,
58
+ tokenizer=tokenizer,
59
+ return_full_text=True,
60
+ task='text-generation',
61
+ temperature=0.6,
62
+ max_new_tokens=256,
63
+ )
64
+ return generate_text
65
+
66
+ def generate_response_with_timeout(self, model_inputs):
67
+ try:
68
+ with concurrent.futures.ThreadPoolExecutor() as executor:
69
+ future = executor.submit(self.llm.model.generate, model_inputs, max_new_tokens=1000, do_sample=True)
70
+ generated_ids = future.result(timeout=60) # Timeout set to 60 seconds
71
+ return generated_ids
72
+ except concurrent.futures.TimeoutError:
73
+ return "Text generation process timed out"
74
+ raise TimeoutError("Text generation process timed out")
75
+
76
+ def query_and_generate_response(self, query):
77
+ query_embedding = self.embeddings.encode(query, convert_to_tensor=True).cpu().numpy()
78
+ distances, indices = self.gpu_index.search(np.array([query_embedding]), k=5)
79
+
80
+ content = ""
81
+ for idx in indices[0]:
82
+ content += "-" * 50 + "\n"
83
+ content += self.all_splits[idx].page_content + "\n"
84
+ distance=distances[0][i]
85
+ print("CHUNK", idx)
86
+ print("Distance :",distance)
87
+ print(self.all_splits[idx].page_content)
88
+ print("############################")
89
+ prompt = f"""<s>
90
+ You are a knowledgeable assistant with access to a comprehensive database.
91
+ I need you to answer my question and provide related information in a specific format.
92
+ I have provided five relatable json files {content}, choose the most suitable chunks for answering the query
93
+ Here's what I need:
94
+ Include a final answer without additional comments, sign-offs, or extra phrases. Be direct and to the point.
95
+ content
96
+ Here's my question:
97
+ Query:{query}
98
+ Solution==>
99
+ RETURN ONLY SOLUTION . IF THEIR IS NO ANSWER RELATABLE IN RETRIEVED CHUNKS , RETURN " NO SOLUTION AVAILABLE"
100
+ IF THE QUERY AND THE RETRIEVED CHUNKS DO NOT CORRELATE MEANINGFULLY, OR IF THE QUERY IS NOT RELEVANT TO TDA2 OR RELATED TOPICS, THEN "NO SOLUTION AVAILABLE."
101
+ Example1
102
+ Query: "How to use IPU1_0 instead of A15_0 to process NDK in TDA2x-EVM",
103
+ Solution: "To use IPU1_0 instead of A15_0 to process NDK in TDA2x-EVM, you need to modify the configuration file of the NDK application. Specifically, change the processor reference from 'A15_0' to 'IPU1_0'.",
104
+
105
+ Example2
106
+ Query: "Can BQ25896 support I2C interface?",
107
+ Solution: "Yes, the BQ25896 charger supports the I2C interface for communication."
108
+ Example3
109
+ Query: "Who is the fastest runner in the world",
110
+ Solution:"NO SOLUTION AVAILABLE"
111
+ Example4
112
+ Query:"What is the price of latest apple MACBOOK "
113
+ Solution:"NO SOLUTION AVAILABLE"
114
+ </s>
115
+ """
116
+ # prompt = f"Query: {query}\nSolution: {content}\n"
117
+
118
+ # Encode and prepare inputs
119
+ messages = [{"role": "user", "content": prompt}]
120
+ encodeds = self.llm.tokenizer.apply_chat_template(messages, return_tensors="pt")
121
+ model_inputs = encodeds.to(self.llm.device)
122
+
123
+ # Perform inference and measure time
124
+ start_time = datetime.now()
125
+ generated_ids = self.generate_response_with_timeout(model_inputs)
126
+ # generated_ids = self.llm.model.generate(model_inputs, max_new_tokens=1000, do_sample=True)
127
+ elapsed_time = datetime.now() - start_time
128
+
129
+ # Decode and return output
130
+ decoded = self.llm.tokenizer.batch_decode(generated_ids)
131
+ generated_response = decoded[0]
132
+ match1 = re.search(r'\[/INST\](.*?)</s>', generated_response, re.DOTALL)
133
+
134
+ match2 = re.search(r'Solution:(.*?)</s>', generated_response, re.DOTALL | re.IGNORECASE)
135
+ if match1:
136
+ solution_text = match1.group(1).strip()
137
+ print(solution_text)
138
+ if "Solution:" in solution_text:
139
+ solution_text = solution_text.split("Solution:", 1)[1].strip()
140
+ elif match2:
141
+ solution_text = match2.group(1).strip()
142
+ print(solution_text)
143
+
144
+ else:
145
+ solution_text=generated_response
146
+ print("Generated response:", generated_response)
147
+ print("Time elapsed:", elapsed_time)
148
+ print("Device in use:", self.llm.device)
149
+
150
+ return solution_text, content
151
+
152
+ def qa_infer_gradio(self, query):
153
+ response = self.query_and_generate_response(query)
154
+ return response
155
+
156
+ if __name__ == "__main__":
157
+ # Example usage
158
+ embedding_model_name = 'flax-sentence-embeddings/all_datasets_v3_MiniLM-L12'
159
+ lm_model_id = "mistralai/Mistral-7B-Instruct-v0.2"
160
+ data_folder = 'sample_embedding_folder2'
161
+
162
+ doc_retrieval_gen = DocumentRetrievalAndGeneration(embedding_model_name, lm_model_id, data_folder)
163
+
164
+ """Dual Interface"""
165
+
166
+ def launch_interface():
167
+ css_code = """
168
+ .gradio-container {
169
+ background-color: #daccdb;
170
+ }
171
+ /* Button styling for all buttons */
172
+ button {
173
+ background-color: #927fc7; /* Default color for all other buttons */
174
+ color: black;
175
+ border: 1px solid black;
176
+ padding: 10px;
177
+ margin-right: 10px;
178
+ font-size: 16px; /* Increase font size */
179
+ font-weight: bold; /* Make text bold */
180
+ }
181
+ """
182
+ EXAMPLES = [
183
+ "On which devices can the VIP and CSI2 modules operate simultaneously?",
184
+ "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?",
185
+ "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?"
186
+ ]
187
+
188
+ file_path = "ticketNames.txt"
189
+
190
+ # Read the file content
191
+ with open(file_path, "r") as file:
192
+ content = file.read()
193
+ ticket_names = json.loads(content)
194
+ dropdown = gr.Dropdown(label="Sample queries", choices=ticket_names)
195
+
196
+ # Define Gradio interfaces
197
+ tab1 = gr.Interface(
198
+ fn=doc_retrieval_gen.qa_infer_gradio,
199
+ inputs=[gr.Textbox(label="QUERY", placeholder="Enter your query here")],
200
+ allow_flagging='never',
201
+ examples=EXAMPLES,
202
+ cache_examples=False,
203
+ outputs=[gr.Textbox(label="SOLUTION"), gr.Textbox(label="RELATED QUERIES")],
204
+ css=css_code
205
+ )
206
+ tab2 = gr.Interface(
207
+ fn=doc_retrieval_gen.qa_infer_gradio,
208
+ inputs=[dropdown],
209
+ allow_flagging='never',
210
+ outputs=[gr.Textbox(label="SOLUTION"), gr.Textbox(label="RELATED QUERIES")],
211
+ css=css_code
212
+ )
213
+
214
+ # Combine interfaces into a tabbed interface
215
+ gr.TabbedInterface(
216
+ [tab1, tab2],
217
+ ["Textbox Input", "FAQs"],
218
+ title="TI E2E FORUM",
219
+ css=css_code
220
+ ).launch(debug=True)
221
+
222
+ # Launch the interface
223
+ launch_interface()
224
+
225
+
226
+
227
+ """Single Interface"""
228
+ # def launch_interface():
229
+ # css_code = """
230
+ # .gradio-container {
231
+ # background-color: #daccdb;
232
+ # }
233
+ # /* Button styling for all buttons */
234
+ # button {
235
+ # background-color: #927fc7; /* Default color for all other buttons */
236
+ # color: black;
237
+ # border: 1px solid black;
238
+ # padding: 10px;
239
+ # margin-right: 10px;
240
+ # font-size: 16px; /* Increase font size */
241
+ # font-weight: bold; /* Make text bold */
242
+ # }
243
+ # """
244
+ # EXAMPLES = ["On which devices can the VIP and CSI2 modules operate simultaneously? ",
245
+ # "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?",
246
+ # "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?"]
247
+
248
+ # file_path = "ticketNames.txt"
249
+
250
+ # # Read the file content
251
+ # with open(file_path, "r") as file:
252
+ # content = file.read()
253
+ # ticket_names = json.loads(content)
254
+ # dropdown = gr.Dropdown(label="Sample queries", choices=ticket_names)
255
+
256
+ # # Define Gradio interface
257
+ # interface = gr.Interface(
258
+ # fn=doc_retrieval_gen.qa_infer_gradio,
259
+ # inputs=[gr.Textbox(label="QUERY", placeholder="Enter your query here")],
260
+ # allow_flagging='never',
261
+ # examples=EXAMPLES,
262
+ # cache_examples=False,
263
+ # outputs=[gr.Textbox(label="SOLUTION"), gr.Textbox(label="RELATED QUERIES")],
264
+ # css=css_code
265
+ # )
266
+
267
+ # # Launch Gradio interface
268
+ # interface.launch(debug=True)
269
+
270
+ # # Launch the interface
271
+ # launch_interface()