
    ;3h5                       d dl m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
mZ d dlZd dlmZ d dlmZmZ d dlmZ ej(                  j+                  d      Zej(                  j+                  d      Zej(                  j+                  d	      Zej(                  j+                  d
      ZdZddZddZddZddZ	 d	 	 	 	 	 ddZe
 G d dej@                               Z!e
 G d d             Z"ddZ#y)    )annotationsN)	dataclassfield)RedirectResponse)	get_tokenwhoami)	get_spaceOAUTH_CLIENT_IDOAUTH_CLIENT_SECRETOAUTH_SCOPESOPENID_PROVIDER_URL   c                0   	 ddl m} t               t	        |        nt        |        t        xs ddz   }| j                  |t        j                  |j                               j                         dd       y # t        $ r}t        d      |d }~ww xY w)	Nr   )SessionMiddlewareCannot initialize OAuth to due a missing library. Please run `pip install gradio[oauth]` or add `gradio[oauth]` to your requirements.txt file in order to install the required dependencies. z-v4noneT)
secret_key	same_site
https_only)starlette.middleware.sessionsr   ImportErrorr	   _add_oauth_routes_add_mocked_oauth_routesr   add_middlewarehashlibsha256encode	hexdigest)appr   esession_secrets       L/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/oauth.pyattach_oauthr$      s    C {# %
 */R58N >>."7"7"9:DDF	  +  k
 	s   A; ;	BBBc                ^   	 ddl m ddlm} d}t
        t        |j                  d            t        t        |j                  d            t        t        |j                  d	            t        t        |j                  d
             |       j                  dt
        t        dt        it        dz          | j                  d      dfd       }| j                  d      dfd       }| j                  d      dd       }y# t        $ r}t	        d      |d}~ww xY w)zIAdd OAuth routes to the FastAPI app (login, callback handler and logout).r   )MismatchingStateError)OAuthr   NzOAuth is required but {} environment variable is not set. Make sure you've enabled OAuth in your Space by setting `hf_oauth: true` in the Space metadata.r
   r   r   r   huggingfacescopez!/.well-known/openid-configuration)name	client_idclient_secretclient_kwargsserver_metadata_url/login/huggingfacec                n   K   t        |       }j                  j                  | |       d{   S 7 w)z)Endpoint that redirects to HF OAuth page.N)_generate_redirect_urir(   authorize_redirect)requestredirect_urioauths     r#   oauth_loginz&_add_oauth_routes.<locals>.oauth_login^   s2      .g6&&99'<PPPPs   +535/login/callbackc                  K   	 
j                   j                  |        d{   }|| j                  d<   t'        |       S 7 # 	$ r- t        | j                  j	                               D ]/  }|j                  d      s| j                  j                  |       1 t        | j                  j                  dd            }| j                  j                  d      }d|dz   i}|r||d<   dt        j                  j                  |       }|t        kD  rQt        j                  j                  d      }|t!        d	      dd
|j#                  d      z   }t%        ||z         cY S t%        |      cY S w xY ww))Endpoint that handles the OAuth callback.N_state_huggingface_nb_redirectsr   _target_url   z/login/huggingface?
SPACE_HOSTzrGradio is not running in a Space (SPACE_HOST environment variable is not set). Cannot redirect to non-iframe view.https:///
oauth_info)r(   authorize_access_tokenlistsessionkeys
startswithpopintquery_paramsgeturllibparse	urlencodeMAX_REDIRECTSosenvironRuntimeErrorrstripr   _redirect_to_target)r3   rA   keynb_redirects
target_urlrI   	login_urihosthost_urlr&   r5   s            r#   oauth_redirect_callbackz2_add_oauth_routes.<locals>.oauth_redirect_callbacke   st    '	/$00GGPPJR )3%"7++U Q$ %	/ GOO0023 ->>"67OO'',-
 w3377KLL --11-@J 3B<RSCS1TL.8]+-fll.D.D\.R-STI
 m+zz~~l3<&?    &C(88'9(<== $I..K%	/sJ   E:A AA E:A =E7C%E7'E:)E74E:6E77E:/logoutc                X   K   | j                   j                  dd       t        |       S wz=Endpoint that logs out the user (e.g. delete cookie session).rA   NrD   rG   rS   r3   s    r#   oauth_logoutz'_add_oauth_routes.<locals>.oauth_logout   '      	L$/"7++   (*r3   fastapi.Requestr3   rd   returnr   )'authlib.integrations.base_client.errorsr&   %authlib.integrations.starlette_clientr'   r   r
   
