prithivMLmods commited on
Commit
b01cc46
·
verified ·
1 Parent(s): d9343a5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -10
app.py CHANGED
@@ -1,9 +1,18 @@
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import json
 
4
  from PIL import Image
5
  from bs4 import BeautifulSoup
6
  import requests
 
 
 
 
 
 
 
 
7
 
8
  def extract_text_from_webpage(html_content):
9
  soup = BeautifulSoup(html_content, 'html.parser')
@@ -13,14 +22,16 @@ def extract_text_from_webpage(html_content):
13
 
14
  def search(query):
15
  term = query
 
16
  all_results = []
17
  max_chars_per_page = 8000
18
  with requests.Session() as session:
19
  resp = session.get(
20
  url="https://www.google.com/search",
21
  headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
22
- params={"q": term, "num": 3},
23
- timeout=5
 
24
  )
25
  resp.raise_for_status()
26
  soup = BeautifulSoup(resp.text, "html.parser")
@@ -29,7 +40,7 @@ def search(query):
29
  link = result.find("a", href=True)
30
  link = link["href"]
31
  try:
32
- 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)
33
  webpage.raise_for_status()
34
  visible_text = extract_text_from_webpage(webpage.text)
35
  if len(visible_text) > max_chars_per_page:
@@ -44,6 +55,8 @@ client_gemma = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
44
  client_mixtral = InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
45
  client_llama = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
46
 
 
 
47
  # Define the main chat function
48
  def respond(message, history):
49
  func_caller = []
@@ -57,13 +70,13 @@ def respond(message, history):
57
  func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
58
  func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
59
 
60
- message_text = message
61
  func_caller.append({"role": "user", "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}'})
62
 
63
  response = client_gemma.chat_completion(func_caller, max_tokens=200)
64
  response = str(response)
65
  try:
66
- response = response[int(response.find("{")):int(response.rindex("</"))]
67
  except:
68
  response = response[int(response.find("{")):(int(response.rfind("}"))+1)]
69
  response = response.replace("\\n", "")
@@ -76,8 +89,10 @@ def respond(message, history):
76
  json_data = json.loads(str(response))
77
  if json_data["name"] == "web_search":
78
  query = json_data["arguments"]["query"]
 
79
  web_results = search(query)
80
- web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
 
81
  messages = f"system\nYou are OpenCHAT 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."
82
  for msg in history:
83
  messages += f"\nuser\n{str(msg[0])}"
@@ -114,15 +129,12 @@ def respond(message, history):
114
  output += response.token.text
115
  yield output
116
 
117
- # Define the Gradio demo
118
  demo = gr.ChatInterface(
119
  fn=respond,
120
  chatbot=gr.Chatbot(show_copy_button=True, likeable=True, layout="panel"),
121
- description="Ask anything and get responses based on web searches and AI models.",
122
  textbox=gr.MultimodalTextbox(),
123
  multimodal=True,
124
  concurrency_limit=200,
125
  )
126
-
127
- # Launch the Gradio demo
128
  demo.launch()
 
1
  import gradio as gr
2
  from huggingface_hub import InferenceClient
3
  import json
4
+ import uuid
5
  from PIL import Image
6
  from bs4 import BeautifulSoup
7
  import requests
8
+ import random
9
+ from transformers import LlavaProcessor, LlavaForConditionalGeneration, TextIteratorStreamer
10
+ from threading import Thread
11
+ import re
12
+ import time
13
+ import torch
14
+ import cv2
15
+ from gradio_client import Client, file
16
 
17
  def extract_text_from_webpage(html_content):
18
  soup = BeautifulSoup(html_content, 'html.parser')
 
22
 
23
  def search(query):
24
  term = query
25
+ start = 0
26
  all_results = []
27
  max_chars_per_page = 8000
28
  with requests.Session() as session:
29
  resp = session.get(
30
  url="https://www.google.com/search",
31
  headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
32
+ params={"q": term, "num": 3, "udm": 14},
33
+ timeout=5,
34
+ verify=None,
35
  )
36
  resp.raise_for_status()
37
  soup = BeautifulSoup(resp.text, "html.parser")
 
40
  link = result.find("a", href=True)
41
  link = link["href"]
42
  try:
43
+ 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)
44
  webpage.raise_for_status()
45
  visible_text = extract_text_from_webpage(webpage.text)
46
  if len(visible_text) > max_chars_per_page:
 
55
  client_mixtral = InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
56
  client_llama = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
57
 
58
+ func_caller = []
59
+
60
  # Define the main chat function
61
  def respond(message, history):
62
  func_caller = []
 
70
  func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
71
  func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
72
 
73
+ message_text = message["text"]
74
  func_caller.append({"role": "user", "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}'})
75
 
76
  response = client_gemma.chat_completion(func_caller, max_tokens=200)
77
  response = str(response)
78
  try:
79
+ response = response[int(response.find("{")):int(response.rindex("}"))+1]
80
  except:
81
  response = response[int(response.find("{")):(int(response.rfind("}"))+1)]
82
  response = response.replace("\\n", "")
 
89
  json_data = json.loads(str(response))
90
  if json_data["name"] == "web_search":
91
  query = json_data["arguments"]["query"]
92
+ gr.Info("Searching Web")
93
  web_results = search(query)
94
+ gr.Info("Extracting relevant Info")
95
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results if res['text']])
96
  messages = f"system\nYou are OpenCHAT 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."
97
  for msg in history:
98
  messages += f"\nuser\n{str(msg[0])}"
 
129
  output += response.token.text
130
  yield output
131
 
 
132
  demo = gr.ChatInterface(
133
  fn=respond,
134
  chatbot=gr.Chatbot(show_copy_button=True, likeable=True, layout="panel"),
135
+ description=" ",
136
  textbox=gr.MultimodalTextbox(),
137
  multimodal=True,
138
  concurrency_limit=200,
139
  )
 
 
140
  demo.launch()