Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -17,7 +17,7 @@ import numpy as np
|
|
17 |
from PIL import Image
|
18 |
import edge_tts
|
19 |
import trimesh
|
20 |
-
import soundfile as sf #
|
21 |
|
22 |
import supervision as sv
|
23 |
from ultralytics import YOLO as YOLODetector
|
@@ -36,13 +36,7 @@ from diffusers import StableDiffusionXLPipeline, EulerAncestralDiscreteScheduler
|
|
36 |
from diffusers import ShapEImg2ImgPipeline, ShapEPipeline
|
37 |
from diffusers.utils import export_to_ply
|
38 |
|
39 |
-
# Additional imports for the new DeepseekR1 feature and FastAPI endpoints
|
40 |
-
import openai
|
41 |
-
from fastapi import FastAPI, HTTPException
|
42 |
-
from fastapi.middleware.cors import CORSMiddleware
|
43 |
-
|
44 |
os.system('pip install backoff')
|
45 |
-
|
46 |
# Global constants and helper functions
|
47 |
|
48 |
MAX_SEED = np.iinfo(np.int32).max
|
@@ -62,72 +56,14 @@ def glb_to_data_url(glb_path: str) -> str:
|
|
62 |
b64_data = base64.b64encode(data).decode("utf-8")
|
63 |
return f"data:model/gltf-binary;base64,{b64_data}"
|
64 |
|
65 |
-
# ---------------------------
|
66 |
-
# Sambanova DeepseekR1 Clients and Chat Function
|
67 |
-
# ---------------------------
|
68 |
-
sambanova_client = openai.OpenAI(
|
69 |
-
api_key=os.environ.get("SAMBANOVA_API_KEY"),
|
70 |
-
base_url="https://api.sambanova.ai/v1",
|
71 |
-
)
|
72 |
-
sambanova_client2 = openai.OpenAI(
|
73 |
-
api_key=os.environ.get("SAMBANOVA_API_KEY_2"),
|
74 |
-
base_url="https://api.sambanova.ai/v1",
|
75 |
-
)
|
76 |
-
sambanova_client3 = openai.OpenAI(
|
77 |
-
api_key=os.environ.get("SAMBANOVA_API_KEY_3"),
|
78 |
-
base_url="https://api.sambanova.ai/v1",
|
79 |
-
)
|
80 |
-
|
81 |
-
def chat_response(prompt: str) -> str:
|
82 |
-
"""
|
83 |
-
Generate a chat response using the primary Sambanova API.
|
84 |
-
If it fails, fallback to the second, and then the third API.
|
85 |
-
"""
|
86 |
-
messages = [
|
87 |
-
{"role": "system", "content": "You are a helpful assistant."},
|
88 |
-
{"role": "user", "content": prompt},
|
89 |
-
]
|
90 |
-
errors = {}
|
91 |
-
try:
|
92 |
-
response = sambanova_client.chat.completions.create(
|
93 |
-
model="DeepSeek-R1-Distill-Llama-70B",
|
94 |
-
messages=messages,
|
95 |
-
temperature=0.1,
|
96 |
-
top_p=0.1
|
97 |
-
)
|
98 |
-
return response.choices[0].message.content
|
99 |
-
except Exception as e:
|
100 |
-
errors['client1'] = str(e)
|
101 |
-
try:
|
102 |
-
response2 = sambanova_client2.chat.completions.create(
|
103 |
-
model="DeepSeek-R1-Distill-Llama-70B",
|
104 |
-
messages=messages,
|
105 |
-
temperature=0.1,
|
106 |
-
top_p=0.1
|
107 |
-
)
|
108 |
-
return response2.choices[0].message.content
|
109 |
-
except Exception as e2:
|
110 |
-
errors['client2'] = str(e2)
|
111 |
-
try:
|
112 |
-
response3 = sambanova_client3.chat.completions.create(
|
113 |
-
model="DeepSeek-R1-Distill-Llama-70B",
|
114 |
-
messages=messages,
|
115 |
-
temperature=0.1,
|
116 |
-
top_p=0.1
|
117 |
-
)
|
118 |
-
return response3.choices[0].message.content
|
119 |
-
except Exception as e3:
|
120 |
-
errors['client3'] = str(e3)
|
121 |
-
return f"Primary error: {errors['client1']}; Second error: {errors['client2']}; Third error: {errors['client3']}"
|
122 |
-
|
123 |
-
# ---------------------------
|
124 |
# Model class for Text-to-3D Generation (ShapE)
|
125 |
-
|
126 |
class Model:
|
127 |
def __init__(self):
|
128 |
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
129 |
self.pipe = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=torch.float16)
|
130 |
self.pipe.to(self.device)
|
|
|
131 |
if torch.cuda.is_available():
|
132 |
try:
|
133 |
self.pipe.text_encoder = self.pipe.text_encoder.half()
|
@@ -136,6 +72,7 @@ class Model:
|
|
136 |
|
137 |
self.pipe_img = ShapEImg2ImgPipeline.from_pretrained("openai/shap-e-img2img", torch_dtype=torch.float16)
|
138 |
self.pipe_img.to(self.device)
|
|
|
139 |
if torch.cuda.is_available():
|
140 |
text_encoder_img = getattr(self.pipe_img, "text_encoder", None)
|
141 |
if text_encoder_img is not None:
|
@@ -143,6 +80,7 @@ class Model:
|
|
143 |
|
144 |
def to_glb(self, ply_path: str) -> str:
|
145 |
mesh = trimesh.load(ply_path)
|
|
|
146 |
rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
|
147 |
mesh.apply_transform(rot)
|
148 |
rot = trimesh.transformations.rotation_matrix(np.pi, [0, 1, 0])
|
@@ -177,9 +115,8 @@ class Model:
|
|
177 |
export_to_ply(images[0], ply_path.name)
|
178 |
return self.to_glb(ply_path.name)
|
179 |
|
180 |
-
# ---------------------------
|
181 |
# New Tools for Web Functionality using DuckDuckGo and smolagents
|
182 |
-
|
183 |
from typing import Any, Optional
|
184 |
from smolagents.tools import Tool
|
185 |
import duckduckgo_search
|
@@ -231,21 +168,27 @@ class VisitWebpageTool(Tool):
|
|
231 |
"You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
|
232 |
) from e
|
233 |
try:
|
|
|
234 |
response = requests.get(url, timeout=20)
|
235 |
-
response.raise_for_status()
|
|
|
|
|
236 |
markdown_content = markdownify(response.text).strip()
|
|
|
|
|
237 |
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
|
|
|
238 |
return truncate_content(markdown_content, 10000)
|
|
|
239 |
except requests.exceptions.Timeout:
|
240 |
return "The request timed out. Please try again later or check the URL."
|
241 |
except RequestException as e:
|
242 |
return f"Error fetching the webpage: {str(e)}"
|
243 |
except Exception as e:
|
244 |
return f"An unexpected error occurred: {str(e)}"
|
245 |
-
|
246 |
-
# ---------------------------
|
247 |
# rAgent Reasoning using Llama mode OpenAI
|
248 |
-
|
249 |
from openai import OpenAI
|
250 |
|
251 |
ACCESS_TOKEN = os.getenv("HF_TOKEN")
|
@@ -270,6 +213,7 @@ def ragent_reasoning(prompt: str, history: list[dict], max_tokens: int = 2048, t
|
|
270 |
Uses the Llama mode OpenAI model to perform a structured reasoning chain.
|
271 |
"""
|
272 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
|
|
273 |
for msg in history:
|
274 |
if msg.get("role") == "user":
|
275 |
messages.append({"role": "user", "content": msg["content"]})
|
@@ -293,10 +237,12 @@ def ragent_reasoning(prompt: str, history: list[dict], max_tokens: int = 2048, t
|
|
293 |
# ------------------------------------------------------------------------------
|
294 |
# New Phi-4 Multimodal Feature (Image & Audio)
|
295 |
# ------------------------------------------------------------------------------
|
|
|
296 |
phi4_user_prompt = '<|user|>'
|
297 |
phi4_assistant_prompt = '<|assistant|>'
|
298 |
phi4_prompt_suffix = '<|end|>'
|
299 |
|
|
|
300 |
phi4_model_path = "microsoft/Phi-4-multimodal-instruct"
|
301 |
phi4_processor = AutoProcessor.from_pretrained(phi4_model_path, trust_remote_code=True)
|
302 |
phi4_model = AutoModelForCausalLM.from_pretrained(
|
@@ -330,9 +276,9 @@ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
|
330 |
|
331 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
332 |
|
333 |
-
# ---------------------------
|
334 |
# Load Models and Pipelines for Chat, Image, and Multimodal Processing
|
335 |
-
#
|
|
|
336 |
model_id = "prithivMLmods/FastThink-0.5B-Tiny"
|
337 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
338 |
model = AutoModelForCausalLM.from_pretrained(
|
@@ -342,11 +288,13 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
342 |
)
|
343 |
model.eval()
|
344 |
|
|
|
345 |
TTS_VOICES = [
|
346 |
-
"en-US-JennyNeural",
|
347 |
-
"en-US-GuyNeural",
|
348 |
]
|
349 |
|
|
|
350 |
MODEL_ID = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
351 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
352 |
model_m = Qwen2VLForConditionalGeneration.from_pretrained(
|
@@ -355,15 +303,20 @@ model_m = Qwen2VLForConditionalGeneration.from_pretrained(
|
|
355 |
torch_dtype=torch.float16
|
356 |
).to("cuda").eval()
|
357 |
|
|
|
|
|
358 |
async def text_to_speech(text: str, voice: str, output_file="output.mp3"):
|
359 |
"""Convert text to speech using Edge TTS and save as MP3"""
|
360 |
communicate = edge_tts.Communicate(text, voice)
|
361 |
await communicate.save(output_file)
|
362 |
return output_file
|
363 |
|
|
|
|
|
364 |
def clean_chat_history(chat_history):
|
365 |
"""
|
366 |
Filter out any chat entries whose "content" is not a string.
|
|
|
367 |
"""
|
368 |
cleaned = []
|
369 |
for msg in chat_history:
|
@@ -371,14 +324,14 @@ def clean_chat_history(chat_history):
|
|
371 |
cleaned.append(msg)
|
372 |
return cleaned
|
373 |
|
374 |
-
# ---------------------------
|
375 |
# Stable Diffusion XL Pipeline for Image Generation
|
376 |
-
#
|
377 |
-
|
|
|
378 |
MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
|
379 |
USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
|
380 |
ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
|
381 |
-
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1"))
|
382 |
|
383 |
sd_pipe = StableDiffusionXLPipeline.from_pretrained(
|
384 |
MODEL_ID_SD,
|
@@ -436,6 +389,7 @@ def generate_image_fn(
|
|
436 |
options["use_resolution_binning"] = True
|
437 |
|
438 |
images = []
|
|
|
439 |
for i in range(0, num_images, BATCH_SIZE):
|
440 |
batch_options = options.copy()
|
441 |
batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
|
@@ -450,9 +404,8 @@ def generate_image_fn(
|
|
450 |
image_paths = [save_image(img) for img in images]
|
451 |
return image_paths, seed
|
452 |
|
453 |
-
# ---------------------------
|
454 |
# Text-to-3D Generation using the ShapE Pipeline
|
455 |
-
|
456 |
@spaces.GPU(duration=120, enable_queue=True)
|
457 |
def generate_3d_fn(
|
458 |
prompt: str,
|
@@ -470,9 +423,7 @@ def generate_3d_fn(
|
|
470 |
glb_path = model3d.run_text(prompt, seed=seed, guidance_scale=guidance_scale, num_steps=num_steps)
|
471 |
return glb_path, seed
|
472 |
|
473 |
-
# ---------------------------
|
474 |
# YOLO Object Detection Setup
|
475 |
-
# ---------------------------
|
476 |
YOLO_MODEL_REPO = "strangerzonehf/Flux-Ultimate-LoRA-Collection"
|
477 |
YOLO_CHECKPOINT_NAME = "images/demo.pt"
|
478 |
yolo_model_path = hf_hub_download(repo_id=YOLO_MODEL_REPO, filename=YOLO_CHECKPOINT_NAME)
|
@@ -492,9 +443,8 @@ def detect_objects(image: np.ndarray):
|
|
492 |
|
493 |
return Image.fromarray(annotated_image)
|
494 |
|
495 |
-
#
|
496 |
-
|
497 |
-
# ---------------------------
|
498 |
@spaces.GPU
|
499 |
def generate(
|
500 |
input_dict: dict,
|
@@ -513,8 +463,7 @@ def generate(
|
|
513 |
- "@web": triggers a web search or webpage visit.
|
514 |
- "@rAgent": initiates a reasoning chain using Llama mode.
|
515 |
- "@yolo": triggers object detection using YOLO.
|
516 |
-
- "@phi4": triggers multimodal (image/audio) processing using the Phi-4 model
|
517 |
-
- **"@deepseekr1": queries the Sambanova DeepSeek-R1 model with fallback APIs.**
|
518 |
"""
|
519 |
text = input_dict["text"]
|
520 |
files = input_dict.get("files", [])
|
@@ -530,6 +479,7 @@ def generate(
|
|
530 |
num_steps=64,
|
531 |
randomize_seed=True,
|
532 |
)
|
|
|
533 |
static_folder = os.path.join(os.getcwd(), "static")
|
534 |
if not os.path.exists(static_folder):
|
535 |
os.makedirs(static_folder)
|
@@ -563,6 +513,7 @@ def generate(
|
|
563 |
# --- Web Search/Visit branch ---
|
564 |
if text.strip().lower().startswith("@web"):
|
565 |
web_command = text[len("@web"):].strip()
|
|
|
566 |
if web_command.lower().startswith("visit"):
|
567 |
url = web_command[len("visit"):].strip()
|
568 |
yield "π Visiting webpage..."
|
@@ -570,6 +521,7 @@ def generate(
|
|
570 |
content = visitor.forward(url)
|
571 |
yield content
|
572 |
else:
|
|
|
573 |
query = web_command
|
574 |
yield "𧀠Performing a web search ..."
|
575 |
searcher = DuckDuckGoSearchTool()
|
@@ -581,24 +533,18 @@ def generate(
|
|
581 |
if text.strip().lower().startswith("@ragent"):
|
582 |
prompt = text[len("@ragent"):].strip()
|
583 |
yield "π Initiating reasoning chain using Llama mode..."
|
|
|
584 |
for partial in ragent_reasoning(prompt, clean_chat_history(chat_history)):
|
585 |
yield partial
|
586 |
return
|
587 |
|
588 |
-
# --- DeepSeek-R1 branch ---
|
589 |
-
if text.strip().lower().startswith("@deepseekr1"):
|
590 |
-
prompt = text[len("@deepseekr1"):].strip()
|
591 |
-
# Directly return the response from the API
|
592 |
-
response = chat_response(prompt)
|
593 |
-
yield response
|
594 |
-
return
|
595 |
-
|
596 |
# --- YOLO Object Detection branch ---
|
597 |
if text.strip().lower().startswith("@yolo"):
|
598 |
yield "π Running object detection with YOLO..."
|
599 |
if not files or len(files) == 0:
|
600 |
yield "Error: Please attach an image for YOLO object detection."
|
601 |
return
|
|
|
602 |
input_file = files[0]
|
603 |
try:
|
604 |
if isinstance(input_file, str):
|
@@ -622,12 +568,15 @@ def generate(
|
|
622 |
if not question:
|
623 |
yield "Error: Please provide a question after @phi4."
|
624 |
return
|
|
|
625 |
input_file = files[0]
|
626 |
try:
|
|
|
627 |
if isinstance(input_file, Image.Image):
|
628 |
input_type = "Image"
|
629 |
file_for_phi4 = input_file
|
630 |
else:
|
|
|
631 |
try:
|
632 |
file_for_phi4 = Image.open(input_file)
|
633 |
input_type = "Image"
|
@@ -649,8 +598,10 @@ def generate(
|
|
649 |
yield "Invalid file type for @phi4 multimodal processing."
|
650 |
return
|
651 |
|
|
|
652 |
streamer = TextIteratorStreamer(phi4_processor, skip_prompt=True, skip_special_tokens=True)
|
653 |
|
|
|
654 |
generation_kwargs = {
|
655 |
**inputs,
|
656 |
"streamer": streamer,
|
@@ -658,14 +609,16 @@ def generate(
|
|
658 |
"num_logits_to_keep": 0,
|
659 |
}
|
660 |
|
|
|
661 |
thread = Thread(target=phi4_model.generate, kwargs=generation_kwargs)
|
662 |
thread.start()
|
663 |
|
|
|
664 |
buffer = ""
|
665 |
yield "π€ Processing with Phi-4..."
|
666 |
for new_text in streamer:
|
667 |
buffer += new_text
|
668 |
-
time.sleep(0.01)
|
669 |
yield buffer
|
670 |
return
|
671 |
|
@@ -745,9 +698,8 @@ def generate(
|
|
745 |
output_file = asyncio.run(text_to_speech(final_response, voice))
|
746 |
yield gr.Audio(output_file, autoplay=True)
|
747 |
|
748 |
-
# ---------------------------
|
749 |
# Gradio Chat Interface Setup and Launch
|
750 |
-
|
751 |
demo = gr.ChatInterface(
|
752 |
fn=generate,
|
753 |
additional_inputs=[
|
@@ -779,39 +731,18 @@ demo = gr.ChatInterface(
|
|
779 |
label="Query Input",
|
780 |
file_types=["image", "audio"],
|
781 |
file_count="multiple",
|
782 |
-
placeholder="β @tts1, @tts2, @image, @3d, @phi4 [image, audio], @rAgent, @web, @yolo,
|
783 |
),
|
784 |
stop_btn="Stop Generation",
|
785 |
multimodal=True,
|
786 |
)
|
787 |
|
|
|
788 |
if not os.path.exists("static"):
|
789 |
os.makedirs("static")
|
790 |
|
791 |
from fastapi.staticfiles import StaticFiles
|
792 |
demo.app.mount("/static", StaticFiles(directory="static"), name="static")
|
793 |
|
794 |
-
# ---------------------------
|
795 |
-
# Mount FastAPI Middleware and Endpoint for DeepSeek-R1
|
796 |
-
# ---------------------------
|
797 |
-
demo.app.add_middleware(
|
798 |
-
CORSMiddleware,
|
799 |
-
allow_origins=["*"],
|
800 |
-
allow_credentials=True,
|
801 |
-
allow_methods=["*"],
|
802 |
-
allow_headers=["*"],
|
803 |
-
)
|
804 |
-
|
805 |
-
@demo.app.post("/chat")
|
806 |
-
async def chat_endpoint(prompt: str):
|
807 |
-
"""
|
808 |
-
FastAPI endpoint for the Sambanova DeepSeek-R1 chatbot.
|
809 |
-
"""
|
810 |
-
result = chat_response(prompt)
|
811 |
-
return {"response": result}
|
812 |
-
|
813 |
-
# ---------------------------
|
814 |
-
# Main Execution
|
815 |
-
# ---------------------------
|
816 |
if __name__ == "__main__":
|
817 |
demo.queue(max_size=20).launch(share=True)
|
|
|
17 |
from PIL import Image
|
18 |
import edge_tts
|
19 |
import trimesh
|
20 |
+
import soundfile as sf # New import for audio file reading
|
21 |
|
22 |
import supervision as sv
|
23 |
from ultralytics import YOLO as YOLODetector
|
|
|
36 |
from diffusers import ShapEImg2ImgPipeline, ShapEPipeline
|
37 |
from diffusers.utils import export_to_ply
|
38 |
|
|
|
|
|
|
|
|
|
|
|
39 |
os.system('pip install backoff')
|
|
|
40 |
# Global constants and helper functions
|
41 |
|
42 |
MAX_SEED = np.iinfo(np.int32).max
|
|
|
56 |
b64_data = base64.b64encode(data).decode("utf-8")
|
57 |
return f"data:model/gltf-binary;base64,{b64_data}"
|
58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
# Model class for Text-to-3D Generation (ShapE)
|
60 |
+
|
61 |
class Model:
|
62 |
def __init__(self):
|
63 |
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
64 |
self.pipe = ShapEPipeline.from_pretrained("openai/shap-e", torch_dtype=torch.float16)
|
65 |
self.pipe.to(self.device)
|
66 |
+
# Ensure the text encoder is in half precision to avoid dtype mismatches.
|
67 |
if torch.cuda.is_available():
|
68 |
try:
|
69 |
self.pipe.text_encoder = self.pipe.text_encoder.half()
|
|
|
72 |
|
73 |
self.pipe_img = ShapEImg2ImgPipeline.from_pretrained("openai/shap-e-img2img", torch_dtype=torch.float16)
|
74 |
self.pipe_img.to(self.device)
|
75 |
+
# Use getattr with a default value to avoid AttributeError if text_encoder is missing.
|
76 |
if torch.cuda.is_available():
|
77 |
text_encoder_img = getattr(self.pipe_img, "text_encoder", None)
|
78 |
if text_encoder_img is not None:
|
|
|
80 |
|
81 |
def to_glb(self, ply_path: str) -> str:
|
82 |
mesh = trimesh.load(ply_path)
|
83 |
+
# Rotate the mesh for proper orientation
|
84 |
rot = trimesh.transformations.rotation_matrix(-np.pi / 2, [1, 0, 0])
|
85 |
mesh.apply_transform(rot)
|
86 |
rot = trimesh.transformations.rotation_matrix(np.pi, [0, 1, 0])
|
|
|
115 |
export_to_ply(images[0], ply_path.name)
|
116 |
return self.to_glb(ply_path.name)
|
117 |
|
|
|
118 |
# New Tools for Web Functionality using DuckDuckGo and smolagents
|
119 |
+
|
120 |
from typing import Any, Optional
|
121 |
from smolagents.tools import Tool
|
122 |
import duckduckgo_search
|
|
|
168 |
"You must install packages `markdownify` and `requests` to run this tool: for instance run `pip install markdownify requests`."
|
169 |
) from e
|
170 |
try:
|
171 |
+
# Send a GET request to the URL with a 20-second timeout
|
172 |
response = requests.get(url, timeout=20)
|
173 |
+
response.raise_for_status() # Raise an exception for bad status codes
|
174 |
+
|
175 |
+
# Convert the HTML content to Markdown
|
176 |
markdown_content = markdownify(response.text).strip()
|
177 |
+
|
178 |
+
# Remove multiple line breaks
|
179 |
markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)
|
180 |
+
|
181 |
return truncate_content(markdown_content, 10000)
|
182 |
+
|
183 |
except requests.exceptions.Timeout:
|
184 |
return "The request timed out. Please try again later or check the URL."
|
185 |
except RequestException as e:
|
186 |
return f"Error fetching the webpage: {str(e)}"
|
187 |
except Exception as e:
|
188 |
return f"An unexpected error occurred: {str(e)}"
|
189 |
+
|
|
|
190 |
# rAgent Reasoning using Llama mode OpenAI
|
191 |
+
|
192 |
from openai import OpenAI
|
193 |
|
194 |
ACCESS_TOKEN = os.getenv("HF_TOKEN")
|
|
|
213 |
Uses the Llama mode OpenAI model to perform a structured reasoning chain.
|
214 |
"""
|
215 |
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
216 |
+
# Incorporate conversation history (if any)
|
217 |
for msg in history:
|
218 |
if msg.get("role") == "user":
|
219 |
messages.append({"role": "user", "content": msg["content"]})
|
|
|
237 |
# ------------------------------------------------------------------------------
|
238 |
# New Phi-4 Multimodal Feature (Image & Audio)
|
239 |
# ------------------------------------------------------------------------------
|
240 |
+
# Define prompt structure for Phi-4
|
241 |
phi4_user_prompt = '<|user|>'
|
242 |
phi4_assistant_prompt = '<|assistant|>'
|
243 |
phi4_prompt_suffix = '<|end|>'
|
244 |
|
245 |
+
# Load Phi-4 multimodal model and processor using unique variable names
|
246 |
phi4_model_path = "microsoft/Phi-4-multimodal-instruct"
|
247 |
phi4_processor = AutoProcessor.from_pretrained(phi4_model_path, trust_remote_code=True)
|
248 |
phi4_model = AutoModelForCausalLM.from_pretrained(
|
|
|
276 |
|
277 |
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
278 |
|
|
|
279 |
# Load Models and Pipelines for Chat, Image, and Multimodal Processing
|
280 |
+
# Load the text-only model and tokenizer (for pure text chat)
|
281 |
+
|
282 |
model_id = "prithivMLmods/FastThink-0.5B-Tiny"
|
283 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
284 |
model = AutoModelForCausalLM.from_pretrained(
|
|
|
288 |
)
|
289 |
model.eval()
|
290 |
|
291 |
+
# Voices for text-to-speech
|
292 |
TTS_VOICES = [
|
293 |
+
"en-US-JennyNeural", # @tts1
|
294 |
+
"en-US-GuyNeural", # @tts2
|
295 |
]
|
296 |
|
297 |
+
# Load multimodal processor and model (e.g. for OCR and image processing)
|
298 |
MODEL_ID = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
299 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
300 |
model_m = Qwen2VLForConditionalGeneration.from_pretrained(
|
|
|
303 |
torch_dtype=torch.float16
|
304 |
).to("cuda").eval()
|
305 |
|
306 |
+
# Asynchronous text-to-speech
|
307 |
+
|
308 |
async def text_to_speech(text: str, voice: str, output_file="output.mp3"):
|
309 |
"""Convert text to speech using Edge TTS and save as MP3"""
|
310 |
communicate = edge_tts.Communicate(text, voice)
|
311 |
await communicate.save(output_file)
|
312 |
return output_file
|
313 |
|
314 |
+
# Utility function to clean conversation history
|
315 |
+
|
316 |
def clean_chat_history(chat_history):
|
317 |
"""
|
318 |
Filter out any chat entries whose "content" is not a string.
|
319 |
+
This helps prevent errors when concatenating previous messages.
|
320 |
"""
|
321 |
cleaned = []
|
322 |
for msg in chat_history:
|
|
|
324 |
cleaned.append(msg)
|
325 |
return cleaned
|
326 |
|
|
|
327 |
# Stable Diffusion XL Pipeline for Image Generation
|
328 |
+
# Model In Use : SG161222/RealVisXL_V5.0_Lightning
|
329 |
+
|
330 |
+
MODEL_ID_SD = os.getenv("MODEL_VAL_PATH") # SDXL Model repository path via env variable
|
331 |
MAX_IMAGE_SIZE = int(os.getenv("MAX_IMAGE_SIZE", "4096"))
|
332 |
USE_TORCH_COMPILE = os.getenv("USE_TORCH_COMPILE", "0") == "1"
|
333 |
ENABLE_CPU_OFFLOAD = os.getenv("ENABLE_CPU_OFFLOAD", "0") == "1"
|
334 |
+
BATCH_SIZE = int(os.getenv("BATCH_SIZE", "1")) # For batched image generation
|
335 |
|
336 |
sd_pipe = StableDiffusionXLPipeline.from_pretrained(
|
337 |
MODEL_ID_SD,
|
|
|
389 |
options["use_resolution_binning"] = True
|
390 |
|
391 |
images = []
|
392 |
+
# Process in batches
|
393 |
for i in range(0, num_images, BATCH_SIZE):
|
394 |
batch_options = options.copy()
|
395 |
batch_options["prompt"] = options["prompt"][i:i+BATCH_SIZE]
|
|
|
404 |
image_paths = [save_image(img) for img in images]
|
405 |
return image_paths, seed
|
406 |
|
|
|
407 |
# Text-to-3D Generation using the ShapE Pipeline
|
408 |
+
|
409 |
@spaces.GPU(duration=120, enable_queue=True)
|
410 |
def generate_3d_fn(
|
411 |
prompt: str,
|
|
|
423 |
glb_path = model3d.run_text(prompt, seed=seed, guidance_scale=guidance_scale, num_steps=num_steps)
|
424 |
return glb_path, seed
|
425 |
|
|
|
426 |
# YOLO Object Detection Setup
|
|
|
427 |
YOLO_MODEL_REPO = "strangerzonehf/Flux-Ultimate-LoRA-Collection"
|
428 |
YOLO_CHECKPOINT_NAME = "images/demo.pt"
|
429 |
yolo_model_path = hf_hub_download(repo_id=YOLO_MODEL_REPO, filename=YOLO_CHECKPOINT_NAME)
|
|
|
443 |
|
444 |
return Image.fromarray(annotated_image)
|
445 |
|
446 |
+
# Chat Generation Function with support for @tts, @image, @3d, @web, @rAgent, @yolo, and now @phi4 commands
|
447 |
+
|
|
|
448 |
@spaces.GPU
|
449 |
def generate(
|
450 |
input_dict: dict,
|
|
|
463 |
- "@web": triggers a web search or webpage visit.
|
464 |
- "@rAgent": initiates a reasoning chain using Llama mode.
|
465 |
- "@yolo": triggers object detection using YOLO.
|
466 |
+
- **"@phi4": triggers multimodal (image/audio) processing using the Phi-4 model.**
|
|
|
467 |
"""
|
468 |
text = input_dict["text"]
|
469 |
files = input_dict.get("files", [])
|
|
|
479 |
num_steps=64,
|
480 |
randomize_seed=True,
|
481 |
)
|
482 |
+
# Copy the GLB file to a static folder.
|
483 |
static_folder = os.path.join(os.getcwd(), "static")
|
484 |
if not os.path.exists(static_folder):
|
485 |
os.makedirs(static_folder)
|
|
|
513 |
# --- Web Search/Visit branch ---
|
514 |
if text.strip().lower().startswith("@web"):
|
515 |
web_command = text[len("@web"):].strip()
|
516 |
+
# If the command starts with "visit", then treat the rest as a URL
|
517 |
if web_command.lower().startswith("visit"):
|
518 |
url = web_command[len("visit"):].strip()
|
519 |
yield "π Visiting webpage..."
|
|
|
521 |
content = visitor.forward(url)
|
522 |
yield content
|
523 |
else:
|
524 |
+
# Otherwise, treat the rest as a search query.
|
525 |
query = web_command
|
526 |
yield "𧀠Performing a web search ..."
|
527 |
searcher = DuckDuckGoSearchTool()
|
|
|
533 |
if text.strip().lower().startswith("@ragent"):
|
534 |
prompt = text[len("@ragent"):].strip()
|
535 |
yield "π Initiating reasoning chain using Llama mode..."
|
536 |
+
# Pass the current chat history (cleaned) to help inform the chain.
|
537 |
for partial in ragent_reasoning(prompt, clean_chat_history(chat_history)):
|
538 |
yield partial
|
539 |
return
|
540 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
541 |
# --- YOLO Object Detection branch ---
|
542 |
if text.strip().lower().startswith("@yolo"):
|
543 |
yield "π Running object detection with YOLO..."
|
544 |
if not files or len(files) == 0:
|
545 |
yield "Error: Please attach an image for YOLO object detection."
|
546 |
return
|
547 |
+
# Use the first attached image
|
548 |
input_file = files[0]
|
549 |
try:
|
550 |
if isinstance(input_file, str):
|
|
|
568 |
if not question:
|
569 |
yield "Error: Please provide a question after @phi4."
|
570 |
return
|
571 |
+
# Determine input type (Image or Audio) from the first file
|
572 |
input_file = files[0]
|
573 |
try:
|
574 |
+
# If file is already a PIL Image, treat as image
|
575 |
if isinstance(input_file, Image.Image):
|
576 |
input_type = "Image"
|
577 |
file_for_phi4 = input_file
|
578 |
else:
|
579 |
+
# Try opening as image; if it fails, assume audio
|
580 |
try:
|
581 |
file_for_phi4 = Image.open(input_file)
|
582 |
input_type = "Image"
|
|
|
598 |
yield "Invalid file type for @phi4 multimodal processing."
|
599 |
return
|
600 |
|
601 |
+
# Initialize the streamer
|
602 |
streamer = TextIteratorStreamer(phi4_processor, skip_prompt=True, skip_special_tokens=True)
|
603 |
|
604 |
+
# Prepare generation kwargs
|
605 |
generation_kwargs = {
|
606 |
**inputs,
|
607 |
"streamer": streamer,
|
|
|
609 |
"num_logits_to_keep": 0,
|
610 |
}
|
611 |
|
612 |
+
# Start generation in a separate thread
|
613 |
thread = Thread(target=phi4_model.generate, kwargs=generation_kwargs)
|
614 |
thread.start()
|
615 |
|
616 |
+
# Stream the response
|
617 |
buffer = ""
|
618 |
yield "π€ Processing with Phi-4..."
|
619 |
for new_text in streamer:
|
620 |
buffer += new_text
|
621 |
+
time.sleep(0.01) # Small delay to simulate real-time streaming
|
622 |
yield buffer
|
623 |
return
|
624 |
|
|
|
698 |
output_file = asyncio.run(text_to_speech(final_response, voice))
|
699 |
yield gr.Audio(output_file, autoplay=True)
|
700 |
|
|
|
701 |
# Gradio Chat Interface Setup and Launch
|
702 |
+
|
703 |
demo = gr.ChatInterface(
|
704 |
fn=generate,
|
705 |
additional_inputs=[
|
|
|
731 |
label="Query Input",
|
732 |
file_types=["image", "audio"],
|
733 |
file_count="multiple",
|
734 |
+
placeholder="β @tts1, @tts2, @image, @3d, @phi4 [image, audio], @rAgent, @web, @yolo, default [plain text]"
|
735 |
),
|
736 |
stop_btn="Stop Generation",
|
737 |
multimodal=True,
|
738 |
)
|
739 |
|
740 |
+
# Ensure the static folder exists
|
741 |
if not os.path.exists("static"):
|
742 |
os.makedirs("static")
|
743 |
|
744 |
from fastapi.staticfiles import StaticFiles
|
745 |
demo.app.mount("/static", StaticFiles(directory="static"), name="static")
|
746 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
747 |
if __name__ == "__main__":
|
748 |
demo.queue(max_size=20).launch(share=True)
|