Offex commited on
Commit
ef9a67d
Β·
verified Β·
1 Parent(s): d2eafd6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -80
app.py CHANGED
@@ -2,9 +2,12 @@ import gradio as gr
2
  import yt_dlp
3
  import os
4
  import shutil
 
5
  from faster_whisper import WhisperModel
6
 
7
- # --- 1. Model Setup ---
 
 
8
  model = None
9
 
10
  def load_model():
@@ -12,116 +15,139 @@ def load_model():
12
  if model is None:
13
  print("πŸ“₯ Loading Whisper Model...")
14
  model = WhisperModel("base", device="cpu", compute_type="int8")
15
- print("βœ… Model Loaded!")
16
  return model
17
 
18
- # --- 2. Helper: Find FFmpeg ---
19
- def get_ffmpeg_dir():
20
- # System me ffmpeg kahan hai, ye pata lagao
 
21
  path = shutil.which("ffmpeg")
22
- if path:
23
- return os.path.dirname(path) # Folder ka rasta return karo
24
- return "/usr/bin" # Default fallback
25
-
26
- # --- 3. Logic: Download Audio from URL ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  def download_audio_from_url(url):
28
- output_path = "downloaded_audio"
29
- if os.path.exists(f"{output_path}.mp3"): os.remove(f"{output_path}.mp3")
30
-
31
- # Dynamic FFmpeg Path (Ye error fix karega)
32
- ffmpeg_dir = get_ffmpeg_dir()
33
- print(f"πŸ”§ FFmpeg found at: {ffmpeg_dir}")
34
 
35
  ydl_opts = {
36
- 'format': 'bestaudio/best',
37
- 'outtmpl': output_path,
38
- 'ffmpeg_location': ffmpeg_dir, # <--- FIXED
39
- 'postprocessors': [{
40
- 'key': 'FFmpegExtractAudio',
41
- 'preferredcodec': 'mp3',
42
- 'preferredquality': '192',
43
  }],
44
- 'quiet': True,
45
- 'no_warnings': True,
46
- 'nocheckcertificate': True,
47
- 'http_headers': {
48
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
49
- 'Referer': 'https://www.tiktok.com/'
50
- }
51
  }
52
 
53
- try:
54
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
55
- ydl.download([url])
56
- return f"{output_path}.mp3"
57
- except Exception as e:
58
- raise Exception(f"Download Fail: {str(e)}")
59
 
60
- # --- 4. Main Transcribe Function (Handles Both) ---
 
 
 
 
61
  def transcribe_media(url_input, file_input):
62
-
63
- audio_file_path = None
64
-
65
  try:
66
- # CASE 1: File Upload
67
- if file_input is not None:
68
- print(f"πŸ“‚ Processing Uploaded File: {file_input}")
69
- audio_file_path = file_input
70
-
71
- # CASE 2: URL Input
72
- elif url_input and url_input.strip() != "":
73
- print(f"πŸ”— Processing URL: {url_input}")
74
- audio_file_path = download_audio_from_url(url_input)
75
-
 
 
 
 
 
76
  else:
77
- return "⚠️ Error: Link daalein ya File upload karein."
78
-
79
- if not os.path.exists(audio_file_path):
80
- return "❌ Error: File nahi mili."
81
-
82
- # --- Transcribe ---
83
- current_model = load_model()
84
-
85
- # Turbo Settings: beam_size=1 (Fast)
86
- segments, _ = current_model.transcribe(
87
- audio_file_path,
88
- beam_size=1,
89
  vad_filter=True
90
  )
91
-
92
- text = " ".join([s.text for s in segments])
93
- return text.strip()
94
 
95
  except Exception as e:
96
  return f"❌ Error: {str(e)}"
97
 
98
- # --- 5. UI ---
 
 
99
  css = """
100
  .container {max-width: 900px; margin: auto;}
101
- .gr-button-primary {background: linear-gradient(90deg, #1CB5E0 0%, #000851 100%); border: none; color: white;}
 
 
 
 
102
  """
103
 
104
  with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
105
-
106
  with gr.Column(elem_classes="container"):
107
- gr.Markdown("# πŸš€ Turbo Transcriber (Link & Upload)")
108
- gr.Markdown("Paste a TikTok link **OR** upload an Audio/Video file.")
 
 
 
109
 
110
  with gr.Tabs():
111
- # TAB 1: Link
112
  with gr.TabItem("πŸ”— Paste Link"):
113
- url_in = gr.Textbox(label="TikTok / YouTube URL", placeholder="https://...")
114
- btn_url = gr.Button("πŸš€ Transcribe Link", variant="primary")
 
 
 
115
 
116
- # TAB 2: File Upload
117
  with gr.TabItem("πŸ“‚ Upload File"):
118
- file_in = gr.Audio(label="Upload File", type="filepath", sources=["upload", "microphone"])
 
 
 
119
  btn_file = gr.Button("πŸ“‚ Transcribe File", variant="primary")
120
 
121
- transcript_out = gr.Code(label="Transcript Result", language="markdown", interactive=False, lines=15)
122
 
123
- # Actions
124
- btn_url.click(fn=transcribe_media, inputs=[url_in, gr.State(None)], outputs=transcript_out)
125
- btn_file.click(fn=transcribe_media, inputs=[gr.State(None), file_in], outputs=transcript_out)
126
 
127
- demo.launch()
 
