Kims12 commited on
Commit
cf025db
·
verified ·
1 Parent(s): 39b6012

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -0
app.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import requests
3
+ import json
4
+ import gradio as gr
5
+ import re
6
+
7
+ # Hugging Face 환경 변수로부터 RapidAPI 키와 호스트 가져오기
8
+ AA_KEY = os.getenv("AA_KEY")
9
+ AA_HOST = "youtube-transcriptor.p.rapidapi.com"
10
+
11
+ # 자막 언어 우선순위 리스트
12
+ LANGUAGE_PRIORITY = ['ko', 'en', 'ja', 'zh']
13
+
14
+ # 유튜브 URL에서 비디오 ID를 추출하는 함수
15
+ def get_video_id(youtube_url):
16
+ # 유튜브 URL 또는 youtu.be 단축 URL에서 video_id 추출
17
+ video_id_match = re.search(r"(?<=v=)[^#&?]*", youtube_url) or re.search(r"(?<=youtu.be/)[^#&?]*", youtube_url)
18
+
19
+ # YouTube Shorts URL 처리
20
+ if not video_id_match:
21
+ video_id_match = re.search(r"(?<=shorts/)[^#&?]*", youtube_url)
22
+
23
+ return video_id_match.group(0) if video_id_match else None
24
+
25
+ # 유튜브 자막을 요청하는 함수 (언어 우선순위를 적용하여 시도)
26
+ def get_youtube_transcript(youtube_url):
27
+ try:
28
+ # 비디오 ID 추출
29
+ video_id = get_video_id(youtube_url)
30
+ if video_id is None:
31
+ return {"error": "잘못된 유튜브 URL입니다."}
32
+
33
+ url = "https://youtube-transcriptor.p.rapidapi.com/transcript"
34
+ headers = {
35
+ "x-rapidapi-key": AA_KEY,
36
+ "x-rapidapi-host": AA_HOST
37
+ }
38
+
39
+ # 1. 우선순위 언어로 시도
40
+ for lang in LANGUAGE_PRIORITY:
41
+ querystring = {"video_id": video_id, "lang": lang}
42
+ response = requests.get(url, headers=headers, params=querystring)
43
+
44
+ if response.status_code == 200:
45
+ data = response.json()
46
+ if data and not isinstance(data, str) and "error" not in data:
47
+ return {"language": lang, "data": data}
48
+ if isinstance(data, dict) and "availableLangs" in data:
49
+ available_langs = data["availableLangs"]
50
+ # 2. 가능한 언어가 있다면 해당 언어로 시도
51
+ for available_lang in available_langs:
52
+ querystring = {"video_id": video_id, "lang": available_lang}
53
+ response = requests.get(url, headers=headers, params=querystring)
54
+ if response.status_code == 200:
55
+ data = response.json()
56
+ if data and not isinstance(data, str) and "error" not in data:
57
+ return {"language": available_lang, "data": data}
58
+
59
+ # 3. 모든 시도 실패시
60
+ return {"error": "자막을 찾을 수 없습니다."}
61
+
62
+ except Exception as e:
63
+ return {"error": "자막을 불러오는데 실패했습니다."}
64
+
65
+ # Gradio 인터페이스 함수
66
+ def youtube_transcript_interface(youtube_url):
67
+ transcript_data = get_youtube_transcript(youtube_url)
68
+ return json.dumps(transcript_data, ensure_ascii=False, indent=2)
69
+
70
+ # Gradio 인터페이스 생성
71
+ interface = gr.Interface(
72
+ fn=youtube_transcript_interface,
73
+ inputs="text",
74
+ outputs="text",
75
+ title="YouTube 자막 추출기",
76
+ description="유튜브 URL을 입력하세요."
77
+ )
78
+
79
+ # Gradio 인터페이스 실행
80
+ interface.launch()