3
حa                 @   s   d Z ddlZddlZddlmZ ddlZddlmZ ddlm	Z	 yddl
mZmZ W n ek
rr   ejd Y nX dd	d
ZdddZdd ZdddZdS )zWrappers and helpers for using Flask with Cozmo.

Flask is a Python web framework. remote_control_cozmo.py and other scripts may use
these utility functions to interact with a web browser.
    N)Thread)sleep)BytesIO)make_response	send_filezCCannot import from flask: Do `pip3 install --user flask` to installTc          	   C   s4   dd }t |t| ||||dd}d|_|j  dS )a  
    Spawn a thread and call sleep_and_open_web_browser from within it so that main thread can keep executing at the
    same time. Insert a small sleep before opening a web-browser
    this gives Flask a chance to start running before the browser starts requesting data from Flask.
    c             S   s.   t | t}|rtj|}|j| ||d d S )N)new	autoraise)r   
webbrowsergetopen)urldelayr   r   specific_browserbrowser r   X/afs/cs.cmu.edu/academic/class/15494-s22/demos/Cozmo-Animation-Explorer/flask_helpers.py_sleep_and_open_web_browser)   s
    
z>_delayed_open_web_browser.<locals>._sleep_and_open_web_browser)r   r   r   r   r   )targetkwargsTN)r   dictdaemonstart)r   r   r   r   r   r   threadr   r   r   _delayed_open_web_browser"   s
    r   	127.0.0.1  F      ?c             C   sN   |st jd}|jt j |r:td| d t| |d | j||dd dS )z
    Run the Flask webserver on specified host and port
    optionally also open that same host:port page in your browser to connect
    werkzeugzhttp://:)r   F)hostport
use_evalexN)logging	getLoggersetLevelERRORr   strrun)	flask_apphost_ip	host_portZenable_flask_loggingZ	open_pageZopen_page_delaylogr   r   r   	run_flask:   s    
r,   c             C   s>   t | }d|jd< d|jd< d|jd< d|jd< d|jd< |S )	Nzno-cachezPragma-DirectivezCache-Directivez#no-cache, no-store, must-revalidatezCache-ControlZPragma0Expires)r   headers)in_fileresponser   r   r   make_uncached_responseN   s    




r2   F   c             C   s^   t  }|r4| j|d|d |jd tt|ddS | j|d |jd tt|ddS dS )	z4Convert PIL image to relevant image file and send itZJPEG)qualityr   z
image/jpeg)mimetypeZPNGz	image/pngN)r   saveseekr2   r   )Zpil_imgZserve_as_jpegZjpeg_qualityZimg_ior   r   r   serve_pil_imageX   s    

r8   )r   TN)r   r   FTr   )Fr3   )__doc__r"   sys	threadingr   r	   timer   ior   flaskr   r   ImportErrorexitr   r,   r2   r8   r   r   r   r   <module>   s   
 

