o
    Rhq
                     @   s  d dl Z d dlZd dlmZmZ d dlmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlZd dlZe Zejedgdgdgd	 ejd
e	dddd eddd Ze  Ze adddddddZd dddddddZdd Zdd Zeddefd d!ZdS )"    N)FastAPI	WebSocket)CORSMiddleware)StaticFilesFileResponse)BytesIO)Image*)Zallow_originsZallow_methodsZallow_headersz/staticZfrontend)	directoryZstatic)name/c                      s
   t dS )Nzfrontend/index.htmlr    r   r   >/home/ubuntu/experiments/live_experiments/Craftertrial/main.pyindex   s   r                     )leftrightupdownjumpattack)r   r   r   r   r   Z	inventoryr   c                 C   s"   | t jv rt j| S t jdS )Nnoop)envZaction_namesr   )Z
action_strr   r   r   decode_action8   s   
r   c              
   C   st   z!| j tjkr| d tj} tjdd} |  }t|	dW S  t
y9 } ztd| W Y d }~dS d }~ww )N   )   r!   )sizezutf-8u   ❌ Raw render error: )ZdtypenpZuint8Zastyper   Zrendertobytesbase64	b64encodedecode	Exceptionprint)obsZ	raw_byteser   r   r   render_obs_raw?   s   
r-   z/ws	websocketc           	   
      s   |   I d H  d}td dd }| t| I d H  	 z:|  I d H }td| t|}t|\a	}}}|rCtd t
 a	tt	}| t|t||dI d H  W n tyq } ztd	| W Y d }~d S d }~ww q)
NFu   ✅ WebSocket connected.c                  S   s   t t} | ddd}|S )Ng        FZ	frame_rawrewarddone)r-   r+   )rawZwebsocket_datar   r   r   
send_frameW   s   z&websocket_endpoint.<locals>.send_frameTu   👉 Received action:u!   🔁 Episode done. Resetting env.r/   u   ❌ Connection closed or error:)acceptr*   Z	send_textjsondumpsZreceive_textr   r   stepr+   resetr-   floatr)   )	r.   r1   r3   dataactionr0   infor2   r,   r   r   r   websocket_endpointP   s6   


r=   ) ZcrafterZnumpyr$   Zfastapir   r   Zfastapi.middleware.corsr   Zfastapi.staticfilesr   Zfastapi.responsesr   ior   ZPILr	   r&   r5   appZadd_middlewareZmountgetr   ZEnvr   r8   r+   Z
ACTION_MAPr   r-   r.   r=   r   r   r   r   <module>   sR   


