-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_api.py
More file actions
227 lines (189 loc) · 7.8 KB
/
test_api.py
File metadata and controls
227 lines (189 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
import time
import requests
import base64
import io
import sys
from PIL import Image, ImageFilter
import numpy as np
API_URL = "http://127.0.0.1:8000"
import os
def apply_cube_lut(image_path: str, lut_content: str, output_path: str):
"""
Apply a .cube LUT to an image using Pillow's Color3DLUT.
"""
print(f"🎨 Applying LUT to {image_path}...")
try:
# 1. Parse .cube content
lines = lut_content.splitlines()
size = 33
table = []
domain_min = [0.0, 0.0, 0.0]
domain_max = [1.0, 1.0, 1.0]
for line in lines:
line = line.strip()
if not line or line.startswith("#"):
continue
if line.startswith("TITLE"):
continue
if line.startswith("LUT_3D_SIZE"):
size = int(line.split()[1])
continue
if line.startswith("DOMAIN_MIN"):
domain_min = [float(x) for x in line.split()[1:]]
continue
if line.startswith("DOMAIN_MAX"):
domain_max = [float(x) for x in line.split()[1:]]
continue
# Helper to parse floats safely
parts = line.split()
if len(parts) == 3:
vals = [float(x) for x in parts]
table.extend(vals)
if len(table) != size * size * size * 3:
print(f"⚠️ Warning: LUT table size mismatch. Expected {size**3 * 3}, got {len(table)}")
# 2. Create Pillow LUT Filter
# Pillow expects the table to be flat list of R, G, B values
# The .cube standard order (B varies slowest, R varies fastest) matches Pillow's expectation
lut_filter = ImageFilter.Color3DLUT(size, table)
# 3. Apply to image
with Image.open(image_path).convert('RGB') as img:
# Resize for speed or consistency if needed, but LUT works on any size
# We use original size here to verify full effect
result = img.filter(lut_filter)
result.save(output_path)
print(f"✅ Saved client-side LUT applied image to: {output_path}")
except Exception as e:
print(f"❌ Failed to apply LUT locally: {e}")
def prepare_input_image():
"""Load or create test image and save to 'test_input_sent.png'."""
# Prioritize model/test.jpg, fallback to model/shw.jpg for backward compat
image_paths = [os.path.join("model", "shw.jpg"), os.path.join("model", "shw.jpg")]
selected_path = None
for p in image_paths:
if os.path.exists(p):
selected_path = p
break
target_path = "test_input_sent.png"
if selected_path:
print(f"📄 Loading test image from: {selected_path}")
img = Image.open(selected_path).convert('RGB')
img.save(target_path)
else:
print("⚠️ Test image not found, using dummy red square.")
img = Image.new('RGB', (100, 100), color = 'red')
img.save(target_path)
with open(target_path, "rb") as f:
return base64.b64encode(f.read()).decode('utf-8')
def check_health():
"""Check if the API is reachable."""
try:
response = requests.get(f"{API_URL}/")
if response.status_code == 200:
print("✅ API is reachable.")
return True
else:
print(f"❌ API returned status code: {response.status_code}")
return False
except requests.exceptions.ConnectionError:
print("❌ Could not connect to API. Is it running?")
return False
def normalize_base64(data: str) -> str:
"""Strip data URL prefix and fix missing padding for base64 strings."""
if "," in data:
data = data.split(",", 1)[1]
padding = (-len(data)) % 4
if padding:
data += "=" * padding
return data
def run_test():
print(f"Testing CLIP-DLUT Backend at {API_URL}...")
if not check_health():
return
# 1. Submit Taks
print("\n1. Submitting Retouch Task...")
# Save input image to disk first for consistency
image_b64 = prepare_input_image()
payload = {
"image": image_b64,
"target_prompt": "一条蓝色色调的巷子",
"original_prompt": "一条巷子",
"iteration": 1000 # Incremented iteration for better effect
}
try:
resp = requests.post(f"{API_URL}/retouch", json=payload)
resp.raise_for_status()
data = resp.json()
task_id = data['task_id']
print(f"✅ Task submitted successfully. Task ID: {task_id}")
except Exception as e:
print(f"❌ Failed to submit task: {e}")
if resp:
print(f"Response: {resp.text}")
return
# 2. Poll Status
print(f"\n2. Polling Task Status (Task ID: {task_id})...")
start_time = time.time()
while True:
try:
query_resp = requests.post(
f"{API_URL}/query_task",
json={
"task_id": task_id,
"include_image": True,
"lut_format": "cube"
}
)
query_resp.raise_for_status()
status_data = query_resp.json()
status = status_data['status']
elapsed = time.time() - start_time
print(f" [{elapsed:.1f}s] Status: {status}, Iteration: {status_data.get('current_iteration')}")
if status == "finished":
print("\n✅ Task Finished!")
lut_content_str = None
if status_data.get('lut'):
print(" - LUT received")
try:
lut_b64 = normalize_base64(status_data['lut'])
lut_bytes = base64.b64decode(lut_b64)
# Save as .cube
lut_content_str = lut_bytes.decode('utf-8')
with open("output.cube", "w") as f:
f.write(lut_content_str)
print(" - Saved LUT to output.cube")
except Exception as e:
print(f" - Failed to save LUT: {e}")
if status_data.get('image'):
print(" - Result image received")
try:
img_b64 = normalize_base64(status_data['image'])
img_bytes = base64.b64decode(img_b64)
with open("server_result.png", "wb") as f:
f.write(img_bytes)
print(" - Saved server result to server_result.png")
except Exception as e:
print(f" - Failed to save Image: {e}")
# Apply LUT locally to verify
if lut_content_str:
# Apply to the exact image we sent
input_image_path = "test_input_sent.png"
if os.path.exists(input_image_path):
apply_cube_lut(input_image_path, lut_content_str, "client_lut_applied.png")
else:
print("⚠️ Skipping local LUT application: Input image test_input_sent.png not found.")
break
if status == "failed":
print("\n❌ Task Failed!")
break
if status == "stopped":
print("\n⚠️ Task Stopped!")
break
time.sleep(2)
if elapsed > 1000: # Timeout
print("\n❌ Test Timed Out (1000s).")
break
except Exception as e:
print(f"❌ Error polling status: {e}")
break
if __name__ == "__main__":
run_test()