o
    /ѹg^,                     @   s  d dl Z d dlmZ d dlmZ d dlmZ d dlZd dlZd dl	m
Z
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mZmZmZ d d	lmZ d d
lmZ e ZG dd deZ G dd deZ!G dd deZ"G dd deZ#G dd deZ$dd Z%eG dd deZ&eG dd deZ'eG dd deZ(eG dd de(Z)eG dd  d e(Z*eG d!d" d"eZ+G d#d$ d$eZ,eG d%d& d&e,Z-eG d'd( d(e,Z.eG d)d* d*e,Z/G d+d, d,eZ0dS )-    N)ABC)
HTTPStatus)Optional)asdictdefinefield
validators)ModelScopeConfig)API_RESPONSE_FIELD_DATAAPI_RESPONSE_FIELD_MESSAGE)NotLoginExceptionNotSupportErrorRequestErrorhandle_http_responseis_okraise_for_http_status)get_endpoint)
get_loggerc                   @      e Zd ZdZdZdS )AcceleratorcpuZgpuN)__name__
__module____qualname__CPUGPU r   r   Y/Users/admin/.pyenv/versions/3.10.0/lib/python3.10/site-packages/modelscope/hub/deploy.pyr          r   c                   @   s   e Zd ZdZdS )VendorZeasN)r   r   r   EASr   r   r   r   r      s    r   c                   @   r   )	EASRegionz
cn-beijingzcn-hangzhouN)r   r   r   ZbeijingZhangzhour   r   r   r   r!   !   r   r!   c                   @       e Zd ZdZdZdZdZdZdS )EASCpuInstanceTypezTEAS Cpu Instance Type, ref(https://help.aliyun.com/document_detail/144261.html)
    zecs.c6.2xlargezecs.c6.4xlargezecs.c6.6xlargezecs.c6.8xlargeNr   r   r   __doc__ZtinysmallZmediumZlarger   r   r   r   r#   &       r#   c                   @   r"   )EASGpuInstanceTypezTEAS Gpu Instance Type, ref(https://help.aliyun.com/document_detail/144261.html)
    zecs.gn5-c28g1.7xlargezecs.gn5-c8g1.4xlargezecs.gn6i-c24g1.12xlargezecs.gn6e-c12g1.3xlargeNr$   r   r   r   r   r(   /   r'   r(   c                 C   s    || j krtd|| j f d S )NzG'min_replica' value: %s has to be smaller than 'max_replica' value: %s!)max_replica
ValueError)instance	attributevaluer   r   r   min_smaller_than_max8   s   
r.   c                   @   sJ   e Zd ZU dZededdZee	d< edede
gdZee	d< dS )ServiceScalingConfigzResource scaling config
       Currently we ignore max_replica
    Args:
        max_replica: maximum replica
        min_replica: minimum replica
       defaultZ	validatorr)   min_replicaN)r   r   r   r%   r   r   ger)   int__annotations__r.   r3   r   r   r   r   r/   ?   s   
 r/   c                   @   sF   e Zd ZU dZeed< eed< eej	e
ej	ejgdZeed< dS )ServiceResourceConfigzEas Resource request.

    Args:
        accelerator: the accelerator(cpu|gpu)
        instance_type: the instance type.
        scaling: The instance scaling config.
    Zinstance_typeZscalingr1   acceleratorN)r   r   r   r%   strr6   r/   r   r   r   r   in_r   r8   r   r   r   r   r7   L   s   
 r7   c                   @   s   e Zd ZdS )ServiceProviderParametersN)r   r   r   r   r   r   r   r;   \   s    r;   c                   @   sZ   e Zd ZU dZeed< eed< eed< dZee ed< ee	j
ee	j
gdZeed< dS )	EASDeployParametersaA  Parameters for EAS Deployment.

    Args:
        resource_group: the resource group to deploy, current default.
        region: The eas instance region(eg: cn-hangzhou).
        access_key_id: The eas account access key id.
        access_key_secret: The eas account access key secret.
        vendor: must be 'eas'
    regionaccess_key_idaccess_key_secretNresource_groupr1   vendor)r   r   r   r%   r9   r6   r@   r   r   r   r    r   r:   rA   r   r   r   r   r<   a   s   
 	r<   c                   @   sZ   e Zd ZU dZeed< eed< dZeed< dZeed< ee	j
ee	j
gdZeed< dS )	EASListParametersa@  EAS instance list parameters.

    Args:
        resource_group: the resource group to deploy, current default.
        region: The eas instance region(eg: cn-hangzhou).
        access_key_id: The eas account access key id.
        access_key_secret: The eas account access key secret.
        vendor: must be 'eas'
    r>   r?   Nr=   r@   r1   rA   )r   r   r   r%   r9   r6   r=   r@   r   r   r    r   r:   rA   r   r   r   r   rB   t   s   
 	rB   c                   @   s:   e Zd ZU dZeed< eed< eed< eed< eed< dS )DeployServiceParametersa  Deploy service parameters

    Args:
        instance_name: the name of the service.
        model_id: the modelscope model_id
        revision: the modelscope model revision
        resource: the resource requirement.
        provider: the cloud service provider.
    instance_namemodel_idrevisionresourceproviderN)r   r   r   r%   r9   r6   r7   r;   r   r   r   r   rC      s   
 	rC   c                   @   s   e Zd ZdZdd ZdS )AttrsToQueryStringz7Convert the attrs class to json string.

    Args:
    c                 C   sD   t | jdd d}t|}t| tj|}t| d| }|S )Nc                 S   s   |d uS Nr   )attrr-   r   r   r   <lambda>   s    z1AttrsToQueryString.to_query_str.<locals>.<lambda>)filterzprovider=%s)r   rH   jsondumpsprinturllibparse
