ScottishHaze commited on
Commit
c8d2fec
·
verified ·
1 Parent(s): 397abc1

Delete isolate-trim.py

Browse files
Files changed (1) hide show
  1. isolate-trim.py +0 -144
isolate-trim.py DELETED
@@ -1,144 +0,0 @@
1
- import os
2
- import json
3
- import subprocess
4
- import pandas as pd
5
- from rich.console import Console
6
- from rich.prompt import Prompt
7
-
8
- # Initialize Rich Console
9
- console = Console()
10
- console.clear()
11
-
12
- # Title Screen
13
- console.print("""[bold cyan]
14
- =====================================
15
- SPEAKER ISOLATION TOOL
16
- =====================================
17
- [/bold cyan]""")
18
- console.print("This tool isolates and trims audio segments based on speaker metadata.")
19
- console.print("Input directories for WAV and JSON files, and an output directory, will be created in the same folder as this script.")
20
-
21
- # Define Paths Relative to Script Location
22
- SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
23
- JSON_DIR = os.path.join(SCRIPT_DIR, "jsons")
24
- AUDIO_DIR = os.path.join(SCRIPT_DIR, "wavs")
25
- OUTPUT_DIR = os.path.join(SCRIPT_DIR, "targeted")
26
-
27
- # Ensure Directories Exist
28
- os.makedirs(JSON_DIR, exist_ok=True)
29
- os.makedirs(AUDIO_DIR, exist_ok=True)
30
- os.makedirs(OUTPUT_DIR, exist_ok=True)
31
-
32
- # Pause to allow user to populate directories
33
- console.print(f"[bold yellow]Please add JSON metadata files to: {JSON_DIR}[/bold yellow]")
34
- console.print(f"[bold yellow]Please add corresponding WAV audio files to: {AUDIO_DIR}[/bold yellow]")
35
- input("\nPress Enter to continue...")
36
-
37
- # Load and Validate Files
38
- json_files = [f for f in os.listdir(JSON_DIR) if f.endswith(".json")]
39
- audio_files = [f for f in os.listdir(AUDIO_DIR) if f.endswith(".wav")]
40
-
41
- if not json_files:
42
- console.print(f"[bold red]Error:[/bold red] No JSON files found in: {JSON_DIR}", style="red")
43
- exit(1)
44
- if not audio_files:
45
- console.print(f"[bold red]Error:[/bold red] No WAV files found in: {AUDIO_DIR}", style="red")
46
- exit(1)
47
-
48
- console.print(f"[bold green]Found {len(json_files)} JSON file(s) and {len(audio_files)} WAV file(s). Starting processing...[/bold green]")
49
-
50
- # Maximum length for trimmed clips (in seconds)
51
- MAX_CLIP_LENGTH = 30
52
-
53
- def crop_and_trim_silence(input_file, output_prefix, max_length):
54
- """Crops audio to chunks of max_length seconds and trims silence."""
55
- # Step 1: Get the duration of the input audio
56
- probe_cmd = [
57
- "ffprobe", "-i", input_file, "-show_entries", "format=duration",
58
- "-v", "error", "-of", "csv=p=0"
59
- ]
60
- result = subprocess.run(probe_cmd, stdout=subprocess.PIPE, text=True)
61
- duration = float(result.stdout.strip())
62
-
63
- # Step 2: Split into chunks of max_length seconds
64
- start_time = 0
65
- chunk_index = 1
66
- while start_time < duration:
67
- end_time = min(start_time + max_length, duration)
68
- chunk_output = f"{output_prefix}_chunk{chunk_index:02d}_raw.wav"
69
-
70
- # Crop the audio to the current chunk
71
- crop_cmd = [
72
- "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
73
- "-i", input_file, "-ss", str(start_time), "-to", str(end_time),
74
- "-c", "copy", chunk_output
75
- ]
76
- subprocess.run(crop_cmd)
77
-
78
- # Step 3: Trim silence from the cropped chunk
79
- trimmed_output = f"{output_prefix}_chunk{chunk_index:02d}.wav"
80
- trim_cmd = [
81
- "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
82
- "-i", chunk_output,
83
- "-af", "silenceremove=start_periods=1:start_duration=0.5:start_threshold=-30dB:stop_periods=1:stop_duration=0.5:stop_threshold=-30dB",
84
- trimmed_output
85
- ]
86
- subprocess.run(trim_cmd)
87
-
88
- console.print(f"[green]Processed chunk:[/green] {trimmed_output}")
89
-
90
- # Cleanup the raw chunk
91
- os.remove(chunk_output)
92
- start_time += max_length
93
- chunk_index += 1
94
-
95
- # Process Each File
96
- for json_file in json_files:
97
- json_path = os.path.join(JSON_DIR, json_file)
98
- wav_file = os.path.join(AUDIO_DIR, os.path.splitext(json_file)[0] + ".wav")
99
-
100
- if not os.path.exists(wav_file):
101
- console.print(f"[bold red]Error:[/bold red] Corresponding WAV file not found for {json_file}", style="red")
102
- continue
103
-
104
- # Load JSON segments
105
- with open(json_path, "r") as f:
106
- try:
107
- segments = json.load(f)
108
- except json.JSONDecodeError:
109
- console.print(f"[bold red]Error:[/bold red] JSON file {json_file} is not properly formatted. Skipping.", style="red")
110
- continue
111
-
112
- # Process each segment
113
- for segment in segments:
114
- speaker = segment.get("speaker")
115
- start_time = segment.get("start")
116
- end_time = segment.get("end")
117
-
118
- if not (speaker and start_time is not None and end_time is not None):
119
- console.print(f"[bold yellow]Skipping invalid segment in {json_file}: {segment}[/bold yellow]", style="yellow")
120
- continue
121
-
122
- if end_time - start_time < 1.0:
123
- console.print(f"[bold yellow]Skipping short segment ({start_time}-{end_time}) for speaker {speaker}.[/bold yellow]", style="yellow")
124
- continue
125
-
126
- output_prefix = os.path.join(OUTPUT_DIR, f"{os.path.splitext(json_file)[0]}_{speaker}_{start_time:.2f}-{end_time:.2f}")
127
-
128
- # Extract the segment
129
- temp_segment = f"{output_prefix}_raw.wav"
130
- extract_cmd = [
131
- "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
132
- "-i", wav_file, "-ss", str(start_time), "-to", str(end_time),
133
- "-c", "copy", temp_segment
134
- ]
135
- subprocess.run(extract_cmd)
136
-
137
- # Crop and trim silence
138
- crop_and_trim_silence(temp_segment, output_prefix, MAX_CLIP_LENGTH)
139
-
140
- # Cleanup the raw segment
141
- os.remove(temp_segment)
142
-
143
- console.print("[bold green]All files processed. Check the output directory for results.[/bold green]")
144
-