
    +jP                    \   d Z 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	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 ddlZddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ  ej         e!          Z"e#de$de%diZ&dNdZ'	 	 dOdPdZ(dQdZ) ej*        d          Z+dZ,d Z-dRd$Z. e            Z/dSd&Z0	 dTdUd)Z1	 dVdWd.Z2dXdYd3Z3dZd7Z4d[d9Z5d\d:Z6d]d=Z7d^d>Z8h d?Z9	 	 	 d_d`dBZ	 	 	 d_d`dCZ:dVd\dDZ;	 dTd`dEZ<	 dTd`dFZ=	 dTd`dGZ>	 dTd`dHZ?	 dTd`dIZ@	 dTd`dJZA	 dTd`dKZB G dL dMe          ZCdS )auG   gr.Workflow — high-level API for building and launching AI pipelines.    )annotationsN)Callable)Optional)HfApi)	get_token)Blocks)
OAuthToken)Request)	get_spacenumberboolean
edges_speclist[tuple[str, str]]nodes
list[dict]returnc           
         dfd}g }t          |           D ]G\  }\  }} ||d          \  }}}	 ||d          \  }
}}|                    d	| |||
||	d
           H|S )Nspecstr	ports_keyr   tuple[str, str, str]c                   |                      d          \  }                                                                pd t          fdD             d           }|t          d dd D                        ||         }|st          d d|           -|d         }|d	         |d	         |                    d
d          fS t          fd|D             d           }|-t          d|d d          d d dd |D                        |d	         |d	         |                    d
d          fS )N.c              3  N   K   | ]}|                     d           k    |V   dS )fnNget).0nfn_names     S/home/wildlama/visual-decline/.venv/lib/python3.11/site-packages/gradio/workflow.py	<genexpr>z0_build_edges.<locals>.resolve.<locals>.<genexpr>,   s7      @@1t)?)?Q)?)?)?)?@@    zedges: no function 'z' in bind dict. Available: c                    g | ]
}|d          S )r    )r   r   s     r!   
<listcomp>z1_build_edges.<locals>.resolve.<locals>.<listcomp>0   s    6661qw666r#   zedges: node 'z	' has no r   idtypetextc              3  L   K   | ]}|d          k    s|d         k    |V  dS )labelr'   Nr%   )r   p	port_hints     r!   r"   z0_build_edges.<locals>.resolve.<locals>.<genexpr><   s?      QQ17y!8!8AdGy<P<PQ<P<P<P<PQQr#   z
edges: no z port 'z' on 'z'. Available: c                    g | ]
}|d          S )r+   r%   )r   r,   s     r!   r&   z1_build_edges.<locals>.resolve.<locals>.<listcomp>B   s    999aqz999r#   )	partitionstripnext
ValueErrorr   )	r   r   _nodeportsportr    r-   r   s	         @@r!   resolvez_build_edges.<locals>.resolve'   s    $s 3 3I--//OO%%-	@@@@@@@$GG<9w 9 9666669 9  
 Y 	LJWJJyJJKKK8D:tDz488FF+C+CCCQQQQQQQ
 
 <<Yss^ < <I < <W < <995999< <   Dz4:txx'?'???r#   outputsinputsedge_)r'   from_node_idfrom_port_id
