bolar_1 date 2026-7-1 d:/proc

This commit is contained in:
2026-11-27 17:44:38 +08:00
commit 0dbdfa57bc
890 changed files with 325428 additions and 0 deletions

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

BIN
main/assets/common/boot.ogg Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,195 @@
"""Generate C header from Opus files — extracts Opus frames from OGG container.
Usage: python gen_audio_prompts.py <opus_dir> <output.h>
"""
import os
import sys
import struct
import random
def parse_ogg_opus(filepath):
"""Extract raw Opus frames from OGG/Opus file.
Validates that page 0 carries OpusHead — refuses OGG/FLAC, OGG/Vorbis
or any other non-Opus container that would otherwise be silently
misinterpreted as Opus packets and break the firmware decoder.
"""
frames = []
with open(filepath, "rb") as f:
data = f.read()
pos = 0
page_num = 0
while pos < len(data):
# OGG page header
if data[pos:pos+4] != b"OggS":
break
num_segments = data[pos+26]
segment_table = data[pos+27:pos+27+num_segments]
data_start = pos + 27 + num_segments
# Reconstruct packets from segments
packet_data = bytearray()
data_offset = data_start
for seg_size in segment_table:
packet_data.extend(data[data_offset:data_offset+seg_size])
data_offset += seg_size
if seg_size < 255:
# Packet complete
if page_num == 0:
# First packet must be OpusHead — reject anything else
# (FLAC marker is "fLaC", Vorbis is b"\x01vorbis", etc.)
if not bytes(packet_data).startswith(b"OpusHead"):
actual = bytes(packet_data[:8]).decode("ascii", errors="replace")
raise ValueError(
f"{filepath}: not OGG/Opus (page-0 packet starts "
f"with {actual!r}). Re-encode the source to Opus "
f"with: ffmpeg -i <src> -c:a libopus -ar 24000 -b:a 24k <out>.opus"
)
if page_num >= 2 and len(packet_data) > 0:
# Skip pages 0 (OpusHead) and 1 (OpusTags)
frames.append(bytes(packet_data))
packet_data = bytearray()
# If packet spans pages (all segments = 255)
if len(packet_data) > 0 and page_num >= 2:
frames.append(bytes(packet_data))
packet_data = bytearray()
pos = data_offset
page_num += 1
return frames
GROUPS = [
"activation_device",
"device_already_bound",
"server_error",
"alarm_wake",
"alarm_set",
"no_network",
"wifi_config",
"wake_response",
"story_expired",
"idle_check",
"idle_goodbye",
"wifi_success",
"welcome",
"shutdown",
"boot",
"error",
"low_battery_20",
"low_battery_10",
] + [f"digit_{d}" for d in range(10)]
def classify_file(filename):
"""Map filename → group.
File naming rule: <group>.ogg or <group>_<n>.ogg, lowercase, ASCII only.
Single-file groups (e.g. boot, shutdown) match by exact stem; multi-file
groups (e.g. welcome_1, error_3) match by `<group>_` prefix.
Match priority follows GROUPS order (longer-prefix groups first to avoid
`server_error_1` falsely matching `server`-style entries; current GROUPS
list has no prefix overlap, but the order is preserved as a safety rail).
"""
stem = os.path.splitext(filename)[0]
for g in GROUPS:
if stem == g or stem.startswith(g + "_"):
return g
return None
def frames_to_c_array(frames, var_name):
"""Convert Opus frames to C byte array with simple format:
[num_frames:u16][frame_size:u16, frame_data:bytes]...
"""
buf = bytearray()
buf.extend(struct.pack("<H", len(frames)))
for frame in frames:
buf.extend(struct.pack("<H", len(frame)))
buf.extend(frame)
lines = [f"static const uint8_t {var_name}[] = {{"]
for i in range(0, len(buf), 16):
chunk = buf[i:i+16]
hex_str = ", ".join(f"0x{b:02x}" for b in chunk)
lines.append(f" {hex_str},")
lines.append("};")
return "\n".join(lines), len(buf)
def main():
if len(sys.argv) < 3:
print(f"Usage: {sys.argv[0]} <opus_dir> <output.h>")
sys.exit(1)
opus_dir = sys.argv[1]
output_h = sys.argv[2]
groups = {g: [] for g in GROUPS}
total_size = 0
# Scan directory
files = []
for f in sorted(os.listdir(opus_dir)):
if f.lower().endswith((".opus", ".ogg")):
filepath = os.path.join(opus_dir, f)
group = classify_file(f)
if group:
files.append((f, filepath, group))
print(f"Found {len(files)} audio files")
# Generate header
header_lines = [
"#pragma once",
"",
"// Auto-generated by gen_audio_prompts.py — DO NOT EDIT",
"",
"#include <cstdint>",
"#include <cstddef>",
"",
]
array_names = {g: [] for g in GROUPS}
for idx, (filename, filepath, group) in enumerate(files):
frames = parse_ogg_opus(filepath)
var_name = f"audio_{group}_{idx}"
c_array, size = frames_to_c_array(frames, var_name)
header_lines.append(f"// {filename} ({len(frames)} frames, {size} bytes)")
header_lines.append(c_array)
header_lines.append("")
array_names[group].append(var_name)
total_size += size
sys.stdout.buffer.write(f" [{group}] {filename}: {len(frames)} frames, {size} bytes\n".encode("utf-8", errors="replace"))
# Generate group index tables. Always emit the symbols even for empty
# groups so audio_prompt.cc's static references compile — count=0 makes
# HasPrompts() return false and the caller falls back gracefully.
for group, names in array_names.items():
if names:
ptrs = ", ".join(names)
header_lines.append(f"static const uint8_t* audio_{group}_files[] = {{ {ptrs} }};")
header_lines.append(f"static const size_t audio_{group}_sizes[] = {{ {', '.join(f'sizeof({n})' for n in names)} }};")
header_lines.append(f"static const int audio_{group}_count = {len(names)};")
else:
header_lines.append(f"static const uint8_t* audio_{group}_files[] = {{ nullptr }};")
header_lines.append(f"static const size_t audio_{group}_sizes[] = {{ 0 }};")
header_lines.append(f"static const int audio_{group}_count = 0;")
header_lines.append("")
# Write header file
os.makedirs(os.path.dirname(output_h), exist_ok=True)
with open(output_h, "w", encoding="utf-8") as f:
f.write("\n".join(header_lines))
print(f"\nGenerated {output_h}: {total_size} bytes total ({total_size/1024:.1f} KB)")
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,62 @@
#!/bin/bash
# Generate low-battery prompt OGG files via IndexTTS HTTP API.
# Outputs to firmware/main/assets/common/{low_battery_20,low_battery_10}.ogg
#
# Requires: curl, ffmpeg, jq (optional for error msg parsing)
# Run from anywhere; paths resolved relative to script location.
set -euo pipefail
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
OUT_DIR="$SCRIPT_DIR/common"
# IndexTTS HTTP endpoint (matches server/config.yaml TTS_BASE_URL)
TTS_URL="${TTS_BASE_URL:-http://192.168.1.150:10140}/audio/speech/stream"
TTS_VOICE="${TTS_VOICE:-my_voice}" # matches server/config.yaml default
TTS_MODEL="${TTS_MODEL:-indextts}"
declare -a TEXTS=(
"low_battery_20|我快没电了,请及时充电哦!"
"low_battery_10|我快没电了,帮我连接电源充电哦!我先退下了。"
)
mkdir -p "$OUT_DIR"
for entry in "${TEXTS[@]}"; do
name="${entry%%|*}"
text="${entry#*|}"
wav_path="$OUT_DIR/${name}.wav"
ogg_path="$OUT_DIR/${name}.ogg"
echo "==> Generating: $name"
echo " Text: $text"
echo " URL: $TTS_URL"
# Call IndexTTS — response is WAV binary
http_code=$(curl -sS -o "$wav_path" -w "%{http_code}" \
-X POST "$TTS_URL" \
-H "Content-Type: application/json" \
-d "$(printf '{"model":"%s","voice":"%s","input":"%s"}' "$TTS_MODEL" "$TTS_VOICE" "$text")")
if [ "$http_code" != "200" ]; then
echo " ERROR: HTTP $http_code"
cat "$wav_path"
echo
rm -f "$wav_path"
exit 1
fi
echo " WAV: $(stat -f%z "$wav_path" 2>/dev/null || stat -c%s "$wav_path") bytes"
# Convert WAV → Opus OGG (24kHz mono, matches firmware decoder expectations)
ffmpeg -y -i "$wav_path" -c:a libopus -ar 24000 -ac 1 -b:a 24k \
-frame_duration 60 "$ogg_path" 2>&1 | tail -3
rm -f "$wav_path"
echo " OGG: $ogg_path ($(stat -f%z "$ogg_path" 2>/dev/null || stat -c%s "$ogg_path") bytes)"
echo
done
echo "Done. Two OGG files generated in $OUT_DIR/"
echo "Next: regenerate audio_prompts_data.h:"
echo " cd $SCRIPT_DIR && python gen_audio_prompts.py common ../audio/audio_prompts_data.h"