API reference

Everything here is importable from khatt itself (import khatt), except the moviepy clips in khatt.video and the Pillow calls in khatt.pillow.

Drawing on images

khatt.draw_text(image, xy, text, *, font='amiri', size_px=48, fill='black', align=None, anchor='la', max_width=None, line_spacing=None, spacing=None, keep_tashkeel=True, digits=None, stroke_width=0, stroke_fill=None, fallback_fonts=(), effect=None, spans=())

Draw shaped text onto image (in place) and return it.

A drop-in for ImageDraw.text that shapes Arabic correctly whether or not Pillow has Raqm. Pass the text as typed (logical order): never reshape or reorder it first.

Parameters:
  • image (Image) – An RGB or RGBA Pillow image.

  • xy (tuple[float, float]) – Where the anchor point of the text goes, in pixels.

  • text (str) – The text; line breaks start new lines and mixed Arabic/Latin text comes out in the correct visual order.

  • font (str | PathLike[str]) – A bundled font name (see khatt.list_fonts()) or the path to a .ttf/.otf font file.

  • size_px (int) – Font size in pixels per em, as in ImageFont.truetype, rounded to a whole number.

  • fill (str | tuple[int, int, int] | tuple[int, int, int, int]) – Text colour: a name, #rrggbb[aa], or an RGB(A) tuple. Its alpha makes the text translucent.

  • align (str | None) – "left", "right" or "center" alignment of lines within the block; None aligns right-to-left paragraphs right and left-to-right ones left. "justify" (with max_width) fills every wrapped line but a paragraph’s last to max_width: Arabic words get a kashida, as in printed Naskh, then the spaces widen. The last line aligns by its direction.

  • anchor (str) – Two letters, as in Pillow. Horizontal: l / m / r for the left, middle or right of the ink. Vertical: a (first line’s ascender), t (top of the ink), m (middle, ascender to descender), s (first line’s baseline), b (bottom of the ink) or d (last line’s descender).

  • max_width (int | None) – Wrap lines at spaces to this many pixels. A word wider than that on its own still gets a line of its own.

  • line_spacing (float | None) – Distance between baselines, in multiples of size_px; default 1.2.

  • spacing (float | None) – Pixels between lines instead of line_spacing, as in Pillow’s multiline_text: each line’s ascender line sits spacing pixels below the previous line’s baseline (plus twice stroke_width, so outlines don’t eat into it). Negative values pull lines closer.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • digits (str | None) – "arabic-indic" writes the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits()); default: as typed.

  • stroke_width (float) – Width in pixels of an outline drawn around the text, as in Pillow: the text grown outward by this much, with round corners, painted under it. It doesn’t move the text: anchors and alignment work as without it (but with spacing, lines also move apart by twice the width, as in Pillow).

  • stroke_fill (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Outline colour, in the same formats as fill; default: fill (which makes the text bolder).

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts tried in order (bundled names or file paths) for characters font has no glyph for, such as a CJK font for Chinese inside Arabic text. Line spacing and anchors still follow font.

  • effect (str | Effect | None) – A preset name (see khatt.list_effects()) or a khatt.Effect. It decides the colours, so fill and stroke_fill are not used, and it brings its own outline, so it can’t be combined with stroke_width.

  • spans (Sequence[Span | tuple[int, int, str | tuple[int, int, int] | tuple[int, int, int, int]]]) – Parts of the text in their own colour, each a khatt.Span or a (start, end, fill) tuple, such as (0, 5, "gold") for the first five characters. Positions are in text as passed; where spans overlap, the later one wins. The text is laid out exactly as without them, and letters keep their joins across a colour change. Not with effect.

Returns:

image, drawn on. Characters the font does not cover are skipped with a khatt.UnsupportedCharacterWarning (see khatt.missing_characters()).

Return type:

Image

khatt.text_bbox(text, *, xy=(0, 0), font='amiri', size_px=48, align=None, anchor='la', max_width=None, line_spacing=None, spacing=None, keep_tashkeel=True, digits=None, stroke_width=0, fallback_fonts=())

The box draw_text() would draw text in, without drawing it.

Like Pillow’s ImageDraw.textbbox, and with draw_text()’s arguments, which mean the same here. The box is exact: it holds every pixel that draw_text() would paint at xy, the outline included, and no row or column of it is blank.

Returns:

(left, top, right, bottom) in pixels, right and bottom exclusive (so right - left is the width). Text with nothing to draw (empty, or only spaces) gives an empty box at xy.

Parameters:
Return type:

tuple[int, int, int, int]

khatt.overlay(image, text, box, *, fit='shrink', font='amiri', max_size_px=None, min_size_px=8, fill='black', align=None, valign='middle', padding=0, line_spacing=None, spacing=None, keep_tashkeel=True, digits=None, stroke_width=0, stroke_fill=None, fallback_fonts=(), effect=None)

Place shaped text inside box on image (in place) and return it.

Parameters:
  • image (Image) – An RGB or RGBA Pillow image.

  • text (str) – The text, as typed (see draw_text()).

  • box (tuple[int, int, int, int]) – (left, top, right, bottom) in pixels.

  • fit (str) – "shrink" (default) uses the largest size from max_size_px down to min_size_px at which the text, wrapped at spaces, fits the box. "wrap" wraps at max_size_px; "none" draws at max_size_px without wrapping.

  • font (str | PathLike[str]) – A bundled font name (see khatt.list_fonts()) or the path to a .ttf/.otf font file.

  • max_size_px (int | None) – The font size for "wrap" and "none" and the largest size "shrink" tries, in pixels per em; default: the height inside the box.

  • min_size_px (int) – The smallest size "shrink" tries.

  • fill (str | tuple[int, int, int] | tuple[int, int, int, int]) – Text colour, as in draw_text().

  • align (str | None) – "left", "right" or "center" within the box; None aligns right-to-left paragraphs right and left-to-right ones left. "justify" fills the wrapped lines to the box’s width, as in draw_text().

  • valign (str) – "top", "middle" or "bottom": where the ink sits in the box.

  • padding (int) – Pixels kept clear inside each edge of the box.

  • line_spacing (float | None) – Distance between baselines, in multiples of the size; default 1.2.

  • spacing (float | None) – Pixels between lines instead of line_spacing, as in draw_text().

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • digits (str | None) – "arabic-indic" writes the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits()); default: as typed.

  • stroke_width (float) – Width in pixels of an outline around the text, as in draw_text(). The outline counts as part of the text: it is fitted inside the padding too.

  • stroke_fill (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Outline colour; default: fill.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts tried in order (bundled names or file paths) for characters font has no glyph for, such as a CJK font for Chinese inside Arabic text. Line spacing and anchors still follow font.

  • effect (str | Effect | None) – A preset name (see khatt.list_effects()) or a khatt.Effect. It decides the colours, so fill and stroke_fill are not used, and it brings its own outline, so it can’t be combined with stroke_width. The text is fitted to the box, and the effect’s outline, glow and shadow may reach past it.

Returns:

image, drawn on. Nothing but an effect is ever drawn outside box: text that does not fit inside the padding (with "shrink", not even at min_size_px) raises a TextOverflowWarning and is clipped to the box.

Return type:

Image

khatt.word_boxes(text, *, xy=(0, 0), font='amiri', size_px=48, align=None, anchor='la', max_width=None, line_spacing=None, spacing=None, keep_tashkeel=True, digits=None, fallback_fonts=(), ranges=None)

Each word’s box and mask, as khatt.draw_text() would draw text at xy.

Takes draw_text’s layout arguments, which mean the same here, so the boxes match what it draws: wrapped lines, alignment and anchors included. The text is shaped as a whole, so letters keep their joins and marks stay with their letter.

Parameters:
Returns:

One WordBox per word (or range) that has ink, in the order of the text: reading order, whatever the direction. Words with nothing to draw, such as a lone space range, are left out.

Return type:

list[WordBox]

class khatt.WordBox(text, start, end, box, mask)

One word as khatt.draw_text() draws it.

Parameters:
text: str

The word, as in the text given.

end: int

text[start:end].

Type:

Where it is in the text given

box: tuple[int, int, int, int]

(left, top, right, bottom) in pixels of the image, right and bottom exclusive: exactly the pixels the word’s ink covers.

mask: Image

The word’s coverage (mode "L", 255 is ink), the size of box. Paste a colour through it at box[:2] to paint just that word.

class khatt.Span(start, end, fill)

Part of the text drawn in its own colour.

start and end are positions in the text as passed (end is not included), so text[start:end] is the part, for example a word to highlight. The text is shaped as one, so letters keep their joins where the colour changes.

Parameters:
khatt.caption_image(text, *, font='amiri', font_size=None, size=(None, None), margin=(None, None), color='black', bg_color=None, stroke_color=None, stroke_width=0, method='label', text_align=None, horizontal_align='center', vertical_align='center', interline=4, transparent=True, keep_tashkeel=True, digits=None, fallback_fonts=(), spans=())

Draw text as moviepy’s TextClip would show it, shaped by khatt.

The arguments are TextClip’s (moviepy 2.2), with the same meaning and defaults except font and text_align.

Parameters:
  • text (str) – The text, as typed. Line breaks start new lines.

  • font (str | PathLike[str] | None) – A bundled font name (see khatt.list_fonts()) or the path to a .ttf/.otf font file; None means "amiri".

  • font_size (int | None) – Font size in pixels per em. None picks the largest size that fits size (the width; for "caption" the height too, and for "label" the height if given).

  • size (tuple[int | None, int | None]) – (width, height) of the text area, without margins. None for either sizes it to the text. "caption" needs the width.

  • margin (Sequence[int | None]) – Space added around the text area: (horizontal, vertical) or (left, top, right, bottom); None is 0.

  • color (str | tuple[int, int, int] | tuple[int, int, int, int]) – Text colour: a name, #rrggbb[aa], or an RGB(A) tuple.

  • bg_color (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Background colour; default: transparent (or black when transparent is False).

  • stroke_color (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Outline colour; None draws the outline (if stroke_width is set) in color, as moviepy does.

  • stroke_width (float) – Outline width in pixels.

  • method (str) – "label" sizes the image to the text; "caption" wraps the text at spaces to the width.

  • text_align (str | None) – "left", "right" or "center" alignment of lines within the text. None (default; moviepy’s is "left") aligns right-to-left paragraphs right and left-to-right ones left. "justify" fills the wrapped lines of "caption" to the width, as in khatt.draw_text().

  • horizontal_align (str) – "left", "center" or "right": where the text sits in a wider area.

  • vertical_align (str) – "top", "center" or "bottom": where the text sits in a taller area.

  • interline (float) – Pixels between lines, as Pillow’s spacing (see khatt.draw_text()).

  • transparent (bool) – RGBA image (True) or RGB.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • digits (str | None) – "arabic-indic" writes the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits()); default: as typed.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts tried in order (bundled names or file paths) for characters font has no glyph for, such as a CJK font for Chinese inside Arabic text. Line spacing and anchors still follow font.

  • spans (Sequence[Span | tuple[int, int, str | tuple[int, int, int] | tuple[int, int, int, int]]]) – Parts of the text in their own colour, as in khatt.draw_text(), such as [(0, 5, "gold")] to highlight the first word of a caption.

Returns:

An RGBA image (RGB when transparent is False). Characters the font does not cover are skipped with a khatt.UnsupportedCharacterWarning.

Return type:

Image

khatt.put_text(image, text, org, *, font='amiri', size_px=32, color=(255, 255, 255), channels='bgr', anchor='ls', align=None, max_width=None, line_spacing=None, stroke_width=0, stroke_color=None, keep_tashkeel=True, digits=None, fallback_fonts=())

Draw shaped text onto a NumPy image (in place) and return it.

The arguments follow cv2.putText(img, text, org, ...): by default org is the left end of the text’s baseline and colours are in BGR order. Only the part of the image under the text is touched.

Parameters:
  • image (Any) – A uint8 array: (height, width) grayscale, or (height, width, 3) or (height, width, 4) colour.

  • text (str) – The text, as typed; line breaks start new lines.

  • org (tuple[float, float]) – Where the anchor point of the text goes, as (x, y).

  • font (str | PathLike[str]) – A bundled font name (see khatt.list_fonts()) or a font file path.

  • size_px (int) – Font size in pixels per em.

  • color (Any) – Text colour in the image’s channel order: one value for grayscale, three for colour, four to set alpha too.

  • channels (str) – "bgr" (OpenCV, the default) or "rgb" (Pillow, Matplotlib and most other libraries); a fourth channel is alpha.

  • anchor (str) – As in khatt.draw_text(); the default "ls" (left end of the baseline) is OpenCV’s org.

  • align (str | None) – Alignment of the lines of a multi-line text, as in khatt.draw_text().

  • max_width (int | None) – Wrap lines at spaces to this many pixels.

  • line_spacing (float | None) – Distance between baselines, in multiples of the size.

  • stroke_width (float) – Width in pixels of an outline around the text.

  • stroke_color (Any) – Outline colour, in the same order as color; default: color.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • digits (str | None) – "arabic-indic" writes the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits()); default: as typed.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters font has no glyph for.

Returns:

image, drawn on.

Raises:

ValueError – if image is not a uint8 array of a supported shape.

Return type:

Any

khatt.tk_image(text, *, font='amiri', size_px=24, fill='black', background=None, max_width=None, align=None, padding=0, stroke_width=0, stroke_fill=None, keep_tashkeel=True, digits=None, fallback_fonts=(), master=None)

text drawn by khatt, as a Tkinter PhotoImage.

Pass it as the image of a Label or Button, or to Canvas.create_image. Keep a reference to it (for example as an attribute of the widget): Tk shows nothing once Python has dropped the image. Every image has the height of a line of the font, so labels and buttons in a row line up. A Tk window (tk.Tk()) must exist first, as for any PhotoImage.

For CustomTkinter, pass khatt.caption_image() (the same picture, as a Pillow image) to customtkinter.CTkImage.

Parameters:
  • text (str) – The text, as typed. Line breaks start new lines.

  • font (str | PathLike[str]) – A bundled font name (see khatt.list_fonts()) or the path to a .ttf/.otf font file.

  • size_px (int) – Font size in pixels per em.

  • fill (str | tuple[int, int, int] | tuple[int, int, int, int]) – Text colour: a name, #rrggbb[aa], or an RGB(A) tuple.

  • background (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – A colour behind the text; default: transparent, so the widget’s own background shows through.

  • max_width (int | None) – Wrap lines at spaces to this many pixels; the image is then this wide.

  • align (str | None) – "left", "right" or "center" alignment of lines; None aligns right-to-left paragraphs right and left-to-right ones left. "justify" with max_width fills the wrapped lines.

  • padding (int) – Empty pixels around the text.

  • stroke_width (float) – Width in pixels of an outline around the text.

  • stroke_fill (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Outline colour; default: fill.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • digits (str | None) – "arabic-indic" writes the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits()); default: as typed.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters font has no glyph for.

  • master (Any) – The Tk widget the image belongs to; default: the first Tk().

Returns:

A PIL.ImageTk.PhotoImage.

Raises:

ImportError – Python was built without Tkinter.

Return type:

Any

khatt.receipt_image(rows, *, width='80mm', title='', footer='', font='noto-naskh', size_px=28, title_size_px=None, line_spacing=1.3, margin=12, direction=None, threshold=128, fallback_fonts=())

A receipt as a black-and-white image for a thermal printer.

Parameters:
  • rows (Sequence[str | tuple[str, str]]) – The body, top to bottom. A string is a line, wrapped at spaces to the width and starting from its own side (Arabic from the right, English from the left); an empty string is a blank line; a string of three or more -, = or _ is a dividing line. A (start, end) pair puts start on the receipt’s starting side and end on the other, as an item and its price; a long start wraps without running into end.

  • width (int | str) – Printable width in dots: "80mm" (576), "58mm" (384) or a number.

  • title (str) – Centered at the top, larger; line breaks start new lines.

  • footer (str) – Centered at the bottom.

  • font (str | PathLike[str]) – A bundled font name or a font file path.

  • size_px (int) – Font size of the body, in dots per em.

  • title_size_px (int | None) – Font size of the title; default 1.4 times size_px.

  • line_spacing (float) – Distance between baselines, in multiples of the size.

  • margin (int) – Blank dots around the receipt.

  • direction (str | None) – "rtl" or "ltr": which side a pair starts on. Default: the direction of the first letter in the receipt.

  • threshold (int) – Coverage (0 to 255) from which a dot prints black.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters font has no glyph for.

Returns:

ready for escpos printer.image(...).

Return type:

A mode "1" image, width dots wide, black text on white

Numbers, poetry and justified text

khatt.arabic_digits(text)

text with its digits written as Arabic-Indic digits (٠١٢٣٤٥٦٧٨٩).

Inside a number, . becomes the Arabic decimal separator ٫ and , the thousands separator ٬, and a % right after a digit becomes ٪: so "1,250.5 ريال 15%" becomes "١٬٢٥٠٫٥ ريال ١٥٪". Each character is replaced by one character, so positions in the text (such as spans) stay the same.

>>> arabic_digits("السعر 150 ريال")
'السعر ١٥٠ ريال'
Parameters:

text (str)

Return type:

str

khatt.poem(verses, *, font='amiri', size_px=48, fill='black', background=None, gap=None, line_spacing=1.8, padding=0, stroke_width=0, stroke_fill=None, keep_tashkeel=True, digits=None, fallback_fonts=())

Draw verses of Arabic poetry in two columns, on their own image.

The first half of each verse goes on the right and the second on the left. All halves are stretched with kashida (then wider spaces) to the width of the longest, so both columns have straight edges, as poetry is printed.

>>> khatt.poem([("قفا نبك من ذكرى حبيب ومنزل", "بسقط اللوى بين الدخول فحومل")])
Parameters:
  • verses (str | Sequence[tuple[str, str]]) – (first half, second half) pairs, or text with one verse per line and its halves split by a tab, asterisks (* or ***) or three or more spaces.

  • font (str | PathLike[str]) – A bundled font name (see khatt.list_fonts()) or the path to a .ttf/.otf font file.

  • size_px (int) – Font size in pixels per em.

  • fill (str | tuple[int, int, int] | tuple[int, int, int, int]) – Text colour: a name, #rrggbb[aa], or an RGB(A) tuple.

  • background (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – A colour behind the poem; default: transparent.

  • gap (int | None) – Pixels between the two halves; default: one and a half size_px.

  • line_spacing (float) – Distance between verses’ baselines, in multiples of size_px.

  • padding (int) – Empty pixels around the poem.

  • stroke_width (float) – Width in pixels of an outline around the letters.

  • stroke_fill (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Outline colour; default: fill.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • digits (str | None) – "arabic-indic" writes the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits()); default: as typed.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters font has no glyph for.

Returns:

An RGBA image, or None when there is nothing to draw.

Raises:

ValueError – a verse does not have exactly two halves.

Return type:

Image | None

Word art, curves and shapes

khatt.word_art(text, *, effect='gold', font=WORD_ART_FONT, size_px=160, align=None, max_width=None, line_spacing=None, spacing=None, keep_tashkeel=True, digits=None, padding=0, background=None, fallback_fonts=(), curve=None)

Draw text as a finished piece of word art, on its own image.

The image is as big as the text and its effect, glow and shadow included, so it can be saved as it is or pasted onto something else.

Parameters:
  • text (str) – The text, as typed.

  • effect (str | Effect) – A preset name (see khatt.list_effects()) or a khatt.Effect.

  • font (str | PathLike[str]) – A bundled font name (see khatt.list_fonts()) or the path to a .ttf/.otf font file. The default is the heavy "lalezar", because effects show best on wide strokes.

  • size_px (int) – Font size in pixels per em.

  • align (str | None) – "left", "right", "center" or "justify" alignment of lines, as in draw_text().

  • max_width (int | None) – Wrap at spaces to this width in pixels.

  • line_spacing (float | None) – Distance between baselines, in multiples of size_px.

  • spacing (float | None) – Pixels between lines, as Pillow’s spacing.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • digits (str | None) – "arabic-indic" writes the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits()); default: as typed.

  • padding (int) – Empty pixels around the art.

  • background (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – A colour behind the art; default: transparent.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters font has no glyph for.

  • curve (str | Arc | Wave | None) – A preset name (see khatt.list_curves()), a khatt.Arc or a khatt.Wave. The whole line bends, so letters stay joined; the effect is then drawn on the bent text.

Returns:

An RGBA image, or None when text has nothing to draw.

Raises:

ValueError – the text is too short for curve.

Return type:

Image | None

class khatt.Effect(fill='black', outline=0, outline_fill='black', bevel=0, shadow=None, glows=(), extrude=None)

How to paint text. Back to front: glows, shadow, depth, outline, fill, bevel.

Parameters:
class khatt.Gradient(colors, angle=90)

A fill that blends through colors, spaced evenly across the text.

Parameters:
  • colors (Sequence[str | tuple[int, int, int] | tuple[int, int, int, int]]) – Two or more colours, as anywhere khatt takes a fill.

  • angle (float) – The direction of the blend in degrees, clockwise: 0 runs left to right, 90 (the default) top to bottom.

class khatt.Glow(radius=0.1, color='white', strength=1.5, offset=(0, 0))

Light around the text. Stack several for a bright core and a wide halo.

Parameters:
class khatt.Shadow(offset=(0.04, 0.05), blur=0.04, color='#00000099')

A shadow behind the text.

Parameters:
class khatt.Extrude(depth=0.1, angle=45, color='#333333', end_color=None)

Solid depth behind the text, as if it were cut from a block.

Parameters:
  • depth (float) – How deep it is, in font sizes.

  • angle (float) – The direction it runs in degrees, clockwise from right; the default, 45, runs down and to the right.

  • color (str | tuple[int, int, int] | tuple[int, int, int, int]) – The colour next to the text.

  • end_color (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – The colour at the far end; default: color all the way.

khatt.get_effect(effect)

Resolve a preset name to its Effect; an Effect passes through.

Presets are plain Effect objects, so dataclasses.replace makes variations: replace(khatt.get_effect("3d"), fill="#2563eb").

Raises:
  • KeyError – effect is not a preset name.

  • ValueError – effect is neither a name nor an Effect.

Parameters:

effect (str | Effect)

Return type:

Effect

khatt.list_effects()

Return the sorted names of all preset effects.

Return type:

list[str]

class khatt.Arc(angle=120)

Text along part of a circle.

The letters stay upright to the reader, and the text keeps its length along the middle of the line.

Parameters:

angle (float) – How much of the circle the text covers, in degrees, up to 350. Positive arches upwards; negative dips downwards, along the bottom of the circle.

class khatt.Wave(height=0.3, waves=1)

Text that rises and falls along its length.

Parameters:
  • height (float) – How far it rises and falls, in font sizes.

  • waves (float) – How many full waves fit along the text.

khatt.list_curves()

Return the sorted names of all preset curves.

Return type:

list[str]

khatt.calligram(text, shape='heart', *, width=800, font='amiri', size_px=None, repeat=True, fill='black', effect=None, line_spacing=1.15, justify=True, keep_tashkeel=True, padding=0, background=None, fallback_fonts=())

Draw text flowing inside a shape.

Lines run from the top of the shape to the bottom, each as wide as the shape at that height. Line breaks in text are treated as spaces.

Parameters:
  • text (str) – The text, as typed.

  • shape (str | Image) – A preset name (see khatt.list_shapes()) or a Pillow image of your own: its opaque pixels, or its dark ones if it has no transparency, are the inside.

  • width (int) – The width of the shape in pixels; the height follows it.

  • font (str | PathLike[str]) – A font name (see khatt.list_fonts()), a style name or the path to a .ttf/.otf file.

  • size_px (int | None) – The font size in pixels. By default small enough for several words a line, so the shape shows, or without repeat, the largest size at which all of the text fits.

  • repeat (bool) – Start the text again whenever it ends, until the shape is full: the default, because the shape shows best when it’s full. False fits the text in once, as big as it goes; short text then gives few lines, and the shape is harder to see.

  • fill (str | tuple[int, int, int] | tuple[int, int, int, int]) – The colour of the text, when there is no effect.

  • effect (str | Effect | None) – A preset name (see khatt.list_effects()) or a khatt.Effect, drawn over the whole calligram.

  • line_spacing (float) – Distance between baselines, in multiples of size_px.

  • justify (bool) – Stretch Arabic lines to the full width with kashida. A line that would need to grow by more than 30% is centred instead, and so is the last line without repeat, and lines of other scripts.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • padding (int) – Empty pixels around the calligram.

  • background (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – A colour behind it; default: transparent.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters font has no glyph for.

Returns:

An RGBA image as big as what was drawn, or None when text has nothing to draw. Text that doesn’t fit at 8 px, the smallest size tried, raises a khatt.TextOverflowWarning, and what fits is drawn.

Return type:

Image | None

khatt.list_shapes()

Return the sorted names of the preset shapes for calligram().

Return type:

list[str]

khatt.zakhrafa(text, style='tatweel')

Decorate text in a zakhrafa style, as plain text to copy and paste.

Arabic words are stretched or ornamented only where their letters join, so they stay joined. Other scripts are left as they are; a style’s frame still goes around the whole text.

Parameters:
Returns:

The decorated text. Empty or blank text comes back unchanged.

Raises:
Return type:

str

khatt.list_zakhrafa()

Return the sorted names of the zakhrafa styles.

Return type:

list[str]

khatt.render_svg(text, *, font='amiri', size_px=96, fill='black', align=None, max_width=None, line_spacing=None, spacing=None, keep_tashkeel=True, digits=None, stroke_width=0, stroke_fill=None, padding=0, background=None, fallback_fonts=())

Draw text as an SVG document of glyph outlines.

Lines are laid out as by khatt.draw_text(): the same wrapping, alignment and line spacing, so the SVG matches the image. Each glyph is its own path, so where Arabic letters join, their outlines overlap; a cutting machine needs them welded (Cricut Design Space: Weld).

Parameters:
  • text (str) – The text, as typed.

  • font (str | PathLike[str]) – A font name (see khatt.list_fonts()), a style name or the path to a .ttf/.otf file.

  • size_px (int) – Font size in pixels per em; the SVG’s units are pixels.

  • fill (str | tuple[int, int, int] | tuple[int, int, int, int]) – Text colour: a name, #rrggbb[aa], or an RGB(A) tuple.

  • align (str | None) – "left", "right" or "center" alignment of lines; None aligns right-to-left paragraphs right. "justify" with max_width fills the wrapped lines, as in khatt.draw_text().

  • max_width (int | None) – Wrap at spaces to this width in pixels.

  • line_spacing (float | None) – Distance between baselines, in multiples of size_px.

  • spacing (float | None) – Pixels between lines, as Pillow’s spacing.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • digits (str | None) – "arabic-indic" writes the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits()); default: as typed.

  • stroke_width (float) – Width of an outline around the letters, in pixels.

  • stroke_fill (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Its colour; default: fill.

  • padding (int) – Empty pixels around the text.

  • background (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – A colour behind the text; default: transparent.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters font has no glyph for.

Returns:

The SVG document, or None when text has nothing to draw.

Return type:

str | None

OCR training data

khatt.ocr_lines(texts, *, fonts=('amiri',), size_px=40, fill='black', background='white', padding=8, rotate=0, blur=0, noise=0, keep_tashkeel=True, digits=None, fallback_fonts=(), seed=None)

Draw each text as a line image for training OCR, with its exact label and word boxes.

Every line gets a font from fonts, a size, colours and degradations picked at random (seed makes the same picks every run). The label is the text as drawn, in logical order: with keep_tashkeel=False it has no diacritics either, and with digits its digits are the drawn ones.

Parameters:
  • texts (Iterable[str]) – One line each; blank ones are skipped. A text may end with a line break (as lines read from a file do), but not contain one.

  • fonts (Sequence[str | PathLike[str]]) – Bundled font names or font files to pick from.

  • size_px (int | tuple[int, int]) – Font size in pixels per em, or (smallest, largest) to pick from.

  • fill (str | tuple[int, int, int] | tuple[int, int, int, int] | Sequence[str | tuple[int, int, int] | tuple[int, int, int, int]]) – Text colour, or a list of colours to pick from.

  • background (str | tuple[int, int, int] | tuple[int, int, int, int] | Sequence[str | tuple[int, int, int] | tuple[int, int, int, int]]) – Background colour, or a list of colours to pick from.

  • padding (int) – Pixels of background around the line (its ink and the font’s ascender and descender).

  • rotate (float) – Turn each image by up to this many degrees either way.

  • blur (float) – Gaussian blur of up to this radius, in pixels.

  • noise (float) – Grey noise of up to this standard deviation, in levels of 255.

  • keep_tashkeel (bool) – Keep Arabic diacritics.

  • digits (str | None) – "arabic-indic" draws and labels digits as ٠ to ٩.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters the picked font has no glyph for.

  • seed (int | None) – Seed for the random picks.

Yields:

One OcrLine per text that has something to draw.

Raises:

ValueError – a text has a line break inside it, or an argument is out of range.

Return type:

Iterator[OcrLine]

class khatt.OcrLine(image, text, words, font, size_px)

A line image and its label.

Parameters:
text: str

exactly the text drawn, in logical (typed) order.

Type:

The label

words: tuple[OcrWord, ...]

Each word with ink, in reading order.

font: str

The font it was drawn in, as given in fonts.

class khatt.OcrWord(text, start, end, box)

One word of an OcrLine and where it is in the image.

Parameters:
text: str

The word, as in the label.

end: int

label[start:end].

Type:

Where it is in the label

box: tuple[int, int, int, int]

(left, top, right, bottom) in pixels, right and bottom exclusive. After a rotation, the smallest upright box around the turned word.

khatt.write_ocr_dataset(texts, folder, **options)

Draw texts with ocr_lines() and save them as a dataset in folder.

Writes images/000001.png and so on; metadata.jsonl, one JSON object per image (file_name, text, font, size_px, and words with each word’s text and box), which Hugging Face datasets loads with load_dataset("imagefolder", data_dir=folder); and labels.txt, each image’s path, a tab and its label, as PaddleOCR’s recognition training reads it.

Parameters:
Returns:

How many images were written.

Return type:

int

Video captions

class khatt.video.TextClip(*args, **kwargs)

A text clip drawn by khatt, with moviepy’s TextClip arguments.

The arguments are moviepy 2.2’s, in the same order and with the same meaning (see khatt.caption.caption_image()), except:

  • font is a bundled font name or a font file path, and None means "amiri" instead of Pillow’s bitmap font;

  • text_align defaults to None: right-to-left paragraphs align right and left-to-right ones left;

  • filename is read as UTF-8 whatever the system locale;

  • keep_tashkeel (keyword only) can strip Arabic diacritics;

  • digits (keyword only): "arabic-indic" draws the digits 0 to 9 as ٠ to ٩ (see khatt.arabic_digits());

  • fallback_fonts (keyword only) are fonts for characters font has no glyph for (see khatt.caption.caption_image()).

Like moviepy’s, it sets text, color and stroke_color.

Parameters:
  • font (Font | None)

  • text (str | None)

  • filename (str | os.PathLike[str] | None)

  • font_size (int | None)

  • size (tuple[int | None, int | None])

  • margin (Sequence[int | None])

  • color (Fill)

  • bg_color (Fill | None)

  • stroke_color (Fill | None)

  • stroke_width (float)

  • method (str)

  • text_align (str | None)

  • horizontal_align (str)

  • vertical_align (str)

  • interline (float)

  • transparent (bool)

  • duration (float | None)

  • keep_tashkeel (bool)

  • digits (str | None)

  • fallback_fonts (Font | Sequence[Font])

khatt.video.word_captions(words, size, *, font='amiri', font_size=None, color='white', highlight_color='gold', stroke_color='black', stroke_width=None, bg_color=None, highlight='word', max_chars=42, max_gap=1.0, hold=0.5, bottom=0.08, interline=4, keep_tashkeel=True, fallback_fonts=())

Word-timed captions for a video of size: each word lights up as it is said.

Lay the result over the video:

words = khatt.words_from_whisper(result)
captions = word_captions(words, video.size)
CompositeVideoClip([video, captions]).write_videofile("out.mp4")

Lines and timing come from khatt.caption_steps(). Every line is centred near the bottom and wrapped to 90% of the width; its highlighted words are drawn with spans, so their letters stay joined to the rest.

Parameters:
  • words (Sequence[Word]) – Timed words, for example from khatt.words_from_whisper().

  • size (tuple[int, int]) – (width, height) of the video.

  • font (str | PathLike[str]) – A bundled font name or a font file path.

  • font_size (int | None) – Pixels per em; default: 6.5% of the height.

  • color (str | tuple[int, int, int] | tuple[int, int, int, int]) – Colour of the words not highlighted.

  • highlight_color (str | tuple[int, int, int] | tuple[int, int, int, int]) – Colour of the highlighted words.

  • stroke_color (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Outline colour, or None for none.

  • stroke_width (float | None) – Outline width in pixels; default: 1/16 of the font size.

  • bg_color (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – A box behind each line, or None for none.

  • highlight (str) – "word" (only the word being said) or "spoken" (the words of the line said so far).

  • max_chars (int) – Longest line, in characters.

  • max_gap (float) – A pause longer than this many seconds starts a new line.

  • hold (float) – Seconds a line stays up after its last word.

  • bottom (float) – Space below the captions, as a fraction of the height.

  • interline (float) – Pixels between the lines of a wrapped caption.

  • keep_tashkeel (bool) – Keep Arabic diacritics (False strips them).

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters font has no glyph for.

Returns:

A transparent clip of size, as long as the captions.

Raises:

ValueError – if there are no words.

Return type:

moviepy.CompositeVideoClip

khatt.video.quran_captions(words, size, *, font='amiri', font_size=None, color='white', highlight_color='gold', stroke_color='black', stroke_width=None, bg_color=None, highlight='word', max_chars=60, hold=1.5, bottom=0.08, fallback_fonts=())

Word-timed captions for a Quran recitation over a video of size.

word_captions() set up for recitations: words from khatt.words_from_quran(), one verse at a time (a long verse is split at max_chars), every mark kept, lines spaced for the marks above and below them, and each verse shown until the next one starts (at most hold seconds after it ends):

words = khatt.words_from_quran(timings, verses)
captions = quran_captions(words, video.size)

The text is drawn exactly as given. Amiri (the default) draws the Uthmani script and the verse medallions; Amiri Quran and Scheherazade New come with pip install khatt-fonts, or pass any font file.

The arguments are word_captions()’s; the line spacing follows the font size.

Parameters:
Return type:

moviepy.CompositeVideoClip

khatt.caption_steps(words, *, max_chars=42, max_gap=1.0, hold=0.5, highlight='word')

What a word-timed caption shows, step by step.

Words are grouped into lines by group_words(). A line shows from its first word’s start until the next line starts, but at most hold seconds after its last word ends. Within it, each word stays highlighted from its start until the next word’s start.

Parameters:
  • words (Sequence[Word]) – Timed words, for example from words_from_whisper().

  • max_chars (int) – Longest caption line, in characters.

  • max_gap (float) – A pause longer than this many seconds starts a new line.

  • hold (float) – Seconds a line stays up after its last word.

  • highlight (str) – "word" highlights only the word being said; "spoken" highlights every word of the line said so far.

Returns:

Steps in time order, without overlaps.

Return type:

list[CaptionStep]

class khatt.CaptionStep(start, end, text, spans)

What a word-timed caption shows from start to end (seconds).

text is the caption line; spans are the (start, end) character ranges of text to highlight, ready for the spans of khatt.caption_image() or khatt.draw_text() with a colour added.

Parameters:
class khatt.Word(text, start, end)

One spoken word and when it is said, in seconds.

Parameters:
khatt.group_words(words, *, max_chars=42, max_gap=1.0)

Split timed words into caption lines.

A new line starts when the next word would make the line longer than max_chars characters, after a pause of more than max_gap seconds, or after a word that ends a sentence or a verse (its number from words_from_quran()). A word longer than max_chars still gets a line of its own.

Parameters:
Return type:

list[list[Word]]

khatt.words_from_whisper(result)

The timed words of a speech recogniser’s result.

Reads the results of openai-whisper and stable-ts (transcribe), faster-whisper (the (segments, info) pair, or just the segments) and whisperX (after align), always with word timestamps turned on (word_timestamps=True for whisper and faster-whisper). Words come back in order with spaces trimmed. A word with no timing of its own, as whisperX leaves numbers, gets the gap around it.

Raises:

ValueError – if the result has no word timings.

Parameters:

result (Any)

Return type:

list[Word]

khatt.words_from_quran(timings, text, *, verse_numbers=True)

The timed words of a Quran recitation, from its word timings and the verses’ text.

Timings give each word of a verse as [position, start_ms, end_ms]. This reads the Quran.com API (chapter_recitations/{reciter}/{chapter} with segments=true, or the QDC audio_files with verse_timings) and Tarteel QUL files (surah by surah, keyed "1:1", or ayah by ayah with surah and ayah).

The text comes from you, so it is always the edition you chose: a mapping of verse keys to verse text ({"1:1": "بِسْمِ ٱللَّهِ ..."}) or to its words, or Quran.com’s verses response with words. Words are counted as Quran.com counts them: a pause sign standing alone, such as ۛ, stays with the word before it, and ۞ with the word after it. Where the text starts a surah’s first verse with the basmala, as Tanzil’s does, the basmala is shown before the verse, lit until its first word, and not counted as one of its words. Editions still differ in a few places (Quran.com counts بَعْدَ مَا in 2:181 as one word), so with Quran.com timings its own verses response is the surest text; a verse with more words than its timings cover gives a warning.

Parameters:
  • timings (Any) – Word timings, in one of the formats above.

  • text (Any) – The verses, in one of the formats above.

  • verse_numbers (bool) – End each verse with its number in an end-of-ayah sign (۝ and the number), which fonts such as Amiri draw as the verse medallion. It is lit after the verse’s last word.

Returns:

The words in order, in seconds. A word with no timing (entries such as [2] are skipped) gets the gap around it.

Raises:

ValueError – if a verse’s text is missing, or its timings point past its last word.

Return type:

list[Word]

Terminal art

khatt.render(text, font='amiri', style='blocks', width=80, threshold=None, *, size=DEFAULT_SIZE, keep_tashkeel=False, fallback_fonts=(), fill=None)

Render Arabic (or mixed-direction) text as text art.

Parameters:
  • text (str) – The text to render; Arabic is shaped with correct positional forms and ligatures, and mixed Arabic/Latin/digit strings come out in visual order. Line breaks start new lines; right-to-left paragraphs are right-aligned.

  • font (str | PathLike[str]) – A bundled font name (see list_fonts()) or the path to a .ttf/.otf font file.

  • style (str) – Output character set (see list_styles()).

  • width (int | None) – Maximum output width in terminal columns; longer lines wrap at spaces. None means no limit (no wrapping).

  • threshold (float | None) – Optional coverage cutoff in [0, 1]: coverage below it renders blank; for braille it is the per-dot cutoff.

  • size (int | None) – Font size in character rows per em, the same for every style. If a single word is wider than width, the whole text shrinks so it fits. None scales the widest line to fill exactly width columns, without wrapping.

  • keep_tashkeel (bool) – Keep Arabic diacritics instead of stripping them (they are usually illegible at character-grid resolution).

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts tried in order (bundled names or file paths) for characters font has no glyph for.

  • fill (str | None) – For the letters style, the text whose letters ink the art (default: text itself). Read right to left along each row when it is Arabic, so the art spells it out.

Returns:

The rendered art, \n-separated, or an empty string when the input contains nothing renderable. Characters the font does not cover are skipped with an UnsupportedCharacterWarning.

Return type:

str

khatt.render_image(text, font='amiri', *, keep_tashkeel=True, fallback_fonts=())

Render text as a high-resolution grayscale image, black on white.

Uses the same shaping and line layout as render() (line breaks, right-aligned right-to-left paragraphs) at 256 pixels per em, without wrapping. The image is cropped to the ink.

Parameters:
Returns:

A Pillow image in mode "L", or None when the input contains nothing renderable. Unsupported characters are skipped with an UnsupportedCharacterWarning.

Return type:

Image | None

khatt.color_art(art, palette, *, direction='rtl', bands=False, mode='truecolor')

Colour text art with terminal colour codes, for printing in a terminal.

Parameters:
  • art (str) – Text art, as returned by khatt.render().

  • palette (str | Sequence[str | tuple[int, int, int] | tuple[int, int, int, int]]) – A palette name (see available_palettes()), colours separated by commas, or a list of colours.

  • direction (str) – Where the gradient starts (see DIRECTIONS).

  • bands (bool) – Solid bands of each colour instead of a smooth blend, like a flag.

  • mode (str) – "truecolor" (24-bit) or "256" for terminals with 256 colours.

Returns:

art with colour codes before each change of colour and a reset at the end of every coloured line. Blank cells get no colour.

Return type:

str

khatt.art_to_image(art, *, fg='black', bg='white', cell_width=12, padding=None, palette=None, direction='rtl', bands=False, canvas=None)

Draw text art as an image, one cell per character.

Parameters:
  • art (str) – Text art as returned by khatt.render(), in any style.

  • fg (str | tuple[int, int, int]) – Ink colour: a Pillow colour name, #rrggbb or an RGB tuple.

  • bg (str | tuple[int, int, int] | None) – Background colour, or None for a transparent background.

  • cell_width (int) – Width of one character cell in pixels; cells are twice as tall.

  • padding (int | None) – Margin around the art in pixels (default: one cell width).

  • palette (str | Sequence[str | tuple[int, int, int] | tuple[int, int, int, int]] | None) – Colour the art with a palette instead of fg: a palette name (see khatt.list_palettes()), colours separated by commas, or a list of colours.

  • direction (str) – Where the palette’s gradient starts: "rtl" (the right edge, the default), "ltr", "down" or "up".

  • bands (bool) – Solid bands of each palette colour instead of a blend.

  • canvas (str | tuple[int, int] | None) – Make an image of this size, (width, height) or a name from CANVASES ("social", "square"…), with the art as large as fits and centred; cell_width and padding are then worked out to suit.

Returns:

An RGB image (RGBA when bg is None), or None when the art contains nothing to draw.

Return type:

Image | None

khatt.art_to_svg(art, *, fg='black', bg='white', cell_width=12, padding=None, palette=None, direction='rtl', bands=False)

Draw text art as an SVG image, the vector twin of art_to_image().

Braille dots, shade blocks and block mosaics become circles and rectangles, so the art stays sharp at any zoom; other characters (the ascii ramp) are SVG text in a bold sans font. The arguments mean what they mean for art_to_image().

Returns:

The SVG document, or None when the art contains nothing to draw.

Parameters:
Return type:

str | None

khatt.art_to_html(art, *, fg='black', bg='white', palette=None, direction='rtl', bands=False)

Text art as an HTML <pre> block, each run of one colour in a <span>.

Unlike an image, the art stays text: it can be copied, and it is drawn by the browser’s monospace font. The arguments mean what they mean for art_to_image().

Parameters:
Return type:

str

khatt.animate(text, effect='type', *, font='amiri', style='blocks', size=DEFAULT_SIZE, palette=None, direction='rtl', bands=False, fps=12, hold=_HOLD, threshold=None, keep_tashkeel=False, fallback_fonts=(), fill=None, frame=None)

Animate one line of text as text art, keeping its letters joined.

Parameters:
Returns:

play it in a terminal or save it.

Return type:

The Animation

class khatt.Animation(frames, durations, colors=None)

Frames of text art, every one the same size, and how long each is shown.

colors holds each frame’s cell colours when the animation is coloured (see khatt.palette.cell_colors()), so a palette’s gradient stays in place while the text changes.

Parameters:
durations: list[float]

Seconds per frame.

ansi(index, mode='truecolor')

Frame index with terminal colour codes (plain when uncoloured).

Parameters:
Return type:

str

play(stream=None, *, loops=1, mode='truecolor')

Play the animation in a terminal, redrawing each frame in place.

Parameters:
  • stream (TextIO | None) – Where to write (default: standard output).

  • loops (int) – How many times to play it; 0 repeats until interrupted.

  • mode (str | None) – "truecolor", "256", or None for no colour codes.

Return type:

None

images(*, fg='black', bg='white', cell_width=12)

Every frame drawn with khatt.art_to_image(), all the same size.

Parameters:
Return type:

list[Image]

save(target, *, fg='black', bg='white', cell_width=12, loops=0)

Save as .gif, .png (APNG), .webp or .cast (asciinema).

Parameters:
  • target (str | Path) – The file; its extension picks the format.

  • fg (str | tuple[int, int, int]) – Colours and cell size of image formats (see khatt.art_to_image()); a palette’s colours win over fg.

  • bg (str | tuple[int, int, int]) – Colours and cell size of image formats (see khatt.art_to_image()); a palette’s colours win over fg.

  • cell_width (int) – Colours and cell size of image formats (see khatt.art_to_image()); a palette’s colours win over fg.

  • loops (int) – How many times image formats play; 0 (the default) loops forever.

Return type:

None

cast(mode='truecolor')

The animation as an asciinema v2 recording (play it with asciinema play).

Parameters:

mode (str)

Return type:

str

khatt.frame_art(art, style='double', *, padding=1)

art inside a frame.

Parameters:
  • art (str) – Text art, as returned by khatt.render().

  • style (str) – A frame style (see available_frames()).

  • padding (int) – Blank rows above and below the art; twice as many blank columns on each side, since terminal cells are twice as tall as they are wide.

Returns:

The framed art, every line the same width.

Return type:

str

khatt.CANVASES

Image sizes by name for frame_art and khatt --canvas: header (1500x500), social (1280x640, GitHub’s social preview), square (1080x1080), story (1080x1920) and wallpaper (1920x1080).

khatt.fetch(text=None, *, font='lalezar', style='quadrants', palette='gold', direction='rtl', bands=False, logo_width=56, width=None, color_mode='truecolor', shaped_by_terminal=False, arabic_digits=False, private=False, facts=None)

A system-information card for the terminal, in Arabic.

Parameters:
  • text (str | None) – The logo; by default the name of the operating system in Arabic letters (ويندوز, أوبونتو, ماك…).

  • font (str | PathLike[str]) – The logo’s font and text-art style (see khatt.render()).

  • style (str) – The logo’s font and text-art style (see khatt.render()).

  • palette (str | Sequence[str | tuple[int, int, int] | tuple[int, int, int, int]]) – The logo’s colours (see khatt.color_art()). The labels take the palette’s second colour, which reads well on dark and light backgrounds in every bundled palette.

  • direction (str) – The logo’s colours (see khatt.color_art()). The labels take the palette’s second colour, which reads well on dark and light backgrounds in every bundled palette.

  • bands (bool) – The logo’s colours (see khatt.color_art()). The labels take the palette’s second colour, which reads well on dark and light backgrounds in every bundled palette.

  • logo_width (int) – The most terminal columns the logo may take; it is drawn as large as fits that and the height of the facts.

  • width (int | None) – The most columns the whole card may take, such as the terminal’s width; the logo shrinks to make room for the facts.

  • color_mode (str | None) – "truecolor", "256", or None for no colour codes.

  • shaped_by_terminal (bool) – Whether the terminal joins and orders Arabic itself; if not, the labels are given to it joined and in display order (see khatt.terminal.for_terminal()).

  • arabic_digits (bool) – Write counts and dates in Eastern Arabic digits (٠١٢٣).

  • private (bool) – Leave out the user@host line, for screenshots.

  • facts (Sequence[Fact] | None) – The lines to show, instead of this machine’s (see system_facts()).

Returns:

the logo on the right, the facts to its left.

Return type:

The card, \n-separated

khatt.fetch_image(text=None, *, font='lalezar', style='quadrants', palette='gold', direction='rtl', bands=False, logo_width=56, arabic_digits=False, private=False, facts=None, text_font='cairo', size_px=26, fg='#cdd6f4', bg='#1e1e2e', cell_width=10)

The card of fetch() drawn as an image, with HarfBuzz shaping the Arabic.

The extra arguments: text_font and size_px for the labels and values, fg for the values, bg for the background (None for transparent), and cell_width for the logo’s character cells.

Parameters:
Return type:

Image

class khatt.Fact(label, value, numeric=False)

One line of the card: an Arabic label and its value.

Parameters:
numeric: bool = False

Whether the value is a count or a date, written in Arabic digits on request.

khatt.from_arabizi(text, words=None)

Arabizi in Arabic letters.

Parameters:
  • text (str) – Arabizi, such as "ana 7abibi, yalla!". Arabic letters in it are left as they are, and so are numbers.

  • words (Mapping[str, str] | None) – Your own spellings, {"arabizi": "عربي"}, matched without regard to case; they win over the built-in list and the rules.

Returns:

The text with every Latin word in Arabic letters, and ?, , and ; as ؟, ، and ؛.

Return type:

str

khatt.is_arabizi(text)

Whether text looks like Arabizi: Latin words with digit letters, or common words.

Only a hint (khatt suggests --arabizi when it sees it); it never converts anything by itself.

Parameters:

text (str)

Return type:

bool

khatt.map_image(image, style, threshold=None, fill=None)

Map a grayscale grid image to lines of text-art characters.

The image size must be an exact multiple of the style’s cell size; use khatt.raster.to_grid() with the style’s cell to produce it. fill is what the letters style inks with (default: خط).

Parameters:
Return type:

str

khatt.get_style(name)

Look up a style by name (case-insensitive).

Parameters:

name (str)

Return type:

Style

khatt.list_styles()

Return the sorted names of all output styles.

Return type:

list[str]

khatt.list_palettes()

Return the sorted names of the bundled palettes.

Return type:

list[str]

khatt.list_frames()

Return the sorted names of the frame styles.

Return type:

list[str]

Fonts

khatt.font_path(font)

Resolve a font name or a font file path to a font file.

Names are case-insensitive and win over a file of the same name. A style name such as "kufi" means a font of that style. With the khatt-fonts package installed, its fonts have names too, and so do its styles. Anything else is taken as the path to a TrueType or OpenType font (.ttf, .otf, or the first font of a .ttc collection).

Raises:
  • KeyError – font is neither a font name nor an existing file.

  • ValueError – the file is not a font khatt can shape and render.

Parameters:

font (str | PathLike[str])

Return type:

Path

khatt.font_paths(fonts)

Resolve fallback fonts with font_path(); a single font is a list of one.

Parameters:

fonts (str | PathLike[str] | Sequence[str | PathLike[str]])

Return type:

tuple[Path, …]

khatt.list_fonts()

Return the sorted names of all fonts: bundled, and from khatt-fonts if installed.

Return type:

list[str]

khatt.missing_characters(text, font='amiri', *, keep_tashkeel=True, fallback_fonts=())

The characters of text that font has no glyph for.

Check before drawing, e.g. to fall back to another font: khatt skips exactly these characters, with an UnsupportedCharacterWarning. Characters the font can still show, such as an accented letter it has in decomposed form, and invisible ones (ZWJ, ZWNJ, bidi marks) are not missing, nor are line breaks and tabs.

Parameters:
  • text (str) – The text, as typed.

  • font (str | PathLike[str]) – A bundled font name (see list_fonts()) or the path to a .ttf/.otf font file.

  • keep_tashkeel (bool) – Count Arabic diacritics, as drawing on images does by default. Pass False to match keep_tashkeel=False and render(), which strip them.

  • fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts that draw what font cannot, as in draw_text(): then only the characters none of them has are missing.

Returns:

Each missing character once, in the order they first appear; an empty list when the font covers the whole text.

Return type:

list[str]

Pillow code you already have

Pillow’s text calls, with Arabic drawn by khatt.

text(), textbbox() and textlength() take the same arguments as ImageDraw.text, textbbox and textlength (with the ImageDraw first). Text with Arabic letters is drawn by khatt, so it comes out the same whether or not Pillow has Raqm. Text that was already shaped with arabic_reshaper and get_display is turned back first (see khatt.unreshape()), so old code that pre-shapes keeps working when Pillow starts shaping too. Any other text goes to Pillow untouched.

For code you can’t change, such as a library that draws with ImageDraw.text, routing() sends its calls through khatt for as long as a with block lasts:

import khatt

with khatt.pillow.routing():
    image = some_library.render_card(name="محمد")
khatt.pillow.text(draw, xy, text, fill=None, font=None, anchor=None, spacing=4, align='left', direction=None, features=None, language=None, stroke_width=0, stroke_fill=None, embedded_color=False, *, font_size=None)

draw.text(xy, text, ...), with Arabic drawn by khatt.

Takes ImageDraw.text’s arguments. direction, features, language and embedded_color only apply to text Pillow draws: khatt lays Arabic out itself. Arabic is drawn on RGB, RGBA, L and LA images; on other modes Pillow draws everything.

Parameters:
Return type:

None

khatt.pillow.textbbox(draw, xy, text, font=None, anchor=None, spacing=4, align='left', direction=None, features=None, language=None, stroke_width=0, embedded_color=False, *, font_size=None)

draw.textbbox(xy, text, ...): the box text() draws Arabic in.

Parameters:
Return type:

tuple[float, float, float, float]

khatt.pillow.textlength(draw, text, font=None, direction=None, features=None, language=None, embedded_color=False, *, font_size=None)

draw.textlength(text, ...): for Arabic, the width text() draws it at.

Parameters:
  • draw (ImageDraw)

  • text (str)

  • font (Any)

  • direction (str | None)

  • features (list[str] | None)

  • language (str | None)

  • embedded_color (bool)

  • font_size (float | None)

Return type:

float

khatt.pillow.routing()

Send Pillow’s text drawing and measuring through khatt inside a with block.

ImageDraw.text, multiline_text, textbbox, multiline_textbbox and textlength, and FreeTypeFont.getbbox and getlength, behave as text(), textbbox() and textlength() until the block ends, also inside libraries that call them. Only text with Arabic letters changes. The methods are restored when the block ends, even after an error. It changes them for the whole process, so other threads see the routing while it lasts.

Return type:

Iterator[None]

Checking and repairing code

khatt.doctor(path=None)

Report which Arabic shaping engines are installed, and double-shaping risks.

Parameters:

path (str | PathLike[str] | None) – A project folder or Python file to look through as well, for code that pre-shapes Arabic (see find_reshaping()).

Returns:

A dict with the khatt, Python and Pillow versions; pillow_raqm (whether ImageDraw.text shapes Arabic); the matplotlib version (None if not installed) and whether it shapes Arabic natively; whether arabic_reshaper is importable; reshaping, the places in path that pre-shape Arabic; and warnings, a list of human-readable problems.

Return type:

DoctorReport

khatt.find_reshaping(path, *, limit=200)

Where a project pre-shapes Arabic text for another library.

Looks through the Python files under path (skipping virtual environments, site-packages and build folders) for calls to arabic_reshaper and to python-bidi’s get_display: the old recipe that now makes Pillow with Raqm and matplotlib 3.11+ shape text twice. A bare reshape(...) or get_display(...) counts only in a file that imports arabic_reshaper or bidi.

Returns:

Up to limit places, each "file:line: code".

Parameters:
Return type:

list[str]

khatt.unreshape(text, *, display_order=None, direction=None)

The text as typed, from arabic_reshaper’s output (and get_display’s).

Presentation forms go back to plain letters (a lam-alef ligature to lam and alef, ﷲ to الله), and lines that get_display reversed are put back in typed order. Symbols typed on purpose, such as ﷺ, stay. Text without presentation forms comes back unchanged.

Parameters:
  • text (str) – Text from arabic_reshaper.reshape, maybe then get_display; one line or several.

  • display_order (bool | None) – Whether the text went through get_display. None (default) tells from each line’s letter shapes.

  • direction (str | None) – "rtl" or "ltr": the direction the lines were written in, for undoing get_display. None (default) guesses: right to left, unless a line has more Latin letters than Arabic. A mostly Arabic line that starts with a Latin word looks the same in display order as one that ends with it; pass "ltr" for those.

Returns:

Plain text for khatt.draw_text(), or for Pillow with Raqm and matplotlib 3.11+, which shape it once.

Return type:

str

khatt.is_reshaped(text)

Whether text has Arabic presentation forms, as arabic_reshaper writes it.

Text as typed never needs them: they are the joined shapes of letters, which a shaper picks itself. Symbols typed on purpose, such as ﷺ and the ornate brackets ﴿ ﴾, don’t count.

Parameters:

text (str)

Return type:

bool

khatt.base_direction(text)

Paragraph direction, "rtl" or "ltr", from the first strong character.

Text with no strong character (digits, punctuation, empty) is "ltr".

Parameters:

text (str)

Return type:

str

khatt.strip_tashkeel(text)

Remove Arabic diacritical marks (harakat, tanween, shadda, sukun…).

Parameters:

text (str)

Return type:

str

exception khatt.ReshapedTextWarning

Text given to khatt was already shaped by arabic_reshaper (see unreshape()).

exception khatt.UnsupportedCharacterWarning

A character has no glyph in the requested font and was skipped.

exception khatt.TextOverflowWarning

Text did not fit in the box given to overlay(); it was clipped to the box.