Spaces:
Running
Running
File size: 1,258 Bytes
17962cc c6714eb 17962cc c6714eb fbf745c 17962cc c6714eb 17962cc c6714eb 17962cc c6714eb 17962cc c6714eb 17962cc fbf745c 17962cc fbf745c 17962cc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import re
from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api._errors import TranscriptsDisabled
MAX_SIZE = 50_000
YT_REGEX = r'^((http)s?:\/\/)?((www\.)|(m\.))?youtube.com\/watch\?([^\?]*&)?v=.+$' # noqa
YT_REGEX_SHORT = r'^((http)s?:\/\/)?youtu.be\/([^\?=]+)(\?[^?]+)?$'
def _extract_video_id(url: str) -> str:
if not re.match(YT_REGEX, url):
if not re.match(YT_REGEX_SHORT, url):
return ''
ind = url.find('?')
ind = len(url) if ind == -1 else ind
return url[url.find('e/')+2:ind]
res = url.split('v=')
ind = res[1].find('&')
ind = len(res[1]) if ind == -1 else ind
return res[1][:ind]
def get_youtube_caption(url: str) -> str:
try:
video_id = _extract_video_id(url)
if not video_id:
return ''
res, size = [], 0
for transcript in YouTubeTranscriptApi.get_transcript(video_id):
res.append(transcript['text'].replace('\n', ' '))
size += len(transcript['text'])
if size >= MAX_SIZE:
return ' '.join(res)[:MAX_SIZE]
return ' '.join(res)[:MAX_SIZE]
except TranscriptsDisabled:
return 'no-cap'
except Exception:
return 'err'
|