Spaces:
Build error
Build error
| """ | |
| 主程序入口点 - 用于 Hugging Face Spaces | |
| """ | |
| import os | |
| import sys | |
| import gradio as gr | |
| # 确保能找到 install_pysrt 包 | |
| current_dir = os.path.dirname(os.path.abspath(__file__)) | |
| if current_dir not in sys.path: | |
| sys.path.append(current_dir) | |
| # 尝试导入并安装 pysrt | |
| try: | |
| import install_pysrt | |
| installed = install_pysrt.is_pysrt_installed() | |
| version = install_pysrt.get_pysrt_version() if installed else "未安装" | |
| if not installed: | |
| print("尝试安装 pysrt...") | |
| success = install_pysrt.installer.install_pysrt() | |
| if success: | |
| version = install_pysrt.get_pysrt_version() | |
| print(f"pysrt {version} 已成功安装") | |
| else: | |
| print("安装 pysrt 失败") | |
| else: | |
| print(f"pysrt {version} 已安装") | |
| import_success = True | |
| except Exception as e: | |
| print(f"导入或安装 install_pysrt 时出错: {e}") | |
| import_success = False | |
| version = "错误" | |
| def create_subtitle(start_time, end_time, text): | |
| """创建字幕并返回结果""" | |
| try: | |
| import pysrt | |
| from pysrt import SubRipFile, SubRipItem, SubRipTime | |
| # 解析时间 | |
| start_parts = [int(x) for x in start_time.split(':')] | |
| end_parts = [int(x) for x in end_time.split(':')] | |
| if len(start_parts) == 3: | |
| start = SubRipTime(hours=start_parts[0], minutes=start_parts[1], seconds=start_parts[2]) | |
| else: | |
| start = SubRipTime(minutes=start_parts[0], seconds=start_parts[1]) | |
| if len(end_parts) == 3: | |
| end = SubRipTime(hours=end_parts[0], minutes=end_parts[1], seconds=end_parts[2]) | |
| else: | |
| end = SubRipTime(minutes=end_parts[0], seconds=end_parts[1]) | |
| # 创建字幕文件 | |
| subs = SubRipFile() | |
| item = SubRipItem(index=1, start=start, end=end, text=text) | |
| subs.append(item) | |
| # 转换为字符串 | |
| return str(subs), f"字幕已成功创建! pysrt 版本: {install_pysrt.get_pysrt_version()}" | |
| except Exception as e: | |
| return "", f"创建字幕时出错: {e}" | |
| # 创建 UI | |
| with gr.Blocks(title="pysrt 演示") as demo: | |
| gr.Markdown(f""" | |
| # pysrt 字幕演示程序 | |
| 当前 pysrt 状态: {"已安装 ✅" if import_success else "未安装 ❌"} | |
| 版本: {version} | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| start_time = gr.Textbox(label="开始时间 (分:秒 或 时:分:秒)", value="00:00") | |
| end_time = gr.Textbox(label="结束时间 (分:秒 或 时:分:秒)", value="00:10") | |
| text = gr.Textbox(label="字幕文本", value="这是一个测试字幕") | |
| create_btn = gr.Button("创建字幕") | |
| with gr.Column(): | |
| result = gr.Textbox(label="生成的 SRT 内容", lines=10) | |
| status = gr.Textbox(label="状态") | |
| create_btn.click(fn=create_subtitle, inputs=[start_time, end_time, text], outputs=[result, status]) | |
| if __name__ == "__main__": | |
| # 显示 pysrt 安装状态 | |
| print("-" * 50) | |
| print(f"pysrt 安装状态: {'成功' if import_success else '失败'}") | |
| if import_success: | |
| print(f"pysrt 版本: {version}") | |
| print("-" * 50) | |
| # 启动 UI | |
| demo.launch() |