HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/projects/env/lib/python3.10/site-packages/uszipcode/__pycache__/search.cpython-38.pyc
U

:�aĉ�@s
dZddlZddlZddlZddlZddlZddlmZddlZ	ddl
mZddlm
Z
ddlZddlmZddlmZmZddlmZmZmZmZmZdd	lmZmZmZdd
lm Z m!Z!dZ"dZ#e�$�j%Z&ee&d
�j%Z'ej(ej)e*ej)d�dd�Z+Gdd�de,�Z-dS)zE
This module allows developer to query zipcode with super clean API.
�N)�OrderedDict)�Engine)�Path)�extract�
extractOne�)�download_db_file�DEFAULT_SIMPLE_DB_FILE_PATH�"DEFAULT_COMPREHENSIVE_DB_FILE_PATH�SIMPLE_DB_FILE_DOWNLOAD_URL�"COMPREHENSIVE_DB_FILE_DOWNLOAD_URL)�ZipcodeTypeEnum�
SimpleZipcode�ComprehensiveZipcode)�MAPPER_STATE_ABBR_SHORT_TO_LONG�MAPPER_STATE_ABBR_LONG_TO_SHORT�dist�z
.uszipcode��
enum_class�attr�valuecCs:t||�std�|||���||kr6td�|||���dS)Nz9param '{}' validation error: '{}' is not a valid {} type!z:param '{}' validation error: '{}' is not a valid {} value!)�
isinstance�	TypeError�format�
ValueErrorr�r�E/Users/sanhehu/Documents/GitHub/uszipcode-project/uszipcode/search.py�validate_enum_arg-s$
������rc@s�eZdZUdZGdd�dej�Zejeej	e
iZejeej	e
iZejdddfeejedfejedfed�dd�Zdd	�Zd
d�Zdd
�Zdd�Zdd�ZdZejeed<dZejeed<dZejeefed<dZ ejeefed<dd�Z!e"dd��Z#e"dd��Z$e"dd��Z%e"dd��Z&d[ee'e(ejed"�d#d$�Z)d\eee'e(ejed%�d&d'�Z*e+ee'd(�d)d*��Z,dddddddddddddddddddddddde-j.e/j0j1d e2feje(e3feeeeeje(e3feje(e3fe(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e(e-ee'e(d+�d,d-�Z4d]eje(efe'eje/e5dfd.�d/d0�Z6e-j.e/j0j1d e2fee-ee'e(d1�d2d3�Z7e-j.e/j0j1d e2fee-ee'e(d4�d5d6�Z8e-j.e/j0j1d e2fee-ee'e(d7�d8d9�Z9e-j.e/j0j1d e2fee-ee'e(d:�d;d<�Z:e-j.e/j0j1d e2feee-ee'e(d=�d>d?�Z;d@e-j.e<d e2feje(e3feje(e3feje(e3fe-ee'e(dA�dBdC�Z=dDdEe-j.e/j>j1dFe2fe(e(e-ee'e(dG�dHdI�Z?dDdEe-j.e/j@j1dFe2fe(e(e-ee'e(dG�dJdK�ZAdDdEe-j.e/jBj1dFe2fe(e(e-ee'e(dG�dLdM�ZCdDdEe-j.e/jDj1dFe2fe(e(e-ee'e(dG�dNdO�ZEdDdEe-j.e/jFj1dFe2fe(e(e-ee'e(dG�dPdQ�ZGdDdEe-j.e/jHj1dFe2fe(e(e-ee'e(dG�dRdS�ZIdDdEe-j.e/jJj1dFe2fe(e(e-ee'e(dG�dTdU�ZKdDdEe-j.e/jLj1dFe2fe(e(e-ee'e(dG�dVdW�ZMedX�dYdZ�ZNdS)^�SearchEngineay
    Zipcode Search Engine.

    :type simple_or_comprehensive: SearchEngine.SimpleOrComprehensiveArgEnum
    :param simple_or_comprehensive: default SearchEngine.SimpleOrComprehensiveArgEnum,
        use the simple zipcode db. Rich Demographics, Real Estate, Employment,
        Education info are not available. if
        SearchEngine.SimpleOrComprehensiveArgEnum.comprehensive,
        use the rich info database.

    :type db_file_path: str
    :param db_file_path: where you want to download the sqlite database to. This
        property allows you to customize where you want to store the data file
        locally. by default it is ${HOME}/.uszipcode/...

    :type download_url: str
    :param download_url: where you want to download the sqlite database file from.
        This property allows you to upload the .sqlite file to your private file
        host and download from it. In case the default download url fail.

    :type engine: Engine
    :param engine: a sqlachemy engine object. It allows you to use any
        backend database instead of the default sqlite database.

    Usage::

        >>> search = SearchEngine()
        >>> zipcode = search.by_zipcode("10001")

    Context Manager::

        >>> with SearchEngine() as search:
        ...     for zipcode in search.by_coordinates(lat, lng, radius):
        ...         # do what every you want


    :meth:`SearchEngine.query` provides mass options to customize your query.

    :attr:`SearchEngine.ses` is a ``sqlalchemy.orm.Session`` object, you can
    use it for query. For example::

        >>> from uszipcode import SearchEngine, SimpleZipcode, ComprehensiveZipcode
        >>> search = SearchEngine()
        >>> search.ses.scalar(SimpleZipcode).filter(SimpleZipcode.zipcode=="10001")

    .. note::

        :class:`SearchEngine` is not multi-thread safe. You should create different
        instance for each thread.
    c@seZdZe��Ze��ZdS)z)SearchEngine.SimpleOrComprehensiveArgEnumN)�__name__�
__module__�__qualname__�enum�auto�simple�
comprehensiverrrr�SimpleOrComprehensiveArgEnumwsr'N)�simple_or_comprehensive�db_file_path�download_url�enginecCs�t|jd|�||_t|t�r2d|_d|_||_n(||_||_|��t	�
�j|jd�|_|j|_t
�|j�|_|j|_||j|jjkr�t|_n|j|jjkr�t|_dS)Nr()�path)rr'r(rrr)r*r+�_download_db_file_if_not_exists�sam�
EngineCreator�
create_sqliteZeng�orm�Session�session�sesr%r�	zip_klassr&r)�selfr(r)r*r+rrr�__init__�s,�
zSearchEngine.__init__cCs�|jdkr|j|j|_|jdkr0|j|j|_t|j�}|��s�|j|jjkrft	|j|jddd�n"|j|jj
kr�t	|j|jddd�dS)Ni)r)r*�
chunk_sizeZ
progress_sizei )r)�_default_db_file_path_mapperr(r*�_default_download_url_mapperr�existsr'r%rr&)r6�prrrr-�s(


��z,SearchEngine._download_db_file_if_not_existscCs|S�Nr�r6rrr�	__enter__�szSearchEngine.__enter__cGs|��dSr=)�close)r6�exc_inforrr�__exit__�szSearchEngine.__exit__cCs|jr|��dSr=�r4r@r>rrr�__del__�szSearchEngine.__del__cCs|j��dS)z,
        close database connection.
        NrCr>rrrr@�szSearchEngine.close�
_city_list�_state_list�_state_to_city_mapper�_city_to_state_mapperc	CsZt�}t�}t�}t�|jj|jj�}|j�|�D]~\}}|dk	r2|�	|�|dk	r2|�
�}z||�	|�Wn|h||<YnXz||�	|�Wq2|h||<Yq2Xq2t|�|_|j�
�tt�|_|j�
�ttdd�|��D�dd�d��|_|j��D]}|�
��qttdd�|��D�dd�d��|_|j��D]}|�
��qFdS)Ncss|]\}}|t|�fVqdSr=��list)�.0�stateZcity_setrrr�	<genexpr>�s�z/SearchEngine._get_cache_data.<locals>.<genexpr>cSs|dS�Nrr��xrrr�<lambda>��z.SearchEngine._get_cache_data.<locals>.<lambda>��keycss|]\}}|t|�fVqdSr=rI)rK�cityZ	state_setrrrrMs�cSs|dSrNrrOrrrrQrR)�set�dict�sa�selectr5�
major_cityrLr4�execute�add�upperrJrE�sortrrFr�sorted�itemsrG�valuesrH)	r6Z	_city_setrGrH�stmtrZrL�	city_list�
state_listrrr�_get_cache_data�sR




