#!/usr/bin/env python3 """Построение спектрограммы аудиофайла.""" from __future__ import annotations import argparse import re import shutil import subprocess import sys from pathlib import Path SIZE_RE = re.compile(r'^(\d{2,5})x(\d{2,5})$') def main() -> int: parser = argparse.ArgumentParser(description='Построить спектрограмму') parser.add_argument('input', type=Path, help='Аудиофайл') parser.add_argument('-o', '--out', type=Path, help='Путь к PNG') parser.add_argument('--size', default='1280x720', help='Размер, например 1280x720') parser.add_argument('--color', choices=['channel', 'intensity', 'rainbow', 'moreland', 'nebulae', 'fire', 'fiery', 'fruit', 'cool', 'magma', 'green', 'viridis', 'plasma', 'cividis', 'terrain'], default='intensity', help='Цветовая схема') parser.add_argument('--scale', choices=['lin', 'log', 'sqrt', 'cbrt', '4thrt', '5thrt'], default='log', help='Шкала частот') parser.add_argument('--force', action='store_true', help='Перезаписать PNG') args = parser.parse_args() source = args.input.expanduser().resolve() if not source.is_file(): parser.error(f'Файл не найден: {source}') match = SIZE_RE.fullmatch(args.size) if not match: parser.error('--size должен быть в формате 1280x720') width, height = int(match.group(1)), int(match.group(2)) if width < 64 or height < 64: parser.error('Размер слишком маленький') ffmpeg = shutil.which('ffmpeg') if not ffmpeg: print('ffmpeg не найден. Установите FFmpeg.', file=sys.stderr) return 1 destination = args.out.expanduser() if args.out else source.with_name(f'{source.stem}_spectrogram.png') destination = destination.resolve() destination.parent.mkdir(parents=True, exist_ok=True) if destination.exists() and not args.force: print(f'Файл уже существует: {destination}', file=sys.stderr) return 1 filter_string = ( f'showspectrumpic=s={width}x{height}:mode=combined:' f'color={args.color}:scale={args.scale}:legend=1' ) command = [ ffmpeg, '-hide_banner', '-loglevel', 'error', '-nostdin', '-i', str(source), '-lavfi', filter_string, '-frames:v', '1', '-y' if args.force else '-n', str(destination), ] result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode != 0: print(f'Ошибка: {result.stderr.strip()}', file=sys.stderr) return 2 print(f'Готово: {destination}') print(f'Размер: {width}x{height}, шкала: {args.scale}, цвет: {args.color}') return 0 if __name__ == '__main__': raise SystemExit(main())