File size: 63,859 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 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 | """Text layout and stylized rendering to an RGBA layer."""
import math
import random
from typing import List, Tuple
import numpy as np
from PIL import Image, ImageChops, ImageDraw, ImageFilter
from scipy import ndimage as ndi
from functools import lru_cache
from .fonts import load_font
EMPHASIS_SCALE = 1.3
# Characters drawn as shapes, because comic fonts do not have them.
SYMBOLS = {
u"\u2601": "breath",
u"💓": "heart_hatch",
u"\u2665": "heart", u"\u2764": "heart", u"\u2661": "heart_line",
u"\U0001F495": "hearts", u"\U0001F494": "heart_broken",
u"\u2605": "star", u"\u2606": "star_line",
u"\u2726": "spark", u"\u2728": "sparkles", u"\U0001F4A5": "burst",
u"\u266a": "note", u"\u266b": "notes",
u"\U0001F4A2": "anger", u"\u26a1": "bolt", u"\U0001F525": "flame",
u"\U0001F4A7": "drop", u"\U0001F4A6": "splash", u"\u2668": "steam", u"\U0001F4A8": "puff",
u"\U0001F4A4": "zzz", u"\U0001F300": "spiral", u"\U0001F4AB": "spiral",
u"\u3030": "wave", u"\u3003": "blush", u"\U0001F48B": "lips",
u"\u2642": "male", u"\u2640": "female",
u"\u273f": "flower", u"\U0001F319": "moon", u"\u2600": "sun",
u"\u2716": "cross", u"\u25cb": "ring",
u"\u2192": "arrow_right", u"\u2190": "arrow_left", u"\u2191": "arrow_up", u"\u2193": "arrow_down",
u"\u2666": "diamond", u"\u2660": "spade", u"\u2663": "club",
u"\U0001F60D": "heart_eyes", u"\U0001F644": "eyes_up", u"\U0001F445": "tongue", u"\U0001F924": "drool",
u"\U0001F4F3": "tremble", u"\U0001F32C": "speed", u"\u2739": "flash",
}
SYMBOL_WIDTH = 0.95 # of the font size
SHAPED_WORDS = 60 # a text of more words is only wrapped, not shaped: the shaping grows with their square
WIDTH_CACHE = 65536 # measured words kept; a page of text at every size the fitting tries is far fewer
# What can be scattered around a caption or a sound effect.
EXTRAS = {"none": None, "hearts": "heart", "sparkles": "spark", "stars": "star",
"notes": "note", "sweat": "drop", "anger": "anger", "motion lines": "motion",
"splashes": "splash", "steam": "steam", "sleep": "zzz", "bolts": "bolt", "flames": "flame",
"flowers": "flower", "hollow hearts": "heart_line", "hatched hearts": "heart_hatch", "tremble lines": "tremble", "speed lines": "speed"}
# Mood presets: how unruly the letters and the lines are. "custom" uses the sliders.
MOODS = {
"calm": dict(jitter=0.08, size_jitter=0.0, line_tilt=0.0, line_shift=0.0, line_spacing=1.08, rough=0.0),
"playful": dict(jitter=0.35, size_jitter=0.2, line_tilt=3.0, line_shift=0.15, line_spacing=1.12, rough=0.0),
"shout": dict(jitter=0.5, size_jitter=0.45, line_tilt=5.0, line_shift=0.25, line_spacing=1.05, rough=0.15),
"shaky": dict(jitter=2.2, size_jitter=0.4, line_tilt=3.0, line_shift=0.15, line_spacing=1.1, rough=0.5),
"rough": dict(jitter=0.3, size_jitter=0.1, line_tilt=1.0, line_shift=0.05, line_spacing=1.05, rough=1.3),
# Hand-lettered for a scream: letters of different sizes, lines tilted and staggered, torn edges.
"scream": dict(jitter=0.35, size_jitter=0.4, line_tilt=6.0, line_shift=0.3, line_spacing=0.95, rough=0.6),
"custom": None,
}
# Color presets. fill2 makes a top-to-bottom gradient, outer is a second outline,
# ink is the color used for plain text inside a light bubble.
PALETTES = {
"auto": None,
"black on white": dict(fill=(24, 24, 24), stroke=(255, 255, 255), ink=(24, 24, 24)),
"pink": dict(fill=(255, 143, 199), stroke=(255, 255, 255), outer=(60, 16, 40), ink=(214, 36, 127)),
"neon green": dict(fill=(140, 255, 90), stroke=(6, 32, 10), glow=(57, 255, 20), ink=(12, 122, 18)),
"gold": dict(fill=(255, 224, 110), fill2=(255, 150, 40), stroke=(58, 33, 0), ink=(150, 90, 0)),
"candy": dict(fill=(255, 122, 217), fill2=(164, 139, 255), stroke=(27, 11, 46), ink=(150, 60, 190)),
"blood": dict(fill=(235, 40, 45), stroke=(20, 0, 0), ink=(190, 20, 25)),
"ice": dict(fill=(200, 244, 255), fill2=(90, 170, 255), stroke=(6, 32, 58), ink=(30, 100, 190)),
"from the art": "accent",
"custom": "custom",
}
BUBBLE_SHAPES = ["none", "oval", "box", "cloud", "burst", "thought", "wavy", "jagged", "dashed", "drip", "torn", "message", "soft", "label"]
MESSAGE_RADIUS = 1.0 # of the font size: how round the corners of a message bubble are, at most
SOFT_BLUR = 0.5 # of the font size: how far the edge of a soft bubble is smeared
SOFT_ALPHA = 0.55 # how solid the middle of a soft bubble is
DRIP_TAIL = ((0.5, 0.22), (1.05, 0.17), (1.55, 0.13)) # drops of a dripping bubble's tail: where along it, radius of the font size
LABEL_ARROW = (2.6, 0.26, 0.95, 0.8) # of the font size: the arrow's length beyond the box, its shaft's width, its head's width and length
TORN_STEP = 0.55 # of the font size: the distance between the points along the edge of a torn box
TORN_SPIKE = (0.06, 0.32) # of the font size: how far a spike of a torn box reaches out, the least and the most
DRIP_GAP = 0.2 # of the font size: the least room between two drips
DRIP_CHANCE = 0.1 # per candidate pixel of a letter's underside, times (0.3 + amount)
DRIP_LENGTH = (0.2, 0.8) # of the font size, times (0.4 + amount)
DRIP_WIDTH = (0.1, 0.17) # of the font size: how thick a drip's neck is
GLOW_REACH = 0.7 # of the font size: how far a bubble's glow reaches, at full strength
DRIP_LOOSE = 0.25 # the share of drips that have a drop falling below them
BUBBLE_DRIPS = 8 # on the underside of a dripping bubble
JAGGED_SPIKES = 22 # of a jagged bubble
WAVES = 16 # of a wavy bubble: bumps round the outline
WAVE_DEPTH = 0.05 # how far a wavy bubble's outline swings in and out, of its radius
WAVE_STEPS = 160 # points of a wavy bubble's outline
DASHES = 28 # of a dashed bubble: dashes round the outline
DASH_SHARE = 0.55 # of each turn that is a dash, not a gap
# The tail of a thought bubble: small circles leading away from it. Each is
# (distance from the bubble's edge, share of the tail's length; radius, share of the font size).
THOUGHT_DOTS = ((0.2, 0.34), (0.6, 0.23), (0.95, 0.14))
# "black": black with no outline to be seen, light letters. "gray" and "blue": the fills of a phone's
# messages, with no outline either; the blue one has light letters.
BUBBLE_THEMES = ["light", "dark", "black", "gray", "blue"]
THEME_BODIES = {"black": (10, 10, 10), "gray": (229, 229, 234), "blue": (45, 156, 255)}
FLAT_THEMES = ("black", "gray", "blue") # themes with no outline of their own to be seen
DARK_THEMES = ("dark", "black", "blue") # themes the letters are light on
TAILS = {"none": None, "down-left": (-0.6, 1.0), "down": (0.0, 1.0), "down-right": (0.6, 1.0),
"left": (-1.0, 0.25), "right": (1.0, 0.25), "up-left": (-0.6, -1.0), "up": (0.0, -1.0),
"up-right": (0.6, -1.0), "custom": None} # "custom": the direction is Style.caption_tail_angle
class Style(object):
"""Lettering options shared by both hosts. Sizes are relative, so they scale with the image."""
def __init__(self, font="Comic Relief Bold", uppercase=True, text_color="auto",
stroke_color="auto", stroke_width=0.12, shadow=0.5, line_spacing=1.08,
rotation=0.0, jitter=0.3, arc=0.0, soften=0.4, grain=0.0, opacity=1.0,
free_size=5.5, bubble_size=9.0, bubble_min_size=1.5, margin=0.08, seed=0,
sfx_font="Bangers", sfx_size=7.0, sfx_color="auto", sfx_tilt=15.0,
sfx_opacity=0.95, sfx_seed=0, caption_font="", bubble_colors="auto",
caption_colors="auto", sfx_colors="auto", bubble_mood="calm",
caption_mood="calm", sfx_mood="shout", caption_extras="none",
sfx_extras="none", caption_bubble="none", caption_bubble_theme="light",
caption_tail="none", size_jitter=0.0, line_tilt=0.0, line_shift=0.0,
rough=0.0, bubble_stroke_width=0.0, bubble_stroke_color="auto",
text_color2="auto", sfx_color2="auto", gradient_angle=0.0, caption_bubble_color="auto",
caption_bubble_color2="auto", caption_tail_angle=45.0, drip=0.0, caption_bubble_glow=0.0,
extras_color="auto", sfx_glow=0.0, sfx_glow_color="auto",
bubble_glow=0.0, bubble_glow_color="auto"):
self.font = font
self.uppercase = uppercase
self.text_color = text_color # "auto" or "#RRGGBB"; used by the "custom" colors
self.stroke_color = stroke_color # "auto" or "#RRGGBB"; caption, "custom" colors
self.stroke_width = stroke_width # fraction of the font size; caption only
self.shadow = shadow # 0..1 strength; caption only
self.line_spacing = line_spacing
self.rotation = rotation # degrees, whole block
self.jitter = jitter # 0..1 per-letter wobble (baseline and angle)
self.arc = arc # -1..1 bend of the block
self.soften = soften # blur radius in px, blends letters with the art
self.grain = grain # 0..1 uneven ink
self.opacity = opacity
self.free_size = free_size # caption: font size, % of image height
self.bubble_size = bubble_size # bubble text: max font size, % of image height
self.bubble_min_size = bubble_min_size # smallest readable size, % of height
self.margin = margin # bubble: gap to the edge, fraction of bubble size
self.seed = seed
self.sfx_font = sfx_font # sound effects: their own font
self.sfx_size = sfx_size # font size, % of image height
self.sfx_color = sfx_color # "auto" or "#RRGGBB"; used by the "custom" colors
self.sfx_tilt = sfx_tilt # each effect is tilted by up to this many degrees
self.sfx_opacity = sfx_opacity
self.sfx_seed = sfx_seed # changes where the effects land and how they tilt
self.caption_font = caption_font # "" = the bubble font
self.bubble_colors = bubble_colors # a PALETTES name, for each kind of text
self.caption_colors = caption_colors
self.sfx_colors = sfx_colors
self.bubble_mood = bubble_mood # a MOODS name, for each kind of text
self.caption_mood = caption_mood
self.sfx_mood = sfx_mood
self.caption_extras = caption_extras # an EXTRAS name
self.sfx_extras = sfx_extras
self.caption_bubble = caption_bubble # draw a bubble behind the caption: BUBBLE_SHAPES
self.caption_bubble_theme = caption_bubble_theme
self.caption_tail = caption_tail # a TAILS name
self.size_jitter = size_jitter # 0..1 letters of different sizes ("custom" mood)
self.line_tilt = line_tilt # each line tilted by up to this many degrees
self.line_shift = line_shift # each line pushed sideways, fraction of the font size
self.rough = rough # 0..1 ragged, angular letter edges
self.bubble_stroke_width = bubble_stroke_width # fraction of the font size; text on a bubble fill; 0 = no outline
self.bubble_stroke_color = bubble_stroke_color # "auto" or "#RRGGBB"; with any colors, not only "custom"
self.text_color2 = text_color2 # "auto" or "#RRGGBB": the bottom of a gradient from text_color; "custom" colors, bubbles and caption
self.sfx_color2 = sfx_color2 # the same for sound effects, from sfx_color
self.gradient_angle = gradient_angle # degrees, every gradient: 0 runs top to bottom, 90 left to right
self.caption_bubble_color = caption_bubble_color # "auto" (the theme's) or "#RRGGBB": the fill of the caption's bubble
self.caption_bubble_color2 = caption_bubble_color2 # "auto" or "#RRGGBB": the bottom of a gradient from it
self.caption_tail_angle = caption_tail_angle # degrees, with caption_tail "custom": 0 points right, 90 down
self.drip = drip # 0..1: drips run down from the letters, none to many and long; every kind of text
self.caption_bubble_glow = caption_bubble_glow # 0..1: a glow of the outline's color round the caption's bubble
self.bubble_glow = bubble_glow # 0..1: a glow round the bubbles you draw yourself (areas with a bubble fill)
self.bubble_glow_color = bubble_glow_color # "auto" (white, or the body of a gray or blue bubble) or "#RRGGBB"
self.sfx_glow = sfx_glow # 0..1: a glow round the letters of a sound effect, none to strong
self.sfx_glow_color = sfx_glow_color # "auto" (the letters' color) or "#RRGGBB"
self.extras_color = extras_color # "auto" (the text's color) or "#RRGGBB": the marks around a caption or an effect
class Paint(object):
"""Colors of one piece of lettering."""
def __init__(self, fill, stroke=None, stroke_px=0, outer=None, outer_px=0, fill2=None,
glow=None, shadow=0.0, bold_px=0, angle=0.0, glow_power=None):
self.angle = angle # of the gradient from fill to fill2, degrees: 0 top to bottom
self.bold_px = bold_px # thickens the fill itself, for thin fonts
self.fill = fill
self.fill2 = fill2 # bottom color of a vertical gradient
self.stroke = stroke
self.stroke_px = stroke_px if stroke is not None else 0
self.outer = outer # second outline, outside the first
self.outer_px = outer_px if outer is not None else 0
self.glow = glow
self.glow_power = glow_power # 0..1 for a glow asked for by the user; None for a palette's own
self.shadow = shadow
def parse_color(value, default):
# type: (str, Tuple[int, int, int]) -> Tuple[int, int, int]
text = (value or "").strip().lstrip("#")
if len(text) == 3:
text = "".join(c * 2 for c in text)
if len(text) == 6:
try:
return (int(text[0:2], 16), int(text[2:4], 16), int(text[4:6], 16))
except ValueError:
pass
return default
def parse_text(text, uppercase):
"""Split into paragraphs of (word, emphasized, glued). *word* marks emphasis."""
text = text.replace(u"️", "").replace("<3", u"♥")
if uppercase:
text = text.upper()
paragraphs = [[]]
word = ""
word_emph = False
emph = False
glue = False # the next piece continues a hyphenated word: no space before it
for ch in text.replace("\r", ""):
if ch == "*":
emph = not emph
elif ch == "\n" or ch.isspace():
if word:
paragraphs[-1].append((word, word_emph, glue))
word = ""
glue = False
if ch == "\n":
paragraphs.append([])
else:
if not word:
word_emph = emph
word += ch
if ch == "-" and word.strip("-"):
# "H-m-m" -> "H-", "m-", "m": a line may break after a hyphen.
paragraphs[-1].append((word, word_emph, glue))
word = ""
glue = True
if word:
paragraphs[-1].append((word, word_emph, glue))
return [p for p in paragraphs if p] or [[]]
def get_fonts(style, size):
return load_font(style.font, size), load_font(style.font, int(round(size * EMPHASIS_SCALE)))
@lru_cache(maxsize=128)
def stem_ratio(font_name):
"""Stroke thickness of a font relative to its size: about 0.05 thin, 0.15 bold."""
font = load_font(font_name, 200)
image = Image.new("L", (400, 400), 0)
ImageDraw.Draw(image).text((100, 300), "I", font=font, fill=255, anchor="ls")
rows = (np.asarray(image) > 128).sum(axis=1)
rows = rows[rows > 0]
if len(rows) < 8:
return 0.12
return float(np.median(rows[len(rows) // 4: 3 * len(rows) // 4])) / 200.0
def pieces(word):
"""Split a word into runs of plain text and single symbols: [(kind or None, text)]."""
result = []
run = ""
for ch in word:
if ch in SYMBOLS:
if run:
result.append((None, run))
run = ""
result.append((SYMBOLS[ch], ch))
else:
run += ch
if run:
result.append((None, run))
return result
@lru_cache(maxsize=WIDTH_CACHE)
def _text_length(font, text):
# The fitting measures the same words at the same sizes again and again, one layout after
# another; a font is one object per (name, size) (load_font), so it is a fine cache key.
return font.getlength(text)
def text_width(font, word):
"""Width of a word, counting drawn symbols at their own width."""
return sum(font.size * SYMBOL_WIDTH if kind else _text_length(font, text)
for kind, text in pieces(word))
def layout(paragraphs, fonts, max_width):
"""Greedy word wrap. Returns [(words, width)], words = [(text, emphasized, width, glued)]."""
base, big = fonts
space = _text_length(base, " ")
lines = []
for para in paragraphs:
current = []
width = 0.0
for word, emph, glue in para:
word_w = text_width(big if emph else base, word)
gap = 0.0 if glue else space
if current and width + gap + word_w > max_width:
lines.append((current, width))
current = []
width = 0.0
width = word_w if not current else width + gap + word_w
current.append((word, emph, word_w, glue))
lines.append((current, width))
return lines
def diamond_profile(count):
"""Relative line widths of a text block that follows an oval: short, long, short."""
return [math.sqrt(max(0.0, 1.0 - ((2 * i + 1 - count) / float(count)) ** 2))
for i in range(count)]
def layout_shaped(paragraphs, fonts, count):
"""Break a single paragraph into `count` lines whose widths follow an oval.
Greedy wrapping fills the first lines and leaves a short last one. This picks the
breaks that bring the line widths closest to the diamond profile instead. Returns
lines in the same form as layout(), or None when it does not apply.
"""
if len(paragraphs) != 1:
return None
base, big = fonts
space = _text_length(base, " ")
tokens =[(word, emph, text_width(big if emph else base, word), glue)
for word, emph, glue in paragraphs[0]]
total_tokens = len(tokens)
if count < 2 or count > total_tokens or total_tokens > SHAPED_WORDS:
return None
gaps = [0.0 if glue else space for _, _, _, glue in tokens]
reach = [0.0]
for index, token in enumerate(tokens):
reach.append(reach[-1] + token[2] + (gaps[index] if index else 0.0))
def width(start, stop):
return reach[stop] - reach[start] - (gaps[start] if start else 0.0)
profile = diamond_profile(count)
targets = [width(0, total_tokens) * p / sum(profile) for p in profile]
infinity = float("inf")
# best[line][stop]: least squared error with tokens[:stop] on the first `line` lines.
best = [[infinity] * (total_tokens + 1) for _ in range(count + 1)]
cut = [[0] * (total_tokens + 1) for _ in range(count + 1)]
best[0][0] = 0.0
for line in range(1, count + 1):
for stop in range(line, total_tokens - (count - line) + 1):
for start in range(line - 1, stop):
if best[line - 1][start] == infinity:
continue
cost = best[line - 1][start] + (width(start, stop) - targets[line - 1]) ** 2
if cost < best[line][stop]:
best[line][stop] = cost
cut[line][stop] = start
lines = []
stop = total_tokens
for line in range(count, 0, -1):
start = cut[line][stop]
lines.append((tokens[start:stop], width(start, stop)))
stop = start
lines.reverse()
return lines
def shape_score(lines):
"""How far a layout is from the diamond shape; lower is better. One line scores 0."""
widths = [w for _, w in lines]
count = len(widths)
if count <= 1:
return 0.0
widest = max(widths) or 1.0
profile = diamond_profile(count)
top = max(profile)
score = sum((w / widest - p / top) ** 2 for w, p in zip(widths, profile)) / count
if widths[-1] < 0.4 * widest:
score += 0.5 # a lone short word on the last line
if widths[0] < 0.3 * widest:
score += 0.2
return score + 0.02 * count
def line_heights(lines, size, style):
"""Height of every line; a line with an emphasized word is taller."""
heights = []
for words, _ in lines:
scale = EMPHASIS_SCALE if any(emph for _, emph, _, _ in words) else 1.0
heights.append(int(math.ceil(size * scale * style.line_spacing)))
return heights
def block_size(lines, size, style):
width = max([w for _, w in lines] or [0.0])
return width, sum(line_heights(lines, size, style))
# ---------------------------------------------------------------- symbols
def _heart():
points = []
for step in range(60):
t = 2 * math.pi * step / 60.0
x = 16 * math.sin(t) ** 3
y = 13 * math.cos(t) - 5 * math.cos(2 * t) - 2 * math.cos(3 * t) - math.cos(4 * t)
points.append((0.5 + x / 34.0, 0.47 - y / 34.0))
return [points]
def _star(spikes, inner):
points = []
for step in range(spikes * 2):
radius = 0.5 if step % 2 == 0 else inner
angle = math.pi * step / spikes - math.pi / 2
points.append((0.5 + radius * math.cos(angle), 0.5 + radius * math.sin(angle)))
return [points]
def _ellipse(cx, cy, rx, ry, steps=28):
return [(cx + rx * math.cos(2 * math.pi * s / steps), cy + ry * math.sin(2 * math.pi * s / steps))
for s in range(steps)]
def _drop():
points = [(0.5, 0.02)]
for step in range(25):
angle = math.radians(-35 + 250 * step / 24.0)
points.append((0.5 + 0.3 * math.cos(angle), 0.66 + 0.3 * math.sin(angle)))
return [points]
def _note():
return [_ellipse(0.36, 0.8, 0.22, 0.16), [(0.5, 0.08), (0.6, 0.08), (0.6, 0.82), (0.5, 0.82)],
[(0.6, 0.08), (0.9, 0.3), (0.9, 0.46), (0.6, 0.26)]]
def _anger():
polygons = []
corner = [(0.57, 0.43), (0.57, 0.04), (0.75, 0.04), (0.75, 0.25), (0.96, 0.25), (0.96, 0.43)]
for quarter in range(4):
angle = math.pi / 2 * quarter
polygons.append([(0.5 + (x - 0.5) * math.cos(angle) - (y - 0.5) * math.sin(angle),
0.5 + (x - 0.5) * math.sin(angle) + (y - 0.5) * math.cos(angle))
for x, y in corner])
return polygons
def _cut(points):
"""A polygon that is taken out of what was drawn before it, not added."""
return {"cut": points}
def _points(shape):
return shape["cut"] if isinstance(shape, dict) else shape
def _moved(shapes, scale, cx, cy, turn=0.0):
"""Shapes shrunk about the middle of the tile, turned (degrees, clockwise) and put at cx, cy."""
cos, sin = math.cos(math.radians(turn)), math.sin(math.radians(turn))
out = []
for shape in shapes:
points = [(cx + scale * ((x - 0.5) * cos - (y - 0.5) * sin), cy + scale * ((x - 0.5) * sin + (y - 0.5) * cos))
for x, y in _points(shape)]
out.append(_cut(points) if isinstance(shape, dict) else points)
return out
def _line(points, wide):
"""A line of the given width through the points, with round ends and joints."""
shapes = []
for (x0, y0), (x1, y1) in zip(points, points[1:]):
length = math.hypot(x1 - x0, y1 - y0) or 1.0
nx, ny = -(y1 - y0) / length * wide / 2.0, (x1 - x0) / length * wide / 2.0
shapes.append([(x0 + nx, y0 + ny), (x1 + nx, y1 + ny), (x1 - nx, y1 - ny), (x0 - nx, y0 - ny)])
shapes.extend(_ellipse(x, y, wide / 2.0, wide / 2.0, 14) for x, y in points)
return shapes
def _inside(x, y, polygon):
"""Whether a point is inside a polygon (the even-odd rule)."""
inside = False
for (x0, y0), (x1, y1) in zip(polygon, polygon[1:] + polygon[:1]):
if (y0 > y) != (y1 > y) and x < x0 + (y - y0) * (x1 - x0) / (y1 - y0):
inside = not inside
return inside
def _hatched(outline, inner, gap, wide):
"""An outline of `outline` minus `inner`, with diagonal lines across `inner`, kept inside it."""
shapes = outline + _cuts(inner)
box = inner[0]
for k in range(-12, 13):
run = []
for step in range(81):
t = step / 80.0
x, y = 0.5 + k * gap + (t - 0.5) * 0.9, 0.5 + (t - 0.5) * 0.9
if _inside(x, y, box):
run.append((x, y))
elif len(run) > 1:
shapes += _line([run[0], run[-1]], wide)
run = []
else:
run = []
if len(run) > 1:
shapes += _line([run[0], run[-1]], wide)
return shapes
def _cuts(shapes):
return [_cut(_points(shape)) for shape in shapes]
def _z():
return [[(0.0, 0.0), (1.0, 0.0), (1.0, 0.22), (0.4, 0.78), (1.0, 0.78), (1.0, 1.0), (0.0, 1.0), (0.0, 0.78),
(0.6, 0.22), (0.0, 0.22)]]
def _arrow():
return [[(0.04, 0.38), (0.56, 0.38), (0.56, 0.16), (0.96, 0.5), (0.56, 0.84), (0.56, 0.62), (0.04, 0.62)]]
def _more_shapes():
"""The marks added to the first six; each fills the unit square like they do."""
heart, drop, spark = _heart(), _drop(), _star(4, 0.13)
stem = [(0.5, 0.56), (0.68, 0.98), (0.32, 0.98)]
spiral = [(0.5 + (0.04 + 0.42 * t) * math.cos(2 * math.pi * 2.4 * t), 0.5 + (0.04 + 0.42 * t) * math.sin(2 * math.pi * 2.4 * t))
for t in [step / 70.0 for step in range(71)]]
wave = [(0.05 + 0.9 * t, 0.5 + 0.17 * math.sin(2 * math.pi * 2 * t)) for t in [step / 40.0 for step in range(41)]]
steam = []
for x0 in (0.24, 0.5, 0.76):
steam += _line([(x0 + 0.07 * math.sin(2 * math.pi * 1.5 * t), 0.92 - 0.84 * t) for t in [s / 24.0 for s in range(25)]], 0.075)
rays = []
for step in range(8):
angle = math.pi / 4 * step
rays += _line([(0.5 + 0.34 * math.cos(angle), 0.5 + 0.34 * math.sin(angle)),
(0.5 + 0.46 * math.cos(angle), 0.5 + 0.46 * math.sin(angle))], 0.075)
petals = [_ellipse(0.5 + 0.27 * math.cos(2 * math.pi * k / 5 - math.pi / 2),
0.5 + 0.27 * math.sin(2 * math.pi * k / 5 - math.pi / 2), 0.2, 0.2) for k in range(5)]
# Short arcs on both sides, as drawn around something that shakes.
tremble = []
for radius in (0.24, 0.42):
for start, stop in ((145, 215), (-35, 35)):
tremble += _line([(0.5 + radius * math.cos(math.radians(start + (stop - start) * s / 9.0)),
0.5 + radius * math.sin(math.radians(start + (stop - start) * s / 9.0))) for s in range(10)], 0.075)
speed = []
for y, x0, x1 in ((0.16, 0.3, 0.98), (0.38, 0.05, 0.92), (0.62, 0.2, 0.98), (0.84, 0.08, 0.76)):
speed += _line([(x0, y), (x1, y)], 0.085)
# A flash: spikes of uneven length round a small middle.
reaches = (0.5, 0.38, 0.48, 0.34, 0.5, 0.4, 0.46, 0.36, 0.5, 0.42)
flash = [(0.5 + (reaches[i // 2] if i % 2 == 0 else 0.18) * math.cos(math.pi * i / len(reaches) - math.pi / 2),
0.5 + (reaches[i // 2] if i % 2 == 0 else 0.18) * math.sin(math.pi * i / len(reaches) - math.pi / 2))
for i in range(2 * len(reaches))]
tongue = [(0.27, 0.02), (0.73, 0.02)] + [(0.5 + 0.23 * math.cos(math.radians(a)), 0.62 + 0.23 * math.sin(math.radians(a)))
for a in range(0, 181, 15)]
eyes = []
for x in (0.26, 0.74): # the whites, with a pupil rolled up
eyes += [_ellipse(x, 0.5, 0.23, 0.32), _cut(_ellipse(x, 0.5, 0.16, 0.25)), _ellipse(x, 0.36, 0.09, 0.1)]
return {
"heart_eyes": _moved(heart, 0.46, 0.25, 0.5) + _moved(heart, 0.46, 0.75, 0.5),
"eyes_up": eyes,
"tongue": [tongue] + _cuts(_line([(0.5, 0.26), (0.5, 0.74)], 0.045)),
"drool": _line([(0.5, 0.0), (0.5, 0.52)], 0.07) + _moved(drop, 0.48, 0.5, 0.74),
"tremble": tremble,
"speed": speed,
"flash": [flash],
"heart_line": heart + _cuts(_moved(heart, 0.64, 0.5, 0.5)),
"heart_hatch": _hatched(heart, _moved(heart, 0.7, 0.5, 0.5)[0:1], 0.1, 0.05),
"hearts": _moved(heart, 0.68, 0.36, 0.62) + _moved(heart, 0.44, 0.76, 0.26, 14),
"heart_broken": heart + _cuts(_line([(0.52, 0.1), (0.42, 0.3), (0.57, 0.46), (0.44, 0.64), (0.5, 0.92)], 0.07)),
"star_line": _star(5, 0.2) + _cuts(_moved(_star(5, 0.2), 0.52, 0.5, 0.52)),
"sparkles": _moved(spark, 0.72, 0.38, 0.58) + _moved(spark, 0.4, 0.78, 0.24) + _moved(spark, 0.3, 0.82, 0.8),
"burst": _star(10, 0.3),
"notes": [_ellipse(0.22, 0.8, 0.17, 0.13), _ellipse(0.68, 0.72, 0.17, 0.13),
[(0.3, 0.16), (0.39, 0.16), (0.39, 0.8), (0.3, 0.8)], [(0.76, 0.08), (0.85, 0.08), (0.85, 0.72), (0.76, 0.72)],
[(0.3, 0.16), (0.85, 0.08), (0.85, 0.27), (0.3, 0.35)]],
"bolt": [[(0.6, 0.02), (0.2, 0.55), (0.46, 0.55), (0.34, 0.98), (0.82, 0.4), (0.54, 0.4), (0.74, 0.02)]],
"flame": [[(0.5, 0.02), (0.62, 0.2), (0.8, 0.38), (0.88, 0.6), (0.8, 0.82), (0.62, 0.96), (0.5, 0.98), (0.36, 0.96),
(0.2, 0.84), (0.12, 0.64), (0.18, 0.46), (0.3, 0.36), (0.34, 0.52), (0.44, 0.4), (0.46, 0.2)],
_cut([(0.5, 0.56), (0.6, 0.7), (0.6, 0.84), (0.5, 0.9), (0.4, 0.84), (0.4, 0.7)])],
"splash": _moved(drop, 0.5, 0.5, 0.27) + _moved(drop, 0.46, 0.22, 0.7, -32) + _moved(drop, 0.46, 0.78, 0.7, 32),
"steam": steam,
"puff": [_ellipse(0.62, 0.5, 0.27, 0.23), _ellipse(0.4, 0.57, 0.2, 0.17), _ellipse(0.8, 0.64, 0.16, 0.14)]
+ _line([(0.03, 0.42), (0.17, 0.42)], 0.06) + _line([(0.02, 0.64), (0.14, 0.64)], 0.06),
"breath": [_ellipse(0.5, 0.56, 0.3, 0.24), _ellipse(0.3, 0.5, 0.2, 0.19), _ellipse(0.42, 0.32, 0.19, 0.18),
_ellipse(0.63, 0.31, 0.2, 0.19), _ellipse(0.78, 0.48, 0.19, 0.18), _ellipse(0.7, 0.68, 0.17, 0.15),
_ellipse(0.34, 0.7, 0.16, 0.14), _ellipse(0.14, 0.72, 0.1, 0.09), _ellipse(0.05, 0.84, 0.05, 0.05)],
"zzz": _moved(_z(), 0.46, 0.26, 0.74) + _moved(_z(), 0.3, 0.68, 0.38) + _moved(_z(), 0.18, 0.9, 0.1),
"spiral": _line(spiral, 0.085),
"wave": _line(wave, 0.1),
"blush": [shape for k in range(3) for shape in _line([(0.12 + 0.28 * k, 0.82), (0.32 + 0.28 * k, 0.18)], 0.085)],
"lips": [[(0.03, 0.5), (0.22, 0.3), (0.4, 0.23), (0.5, 0.32), (0.6, 0.23), (0.78, 0.3), (0.97, 0.5), (0.78, 0.74),
(0.5, 0.85), (0.22, 0.74)]]
+ _cuts(_line([(0.13, 0.5), (0.35, 0.47), (0.5, 0.53), (0.65, 0.47), (0.87, 0.5)], 0.04)),
"male": [_ellipse(0.4, 0.62, 0.32, 0.32), _cut(_ellipse(0.4, 0.62, 0.2, 0.2))]
+ _line([(0.63, 0.39), (0.9, 0.12)], 0.1) + _line([(0.62, 0.1), (0.91, 0.1), (0.91, 0.39)], 0.1),
"female": [_ellipse(0.5, 0.33, 0.29, 0.29), _cut(_ellipse(0.5, 0.33, 0.17, 0.17))]
+ _line([(0.5, 0.62), (0.5, 0.96)], 0.11) + _line([(0.3, 0.8), (0.7, 0.8)], 0.11),
"flower": petals + [_cut(_ellipse(0.5, 0.5, 0.1, 0.1))],
"moon": [_ellipse(0.48, 0.5, 0.46, 0.46, 40), _cut(_ellipse(0.66, 0.42, 0.38, 0.38, 40))],
"sun": [_ellipse(0.5, 0.5, 0.24, 0.24)] + rays,
"cross": _line([(0.14, 0.14), (0.86, 0.86)], 0.17) + _line([(0.86, 0.14), (0.14, 0.86)], 0.17),
"ring": [_ellipse(0.5, 0.5, 0.46, 0.46, 40), _cut(_ellipse(0.5, 0.5, 0.31, 0.31, 40))],
"arrow_right": _arrow(), "arrow_down": _moved(_arrow(), 1.0, 0.5, 0.5, 90),
"arrow_left": _moved(_arrow(), 1.0, 0.5, 0.5, 180), "arrow_up": _moved(_arrow(), 1.0, 0.5, 0.5, 270),
"diamond": [[(0.5, 0.02), (0.88, 0.5), (0.5, 0.98), (0.12, 0.5)]],
"spade": _moved(heart, 0.84, 0.5, 0.42, 180) + [stem],
"club": [_ellipse(0.5, 0.27, 0.22, 0.22), _ellipse(0.27, 0.58, 0.22, 0.22), _ellipse(0.73, 0.58, 0.22, 0.22),
_ellipse(0.5, 0.5, 0.14, 0.14), stem],
}
SHAPES = {"heart": _heart(), "star": _star(5, 0.2), "spark": _star(4, 0.13), "drop": _drop(),
"note": _note(), "anger": _anger()}
SHAPES.update(_more_shapes())
def symbol_tile(kind, px, grow=0):
"""A symbol as an 'L' mask of side px + 2 * grow, optionally grown for an outline."""
px = max(4, int(px))
scale = 4
big = Image.new("L", (px * scale, px * scale), 0)
draw = ImageDraw.Draw(big)
for shape in SHAPES[kind]: # in order: a cut takes out of what is already there
draw.polygon([(x * px * scale, y * px * scale) for x, y in _points(shape)],
fill=0 if isinstance(shape, dict) else 255)
tile = Image.new("L", (px + 2 * grow, px + 2 * grow), 0)
tile.paste(big.resize((px, px), Image.LANCZOS), (grow, grow))
if grow > 0:
tile = tile.filter(ImageFilter.MaxFilter(2 * min(grow, 15) + 1))
return tile
# ---------------------------------------------------------------- rendering
def _solid(color, mask):
layer = Image.new("RGBA", mask.size, tuple(color) + (0,))
layer.putalpha(mask)
return layer
def _gradient(top, bottom, mask, angle=0.0):
"""A gradient across the inked part of the mask, from `top` to `bottom` along a direction:
angle 0 is down the rows, 90 is along them from left to right (degrees)."""
bounds = mask.getbbox()
if bounds is None:
return _solid(top, mask)
if angle % 360.0 == 0.0:
rows = np.clip((np.arange(mask.height) - bounds[1]) / float(max(1, bounds[3] - bounds[1] - 1)), 0, 1)
colors = np.array(top, dtype=np.float32)[None, :] * (1 - rows[:, None]) \
+ np.array(bottom, dtype=np.float32)[None, :] * rows[:, None]
array = np.repeat(colors[:, None, :], mask.width, axis=1).astype(np.uint8)
else:
wide, high = max(1, bounds[2] - bounds[0] - 1), max(1, bounds[3] - bounds[1] - 1)
sin, cos = math.sin(math.radians(angle)), math.cos(math.radians(angle))
ys, xs = np.mgrid[0:mask.height, 0:mask.width]
# How far along the direction each pixel is, against the length of the inked box in it.
along = ((xs - (bounds[0] + wide / 2.0)) * sin + (ys - (bounds[1] + high / 2.0)) * cos) \
/ max(1.0, abs(wide * sin) + abs(high * cos)) + 0.5
t = np.clip(along, 0, 1)[..., None].astype(np.float32)
array = (np.array(top, dtype=np.float32) * (1 - t) + np.array(bottom, dtype=np.float32) * t).astype(np.uint8)
layer = Image.fromarray(array, "RGB").convert("RGBA")
layer.putalpha(mask)
return layer
def _roughen(masks, amount, size, seed, stem=0.15):
"""Push the letter edges around with noise: ragged where it is smooth, angular where it is blocky.
Both the grain of the noise and its reach follow the stroke thickness of the font
(stem, relative to the size): a thin font gets a fine, shallow tremor that shows
on its hairlines without shredding them; a bold one gets big bites.
"""
if amount <= 0:
return masks
width, height = masks[0].size
state = np.random.RandomState(seed % (2 ** 32))
stem = max(0.04, min(0.16, stem))
cell = max(2, int(size * stem * 1.1))
reach = size * min(0.07, 0.75 * stem)
grid = (height // cell + 2, width // cell + 2)
def field():
coarse = state.uniform(-1, 1, grid)
smooth = ndi.zoom(coarse, (height / float(grid[0]), width / float(grid[1])), order=1)
blocky = np.kron(coarse, np.ones((cell, cell)))
canvas = np.zeros((height, width), dtype=np.float32)
sh, sw = min(height, smooth.shape[0]), min(width, smooth.shape[1])
canvas[:sh, :sw] = 0.55 * smooth[:sh, :sw]
canvas += 0.45 * blocky[:height, :width]
return canvas * amount * reach
rows, cols = np.mgrid[0:height, 0:width].astype(np.float32)
coords = [rows + field(), cols + field()]
return [Image.fromarray(ndi.map_coordinates(np.asarray(mask, dtype=np.float32), coords, order=1,
mode="constant").clip(0, 255).astype(np.uint8), "L")
for mask in masks]
def _draw_line(masks, grows, words, x, baseline, center_x, half, size, style, fonts, rng):
"""Draw one line of words into the masks (one mask per outline width in `grows`)."""
base, big = fonts
space = base.getlength(" ")
arc_amp = style.arc * size * 0.9
per_char = style.jitter > 0 or style.arc != 0 or style.size_jitter > 0
for position, (word, emph, word_w, glue) in enumerate(words):
font = big if emph else base
if position and not glue:
x += space
cursor = x
for kind, run in pieces(word):
units = [run] if (kind or not per_char) else list(run)
for unit in units:
unit_font = font
if per_char and style.size_jitter > 0:
unit_font = load_font(style.font, max(6, int(round(
font.size * (1 + rng.uniform(-1, 1) * 0.28 * style.size_jitter)))))
unit_w = unit_font.size * SYMBOL_WIDTH if kind else unit_font.getlength(unit)
if not per_char and not kind:
for mask, grow in zip(masks, grows):
ImageDraw.Draw(mask).text((cursor, baseline), unit, font=unit_font, fill=255,
anchor="ls", stroke_width=grow)
cursor += unit_w
continue
t = ((cursor + unit_w / 2.0) - center_x) / half
dy = arc_amp * t * t + rng.uniform(-1, 1) * style.jitter * 0.07 * size
angle = -math.degrees(math.atan(2 * arc_amp * t / half))
angle += rng.uniform(-1, 1) * style.jitter * 7.0
for mask, grow in zip(masks, grows):
if kind:
px = int(unit_font.size * 0.82)
tile = symbol_tile(kind, px, grow)
origin = (int(round(cursor + (unit_w - px) / 2.0)) - grow,
int(round(baseline + dy)) - px - grow)
else:
m = int(unit_font.size * 0.6) + grow
tile = Image.new("L", (int(math.ceil(unit_w)) + 2 * m,
int(unit_font.size * 1.4) + 2 * m), 0)
ImageDraw.Draw(tile).text((m, m + unit_font.size), unit, font=unit_font,
fill=255, anchor="ls", stroke_width=grow)
origin = (int(round(cursor)) - m, int(round(baseline + dy)) - (m + unit_font.size))
if angle:
tile = tile.rotate(angle, resample=Image.BICUBIC)
mask.paste(255, origin, tile)
cursor += unit_w
x += word_w
def _drip(masks, grows, size, amount, seed):
# type: (List[Image.Image], List[int], int, float, int) -> List[Image.Image]
"""Drips running down from the underside of the letters, added to every mask (the fill and its
outlines grow round them as they do round the letters). amount 0..1 is how many and how long."""
ink = np.asarray(masks[0]) > 127
below = ink & ~np.roll(ink, -1, axis=0) # ink with no ink right under it: the underside of a stroke
rng = random.Random(seed * 131 + 7)
drops = Image.new("L", masks[0].size, 0)
pen = ImageDraw.Draw(drops)
gap = max(2, int(size * DRIP_GAP))
ys, xs = np.nonzero(below)
order = sorted(range(len(xs)), key=lambda i: (xs[i], ys[i]))
last = -gap
for i in order:
x, y = int(xs[i]), int(ys[i])
if x - last < gap or rng.random() > DRIP_CHANCE * (0.3 + amount):
continue
length = size * rng.uniform(*DRIP_LENGTH) * (0.4 + amount)
wide = max(2.0, size * rng.uniform(*DRIP_WIDTH))
if ink[min(ink.shape[0] - 1, y + 1):min(ink.shape[0], y + int(length) + 1), x].any():
continue # something is in the way: a drip would run through a letter
last = x
pen.rectangle((x - wide * 0.35, y - wide, x + wide * 0.35, y + length), fill=255) # the neck
pen.ellipse((x - wide * 0.6, y + length - wide * 0.6, x + wide * 0.6, y + length + wide * 0.8), fill=255) # the bulb
if rng.random() < DRIP_LOOSE: # one that has let go
fall = y + length + wide * rng.uniform(1.4, 2.6)
pen.ellipse((x - wide * 0.4, fall - wide * 0.5, x + wide * 0.4, fall + wide * 0.6), fill=255)
out = []
for mask, grow in zip(masks, grows):
grown = drops.filter(ImageFilter.MaxFilter(2 * min(grow, 15) + 1)) if grow > 0 else drops
out.append(ImageChops.lighter(mask, grown))
return out
def render_block(lines, size, style, paint):
# type: (List, int, Style, Paint) -> Image.Image
"""Render laid-out lines to an RGBA layer. The text block is centered in the layer."""
if not isinstance(paint, Paint):
paint = Paint(paint)
fonts = get_fonts(style, size)
rng = random.Random(style.seed)
heights = line_heights(lines, size, style)
block_w, block_h = block_size(lines, size, style)
grows = [paint.bold_px]
if paint.stroke_px > 0:
grows.append(paint.bold_px + paint.stroke_px)
if paint.outer_px > 0:
grows.append(paint.bold_px + paint.stroke_px + paint.outer_px)
reach = grows[-1]
sway = abs(style.line_shift) * size + math.sin(math.radians(min(45.0, abs(style.line_tilt)))) * block_w / 2.0
pad = int(size * 1.0 + reach + abs(style.arc * size * 0.9) + sway + size * 0.3 * style.size_jitter)
width = int(math.ceil(block_w)) + 2 * pad
height = block_h + 2 * pad
masks = [Image.new("L", (width, height), 0) for _ in grows]
half = (block_w / 2.0) or 1.0
top = pad
for index, (words, line_w) in enumerate(lines):
ink = heights[index] / style.line_spacing
tilt = rng.uniform(-1, 1) * style.line_tilt if style.line_tilt else 0.0
shift = rng.uniform(-1, 1) * style.line_shift * size if style.line_shift else 0.0
if not tilt:
x = pad + (block_w - line_w) / 2.0 + shift
baseline = top + heights[index] * 0.5 + ink * 0.35
_draw_line(masks, grows, words, x, baseline, pad + block_w / 2.0 + shift, half,
size, style, fonts, rng)
else:
# A tilted line is drawn on its own strip, turned, and laid onto the block.
margin = int(size * 1.0 + reach)
strip_size = (int(math.ceil(line_w)) + 2 * margin, heights[index] + 2 * margin)
strips = [Image.new("L", strip_size, 0) for _ in grows]
_draw_line(strips, grows, words, margin, margin + heights[index] * 0.5 + ink * 0.35,
margin + line_w / 2.0, half, size, style, fonts, rng)
for mask, strip in zip(masks, strips):
turned = strip.rotate(tilt, resample=Image.BICUBIC, expand=True)
mask.paste(255, (int(round(pad + block_w / 2.0 + shift - turned.width / 2.0)),
int(round(top + heights[index] / 2.0 - turned.height / 2.0))), turned)
top += heights[index]
masks = _roughen(masks, style.rough, size, style.seed, stem_ratio(style.font))
if style.drip > 0:
masks = _drip(masks, grows, size, style.drip, style.seed)
layer = Image.new("RGBA", (width, height), (0, 0, 0, 0))
ink_mask = masks[-1]
if paint.glow is not None:
power = paint.glow_power
halo = ink_mask.filter(ImageFilter.MaxFilter(3)).filter(
ImageFilter.GaussianBlur(max(2.0, size * 0.16 * (1.0 if power is None else 0.4 + 1.2 * power))))
boost = 1.6 if power is None else 1.2 + power
halo = halo.point(lambda v: min(255, int(v * boost)))
layer = Image.alpha_composite(layer, _solid(paint.glow, halo))
if paint.shadow > 0:
offset = max(1, int(round(size * 0.07)))
shade = ImageChops.offset(ink_mask, offset, offset).filter(ImageFilter.GaussianBlur(offset * 0.6))
shade = shade.point(lambda v: int(v * min(1.0, paint.shadow) * 0.75))
layer = Image.alpha_composite(layer, _solid((0, 0, 0), shade))
if len(masks) > 2:
layer = Image.alpha_composite(layer, _solid(paint.outer, masks[2]))
if len(masks) > 1:
layer = Image.alpha_composite(layer, _solid(paint.stroke, masks[1]))
if paint.fill2 is not None:
layer = Image.alpha_composite(layer, _gradient(paint.fill, paint.fill2, masks[0], paint.angle))
else:
layer = Image.alpha_composite(layer, _solid(paint.fill, masks[0]))
if style.rotation:
layer = layer.rotate(style.rotation, resample=Image.BICUBIC, expand=True)
return _finish(layer, style)
def _finish(layer, style):
"""Soften, grain and opacity, done on premultiplied alpha to avoid dark fringes."""
if style.soften <= 0 and style.grain <= 0 and style.opacity >= 1:
return layer
arr = np.asarray(layer).astype(np.float32) / 255.0
alpha = arr[..., 3]
rgb = arr[..., :3] * alpha[..., None]
if style.soften > 0:
alpha = ndi.gaussian_filter(alpha, style.soften)
rgb = np.stack([ndi.gaussian_filter(rgb[..., c], style.soften) for c in range(3)], axis=-1)
if style.grain > 0:
noise = np.random.RandomState(style.seed % (2 ** 32)).rand(*alpha.shape).astype(np.float32)
noise = ndi.gaussian_filter(noise, 0.8)
noise = (noise - noise.min()) / max(1e-6, float(noise.max() - noise.min()))
keep = 1.0 - min(1.0, style.grain) * noise
alpha = alpha * keep
rgb = rgb * keep[..., None]
if style.opacity < 1:
alpha = alpha * max(0.0, style.opacity)
rgb = rgb * max(0.0, style.opacity)
out = np.zeros_like(arr)
safe = np.maximum(alpha, 1e-6)
out[..., :3] = np.clip(rgb / safe[..., None], 0, 1)
out[..., 3] = np.clip(alpha, 0, 1)
return Image.fromarray((out * 255 + 0.5).astype(np.uint8), "RGBA")
def _mark_fits(avoid, center, canvas_size, x, y, w, h):
"""May a mark be drawn at (x, y) of the canvas? Not over `avoid`, not cut by the image edge."""
if avoid is None or center is None:
return True
rows, cols = avoid.shape
x0 = int(round(center[0] - canvas_size[0] / 2.0 + x))
y0 = int(round(center[1] - canvas_size[1] / 2.0 + y))
if x0 < 0 or y0 < 0 or x0 + w > cols or y0 + h > rows:
return False
return float(avoid[y0:y0 + h, x0:x0 + w].mean()) < 0.05
def decorate(layer, kind, size, paint, seed, avoid=None, center=None):
"""Scatter marks (or action lines) around a rendered block.
Returns a larger layer with the block still in its center. avoid is a boolean mask
of the image and center the place the block will be pasted at: a mark that would
land on the mask or be cut by the image edge is moved along the frame, or left out.
"""
if not kind:
return layer
rng = random.Random(seed * 7919 + 13)
margin = int(size * 2.1)
canvas = Image.new("RGBA", (layer.width + 2 * margin, layer.height + 2 * margin), (0, 0, 0, 0))
bounds = layer.getbbox() or (0, 0, layer.width, layer.height)
cx = margin + (bounds[0] + bounds[2]) / 2.0
cy = margin + (bounds[1] + bounds[3]) / 2.0
stroke = paint.stroke if paint.stroke is not None else (0, 0, 0)
if kind == "motion":
# Action lines: tapered strokes bursting out from the block, all around it.
rx = (bounds[2] - bounds[0]) / 2.0 + size * 0.25
ry = (bounds[3] - bounds[1]) / 2.0 + size * 0.2
draw = ImageDraw.Draw(canvas)
count = max(12, int((rx + ry) / (size * 0.42)))
for index in range(count):
angle = 2 * math.pi * index / count + rng.uniform(-0.1, 0.1)
dx, dy = math.cos(angle), math.sin(angle)
start = 1.0 + rng.uniform(0.0, 0.1)
x0, y0 = cx + rx * start * dx, cy + ry * start * dy
length = size * rng.uniform(0.7, 1.5)
half = size * rng.uniform(0.08, 0.14)
x1, y1 = x0 + dx * length, y0 + dy * length
if not _mark_fits(avoid, center, canvas.size, min(x0, x1) - half, min(y0, y1) - half,
int(abs(x1 - x0) + 2 * half) + 1, int(abs(y1 - y0) + 2 * half) + 1):
continue
draw.polygon([(x0 - dy * half, y0 + dx * half), (x0 + dy * half, y0 - dx * half), (x1, y1)],
fill=tuple(stroke) + (255,))
inset = max(1.0, size * 0.03)
inner = [(x0 + dx * inset - dy * (half - inset), y0 + dy * inset + dx * (half - inset)),
(x0 + dx * inset + dy * (half - inset), y0 + dy * inset - dx * (half - inset)),
(x0 + dx * (length - 3 * inset), y0 + dy * (length - 3 * inset))]
draw.polygon(inner, fill=tuple(paint.fill) + (255,))
else:
# Marks sit on a frame around the block, so none of them covers the letters.
rx = (bounds[2] - bounds[0]) / 2.0 + size * 0.7
ry = (bounds[3] - bounds[1]) / 2.0 + size * 0.7
count = rng.randint(5, 7)
start = rng.uniform(0, 2 * math.pi)
for index in range(count):
base = start + 2 * math.pi * index / count + rng.uniform(-0.25, 0.25)
px = int(size * rng.uniform(0.5, 0.85))
grow = max(2, int(px * 0.12))
tile = mark_tile(kind, px, paint.fill, stroke, grow)
tile = tile.rotate(rng.uniform(-25, 25), resample=Image.BICUBIC, expand=True)
for shift in (0.0, 0.35, -0.35, 0.7, -0.7): # slide along the frame to a free place
angle = base + shift
reach = min(rx / max(1e-6, abs(math.cos(angle))), ry / max(1e-6, abs(math.sin(angle))))
x = int(cx + reach * math.cos(angle) - tile.width / 2.0)
y = int(cy + reach * math.sin(angle) - tile.height / 2.0)
x = max(0, min(x, canvas.width - tile.width))
y = max(0, min(y, canvas.height - tile.height))
if _mark_fits(avoid, center, canvas.size, x, y, tile.width, tile.height):
canvas.alpha_composite(tile, (x, y))
break
canvas.alpha_composite(layer, (margin, margin))
return canvas
def mark_tile(kind, px, fill, outline, grow):
"""A mark as a colored RGBA tile: its shape in `fill`, with an outline `grow` pixels wide
around it. The tile is px + 2 * grow on a side."""
return Image.alpha_composite(_solid(outline, symbol_tile(kind, px, grow)),
_solid(fill, _pad_tile(symbol_tile(kind, px, 0), grow)))
def _pad_tile(tile, grow):
padded = Image.new("L", (tile.width + 2 * grow, tile.height + 2 * grow), 0)
padded.paste(tile, (grow, grow))
return padded
def _torn_outline(cx, cy, a, b, size, rng):
# type: (float, float, float, float, int, random.Random) -> List[Tuple[float, float]]
"""The points of a box that is torn along its edges: every other point is pushed out by a spike
of uneven length, the ones between a little in. a and b are the half sides."""
corners = [(cx - a, cy - b), (cx + a, cy - b), (cx + a, cy + b), (cx - a, cy + b)]
points = []
for (x0, y0), (x1, y1) in zip(corners, corners[1:] + corners[:1]):
length = math.hypot(x1 - x0, y1 - y0)
nx, ny = (y1 - y0) / length, -(x1 - x0) / length # the way out of the box, for a walk clockwise
count = max(2, int(length / (size * TORN_STEP)))
for index in range(count):
t = (index + rng.uniform(-0.2, 0.2)) / count
push = size * rng.uniform(*TORN_SPIKE) if index % 2 == 0 else -size * rng.uniform(0.0, 0.08)
points.append((x0 + (x1 - x0) * t + nx * push, y0 + (y1 - y0) * t + ny * push))
return points
def bubble_shape(kind, text_w, text_h, size, tail, seed, tail_angle=0.0):
"""A drawn speech bubble around a text block.
Returns (fill mask, outline mask, (cx, cy)): the masks share a size and (cx, cy) is
where the center of the text goes.
"""
rng = random.Random(seed * 31 + 5)
if kind in ("box", "torn", "message", "label"):
a = text_w / 2.0 + size * 0.7
b = text_h / 2.0 + size * 0.55
else:
a = text_w / 2.0 * 1.42 + size * 0.45
b = text_h / 2.0 * 1.42 + size * 0.4
if kind == "soft": # a soft edge needs room to fade out in
a, b = a * 1.1, b * 1.25
tail_len = size * 0.9 + b * 0.3
if kind == "label":
tail_len = size * LABEL_ARROW[0] + b * 0.3 # room for an arrow beside the box
thick = max(2, int(round(size * 0.09)))
margin = int(tail_len + max(a, b) * 0.32 + thick + 4 + (b * 0.8 + size if kind == "drip" else 0) # drips hang below
+ (size * 2 * SOFT_BLUR + size if kind == "soft" else 0)) # the blur of a soft patch reaches out
scale = 3
width = int(2 * a) + 2 * margin
height = int(2 * b) + 2 * margin
cx, cy = width / 2.0, height / 2.0
big = Image.new("L", (width * scale, height * scale), 0)
draw = ImageDraw.Draw(big)
def up(points):
return [(x * scale, y * scale) for x, y in points]
if kind == "box":
draw.rounded_rectangle(up([(cx - a, cy - b), (cx + a, cy + b)]), radius=size * 0.5 * scale, fill=255)
elif kind == "label": # a plain label with square corners; its tail is an arrow, drawn below
draw.rounded_rectangle(up([(cx - a, cy - b), (cx + a, cy + b)]), radius=size * 0.1 * scale, fill=255)
elif kind in ("cloud", "thought"): # a thought bubble is a cloud with a tail of small circles
radius = 0.36 * min(a, b)
draw.ellipse(up([(cx - a + radius * 0.6, cy - b + radius * 0.6),
(cx + a - radius * 0.6, cy + b - radius * 0.6)]), fill=255)
puffs = max(8, int(2 * math.pi * math.sqrt((a * a + b * b) / 2.0) / (radius * 1.15)))
for index in range(puffs):
angle = 2 * math.pi * index / puffs
px = cx + (a - radius * 0.75) * math.cos(angle)
py = cy + (b - radius * 0.75) * math.sin(angle)
r = radius * rng.uniform(0.85, 1.1)
draw.ellipse(up([(px - r, py - r), (px + r, py + r)]), fill=255)
elif kind == "burst":
spikes = 16
points = []
for index in range(spikes * 2):
angle = math.pi * index / spikes
reach = (1.3 + rng.uniform(-0.06, 0.1)) if index % 2 == 0 else 1.0
points.append((cx + a * reach * math.cos(angle), cy + b * reach * math.sin(angle)))
draw.polygon(up(points), fill=255)
elif kind == "jagged": # a shout drawn fast: many thin spikes of uneven length
points = []
for index in range(JAGGED_SPIKES * 2):
angle = math.pi * index / JAGGED_SPIKES
reach = (1.12 + rng.uniform(0.0, 0.3)) if index % 2 == 0 else (0.94 + rng.uniform(-0.04, 0.04))
points.append((cx + a * reach * math.cos(angle), cy + b * reach * math.sin(angle)))
draw.polygon(up(points), fill=255)
elif kind == "message": # a phone message: a rounded box with a small hook at the lower corner
radius = min(b, size * MESSAGE_RADIUS)
draw.rounded_rectangle(up([(cx - a, cy - b), (cx + a, cy + b)]), radius=radius * scale, fill=255)
side = -1 if tail in ("down-left", "left", "up-left") else 1 if tail in ("down-right", "right", "up-right") else 0
if side:
draw.polygon(up([(cx + side * (a - radius * 0.9), cy + b - radius * 0.6),
(cx + side * (a + size * 0.45), cy + b + size * 0.28),
(cx + side * (a - radius * 2.0), cy + b)]), fill=255)
elif kind == "soft": # a soft patch behind a thought or an aside: no outline, a blurred edge
draw.ellipse(up([(cx - a, cy - b), (cx + a, cy + b)]), fill=255)
elif kind == "torn": # a box with torn, spiky edges: the black caption boxes of a page
draw.polygon(up(_torn_outline(cx, cy, a, b, size, rng)), fill=255)
elif kind == "drip": # an oval with drips hanging from its underside, one of them let go
draw.ellipse(up([(cx - a, cy - b), (cx + a, cy + b)]), fill=255)
for index in range(BUBBLE_DRIPS):
turn = math.radians(25 + 130.0 * (index + rng.uniform(-0.25, 0.25)) / (BUBBLE_DRIPS - 1))
x, y = cx + 0.92 * a * math.cos(turn), cy + 0.92 * b * math.sin(turn)
length, wide = b * rng.uniform(0.15, 0.7), size * rng.uniform(0.1, 0.17)
draw.rectangle(up([(x - wide * 0.4, y - wide), (x + wide * 0.4, y + length)]), fill=255)
draw.ellipse(up([(x - wide * 0.7, y + length - wide * 0.6), (x + wide * 0.7, y + length + wide * 0.9)]), fill=255)
if index == BUBBLE_DRIPS // 2:
fall = y + length + wide * 2.2
draw.ellipse(up([(x - wide * 0.45, fall - wide * 0.5), (x + wide * 0.45, fall + wide * 0.7)]), fill=255)
elif kind == "wavy": # an outline that shakes: fear, a trembling voice
points = [(cx + a * (1 + WAVE_DEPTH * math.sin(WAVES * t)) * math.cos(t),
cy + b * (1 + WAVE_DEPTH * math.sin(WAVES * t)) * math.sin(t))
for t in [2 * math.pi * step / WAVE_STEPS for step in range(WAVE_STEPS)]]
draw.polygon(up(points), fill=255)
else:
draw.ellipse(up([(cx - a, cy - b), (cx + a, cy + b)]), fill=255)
direction = TAILS.get(tail)
if tail == "custom":
direction = (math.cos(math.radians(tail_angle)), math.sin(math.radians(tail_angle)))
if kind in ("message", "soft"):
direction = None # a message has its hook, a soft patch no tail
if kind == "label" and direction is not None:
# An arrow that leaves the box's edge, shaft and head in one piece: the outline draws round it.
length = math.hypot(*direction)
dx, dy = direction[0] / length, direction[1] / length
reach = min(a / abs(dx) if dx else 1e9, b / abs(dy) if dy else 1e9) # where the ray leaves the box
_, shaft, head, head_len = [size * value for value in LABEL_ARROW]
start = (cx + dx * (reach - size * 0.1), cy + dy * (reach - size * 0.1))
neck = (cx + dx * (reach + tail_len - head_len), cy + dy * (reach + tail_len - head_len))
tip = (cx + dx * (reach + tail_len), cy + dy * (reach + tail_len))
draw.polygon(up([(start[0] - dy * shaft / 2, start[1] + dx * shaft / 2), (start[0] + dy * shaft / 2, start[1] - dx * shaft / 2),
(neck[0] + dy * shaft / 2, neck[1] - dx * shaft / 2), (neck[0] + dy * head / 2, neck[1] - dx * head / 2),
tip, (neck[0] - dy * head / 2, neck[1] + dx * head / 2), (neck[0] - dy * shaft / 2, neck[1] + dx * shaft / 2)]),
fill=255)
direction = None
if direction is not None:
length = math.hypot(*direction)
dx, dy = direction[0] / length, direction[1] / length
angle = math.atan2(dy * a, dx * b) # where the ray leaves the ellipse
edge = (cx + a * math.cos(angle), cy + b * math.sin(angle))
if kind == "drip": # a dripping bubble lets its tail fall as drops, each pointing back at the bubble
for along, wide in DRIP_TAIL:
px, py = edge[0] + dx * tail_len * along, edge[1] + dy * tail_len * along
r = size * wide
draw.ellipse(up([(px - r, py - r), (px + r, py + r)]), fill=255)
draw.polygon(up([(px - dy * r * 0.92, py + dx * r * 0.92), (px + dy * r * 0.92, py - dx * r * 0.92),
(px - dx * r * 2.1, py - dy * r * 2.1)]), fill=255)
elif kind == "thought":
for along, wide in THOUGHT_DOTS:
px, py = edge[0] + dx * tail_len * along, edge[1] + dy * tail_len * along
draw.ellipse(up([(px - size * wide, py - size * wide), (px + size * wide, py + size * wide)]), fill=255)
else:
root = (cx + a * 0.78 * math.cos(angle), cy + b * 0.78 * math.sin(angle))
half = size * 0.42
draw.polygon(up([(root[0] - dy * half, root[1] + dx * half),
(root[0] + dy * half, root[1] - dx * half),
(edge[0] + dx * tail_len, edge[1] + dy * tail_len)]), fill=255)
fill_mask = big.resize((width, height), Image.LANCZOS)
if kind == "soft":
fill_mask = fill_mask.filter(ImageFilter.GaussianBlur(size * SOFT_BLUR)).point(lambda v: int(v * SOFT_ALPHA))
return fill_mask, Image.new("L", fill_mask.size, 0), (cx, cy) # no outline at all
outline = fill_mask.filter(ImageFilter.MaxFilter(2 * min(thick, 15) + 1))
if kind == "dashed": # a whisper: the outline in dashes
wedges = Image.new("L", outline.size, 0)
pen = ImageDraw.Draw(wedges)
reach = 2 * max(width, height)
for dash in range(DASHES):
start = 2 * math.pi * dash / DASHES
stop = start + 2 * math.pi / DASHES * DASH_SHARE
pen.polygon([(cx, cy), (cx + reach * math.cos(start), cy + reach * math.sin(start)),
(cx + reach * math.cos(stop), cy + reach * math.sin(stop))], fill=255)
ring = ImageChops.multiply(ImageChops.subtract(outline, fill_mask), wedges)
outline = ImageChops.lighter(ring, fill_mask)
return fill_mask, outline, (cx, cy)
def glow_around(layer, mask, color, reach):
# type: (Image.Image, Image.Image, Tuple[int, int, int], float) -> Image.Image
"""The layer on a canvas `reach` pixels larger on every side, with a glow of `color` round the
shape of `mask` (a mask of the layer's size). The layer stays in the middle."""
r = max(1, int(round(reach)))
canvas = Image.new("RGBA", (layer.width + 2 * r, layer.height + 2 * r), (0, 0, 0, 0))
halo = Image.new("L", canvas.size, 0)
halo.paste(mask, (r, r))
halo = halo.filter(ImageFilter.MaxFilter(3)).filter(ImageFilter.GaussianBlur(max(2.0, r * 0.45)))
halo = halo.point(lambda v: min(255, int(v * 1.8)))
canvas = Image.alpha_composite(canvas, _solid(color, halo))
canvas.alpha_composite(layer, (r, r))
return canvas
def paste_centered(image, layer, cx, cy):
"""Alpha-composite an RGBA layer onto an RGB(A) image, centered at (cx, cy)."""
overlay = Image.new("RGBA", image.size, (0, 0, 0, 0))
overlay.paste(layer, (int(round(cx - layer.width / 2.0)), int(round(cy - layer.height / 2.0))))
return Image.alpha_composite(image.convert("RGBA"), overlay)
|