o
    :DiI                     @   s  d Z dZddlZddlm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 ddlmZ dd	lmZ eejjejjejjejjgZeejjejjgZeejjejjgZd
ZdZdZe	dZe	dZ G dd de!Z"G dd de"Z#G dd de"Z$								d@ddZ%					dAddZ&dd Z'G dd de(Z)d d! Z*d"d# Z+d$d% Z,			&dBd'd(Z-			&dBd)d*Z.e/e0fZ1G d+d, d,e(Z2dCd-d.Z3d/d0 Z4d1d2 Z5d3d4 Z6d5d6gd7d8gd7d8gd9d:gd;d<gd7d8gd=d>gd?Z7dS )Dat  Contains routines for printing protocol messages in JSON format.

Simple usage example:

  # Create a proto object and serialize it to a json format string.
  message = my_proto_pb2.MyMessage(foo='bar')
  json_string = json_format.MessageToJson(message)

  # Parse a json format string to proto object.
  message = json_format.Parse(json_string, my_proto_pb2.MyMessage())
zjieluo@google.com (Jie Luo)    N)OrderedDict)methodcaller)type_checkers)
descriptor)message_factory)symbol_databaseInfinityz	-InfinityNaNu.   [-](?![-])|(?<![-])[-]z\[[a-zA-Z0-9\._]*\]$c                   @      e Zd ZdZdS )Errorz'Top-level module error for json_format.N__name__
__module____qualname____doc__ r   r   T/var/www/Datamplify/venv/lib/python3.10/site-packages/google/protobuf/json_format.pyr   6       r   c                   @   r
   )SerializeToJsonErrorz&Thrown if serialization to JSON fails.Nr   r   r   r   r   r   :   r   r   c                   @   r
   )
ParseErrorz Thrown in case of parsing error.Nr   r   r   r   r   r   >   r   r   F   Tc	           
      C   s"   t |||||d}	|	| |||S )a  Converts protobuf message to JSON format.

  Args:
    message: The protocol buffers message instance to serialize.
    including_default_value_fields: If True, singular primitive fields,
        repeated fields, and map fields will always be serialized.  If
        False, only serialize non-empty fields.  Singular message fields
        and oneof fields are not affected by this option.
    preserving_proto_field_name: If True, use the original proto field
        names as defined in the .proto file. If False, convert the field
        names to lowerCamelCase.
    indent: The JSON object will be pretty-printed with this indent level.
        An indent level of 0 or negative will only insert newlines. If the
        indent level is None, no newlines will be inserted.
    sort_keys: If True, then the output will be sorted by field names.
    use_integers_for_enums: If true, print integers instead of enum names.
    descriptor_pool: A Descriptor Pool for resolving types. If None use the
        default.
    float_precision: If set, use this to specify float field valid digits.
    ensure_ascii: If True, strings with non-ASCII characters are escaped.
        If False, Unicode strings are returned unchanged.

  Returns:
    A string containing the JSON formatted protocol buffer message.
  float_precision)_PrinterToJsonString)
messageincluding_default_value_fieldspreserving_proto_field_nameindent	sort_keysuse_integers_for_enumsdescriptor_poolr   ensure_asciiprinterr   r   r   MessageToJsonB   s   #r$   c                 C   s   t |||||d}|| S )a  Converts protobuf message to a dictionary.

  When the dictionary is encoded to JSON, it conforms to proto3 JSON spec.

  Args:
    message: The protocol buffers message instance to serialize.
    including_default_value_fields: If True, singular primitive fields,
        repeated fields, and map fields will always be serialized.  If
        False, only serialize non-empty fields.  Singular message fields
        and oneof fields are not affected by this option.
    preserving_proto_field_name: If True, use the original proto field
        names as defined in the .proto file. If False, convert the field
        names to lowerCamelCase.
    use_integers_for_enums: If true, print integers instead of enum names.
    descriptor_pool: A Descriptor Pool for resolving types. If None use the
        default.
    float_precision: If set, use this to specify float field valid digits.

  Returns:
    A dict representation of the protocol buffer message.
  r   )r   _MessageToJsonObject)r   r   r   r    r!   r   r#   r   r   r   MessageToDictn   s   
