Nithish310 commited on
Commit
b70feb9
·
verified ·
1 Parent(s): 6f5e8dd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -76
app.py CHANGED
@@ -40,7 +40,7 @@ def llava(message, history):
40
 
41
  gr.Info("Analyzing image")
42
  image = Image.open(image).convert("RGB")
43
- prompt = f"<image>\n{txt}"
44
 
45
  inputs = processor(prompt, image, return_tensors="pt")
46
  return inputs
@@ -48,12 +48,9 @@ def llava(message, history):
48
 
49
  def extract_text_from_webpage(html_content):
50
  soup = BeautifulSoup(html_content, 'html.parser')
51
- for tag in soup(["script", "style", "header", "footer"]:
52
  tag.extract()
53
- visible_text = soup.get_text(strip=True)
54
- if len(visible_text) > max_chars_per_page and visible_text.endswith("..."):
55
- visible_text = visible_text[:max_chars_per_page]
56
- return visible_text
57
 
58
 
59
  def search(query):
@@ -119,47 +116,43 @@ def respond(message, history):
119
  {"type": "function", "function": {"name": "web_search", "description": "Search query on google",
120
  "parameters": {"type": "object", "properties": {
121
  "query": {"type": "string", "description": "web search query"}},
122
- "required": ["query"]}},
123
  {"type": "function", "function": {"name": "general_query", "description": "Reply general query of USER",
124
  "parameters": {"type": "object", "properties": {
125
  "prompt": {"type": "string", "description": "A detailed prompt"}},
126
- "required": ["prompt"]}},
127
  {"type": "function", "function": {"name": "image_generation", "description": "Generate image for user",
128
  "parameters": {"type": "object", "properties": {
129
  "query": {"type": "string",
130
  "description": "image generation prompt"}},
131
- "required": ["query"]}},
132
  {"type": "function",
133
  "function": {"name": "image_qna", "description": "Answer question asked by user related to image",
134
  "parameters": {"type": "object",
135
  "properties": {"query": {"type": "string", "description": "Question by user"}},
136
- "required": ["query"]}},
137
  ]
138
 
139
-
140
  for msg in history:
141
  func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
142
  func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
143
 
144
-
145
  message_text = message["text"]
146
  func_caller.append({"role": "user",
147
  "content": f'[SYSTEM]You are a helpful assistant. You have 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}'})
148
 
149
-
150
  response = client_gemma.chat_completion(func_caller, max_tokens=200)
151
  response = str(response)
152
  try:
153
  response = response[int(response.find("{")):int(response.rindex("</"))]
154
  except:
155
- response = response[int(response.find("{")):(int(response.find("}")) + 1)]
156
  response = response.replace("\\n", "")
157
  response = response.replace("\\'", "'")
158
  response = response.replace('\\"', '"')
159
  response = response.replace('\\', '')
160
  print(f"\n{response}")
161
 
162
-
163
  try:
164
  json_data = json.loads(str(response))
165
  if json_data["name"] == "web_search":
@@ -168,13 +161,17 @@ def respond(message, history):
168
  web_results = search(query)
169
  gr.Info("Extracting relevant Info")
170
  web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
171
- messages = f"[SYSTEM]You are OpenCHAT mini a helpful assistant made by Nithish. 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 Unnecesary 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. [USER]\n{message_text}[WEB_RESULT]\n{web2}[ASSISTANT]"
 
 
 
 
172
  stream = client_mixtral.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True,
173
  details=True, return_full_text=False)
174
  output = ""
175
  for response in stream:
176
  if not response.token.text == "hello":
177
- output += response.token.text.replace("]", "")
178
  yield output
179
  elif json_data["name"] == "image_generation":
180
  query = json_data["arguments"]["query"]
@@ -182,7 +179,7 @@ def respond(message, history):
182
  yield "Generating Image, Please wait 10 sec..."
183
  try:
184
  client_sd3 = InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers")
185
- seed = random.randint(0, 99999)
186
  negativeprompt = ""
187
  image = client_sd3.text_to_image(query, negative_prompt=f"{seed},{negativeprompt}")
188
  yield gr.Image(image)
@@ -202,82 +199,40 @@ def respond(message, history):
202
  buffer += new_text
203
  yield buffer
204
  else:
205
- messages = f"[SYSTEM]You are OpenGPT a Expert AI Chat bot made by Nithish. You answers users query like professional . You are also Mastered 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. [USER]\n{message_text}[ASSISTANT]"
 
 
 
 
206
  stream = client_yi.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True,
207
  details=True, return_full_text=False)
208
  output = ""
209
  for response in stream:
210
- if not response.token.text == " ":
211
- output += response.token.text
212
  yield output
213
  except:
214
- messages = f"[SYSTEM]You are OpenGPT a helpful AI CHAT BOT made by Nithish. You answers users query like professional . 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.[USER]\n{message_text}[ASSISTANT]"
 
 
 
 
215
  stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True,
216
  details=True, return_full_text=False)
217
  output = ""
218
  for response in stream:
219
  if not response.token.text == "<|eot_id|>":
220
- output += response.token
221
  yield output
222
 
 
223
  demo = gr.ChatInterface(
224
  fn=respond,
225
- chatbot=gr.Chatbot(
226
- show_copy_button=True,
227
- likeable=True,
228
- layout="panel",
229
- ),
230
  description="# OpenGPT 4o \n ### chat, generate images, perform web searches, and Q&A with images.",
231
  textbox=gr.MultimodalTextbox(),
232
  multimodal=True,
233
- concurrency_limit=20,
234
  cache_examples=False,
235
- theme="default",
236
- css=
237
- .chat-container {
238
- border: 1px solid #ccc;
239
- border-radius: 5px;
240
- padding: 10px;
241
- }
242
- .chat-message {
243
- background-color: #f0f0f0;
244
- padding: 10px;
245
- border-radius: 5px;
246
- margin-bottom: 10px;
247
- }
248
- .chat-message.own {
249
- background-color: #dff0d8;
250
- }
251
- .chat-message.own::before {
252
- content: 'You';
253
- font-weight: bold;
254
- }
255
- .chat-message.bot::before {
256
- content: 'Bot';
257
- font-weight: bold;
258
- }
259
- /* Add this to make it look like Hugging Chat v0.9.2 */
260
- .chat-container {
261
- background-color: #f0f0f0;
262
- padding: 20px;
263
- }
264
- .chat-message {
265
- background-color: #dff0d8;
266
- padding: 10px;
267
- border-radius: 5px;
268
- margin-bottom: 10px;
269
- }
270
- .chat-message.own {
271
- background-color: #dff0d8;
272
- }
273
- .chat-message.own::before {
274
- content: 'You';
275
- font-weight: bold;
276
- }
277
- .chat-message.bot::before {
278
- content: 'Bot';
279
- font-weight: bold;
280
- }
281
- ,
282
  )
283
  demo.launch()
 
40
 
41
  gr.Info("Analyzing image")
42
  image = Image.open(image).convert("RGB")
43
+ prompt = f"<|im_start|>user <image>\n{txt}<|im_start|>assistant"
44
 
45
  inputs = processor(prompt, image, return_tensors="pt")
46
  return inputs
 
48
 
49
  def extract_text_from_webpage(html_content):
50
  soup = BeautifulSoup(html_content, 'html.parser')
51
+ for tag in soup(["script", "style", "header", "footer"]):
52
  tag.extract()
53
+ return soup.get_text(strip=True)
 
 
 
54
 
55
 
56
  def search(query):
 
116
  {"type": "function", "function": {"name": "web_search", "description": "Search query on google",
117
  "parameters": {"type": "object", "properties": {
118
  "query": {"type": "string", "description": "web search query"}},
119
+ "required": ["query"]}}},
120
  {"type": "function", "function": {"name": "general_query", "description": "Reply general query of USER",
121
  "parameters": {"type": "object", "properties": {
122
  "prompt": {"type": "string", "description": "A detailed prompt"}},
123
+ "required": ["prompt"]}}},
124
  {"type": "function", "function": {"name": "image_generation", "description": "Generate image for user",
125
  "parameters": {"type": "object", "properties": {
126
  "query": {"type": "string",
127
  "description": "image generation prompt"}},
128
+ "required": ["query"]}}},
129
  {"type": "function",
130
  "function": {"name": "image_qna", "description": "Answer question asked by user related to image",
131
  "parameters": {"type": "object",
132
  "properties": {"query": {"type": "string", "description": "Question by user"}},
133
+ "required": ["query"]}}},
134
  ]
