File size: 10,703 Bytes
d847b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21efdcf
 
 
 
 
 
d847b3c
 
 
 
 
 
 
 
433e26f
 
d847b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21efdcf
d847b3c
433e26f
d847b3c
 
 
 
21efdcf
 
d847b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21efdcf
 
 
d847b3c
 
21efdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d847b3c
 
 
 
 
 
21efdcf
 
 
d847b3c
 
21efdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d847b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21efdcf
 
d847b3c
21efdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d847b3c
 
 
 
 
 
 
 
 
 
 
21efdcf
 
 
d847b3c
 
 
 
 
21efdcf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d847b3c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433e26f
 
 
 
 
 
 
 
d847b3c
 
 
 
 
 
 
 
433e26f
d847b3c
 
433e26f
d847b3c
 
 
 
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""Python client for the LandmarkDiff REST API.

Provides a clean interface for interacting with the FastAPI server,
handling image encoding/decoding, error handling, and session management.

Usage:
    from landmarkdiff.api_client import LandmarkDiffClient

    client = LandmarkDiffClient("http://localhost:8000")

    # Single prediction
    result = client.predict("patient.png", procedure="rhinoplasty", intensity=65)
    result.save("output.png")

    # Face analysis
    analysis = client.analyze("patient.png")
    print(f"Fitzpatrick type: {analysis['fitzpatrick_type']}")

    # Batch processing
    results = client.batch_predict(
        ["patient1.png", "patient2.png"],
        procedure="blepharoplasty",
    )
