Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
| 2 |
+
from googleapiclient.discovery import build
|
| 3 |
+
from docx import Document
|
| 4 |
+
import re
|
| 5 |
+
|
| 6 |
+
def get_youtube_transcript(video_id):
|
| 7 |
+
try:
|
| 8 |
+
transcript = YouTubeTranscriptApi.get_transcript(video_id)
|
| 9 |
+
return transcript
|
| 10 |
+
except Exception as e:
|
| 11 |
+
print(f"An error occurred: {e}")
|
| 12 |
+
return None
|
| 13 |
+
|
| 14 |
+
def get_video_title(api_key, video_id):
|
| 15 |
+
youtube = build('youtube', 'v3', developerKey=api_key)
|
| 16 |
+
request = youtube.videos().list(part='snippet', id=video_id)
|
| 17 |
+
response = request.execute()
|
| 18 |
+
if 'items' in response and len(response['items']) > 0:
|
| 19 |
+
return response['items'][0]['snippet']['title']
|
| 20 |
+
return None
|
| 21 |
+
|
| 22 |
+
def save_transcript_to_doc(transcript, filename):
|
| 23 |
+
doc = Document()
|
| 24 |
+
doc.add_heading('YouTube Video Transcript', 0)
|
| 25 |
+
|
| 26 |
+
for entry in transcript:
|
| 27 |
+
start_time = entry['start']
|
| 28 |
+
duration = entry['duration']
|
| 29 |
+
text = entry['text']
|
| 30 |
+
doc.add_paragraph(f"{start_time:.2f} - {duration:.2f}: {text}")
|
| 31 |
+
|
| 32 |
+
doc.save(filename)
|
| 33 |
+
|
| 34 |
+
def sanitize_filename(filename):
|
| 35 |
+
return re.sub(r'[\\/*?:"<>|]', "_", filename)
|
| 36 |
+
|
| 37 |
+
if __name__ == "__main__":
|
| 38 |
+
api_key = 'YOUR_YOUTUBE_DATA_API_KEY' # Replace this with your API key
|
| 39 |
+
video_id = 'dQw4w9WgXcQ' # Replace this with your video ID
|
| 40 |
+
|
| 41 |
+
transcript = get_youtube_transcript(video_id)
|
| 42 |
+
video_title = get_video_title(api_key, video_id)
|
| 43 |
+
|
| 44 |
+
if transcript and video_title:
|
| 45 |
+
sanitized_title = sanitize_filename(video_title)
|
| 46 |
+
output_filename = f"{sanitized_title}.docx"
|
| 47 |
+
save_transcript_to_doc(transcript, output_filename)
|
| 48 |
+
print(f"Transcript saved to {output_filename}.")
|
| 49 |
+
else:
|
| 50 |
+
print("Transcript or video title not available.")
|