
    5i-              	          d dl mZmZ d dlm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mZ  e              ed          Z e	j        d          Zes ed	           d#dedededefdZd$dedededefdZd%defdZe                    d          d             Ze                    d          d&dededefd            Ze                    d          d&dededefd            Zedk    rd dlZ ej        ed d!"           dS dS )'    )FastAPIHTTPException)StreamingResponse)ImageN)load_dotenvAI Renovation Inference Service)titleSTABILITY_API_KEYuG   ⚠️ Warning: STABILITY_API_KEY not set. Will use placeholder images.living_roomstyle	layout_id	room_typereturnc                    dddddd}|                     ||d                   }i dd	| d
dd	| d
dd| ddd| ddd| ddd| ddd| ddd| ddd| ddd| ddd| ddd| dd d!| d"d#d!| d"d$d%| d&d'd%| d&d(d%| d&}|                     | |d                   }| d)| d*}d+}||fS ),uJ   根据风格和房间类型生成 Stability AI 提示词和负面提示词z+living room, sofa, coffee table, TV cabinetz"bedroom, bed, nightstand, wardrobez$kitchen, cabinets, countertops, sinkz!bathroom, bathtub, shower, vanityz!dining room, dining table, chairs)r   bedroomkitchenbathroomdining_roomr      现代简约zultra modern minimalist z, floor-to-ceiling windows, pure white walls, no decorations, sleek glass coffee table, hidden LED strip lighting, open concept, IKEA-style furniture, concrete floor, high ceiling, 8K realistic photozmodern minimalistu	   北欧风zauthentic Scandinavian z, light birch wood floor, sheepskin rug, hygge atmosphere, pastel color palette (mint, blush, sky blue), pendant lamp with fabric shade, minimalist bookshelf, Monstera plant, white walls with wood accents, cozy textiles, 8K realistic photoScandinavianu   中式风格ztraditional Chinese a  , dark rosewood furniture with intricate carvings, red lacquer cabinets, golden dragon motifs, silk embroidered cushions, paper lanterns hanging from ceiling, moon gate entrance, bonsai tree, calligraphy wall art, terra cotta floor tiles, 8K realistic photozChinese traditionalu   美式风格zclassic American z, warm beige walls, overstuffed sectional sofa, brick fireplace with wooden mantel, oak hardwood floor, vintage rug, family photos on wall, ceiling fan with lights, bay window with curtains, 8K realistic photozAmerican classicu	   工业风zauthentic industrial loft z, exposed red brick walls, polished concrete floor, black metal frame furniture, Edison bulb pendant lights, steel beams on ceiling, leather sofa with metal legs, vintage factory cart coffee table, pipe shelving, 8K realistic photo
industrialu   日式风格zzen Japanese z, tatami mat floor, low wooden table, shoji sliding paper doors, bonsai tree, neutral earth tones (beige, brown, gray), minimalist futon, bamboo accents, rock garden view through window, 8K realistic photozJapanese zenu	   轻奢风zluxury modern z, Italian marble floor, gold-plated furniture legs, crystal chandelier, velvet sofa in emerald green, mirrored accent wall, abstract art painting, smart home automation visible, floor-to-ceiling curtains, 8K realistic photozluxury modernu   地中海风格zauthentic Mediterranean a*  , white stucco walls with blue accents, arched doorways and windows, terracotta floor tiles, mosaic tile borders in blue and white, exposed wooden ceiling beams, wicker furniture with blue cushions, large clay pots with olive trees, sea view through window, wrought iron details, 8K realistic photoMediterraneanmediterranean, zS, professional architectural photography, canon EOS R5, 24mm lens, f/8, high detailzcartoon, drawing, sketch, low quality, blurry, distorted, deformed, ugly, bad anatomy, watermark, text, signature, other styles mixed, messy, cluttered)get)	r   r   r   room_prompts	room_descstyle_promptsbase_promptpromptnegative_prompts	            ;/home/ubuntu/projects/home-renovation-app/ai-service/app.pygenerate_promptr#      s   
 E797: L   L,GHHI  F9  F  F  F  K	  K  K  K 	  jy  j  j  j	
 	  m)  m  m  m 	  |y  |  |  | 	   Ci   C   C   C 	  II  I  I  I 	  M	  M  M  M 	  e)  e  e  e 	  f9  f  f  f  	  A	  A  A  A!" 	  A	  A  A  A#& 	  Qi  Q  Q  Q'( 	  U)  U  U  U), 	  li  l  l  l-. 	  jI  j  j  j/0 	  jI  j  j  j1M4  ##E=+HIIK }}y}}}F pO?""     	1024x1024r    r!   sizec                   K   t           st                      S 	 t          t          |                    d                    \  }}t          j                    4 d{V }|                    ddt            ddd| dd|d	dgd
d||dddd           d{V }|j        dk    r7t          d|j
                    t                      cddd          d{V  S |                                }|d         d         d         }t          j        |          }	|	cddd          d{V  S # 1 d{V swxY w Y   dS # t          $ r*}
t          d|
            t                      cY d}
