
    qi!                         d 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m	Z	m
Z
mZ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mZmZ dd	lmZ dd
lmZmZmZmZ e G d de             Z G d de      Z y)zFal's image generation service implementation.

This module provides integration with Fal's image generation API
for creating images from text prompts using various AI models.
    N)	dataclassfield)AnyAsyncGeneratorDictOptionalUnion)logger)Image)	BaseModel)
ErrorFrameFrameURLImageRawFrame)ImageGenService)	NOT_GIVENImageGenSettings	_NotGiven_warn_deprecated_paramc                   :   e Zd ZU dZ ed       Zedz  ez  ed<    ed       Z	eez  ed<    ed       Z
eez  ed	<    ed
       Zeeeef   z  ez  ed<    ed       Zeez  ed<    ed       Zeez  ed<    ed       Zeez  ed<   deeef   fdZy)FalImageGenSettingsaG  Settings for the Fal image generation service.

    Parameters:
        model: Fal.ai model identifier.
        seed: Random seed for reproducible generation. ``None`` uses a random seed.
        num_inference_steps: Number of inference steps for generation.
        num_images: Number of images to generate.
        image_size: Image dimensions as a string preset or dict with width/height.
        expand_prompt: Whether to automatically expand/enhance the prompt.
        enable_safety_checker: Whether to enable content safety filtering.
        format: Output image format.
    c                      t         S Nr        L/opt/pipecat/venv/lib/python3.12/site-packages/pipecat/services/fal/image.py<lambda>zFalImageGenSettings.<lambda>,   s     r   )default_factoryNseedc                      t         S r   r   r   r   r   r   zFalImageGenSettings.<lambda>-   s     r   num_inference_stepsc                      t         S r   r   r   r   r   r   zFalImageGenSettings.<lambda>.   s    	 r   
num_imagesc                      t         S r   r   r   r   r   r   zFalImageGenSettings.<lambda>/   s    QZ r   
image_sizec                      t         S r   r   r   r   r   r   zFalImageGenSettings.<lambda>0   s    I r   expand_promptc                      t         S r   r   r   r   r   r   zFalImageGenSettings.<lambda>1   s    I r   enable_safety_checkerc                      t         S r   r   r   r   r   r   zFalImageGenSettings.<lambda>2   s    I r   formatreturnc                     i }| j                   | j                   |d<   | j                  |d<   | j                  |d<   | j                  |d<   | j                  |d<   | j
                  |d<   | j                  |d<   |S )zFBuild the Fal API arguments dict from settings, excluding None values.r   r!   r#   r%   r'   r)   r+   )r   r!   r#   r%   r'   r)   r+   )selfargss     r   to_api_argumentsz$FalImageGenSettings.to_api_arguments4   s~    !99 99DL&*&>&>"#!__\!__\ $ 2 2_(,(B(B$%Xr   )__name__
__module____qualname____doc__r   r   intr   __annotations__r!   r#   r%   strr   r'   boolr)   r+   r   r0   r   r   r   r   r      s     $)9J#KD#*y
 K+0AR+SyS"'8I"JJiJ38IZ3[Jd38n$y0[&+<M&NM4)#N.3DU.V4)+V#4EFFC)OF$sCx. r   r   c                        e Zd ZU dZeZeed<    G d de      Zeed<   dddddde	e   de
j                  d	e	e   d
e	e   de	e   f
 fdZdedeedf   fdZ xZS )FalImageGenServicezFal's image generation service.

    Provides text-to-image generation using Fal.ai's API with configurable
    parameters for image quality, safety, and format options.
    	_settingsc                       e Zd ZU dZdZee   ed<   dZeed<   dZ	eed<   dZ
eeeeef   f   ed	<   d
Zeed<   dZeed<   dZeed<   y)FalImageGenService.InputParamsa  Input parameters for Fal.ai image generation.

        .. deprecated:: 0.0.105
            Use ``settings=FalImageGenSettings(...)`` instead.

        Parameters:
            seed: Random seed for reproducible generation. If None, uses random seed.
            num_inference_steps: Number of inference steps for generation. Defaults to 8.
            num_images: Number of images to generate. Defaults to 1.
            image_size: Image dimensions as string preset or dict with width/height. Defaults to "square_hd".
            expand_prompt: Whether to automatically expand/enhance the prompt. Defaults to False.
            enable_safety_checker: Whether to enable content safety filtering. Defaults to True.
            format: Output image format. Defaults to "png".
        Nr      r!      r#   	square_hdr%   Fr'   Tr)   pngr+   )r1   r2   r3   r4   r   r   r5   r6   r!   r#   r%   r	   r7   r   r'   r8   r)   r+   r   r   r   InputParamsr=   L   sg    	 #hsm"#$S$
C1<
E#tCH~-.<#t#&*t*r   rB   N)paramsmodelkeysettingsrC   aiohttp_sessionrD   rE   rF   c          
      6   t        dddddddd	      }|t        d