quote_plus)selfZ	self_dictZjson_strZsafe_strZquery_paramr   r   r   to_query_str   s   

zAttrsToQueryString.to_query_strN)r   r   r   r%   rU   r   r   r   r   rI      s    rI   c                   @   s.   e Zd ZU eed< dZeed< dZeed< dS )ListServiceParametersrH   r   skipd   limitN)r   r   r   r;   r6   rW   r5   rY   r   r   r   r   rV      s   
 rV   c                   @      e Zd ZU eed< dS )GetServiceParametersrH   Nr   r   r   r;   r6   r   r   r   r   r[         
 r[   c                   @   rZ   )DeleteServiceParametersrH   Nr\   r   r   r   r   r^      r]   r^   c                
   @   s   e Zd ZdZdddZdedededed	ef
d
dZded	efddZ	ded	efddZ
		dd	edee dee fddZdS )ServiceDeployerzEFacilitate model deployment on to supported service provider(s).
    Nc                 C   sB   |d ur|nt  | _dt i| _t | _| jd u rtdd S )Nz
user-agentz5Token does not exist, please login with HubApi first.)r   endpointr	   Zget_user_agentheadersZget_cookiescookiesr   )rT   r`   r   r   r   __init__   s   

zServiceDeployer.__init__rE   rF   rD   rG   rH   c                 C   s   |j tjkrtd|j  t|||||d}| j d}t|}tj||| j	| j
d}	t|	t| j	d |	jtjkrU|	jtjk rUt|	 rM|	 t }
|
S t|	 t t|	 dS )a  Deploy model to cloud, current we only support PAI EAS, this is an async API ,
        and the deployment could take a while to finish remotely. Please check deploy instance
        status separately via checking the status.

        Args:
            model_id (str): The deployed model id
            revision (str): The model revision
            instance_name (str): The deployed model instance name.
            resource (ServiceResourceConfig): The service resource information.
            provider (ServiceProviderParameters): The service provider parameter

        Raises:
            NotSupportError: Not supported platform.
            RequestError: The server return error.

        Returns:
            ServiceInstanceInfo: The information of the deployed service instance.
        z1Not support vendor: %s ,only support EAS current.)rD   rE   rF   rG   rH   z/api/v1/deployer/endpoint)rN   rb   ra   Zcreate_serviceN)rA   r   r    r   rC   r`   r   requestspostrb   ra   r   loggerstatus_coder   OKMULTIPLE_CHOICESr   rN   r
   r   r   r   )rT   rE   rF   rD   rG   rH   Zcreate_paramspathbodyrdatar   r   r   create   s4   zServiceDeployer.createc                 C      t |d}d| j|| f }tj|| j| jd}t|t| jd |j	t
jkr=t| r5| t }|S t| t t| dS )a  Query the specified instance information.

        Args:
            instance_name (str): The deployed instance name.
            provider (ServiceProviderParameters): The cloud provider information, for eas
                need region(eg: ch-hangzhou), access_key_id and access_key_secret.

        Raises:
            RequestError: The request is failed from server.

        Returns:
            Dict: The information of the requested service instance.
        rH   !%s/api/v1/deployer/endpoint/%s?%srb   ra   Zget_serviceN)r[   r`   rU   rd   getrb   ra   r   rf   rg   r   rh   r   rN   r
   r   r   r   rT   rD   rH   paramsrj   rl   rm   r   r   r   rs      s   
zServiceDeployer.getc                 C   ro   )a   Delete deployed model, this api send delete command and return, it will take
        some to delete, please check through the cloud console.

        Args:
            instance_name (str): The instance name you want to delete.
            provider (ServiceProviderParameters): The cloud provider information, for eas
                need region(eg: ch-hangzhou), access_key_id and access_key_secret.

        Raises:
            RequestError: The request is failed.

        Returns:
            Dict: The deleted instance information.
        rp   rq   rr   Zdelete_serviceN)r^   r`   rU   rd   deleterb   ra   r   rf   rg   r   rh   r   rN   r
   r   r   r   rt   r   r   r   rv     s   
zServiceDeployer.deleter   rX   rW   rY   c                 C   s   t |||d}d| j| f }tj|| j| jd}t|t| jd |j	t
jkr>t| r6| t }|S t| t t| dS )a  List deployed model instances.

        Args:
            provider (ServiceProviderParameters): The cloud service provider parameter,
                for eas, need access_key_id and access_key_secret.
            skip (int, optional): start of the list, current not support.
            limit (int, optional): maximum number of instances return, current not support

        Raises:
            RequestError: The request is failed from server.

        Returns:
            List: List of instance information
        )rH   rW   rY   z%s/api/v1/deployer/endpoint?%srr   Zlist_service_instancesN)rV   r`   rU   rd   rs   rb   ra   r   rf   rg   r   rh   r   rN   r
   r   r   r   )rT   rH   rW   rY   ru   rj   rl   rm   r   r   r   list1  s   zServiceDeployer.listrJ   )r   rX   )r   r   r   r%   rc   r9   r7   r;   rn   rs   rv   r   r5   rw   r   r   r   r   r_      s&    
	
. r_   )1rQ   abcr   httpr   typingr   rN   rd   attrsr   r   r   r   Zmodelscope.hub.apir	   Zmodelscope.hub.constantsr
   r   Zmodelscope.hub.errorsr   r   r   r   r   r   Zmodelscope.hub.utils.utilsr   Zmodelscope.utils.loggerr   rf   objectr   r   r!   r#   r(   r.   r/   r7   r;   r<   rB   rC   rI   rV   r[   r^   r_   r   r   r   r   <module>   sN     		