IDS75912 commited on
Commit
521c944
·
1 Parent(s): 27384f5
Files changed (1) hide show
  1. main.py +20 -7
main.py CHANGED
@@ -46,15 +46,28 @@ app.add_middleware(
46
 
47
  ANIMALS = ['Cat', 'Dog', 'Panda'] # Animal names here, these represent the labels of the images that we trained our model on.
48
 
49
- # 1) download your SavedModel from the Hub:
50
- # so refer to the repository where your model is, not the one for the space!
51
  repo_id = "IDS75912/masterclass-2025"
52
- hf_hub_download(repo_id, filename="config.json", repo_type="model", local_dir="./model")
53
- hf_hub_download(repo_id, filename="metadata.json", repo_type="model", local_dir="./model")
54
- hf_hub_download(repo_id, filename="model.weights.h5", repo_type="model", local_dir="./model")
 
 
 
 
 
 
 
 
 
55
 
56
  # 2) load it
57
- model = tf.keras.models.load_model("./model")
 
 
 
 
58
 
59
 
60
 
@@ -76,7 +89,7 @@ async def uploadImage(img: UploadFile = File(...)):
76
  @app.get("/")
77
  def read_root() -> Dict[str, Any]:
78
  """Root endpoint."""
79
- return {"message": "Hello from FastAPI in the 'aai9' conda env"}
80
 
81
 
82
  # @app.post("/echo")
 
46
 
47
  ANIMALS = ['Cat', 'Dog', 'Panda'] # Animal names here, these represent the labels of the images that we trained our model on.
48
 
49
+ # 1) download your SavedModel from the Hub into a writable directory (Spaces often
50
+ # run with the repository checkout read-only). Prefer TMPDIR or /tmp.
51
  repo_id = "IDS75912/masterclass-2025"
52
+ local_model_dir = os.environ.get('HF_MODEL_DIR') or os.environ.get('TMPDIR') or '/tmp/model'
53
+
54
+ # Ensure the directory exists and is writable. If creating fails, raise a clear error.
55
+ try:
56
+ os.makedirs(local_model_dir, exist_ok=True)
57
+ except PermissionError:
58
+ raise RuntimeError(f"Cannot create model directory '{local_model_dir}'. Ensure the process has write access or set HF_MODEL_DIR to a writable path.")
59
+
60
+ # download files into local_model_dir
61
+ hf_hub_download(repo_id, filename="config.json", repo_type="model", local_dir=local_model_dir)
62
+ hf_hub_download(repo_id, filename="metadata.json", repo_type="model", local_dir=local_model_dir)
63
+ hf_hub_download(repo_id, filename="model.weights.h5", repo_type="model", local_dir=local_model_dir)
64
 
65
  # 2) load it
66
+ # If the hub returns an unpacked model folder, point load_model at that directory.
67
+ try:
68
+ model = tf.keras.models.load_model(local_model_dir)
69
+ except (IOError, OSError, ValueError) as e:
70
+ raise RuntimeError(f"Failed to load model from '{local_model_dir}': {e}")
71
 
72
 
73
 
 
89
  @app.get("/")
90
  def read_root() -> Dict[str, Any]:
91
  """Root endpoint."""
92
+ return {"message": "Hello from FastAPI in "}
93
 
94
 
95
  # @app.post("/echo")