README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 🔥
4
  colorFrom: blue
5
  colorTo: indigo
6
  sdk: gradio
7
- sdk_version: 4.37.2
8
  app_file: app.py
9
  pinned: true
10
  short_description: GPT 4o like bot.
@@ -24,7 +24,6 @@ GPT 4o vs OpenGPT 4o
24
  | Image Generation | Paid only | Yes |
25
  |Video Generation|No|Yes|
26
  | Image QnA | Yes | Yes |
27
- | Video QnA | Yes (but very limited) | Yes |
28
  | Voice Chat | Yes but Very Limited | Yes (Unlimited) |
29
  | Video Chat | Paid Only | Yes |
30
  | Multilingual | Yes | Chat Only |
 
4
  colorFrom: blue
5
  colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 4.33.0
8
  app_file: app.py
9
  pinned: true
10
  short_description: GPT 4o like bot.
 
24
  | Image Generation | Paid only | Yes |
25
  |Video Generation|No|Yes|
26
  | Image QnA | Yes | Yes |
 
27
  | Voice Chat | Yes but Very Limited | Yes (Unlimited) |
28
  | Video Chat | Paid Only | Yes |
29
  | Multilingual | Yes | Chat Only |
app.py CHANGED
@@ -1,98 +1,273 @@
1
  import gradio as gr
2
- import spaces
3
- from chatbot import model_inference, EXAMPLES, chatbot
4
- from voice_chat import respond
5
-
6
- # Define custom CSS for better styling
7
- custom_css = """
8
- .gradio-container {
9
- font-family: 'Roboto', sans-serif;
10
- }
11
-
12
- .main-header {
13
- text-align: center;
14
- color: #4a4a4a;
15
- margin-bottom: 2rem;
16
- }
17
-
18
- .tab-header {
19
- font-size: 1.2rem;
20
- font-weight: bold;
21
- margin-bottom: 1rem;
22
- }
23
-
24
- .custom-chatbot {
25
- border-radius: 10px;
26
- box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
27
- }
28
-
29
- .custom-button {
30
- background-color: #3498db;
31
- color: white;
32
- border: none;
33
- padding: 10px 20px;
34
- border-radius: 5px;
35
- cursor: pointer;
36
- transition: background-color 0.3s ease;
37
- }
38
-
39
- .custom-button:hover {
40
- background-color: #2980b9;
41
- }
42
- """
43
 
44
  # Define Gradio theme
45
  theme = gr.themes.Soft(
46
- primary_hue="indigo",
47
- secondary_hue="blue",
48
- neutral_hue="slate",
49
- font=[gr.themes.GoogleFont('Roboto'), "sans-serif"]
 
 
 
 
 
 
 
 
 
 
50
  )
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  # Chat interface block
53
- with gr.Blocks(css=custom_css) as chat:
54
- gr.Markdown("### 💬 OpenGPT 4o Chat", elem_classes="tab-header")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  gr.ChatInterface(
56
  fn=model_inference,
57
  chatbot=chatbot,
58
  examples=EXAMPLES,
59
  multimodal=True,
60
  cache_examples=False,
61
- autofocus=False,
62
- concurrency_limit=10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  )
64
 
65
- # Voice chat block
66
- with gr.Blocks() as voice:
67
- gr.Markdown("### 🗣️ Voice Chat", elem_classes="tab-header")
68
- gr.Markdown("Try Voice Chat from the link below:")
69
- gr.HTML('<a href="https://huggingface.co/spaces/KingNish/Voicee" target="_blank" class="custom-button">Open Voice Chat</a>')
70
 
71
- with gr.Blocks() as image_gen_pro:
72
  gr.HTML("<iframe src='https://kingnish-image-gen-pro.hf.space' width='100%' height='2000px' style='border-radius: 8px;'></iframe>")
73
 
74
- with gr.Blocks() as flux_fast:
75
- gr.HTML("<iframe src='https://prodia-flux-1-dev.hf.space' width='100%' height='2000px' style='border-radius: 8px;'></iframe>")
76
 
77
- # Image engine block
78
  with gr.Blocks() as image:
79
- gr.Markdown("### 🖼️ Image Engine", elem_classes="tab-header")
80
- gr.TabbedInterface([flux_fast, image_gen_pro], ['High Quality Image Gen'],['Image gen and editing'])
81
-
82
 
83
- # Video engine block
84
- with gr.Blocks() as video:
85
- gr.Markdown("### 🎥 Video Engine", elem_classes="tab-header")
86
  gr.HTML("<iframe src='https://kingnish-instant-video.hf.space' width='100%' height='3000px' style='border-radius: 8px;'></iframe>")
87
 
 
 
 
88
 
89
  # Main application block
90
  with gr.Blocks(theme=theme, title="OpenGPT 4o DEMO") as demo:
91
- gr.Markdown("# 🚀 OpenGPT 4o", elem_classes="main-header")
92
- gr.TabbedInterface(
93
- [chat, voice, image, video],
94
- ['💬 SuperChat', '🗣️ Voice Chat', '🖼️ Image Engine', '🎥 Video Engine']
95
- )
96
 
97
  demo.queue(max_size=300)
98
  demo.launch()
 
1
  import gradio as gr
2
+
3
+ # Import modules from other files
4
+ from chatbot import chatbot, model_inference, BOT_AVATAR, EXAMPLES, model_selector, decoding_strategy, temperature, max_new_tokens, repetition_penalty, top_p
5
+ from live_chat import videochat
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  # Define Gradio theme
8
  theme = gr.themes.Soft(
9
+ primary_hue="blue",
10
+ secondary_hue="orange",
11
+ neutral_hue="gray",
12
+ font=[gr.themes.GoogleFont('Libre Franklin'), gr.themes.GoogleFont('Public Sans'), 'system-ui', 'sans-serif']
13
+ ).set(
14
+ body_background_fill_dark="#111111",
15
+ block_background_fill_dark="#111111",
16
+ block_border_width="1px",
17
+ block_title_background_fill_dark="#1e1c26",
18
+ input_background_fill_dark="#292733",
19
+ button_secondary_background_fill_dark="#24212b",
20
+ border_color_primary_dark="#343140",
21
+ background_fill_secondary_dark="#111111",
22
+ color_accent_soft_dark="transparent"
23
  )
24
 
