Last active
August 6, 2019 12:41
-
-
Save zevaverbach/dcf55b4e49a3e1ad7b2941e2385fd08a to your computer and use it in GitHub Desktop.
Make transcripts from YouTube captions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
MIT License | |
Copyright (c) 2019 Zev Averbach | |
Permission is hereby granted, free of charge, to any person obtaining a copy | |
of this software and associated documentation files (the "Software"), to deal | |
in the Software without restriction, including without limitation the rights | |
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
copies of the Software, and to permit persons to whom the Software is | |
furnished to do so, subject to the following conditions: | |
The above copyright notice and this permission notice shall be included in all | |
copies or substantial portions of the Software. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
SOFTWARE. | |
This product includes youtube_transcript_api developed by Jonas Depoix, Copyright (c) 2018 Jonas Depoix | |
""" | |
import json | |
from typing import List, Optional, Dict, Union | |
from youtube_transcript_api import YouTubeTranscriptApi | |
from google_sheets import Sheet | |
PARAGRAPH_MAX_CHARS = 400 | |
TRANSCRIPT_IN_GOOGLE_SHEETS_RATE_LIMIT_NUM_CHARS = 1_000 | |
TRANSCRIPT_IN_GOOGLE_SHEETS_MAX_CHARS_PER_CELL = 50_000 | |
def get_json_transcript(video_id: str) -> dict: | |
return YouTubeTranscriptApi.get_transcript(video_id) | |
def make_paragraphs(transcript_json: dict) -> List[str]: | |
paragraphs = [] | |
paragraph = "" | |
for snip in transcript_json: | |
if paragraph == "": | |
space = "" | |
else: | |
space = " " | |
paragraph += f'{space}{snip["text"]}' | |
if len(paragraph) > PARAGRAPH_MAX_CHARS: | |
paragraphs.append(paragraph) | |
paragraph = "" | |
return paragraphs | |
def get_transcript_paragraphs(video_id: str) -> List[str]: | |
return make_paragraphs(get_json_transcript(video_id)) | |
def write_json(video_id: str, json_text: List[Dict[Union[str, float]]]): | |
json.dump(json_text, open(f"{video_id}.json", "w"), indent=4) | |
def write_paragraphs_to_file(video_id: str, paragraphs: List[str]): | |
with open(f"{video_id}.txt", "w") as fout: | |
fout.write("\n\n".join(paragraphs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment