File size: 11,839 Bytes
f6e4978
 
 
 
4907c9e
 
ed83cdc
649533c
 
 
 
 
 
f6e4978
4907c9e
649533c
4907c9e
649533c
4907c9e
e614c70
649533c
 
 
4907c9e
e614c70
4907c9e
 
 
 
 
 
 
 
 
ed83cdc
4907c9e
 
 
 
 
 
 
 
 
 
 
ed83cdc
4907c9e
649533c
4907c9e
f6e4978
1fe6f4e
649533c
f6e4978
fa53bfa
 
 
 
f6e4978
0e03f83
 
f6e4978
4907c9e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6e4978
 
fa53bfa
 
f6e4978
fa53bfa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e03f83
 
fa53bfa
 
 
f6e4978
 
0e03f83
649533c
0e03f83
649533c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e03f83
649533c
 
 
 
 
 
0e03f83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
649533c
 
0e03f83
 
 
 
 
 
 
 
 
 
4907c9e
649533c
4907c9e
5ca6f4f
4907c9e
 
 
0e03f83
4907c9e
 
 
 
 
 
 
 
 
 
 
 
0e03f83
649533c
0e03f83
 
f6e4978
4907c9e
 
ed83cdc
649533c
0e03f83
4907c9e
0e03f83
4907c9e
 
 
 
 
 
 
 
0e03f83
 
 
 
 
4907c9e
 
 
 
 
0e03f83
4907c9e
 
 
 
fa53bfa
4907c9e
 
0e03f83
fa53bfa
4907c9e
 
 
 
 
 
0e03f83
4907c9e
f6e4978
 
0e03f83
 
 
f6e4978
4907c9e
ed83cdc
4907c9e
f6e4978
 
 
 
4907c9e
 
f6e4978
4907c9e
 
 
 
 
 
649533c
f6e4978
4907c9e
f6e4978
ed83cdc
4907c9e
0e03f83
4907c9e
 
 
 
0e03f83
f6e4978
4907c9e
 
f6e4978
4907c9e
 
 
 
fa53bfa
ed83cdc
4907c9e
f6e4978
4907c9e
 
 
 
 
 
 
f6e4978
0e03f83
 
 
4907c9e
 
 
 
f6e4978
4907c9e
 
 
f6e4978
4907c9e
 
f6e4978
4907c9e
 
 
f6e4978
4907c9e
0e03f83
 
 
4907c9e
 
f6e4978
4907c9e
 
 
 
 
 
 
 
 
 
 
f6e4978
4907c9e
 
 
 
 
 
 
f6e4978
4907c9e
 
f6e4978
4907c9e
 
f6e4978
4907c9e
0e03f83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6e4978
 
4907c9e
fa53bfa
4907c9e
0e03f83
4907c9e
 
0e03f83
f6e4978
4907c9e
0e03f83
74ac4b6
0e03f83
4907c9e
f6e4978
4907c9e
 
f6e4978
0e03f83
f6e4978
 
 
649533c
4907c9e
 
 
 
 
0e03f83
4907c9e
 
0e03f83
4907c9e
f6e4978
4907c9e
649533c
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import os
import cv2
import gradio as gr
import google.generativeai as genai
from ultralytics import YOLO
import tempfile
import torch
import spaces

import numpy as np
from PIL import Image, ImageDraw, ImageFont
import arabic_reshaper
from bidi.algorithm import get_display

# =============================
# Gemini API Key
# =============================
# ⚠️ الصق مفتاحك محليًا هنا داخل ملفك (لا تنشره بمستودع عام)
GEMINI_API_KEY = "AIzaSyAvm28ZnTMaZ1Jtg9sYM-EO4qlAN2W4BIQ"

# خيار "أقل خطورة": لو موجود Secrets/Env استخدمه بدل المكتوب
# GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") or "PASTE_YOUR_GEMINI_KEY_HERE"

genai.configure(api_key=GEMINI_API_KEY)

SYSTEM_PROMPT = (
    "لدي نص خام عبارة عن حروف عربية متتابعة بدون مسافات "
    "ومع وجود تكرار بسيط لأنه ناتج من مترجم لغة الإشارة.\n"
    "مهمتك:\n"
    "1) إزالة التكرار غير الضروري.\n"
    "2) إضافة المسافات بين الكلمات.\n"
    "3) إخراج الجملة الأقرب للمعنى.\n"
    "أعد النص فقط بدون شرح."
)

def fix_with_gemini(raw_text: str) -> str:
    if not raw_text:
        return ""
    try:
        model = genai.GenerativeModel("models/gemini-2.5-flash")
        prompt = SYSTEM_PROMPT + f"\n\nالنص الخام:\n«{raw_text}»"
        resp = model.generate_content(prompt)
        return (resp.text or "").strip()
    except Exception as e:
        return f"خطأ في Gemini: {e}"


# =============================
# إعدادات YOLO
# =============================
WEIGHTS_PATH = "best.pt"
IMG_SIZE = 1080
CONF_THRESHOLD = 0.15

