Zuii commited on
Commit
9b05d2a
Β·
verified Β·
1 Parent(s): 7152ff6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -99
app.py CHANGED
@@ -1,116 +1,66 @@
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
- # πŸ“© Setup request payload (matches the curl command structure)
54
- data = {
55
- "image": encoded_person_img,
56
- "format": "png"
57
- }
58
 
59
 
60
- result_img = None
61
- max_retries = 5
62
- retry_delay = 5
 
 
63
 
64
- try:
65
- session = requests.Session()
66
-
67
- # πŸ” Retry loop for "Too many users" error
68
- for attempt in range(max_retries):
69
- response = session.post(url, headers=headers, json=data, timeout=60)
70
- print("Response code:", response.status_code)
71
-
72
- # βœ… Success β€” process the result
73
- if response.status_code == 200:
74
- result_url = response.json().get('result_url', '')
75
- print("βœ… Success:", result_url)
76
-
77
- # If Pixelcut returns a result URL, fetch the final image
78
- if result_url:
79
- result_img_data = requests.get(result_url).content
80
- result_np = np.frombuffer(result_img_data, np.uint8)
81
- result_img = cv2.imdecode(result_np, cv2.IMREAD_UNCHANGED)
82
- info = "Success"
83
- break
84
-
85
- else:
86
- # πŸ”₯ If API returns "Too many users" error, retry with delay
87
- print("Full response:", response.text)
88
- if "Too many users" in response.text:
89
- print(f"Attempt {attempt + 1}/{max_retries}: API busy. Retrying in {retry_delay} seconds...")
90
- time.sleep(retry_delay)
91
- else:
92
- info = f"Error: {response.status_code} - {response.text}"
93
- break
94
 
95
- else:
96
- # ❌ If all retries fail
97
- info = "API still overloaded β€” please try again later."
 
 
 
 
 
 
98
 
99
- # πŸ›‘ Handle timeouts specifically
100
- except requests.exceptions.ReadTimeout:
101
- print("Timeout!")
102
- info = "Too many users, please try again later"
103
- raise gr.Error("Too many users, please try again later")
104
 
105
- # ❗ Handle any other unexpected errors
106
- except Exception as err:
107
- print(f"❌ Other error: {err}")
108
- info = "Error, please contact the admin"
 
109
 
110
- end_time = time.time()
111
- print(f"⏳ Time used: {end_time - start_time:.2f} seconds")
112
 
113
- return result_img, seed, info
114
 
115
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
116
 
 
 
1
  import requests
 
 
 
 
 
 
2
  import gradio as gr
3
 
4
+ # Set your Pixelcut API key directly
5
+ API_KEY = "sk_7c19e4f2ad434a3ebc70fdd85ade5309"
6
 
7
+ # Function to remove background from a local image file
8
+ def remove_bg(image_path):
9
+ try:
10
+ with open(image_path, "rb") as image_file:
11
+ response = requests.post(
12
+ "https://api.developer.pixelcut.ai/v1/remove-background",
13
+ headers={
14
+ "Accept": "application/json",
15
+ "X-API-KEY": API_KEY,
16
+ },
17
+ files={"image": image_file},
18
+ data={"format": "png"},
19
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
+ # Handle API response
22
+ if response.status_code == 200:
23
+ result = response.json()
24
+ return result["output_url"] # Return the output image URL from API
25
+ else:
26
+ return f"Error: {response.status_code} - {response.json()['error']}"
 
27
 
28
+ except Exception as e:
29
+ return f"Exception: {e}"
 
 
 
30
 
31
 
32
+ # Define the Tryonn function without CSS
33
+ def tryonn(person_image, garment_image):
34
+ # Process the images using the Pixelcut API
35
+ person_result = remove_bg(person_image)
36
+ garment_result = remove_bg(garment_image)
37
 
38
+ # If both images are processed successfully, combine them (mock-up display)
39
+ if "Error" not in person_result and "Error" not in garment_result:
40
+ return person_result, garment_result, "βœ… Success!"
41
+ else:
42
+ return person_result, garment_result, "❌ Failed, check errors."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
+ # Gradio interface setup (CSS removed)
45
+ with gr.Blocks() as Tryon:
46
+ gr.Markdown("## Upload a Person Image and Garment Image")
47
+ with gr.Row():
48
+ person_input = gr.Image(type="filepath", label="Person Image")
49
+ garment_input = gr.Image(type="filepath", label="Garment Image")
50
+ output_person = gr.Image(label="Processed Person Image")
51
+ output_garment = gr.Image(label="Processed Garment Image")
52
+ status = gr.Textbox(label="Status")
53
 
54
+ submit_button = gr.Button("Run Try-On")
 
 
 
 
55
 
56
+ submit_button.click(
57
+ fn=tryonn,
58
+ inputs=[person_input, garment_input],
59
+ outputs=[output_person, output_garment, status],
60
+ )
61
 
62
+ Tryon.launch()
 
63
 
 
64
 
65
  example_path = os.path.join(os.path.dirname(__file__), 'assets')
66