Download tests/test_marks_censor.py from Kazzze/sd-comic-lettering: direct link, hf CLI and curl.
- Browser
- Download file 9.12 kB
-
https://huggingface.co/Kazzze/sd-comic-lettering/resolve/main/tests/test_marks_censor.py
- Command line
-
hf download hf://Kazzze/sd-comic-lettering/tests/test_marks_censor.py
-
curl -L -o test_marks_censor.py https://huggingface.co/Kazzze/sd-comic-lettering/resolve/main/tests/test_marks_censor.py
9.12 kB
| """Censor regions (bar, white, mosaic, blur), marks standing alone, and the marks added with them. | |
| Run from the repository folder: python -m pytest tests | |
| """ | |
| import json | |
| import os | |
| import sys | |
| from typing import Dict, List, Tuple | |
| import numpy as np | |
| import pytest | |
| from PIL import Image | |
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | |
| from comic_lettering import Style, arrange, draw, letter, web # noqa: E402 | |
| from comic_lettering.core import CENSOR_LOOKS, _regions # noqa: E402 | |
| from comic_lettering.render import EXTRAS, SHAPES, SYMBOLS # noqa: E402 | |
| from test_bubble_lines import page # noqa: E402 | |
| SIZE = (400, 300) | |
| BOX = (100, 80, 260, 180) # x0, y0, x1, y1 of the area under test | |
| EDGE = 12 # pixels around the box that the soft outline of an area may touch | |
| NEW_MARKS = [u"\U0001F60D", u"\U0001F644", u"\U0001F445", u"\U0001F924", u"\U0001F4F3", u"\U0001F32C", u"✹"] | |
| HEART = u"♥" | |
| def art(): | |
| # type: () -> Image.Image | |
| """A picture with something to see in every part: noise, so a blur and a mosaic show.""" | |
| rng = np.random.RandomState(7) | |
| return Image.fromarray(rng.randint(0, 256, (SIZE[1], SIZE[0], 3)).astype(np.uint8), "RGB") | |
| def box(x0, y0, x1, y1): | |
| # type: (int, int, int, int) -> Dict | |
| return {"type": "polygon", "points": [[x0, y0], [x1, y0], [x1, y1], [x0, y1]]} | |
| def censor(look="bar", rect=BOX, **more): | |
| # type: (str, Tuple, **object) -> List[Dict] | |
| region = {"id": "c", "kind": "censor", "look": look, "shapes": [box(*rect)]} | |
| region.update(more) | |
| return [region] | |
| def mark(symbol, rect=BOX, **more): | |
| # type: (str, Tuple, **object) -> List[Dict] | |
| region = {"id": "m", "kind": "mark", "text": symbol, "shapes": [box(*rect)]} | |
| region.update(more) | |
| return [region] | |
| def inside(image): | |
| # type: (Image.Image) -> np.ndarray | |
| x0, y0, x1, y1 = BOX | |
| return np.asarray(image.convert("RGB"))[y0 + EDGE:y1 - EDGE, x0 + EDGE:x1 - EDGE].astype(int) | |
| def outside_same(first, second): | |
| # type: (Image.Image, Image.Image) -> bool | |
| """Is everything but the area (and the edge round it) the same in both pictures?""" | |
| keep = np.ones((SIZE[1], SIZE[0]), dtype=bool) | |
| x0, y0, x1, y1 = BOX | |
| keep[y0 - EDGE:y1 + EDGE, x0 - EDGE:x1 + EDGE] = False | |
| return bool((np.asarray(first.convert("RGB"))[keep] == np.asarray(second.convert("RGB"))[keep]).all()) | |
| def test_a_bar_covers_its_area_and_nothing_else(): | |
| # type: () -> None | |
| base = art() | |
| shown, _ = letter(base, regions=censor("bar")) | |
| assert (inside(shown) == 0).all() | |
| assert outside_same(shown, base) | |
| def test_a_white_bar(): | |
| # type: () -> None | |
| base = art() | |
| shown, _ = letter(base, regions=censor("white")) | |
| assert (inside(shown) == 255).all() and outside_same(shown, base) | |
| def test_a_mosaic_is_made_of_squares_of_one_color(): | |
| # type: () -> None | |
| base = art() | |
| shown, _ = letter(base, regions=censor("mosaic", scale=2.0)) | |
| patch = inside(shown) | |
| assert not (patch == inside(base)).all() | |
| assert len(np.unique(patch.reshape(-1, 3), axis=0)) < len(np.unique(inside(base).reshape(-1, 3), axis=0)) / 20 | |
| assert outside_same(shown, base) | |
| def test_a_blur_smooths_what_is_under_it(): | |
| # type: () -> None | |
| base = art() | |
| shown, _ = letter(base, regions=censor("blur")) | |
| assert inside(shown).std() < inside(base).std() / 2 | |
| assert outside_same(shown, base) | |
| def test_stronger_mosaic_has_larger_squares(): | |
| # type: () -> None | |
| base = art() | |
| colors = [len(np.unique(inside(letter(base, regions=censor("mosaic", scale=s))[0]).reshape(-1, 3), axis=0)) for s in (1.0, 2.0, 4.0)] | |
| assert colors[0] > colors[1] > colors[2] | |
| def test_a_scene_with_only_a_censor_is_not_empty(): | |
| # type: () -> None | |
| base = art() | |
| scene = arrange(base, regions=censor()) | |
| assert scene["empty"] is False and scene["info"]["censored"] == 1 | |
| assert not np.array_equal(np.asarray(draw(base, scene)), np.asarray(base)) | |
| # A keep-out area alone still draws nothing, as before. | |
| assert arrange(base, regions=[{"id": "k", "kind": "keepout", "shapes": [box(*BOX)]}])["empty"] is True | |
| def test_a_censor_is_under_the_lettering(): | |
| # type: () -> None | |
| base = art() | |
| look = Style(caption_colors="custom", text_color="#ff0000", stroke_width=0.0, shadow=0.0) | |
| shown, _ = letter(base, caption="HELLO", style=look, pins={"caption": {"cx": 180, "cy": 130, "size": 60}}, regions=censor()) | |
| patch = inside(shown) | |
| red = (patch[..., 0] > 200) & (patch[..., 1] < 60) & (patch[..., 2] < 60) | |
| assert red.sum() > 50, "the lettering is not on top of the bar" | |
| def test_the_status_counts_censored_areas(): | |
| # type: () -> None | |
| scene = arrange(art(), regions=censor("bar") + censor("blur", rect=(10, 10, 60, 40), id="d")) | |
| assert scene["info"]["censored"] == 2 | |
| assert "censored: 2" in web.describe(scene["info"])[0] | |
| def test_censor_regions_are_cleaned(): | |
| # type: () -> None | |
| odd = _regions(censor("sparkly", text="no text here", follow=True, color="#ff0000", scale=99))[0] | |
| assert odd["look"] == CENSOR_LOOKS[0] and odd["text"] == "" and odd["follow"] is False | |
| assert odd["color"] == "" and odd["scale"] == 4.0 | |
| assert [_regions(censor(look))[0]["look"] for look in CENSOR_LOOKS] == list(CENSOR_LOOKS) | |
| def test_a_mark_stands_where_its_area_is_as_large_as_its_box(): | |
| # type: () -> None | |
| base = art() | |
| scene = arrange(base, regions=mark(HEART)) | |
| items = [item for item in scene["items"] if item["kind"] == "mark"] | |
| assert len(items) == 1 and items[0]["text"] == HEART | |
| x0, y0, x1, y1 = BOX | |
| assert abs(items[0]["cx"] - (x0 + x1) / 2.0) < 3 and abs(items[0]["cy"] - (y0 + y1) / 2.0) < 3 | |
| assert abs(items[0]["size"] - max(x1 - x0, y1 - y0)) < 6 | |
| assert scene["info"]["regions"] == 1 | |
| assert not np.array_equal(np.asarray(draw(base, scene)), np.asarray(base)) | |
| def test_a_mark_has_a_color_a_scale_and_a_tilt(): | |
| # type: () -> None | |
| base = art() | |
| flat = letter(base, regions=mark(HEART))[0] | |
| red = letter(base, regions=mark(HEART, color="#ff0000"))[0] | |
| patch = inside(red) | |
| assert ((patch[..., 0] == 255) & (patch[..., 1] == 0) & (patch[..., 2] == 0)).any() | |
| big = arrange(base, regions=mark(HEART, scale=2.0))["items"][0]["size"] | |
| assert big == 2 * arrange(base, regions=mark(HEART))["items"][0]["size"] | |
| tilted = letter(base, regions=mark(HEART, rotation=30))[0] | |
| assert not np.array_equal(np.asarray(flat), np.asarray(tilted)) | |
| def test_a_mark_takes_the_first_mark_of_its_text(): | |
| # type: () -> None | |
| base = art() | |
| assert arrange(base, regions=mark(u"ab <3 " + u"★"))["items"][0]["mark"] == "heart" | |
| assert arrange(base, regions=mark("nothing to draw"))["items"] == [] | |
| assert arrange(base, regions=mark(""))["items"] == [] | |
| def test_marks_and_censors_survive_json_and_old_scenes(): | |
| # type: () -> None | |
| base = art() | |
| regions = censor("mosaic") + mark(HEART, rect=(280, 200, 380, 280), color="#00ff00", id="m2") | |
| scene = arrange(base, regions=regions) | |
| again = json.loads(json.dumps(scene)) | |
| assert np.array_equal(np.asarray(draw(base, scene)), np.asarray(draw(base, again))) | |
| for region in again["regions"]: # a scene saved before looks and colors existed | |
| region.pop("look", None) | |
| region.pop("color", None) | |
| draw(base, again) | |
| def test_every_new_mark_is_drawn_offered_and_grouped(capsys): | |
| # type: (pytest.CaptureFixture) -> None | |
| for char in NEW_MARKS: | |
| assert char in SYMBOLS and SYMBOLS[char] in SHAPES | |
| assert char in web.SYMBOLS | |
| offered = [entry["symbol"] for entry in web._marks()] | |
| assert all(char in offered for char in NEW_MARKS) | |
| web._check_groups([]) | |
| assert capsys.readouterr().err == "", "MARK_GROUPS and SYMBOLS differ" | |
| for name in ("tremble lines", "speed lines"): | |
| assert EXTRAS[name] in SHAPES | |
| def test_new_marks_have_ink_and_stay_inside_their_tile(): | |
| # type: () -> None | |
| from comic_lettering.render import symbol_tile | |
| for char in NEW_MARKS: | |
| tile = np.asarray(symbol_tile(SYMBOLS[char], 64)) | |
| assert (tile > 128).sum() > 64 * 64 * 0.04, SYMBOLS[char] | |
| def test_marks_around_a_caption_are_unchanged(): | |
| # type: () -> None | |
| # decorate() draws its marks through mark_tile() now; a caption with marks around it is as it was. | |
| base = page() | |
| first = letter(base, caption="Hello", placement="center", style=Style(caption_extras="hearts"))[0] | |
| second = letter(base, caption="Hello", placement="center", style=Style(caption_extras="hearts"))[0] | |
| assert np.array_equal(np.asarray(first), np.asarray(second)) | |
| assert not np.array_equal(np.asarray(first), np.asarray(letter(base, caption="Hello", placement="center")[0])) | |
| letter(base, caption="Hello", placement="center", style=Style(caption_extras="tremble lines")) | |
| letter(base, sfx="BAM", style=Style(sfx_extras="speed lines")) | |