to_node_id
to_port_idr(   )r   r   r   r   r   r   )	enumerateappend)r   r   r8   resulti	from_specto_specr<   r=   	edge_typer>   r?   r4   s    `           r!   _build_edgesrG   #   s    @ @ @ @ @ @> F#,Z#8#8 
 
Iw07	90M0M-lI$+GGX$>$>!
J!akk , ,((! 		
 		
 		
 		
 Mr#   My Workflowbounddict[str, Callable]edgeslist[tuple[str, str]] | Nonenamer   c                   g }t          |                                           D ]\  }\  }}	 t          j        |          }n*# t          t
          f$ r t          j                    }Y nw xY wd |j                                        D             }ddt          	                    |j
        d          dg}	|sddddg}|                    d| d	|d
|d|dz  z   dddt          t          |          t          |	                    dz  z   ||	i d           t          |pg |          }
t          j        d|||
d          S )Nc                n    g | ]2\  }}|d k    d| |t                               |j        d          d3S selfin_r)   r'   r+   r(   _PY_TO_PORTr   
annotationr   r,   params      r!   r&   z'_workflow_from_bind.<locals>.<listcomp>c   sX     
 
 
 5F{{  Aii#(8&AA  {{r#   out_0outputr)   rS   in_0inputfn_r   	transformP   i        $   )r'   sourcer   kindr+   xywidthheightr:   r9   data1)versionrM   r   rK   )r@   itemsinspect	signaturer3   	TypeError	Signature
parametersrU   r   return_annotationrA   maxlenrG   jsondumps)rI   rK   rM   r   rC   r    r   sigr:   r9   
edge_dictss              r!   _workflow_from_bindry   W   s   
 E%ekkmm44 )
 )
=GR	&#B''CCI& 	& 	& 	&#%%CCC	&
 
  N0022
 
 
 !#(=vFF 
  	H#gvFFGF%Goo# !c'\s3v;;G==BB " 	
 	
 	
 	
" ekr511J:
KK  s   A$A)(A)
str | Nonec                 >    t                      dS t                      S )a  Return the local Hugging Face token when running outside Spaces.

    Avoid reading a Space's token/secret here: `get_token` is exposed to the
    browser so the workflow canvas can authenticate local apps with the user's
    `huggingface_hub login` token.
    N)r   hf_get_tokenr%   r#   r!   _get_locally_saved_hf_tokenr}      s     {{t>>r#       gradio_workflow_write_tokenzx-gradio-workflow-write-tokenrequestRequest | Noneboolc                   | dS 	 d t          | j        pi                                           D             }n# t          $ r Y dS w xY w|                    t
                    }|rt          j        |t                    S |                    dd          	                    d          D ]}|
                                                    d          \  }}}|                    t                    r<|r:t          j        t          j                            |          t                    r dS 	 | j                            d	          }n# t          $ r d}Y nw xY w|rt          j        |t                    S dS )
uV  True when the request carries the per-process write token, checked in
    header → cookie → query-param order (mirrors trackio's scheme). The cookie
    name is prefix-matched because the frontend suffixes it with the port —
    cookies are shared across ports on the same host, so two local apps would
    otherwise clobber each other.NFc                >    i | ]\  }}|                                 |S r%   )lower)r   kvs      r!   
<dictcomp>z,_request_has_write_token.<locals>.<dictcomp>   s&    PPPDAq17799aPPPr#   cookie ;=Twrite_token)dictheadersrl   	Exceptionr   _WRITE_TOKEN_HEADERsecretscompare_digestWRITE_TOKENsplitr1   r0   
startswith_WRITE_TOKEN_COOKIE_PREFIXurllibparseunquotequery_params)r   r   header_valuer   rM   r4   valuequery_values           r!   _request_has_write_tokenr      s    uPPD1FB,G,G,M,M,O,OPPP   uu;;233L A%lK@@@++h++11#66  11#66aOO677		 &v|';';E'B'BKPP	
 44*..}==    @%k;???5s!   29 
AA.E	 	EEoauth_tokenc                |   t                      }|r| sdS 	 t                              | d          }n# t          $ r Y dS w xY wt	          j        d          p|                    d          d         |                    d          k    rdS t          fd|                    d	g           D                       S )
zOn Spaces, write access belongs to the Space owner: the OAuth user must
    be the owning user, or an admin/write member of the owning org.FT)tokencacheSPACE_AUTHOR_NAME/r   rM   c              3  x   K   | ]4}|                     d           k    o|                     d          dv V  5dS )rM   	roleInOrg)adminwriteNr   )r   orgowners     r!   r"   z6_oauth_token_has_space_write_access.<locals>.<genexpr>   s]         	5 OSWW[%9%9=O%O     r#   orgs)	r   _hf_apiwhoamir   osgetenvr   r   any)r   space_idwhor   s      @r!   #_oauth_token_has_space_write_accessr      s     {{H ; unn;dn;;   uuI)**DhnnS.A.A!.DE
wwv%t    7762&&     s   4 
AAr   OAuthToken | Nonec                l    t                      t          |r|j        nd          S t          |           S )zWhether this request may modify the workflow (and, locally, use the
    host's saved HF token). Locally: requires the launch-time write token.
    On Spaces: requires the OAuth user to own the Space (or have org write).N)r   r   r   r   )r   r   s     r!   has_write_accessr      s5     {{2%3Q5;;TRRR#G,,,r#   ri   listidxintc                    t          |           |k    r| |         nd }|r|S |r|j        S t          |          rt                      S d S N)rt   r   r   r}   )ri   r   r   r   manuals        r!   _resolve_tokenr      s]     d))c//T#YYtF  {(( -*,,,4r#      urlhf_tokentimeoutc                |    |rdd| ini }t          j        | ||          }|                                 |j        S )NAuthorizationBearer )r   r   )httpxr   raise_for_statusr)   )r   r   r   r   resps        r!   _hf_requestr      sO    9AI 4( 4 455rG9S'7;;;D9r#   sr   pipeline_tagc                   |p|                      d          }|                      d          |                      dd          |                      dd          |                      d          ||                      d          |                      d          p|                      d	          |                      d
g           |                      d          ddS )Nai_categoryr'   likesr   trendingScoreruntimetitleshortDescriptionai_short_descriptiontagssdk)r   short_descriptionr   r   )r'   r   r   r   r   cardDatar   )r   r   effective_tags      r!   _normalize_space_resultr      s     8AEE-$8$8MeeDkkw""2255##%UU7^^())JQUU3I-J-JEE&"%%55<<
 
  r#   extc                   t           j                            t          j                    dt          j        d                                           d|           }t          | d          r|                     |           n=t          |d          5 }|
                    |            d d d            n# 1 swxY w Y   |d| ddS )	Nhf_workflow_   r   savewb/gradio_api/file=Tpathr   is_file)r   r   jointempfile
gettempdirurandomhexhasattrr   openr   )rB   r   r   fs       r!   	_save_tmpr     s    7<<Ibjmm.?.?.A.AIICII D vv D$ 	GGFOOO	 	 	 	 	 	 	 	 	 	 	 	 	 	 	!;T!;!;MMMs   B44B8;B8c                    t          | t                    r+|                     d          p|                     dd          n| S )Nr   r   r   )
isinstancer   r   )as    r!   _img_urlr     s7    0:1d0C0CJ155<<,155,,Jr#   er   c                   d }t          | dd           }|t          |dd           }|t          | dd           }|dv rdddS |dk    rdd	dS |d
k    rddiS t          |           j        }|dv rdd	dS |dk    rdddS t          | dd           pd}t          | dd           pt          |           }| d|                                 }d|v sd|v rd|v rddiS d|v sd|v sd|v rddiS d|v sd|v rdddS d|v sd|v sd|v sd|v sd|v rdddS d |v sd!|v rdd	dS d"|v sd#|v rd"d$dS d%|v sd&|v sd'|v rd'd(dS d)ddS )*Nresponsestatus_code)i  i  authz.Sign in with your HF account to use this model)
error_type
suggestioni  	not_foundu7   Space not found — it may have been deleted or renamedi  r   quota)RepositoryNotFoundErrorEntryNotFoundErrorRevisionNotFoundErrorGatedRepoErrorr   r   message zerogpugpuworkerz
rate limit
rate_limitsleepingpausedu5   Space is sleeping or paused — try again in a minuteunauthorizedauthenticationzlog inapi_keyzapi keyz	not foundzrepository not foundbuild_errorzbuild erroru3   Space has a build error — contact the Space ownerz	timed outr   
connectionu1   Could not connect to the Space — it may be downunknown)getattrr(   __name__r   r   )r   http_statusr   	type_namer   r   fulls          r!   _classify_errorr    s   "Kq*d++Hht<<a55j   J
 
 	
 c%S
 
 	
 cg&&Q I    &S
 
 	
 $$$ J
 
 	

 Aw%%+EaD))3SVVGg%%''DDUd]]x4/?/?e$$$,$..,$2F2Fg&&TX--$Q
 
 	

 	$t##t !J
 
 	
 d4<<%S
 
 	
  5 5'O
 
 	
 di4//<43G3G&M
 
 	
 $2666r#   c                    t          | dd           }t          | dd           pt          |           }t          |           }|                    d          dk    rd}d }d|i|}|r||d<   t	          j        |          S )Nr   r   r   r   zAuthentication requirederror)r  r   r  r   ru   rv   )r   r   r   
classifiederrs        r!   _format_errorr  n  s    Aw%%EaD))3SVVG ##J~~l##v--+G
*z
*C G:c??r#   >&   game-ai	visual-qa3d-modelingimage-editingtext-analysisvoice-cloningstyle-transfercode-generationimage-upscalingmedical-imagingpose-estimationdataset-creationface-recognitionimage-captioningimage-generationmusic-generationspeech-synthesisvideo-generationagent-environmentanomaly-detectiondocument-analysisfine-tuning-toolsbackground-removaldata-visualizationfinancial-analysismodel-benchmarkingsentiment-analysistext-summarizationcharacter-animationlanguage-translationrecommendation-systemsocrimageotherchatbotstext-generationobject-detectionquestion-answeringOptional[Request]Optional[OAuthToken]c                V    |r|j         S t          |          rt                      pdS dS )u   Return the HF token for this browser session. The host's locally saved
    token is only revealed to sessions holding the write token — share-link
    visitors and other remote clients get "" (logged-out experience).r   )r   r   r}   _datar   r   s      r!   r   r     s:      {(( 3*,,222r#   c                *    t          ||          rdndS )Ntruefalse)r   r@  s      r!   get_write_accessrE    s    
 &gu55B667Br#   c                h    t                      #t          t          j        d                    rdndS )a  Whether OAuth sign-in is actually wired up. On a Space this requires
    `hf_oauth: true` in the README metadata, which provisions OAUTH_CLIENT_ID
    and causes the `/login/huggingface` route to be mounted (mirrors the gate
    that adds the LoginButton in `__init__`). Without it, sign-in would 404, so
    the frontend hides the login button and explains the fix on the read-only
    badge. OAuth is not used locally (the write-token model is used instead).NOAUTH_CLIENT_IDrC  rD  )r   r   r   r   )rA  s    r!   get_oauth_availablerH    s5     ;;"tBI6G,H,H'I'I" 	r#   c                h   | r| d         nd}	 ddl m}m} t          |           dk    r| d         nd }t          |           dk    r| d         nd}t	          | d||          }t          j        d|pd          st          j        d	d
dd          S  |||          }	t          j	        |          }
|r|dk    rt|	
                    d          }t          t          |t                    r|                    di           ni                                           }||v r|n|r|d         nd}g }|
D ]}t          |t                    rVd|v sd|v rN|                    d          p|                    dd          }|                    |r ||          nd            m|                    |           |r&|d         |                                 |r|d          |	j        |d|i}t          |t          t&          f          rt          |          n|g}t(          j                            t/          j                              fdt          j        fd|D                       S # t2          $ r7}t4                              d||d           t9          |          cY d }~S d }~ww xY w)Nr   r   )Clienthandle_file      []   z[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+zInvalid Space IDr   z%Space ID must be in owner/repo formatr  r   r   )r   z/predictr   )return_formatnamed_endpointsr   r   r.   api_namec                   t          | t                    r|                     d          p|                     d          }t          |t                    rZt          j                            |                                        r(t          j                            |          r	|d| ddS | S t          | t                    rZt          j                            |                                         r(t          j                            |           r	| d|  ddS t          | t          t          f          rfd| D             S | S )Nr   r   r   Tr   c                &    g | ]} |          S r%   r%   )r   r   process_items     r!   r&   z4call_space.<locals>.process_item.<locals>.<listcomp>  s!    666AQ666r#   )r   r   r   r   r   r   realpathr   existsr   tuple)itemr   _tmpdirrV  s     r!   rV  z call_space.<locals>.process_item  sY   $%% xx''<488G+<+<tS))	((..99'BB	 t,,	 !%9499#'  
 4%%	G$$T**55g>>	 GNN4((	 !5t55#  
 $u.. 766666666Kr#   c                &    g | ]} |          S r%   r%   )r   rC   rV  s     r!   r&   zcall_space.<locals>.<listcomp>  s!    ;;;q<<??;;;r#   zcall_space failed for %s: %sTexc_info)gradio_clientrJ  rK  rt   r   re	fullmatchru   rv   loadsview_apir   r   r   r   keysrA   poppredictrY  r   r   rW  r   r   r   loggerr  r  )ri   r   r   r   rJ  rK  endpoint	args_jsonr   clientargsapi_infonamed	processedargr   rB   r   r[  rV  s                     @@r!   
call_spacerp    s2    &tAwwBHI 55555555!$ii!mm477"4yy1}}DGG$	!$5'::|>BOO 	:/"-"I    111z)$$ 	8z11V<<H "(D11HLL!2B777$&& E %--4UE!HH:  	 	& 	&C#t$$ &%3,,&C--ggenn;(;(;  S!BS!1!1!1dCCCC  %%%% 	IbM1MMOOO  	IbM1>X>>!+FT5M!B!BPf'""8#6#8#899	 	 	 	 	 	8 z;;;;F;;;<<<      3Xq4PPPQ s%   BI0 GI0 0
J1:,J,&J1,J1c           	        | r| d         nd}d}	 ddl m} t          |           dk    r| d         nd }t          |           dk    r| d         nd}t          | d||          }t          |           dk    r| d         r| d         nd	}	 ||||	
          }
t	          j        |          }|pd}|r|d         nd}t          |          dk    r|d         nd}|dv r	 |
                    |d          }nt# t          $ rg}t          |          	                                }d|v r7d|v r3|

                    d|dgd          }|j        d         j        j        }n Y d }~nd }~ww xY wt	          j        |g          S |dk    r-t	          j        |
                    |          j        g          S |dk    r-t	          j        |
                    |          j        g          S |dv r2t	          j        d |
                    |          D             g          S |dk    r2t	          j        d |
                    |          D             g          S |dk    r2t	          j        d |
                    |          D             g          S |dk    rU|
                    ||          }t/          |t0                    r|d         j        n|j        }t	          j        |g          S |dk    rN|
                    |          }t	          j        t7          |d          r|                                n|g          S |d k    r@t	          j        |
                    ||r|                    d!          ng           g          S |d"k    r6t	          j        t?          |
                     |          d#          g          S |d$v r6t	          j        t?          |
!                    |          d%          g          S |d&k    r6t	          j        t?          |
"                    |          d'          g          S |d(k    r?t	          j        d) |
#                    tI          |                    D             g          S |d*k    r?t	          j        d+ |
%                    tI          |                    D             g          S |d,k    r?t	          j        d- |
&                    tI          |                    D             g          S |d.k    r[|
'                    tI          |                    }t	          j        t7          |d/          r|j(        nt          |          g          S |d0k    rEt	          j        t?          |
)                    tI          |          |1          d#          g          S |d2k    r[|
*                    tI          |                    }t	          j        t7          |d3          r|j+        nt          |          g          S |d4k    r?t	          j        d5 |
,                    tI          |                    D             g          S |d6v rG|
-                    tI          |          |          }t	          j        |r|d         j        ndg          S |d7k    r|rd8d9| ini }t]          j/        d:| |d;tI          |          id<=          }|0                                 dd l1}dd>l2m3} |4                    |5                    |j                            }t	          j        t?          |d#          g          S 	 |

                    d|dgd          }t	          j        |j        d         j        j        g          S # t          $ r Y nw xY w|rd8d9| ini }t]          j/        d:| |d;|s|n||gid<=          }|0                                 	 |                                }n# t          $ r
 |j+        }Y nw xY wt	          j        |g          S # t          $ r8}tl          7                    d?|||d@A           tq          |          cY d }~S d }~ww xY w)BNr   r   )InferenceClientrL  rM  rN  rO     auto)modelr   providerr:  )r:  ztext2text-generationconversationali   )max_new_tokensznot supportedrw  user)rolecontent)
max_tokenssummarizationtranslation)ztext-classificationzzero-shot-classificationc                ,    g | ]}|j         |j        d S r+   scorer  r   rs     r!   r&   zcall_model.<locals>.<listcomp>F  4        #$'AG<<  r#   ztoken-classificationc                8    g | ]}|j         |j        |j        d S )entity_groupwordr  r  r  s     r!   r&   zcall_model.<locals>.<listcomp>O  s@        	 -.N$%F%&W   r#   z	fill-maskc                8    g | ]}|j         |j        |j        d S )	token_strr  sequencer  r  s     r!   r&   zcall_model.<locals>.<listcomp>\  s@        	 *+%&W()
   r#   r<  )questioncontextzfeature-extractiontolistzsentence-similarity
ztext-to-imagepng)ztext-to-speechztext-to-audiowavztext-to-videomp4zimage-classificationc                ,    g | ]}|j         |j        d S r  r  r  s     r!   r&   zcall_model.<locals>.<listcomp>|  r  r#   r;  c                8    g | ]}|j         |j        |j        d S )r+   r  boxr  r  s     r!   r&   zcall_model.<locals>.<listcomp>  s8        #$'AGAEJJ  r#   zimage-segmentationc                ,    g | ]}|j         |j        d S r  r  r  s     r!   r&   zcall_model.<locals>.<listcomp>  r  r#   zimage-to-textgenerated_textzimage-to-image)promptzautomatic-speech-recognitionr)   zaudio-classificationc                ,    g | ]}|j         |j        d S r  r  r  s     r!   r&   zcall_model.<locals>.<listcomp>  r  r#   )zvisual-question-answeringzdocument-question-answeringzimage-text-to-textzdepth-estimationr   r   z,https://api-inference.huggingface.co/models/r:   <   )r   ru   r   )Imagez&call_model failed for %s (task=%s): %sTr]  )9huggingface_hubrr  rt   r   ru   rb  text_generationr   r   r   chat_completionchoicesr   r{  rv   r}  summary_textr~  translation_texttext_classificationtoken_classification	fill_maskquestion_answeringr   r   answerfeature_extractionr   r  sentence_similarityr   r   text_to_imagetext_to_speechtext_to_videoimage_classificationr   object_detectionimage_segmentationimage_to_textr  image_to_imageautomatic_speech_recognitionr)   audio_classificationvisual_question_answeringr   postr   ioPILr  r   BytesIOrg  r  r  )ri   r   r   model_idtaskrr  r   ri  r   rv  rj  rk  a0a1rB   innermsgr  	qa_result	qa_answerr   r   _io_Image	depth_imgfallback_respparsedr   s                               r!   
call_modelr    s	    &tAwwBHD 333333"%d))a--tAwwT"4yy1}}DGG$	!$5':: "$ii!mmQm477V xx(SSSz)$$00$T!WW"D		AT!WW2 
 
 


//3/GG   %jj&&(("c)).>#.E.E.."(R889c /  A Yq\19FF FFFF :vh'''?"":v33B77DEFFF=  :v11"55FGHHHFFF: !'!;!;B!?!?     ))):  "(!<!<R!@!@  	   ;:  "(!1!1"!5!5  	   '''112r1JJI'1)T'B'BX	!##	HX  :yk***'''))"--A:WQ-A-AHqxxzzzqIJJJ(((:++B"0L"MMN   ?"":y)=)=b)A)A5IIJKKK666:y)>)>r)B)BEJJKLLL?"":y)=)=b)A)A5IIJKKK))): !'!<!<Xb\\!J!J     %%%: !'!8!8"!F!F     ''': !'!:!:8B<<!H!H     ?""$$Xb\\22A:%,Q0@%A%AM!!s1vvN   ###:600"b0II5QQR   11133HRLLAAA:F););GqvvQHIII))): !'!<!<Xb\\!J!J      
 
 

 00"rBBA:a7qt{{R8999%%%AIQ(<((<(<==rG:IxII-	  D !!###++++++CKK$=$=>>I:yE::;<<<	&& R001c '  A :qy|3;<=== 	 	 	D	=EM?$8h$8$8992
E8EEb6BBr2h7	
 
 
 	&&(((	("''))FF 	( 	( 	("'FFF	(z6(###      4 	 	
 	
 	
 Q s  C
` C3 2` 3
E$=AE` E$$` <2` /2` "5` 7` 7` A` #A` 7A` =;` 99` 3;` /A` 4A` 9A` >A ` A
` *A ` A` A
` B(` A^
 

^` ^A` _2 1` 2`` `` 
a (-aa a c           
        	 | d         }t          |           dk    r| d         r| d         nd}t          |           dk    r| d         r| d         nd}t          |           dk    r| d         rt          | d                   nd}t          |           dk    r| d         rt          | d                   nd}t          | d	||          }t          j                            ||||t          |d
          d          }	t          j        t          d|	 |d                    }
