navidved commited on
Commit
d726228
·
verified ·
1 Parent(s): bda9ee3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -91
app.py CHANGED
@@ -1,130 +1,87 @@
1
  import gradio as gr
2
- import requests, os, time, pathlib
 
 
3
 
4
- ASR_API_URL = os.getenv("ASR_API_URL")
5
- AUTH_TOKEN = os.getenv("AUTH_TOKEN")
6
-
7
- # ---------- کمکى: استخراج مسیر واقعی فایل ----------
8
- def extract_path(audio_value):
9
- """
10
- audio_value می‌تواند None، رشته یا دیکشنری باشد.
11
- خروجی: مسیر فایل یا None
12
- """
13
- if not audio_value:
14
- return None
15
- if isinstance(audio_value, dict):
16
- return audio_value.get("path") # گرادیو ≥ 4
17
- # برای سازگاری با نسخه‌های قدیم‌تر که str برمی‌گردانند
18
- return audio_value if isinstance(audio_value, (str, pathlib.Path)) else None
19
-
20
- # ---------- پردازش ----------
21
- def transcribe_audio(audio_value):
22
- file_path = extract_path(audio_value)
23
- if not file_path:
24
- return "❌ فایل صوتی هنوز آماده نیست.", ""
25
 
 
26
  if not ASR_API_URL or not AUTH_TOKEN:
27
  return "❌ Error: ASR_API_URL or AUTH_TOKEN is not set.", ""
28
-
29
  headers = {
30
- "accept": "application/json",
31
- "Authorization": f"Bearer {AUTH_TOKEN}",
32
  }
33
-
34
- start = time.time()
 
 
35
  try:
36
- with open(file_path, "rb") as f:
37
- files = {"file": (os.path.basename(file_path), f, "audio/mpeg")}
38
- response = requests.post(ASR_API_URL, headers=headers, files=files)
39
  except Exception as e:
40
- return f"❌ Error: {e}", ""
 
41
 
42
- elapsed = time.time() - start
43
  if response.status_code == 200:
44
- data = response.json()
45
- txt = data.get("transcription", "No transcription returned.")
46
- elapsed = data.get("time", elapsed)
47
- return txt, f"{elapsed:.2f} seconds"
48
-
49
- return f"❌ Error {response.status_code}: {response.text}", ""
50
-
51
-
52
- # ---------- رابط کاربری ----------
53
- CUSTOM_CSS = """
54
- #gooya-title {color:white; background:linear-gradient(90deg,#224CA5 0%,#2CD8D5 100%);
55
- border-radius:12px;padding:20px 10px;margin-bottom:12px;}
56
- .gooya-badge {display:inline-block;background:#224CA5;color:#fff;border-radius:16px;
57
- padding:6px 16px;font-size:0.97rem;margin-top:4px;}
58
- """
59
-
60
- with gr.Blocks(css=CUSTOM_CSS) as demo:
61
-
62
- gr.HTML("""
63
- <div id="gooya-title">
64
- <h1 style='margin-bottom:10px;font-weight:800;font-size:2rem;'>Gooya ASR
65
- <span style="font-size:1.1rem;font-weight:400;opacity:0.8;'>v1.4</span></h1>
66
- <p style='font-size:1.12rem;margin-bottom:2px;'>High-performance Persian Speech-to-Text</p>
67
- <p style='font-size:0.98rem;color:#c6e8fa'>Upload or record a Persian audio file (max 30s) and instantly receive the transcription.</p>
68
- </div>
69
- """)
70
 
71
  with gr.Row():
72
  with gr.Column():
73
  audio = gr.Audio(
74
  label="Audio Input (Upload or record, up to 30s)",
75
  type="filepath",
76
- sources=["upload", "microphone"],
77
  show_label=True,
 
78
  )
79
  with gr.Column():
80
- inf_time_lbl = gr.Label(label="⏱️ Processing Time", elem_classes="gooya-badge")
81
  transcription = gr.Textbox(
82
  label="📝 Transcription",
83
  lines=5,
84
  show_copy_button=True,
85
  placeholder="The transcription will appear here...",
86
- elem_id="gooya-textbox",
87
  )
88
 
89
  with gr.Row():
90
- submit_btn = gr.Button("Transcribe", variant="primary", interactive=False)
91
- clear_btn = gr.Button("Clear", variant="secondary")
92
 
93
- # ---------- فعال / غیرفعال کردن دکمه ----------
94
- def toggle_btn(audio_value):
95
- return gr.Button.update(interactive=bool(extract_path(audio_value)))
 
 
96
 
97
- # بعد از آپلود فایل
98
- audio.change(toggle_btn, inputs=audio, outputs=submit_btn, queue=False)
99
- # بعد از پایان ضبط میکروفون
100
- audio.stop_recording(toggle_btn, inputs=audio, outputs=submit_btn, queue=False)
101
 
