Spaces:
Running
Running
File size: 5,463 Bytes
f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 0ff4c41 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d 7ae42ca f3f723d |
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 144 |
import streamlit as st
import cv2
import numpy as np
import base64
import requests
import json
import time
import random
import os
# Function to handle the try-on process
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 = "http://" + os.environ['tryon_url'] + "Submit"
token = os.environ['token']
cookie = os.environ['Cookie']
referer = os.environ['referer']
headers = {'Content-Type': 'application/json', 'token': token, 'Cookie': cookie, 'referer': referer}
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 = "http://" + os.environ['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 Try-On", page_icon=":guardsman:", layout="wide")
# Title and description
st.title("Virtual Try-On")
st.markdown("""
**Step 1:** Upload a person image ⬇️
**Step 2:** Upload a garment image ⬇️
**Step 3:** Press “Run” to get try-on results
""")
# Columns for uploading images
col1, col2 = st.columns(2)
with col1:
st.image("assets/upload_person.png", caption="Upload your person image here.", use_column_width=True)
person_img = st.file_uploader("Person Image", type=["jpg", "jpeg", "png"], label_visibility="collapsed")
with col2:
st.image("assets/upload_garment.png", caption="Upload your garment image here.", use_column_width=True)
garment_img = st.file_uploader("Garment Image", type=["jpg", "jpeg", "png"], label_visibility="collapsed")
# Show options and button if images are uploaded
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)
st.sidebar.header("Options")
seed = st.sidebar.slider("Seed", 0, MAX_SEED, 0)
randomize_seed = st.sidebar.checkbox("Random seed", value=True)
st.sidebar.markdown("---")
# Display example images
st.sidebar.image("assets/seed_example.png", caption="Example of seed usage", use_column_width=True)
if st.sidebar.button("Run"):
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.")
# Footer or additional information
st.markdown("---")
st.markdown("Built with Streamlit & Python. [GitHub repository](#)")
# Add some styling and visual improvements
st.markdown("""
<style>
.css-18e3th9 {padding: 0.5rem 1rem;} /* Increase padding for the sidebar */
.css-1d391kg {padding: 1rem;} /* Increase padding for main content area */
.css-1v0mbdj {font-size: 20px;} /* Adjust font size for titles and labels */
</style>
""", unsafe_allow_html=True)
|