ValueErrorformatr   r   r   registerrJ   )	r    r'   r!   msgr6   rZ   r`   r&   r5   s	          @@r#   r   r   9   s@   Q?	; 
 $5677"$9:;;N344"$9:;; GE	NN!)-/2UU   	WW!"Q #Q 	WW-,  -,^ 	WWY, ,q  k
 	s   D 	D,D''D,c                    t        j                  d       t               | j                  d      d	d       }| j                  d      d
fd       }| j                  d      d
d       }y)a  Add fake oauth routes if Gradio is run locally and OAuth is enabled.

    Clicking on a gr.LoginButton will have the same behavior as in a Space (i.e. gets redirected in a new tab) but
    instead of authenticating with HF, a mocked user profile is added to the session.
    zGradio does not support OAuth features outside of a Space environment. To help you debug your app locally, the login and logout buttons are mocked with your profile. To make it work, your machine must be logged in to Huggingface.r/   c                z   K   t        |       }t        dt        j                  j	                  d|i      z         S w)z.Fake endpoint that redirects to HF OAuth page.z/login/callback?r<   )r1   r   rK   rL   rM   )r3   r4   s     r#   r6   z-_add_mocked_oauth_routes.<locals>.oauth_login   s;      .g6!7!78U!VV
 	
s   9;r7   c                @   K   | j                   d<   t        |       S w)r9   rA   )rD   rS   )r3   mocked_oauth_infos    r#   rZ   z9_add_mocked_oauth_routes.<locals>.oauth_redirect_callback   s"      ):%"7++s   r[   c                X   K   | j                   j                  dd       t        |       S wr]   r^   r_   s    r#   r`   z._add_mocked_oauth_routes.<locals>.oauth_logout   ra   rb   Nrc   re   )warningswarn_get_mocked_oauth_inforJ   )r    r6   rZ   r`   rp   s       @r#   r   r      s{     MM	T
 /0 	WW!"
 #
 	WW,  ,
 	WWY, ,    c                L   d| j                   v r| j                   d   }n,dt        j                  j                  | j                         z   }| j	                  d      j                  |      }t        |      }|j                  j                  d      r|j                  dd      }|S )Nr<   z/?rZ   )r<   z	.hf.spacezhttp://r?   )
rI   rK   rL   rM   url_forinclude_query_paramsstrnetlocendswithreplace)r3   targetr4   redirect_uri_as_strs       r#   r1   r1      s    ,,,%%m4 ..w/C/CDD??#<=RR S L l+##K0199)ZPru   c                P    | j                   j                  d|      }t        |      S )Nr<   )rI   rJ   r   )r3   default_targetr}   s      r#   rS   rS      s'     !!%%m^DFF##ru   c                      e Zd ZU dZ ed      Zded<    ed      Zded<    ed      Zded<    ed      Z	ded<   dd	Z
y
)OAuthProfilea  
    A Gradio OAuthProfile object that can be used to inject the profile of a user in a
    function. If a function expects `OAuthProfile` or `Optional[OAuthProfile]` as input,
    the value will be injected from the FastAPI session if the user is logged in. If the
    user is not logged in and the function expects `OAuthProfile`, an error will be
    raised.

    Attributes:
        name (str): The name of the user (e.g. 'Abubakar Abid').
        username (str): The username of the user (e.g. 'abidlabs')
        profile (str): The profile URL of the user (e.g. 'https://huggingface.co/abidlabs').
        picture (str): The profile picture URL of the user.

    Example:
        import gradio as gr
        from typing import Optional


        def hello(profile: Optional[gr.OAuthProfile]) -> str:
            if profile is None:
                return "I don't know you."
            return f"Hello {profile.name}"


        with gr.Blocks() as demo:
            gr.LoginButton()
            gr.Markdown().attach_load_event(hello, None)
    F)initry   r*   usernameprofilepicturec                v    | j                  |       | d   | _        | d   | _        | d   | _        | d   | _        y )Nr*   preferred_usernamer   r   )updater*   r   r   r   )selfdatas     r#   __init__zOAuthProfile.__init__   s<    DL	12IIru   N)r   dict)__name__
