Darshan-BugendaiTech commited on
Commit
c17787a
1 Parent(s): a228c28

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +65 -269
app.py CHANGED
@@ -1,276 +1,72 @@
1
- from transformers import pipeline
2
- from langchain.llms import HuggingFacePipeline
3
- import torch
4
- import bitsandbytes as bnb
5
- from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig, pipeline, BitsAndBytesConfig
6
-
7
-
8
- from langchain.vectorstores import Chroma
9
- from langchain.text_splitter import RecursiveCharacterTextSplitter
10
- from langchain.chains import RetrievalQA
11
- from langchain.document_loaders import TextLoader
12
- from langchain.document_loaders import UnstructuredExcelLoader
13
- from langchain.embeddings import HuggingFaceInstructEmbeddings
14
- from langchain.memory import ConversationBufferWindowMemory
15
- from langchain.prompts import ChatPromptTemplate
16
- from langchain.memory import ConversationBufferWindowMemory
17
  import gradio as gr
18
- from controller import Controller
19
-
20
- # Loading Model
21
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
22
- bnb_config = BitsAndBytesConfig(
23
- load_in_4bit=True, # Load model weights in 4-bit format
24
- bnb_4bit_compute_type=torch.float16 # To avoid slow inference as input type into Linear4bit is torch.float16
 
 
 
 
 
 
 
 
25
  )
26
 
27
- MODEL_NAME = "HuggingFaceH4/zephyr-7b-beta"
 
28
 
29
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
30
- model = AutoModelForCausalLM.from_pretrained(
31
- MODEL_NAME, device_map="auto", torch_dtype=torch.float16, quantization_config=bnb_config
 
 
 
 
32
  )
 
33
 
