o
    Pf6                     @   s  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Zd dl	m
Z
 d dlmZmZmZmZmZmZmZmZmZmZmZ d dlmZmZmZmZ d dlZd dlmZm Z  d dl!m"Z"m#Z#m$Z$m%Z%m&Z& zd dl'Z(W n e)y{   dZ(Y nw eee*  Z+ee+ee+ f Z,ee-e*e.ee/f Z0ee0df Z1ee.e-e*df Z2eee*  Z3e4ee e Z5e56d e57d d	ee* d
ee* fddZ8de,d
dfddZ9de+d
eee*  fddZ:de,d
eeee*  eeee*   f fddZ;ded
efddZ<		dPdedee de-d
e-fddZ=de-d
e.fddZ>		dQded ee*e*f de-d!ee? d
ej@f
d"d#ZAded
eee*d$f  fd%d&ZB	'dRded(e.d
eeee*   fd)d*ZCd+e-d
e-fd,d-ZDd.e-d/e-d
e.fd0d1ZEd2e-d
e-fd3d4ZFe
de-d
ee- fd5d6ZGd7ed
efd8d9ZHd:ed;ed
efd<d=ZId>e1d
ee-e0f fd?d@ZJdAe-d
e-fdBdCZKdAe-d
e-fdDdEZLdFe-d
e-fdGdHZMded
e fdIdJZNG dKdL dLZOdMee-e?e*f d
e-fdNdOZPdS )S    N)contextmanager)AnyCallableDictIterableIteratorListOptionalSequenceTupleTypeUnion)urlparseuses_netlocuses_paramsuses_relative)ElementFigure)_locations_mirror_parse_sizenone_maxnone_min	write_png datalocationreturnc              
   C   s  t | tjstdurt | tjrt|  } t| ds)td| dt	|  dt
| dkr7td| dz
| d | d	 f}W n ttfyW   td
| dt	|  dw |D ]*}zt| W n ttfyx   td|dt	| dw tt|rtdqZdd |D S )a  Validate a single lat/lon coordinate pair and convert to a list

    Validate that location:
    * is a sized variable
    * with size 2
    * allows indexing (i.e. has an ordering)
    * where both values are floats (or convertible to float)
    * and both values are not NaN
    N__len__zPLocation should be a sized variable, for example a list or a tuple, instead got z	 of type .   z:Expected two (lat, lon) values for location, instead got: r      zKLocation should support indexing, like a list or a tuple does, instead got z5Location should consist of two numerical values, but z is not convertible to float.z$Location values cannot contain NaNs.c                 S      g | ]}t |qS  )float.0xr"   r"   \/home/deployuser/azure_apps/autowriter/venv/lib/python3.10/site-packages/folium/utilities.py
<listcomp>f       z%validate_location.<locals>.<listcomp>)
isinstancenpndarraypd	DataFramesqueezetolisthasattr	TypeErrortypelen
ValueErrorKeyErrorr#   mathisnan)r   coordscoordr"   r"   r'   validate_location<   sX   

r;   	locationsc                 C   sV   zt |  W n ty   td| dw z	tt |  W dS  ty*   tdw )zHHelper function that does basic validation of line and multi-line types.zGLocations should be an iterable with coordinate pairs, but instead got r   zLocations is empty.N)iterr2   nextStopIterationr5   r<   r"   r"   r'   _validate_locations_basicsi   s   rA   c                 C   s   t | } t|  dd | D S )z3Validate an iterable with lat/lon coordinate pairs.c                 S   r!   r"   r;   r%   
coord_pairr"   r"   r'   r(   |   r)   z&validate_locations.<locals>.<listcomp>)if_pandas_df_convert_to_numpyrA   r@   r"   r"   r'   validate_locationsx   s   rF   c              	   C   sh   t | } t|  zttttttt|  W n ttfy,   dd | D  Y S w dd | D S )zDValidate an iterable with possibly nested lists of coordinate pairs.c                 S   r!   r"   rB   rC   r"   r"   r'   r(      r)   z,validate_multi_locations.<locals>.<listcomp>c                 S   r!   r"   )rF   )r%   lstr"   r"   r'   r(      r)   )rE   rA   r#   r>   r=   r2   r?   r@   r"   r"   r'   validate_multi_locations   s   $rH   objc                 C   s   t durt| t jr| jS | S )zReturn a Numpy array from a Pandas dataframe.

    Iterating over a DataFrame has weird side effects, such as the first
    row being the column names. Converting to Numpy is more safe.
    N)r-   r*   r.   values)rI   r"   r"   r'   rE      s   rE   upperimagecolormaporiginc                 C   s   t | tr?t| s?tj| d dd }t| d}| }W d   n1 s)w   Y  t	|
