aeon12 commited on
Commit
92d33f0
·
verified ·
1 Parent(s): f2c7008

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -48
app.py CHANGED
@@ -1,51 +1,160 @@
1
- def virtual_tryon(job):
2
- print('Started processing')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  try:
5
- # Parse the JSON input
6
- job_input = job["input"]
7
- product_image_base64 = job_input.get('product_image')
8
- user_image_base64 = job_input.get('user_image')
9
- background = job_input.get('background')
10
- print('Input parsed')
11
-
12
- # Convert base64 images to PIL Image
13
- user_image = base64_to_pil_image(user_image_base64)
14
- user_image.convert('RGB').save('/tmp/user.jpg')
15
- print('User image saved')
16
-
17
- product_image = base64_to_pil_image(product_image_base64)
18
- product_image.convert('RGB').save('/tmp/product.jpg')
19
- print('Product image saved')
20
-
21
- # Create SDXL pipeline
22
- pipeline = create_sdxl_pipeline_with_dinov2(MODEL_NAME)
23
- print('Pipeline generated')
24
- segment_cloth = "dress cloth sweater shirt tshirt"
25
-
26
- # Describe the garment
27
- garment_description, gender_description, garment_description_full = describe_garment('/tmp/product.jpg', '/tmp/user.jpg')
28
-
29
- if 'hood' in garment_description:
30
- garment_description = 'hoodie'
31
- prompt = f"photo at dusk, a {gender_description} wearing {garment_description}, background is {background}, 35 mm film camera"
32
- insight = Insight_Face2(MODEL_NAME, LORA_CKPT, IMAGE_ENCODER_CKPT, FACE_MODEL_PATH)
33
- single_image = insight.generate(prompt, NEGATIVE_PROMPT, 1, user_image)
34
- single_image.save('/tmp/Single_IP_Result.jpg')
35
-
36
- # Virtual Try-on
37
- ip_weight = 0.5
38
- virt_try = VirtualTryon(MODEL_NAME, pipeline, ip_weight, IMAGE_ENCODER_CKPT, segment_cloth)
39
- final_im = virt_try.generate(garment_description_full, NEGATIVE_PROMPT, product_image, single_image)
40
- final_im.save('/tmp/Try_on.jpg')
41
-
42
- final_im = np.asarray(final_im)
43
- final_im = cv2.cvtColor(final_im, cv2.COLOR_BGR2RGB)
44
-
45
- _, buffer = cv2.imencode('.png', final_im)
46
- image_base64 = base64.b64encode(buffer).decode('utf-8')
47
-
48
- return {"output": image_base64}
49
  except Exception as e:
50
- print(f"An error occurred: {str(e)}")
51
- return {"error": str(e)}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import base64
4
+ import time
5
+ import os
6
+ from PIL import Image
7
+ import io
8
+ import json
9
+
10
+ API_KEY = 'N80HWHVG3DV8URRNYZY382UPSHP1N8G1SNPYG0E9'
11
+ API_URL = 'https://api.runpod.ai/v2/31jyh9kh7nwyga'
12
+
13
+ # ... [previous code for cloth_images, user_images, and scene_options remains unchanged] ...
14
+
15
+ def get_base64_from_url(url):
16
+ response = requests.get(url)
17
+ return base64.b64encode(response.content).decode('utf-8')
18
+
19
+ def get_base64_from_image(image):
20
+ buffered = io.BytesIO()
21
+ image.save(buffered, format="PNG")
22
+ return base64.b64encode(buffered.getvalue()).decode('utf-8')
23
+
24
+ def generate_tryon(cloth_input, user_input, background):
25
+ if isinstance(cloth_input, str): # URL selected
26
+ cloth_base64 = get_base64_from_url(cloth_input)
27
+ else: # Image uploaded
28
+ cloth_base64 = get_base64_from_image(cloth_input)
29
 
