Virtual-Try-On / app.py
Anirudh1950's picture
Mirror from GitHub
258bfa8 verified
Raw History Blame Contribute Delete
25.5 kB
import streamlit as st
import os
import base64
import requests
import google.auth
from google.auth.transport.requests import Request
import io
import json
from PIL import Image
import json
import shutil
import cv2
import tempfile
import numpy as np
from google.oauth2 import service_account
# Configuration Defaults
DEFAULT_PROJECT_ID = "project-67b75fc2-12dc-4bad-95d"
DEFAULT_REGION = "us-central1"
# Unique bucket name
DEFAULT_BUCKET = f"gs://tryon-{DEFAULT_PROJECT_ID.replace('project-', '')}"
st.set_page_config(page_title="Virtual Clothing", layout="wide")
# --- CUSTOM CSS INJECTION ---
st.markdown("""
<style>
/* IMPORT FONTS */
@import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600&family=Lato:wght@300;400&display=swap');
/* GLOBAL THEME */
.stApp {
background-color: #050505;
font-family: 'Lato', sans-serif;
color: #ffffff;
}
/* HEADERS */
h1, h2, h3 {
font-family: 'Playfair Display', serif !important;
font-weight: 400;
text-transform: uppercase;
letter-spacing: 4px;
color: #ffffff;
margin-bottom: 20px;
border-bottom: 1px solid #333;
padding-bottom: 10px;
}
/* SIDEBAR */
section[data-testid="stSidebar"] {
background-color: #0a0a0a;
border-right: 1px solid #222;
}
/* CARDS / CONTAINERS */
.stCard {
background: transparent;
border: 1px solid #333;
border-radius: 0px; /* Sharp edges */
padding: 30px;
}
/* BUTTONS */
div.stButton > button {
background-color: #ffffff;
color: #000000;
border: 1px solid #ffffff;
border-radius: 0px; /* Sharp edges */
padding: 12px 40px;
font-family: 'Lato', sans-serif;
text-transform: uppercase;
letter-spacing: 2px;
font-size: 14px;
transition: all 0.3s ease;
width: 100%;
}
div.stButton > button:hover {
background-color: #000000;
color: #ffffff;
border-color: #ffffff;
}
/* INPUTS */
div[data-testid="stTextInput"] > div > div > input {
background-color: #111;
color: #fff;
border: 1px solid #333;
border-radius: 0px;
padding: 10px;
}
div[data-testid="stTextInput"] > div > div > input:focus {
border-color: #fff;
}
/* FILE UPLOADER */
section[data-testid="stFileUploader"] {
background-color: #0a0a0a;
border: 1px solid #333; /* Minimal border */
border-radius: 0px;
padding: 20px;
text-align: center;
}
section[data-testid="stFileUploader"] small {
font-family: 'Lato', sans-serif;
letter-spacing: 1px;
}
/* TABS */
.stTabs [data-baseweb="tab-list"] {
gap: 0px;
background-color: transparent;
justify-content: flex-start;
border-bottom: 1px solid #333;
margin-bottom: 40px;
}
.stTabs [data-baseweb="tab"] {
background-color: transparent;
border-radius: 0px;
color: #666;
padding: 10px 40px;
font-family: 'Playfair Display', serif;
font-size: 18px;
border: none;
}
.stTabs [aria-selected="true"] {
background-color: transparent;
color: #ffffff !important;
border-bottom: 2px solid #ffffff;
}
/* PROGRESS BAR */
.stProgress > div > div > div > div {
background-color: #ffffff;
}
/* HIDE STREAMLIT ELEMENTS */
#MainMenu {visibility: hidden;}
header {visibility: hidden;}
footer {visibility: hidden;}
/* ALERTS */
.stAlert {
background-color: #0a0a0a;
border: 1px solid #333;
color: #ddd;
border-radius: 0px;
}
</style>
""", unsafe_allow_html=True)
# --- Session State Initialization ---
if 'img_data' not in st.session_state:
st.session_state.img_data = None
def get_gcloud_token():
"""Attempts to get a token from the gcloud CLI."""
try:
# Check if gcloud is installed
import subprocess
result = subprocess.run(
["gcloud", "auth", "print-access-token"],
capture_output=True,
text=True,
shell=True
)
if result.returncode == 0:
token = result.stdout.strip()
if token:
return token
except Exception:
pass
return None
def get_access_token(service_account_json=None, raw_token=None):
"""Retrieves the Google Cloud access token."""
try:
# 1. Try Manual Input
if raw_token:
t = raw_token.strip().strip('"').strip("'")
if t.lower().startswith("bearer "):
t = t[7:]
return t
# 2. Try Service Account JSON
if service_account_json:
credentials = service_account.Credentials.from_service_account_info(
json.load(service_account_json),
scopes=['https://www.googleapis.com/auth/cloud-platform']
)
credentials.refresh(Request())
return credentials.token
# 3. Try gcloud CLI (Auto-Auth)
gcloud_token = get_gcloud_token()
if gcloud_token:
return gcloud_token
# 4. Try Default Credentials
credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
credentials.refresh(Request())
return credentials.token
except Exception as e:
return None
def encode_image(image_input):
"""Encodes an image input (file-like, bytes, or path) to base64."""
try:
# Handle bytes/bytearray
if isinstance(image_input, (bytes, bytearray)):
image = Image.open(io.BytesIO(image_input))
# Handle file-like object (UploadedFile)
elif hasattr(image_input, "read"):
image_input.seek(0)
image = Image.open(image_input)
# Handle string path
elif isinstance(image_input, str) and os.path.exists(image_input):
image = Image.open(image_input)
else:
raise ValueError("Unsupported image input type")
if image.mode != 'RGB':
image = image.convert('RGB')
# Increased to 4096 for 4K quality (User Request)
max_size = 4096
if image.width > max_size or image.height > max_size:
image.thumbnail((max_size, max_size))
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format='JPEG', quality=100) # Maximum quality JPEG
img_byte_arr = img_byte_arr.getvalue()
return base64.b64encode(img_byte_arr).decode("utf-8")
except Exception as e:
st.error(f"Image Encoding Error: {e}")
return None
def generate_tryon_api(person_input, product_input, project_id, region, token, gcs_bucket):
"""Reusable helper to call the Vertex AI Try-On API."""
try:
person_b64 = encode_image(person_input)
product_b64 = encode_image(product_input)
if not person_b64 or not product_b64:
raise ValueError("Failed to encode images")
endpoint = f"https://{region}-aiplatform.googleapis.com/v1/projects/{project_id}/locations/{region}/publishers/google/models/virtual-try-on-preview-08-04:predict"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json; charset=utf-8",
}
request_body = {
"instances": [
{
"personImage": {"image": {"bytesBase64Encoded": person_b64}},
"productImages": [{"image": {"bytesBase64Encoded": product_b64}}]
}
],
"parameters": {
"sampleCount": 1,
"storageUri": gcs_bucket if gcs_bucket.endswith("/") else f"{gcs_bucket}/output"
}
}
response = requests.post(endpoint, headers=headers, json=request_body)
response.raise_for_status()
result = response.json()
predictions = result.get('predictions')
if predictions:
prediction = predictions[0]
if 'bytesBase64Encoded' in prediction:
return base64.b64decode(prediction['bytesBase64Encoded'])
elif 'gcsUri' in prediction:
return download_gcs_image(prediction['gcsUri'], token)
else:
st.error(f"Unknown prediction format. Keys: {prediction.keys()}")
st.write("Full Response:", result)
else:
st.error("API returned success but no 'predictions' key.")
st.write("Full Response:", result)
return None
except requests.exceptions.HTTPError as e:
st.error(f"API Request Failed: {e}")
if e.response is not None:
st.error(f"Server Response: {e.response.text}")
return None
except Exception as e:
st.error(f"Generation Failed: {e}")
return None
def upscale_image(img_bytes, target_width=None, target_height=None):
"""Upscales image to target resolution using Lanczos resampling."""
try:
img = Image.open(io.BytesIO(img_bytes))
# Default to 4K if no target specified
if not target_width: target_width = 2160 # Standard 4K width (vertical p.)
if not target_height: target_height = 3840
# If already larger, skip
if img.width >= target_width and img.height >= target_height:
return img_bytes
st.info(f"✨ Upscaling from {img.width}x{img.height} to {target_width}x{target_height}...")
# High-quality resize
img = img.resize((target_width, target_height), Image.Resampling.LANCZOS)
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
except Exception as e:
st.error(f"Upscaling failed: {e}")
return img_bytes
def remove_watermark(img_data):
"""Crops the bottom 60 pixels to remove the watermark."""
try:
img = Image.open(io.BytesIO(img_data))
width, height = img.size
# Crop bottom 60 pixels (standard watermark area)
if height > 100:
img = img.crop((0, 0, width, height - 60))
buf = io.BytesIO()
img.save(buf, format="PNG")
return buf.getvalue()
except Exception as e:
st.error(f"Watermark removal failed: {e}")
return img_data
def process_video_frames(video_path, product_top, product_bottom, project_id, region, token, gcs_bucket):
"""
1. Reads original video FPS.
2. Processes EVERY frame (Slow but high quality).
3. Writes output at ORIGINAL FPS.
"""
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
st.error("Could not open video file.")
return None
fps = cap.get(cv2.CAP_PROP_FPS)
if fps <= 0: fps = 24.0 # Fallback
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# Temp output file
output_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name
# Use mp4v codec
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
# Progress UI
progress_bar = st.progress(0)
status_text = st.empty()
frame_count = 0
while True:
ret, frame = cap.read()
if not ret:
break
status_text.text(f"Processing frame {frame_count}/{total_frames}...")
# Convert for Processing
rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
pil_img = Image.fromarray(rgb_frame)
buf = io.BytesIO()
pil_img.save(buf, format="JPEG")
img_bytes = buf.getvalue()
final_frame = frame # Default to original if fail
try:
processed_bytes = img_bytes
# Step 1: Top
if product_top:
res = generate_tryon_api(processed_bytes, product_top, project_id, region, token, gcs_bucket)
if res: processed_bytes = res
# Step 2: Bottom
if product_bottom:
res = generate_tryon_api(processed_bytes, product_bottom, project_id, region, token, gcs_bucket)
if res: processed_bytes = res
if processed_bytes:
processed_bytes = remove_watermark(processed_bytes)
# Convert to CV2 for Video Writer
res_pil = Image.open(io.BytesIO(processed_bytes))
res_pil = res_pil.resize((width, height)) # Encode might resize, so we force back to original
res_np = np.array(res_pil)
final_frame = cv2.cvtColor(res_np, cv2.COLOR_RGB2BGR)
except Exception as e:
st.error(f"Error at frame {frame_count}: {e}")
out.write(final_frame)
frame_count += 1
if total_frames > 0:
progress_bar.progress(min(frame_count / total_frames, 1.0))
cap.release()
out.release()
return output_path
def download_gcs_image(gcs_uri, token):
"""Downloads image from GCS using the access token."""
try:
if not gcs_uri.startswith("gs://"):
return None
parts = gcs_uri[5:].split("/", 1)
if len(parts) != 2:
return None
bucket_name, object_name = parts
object_name_encoded = requests.utils.quote(object_name, safe='')
url = f"https://storage.googleapis.com/storage/v1/b/{bucket_name}/o/{object_name_encoded}?alt=media"
headers = {"Authorization": f"Bearer {token}"}
response = requests.get(url, headers=headers)
response.raise_for_status()
return response.content
except Exception as e:
st.error(f"Failed to download from GCS: {e}")
return None
def create_bucket_if_missing(bucket_name, project_id, token):
"""Creates a GCS bucket if it doesn't exist."""
try:
if not bucket_name.startswith("gs://"):
return False, "Bucket must start with gs://"
b_name = bucket_name.replace("gs://", "").strip("/")
check_url = f"https://storage.googleapis.com/storage/v1/b/{b_name}"
headers = {"Authorization": f"Bearer {token}"}
resp = requests.get(check_url, headers=headers)
if resp.status_code == 200:
return True, "Bucket exists."
if resp.status_code == 404:
st.info(f"Bucket {bucket_name} not found. Creating it...")
create_url = f"https://storage.googleapis.com/storage/v1/b?project={project_id}"
data = {"name": b_name, "location": "US"}
create_resp = requests.post(create_url, headers=headers, json=data)
if create_resp.status_code == 200:
return True, "Created new bucket successfully."
else:
return False, f"Failed to create bucket: {create_resp.text}"
if resp.status_code == 403:
return False, "Access Denied. Change GCS Bucket name."
if resp.status_code == 401:
return False, "Token Expired. Re-Authenticate."
return False, f"Error checking bucket: {resp.status_code}"
except Exception as e:
return False, f"Bucket check failed: {e}"
def main():
# --- Sidebar Configuration (Kept for settings) ---
st.sidebar.header("⚙️ SYSTEM CONFIG")
# Auto-load local service_account.json if exists
default_key_file = None
if os.path.exists("service_account.json"):
st.sidebar.success("✅ Auto-loaded 'service_account.json'")
default_key_file = open("service_account.json", "r")
key_file = st.sidebar.file_uploader("Upload Service Account JSON", type=["json"], key="auth_json")
# Use uploaded file if present, otherwise fallback to local auto-loaded file
final_key_file = key_file if key_file else default_key_file
st.sidebar.markdown("**OR**")
# Auto-load cached token
cached_token = ""
if os.path.exists(".token"):
with open(".token", "r") as f:
cached_token = f.read().strip()
default_token = os.environ.get("GCP_ACCESS_TOKEN", cached_token)
access_token_input = st.sidebar.text_input("Paste Access Token", value=default_token, type="password")
if access_token_input:
# Cache the token for next time
with open(".token", "w") as f:
f.write(access_token_input)
project_id = st.sidebar.text_input("Project ID", value=DEFAULT_PROJECT_ID)
region = st.sidebar.text_input("Region", value=DEFAULT_REGION)
gcs_bucket = st.sidebar.text_input("GCS Bucket", value=DEFAULT_BUCKET)
# --- UI HEADER & TABS ---
st.title("VIRTUAL CLOTHING")
tab_image, tab_video = st.tabs(["📸 IMAGE STUDIO", "🎥 VIDEO STUDIO"])
# --- HELPER: GENERATION LOGIC ---
def run_generation(mode, person_file_input, top_input, bottom_input):
# Reset session state on new generate
st.session_state.img_data = None
if not person_file_input or (not top_input and not bottom_input):
st.warning("Please upload a Person and at least one Garment.")
return
with st.spinner("Preparing..."):
token = get_access_token(final_key_file, access_token_input)
if not token:
return
success, msg = create_bucket_if_missing(gcs_bucket, project_id, token)
if not success:
st.error(msg)
return
with st.spinner(f"Running {mode}..."):
try:
# --- Video Mode Logic ---
if mode == "Video Try-On":
# Save uploaded video to temp file
tfile = tempfile.NamedTemporaryFile(delete=False)
tfile.write(person_file_input.read())
video_path = tfile.name
st.info("Starting Video Processing (1 FPS extraction)...")
final_video_path = process_video_frames(
video_path,
top_input,
bottom_input,
project_id,
region,
token,
gcs_bucket
)
if final_video_path:
st.success("Video Processing Complete!")
st.video(final_video_path)
with open(final_video_path, "rb") as f:
st.download_button("Download Video", f, "tryon_video.mp4", "video/mp4")
else:
st.error("Validation failed or no frames processed.")
return # Stop here for video
# --- Image Mode Logic ---
current_person_img = person_file_input
generated_img = None
# Get Original Dimensions
orig_w, orig_h = 2160, 3840 # Default fallback
try:
if hasattr(person_file_input, 'seek'):
person_file_input.seek(0)
with Image.open(person_file_input) as p_preview:
orig_w, orig_h = p_preview.size
if hasattr(person_file_input, 'seek'):
person_file_input.seek(0)
except Exception as e:
st.warning(f"Could not read original dimensions, defaulting to 4K: {e}")
# --- Step 1: Apply Top (if present) ---
if top_input:
st.info("Step 1/2: Applying Top...")
generated_img = generate_tryon_api(current_person_img, top_input, project_id, region, token, gcs_bucket)
if not generated_img:
st.error("Failed to generate Top try-on. Stopping.")
return
# Prepare for next step
current_person_img = generated_img
# --- Step 2: Apply Bottom (if present) ---
if bottom_input:
step_label = "Step 2/2" if top_input else "Step 1/1"
st.info(f"{step_label}: Applying Bottom...")
generated_img = generate_tryon_api(current_person_img, bottom_input, project_id, region, token, gcs_bucket)
if not generated_img:
st.error("Failed to generate Bottom try-on.")
return
# Success Handling
if generated_img:
# 1. Remove watermark
clean_img = remove_watermark(generated_img)
# 2. Resize to Original Dimensions
# We match the original person's image dimensions exactly.
final_img = upscale_image(clean_img, orig_w, orig_h)
st.success("Generation Successful!")
st.session_state.img_data = final_img
except Exception as e:
st.error(f"Workflow Failed: {e}")
# --- TABS CONTENT ---
with tab_image:
col1, col2 = st.columns(2)
with col1:
st.markdown("### 1. PERSON IMAGE")
p_img = st.file_uploader("Upload Person", type=["jpg", "png", "jpeg"], key="person_img")
if p_img:
st.image(p_img, caption="Person", use_column_width=True)
elif os.path.exists("person.jpg"):
st.info("Using local 'person.jpg'")
st.image("person.jpg", caption="Person (Local)", use_column_width=True)
p_img = open("person.jpg", "rb")
with col2:
st.markdown("### 2. CHOOSE GARMENTS")
st.write("Upload one or both.")
t_img = st.file_uploader("Upload Top", type=["jpg", "png", "jpeg"], key="top")
if t_img:
st.image(t_img, caption="Top", width=150)
b_img = st.file_uploader("Upload Bottom", type=["jpg", "png", "jpeg"], key="bottom")
if b_img:
st.image(b_img, caption="Bottom", width=150)
st.divider()
if st.button("✨ GENERATE IMAGE", type="primary", key="btn_img"):
run_generation("Image Try-On", p_img, t_img, b_img)
with tab_video:
col1, col2 = st.columns(2)
with col1:
st.markdown("### 1. PERSON VIDEO")
p_vid = st.file_uploader("Upload Video", type=["mp4", "mov", "avi"], key="person_vid")
if p_vid:
st.video(p_vid)
with col2:
st.markdown("### 2. CHOOSE GARMENTS")
st.write("Use same garments as Image Mode for now.")
t_vid = st.file_uploader("Upload Top", type=["jpg", "png", "jpeg"], key="top_vid")
b_vid = st.file_uploader("Upload Bottom", type=["jpg", "png", "jpeg"], key="bottom_vid")
st.divider()
if st.button("✨ GENERATE VIDEO", type="primary", key="btn_vid"):
run_generation("Video Try-On", p_vid, t_vid, b_vid)
# --- Display Result Section (Common) ---
if st.session_state.img_data:
st.divider()
st.subheader("🎉 Result")
# Verify Resolution
try:
res_img = Image.open(io.BytesIO(st.session_state.img_data))
st.info(f"Output Resolution: {res_img.width}x{res_img.height}")
st.image(st.session_state.img_data, caption=f"Try-On Result ({res_img.width}x{res_img.height})", use_column_width=True)
except:
st.image(st.session_state.img_data, caption="Try-On Result", use_column_width=True)
st.download_button(
label="Download Result",
data=st.session_state.img_data,
file_name="tryon_result.png",
mime="image/png"
)
if __name__ == "__main__":
main()