r&   c                 C   s"   | j tjjko| jjo| j jS N)typer   FieldDescriptorTYPE_MESSAGEmessage_typehas_options
GetOptions	map_entry)fieldr   r   r   _IsMapEntry   s
   
r0   c                   @   st   e Zd ZdZ					dddZdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd ZdS )r   z)JSON format printer for protocol message.FNc                 C   s6   || _ || _|| _|| _|rd|| _d S d | _d S )Nz.{}g)r   r   r    r!   formatfloat_format)selfr   r   r    r!   r   r   r   r   __init__   s   
z_Printer.__init__c                 C   s   |  |}tj||||dS )N)r   r   r"   )r%   jsondumps)r3   r   r   r   r"   jsr   r   r   r      s   
z_Printer.ToJsonStringc                 C   sL   |j }|j}t|r| |S |tv rtt| d || S i }| ||S )zEConverts message to an object according to Proto3 JSON Specification.r   )
DESCRIPTOR	full_name_IsWrapperMessage_WrapperMessageToJsonObject_WKTJSONMETHODSr   _RegularMessageToJsonObject)r3   r   message_descriptorr9   r7   r   r   r   r%      s   
z_Printer._MessageToJsonObjectc              
      s  |  }z|D ]l\ }jr j}n j}t rF jjd }i }|D ]}t|tr2|r/d}	nd}	nt	|}	
||| ||	< q#|||< q jtjjkrZ fdd|D ||< q jrkd j }
 |||< q
 |||< qjr|j}
|
jD ]D  jtjjkr jtjjks jrq}jr j}n j}||v rq}t ri ||< q} jtjjkrg ||< q}
  j||< q}W |S W |S  ty } z
td j||d}~ww )	z?Converts normal message according to Proto3 JSON Specification.valuetruefalsec                    s   g | ]}  |qS r   )_FieldToJsonObject).0kr/   r3   r   r   
<listcomp>   s    z8_Printer._RegularMessageToJsonObject.<locals>.<listcomp>z[%s]z#Failed to serialize {0} field: {1}.N)
ListFieldsr   name	json_namer0   r+   fields_by_name
isinstanceboolstrrB   labelr   r)   LABEL_REPEATEDis_extensionr9   r   r8   fieldscpp_typeCPPTYPE_MESSAGEcontaining_oneofdefault_value
ValueErrorr   r1   )r3   r   r7   rQ   r?   rH   v_fieldjs_mapkeyrecorded_keyr>   er   rE   r   r=      sr   






z$_Printer._RegularMessageToJsonObjectc                 C   s.  |j tjjkr| |S |j tjjkr9| jr|S |jjdkr dS |jj	
|d}|dur/|jS |jjr7td|S |j tjjkrQ|jtjjkrOt|dS |S |j tjjkr\t|S |j tv ret|S |j tv rt|rw|dk rutS tS t|r~tS |j tjjkr| j rt!t"|| j S t#$|S |S )z<Converts field value according to Proto3 JSON Specification.google.protobuf.NullValueNzKEnum field contains an integer value which can not mapped to an enum value.utf-8g        )%rR   r   r)   rS   r%   CPPTYPE_ENUMr    	enum_typer9   values_by_numbergetrH   	is_closedr   CPPTYPE_STRINGr(   
TYPE_BYTESbase64	b64encodedecodeCPPTYPE_BOOLrL   _INT64_TYPESrM   _FLOAT_TYPESmathisinf_NEG_INFINITY	_INFINITYisnan_NANCPPTYPE_FLOATr2   floatr1   r   ToShortestFloat)r3   r/   r?   
enum_valuer   r   r   rB      sB   