34
- generation_config = GenerationConfig.from_pretrained(MODEL_NAME)
35
- generation_config.max_new_tokens = 2000
36
- generation_config.temperature = 0.7
37
- generation_config.do_sample = True
38
-
39
- pipe = pipeline(
40
- "text-generation",
41
- model=model,
42
- tokenizer=tokenizer,
43
- return_full_text=True,
44
- generation_config=generation_config,
45
- num_return_sequences=1,
46
- eos_token_id=tokenizer.eos_token_id,
47
- pad_token_id=tokenizer.eos_token_id,
48
- )
49
- zephyr_llm = HuggingFacePipeline(pipeline=pipe)
50
-
51
- """--------------------------------------------Starting UI part--------------------------------------------"""
52
- # Configurations
53
- persist_directory = "db"
54
- chunk_size = 150
55
- chunk_overlap = 0
56
-
57
- class Retriever:
58
- def __init__(self):
59
- self.text_retriever = None
60
- self.vectordb = None
61
- self.embeddings = None
62
- self.memory = ConversationBufferWindowMemory(k=2, return_messages=True)
63
-
64
- def create_and_add_embeddings(self, file):
65
- os.makedirs("db", exist_ok=True) # Recheck this and understand reason of above
66
-
67
- self.embeddings = HuggingFaceInstructEmbeddings(model_name="BAAI/bge-base-en-v1.5",
68
- model_kwargs={"device": "cuda"})
69
-
70
- loader = UnstructuredExcelLoader(file)
71
- documents = loader.load()
72
- text_splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap)
73
- texts = text_splitter.split_documents(documents)
74
-
75
- self.vectordb = Chroma.from_documents(documents=texts,
76
- embedding=self.embeddings,
77
- persist_directory=persist_directory)
78
-
79
- self.text_retriever = self.vectordb.as_retriever(search_kwargs={"k": 3})
80
-
81
-
82
- def retrieve_text(self, query):
83
- prompt_zephyr = ChatPromptTemplate.from_messages([
84
- ("system", "You are an helpful and harmless AI Assistant who is excited to be able to help the user, but will refuse to do anything that could be considered harmful to the user."),
85
- ("human", "Context: {context}\n <|user|>\n {question}\n<|assistant|>\n"),
86
- ])
87
-
88
- qa = RetrievalQA.from_chain_type(
89
- llm=zephyr_llm,
90
- chain_type="stuff",
91
- retriever=self.text_retriever,
92
- return_source_documents=False,
93
- verbose=False,
94
- chain_type_kwargs={"prompt": prompt_zephyr},
95
- memory=self.memory,
96
- )
97
-
98
- response = qa.run(query)
99
- return response
100
-
101
- class Controller:
102
- def __init__(self):
103
- self.retriever = None
104
- self.query = ""
105
-
106
- def embed_document(self, file):
107
- if file is not None:
108
- self.retriever = Retriever()
109
- self.retriever.create_and_add_embeddings(file.name)
110
-
111
- def retrieve(self, query):
112
- texts = self.retriever.retrieve_text(query)
113
- return texts
114
-
115
-
116
- # Gradio Demo for trying out the Application
117
- import os
118
- from controller import Controller
119
- import gradio as gr
120
-
121
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
122
- colors = ["#64A087", "green", "black"]
123
-
124
- CSS = """
125
- #question input {
126
- font-size: 16px;
127
- }
128
- #app-title {
129
- width: 100%;
130
- margin: auto;
131
- }
132
- #url-textbox {
133
- padding: 0 !important;
134
- }
135
- #short-upload-box .w-full {
136
- min-height: 10rem !important;
137
- }
138
-
139
- #select-a-file {
140
- display: block;
141
- width: 100%;
142
- }
143
- #file-clear {
144
- padding-top: 2px !important;
145
- padding-bottom: 2px !important;
146
- padding-left: 8px !important;
147
- padding-right: 8px !important;
148
- margin-top: 10px;
149
- }
150
- .gradio-container .gr-button-primary {
151
- background: linear-gradient(180deg, #CDF9BE 0%, #AFF497 100%);
152
- border: 1px solid #B0DCCC;
153
- border-radius: 8px;
154
- color: #1B8700;
155
- }
156
- .gradio-container.dark button#submit-button {
157
- background: linear-gradient(180deg, #CDF9BE 0%, #AFF497 100%);
158
- border: 1px solid #B0DCCC;
159
- border-radius: 8px;
160
- color: #1B8700
161
- }
162
- table.gr-samples-table tr td {
163
- border: none;
164
- outline: none;
165
- }
166
- table.gr-samples-table tr td:first-of-type {
167
- width: 0%;
168
- }
169
- div#short-upload-box div.absolute {
170
- display: none !important;
171
- }
172
- gradio-app > div > div > div > div.w-full > div, .gradio-app > div > div > div > div.w-full > div {
173
- gap: 0px 2%;
174
- }
175
- gradio-app div div div div.w-full, .gradio-app div div div div.w-full {
176
- gap: 0px;
177
- }
178
- gradio-app h2, .gradio-app h2 {
179
- padding-top: 10px;
180
- }
181
- #answer {
182
- overflow-y: scroll;
183
- color: white;
184
- background: #666;
185
- border-color: #666;
186
- font-size: 20px;
187
- font-weight: bold;
188
- }
189
- #answer span {
190
- color: white;
191
- }
192
- #answer textarea {
193
- color:white;
194
- background: #777;
195
- border-color: #777;
196
- font-size: 18px;
197
- }
198
- #url-error input {
199
- color: red;
200
- }
201
- """
202
-
203
- controller = Controller()
204
-
205
-
206
- def process_pdf(file):
207
  if file is not None:
208
- controller.embed_document(file)
209
- return (
210
- gr.update(visible=True),
211
- gr.update(visible=True),
212
- gr.update(visible=True),
213
- gr.update(visible=True),
214
- )
215
-
216
-
217
- def respond(message, history):
218
- botmessage = controller.retrieve(message)
219
- history.append((message, botmessage))
220
- return "", history
221
-
222
-
223
- def clear_everything():
224
- return (None, None, None)
225
-
226
-
227
- with gr.Blocks(css=CSS, title="") as demo:
228
- gr.Markdown("# Marketing Email Generator ", elem_id="app-title")
229
- gr.Markdown("## Upload a CSV and ask your query!", elem_id="select-a-file")
230
- gr.Markdown(
231
- "Drop your file here 👇",
232
- elem_id="select-a-file",
233
- )
234
- with gr.Row():
235
- with gr.Column(scale=3):
236
- upload = gr.File(label="Upload PDF", type="file")
237
- with gr.Row():
238
- clear_button = gr.Button("Clear", variant="secondary")
239
-
240
- with gr.Column(scale=6):
241
- chatbot = gr.Chatbot()
242
- with gr.Row().style(equal_height=True):
243
- with gr.Column(scale=8):
244
- question = gr.Textbox(
245
- show_label=False,
246
- placeholder="e.g. What is the document about?",
247
- lines=1,
248
- max_lines=1,
249
- ).style(container=False)
250
- with gr.Column(scale=1, min_width=60):
251
- submit_button = gr.Button(
252
- "Send your Request 🤖", variant="primary", elem_id="submit-button"
253
- )
254
-
255
- upload.change(
256
- fn=process_pdf,
257
- inputs=[upload],
258
- outputs=[
259
- question,
260
- clear_button,
261
- submit_button,
262
- chatbot,
263
- ],
264
- api_name="upload",
265
- )
266
- question.submit(respond, [question, chatbot], [question, chatbot])
267
- submit_button.click(respond, [question, chatbot], [question, chatbot])
268
- clear_button.click(
269
- fn=clear_everything,
270
- inputs=[],
271
- outputs=[upload, question, chatbot],
272
- api_name="clear",
273
- )
274
-
275
- if __name__ == "__main__":
276
- demo.launch(enable_queue=False, debug=True, share=False)
 
