Turbiling commited on
Commit
c7c3cbe
·
verified ·
1 Parent(s): 99e68b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -150
app.py CHANGED
@@ -1,150 +1,17 @@
1
- import os
2
- import gradio as gr
3
- import tempfile
4
- import yt_dlp
5
- import subprocess
6
- from pydub import AudioSegment
7
- from groq import Groq
8
-
9
- # ✅ Environment Variables
10
- GROQ_API_KEY = os.getenv("GROQ_API_KEY")
11
- if not GROQ_API_KEY:
12
- raise EnvironmentError("Please set GROQ_API_KEY.")
13
-
14
- groq_client = Groq(api_key=GROQ_API_KEY)
15
-
16
- # Download YouTube Audio
17
- def download_youtube_audio(youtube_url):
18
- with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmp_file:
19
- ydl_opts = {
20
- "format": "bestaudio/best",
21
- "outtmpl": tmp_file.name,
22
- "quiet": True,
23
- "postprocessors": [{
24
- "key": "FFmpegExtractAudio",
25
- "preferredcodec": "mp3",
26
- "preferredquality": "192",
27
- }],
28
- }
29
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
30
- ydl.download([youtube_url])
31
- return tmp_file.name
32
-
33
- # ✅ Convert to WAV safely
34
- def convert_to_wav(input_path):
35
- try:
36
- tmp_wav = tempfile.NamedTemporaryFile(suffix=".wav", delete=False, prefix="conv_")
37
- out_wav = tmp_wav.name
38
- result = subprocess.run(
39
- ["ffmpeg", "-y", "-i", str(input_path), "-ar", "16000", "-ac", "1", out_wav],
40
- stdout=subprocess.PIPE,
41
- stderr=subprocess.PIPE
42
- )
43
- if result.returncode != 0:
44
- audio = AudioSegment.from_file(input_path)
45
- audio = audio.set_frame_rate(16000).set_channels(1)
46
- audio.export(out_wav, format="wav")
47
- return out_wav
48
- except Exception as e:
49
- raise RuntimeError(f"❌ Error converting to WAV: {e}")
50
-
51
- # ✅ Split long audio into 5-min chunks
52
- def split_audio(file_path, max_duration_ms=5*60*1000):
53
- audio = AudioSegment.from_file(file_path)
54
- chunks = []
55
- for i in range(0, len(audio), max_duration_ms):
56
- chunk = audio[i:i + max_duration_ms]
57
- temp_chunk = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
58
- chunk.export(temp_chunk.name, format="wav")
59
- chunks.append(temp_chunk.name)
60
- return chunks
61
-
62
- # ✅ Transcription using Groq Whisper
63
- def transcribe_audio(audio_path):
64
- try:
65
- chunks = split_audio(audio_path)
66
- transcript = ""
67
- for chunk in chunks:
68
- with open(chunk, "rb") as f:
69
- response = groq_client.audio.transcriptions.create(
70
- model="whisper-large-v3",
71
- file=f
72
- )
73
- transcript += response.text + "\n"
74
- return transcript.strip()
75
- except Exception as e:
76
- return f"❌ Error during transcription: {e}"
77
-
78
- # ✅ Chunk-wise summarization using Groq LLM
79
- def summarize_text(text, lang):
80
- try:
81
- chunks = [text[i:i+2000] for i in range(0, len(text), 2000)]
82
- summaries = []
83
-
84
- for idx, chunk in enumerate(chunks):
85
- prompt = (
86
- f"Summarize the following text in English:\n\n{chunk}"
87
- if lang == "English"
88
- else f"مندرجہ ذیل عبارت کا جامع اور رواں اردو خلاصہ تحریر کریں:\n\n{chunk}"
89
- )
90
- response = groq_client.chat.completions.create(
91
- model="openai/gpt-oss-120b",
92
- messages=[{"role": "user", "content": prompt}],
93
- temperature=0.6,
94
- )
95
- summaries.append(response.choices[0].message.content.strip())
96
-
97
- # Meta-summary
98
- combined = "\n".join(summaries)
99
- final_prompt = (
100
- f"Combine and condense these summaries into one clear, fluent English summary:\n\n{combined}"
101
- if lang == "English"
102
- else f"مندرجہ ذیل خلاصوں کو یکجا کر کے ایک مختصر مگر جامع اردو خلاصہ تحریر کریں:\n\n{combined}"
103
- )
104
- final_response = groq_client.chat.completions.create(
105
- model="openai/gpt-oss-120b",
106
- messages=[{"role": "user", "content": final_prompt}],
107
- temperature=0.6,
108
- )
109
- return final_response.choices[0].message.content.strip()
110
- except Exception as e:
111
- return f"❌ Summarization failed: {e}"
112
-
113
- # ✅ Main Function
114
- def process_input(youtube_url, audio_file, lang):
115
- try:
116
- if youtube_url:
117
- audio_path = download_youtube_audio(youtube_url)
118
- elif audio_file:
119
- audio_path = audio_file
120
- else:
121
- return "❌ Please upload an audio or paste YouTube link.", "", ""
122
-
123
- wav_path = convert_to_wav(audio_path)
124
- transcript = transcribe_audio(wav_path)
125
- if transcript.startswith("❌"):
126
- return transcript, "", ""
127
-
128
- summary = summarize_text(transcript, lang)
129
- return "✅ Transcription Completed!", transcript, summary
130
- except Exception as e:
131
- return f"❌ Error: {e}", "", ""
132
-
133
- # ✅ Gradio Interface
134
- with gr.Blocks(title="🎧 Urdu & English Audio Summarizer") as app:
135
- gr.Markdown("## 🎧 Transcribe & Summarize English or Urdu Audio / YouTube Videos")
136
-
137
- with gr.Row():
138
- youtube_link = gr.Textbox(label="📺 YouTube Link (optional)")
139
- lang_choice = gr.Dropdown(["English", "Urdu"], value="English", label="🌐 Summary Language")
140
-
141
- audio_input = gr.Audio(type="filepath", label="🎙️ Upload Audio (optional)")
142
- btn = gr.Button("🚀 Transcribe & Summarize")
143
-
144
- status = gr.Textbox(label="Status")
145
- transcript_box = gr.Textbox(label="📝 Transcription", lines=8)
146
- summary_box = gr.Textbox(label="🧩 Summary", lines=8)
147
-
148
- btn.click(process_input, [youtube_link, audio_input, lang_choice], [status, transcript_box, summary_box])
149
-
150
- app.launch()
 
1
+ ---
2
+ title: SmartTranscribe Rate-limited Urdu/English Summaries
3
+ emoji: 🎙️
4
+ colorFrom: indigo
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: "4.44.0"
8
+ app_file: app.py
9
+ pinned: true
10
+ ---
11
+
12
+ # SmartTranscribe
13
+
14
+ Notes:
15
+ - This version respects Groq tokens-per-minute (TPM) limits by chunking transcripts and rate-limiting requests.
16
+ - You can tweak TPM via env var `GROQ_TPM_LIMIT` (default 8000).
17
+ - You can adjust chunk size via `CHUNK_CHARS` and output size via `OUT_TOKENS_PER_CHUNK`.