o
    ]jq                     @   s  d dl Z d dlZd dl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	Zej r?d
ndZe je jeZe jedZdZdZe jedd e	 Zejedgdgdgd ejdeeddd e d ej!eed
krej"nej#ed
krdnddd$eZ%e%&  e%j'dd ed
kre%j(j$ej#d dej)jj*_+dej)j,_+dej)j,_-e d dd Z.e/d ed!ed!fd"e0d#e0fd$d%Z1dS )&    N)Image) StableDiffusionXLImg2ImgPipeline)Body)FastAPI)HTTPException)CORSMiddleware)StaticFilesz(stabilityai/stable-diffusion-xl-base-1.0cudacpuoutputi   z
overlapping fabric, folded layers, crumpled, double layers,
tilted, asymmetrical, distorted, curved lines, warped,
mannequin, body, person, blurry, low quality
T)exist_ok*POSTzContent-Type)allow_originsallow_methodsallow_headersz/output)	directory)namezLoading model...fp16)torch_dtypevariantuse_safetensors)disable)dtypezModel loaded!c                 C   s\   t | d}t dttfd}|d t|j d }t|j d }||||f |S )NRGB)   r   r   )  r      )	r   openconvertnewCANVAS_SIZE	thumbnailwidthheightpaste)
image_pathimagecanvasxy r+   Ghtdocs/OOTD2/inpainting/stable_diffusion/stable_diffusion_xl_img2img.pyprepare_image>   s   
r-   z	/generate.r'   promptc                 C   s   | }t d|  dd tj|stjt|}tj|s'tdd|  d| s1tdddt	|}t
  t|t|d	d
dt
jtdddjd }W d    n1 sYw   Y  t  d}tjt|}|| dtj|tdS )Nzimage: T)flushi  u*   입력 파일을 찾을 수 없습니다: )status_codedetaili  u'   prompt가 입력되지 않았습니다.g?g      (@2   )device*   )r.   negative_promptr'   strengthguidance_scalenum_inference_steps	generatorr   z.pngsuccess)statusr'   )printospathisabsjoin
SCRIPT_DIRisfiler   stripr-   torchinference_modepipeNEGATIVE_PROMPT	GeneratorDEVICEmanual_seedimagesuuiduuid4
OUTPUT_DIRsaverelpath)r'   r.   r&   input_imageresultfilename	save_pathr+   r+   r,   generateM   s8   

rU   )2r=   rL   rD   PILr   	diffusersr   fastapir   r   r   fastapi.middleware.corsr   fastapi.staticfilesr   MODEL_IDr	   is_availablerI   r>   dirnameabspath__file__rA   r@   rN   r!   rG   makedirsappadd_middlewaremountr<   from_pretrainedfloat16float32torF   enable_attention_slicingset_progress_bar_configvaebackendsmatmul
allow_tf32cudnn	benchmarkr-   poststrrU   r+   r+   r+   r,   <module>   sZ    

&