
    Pi.                    l   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Zd dlZd dl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 d dlmZ ej                                         d?dZ 	 	 d@dAdZ!	 dBdCdZ"dDd#Z#dEd(Z$dFd*Z%dGd,Z&dBdHd-Z'dId/Z(dJd0Z)dKd3Z*dKd4Z+dLd9Z,	 dMdNd>Z-dS )O    )annotationsN)BytesIO)Path)Literalcast)quote)get_mimetypeis_http_url_like)ImageOps)processing_utils)WatermarkOptions)	ImageData)Errororig_img)np.ndarray | PIL.Image.Image | str | PathreturnPIL.Image.Imagec                   t          | t          j                  r t          j                            |           }nt          | t          t          f          r t          j                            |           }nNt          | t          j        j                  r| }n,t          dt          t          |                     z             |S )z
    Provided an array, PIL Image or filepath, return a PIL Image.
    Parameters:
        orig_img: Local image file. If a filepath, it must be a webp, png, jpeg, or bmp.
    Returns:
        open_img: A PIL.Image.Image.
    zeExpected image or path to image of type webp, png, bmp or jpeg; PIL image; or numpy array. Received  )
isinstancenpndarrayPILImage	fromarraystrr   open
ValueErrortype)r   open_imgs     f/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/gradio/image_utils.py
open_imager!      s     (BJ'' 

9&&x00	HsDk	*	* 
9>>(++	Hcio	.	. 
s$x..!!"
 
 	
 O    imagewebpimPIL.Image.Image | Noner   #Literal['numpy', 'pil', 'filepath']	cache_dirr   nameformat)np.ndarray | PIL.Image.Image | str | Nonec                4   | | S |dk    r| S |dk    rt          j        |           S |dk    rK	 t          j        | |||          }n/# t          t
          f$ r t          j        | ||d          }Y nw xY w|S t          dt          |          z   dz             )	z3Helper method to format an image based on self.typeNpilnumpyfilepath)r(   r)   r*   pngzUnknown type: z1. Please choose from: 'numpy', 'pil', 'filepath'.)r   arrayr   save_pil_to_cacheKeyErrorr   r   )r%   r   r(   r)   r*   paths         r    format_imager5   /   s     
z	u}}		x||				#5id6  DD *% 	 	 	#5#	  DDD	 $iiAB
 
 	
s   A )A32A3yc                   t          | t          j                  rt          j        | ||          }nt          | t
          j        j                  rG	 t          j        | ||          }n# t          t          f$ r t          j        | |d          }Y nmw xY wt          | t                    rt          |           }nDt          | t                    r| }n,t          dt          t          |                     z             |S )Nr(   r*   r0   z6Cannot process this value as an Image, it is of type: )r   r   r   r   save_img_array_to_cacher   r   r2   r3   r   r   r   r   )r6   r(   r*   r4   s       r    
save_imager:   S   s!    !RZ   
76
 
 
 
Asy	'	' 
	#5Yv  DD *% 	 	 	#5Yu  DDD	 
At		 
1vv	As		 
Ds4PQ77||S
 
 	
 Ks   A+ +(BBbase_imgwatermark_optionr   c                @   t          |           } | j        \  }}t          t          t          j        t
          j        j        z  t          z  t          z  |j	                            |_	        |j	        j        \  }}t          |j        t                    rZd}|j        dk    r||}}nR|j        dk    r||z
  |z
  |}}n<|j        dk    r|||z
  |z
  }}n&|j        dk    r||z
  |z
  ||z
  |z
  }}n
|j        \  }}|dk     s||z   |k    s|dk     s	||z   |k    r||z
  dz
  }||z
  dz
  }||f}	| j        }