z_Printer._FieldToJsonObjectc                 C   s   |  si S t }|j}||d< t|| j}||j |j}|j}t	|r/| 
||d< |S |tv rBtt| d || |d< |S | ||S )z<Converts Any message according to Proto3 JSON Specification.@typer?   r   )rG   r   type_url_CreateMessageFromTypeUrlr!   ParseFromStringr?   r8   r9   r:   r;   r<   r   r=   )r3   r   r7   rv   sub_messager>   r9   r   r   r   _AnyMessageToJsonObject)  s(   z _Printer._AnyMessageToJsonObjectc                 C   s   |  S )z8Converts message according to Proto3 JSON Specification.)r   r3   r   r   r   r   _GenericMessageToJsonObject>  s   z$_Printer._GenericMessageToJsonObjectc                 C   s   | d}|du s|dkrdS |dkr| |jS |dkr3|j}t|r)tdt|r2tdnt||}|j	j
| }| ||S )z>Converts Value message according to Proto3 JSON Specification.kindN
null_value
list_valuenumber_valuezTFail to serialize Infinity for Value.number_value, which would parse as string_valuezOFail to serialize NaN for Value.number_value, which would parse as string_value)
WhichOneof_ListValueMessageToJsonObjectr   r   rk   rl   rV   ro   getattrr8   rJ   rB   )r3   r   whichr?   oneof_descriptorr   r   r   _ValueMessageToJsonObjectD  s   



z"_Printer._ValueMessageToJsonObjectc                    s    fdd|j D S )zBConverts ListValue message according to Proto3 JSON Specification.c                    s   g | ]}  |qS r   )r   )rC   r?   r3   r   r   rF   \  s    z:_Printer._ListValueMessageToJsonObject.<locals>.<listcomp>)valuesr{   r   r   r   r   Z  s   
z&_Printer._ListValueMessageToJsonObjectc                 C   s*   |j }i }|D ]}| || ||< q|S )z?Converts Struct message according to Proto3 JSON Specification.)rQ   r   )r3   r   rQ   retrY   r   r   r   _StructMessageToJsonObject_  s
   z#_Printer._StructMessageToJsonObjectc                 C   s   |  |jjd |jS )Nr?   )rB   r8   rJ   r?   r{   r   r   r   r;   g  s   z$_Printer._WrapperMessageToJsonObjectFFFNN)r   r   r   r   r4   r   r%   r=   rB   rz   r|   r   r   r   r;   r   r   r   r   r      s$    
@,r   c                 C   s   | j jdkS )Nzgoogle/protobuf/wrappers.proto)filerH   )r>   r   r   r   r:   l  s   r:   c                 C   s4   i }| D ]\}}||v rt d||||< q|S )Nz'Failed to load JSON: duplicate key {0}.)r   r1   )r7   resultrH   r?   r   r   r   _DuplicateCheckerp  s   
r   c              
   C   sp   t  }|du r|jn|}| dd }z||}W n ty/ } ztd| |d}~ww t	|}| S )z"Creates a message from a type URL.N/z0Can not find message descriptor by type_url: {0})
r   DefaultpoolsplitFindMessageTypeByNameKeyError	TypeErrorr1   r   GetMessageClass)rv   r!   dbr   	type_namer>   r[   message_classr   r   r   rw   y  s   
rw   d   c              
   C   sd   t | ts
| d} z	tj| td}W n ty) } z
tdt||d}~ww t	|||||S )al  Parses a JSON representation of a protocol message into a message.

  Args:
    text: Message JSON representation.
    message: A protocol buffer message to merge into.
    ignore_unknown_fields: If True, do not raise errors for unknown fields.
    descriptor_pool: A Descriptor Pool for resolving types. If None use the
      default.
    max_recursion_depth: max recursion depth of JSON message to be
      deserialized. JSON messages over this depth will fail to be
      deserialized. Default value is 100.

  Returns:
    The same message passed as argument.

  Raises::
    ParseError: On JSON parsing problems.
  r]   )object_pairs_hookzFailed to load JSON: {0}.N)
