batlahiya commited on
Commit
8e4885e
·
verified ·
1 Parent(s): 5f3768e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +172 -62
app.py CHANGED
@@ -1,63 +1,173 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
- """
43
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
44
- """
45
- demo = gr.ChatInterface(
46
- respond,
47
- additional_inputs=[
48
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
49
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
50
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
51
- gr.Slider(
52
- minimum=0.1,
53
- maximum=1.0,
54
- value=0.95,
55
- step=0.05,
56
- label="Top-p (nucleus sampling)",
57
- ),
58
- ],
59
- )
60
-
61
-
62
- if __name__ == "__main__":
63
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
  import gradio as gr
3
+ import os
4
+ import re
5
+ from pathlib import Path
6
+ from unidecode import unidecode
7
+
8
+ from langchain_community.document_loaders import PyPDFLoader
9
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
10
+ from langchain_community.vectorstores import Chroma
11
+ from langchain.chains import ConversationalRetrievalChain
12
+ from langchain.memory import ConversationBufferMemory
13
+
14
+ from langchain_huggingface import HuggingFaceEmbeddings, HuggingFacePipeline
15
+ from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline
16
+
17
+ import chromadb
18
+ import torch
19
+ from concurrent.futures import ThreadPoolExecutor
20
+
21
+ # Environment configuration
22
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
23
+
24
+ # Predefined values
25
+ predefined_pdf = "t6.pdf"
26
+ predefined_llm = "meta-llama/Llama-2-7b-hf" # Use a smaller model for faster responses
27
+
28
+ def load_doc(list_file_path, chunk_size, chunk_overlap):
29
+ loaders = [PyPDFLoader(x) for x in list_file_path]
30
+ pages = []
31
+ for loader in loaders:
32
+ pages.extend(loader.load())
33
+ text_splitter = RecursiveCharacterTextSplitter(
34
+ chunk_size=chunk_size,
35
+ chunk_overlap=chunk_overlap)
36
+ doc_splits = text_splitter.split_documents(pages)
37
+ return doc_splits
38
+
39
+ def create_db(splits, collection_name):
40
+ embedding = HuggingFaceEmbeddings()
41
+ new_client = chromadb.EphemeralClient()
42
+ vectordb = Chroma.from_documents(
43
+ documents=splits,
44
+ embedding=embedding,
45
+ client=new_client,
46
+ collection_name=collection_name,
47
+ )
48
+ return vectordb
49
+
50
+ def load_db():
51
+ embedding = HuggingFaceEmbeddings()
52
+ vectordb = Chroma(
53
+ embedding_function=embedding)
54
+ return vectordb
55
+
56
+ def create_collection_name(filepath):
57
+ collection_name = Path(filepath).stem
58
+ collection_name = collection_name.replace(" ", "-")
59
+ collection_name = unidecode(collection_name)
60
+ collection_name = re.sub('[^A-Za-z0-9]+', '-', collection_name)
61
+ collection_name = collection_name[:50]
62
+ if len(collection_name) < 3:
63
+ collection_name = collection_name + 'xyz'
64
+ if not collection_name[0].isalnum():
65
+ collection_name = 'A' + collection_name[1:]
66
+ if not collection_name[-1].isalnum():
67
+ collection_name = collection_name[:-1] + 'Z'
68
+ print('Filepath: ', filepath)
69
+ print('Collection name: ', collection_name)
70
+ return collection_name
71
+
72
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db):
73
+ if not torch.cuda.is_available():
74
+ print("CUDA is not available. This demo does not work on CPU.")
75
+ return None
76
+
77
+ def init_llm():
78
+ print("Initializing HF model and tokenizer...")
79
+ model = AutoModelForCausalLM.from_pretrained(llm_model, device_map="auto", load_in_4bit=True)
80
+ tokenizer = AutoTokenizer.from_pretrained(llm_model)
81
+ tokenizer.use_default_system_prompt = False
82
+
83
+ print("Initializing HF pipeline...")
84
+ hf_pipeline = pipeline(
85
+ "text-generation",
86
+ model=model,
87
+ tokenizer=tokenizer,
88
+ device_map='auto',
89
+ max_new_tokens=max_tokens,
90
+ do_sample=True,
91
+ top_k=top_k,
92
+ num_return_sequences=1,
93
+ eos_token_id=tokenizer.eos_token_id
94
+ )
95
+ llm = HuggingFacePipeline(pipeline=hf_pipeline, model_kwargs={'temperature': temperature})
96
+
97
+ print("Defining buffer memory...")
98
+ memory = ConversationBufferMemory(
99
+ memory_key="chat_history",
100
+ output_key='answer',
101
+ return_messages=True
102
+ )
103
+ retriever = vector_db.as_retriever()
104
+  
105
+ print("Defining retrieval chain...")
106
+ qa_chain = ConversationalRetrievalChain.from_llm(
107
+ llm,
108
+ retriever=retriever,
109
+ chain_type="stuff",
110
+ memory=memory,
111
+ return_source_documents=True,
112
+ verbose=False,
113
+ )
114
+ return qa_chain
115
+
116
+ with ThreadPoolExecutor() as executor:
117
+ future = executor.submit(init_llm)
118
+ qa_chain = future.result()
119
+  
120
+ print("Initialization complete!")
121
+ return qa_chain
122
+
123
+ # Define the conversation function with streaming
124
+ @spaces.GPU()
125
+ def conversation(message):
126
+ global qa_chain
127
+ # Generate response using QA chain with yield for streaming
128
+ for response_part in qa_chain({"question": message}):
129
+ yield response_part["answer"]
130
+ # Extract sources and their content
131
+ response_sources = response["source_documents"]
132
+ response_source1 = response_sources[0].page_content.strip() if response_sources and len(response_sources) > 0 else ""
133
+ response_source2 = response_sources[1].page_content.strip() if response_sources and len(response_sources) > 1 else ""
134
+ response_source3 = response_sources[2].page_content.strip() if response_sources and len(response_sources) > 2 else ""
135
+
136
+ # Langchain sources are zero-based
137
+ response_source1_page = response_sources[0].metadata["page"] + 1 if response_sources and len(response_sources) > 0 else 0
138
+ response_source2_page = response_sources[1].metadata["page"] + 1 if response_sources and len(response_sources) > 1 else 0
139
+ response_source3_page = response_sources[2].metadata["page"] + 1 if response_sources and len(response_sources) > 2 else 0
140
+
141
+ # Format the response for visualization
142
+ answer_visualization = (
143
+ f"Question: {message}\n"
144
+ f"Answer: {response_answer}\n\n"
145
+ f"Source 1 (Page {response_source1_page}): {response_source1}\n\n"
146
+ f"Source 2 (Page {response_source2_page}): {response_source2}\n\n"
147
+ f"Source 3 (Page {response_source3_page}): {response_source3}"
148
+ )
149
+
150
+ yield answer_visualization
151
+
152
+ # Load the PDF document and create the vector database (replace with your logic)
153
+ pdf_filepath = predefined_pdf
154
+ doc_splits = load_doc([pdf_filepath], chunk_size=2048, chunk_overlap=512)
155
+ collection_name = create_collection_name(pdf_filepath)
156
+ vector_db = create_db(doc_splits, collection_name)
157
+
158
+ # Initialize the LLM chain with threading
159
+ qa_chain = initialize_llmchain(predefined_llm, temperature=0.7, max_tokens=64, top_k=1, vector_db=vector_db)
160
+
161
+ # Check if qa_chain is properly initialized
162
+ if qa_chain is None:
163
+ print("Failed to initialize the QA chain. Please check the CUDA availability and model paths.")
164
+ else:
165
+ # Launch the Gradio interface with share option
166
+ interface = gr.Interface(
167
+ fn=conversation,
168
+ inputs="textbox", # Use a single input textbox
169
+ outputs="text", # Text output for streaming
170
+ title="Conversational AI with Retrieval",
171
+ description="Ask me anything about the uploaded PDF document!",
172
+ )
173
+ interface.launch()