tee342 commited on
Commit
9f645d6
·
verified ·
1 Parent(s): 64cfce3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -303
app.py CHANGED
@@ -23,6 +23,16 @@ from mutagen.mp3 import MP3
23
  from mutagen.id3 import ID3, TIT2, TPE1, TALB, TYER
24
  from TTS.api import TTS
25
  import pickle
 
 
 
 
 
 
 
 
 
 
26
 
27
  # Suppress warnings
28
  warnings.filterwarnings("ignore")
@@ -282,30 +292,6 @@ def generate_tts(text):
282
  tts.tts_to_file(text=text, file_path=out_path)
283
  return out_path
284
 
285
- # === Analyze Audio Stats ===
286
- def analyze_audio(audio_path):
287
- y, sr = torchaudio.load(audio_path)
288
- rms = np.mean(librosa.feature.rms(y=y.numpy().flatten()))
289
- tempo, _ = librosa.beat.beat_track(y=y.numpy().flatten(), sr=sr)
290
- silence_ratio = np.mean(np.abs(y.numpy()) < 0.01)
291
-
292
- plt.figure(figsize=(10, 4))
293
- plt.plot(y.numpy().flatten(), color="lightblue")
294
- plt.title("Loudness Over Time")
295
- plt.tight_layout()
296
- buf = BytesIO()
297
- plt.savefig(buf, format="png")
298
- plt.close()
299
- image = Image.open(buf)
300
-
301
- stats = {
302
- "rms_loudness": float(rms),
303
- "silence_ratio": float(silence_ratio),
304
- "tempo_bpm": int(tempo)
305
- }
306
-
307
- return stats, image
308
-
309
  # === Save/Load Project File (.aiproj) ===
310
  def save_project(audio_path, preset_name, effects):