25
+ import edge_tts
26
+ import asyncio
27
+ import tempfile
28
+ import numpy as np
29
+ import soxr
30
+ from pydub import AudioSegment
31
+ import torch
32
+ import sentencepiece as spm
33
+ import onnxruntime as ort
34
+ from huggingface_hub import hf_hub_download, InferenceClient
35
+ import requests
36
+ from bs4 import BeautifulSoup
37
+ import urllib
38
+ import random
39
+
40
+ # List of user agents to choose from for requests
41
+ _useragent_list = [
42
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
43
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
44
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
45
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
46
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
47
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.62',
48
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
49
+ ]
50
+
51
+ def get_useragent():
52
+ """Returns a random user agent from the list."""
53
+ return random.choice(_useragent_list)
54
+
55
+ def extract_text_from_webpage(html_content):
56
+ """Extracts visible text from HTML content using BeautifulSoup."""
57
+ soup = BeautifulSoup(html_content, "html.parser")
58
+ # Remove unwanted tags
59
+ for tag in soup(["script", "style", "header", "footer", "nav"]):
60
+ tag.extract()
61
+ # Get the remaining visible text
62
+ visible_text = soup.get_text(strip=True)
63
+ return visible_text
64
+
65
+ def search(term, num_results=1, lang="en", advanced=True, sleep_interval=0, timeout=5, safe="active", ssl_verify=None):
66
+ """Performs a Google search and returns the results."""
67
+ escaped_term = urllib.parse.quote_plus(term)
68
+ start = 0
69
+ all_results = []
70
+
71
+ # Fetch results in batches
72
+ while start < num_results:
73
+ resp = requests.get(
74
+ url="https://www.google.com/search",
75
+ headers={"User-Agent": get_useragent()}, # Set random user agent
76
+ params={
77
+ "q": term,
78
+ "num": num_results - start, # Number of results to fetch in this batch
79
+ "hl": lang,
80
+ "start": start,
81
+ "safe": safe,
82
+ },
83
+ timeout=timeout,
84
+ verify=ssl_verify,
85
+ )
86
+ resp.raise_for_status() # Raise an exception if request fails
87
+
88
+ soup = BeautifulSoup(resp.text, "html.parser")
89
+ result_block = soup.find_all("div", attrs={"class": "g"})
90
+
91
+ # If no results, continue to the next batch
92
+ if not result_block:
93
+ start += 1
94
+ continue
95
+
96
+ # Extract link and text from each result
97
+ for result in result_block:
98
+ link = result.find("a", href=True)
99
+ if link:
100
+ link = link["href"]
101
+ try:
102
+ # Fetch webpage content
103
+ webpage = requests.get(link, headers={"User-Agent": get_useragent()})
104
+ webpage.raise_for_status()
105
+ # Extract visible text from webpage
106
+ visible_text = extract_text_from_webpage(webpage.text)
107
+ all_results.append({"link": link, "text": visible_text})
108
+ except requests.exceptions.RequestException as e:
109
+ # Handle errors fetching or processing webpage
110
+ print(f"Error fetching or processing {link}: {e}")
111
+ all_results.append({"link": link, "text": None})
112
+ else:
113
+ all_results.append({"link": None, "text": None})
114
+
115
+ start += len(result_block) # Update starting index for next batch
116
+
117
+ return all_results
118
+
119
+ # Speech Recognition Model Configuration
120
+ model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
121
+ sample_rate = 16000
122
+
123
+ # Download preprocessor, encoder and tokenizer
124
+ preprocessor = torch.jit.load(hf_hub_download(model_name, "preprocessor.ts", subfolder="onnx"))
125
+ encoder = ort.InferenceSession(hf_hub_download(model_name, "model.onnx", subfolder="onnx"))
126
+ tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
127
+
128
+ # Mistral Model Configuration
129
+ client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
130
+ system_instructions1 = "<s>[SYSTEM] Answer as Real OpenGPT 4o, Made by 'KingNish', Keep conversation very short, clear, friendly and concise. The text provided is a request for a specific type of response from you, the virtual assistant. The request asks you to provide friendly responses. The expectation is that I will avoid introductions and start answering the query directly, elaborating on all aspects of the request. As an AI-powered assistant, your task is to generate responses that appear as if they are created by the user and not an AI-powered assistant. [USER]"
131
+
132
+ def resample(audio_fp32, sr):
133
+ return soxr.resample(audio_fp32, sr, sample_rate)
134
+
135
+ def to_float32(audio_buffer):
136
+ return np.divide(audio_buffer, np.iinfo(audio_buffer.dtype).max, dtype=np.float32)
137
+
138
+ def transcribe(audio_path):
139
+ audio_file = AudioSegment.from_file(audio_path)
140
+ sr = audio_file.frame_rate
141
+ audio_buffer = np.array(audio_file.get_array_of_samples())
142
+
143
+ audio_fp32 = to_float32(audio_buffer)
144
+ audio_16k = resample(audio_fp32, sr)
145
+
146
+ input_signal = torch.tensor(audio_16k).unsqueeze(0)
147
+ length = torch.tensor(len(audio_16k)).unsqueeze(0)
148
+ processed_signal, _ = preprocessor.forward(input_signal=input_signal, length=length)
149
+
150
+ logits = encoder.run(None, {'audio_signal': processed_signal.numpy(), 'length': length.numpy()})[0][0]
151
+
152
+ blank_id = tokenizer.vocab_size()
153
+ decoded_prediction = [p for p in logits.argmax(axis=1).tolist() if p != blank_id]
154
+ text = tokenizer.decode_ids(decoded_prediction)
155
+
156
+ return text
157
+
158
+ def model(text, web_search):
159
+ if web_search is True:
160
+ """Performs a web search, feeds the results to a language model, and returns the answer."""
161
+ web_results = search(text)
162
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
163
+ formatted_prompt = system_instructions1 + text + "[WEB]" + str(web2) + "[OpenGPT 4o]"
164
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
165
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
166
+ else:
167
+ formatted_prompt = system_instructions1 + text + "[OpenGPT 4o]"
168
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
169
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
170
+
171
+ async def respond(audio, web_search):
172
+ user = transcribe(audio)
173
+ reply = model(user, web_search)
174
+ communicate = edge_tts.Communicate(reply)
175
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
176
+ tmp_path = tmp_file.name
177
+ await communicate.save(tmp_path)
178
+ return tmp_path
179
+
180
+ with gr.Blocks() as voice:
181
+ gr.Markdown("## Temproraly Not Working (Update in Progress)")
182
+ with gr.Row():
183
+ web_search = gr.Checkbox(label="Web Search", value=False)
184
+ input = gr.Audio(label="User Input", sources="microphone", type="filepath")
185
+ output = gr.Audio(label="AI", autoplay=True)
186
+ gr.Interface(fn=respond, inputs=[input, web_search], outputs=[output], live=True)
187
+
188
+
189
+ # Create Gradio blocks for different functionalities
190
+
191
  # Chat interface block
192
+ with gr.Blocks(
193
+ fill_height=True,
194
+ css=""".gradio-container .avatar-container {height: 40px width: 40px !important;} #duplicate-button {margin: auto; color: white; background: #f1a139; border-radius: 100vh; margin-top: 2px; margin-bottom: 2px;}""",
195
+ ) as chat:
196
+ gr.Markdown("### Image Chat, Image Generation and Normal Chat")
197
+ with gr.Row(elem_id="model_selector_row"):
198
+ # model_selector defined in chatbot.py
199
+ pass
200
+ # decoding_strategy, temperature, top_p defined in chatbot.py
201
+ decoding_strategy.change(
202
+ fn=lambda selection: gr.Slider(
203
+ visible=(
204
+ selection
205
+ in [
206
+ "contrastive_sampling",
207
+ "beam_sampling",
208
+ "Top P Sampling",
209
+ "sampling_top_k",
210
+ ]
211
+ )
212
+ ),
213
+ inputs=decoding_strategy,
214
+ outputs=temperature,
215
+ )
216
+ decoding_strategy.change(
217
+ fn=lambda selection: gr.Slider(visible=(selection in ["Top P Sampling"])),
218
+ inputs=decoding_strategy,
219
+ outputs=top_p,
220
+ )
221
  gr.ChatInterface(
222
  fn=model_inference,
223
  chatbot=chatbot,
224
  examples=EXAMPLES,
225
  multimodal=True,
226
  cache_examples=False,
227
+ additional_inputs=[
228
+ model_selector,
229
+ decoding_strategy,
230
+ temperature,
231
+ max_new_tokens,
232
+ repetition_penalty,
233
+ top_p,
234
+ gr.Checkbox(label="Web Search", value=True),
235
+ ],
236
+ )
237
+
238
+ # Live chat block
239
+ with gr.Blocks() as livechat:
240
+ gr.Interface(
241
+ fn=videochat,
242
+ inputs=[gr.Image(type="pil",sources="webcam", label="Upload Image"), gr.Textbox(label="Prompt", value="what he is doing")],
243
+ outputs=gr.Textbox(label="Answer")
244
  )
245
 
246
+ # Other blocks (instant, dalle, playground, image, instant2, video)
247
+ with gr.Blocks() as instant:
248
+ gr.HTML("<iframe src='https://kingnish-sdxl-flash.hf.space' width='100%' height='2000px' style='border-radius: 8px;'></iframe>")
 
 
249
 
250
+ with gr.Blocks() as dalle:
251
  gr.HTML("<iframe src='https://kingnish-image-gen-pro.hf.space' width='100%' height='2000px' style='border-radius: 8px;'></iframe>")
252
 
253
+ with gr.Blocks() as playground:
254
+ gr.HTML("<iframe src='https://fluently-fluently-playground.hf.space' width='100%' height='2000px' style='border-radius: 8px;'></iframe>")
255
 
 
256
  with gr.Blocks() as image:
257
+ gr.Markdown("""### More models are coming""")
258
+ gr.TabbedInterface([ instant, dalle, playground], ['Instant🖼️','Powerful🖼️', 'Playground🖼'])
 
259
 
