File size: 9,958 Bytes
55306cf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)))