wylum commited on
Commit
34473de
·
verified ·
1 Parent(s): 2156d4e

Delete app-workflow.py

Browse files
Files changed (1) hide show
  1. app-workflow.py +0 -384
app-workflow.py DELETED
@@ -1,384 +0,0 @@
1
- import gradio as gr
2
- import os
3
-
4
- from langchain_community.document_loaders import PyPDFLoader
5
- from langchain.text_splitter import RecursiveCharacterTextSplitter
6
- from langchain_community.vectorstores import Chroma
7
- from langchain.chains import ConversationalRetrievalChain
8
- from langchain_community.embeddings import HuggingFaceEmbeddings
9
- from langchain_community.llms import HuggingFacePipeline
10
- from langchain.chains import ConversationChain
11
- from langchain.memory import ConversationBufferMemory
12
- from langchain_community.llms import HuggingFaceEndpoint
13
-
14
- from pathlib import Path
15
- import chromadb
16
- from unidecode import unidecode
17
-
18
- from transformers import AutoTokenizer
19
- import transformers
20
- import torch
21
- import tqdm
22
- import accelerate
23
- import re
24
-
25
-
26
-
27
- # default_persist_directory = './chroma_HF/'
28
- list_llm = ["mistralai/Mistral-7B-Instruct-v0.2", "mistralai/Mixtral-8x7B-Instruct-v0.1", "mistralai/Mistral-7B-Instruct-v0.1", \
29
- "google/gemma-7b-it","google/gemma-2b-it", \
30
- "HuggingFaceH4/zephyr-7b-beta", "HuggingFaceH4/zephyr-7b-gemma-v0.1", \
31
- "meta-llama/Llama-2-7b-chat-hf", "microsoft/phi-2", \
32
- "TinyLlama/TinyLlama-1.1B-Chat-v1.0", "mosaicml/mpt-7b-instruct", "tiiuae/falcon-7b-instruct", \
33
- "google/flan-t5-xxl"
34
- ]
35
- list_llm_simple = [os.path.basename(llm) for llm in list_llm]
36
-
37
- #huggingface_token = os.getenv("huffingface_read_token")
38
-
39
- # Load PDF document and create doc splits
40
- def load_doc(list_file_path, chunk_size, chunk_overlap):
41
- # Processing for one document only
42
- # loader = PyPDFLoader(file_path)
43
- # pages = loader.load()
44
- loaders = [PyPDFLoader(x) for x in list_file_path]
45
- pages = []
46
- for loader in loaders:
47
- pages.extend(loader.load())
48
- # text_splitter = RecursiveCharacterTextSplitter(chunk_size = 600, chunk_overlap = 50)
49
- text_splitter = RecursiveCharacterTextSplitter(
50
- chunk_size = chunk_size,
51
- chunk_overlap = chunk_overlap)
52
- doc_splits = text_splitter.split_documents(pages)
53
- return doc_splits
54
-
55
-
56
- # Create vector database
57
- def create_db(splits, collection_name):
58
- embedding = HuggingFaceEmbeddings()
59
- new_client = chromadb.EphemeralClient()
60
- vectordb = Chroma.from_documents(
61
- documents=splits,
62
- embedding=embedding,
63
- client=new_client,
64
- collection_name=collection_name,
65
- # persist_directory=default_persist_directory
66
- )
67
- return vectordb
68
-
69
-
70
- # Load vector database
71
- def load_db():
72
- embedding = HuggingFaceEmbeddings()
73
- vectordb = Chroma(
74
- # persist_directory=default_persist_directory,
75
- embedding_function=embedding)
76
- return vectordb
77
-
78
-
79
- # Initialize langchain LLM chain
80
- def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
81
- progress(0.1, desc="Initializing HF tokenizer...")
82
- # HuggingFacePipeline uses local model
83
- # Note: it will download model locally...
84
- # tokenizer=AutoTokenizer.from_pretrained(llm_model)
85
- # progress(0.5, desc="Initializing HF pipeline...")
86
- # pipeline=transformers.pipeline(
87
- # "text-generation",
88
- # model=llm_model,
89
- # tokenizer=tokenizer,
90
- # torch_dtype=torch.bfloat16,
91
- # trust_remote_code=True,
92
- # device_map="auto",
93
- # # max_length=1024,
94
- # max_new_tokens=max_tokens,
95
- # do_sample=True,
96
- # top_k=top_k,
97
- # num_return_sequences=1,
98
- # eos_token_id=tokenizer.eos_token_id
99
- # )
100
- # llm = HuggingFacePipeline(pipeline=pipeline, model_kwargs={'temperature': temperature})
101
-
102
- # HuggingFaceHub uses HF inference endpoints
103
- progress(0.5, desc="Initializing HF Hub...")
104
- # Use of trust_remote_code as model_kwargs
105
- # Warning: langchain issue
106
- # URL: https://github.com/langchain-ai/langchain/issues/6080
107
- if llm_model == "mistralai/Mixtral-8x7B-Instruct-v0.1":
108
- llm = HuggingFaceEndpoint(
109
- repo_id=llm_model,
110
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "load_in_8bit": True}
111
- temperature = temperature,
112
- max_new_tokens = max_tokens,
113
- top_k = top_k,
114
- load_in_8bit = True,
115
- )
116
- elif llm_model in ["HuggingFaceH4/zephyr-7b-gemma-v0.1","mosaicml/mpt-7b-instruct"]:
117
- raise gr.Error("LLM model is too large to be loaded automatically on free inference endpoint")
118
- llm = HuggingFaceEndpoint(
119
- repo_id=llm_model,
120
- temperature = temperature,
121
- max_new_tokens = max_tokens,
122
- top_k = top_k,
123
- )
124
- elif llm_model == "microsoft/phi-2":
125
- # raise gr.Error("phi-2 model requires 'trust_remote_code=True', currently not supported by langchain HuggingFaceHub...")
126
- llm = HuggingFaceEndpoint(
127
- repo_id=llm_model,
128
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
129
- temperature = temperature,
130
- max_new_tokens = max_tokens,
131
- top_k = top_k,
132
- trust_remote_code = True,
133
- torch_dtype = "auto",
134
- )
135
- elif llm_model == "TinyLlama/TinyLlama-1.1B-Chat-v1.0":
136
- llm = HuggingFaceEndpoint(
137
- repo_id=llm_model,
138
- #repo_id="meta-llama/Llama-3.1-8B",
139
- #huggingfacehub_api_token = huggingface_token,
140
- task="text-generation", # Explicitly specify task
141
- # model_kwargs={"temperature": temperature, "max_new_tokens": 250, "top_k": top_k}
142
- temperature = temperature,
143
- max_new_tokens = 250,
144
- top_k = top_k,
145
- )
146
- elif llm_model == "meta-llama/Llama-2-7b-chat-hf":
147
- #raise gr.Error("Llama-2-7b-chat-hf model requires a Pro subscription...")
148
- llm = HuggingFaceEndpoint(
149
- repo_id=llm_model,
150
- task="text-generation", # Explicitly specify task
151
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
152
- temperature = temperature,
153
- max_new_tokens = max_tokens,
154
- top_k = top_k,
155
- )
156
- else:
157
- llm = HuggingFaceEndpoint(
158
- repo_id=llm_model,
159
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k, "trust_remote_code": True, "torch_dtype": "auto"}
160
- # model_kwargs={"temperature": temperature, "max_new_tokens": max_tokens, "top_k": top_k}
161
- temperature = temperature,
162
- max_new_tokens = max_tokens,
163
- top_k = top_k,
164
- )
165
-
166
- progress(0.75, desc="Defining buffer memory...")
167
- memory = ConversationBufferMemory(
168
- memory_key="chat_history",
169
- output_key='answer',
170
- return_messages=True
171
- )
172
- # retriever=vector_db.as_retriever(search_type="similarity", search_kwargs={'k': 3})
173
- retriever=vector_db.as_retriever()
174
- progress(0.8, desc="Defining retrieval chain...")
175
- qa_chain = ConversationalRetrievalChain.from_llm(
176
- llm,
177
- retriever=retriever,
178
- chain_type="stuff",
179
- memory=memory,
180
- # combine_docs_chain_kwargs={"prompt": your_prompt})
181
- return_source_documents=True,
182
- #return_generated_question=False,
183
- verbose=False,
184
- )
185
- progress(0.9, desc="Done!")
186
- return qa_chain
187
-
188
-
189
- # Generate collection name for vector database
190
- # - Use filepath as input, ensuring unicode text
191
- def create_collection_name(filepath):
192
- # Extract filename without extension
193
- collection_name = Path(filepath).stem
194
- # Fix potential issues from naming convention
195
- ## Remove space
196
- collection_name = collection_name.replace(" ","-")
197
- ## ASCII transliterations of Unicode text
198
- collection_name = unidecode(collection_name)
199
- ## Remove special characters
200
- #collection_name = re.findall("[\dA-Za-z]*", collection_name)[0]
201
- collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
202
- ## Limit length to 50 characters
203
- collection_name = collection_name[:50]
204
- ## Minimum length of 3 characters
205
- if len(collection_name) < 3:
206
- collection_name = collection_name + 'xyz'
207
- ## Enforce start and end as alphanumeric character
208
- if not collection_name[0].isalnum():
209
- collection_name = 'A' + collection_name[1:]
210
- if not collection_name[-1].isalnum():
211
- collection_name = collection_name[:-1] + 'Z'
212
- print('Filepath: ', filepath)
213
- print('Collection name: ', collection_name)
214
- return collection_name
215
-
216
-
217
- # Initialize database
218
- def initialize_database(list_file_obj, chunk_size, chunk_overlap, progress=gr.Progress()):
219
- # Create list of documents (when valid)
220
- list_file_path = [x.name for x in list_file_obj if x is not None]
221
- # Create collection_name for vector database
222
- progress(0.1, desc="Creating collection name...")
223
- collection_name = create_collection_name(list_file_path[0])
224
- progress(0.25, desc="Loading document...")
225
- # Load document and create splits
226
- doc_splits = load_doc(list_file_path, chunk_size, chunk_overlap)
227
- # Create or load vector database
228
- progress(0.5, desc="Generating vector database...")
229
- # global vector_db
230
- vector_db = create_db(doc_splits, collection_name)
231
- progress(0.9, desc="Done!")
232
- return vector_db, collection_name, "Complete!"
233
-
234
-
235
- def initialize_LLM(llm_option, llm_temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
236
- # print("llm_option",llm_option)
237
- llm_name = list_llm[llm_option]
238
- print("llm_name: ",llm_name)
239
- qa_chain = initialize_llmchain(llm_name, llm_temperature, max_tokens, top_k, vector_db, progress)
240
- return qa_chain, "Complete!"
241
-
242
-
243
- def format_chat_history(message, chat_history):
244
- formatted_chat_history = []
245
- for user_message, bot_message in chat_history:
246
- formatted_chat_history.append(f"User: {user_message}")
247
- formatted_chat_history.append(f"Assistant: {bot_message}")
248
- return formatted_chat_history
249
-
250
-
251
- def conversation(qa_chain, message, history):
252
- formatted_chat_history = format_chat_history(message, history)
253
- #print("formatted_chat_history",formatted_chat_history)
254
-
255
- # Generate response using QA chain
256
- response = qa_chain({"question": message, "chat_history": formatted_chat_history})
257
- response_answer = response["answer"]
258
- if response_answer.find("Helpful Answer:") != -1:
259
- response_answer = response_answer.split("Helpful Answer:")[-1]
260
- response_sources = response["source_documents"]
261
- response_source1 = response_sources[0].page_content.strip()
262
- response_source2 = response_sources[1].page_content.strip()
263
- response_source3 = response_sources[2].page_content.strip()
264
- # Langchain sources are zero-based
265
- response_source1_page = response_sources[0].metadata["page"] + 1
266
- response_source2_page = response_sources[1].metadata["page"] + 1
267
- response_source3_page = response_sources[2].metadata["page"] + 1
268
- # print ('chat response: ', response_answer)
269
- # print('DB source', response_sources)
270
-
271
- # Append user message and response to chat history
272
- new_history = history + [(message, response_answer)]
273
- # return gr.update(value=""), new_history, response_sources[0], response_sources[1]
274
- return qa_chain, gr.update(value=""), new_history, response_source1, response_source1_page, response_source2, response_source2_page, response_source3, response_source3_page
275
-
276
-
277
- def upload_file(file_obj):
278
- list_file_path = []
279
- for idx, file in enumerate(file_obj):
280
- file_path = file_obj.name
281
- list_file_path.append(file_path)
282
- # print(file_path)
283
- # initialize_database(file_path, progress)
284
- return list_file_path
285
-
286
-
287
- def demo():
288
- with gr.Blocks(theme="base") as demo:
289
- vector_db = gr.State()
290
- qa_chain = gr.State()
291
- collection_name = gr.State()
292
-
293
- gr.Markdown(
294
- """<center><h2>PDF-based chatbot</center></h2>
295
- <h3>Ask any questions about your PDF documents</h3>""")
296
- gr.Markdown(
297
- """<b>Note:</b> This AI assistant, using Langchain and open-source LLMs, performs retrieval-augmented generation (RAG) from your PDF documents. \
298
- The user interface explicitely shows multiple steps to help understand the RAG workflow.
299
- This chatbot takes past questions into account when generating answers (via conversational memory), and includes document references for clarity purposes.<br>
300
- <br><b>Warning:</b> This space uses the free CPU Basic hardware from Hugging Face. Some steps and LLM models used below (free inference endpoints) can take some time to generate a reply.
301
- """)
302
-
303
- with gr.Tab("Step 1 - Upload PDF"):
304
- with gr.Row():
305
- document = gr.Files(height=100, file_count="multiple", file_types=[".pdf"], interactive=True, label="Upload your PDF documents (single or multiple)")
306
- # upload_btn = gr.UploadButton("Loading document...", height=100, file_count="multiple", file_types=["pdf"], scale=1)
307
-
308
- with gr.Tab("Step 2 - Process document"):
309
- with gr.Row():
310
- db_btn = gr.Radio(["ChromaDB"], label="Vector database type", value = "ChromaDB", type="index", info="Choose your vector database")
311
- with gr.Accordion("Advanced options - Document text splitter", open=False):
312
- with gr.Row():
313
- slider_chunk_size = gr.Slider(minimum = 100, maximum = 1000, value=600, step=20, label="Chunk size", info="Chunk size", interactive=True)
314
- with gr.Row():
315
- slider_chunk_overlap = gr.Slider(minimum = 10, maximum = 200, value=40, step=10, label="Chunk overlap", info="Chunk overlap", interactive=True)
316
- with gr.Row():
317
- db_progress = gr.Textbox(label="Vector database initialization", value="None")
318
- with gr.Row():
319
- db_btn = gr.Button("Generate vector database")
320
-
321
- with gr.Tab("Step 3 - Initialize QA chain"):
322
- with gr.Row():
323
- llm_btn = gr.Radio(list_llm_simple, \
324
- label="LLM models", value = list_llm_simple[0], type="index", info="Choose your LLM model")
325
- with gr.Accordion("Advanced options - LLM model", open=False):
326
- with gr.Row():
327
- slider_temperature = gr.Slider(minimum = 0.01, maximum = 1.0, value=0.7, step=0.1, label="Temperature", info="Model temperature", interactive=True)
328
- with gr.Row():
329
- slider_maxtokens = gr.Slider(minimum = 224, maximum = 4096, value=1024, step=32, label="Max Tokens", info="Model max tokens", interactive=True)
330
- with gr.Row():
331
- slider_topk = gr.Slider(minimum = 1, maximum = 10, value=3, step=1, label="top-k samples", info="Model top-k samples", interactive=True)
332
- with gr.Row():
333
- llm_progress = gr.Textbox(value="None",label="QA chain initialization")
334
- with gr.Row():
335
- qachain_btn = gr.Button("Initialize Question Answering chain")
336
-
337
- with gr.Tab("Step 4 - Chatbot"):
338
- chatbot = gr.Chatbot(height=300)
339
- with gr.Accordion("Advanced - Document references", open=False):
340
- with gr.Row():
341
- doc_source1 = gr.Textbox(label="Reference 1", lines=2, container=True, scale=20)
342
- source1_page = gr.Number(label="Page", scale=1)
343
- with gr.Row():
344
- doc_source2 = gr.Textbox(label="Reference 2", lines=2, container=True, scale=20)
345
- source2_page = gr.Number(label="Page", scale=1)
346
- with gr.Row():
347
- doc_source3 = gr.Textbox(label="Reference 3", lines=2, container=True, scale=20)
348
- source3_page = gr.Number(label="Page", scale=1)
349
- with gr.Row():
350
- msg = gr.Textbox(placeholder="Type message (e.g. 'What is this document about?')", container=True)
351
- with gr.Row():
352
- submit_btn = gr.Button("Submit message")
353
- clear_btn = gr.ClearButton([msg, chatbot], value="Clear conversation")
354
-
355
- # Preprocessing events
356
- #upload_btn.upload(upload_file, inputs=[upload_btn], outputs=[document])
357
- db_btn.click(initialize_database, \
358
- inputs=[document, slider_chunk_size, slider_chunk_overlap], \
359
- outputs=[vector_db, collection_name, db_progress])
360
- qachain_btn.click(initialize_LLM, \
361
- inputs=[llm_btn, slider_temperature, slider_maxtokens, slider_topk, vector_db], \
362
- outputs=[qa_chain, llm_progress]).then(lambda:[None,"",0,"",0,"",0], \
363
- inputs=None, \
364
- outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
365
- queue=False)
366
-
367
- # Chatbot events
368
- msg.submit(conversation, \
369
- inputs=[qa_chain, msg, chatbot], \
370
- outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
371
- queue=False)
372
- submit_btn.click(conversation, \
373
- inputs=[qa_chain, msg, chatbot], \
374
- outputs=[qa_chain, msg, chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
375
- queue=False)
376
- clear_btn.click(lambda:[None,"",0,"",0,"",0], \
377
- inputs=None, \
378
- outputs=[chatbot, doc_source1, source1_page, doc_source2, source2_page, doc_source3, source3_page], \
379
- queue=False)
380
- demo.queue().launch(debug=True)
381
-
382
-
383
- if __name__ == "__main__":
384
- demo()