atef91 commited on
Commit
a9c13c0
·
verified ·
1 Parent(s): 108bf0f

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +136 -32
app.py CHANGED
@@ -70,10 +70,12 @@ def send_security_alert(message: str, details: Optional[dict] = None):
70
  # Send email
71
  server.send_message(msg)
72
  server.quit()
73
- print("تم إرسال التنبيه بنجاح")
 
74
 
75
  except Exception as e:
76
- print(f"فشل في إرسال التنبيه الأمني: {str(e)}")
 
77
 
78
  class SecurityManager:
79
  def __init__(self):
@@ -216,24 +218,78 @@ def download_with_progress(url: str, fname: str):
216
  size = file.write(data)
217
  bar.update(size)
218
 
219
- # Initialize face analyzer
220
- app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
221
- app.prepare(ctx_id=-1, det_size=(640, 640))
222
-
223
- # Initialize face swapper
224
- def init_face_swapper():
225
- model_path = os.path.expanduser('~/.insightface/models/inswapper_128.onnx')
226
- model_url = "https://huggingface.co/ashleykleynhans/inswapper/resolve/main/inswapper_128.onnx"
227
-
228
- if not os.path.exists(model_path):
229
- print("تحميل نموذج تبديل الوجوه...")
230
- os.makedirs(os.path.dirname(model_path), exist_ok=True)
231
- download_with_progress(model_url, model_path)
232
-
233
- return insightface.model_zoo.get_model(model_path, providers=['CPUExecutionProvider'])
234
-
235
- # Initialize swapper
236
- swapper = init_face_swapper()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
 
238
  @protected_function
239
  def process_frame(frame, source_face):
@@ -429,25 +485,67 @@ def send_test_alert():
429
  except Exception as e:
430
  return f"فشل في إرسال التنبيه التجريبي: {str(e)}"
431
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
432
  # Create Gradio interface
433
  with gr.Blocks(title="Vudwos") as demo:
434
  if not _app.verify_integrity():
435
  raise RuntimeError("فشل التحقق من سلامة التطبيق")
436
 
437
- gr.Markdown("""# Vudwos - تبديل الوجوه في الفيديو
438
- قم بتحميل صورة المصدر والفيديو لتبديل الوجوه
439
  """)
440
 
441
- with gr.Row():
442
- with gr.Column():
443
- source_img = gr.Image(label="صورة المصدر")
444
- video_input = gr.Video(label="الفيديو")
445
- submit_btn = gr.Button("بدء التحويل")
446
-
447
- with gr.Column():
448
- video_output = gr.Video(label="الفيديو المحول")
449
- status_text = gr.Textbox(label="الحالة", interactive=False)
450
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
  with gr.Row():
452
  donate_btn = gr.Button("💝 تبرع للمشروع")
453
  verify_btn = gr.Button("✅ تحقق من التبرع")
@@ -460,6 +558,12 @@ with gr.Blocks(title="Vudwos") as demo:
460
  outputs=[video_output, status_text]
461
  )
462
 
 
 
 
 
 
 
463
  donate_btn.click(
464
  fn=open_donation,
465
  inputs=[],
 
70
  # Send email
71
  server.send_message(msg)
72
  server.quit()
73
+ print("تم إرسال التنبيه بنجاح")
74
+ return True
75
 
76
  except Exception as e:
77
+ print(f"فشل في إرسال التنبيه: {str(e)}")
78
+ return False
79
 
80
  class SecurityManager:
81
  def __init__(self):
 
218
  size = file.write(data)
219
  bar.update(size)
220
 
221
+ @protected_function
222
+ def enhance_video(video_path, enhancement_type="all", progress=gr.Progress()):
223
+ """Enhance video quality"""
224
+ try:
225
+ if video_path is None:
226
+ return None, "الرجاء تحميل فيديو للتحسين"
227
+
228
+ with tempfile.TemporaryDirectory() as temp_dir:
229
+ # Copy input video
230
+ input_path = os.path.join(temp_dir, "input.mp4")
231
+ shutil.copy2(video_path, input_path)
232
+
233
+ # Prepare output path
234
+ output_path = os.path.join(temp_dir, "enhanced.mp4")
235
+
236
+ # Get video properties
237
+ cap = cv2.VideoCapture(input_path)
238
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
239
+ fps = cap.get(cv2.CAP_PROP_FPS)
240
+ width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
241
+ height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
242
+
243
+ # Prepare enhanced video writer
244
+ fourcc = cv2.VideoWriter_fourcc(*'mp4v')
245
+ out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
246
+
247
+ frame_count = 0
248
+ progress(0, desc="جاري تحسين الفيديو...")
249
+
250
+ while cap.isOpened():
251
+ ret, frame = cap.read()
252
+ if not ret:
253
+ break
254
+
255
+ # Apply enhancements based on type
256
+ if enhancement_type in ["all", "denoise"]:
257
+ # Denoise frame
258
+ frame = cv2.fastNlMeansDenoisingColored(frame, None, 10, 10, 7, 21)
259
+
260
+ if enhancement_type in ["all", "sharpen"]:
261
+ # Sharpen frame
262
+ kernel = np.array([[-1,-1,-1], [-1,9,-1], [-1,-1,-1]])
263
+ frame = cv2.filter2D(frame, -1, kernel)
264
+
265
+ if enhancement_type in ["all", "contrast"]:
266
+ # Enhance contrast
267
+ lab = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)
268
+ l, a, b = cv2.split(lab)
269
+ clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
270
+ l = clahe.apply(l)
271
+ lab = cv2.merge((l,a,b))
272
+ frame = cv2.cvtColor(lab, cv2.COLOR_LAB2BGR)
273
+
274
+ # Write enhanced frame
275
+ out.write(frame)
276
+
277
+ # Update progress
278
+ frame_count += 1
279
+ progress(frame_count / total_frames)
280
+
281
+ # Release resources
282
+ cap.release()
283
+ out.release()
284
+
285
+ # Copy to final location
286
+ final_output = tempfile.mktemp(suffix='.mp4')
287
+ shutil.copy2(output_path, final_output)
288
+
289
+ return final_output, "تم تحسين الفيديو بنجاح!"
290
+
291
+ except Exception as e:
292
+ return None, f"حدث خطأ أثناء تحسين الفيديو: {str(e)}"
293
 