t          j
        |
                    dg           d |
                    dg           D             |
                    dd          d          S # t          $ rW}t                              d| r| d         nd|d           t          j
        t          |          ddd          cY d }~S d }~ww xY w)Nr   rL  defaultrM  trainrO  rs  
      d   )datasetconfigr   offsetlengthz,https://datasets-server.huggingface.co/rows?   r   featuresc                :    g | ]}|                     d i           S )rowr   r  s     r!   r&   z!fetch_dataset.<locals>.<listcomp>  s&    JJJaub))JJJr#   rowsnum_rows_total)r  r  r  zfetch_dataset failed for %s: %sr   Tr]  r  rP  )rt   r   r   r   r   	urlencodeminru   rb  r   rv   r   r   rg  r  r   )ri   r   r   
dataset_idr  r   r  r  r   paramsrB   r   s               r!   fetch_datasetr    s   %X!W
IIMMd1gMa9t99q==T!W=Q'!$TQ47T!W!$TQ47T!W!$5'::''%  fc** 
 
 GvGG  
 
 z"JJz266JJ6::fb3I3IJJJ"(**-=q"A"A 
 
 	
  X X X-#DGG	 	 	
 	
 	
 zCFF)SUVVWWWWWWWWXs   E?F 
G#AGG#G#c                   | r| d         nd}	 t          |           dk    r| d         r| d         nd}t          |           dk    r| d         r| d         ndrt          vrdt          | d||          t          |           dk    rt          | d                   ndd+dd,fd}s|rddg}r6|                    dt
          j                                                  n7|r5|                    dt
          j                            |                      dd                    |          z   }t          |          }t          j        |          }	t          |	t                    s|S |dk    rS|rQt          |	          dk     r> ||          D ]2t          fd|	D                       s|	                               3rfd|	D             }	|dk    r|	                    d d           n|dk    r|	                    d  d           t          j        fd!|	d d"         D                       S d#}