"""

from __future__ import annotations

import base64
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any

import cv2
import numpy as np


class LandmarkDiffAPIError(Exception):
    """Base exception for LandmarkDiff API errors."""

    pass


@dataclass
class PredictionResult:
    """Result from a single prediction."""

    output_image: np.ndarray
    procedure: str
    intensity: float
    confidence: float = 0.0
    landmarks_before: list[Any] | None = None
    landmarks_after: list[Any] | None = None
    metrics: dict[str, float] = field(default_factory=dict)
    metadata: dict[str, Any] = field(default_factory=dict)

    def save(self, path: str | Path, fmt: str = ".png") -> None:
        """Save the output image to a file."""
        cv2.imwrite(str(path), self.output_image)

    def show(self) -> None:
        """Display the output image (requires GUI)."""
        cv2.imshow("LandmarkDiff Prediction", self.output_image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


class LandmarkDiffClient:
    """Client for the LandmarkDiff REST API.

    Args:
        base_url: Server URL (e.g. "http://localhost:8000").
        timeout: Request timeout in seconds.
    """

    def __init__(self, base_url: str = "http://localhost:8000", timeout: float = 60.0) -> None:
        self.base_url = base_url.rstrip("/")
        self.timeout = timeout
        self._session = None

    def _get_session(self) -> Any:
        """Lazy-initialize requests session."""
        if self._session is None:
            try:
                import requests
            except ImportError as e:
                raise ImportError("requests required. Install with: pip install requests") from e
            self._session = requests.Session()
        return self._session

    def _read_image(self, image_path: str | Path) -> bytes:
        """Read image file as bytes."""
        path = Path(image_path)
        if not path.exists():
            raise FileNotFoundError(f"Image not found: {path}")
        return path.read_bytes()

    def _decode_base64_image(self, b64_string: str) -> np.ndarray:
        """Decode a base64-encoded image to numpy array."""
        img_bytes = base64.b64decode(b64_string)
        arr = np.frombuffer(img_bytes, np.uint8)
        img = cv2.imdecode(arr, cv2.IMREAD_COLOR)
        if img is None:
            raise ValueError("Failed to decode base64 image")
        return img

    # ------------------------------------------------------------------
    # API methods
    # ------------------------------------------------------------------

    def health(self) -> dict[str, Any]:
        """Check server health.

        Returns:
            Dict with status and version info.

        Raises:
            LandmarkDiffAPIError: If server is unreachable or returns an error.
        """
        session = self._get_session()
        try:
            resp = session.get(f"{self.base_url}/health", timeout=self.timeout)
            resp.raise_for_status()
            return resp.json()
        except Exception as e:
            import requests

            if isinstance(e, requests.ConnectionError):
                raise LandmarkDiffAPIError(
                    f"Cannot connect to LandmarkDiff server at {self.base_url}. "
                    f"Make sure the server is running (python -m landmarkdiff serve)."
                ) from None
            elif isinstance(e, requests.HTTPError):
                raise LandmarkDiffAPIError(
                    f"Server returned error {e.response.status_code}: {e.response.text[:200]}"
                ) from None
            else:
                raise

    def procedures(self) -> list[str]:
        """List available surgical procedures.

        Returns:
            List of procedure names.

        Raises:
            LandmarkDiffAPIError: If server is unreachable or returns an error.
        """
        session = self._get_session()
        try:
            resp = session.get(f"{self.base_url}/procedures", timeout=self.timeout)
            resp.raise_for_status()
            return resp.json().get("procedures", [])
        except Exception as e:
            import requests

            if isinstance(e, requests.ConnectionError):
                raise LandmarkDiffAPIError(
                    f"Cannot connect to LandmarkDiff server at {self.base_url}. "
                    f"Make sure the server is running (python -m landmarkdiff serve)."
                ) from None
            elif isinstance(e, requests.HTTPError):
                raise LandmarkDiffAPIError(
                    f"Server returned error {e.response.status_code}: {e.response.text[:200]}"
                ) from None
            else:
                raise

    def predict(
        self,
        image_path: str | Path,
        procedure: str = "rhinoplasty",
        intensity: float = 65.0,
        seed: int = 42,
    ) -> PredictionResult:
        """Run surgical outcome prediction.

        Args:
            image_path: Path to input face image.
            procedure: Surgical procedure type.
            intensity: Intensity of the modification (0-100).
            seed: Random seed for reproducibility.

        Returns:
            PredictionResult with output image and metadata.
        """
        session = self._get_session()
        image_bytes = self._read_image(image_path)

        files = {"image": ("image.png", image_bytes, "image/png")}
        data = {
            "procedure": procedure,
            "intensity": str(intensity),
            "seed": str(seed),
        }

        resp = session.post(
            f"{self.base_url}/predict", files=files, data=data, timeout=self.timeout
        )
        try:
            resp.raise_for_status()
            result = resp.json()

            # Decode output image
            output_img = self._decode_base64_image(result["output_image"])

            return PredictionResult(
                output_image=output_img,
                procedure=procedure,
                intensity=intensity,
                confidence=result.get("confidence", 0.0),
                metrics=result.get("metrics", {}),
                metadata=result.get("metadata", {}),
            )
        except Exception as e:
            import requests

            if isinstance(e, requests.ConnectionError):
                raise LandmarkDiffAPIError(
                    f"Cannot connect to LandmarkDiff server at {self.base_url}. "
                    f"Make sure the server is running (python -m landmarkdiff serve)."
                ) from None
            elif isinstance(e, requests.HTTPError):
                raise LandmarkDiffAPIError(
                    f"Server returned error {e.response.status_code}: {e.response.text[:200]}"
                ) from None
            else:
                raise

    def analyze(self, image_path: str | Path) -> dict[str, Any]:
        """Analyze a face image without generating a prediction.

        Returns face landmarks, Fitzpatrick type, pose estimation, etc.

        Args:
            image_path: Path to input face image.

        Returns:
            Dict with analysis results.

        Raises:
            LandmarkDiffAPIError: If server is unreachable or returns an error.
        """
        session = self._get_session()
        image_bytes = self._read_image(image_path)

        files = {"image": ("image.png", image_bytes, "image/png")}
        try:
            resp = session.post(f"{self.base_url}/analyze", files=files, timeout=self.timeout)
            resp.raise_for_status()
            return resp.json()
        except Exception as e:
            import requests

            if isinstance(e, requests.ConnectionError):
                raise LandmarkDiffAPIError(
                    f"Cannot connect to LandmarkDiff server at {self.base_url}. "
                    f"Make sure the server is running (python -m landmarkdiff serve)."
                ) from None
            elif isinstance(e, requests.HTTPError):
                raise LandmarkDiffAPIError(
                    f"Server returned error {e.response.status_code}: {e.response.text[:200]}"
                ) from None
            else:
                raise

    def batch_predict(
        self,
        image_paths: list[str | Path],
        procedure: str = "rhinoplasty",
        intensity: float = 65.0,
        seed: int = 42,
    ) -> list[PredictionResult]:
        """Run batch prediction on multiple images.

        Args:
            image_paths: List of image file paths.
            procedure: Procedure to apply to all images.
            intensity: Intensity for all images.
            seed: Base random seed.

        Returns:
            List of PredictionResult objects.
        """
        results = []
        for i, path in enumerate(image_paths):
            try:
                result = self.predict(
                    path,
                    procedure=procedure,
                    intensity=intensity,
                    seed=seed + i,
                )
                results.append(result)
            except Exception as e:
                # Create a failed result
                results.append(
                    PredictionResult(
                        output_image=np.zeros((512, 512, 3), dtype=np.uint8),
                        procedure=procedure,
                        intensity=intensity,
                        metadata={"error": str(e), "path": str(path)},
                    )
                )
        return results

    def close(self) -> None:
        """Close the HTTP session."""
        if self._session is not None:
            self._session.close()
            self._session = None

    def __enter__(self) -> LandmarkDiffClient:
        return self

    def __exit__(self, *args: Any) -> None:
        self.close()

    def __repr__(self) -> str:
        return f"LandmarkDiffClient(base_url='{self.base_url}')"