"""Python 3, standard library only. ACTION=me|search|download|image.""" import os,json,urllib.request,urllib.parse,urllib.error base=os.environ.get('MOTIONGIT_BASE_URL','http://127.0.0.1:8095').rstrip('/') key=os.environ['MOTIONGIT_API_KEY'];action=os.environ.get('ACTION','me') routes={'me':'/api/v1/me','search':'/api/v1/stickers/search?'+urllib.parse.urlencode({'q':os.environ.get('QUERY','增长'),'limit':5}),'download':'/api/v1/stickers/'+urllib.parse.quote(os.environ.get('PRESET','growth'),safe=''),'image':'/api/v1/images'} headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'} body=json.dumps({'prompt':os.environ.get('PROMPT','清晨城市天际线'),'size':'1536x1024'}).encode() if action=='image' else None try: response=urllib.request.urlopen(urllib.request.Request(base+routes[action],data=body,headers=headers),timeout=65) except urllib.error.HTTPError as error: response=error with response: status=response.status;result=json.load(response) print(json.dumps({'status':status,'body':result},ensure_ascii=False,indent=2)) if status>=400: if status==503 and result.get('error',{}).get('code')=='not_enabled': print('生图内测未启用,本次没有扣点。') else: raise SystemExit(1) elif action=='download': with open(os.environ.get('OUTPUT','sticker.json'),'w') as file: json.dump(result,file) elif action=='image': if urllib.parse.urlsplit(result['url']).netloc!=urllib.parse.urlsplit(base).netloc: raise ValueError('Unexpected asset origin') with urllib.request.urlopen(urllib.request.Request(result['url'],headers=headers),timeout=65) as image,open(os.environ.get('OUTPUT','generated.png'),'wb') as file: file.write(image.read())