Debian Codegraph @

python/louis/__init__.py.in

raw
1 # Liblouis Python ctypes bindings
2 #
3 # Copyright (C) 2009-2010 James Teh <[email protected]>
4 # Copyright (C) 2010-2012 Michael Whapples <[email protected]>
5 # Copyright (C) 2012-2024 Christian Egli <[email protected]>
6 # Copyright (C) 2015-2016 Davy Kager <[email protected]>
7 # Copyright (C) 2016 matt venn <[email protected]>
8 # Copyright (C) 2018-2025 Leonard de Ruijter <[email protected]>
9 # Copyright (C) 2018 Bue Vester-Andersen <[email protected]>
10 # Copyright (C) 2019 Dave Mielke <[email protected]>
11 # Copyright (C) 2019-2020 AndrĂ©-Abush Clause <[email protected]>
12 # Copyright (C) 2019 Bert Frees <[email protected]>
13 # Copyright (C) 2023 Rob Beezer <[email protected]>
14 # Copyright (C) 2024 Daniel Garcia Moreno <[email protected]>
15 #
16 # This file is part of liblouis.
17 #
18 # liblouis is free software: you can redistribute it and/or modify it
19 # under the terms of the GNU Lesser General Public License as published
20 # by the Free Software Foundation, either version 2.1 of the License, or
21 # (at your option) any later version.
22 #
23 # liblouis is distributed in the hope that it will be useful, but
24 # WITHOUT ANY WARRANTY; without even the implied warranty of
25 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26 # Lesser General Public License for more details.
27 #
28 # You should have received a copy of the GNU Lesser General Public
29 # License along with liblouis. If not, see <http://www.gnu.org/licenses/>.
30 #
31
32 """Liblouis Python ctypes bindings
33 These bindings allow you to use the liblouis braille translator and back-translator library
34 from within Python.
35 This documentation is only related to the Python helper.
36 Please see the liblouis documentation for more information.
37
38 Most of these functions take a C{tableList} argument which specifies
39 a list of translation tables to use. Please see the liblouis documentation
40 concerning the C{tableList} parameter to the C{lou_translateString}
41 function for information about how liblouis searches for these tables.
42
43 :author: Michael Curran <[email protected]>
44 :author: James Teh <[email protected]>
45 :author: Eitan Isaacson <[email protected]>
46 :author: Michael Whapples <[email protected]>
47 :author: Davy Kager <[email protected]>
48 :author: Leonard de Ruijter <[email protected]>
49 :author: Babbage B.V. <[email protected]>
50 :author: Andre-Abush Clause <[email protected]>
51 """
52
53 from atexit import register
54 from collections.abc import Generator, Iterable, Sequence
55 from ctypes import (
56 Array,
57 CFUNCTYPE,
58 POINTER,
59 c_char,
60 c_char_p,
61 c_int,
62 c_ushort,
63 cdll,
64 create_string_buffer,
65 string_at,
66 )
67 from sys import (
68 byteorder,
69 getdefaultencoding,
70 getfilesystemencoding,
71 platform,
72 )
73
74 try: # Native win32
75 from ctypes import WINFUNCTYPE, windll
76
77 _loader, _functype = windll, WINFUNCTYPE
78 except ImportError: # Unix/Cygwin
79 _loader, _functype = cdll, CFUNCTYPE
80 liblouis = _loader["###LIBLOUIS_SONAME###"]
81 _is_windows = platform == "win32"
82 _endianness = "be" if byteorder == "big" else "le"
83
84 # { Module Configuration
85 wideCharBytes: int = liblouis.lou_charSize()
86 """
87 Specifies the charSize (in bytes) used by liblouis.
88 This is fetched once using `liblouis.lou_charSize`.
89 Call it directly, since `charSize` is not yet defined.
90 """
91 outlenMultiplier: int = 4 + wideCharBytes * 2
92 """
93 Specifies the number by which the input length should be multiplied
94 to calculate the maximum output length.
95 The default will handle the case where every input character is
96 undefined in the translation table.
97 """
98 fileSystemEncoding: str = "mbcs" if _is_windows else getfilesystemencoding()
99 """Specifies the encoding to use when encode/decode file/dir name."""
100 conversionEncoding: str = "utf_%d_%s" % (wideCharBytes * 8, _endianness)
101 """Specifies the encoding to use when converting from byte strings to unicode strings."""
102
103
104 # Some general utility functions
105 TableListT = list[str | bytes]
106
107
108 def _createTableBuf(tablesList: TableListT) -> Array[c_char]:
109 """Creates a tables string for liblouis calls"""
110 return create_string_buffer(
111 b",".join(
112 [
113 x.encode(fileSystemEncoding) if isinstance(x, str) else bytes(x)
114 for x in tablesList
115 ]
116 )
117 )
118
119
120 def _createTypeformbuf(
121 length: int,
122 typeform: Iterable[int] | None = None,
123 ) -> Array[c_ushort]:
124 """Creates a typeform buffer for liblouis calls"""
125 return (c_ushort * length)(*typeform) if typeform else (c_ushort * length)()
126
127
128 ENCODING_ERROR_HANDLER = "surrogatepass"
129
130
131 def _createEncodedBuf(
132 x: str,
133 encoding: str = conversionEncoding,
134 errors: str = ENCODING_ERROR_HANDLER,
135 ) -> Array[c_char]:
136 return create_string_buffer(x.encode(encoding, errors))
137
138
139 def _processTableFiles(stringArray: Sequence[bytes] | None) -> Generator[str]:
140 if not stringArray:
141 return
142 i = 0
143 while stringArray[i] is not None:
144 yield stringArray[i].decode(fileSystemEncoding, errors=ENCODING_ERROR_HANDLER)
145 i += 1
146 liblouis.lou_freeTableFiles(stringArray)
147
148
149 def _createQueryStringBuf(dct: dict[str, str]) -> Array[c_char]:
150 """Create a query string from a dictionary"""
151 if not isinstance(dct, dict):
152 raise TypeError("Query should be a dictionary")
153 return create_string_buffer(
154 " ".join(
155 f"{k}:{v}"
156 for k, v in dct.items()
157 if isinstance(k, str) and isinstance(v, str)
158 ).encode(getdefaultencoding(), errors=ENCODING_ERROR_HANDLER)
159 )
160
161
162 register(liblouis.lou_free)
163
164 liblouis.lou_version.restype = c_char_p
165 liblouis.lou_version.argtypes = ()
166
167 liblouis.lou_charSize.restype = c_int
168 liblouis.lou_charSize.argtypes = ()
169
170 liblouis.lou_translateString.restype = c_int
171 liblouis.lou_translateString.argtypes = (
172 c_char_p,
173 POINTER(c_char),
174 POINTER(c_int),
175 POINTER(c_char),
176 POINTER(c_int),
177 POINTER(c_ushort),
178 POINTER(c_char),
179 c_int,
180 )
181
182 liblouis.lou_translate.restype = c_int
183 liblouis.lou_translate.argtypes = (
184 c_char_p,
185 POINTER(c_char),
186 POINTER(c_int),
187 POINTER(c_char),
188 POINTER(c_int),
189 POINTER(c_ushort),
190 POINTER(c_char),
191 POINTER(c_int),
192 POINTER(c_int),
193 POINTER(c_int),
194 c_int,
195 )
196
197 liblouis.lou_backTranslateString.restype = c_int
198 liblouis.lou_backTranslateString.argtypes = (
199 c_char_p,
200 POINTER(c_char),
201 POINTER(c_int),
202 POINTER(c_char),
203 POINTER(c_int),
204 POINTER(c_ushort),
205 POINTER(c_char),
206 c_int,
207 )
208
209 liblouis.lou_backTranslate.restype = c_int
210 liblouis.lou_backTranslate.argtypes = (
211 c_char_p,
212 POINTER(c_char),
213 POINTER(c_int),
214 POINTER(c_char),
215 POINTER(c_int),
216 POINTER(c_ushort),
217 POINTER(c_char),
218 POINTER(c_int),
219 POINTER(c_int),
220 POINTER(c_int),
221 c_int,
222 )
223
224 liblouis.lou_hyphenate.restype = c_int
225 liblouis.lou_hyphenate.argtypes = (
226 c_char_p,
227 POINTER(c_char),
228 c_int,
229 POINTER(c_char),
230 c_int,
231 )
232
233 liblouis.lou_checkTable.restype = c_int
234 liblouis.lou_checkTable.argtypes = (c_char_p,)
235
236 liblouis.lou_compileString.restype = c_int
237 liblouis.lou_compileString.argtypes = (c_char_p, c_char_p)
238
239 liblouis.lou_getTypeformForEmphClass.restype = c_ushort
240 liblouis.lou_getTypeformForEmphClass.argtypes = (c_char_p, c_char_p)
241
242 liblouis.lou_dotsToChar.restype = c_int
243 liblouis.lou_dotsToChar.argtypes = (
244 c_char_p,
245 POINTER(c_char),
246 POINTER(c_char),
247 c_int,
248 c_int,
249 )
250
251 liblouis.lou_charToDots.restype = c_int
252 liblouis.lou_charToDots.argtypes = (
253 c_char_p,
254 POINTER(c_char),
255 POINTER(c_char),
256 c_int,
257 c_int,
258 )
259
260 LogCallback = _functype(None, c_int, c_char_p)
261
262 liblouis.lou_registerLogCallback.restype = None
263 liblouis.lou_registerLogCallback.argtypes = (LogCallback,)
264
265 liblouis.lou_setLogLevel.restype = None
266 liblouis.lou_setLogLevel.argtypes = (c_int,)
267
268 liblouis.lou_findTable.restype = POINTER(c_char)
269 liblouis.lou_findTable.argtypes = (c_char_p,)
270
271 liblouis.lou_freeTableFile.restype = None
272 liblouis.lou_freeTableFile.argtypes = (POINTER(c_char),)
273
274 liblouis.lou_findTables.restype = POINTER(c_char_p)
275 liblouis.lou_findTables.argtypes = (c_char_p,)
276
277 liblouis.lou_freeTableFiles.restype = None
278 liblouis.lou_freeTableFiles.argtypes = (POINTER(c_char_p),)
279
280 liblouis.lou_getTableInfo.restype = POINTER(c_char)
281 liblouis.lou_getTableInfo.argtypes = (c_char_p, c_char_p)
282
283 liblouis.lou_freeTableInfo.restype = None
284 liblouis.lou_freeTableInfo.argtypes = (liblouis.lou_getTableInfo.restype,)
285
286 liblouis.lou_listTables.restype = POINTER(c_char_p)
287 liblouis.lou_listTables.argtypes = ()
288
289 liblouis.lou_free.restype = None
290 liblouis.lou_free.argtypes = ()
291
292
293 def version() -> str:
294 """Obtain version information for liblouis.
295 :return: The version of liblouis, plus other information, such as
296 the release date and perhaps notable changes.
297 """
298 return liblouis.lou_version().decode("ASCII")
299
300
301 def charSize() -> int:
302 """Obtain charSize information for liblouis.
303 :return: The size of the widechar with which liblouis was compiled.
304 """
305 return liblouis.lou_charSize()
306
307
308 def translate(
309 tableList: TableListT,
310 inbuf: str,
311 typeform: list[int] | None = None,
312 cursorPos: int = 0,
313 mode: int = 0,
314 ) -> tuple[str, list[int], list[int], int]:
315 """Translate a string of characters, providing position information.
316 :param tableList: A list of translation tables.
317 :param inbuf: The string to translate.
318 :param typeform: A list of typeform constants indicating the typeform for each position in inbuf,
319 `None` for no typeform information.
320 :param cursorPos: The position of the cursor in inbuf.
321 :param mode: The translation mode; add multiple values for a combined mode.
322 :return: A tuple of: the translated string,
323 a list of input positions for each position in the output,
324 a list of output positions for each position in the input, and
325 the position of the cursor in the output.
326 :raise RuntimeError: If a complete translation could not be done.
327 :see: lou_translate in the liblouis documentation
328 """
329 tableBuf: Array[c_char] = _createTableBuf(tableList)
330 _inbuf = _createEncodedBuf(inbuf)
331 inlen = c_int(len(_inbuf) // wideCharBytes)
332 outlen = c_int(inlen.value * outlenMultiplier)
333 outbuf = create_string_buffer(outlen.value * wideCharBytes)
334 typeformbuf = None
335 if typeform:
336 typeformbuf = _createTypeformbuf(outlen.value, typeform)
337 inPos = (c_int * outlen.value)()
338 outPos = (c_int * inlen.value)()
339 _cursorPos = c_int(cursorPos)
340 if not liblouis.lou_translate(
341 tableBuf,
342 _inbuf,
343 inlen,
344 outbuf,
345 outlen,
346 typeformbuf,
347 None,
348 outPos,
349 inPos,
350 _cursorPos,
351 mode,
352 ):
353 raise RuntimeError(
354 f"Can't translate: tables {tableList!r}, inbuf {inbuf!r}, typeform {typeform!r}, cursorPos {cursorPos!r}, mode {mode!r}"
355 )
356 if isinstance(typeform, list) and typeformbuf is not None:
357 typeform[:] = list(typeformbuf)
358 return (
359 outbuf.raw[: outlen.value * wideCharBytes].decode(
360 conversionEncoding,
361 errors=ENCODING_ERROR_HANDLER,
362 ),
363 inPos[: outlen.value],
364 outPos[: inlen.value],
365 _cursorPos.value,
366 )
367
368
369 def translateString(
370 tableList: TableListT,
371 inbuf: str,
372 typeform: list[int] | None = None,
373 mode: int = 0,
374 ) -> str:
375 """Translate a string of characters.
376 :param tableList: A list of translation tables.
377 :param inbuf: The string to translate.
378 :param typeform: A list of typeform constants indicating the typeform for each position in inbuf,
379 `None` for no typeform information.
380 :param mode: The translation mode; add multiple values for a combined mode.
381 :return: The translated string.
382 :raise RuntimeError: If a complete translation could not be done.
383 :see: lou_translateString in the liblouis documentation
384 """
385 tableBuf = _createTableBuf(tableList)
386 _inbuf = _createEncodedBuf(inbuf)
387 inlen = c_int(len(_inbuf) // wideCharBytes)
388 outlen = c_int(inlen.value * outlenMultiplier)
389 outbuf = create_string_buffer(outlen.value * wideCharBytes)
390 typeformbuf = None
391 if typeform:
392 typeformbuf = _createTypeformbuf(outlen.value, typeform)
393 if not liblouis.lou_translateString(
394 tableBuf,
395 _inbuf,
396 inlen,
397 outbuf,
398 outlen,
399 typeformbuf,
400 None,
401 mode,
402 ):
403 raise RuntimeError(
404 f"Can't translate: tables {tableList}, inbuf {inbuf}, typeform {typeform}, mode {mode}"
405 )
406 if isinstance(typeform, list) and typeformbuf is not None:
407 typeform[:] = list(typeformbuf)
408 return outbuf.raw[: outlen.value * wideCharBytes].decode(
409 conversionEncoding,
410 errors=ENCODING_ERROR_HANDLER,
411 )
412
413
414 def backTranslate(
415 tableList: TableListT,
416 inbuf: str,
417 typeform: list[int] | None = None,
418 cursorPos: int = 0,
419 mode: int = 0,
420 ) -> tuple[str, list[int], list[int], int]:
421 """Back translates a string of characters, providing position information.
422 :param tableList: A list of translation tables.
423 :param inbuf: Braille to back translate.
424 :param typeform: List where typeform constants will be placed.
425 :param cursorPos: Position of cursor.
426 :param mode: Translation mode.
427 :return: A tuple: A string of the back translation,
428 a list of input positions for each position in the output,
429 a list of the output positions for each position in the input and
430 the position of the cursor in the output.
431 :raise RuntimeError: If a complete back translation could not be done.
432 :see: lou_backTranslate in the liblouis documentation.
433 """
434 tableBuf = _createTableBuf(tableList)
435 _inbuf = _createEncodedBuf(inbuf)
436 inlen = c_int(len(_inbuf) // wideCharBytes)
437 outlen = c_int(inlen.value * outlenMultiplier)
438 outbuf = create_string_buffer(outlen.value * wideCharBytes)
439 typeformbuf = None
440 if isinstance(typeform, list):
441 typeformbuf = _createTypeformbuf(outlen.value)
442 inPos = (c_int * outlen.value)()
443 outPos = (c_int * inlen.value)()
444 _cursorPos = c_int(cursorPos)
445 if not liblouis.lou_backTranslate(
446 tableBuf,
447 _inbuf,
448 inlen,
449 outbuf,
450 outlen,
451 typeformbuf,
452 None,
453 outPos,
454 inPos,
455 _cursorPos,
456 mode,
457 ):
458 raise RuntimeError(
459 f"Can't back translate: tables {tableList!r}, inbuf {inbuf!r}, typeform {typeform!r}, cursorPos {cursorPos!r}, mode {mode!r}"
460 )
461 if isinstance(typeform, list) and typeformbuf is not None:
462 typeform[:] = list(typeformbuf)
463 return (
464 outbuf.raw[: outlen.value * wideCharBytes].decode(
465 conversionEncoding,
466 errors=ENCODING_ERROR_HANDLER,
467 ),
468 inPos[: outlen.value],
469 outPos[: inlen.value],
470 _cursorPos.value,
471 )
472
473
474 def backTranslateString(
475 tableList: TableListT,
476 inbuf: str,
477 typeform: list[int] | None = None,
478 mode: int = 0,
479 ) -> str:
480 """Back translate from Braille.
481 :param tableList: A list of translation tables.
482 :param inbuf: The Braille to back translate.
483 :param typeform: List for typeform constants to be put in.
484 If you don't want typeform data then give `None`
485 :param mode: The translation mode
486 :return: The back translation of inbuf.
487 :raise RuntimeError: If a complete back translation could not be done.
488 :see: lou_backTranslateString in the liblouis documentation.
489 """
490 tableBuf = _createTableBuf(tableList)
491 _inbuf = _createEncodedBuf(inbuf)
492 inlen = c_int(len(_inbuf) // wideCharBytes)
493 outlen = c_int(inlen.value * outlenMultiplier)
494 outbuf = create_string_buffer(outlen.value * wideCharBytes)
495 typeformbuf = None
496 if isinstance(typeform, list):
497 typeformbuf = _createTypeformbuf(outlen.value)
498 if not liblouis.lou_backTranslateString(
499 tableBuf,
500 _inbuf,
501 inlen,
502 outbuf,
503 outlen,
504 typeformbuf,
505 None,
506 mode,
507 ):
508 raise RuntimeError(
509 f"Can't back translate: tables {tableList!r}, inbuf {inbuf!r}, mode {mode!r}"
510 )
511 if isinstance(typeform, list) and typeformbuf is not None:
512 typeform[:] = list(typeformbuf)
513 return outbuf.raw[: outlen.value * wideCharBytes].decode(
514 conversionEncoding,
515 errors=ENCODING_ERROR_HANDLER,
516 )
517
518
519 def hyphenate(tableList: TableListT, inbuf: str, mode: int = 0) -> str:
520 """Get information for hyphenation.
521 :param tableList: A list of translation tables and hyphenation
522 dictionaries.
523 :param inbuf: The text to get hyphenation information about.
524 This should be a single word and leading/trailing whitespace
525 and punctuation is ignored.
526 :param mode: Lets liblouis know if inbuf is plain text or Braille.
527 Set to 0 for text and anyother value for Braille.
528 :return: A string with '1' at the beginning of every syllable
529 and '0' elsewhere.
530 :raise RuntimeError: If hyphenation data could not be produced.
531 :see: lou_hyphenate in the liblouis documentation.
532 """
533 tableBuf = _createTableBuf(tableList)
534 _inbuf = _createEncodedBuf(inbuf)
535 inlen = c_int(len(_inbuf) // wideCharBytes)
536 hyphen_string = create_string_buffer(inlen.value + 1)
537 if not liblouis.lou_hyphenate(
538 tableBuf,
539 _inbuf,
540 inlen,
541 hyphen_string,
542 mode,
543 ):
544 raise RuntimeError(
545 f"Can't hyphenate: tables {tableList!r}, inbuf {inbuf!r}, mode {mode!r}"
546 )
547 return hyphen_string.value.decode("ASCII")
548
549
550 def checkTable(tableList: TableListT) -> None:
551 """Check if the specified tables can be found and compiled.
552 This can be used to check if a list of tables contains errors
553 before sending it to other liblouis functions
554 that accept a list of tables.
555 :param tableList: A list of translation tables.
556 :raise RuntimeError: If compilation failed.
557 :see: lou_checkTable in the liblouis documentation
558 """
559 tableBuf = _createTableBuf(tableList)
560 if not liblouis.lou_checkTable(tableBuf):
561 raise RuntimeError(f"Can't compile: tables {tableList}")
562
563
564 def compileString(tableList: TableListT, inString: str) -> None:
565 """Compile a table entry on the fly at run-time.
566 :param tableList: A list of translation tables.
567 :param inString: The table entry to be added.
568 :raise RuntimeError: If compilation of the entry failed.
569 :see: lou_compileString in the liblouis documentation
570 """
571 tableBuf = _createTableBuf(tableList)
572 inbuf = create_string_buffer(
573 inString.encode("ASCII") if isinstance(inString, str) else bytes(inString)
574 )
575 if not liblouis.lou_compileString(tableBuf, inbuf):
576 raise RuntimeError(
577 f"Can't compile entry: tables {tableList}, inString {inString}"
578 )
579
580
581 def getTypeformForEmphClass(tableList: TableListT, emphClass: str) -> int:
582 """Get the typeform bit for the named emphasis class.
583 :param tableList: A list of translation tables.
584 :param emphClass: An emphasis class name.
585 :see: lou_getTypeformForEmphClass in the liblouis documentation
586 """
587 tableBuf = _createTableBuf(tableList)
588 bEmphClass = emphClass.encode("ASCII")
589 return liblouis.lou_getTypeformForEmphClass(tableBuf, bEmphClass)
590
591
592 def dotsToChar(tableList: TableListT, inbuf: str) -> str:
593 """Convert a string of dot patterns to a string of characters according to the specifications in tableList.
594 :param tableList: A list of translation tables.
595 :param inbuf: a string of dot patterns, either in liblouis format or Unicode braille.
596 :raise RuntimeError: If a complete conversion could not be done.
597 :see: lou_dotsToChar in the liblouis documentation
598 """
599 tableBuf = _createTableBuf(tableList)
600 _inbuf = _createEncodedBuf(inbuf)
601 length = c_int(len(inbuf) // wideCharBytes)
602 outbuf = create_string_buffer(length.value * wideCharBytes)
603 if not liblouis.lou_dotsToChar(tableBuf, _inbuf, outbuf, length, 0):
604 raise RuntimeError(
605 f"Can't convert dots to char: tables {tableList}, inbuf {inbuf!r}"
606 )
607 return outbuf.raw[: length.value * wideCharBytes].decode(
608 conversionEncoding,
609 errors=ENCODING_ERROR_HANDLER,
610 )
611
612
613 def charToDots(tableList: TableListT, inbuf: str, mode: int = 0) -> str:
614 """Convert a string of characterss to a string of dot patterns according to the specifications in tableList.
615 :param tableList: A list of translation tables.
616 :param inbuf: a string of characters.
617 :param mode: The translation mode; add multiple values for a combined mode.
618 :raise RuntimeError: If a complete conversion could not be done.
619 :see: lou_charToDots in the liblouis documentation
620 """
621 tableBuf = _createTableBuf(tableList)
622 _inbuf = _createEncodedBuf(inbuf)
623 length = c_int(len(inbuf) // wideCharBytes)
624 outbuf = create_string_buffer(length.value * wideCharBytes)
625 if not liblouis.lou_charToDots(tableBuf, _inbuf, outbuf, length, mode):
626 raise RuntimeError(
627 f"Can't convert char to dots: tables {tableList!r}, inbuf {inbuf!r}, mode {mode!r}"
628 )
629 return outbuf.raw[: length.value * wideCharBytes].decode(
630 conversionEncoding,
631 errors=ENCODING_ERROR_HANDLER,
632 )
633
634
635 def registerLogCallback(logCallback) -> None:
636 """Register logging callbacks.
637 Set to `None` for default callback.
638 :param logCallback: The callback to use.
639 The callback must take two arguments:
640 :param level: The log level on which a message is logged.
641 :type level: int
642 :param message: The logged message.
643 Note that the callback should provide its own UTF-8 decoding routine.
644 :type message: bytes
645
646 Example callback:
647
648 @louis.LogCallback
649 def incomingLouisLog(level, message):
650 print("Message %s logged at level %d" % (message.decode("ASCII"), level))
651
652 @type logCallback: `LogCallback`
653 """
654 if logCallback is None:
655 logCallback = LogCallback(0)
656 elif not isinstance(logCallback, LogCallback):
657 raise TypeError(
658 f"logCallback should be of type {LogCallback.__name__} or NoneType"
659 )
660 return liblouis.lou_registerLogCallback(logCallback)
661
662
663 def setLogLevel(level: int) -> None:
664 """Set the level for logging callback to be called at.
665 :param level: one of the C{LOG_*} constants.
666 :raise ValueError: If an invalid log level is provided.
667 """
668 if level not in logLevels:
669 raise ValueError("Level %d is an invalid log level" % level)
670 return liblouis.lou_setLogLevel(level)
671
672
673 def findTable(query: dict[str, str]) -> str | None:
674 """Find the best match for a query
675
676 Returns the name of the table, or None when no match can be
677 found. An error message is given when the query is invalid. Freeing.
678 :param query: The query to lookup.
679 """
680 queryStr = _createQueryStringBuf(query)
681 result = liblouis.lou_findTable(queryStr)
682 if not result:
683 return None
684 string = string_at(result).decode(fileSystemEncoding, errors=ENCODING_ERROR_HANDLER)
685 liblouis.lou_freeTableFile(result)
686 return string
687
688
689 def findTables(query: dict[str, str]) -> list[str]:
690 """Find all matches for a query, best match first.
691
692 Returns the names of the matched tables.
693 An error message is given when the query is invalid.
694 :param query: The query to lookup.
695 """
696 queryStr = _createQueryStringBuf(query)
697 result = liblouis.lou_findTables(queryStr)
698 return list(_processTableFiles(result))
699
700
701 def getTableInfo(tableName: str, key: str) -> str | None:
702 """Read metadata from a file.
703
704 Returns the value of the first occurring metadata field specified by
705 `key' in `table', or None when the field does not exist.
706 """
707 bTableName = _createEncodedBuf(tableName, fileSystemEncoding)
708 bKey = _createEncodedBuf(key, getdefaultencoding())
709 result = liblouis.lou_getTableInfo(bTableName, bKey)
710 if not result:
711 return None
712 string = string_at(result).decode(errors=ENCODING_ERROR_HANDLER)
713 liblouis.lou_freeTableInfo(result)
714 return string
715
716
717 def listTables() -> list[str]:
718 """List available tables.
719
720 Returns the names of available tables as list of strings.
721 Only tables that are discoverable, i.e. the have active metadata, are listed.
722 """
723 result = liblouis.lou_listTables()
724 return list(_processTableFiles(result))
725
726
727 # { Typeforms
728 plain_text = 0x0000
729 emph_1 = comp_emph_1 = italic = 0x0001
730 emph_2 = comp_emph_2 = underline = 0x0002
731 emph_3 = comp_emph_3 = bold = 0x0004
732 emph_4 = 0x0008
733 emph_5 = 0x0010
734 emph_6 = 0x0020
735 emph_7 = 0x0040
736 emph_8 = 0x0080
737 emph_9 = 0x0100
738 emph_10 = 0x0200
739 computer_braille = 0x0400
740 no_translate = 0x0800
741 no_contract = 0x1000
742 # }
743
744 # { Translation modes
745 noContractions = 1
746 compbrlAtCursor = 2
747 dotsIO = 4
748 compbrlLeftCursor = 32
749 ucBrl = 64
750 noUndefined = 128
751 noUndefinedDots = noUndefined # alias for backward compatiblity
752 partialTrans = 256
753 # }
754
755 # { logLevels
756 LOG_ALL = 0
757 LOG_DEBUG = 10000
758 LOG_INFO = 20000
759 LOG_WARN = 30000
760 LOG_ERROR = 40000
761 LOG_FATAL = 50000
762 LOG_OFF = 60000
763 # }
764
765 logLevels = (LOG_ALL, LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL, LOG_OFF)
766
767 if __name__ == "__main__":
768 # Just some common tests.
769 print(version())
770 print(translate([b"../tables/en-us-g2.ctb"], "Hello world!", cursorPos=5))