
    Qi!                        d Z ddlZddlZddlZddlmZ ej                  j                  dd       ddlZddl	Z	ddl
mZ  ed      Zedz  Zedz  Zed	z  Zed
z  ZdZdZdZdedefdZdededdfdZd Zedk(  r e        yy)u   컨셉 #04 v2 — 현실-판타지 경계 해체 하이브리드 이미지 생성 스크립트
폰트 규칙 전면 적용 버전 (brief-v2.md 기반)
    N)Pathz&/home/jay/workspace/tools/ai-image-gen)sync_playwrightzF/home/jay/workspace/output/meta-ads/concept-catalog/04-reality-fantasyzbg.jpgztemplate-v2.htmlzsample-v2.pngz04-reality-fantasy-v2.pngz0https://generativelanguage.googleapis.com/v1betaz3https://www.googleapis.com/auth/generative-languageu  A dark, moody office interior at night. A tired Korean office worker (30s, male) sits at a cluttered desk with papers and a laptop, dimly lit by the monitor glow. The room has gray walls, fluorescent lights mostly off, a coffee cup, and a stack of documents. The atmosphere is heavy and exhausted — blue-gray color tone, cinematic shallow depth of field. No text, no UI elements, no overlays. Photorealistic, ultra-high quality, 1:1 square format.tokenreturnc           
      <   t         j                         rt        dt                 t         S ddg}|D ]  }t        d|        d|  dd}d|v rt         d	| d
}dt        igdddd}nt         d	| d}ddt        igigdddgid}	 t        j                  |||d      }|j                  dv rt        d|j                   d       |j                          |j                         }d}d}	d|v r=|j                  dg       }
|
r|
d   }|j                  d       }|j                  d!d"      }	nc|j                  d#g       }|rO|d   j                  d$i       j                  dg       }|D ]%  }d%|v s|d%   d&   }|d%   j                  d!d      }	 n |st        d'       rt        j                  |      }d(|	v rd)nd*}t        d+| z  }|j                  |       t        d,| d-t        |      d.d/       |c S  t-        d5      # t
        j                   $ rG}t        d0|j"                  j                   d1|j"                  j$                  dd2         Y d}~-d}~wt&        $ r/}t        d3t)        |      j*                   d4|        Y d}~cd}~ww xY w)6u{   Gemini API로 배경 이미지를 생성하고 저장합니다.
    기존 bg.jpg가 있으면 재사용 (API 절약).
    u"   [배경] 기존 bg.jpg 재사용: z)gemini-2.0-flash-preview-image-generationzimagen-3.0-generate-002u   [배경] 모델 시도: zBearer zapplication/json)AuthorizationzContent-Typeimagenz/models/z:predictprompt   z1:1)sampleCountaspectRatio)	instances
parametersz:generateContentpartstextresponseModalitiesIMAGETEXT)contentsgenerationConfigx   )headersjsontimeout)i  i  u     → HTTP u   , 다음 모델 시도...Nz
image/jpegpredictionsr   bytesBase64EncodedmimeTypez	image/png
candidatescontent
inlineDatadatau9     → 이미지 데이터 없음, 다음 모델 시도...pngz.pngz.jpgbgu   [배경] 저장 완료:  (,z bytes)u     → HTTP 오류: z -    u     → 오류: z: u/   모든 Gemini 모델에서 배경 생성 실패)BG_PATHexistsprintGEMINI_API_BASE	BG_PROMPTrequestspoststatus_coderaise_for_statusr   getbase64	b64decode
OUTPUT_DIRwrite_byteslen	HTTPErrorresponser   	Exceptiontype__name__RuntimeError)r   model_ordermodel_idr   urlpayloadrespr!   	image_b64	mime_typer   predr   r   partimage_bytesext	save_pathes                      o/home/jay/workspace/.worktrees/task-2117-dev1/output/meta-ads/concept-catalog/04-reality-fantasy/generate-v2.pygenerate_backgroundrJ   %   s    ~~27)<= 	4!K   ?(
34&ug..

 x$%XhZx@C'34./FG
 %%XhZ7GHC%(;'<=>%9GV;L$MG
+	==gGSQD:-D$4$4#55NOP!!#99;DI$I8#"hh}b9&q>D $)= >I $[ AI!XXlB7
&qM--i<@@"ME % "'4/(,\(:6(BI(,\(:(>(>z<(XI!	" QS **95K!Y.&FC"r#Z/I!!+.,YKr#k:J19MWUVq?B H
II !! 	'

(>(>'?s1::??SWTWCXBYZ[ 	N47#3#3"4Bqc:;	s9   A HB'H6-H%AHJ<I  J,$JJbg_pathoutput_pathc                    t         j                         st        dt                t        dt                 dt         j	                          }d| j	                          }t               5 }|j                  j                         }	 |j                  ddd      }|j                  |d       |j                  d	| d
| d       |j                  d       |j                  j                  dd       |j                  t        |      d       t        d|        |j!                          	 ddd       y# |j!                          w xY w# 1 sw Y   yxY w)uQ   Playwright로 HTML 템플릿을 캡처하여 최종 이미지를 저장합니다.u   템플릿 파일 없음: u   [HTML] 캡처 시작: zfile://i8  )widthheight)viewportnetworkidle)
wait_untilz0() => {
                window.BG_IMAGE_PATH = "z";
                const bgEl = document.getElementById('bg');
                if (bgEl) {
                    bgEl.style.setProperty('--bg-url', 'url("z%")');
                }
            }i	  T)parentsexist_okr"   )pathr9   u   [HTML] 캡처 완료: N)TEMPLATE_PATHr(   FileNotFoundErrorr)   resolver   chromiumlaunchnew_pagegotoevaluatewait_for_timeoutparentmkdir
