
    ;3hL/                    B   d Z ddlmZ ddlmZ ddlmZmZ 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mZm	Z	 dd	lmZ dd
lmZmZ ddlmZ ddlmZ erddlmZ ej@                  jC                           G d de      Z" G d de      Z# e        G d de             Z$y)zgr.AnnotatedImage() component.    )annotations)Sequence)TYPE_CHECKINGAnyNhandle_file)document)processing_utilsutils)	Component)FileDataGradioModel)Events)I18nData)Timerc                  "    e Zd ZU ded<   ded<   y)
Annotationr   imagestrlabelN__name__
__module____qualname____annotations__     a/var/www/html/audio-gradio/venv/lib/python3.12/site-packages/gradio/components/annotated_image.pyr   r      s    OJr   r   c                  "    e Zd ZU ded<   ded<   y)AnnotatedImageDatar   r   zlist[Annotation]r   Nr   r   r   r   r    r       s    O!!r   r    c                       e Zd ZdZej
                  gZeZ	 ddddddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZ		 	 	 	 dd	Z
	 	 	 	 dd
ZddZddZ xZS )AnnotatedImageaF  
    Creates a component to displays a base image and colored annotations on top of that image. Annotations can take the from of rectangles (e.g. object detection) or masks (e.g. image segmentation).
    As this component does not accept user input, it is rarely used as an input component.

    Demos: image_segmentation
    NwebpT   value)formatshow_legendheightwidth	color_mapr   everyinputs
show_label	containerscale	min_widthvisibleelem_idelem_classesrenderkeypreserved_by_keyshow_fullscreen_buttonc                   || _         || _        || _        || _        || _        || _        d| _        t        | !  |||	|
||||||||||       y)a  
        Parameters:
            value: Tuple of base image and list of (annotation, label) pairs.
            format: Format used to save images before it is returned to the front end, such as 'jpeg' or 'png'. This parameter only takes effect when the base image is returned from the prediction function as a numpy array or a PIL Image. The format should be supported by the PIL library.
            show_legend: If True, will show a legend of the annotations.
            height: The height of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image.
            width: The width of the component, specified in pixels if a number is passed, or in CSS units if a string is passed. This has no effect on the preprocessed image file or numpy array, but will affect the displayed image.
            color_map: A dictionary mapping labels to colors. The colors must be specified as hex codes.
            label: the label for this component. Appears above the component and is also used as the header if there are a table of examples for this component. If None and used in a `gr.Interface`, the label will be the name of the parameter this component is assigned to.
            every: Continously calls `value` to recalculate it if `value` is a function (has no effect otherwise). Can provide a Timer whose tick resets `value`, or a float that provides the regular interval for the reset Timer.
            inputs: Components that are used as inputs to calculate `value` if `value` is a function (has no effect otherwise). `value` is recalculated any time the inputs change.
            show_label: if True, will display label.
            container: If True, will place the component in a container - providing some extra padding around the border.
            scale: Relative width compared to adjacent Components in a Row. For example, if Component A has scale=2, and Component B has scale=1, A will be twice as wide as B. Should be an integer.
            min_width: Minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain scale value results in this Component being narrower than min_width, the min_width parameter will be respected first.
            visible: If False, component will be hidden.
            elem_id: An optional string that is assigned as the id of this component in the HTML DOM. Can be used for targeting CSS styles.
            elem_classes: An optional list of strings that are assigned as the classes of this component in the HTML DOM. Can be used for targeting CSS styles.
            render: If False, component will not render be rendered in the Blocks context. Should be used if the intention is to assign event listeners now but render the component later.
            key: in a gr.render, Components with the same key across re-renders are treated as the same component, not a new component. Properties set in 'preserved_by_key' are not reset across a re-render.
            preserved_by_key: A list of parameters from this component's constructor. Inside a gr.render() function, if a component is re-rendered with the same key, these (and only these) parameters will be preserved in the UI (if they have been changed by the user or an event listener) instead of re-rendered based on the values provided during constructor.
            show_fullscreen_button: If True, will show a button to allow the image to be viewed in fullscreen mode.
        za tuple of type [image: str, annotations: list[tuple[mask: str, label: str]]] where 'image' is the path to the base image and 'annotations' is a list of tuples where each tuple has a 'mask' image filepath and a corresponding label.)r   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r%   N)	r&   r'   r(   r)   r*   r7   _value_descriptionsuper__init__)selfr%   r&   r'   r(   r)   r*   r   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   	__class__s                        r   r;   zAnnotatedImage.__init__1   sy    j &
"&<# #L!%- 	 	
r   c                    |y|j                   j                  }|j                  D cg c]$  }|j                   j                  |j                  f& }}||fS c c}w )aA  
        Parameters:
            payload: Dict of base image and list of annotations.
        Returns:
            Passes its value as a `tuple` consisting of a `str` filepath to a base image and `list` of annotations. Each annotation itself is `tuple` of a mask (as a `str` filepath to image) and a `str` label.
        N)r   pathr   r   )r<   payloadbase_imgar   s        r   
