Download app.py from seagullOk/Audio_Transcribe_Interface: direct link, hf CLI and curl.
- Browser
- Download file 4.22 kB
-
https://huggingface.co/spaces/seagullOk/Audio_Transcribe_Interface/resolve/main/app.py
- Command line
-
hf download hf://spaces/seagullOk/Audio_Transcribe_Interface/app.py
-
curl -L -o app.py https://huggingface.co/spaces/seagullOk/Audio_Transcribe_Interface/resolve/main/app.py
4.22 kB
| import openai | |
| import gradio as gr | |
| import os | |
| from pydub import AudioSegment | |
| import math | |
| import tempfile | |
| import time # ✅ 用来加延时 | |
| from datetime import datetime | |
| # 从环境变量读取 API Key | |
| print("程序启动,开始读取 API Key") | |
| openai.api_key = os.getenv("OPENAI_API_KEY") | |
| print(f"读取到 API Key,长度: {len(openai.api_key) if openai.api_key else 'None'}") | |
| # ✅ 新增:检查当前 API 余额 | |
| def check_openai_quota(): | |
| try: | |
| # 通过 billing API 获取配额(需要付费账户) | |
| sub = openai.Subscription.retrieve() | |
| usage = openai.Usage.retrieve( | |
| start_date=datetime.now().strftime("%Y-%m-01"), | |
| end_date=datetime.now().strftime("%Y-%m-%d") | |
| ) | |
| total = sub["hard_limit_usd"] | |
| used = usage["total_usage"] / 100 # 转成 USD | |
| remain = total - used | |
| return remain | |
| except Exception as e: | |
| print("⚠️ 无法获取配额信息(可能是免费账户)", e) | |
| return None | |
| def seconds_to_srt_time(seconds: float) -> str: | |
| ms = int((seconds - int(seconds)) * 1000) | |
| s = int(seconds) % 60 | |
| m = (int(seconds) // 60) % 60 | |
| h = int(seconds) // 3600 | |
| return f"{h:02}:{m:02}:{s:02},{ms:03}" | |
| def merge_srt_segments(segments): | |
| srt_output = "" | |
| counter = 1 | |
| for seg in segments: | |
| for entry in seg: | |
| start = seconds_to_srt_time(entry["start"]) | |
| end = seconds_to_srt_time(entry["end"]) | |
| text = entry["text"].replace("\n", " ").strip() | |
| srt_output += f"{counter}\n{start} --> {end}\n{text}\n\n" | |
| counter += 1 | |
| return srt_output | |
| def transcribe_long_audio_with_timestamps(audio_path, segment_length_minutes=5): | |
| try: | |
| # ✅ 调用前检查配额 | |
| remain = check_openai_quota() | |
| if remain is not None and remain <= 0: | |
| return "❌ API 配额已用完,请充值或更换 API Key", None | |
| segment_length_ms = segment_length_minutes * 60 * 1000 | |
| audio = AudioSegment.from_file(audio_path) | |
| duration_ms = len(audio) | |
| num_segments = math.ceil(duration_ms / segment_length_ms) | |
| all_segments_srt = [] | |
| for i in range(num_segments): | |
| start = i * segment_length_ms | |
| end = min((i + 1) * segment_length_ms, duration_ms) | |
| segment = audio[start:end] | |
| with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as tmp: | |
| segment.export(tmp.name, format="mp3") | |
| temp_file_path = tmp.name | |
| with open(temp_file_path, "rb") as f: | |
| response = openai.audio.transcriptions.create( | |
| model="whisper-1", | |
| file=f, | |
| response_format="verbose_json" | |
| ) | |
| os.remove(temp_file_path) | |
| segments = [] | |
| for segment_info in response.segments: | |
| segments.append({ | |
| "start": segment_info.start + start / 1000, | |
| "end": segment_info.end + start / 1000, | |
| "text": segment_info.text | |
| }) | |
| all_segments_srt.append(segments) | |
| # ✅ 加个延时,避免请求过快 | |
| time.sleep(1) | |
| srt_text = merge_srt_segments(all_segments_srt) | |
| with open("transcript.srt", "w", encoding="utf-8") as f: | |
| f.write(srt_text) | |
| full_text = "\n\n".join([seg["text"].strip() for segs in all_segments_srt for seg in segs]) | |
| return full_text, "transcript.srt" | |
| except Exception as e: | |
| return f"❌ 出现错误:{str(e)}", None | |
| app = gr.Interface( | |
| fn=transcribe_long_audio_with_timestamps, | |
| inputs=gr.Audio(type="filepath", label="📤 上传音频(自动分段,含时间戳)"), | |
| outputs=[ | |
| gr.Textbox(label="📝 转录纯文本"), | |
| gr.File(label="⬇️ 下载带时间戳字幕 (.srt)") | |
| ], | |
| title="🎧 Whisper 长音频分段转录(带时间戳 .srt)", | |
| description="上传音频,自动分段转录并生成带时间戳的 SRT 字幕文件,时间戳与音频整体时长对应。" | |
| ) | |
| app.queue() # ✅ 开启队列模式 | |
| app.launch() # ✅ 启动应用 |