
    ;gX                        d dl m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mZ ddlmZmZ ddl	mZ dd	lmZ dd
lmZ ddlmZmZ  G d de      Zd Zd Zd Zd ZddZddZ G d de      Z dZ!y)    )annotationsN)defaultdict)ClassVar   )ColumnRow)	HoloViewsMarkdown)Param)param_reprs)Viewer)ButtonSelectc                      e Zd ZdZy)PipelineErrorzb
    Custom error type which can be raised to display custom error
    message in a Pipeline.
    N)__name__
__module____qualname____doc__     .lib/python3.12/site-packages/panel/pipeline.pyr   r      s    r   r   c                h    d||<   | j                  |g       D ]  }||   dk(  st        | ||        y)zC
    Traverse the graph from a node and mark visited vertices.
    TFN)gettraverse)graphvvisitedis       r   r   r      s:     GAJYYq"1:UAw' r   c                v    | j                  |      }|y||v r|gS |D ]  }t        | ||      }||g|z   c S  y)z@
    Find a route to the target node from the current node.
    N)r   
find_route)r   currenttarget
next_nodesnroutes         r   r!   r!   %   s[     7#J	:	xAua0E}3u9	 
 r   c                   g }| j                         D cg c]  }|D ]  }|  }}}| D ]  }||vs|j                  |        t        |      dkD  rt        d      t        |      dk(  rt        d      |d   S c c}}w )zC
    Search for the root node by finding nodes without inputs.
    r   ziGraph has more than one node with no incoming edges. Ensure that the graph only has a single source node.r   z^Graph has no source node. Ensure that the graph is not cyclic and has a single starting point.)valuesappendlen
ValueError)r   rootststtargetssrcs         r   get_rootr1   7   s    
 E <<>6>R2aq2q>G6gLL  5zA~ : ; 	; 
Uq + , 	, 8O 7s   A=c           	        |j                         D ci c])  \  }}j                  |      t        fd|D              + }}}dgt              z  }t	        |j                  |       |       t        |      S c c}}w )zE
    Check if the graph is fully traversable from the root node.
    c              3  @   K   | ]  }j                  |        y wN)index).0r.   stagess     r   	<genexpr>z!is_traversable.<locals>.<genexpr>R   s     'FAQs   F)itemsr5   tupler*   r   all)rootr   r7   stgts	int_graphr   s     `    r   is_traversabler@   M   s{     !&/ -WQ a%'F'F"FF -  /gc&k!GYT*G4w<	/s   .A<c           	         g }|j                  | g       D ]!  }|j                  t        |||dz                # |rt        |      S |dz   S Nr   )r   r)   	get_depthmax)noder   depthdepthssubs        r   rC   rC   Y   sJ    Fyyr"iUE!G45 # 3v;-eAg-r   c                    |#t        t              }||   j                  |        |j                  | g       D ]4  }|||dz      vr||dz      j                  |       t	        |||dz   |       6 |S rB   )r   listr)   r   get_breadths)rE   r   rF   breadthsrH   s        r   rK   rK   `   sz    t$t$yyr"huQw''U1W$$S)S%q(3 # Or   c                  `    e Zd ZU dZ ej
                  dd      Z ej
                  dd      Z ej
                  dd      Z ej                  ddd	
      Z
 ej                  ddd
      Z ej
                  dd      Z ej                  d       Z ej                  d       ZdZded<   g i f fd	Zd Zd Zd Zd Zd Zd Zd Zd Zd Zed        Zed        Zd Zd  Z  ejB                  d!d"      d#        Z" ejB                  d$d"      d%        Z#d& Z$d' Z%d( Z&d*d)Z' xZ(S )+PipelineaJ  
    A Pipeline represents a directed graph of stages, which each
    return a panel object to render. A pipeline therefore represents
    a UI workflow of multiple linear or branching stages.

    The Pipeline layout consists of a number of sub-components:

    * header:

      * title: The name of the current stage.
      * error: A field to display the error state.
      * network: A network diagram representing the pipeline.
      * buttons: All navigation buttons and selectors.
      * prev_button: The button to go to the previous stage.
      * prev_selector: The selector widget to select between
        previous branching stages.
      * next_button: The button to go to the previous stage
      * next_selector: The selector widget to select the next
        branching stages.

    * stage: The contents of the current pipeline stage.

    By default any outputs of one stage annotated with the
    param.output decorator are fed into the next stage. Additionally,
    if the inherit_params parameter is set any parameters which are
    declared on both the previous and next stage are also inherited.

    The stages are declared using the add_stage method and must each
    be given a unique name. By default any stages will simply be
    connected linearly, but an explicit graph can be declared using
    the define_graph method.
    FzI
        Whether to automatically advance if the ready parameter is True.)defaultdocz]
        Whether to raise errors, useful for debugging while building
        an application.TzP
        Whether parameters should be inherited between pipeline
        stages.NzU
        Parameter name to watch to switch between different branching
        stages)rO   