���	���	zSearchEngine._get_cache_datacCs|jdkr|��|jS)z1
        Return all available city name.
        N)rErer>rrrrcs
zSearchEngine.city_listcCs|jdkr|��|jS)z2
        Return all available state name.
        N)rFrer>rrrrds
zSearchEngine.state_listcCs|jdkr|��|jSr=)rGrer>rrr�state_to_city_mapper#s
z!SearchEngine.state_to_city_mappercCs|jdkr|��|jSr=)rHrer>rrr�city_to_state_mapper)s
z!SearchEngine.city_to_state_mapperT�F)rL�
best_match�min_similarity�returncCs�t�}|��tkr"|�|���nX|rNt||j�\}}||krz|�t|�n,t||j�D]\}}||krZ|�t|�qZt|�dkr�d}t	||��|S)z�
        Fuzzy search correct state.

        :param best_match: bool, when True, only the best matched state
            will be return. otherwise, will return all matching states.
        rzT'%s' is not a valid state name, use 2 letter short name or correct full name please.)
rJr]r�appendrrdrr�lenr)r6rLrirjZresult_state_short_listZ
state_long�
confidence�messagerrr�
find_state/s$��zSearchEngine.find_state)rUrLrirjrkc	Cs�|r&|j|dd�d}|j|��}n|j}t�}|rXt||�\}}||kr~|�|�n&t||�D]\}}||krb|�|�qbt|�dkr�t	d|��|S)u�
        Fuzzy search correct city.

        :param city: city name.
        :param state: search city in specified state.
        :param best_match: bool, when True, only the best matched city
            will return. otherwise, will return all matching cities.

        **中文文档**

        如果给定了state, 则只在指定的state里的城市中寻找, 否则, 在全国所有的城市中寻找。
        T�rirz'%s' is not a valid city name)
