Spaces:
Sleeping
Sleeping
File size: 1,910 Bytes
cc00532 8436a60 cc00532 8436a60 cc00532 8436a60 cc00532 8436a60 cc00532 85a550a cc00532 | 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 43 44 45 46 47 48 49 | from pytube import YouTube
from youtube_transcript_api import YouTubeTranscriptApi
import re
import os
def download_video_transcript(video_url):
try:
video_id = re.search(r"(?<=v=)[\w-]+", video_url)
if video_id:
video_id = video_id.group()
yt = YouTube(video_url)
stream = yt.streams.get_highest_resolution()
print(f'Downloading {yt.title}...')
modified_title = yt.title.replace(" ", "_")
download_path = 'CS370_Milestone5/videos' # Updated path to CS370_Milestone5 repository
captions_path = 'CS370_Milestone5/captions' # Updated path to CS370_Milestone5 repository
# Create directories if they don't exist
os.makedirs(download_path, exist_ok=True)
os.makedirs(captions_path, exist_ok=True)
video_file = f'{download_path}/{modified_title}.mp4'
stream.download(output_path=download_path, filename=modified_title + '.mp4')
print('Download completed!')
transcript_list = YouTubeTranscriptApi.list_transcripts(video_id)
transcript = transcript_list.find_generated_transcript(['en']).fetch()
captions = ""
for i, line in enumerate(transcript):
start_time = line['start']
formatted_time = f"{int(start_time // 60):02d}:{int(start_time % 60):02d}"
captions += f"{formatted_time} {line['text']}\n"
with open(f'{captions_path}/{modified_title}.txt', 'w', encoding='utf-8') as file:
file.write(captions)
# Delete video file after captions are saved
os.remove(video_file)
return captions
else:
print("Video ID not found in URL.")
return None
except Exception as e:
print("Error:", e)
return None
|