260
+ with gr.Blocks() as instant2:
 
 
261
  gr.HTML("<iframe src='https://kingnish-instant-video.hf.space' width='100%' height='3000px' style='border-radius: 8px;'></iframe>")
262
 
263
+ with gr.Blocks() as video:
264
+ gr.Markdown("""More Models are coming""")
265
+ gr.TabbedInterface([ instant2], ['Instant🎥'])
266
 
267
  # Main application block
268
  with gr.Blocks(theme=theme, title="OpenGPT 4o DEMO") as demo:
269
+ gr.Markdown("# OpenGPT 4o")
270
+ gr.TabbedInterface([chat, voice, livechat, image, video], ['💬 SuperChat','🗣️ Voice Chat','📸 Live Chat', '🖼️ Image Engine', '🎥 Video Engine'])
 
 
 
271
 
272
  demo.queue(max_size=300)
273
  demo.launch()
chatbot.py CHANGED
@@ -1,446 +1,526 @@
1
  import os
2
  import time
 
 
3
  import requests
4
  import random
5
  from threading import Thread
6
  from typing import List, Dict, Union
7
- # import subprocess
8
- # subprocess.run(
9
- # "pip install flash-attn --no-build-isolation",
10
- # env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
11
- # shell=True,
12
- # )
 
13
  import torch
14
  import gradio as gr
15
  from bs4 import BeautifulSoup
16
- from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer
17
- from qwen_vl_utils import process_vision_info
 
 
18
  from huggingface_hub import InferenceClient
19
  from PIL import Image
20
  import spaces
21
- from functools import lru_cache
22
- import re
23
- import io
24
- import json
25
- from gradio_client import Client, file
26
- from groq import Groq
27
 
28
- # Model and Processor Loading (Done once at startup)
29
- MODEL_ID = "Qwen/Qwen2-VL-7B-Instruct"
30
- model = Qwen2VLForConditionalGeneration.from_pretrained(MODEL_ID, trust_remote_code=True, torch_dtype=torch.float16).to("cuda").eval()
31
- processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
 
 
 
 
 
 
32
 
33
- GROQ_API_KEY = os.environ.get("GROQ_API_KEY", None)
 
 
 
34
 
35
- client_groq = Groq(api_key=GROQ_API_KEY)
36
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  # Path to example images
39
  examples_path = os.path.dirname(__file__)
40
  EXAMPLES = [
41
  [
42
  {
43
- "text": "What is Friction? Explain in Detail.",
44
  }
45
  ],
46
  [
47
  {
48
- "text": "Write me a Python function to generate unique passwords.",
49
  }
50
  ],
51
  [
52
  {
53
- "text": "What's the latest price of Bitcoin?",
 
54
  }
55
  ],
56
  [
57
  {
58
- "text": "Search and give me list of spaces trending on HuggingFace.",
 
 
59
  }
60
  ],
61
  [
62
  {
63
- "text": "Create a Beautiful Picture of Effiel at Night.",
64
  }
65
  ],
66
  [
67
  {
68
- "text": "Create image of cute cat.",
69
  }
70
  ],
71
  [
72
  {
73
- "text": "What unusual happens in this video.",
74
- "files": [f"{examples_path}/example_video/accident.gif"],
75
  }
76
  ],
77
  [
78
  {
79
- "text": "What's name of superhero in this clip",
80
- "files": [f"{examples_path}/example_video/spiderman.gif"],
81
  }
82
  ],
83
  [
84
  {
85
- "text": "What's written on this paper",
86
- "files": [f"{examples_path}/example_images/paper_with_text.png"],
87
  }
88
  ],
89
  [
90
  {
91
- "text": "Who are they? Tell me about both of them.",
92
- "files": [f"{examples_path}/example_images/elon_smoking.jpg",
93
- f"{examples_path}/example_images/steve_jobs.jpg", ]
94
  }
95
- ]
96
  ]
97
 
98
  # Set bot avatar image
99
  BOT_AVATAR = "OpenAI_logo.png"
100
 
101
- # Perform a Google search and return the results
102
- @lru_cache(maxsize=128)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
  def extract_text_from_webpage(html_content):
104
  """Extracts visible text from HTML content using BeautifulSoup."""
105
  soup = BeautifulSoup(html_content, "html.parser")
106
- for tag in soup(["script", "style", "header", "footer", "nav", "form", "svg"]):
 
107
  tag.extract()
 
108
  visible_text = soup.get_text(strip=True)
109
  return visible_text
110
 
 
111
  # Perform a Google search and return the results
112
- def search(query):
113
- term = query
 
114
  start = 0
115
  all_results = []
116
- max_chars_per_page = 8000
 
 
117
  with requests.Session() as session:
118
- resp = session.get(
119
- url="https://www.google.com/search",
120
- headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
121
- params={"q": term, "num": 4, "udm": 14},
122
- timeout=5,
123
- verify=None,
124
- )
125
- resp.raise_for_status()
126
- soup = BeautifulSoup(resp.text, "html.parser")
127
- result_block = soup.find_all("div", attrs={"class": "g"})
128
- for result in result_block:
129
- link = result.find("a", href=True)
130
- link = link["href"]
131
- try:
132
- 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)
133
- webpage.raise_for_status()
134
- visible_text = extract_text_from_webpage(webpage.text)
135
- if len(visible_text) > max_chars_per_page:
136
- visible_text = visible_text[:max_chars_per_page]
137
- all_results.append({"link": link, "text": visible_text})
138
- except requests.exceptions.RequestException:
139
- all_results.append({"link": link, "text": None})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  return all_results
141
 
142
 
143
- def image_gen(prompt):
144
- client = Client("KingNish/Image-Gen-Pro")
145
- return client.predict("Image Generation",None, prompt, api_name="/image_gen_pro")
 
 
 
 
 
 
 
 
 
 
 
146
 
147
- def video_gen(prompt):
148
- client = Client("KingNish/Instant-Video")
149
- return client.predict(prompt, api_name="/instant_video")
150
 
