sd-comic-lettering / tests /test_robustness.py
Kazzze's picture
Update to current version
55306cf verified
Raw History Blame Contribute Delete
10.4 kB
"""Long text, fonts without the letters, numbers out of range, renders in parallel, settings on disk.
Run from the repository folder: python -m pytest tests
"""
import importlib.util
import json
import os
import sys
import threading
import time
import numpy as np
import pytest
from PIL import Image
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, REPO)
from comic_lettering import Style, arrange, draw, letter, web # noqa: E402
from comic_lettering.__main__ import option_value # noqa: E402
from comic_lettering.core import _is_number, _pin # noqa: E402
from comic_lettering.fonts import DEFAULT_FONT, missing_glyphs # noqa: E402
from test_bubble_lines import page # noqa: E402
LONG_WORDS = 800 # a text this long used to take over a minute to fit
LONG_LIMIT = 5.0 # seconds it may take now: it takes a fraction of one
SLOW_RENDER = 0.6 # seconds the slow render of the parallel test takes
HEAD_START = 0.15 # seconds the slow render is ahead of the fast one
CYRILLIC_ONLY = "Bangers" # a bundled font with Latin letters and no Cyrillic
ONE_PIXEL = (1, 1)
def test_long_text_does_not_take_minutes():
# type: () -> None
text = " ".join("word%d" % number for number in range(LONG_WORDS))
for kind in ({"text": text}, {"caption": text}, {"sfx": text}):
start = time.time()
arrange(page(), **kind)
assert time.time() - start < LONG_LIMIT, kind.keys()
def test_long_text_still_goes_where_it_used_to():
# type: () -> None
# A text too long for a bubble is not lost: it goes to the caption, as before.
scene = arrange(page(), text=" ".join(["lots", "of", "words"] * 80))
kinds = [item["kind"] for item in scene["items"]]
assert "caption" in kinds and scene["info"]["bubbles_filled"] == 0
def test_one_pixel_image_is_not_an_error():
# type: () -> None
for kind in ({"sfx": "BAM"}, {"caption": "Hi"}, {"text": "Hi"}):
letter(Image.new("RGB", ONE_PIXEL, (200, 200, 200)), **kind)
def test_font_without_the_letters_is_replaced_and_says_so():
# type: () -> None
base = page()
other = Style(font=CYRILLIC_ONLY, caption_font="Chewy", sfx_font="Luckiest Guy")
shown, info = letter(base, text=u"Привет!\nHello", caption=u"Привет", sfx=u"ЩЁЛК", style=other)
assert len(info["warnings"]) == 3
assert all(DEFAULT_FONT in note for note in info["warnings"])
default = Style(font=DEFAULT_FONT, caption_font=DEFAULT_FONT, sfx_font=DEFAULT_FONT)
expected, _ = letter(base, text=u"Привет!\nHello", caption=u"Привет", sfx=u"ЩЁЛК", style=default)
assert np.array_equal(np.asarray(shown), np.asarray(expected))
assert other.font == CYRILLIC_ONLY, "the caller's style was changed"
def test_font_with_the_letters_is_left_alone():
# type: () -> None
base = page()
assert letter(base, text="Hi\nthere", style=Style(font=CYRILLIC_ONLY))[1]["warnings"] == []
assert letter(base, text=u"Привет", style=Style(font=DEFAULT_FONT))[1]["warnings"] == []
# Marks drawn as shapes are not letters of the font.
assert letter(base, text=u"Hi ♥ <3 *you*", style=Style(font=CYRILLIC_ONLY))[1]["warnings"] == []
def test_letters_no_font_has_stay_boxes_and_say_so():
# type: () -> None
_, info = letter(page(), text=u"漢字", style=Style(font=DEFAULT_FONT))
assert len(info["warnings"]) == 1 and "empty boxes" in info["warnings"][0]
def test_text_of_areas_counts_too():
# type: () -> None
square = [[100, 600], [560, 600], [560, 800], [100, 800]]
regions = [{"id": "a", "kind": "text", "fill": "light", "text": u"Привет", "shapes": [{"type": "polygon", "points": square}]}]
scene = arrange(page(), regions=regions, style=Style(font=CYRILLIC_ONLY))
assert scene["style"]["font"] == DEFAULT_FONT and len(scene["info"]["warnings"]) == 1
def test_missing_glyphs():
# type: () -> None
assert missing_glyphs(CYRILLIC_ONLY, u"Hello, World! 0123456789") == ""
assert missing_glyphs(CYRILLIC_ONLY, u"Привет Привет") == u"Привет", "in order of appearance, each once"
assert set(missing_glyphs(CYRILLIC_ONLY, u"Привет")) == set(u"Привет")
assert missing_glyphs(CYRILLIC_ONLY, u"a​b \t\n") == "", "spaces and invisible characters are not letters"
assert missing_glyphs("No Such Font", u"Привет") == "", "a font that is not used has nothing missing"
assert missing_glyphs(DEFAULT_FONT, u"Привет") == ""
def test_numbers_that_are_not_numbers():
# type: () -> None
for bad in (float("nan"), float("inf"), float("-inf"), True, None, "5"):
assert not _is_number(bad), bad
assert _is_number(5) and _is_number(-0.5)
assert _pin({"cx": 1, "cy": 2, "rotation": float("inf"), "size": float("nan")}) == {"cx": 1.0, "cy": 2.0}
base = page()
letter(base, caption="Hi", pins={"caption": {"rotation": float("inf")}})
letter(base, sfx="BAM", pins={"sfx:0": {"rotation": float("-inf")}})
infinite = [{"id": "a", "kind": "text", "fill": "light", "text": "Hi", "rotation": float("inf"), "scale": float("nan"),
"shapes": [{"type": "polygon", "points": [[100, 600], [float("inf"), 600], [560, 800], [100, 800]]}]}]
letter(base, regions=infinite)
def test_a_font_size_out_of_range_does_not_crash_the_core():
# type: () -> None
for size in (1e9, float("nan"), float("inf"), -5.0, 0.0):
style = Style(bubble_size=size)
letter(page(), text="Hello there", style=style)
def test_settings_are_brought_back_into_range():
# type: () -> None
values = web.merge_values({"bubble_size": 1e9, "arc": float("nan"), "margin": float("inf"), "white_threshold": 99999,
"opacity": -3, "line_spacing": 0})
assert values["bubble_size"] == 30.0
assert values["arc"] == web.DEFAULTS["arc"] and values["margin"] == web.DEFAULTS["margin"]
assert values["white_threshold"] == 255 and isinstance(values["white_threshold"], int)
assert values["opacity"] == 0.1 and values["line_spacing"] == 0.7
assert web.merge_values({}) == web.merge_values(web.merge_values({})), "the defaults are inside their limits"
def test_the_route_answers_for_settings_out_of_range():
# type: () -> None
session = web.new_session(page(), "x")
for settings in ({"bubble_size": 1e9}, {"bubble_size": float("nan")}, {"arc": 50}, {"rotation": float("inf")}):
status, body = web.answer_render({"session": session["id"], "text": "Hi", "caption": "Cap", "settings": settings})
assert status == 200, (settings, body)
def test_limits_are_the_ranges_of_the_comfyui_node():
# type: () -> None
pytest.importorskip("torch")
spec = importlib.util.spec_from_file_location("sdcl_node_package", os.path.join(REPO, "__init__.py"),
submodule_search_locations=[REPO])
package = importlib.util.module_from_spec(spec)
sys.modules["sdcl_node_package"] = package
try:
spec.loader.exec_module(package)
from sdcl_node_package import comfy_nodes
except ImportError as problem: # a host with no ComfyUI around: nothing to compare with
pytest.skip(str(problem))
types = comfy_nodes.ComicLettering.INPUT_TYPES()
inputs = dict(types["required"], **types["optional"])
for key, (low, high) in web.LIMITS.items():
options = inputs[key][1]
assert (options["min"], options["max"]) == (low, high), key
def test_option_value_checks_ranges():
# type: () -> None
style = Style()
assert option_value(style, "bubble_size", "9") == 9.0
for value in ("1e9", "nan", "inf", "-1", "0"):
with pytest.raises(ValueError):
option_value(style, "bubble_size", value)
def test_renders_of_one_image_take_turns(monkeypatch):
# type: (pytest.MonkeyPatch) -> None
base = page()
session = web.new_session(base, "t")
real = web.make_scene
def slow_for_slow_text(image, text, *rest, **more):
if text == "slow":
time.sleep(SLOW_RENDER) # the older request is the slower one
return real(image, text, *rest, **more)
monkeypatch.setattr(web, "make_scene", slow_for_slow_text)
answers = {}
def ask(name, text):
answers[name] = web.render_session(session, text, "", "", False, {})
older = threading.Thread(target=ask, args=("older", "slow"))
newer = threading.Thread(target=ask, args=("newer", "Hi"))
older.start()
time.sleep(HEAD_START)
newer.start()
older.join()
newer.join()
assert answers["older"]["version"] < answers["newer"]["version"]
expected = draw(base, arrange(base, text="Hi"))
assert np.array_equal(np.asarray(session["result"]), np.asarray(expected)), "the older render's picture won"
@pytest.fixture
def settings_file(tmp_path, monkeypatch):
path = str(tmp_path / "user_settings.json")
monkeypatch.setattr(web, "SETTINGS_FILE", path)
return path
def test_saving_settings_leaves_no_temporary_file(settings_file, tmp_path):
# type: (str, object) -> None
web.save_settings({"font": "Pangolin"})
assert json.load(open(settings_file))["font"] == "Pangolin"
assert os.listdir(str(tmp_path)) == ["user_settings.json"]
def test_a_failed_save_keeps_the_old_settings_and_says_so(settings_file, monkeypatch):
# type: (str, pytest.MonkeyPatch) -> None
web.save_settings({"font": "Pangolin"})
def fail(source, target):
raise OSError("disk full")
monkeypatch.setattr(web.os, "replace", fail)
status, body = web.answer_settings({"settings": {"font": "Bangers"}})
assert status == 500 and "disk full" in body["error"]
assert web.load_settings()["font"] == "Pangolin"
def test_saving_where_nothing_can_be_written_says_so(tmp_path, monkeypatch):
# type: (object, pytest.MonkeyPatch) -> None
monkeypatch.setattr(web, "SETTINGS_FILE", str(tmp_path / "no" / "such" / "folder" / "user_settings.json"))
status, body = web.answer_settings({"settings": {"font": "Bangers"}})
assert status == 500 and "Could not save" in body["error"]