
    ]j6                         d 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
 ddlmZ  ej                  e      ZdZd eej$                  j'                  dd	            fZi Zd
Z G d de      Z G d de      Zy)z .. include::../docs/client.md
    N)Optional)	BaseModelconstrroot_validator)HTTPAdapter   g      $@TIMEOUT   zhttp://localhost:8080c                   t    e Zd ZU dZee   ed<   dZee   ed<   dZe e	          ed<    e
dd      d        Zy)ClientCredentialsNemailpasswordapi_keyT)preallow_reusec                 B    d|v sd|v sJ d       d|vsd|v sJ d       |S )Nr   r   z3At least one of email or api_key should be includedr   z.Provide both email and password for login auth )clsvaluess     I/root/env/lib/python3.12/site-packages/label_studio_sdk/_legacy/client.pyeither_key_or_email_passwordz.ClientCredentials.either_key_or_email_password   sK     vf!4	A@	A4 6!Z6%9	<;	<9    )__name__
__module____qualname__r   r   str__annotations__r   r   r   r   r   r   r   r   r   r      sH    E8C="Hhsm""&GXfh&$/ 0r   r   c            	           e Zd Z	 	 	 	 	 	 	 	 	 ddedededefdZd Zdefd	Zd
 Z	d Z
defdZd Zd Zd Zd Zd Zd ZddZd Zd Zd Zd Zd Zd Zd Zd Zy)ClientNurlr   extra_headerscookiesc
                    |st        j                  dt              }|j                  d      | _        |	| _        |xs | j                         | _        || _        ||t        j                  d      }|t        |      }||t        d      |j                  r|j                  n| j                  |      | _        dd| j                   i| _        |r | j                  j                  d	d
| i       |r| j                  j                  |       |r|n| j                         | _        d| j                   v | _        y)a  Initialize the client. Do this before using other Label Studio SDK classes and methods in your script.

        Parameters
        ----------
        url: str
            Label Studio host address.
            Example: http://localhost:8080
        api_key: str
            User token for the API. You can find this on your user account page in Label Studio.
        credentials: ClientCredentials
            User email and password or api_key.
        session: requests.Session()
            If None, a new one is created.
        extra_headers: dict
            Additional headers that will be passed to each http request
        cookies: dict
            Cookies that will be passed to each http request.
        oidc_token: str
            Bearer token for proxy authentication - in case the server is behind an authenticating proxy.
        versions: dict
            Versions of Label Studio components for the connected instance
        make_request_raise: bool
            If true, make_request will raise exceptions on request errors
        LABEL_STUDIO_URL/NLABEL_STUDIO_API_KEY)r   zlIf neither 'api_key' nor 'credentials' are provided, 'LABEL_STUDIO_API_KEY' environment variable must be setAuthorizationzToken zProxy-AuthorizationzBearer zlabel-studio-enterprise-backend)osgetenvLABEL_STUDIO_DEFAULT_URLrstripr    make_request_raiseget_sessionsessionr"   r   RuntimeErrorr   get_api_keyheadersupdateget_versionsversionsis_enterprise)
selfr    r   credentialsr.   r!   r"   
oidc_tokenr4   r,   s
             r   __init__zClient.__init__'   s8   H )).0HIC::c?"44$"2"2"4  ?{2ii 67G+G<K?{2  "" !!+. 	 (6$,,)@ALL!6'*8N OPLL. %-$2C2C2E>$--Or   c                 d    | j                  dd      j                         | _        | j                  S )zCall /version api and get all Label Studio component versions

        Returns
        -------
        dict with Label Studio component names and their versions

        GETz/api/version)make_requestjsonr4   )r6   s    r   r3   zClient.get_versionsr   s+     ))%@EEG}}r   r7   c                    | j                  d      }| j                  j                  |       | j                  j                  j                  dd       }t	        di |j	                         d|i}| j                  j                  ||t	        | j                        | j                        j                          | j                  j                  | j                  d            j                         j                  d      }|S )	Nz/user/login	csrftokencsrfmiddlewaretoken)Referer)datar1   r"   z/api/current-user/tokentokenr   )	get_urlr.   getr"   dictpostr    raise_for_statusr=   )r6   r7   	login_url
csrf_token
login_datar   s         r   r0   zClient.get_api_key}   s    LL/	#\\))--k4@
OK,,.OJO
*LL	 	 	

 

LLT\\*CDETVS\ 	
 r   c                 F    | j                  dd      }|j                         S )zCall Label Studio /health endpoint to check the connection to the server.

        Returns
        -------
        dict
            Status string like "UP"
        r;   z/healthr<   r=   )r6   responses     r   check_connectionzClient.check_connection   s"     $$UI6}}r   c                 &     | j                   di |S )List all projects in Label Studio.

        Returns
        -------
        list or `label_studio_sdk.project.Project` instances

        r   )list_projects)r6   query_paramss     r   get_projectszClient.get_projects   s     "t!!1L11r   
project_idc                 2    | j                  dd| d      }|S )zrDelete a project in Label Studio.

        Returns
        -------
        dict
            Status string
        DELETEz/api/projects/r%   )r<   )r6   rU   rN   s      r   delete_projectzClient.delete_project   s$     $$X
|1/MNr   c                     g }| j                         D cg c]  }|j                         d    }}|D ]$  }| j                  |      }|j                  |       & |S c c}w )zDeletes all projects in Label Studio.

        Returns
        -------
        List
            List of (dict) status strings
        id)rR   
get_paramsrX   append)r6   	responsesprojectproject_idsrU   rN   s         r   delete_all_projectszClient.delete_all_projects   sn     	AEASASAUVgw))+D1VV% 	'J**:6HX&	' 	 Ws   Ac           	         ddl m} ddi}|j                  |       | j                  dd|      }|j                  dk(  rg }|j                         d	   D ]m  }|j                  | |d
   |      }|j                  |       t        j                  d|j                   d|j                         j                  d       d       o |S y)rQ      Project	page_sizei r;   z/api/projects)params   resultsrZ   )clientrU   rf   zProject z "titlez" is retrievedN)r^   rd   r2   r<   status_coder=   _create_from_idr\   loggerdebugrZ   r[   rE   )r6   rS   rd   rf   rN   projectsrB   r^   s           r   rR   zClient.list_projects   s     	%x(l#$$UOF$K3&H 	2 !11DJt 2  (wzzl"W-?-?-A-E-Eg-N,O~^ O 'r   c                 &     | j                   di |S )Nr   )start_project)r6   kwargss     r   create_projectzClient.create_project   s    !t!!+F++r   c                     ddl m}  || j                  | j                  | j                  | j
                        } |j                  di | |S )zCreate a new project instance.

        Parameters
        ----------
        kwargs:
            Parameters for `project.start_project(**kwargs)`

        Returns
        -------
        `label_studio_sdk.project.Project`

        rb   rc   )r    r   r.   r4   r   )r^   rd   r    r   r.   r4   rq   )r6   rr   rd   r^   s       r   rq   zClient.start_project   sG     	%LLLL]]	
 	''r   c                 2    ddl m} |j                  | |      S )a  Return project SDK object by ID existed in Label Studio

        Parameters
        ----------
        id: int
            Project ID for the project you want to retrieve.

        Returns
        -------
        `label_studio_sdk.project.Project`

        rb   rc   )r^   rd   get_from_id)r6   rZ   rd   s      r   get_projectzClient.get_project   s     	%""4,,r   c                     ddl m} | j                  dd      }g }|j                         D ]  }| |d<   |j	                   |di |         |S )zReturn all users from the current organization account

        Parameters
        ----------

        Returns
        -------
        list of `label_studio_sdk.users.User`

        rb   Userr;   
/api/usersri   r   )usersrz   r<   r=   r\   )r6   rz   rN   r|   	user_datas        r   	get_userszClient.get_users  sX     	 $$UL9! 	,I"&IhLL*	*+	, r   c                    ddl m} t        ||      rR|j                  r|j                  n|j                  |j                  |j
                  |j                  |j                  dn|}| j                  dd|d      }|j                         }| |d<   |j                  d	k  r |di |S d
|j                  v r|du ryt        j                  dt        |j                               z          y)a  Create a new user

        Parameters
        ----------
        user: User or dict
            User instance, you can initialize it this way:
            User(username='x', email='x@x.xx', first_name='X', last_name='Z')
        exist_ok: bool
            True by default, it won't print error if user exists and exist_ok=True

        Returns
        -------
        `label_studio_sdk.users.User`
            Created user

        rb   ry   )usernamer   
first_name	last_namephonePOSTr{   F)r=   raise_exceptionsri     zalready existsTNzCreate user error: r   )r|   rz   
isinstancer   r   r   r   r   r<   r=   rk   textrm   errorr   )r6   userexist_okrz   payloadrN   r}   s          r   create_userzClient.create_user  s    " 	  $% .2]]DMM