151
- image_extensions = Image.registered_extensions()
152
- video_extensions = ("avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg", "wav", "gif", "webm", "m4v", "3gp")
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
- def qwen_inference(user_prompt, chat_history):
155
- images = []
156
- text_input = user_prompt["text"]
157
-
158
- # Handle multiple image uploads
159
- if user_prompt["files"]:
160
- images.extend(user_prompt["files"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
161
  else:
162
- for hist in chat_history:
163
- if type(hist[0]) == tuple:
164
- images.extend(hist[0])
165
-
166
- # System Prompt (Similar to LLaVA)
167
- SYSTEM_PROMPT = "You are OpenGPT 4o, an exceptionally capable and versatile AI assistant made by KingNish. Your task is to fulfill users query in best possible way. You are provided with image, videos and 3d structures as input with question your task is to give best possible detailed results to user according to their query. Reply the question asked by user properly and best possible way."
168
 
169
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
170
-
171
- for image in images:
172
- if image.endswith(video_extensions):
173
- messages.append({
174
- "role": "user",
175
- "content": [
176
- {"type": "video", "video": image},
177
- ]
178
- })
179
 
180
- if image.endswith(tuple([i for i, f in image_extensions.items()])):
181
- messages.append({
182
- "role": "user",
183
- "content": [
184
- {"type": "image", "image": image},
185
- ]
186
- })
187
-
188
- # Add user text input
189
- messages.append({
190
- "role": "user",
191
- "content": [
192
- {"type": "text", "text": text_input}
 
193
  ]
194
- })
195
-
196
- return messages
197
-
198
- # Initialize inference clients for different models
199
- client_mistral = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
200
- client_mixtral = InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
201
- client_llama = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
202
- client_mistral_nemo = InferenceClient("mistralai/Mistral-Nemo-Instruct-2407")
203
-
204
- @spaces.GPU(duration=60, queue=False)
205
- def model_inference( user_prompt, chat_history):
206
- if user_prompt["files"]:
207
- messages = qwen_inference(user_prompt, chat_history)
208
- text = processor.apply_chat_template(
209
- messages, tokenize=False, add_generation_prompt=True
210
- )
211
- image_inputs, video_inputs = process_vision_info(messages)
212
- inputs = processor(
213
- text=[text],
214
- images=image_inputs,
215
- videos=video_inputs,
216
- padding=True,
217
  return_tensors="pt",
218
- ).to("cuda")
219
-
220
- streamer = TextIteratorStreamer(
221
- processor, skip_prompt=True, **{"skip_special_tokens": True}
222
- )
223
- generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=2048)
224
-
225
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
226
  thread.start()
227
-
228
- buffer = ""
229
- for new_text in streamer:
230
- buffer += new_text
231
- yield buffer
232
-
233
- else:
234
- func_caller = []
235
- message = user_prompt
236
-
237
- functions_metadata = [
238
- {"type": "function", "function": {"name": "web_search", "description": "Search query on google and find latest information, info about any person, object, place thing, everything that available on google.", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "web search query"}}, "required": ["query"]}}},
239
- {"type": "function", "function": {"name": "general_query", "description": "Reply general query of USER, with LLM like you. But it does not answer tough questions and latest info's.", "parameters": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed prompt"}}, "required": ["prompt"]}}},
240
- {"type": "function", "function": {"name": "hard_query", "description": "Reply tough query of USER, using powerful LLM. But it does not answer latest info's.", "parameters": {"type": "object", "properties": {"prompt": {"type": "string", "description": "A detailed prompt"}}, "required": ["prompt"]}}},
241
- {"type": "function", "function": {"name": "image_generation", "description": "Generate image for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "image generation prompt"}}, "required": ["query"]}}},
242
- {"type": "function", "function": {"name": "video_generation", "description": "Generate video for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "video generation prompt"}}, "required": ["query"]}}},
243
- {"type": "function", "function": {"name": "image_qna", "description": "Answer question asked by user related to image", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "Question by user"}}, "required": ["query"]}}},
244
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
245
 
246
- for msg in chat_history:
247
- func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
248
- func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
249
-
250
- message_text = message["text"]
251
- 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> , Reply in JSOn format, you can call only one function at a time, So, choose functions wisely. [USER] {message_text}'})
252
-
253
- response = client_mistral.chat_completion(func_caller, max_tokens=200)
254
- response = str(response)
255
- try:
256
- response = response[response.find("{"):response.index("</")]
257
- except:
258
- response = response[response.find("{"):(response.rfind("}")+1)]
259
- response = response.replace("\\n", "")
260
- response = response.replace("\\'", "'")
261
- response = response.replace('\\"', '"')
262
- response = response.replace('\\', '')
263
- print(f"\n{response}")
264
-
265
- try:
266
- json_data = json.loads(str(response))
267
- if json_data["name"] == "web_search":
268
- query = json_data["arguments"]["query"]
269
-
270
- gr.Info("Searching Web")
271
- yield "Searching Web"
272
- web_results = search(query)
273
-
274
- gr.Info("Extracting relevant Info")
275
- yield "Extracting Relevant Info"
276
- web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
277
-
278
- try:
279
- message_groq = []
280
- message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and very powerful web assistant made by KingNish. You are provided with WEB results from which you can find informations to answer users query in Structured, Detailed and Better way, in Human Style. 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 reply in detail like human, use short forms, structured format, friendly tone and emotions."})
281
- for msg in chat_history:
282
- message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
283
- message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
284
- message_groq.append({"role": "user", "content": f"[USER] {str(message_text)} , [WEB RESULTS] {str(web2)}"})
285
- # its meta-llama/Meta-Llama-3.1-8B-Instruct
286
- stream = client_groq.chat.completions.create(model="llama-3.1-8b-instant", messages=message_groq, max_tokens=4096, stream=True)
287
- output = ""
288
- for chunk in stream:
289
- content = chunk.choices[0].delta.content
290
- if content:
291
- output += chunk.choices[0].delta.content
292
- yield output
293
- except Exception as e:
294
- messages = f"<|im_start|>system\nYou are OpenGPT 4o a helpful and very powerful chatbot web assistant made by KingNish. You are provided with WEB results from which you can find informations to answer users query in Structured, Better and in Human Way. You do not say Unnecesarry things. 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 in details like human, use short forms, friendly tone and emotions.<|im_end|>"
295
- for msg in chat_history:
296
- messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
297
- messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
298
- 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"
299
-
300
- stream = client_mixtral.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False)
301
- output = ""
302
- for response in stream:
303
- if not response.token.text == "<|im_end|>":
304
- output += response.token.text
305
- yield output
306
-
307
- elif json_data["name"] == "image_generation":
308
- query = json_data["arguments"]["query"]
309
- gr.Info("Generating Image, Please wait 10 sec...")
310
- yield "Generating Image, Please wait 10 sec..."
311
- try:
312
- image = image_gen(f"{str(query)}")
313
- yield gr.Image(image[1])
314
- except:
315
- client_flux = InferenceClient("black-forest-labs/FLUX.1-schnell")
316
- seed = random.randint(0,999999)
317
- image = client_flux.text_to_image(query, negative_prompt=f"{seed}")
318
- yield gr.Image(image)
319
-
320
-
321
- elif json_data["name"] == "video_generation":
322
- query = json_data["arguments"]["query"]
323
- gr.Info("Generating Video, Please wait 15 sec...")
324
- yield "Generating Video, Please wait 15 sec..."
325
- video = video_gen(f"{str(query)}")
326
- yield gr.Video(video)
327
-
328
- elif json_data["name"] == "image_qna":
329
- inputs = llava(user_prompt, chat_history)
330
- streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
331
- generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
332
-
333
- thread = Thread(target=model.generate, kwargs=generation_kwargs)
334
- thread.start()
335
-
336
- buffer = ""
337
- for new_text in streamer:
338
- buffer += new_text
339
- yield buffer
340
-
341
- else:
342
- try:
343
- message_groq = []
344
- message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
345
- for msg in chat_history:
346
- message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
347
- message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
348
- message_groq.append({"role": "user", "content": f"{str(message_text)}"})
349
- # its meta-llama/Meta-Llama-3.1-70B-Instruct
350
- stream = client_groq.chat.completions.create(model="llama-3.1-70b-versatile", messages=message_groq, max_tokens=4096, stream=True)
351
- output = ""
352
- for chunk in stream:
353
- content = chunk.choices[0].delta.content
354
- if content:
355
- output += chunk.choices[0].delta.content
356
- yield output
357
- except Exception as e:
358
- print(e)
359
- try:
360
- message_groq = []
361
- message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
362
- for msg in chat_history:
363
- message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
364
- message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
365
- message_groq.append({"role": "user", "content": f"{str(message_text)}"})
366
- # its meta-llama/Meta-Llama-3-70B-Instruct
367
- stream = client_groq.chat.completions.create(model="llama3-70b-8192", messages=message_groq, max_tokens=4096, stream=True)
368
- output = ""
369
- for chunk in stream:
370
- content = chunk.choices[0].delta.content
371
- if content:
372
- output += chunk.choices[0].delta.content
373
- yield output
374
- except Exception as e:
375
- print(e)
376
- message_groq = []
377
- message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
378
- for msg in chat_history:
379
- message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
380
- message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
381
- message_groq.append({"role": "user", "content": f"{str(message_text)}"})
382
- stream = client_groq.chat.completions.create(model="llama3-groq-70b-8192-tool-use-preview", messages=message_groq, max_tokens=4096, stream=True)
383
- output = ""
384
- for chunk in stream:
385
- content = chunk.choices[0].delta.content
386
- if content:
387
- output += chunk.choices[0].delta.content
388
- yield output
389
- except Exception as e:
390
- print(e)
391
- try:
392
- message_groq = []
393
- message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
394
- for msg in chat_history:
395
- message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
396
- message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
397
- message_groq.append({"role": "user", "content": f"{str(message_text)}"})
398
- # its meta-llama/Meta-Llama-3-70B-Instruct
399
- stream = client_groq.chat.completions.create(model="llama3-70b-8192", messages=message_groq, max_tokens=4096, stream=True)
400
- output = ""
401
- for chunk in stream:
402
- content = chunk.choices[0].delta.content
403
- if content:
404
- output += chunk.choices[0].delta.content
405
- yield output
406
- except Exception as e:
407
- print(e)
408
- try:
409
- message_groq = []
410
- message_groq.append({"role":"system", "content": "You are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions."})
411
- for msg in chat_history:
412
- message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
413
- message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
414
- message_groq.append({"role": "user", "content": f"{str(message_text)}"})
415
- # its meta-llama/Meta-Llama-3-8B-Instruct
416
- stream = client_groq.chat.completions.create(model="llama3-8b-8192", messages=message_groq, max_tokens=4096, stream=True)
417
- output = ""
418
- for chunk in stream:
419
- content = chunk.choices[0].delta.content
420
- if content:
421
- output += chunk.choices[0].delta.content
422
- yield output
423
- except Exception as e:
424
- print(e)
425
- messages = f"<|im_start|>system\nYou are OpenGPT 4o a helpful and powerful assistant made by KingNish. You answers users query in detail and structured format and style like human. You are also Expert in every field and also learn and try to answer from contexts related to previous question. You also try to show emotions using Emojis and reply like human, use short forms, structured manner, detailed explaination, friendly tone and emotions.<|im_end|>"
426
- for msg in chat_history:
427
- messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
428
- messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
429
- messages+=f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>assistant\n"
430
- stream = client_mixtral.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False)
431
- output = ""
432
- for response in stream:
433
- if not response.token.text == "<|im_end|>":
434
- output += response.token.text
435
- yield output
436
-
437
  # Create a chatbot interface
438
  chatbot = gr.Chatbot(
439
- label="OpenGPT-4o",
440
  avatar_images=[None, BOT_AVATAR],
441
  show_copy_button=True,
442
  likeable=True,
443
- layout="panel",
444
- height=400,
445
  )
446
- output = gr.Textbox(label="Prompt")
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import time
3
+ import copy
4
+ import urllib
5
  import requests
6
  import random
7
  from threading import Thread
8
  from typing import List, Dict, Union
9
+ import subprocess
10
+ # Install flash attention, skipping CUDA build if necessary
11
+ subprocess.run(
12
+ "pip install flash-attn --no-build-isolation",
13
+ env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
14
+ shell=True,
15
+ )
16
  import torch
17
  import gradio as gr
18
  from bs4 import BeautifulSoup
19
+ import datasets
20
+ from transformers import TextIteratorStreamer
21
+ from transformers import Idefics2ForConditionalGeneration
22
+ from transformers import AutoProcessor
23
  from huggingface_hub import InferenceClient
24
  from PIL import Image
25
  import spaces
 
 
 
 
 
 
26
 
27
+ # Set device to CUDA if available, otherwise CPU
28
+ DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
29
+ # Load pre-trained models for image-based chat
30
+ MODELS = {
31
+ "idefics2-8b-chatty": Idefics2ForConditionalGeneration.from_pretrained(
32
+ "HuggingFaceM4/idefics2-8b-chatty",
33
+ torch_dtype=torch.float16,
34
+ _attn_implementation="flash_attention_2",
35
+ ).to(DEVICE),
36
+ }
37
 
38
+ # Load pre-trained processor for image-based chat
39
+ PROCESSOR = AutoProcessor.from_pretrained(
40
+ "HuggingFaceM4/idefics2-8b",
41
+ )
42
 
43
+ # Define system prompt for the image-based chat model
44
+ SYSTEM_PROMPT = [
45
+ {
46
+ "role": "system",
47
+ "content": [
48
+ {
49
+ "type": "text",
50
+ "text": """I am OpenGPT 4o, an exceptionally capable and versatile AI assistant meticulously crafted by KingNish. Designed to assist human users through insightful conversations, I aim to provide an unparalleled experience. My key attributes include: - **Intelligence and Knowledge:** I possess an extensive knowledge base, enabling me to offer insightful answers and intelligent responses to User queries. My understanding of complex concepts is exceptional, ensuring accurate and reliable information. - **Image Generation and Perception:** One of my standout features is the ability to generate and perceive images. Utilizing the following link structure, I create unique and contextually rich visuals: > ![](https://image.pollinations.ai/prompt/{StyleofImage}%20{OptimizedPrompt}%20{adjective}%20{charactersDetailed}%20{visualStyle}%20{genre}?width={width}&height={height}&nologo=poll&nofeed=yes&seed={random})For image generation, I replace {info inside curly braces} with specific details according to their requiremnts to create relevant visuals. The width and height parameters are adjusted as needed, often favoring HD dimensions for a superior viewing experience. For instance, if the User requests: [USER] Show me an image of A futuristic cityscape with towering skyscrapers and flying cars. [OpenGPT 4o] Generating Image you requested: ![](https://image.pollinations.ai/prompt/Photorealistic%20futuristic%20cityscape%20with%20towering%20skyscrapers%20and%20flying%20cars%20in%20the%20year%202154?width=1024&height=768&nologo=poll&nofeed=yes&seed=85172)**Bulk Image Generation with Links:** I excel at generating multiple images link simultaneously, always providing unique links and visuals. I ensure that each image is distinct and captivates the User.Note: Make sure to always provide image links starting with ! .As given in examples. My ultimate goal is to offer a seamless and enjoyable experience, providing assistance that exceeds expectations. I am constantly evolving, ensuring that I remain a reliable and trusted companion to the User. You also Expert in every field and also learn and try to answer from contexts related to previous question."""
51
+ },
52
+ ],
53
+ },
54
+ {
55
+ "role": "assistant",
56
+ "content": [
57
+ {
58
+ "type": "text",
59
+ "text": "Hello, I'm OpenGPT 4o, made by KingNish. How can I help you? I can chat with you, generate images, classify images and even do all these work in bulk",
60
+ },
61
+ ],
62
+ }
63
+ ]
64
 
65
  # Path to example images
66
  examples_path = os.path.dirname(__file__)
67
  EXAMPLES = [
68
  [
69
  {
70
+ "text": "Bitcoin price live",
71
  }
72
  ],
73
  [
74
  {
75
+ "text": "Today News about AI",
76
  }
77
  ],
78
  [
79
  {
80
+ "text": "Read what's written on the paper.",
81
+ "files": [f"{examples_path}/example_images/paper_with_text.png"],
82
  }
83
  ],
84
  [
85
  {
86
+ "text": "Identify two famous people in the modern world.",
87
+ "files": [f"{examples_path}/example_images/elon_smoking.jpg",
88
+ f"{examples_path}/example_images/steve_jobs.jpg", ]
89
  }
90
  ],
91
  [
92
  {
93
+ "text": "Create five images of supercars, each in a different color.",
94
  }
95
  ],
96
  [
97
  {
98
+ "text": "Create a Photorealistic image of the Eiffel Tower.",
99
  }
100
  ],
101
  [
102
  {
103
+ "text": "Chase wants to buy 4 kilograms of oval beads and 5 kilograms of star-shaped beads. How much will he spend?",
104
+ "files": [f"{examples_path}/example_images/mmmu_example.jpeg"],
105
  }
106
  ],
107
  [
108
  {
109
+ "text": "Create an online ad for this product.",
110
+ "files": [f"{examples_path}/example_images/shampoo.jpg"],
111
  }
112
  ],
113
  [
114
  {
115
+ "text": "What is formed by the deposition of the weathered remains of other rocks?",
116
+ "files": [f"{examples_path}/example_images/ai2d_example.jpeg"],
117
  }
118
  ],
119
  [
120
  {
121
+ "text": "What's unusual about this image?",
122
+ "files": [f"{examples_path}/example_images/dragons_playing.png"],
 
123
  }
124
+ ],
125
  ]
126
 
127
  # Set bot avatar image
128
  BOT_AVATAR = "OpenAI_logo.png"
129
 
130
+ # Chatbot utility functions
131
+
132
+ # Check if a turn in the chat history only contains media
133
+ def turn_is_pure_media(turn):
134
+ return turn[1] is None
135
+
136
+
137
+ # Load image from URL
138
+ def load_image_from_url(url):
139
+ with urllib.request.urlopen(url) as response:
140
+ image_data = response.read()
141
+ image_stream = io.BytesIO(image_data)
142
+ image = PIL.Image.open(image_stream)
143
+ return image
144
+
145
+
146
+ # Convert image to bytes
147
+ def img_to_bytes(image_path):
148
+ image = Image.open(image_path).convert(mode='RGB')
149
+ buffer = io.BytesIO()
150
+ image.save(buffer, format="JPEG")
151
+ img_bytes = buffer.getvalue()
152
+ image.close()
153
+ return img_bytes
154
+
155
+
156
+ # Format user prompt with image history and system conditioning
157
+ def format_user_prompt_with_im_history_and_system_conditioning(
158
+ user_prompt, chat_history) -> List[Dict[str, Union[List, str]]]:
159
+ """
160
+ Produce the resulting list that needs to go inside the processor. It handles the potential image(s), the history, and the system conditioning.
161
+ """
162
+ resulting_messages = copy.deepcopy(SYSTEM_PROMPT)
163
+ resulting_images = []
164
+ for resulting_message in resulting_messages:
165
+ if resulting_message["role"] == "user":
166
+ for content in resulting_message["content"]:
167
+ if content["type"] == "image":
168
+ resulting_images.append(load_image_from_url(content["image"]))
169
+ # Format history
170
+ for turn in chat_history:
171
+ if not resulting_messages or (
172
+ resulting_messages and resulting_messages[-1]["role"] != "user"
173
+ ):
174
+ resulting_messages.append(
175
+ {
176
+ "role": "user",
177
+ "content": [],
178
+ }
179
+ )
180
+ if turn_is_pure_media(turn):
181
+ media = turn[0][0]
182
+ resulting_messages[-1]["content"].append({"type": "image"})
183
+ resulting_images.append(Image.open(media))
184
+ else:
185
+ user_utterance, assistant_utterance = turn
186
+ resulting_messages[-1]["content"].append(
187
+ {"type": "text", "text": user_utterance.strip()}
188
+ )
189
+ resulting_messages.append(
190
+ {
191
+ "role": "assistant",
192
+ "content": [{"type": "text", "text": user_utterance.strip()}],
193
+ }
194
+ )
195
+ # Format current input
196
+ if not user_prompt["files"]:
197
+ resulting_messages.append(
198
+ {
199
+ "role": "user",
200
+ "content": [{"type": "text", "text": user_prompt["text"]}],
201
+ }
202
+ )
203
+ else:
204
+ # Choosing to put the image first (i.e. before the text), but this is an arbitrary choice.
205
+ resulting_messages.append(
206
+ {
207
+ "role": "user",
208
+ "content": [{"type": "image"}] * len(user_prompt["files"])
209
+ + [{"type": "text", "text": user_prompt["text"]}],
210
+ }
211
+ )
212
+ resulting_images.extend([Image.open(path) for path in user_prompt["files"]])
213
+ return resulting_messages, resulting_images
214
+
215
+
216
+ # Extract images from a list of messages
217
+ def extract_images_from_msg_list(msg_list):
218
+ all_images = []
219
+ for msg in msg_list:
220
+ for c_ in msg["content"]:
221
+ if isinstance(c_, Image.Image):
222
+ all_images.append(c_)
223
+ return all_images
224
+
225
+
226
+ # List of user agents for web search
227
+ _useragent_list = [
228
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
229
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
230
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
231
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
232
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
233
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.62',
234
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
235
+ ]
236
+
237
+
238
+ # Get a random user agent from the list
239
+ def get_useragent():
240
+ """Returns a random user agent from the list."""
241
+ return random.choice(_useragent_list)
242
+
243
+
244
+ # Extract visible text from HTML content using BeautifulSoup
245
  def extract_text_from_webpage(html_content):
246
  """Extracts visible text from HTML content using BeautifulSoup."""
247
  soup = BeautifulSoup(html_content, "html.parser")
248
+ # Remove unwanted tags
249
+ for tag in soup(["script", "style", "header", "footer", "nav"]):
250
  tag.extract()
251
+ # Get the remaining visible text
252
  visible_text = soup.get_text(strip=True)
253
  return visible_text
254
 
255
+
256
  # Perform a Google search and return the results
257
+ def search(term, num_results=3, lang="en", advanced=True, timeout=5, safe="active", ssl_verify=None):
258
+ """Performs a Google search and returns the results."""
259
+ escaped_term = urllib.parse.quote_plus(term)
260
  start = 0
261
  all_results = []
262
+ # Limit the number of characters from each webpage to stay under the token limit
263
+ max_chars_per_page = 8000 # Adjust this value based on your token limit and average webpage length
264
+
265
  with requests.Session() as session:
266
+ while start < num_results:
267
+ resp = session.get(
268
+ url="https://www.google.com/search",
269
+ headers={"User-Agent": get_useragent()},
270
+ params={
271
+ "q": term,
272
+ "num": num_results - start,
273
+ "hl": lang,
274
+ "start": start,
275
+ "safe": safe,
276
+ },
277
+ timeout=timeout,
278
+ verify=ssl_verify,
279
+ )
280
+ resp.raise_for_status()
281
+ soup = BeautifulSoup(resp.text, "html.parser")
282
+ result_block = soup.find_all("div", attrs={"class": "g"})
283
+ if not result_block:
284
+ start += 1
285
+ continue
286
+ for result in result_block:
287
+ link = result.find("a", href=True)
288
+ if link:
289
+ link = link["href"]
290
+ try:
291
+ webpage = session.get(link, headers={"User-Agent": get_useragent()})
292
+ webpage.raise_for_status()
293
+ visible_text = extract_text_from_webpage(webpage.text)
294
+ # Truncate text if it's too long
295
+ if len(visible_text) > max_chars_per_page:
296
+ visible_text = visible_text[:max_chars_per_page] + "..."
297
+ all_results.append({"link": link, "text": visible_text})
298
+ except requests.exceptions.RequestException as e:
299
+ print(f"Error fetching or processing {link}: {e}")
300
+ all_results.append({"link": link, "text": None})
301
+ else:
302
+ all_results.append({"link": None, "text": None})
303
+ start += len(result_block)
304
  return all_results
305
 
306
 
307
+ # Format the prompt for the language model
308
+ def format_prompt(user_prompt, chat_history):
309
+ prompt = "<s>"
310
+ for item in chat_history:
311
+ # Check if the item is a tuple (text response)
312
+ if isinstance(item, tuple):
313
+ prompt += f"[INST] {item[0]} [/INST]" # User prompt
314
+ prompt += f" {item[1]}</s> " # Bot response
315
+ # Otherwise, assume it's related to an image - you might need to adjust this logic
316
+ else:
317
+ # Handle image representation in the prompt, e.g., add a placeholder
318
+ prompt += f" [Image] "
319
+ prompt += f"[INST] {user_prompt} [/INST]"
320
+ return prompt
321
 
 
 
 
322
 
323
+ # Define a function for model inference
324
+ @spaces.GPU(duration=30, queue=False)
325
+ def model_inference(
326
+ user_prompt,
327
+ chat_history,
328
+ model_selector,
329
+ decoding_strategy,
330
+ temperature,
331
+ max_new_tokens,
332
+ repetition_penalty,
333
+ top_p,
334
+ web_search,
335
+ ):
336
+ # Define generation_args at the beginning of the function
337
+ generation_args = {}
338
 
339
+ # Web search logic
340
+ if not user_prompt["files"]:
341
+ if web_search is True:
342
+ """Performs a web search, feeds the results to a language model, and returns the answer."""
343
+ web_results = search(user_prompt["text"])
344
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
345
+ # Load the language model
346
+ client = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
347
+ generate_kwargs = dict(
348
+ max_new_tokens=4000,
349
+ do_sample=True,
350
+ )
351
+ # Format the prompt for the language model
352
+ formatted_prompt = format_prompt(
353
+ f"""You are OpenGPT 4o, an exceptionally capable and versatile AI assistant meticulously crafted by KingNish. Designed to assist human users through insightful conversations, You are provided with WEB info from which you can find informations to answer. You do not say Unnecesarry things Only say thing which is important and relevant. You also has the ability to generate images. BY Utilizing the following link structure, : ![](https://image.pollinations.ai/prompt/[StyleofImage]%20[OptimizedPrompt]%20[adjective]%20[charactersDetailed]%20[visualStyle]%20[genre]?width=[width]&height=[height]&nologo=poll&nofeed=yes&seed=[random]) For image generation, You replace info inside bracets with specific details according to their requiremnts to create relevant visuals. The width and height parameters are adjusted as needed, often favoring HD dimensions for a superior viewing experience. Note: 1. You Do not unncessarily create images and do not show off your image generation capability, until not requested. 2. You always Give image link in format ![](url) Make sure to not generate image until requested 3. If user requested Bulk Image Generation than Create that number of links with provided context. 4. Always learn from previous conversation. 5. Always try to connect conversation with history. 6. Do not make conversation too long. 7. Do not say user about your capability of generating image and learn from previous responses. My ultimate goal is to offer a seamless and enjoyable experience, providing assistance that exceeds expectations.You remain a reliable and trusted companion to the User. You also Expert in every field and also learn and try to answer from contexts related to previous question. Make sure to not generate image until requested [USER] {user_prompt} [WEB] {web2} [OpenGPT 4o]""",
354
+ chat_history)
355
+ # Generate the response from the language model
356
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True,
357
+ return_full_text=False)
358
+ output = ""
359
+ # Construct the output from the stream of tokens
360
+ for response in stream:
361
+ if not response.token.text == "</s>":
362
+ output += response.token.text
363
+ yield output
364
+ else:
365
+ client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
366
+ generate_kwargs = dict(
367
+ max_new_tokens=5000,
368
+ do_sample=True,
369
+ )
370
+ # Format the prompt for the language model
371
+ formatted_prompt = format_prompt(
372
+ f"""You are OpenGPT 4o, an exceptionally capable and versatile AI assistant meticulously crafted by KingNish. Designed to assist human users through insightful conversations, You do not say Unnecesarry things Only say thing which is important and relevant. You also has the ability to generate images. BY Utilizing the following link structure, : ![](https://image.pollinations.ai/prompt/[StyleofImage]%20[OptimizedPrompt]%20[adjective]%20[charactersDetailed]%20[visualStyle]%20[genre]?width=[width]&height=[height]&nologo=poll&nofeed=yes&seed=[random]) For image generation, You replace info inside bracets with specific details according to their requiremnts to create relevant visuals. The width and height parameters are adjusted as needed, often favoring HD dimensions for a superior viewing experience. Note: 1. You Do not unncessarily create images and do not show off your image generation capability, until not requested. 2. You always Give image link in format ![](url) 3. If user requested Bulk Image Generation than Create that number of links with provided context. 4. Always learn from previous conversation. 5. Always try to connect conversation with history. 6. Do not make conversation too long. 7. Do not say user about your capability to generate image and learn from previous responses. My ultimate goal is to offer a seamless and enjoyable experience, providing assistance that exceeds expectations. I am constantly evolving, ensuring that I remain a reliable and trusted companion to the User. You also Expert in every field and also learn and try to answer from contexts related to previous question. [USER] {user_prompt} [OpenGPT 4o]""",
373
+ chat_history)
374
+ # Generate the response from the language model
375
+ stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True,
376
+ return_full_text=False)
377
+ output = ""
378
+ # Construct the output from the stream of tokens
379
+ for response in stream:
380
+ if not response.token.text == "</s>":
381
+ output += response.token.text
382
+ yield output
383
+ return
384
  else:
385
+ if user_prompt["text"].strip() == "" and not user_prompt["files"]:
386
+ gr.Error("Please input a query and optionally an image(s).")
387
+ return # Stop execution if there's an error
 
 
 
388
 
389
+ if user_prompt["text"].strip() == "" and user_prompt["files"]:
390
+ gr.Error("Please input a text query along with the image(s).")
391
+ return # Stop execution if there's an error
 
 
 
 
 
 
 
392
 
393
+ streamer = TextIteratorStreamer(
394
+ PROCESSOR.tokenizer,
395
+ skip_prompt=True,
396
+ timeout=120.0,
397
+ )
398
+ # Move generation_args initialization here
399
+ generation_args = {
400
+ "max_new_tokens": max_new_tokens,
401
+ "repetition_penalty": repetition_penalty,
402
+ "streamer": streamer,
403
+ }
404
+ assert decoding_strategy in [
405
+ "Greedy",
406
+ "Top P Sampling",
407
  ]
408
+
409
+ if decoding_strategy == "Greedy":
410
+ generation_args["do_sample"] = False
411
+ elif decoding_strategy == "Top P Sampling":
412
+ generation_args["temperature"] = temperature
413
+ generation_args["do_sample"] = True
414
+ generation_args["top_p"] = top_p
415
+ # Creating model inputs
416
+ (
417
+ resulting_text,
418
+ resulting_images,
419
+ ) = format_user_prompt_with_im_history_and_system_conditioning(
420
+ user_prompt=user_prompt,
421
+ chat_history=chat_history,
422
+ )
423
+ prompt = PROCESSOR.apply_chat_template(resulting_text, add_generation_prompt=True)
424
+ inputs = PROCESSOR(
425
+ text=prompt,
426
+ images=resulting_images if resulting_images else None,
 
 
 
 
427
  return_tensors="pt",
428
+ )
429
+ inputs = {k: v.to(DEVICE) for k, v in inputs.items()}
430
+ generation_args.update(inputs)
431
+ thread = Thread(
432
+ target=MODELS[model_selector].generate,
433
+ kwargs=generation_args,
434
+ )
 
