daili0015 commited on
Commit
0173443
·
verified ·
1 Parent(s): d788d33

Upload 7 files

Browse files
Files changed (7) hide show
  1. .gitattributes +36 -35
  2. .gitignore +2 -0
  3. README.md +13 -13
  4. app.py +133 -0
  5. push.sh +9 -0
  6. requirements.txt +8 -0
  7. utils.py +176 -0
.gitattributes CHANGED
@@ -1,35 +1,36 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.jpg filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ order.txt
2
+ push.sh
README.md CHANGED
@@ -1,13 +1,13 @@
1
- ---
2
- title: Vtondemo
3
- emoji: 🏆
4
- colorFrom: pink
5
- colorTo: indigo
6
- sdk: gradio
7
- sdk_version: 5.16.0
8
- app_file: app.py
9
- pinned: false
10
- license: apache-2.0
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: Vtondemo
3
+ emoji: 🏆
4
+ colorFrom: pink
5
+ colorTo: indigo
6
+ sdk: gradio
7
+ sdk_version: 5.16.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: apache-2.0
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import cv2
3
+ from mtcnn.mtcnn import MTCNN
4
+ from utils import *
5
+
6
+
7
+ cloth_examples = get_cloth_examples(hr=0)
8
+ cloth_hr_examples = get_cloth_examples(hr=1)
9
+ pose_examples = get_pose_examples()
10
+ face_detector = MTCNN()
11
+
12
+ # Description
13
+ title = r"""
14
+ <h1 align="center">VTON Test Demo</h1>
15
+ """
16
+
17
+
18
+ def onClick(cloth_image, pose_image, request: gr.Request):
19
+ if pose_image is None:
20
+ yield None, "no pose image found !", ""
21
+ return None, "no pose image found !", ""
22
+ if cloth_image is None:
23
+ yield None, "no cloth image found !", ""
24
+ return None, "no cloth image found !", ""
25
+
26
+ pose_id = os.path.basename(pose_image).split(".")[0]
27
+ cloth_id = int(os.path.basename(cloth_image).split(".")[0])
28
+
29
+ try:
30
+
31
+ client_ip = request.client.host
32
+ x_forwarded_for = dict(request.headers).get('x-forwarded-for')
33
+ if x_forwarded_for:
34
+ client_ip = x_forwarded_for
35
+
36
+ pose_np = cv2.imread(pose_image)
37
+ faces = face_detector.detect_faces(pose_np[:,:,::-1])
38
+ if len(faces)==0:
39
+ print(client_ip, 'faces num is 0! ', flush=True)
40
+ yield None, "Fatal Error !!! No face detected !!! You must upload a human photo!!! Not clothing photo!!!", ""
41
+ return None, "Fatal Error !!! No face detected !!! You must upload a human photo!!! Not clothing photo!!!", ""
42
+ else:
43
+ x, y, w, h = faces[0]["box"]
44
+ H, W = pose_np.shape[:2]
45
+ max_face_ratio = 1/3.3
46
+ if w/W>max_face_ratio or h/H>max_face_ratio:
47
+ yield None, "Fatal Error !!! Headshot is not allowed !!! You must upload a full-body or half-body photo!!!", ""
48
+ return None, "Fatal Error !!! Headshot is not allowed !!! You must upload a full-body or half-body photo!!!", ""
49
+
50
+ if not check_region_warp(client_ip):
51
+ yield None, "Failed !!! Our server is under maintenance, please try again later", ""
52
+ return None, "Failed !!! Our server is under maintenance, please try again later", ""
53
+
54
+ # client_ip = '8.8.8.8'
55
+ yield None, "begin to upload ", ""
56
+
57
+ timeId = int( str(time.time()).replace(".", "") )+random.randint(1000, 9999)
58
+ upload_url = upload_pose_img(client_ip, timeId, pose_image)
59
+ # exit(0)
60
+ yield None, "begin to public task ", ""
61
+ # return None, "begin to public task ", ""
62
+
63
+ if len(upload_url)==0:
64
+ yield None, "fail to upload", ""
65
+ return None, "fail to upload", ""
66
+
67
+ public_res = publicClothSwap(upload_url, cloth_id, is_hr=0)
68
+ if public_res is None:
69
+ yield None, "fail to public you task", ""
70
+ return None, "fail to public you task", ""
71
+
72
+ print(client_ip, public_res['mid_result'])
73
+ yield public_res['mid_result'], f"task is processing", ""
74
+
75
+ max_try = 120*3
76
+ wait_s = 0.5
77
+ for i in range(max_try):
78
+ time.sleep(wait_s)
79
+ state = getInfRes(public_res['id'])
80
+ timestamp = int(time.time() * 1000)
81
+ if state is None:
82
+ yield None, "task query failed,", ""
83
+ elif state['status']=='PROCESSING':
84
+ yield None, f"wait {i}", ""
85
+ elif state['status']=='SUCCEED':
86
+ yield state['output1'] + f"?t={timestamp}", f"task finished, {state['msg']}", ""
87
+ return state['output1'] + f"?t={timestamp}", f"task finished, {state['msg']}", ""
88
+ elif state['status']=='FAILED':
89
+ yield None, f"task failed, {state['msg']}", ""
90
+ return None, f"task failed, {state['msg']}", ""
91
+ else:
92
+ yield None, f"{i}", ""
93
+ return None, "no machine...", ""
94
+ except Exception as e:
95
+ print(e)
96
+ raise e
97
+ return None, "fail to create task", ""
98
+
99
+ with gr.Blocks() as demo:
100
+ gr.Markdown(title)
101
+
102
+ with gr.Row():
103
+ with gr.Column():
104
+ cloth_image = gr.Image(value=None, interactive=False, type="filepath", label="choose a clothing")
105
+ example = gr.Examples(inputs=cloth_image,examples_per_page=20,examples=cloth_examples, label="clothing")
106
+ hr_example = gr.Examples(inputs=cloth_image,examples_per_page=9,examples=cloth_hr_examples, label="invalid clothing")
107
+
108
+ with gr.Column():
109
+ pose_image = gr.Image(value=None, type="filepath", label="choose/upload a photo")
110
+ example_pose = gr.Examples(inputs=pose_image,
111
+ examples_per_page=20,
112
+ examples=pose_examples)
113
+
114
+ with gr.Column():
115
+ with gr.Column():
116
+
117
+ run_button = gr.Button(value="Submit")
118
+ info_text = gr.Textbox(value="", interactive=False,
119
+ label='log')
120
+ res_image = gr.Image(label="result image", value=None, type="filepath")
121
+ MK01 = gr.Markdown()
122
+
123
+ run_button.click(fn=onClick, inputs=[cloth_image, pose_image],
124
+ outputs=[res_image, info_text, MK01])
125
+
126
+
127
+ if __name__ == "__main__":
128
+
129
+ demo.queue(max_size=50)
130
+ # demo.queue(concurrency_count=60)
131
+ # demo.launch(server_name='0.0.0.0', server_port=225)
132
+ demo.launch(server_name='0.0.0.0')
133
+
push.sh ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+
2
+
3
+ git config --global http.proxy http://127.0.0.1:7890
4
+ git config --global https.proxy http://127.0.0.1:7890
5
+
6
+ git add .
7
+ git commit -m "init"
8
+ git push
9
+
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ opencv-python
2
+ numpy
3
+ requests
4
+ gradio==4.40.0
5
+ gradio-client==1.2.0
6
+ func_timeout
7
+ mtcnn
8
+ tensorflow
utils.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import os
3
+ import sys
4
+ import cv2
5
+ import json
6
+ import random
7
+ import time
8
+ import requests
9
+ import func_timeout
10
+ import numpy as np
11
+ import gradio as gr
12
+
13
+
14
+ OssUrl = ""
15
+ Regions = ""
16
+ TOKEN = os.environ['TOKEN']
17
+ UKAPIURL = os.environ['UKAPIURL']
18
+
19
+
20
+ proj_dir = os.path.dirname(os.path.abspath(__file__))
21
+ data_dir = os.path.join(proj_dir, 'Datas')
22
+ # data_dir = "Datas"
23
+ tmpFolder = "tmp"
24
+ os.makedirs(tmpFolder, exist_ok=True)
25
+
26
+
27
+ def get_cloth_examples(hr=0):
28
+ cloth_dir = os.path.join(data_dir, 'ClothImgs')
29
+ examples = []
30
+ files = sorted(os.listdir(cloth_dir))
31
+ hr_clothes = list(range(588, 597))
32
+ # hr_clothes = []
33
+ for f in files:
34
+ if '.jpg' not in f and '.png' not in f:
35
+ continue
36
+
37
+ cloth_id = f.split(".")[0]
38
+ if int(cloth_id) in hr_clothes and hr==0:
39
+ continue
40
+ if int(cloth_id) not in hr_clothes and hr==1:
41
+ continue
42
+
43
+ cloth_path = os.path.join(cloth_dir, f)
44
+ examples.append(cloth_path)
45
+ examples = examples[::-1]
46
+ return examples
47
+
48
+ def get_pose_examples():
49
+ pose_dir = os.path.join(data_dir, 'PoseImgs')
50
+ examples = []
51
+ for f in os.listdir(pose_dir):
52
+ if '.jpg' not in f and '.png' not in f:
53
+ continue
54
+ pose_id = f.split(".")[0]
55
+ pose_path = os.path.join(pose_dir, f)
56
+ examples.append(pose_path)
57
+ return examples
58
+
59
+ def get_result_example(cloth_id, pose_id):
60
+ result_dir = os.path.join(data_dir, 'ResultImgs')
61
+ res_path = os.path.join(result_dir, f"{cloth_id}_{pose_id}.jpg")
62
+ return res_path
63
+
64
+ # def get_tips():
65
+ # path1 = OssUrl+'ClothData/Publics/PoseGuide/tip1.jpg'
66
+ # path2 = OssUrl+'ClothData/Publics/PoseGuide/tip2.jpg'
67
+ # return path1, path2
68
+
69
+ def upload_pose_img(clientIp, timeId, img):
70
+ fileName = clientIp.replace(".", "")+str(timeId)+".jpg"
71
+ local_path = os.path.join(tmpFolder, fileName)
72
+ img = cv2.imread(img)
73
+ cv2.imwrite(os.path.join(tmpFolder, fileName), img)
74
+
75
+ json_data = {
76
+ "token": "c0e69e5d129b11efa10c525400b75156",
77
+ "input1": fileName,
78
+ "input2": "",
79
+ "protocol": "",
80
+ "cloud": "ali"
81
+ }
82
+
83
+ session = requests.session()
84
+ ret = requests.post(
85
+ f"{UKAPIURL}/upload",
86
+ headers={'Content-Type': 'application/json'},
87
+ json=json_data
88
+ )
89
+
90
+ res = ""
91
+ if ret.status_code==200:
92
+ if 'upload1' in ret.json():
93
+ upload_url = ret.json()['upload1']
94
+ headers = {'Content-Type': 'image/jpeg'}
95
+ response = session.put(upload_url, data=open(local_path, 'rb').read(), headers=headers)
96
+ # print(response.status_code)
97
+ if response.status_code == 200:
98
+ res = upload_url
99
+ if os.path.exists(local_path):
100
+ os.remove(local_path)
101
+ return res
102
+
103
+
104
+ def publicClothSwap(image, clothId, is_hr=0):
105
+ json_data = {
106
+ "image": image,
107
+ "task_type": "11",
108
+ "param1": str(clothId),
109
+ "param2": "",
110
+ "param3": "",
111
+ "param4": str(is_hr),
112
+ "delete_if_complete": "1",
113
+ "force_celery":"1"
114
+ }
115
+
116
+ headers = {
117
+ 'Authorization': f'Bearer {TOKEN}',
118
+ 'Content-Type': 'application/json'
119
+ }
120
+
121
+ ret = requests.post(
122
+ f'{UKAPIURL}/public_advton',
123
+ headers=headers,
124
+ json=json_data
125
+ )
126
+
127
+ if ret.status_code == 200:
128
+ response = ret.json()
129
+ if 'mid_result' in response and 'id' in response:
130
+ return {'mid_result': response['mid_result'], 'id': response['id'], "msg": response['msg']}
131
+ # print(response)
132
+ return None
133
+ else:
134
+ return None
135
+
136
+ def getInfRes(taskId):
137
+ headers = {
138
+ 'Content-Type': 'application/json'
139
+ }
140
+ json_data = {
141
+ 'id': taskId
142
+ }
143
+ ret = requests.post(
144
+ f'{UKAPIURL}/status_advton',
145
+ headers=headers,
146
+ json=json_data
147
+ )
148
+ if ret.status_code == 200:
149
+ response = ret.json()
150
+ if 'status' in response:
151
+ return response
152
+ print(response)
153
+ return None
154
+ else:
155
+ return None
156
+
157
+ @func_timeout.func_set_timeout(10)
158
+ def check_region(ip):
159
+ session = requests.session()
160
+ # ret = requests.get(f"https://api.ip2location.io/?ip={ip}")
161
+ ret = requests.get(f"https://realip.cc/?ip={ip}")
162
+ # print(ret)
163
+ nat = ret.json()['country'].lower()
164
+ if nat in Regions.lower():
165
+ print(nat, 'invalid', ip)
166
+ return False
167
+ else:
168
+ print(nat, 'valid', ip)
169
+ return True
170
+
171
+ def check_region_warp(ip):
172
+ try:
173
+ return check_region(ip)
174
+ except Exception as e:
175
+ print(e)
176
+ return True