rd$nd}|dk    r	d%| d&|
 }nd%| d'|
 }t          |          S # t"          $ rK}t$                              d(||d)           t          j        d*t)          |          i          cY d }~S d }~ww xY w)-Nr   trendingrL  r   rM  rO  rs  Fr   r   r   r   c                    |                      d          pg }d|v sd|v rdS |                      d          pi                      d          pd}dt          |                                          v S )	Nr   zzero-gpur   Tr   hardwarer   zero)r   r   r   )r   r   hws      r!   _has_zero_gpuz$search_spaces.<locals>._has_zero_gpu  sr    55==&BDT!!Y$%6%6t%%	""(b--j99?RBSWW]]__,,r#   qr   r   c                    | sg S dt           j                            |            d}r|dz  }	 t          j        t          |                    S # t          $ r g cY S w xY w)Nz7https://huggingface.co/api/spaces?filter=gradio&search=z;&limit=24&expand[]=likes&expand[]=cardData&expand[]=runtime&filter=zero-gpu)r   r   quoteru   rb  r   r   )r  fb_urlr   zero_gpu_onlys     r!   _fallback_searchz'search_spaces.<locals>._fallback_search$  s     	F!<--a00F F F   -,,z+fh"?"?@@@   			s   !A A"!A"z
sdk=gradiozincludeNonRunning=falsez	category=zq=z2https://huggingface.co/api/spaces/semantic-search?&search   c              3  p   K   | ]0}|                     d                                d           k    V  1dS )r'   Nr   )r   r,   fbs     r!   r"   z search_spaces.<locals>.<genexpr>Q  s<      KKqquuT{{bffTll:KKKKKKr#   c                *    g | ]} |          |S r%   r%   )r   r   r  s     r!   r&   z!search_spaces.<locals>.<listcomp>W  s(    @@@}}Q/?/?@!@@@r#   newc                0    |                      d          pdS )N	createdAtr   r   r   s    r!   <lambda>zsearch_spaces.<locals>.<lambda>[  s    !%%"4"4": r#   T)keyreversec                0    |                      d          pdS )Nr   r   r   r  s    r!   r  zsearch_spaces.<locals>.<lambda>`  s    !%%"8"8"=A r#   c                0    g | ]}t          |          S r%   )r   )r   r   r   s     r!   r&   z!search_spaces.<locals>.<listcomp>d  s$    OOOa(L99OOOr#   0   z2&expand[]=likes&expand[]=cardData&expand[]=runtimer  z/https://huggingface.co/api/spaces?filter=gradioz%&limit=24&sort=createdAt&direction=-1z)&limit=48&sort=trendingScore&direction=-1z"search_spaces failed (kind=%s): %sr]  r  )r   r   r   r   )r  r   r   r   )rt   VALID_SPACE_CATEGORIESr   r   rA   r   r   r  r   r   ru   rb  r   r   r   sortrv   r   rg  r  r   )ri   r   r   rd   queryr  r  r   rawr  base_expandzero_filterr   r  r  r   r   r  s                @@@@@r!   search_spacesr    s    *477
Di-t99q==T!W=Q""%d))a--DG-tAww  	L0FFFL!$5'::),TQT!WE	- 	- 	- 	-	 	 	 	 	 	 	2  (	5 (	"$=>F @L&,*<*<\*J*JLLMMMM
  @>6<#5#5e#<#<>>???FJ J C c8,,CZ__Ffd++ 
