bolar_2 backup
This commit is contained in:
226
assets/gen_audio_prompts.py
Normal file
226
assets/gen_audio_prompts.py
Normal file
@@ -0,0 +1,226 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate deterministic packed-Opus prompt data for firmware2.
|
||||
|
||||
The input directory may contain .ogg or .opus files, but every file must be
|
||||
an Ogg/Opus container. Output format per asset:
|
||||
|
||||
[frame_count:u16-le][frame_size:u16-le][frame_bytes]...
|
||||
|
||||
Only the OpusHead and OpusTags packets are removed. Packet continuation across
|
||||
Ogg pages is supported and malformed/truncated input fails the build.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import pathlib
|
||||
import re
|
||||
import struct
|
||||
import sys
|
||||
|
||||
|
||||
GROUPS = (
|
||||
"activation_device",
|
||||
"device_already_bound",
|
||||
"server_error",
|
||||
"alarm_wake",
|
||||
"alarm_set",
|
||||
"no_network",
|
||||
"wifi_config",
|
||||
"wake_response",
|
||||
"story_expired",
|
||||
"idle_check",
|
||||
"idle_goodbye",
|
||||
"snore_light",
|
||||
"wifi_success",
|
||||
"welcome",
|
||||
"shutdown",
|
||||
"boot",
|
||||
"error",
|
||||
"low_battery_20",
|
||||
"low_battery_10",
|
||||
"net4g_boot_on",
|
||||
"net4g_off",
|
||||
"net4g_on",
|
||||
"net4g_no_wifi",
|
||||
*(f"digit_{digit}" for digit in range(10)),
|
||||
)
|
||||
|
||||
|
||||
def classify(path: pathlib.Path) -> str | None:
|
||||
stem = path.stem.lower()
|
||||
for group in sorted(GROUPS, key=len, reverse=True):
|
||||
if stem == group or stem.startswith(group + "_"):
|
||||
return group
|
||||
return None
|
||||
|
||||
|
||||
def parse_ogg_opus(path: pathlib.Path) -> list[bytes]:
|
||||
data = path.read_bytes()
|
||||
offset = 0
|
||||
packet = bytearray()
|
||||
packets: list[bytes] = []
|
||||
expected_sequence = 0
|
||||
|
||||
while offset < len(data):
|
||||
if len(data) - offset < 27 or data[offset : offset + 4] != b"OggS":
|
||||
raise ValueError(f"{path}: malformed Ogg page at byte {offset}")
|
||||
if data[offset + 4] != 0:
|
||||
raise ValueError(f"{path}: unsupported Ogg version")
|
||||
|
||||
sequence = struct.unpack_from("<I", data, offset + 18)[0]
|
||||
if sequence != expected_sequence:
|
||||
raise ValueError(
|
||||
f"{path}: non-contiguous Ogg sequence "
|
||||
f"{sequence}, expected {expected_sequence}"
|
||||
)
|
||||
expected_sequence += 1
|
||||
|
||||
segment_count = data[offset + 26]
|
||||
table_start = offset + 27
|
||||
payload_start = table_start + segment_count
|
||||
if payload_start > len(data):
|
||||
raise ValueError(f"{path}: truncated Ogg segment table")
|
||||
|
||||
cursor = payload_start
|
||||
for segment_size in data[table_start:payload_start]:
|
||||
end = cursor + segment_size
|
||||
if end > len(data):
|
||||
raise ValueError(f"{path}: truncated Ogg page payload")
|
||||
packet.extend(data[cursor:end])
|
||||
cursor = end
|
||||
if segment_size < 255:
|
||||
packets.append(bytes(packet))
|
||||
packet.clear()
|
||||
offset = cursor
|
||||
|
||||
if packet:
|
||||
raise ValueError(f"{path}: unterminated packet at end of Ogg stream")
|
||||
if len(packets) < 2 or not packets[0].startswith(b"OpusHead"):
|
||||
marker = packets[0][:8] if packets else b"<empty>"
|
||||
raise ValueError(f"{path}: not Ogg/Opus, first packet={marker!r}")
|
||||
if not packets[1].startswith(b"OpusTags"):
|
||||
raise ValueError(f"{path}: missing OpusTags packet")
|
||||
|
||||
frames = [packet for packet in packets[2:] if packet]
|
||||
if not frames:
|
||||
raise ValueError(f"{path}: contains no Opus audio packets")
|
||||
if len(frames) > 0xFFFF:
|
||||
raise ValueError(f"{path}: too many Opus packets")
|
||||
for frame in frames:
|
||||
if len(frame) > 0xFFFF:
|
||||
raise ValueError(f"{path}: Opus packet exceeds uint16 size")
|
||||
return frames
|
||||
|
||||
|
||||
def pack_frames(frames: list[bytes]) -> bytes:
|
||||
output = bytearray(struct.pack("<H", len(frames)))
|
||||
for frame in frames:
|
||||
output.extend(struct.pack("<H", len(frame)))
|
||||
output.extend(frame)
|
||||
return bytes(output)
|
||||
|
||||
|
||||
def identifier(path: pathlib.Path, index: int) -> str:
|
||||
stem = re.sub(r"[^a-zA-Z0-9_]", "_", path.stem)
|
||||
return f"prompt_{stem}_{index}"
|
||||
|
||||
|
||||
def bytes_as_cpp(data: bytes) -> list[str]:
|
||||
lines = []
|
||||
for offset in range(0, len(data), 16):
|
||||
chunk = ", ".join(f"0x{value:02x}" for value in data[offset : offset + 16])
|
||||
lines.append(f" {chunk},")
|
||||
return lines
|
||||
|
||||
|
||||
def generate(input_dir: pathlib.Path, output: pathlib.Path) -> None:
|
||||
candidates = sorted(
|
||||
(
|
||||
path
|
||||
for path in input_dir.iterdir()
|
||||
if path.is_file() and path.suffix.lower() in {".ogg", ".opus"}
|
||||
),
|
||||
key=lambda path: path.name,
|
||||
)
|
||||
assets = []
|
||||
for index, path in enumerate(candidates):
|
||||
group = classify(path)
|
||||
if group is None:
|
||||
raise ValueError(f"{path}: filename does not match a prompt group")
|
||||
frames = parse_ogg_opus(path)
|
||||
packed = pack_frames(frames)
|
||||
assets.append((identifier(path, index), group, path.name, frames, packed))
|
||||
|
||||
if not assets:
|
||||
raise ValueError(f"{input_dir}: no prompt assets found")
|
||||
|
||||
lines = [
|
||||
"#pragma once",
|
||||
"",
|
||||
"// Generated by assets/gen_audio_prompts.py. Do not edit.",
|
||||
"#include <cstddef>",
|
||||
"#include <cstdint>",
|
||||
"",
|
||||
"namespace borla::generated_prompts {",
|
||||
"",
|
||||
"struct PromptBlob {",
|
||||
" const char* group;",
|
||||
" const char* filename;",
|
||||
" const uint8_t* data;",
|
||||
" size_t size;",
|
||||
"};",
|
||||
"",
|
||||
]
|
||||
total = 0
|
||||
max_frame = 0
|
||||
for name, group, filename, frames, packed in assets:
|
||||
lines.append(
|
||||
f"// {filename}: {len(frames)} frames, {len(packed)} packed bytes"
|
||||
)
|
||||
lines.append(f"static const uint8_t {name}[] = {{")
|
||||
lines.extend(bytes_as_cpp(packed))
|
||||
lines.extend(("};", ""))
|
||||
total += len(packed)
|
||||
max_frame = max(max_frame, *(len(frame) for frame in frames))
|
||||
|
||||
lines.append("static const PromptBlob kPromptBlobs[] = {")
|
||||
for name, group, filename, _frames, _packed in assets:
|
||||
lines.append(
|
||||
f' {{"{group}", "{filename}", {name}, sizeof({name})}},'
|
||||
)
|
||||
lines.extend(
|
||||
(
|
||||
"};",
|
||||
"",
|
||||
"static constexpr size_t kPromptBlobCount =",
|
||||
" sizeof(kPromptBlobs) / sizeof(kPromptBlobs[0]);",
|
||||
"",
|
||||
"} // namespace borla::generated_prompts",
|
||||
"",
|
||||
)
|
||||
)
|
||||
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
output.write_text("\n".join(lines), encoding="utf-8")
|
||||
print(
|
||||
f"generated {output}: assets={len(assets)} "
|
||||
f"packed={total} bytes max_frame={max_frame}"
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("input_dir", type=pathlib.Path)
|
||||
parser.add_argument("output", type=pathlib.Path)
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
generate(args.input_dir, args.output)
|
||||
except (OSError, ValueError) as error:
|
||||
print(f"audio prompt generation failed: {error}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user