Ssul's Blog

Youtube 영상 정보/자막 정보 추출방법 본문

dev/기능구현

Youtube 영상 정보/자막 정보 추출방법

Ssul 2024. 1. 12. 20:35

0. 영상을 요약해주는 AI만들기 위하여

- Youtube영상 정보를 어떻게 가져 올것인가?

- 크롤링? 아마 잘 만들어 놓은 라이브러리가 있을 것이다.

- 역시나 있다. yt-dlp, youtube-transcript-api

 

 

1. 유튜브 영상 정보 가져오기(채널명, 영상길이, 제목 등등)

pip install yt-dlp

- 설치하자. 해당 라이브러리는 youtube영상의 정보를 가져오는 라이브러리

 

import yt_dlp

def get_youtube_video_info(video_url):
    ydl_opts = {
        'noplaylist': True,
        'quiet': True,
        'no_warnings': True,
    }

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        video_info = ydl.extract_info(video_url, download=False)
        video_id = video_info['id']
        title = video_info['title']
        upload_date = video_info['upload_date']
        channel = video_info['channel']
        duration = video_info['duration_string']

    return video_id, title, upload_date, channel, duration

- import 하고,

- 유튜브 영상 정보를 가져오는 함수 만들기. 비디오 주소를 입력 받는다.

- yt_dlp 사용할 옵션을 ydl_opts로 설정

- video_info = ydl.extract_info(video_url, download=False): download는 할수 있지만 하지 않는 것으로 설정

- 비디오 id, 제목, 업로드날짜, 채널명, 영상길이 정보를 가져와서 리턴해준다

 

video_url = 'https://www.youtube.com/watch?v=CyEsljuyEW8'
get_youtube_video_info(video_url)

- 노빠꾸 탁재훈 초롱이편 주소를 video_url설정

- 위에 선언한 함수 호출

성공적으로 영상정보를 가져왔음!

 

2. 유튜브 자막가져오기

- AI를 활용해서, 유튜브 영상을 요약하는 서비스를 만들려고 한다.

- 하지만, 영상을 모두 다운 받아서, 요약하는 것은 정확도는 높을수 있으나, 다 다운받는 것은 불가능

- 결론은 자막정보를 가져와서, 그것을 언어모델에 넣어서 요약하는 전략

- 그러기 위해서는 유튜브 자막 정보를 가져와야 함

 

pip install youtube-transcript-api

- 설치하시고,

 

from youtube_transcript_api import YouTubeTranscriptApi
from youtube_transcript_api.formatters import SRTFormatter, TextFormatter

def get_video_id(video_url):
    video_id = video_url.split('v=')[1][:11]
    return video_id

video_url = 'https://www.youtube.com/watch?v=CyEsljuyEW8'
video_id = get_video_id(video_url)

- 설치한 라이브러리를 임포트 해주고,

- 유튜브 영상의 id를 추출하는 함수를 선언

*유튜브 영상은 영상마다 고유한 아이디가 있음. v= 뒤에 있는 11개의 문자가 영상의 공유 아이디

- 이번에는 문복희 먹방을 영상으로 설정하고, 고유한 영상 아이디 추출

*노빠꾸 탁재훈은 확실히 국내용인듯. 자막정보가 한국어 한개라서.. 글로벌 먹방영상으로~

 

transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)

for transcript in transcript_list:
    print(f"- [자막언어] {transcript.language}, [자막 언어 코드] {transcript.language_code}")

- 해당 영상에 설정된 자막정보. 다양한 언어 자막이 있을 경우, 여러개가 출력될것

역시 글로벌 먹방...8개 언어로 번역되어있다.

 

transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['ko', 'en'])
srt_formatter = SRTFormatter()
srt_formatted = srt_formatter.format_transcript(transcript)
print(srt_formatted[:150])

download_folder = "./make_service_for_me"

srt_file = f"{download_folder}/{video_id}.srt"
with open(srt_file, 'w') as f:
    f.write(srt_formatted)
print("- SRT 파일경로:", srt_file)

- 자막정보를 가져와서, SRT파일로 저장해보자

- transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['ko', 'en']): 한글, 영어 순으로 탐색해서 먼저 발견된 언어를 transcript에 저장

- 친절하게 SRT포맷터가 있어서, 이것으로 자막파일 생성

- 파일 경로 지정 후, 저장

srt자막 파일

(잠깐 상식. srt자막파일 해석

첫번째는 자막 인덱스(순서)

두번째는 자막 표시시간(출력/출력끝)

세번째는 자막내용

그리고, 한칸 띄우기)

 

 

transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en', 'ko'])
text_formatter = TextFormatter()
text_formatted = text_formatter.format_transcript(transcript)
print(text_formatted[:100])

text_file = f"{download_folder}/{video_id}.txt"
with open(text_file, 'w') as f:
    f.write(text_formatted)
print("- TXT 파일경로:", text_file)

- 이번에는 텍스트 파일로 저장해본다.

- transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=['en', 'ko']): 영어, 한글 순으로 탐색해서 먼저 발견된 언어를 저장. 이번에는 영어로 저장됨

- 파일 경로 지정 후, 저장

txt파일. 잘 저장 된다

 

3. 요약된 자막정보를 LLM에 넣어서 요약하기

- 요건 다른 글에서 작성예정