Sara-Adjo commited on
Commit
d0bb4d2
·
verified ·
1 Parent(s): 0bbc45f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -58
app.py CHANGED
@@ -1,103 +1,91 @@
1
- import os
2
- import io
3
- import base64
4
- from pathlib import Path
5
- from flask import (Flask, request, render_template,jsonify, redirect, url_for)
6
- from werkzeug.utils import secure_filename
7
- from PIL import Image
8
- from predict import predict_pytorch, predict_tensorflow
9
 
10
 
 
 
 
 
11
 
12
- app = Flask(__name__)
 
 
 
13
 
 
14
 
15
- app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024 # 5 MB upload limit
16
- ALLOWED_EXT = {"png", "jpg", "jpeg", "webp", "bmp"}
17
 
18
- PYTORCH_MODEL_PATH = os.getenv("PYTORCH_MODEL_PATH", "sara_model.pth")
19
- TF_MODEL_PATH = os.getenv("TF_MODEL_PATH", "sara_model.keras")
 
20
 
21
  CLASS_ICONS = {
22
- "buildings",
23
- "forest",
24
- "glacier",
25
- "mountain",
26
- "sea",
27
- "street",
28
  }
29
 
 
 
30
 
31
- def allowed_file(filename: str) -> bool:
32
- return ("." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXT)
33
-
34
-
35
- def image_to_b64(img: Image.Image, fmt: str = "JPEG") -> str:
36
  buf = io.BytesIO()
37
- img.convert("RGB").save(buf, format=fmt)
38
  return base64.b64encode(buf.getvalue()).decode("utf-8")
39
 
40
-
41
- # Routes
42
  @app.route("/", methods=["GET"])
43
  def index():
44
  return render_template("index.html")
45
 
46
-
47
  @app.route("/predict", methods=["POST"])
48
  def predict():
49
  model_choice = request.form.get("model", "pytorch")
50
- file = request.files.get("image")
51
 
52
  if not file or file.filename == "":
53
- return render_template("index.html", error="Please upload an image file."), 400
54
-
55
  if not allowed_file(file.filename):
56
- return render_template("index.html", error="Unsupported file type. " "Use JPG, PNG, WEBP or BMP."), 400
57
 
58
-
59
  img_bytes = file.read()
60
- pil_img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
61
-
62
- tmp_path = Path("tmp_upload.jpg")
63
- pil_img.save(tmp_path, format="JPEG")
64
 
65
  try:
66
  if model_choice == "pytorch":
67
- result = predict_pytorch(str(tmp_path),model_path=PYTORCH_MODEL_PATH)
 
 
68
  else:
69
- result = predict_tensorflow(str(tmp_path),model_path=TF_MODEL_PATH)
 
 
 
70
  except FileNotFoundError as e:
71
  tmp_path.unlink(missing_ok=True)
72
- return render_template("index.html",error=f"Model file not found: {e}. " "Train a model first."), 500
73
  except Exception as e:
74
  tmp_path.unlink(missing_ok=True)
75
- return render_template("index.html",error=f"Inference error: {e}"), 500
 
76
  finally:
77
  tmp_path.unlink(missing_ok=True)
78
 
79
- img_b64 = image_to_b64(pil_img)
80
- probs = result["all_probabilities"]
81
-
82
- # Sort by confidence descending for the bar chart
83
- sorted_probs = sorted(probs.items(), key=lambda x: -x[1])
84
-
85
- return render_template(
86
- "index.html",
87
- result = result,
88
- model_used = model_choice,
89
- img_b64 = img_b64,
90
- sorted_probs = sorted_probs,
91
- class_icons = CLASS_ICONS,
92
- )
93
 
 
 
 
94
 
95
  @app.route("/health")
96
  def health():
97
- return jsonify({"status": "ok"}), 200
98
-
99
-
100
 
101
  if __name__ == "__main__":
102
  port = int(os.getenv("PORT", 7860))
 
 
 
103
  app.run(host="0.0.0.0", port=port, debug=False)
 
 
 
 
 
 
 
 
 
1
 
2
 
3
+ import os, io, sys, base64, traceback
4
+ from pathlib import Path
5
+ from flask import Flask, request, render_template, jsonify
6
+ from PIL import Image
7
 
8
+ # Répertoire absolu contenant app.py
9
+ BASE_DIR = Path(__file__).resolve().parent
10
+ if str(BASE_DIR) not in sys.path:
11
+ sys.path.insert(0, str(BASE_DIR))
12
 
13
+ from predict import predict_pytorch, predict_tensorflow
14
 
15
+ app = Flask(__name__, template_folder=str(BASE_DIR / "templates"))
16
+ app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024
17
 
18
+ ALLOWED_EXT = {"png", "jpg", "jpeg", "webp", "bmp"}
19
+ PYTORCH_MODEL_PATH = os.getenv("PYTORCH_MODEL_PATH", str(BASE_DIR / "sara_model.pth"))
20
+ TF_MODEL_PATH = os.getenv("TF_MODEL_PATH", str(BASE_DIR / "sara_model.keras"))
21
 
22
  CLASS_ICONS = {
23
+ "buildings": "🏙️", "forest": "🌲", "glacier": "🧊",
24
+ "mountain": "🏔️", "sea": "🌊", "street": "🛣️",
 
 
 
 
25
  }
26
 
27
+ def allowed_file(filename):
28
+ return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXT
29
 
30
+ def image_to_b64(img):
 
 
 
 
31
  buf = io.BytesIO()
32
+ img.convert("RGB").save(buf, format="JPEG")
33
  return base64.b64encode(buf.getvalue()).decode("utf-8")
34
 
 
 
35
  @app.route("/", methods=["GET"])
36
  def index():
37
  return render_template("index.html")
38
 
 
39
  @app.route("/predict", methods=["POST"])
40
  def predict():
41
  model_choice = request.form.get("model", "pytorch")
42
+ file = request.files.get("image")
43
 
44
  if not file or file.filename == "":
45
+ return render_template("index.html", error="Veuillez uploader une image."), 400
 
46
  if not allowed_file(file.filename):
47
+ return render_template("index.html", error="Format non supporté. Utilisez JPG, PNG, WEBP ou BMP."), 400
48
 
 
49
  img_bytes = file.read()
50
+ pil_img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
51
+ tmp_path = BASE_DIR / "tmp_upload.jpg"
52
+ pil_img.save(str(tmp_path), format="JPEG")
 
53
 
54
  try:
55
  if model_choice == "pytorch":
56
+ if not Path(PYTORCH_MODEL_PATH).exists():
57
+ raise FileNotFoundError(f"Modèle PyTorch introuvable : {PYTORCH_MODEL_PATH}")
58
+ result = predict_pytorch(str(tmp_path), model_path=PYTORCH_MODEL_PATH)
59
  else:
60
+ if not Path(TF_MODEL_PATH).exists():
61
+ raise FileNotFoundError(f"Modèle TensorFlow introuvable : {TF_MODEL_PATH}")
62
+ result = predict_tensorflow(str(tmp_path), model_path=TF_MODEL_PATH)
63
+
64
  except FileNotFoundError as e:
65
  tmp_path.unlink(missing_ok=True)
66
+ return render_template("index.html", error=f"Modèle introuvable : {e}"), 500
67
  except Exception as e:
68
  tmp_path.unlink(missing_ok=True)
69
+ print("ERREUR INFERENCE :", traceback.format_exc())
70
+ return render_template("index.html", error=f"Erreur : {str(e)}"), 500
71
  finally:
72
  tmp_path.unlink(missing_ok=True)
73
 
74
+ img_b64 = image_to_b64(pil_img)
75
+ sorted_probs = sorted(result["all_probabilities"].items(), key=lambda x: -x[1])
 
 
 
 
 
 
 
 
 
 
 
 
76
 
77
+ return render_template("index.html",
78
+ result=result, model_used=model_choice,
79
+ img_b64=img_b64, sorted_probs=sorted_probs, class_icons=CLASS_ICONS)
80
 
81
  @app.route("/health")
82
  def health():
83
+ return jsonify({"status": "ok", "pytorch": Path(PYTORCH_MODEL_PATH).exists(),
84
+ "tensorflow": Path(TF_MODEL_PATH).exists()}), 200
 
85
 
86
  if __name__ == "__main__":
87
  port = int(os.getenv("PORT", 7860))
88
+ print(f"BASE_DIR : {BASE_DIR}")
89
+ print(f"PyTorch : {PYTORCH_MODEL_PATH} — existe : {Path(PYTORCH_MODEL_PATH).exists()}")
90
+ print(f"TF : {TF_MODEL_PATH} — existe : {Path(TF_MODEL_PATH).exists()}")
91
  app.run(host="0.0.0.0", port=port, debug=False)