slides_API_AI_anchor.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # In[13]:
  4. from __future__ import print_function
  5. import os.path
  6. from googleapiclient.discovery import build
  7. from google_auth_oauthlib.flow import InstalledAppFlow
  8. from google.auth.transport.requests import Request
  9. from google.oauth2.credentials import Credentials
  10. from google.oauth2 import service_account
  11. import argparse
  12. import requests
  13. import pprint
  14. import json
  15. import calendar
  16. import time
  17. import os
  18. import shutil
  19. from distutils.util import strtobool
  20. # If modifying these scopes, delete the file token.json.
  21. SCOPES = ['https://www.googleapis.com/auth/presentations.readonly',
  22. 'https://www.googleapis.com/auth/drive.metadata.readonly']
  23. def main(PRESENTATION_ID, save_to_local):
  24. """Shows basic usage of the Slides API.
  25. Prints the number of slides and elments in a sample presentation.
  26. """
  27. # # For personal account test
  28. # creds = None
  29. # # The file token.json stores the user's access and refresh tokens, and is
  30. # # created automatically when the authorization flow completes for the first
  31. # # time.
  32. # if os.path.exists('token.json'):
  33. # creds = Credentials.from_authorized_user_file('token.json', SCOPES)
  34. # # If there are no (valid) credentials available, let the user log in.
  35. # if not creds or not creds.valid:
  36. # if creds and creds.expired and creds.refresh_token:
  37. # creds.refresh(Request())
  38. # else:
  39. # flow = InstalledAppFlow.from_client_secrets_file(
  40. # 'credentials.json', SCOPES)
  41. # creds = flow.run_local_server(port=0)
  42. # # Save the credentials for the next run
  43. # with open('token.json', 'w') as token:
  44. # token.write(creds.to_json())
  45. credentials = service_account.Credentials.from_service_account_file('spread2.json')
  46. scoped_credentials = credentials.with_scopes(SCOPES)
  47. creds = credentials
  48. memo_list=[]
  49. img_list=[]
  50. def save_to_img(name, url):
  51. with open(name, 'wb') as handle:
  52. response = requests.get(url, stream=True)
  53. if not response.ok:
  54. print(response)
  55. for block in response.iter_content(1024):
  56. if not block:
  57. break
  58. handle.write(block)
  59. print('\t----> save to',name)
  60. def slide_info(PRESENTATION_ID):
  61. service = build('slides', 'v1', credentials=creds)
  62. # Call the Slides API
  63. presentation = service.presentations().get(
  64. presentationId=PRESENTATION_ID).execute()
  65. slides = presentation.get('slides')
  66. # Create the directory
  67. if save_to_local:
  68. dir = presentation['title']
  69. if os.path.exists(dir):
  70. shutil.rmtree(dir)
  71. os.makedirs(dir)
  72. print('The presentation contains {} slides:'.format(len(slides)))
  73. for i, slide in enumerate(slides):
  74. print('-'*80)
  75. print('Page #', i, ' ',slide['objectId'])
  76. # Check if the memo exists
  77. if 'text' in slide['slideProperties']['notesPage']['pageElements'][1]['shape'].keys():
  78. print('Memo:',end='')
  79. memo = slide['slideProperties']['notesPage']['pageElements'][1]['shape']['text']['textElements'][1]['textRun']['content']
  80. pprint.pprint(memo)
  81. memo_list.append(memo)
  82. # save to local txt file
  83. if save_to_local:
  84. with open('./'+dir+'/'+presentation['title']+'_'+str(i+1)+'.txt', "w") as text_file:
  85. text_file.write(memo)
  86. print('\t----> save to',presentation['title']+'_'+str(i+1)+'.txt')
  87. else:
  88. memo_list.append("")
  89. # Convert the content of the presentation to png
  90. thumbnail = service.presentations().pages().getThumbnail(presentationId=PRESENTATION_ID, pageObjectId=slide['objectId']).execute()
  91. pprint.pprint(thumbnail)
  92. img_list.append(thumbnail['contentUrl'])
  93. # save to local img file
  94. if save_to_local:
  95. save_to_img('./'+dir+'/'+presentation['title']+'_'+str(i+1)+'.png',thumbnail['contentUrl'])
  96. # data
  97. my_data = { "name": presentation['title'], "text_content": memo_list, "image_urls": img_list, "avatar": "7", "client_id": calendar.timegm(time.gmtime()) }
  98. # headers
  99. my_headers = {'accept': 'application/json',
  100. 'Content-Type': 'application/json; charset=UTF-8'}
  101. # Serializing json
  102. json_object = json.dumps(my_data, indent = 4)
  103. # post
  104. r = requests.post('http://www.choozmo.com:8888/make_anchor_video_v2', data = json_object, headers = my_headers)
  105. print(r)
  106. slide_info(PRESENTATION_ID)
  107. # # Find all presentations in the folder
  108. # service = build('drive', 'v2', credentials=creds)
  109. # children = service.children().list(
  110. # q="mimeType='application/vnd.google-apps.presentation'",
  111. # folderId=folderId).execute()
  112. # for child in children.get('items', []):
  113. # print('File Id: %s' % child['id'])
  114. # slide_info(child['id'])
  115. # print('='*80)
  116. if __name__ == '__main__':
  117. parser = argparse.ArgumentParser()
  118. parser.add_argument('--presentation_id', required=True)
  119. parser.add_argument('--save_to_local', required=False, default=True)
  120. args = parser.parse_args()
  121. main(str(args.presentation_id), strtobool(args.save_to_local))
  122. # for test
  123. # main('10KhVZes8N6ibHsrM8ZU2NuMDsl8AWk_PSdrtvdXr3Kw', True)