|                     d          } |j	                            d          |_	        |                     |j	        |	|j	                   |                     |
          } | S )	aw  Overlays a watermark image on a base image.
    Parameters:
        base_img: Base image onto which the watermark is applied. Can be an array, PIL Image, or filepath.
        watermarkOption: WatermarkOptions instance containing watermark image and position settings.
    Returns:
        watermarked_img: A PIL Image of the base image overlaid with the watermark image.
    
   ztop-leftz	top-rightzbottom-leftzbottom-rightr   RGBA)mask)r!   sizer   r   r   r   r   r   r   	watermarkr   positionmodeconvertpaste)r;   r<   base_img_widthbase_img_heightwatermark_widthwatermark_heightpaddingxr6   watermark_positionorig_img_modes              r    add_watermarkrO   p   s    (##H&.m#NO!+RZ#)/)C/$68H8RSS" " )9(B(G%O%"+S11 )$
22GqAA&+55!O3g=wqAA&-77O.>>HqAA&.8807:"22W< A
  (1 	
A//q55/11_,r1..3QMM''H!1!;!C!CF!K!KNN"$6=M=W     ..HOr"   imgfinal_widthintfinal_heightc           	     H   | j         \  }}||z  }||z  |k    r|}||z  }n|}||z  }||z
  dz  }||z
  dz  }	|                     t          |          t          |	          t          ||z             t          |	|z             f          }
|
                    ||f          }|S )N   )rA   croprR   resize)rP   rQ   rS   original_widthoriginal_heighttarget_aspect_ratiocrop_height
crop_widthlefttopimg_croppedimg_resizeds               r    
crop_scalera      s    &)h#NO%4'*===% #66

#
 #66Z'1,D[(A
-C((	TCHHc$"344c#:K6L6LM K $$k<%@AAKr"   encodingc                H   t          j        |           }t          j                            t          t          j        |                              }	 t          t          d          rt          j
        |          }n # t          $ r t          d|           Y nw xY w|J |S )Nexif_transposez0Failed to transpose image %s based on EXIF data.)r   extract_base64_datar   r   r   r   base64	b64decodehasattrr   rd   	Exceptionprint)rb   image_encodedrP   s      r    decode_base64_to_imagerl      s    $8BBM
)..!1-!@!@AA
B
BC
8-.. 	/)#..C 
 
 
>	
 	
 	
 	
 	


 ???Js   )A> >BB
np.ndarrayc                H    t          |           }t          j        |          S N)rl   r   asarray)rb   rP   s     r    decode_base64_to_image_arrayrq      s    
 
*
*C:c??r"   c                B    t          |           }t          |||          S ro   )rl   r:   )rb   r(   r*   rP   s       r    decode_base64_to_filers      s!    
 
*
*Cc9f---r"   image_arrayc                l   t                      5 }t          j                            t	          j        | t          j        d                    }|                    |d           |	                                }d d d            n# 1 swxY w Y   t          t          j        |          d          }d|z   S )NF)
force_copyJPEGutf-8data:image/jpeg;base64,)r   r   r   r   r   _convertr   uint8savegetvaluer   rf   	b64encode)rt   output_bytes	pil_image
bytes_data
base64_strs        r    encode_image_array_to_base64r      s    	 -lI''%k28NNN
 
	 	|V,,,!**,,
- - - - - - - - - - - - - - - V%j117;;J$z11s   A)BBBc                    t                      5 }|                     |d           |                                }d d d            n# 1 swxY w Y   t          t	          j        |          d          }d|z   S )Nrw   rx   ry   )r   r|   r}   r   rf   r~   )r#   r   r   r   s       r    encode_image_to_base64r      s    	 -l

<(((!**,,
- - - - - - - - - - - - - - - V%j117;;J$z11s   +AA
A

image_file
str | Pathc                   t          t          |                     }t          | d          5 }|                                }d d d            n# 1 swxY w Y   t          t	          j        |          d          }d| d|z   S )Nrbrx   data:z;base64,)r	   r   r   readrf   r~   )r   	mime_typefr   r   s        r    encode_image_file_to_base64r      s    S__--I	j$		 1VVXX
              V%j117;;J&9&&&33s   AAAc                   t          |           } t          |           r/t          j        |           }|                                 |j        S t          |           5 }|                                }ddd           n# 1 swxY w Y   |S )z
    Provided a path or URL to an SVG file, return the SVG content as a string.
    Parameters:
        image_file: Local file path or URL to an SVG file
    Returns:
        str: The SVG content as a string
    N)r   r
   httpxgetraise_for_statustextr   r   )r   responsefilesvg_contents       r    extract_svg_contentr      s     ZJ
