test_demo / playform.py
elgammal's picture
fix header
144841b
# this is to test actual playform
import functools
import requests
from requests.exceptions import RequestException
import io
import numpy
from PIL import Image
# change this url to staging server or production server url
api_url_base = "https://stage.playform.io/api/app/projects/"
api_url_tail = "/generate/"
playform_load = """
function(url_params) {
console.log(url_params);
const params = new URLSearchParams(window.location.search);
url_params = Object.fromEntries(params);
return [url_params];
}
"""
def get_session_param(param):
api_url = ""
token = ""
try:
if isinstance(param,list):
api_url=api_url_base+str(param[0]["id"])+api_url_tail
token = param[0]["token"]
#token = token[4:]
except:
pass
return api_url, token
def prep_image(image):
# takes a numpy image and prepare it to be sent
if image.dtype == numpy.uint8:
img = Image.fromarray(image)
else:
img = Image.fromarray((image*255).astype(numpy.uint8))
return img
def send_image(img,api_url,token):
# takes a PIL image and send it
output=io.BytesIO()
img.save(output, format='JPEG')
f=output.getvalue()
files = [('image',('image.jpg',f,'image/jpeg'))]
# Set the headers for the request
headers = {'Authorization': f'{token}'}
payload = {}
print(api_url,token)
print(f'header: {headers}')
try:
response = requests.post(api_url,data=payload, headers=headers,files = files)
response.raise_for_status()
print("request sent")
print(response.text)
except RequestException as e:
print('Request failed:', e)
return
def playform(func):
@functools.wraps(func)
def wrapper_playform(*args, **kwargs):
ret_value = func(*args, **kwargs)
#print(f'return type {type(ret_value)}')
value = ret_value[0]
# print(f'input type: {type(args)}')
# param= args[-1]
# print(f'param: , {param}')
api_url, token = get_session_param(args[-1])
# print(api_url)
# print(token)
# modified code to deal with multiple output
if isinstance(value,list):
print(f'number of outputs: {len(value)}')
for k in value:
if isinstance(k,numpy.ndarray):
# print(f'output: ')
# print(f'output type {type(k)}')
# print(f'output dim {k.shape}')
# print(f'data type {k.dtype}')
# print(f'max value {k.max()} min value {k.min()}' )
img = prep_image(k)
send_image(img,api_url,token)
elif isinstance(value,numpy.ndarray ):
# print('numpy array')
img = prep_image(value)
send_image(img,api_url,token)
else:
print('unpredicted return type')
return ret_value
return wrapper_playform