Delete identify-speaker.py
Browse files- identify-speaker.py +0 -178
identify-speaker.py
DELETED
|
@@ -1,178 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import json
|
| 3 |
-
import pandas as pd
|
| 4 |
-
import tempfile
|
| 5 |
-
import subprocess
|
| 6 |
-
from playsound import playsound
|
| 7 |
-
from rich.console import Console
|
| 8 |
-
from rich.prompt import Prompt
|
| 9 |
-
from rich.text import Text
|
| 10 |
-
|
| 11 |
-
# Initialize Rich Console
|
| 12 |
-
console = Console()
|
| 13 |
-
console.clear()
|
| 14 |
-
|
| 15 |
-
# Title Screen
|
| 16 |
-
console.print("""[bold cyan]
|
| 17 |
-
=====================================
|
| 18 |
-
SPEAKER IDENTIFICATION TOOL
|
| 19 |
-
=====================================
|
| 20 |
-
[/bold cyan]""")
|
| 21 |
-
console.print("This tool will identify target speakers in audio files based on provided JSON metadata.")
|
| 22 |
-
console.print("Ensure the paths to JSON and audio files are correct before proceeding.\n")
|
| 23 |
-
|
| 24 |
-
# Paths
|
| 25 |
-
JSON_DIR = "NO JSON PATH ENTERED" # JSON files with all speakers
|
| 26 |
-
AUDIO_DIR = "NO WAVS PATH ENTERED" # Original WAV files
|
| 27 |
-
MAPPING_FILE = "NO MAPPINGS FILE ENTERED" # Speaker mapping CSV
|
| 28 |
-
|
| 29 |
-
# Helper Function to Validate Paths
|
| 30 |
-
def validate_path(path, path_type="directory", should_exist=True):
|
| 31 |
-
"""Validate a path and optionally create or exit on failure."""
|
| 32 |
-
if path_type == "directory":
|
| 33 |
-
if should_exist and not os.path.isdir(path):
|
| 34 |
-
console.print(f"[bold red]Error:[/bold red] {path}", style="red")
|
| 35 |
-
return False
|
| 36 |
-
elif not should_exist:
|
| 37 |
-
os.makedirs(path, exist_ok=True)
|
| 38 |
-
elif path_type == "file":
|
| 39 |
-
if should_exist and not os.path.isfile(path):
|
| 40 |
-
console.print(f"[bold yellow]Warning:[/bold yellow] File does not exist: {path}", style="yellow")
|
| 41 |
-
return False
|
| 42 |
-
return True
|
| 43 |
-
|
| 44 |
-
# Validate Paths
|
| 45 |
-
paths_valid = True
|
| 46 |
-
paths_valid &= validate_path(JSON_DIR, "directory")
|
| 47 |
-
paths_valid &= validate_path(AUDIO_DIR, "directory")
|
| 48 |
-
paths_valid &= validate_path(MAPPING_FILE, "file", should_exist=False)
|
| 49 |
-
|
| 50 |
-
if not paths_valid:
|
| 51 |
-
console.print("\n[bold red]One or more paths are invalid. Please fix the issues and restart the tool.[/bold red]", style="red")
|
| 52 |
-
exit(1)
|
| 53 |
-
|
| 54 |
-
console.print("\n[bold green]All paths validated successfully![/bold green]\n")
|
| 55 |
-
|
| 56 |
-
# Confirm Start
|
| 57 |
-
start_tool = Prompt.ask("[bold yellow]Are you ready to start identifying speakers?[/bold yellow]", choices=["y", "n"], default="y")
|
| 58 |
-
if start_tool.lower() != "y":
|
| 59 |
-
console.print("\n[bold red]Exiting tool as per user request.[/bold red]", style="red")
|
| 60 |
-
exit(0)
|
| 61 |
-
|
| 62 |
-
# Load or Initialize Mapping File
|
| 63 |
-
df = pd.DataFrame(columns=['json_file', 'target_speaker_label'])
|
| 64 |
-
if os.path.isfile(MAPPING_FILE):
|
| 65 |
-
df = pd.read_csv(MAPPING_FILE)
|
| 66 |
-
|
| 67 |
-
# Pre-validate Files
|
| 68 |
-
json_files = [f for f in os.listdir(JSON_DIR) if f.endswith(".json")]
|
| 69 |
-
valid_files = []
|
| 70 |
-
for json_file in json_files:
|
| 71 |
-
json_path = os.path.join(JSON_DIR, json_file)
|
| 72 |
-
wav_file = os.path.join(AUDIO_DIR, os.path.splitext(json_file)[0] + ".wav")
|
| 73 |
-
if not os.path.exists(json_path) or not os.path.exists(wav_file):
|
| 74 |
-
console.print(f"[bold yellow]Skipping {json_file}:[/bold yellow] Missing JSON or WAV file.", style="yellow")
|
| 75 |
-
else:
|
| 76 |
-
valid_files.append((json_file, json_path, wav_file))
|
| 77 |
-
|
| 78 |
-
# Display Initial Counts
|
| 79 |
-
console.print(f"[bold green]Found {len(valid_files)} valid file(s) to process.[/bold green]")
|
| 80 |
-
already_mapped_count = 0
|
| 81 |
-
valid_files_to_process = []
|
| 82 |
-
|
| 83 |
-
# Filter Out Already Mapped Files
|
| 84 |
-
for json_file, json_path, wav_file in valid_files:
|
| 85 |
-
if json_file in df['json_file'].values and pd.notna(df.loc[df['json_file'] == json_file, 'target_speaker_label'].values[0]):
|
| 86 |
-
already_mapped_count += 1
|
| 87 |
-
else:
|
| 88 |
-
valid_files_to_process.append((json_file, json_path, wav_file))
|
| 89 |
-
|
| 90 |
-
# Display Count of Already Mapped Files
|
| 91 |
-
if already_mapped_count > 0:
|
| 92 |
-
console.print(f"[bold blue]Skipped {already_mapped_count} already mapped file(s).[/bold blue]", style="blue")
|
| 93 |
-
|
| 94 |
-
# Process Files
|
| 95 |
-
for json_index, (json_file, json_path, wav_file) in enumerate(valid_files_to_process, start=1):
|
| 96 |
-
with open(json_path, "r") as f:
|
| 97 |
-
try:
|
| 98 |
-
segments = json.load(f)
|
| 99 |
-
except json.JSONDecodeError:
|
| 100 |
-
console.print(f"[bold red]Error:[/bold red] JSON file {json_file} is not properly formatted. Skipping.", style="red")
|
| 101 |
-
continue
|
| 102 |
-
|
| 103 |
-
if not segments:
|
| 104 |
-
console.print(f"[bold yellow]No segments found in {json_file}. Skipping.[/bold yellow]", style="yellow")
|
| 105 |
-
continue
|
| 106 |
-
|
| 107 |
-
console.print(f"Processing Episode: [bold green]{json_file}[/bold green]", style="bold blue")
|
| 108 |
-
|
| 109 |
-
unique_speakers = list(set(seg["speaker"] for seg in segments))
|
| 110 |
-
target_speaker_label = None
|
| 111 |
-
|
| 112 |
-
for speaker_index, speaker_label in enumerate(unique_speakers, start=1):
|
| 113 |
-
console.print(f"Speaker Number/Total: {speaker_index}/{len(unique_speakers)}", style="cyan")
|
| 114 |
-
|
| 115 |
-
speaker_segments = [seg for seg in segments if seg["speaker"] == speaker_label]
|
| 116 |
-
|
| 117 |
-
for segment_index, segment in enumerate(speaker_segments, start=1):
|
| 118 |
-
start_time, end_time = segment["start"], segment["end"]
|
| 119 |
-
|
| 120 |
-
if not (2.0 <= end_time - start_time <= 10.0):
|
| 121 |
-
continue
|
| 122 |
-
|
| 123 |
-
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_segment:
|
| 124 |
-
segment_path = temp_segment.name
|
| 125 |
-
cmd = [
|
| 126 |
-
"ffmpeg", "-hide_banner", "-loglevel", "error", "-y",
|
| 127 |
-
"-i", wav_file, "-ss", str(start_time), "-to", str(end_time), "-c", "copy",
|
| 128 |
-
segment_path
|
| 129 |
-
]
|
| 130 |
-
subprocess_run = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
| 131 |
-
if subprocess_run.returncode != 0:
|
| 132 |
-
console.print(f"[bold red]Error extracting segment {start_time}-{end_time} for speaker {speaker_label}.[/bold red]", style="red")
|
| 133 |
-
continue
|
| 134 |
-
|
| 135 |
-
try:
|
| 136 |
-
playsound(segment_path)
|
| 137 |
-
except Exception as e:
|
| 138 |
-
console.print(f"[bold red]Error playing segment for speaker {speaker_label}:[/bold red] {e}", style="red")
|
| 139 |
-
os.remove(segment_path)
|
| 140 |
-
continue
|
| 141 |
-
|
| 142 |
-
os.remove(segment_path)
|
| 143 |
-
|
| 144 |
-
user_input = Prompt.ask(f"Is this the target speaker? [Y]es, [N]o, [T]ry Another Segment")
|
| 145 |
-
|
| 146 |
-
if user_input.lower() == "y":
|
| 147 |
-
target_speaker_label = speaker_label
|
| 148 |
-
break
|
| 149 |
-
elif user_input.lower() == "n":
|
| 150 |
-
console.print("[bold magenta]Skipping this speaker and moving to the next one immediately.[/bold magenta]", style="magenta")
|
| 151 |
-
break
|
| 152 |
-
elif user_input.lower() == "t":
|
| 153 |
-
console.print("[bold cyan]Trying another segment for the same speaker.[/bold cyan]", style="cyan")
|
| 154 |
-
continue
|
| 155 |
-
|
| 156 |
-
if target_speaker_label:
|
| 157 |
-
break
|
| 158 |
-
|
| 159 |
-
if target_speaker_label:
|
| 160 |
-
df = pd.concat([df, pd.DataFrame({"json_file": [json_file], "target_speaker_label": [target_speaker_label]})], ignore_index=True)
|
| 161 |
-
console.print(f"[bold green]Mapped {json_file} to speaker {target_speaker_label}.[/bold green]", style="green")
|
| 162 |
-
else:
|
| 163 |
-
df = pd.concat([df, pd.DataFrame({"json_file": [json_file], "target_speaker_label": ["not-target-speaker"]})], ignore_index=True)
|
| 164 |
-
console.print(f"[bold yellow]No target speaker identified for {json_file}.[/bold yellow]", style="yellow")
|
| 165 |
-
|
| 166 |
-
console.print(f"[bold blue]Processed entries: {json_index}/{len(valid_files_to_process)}[/bold blue]", style="blue")
|
| 167 |
-
console.print(f"[bold blue]Unprocessed remaining: {len(valid_files_to_process) - json_index}[/bold blue]", style="blue")
|
| 168 |
-
|
| 169 |
-
df.to_csv(MAPPING_FILE, index=False)
|
| 170 |
-
console.print(f"[bold cyan]Mapping saved to {MAPPING_FILE}.[/bold cyan]", style="cyan")
|
| 171 |
-
|
| 172 |
-
# Ask user whether to process the next episode
|
| 173 |
-
continue_processing = Prompt.ask("[bold yellow]Do you want to process the next episode? Default: yes[/bold yellow]", choices=["y", "n"], default="y")
|
| 174 |
-
if continue_processing.lower() != "y":
|
| 175 |
-
console.print("[bold red]Stopping processing as per user request.[/bold red]", style="red")
|
| 176 |
-
break
|
| 177 |
-
|
| 178 |
-
console.print("[bold green]Processing complete.[/bold green]")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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