
    Bi9                        d Z ddlZddlZddlmZmZ ddlmZ ddlmZm	Z	m
Z
 ddlmZmZ ddlmZmZmZ dd	lmZmZ dd
lmZ  ej.                  e      Z G d d      Z	 	 	 ddede	e   de	e   de	e   de
eee   f   f
dZy)z
Core visual generation logic for Napkin AI API.

Provides high-level interface for generating visuals through the API,
handling the complete workflow from request to downloaded files.
    N)datetimetimezone)Path)ListOptionalTuple   )NapkinAPIClientProcessingError)VisualRequestStatusResponseOutputFormat)Settingsget_settings)get_style_by_namec            (       .   e Zd ZdZd"dee   fdZd Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 d#de	dee	   d	ee	   d
ee	   dee
   dee	   dee	   dededee
   dee
   dee	   dee	   dee   dee   def dZ	 d$de	de	d	e	de
de	f
dZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d%de	dee   dee	   d	ee	   d
ee	   dee
   dee	   dee	   dededee
   dee
   dedee	   dee	   dee   dee   deeee   f   f$dZ	 	 	 	 d&dee	   dee   dee	   d	ee	   d ee
   deee	eee   f      fd!Zy)'VisualGeneratorz+High-level interface for visual generation.Nsettingsc                 8    |xs
 t               | _        d| _        y)z
        Initialize visual generator.

        Args:
            settings: Configuration settings. If None, loads from environment.
        N)r   r   client)selfr   s     1/var/www/html/Napkin-AI-API/src/core/generator.py__init__zVisualGenerator.__init__   s     !2LN15    c                    K   t        | j                        | _        | j                  j                          d{    | S 7 w)zAsync context manager entry.N)r
   r   r   
__aenter__)r   s    r   r   zVisualGenerator.__aenter__$   s6     %dmm4kk$$&&& 	's   8AAAc                 t   K   | j                   r&| j                   j                  |||       d{    yy7 w)zAsync context manager exit.N)r   	__aexit__)r   exc_typeexc_valexc_tbs       r   r   zVisualGenerator.__aexit__*   s1     ;;++'''6BBB Bs   -868contentstyleformatlanguage
variationscontext_beforecontext_aftertransparentinvertedwidthheight	visual_idvisual_querytransparent_backgroundinverted_colorreturnc                 N   |xs | j                   j                  }|xs | j                   j                  }|xs | j                   j                  }	 t	        |j                               }d}|r	 t        |      }|j                  }n,	 t        | j                   j                        }|j                  }t        |||||||||n|||n|	|
|||      S # t        $ r t        j                  }Y w xY w# t        $ r |}Y Lw xY w# t        $ r | j                   j                  }Y qw xY w)az  
        Prepare visual request with defaults.

        Args:
            content: Text content to visualize.
            style: Style name or ID.
            format: Output format (svg/png).
            language: Language code.
            variations: Number of variations (1-4).
            context_before: Context before content.
            context_after: Context after content.
            transparent: Enable transparent background.
            inverted: Invert colors.
            width: Width in pixels (PNG only).
            height: Height in pixels (PNG only).

        Returns:
            Prepared VisualRequest.
        N)r"   r$   style_idr%   number_of_visualsr'   r(   r/   r0   r+   r,   r-   r.   )r   default_formatdefault_languagedefault_variationsr   lower
ValueErrorSVGr   iddefault_styler   )r   r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   
format_strformat_enumr3   	style_objs                       r   _prepare_requestz VisualGenerator._prepare_request/   s5   L ;t}};;
=t}}==C4==#C#C
	+&z'7'7'9:K
 !-e4	$<<7-dmm.I.IJ	$<<
 ()'%1 $:-;-G>X%
 	
-  	+&**K	+  ! !  7==667s6   C .C1 +D C.-C.1C?>C?D$#D$
request_idfile_idindexc                     t        j                  t        j                        j	                  d      }|dkD  rd| d|dd  d|dz    d	| S d| d|dd  d	| S )
a  
        Generate filename for saved visual.

        Args:
            request_id: Request ID.
            file_id: File ID.
            format: File format.
            index: File index for multiple variations.

        Returns:
            Generated filename.
        z%Y%m%d_%H%M%Sr   napkin__N   _v   .)r   nowr   utcstrftime)r   rA   rB   r$   rC   	timestamps         r   _generate_filenamez"VisualGenerator._generate_filename   sr    ( LL.77H	19YKqBQ(8519+QvhOO1Z^$4AfX>>r   