d}d| d| }n#d| jjv rZt| ||d	}t	|
d}d
| }ntt| }|ddS )ap  
    Infers the type of an image argument and transforms it into a URL.

    Parameters
    ----------
    image: string, file or array-like object
        * If string, it will be written directly in the output file.
        * If file, it's content will be converted as embedded in the
          output file.
        * If array-like, it will be converted to PNG base64 string and
          embedded in the output.
    origin: ['upper' | 'lower'], optional, default 'upper'
        Place the [0, 0] index of the array in the upper left or
        lower left corner of the axes.
    colormap: callable, used only for `mono` image.
        Function of the form [x -> (r,g,b)] or [x -> (r,g,b,a)]
        for transforming a mono image into RGB.
        It must output iterables of length 3 or 4, with values between
        0. and 1.  You can use colormaps from `matplotlib.cm`.

    r    Nrbzutf-8zdata:image/z;base64,r,   )rN   rM   zdata:image/png;base64,
 )r*   str_is_urlospathsplitextopenreadbase64	b64encodedecode	__class____name__r   jsonloadsdumpsreplace)rL   rM   rN   
fileformatfimg
b64encodedurlr"   r"   r'   image_to_url   s   
rh   rg   c                 C   s&   zt | jtv W S  ty   Y dS w )z+Check to see if `url` has a valid protocol.F)r   scheme_VALID_URLS	Exception)rg   r"   r"   r'   rT      s
   rT   
lat_bounds
height_outc              
   C   sH  dd }t |  }|j\}}}t|d d}	t|d d}
|du r%|}|dkr7|ddd	ddddf }|	t d
| dd
|  ||
|	   }||	t d
| dd
|  |||
||	   }t |||f}t|D ] }t|D ]}t 	||||dd||f |dd||f< quqo|dkr|ddd	ddddf }|S )aP  
    Transforms an image computed in (longitude,latitude) coordinates into
    the a Mercator projection image.

    Parameters
    ----------

    data: numpy array or equivalent list-like object.
        Must be NxM (mono), NxMx3 (RGB) or NxMx4 (RGBA)

    lat_bounds : length 2 tuple
        Minimal and maximal value of the latitude of the image.
        Bounds must be between -85.051128779806589 and 85.051128779806589
        otherwise they will be clipped to that values.

    origin : ['upper' | 'lower'], optional, default 'upper'
        Place the [0,0] index of the array in the upper left or lower left
        corner of the axes.

    height_out : int, default None
        The expected height of the output.
        If None, the height of the input is used.

    See https://en.wikipedia.org/wiki/Web_Mercator for more details.

    c                 S   s$   t t | t j d d t j S )Ng     f@)r+   arcsinhtanpi)r&   r"   r"   r'   mercator   s   $z$mercator_transform.<locals>.mercatorr   gIECUr    gIECU@NrK   rO   g      ?g      ?)
r+   
atleast_3dcopyshapemaxminlinspacezerosrangeinterp)r   rl   rN   rm   rq   arrayheightwidthnblayerslat_minlat_maxlatslatslatsoutijr"   r"   r'   mercator_transform   s2   !
0r   .c                 c   s    t | ttfr| }n@d| v rdd | d D }n2d| v r*| d r'| d d ng }n!d| v rE| d d rEd| d d v rE| d d d }n| d| }|D ]}t |ttfr^t|V   dS t|E dH  qMdS )	zH
    Returns all the coordinate tuples from a geometry or feature.

    featuresc                 S   s    g | ]}|d  r|d  d qS )geometrycoordinatesr"   )r%   geomr"   r"   r'   r(     s    
ziter_coords.<locals>.<listcomp>r   r   
geometriesr   N)r*   tuplelistgetr#   intiter_coords)rI   r9   r:   r"   r"   r'   r     s*   

r   Flonlatc                 C   s   ddgddgg}t | D ].}t|d d |d t|d d |d gt|d d |d t|d d |d gg}q|rAt|}|S )ze
    Computes the bounds of the object in the form
    [[lat_min, lon_min], [lat_max, lon_max]]

    Nr   r    )r   r   r   r   )r<   r   boundspointr"   r"   r'   
get_bounds.  s   	
r   keyc                 C   s   d dd t| dD S )zConvert a python_style_variable_name to lowerCamelCase.

    Examples
    --------
    >>> camelize("variable_name")
    'variableName'
    >>> camelize("variableName")
    'variableName'
    r   c                 s   s(    | ]\}}|d kr|  n|V  qdS )r   N)
