app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pickle
3
+ import threading
4
+ import webbrowser
5
+ import numpy as np
6
+ from flask import Flask, request, render_template, url_for
7
+ from werkzeug.utils import secure_filename
8
+ from PIL import Image
9
+
10
+ # ---------------------------------------------------------------------------
11
+ # إعدادات عامة
12
+ # ---------------------------------------------------------------------------
13
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
14
+ MODEL_DIR = os.path.join(BASE_DIR, "model")
15
+ UPLOAD_FOLDER = os.path.join(BASE_DIR, "static", "uploads")
16
+ ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"}
17
+ IMG_SIZE = (224, 224) # غيّرها لو الموديل اتدرب على مقاس مختلف
18
+
19
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
20
+
21
+ app = Flask(__name__)
22
+ app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
23
+ app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 # حد أقصى 16MB للصورة المرفوعة
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # تحميل أسماء الأصناف (class_names.pkl)
27
+ # ---------------------------------------------------------------------------
28
+ with open(os.path.join(MODEL_DIR, "class_names.pkl"), "rb") as f:
29
+ CLASS_NAMES = pickle.load(f)
30
+
31
+ # ---------------------------------------------------------------------------
32
+ # تحميل الموديل: بيفضّل نسخة TFLite المضغوطة لو موجودة، وإلا يرجع لموديل Keras الكامل
33
+ # ---------------------------------------------------------------------------
34
+ TFLITE_PATH = os.path.join(MODEL_DIR, "animal_model.tflite")
35
+ KERAS_PKL_PATH = os.path.join(MODEL_DIR, "Animal_model.pkl")
36
+
37
+ USE_TFLITE = os.path.exists(TFLITE_PATH)
38
+
39
+ if USE_TFLITE:
40
+ import tensorflow as tf
41
+ interpreter = tf.lite.Interpreter(model_path=TFLITE_PATH)
42
+ interpreter.allocate_tensors()
43
+ input_details = interpreter.get_input_details()
44
+ output_details = interpreter.get_output_details()
45
+
46
+ def predict(img_array):
47
+ interpreter.set_tensor(input_details[0]["index"], img_array.astype(input_details[0]["dtype"]))
48
+ interpreter.invoke()
49
+ return interpreter.get_tensor(output_details[0]["index"])[0]
50
+
51
+ else:
52
+ # يتطلب تثبيت tensorflow/keras (موضّح في requirements.txt)
53
+ with open(KERAS_PKL_PATH, "rb") as f:
54
+ model = pickle.load(f)
55
+
56
+ def predict(img_array):
57
+ return model.predict(img_array, verbose=0)[0]
58
+
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # دوال مساعدة
62
+ # ---------------------------------------------------------------------------
63
+ def allowed_file(filename: str) -> bool:
64
+ return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
65
+
66
+
67
+ def prepare_image(image_path: str) -> np.ndarray:
68
+ # ملحوظة: الموديل نفسه فيه طبقة Rescaling(1/255) + Normalization جواه
69
+ # (اتأكدنا من ده من config.json المخزّن جوه الـ pkl)، فمينفعش نقسم على
70
+ # 255 هنا تاني، وإلا القيم بتتقسم مرتين والموديل بيدي تنبؤات غلط.
71
+ img = Image.open(image_path).convert("RGB").resize(IMG_SIZE)
72
+ arr = np.array(img, dtype=np.float32) # يفضل بين 0 و 255 زي ما الموديل متوقع
73
+ return np.expand_dims(arr, axis=0)
74
+
75
+
76
+ # ---------------------------------------------------------------------------
77
+ # الـ Routes
78
+ # ---------------------------------------------------------------------------
79
+ @app.route("/", methods=["GET", "POST"])
80
+ def index():
81
+ prediction = None
82
+ confidence = None
83
+ image_url = None
84
+
85
+ if request.method == "POST":
86
+ file = request.files.get("image")
87
+
88
+ if file is None or file.filename == "":
89
+ return render_template("index.html", error="من فضلك اختر صورة أولاً.")
90
+
91
+ if not allowed_file(file.filename):
92
+ return render_template("index.html", error="امتداد الصورة غير مدعوم (png / jpg / jpeg فقط).")
93
+
94
+ filename = secure_filename(file.filename)
95
+ save_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
96
+ file.save(save_path)
97
+
98
+ img_array = prepare_image(save_path)
99
+ preds = predict(img_array)
100
+
101
+ class_index = int(np.argmax(preds))
102
+ prediction = CLASS_NAMES[class_index]
103
+ confidence = round(float(np.max(preds)) * 100, 2)
104
+ image_url = url_for("static", filename=f"uploads/{filename}")
105
+
106
+ return render_template(
107
+ "index.html",
108
+ prediction=prediction,
109
+ confidence=confidence,
110
+ image_url=image_url,
111
+ )
112
+
113
+
114
+ def open_browser():
115
+ """
116
+ بيفتح الرابط في المتصفح الحقيقي بتاع الجهاز (كروم/إيدج/فايرفوكس)
117
+ بدل ما VSCode يفتحه جوه الـ Simple Browser المدمج فيه.
118
+ """
119
+ webbrowser.open_new_tab("http://127.0.0.1:5000")
120
+
121
+
122
+ if __name__ == "__main__":
123
+ # WERKZEUG_RUN_MAIN بتتحدد لو الـ reloader بتاع Flask بيشغل نسخة تانية
124
+ # من البروسيس، فبنفتح المتصفح مرة واحدة بس مش مرتين
125
+ if os.environ.get("WERKZEUG_RUN_MAIN") != "true":
126
+ threading.Timer(1.0, open_browser).start()
127
+
128
+ app.run(debug=True)
model/Animal_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fbd13014e63bd50b9bd2f65e62e14b50d7fe0964e51bf2288079bdb13e2ddad2
3
+ size 273008161
model/class_names.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cd0464e8d28bf5dbd5573a95b2ac6ac9b5e66775e1d99a7b11c43a9c84410417
3
+ size 53
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Flask==3.1.3
2
+ tensorflow==2.17.0
3
+ numpy
4
+ Pillow
5
+ Werkzeug
static/css/style.css ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @import url('https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&family=Fraunces:ital,wght@0,600;0,700;1,600&display=swap');
2
+
3
+ :root {
4
+ --sand: #EDE3D0;
5
+ --sand-dark: #DCCBA6;
6
+ --savanna-green: #5C6E4A;
7
+ --clay: #B5652C;
8
+ --charcoal: #2B2620;
9
+ --cream-text: #FAF6EE;
10
+ --stripe: #3A3530;
11
+ }
12
+
13
+ * { box-sizing: border-box; }
14
+
15
+ body {
16
+ margin: 0;
17
+ min-height: 100vh;
18
+ background: var(--sand);
19
+ background-image:
20
+ repeating-linear-gradient(135deg, rgba(58,53,48,0.03) 0px, rgba(58,53,48,0.03) 2px, transparent 2px, transparent 14px);
21
+ font-family: 'Cairo', sans-serif;
22
+ color: var(--charcoal);
23
+ display: flex;
24
+ justify-content: center;
25
+ padding: 48px 20px;
26
+ }
27
+
28
+ .page {
29
+ width: 100%;
30
+ max-width: 640px;
31
+ }
32
+
33
+ .hero {
34
+ text-align: center;
35
+ margin-bottom: 32px;
36
+ }
37
+
38
+ .eyebrow {
39
+ display: inline-block;
40
+ font-size: 12px;
41
+ letter-spacing: 0.12em;
42
+ text-transform: uppercase;
43
+ color: var(--clay);
44
+ font-weight: 700;
45
+ border: 1.5px solid var(--clay);
46
+ border-radius: 999px;
47
+ padding: 4px 14px;
48
+ margin-bottom: 18px;
49
+ }
50
+
51
+ .hero h1 {
52
+ font-family: 'Fraunces', serif;
53
+ font-weight: 700;
54
+ font-size: clamp(32px, 5vw, 44px);
55
+ margin: 0 0 10px;
56
+ color: var(--charcoal);
57
+ }
58
+
59
+ .subtitle {
60
+ color: #55503f;
61
+ font-size: 16px;
62
+ margin: 0 auto;
63
+ max-width: 440px;
64
+ line-height: 1.6;
65
+ }
66
+
67
+ .panel {
68
+ background: var(--cream-text);
69
+ border: 1px solid var(--sand-dark);
70
+ border-radius: 18px;
71
+ padding: 32px;
72
+ box-shadow: 0 10px 30px rgba(43, 38, 32, 0.08);
73
+ }
74
+
75
+ .upload-form {
76
+ display: flex;
77
+ flex-direction: column;
78
+ gap: 18px;
79
+ }
80
+
81
+ .dropzone {
82
+ position: relative;
83
+ display: flex;
84
+ flex-direction: column;
85
+ align-items: center;
86
+ justify-content: center;
87
+ gap: 10px;
88
+ border: 2px dashed var(--sand-dark);
89
+ border-radius: 14px;
90
+ padding: 40px 20px;
91
+ cursor: pointer;
92
+ transition: border-color 0.2s ease, background 0.2s ease;
93
+ background: #FFFDF8;
94
+ }
95
+
96
+ .dropzone:hover {
97
+ border-color: var(--clay);
98
+ background: #FFF8ED;
99
+ }
100
+
101
+ .dropzone-icon { font-size: 28px; }
102
+
103
+ .dropzone-text {
104
+ font-weight: 600;
105
+ color: var(--charcoal);
106
+ font-size: 15px;
107
+ }
108
+
109
+ .dropzone input[type="file"] {
110
+ position: absolute;
111
+ inset: 0;
112
+ opacity: 0;
113
+ cursor: pointer;
114
+ }
115
+
116
+ .preview-img {
117
+ max-width: 100%;
118
+ max-height: 220px;
119
+ border-radius: 10px;
120
+ object-fit: contain;
121
+ box-shadow: 0 6px 18px rgba(43, 38, 32, 0.12);
122
+ }
123
+
124
+ .upload-status {
125
+ margin: 0;
126
+ text-align: center;
127
+ font-size: 14px;
128
+ font-weight: 700;
129
+ color: var(--savanna-green);
130
+ }
131
+
132
+ .btn:disabled {
133
+ opacity: 0.7;
134
+ cursor: not-allowed;
135
+ transform: none;
136
+ }
137
+
138
+ .btn {
139
+ background: var(--savanna-green);
140
+ color: var(--cream-text);
141
+ border: none;
142
+ border-radius: 10px;
143
+ padding: 14px 20px;
144
+ font-family: 'Cairo', sans-serif;
145
+ font-weight: 700;
146
+ font-size: 16px;
147
+ cursor: pointer;
148
+ transition: background 0.2s ease, transform 0.15s ease;
149
+ }
150
+
151
+ .btn:hover {
152
+ background: #4a5a3b;
153
+ transform: translateY(-1px);
154
+ }
155
+
156
+ .error {
157
+ color: #A13B2A;
158
+ background: #FBE9E3;
159
+ border: 1px solid #E7B9A9;
160
+ border-radius: 10px;
161
+ padding: 10px 14px;
162
+ margin-top: 16px;
163
+ font-weight: 600;
164
+ font-size: 14px;
165
+ }
166
+
167
+ .result {
168
+ margin-top: 28px;
169
+ display: grid;
170
+ grid-template-columns: 140px 1fr;
171
+ gap: 20px;
172
+ align-items: center;
173
+ padding-top: 24px;
174
+ border-top: 1px dashed var(--sand-dark);
175
+ }
176
+
177
+ .result-image img {
178
+ width: 100%;
179
+ aspect-ratio: 1;
180
+ object-fit: cover;
181
+ border-radius: 12px;
182
+ border: 3px solid var(--sand-dark);
183
+ }
184
+
185
+ .result-label {
186
+ font-size: 12px;
187
+ text-transform: uppercase;
188
+ letter-spacing: 0.1em;
189
+ color: var(--clay);
190
+ font-weight: 700;
191
+ }
192
+
193
+ .result-class {
194
+ font-family: 'Fraunces', serif;
195
+ font-size: 28px;
196
+ margin: 4px 0 12px;
197
+ color: var(--charcoal);
198
+ }
199
+
200
+ .confidence-bar {
201
+ background: var(--sand-dark);
202
+ border-radius: 999px;
203
+ height: 8px;
204
+ overflow: hidden;
205
+ }
206
+
207
+ .confidence-fill {
208
+ height: 100%;
209
+ background: var(--clay);
210
+ border-radius: 999px;
211
+ }
212
+
213
+ .confidence-text {
214
+ display: block;
215
+ margin-top: 8px;
216
+ font-size: 13px;
217
+ color: #55503f;
218
+ font-weight: 600;
219
+ }
220
+
221
+ .footer {
222
+ text-align: center;
223
+ margin-top: 24px;
224
+ font-size: 13px;
225
+ color: #8a8368;
226
+ letter-spacing: 0.04em;
227
+ }
228
+
229
+ @media (max-width: 480px) {
230
+ .result {
231
+ grid-template-columns: 1fr;
232
+ }
233
+ .result-image img {
234
+ max-width: 180px;
235
+ margin: 0 auto;
236
+ }
237
+ }
static/uploads/.gitkeep ADDED
File without changes
templates/index.html ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="ar" dir="rtl">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>مصنّف حيوانات السافانا</title>
7
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
8
+ </head>
9
+ <body>
10
+ <main class="page">
11
+ <header class="hero">
12
+ <span class="eyebrow">CNN · Flask Deployment</span>
13
+ <h1>مصنّف حيوانات السافانا</h1>
14
+ <p class="subtitle">ارفع صورة، والموديل هيحدد نوع الحيوان: جاموس، فيل، وحيد قرن، أو حمار وحشي.</p>
15
+ </header>
16
+
17
+ <section class="panel">
18
+ <form action="/" method="post" enctype="multipart/form-data" class="upload-form" id="uploadForm">
19
+ <label for="image" class="dropzone" id="dropzone">
20
+ <span class="dropzone-icon" id="dropzoneIcon">🐾</span>
21
+ <span class="dropzone-text" id="dropzoneText">اضغط لاختيار صورة (PNG / JPG)</span>
22
+ <img id="previewImg" class="preview-img" alt="معاينة الصورة" hidden>
23
+ <input type="file" name="image" id="image" accept=".png,.jpg,.jpeg" required>
24
+ </label>
25
+ <p class="upload-status" id="uploadStatus" hidden>✅ الصورة اترفعت، دوس "صنّف الصورة" عشان تعرف النوع</p>
26
+ <button type="submit" class="btn" id="submitBtn">صنّف الصورة</button>
27
+ </form>
28
+
29
+ {% if error %}
30
+ <p class="error">{{ error }}</p>
31
+ {% endif %}
32
+
33
+ {% if prediction %}
34
+ <div class="result">
35
+ <div class="result-image">
36
+ <img src="{{ image_url }}" alt="الصورة المرفوعة">
37
+ </div>
38
+ <div class="result-details">
39
+ <span class="result-label">النتيجة</span>
40
+ <h2 class="result-class">{{ prediction }}</h2>
41
+ <div class="confidence-bar">
42
+ <div class="confidence-fill" style="width: {{ confidence }}%;"></div>
43
+ </div>
44
+ <span class="confidence-text">نسبة الثقة: {{ confidence }}%</span>
45
+ </div>
46
+ </div>
47
+ {% endif %}
48
+ </section>
49
+
50
+ <footer class="footer">
51
+ <span>Buffalo · Elephant · Rhino · Zebra</span>
52
+ </footer>
53
+ </main>
54
+
55
+ <script>
56
+ const imageInput = document.getElementById('image');
57
+ const previewImg = document.getElementById('previewImg');
58
+ const dropzoneIcon = document.getElementById('dropzoneIcon');
59
+ const dropzoneText = document.getElementById('dropzoneText');
60
+ const uploadStatus = document.getElementById('uploadStatus');
61
+ const submitBtn = document.getElementById('submitBtn');
62
+ const uploadForm = document.getElementById('uploadForm');
63
+
64
+ // لما المستخدم يختار صورة، يظهرها فورًا كمعاينة + رسالة تأكيد
65
+ imageInput.addEventListener('change', () => {
66
+ const file = imageInput.files[0];
67
+ if (!file) return;
68
+
69
+ const reader = new FileReader();
70
+ reader.onload = (e) => {
71
+ previewImg.src = e.target.result;
72
+ previewImg.hidden = false;
73
+ dropzoneIcon.hidden = true;
74
+ dropzoneText.textContent = file.name;
75
+ uploadStatus.hidden = false;
76
+ };
77
+ reader.readAsDataURL(file);
78
+ });
79
+
80
+ // نص الزرار بيتغير وقت الإرسال، عشان تعرف إن الموديل شغال بيحلل
81
+ uploadForm.addEventListener('submit', () => {
82
+ submitBtn.textContent = 'بيتم التصنيف...';
83
+ submitBtn.disabled = true;
84
+ });
85
+ </script>
86
+ </body>
87
+ </html>