import os 
import time
import requests
from PIL import Image
import threading
class swap_face():
    def __init__(self, imgurl):
        self.imgurl = imgurl
    def run(self):
        name_hash = str(time.time()).replace('.','')
        src_img = 'FaceSwap/src_img/'+name_hash+'.jpg'
        sv_path = '/var/www/html/swap_save/'+name_hash+'.avi'
        print(name_hash)
        
        try:
            im = Image.open(requests.get(self.imgurl, stream=True).raw)
            im= im.convert("RGB")
            im.save(src_img)
        except:
            return {'msg':'圖片錯誤'}
        
        x = threading.Thread(target=self.runthreadswap, args=(src_img,sv_path))
        x.start()
        time.sleep(20)
        load_time = 0
        while True:
            print('waiting...')
            if os.path.exists(sv_path):
                break
            time.sleep(10)
            load_time+=10
        
            print('waiting...')
        self.notify_group('人物生成成功,在:www.choozmo.com:8168/swap_save/'+name_hash+'.avi')
        return {'msg':'生成中,成果會在line中展示'}

    def runthreadswap(self,src_img,sv_path):
        os.system('python3 FaceSwap/main_video.py --src_img '+src_img+' --video_path ./FaceSwap/b1.mp4 --correct_color --save_path '+sv_path)    
        

    def notify_group(self,msg):
        headers = {
                "Authorization": "Bearer " + "WekCRfnAirSiSxALiD6gcm0B56EejsoK89zFbIaiZQD",
                "Content-Type": "application/x-www-form-urlencoded"
        }
        params = {"message": msg}   
        r = requests.post("https://notify-api.line.me/api/notify",headers=headers, params=params)
        #print(r)