youtube-transcript-api icon indicating copy to clipboard operation
youtube-transcript-api copied to clipboard

Can it be used with private videos?

Open bml1g12 opened this issue 6 years ago • 10 comments

Can this be used with private videos?

I tried the approach here https://github.com/jdepoix/youtube-transcript-api#cookies

And when providing the video id as a list got "The video is no longer available" and when providing the video id as a string got "Subtitles are disabled for this video". I can view the automatically generated transcript; so subtitles are enabled I think. I am the video author.

bml1g12 avatar Aug 25 '20 14:08 bml1g12

I have never tried this before to be honest, however I would expect it to work, using the cookie feature you mentioned.

I'll have to try this myself to replicate the error. I am quite busy atm, so it'll probably take me a while until I can take some time to dig deeper into this. @danielcliu since you implemented the cookie feature: you got any ideas on this?

jdepoix avatar Aug 25 '20 15:08 jdepoix

I see, thanks for any help with this! I noticed the official API allows downloads of captions of one's own data, so in case it useful to anyone else in the same situation you can use this: https://developers.google.com/youtube/v3/docs/captions/download

Albeit setting up the Google API OAuth etc. etc. is a real pain, took me many hours and haven't figured out how to use it without manual steps yet, so imagine youtube-transcript-api with cookies would be easier even after implementing this!

bml1g12 avatar Aug 25 '20 15:08 bml1g12

Uh I didn't realize i was in the wrong account. I have been wrapped in a lot of other things due to the times and haven't been checking this repo as much as I should. I am a bit confused, have you tried with cookies yet? I would imagine it would recognize you as the videos owner if you had, but I haven't tested that. If you haven't I can test this later. Also if you are using python I could help you use the Youtube Data Api if you'd like, although I'm not sure this board is the right place to provide that help.

danielcliu avatar Aug 27 '20 17:08 danielcliu

Yes I did try with the cookies approach and got the above error.

Thanks that's very kind to offer to help, I have a working script that uses the official Python API now, but one challenge I have is that it asks my to authorize my account every time I run it (to go to a URL and get a token) which is quite time consuming. I'm not familiar enough with Google cloud to know how to get it to remember that my "app" is authorised to view my private YouTube videos.

I expect the cookies approach with your API would be easier for many users than dealing with all the Google cloud complexities

bml1g12 avatar Aug 28 '20 10:08 bml1g12

@bml1g12 I tried with cookies and was able to grab captions from a private video I owned. So I would redownload your cookies try again with that and if it doesn 't let me know and we'll try to figure this out. What version of this library are you using? What python version?

In terms of your frustrations with the Youtube Data API, I believe to avoid OAuth2'ing every time I pickled my credentials and loaded them in when necessary. Youtube will refresh expired tokens so I remember it working for a long time.

danielcliu avatar Aug 30 '20 00:08 danielcliu

@danielcliu thanks for taking the time to do the testing!

jdepoix avatar Aug 31 '20 10:08 jdepoix

Thanks indeed!

from youtube_transcript_api import YouTubeTranscriptApi
transcript = YouTubeTranscriptApi.get_transcript(
    "ti-O2Gk1DKo",
    cookies='peterlowe_raw_transcript.txt')

Was my script; does that look correct? The "ti-O2Gk1DKo" came from the URL and the .txt file came from the README suggested browser extension from firefox.

I was using Python 3.7.6 with youtube-transcript-api==0.3.1.

Ah pickling the credentials sounds like a good solution here; do you have a code snippet for that? (i.e. to serialize the credentials).

bml1g12 avatar Sep 02 '20 09:09 bml1g12

@bml1g12 Sorry for such a long wait

I'm not sure why you're having difficulties. I am running python 3.6.9 and youtube-transcript-api==0.3.1 and I was able to get it to reach a private vid. I'm not sure how to manage python versions and there are packages I need to run in 3.6, but I doubt its the python version number that is causing the error. I have to ask because of the name, the file peterlowe_raw_transcript.txt contains the cookies from your browser when you can view the private video right? Because that name implies it holds a transcript. In addition, is that file in the directory you are running this script? If it is not it may be messing up the import or something. You aren't getting and FileNotFoundErrors when you run this right?

For context this is my code that worked.

from youtube_transcript_api import YouTubeTranscriptApi

video_id = 'hE6a-5fB83w'
cookies = 'cookies.txt'
x = YouTubeTranscriptApi.get_transcript(video_id, cookies = cookies)
print(x)

danielcliu avatar Sep 21 '20 00:09 danielcliu

