Zuii commited on
Commit
5d7df65
Β·
verified Β·
1 Parent(s): f7221f1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +102 -57
app.py CHANGED
@@ -1,62 +1,107 @@
 
1
  import requests
 
 
 
2
  import base64
3
-
4
- # --- Configuration ---
5
- API_KEY = "sk_7c19e4f2ad434a3ebc70fdd85ade5309"
6
- PERSON_IMAGE_PATH = "path_to_person_image.jpg"
7
- GARMENT_IMAGE_PATH = "path_to_garment_image.jpg"
8
-
9
- # --- Helper Function: Read Image and Convert to Base64 ---
10
- def encode_image(image_path):
11
- with open(image_path, "rb") as image_file:
12
- return base64.b64encode(image_file.read()).decode("utf-8")
13
-
14
- # --- Step 1: Remove Background from Person Image ---
15
- def remove_background(image_path):
16
- with open(image_path, "rb") as image_file:
17
- response = requests.post(
18
- "https://api.developer.pixelcut.ai/v1/remove-background",
19
- headers={
20
- "Accept": "application/json",
21
- "X-API-KEY": API_KEY,
22
- },
23
- files={"image": image_file},
24
- data={"format": "png"},
25
- )
26
-
27
- if response.status_code == 200:
28
- return response.json().get("url")
29
- else:
30
- print("Error:", response.json())
31
- return None
32
-
33
- # --- Step 2: Try-On Function ---
34
- def tryonn(person_image_path, garment_image_path):
35
- # Get background-removed URLs
36
- person_url = remove_background(person_image_path)
37
- garment_url = remove_background(garment_image_path)
38
-
39
- if not person_url or not garment_url:
40
- print("Failed to process images!")
41
- return
42
-
43
- # Make the try-on API call
44
- tryon_response = requests.post(
45
- "https://api.example.com/v1/tryon",
46
- headers={"Accept": "application/json", "X-API-KEY": API_KEY},
47
- json={"person_image_url": person_url, "garment_image_url": garment_url},
48
- )
49
-
50
- if tryon_response.status_code == 200:
51
- tryon_result_url = tryon_response.json().get("result_url")
52
- print("Try-On Success! Result:", tryon_result_url)
53
- else:
54
- print("Try-On Failed:", tryon_response.json())
55
-
56
- # --- Execute the try-on function ---
57
- tryonn(PERSON_IMAGE_PATH, GARMENT_IMAGE_PATH)
58
-
59
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
62
 
 
1
+ import os
2
  import requests
3
+ import json
4
+ import time
5
+ import cv2
6
  import base64
7
+ import random
8
+ import numpy as np
9
+ import gradio as gr
10
+
11
+ MAX_SEED = 999999
12
+
13
+ # βœ… Hardcoded Pixelcut API key
14
+ pixelcut_api_key = "sk_7c19e4f2ad434a3ebc70fdd85ade5309"
15
+
16
+
17
+ # Convert images to PNG format
18
+ def convert_to_png(image):
19
+ return cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
20
+
21
+
22
+ # Encode images to base64 PNG format
23
+ def encode_image(image):
24
+ image = convert_to_png(image)
25
+ _, buffer = cv2.imencode('.png', image)
26
+ return base64.b64encode(buffer).decode('utf-8')
27
+
28
+
29
+ # Main try-on function using Pixelcut API
30
+ def tryon(person_img, garment_img, seed, randomize_seed):
31
+ start_time = time.time()
32
+
33
+ # πŸ›‘ Check if images are provided
34
+ if person_img is None or garment_img is None:
35
+ return None, None, "Empty image"
36
+
37
+ # 🎲 Handle seed randomization
38
+ if randomize_seed:
39
+ seed = random.randint(0, MAX_SEED)
40
+
41
+ # πŸ”₯ Convert images to base64 PNG
42
+ encoded_person_img = encode_image(person_img)
43
+ encoded_garment_img = encode_image(garment_img)
44
+
45
+ # 🌟 Setup Pixelcut API endpoint and headers
46
+ url = "https://api.developer.pixelcut.ai/v1/remove-background"
47
+ headers = {
48
+ 'Content-Type': 'application/json',
49
+ 'Accept': 'application/json',
50
+ 'X-API-KEY': pixelcut_api_key
51
+ }
52
+
53
+ # πŸ”§ Send person image for background removal
54
+ person_data = {"image": encoded_person_img, "format": "png"}
55
+ garment_data = {"image": encoded_garment_img, "format": "png"}
56
+
57
+ try:
58
+ # πŸš€ Process Person Image
59
+ person_response = requests.post(url, headers=headers, json=person_data, timeout=60)
60
+ if person_response.status_code == 200:
61
+ person_result_url = person_response.json().get('url', '')
62
+ else:
63
+ return None, None, f"Person image error: {person_response.status_code}"
64
+
65
+ # πŸš€ Process Garment Image
66
+ garment_response = requests.post(url, headers=headers, json=garment_data, timeout=60)
67
+ if garment_response.status_code == 200:
68
+ garment_result_url = garment_response.json().get('url', '')
69
+ else:
70
+ return None, None, f"Garment image error: {garment_response.status_code}"
71
+
72
+ # πŸ”₯ Call the try-on API with both processed images
73
+ tryon_url = "https://api.example.com/v1/tryon"
74
+ tryon_payload = {
75
+ "person_image_url": person_result_url,
76
+ "garment_image_url": garment_result_url
77
+ }
78
+ tryon_response = requests.post(tryon_url, headers=headers, json=tryon_payload, timeout=60)
79
+
80
+ # βœ… Handle the try-on result
81
+ if tryon_response.status_code == 200:
82
+ result_url = tryon_response.json().get('result_url', '')
83
+ result_img_data = requests.get(result_url).content
84
+ result_np = np.frombuffer(result_img_data, np.uint8)
85
+ result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
86
+ info = "Success"
87
+ else:
88
+ info = f"Try-On error: {tryon_response.status_code}"
89
+
90
+ # πŸ›‘ Handle timeout or API errors
91
+ except requests.exceptions.ReadTimeout:
92
+ print("Timeout!")
93
+ info = "Too many users, please try again later"
94
+ raise gr.Error("Too many users, please try again later")
95
+
96
+ except Exception as err:
97
+ print(f"❌ Other error: {err}")
98
+ info = "Error, please contact the admin"
99
+ result_img = None
100
+
101
+ end_time = time.time()
102
+ print(f"⏳ Time used: {end_time - start_time:.2f} seconds")
103
+
104
+ return result_img, seed, info
105
 
106
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
107