
    opjJ                        d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	m
Z
 ddlmZmZmZmZ  ej                   e      ZddZ	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZddZdd	Zdd
Z	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZy)u   Background image generation for Abacus AI provider.

Allows running image generation asynchronously — the caller receives a
``job_id`` immediately and can poll for the result later.
    )annotationsN)Path)AnyDictListOptionalc            	         	 ddl m}   |        dz  dz  S # t        $ rO t        t        j
                  j                  dt        j                  j                  d                  dz  dz  cY S w xY w)z:Return the directory where background job state is stored.r   get_hermes_homecacheabacus_ai_jobsHERMES_HOMEz	~/.hermes)	hermes_constantsr   ImportErrorr   osenvirongetpath
expanduserr
   s    7/root/.hermes/plugins/image_gen/abacus_ai/background.py	_jobs_dirr      se    q4 7*-=== qBJJNN="''2D2D[2QRSV]]`pppqs    AA-,A-c                    ddl m}  |       }	t        |      }
|r||
d<   |r||
d<   |r||
d<   |||
d<   |||
d<    |	j                  d	| |d|
S )
zRun a single image generation synchronously and return the result dict.

    This is the worker that background threads call. It imports the provider
    lazily to avoid circular imports at module level.
       )AbacusAIImageProvidermodelquality
resolution
num_imagesrewrite_prompt)promptaspect_ratio )providerr   dictgenerate)r    r!   r   r   r   r   r   kwargsr   r#   
gen_kwargss              r   _image_generate_syncr(      s      0$&H "&fJ#
7 '
9#-
< #-
< !'5
#$8 !      c                   t               }|| z  }|dz  }|dz  }t        || dd       	 |j                  d      }t        |t              r	t        |      dkD  rg }|D ]  }t        |t              rt        |j                  dd      |j                  d	|j                  d	d
            |j                  d      |j                  d      |j                  d            }	|j                  |	       |j                  ddd        t        d |D              rdnd}
t        || |
t        |      t        d |D              d       t        |d|i       yt        |j                  dd      |j                  d	d
      |j                  d      |j                  d      |j                  d      |j                  d      |j                  d            }	|	j                  d      rdnd}t        || ||	j                  dd      d       t        ||	       y# t        $ r:}t        j                  d| |       t        || dt        |      d       Y d}~yd}~ww xY w) z2Run a background job and write the result to disk.status.jsonresult.jsonrunning)job_idstatusjobsr   r     r!   squarer   r   r   )r    r!   r   r   r   FzInvalid job specsuccesserrorc              3  >   K   | ]  }|j                  d         yw)r4   Nr   .0rs     r   	<genexpr>z_run_job.<locals>.<genexpr>g   s      ,%&i ,s   	completedfailedc              3  D   K   | ]  }|j                  d       sd  yw)r4   r   Nr7   r8   s     r   r;   z_run_job.<locals>.<genexpr>n   s      HqquuY7G Hs     )r.   r/   totalr<   resultsr   r   )r    r!   r   r   r   r   r   r4   )r.   r/   r4   zBackground job %s failed: %s)r.   r/   r5   N)r   _write_statusr   
isinstancelistlenr$   r(   appendanysum_write_json	Exceptionloggerr5   str)r.   paramsjobs_dirjob_dirstatus_pathresult_path	jobs_listr@   job_specresult
status_msgr/   excs                r   _run_jobrV   F   sC   {HGM)KM)K +&IFG:JJv&	i&3y>A+=G% h-1'||Hb9%-\\*FJJ~x,P& 'll73 (Y 7#+<<#=F NN6*NN$)4FG" ), ,*1, )  + $W  HG HH	(  i%9: *zz(B/#ZZAjj)

9-!::l3!::l3%zz*:;F %+JJy$9[xF+  !::i7( 
 V, 3VSAkX$
 	 	s   D*H B>H 	I0IIc                    | j                   j                  dd       | j                  t        j                  |dt
              d       y)z%Write status JSON to disk atomically.Tparentsexist_ok   indentdefaultutf-8encodingNparentmkdir
write_textjsondumpsrK   r   datas     r   rA   rA      6    KKdT2OODJJtAs;gONr)   c                    | j                   j                  dd       | j                  t        j                  |dt
              d       y)z%Write result JSON to disk atomically.TrX   r[   r\   r_   r`   Nrb   rh   s     r   rH   rH      rj   r)   c                   | j                  d      xs dj                         }|s*| j                  d      st        j                  dddd      S t	        j
                         j                  dd	 }t        |       }t        j                  t        ||fd
d|       }|j                          t        j                  d
|ddd      S )a]  Start a background image generation job.

    Accepts the same parameters as ``image_generate`` plus an optional
    ``jobs`` array for batch generation. Returns immediately with a
    ``job_id``. Use ``image_generate_background_status`` to poll for
    completion.

    Parameters in ``args``:
        prompt (str): The image description.
        aspect_ratio (str, optional): ``square``, ``landscape``, or
            ``portrait``. Default ``square``.
        model (str, optional): Model ID override.
        quality (str, optional): ``low``, ``medium``, ``high``.
        resolution (str, optional): ``1080p``, ``2K``, ``4K``.
        num_images (int, optional): 1-4 images.
        rewrite_prompt (bool, optional): Auto-improve prompt.
        jobs (list, optional): Batch of job specs, each with its own
            ``prompt`` and optional overrides.
    r    r1   r0   FzPrompt is requiredbackground_job_creation)r4   r5   purposeN   Tzabacus-ai-bg-)targetargsdaemonnamequeued)r4   r.   r/   rn   )r   striprf   rg   uuiduuid4hexr$   	threadingThreadrV   start)rq   r&   r    r.   rL   threads         r   !image_generate_background_handlerr}      s    , hhx &B--/F$((6*zz)0
  	 ZZ\cr"F $ZFfVH%	F LLN::,	  r)   c                ~   | j                  d      xs dj                         }|st        j                  ddd      S t	               |z  }|dz  }|dz  }|j                         st        j                  dd| d	d      S 	 t        j                  |j                  d
            }d}|j                         r%t        j                  |j                  d
            }t        j                  d||j                  dd      |d      S # t        $ r+}t        j                  dt        |      d      cY d}~S d}~ww xY w)zCheck the status of a background image generation job.

    Parameters in ``args``:
        job_id (str): The job ID returned by
            ``image_generate_background``.
    r.   r1   Fzjob_id is requiredr3   r+   r,   zJob 'z' not foundr_   r`   NTr/   unknown)r4   r.   r/   rS   )
r   ru   rf   rg   r   existsloads	read_textrI   rK   )	rq   r&   r.   rN   rO   rP   r/   rS   rU   s	            r   (image_generate_background_status_handlerr      s?    hhx &B--/Fzz)
  	
 kF"GM)KM)KzzVHK0
  	
K1171CDZZ 5 5w 5 GHFzzjj95	
  	  zzX
  	s   BD 	D< D71D<7D<)returnr   )r2   NNNNN)r    rK   r!   rK   r   Optional[str]r   r   r   r   r   zOptional[int]r   zOptional[bool]r&   r   r   Dict[str, Any])r.   rK   rL   r   r   None)r   r   ri   r   r   r   )r   r   ri   r   r   r   )rq   r$   r&   r   r   rK   )__doc__
__future__r   rf   loggingr   ry   timerv   pathlibr   typingr   r   r   r   	getLogger__name__rJ   r   r(   rV   rA   rH   r}   r   r"   r)   r   <module>r      s    #   	     , ,			8	$q !! $ $%)%%% % 	%
 % % #% % %PDNOO/
///d)
)))r)   