
    g5j                        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dS )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dS )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.
    returnstrc                    dS )Nfal selfs    D/home/rurouni/.hermes/hermes-agent/plugins/image_gen/fal/__init__.pynamezFalImageGenProvider.name2   s    u    c                    dS )NFAL.air   r   s    r   display_namez FalImageGenProvider.display_name6   s    xr   boolc                t    dd l m} 	 t          |                                          S # t          $ r Y dS w xY w)Nr   F)tools.image_generation_toolimage_generation_toolr   check_fal_api_key	Exceptionr   _its     r   is_availablez FalImageGenProvider.is_available:   sW    
 	211111	--//000 	 	 	55	s    ) 
77List[Dict[str, Any]]c                T    dd l m} d |j                                        D             S )Nr   c           
         g | ]]\  }}||                     d |          |                     dd          |                     dd          |                     dd          d^S )displayspeed 	strengthsprice)idr&   r'   r)   r*   )get).0model_idmetas      r   
<listcomp>z3FalImageGenProvider.list_models.<locals>.<listcomp>G   s|     	
 	
 	
 $ 88Ix88'2..!XXk266'2.. 	
 	
 	
r   )r   r   
FAL_MODELSitemsr    s     r   list_modelszFalImageGenProvider.list_modelsE   sE    111111	
 	
 #&."6"6"8"8	
 	
 	
 		
r   Optional[str]c                    dd l m} |j        S )Nr   )r   r   DEFAULT_MODELr    s     r   default_modelz!FalImageGenProvider.default_modelR   s    111111  r   Dict[str, Any]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   s4    w %+: 	
 
 	
r   c                    dd l m} 	 |                                \  }}n# t          $ r	 dgddcY S w xY w|                    d          r)ddgt          |                    d          pd          dS dgddS )Nr   text)
modalitiesmax_reference_imagesedit_endpointimagerF      )r   r   _resolve_fal_modelr   r,   int)r   r!   	_model_idr/   s       r   capabilitiesz FalImageGenProvider.capabilitiesd   s    
 	211111	G!4466OItt 	G 	G 	G#)(AFFFFF	G88O$$ 	%w/(+DHH5K,L,L,QPQ(R(R    &hBBBs     33N)	image_urlreference_image_urlsr=   aspect_ratiorN   rO   Optional[List[str]]kwargsr   c          	        ddl m} t          |          }fddD             }|||d<   |||d<   	  |j        d||d|}	nS# t          $ rF}
t
                              d|
d	
           ddd|
 t          |
          j        d||dcY d}
~
S d}
~
ww xY w	 t          |	t                    rt          j        |	          n|	}n# t          $ r	 dddd}Y nw xY wt          |t                    sddddd}|                    dd           |                    d|           |                    d|           d|vr.	 |                                \  }}||d<   n# t          $ r Y nw xY w|S )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   Nc                :    i | ]}|v |         ||         S )Nr   )r-   r<   rR   s     r   
<dictcomp>z0FalImageGenProvider.generate.<locals>.<dictcomp>   s?     

 

 

 f}}!8  "9!8!8r   )num_inference_stepsguidance_scale
num_imagesoutput_formatseedrN   rO   )r=   rP   z"FAL image_generate_tool raised: %sT)exc_infoFzFAL image generation failed: r   )successrH   error
error_typeproviderr=   rP   zInvalid JSON from FAL pipeline)r\   rH   r]   z)FAL pipeline returned a non-dict responseprovider_contract)r\   rH   r]   r^   r_   r=   rP   modelr   )r   r   r
   image_generate_toolr   loggerwarningtype__name__
isinstancer   jsonloadsdict
setdefaultrJ   )r   r=   rP   rN   rO   rR   r!   aspectpassthroughrawexcresponser.   _metas        `        r   generatezFalImageGenProvider.generatev   sR   " 	211111%l33

 

 

 



 

 

  '0K$+2FK./	)#) #   CC
  
	 
	 
	NN?tNTTT >>>"3ii0!  &       
		d*4S#*>*>Gtz#CHH 	d 	d 	d#(4BbccHHH	d (D)) 	 D1	 H 	J...Hf---NF333 ("""%"8"8":":%$,!!   sA   A 
B;B
BB+C CC>E 
E('E()r   r   )r   r   )r   r#   )r   r4   )r   r8   )r=   r   rP   r   rN   r4   rO   rQ   rR   r   r   r8   )rf   
__module____qualname____doc__propertyr   r   r"   r3   r7   rB   rM   r   rr   r   r   r   r   r   (   s             X    X	 	 	 	
 
 
 
! ! ! !
 
 
 
C C C C* 1S
 $(48S S S S S S S Sr   r   r   Nonec                H    |                      t                                 dS )uF   Plugin entry point — wire ``FalImageGenProvider`` into the registry.N)register_image_gen_providerr   )ctxs    r   registerr{      s#    ##$7$9$9:::::r   )r   rw   )ru   
__future__r   rh   loggingostypingr   r   r   r   agent.image_gen_providerr   r	   r
   	getLoggerrf   rc   r   r{   r   r   r   <module>r      s    . # " " " " "   				 , , , , , , , , , , , ,          
	8	$	$a a a a a* a a aR; ; ; ; ; ;r   