o
    i!                     @   s   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 eG dd deZG dd deZdS )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	_NotGivenc                   @   s   e Zd ZU dZedd dZedB eB ed< edd dZ	eeB ed< ed	d dZ
eeB ed
< edd dZeeeef B eB ed< edd dZeeB ed< edd dZeeB ed< edd dZeeB ed< deeef fddZdS )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                   C      t S Nr    r   r   N/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/services/fal/image.py<lambda>,       zFalImageGenSettings.<lambda>)default_factoryNseedc                   C   r   r   r   r   r   r   r   r   -   r   num_inference_stepsc                   C   r   r   r   r   r   r   r   r   .   r   
num_imagesc                   C   r   r   r   r   r   r   r   r   /   r   
image_sizec                   C   r   r   r   r   r   r   r   r   0   r   expand_promptc                   C   r   r   r   r   r   r   r   r   1   r   enable_safety_checkerc                   C   r   r   r   r   r   r   r   r   2   r   formatreturnc                 C   sX   i }| j dur| 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.Nr   r   r   r   r    r!   r"   )r   r   r   r   r    r!   r"   )selfargsr   r   r   to_api_arguments4   s   







z$FalImageGenSettings.to_api_arguments)__name__
__module____qualname____doc__r   r   intr   __annotations__r   r   r   strr   r    boolr!   r"   r   r&   r   r   r   r   r      s   
 &r   c                       s   e Zd ZU dZeZeed< G d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dZdedeedf fddZ  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                   @   sz   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< dS )zFalImageGenService.InputParamsa  Input parameters for Fal.ai image generation.

        .. deprecated:: 0.0.105
            Use ``settings=FalImageGenService.Settings(...)`` 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"   )r'   r(   r)   r*   r   r   r+   r,   r   r   r   r   r-   r   r    r.   r!   r"   r   r   r   r   InputParamsL   s   
 r5   N)paramsmodelkeysettingsr6   aiohttp_sessionr7   r8   r9   c             
      s   | j ddddddddd	}|dur| d
d
 ||_|durA| d |sA|j|_|j|_|j|_|j|_|j|_|j|_|j	|_	|durJ|
| t jdd|i| || _|p_tdd| _|rj|tjd< dS dS )aj  Initialize the FalImageGenService.

        Args:
            params: Input parameters for image generation configuration.

                .. deprecated:: 0.0.105
                    Use ``settings=FalImageGenService.Settings(...)`` 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=FalImageGenService.Settings(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-sdxlNr1   r2   r3   FTr4   )r7   r   r   r   r   r    r!   r"   r7   r6   r9   FAL_KEY r   )Settings"_warn_init_param_moved_to_settingsr7   r   r   r   r   r    r!   r"   apply_updatesuper__init___aiohttp_sessionosgetenv_api_keyenviron)r$   r6   r:   r7   r8   r9   kwargsdefault_settings	__class__r   r   rA   f   s>   

zFalImageGenService.__init__promptr#   c              	   C  s  dt fdd}td|  d| j dd}d|i| j }| jjd	| jj ||d
4 I dH 7}|j	dkrZ|
 I dH }td|j	 d| dV  	 W d  I dH  dS | I dH }W d  I dH  n1 I dH sqw   Y  |r|d d d nd}|stdV  dS td|  td| d | j|4 I dH 3}td|  |j I dH }	t||	I dH \}
}}t||
||d}|V  W d  I dH  dS 1 I dH sw   Y  dS )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                 S   s&   t | }t|}| |j|jfS r   )ioBytesIOr
   opentobytessizer"   )rL   bufferimager   r   r   load_image_bytes   s   

z:FalImageGenService.run_image_gen.<locals>.load_image_byteszGenerating image from prompt: zKey zapplication/json)AuthorizationzContent-TyperK   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 )r[   rS   rQ   r"   )bytesr	   debugrE   r0   r&   rB   postr7   statustextr   rV   getcontentreadasyncio	to_threadr   )r$   rK   rT   rW   payloadresp
error_textresponse	image_urlrL   image_bytesrQ   r"   framer   r   r   run_image_gen   sB   

	(
.z FalImageGenService.run_image_gen)r'   r(   r)   r*   r   r=   r,   r   r5   r   aiohttpClientSessionr-   rA   r   r   rm   __classcell__r   r   rI   r   r/   B   s,   
 "Cr/   ) r*   rd   rM   rC   dataclassesr   r   typingr   r   r   r   r   rn   logurur	   PILr
   pydanticr   pipecat.frames.framesr   r   r   pipecat.services.image_servicer   pipecat.services.settingsr   r   r   r   r/   r   r   r   r   <module>   s    $