selfitcamera commited on
Commit
1457e31
1 Parent(s): 75ec4ea
.DS_Store ADDED
Binary file (8.2 kB). View file
 
Datas/.DS_Store ADDED
Binary file (6.15 kB). View file
 
Datas/task3/.DS_Store ADDED
Binary file (8.2 kB). View file
 
Datas/task3/showcases/src01_flower-water.jpg ADDED
Datas/task3/showcases/src01_mountain-water.jpg ADDED
Datas/task3/showcases/src01_rock-on-water.jpg ADDED
Datas/task3/srcs/.DS_Store ADDED
Binary file (6.15 kB). View file
 
Datas/task3/srcs/src01.jpg ADDED
Datas/task3/temps/flow-water.jpg ADDED
Datas/task3/temps/flower-water.jpg ADDED
Datas/task3/temps/mountain-water.jpg ADDED
Datas/task3/temps/plant-desk.jpg ADDED
Datas/task3/temps/rock-on-water.jpg ADDED
Datas/task3/temps/snow-water.jpg ADDED
Datas/task3/temps/wood-flower.jpg ADDED
README.md CHANGED
@@ -4,7 +4,7 @@ emoji: 🔥
4
  colorFrom: purple
5
  colorTo: pink
6
  sdk: gradio
7
- sdk_version: 4.44.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
 
4
  colorFrom: purple
5
  colorTo: pink
6
  sdk: gradio
7
+ sdk_version: 4.40.0
8
  app_file: app.py
9
  pinned: false
10
  license: apache-2.0