135
 
 
136
  for msg in history:
137
  func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
138
  func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
139
 
 
140
  message_text = message["text"]
141
  func_caller.append({"role": "user",
142
  "content": f'[SYSTEM]You are a helpful assistant. You have 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}'})
143
 
 
144
  response = client_gemma.chat_completion(func_caller, max_tokens=200)
145
  response = str(response)
146
  try:
147
  response = response[int(response.find("{")):int(response.rindex("</"))]
148
  except:
149
+ response = response[int(response.find("{")):(int(response.rfind("}")) + 1)]
150
  response = response.replace("\\n", "")
151
  response = response.replace("\\'", "'")
152
  response = response.replace('\\"', '"')
153
  response = response.replace('\\', '')
154
  print(f"\n{response}")
155
 
 
156
  try:
157
  json_data = json.loads(str(response))
158
  if json_data["name"] == "web_search":
 
161
  web_results = search(query)
162
  gr.Info("Extracting relevant Info")
163
  web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
164
+ messages = f"<|im_start|>system\nYou are OpenCHAT mini a helpful assistant made by Nithish. 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|>"
165
+ for msg in history:
166
+ messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
167
+ messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
168
+ messages += f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>web_result\n{web2}<|im_end|>\n<|im_start|>assistant\n"
169
  stream = client_mixtral.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True,
