EngReem85 commited on
Commit
911101b
·
verified ·
1 Parent(s): 9b33c41

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -10
app.py CHANGED
@@ -35,21 +35,29 @@ def ensure_model_exists():
35
 
36
  ensure_model_exists()
37
 
 
 
 
 
 
38
  # ============================================
39
- # 2. دالة معالجة الصورة
40
  # ============================================
41
  def process_image_for_mnist(image_input):
 
42
  if image_input is None:
43
  return None, None
44
 
45
  if isinstance(image_input, dict):
46
- image = image_input.get('composite', None) or image_input.get('background', None)
 
 
47
  if image is None and len(image_input) > 0:
48
  image = list(image_input.values())[0]
49
  else:
50
  image = image_input
51
 
52
- if image is None or not isinstance(image, np.ndarray):
53
  return None, None
54
 
55
  if len(image.shape) == 3 and image.shape[-1] == 4:
@@ -71,7 +79,6 @@ def process_image_for_mnist(image_input):
71
 
72
  return normalized, reshaped
73
 
74
- # Variable لحفظ النموذج داخل الـ GPU Worker
75
  loaded_model = None
76
 
77
  # ============================================
@@ -81,18 +88,17 @@ loaded_model = None
81
  def predict_sketch(image):
82
  global loaded_model
83
  try:
 
84
  if image is None:
85
- return {}, None, "⚠️ يرجى الرسم في المربع أولاً!"
86
 
87
  normalized, reshaped = process_image_for_mnist(image)
88
 
89
  if normalized is None:
90
  return {}, None, "⚠️ تعذر معالجة الصورة المدخلة."
91
 
92
- # تحميل TensorFlow وتكوين الـ GPU ديناميكياً داخل بيئة ZeroGPU فقط
93
  import tensorflow as tf
94
 
95
- # تهيئة نمو الذاكرة لتفادي انهيار CUDA memory allocation
96
  gpus = tf.config.list_physical_devices('GPU')
97
  if gpus:
98
  try:
@@ -104,7 +110,6 @@ def predict_sketch(image):
104
  if loaded_model is None:
105
  loaded_model = tf.keras.models.load_model(model_path)
106
 
107
- # التوقع
108
  preds = loaded_model(reshaped, training=False).numpy()[0]
109
  predicted_class = int(np.argmax(preds))
110
  confidence = float(np.max(preds))
@@ -130,7 +135,17 @@ def predict_sketch(image):
130
  return {}, None, f"❌ خطأ أثناء التوقّع: {str(e)}"
131
 
132
  # ============================================
133
- # 4. بناء واجهة Gradio
 
 
 
 
 
 
 
 
 
 
134
  # ============================================
135
  with gr.Blocks(title="MNIST Recognizer on ZeroGPU") as demo:
136
  gr.Markdown("# 🧠 التعرف على الأرقام المكتوبة بخط اليد (ZeroGPU)")
@@ -138,17 +153,26 @@ with gr.Blocks(title="MNIST Recognizer on ZeroGPU") as demo:
138
  with gr.Row():
139
  with gr.Column(scale=1):
140
  sketch = gr.Sketchpad(label="✏️ منطقة الرسم")
141
- submit_btn = gr.Button("🔮 توقع", variant="primary")
 
 
142
  info = gr.Textbox(label="📌 معلومات التصحيح", interactive=False, lines=8)
143
 
144
  with gr.Column(scale=1):
145
  output = gr.Label(num_top_classes=3, label="📊 احتمالات التوقع")
146
  processed_img = gr.Image(label="🖼️ الصورة بعد المعالجة", image_mode="L")
147
 
 
148
  submit_btn.click(
149
  fn=predict_sketch,
150
  inputs=sketch,
151
  outputs=[output, processed_img, info]
152
  )
 
 
 
 
 
 
153
 
154
  demo.launch()
 
35
 
36
  ensure_model_exists()
37
 
38
+ # تحميل بيانات الاختبار للأمثلة العشوائية
39
+ import tensorflow as tf
40
+ (_, _), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
41
+ test_images_norm = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255.0
42
+
43
  # ============================================
