
    
Ei:3                     8   d dl mZ d dlmZ d dlmZmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d dlmZ d d	lmZ d d
lm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mZm Z m!Z! d dl"m#Z# d dl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* d dl+m,Z, d dl-m.Z. d dl/m0Z0  ee1      Z2 G d d      Z3y)    )Path)Optional)HTTPExceptionstatus)run_in_threadpool)Session)setup_logger)ERR_UNEXPECTED)ProductTemplate)ProjectMaster)ProductImage)ProductTemplateRepository)ProjectRepository)ProductImageRepository)validate_overlay_filecreate_thumbnail_from_pathresize_image_to_sizesave_upload_file_streamedsafe_deleteapply_color_layer_to_image)generate_final_image_from_mask)ASSETS_ROOT	final_dirfinal_thumb_diroverlay_dirrel_pathabs_from_db)crop_transparent_canvas)normalize_white_background)colorize_preview_with_maskc                   d    e Zd ZdZe	 ddedededee   de	f
d       Z
ed	ed
ededz  fd       Zy)ProductImageServicez
    Handles generation and regeneration of final product images.
    Files are stored under per-project final_images directories.
    Nsession
project_idtemplate_unique_namecurrent_user_idreturnc           	        K   t        j                  | |      st        t        j                  d      t        j                  | |      }|r|j                  rt        t        j                  d      |j                  st        t        j                  d      t        j                        xs t        j                        }t        |j                        xs t        |j                        }|j                  rt        |j                        nd}t        |      }|j                  dd       t!        |      }	|	j                  dd       	 t#        fdd	D              rj$                  nj&                  }
t)        t*        j,                  j&                  t/        |      t/        |      j0                         d{   }t        |      }	 t=        ||	      }d}j@                  }jB                  }|r'|r%	 tE        |      }tE        |      }tG        ||||      }dt        dz  dtH        t.           fd}tK        |j8                  j8                   ||       ||      |r ||      nd      }tM        jN                  | |      }|S 7 # t        $ r  t2        $ r= t4        j7                  d
j8                  |       t        t        j:                  d      w xY w# t2        $ r= t?        |       t4        j7                  d|       t        t        j:                  d      w xY w# t2        $ r$ t4        j7                  dj0                         Y 5w xY ww)z
        Generate final image(s) for a project using the given template.
        Resulting files are stored in:
            assets/projects/project_[id]/final_images/
        DB paths stored as 'assets/...' relative strings.
        zTemplate not found)status_codedetailProject not foundzProject has no overlay imageNTparentsexist_okc              3   :   K   | ]  }|j                   v   y wNunique_name).0wtpls     T/var/www/html/story-book/Story-Book-python-api/app/services/product_image_service.py	<genexpr>z;ProductImageService.generate_for_project.<locals>.<genexpr>U   s     8fWeRScoo9MWe   mugcupz=Failed to generate final image for template %s and project %szFailed to generate final imagez'Failed to create final thumbnail for %sz"Failed to generate final thumbnailr*   z-Failed to create product-resized image for %spr'   c                     t        |       S r0   r   r=   s    r6   _db_relz9ProductImageService.generate_for_project.<locals>._db_rel|   s    A;    )project_master_idproduct_template_idfinal_image_pathfinal_image_thumbnail_pathfinal_image_product_path)(r   get_by_unique_namer   r   HTTP_404_NOT_FOUNDr   get_project
is_deletedoverlay_image_pathHTTP_400_BAD_REQUESTr   	file_pathr   logo_image_pathr   mkdirr   anymain_black_mask_pathmain_white_mask_pathr   r   base_image_pathstrr2   	Exceptionlogger	exceptionidHTTP_500_INTERNAL_SERVER_ERRORr   r   widthheightintr   r   r   r   create)r#   r$   r%   r&   projecttpl_psd_absoverlay_abslogo_absout_final_dirout_final_thumb_dir
mask_imagefinal_path_str	final_absfinal_thumb_absproduct_resized_pathr[   r\   r4   hrA   product_imager5   s                        @r6   generate_for_projectz(ProductImageService.generate_for_project-   s     *C)U)UV]_s)tF,E,ENbcc ,=+H+HR\+]',,F,E,ENabb ))F,G,GPnoo "#--0GD4G!'"<"<=agF`F`Aa;B;R;R;w667X\ "*-D48-j9!!$!>	|588fWe8f5f11lo  mE  mEJ#4.##((K M"$ N (		t8DWXO 04		VcJK';I}VWYZ'[$
	td{ 	x} 	 %%jj #$Y/'.'?FZW-A%B`d
 /55g}Me  	 	|\^a^d^dfpqF,Q,QZz{{	|  	t	"F	R E ENrss		t  c  !PRURaRabcsp   EM!A3J J	J M!K( %M!$L1 (A,M!J AK%%M!(AL..M!1)MM!MM!dbproduct_image_idcolorc           	      v  K   	 t        |       | j                  t        |      }|r|j                  rt        t        j                  d      t        j                  | |j                        st        t        j                  d      t        j                  | |j                        }|r|j                  rt        t        j                  d      |j                   }t#        j$                        xs t'        j$                        }	 t)        |      j+                  dd       t-        |t)        |             d{   j/                         }	t1        |	       t3        |	d	       |j:                  rt#        |j:                        nd}
t=        |      }|j+                  dd       t?        |      }|j+                  dd       tA        fddD              rjB                  njD                  }	 tG        tH        jJ                  jD                  tM        |	      tM        |      jN                         d{   }t'        |      }d}	 jR                  rjT                  r|rtG        tV        t#        jR                        xs t'        jR                        t#        jT                        xs t'        jT                        ||       d{   }tG        tX        |t'        |             d{    tQ        t'        |             d}	 t[        ||      }d}j\                  }j^                  }|r'|r%	 ta        |      }ta        |      }tc        ||||      }dtd        tL           dtd        t&           fd} ||jf                        } ||jh                        } ||jj                        }dtd        t&           dtd        tL           fd}	  ||      |_3         ||      |_4        |r ||      nd|_5        | jm                  |       | jo                          | jq                  |       tQ        |       tQ        |       tQ        |       tQ        |	       dd|j                   |j                  |jf                  |jh                  |jj                  dS # t        $ r  t        t        j                  t
              w xY w7 # t        $ r2 t4        j7                  d
