Spaces:
Sleeping
Sleeping
Commit ·
5a5e72e
0
Parent(s):
Super-squash branch 'main' using huggingface_hub
Browse filesFiles changed (43)
- .gitattributesAdded+42
- DockerfileAdded+21
- README.mdAdded+10
- app.pyAdded+142
- assets/decoder-arcface.jsonAdded+66
- assets/decoder-facenet.jsonAdded+66
- assets/model-repository.jsonAdded+5
- assets/voice-arcface.jsonAdded+64
- assets/voice-facenet.jsonAdded+64
- example_data.pyAdded+127
- examples/example-1-credit.txtAdded+1
- examples/example-1-licence.jsonAdded+1
- examples/example-1.wavAdded+3
- examples/example-2-credit.txtAdded+1
- examples/example-2-licence.jsonAdded+1
- examples/example-2.wavAdded+3
- examples/example-3-credit.txtAdded+1
- examples/example-3-licence.jsonAdded+1
- examples/example-3.wavAdded+3
- examples/example-4-credit.txtAdded+1
- examples/example-4-licence.jsonAdded+1
- examples/example-4.wavAdded+3
- examples/example-5-credit.txtAdded+1
- examples/example-5-licence.jsonAdded+1
- examples/example-5.wavAdded+3
- examples/examples.jsonAdded+1
- inference-requirements.txtAdded+9
- requirements.txtAdded+104
- s2f/VENDORED.jsonAdded+123
- s2f/__init__.pyAdded
- s2f/asset_contract.pyAdded+258
- s2f/audio_features.pyAdded+87
- s2f/decoder_geometry_policy.pyAdded+683
- s2f/decoder_heads.pyAdded+38
- s2f/decoder_native_wflw98.pyAdded+916
- s2f/model_assets.pyAdded+99
- s2f/model_state.pyAdded+25
- s2f/native_wflw98_decoder.pyAdded+87
- s2f/pipeline.pyAdded+167
- s2f/pixel_codec.pyAdded+96
- s2f/qualified_audio.pyAdded+64
- s2f/runtime.pyAdded+99
- s2f/voice_model.pyAdded+99
123456789101112131415161718192021222324252627282930313233343536373839404142*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textexamples/example-1.wav filter=lfs diff=lfs merge=lfs -textexamples/example-2.wav filter=lfs diff=lfs merge=lfs -textexamples/example-3.png filter=lfs diff=lfs merge=lfs -textexamples/example-3.wav filter=lfs diff=lfs merge=lfs -textexamples/example-4.wav filter=lfs diff=lfs merge=lfs -textexamples/example-5.png filter=lfs diff=lfs merge=lfs -textexamples/example-5.wav filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021FROM python:3.10.12-bookworm@sha256:bac3a0e0d16125977e351c861e2f4b12ecafeaa6f72431dc970d0b9155103232
RUN apt-get update \ && apt-get install -y --no-install-recommends ffmpeg libgl1 libsm6 libxext6 \ && rm -rf /var/lib/apt/lists/*RUN useradd --create-home --uid 1000 --user-group userUSER userENV HOME=/home/user \ PATH=/home/user/venv/bin:$PATH \ HF_HOME=/home/user/.cache/huggingfaceRUN python -m venv /home/user/venv \ && mkdir -p /home/user/.cache/huggingface /home/user/appWORKDIR /home/user/app
COPY --chown=user:user requirements.txt .RUN pip install --no-cache-dir --require-hashes -r requirements.txtCOPY --chown=user:user . .
ENV GRADIO_SERVER_NAME=0.0.0.0 GRADIO_SERVER_PORT=7860 GRADIO_ANALYTICS_ENABLED=FalseEXPOSE 7860CMD ["python", "app.py"]12345678910---title: Speech2Faceemoji: 🗣️colorFrom: bluecolorTo: indigosdk: dockerapp_port: 7860pinned: falselicense: cc-by-nc-4.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142from __future__ import annotations
import osfrom pathlib import Pathfrom threading import Lock, Threadfrom typing import Any
from s2f import runtime as _runtime
os.environ["GRADIO_ANALYTICS_ENABLED"] = "False"
import gradio as gr
from s2f.pipeline import PAIRS, SpeechToFacefrom example_data import load_examples
ASSETS = Path(os.environ.get("S2F_ASSETS", Path(__file__).parent / "assets"))MODEL = SpeechToFace(ASSETS)_PAIR_LOAD_LOCKS = {pair: Lock() for pair in PAIRS}_MODEL_LOAD_LOCK = Lock()_READY_PAIRS: set[str] = set()EXAMPLES = load_examples(Path(os.environ.get("S2F_EXAMPLES", Path(__file__).parent / "examples")))
TITLE = "Speech2Face"INTRO = ( "Record or upload about six seconds of speech. It guesses a frontal, neutral face: " "a rough, average-looking estimate, not the speaker's real face. " "Do not use it to identify anyone.")STORY = ( "Follows Speech2Face (Oh et al., 2019) and Cole et al. (2017), with substitutions: " "voice to VGG-Face features to face. Trained on AVSpeech and VGGFace2.")CREDITS = ( "**Credits**\n" "- Speech2Face: Oh et al., CVPR 2019. Face decoder: Cole et al., CVPR 2017. " "This is an independent version with substitutions.\n" "- AVSpeech (Ephrat et al., 2018): annotations © Google LLC, " "[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). " "The videos belong to their owners.\n" "- VGGFace2 (Cao et al., 2018). No images are included.\n" "- VGG-Face (Parkhi et al., 2015), CC BY-NC 4.0. Not included; these models depend on it.\n" "- The faces can reflect biases in the training data.\n" "- Licence: [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/), " "non-commercial use only.")
def warm_models() -> None: failed = False for pair in PAIRS: try: with _PAIR_LOAD_LOCKS[pair]: if pair not in _READY_PAIRS: with _MODEL_LOAD_LOCK: MODEL.voice(pair) MODEL.decoder(pair) _READY_PAIRS.add(pair) except Exception: if not failed: print("Model warm-up failed; requests will retry loading.", flush=True) failed = True
def generate(audio: str | None, pair_label: str) -> Any: if audio is None: raise gr.Error("Record or upload a voice first.") pair = next(key for key, label in PAIRS.items() if label == pair_label) with _PAIR_LOAD_LOCKS[pair]: if pair not in _READY_PAIRS: with _MODEL_LOAD_LOCK: result = MODEL(audio, pair) _READY_PAIRS.add(pair) return result return MODEL(audio, pair)
def load_example(index: int | str | None) -> tuple[str | None, str | None, None]: if index is None: return None, None, None item = EXAMPLES[int(index)] return item["audio"], item["audio"], None
with gr.Blocks(title=TITLE, analytics_enabled=False) as demo: gr.Markdown(f"# {TITLE}\n{INTRO}") with gr.Tab("Try it"): with gr.Row(): with gr.Column(): audio = gr.Audio( sources=["microphone", "upload"], type="filepath", format=None, label="Your voice (about 6 s)", buttons=[], ) pair = gr.Radio(list(PAIRS.values()), value=PAIRS["arcface"], label="Decoder") button = gr.Button("Generate face", variant="primary") with gr.Column(): face = gr.Image(label="Generated face", type="numpy", height=320) button.click(generate, inputs=[audio, pair], outputs=face) if EXAMPLES: with gr.Accordion("Examples", open=True): gr.Markdown( "CC BY covers these clips; it does not give consent from the people shown." ) gr.Markdown("To request removal of an example, use this Space's Community tab.") with gr.Row(): with gr.Column(): example = gr.Dropdown( [(f"Example {i + 1}", i) for i in range(len(EXAMPLES))], value=0, label="Example voice", ) load_button = gr.Button("Load example") example_audio = gr.Audio( type="filepath", format=None, label="Example voice", interactive=False, buttons=[], ) load_button.click( load_example, inputs=example, outputs=[audio, example_audio, face], ) with gr.Tab("How it was built"): gr.Markdown(f"{STORY}\n\n{CREDITS}") if EXAMPLES: example_credits = gr.Textbox( value="\n\n".join( f"Example {i + 1}: {item['credit']}" for i, item in enumerate(EXAMPLES) ), label="Example credits", lines=12, interactive=False, )
if __name__ == "__main__": Thread(target=warm_models, daemon=True).start() demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "binding": { "decoder_arm": "cvlface_arcface_ir101_webface4m", "decoder_receipt": { "sha256": "4a46761d593de1c6ad6f4dc44cff66b9c1322bf3a2320bd74adc9f95d934fc80", "size_bytes": 3158 }, "encoder_sha256": "6c5a90621b19c27484daffcc903c35b608737935888b085c7fee286c8fb80f86", "fc3": { "sha256": "5a28ca9ee502c73bfed67088b1ef5ce1c6f8785581a69da7e3cf73a3f4377e87", "size_bytes": 16388506 }, "final_export_sha256": "4f13d6489dcab644482b2b85e7203237ebf422acf4b7321cf21b4a840febebe7", "freeze_bundle": { "sha256": "d2b91d79a52792bd64384cc98c7be04002c3bcf8cc86445b4335c7d8c0901fbb", "size_bytes": 5036 }, "model_state": { "sha256": "a691416e1a9c6cc0b254380dac9da0a741b6862d8dace1c472934d9c36a0420b", "size_bytes": 228270644 }, "production_complete_sha256": "5404a6b63057b0fc61909c5d738969843618e49db660d0acdb4e0dc150d4783e", "representative_seed": 31415, "run_manifest": { "sha256": "3016ebdf66d7ea1fc50f04c276ba6a18b9dab5cc2df1996821e5dc4b5389e00e", "size_bytes": 6385523 }, "voice_model_state_sha256": "a94d0e6b0967847d4f19733e584476f9f4e4f5cb8b1d234c96301095dd09de7d" }, "file": "decoder-arcface.safetensors", "label": "arcface", "probe": { "device": "cpu", "dtype": "float32", "input": "random(1,4096)", "output_sha256": "bb0b7ace5891b2372c944f42cc00419aeef2e2dd452f74c0bbfd9aeb30902817", "seed": 777, "shape": [ 1, 3, 224, 224 ] }, "schema": "speech2face.space-decoder-asset/v3", "sha256": "266f82398e0718d81881626d1c113062fa8d553588fea027556f467a87a16221", "size_bytes": 228266060, "space_sources": { "inference-requirements.txt": "42d70de51744f4509edd6af3081d77d719f7361e7280c59f1b497df0317d1cea", "s2f/VENDORED.json": "aa971c587a24935d422adb8c1085e4fd3c61ead6050a5a16f3e8952e4ff0c077", "s2f/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "s2f/asset_contract.py": "d661111c98f3bc4e850fc4c8b74accf0b80d9ef5044f24740b61ec7115a70e03", "s2f/audio_features.py": "070cc98b5c2138d646b39184066a79a36cbb518c1ecdde1f69e6091551db5c07", "s2f/decoder_geometry_policy.py": "9b4585ac37fc896b15826a1c61a53861a1012be037026e2494081730e7972f59", "s2f/decoder_heads.py": "c26b1edd0dc98ca0eaab2f49738d1b95bed0c022214f78fd6d7babc1970dd4f4", "s2f/decoder_native_wflw98.py": "63af676af0cc1705665a8d286a70f2db9714d1f8226e77a7b14fc454dd231687", "s2f/model_assets.py": "12f67980c1bdcc076b40bdcc58c0d3462446fc4e09382ce8ef9cb1a628bf1fc1", "s2f/model_state.py": "07abc03477f8933b582a718b854201a2c56691b37a75a25f2c1f9c3c25cc9900", "s2f/native_wflw98_decoder.py": "80f6d386687b2d98329bc9a031851b4b5ff3e79ff5438f197c0acff15e926224", "s2f/pipeline.py": "5e95724f66dfa16c7afddd248ac10060b620408676f0bb7a250046def0ad94a5", "s2f/pixel_codec.py": "6c507ccb1d462c5299b3a6daceb22f205d8672193a9c4eecf5c486d91d46f0aa", "s2f/qualified_audio.py": "446b5bce14b7a5c81c6762043ed3e491594e6c4e1df820cc14e2d1b061f04a42", "s2f/runtime.py": "708d6c5d794f7fd9e4343da9694a5a34393992eaa186b4c97ca5cfe9ab6eb0c9", "s2f/voice_model.py": "55670d8ec09285b2314eb2173d1917339b197c32dd8940991b216aa00ea075d3" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566{ "binding": { "decoder_arm": "facenet_pytorch_vggface2", "decoder_receipt": { "sha256": "73877719f6bb89fb5c33f591541c73c11373f32a1299f3c82d96f145cd4cfb96", "size_bytes": 3124 }, "encoder_sha256": "4541cc28dc4bbfcc6c2759a3149baeb1ed4ca68974223ec3830661ccf728171d", "fc3": { "sha256": "54567e09a4e0482f9ff9a4a392434a0624c2df173a4e8557ec03f301d9f19fc0", "size_bytes": 16388506 }, "final_export_sha256": "4acf19feea2b7fe853b4bb5425ab6398a2f997495be0581e333977c03724de5d", "freeze_bundle": { "sha256": "d2b91d79a52792bd64384cc98c7be04002c3bcf8cc86445b4335c7d8c0901fbb", "size_bytes": 5036 }, "model_state": { "sha256": "55721d4674b5553768cd25432da451b3a2ce373449d447b77686e8172a336a41", "size_bytes": 228270644 }, "production_complete_sha256": "856797bfabb21609eed7f7357c853f1d63c3ccc8db0f6bac47124e8303382336", "representative_seed": 31415, "run_manifest": { "sha256": "b88b3d0d720b4f0358cee46758d0adc5047b526effe3a3923286858536022cc7", "size_bytes": 6166213 }, "voice_model_state_sha256": "8e2bdb05504dff995c4ca21e6e82f8447b7e5f35543c56687438f599966f5546" }, "file": "decoder-facenet.safetensors", "label": "facenet", "probe": { "device": "cpu", "dtype": "float32", "input": "random(1,4096)", "output_sha256": "e5c7bc9a91256da6109e35acca096c01441296e454f2213f20e3ad5d451d01f7", "seed": 777, "shape": [ 1, 3, 224, 224 ] }, "schema": "speech2face.space-decoder-asset/v3", "sha256": "f18cfa9c8600eead5002e911b53514aa6f86368d5012c01d9260b932ffdb9bb9", "size_bytes": 228266052, "space_sources": { "inference-requirements.txt": "42d70de51744f4509edd6af3081d77d719f7361e7280c59f1b497df0317d1cea", "s2f/VENDORED.json": "aa971c587a24935d422adb8c1085e4fd3c61ead6050a5a16f3e8952e4ff0c077", "s2f/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "s2f/asset_contract.py": "d661111c98f3bc4e850fc4c8b74accf0b80d9ef5044f24740b61ec7115a70e03", "s2f/audio_features.py": "070cc98b5c2138d646b39184066a79a36cbb518c1ecdde1f69e6091551db5c07", "s2f/decoder_geometry_policy.py": "9b4585ac37fc896b15826a1c61a53861a1012be037026e2494081730e7972f59", "s2f/decoder_heads.py": "c26b1edd0dc98ca0eaab2f49738d1b95bed0c022214f78fd6d7babc1970dd4f4", "s2f/decoder_native_wflw98.py": "63af676af0cc1705665a8d286a70f2db9714d1f8226e77a7b14fc454dd231687", "s2f/model_assets.py": "12f67980c1bdcc076b40bdcc58c0d3462446fc4e09382ce8ef9cb1a628bf1fc1", "s2f/model_state.py": "07abc03477f8933b582a718b854201a2c56691b37a75a25f2c1f9c3c25cc9900", "s2f/native_wflw98_decoder.py": "80f6d386687b2d98329bc9a031851b4b5ff3e79ff5438f197c0acff15e926224", "s2f/pipeline.py": "5e95724f66dfa16c7afddd248ac10060b620408676f0bb7a250046def0ad94a5", "s2f/pixel_codec.py": "6c507ccb1d462c5299b3a6daceb22f205d8672193a9c4eecf5c486d91d46f0aa", "s2f/qualified_audio.py": "446b5bce14b7a5c81c6762043ed3e491594e6c4e1df820cc14e2d1b061f04a42", "s2f/runtime.py": "708d6c5d794f7fd9e4343da9694a5a34393992eaa186b4c97ca5cfe9ab6eb0c9", "s2f/voice_model.py": "55670d8ec09285b2314eb2173d1917339b197c32dd8940991b216aa00ea075d3" }}12345{ "repo_id": "ProgramComputer/Speech2Face-models", "revision": "d9098ed486e0822e755f39ce16b37acb4787ebfa", "schema": "speech2face.space-model-repository/v1"}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{ "binding": { "decoder_arm": "cvlface_arcface_ir101_webface4m", "decoder_receipt": { "sha256": "4a46761d593de1c6ad6f4dc44cff66b9c1322bf3a2320bd74adc9f95d934fc80", "size_bytes": 3158 }, "encoder_sha256": "6c5a90621b19c27484daffcc903c35b608737935888b085c7fee286c8fb80f86", "fc3": { "sha256": "5a28ca9ee502c73bfed67088b1ef5ce1c6f8785581a69da7e3cf73a3f4377e87", "size_bytes": 16388506 }, "final_export_sha256": "4f13d6489dcab644482b2b85e7203237ebf422acf4b7321cf21b4a840febebe7", "freeze_bundle": { "sha256": "d2b91d79a52792bd64384cc98c7be04002c3bcf8cc86445b4335c7d8c0901fbb", "size_bytes": 5036 }, "model_state": { "sha256": "a691416e1a9c6cc0b254380dac9da0a741b6862d8dace1c472934d9c36a0420b", "size_bytes": 228270644 }, "production_complete_sha256": "5404a6b63057b0fc61909c5d738969843618e49db660d0acdb4e0dc150d4783e", "representative_seed": 31415, "run_manifest": { "sha256": "3016ebdf66d7ea1fc50f04c276ba6a18b9dab5cc2df1996821e5dc4b5389e00e", "size_bytes": 6385523 }, "voice_model_state_sha256": "a94d0e6b0967847d4f19733e584476f9f4e4f5cb8b1d234c96301095dd09de7d" }, "file": "voice-arcface.keras", "label": "arcface", "probe": { "device": "cpu", "dtype": "float32", "input": "standard_normal(1,598,257,2)", "output_sha256": "a8527a4d513dd34a12dafa44693f7f1b7ca500d4088c358ebb838ecfd8012590", "seed": 777, "shape": [ 1, 4096 ] }, "schema": "speech2face.space-voice-asset/v3", "sha256": "6c5a90621b19c27484daffcc903c35b608737935888b085c7fee286c8fb80f86", "size_bytes": 592393484, "space_sources": { "inference-requirements.txt": "42d70de51744f4509edd6af3081d77d719f7361e7280c59f1b497df0317d1cea", "s2f/VENDORED.json": "aa971c587a24935d422adb8c1085e4fd3c61ead6050a5a16f3e8952e4ff0c077", "s2f/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "s2f/asset_contract.py": "d661111c98f3bc4e850fc4c8b74accf0b80d9ef5044f24740b61ec7115a70e03", "s2f/audio_features.py": "070cc98b5c2138d646b39184066a79a36cbb518c1ecdde1f69e6091551db5c07", "s2f/decoder_geometry_policy.py": "9b4585ac37fc896b15826a1c61a53861a1012be037026e2494081730e7972f59", "s2f/decoder_heads.py": "c26b1edd0dc98ca0eaab2f49738d1b95bed0c022214f78fd6d7babc1970dd4f4", "s2f/decoder_native_wflw98.py": "63af676af0cc1705665a8d286a70f2db9714d1f8226e77a7b14fc454dd231687", "s2f/model_assets.py": "12f67980c1bdcc076b40bdcc58c0d3462446fc4e09382ce8ef9cb1a628bf1fc1", "s2f/model_state.py": "07abc03477f8933b582a718b854201a2c56691b37a75a25f2c1f9c3c25cc9900", "s2f/native_wflw98_decoder.py": "80f6d386687b2d98329bc9a031851b4b5ff3e79ff5438f197c0acff15e926224", "s2f/pipeline.py": "5e95724f66dfa16c7afddd248ac10060b620408676f0bb7a250046def0ad94a5", "s2f/pixel_codec.py": "6c507ccb1d462c5299b3a6daceb22f205d8672193a9c4eecf5c486d91d46f0aa", "s2f/qualified_audio.py": "446b5bce14b7a5c81c6762043ed3e491594e6c4e1df820cc14e2d1b061f04a42", "s2f/runtime.py": "708d6c5d794f7fd9e4343da9694a5a34393992eaa186b4c97ca5cfe9ab6eb0c9", "s2f/voice_model.py": "55670d8ec09285b2314eb2173d1917339b197c32dd8940991b216aa00ea075d3" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364{ "binding": { "decoder_arm": "facenet_pytorch_vggface2", "decoder_receipt": { "sha256": "73877719f6bb89fb5c33f591541c73c11373f32a1299f3c82d96f145cd4cfb96", "size_bytes": 3124 }, "encoder_sha256": "4541cc28dc4bbfcc6c2759a3149baeb1ed4ca68974223ec3830661ccf728171d", "fc3": { "sha256": "54567e09a4e0482f9ff9a4a392434a0624c2df173a4e8557ec03f301d9f19fc0", "size_bytes": 16388506 }, "final_export_sha256": "4acf19feea2b7fe853b4bb5425ab6398a2f997495be0581e333977c03724de5d", "freeze_bundle": { "sha256": "d2b91d79a52792bd64384cc98c7be04002c3bcf8cc86445b4335c7d8c0901fbb", "size_bytes": 5036 }, "model_state": { "sha256": "55721d4674b5553768cd25432da451b3a2ce373449d447b77686e8172a336a41", "size_bytes": 228270644 }, "production_complete_sha256": "856797bfabb21609eed7f7357c853f1d63c3ccc8db0f6bac47124e8303382336", "representative_seed": 31415, "run_manifest": { "sha256": "b88b3d0d720b4f0358cee46758d0adc5047b526effe3a3923286858536022cc7", "size_bytes": 6166213 }, "voice_model_state_sha256": "8e2bdb05504dff995c4ca21e6e82f8447b7e5f35543c56687438f599966f5546" }, "file": "voice-facenet.keras", "label": "facenet", "probe": { "device": "cpu", "dtype": "float32", "input": "standard_normal(1,598,257,2)", "output_sha256": "ab4dd3db11406b76db2fe0fb6622e428194ce0d6dd161c5de4d583fa437e2e8f", "seed": 777, "shape": [ 1, 4096 ] }, "schema": "speech2face.space-voice-asset/v3", "sha256": "4541cc28dc4bbfcc6c2759a3149baeb1ed4ca68974223ec3830661ccf728171d", "size_bytes": 592393484, "space_sources": { "inference-requirements.txt": "42d70de51744f4509edd6af3081d77d719f7361e7280c59f1b497df0317d1cea", "s2f/VENDORED.json": "aa971c587a24935d422adb8c1085e4fd3c61ead6050a5a16f3e8952e4ff0c077", "s2f/__init__.py": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "s2f/asset_contract.py": "d661111c98f3bc4e850fc4c8b74accf0b80d9ef5044f24740b61ec7115a70e03", "s2f/audio_features.py": "070cc98b5c2138d646b39184066a79a36cbb518c1ecdde1f69e6091551db5c07", "s2f/decoder_geometry_policy.py": "9b4585ac37fc896b15826a1c61a53861a1012be037026e2494081730e7972f59", "s2f/decoder_heads.py": "c26b1edd0dc98ca0eaab2f49738d1b95bed0c022214f78fd6d7babc1970dd4f4", "s2f/decoder_native_wflw98.py": "63af676af0cc1705665a8d286a70f2db9714d1f8226e77a7b14fc454dd231687", "s2f/model_assets.py": "12f67980c1bdcc076b40bdcc58c0d3462446fc4e09382ce8ef9cb1a628bf1fc1", "s2f/model_state.py": "07abc03477f8933b582a718b854201a2c56691b37a75a25f2c1f9c3c25cc9900", "s2f/native_wflw98_decoder.py": "80f6d386687b2d98329bc9a031851b4b5ff3e79ff5438f197c0acff15e926224", "s2f/pipeline.py": "5e95724f66dfa16c7afddd248ac10060b620408676f0bb7a250046def0ad94a5", "s2f/pixel_codec.py": "6c507ccb1d462c5299b3a6daceb22f205d8672193a9c4eecf5c486d91d46f0aa", "s2f/qualified_audio.py": "446b5bce14b7a5c81c6762043ed3e491594e6c4e1df820cc14e2d1b061f04a42", "s2f/runtime.py": "708d6c5d794f7fd9e4343da9694a5a34393992eaa186b4c97ca5cfe9ab6eb0c9", "s2f/voice_model.py": "55670d8ec09285b2314eb2173d1917339b197c32dd8940991b216aa00ea075d3" }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127from __future__ import annotations
import hashlibimport jsonfrom datetime import datetime, timedeltafrom pathlib import Pathimport reimport structfrom typing import Any
SCHEMA = "speech2face.space-examples/v2/data"
def need(ok: Any, message: str) -> None: if not ok: raise ValueError(message)
def check_evidence(evidence: dict[str, Any], credit: str) -> None: need( set(evidence) == {"youtube_id", "captured_utc", "method", "part", "item", "raw_response_sha256"} and evidence["method"] == "YouTube Data API v3 videos.list" and evidence["part"] == "status,snippet,contentDetails" and re.fullmatch(r"[0-9a-f]{64}", evidence["raw_response_sha256"]) is not None, "Invalid public example evidence schema", ) item = evidence["item"] need( set(item) == {"id", "status", "contentDetails", "snippet"} and re.fullmatch(r"[A-Za-z0-9_-]{11}", item["id"]) is not None and item["id"] == evidence["youtube_id"] and "https://www.youtube.com/watch?v=" + item["id"] in credit and item["status"] == {"license": "creativeCommon", "privacyStatus": "public"} and item["contentDetails"] == {"licensedContent": False}, "Example needs public CC source/credit binding", ) snippet = item["snippet"] need( set(snippet) == {"channelTitle", "channelId", "title", "publishedAt"} and all(isinstance(v, str) and v.strip() for v in snippet.values()), "Invalid example source snippet", ) date = datetime.fromisoformat(evidence["captured_utc"].replace("Z", "+00:00")) need(date.utcoffset() == timedelta(0), "Example needs dated UTC licence evidence")
def load_examples(root: str | Path) -> list[dict[str, Any]]: root = Path(root) if not root.exists(): return [] need(root.is_dir() and not root.is_symlink(), "Invalid example data directory")
def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]: result: dict[str, Any] = {} for key, value in items: need(key not in result, "Duplicate example data key") result[key] = value return result
manifest = json.loads( (root / "examples.json").read_text(encoding="utf-8"), object_pairs_hook=pairs, ) need( isinstance(manifest.get("examples"), list) and 1 <= len(manifest["examples"]) <= 8, "One to eight reviewed examples required", ) need( set(manifest) == {"schema", "examples"} and manifest["schema"] == SCHEMA, "Reviewed examples schema differs", ) rows: list[dict[str, Any]] rows, expected_files = [], {"examples.json"} for number, entry in enumerate(manifest["examples"], 1): need( set(entry) == {"id", "audio", "evidence", "credit_file", "credit"} and entry["id"] == f"example-{number}" and isinstance(entry["credit"], str), "Invalid example record", ) resolved: dict[str, str] = {} for field in ("audio", "evidence", "credit_file"): ref = entry[field] name = ref["file"] need( set(ref) == {"file", "sha256", "size_bytes"} and Path(name).name == name and name not in ("", ".", "..") and "\\" not in name and ":" not in name and name not in expected_files, "Unsafe/duplicate example data path", ) expected_files.add(name) path = root / name need( path.is_file() and not path.is_symlink() and 0 < ref["size_bytes"] <= 8 << 20 and path.stat().st_size == ref["size_bytes"], "Example file length differs", ) raw = path.read_bytes() need(hashlib.sha256(raw).hexdigest() == ref["sha256"], "Example file SHA differs") if field == "audio": need( raw[:4] == b"RIFF" and raw[8:16] == b"WAVEfmt " and struct.unpack("<HHIIHHH", raw[20:38]) == (3, 1, 16000, 64000, 4, 32, 0) and raw[38:42] == b"fact" and raw[50:54] == b"data" and struct.unpack("<II", raw[42:50]) == (4, 96000) and struct.unpack("<I", raw[4:8])[0] == len(raw) - 8 and struct.unpack("<I", raw[54:58])[0] == 384000 and len(raw) == 384058, "Example must be a six-second 16 kHz mono float WAV", ) elif field == "credit_file": need(raw == (entry["credit"] + "\n").encode("utf-8"), "Example credit differs") else: evidence = json.loads(raw, object_pairs_hook=pairs) check_evidence(evidence, entry["credit"]) resolved[field] = str(path.absolute()) rows.append({**entry, **resolved, "audio_sha256": entry["audio"]["sha256"]}) need({p.name for p in root.iterdir()} == expected_files, "Unlisted example data must not ship") return rows1UMA MOOC, MOOC UMA Claves de educación financiera para la ciudadanía: Módulo 5 Video 6. https://www.youtube.com/watch?v=_bLWIeFsG-A. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.1{"captured_utc":"2026-11-11T16:39:45.403308Z","item":{"contentDetails":{"licensedContent":false},"id":"_bLWIeFsG-A","snippet":{"channelId":"UCYCpka3pIEGYjjcrssW10FQ","channelTitle":"UMA MOOC","publishedAt":"2016-10-11T06:57:46Z","title":"MOOC UMA Claves de educación financiera para la ciudadanía: Módulo 5 Video 6"},"status":{"license":"creativeCommon","privacyStatus":"public"}},"method":"YouTube Data API v3 videos.list","part":"status,snippet,contentDetails","raw_response_sha256":"00ad7362c63ebc16da2170ab5697ca10161bb6da6f186536c573288ec140fb2f","youtube_id":"_bLWIeFsG-A"}123version https://git-lfs.github.com/spec/v1oid sha256:c6b81fefcb73eb119675ffad1d36ae168144be90f61bfffb0eae75b53bcefd63size 3840581NIOS Senior Secondary Courses, 503 Developing Writing Skills In Lower Classes. https://www.youtube.com/watch?v=7OAbZ10TB9M. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.1{"captured_utc":"2026-11-11T16:37:40.931302Z","item":{"contentDetails":{"licensedContent":false},"id":"7OAbZ10TB9M","snippet":{"channelId":"UC6R9rI-1iEsPCPmvzlunKDg","channelTitle":"NIOS Senior Secondary Courses","publishedAt":"2017-11-10T11:30:31Z","title":"503 Developing Writing Skills In Lower Classes"},"status":{"license":"creativeCommon","privacyStatus":"public"}},"method":"YouTube Data API v3 videos.list","part":"status,snippet,contentDetails","raw_response_sha256":"132c8fce0ab86566f895f90aef2f2efbf2b317fd278ab1f11cb8a695624d9912","youtube_id":"7OAbZ10TB9M"}123version https://git-lfs.github.com/spec/v1oid sha256:938040ed903d4f9db0a15945e54cee25fbf6ec0b97cba39944bf4429ae6b35c6size 3840581UN University, トランジション藤野:より良き未来へ. https://www.youtube.com/watch?v=BWreEnRE7A8. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.1{"captured_utc":"2026-11-11T16:38:01.984878Z","item":{"contentDetails":{"licensedContent":false},"id":"BWreEnRE7A8","snippet":{"channelId":"UCtjLPHCyI5V-xuumAXzAizA","channelTitle":"UN University","publishedAt":"2011-08-16T02:37:48Z","title":"トランジション藤野:より良き未来へ"},"status":{"license":"creativeCommon","privacyStatus":"public"}},"method":"YouTube Data API v3 videos.list","part":"status,snippet,contentDetails","raw_response_sha256":"6a908a9172724dc0e3708a1f66422cd69a200c0b4acf755f4135eb99ed4b84da","youtube_id":"BWreEnRE7A8"}123version https://git-lfs.github.com/spec/v1oid sha256:20cf687ccb9dae5e4e2250db14de2e3af6788ce0bcb5616d5d4a291b9650107asize 3840581FISCALITÉuqtr.ca, Semaine 2 - Avantages imposables. https://www.youtube.com/watch?v=rtV0k5a-xfo. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.1{"captured_utc":"2026-11-11T16:40:57.190180Z","item":{"contentDetails":{"licensedContent":false},"id":"rtV0k5a-xfo","snippet":{"channelId":"UCGKdsD2EEVN-PLLXrI_Swug","channelTitle":"FISCALITÉuqtr.ca","publishedAt":"2015-03-09T15:54:38Z","title":"Semaine 2 - Avantages imposables"},"status":{"license":"creativeCommon","privacyStatus":"public"}},"method":"YouTube Data API v3 videos.list","part":"status,snippet,contentDetails","raw_response_sha256":"0299537f6c676063c0462613d0fd8b4d39ec984caf074e0c5185a48cbab6d2cf","youtube_id":"rtV0k5a-xfo"}123version https://git-lfs.github.com/spec/v1oid sha256:a8921af7b46aa714f937d70de6dcc9da0918a99a9648637934bef93e6ee50489size 3840581Dig In Seattle, Growing and Planting Clematis. https://www.youtube.com/watch?v=FK10h4h52ok. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.1{"captured_utc":"2026-11-11T16:38:13.011363Z","item":{"contentDetails":{"licensedContent":false},"id":"FK10h4h52ok","snippet":{"channelId":"UCX9v0bDQ60K1mSTnLZjJd5A","channelTitle":"Dig In Seattle","publishedAt":"2015-07-18T13:21:15Z","title":"Growing and Planting Clematis"},"status":{"license":"creativeCommon","privacyStatus":"public"}},"method":"YouTube Data API v3 videos.list","part":"status,snippet,contentDetails","raw_response_sha256":"23254690293b3b165a0ce228ea8a4e5aed6da642ad458d065393544dfe56a489","youtube_id":"FK10h4h52ok"}123version https://git-lfs.github.com/spec/v1oid sha256:87ae0d09c0517c18aba5e2f99d72faae43987610f0d807fd826bddcd5ef9bd2dsize 3840581{"examples":[{"audio":{"file":"example-1.wav","sha256":"c6b81fefcb73eb119675ffad1d36ae168144be90f61bfffb0eae75b53bcefd63","size_bytes":384058},"credit":"UMA MOOC, MOOC UMA Claves de educación financiera para la ciudadanía: Módulo 5 Video 6. https://www.youtube.com/watch?v=_bLWIeFsG-A. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.","credit_file":{"file":"example-1-credit.txt","sha256":"a5707b38da18e7641dd8431c988264fe89d7443c2573cc0be243bc95b9bfa7e5","size_bytes":304},"evidence":{"file":"example-1-licence.json","sha256":"3c4b173b4e14fefaca13a419c1127e0a9d0708a4502c6b1b6dc0142b88ee13e0","size_bytes":583},"id":"example-1"},{"audio":{"file":"example-2.wav","sha256":"938040ed903d4f9db0a15945e54cee25fbf6ec0b97cba39944bf4429ae6b35c6","size_bytes":384058},"credit":"NIOS Senior Secondary Courses, 503 Developing Writing Skills In Lower Classes. https://www.youtube.com/watch?v=7OAbZ10TB9M. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.","credit_file":{"file":"example-2-credit.txt","sha256":"2f3f3dc50a257cb5d95680d7f5816de893b1ca82825822a70aa15971e876a55d","size_bytes":292},"evidence":{"file":"example-2-licence.json","sha256":"26bb8ef3750e4b411ac094e2a6a063e5a1dd22eaff42a99626cf6115e50ac179","size_bytes":571},"id":"example-2"},{"audio":{"file":"example-3.wav","sha256":"20cf687ccb9dae5e4e2250db14de2e3af6788ce0bcb5616d5d4a291b9650107a","size_bytes":384058},"credit":"UN University, トランジション藤野:より良き未来へ. https://www.youtube.com/watch?v=BWreEnRE7A8. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.","credit_file":{"file":"example-3-credit.txt","sha256":"38548092b2dbadf3d566b036c7719898ee3dfb2a4305c6d1fe4dfd1d5ee5250c","size_bytes":281},"evidence":{"file":"example-3-licence.json","sha256":"0df71ba4bf590e42090fe05db2523fe126e26a1331e46190813104440e85cf88","size_bytes":560},"id":"example-3"},{"audio":{"file":"example-4.wav","sha256":"a8921af7b46aa714f937d70de6dcc9da0918a99a9648637934bef93e6ee50489","size_bytes":384058},"credit":"FISCALITÉuqtr.ca, Semaine 2 - Avantages imposables. https://www.youtube.com/watch?v=rtV0k5a-xfo. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.","credit_file":{"file":"example-4-credit.txt","sha256":"8e5af413086106d6aaa9ccd9c5e65a92a52f863e1cfdf793ca97f069ad6c6039","size_bytes":266},"evidence":{"file":"example-4-licence.json","sha256":"81edd644d29c8c78935ad5096f2c4ffa91c511c87a7640e183476e89bbb11496","size_bytes":545},"id":"example-4"},{"audio":{"file":"example-5.wav","sha256":"87ae0d09c0517c18aba5e2f99d72faae43987610f0d807fd826bddcd5ef9bd2d","size_bytes":384058},"credit":"Dig In Seattle, Growing and Planting Clematis. https://www.youtube.com/watch?v=FK10h4h52ok. licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Trimmed, cropped and resampled for this demo. Clips shorter than 6 s are repeated to fill 6 s.","credit_file":{"file":"example-5-credit.txt","sha256":"421f3a9e8182f815c6a89d1a488b571150ea6c9443e9884cf3f7bf5351ccc472","size_bytes":260},"evidence":{"file":"example-5-licence.json","sha256":"15be91c5ec0ac4f1da07a22c03c22ee57c6ee199fae4c0885292cfbbda7274f9","size_bytes":539},"id":"example-5"}],"schema":"speech2face.space-examples/v2/data"}123456789--extra-index-url https://download.pytorch.org/whl/cu124tensorflow==2.20.0keras==3.11.3numpy==2.2.6h5py==3.14.0torch==2.5.1+cu124safetensors==0.4.5scipy==1.14.1av==12.3.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104--require-hashes--extra-index-url https://download.pytorch.org/whl/cu124absl-py==2.5.1 --hash=sha256:721200f2f0e9960f2ca9dc3a2a706b201f5f75d812c158f059cbbe29eeafbdb8annotated-doc==0.0.6 --hash=sha256:361ca0950cc7082f53fa69e9328409f40a62c61e57e0a47e1825a08078a58a53annotated-types==0.8.0 --hash=sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0anyio==4.16.0 --hash=sha256:c66ae634e0b8228396b801741beb3294326d4b6102f7bba4041c0dfb58c29026astunparse==1.6.3 --hash=sha256:c2652417f2c8b5bb325c885ae329bdf3f86424075c4fd1a128674bc6fba4b8e8av==12.3.0 --hash=sha256:0220fce2a62d71cc5e89617419b6224ddb43f1753b00f68b5c9af8b5f41d38c9brotli==1.2.1 --hash=sha256:f760d9a9c441bfc87eee720ddb0946d3e19995b20983ae14038e033f1664efcbcertifi==2026.10.23 --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1charset-normalizer==3.5.2 --hash=sha256:8a893cc101149f80a653f82062ebc95b34525a2614382e1da5458fe7c6997249click==8.5.1 --hash=sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37exceptiongroup==1.3.1 --hash=sha256:a7a39a3bd276781e98394987d3a5701d0c4edffb633bb7a5144577f82c773598fastapi==0.162.5 --hash=sha256:5303c67415fde762889ca337db79d27b755b8bd09cef314fa7a4340bb30bfd2bfilelock==4.1.0 --hash=sha256:2ce9818e3e2d8f284c1a964414447ef148d42a5fd5e2a477a7118e574b293ec1flatbuffers==25.12.19 --hash=sha256:7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4fsspec==2026.9.0 --hash=sha256:8dd6e646e99ea382bd85f97a45e6b526a442d79423a7dc673f1e2756d05fcb5fgast==0.7.0 --hash=sha256:99cbf1365633a74099f69c59bd650476b96baa5ef196fec88032b00b31ba36f7google-pasta==0.2.0 --hash=sha256:b32482794a366b5366a32c92a9a9201b107821889935a02b3e51f6b432ea84edgradio==6.32.0 --hash=sha256:0d5170c3dfa445ee932979ecf0abac43a3814b603868d4d2c6efec5b5605372cgradio-client==2.7.2 --hash=sha256:12c9d2d940df28eb8dce58eef61f5e808265ad87bbbca53704d1330aa701e5e2groovy==0.1.2 --hash=sha256:7f7975bab18c729a257a8b1ae9dcd70b7cafb1720481beae47719af57c35fa64grpcio==1.85.1 --hash=sha256:1f04e51dc65c82af420f6cd177ea76132a78c14dc7adc3044f549b419bc70487h11==0.16.0 --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86h5py==3.14.0 --hash=sha256:1223b902ef0b5d90bcc8a4778218d6d6cd0f5561861611eda59fa6c52b922f4dhf-gradio==0.4.1 --hash=sha256:76b8cb8be6abe62d74c1ad2d35b42f0629db89aa9e1a8d033cecfe7c856eeab3hf-xet==1.8.0 --hash=sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6dhttpcore==1.0.9 --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55httpcore2==2.14.0 --hash=sha256:4c4f64f4b544afeb778c42c0ffb5941b29e671157e90ed3f6dc787c4bca90cd1httpx==0.28.1 --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59adhttpx2==2.14.0 --hash=sha256:9d20c13a10bae1773a0be3b0f1e5beeb4bdd549bc3a2ba18efa32897c65403e4huggingface-hub==2.4.0 --hash=sha256:42ecfd93ede47bdd333daebbf66a32d7bfe2e18752754fe4d2d4f98a0179d801idna==3.20 --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582cjinja2==3.1.6 --hash=sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67keras==3.11.3 --hash=sha256:f484f050e05ee400455b05ec8c36ed35edc34de94256b6073f56cfe68f65491flibclang==18.1.1 --hash=sha256:c533091d8a3bbf7460a00cb6c1a71da93bffe148f172c7d03b1c31fbf8aa2a0bmarkdown==3.10.3 --hash=sha256:fa6c92a00a4a3c98b22728c64a935ae1928250ae65058a6ded814d2cc29a4ceamarkdown-it-py==4.3.0 --hash=sha256:7aa1511a46c39138de78d9eba92ce47e63124d8003fc98b3a351909e04239efamarkupsafe==3.0.4 --hash=sha256:d1aca03ede943eb80ab3d63bb082c84b7aab85ea83bd0fd0c200260945fb49d9mdurl==0.1.2 --hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8ml-dtypes==0.6.0 --hash=sha256:6ec0d244a5bba12239025389ad88bbfb45f9f10e25ab4f678e9a4768ebd47532mpmath==1.3.0 --hash=sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2cnamex==0.1.0 --hash=sha256:e2012a474502f1e2251267062aae3114611f07df4224b6e06334c57b0f2ce87cnetworkx==3.4.2 --hash=sha256:df5d4365b724cf81b8c6a7312509d0c22386097011ad1abe274afd5e9d3bbc5fnumpy==2.2.6 --hash=sha256:fc7b73d02efb0e18c000e9ad8b83480dfcd5dfd11065997ed4c6747470ae8915nvidia-cublas-cu12==12.4.5.8 --hash=sha256:2fc8da60df463fdefa81e323eef2e36489e1c94335b5358bcb38360adf75ac9bnvidia-cuda-cupti-cu12==12.4.127 --hash=sha256:9dec60f5ac126f7bb551c055072b69d85392b13311fcc1bcda2202d172df30fbnvidia-cuda-nvrtc-cu12==12.4.127 --hash=sha256:a178759ebb095827bd30ef56598ec182b85547f1508941a3d560eb7ea1fbf338nvidia-cuda-runtime-cu12==12.4.127 --hash=sha256:64403288fa2136ee8e467cdc9c9427e0434110899d07c779f25b5c068934faa5nvidia-cudnn-cu12==9.1.0.70 --hash=sha256:165764f44ef8c61fcdfdfdbe769d687e06374059fbb388b6c89ecb0e28793a6fnvidia-cufft-cu12==11.2.1.3 --hash=sha256:f083fc24912aa410be21fa16d157fed2055dab1cc4b6934a0e03cba69eb242b9nvidia-curand-cu12==10.3.5.147 --hash=sha256:a88f583d4e0bb643c49743469964103aa59f7f708d862c3ddb0fc07f851e3b8bnvidia-cusolver-cu12==11.6.1.9 --hash=sha256:19e33fa442bcfd085b3086c4ebf7e8debc07cfe01e11513cc6d332fd918ac260nvidia-cusparse-cu12==12.3.1.170 --hash=sha256:ea4f11a2904e2a8dc4b1833cc1b5181cde564edd0d5cd33e3c168eff2d1863f1nvidia-nccl-cu12==2.21.5 --hash=sha256:8579076d30a8c24988834445f8d633c697d42397e92ffc3f63fa26766d25e0a0nvidia-nvjitlink-cu12==12.4.127 --hash=sha256:06b3b9b25bf3f8af351d664978ca26a16d2c5127dbd53c0497e28d1fb9611d57nvidia-nvtx-cu12==12.4.127 --hash=sha256:781e950d9b9f60d8241ccea575b32f5105a5baf4c2351cab5256a24869f12a1aopentelemetry-api==1.45.2 --hash=sha256:2cbd737377e710ee740d261c94e93fa0f08e6d037c18f17513cc0a2d94479a34opt-einsum==3.4.0 --hash=sha256:69bb92469f86a1565195ece4ac0323943e83477171b91d24c35afe028a90d7cdoptree==0.20.0 --hash=sha256:4fcebed2ae8ff91dafc958e554bfde0e0ce3974d869eeb75da14b984854b6ce2orjson==3.13.0 --hash=sha256:93c70a5e22bbbbdeafc7b273441e8452a196041d67fd4d9a9c450c66370a8486packaging==26.3 --hash=sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1cpandas==2.3.3 --hash=sha256:dd7478f1463441ae4ca7308a70e90b33470fa593429f9d4c578dd00d1fa78838pillow==12.3.0 --hash=sha256:f0606c8bf2cdefea14a43530f7657cbbb7ecf1c4222512492ef4a4434a9501ecpip==25.2 --hash=sha256:6d67a2b4e7f14d8b31b8b52648866fa717f45a1eb70e83002f4331d07e953717protobuf==7.36.2 --hash=sha256:89f23aa53c24553a2416fd4fd1ec06f74fa42b14b546d8883128813f775bbfd2pydantic==2.14.3 --hash=sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8pydantic-core==2.50.4 --hash=sha256:ed9c0b6f236648dbf30d57e9f57e1f74878caafa04833a19f529b5ba5164b7a8pydub==0.25.1 --hash=sha256:65617e33033874b59d87db603aa1ed450633288aefead953b30bded59cb599a6pygments==2.21.0 --hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9python-dateutil==3.0.0 --hash=sha256:3c79630202e4152c6add678446984236efe4f57e84d8e892aab0637bab82e9fdpython-multipart==0.0.32 --hash=sha256:ff6d3f776f16878c894e52e107296ffc890e913c611b1a4ec6c44e2821fe2e23pytz==2026.6 --hash=sha256:7fed3fee8fd6bd4a2b7b75a8d56021d0624127bf69bd5691f115db929ac570b3pyyaml==6.0.3 --hash=sha256:9c7708761fccb9397fe64bbc0395abcae8c4bf7b0eac081e12b809bf47700d0brequests==2.34.2 --hash=sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0rich==15.0.0 --hash=sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bbsafehttpx==0.1.7 --hash=sha256:c4f4a162db6993464d7ca3d7cc4af0ffc6515a606dfd220b9f82c6945d869cdesafetensors==0.4.5 --hash=sha256:c6d156bdb26732feada84f9388a9f135528c1ef5b05fae153da365ad4319c4c5scipy==1.14.1 --hash=sha256:8e32dced201274bf96899e6491d9ba3e9a5f6b336708656466ad0522d8528f69semantic-version==2.10.0 --hash=sha256:de78a3b8e0feda74cabc54aab2da702113e33ac9d9eb9d2389bcf1f58b7d9177setuptools==80.9.0 --hash=sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922shellingham==1.5.4 --hash=sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686six==1.17.0 --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274starlette==1.7.0 --hash=sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93esympy==1.13.1 --hash=sha256:db36cdc64bf61b9b24578b6f7bab1ecdd2452cf008f34faa33776680c26d66f8tensorboard==2.20.0 --hash=sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6tensorboard-data-server==0.7.2 --hash=sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530tensorflow==2.20.0 --hash=sha256:7abd7f3a010e0d354dc804182372779a722d474c4d8a3db8f4a3f5baef2a591etermcolor==3.3.0 --hash=sha256:cf642efadaf0a8ebbbf4bc7a31cec2f9b5f21a9f726f4ccbb08192c9c26f43a5tomli==2.5.0 --hash=sha256:32a7b79ac57a2e83670ce329ccf675798bc5a2094783a63676866b70503f2e2btomlkit==0.14.0 --hash=sha256:592064ed85b40fa213469f81ac584f67a4f2992509a7c3ea2d632208623a3680torch==2.5.1+cu124 --hash=sha256:9dde30f399ca22137455cca4d47140dfb7f4176e2d16a9729fc044eebfadb13atqdm==4.70.1 --hash=sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73triton==3.1.0 --hash=sha256:6b0dd10a925263abbe9fa37dcde67a5e9b2383fc269fdf59f5657cac38c5d1d8truststore==0.10.5 --hash=sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951ctyper==0.29.1 --hash=sha256:00dbc549c13428bec1be55fe1f4d0fb8c6637a310e4f178ef14abe9534ee7b58typing-extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8typing-inspection==0.4.5 --hash=sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39tzdata==2026.6 --hash=sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aecurllib3==2.8.0 --hash=sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3uvicorn==0.54.0 --hash=sha256:505bdb0f318731d45f1f712071fc781a8981f6847a31c902c9f5e652d4f67fafwerkzeug==3.1.9 --hash=sha256:6392e50c78460ba618e5b21f08a71f59c99ce99cdc6cf6e3dd7e6ccca8754fabwheel==0.48.0 --hash=sha256:3217dcc807155e45db462d7ef2431f5ddda0d7273b700d05a67b271ceb1287abwrapt==2.5.2 --hash=sha256:0fa61d2f1033039aa47f8f1b4e076ca3c9d0fc08e448c4b1bd06d8b59da89cbf123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123{ "audio_features.py": { "source": "src/audio_features.py", "sha256": "070cc98b5c2138d646b39184066a79a36cbb518c1ecdde1f69e6091551db5c07", "source_sha256": "7e1d5b7baa90bc265c826b6e1a9aebbaf904cc04dcd5faab42a258667a745047", "verbatim": false, "changes": [ "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ] }, "voice_model.py": { "source": "workstreams/20261007/voice/voice-training-v1/candidate/src/voice_model.py", "sha256": "55670d8ec09285b2314eb2173d1917339b197c32dd8940991b216aa00ea075d3", "source_sha256": "f8b78bf1613e2774586c76edca38a8e7a407a8736a27921ce5d5f0a26ac3d56f", "verbatim": false, "changes": [ "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ] }, "decoder_geometry_policy.py": { "source": "src/decoder_geometry_policy.py", "sha256": "9b4585ac37fc896b15826a1c61a53861a1012be037026e2494081730e7972f59", "source_sha256": "0d72c7ce3daf0785d5a465f1e5bc7da1cdca85612704f6230b981601176ddec2", "verbatim": false, "changes": [ "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ] }, "decoder_native_wflw98.py": { "source": "src/decoder_native_wflw98.py", "sha256": "63af676af0cc1705665a8d286a70f2db9714d1f8226e77a7b14fc454dd231687", "source_sha256": "b3dfc8dcae7f3b346e1b492948ebd9aa945056320cb1d2898168179f26d1c3d5", "verbatim": false, "changes": [ "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ] }, "native_wflw98_decoder.py": { "source": "src/native_wflw98_decoder.py", "sha256": "80f6d386687b2d98329bc9a031851b4b5ff3e79ff5438f197c0acff15e926224", "source_sha256": "218f91383de9aecc91e2adb449330d1c33e6e8d7662995208e9bb68b24454fb9", "verbatim": false, "changes": [ "Only import changed: .paper_decoder -> .decoder_heads. Both decoder classes and their computation are verbatim; exporter checks their source and probe bitwise.", "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ] }, "decoder_heads.py": { "source": "src/paper_decoder.py", "sha256": "c26b1edd0dc98ca0eaab2f49738d1b95bed0c022214f78fd6d7babc1970dd4f4", "source_sha256": "ef459ea5282f49d8663713d90c5d59e5b624be826a552c2cc8b404fedc81a70e", "verbatim": false, "changes": [ "Extracted DECODER_FEATURE_DIM unchanged and _make_decoder_heads as exactly textwrap.dedent(inspect.getsource(original)), preserving relative continuation indentation. Inference-only header/import scaffolding. Exporter compares the dedented original to the exact copied function source and DECODER_FEATURE_DIM by value; the bitwise probe is unchanged.", "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ], "symbols": [ "DECODER_FEATURE_DIM", "_make_decoder_heads" ] }, "pixel_codec.py": { "verbatim": false, "changes": [ "Extracted _chunk, encode_png_rgb, decode_png_rgb and quantize_rgb verbatim. Added minimal imports, IMAGE_SIZE=224, the unchanged PNG signature and local EvidenceError(ValueError). Exporter compares all four function sources, _PNG_SIGNATURE and IMAGE_SIZE by value.", "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ], "symbols": [ "_chunk", "encode_png_rgb", "decode_png_rgb", "quantize_rgb" ], "source": "src/decoder_heldout_evaluation_v1.py", "source_sha256": "708ca20db33ca5c1ec7473c38b7c9dfc07c61ca1877b7023d76e143100f6412c", "sha256": "6c507ccb1d462c5299b3a6daceb22f205d8672193a9c4eecf5c486d91d46f0aa" }, "model_state.py": { "verbatim": false, "changes": [ "Extracted reloaded_variables_hash verbatim. Added hashlib and local need(ok,message) raising ValueError instead of importing the project IO module. The exporter checks function source equality.", "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ], "symbols": [ "reloaded_variables_hash" ], "source": "workstreams/20261007/voice/voice-training-v1/candidate/src/voice_evaluation_c55_v2.py", "source_sha256": "7f4ded413524aa004da3a8e9a249f77a8430a25f2754f0a964eaab6ccb473d54", "sha256": "07abc03477f8933b582a718b854201a2c56691b37a75a25f2c1f9c3c25cc9900" }, "qualified_audio.py": { "source": "workstreams/20261007/voice/voice-training-v1/candidate/src/voice_audio_v1.py", "source_sha256": "eeb8e9f2cf0bef1d602e987e5fd9452a5d5c0f0ea3d3d242a294eda97c5bf1e9", "sha256": "446b5bce14b7a5c81c6762043ed3e491594e6c4e1df820cc14e2d1b061f04a42", "verbatim": false, "symbols": [ "decode_row: retained/resampler/demux block" ], "changes": [ "Extracted the decode/count/retain loop verbatim, including first stream, one codec thread, fltp mono 16000 resampler, packet-error policy and first-six-seconds retention. Uses the unchanged audio_features.repeat_or_trim_waveform.", "Added filepath and wheel-version admission; omitted corpus-specific row/probe admission and the STFT/receipt return. The host checker authenticates the source row and compares the actual Gradio filepath/PyAV waveform and STFT against the qualified worker bitwise. The voice exporter compares the complete extracted loop source exactly.", "Comments and docstrings removed; reformatted to the owner's style with type hints; no behaviour change (AST-equal after removing docstrings and annotations)", "Source-style round 2: precise available types or typing imports replace object annotations; empty docstring suites use pass. Registered source comparisons use speech2face.space-source-comparison/normalized-ast-v1 (function-scope annotations and permitted typing imports only); original source/source_sha256 evidence is unchanged.", "Round 3: owner-style corrections and speech2face.space-source-comparison/normalized-ast-v2 preserve runtime typing bindings, unsafe bare-annotation effects, literal whitespace and annotations-future imports. Numerical function bodies and original source/source_sha256 evidence are unchanged." ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258from __future__ import annotations
import hashlibimport jsonfrom pathlib import Pathfrom 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 manifest123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687from __future__ import annotations
import mathfrom pathlib import Path
import numpy as np
PAPER_SAMPLE_RATE = 16_000PAPER_DURATION_SECONDS = 6.0PAPER_FRAME_LENGTH = 400PAPER_HOP_LENGTH = 160PAPER_FFT_LENGTH = 512PAPER_TIME_FRAMES = 598PAPER_FREQUENCY_BINS = 257PAPER_SPECTROGRAM_SHAPE = (PAPER_TIME_FRAMES, PAPER_FREQUENCY_BINS, 2)
def adjust_stft_width(stft: np.ndarray, target_width: int = 601) -> np.ndarray: if stft.ndim != 2 or stft.shape[1] <= 0: raise ValueError(f"STFT must be rank 2 with a non-empty time axis, got {stft.shape}") if target_width <= 0: raise ValueError("target_width must be positive") if stft.shape[1] == target_width: return stft if stft.shape[1] > target_width: return stft[:, :target_width] repeats = int(math.ceil(target_width / stft.shape[1])) return np.tile(stft, (1, repeats))[:, :target_width]
def repeat_or_trim_waveform(waveform: np.ndarray, target_samples: int) -> np.ndarray: values = np.asarray(waveform, dtype=np.float32).reshape(-1) if target_samples <= 0: raise ValueError("target_samples must be positive") if values.size == 0: raise ValueError("Decoded audio waveform is empty") if values.size >= target_samples: return values[:target_samples] repeats = int(math.ceil(target_samples / values.size)) return np.tile(values, repeats)[:target_samples]
def audio_to_complex_spectrogram( audio_path: str | Path, sr: int = PAPER_SAMPLE_RATE, duration: float = PAPER_DURATION_SECONDS,) -> np.ndarray: import librosa
if sr != PAPER_SAMPLE_RATE or duration != PAPER_DURATION_SECONDS: raise ValueError( "The paper-faithful contract is fixed at 16 kHz and 6.0 seconds; " f"got sr={sr}, duration={duration}" ) waveform, _ = librosa.load(str(audio_path), sr=sr, mono=True) waveform = repeat_or_trim_waveform(waveform, target_samples=int(round(sr * duration))) return waveform_to_complex_spectrogram(waveform)
def waveform_to_complex_spectrogram(waveform: np.ndarray) -> np.ndarray: values = repeat_or_trim_waveform( np.asarray(waveform, dtype=np.float32), target_samples=int(PAPER_SAMPLE_RATE * PAPER_DURATION_SECONDS), ) frames = np.lib.stride_tricks.sliding_window_view(values, PAPER_FRAME_LENGTH)[ ::PAPER_HOP_LENGTH ] if frames.shape != (PAPER_TIME_FRAMES, PAPER_FRAME_LENGTH): raise ValueError(f"Unexpected framed waveform shape: {frames.shape}")
window = np.hanning(PAPER_FRAME_LENGTH + 1)[:-1].astype(np.float32) stft = np.fft.rfft( frames * window[None, :], n=PAPER_FFT_LENGTH, axis=1, ) if stft.shape != (PAPER_TIME_FRAMES, PAPER_FREQUENCY_BINS): raise ValueError(f"Unexpected STFT shape: {stft.shape}")
result = np.empty(PAPER_SPECTROGRAM_SHAPE, dtype=np.float32) result[:, :, 0] = stft.real.astype(np.float32, copy=False) result[:, :, 1] = stft.imag.astype(np.float32, copy=False) result = np.sign(result) * (np.abs(result) ** 0.3) if not np.isfinite(result).all(): raise ValueError("Spectrogram contains non-finite values") return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683from __future__ import annotations
import hashlibimport jsonimport mathimport structfrom pathlib import Pathfrom typing import Any, Mapping, Sequence
POLICY_SCHEMA = "speech2face.decoder-geometry-topology-policy/v1"SYNTHETIC_SCHEMA = "speech2face.decoder-geometry-synthetic-fixture/v1"EXPECTED_POLICY_SIZE = 8_766EXPECTED_POLICY_SHA256 = "c426bd750ed25299e331cdb38b54d411bebb358fa88c3f8459e7c9e5fb5fb07d"LANDMARK_COUNT = 98VECTOR_DIMENSIONS = 196POLYHARMONIC_REGULARIZATION = 1e-5POLYHARMONIC_CONDITION_LIMIT = 100_000_000.0BOUNDARY_POINTS = ( (-1.0, -1.0), (0.0, -1.0), (1.0, -1.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (-1.0, 1.0), (-1.0, 0.0),)SPLITS = frozenset({"train", "validation", "test"})_ROOT_KEYS = { "schema", "status", "reviewed", "execution_allowed", "evidence", "cole65_decision", "proposed_geometry", "target_reduction", "required_implementation_after_approval", "claims",}_RECORD_KEYS = {"sample_id", "identity", "split", "wflw98_landmarks_normalized"}
class GeometryPolicyError(ValueError): pass
def _duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]: result: dict[str, Any] = {} for key, value in pairs: if key in result: raise GeometryPolicyError(f"Duplicate JSON key: {key}") result[key] = value return result
def canonical_sha256(value: Any) -> str: payload = json.dumps( value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False ).encode("utf-8") return hashlib.sha256(payload).hexdigest()
def parse_geometry_policy_bytes(raw: bytes) -> Mapping[str, Any]: if ( len(raw) != EXPECTED_POLICY_SIZE or hashlib.sha256(raw).hexdigest() != EXPECTED_POLICY_SHA256 ): raise GeometryPolicyError("Geometry policy size or SHA-256 changed") try: payload = json.loads( raw.decode("utf-8", errors="strict"), object_pairs_hook=_duplicates, parse_constant=lambda value: (_ for _ in ()).throw( GeometryPolicyError(f"Non-finite JSON constant: {value}") ), ) except (UnicodeDecodeError, json.JSONDecodeError) as exc: raise GeometryPolicyError("Geometry policy is not strict UTF-8 JSON") from exc if type(payload) is not dict or set(payload) != _ROOT_KEYS: raise GeometryPolicyError("Geometry policy root fields changed") if ( payload["schema"] != POLICY_SCHEMA or payload["status"] != "review_required" or payload["reviewed"] is not False or payload["execution_allowed"] is not False ): raise GeometryPolicyError("Geometry review gate changed") if payload["cole65_decision"] != { "exact_numeric_topology_available": False, "spiga_wflw98_crosswalk_available": False, "mapping_config_must_remain_empty_and_unreviewed": True, "indices_54_76_82_may_not_be_used_as_a_guessed_five_point_mapping": True, "paper_faithful_cole65_claim_allowed": False, "status": "no_go", }: raise GeometryPolicyError("Cole-65 decision changed") geometry = payload["proposed_geometry"] if ( type(geometry) is not dict or geometry.get("decision") != "intentional_non_paper_faithful_native_wflw98_substitution" or geometry.get("topology") != "spiga_wflw98" or geometry.get("landmark_count") != LANDMARK_COUNT or geometry.get("geometry_vector_dimensions") != VECTOR_DIMENSIONS or geometry.get("source_subset_or_crosswalk") is not None or geometry.get("pixel_coordinate_convention") != "zero_based_pixel_centers_xy_origin_top_left" or geometry.get("decoder_coordinate_convention") != "align_corners_true_normalized_negative1_to_positive1" or geometry.get("pixel_to_decoder_formula") != "x_norm=2*x_pixel/223-1;y_norm=2*y_pixel/223-1" or geometry.get("off_canvas_policy") != "allow_without_clipping_within_registered_numeric_excursion" or geometry.get("maximum_absolute_normalized_coordinate") != 2.0 or geometry.get("equivalent_pixel_center_range_inclusive") != [-111.5, 334.5] or geometry.get("out_of_range_policy") != "pre_freeze_drop_with_landmark_numeric_excursion_no_replacement" or geometry.get("polyharmonic_k1_conditioning") != { "basis": "cole_phi1_euclidean_distance_r_not_thin_plate_spline", "regularization_diagonal": POLYHARMONIC_REGULARIZATION, "control_order": ( "wflw98_target_points_index_0_through_97_then_registered_boundary_points" ), "boundary_points_normalized_xy": [list(point) for point in BOUNDARY_POINTS], "system_definition": ( "A=[[cdist_l2(C,C)+1e-5*I,P],[P_transpose,zeros_3x3]];" "P_columns=[1,x,y]" ), "system_shape": [109, 109], "condition_dtype": "float64", "condition_number": ( "spectral_2_norm_sigma_max_over_sigma_min_" "numpy_linalg_svd_compute_uv_false" ), "maximum_condition_number_inclusive": POLYHARMONIC_CONDITION_LIMIT, "solve_dtype": "float64_system_rhs_and_coefficients", "dense_query_dtype": ( "input_float32_after_radial_and_affine_coefficients_" "cast_once_to_float32" ), "target_generation_control_displacement_range_inclusive": [-4.0, 4.0], "runtime_predicted_control_displacement_range_inclusive": [-4.0, 4.0], "normwise_relative_solve_residual": ( "inf_norm_Ax_minus_b_divided_by_inf_norm_A_times_inf_norm_x_" "plus_inf_norm_b_with_float64_tiny_denominator_floor" ), "maximum_normwise_relative_solve_residual_inclusive": 1e-10, "production_solve_backend": ( "differentiable_torch_float64_autograd_with_coefficient_cast_" "on_gradient_path" ), "pre_freeze_identity_evaluation": ( "each_minimum_three_provisional_identity_mean_in_every_split" ), "identity_system_failure_policy": ( "exclude_entire_identity_no_replacement_on_nonfinite_svd_or_" "condition_failure" ), "per_image_to_identity_rhs": ( "identity_mean_minus_persisted_image_landmarks_with_system_" "controls_identity_mean" ), "per_image_to_identity_solve_order": ( "identity_utf8_then_sample_id_utf8" ), "per_image_to_identity_failure_policy": ( "exclude_entire_identity_no_replacement_on_nonfinite_solve_or_" "residual_failure" ), "global_train_evaluation": ( "equal_identity_mean_over_remaining_eligible_train_identities" ), "global_mean_compute_policy": ( "compute_once_after_all_identity_system_and_per_image_solve_exclusions" ), "global_system_failure_policy": ( "fail_entire_stage_on_nonfinite_svd_or_condition_failure_no_" "recompute_no_backfill" ), "identity_to_global_rhs": ( "global_train_mean_minus_identity_mean_with_system_controls_" "global_train_mean_for_every_remaining_identity_all_splits" ), "identity_to_global_solve_order": "identity_utf8", "identity_to_global_failure_policy": ( "fail_entire_stage_on_nonfinite_solve_or_residual_failure_no_" "identity_exclusion_no_recompute_no_backfill" ), "accepted_manifest_freeze_policy": ( "freeze_only_after_all_registered_coordinate_condition_and_" "residual_gates_pass" ), "runtime_condition_evaluation": ( "every_batch_item_predicted_target_geometry_before_solve" ), "runtime_predicted_geometry_policy": ( "fail_run_receipted_no_clamp_no_skip_no_retry_on_nonfinite_" "condition_or_residual_violation" ), } or geometry.get("all_four_perceptual_arms_share_identical_geometry_targets") is not True or geometry.get("loss_formula_and_weights_unchanged") is not True or geometry.get("warp_control_topology_changes_from_65_to_98") is not True or geometry.get("runtime_mean_landmark_range_change") != "permit_registered_finite_range_negative2_to_positive2_without_clipping" or geometry.get("runtime_predicted_landmark_head") != "linear_196_output_no_tanh" or geometry.get("runtime_predicted_landmark_range") != "finite_negative2_to_positive2_required_before_loss_or_warp_else_fail_run" ): raise GeometryPolicyError("Native WFLW98 geometry contract changed") reduction = payload["target_reduction"] if ( type(reduction) is not dict or reduction.get("minimum_accepted_images_per_identity") != 3 or reduction.get("identity_split_disjoint_required") is not True or reduction.get("input_record_order") != "identity_utf8_bytes_then_sample_id_utf8_bytes" or reduction.get("aligned_affine_source") != ( "opencv_getAffineTransform_from_float32_x_sorted_pupils_and_" "constructed_third_points_returns_2x3_float64" ) or reduction.get("aligned_affine_application") != ( "promote_source_float32_xy_to_float64_then_math_fsum_m00_times_x_" "m01_times_y_m02_and_same_for_y_no_intermediate_rounding" ) or reduction.get("pixel_to_normalized_computation") != "binary64_formula_then_cast_once_to_ieee754_float32" or reduction.get("persisted_per_image_landmarks") != ( "numpy_lib_format_write_array_version_2_0_little_endian_float32_" "c_order_shape_98x2_allow_pickle_false" ) or reduction.get("within_identity_accumulation") != ( "math_fsum_binary64_over_persisted_float32_coordinates_then_" "divide_by_count_then_cast_once_to_float32" ) or reduction.get("global_mean_eligible_split") != "train" or reduction.get("global_mean_weighting") != "equal_weight_per_eligible_train_identity" or reduction.get("global_mean_accumulation") != ( "math_fsum_binary64_over_persisted_float32_identity_means_then_" "divide_by_identity_count_then_cast_once_to_float32" ) or reduction.get("persisted_identity_and_global_means") != ( "numpy_lib_format_write_array_version_2_0_little_endian_float32_" "c_order_shape_98x2_allow_pickle_false" ) or reduction.get("conditioning_input_precision") != "persisted_float32_geometry_promoted_exactly_to_float64" or reduction.get("validation_or_test_identity_may_affect_global_mean") is not False or reduction.get("validation_and_test_targets_use_frozen_train_global_mean") is not True or reduction.get("outcome_backfill") is not False or reduction.get("retained_identity_or_image_count_target") is not None ): raise GeometryPolicyError("Target-reduction contract changed") if any(value is not False for value in payload["claims"].values()): raise GeometryPolicyError("Blocked geometry claims changed") return payload
def load_geometry_policy(path: str | Path) -> Mapping[str, Any]: original = Path(path).absolute() try: info = original.lstat() except OSError as exc: raise GeometryPolicyError("Geometry policy is missing") from exc if ( original.is_symlink() or bool(getattr(info, "st_file_attributes", 0) & 0x400) or not original.is_file() or info.st_nlink != 1 ): raise GeometryPolicyError("Geometry policy must be one regular non-link file") return parse_geometry_policy_bytes(original.read_bytes())
def verify_bound_evidence(policy: Mapping[str, Any], repository_root: str | Path) -> None: root = Path(repository_root).resolve(strict=True) evidence = policy["evidence"] evidence_payloads: dict[str, bytes] = {} for label, binding in evidence.items(): lexical = root.joinpath(*binding["path"].split("/")) info = lexical.lstat() if ( lexical.is_symlink() or bool(getattr(info, "st_file_attributes", 0) & 0x400) or not lexical.is_file() or info.st_nlink != 1 ): raise GeometryPolicyError(f"Unsafe evidence file: {label}") candidate = lexical.resolve(strict=True) try: candidate.relative_to(root) except ValueError as exc: raise GeometryPolicyError(f"Evidence path escapes repository: {label}") from exc expected_size = binding["size_bytes"] if type(expected_size) is not int or info.st_size != expected_size: raise GeometryPolicyError(f"Evidence size changed: {label}") digest = hashlib.sha256() raw_parts: list[bytes] = [] total = 0 with candidate.open("rb") as handle: while total < expected_size: chunk = handle.read(min(65_536, expected_size - total)) if not chunk: break total += len(chunk) digest.update(chunk) raw_parts.append(chunk) after = lexical.lstat() if ( total != expected_size or after.st_size != expected_size or after.st_ino != info.st_ino or after.st_mtime_ns != info.st_mtime_ns or digest.hexdigest() != binding["sha256"] ): raise GeometryPolicyError(f"Evidence binding changed: {label}") evidence_payloads[label] = b"".join(raw_parts) cole = json.loads(evidence_payloads["cole65_mapping_config"].decode("utf-8")) if cole.get("reviewed") is not False or any( cole.get(field) for field in ("indices", "left_eye_source_indices", "right_eye_source_indices") ): raise GeometryPolicyError("Cole-65 mapping is no longer empty and blocked")
def _point(value: Any, label: str) -> tuple[float, float]: if type(value) not in (list, tuple) or len(value) != 2: raise GeometryPolicyError(f"{label} is not a point") if any(type(item) not in (int, float) or not math.isfinite(item) for item in value): raise GeometryPolicyError(f"{label} is not finite") result = float(value[0]), float(value[1]) if any(item < -2.0 or item > 2.0 for item in result): raise GeometryPolicyError(f"{label} is outside normalized decoder coordinates") return result
def _float32(value: float) -> float: try: rounded = struct.unpack("<f", struct.pack("<f", float(value)))[0] except (OverflowError, struct.error) as exc: raise GeometryPolicyError("Coordinate cannot be represented as float32") from exc if not math.isfinite(rounded): raise GeometryPolicyError("Coordinate is non-finite after float32 cast") return rounded
def _displacement(value: Any, label: str) -> tuple[float, float]: if type(value) not in (list, tuple) or len(value) != 2: raise GeometryPolicyError(f"{label} is not a displacement vector") if any(type(item) not in (int, float) or not math.isfinite(item) for item in value): raise GeometryPolicyError(f"{label} is not finite") result = float(value[0]), float(value[1]) if any(item < -4.0 or item > 4.0 for item in result): raise GeometryPolicyError(f"{label} exceeds the registered displacement range") return result
def _polyharmonic_k1_system( landmarks: Sequence[Sequence[float]],) -> tuple[Any, Any]: try: import numpy as np except ImportError as exc: raise GeometryPolicyError("NumPy is required for conditioning validation") from exc if type(landmarks) not in (list, tuple) or len(landmarks) != LANDMARK_COUNT: raise GeometryPolicyError("Conditioning requires exactly 98 landmarks") points = [ _point(point, f"conditioning landmark {index}") for index, point in enumerate(landmarks) ] controls = np.asarray([*points, *BOUNDARY_POINTS], dtype=np.float64) delta = controls[:, None, :] - controls[None, :, :] radial = np.sqrt(np.sum(delta * delta, axis=2, dtype=np.float64)) radial.flat[:: radial.shape[0] + 1] += POLYHARMONIC_REGULARIZATION affine = np.column_stack( [np.ones((controls.shape[0],), dtype=np.float64), controls] ) system = np.block( [ [radial, affine], [affine.T, np.zeros((3, 3), dtype=np.float64)], ] ) if system.shape != (109, 109) or not np.isfinite(system).all(): raise GeometryPolicyError("Registered polyharmonic system is malformed") return system, np
def polyharmonic_k1_condition_number( landmarks: Sequence[Sequence[float]],) -> float: system, np = _polyharmonic_k1_system(landmarks) singular_values = np.linalg.svd(system, compute_uv=False) smallest = float(singular_values[-1]) result = ( math.inf if smallest <= 0.0 else float(singular_values[0]) / smallest ) if not math.isfinite(result): raise GeometryPolicyError("Polyharmonic system condition number is non-finite") return result
def polyharmonic_k1_solve_relative_residual( landmarks: Sequence[Sequence[float]], displacements: Sequence[Sequence[float]],) -> float: system, np = _polyharmonic_k1_system(landmarks) if type(displacements) not in (list, tuple) or len(displacements) != LANDMARK_COUNT: raise GeometryPolicyError("Residual check requires exactly 98 displacements") values = np.asarray( [ _displacement(value, f"conditioning displacement {index}") for index, value in enumerate(displacements) ], dtype=np.float64, ) rhs = np.concatenate( [values, np.zeros((len(BOUNDARY_POINTS) + 3, 2), dtype=np.float64)], axis=0, ) coefficients = np.linalg.solve(system, rhs) residual = system @ coefficients - rhs denominator = ( np.linalg.norm(system, ord=np.inf) * np.linalg.norm(coefficients, ord=np.inf) + np.linalg.norm(rhs, ord=np.inf) ) result = float( np.linalg.norm(residual, ord=np.inf) / max(float(denominator), np.finfo(np.float64).tiny) ) if not math.isfinite(result): raise GeometryPolicyError("Polyharmonic solve residual is non-finite") return result
def derive_synthetic_geometry_fixture( policy: Mapping[str, Any], records: Sequence[Mapping[str, Any]], *, fixture_id: str,) -> dict[str, Any]: if policy["reviewed"] is not False or policy["execution_allowed"] is not False: raise GeometryPolicyError("Synthetic review requires the blocked policy") if type(fixture_id) is not str or not fixture_id.startswith("synthetic:"): raise GeometryPolicyError("fixture_id must use the synthetic: namespace") if type(records) not in (list, tuple) or not records: raise GeometryPolicyError("Synthetic records are required") parsed: list[tuple[bytes, bytes, str, str, tuple[tuple[float, float], ...]]] = [] seen_samples: set[str] = set() identity_splits: dict[str, str] = {} for ordinal, record in enumerate(records): if type(record) is not dict or set(record) != _RECORD_KEYS: raise GeometryPolicyError(f"Synthetic record {ordinal} fields changed") sample_id = record["sample_id"] identity = record["identity"] split = record["split"] if ( type(sample_id) is not str or not sample_id.startswith("synthetic:") or type(identity) is not str or not identity.startswith("synthetic:") or split not in SPLITS ): raise GeometryPolicyError(f"Synthetic record {ordinal} identity changed") if sample_id in seen_samples: raise GeometryPolicyError(f"Duplicate sample_id: {sample_id}") seen_samples.add(sample_id) prior = identity_splits.setdefault(identity, split) if prior != split: raise GeometryPolicyError(f"Identity {identity!r} leaks across splits") landmarks = record["wflw98_landmarks_normalized"] if type(landmarks) not in (list, tuple) or len(landmarks) != LANDMARK_COUNT: raise GeometryPolicyError("Synthetic WFLW98 landmark count changed") points = tuple( tuple( _float32(coordinate) for coordinate in _point(point, f"record {ordinal} landmark {index}") ) for index, point in enumerate(landmarks) ) parsed.append((identity.encode(), sample_id.encode(), identity, split, points)) parsed.sort(key=lambda row: (row[0], row[1])) grouped: dict[ tuple[str, str], list[tuple[str, tuple[tuple[float, float], ...]]], ] = {} for _identity_bytes, sample_bytes, identity, split, points in parsed: grouped.setdefault((identity, split), []).append( (sample_bytes.decode("utf-8"), points) ) eligible = {key: values for key, values in grouped.items() if len(values) >= 3} means: list[dict[str, Any]] = [] conditioning_failures: list[dict[str, Any]] = [] for (identity, split), observations in sorted( eligible.items(), key=lambda item: (item[0][0].encode(), item[0][1].encode()) ): mean = [ [ _float32( math.fsum(points[index][axis] for _sample_id, points in observations) / len(observations) ) for axis in range(2) ] for index in range(LANDMARK_COUNT) ] try: condition_number = polyharmonic_k1_condition_number(mean) except Exception as exc: conditioning_failures.append( { "identity": identity, "split": split, "failure_stage": "identity_system", "failure_kind": type(exc).__name__, "reason": "landmark_conditioning_failure", } ) continue if condition_number > POLYHARMONIC_CONDITION_LIMIT: conditioning_failures.append( { "identity": identity, "split": split, "failure_stage": "identity_system", "condition_number": condition_number, "reason": "landmark_conditioning_failure", } ) continue maximum_per_image_residual = 0.0 residual_failure: dict[str, Any] | None = None for sample_id, points in observations: displacement = [ [mean[index][axis] - points[index][axis] for axis in range(2)] for index in range(LANDMARK_COUNT) ] try: residual = polyharmonic_k1_solve_relative_residual( mean, displacement ) except Exception as exc: residual_failure = { "identity": identity, "split": split, "sample_id": sample_id, "failure_stage": "per_image_to_identity_solve", "failure_kind": type(exc).__name__, "reason": "landmark_conditioning_failure", } break maximum_per_image_residual = max(maximum_per_image_residual, residual) if residual > 1e-10: residual_failure = { "identity": identity, "split": split, "sample_id": sample_id, "failure_stage": "per_image_to_identity_solve", "relative_residual": residual, "reason": "landmark_conditioning_failure", } break if residual_failure is not None: conditioning_failures.append(residual_failure) continue means.append( { "identity": identity, "split": split, "accepted_images": len(observations), "mean_landmarks": mean, "polyharmonic_k1_condition_number_float64": condition_number, "maximum_per_image_to_identity_relative_residual_float64": ( maximum_per_image_residual ), } ) train_means = [row["mean_landmarks"] for row in means if row["split"] == "train"] if not train_means: raise GeometryPolicyError("No eligible synthetic train identity") global_mean = [ [ _float32( math.fsum(mean[index][axis] for mean in train_means) / len(train_means) ) for axis in range(2) ] for index in range(LANDMARK_COUNT) ] try: global_condition = polyharmonic_k1_condition_number(global_mean) except Exception as exc: raise GeometryPolicyError( "Global train polyharmonic system validation failed" ) from exc if global_condition > POLYHARMONIC_CONDITION_LIMIT: raise GeometryPolicyError( "Global train geometry exceeds the polyharmonic conditioning limit" ) maximum_identity_to_global_residual = 0.0 for row in means: displacement = [ [ global_mean[index][axis] - row["mean_landmarks"][index][axis] for axis in range(2) ] for index in range(LANDMARK_COUNT) ] try: residual = polyharmonic_k1_solve_relative_residual( global_mean, displacement ) except Exception as exc: raise GeometryPolicyError( "Identity-to-global polyharmonic solve validation failed for " f"{row['identity']}" ) from exc if residual > 1e-10: raise GeometryPolicyError( "Identity-to-global polyharmonic residual exceeds the limit for " f"{row['identity']}" ) row["identity_to_global_relative_residual_float64"] = residual maximum_identity_to_global_residual = max( maximum_identity_to_global_residual, residual ) result = { "schema": SYNTHETIC_SCHEMA, "fixture_id": fixture_id, "sealable": False, "topology": "spiga_wflw98", "landmark_count": LANDMARK_COUNT, "geometry_vector_dimensions": VECTOR_DIMENSIONS, "eligible_identity_means": means, "conditioning_failures": conditioning_failures, "eligible_train_identity_count": len(train_means), "global_train_equal_identity_mean": global_mean, "global_train_polyharmonic_k1_condition_number_float64": global_condition, "maximum_identity_to_global_relative_residual_float64": ( maximum_identity_to_global_residual ), "claims": { "cole65_mapping_used": False, "validation_or_test_used_in_global_mean": False, "real_target_generated": False, "training_authorized": False, }, } result["synthetic_identity_sha256"] = canonical_sha256(result) return result
__all__ = [ "BOUNDARY_POINTS", "EXPECTED_POLICY_SHA256", "EXPECTED_POLICY_SIZE", "GeometryPolicyError", "LANDMARK_COUNT", "POLICY_SCHEMA", "POLYHARMONIC_CONDITION_LIMIT", "POLYHARMONIC_REGULARIZATION", "SYNTHETIC_SCHEMA", "VECTOR_DIMENSIONS", "derive_synthetic_geometry_fixture", "load_geometry_policy", "parse_geometry_policy_bytes", "polyharmonic_k1_condition_number", "polyharmonic_k1_solve_relative_residual", "verify_bound_evidence",]1234567891011121314151617181920212223242526272829303132333435363738from __future__ import annotations
from torch import nn
DECODER_FEATURE_DIM = 4096
def _make_decoder_heads( *, landmark_count: int, bounded_geometry: bool,) -> tuple[nn.Linear, nn.Sequential, nn.Linear, nn.Sequential]: fc3 = nn.Linear(DECODER_FEATURE_DIM, 1000) geometry_head = nn.Sequential( nn.Linear(1000, 800), nn.ReLU(), nn.Linear(800, 600), nn.ReLU(), nn.Linear(600, 400), nn.ReLU(), nn.Linear(400, 200), nn.ReLU(), nn.Linear(200, landmark_count * 2), *([nn.Tanh()] if bounded_geometry else []), ) texture_fc = nn.Linear(1000, 14 * 14 * 256) texture_decoder = nn.Sequential( nn.ConvTranspose2d(256, 128, 5, stride=2, padding=2, output_padding=1), nn.ReLU(), nn.ConvTranspose2d(128, 64, 5, stride=2, padding=2, output_padding=1), nn.ReLU(), nn.ConvTranspose2d(64, 32, 5, stride=2, padding=2, output_padding=1), nn.ReLU(), nn.ConvTranspose2d(32, 32, 5, stride=2, padding=2, output_padding=1), nn.ReLU(), nn.Conv2d(32, 3, 1), ) return fc3, geometry_head, texture_fc, texture_decoder123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916from __future__ import annotations
import hashlibimport ioimport mathimport osimport structfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, Iterable, Sequence
import numpy as np
from .decoder_geometry_policy import ( BOUNDARY_POINTS, LANDMARK_COUNT, POLYHARMONIC_CONDITION_LIMIT, POLYHARMONIC_REGULARIZATION, VECTOR_DIMENSIONS,)
ALIGNED_IMAGE_SIZE = 224NORMALIZED_COORDINATE_LIMIT = 2.0POLYHARMONIC_RESIDUAL_LIMIT = 1e-10MINIMUM_ACCEPTED_IMAGES = 3NPY_VERSION = (2, 0)MAX_LANDMARK_NPY_BYTES = 4_096SPLITS = frozenset({"train", "validation", "test"})_LITTLE_F4 = np.dtype("<f4")
class NativeWFLW98Error(ValueError): pass
class LandmarkNumericExcursion(NativeWFLW98Error): pass
_NUMERICAL_FAILURES = ( NativeWFLW98Error, np.linalg.LinAlgError, FloatingPointError, OverflowError,)
@dataclass(frozen=True)class GeometryRecord: sample_id: str identity: str split: str landmarks: np.ndarray
@dataclass(frozen=True)class IdentityGeometry: identity: str split: str accepted_sample_ids: tuple[str, ...] accepted_landmark_sha256s: tuple[str, ...] mean_landmarks: np.ndarray condition_number: float maximum_image_to_identity_residual: float identity_to_global_residual: float
@dataclass(frozen=True)class PreFreezeGeometry: identities: tuple[IdentityGeometry, ...] global_train_mean: np.ndarray global_condition_number: float sample_failures: tuple[dict[str, Any], ...] identity_failures: tuple[dict[str, Any], ...]
def _utf8(value: str, label: str) -> bytes: if type(value) is not str or not value: raise NativeWFLW98Error(f"{label} must be a non-empty string") try: return value.encode("utf-8", errors="strict") except UnicodeEncodeError as exc: raise NativeWFLW98Error(f"{label} is not strict UTF-8") from exc
def _round_binary32(value: float) -> float: try: result = struct.unpack("<f", struct.pack("<f", float(value)))[0] except (OverflowError, struct.error) as exc: raise LandmarkNumericExcursion("coordinate is not representable as float32") from exc if not math.isfinite(result): raise LandmarkNumericExcursion("coordinate became non-finite after float32 cast") return result
def _readonly_f4(value: np.ndarray) -> np.ndarray: result = np.ascontiguousarray(value, dtype=_LITTLE_F4).copy(order="C") result.setflags(write=False) return result
def _require_persisted_f4_landmarks( value: np.ndarray, *, label: str, coordinate_gate: bool = True,) -> np.ndarray: if not isinstance(value, np.ndarray): raise NativeWFLW98Error(f"{label} must be a NumPy array") if value.shape != (LANDMARK_COUNT, 2): raise NativeWFLW98Error( f"{label} must have shape ({LANDMARK_COUNT}, 2); got {value.shape}" ) if value.dtype != _LITTLE_F4: raise NativeWFLW98Error(f"{label} must have dtype little-endian float32") if not value.flags.c_contiguous: raise NativeWFLW98Error(f"{label} must be C contiguous") if coordinate_gate: if not np.isfinite(value).all(): raise LandmarkNumericExcursion(f"{label} contains non-finite coordinates") if bool(np.any(np.abs(value) > NORMALIZED_COORDINATE_LIMIT)): raise LandmarkNumericExcursion( f"{label} exceeds the inclusive normalized coordinate range [-2, 2]" ) return value
def apply_alignment_affine_to_wflw98( source_landmarks_pixel: np.ndarray, transform_2x3: np.ndarray,) -> np.ndarray: if not isinstance(source_landmarks_pixel, np.ndarray): raise NativeWFLW98Error("source landmarks must be a NumPy array") if source_landmarks_pixel.shape != (LANDMARK_COUNT, 2): raise NativeWFLW98Error( f"source landmarks must have shape ({LANDMARK_COUNT}, 2)" ) if source_landmarks_pixel.dtype != _LITTLE_F4: raise NativeWFLW98Error("source landmarks must be little-endian float32") if not source_landmarks_pixel.flags.c_contiguous: raise NativeWFLW98Error("source landmarks must be C contiguous") if not np.isfinite(source_landmarks_pixel).all(): raise LandmarkNumericExcursion("source landmarks contain non-finite coordinates") if not isinstance(transform_2x3, np.ndarray): raise NativeWFLW98Error("alignment transform must be a NumPy array") if transform_2x3.shape != (2, 3) or transform_2x3.dtype != np.dtype("<f8"): raise NativeWFLW98Error("alignment transform must be a float64 2x3 array") if not transform_2x3.flags.c_contiguous or not np.isfinite(transform_2x3).all(): raise NativeWFLW98Error("alignment transform must be finite and C contiguous")
output = np.empty((LANDMARK_COUNT, 2), dtype=_LITTLE_F4, order="C") matrix = transform_2x3 for index in range(LANDMARK_COUNT): x = float(source_landmarks_pixel[index, 0]) y = float(source_landmarks_pixel[index, 1]) for axis in range(2): pixel = math.fsum( ( float(matrix[axis, 0]) * x, float(matrix[axis, 1]) * y, float(matrix[axis, 2]), ) ) normalized = 2.0 * pixel / float(ALIGNED_IMAGE_SIZE - 1) - 1.0 if ( not math.isfinite(normalized) or normalized < -NORMALIZED_COORDINATE_LIMIT or normalized > NORMALIZED_COORDINATE_LIMIT ): raise LandmarkNumericExcursion( "aligned WFLW98 coordinate exceeds the registered numeric excursion" ) output[index, axis] = _round_binary32(normalized) return output
def registered_alignment_affine_from_wflw98( source_landmarks_pixel: np.ndarray,) -> np.ndarray: if not isinstance(source_landmarks_pixel, np.ndarray): raise NativeWFLW98Error("source landmarks must be a NumPy array") if source_landmarks_pixel.shape != (LANDMARK_COUNT, 2): raise NativeWFLW98Error("source landmarks must have shape (98, 2)") if source_landmarks_pixel.dtype != _LITTLE_F4: raise NativeWFLW98Error("source landmarks must be little-endian float32") if not source_landmarks_pixel.flags.c_contiguous: raise NativeWFLW98Error("source landmarks must be C contiguous") if not np.isfinite(source_landmarks_pixel).all(): raise LandmarkNumericExcursion("source landmarks contain non-finite coordinates") pupils = source_landmarks_pixel[[96, 97]].copy(order="C") if pupils[0, 0] == pupils[1, 0]: raise LandmarkNumericExcursion("WFLW pupil x coordinates tie") if pupils[0, 0] > pupils[1, 0]: pupils = pupils[::-1].copy(order="C") source_delta = pupils[1] - pupils[0] if float(np.linalg.norm(source_delta)) <= 1e-6: raise LandmarkNumericExcursion("WFLW pupil centers coincide") target_left = np.asarray([84.5, 100.0], dtype=_LITTLE_F4) target_right = np.asarray([139.5, 100.0], dtype=_LITTLE_F4) source_mid = pupils.mean(axis=0) target_mid = (target_left + target_right) * np.float32(0.5) target_delta = target_right - target_left source_third = source_mid + np.asarray( [-source_delta[1], source_delta[0]], dtype=_LITTLE_F4 ) target_third = target_mid + np.asarray( [-target_delta[1], target_delta[0]], dtype=_LITTLE_F4 ) try: import cv2 except ImportError as exc: raise NativeWFLW98Error("OpenCV is required to construct the registered affine") from exc result = cv2.getAffineTransform( np.stack((pupils[0], pupils[1], source_third)), np.stack((target_left, target_right, target_third)), ) if ( not isinstance(result, np.ndarray) or result.shape != (2, 3) or result.dtype != np.dtype("<f8") or not result.flags.c_contiguous or not np.isfinite(result).all() ): raise NativeWFLW98Error("OpenCV affine output contract changed") return result
def exact_landmark_npy_v2_bytes(value: np.ndarray) -> bytes: array = _require_persisted_f4_landmarks(value, label="landmark array") buffer = io.BytesIO() np.lib.format.write_array( buffer, array, version=NPY_VERSION, allow_pickle=False, ) raw = buffer.getvalue() if len(raw) > MAX_LANDMARK_NPY_BYTES: raise NativeWFLW98Error("landmark NPY exceeds the registered byte cap") replay = read_exact_landmark_npy_v2_bytes(raw) if replay.tobytes(order="C") != array.tobytes(order="C"): raise NativeWFLW98Error("landmark NPY verification changed array bytes") return raw
def read_exact_landmark_npy_v2_bytes(raw: bytes) -> np.ndarray: if type(raw) is not bytes or not raw or len(raw) > MAX_LANDMARK_NPY_BYTES: raise NativeWFLW98Error("landmark NPY byte length is invalid") header_handle = io.BytesIO(raw) try: version = np.lib.format.read_magic(header_handle) except (ValueError, EOFError) as exc: raise NativeWFLW98Error("landmark NPY magic/version is invalid") from exc if version != NPY_VERSION: raise NativeWFLW98Error("landmark NPY version must be 2.0") try: shape, fortran_order, dtype = np.lib.format.read_array_header_2_0(header_handle) except (ValueError, EOFError) as exc: raise NativeWFLW98Error("landmark NPY header is invalid") from exc if shape != (LANDMARK_COUNT, 2): raise NativeWFLW98Error("landmark NPY shape changed") if fortran_order is not False or dtype != _LITTLE_F4: raise NativeWFLW98Error("landmark NPY dtype/order changed") handle = io.BytesIO(raw) try: array = np.lib.format.read_array(handle, allow_pickle=False) except (ValueError, EOFError) as exc: raise NativeWFLW98Error("landmark NPY payload is invalid") from exc if handle.tell() != len(raw): raise NativeWFLW98Error("landmark NPY has trailing bytes") _require_persisted_f4_landmarks(array, label="landmark NPY payload") return _readonly_f4(array)
def write_exact_landmark_npy_v2(path: str | Path, value: np.ndarray) -> int: destination = Path(path).absolute() parent = destination.parent try: parent_info = parent.lstat() except OSError as exc: raise NativeWFLW98Error("landmark output parent is missing") from exc try: resolved_parent = parent.resolve(strict=True) except OSError as exc: raise NativeWFLW98Error("landmark output parent cannot be resolved") from exc if ( parent.is_symlink() or bool(getattr(parent_info, "st_file_attributes", 0) & 0x400) or not parent.is_dir() or os.path.normcase(str(resolved_parent)) != os.path.normcase(str(parent)) ): raise NativeWFLW98Error("landmark output parent is unsafe") try: destination.lstat() except FileNotFoundError: pass else: raise NativeWFLW98Error("landmark output already exists")
raw = exact_landmark_npy_v2_bytes(value) temporary = destination.with_name(destination.name + ".partial") temporary_created = False destination_published = False try: with temporary.open("xb") as handle: temporary_created = True handle.write(raw) handle.flush() os.fsync(handle.fileno()) os.link(temporary, destination) destination_published = True temporary.unlink() temporary_created = False destination_info = destination.lstat() if ( destination.is_symlink() or bool(getattr(destination_info, "st_file_attributes", 0) & 0x400) or not destination.is_file() or destination_info.st_nlink != 1 or destination_info.st_size != len(raw) ): raise NativeWFLW98Error("published landmark NPY path is unsafe") published = destination.read_bytes() if published != raw: raise NativeWFLW98Error("published landmark NPY changed") read_exact_landmark_npy_v2_bytes(published) except Exception: if destination_published: try: destination.unlink() except FileNotFoundError: pass if temporary_created: try: temporary.unlink() except FileNotFoundError: pass raise return len(raw)
def _numpy_system(landmarks: np.ndarray) -> np.ndarray: points = _require_persisted_f4_landmarks( landmarks, label="polyharmonic controls", ).astype(np.float64, copy=False) controls = np.concatenate( [points, np.asarray(BOUNDARY_POINTS, dtype=np.float64)], axis=0, ) delta = controls[:, None, :] - controls[None, :, :] radial = np.sqrt(np.sum(delta * delta, axis=2, dtype=np.float64)) radial.flat[:: radial.shape[0] + 1] += POLYHARMONIC_REGULARIZATION affine = np.column_stack( (np.ones((controls.shape[0],), dtype=np.float64), controls) ) system = np.block( [ [radial, affine], [affine.T, np.zeros((3, 3), dtype=np.float64)], ] ) if system.shape != (109, 109) or not np.isfinite(system).all(): raise NativeWFLW98Error("polyharmonic system is malformed") return system
def _numpy_condition_number(landmarks: np.ndarray) -> float: singular_values = np.linalg.svd(_numpy_system(landmarks), compute_uv=False) smallest = float(singular_values[-1]) result = math.inf if smallest <= 0.0 else float(singular_values[0]) / smallest if not math.isfinite(result): raise NativeWFLW98Error("polyharmonic condition number is non-finite") return result
def _require_displacements(value: np.ndarray) -> np.ndarray: if not isinstance(value, np.ndarray) or value.shape != (LANDMARK_COUNT, 2): raise NativeWFLW98Error("displacements must have shape (98, 2)") result = np.asarray(value, dtype=np.float64, order="C") if not np.isfinite(result).all() or bool(np.any(np.abs(result) > 4.0)): raise NativeWFLW98Error("displacement exceeds the inclusive range [-4, 4]") return result
def _numpy_solve_relative_residual( controls: np.ndarray, displacements: np.ndarray,) -> float: system = _numpy_system(controls) values = _require_displacements(displacements) rhs = np.concatenate( [ values, np.zeros((len(BOUNDARY_POINTS) + 3, 2), dtype=np.float64), ], axis=0, ) coefficients = np.linalg.solve(system, rhs) if not np.isfinite(coefficients).all(): raise NativeWFLW98Error("polyharmonic coefficients are non-finite") residual = system @ coefficients - rhs denominator = ( float(np.linalg.norm(system, ord=np.inf)) * float(np.linalg.norm(coefficients, ord=np.inf)) + float(np.linalg.norm(rhs, ord=np.inf)) ) result = float( np.linalg.norm(residual, ord=np.inf) / max(denominator, float(np.finfo(np.float64).tiny)) ) if not math.isfinite(result): raise NativeWFLW98Error("polyharmonic residual is non-finite") return result
def _fsum_mean(values: Sequence[np.ndarray]) -> np.ndarray: if not values: raise NativeWFLW98Error("cannot reduce an empty landmark sequence") for index, value in enumerate(values): _require_persisted_f4_landmarks(value, label=f"mean input {index}") result = np.empty((LANDMARK_COUNT, 2), dtype=_LITTLE_F4, order="C") count = len(values) for landmark in range(LANDMARK_COUNT): for axis in range(2): mean = math.fsum(float(value[landmark, axis]) for value in values) / count result[landmark, axis] = _round_binary32(mean) return result
def _identity_sort_key(value: tuple[str, str]) -> tuple[bytes, bytes]: identity, split = value return _utf8(identity, "identity"), _utf8(split, "split")
def reduce_prefreeze_geometry(records: Iterable[GeometryRecord]) -> PreFreezeGeometry: parsed: list[tuple[bytes, bytes, GeometryRecord]] = [] seen_samples: set[str] = set() identity_splits: dict[str, str] = {} for ordinal, record in enumerate(records): if type(record) is not GeometryRecord: raise NativeWFLW98Error(f"record {ordinal} must be GeometryRecord") identity_bytes = _utf8(record.identity, f"record {ordinal} identity") sample_bytes = _utf8(record.sample_id, f"record {ordinal} sample_id") if record.split not in SPLITS: raise NativeWFLW98Error(f"record {ordinal} split changed") if record.sample_id in seen_samples: raise NativeWFLW98Error(f"duplicate sample_id: {record.sample_id}") seen_samples.add(record.sample_id) prior = identity_splits.setdefault(record.identity, record.split) if prior != record.split: raise NativeWFLW98Error( f"identity {record.identity!r} leaks across {prior!r}/{record.split!r}" ) _require_persisted_f4_landmarks( record.landmarks, label=f"record {ordinal} landmarks", coordinate_gate=False, ) snapshot = GeometryRecord( sample_id=record.sample_id, identity=record.identity, split=record.split, landmarks=_readonly_f4(record.landmarks), ) parsed.append((identity_bytes, sample_bytes, snapshot)) if not parsed: raise NativeWFLW98Error("geometry records are empty") parsed.sort(key=lambda item: (item[0], item[1]))
sample_failures: list[dict[str, Any]] = [] grouped: dict[tuple[str, str], list[GeometryRecord]] = {} for _identity_bytes, _sample_bytes, record in parsed: try: _require_persisted_f4_landmarks( record.landmarks, label=f"sample {record.sample_id} landmarks", ) except LandmarkNumericExcursion: sample_failures.append( { "identity": record.identity, "split": record.split, "sample_id": record.sample_id, "failure_stage": "coordinate_gate", "reason": "landmark_numeric_excursion", } ) continue grouped.setdefault((record.identity, record.split), []).append(record)
identity_failures: list[dict[str, Any]] = [] survivors: list[dict[str, Any]] = [] all_identity_keys = sorted(identity_splits.items(), key=_identity_sort_key) for identity, split in all_identity_keys: observations = grouped.get((identity, split), []) if len(observations) < MINIMUM_ACCEPTED_IMAGES: identity_failures.append( { "identity": identity, "split": split, "failure_stage": "minimum_images", "accepted_images": len(observations), "reason": "fewer_than_three_geometry_eligible_images", } ) continue mean = _fsum_mean([record.landmarks for record in observations]) try: condition = _numpy_condition_number(mean) except _NUMERICAL_FAILURES as exc: identity_failures.append( { "identity": identity, "split": split, "failure_stage": "identity_system", "failure_kind": type(exc).__name__, "reason": "landmark_conditioning_failure", } ) continue if condition > POLYHARMONIC_CONDITION_LIMIT: identity_failures.append( { "identity": identity, "split": split, "failure_stage": "identity_system", "condition_number": condition, "reason": "landmark_conditioning_failure", } ) continue maximum_residual = 0.0 solve_failure: dict[str, Any] | None = None for observation in observations: displacement = mean.astype(np.float64) - observation.landmarks.astype(np.float64) try: residual = _numpy_solve_relative_residual(mean, displacement) except _NUMERICAL_FAILURES as exc: solve_failure = { "identity": identity, "split": split, "sample_id": observation.sample_id, "failure_stage": "per_image_to_identity_solve", "failure_kind": type(exc).__name__, "reason": "landmark_conditioning_failure", } break maximum_residual = max(maximum_residual, residual) if residual > POLYHARMONIC_RESIDUAL_LIMIT: solve_failure = { "identity": identity, "split": split, "sample_id": observation.sample_id, "failure_stage": "per_image_to_identity_solve", "relative_residual": residual, "reason": "landmark_conditioning_failure", } break if solve_failure is not None: identity_failures.append(solve_failure) continue survivors.append( { "identity": identity, "split": split, "sample_ids": tuple(record.sample_id for record in observations), "landmark_sha256s": tuple( hashlib.sha256(record.landmarks.tobytes(order="C")).hexdigest() for record in observations ), "mean": mean, "condition": condition, "image_residual": maximum_residual, } )
train_means = [row["mean"] for row in survivors if row["split"] == "train"] if not train_means: raise NativeWFLW98Error("no train identity survives the pre-global gates") global_mean = _fsum_mean(train_means) try: global_condition = _numpy_condition_number(global_mean) except _NUMERICAL_FAILURES as exc: raise NativeWFLW98Error("global train system validation failed") from exc if global_condition > POLYHARMONIC_CONDITION_LIMIT: raise NativeWFLW98Error("global train system exceeds the condition limit")
final_identities: list[IdentityGeometry] = [] for row in survivors: displacement = global_mean.astype(np.float64) - row["mean"].astype(np.float64) try: residual = _numpy_solve_relative_residual(global_mean, displacement) except _NUMERICAL_FAILURES as exc: raise NativeWFLW98Error( f"identity-to-global solve failed for {row['identity']}" ) from exc if residual > POLYHARMONIC_RESIDUAL_LIMIT: raise NativeWFLW98Error( f"identity-to-global residual exceeds the limit for {row['identity']}" ) final_identities.append( IdentityGeometry( identity=row["identity"], split=row["split"], accepted_sample_ids=row["sample_ids"], accepted_landmark_sha256s=row["landmark_sha256s"], mean_landmarks=_readonly_f4(row["mean"]), condition_number=float(row["condition"]), maximum_image_to_identity_residual=float(row["image_residual"]), identity_to_global_residual=float(residual), ) )
return PreFreezeGeometry( identities=tuple(final_identities), global_train_mean=_readonly_f4(global_mean), global_condition_number=float(global_condition), sample_failures=tuple(sample_failures), identity_failures=tuple(identity_failures), )
def _require_torch() -> Any: try: import torch except ImportError as exc: raise NativeWFLW98Error("PyTorch is required for differentiable warping") from exc return torch
def _validate_torch_landmarks( value: Any, *, label: str, batch: int | None = None,) -> Any: torch = _require_torch() if not torch.is_tensor(value) or value.dtype != torch.float32: raise NativeWFLW98Error(f"{label} must be a float32 Torch tensor") if value.ndim != 3 or value.shape[1:] != (LANDMARK_COUNT, 2): raise NativeWFLW98Error(f"{label} must have shape (B,98,2)") if batch is not None and value.shape[0] != batch: raise NativeWFLW98Error(f"{label} batch dimension changed") detached = value.detach() if not bool(torch.isfinite(detached).all().item()): raise NativeWFLW98Error(f"{label} contains non-finite coordinates") if bool((torch.abs(detached) > NORMALIZED_COORDINATE_LIMIT).any().item()): raise NativeWFLW98Error(f"{label} exceeds the inclusive range [-2,2]") return value
def solve_wflw98_polyharmonic_coefficients( source_landmarks: Any, target_controls: Any,) -> tuple[Any, tuple[dict[str, float], ...]]: torch = _require_torch() target_controls = _validate_torch_landmarks( target_controls, label="target controls", ) source_landmarks = _validate_torch_landmarks( source_landmarks, label="source landmarks", batch=target_controls.shape[0], ) if source_landmarks.device != target_controls.device: raise NativeWFLW98Error("source and target landmarks must share one device") target64 = target_controls.to(dtype=torch.float64) source64 = source_landmarks.to(dtype=torch.float64) displacement64 = target64 - source64 detached_displacement = displacement64.detach() if not bool(torch.isfinite(detached_displacement).all().item()): raise NativeWFLW98Error("target-minus-source contains non-finite values") if bool((torch.abs(detached_displacement) > 4.0).any().item()): raise NativeWFLW98Error("target-minus-source exceeds the range [-4,4]")
target_cpu = target_controls.detach().to(device="cpu").numpy() conditions: list[float] = [] for batch_index in range(target_controls.shape[0]): condition = _numpy_condition_number( np.ascontiguousarray(target_cpu[batch_index], dtype=_LITTLE_F4) ) if condition > POLYHARMONIC_CONDITION_LIMIT: raise NativeWFLW98Error( f"batch item {batch_index} exceeds the polyharmonic condition limit" ) conditions.append(condition)
boundary64 = torch.tensor( BOUNDARY_POINTS, device=target_controls.device, dtype=torch.float64, )[None].expand(target_controls.shape[0], -1, -1) controls64 = torch.cat((target64, boundary64), dim=1) zero_boundary = torch.zeros_like(boundary64) values64 = torch.cat((displacement64, zero_boundary), dim=1) count = controls64.shape[1] radial = torch.cdist(controls64, controls64, p=2) radial = radial + torch.eye( count, device=radial.device, dtype=torch.float64, )[None] * POLYHARMONIC_REGULARIZATION affine = torch.cat( ( torch.ones( (controls64.shape[0], count, 1), device=radial.device, dtype=torch.float64, ), controls64, ), dim=2, ) system = torch.cat( ( torch.cat((radial, affine), dim=2), torch.cat( ( affine.transpose(1, 2), torch.zeros( (controls64.shape[0], 3, 3), device=radial.device, dtype=torch.float64, ), ), dim=2, ), ), dim=1, ) rhs = torch.cat( ( values64, torch.zeros( (controls64.shape[0], 3, 2), device=radial.device, dtype=torch.float64, ), ), dim=1, ) coefficients64 = torch.linalg.solve(system, rhs) residual64 = torch.bmm(system, coefficients64) - rhs diagnostics: list[dict[str, float]] = [] tiny = torch.finfo(torch.float64).tiny for batch_index, condition in enumerate(conditions): matrix_norm = torch.linalg.matrix_norm(system[batch_index], ord=float("inf")) coefficient_norm = torch.linalg.matrix_norm( coefficients64[batch_index], ord=float("inf") ) rhs_norm = torch.linalg.matrix_norm(rhs[batch_index], ord=float("inf")) residual_norm = torch.linalg.matrix_norm( residual64[batch_index], ord=float("inf") ) denominator = torch.clamp( matrix_norm * coefficient_norm + rhs_norm, min=tiny, ) relative = residual_norm / denominator relative_value = float(relative.detach().cpu().item()) if ( not math.isfinite(relative_value) or relative_value > POLYHARMONIC_RESIDUAL_LIMIT ): raise NativeWFLW98Error( f"batch item {batch_index} exceeds the polyharmonic residual limit" ) diagnostics.append( { "condition_number_float64": float(condition), "relative_residual_float64": relative_value, } ) return coefficients64.to(dtype=torch.float32), tuple(diagnostics)
def evaluate_wflw98_displacement( target_controls: Any, coefficients: Any, query_points: Any,) -> Any: torch = _require_torch() target_controls = _validate_torch_landmarks( target_controls, label="target controls", ) if ( not torch.is_tensor(coefficients) or coefficients.dtype != torch.float32 or coefficients.shape != (target_controls.shape[0], 109, 2) ): raise NativeWFLW98Error("coefficients must have shape (B,109,2) float32") if ( not torch.is_tensor(query_points) or query_points.dtype != torch.float32 or query_points.ndim != 3 or query_points.shape[0] != target_controls.shape[0] or query_points.shape[2] != 2 ): raise NativeWFLW98Error("query points must have shape (B,M,2) float32") if ( query_points.device != target_controls.device or coefficients.device != target_controls.device ): raise NativeWFLW98Error("warp tensors must share one device") if not bool(torch.isfinite(coefficients.detach()).all().item()): raise NativeWFLW98Error("coefficients contain non-finite values") if not bool(torch.isfinite(query_points.detach()).all().item()): raise NativeWFLW98Error("query points contain non-finite values") if bool((torch.abs(query_points.detach()) > NORMALIZED_COORDINATE_LIMIT).any().item()): raise NativeWFLW98Error("query points exceed the inclusive range [-2,2]") boundary = torch.tensor( BOUNDARY_POINTS, device=target_controls.device, dtype=torch.float32, )[None].expand(target_controls.shape[0], -1, -1) controls = torch.cat((target_controls, boundary), dim=1) radial_weights = coefficients[:, : controls.shape[1]] affine_weights = coefficients[:, controls.shape[1] :] query_radial = torch.cdist(query_points, controls, p=2) query_affine = torch.cat( ( torch.ones( (query_points.shape[0], query_points.shape[1], 1), device=query_points.device, dtype=torch.float32, ), query_points, ), dim=2, ) return torch.bmm(query_radial, radial_weights) + torch.bmm( query_affine, affine_weights )
def warp_image_wflw98( image: Any, source_landmarks: Any, target_landmarks: Any,) -> tuple[Any, tuple[dict[str, float], ...]]: torch = _require_torch() if ( not torch.is_tensor(image) or image.dtype != torch.float32 or image.ndim != 4 or image.shape[1] != 3 ): raise NativeWFLW98Error("image must have shape (B,3,H,W) float32") batch, _channels, height, width = image.shape if (height, width) != (ALIGNED_IMAGE_SIZE, ALIGNED_IMAGE_SIZE): raise NativeWFLW98Error("image must use the registered 224x224 decoder canvas") if not bool(torch.isfinite(image.detach()).all().item()): raise NativeWFLW98Error("image contains non-finite values") source_landmarks = _validate_torch_landmarks( source_landmarks, label="source landmarks", batch=batch, ) target_landmarks = _validate_torch_landmarks( target_landmarks, label="target landmarks", batch=batch, ) if source_landmarks.device != image.device or target_landmarks.device != image.device: raise NativeWFLW98Error("image and landmark tensors must share one device") coefficients, diagnostics = solve_wflw98_polyharmonic_coefficients( source_landmarks, target_landmarks, ) ys = torch.linspace(-1.0, 1.0, height, device=image.device, dtype=torch.float32) xs = torch.linspace(-1.0, 1.0, width, device=image.device, dtype=torch.float32) grid_y, grid_x = torch.meshgrid(ys, xs, indexing="ij") query = torch.stack((grid_x, grid_y), dim=2).reshape(1, height * width, 2) query = query.expand(batch, -1, -1) dense_forward = evaluate_wflw98_displacement( target_landmarks, coefficients, query, ) inverse_grid = (query - dense_forward).reshape(batch, height, width, 2) warped = torch.nn.functional.grid_sample( image, inverse_grid, mode="bilinear", padding_mode="border", align_corners=True, ) return warped, diagnostics
__all__ = [ "ALIGNED_IMAGE_SIZE", "GeometryRecord", "IdentityGeometry", "LandmarkNumericExcursion", "MAX_LANDMARK_NPY_BYTES", "MINIMUM_ACCEPTED_IMAGES", "NORMALIZED_COORDINATE_LIMIT", "NPY_VERSION", "NativeWFLW98Error", "POLYHARMONIC_RESIDUAL_LIMIT", "PreFreezeGeometry", "apply_alignment_affine_to_wflw98", "evaluate_wflw98_displacement", "exact_landmark_npy_v2_bytes", "read_exact_landmark_npy_v2_bytes", "registered_alignment_affine_from_wflw98", "reduce_prefreeze_geometry", "solve_wflw98_polyharmonic_coefficients", "warp_image_wflw98", "write_exact_landmark_npy_v2",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899from __future__ import annotations
import jsonimport osfrom pathlib import Pathfrom threading import Lockfrom typing import Any
from .asset_contract import checked_asset, need, sha256_file
MODEL_REPOSITORY = "ProgramComputer/Speech2Face-models"REPOSITORY_SCHEMA = "speech2face.space-model-repository/v1"WEIGHT_FILES = ( "voice-arcface.keras", "voice-facenet.keras", "decoder-arcface.safetensors", "decoder-facenet.safetensors",)_DOWNLOADS: dict[tuple[str, str, str, str, int], Path] = {}_DOWNLOAD_LOCK = Lock()
def validate_repository_record(record: dict[str, str]) -> dict[str, str]: need( type(record) is dict and set(record) == {"schema", "repo_id", "revision"} and record["schema"] == REPOSITORY_SCHEMA and record["repo_id"] == MODEL_REPOSITORY, "Invalid model repository record", ) revision = record["revision"] need( isinstance(revision, str) and ( revision == "main" or len(revision) == 40 and all(c in "0123456789abcdef" for c in revision) ), "Invalid model repository revision", ) return record
def load_repository_record(path: str | Path) -> dict[str, str]: try: return validate_repository_record(json.loads(Path(path).read_text(encoding="utf-8"))) except Exception: raise ValueError("Invalid model repository record") from None
def _checked_download(path: Path, reference: dict[str, Any]) -> Path: try: need( path.is_file() and path.stat().st_size == reference["size_bytes"] and sha256_file(path) == reference["sha256"], "Downloaded model weight failed integrity verification", ) except Exception: raise ValueError("Downloaded model weight failed integrity verification") from None return path
def resolve_model_asset(root: str | Path, reference: dict[str, Any]) -> Path: name = reference["file"] need(name in WEIGHT_FILES, "Unregistered model weight") local = Path(root) / name if local.exists() or local.is_symlink(): return checked_asset(root, reference) record = load_repository_record(Path(root) / "model-repository.json") need( type(reference["size_bytes"]) is int and reference["size_bytes"] > 0 and isinstance(reference["sha256"], str) and len(reference["sha256"]) == 64 and all(c in "0123456789abcdef" for c in reference["sha256"]), "Invalid model weight integrity record", ) key = record["repo_id"], record["revision"], name, reference["sha256"], reference["size_bytes"] with _DOWNLOAD_LOCK: if key not in _DOWNLOADS: try: from huggingface_hub import __version__, hf_hub_download
need(__version__ == "2.4.0", "Use the pinned model-download runtime") downloaded = Path( hf_hub_download( repo_id=record["repo_id"], filename=name, repo_type="model", revision=record["revision"], token=os.environ.get("HF_TOKEN"), ) ) except Exception: raise ValueError("Model weight download failed") from None _DOWNLOADS[key] = _checked_download(downloaded, reference) return _DOWNLOADS[key] return _checked_download(_DOWNLOADS[key], reference)12345678910111213141516171819202122232425from __future__ import annotations
import hashlibfrom typing import Any
def need(ok: Any, message: str) -> None: if not ok: raise ValueError(message)
def reloaded_variables_hash(model: Any) -> str: h = hashlib.sha256() scope = model.name + "/" for v in model.variables: path = str(getattr(v, "path", v.name)) need( path and not path.startswith(scope), "Reloaded model variable path must be nonempty and omit the model scope", ) a = v.numpy() h.update((scope + path).encode()) h.update(str((a.shape, str(a.dtype))).encode()) h.update(a.tobytes()) return h.hexdigest()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687from __future__ import annotations
import torchfrom torch import nn
from .decoder_native_wflw98 import ( ALIGNED_IMAGE_SIZE, NORMALIZED_COORDINATE_LIMIT, NativeWFLW98Error, warp_image_wflw98,)from .decoder_geometry_policy import LANDMARK_COUNTfrom .decoder_heads import DECODER_FEATURE_DIM, _make_decoder_heads
def _landmarks(value: torch.Tensor, *, label: str) -> None: if not torch.is_tensor(value) or value.dtype != torch.float32: raise NativeWFLW98Error(f"{label} must be float32") if value.ndim != 3 or value.shape[1:] != (LANDMARK_COUNT, 2) or value.shape[0] < 1: raise NativeWFLW98Error(f"{label} must have nonempty shape (B,98,2)") if not torch.isfinite(value.detach()).all(): raise NativeWFLW98Error(f"{label} contains non-finite coordinates") if (value.detach().abs() > NORMALIZED_COORDINATE_LIMIT).any(): raise NativeWFLW98Error(f"{label} exceeds inclusive range [-2,2]")
class NativeWFLW98FaceWarp(nn.Module): def __init__( self, mean_landmarks: torch.Tensor, ) -> None: super().__init__() mean = torch.as_tensor(mean_landmarks) if mean.shape != (LANDMARK_COUNT, 2): raise NativeWFLW98Error("mean landmarks must have shape (98,2)") _landmarks(mean[None], label="mean landmarks") self.register_buffer("mean_landmarks", mean.detach().clone())
def forward( self, texture: torch.Tensor, landmarks: torch.Tensor, ) -> tuple[torch.Tensor, tuple[dict[str, float], ...]]: _landmarks(landmarks, label="predicted landmarks") source = self.mean_landmarks[None].expand(landmarks.shape[0], -1, -1) return warp_image_wflw98(texture, source, landmarks)
class NativeWFLW98FaceDecoder(nn.Module): def __init__( self, mean_landmarks: torch.Tensor, ) -> None: super().__init__() (self.fc3, self.geometry_head, self.texture_fc, self.texture_decoder) = ( _make_decoder_heads(landmark_count=LANDMARK_COUNT, bounded_geometry=False) ) self.warp = NativeWFLW98FaceWarp(mean_landmarks)
def forward( self, feature: torch.Tensor, ) -> dict[str, torch.Tensor | tuple[dict[str, float], ...]]: if ( not torch.is_tensor(feature) or feature.dtype != torch.float32 or feature.ndim != 2 or feature.shape[1] != DECODER_FEATURE_DIM or feature.shape[0] < 1 ): raise ValueError("feature must have nonempty float32 shape (B,4096)") if not torch.isfinite(feature.detach()).all(): raise ValueError("feature contains non-finite values") shared = torch.relu(self.fc3(feature)) landmarks = self.geometry_head(shared).reshape(-1, LANDMARK_COUNT, 2) _landmarks(landmarks, label="predicted landmarks") seed = torch.relu(self.texture_fc(shared)).reshape(-1, 256, 14, 14) texture = self.texture_decoder(seed) if texture.shape[1:] != (3, ALIGNED_IMAGE_SIZE, ALIGNED_IMAGE_SIZE): raise ValueError("texture decoder changed the registered RGB224 canvas") rendered, diagnostics = self.warp(texture, landmarks) return { "landmarks": landmarks, "registered_texture": texture, "rendered_face": rendered, "warp_diagnostics": diagnostics, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167from __future__ import annotations
from pathlib import Pathfrom typing import Any, Callable
from .runtime import configure_tensorflow, configure_torch, cpu_voice_call
import numpy as np
from .asset_contract import load_manifest, needfrom .model_assets import resolve_model_assetfrom .audio_features import waveform_to_complex_spectrogramfrom .qualified_audio import decode_audio_file as to_waveformfrom .model_state import reloaded_variables_hashfrom .pixel_codec import quantize_rgb
PAIRS = { "arcface": "ArcFace decoder", "facenet": "FaceNet decoder",}
class SpeechToFace: def __init__(self, asset_dir: str | Path) -> None: self.asset_dir = Path(asset_dir) self._voices: dict[str, Any] = {} self._decoders: dict[str, Any] = {} self._manifests: dict[tuple[str, str], dict[str, Any]] = {} self._voice_output_devices: dict[str, str] = {} self._decoder_output_devices: dict[str, str] = {}
def _manifest(self, part: str, pair: str) -> dict[str, Any]: if pair not in PAIRS: raise ValueError(f"Unknown pipeline {pair!r}") key = part, pair if key not in self._manifests: manifest = load_manifest(self.asset_dir, part, pair) other = self._manifests.get(("decoder" if part == "voice" else "voice", pair)) need( other is None or other["binding"] == manifest["binding"], "Crossed voice/decoder assets", ) self._manifests[key] = manifest return self._manifests[key]
def voice(self, pair: str) -> Any: if pair not in self._voices: manifest = self._manifest("voice", pair) tf = configure_tensorflow() with tf.device("/CPU:0"): model = tf.keras.models.load_model( resolve_model_asset(self.asset_dir, manifest), compile=False, safe_mode=True, ) need( all(str(v.dtype) == "float32" for v in model.variables) and reloaded_variables_hash(model) == manifest["binding"]["voice_model_state_sha256"], "Loaded final voice model state differs", ) self._voices[pair] = model return self._voices[pair]
def decoder(self, pair: str) -> Any: if pair not in self._decoders: manifest = self._manifest("decoder", pair) torch = configure_torch() from safetensors.torch import load_file from .native_wflw98_decoder import NativeWFLW98FaceDecoder
state = load_file(str(resolve_model_asset(self.asset_dir, manifest)), device="cpu") model = NativeWFLW98FaceDecoder(state["warp.mean_landmarks"].clone()) model.load_state_dict(state, strict=True) model.cpu().eval().requires_grad_(False) need( all( p.dtype == torch.float32 and p.device.type == "cpu" for p in model.parameters() ), "Decoder must remain CPU float32", ) self._decoders[pair] = model return self._decoders[pair]
def predict_fc7( self, audio_path: str | Path, pair: str, *, _audio_observer: Callable[[np.ndarray, np.ndarray], None] | None = None, ) -> np.ndarray: wave = to_waveform(audio_path) spectrogram = waveform_to_complex_spectrogram(wave) if _audio_observer is not None: _audio_observer(wave.copy(), spectrogram.copy()) return self.voice_stft(spectrogram, pair)
def voice_stft( self, spectrogram: np.ndarray, pair: str, ) -> np.ndarray: need( spectrogram.dtype == np.float32 and spectrogram.shape == (598, 257, 2) and np.isfinite(spectrogram).all(), "Invalid STFT", ) result = cpu_voice_call(self.voice(pair), spectrogram[None]) self._voice_output_devices[pair] = result.device feature = result.numpy() need( feature.dtype == np.float32 and feature.shape == (1, 4096) and np.isfinite(feature).all(), "Final voice output differs", ) configure_tensorflow() return feature[0].copy()
def raw_face(self, feature: np.ndarray, pair: str) -> np.ndarray: torch = configure_torch() values = np.asarray(feature) need( values.dtype == np.float32 and values.shape == (4096,) and np.isfinite(values).all(), "Invalid fc7", ) with torch.no_grad(): tensor = self.decoder(pair)(torch.from_numpy(values[None].copy()))["rendered_face"][0] need( tensor.dtype == torch.float32 and tensor.device.type == "cpu", "Decoder output must remain CPU float32", ) self._decoder_output_devices[pair] = str(tensor.device) result = tensor.cpu().numpy() configure_torch() return result
def render_fc7( self, feature: np.ndarray, pair: str, *, _raw_observer: Callable[[np.ndarray], None] | None = None, ) -> np.ndarray: raw = self.raw_face(feature, pair) if _raw_observer is not None: _raw_observer(raw.copy()) pixels, _outside_fraction = quantize_rgb(raw) return pixels
def infer( self, audio_path: str | Path, pair: str, *, _feature_observer: Callable[[np.ndarray], None] | None = None, _audio_observer: Callable[[np.ndarray, np.ndarray], None] | None = None, ) -> tuple[np.ndarray, np.ndarray]: feature = self.predict_fc7(audio_path, pair, _audio_observer=_audio_observer) if _feature_observer is not None: _feature_observer(feature.copy()) return feature, self.render_fc7(feature, pair)
def __call__(self, audio_path: str, pair: str) -> np.ndarray: return self.infer(audio_path, pair)[1]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596from __future__ import annotations
import structimport zlib
import numpy as np
IMAGE_SIZE = 224_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
class EvidenceError(ValueError): pass
def _chunk(kind: bytes, data: bytes) -> bytes: return ( struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) )
def encode_png_rgb(image: np.ndarray) -> bytes: array = np.asarray(image) if array.dtype != np.uint8 or array.ndim != 3 or array.shape[2] != 3 or 0 in array.shape[:2]: raise EvidenceError("PNG encoder accepts uint8 RGB HWC only") height, width = array.shape[:2] scanlines = np.zeros((height, 1 + width * 3), dtype=np.uint8) scanlines[:, 1:] = np.ascontiguousarray(array).reshape(height, width * 3) header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0) return ( _PNG_SIGNATURE + _chunk(b"IHDR", header) + _chunk(b"IDAT", zlib.compress(scanlines.tobytes(), 9)) + _chunk(b"IEND", b"") )
def decode_png_rgb(raw: bytes) -> np.ndarray: if not raw.startswith(_PNG_SIGNATURE): raise EvidenceError("PNG signature missing") idat: list[bytes] offset, header, idat, ended = len(_PNG_SIGNATURE), None, [], False while offset < len(raw): if offset + 8 > len(raw): raise EvidenceError("PNG chunk header truncated") (length,) = struct.unpack(">I", raw[offset : offset + 4]) kind = raw[offset + 4 : offset + 8] data = raw[offset + 8 : offset + 8 + length] crc = raw[offset + 8 + length : offset + 12 + length] if ( len(data) != length or len(crc) != 4 or struct.unpack(">I", crc)[0] != (zlib.crc32(kind + data) & 0xFFFFFFFF) ): raise EvidenceError("PNG chunk is truncated or fails its CRC") offset += 12 + length if kind == b"IHDR" and header is None and length == 13: header = struct.unpack(">IIBBBBB", data) elif kind == b"IDAT" and header is not None: idat.append(data) elif kind == b"IEND" and length == 0: ended = True break else: raise EvidenceError("Unexpected PNG chunk") if not ended or offset != len(raw) or header is None: raise EvidenceError("PNG stream is incomplete or has trailing bytes") width, height, depth, color, compression, filtering, interlace = header if ( (depth, color, compression, filtering, interlace) != (8, 2, 0, 0, 0) or not width or not height ): raise EvidenceError("Only non-interlaced 8-bit RGB PNG is accepted") data = zlib.decompress(b"".join(idat)) stride = 1 + width * 3 if len(data) != stride * height: raise EvidenceError("PNG pixel payload size mismatch") rows = np.frombuffer(data, dtype=np.uint8).reshape(height, stride) if np.any(rows[:, 0] != 0): raise EvidenceError("Only PNG filter type 0 is accepted") return rows[:, 1:].reshape(height, width, 3).copy()
def quantize_rgb(chw: np.ndarray) -> tuple[np.ndarray, float]: array = np.asarray(chw) if array.dtype != np.float32 or array.shape != (3, IMAGE_SIZE, IMAGE_SIZE): raise EvidenceError("Image must be float32 CHW (3,224,224)") if not np.isfinite(array).all(): raise EvidenceError("Image contains non-finite values") outside = int(np.count_nonzero((array < 0.0) | (array > 1.0))) quantized = np.rint(np.clip(array.astype(np.float64), 0.0, 1.0) * 255.0).astype(np.uint8) return np.ascontiguousarray(quantized.transpose(1, 2, 0)), outside / array.size12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364from __future__ import annotations
import iofrom pathlib import Path
from . import runtime as _runtimeimport numpy as npfrom .asset_contract import needfrom .audio_features import repeat_or_trim_waveform
MAX_AUDIO_BYTES = 32 << 20
def decode_audio_file(audio_path: str | Path) -> np.ndarray: import av
need(av.__version__ == "12.3.0" and np.__version__ == "2.2.6", "Audio runtime versions differ") path = Path(audio_path) need(path.is_file() and 0 < path.stat().st_size <= MAX_AUDIO_BYTES, "The recording is empty") raw = path.read_bytes() need(0 < len(raw) <= MAX_AUDIO_BYTES, "Audio bytes exceed per-row bound") seconds = 6 retained: list[np.ndarray] retained, kept, decoded_samples, errors = [], 0, 0, 0 target = seconds * 16000 with av.open(io.BytesIO(raw), mode="r") as container: need(container.streams.audio, "No audio stream") stream = container.streams.audio[0] stream.codec_context.thread_count = 1 resampler = av.AudioResampler(format="fltp", layout="mono", rate=16000)
def keep(frames: list[av.AudioFrame]) -> None: nonlocal kept for frame in frames: wave = frame.to_ndarray().reshape(-1).astype(np.float32, copy=False) need(np.isfinite(wave).all(), "Non-finite resampled waveform") length = min(len(wave), target - kept) if length > 0: retained.append(wave[:length].copy()) kept += length
for packet in container.demux(stream): try: frames = packet.decode() except av.error.FFmpegError: errors += 1 if errors > 64: break continue for frame in frames: decoded_samples += int(frame.samples) keep(resampler.resample(frame)) keep(resampler.resample(None)) context = stream.codec_context channels = getattr(context, "channels", None) or len(context.layout.channels) observed = { "audio_codec": str(context.name), "audio_sample_rate": int(context.sample_rate), "audio_channels": int(channels), "audio_decoded_samples": decoded_samples, } need(kept > 0, "No decodable waveform") waveform = repeat_or_trim_waveform(np.concatenate(retained), target) return waveform123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899from __future__ import annotations
import osfrom typing import Any
from .asset_contract import need
ENVIRONMENT = { "TF_DETERMINISTIC_OPS": "1", "TF_ENABLE_ONEDNN_OPTS": "0", "NVIDIA_TF32_OVERRIDE": "0", "CUBLAS_WORKSPACE_CONFIG": ":4096:8", "OMP_NUM_THREADS": "1", "OPENBLAS_NUM_THREADS": "1", "MKL_NUM_THREADS": "1", "BLIS_NUM_THREADS": "1", "NUMEXPR_NUM_THREADS": "1", "VECLIB_MAXIMUM_THREADS": "1", "CUDA_VISIBLE_DEVICES": "", "NPY_DISABLE_CPU_FEATURES": "AVX512F AVX512CD AVX512_SKX AVX512_CLX AVX512_CNL AVX512_ICL",}os.environ.update(ENVIRONMENT)_TF = None_TORCH = None
def configure_tensorflow() -> Any: global _TF if _TF is None: import numpy as np import tensorflow as tf import keras
need( tf.__version__ == "2.20.0" and keras.__version__ == "3.11.3" and np.__version__ == "2.2.6", "Use the pinned voice/Space runtime", ) tf.config.threading.set_intra_op_parallelism_threads(1) tf.config.threading.set_inter_op_parallelism_threads(1) tf.config.set_visible_devices([], "GPU") tf.config.experimental.enable_op_determinism() tf.config.experimental.enable_tensor_float_32_execution(False) tf.keras.mixed_precision.set_global_policy("float32") tf.keras.utils.set_random_seed(1729) tf.random.set_global_generator(tf.random.Generator.from_seed(1729, alg="philox")) _TF = tf need( not _TF.config.experimental.tensor_float_32_execution_enabled() and _TF.keras.mixed_precision.global_policy().name == "float32" and not _TF.config.list_logical_devices("GPU"), "TF CPU/precision policy changed", ) return _TF
def cpu_voice_call(model: Any, tensor: Any) -> Any: tf = configure_tensorflow() devices = [str(getattr(v, "handle", v).device) for v in model.variables] need( devices and all(d.upper().endswith("/DEVICE:CPU:0") for d in devices), "Voice variables must be on CPU:0", ) with tf.device("/CPU:0"): result = model(tensor, training=False) need("CPU:0" in result.device.upper(), "Voice output must be on CPU:0") return result
def configure_torch() -> Any: global _TORCH if _TORCH is None: import torch
need(torch.__version__ == "2.5.1+cu124", "Use the pinned decoder Torch build") torch.use_deterministic_algorithms(True, warn_only=False) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False torch.backends.cuda.matmul.allow_tf32 = False torch.backends.cudnn.allow_tf32 = False torch.set_float32_matmul_precision("highest") torch.set_num_threads(1) if torch.get_num_interop_threads() != 1: torch.set_num_interop_threads(1) _TORCH = torch need( _TORCH.get_default_dtype() == _TORCH.float32 and _TORCH.are_deterministic_algorithms_enabled() and not _TORCH.is_deterministic_algorithms_warn_only_enabled() and not _TORCH.backends.cuda.matmul.allow_tf32 and not _TORCH.backends.cudnn.allow_tf32 and _TORCH.backends.cudnn.deterministic and not _TORCH.backends.cudnn.benchmark and _TORCH.get_float32_matmul_precision() == "highest" and _TORCH.get_num_threads() == _TORCH.get_num_interop_threads() == 1, "Torch precision policy changed", ) return _TORCH123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899from __future__ import annotations
from typing import Any
from .audio_features import PAPER_SPECTROGRAM_SHAPE
def speech2face_voice_spatial_shapes( input_time: int = PAPER_SPECTROGRAM_SHAPE[0], input_frequency: int = PAPER_SPECTROGRAM_SHAPE[1],) -> list[tuple[str, int, int]]: time_steps, frequency_bins = int(input_time), int(input_frequency) shapes: list[tuple[str, int, int]] = [("input", time_steps, frequency_bins)]
def valid_conv(name: str, kernel: int = 4, stride: int = 1) -> None: nonlocal time_steps, frequency_bins time_steps = (time_steps - kernel) // stride + 1 frequency_bins = (frequency_bins - kernel) // stride + 1 if min(time_steps, frequency_bins) <= 0: raise ValueError(f"{name} collapses spatial dimensions") shapes.append((name, time_steps, frequency_bins))
def temporal_pool(name: str) -> None: nonlocal time_steps time_steps = (time_steps - 2) // 2 + 1 if time_steps <= 0: raise ValueError(f"{name} collapses the time dimension") shapes.append((name, time_steps, frequency_bins))
valid_conv("conv1") valid_conv("conv2") valid_conv("conv3") temporal_pool("pool1") valid_conv("conv4") temporal_pool("pool2") valid_conv("conv5") temporal_pool("pool3") valid_conv("conv6") temporal_pool("pool4") valid_conv("conv7") valid_conv("conv8", stride=2) valid_conv("conv9", stride=2) shapes.append(("temporal_average", 1, frequency_bins)) return shapes
def build_voice_encoder_4096(input_shape: tuple[int, ...] = PAPER_SPECTROGRAM_SHAPE) -> Any: input_shape = tuple(int(value) for value in input_shape) if input_shape != PAPER_SPECTROGRAM_SHAPE: raise ValueError( f"Paper voice input must be {PAPER_SPECTROGRAM_SHAPE}; got {input_shape}" ) shape_trace = speech2face_voice_spatial_shapes(input_shape[0], input_shape[1]) temporal_pool_size = shape_trace[-2][1] try: from tensorflow.keras import Sequential from tensorflow.keras.layers import ( AveragePooling2D, BatchNormalization, Conv2D, Dense, Flatten, MaxPooling2D, ReLU, ) except ImportError as exc: raise ImportError( "TensorFlow is required to build the trainable voice encoder; " "use speech2face_voice_spatial_shapes for shape-only inspection" ) from exc
model = Sequential(name="voice_encoder_speech2face_table1")
def add_conv(filters: int, *, strides: int = 1, first: bool = False) -> None: kwargs: dict[str, tuple[int, ...]] = {"input_shape": input_shape} if first else {} model.add(Conv2D(filters, (4, 4), strides=strides, padding="valid", **kwargs)) model.add(ReLU()) model.add(BatchNormalization())
add_conv(64, first=True) add_conv(64) add_conv(128) model.add(MaxPooling2D((2, 1), strides=(2, 1), padding="valid")) add_conv(128) model.add(MaxPooling2D((2, 1), strides=(2, 1), padding="valid")) add_conv(128) model.add(MaxPooling2D((2, 1), strides=(2, 1), padding="valid")) add_conv(256) model.add(MaxPooling2D((2, 1), strides=(2, 1), padding="valid")) add_conv(512) add_conv(512, strides=2) model.add(Conv2D(512, (4, 4), strides=2, padding="valid")) model.add(AveragePooling2D((temporal_pool_size, 1), strides=(1, 1), padding="valid")) model.add(ReLU()) model.add(BatchNormalization()) model.add(Flatten()) model.add(Dense(4096, activation="relu")) model.add(Dense(4096)) return model.gitattributesAdded+42
DockerfileAdded+21
README.mdAdded+10
app.pyAdded+142
assets/decoder-arcface.jsonAdded+66
assets/decoder-facenet.jsonAdded+66
assets/model-repository.jsonAdded+5
assets/voice-arcface.jsonAdded+64
assets/voice-facenet.jsonAdded+64
example_data.pyAdded+127
examples/example-1-credit.txtAdded+1
examples/example-1-licence.jsonAdded+1
examples/example-1.wavAdded+3
examples/example-2-credit.txtAdded+1
examples/example-2-licence.jsonAdded+1
examples/example-2.wavAdded+3
examples/example-3-credit.txtAdded+1
examples/example-3-licence.jsonAdded+1
examples/example-3.wavAdded+3
examples/example-4-credit.txtAdded+1
examples/example-4-licence.jsonAdded+1
examples/example-4.wavAdded+3
examples/example-5-credit.txtAdded+1
examples/example-5-licence.jsonAdded+1
examples/example-5.wavAdded+3
examples/examples.jsonAdded+1
inference-requirements.txtAdded+9
requirements.txtAdded+104
s2f/VENDORED.jsonAdded+123
s2f/__init__.pyAdded
s2f/asset_contract.pyAdded+258
s2f/audio_features.pyAdded+87
s2f/decoder_geometry_policy.pyAdded+683
s2f/decoder_heads.pyAdded+38
s2f/decoder_native_wflw98.pyAdded+916
s2f/model_assets.pyAdded+99
s2f/model_state.pyAdded+25
s2f/native_wflw98_decoder.pyAdded+87
s2f/pipeline.pyAdded+167
s2f/pixel_codec.pyAdded+96
s2f/qualified_audio.pyAdded+64
s2f/runtime.pyAdded+99
s2f/voice_model.pyAdded+99