Spaces:
Sleeping

File size: 10,031 Bytes
5a5e72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import hashlib
import json
from pathlib import Path
from typing import Any


FINAL = {
    "arcface": {
        "complete": "5404a6b63057b0fc61909c5d738969843618e49db660d0acdb4e0dc150d4783e",
        "encoder": "6c5a90621b19c27484daffcc903c35b608737935888b085c7fee286c8fb80f86",
        "fc3": "5a28ca9ee502c73bfed67088b1ef5ce1c6f8785581a69da7e3cf73a3f4377e87",
        "job": "fa2ac7a05001130bb3db76c5bf41b83da2ec2ae0b2df23a5c043af602ea5ea71",
        "model_state_prefix": "a94d0e6b",
        "decoder_state_prefix": "a691416e",
    },
    "facenet": {
        "complete": "856797bfabb21609eed7f7357c853f1d63c3ccc8db0f6bac47124e8303382336",
        "encoder": "4541cc28dc4bbfcc6c2759a3149baeb1ed4ca68974223ec3830661ccf728171d",
        "fc3": "54567e09a4e0482f9ff9a4a392434a0624c2df173a4e8557ec03f301d9f19fc0",
        "job": "b4775b9db9db08ab58c771d29765ca124b25d380cfdd894a663b40fe33555923",
        "model_state_prefix": "8e2bdb05",
        "decoder_state_prefix": "55721d46",
    },
}
SCHEMAS = {part: f"speech2face.space-{part}-asset/v3" for part in ("voice", "decoder")}


def need(ok: Any, message: str) -> None:
    if not ok:
        raise ValueError(message)


def sha256_file(path: str | Path) -> str:
    digest = hashlib.sha256()
    with Path(path).open("rb") as stream:
        for block in iter(lambda: stream.read(4 << 20), b""):
            digest.update(block)
    return digest.hexdigest()


def file_ref(path: str | Path) -> dict[str, str | int]:
    path = Path(path).absolute()
    return {"path": str(path), "sha256": sha256_file(path), "size_bytes": path.stat().st_size}


def inline_evidence(reference: dict[str, Any]) -> dict[str, Any]:
    raw = Path(reference["path"]).read_bytes()
    need(
        len(raw) == reference["size_bytes"]
        and hashlib.sha256(raw).hexdigest() == reference["sha256"],
        "Source evidence differs",
    )
    return {"reference": reference, "json": raw.decode("utf-8")}


def evidence_document(evidence: dict[str, Any]) -> dict[str, Any]:
    raw = evidence["json"].encode("utf-8")
    reference = evidence["reference"]
    need(
        len(raw) == reference["size_bytes"]
        and hashlib.sha256(raw).hexdigest() == reference["sha256"],
        "Embedded evidence differs",
    )
    return json.loads(raw)


def production_binding(evidence: dict[str, Any], label: str) -> dict[str, Any]:
    pins = FINAL[label]
    complete = evidence_document(evidence["complete"])
    exported = evidence_document(evidence["final_export"])
    decoder = evidence_document(evidence["decoder_receipt"])
    need(
        evidence["complete"]["reference"]["sha256"] == pins["complete"],
        "Another production completion",
    )
    need(
        complete["schema"] == "speech2face.voice-production/v1/complete"
        and complete["selection"] == "final_epoch3"
        and complete["frontier"]["epoch"] == 3
        and complete["frontier"]["epoch_complete"] is True
        and complete["official_test_accessed"] is False,
        "Only production final_epoch3 is deployable",
    )
    need(
        complete["encoder"]["sha256"] == pins["encoder"]
        and complete["model_state_sha256"].startswith(pins["model_state_prefix"]),
        "Another final encoder",
    )
    need(
        exported["encoder"] == complete["encoder"]
        and exported["model_state_sha256"] == complete["model_state_sha256"]
        and exported["binding"]
        and all(complete.get(k) == v for k, v in exported["binding"].items()),
        "Final export/completion differs",
    )
    need(
        evidence["decoder_receipt"]["reference"] == complete["decoder_receipt"]
        and decoder["schema"] == "speech2face.decoder-s08-fc3-export/v1"
        and decoder["full_state_authenticated"] is True
        and decoder["winner_frozen"] is True
        and decoder["projection"] == complete["decoder_projection"]
        and decoder["projection"]["sha256"] == pins["fc3"]
        and decoder["model_state"]["sha256"].startswith(pins["decoder_state_prefix"]),
        "Another decoder/fc3 pairing",
    )
    return {
        "production_complete_sha256": pins["complete"],
        "encoder_sha256": pins["encoder"],
        "final_export_sha256": evidence["final_export"]["reference"]["sha256"],
        "voice_model_state_sha256": complete["model_state_sha256"],
        "decoder_receipt": compact_ref(complete["decoder_receipt"]),
        "fc3": compact_ref(decoder["projection"]),
        "model_state": compact_ref(decoder["model_state"]),
        "freeze_bundle": compact_ref(decoder["freeze_bundle"]),
        "run_manifest": compact_ref(decoder["run_manifest"]),
        "decoder_arm": decoder["decoder_arm"],
        "representative_seed": decoder["representative_seed"],
    }