2
  import yt_dlp
3
  import os
4
  import shutil
5
+ import subprocess
6
  from faster_whisper import WhisperModel
7
 
8
+ # ===============================
9
+ # 1. Whisper Model (Lazy Load)
10
+ # ===============================
11
  model = None
12
 
13
  def load_model():
 
15
  if model is None:
16
  print("πŸ“₯ Loading Whisper Model...")
17
  model = WhisperModel("base", device="cpu", compute_type="int8")
18
+ print("βœ… Model Loaded")
19
  return model
20
 
21
+ # ===============================
22
+ # 2. FFmpeg Path
23
+ # ===============================
24
+ def get_ffmpeg_path():
25
  path = shutil.which("ffmpeg")
26
+ return path if path else "/usr/bin/ffmpeg"
27
+
28
+ # ===============================
29
+ # 3. Convert Video β†’ Audio
30
+ # ===============================
31
+ def extract_audio(video_path):
32
+ audio_path = "uploaded_audio.wav"
33
+ if os.path.exists(audio_path):
34
+ os.remove(audio_path)
35
+
36
+ cmd = [
37
+ get_ffmpeg_path(),
38
+ "-i", video_path,
39
+ "-vn",
40
+ "-ac", "1",
41
+ "-ar", "16000",
42
+ audio_path,
43
+ "-y"
44
+ ]
45
+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
46
+ return audio_path
47
+
48
+ # ===============================
49
+ # 4. Download Audio from ANY URL
50
+ # ===============================
51
  def download_audio_from_url(url):
52
+ output = "url_audio.%(ext)s"
 
 
 
 
 
53
 
54
  ydl_opts = {
55
+ "format": "bestaudio/best",
56
+ "outtmpl": output,
57
+ "ffmpeg_location": os.path.dirname(get_ffmpeg_path()),
58
+ "postprocessors": [{
59
+ "key": "FFmpegExtractAudio",
60
+ "preferredcodec": "wav",
61
+ "preferredquality": "192",
62
  }],
63
+ "quiet": True,
64
+ "nocheckcertificate": True,
 
 
 
 
 
65
  }
66
 
67
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
68
+ ydl.download([url])
 
 
 
 
69
 
70
+ return "url_audio.wav"
71
+
72
+ # ===============================
73
+ # 5. Main Transcribe Logic
74
+ # ===============================
75
  def transcribe_media(url_input, file_input):
76
+
 
 
77
  try:
78
+ audio_path = None
79
+
80
+ # ---------- FILE UPLOAD ----------
81
+ if file_input:
82
+ ext = os.path.splitext(file_input)[1].lower()
83
+
84
+ if ext in [".mp3", ".wav", ".m4a"]:
85
+ audio_path = file_input
86
+ else:
87
+ audio_path = extract_audio(file_input)
88
+
89
+ # ---------- URL ----------
90
+ elif url_input and url_input.strip():
91
+ audio_path = download_audio_from_url(url_input)
92
+
93
  else:
94
+ return "⚠️ Please paste a link or upload a file."
95
+
96
+ if not os.path.exists(audio_path):
97
+ return "❌ Audio processing failed."
98
+
99
+ model = load_model()
100
+
101
+ segments, _ = model.transcribe(
102
+ audio_path,
103
+ beam_size=1,
 
 
104
  vad_filter=True
105
  )
106
+
107
+ text = " ".join(seg.text for seg in segments)
108
+ return text.strip() if text else "⚠️ No speech detected."
109
 
110
  except Exception as e:
111
  return f"❌ Error: {str(e)}"
112
 
113
+ # ===============================
114
+ # 6. UI
115
+ # ===============================
116
  css = """
117
  .container {max-width: 900px; margin: auto;}
118
+ .gr-button-primary {
119
+ background: linear-gradient(90deg,#ff416c,#ff4b2b);
120
+ border: none;
121
+ color: white;
122
+ }
123
  """
124
 
125
  with gr.Blocks(theme=gr.themes.Soft(), css=css) as demo:
 
126
  with gr.Column(elem_classes="container"):
127
+ gr.Markdown("## πŸš€ Universal Video Transcript Tool")
128
+ gr.Markdown(
129
+ "Supports **YouTube, TikTok, Instagram, Facebook, Twitter/X**\n\n"
130
+ "**OR** upload video/audio file."
131
+ )
132
 
133
  with gr.Tabs():
 
134
  with gr.TabItem("πŸ”— Paste Link"):
135
+ url_in = gr.Textbox(
136
+ label="Video URL",
137
+ placeholder="https://youtube.com / tiktok.com / instagram.com"
138
+ )
139
+ btn_url = gr.Button("🎧 Transcribe Link", variant="primary")
140
 
 
141
  with gr.TabItem("πŸ“‚ Upload File"):
142
+ file_in = gr.File(
143
+ label="Upload Video / Audio",
144
+ file_types=[".mp4", ".mkv", ".mov", ".webm", ".avi", ".mp3", ".wav"]
145
+ )
146
  btn_file = gr.Button("πŸ“‚ Transcribe File", variant="primary")
147
 
148
+ output = gr.Code(label="Transcript Output", language="markdown", lines=15)
149
 
150
+ btn_url.click(transcribe_media, [url_in, gr.State(None)], output)
151
+ btn_file.click(transcribe_media, [gr.State(None), file_in], output)
 
152
 
153
+ demo.launch()