294
  @protected_function
295
  def process_frame(frame, source_face):
 
485
  except Exception as e:
486
  return f"فشل في إرسال التنبيه التجريبي: {str(e)}"
487
 
488
+ # Initialize face analyzer
489
+ app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
490
+ app.prepare(ctx_id=-1, det_size=(640, 640))
491
+
492
+ # Initialize face swapper
493
+ def init_face_swapper():
494
+ model_path = os.path.expanduser('~/.insightface/models/inswapper_128.onnx')
495
+ model_url = "https://huggingface.co/ashleykleynhans/inswapper/resolve/main/inswapper_128.onnx"
496
+
497
+ if not os.path.exists(model_path):
498
+ print("تحميل نموذج تبديل الوجوه...")
499
+ os.makedirs(os.path.dirname(model_path), exist_ok=True)
500
+ download_with_progress(model_url, model_path)
501
+
502
+ return insightface.model_zoo.get_model(model_path, providers=['CPUExecutionProvider'])
503
+
504
+ # Initialize swapper
505
+ swapper = init_face_swapper()
506
+
507
  # Create Gradio interface
508
  with gr.Blocks(title="Vudwos") as demo:
509
  if not _app.verify_integrity():
510
  raise RuntimeError("فشل التحقق من سلامة التطبيق")
511
 
512
+ gr.Markdown("""# Vudwos - معالجة الفيديو الذكية
513
+ قم بتحميل صورة المصدر والفيديو لتبديل الوجوه، أو قم بتحسين جودة الفيديو
514
  """)
515
 
516
+ with gr.Tabs():
517
+ with gr.TabItem("🎭 تبديل الوجوه"):
518
+ with gr.Row():
519
+ with gr.Column():
520
+ source_img = gr.Image(label="صورة المصدر")
521
+ video_input = gr.Video(label="الفيديو")
522
+ submit_btn = gr.Button("بدء التحويل")
523
+
524
+ with gr.Column():
525
+ video_output = gr.Video(label="الفيديو المحول")
526
+ status_text = gr.Textbox(label="الحالة", interactive=False)
527
+
528
+ with gr.TabItem("✨ تحسين الفيديو"):
529
+ with gr.Row():
530
+ with gr.Column():
531
+ enhance_video_input = gr.Video(label="الفيديو المراد تحسينه")
532
+ enhancement_type = gr.Radio(
533
+ choices=["all", "denoise", "sharpen", "contrast"],
534
+ value="all",
535
+ label="نوع التحسين",
536
+ info="""
537
+ - all: كل التحسينات
538
+ - denoise: إزالة التشويش
539
+ - sharpen: زيادة الحدة
540
+ - contrast: تحسين التباين
541
+ """
542
+ )
543
+ enhance_btn = gr.Button("تحسين الفيديو")
544
+
545
+ with gr.Column():
546
+ enhanced_video_output = gr.Video(label="الفيديو المحسن")
547
+ enhance_status = gr.Textbox(label="الحالة", interactive=False)
548
+
549
  with gr.Row():
550
  donate_btn = gr.Button("💝 تبرع للمشروع")
551
  verify_btn = gr.Button("✅ تحقق من التبرع")
 
558
  outputs=[video_output, status_text]
559
  )
560
 
561
+ enhance_btn.click(
562
+ fn=enhance_video,
563
+ inputs=[enhance_video_input, enhancement_type],
564
+ outputs=[enhanced_video_output, enhance_status]
565
+ )
566
+
567
  donate_btn.click(
568
  fn=open_donation,
569
  inputs=[],