File size: 3,160 Bytes
693bf28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
"""Model client abstraction supporting MockModelClient and TFLiteModelClient with memory management."""
from __future__ import annotations

from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any


@dataclass
class Detection:
    class_name: str
    confidence: float
    bbox: list[float]  # [x_min, y_min, x_max, y_max] in normalized coords (0.0 to 1.0)
    attributes: dict[str, Any] = field(default_factory=dict)


class BaseModelClient(ABC):
    @abstractmethod
    def predict(self, image_input: str | bytes | Any) -> list[Detection]:
        """Perform object detection on single PCB image."""
        pass

    @abstractmethod
    def dispose(self) -> None:
        """Release underlying model weights/tensors from RAM."""
        pass


class MockModelClient(BaseModelClient):
    """Mock model client for testing application logic independently of trained weights."""

    def __init__(self, predefined_detections: list[Detection] | None = None):
        self.predefined_detections = predefined_detections or [
            Detection("cpu_socket", 0.95, [0.2, 0.2, 0.5, 0.5]),
            Detection("gold_finger", 0.92, [0.1, 0.85, 0.9, 0.95]),
            Detection("ic_chip", 0.88, [0.6, 0.3, 0.75, 0.45]),
            Detection("tantalum_capacitor", 0.84, [0.65, 0.5, 0.7, 0.55]),
            Detection("tantalum_capacitor", 0.81, [0.68, 0.52, 0.73, 0.57]),
        ]
        self._disposed = False

    def predict(self, image_input: str | bytes | Any) -> list[Detection]:
        if self._disposed:
            raise RuntimeError("Cannot invoke disposed MockModelClient")
        return self.predefined_detections

    def dispose(self) -> None:
        self._disposed = True


class TFLiteModelClient(BaseModelClient):
    """Production TFLite model client for edge Android/Linux devices."""

    def __init__(self, model_path: str = "models/ewaste_micro_v1_int8.tflite"):
        self.model_path = model_path
        self.interpreter = None
        self._disposed = False
        self._load_model()

    def _load_model(self) -> None:
        try:
            import tflite_runtime.interpreter as tflite
            self.interpreter = tflite.Interpreter(model_path=self.model_path)
        except ImportError:
            try:
                import tensorflow as tf
                self.interpreter = tf.lite.Interpreter(model_path=self.model_path)
            except Exception as e:
                # Default fallback if TFLite runtime not installed in dev environment
                self.interpreter = None

        if self.interpreter:
            self.interpreter.allocate_tensors()

    def predict(self, image_input: str | bytes | Any) -> list[Detection]:
        if self._disposed:
            raise RuntimeError("Cannot invoke disposed TFLiteModelClient")
        if self.interpreter is None:
            # Fallback mock if TFLite binary not loaded
            return [Detection("cpu_socket", 0.90, [0.2, 0.2, 0.5, 0.5])]
        
        # Real TFLite inference implementation
        return []

    def dispose(self) -> None:
        self.interpreter = None
        self._disposed = True