Spaces:
Paused
Paused
File size: 14,326 Bytes
3f9c56c |
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 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 |
import argparse
import unittest
import os
import sys
import time
import datetime
from enum import Enum
from typing import List, Tuple
import cv2
import requests
import numpy as np
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
TIMEOUT = 20 # seconds
CWD = os.getcwd()
SKI_IMAGE = os.path.join(CWD, "images/ski.jpg")
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
test_result_dir = os.path.join("results", f"test_result_{timestamp}")
test_expectation_dir = "expectations"
os.makedirs(test_result_dir, exist_ok=True)
os.makedirs(test_expectation_dir, exist_ok=True)
driver_path = ChromeDriverManager().install()
class GenType(Enum):
txt2img = "txt2img"
img2img = "img2img"
def _find_by_xpath(self, driver: webdriver.Chrome, xpath: str) -> "WebElement":
return driver.find_element(By.XPATH, xpath)
def tab(self, driver: webdriver.Chrome) -> "WebElement":
return self._find_by_xpath(
driver,
f"//*[@id='tabs']/*[contains(@class, 'tab-nav')]//button[text()='{self.value}']",
)
def controlnet_panel(self, driver: webdriver.Chrome) -> "WebElement":
return self._find_by_xpath(
driver, f"//*[@id='tab_{self.value}']//*[@id='controlnet']"
)
def generate_button(self, driver: webdriver.Chrome) -> "WebElement":
return self._find_by_xpath(driver, f"//*[@id='{self.value}_generate_box']")
def prompt_textarea(self, driver: webdriver.Chrome) -> "WebElement":
return self._find_by_xpath(driver, f"//*[@id='{self.value}_prompt']//textarea")
class SeleniumTestCase(unittest.TestCase):
def __init__(self, methodName: str = "runTest") -> None:
super().__init__(methodName)
self.driver = None
self.gen_type = None
def setUp(self) -> None:
super().setUp()
self.driver = webdriver.Chrome(driver_path)
self.driver.get(webui_url)
wait = WebDriverWait(self.driver, TIMEOUT)
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#controlnet")))
self.gen_type = GenType.txt2img
def tearDown(self) -> None:
self.driver.quit()
super().tearDown()
def select_gen_type(self, gen_type: GenType):
gen_type.tab(self.driver).click()
self.gen_type = gen_type
def set_prompt(self, prompt: str):
textarea = self.gen_type.prompt_textarea(self.driver)
textarea.clear()
textarea.send_keys(prompt)
def expand_controlnet_panel(self):
controlnet_panel = self.gen_type.controlnet_panel(self.driver)
input_image_group = controlnet_panel.find_element(
By.CSS_SELECTOR, ".cnet-input-image-group"
)
if not input_image_group.is_displayed():
controlnet_panel.click()
def enable_controlnet_unit(self):
controlnet_panel = self.gen_type.controlnet_panel(self.driver)
enable_checkbox = controlnet_panel.find_element(
By.CSS_SELECTOR, ".cnet-unit-enabled input[type='checkbox']"
)
if not enable_checkbox.is_selected():
enable_checkbox.click()
def iterate_preprocessor_types(self, ignore_none: bool = True):
dropdown = self.gen_type.controlnet_panel(self.driver).find_element(
By.CSS_SELECTOR,
f"#{self.gen_type.value}_controlnet_ControlNet-0_controlnet_preprocessor_dropdown",
)
index = 0
while True:
dropdown.click()
options = dropdown.find_elements(
By.XPATH, "//ul[contains(@class, 'options')]/li"
)
input_element = dropdown.find_element(By.CSS_SELECTOR, "input")
if index >= len(options):
return
option = options[index]
index += 1
if "none" in option.text and ignore_none:
continue
option_text = option.text
option.click()
yield option_text
def select_control_type(self, control_type: str):
controlnet_panel = self.gen_type.controlnet_panel(self.driver)
control_type_radio = controlnet_panel.find_element(
By.CSS_SELECTOR, f'.controlnet_control_type input[value="{control_type}"]'
)
control_type_radio.click()
time.sleep(3) # Wait for gradio backend to update model/module
def set_seed(self, seed: int):
seed_input = self.driver.find_element(
By.CSS_SELECTOR, f"#{self.gen_type.value}_seed input[type='number']"
)
seed_input.clear()
seed_input.send_keys(seed)
def set_subseed(self, seed: int):
show_button = self.driver.find_element(
By.CSS_SELECTOR,
f"#{self.gen_type.value}_subseed_show input[type='checkbox']",
)
if not show_button.is_selected():
show_button.click()
subseed_locator = (
By.CSS_SELECTOR,
f"#{self.gen_type.value}_subseed input[type='number']",
)
WebDriverWait(self.driver, TIMEOUT).until(
EC.visibility_of_element_located(subseed_locator)
)
subseed_input = self.driver.find_element(*subseed_locator)
subseed_input.clear()
subseed_input.send_keys(seed)
def upload_controlnet_input(self, img_path: str):
controlnet_panel = self.gen_type.controlnet_panel(self.driver)
image_input = controlnet_panel.find_element(
By.CSS_SELECTOR, '.cnet-input-image-group .cnet-image input[type="file"]'
)
image_input.send_keys(img_path)
def upload_img2img_input(self, img_path: str):
image_input = self.driver.find_element(
By.CSS_SELECTOR, '#img2img_image input[type="file"]'
)
image_input.send_keys(img_path)
def generate_image(self, name: str):
self.gen_type.generate_button(self.driver).click()
progress_bar_locator_visible = EC.visibility_of_element_located(
(By.CSS_SELECTOR, f"#{self.gen_type.value}_results .progress")
)
WebDriverWait(self.driver, TIMEOUT).until(progress_bar_locator_visible)
WebDriverWait(self.driver, TIMEOUT * 10).until_not(progress_bar_locator_visible)
generated_imgs = self.driver.find_elements(
By.CSS_SELECTOR,
f"#{self.gen_type.value}_results #{self.gen_type.value}_gallery img",
)
for i, generated_img in enumerate(generated_imgs):
# Use requests to get the image content
img_content = requests.get(generated_img.get_attribute("src")).content
# Save the image content to a file
global overwrite_expectation
dest_dir = (
test_expectation_dir if overwrite_expectation else test_result_dir
)
img_file_name = f"{self.__class__.__name__}_{name}_{i}.png"
with open(
os.path.join(dest_dir, img_file_name),
"wb",
) as img_file:
img_file.write(img_content)
if not overwrite_expectation:
try:
img1 = cv2.imread(os.path.join(test_expectation_dir, img_file_name))
img2 = cv2.imread(os.path.join(test_result_dir, img_file_name))
except Exception as e:
self.assertTrue(False, f"Get exception reading imgs: {e}")
continue
self.expect_same_image(
img1,
img2,
diff_img_path=os.path.join(
test_result_dir, img_file_name.replace(".png", "_diff.png")
),
)
def expect_same_image(self, img1, img2, diff_img_path: str):
# Calculate the difference between the two images
diff = cv2.absdiff(img1, img2)
# Set a threshold to highlight the different pixels
threshold = 30
diff_highlighted = np.where(diff > threshold, 255, 0).astype(np.uint8)
# Assert that the two images are similar within a tolerance
similar = np.allclose(img1, img2, rtol=0.5, atol=1)
if not similar:
# Save the diff_highlighted image to inspect the differences
cv2.imwrite(diff_img_path, diff_highlighted)
self.assertTrue(similar)
simple_control_types = {
"Canny": "canny",
"Depth": "depth_midas",
"Normal": "normal_bae",
"OpenPose": "openpose_full",
"MLSD": "mlsd",
"Lineart": "lineart_standard (from white bg & black line)",
"SoftEdge": "softedge_pidinet",
"Scribble": "scribble_pidinet",
"Seg": "seg_ofade20k",
"Tile": "tile_resample",
# Shuffle and Reference are not stable, and expected to fail.
# The majority of pixels are same, but some outlier pixels can have big diff.
"Shuffle": "shuffle",
"Reference": "reference_only",
}.keys()
class SeleniumTxt2ImgTest(SeleniumTestCase):
def setUp(self) -> None:
super().setUp()
self.select_gen_type(GenType.txt2img)
self.set_seed(100)
self.set_subseed(1000)
def test_simple_control_types(self):
"""Test simple control types that only requires input image."""
for control_type in simple_control_types:
with self.subTest(control_type=control_type):
self.expand_controlnet_panel()
self.select_control_type(control_type)
self.upload_controlnet_input(SKI_IMAGE)
self.generate_image(f"{control_type}_ski")
class SeleniumImg2ImgTest(SeleniumTestCase):
def setUp(self) -> None:
super().setUp()
self.select_gen_type(GenType.img2img)
self.set_seed(100)
self.set_subseed(1000)
def test_simple_control_types(self):
"""Test simple control types that only requires input image."""
for control_type in simple_control_types:
with self.subTest(control_type=control_type):
self.expand_controlnet_panel()
self.select_control_type(control_type)
self.upload_img2img_input(SKI_IMAGE)
self.upload_controlnet_input(SKI_IMAGE)
self.generate_image(f"img2img_{control_type}_ski")
class SeleniumInpaintTest(SeleniumTestCase):
def setUp(self) -> None:
super().setUp()
def draw_inpaint_mask(self, target_canvas):
size = target_canvas.size
width = size["width"]
height = size["height"]
brush_radius = 5
repeat = int(width * 0.1 / brush_radius)
trace: List[Tuple[int, int]] = [
(brush_radius, 0),
(0, height * 0.2),
(brush_radius, 0),
(0, -height * 0.2),
] * repeat
actions = ActionChains(self.driver)
actions.move_to_element(target_canvas) # move to the canvas
actions.move_by_offset(*trace[0])
actions.click_and_hold() # click and hold the left mouse button down
for stop_point in trace[1:]:
actions.move_by_offset(*stop_point)
actions.release() # release the left mouse button
actions.perform() # perform the action chain
def draw_cn_mask(self):
canvas = self.gen_type.controlnet_panel(self.driver).find_element(
By.CSS_SELECTOR, ".cnet-input-image-group .cnet-image canvas"
)
self.draw_inpaint_mask(canvas)
def draw_a1111_mask(self):
canvas = self.driver.find_element(By.CSS_SELECTOR, "#img2maskimg canvas")
self.draw_inpaint_mask(canvas)
def test_txt2img_inpaint(self):
self.select_gen_type(GenType.txt2img)
self.expand_controlnet_panel()
self.select_control_type("Inpaint")
self.upload_controlnet_input(SKI_IMAGE)
self.draw_cn_mask()
self.set_seed(100)
self.set_subseed(1000)
for option in self.iterate_preprocessor_types():
with self.subTest(option=option):
self.generate_image(f"{option}_txt2img_ski")
def test_img2img_inpaint(self):
# Note: img2img inpaint can only use A1111 mask.
# ControlNet input is disabled in img2img inpaint.
self._test_img2img_inpaint(use_cn_mask=False, use_a1111_mask=True)
def _test_img2img_inpaint(self, use_cn_mask: bool, use_a1111_mask: bool):
self.select_gen_type(GenType.img2img)
self.expand_controlnet_panel()
self.select_control_type("Inpaint")
self.upload_img2img_input(SKI_IMAGE)
# Send to inpaint
self.driver.find_element(
By.XPATH, f"//*[@id='img2img_copy_to_img2img']//button[text()='inpaint']"
).click()
time.sleep(3)
# Select latent noise to make inpaint effect more visible.
self.driver.find_element(
By.XPATH,
f"//input[@name='radio-img2img_inpainting_fill' and @value='latent noise']",
).click()
self.set_prompt("(coca-cola:2.0)")
self.enable_controlnet_unit()
self.upload_controlnet_input(SKI_IMAGE)
self.set_seed(100)
self.set_subseed(1000)
prefix = ""
if use_cn_mask:
self.draw_cn_mask()
prefix += "controlnet"
if use_a1111_mask:
self.draw_a1111_mask()
prefix += "A1111"
for option in self.iterate_preprocessor_types():
with self.subTest(option=option, mask_prefix=prefix):
self.generate_image(f"{option}_{prefix}_img2img_ski")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Your script description.")
parser.add_argument(
"--overwrite_expectation", action="store_true", help="overwrite expectation"
)
parser.add_argument(
"--target_url", type=str, default="http://localhost:7860", help="WebUI URL"
)
args, unknown_args = parser.parse_known_args()
overwrite_expectation = args.overwrite_expectation
webui_url = args.target_url
sys.argv = sys.argv[:1] + unknown_args
unittest.main()
|