preprocesszAnnotatedImage.preprocess~   sV     ?==%%8?8K8KL1agg.LL+&& Ms   )Ac                .   |y|d   }t        |t              rkt        j                  |      r!t	        j
                  || j                        }|}t        j                  t        j                  j                  |            }nt        |t        j                        rKt	        j                  || j                  | j                        }t        t        j                   |            }nt        |t        j                  j                        r`t	        j"                  || j                  | j                        }t        t        j                   |            }t        j                  |      }nt%        d      g }| j&                  xs i }d }|d   D ]  \  }}	t        j(                  |j*                  d   |j*                  d   f      }
t        |t        j                        r|}
nL|\  }}}}d}d	|
||||f<   d|
|||||z   f<   d|
||||z
  |f<   d|
|||z   ||f<   d|
||z
  |||f<   |	|v r |||	         }ng d
}t        j(                  |j*                  d   |j*                  d   df      }t        j,                  |
      }d||dkD  <   |d   |z  |dddddf<   |d   |z  |dddddf<   |d   |z  |dddddf<   |
dz  |dddddf<   t        j                  j/                  |j1                  t        j2                              }t	        j"                  || j                  d      }t        t        j                   |            }|j5                  t7        t9        |      |	              t;        t9        |      |      S )a  
        Parameters:
            value: Expects a a tuple of a base image and list of annotations: a `tuple[Image, list[Annotation]]`. The `Image` itself can be `str` filepath, `numpy.ndarray`, or `PIL.Image`. Each `Annotation` is a `tuple[Mask, str]`. The `Mask` can be either a `tuple` of 4 `int`'s representing the bounding box coordinates (x1, y1, x2, y2), or 0-1 confidence mask in the form of a `numpy.ndarray` of the same shape as the image, while the second element of the `Annotation` tuple is a `str` label.
        Returns:
            Tuple of base image file and list of annotations, with each annotation a two-part tuple where the first element image path of the mask, and the second element is the label.
        Nr   )	cache_dir)rE   r&   zUAnnotatedImage only accepts filepaths, PIL images or numpy arrays for the base image.c           
         | j                  d      } t        |       }t        d||dz        D cg c]  }t        | |||dz  z    d       c}S c c}w )N#r         )lstriplenrangeint)r%   lvis      r   
hex_to_rgbz.AnnotatedImage.postprocess.<locals>.hex_to_rgb   sQ    LL%EUB=B1b"PQ'=RSCa!bAg+.3SSSs   A   rH   g      ?)   r   r         rR   png)r?   )r   r   r   r   )
isinstancer   client_utilsis_http_url_liker
   save_url_to_cacheGRADIO_CACHEnparrayPILImageopenndarraysave_img_array_to_cacher&   r   abspathsave_pil_to_cache
ValueErrorr*   zerosshapecopy	fromarrayastypeuint8appendr   r   r    )r<   r%   rA   base_img_path	base_filesectionsr*   rP   maskr   
mask_arrayx1y1x2y2border_width	rgb_colorcolored_mask
solid_maskcolored_mask_img	mask_filemask_file_paths                         r   postprocesszAnnotatedImage.postprocess   sj     =8h$,,X6+==(9(9 %Mxx		x 89H"**-(@@D$5$5dkkI  i 89M#))//2(::D$5$5dkkI  i 89Mxx)Hg  NN(b		T
 !8 #	KD%8>>!#4hnnQ6G"HIJ$

+!
!%BB +.
2b5"R%<(<=
2b5"rL'8"889<=
2b5"|"3b"889<=
2\ 112b589<=
2,r12b589	!&y'78	'	88X^^A%6q8I1$MNL,J)*JzA~&$-aL:$=LAq!$-aL:$=LAq!$-aL:$=LAq!$.$4LAq!"yy22L3H3H3RS ):: D,=,=eI !y!9:NOO~!>eLC#	J ". 
 	
r   c                    t        d      g dS )NPhttps://raw.githubusercontent.com/gradio-app/gradio/main/test/test_files/bus.pngrV   r   r<   s    r   example_payloadzAnnotatedImage.example_payload   s     b 	
 	
r   c                    dg ddfgfS )Nr   )r   r   d   r   busr   r   s    r   example_valuezAnnotatedImage.example_value   s    ^&'
 	
r   )N)(r%   zjtuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | Noner&   r   r'   boolr(   int | str | Noner)   r   r*   zdict[str, str] | Noner   zstr | I18nData | Noner+   zTimer | float | Noner,   z7Component | Sequence[Component] | set[Component] | Noner-   zbool | Noner.   r   r/   z
int | Noner0   rM   r1   r   r2   z
str | Noner3   list[str] | str | Noner4   r   r5   z(int | str | tuple[int | str, ...] | Noner6   r   r7   r   )r@   AnnotatedImageData | Nonereturnz(tuple[str, list[tuple[str, str]]] | None)r%   zntuple[np.ndarray | PIL.Image.Image | str, Sequence[tuple[np.ndarray | tuple[int, int, int, int], str]]] | Noner   r   )r   r   )r   r   r   __doc__r   selectEVENTSr    
data_modelr;   rC   r}   r   r   __classcell__)r=   s   @r   r"   r"   $   s    mm_F#J K
  #'"&+/'+&*JN"& "/38<3:'+9K
K
 K
 K
 !K
  K
 )K
 %K
  $!K
" H#K
$  %K
& 'K
( )K
* +K
, -K
. /K
0 -1K
2 3K
4 65K
6 17K
8 !%9K
Z'0'	1'Z
Z
 
#Z
x

r   r"   )%r   
__future__r   collections.abcr   typingr   r   gradio_client.utilsr   rX   numpyr\   	PIL.Imager^   gradio_clientr   gradio_client.documentationr	   gradior
   gradio.components.baser   gradio.data_classesr   r   gradio.eventsr   gradio.i18nr   gradio.componentsr   r_   initr   r    r"   r   r   r   <module>r      s{    $ " $ % *   % 0 * , 5    ' 		  
" "
 
P
Y P
 P
r   