File size: 5,076 Bytes
f3f723d
7ae42ca
 
 
 
 
 
f3f723d
 
7ae42ca
0c1cc13
 
 
 
 
 
 
 
 
 
 
 
 
7ae42ca
 
 
 
 
 
f3f723d
7ae42ca
 
 
 
 
0c1cc13
f3f723d
 
 
 
 
7ae42ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0c1cc13
7ae42ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3f723d
7ae42ca
f3f723d
7ae42ca
f3f723d
7ae42ca
 
 
 
 
 
 
f3f723d
acbf029
7ae42ca
e730bab
f3f723d
acbf029
a75d96a
acbf029
 
0ff4c41
7ae42ca
acbf029
 
 
 
f3f723d
 
 
acbf029
 
f3f723d
acbf029
7ae42ca
acbf029
 
 
 
f3f723d
acbf029
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7ae42ca
f3f723d
 
 
 
 
acbf029
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
import streamlit as st
import cv2
import numpy as np
import base64
import requests
import json
import time
import random
import os

# Load environment variables
tryon_url = os.environ.get('tryon_url', 'http://default-url/')  # Default URL for testing
token = os.environ.get('token', 'default-token')
cookie = os.environ.get('Cookie', 'default-cookie')
referer = os.environ.get('referer', 'default-referer')

headers = {
    'Content-Type': 'application/json',
    'token': token,
    'Cookie': cookie,
    'referer': referer
}

def tryon(person_img, garment_img, seed, randomize_seed):
    if person_img is None or garment_img is None:
        st.warning("Empty image")
        return None, None, "Empty image"
    if randomize_seed:
        seed = random.randint(0, MAX_SEED)
    
    encoded_person_img = cv2.imencode('.jpg', cv2.cvtColor(person_img, cv2.COLOR_RGB2BGR))[1].tobytes()
    encoded_person_img = base64.b64encode(encoded_person_img).decode('utf-8')
    encoded_garment_img = cv2.imencode('.jpg', cv2.cvtColor(garment_img, cv2.COLOR_RGB2BGR))[1].tobytes()
    encoded_garment_img = base64.b64encode(encoded_garment_img).decode('utf-8')

    url = tryon_url + "Submit"
    data = {
        "clothImage": encoded_garment_img,
        "humanImage": encoded_person_img,
        "seed": seed
    }
    try:
        response = requests.post(url, headers=headers, data=json.dumps(data), timeout=50)
        if response.status_code == 200:
            result = response.json()['result']
            status = result['status']
            if status == "success":
                uuid = result['result']
    except Exception as err:
        st.error(f"Post Exception Error: {err}")
        return None, None, "Too many users, please try again later"

    time.sleep(9)
    Max_Retry = 12
    result_img = None
    info = ""
    for i in range(Max_Retry):
        try:
            url = tryon_url + "Query?taskId=" + uuid
            response = requests.get(url, headers=headers, timeout=20)
            if response.status_code == 200:
                result = response.json()['result']
                status = result['status']
                if status == "success":
                    result = base64.b64decode(result['result'])
                    result_np = np.frombuffer(result, np.uint8)
                    result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
                    result_img = cv2.cvtColor(result_img, cv2.COLOR_RGB2BGR)
                    info = "Success"
                    break
                elif status == "error":
                    info = "Error"
                    break
            else:
                info = "URL error, please contact the admin"
                break
        except requests.exceptions.ReadTimeout:
            info = "Http Timeout, please try again later"
        except Exception as err:
            info = f"Get Exception Error: {err}"
        time.sleep(1)
    
    if info == "":
        info = f"No image after {Max_Retry} retries"
    if info != "Success":
        st.warning("Too many users, please try again later")

    return result_img, seed, info

MAX_SEED = 999999

# Set up the Streamlit app
st.set_page_config(page_title="Virtual-DressUp", page_icon=":dress:", layout="wide")

st.title("Virtual-DressUp")
st.markdown("""
**Project Overview:**  
This project leverages the advanced virtual try on clothes, model is created by Kwai-Kolors. We've created interactive GUI for users to experience virtual try-ons. For more innovative features and models, check out their official website!

[Explore Kwai-Kolors' website](https://klingai.com/)
""")

# Display the demo image
st.image("demo img.png", caption="Demo Image", use_column_width=True)

# Image upload columns
col1, col2 = st.columns(2)

with col1:
    person_img = st.file_uploader("Upload Person Image", type=["jpg", "jpeg", "png"])

with col2:
    garment_img = st.file_uploader("Upload Garment Image", type=["jpg", "jpeg", "png"])

# Always show slider options
st.sidebar.header("Options")
seed = st.sidebar.slider("Seed", 0, MAX_SEED, 0)
randomize_seed = st.sidebar.checkbox("Random seed", value=True)

# Show steps in sidebar
st.sidebar.markdown("""
**Steps to Follow:**
1. Upload a person image ⬇️
2. Upload a garment image ⬇️
3. Press "Run" to get try-on results 🎉
""")

if st.sidebar.button("Run"):
    if person_img and garment_img:
        person_img = np.array(bytearray(person_img.read()), dtype=np.uint8)
        garment_img = np.array(bytearray(garment_img.read()), dtype=np.uint8)
        person_img = cv2.imdecode(person_img, cv2.IMREAD_COLOR)
        garment_img = cv2.imdecode(garment_img, cv2.IMREAD_COLOR)
        
        result_img, seed_used, result_info = tryon(person_img, garment_img, seed, randomize_seed)
        if result_info == "Success":
            st.image(result_img, caption="Result", channels="BGR")
            st.sidebar.text(f"Seed used: {seed_used}")
        else:
            st.sidebar.error(result_info)
    else:
        st.sidebar.warning("Please upload both images to proceed.")