Download app.py from eslamrefai22/Animal_classifier_model: direct link, hf CLI and curl.
- Browser
- Download file 5.26 kB
-
https://huggingface.co/spaces/eslamrefai22/Animal_classifier_model/resolve/main/app.py
- Command line
-
hf download hf://spaces/eslamrefai22/Animal_classifier_model/app.py
-
curl -L -o app.py https://huggingface.co/spaces/eslamrefai22/Animal_classifier_model/resolve/main/app.py
5.26 kB
| import os | |
| import pickle | |
| import threading | |
| import webbrowser | |
| import numpy as np | |
| from flask import Flask, request, render_template, url_for | |
| from werkzeug.utils import secure_filename | |
| from PIL import Image | |
| # --------------------------------------------------------------------------- | |
| # إعدادات عامة | |
| # --------------------------------------------------------------------------- | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| MODEL_DIR = os.path.join(BASE_DIR, "model") | |
| UPLOAD_FOLDER = os.path.join(BASE_DIR, "static", "uploads") | |
| ALLOWED_EXTENSIONS = {"png", "jpg", "jpeg"} | |
| IMG_SIZE = (224, 224) # غيّرها لو الموديل اتدرب على مقاس مختلف | |
| os.makedirs(UPLOAD_FOLDER, exist_ok=True) | |
| app = Flask(__name__) | |
| app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER | |
| app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 # حد أقصى 16MB للصورة المرفوعة | |
| # --------------------------------------------------------------------------- | |
| # تحميل أسماء الأصناف (class_names.pkl) | |
| # --------------------------------------------------------------------------- | |
| with open(os.path.join(MODEL_DIR, "class_names.pkl"), "rb") as f: | |
| CLASS_NAMES = pickle.load(f) | |
| # --------------------------------------------------------------------------- | |
| # تحميل الموديل: بيفضّل نسخة TFLite المضغوطة لو موجودة، وإلا يرجع لموديل Keras الكامل | |
| # --------------------------------------------------------------------------- | |
| TFLITE_PATH = os.path.join(MODEL_DIR, "animal_model.tflite") | |
| KERAS_PKL_PATH = os.path.join(MODEL_DIR, "Animal_model.pkl") | |
| USE_TFLITE = os.path.exists(TFLITE_PATH) | |
| if USE_TFLITE: | |
| import tensorflow as tf | |
| interpreter = tf.lite.Interpreter(model_path=TFLITE_PATH) | |
| interpreter.allocate_tensors() | |
| input_details = interpreter.get_input_details() | |
| output_details = interpreter.get_output_details() | |
| def predict(img_array): | |
| interpreter.set_tensor(input_details[0]["index"], img_array.astype(input_details[0]["dtype"])) | |
| interpreter.invoke() | |
| return interpreter.get_tensor(output_details[0]["index"])[0] | |
| else: | |
| # يتطلب تثبيت tensorflow/keras (موضّح في requirements.txt) | |
| with open(KERAS_PKL_PATH, "rb") as f: | |
| model = pickle.load(f) | |
| def predict(img_array): | |
| return model.predict(img_array, verbose=0)[0] | |
| # --------------------------------------------------------------------------- | |
| # دوال مساعدة | |
| # --------------------------------------------------------------------------- | |
| def allowed_file(filename: str) -> bool: | |
| return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS | |
| def prepare_image(image_path: str) -> np.ndarray: | |
| # ملحوظة: الموديل نفسه فيه طبقة Rescaling(1/255) + Normalization جواه | |
| # (اتأكدنا من ده من config.json المخزّن جوه الـ pkl)، فمينفعش نقسم على | |
| # 255 هنا تاني، وإلا القيم بتتقسم مرتين والموديل بيدي تنبؤات غلط. | |
| img = Image.open(image_path).convert("RGB").resize(IMG_SIZE) | |
| arr = np.array(img, dtype=np.float32) # يفضل بين 0 و 255 زي ما الموديل متوقع | |
| return np.expand_dims(arr, axis=0) | |
| # --------------------------------------------------------------------------- | |
| # الـ Routes | |
| # --------------------------------------------------------------------------- | |
| def index(): | |
| prediction = None | |
| confidence = None | |
| image_url = None | |
| if request.method == "POST": | |
| file = request.files.get("image") | |
| if file is None or file.filename == "": | |
| return render_template("index.html", error="من فضلك اختر صورة أولاً.") | |
| if not allowed_file(file.filename): | |
| return render_template("index.html", error="امتداد الصورة غير مدعوم (png / jpg / jpeg فقط).") | |
| filename = secure_filename(file.filename) | |
| save_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) | |
| file.save(save_path) | |
| img_array = prepare_image(save_path) | |
| preds = predict(img_array) | |
| class_index = int(np.argmax(preds)) | |
| prediction = CLASS_NAMES[class_index] | |
| confidence = round(float(np.max(preds)) * 100, 2) | |
| image_url = url_for("static", filename=f"uploads/{filename}") | |
| return render_template( | |
| "index.html", | |
| prediction=prediction, | |
| confidence=confidence, | |
| image_url=image_url, | |
| ) | |
| def open_browser(): | |
| """ | |
| بيفتح الرابط في المتصفح الحقيقي بتاع الجهاز (كروم/إيدج/فايرفوكس) | |
| بدل ما VSCode يفتحه جوه الـ Simple Browser المدمج فيه. | |
| """ | |
| webbrowser.open_new_tab("http://127.0.0.1:5000") | |
| if __name__ == "__main__": | |
| # WERKZEUG_RUN_MAIN بتتحدد لو الـ reloader بتاع Flask بيشغل نسخة تانية | |
| # من البروسيس، فبنفتح المتصفح مرة واحدة بس مش مرتين | |
| if os.environ.get("WERKZEUG_RUN_MAIN") != "true": | |
| threading.Timer(1.0, open_browser).start() | |
| app.run(debug=True) | |