123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185 |
- #!/usr/bin/env python
- # coding: utf-8
- # In[39]:
- from __future__ import print_function
- import os.path
- from googleapiclient.discovery import build
- from google_auth_oauthlib.flow import InstalledAppFlow
- from google.auth.transport.requests import Request
- from google.oauth2.credentials import Credentials
- from google.oauth2 import service_account
- import argparse
- import requests
- import pprint
- import json
- import calendar
- import time
- import os
- import shutil
- from distutils.util import strtobool
- # If modifying these scopes, delete the file token.json.
- SCOPES = ['https://www.googleapis.com/auth/presentations.readonly',
- 'https://www.googleapis.com/auth/drive.metadata.readonly']
- def main(PRESENTATION_ID, save_to_local,eng):
- """Shows basic usage of the Slides API.
- Prints the number of slides and elments in a sample presentation.
- """
- # # For personal account test
- # creds = None
- # # The file token.json stores the user's access and refresh tokens, and is
- # # created automatically when the authorization flow completes for the first
- # # time.
- # if os.path.exists('token.json'):
- # creds = Credentials.from_authorized_user_file('token.json', SCOPES)
- # # If there are no (valid) credentials available, let the user log in.
- # if not creds or not creds.valid:
- # if creds and creds.expired and creds.refresh_token:
- # creds.refresh(Request())
- # else:
- # flow = InstalledAppFlow.from_client_secrets_file(
- # 'credentials.json', SCOPES)
- # creds = flow.run_local_server(port=0)
- # # Save the credentials for the next run
- # with open('token.json', 'w') as token:
- # token.write(creds.to_json())
- credentials = service_account.Credentials.from_service_account_file('spread2.json')
- scoped_credentials = credentials.with_scopes(SCOPES)
- creds = credentials
- notes_list=[]
- sub_title_list=[]
- img_list=[]
- def save_to_img(name, url):
- with open(name, 'wb') as handle:
- response = requests.get(url, stream=True)
- if not response.ok:
- print(response)
- for block in response.iter_content(1024):
- if not block:
- break
- handle.write(block)
- print('\t----> save to',name)
-
-
- def slide_info(PRESENTATION_ID):
- service = build('slides', 'v1', credentials=creds)
- # Call the Slides API
- presentation = service.presentations().get(
- presentationId=PRESENTATION_ID).execute()
- slides = presentation.get('slides')
-
- # Create the directory
- if save_to_local:
- dir = presentation['title']
- if os.path.exists(dir):
- shutil.rmtree(dir)
- os.makedirs(dir)
-
-
- print('The presentation contains {} slides:'.format(len(slides)))
- for i, slide in enumerate(slides):
- print('-'*80)
- print('Page #', i, ' ',slide['objectId'])
- # Check if the notes exists
- if 'text' in slide['slideProperties']['notesPage']['pageElements'][1]['shape'].keys():
-
- notes = slide['slideProperties']['notesPage']['pageElements'][1]['shape']['text']['textElements'][1]['textRun']['content']
-
- # Check if the sub_title exists
- print(notes)
- print('[sub_title]' in notes)
- if '[sub_title]' in notes:
- sub_title = notes.split('[sub_title]')[1].strip()
- print('Sub_title:',end='')
- pprint.pprint(sub_title)
- sub_title_list.append(sub_title)
-
- # save to local txt file
- if '[sub_title]' in notes:
- with open('./'+dir+'/'+presentation['title']+'_sub_title_'+str(i+1)+'.txt', "w") as text_file:
- text_file.write(sub_title)
- print('\t----> save to',presentation['title']+'_sub_title_'+str(i+1)+'.txt')
-
- notes = notes.split('[sub_title]')[0].strip()
-
- print('Notes:',end='')
- pprint.pprint(notes)
- notes_list.append(notes)
-
- # save to local txt file
- if save_to_local:
- with open('./'+dir+'/'+presentation['title']+'_lines_'+str(i+1)+'.txt', "w") as text_file:
- text_file.write(notes)
- print('\t----> save to',presentation['title']+'_lines_'+str(i+1)+'.txt')
-
- else:
- notes_list.append("")
-
- # Convert the content of the presentation to png
- thumbnail = service.presentations().pages().getThumbnail(presentationId=PRESENTATION_ID, pageObjectId=slide['objectId']).execute()
- pprint.pprint(thumbnail)
- img_list.append(thumbnail['contentUrl'])
-
- # save to local img file
- if save_to_local:
- save_to_img('./'+dir+'/'+presentation['title']+'_'+str(i+1)+'.png',thumbnail['contentUrl'])
-
-
- # data
- my_data = { "name": presentation['title'], "text_content": notes_list, "image_urls": img_list, "avatar": "7", "client_id": calendar.timegm(time.gmtime()) }
- if eng:
- my_data['sub_titles'] = sub_title_list
-
-
-
- # headers
- my_headers = {'accept': 'application/json',
- 'Content-Type': 'application/json; charset=UTF-8'}
-
- # Serializing json
- json_object = json.dumps(my_data, indent = 4)
-
-
- # post
- if eng:
- r = requests.post('http://www.choozmo.com:8888/make_anchor_video_eng', data = json_object, headers = my_headers)
- else:
- r = requests.post('http://www.choozmo.com:8888/make_anchor_video_v2', data = json_object, headers = my_headers)
- print(r)
-
- slide_info(PRESENTATION_ID)
-
-
- # # Find all presentations in the folder
- # service = build('drive', 'v2', credentials=creds)
- # children = service.children().list(
- # q="mimeType='application/vnd.google-apps.presentation'",
- # folderId=folderId).execute()
- # for child in children.get('items', []):
- # print('File Id: %s' % child['id'])
- # slide_info(child['id'])
- # print('='*80)
-
-
- if __name__ == '__main__':
- parser = argparse.ArgumentParser()
- parser.add_argument('--presentation_id', required=True)
- parser.add_argument('--save_to_local', required=False, default=True)
- parser.add_argument('--eng', required=False, default=False)
- args = parser.parse_args()
- main(str(args.presentation_id), strtobool(args.save_to_local), strtobool(args.eng))
- # for test
- # main('1FWiSRq150AIEDx9uXWRi9Fj9FhyJAWQWt8iRu_h8KPc', True, True)
|