slides_API_AI_anchor.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # In[39]:
  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,eng):
  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. notes_list=[]
  49. sub_title_list=[]
  50. img_list=[]
  51. def save_to_img(name, url):
  52. with open(name, 'wb') as handle:
  53. response = requests.get(url, stream=True)
  54. if not response.ok:
  55. print(response)
  56. for block in response.iter_content(1024):
  57. if not block:
  58. break
  59. handle.write(block)
  60. print('\t----> save to',name)
  61. def slide_info(PRESENTATION_ID):
  62. service = build('slides', 'v1', credentials=creds)
  63. # Call the Slides API
  64. presentation = service.presentations().get(
  65. presentationId=PRESENTATION_ID).execute()
  66. slides = presentation.get('slides')
  67. # Create the directory
  68. if save_to_local:
  69. dir = presentation['title']
  70. if os.path.exists(dir):
  71. shutil.rmtree(dir)
  72. os.makedirs(dir)
  73. print('The presentation contains {} slides:'.format(len(slides)))
  74. for i, slide in enumerate(slides):
  75. print('-'*80)
  76. print('Page #', i, ' ',slide['objectId'])
  77. # Check if the notes exists
  78. if 'text' in slide['slideProperties']['notesPage']['pageElements'][1]['shape'].keys():
  79. notes = slide['slideProperties']['notesPage']['pageElements'][1]['shape']['text']['textElements'][1]['textRun']['content']
  80. # Check if the sub_title exists
  81. print(notes)
  82. print('[sub_title]' in notes)
  83. if '[sub_title]' in notes:
  84. sub_title = notes.split('[sub_title]')[1].strip()
  85. print('Sub_title:',end='')
  86. pprint.pprint(sub_title)
  87. sub_title_list.append(sub_title)
  88. # save to local txt file
  89. if '[sub_title]' in notes:
  90. with open('./'+dir+'/'+presentation['title']+'_sub_title_'+str(i+1)+'.txt', "w") as text_file:
  91. text_file.write(sub_title)
  92. print('\t----> save to',presentation['title']+'_sub_title_'+str(i+1)+'.txt')
  93. notes = notes.split('[sub_title]')[0].strip()
  94. print('Notes:',end='')
  95. pprint.pprint(notes)
  96. notes_list.append(notes)
  97. # save to local txt file
  98. if save_to_local:
  99. with open('./'+dir+'/'+presentation['title']+'_lines_'+str(i+1)+'.txt', "w") as text_file:
  100. text_file.write(notes)
  101. print('\t----> save to',presentation['title']+'_lines_'+str(i+1)+'.txt')
  102. else:
  103. notes_list.append("")
  104. # Convert the content of the presentation to png
  105. thumbnail = service.presentations().pages().getThumbnail(presentationId=PRESENTATION_ID, pageObjectId=slide['objectId']).execute()
  106. pprint.pprint(thumbnail)
  107. img_list.append(thumbnail['contentUrl'])
  108. # save to local img file
  109. if save_to_local:
  110. save_to_img('./'+dir+'/'+presentation['title']+'_'+str(i+1)+'.png',thumbnail['contentUrl'])
  111. # data
  112. my_data = { "name": presentation['title'], "text_content": notes_list, "image_urls": img_list, "avatar": "7", "client_id": calendar.timegm(time.gmtime()) }
  113. if eng:
  114. my_data['sub_titles'] = sub_title_list
  115. # headers
  116. my_headers = {'accept': 'application/json',
  117. 'Content-Type': 'application/json; charset=UTF-8'}
  118. # Serializing json
  119. json_object = json.dumps(my_data, indent = 4)
  120. # post
  121. if eng:
  122. r = requests.post('http://www.choozmo.com:8888/make_anchor_video_eng', data = json_object, headers = my_headers)
  123. else:
  124. r = requests.post('http://www.choozmo.com:8888/make_anchor_video_v2', data = json_object, headers = my_headers)
  125. print(r)
  126. slide_info(PRESENTATION_ID)
  127. # # Find all presentations in the folder
  128. # service = build('drive', 'v2', credentials=creds)
  129. # children = service.children().list(
  130. # q="mimeType='application/vnd.google-apps.presentation'",
  131. # folderId=folderId).execute()
  132. # for child in children.get('items', []):
  133. # print('File Id: %s' % child['id'])
  134. # slide_info(child['id'])
  135. # print('='*80)
  136. if __name__ == '__main__':
  137. parser = argparse.ArgumentParser()
  138. parser.add_argument('--presentation_id', required=True)
  139. parser.add_argument('--save_to_local', required=False, default=True)
  140. parser.add_argument('--eng', required=False, default=False)
  141. args = parser.parse_args()
  142. main(str(args.presentation_id), strtobool(args.save_to_local), strtobool(args.eng))
  143. # for test
  144. # main('1FWiSRq150AIEDx9uXWRi9Fj9FhyJAWQWt8iRu_h8KPc', True, True)