allow_refsrP   zC
        Parameter name to watch to check whether a stage is ready.zY
        Whether to show the header with the title, network diagram,
        and buttons.c                8    | j                   j                  d      S )Nnextparamtriggerxs    r   <lambda>zPipeline.<lambda>   s    !''//&*Ar   )rO   c                8    | j                   j                  d      S )NpreviousrT   rW   s    r   rY   zPipeline.<lambda>   s    aggooj.Ir   )next_parameterready_parameterzClassVar[tuple[str, ...]]_ignored_refsc                   	 dd l }t        |   di | d | _        i | _        i | _        d | _        d| _	        d| _
        d | _        i | _        g | _        |j                  j                         | _        | j                   j#                  | j$                         t'        | j(                  j*                        j,                  d   | _        d| j.                  _        t3        d      | _        t'        | j(                  j6                        j,                  d   | _        d| j8                  _        t3        d      | _        d| j.                  _        | j:                  j(                  j?                  | j@                  d       tC        d	      | _"        tG        d
d      | _$        tK        d      | _&        tK        | j.                  | j8                        | _'        tK        tQ        | jH                  | jL                        | jD                  | jN                  d      | _)        | jU                         | jD                  _+        tK               | _,        tQ        | jR                  | jX                  d      | _        |D ]@  }i }t[        |      dk(  r|\  }}nt[        |      dk(  r|\  }}} | j\                  |fi | B | j_                  |       y # t        $ r t        d      d w xY w)Nr   z+Pipeline requires holoviews to be installedTF}   )widthvaluebokeh)backendz# Headerr   r   r      )margind   stretch_width)sizing_mode      r   )0	holoviews	ExceptionImportErrorsuper__init___stage_stages_states_state_linear_block_error_graph_routestreamsSelection1D_progress_seladd_subscriber
_set_stager   rU   r[   layoutprev_buttonra   r   prev_selectorrS   next_buttonnext_selectordisabledwatch_update_progressr	   networkr
   titler   errorbuttonsr   header_make_progressobjectstager*   	add_stagedefine_graph)	selfr7   r   paramshvr   kwargsname	__class__s	           r   rq   zPipeline.__init__   s`   	W" 	"6"   ZZ335))$//: !4!45<<Q?!$##. 188;!$##.$(!  &&t'<'<gF 1j>
s^
4++T-=-=>4::tzz*LLLL'	
 #113U
T[[$**/R EF5zQ#eUq&+#eVDNN41&1  	% c  	WKLRVV	Ws   K K!c                    | j                   S r4   )r   r   s    r   	__panel__zPipeline.__panel__   s    {{r   c                   t        fd| j                  j                         D              rt        d d      t	        t
              rt        t        j                        s&t	        t        j                        st        d      y y )Nc              3  2   K   | ]  \  }\  }}|u   y wr4   r   )r6   r%   r=   kwr   s       r   r8   z%Pipeline._validate.<locals>.<genexpr>   s      A,@ja!Ruz,@s   zStage z is already in pipelinez;Pipeline stages must be Parameterized classes or instances.)	anyrs   r9   r+   
isinstancetype
issubclassrU   Parameterized)r   r   s    `r   	_validatezPipeline._validate   ss    ADLL,>,>,@AAveW,CDEEeT*z%ATAT/Uu':':;Z[[ < 0Vr   c                <   d}t        | j                  j                               D ]s  \  }\  }\  }}t        |t        j
                        rt        |      j                  }n|j                  }dj                  t        |            }|d| d| d| d| d	z  }u |S )Nz	Pipeline:z, z
    [z] z: ())
	enumeraters   r9   r   rU   r   r   r   joinr   )r   repr_strr   r   r   _cls_namer   s           r   __repr__zPipeline.__repr__   s    %.t||/A/A/C%D!A!jua%!4!45;// >>YY{512F'!BtfBxj&CCH &E r   c                "    | j                         S r4   )r   r   s    r   __str__zPipeline.__str__   s    }}r   c                &    | j                   |   d   S )Nr   )rs   )r   r5   s     r   __getitem__zPipeline.__getitem__   s    ||E"1%%r   c                   | j                   |j                  us| j                  rd| _        y | j                  }|j                  r|j
                  rd|_        n|j                  s|j
                  sd|_        | j                  | j                     d   }|j
                  r.|j                  d| j                        r| j                          y y y )NFTauto_advance)ru   objrw   r   r   newrs   rr   r   r   _next)r   eventbuttonstage_kwargss       r   _unblockzPipeline._unblock   s    ;;eii'4;;DK!!??uyy#FO"FO||DKK0499)).$:K:KLJJL M9r   c                    | j                   |j                  ury |j                  | j                  _        | j                          y r4   )ru   r   r   r   rb   r   )r   r   s     r   _select_nextzPipeline._select_next
  s3    ;;eii'#(99 r   c           	        | j                   | j                     \  }}g }| j                  j                         D ]%  \  }}| j                  |v s|j	                  |       ' |D cg c]   }|| j
                  v s| j
                  |   " }}g }i i }
}	|D ]a  }|j                  j                         j                         D ]H  \  }\  }}}||j                  vr||
vr
 |       |
