Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,106 +1,210 @@
|
|
1 |
import torch
|
2 |
-
|
3 |
import gradio as gr
|
4 |
import pytube as pt
|
5 |
from transformers import pipeline
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
MODEL_NAME = "ihanif/wav2vec2-xls-r-300m-pashto"
|
10 |
-
lang = "ps"
|
11 |
|
12 |
-
#
|
13 |
-
|
14 |
-
#model = Wav2Vec2ForCTC.from_pretrained(MODEL_NAME)
|
15 |
|
|
|
16 |
device = 0 if torch.cuda.is_available() else "cpu"
|
17 |
-
pipe = pipeline(
|
18 |
-
task="automatic-speech-recognition",
|
19 |
-
model=MODEL_NAME,
|
20 |
-
#chunk_length_s=30,
|
21 |
-
device=device,
|
22 |
-
)
|
23 |
|
24 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
def transcribe(microphone, file_upload):
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
#
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
39 |
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
def
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
"
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
)
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
)
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import torch
|
|
|
2 |
import gradio as gr
|
3 |
import pytube as pt
|
4 |
from transformers import pipeline
|
5 |
+
import os
|
6 |
+
import tempfile
|
7 |
+
import warnings
|
|
|
|
|
8 |
|
9 |
+
# Suppress warnings for cleaner output in Spaces
|
10 |
+
warnings.filterwarnings("ignore")
|
|
|
11 |
|
12 |
+
MODEL_NAME = "ihanif/wav2vec2-xls-r-300m-pashto"
|
13 |
device = 0 if torch.cuda.is_available() else "cpu"
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
|
15 |
+
# Initialize pipeline globally to avoid reloading
|
16 |
+
print("🔄 Loading Pashto ASR model...")
|
17 |
+
try:
|
18 |
+
pipe = pipeline(
|
19 |
+
task="automatic-speech-recognition",
|
20 |
+
model=MODEL_NAME,
|
21 |
+
device=device,
|
22 |
+
)
|
23 |
+
print("✅ Model loaded successfully!")
|
24 |
+
except Exception as e:
|
25 |
+
print(f"❌ Failed to load model: {e}")
|
26 |
+
pipe = None
|
27 |
|
28 |
def transcribe(microphone, file_upload):
|
29 |
+
"""Transcribe audio from microphone or uploaded file"""
|
30 |
+
if pipe is None:
|
31 |
+
return "❌ Model not available. Please try again later."
|
32 |
+
|
33 |
+
if microphone is None and file_upload is None:
|
34 |
+
return "⚠️ Please provide audio input through microphone or file upload."
|
35 |
+
|
36 |
+
# Use microphone input if available, otherwise use uploaded file
|
37 |
+
audio_input = microphone if microphone is not None else file_upload
|
38 |
+
|
39 |
+
try:
|
40 |
+
# Process the audio
|
41 |
+
result = pipe(audio_input)
|
42 |
+
transcription = result["text"] if isinstance(result, dict) else str(result)
|
43 |
|
44 |
+
if not transcription.strip():
|
45 |
+
return "⚠️ No speech detected. Please ensure the audio contains clear Pashto speech."
|
46 |
+
|
47 |
+
return f"📝 **Transcription:**\n\n{transcription}"
|
48 |
+
|
49 |
+
except Exception as e:
|
50 |
+
return f"❌ Transcription failed: {str(e)}"
|
51 |
+
|
52 |
+
def create_youtube_embed(yt_url):
|
53 |
+
"""Create YouTube embed HTML"""
|
54 |
+
try:
|
55 |
+
# Extract video ID from various YouTube URL formats
|
56 |
+
if "youtu.be/" in yt_url:
|
57 |
+
video_id = yt_url.split("youtu.be/")[-1].split("?")[0]
|
58 |
+
elif "watch?v=" in yt_url:
|
59 |
+
video_id = yt_url.split("watch?v=")[-1].split("&")[0]
|
60 |
+
else:
|
61 |
+
return '<div style="text-align: center; color: red;">Invalid YouTube URL</div>'
|
62 |
+
|
63 |
+
return f'''
|
64 |
+
<div style="text-align: center;">
|
65 |
+
<iframe width="560" height="315"
|
66 |
+
src="https://www.youtube.com/embed/{video_id}"
|
67 |
+
frameborder="0"
|
68 |
+
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
69 |
+
allowfullscreen>
|
70 |
+
</iframe>
|
71 |
+
</div>
|
72 |
+
'''
|
73 |
+
except Exception:
|
74 |
+
return '<div style="text-align: center; color: red;">Error creating video embed</div>'
|
75 |
+
|
76 |
+
def transcribe_youtube(yt_url):
|
77 |
+
"""Transcribe audio from YouTube video"""
|
78 |
+
if pipe is None:
|
79 |
+
return "", "❌ Model not available. Please try again later."
|
80 |
+
|
81 |
+
if not yt_url or not yt_url.strip():
|
82 |
+
return "", "⚠️ Please provide a valid YouTube URL."
|
83 |
+
|
84 |
+
try:
|
85 |
+
# Create video embed
|
86 |
+
embed_html = create_youtube_embed(yt_url)
|
87 |
+
|
88 |
+
# Download YouTube audio
|
89 |
+
yt = pt.YouTube(yt_url)
|
90 |
+
|
91 |
+
# Get the best audio stream
|
92 |
+
audio_stream = yt.streams.filter(only_audio=True).first()
|
93 |
+
if not audio_stream:
|
94 |
+
return embed_html, "❌ No audio stream found in this video."
|
95 |
+
|
96 |
+
# Create temporary file for audio
|
97 |
+
with tempfile.NamedTemporaryFile(suffix=".mp4", delete=False) as tmp_file:
|
98 |
+
audio_file = tmp_file.name
|
99 |
+
|
100 |
+
try:
|
101 |
+
# Download audio
|
102 |
+
audio_stream.download(filename=audio_file)
|
103 |
+
|
104 |
+
# Transcribe
|
105 |
+
result = pipe(audio_file)
|
106 |
+
transcription = result["text"] if isinstance(result, dict) else str(result)
|
107 |
+
|
108 |
+
if not transcription.strip():
|
109 |
+
return embed_html, "⚠️ No Pashto speech detected in the video."
|
110 |
+
|
111 |
+
return embed_html, f"📝 **Transcription:**\n\n{transcription}"
|
112 |
+
|
113 |
+
finally:
|
114 |
+
# Clean up temporary file
|
115 |
+
if os.path.exists(audio_file):
|
116 |
+
os.remove(audio_file)
|
117 |
+
|
118 |
+
except Exception as e:
|
119 |
+
return create_youtube_embed(yt_url), f"❌ YouTube transcription failed: {str(e)}"
|
120 |
+
|
121 |
+
# Create Gradio interface
|
122 |
+
with gr.Blocks(
|
123 |
+
title="Pashto ASR - د پښتو وینا پیژندنه",
|
124 |
+
theme=gr.themes.Soft(),
|
125 |
+
css="""
|
126 |
+
.gradio-container {
|
127 |
+
max-width: 900px !important;
|
128 |
+
margin: auto !important;
|
129 |
+
}
|
130 |
+
"""
|
131 |
+
) as demo:
|
132 |
+
|
133 |
+
gr.Markdown("""
|
134 |
+
# 🎤 Pashto Speech Recognition
|
135 |
+
# د پښتو اتوماتیک وینا پیژندنه
|
136 |
+
|
137 |
+
This application transcribes Pashto speech to text using advanced AI models.
|
138 |
+
""")
|
139 |
+
|
140 |
+
with gr.Tabs():
|
141 |
+
with gr.TabItem("🎵 Audio Transcription"):
|
142 |
+
gr.Markdown("### Upload an audio file or record using your microphone")
|
143 |
+
|
144 |
+
with gr.Row():
|
145 |
+
with gr.Column():
|
146 |
+
microphone_input = gr.Audio(
|
147 |
+
source="microphone",
|
148 |
+
type="filepath",
|
149 |
+
label="🎤 Record Audio"
|
150 |
+
)
|
151 |
+
file_input = gr.Audio(
|
152 |
+
source="upload",
|
153 |
+
type="filepath",
|
154 |
+
label="📁 Upload Audio File"
|
155 |
+
)
|
156 |
+
transcribe_btn = gr.Button("🔄 Transcribe", variant="primary")
|
157 |
+
|
158 |
+
with gr.Column():
|
159 |
+
audio_output = gr.Textbox(
|
160 |
+
label="📝 Transcription Result",
|
161 |
+
lines=8,
|
162 |
+
placeholder="Transcription will appear here..."
|
163 |
+
)
|
164 |
+
|
165 |
+
transcribe_btn.click(
|
166 |
+
fn=transcribe,
|
167 |
+
inputs=[microphone_input, file_input],
|
168 |
+
outputs=audio_output
|
169 |
+
)
|
170 |
+
|
171 |
+
with gr.TabItem("📺 YouTube Transcription"):
|
172 |
+
gr.Markdown("### Enter a YouTube URL to transcribe Pashto content")
|
173 |
+
|
174 |
+
with gr.Row():
|
175 |
+
youtube_url = gr.Textbox(
|
176 |
+
label="🔗 YouTube URL",
|
177 |
+
placeholder="https://www.youtube.com/watch?v=...",
|
178 |
+
lines=1
|
179 |
+
)
|
180 |
+
youtube_btn = gr.Button("🔄 Transcribe YouTube", variant="primary")
|
181 |
+
|
182 |
+
youtube_video = gr.HTML(label="📺 Video Preview")
|
183 |
+
youtube_output = gr.Textbox(
|
184 |
+
label="📝 Transcription Result",
|
185 |
+
lines=8,
|
186 |
+
placeholder="YouTube transcription will appear here..."
|
187 |
+
)
|
188 |
+
|
189 |
+
youtube_btn.click(
|
190 |
+
fn=transcribe_youtube,
|
191 |
+
inputs=youtube_url,
|
192 |
+
outputs=[youtube_video, youtube_output]
|
193 |
+
)
|
194 |
+
|
195 |
+
gr.Markdown("""
|
196 |
+
---
|
197 |
+
### 📋 Instructions:
|
198 |
+
- **Audio Transcription**: Upload a Pashto audio file or record directly using your microphone
|
199 |
+
- **YouTube Transcription**: Paste a YouTube URL containing Pashto speech
|
200 |
+
- **Supported formats**: WAV, MP3, MP4, and other common audio formats
|
201 |
+
- **Note**: This model works best with clear Pashto speech
|
202 |
+
|
203 |
+
### 🔧 Powered by:
|
204 |
+
- Model: `ihanif/wav2vec2-xls-r-300m-pashto`
|
205 |
+
- Framework: Transformers + Gradio
|
206 |
+
""")
|
207 |
+
|
208 |
+
# Launch the app
|
209 |
+
if __name__ == "__main__":
|
210 |
+
demo.launch()
|