EngReem85 commited on
Commit
8313df0
·
verified ·
1 Parent(s): 15dfdee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -13
app.py CHANGED
@@ -4,10 +4,10 @@ import tensorflow as tf
4
  import cv2
5
  from tensorflow.keras import datasets, layers, models
6
  import os
7
- import spaces # <--- 1. استيراد مكتبة spaces
8
 
9
  # ============================================
10
- # 1. تحميل النموذج في النطاق العام (مرة واحدة فقط)
11
  # ============================================
12
  model_path = 'mnist_cnn_model.keras'
13
 
@@ -42,24 +42,50 @@ else:
42
  test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
43
 
44
  # ============================================
45
- # 3. دوال التنبؤ والمثال العشوائي
46
  # ============================================
47
- # --- الدالة التي تستخدم GPU يتم تزيينها بـ @spaces.GPU ---
48
  @spaces.GPU
49
  def predict_sketch(image):
50
  try:
51
- gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
 
 
 
 
 
 
52
  resized = cv2.resize(gray, (28, 28))
53
- inverted = 255 - resized
54
- normalized = inverted.astype('float32') / 255.0
55
- reshaped = normalized.reshape(1, 28, 28, 1)
56
 
57
- pred = model.predict(reshaped, verbose=0)[0]
58
- return {str(i): float(pred[i]) for i in range(10)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  except Exception as e:
60
  return {"خطأ": str(e)}
61
 
62
- # --- هذه الدالة لا تحتاج GPU، لذا لا تزينها ---
 
 
63
  def random_example():
64
  idx = np.random.randint(0, len(test_images))
65
  img = test_images[idx].reshape(28, 28)
@@ -67,7 +93,7 @@ def random_example():
67
  return img_rgb, f"الرقم الحقيقي: {test_labels[idx]}"
68
 
69
  # ============================================
70
- # 4. بناء واجهة Gradio
71
  # ============================================
72
  with gr.Blocks(title="MNIST Recognizer") as demo:
73
  gr.Markdown("# 🧠 التعرف على الأرقام المكتوبة بخط اليد")
@@ -88,6 +114,6 @@ with gr.Blocks(title="MNIST Recognizer") as demo:
88
  random_btn.click(fn=random_example, inputs=[], outputs=[sketch, info])
89
 
90
  # ============================================
91
- # 5. 🔥 التشغيل: يجب أن يكون في النطاق العام (بدون if __name__)
92
  # ============================================
93
  demo.launch()
 
4
  import cv2
5
  from tensorflow.keras import datasets, layers, models
6
  import os
7
+ import spaces
8
 
9
  # ============================================
10
+ # 1. تحميل أو بناء النموذج
11
  # ============================================
12
  model_path = 'mnist_cnn_model.keras'
13
 
 
42
  test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
43
 
44
  # ============================================
45
+ # 3. دالة معالجة الصورة والتنبؤ (ذكية)
46
  # ============================================
 
47
  @spaces.GPU
48
  def predict_sketch(image):
49
  try:
50
+ # 1. تحويل إلى تدرج رمادي
51
+ if len(image.shape) == 3:
52
+ gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
53
+ else:
54
+ gray = image
55
+
56
+ # 2. تغيير الحجم إلى 28x28
57
  resized = cv2.resize(gray, (28, 28))
 
 
 
58
 
59
+ # 3. تطبيع القيم إلى [0,1]
60
+ normalized = resized.astype('float32') / 255.0
61
+
62
+ # 4. **المعالجة الذكية: نحاول كلا الاتجاهين ونأخذ الأفضل**
63
+ # MNIST تدربت على خلفية سوداء (0) وأرقام بيضاء (1)
64
+ # لكن Sketchpad قد يعطي خلفية بيضاء وأرقام سوداء
65
+
66
+ # الخيار 1: الصورة كما هي (افتراض أن الخلفية سوداء والرقم أبيض)
67
+ img1 = normalized.reshape(1, 28, 28, 1)
68
+ pred1 = model.predict(img1, verbose=0)[0]
69
+
70
+ # الخيار 2: قلب الألوان (افتراض أن الخلفية بيضاء والرقم أسود)
71
+ img2 = (1 - normalized).reshape(1, 28, 28, 1)
72
+ pred2 = model.predict(img2, verbose=0)[0]
73
+
74
+ # اختيار النتيجة ذات الثقة الأعلى
75
+ max_conf1 = np.max(pred1)
76
+ max_conf2 = np.max(pred2)
77
+
78
+ if max_conf1 >= max_conf2:
79
+ return {str(i): float(pred1[i]) for i in range(10)}
80
+ else:
81
+ return {str(i): float(pred2[i]) for i in range(10)}
82
+
83
  except Exception as e:
84
  return {"خطأ": str(e)}
85
 
86
+ # ============================================
87
+ # 4. دالة المثال العشوائي
88
+ # ============================================
89
  def random_example():
90
  idx = np.random.randint(0, len(test_images))
91
  img = test_images[idx].reshape(28, 28)
 
93
  return img_rgb, f"الرقم الحقيقي: {test_labels[idx]}"
94
 
95
  # ============================================
96
+ # 5. بناء واجهة Gradio
97
  # ============================================
98
  with gr.Blocks(title="MNIST Recognizer") as demo:
99
  gr.Markdown("# 🧠 التعرف على الأرقام المكتوبة بخط اليد")
 
114
  random_btn.click(fn=random_example, inputs=[], outputs=[sketch, info])
115
 
116
  # ============================================
117
+ # 6. تشغيل التطبيق (في النطاق العام لـ ZeroGPU)
118
  # ============================================
119
  demo.launch()