app.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ from utils import *
3
+
4
+
5
+ taskType = "3"
6
+ temp_examples = get_temps_examples(taskType)
7
+ user_examples = get_user_examples(taskType)
8
+ showcase_examples = get_showcase_examples(taskType)
9
+ user_recorder = UserRecorder()
10
+
11
+ # 当试用次数耗尽,显示的信息
12
+ no_more_attempts = "Sorry, You've used all trial attempts. Please enter your token to continue..."
13
+
14
+ # Description
15
+ title = r"""
16
+ <h1 align="center">Selfit AI App: Product poster background generation</h1>
17
+ """
18
+
19
+ description = r"""
20
+ <a href='https://heybeauty.ai/extension' target='_blank'><b> Go to HeyBeauty for Faster and Free AI App! 🤗 </b></a>.<br>
21
+
22
+ <b>Official 🤗 Gradio demo</b> for <a href='https://github.com/selfitcamera/Outfit-Anyone-in-the-Wild' target='_blank'><b>Product poster background generation</b></a>.<br>
23
+ 1. Please wait for a while after submitting the task, you will get the result within 30 seconds.
24
+ 2. Share app with your friends and enjoy! 😊.<br>
25
+ """
26
+
27
+ css = """
28
+ .gradio-container {width: 85% !important}
29
+ """
30
+
31
+
32
+ def onClick(temp_image, user_image, caption_text, request: gr.Request):
33
+ print("======> temp_image ", type(temp_image), temp_image)
34
+ print("======> user_image ", type(user_image))
35
+ print("======> caption_text ", type(caption_text))
36
+ if temp_image is None:
37
+ yield None, "please choose a template background!!!"
38
+ return None, "please choose a template background!!!"
39
+
40
+ try:
41
+ client_ip = request.client.host
42
+ x_forwarded_for = dict(request.headers).get('x-forwarded-for')
43
+ if x_forwarded_for: client_ip = x_forwarded_for
44
+ if not check_region_warp(client_ip):
45
+ return None, "Failed !!! Our server is under maintenance, please try again later"
46
+
47
+ _, total_n, _ = user_recorder.get_record(client_ip)
48
+ if total_n>=LimitTask:
49
+ print(no_more_attempts)
50
+ yield None, no_more_attempts
51
+ return None, "no_more_attempts"
52
+
53
+ upload_url = upload_user_img(client_ip, user_image)
54
+ if len(upload_url)==0:
55
+ yield None, "fail to upload"
56
+ return None, "fail to upload"
57
+
58
+ taskId = publicSelfitTask(upload_url, temp_image, caption_text)
59
+ if not taskId:
60
+ yield None, "fail to public task..."
61
+ return None, "fail to public task..."
62
+
63
+ # taskId = "95a19e33-1ff5-446e-ac37-d3a8dd59eba8-e1"
64
+ max_try = 30
65
+ wait_s = 3
66
+ time.sleep(5)
67
+ for i in range(max_try):
68
+ time.sleep(wait_s)
69
+ taskStatus = getTaskRes(taskId)
70
+ if taskStatus is None: continue
71
+ user_recorder.save_record(taskStatus, ip=client_ip)
72
+
73
+ status = taskStatus['status']
74
+ if status in ['FAILED', 'CANCELLED', 'TIMED_OUT', ]:
75
+ yield None, f"task failed, query {i}, status {status}"
76
+ return None, f"task failed, query {i}, status {status}"
77
+ elif status in ['IN_QUEUE', 'IN_PROGRESS', 'IN_QUEUE', ]:
78
+ yield None, f"task is on processing, query {i}, status {status}"
79
+ elif status=='COMPLETED':
80
+ out = taskStatus['output']['job_results']['output1']
81
+ yield out, f"task is COMPLETED"
82
+ return out, f"{i} task COMPLETED"
83
+ yield None, "fail to query task.."
84
+ return None, "fail to query task.."
85
+ except Exception as e:
86
+ print(e)
87
+ # raise e
88
+ yield None, "fail to create task"
89
+ return None, "fail to create task"
90
+
91
+ def onLoad(request: gr.Request):
92
+ client_ip = request.client.host
93
+ x_forwarded_for = dict(request.headers).get('x-forwarded-for')
94
+ if x_forwarded_for:
95
+ client_ip = x_forwarded_for
96
+ his_datas, total_n, msg = user_recorder.get_record(client_ip)
97
+ left_n = max(0, LimitTask-total_n)
98
+ his_datas.append(msg)
99
+ his_datas.append(f"Submit ({left_n} attempts left)")
100
+ return his_datas
101
+
102
+ with gr.Blocks(css=css) as demo:
103
+ gr.Markdown(title)
104
+ gr.Markdown(description)
105
+
106
+ with gr.Row():
107
+ with gr.Column():
108
+ with gr.Column():
109
+ temp_image = gr.Image(sources='clipboard', type="filepath", label="Choose a template",
110
+ value=temp_examples[0][0])
111
+ temp_example = gr.Examples(inputs=[temp_image],
112
+ examples_per_page=9, examples=temp_examples)
113
+ with gr.Column():
114
+ with gr.Column():
115
+ user_image = gr.Image(value=None, type="numpy", label="product photo")
116
+ caption_text = gr.Textbox(value="", interactive=True,
117
+ label='English caption text(optional)')
118
+ with gr.Column():
119
+ with gr.Column():
120
+ res_image = gr.Image(label="generate image", value=None, type="filepath")
121
+ info_text = gr.Textbox(value="", interactive=False,
122
+ label='runtime information')
123
+ run_button = gr.Button(value="Submit")
124
+ MK01 = gr.Markdown()
125
+
126
+ with gr.Column():
127
+ show_case = gr.Examples(
128
+ examples=showcase_examples,
129
+ inputs=[temp_image, user_image, res_image, ],
130
+ label=None
131
+ )
132
+
133
+ with gr.Tab('history'):
134
+
135
+ with gr.Row():
136
+ MK02 = gr.Markdown()
137
+
138
+ with gr.Row():
139
+ his_input1 = gr.HTML()
140
+ his_output1 = gr.HTML()
141
+
142
+ with gr.Row():
143
+ his_input2 = gr.HTML()
144
+ his_output2 = gr.HTML()
145
+
146
+ with gr.Row():
147
+ his_input3 = gr.HTML()
148
+ his_output3 = gr.HTML()
149
+
150
+ run_button.click(fn=onClick, inputs=[temp_image, user_image, caption_text],
151
+ outputs=[res_image, info_text], concurrency_limit=50)
152
+ demo.load(onLoad, inputs=[], outputs=[his_input1, his_output1,
153
+ his_input2, his_output2, his_input3, his_output3,
154
+ MK02, run_button])
155
+
156
+ if __name__ == "__main__":
157
+
158
+ demo.queue(max_size=50)
159
+ # demo.queue(concurrency_count=60)
160
+ # demo.launch(server_name='0.0.0.0', server_port=225)
161
+ demo.launch(server_name='0.0.0.0')
162
+
requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ opencv-python
2
+ numpy
3
+ requests
4
+ gradio==4.40.0
5
+ gradio-client==1.2.0
6
+ func_timeout
7
+ Pillow==9.5.0
tools/run01_convert.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import sys
4
+ import cv2
5
+ import json
6
+ import random
7
+ import time
8
+ import pickle
9
+ import requests
10
+ import func_timeout
11
+ import numpy as np
12
+
13
+
14
+ proj_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
15
+ data_dir = os.path.join(proj_dir, 'Datas')
16
+
17
+ work_dir = os.path.join(data_dir, 'task3/temps')
18
+ for f in os.listdir(work_dir):
19
+ img = cv2.imread(os.path.join(work_dir, f))
20
+ cv2.imwrite(os.path.join(work_dir, f.replace(".png", ".jpg")), img)
21
+
utils.py ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import sys
4
+ import cv2
5
+ import json
6
+ import random
7
+ import time
8
+ import pickle
9
+ import requests
10
+ import func_timeout
11
+ import numpy as np
12
+ import gradio as gr
13
+ from collections import OrderedDict
14
+
15
+
16
+ apiUrl = os.environ['apiUrl']
17
+ uploadToken = os.environ['uploadToken']
18
+ openId = os.environ['openId']
19
+ apiKey = os.environ['apiKey']
20
+ Regions = os.environ['Regions']
21
+ LimitTask = int(os.environ['LimitTask'])
22
+
23
+
24
+ proj_dir = os.path.dirname(os.path.abspath(__file__))
25
+ data_dir = os.path.join(proj_dir, 'Datas')
26
+ tmpFolder = os.path.join(proj_dir, 'tmp')
27
+ os.makedirs(tmpFolder, exist_ok=True)
28
+
29
+
30
+
31
+ def load_pkl(path):
32
+ with open(path, 'rb') as f:
33
+ return pickle.load(f)
34
+
35
+ def save_pkl(data, path, reweite=False):
36
+ if not os.path.exists(path) or reweite: # 不存在或者强制重写
37
+ with open(path,'wb') as file:
38
+ pickle.dump(data, file, protocol=4)
39
+ return data
40
+ else:
41
+ load_data = load_pkl(path)
42
+ for k in data:
43
+ load_data[k] = data[k]
44
+ save_pkl(load_data, path, reweite=True)
45
+ return load_data
46
+
47
+ class UserRecorder(object):
48
+
49
+ def __init__(self, ):
50
+ super(UserRecorder, self).__init__()
51
+ record_dir = os.path.join(data_dir, 'UserRecord')
52
+ self.ip_dir = os.path.join(record_dir, 'Ips')
53
+ self.token_dir = os.path.join(record_dir, 'Tokens')
54
+ os.makedirs(self.ip_dir, exist_ok=True)
55
+ os.makedirs(self.token_dir, exist_ok=True)
56
+
57
+ def save_record(self, taskRes, ip=None, token=None):
58
+ if ip is None and token is None: return
59
+ if ip is not None:
60
+ record_path = os.path.join(self.ip_dir, f'{ip}.pkl')
61
+ else:
62
+ record_path = os.path.join(self.token_dir, f'{token}.pkl')
63
+ taskId = taskRes['id']
64
+ status = taskRes['status']
65
+ if 'output' in taskRes:
66
+ input1 = taskRes['output']['job_results']['input1']
67
+ output1 = taskRes['output']['job_results']['output1']
68
+ else:
69
+ input1, output1 = None, None
70
+ data = OrderedDict()
71
+ data[taskId] = {'input1':input1, 'output1':output1, 'status':status, }
72
+ save_data = save_pkl(data, record_path, reweite=False)
73
+ return save_data
74
+
75
+ def get_record(self, ip=None, token=None):
76
+ if ip is None and token is None: return
77
+ if ip is not None:
78
+ identity = ip
79
+ record_path = os.path.join(self.ip_dir, f'{ip}.pkl')
80
+ else:
81
+ identity = token
82
+ record_path = os.path.join(self.token_dir, f'{token}.pkl')
83
+ if os.path.exists(record_path):
84
+ record_data = load_pkl(record_path)
85
+ else:
86
+ record_data = {}
87
+ total_n = len(record_data)
88
+ success_n, fail_n, process_n = 0, 0, 0
89
+ shows = [None]*6
90
+ show_i = 0
91
+ print(record_data)
92
+ for key in reversed(record_data):
93
+ status = record_data[key]['status']
94
+ if status in ['FAILED', 'CANCELLED', 'TIMED_OUT', ]:
95
+ fail_n += 1
96
+
97
+ elif status in ['COMPLETED', ]:
98
+ success_n += 1
99
+ if record_data[key]['input1'] is not None:
100
+ input1 = record_data[key]['input1']
101
+ output1 = record_data[key]['output1']
102
+ shows[show_i*2] = f"<img src=\"{input1}\" >"
103
+ shows[show_i*2+1] = f"<img src=\"{output1}\" >"
104
+ show_i += 1
105
+ elif status in ['IN_QUEUE', 'IN_PROGRESS', 'IN_QUEUE', ]:
106
+ process_n += 1
107
+
108
+ msg = f"Dear {identity}, You have {total_n} tasks, {success_n} successed, {fail_n} failed, {process_n} processing, "
109
+
110
+ return shows, total_n, msg
111
+
112
+
113
+ def get_temps_examples(taskType):
114
+ temp_dir = os.path.join(data_dir, f'task{taskType}/temps')
115
+ examples = []
116
+ files = [f for f in sorted(os.listdir(temp_dir)) if '.' in f]
117
+ for f in files:
118
+ temp_name = f.split(".")[0]
119
+ if len(temp_name)==0: continue
120
+ temp_path = os.path.join(temp_dir, f)
121
+ examples.append([temp_path])
122
+ return examples
123
+
124
+ def get_user_examples(taskType):
125
+ user_dir = os.path.join(data_dir, f'task{taskType}/srcs')
126
+ examples = []
127
+ files = [f for f in sorted(os.listdir(user_dir)) if '.' in f]
128
+ for f in files:
129
+ user_id = f.split(".")[0]
130
+ if len(user_id)==0: continue
131
+ user_path = os.path.join(user_dir, f)
132
+ examples.append([user_path])
133
+ return examples
134
+
135
+ def get_showcase_examples(taskType):
136
+ if taskType=="3":
137
+ examples=[
138
+ ["task3/temps/flow-water.jpg", "task3/srcs/src01.jpg", "task3/showcases/src01_flower-water.jpg"],
139
+ ["task3/temps/mountain-water.jpg", "task3/srcs/src01.jpg", "task3/showcases/src01_mountain-water.jpg"],
140
+ ["task3/temps/rock-on-water.jpg", "task3/srcs/src01.jpg", "task3/showcases/src01_rock-on-water.jpg"],
141
+ ]
142
+ for i in range(len(examples)):
143
+ for j in range(len(examples[i])):
144
+ examples[i][j] = os.path.join(data_dir, examples[i][j])
145
+ assert os.path.exists(examples[i][j]), examples[i][j]
146
+ return examples
147
+
148
+ def get_result_example(cloth_id, pose_id):
149
+ result_dir = os.path.join(data_dir, 'ResultImgs')
150
+ res_path = os.path.join(result_dir, f"{cloth_id}_{pose_id}.jpg")
151
+ return res_path
152
+
153
+ def upload_user_img(clientIp, img):
154
+ timeId = int( str(time.time()).replace(".", "") )+random.randint(1000, 9999)
155
+ fileName = clientIp.replace(".", "")+str(timeId)+".jpg"
156
+ local_path = os.path.join(tmpFolder, fileName)
157
+ cv2.imwrite(os.path.join(tmpFolder, fileName), img[:,:,::-1])
158
+ params = {'token':uploadToken, 'input1':fileName, 'input2':''}
159
+ session = requests.session()
160
+ ret = requests.post(f"{apiUrl}/upload", data=json.dumps(params))
161
+ res = ""
162
+ if ret.status_code==200:
163
+ if 'upload1' in ret.json():
164
+ upload_url = ret.json()['upload1']
165
+ with open(local_path, 'rb') as file:
166
+ response = requests.put(upload_url, data=file)
167
+ if response.status_code == 200:
168
+ res = upload_url
169
+ else:
170
+ print(ret.json(), ret.status_code, 'call upload failed')
171
+ if os.path.exists(local_path):
172
+ os.remove(local_path)
173
+ return res
174
+
175
+
176
+ def publicSelfitTask(image, temp_image, caption_text):
177
+ temp_name = os.path.basename(temp_image).split('.')[0]
178
+ params = {'openId':openId, 'apiKey':apiKey, 'image':image, 'mask':"",
179
+ "image_type":"2", "task_type":"3", 'param1':temp_name,
180
+ 'param2':str(caption_text), 'param3':"1", 'param4':"", 'param5':""}
181
+ session = requests.session()
182
+ ret = requests.post(f"{apiUrl}/public", data=json.dumps(params))
183
+ print(ret)
184
+ if ret.status_code==200:
185
+ if 'id' in ret.json():
186
+ print(ret.json())
187
+ return ret.json()['id']
188
+ else:
189
+ print(ret.json(), ret.status_code, 'call public failed')
190
+
191
+ def getTaskRes(taskId):
192
+ params = {'id':taskId}
193
+ session = requests.session()
194
+ ret = requests.post(f"{apiUrl}/status", data=json.dumps(params))
195
+ print(ret)
196
+ if ret.status_code==200:
197
+ if 'status' in ret.json():
198
+ print(ret.json())
199
+ return ret.json()
200
+ else:
201
+ print(ret.json(), ret.status_code, 'call status failed')
202
+ return None
203
+
204
+ @func_timeout.func_set_timeout(10)
205
+ def check_region(ip):
206
+ session = requests.session()
207
+ ret = requests.get(f"https://webapi-pc.meitu.com/common/ip_location?ip={ip}")
208
+ for k in ret.json()['data']:
209
+ nat = ret.json()['data'][k]['nation']
210
+ if nat in Regions:
211
+ print(nat, 'invalid')
212
+ return False
213
+ else:
214
+ print(nat, 'valid')
215
+ return True
216
+ def check_region_warp(ip):
217
+ try:
218
+ return check_region(ip)
219
+ except Exception as e:
220
+ print(e)
221
+ return True