102
- # ---------- پردازش ----------
103
  submit_btn.click(
104
  transcribe_audio,
105
  inputs=audio,
106
- outputs=[transcription, inf_time_lbl],
107
- ).then(
108
- lambda: gr.Button.update(interactive=False),
109
- None,
110
- submit_btn,
111
- queue=False,
112
  )
113
-
114
- # ---------- پاک‌کردن ----------
115
- def clear_all():
116
- return (
117
- "", # متن
118
- "", # زمان
119
- gr.Audio.update(value=None), # پاک کردن کامپوننت Audio
120
- gr.Button.update(interactive=False), # غیر فعال کردن دکمه
121
- )
122
-
123
  clear_btn.click(
124
- clear_all,
125
  None,
126
- [transcription, inf_time_lbl, audio, submit_btn],
127
- queue=False,
128
  )
129
 
130
- demo.launch()
 
1
  import gradio as gr
2
+ import requests
3
+ import os
4
+ import time
5
 
6
+ ASR_API_URL = os.getenv('ASR_API_URL')
7
+ AUTH_TOKEN = os.getenv('AUTH_TOKEN')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ def transcribe_audio(file_path):
10
  if not ASR_API_URL or not AUTH_TOKEN:
11
  return "❌ Error: ASR_API_URL or AUTH_TOKEN is not set.", ""
 
12
  headers = {
13
+ 'accept': 'application/json',
14
+ 'Authorization': f'Bearer {AUTH_TOKEN}',
15
  }
16
+ files = {
17
+ 'file': (file_path, open(file_path, 'rb'), 'audio/mpeg'),
18
+ }
19
+ start_time = time.time()
20
  try:
21
+ response = requests.post(ASR_API_URL, headers=headers, files=files)
 
 
22
  except Exception as e:
23
+ return f"❌ Error: {str(e)}", ""
24
+ inference_time = time.time() - start_time
25
 
 
26
  if response.status_code == 200:
27
+ res = response.json()
28
+ transcription = res.get("transcription", "No transcription returned.")
29
+ inference_time_str = f"{res.get('time', inference_time):.2f} seconds"
30
+ return transcription, inference_time_str
31
+ else:
32
+ return f"❌ Error: {response.status_code}, {response.text}", ""
33
+
34
+ with gr.Blocks(css="""
35
+ #gooya-title {color:white; background: linear-gradient(90deg, #224CA5 0%, #2CD8D5 100%); border-radius: 12px; padding:20px 10px;margin-bottom:12px;}
36
+ .gooya-badge {display:inline-block; background:#224CA5; color:#fff; border-radius:16px; padding:6px 16px; font-size:0.97rem; margin-top:4px;}
37
+ #gooya-box {background:#F7FAFF; border:1px solid #e7e9ef; border-radius:14px; padding:22px 18px; margin-top:12px;}
38
+ """) as demo:
39
+ gr.HTML("""<div id="gooya-title">
40
+ <h1 style='margin-bottom:10px;font-weight:800;font-size:2rem;'>Gooya ASR <span style="font-size:1.1rem; font-weight:400; opacity:0.8;">v1.4</span></h1>
41
+ <p style='font-size:1.12rem; margin-bottom:2px;'>High-performance Persian Speech-to-Text</p>
42
+ <p style='font-size:0.98rem; color:#c6e8fa'>Upload or record a Persian audio file (max 30s) and instantly receive the transcription.</p>
43
+ </div>""")
 
 
 
 
 
 
 
 
 
44
 
45
  with gr.Row():
46
  with gr.Column():
47
  audio = gr.Audio(
48
  label="Audio Input (Upload or record, up to 30s)",
49
  type="filepath",
 
50
  show_label=True,
51
+ sources=["upload", "microphone"]
52
  )
53
  with gr.Column():
54
+ inference_time = gr.Label(label="⏱️ Processing Time", elem_classes="gooya-badge")
55
  transcription = gr.Textbox(
56
  label="📝 Transcription",
57
  lines=5,
58
  show_copy_button=True,
59
  placeholder="The transcription will appear here...",
60
+ elem_id="gooya-textbox"
61
  )
62
 
63
  with gr.Row():
64
+ submit_btn = gr.Button("Transcribe", variant="primary")
65
+ clear_btn = gr.Button("Clear", variant="secondary")
66
 
67
+ gr.Markdown("""
68
+ **Instructions:**
69
+ - Maximum audio length: **30 seconds**
70
+ - Input audio should be in Persian.
71
+ - The transcription and processing time will be displayed instantly.
72
 
73
+ For performance benchmarks, visit: [Persian ASR Leaderboard](https://huggingface.co/spaces/navidved/open_persian_asr_leaderboard)
74
+ """)
 
 
75
 
 
76
  submit_btn.click(
77
  transcribe_audio,
78
  inputs=audio,
79
+ outputs=[transcription, inference_time]
 
 
 
 
 
80
  )
 
 
 
 
 
 
 
 
 
 
81
  clear_btn.click(
82
+ lambda: ("", ""),
83
  None,
84
+ [transcription, inference_time, audio]
 
85
  )
86
 
87
+ demo.launch(share=True)