Update app.py
Browse files
app.py
CHANGED
|
@@ -1,455 +1 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import numpy as np
|
| 3 |
-
import torch
|
| 4 |
-
import gradio as gr
|
| 5 |
-
import spaces
|
| 6 |
-
|
| 7 |
-
from transformers import Qwen3OmniMoeForConditionalGeneration, Qwen3OmniMoeProcessor
|
| 8 |
-
from qwen_omni_utils import process_mm_info
|
| 9 |
-
|
| 10 |
-
# =========================================================
|
| 11 |
-
# Patch لتجاوز مشكلة lm_head في Qwen3OmniMoeTalker*
|
| 12 |
-
# =========================================================
|
| 13 |
-
|
| 14 |
-
def _patched_mark_tied_weights_as_initialized(self):
|
| 15 |
-
"""
|
| 16 |
-
بعض إصدارات transformers + Qwen3-Omni تسبب خطأ:
|
| 17 |
-
Qwen3OmniMoeTalkerForConditionalGeneration has no attribute `lm_head`
|
| 18 |
-
عند محاولة ربط الـ tied weights.
|
| 19 |
-
هذا الـ patch يجعل هذه الخطوة no-op (لا تقوم بشيء)،
|
| 20 |
-
وهو آمن للاستنتاج (inference) في معظم الحالات.
|
| 21 |
-
"""
|
| 22 |
-
return
|
| 23 |
-
|
| 24 |
-
# تطبيق الـ patch قبل أي استدعاء لـ from_pretrained
|
| 25 |
-
if hasattr(Qwen3OmniMoeForConditionalGeneration, "mark_tied_weights_as_initialized"):
|
| 26 |
-
Qwen3OmniMoeForConditionalGeneration.mark_tied_weights_as_initialized = (
|
| 27 |
-
_patched_mark_tied_weights_as_initialized
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
# =========================================================
|
| 31 |
-
# إعدادات عامة
|
| 32 |
-
# =========================================================
|
| 33 |
-
|
| 34 |
-
MODEL_PATH = os.getenv("MODEL_PATH", "Qwen/Qwen3-Omni-30B-A3B-Instruct")
|
| 35 |
-
USE_AUDIO_IN_VIDEO = True # استخدام الصوت داخل الفيديو إذا وجد
|
| 36 |
-
|
| 37 |
-
VOICE_CHOICES = ["Ethan", "Chelsie", "Aiden"]
|
| 38 |
-
DEFAULT_VOICE = "Ethan"
|
| 39 |
-
|
| 40 |
-
# سنحمّل النموذج كسولياً (عند أول استدعاء فقط)
|
| 41 |
-
model = None
|
| 42 |
-
processor = None
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
def load_model():
|
| 46 |
-
"""
|
| 47 |
-
تحميل Qwen3-Omni والمعالج عند أول استدعاء فقط.
|
| 48 |
-
- نستخدم attn_implementation="eager" لتفادي الحاجة لـ flash-attn.
|
| 49 |
-
- لا نستخدم device_map="auto" لتفادي مشاكل توزيع الذاكرة على ZeroGPU.
|
| 50 |
-
"""
|
| 51 |
-
global model, processor
|
| 52 |
-
|
| 53 |
-
if model is not None and processor is not None:
|
| 54 |
-
return
|
| 55 |
-
|
| 56 |
-
print(f"[ZeroGPU] Loading model from: {MODEL_PATH}")
|
| 57 |
-
|
| 58 |
-
# اختيار نوع البيانات والجهاز
|
| 59 |
-
if torch.cuda.is_available():
|
| 60 |
-
torch_dtype = torch.bfloat16
|
| 61 |
-
device = "cuda"
|
| 62 |
-
else:
|
| 63 |
-
torch_dtype = torch.float32
|
| 64 |
-
device = "cpu"
|
| 65 |
-
|
| 66 |
-
# تحميل النموذج (بدون flash_attention_2)
|
| 67 |
-
local_model = Qwen3OmniMoeForConditionalGeneration.from_pretrained(
|
| 68 |
-
MODEL_PATH,
|
| 69 |
-
torch_dtype=torch_dtype,
|
| 70 |
-
attn_implementation="eager", # آمن على ZeroGPU بدون flash-attn
|
| 71 |
-
)
|
| 72 |
-
local_model.to(device)
|
| 73 |
-
|
| 74 |
-
local_processor = Qwen3OmniMoeProcessor.from_pretrained(MODEL_PATH)
|
| 75 |
-
|
| 76 |
-
model = local_model
|
| 77 |
-
processor = local_processor
|
| 78 |
-
print(f"[ZeroGPU] Model loaded on {device} with dtype {torch_dtype}.")
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
def build_messages_from_history(
|
| 82 |
-
history,
|
| 83 |
-
system_prompt,
|
| 84 |
-
user_text,
|
| 85 |
-
image,
|
| 86 |
-
audio_path,
|
| 87 |
-
video_path,
|
| 88 |
-
):
|
| 89 |
-
"""
|
| 90 |
-
تحويل تاريخ الدردشة + المدخل الحالي إلى conversation بالـ format
|
| 91 |
-
المطلوب من Qwen3-Omni.
|
| 92 |
-
history: list of [user_text, assistant_text]
|
| 93 |
-
"""
|
| 94 |
-
messages = []
|
| 95 |
-
|
| 96 |
-
if system_prompt:
|
| 97 |
-
messages.append(
|
| 98 |
-
{
|
| 99 |
-
"role": "system",
|
| 100 |
-
"content": [{"type": "text", "text": system_prompt}],
|
| 101 |
-
}
|
| 102 |
-
)
|
| 103 |
-
|
| 104 |
-
# تاريخ المحادثة
|
| 105 |
-
for user_msg, assistant_msg in history:
|
| 106 |
-
if user_msg:
|
| 107 |
-
messages.append(
|
| 108 |
-
{
|
| 109 |
-
"role": "user",
|
| 110 |
-
"content": [{"type": "text", "text": user_msg}],
|
| 111 |
-
}
|
| 112 |
-
)
|
| 113 |
-
if assistant_msg:
|
| 114 |
-
messages.append(
|
| 115 |
-
{
|
| 116 |
-
"role": "assistant",
|
| 117 |
-
"content": [{"type": "text", "text": assistant_msg}],
|
| 118 |
-
}
|
| 119 |
-
)
|
| 120 |
-
|
| 121 |
-
# محتوى رسالة المستخدم الحالية
|
| 122 |
-
user_content = []
|
| 123 |
-
|
| 124 |
-
if image is not None:
|
| 125 |
-
user_content.append({"type": "image", "image": image})
|
| 126 |
-
|
| 127 |
-
if audio_path is not None and audio_path != "":
|
| 128 |
-
user_content.append({"type": "audio", "audio": audio_path})
|
| 129 |
-
|
| 130 |
-
if video_path is not None and video_path != "":
|
| 131 |
-
user_content.append({"type": "video", "video": video_path})
|
| 132 |
-
|
| 133 |
-
if user_text and user_text.strip():
|
| 134 |
-
user_content.append({"type": "text", "text": user_text.strip()})
|
| 135 |
-
|
| 136 |
-
if user_content:
|
| 137 |
-
messages.append(
|
| 138 |
-
{
|
| 139 |
-
"role": "user",
|
| 140 |
-
"content": user_content,
|
| 141 |
-
}
|
| 142 |
-
)
|
| 143 |
-
|
| 144 |
-
return messages
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
# =========================================================
|
| 148 |
-
# دالة الاستدلال (تعمل على ZeroGPU)
|
| 149 |
-
# =========================================================
|
| 150 |
-
|
| 151 |
-
@spaces.GPU(duration=120)
|
| 152 |
-
def qwen3_omni_inference(
|
| 153 |
-
history,
|
| 154 |
-
user_text,
|
| 155 |
-
image,
|
| 156 |
-
audio_path,
|
| 157 |
-
video_path,
|
| 158 |
-
system_prompt,
|
| 159 |
-
return_audio,
|
| 160 |
-
speaker,
|
| 161 |
-
temperature,
|
| 162 |
-
top_p,
|
| 163 |
-
max_tokens,
|
| 164 |
-
):
|
| 165 |
-
"""
|
| 166 |
-
- تنفيذ الاستدلال على ZeroGPU.
|
| 167 |
-
- يدعم نص + صورة + صوت + فيديو في نفس الرسالة.
|
| 168 |
-
- مخرج نصي دائماً، ومخرج صوتي اختياري.
|
| 169 |
-
"""
|
| 170 |
-
|
| 171 |
-
# في حالة عدم وجود مداخل من المستخدم
|
| 172 |
-
if not (user_text or image is not None or audio_path or video_path):
|
| 173 |
-
return history, None, "", None, None, None
|
| 174 |
-
|
| 175 |
-
load_model()
|
| 176 |
-
global model, processor
|
| 177 |
-
|
| 178 |
-
messages = build_messages_from_history(
|
| 179 |
-
history=history,
|
| 180 |
-
system_prompt=system_prompt,
|
| 181 |
-
user_text=user_text,
|
| 182 |
-
image=image,
|
| 183 |
-
audio_path=audio_path,
|
| 184 |
-
video_path=video_path,
|
| 185 |
-
)
|
| 186 |
-
|
| 187 |
-
# بناء نص المحادثة باستخدام chat_template
|
| 188 |
-
text_prompt = processor.apply_chat_template(
|
| 189 |
-
messages,
|
| 190 |
-
add_generation_prompt=True,
|
| 191 |
-
tokenize=False,
|
| 192 |
-
)
|
| 193 |
-
|
| 194 |
-
# تجهيز الوسائط المتعددة
|
| 195 |
-
audios, images, videos = process_mm_info(
|
| 196 |
-
messages,
|
| 197 |
-
use_audio_in_video=USE_AUDIO_IN_VIDEO,
|
| 198 |
-
)
|
| 199 |
-
|
| 200 |
-
# تحويل إلى تينسورات
|
| 201 |
-
inputs = processor(
|
| 202 |
-
text=text_prompt,
|
| 203 |
-
audio=audios,
|
| 204 |
-
images=images,
|
| 205 |
-
videos=videos,
|
| 206 |
-
return_tensors="pt",
|
| 207 |
-
padding=True,
|
| 208 |
-
use_audio_in_video=USE_AUDIO_IN_VIDEO,
|
| 209 |
-
)
|
| 210 |
-
|
| 211 |
-
# نقل إلى جهاز النموذج ونفس dtype
|
| 212 |
-
first_param = next(model.parameters())
|
| 213 |
-
device = first_param.device
|
| 214 |
-
dtype = first_param.dtype
|
| 215 |
-
inputs = inputs.to(device=device, dtype=dtype)
|
| 216 |
-
|
| 217 |
-
# إعدادات التوليد
|
| 218 |
-
gen_kwargs = dict(
|
| 219 |
-
temperature=float(temperature),
|
| 220 |
-
top_p=float(top_p),
|
| 221 |
-
max_new_tokens=int(max_tokens),
|
| 222 |
-
thinker_return_dict_in_generate=True,
|
| 223 |
-
use_audio_in_video=USE_AUDIO_IN_VIDEO,
|
| 224 |
-
)
|
| 225 |
-
|
| 226 |
-
# توليد نص فقط أو نص + صوت
|
| 227 |
-
if not return_audio:
|
| 228 |
-
gen_kwargs["return_audio"] = False
|
| 229 |
-
text_ids, audio_out = model.generate(**inputs, **gen_kwargs)
|
| 230 |
-
audio_out = None
|
| 231 |
-
else:
|
| 232 |
-
gen_kwargs["speaker"] = speaker
|
| 233 |
-
text_ids, audio_out = model.generate(**inputs, **gen_kwargs)
|
| 234 |
-
|
| 235 |
-
# استخراج النص الناتج (بدون مدخل prompt)
|
| 236 |
-
input_len = inputs["input_ids"].shape[1]
|
| 237 |
-
generated_text = processor.batch_decode(
|
| 238 |
-
text_ids.sequences[:, input_len:],
|
| 239 |
-
skip_special_tokens=True,
|
| 240 |
-
clean_up_tokenization_spaces=False,
|
| 241 |
-
)[0]
|
| 242 |
-
|
| 243 |
-
# تحديث تاريخ الدردشة
|
| 244 |
-
user_display = (
|
| 245 |
-
user_text if (user_text and user_text.strip()) else "[Multimodal message]"
|
| 246 |
-
)
|
| 247 |
-
history = history + [[user_display, generated_text]]
|
| 248 |
-
|
| 249 |
-
# تجهيز الصوت الناتج إن وجد
|
| 250 |
-
gr_audio = None
|
| 251 |
-
if audio_out is not None:
|
| 252 |
-
audio_np = audio_out.reshape(-1).detach().cpu().numpy()
|
| 253 |
-
sample_rate = 24000
|
| 254 |
-
gr_audio = (sample_rate, audio_np.astype(np.float32))
|
| 255 |
-
|
| 256 |
-
# نعيد: history الجديد + صوت الرد + تفريغ مدخلات المستخدم
|
| 257 |
-
return history, gr_audio, "", None, None, None
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
# =========================================================
|
| 261 |
-
# دوال واجهة Gradio
|
| 262 |
-
# =========================================================
|
| 263 |
-
|
| 264 |
-
def clear_chat():
|
| 265 |
-
"""إعادة تعيين المحادثة ومخرج الصوت."""
|
| 266 |
-
return [], None
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
def create_interface():
|
| 270 |
-
with gr.Blocks(
|
| 271 |
-
title="Qwen3-Omni-30B-A3B – ZeroGPU Chat",
|
| 272 |
-
) as demo:
|
| 273 |
-
gr.Markdown(
|
| 274 |
-
"""
|
| 275 |
-
<h1 style="text-align:center;">Qwen3-Omni-30B-A3B – ZeroGPU Chat</h1>
|
| 276 |
-
<p style="text-align:center;">
|
| 277 |
-
دردشة متعددة الوسائط (نص + صورة + صوت + فيديو) تعمل على ZeroGPU.<br/>
|
| 278 |
-
اكتب رسالتك، ويمكنك إضافة صورة/صوت/فيديو، ثم اضغط <b>إرسال</b> أو Enter.<br/>
|
| 279 |
-
(لإضافة سطر جديد استخدم Shift+Enter)
|
| 280 |
-
</p>
|
| 281 |
-
"""
|
| 282 |
-
)
|
| 283 |
-
|
| 284 |
-
with gr.Row():
|
| 285 |
-
# العمود الأيسر: المحادثة
|
| 286 |
-
with gr.Column(scale=3):
|
| 287 |
-
chatbot = gr.Chatbot(
|
| 288 |
-
label="المحادثة",
|
| 289 |
-
height=480,
|
| 290 |
-
)
|
| 291 |
-
|
| 292 |
-
audio_output = gr.Audio(
|
| 293 |
-
label="رد النموذج (صوت)",
|
| 294 |
-
type="numpy",
|
| 295 |
-
autoplay=True,
|
| 296 |
-
)
|
| 297 |
-
|
| 298 |
-
with gr.Row():
|
| 299 |
-
user_text = gr.Textbox(
|
| 300 |
-
label="رسالتك",
|
| 301 |
-
placeholder="اكتب رسالتك هنا (يمكنك أيضاً إرفاق صورة/صوت/فيديو من الأسفل)...",
|
| 302 |
-
lines=3,
|
| 303 |
-
show_label=False,
|
| 304 |
-
)
|
| 305 |
-
|
| 306 |
-
with gr.Row():
|
| 307 |
-
image_input = gr.Image(
|
| 308 |
-
label="📷 صورة (اختياري)",
|
| 309 |
-
type="pil",
|
| 310 |
-
sources=["upload", "webcam"],
|
| 311 |
-
height=150,
|
| 312 |
-
)
|
| 313 |
-
audio_input = gr.Audio(
|
| 314 |
-
label="🎙️ صوت (اختياري)",
|
| 315 |
-
type="filepath",
|
| 316 |
-
sources=["microphone", "upload"],
|
| 317 |
-
)
|
| 318 |
-
video_input = gr.Video(
|
| 319 |
-
label="🎬 فيديو (اختياري)",
|
| 320 |
-
)
|
| 321 |
-
|
| 322 |
-
with gr.Row():
|
| 323 |
-
send_btn = gr.Button("إرسال", variant="primary", scale=2)
|
| 324 |
-
clear_btn = gr.Button("مسح المحادثة", variant="secondary")
|
| 325 |
-
|
| 326 |
-
# العمود الأيمن: الإعدادات
|
| 327 |
-
with gr.Column(scale=1):
|
| 328 |
-
gr.Markdown("### إعدادات النموذج")
|
| 329 |
-
|
| 330 |
-
system_prompt = gr.Textbox(
|
| 331 |
-
label="System Prompt",
|
| 332 |
-
value="You are a helpful, multilingual assistant.",
|
| 333 |
-
lines=4,
|
| 334 |
-
placeholder="يمكنك التحكم في شخصية النموذج من هنا (اختياري).",
|
| 335 |
-
)
|
| 336 |
-
|
| 337 |
-
return_audio = gr.Checkbox(
|
| 338 |
-
label="تفعيل مخرج صوتي (النموذج يتكلم)؟",
|
| 339 |
-
value=True,
|
| 340 |
-
)
|
| 341 |
-
|
| 342 |
-
speaker = gr.Dropdown(
|
| 343 |
-
label="صوت المتحدث (speaker)",
|
| 344 |
-
choices=VOICE_CHOICES,
|
| 345 |
-
value=DEFAULT_VOICE,
|
| 346 |
-
)
|
| 347 |
-
|
| 348 |
-
with gr.Accordion("إعدادات متقدمة", open=False):
|
| 349 |
-
temperature = gr.Slider(
|
| 350 |
-
label="Temperature (العشوائية)",
|
| 351 |
-
minimum=0.0,
|
| 352 |
-
maximum=1.5,
|
| 353 |
-
value=0.6,
|
| 354 |
-
step=0.05,
|
| 355 |
-
)
|
| 356 |
-
|
| 357 |
-
top_p = gr.Slider(
|
| 358 |
-
label="Top-p (حجم العينة)",
|
| 359 |
-
minimum=0.1,
|
| 360 |
-
maximum=1.0,
|
| 361 |
-
value=0.95,
|
| 362 |
-
step=0.05,
|
| 363 |
-
)
|
| 364 |
-
|
| 365 |
-
max_tokens = gr.Slider(
|
| 366 |
-
label="Max new tokens (طول الرد الأقصى)",
|
| 367 |
-
minimum=16,
|
| 368 |
-
maximum=1024,
|
| 369 |
-
value=384,
|
| 370 |
-
step=16,
|
| 371 |
-
)
|
| 372 |
-
|
| 373 |
-
gr.Markdown(
|
| 374 |
-
"""
|
| 375 |
-
**ملاحظات:**
|
| 376 |
-
- يمكنك إرسال نص فقط، أو نص مع صورة/صوت/فيديو في رسالة واحدة.
|
| 377 |
-
- Enter للإرسال، وShift+Enter لسطر جديد.
|
| 378 |
-
- تشغيل النموذج على ZeroGPU قد يستغرق عدة ثوانٍ حسب طول الرسالة.
|
| 379 |
-
"""
|
| 380 |
-
)
|
| 381 |
-
|
| 382 |
-
# حالة المحادثة
|
| 383 |
-
history_state = gr.State([])
|
| 384 |
-
|
| 385 |
-
# مدخلات دالة الإرسال
|
| 386 |
-
send_inputs = [
|
| 387 |
-
history_state,
|
| 388 |
-
user_text,
|
| 389 |
-
image_input,
|
| 390 |
-
audio_input,
|
| 391 |
-
video_input,
|
| 392 |
-
system_prompt,
|
| 393 |
-
return_audio,
|
| 394 |
-
speaker,
|
| 395 |
-
temperature,
|
| 396 |
-
top_p,
|
| 397 |
-
max_tokens,
|
| 398 |
-
]
|
| 399 |
-
|
| 400 |
-
send_outputs = [
|
| 401 |
-
history_state,
|
| 402 |
-
audio_output,
|
| 403 |
-
user_text,
|
| 404 |
-
image_input,
|
| 405 |
-
audio_input,
|
| 406 |
-
video_input,
|
| 407 |
-
]
|
| 408 |
-
|
| 409 |
-
# إرسال بالزر
|
| 410 |
-
send_btn.click(
|
| 411 |
-
fn=qwen3_omni_inference,
|
| 412 |
-
inputs=send_inputs,
|
| 413 |
-
outputs=send_outputs,
|
| 414 |
-
queue=True,
|
| 415 |
-
).then(
|
| 416 |
-
lambda h: h,
|
| 417 |
-
inputs=history_state,
|
| 418 |
-
outputs=chatbot,
|
| 419 |
-
)
|
| 420 |
-
|
| 421 |
-
# إرسال بالـ Enter من Textbox
|
| 422 |
-
user_text.submit(
|
| 423 |
-
fn=qwen3_omni_inference,
|
| 424 |
-
inputs=send_inputs,
|
| 425 |
-
outputs=send_outputs,
|
| 426 |
-
queue=True,
|
| 427 |
-
).then(
|
| 428 |
-
lambda h: h,
|
| 429 |
-
inputs=history_state,
|
| 430 |
-
outputs=chatbot,
|
| 431 |
-
)
|
| 432 |
-
|
| 433 |
-
# مسح المحادثة
|
| 434 |
-
clear_btn.click(
|
| 435 |
-
fn=clear_chat,
|
| 436 |
-
inputs=None,
|
| 437 |
-
outputs=[history_state, audio_output],
|
| 438 |
-
).then(
|
| 439 |
-
lambda: [],
|
| 440 |
-
inputs=None,
|
| 441 |
-
outputs=chatbot,
|
| 442 |
-
).then(
|
| 443 |
-
lambda: ("", None, None),
|
| 444 |
-
inputs=None,
|
| 445 |
-
outputs=[user_text, image_input, audio_input],
|
| 446 |
-
)
|
| 447 |
-
|
| 448 |
-
return demo
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
demo = create_interface()
|
| 452 |
-
|
| 453 |
-
if __name__ == "__main__":
|
| 454 |
-
# إيقاف SSR لأنه تجريبي وقد يسبب مشكلة "Starting..."
|
| 455 |
-
demo.launch(ssr_mode=False)
|
|
|
|
| 1 |
+
import os import numpy as np import torch import gradio as gr import spaces import warnings warnings.filterwarnings("ignore") from transformers import Qwen3OmniMoeForConditionalGeneration, Qwen3OmniMoeProcessor from qwen_omni_utils import process_mm_info # ========================================================= # Patches لتجاوز مشاكل التوافق في Qwen3-Omni # ========================================================= def _patched_mark_tied_weights_as_initialized(self): """ تجاوز مشكلة lm_head في tied weights """ return def _patched_init_weights(self, module): """ تجاوز مشكلة initializer_range في Qwen3OmniMoeTalkerConfig """ # نحاول الحصول على initializer_range، وإذا لم يكن موجود نستخدم قيمة افتراضية try: std = self.config.initializer_range except AttributeError: # قيمة افتراضية آمنة std = 0.02 # تطبيق التهيئة الأساسية if isinstance(module, torch.nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, torch.nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() def _patched_initialize_weights(self): """ تجاوز كامل لدالة initialize_weights في حالة استمرار المشاكل """ # نحاول التهيئة العادية، وإذا فشلت نتجاهلها try: # محاولة استخدام الدالة الأصلية إذا كانت موجودة if hasattr(self, '_original_initialize_weights'): self._original_initialize_weights() else: # تهيئة بسيطة آمنة for module in self.modules(): if isinstance(module, (torch.nn.Linear, torch.nn.Embedding)): if hasattr(module, 'weight'): module.weight.data.normal_(mean=0.0, std=0.02) if hasattr(module, 'bias') and module.bias is not None: module.bias.data.zero_() except Exception as e: print(f"Warning: Could not initialize weights properly: {e}") # نستمر بدون تهيئة - النموذج المحمل مسبقاً يجب أن يعمل # تطبيق الـ patches قبل أي استدعاء لـ from_pretrained def apply_patches(): """تطبيق جميع الـ patches اللازمة""" # Patch 1: تجاوز مشكلة lm_head if hasattr(Qwen3OmniMoeForConditionalGeneration, "mark_tied_weights_as_initialized"): Qwen3OmniMoeForConditionalGeneration.mark_tied_weights_as_initialized = ( _patched_mark_tied_weights_as_initialized ) # Patch 2: تجاوز مشكلة initializer_range if hasattr(Qwen3OmniMoeForConditionalGeneration, "_init_weights"): Qwen3OmniMoeForConditionalGeneration._init_weights = _patched_init_weights # Patch 3: تجاوز initialize_weights بالكامل إذا لزم if hasattr(Qwen3OmniMoeForConditionalGeneration, "initialize_weights"): # حفظ الدالة الأصلية Qwen3OmniMoeForConditionalGeneration._original_initialize_weights = ( Qwen3OmniMoeForConditionalGeneration.initialize_weights ) Qwen3OmniMoeForConditionalGeneration.initialize_weights = _patched_initialize_weights # تطبيق الـ patches apply_patches() # ========================================================= # إعدادات عامة # ========================================================= MODEL_PATH = os.getenv("MODEL_PATH", "Qwen/Qwen3-Omni-30B-A3B-Instruct") USE_AUDIO_IN_VIDEO = True # استخدام الصوت داخل الفيديو إذا وجد VOICE_CHOICES = ["Ethan", "Chelsie", "Aiden"] DEFAULT_VOICE = "Ethan" # سنحمّل النموذج كسولياً (عند أول استدعاء فقط) model = None processor = None def load_model(): """ تحميل Qwen3-Omni والمعالج عند أول استدعاء فقط. - نستخدم attn_implementation="eager" لتفادي الحاجة لـ flash-attn. - نضيف low_cpu_mem_usage=True لتحسين الأداء - نضيف ignore_mismatched_sizes=True لتجاوز مشاكل الأحجام """ global model, processor if model is not None and processor is not None: return print(f"[ZeroGPU] Loading model from: {MODEL_PATH}") # اختيار نوع البيانات والجهاز if torch.cuda.is_available(): torch_dtype = torch.bfloat16 device = "cuda" else: torch_dtype = torch.float32 device = "cpu" try: # محاولة تحميل النموذج مع خيارات إضافية للأمان local_model = Qwen3OmniMoeForConditionalGeneration.from_pretrained( MODEL_PATH, torch_dtype=torch_dtype, attn_implementation="eager", # آمن على ZeroGPU بدون flash-attn low_cpu_mem_usage=True, # تحسين استخدام الذاكرة ignore_mismatched_sizes=True, # تجاوز مشاكل الأحجام trust_remote_code=True, # السماح بالكود المخصص ) # نقل النموذج إلى الجهاز المناسب local_model = local_model.to(device) # وضع النموذج في وضع التقييم (inference) local_model.eval() except Exception as e: print(f"Error loading model: {e}") print("Attempting alternative loading method...") # محاولة بديلة مع تعطيل _init_weights try: # تعطيل _init_weights مؤقتاً original_init_weights = None if hasattr(Qwen3OmniMoeForConditionalGeneration, "_init_weights"): original_init_weights = Qwen3OmniMoeForConditionalGeneration._init_weights Qwen3OmniMoeForConditionalGeneration._init_weights = lambda self, module: None local_model = Qwen3OmniMoeForConditionalGeneration.from_pretrained( MODEL_PATH, torch_dtype=torch_dtype, attn_implementation="eager", low_cpu_mem_usage=True, ) # استعادة _init_weights if original_init_weights: Qwen3OmniMoeForConditionalGeneration._init_weights = original_init_weights local_model = local_model.to(device) local_model.eval() except Exception as e2: raise RuntimeError(f"Failed to load model: {e2}") # تحميل المعالج try: local_processor = Qwen3OmniMoeProcessor.from_pretrained( MODEL_PATH, trust_remote_code=True ) except Exception as e: print(f"Error loading processor: {e}") raise model = local_model processor = local_processor print(f"[ZeroGPU] Model loaded successfully on {device} with dtype {torch_dtype}.") def build_messages_from_history( history, system_prompt, user_text, image, audio_path, video_path, ): """ تحويل تاريخ الدردشة + المدخل الحالي إلى conversation بالـ format المطلوب من Qwen3-Omni. history: list of [user_text, assistant_text] """ messages = [] if system_prompt: messages.append( { "role": "system", "content": [{"type": "text", "text": system_prompt}], } ) # تاريخ المحادثة for user_msg, assistant_msg in history: if user_msg: messages.append( { "role": "user", "content": [{"type": "text", "text": user_msg}], } ) if assistant_msg: messages.append( { "role": "assistant", "content": [{"type": "text", "text": assistant_msg}], } ) # محتوى رسالة المستخدم الحالية user_content = [] if image is not None: user_content.append({"type": "image", "image": image}) if audio_path is not None and audio_path != "": user_content.append({"type": "audio", "audio": audio_path}) if video_path is not None and video_path != "": user_content.append({"type": "video", "video": video_path}) if user_text and user_text.strip(): user_content.append({"type": "text", "text": user_text.strip()}) if user_content: messages.append( { "role": "user", "content": user_content, } ) return messages # ========================================================= # دالة الاستدلال (تعمل على ZeroGPU) # ========================================================= @spaces.GPU(duration=120) def qwen3_omni_inference( history, user_text, image, audio_path, video_path, system_prompt, return_audio, speaker, temperature, top_p, max_tokens, ): """ - تنفيذ الاستدلال على ZeroGPU. - يدعم نص + صورة + صوت + فيديو في نفس الرسالة. - مخرج نصي دائماً، ومخرج صوتي اختياري. """ # في حالة عدم وجود مداخل من المستخدم if not (user_text or image is not None or audio_path or video_path): return history, None, "", None, None, None try: load_model() global model, processor messages = build_messages_from_history( history=history, system_prompt=system_prompt, user_text=user_text, image=image, audio_path=audio_path, video_path=video_path, ) # بناء نص المحادثة باستخدام chat_template text_prompt = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=False, ) # تجهيز الوسائط المتعددة audios, images, videos = process_mm_info( messages, use_audio_in_video=USE_AUDIO_IN_VIDEO, ) # تحويل إلى تينسورات inputs = processor( text=text_prompt, audio=audios, images=images, videos=videos, return_tensors="pt", padding=True, use_audio_in_video=USE_AUDIO_IN_VIDEO, ) # نقل إلى جهاز النموذج ونفس dtype first_param = next(model.parameters()) device = first_param.device # تحويل المدخلات إلى الجهاز المناسب for key in inputs: if hasattr(inputs[key], 'to'): inputs[key] = inputs[key].to(device) # إعدادات التوليد gen_kwargs = dict( temperature=float(temperature) if temperature > 0 else 1e-7, top_p=float(top_p), max_new_tokens=int(max_tokens), do_sample=temperature > 0, use_audio_in_video=USE_AUDIO_IN_VIDEO, ) # إضافة thinker_return_dict_in_generate فقط إذا كان مدعوماً if hasattr(model, 'config') and hasattr(model.config, 'thinker_return_dict_in_generate'): gen_kwargs["thinker_return_dict_in_generate"] = True # توليد نص فقط أو نص + صوت with torch.no_grad(): if not return_audio: gen_kwargs["return_audio"] = False outputs = model.generate(**inputs, **gen_kwargs) text_ids = outputs audio_out = None else: gen_kwargs["speaker"] = speaker gen_kwargs["return_audio"] = True outputs = model.generate(**inputs, **gen_kwargs) if isinstance(outputs, tuple): text_ids, audio_out = outputs else: text_ids = outputs audio_out = None # استخراج النص الناتج (بدون مدخل prompt) input_len = inputs["input_ids"].shape[1] # التعامل مع الأنواع المختلفة من المخرجات if hasattr(text_ids, 'sequences'): generated_ids = text_ids.sequences[:, input_len:] else: generated_ids = text_ids[:, input_len:] generated_text = processor.batch_decode( generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False, )[0] # تحديث تاريخ الدردشة user_display = ( user_text if (user_text and user_text.strip()) else "[Multimodal message]" ) history = history + [[user_display, generated_text]] # تجهيز الصوت الناتج إن وجد gr_audio = None if audio_out is not None: try: audio_np = audio_out.reshape(-1).detach().cpu().numpy() sample_rate = 24000 gr_audio = (sample_rate, audio_np.astype(np.float32)) except Exception as e: print(f"Warning: Could not process audio output: {e}") gr_audio = None # نعيد: history الجديد + صوت الرد + تفريغ مدخلات المستخدم return history, gr_audio, "", None, None, None except Exception as e: print(f"Error during inference: {e}") import traceback traceback.print_exc() # في حالة الخطأ، نضيف رسالة خطأ للمحادثة user_display = ( user_text if (user_text and user_text.strip()) else "[Multimodal message]" ) error_message = f"عذراً، حدث خطأ أثناء معالجة الرسالة: {str(e)}" history = history + [[user_display, error_message]] return history, None, "", None, None, None # ========================================================= # دوال واجهة Gradio # ========================================================= def clear_chat(): """إعادة تعيين المحادثة ومخرج الصوت.""" return [], None def create_interface(): with gr.Blocks( title="Qwen3-Omni-30B-A3B – ZeroGPU Chat", theme=gr.themes.Soft(), ) as demo: gr.Markdown( """ <h1 style="text-align:center;">🤖 Qwen3-Omni-30B-A3B – ZeroGPU Chat</h1> <p style="text-align:center;"> دردشة متعددة الوسائط (نص + صورة + صوت + فيديو) تعمل على ZeroGPU.<br/> اكتب رسالتك، ويمكنك إضافة صورة/صوت/فيديو، ثم اضغط <b>إرسال</b> أو Enter.<br/> (لإضافة سطر جديد استخدم Shift+Enter) </p> """ ) with gr.Row(): # العمود الأيسر: المحادثة with gr.Column(scale=3): chatbot = gr.Chatbot( label="المحادثة", height=480, elem_id="chatbot", ) audio_output = gr.Audio( label="رد النموذج (صوت)", type="numpy", autoplay=True, visible=True, ) with gr.Row(): user_text = gr.Textbox( label="رسالتك", placeholder="اكتب رسالتك هنا (يمكنك أيضاً إرفاق صورة/صوت/فيديو من الأسفل)...", lines=3, show_label=False, elem_id="message", ) with gr.Row(): image_input = gr.Image( label="📷 صورة (اختياري)", type="pil", sources=["upload", "webcam"], height=150, ) audio_input = gr.Audio( label="🎙️ صوت (اختياري)", type="filepath", sources=["microphone", "upload"], ) video_input = gr.Video( label="🎬 فيديو (اختياري)", height=150, ) with gr.Row(): send_btn = gr.Button("إرسال", variant="primary", scale=2) clear_btn = gr.Button("مسح المحادثة", variant="secondary") # العمود الأيمن: الإعدادات with gr.Column(scale=1): gr.Markdown("### ⚙️ إعدادات النموذج") system_prompt = gr.Textbox( label="System Prompt", value="You are a helpful, multilingual assistant.", lines=4, placeholder="يمكنك التحكم في شخصية النموذج من هنا (اختياري).", ) return_audio = gr.Checkbox( label="تفعيل مخرج صوتي (النموذج يتكلم)؟", value=True, ) speaker = gr.Dropdown( label="صوت المتحدث (speaker)", choices=VOICE_CHOICES, value=DEFAULT_VOICE, ) with gr.Accordion("إعدادات متقدمة", open=False): temperature = gr.Slider( label="Temperature (العشوائية)", minimum=0.0, maximum=1.5, value=0.6, step=0.05, ) top_p = gr.Slider( label="Top-p (حجم العينة)", minimum=0.1, maximum=1.0, value=0.95, step=0.05, ) max_tokens = gr.Slider( label="Max new tokens (طول الرد الأقصى)", minimum=16, maximum=1024, value=384, step=16, ) gr.Markdown( """ **📝 ملاحظات:** - يمكنك إرسال نص فقط، أو نص مع صورة/صوت/فيديو في رسالة واحدة - Enter للإرسال، Shift+Enter لسطر جديد - تشغيل النموذج على ZeroGPU قد يستغرق عدة ثوانٍ حسب طول الرسالة - النموذج يدعم اللغات المتعددة بما فيها العربية والإنجليزية """ ) # حالة المحادثة history_state = gr.State([]) # مدخلات دالة الإرسال send_inputs = [ history_state, user_text, image_input, audio_input, video_input, system_prompt, return_audio, speaker, temperature, top_p, max_tokens, ] send_outputs = [ history_state, audio_output, user_text, image_input, audio_input, video_input, ] # إرسال بالزر send_btn.click( fn=qwen3_omni_inference, inputs=send_inputs, outputs=send_outputs, queue=True, ).then( lambda h: h, inputs=history_state, outputs=chatbot, ) # إرسال بالـ Enter من Textbox user_text.submit( fn=qwen3_omni_inference, inputs=send_inputs, outputs=send_outputs, queue=True, ).then( lambda h: h, inputs=history_state, outputs=chatbot, ) # مسح المحادثة clear_btn.click( fn=clear_chat, inputs=None, outputs=[history_state, audio_output], ).then( lambda: [], inputs=None, outputs=chatbot, ).then( lambda: ("", None, None, None), inputs=None, outputs=[user_text, image_input, audio_input, video_input], ) # رسالة تحميل النموذج عند بدء التطبيق demo.load( lambda: gr.Info("جاري تحميل النموذج... قد يستغرق هذا بضع دقائق في المرة الأولى."), inputs=None, outputs=None, ) return demo # إنشاء الواجهة demo = create_interface() if __name__ == "__main__": # إطلاق التطبيق demo.launch( ssr_mode=False, # تعطيل SSR لتجنب مشاكل "Starting..." show_error=True, # عرض الأخطاء بشكل واضح )
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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