Offex commited on
Commit
dcc09a9
·
verified ·
1 Parent(s): 6f8108d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +95 -0
app.py CHANGED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import uuid
4
+ import re
5
+ from pydub import AudioSegment, silence
6
+
7
+ # -----------------------------
8
+ # Filename cleaner
9
+ # -----------------------------
10
+ def clean_file_name(file_path):
11
+ base = os.path.basename(file_path)
12
+ name, ext = os.path.splitext(base)
13
+
14
+ name = re.sub(r'[^a-zA-Z0-9]+', '_', name)
15
+ name = re.sub(r'_+', '_', name).strip('_')
16
+
17
+ uid = uuid.uuid4().hex[:6]
18
+ return os.path.join(os.path.dirname(file_path), f"{name}_{uid}{ext}")
19
+
20
+ # -----------------------------
21
+ # Fast silence removal
22
+ # -----------------------------
23
+ def remove_silence_fast(file_path, keep_silence_ms=50):
24
+ audio = AudioSegment.from_file(file_path)
25
+ audio = audio.set_channels(1)
26
+
27
+ silence_thresh = audio.dBFS - 16
28
+
29
+ chunks = silence.split_on_silence(
30
+ audio,
31
+ min_silence_len=120,
32
+ silence_thresh=silence_thresh,
33
+ keep_silence=keep_silence_ms
34
+ )
35
+
36
+ if not chunks:
37
+ return file_path
38
+
39
+ out = chunks[0]
40
+ for c in chunks[1:]:
41
+ out += c
42
+
43
+ out_path = clean_file_name(file_path)
44
+ out.export(out_path)
45
+ return out_path
46
+
47
+ # -----------------------------
48
+ # Duration
49
+ # -----------------------------
50
+ def duration(path):
51
+ return len(AudioSegment.from_file(path)) / 1000
52
+
53
+ # -----------------------------
54
+ # Main function
55
+ # -----------------------------
56
+ def process_audio(audio_file, seconds):
57
+ keep_ms = int(seconds * 1000)
58
+
59
+ before = duration(audio_file)
60
+ output = remove_silence_fast(audio_file, keep_ms)
61
+ after = duration(output)
62
+
63
+ text = (
64
+ f"Old Duration : {before:.2f}s\n"
65
+ f"New Duration : {after:.2f}s\n"
66
+ f"Saved : {before - after:.2f}s"
67
+ )
68
+
69
+ return output, output, text
70
+
71
+ # -----------------------------
72
+ # UI
73
+ # -----------------------------
74
+ with gr.Blocks(title="Remove Silence From Audio") as demo:
75
+ gr.Markdown("## 🔇 Fast Audio Silence Remover")
76
+
77
+ with gr.Row():
78
+ with gr.Column():
79
+ audio = gr.Audio(type="filepath", sources=["upload", "microphone"])
80
+ silence_keep = gr.Number(value=0.05, label="Keep Silence (seconds)")
81
+ btn = gr.Button("Remove Silence")
82
+
83
+ with gr.Column():
84
+ out_audio = gr.Audio()
85
+ out_file = gr.File()
86
+ info = gr.Textbox()
87
+
88
+ btn.click(
89
+ process_audio,
90
+ [audio, silence_keep],
91
+ [out_audio, out_file, info]
92
+ )
93
+
94
+ # ✅ HF EXPECTS THIS ONLY
95
+ demo.queue().launch()