DaimonKing commited on
Commit
9dc56a0
·
verified ·
1 Parent(s): 5ff5f66

Mark 1 app.py

Browse files
Files changed (1) hide show
  1. app.py +190 -63
app.py CHANGED
@@ -1,64 +1,191 @@
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
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
-
62
-
63
- if __name__ == "__main__":
64
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import os
3
+ from langchain.document_loaders import WebBaseLoader
4
+ from langchain_community.vectorstores import FAISS
5
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
6
+ from langchain.chains import ConversationalRetrievalChain
7
+ from langchain.chains import ConversationChain
8
+ from langchain.memory import ConversationBufferMemory
9
+ from langchain_community.llms import HuggingFaceEndpoint
10
+ from langchain_community.embeddings import OllamaEmbeddings
11
+ from langchain_ollama import ChatOllama
12
+ import re
13
+ import torch
14
+
15
+
16
+ def preprocessing_text(document: list) -> list:
17
+ document[0].page_content = re.sub(r"\n{2,}", "\n\n", document[0].page_content)
18
+ return document
19
+
20
+ def loading_the_webpage(url: str) -> list:
21
+ loader = WebBaseLoader(url)
22
+ document = preprocessing_text(loader.load())
23
+ return document
24
+
25
+
26
+ def chunking(document: list) -> list:
27
+ text_splitter = RecursiveCharacterTextSplitter(chunk_size= 1024,
28
+ chunk_overlap= 128,
29
+ separators= ["\n\n", "\n", " ", ""])
30
+ return text_splitter.split_documents(documents= document)
31
+
32
+
33
+
34
+ def create_vector_db(chunked_documents):
35
+ embeddings = OllamaEmbeddings(model= 'nomic-embed-text', show_progress= True)
36
+ vector_db = FAISS.from_documents(chunked_documents, embeddings)
37
+ return vector_db
38
+
39
+
40
+ # Initialize langchain LLM chain
41
+ def initialize_llmchain(llm_model, temperature, max_tokens, top_k, vector_db, progress=gr.Progress()):
42
+ llm = ChatOllama(model= "mistral",
43
+ temperature= temperature,
44
+ top_k= top_k,
45
+ num_predict= max_tokens)
46
+
47
+ memory = ConversationBufferMemory(
48
+ memory_key="chat_history",
49
+ output_key='answer',
50
+ return_messages=True
51
+ )
52
+
53
+ retriever=vector_db.as_retriever()
54
+ qa_chain = ConversationalRetrievalChain.from_llm(
55
+ llm,
56
+ retriever=retriever,
57
+ chain_type="stuff",
58
+ memory=memory,
59
+ return_source_documents=True,
60
+ verbose=False,
61
+ )
62
+ return qa_chain
63
+
64
+ def process_url_and_query(url: str, query: str):
65
+ # Load and process the webpage
66
+ documents = loading_the_webpage(url)
67
+ documents = preprocessing_text(documents)
68
+
69
+ # Chunk the documents
70
+ chunked_documents = chunking(documents)
71
+
72
+ # Create a vector database from chunked documents
73
+ vector_db = create_vector_db(chunked_documents)
74
+
75
+ # Initialize the LLM chain
76
+ qa_chain = initialize_llmchain(llm_model="mistral", temperature=0.7, max_tokens=150, top_k=5, vector_db=vector_db)
77
+
78
+ # Get the answer for the user's query
79
+ answer = qa_chain({"question": query})
80
+
81
+ return answer['answer']
82
+
83
+ with gr.Blocks() as demo:
84
+ gr.Markdown("# Webpage Querying App")
85
+
86
+ url_input = gr.Textbox(label="Enter URL")
87
+ query_input = gr.Textbox(label="Enter your query")
88
+
89
+ submit_button = gr.Button("Submit")
90
+
91
+ output_textbox = gr.Textbox(label="Response", interactive=False)
92
+
93
+ submit_button.click(process_url_and_query, inputs=[url_input, query_input], outputs=output_textbox)
94
+
95
+ # Launch the app
96
+ demo.launch()
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+
110
+
111
+
112
+
113
+
114
+
115
+
116
+
117
+
118
+
119
+
120
+
121
+
122
+
123
+
124
+
125
+
126
+
127
+
128
+ # import gradio as gr
129
+ # from huggingface_hub import InferenceClient
130
+
131
+ # """
132
+ # 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
133
+ # """
134
+ # client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
135
+
136
+
137
+ # def respond(
138
+ # message,
139
+ # history: list[tuple[str, str]],
140
+ # system_message,
141
+ # max_tokens,
142
+ # temperature,
143
+ # top_p,
144
+ # ):
145
+ # messages = [{"role": "system", "content": system_message}]
146
+
147
+ # for val in history:
148
+ # if val[0]:
149
+ # messages.append({"role": "user", "content": val[0]})
150
+ # if val[1]:
151
+ # messages.append({"role": "assistant", "content": val[1]})
152
+
153
+ # messages.append({"role": "user", "content": message})
154
+
155
+ # response = ""
156
+
157
+ # for message in client.chat_completion(
158
+ # messages,
159
+ # max_tokens=max_tokens,
160
+ # stream=True,
161
+ # temperature=temperature,
162
+ # top_p=top_p,
163
+ # ):
164
+ # token = message.choices[0].delta.content
165
+
166
+ # response += token
167
+ # yield response
168
+
169
+
170
+ # """
171
+ # For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
172
+ # """
173
+ # demo = gr.ChatInterface(
174
+ # respond,
175
+ # additional_inputs=[
176
+ # gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
177
+ # gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
178
+ # gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
179
+ # gr.Slider(
180
+ # minimum=0.1,
181
+ # maximum=1.0,
182
+ # value=0.95,
183
+ # step=0.05,
184
+ # label="Top-p (nucleus sampling)",
185
+ # ),
186
+ # ],
187
+ # )
188
+
189
+
190
+ # if __name__ == "__main__":
191
+ # demo.launch()