File size: 30,533 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
# The core

`comic_lettering/` is a plain Python package. It needs `numpy`, `scipy` and `Pillow`, runs on Python 3.9 and newer, and imports nothing from any host.

- [Three functions](#three-functions)
- [Arguments](#arguments)
- [Style](#style)
- [The scene](#the-scene)
- [Pins: placing by hand](#pins-placing-by-hand)
- [Regions: areas drawn by hand](#regions-areas-drawn-by-hand)
- [How bubbles are found](#how-bubbles-are-found)
- [How text is fitted into a bubble](#how-text-is-fitted-into-a-bubble)
- [How free text finds its place](#how-free-text-finds-its-place)
- [Characters](#characters)
- [Fonts](#fonts)
- [Command line](#command-line)

## Three functions

```python

from PIL import Image

from comic_lettering import Style, arrange, draw, letter



image = Image.open("page.png")



# One call:

result, info = letter(image, "Hi!\nYo.", caption="Last day of summer.", sfx="SPLASH")



# The same in two steps:

scene = arrange(image, "Hi!\nYo.", caption="Last day of summer.", sfx="SPLASH")

result = draw(image, scene)

```

| Function | Returns | Does |
|---|---|---|
| `letter(image, ...)` | `(image, info)` | `arrange()` then `draw()` |
| `arrange(image, ...)` | `scene` (dict) | Decides what goes where. Draws nothing. |
| `draw(image, scene)` | `image` | Draws a scene onto the image it was made for. |

`image` is a `PIL.Image`. The result is a new RGB image; the input is not changed. When nothing was asked for, `scene["empty"]` is true and `draw()` hands the input back untouched.

Everything exported: `letter`, `arrange`, `draw`, `Style`, `Paint`, `font_names`, `list_fonts`, `font_sample`, and the lists `PLACEMENTS`, `PALETTES`, `MOODS`, `EXTRAS`, `BUBBLE_SHAPES`, `BUBBLE_THEMES`, `TAILS`.

## Arguments

`arrange(image, text="", caption="", spill=True, placement="auto", style=None, erase=True, white_threshold=120, rtl=False, numbers=False, sfx="", pins=None, regions=None)`

`letter()` takes the same, `pins` and `regions` included.

| Argument | Meaning |
|---|---|
| `text` | One line per bubble found in the art, in reading order. An empty line leaves its bubble alone. A line may carry two marks for its own bubble: `\|` for a line break inside it and `[6]` at its start for its largest font size. See [Marks in a bubble line](#marks-in-a-bubble-line). |
| `caption` | Free text, drawn on the art or in a bubble drawn for it (`style.caption_bubble`). |
| `sfx` | Sound effects, one per line. `"WORD x5"` stacks the word five times. |
| `spill` | `True`: a line that does not fit its bubble at a readable size is added to the caption. `False`: always write into the bubbles, however small, and drop lines left over. |
| `placement` | Where the caption goes: one of `PLACEMENTS` (`auto`, `top`, `bottom`, `center`, four corners). |
| `style` | A `Style`; the default one when `None`. |
| `erase` | Erase the letters the model drew inside a bubble before writing. |
| `white_threshold` | The darkest light fill that still counts as a bubble, 0..255. |
| `rtl` | Reading order right to left (manga). Not exposed in the editor. |
| `numbers` | Draw each bubble's number instead of any text. |
| `pins` | What was placed by hand. See [Pins](#pins-placing-by-hand). |
| `regions` | Areas drawn by hand. See [Regions](#regions-areas-drawn-by-hand). |

In any text, `*word*` makes a word bigger (by `EMPHASIS_SCALE`, 1.3), and the characters in `render.SYMBOLS` are drawn as shapes.

## Style

`Style` holds every option of the look. Sizes are relative to the image, so a style gives the same picture at any resolution.

| Option | Default | Meaning |
|---|---|---|
| `font`, `caption_font`, `sfx_font` | `Comic Relief Bold`, `""`, `Bangers` | Font names from `font_names()`. An empty `caption_font` means the bubble font. |
| `bubble_colors`, `caption_colors`, `sfx_colors` | `auto` | A `PALETTES` name. |
| `bubble_mood`, `caption_mood`, `sfx_mood` | `calm`, `calm`, `shout` | A `MOODS` name. |
| `caption_extras`, `sfx_extras` | `none` | An `EXTRAS` name: marks scattered around. |
| `caption_bubble` | `none` | A `BUBBLE_SHAPES` name: draw a bubble for the caption. |
| `caption_bubble_theme`, `caption_tail` | `light`, `none` | `BUBBLE_THEMES`, `TAILS`. `BUBBLE_SHAPES` are `none`, `oval`, `box`, `cloud`, `burst`, `thought`, `wavy`, `jagged`, `dashed`, `drip` (its tail falls as drops, `DRIP_TAIL`), `torn`, `message` (a very round box, a hook at the lower corner on the side the tail points to) `soft` (blurred, half clear, no outline, no tail) and `label` (a box with square corners whose tail is an arrow, a shaft and a head in one piece). `BUBBLE_THEMES` are `light`, `dark`, and the flat ones `black`, `gray` (229, 229, 234) and `blue` (45, 156, 255): no outline to be seen, light letters on black and blue (`THEME_BODIES`). The tail `custom` points where `caption_tail_angle` says. |
| `extras_color` | `auto` | `auto` or `#RRGGBB`: the color of the marks around a caption or an effect (`caption_extras`, `sfx_extras`), with a dark or light outline to suit it. `auto` is the text's own paint. |
| `drip` | `0.0` | Drips run down from the underside of the letters of every kind of text: 0 none, 1 many and long. They are added to the letters' masks, so the fill and its outlines grow round them; nothing is added above the letters. `seed` changes them. |
| `caption_bubble_glow` | `0.0` | A glow of the outline's color (the palette's fill, or the text color) round the caption's bubble, 0..1; the bubble itself stays where it is. |
| `caption_tail_angle` | `45.0` | With `caption_tail` `custom`: degrees, 0 points right, 90 down (the screen's clockwise). |
| `caption_bubble_color`, `caption_bubble_color2` | `auto` | The fill of the caption's bubble, and the color a gradient from it fades to. `auto` is the theme's own fill; the text takes dark or light ink to suit a fill of your own. |
| `gradient_angle` | `0.0` | Degrees, for every gradient (a palette's, `text_color2`, `sfx_color2`, the bubble fill): 0 runs top to bottom, 90 left to right. 0 is drawn exactly as before. |
| `uppercase` | `True` | Capital letters. |
| `bubble_size` | `9.0` | Bubble text: the largest font size tried, % of image height. |
| `bubble_min_size` | `1.5` | The smallest size still readable, % of image height. |
| `margin` | `0.08` | Gap between the text and the bubble edge, fraction of the bubble. |
| `free_size` | `5.5` | Caption font size, % of image height. |
| `stroke_width`, `shadow` | `0.12`, `0.5` | Caption outline (fraction of the font size) and shadow strength. |
| `sfx_size`, `sfx_tilt`, `sfx_opacity` | `7.0`, `15.0`, `0.95` | Effect size (% of height), largest random tilt in degrees, opacity. |
| `sfx_glow`, `sfx_glow_color` | `0.0`, `auto` | A glow round the letters of every effect, 0..1 (reach and strength); `auto` is the letters' own color. It takes the place of a palette's own glow. |
| `text_color`, `stroke_color`, `sfx_color` | `auto` | `auto` or `#RRGGBB`. Used by the `custom` palette. |
| `text_color2`, `sfx_color2` | `auto` | `auto` or `#RRGGBB`: the bottom of a top-to-bottom gradient from `text_color` (bubbles and caption) or `sfx_color`. Used by the `custom` palette only; `auto`, or anything that is not a color, leaves one flat color. |
| `bubble_glow`, `bubble_glow_color` | `0.0`, `auto` | A glow round the areas painted as a bubble (`fill` other than `none` and `soft`), 0..1, reaching out in proportion to the area's text size; `auto` is white, or the body of a `gray` or `blue` one. |
| `bubble_stroke_width`, `bubble_stroke_color` | `0.0`, `auto` | Outline of text on a bubble fill: bubbles found in the art, filled areas, a caption put in a bubble. Not text on the art. Width is a fraction of the font size, `0` for none; the fitting keeps room for it, so it stays inside the bubble. Color is `auto` or `#RRGGBB`, with any palette: `auto` is black on a light fill, white on a dark one. |
| `jitter`, `size_jitter`, `rough`, `line_tilt`, `line_shift`, `line_spacing` | `0.3`, `0`, `0`, `0`, `0`, `1.08` | The `custom` mood. |
| `arc`, `rotation` | `0`, `0` | Bend (-1..1) and tilt (degrees) of a whole block. |
| `soften`, `grain`, `opacity` | `0.4`, `0`, `1.0` | Blur in pixels, uneven ink, opacity. |
| `seed`, `sfx_seed` | `0`, `0` | Seeds of the letter wobble and of the effect placement. |

**Palettes** (`render.PALETTES`) are dicts of colors: `fill`, optional `fill2` (a top-to-bottom gradient), `stroke`, optional `outer` (a second outline) and `glow`, and `ink` (the color of plain text inside a light bubble). `auto` is `None`; `from the art` is computed from the image by `accent_palette()`; `custom` reads the color options: `text_color`, `stroke_color`, `sfx_color` and, for a gradient, `text_color2` and `sfx_color2`.

**Moods** (`render.MOODS`) are dicts of the six mood options; `scream` is the one for a hand-lettered shout (uneven letter sizes, tilted and staggered lines, rough edges). `custom` is `None` and reads them from the style.

## The scene

A dict of plain values: it survives `json.dumps` and back.

```python

{

  "version": 1,

  "size": [896, 1152],            # the image the scene was made for

  "style": {...},                 # vars(style)

  "white_threshold": 120, "rtl": False, "erase": True,

  "people": True,                 # the character mask was part of the placement

  "empty": False,                 # True: nothing to draw

  "bubbles": [[x0, y0, x1, y1], ...],   # every bubble found, in reading order

  "regions": [...],               # the regions, cleaned

  "items": [...],                 # what is drawn, in order

  "info": {"bubbles_found": 2, "bubbles_filled": 2, "free_text": True,

           "font_sizes": [64, 50], "characters": True, "sfx": 1, "regions": 3,

           "warnings": []},

}

```

`info["warnings"]` is always there: a list of sentences, each saying what was asked for and could not be done. Empty when all went as asked. Two things put a sentence there: line breaks typed by hand that did not fit, and a font that has no glyph for a letter of the text it was chosen for. In that case the default font (`Comic Relief Bold`, Latin and Cyrillic) is used for that kind of text (bubbles, caption, sound effects), and the scene's `style` carries it, so `draw()` draws what `arrange()` planned; if the default font lacks the letter too, the text is left alone and the sentence says it is drawn as empty boxes. `arrange()` does not change the `Style` it was given. The hosts show them as they are: the editor in its status line, everything else on the error stream (`web.log_warnings`).

`info["characters"]` is present when something was placed automatically: `True` when a character mask was used, `False` when none was available.

### Items

Every item has `kind`, `text`, `size` (font size in pixels) and `lines` (the text broken into lines and measured; `draw()` takes it as it is). Items that can be moved by hand also have an `id`.

| `kind` | What | `id` | Place |
|---|---|---|---|
| `bubble` | Text inside the n-th bubble found in the art | none | `bubble` (index into `scene["bubbles"]`), `cx`, `cy` |
| `caption` | Text straight on the art | `caption` | `cx`, `cy`, `box`, `rotation`, `reach`, `placement` |
| `balloon` | Text inside a bubble drawn for the caption | `caption` | `x`, `y`, `box`, `tall` |
| `sfx` | A sound effect | `sfx:<index>` | `x`, `y`, `nominal` (its size before tilting), `room` (the box it reserves), `rotation`, `index` |
| `region` | Text fitted into a hand-drawn area | `region:<id>` | `region` (index into `scene["regions"]`), `cx`, `cy`, `fill` |
| `path` | Text along a brush stroke | `region:<id>` | `region`, `path` (the smoothed centre line), `voice`, `fill` |
| `mark` | One mark standing in a hand-drawn area | `region:<id>` | `region`, `cx`, `cy`, `size` (its side), `mark` (the shape name), `color`, `rotation` |

A censor, tone, lines or frame region adds no item: `draw()` lays them on the art from `scene["regions"]` before anything is lettered, and `info["censored"]` and `info["decorated"]` count them.

An image with transparency (`has_alpha()`) is lettered on its colors and comes back with its own alpha; `upright()` turns a photo the way its EXIF orientation says (the editor and the command line do it on opening). A `placement` that is none of `PLACEMENTS` is read as `auto`.

A sound effect that belongs to a region carries `"region": "<region id>"`, and its `index` starts at `1000` (`REGION_SFX`): adding or removing an ordinary effect does not change how the effects of regions are drawn.

Real examples:

```json

{"kind": "bubble", "bubble": 0, "text": "Hi", "size": 64, "cx": 240.9, "cy": 257.7, "lines": [...]}

{"kind": "caption", "id": "caption", "text": "Later", "placement": "top-left", "size": 63,

 "cx": 148.0, "cy": 85.0, "box": [-17, 14, 313, 155], "rotation": 0.0, "reach": 0.46, "lines": [...]}

{"kind": "sfx", "id": "sfx:0", "text": "THUD", "index": 0, "size": 60, "x": 216, "y": 658,

 "nominal": [168, 84], "room": [148, 571, 451, 829], "rotation": 7.7}

```

## Pins: placing by hand

`pins` is a dict from item id to what was set by hand. Whatever a pin leaves out is still decided by `arrange()`.

```python

pins = {

    "caption": {"cx": 300, "cy": 500},                 # only the place

    "sfx:0":   {"size": 120, "rotation": -20},         # only size and tilt

    "sfx:1":   {"cx": 640, "cy": 900, "size": 90, "rotation": 8},

}

scene = arrange(image, caption="Later...", sfx="THUD\nBAM", pins=pins)

```

| Key | Meaning |
|---|---|
| `cx`, `cy` | The middle of the item, in image pixels. Both or neither. |
| `size` | Font size in pixels, clamped to 8..2000. |
| `rotation` | Tilt in degrees, counter-clockwise. |
| `reach` | Caption only: how wide the block may be, as the scene reported it. Keeps the line breaks the caption had when it was pinned. |
| `tall` | Drawn bubble only: keep the tall, narrow variant. |

The id `caption` addresses the caption, or the bubble drawn for it. Things placed after a pinned item keep off it where it now stands.

The round trip the editor makes: read an item from the scene, send back a pin with the values the user changed plus `reach` or `tall` from the item.

## Regions: areas drawn by hand

`regions` is a list of at most 40 areas.

```python

regions = [{

    "id": "a",

    "kind": "text",                       # "text" | "sfx" | "keepout" | "censor" | "mark" | "tone" | "lines" | "frame"

    "text": "Not one more step.",

    "fill": "light",                      # "none" | "light" | "dark" | "black" | "gray" | "blue" | "soft"; kind "text" only

    "shapes": [{"type": "polygon", "points": [[600, 880], [860, 880], [860, 1080], [600, 1080]]}],

    "rotation": 0, "scale": 1.0,          # optional

    "follow": False, "flip": False,       # optional

}]

```

| Key | Meaning |
|---|---|
| `kind` | `text`: the text is fitted into the area as into a bubble. `sfx`: the text is one sound effect, sized to the area and put in its middle. `keepout`: nothing placed automatically may land there. `censor`: the art under the area is covered, see `look`. `mark`: one mark (a character of the picker, `render.SYMBOLS`) stands in the area: its `text` holds it, the first one found is used, and a text with none draws nothing. |
| `tone`, `lines`, `frame` | Painted on the art with the censors, in the order drawn (module `painting.py`). `tone`: a screen tone, `look` `dots`, `hatch`, `cross` or `fade` (dots that grow along the pattern's direction); `scale` is its pitch, `rotation` its angle in degrees. `lines`: `focus` (rays in towards the middle, which stays clear; `scale` is how many), `speed` (streaks along `rotation`) `tremor` (wavy broken lines on both sides of every brush stroke of the region, or of a polygon's outline: `painting.tremor`; they are not clipped to the area) `dashes` (the same in short straight dashes) or `halo` (sharp spikes standing out from both sides of a stroke, or from the outside of a polygon: `painting.halo`; `scale` makes them longer; not clipped either). `frame`: a border along the outline, `border`, `double`, `dark` (the inside darkened, a light border) or `xray` (the picture inside turned into a negative, its contrast stretched, colored from dark blue through the region's `color`, default `painting.XRAY_TINT`, to near white, with a light border and a faint glow: `painting.xray`); `scale` is the border's width. All three take a `color` (default black) and none takes text. `info["decorated"]` counts them. |
| `look` | `censor` only: `bar` (black, the default), `white`, `mosaic` (squares of one color), `blur` or `ghost` (the area's picture repeated `GHOST_COPIES` times behind it, shifted along `rotation`, each copy softer and weaker; the area itself stays sharp). `scale` is the strength of a mosaic, a blur or a ghost: the size of its squares, the reach of its blur, the step between the copies. A censor is drawn on the art before any lettering, so text and marks stay on top of it; nothing placed automatically lands on it. A scene with a censor and nothing else is not empty. |
| `color` | `mark`, `tone`, `lines`, `frame`: `#RRGGBB`. A mark without it is white with a dark outline; with it, the outline is dark on a light color and light on a dark one. |
| `fill` | `none`: the text gets the caption's outline. `light` / `dark` / `black` / `gray` / `blue` / `soft`: the area is painted as a bubble first (`black`, `gray`, `blue`: no outline to be seen; `soft`: a blurred half-clear patch). |
| `shapes` | What the area is made of, in the order it was drawn. Up to 200 shapes, 4000 points each. |
| `rotation` | Tilt of the text or effect, degrees, counter-clockwise, -180..180. Without it an effect is tilted at random. |
| `scale` | How large the text is against what the area would give it, 0.2..4. Above 1 it may reach out of the area. A mark is as large as the area's box times this. |
| `follow` | The text runs along the region's longest brush stroke and bends with it, in the direction the stroke was drawn. Letters are about 0.6 of the brush width tall. |
| `flip` | With `follow`: along the stroke the other way round. |

**Shapes**

| `type` | Fields | Meaning |
|---|---|---|
| `polygon` | `points` (3 or more) | An outline that is closed and filled. |
| `stroke` | `points`, `width` | A brush stroke with round ends and joints. |
| `erase` | `points`, `width` | Rubs out what the shapes before it painted. |

A region is all of its shapes together, rasterised with Pillow in drawing order and rounded off with a small Gaussian blur, since a hand is not steady. A region needs at least one shape that paints. Everything placed automatically keeps off every region.

Text in a tilted area is fitted in the area's own frame: the mask is rotated (`scipy.ndimage.affine_transform`), the text is fitted upright, and the block is rotated back when drawn.

## How bubbles are found

`detect.detect_bubbles(rgb, white_threshold=120, min_area=0.0015, max_area=0.6, min_outline=0.8, rtl=False)` returns `Bubble` objects in reading order.

A bubble is a **flat fill enclosed by a contrasting outline, with a smooth, nearly convex shape**:

1. **Flat fill.** Pixels that are bright enough (`white_threshold`), nearly unsaturated or only lightly tinted (`MAX_TINT`, 48) and locally flat. A second pass looks for near-black fills (dark bubbles).
2. **Connected components** of such pixels, between `min_area` and `max_area` of the image.
3. **Shape tests** (`is_bubble`), on measurements taken by `scan()`: how flat the fill is, solidity against the convex hull, how much of its bounding box it fills, the share of its border that touches an outline of the opposite brightness (`min_outline`). The thresholds were measured on real generations and are explained in the code.
4. **Stricter tests** for the risky cases: a tinted fill (cream, beige) has to be brighter, flatter, more solid and better outlined, so a face is not taken for a bubble; a bubble below `SMALL` (0.3% of the image) has to pass a stricter test too, with a fill as even as `SMALL_FLATNESS` (1.2: a word or two in a tiny bubble). A fill darker than `DIM_FILL` (185) needs a line `DIM_OUTLINE` (0.95) of the way round: faces in a gray scene and a wall had 0.82 to 0.93, the real dim bubbles 0.99 and 1.0.
   **Dark bubbles** (`_is_dark_bubble`): near-black fills (no channel above `DARK_BLACK`, 12) larger than `DARK_SHARE` (0.8%). A dark bubble on a light ground has no line of its own to see, so the contrast of its line is about 0: then the shape has to say it (flat, convex 0.9, filling 0.6 to 0.94 of its box) and the ground has to be light nearly all round (0.93). A bright line with gaps passes when it is strong (contrast 70), a scalloped one when it is closed all round (0.98) and strong (100). An open mouth, a hood, a piano, a chalkboard and a monitor stay out: they are less convex, uneven or open. Measured on 16 scenes asked for dark bubbles and 16 of dark and small look-alikes: 19 of 25 dark bubbles are found (9 before), with no wrong find.
5. **Ragged bubbles** (a shout with spikes, a cloud with scallops) are not convex, so they have a second way in, `_is_ragged` (never longer than `RAGGED_ASPECT`, 3 times its width: a strip of white ground beside a dark dress was 4.5): solidity down to `RAGGED_SOLIDITY` (0.52) and extent down to `RAGGED_EXTENT` (0.38), a fill no flatter than `RAGGED_FLATNESS` (2.1: shouted letters fill such a bubble), but then bright (`RAGGED_BRIGHT`, 190), outlined all the way round (`RAGGED_OUTLINE`, 0.96), and larger than `RAGGED_SHARE` (0.9% of the image). A cream fill that fails the paper test above still passes when it is that bright and closed. A smooth bubble may be as uneven as `SMOOTH_FLATNESS` (1.4). A fill darker than `DIM_FILL` (160) needs a line `DIM_OUTLINE` (0.95) of the way round: a face and a wall in night scenes were taken for bubbles before. Measured on two corpora of generated scenes: 49 without a bubble (white dresses with lace, foam, clouds, fur, stickers, starbursts, teeth, windows), then 16 with jagged, cloud and wavy bubbles and 16 without. None of the scenes without a bubble has a find; in the bubble scenes 8 of 9 real bubbles that were missed are found, with no wrong find. `tests/test_detect_ragged.py` keeps the shapes in view, `tests/test_detect_measured.py` the measurements.
6. **Letters that touch the outline.** A letter the model drew into the outline is not a hole in the fill, so it was neither erased nor counted as room for text: a shout with huge letters had almost none left. Every bubble that passes, light or dark, is given its bays back (`_take_in_letters`): the fill is closed with a disk of `LETTER_STROKE` (0.12 of the square root of its area), and a bay that this adds is taken in when no more than `BAY_OPEN` (0.12) of its edge faces away from the bubble. The gaps between the spikes of a jagged outline open to the outside and stay out. The measurements that decide whether a region is a bubble are taken before this. `tests/test_detect_letters_on_edge.py`. Rectangles stay out on purpose: a window pane and a picture frame are the look-alikes there.

Reading order is rows top to bottom; bubbles that overlap vertically share a row and go left to right within it (right to left with `rtl`).

`erase_letters(rgb, bubble)` paints over everything the fill encloses (the model's letters) with the bubble's own color, in place. The result of a detection is cached for the last six images, keyed by an MD5 of the pixels.

## How text is fitted into a bubble

For one line of text and one bubble (`_fit_bubble`, `_fit_text`):

1. Start at `bubble_size` and go down. At each size, lay the text out against the bubble's real shape: every row of the mask gives the width available at that height, minus `margin`.
2. Prefer a **diamond**: short lines at the top and bottom, long in the middle (`layout_shaped`, `diamond_profile`). A better shape is worth up to 20% of font size (`SHAPE_REACH` 0.8, `SHAPE_WEIGHT` 0.6).
3. If nothing fits above `bubble_min_size` in `MAX_LINES` (8) lines: drop the emphasis, then hyphenate the longest words (`_split_word`: near the middle, after a vowel that a consonant follows where there is one, three letters or more on each side).
4. Still nothing: with `spill`, the line goes to the caption and the bubble stays free for the next line (`_assign`).

### Marks in a bubble line

A line of `text` is read by `_Line` before it is fitted (`_fit_line`). The two marks live only there, in the core, so every host has them: the editor, automatic mode, the ComfyUI node and the command line pass the text through untouched. The scene item keeps the line as it was typed in `text`, marks included.

| Mark | Constant | Meaning |
|---|---|---|
| `\|` | `LINE_BREAK` | A line break inside the bubble. Empty pieces are dropped, so `a\|\|b` is two lines. |
| `[6]`, `[6.5%]` at the start | `SIZE_MARK` | The largest font size tried in this bubble, in the unit of `Style.bubble_size` (% of image height), in place of it. Capped at `LARGEST_SIZE` (30). |

Neither character means anything else in a text: `*` is emphasis, `-` a place to break a word, `<3` a heart, and none of the marks in `render.SYMBOLS` is `|`, `[` or `]`. The size is in square brackets and not in braces, so a host that expands `{a|b}` in its text fields cannot take a size followed by a break for one of those.

**Breaks typed by hand** (`_fit_broken`). The text becomes one paragraph per piece and is laid out with one line per paragraph, never wrapped further. The sizes go down pixel by pixel from the largest to the smallest allowed and the first that fits wins: with the breaks given there is no shape to weigh. Emphasis is dropped before the breaks are. If nothing fits, the breaks are given up: the pieces are joined with spaces and fitted as any other line (steps 1 to 4 above), and `BREAKS_DROPPED` with the bubble's number goes into `info["warnings"]`. A line that then goes to the caption keeps its breaks there.

**A size of its own.** The line is fitted with a copy of the style whose `bubble_size` is the given one, and with `strict` off: whoever typed the size meant this bubble, so the line is written there however small, as with `spill=False`, and `bubble_min_size` does not send it to the caption. The smallest size is then the floor of all text (`FLOOR_SIZE`, 1.2% of image height, at least `FLOOR_PX`).

## How free text finds its place

Three masks drive every automatic placement:

| Mask | What is in it | Weight |
|---|---|---|
| `static` | Bubbles, characters, regions | Must be avoided where possible |
| `precious` | Heads (the top quarter of each character), bubbles, regions | Avoided first when something has to be covered |
| `energy` | Edge energy of the art (`_energy`) | Lower is calmer: effects and drawn bubbles go to calm areas |

- **Caption, `auto`** (`_place_free`): a band at the top or bottom, then a narrower block in a corner, then the same a little smaller. The first that is clear wins; otherwise the one that covers the least, a head counting most.
- **Drawn bubble** (`_place_balloon`): a calm, free spot by integral images over `energy` and `static`; tried tall and narrow, then shrunk in steps down to 0.6 of its size, when nothing is free.
- **Sound effects** (`_place_sfx`, `_calm_spot`): one after another, each reserving its `room` so the next keeps off it. An effect that would land on a character is drawn smaller first, down to 65%. The place does not depend on the effect's look, so changing a font does not move it.
- **Marks around** (`decorate`): left out where they would land on a character or be cut by the image edge.

Pinned items are placed first where the pin says, and reserve their room like any other.

## Characters

`people.person_mask(rgb)` returns a boolean mask of the characters, or `None`.

It uses `ultralytics` and a model file matching `person_yolov8*-seg.pt`, **only if both are already on the machine**. Nothing is downloaded. The model is looked for, relative to the host's working directory, in:

```

models/adetailer            models/ultralytics/segm     models/ultralytics

models/Ultralytics/segm     models/yolo

../../Models/Ultralytics/segm   ../../Models/AfterDetailer   ../../Models/adetailer   (StabilityMatrix)

../ComfyUI/models/ultralytics/segm                                                   (a sibling ComfyUI)

```

The environment variable `SDCL_PERSON_MODEL` points at any other file. The smallest matching file is used: this only needs a rough silhouette. Any failure (no library, a broken file, a failed prediction) means `None`, never an error.

## Fonts

`fonts.list_fonts()` returns `{display name: path}`; `font_names()` the names in list order:

1. the user's own files in `fonts/` (`.ttf`, `.otf`, `.ttc`), git-ignored;
2. the twenty-nine bundled fonts in `fonts/bundled/`;
3. a few comic-looking system fonts, when installed.

The display name is read from the font's name table. `font_sample(style, text, size)` renders a preview strip.

## Command line

From the repository folder:

```

python -m comic_lettering in.png out.png --text "Hi!\nYo." --caption "Later..." --sfx "THUD\nBAM"

```

`\n` separates bubbles, caption lines and effects; within a bubble's line, `|` is a line break and `[6]` at its start its size (`--text "Hi!\n[4]Go on,|ask nicely."`, in quotes, or the shell takes `|` for a pipe). Common options have flags (`--font`, `--placement`, `--no-erase`, `--no-spill`, `--numbers`, `--white-threshold`, the sizes); any other `Style` option goes through `--opt`:

```

python -m comic_lettering in.png out.png --caption "So cool" --opt caption_colors=pink --opt caption_bubble=cloud --opt caption_tail=down-left

```

`--opt` checks the value: a number must be one, a name must be on the option's list (`caption_bubble=ovl` stops the command), a font must exist, and a switch (`uppercase`) takes `true`, `yes`, `on` or `1` for on and anything else for off. `--layout FILE` reads what was placed and drawn by hand from a JSON file, `{"pins": {...}, "regions": [...]}`, as [pins and regions](#pins-placing-by-hand) are given to `arrange()`:

```

python -m comic_lettering in.png out.png --text "Hi" --layout layout.json

```

The command prints the scene's `info`, and its warnings once more on the error stream.