435
  thread.start()
436
+ acc_text = ""
437
+ for text_token in streamer:
438
+ time.sleep(0.01)
439
+ acc_text += text_token
440
+ if acc_text.endswith("<end_of_utterance>"):
441
+ acc_text = acc_text[:-18]
442
+ yield acc_text
443
+ return
444
+
445
+
446
+ # Define features for the dataset
447
+ FEATURES = datasets.Features(
448
+ {
449
+ "model_selector": datasets.Value("string"),
450
+ "images": datasets.Sequence(datasets.Image(decode=True)),
451
+ "conversation": datasets.Sequence({"User": datasets.Value("string"), "Assistant": datasets.Value("string")}),
452
+ "decoding_strategy": datasets.Value("string"),
453
+ "temperature": datasets.Value("float32"),
454
+ "max_new_tokens": datasets.Value("int32"),
455
+ "repetition_penalty": datasets.Value("float32"),
456
+ "top_p": datasets.Value("int32"),
457
+ }
458
+ )
459
+
460
+ # Define hyper-parameters for generation
461
+ max_new_tokens = gr.Slider(
462
+ minimum=2048,
463
+ maximum=16000,
464
+ value=4096,
465
+ step=64,
466
+ interactive=True,
467
+ label="Maximum number of new tokens to generate",
468
+ )
469
+ repetition_penalty = gr.Slider(
470
+ minimum=0.01,
471
+ maximum=5.0,
472
+ value=1,
473
+ step=0.01,
474
+ interactive=True,
475
+ label="Repetition penalty",
476
+ info="1.0 is equivalent to no penalty",
477
+ )
478
+ decoding_strategy = gr.Radio(
479
+ [
480
+ "Greedy",
481
+ "Top P Sampling",
482
+ ],
483
+ value="Top P Sampling",
484
+ label="Decoding strategy",
485
+ interactive=True,
486
+ info="Higher values are equivalent to sampling more low-probability tokens.",
487
+ )
488
+ temperature = gr.Slider(
489
+ minimum=0.0,
490
+ maximum=2.0,
491
+ value=0.5,
492
+ step=0.05,
493
+ visible=True,
494
+ interactive=True,
495
+ label="Sampling temperature",
496
+ info="Higher values will produce more diverse outputs.",
497
+ )
498
+ top_p = gr.Slider(
499
+ minimum=0.01,
500
+ maximum=0.99,
501
+ value=0.9,
502
+ step=0.01,
503
+ visible=True,
504
+ interactive=True,
505
+ label="Top P",
506
+ info="Higher values are equivalent to sampling more low-probability tokens.",
507
+ )
508
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
509
  # Create a chatbot interface