xEc&kkAoo**511 * *BKKKKFKKKKK *b)))  A@@@@V@@@u}}::       !!==      :OOOO6#2#;OOO  
 K,9A((r5==FF F8CF F CJJ J<GJ J 
 3))) - - -94TRRRz7CFF+,,,,,,,,-s,   E(I9 <CI9 
.I9 9
KA K	K	Kc                t   | r| d         nd}	 t          |           dk    r| d         r| d         nd}t          |           dk    r| d         r| d         nd}t          | d||          }|dk    rd}n|d	k    rd
}nd}d| d}|r%|dt          j                            |           z  }|r%|dt          j                            |           z  }t          ||          S # t          $ rK}	t                              d||	d           t          j
        dt          |	          i          cY d }	~	S d }	~	ww xY w)Nr   r  rL  r   rM  rO  r  zlikes&direction=-1r  zcreatedAt&direction=-1ztrendingScore&direction=-1z'https://huggingface.co/api/models?sort=zc&limit=60&expand[]=likes&expand[]=downloads&expand[]=pipeline_tag&expand[]=inferenceProviderMappingz&search=z&pipeline_tag=z"search_models failed (kind=%s): %sTr]  r  )rt   r   r   r   r  r   r   rg  r  ru   rv   r   )
ri   r   r   rd   r  r   r   r  r   r   s
             r!   search_modelsr  |  s    *477
