"""A gradient of your own for the text, the thought bubble, and the command line's fixes. Run from the repository folder: python -m pytest tests """ import json import os import sys from typing import 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 BUBBLE_SHAPES, Style, arrange, draw, letter # noqa: E402 from comic_lettering.__main__ import main, option_value # noqa: E402 from comic_lettering.web import merge_values, read_layout # noqa: E402 from test_bubble_lines import page # noqa: E402 TOP = "#ff0000" BOTTOM = "#0000ff" MIN_INK_PIXELS = 50 # fewer changed pixels than this means no text was drawn at all SQUARE = [[100, 600], [560, 600], [560, 800], [100, 800]] # a painted area on the empty part of the page def custom_look(**more): # type: (**str) -> Style """Caption in one flat color of its own, nothing around the letters to blur the check.""" look = Style(caption_colors="custom", bubble_colors="custom", sfx_colors="custom", text_color=TOP, sfx_color=TOP, stroke_width=0.0, shadow=0.0, soften=0.0, caption_mood="calm", jitter=0.0) for key, value in more.items(): setattr(look, key, value) return look def inked(image, base): # type: (Image.Image, Image.Image) -> Tuple[np.ndarray, np.ndarray] """The pixels the lettering changed and their rows.""" changed = (np.asarray(image.convert("RGB")).astype(int) != np.asarray(base.convert("RGB")).astype(int)).any(axis=2) rows, cols = np.nonzero(changed) assert len(rows) > MIN_INK_PIXELS, "nothing was drawn" return rows, cols def halves(image, base): # type: (Image.Image, Image.Image) -> Tuple[np.ndarray, np.ndarray] """The mean (R, G, B) of the upper and of the lower half of the inked pixels, by row.""" rows, cols = inked(image, base) pixels = np.asarray(image.convert("RGB"))[rows, cols].astype(float) middle = (rows.min() + rows.max()) / 2.0 return pixels[rows < middle].mean(axis=0), pixels[rows >= middle].mean(axis=0) def test_caption_gradient_goes_from_the_first_color_to_the_second(): # type: () -> None base = page() shown, _ = letter(base, caption="HELLO\nWORLD", placement="center", style=custom_look(text_color2=BOTTOM, caption_mood="calm")) upper, lower = halves(shown, base) assert upper[0] > upper[2], "the top of the letters is not closer to the first color" assert lower[2] > lower[0], "the bottom of the letters is not closer to the second color" def test_sound_effect_gradient(): # type: () -> None base = page() shown, _ = letter(base, sfx="BAM", style=custom_look(sfx_color2=BOTTOM, sfx_mood="calm")) upper, lower = halves(shown, base) assert upper[0] > lower[0] and lower[2] > upper[2] def test_bubble_text_gradient(): # type: () -> None base = page() shown, _ = letter(base, text="Hello there, how are you", style=custom_look(text_color2=BOTTOM)) box = (40, 50, 330, 250) upper, lower = halves(shown.crop(box), base.crop(box)) assert upper[0] > lower[0] and lower[2] > upper[2] def test_second_color_that_is_auto_or_not_a_color_changes_nothing(): # type: () -> None base = page() kwargs = dict(caption="HELLO\nWORLD", text="Hi there", placement="center") plain = letter(base, style=custom_look(), **kwargs)[0] for value in ("auto", "", "blue-ish", "#12"): assert np.array_equal(np.asarray(plain), np.asarray(letter(base, style=custom_look(text_color2=value), **kwargs)[0])) def test_second_color_is_ignored_unless_the_colors_are_custom(): # type: () -> None base = page() kwargs = dict(caption="HELLO", text="Hi there", sfx="BAM", placement="center") plain = letter(base, style=Style(), **kwargs)[0] other = letter(base, style=Style(text_color2=BOTTOM, sfx_color2=BOTTOM, text_color=TOP), **kwargs)[0] assert np.array_equal(np.asarray(plain), np.asarray(other)) def test_scene_from_before_the_second_color_still_draws(): # type: () -> None base = page() scene = arrange(base, text="Hi there", caption="HELLO", placement="center") for key in ("text_color2", "sfx_color2"): del scene["style"][key] # a scene saved by an earlier version knows nothing of them assert np.array_equal(np.asarray(draw(base, scene)), np.asarray(letter(base, text="Hi there", caption="HELLO", placement="center")[0])) def test_thought_bubble_is_a_choice_and_draws_a_tail_of_circles(): # type: () -> None assert "thought" in BUBBLE_SHAPES assert merge_values({"caption_bubble": "thought"})["caption_bubble"] == "thought" base = page() shapes = {} for shape in ("cloud", "thought"): shapes[shape] = letter(base, caption="Hmm...", placement="center", style=Style(caption_bubble=shape, caption_tail="down-left"))[0] assert not np.array_equal(np.asarray(shapes["cloud"]), np.asarray(shapes["thought"])) plain = letter(base, caption="Hmm...", placement="center", style=Style(caption_bubble="thought"))[0] assert not np.array_equal(np.asarray(plain), np.asarray(shapes["thought"])), "the tail is not drawn" def test_opt_false_is_false(): # type: () -> None style = Style() assert option_value(style, "uppercase", "false") is False assert option_value(style, "uppercase", "0") is False assert option_value(style, "uppercase", "True") is True assert option_value(style, "uppercase", "yes") is True def test_opt_checks_a_name_against_its_list_and_a_number_against_its_type(): # type: () -> None style = Style() assert option_value(style, "caption_bubble", "oval") == "oval" assert option_value(style, "caption_tail", "down-left") == "down-left" assert option_value(style, "shadow", "0.25") == 0.25 assert option_value(style, "seed", "7") == 7 assert option_value(style, "text_color2", "#ff00aa") == "#ff00aa" for name, value in (("caption_bubble", "ovl"), ("bubble_colors", "pinkish"), ("font", "No Such Font"), ("shadow", "heavy"), ("seed", "1.5")): with pytest.raises(ValueError): option_value(style, name, value) def test_read_layout(): # type: () -> None assert read_layout("") == ({}, []) assert read_layout("not json") == ({}, []) assert read_layout("[1, 2]") == ({}, []) pins, regions = read_layout(json.dumps({"pins": {"caption": {"cx": 5, "cy": 6}}, "regions": [{"id": "a"}]})) assert pins == {"caption": {"cx": 5, "cy": 6}} and regions == [{"id": "a"}] assert read_layout(json.dumps({"pins": [], "regions": {}})) == ({}, []) def test_letter_takes_pins_and_regions_like_arrange(): # type: () -> None base = page() regions = [{"id": "a", "kind": "text", "fill": "light", "text": "Hi", "shapes": [{"type": "polygon", "points": SQUARE}]}] scene = arrange(base, caption="Later", placement="top", pins={"caption": {"cx": 330, "cy": 300}}, regions=regions) direct = draw(base, scene) through_letter, info = letter(base, caption="Later", placement="top", pins={"caption": {"cx": 330, "cy": 300}}, regions=regions) assert np.array_equal(np.asarray(direct), np.asarray(through_letter)) assert info["regions"] == 1 assert not np.array_equal(np.asarray(through_letter), np.asarray(letter(base, caption="Later", placement="top")[0])) def run_cli(monkeypatch, arguments): # type: (pytest.MonkeyPatch, list) -> None monkeypatch.setattr(sys, "argv", ["comic_lettering"] + arguments) main() def test_cli_layout_file_places_a_region(monkeypatch, tmp_path, capsys): # type: (pytest.MonkeyPatch, object, object) -> None source = str(tmp_path / "in.png") page().save(source) layout = tmp_path / "layout.json" layout.write_text(json.dumps({"regions": [{"id": "a", "kind": "text", "fill": "light", "text": "Hi", "shapes": [{"type": "polygon", "points": SQUARE}]}]}), encoding="utf-8") with_layout, without = str(tmp_path / "with.png"), str(tmp_path / "without.png") run_cli(monkeypatch, [source, with_layout, "--text", "Hello", "--layout", str(layout)]) assert "'regions': 1" in capsys.readouterr().out run_cli(monkeypatch, [source, without, "--text", "Hello"]) assert not np.array_equal(np.asarray(Image.open(with_layout)), np.asarray(Image.open(without))) def test_cli_stops_on_a_bad_option_or_layout(monkeypatch, tmp_path): # type: (pytest.MonkeyPatch, object) -> None source = str(tmp_path / "in.png") page().save(source) broken = tmp_path / "broken.json" broken.write_text("{not json", encoding="utf-8") for extra in (["--opt", "caption_bubble=ovl"], ["--opt", "no_such_option=1"], ["--opt", "shadow=heavy"], ["--layout", str(broken)], ["--layout", str(tmp_path / "missing.json")]): with pytest.raises(SystemExit) as stop: run_cli(monkeypatch, [source, str(tmp_path / "out.png"), "--text", "Hi"] + extra) assert stop.value.code == 2 def test_cli_uppercase_option_turns_it_off(monkeypatch, tmp_path): # type: (pytest.MonkeyPatch, object) -> None source = str(tmp_path / "in.png") page().save(source) lower, upper = str(tmp_path / "lower.png"), str(tmp_path / "upper.png") run_cli(monkeypatch, [source, lower, "--text", "Hello there", "--opt", "uppercase=false"]) run_cli(monkeypatch, [source, upper, "--text", "Hello there", "--no-uppercase"]) assert np.array_equal(np.asarray(Image.open(lower)), np.asarray(Image.open(upper)))