EngReem85 commited on
Commit
c8e0182
·
verified ·
1 Parent(s): a5d68f6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -44
app.py CHANGED
@@ -3,13 +3,13 @@ import numpy as np
3
  import tensorflow as tf
4
  import cv2
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
- else:
 
13
  model = models.Sequential([
14
  layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
15
  layers.MaxPooling2D((2, 2)),
@@ -20,48 +20,28 @@ else:
20
  layers.Dense(10, activation='softmax')
21
  ])
22
  model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
23
- (train_images, train_labels), _ = datasets.mnist.load_data()
24
- train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
25
- model.fit(train_images, train_labels, epochs=3, validation_split=0.1, verbose=1)
26
- model.save(model_path)
27
 
28
- # ========== 2. بيانات MNIST ==========
29
- (_, _), (test_images, test_labels) = datasets.mnist.load_data()
30
- test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
31
-
32
- # ========== 3. دوال التنبؤ والعشوائي ==========
33
- def predict_sketch(image):
34
  try:
35
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
36
- resized = cv2.resize(gray, (28, 28))
37
- inverted = 255 - resized
38
- normalized = inverted.astype('float32') / 255.0
39
- reshaped = normalized.reshape(1, 28, 28, 1)
40
- pred = model.predict(reshaped, verbose=0)[0]
41
  return {str(i): float(pred[i]) for i in range(10)}
42
  except Exception as e:
43
  return {"error": str(e)}
44
 
45
- def random_example():
46
- idx = np.random.randint(0, len(test_images))
47
- img = test_images[idx].reshape(28, 28)
48
- img_rgb = np.stack([img] * 3, axis=2)
49
- return img_rgb, f"الرقم الحقيقي: {test_labels[idx]}"
50
-
51
- # ========== 4. الواجهة (بدون launch) ==========
52
- with gr.Blocks(title="MNIST Recognizer") as demo:
53
- gr.Markdown("# 🧠 التعرف على الأرقام")
54
- with gr.Row():
55
- with gr.Column():
56
- sketch = gr.Sketchpad(label="ارسم هنا")
57
- with gr.Row():
58
- submit_btn = gr.Button("توقع", variant="primary")
59
- random_btn = gr.Button("عشوائي", variant="secondary")
60
- info = gr.Textbox(label="معلومات")
61
- with gr.Column():
62
- output = gr.Label(num_top_classes=3, label="الاحتمالات")
63
- submit_btn.click(fn=predict_sketch, inputs=sketch, outputs=output)
64
- random_btn.click(fn=random_example, inputs=[], outputs=[sketch, info])
65
-
66
- # ========== 5. ❌ ممنوع استخدام launch() هنا ==========
67
- # Spaces يتولى التشغيل عبر المتغير 'demo'
 
3
  import tensorflow as tf
4
  import cv2
5
  from tensorflow.keras import datasets, layers, models
 
6
 
7
+ # تحميل النموذج (إذا لم تجده، ابنه)
8
+ try:
9
+ model = tf.keras.models.load_model('mnist_cnn_model.keras')
10
+ print("✅ تم تحميل النموذج")
11
+ except:
12
+ print("⚠️ بناء نموذج جديد...")
13
  model = models.Sequential([
14
  layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),
15
  layers.MaxPooling2D((2, 2)),
 
20
  layers.Dense(10, activation='softmax')
21
  ])
22
  model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
23
+ (x_train, y_train), _ = datasets.mnist.load_data()
24
+ x_train = x_train.reshape(-1, 28, 28, 1).astype('float32') / 255
25
+ model.fit(x_train, y_train, epochs=3, validation_split=0.1, verbose=1)
26
+ model.save('mnist_cnn_model.keras')
27
 
28
+ # دالة التنبؤ
29
+ def predict(image):
 
 
 
 
30
  try:
31
  gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
32
+ img = cv2.resize(gray, (28, 28))
33
+ img = (255 - img).astype('float32') / 255.0
34
+ img = img.reshape(1, 28, 28, 1)
35
+ pred = model.predict(img, verbose=0)[0]
 
36
  return {str(i): float(pred[i]) for i in range(10)}
37
  except Exception as e:
38
  return {"error": str(e)}
39
 
40
+ # 🔥 تعريف demo (يجب أن يكون في المستوى العام)
41
+ demo = gr.Interface(
42
+ fn=predict,
43
+ inputs=gr.Sketchpad(label="ارسم هنا"),
44
+ outputs=gr.Label(num_top_classes=3),
45
+ title="MNIST Recognizer",
46
+ description="ارسم رقماً بالماوس"
47
+ )