
    `gj                        d 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m	Z	m
Z
 ddlmZmZmZ  ej                  e      Z G d de      Zd	dZy)
u  FAL.ai image generation backend.

Wraps the 18-model FAL catalog (FLUX 2, Z-Image, Nano Banana, GPT
Image 1.5, Recraft, Imagen 4, Qwen, Ideogram, …) as an
:class:`ImageGenProvider` implementation.

The heavy lifting — model catalog, payload construction, request
submission, managed-Nous-gateway selection, Clarity Upscaler chaining
— lives in :mod:`tools.image_generation_tool`. This plugin reaches into
that module via call-time indirection (``import tools.image_generation_tool as _it``)
so:

* the existing test suite (``tests/tools/test_image_generation.py``,
  ``tests/tools/test_managed_media_gateways.py``) keeps patching
  ``image_tool._submit_fal_request`` / ``image_tool.fal_client`` /
  ``image_tool._managed_fal_client`` without modification, and
* there's exactly one canonical FAL code path on disk — the plugin is a
  registration adapter, not a parallel implementation.

See issue #26241 for the migration plan and the
``plugin-extraction-test-patch-compatibility.md`` rules this follows.
    )annotationsN)AnyDictListOptional)DEFAULT_ASPECT_RATIOImageGenProviderresolve_aspect_ratioc                      e Zd ZdZedd       Zedd       ZddZddZddZ	ddZ
ddZefd	d	d
	 	 	 	 	 	 	 	 	 	 	 ddZy	)FalImageGenProvidera  FAL.ai image generation backend.

    Delegates to ``tools.image_generation_tool.image_generate_tool`` so
    the in-tree FAL implementation (model catalog, payload builder,
    managed-gateway selection, Clarity Upscaler chaining) is the single
    source of truth. Everything is resolved at call time via the
    ``_it`` indirection so tests can monkey-patch the legacy module.
    c                     y)Nfal selfs    Q/root/.hermes/venv/lib/python3.12/site-packages/plugins/image_gen/fal/__init__.pynamezFalImageGenProvider.name2   s        c                     y)NFAL.air   r   s    r   display_namez FalImageGenProvider.display_name6   s    r   c                `    dd l m} 	 t        |j                               S # t        $ r Y yw xY w)Nr   F)tools.image_generation_toolimage_generation_toolboolcheck_fal_api_key	Exceptionr   _its     r   is_availablez FalImageGenProvider.is_available:   s2    
 	2	--/00 		s   ! 	--c                    dd l m} |j                  j                         D cg c]M  \  }}||j	                  d|      |j	                  dd      |j	                  dd      |j	                  dd      dO c}}S c c}}w )Nr   displayspeed 	strengthsprice)idr"   r#   r%   r&   )r   r   
FAL_MODELSitemsget)r   r   model_idmetas       r   list_modelszFalImageGenProvider.list_modelsE   sw    1 #&.."6"6"8	
 $ 88Ix8'2.!XXk26'2.	
 		
 	
s   AA:c                &    dd l m} |j                  S )Nr   )r   r   DEFAULT_MODELr   s     r   default_modelz!FalImageGenProvider.default_modelR   s    1   r   c                    dddddddgdS )	Nr   paidub   Pick from flux-2-klein, flux-2-pro, gpt-image, nano-banana, etc. — text-to-image & image editingFAL_KEYzFAL API keyzhttps://fal.ai/dashboard/keys)keyprompturl)r   badgetagenv_varsr   r   s    r   get_setup_schemaz$FalImageGenProvider.get_setup_schemaV   s*    w %+:	
 	
r   c                    dd l m} 	 |j                         \  }}|j	                  d      r#ddgt        |j	                  d      xs d      dS dgddS # t        $ r	 dgddcY S w xY w)Nr   text)
modalitiesmax_reference_imagesedit_endpointimager>      )r   r   _resolve_fal_modelr   r*   int)r   r   	_model_idr,   s       r   capabilitiesz FalImageGenProvider.capabilitiesd   s    
 	2	G!446OIt 88O$%w/(+DHH5K,L,QPQ(R   &hBB  	G#)(AFF	Gs   A A'&A'N)	image_urlreference_image_urlsc          	        ddl m} t        |      }dD ci c]  }||v r||   |||    }	}|||	d<   |||	d<   	  |j                  d||d|	}
	 t        |
t              rt        j                  |
      n|
}t        |t              sd
dddd}|j                  dd       |j                  d|       |j                  d|       d|vr	 |j                         \  }}||d<   |S |S c c}w # t        $ rB}t
        j                  d|d	       d
dd| t        |      j                  d||dcY d}~S d}~ww xY w# t        $ r	 d
ddd}Y w xY w# t        $ r Y |S w xY w)a  Generate or edit an image via the legacy FAL pipeline.

        Forwards prompt + aspect_ratio + image_url/reference_image_urls (and
        any forward-compat extras the schema supports) into
        :func:`tools.image_generation_tool.image_generate_tool`, then reshapes
        its JSON-string response into the provider-ABC dict format consumed by
        ``_dispatch_to_plugin_provider``.
        r   N)num_inference_stepsguidance_scale
num_imagesoutput_formatseedrF   rG   )r5   aspect_ratioz"FAL image_generate_tool raised: %sT)exc_infoFzFAL image generation failed: r   )successr@   error
error_typeproviderr5   rN   zInvalid JSON from FAL pipeline)rP   r@   rQ   z)FAL pipeline returned a non-dict responseprovider_contract)rP   r@   rQ   rR   rS   r5   rN   modelr   )r   r   r
   image_generate_toolr   loggerwarningtype__name__
isinstancestrjsonloadsdict
setdefaultrB   )r   r5   rN   rF   rG   kwargsr   aspectr4   passthroughrawexcresponser+   _metas                  r   generatezFalImageGenProvider.generatev   s   " 	2%l3

 f}!8 

 

  '0K$+2FK./	)#)) # C"	d*4S#*>tzz#CH (D) D1	H 	J.Hf-NF3 (""%"8"8":%$,! x

2  
	NN?tNT 8>"3i00!  & 
	  	d#(4BbcH	d,  sF   C(C- 'D; E -	D867D3-D83D8;EE	EE)returnr\   )ri   r   )ri   zList[Dict[str, Any]])ri   Optional[str])ri   Dict[str, Any])r5   r\   rN   r\   rF   rj   rG   zOptional[List[str]]ra   r   ri   rk   )rZ   
__module____qualname____doc__propertyr   r   r    r-   r0   r:   rE   r   rh   r   r   r   r   r   (   s        	
!
C* 1S
 $(48SS S
 !S 2S S 
Sr   r   c                6    | j                  t                      y)uF   Plugin entry point — wire ``FalImageGenProvider`` into the registry.N)register_image_gen_providerr   )ctxs    r   registerrs      s    ##$7$9:r   )ri   None)rn   
__future__r   r]   loggingostypingr   r   r   r   agent.image_gen_providerr   r	   r
   	getLoggerrZ   rW   r   rs   r   r   r   <module>r{      sQ   . #   	 , ,  
		8	$a* aR;r   