rK   rM   rg   r5   loadsr   rV   r   r1   	ParseDict)textr   ignore_unknown_fieldsr!   max_recursion_depthr7   r[   r   r   r   Parse  s   


r   c                 C   s   t |||}|| |d |S )a8  Parses a JSON dictionary representation into a message.

  Args:
    js_dict: Dict representation of a JSON message.
    message: A protocol buffer message to merge into.
    ignore_unknown_fields: If True, do not raise errors for unknown fields.
    descriptor_pool: A Descriptor Pool for resolving types. If None use the
      default.
    max_recursion_depth: max recursion depth of JSON message to be
      deserialized. JSON messages over this depth will fail to be
      deserialized. Default value is 100.

  Returns:
    The same message passed as argument.
   )_ParserConvertMessage)js_dictr   r   r!   r   parserr   r   r   r     s   r   c                   @   s`   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd ZdS )r   z(JSON format parser for protocol message.c                 C   s   || _ || _|| _d| _d S )Nr   )r   r!   r   recursion_depth)r3   r   r!   r   r   r   r   r4     s   
z_Parser.__init__c                 C   s   |  j d7  _ | j | jkrtd| j|j}|j}|s |j}t|r,| ||| n|t	v r>t
t	| d ||||  n| ||| |  j d8  _ dS )a  Convert a JSON object into a message.

    Args:
      value: A JSON object.
      message: A WKT or regular protocol message to record the data.
      path: parent path to log parse error info.

    Raises:
      ParseError: In case of convert problems.
       z,Message too deep. Max recursion depth is {0}N)r   r   r   r1   r8   r9   rH   r:   _ConvertWrapperMessager<   r   _ConvertFieldValuePair)r3   r?   r   pathr>   r9   r   r   r   r     s   z_Parser.ConvertMessagec                 C   s2  g }|j }tdd |jD }|D ]}z||d}|s%|j|d}|sXt|rX|js8td	|j
||dd }	|j|	}|sXd|	ddd }	|j|	}|sp| jr_W qtd	|j
||d	d
 |jD ||v rtd	|j j
|||| || }
|jdur|
dur|jj}||v rtd	|j j
|||| |
du r|jtjjkr|jj
dkrt||j}d|_n|jtjjkr|jj
dkrt||jd n||j W qt|r||j | |
||d	|| n|j tjj!kr|||j t"|
t#std	||
||jtjjkrQt$|
D ].\}}t||j% }|du rB|j j
dkrBtd	|||| &||d	||| q!ntt$|
D ]%\}}|du rgtd	|||t||jt'||d	||| qUnI|jtjjkr|j(r|j| }nt||j}|)  | &|
|d	|| n!|j(rt'|
|d	|||j|< nt||jt'|
|d	|| W q ty } z|r|jdu rtd	|||tt*||d}~w t+y } z	td	|||d}~w t,y } z	td	|||d}~ww dS )a'  Convert field value pairs into regular message.

    Args:
      js: A JSON object to convert the field value pairs.
      message: A regular protocol message to record the data.
      path: parent path to log parse error info.

    Raises:
      ParseError: In case of problems converting.
    c                 s   s    | ]}|j |fV  qd S r'   rI   rC   fr   r   r   	<genexpr>  s    z1_Parser._ConvertFieldValuePair.<locals>.<genexpr>Nz0Message type {0} does not have extensions at {1}r   r   .zaMessage type "{0}" has no field named "{1}" at "{2}".
 Available Fields(except extensions): "{3}"c                 S   s   g | ]}|j qS r   r   r   r   r   r   rF     s    z2_Parser._ConvertFieldValuePair.<locals>.<listcomp>zBMessage type "{0}" should not have multiple "{1}" fields at "{2}".zHMessage type "{0}" should not have multiple "{1}" oneof fields at "{2}".google.protobuf.Valuer   r\   {0}.{1}z4repeated field {0} must be in [] which is {1} at {2}zPnull is not allowed to be used as an element in a repeated field at {0}.{1}[{2}]z{0}.{1}[{2}]zFailed to parse {0} field: {1}.)-r8   dictrQ   ra   rJ   _VALID_EXTENSION_NAMEmatchis_extendabler   r1   r9   
Extensions_FindExtensionByNamejoinr   r   appendrT   rH   rR   r   r)   rS   r+   r   r~   r^   r_   setattr
ClearFieldr0   _ConvertMapFieldValuerN   rO   rK   list	enumerateaddr   _ConvertScalarFieldValuerP   SetInParentrM   rV   r   )r3   r7   r   r   namesr>   fields_by_json_namerH   r/   
identifierr?   
oneof_namery   indexitemr[   r   r   r   r     s  












z_Parser._ConvertFieldValuePairc           	   
   C   s  t |tr	|s	dS z|d }W n ty# } ztd||d}~ww zt|| j}W n tyA } z	td|||d}~ww |j}|j	}t
|rY| |d |d| n%|tv rptt| d |d |d||  n|d= | ||| ||d< | |_||_dS )z/Convert a JSON representation into Any message.Nru   z0@type is missing when parsing any message at {0}
{0} at {1}r?   	{0}.valuer   )rK   r   r   r   r1   rw   r!   r   r8   r9   r:   r   r<   r   r   SerializeToStringr?   rv   )	r3   r?   r   r   rv   r[   ry   r>   r9   r   r   r   _ConvertAnyMessager  sF   

z_Parser._ConvertAnyMessagec              
   C   s<   z| | W dS  ty } z	td|||d}~ww )z?Convert a JSON representation into message with FromJsonString.r   N)FromJsonStringrV   r   r1   )r3   r?   r   r   r[   r   r   r   _ConvertGenericMessage  s   z_Parser._ConvertGenericMessagec                 C   s   t |tr| ||j| dS t |tr| ||j| dS |du r'd|_dS t |tr1||_	dS t |t
r;||_dS t |trE||_dS td|t||)z1Convert a JSON representation into Value message.Nr   z(Value {0} has unexpected type {1} at {2})rK   r   _ConvertStructMessagestruct_valuer   _ConvertListValueMessager   r~   rL   
bool_valuerM   string_value_INT_OR_FLOATr   r   r1   r(   )r3   r?   r   r   r   r   r   _ConvertValueMessage  s   









z_Parser._ConvertValueMessagec              	   C   sV   t |tstd|||d t|D ]\}}| ||j d|| qdS )z5Convert a JSON representation into ListValue message.z+ListValue must be in [] which is {0} at {1}r   {0}[{1}]N)	rK   r   r   r1   r   r   r   r   r   )r3   r?   r   r   r   r   r   r   r   r     s   


z _Parser._ConvertListValueMessagec              	   C   sP   t |tstd|||  |D ]}| || |j| d|| qdS )z2Convert a JSON representation into Struct message.z,Struct must be in a dict which is {0} at {1}r   N)rK   r   r   r1   Clearr   rQ   )r3   r?   r   r   rY   r   r   r   r     s   

z_Parser._ConvertStructMessagec              	   C   s,   |j jd }t|dt||d|d dS )z3Convert a JSON representation into Wrapper message.r?   r   r   N)r8   rJ   r   r   r1   )r3   r?   r   r   r/   r   r   r   r     s
   z_Parser._ConvertWrapperMessagec           	   	   C   s   t |tstd|j|||jjd }|jjd }|D ]:}t||d|d}|jt	j
jkrD| || t||j| d|| qt|| |d||dt||j|< qdS )	af  Convert map field value for a message map field.

    Args:
      value: A JSON object to convert the map field value.
      message: A protocol message to record the converted data.
      field: The descriptor of the map field to be converted.
      path: parent path to log parse error info.

    Raises:
      ParseError: In case of convert problems.
    z3Map field {0} must be in a dict which is {1} at {2}rY   r?   z{0}.keyTr   r   N)rK   r   r   r1   rH   r+   rJ   r   rR   r   r)   rS   r   r   )	r3   r?   r   r/   r   	key_fieldvalue_fieldrY   	key_valuer   r   r   r     s*   



z_Parser._ConvertMapFieldValueN)r   r   r   r   r4   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s     	 	
r   c           	   
   C   s  z|j tv rt| W S |j tv rt| |W S |j tjjkr#t| |W S |j tjj	kr\|j
tjjkrPt| tr<| d}n| }|ddt|d    }t|W S t| rYtd| W S |j tjjkr|jj| d}|du rzt| }|jj|d}W n ty } ztd| |jj|d}~ww |du r|jjrtd| |jj|W S |jW S W dS  ty } z	td|||d}~ww )aq  Convert a single scalar field value.

  Args:
    value: A scalar value to convert the scalar field value.
    field: The descriptor of the field to convert.
    path: parent path to log parse error info.
    require_str: If True, the field value must be a str.

  Returns:
    The converted scalar field value

  Raises:
    ParseError: In case of convert problems.
  r]      =   zUnpaired surrogateNz(Invalid enum value {0} for enum type {1}r   ) rR   
_INT_TYPES_ConvertIntegerrj   _ConvertFloatr   r)   rh   _ConvertBoolrc   r(   rd   rK   rM   encodelenre   urlsafe_b64decode_UNPAIRED_SURROGATE_PATTERNsearchr   r^   r_   values_by_namera   intr`   rV   r1   r9   rb   number)	r?   r/   r   require_strencodedpadded_valuert   r   r[   r   r   r   r     sV   




r   c                 C   sf   t | tr|  std| t | tr#| ddkr#td| t | tr/td| t| S )zConvert an integer.

  Args:
    value: A scalar value to convert.

  Returns:
    The integer value.

  Raises:
    ParseError: If an integer couldn't be consumed.
  zCouldn't parse integer: {0} r   zCouldn't parse integer: "{0}"z2Bool value {0} is not acceptable for integer field)	rK   rr   
