147 lines
5.2 KiB
Python
147 lines
5.2 KiB
Python
|
|
"""H3 原生音画共同归档;仅接受完整时间区间,绝不裁掉末尾台词。"""
|
|||
|
|
|
|||
|
|
import wave
|
|||
|
|
from pathlib import Path
|
|||
|
|
|
|||
|
|
|
|||
|
|
def verify_runtime(diffusers):
|
|||
|
|
import importlib.metadata
|
|||
|
|
import json
|
|||
|
|
import re
|
|||
|
|
import sys
|
|||
|
|
|
|||
|
|
from .video_profiles import H3_RUNTIME_COMMIT
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
source = Path(diffusers.__file__).resolve(strict=True)
|
|||
|
|
distribution = importlib.metadata.distribution("diffusers")
|
|||
|
|
if (
|
|||
|
|
not source.is_relative_to(Path(sys.prefix).resolve())
|
|||
|
|
or Path(distribution.locate_file("diffusers/__init__.py")).resolve()
|
|||
|
|
!= source
|
|||
|
|
):
|
|||
|
|
raise ValueError("Diffusers source escaped its isolated environment")
|
|||
|
|
provenance = json.loads(distribution.read_text("direct_url.json") or "{}")
|
|||
|
|
repository = "https://github.com/huggingface/diffusers"
|
|||
|
|
vcs = provenance.get("vcs_info")
|
|||
|
|
if vcs is not None:
|
|||
|
|
if (
|
|||
|
|
provenance.get("url") not in (repository, repository + ".git")
|
|||
|
|
or vcs.get("vcs") != "git"
|
|||
|
|
or vcs.get("commit_id") != H3_RUNTIME_COMMIT
|
|||
|
|
):
|
|||
|
|
raise ValueError(
|
|||
|
|
"Diffusers git revision differs from native AV contract"
|
|||
|
|
)
|
|||
|
|
proof = "git_direct_url"
|
|||
|
|
else:
|
|||
|
|
if (
|
|||
|
|
provenance.get("url") != f"{repository}/archive/{H3_RUNTIME_COMMIT}.zip"
|
|||
|
|
or "dir_info" in provenance
|
|||
|
|
):
|
|||
|
|
raise ValueError(
|
|||
|
|
"Diffusers archive revision differs from native AV contract"
|
|||
|
|
)
|
|||
|
|
archive = provenance.get("archive_info", {})
|
|||
|
|
digest = archive.get("hashes", {}).get("sha256")
|
|||
|
|
if (
|
|||
|
|
not isinstance(digest, str)
|
|||
|
|
or re.fullmatch("[0-9a-f]{64}", digest) is None
|
|||
|
|
):
|
|||
|
|
raise ValueError("Missing installed archive SHA256 provenance")
|
|||
|
|
proof = "archive_direct_url"
|
|||
|
|
return {
|
|||
|
|
"installed_source_revision": H3_RUNTIME_COMMIT,
|
|||
|
|
"provenance_type": proof,
|
|||
|
|
}
|
|||
|
|
except (
|
|||
|
|
OSError,
|
|||
|
|
ValueError,
|
|||
|
|
TypeError,
|
|||
|
|
AttributeError,
|
|||
|
|
importlib.metadata.PackageNotFoundError,
|
|||
|
|
) as exc:
|
|||
|
|
raise RuntimeError(
|
|||
|
|
"Cannot verify native AV Diffusers source revision/provenance"
|
|||
|
|
) from exc
|
|||
|
|
|
|||
|
|
|
|||
|
|
def prepare_audio(audio, sampling_rate, video_frames):
|
|||
|
|
import numpy as np
|
|||
|
|
|
|||
|
|
if type(sampling_rate) is not int or sampling_rate != 32000:
|
|||
|
|
raise RuntimeError("Native audio requires its original 32000 Hz sampling rate")
|
|||
|
|
if type(video_frames) is not int or video_frames not in range(124, 346, 17):
|
|||
|
|
raise RuntimeError("Native audio requires a full native video interval")
|
|||
|
|
if hasattr(audio, "detach"):
|
|||
|
|
audio = audio.detach().float().cpu().numpy()
|
|||
|
|
array = np.asarray(audio)
|
|||
|
|
if (
|
|||
|
|
array.ndim != 3
|
|||
|
|
or array.shape[:2] != (1, 2)
|
|||
|
|
or array.shape[-1] < 1
|
|||
|
|
or not np.issubdtype(array.dtype, np.floating)
|
|||
|
|
or not np.isfinite(array).all()
|
|||
|
|
):
|
|||
|
|
raise RuntimeError(
|
|||
|
|
"Native audio must be a finite floating waveform with shape (1, 2, samples)"
|
|||
|
|
)
|
|||
|
|
samples = array.shape[-1]
|
|||
|
|
audio_duration, video_duration = samples / sampling_rate, video_frames / 24
|
|||
|
|
# 官方40Hz音频latent以最近格点量化;允许半格误差,不用shortest/剪音频伪造同步。
|
|||
|
|
if abs(audio_duration - video_duration) > 1 / 80 + 1 / sampling_rate:
|
|||
|
|
raise RuntimeError(
|
|||
|
|
"Native audio duration does not match its full video interval"
|
|||
|
|
)
|
|||
|
|
return np.ascontiguousarray(array[0], dtype=np.float32), {
|
|||
|
|
"sample_rate": sampling_rate,
|
|||
|
|
"channels": 2,
|
|||
|
|
"audio_samples": samples,
|
|||
|
|
"audio_duration": audio_duration,
|
|||
|
|
"video_duration": video_duration,
|
|||
|
|
"video_frames": video_frames,
|
|||
|
|
"fps": 24,
|
|||
|
|
"start_sample": 0,
|
|||
|
|
"end_sample": samples,
|
|||
|
|
"av_duration_delta": audio_duration - video_duration,
|
|||
|
|
"output_policy": "full_native",
|
|||
|
|
"audio_trimmed": False,
|
|||
|
|
}
|
|||
|
|
|
|||
|
|
|
|||
|
|
def export_native_av(
|
|||
|
|
frames, audio, sampling_rate, video_path, audio_path, encode_video
|
|||
|
|
):
|
|||
|
|
import numpy as np
|
|||
|
|
import torch
|
|||
|
|
|
|||
|
|
waveform, metadata = prepare_audio(audio, sampling_rate, len(frames))
|
|||
|
|
video_path, audio_path = Path(video_path), Path(audio_path)
|
|||
|
|
# WAV和MP4使用同一完整区间;PCM归档保留每个采样点,便于后续ASR与审计。
|
|||
|
|
pcm = np.rint(np.clip(waveform.T, -1, 1) * 32767).astype("<i2")
|
|||
|
|
owned = False
|
|||
|
|
try:
|
|||
|
|
stream = audio_path.open("xb")
|
|||
|
|
owned = True
|
|||
|
|
with stream, wave.open(stream, "wb") as wav:
|
|||
|
|
wav.setnchannels(2)
|
|||
|
|
wav.setsampwidth(2)
|
|||
|
|
wav.setframerate(sampling_rate)
|
|||
|
|
wav.writeframes(pcm.tobytes())
|
|||
|
|
encode_video(
|
|||
|
|
frames,
|
|||
|
|
fps=24,
|
|||
|
|
output_path=str(video_path),
|
|||
|
|
audio=torch.from_numpy(waveform),
|
|||
|
|
audio_sample_rate=sampling_rate,
|
|||
|
|
)
|
|||
|
|
except BaseException:
|
|||
|
|
if owned:
|
|||
|
|
audio_path.unlink(missing_ok=True)
|
|||
|
|
raise
|
|||
|
|
return {
|
|||
|
|
**metadata,
|
|||
|
|
"audio_path": str(audio_path.resolve()),
|
|||
|
|
"audio_format": "pcm_s16le",
|
|||
|
|
}
|