|<   |
|   }|||   }||	|<   |j	                  |       J |j                  d| j                        sdD cg c]"  }|j                  |      xs t        | |d       $ }}|j                  j                  d      j                         D cg c]  \  }}||vr| }}}|	j                  |j                  j                         j                         D ci c]  \  }}||j                  v r|dk7  r||v r||! c}}       d t        |t        j                        r$ |j                  j                  d
i |	 || _        n |d
i |	| _        |D ]   }d| j                   j                  |   _        " |j                  d| j$                        }|r@||j                  v r2| j                   j                  j'                  | j(                  |d       |j                  d	| j*                        }|r@||j                  v r2| j                   j                  j'                  | j,                  |d       | j                   | j
                  | j                  <   | j                   j/                         S c c}w c c}w c c}}w c c}}w )Ninherit_params)r]   r\   existingr   r   r]   F)onlychangedr\   r   )rs   rr   ry   r9   r)   rt   rU   outputsr   r   getattrobjectsupdater(   r   r   ru   
precedencer]   r   r   r\   r   panel)r   r   r   r[   r0   r>   prevprev_statesr   r   resultsstater   r   methodr5   resultpignoredkr   r   outputready_param
next_params                            r   _init_stagezPipeline._init_stage  s?   "ll4;;7|**,IC{{d"$ - 7?Whd$$,,BVt||D)hWb E,1KK,?,?,A,G,G,I((q&%u{{*(&,hGFO $#E]F%tt$ -J  0$2E2EF$IK$Iq (++A.H'$42HH$I  K(-(;(;J(G(M(M(O /(O1g- (O /0B0B0D0J0J0L T0L1"#u{{"2qF{qF{  !!t0L T U! !& eU001EKK((DK/&/DK F35DKKf%0  #&&'8$:N:NO;%++5KK##DMM;E#R!%%&68K8KL
*3KK##D$5$5zu#U$(KKT[[!{{  ""U X K/Ts   %M"9M",'M'M,
$M2c                   |sy | j                   j                  j                  |d   df   }|| j                  j                  v r-|| j                  _        | j                  j                  d       y || j                  j                  v r-|| j                  _        | j                  j                  d       y || j                  v rNt        | j                        dkD  r5| j                  j                  d       t        | j                        dkD  r4y y t        | j                  | j                  |      }|.t        | j                  | j                  |      }|t        d      | j                  g|z   }|D ]H  }|| j                  j                  vr y || j                  _        | j                  j                  d       J y )Nr   rk   rS   r[   r   z$Could not find route to target node.)r}   sourceilocr   optionsrb   rU   rV   r   rz   r*   r!   ry   _next_stagerr   r+   )r   r5   r   r&   rs        r   r   zPipeline._set_stageC  sp   ""))..uQx{;D&&...',D$JJv&d((000',D$JJz*dkk!dkk"Q&

"":. dkk"Q& t{{D,<,<eDE}"4;;UC=$%KLL))*U2D..666+,""(

""6*	 r   c                .    | j                   j                  S r4   )r   rb   r   s    r   r   zPipeline._next_stagea      !!'''r   c                .    | j                   j                  S r4   )r   rb   r   s    r   _prev_stagezPipeline._prev_stagee  r   r   c                   | j                   | j                     \  }}t        | j                  j	                  | j                  g             }|j	                  d| j
                        }|r$||j                  v rt        | j                  |      nd }|	|r|d   nd }|| j                  _
        || j                  _        t        |       | j                  _        g }| j                  j                         D ]%  \  }}| j                  |v s|j                  |       ' || j                   _
        |r| j"                  d   nd | j                   _        t        |       | j                   _        | j$                  d| j&                  _        nd| j&                  _        | j(                  d| j*                  _        y |j	                  d| j,                        }	|	|j                  v rt        ||	       nd}
|
| j*                  _        y )Nr\   r   r   TFr]   )rs   rr   rJ   ry   r   r\   rU   r   ru   r   r   rb   boolr   r9   r)   r   rz   r   r   r   r   r]   )r   r   r   r   r   optionr[   r0   r>   readyr   s              r   _update_buttonzPipeline._update_buttoni  s   T[[1vt{{t{{B78ZZ 0$2E2EF
5?JRWR]R]D]j1cg>#*WQZF%,"#) *.w-&7#**,IC{{d"$ - &."6>4;;r?D *.x.&8# #(,D%(-D% #(,D%JJ0$2F2FGE6;u{{6JGE511PUH(0D%r   c                |   t        |t              rt        |      nd}| j                  rft	        j
                         \  }}}t        j                  |d       t        j                  ||      z   }|ddj                  |dd       dd|d   }n|xs d}t        dd	d
dd      }|j                  d| d       |S )N z

Traceback (innermost last):
r   20 z#Undefined error, enable debug mode.Errordangerrh   centerre   )r   button_typera   alignrg   zalert(`z`))code)r   r   strdebugsysexc_infotb	format_tbformat_exception_onlyr   r   js_on_click)	r   emsgr   rb   trbtb_list	tracebackr   s	            r   _get_error_buttonzPipeline._get_error_button  s    "1m4c!f"::"||~D%ll3-0H0Hu0UUGrwwwr"~6EI DDIW(#&|=')B 78r   rS   )r   c                   | j                   | j                  }}| j                  | _        d| j                  _        	 | j                         | j                  d<   g | j                  d d  d | _        | j                          | j                  j                  | j                         | j                  | j                     d   }|j                  d| j                        }|rDt        | j                   |d      r-|j                  d| j                        r| j!                          	 | j+                          d| j                  _        y # t"        $ r}| j                  | _        || _        || _         |j%                         | j                  d<   | j'                  |      g| j                  d d  | j(                  r||cY d }~| j+                          d| j                  _        S d }~ww xY w# | j+                          d| j                  _        w xY w)NTr   r   r]   Fr   )ru   rr   r   r   loadingr   r   rx   r   rz   r)   rs   r   r]   r   r   r   rn   r   r   r   r   )r   
prev_state
prev_stager   r   r   s         r   r   zPipeline._next  s   !%dkkJ
&&!

	' ,,.DJJqM DJJqMDK!KKt{{+<<4R8L&**+<d>R>RSK[% H  1B1BC

!!#!&DJJ+  	++DK$DK$DK&,,.DJJqM!33A67DJJqMzzH !!#!&DJJ+	( !!#!&DJJs7   E C	G& 	G#A*G7G#8G& G##G& &#H	r[   c                   | j                   | j                  }}| j                  | _        	 | j                  | j                  v rF| j                  | j                     | _         | j                   j	                         | j
                  d<   n| j                         | j
                  d<   d| _        g | j                  d d  d | _	        | j                          | j                  j                          | j!                          y # t        $ rV}| j                  |      g| j                  d d  | j                  | _	        || _        || _         | j                  r|Y d }~kd }~ww xY w# | j!                          w xY w)Nr   T)ru   rr   r   rt   r   r   r   rw   r   rx   r   rz   poprn   r   r   r   )r   r   r   r   s       r   	_previouszPipeline._previous  s"   !%dkkJ
&&	${{dll*"ll4;;7 $ 1 1 3

1 $ 0 0 2

1DK DJJqMDK!KKOO!!#  	!33A67DJJqM++DK$DK$DKzz 	 !!#s2   BC> -A E  >	EAEE  EE   E2c                ~    d| j                   z   | j                  _        | j                         | j                  _        y )Nz
## Stage: )rr   r   r   r   r   )r   argss     r   r   zPipeline._update_progress  s,    (4;;6

"113r   c                   dd l }dd l}| j                  rbt        | j                        }t	        || j                        }t        || j                        }t        d |j                         D              }n	d }d\  }}i }d|dz
  dz  z   }g }| j                  j                         D ]  \  }	}
|
D ]  }|j                  |	|f        ! g }|j                         D ]  \  }}t        |      }d|z  }t        |d d d         D ][  \  }}|| j                  k(  rd	}n&|| j                  k(  rd
}n|| j                  k(  rd}nd}|j                  ||dz  ||z  z   ||f       ]  ddddd}d }|j                  |g dd      j!                  ddg|gdddddd	      }|| j"                  _        |j'                  ||f      j!                  dd|g dgd ddd	      }|j)                  |dd gd!      j!                  d"g dd#      }| j*                  r||z  |z  n||z  }d$|d%z   f}|j!                  d d d&dd'||d'd(dgd d)       |S )*Nr   c              3  2   K   | ]  }t        |        y wr4   )r*   )r6   r   s     r   r8   z*Pipeline._make_progress.<locals>.<genexpr>  s     @.?c!f.?s   )r   r   P   r      g      ?r   activer   rS   inactiveg       @whitez#5cb85credyellow)r
  r	  r   rS   c                t    ddl m} | j                  d   }| j                  j	                  |      }|g|_        y )Nr   )TapToolglyph_renderer)bokeh.modelsr  handlesr   
select_one	renderers)plotelementr  grtaps        r   tap_rendererz-Pipeline._make_progress.<locals>.tap_renderer  s1    ,./B**''0CDCMr   )rX   yStageStater  T
   rc   )	alphadefault_toolshookshover_alphaselection_alphanonselection_alphaaxiswisesizerd   blackhovergray)	edge_hover_line_color
node_colorcmaptoolsr  selection_policynode_hover_fill_colorr$  rd   rX   r  r  g333333ӿ)yoffsetr  r$  rd   g      пg      ?i  F)r   r   )xaxisyaxis	min_width
responsive
show_frameheightxlimshared_axesylimr  toolbarrd   )rm   holoviews.plotting.bokehry   r1   rC   rK   rD   r(   r9   r)   r*   r   rr   rx   r   Nodesoptsr}   r   GraphLabelsrv   )r   r   rm   r<   rF   rL   max_breadthr5  edgesr0   r>   r.   nodessubnodesbreadthstepr   r%   r   r+  r  r   labelsr  r6  s                            r   r   zPipeline._make_progress  s   ';;DKK(DdDKK0E#D$++6H@hoo.?@@KD!%KH{1}****,ICc1X&  - '~~/OE8(mGg:D!(4R4.11#$E$++%#E$***"E&EeT"WQtV^Q>? 2  0 $y5 "	!  3W=BBE7<.1G C 

 %*!%(--")gDWI"(4 . J 53*g6;;T7 < 
 ,0<<&eemut|$		dcdV$Ey$ 	 	

 r   c                2   | j                  |       |D ]  }|| j                  vst        d| d       | j                  s| j                  rt        d      ||f| j                  |<   t        | j                        dk(  r5|| _        |g| _	        i | _        | j                         g| j                  dd n<| j                  D cg c]  }|| j                  vs| c}d   }|f| j                  |<   | j                          | j                          yc c}w )af  
        Adds a new, named stage to the Pipeline.

        Parameters
        ----------
        name: str
          A string name for the Pipeline stage
        stage: param.Parameterized
          A Parameterized object which represents the Pipeline stage.
        **kwargs: dict
          Additional arguments declaring the behavior of the stage.
        zKeyword argument z is not a valid parameter.z.Cannot add stage after graph has been defined.r   Nr   )r   rU   r+   rv   ry   RuntimeErrorrs   r*   rr   rz   r   r   r   r   )r   r   r   r   r   r=   r[   s          r   r   zPipeline.add_stage  s     	uA

" #4QC7Q!RSS  ||OPP#V_Tt||!DK&DKDK!--/0DJJqM#'<<H<a1DKK3G<HKH%)GDKK! Is   DDc           	     
   t        | j                        }|si | _        y|j                         D ci c]  \  }}|t	        |t
              r|n|f }}}g }|j                         D ]2  \  }}||vr|j                  |       ||D 	cg c]	  }	|	|vs|	 c}	z  }4 |r't        dt        |      dk(  r|d   z        |z        |r!| j                  s|st        d      d| _	        n&t        |dd |dd       D 
	ci c]	  \  }
}	|
|	f }}
}	t        |      }t        |||      st        d| d	      || j                  u}|| _        || _        |g| _        | j                  sMt        | j                   | j"                        t        | j$                  | j&                        g| j(                  dd |r| j+                         g| j,                  dd | j/                          | j1                          yc c}}w c c}	w c c}	}
w )
a  
        Declares a custom graph structure for the Pipeline overriding
        the default linear flow. The graph should be defined as an
        adjacency mapping.

        Parameters
        ----------
        graph: dict
          Dictionary declaring the relationship between different
          pipeline stages. Should map from a single stage name to
          one or more stage names.
        NzZPipeline stage(s) %s not found, ensure all stages referenced in the graph have been added.r   r   z?Graph has already been defined, cannot override existing graph.Fr   z+Graph is not fully traversable from stage: .)rJ   rs   ry   r9   r   r:   r)   r+   r*   rv   zipr1   r@   rr   rz   r   r   r   r   r   r   r   r   r   r   )r   r   forcer7   r   r   	not_foundr   r/   r.   r=   r<   reinits                r   r   zPipeline.define_graph;  s    dll#DKDIKKMRMDAqAu-AA47MR	${{}OFGV#  (W@W!W@@I  - ;!$Y1!41E  ;DE  LLE  "C D D DL),VCR[&*)EF)EAQW)EEFdE62J4&PQRSST[[(f||t))4+;+;<t))4+;+;<DLLO !--/0DJJqMM S A Gs    G4	G:G:>G?)F))r   r   r   r   rU   Booleanr   r   r   Stringr\   r]   show_headerActionrS   r[   r^   __annotations__rq   r   r   r   r   r   r   r   r   r   propertyr   r   r   r   dependsr   r  r   r   r   r   __classcell__)r   s   @r   rN   rN   l   s   B !5== 5L ML EMM% . E #U]]4 6 N "U\\$5 G N #ell4E HF GO  %-- 3 K 5<< ABDu||$IJH/TM,T  4!l\	& 1#f+< ( ( ( (1@ U]]6&' '': U]]:T*$ +$24ANB8r   rN   )rN   )r   )r   N)"
__future__r   r   r   r   collectionsr   typingr   rU   r   r   r   paner	   r
   r   utilr   viewabler   widgetsr   r   rG  r   r   r!   r1   r@   rC   rK   rN   __all__r   r   r   <module>r^     si    " 
  #    %    #L ($,	.Gv GTr   