File size: 5,551 Bytes
6cff877
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import os
import cv2
import gradio as gr
import numpy as np
from PIL import Image
from insightface.app import FaceAnalysis
from insightface.model_zoo import get_model
from huggingface_hub import hf_hub_download
import tempfile

# --- 1. تجهيز الموديلات (طريقة hf_hub الرسمية) ---
print("--- جاري التحقق من الموديلات ---")

try:
    # تحميل موديل التبديل (inswapper_128)
    model_path = hf_hub_download(
        repo_id="ezioruan/inswapper_128.onnx",
        filename="inswapper_128.onnx",
        local_dir=os.path.expanduser("~/.insightface/models"),
        local_dir_use_symlinks=False
    )
except Exception as e:
    print(f"❌ خطأ في تحميل الموديل: {e}")
    model_path = None

# تهيئة محرك تحليل الوجوه - تم تقليل det_size لتسريع الـ CPU
print("--- تهيئة FaceAnalysis (Optimization: 320x320) ---")
face_app = FaceAnalysis(name='buffalo_l', providers=['CPUExecutionProvider'])
face_app.prepare(ctx_id=0, det_size=(320, 320))

# تحميل المبدل مع التحقق من المسار
swapper = None
if model_path and os.path.exists(model_path):
    try:
        swapper = get_model(model_path, download=False)
        print("✅ تم تحميل Swapper بنجاح")
    except Exception as e:
        print(f"❌ فشل تحميل Swapper: {e}")

# --- 2. منطق المعالجة الأساسي ---

def process_video(source_img, target_video, progress=gr.Progress()):
    if swapper is None:
        return None, "❌ عذراً، موديل التبديل غير جاهز حالياً."
    
    if source_img is None or target_video is None:
        return None, "⚠️ يرجى رفع الصورة والفيديو أولاً."

    # تحويل الصورة المصدر واستخراج الوجه الأول
    face_img = cv2.cvtColor(np.array(source_img), cv2.COLOR_RGB2BGR)
    source_faces = face_app.get(face_img)
    
    if len(source_faces) == 0:
        return None, "❌ لم يتم العثور على وجه واضح في صورتك."
    
    # نأخذ أول وجه تم العثور عليه
    source_face = source_faces[0]

    # إعداد الفيديو
    cap = cv2.VideoCapture(target_video)
    fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    # ملف مؤقت للنتيجة
    output_path = tempfile.mktemp(suffix='.mp4')
    fourcc = cv2.VideoWriter_fourcc(*'mp4v') 
    out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

    frame_count = 0
    try:
        while cap.isOpened():
            ret, frame = cap.read()
            if not ret:
                break
            
            # تحليل الوجوه في الفريم (تبديل أول وجه يظهر فقط لتسريع العملية)
            target_faces = face_app.get(frame)
            if target_faces:
                # نبدل أول وجه فقط المكتشف في الفيديو لتقليل زمن المعالجة على CPU
                frame = swapper.get(frame, target_faces[0], source_face, paste_back=True)
            
            out.write(frame)
            frame_count += 1
            
            if frame_count % 5 == 0:
                percent = int((frame_count / total_frames) * 100)
                progress(frame_count / total_frames, desc=f"🎬 جاري المعالجة: {percent}%")

    except Exception as e:
        return None, f"🔥 خطأ تقني: {str(e)}"
    finally:
        cap.release()
        out.release()
    
    return output_path, "✅ اكتملت المعالجة! لاحظ أن الجودة مرتبطة بدقة الكشف (320px)."

# --- 3. واجهة المستخدم الرسومية ---
css = """
.upload-box { border: 2px dashed #4f46e5; border-radius: 15px; padding: 15px; background: #f9fafb; }
#mix-btn { background: linear-gradient(90deg, #4f46e5, #7c3aed); color: white; border-radius: 10px; font-weight: bold; }
.warning-text { color: #ef4444; font-weight: bold; text-align: center; }
"""

with gr.Blocks(css=css, theme=gr.themes.Soft(primary_hue="indigo")) as demo:
    gr.HTML("""
        <div style="text-align: center; padding: 10px;">
            <h1 style="color: #4f46e5; margin-bottom: 5px;">🎭 AI Face Mix Pro</h1>
            <p style="color: #666;">أداة تبديل الوجوه المتقدمة (نسخة CPU المحسنة)</p>
        </div>
    """)
    
    with gr.Row():
        with gr.Column():
            with gr.Group(elem_classes="upload-box"):
                source_image = gr.Image(label="📸 ارفع صورتك الشخصية", type="pil")
                target_vid = gr.Video(label="🎬 ارفع فيديو المشهد")
            
            gr.Markdown("⚠️ **تنبيه:** بما أنك تستخدم النسخة المجانية، المعالجة قد تستغرق وقتاً طويلاً حسب طول الفيديو.", elem_classes="warning-text")
            mix_btn = gr.Button("🚀 ابدأ الخلط الآن", elem_id="mix-btn")
        
        with gr.Column():
            output_vid = gr.Video(label="✨ النتيجة النهائية")
            status = gr.Textbox(label="📡 حالة النظام", interactive=False)

    mix_btn.click(
        fn=process_video,
        inputs=[source_image, target_vid],
        outputs=[output_vid, status]
    )

if __name__ == "__main__":
    demo.launch()