1
+ # Importing Necessary Libraries
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import gradio as gr
3
+ from llama_index import download_loader, ServiceContext, VectorStoreIndex
4
+ from llama_index.embeddings import HuggingFaceEmbedding
5
+ from llama_index import Prompt
6
+
7
+ # Loading the Zephyr Model using Llama CPP
8
+ from llama_index.llms import LlamaCPP
9
+ llm = LlamaCPP(
10
+ model_url='https://huggingface.co/TheBloke/zephyr-7B-beta-GGUF/resolve/main/zephyr-7b-beta.Q5_K_M.gguf?download=true',
11
+ model_path=None,
12
+ temperature=0.3,
13
+ max_new_tokens=2000,
14
+ context_window=3900,
15
+ # set to at least 1 to use GPU
16
+ model_kwargs={"n_gpu_layers": 0},
17
+ verbose=True
18
  )
19
 
20
+ # Loading Embedding Model
21
+ embed_model = HuggingFaceEmbedding(model_name="BAAI/bge-base-en-v1.5")
22
 
23
+ # Defining custom Prompt
24
+ TEMPLATE_STR = (
25
+ '''You are an helpful and responsible AI assistant who is excited to help user but will never harm humans or engage in the activity that causes harm to anyone. Given with the context below help user with the query.
26
+ {context}
27
+ <|user|>\n
28
+ {query_str}\n
29
+ <|assistant|>\n'''
30
  )
31
+ QA_TEMPLATE = Prompt(TEMPLATE_STR)
32
 
33
+ # User Interface functions
34
+ def build_the_bot(file):
35
+ global service_context, index
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
  if file is not None:
37
+ # Loading Data
38
+ PandasExcelReader = download_loader("PandasExcelReader")
39
+ loader = PandasExcelReader(pandas_config={"header": 0})
40
+ documents = loader.load_data(file=file)
41
+
42
+ service_context = ServiceContext.from_defaults(
43
+ chunk_size=150,chunk_overlap=10,
44
+ llm=llm,embed_model=embed_model,
45
+ )
46
+
47
+ index = VectorStoreIndex.from_documents(documents, service_context=service_context,text_qa_template=QA_TEMPLATE)
48
+
49
+ return('Index saved successfull!!!')
50
+
51
+ def chat(chat_history, user_input):
52
+ global service_context, index
53
+ query_engine = index.as_query_engine(streaming=False)
54
+ bot_response = query_engine.query(user_input)
55
+ bot_response = str(bot_response)
56
+ return chat_history + [(user_input, bot_response)]
57
+
58
+ # User Interface
59
+ with gr.Blocks() as demo:
60
+ gr.Markdown('# Marketing Email Generator')
61
+ with gr.Tab("Input Text Document"):
62
+ upload = gr.File(label="Upload Your Excel")
63
+ upload.upload(fn=build_the_bot,inputs=[upload],show_progress='full')
64
+
65
+ with gr.Tab("Knowledge Bot"):
66
+ chatbot = gr.Chatbot()
67
+ message = gr.Textbox ()
68
+ submit_button = gr.Button("Submit")
69
+ submit_button.click(chat, [chatbot, message], chatbot)
70
+ message.submit(chat, [chatbot, message], chatbot)
71
+
72
+ demo.queue().launch(debug = True,share=True)