aecpic/aecpic.py
2025-02-02 06:54:31 +09:00

126 lines
3.1 KiB
Python
Executable file

#!/usr/bin/env PYTHONUTF8=1 python3
'''
get a picture at some url in use curl, then open new anvil window and set the picture to background picture on to the window.
author: moli
'''
import os
import subprocess
import tempfile
import requests
import json
import mimetypes
from PIL import Image
import argparse
def getSuffix(url):
'''
get the suffix in the url.
>>> import apcpic
>>> apcpic.getSuffix('https://moli-green.xyz/img.webp')
'.webp'
'''
mimetype = mimetypes.guess_type(url)
match mimetype:
case 'image/png', encoding:
return '.png'
case 'image/jpeg', encoding:
return '.jpeg'
case 'image/webp', encoding:
return '.webp'
case 'image/avif', encoding:
return '.avif'
case 'image/gif', encoding:
return '.gif'
case _:
raise RuntimeError('this image type not supported.')
def download(url):
'''
download the iamge file to the temporary file.
>>> import apcpic
>>> r = apcpic.download('https://moli-green.xyz/img.webp')
>>> if r != '':
... pass
'''
suffix = getSuffix(url)
filename = ''
with tempfile.NamedTemporaryFile(
mode='wb',
delete=False,
suffix=suffix) as f:
r = subprocess.run(['curl', url], capture_output = True)
f.write(r.stdout)
filename = f.name
return filename
def getPNG(url):
'''
get PNG file path.
>>> import apcpic
>>> r = apcpic.getPNG('https://moli-green.xyz/img.webp')
>>> if r != '':
... pass
'''
png_filename = ''
with tempfile.NamedTemporaryFile(
mode='wb',
delete=False,
suffix='.png') as f:
png_filename = f.name
filename = download(url)
# print(filename)
img = Image.open(filename)
img.save(png_filename)
return png_filename
def anvil_Pic(host='localhost', url=None):
'''
Pic command send to Anvil.
'''
if not url:
raise RuntimeError('not have url.')
if 'ANVIL_API_PORT' not in os.environ:
raise RuntimeError('not in Anvil')
filename = getPNG(url)
ANVIL_API_PORT = os.environ['ANVIL_API_PORT']
ANVIL_API_SESS = os.environ['ANVIL_API_SESS']
ANVIL_WIN_ID = os.environ['ANVIL_WIN_ID']
if ANVIL_WIN_ID == '':
raise RuntimeError('not on window.')
h = {
'Anvil-Sess': ANVIL_API_SESS,
'Accept': 'application/json',
}
d = {
'Winid': int(ANVIL_WIN_ID),
'Cmd': 'Pic',
'Args': [filename, 'fit'],
}
s = f'http://{host}:{int(ANVIL_API_PORT)}/execute'
r = requests.post(s, headers=h, data=json.dumps(d))
if r.status_code != requests.codes.ok:
raise RuntimeError(f'status code: {r.status_code}')
if __name__ == '__main__':
p = argparse.ArgumentParser(
description='Downlowad Url Image and Set Anvil Picture.')
p.add_argument('--host', default='localhost', help='Hostname')
p.add_argument('url', help='Image URL')
arg = p.parse_args()
anvil_Pic(arg.host, arg.url)