D-t99q==T!W=Q""%d))a--DG-tAww!$5'::8'DDU]]+DD/D2d 2 2 2 	
  	:9fl0077999C 	GFFL$6$6|$D$DFFFC3))) - - -94TRRRz7CFF+,,,,,,,,-s   CC" "
D7,A D2,D72D7c                j   | r| d         nd}	 t          | d||          }|r#dt          j                            |           dnd}d| d}t	          ||          S # t
          $ rK}t                              d||d	
           t          j	        dt          |          i          cY d }~S d }~ww xY w)Nr   r   rL  zsearch=r  z$https://huggingface.co/api/datasets?z sort=likes&direction=-1&limit=20z%search_datasets failed (query=%s): %sTr]  r  )r   r   r   r  r   r   rg  r  ru   rv   r   )ri   r   r   r  r   search_paramr   r   s           r!   search_datasetsr    s     #DGGE-!$5'::AFN=!3!3E!:!:====Bc\ccc3))) - - -<eQQUVVVz7CFF+,,,,,,,,-s   AA 
B2'A B-'B2-B2c                   | r| d         nd}	 t          | d||          }	 t          j        t          dt          j                            |           |d                    }n"# t          $ r}t          d          |d }~ww xY w|                    dg           }|st          d	          t          d
 |D             |d                   }	 t          j        t          dt          j        
                    ||d         |d         d          z   |d                    }	n"# t          $ r}t          d          |d }~ww xY wt          j        |d         |d         |	                    dg           d          S # t          $ rK}
t                              d||
d           t          j        dt          |
          i          cY d }
~
S d }
~
ww xY w)Nr   r   rL  z6https://datasets-server.huggingface.co/splits?dataset=r  r  u:   Could not load dataset — it may not be viewer-compatiblesplitsz*No available splits found for this datasetc              3  2   K   | ]}|d          dk    |V  dS )r   r  Nr%   )r   r   s     r!   r"   z%get_dataset_schema.<locals>.<genexpr>  s0      BBQAgJ',A,Aq,A,A,A,ABBr#   z2https://datasets-server.huggingface.co/first-rows?r  r   )r  r  r   r  )r  r   r  z$get_dataset_schema failed for %s: %sTr]  r  )r   ru   rb  r   r   r   r  r   r   r2   r  rv   rg  r  r   )ri   r   r   r  r   splits_dataexcr
  picked	rows_datar   s              r!   get_dataset_schemar    sW    !(abJ0-!$5'::	*mV\M_M_`jMkMkmm   KK  	 	 	L 	 2.. 	JHIIIBB&BBBF1INN	
Hl,,'1&,X&6%+G_      II  	 	 	L 	 z *%MM*b99 
 
 	
  - - -2JD 	 	
 	
 	
 z7CFF+,,,,,,,,	-sh   E? AA& %E? &
B0B  BA
E? AD% $E? %
E/D??E:E? ?
G	A G	GGc                  @     e Zd ZdZ	 ddddd fd
Zd Z fdZ xZS )Workflowa  
    Build and launch a visual AI workflow as a Gradio app.

    Reads a workflow topology from a JSON file and optionally binds Python functions
    that can be used as nodes in the workflow.

    Example:
        ```python
        from gradio import Workflow

        def summarize(text: str) -> str:
            return text[:200]

        Workflow(graph="workflow.json", bind={"summarize": summarize}).launch()
        ```

    The graph file defines nodes and edges:
        ```json
        {
          "nodes": [
            {"id": "sum", "kind": "transform", "source": "fn", "fn": "summarize", ...},
            {"id": "img", "kind": "transform", "source": "space", "space_id": "black-forest-labs/FLUX.1-schnell", ...}
          ],
          "edges": [
            {"id": "e1", "from_node_id": "sum", "from_port_id": "out_0", "to_node_id": "img", "to_port_id": "in_0", "type": "text"}
          ]
        }
        ```
    N)bindrK   graphrz   r  +dict[str, Callable] | list[Callable] | NonerK   rL   c                  |zt          j        d          j        j        }t          j                            t          j                            |                    }t          j                            |d          }t          |t                    rd |D             }|| _        t          j                            t          j                            |                    d                             dd                              dd                                          | _        |pi | _        |pg | _        t'          j        d	t*                     t-                                          d
           |                                  dS )uw  
        Parameters:
            graph: Path to the workflow JSON file describing the canvas graph
                (nodes + edges). Defaults to `workflow.json` in the same
                directory as the calling script. The file is created on first
                save if it doesn't exist.
            bind: Functions callable from the canvas frontend via the `call_fn` server
                function. Pass a list of callables (keys default to ``fn.__name__``) or
                a dict mapping explicit names to callables.
            edges: List of ``(from_endpoint, to_endpoint)`` tuples that wire nodes
                together when generating a workflow from ``bind`` (ignored when an
                existing ``graph`` file is loaded). Each endpoint is either
                ``"fn_name"`` (uses the first available port) or
                ``"fn_name.port_label"`` to target a specific port.

                Example::

                    edges=[
                        ("shout", "reverse"),         # first output → first input
                        ("clean.output", "tag.text"), # by port label
                    ]
        NrL  zworkflow.jsonc           	     L    i | ]!}t          |d t          |                    |"S )r  )r  repr)r   r   s     r!   r   z%Workflow.__init__.<locals>.<dictcomp>!  s,    IIIbGB
