Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
@@ -6,11 +6,71 @@ import torch
|
|
6 |
import edge_tts
|
7 |
import asyncio
|
8 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
9 |
-
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
|
10 |
from transformers.image_utils import load_image
|
11 |
-
from huggingface_hub import InferenceClient
|
12 |
import time
|
13 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
# Load text-only model and tokenizer
|
15 |
model_id = "prithivMLmods/FastThink-0.5B-Tiny"
|
16 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
@@ -21,6 +81,11 @@ model = AutoModelForCausalLM.from_pretrained(
|
|
21 |
)
|
22 |
model.eval()
|
23 |
|
|
|
|
|
|
|
|
|
|
|
24 |
# Load multimodal (OCR) model and processor
|
25 |
MODEL_ID = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
26 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
@@ -30,20 +95,6 @@ model_m = Qwen2VLForConditionalGeneration.from_pretrained(
|
|
30 |
torch_dtype=torch.float16
|
31 |
).to("cuda").eval()
|
32 |
|
33 |
-
TTS_VOICES = [
|
34 |
-
"en-US-JennyNeural", # @tts1
|
35 |
-
"en-US-GuyNeural", # @tts2
|
36 |
-
]
|
37 |
-
|
38 |
-
def image_gen(prompt):
|
39 |
-
"""Generate image using API"""
|
40 |
-
try:
|
41 |
-
client = InferenceClient("prithivMLmods/STABLE-HAMSTER")
|
42 |
-
return client.text_to_image(prompt)
|
43 |
-
except:
|
44 |
-
client_flux = InferenceClient("black-forest-labs/FLUX.1-schnell")
|
45 |
-
return client_flux.text_to_image(prompt)
|
46 |
-
|
47 |
async def text_to_speech(text: str, voice: str, output_file="output.mp3"):
|
48 |
"""Convert text to speech using Edge TTS and save as MP3"""
|
49 |
communicate = edge_tts.Communicate(text, voice)
|
@@ -51,85 +102,168 @@ async def text_to_speech(text: str, voice: str, output_file="output.mp3"):
|
|
51 |
return output_file
|
52 |
|
53 |
def clean_chat_history(chat_history):
|
54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
55 |
|
56 |
@spaces.GPU
|
57 |
-
def generate(
|
58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
text = input_dict["text"]
|
60 |
files = input_dict.get("files", [])
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
else:
|
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 |
demo = gr.ChatInterface(
|
117 |
fn=generate,
|
118 |
additional_inputs=[
|
119 |
-
gr.Slider(label="Max new tokens", minimum=1, maximum=
|
120 |
gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6),
|
121 |
-
gr.Slider(label="Top-p", minimum=0.05, maximum=1.0, step=0.05, value=0.9),
|
122 |
gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50),
|
123 |
gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2),
|
124 |
],
|
125 |
examples=[
|
126 |
-
["@tts1 Who is Nikola Tesla?"],
|
127 |
[{"text": "Extract JSON from the image", "files": ["examples/document.jpg"]}],
|
128 |
-
["
|
129 |
-
["A train travels 60 kilometers per hour.
|
|
|
|
|
|
|
130 |
],
|
131 |
cache_examples=False,
|
132 |
-
|
|
|
|
|
133 |
fill_height=True,
|
134 |
textbox=gr.MultimodalTextbox(label="Query Input", file_types=["image"], file_count="multiple"),
|
135 |
stop_btn="Stop Generation",
|
|
|
6 |
import edge_tts
|
7 |
import asyncio
|
8 |
from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
|
9 |
+
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, TextIteratorStreamer
|
10 |
from transformers.image_utils import load_image
|
|
|
11 |
import time
|
12 |
|
13 |
+
# =============================================================================
|
14 |
+
# New imports and helper classes for image generation
|
15 |
+
# =============================================================================
|
16 |
+
try:
|
17 |
+
# We use Hugging Face’s InferenceClient as a generic image-generation API client.
|
18 |
+
from huggingface_hub import InferenceClient as HFInferenceClient
|
19 |
+
except ImportError:
|
20 |
+
HFInferenceClient = None
|
21 |
+
|
22 |
+
# A simple wrapper client for our primary image-generation space.
|
23 |
+
class Client:
|
24 |
+
def __init__(self, repo_id):
|
25 |
+
self.repo_id = repo_id
|
26 |
+
if HFInferenceClient is not None:
|
27 |
+
self.client = HFInferenceClient(repo_id)
|
28 |
+
else:
|
29 |
+
self.client = None
|
30 |
+
|
31 |
+
def predict(self, task, arg2, prompt, api_name):
|
32 |
+
if self.client is not None:
|
33 |
+
# Here we assume that calling the client with the prompt returns an image.
|
34 |
+
# (Depending on your API, you might need to adjust parameters.)
|
35 |
+
return self.client(prompt)
|
36 |
+
else:
|
37 |
+
raise Exception("HFInferenceClient not available")
|
38 |
+
|
39 |
+
def image_gen(prompt):
|
40 |
+
"""
|
41 |
+
Uses the STABLE-HAMSTER space to generate an image based on the prompt.
|
42 |
+
"""
|
43 |
+
client = Client("prithivMLmods/STABLE-HAMSTER")
|
44 |
+
return client.predict("Image Generation", None, prompt, api_name="/stable_hamster")
|
45 |
+
|
46 |
+
# =============================================================================
|
47 |
+
# Original Code (with modifications below)
|
48 |
+
# =============================================================================
|
49 |
+
|
50 |
+
DESCRIPTION = """
|
51 |
+
# QwQ Edge 💬
|
52 |
+
"""
|
53 |
+
|
54 |
+
css = '''
|
55 |
+
h1 {
|
56 |
+
text-align: center;
|
57 |
+
display: block;
|
58 |
+
}
|
59 |
+
|
60 |
+
#duplicate-button {
|
61 |
+
margin: auto;
|
62 |
+
color: #fff;
|
63 |
+
background: #1565c0;
|
64 |
+
border-radius: 100vh;
|
65 |
+
}
|
66 |
+
'''
|
67 |
+
|
68 |
+
MAX_MAX_NEW_TOKENS = 2048
|
69 |
+
DEFAULT_MAX_NEW_TOKENS = 1024
|
70 |
+
MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "4096"))
|
71 |
+
|
72 |
+
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
|
73 |
+
|
74 |
# Load text-only model and tokenizer
|
75 |
model_id = "prithivMLmods/FastThink-0.5B-Tiny"
|
76 |
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
|
|
81 |
)
|
82 |
model.eval()
|
83 |
|
84 |
+
TTS_VOICES = [
|
85 |
+
"en-US-JennyNeural", # @tts1
|
86 |
+
"en-US-GuyNeural", # @tts2
|
87 |
+
]
|
88 |
+
|
89 |
# Load multimodal (OCR) model and processor
|
90 |
MODEL_ID = "prithivMLmods/Qwen2-VL-OCR-2B-Instruct"
|
91 |
processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
|
|
|
95 |
torch_dtype=torch.float16
|
96 |
).to("cuda").eval()
|
97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
98 |
async def text_to_speech(text: str, voice: str, output_file="output.mp3"):
|
99 |
"""Convert text to speech using Edge TTS and save as MP3"""
|
100 |
communicate = edge_tts.Communicate(text, voice)
|
|
|
102 |
return output_file
|
103 |
|
104 |
def clean_chat_history(chat_history):
|
105 |
+
"""
|
106 |
+
Filter out any chat entries whose "content" is not a string.
|
107 |
+
This helps prevent errors when concatenating previous messages.
|
108 |
+
"""
|
109 |
+
cleaned = []
|
110 |
+
for msg in chat_history:
|
111 |
+
if isinstance(msg, dict) and isinstance(msg.get("content"), str):
|
112 |
+
cleaned.append(msg)
|
113 |
+
return cleaned
|
114 |
|
115 |
@spaces.GPU
|
116 |
+
def generate(
|
117 |
+
input_dict: dict,
|
118 |
+
chat_history: list[dict],
|
119 |
+
max_new_tokens: int = 1024,
|
120 |
+
temperature: float = 0.6,
|
121 |
+
top_p: float = 0.9,
|
122 |
+
top_k: int = 50,
|
123 |
+
repetition_penalty: float = 1.2,
|
124 |
+
):
|
125 |
+
"""
|
126 |
+
Generates chatbot responses with support for multimodal input, TTS, and now image generation.
|
127 |
+
If the query starts with an @tts command (e.g. "@tts1"), previous chat history is cleared.
|
128 |
+
If the query starts with an @image command, the image generation branch is used.
|
129 |
+
"""
|
130 |
text = input_dict["text"]
|
131 |
files = input_dict.get("files", [])
|
132 |
+
|
133 |
+
# -------------------------------------------------------------------------
|
134 |
+
# NEW: Check for image generation command (@image)
|
135 |
+
# -------------------------------------------------------------------------
|
136 |
+
image_prefix = "@image"
|
137 |
+
if text.strip().lower().startswith(image_prefix):
|
138 |
+
# Remove the prefix and any extra whitespace
|
139 |
+
query = text[len(image_prefix):].strip()
|
140 |
+
yield "Generating Image, Please wait 10 sec..."
|
141 |
+
try:
|
142 |
+
image = image_gen(query)
|
143 |
+
# If the API returns a tuple (as in the snippet) use the second element;
|
144 |
+
# otherwise assume it returns an image directly.
|
145 |
+
if isinstance(image, (list, tuple)) and len(image) > 1:
|
146 |
+
yield gr.Image(image[1])
|
147 |
+
else:
|
148 |
+
yield gr.Image(image)
|
149 |
+
except Exception as e:
|
150 |
+
yield "Error in primary image generation, trying fallback..."
|
151 |
+
try:
|
152 |
+
# Use the fallback image generation client.
|
153 |
+
if HFInferenceClient is not None:
|
154 |
+
client_flux = HFInferenceClient("black-forest-labs/FLUX.1-schnell")
|
155 |
+
image = client_flux.text_to_image(query)
|
156 |
+
yield gr.Image(image)
|
157 |
+
else:
|
158 |
+
yield "Fallback client not available."
|
159 |
+
except Exception as fallback_error:
|
160 |
+
yield f"Error in image generation: {str(fallback_error)}"
|
161 |
+
return # End execution after processing the image-generation request.
|
162 |
+
|
163 |
+
# -------------------------------------------------------------------------
|
164 |
+
# Continue with the original processing (image files, TTS, or text conversation)
|
165 |
+
# -------------------------------------------------------------------------
|
166 |
+
if len(files) > 1:
|
167 |
+
images = [load_image(image) for image in files]
|
168 |
+
elif len(files) == 1:
|
169 |
+
images = [load_image(files[0])]
|
170 |
else:
|
171 |
+
images = []
|
172 |
+
|
173 |
+
tts_prefix = "@tts"
|
174 |
+
is_tts = any(text.strip().lower().startswith(f"{tts_prefix}{i}") for i in range(1, 3))
|
175 |
+
voice_index = next((i for i in range(1, 3) if text.strip().lower().startswith(f"{tts_prefix}{i}")), None)
|
176 |
+
|
177 |
+
if is_tts and voice_index:
|
178 |
+
voice = TTS_VOICES[voice_index - 1]
|
179 |
+
text = text.replace(f"{tts_prefix}{voice_index}", "").strip()
|
180 |
+
# Clear any previous chat history to avoid concatenation issues
|
181 |
+
conversation = [{"role": "user", "content": text}]
|
182 |
+
else:
|
183 |
+
voice = None
|
184 |
+
text = text.replace(tts_prefix, "").strip()
|
185 |
+
conversation = clean_chat_history(chat_history)
|
186 |
+
conversation.append({"role": "user", "content": text})
|
187 |
+
|
188 |
+
if images:
|
189 |
+
# Multimodal branch using the OCR model
|
190 |
+
messages = [{
|
191 |
+
"role": "user",
|
192 |
+
"content": [
|
193 |
+
*[{"type": "image", "image": image} for image in images],
|
194 |
+
{"type": "text", "text": text},
|
195 |
+
]
|
196 |
+
}]
|
197 |
+
prompt = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
198 |
+
inputs = processor(text=[prompt], images=images, return_tensors="pt", padding=True).to("cuda")
|
199 |
+
streamer = TextIteratorStreamer(processor, skip_prompt=True, skip_special_tokens=True)
|
200 |
+
generation_kwargs = {**inputs, "streamer": streamer, "max_new_tokens": max_new_tokens}
|
201 |
+
thread = Thread(target=model_m.generate, kwargs=generation_kwargs)
|
202 |
+
thread.start()
|
203 |
+
|
204 |
+
buffer = ""
|
205 |
+
yield "Thinking..."
|
206 |
+
for new_text in streamer:
|
207 |
+
buffer += new_text
|
208 |
+
buffer = buffer.replace("<|im_end|>", "")
|
209 |
+
time.sleep(0.01)
|
210 |
+
yield buffer
|
211 |
+
else:
|
212 |
+
# Text-only branch using the text model
|
213 |
+
input_ids = tokenizer.apply_chat_template(conversation, add_generation_prompt=True, return_tensors="pt")
|
214 |
+
if input_ids.shape[1] > MAX_INPUT_TOKEN_LENGTH:
|
215 |
+
input_ids = input_ids[:, -MAX_INPUT_TOKEN_LENGTH:]
|
216 |
+
gr.Warning(f"Trimmed input from conversation as it was longer than {MAX_INPUT_TOKEN_LENGTH} tokens.")
|
217 |
+
input_ids = input_ids.to(model.device)
|
218 |
+
streamer = TextIteratorStreamer(tokenizer, timeout=20.0, skip_prompt=True, skip_special_tokens=True)
|
219 |
+
generation_kwargs = {
|
220 |
+
"input_ids": input_ids,
|
221 |
+
"streamer": streamer,
|
222 |
+
"max_new_tokens": max_new_tokens,
|
223 |
+
"do_sample": True,
|
224 |
+
"top_p": top_p,
|
225 |
+
"top_k": top_k,
|
226 |
+
"temperature": temperature,
|
227 |
+
"num_beams": 1,
|
228 |
+
"repetition_penalty": repetition_penalty,
|
229 |
+
}
|
230 |
+
t = Thread(target=model.generate, kwargs=generation_kwargs)
|
231 |
+
t.start()
|
232 |
+
|
233 |
+
outputs = []
|
234 |
+
for new_text in streamer:
|
235 |
+
outputs.append(new_text)
|
236 |
+
yield "".join(outputs)
|
237 |
+
|
238 |
+
final_response = "".join(outputs)
|
239 |
+
yield final_response
|
240 |
+
|
241 |
+
if is_tts and voice:
|
242 |
+
output_file = asyncio.run(text_to_speech(final_response, voice))
|
243 |
+
yield gr.Audio(output_file, autoplay=True)
|
244 |
|
245 |
demo = gr.ChatInterface(
|
246 |
fn=generate,
|
247 |
additional_inputs=[
|
248 |
+
gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS),
|
249 |
gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6),
|
250 |
+
gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9),
|
251 |
gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50),
|
252 |
gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2),
|
253 |
],
|
254 |
examples=[
|
255 |
+
["@tts1 Who is Nikola Tesla, and why did he die?"],
|
256 |
[{"text": "Extract JSON from the image", "files": ["examples/document.jpg"]}],
|
257 |
+
[{"text": "summarize the letter", "files": ["examples/1.png"]}],
|
258 |
+
["A train travels 60 kilometers per hour. If it travels for 5 hours, how far will it travel in total?"],
|
259 |
+
["Write a Python function to check if a number is prime."],
|
260 |
+
["@tts2 What causes rainbows to form?"],
|
261 |
+
["@image A beautiful sunset over a mountain range"],
|
262 |
],
|
263 |
cache_examples=False,
|
264 |
+
type="messages",
|
265 |
+
description=DESCRIPTION,
|
266 |
+
css=css,
|
267 |
fill_height=True,
|
268 |
textbox=gr.MultimodalTextbox(label="Query Input", file_types=["image"], file_count="multiple"),
|
269 |
stop_btn="Stop Generation",
|