EngReem85 commited on
Commit
914f0bc
·
verified ·
1 Parent(s): 66c7ba5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -69
app.py CHANGED
@@ -5,16 +5,13 @@ import cv2
5
  from tensorflow.keras import datasets, layers, models
6
  import os
7
 
8
- # ============================================
9
  # 1. تحميل أو بناء النموذج
10
- # ============================================
11
  model_path = 'mnist_cnn_model.keras'
12
-
13
  if os.path.exists(model_path):
14
  model = tf.keras.models.load_model(model_path)
15
  print("✅ تم تحميل النموذج المحفوظ.")
16
  else:
17
- print("⚠️ لم يتم العثور على النموذج، جارٍ البناء والتدريب...")
18
  model = models.Sequential([
19
  layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
20
  layers.MaxPooling2D((2, 2)),
@@ -30,79 +27,37 @@ else:
30
  (train_images, train_labels), _ = datasets.mnist.load_data()
31
  train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
32
  model.fit(train_images, train_labels, epochs=3, validation_split=0.1, verbose=1)
33
- model.save('mnist_cnn_model.keras')
34
- print("✅ تم بناء النموذج وتدريبه وحفظه.")
35
-
36
- # ============================================
37
- # 2. تحميل بيانات MNIST للأمثلة العشوائية
38
- # ============================================
39
- (_, _), (test_images, test_labels) = datasets.mnist.load_data()
40
- test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
41
 
42
- # ============================================
43
- # 3. دالة معالجة الصورة والتنبؤ
44
- # ============================================
45
  def predict_image(image):
46
- """
47
- تستقبل صورة (مرسومة أو مرفوعة)، تعالجها وتعيد الاحتمالات.
48
- """
49
  try:
50
- # إذا كانت الصورة قادمة كـ dict (من ImageEditor) نأخذ 'composite'
51
  if isinstance(image, dict):
52
  image = image['composite']
53
- # تحويل إلى تدرج رمادي
54
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
55
- # تغيير الحجم
56
  resized = cv2.resize(gray, (28, 28))
57
- # قلب الألوان (افتراض خلفية سوداء ورسم أبيض)
58
  inverted = 255 - resized
59
  normalized = inverted.astype('float32') / 255.0
60
  reshaped = normalized.reshape(1, 28, 28, 1)
61
- # التنبؤ
62
- prediction = model.predict(reshaped, verbose=0)[0]
63
- return {str(i): float(prediction[i]) for i in range(10)}
64
  except Exception as e:
65
- return {"خطأ": str(e)}
66
-
67
- # ============================================
68
- # 4. دالة المثال العشوائي
69
- # ============================================
70
- def random_example():
71
- idx = np.random.randint(0, len(test_images))
72
- img = test_images[idx].reshape(28, 28)
73
- img_rgb = np.stack([img] * 3, axis=2)
74
- # ImageEditor يتوقع dict يحتوي على 'composite'
75
- return {"composite": img_rgb}, f"الرقم الحقيقي: {test_labels[idx]}"
76
-
77
- # ============================================
78
- # 5. بناء الواجهة باستخدام gr.ImageEditor
79
- # ============================================
80
- with gr.Blocks(title="MNIST Digit Recognizer") as demo:
81
- gr.Markdown("# 🧠 التعرف على الأرقام المكتوبة بخط اليد")
82
- gr.Markdown("ارسم رقماً في المربع أو ارفع صورة، ثم اضغط **توقع**.")
83
-
84
- with gr.Row():
85
- with gr.Column(scale=1):
86
- # استخدام ImageEditor (مدعوم رسمياً للرسم)
87
- input_image = gr.ImageEditor(
88
- label="ارسم أو ارفع صورة",
89
- type="numpy",
90
- brush=gr.Brush(colors=["#FFFFFF"], default_color="#FFFFFF"),
91
- canvas_size=(280, 280)
92
- )
93
- with gr.Row():
94
- submit_btn = gr.Button("🔮 توقع", variant="primary")
95
- random_btn = gr.Button("🎲 مثال عشوائي", variant="secondary")
96
- info = gr.Textbox(label="📌 معلومات", interactive=False)
97
-
98
- with gr.Column(scale=1):
99
- output = gr.Label(num_top_classes=3, label="📊 الاحتمالات")
100
-
101
- # ربط الأزرار
102
- submit_btn.click(fn=predict_image, inputs=input_image, outputs=output)
103
- random_btn.click(fn=random_example, inputs=[], outputs=[input_image, info])
104
-
105
- # ============================================
106
- # 6. تشغيل التطبيق (بدون if __name__)
107
- # ============================================
108
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
5
  from tensorflow.keras import datasets, layers, models
6
  import os
7
 
 
8
  # 1. تحميل أو بناء النموذج
 
9
  model_path = 'mnist_cnn_model.keras'
 
10
  if os.path.exists(model_path):
11
  model = tf.keras.models.load_model(model_path)
12
  print("✅ تم تحميل النموذج المحفوظ.")
13
  else:
14
+ print("⚠️ بناء النموذج وتدريبه...")
15
  model = models.Sequential([
16
  layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
17
  layers.MaxPooling2D((2, 2)),
 
27
  (train_images, train_labels), _ = datasets.mnist.load_data()
28
  train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
29
  model.fit(train_images, train_labels, epochs=3, validation_split=0.1, verbose=1)
30
+ model.save(model_path)
31
+ print("✅ تم حفظ النموذج.")
 
 
 
 
 
 
32
 
33
+ # 2. دالة التنبؤ
 
 
34
  def predict_image(image):
 
 
 
35
  try:
36
+ # إذا كانت الصورة قادمة من ImageEditor كـ dict
37
  if isinstance(image, dict):
38
  image = image['composite']
 
39
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
 
40
  resized = cv2.resize(gray, (28, 28))
 
41
  inverted = 255 - resized
42
  normalized = inverted.astype('float32') / 255.0
43
  reshaped = normalized.reshape(1, 28, 28, 1)
44
+ pred = model.predict(reshaped, verbose=0)[0]
45
+ return {str(i): float(pred[i]) for i in range(10)}
 
46
  except Exception as e:
47
+ return {"error": str(e)}
48
+
49
+ # 3. إنشاء الواجهة باستخدام gr.Interface (الأكثر استقراراً)
50
+ demo = gr.Interface(
51
+ fn=predict_image,
52
+ inputs=gr.ImageEditor(
53
+ label="ارسم أو ارفع صورة",
54
+ type="numpy",
55
+ canvas_size=(280, 280)
56
+ ),
57
+ outputs=gr.Label(num_top_classes=3, label="الاحتمالات"),
58
+ title="🧠 التعرف على الأرقام المكتوبة بخط اليد",
59
+ description="ارسم رقماً (0-9) في المربع، أو ارفع صورة، واضغط Submit."
60
+ )
61
+
62
+ # 4. التشغيل (بدون أي معاملات إضافية)
63
+ demo.launch()