DHH55rIIIr#   r   r4   r   -zOgr.Workflow is currently in beta. Its API and UX may change in future releases.workflow)mode)sys	_getframef_codeco_filenamer   r   dirnameabspathr   r   r   _workflow_filesplitextbasenamereplacer   _workflow_name_bound_edgeswarningswarnUserWarningsuper__init___build)rQ   r  r  rK   caller_filename
caller_dir	__class__s         r!   r-  zWorkflow.__init__  s:   : =!mA..5AO)I)IJJJGLL_==EdD!! 	JIIDIIID#GRW--e4455a8WS#WS#UWW	 	 ,0:2-2[b]	
 	
 	

 	j)))r#   c                V   	
 dd l }ddlm}  j        rDt          j                             j                  r t          	                    d j                   d fd} j
        	dd	fd
} j        
ddd	fd}	 	 dd
fd}t          t          t          t          t          t           t"          t$          t&          t(          |||g} 5  t+                      *t	          j        d          r|                    d            |||           d d d            d S # 1 swxY w Y   d S )Nr   )WorkflowCanvasztWorkflow: edges= is ignored because '%s' already exists. Delete the file to regenerate the workflow from bind/edges.r   rz   c                    	 t          j        d          5 } |                                 cd d d            S # 1 swxY w Y   d S # t          $ r. j        r#t          j        j        j                  cY S Y d S w xY w)Nutf-8encoding)rM   )r   r"  readFileNotFoundErrorr'  ry   r(  r&  )r   rQ   s    r!   _load_initialz&Workflow._build.<locals>._load_initialB  s    $-@@@ $A6688$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $$   ; .T[t7J      tts.   A :A >A >A 2A?>A?_tokenr>  r   c                X   | r| d         nd}	 t          |           dk    r| d         nd}                    |          }|t          j        d| dddd	          S t          j        |          }t          |t                    s|g} || }t          |t          t          f          rt          |          n|g}t          j        |          S # t          $ rM}t          
                    d