t         d
       ||_        |t        dt                |sw|j                  |_        |j                  |_        |j
                  |_        |j                  |_        |j                  |_        |j                  |_        |j                  |_	        ||j                  |       t        | 0  dd|i| || _        |xs t        j                  dd      | _        |r|t        j"                  d<   yy)aZ  Initialize the FalImageGenService.

        Args:
            params: Input parameters for image generation configuration.

                .. deprecated:: 0.0.105
                    Use ``settings=FalImageGenSettings(...)`` instead.

            aiohttp_session: HTTP client session for downloading generated images.
            model: The Fal.ai model to use for generation. Defaults to "fal-ai/fast-sdxl".

                .. deprecated:: 0.0.105
                    Use ``settings=FalImageGenSettings(model=...)`` instead.

            key: Optional API key for Fal.ai. If provided, sets FAL_KEY environment variable.
            settings: Runtime-updatable settings. When provided alongside deprecated
                parameters, ``settings`` values take precedence.
            **kwargs: Additional arguments passed to parent ImageGenService.
        zfal-ai/fast-sdxlNr>   r?   r@   FTrA   )rD   r   r!   r#   r%   r'   r)   r+   rD   rC   rF   FAL_KEY r   )r   r   rD   r   r!   r#   r%   r'   r)   r+   apply_updatesuper__init___aiohttp_sessionosgetenv_api_keyenviron)	r.   rC   rG   rD   rE   rF   kwargsdefault_settings	__class__s	           r   rM   zFalImageGenService.__init__f   s    < /$ !""&	
 "7,?I%*""8-@A(. %7=7Q7Q 4.4.?.? +.4.?.? +171E1E .9?9U9U 6*0-- ' ))(3="2=f= /7ryyB7$'BJJy! r   promptr,   c                  K   dt         fd}t        j                  d|        d| j                   dd}d|i| j                  j                         }| j                  j                  d| j                  j                   ||	      4 d
{   }|j                  dk7  rI|j                          d
{   }t        d|j                   d|        	 d
d
d
      d
{    y
|j                          d
{   }d
d
d
      d
{    r|d   d   d   nd
}|st        d       y
t        j                  d|        t        j                  d| d       | j                  j                  |      4 d
{   }t        j                  d|        |j                  j                          d
{   }	t!        j"                  ||	       d
{   \  }
}}t%        ||
||      }| d
d
d
      d
{    y
7 {7 W7 *7 7 # 1 d
{  7  sw Y   xY w7 7 r7 V7 0# 1 d
{  7  sw Y   y
xY ww)a  Generate an image from a text prompt.

        Args:
            prompt: The text prompt to generate an image from.

        Yields:
            URLImageRawFrame: Frame containing the generated image data and metadata.
            ErrorFrame: If image generation fails.
        encoded_imagec                     t        j                  |       }t        j                  |      }|j	                         |j
                  |j                  fS r   )ioBytesIOr   opentobytessizer+   )rX   bufferimages      r   load_image_bytesz:FalImageGenService.run_image_gen.<locals>.load_image_bytes   s9    ZZ.FJJv&EMMOUZZ>>r   zGenerating image from prompt: zKey zapplication/json)AuthorizationzContent-TyperV   zhttps://fal.run/)jsonheadersN   zFal API error (z): )errorimagesr   urlzImage generation failedzImage generated at: zDownloading image z ...zDownloaded image )rh   r`   r^   r+   )bytesr
   debugrQ   r;   r0   rN   postrD   statustextr   rc   getcontentreadasyncio	to_threadr   )r.   rV   ra   rd   payloadresp
error_textresponse	image_urlrX   image_bytesr^   r+   frames                 r   run_image_genz FalImageGenService.run_image_gen   s<    	?E 	?
 	5fX>?  $DMM?3.
 VIt~~'F'F'HI((--t~~3345 . 
 		) 		) {{c!#'99;.
 S'UVV		) 		) 		) "YY[(H		) 		) 5=HX&q)%0$	677+I;78 	))D9:((,,Y7 	 	8LL,YK89"*"2"2"7"7"99M070A0ABRTa0b*b'[$$+DY_`EK	 	 	+		) /		) )		) 		) 		) 		)*	9*b	 	 	 	s   BIH	I#H5H6$HI%H&I+H>H?HIHA4IH.I6H6=H0>H6H2H68IH4IHIHIH+H!H+&	I0H62H64I6I<H?=II)r1   r2   r3   r4   r   Settingsr6   r   rB   r   aiohttpClientSessionr7   rM   r   r   rz   __classcell__)rU   s   @r   r:   r:   B   s     #H""i 0 #"
 )-#!26A( %A( !..	A(
 }A( c]A( ./A(F3# 3.2M 3r   r:   )!r4   rq   rZ   rO   dataclassesr   r   typingr   r   r   r   r	   r|   logurur
   PILr   pydanticr   pipecat.frames.framesr   r   r   pipecat.services.image_servicer   pipecat.services.settingsr   r   r   r   r   r:   r   r   r   <module>r      sd     	 	 ( = =     E E : d d !* ! !HZ Zr   