Spaces:
Build error
Build error
| import subprocess | |
| import sys | |
| import os | |
| import random | |
| import gradio as gr | |
| from pydub import AudioSegment | |
| from youtube_transcript_api import YouTubeTranscriptApi | |
| try: | |
| import openai | |
| except ImportError: | |
| subprocess.check_call([sys.executable, "-m", "pip", "install", "openai"]) | |
| import openai # Import the library after installing it | |
| def DownloadScript(youtube_url, key): | |
| video_id = youtube_url.split("v=")[-1] | |
| transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en']) | |
| full_text = " ".join([entry['text'] for entry in transcript]) | |
| return full_text | |
| def GenQuiz(text, key): | |
| prompt = "請依附內容,為我出五題選擇題"+text | |
| openai.api_key = key | |
| completion = openai.chat.completions.create( | |
| model="gpt-4o", | |
| messages=[{"role": "user", "content": prompt}] | |
| ) | |
| return completion.choices[0].message.content | |
| def setup_gradio_interface(): | |
| with gr.Blocks() as demo: | |
| gr.Markdown( | |
| """ | |
| <h1 style="text-align: center; font-size: 36px; color: #333;">YouTube 字幕考題生成器</h1> | |
| """ | |
| ) | |
| with gr.Tab("字幕考題生成"): | |
| api_key_input = gr.Textbox(label="第一步:請輸入OpenAI API金鑰", placeholder="OpenAI API Key") | |
| youtube_input = gr.Textbox( | |
| label="第二步:請輸入 YouTube 影片連結", | |
| placeholder="https://www.youtube.com/watch?v=example" | |
| ) | |
| submit_button = gr.Button("載入字幕") | |
| txt_cc_output = gr.Textbox( | |
| label="第三步:下載字幕", | |
| placeholder="字幕將顯示在此處", | |
| interactive=False | |
| ) | |
| submit2_button = gr.Button("考題生成") | |
| txt_quiz_output = gr.Textbox( | |
| label="第四步:考題生成", | |
| placeholder="考題將顯示在此處", | |
| interactive=False | |
| ) | |
| # 連接按鈕到功能 | |
| submit_button.click( | |
| DownloadScript, | |
| inputs=[youtube_input, api_key_input], | |
| outputs=[txt_cc_output] | |
| ) | |
| submit2_button.click( | |
| GenQuiz, | |
| inputs=[txt_cc_output, api_key_input], | |
| outputs=[txt_quiz_output] | |
| ) | |
| return demo | |
| # 執行界面 | |
| if __name__ == "__main__": | |
| demo = setup_gradio_interface() | |
| demo.launch() | |