30
+ if isinstance(user_input, str): # URL selected
31
+ user_base64 = get_base64_from_url(user_input)
32
+ else: # Image uploaded
33
+ user_base64 = get_base64_from_image(user_input)
34
+
35
+ input_data = {
36
+ "user_image": user_base64,
37
+ "product_image": cloth_base64,
38
+ "background": background
39
+ }
40
+
41
+ # Prepare log message
42
+ log_data = {
43
+ "user_image": user_base64[:20] + '...' if user_base64 else 'undefined',
44
+ "product_image": cloth_base64[:20] + '...' if cloth_base64 else 'undefined',
45
+ "background": background,
46
+ }
47
+ log_message = f"Sending data:\n{json.dumps(log_data, indent=2)}"
48
+
49
+ response = requests.post(
50
+ f"{API_URL}/run",
51
+ headers={
52
+ "Authorization": f"Bearer {API_KEY}",
53
+ "Content-Type": "application/json"
54
+ },
55
+ json=input_data
56
+ )
57
+
58
+ if not response.ok:
59
+ error_text = response.text
60
+ raise Exception(f"Failed to upload image: {response.status_code} {response.reason} - {error_text}")
61
+
62
+ job_id = response.json()['id']
63
+
64
+ while True:
65
+ status_response = requests.get(
66
+ f"{API_URL}/status/{job_id}",
67
+ headers={"Authorization": f"Bearer {API_KEY}"}
68
+ )
69
+
70
+ if not status_response.ok:
71
+ raise Exception(f"Status check failed: {status_response.status_code} {status_response.reason} - {status_response.text}")
72
+
73
+ status_data = status_response.json()
74
+ if status_data['status'] == 'COMPLETED':
75
+ output_base64 = status_data['output']['output']
76
+ output_image = Image.open(io.BytesIO(base64.b64decode(output_base64)))
77
+ return output_image, log_message
78
+ elif status_data['status'] == 'FAILED':
79
+ raise Exception(f"Job processing failed: {status_data}")
80
+
81
+ time.sleep(2)
82
+
83
+ def tryon_interface(cloth_selected, cloth_upload, user_selected, user_upload, scene_selection, custom_scene):
84
+ cloth = cloth_upload if cloth_upload is not None else cloth_selected
85
+ user = user_upload if user_upload is not None else user_selected
86
+ background = custom_scene if custom_scene else scene_selection
87
+
88
+ if not cloth:
89
+ return None, "Please select or upload a clothing image.", ""
90
+ if not user:
91
+ return None, "Please select or upload a user image.", ""
92
+ if not background:
93
+ return None, "Please select or enter a background scene.", ""
94
+
95
  try:
96
+ result_image, log_message = generate_tryon(cloth, user, background)
97
+ return result_image, "Try-on image generated successfully!", log_message
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  except Exception as e:
99
+ return None, f"Error: {str(e)}", ""
100
+
101
+ def select_image(evt: gr.SelectData, image_list):
102
+ if evt.index < len(image_list):
103
+ return image_list[evt.index]["url"]
104
+ return None
105
+
106
+ with gr.Blocks() as demo:
107
+ gr.Markdown("# Virtual Try-On Application")
108
+
109
+ with gr.Row():
110
+ with gr.Column():
111
+ gr.Markdown("## Available Clothing")
112
+ cloth_gallery = gr.Gallery(
113
+ [img["url"] for img in cloth_images],
114
+ label="Click to select clothing",
115
+ columns=4,
116
+ height=500
117
+ )
118
+ cloth_selected = gr.Textbox(label="Selected Clothing URL", visible=False)
119
+ cloth_upload = gr.Image(label="Or Upload Custom Clothing")
120
+
121
+ with gr.Column():
122
+ gr.Markdown("## Available User Images")
123
+ user_gallery = gr.Gallery(
124
+ [img["url"] for img in user_images],
125
+ label="Click to select user image",
126
+ columns=3,
127
+ height=500
128
+ )
129
+ user_selected = gr.Textbox(label="Selected User Image URL", visible=False)
130
+ user_upload = gr.Image(label="Or Upload Custom User Image")
131
+
132
+ with gr.Row():
133
+ scene_selection = gr.Dropdown(choices=scene_options, label="Select Scene")
134
+ custom_scene = gr.Textbox(label="Or Enter Custom Scene")
135
+
136
+ generate_button = gr.Button("Generate Try-On")
137
+
138
+ output_image = gr.Image(label="Try-On Result")
139
+ output_text = gr.Textbox(label="Status")
140
+ log_output = gr.Textbox(label="API Request Details", lines=10)
141
+
142
+ cloth_gallery.select(
143
+ fn=lambda evt: select_image(evt, cloth_images),
144
+ inputs=[cloth_gallery],
145
+ outputs=[cloth_selected]
146
+ )
147
+
148
+ user_gallery.select(
149
+ fn=lambda evt: select_image(evt, user_images),
150
+ inputs=[user_gallery],
151
+ outputs=[user_selected]
152
+ )
153
+
154
+ generate_button.click(
155
+ tryon_interface,
156
+ inputs=[cloth_selected, cloth_upload, user_selected, user_upload, scene_selection, custom_scene],
157
+ outputs=[output_image, output_text, log_output]
158
+ )
159
+
160
+ demo.launch()