
    &`iA                     j   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZmZmZmZ d dlmZ d dlZd dlZ	 d dlmZ n# e$ r dZY nw xY wd dlmZ d dlmZ d dlmZ d d	lmZmZmZm Z m!Z! d d
l"m#Z#m$Z$m%Z% d dl&m'Z' d dl(m)Z)m*Z* d dl+m,Z,m-Z-m.Z. erd dl/m0Z0  ej1        e2          Z3d  e4 e5d           e5d          dz             D             Z6de7dede7fdZ8e#de7de7fd            Z9e#de.dede.fd            Z:e#de,ded         fd            Z;e$ G d de                      Z<dS )     N)Path)TYPE_CHECKINGListOptionalUnion)urlparse)
smart_open)InputReader)	IOContext)Policy)DEFAULT_POLICY_IDMultiAgentBatchSampleBatchconcat_samples convert_ma_batch_to_sample_batch)DeveloperAPI	PublicAPIoverride)unpack_if_needed)clip_actionnormalize_action)AnyFileTypeSampleBatchType)RolloutWorkerc                 ,    g | ]}t          |          S  )chr.0is     q/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/rllib/offline/json_reader.py
<listcomp>r#   )   s    @@@Q#a&&@@@    cz   	json_datapolicyreturnc                 ~   |                                  D ]&\  }}||j        v r|j        |         j        nd}|j                            d          rh|t
          j        k    s0|t
          j        k    s |t
          j        k    s|t
          j        k    r(t          j	        |j
        d | |         d          | |<   |j                            d          rg|t
          j        k    s0|t
          j        k    s |t
          j        k    s|t
          j        k    r't          j	        |j        d | |         d          | |<   (| S )a@  Handle nested action/observation spaces for policies.

    Translates nested lists/dicts from the json into proper
    np.ndarrays, according to the (nested) observation- and action-
    spaces of the given policy.

    Providing nested lists w/o this preprocessing step would
    confuse a SampleBatch constructor.
     _disable_action_flatteningc                 *    t          j        |           S Nnparraycomps    r"   <lambda>z0_adjust_obs_actions_for_policy.<locals>.<lambda>E       RXd^^ r$   F)check_types_disable_preprocessor_apic                 *    t          j        |           S r/   r0   r3   s    r"   r5   z0_adjust_obs_actions_for_policy.<locals>.<lambda>R   r6   r$   )itemsview_requirementsdata_colconfiggetr   ACTIONSPREV_ACTIONStreemap_structure_up_toaction_space_structOBSNEXT_OBSobservation_space_struct)r(   r)   kvr<   s        r"   _adjust_obs_actions_for_policyrI   ,   s]    !!  1 F,,, $Q'00 	 =9:: 	$$$;...K,,,;3333*++!!	  IaLL ]:;; 	  ;?**K(((;///3/++!!	  IaL r$   c                     i }|                                  D ]*\  }}|t          j        k    r||t          j        <   %|||<   +|S )zEMake sure DONES in json data is properly translated into TERMINATEDS.)r:   r   DONESTERMINATEDS)r(   new_json_datarG   rH   s       r"   _adjust_donesrN   Y   sY     M!! ! !1!!!56M+122  !M!r$   batchioctxc                    |j         }|                    d          r<|j        t          d          t	          | t
                    r|j        j                            t                    }|Wt          |j        j                  dk    sJ t          t          |j        j                                                            }t          | t
          j                 |j                  | t
          j        <   na| j                                        D ]G\  }}t          |t
          j                 |j        j        |         j                  |t
          j        <   H|                    d          du r|                    d          du r|j        t          d          d	}t	          | t
                    r|j        j                            t                    }|Wt          |j        j                  dk    sJ t          t          |j        j                                                            }t	          |j        t"          t$          f          r)|j                             d
          st          |          t'          | t
          j                 |j                  | t
          j        <   n| j                                        D ]\  }}|j        j        |         }t	          |j        t"          t$          f          r)|j                             d
          st          |          t'          |t
          j                 |j        j        |         j                  |t
          j        <   | S )Nclip_actionszCclip_actions is True but cannot clip actions since no workers existr'   actions_in_input_normalizedFnormalize_actionsTzWactions_in_input_normalized is False butcannot normalize actions since no workers exista  Normalization of offline actions that are flattened is not supported! Make sure that you record actions into offline file with the `_disable_action_flattening=True` flag OR as already normalized (between -1.0 and 1.0) values. Also, when reading already normalized action values from offline files, make sure to set `actions_in_input_normalized=True` so that RLlib will not perform normalization on top.r-   )r=   r>   worker
ValueError
isinstancer   
policy_mapr   lennextitervaluesr   r?   rC   policy_batchesr:   tupledictr   )rO   rP   cfgr)   pidb	error_msgs          r"   postprocess_actionsrd   h   s0    ,C ww~ <U   e[)) 	\,001BCCF~5<233q8888d5<#:#A#A#C#CDDEE)4k)*F,F* *E+%&&  .4466  Q)4k)*L+C0D* *+%&& 	-..%77GG'((D00<B  , 	 e[)) 	\,001BCCF~5<233q8888d5<#:#A#A#C#CDDEE*UDM  ,m''(DEE, !+++)9k)*F,F* *E+%&&  .4466 	 	Q05.  0 -++,HII0 %Y///)9k)*L+C0D* *+%&&
 Lr$   rU   r   c                    d| v r|                      d          }nt          d          |dk    r|'t          |j                  dk    rt          d          |                                 D ]\  }}t          |          | |<   |Ct          t          |j                                                            }t          | |          } t          |           } t          |           S |dk    ri }| d                                         D ]\  }}i }	|                                D ]3\  }}|t          j        k    rt          j        }t          |          |	|<   4||j        |         }t          |	|          }	t          |	          }	t          |	          ||<   t          || d                   S t          d	|          )
Ntypez JSON record missing 'type' fieldr   r'   z\Found single-agent SampleBatch in input file, but our PolicyMap contains more than 1 policy!r   r]   countz<Type field must be one of ['SampleBatch', 'MultiAgentBatch'])poprV   rY   rX   r:   r   rZ   r[   r\   rI   rN   r   rK   rL   r   )
r(   rU   	data_typerG   rH   r)   r]   	policy_idpolicy_batchinners
             r"   from_json_datarm      s    MM&))		;<<<M!!#f&7"8"8A"="=9   OO%% 	/ 	/DAq+A..IaLL$v07799::;;F6y&III!),,	9%%%	'	'	''01A'B'H'H'J'J 	; 	;#I|E$**,, / /1)))#/A+A..a!*956ufEE!%((E(3E(:(:N9%%~y/ABBBJI
 
 	
r$   c                       e Zd ZdZe	 ddeeee         f         dee	         fd            Z
 ee          defd            ZdefdZd	edefd
Zd Zdedee         fdZdefdZdefdZdedefdZdS )
JsonReaderzxReader object that loads experiences from JSON file chunks.

    The input files will be read from in random order.
    NinputsrP   c                    t                               d           |pt                      | _        dx| _        | _        d| _        | j        rv| j        j                            dd          | _        | j        j                            dd          }|r/t          t          j        | j        |z            d          | _        | j        j        | j        j        j        | _        | j                            t                    | _        | j        Rt          | j                  dk    sJ t          t!          | j                                                            | _        t%          |t&                    r3t(          j                            t(          j                            |                    }t(          j                            |          r^t(          j                            |d          t(          j                            |d          g}t                               d	|            n|g}t7          d
 |D                       r%t9          d                    |          dz             g | _        |D ].}| j                            tA          j         |                     /nSt%          |tB          tD          f          rtC          |          | _        n"t9          d                    |                    | j        r@t                               d                    t          | j                                       n"t9          d                    |                    d| _#        dS )aB  Initializes a JsonReader instance.

        Args:
            inputs: Either a glob expression for files, e.g. `/tmp/**/*.json`,
                or a list of single file paths or URIs, e.g.,
                ["s3://bucket/file.json", "s3://bucket/file2.json"].
            ioctx: Current IO context object or None.
        zeYou are using JSONReader. It is recommended to use DatasetReader instead for better sharding support.Nr'   train_batch_sizenum_env_runnersr   z*.jsonz*.zipz+Treating input directory as glob patterns: c              3   T   K   | ]#}t          |          j        d gt          z   vV  $dS )r,   N)r   schemeWINDOWS_DRIVESr   s     r"   	<genexpr>z&JsonReader.__init__.<locals>.<genexpr>  s7      SSq8A;;%bTN-BBSSSSSSr$   z"Don't know how to glob over `{}`, z/please specify a list of files to read instead.z*type of inputs must be list or str, not {}zFound {} input files.zNo files found matching {})$loggerinfor   rP   default_policyrX   
batch_sizer=   r>   maxmathceilrU   r   rY   rZ   r[   r\   rW   strospathabspath
expanduserisdirjoinwarninganyrV   formatfilesextendgloblistr^   cur_file)selfrp   rP   num_workersr!   s        r"   __init__zJsonReader.__init__   s     	C	
 	
 	

 )ikk
044do: 	S"j/334FJJDO*+//0A1EEK S"%di+0M&N&NPQ"R"R:("j/:DO"&/"5"56G"H"HD"*4?++q0000&*40F0F0H0H+I+I&J&J#fc"" 	W__RW%7%7%?%?@@Fw}}V$$ "',,vx88"',,vw:W:WXUVUUVVVV SSFSSSSS 4 8??GGGH  
  
 4 4AJ%%dill33334u.. 	fDJJ<CCFKK   : 	JKK/66s4:GGHHHH9@@HHIIIr$   r*   c                 @   g }d}|| j         k     r|                     |                                           }d}|sl|dk     rf|dz  }t                              d                    | j                             |                     |                                           }|s|dk     f|s't          d                    | j                            |                     |          }||j	        z  }|
                    |           || j         k     t          |          }|S )Nr   d   r'   zSkipping empty line in {}z3Failed to read valid experience batch from file: {})r{   
_try_parse
_next_linerx   debugr   r   rV   _postprocess_if_neededrg   appendr   )r   retrg   rO   triess        r"   rZ   zJsonReader.next'  s,   do%%OODOO$5$566EE ;
8??NNOOO(9(9::  ;   IPP   
 //66EU[ EJJu do%%  S!!
r$   c              #      K   | j         D ]L}|                     |          }	 |                                }|sn|                     |          }|n|V  4MdS )a  Reads through all files and yields one SampleBatchType per line.

        When reaching the end of the last file, will start from the beginning
        again.

        Yields:
            One SampleBatch or MultiAgentBatch per line in all input files.
        TN)r   _try_open_filereadliner   )r   r   filelinerO   s        r"   read_all_fileszJsonReader.read_all_files>  s{       J 		 		D&&t,,D}} --=		 		r$   rO   c                 T   | j         j                            d          s|S t          |          }t	          |t
                    rUg }|                                D ]/}|                    | j        	                    |                     0t          |          S t          d          )Npostprocess_inputsz7Postprocessing of multi-agent data not implemented yet.)rP   r=   r>   r   rW   r   split_by_episoder   rz   postprocess_trajectoryr   NotImplementedError)r   rO   out	sub_batchs       r"   r   z!JsonReader._postprocess_if_neededR  s    z $$%9:: 	L077e[)) 
	C"3355 R R	

4.EEiPPQQQQ!#&&& &I  r$   c                    t          |          j        dgt          z   vr2t          "t	          d                    |                    t          }n|                    d          rFt          j        	                    t          j
                            dd          |dd                    }|}t          j                            |          s<t          j        	                    t          t                    j        j        |          }t          j                            |          st!          d| d          t#          j        d|          rt'          j        |d	          5 }|                    t          |          j                   d d d            n# 1 swxY w Y   t#          j        dd
|          }t          j                            |          sJ t.          } ||d	          }|S )Nr,   zBYou must install the `smart_open` module to read from URIs like {}z~/HOME   zOffline file z not found!z\.zip$rz.json)r   ru   rv   r	   rV   r   
startswithr   r   r   environr>   existsr   __file__parentFileNotFoundErrorresearchzipfileZipFile
extractallsubopen)r   r   ctx	path_origzip_refr   s         r"   r   zJsonReader._try_open_filed  s   D>> ~(===! ((.t   CC t$$ Jw||BJNN62$>$>QRRII I7>>$'' Hw||DNN$9$@$GG7>>$'' P'(N	(N(N(NOOO yD)) ,_T3// :7&&tDzz'8999: : : : : : : : : : : : : : :vi$77w~~d+++++Cs4~~s   &(FF!Fr   c                    |                                 }|sd S 	 |                     |          }nD# t          $ r7 t                              d                    | j        |                     Y d S w xY wt          || j                  }|S )Nz&Ignoring corrupt json record in {}: {})	strip
_from_json	Exceptionrx   	exceptionr   r   rd   rP   )r   r   rO   s      r"   r   zJsonReader._try_parse  s    zz|| 	4	OOD))EE 	 	 	8??tTT   44		 $E4:66s   0 =A10A1c                     | j         s|                                 | _         | j                                         }d}|s|dk     r|dz  }t          | j         d          r| j                                          |                                 | _         | j                                         }|s2t
                              d                    | j                              |s|dk     |s't          d                    | j	                            |S )Nr   r   r'   closezIgnoring empty file {}z'Failed to read next line from files: {})
r   
_next_filer   hasattrr   rx   r   r   rV   r   )r   r   r   s      r"   r   zJsonReader._next_line  s   } 	. OO--DM}%%'' 	M53;;QJEt}g.. &##%%% OO--DM=))++D M5<<T]KKLLL  	M53;;  	9@@LL   r$   c                 8   | j         f| j        j        Z| j        j        j        }| j        j        j        pd}| j        t          t          | j                  dz
  ||z  z                     }nt          j	        | j                  }| 
                    |          S )Nr'   )r   rP   rU   worker_indexr   r   roundrY   randomchoicer   )r   idxtotalr   s       r"   r   zJsonReader._next_file  s     = TZ%6%B*#0CJ%16QE:eS__q%8S5[$IJJKDD =,,D""4(((r$   datac                     t          |t                    r|                    d          }t          j        |          }t          || j        j                  S )Nzutf-8)rW   bytesdecodejsonloadsrm   rP   rU   )r   r   r(   s      r"   r   zJsonReader._from_json  sI    dE"" 	(;;w''DJt$$	i):;;;r$   r/   )__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r
   r   rZ   r   r   r   r   r   r   r   r   r   r$   r"   ro   ro      sf        
 JN; ;CcN+;4<Y4G; ; ; Y;z Xko    ,    (O     $  >s x'@     C    &
)H 
) 
) 
) 
)<s < < < < < < <r$   ro   )=r   r   loggingr}   r   r   r   r   pathlibr   typingr   r   r   r   urllib.parser   numpyr1   rA   r	   ImportErrorray.rllib.offline.input_readerr
   ray.rllib.offline.io_contextr   ray.rllib.policy.policyr   ray.rllib.policy.sample_batchr   r   r   r   r   ray.rllib.utils.annotationsr   r   r   ray.rllib.utils.compressionr   "ray.rllib.utils.spaces.space_utilsr   r   ray.rllib.utils.typingr   r   r   ray.rllib.evaluationr   	getLoggerr   rx   rangeordrv   r_   rI   rN   rd   rm   ro   r   r$   r"   <module>r      sA       				  				        7 7 7 7 7 7 7 7 7 7 7 7 ! ! ! ! ! !     %%%%%%%   JJJ 7 6 6 6 6 6 2 2 2 2 2 2 * * * * * *              J I I I I I I I I I 8 8 8 8 8 8 L L L L L L L L A A A A A A A A A A 3222222		8	$	$@@%%C##c((Q,"?"?@@@*d *F *t * * * *Z T d     J Jy J_ J J J JZ &
c &
8O+D &
 &
 &
 &
V S< S< S< S< S< S< S< S< S< S<s   A	 	AA