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.textthat 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
anchorpoint 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;Nonealigns right-to-left paragraphs right and left-to-right ones left."justify"(withmax_width) fills every wrapped line but a paragraph’s last tomax_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/rfor 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) ord(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’smultiline_text: each line’s ascender line sitsspacingpixels below the previous line’s baseline (plus twicestroke_width, so outlines don’t eat into it). Negative values pull lines closer.keep_tashkeel (bool) – Keep Arabic diacritics (
Falsestrips them).digits (str | None) –
"arabic-indic"writes the digits 0 to 9 as ٠ to ٩ (seekhatt.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
fonthas no glyph for, such as a CJK font for Chinese inside Arabic text. Line spacing and anchors still followfont.effect (str | Effect | None) – A preset name (see
khatt.list_effects()) or akhatt.Effect. It decides the colours, sofillandstroke_fillare not used, and it brings its own outline, so it can’t be combined withstroke_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.Spanor a(start, end, fill)tuple, such as(0, 5, "gold")for the first five characters. Positions are intextas 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 witheffect.
- Returns:
image, drawn on. Characters the font does not cover are skipped with akhatt.UnsupportedCharacterWarning(seekhatt.missing_characters()).- Return type:
- 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 drawtextin, without drawing it.Like Pillow’s
ImageDraw.textbbox, and withdraw_text()’s arguments, which mean the same here. The box is exact: it holds every pixel thatdraw_text()would paint atxy, the outline included, and no row or column of it is blank.- Returns:
(left, top, right, bottom)in pixels,rightandbottomexclusive (soright - leftis the width). Text with nothing to draw (empty, or only spaces) gives an empty box atxy.- Parameters:
- Return type:
- 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
boxonimage(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 frommax_size_pxdown tomin_size_pxat which the text, wrapped at spaces, fits the box."wrap"wraps atmax_size_px;"none"draws atmax_size_pxwithout 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;Nonealigns right-to-left paragraphs right and left-to-right ones left."justify"fills the wrapped lines to the box’s width, as indraw_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 indraw_text().keep_tashkeel (bool) – Keep Arabic diacritics (
Falsestrips them).digits (str | None) –
"arabic-indic"writes the digits 0 to 9 as ٠ to ٩ (seekhatt.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
fonthas no glyph for, such as a CJK font for Chinese inside Arabic text. Line spacing and anchors still followfont.effect (str | Effect | None) – A preset name (see
khatt.list_effects()) or akhatt.Effect. It decides the colours, sofillandstroke_fillare not used, and it brings its own outline, so it can’t be combined withstroke_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 outsidebox: text that does not fit inside the padding (with"shrink", not even atmin_size_px) raises aTextOverflowWarningand is clipped to the box.- Return type:
- 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 drawtextatxy.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:
text (str) – The text, as typed.
ranges (Sequence[tuple[int, int]] | None) – The parts to measure, as
(start, end)positions intext, instead of its words (runs of characters between spaces). For example[(0, 3)]for the first three characters, or a verse number.size_px (int)
align (str | None)
anchor (str)
max_width (int | None)
line_spacing (float | None)
spacing (float | None)
keep_tashkeel (bool)
digits (str | None)
fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]])
- Returns:
One
WordBoxper 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:
- class khatt.WordBox(text, start, end, box, mask)¶
One word as
khatt.draw_text()draws it.
- class khatt.Span(start, end, fill)¶
Part of the text drawn in its own colour.
startandendare positions in the text as passed (endis not included), sotext[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.
- 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
textas moviepy’sTextClipwould show it, shaped by khatt.The arguments are
TextClip’s (moviepy 2.2), with the same meaning and defaults exceptfontandtext_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;Nonemeans"amiri".font_size (int | None) – Font size in pixels per em.
Nonepicks the largest size that fitssize(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.Nonefor 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);Noneis 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
transparentisFalse).stroke_color (str | tuple[int, int, int] | tuple[int, int, int, int] | None) – Outline colour;
Nonedraws the outline (ifstroke_widthis set) incolor, 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 inkhatt.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(seekhatt.draw_text()).transparent (bool) – RGBA image (
True) or RGB.keep_tashkeel (bool) – Keep Arabic diacritics (
Falsestrips them).digits (str | None) –
"arabic-indic"writes the digits 0 to 9 as ٠ to ٩ (seekhatt.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
fonthas no glyph for, such as a CJK font for Chinese inside Arabic text. Line spacing and anchors still followfont.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
transparentisFalse). Characters the font does not cover are skipped with akhatt.UnsupportedCharacterWarning.- Return type:
- 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 defaultorgis 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
uint8array:(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
anchorpoint 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’sorg.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 (
Falsestrips them).digits (str | None) –
"arabic-indic"writes the digits 0 to 9 as ٠ to ٩ (seekhatt.arabic_digits()); default: as typed.fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters
fonthas no glyph for.
- Returns:
image, drawn on.- Raises:
ValueError – if
imageis not auint8array of a supported shape.- Return type:
- 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)¶
textdrawn by khatt, as a TkinterPhotoImage.Pass it as the
imageof aLabelorButton, or toCanvas.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 anyPhotoImage.For CustomTkinter, pass
khatt.caption_image()(the same picture, as a Pillow image) tocustomtkinter.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;Nonealigns right-to-left paragraphs right and left-to-right ones left."justify"withmax_widthfills 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 (
Falsestrips them).digits (str | None) –
"arabic-indic"writes the digits 0 to 9 as ٠ to ٩ (seekhatt.arabic_digits()); default: as typed.fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters
fonthas 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:
- 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 putsstarton the receipt’s starting side andendon the other, as an item and its price; a longstartwraps without running intoend.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
fonthas no glyph for.
- Returns:
ready for
escposprinter.image(...).- Return type:
A mode
"1"image,widthdots wide, black text on white
Numbers, poetry and justified text¶
- khatt.arabic_digits(text)¶
textwith 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 asspans) stay the same.>>> arabic_digits("السعر 150 ريال") 'السعر ١٥٠ ريال'
- 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 (
Falsestrips them).digits (str | None) –
"arabic-indic"writes the digits 0 to 9 as ٠ to ٩ (seekhatt.arabic_digits()); default: as typed.fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters
fonthas no glyph for.
- Returns:
An RGBA image, or
Nonewhen 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
textas 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 akhatt.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 indraw_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 (
Falsestrips them).digits (str | None) –
"arabic-indic"writes the digits 0 to 9 as ٠ to ٩ (seekhatt.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
fonthas no glyph for.curve (str | Arc | Wave | None) – A preset name (see
khatt.list_curves()), akhatt.Arcor akhatt.Wave. The whole line bends, so letters stay joined; the effect is then drawn on the bent text.
- Returns:
An RGBA image, or
Nonewhentexthas 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:
fill (str | tuple[int, int, int] | tuple[int, int, int, int] | Gradient) – The colour of the letters, or a
Gradient.outline (float) – Outline width, in font sizes.
outline_fill (str | tuple[int, int, int] | tuple[int, int, int, int] | Gradient) – The colour of the outline, or a
Gradient.bevel (float) – How wide the rounded edge of the letters is, in font sizes. It catches light from the top left.
glows (Glow | Sequence[Glow]) – One
Glowor several, widest first.
- class khatt.Gradient(colors, angle=90)¶
A fill that blends through
colors, spaced evenly across the text.
- 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.
- class khatt.Shadow(offset=(0.04, 0.05), blur=0.04, color='#00000099')¶
A shadow behind the text.
- 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:
colorall the way.
- khatt.get_effect(effect)¶
Resolve a preset name to its
Effect; anEffectpasses through.Presets are plain
Effectobjects, sodataclasses.replacemakes variations:replace(khatt.get_effect("3d"), fill="#2563eb").- Raises:
KeyError –
effectis not a preset name.ValueError –
effectis neither a name nor anEffect.
- Parameters:
- Return type:
- 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.
- 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
textflowing 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
textare 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.
Falsefits 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 akhatt.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 (
Falsestrips 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
fonthas no glyph for.
- Returns:
An RGBA image as big as what was drawn, or
Nonewhentexthas nothing to draw. Text that doesn’t fit at 8 px, the smallest size tried, raises akhatt.TextOverflowWarning, and what fits is drawn.- Return type:
Image | None
- khatt.list_shapes()¶
Return the sorted names of the preset shapes for
calligram().
- khatt.zakhrafa(text, style='tatweel')¶
Decorate
textin 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:
text (str) – The text, as typed.
style (str) – A style name (see
khatt.list_zakhrafa()).
- Returns:
The decorated text. Empty or blank text comes back unchanged.
- Raises:
KeyError –
styleis not a style name.ValueError –
textorstyleis not a string.
- Return type:
- 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
textas 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;Nonealigns right-to-left paragraphs right."justify"withmax_widthfills the wrapped lines, as inkhatt.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 (
Falsestrips them).digits (str | None) –
"arabic-indic"writes the digits 0 to 9 as ٠ to ٩ (seekhatt.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
fonthas no glyph for.
- Returns:
The SVG document, or
Nonewhentexthas 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 (seedmakes the same picks every run). The label is the text as drawn, in logical order: withkeep_tashkeel=Falseit has no diacritics either, and withdigitsits 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
OcrLineper 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:
- class khatt.OcrLine(image, text, words, font, size_px)¶
A line image and its label.
- khatt.write_ocr_dataset(texts, folder, **options)¶
Draw
textswithocr_lines()and save them as a dataset infolder.Writes
images/000001.pngand so on;metadata.jsonl, one JSON object per image (file_name,text,font,size_px, andwordswith each word’stextandbox), which Hugging Facedatasetsloads withload_dataset("imagefolder", data_dir=folder); andlabels.txt, each image’s path, a tab and its label, as PaddleOCR’s recognition training reads it.- Parameters:
texts (Iterable[str]) – One line each, as in
ocr_lines().**options (Any) –
ocr_lines()’s keyword arguments.
- Returns:
How many images were written.
- Return type:
Video captions¶
- class khatt.video.TextClip(*args, **kwargs)¶
A text clip drawn by khatt, with moviepy’s
TextCliparguments.The arguments are moviepy 2.2’s, in the same order and with the same meaning (see
khatt.caption.caption_image()), except:fontis a bundled font name or a font file path, andNonemeans"amiri"instead of Pillow’s bitmap font;text_aligndefaults toNone: right-to-left paragraphs align right and left-to-right ones left;filenameis 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 ٩ (seekhatt.arabic_digits());fallback_fonts(keyword only) are fonts for charactersfonthas no glyph for (seekhatt.caption.caption_image()).
Like moviepy’s, it sets
text,colorandstroke_color.- Parameters:
font (Font | None)
text (str | None)
filename (str | os.PathLike[str] | None)
font_size (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 withspans, so their letters stay joined to the rest.- Parameters:
words (Sequence[Word]) – Timed words, for example from
khatt.words_from_whisper().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
Nonefor 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
Nonefor 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 (
Falsestrips them).fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters
fonthas 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 fromkhatt.words_from_quran(), one verse at a time (a long verse is split atmax_chars), every mark kept, lines spaced for the marks above and below them, and each verse shown until the next one starts (at mostholdseconds 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:
font_size (int | None)
color (str | tuple[int, int, int] | tuple[int, int, int, int])
highlight_color (str | tuple[int, int, int] | tuple[int, int, int, int])
stroke_color (str | tuple[int, int, int] | tuple[int, int, int, int] | None)
stroke_width (float | None)
bg_color (str | tuple[int, int, int] | tuple[int, int, int, int] | None)
highlight (str)
max_chars (int)
hold (float)
bottom (float)
fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]])
- 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 mostholdseconds 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:
- class khatt.CaptionStep(start, end, text, spans)¶
What a word-timed caption shows from
starttoend(seconds).textis the caption line;spansare the(start, end)character ranges oftextto highlight, ready for thespansofkhatt.caption_image()orkhatt.draw_text()with a colour added.
- class khatt.Word(text, start, end)¶
One spoken word and when it is said, in seconds.
- 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_charscharacters, after a pause of more thanmax_gapseconds, or after a word that ends a sentence or a verse (its number fromwords_from_quran()). A word longer thanmax_charsstill gets a line of its own.
- 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 (afteralign), always with word timestamps turned on (word_timestamps=Truefor 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:
- 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}withsegments=true, or the QDCaudio_fileswithverse_timings) and Tarteel QUL files (surah by surah, keyed"1:1", or ayah by ayah withsurahandayah).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’sversesresponse withwords. 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 ownversesresponse 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:
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.
Nonemeans no limit (no wrapping).threshold (float | None) – Optional coverage cutoff in [0, 1]: coverage below it renders blank; for
brailleit 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.Nonescales the widest line to fill exactlywidthcolumns, 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
fonthas no glyph for.fill (str | None) – For the
lettersstyle, the text whose letters ink the art (default:textitself). 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 anUnsupportedCharacterWarning.- Return type:
- 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:
text (str) – The text to render.
font (str | PathLike[str]) – A bundled font name (see
list_fonts()) or the path to a .ttf/.otf font file.keep_tashkeel (bool) – Keep Arabic diacritics (the default, unlike
render(): images have the resolution to show them). PassFalseto strip them.fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts for characters
fonthas no glyph for, as inrender().
- Returns:
A Pillow image in mode
"L", orNonewhen the input contains nothing renderable. Unsupported characters are skipped with anUnsupportedCharacterWarning.- 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:
artwith colour codes before each change of colour and a reset at the end of every coloured line. Blank cells get no colour.- Return type:
- 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,
#rrggbbor an RGB tuple.bg (str | tuple[int, int, int] | None) – Background colour, or
Nonefor 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 (seekhatt.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 fromCANVASES("social","square"…), with the art as large as fits and centred;cell_widthandpaddingare then worked out to suit.
- Returns:
An RGB image (RGBA when
bgisNone), orNonewhen 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
asciiramp) are SVG text in a bold sans font. The arguments mean what they mean forart_to_image().- Returns:
The SVG document, or
Nonewhen 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().
- 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:
text (str) – One line; line breaks become spaces.
effect (str) –
"type","wipe","kashida"or"shimmer"(see the module docstring).shimmerneeds apalette.font (str | PathLike[str]) – As for
khatt.render().style (str) – As for
khatt.render().size (int) – As for
khatt.render().threshold (float | None) – As for
khatt.render().keep_tashkeel (bool) – As for
khatt.render().fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – As for
khatt.render().palette (str | Sequence[str | tuple[int, int, int] | tuple[int, int, int, int]] | None) – Colour the frames (see
khatt.color_art()).direction (str) – Colour the frames (see
khatt.color_art()).bands (bool) – Colour the frames (see
khatt.color_art()).fill (str | None) – For the
lettersstyle, the text whose letters ink the art (default:text).frame (str | None) – Put every frame inside this frame style (see
khatt.frame_art()).fps (float) – Frames per second.
hold (float) – Seconds the finished text stays on screen at the end.
- 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.
colorsholds each frame’s cell colours when the animation is coloured (seekhatt.palette.cell_colors()), so a palette’s gradient stays in place while the text changes.- Parameters:
- ansi(index, mode='truecolor')¶
Frame
indexwith terminal colour codes (plain when uncoloured).
- play(stream=None, *, loops=1, mode='truecolor')¶
Play the animation in a terminal, redrawing each frame in place.
- images(*, fg='black', bg='white', cell_width=12)¶
Every frame drawn with
khatt.art_to_image(), all the same size.
- save(target, *, fg='black', bg='white', cell_width=12, loops=0)¶
Save as
.gif,.png(APNG),.webpor.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 overfg.bg (str | tuple[int, int, int]) – Colours and cell size of image formats (see
khatt.art_to_image()); a palette’s colours win overfg.cell_width (int) – Colours and cell size of image formats (see
khatt.art_to_image()); a palette’s colours win overfg.loops (int) – How many times image formats play;
0(the default) loops forever.
- Return type:
None
- khatt.frame_art(art, style='double', *, padding=1)¶
artinside 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:
- khatt.CANVASES¶
Image sizes by name for
frame_artandkhatt --canvas:header(1500x500),social(1280x640, GitHub’s social preview),square(1080x1080),story(1080x1920) andwallpaper(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", orNonefor 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@hostline, 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_fontandsize_pxfor the labels and values,fgfor the values,bgfor the background (Nonefor transparent), andcell_widthfor the logo’s character cells.
- class khatt.Fact(label, value, numeric=False)¶
One line of the card: an Arabic label and its value.
- khatt.from_arabizi(text, words=None)¶
Arabizi in Arabic letters.
- Parameters:
- Returns:
The text with every Latin word in Arabic letters, and
?,,and;as؟,،and؛.- Return type:
- khatt.is_arabizi(text)¶
Whether
textlooks like Arabizi: Latin words with digit letters, or common words.Only a hint (khatt suggests
--arabiziwhen it sees it); it never converts anything by itself.
- 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’scellto produce it.fillis what thelettersstyle inks with (default:خط).
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 thekhatt-fontspackage 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.ttccollection).
- khatt.font_paths(fonts)¶
Resolve fallback fonts with
font_path(); a single font is a list of one.
- khatt.list_fonts()¶
Return the sorted names of all fonts: bundled, and from
khatt-fontsif installed.
- khatt.missing_characters(text, font='amiri', *, keep_tashkeel=True, fallback_fonts=())¶
The characters of
textthatfonthas 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
Falseto matchkeep_tashkeel=Falseandrender(), which strip them.fallback_fonts (str | PathLike[str] | Sequence[str | PathLike[str]]) – Fonts that draw what
fontcannot, as indraw_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:
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,languageandembedded_coloronly 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 boxtext()draws Arabic in.- Parameters:
- Return type:
- 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 widthtext()draws it at.
- khatt.pillow.routing()¶
Send Pillow’s text drawing and measuring through khatt inside a
withblock.ImageDraw.text,multiline_text,textbbox,multiline_textbboxandtextlength, andFreeTypeFont.getbboxandgetlength, behave astext(),textbbox()andtextlength()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(whetherImageDraw.textshapes Arabic); the matplotlib version (Noneif not installed) and whether it shapes Arabic natively; whetherarabic_reshaperis importable;reshaping, the places inpaththat pre-shape Arabic; andwarnings, 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-packagesand build folders) for calls to arabic_reshaper and to python-bidi’sget_display: the old recipe that now makes Pillow with Raqm and matplotlib 3.11+ shape text twice. A barereshape(...)orget_display(...)counts only in a file that imports arabic_reshaper or bidi.
- 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 thatget_displayreversed 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 thenget_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 undoingget_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:
- khatt.is_reshaped(text)¶
Whether
texthas 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.
- khatt.base_direction(text)¶
Paragraph direction,
"rtl"or"ltr", from the first strong character.Text with no strong character (digits, punctuation, empty) is
"ltr".
- khatt.strip_tashkeel(text)¶
Remove Arabic diacritical marks (harakat, tanween, shadda, sukun…).
- 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.