#!/usr/bin/env python3 """Генерация глав аудиофайла по интервалам тишины.""" from __future__ import annotations import argparse import re import shutil import subprocess import sys import tempfile from pathlib import Path START_RE = re.compile(r'silence_start:\s*(-?\d+(?:\.\d+)?)') END_RE = re.compile(r'silence_end:\s*(-?\d+(?:\.\d+)?)') def probe_duration(path: Path, ffprobe: str) -> float: result = subprocess.run( [ffprobe, '-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', str(path)], capture_output=True, text=True, check=False, ) try: return float(result.stdout.strip()) except ValueError: return 0.0 def detect_silences(path: Path, ffmpeg: str, threshold: str, minimum: float) -> list[tuple[float, float]]: result = subprocess.run( [ffmpeg, '-hide_banner', '-nostdin', '-i', str(path), '-af', f'silencedetect=noise={threshold}:d={minimum}', '-f', 'null', '-'], capture_output=True, text=True, check=False, ) if result.returncode != 0: raise RuntimeError(result.stderr.strip()) starts = [float(value) for value in START_RE.findall(result.stderr)] ends = [float(value) for value in END_RE.findall(result.stderr)] silences = [] for index, start in enumerate(starts): if index < len(ends) and ends[index] > start: silences.append((max(0.0, start), ends[index])) return silences def escape(value: str) -> str: return value.replace('\\', '\\\\').replace(';', '\\;').replace('#', '\\#').replace('=', '\\=') def main() -> int: parser = argparse.ArgumentParser(description='Создать главы по тишине') parser.add_argument('input', type=Path, help='Аудиофайл') parser.add_argument('-o', '--out', type=Path, help='Файл ffmetadata') parser.add_argument('--threshold', default='-40dB', help='Порог тишины') parser.add_argument('--min-silence', type=float, default=0.8, help='Минимальная пауза в секундах') parser.add_argument('--min-chapter', type=float, default=20.0, help='Минимальная длина главы') parser.add_argument('--title', default='', help='Название книги или записи') parser.add_argument('--prefix', default='Chapter', help='Префикс названий глав') parser.add_argument('--titles', type=Path, help='Файл со списком названий, по одному на строку') parser.add_argument('--mux-out', type=Path, help='Собрать M4B с главами') raw = sys.argv[1:] fixed: list[str] = [] skip = False for index, value in enumerate(raw): if skip: skip = False continue if value == '--threshold' and index + 1 < len(raw): candidate = raw[index + 1] if candidate.startswith('-') and candidate not in ('-h', '--help'): fixed.append(f'--threshold={candidate}') skip = True continue fixed.append(value) args = parser.parse_args(fixed) source = args.input.expanduser().resolve() if not source.is_file(): parser.error(f'Файл не найден: {source}') if args.min_silence <= 0 or args.min_chapter <= 0: parser.error('Длины должны быть больше нуля') ffmpeg = shutil.which('ffmpeg') ffprobe = shutil.which('ffprobe') if not ffmpeg or not ffprobe: print('ffmpeg и ffprobe должны быть установлены.', file=sys.stderr) return 1 total = probe_duration(source, ffprobe) if total <= 0: print('Не удалось определить длительность.', file=sys.stderr) return 1 try: silences = detect_silences(source, ffmpeg, args.threshold, args.min_silence) except RuntimeError as error: print(f'Ошибка анализа: {error}', file=sys.stderr) return 2 if not silences: print('Тишина не найдена. Проверьте порог --threshold.', file=sys.stderr) return 1 boundaries = [0.0] end_boundary = total for start, end in silences: if start <= 0.05: continue if end >= total - 0.05: end_boundary = min(end_boundary, max(0.0, start)) else: boundaries.append((start + end) / 2) boundaries.append(end_boundary) boundaries = sorted(set(round(value, 3) for value in boundaries)) segments = [ (boundaries[index], boundaries[index + 1]) for index in range(len(boundaries) - 1) if boundaries[index + 1] - boundaries[index] >= args.min_chapter ] if not segments: print('После фильтрации не осталось глав. Уменьшите --min-chapter.', file=sys.stderr) return 1 titles: list[str] = [] if args.titles: titles_path = args.titles.expanduser() if not titles_path.is_file(): parser.error(f'Файл названий не найден: {titles_path}') titles = [line.strip() for line in titles_path.read_text(encoding='utf-8').splitlines() if line.strip()] lines = [';FFMETADATA1'] if args.title: lines.append(f'title={escape(args.title)}') for number, (start, end) in enumerate(segments, start=1): if number <= len(titles): name = titles[number - 1] else: name = f'{args.prefix} {number}' lines.extend([ '[CHAPTER]', 'TIMEBASE=1/1000', f'START={int(round(start * 1000))}', f'END={int(round(end * 1000))}', f'title={escape(name)}', ]) destination = args.out.expanduser() if args.out else source.with_suffix('.ffmeta') destination = destination.resolve() if destination.exists(): print(f'Файл уже существует: {destination}', file=sys.stderr) return 1 destination.write_text('\n'.join(lines) + '\n', encoding='utf-8') print(f'Готово: {destination}') print(f'Глав: {len(segments)}') if args.mux_out: mux_target = args.mux_out.expanduser().resolve() if mux_target.exists(): print(f'Файл уже существует: {mux_target}', file=sys.stderr) return 1 mux_target.parent.mkdir(parents=True, exist_ok=True) with tempfile.TemporaryDirectory() as directory: meta = Path(directory) / 'chapters.ffmeta' meta.write_text(destination.read_text(encoding='utf-8'), encoding='utf-8') command = [ ffmpeg, '-hide_banner', '-loglevel', 'error', '-nostdin', '-i', str(source), '-i', str(meta), '-map', '0:a', '-map_metadata', '1', '-map_chapters', '1', '-c:a', 'aac', '-b:a', '96k', '-movflags', '+faststart', str(mux_target), ] result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode != 0: print(f'Ошибка сборки M4B: {result.stderr.strip()}', file=sys.stderr) return 2 print(f'M4B с главами: {mux_target}') return 0 if __name__ == '__main__': raise SystemExit(main())