Mr-HASSAN commited on
Commit
e614c70
·
verified ·
1 Parent(s): 0258179

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -33
app.py CHANGED
@@ -4,6 +4,7 @@ import os
4
  import cv2
5
  import numpy as np
6
  import gradio as gr
 
7
  from ultralytics import YOLO
8
  from PIL import Image, ImageDraw, ImageFont
9
  import arabic_reshaper
@@ -13,19 +14,29 @@ import google.generativeai as genai
13
  import torch
14
 
15
  # ==========================
16
- # ⚠️ هنا تحط مفتاحك مباشرة
17
  # ==========================
18
 
19
- GEMINI_API_KEY = "YOUR_GEMINI_API_KEY_HERE" # 👈 استبدله بمفتاحك
20
-
21
  genai.configure(api_key=GEMINI_API_KEY)
22
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  # ==========================
24
  # إعدادات أداء PyTorch / GPU
25
  # ==========================
26
 
27
- # تفعيل تسريع CUDNN
28
- torch.backends.cudnn.benchmark = True
29
 
30
  DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu"
31
  USE_HALF = DEVICE.startswith("cuda")
@@ -53,10 +64,6 @@ arabic_map = {
53
  "toot": "ة", "al": "ال"
54
  }
55
 
56
- # ==========================
57
- # نص توجيهات Gemini
58
- # ==========================
59
-
60
  SYSTEM_PROMPT = (
61
  "أنت مساعد ذكي يستقبل كلمات أو جمل قصيرة قادمة من مترجم لغة "
62
  "الإشارة العربية، ودورك أن تعيد صياغتها كنص عربي واضح ومفهوم، "
@@ -64,7 +71,7 @@ SYSTEM_PROMPT = (
64
  )
65
 
66
  # ==========================
67
- # إعداد خط عربي مرة وحدة (بدون تكرار)
68
  # ==========================
69
 
70
  DEFAULT_FONT_SIZE = 24
@@ -77,21 +84,15 @@ except Exception:
77
 
78
 
79
  def prepare_arabic(text: str) -> str:
80
- """تجهيز النص العربي (reshaper + bidi) بدون رسم."""
81
  reshaped = arabic_reshaper.reshape(text)
82
  bidi_text = get_display(reshaped)
83
  return bidi_text
84
 
85
-
86
  # ==========================
87
- # رسم الديتكشن بشكل أسرع
88
  # ==========================
89
 
90
  def draw_detections(result, frame, names):
91
- """
92
- نرسم البوكسات بـ OpenCV،
93
- وبعدين نحول الصورة إلى PIL مرة واحدة ونرسم كل النصوص.
94
- """
95
  boxes = result.boxes
96
  detected_labels = []
97
 
@@ -112,7 +113,7 @@ def draw_detections(result, frame, names):
112
  ar_label = arabic_map.get(eng_label, eng_label)
113
  detected_labels.append(ar_label)
114
 
115
- # رسم البوكس
116
  cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
117
 
118
  label_bg_y1 = max(0, y1 - 35)
@@ -127,13 +128,12 @@ def draw_detections(result, frame, names):
127
 
128
  label_infos.append(
129
  (
130
- prepare_arabic(ar_label), # نص عربي جاهز للرسم
131
  x1 + 5,
132
  label_bg_y1 + 5,
133
  )
134
  )
135
 
136
- # نحول لمرة وحدة إلى PIL ونرسم كل النصوص
137
  img_pil = Image.fromarray(frame)
138
  draw = ImageDraw.Draw(img_pil)
139
 
@@ -142,7 +142,6 @@ def draw_detections(result, frame, names):
142
 
143
  return np.array(img_pil), detected_labels
144
 
145
-
146
  # ==========================
147
  # تحميل YOLO على GPU + half
148
  # ==========================
@@ -151,7 +150,6 @@ print("🔹 Loading YOLO model...")
151
  model = YOLO(WEIGHTS_PATH)
152
  model.to(DEVICE)
153
 
154
- # تفعيل half precision لو معنا GPU
155
  if USE_HALF:
156
  try:
157
  model.model.half()
@@ -161,7 +159,6 @@ if USE_HALF:
161
 
162
  print("📚 Classes:", model.names)
163
 
164
-
165
  # ==========================
166
  # Gemini API Call
167
  # ==========================
@@ -171,7 +168,6 @@ def call_gemini_on_word(word: str) -> str:
171
  return ""
172
 
173
  try:
174
- # flash سريع أصلا، نخليه كما هو
175
  model_g = genai.GenerativeModel("gemini-1.5-flash")
176
 
177
  prompt = (
@@ -185,7 +181,6 @@ def call_gemini_on_word(word: str) -> str:
185
  except Exception as e:
186
  return f"خطأ Gemini: {e}"
187
 
188
-
189
  # ==========================
190
  # معالجة الفريم
191
  # ==========================
@@ -201,12 +196,9 @@ def process_frame(
201
  if chat_history is None:
202
  chat_history = []
203
 
204
- # Gradio يعطينا RGB، نحوله BGR لـ OpenCV
205
  frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
206
- # نعكس الصورة أفقياً
207
  frame_bgr = cv2.flip(frame_bgr, 1)
208
 
209
- # YOLO على GPU + نصف دقة لو متوفر
210
  results = model.predict(
211
  frame_bgr,
212
  conf=CONF_THRESHOLD,
@@ -269,7 +261,6 @@ def process_frame(
269
  chat_history,
270
  )
271
 
272
-
273
  # ==========================
274
  # واجه�� Gradio
275
  # ==========================
@@ -317,8 +308,6 @@ with gr.Blocks() as demo:
317
  ],
318
  )
319
 
320
-
321
  if __name__ == "__main__":
322
- # لو أنت على Hugging Face Spaces وطلع لك موضوع الـ hot-reload،
323
- # نقدر نضيف باتش بسيط هنا، بس حالياً نخليها عادية:
324
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
4
  import cv2
5
  import numpy as np
6
  import gradio as gr
7
+ import gradio.utils as gr_utils
8
  from ultralytics import YOLO
9
  from PIL import Image, ImageDraw, ImageFont
10
  import arabic_reshaper
 
14
  import torch
15
 
16
  # ==========================
17
+ # ⚠️ Gemini API Key
18
  # ==========================
19
 
20
+ GEMINI_API_KEY = "YOUR_GEMINI_API_KEY_HERE" # حط المفتاح هنا
 
21
  genai.configure(api_key=GEMINI_API_KEY)
22
 
23
+ # ==========================
24
+ # Patch لمشكلة Spaces hot-reload
25
+ # ==========================
26
+
27
+ # داخل Hugging Face Spaces، SPACE_ID يكون موجود في الـ env
28
+ if os.getenv("SPACE_ID"):
29
+ def _no_watchfn_spaces(*args, **kwargs):
30
+ # نطفي الـ hot-reload اللي يسبب RuntimeError
31
+ return
32
+ # نكتب فوق الدالة الأصلية
33
+ gr_utils.watchfn_spaces = _no_watchfn_spaces
34
+
35
  # ==========================
36
  # إعدادات أداء PyTorch / GPU
37
  # ==========================
38
 
39
+ torch.backends.cudnn.benchmark = True # تسريع الـ conv على GPU
 
40
 
41
  DEVICE = "cuda:0" if torch.cuda.is_available() else "cpu"
42
  USE_HALF = DEVICE.startswith("cuda")
 
64
  "toot": "ة", "al": "ال"
65
  }
66
 
 
 
 
 
67
  SYSTEM_PROMPT = (
68
  "أنت مساعد ذكي يستقبل كلمات أو جمل قصيرة قادمة من مترجم لغة "
69
  "الإشارة العربية، ودورك أن تعيد صياغتها كنص عربي واضح ومفهوم، "
 
71
  )
72
 
73
  # ==========================
74
+ # إعداد خط عربي مرة وحدة
75
  # ==========================
76
 
77
  DEFAULT_FONT_SIZE = 24
 
84
 
85
 
86
  def prepare_arabic(text: str) -> str:
 
87
  reshaped = arabic_reshaper.reshape(text)
88
  bidi_text = get_display(reshaped)
89
  return bidi_text
90
 
 
91
  # ==========================
92
+ # رسم الديتكشن بشكل سريع
93
  # ==========================
94
 
95
  def draw_detections(result, frame, names):
 
 
 
 
96
  boxes = result.boxes
97
  detected_labels = []
98
 
 
113
  ar_label = arabic_map.get(eng_label, eng_label)
114
  detected_labels.append(ar_label)
115
 
116
+ # box
117
  cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
118
 
119
  label_bg_y1 = max(0, y1 - 35)
 
128
 
129
  label_infos.append(
130
  (
131
+ prepare_arabic(ar_label),
132
  x1 + 5,
133
  label_bg_y1 + 5,
134
  )
135
  )
136
 
 
137
  img_pil = Image.fromarray(frame)
138
  draw = ImageDraw.Draw(img_pil)
139
 
 
142
 
143
  return np.array(img_pil), detected_labels
144
 
 
145
  # ==========================
146
  # تحميل YOLO على GPU + half
147
  # ==========================
 
150
  model = YOLO(WEIGHTS_PATH)
151
  model.to(DEVICE)
152
 
 
153
  if USE_HALF:
154
  try:
155
  model.model.half()
 
159
 
160
  print("📚 Classes:", model.names)
161
 
 
162
  # ==========================
163
  # Gemini API Call
164
  # ==========================
 
168
  return ""
169
 
170
  try:
 
171
  model_g = genai.GenerativeModel("gemini-1.5-flash")
172
 
173
  prompt = (
 
181
  except Exception as e:
182
  return f"خطأ Gemini: {e}"
183
 
 
184
  # ==========================
185
  # معالجة الفريم
186
  # ==========================
 
196
  if chat_history is None:
197
  chat_history = []
198
 
 
199
  frame_bgr = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
 
200
  frame_bgr = cv2.flip(frame_bgr, 1)
201
 
 
202
  results = model.predict(
203
  frame_bgr,
204
  conf=CONF_THRESHOLD,
 
261
  chat_history,
262
  )
263
 
 
264
  # ==========================
265
  # واجه�� Gradio
266
  # ==========================
 
308
  ],
309
  )
310
 
311
+ # في Spaces ما نحتاج نحدد port غالباً
312
  if __name__ == "__main__":
313
+ demo.launch()