wrapper.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """Provides a wrpper for the Rust based implementation."""
  2. from typing import Optional, Union
  3. from .bidi import get_base_level_inner, get_display_inner
  4. StrOrBytes = Union[str, bytes]
  5. def get_display(
  6. str_or_bytes: StrOrBytes,
  7. encoding: str = "utf-8",
  8. base_dir: Optional[str] = None,
  9. debug: bool = False,
  10. ) -> StrOrBytes:
  11. """Accepts string or bytes. In case of bytes, `encoding`
  12. is needed as the inner function expects a valid string (default:"utf-8").
  13. Set `base_dir` to 'L' or 'R' to override the calculated base_level.
  14. Set `debug` to True to return the calculated levels.
  15. Returns the display layout, either as unicode or `encoding` encoded
  16. string.
  17. """
  18. if isinstance(str_or_bytes, bytes):
  19. text = str_or_bytes.decode(encoding)
  20. was_decoded = True
  21. else:
  22. text = str_or_bytes
  23. was_decoded = False
  24. display = get_display_inner(text, base_dir, debug)
  25. if was_decoded:
  26. display = display.encode(encoding)
  27. return display
  28. def get_base_level(text: str) -> int:
  29. """Returns the base unicode level of the 1st paragraph in `text`.
  30. Return value of 0 means LTR, while 1 means RTL.
  31. """
  32. return get_base_level_inner(text)