#!/usr/bin/env python3 """Базовая очистка голосовой записи через ffmpeg.""" from __future__ import annotations import argparse import shutil import subprocess import sys from pathlib import Path AUDIO_EXTENSIONS = {'.wav', '.mp3', '.m4a', '.flac', '.ogg', '.aac', '.opus'} def collect(paths: list[Path], recursive: bool) -> list[Path]: files: list[Path] = [] for path in paths: if path.is_dir(): iterator = path.rglob('*') if recursive else path.glob('*') files.extend( item for item in iterator if item.is_file() and item.suffix.lower() in AUDIO_EXTENSIONS ) elif path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS: files.append(path) else: print(f'Пропуск: {path}', file=sys.stderr) return sorted(set(files), key=lambda item: str(item).lower()) def codec_args(suffix: str) -> list[str]: suffix = suffix.lower() if suffix == '.mp3': return ['-c:a', 'libmp3lame', '-b:a', '192k'] if suffix in {'.m4a', '.aac'}: return ['-c:a', 'aac', '-b:a', '192k'] if suffix == '.flac': return ['-c:a', 'flac'] if suffix == '.ogg': return ['-c:a', 'libvorbis', '-q:a', '5'] if suffix == '.opus': return ['-c:a', 'libopus', '-b:a', '96k'] return ['-c:a', 'pcm_s16le'] def main() -> int: parser = argparse.ArgumentParser(description='Очистить голосовую запись') parser.add_argument('inputs', nargs='+', type=Path, help='Файлы или папки') parser.add_argument('-o', '--out', type=Path, default=Path('clean_voice'), help='Папка для результата') parser.add_argument('--preset', choices=['light', 'strong'], default='light', help='Сила обработки') parser.add_argument('--recursive', action='store_true', help='Обходить вложенные папки') parser.add_argument('--overwrite', action='store_true', help='Перезаписать существующие файлы') args = parser.parse_args() if args.preset == 'strong': filters = 'highpass=f=90,lowpass=f=11000,afftdn=nr=20:nf=-30,dynaudnorm=f=200:g=15:p=0.95' else: filters = 'highpass=f=80,lowpass=f=12000,afftdn=nr=10:nf=-25,dynaudnorm=f=150:g=12:p=0.9' ffmpeg = shutil.which('ffmpeg') if not ffmpeg: print('ffmpeg не найден. Установите FFmpeg.', file=sys.stderr) return 1 files = collect([path.expanduser() for path in args.inputs], args.recursive) if not files: print('Аудиофайлы не найдены.', file=sys.stderr) return 1 out_dir = args.out.expanduser().resolve() out_dir.mkdir(parents=True, exist_ok=True) done = skipped = failed = 0 for source in files: destination = out_dir / f'{source.stem}_clean{source.suffix}' if destination.exists() and not args.overwrite: print(f'Пропуск: {destination}') skipped += 1 continue command = [ ffmpeg, '-hide_banner', '-loglevel', 'error', '-nostdin', '-i', str(source), '-af', filters, '-map', '0:a', '-map_metadata', '0', ] command += codec_args(source.suffix) command += ['-y' if args.overwrite else '-n', str(destination)] result = subprocess.run(command, capture_output=True, text=True, check=False) if result.returncode == 0: print(f'Готово: {source.name} -> {destination.name}') done += 1 else: print(f'Ошибка: {source}: {result.stderr.strip()}', file=sys.stderr) failed += 1 print(f'Итог: готово {done}, пропущено {skipped}, ошибок {failed}') return 0 if failed == 0 else 2 if __name__ == '__main__': raise SystemExit(main())