Skip to content

Commit c68aa2c

Browse files
"Added sample: python/captions.py"
1 parent 670a165 commit c68aa2c

1 file changed

Lines changed: 206 additions & 0 deletions

File tree

python/captions.py

Lines changed: 206 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,206 @@
1+
#!/usr/bin/python
2+
3+
# Usage example:
4+
# python captions.py --videoid='<video_id>' --name='<name>' --file='<file>' --language='<language>' --action='action'
5+
6+
import httplib2
7+
import os
8+
import sys
9+
10+
from apiclient.discovery import build_from_document
11+
from apiclient.errors import HttpError
12+
from oauth2client.client import flow_from_clientsecrets
13+
from oauth2client.file import Storage
14+
from oauth2client.tools import argparser, run_flow
15+
16+
17+
# The CLIENT_SECRETS_FILE variable specifies the name of a file that contains
18+
19+
# the OAuth 2.0 information for this application, including its client_id and
20+
# client_secret. You can acquire an OAuth 2.0 client ID and client secret from
21+
# the {{ Google Cloud Console }} at
22+
# {{ https://cloud.google.com/console }}.
23+
# Please ensure that you have enabled the YouTube Data API for your project.
24+
# For more information about using OAuth2 to access the YouTube Data API, see:
25+
# https://developers.google.com/youtube/v3/guides/authentication
26+
# For more information about the client_secrets.json file format, see:
27+
# https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
28+
CLIENT_SECRETS_FILE = "client_secrets.json"
29+
30+
# This OAuth 2.0 access scope allows for full read/write access to the
31+
# authenticated user's account and requires requests to use an SSL connection.
32+
YOUTUBE_READ_WRITE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
33+
YOUTUBE_API_SERVICE_NAME = "youtube"
34+
YOUTUBE_API_VERSION = "v3"
35+
36+
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
37+
# missing.
38+
MISSING_CLIENT_SECRETS_MESSAGE = """
39+
WARNING: Please configure OAuth 2.0
40+
41+
To make this sample run you will need to populate the client_secrets.json file
42+
found at:
43+
%s
44+
with information from the APIs Console
45+
https://developers.google.com/console
46+
47+
For more information about the client_secrets.json file format, please visit:
48+
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
49+
""" % os.path.abspath(os.path.join(os.path.dirname(__file__),
50+
CLIENT_SECRETS_FILE))
51+
52+
# Authorize the request and store authorization credentials.
53+
def get_authenticated_service(args):
54+
flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_READ_WRITE_SSL_SCOPE,
55+
message=MISSING_CLIENT_SECRETS_MESSAGE)
56+
57+
storage = Storage("%s-oauth2.json" % sys.argv[0])
58+
credentials = storage.get()
59+
60+
if credentials is None or credentials.invalid:
61+
credentials = run_flow(flow, storage, args)
62+
63+
# Trusted testers can download this discovery document from the developers page
64+
# and it should be in the same directory with the code.
65+
with open("youtube-v3-api-captions.json", "r") as f:
66+
doc = f.read()
67+
return build_from_document(doc, http=credentials.authorize(httplib2.Http()))
68+
69+
70+
# Call the API's captions.list method to list the existing caption tracks.
71+
def list_captions(youtube, video_id):
72+
results = youtube.captions().list(
73+
part="snippet",
74+
videoId=video_id
75+
).execute()
76+
77+
for item in results["items"]:
78+
id = item["id"]
79+
name = item["snippet"]["name"]
80+
language = item["snippet"]["language"]
81+
print "Caption track '%s(%s)' in '%s' language." % (name, id, language)
82+
83+
return results["items"]
84+
85+
86+
# Call the API's captions.insert method to upload a caption track in draft status.
87+
def upload_caption(youtube, video_id, language, name, file):
88+
insert_result = youtube.captions().insert(
89+
part="snippet",
90+
body=dict(
91+
snippet=dict(
92+
videoId=video_id,
93+
language=language,
94+
name=name,
95+
isDraft=True
96+
)
97+
),
98+
media_body=file
99+
).execute()
100+
101+
id = insert_result["id"]
102+
name = insert_result["snippet"]["name"]
103+
language = insert_result["snippet"]["language"]
104+
status = insert_result["snippet"]["status"]
105+
print "Uploaded caption track '%s(%s) in '%s' language, '%s' status." % (name,
106+
id, language, status)
107+
108+
109+
# Call the API's captions.update method to update an existing caption track's draft status
110+
# and publish it. If a new binary file is present, update the track with the file as well.
111+
def update_caption(youtube, caption_id, file):
112+
update_result = youtube.captions().update(
113+
part="snippet",
114+
body=dict(
115+
id=caption_id,
116+
snippet=dict(
117+
isDraft=False
118+
)
119+
),
120+
media_body=file
121+
).execute()
122+
123+
name = update_result["snippet"]["name"]
124+
isDraft = update_result["snippet"]["isDraft"]
125+
print "Updated caption track '%s' draft status to be: '%s'" % (name, isDraft)
126+
if file:
127+
print "and updated the track with the new uploaded file."
128+
129+
130+
# Call the API's captions.download method to download an existing caption track.
131+
def download_caption(youtube, caption_id, tfmt):
132+
subtitle = youtube.captions().download(
133+
id=caption_id,
134+
tfmt=tfmt
135+
).execute()
136+
137+
print "First line of caption track: %s" % (subtitle)
138+
139+
# Call the API's captions.delete method to delete an existing caption track.
140+
def delete_caption(youtube, caption_id):
141+
youtube.captions().delete(
142+
id=caption_id
143+
).execute()
144+
145+
print "caption track '%s' deleted succesfully" % (caption_id)
146+
147+
148+
if __name__ == "__main__":
149+
# The "videoid" option specifies the YouTube video ID that uniquely
150+
# identifies the video for which the caption track will be uploaded.
151+
argparser.add_argument("--videoid",
152+
help="Required; ID for video for which the caption track will be uploaded.")
153+
# The "name" option specifies the name of the caption trackto be used.
154+
argparser.add_argument("--name", help="Caption track name", default="YouTube for Developers")
155+
# The "file" option specifies the binary file to be uploaded as a caption track.
156+
argparser.add_argument("--file", help="Captions track file to upload")
157+
# The "language" option specifies the language of the caption track to be uploaded.
158+
argparser.add_argument("--language", help="Caption track language", default="en")
159+
# The "captionid" option specifies the ID of the caption track to be processed.
160+
argparser.add_argument("--captionid", help="Required; ID of the caption track to be processed")
161+
# The "action" option specifies the action to be processed.
162+
argparser.add_argument("--action", help="Action", default="all")
163+
164+
165+
args = argparser.parse_args()
166+
167+
if (args.action in ('upload', 'list', 'all')):
168+
if not args.videoid:
169+
exit("Please specify videoid using the --videoid= parameter.")
170+
171+
if (args.action in ('update', 'download', 'delete')):
172+
if not args.captionid:
173+
exit("Please specify captionid using the --captionid= parameter.")
174+
175+
if (args.action in ('upload', 'all')):
176+
if not args.file:
177+
exit("Please specify a caption track file using the --file= parameter.")
178+
if not os.path.exists(args.file):
179+
exit("Please specify a valid file using the --file= parameter.")
180+
181+
youtube = get_authenticated_service(args)
182+
try:
183+
if args.action == 'upload':
184+
upload_caption(youtube, args.videoid, args.language, args.name, args.file)
185+
elif args.action == 'list':
186+
list_captions(youtube, args.videoid)
187+
elif args.action == 'update':
188+
update_caption(youtube, args.captionid, args.file);
189+
elif args.action == 'download':
190+
download_caption(youtube, args.captionid, 'srt')
191+
elif args.action == 'delete':
192+
delete_caption(youtube, args.captionid);
193+
else:
194+
# All the available methods are used in sequence just for the sake of an example.
195+
upload_caption(youtube, args.videoid, args.language, args.name, args.file)
196+
captions = list_captions(youtube, args.videoid)
197+
198+
if captions:
199+
first_caption_id = captions[0]['id'];
200+
update_caption(youtube, first_caption_id, None);
201+
download_caption(youtube, first_caption_id, 'srt')
202+
delete_caption(youtube, first_caption_id);
203+
except HttpError, e:
204+
print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)
205+
else:
206+
print "Created and managed caption tracks."

0 commit comments

Comments
 (0)