You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

176 lines
6.3 KiB

import streamlit as st
import requests
from PIL import Image
from utils.weather import get_weather_data
from utils.outfits import generate_sample_outfits
from utils.outfits import generate_fallback_outfits
from utils.image_processing import process_image_for_try_on
from config import MOONSHOT_API_KEY
def show_recommendations_tab():
st.header("智能穿搭推荐")
with st.form("scene_form"):
col1, col2 = st.columns(2)
with col1:
scene_input = st.text_input("描述你的场景需求",
placeholder="例如: 今天要和朋友们去公园野餐")
with col2:
city_input = st.text_input("输入城市名称",
placeholder="例如: 北京",
value="北京")
use_weather = st.checkbox("获取当地天气信息", value=True)
submitted = st.form_submit_button("获取穿搭建议")
if submitted and scene_input:
with st.spinner("正在生成穿搭建议..."):
try:
weather_info = ""
if use_weather and city_input:
weather_data = get_weather_data(city_input)
if weather_data:
weather_info = f"""
## 当前天气情况
- 城市: {weather_data['city']}
- 天气状况: {weather_data['description']}
- 温度: {weather_data['temp']}°C
- 湿度: {weather_data['humidity']}%
"""
st.markdown(weather_info)
prompt = build_prompt(scene_input, weather_info if use_weather else "")
response = call_moonshot_api(prompt)
if response:
st.session_state.recommendations = response
st.success("穿搭建议生成成功!")
# 新增:根据建议生成图片
outfit_image = generate_sample_outfits(response)
if outfit_image:
st.image(outfit_image, caption="推荐穿搭可视化", width=300)
st.session_state.outfit_image = outfit_image
else:
st.warning("无法生成穿搭图片,但文字建议有效")
else:
st.error("获取穿搭建议失败")
except Exception as e:
st.error(f"获取建议时出错: {str(e)}")
# recommendations.py 修改后的显示部分
if st.session_state.recommendations:
st.markdown("### 您的专属穿搭建议")
st.markdown(st.session_state.recommendations)
st.markdown("### 搭配示例")
try:
sample_images = generate_sample_outfits(
st.session_state.recommendations,
save_to_local=True
)
if sample_images:
# 确保只显示实际生成的图片数量
num_images = min(3, len(sample_images))
cols = st.columns(num_images)
for i in range(num_images):
with cols[i]:
st.image(
sample_images[i],
use_container_width=True,
caption=f"穿搭方案 {i + 1}"
)
st.success(f"示例 {i + 1}")
else:
st.warning("无法生成任何穿搭示例图片")
except Exception as e:
st.error(f"生成穿搭示例时出错: {str(e)}")
# 显示回退方案
fallback_images = generate_fallback_outfits(save_to_local=True)
cols = st.columns(3)
for i, col in enumerate(cols):
col.image(
fallback_images[i],
use_container_width=True,
caption=f"穿搭方案 {i + 1} (示例)"
)
def build_prompt(scene_input, weather_info):
return f"""
你是一位专业的时尚穿搭助手,请根据以下信息为用户提供穿搭建议:
### 用户信息
{st.session_state.user_info}
### 场景描述
{scene_input}
### 天气信息
{weather_info if weather_info else "用户未提供天气信息"}
### 请提供以下内容:
1. 适合该场景的3套穿搭方案
2. 每套方案的风格特点和适用场合说明
3. 颜色搭配建议
4. 材质和面料选择建议
5. 购买建议和品牌推荐(可选)
"""
def call_moonshot_api(prompt):
headers = {
"Authorization": f"Bearer {MOONSHOT_API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": "moonshot-v1-128k",
"messages": [
{
"role": "system",
"content": "你是一位专业的时尚顾问,擅长根据用户特征、场景和天气状况提供个性化的穿搭建议。"
},
{
"role": "user",
"content": prompt
}
],
"temperature": 0.7,
"max_tokens": 2000
}
response = requests.post(
"https://api.moonshot.cn/v1/chat/completions",
headers=headers,
json=data
)
if response.status_code == 200:
result = response.json()
return result["choices"][0]["message"]["content"]
else:
st.error(f"API调用失败: {response.text}")
return None
def show_virtual_tryon_tab():
st.header("虚拟试衣间")
st.info("此功能正在开发中,即将推出!")
uploaded_file = st.file_uploader("上传你的照片进行虚拟试衣", type=["jpg", "png", "jpeg"])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image, caption="上传的照片", use_container_width=True)
gray, edges = process_image_for_try_on(image)
col1, col2 = st.columns(2)
col1.image(gray, caption="灰度处理", use_container_width=True, channels="GRAY")
col2.image(edges, caption="边缘检测", use_container_width=True, channels="GRAY")