File size: 12,473 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 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 | """Gradient angle and a bubble fill of your own, more bubble shapes and a tail you aim, tones, lines
and windows, transparency and turned photos kept, and the fonts that ship.
Run from the repository folder: python -m pytest tests
"""
import io
import os
import sys
from typing import Dict, List, Tuple
import numpy as np
import pytest
from PIL import Image, ImageFont
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, REPO)
from comic_lettering import BUBBLE_SHAPES, Style, TAILS, arrange, draw, letter, web # noqa: E402
from comic_lettering.core import PAINTED, _regions, has_alpha, upright # noqa: E402
from comic_lettering.fonts import BUNDLED_DIR, list_fonts, missing_glyphs # noqa: E402
from comic_lettering.painting import FRAME_LOOKS, LINES_LOOKS, TONE_LOOKS # noqa: E402
from comic_lettering.render import _gradient # noqa: E402
from test_bubble_lines import page # noqa: E402
SIZE = (400, 300)
BOX = (100, 80, 260, 180)
EDGE = 10
TOP = (255, 0, 0)
BOTTOM = (0, 0, 255)
MIN_INK = 50
def art():
# type: () -> Image.Image
rng = np.random.RandomState(11)
return Image.fromarray(rng.randint(0, 256, (SIZE[1], SIZE[0], 3)).astype(np.uint8), "RGB")
def area(kind, look="", rect=BOX, **more):
# type: (str, str, Tuple, **object) -> List[Dict]
shape = {"type": "polygon", "points": [[rect[0], rect[1]], [rect[2], rect[1]], [rect[2], rect[3]], [rect[0], rect[3]]]}
return [dict({"id": "a", "kind": kind, "look": look, "shapes": [shape]}, **more)]
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
keep = np.ones((SIZE[1], SIZE[0]), dtype=bool)
x0, y0, x1, y1 = BOX
keep[y0 - 3 * EDGE:y1 + 3 * EDGE, x0 - 3 * EDGE:x1 + 3 * EDGE] = False
return bool((np.asarray(first.convert("RGB"))[keep] == np.asarray(second.convert("RGB"))[keep]).all())
def test_gradient_angle_zero_is_the_old_vertical_gradient():
# type: () -> None
mask = Image.new("L", (60, 40), 0)
mask.paste(255, (10, 5, 50, 35))
assert np.array_equal(np.asarray(_gradient(TOP, BOTTOM, mask)), np.asarray(_gradient(TOP, BOTTOM, mask, 0.0)))
assert np.array_equal(np.asarray(_gradient(TOP, BOTTOM, mask)), np.asarray(_gradient(TOP, BOTTOM, mask, 360.0)))
def test_gradient_angle_turns_the_gradient():
# type: () -> None
mask = Image.new("L", (80, 80), 0)
mask.paste(255, (10, 10, 70, 70))
across = np.asarray(_gradient(TOP, BOTTOM, mask, 90.0)).astype(int)
assert across[40, 12, 0] > across[40, 68, 0] and across[40, 68, 2] > across[40, 12, 2], "90 degrees runs left to right"
assert abs(int(across[12, 40, 0]) - int(across[68, 40, 0])) < 40, "and the rows are all alike"
down = np.asarray(_gradient(TOP, BOTTOM, mask, 0.0)).astype(int)
assert down[12, 40, 0] > down[68, 40, 0]
back = np.asarray(_gradient(TOP, BOTTOM, mask, 180.0)).astype(int)
assert back[12, 40, 2] > back[68, 40, 2], "180 degrees is bottom to top"
assert (np.asarray(_gradient(TOP, BOTTOM, mask, 45.0))[..., 3] == np.asarray(mask)).all(), "the shape of the mask stays"
def test_gradient_angle_reaches_the_lettering():
# type: () -> None
base = page()
look = dict(caption_colors="custom", text_color="#ff0000", text_color2="#0000ff", stroke_width=0.0, shadow=0.0, soften=0.0, jitter=0.0)
down = letter(base, caption="HELLO WORLD", placement="center", style=Style(**look))[0]
along = letter(base, caption="HELLO WORLD", placement="center", style=Style(gradient_angle=90.0, **look))[0]
assert not np.array_equal(np.asarray(down), np.asarray(along))
def test_the_bubble_of_the_caption_can_have_a_fill_and_a_gradient():
# type: () -> None
base = Image.new("RGB", (400, 300), (120, 120, 120))
plain = letter(base, caption="Hi", placement="center", style=Style(caption_bubble="oval"))[0]
filled = letter(base, caption="Hi", placement="center", style=Style(caption_bubble="oval", caption_bubble_color="#ffe08a"))[0]
both = letter(base, caption="Hi", placement="center", style=Style(caption_bubble="oval", caption_bubble_color="#ffe08a",
caption_bubble_color2="#ff4488"))[0]
assert not np.array_equal(np.asarray(plain), np.asarray(filled))
assert not np.array_equal(np.asarray(filled), np.asarray(both))
yellow = (np.abs(np.asarray(filled).astype(int) - (255, 224, 138)) < 6).all(axis=2)
assert yellow.sum() > 200, "the fill is the color asked for"
assert not (np.abs(np.asarray(plain).astype(int) - (255, 224, 138)) < 6).all(axis=2).any()
def test_a_dark_fill_gets_light_text_and_a_light_one_dark():
# type: () -> None
base = Image.new("RGB", (400, 300), (120, 120, 120))
for fill, light_ink in (("#101030", True), ("#fff0c0", False)):
shown = np.asarray(letter(base, caption="HELLO", placement="center", style=Style(caption_bubble="oval", caption_bubble_color=fill))[0]).astype(int)
patch = shown[110:190, 120:280]
text = patch[(patch.sum(axis=2) > 600)] if light_ink else patch[(patch.sum(axis=2) < 150)]
assert len(text) > MIN_INK, fill
def test_new_bubble_shapes_are_choices_and_draw():
# type: () -> None
assert {"wavy", "jagged", "dashed"} <= set(BUBBLE_SHAPES)
base = Image.new("RGB", (400, 300), (120, 120, 120))
drawn = {}
for shape in BUBBLE_SHAPES:
assert web.merge_values({"caption_bubble": shape})["caption_bubble"] == shape
drawn[shape] = np.asarray(letter(base, caption="Hmm", placement="center", style=Style(caption_bubble=shape))[0])
for shape in ("wavy", "jagged", "dashed"):
assert not np.array_equal(drawn[shape], drawn["oval"]), shape
assert not np.array_equal(drawn["wavy"], drawn["jagged"])
def test_a_tail_can_point_anywhere():
# type: () -> None
assert "custom" in TAILS and TAILS["custom"] is None
assert web.merge_values({"caption_tail": "custom"})["caption_tail"] == "custom"
base = Image.new("RGB", (400, 300), (120, 120, 120))
shots = [np.asarray(letter(base, caption="Hi", placement="center", style=Style(caption_bubble="oval", caption_tail="custom",
caption_tail_angle=angle))[0]) for angle in (0, 90, 180, 270)]
plain = np.asarray(letter(base, caption="Hi", placement="center", style=Style(caption_bubble="oval"))[0])
assert all(not np.array_equal(shot, plain) for shot in shots)
assert len(set(shot.tobytes() for shot in shots)) == 4, "each direction is its own picture"
# A named direction and the same direction as an angle draw the same tail.
named = np.asarray(letter(base, caption="Hi", placement="center", style=Style(caption_bubble="oval", caption_tail="down"))[0])
custom = np.asarray(letter(base, caption="Hi", placement="center", style=Style(caption_bubble="oval", caption_tail="custom", caption_tail_angle=90))[0])
assert np.array_equal(named, custom)
@pytest.mark.parametrize("kind,looks", [("tone", TONE_LOOKS), ("lines", LINES_LOOKS), ("frame", FRAME_LOOKS)])
def test_painted_areas_draw_every_look_under_the_lettering(kind, looks):
# type: (str, Tuple) -> None
base = art()
pictures = []
for look in looks:
shown, info = letter(base, regions=area(kind, look))
assert info["decorated"] == 1
assert not np.array_equal(np.asarray(shown), np.asarray(base)), look
pictures.append(np.asarray(shown).tobytes())
assert len(set(pictures)) == len(looks), "each look is its own picture"
def test_a_tone_stays_inside_its_area_and_has_a_color_and_an_angle():
# type: () -> None
base = art()
shown, _ = letter(base, regions=area("tone", "dots"))
assert outside_same(shown, base)
black = inside(shown)
assert (black.sum(axis=2) < inside(base).sum(axis=2)).any()
blue = letter(base, regions=area("tone", "hatch", color="#0000ff"))[0]
assert outside_same(blue, base)
turned = letter(base, regions=area("tone", "hatch", color="#0000ff", rotation=45))[0]
assert not np.array_equal(np.asarray(blue), np.asarray(turned))
def test_a_window_with_a_dark_inside_darkens_it_and_a_scene_of_painted_areas_is_not_empty():
# type: () -> None
base = art()
shown, _ = letter(base, regions=area("frame", "dark"))
assert inside(shown).mean() < inside(base).mean() / 3
for kind in PAINTED:
assert arrange(base, regions=area(kind))["empty"] is False, kind
def test_painted_regions_are_cleaned():
# type: () -> None
odd = _regions(area("tone", "sparkly", text="no text", color="not a color", follow=True))[0]
assert odd["look"] == TONE_LOOKS[0] and odd["text"] == "" and odd["color"] == "" and odd["follow"] is False
assert _regions(area("lines", "speed", color="#00ff00"))[0]["color"] == "#00ff00"
assert _regions(area("text", "dots"))[0]["look"] == "", "a text area has no look"
def test_the_status_counts_tones_lines_and_frames():
# type: () -> None
scene = arrange(art(), regions=area("tone") + area("frame", id="b", rect=(10, 10, 60, 50)))
assert scene["info"]["decorated"] == 2
assert "tones, lines and frames: 2" in web.describe(scene["info"])[0]
def test_an_image_with_transparency_keeps_it():
# type: () -> None
base = Image.new("RGBA", SIZE, (200, 100, 50, 255))
base.paste((0, 0, 0, 0), (0, 0, 60, 60))
assert has_alpha(base) and not has_alpha(Image.new("RGB", SIZE))
shown, _ = letter(base, caption="Hi", placement="center")
assert shown.mode == "RGBA" and shown.getpixel((10, 10))[3] == 0 and shown.getpixel((300, 250))[3] == 255
session = web.new_session(base, "t")
assert session["image"].mode == "RGBA"
assert web.new_session(Image.new("RGB", SIZE), "t")["image"].mode == "RGB"
buffer = io.BytesIO()
web.render_session(session, "", "Hi", "", False, {})
session["result"].save(buffer, "PNG")
assert Image.open(io.BytesIO(buffer.getvalue())).mode == "RGBA"
def test_a_turned_photo_is_set_upright():
# type: () -> None
sideways = Image.new("RGB", (40, 20), (255, 0, 0))
exif = Image.Exif()
exif[0x0112] = 6 # rotated a quarter turn: a browser shows it 20 wide and 40 tall
buffer = io.BytesIO()
sideways.save(buffer, "JPEG", exif=exif)
status, body = web.answer_upload(buffer.getvalue(), "photo.jpg")
assert status == 200 and (body["width"], body["height"]) == (20, 40)
assert upright(Image.open(io.BytesIO(buffer.getvalue()))).size == (20, 40)
plain = io.BytesIO()
sideways.save(plain, "PNG")
assert web.answer_upload(plain.getvalue(), "plain.png")[1]["width"] == 40
def test_a_placement_that_is_none_of_them_is_auto():
# type: () -> None
base = page()
auto = letter(base, caption="Hi", placement="auto")[0]
for bad in (None, "", "nowhere"):
assert np.array_equal(np.asarray(letter(base, caption="Hi", placement=bad)[0]), np.asarray(auto)), bad
def test_every_shipped_font_loads_has_latin_and_has_its_license():
# type: () -> None
names = os.listdir(BUNDLED_DIR)
fonts = [name for name in names if name.lower().endswith((".ttf", ".otf"))]
licenses = [name.lower() for name in os.listdir(os.path.join(BUNDLED_DIR, "licenses"))]
assert len(fonts) >= 26
for name in fonts:
ImageFont.truetype(os.path.join(BUNDLED_DIR, name), 20)
stem = name.split("-")[0].split(".")[0].lower()
assert any(entry.startswith(stem) for entry in licenses), "no license for " + name
shown = list_fonts()
for family in ("Bebas Neue", "Boogaloo", "Bubblegum Sans", "Gochi Hand", "Londrina Solid", "Londrina Solid Black", "Marmelad",
"Rubik Bubbles", "Stalinist One", "Underdog"):
assert family in shown, family
assert missing_glyphs(family, u"Hello, World! 0123456789 ?!.,") == "", family
for family in ("Marmelad", "Rubik Bubbles", "Stalinist One", "Underdog"):
assert missing_glyphs(family, u"Привет, мир!") == "", family + " should have Cyrillic"
|