## 9Z((!!###}* 	&))++K	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	& 	&s   A>>BBpayloadImageData | None
image_modeULiteral['1', 'L', 'P', 'RGB', 'RGBA', 'CMYK', 'YCbCr', 'LAB', 'HSV', 'I', 'F'] | Nonec                   | | S | j         rj| j                             d          rP|dk    rt          | j                   S |dk    rt          | j                   S |dk    rt	          | j         ||          S | j        t          d          t          | j                  }| j        r=t          | j                  }|j	        }|j
                            dd          }|dv rd	}nd
}d}|                                dk    r$|dk    rt          |          S t          d          t          j                            |          }	|dk    r|d |	j        fv rt          |          S |	                                }
|
                    dd          dk    rSt+          t,          d          r>	 t-          j        |	          }	n(# t0          $ r t3          j        d| d           Y nw xY w|                                dk    rX|	Vt3          j                    5  t3          j        d           ||	                    |          }	d d d            n# 1 swxY w Y   t=          |	||||          S )Nr   r-   r.   r/   zImage path is None.. )jpgjpegr   r#   r$   svgz9SVG files are not supported as input images for this app.i     rd   zFailed to transpose image z based on EXIF data.gifignore)r   r(   r)   r*   )url
startswithrl   rq   rs   r4   r   r   	orig_namestemsuffixreplacelowerr   r   r   r   r   rD   getexifr   rh   r   rd   ri   warningswarncatch_warningssimplefilterrE   r5   )r   r(   r*   r   r   	file_pathpr)   r   r%   exifs              r    preprocess_imager     s    { Iw{--g66 I5==)'+666W__/<<<Z(iHHH|.///W\""I "##v!!#r**_$$F||~~:y>>!OPPP			"	"BzzdBG_<<9~~::<<DxxQ13C!D!D	X(,,BB 	X 	X 	XMVyVVVWWWWW	X||~~2>$&& 	, 	,!(+++%ZZ
++	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 	, 
   s$   'F< <"G! G!,I		IIvalue0np.ndarray | PIL.Image.Image | str | Path | NonerB   WatermarkOptions | Nonec                   ddl m} | dS t          | t                    rv|                                                     d          rOt          |           }| |d           t          t          |           j	        dt          |                     S |r|j        t          | |          } t          | ||          }t          |                                          rt          |          j	        nd}t          ||	          S )
a+  
    Parameters:
        value: Expects a `numpy.array`, `PIL.Image`, or `str` or `pathlib.Path` filepath to an image which is displayed.
        watermark: An optional `WatermarkOptions` instance to apply a watermark to the image.
    Returns:
        Returns the image as a `FileData` object.
    r   )WarningNz.svgzUWatermarking for SVG images is currently not supported. No watermark will be applied.zdata:image/svg+xml,)r   r   r8   )r4   r   )gradior   r   r   r   endswithr   r   r   r)   r   rB   rO   r:   exists)r   r(   r*   rB   r   r   savedr   s           r    postprocess_imager   C  s#    }t% 	
%++--"8"8"@"@ 	
)%00 Gg   5kk&:eK&8&8::
 
 
 	
  0Y(4eY//u	&AAAE$(KK$6$6$8$8BU  dI%95555r"   )r   r   r   r   )r#   r$   )r%   r&   r   r'   r(   r   r)   r   r*   r   r   r+   )r$   )r6   r   r(   r   r*   r   )r;   r   r<   r   r   r   )rP   r   rQ   rR   rS   rR   )rb   r   r   r   )rb   r   r   rm   )rb   r   r(   r   r*   r   r   r   )rt   rm   r   r   )r#   r   r   r   )r   r   r   r   )r   r   r(   r   r*   r   r   r   r   r'   r   r+   ro   )
r   r   r(   r   r*   r   rB   r   r   r   ).
__future__r   rf   r   ior   pathlibr   typingr   r   urllib.parser   r   r.   r   	PIL.Imager   gradio_client.utilsr	   r
   r   r   r   gradio.components.image_editorr   gradio.data_classesr   gradio.exceptionsr   r   initr!   r5   r:   rO   ra   rl   rq   rs   r   r   r   r   r   r    r"   r    <module>r      si   " " " " " "                                              > > > > > > > >       # # # # # # ; ; ; ; ; ; ) ) ) ) ) ) # # # # # # 	      6 !
 !
 !
 !
 !
J QW    :4 4 4 4n   .      
. . . . .
2 2 2 22 2 2 24 4 4 4   &; ; ; ;D *.	6 6 6 6 6 6 6r"   