rehaan commited on
Commit
b8132d8
·
1 Parent(s): 3d7d8b7

Refactor model loading logic and improve error handling in app.py; add new .codex file

Browse files
Files changed (4) hide show
  1. .codex +0 -0
  2. __pycache__/app.cpython-314.pyc +0 -0
  3. app.py +35 -10
  4. requirements.txt +2 -1
.codex ADDED
File without changes
__pycache__/app.cpython-314.pyc ADDED
Binary file (10.2 kB). View file
 
app.py CHANGED
@@ -13,6 +13,7 @@ import logging
13
  import numpy as np
14
  import requests
15
  from io import BytesIO
 
16
 
17
 
18
  # =============================================================================
@@ -28,19 +29,38 @@ logger = logging.getLogger(__name__)
28
  # =============================================================================
29
 
30
  MODEL_NAME = "datdevsteve/dinov2-nivra-finetuned"
 
 
 
 
31
 
32
- logger.info(f"[i] Loading model: {MODEL_NAME}")
33
 
34
- try:
35
- image_processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
36
- model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
37
- model.eval()
38
- logger.info("[i] Model loaded successfully")
39
- except Exception as e:
40
- logger.error(f"[!] Error loading model: {e}")
41
- raise
42
 
43
- id2label = model.config.id2label if hasattr(model.config, "id2label") else {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
 
45
 
46
  # =============================================================================
@@ -62,6 +82,7 @@ def classify_confidence(score: float) -> str:
62
 
63
  def predict_medical_image(image: Image.Image, top_k: int = 5) -> Dict[str, Any]:
64
  try:
 
65
  inputs = image_processor(images=image, return_tensors="pt")
66
 
67
  with torch.no_grad():
@@ -187,6 +208,10 @@ def create_demo():
187
  with gr.Blocks(title="Nivra Medical Image Classifier") as demo:
188
 
189
  gr.Markdown("# 🏥 Nivra Medical Image Classifier")
 
 
 
 
190
 
191
  with gr.Row():
192
  with gr.Column(scale=2):
 
13
  import numpy as np
14
  import requests
15
  from io import BytesIO
16
+ from threading import Lock
17
 
18
 
19
  # =============================================================================
 
29
  # =============================================================================
30
 
31
  MODEL_NAME = "datdevsteve/dinov2-nivra-finetuned"
32
+ image_processor = None
33
+ model = None
34
+ id2label = {}
35
+ model_load_lock = Lock()
36
 
 
37
 
38
+ def ensure_model_loaded() -> None:
39
+ global image_processor, model, id2label
 
 
 
 
 
 
40
 
41
+ if image_processor is not None and model is not None:
42
+ return
43
+
44
+ with model_load_lock:
45
+ if image_processor is not None and model is not None:
46
+ return
47
+
48
+ logger.info(f"[i] Loading model: {MODEL_NAME}")
49
+
50
+ try:
51
+ image_processor = AutoImageProcessor.from_pretrained(MODEL_NAME)
52
+ model = AutoModelForImageClassification.from_pretrained(MODEL_NAME)
53
+ model.eval()
54
+ id2label = (
55
+ model.config.id2label if hasattr(model.config, "id2label") else {}
56
+ )
57
+ logger.info("[i] Model loaded successfully")
58
+ except Exception as e:
59
+ logger.error(f"[!] Error loading model: {e}")
60
+ raise RuntimeError(
61
+ f"Unable to load model '{MODEL_NAME}'. Check Space network access "
62
+ f"and repository visibility. Original error: {e}"
63
+ ) from e
64
 
65
 
66
  # =============================================================================
 
82
 
83
  def predict_medical_image(image: Image.Image, top_k: int = 5) -> Dict[str, Any]:
84
  try:
85
+ ensure_model_loaded()
86
  inputs = image_processor(images=image, return_tensors="pt")
87
 
88
  with torch.no_grad():
 
208
  with gr.Blocks(title="Nivra Medical Image Classifier") as demo:
209
 
210
  gr.Markdown("# 🏥 Nivra Medical Image Classifier")
211
+ gr.Markdown(
212
+ "Upload an image or provide a public URL. "
213
+ "The model is loaded on the first prediction so the Space can start quickly."
214
+ )
215
 
216
  with gr.Row():
217
  with gr.Column(scale=2):
requirements.txt CHANGED
@@ -9,9 +9,10 @@ transformers==4.41.2
9
  numpy<2
10
 
11
  Pillow>=10.0
 
12
 
13
  # Validation / typing (3.11-compatible wheels exist)
14
  pydantic>=2.7,<3
15
 
16
  # Auth / crypto
17
- python-jose[cryptography]>=3.3.0
 
9
  numpy<2
10
 
11
  Pillow>=10.0
12
+ requests>=2.31.0
13
 
14
  # Validation / typing (3.11-compatible wheels exist)
15
  pydantic>=2.7,<3
16
 
17
  # Auth / crypto
18
+ python-jose[cryptography]>=3.3.0