Spaces:
Running
on
Zero
Running
on
Zero
File size: 25,148 Bytes
fabaa3c 5865d17 fabaa3c 5865d17 fabaa3c 0fe027e 1001ad3 ad296b8 fabaa3c 5865d17 1001ad3 ad296b8 33f38e0 ce441ed cd4b4e1 ce441ed fabaa3c ad296b8 fabaa3c ad296b8 fabaa3c ad296b8 fabaa3c 7b9282e ad296b8 7b9282e 8ee9612 50e18af 8ee9612 fabaa3c 50e18af fabaa3c ad296b8 fabaa3c ad296b8 fabaa3c ad296b8 fabaa3c ad296b8 fabaa3c ad296b8 fabaa3c dd7d8ba c5ecf2c fabaa3c dd7d8ba fabaa3c 1c3458d fabaa3c dd7d8ba 5b3a290 0e92f07 ad296b8 0e92f07 fabaa3c 1ecfe13 ad296b8 1c3458d ad296b8 1c3458d ad296b8 fabaa3c 5c541d7 ad296b8 5e7db30 ad296b8 700b80f 5865d17 ad296b8 5865d17 fabaa3c ad296b8 5865d17 ad296b8 5865d17 ad296b8 0c929f6 ad296b8 5d14293 ad296b8 5865d17 1001ad3 fabaa3c 1001ad3 eb2581c fabaa3c ad296b8 c0a2253 ad296b8 166c44c ad296b8 b7d0207 ad296b8 de058f9 ad296b8 de058f9 15584ad ad296b8 f23ca18 ad296b8 de058f9 ad296b8 15584ad ad296b8 15584ad ad296b8 397998c ad296b8 397998c ad296b8 fabaa3c 1001ad3 fabaa3c ad296b8 fabaa3c 1001ad3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 |
import os
import time
import requests
import random
from threading import Thread
from typing import List, Dict, Union
# import subprocess
# subprocess.run(
# "pip install flash-attn --no-build-isolation",
# env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"},
# shell=True,
# )
import torch
import gradio as gr
from bs4 import BeautifulSoup
from transformers import LlavaProcessor, LlavaForConditionalGeneration,
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer
from qwen_vl_utils import process_vision_info
from huggingface_hub import InferenceClient
from PIL import Image
import spaces
from functools import lru_cache
import cv2
import re
import io
import json
from gradio_client import Client, file
from groq import Groq
# Model and Processor Loading (Done once at startup)
MODEL_ID = "Qwen/Qwen2-VL-2B-Instruct"
model = Qwen2VLForConditionalGeneration.from_pretrained(MODEL_ID, trust_remote_code=True, torch_dtype=torch.float16).to("cuda").eval()
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
GROQ_API_KEY = os.environ.get("GROQ_API_KEY", None)
client_groq = Groq(api_key=GROQ_API_KEY)
def sample_frames(video_file) :
try:
video = cv2.VideoCapture(video_file)
total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
num_frames = 12
interval = total_frames // num_frames
frames = []
for i in range(total_frames):
ret, frame = video.read()
pil_img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
if not ret:
continue
if i % interval == 0:
frames.append(pil_img)
video.release()
return frames
except:
frames=[]
return frames
# Path to example images
examples_path = os.path.dirname(__file__)
EXAMPLES = [
[
{
"text": "What is Friction? Explain in Detail.",
}
],
[
{
"text": "Write me a Python function to generate unique passwords.",
}
],
[
{
"text": "What's the latest price of Bitcoin?",
}
],
[
{
"text": "Search and give me list of spaces trending on HuggingFace.",
}
],
[
{
"text": "Create a Beautiful Picture of Effiel at Night.",
}
],
[
{
"text": "Create image of cute cat.",
}
],
[
{
"text": "What unusual happens in this video.",
"files": [f"{examples_path}/example_video/accident.gif"],
}
],
[
{
"text": "What's name of superhero in this clip",
"files": [f"{examples_path}/example_video/spiderman.gif"],
}
],
[
{
"text": "What's written on this paper",
"files": [f"{examples_path}/example_images/paper_with_text.png"],
}
],
[
{
"text": "Who are they? Tell me about both of them",
"files": [f"{examples_path}/example_images/elon_smoking.jpg",
f"{examples_path}/example_images/steve_jobs.jpg", ]
}
]
]
# Set bot avatar image
BOT_AVATAR = "OpenAI_logo.png"
# Perform a Google search and return the results
@lru_cache(maxsize=128)
def extract_text_from_webpage(html_content):
"""Extracts visible text from HTML content using BeautifulSoup."""
soup = BeautifulSoup(html_content, "html.parser")
for tag in soup(["script", "style", "header", "footer", "nav", "form", "svg"]):
tag.extract()
visible_text = soup.get_text(strip=True)
return visible_text
# Perform a Google search and return the results
def search(query):
term = query
start = 0
all_results = []
max_chars_per_page = 8000
with requests.Session() as session:
resp = session.get(
url="https://www.google.com/search",
headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/111.0"},
params={"q": term, "num": 4, "udm": 14},
timeout=5,
verify=None,
)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, "html.parser")
result_block = soup.find_all("div", attrs={"class": "g"})
for result in result_block:
link = result.find("a", href=True)
link = link["href"]
try:
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)
webpage.raise_for_status()
visible_text = extract_text_from_webpage(webpage.text)
if len(visible_text) > max_chars_per_page:
visible_text = visible_text[:max_chars_per_page]
all_results.append({"link": link, "text": visible_text})
except requests.exceptions.RequestException:
all_results.append({"link": link, "text": None})
return all_results
def image_gen(prompt):
client = Client("KingNish/Image-Gen-Pro")
return client.predict("Image Generation",None, prompt, api_name="/image_gen_pro")
def video_gen(prompt):
client = Client("KingNish/Instant-Video")
return client.predict(prompt, api_name="/instant_video")
image_extensions = Image.registered_extensions()
video_extensions = ("avi", "mp4", "mov", "mkv", "flv", "wmv", "mjpeg", "wav", "gif", "webm", "m4v", "3gp")
def qwen_inference(user_prompt, chat_history):
images = []
text_input = user_prompt["text"]
# Handle multiple image uploads
if user_prompt["files"]:
images.extend(user_prompt["files"])
else:
for hist in chat_history:
if type(hist[0]) == tuple:
images.extend(hist[0])
# System Prompt (Similar to LLaVA)
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."
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
for image in images:
if image.endswith(video_extensions):
messages.append({
"role": "user",
"content": [
{"type": "video", "video": image},
]
})
if image.endswith(tuple([i for i, f in image_extensions.items()])):
messages.append({
"role": "user",
"content": [
{"type": "image", "image": image},
]
})
# Add user text input
messages.append({
"role": "user",
"content": [
{"type": "text", "text": text_input}
]
})
text = processor.apply_chat_template(
messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
text=[text],
images=image_inputs,
videos=video_inputs,
padding=True,
return_tensors="pt",
).to("cuda")
streamer = TextIteratorStreamer(
processor, skip_prompt=True, **{"skip_special_tokens": True}
)
generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=2048)
return generation_kwargs
# Initialize inference clients for different models
client_mistral = InferenceClient("mistralai/Mistral-7B-Instruct-v0.3")
client_mixtral = InferenceClient("NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO")
client_llama = InferenceClient("meta-llama/Meta-Llama-3-8B-Instruct")
client_mistral_nemo = InferenceClient("mistralai/Mistral-Nemo-Instruct-2407")
@spaces.GPU(duration=60, queue=False)
def model_inference( user_prompt, chat_history):
if user_prompt["files"]:
generation_kwargs = qwen_inference(user_prompt, chat_history)
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
buffer = ""
for new_text in streamer:
buffer += new_text
yield buffer
else:
func_caller = []
message = user_prompt
functions_metadata = [
{"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"]}}},
{"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"]}}},
{"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"]}}},
{"type": "function", "function": {"name": "image_generation", "description": "Generate image for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "image generation prompt"}}, "required": ["query"]}}},
{"type": "function", "function": {"name": "video_generation", "description": "Generate video for user", "parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "video generation prompt"}}, "required": ["query"]}}},
{"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"]}}},
]
for msg in chat_history:
func_caller.append({"role": "user", "content": f"{str(msg[0])}"})
func_caller.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_text = message["text"]
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}'})
response = client_mistral.chat_completion(func_caller, max_tokens=200)
response = str(response)
try:
response = response[response.find("{"):response.index("</")]
except:
response = response[response.find("{"):(response.rfind("}")+1)]
response = response.replace("\\n", "")
response = response.replace("\\'", "'")
response = response.replace('\\"', '"')
response = response.replace('\\', '')
print(f"\n{response}")
try:
json_data = json.loads(str(response))
if json_data["name"] == "web_search":
query = json_data["arguments"]["query"]
gr.Info("Searching Web")
yield "Searching Web"
web_results = search(query)
gr.Info("Extracting relevant Info")
yield "Extracting Relevant Info"
web2 = ' '.join([f"Link: {res['link']}\nText: {res['text']}\n\n" for res in web_results])
try:
message_groq = []
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."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"[USER] {str(message_text)} , [WEB RESULTS] {str(web2)}"})
# its meta-llama/Meta-Llama-3.1-8B-Instruct
stream = client_groq.chat.completions.create(model="llama-3.1-8b-instant", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
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|>"
for msg in chat_history:
messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
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"
stream = client_mixtral.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False)
output = ""
for response in stream:
if not response.token.text == "<|im_end|>":
output += response.token.text
yield output
elif json_data["name"] == "image_generation":
query = json_data["arguments"]["query"]
gr.Info("Generating Image, Please wait 10 sec...")
yield "Generating Image, Please wait 10 sec..."
try:
image = image_gen(f"{str(query)}")
yield gr.Image(image[1])
except:
client_sd3 = InferenceClient("stabilityai/stable-diffusion-3-medium-diffusers")
seed = random.randint(0,999999)
image = client_sd3.text_to_image(query, negative_prompt=f"{seed}")
yield gr.Image(image)
elif json_data["name"] == "video_generation":
query = json_data["arguments"]["query"]
gr.Info("Generating Video, Please wait 15 sec...")
yield "Generating Video, Please wait 15 sec..."
video = video_gen(f"{str(query)}")
yield gr.Video(video)
elif json_data["name"] == "image_qna":
inputs = llava(user_prompt, chat_history)
streamer = TextIteratorStreamer(processor, skip_prompt=True, **{"skip_special_tokens": True})
generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
thread = Thread(target=model.generate, kwargs=generation_kwargs)
thread.start()
buffer = ""
for new_text in streamer:
buffer += new_text
yield buffer
else:
try:
message_groq = []
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."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
# its meta-llama/Meta-Llama-3.1-70B-Instruct
stream = client_groq.chat.completions.create(model="llama-3.1-70b-versatile", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
try:
message_groq = []
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."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
# its meta-llama/Meta-Llama-3-70B-Instruct
stream = client_groq.chat.completions.create(model="llama3-70b-8192", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
message_groq = []
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."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
stream = client_groq.chat.completions.create(model="llama3-groq-70b-8192-tool-use-preview", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
try:
message_groq = []
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."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
# its meta-llama/Meta-Llama-3-70B-Instruct
stream = client_groq.chat.completions.create(model="llama3-70b-8192", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
try:
message_groq = []
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."})
for msg in chat_history:
message_groq.append({"role": "user", "content": f"{str(msg[0])}"})
message_groq.append({"role": "assistant", "content": f"{str(msg[1])}"})
message_groq.append({"role": "user", "content": f"{str(message_text)}"})
# its meta-llama/Meta-Llama-3-8B-Instruct
stream = client_groq.chat.completions.create(model="llama3-8b-8192", messages=message_groq, max_tokens=4096, stream=True)
output = ""
for chunk in stream:
content = chunk.choices[0].delta.content
if content:
output += chunk.choices[0].delta.content
yield output
except Exception as e:
print(e)
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|>"
for msg in chat_history:
messages += f"\n<|im_start|>user\n{str(msg[0])}<|im_end|>"
messages += f"\n<|im_start|>assistant\n{str(msg[1])}<|im_end|>"
messages+=f"\n<|im_start|>user\n{message_text}<|im_end|>\n<|im_start|>assistant\n"
stream = client_mixtral.text_generation(messages, max_new_tokens=4000, do_sample=True, stream=True, details=True, return_full_text=False)
output = ""
for response in stream:
if not response.token.text == "<|im_end|>":
output += response.token.text
yield output
# Create a chatbot interface
chatbot = gr.Chatbot(
label="OpenGPT-4o",
avatar_images=[None, BOT_AVATAR],
show_copy_button=True,
likeable=True,
layout="panel",
height=400,
)
output = gr.Textbox(label="Prompt") |