capitalize)r%   r   r&   r"   r"   r'   	<genexpr>R  s   & zcamelize.<locals>.<genexpr>_)join	enumeratesplit)r   r"   r"   r'   camelizeH  s   
r   obj1obj2c                 C   s   t | t |kS )zs
    Return True/False if the normalized rendered version of
    two folium map objects are the equal or not.

    )	normalize)r   r   r"   r"   r'   compare_renderedU  s   r   renderedc                 C   s(   d dd |  D }|dd}|S )zBReturn the input string without non-functional spaces or newlines.r   c                 S   s   g | ]
}|  r|  qS r"   )strip)r%   liner"   r"   r'   r(   `  s    znormalize.<locals>.<listcomp>z, ,)r   
splitlinesrb   )r   r   r"   r"   r'   r   ^  s   r   c              	   c   s    d}z1t jddd\}}t|t| tr| dn|  t| |V  W tj	|r3t
| dS dS tj	|rAt
| w w )z9Yields the path of a temporary HTML file containing data.r   z.htmlfolium_)suffixprefixutf8N)tempfilemkstemprU   writer*   rS   encodecloserV   isfileremove)r   filepathfidr"   r"   r'   temp_html_filepathe  s    
r   item_originalc                 C   sj   t  | }t j|_t|dr3t|jdkr3t	 }|j
 D ]}t|}||_||| < q ||_|S )zBReturn a recursive deep-copy of item where each copy has a new ID.	_childrenr   )rs   uuiduuid4hex_idr1   r4   r   collectionsOrderedDictrJ   	deep_copy_parentget_name)r   itemchildren_newsubitem_originalsubitemr"   r"   r'   r   s  s   
r   elementclsc                 C   s4   | j }|du rtd| t||st||S |S )z:Return the first object in the parent tree of class `cls`.Nz2The top of the tree was reached without finding a )r   r5   r*   get_obj_in_upper_tree)r   r   parentr"   r"   r'   r     s   

r   kwargsc                  K   s   dd |   D S )z=Return a dict with lower-camelcase keys and non-None values..c                 S   s"   i | ]\}}|d urt ||qS N)r   )r%   r   valuer"   r"   r'   
<dictcomp>  s   " z!parse_options.<locals>.<dictcomp>)items)r   r"   r"   r'   parse_options  s   r   textc                 C   s   t dd| S )z6Escape backticks so text can be used in a JS template.z(?<!\\)`z\`)resubr   r"   r"   r'   escape_backticks  s   r   c                 C   s   |  ddS )N"z\")rb   r   r"   r"   r'   escape_double_quotes  s   r   rV   c                 C   s   d dd | dD S )zBConvert a path like obj1.obj2 to array notation: ["obj1"]["obj2"].r   c                 s   s     | ]}d t | dV  qdS )z["z"]N)r   r$   r"   r"   r'   r     s    z?javascript_identifier_path_to_array_notation.<locals>.<genexpr>r   )r   r   )rV   r"   r"   r'   ,javascript_identifier_path_to_array_notation  s   r   c                 C   s   |   }t|tsJ d|S )z=Return the root element of the tree and assert it's a Figure.z8You cannot render this Element if it is not in a Figure.)get_rootr*   r   )rI   figurer"   r"   r'   get_and_assert_figure_root  s   r   c                   @   s.   e Zd ZdZdeed f fddZdd ZdS )JsCodezWrapper around Javascript code.js_codec                 C   s    t |tr|j| _d S || _d S r   )r*   r   r   )selfr   r"   r"   r'   __init__  s   

zJsCode.__init__c                 C   s   | j S r   )r   )r   r"   r"   r'   __str__  s   zJsCode.__str__N)r^   
__module____qualname____doc__r   rS   r   r   r"   r"   r"   r'   r     s    r   r   c                 C   sD   t | ttfr|  dS | dd dkr | dd dvr td| S )z,Parse a font size value, if number set as pxpxNrem)emr   z2The font size must be expressed in rem, em, or px.)r*   r   r#   r5   )r   r"   r"   r'   parse_font_size  s
   
 r   )NrK   )rK   N)F)QrZ   r   rs   r_   r7   rU   r   r   r   
contextlibr   typingr   r   r   r   r   r   r	   r
   r   r   r   urllib.parser   r   r   r   numpyr+   branca.elementr   r   branca.utilitiesr   r   r   r   r   pandasr-   ImportErrorr#   TypeLineTypeMultiLinerS   booldictTypeJsonValueNoNoneTypeJsonValueTypePathOptions
TypeBoundssetrj   discardaddr;   rA   rF   rH   rE   rh   rT   r   r,   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r"   r"   r"   r'   <module>   s    4

-

*

B!
	
	 