ScottishHaze commited on
Commit
38ef1a1
·
verified ·
1 Parent(s): 6f53430

Upload 4 files

Browse files

Code Rebase, clean up - no changes functionality, just under-hood stuff

Files changed (4) hide show
  1. dataset-creation.py +52 -0
  2. diarize-dataset.py +66 -0
  3. identify-speaker.py +122 -0
  4. isolate-trim.py +130 -0
dataset-creation.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ from rich.console import Console
4
+ from rich.prompt import Prompt
5
+ from rich.table import Table
6
+
7
+ # Initialize Rich Console
8
+ console = Console()
9
+
10
+ # Prompt user for input and output directories
11
+ INPUT_DIR = Prompt.ask("[bold cyan]Enter the input directory for video files[/bold cyan]", default="PATH-TO-VIDEOS")
12
+ OUTPUT_DIR = Prompt.ask("[bold cyan]Enter the output directory for extracted audio[/bold cyan]", default="SAVE-PATH-OF-WAVS")
13
+
14
+ # Ensure directories exist
15
+ if not os.path.isdir(INPUT_DIR):
16
+ console.print(f"[bold red]Error:[/bold red] Input directory does not exist: {INPUT_DIR}", style="red")
17
+ exit(1)
18
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
19
+
20
+ # Process video files
21
+ video_files = [f for f in sorted(os.listdir(INPUT_DIR)) if f.endswith((".mkv", ".mp4"))]
22
+ if not video_files:
23
+ console.print(f"[bold red]Error:[/bold red] No video files found in: {INPUT_DIR}", style="red")
24
+ exit(1)
25
+
26
+ console.print(f"[bold green]Found {len(video_files)} video file(s). Starting processing...[/bold green]")
27
+ for index, file_name in enumerate(video_files, start=1):
28
+ input_path = os.path.join(INPUT_DIR, file_name)
29
+ output_file = os.path.join(OUTPUT_DIR, f"{index:04d}_eng.wav")
30
+
31
+ # Construct ffmpeg command
32
+ ffmpeg_command = [
33
+ "ffmpeg",
34
+ "-i", input_path,
35
+ "-map", "0:m:language:eng",
36
+ "-vn",
37
+ "-acodec", "pcm_s16le",
38
+ "-ar", "16000",
39
+ "-ac", "1",
40
+ output_file
41
+ ]
42
+
43
+ console.print(f"Processing: {file_name} ({index}/{len(video_files)})")
44
+
45
+ # Execute the ffmpeg command
46
+ try:
47
+ subprocess.run(ffmpeg_command, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
48
+ console.print(f"[bold green]Success:[/bold green] Extracted audio to: {output_file}", style="green")
49
+ except subprocess.CalledProcessError as e:
50
+ console.print(f"[bold red]Error processing {file_name}:[/bold red] {e}", style="red")
51
+
52
+ console.print("[bold green]All files processed successfully.[/bold green]")
diarize-dataset.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from rich.console import Console
4
+ from rich.prompt import Prompt
5
+ from pyannote.audio import Pipeline
6
+
7
+ # Initialize Rich Console
8
+ console = Console()
9
+
10
+ # Prompt user for configuration
11
+ HF_TOKEN = Prompt.ask("[bold cyan]Enter your Hugging Face token[/bold cyan]", default="HF-TOKEN-HERE")
12
+ INPUT_DIR = Prompt.ask("[bold cyan]Enter the input directory for WAV files[/bold cyan]", default="WAVS-PATH")
13
+ OUTPUT_DIR = Prompt.ask("[bold cyan]Enter the output directory for diarization JSON files[/bold cyan]", default="JSONS-PATH")
14
+
15
+ # Validate configuration
16
+ if not HF_TOKEN or not HF_TOKEN.startswith("hf_"):
17
+ console.print("[bold red]Error:[/bold red] Invalid Hugging Face token.", style="red")
18
+ exit(1)
19
+ if not os.path.isdir(INPUT_DIR):
20
+ console.print(f"[bold red]Error:[/bold red] Input directory does not exist: {INPUT_DIR}", style="red")
21
+ exit(1)
22
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
23
+
24
+ # Load the speaker diarization pipeline
25
+ console.print("[bold cyan]Loading speaker diarization pipeline...[/bold cyan]")
26
+ try:
27
+ pipeline = Pipeline.from_pretrained("pyannote/speaker-diarization", use_auth_token=HF_TOKEN)
28
+ console.print("[bold green]Pipeline loaded successfully.[/bold green]")
29
+ except Exception as e:
30
+ console.print(f"[bold red]Error loading pipeline:[/bold red] {e}", style="red")
31
+ exit(1)
32
+
33
+ # Process WAV files
34
+ wav_files = [f for f in os.listdir(INPUT_DIR) if f.endswith(".wav")]
35
+ if not wav_files:
36
+ console.print(f"[bold red]Error:[/bold red] No WAV files found in: {INPUT_DIR}", style="red")
37
+ exit(1)
38
+
39
+ console.print(f"[bold green]Found {len(wav_files)} WAV file(s). Starting processing...[/bold green]")
40
+ for i, file_name in enumerate(wav_files, start=1):
41
+ console.print(f"[bold blue][{i}/{len(wav_files)}] Processing {file_name}...[/bold blue]")
42
+ file_path = os.path.join(INPUT_DIR, file_name)
43
+
44
+ try:
45
+ diarization = pipeline(file_path)
46
+ except Exception as e:
47
+ console.print(f"[bold red]Error processing {file_name}:[/bold red] {e}", style="red")
48
+ continue
49
+
50
+ # Extract and save speaker segments
51
+ data = [
52
+ {
53
+ "speaker": speaker,
54
+ "start": turn.start,
55
+ "end": turn.end
56
+ }
57
+ for turn, _, speaker in diarization.itertracks(yield_label=True)
58
+ ]
59
+
60
+ output_path = os.path.join(OUTPUT_DIR, f"{os.path.splitext(file_name)[0]}.json")
61
+ with open(output_path, "w") as f:
62
+ json.dump(data, f, indent=2)
63
+
64
+ console.print(f"[bold green]Finished processing {file_name}. Results saved to {output_path}.[/bold green]")
65
+
66
+ console.print("[bold green]All files processed successfully.[/bold green]")
identify-speaker.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import pandas as pd
4
+ import tempfile
5
+ import subprocess
6
+ from datetime import datetime
7
+ from playsound import playsound
8
+ from rich.console import Console
9
+ from rich.prompt import Prompt
10
+
11
+ # Initialize Rich Console
12
+ console = Console()
13
+
14
+ # Paths
15
+ JSON_DIR = "JSON-PATH" # JSON files with all speakers
16
+ AUDIO_DIR = "WAVS-PATH" # Original WAV files
17
+ MAPPING_FILE = "PATH-TO-speaker_mapping.csv" # Speaker mapping CSV
18
+
19
+ # Validate paths
20
+ if not os.path.isdir(JSON_DIR):
21
+ console.print(f"[bold red]Error:[/bold red] JSON directory does not exist: {JSON_DIR}", style="red")
22
+ exit(1)
23
+ if not os.path.isdir(AUDIO_DIR):
24
+ console.print(f"[bold red]Error:[/bold red] Audio directory does not exist: {AUDIO_DIR}", style="red")
25
+ exit(1)
26
+ if not os.path.isfile(MAPPING_FILE):
27
+ console.print(f"[bold yellow]Warning:[/bold yellow] Mapping file does not exist. A new file will be created: {MAPPING_FILE}", style="yellow")
28
+ df = pd.DataFrame(columns=['json_file', 'target_speaker_label'])
29
+ else:
30
+ df = pd.read_csv(MAPPING_FILE)
31
+
32
+ # Pre-validate files
33
+ json_files = [f for f in os.listdir(JSON_DIR) if f.endswith(".json")]
34
+ valid_files = []
35
+ for json_file in json_files:
36
+ json_path = os.path.join(JSON_DIR, json_file)
37
+ wav_file = os.path.join(AUDIO_DIR, os.path.splitext(json_file)[0] + ".wav")
38
+ if not os.path.exists(json_path) or not os.path.exists(wav_file):
39
+ console.print(f"[bold yellow]Skipping {json_file}:[/bold yellow] Missing JSON or WAV file.", style="yellow")
40
+ else:
41
+ valid_files.append((json_file, json_path, wav_file))
42
+
43
+ console.print(f"[bold green]Found {len(valid_files)} valid file(s) to process.[/bold green]")
44
+
45
+ # Process files
46
+ for json_file, json_path, wav_file in valid_files:
47
+ if json_file in df['json_file'].values and pd.notna(df.loc[df['json_file'] == json_file, 'target_speaker_label'].values[0]):
48
+ console.print(f"[bold blue]Skipping {json_file}:[/bold blue] Already mapped.", style="blue")
49
+ continue
50
+
51
+ with open(json_path, "r") as f:
52
+ try:
53
+ segments = json.load(f)
54
+ except json.JSONDecodeError:
55
+ console.print(f"[bold red]Error:[/bold red] JSON file {json_file} is not properly formatted. Skipping.", style="red")
56
+ continue
57
+
58
+ if not segments:
59
+ console.print(f"[bold yellow]No segments found in {json_file}. Skipping.[/bold yellow]", style="yellow")
60
+ continue
61
+
62
+ console.rule(f"Processing Episode: [bold green]{json_file}[/bold green]", style="bold blue")
63
+
64
+ unique_speakers = list(set(seg["speaker"] for seg in segments))
65
+ target_speaker_label = None
66
+
67
+ for speaker_label in unique_speakers:
68
+ speaker_segments = [seg for seg in segments if seg["speaker"] == speaker_label]
69
+
70
+ for segment in speaker_segments:
71
+ start_time, end_time = segment["start"], segment["end"]
72
+
73
+ if end_time - start_time < 1.0:
74
+ console.print(f"[bold yellow]Skipping short segment {start_time}-{end_time} for speaker {speaker_label}.[/bold yellow]", style="yellow")
75
+ continue
76
+
77
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_segment:
78
+ segment_path = temp_segment.name
79
+ cmd = [
80
+ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
81
+ "-i", wav_file, "-ss", str(start_time), "-to", str(end_time), "-c", "copy",
82
+ segment_path
83
+ ]
84
+ subprocess_run = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
85
+ if subprocess_run.returncode != 0:
86
+ console.print(f"[bold red]Error extracting segment {start_time}-{end_time} for speaker {speaker_label}.[/bold red]", style="red")
87
+ continue
88
+
89
+ try:
90
+ playsound(segment_path)
91
+ except Exception as e:
92
+ console.print(f"[bold red]Error playing segment for speaker {speaker_label}:[/bold red] {e}", style="red")
93
+ os.remove(segment_path)
94
+ continue
95
+
96
+ os.remove(segment_path)
97
+ user_input = Prompt.ask(
98
+ f"Speaker: [bold yellow]{speaker_label}[/bold yellow]. Is this the target speaker? [Y]es/[N]o/[S]kip remaining",
99
+ choices=["y", "n", "s"]
100
+ )
101
+
102
+ if user_input == "y":
103
+ target_speaker_label = speaker_label
104
+ break
105
+ elif user_input == "s":
106
+ break
107
+
108
+ if target_speaker_label or user_input == "s":
109
+ break
110
+
111
+ if target_speaker_label:
112
+ df = pd.concat([df, pd.DataFrame({"json_file": [json_file], "target_speaker_label": [target_speaker_label]})], ignore_index=True)
113
+ console.print(f"[bold green]Mapped {json_file} to speaker {target_speaker_label}.[/bold green]", style="green")
114
+ else:
115
+ df = pd.concat([df, pd.DataFrame({"json_file": [json_file], "target_speaker_label": ["not-target-speaker"]})], ignore_index=True)
116
+ console.print(f"[bold yellow]No target speaker identified for {json_file}.[/bold yellow]", style="yellow")
117
+
118
+ df.to_csv(MAPPING_FILE, index=False)
119
+ console.print(f"[bold cyan]Mapping saved to {MAPPING_FILE}.[/bold cyan]", style="cyan")
120
+
121
+ console.print("[bold green]Processing complete.[/bold green]")
122
+
isolate-trim.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import subprocess
4
+ import pandas as pd
5
+ from rich.console import Console
6
+
7
+ # Initialize Rich Console
8
+ console = Console()
9
+
10
+ # Paths
11
+ JSON_DIR = "JSON-PATH" # JSON files with speaker data
12
+ AUDIO_DIR = "WAVS-PATH" # Original WAV files
13
+ MAPPING_FILE = "PATH-TO-speaker_mapping.csv" # Mapping CSV
14
+ OUTPUT_DIR = "SAVE-PATH-TARGETED-SPEAKER-WAVS" # Directory for extracted speaker WAVs
15
+
16
+ # Ensure output directory exists
17
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
18
+
19
+ # Load the speaker mapping file
20
+ if not os.path.exists(MAPPING_FILE):
21
+ console.print(f"[bold red]Mapping file not found:[/bold red] {MAPPING_FILE}")
22
+ exit(1)
23
+
24
+ df = pd.read_csv(MAPPING_FILE)
25
+
26
+ # Maximum length for trimmed clips (in seconds)
27
+ MAX_CLIP_LENGTH = 30
28
+
29
+ def crop_and_trim_silence(input_file, output_prefix, max_length):
30
+ """
31
+ Crops the audio to chunks of max_length seconds, then trims silence.
32
+ """
33
+ # Step 1: Get the duration of the input audio
34
+ probe_cmd = [
35
+ "ffprobe", "-i", input_file, "-show_entries", "format=duration",
36
+ "-v", "error", "-of", "csv=p=0"
37
+ ]
38
+ result = subprocess.run(probe_cmd, stdout=subprocess.PIPE, text=True)
39
+ duration = float(result.stdout.strip())
40
+
41
+ # Step 2: Split into chunks of max_length seconds
42
+ start_time = 0
43
+ chunk_index = 1
44
+ while start_time < duration:
45
+ end_time = min(start_time + max_length, duration)
46
+ chunk_output = f"{output_prefix}_chunk{chunk_index:02d}_raw.wav"
47
+
48
+ # Crop the audio to the current chunk
49
+ crop_cmd = [
50
+ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
51
+ "-i", input_file, "-ss", str(start_time), "-to", str(end_time),
52
+ "-c", "copy", chunk_output
53
+ ]
54
+ subprocess.run(crop_cmd)
55
+
56
+ # Step 3: Trim silence from the cropped chunk
57
+ trimmed_output = f"{output_prefix}_chunk{chunk_index:02d}.wav"
58
+ trim_cmd = [
59
+ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
60
+ "-i", chunk_output,
61
+ "-af", "silenceremove=start_periods=1:start_duration=0.5:start_threshold=-30dB:"
62
+ "stop_periods=1:stop_duration=0.5:stop_threshold=-30dB",
63
+ trimmed_output
64
+ ]
65
+ subprocess.run(trim_cmd)
66
+
67
+ console.print(f"[green]Processed chunk:[/green] {trimmed_output}")
68
+
69
+ # Cleanup the raw chunk
70
+ os.remove(chunk_output)
71
+ start_time += max_length
72
+ chunk_index += 1
73
+
74
+ # Process each file in the mapping
75
+ for _, row in df.iterrows():
76
+ json_file = row['json_file']
77
+ target_speaker_label = row['target_speaker_label']
78
+
79
+ # Skip files without a valid target speaker
80
+ if target_speaker_label == "not-target-speaker" or pd.isna(target_speaker_label):
81
+ console.print(f"[yellow]Skipping {json_file}:[/yellow] No target speaker identified.")
82
+ continue
83
+
84
+ # Paths
85
+ json_path = os.path.join(JSON_DIR, json_file)
86
+ wav_file = os.path.join(AUDIO_DIR, os.path.splitext(json_file)[0] + ".wav")
87
+
88
+ if not os.path.exists(json_path) or not os.path.exists(wav_file):
89
+ console.print(f"[red]Missing JSON or WAV file for {json_file}, skipping.[/red]")
90
+ continue
91
+
92
+ # Load JSON segments
93
+ with open(json_path, "r") as f:
94
+ segments = json.load(f)
95
+
96
+ # Process only segments for the target speaker
97
+ for segment in segments:
98
+ if segment["speaker"] != target_speaker_label:
99
+ continue
100
+
101
+ start_time = segment["start"]
102
+ end_time = segment["end"]
103
+
104
+ # Skip short segments
105
+ if end_time - start_time < 1.0:
106
+ console.print(f"[yellow]Skipping short segment {start_time}-{end_time} for {target_speaker_label}.[/yellow]")
107
+ continue
108
+
109
+ # Output file prefix
110
+ output_prefix = os.path.join(
111
+ OUTPUT_DIR,
112
+ f"{os.path.splitext(json_file)[0]}_{start_time:.2f}-{end_time:.2f}"
113
+ )
114
+
115
+ # Extract the segment
116
+ temp_segment = f"{output_prefix}_raw.wav"
117
+ extract_cmd = [
118
+ "ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
119
+ "-i", wav_file, "-ss", str(start_time), "-to", str(end_time),
120
+ "-c", "copy", temp_segment
121
+ ]
122
+ subprocess.run(extract_cmd)
123
+
124
+ # Crop and trim silence
125
+ crop_and_trim_silence(temp_segment, output_prefix, MAX_CLIP_LENGTH)
126
+
127
+ # Cleanup the raw segment
128
+ os.remove(temp_segment)
129
+
130
+ console.print("[bold green]All files processed. Check the output directory for results.[/bold green]")