Speech2Face / example_data.py
ProgramComputer's picture
Super-squash branch 'main' using huggingface_hub
5a5e72e
Raw History Blame Contribute Delete
5.18 kB
from __future__ import annotations
import hashlib
import json
from datetime import datetime, timedelta
from pathlib import Path
import re
import struct
from 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 rows