rprfr]rcrJrrlrrmr)	r6rUrLrirjZstate_shortZ	city_poolZresult_city_listrnrrr�	find_cityUszSearchEngine.find_city)�sort_by�flag_radius_querycCsf|dkr|rbt}nPt|t�r\|��tkrB|dkr<d}t|��t}qb|tjjkrbd}t|��n|j}|S)z�
        Result ``sort_by`` argument.

        :param sort_by: str, or sqlalchemy ORM attribute.
        :param flag_radius_query:
        :return:
        NFz<`sort_by` arg can be 'dist' only under distance based query!z?`sort_by` arg has to be one of the Zipcode attribute or 'dist'!)	�SORT_BY_DISTr�str�lowerrr�	__table__�columns�name)rsrt�msgrrr�_resolve_sort_bys	

zSearchEngine._resolve_sort_by)�zipcode�prefix�patternrUrL�lat�lng�population_lower�population_upper�population_density_lower�population_density_upper�land_area_in_sqmi_lower�land_area_in_sqmi_upper�water_area_in_sqmi_lower�water_area_in_sqmi_upper�housing_units_lower�housing_units_upper�occupied_housing_units_lower�occupied_housing_units_upper�median_home_value_lower�median_home_value_upper�median_household_income_lower�median_household_income_upper�zipcode_typers�	ascending�returnsc1Cs�t�}tt|ttf�t|ttf�t|ttf�g�}|dk�rBd}|dkrRtd��n<|dkr`d} n.|dkrnd} n |d	kr|d
} n|dkr�d} nd
} |d	kr�d}!tj�|!�d}"t	�
|�d}#t|| |"�}$t|| |#�}%||$}&||$}'||%}(||%})|�|j
j|&k�|�|j
j|'k�|�|j
j|(k�|�|j
j|)k�n|dk�rRd}nd}!t|!��|dk	�r(|dk	�r(|j|dd�d}|j||dd�d}|�|j
j|k�|�|j
j|k�zN|j|dd�d}|j||dd�d}|�|j
j|k�|�|j
j|k�Wntk
�r$gYSXn�|dk	�rxz(|j|dd�d}|�|j
j|k�Wntk
�rtgYSXnR|dk	�r�z*|j|ddd�d}|�|j
j|k�Wntk
�r�gYSXnt|dk|dk|dkg�dk�r�d}!t|!��|dk	�r|�|j
j|jk�|dk	�r4|�|j
jt|�k�|dk	�rV|�|j
j�t|���|dk	�r||�|j
j�dt|���|	dk	�r�|�|j
j|	k�|
dk	�r�|�|j
j|
k�|dk	�r�|�|j
j|k�|dk	�r�|�|j
j|k�|
dk	�r|�|j
j|
k�|dk	�r$|�|j
j|k�|dk	�r@|�|j
j|k�|dk	�r\|�|j
j|k�|dk	�rx|�|j
j|k�|dk	�r�|�|j
j|k�|dk	�r�|�|j
j|k�|dk	�r�|�|j
j|k�|dk	�r�|�|j
j |k�|dk	�r|�|j
j |k�|dk	�r |�|j
j!|k�|dk	�r<|�|j
j!|k�|�"||�}t#�$|j
�j%|�}*|dk�rfn:|t&k�rrn.t'|j
|�}+|�r�|+�(�},n|+�)�},|*�*|,�}*|�r~t�}-|j+�,|*�D]*}.|.�-||�}/|/|k�r�|-�|/|.f��q�|t&k�rf|�r&|�rt.j/||-dd�d�}0ntt0|-dd�d��}0n2|�rBt.j1||-dd�d�}0ntt0|-dd�dd��}0dd�|0D�Sd d�|-d|�D�Sn |�r�|*�2|�}*|j+�,|*��3�SdS)!a�
        Query zipcode the simple way.

        :param zipcode: int or str, find the exactly matched zipcode. Will be
            automatically zero padding to 5 digits
        :param prefix: str, zipcode prefix.
        :param pattern: str, zipcode wildcard.
        :param city: str, city name.
        :param state: str, state name, two letter abbr or state full name.
        :param lat: latitude.
        :param lng: longitude.
        :param radius: number, only returns zipcodes within a specific circle.
        :param population_lower:
        :param population_upper:
        :param population_density_lower:
        :param population_density_upper:
        :param land_area_in_sqmi_lower:
        :param land_area_in_sqmi_upper:
        :param water_area_in_sqmi_lower:
        :param water_area_in_sqmi_upper:
        :param housing_units_lower:
        :param housing_units_upper:
        :param occupied_housing_units_lower:
        :param occupied_housing_units_upper:
        :param median_home_value_lower:
        :param median_home_value_upper:
        :param median_household_income_lower:
        :param median_household_income_upper:
        :param zipcode_type: str or :class`~uszipcode.model.ZipcodeType` attribute.
            if None, allows to return any type of zipcode.
            if specified, only return specified zipcode type.
        :param sort_by: str or :class:`~uszipcode.model.Zipcode` attribute,
            specified which field is used for sorting.
        :param ascending: bool, True means ascending, False means descending.
        :param returns: int or None, limit the number of result to returns.

        :return: list of :class:`~uszipcode.model.SimpleZipcode` or
            :class:`~uszipcode.model.ComprehensiveZipcode`.
        �Trz&`radius` parameters can't less than 0!�2g�������?�dg�������?�g�?i�g�?g@zL
warning! search within radius >= 250 miles may greatly slow down the query!g^�IKQ@FzDYou can either specify all of `lat`, `lng`, `radius` or none of themNrqrzBYou can only specify one of the `zipcode`, `prefix` and `pattern`!z%%%s%%cSs|dSrNrrOrrrrQ�rRz$SearchEngine.query.<locals>.<lambda>rScSs|dSrNrrOrrrrQ�rRcSs|dSrNrrOrrrrQ�rRcSs|dSrNrrOrrrrQ�rR)rT�reversecSsg|]\}}|�qSrr�rK�_�zrrr�
<listcomp>�sz&SearchEngine.query.<locals>.<listcomp>cSsg|]\}}|�qSrrr�rrrr��s)4rJ�sumr�int�floatr�sys�stdout�write�math�cos�absrlr5r�r�rprrrLrZr�rr}rv�
startswith�like�
population�population_density�land_area_in_sqmi�water_area_in_sqmi�
housing_units�occupied_housing_units�median_home_value�median_household_incomer|rXrY�whereru�getattr�asc�desc�order_byr4�scalarsZ	dist_from�heapq�	nsmallestr_�nlargest�limit�all)1r6r}r~rrUrLr�r��radiusr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rsr�r��filtersZ_n_radius_param_not_nullrtZradius_coefr{Zdist_btwn_lat_degZdist_btwn_lon_degZlat_degr_radZlon_degr_radZ	lat_lowerZ	lat_upperZ	lng_lowerZ	lng_upperrb�fieldZby�pairsr�rZ	pairs_newrrr�query�sVK�




 



�



�

�

�

�

�

�



�

�

�

�

�

�





���
zSearchEngine.query)r}�zero_paddingrkcCs,|rt|��d�}nt|�}|j�|j|�S)a�
        Search zipcode by exact 5 digits zipcode. No zero padding is needed.

        :param zipcode: int or str, the zipcode will be automatically
            zero padding to 5 digits.
        :param zipcode_type: str or :class`~uszipcode.model.ZipcodeType` attribute.
            by default, it returns any zipcode type.
        :param zero_padding: bool, toggle on and off automatic zero padding.
        r)rv�zfillr4�getr5)r6r}r�rrr�
by_zipcode�szSearchEngine.by_zipcode)r~r�rsr�r�cCs|j|||||d�S)zb
        Search zipcode information by first N digits.

        Returns multiple results.
        )r~rsr�r�r��r�)r6r~r�rsr�r�rrr�	by_prefix�s
�zSearchEngine.by_prefix)rr�rsr�r�cCs|j|||||d�S)zP
        Search zipcode by wildcard.

        Returns multiple results.
        )rrsr�r�r�r�)r6rr�rsr�r�rrr�
by_pattern�s
�zSearchEngine.by_pattern)rUr�rsr�r�cCs|j|||||d�S)z�
        Search zipcode information by fuzzy City name.

        My engine use fuzzy match and guess what is the city you want.
        )rUrsr�r�r�r�)r6rUr�rsr�r�rrr�by_city�s
�zSearchEngine.by_city)rLr�rsr�r�cCs|j|||||d�S)z�
        Search zipcode information by fuzzy State name.

        My engine use fuzzy match and guess what is the state you want.
        )rLrsr�r�r�r�)r6rLr�rsr�r�rrr�by_states
�zSearchEngine.by_state)rUrLr�rsr�r�cCs|j||||||d�S)z�
        Search zipcode information by fuzzy city and state name.

        My engine use fuzzy match and guess what is the state you want.
        )rUrLrsr�r�r�r�)r6rUrLr�rsr�r�rrr�by_city_and_states�zSearchEngine.by_city_and_stateg9@)r�r�r�r�rsr�r�c	Cs|j|||||||d�S)u�
        Search zipcode information near a coordinates on a map.

        Returns multiple results.

        :param lat: center latitude.
        :param lng: center longitude.
        :param radius: only returns zipcode within X miles from ``lat``, ``lng``.

        **中文文档**

        1. 计算出在中心坐标处, 每一经度和纬度分别代表多少miles.
        2. 以给定坐标为中心, 画出一个矩形, 长宽分别为半径的2倍多一点, 找到该
          矩形内所有的Zipcode.
        3. 对这些Zipcode计算出他们的距离, 然后按照距离远近排序。距离超过我们
          限定的半径的直接丢弃.
        )r�r�r�rsr�r�r�r�)r6r�r�r�r�rsr�r�rrr�by_coordinates)s�zSearchEngine.by_coordinates���lF)rwr]r�rsr�r�cCs|j||||||d�S)zA
        Search zipcode information by population range.
        )r�r�rsr�r�r�r��r6rwr]r�rsr�r�rrr�
by_populationJs�zSearchEngine.by_populationcCs|j||||||d�S)z�
        Search zipcode information by population density range.

        `population density` is `population per square miles on land`
        )r�r�rsr�r�r�r�r�rrr�by_population_density]s�z"SearchEngine.by_population_densitycCs|j||||||d�S)zK
        Search zipcode information by land area / sq miles range.
        )r�r�rsr�r�r�r�r�rrr�by_land_area_in_sqmirs�z!SearchEngine.by_land_area_in_sqmicCs|j||||||d�S)zL
        Search zipcode information by water area / sq miles range.
        )r�r�rsr�r�r�r�r�rrr�by_water_area_in_sqmi�s�z"SearchEngine.by_water_area_in_sqmicCs|j||||||d�S)z?
        Search zipcode information by house of units.
        )r�r�rsr�r�r�r�r�rrr�by_housing_units�s�zSearchEngine.by_housing_unitscCs|j||||||d�S)zH
        Search zipcode information by occupied house of units.
        )r�r�rsr�r�r�r�r�rrr�by_occupied_housing_units�s�z&SearchEngine.by_occupied_housing_unitscCs|j||||||d�S)zB
        Search zipcode information by median home value.
        )r�r�rsr�r�r�r�r�rrr�by_median_home_value�s�z!SearchEngine.by_median_home_valuecCs|j||||||d�S)zH
        Search zipcode information by median household income.
        )r�r�rsr�r�r�r�r�rrr�by_median_household_income�s�z'SearchEngine.by_median_household_income)r}cCs8d�|jjt|��d��}t�|�}t|j�	|��
��S)Nz%SELECT * FROM {} WHERE zipcode = '{}'r)rr5�
__tablename__rvr�rX�textrWr+r[�fetchone)r6r}�sqlrbrrr�inspect_raw_data�s�
zSearchEngine.inspect_raw_data)Trh)NTrh)T)Or r!r"�__doc__r#�Enumr'r%r	r&r
r9rrr:�typing�Unionrvrr7r-r?rBrDr@rE�List�__annotations__rFrG�DictrJrHre�propertyrcrdrfrg�boolr�rprr�staticmethodr|r
ZStandardrr}rz�
DEFAULT_LIMITr�r�rr�r�r�r�r�r�rur�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrCsh
3����!2



��)��*�� ��������������#����������������r).r�r�r�r#r�r��collectionsr�
sqlalchemyrXZsqlalchemy.enginer�sqlalchemy.ormr1�sqlalchemy_mater.Zpathlib_materZfuzzywuzzy.processrrZdbrr	r
rrZmodelr
rrZ
state_abbrrrrur��home�abspath�HOMEZHOME_USZIPCODE�Typer�rvr�objectrrrrr�<module>s0

