fonts.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. # Copyright (c) 2024 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from pathlib import Path
  15. import PIL
  16. from PIL import ImageFont
  17. from . import logging
  18. from .cache import CACHE_DIR
  19. from .download import download
  20. from .flags import LOCAL_FONT_FILE_PATH
  21. def create_font(txt: str, sz: tuple, font_path: str) -> ImageFont:
  22. """
  23. Create a font object with specified size and path, adjusted to fit within the given image region.
  24. Parameters:
  25. txt (str): The text to be rendered with the font.
  26. sz (tuple): A tuple containing the height and width of an image region, used for font size.
  27. font_path (str): The path to the font file.
  28. Returns:
  29. ImageFont: An ImageFont object adjusted to fit within the given image region.
  30. """
  31. font_size = int(sz[1] * 0.8)
  32. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  33. if int(PIL.__version__.split(".")[0]) < 10:
  34. length = font.getsize(txt)[0]
  35. else:
  36. length = font.getlength(txt)
  37. if length > sz[0]:
  38. font_size = int(font_size * sz[0] / length)
  39. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  40. return font
  41. def create_font_vertical(
  42. txt: str, sz: tuple, font_path: str, scale=1.2
  43. ) -> ImageFont.FreeTypeFont:
  44. n = len(txt) if len(txt) > 0 else 1
  45. base_font_size = int(sz[1] / n * 0.8 * scale)
  46. base_font_size = max(base_font_size, 10)
  47. font = ImageFont.truetype(font_path, base_font_size, encoding="utf-8")
  48. if int(PIL.__version__.split(".")[0]) < 10:
  49. max_char_width = max([font.getsize(c)[0] for c in txt])
  50. else:
  51. max_char_width = max([font.getlength(c) for c in txt])
  52. if max_char_width > sz[0]:
  53. new_size = int(base_font_size * sz[0] / max_char_width)
  54. new_size = max(new_size, 10)
  55. font = ImageFont.truetype(font_path, new_size, encoding="utf-8")
  56. return font
  57. class Font:
  58. def __init__(self, font_name=None, local_path=None):
  59. if local_path is None:
  60. if Path(str(LOCAL_FONT_FILE_PATH)).is_file():
  61. local_path = str(LOCAL_FONT_FILE_PATH)
  62. self._local_path = local_path
  63. if not local_path:
  64. assert font_name is not None
  65. self._font_name = font_name
  66. @property
  67. def path(self):
  68. # HACK: download font file when needed only
  69. if not self._local_path:
  70. self._get_offical_font()
  71. return self._local_path
  72. def _get_offical_font(self):
  73. """
  74. Download the official font file.
  75. """
  76. font_path = (Path(CACHE_DIR) / "fonts" / self._font_name).resolve().as_posix()
  77. if not Path(font_path).is_file():
  78. download(
  79. url=f"https://paddle-model-ecology.bj.bcebos.com/paddlex/PaddleX3.0/fonts/{self._font_name}",
  80. save_path=font_path,
  81. )
  82. self._local_path = font_path
  83. if Path(str(LOCAL_FONT_FILE_PATH)).is_file():
  84. logging.warning(
  85. f"Using the local font file(`{LOCAL_FONT_FILE_PATH}`) specified by `LOCAL_FONT_FILE_PATH`!"
  86. )
  87. PINGFANG_FONT = Font(font_name="PingFang-SC-Regular.ttf")
  88. SIMFANG_FONT = Font(font_name="simfang.ttf")
  89. LATIN_FONT = Font(font_name="latin.ttf")
  90. TH_FONT = Font(font_name="th.ttf")
  91. EL_FONT = Font(font_name="el.ttf")
  92. KOREAN_FONT = Font(font_name="korean.ttf")
  93. ARABIC_FONT = Font(font_name="arabic.ttf")
  94. CYRILLIC_FONT = Font(font_name="cyrillic.ttf")
  95. KANNADA_FONT = Font(font_name="kannada.ttf")
  96. TELUGU_FONT = Font(font_name="telugu.ttf")
  97. TAMIL_FONT = Font(font_name="tamil.ttf")
  98. DEVANAGARI_FONT = Font(font_name="devanagari.ttf")