mariajessington commited on
Commit
0b10c0a
Β·
verified Β·
1 Parent(s): 31e9cbe

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +72 -73
app.py CHANGED
@@ -1,73 +1,72 @@
1
- import json
2
- import numpy as np
3
- import tensorflow as tf
4
- from PIL import Image
5
- import gradio as gr
6
-
7
- IMG_SIZE = 224
8
- MODEL_PATH = "model/animal_cnn.keras"
9
- NAMES_PATH = "model/class_names.json"
10
-
11
- # ─── Load Model ───────────────────────
12
- print("⏳ Loading model...")
13
- model = tf.keras.models.load_model(MODEL_PATH)
14
-
15
- with open(NAMES_PATH) as f:
16
- class_names = json.load(f)
17
-
18
- print("βœ… Model loaded")
19
-
20
- # ─── Emoji Map ───────────────────────
21
- EMOJI = {
22
- "cat": "🐱", "dog": "🐢", "lion": "🦁", "tiger": "🐯",
23
- "elephant": "🐘", "horse": "🐴", "bear": "🐻",
24
- "default": "🐾"
25
- }
26
-
27
- def get_emoji(label):
28
- for key in EMOJI:
29
- if key in label.lower():
30
- return EMOJI[key]
31
- return EMOJI["default"]
32
-
33
- # ─── Preprocess ──────────────────────
34
- def prepare(img):
35
- img = img.convert("RGB")
36
- img = img.resize((IMG_SIZE, IMG_SIZE))
37
- arr = np.array(img) / 255.0
38
- arr = np.expand_dims(arr, axis=0)
39
- return arr
40
-
41
- # ─── Predict Function (TOP 5) ─────────
42
- def predict(image):
43
- arr = prepare(image)
44
- preds = model.predict(arr)[0]
45
-
46
- # Top 5 predictions
47
- top_indices = np.argsort(preds)[::-1][:5]
48
-
49
- result = "🐾 **Prediction Results:**\n\n"
50
-
51
- for i, idx in enumerate(top_indices):
52
- label = class_names[idx]
53
- confidence = preds[idx] * 100
54
- emoji = get_emoji(label)
55
-
56
- if i == 0:
57
- result += f"πŸ‘‰ **{emoji} {label.title()} ({confidence:.2f}%)**\n\n"
58
- else:
59
- result += f"{emoji} {label.title()} ({confidence:.2f}%)\n"
60
-
61
- return result
62
-
63
- # ─── Gradio UI ──────────────────────
64
- app = gr.Interface(
65
- fn=predict,
66
- inputs=gr.Image(type="pil"),
67
- outputs="markdown",
68
- title="🐾 Animal Classifier",
69
- description="Upload an image β†’ AI will tell what animal it is"
70
- )
71
-
72
- # ─── Run ────────────────────────────
73
- app.launch()
 
1
+ import os
2
+ import json
3
+ import numpy as np
4
+ import tensorflow as tf
5
+ from flask import Flask, request, jsonify
6
+ from PIL import Image
7
+
8
+ app = Flask(__name__)
9
+
10
+ # βœ… Correct Paths (IMPORTANT FIX)
11
+ MODEL_PATH = "animal_cnn.keras"
12
+ CLASS_NAMES_PATH = "class_names.json"
13
+
14
+ # βœ… Load Model
15
+ print("⏳ Loading model...")
16
+ model = tf.keras.models.load_model(MODEL_PATH)
17
+
18
+ # βœ… Load Class Names
19
+ with open(CLASS_NAMES_PATH, "r") as f:
20
+ class_names = json.load(f)
21
+
22
+ print("βœ… Model loaded successfully!")
23
+
24
+
25
+ # βœ… Image Preprocessing Function
26
+ def preprocess_image(image):
27
+ image = image.resize((224, 224)) # same as training
28
+ image = np.array(image) / 255.0
29
+ image = np.expand_dims(image, axis=0)
30
+ return image
31
+
32
+
33
+ # βœ… Home Route (Test)
34
+ @app.route("/")
35
+ def home():
36
+ return "🐾 Animal Classifier API is Running!"
37
+
38
+
39
+ # βœ… Prediction Route
40
+ @app.route("/predict", methods=["POST"])
41
+ def predict():
42
+ try:
43
+ if "file" not in request.files:
44
+ return jsonify({"error": "No file uploaded"}), 400
45
+
46
+ file = request.files["file"]
47
+
48
+ # Open image
49
+ image = Image.open(file).convert("RGB")
50
+
51
+ # Preprocess
52
+ processed_image = preprocess_image(image)
53
+
54
+ # Predict
55
+ predictions = model.predict(processed_image)[0]
56
+ top_index = np.argmax(predictions)
57
+ confidence = float(predictions[top_index])
58
+
59
+ result = {
60
+ "prediction": class_names[top_index],
61
+ "confidence": round(confidence * 100, 2)
62
+ }
63
+
64
+ return jsonify(result)
65
+
66
+ except Exception as e:
67
+ return jsonify({"error": str(e)}), 500
68
+
69
+
70
+ # βœ… Run App
71
+ if __name__ == "__main__":
72
+ app.run(host="0.0.0.0", port=7860)