is_integerr   r1   rM   findrL   r   )r?   r   r   r   r   #  s   
r   c              
   C   s  t | tr8t| rtdt| r| dkrtdtd|jtjj	kr8| t
jkr/td| t
jk r8td| dkr@tdzt| W S  ty } z2| tkr[td	W  Y d
}~S | tkritdW  Y d
}~S | tkrwtdW  Y d
}~S td| |d
}~ww )z!Convert an floating point number.z,Couldn't parse NaN, use quoted "NaN" insteadr   zICouldn't parse Infinity or value too large, use quoted "Infinity" insteadzKCouldn't parse -Infinity or value too small, use quoted "-Infinity" insteadzFloat value too largezFloat value too smallnanz-Couldn't parse float "nan", use "NaN" insteadz-infNinfzCouldn't parse float: {0})rK   rr   rk   ro   r   rl   rR   r   r)   rq   r   
_FLOAT_MAX
_FLOAT_MINrV   rm   rn   rp   r1   )r?   r/   r[   r   r   r   r   <  s4   





r   c                 C   s@   |r| dkrdS | dkrdS t d| t| tst d| S )zConvert a boolean value.

  Args:
    value: A scalar value to convert.
    require_str: If True, value must be a str.

  Returns:
    The bool parsed.

  Raises:
    ParseError: If a boolean value couldn't be consumed.
  r@   TrA   Fz#Expected "true" or "false", not {0}z%Expected true or false without quotes)r   r1   rK   rL   )r?   r   r   r   r   r   `  s   
r   rz   r   r|   r   r   r   r   r   r   r   )zgoogle.protobuf.Anyzgoogle.protobuf.Durationzgoogle.protobuf.FieldMaskzgoogle.protobuf.ListValuezgoogle.protobuf.Structzgoogle.protobuf.Timestampr   )FFr   FFNNTr   )FNr   )F)8r   
__author__re   collectionsr   r5   rk   operatorr   regoogle.protobuf.internalr   google.protobufr   r   r   	frozensetr)   CPPTYPE_INT32CPPTYPE_UINT32CPPTYPE_INT64CPPTYPE_UINT64r   ri   rq   CPPTYPE_DOUBLErj   rn   rm   rp   compiler   r   	Exceptionr   r   r   r$   r&   r0   objectr   r:   r   rw   r   r   r   rr   r   r   r   r   r   r   r<   r   r   r   r   <module>   s   

.
& S	
#
  
&:$