||d           t          j        t          |          ddd	          cY d }~S d }~ww xY w)Nr   r   rL  rN  zNo function 'z' bound to this workflowr  z&Check the bind= argument to Workflow()rP  zcall_fn failed for %s: %sTr]  )rt   r   ru   rv   rb  r   r   rY  r   rg  r  r   )	ri   r;  r    ri  r   rk  rB   r   rI   s	           r!   call_fnz Workflow._build.<locals>.call_fnO  sb   !%-d1gg2G'*4yy1}}DGG$	YYw''::%VW%V%V%V*3*R    z),,!$-- " 6DT)3FT5M)J)JXfQWPXz&)))   8'1tTTTz!!ffIRPP       s&   AC A2C 
D)AD$D)$D)i  P c                   g }                                 D ]\  }}	 t          j        |          }n*# t          t          f$ r t          j                    }Y nw xY wd |j                                         D             }|sddddg}ddt                              |j	        d          dg}|
                    ||||d           t          j        |          S )	a$  Return the bound functions' signatures so the canvas can offer
            them as add-able nodes via a dedicated bottom-bar button. The
            output port shape mirrors `_workflow_from_bind` so re-adding a
            previously-deleted node produces an identical template.
            c                n    g | ]2\  }}|d k    d| |t                               |j        d          d3S rP   rT   rW   s      r!   r&   z;Workflow._build.<locals>.list_bound_fns.<locals>.<listcomp>x  sX        !5F{{ (Aii!" +0@& I I  #{{r#   r[   r\   r)   rS   rY   rZ   )r   r+   r:   r9   )rl   rm   rn   r3   ro   rp   rq   rU   r   rr   rA   ru   rv   )	rA  r;  	templatesr    r   rw   r:   r9   rI   s	           r!   list_bound_fnsz'Workflow._build.<locals>.list_bound_fnsl  s-    I${{}}  .!+B//CC"I. . . .!+--CCC.  %(N$8$8$:$:    P%+gvNNOF &!) +0Ev N N    %!("(#*	     :i(((s   3$AAr   r=  r   c                   t          ||          st          j        dddd          S 	 t          | t                    r
| r| d         nt          |           }t          |                                          k    rt          j        ddi          S 	 t          j        |           n5# t          j	        $ r#}t          j        dd| i          cY d }~S d }~ww xY wt          d	d
          5 }|                    |           d d d            n# 1 swxY w Y   dS # t          $ rJ}t                              d|d           t          j        dt          |          i          cY d }~S d }~ww xY w)Nz+Write access required to save this workflowr   zXOpen the app via the write-access link printed at launch (or sign in as the Space owner)rP  r   r  z#Workflow payload exceeds 5 MB limitzInvalid workflow JSON: wr5  r6  okzsave_workflow failed: %sTr]  )r   ru   rv   r   r   r   rt   encoderb  JSONDecodeErrorr   r   r   rg  r  )	ri   r   r   payloadr  r   r   _max_workflow_bytesworkflow_files	          r!   save_workflowz&Workflow._build.<locals>.save_workflow  s   
 $GU33 z!N&,'L   5%/d%;%;SS$q''#d))w~~''((+>>>:w0U&VWWWRJw''''+ R R R:w0O#0O0O&PQQQQQQQQR-w??? %1GGG$$$% % % % % % % % % % % % % % %t 5 5 57TJJJz7CFF"3444444445sr   A(D  B* )D  *C9CCD  CD  1DD  DD  DD   
E4*?E/)E4/E4rG  F)visible)r   server_functionsr   rz   r   )r;  r>  r   r   NNr   r=  r   r>  r   r   )gradio gradio.components.workflowcanvasr3  r(  r   r   rX  r"  rg  warningr'  r   rE  rH  rp  r  r  r  r  r  r  r   r   LoginButton)rQ   grr3  r:  r=  rA  rJ  rL  rH  rI   rI  s   `       @@@r!   r.  zWorkflow._build5  s    CCCCCC; 	27>>$*=>> 	NNN#  		 		 		 		 		 		 	 	 	 	 	 	 	2 +-&	) &	) &	) &	) &	) &	) &	)T *.*.	5 	5 	5 	5 	5 	5 	5 	5< 
   	 	{{&295F+G+G&u---N#!1   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	s   ADD"%D"c                b   |rgt          t          j        t                      j                  j                  }|                    t          t          ||                               t          j
                    g|                    d          pg |d<   t          |                    dd                    }t          |                    dd                    }t          |                    dd                    }d|d<   | j        }d | _        	  t                      j        di |}|| _        n# || _        w xY w|\  }	}
}d}t                      @|
r>d|
v rd	nd}|
 | d
t           }|                    dd          st!          d|            |r!t#          j        |p| j        r|r|n|
           t          t)          t*          dt*          j        j                            }|s*t1          t3          j        dd                    dk    s|s|s|                                  |S )u  Launch the workflow as a Gradio app. Accepts the same arguments as `gr.Blocks.launch()`.
        `call_space` / `_save_tmp` write inference outputs to the system tempdir
        and serve them back as `/gradio_api/file=…` URLs; the tempdir is added
        to `allowed_paths` so those URLs resolve.

        Locally, editing requires the write token: the full edit link is printed
        after the standard launch output (and used for `inbrowser`). Plain
        local/share URLs open the app read-only.allowed_pathsprevent_thread_lockFdebug	inbrowserc                     d S r   r%   r%   r#   r!   r  z!Workflow.launch.<locals>.<lambda>  s    D r#   N?r  zwrite_token=quietzb
* Workflow write-access link (keep private as it lets you edit the workflow that all users see): ps1GRADIO_DEBUG0rL  r%   )r   rm   rn   r,  launchrq   updater   zipr   r   r   r   block_threadr   r   print
webbrowserr   sharer  r  flagsinteractiver   r   r   )rQ   rk  kwargsnamesrW  rX  rY  real_block_threadlaunch_resultr4   	local_url	share_url	write_urlsepis_in_interactive_moder1  s                  r!   r`  zWorkflow.launch  si     	2*577>::EFFEMM$s5$//00111!!#
jj))/R#
 #6::.CU#K#KLLVZZ//00K7788	#{ -(L	2*EGGN44V44M 1D 1D1111"/9i	;;9	))##sC$DcDD{DDI::gu--  F  {D  F  F    	OS4:R)Rii   "&gc5#):O&P&P!Q!Q	 29^S1122a77' 80F 8 s   D8 8	Er   )r  rz   r  r  rK   rL   )r  
__module____qualname____doc__r-  r.  r`  __classcell__)r1  s   @r!   r  r    s         @ !5 =A.25 5 5 5 5 5 5 5nR R Rh8 8 8 8 8 8 8 8 8r#   r  )r   r   r   r   r   r   )NrH   )rI   rJ   rK   rL   rM   r   r   r   rM  )r   r   r   r   )r   rz   r   r   rN  )r   r   r   r   r   r   r   )ri   r   r   r   r   r   r   rz   )r   )r   r   r   rz   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   )r   r   )r   r   r   r   )r   r   r   r   )NNNrO  )Drt  
__future__r   rm   ru   loggingr   r`  r   r  r   urllib.parser   r)  re  collections.abcr   typingr   r   r  r   r   r|   gradio.blocksr   gradio.oauthr	   gradio.route_utilsr
   gradio.utilsr   	getLoggerr  rg  r   floatr   rU   rG   ry   r}   token_urlsafer   r   r   r   r   r   r   r   r   r   r   r   r  r  r  rE  rH  rp  r  r  r  r  r  r  r  r%   r#   r!   <module>r     s_   M M " " " " " "    				 				  



           $ $ $ $ $ $        ! ! ! ! ! ! 5 5 5 5 5 5             # # # # # # & & & & & & " " " " " "		8	$	$ HeXtY?1 1 1 1l +/4 4 4 4 4n	 	 	 	" $g#B'': 5    D %''   ( @D- - - - - <@
 
 
 
 
       &	N 	N 	N 	NK K K KL7 L7 L7 L7^
 
 
 
' ' ' V !%"&      !%"&C C C C C     LPM  M  M  M  M b LPD  D  D  D  D P LP(X (X (X (X (XX LPm- m- m- m- m-b LP- - - - -> LP- - - - - LP4- 4- 4- 4- 4-nb b b b bv b b b b br#   