~
S d}
~
ww xY w)u$   调用 Stability AI API 生成图片xNzRhttps://api.stability.ai/v1/generation/stable-diffusion-xl-1024-v1-0/text-to-imagezBearer zapplication/json)AuthorizationzContent-TypeAccept   )textweight   NONE   )text_prompts	cfg_scaleclip_guidance_presetheightwidthsamplesstepsg      N@)headersjsontimeout   zStability AI API Error: 	artifactsr   base64z Error calling Stability AI API: )r
   generate_placeholder_imagemapintsplithttpxAsyncClientpoststatus_codeprintr-   r;   r?   	b64decode	Exception)r    r!   r'   r7   r6   clientresponsedataimage_base64image_byteses              r"   generate_with_stabilityrQ   F   s      ,)+++',CC11v$&& 	 	 	 	 	 	 	&#[[d%B/@%B%B$60  "(155!0B??% "#,2$"   ' )        H, #s**@@@AAA1333	 	 	 	 	 	 	 	 	 	 	 	 	 	6 ==??D,Q/9L *<88K?	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	B  , , ,444555)++++++++,sO   AD> A+D+D> =D+D> +
D55D> 8D59D> >
E2E-'E2-E2   c                     t          j        d| |fd          }t          j                    }|                    |d           |                    d           |                                S )u8   生成占位图（当 API 不可用时的后备方案）RGB)   rU   rU   PNG)formatr   )r   newioBytesIOsaveseekgetvalue)r7   r6   imgimg_byte_arrs       r"   r@   r@   u   s`    
)EE6?O
<
<C:<<LHH\%H(((a  """r$   /c                  (   K   dddgt           rdnddS )Nr   
/inference/inference/allzStable Diffusion XLPlaceholder)message	endpointsmodel)r
    r$   r"   rootri   }   s1       5"$45*;N&&  r$   rb   r   c                   K   t          | ||          \  }}t          d|  d|            t          d|dd          d           	 t          ||           d{V }t          j        |                              d          }|| ||dS # t          $ rb}t          d	|            t          j        t                                                    d          | ||t          |          d
cY d}~S d}~ww xY w)u   
    根据风格生成装修效果图
    暂时使用 Stability AI（Leonardo AI Key 未配置）
    返回 JSON 格式: {"image_base64": "...", "style": "...", "layout_id": "...", "room_type": "..."}
    u    🔍 调用 Stability AI: style=z, room_type=u   🔍 提示词: Nr=   z...utf-8)rN   r   r   r   u   ❌ Stability AI 调用失败: )rN   r   r   r   error)	r#   rH   rQ   r?   	b64encodedecoderJ   r@   str)r   r   r   r    r!   rO   rN   rP   s           r"   	inferencerp      sV      .eY	JJFO	
KU
K
K	
K
KLLL	
.VDSD\
.
.
.///
3FOLLLLLLLL'44;;GDD(""	
 
 	
  	
 	
 	
333444 #,-G-I-IJJQQRYZZ""VV
 
 	
 	
 	
 	
 	
 	
	
s    AB 
C8AC3-C83C8rc   c                 T  K   g }g d}t          |          D ]\  }\  }}t          | ||          \  }}	| d| d|dz    }
t          |
|	           d{V }t          j        |                              d          }|                    |dz   | |||  d| dd	           d
| ||dS )u:   返回 3 套不同角度的方案（使用 Stability AI）))u   客厅全景z.full room view, wide angle, corner perspective)u   餐厅视角z+dining area view, warm lighting, side angle)u   厨房视角z0kitchen area view, modern appliances, front viewr   z, view r,   Nrk   z - u    （Stable Diffusion XL 生成）)plan_idr   viewrN   description   )countr   r   plans)	enumerater#   rQ   r?   rm   rn   append)r   r   r   resultsviewsi	view_name	view_descr    r!   full_promptrO   rN   s                r"   inference_allr      s      G  E &/u%5%5  !!Iy"1%I"N"N::9::QqS::3KQQQQQQQQ'44;;GDD1u(#SS	SSS
 
 	 	 	 	 YQQQr$   __main__z0.0.0.0iA  )hostport)r   )r%   r&   )rR   rR   )r   Nr   )fastapir   r   fastapi.responsesr   PILr   rY   r?   osrD   dotenvr   appgetenvr
   rH   ro   tupler#   bytesrQ   r@   r   ri   rF   rp   r   __name__uvicornrunrh   r$   r"   <module>r      sN   * * * * * * * * / / / / / /       				  				        g5666BI122  U	E
STTT1# 1#3 1#3 1#3 1#SX 1# 1# 1# 1#f-, -,# -, -,PS -,fk -, -, -, -,^# # # # # #    ,
 
3 
C 
SV 
 
 
 
> 
R Rs R RWZ R R R R6 zNNNGK)$////// r$   