kamau1 commited on
Commit
28552c3
·
verified ·
1 Parent(s): 0c8b8e3

Downgrade YOLOv5 for compatibility, simplify model loading, fix Pydantic warnings, and improve error handling

Browse files
Files changed (4) hide show
  1. Dockerfile +25 -45
  2. app/models/inference.py +4 -2
  3. app/models/yolo.py +2 -18
  4. requirements.txt +1 -1
Dockerfile CHANGED
@@ -17,51 +17,31 @@ RUN pip install huggingface_hub
17
  # Create models directory
18
  RUN mkdir -p /models
19
 
20
- # Create a Python script for model downloading
21
- RUN echo 'from huggingface_hub import hf_hub_download\n\
22
- import os\n\
23
- \n\
24
- def download_model():\n\
25
- try:\n\
26
- print("Attempting to download model...")\n\
27
- hf_hub_download(\n\
28
- "seamo-ai/marina-species-v1",\n\
29
- "marina-benthic-33k.pt",\n\
30
- local_dir="/models",\n\
31
- local_dir_use_symlinks=False\n\
32
- )\n\
33
- print("Model downloaded successfully")\n\
34
- return True\n\
35
- except Exception as e:\n\
36
- print(f"Model download failed: {e}")\n\
37
- # Create a placeholder file to prevent build failure\n\
38
- with open("/models/marina-benthic-33k.pt", "w") as f:\n\
39
- f.write("placeholder")\n\
40
- print("Created placeholder model file")\n\
41
- return False\n\
42
- \n\
43
- def download_names():\n\
44
- try:\n\
45
- print("Attempting to download class names...")\n\
46
- hf_hub_download(\n\
47
- "seamo-ai/marina-species-v1",\n\
48
- "marina-benthic-33k.names",\n\
49
- local_dir="/models",\n\
50
- local_dir_use_symlinks=False\n\
51
- )\n\
52
- print("Class names downloaded successfully")\n\
53
- return True\n\
54
- except Exception as e:\n\
55
- print(f"Class names download failed: {e}")\n\
56
- return False\n\
57
- \n\
58
- if __name__ == "__main__":\n\
59
- download_model()\n\
60
- download_names()\n\
61
- ' > /tmp/download_models.py
62
-
63
- # Run the model download script
64
- RUN python /tmp/download_models.py
65
 
66
  # Stage 2: Build the application
67
  FROM python:3.10-slim
 
17
  # Create models directory
18
  RUN mkdir -p /models
19
 
20
+ # Download models from HuggingFace Hub
21
+ RUN python -c "\
22
+ from huggingface_hub import hf_hub_download; \
23
+ import os; \
24
+ try: \
25
+ print('Downloading model...'); \
26
+ hf_hub_download('seamo-ai/marina-species-v1', 'marina-benthic-33k.pt', local_dir='/models', local_dir_use_symlinks=False); \
27
+ print('Model downloaded successfully'); \
28
+ except Exception as e: \
29
+ print(f'Model download failed: {e}'); \
30
+ with open('/models/marina-benthic-33k.pt', 'w') as f: \
31
+ f.write('placeholder'); \
32
+ print('Created placeholder model file'); \
33
+ "
34
+
35
+ # Download class names file
36
+ RUN python -c "\
37
+ from huggingface_hub import hf_hub_download; \
38
+ try: \
39
+ print('Downloading class names...'); \
40
+ hf_hub_download('seamo-ai/marina-species-v1', 'marina-benthic-33k.names', local_dir='/models', local_dir_use_symlinks=False); \
41
+ print('Class names downloaded successfully'); \
42
+ except Exception as e: \
43
+ print(f'Class names download failed: {e}'); \
44
+ "
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  # Stage 2: Build the application
47
  FROM python:3.10-slim
app/models/inference.py CHANGED
@@ -77,15 +77,17 @@ class InferenceRequest(BaseModel):
77
 
78
  class InferenceResponse(BaseModel):
79
  """Response model for marine species detection."""
 
 
80
  detections: List[Detection] = Field(..., description="List of detected marine species")
81
  annotated_image: Optional[str] = Field(
82
- default=None,
83
  description="Base64 encoded annotated image (if requested)"
84
  )
85
  processing_time: float = Field(..., description="Processing time in seconds")
86
  model_info: ModelInfo = Field(..., description="Information about the model used")
87
  image_dimensions: Dict[str, int] = Field(
88
- ...,
89
  description="Original image dimensions (width, height)"
90
  )
91
 
 
77
 
78
  class InferenceResponse(BaseModel):
79
  """Response model for marine species detection."""
80
+ model_config = {"protected_namespaces": ()}
81
+
82
  detections: List[Detection] = Field(..., description="List of detected marine species")
83
  annotated_image: Optional[str] = Field(
84
+ default=None,
85
  description="Base64 encoded annotated image (if requested)"
86
  )
87
  processing_time: float = Field(..., description="Processing time in seconds")
88
  model_info: ModelInfo = Field(..., description="Information about the model used")
89
  image_dimensions: Dict[str, int] = Field(
90
+ ...,
91
  description="Original image dimensions (width, height)"
92
  )
93
 
app/models/yolo.py CHANGED
@@ -54,24 +54,8 @@ class MarineSpeciesYOLO:
54
 
55
  logger.info(f"Loading YOLOv5 model from: {self.model_path}")
56
 
57
- # Handle PyTorch 2.6+ weights_only issue
58
- import torch
59
- import warnings
60
-
61
- # Temporarily suppress warnings and set safe globals for numpy
62
- with warnings.catch_warnings():
63
- warnings.simplefilter("ignore")
64
-
65
- # Add safe globals for numpy operations that YOLOv5 needs
66
- torch.serialization.add_safe_globals([
67
- 'numpy.core.multiarray._reconstruct',
68
- 'numpy.ndarray',
69
- 'numpy.dtype',
70
- 'numpy.core.multiarray.scalar',
71
- ])
72
-
73
- # Load the model with YOLOv5
74
- self.model = yolov5.load(self.model_path, device=self.device)
75
 
76
  # Get class names if available
77
  if hasattr(self.model, 'names'):
 
54
 
55
  logger.info(f"Loading YOLOv5 model from: {self.model_path}")
56
 
57
+ # Load model exactly like the original Gradio implementation
58
+ self.model = yolov5.load(self.model_path, device=self.device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  # Get class names if available
61
  if hasattr(self.model, 'names'):
requirements.txt CHANGED
@@ -5,7 +5,7 @@ uvicorn[standard]==0.24.0
5
  # Machine Learning and Computer Vision
6
  torch>=1.13.0
7
  torchvision>=0.14.0
8
- yolov5==7.0.13
9
  opencv-python-headless==4.8.1.78
10
  Pillow==10.1.0
11
  numpy==1.24.3
 
5
  # Machine Learning and Computer Vision
6
  torch>=1.13.0
7
  torchvision>=0.14.0
8
+ yolov5==6.2.3
9
  opencv-python-headless==4.8.1.78
10
  Pillow==10.1.0
11
  numpy==1.24.3