File size: 11,692 Bytes
2407511
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Local-first resolution for the private CodeBlueX model artifacts."""

from __future__ import annotations

import hashlib
import os
import shutil
import threading
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from types import MappingProxyType
from typing import Any, Callable, Iterator, Mapping, Optional


PRIVATE_MODEL_REPOSITORY = "AnirudhShashikumar/SatQuery_AI_Models"
SATQUERY_VISION_ENCODER_V1 = "satquery_vision_encoder_v1"
RSVQA_SPECIALIST_V1 = "rsvqa_specialist_v1"
GROUNDING_SPECIALIST_V1_1 = "grounding_specialist_v1_1"
PIX2PIX_SAR_TRANSLATION = "pix2pix_sar_translation"
SARFUSIONFORMER_SAR_TRANSLATION = "sarfusionformer_sar_translation"
SARFUSIONFORMER_COLOR_CORRECTOR = "sarfusionformer_color_corrector"


@dataclass(frozen=True)
class ModelArtifact:
    key: str
    name: str
    repository_path: str
    sha256: str


CODEBLUEX_ARTIFACTS: Mapping[str, ModelArtifact] = MappingProxyType(
    {
        SATQUERY_VISION_ENCODER_V1: ModelArtifact(
            key=SATQUERY_VISION_ENCODER_V1,
            name="SatQuery Vision Encoder v1 adapter",
            repository_path="satquery_vision_encoder_v1/satquery_vision_encoder_v1_adapter.pt",
            sha256="a99c0bf0fb44044988ef1698483888c8a2e3a047d2d2d56478837575cf7626ea",
        ),
        RSVQA_SPECIALIST_V1: ModelArtifact(
            key=RSVQA_SPECIALIST_V1,
            name="RSVQA Specialist v1 head",
            repository_path="rsvqa_specialist_v1/rsvqa_specialist_v1_head.pt",
            sha256="71c0ab56ee650813bd495e8a3bc777353b6907a097af860e417f60523efe56ad",
        ),
        GROUNDING_SPECIALIST_V1_1: ModelArtifact(
            key=GROUNDING_SPECIALIST_V1_1,
            name="Grounding Specialist v1.1 head",
            repository_path="grounding_specialist_v1_1/grounding_specialist_v1_1_head.pt",
            sha256="5e8db30becadb1d063fc0154614ee2a2a4b7a2c2923db3fce4ff036c65007342",
        ),
        PIX2PIX_SAR_TRANSLATION: ModelArtifact(
            key=PIX2PIX_SAR_TRANSLATION,
            name="Pix2Pix SAR reconstruction checkpoint",
            repository_path="sar_translation/pix2pix/pix2pix_gen_180.pth",
            sha256="5bdc6bf9b29986860d6537265280bb47b74f85ebe1222256ddc59acce3a743b3",
        ),
        SARFUSIONFORMER_SAR_TRANSLATION: ModelArtifact(
            key=SARFUSIONFORMER_SAR_TRANSLATION,
            name="SARFusionFormer SAR reconstruction checkpoint",
            repository_path="sar_translation/sarfusionformer/sarfusionformer_256_decoder_best.pt",
            sha256="6c8ac2d482b66877a910a9c95e6398f9e0586f13f786d0243c736a2d10b30548",
        ),
        SARFUSIONFORMER_COLOR_CORRECTOR: ModelArtifact(
            key=SARFUSIONFORMER_COLOR_CORRECTOR,
            name="SARFusionFormer color-corrector checkpoint",
            repository_path="sar_translation/sarfusionformer/color_corrector_256_best.pt",
            sha256="15298976fbffe93c16d81716c40fe3c7a09499e63e649edd4de9a1fd70ec675d",
        ),
    }
)


class ModelArtifactError(RuntimeError):
    """Base class for credential-safe artifact resolution failures."""


class UnknownModelArtifactError(ModelArtifactError):
    """Raised when a caller requests an artifact outside the CodeBlueX allowlist."""


class ModelArtifactChecksumError(ModelArtifactError):
    """Raised when an existing or downloaded artifact has the wrong identity."""


class ModelArtifactAuthenticationError(ModelArtifactError):
    """Raised when a private download is needed but no environment token exists."""


class ModelArtifactMissingError(ModelArtifactError):
    """Raised when an explicit local override is absent and cannot be replaced."""


class ModelArtifactDownloadError(ModelArtifactError):
    """Raised when the private repository cannot provide the requested artifact."""


class ModelArtifactFilesystemError(ModelArtifactError):
    """Raised when a verified artifact cannot be published to its local path."""


DownloadFunction = Callable[..., Any]


def sha256_file(path: Path) -> str:
    digest = hashlib.sha256()
    try:
        with path.open("rb") as stream:
            for chunk in iter(lambda: stream.read(1024 * 1024), b""):
                digest.update(chunk)
    except OSError as error:
        raise ModelArtifactFilesystemError(f"Could not read model artifact {path.name}.") from error
    return digest.hexdigest()


@contextmanager
def _exclusive_file_lock(path: Path) -> Iterator[None]:
    """Serialize publication across workers while keeping local reads lock-free."""
    try:
        import fcntl

        with path.open("a+b") as lock_stream:
            fcntl.flock(lock_stream.fileno(), fcntl.LOCK_EX)
            try:
                yield
            finally:
                fcntl.flock(lock_stream.fileno(), fcntl.LOCK_UN)
    except ModelArtifactError:
        raise
    except OSError as error:
        raise ModelArtifactFilesystemError("Could not lock the local model artifact directory.") from error


class ModelArtifactResolver:
    """Resolve pinned artifacts locally, downloading only an absent allowlisted file."""

    def __init__(
        self,
        *,
        repository_id: str = PRIVATE_MODEL_REPOSITORY,
        artifacts: Mapping[str, ModelArtifact] = CODEBLUEX_ARTIFACTS,
        environment: Optional[Mapping[str, str]] = None,
        downloader: Optional[DownloadFunction] = None,
        models_root: Optional[Path] = None,
    ) -> None:
        self.repository_id = repository_id
        self.artifacts = dict(artifacts)
        self.environment = environment if environment is not None else os.environ
        self.downloader = downloader
        self.models_root = (models_root or Path(__file__).resolve().parents[1] / "models").resolve()

    def _artifact(self, key: str) -> ModelArtifact:
        try:
            artifact = self.artifacts[key]
        except KeyError:
            raise UnknownModelArtifactError(
                f"{key!r} is not an allowlisted CodeBlueX model artifact."
            ) from None
        repository_path = PurePosixPath(artifact.repository_path)
        if repository_path.is_absolute() or ".." in repository_path.parts:
            raise UnknownModelArtifactError(f"Unsafe repository path configured for {artifact.name}.")
        return artifact

    def _default_path(self, artifact: ModelArtifact) -> Path:
        return self.models_root.joinpath(*PurePosixPath(artifact.repository_path).parts)

    @staticmethod
    def _verify_existing(path: Path, artifact: ModelArtifact) -> Optional[Path]:
        if not path.exists():
            return None
        if not path.is_file():
            raise ModelArtifactFilesystemError(
                f"Expected {artifact.name} to be a regular file at {path}."
            )
        actual = sha256_file(path)
        if actual != artifact.sha256:
            raise ModelArtifactChecksumError(
                f"Local {artifact.name} failed SHA-256 verification; expected {artifact.sha256}, received {actual}."
            )
        return path

    def _download_function(self) -> DownloadFunction:
        if self.downloader is not None:
            return self.downloader
        try:
            from huggingface_hub import hf_hub_download
        except ImportError:
            raise ModelArtifactDownloadError(
                "huggingface_hub is required to retrieve missing private model artifacts."
            ) from None
        return hf_hub_download

    def resolve(
        self,
        key: str,
        *,
        local_path: Optional[Path] = None,
        download_if_missing: bool = True,
    ) -> Path:
        artifact = self._artifact(key)
        target = (local_path or self._default_path(artifact)).expanduser().resolve()
        verified = self._verify_existing(target, artifact)
        if verified is not None:
            return verified

        if not download_if_missing:
            raise ModelArtifactMissingError(
                f"Explicit checkpoint for {artifact.name} is missing at {target}; automatic download is disabled for configured overrides."
            )

        token = self.environment.get("HF_TOKEN", "").strip()
        if not token:
            raise ModelArtifactAuthenticationError(
                f"{artifact.name} is missing and HF_TOKEN is required to access the private model repository."
            )

        try:
            target.parent.mkdir(parents=True, exist_ok=True)
        except OSError as error:
            raise ModelArtifactFilesystemError(
                f"Could not create the local directory for {artifact.name}."
            ) from error

        lock_path = target.parent / f".{target.name}.lock"
        with _exclusive_file_lock(lock_path):
            verified = self._verify_existing(target, artifact)
            if verified is not None:
                return verified

            downloader = self._download_function()
            try:
                downloaded = Path(
                    downloader(
                        repo_id=self.repository_id,
                        filename=artifact.repository_path,
                        token=token,
                    )
                ).resolve()
            except Exception:
                raise ModelArtifactDownloadError(
                    f"Could not retrieve {artifact.name} from the private model repository; verify HF_TOKEN access and network availability."
                ) from None

            if not downloaded.is_file():
                raise ModelArtifactDownloadError(
                    f"The private model repository did not return a file for {artifact.name}."
                )
            actual = sha256_file(downloaded)
            if actual != artifact.sha256:
                raise ModelArtifactChecksumError(
                    f"Downloaded {artifact.name} failed SHA-256 verification; expected {artifact.sha256}, received {actual}."
                )

            temporary = target.parent / (
                f".{target.name}.{os.getpid()}.{threading.get_ident()}.part"
            )
            try:
                shutil.copyfile(downloaded, temporary)
                if sha256_file(temporary) != artifact.sha256:
                    raise ModelArtifactChecksumError(
                        f"Staged {artifact.name} failed SHA-256 verification."
                    )
                os.replace(temporary, target)
            except ModelArtifactError:
                raise
            except OSError as error:
                raise ModelArtifactFilesystemError(
                    f"Could not publish the verified {artifact.name} to its local model path."
                ) from error
            finally:
                try:
                    temporary.unlink(missing_ok=True)
                except OSError:
                    pass

            return target


_DEFAULT_RESOLVER = ModelArtifactResolver()


def resolve_model_artifact(
    key: str,
    *,
    local_path: Optional[Path] = None,
    download_if_missing: bool = True,
) -> Path:
    """Resolve one of the pinned CodeBlueX artifacts."""
    return _DEFAULT_RESOLVER.resolve(
        key,
        local_path=local_path,
        download_if_missing=download_if_missing,
    )


def resolve_configured_model_artifact(
    key: str,
    *,
    environment_key: str,
    local_path: Path,
) -> Path:
    """Honor an explicit checkpoint path without replacing a missing override."""
    explicitly_configured = bool(
        _DEFAULT_RESOLVER.environment.get(environment_key, "").strip()
    )
    return resolve_model_artifact(
        key,
        local_path=local_path,
        download_if_missing=not explicitly_configured,
    )