Keras
sdhaos commited on
Commit
6574d7d
·
verified ·
1 Parent(s): 3fefe67

Upload aminatron_model.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. aminatron_model.py +103 -0
aminatron_model.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections import Counter
4
+ from functools import lru_cache
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from PIL import Image
9
+
10
+
11
+ PROJECT_DIR = Path(__file__).resolve().parent
12
+ LOCAL_MODEL_PATH = PROJECT_DIR / "model" / "aminatron.pt"
13
+
14
+
15
+ def resolve_model_path(model_path: str | None = None) -> str:
16
+ """Return the Aminatron model path or fail with a clear setup message."""
17
+
18
+ if model_path:
19
+ return str(Path(model_path).expanduser().resolve()) if Path(model_path).exists() else model_path
20
+
21
+ if LOCAL_MODEL_PATH.exists():
22
+ return str(LOCAL_MODEL_PATH)
23
+
24
+ raise FileNotFoundError(
25
+ f"Aminatron model not found: {LOCAL_MODEL_PATH}. "
26
+ "Create it with: python train.py --save-as-aminatron"
27
+ )
28
+
29
+
30
+ @lru_cache(maxsize=3)
31
+ def load_model(model_path: str | None = None) -> YOLO:
32
+ """Load and cache the detector model."""
33
+
34
+ from ultralytics import YOLO
35
+
36
+ return YOLO(resolve_model_path(model_path))
37
+
38
+
39
+ def detect_image(
40
+ image: Image.Image,
41
+ model_path: str | None = None,
42
+ confidence: float = 0.25,
43
+ iou: float = 0.45,
44
+ image_size: int = 640,
45
+ max_detections: int = 100,
46
+ ) -> Any:
47
+ """Detect multiple objects on a single image."""
48
+
49
+ model = load_model(model_path)
50
+ rgb_image = image.convert("RGB")
51
+ results = model.predict(
52
+ rgb_image,
53
+ conf=confidence,
54
+ iou=iou,
55
+ imgsz=image_size,
56
+ max_det=max_detections,
57
+ verbose=False,
58
+ )
59
+ return results[0]
60
+
61
+
62
+ def format_detections(result: Any) -> list[dict[str, object]]:
63
+ """Convert YOLO boxes to readable dictionaries."""
64
+
65
+ detections = []
66
+ names = result.names
67
+
68
+ for box in result.boxes:
69
+ class_id = int(box.cls[0].item())
70
+ confidence = float(box.conf[0].item())
71
+ x1, y1, x2, y2 = [float(value) for value in box.xyxy[0].tolist()]
72
+ detections.append(
73
+ {
74
+ "class": names[class_id],
75
+ "confidence": round(confidence, 4),
76
+ "box": [round(x1, 2), round(y1, 2), round(x2, 2), round(y2, 2)],
77
+ }
78
+ )
79
+
80
+ detections.sort(key=lambda item: item["confidence"], reverse=True)
81
+ return detections
82
+
83
+
84
+ def summarize_detections(detections: list[dict[str, object]]) -> dict[str, int]:
85
+ """Count detected objects by class."""
86
+
87
+ return dict(Counter(str(item["class"]) for item in detections))
88
+
89
+
90
+ def render_result_image(result: Any) -> Image.Image:
91
+ """Return a PIL image with bounding boxes drawn by YOLO."""
92
+
93
+ # Ultralytics returns a BGR numpy image from plot(), PIL expects RGB.
94
+ annotated_bgr = result.plot()
95
+ return Image.fromarray(annotated_bgr[..., ::-1])
96
+
97
+
98
+ def save_result_image(result: Any, output_path: Path) -> Path:
99
+ """Save an annotated prediction image."""
100
+
101
+ output_path.parent.mkdir(parents=True, exist_ok=True)
102
+ render_result_image(result).save(output_path)
103
+ return output_path