screenshotstrclose)rK   rL   template_urlbg_file_urlpbrowserpages          rI   capture_htmlri   u   sP   !";M? KLL	"=/
23]22456LGOO-./K		 a**##%	##tt-L#MDIIl}I= MM ))4 6> ?J] K	  !!$'$$TD$AOO[!1O>*;-89MMO- , MMO- s%   -E	BD;!E;EEEc                     t        d       t        d       t        d       t        d       t        d       t        j                  t              } t        dt	        |        d       t        d       t        |       }t        d       t        |t               t        d	       t        j                  t        t               t        d
t                t        d       t        d       t        d       g d}|D ]&  \  }}}}|rdnd}t        d| d|dd|dd|        ( t        j                         j                  dz  }t        j                         j                  dz  }	t        d       t        d|        t        dt                t        dt         d|dd       t        dt         d|	dd       t        d       y )Nz<============================================================u:   컨셉 #04 v2 현실-판타지 경계 해체 생성 시작u6   폰트 규칙: 핵심 88px / 서브 64px / 최소 40pxu!   
[인증] SA 토큰 획득 중...u'   [인증] 토큰 획득 성공 (길이: z chars)u%   
[1단계] 배경 이미지 준비...u8   
[2단계] HTML 오버레이 캡처 → sample-v2.png...u2   
[3단계] 복사 → 04-reality-fantasy-v2.png...u	   [복사] z=
============================================================u+   폰트 규칙 최종 검증 체크리스트)	)zmain-headline88pxu   ≥84pxT)zsub-copy64px   ≥64pxT)zevent-reward72pxrm   T)zevent-label40px   ≥40pxT)zlv-badge48pxrp   T)zcta-btn44pxrp   T)zfooter-noticero   rp   T)u   hud 세부 수치 텍스트u   없음u	   삭제됨T)u   40px 미만 폰트u   0건u   전체 0건Tu   ✓u   ✗z  [z] z<22 z<8i   u   
생성 완료!u     배경:       u     템플릿:     z  sample-v2:  r$   z.0fz KB)u     v2 최종:    )r)   gcloud_authget_service_account_tokenGEMINI_SCOPEr5   rJ   ri   SAMPLE_PATHshutilcopy2
FINAL_PATHstatst_sizerV   )
r   rK   checksnamesizeruleokmarksize_kbfinal_kbs
             rI   mainr      s   	(O	
FG	
BC	(O 

./11,?E	3CJ<w
GH 

23!%(G 

EF+& 

?@
LLj)	Ij\
"# 
/	
78	(O
F !' 9dD"uD6D:QtBiq789  ((4/G ((4/H	
	WI
&'	m_
-.	N;-r'#d
;<	ZL8C.
=>	(O    __main__)__doc__sysr1   rx   pathlibr   rU   insertrt   r,   playwright.sync_apir   r3   r'   rV   rw   rz   r*   rv   r+   rb   rJ   ri   r   r:    r   rI   <module>r      s        ; <   /Z[

x
//?*55
DD= 
MJs MJt MJ`$ T d D2j zF r   