output_dir
save_filesc                   !K   | j                   st        d      | j                  ||||||||	|
||||||      !t        j	                  d!j
                   d!j                   d       | j                   j                  !       d{   }|j                  }t        j	                  d|        | j                   j                  |       d{   }|j                  j                  dk7  rt        d	|j                  xs d
       t        j	                  d|j                   d       g }|rO|j                  dkD  r?|xs | j                  j                   }t#        |      }|j%                  dd       t'        |dg       xs g }dt(        t*           dt(        t*           dt*        f!fd}|r1t-        |      D ]  \  }}|j/                  dd|dz          }|j/                  d      } ||j/                  d      |      }|j/                  d      xs | j1                  ||||      }||z  }	 |r\| j                   j3                  |       d{   }|j5                  |       |j7                  |       t        j	                  d|       nL| j                   j9                  |||       d{    |j7                  |       t        j	                  d|       ! ||fS t=        |j                        D ]  }d|dz    }| j1                  ||!j                  j                  |      }||z  }	 | j                   j9                  |||       d{    |j7                  |       t        j	                  d|        ||fS 7 7 7 77 # t:        $ r"} t        j                  d||        Y d} ~ d} ~ ww xY w7 j# t:        $ r!} t        j                  d||        Y d} ~ d} ~ ww xY ww)a\  
        Generate visuals from text content.

        Args:
            content: Text content to visualize.
            output_dir: Directory to save files (uses config default if None).
            style: Style name or ID.
            format: Output format (svg/png).
            language: Language code.
            variations: Number of variations (1-4).
            context_before: Context before content.
            context_after: Context after content.
            transparent: Enable transparent background.
            inverted: Invert colors.
            width: Width in pixels (PNG only).
            height: Height in pixels (PNG only).
            save_files: Whether to save files to disk.

        Returns:
            Tuple of (final status, list of saved file paths).

        Raises:
            ProcessingError: If generation fails.
        z/Generator must be used as async context manager)r"   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   zGenerating z visual(s) in z formatNzRequest created: 	completedzGeneration failed: zUnknown errorzGeneration completed: z file(s) readyr   T)parentsexist_okfilesfmturlr1   c                     | dv r| S |r8d|j                         v sd|j                         v ryd|j                         v ryt        d      rj                  j                  S dS )N>   pngsvgz.svgz	image/svgr[   z.pngrZ   r$   )r8   hasattrr$   value)rW   rX   requests     r   