MIN_STABLE_FRAMES = 1
FRAME_SKIP = 1
MAX_FRAMES = 1000
WORD_GAP_FRAMES = 10

CENTER_CROP = True

arabic_map = {
    "aleff": "ا",
    "bb": "ب",
    "ta": "ت",
    "taa": "ت",
    "thaa": "ث",
    "jeem": "ج",
    "haa": "ح",
    "khaa": "خ",
    "dal": "د",
    "dha": "ظ",
    "dhad": "ض",
    "fa": "ف",
    "gaaf": "ق",
    "ghain": "غ",
    "ha": "ه",
    "kaaf": "ك",
    "laam": "ل",
    "meem": "م",
    "nun": "ن",
    "ra": "ر",
    "saad": "ص",
    "seen": "س",
    "sheen": "ش",
    "thal": "ذ",
    "toot": "ة",
    "waw": "و",
    "ya": "ي",
    "yaa": "ي",
    "zay": "ز",
    "ain": "ع",
    "al": "ال",
    "la": "لا",
}

yolo_model = None
DEVICE = "cpu"

def get_model():
    global yolo_model, DEVICE

    if yolo_model is None:
        print("🔹 Loading YOLO model...")
        yolo_model = YOLO(WEIGHTS_PATH)
        print("📚 Classes:", yolo_model.names)

    if torch.cuda.is_available():
        if DEVICE != "cuda":
            DEVICE = "cuda"
            try:
                yolo_model.to(DEVICE)
                print("✅ YOLO model moved to cuda")
            except Exception as e:
                print("⚠️ تعذر نقل الموديل إلى cuda:", e)
    else:
        if DEVICE != "cpu":
            print("⚠️ CUDA غير متوفر، سيتم استخدام CPU.")
        DEVICE = "cpu"

    return yolo_model


# =============================
# إصلاح ????: رسم عربي على الفيديو via PIL
# =============================
FONT_PATH = os.path.join(os.path.dirname(__file__), "NotoNaskhArabic-VariableFont_wght.ttf")

def draw_arabic_text(frame_bgr, text, x, y, font_size=36, bgr_color=(0, 255, 0)):
    img = Image.fromarray(cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img)

    try:
        font = ImageFont.truetype(FONT_PATH, font_size)
    except Exception as e:
        print("⚠️ خطأ تحميل الخط العربي:", e)
        font = ImageFont.load_default()

    shaped = arabic_reshaper.reshape(text)
    rtl_text = get_display(shaped)

    rgb_color = (bgr_color[2], bgr_color[1], bgr_color[0])
    draw.text((x, y), rtl_text, font=font, fill=rgb_color)

    return cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)