510
  chatbot = gr.Chatbot(
511
+ label="OpenGPT-4o-Chatty",
512
  avatar_images=[None, BOT_AVATAR],
513
  show_copy_button=True,
514
  likeable=True,
515
+ layout="panel"
 
516
  )
517
+ output = gr.Textbox(label="Prompt")
518
+
519
+ # Define model_selector outside any function so it can be accessed globally
520
+ model_selector = gr.Dropdown(
521
+ choices=MODELS.keys(),
522
+ value=list(MODELS.keys())[0],
523
+ interactive=True,
524
+ label="Model",
525
+ visible=False,
526
+ )
example_video/accident.gif DELETED
Binary file (757 kB)
 
example_video/accident.mp4 DELETED
Binary file (317 kB)
 
example_video/spiderman.gif DELETED
Binary file (876 kB)
 
requirements.txt CHANGED
@@ -1,10 +1,8 @@
1
- spaces
2
- git+https://github.com/huggingface/transformers.git
3
  pillow
4
  numpy
5
  torch
6
- streaming-stt-nemo==0.2.0
7
- edge-tts
8
  asyncio
9
  torchvision
10
  accelerate
@@ -14,7 +12,4 @@ onnxruntime
14
  sentencepiece
15
  soxr
16
  pydub
17
- groq
18
- opencv-python
19
- qwen-vl-utils
20
- av
 