@bml1g12 As for the pickling, I'm not sure off top honestly cause its been a while but I think I pickled the flow like in the example docs when you flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(client_secrets_file, scopes) I would pickle the flow object into a file and then load it on subsequent runs if that file wasn't empty.

danielcliu avatar Sep 21 '20 00:09 danielcliu

Yes its a file from the firefox plugin cookies.txt with the first few lines like the below (... representing more text I have omitted):

# Netscape HTTP Cookie File
# https://curl.haxx.se/rfc/cookie_spec.html
# This is a generated file! Do not edit.

#HttpOnly_.youtube.com ...

Tried

from youtube_transcript_api import YouTubeTranscriptApi

video_id = 'YXR58zm86kM'
cookies = 'cookies.txt'
x = YouTubeTranscriptApi.get_transcript(video_id, cookies = cookies)
print(x)

With youtube-transcript-api==0.3.1
Python 3.7.6

And I get

(thriai) F:\Archived Photo\Family\Family History\DadInterview\24thMayPart1>python youtubeapipythonplugin.py Traceback (most recent call last): File "youtubeapipythonplugin.py", line 5, in <module> x = YouTubeTranscriptApi.get_transcript(video_id, cookies = cookies) File "C:\Users\Ben\.conda\envs\thriai\lib\site-packages\youtube_transcript_api\_api.py", line 128, in get_transcript return cls.list_transcripts(video_id, proxies, cookies).find_transcript(languages).fetch() File "C:\Users\Ben\.conda\envs\thriai\lib\site-packages\youtube_transcript_api\_api.py", line 70, in list_transcripts return TranscriptListFetcher(http_client).fetch(video_id) File "C:\Users\Ben\.conda\envs\thriai\lib\site-packages\youtube_transcript_api\_transcripts.py", line 34, in fetch self._extract_captions_json(self._fetch_html(video_id), video_id) File "C:\Users\Ben\.conda\envs\thriai\lib\site-packages\youtube_transcript_api\_transcripts.py", line 44, in _extract_captions_json raise TranscriptsDisabled(video_id) youtube_transcript_api._errors.TranscriptsDisabled: Could not retrieve a transcript for the video https://www.youtube.com/watch?v=YXR58zm86kM! This is most likely caused by: Subtitles are disabled for this video If you are sure that the described cause is not responsible for this error and that a transcript should be retrievable, please create an issue at https://github.com/jdepoix/youtube-transcript-api/issues. Please add which version of youtube_transcript_api you are using and provide the information needed to replicate the error. Also make sure that there are no open issues which already describe your problem!

Regardless, I will close this ticket as I have found another couple of ways to get transcript.

In case it is of interest to others how I did this:

The first way I tried was via the Google speech_v1.SpeechClient() Speech To Text api (transcribe.zip attached) on the raw video file transcribe.zip

But bizarrely no matter what parameters I chose, the accuracy was far worse than youtube transcription. So the second way was simply to open the transcript in the yuotube GUI, copy-paste it to a .txt file and run a little script to parse it:

import pandas as pd
def extract(filename, speaker):
    a_file = open(filename)
    file_contents = a_file.read()
    timestamp_string_pair_list = [i.split("\n") for i in file_contents.rstrip().split("\n\n")]
    dict_list = []
    for timestamp, sentence in  timestamp_string_pair_list:
        timestamp_from, timestamp_to = timestamp.split(",")
        dict_list.append({"speaker": speaker, "timestamp_from": timestamp_from,
                          "timestamp_to": timestamp_to, "sentence": sentence})
    return dict_list

dict_list = extract("benlowe_downloaded_mytranscript.txt", speaker="Ben")
dict_list.extend(extract("peterlowe_downloaded_mytranscript.txt", speaker="Peter"))

df = pd.DataFrame(dict_list)
df["timestamp_to"] = pd.to_datetime(df["timestamp_to"])
df["timestamp_from"] = pd.to_datetime(df["timestamp_from"])
df = df.sort_values("timestamp_from")

speaker = None
sentences = ""
for index, row in df.iterrows():
    from_timestamp_seconds = row["timestamp_from"].ctime().split(" ")[-2]
    if row["speaker"] != speaker:
        print(speaker, ":", from_timestamp_seconds, ":", sentences, "\n")
        speaker = row["speaker"]
        sentences = ""
        print()
    sentences += " " + row["sentence"]

And this works nicely. Here I have a video with audio for each speaker, so can nicely separate the transcript by speaker as an added bonus.

bml1g12 avatar Sep 27 '20 05:09 bml1g12