mohmmed5787 commited on
Commit
79bb5bd
·
verified ·
1 Parent(s): 5e7e544

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +318 -0
app.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ import os
4
+ import numpy as np
5
+ from pathlib import Path
6
+ import tempfile
7
+ import cv2
8
+ from PIL import Image
9
+ import torchaudio
10
+ import subprocess
11
+ import warnings
12
+ warnings.filterwarnings('ignore')
13
+
14
+ # تحميل النماذج
15
+ print("🔄 جاري تحميل النماذج...")
16
+
17
+ # SadTalker للوجه المتحرك
18
+ try:
19
+ from sadtalker.test_audio2coeff import Audio2Coeff
20
+ from sadtalker.facerender.animate import AnimateFromCoeff
21
+ from sadtalker.test_audio2video import audio2video
22
+ print("✅ SadTalker جاهز")
23
+ except:
24
+ print("⚠️ SadTalker غير متوفر، سيتم استخدام Wav2Lip")
25
+
26
+ # Wav2Lip كخيار احتياطي
27
+ try:
28
+ import sys
29
+ sys.path.append('./Wav2Lip')
30
+ from models import Wav2Lip
31
+ from inference import load_checkpoint
32
+ print("✅ Wav2Lip جاهز")
33
+ except:
34
+ print("⚠️ Wav2Lip غير متوفر")
35
+
36
+ # TTS العربي
37
+ try:
38
+ from TTS.api import TTS
39
+ tts_model = TTS("tts_models/ara/fairseq/vits")
40
+ print("✅ Arabic TTS جاهز")
41
+ except:
42
+ print("⚠️ TTS غير متوفر")
43
+
44
+ def process_lipsync(
45
+ image_file,
46
+ audio_file=None,
47
+ text_input=None,
48
+ emotional_intensity=80,
49
+ stability=90,
50
+ lip_sync_accuracy=95
51
+ ):
52
+ """
53
+ معالجة مزامنة الشفاه
54
+ """
55
+ try:
56
+ # التحقق من المدخلات
57
+ if image_file is None:
58
+ return None, "❌ الرجاء رفع صورة"
59
+
60
+ if audio_file is None and not text_input:
61
+ return None, "❌ الرجاء إدخال صوت أو نص"
62
+
63
+ # إنشاء مجلد مؤقت
64
+ temp_dir = tempfile.mkdtemp()
65
+
66
+ # معالجة الصورة
67
+ image_path = os.path.join(temp_dir, "image.png")
68
+ if isinstance(image_file, str):
69
+ img = Image.open(image_file)
70
+ else:
71
+ img = Image.fromarray(image_file)
72
+ img.save(image_path)
73
+
74
+ # معالجة الصوت
75
+ if text_input and audio_file is None:
76
+ # تحويل النص إلى صوت
77
+ audio_path = os.path.join(temp_dir, "audio.wav")
78
+ try:
79
+ tts_model.tts_to_file(
80
+ text=text_input,
81
+ file_path=audio_path
82
+ )
83
+ except Exception as e:
84
+ return None, f"❌ خطأ في تحويل النص إلى صوت: {str(e)}"
85
+ else:
86
+ audio_path = audio_file
87
+
88
+ # تطبيق SadTalker
89
+ output_video = os.path.join(temp_dir, "output.mp4")
90
+
91
+ try:
92
+ # محاولة SadTalker أولاً
93
+ from sadtalker.inference import inference
94
+
95
+ result = inference(
96
+ source_image=image_path,
97
+ driven_audio=audio_path,
98
+ result_dir=temp_dir,
99
+ pose_style=int(emotional_intensity / 100 * 46), # 0-46
100
+ still=stability > 50,
101
+ preprocess='crop',
102
+ expression_scale=lip_sync_accuracy / 100,
103
+ )
104
+
105
+ output_video = result
106
+
107
+ except Exception as e:
108
+ # استخدام Wav2Lip كبديل
109
+ try:
110
+ checkpoint_path = './Wav2Lip/checkpoints/wav2lip_gan.pth'
111
+
112
+ cmd = f"""
113
+ cd Wav2Lip && python inference.py \
114
+ --checkpoint_path {checkpoint_path} \
115
+ --face {image_path} \
116
+ --audio {audio_path} \
117
+ --outfile {output_video} \
118
+ --pads 0 10 0 0 \
119
+ --fps 25 \
120
+ --resize_factor {stability / 100} \
121
+ --nosmooth
122
+ """
123
+
124
+ subprocess.run(cmd, shell=True, check=True)
125
+
126
+ except Exception as e2:
127
+ return None, f"❌ خطأ في الإنتاج: {str(e2)}"
128
+
129
+ # تحسين الفيديو
130
+ enhanced_video = os.path.join(temp_dir, "enhanced.mp4")
131
+ enhance_video_quality(output_video, enhanced_video, lip_sync_accuracy)
132
+
133
+ return enhanced_video, "✅ تم الإنتاج بنجاح!"
134
+
135
+ except Exception as e:
136
+ return None, f"❌ خطأ: {str(e)}"
137
+
138
+ def enhance_video_quality(input_video, output_video, quality_level):
139
+ """
140
+ تحسين جودة الفيديو
141
+ """
142
+ try:
143
+ # استخدام FFmpeg لتحسين الجودة
144
+ cmd = f"""
145
+ ffmpeg -i {input_video} \
146
+ -vf "unsharp=5:5:1.0:5:5:0.0" \
147
+ -c:v libx264 \
148
+ -preset slow \
149
+ -crf {int((100 - quality_level) / 5)} \
150
+ -c:a aac \
151
+ -b:a 192k \
152
+ {output_video} \
153
+ -y
154
+ """
155
+ subprocess.run(cmd, shell=True, check=True)
156
+ return True
157
+ except:
158
+ # إذا فشل، انسخ الملف الأ��لي
159
+ import shutil
160
+ shutil.copy(input_video, output_video)
161
+ return False
162
+
163
+ # إنشاء الواجهة
164
+ print("🎨 إنشاء الواجهة...")
165
+
166
+ # قراءة HTML
167
+ html_file = Path(__file__).parent / "index.html"
168
+ if html_file.exists():
169
+ with open(html_file, 'r', encoding='utf-8') as f:
170
+ custom_html = f.read()
171
+ else:
172
+ custom_html = """
173
+ <div style="text-align:center; padding:20px; background:linear-gradient(135deg, #667eea 0%, #764ba2 100%); border-radius:15px;">
174
+ <h1 style="color:white; font-size:3em;">🎬 استوديو مزامنة الشفاه</h1>
175
+ <p style="color:white; font-size:1.2em;">⚡ Powered by Hugging Face AI</p>
176
+ </div>
177
+ """
178
+
179
+ # Gradio Interface مع HTML مخصص
180
+ with gr.Blocks(
181
+ theme=gr.themes.Soft(
182
+ primary_hue="purple",
183
+ secondary_hue="pink",
184
+ ),
185
+ css="""
186
+ .gradio-container {
187
+ max-width: 1200px !important;
188
+ margin: auto !important;
189
+ }
190
+ """,
191
+ title="استوديو مزامنة الشفاه"
192
+ ) as app:
193
+
194
+ # إضافة HTML المخصص
195
+ gr.HTML(custom_html)
196
+
197
+ with gr.Row():
198
+ with gr.Column(scale=1):
199
+ gr.Markdown("### 🖼️ الصورة")
200
+ image_input = gr.Image(
201
+ label="ارفع صورة الوجه",
202
+ type="filepath",
203
+ height=400
204
+ )
205
+
206
+ with gr.Column(scale=1):
207
+ gr.Markdown("### 🎤 الصوت أو النص")
208
+
209
+ mode_selector = gr.Radio(
210
+ ["رفع ملف صوتي", "إدخال نص"],
211
+ value="رفع ملف صوتي",
212
+ label="اختر الطريقة"
213
+ )
214
+
215
+ audio_input = gr.Audio(
216
+ label="ارفع ملف صوتي",
217
+ type="filepath",
218
+ visible=True
219
+ )
220
+
221
+ text_input = gr.Textbox(
222
+ label="أو اكتب النص (سيتم تحويله لصوت)",
223
+ placeholder="اكتب النص هنا...",
224
+ lines=5,
225
+ visible=False
226
+ )
227
+
228
+ # الإعدادات المتقدمة
229
+ with gr.Accordion("⚙️ إعدادات متقدمة", open=False):
230
+ with gr.Row():
231
+ emotional_intensity = gr.Slider(
232
+ minimum=0,
233
+ maximum=100,
234
+ value=80,
235
+ step=1,
236
+ label="💫 التعبير العاطفي (Emotional Intensity)"
237
+ )
238
+
239
+ stability = gr.Slider(
240
+ minimum=0,
241
+ maximum=100,
242
+ value=90,
243
+ step=1,
244
+ label="🎯 ثبات الوجه (Face Stability)"
245
+ )
246
+
247
+ lip_sync_accuracy = gr.Slider(
248
+ minimum=0,
249
+ maximum=100,
250
+ value=95,
251
+ step=1,
252
+ label="💋 دقة مزامنة الشفاه (Lip Sync Precision)"
253
+ )
254
+
255
+ # زر الإنتاج
256
+ generate_btn = gr.Button(
257
+ "🎬 إنتاج الفيديو الآن",
258
+ variant="primary",
259
+ size="lg"
260
+ )
261
+
262
+ # النتائج
263
+ with gr.Row():
264
+ with gr.Column():
265
+ output_video = gr.Video(label="✨ الفيديو الناتج")
266
+ status_message = gr.Textbox(label="الحالة", interactive=False)
267
+
268
+ # معالجة تغيير الوضع
269
+ def toggle_mode(mode):
270
+ if mode == "رفع ملف صوتي":
271
+ return gr.update(visible=True), gr.update(visible=False)
272
+ else:
273
+ return gr.update(visible=False), gr.update(visible=True)
274
+
275
+ mode_selector.change(
276
+ fn=toggle_mode,
277
+ inputs=[mode_selector],
278
+ outputs=[audio_input, text_input]
279
+ )
280
+
281
+ # معالجة الإنتاج
282
+ generate_btn.click(
283
+ fn=process_lipsync,
284
+ inputs=[
285
+ image_input,
286
+ audio_input,
287
+ text_input,
288
+ emotional_intensity,
289
+ stability,
290
+ lip_sync_accuracy
291
+ ],
292
+ outputs=[output_video, status_message]
293
+ )
294
+
295
+ # دليل الاستخدام
296
+ gr.Markdown("""
297
+ ## 📚 كيفية الاستخدام
298
+
299
+ 1. **ارفع صورة**: اختر صورة واضحة للوجه (يفضل بورتريه)
300
+ 2. **أضف الصوت**: ارفع ملف صوتي أو اكتب نصاً
301
+ 3. **اضبط الإعدادات**: (اختياري) عدّل الإعدادات المتقدمة
302
+ 4. **اضغط إنتاج**: انتظر النتيجة المذهلة!
303
+
304
+ ---
305
+
306
+ ⚡ **Powered by**: Hugging Face AI
307
+ 🎭 **التقنيات**: SadTalker, Wav2Lip, MMS-TTS-Arabic
308
+ 💡 **نمط**: Hedra Emotional + HeyGen Stability
309
+ """)
310
+
311
+ print("✅ التطبيق جاهز!")
312
+
313
+ if __name__ == "__main__":
314
+ app.launch(
315
+ server_name="0.0.0.0",
316
+ server_port=7860,
317
+ share=False
318
+ )