Virtual-Try-On / try_on.py
Anirudh1950's picture
Publish project from GitHub
8a09f8a verified
Raw History Blame Contribute Delete
5.01 kB
import argparse
import base64
import json
import os
import sys
import time
import requests
import google.auth
from google.auth.transport.requests import Request
def get_access_token():
"""Retrieves the default Google Cloud access token."""
credentials, project = google.auth.default(scopes=['https://www.googleapis.com/auth/cloud-platform'])
credentials.refresh(Request())
return credentials.token, project
def encode_image(image_path):
"""Encodes an image file to a base64 string."""
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode("utf-8")
return encoded_string
def virtual_try_on(project_id, region, gcs_bucket, person_image_path, product_image_path):
"""
Sends a request to the Vertex AI Virtual Try-On API.
"""
print(f"Authenticating...")
access_token, default_project = get_access_token()
if not project_id:
project_id = default_project
print(f"Using default project ID: {project_id}")
if not project_id:
print("Error: Project ID not found. Please provide it via --project_id.")
return
print(f"Encoding images...")
try:
person_b64 = encode_image(person_image_path)
product_b64 = encode_image(product_image_path)
except FileNotFoundError as e:
print(f"Error loading images: {e}")
return
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 {access_token}",
"Content-Type": "application/json; charset=utf-8",
}
# Construct the request body
request_body = {
"instances": [
{
"personImage": {
"image": {
"bytesBase64Encoded": person_b64
}
},
"productImages": [
{
"image": {
"bytesBase64Encoded": product_b64
}
}
]
}
],
"parameters": {
"sampleCount": 1,
"storageUri": gcs_bucket,
# Optional parameters
# "addWatermark": True,
# "baseSteps": 32,
# "personGeneration": "allow_adult",
}
}
print(f"Sending request to {endpoint}...")
try:
response = requests.post(endpoint, headers=headers, json=request_body)
response.raise_for_status()
result = response.json()
print("\nRequest Successful!")
print(json.dumps(result, indent=2))
# Parse for output path if available (structure depends on API response)
predictions = result.get('predictions')
if predictions:
for pred in predictions:
# The response usually contains the GCS uri or the base64 of the result
# Based on docs: { "predictions": [ { "mimeType": "image/png", "bytesBase64Encoded": "..." } ] }
# But param 'storageUri' implies it might be saved there.
# Let's check keys.
if 'bytesBase64Encoded' in pred:
print("\nImage generated successfully (Base64 received).")
# Optionally save it locally
# output_filename = "output_tryon.png"
# with open(output_filename, "wb") as f:
# f.write(base64.b64decode(pred['bytesBase64Encoded']))
# print(f"Saved to {output_filename}")
print(f"\nCheck your GCS bucket {gcs_bucket} for results if configured.")
except requests.exceptions.RequestException as e:
print(f"\nRequest Failed: {e}")
if hasattr(e, 'response') and e.response is not None:
print(f"Status Code: {e.response.status_code}")
print(f"Response Body: {e.response.text}")
def main():
parser = argparse.ArgumentParser(description="Google Vertex AI Virtual Try-On Client")
parser.add_argument("--project_id", help="Google Cloud Project ID")
parser.add_argument("--region", default="us-central1", help="GCP Region (default: us-central1)")
parser.add_argument("--gcs_bucket", required=True, help="GCS Bucket URI (e.g., gs://my-bucket)")
parser.add_argument("--person_image", required=True, help="Path to the person's image")
parser.add_argument("--product_image", required=True, help="Path to the product's image")
args = parser.parse_args()
virtual_try_on(
args.project_id,
args.region,
args.gcs_bucket,
args.person_image,
args.product_image
)
if __name__ == "__main__":
main()