44
+ # 2. دالة معالجة الصورة الآمنة
45
  # ============================================
46
  def process_image_for_mnist(image_input):
47
+ # التحقق الآمن من الصفر/الغياب بدون تقييم المصفوفة كـ Boolean
48
  if image_input is None:
49
  return None, None
50
 
51
  if isinstance(image_input, dict):
52
+ image = image_input.get('composite', None)
53
+ if image is None:
54
+ image = image_input.get('background', None)
55
  if image is None and len(image_input) > 0:
56
  image = list(image_input.values())[0]
57
  else:
58
  image = image_input
59
 
60
+ if image is None or not isinstance(image, np.ndarray) or image.size == 0:
61
  return None, None
62
 
63
  if len(image.shape) == 3 and image.shape[-1] == 4:
 
79
 
80
  return normalized, reshaped
81
 
 
82
  loaded_model = None
83
 
84
  # ============================================
 
88
  def predict_sketch(image):
89
  global loaded_model
90
  try:
91
+ # إصلاح سبب الخطأ: استخدام size أو is None بشكل صريح
92
  if image is None:
93
+ return {}, None, "⚠️ يرجى الرسم في المربع أو اختيار مثال أولاً!"
94
 
95
  normalized, reshaped = process_image_for_mnist(image)
96
 
97
  if normalized is None:
98
  return {}, None, "⚠️ تعذر معالجة الصورة المدخلة."
99
 
 
100
  import tensorflow as tf
101
 
 
102
  gpus = tf.config.list_physical_devices('GPU')
103
  if gpus:
104
  try:
 
110
  if loaded_model is None:
111
  loaded_model = tf.keras.models.load_model(model_path)
112
 
 
113
  preds = loaded_model(reshaped, training=False).numpy()[0]
114
  predicted_class = int(np.argmax(preds))
115
  confidence = float(np.max(preds))
 
135
  return {}, None, f"❌ خطأ أثناء التوقّع: {str(e)}"
136
 
137
  # ============================================
138
+ # 4. دالة اختيار مثال عشوائي (تمت إعادتها)
139
+ # ============================================
140
+ def random_example():
141
+ idx = np.random.randint(0, len(test_images))
142
+ img = test_images[idx]
143
+ img_large = cv2.resize(img, (280, 280), interpolation=cv2.INTER_NEAREST)
144
+ img_rgb = np.stack([img_large] * 3, axis=2)
145
+ return img_rgb, f"🎲 تم اختيار رقم عشوائي (الرقم الحقيقي: {test_labels[idx]})"
146
+
147
+ # ============================================
148
+ # 5. بناء واجهة Gradio
149
  # ============================================
150
  with gr.Blocks(title="MNIST Recognizer on ZeroGPU") as demo:
151
  gr.Markdown("# 🧠 التعرف على الأرقام المكتوبة بخط اليد (ZeroGPU)")
 
153
  with gr.Row():
154
  with gr.Column(scale=1):
155
  sketch = gr.Sketchpad(label="✏️ منطقة الرسم")
156
+ with gr.Row():
157
+ submit_btn = gr.Button("🔮 توقع", variant="primary")
158
+ random_btn = gr.Button("🎲 مثال عشوائي", variant="secondary")
159
  info = gr.Textbox(label="📌 معلومات التصحيح", interactive=False, lines=8)
160
 
161
  with gr.Column(scale=1):
162
  output = gr.Label(num_top_classes=3, label="📊 احتمالات التوقع")
163
  processed_img = gr.Image(label="🖼️ الصورة بعد المعالجة", image_mode="L")
164
 
165
+ # ربط الأحداث
166
  submit_btn.click(
167
  fn=predict_sketch,
168
  inputs=sketch,
169
  outputs=[output, processed_img, info]
170
  )
171
+
172
+ random_btn.click(
173
+ fn=random_example,
174
+ inputs=[],
175
+ outputs=[sketch, info]
176
+ )
177
 
178
  demo.launch()