瀏覽代碼

adjust slide

ming 3 年之前
父節點
當前提交
7909b28d7e
共有 3 個文件被更改,包括 77 次插入103 次删除
  1. 44 103
      api/gSlide.py
  2. 30 0
      api/main.py
  3. 3 0
      api/models.py

+ 44 - 103
api/gSlide.py

@@ -17,12 +17,26 @@ import os
 import shutil
 import shutil
 from distutils.util import strtobool
 from distutils.util import strtobool
 
 
-# If modifying these scopes, delete the file token.json.
 SCOPES = ['https://www.googleapis.com/auth/presentations.readonly',
 SCOPES = ['https://www.googleapis.com/auth/presentations.readonly',
           'https://www.googleapis.com/auth/drive.metadata.readonly']
           'https://www.googleapis.com/auth/drive.metadata.readonly']
 
 
-def main(PRESENTATION_ID, save_to_local,eng):
+dir_sound = 'mp3_track/'
+dir_photo = 'photo/'
+dir_text = 'text_file/'
+dir_video = 'video_material/'
+dir_title = 'title/'
+dir_subtitle = 'subtitle/'
+dir_anchor = 'anchor_raw/'
+tmp_video_dir = 'tmp_video/'
+video_sub_folder = 'ai_anchor_video/'
 
 
+def parse_url(url):
+    #https://docs.google.com/presentation/d/17jJ3OZWh8WorFcolB_LiTa7xQ3R-xrmFlqJ_EyCj06M/edit#slide=id.p
+    url = url.replace('')
+    return url.split('/')[5]
+
+def parse_slide_url(slide_url,eng):
+    PRESENTATION_ID = parse_url(slide_url)
     credentials = service_account.Credentials.from_service_account_file('spread2.json')
     credentials = service_account.Credentials.from_service_account_file('spread2.json')
     scoped_credentials = credentials.with_scopes(SCOPES)
     scoped_credentials = credentials.with_scopes(SCOPES)
     creds = credentials
     creds = credentials
@@ -31,108 +45,35 @@ def main(PRESENTATION_ID, save_to_local,eng):
     sub_title_list=[]
     sub_title_list=[]
     img_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)
+    service = build('slides', 'v1', credentials=creds)
         # Call the Slides API
         # 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)
-        
+    presentation = service.presentations().get(
+        presentationId=PRESENTATION_ID).execute()
+    slides = presentation.get('slides')
         
         
-        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("")
+    for i, slide in enumerate(slides):
+        # 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']
+            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)
+                notes = notes.split('[sub_title]')[0].strip()
+            pprint.pprint(notes)
+            notes_list.append(notes)  
+        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'])
+        # 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)
-    
+    # data
+    slide_content = { "name": presentation['title'], "text_content": notes_list, "image_urls": img_list, "avatar": "7", "client_id": calendar.timegm(time.gmtime()) }
+    if eng:
+        slide_content['sub_titles'] = sub_title_list
+    return slide_content
+        

+ 30 - 0
api/main.py

@@ -40,6 +40,7 @@ import mailer
 from moviepy.editor import VideoFileClip
 from moviepy.editor import VideoFileClip
 import traceback
 import traceback
 import logging
 import logging
+import gSlide
 pymysql.install_as_MySQLdb()
 pymysql.install_as_MySQLdb()
 
 
 app = FastAPI()
 app = FastAPI()
@@ -208,6 +209,35 @@ async def create_upload_file(file: UploadFile = File(...)):
         return {'msg':'檔案無法使用'}
         return {'msg':'檔案無法使用'}
     return {"msg": 'www.choozmo.com:8168/'+tmp_img_sub_folder+img_name+'.jpg'}
     return {"msg": 'www.choozmo.com:8168/'+tmp_img_sub_folder+img_name+'.jpg'}
 
 
+@app.post("/make_anchor_video_gSlide")
+async def make_anchor_video_gSlide(req:models.gSlide_req,token: str = Depends(oauth2_scheme)):
+    gSlide.parse_slide_url()
+    if len(image_urls) != len(text_content):
+        return {'msg':'副標題數量、圖片(影片)數量以及台詞數量必須一致'}
+    for idx in range(len(image_urls)):
+        if 'http' not in image_urls[idx]:
+            image_urls[idx] = 'http://'+image_urls[idx]
+    if multiLang==0:
+        for txt in text_content:
+            if re.search('[a-zA-Z]', txt) !=None:
+                print('語言錯誤')
+                return {'msg':'輸入字串不能包含英文字!'}
+    name_hash = str(time.time()).replace('.','')
+    for imgu in image_urls:
+        try:
+            if get_url_type(imgu) =='video/mp4':
+                r=requests.get(imgu)
+            else:
+                im = Image.open(requests.get(imgu, stream=True).raw)
+                im= im.convert("RGB")
+        except:
+            return {'msg':"無法辨別圖片網址"+imgu}
+    user_id = get_user_id(token)
+    save_history(req,name_hash,user_id)
+    x = threading.Thread(target=gen_video_queue, args=(name_hash,name, text_content, image_urls,int(avatar),multiLang,user_id))
+    x.start()
+    return {"msg":"製作影片需要時間,請您耐心等候,成果會傳送至LINE群組中"} 
+
 @app.post("/make_anchor_video")
 @app.post("/make_anchor_video")
 async def make_anchor_video(req:models.request,token: str = Depends(oauth2_scheme)):
 async def make_anchor_video(req:models.request,token: str = Depends(oauth2_scheme)):
     if len(req.image_urls) != len(req.text_content):
     if len(req.image_urls) != len(req.text_content):

+ 3 - 0
api/models.py

@@ -17,6 +17,9 @@ class request(BaseModel):
     client_id :str
     client_id :str
     multiLang :int
     multiLang :int
 
 
+class gSlide_req(BaseModel):
+    slide_url: str
+
 class request_eng(BaseModel):
 class request_eng(BaseModel):
     name: str
     name: str
     text_content: List[str]
     text_content: List[str]