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