dac202 commited on
Commit
ad16150
·
1 Parent(s): 0a56a05

initial commit

Browse files
app.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+ import whisper_timestamped as whisper_t
5
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline
6
+ from transformers import WhisperForConditionalGeneration
7
+ from peft import PeftModel
8
+ import time
9
+ import re
10
+ import html
11
+ import json
12
+ import shutil
13
+ from fsp import analyze_audio, apply_censoring, default_curse_words, seconds_to_minutes
14
+ from datetime import datetime
15
+
16
+ # MODIFIED: Print start time and filename
17
+ print(f"Executing {os.path.basename(__file__)} at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
18
+
19
+ ################ Load models
20
+
21
+ ## 1. Toxicity filter. Using the base version
22
+ print('Loading toxicity classifier...')
23
+ tox_model = "cardiffnlp/twitter-roberta-large-sensitive-multilabel"
24
+
25
+ tox_tokenizer = AutoTokenizer.from_pretrained(tox_model)
26
+ tox_model = AutoModelForSequenceClassification.from_pretrained(tox_model)
27
+
28
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
29
+
30
+ tox_model.to(device)
31
+ tox_pipe = pipeline("text-classification", model=tox_model, tokenizer=tox_tokenizer, device=device, top_k=2)
32
+
33
+ ## 2. Create our Whisper model from the LoRA weights
34
+ ## Whisper_timestamped requires the entire model to be saved, this saves static storage space by only saving the lora config
35
+ def load_whisper_model(model_path, lora_config, base_model_name="openai/whisper-medium.en"):
36
+ if os.path.exists('./whisper-medium-ft/model.safetensors'):
37
+ print(f'Fine tuned model at {model_path} already exists')
38
+ return
39
+
40
+ print(f'Fine-tuned model not found. Creating model from LoRA configuration at {lora_config}')
41
+ model = WhisperForConditionalGeneration.from_pretrained(base_model_name)
42
+
43
+ model = PeftModel.from_pretrained(model, lora_config)
44
+
45
+ mdoel = model.merge_and_unload()
46
+ model.save_pretrained(model_path)
47
+
48
+ print(f'Whisper model from {lora_config} saved at {model_path}')
49
+ return
50
+
51
+ # Where fsp.py expects to find our fine-tuned model
52
+ model_path = 'whisper-medium-ft'
53
+ lora_config = './lora_config'
54
+
55
+ # Uncheck when uploaded to hf
56
+ load_whisper_model(model_path=model_path, lora_config=lora_config)
57
+
58
+ ###### Helper functions #######
59
+
60
+ def format_metadata_header(filename, metadata, explicit_word_count):
61
+ title, artist, album, year = metadata.get('title', 'N/A'), metadata.get('artist', 'N/A'), metadata.get('album', 'N/A'), metadata.get('year', 'N/A')
62
+ genius_url, wer_score = metadata.get('genius_url'), metadata.get('wer_score')
63
+ genius_link = f"|| **[View lyrics on Genius]({genius_url})**" if genius_url else ""
64
+ wer_display = f"| similarity score = {wer_score} (lower is better)" if wer_score and genius_url else ""
65
+
66
+ status_message = ""
67
+ if explicit_word_count == 0:
68
+ status_message = "\n\n**✅ No explicit content found in this track.**"
69
+
70
+ return f"### Details for: *{filename}*\n**Artist:** {artist} | **Song:** {title} | **Album:** {album} ({year}) {genius_link} {wer_display}{status_message}"
71
+
72
+ def generate_static_transcript(transcript_data, initial_times):
73
+ initial_times_set = {f"{t['start']}-{t['end']}" for t in initial_times}
74
+ table_header = "<table><thead><tr><th style='width: 125px;'>Time</th><th>Line transcript</th><th>Explicit flag(s)</th></tr></thead><tbody>"
75
+ table_rows = []
76
+
77
+ all_lines = [" ".join([word['text'] for word in segment.get('line_words', [])]) for segment in transcript_data]
78
+
79
+ explicit_results = []
80
+ if all_lines:
81
+ pipeline_outputs = tox_pipe(all_lines)
82
+
83
+ for line_result in pipeline_outputs:
84
+ flags = []
85
+
86
+ for d in line_result:
87
+ label = d['label']
88
+ score = d['score']
89
+
90
+ if score < 0.5: continue
91
+ elif label == 'confilctual' or label == 'selfharm': flags.append('violence')
92
+ elif label == 'profanity': flags.append('curse')
93
+ elif label == 'drugs': flags.append('drugs')
94
+ elif label == 'sex': flags.append('sex')
95
+
96
+ explicit_results.append(flags)
97
+
98
+ for i, segment in enumerate(transcript_data):
99
+ start_time_str, end_time_str = seconds_to_minutes(segment.get('start')), seconds_to_minutes(segment.get('end'))
100
+
101
+ explicit_flag = ""
102
+
103
+ if explicit_results:
104
+ for flags in explicit_results[i]:
105
+ if 'violence' in flags: explicit_flag += '💥'
106
+ if 'curse' in flags: explicit_flag += '🤬'
107
+ if 'drugs' in flags: explicit_flag += '🚬'
108
+ if 'sex' in flags: explicit_flag += '🔞'
109
+
110
+ words_in_line = segment.get('line_words', [])
111
+ formatted_words = []
112
+
113
+ for word in words_in_line:
114
+ word_id = f"{word['start']}-{word['end']}"
115
+
116
+ if word_id in initial_times_set:
117
+ formatted_words.append(f"<s>{html.escape(word['text'])}</s>")
118
+
119
+ else:
120
+ formatted_words.append(html.escape(word["text"]))
121
+
122
+ formatted_line = " ".join(formatted_words)
123
+ table_rows.append(f"<tr><td>{start_time_str} - {end_time_str}</td><td>{formatted_line}</td><td style='text-align:center'>{explicit_flag}</td></tr>")
124
+
125
+ return table_header + "".join(table_rows) + "</tbody></table>"
126
+
127
+ def handle_batch_analysis(files, progress=gr.Progress()):
128
+ if not files:
129
+ raise gr.Error("Please upload one or more audio files.")
130
+
131
+ yield gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), None, None, None, None, None
132
+
133
+ try:
134
+ model, fine_tuned = (whisper_t.load_model(model_path, device=device), True)
135
+ except Exception as e:
136
+ raise gr.Error(f"Error loading fine-tuned Whisper model: {e}")
137
+
138
+ all_results = {}
139
+ num_files = len(files)
140
+ for i, audio_file in enumerate(files):
141
+ progress((i + 1) / num_files, desc=f"Analyzing File {i + 1} of {num_files}")
142
+ filename = os.path.basename(audio_file.name)
143
+ analysis_state = analyze_audio(audio_file.name, model, device, fine_tuned, progress=None)
144
+ all_results[filename] = analysis_state
145
+ # MODIFIED: Print filename to console after transcription
146
+ print(f"Transcription complete for: {filename}")
147
+
148
+ file_list = list(all_results.keys())
149
+ first_file_results = all_results[file_list[0]]
150
+ explicit_count_first_file = len(first_file_results['initial_explicit_times'])
151
+ header = format_metadata_header(file_list[0], first_file_results['metadata'], explicit_count_first_file)
152
+ transcript_html = generate_static_transcript(first_file_results['transcript'], first_file_results['initial_explicit_times'])
153
+
154
+ # Check if ANY file has explicit content to determine if the apply button should be active
155
+ any_explicit_content = any(len(res['initial_explicit_times']) > 0 for res in all_results.values())
156
+ if any_explicit_content:
157
+ apply_button_update = gr.update(interactive=True, value="Apply all edits")
158
+ else:
159
+ apply_button_update = gr.update(interactive=False, value="No edits to make")
160
+
161
+ yield (
162
+ gr.update(visible=False),
163
+ gr.update(visible=True),
164
+ gr.update(visible=False),
165
+ all_results,
166
+ gr.update(choices=file_list, value=file_list[0]),
167
+ header,
168
+ transcript_html,
169
+ apply_button_update
170
+ )
171
+
172
+ def update_details_view(selected_filename, all_results):
173
+ if not selected_filename or not all_results:
174
+ return "", ""
175
+
176
+ file_results = all_results[selected_filename]
177
+ explicit_word_count = len(file_results['initial_explicit_times'])
178
+ header = format_metadata_header(selected_filename, file_results['metadata'], explicit_word_count)
179
+ transcript_html = generate_static_transcript(file_results['transcript'], file_results['initial_explicit_times'])
180
+ return header, transcript_html
181
+
182
+ def handle_batch_finalization(all_results, progress=gr.Progress()):
183
+ if not all_results:
184
+ raise gr.Error("No active analysis session. Please process files first.")
185
+
186
+ output_paths = []
187
+ num_files = len(all_results)
188
+ for i, (filename, analysis_state) in enumerate(all_results.items()):
189
+ progress((i + 1) / num_files, desc=f"Applying edits {i + 1} of {num_files}")
190
+ times_to_censor = analysis_state.get('initial_explicit_times', [])
191
+ output_path = apply_censoring(analysis_state, times_to_censor, progress=None)
192
+ if output_path:
193
+ output_paths.append(output_path)
194
+
195
+ status_message = f"✅ **Success!** {len(output_paths)} of {len(all_results)} files have been censored."
196
+
197
+ yield (
198
+ gr.update(visible=True),
199
+ gr.update(visible=False),
200
+ gr.update(visible=True),
201
+ status_message,
202
+ output_paths,
203
+ gr.update(visible=True),
204
+ gr.update(visible=False)
205
+ )
206
+
207
+ def return_to_start(all_results):
208
+ """Cleans up all temporary directories and resets the UI to its initial state."""
209
+ if all_results:
210
+ for analysis_state in all_results.values():
211
+ temp_dir_path = analysis_state.get('temp_dir')
212
+ if temp_dir_path and os.path.exists(temp_dir_path):
213
+ try:
214
+ shutil.rmtree(temp_dir_path)
215
+ except Exception as e:
216
+ print(f"Error removing temporary directory {temp_dir_path}: {e}")
217
+
218
+ return (
219
+ gr.update(visible=True), # upload_view
220
+ gr.update(visible=False), # review_view
221
+ gr.update(visible=False), # final_view
222
+ gr.update(visible=True, interactive=True), # apply_button
223
+ gr.update(choices=[], value=None, visible=True), # processed_files_selector
224
+ None, # analysis_results_state
225
+ "", # details_header
226
+ "", # transcript_output
227
+ "", # final_status_output
228
+ None, # edited_files_output
229
+ None # files_input (to clear it)
230
+ )
231
+
232
+
233
+ ###### Gradio UI Definition ########
234
+ css = """
235
+ #main-container { max-width: 1250px; margin: auto; }
236
+ #main-container .prose { font-size: 15px !important; }
237
+ #upload-view { max-width: 60%; margin: 0 auto; }
238
+ #loading-view { min-height: 500px; display: flex; justify-content: center; align-items: center; }
239
+ #apply-button { background-color: #3d9c3e !important; color: white !important; }
240
+ #processed-files-radio { min-height: 300px; }
241
+ s { color: #d32f2f; text-decoration: line-through; }
242
+ """
243
+
244
+ with gr.Blocks(theme=gr.themes.Soft(), title="FSP Finder", css=css) as demo:
245
+ analysis_results_state = gr.State(None)
246
+
247
+ with gr.Column(elem_id="main-container"):
248
+ gr.Markdown("# FSP Finder - AI-powered explicit content detector")
249
+ gr.Markdown("Detects and automatically censors explicit content in music files. For source code and more details, visit our [github page](https://github.com/dclark202/auto-censoring).")
250
+ gr.Markdown("---")
251
+
252
+ with gr.Column(visible=True) as upload_view:
253
+ gr.Markdown("### How to use")
254
+ gr.Markdown('- Upload one or more audio files using the box below. Most common audio formats are accepted (e.g., `.mp3`, `.wav`, etc.).')
255
+ gr.Markdown(f'- Click the **Process audio** button to create the transcriptions of the uploaded track(s). You will have a chance to review the edits before applying the censoring.')
256
+
257
+ files_input = gr.File(label="Upload audio files", file_count="multiple", elem_id="upload-view", file_types=["audio"])
258
+ process_button = gr.Button("Process audio", elem_id="upload-view")
259
+
260
+ gr.Markdown('---')
261
+ gr.Markdown('### How it works')
262
+ gr.Markdown("This app uses a fine-tuned version of OpenAI's automatic speech recognition model [Whisper](https://github.com/openai/whisper) to create a lyrics transcript of the uploaded music files. Explicit content (e.g., curse words) are then searched for in the lyrics transcript and highlighted. The vocals stem of the track is split off from the song using [demucs](https://github.com/facebookresearch/demucs) and muted at the appropriate times to create a high-quality edited version of the song.")
263
+
264
+ with gr.Column(visible=False) as review_view:
265
+ gr.Markdown("### Review transcript(s) and apply edits")
266
+ gr.Markdown(f'Words to be censored will appear in <caption>{html.escape("red strikethrough")}</s> text in the transcript below. Apply edits by clicking **Apply all edits** below.')
267
+ gr.Markdown("""Entries in the **Explicit flag** column are determined by running the corresponding line through a [toxicity filter](https://huggingface.co/cardiffnlp/twitter-roberta-large-sensitive-multilabel).
268
+
269
+ - 💥 = violence or self harm
270
+ - 🤬 = curse words
271
+ - 🚬 = drugs
272
+ - 🔞 = sexual content
273
+
274
+ We are currently working on allowing users to select additional words to censor from the full transcript, this flag should guide users towards identifying additional potentially explicit lines.""")
275
+ gr.Markdown("**Note**: Whisper's processing is not deterministic and it can sometimes get confused and hallucinate with audio. If your transcription seems inaccurate (e.g., a line contains the same word repeated *many* times, or a line contains a significant amount of transcribed text not present in the song), please try running the program again on that song.")
276
+
277
+ with gr.Row(variant="panel"):
278
+ with gr.Column(scale=1):
279
+ processed_files_selector = gr.Radio(label="Select a file to view its transcript", interactive=True, elem_id="processed-files-radio")
280
+ apply_button = gr.Button("Apply all edits", elem_id="apply-button", interactive=False)
281
+ return_to_start_button = gr.Button("Return to start")
282
+ with gr.Column(visible=False) as final_view:
283
+ final_status_output = gr.Markdown()
284
+ edited_files_output = gr.File(label="Download your edited files", file_count="multiple")
285
+
286
+ with gr.Column(scale=3):
287
+ details_header = gr.Markdown()
288
+ with gr.Accordion("Full audio transcript", open=True):
289
+ transcript_output = gr.HTML()
290
+
291
+ with gr.Column(visible=False, elem_id="loading-view") as loading_view:
292
+ gr.Markdown("## ⏳ Processing... please wait")
293
+
294
+ # --- Event Handlers ---
295
+ process_button.click(
296
+ fn=handle_batch_analysis,
297
+ inputs=[files_input],
298
+ outputs=[upload_view, review_view, loading_view, analysis_results_state, processed_files_selector, details_header, transcript_output, apply_button]
299
+ )
300
+
301
+ processed_files_selector.change(
302
+ fn=update_details_view,
303
+ inputs=[processed_files_selector, analysis_results_state],
304
+ outputs=[details_header, transcript_output]
305
+ )
306
+
307
+ apply_button.click(
308
+ fn=handle_batch_finalization,
309
+ inputs=[analysis_results_state],
310
+ outputs=[review_view, loading_view, final_view, final_status_output, edited_files_output, processed_files_selector, apply_button]
311
+ )
312
+
313
+ return_to_start_button.click(
314
+ fn=return_to_start,
315
+ inputs=[analysis_results_state],
316
+ outputs=[
317
+ upload_view,
318
+ review_view,
319
+ final_view,
320
+ apply_button,
321
+ processed_files_selector,
322
+ analysis_results_state,
323
+ details_header,
324
+ transcript_output,
325
+ final_status_output,
326
+ edited_files_output,
327
+ files_input
328
+ ],
329
+ js="() => { if (confirm('Are you sure you want to return to the start? All current analysis will be lost.')) { return true; } else { return false; } }"
330
+ )
331
+
332
+ demo.launch(share=True, favicon_path='fav.png')
fav.png ADDED
fsp.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import whisper_timestamped as whisper_t
2
+ import whisper
3
+ import torch
4
+ import os
5
+ import demucs.separate
6
+ import re
7
+ from pydub import AudioSegment
8
+ from mutagen.easyid3 import EasyID3
9
+ import lyricsgenius
10
+ import jiwer
11
+ import shutil
12
+ import tempfile
13
+
14
+ GENIUS_API_TOKEN = os.getenv("GENIUS_API_TOKEN") # Or your key here!
15
+ genius = lyricsgenius.Genius(GENIUS_API_TOKEN, verbose=False, remove_section_headers=True)
16
+
17
+ default_curse_words = {'fuck', 'shit', 'piss', 'bitch', 'nigg', 'cock', 'faggot', 'cunt', 'clint', 'tits', 'pussy', 'dick', 'asshole', 'whore', 'goddam'}
18
+
19
+ # --- Helper Functions (remove_punctuation, get_metadata, etc.) ---
20
+ def remove_punctuation(s):
21
+ s = re.sub(r'[^a-zA-Z0-9\s]', '', s)
22
+ return s.lower()
23
+
24
+ def silence_audio_segment(input_audio_path, output_audio_path, times):
25
+ audio = AudioSegment.from_file(input_audio_path)
26
+ for (start_ms, end_ms) in times:
27
+ before_segment = audio[:start_ms]
28
+ target_segment = audio[start_ms:end_ms] - 60
29
+ after_segment = audio[end_ms:]
30
+ audio = before_segment + target_segment + after_segment
31
+ audio.export(output_audio_path, format='wav')
32
+
33
+ def combine_audio(path1, path2, outpath):
34
+ audio1 = AudioSegment.from_file(path1, format='wav')
35
+ audio2 = AudioSegment.from_file(path2, format='wav')
36
+ combined_audio = audio1.overlay(audio2)
37
+ combined_audio.export(outpath, format="mp3")
38
+
39
+ def get_metadata(original_audio_path):
40
+ try:
41
+ audio_orig = EasyID3(original_audio_path)
42
+ metadata = {'title': audio_orig.get('title', [None])[0], 'artist': audio_orig.get('artist', [None])[0], 'album': audio_orig.get('album', [None])[0], 'year': audio_orig.get('date', [None])[0]}
43
+ except Exception:
44
+ metadata = {'title': 'N/A', 'artist': 'N/A', 'album': 'N/A', 'year': 'N/A'}
45
+ return metadata
46
+
47
+ def transfer_metadata(original_audio_path, edited_audio_path):
48
+ try:
49
+ audio_orig = EasyID3(original_audio_path)
50
+ audio_edit = EasyID3(edited_audio_path)
51
+ for key in audio_orig.keys():
52
+ audio_edit[key] = audio_orig[key]
53
+ audio_edit.save()
54
+ except Exception as e:
55
+ print(f"Could not transfer metadata: {e}")
56
+
57
+ def seconds_to_minutes(time):
58
+ mins = int(time // 60)
59
+ secs = int(time % 60)
60
+
61
+ if secs == 0:
62
+ return f'{mins}:00'
63
+
64
+ elif secs < 10:
65
+ return f'{mins}:0{secs}'
66
+
67
+ else:
68
+ return f"{mins}:{secs}"
69
+
70
+ def get_genius_url(artist, song_title):
71
+ if not artist or not song_title or artist == 'N/A' or song_title == 'N/A': return None
72
+ try:
73
+ song = genius.search_song(song_title, artist)
74
+ return song.url if song else None
75
+ except Exception: return None
76
+
77
+ def calculate_wer(ground_truth, hypothesis):
78
+ if not ground_truth or not hypothesis or "not available" in ground_truth.lower(): return None
79
+ try:
80
+ transformation = jiwer.Compose([jiwer.ToLowerCase(), jiwer.RemovePunctuation(), jiwer.RemoveMultipleSpaces(), jiwer.Strip(), jiwer.ExpandCommonEnglishContractions(), jiwer.RemoveEmptyStrings()])
81
+ error = jiwer.mer(transformation(ground_truth), transformation(hypothesis))
82
+ return f"{error:.3f}"
83
+ except Exception: return "Error"
84
+
85
+ def get_genius_lyrics(artist, song_title):
86
+ if not artist or not song_title or artist == 'N/A' or song_title == 'N/A': return "Lyrics not available (missing metadata)."
87
+ try:
88
+ song = genius.search_song(song_title, artist)
89
+ return song.lyrics if song else "Could not find lyrics on Genius."
90
+ except Exception: return "An error occurred while searching for lyrics."
91
+
92
+ ##########################################################
93
+ # STEP 1: Analyze Audio, Separate Tracks, and Transcribe #
94
+ ##########################################################
95
+ def analyze_audio(audio_path, model, device, fine_tuned=True, progress=None):
96
+ """
97
+ Performs audio separation and transcription. Does NOT apply any edits.
98
+ Returns a state dictionary with paths to temp files and the transcript.
99
+ """
100
+ if progress: progress(0, desc="Setting up temporary directory...")
101
+ run_temp_dir = tempfile.mkdtemp()
102
+
103
+ source_path = os.path.abspath(audio_path)
104
+
105
+ # This line is changed to use the standardized filename 'temp_audio.mp3'
106
+ temp_audio_path = os.path.join(run_temp_dir, 'temp_audio.mp3')
107
+ shutil.copy(source_path, temp_audio_path)
108
+
109
+ metadata = get_metadata(temp_audio_path)
110
+ metadata['genius_url'] = get_genius_url(metadata['artist'], metadata['title'])
111
+ metadata['genius_lyrics'] = get_genius_lyrics(metadata['artist'], metadata['title'])
112
+
113
+ if progress: progress(0.1, desc="Separating vocals with Demucs...")
114
+ demucs.separate.main(["--two-stems", "vocals", "-n", "mdx_extra", "-o", run_temp_dir, temp_audio_path])
115
+ demucs_out_name = os.path.splitext(os.path.basename(temp_audio_path))[0]
116
+ vocals_path = os.path.join(run_temp_dir, "mdx_extra", demucs_out_name, "vocals.wav")
117
+ no_vocals_path = os.path.join(run_temp_dir, "mdx_extra", demucs_out_name, "no_vocals.wav")
118
+
119
+ if progress: progress(0.6, desc="Transcribing with Whisper...")
120
+ if not fine_tuned:
121
+ result = model.transcribe(vocals_path, language='en', task='transcribe', word_timestamps=True)
122
+ word_key, prob_key = 'word', 'probability'
123
+ else:
124
+ audio = whisper_t.load_audio(vocals_path)
125
+ result = whisper_t.transcribe(model, audio, beam_size=5, best_of=5, temperature=(0.0, 0.2, 0.4, 0.6, 0.8, 1.0), language="en", task='transcribe')
126
+ word_key, prob_key = 'text', 'confidence'
127
+
128
+ full_transcript = []
129
+ initial_explicit_times = []
130
+
131
+ for segment in result["segments"]:
132
+ segment_words = []
133
+ seg = segment.get('words', [])
134
+ prev_word = ''
135
+
136
+ for i, word_info in enumerate(seg):
137
+ word_text = word_info.get(word_key, '').strip()
138
+ if not word_text: continue
139
+
140
+ cleaned_word = remove_punctuation(word_text)
141
+ is_explicit = any(curse in cleaned_word for curse in default_curse_words)
142
+
143
+ start_time = float(word_info['start'])
144
+ end_time = float(word_info['end'])
145
+
146
+ word_data = {'text': word_text, 'start': start_time, 'end': end_time, 'prob': word_info[prob_key]}
147
+ segment_words.append(word_data)
148
+
149
+ if is_explicit:
150
+ initial_explicit_times.append({'start': start_time, 'end': end_time})
151
+
152
+ # Handle two word cluster "god damn"
153
+ if cleaned_word == 'damn' and prev_word == 'god':
154
+ god_start = seg[i-1]['start']
155
+ god_end = seg[i-1]['end']
156
+ initial_explicit_times.append({'start': god_start, 'end': god_end})
157
+ initial_explicit_times.append({'start': start_time, 'end': end_time})
158
+
159
+ prev_word = cleaned_word
160
+
161
+ full_transcript.append({'line_words': segment_words, 'start': segment['start'], 'end': segment['end']})
162
+
163
+ transcript_text = " ".join([word['text'] for seg in full_transcript for word in seg['line_words']])
164
+ metadata['wer_score'] = calculate_wer(metadata['genius_lyrics'], transcript_text)
165
+
166
+ if device == 'cuda': torch.cuda.empty_cache()
167
+
168
+ return {
169
+ "temp_dir": run_temp_dir,
170
+ "vocals_path": vocals_path,
171
+ "no_vocals_path": no_vocals_path,
172
+ "original_audio_path_copy": temp_audio_path,
173
+ "original_filename": os.path.basename(source_path),
174
+ "transcript": full_transcript,
175
+ "initial_explicit_times": initial_explicit_times,
176
+ "metadata": metadata
177
+ }
178
+
179
+ ##############################################
180
+ # STEP 2: Apply Censoring and Finalize Audio #
181
+ ##############################################
182
+
183
+ def apply_censoring(analysis_state, times_to_censor, progress=None):
184
+ """
185
+ Takes the state from analyze_audio and a final list of timestamps,
186
+ applies silencing, and creates the final audio file in the temp directory.
187
+ """
188
+ if not times_to_censor:
189
+ # If there's nothing to censor, we don't need to do anything.
190
+ # The temporary directory will be cleaned up by the app logic.
191
+ return None
192
+
193
+ if progress: progress(0, desc="Applying silence to vocal track...")
194
+ times_in_ms = [(int(t['start']*1000), int(t['end']*1000)) for t in times_to_censor]
195
+ silence_audio_segment(analysis_state['vocals_path'], analysis_state['vocals_path'], times_in_ms)
196
+
197
+ base_name = os.path.splitext(analysis_state['original_filename'])[0]
198
+ # MODIFIED: Save the output file to the existing temporary directory.
199
+ output_path = os.path.join(analysis_state['temp_dir'], f"{base_name}-edited.mp3")
200
+
201
+ if progress: progress(0.6, desc="Combining audio tracks...")
202
+ combine_audio(analysis_state['vocals_path'], analysis_state['no_vocals_path'], output_path)
203
+ transfer_metadata(analysis_state['original_audio_path_copy'], output_path)
204
+
205
+ # MODIFIED: The temporary directory is no longer removed here.
206
+ # Cleanup will be handled by the main application UI logic.
207
+
208
+ return output_path
lora_config/adapter_config.json ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alpha_pattern": {},
3
+ "auto_mapping": {
4
+ "base_model_class": "WhisperForConditionalGeneration",
5
+ "parent_library": "transformers.models.whisper.modeling_whisper"
6
+ },
7
+ "base_model_name_or_path": "openai/whisper-medium.en",
8
+ "bias": "none",
9
+ "corda_config": null,
10
+ "eva_config": null,
11
+ "exclude_modules": null,
12
+ "fan_in_fan_out": false,
13
+ "inference_mode": true,
14
+ "init_lora_weights": true,
15
+ "layer_replication": null,
16
+ "layers_pattern": null,
17
+ "layers_to_transform": null,
18
+ "loftq_config": {},
19
+ "lora_alpha": 32,
20
+ "lora_bias": false,
21
+ "lora_dropout": 0.05,
22
+ "megatron_config": null,
23
+ "megatron_core": "megatron.core",
24
+ "modules_to_save": [
25
+ "proj_out"
26
+ ],
27
+ "peft_type": "LORA",
28
+ "qalora_group_size": 16,
29
+ "r": 16,
30
+ "rank_pattern": {},
31
+ "revision": null,
32
+ "target_modules": [
33
+ "q_proj",
34
+ "v_proj"
35
+ ],
36
+ "task_type": null,
37
+ "trainable_token_indices": null,
38
+ "use_dora": false,
39
+ "use_qalora": false,
40
+ "use_rslora": false
41
+ }
lora_config/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:78a08d64b52b111d5c532eb368665b4a71464b327c66f52ec4dfe466c2ff37c2
3
+ size 231350472
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ # Gradio Web UI