# =============================
# تكبير + قص من الوسط 640x640
# =============================
def resize_and_center_crop(frame, target: int = 640):
    h, w = frame.shape[:2]
    short_side = min(w, h)
    if short_side <= 0:
        return frame

    scale = target / short_side
    new_w = int(w * scale)
    new_h = int(h * scale)

    frame = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)

    h, w = frame.shape[:2]
    x1 = max(0, (w - target) // 2)
    y1 = max(0, (h - target) // 2)
    x2 = min(x1 + target, w)
    y2 = min(y1 + target, h)

    crop = frame[y1:y2, x1:x2]

    ch, cw = crop.shape[:2]
    if ch != target or cw != target:
        crop = cv2.resize(crop, (target, target), interpolation=cv2.INTER_AREA)

    return crop


# =============================
# تجهيز الفيديو قبل المعالجة
# =============================
def preprocess_video(input_path: str, target_short_side: int = 1080, target_fps: int = 8) -> str:
    cap = cv2.VideoCapture(input_path)
    if not cap.isOpened():
        print("[preprocess] تعذر فتح الفيديو، سنستخدم الملف الأصلي كما هو.")
        return input_path

    orig_fps = cap.get(cv2.CAP_PROP_FPS)
    w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

    if orig_fps <= 0:
        frame_step = 1
        out_fps = float(target_fps)
    else:
        frame_step = max(1, int(round(orig_fps / target_fps)))
        out_fps = orig_fps / frame_step

    short_side = min(w, h)
    scale = 1.0 if short_side <= 0 else (target_short_side / short_side)
    new_w = int(w * scale)
    new_h = int(h * scale)

    fd, tmp_path = tempfile.mkstemp(suffix=".mp4")
    os.close(fd)

    out_w, out_h = (IMG_SIZE, IMG_SIZE) if CENTER_CROP else (new_w, new_h)

    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    out = cv2.VideoWriter(tmp_path, fourcc, out_fps, (out_w, out_h))

    frame_idx = 0
    while True:
        ret, frame = cap.read()
        if not ret:
            break

        if frame_idx % frame_step == 0:
            if CENTER_CROP:
                processed = resize_and_center_crop(frame, target=IMG_SIZE)
            else:
                processed = cv2.resize(frame, (new_w, new_h), interpolation=cv2.INTER_AREA)
            out.write(processed)

        frame_idx += 1

    cap.release()
    out.release()
    print(f"[preprocess] orig=({w}x{h}), new=({out_w}x{out_h}), saved={tmp_path}")
    return tmp_path


# =============================
# معالجة فريم واحد
# =============================
def detect_frame(frame_bgr):
    model = get_model()

    frame_rgb = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2RGB)
    result = model.predict(
        frame_rgb,
        conf=CONF_THRESHOLD,
        imgsz=IMG_SIZE,
        verbose=False,
        device=DEVICE,
    )[0]

    boxes = result.boxes
    num_boxes = 0 if boxes is None else len(boxes)
    print(f"[detect_frame] boxes={num_boxes}")

    if boxes is None or len(boxes) == 0:
        return [], frame_bgr

    labels = []
    for box in boxes:
        x1, y1, x2, y2 = map(int, box.xyxy[0])
        cls_id = int(box.cls[0])

        if isinstance(model.names, dict):
            eng = model.names.get(cls_id, str(cls_id))
        else:
            eng = model.names[cls_id] if cls_id < len(model.names) else str(cls_id)

        letter = arabic_map.get(eng, eng)
        labels.append(letter)

        cv2.rectangle(frame_bgr, (x1, y1), (x2, y2), (0, 255, 0), 2)
        frame_bgr = draw_arabic_text(frame_bgr, letter, x1, max(0, y1 - 45), font_size=36)

    return labels, frame_bgr


# =============================
# VIDEO → RAW TEXT + OUTPUT VIDEO + DEBUG
# =============================
def extract_and_render(video_path: str):
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        return "", None, "تعذر فتح الفيديو في extract_and_render"

    fourcc = cv2.VideoWriter_fourcc(*"mp4v")
    out_path = "processed_output.mp4"

    fps = cap.get(cv2.CAP_PROP_FPS)
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    if fps <= 0:
        fps = 8.0

    out = cv2.VideoWriter(out_path, fourcc, fps, (width, height))

    word = ""
    words = []
    last_label = None
    last_added = None
    stable = 0
    last_seen = None
    frame_index = 0

    frames_with_dets = 0
    debug_lines = []

    while True:
        ret, frame = cap.read()
        if not ret:
            break

        frame_index += 1
        if frame_index > MAX_FRAMES:
            break

        if FRAME_SKIP > 1 and frame_index % FRAME_SKIP != 0:
            continue

        frame = cv2.flip(frame, 1)
        labels, rendered = detect_frame(frame)
        out.write(rendered)

        if labels:
            frames_with_dets += 1
            debug_lines.append(f"frame {frame_index}: {labels}")

            label = labels[0]
            last_seen = frame_index

            if label == last_label:
                stable += 1
            else:
                last_label = label
                stable = 1

            if stable >= MIN_STABLE_FRAMES:
                if label != last_added:
                    word += label
                    last_added = label
                stable = 0
        else:
            if word and last_seen and (frame_index - last_seen >= WORD_GAP_FRAMES):
                words.append(word)
                word = ""
                last_label = None
                last_added = None
                stable = 0
                last_seen = None

    cap.release()
    out.release()

    if word:
        words.append(word)

    raw_text = " ".join(words).strip()

    if not debug_lines:
        debug_info = (
            f"total_frames={frame_index}, frames_with_detections=0\n"
            "لم يتم رصد أي صناديق (boxes) من YOLO في أي فريم.\n"
            "تحقق من:\n"
            "- أن best.pt هو موديل detection وتدريبه سليم.\n"
            "- أن الفيديو مشابه لتدريب الموديل من ناحية وضعية اليد والكاميرا."
        )
    else:
        sample = "\n".join(debug_lines[:30])
        debug_info = (
            f"total_frames={frame_index}, frames_with_detections={frames_with_dets}\n"
            "أمثلة من الفريمات اللي فيها حروف:\n"
            f"{sample}"
        )

    return raw_text, out_path, debug_info


# =============================
# Gradio + @spaces.GPU
# =============================
@spaces.GPU
def run(file):
    if file is None:
        return "لم يتم رفع فيديو", "", None, "لم يتم رفع فيديو"

    video_path = file.name
    light_path = preprocess_video(video_path, target_short_side=640, target_fps=8)

    raw, processed_path, debug_info = extract_and_render(light_path)
    pretty = fix_with_gemini(raw) if raw else ""

    if not raw:
        raw = "لم يتم التعرف على أي نص من الإشارات."

    return raw, pretty, processed_path, debug_info


with gr.Blocks() as demo:
    gr.Markdown("## 🤟 ASL → Arabic (YOLO + Gemini) — إصلاح ظهور الحروف العربية داخل الفيديو")

    inp = gr.File(label="ارفع فيديو الإشارة")
    raw = gr.Textbox(label="النص الخام", lines=3)
    pretty = gr.Textbox(label="النص المحسن (Gemini)", lines=3)
    video_out = gr.Video(label="الفيديو بعد البروسيس")
    debug_box = gr.Textbox(label="Debug info", lines=10)

    btn = gr.Button("ابدأ المعالجة")
    btn.click(run, inputs=[inp], outputs=[raw, pretty, video_out, debug_box])

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0", server_port=7860)