311
  project_data = {
@@ -350,283 +336,27 @@ def mix_tracks(track1, track2, volume_offset=0):
350
  mixed.export(out_path, format="wav")
351
  return out_path
352
 
353
- # === Voice Style Transfer (Dummy) ===
354
- def apply_style_transfer(audio_path, mood="Happy"):
355
- return audio_path
356
 
357
- # === Load Custom Plugins ===
358
- def load_plugin(plugin_file, audio_file):
359
- try:
360
- from importlib.util import spec_from_file_location, module_from_spec
361
- spec = spec_from_file_location("plugin", plugin_file.name)
362
- plugin = module_from_spec(spec)
363
- spec.loader.exec_module(plugin)
364
-
365
- # Run plugin
366
- audio = AudioSegment.from_file(audio_file)
367
- processed = plugin.process(audio)
368
-
369
- out_path = os.path.join(tempfile.gettempdir(), "plugin_output.wav")
370
- processed.export(out_path, format="wav")
371
- return out_path
372
- except Exception as e:
373
- return f"⚠️ Plugin error: {str(e)}"
374
-
375
- # === Auto-Save / Resume Session Handling ===
376
- session_state = gr.State()
377
-
378
- def save_or_resume_session(audio, preset, effects, action="save"):
379
- if action == "save":
380
- return {"audio": audio, "preset": preset, "effects": effects}, None, None, None
381
- elif action == "load" and audio is not None:
382
- return (
383
- None,
384
- audio.get("audio"),
385
- audio.get("preset"),
386
- audio.get("effects")
387
- )
388
- return None, None, None, None
389
-
390
- # === UI ===
391
- effect_options = [
392
- "Noise Reduction",
393
- "Compress Dynamic Range",
394
- "Add Reverb",
395
- "Pitch Shift",
396
- "Echo",
397
- "Stereo Widening",
398
- "Bass Boost",
399
- "Treble Boost",
400
- "Normalize"
401
- ]
402
-
403
- with gr.Blocks(title="AI Audio Studio", css="style.css") as demo:
404
- gr.Markdown("## 🎧 Ultimate AI Audio Studio\nUpload, edit, export — powered by AI!")
405
-
406
- # --- Single File Studio ---
407
- with gr.Tab("🎵 Single File Studio"):
408
- gr.Interface(
409
- fn=process_audio,
410
- inputs=[
411
- gr.Audio(label="Upload Audio", type="filepath"),
412
- gr.CheckboxGroup(choices=effect_options, label="Apply Effects in Order"),
413
- gr.Checkbox(label="Isolate Vocals After Effects"),
414
- gr.Dropdown(choices=preset_names, label="Select Preset", value=preset_names[0] if preset_names else None),
415
- gr.Dropdown(choices=["MP3", "WAV"], label="Export Format", value="MP3")
416
- ],
417
- outputs=[
418
- gr.Audio(label="Processed Audio", type="filepath"),
419
- gr.Image(label="Waveform Preview"),
420
- gr.Textbox(label="Session Log (JSON)", lines=5),
421
- gr.Textbox(label="Detected Genre", lines=1),
422
- gr.Textbox(label="Status", value="✅ Ready", lines=1)
423
- ],
424
- title="Edit One File at a Time",
425
- description="Apply effects, preview waveform, and get full session log.",
426
- flagging_mode="never",
427
- submit_btn="Process Audio",
428
- clear_btn=None
429
- )
430
-
431
- # --- Batch Processing ---
432
- with gr.Tab("🔊 Batch Processing"):
433
- gr.Interface(
434
- fn=batch_process_audio,
435
- inputs=[
436
- gr.File(label="Upload Multiple Files", file_count="multiple"),
437
- gr.CheckboxGroup(choices=effect_options, label="Apply Effects in Order"),
438
- gr.Checkbox(label="Isolate Vocals After Effects"),
439
- gr.Dropdown(choices=preset_names, label="Select Preset", value=preset_names[0] if preset_names else None),
440
- gr.Dropdown(choices=["MP3", "WAV"], label="Export Format", value="MP3")
441
- ],
442
- outputs=[
443
- gr.File(label="Download ZIP of All Processed Files"),
444
- gr.Textbox(label="Status", value="✅ Ready", lines=1)
445
- ],
446
- title="Batch Audio Processor",
447
- description="Upload multiple files, apply effects in bulk, and download all results in a single ZIP.",
448
- flagging_mode="never",
449
- submit_btn="Process All Files",
450
- clear_btn=None
451
- )
452
-
453
- # --- Remix Mode ---
454
- with gr.Tab("🎛 Remix Mode"):
455
- gr.Interface(
456
- fn=stem_split,
457
- inputs=gr.Audio(label="Upload Music Track", type="filepath"),
458
- outputs=[
459
- gr.File(label="Vocals"),
460
- gr.File(label="Drums"),
461
- gr.File(label="Bass"),
462
- gr.File(label="Other")
463
- ],
464
- title="Split Into Drums, Bass, Vocals, and More",
465
- description="Use AI to separate musical elements like vocals, drums, and bass.",
466
- flagging_mode="never",
467
- clear_btn=None
468
- )
469
-
470
- # --- Transcribe & Edit ---
471
- with gr.Tab("📝 Transcribe & Edit"):
472
- gr.Interface(
473
- fn=transcribe_audio,
474
- inputs=gr.Audio(label="Upload Audio", type="filepath"),
475
- outputs=gr.Textbox(label="Transcribed Text", lines=10),
476
- title="Transcribe & Edit Spoken Content",
477
- description="Convert voice to text and edit it before exporting again."
478
- )
479
-
480
- # --- TTS Voice Generator ---
481
- with gr.Tab("💬 TTS Voice Generator"):
482
- gr.Interface(
483
- fn=generate_tts,
484
- inputs=gr.Textbox(label="Enter Text", lines=5),
485
- outputs=gr.Audio(label="Generated Speech", type="filepath"),
486
- title="Text-to-Speech Generator",
487
- description="Type anything and turn it into natural-sounding speech."
488
- )
489
-
490
- # --- Speaker Matching (Dummy) ===
491
- def match_speakers(*args):
492
- return "⚠️ Speaker matching requires Python 3.9 or below"
493
-
494
- with gr.Tab("🧏‍♂️ Match Speakers"):
495
- gr.Interface(
496
- fn=match_speakers,
497
- inputs=[
498
- gr.File(label="Clip 1"),
499
- gr.File(label="Clip 2")
500
- ],
501
- outputs=gr.Textbox(label="Match Score", lines=1),
502
- title="Are These the Same Person?",
503
- description="Detect speaker similarity using AI."
504
- )
505
-
506
- # --- Voice Cloning (Dummy) ===
507
- with gr.Tab("🎭 Voice Cloning (Dubbing)"):
508
- gr.Interface(
509
- fn=apply_style_transfer,
510
- inputs=[
511
- gr.File(label="Source Voice Clip"),
512
- gr.Radio(["Happy", "Sad", "Angry", "Calm"], label="Choose Tone")
513
- ],
514
- outputs=gr.Audio(label="Stylized Output", type="filepath"),
515
- title="Replace Voice Using AI",
516
- description="Clone voice from source to target speaker using AI"
517
- )
518
-
519
- # --- Auto-Save / Resume Sessions ===
520
- with gr.Tab("🧾 Auto-Save & Resume"):
521
- gr.Markdown("Save your current session and come back later.")
522
-
523
- action_radio = gr.Radio(["save", "load"], label="Action", value="save")
524
- audio_input = gr.Audio(label="Upload or Load Audio", type="filepath")
525
- preset_dropdown = gr.Dropdown(choices=preset_names, label="Used Preset", value=preset_names[0] if preset_names else None)
526
- effect_checkbox = gr.CheckboxGroup(choices=effect_options, label="Applied Effects")
527
- save_btn = gr.Button("Save or Load Session")
528
-
529
- session_data = gr.State()
530
-
531
- loaded_audio = gr.Audio(label="Loaded Audio", type="filepath")
532
- loaded_preset = gr.Dropdown(choices=preset_names, label="Loaded Preset")
533
- loaded_effects = gr.CheckboxGroup(choices=effect_options, label="Loaded Effects")
534
-
535
- def handle_action(audio, preset, effects, action):
536
- if action == "save":
537
- return {"audio": audio, "preset": preset, "effects": effects}, None, None, None
538
- elif action == "load" and isinstance(audio, dict):
539
- return (
540
- None,
541
- audio.get("audio"),
542
- audio.get("preset"),
543
- audio.get("effects")
544
- )
545
- return None, None, None, None
546
-
547
- save_btn.click(
548
- fn=handle_action,
549
- inputs=[audio_input, preset_dropdown, effect_checkbox, action_radio],
550
- outputs=[session_data, loaded_audio, loaded_preset, loaded_effects]
551
- )
552
-
553
- # --- VAD – Detect & Remove Silence ===
554
- with gr.Tab("✂️ Trim Silence Automatically"):
555
- gr.Interface(
556
- fn=detect_silence,
557
- inputs=[
558
- gr.File(label="Upload Track"),
559
- gr.Slider(minimum=-100, maximum=-10, value=-50, label="Silence Threshold (dB)"),
560
- gr.Number(label="Min Silence Length (ms)", value=1000)
561
- ],
562
- outputs=gr.File(label="Trimmed Output"),
563
- title="Auto-Detect & Remove Silence",
564
- description="Detect and trim silence at start/end or between words"
565
- )
566
-
567
- # --- Load/Save Project File (.aiproj) ===
568
- with gr.Tab("📁 Save/Load Project"):
569
- gr.Interface(
570
- fn=save_project,
571
- inputs=[
572
- gr.File(label="Original Audio"),
573
- gr.Dropdown(choices=preset_names, label="Used Preset", value=preset_names[0] if preset_names else None),
574
- gr.CheckboxGroup(choices=effect_options, label="Applied Effects")
575
- ],
576
- outputs=gr.File(label="Project File (.aiproj)"),
577
- title="Save Everything Together",
578
- description="Save your session, effects, and settings in one file to reuse later."
579
- )
580
-
581
- gr.Interface(
582
- fn=load_project,
583
- inputs=gr.File(label="Upload .aiproj File"),
584
- outputs=[
585
- gr.Dropdown(choices=preset_names, label="Loaded Preset"),
586
- gr.CheckboxGroup(choices=effect_options, label="Loaded Effects")
587
- ],
588
- title="Resume Last Project",
589
- description="Load your saved session"
590
- )
591
-
592
- # --- Mix Two Tracks ===
593
- with gr.Tab("🔀 Mix Two Tracks"):
594
- gr.Interface(
595
- fn=mix_tracks,
596
- inputs=[
597
- gr.File(label="Main Track"),
598
- gr.File(label="Background Track"),
599
- gr.Slider(minimum=-10, maximum=10, value=0, label="Volume Offset (dB)")
600
- ],
601
- outputs=gr.File(label="Mixed Output"),
602
- title="Overlay Two Tracks",
603
- description="Mix, blend, or subtract two audio files."
604
- )
605
-
606
- # --- Voice Style Transfer ===
607
- with gr.Tab("🧠 Voice Style Transfer"):
608
- gr.Interface(
609
- fn=apply_style_transfer,
610
- inputs=[
611
- gr.Audio(label="Upload Voice Clip", type="filepath"),
612
- gr.Radio(["Happy", "Sad", "Angry", "Calm"], label="Choose Tone")
613
- ],
614
- outputs=gr.Audio(label="Stylized Output", type="filepath"),
615
- title="Change Emotional Tone of Voice",
616
- description="Shift the emotional style of any voice clip."
617
- )
618
-
619
- # --- Custom Effect Plugin System ===
620
- with gr.Tab("🧩 Load Custom Effect"):
621
- gr.Interface(
622
- fn=load_plugin,
623
- inputs=[
624
- gr.File(label="Upload .py plugin"),
625
- gr.Audio(label="Upload Audio", type="filepath")
626
- ],
627
- outputs=gr.Audio(label="Processed Output", type="filepath"),
628
- title="Run Your Own Python Effect",
629
- description="Upload a .py file with a 'process' function"
630
- )
631
-
632
- demo.launch()
 
23
  from mutagen.id3 import ID3, TIT2, TPE1, TALB, TYER
24
  from TTS.api import TTS
25
  import pickle
26
+ import subprocess
27
+
28
+ # Install OpenVoice from GitHub during startup
29
+ try:
30
+ import openvoice
31
+ except ImportError:
32
+ print("Installing OpenVoice from GitHub...")
33
+ subprocess.run(["pip", "install", "git+https://github.com/myshell-ai/OpenVoice.git"])
34
+ from openvoice.se_extractor import get_se
35
+ from openvoice.api import ToneColorConverter
36
 
37
  # Suppress warnings
38
  warnings.filterwarnings("ignore")
 
292
  tts.tts_to_file(text=text, file_path=out_path)
293
  return out_path
294
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
  # === Save/Load Project File (.aiproj) ===
296
  def save_project(audio_path, preset_name, effects):
297
  project_data = {
 
336
  mixed.export(out_path, format="wav")
337
  return out_path
338
 
339
+ # === Voice Style Transfer (Clone Voice) ===
340
+ from openvoice.se_extractor import get_se
341
+ from openvoice.api import ToneColorConverter
342
 
343
+ tone_converter = ToneColorConverter().to("cuda" if torch.cuda.is_available() else "cpu")
344
+
345
+ def clone_voice(source_audio, target_audio, text):
346
+ source_se, _ = get_se(source_audio)
347
+ target_se, _ = get_se(target_audio)
348
+
349
+ out_path = os.path.join(tempfile.gettempdir(), "cloned_output.wav")
350
+
351
+ # Generate base TTS
352
+ tts.tts_to_file(text=text, file_path=out_path)
353
+
354
+ # Apply voice conversion
355
+ tone_converter.convert(
356
+ audio_src_path=out_path,
357
+ src_se=source_se,
358
+ tgt_se=target_se,
359
+ output_path=out_path
360
+ )
361
+
362
+ return out_path