_infer_extz,VisualGenerator.generate.<locals>._infer_ext   s`    .(J,syy{0J$,$/6w/Iw~~++TuTr   r;   file_rI   r$   filenamez	Saved: %szFailed to download file %s: %s)r   RuntimeErrorr@   loggerinfor4   r$   create_visualrA   wait_for_completionstatusr]   r   errorfiles_readyr   storage_pathr   mkdirgetattrr   str	enumerategetrO   download_file_by_urlwrite_bytesappenddownload_file	Exceptionrange)"r   r"   rP   r#   r$   r%   r&   r'   r(   r)   r*   r+   r,   rQ   r-   r.   r/   r0   responserA   final_statussaved_pathsrV   r_   i	file_inforB   file_urlfile_fmtra   	file_pathfile_contenter^   s"                                    @r   generatezVisualGenerator.generate   s    X {{PQQ ''!)'#%#9) ( 
& 	'334N7>>BRRYZ	

 227;;((
'
|45 "[[<<ZHH$$3!%l&8&8&KO%LM  	,\-E-E,FnUV ,22Q6#At}}'A'AJj)JTD9 L'26<"E	U 	UHSM 	Uc 	U $-e$4LAy'mmDE!a%/BG(}}U3H))--*A8LH  )}}Z8  D<S<S"GXq=H !+X 5IS#151Q1Q (2 ,L &11,?'..y9"KKY? #'++";"; * ' )#  
 (..y9"KKY?; %5f [((# |778A %a!eWoG#66"GW^^-A-A1 H !+X 5I	S"kk77&#%  
 $**95K; 9" [((q < I\, % S%EwPQRRS % S%EwPQRRSs   BO-	N
AO-NE"O-4 NNAN2N3+NAO-3 O N>+O ?O-O-NN	N;N60O-6N;;O->O  	O*	O% O-%O**O-contentsconcurrent_limitc                    K   |xs  j                   j                  }t        j                  |      dt        dt
        f fd}t        |      D 	cg c]  \  }}	 ||	|       }
}}	t        j                  |
  d{   }t        d |D              }t        j                  d| dt        |       d       |S c c}	}w 7 Cw)	a  
        Generate visuals for multiple contents in batch.

        Args:
            contents: List of text contents.
            output_dir: Directory to save files.
            style: Style name or ID.
            format: Output format.
            concurrent_limit: Max concurrent requests.
            **kwargs: Additional generation parameters.

        Returns:
            List of tuples (content, status, file_paths) for each generation.
        r"   rC   c           	        K   
4 d{    	 d}rd|dz   dz  } 	j                   d| |d d{   \  }}| ||fcddd      d{    S 7 M7 7 	# t        $ r?}t        j                  d|dz    d|        | dg fcY d}~cddd      d{  7   S d}~ww xY w# 1 d{  7  sw Y   yxY ww)	z%Generate visual for one content item.Nbatch_rI   03dr"   rP   r#   r$   z#Failed to generate visual for item z:  )r   rt   rc   rh   )r"   rC   item_dirrg   pathsr   r$   kwargsrP   r   	semaphorer#   s         r   generate_onez4VisualGenerator.generate_batch.<locals>.generate_one[  s      y-#H!#-&30H#H*7$-- + '#+#%	+
 !+ %MFE #FE1 !yy% ! ! -LL#FuqykQSTUSV!WX"D",,# !yy- !yys   B>AB>B)*AAAB>AB>AB>	B&'"B!	B&
B)B>BB>!B&&B))B;/B20B;7B>Nc              3   .   K   | ]  \  }}}|s
d   yw)rI   Nr   ).0rF   rg   s      r   	<genexpr>z1VisualGenerator.generate_batch.<locals>.<genexpr>v  s     Aw|q&!&ws   zBatch generation completed: /z successful)r   batch_concurrent_limitasyncio	Semaphorerm   intrn   gathersumrc   rd   len)r   r   rP   r#   r$   r   r   r   ry   r"   tasksresults
successfulr   s   ` ``` `      @r   generate_batchzVisualGenerator.generate_batch?  s     . ,St}}/S/S %%&67		- 	-C 	- 	-, =Fh<OP<Ojagq)<OP.. AwAA
*:,aHkR	
  Q.s   ACC0CC	AC)N)NNNNNNFFNNNNNN)r   )NNNNNNNFFNNTNNNN)NNNN)__name__
__module____qualname____doc__r   r   r   r   r   rm   r   boolr   r@   rO   r   r   r   r   r   r   r   r   r   r   r      s!   56(!3 6C  $ $"&$((,'+!# $#'&*15)-!S
S
 }S
 	S

 3-S
 SMS
 !S
  }S
 S
 S
 }S
 S
 C=S
 smS
 !)S
  !!S
" 
#S
t ?? ? 	?
 ? 
?8 &*# $"&$((,'+!# $#'&*15)-%`)`) TN`) }	`)
 `) 3-`) SM`) !`)  }`) `) `) }`) `) `) C=`)  sm!`)" !)#`)$ !%`)& 
~tDz)	*'`)J &*# $*.<s)< TN< }	<
 < #3-< 
eCd34	5<r   r   r"   rP   r#   r$   r1   c           	         K   t               4 d{   } |j                  d| |||d| d{   cddd      d{    S 7 47 7 	# 1 d{  7  sw Y   yxY ww)aA  
    Convenience function to generate a visual.

    Args:
        content: Text content to visualize.
        output_dir: Directory to save files.
        style: Style name or ID.
        format: Output format.
        **kwargs: Additional generation parameters.

    Returns:
        Tuple of (status, file_paths).
    Nr   r   )r   r   )r"   rP   r#   r$   r   	generators         r   generate_visualr   ~  sd     (   I'Y'' 
!	

 
 
 !  
 !   sS   A!AA!AAAA! A
A!A
A!AAAA!)NNN)r   r   loggingr   r   pathlibr   typingr   r   r   
api.clientr
   r   
api.modelsr   r   r   utils.configr   r   utils.constantsr   	getLoggerr   rc   r   rm   r   r   r   r   <module>r      s      '  ( ( 9 D D 1 / 
		8	$d dR "& 	


 C=
 SM	
 >4:%&
r   