arjunanand13 commited on
Commit
c1a3363
1 Parent(s): 328bdbb

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +167 -0
app.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain.document_loaders import TextLoader, DirectoryLoader
3
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
4
+ from langchain.vectorstores import FAISS
5
+ from sentence_transformers import SentenceTransformer
6
+ import faiss
7
+ import torch
8
+ import numpy as np
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline, BitsAndBytesConfig
10
+ from datetime import datetime
11
+ import json
12
+ import gradio as gr
13
+
14
+ class DocumentRetrievalAndGeneration:
15
+ def __init__(self, embedding_model_name, lm_model_id, data_folder):
16
+ self.all_splits = self.load_documents(data_folder)
17
+ self.embeddings = SentenceTransformer(embedding_model_name)
18
+ self.gpu_index = self.create_faiss_index()
19
+ self.llm = self.initialize_llm(lm_model_id)
20
+
21
+ def load_documents(self, folder_path):
22
+ loader = DirectoryLoader(folder_path, loader_cls=TextLoader)
23
+ documents = loader.load()
24
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size=5000, chunk_overlap=250)
25
+ all_splits = text_splitter.split_documents(documents)
26
+ print('Length of documents:', len(documents))
27
+ print("LEN of all_splits", len(all_splits))
28
+ for i in range(5):
29
+ print(all_splits[i].page_content)
30
+ return all_splits
31
+
32
+ def create_faiss_index(self):
33
+ all_texts = [split.page_content for split in self.all_splits]
34
+ embeddings = self.embeddings.encode(all_texts, convert_to_tensor=True).cpu().numpy()
35
+ index = faiss.IndexFlatL2(embeddings.shape[1])
36
+ index.add(embeddings)
37
+ gpu_resource = faiss.StandardGpuResources()
38
+ gpu_index = faiss.index_cpu_to_gpu(gpu_resource, 0, index)
39
+ return gpu_index
40
+
41
+ def initialize_llm(self, model_id):
42
+ bnb_config = BitsAndBytesConfig(
43
+ load_in_4bit=True,
44
+ bnb_4bit_use_double_quant=True,
45
+ bnb_4bit_quant_type="nf4",
46
+ bnb_4bit_compute_dtype=torch.bfloat16
47
+ )
48
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
49
+ model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=bnb_config)
50
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
51
+ generate_text = pipeline(
52
+ model=model,
53
+ tokenizer=tokenizer,
54
+ return_full_text=True,
55
+ task='text-generation',
56
+ temperature=0.6,
57
+ max_new_tokens=256,
58
+ )
59
+ return generate_text
60
+
61
+ def query_and_generate_response(self, query):
62
+ query_embedding = self.embeddings.encode(query, convert_to_tensor=True).cpu().numpy()
63
+ distances, indices = self.gpu_index.search(np.array([query_embedding]), k=5)
64
+
65
+ content = ""
66
+ for idx in indices[0]:
67
+ content += "-" * 50 + "\n"
68
+ content += self.all_splits[idx].page_content + "\n"
69
+ print("CHUNK", idx)
70
+ print(self.all_splits[idx].page_content)
71
+ print("############################")
72
+ prompt = f"""
73
+ You are a knowledgeable assistant with access to a comprehensive database.
74
+ I need you to answer my question and provide related information in a specific format.
75
+ I have provided five relatable json files {content}, choose the most suitable chunks for answering the query
76
+ Here's what I need:
77
+ Include a final answer without additional comments, sign-offs, or extra phrases. Be direct and to the point.
78
+ content
79
+ Here's my question:
80
+ Query:{query}
81
+ Solution==>
82
+ Example1
83
+ Query: "How to use IPU1_0 instead of A15_0 to process NDK in TDA2x-EVM",
84
+ 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'.",
85
+
86
+ Example2
87
+ Query: "Can BQ25896 support I2C interface?",
88
+ Solution: "Yes, the BQ25896 charger supports the I2C interface for communication.",
89
+ """
90
+ # prompt = f"Query: {query}\nSolution: {content}\n"
91
+
92
+ # Encode and prepare inputs
93
+ messages = [{"role": "user", "content": prompt}]
94
+ encodeds = self.llm.tokenizer.apply_chat_template(messages, return_tensors="pt")
95
+ model_inputs = encodeds.to(self.llm.device)
96
+
97
+ # Perform inference and measure time
98
+ start_time = datetime.now()
99
+ generated_ids = self.llm.model.generate(model_inputs, max_new_tokens=1000, do_sample=True)
100
+ elapsed_time = datetime.now() - start_time
101
+
102
+ # Decode and return output
103
+ decoded = self.llm.tokenizer.batch_decode(generated_ids)
104
+ generated_response = decoded[0]
105
+ print("Generated response:", generated_response)
106
+ print("Time elapsed:", elapsed_time)
107
+ print("Device in use:", self.llm.device)
108
+
109
+ return generated_response, content
110
+
111
+ def qa_infer_gradio(self, query):
112
+ response = self.query_and_generate_response(query)
113
+ return response
114
+
115
+ if __name__ == "__main__":
116
+ # Example usage
117
+ embedding_model_name = 'flax-sentence-embeddings/all_datasets_v3_MiniLM-L12'
118
+ lm_model_id = "mistralai/Mistral-7B-Instruct-v0.2"
119
+ data_folder = 'sample_embedding_folder2'
120
+
121
+ doc_retrieval_gen = DocumentRetrievalAndGeneration(embedding_model_name, lm_model_id, data_folder)
122
+
123
+ # Define Gradio interface function
124
+ def launch_interface():
125
+ css_code = """
126
+ .gradio-container {
127
+ background-color: #daccdb;
128
+ }
129
+ /* Button styling for all buttons */
130
+ button {
131
+ background-color: #927fc7; /* Default color for all other buttons */
132
+ color: black;
133
+ border: 1px solid black;
134
+ padding: 10px;
135
+ margin-right: 10px;
136
+ font-size: 16px; /* Increase font size */
137
+ font-weight: bold; /* Make text bold */
138
+ }
139
+ """
140
+ EXAMPLES = ["Can the VIP and CSI2 modules operate simultaneously? ",
141
+ "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?",
142
+ "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?"]
143
+
144
+ file_path = "ticketNames.txt"
145
+
146
+ # Read the file content
147
+ with open(file_path, "r") as file:
148
+ content = file.read()
149
+ ticket_names = json.loads(content)
150
+ dropdown = gr.Dropdown(label="Sample queries", choices=ticket_names)
151
+
152
+ # Define Gradio interface
153
+ interface = gr.Interface(
154
+ fn=doc_retrieval_gen.qa_infer_gradio,
155
+ inputs=[gr.Textbox(label="QUERY", placeholder="Enter your query here")],
156
+ allow_flagging='never',
157
+ examples=EXAMPLES,
158
+ cache_examples=False,
159
+ outputs=[gr.Textbox(label="SOLUTION"), gr.Textbox(label="RELATED QUERIES")],
160
+ css=css_code
161
+ )
162
+
163
+ # Launch Gradio interface
164
+ interface.launch(debug=True)
165
+
166
+ # Launch the interface
167
+ launch_interface()