__module____qualname____doc__r   r*   __annotations__r   r   r   r    ru   r#   r   r      sJ    : 5!D#!u%Hc%e$GS$e$GS$'ru   r   c                  0    e Zd ZU dZded<   ded<   ded<   y)
OAuthTokenak  
    A Gradio OAuthToken object that can be used to inject the access token of a user in a
    function. If a function expects `OAuthToken` or `Optional[OAuthToken]` as input,
    the value will be injected from the FastAPI session if the user is logged in. If the
    user is not logged in and the function expects `OAuthToken`, an error will be
    raised.

    Attributes:
        token (str): The access token of the user.
        scope (str): The scope of the access token.
        expires_at (int): The expiration timestamp of the access token.

    Example:
        import gradio as gr
        from typing import Optional
        from huggingface_hub import whoami


        def list_organizations(oauth_token: Optional[gr.OAuthToken]) -> str:
            if oauth_token is None:
                return "Please log in to list organizations."
            org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]]
            return f"You belong to {', '.join(org_names)}."


        with gr.Blocks() as demo:
            gr.LoginButton()
            gr.Markdown().attach_load_event(list_organizations, None)
    ry   tokenr)   rH   
expires_atN)r   r   r   r   r   r   ru   r#   r   r     s    < JJOru   r   c                     t               } | t        d      t               }|d   dk7  rt        d      | ddddt        t	        j                               d	z   d
|d   |d   d|d    |d   dddddddddS )Na  Your machine must be logged in to HF to debug a Gradio app locally. Please run `huggingface-cli login` or set `HF_TOKEN` as environment variable with one of your access token. You can generate a new token in your settings page (https://huggingface.co/settings/tokens).typeuserzYour machine is not logged in with a personal account. Please use a personal access token. You can generate a new token in your settings page (https://huggingface.co/settings/tokens).beareri  AAAAAAAAAAAAAAAAAAAAAAAAAAzopenid profileip  11111111111111111111111fullnamer*   zhttps://huggingface.co/	avatarUrlr   z$00000000-0000-0000-0000-000000000000idaaaaaaaaaaaaaaaaaaaidzhttps://huggingface.co)subr*   r   r   r   websiteaud	auth_timenonceiatexpiss)access_token
token_type
expires_inid_tokenr)   r   userinfo)r   ri   r   rH   time)r   r   s     r#   rt   rt   *  s    KE}F
 	
 8DF|v9
 	
 0!$))+&4,$"&v,0f?K(9#*+
 ru   )r    fastapi.FastAPI)r    r   rf   None)r3   rd   rf   ry   )r@   )r3   rd   r   ry   rf   r   )rf   ztyping.Dict)$
__future__r   r   rO   r   typingurllib.parserK   rr   dataclassesr   r   fastapifastapi.responsesr   huggingface_hubr   r   gradio.utilsr	   rP   rJ   r
   r   r   r   rN   r$   r   r   r1   rS   Dictr   r   rt   r   ru   r#   <module>r      s    "  	     (  . - "**..!23jjnn%:; zz~~n-jjnn%:; @`,F!,H& 58$$.1$$ ('6;; (' ('V ! ! !H'ru   