KingNish commited on
Commit
4a8ac8b
1 Parent(s): 6bf51ed

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +235 -0
app.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ import json
4
+ import re
5
+ import uuid
6
+ from PIL import Image
7
+ from bs4 import BeautifulSoup
8
+ import requests
9
+ import random
10
+ from gradio_client import Client, file
11
+
12
+ def generate_caption_instructblip(image_path, question):
13
+ client = Client("hysts/image-captioning-with-blip")
14
+ return client.predict(file(image_path), f"Answer this Question in detail {question}", api_name="/caption")
15
+
16
+ def extract_text_from_webpage(html_content):
17
+ """Extracts visible text from HTML content using BeautifulSoup."""
18
+ soup = BeautifulSoup(html_content, 'html.parser')
19
+ # Remove unwanted tags
20
+ for tag in soup(["script", "style", "header", "footer", "nav", "form", "svg"]):
21
+ tag.extract()
22
+ return soup.get_text(strip=True)
23
+
24
+ # Perform a Google search and return the results
25
+ def search(query):
26
+ """Performs a Google search and returns the results."""
27
+ term=query
28
+ print(f"Running web search for query: {term}")
29
+ start = 0
30
+ all_results = []
31
+ # Limit the number of characters from each webpage to stay under the token limit
32
+ max_chars_per_page = 8000 # Adjust this value based on your token limit and average webpage length
33
+
34
+ with requests.Session() as session:
35
+ resp = session.get(
36
+ url="https://www.google.com/search",
37
+ headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
38
+ params={
39
+ "q": term,
40
+ "num": 3,
41
+ "udm": 14,
42
+ },
43
+ timeout=5,
44
+ verify=None,
45
+ )
46
+ resp.raise_for_status()
47
+ soup = BeautifulSoup(resp.text, "html.parser")
48
+ result_block = soup.find_all("div", attrs={"class": "g"})
49
+ for result in result_block:
50
+ link = result.find("a", href=True)
51
+ link = link["href"]
52
+ try:
53
+ webpage = session.get(link, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"}, timeout=5,verify=False)
54
+ webpage.raise_for_status()
55
+ visible_text = extract_text_from_webpage(webpage.text)
56
+ # Truncate text if it's too long
57
+ if len(visible_text) > max_chars_per_page:
58
+ visible_text = visible_text[:max_chars_per_page]
59
+ all_results.append({"link": link, "text": visible_text})
60
+ except requests.exceptions.RequestException as e:
61
+ all_results.append({"link": link, "text": None})
62
+ return all_results
63
+
64
+
65
+ client = InferenceClient("google/gemma-1.1-7b-it")
66
+
67
+ def respond(
68
+ message, history
69
+ ):
70
+ messages = []
71
+ vqa=""
72
+ if message["files"]:
73
+ try:
74
+ vqa = "[CAPTION of IMAGE] "
75
+ image = message["files"][0]
76
+ gr.Info("Analyzing image")
77
+ vqa += generate_caption_instructblip(image, message["text"])
78
+ print(vqa)
79
+ except:
80
+ vqa = ""
81
+
82
+
83
+ functions_metadata = [
84
+ {
85
+ "type": "function",
86
+ "function": {
87
+ "name": "web_search",
88
+ "description": "Search query on google and find latest information.",
89
+ "parameters": {
90
+ "type": "object",
91
+ "properties": {
92
+ "query": {
93
+ "type": "string",
94
+ "description": "web search query",
95
+ }
96
+ },
97
+ "required": ["query"],
98
+ },
99
+ },
100
+ },
101
+ {
102
+ "type": "function",
103
+ "function": {
104
+ "name": "general_query",
105
+ "description": "Reply general query of USER through LLM like you, it does'nt know latest information. But very helpful in general query. Its very powerful LLM. It knows many thing just like you except latest things, or thing that you don't know.",
106
+ "parameters": {
107
+ "type": "object",
108
+ "properties": {
109
+ "prompt": {
110
+ "type": "string",
111
+ "description": "A detailed prompt so that an LLm can understand better, what user wants.",
112
+ }
113
+ },
114
+ "required": ["prompt"],
115
+ },
116
+ },
117
+ },
118
+ {
119
+ "type": "function",
120
+ "function": {
121
+ "name": "image_generation",
122
+ "description": "Generate image for user.",
123
+ "parameters": {
124
+ "type": "object",
125
+ "properties": {
126
+ "query": {
127
+ "type": "string",
128
+ "description": "image generation prompt in detail.",
129
+ },
130
+ "number_of_image": {
131
+ "type": "integer",
132
+ "description": "number of images to generate.",
133
+ }
134
+ },
135
+ "required": ["query"],
136
+ },
137
+ },
138
+ },
139
+ {
140
+ "type": "function",
141
+ "function": {
142
+ "name": "image_qna",
143
+ "description": "Answer question asked by user related to image.",
144
+ "parameters": {
145
+ "type": "object",
146
+ "properties": {
147
+ "query": {
148
+ "type": "string",
149
+ "description": "Question by user",
150
+ }
151
+ },
152
+ "required": ["query"],
153
+ },
154
+ },
155
+ }
156
+ ]
157
+
158
+ message_text = message["text"]
159
+
160
+ client_mixtral = InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
161
+ client_llama = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
162
+ generate_kwargs = dict( max_new_tokens=2000, do_sample=True, stream=True, details=True, return_full_text=False )
163
+
164
+ messages.append({"role": "user", "content": f'[SYSTEM]You are a helpful assistant with access to the following functions: \n {str(functions_metadata)}\n\nTo use these functions respond with:\n<functioncall> {{ "name": "function_name", "arguments": {{ "arg_1": "value_1", "arg_1": "value_1", ... }} }} </functioncall> [USER] {message_text} {vqa}'})
165
+
166
+ response = client.chat_completion( messages, max_tokens=150)
167
+ response = str(response)
168
+ try:
169
+ response = response[int(response.find("{")):int(response.rindex("</functioncall>"))]
170
+ except:
171
+ print("A error occured")
172
+ response = response.replace("\\n", "")
173
+ response = response.replace("\\'", "'")
174
+ response = response.replace('\\"', '"')
175
+ print(f"\n{response}")
176
+ # Extract JSON content from the response
177
+ try:
178
+ json_data = json.loads(str(response))
179
+ if json_data["name"] == "web_search":
180
+ query = json_data["arguments"]["query"]
181
+ gr.Info("Searching Web")
182
+ web_results = search(query)
183
+ gr.Info("Extracting relevant Info")
184
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
185
+ messages = f"<|im_start|>system\nYou are OpenGPT 4o mini a helpful assistant made by KingNish. You are provided with WEB results from which you can find informations to answer users query in Structured and More better way. You do not say Unnecesarry things Only say thing which is important and relevant. You also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis and reply like human, use short forms, friendly tone and emotions.<|im_end|>"
186
+ for msg in history:
187
+ messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
188
+ messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
189
+ messages+=f"\n<|im_start|>user\n{message_text} {vqa}<|im_end|>\n<|im_start|>web_result\n{web2}<|im_end|>\n<|im_start|>assistant\n"
190
+ stream = client_mixtral.text_generation(messages, **generate_kwargs)
191
+ output = ""
192
+ for response in stream:
193
+ if not response.token.text == "<|im_end|>":
194
+ output += response.token.text
195
+ yield output
196
+ elif json_data["name"] == "image_generation":
197
+ query = json_data["arguments"]["query"]
198
+ gr.Info("Generating Image, Please wait...")
199
+ seed = random.randint(1, 99999)
200
+ image = f"![](https://image.pollinations.ai/prompt/{query}?{seed})"
201
+ yield image
202
+ gr.Info("We are going to Update Our Image Generation Engine to more powerful ones in Next Update. ThankYou")
203
+ else:
204
+ messages = f"<|start_header_id|>system\nYou are OpenGPT 4o mini a helpful assistant made by KingNish. You answers users query like human friend. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis and reply like human, use short forms, friendly tone and emotions.<|end_header_id|>"
205
+ for msg in history:
206
+ messages += f"\n<|start_header_id|>user\n{str(msg[0])}<|end_header_id|>"
207
+ messages += f"\n<|start_header_id|>assistant\n{str(msg[1])}<|end_header_id|>"
208
+ messages+=f"\n<|start_header_id|>user\n{message_text} {vqa}<|end_header_id|>\n<|start_header_id|>assistant\n"
209
+ stream = client_llama.text_generation(messages, **generate_kwargs)
210
+ output = ""
211
+ for response in stream:
212
+ if not response.token.text == "<|eot_id|>":
213
+ output += response.token.text
214
+ yield output
215
+ except:
216
+ messages = f"<|start_header_id|>system\nYou are OpenGPT 4o mini a helpful assistant made by KingNish. You answers users query like human friend. You are also Expert in every field and also learn and try to answer from contexts related to previous question. Try your best to give best response possible to user. You also try to show emotions using Emojis and reply like human, use short forms, friendly tone and emotions.<|end_header_id|>"
217
+ for msg in history:
218
+ messages += f"\n<|start_header_id|>user\n{str(msg[0])}<|end_header_id|>"
219
+ messages += f"\n<|start_header_id|>assistant\n{str(msg[1])}<|end_header_id|>"
220
+ messages+=f"\n<|start_header_id|>user\n{message_text} {vqa}<|end_header_id|>\n<|start_header_id|>assistant\n"
221
+ stream = client_llama.text_generation(messages, **generate_kwargs)
222
+ output = ""
223
+ for response in stream:
224
+ if not response.token.text == "<|eot_id|>":
225
+ output += response.token.text
226
+ yield output
227
+
228
+ demo = gr.ChatInterface(fn=respond, title="OpenGPT 4o mini", textbox=gr.MultimodalTextbox(), multimodal=True,
229
+ examples=[["Hy, who are you?"],
230
+ ["What's the current price of Bitcoin"],
231
+ ["Write me a Python function to calculate the first 10 digits of the fibonacci sequence."],
232
+ ["Create A Beautiful image of Effiel Tower at Night"]
233
+ ["What's the colour of Car in given image"]])
234
+
235
+ demo.launch()