tregu0458 commited on
Commit
4235624
·
verified ·
1 Parent(s): 324f98e

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from youtube_transcript_api import (
3
+ YouTubeTranscriptApi,
4
+ NoTranscriptFound,
5
+ TranscriptsDisabled,
6
+ VideoUnavailable
7
+ )
8
+ from typing import List, Dict, Optional
9
+ import re
10
+ import gradio as gr
11
+
12
+ class YoutubeTranscript:
13
+ @staticmethod
14
+ def get_video_id(url: str) -> str:
15
+ """URLからVideo IDを抽出"""
16
+ # Use regular expression for more robust ID extraction
17
+ match = re.search(r"(?<=v=)[^&#]+|(?<=be/)[^&#]+", url)
18
+ return match.group(0) if match else None
19
+
20
+ @staticmethod
21
+ def get_transcript(url: str, language: str = 'ja') -> Optional[List[Dict]]:
22
+ """
23
+ YouTubeの書き起こしを取得
24
+
25
+ Args:
26
+ url: YouTube動画のURL
27
+ language: 字幕の言語 (ja, en, en-US)
28
+
29
+ Returns:
30
+ 字幕データのリスト。取得失敗時はNone
31
+ Raises:
32
+ NoTranscriptFound: 指定された言語の字幕が見つからない場合
33
+ """
34
+ try:
35
+ video_id = YoutubeTranscript.get_video_id(url)
36
+ if video_id is None:
37
+ print(f"無効なURLです: {url}")
38
+ return None
39
+
40
+ transcript = YouTubeTranscriptApi.get_transcript(
41
+ video_id,
42
+ languages=[language] # 指定された言語を使用
43
+ )
44
+ return transcript
45
+
46
+ except TranscriptsDisabled:
47
+ print(f"この動画では字幕が無効になっています: {url}")
48
+ return None
49
+
50
+ except VideoUnavailable:
51
+ print(f"動画が利用できません: {url}")
52
+ return None
53
+
54
+ except Exception as e:
55
+ # Check if the exception is related to language not found
56
+ if "does not have any transcripts" in str(e) or \
57
+ "Could not retrieve a transcript for the video" in str(e):
58
+ raise NoTranscriptFound(f"指定した言語 ({language}) の字幕が見つかりません: {url}") from e
59
+ else:
60
+ print(f"予期せぬエラーが発生しました: {str(e)}")
61
+ return None
62
+
63
+
64
+ # The function 'get_transcript_for_gradio' should be outside the class
65
+ def get_transcript_for_gradio(url: str, language: str) -> str:
66
+ """Gradio UI 用の書き起こし取得関数"""
67
+ try:
68
+ transcript = YoutubeTranscript.get_transcript(url, language)
69
+ if transcript:
70
+ # formatted_transcript = "\n".join(
71
+ # [f"[{entry['start']:.1f}s] {entry['text']}" for entry in transcript]
72
+ # )
73
+ formatted_transcript = "".join(
74
+ [f"{entry['text']}" for entry in transcript]
75
+ )
76
+ return formatted_transcript,str(len(formatted_transcript))
77
+ else:
78
+ return "字幕の取得に失敗しました。","字幕の取得に失敗しました。"
79
+ except NoTranscriptFound as e:
80
+ return str(e),str(len(e)) # Return the error message from the exception
81
+ except Exception as e:
82
+ return f"予期せぬエラーが発生しました: {str(e)}",str(len(e))
83
+
84
+ iface = gr.Interface(
85
+ fn=get_transcript_for_gradio,
86
+ inputs=[
87
+ gr.Textbox(lines=1, placeholder="YouTube動画のURLを入力してください",show_copy_button=True),
88
+ gr.Radio(["ja", "en", "en-US"], label="言語", value="ja") # ラジオボタンを追加
89
+ ],
90
+ outputs=[
91
+ gr.Code(label="字幕", max_lines=10),
92
+ gr.Textbox(label="文字数") # Add a Textbox for character count
93
+ ],
94
+ title="YouTube字幕取得アプリ",
95
+ description="YouTube動画のURLを入力すると、字幕を取得して表示します。",
96
+ )
97
+
98
+ iface.launch()