def compact_ref(reference: dict[str, Any]) -> dict[str, Any]:
    return {key: reference[key] for key in ("sha256", "size_bytes") if key in reference}


def space_sources() -> dict[str, str]:
    app = Path(__file__).resolve().parents[1]
    vendored = json.loads((app / "s2f/VENDORED.json").read_text(encoding="utf-8"))
    for name, entry in vendored.items():
        need(
            Path(name).name == name and sha256_file(app / "s2f" / name) == entry["sha256"],
            "Vendored file differs: " + name,
        )
        need(
            not entry["verbatim"] or entry["sha256"] == entry["source_sha256"],
            "Verbatim source record differs: " + name,
        )
    paths = [app / "inference-requirements.txt", app / "s2f/VENDORED.json"]
    paths += sorted((app / "s2f").glob("*.py"))
    return {path.relative_to(app).as_posix(): sha256_file(path) for path in paths}


def checked_asset(root: str | Path, reference: dict[str, Any]) -> Path:
    name = reference["file"]
    need(Path(name).name == name, "Asset must be a basename")
    path = Path(root) / name
    need(
        path.stat().st_size == reference["size_bytes"]
        and sha256_file(path) == reference["sha256"],
        "Asset bytes differ: " + name,
    )
    return path


def load_manifest(root: str | Path, part: str, label: str) -> dict[str, Any]:
    from .model_assets import resolve_model_asset

    need(label in FINAL and part in SCHEMAS, "Unregistered Space asset")
    manifest = json.loads((Path(root) / f"{part}-{label}.json").read_text(encoding="utf-8"))
    need(
        manifest["schema"] == SCHEMAS[part] and manifest["label"] == label,
        "Old or mismatched asset manifest",
    )
    need(
        set(manifest)
        == {"schema", "label", "file", "sha256", "size_bytes", "binding", "space_sources", "probe"},
        "Space manifests contain only compact bindings; keep host provenance separate",
    )
    binding = manifest["binding"]
    need(
        set(binding)
        == {
            "production_complete_sha256",
            "encoder_sha256",
            "final_export_sha256",
            "voice_model_state_sha256",
            "decoder_receipt",
            "fc3",
            "model_state",
            "freeze_bundle",
            "run_manifest",
            "decoder_arm",
            "representative_seed",
        },
        "Unexpected binding fields",
    )

    def digest(value: Any) -> bool:
        return (
            isinstance(value, str)
            and len(value) == 64
            and all(c in "0123456789abcdef" for c in value)
        )

    for key in (
        "production_complete_sha256",
        "encoder_sha256",
        "final_export_sha256",
        "voice_model_state_sha256",
    ):
        need(digest(binding[key]), "Invalid binding digest")
    for key in ("decoder_receipt", "fc3", "model_state", "freeze_bundle", "run_manifest"):
        ref = binding[key]
        need(
            set(ref) in ({"sha256"}, {"sha256", "size_bytes"})
            and digest(ref["sha256"])
            and (
                "size_bytes" not in ref
                or type(ref["size_bytes"]) is int and ref["size_bytes"] >= 0
            ),
            "Compact references contain only a digest and optional size",
        )
    pins = FINAL[label]
    need(
        binding["production_complete_sha256"] == pins["complete"]
        and binding["encoder_sha256"] == pins["encoder"]
        and binding["fc3"]["sha256"] == pins["fc3"]
        and binding["voice_model_state_sha256"].startswith(pins["model_state_prefix"])
        and binding["model_state"]["sha256"].startswith(pins["decoder_state_prefix"])
        and manifest["space_sources"] == space_sources(),
        "Asset identity or inference sources differ",
    )

    def no_paths(value: Any) -> bool:
        if isinstance(value, dict):
            return all(
                k not in ("path", "json", "evidence", "decoder_provenance") and no_paths(v)
                for k, v in value.items()
            )
        if isinstance(value, list):
            return all(no_paths(v) for v in value)
        return not isinstance(value, str) or (
            not value.startswith(("/", "C:", "D:")) and "\\" not in value
        )

    need(no_paths(manifest), "Host provenance must not ship in Space manifests")
    probe = manifest["probe"]
    need(
        set(probe) == {"seed", "device", "dtype", "shape", "input", "output_sha256"}
        and probe["seed"] == 777
        and probe["device"] == "cpu"
        and probe["dtype"] == "float32"
        and probe["shape"] == ([1, 4096] if part == "voice" else [1, 3, 224, 224])
        and probe["input"]
        == ("standard_normal(1,598,257,2)" if part == "voice" else "random(1,4096)")
        and digest(probe["output_sha256"]),
        "Only registered CPU probes are accepted",
    )
    expected_file = f"voice-{label}.keras" if part == "voice" else f"decoder-{label}.safetensors"
    need(manifest["file"] == expected_file, "Unexpected asset name")
    resolve_model_asset(root, manifest)
    if part == "voice":
        need(
            manifest["sha256"] == FINAL[label]["encoder"],
            "Voice asset is not the byte-exact final .keras",
        )
    return manifest