170
  details=True, return_full_text=False)
171
  output = ""
172
  for response in stream:
173
  if not response.token.text == "hello":
174
+ output += response.token.text.replace("<|im_end|>", "")
175
  yield output
176
  elif json_data["name"] == "image_generation":
177
  query = json_data["arguments"]["query"]
 
179
  yield "Generating Image, Please wait 10 sec..."
180
  try:
181
  client_sd3 = InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers")
182
+ seed = random.randint(0, 999999)
183
  negativeprompt = ""
184
  image = client_sd3.text_to_image(query, negative_prompt=f"{seed},{negativeprompt}")
185
  yield gr.Image(image)
 
199
  buffer += new_text
200
  yield buffer
201
  else:
202
+ messages = f"<|im_start|>system\nYou are OpenGPT a Expert AI Chat bot made by Nithish. You answers users query like professional AI. You are also Mastered 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.<|im_end|>"
203
+ for msg in history:
204
+ messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
205
+ messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
206
+ messages += f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>assistant\n"
207
  stream = client_yi.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True,
208
  details=True, return_full_text=False)
209
  output = ""
210
  for response in stream:
211
+ if not response.token.text == "<|endoftext|>":
212
+ output += response.token.text.replace("<|im_end|>", "")
213
  yield output
214
  except:
215
+ messages = f"<|start_header_id|>system\nYou are OpenGPT a helpful AI CHAT BOT made by Nithish. You answers users query like professional . 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.<|end_header_id|>"
216
+ for msg in history:
217
+ messages += f"\n<|start_header_id|>user\n{str(msg[0])}<|end_header_id|>"
218
+ messages += f"\n<|start_header_id|>assistant\n{str(msg[1])}<|end_header_id|>"
219
+ messages += f"\n<|start_header_id|>user\n{message_text}<|end_header_id|>\n<|start_header_id|>assistant\n"
220
  stream = client_llama.text_generation(messages, max_new_tokens=2000, do_sample=True, stream=True,
221
  details=True, return_full_text=False)
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
+
229
  demo = gr.ChatInterface(
230
  fn=respond,
231
+ chatbot=gr.Chatbot(show_copy_button=True, likeable=True, layout="panel"),
 
 
 
 
232
  description="# OpenGPT 4o \n ### chat, generate images, perform web searches, and Q&A with images.",
233
  textbox=gr.MultimodalTextbox(),
234
  multimodal=True,
235
+ concurrency_limit=200,
236
  cache_examples=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  )
238
  demo.launch()