AIRider's picture
Update app.py
258b06c verified
raw
history blame
3.02 kB
import os
import requests
import json
import gradio as gr
import re
# Hugging Face ํ™˜๊ฒฝ ๋ณ€์ˆ˜๋กœ๋ถ€ํ„ฐ RapidAPI ํ‚ค์™€ ํ˜ธ์ŠคํŠธ ๊ฐ€์ ธ์˜ค๊ธฐ
AA_KEY = os.getenv("AA_KEY")
AA_HOST = "youtube-transcriptor.p.rapidapi.com"
# ์œ ํŠœ๋ธŒ URL์—์„œ ๋น„๋””์˜ค ID๋ฅผ ์ถ”์ถœํ•˜๋Š” ํ•จ์ˆ˜
def get_video_id(youtube_url):
# ์ผ๋ฐ˜์ ์ธ YouTube URL (watch?v=...)
match = re.search(r"(?:v=|\/)([0-9A-Za-z_-]{11}).*", youtube_url)
if match:
return match.group(1)
# YouTube Shorts URL
match = re.search(r"youtu\.be\/([0-9A-Za-z_-]{11})", youtube_url)
if match:
return match.group(1)
# YouTube Shorts URL (/shorts/...)
match = re.search(r"\/shorts\/([0-9A-Za-z_-]{11})", youtube_url)
if match:
return match.group(1)
return None
# ์ž๋ง‰ ์–ธ์–ด ์šฐ์„ ์ˆœ์œ„ ๋ฆฌ์ŠคํŠธ
LANGUAGE_PRIORITY = ['ko', 'en', 'ja', 'zh']
# ์œ ํŠœ๋ธŒ ์ž๋ง‰์„ ์š”์ฒญํ•˜๋Š” ํ•จ์ˆ˜ (์–ธ์–ด ์šฐ์„ ์ˆœ์œ„๋ฅผ ์ ์šฉํ•˜์—ฌ ์‹œ๋„)
def get_youtube_transcript(youtube_url):
# ๋น„๋””์˜ค ID ์ถ”์ถœ
video_id = get_video_id(youtube_url)
if video_id is None:
return {"error": "์ž˜๋ชป๋œ ์œ ํŠœ๋ธŒ URL์ž…๋‹ˆ๋‹ค. ๋น„๋””์˜ค ID๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."}
url = "https://youtube-transcriptor.p.rapidapi.com/transcript"
headers = {
"x-rapidapi-key": AA_KEY,
"x-rapidapi-host": AA_HOST
}
# ์–ธ์–ด ์šฐ์„ ์ˆœ์œ„์— ๋”ฐ๋ผ ์ˆœ์ฐจ์ ์œผ๋กœ ์š”์ฒญ์„ ์‹œ๋„
for lang in LANGUAGE_PRIORITY:
querystring = {"video_id": video_id, "lang": lang}
response = requests.get(url, headers=headers, params=querystring)
if response.status_code == 200:
try:
data = response.json()
# API ์‘๋‹ต ๊ตฌ์กฐ ํ™•์ธ ๋ฐ ์˜ฌ๋ฐ”๋ฅธ ์ฒ˜๋ฆฌ
if isinstance(data, dict) and "transcript" in data:
return {"language": lang, "data": data}
elif isinstance(data, list) and len(data) > 0 and "text" in data[0]:
return {"language": lang, "data": {"transcript": data}}
else:
continue # ํ˜„์žฌ ์–ธ์–ด์— ์ž๋ง‰์ด ์—†์œผ๋ฉด ๋‹ค์Œ ์–ธ์–ด๋กœ ์‹œ๋„
except json.JSONDecodeError as e:
continue # JSON ๋””์ฝ”๋”ฉ ์˜ค๋ฅ˜ ์‹œ ๋‹ค์Œ ์–ธ์–ด๋กœ ์‹œ๋„
# ๋ชจ๋“  ์–ธ์–ด์—์„œ ์ž๋ง‰์„ ์ฐพ์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ
return {"error": "์šฐ์„ ์ˆœ์œ„ ์–ธ์–ด๋กœ ์ž๋ง‰์„ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."}
# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ •์˜
def youtube_transcript_interface(youtube_url):
# ์ž๋ง‰ ๋ฐ์ดํ„ฐ ๊ฐ€์ ธ์˜ค๊ธฐ
transcript_data = get_youtube_transcript(youtube_url)
# ๊ฒฐ๊ณผ ์ถœ๋ ฅ
return json.dumps(transcript_data, ensure_ascii=False, indent=2)
# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ
interface = gr.Interface(
fn=youtube_transcript_interface,
inputs="text",
outputs="text",
title="YouTube ์ž๋ง‰ ์ถ”์ถœ๊ธฐ",
description="์œ ํŠœ๋ธŒ URL์„ ์ž…๋ ฅํ•˜์„ธ์š”."
)
# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์‹คํ–‰
interface.launch()