|       t        t        j8                  d      w xY w7 # t        $ r= tQ        |	       t4        j7                  d|       t        t        j8                  d      w xY w7 ~7 _# t        $ r_ tQ        |       tQ        |rt'        |      nd       tQ        |	       t4        j7                  d       t        t        j8                  d      w xY w# t        $ rH tQ        |       tQ        |	       t4        j7                  d|       t        t        j8                  d      w xY w# t        $ r t4        j7                  d       Y w xY w# t        $ rn | js                          tQ        |       tQ        |       tQ        |       tQ        |	       t4        j7                  d|       t        t        j8                  d      w xY ww)z
        Replace overlay (temporary), regenerate final image and derivatives,
        update DB atomically, and cleanup old files on success.
        r<   zImage record not foundzAssociated template not foundr+   Tr,   N)   rq   rq   )
target_rgbz3Failed to store temporary overlay for project_id=%sz'Failed to store temporary overlay imagec              3   :   K   | ]  }|j                   v   y wr0   r1   )r3   r4   templates     r6   r7   z>ProductImageService.regenerate_single_image.<locals>.<genexpr>   s      9l]kXY!x?S?S:S]kr8   r9   z8Failed to regenerate final image for product_image_id=%sz Failed to regenerate final imagez/Failed to apply color layer during regenerationzFailed to apply color layerz%Failed to create new thumbnail for %sz$Failed to regenerate final thumbnailz&Failed to create resized product imager=   r'   c                      | rt        |       S d S r0   )r   r@   s    r6   _abs_from_db_pathzFProductImageService.regenerate_single_image.<locals>._abs_from_db_path  s    %&;q>0D0rB   c                      | rt        |       S d S r0   r?   r@   s    r6   _relz9ProductImageService.regenerate_single_image.<locals>._rel  s    "#8A;--rB   z:Failed to update DB while regenerating product image id=%szFailed to update databasez$Final image regenerated successfully)successmessagern   rC   rE   rF   rG   ):r   rV   r   r   rM   r
   getr   rK   rI   r   	get_by_idrD   r   rJ   rC   rY   r   rN   r   r   rP   r   resolver   r   rW   rX   rZ   rO   r   r   rQ   rR   rS   r   r   rT   rU   r2   r   color_preview_pathcolor_white_mask_pathr    r   r   r[   r\   r]   r   r   rE   rF   rG   addcommitrefreshrollback)rm   rn   new_overlay_filero   current_userimg_rowr_   r$   r`   overlay_temp_absrb   rc   rd   re   new_final_path_strnew_final_abs
color_tempnew_thumb_absnew_product_absr[   r\   r4   rj   rv   old_final_absold_thumb_absold_prod_absrx   rt   s                               @r6   regenerate_single_imagez+ProductImageService.regenerate_single_image   s    	T!"23
 &&'78',, 9 9BZ[[ -66r7;V;VW 9 9Babb#//G4M4MN',, 9 9BUVVZZ
 "("4"45Qh>P>P9Q	y
#))$)F&?@PR]^hRi&j jssu#$45&'7OT <C;R;R;w667X\ "*-D48-j9!!$!>699l]k9l6lX22rz  sP  sP
	r'8.((--$%M"$$( " /0
	**x/M/MRW#4. ; ;<aXE`E`@a > >?g4HfHfCg!$ 
 (.!$  
 D,-!
	v6}FYZM VKJK"6}mUVXY"Z
	1# 	18D> 	1 *'*B*BC)'*L*LM()I)IJ	.HTN 	.x} 	.	k'+M':G$15m1DG.HWtO/D]aG,FF7OIIKJJw 	M"M"L! 	$% = '

!(!:!: ' 8 8*1*L*L(/(H(H
 	
e  	T ; ;NSS	T2 !k  	yRT^_ E ENwxx	y""  	r()WYij E ENpqq	r  	&JZ(DA()NO554 	  	v&()DmT E ENtuu		v  K  !IJK.  	kKKM&&(()Y[kl E ENijj	ks  Z9R C=Z94S S*S -BZ99AT  T	T Z9BU U!U 9U:U W !Z9 $X $A2Z9AX? 4A(Z9)SZ9S ;TZ9	T AUZ9U U A(WZ9AXZ9X<8Z9;X<<Z9?A7Z66Z9r0   )__name__
__module____qualname____doc__staticmethodr   r]   rU   r   r   rl   r    rB   r6   r"   r"   '   s    
 
 *.	ZZZ "Z "#	Z
 
Z Zx h
h
h
 Tz	h
 h
rB   r"   N)4pathlibr   typingr   fastapir   r   fastapi.concurrencyr   sqlmodelr   app.core.loggingr	   app.core.constantsr
   app.models.product_templater   app.models.project_masterr   app.models.product_imager   &app.repositories.product_template_repor   app.repositories.project_repor   #app.repositories.product_image_repor   app.utils.imager   r   r   r   r   r   "app.utils.generate_final_from_maskr   app.utils.pathsr   r   r   r   r   r   app.utils.image_cropr   app.utils.image_backgroundr   app.utils.colorizer    r   rW   r"   r   rB   r6   <module>r      sg      ) 1  ) - 7 3 1 L ; F  N  9 A 9	h	L
 L
rB   