"oo!^^  	 $$Lw % 
 MMO	"	(#%$)$$8==0X5ELL.X]]_1EEFr   c                     ddl m} | j                  sJ d       | j                  dd      }g }|j	                         D ]  }| |d<   |j                   |di |         |S )zReturn all workspaces from the current organization account

        Parameters
        ----------

        Returns
        -------
        list of `label_studio_sdk.workspaces.Workspace`

        rb   )	WorkspacezEWorkspaces are available only for Enterprise instance of Label Studior;   z/api/workspacesri   r   )
workspacesr   r5   r<   r=   r\   )r6   r   rN   r   workspace_datas        r   get_workspaceszClient.get_workspacesE  s{     	* 	SR	S $$U,=>
&mmo 	;N'+N8$i9.9:	; r   c                 X    | j                         }|D ]  }|j                  |k(  s|c S  y)zReturn workspace by title from the current organization account

        Parameters
        ----------
        title: str
            Workspace title

        Returns
        -------
        `label_studio_sdk.workspaces.Workspace` or None

        N)r   rj   )r6   rj   r   	workspaces       r   get_workspace_by_titlezClient.get_workspace_by_title^  s8     ((*
# 	!I%'  	! r   c                     | j                  dd      j                         }|d   }| j                  dd|       }|j                         S )zfReturn active organization for the current user

        Returns
        -------
        dict
        r;   z/api/current-user/whoamiactive_organizationz/api/organizations/rM   )r6   rN   organization_ids      r   get_organizationzClient.get_organizationq  sT     $$U,FGLLN"#89 $$U.A/AR,ST}}r   c                     t        j                         }|j                  j                  t               |j                  dt        t                     |j                  dt        t                     |S )zkCreate a session with requests.Session()

        Returns
        -------
        request.Session

        zhttp://)max_retrieszhttps://)requestsSessionr1   r2   HEADERSmountr   MAX_RETRIES)r6   r.   s     r   r-   zClient.get_session  sO     ""$w'i!EFj++"FGr   c                 B    | j                    d|j                  d       S )zmGet the URL of the Label Studio server

        Returns
        -------
        String with the URL

        r%   )r    lstrip)r6   suffixs     r   rD   zClient.get_url  s#     ((1V]]3/011r   c           	         d|vr	t         |d<   | j                  }d|v r|j                  d      }t        j	                  | d| d| d|         | j
                  j                  || j                  |      g|| j                  | j                  d|}|r0|j                  dk\  r!| j                  |       |j                          |S )a  Make a request with an API key to Label Studio instance

        Parameters
        ----------
        method: str
            HTTP method like POST, PATCH, GET, DELETE.
        url: str
            URL of the API endpoint that you want to make a request to.

        args
            session.request(*args)
        kwargs
            session.request(*kwargs)

        Returns
        -------
        Response object for the relevant endpoint.

        timeoutr   z: z with args=z	, kwargs=)r1   r"   r   )r	   r,   poprm   rn   r.   requestrD   r1   r"   rk   log_response_errorrH   )r6   methodr    argsrr   r   rN   s          r   r<   zClient.make_request  s    ( F" 'F922'%zz*<=xr#k$yIJ'4<<''LL

 
 LLLL	
 
 ##s*''1))+r   c           	          	 t        j                  t        j                  |j                        d      }t
        j                  d|j                   d|j                   d| d       y #  |j                  }Y DxY w)N   )indentz;
--------------------------------------------
Request URL: z
Response status code: z
Response content:
z

SDK error traceback:)	r=   dumpsloadscontentr   rm   r   r    rk   )r6   rN   r   s      r   r   zClient.log_response_error  sw    	$jjH,<,<!=aHG 	$LL> *%%-%9%9$: ;"") +#$	
	$mmGs   4A* *A:c           	      f    | j                  dd| dt        |       d      }|j                         S )z&See project.sync_storage for more infor   z/api/storages/r%   z/sync)r<   r   r=   )r6   storage_type
storage_idrN   s       r   sync_storagezClient.sync_storage  s9    $$n\N!C
O3DEJ
 }}r   )	NNNNNNNNT)T)r   r   r   r   rF   r9   r3   r   r0   rO   rT   intrX   r`   rR   rs   rq   rw   r~   r   r   r   r   r-   rD   r<   r   r   r   r   r   r   r   &   s     "IPIP IP IP IPV	'8 &	2	 	2,0-"(+Z2&2*X
r   r   )__doc__r=   loggingr(   r   typingr   pydanticr   r   r   requests.adaptersr   	getLoggerr   rm   r   r   environrE   r	   r   r*   r   objectr   r   r   r   <module>r      s~      	   6 6 )			8	$RZZ^^Is34
5
2 	  qV qr   