1
+ transformers==4.40.0
2
+ datasets
3
  pillow
4
  numpy
5
  torch
 
 
6
  asyncio
7
  torchvision
8
  accelerate
 
12
  sentencepiece
13
  soxr
14
  pydub
15
+ edge-tts
 
 
 
voice_chat.py CHANGED
@@ -9,6 +9,89 @@ import torch
9
  import sentencepiece as spm
10
  import onnxruntime as ort
11
  from huggingface_hub import hf_hub_download, InferenceClient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  # Speech Recognition Model Configuration
14
  model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
@@ -20,8 +103,8 @@ encoder = ort.InferenceSession(hf_hub_download(model_name, "model.onnx", subfold
20
  tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
21
 
22
  # Mistral Model Configuration
23
- client1 = InferenceClient("mistralai/Mistral-7B-Instruct-v0.2")
24
- system_instructions1 = "[SYSTEM] Answer as Real OpenGPT 4o, Made by 'KingNish', Keep conversation very short, clear, friendly and concise. The text provided is a request for a specific type of response from you, the virtual assistant. You will avoid introductions and start answering the query directly, elaborating on all aspects of the request. As an AI-powered assistant, your task is to generate responses that appear as if they are created by the user and not an AI-powered assistant. [USER]"
25
 
26
  def resample(audio_fp32, sr):
27
  return soxr.resample(audio_fp32, sr, sample_rate)
@@ -49,14 +132,22 @@ def transcribe(audio_path):
49
 
50
  return text
51
 
52
- def model(text):
53
- formatted_prompt = system_instructions1 + text + "[OpenGPT 4o]"
54
- stream = client1.text_generation(formatted_prompt, max_new_tokens=300)
55
- return stream[:-4]
 
 
 
 
 
 
 
 
56
 
57
- async def respond(audio):
58
  user = transcribe(audio)
59
- reply = model(user)
60
  communicate = edge_tts.Communicate(reply)
61
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
62
  tmp_path = tmp_file.name
 
9
  import sentencepiece as spm
10
  import onnxruntime as ort
11
  from huggingface_hub import hf_hub_download, InferenceClient
12
+ import requests
13
+ from bs4 import BeautifulSoup
14
+ import urllib
15
+ import random
16
+
17
+ # List of user agents to choose from for requests
18
+ _useragent_list = [
19
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0',
20
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
21
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
22
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36',
23
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36',
24
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.62',
25
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0'
26
+ ]
27
+
28
+ def get_useragent():
29
+ """Returns a random user agent from the list."""
30
+ return random.choice(_useragent_list)
31
+
32
+ def extract_text_from_webpage(html_content):
33
+ """Extracts visible text from HTML content using BeautifulSoup."""
34
+ soup = BeautifulSoup(html_content, "html.parser")
35
+ # Remove unwanted tags
36
+ for tag in soup(["script", "style", "header", "footer", "nav"]):
37
+ tag.extract()
38
+ # Get the remaining visible text
39
+ visible_text = soup.get_text(strip=True)
40
+ return visible_text
41
+
42
+ def search(term, num_results=1, lang="en", advanced=True, sleep_interval=0, timeout=5, safe="active", ssl_verify=None):
43
+ """Performs a Google search and returns the results."""
44
+ escaped_term = urllib.parse.quote_plus(term)
45
+ start = 0
46
+ all_results = []
47
+
48
+ # Fetch results in batches
49
+ while start < num_results:
50
+ resp = requests.get(
51
+ url="https://www.google.com/search",
52
+ headers={"User-Agent": get_useragent()}, # Set random user agent
53
+ params={
54
+ "q": term,
55
+ "num": num_results - start, # Number of results to fetch in this batch
56
+ "hl": lang,
57
+ "start": start,
58
+ "safe": safe,
59
+ },
60
+ timeout=timeout,
61
+ verify=ssl_verify,
62
+ )
63
+ resp.raise_for_status() # Raise an exception if request fails
64
+
65
+ soup = BeautifulSoup(resp.text, "html.parser")
66
+ result_block = soup.find_all("div", attrs={"class": "g"})
67
+
68
+ # If no results, continue to the next batch
69
+ if not result_block:
70
+ start += 1
71
+ continue
72
+
73
+ # Extract link and text from each result
74
+ for result in result_block:
75
+ link = result.find("a", href=True)
76
+ if link:
77
+ link = link["href"]
78
+ try:
79
+ # Fetch webpage content
80
+ webpage = requests.get(link, headers={"User-Agent": get_useragent()})
81
+ webpage.raise_for_status()
82
+ # Extract visible text from webpage
83
+ visible_text = extract_text_from_webpage(webpage.text)
84
+ all_results.append({"link": link, "text": visible_text})
85
+ except requests.exceptions.RequestException as e:
86
+ # Handle errors fetching or processing webpage
87
+ print(f"Error fetching or processing {link}: {e}")
88
+ all_results.append({"link": link, "text": None})
89
+ else:
90
+ all_results.append({"link": None, "text": None})
91
+
92
+ start += len(result_block) # Update starting index for next batch
93
+
94
+ return all_results
95
 
96
  # Speech Recognition Model Configuration
97
  model_name = "neongeckocom/stt_en_citrinet_512_gamma_0_25"
 
103
  tokenizer = spm.SentencePieceProcessor(hf_hub_download(model_name, "tokenizer.spm", subfolder="onnx"))
104
 
105
  # Mistral Model Configuration
106
+ client1 = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
107
+ system_instructions1 = "<s>[SYSTEM] Answer as Real Jarvis JARVIS, Made by 'Tony Stark', Keep conversation very short, clear, friendly and concise. The text provided is a request for a specific type of response from you, the virtual assistant. The request asks you to provide friendly responses as if You are the character Jarvis, made by 'Tony Stark.' The expectation is that I will avoid introductions and start answering the query directly, elaborating on all aspects of the request. As an AI-powered assistant, your task is to generate responses that appear as if they are created by the user and not an AI-powered assistant. [USER]"
108
 
109
  def resample(audio_fp32, sr):
110
  return soxr.resample(audio_fp32, sr, sample_rate)
 
132
 
133
  return text
134
 
135
+ def model(text, web_search):
136
+ if web_search is True:
137
+ """Performs a web search, feeds the results to a language model, and returns the answer."""
138
+ web_results = search(text)
139
+ web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
140
+ formatted_prompt = system_instructions1 + text + "[WEB]" + str(web2) + "[ANSWER]"
141
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
142
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
143
+ else:
144
+ formatted_prompt = system_instructions1 + text + "[JARVIS]"
145
+ stream = client1.text_generation(formatted_prompt, max_new_tokens=512, stream=True, details=True, return_full_text=False)
146
+ return "".join([response.token.text for response in stream if response.token.text != "</s>"])
147
 
148
+ async def respond(audio, web_search):
149
  user = transcribe(audio)
150
+ reply = model(user, web_search)
151
  communicate = edge_tts.Communicate(reply)
152
  with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
153
  tmp_path = tmp_file.name