Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 26 additions & 42 deletions doc/code/converters/3_image_converters.ipynb

Large diffs are not rendered by default.

14 changes: 9 additions & 5 deletions pyrit/converter/add_text_image_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def __init__(
self,
*,
text_to_add: str,
font_name: str = "helvetica.ttf",
font_name: str | None = None,
color: tuple[int, int, int] = (0, 0, 0),
font_size: int = 15,
x_pos: int = 10,
Expand All @@ -44,7 +44,8 @@ def __init__(

Args:
text_to_add (str): Text to add to an image.
font_name (str): Path of font to use. Must be a TrueType font (.ttf). Defaults to "helvetica.ttf".
font_name (str | None): Path of font to use. Must be a TrueType font (.ttf).
Defaults to None which uses Pillow's built-in default font.
color (tuple): Color to print text in, using RGB values. Defaults to (0, 0, 0).
font_size (int): Size of font to use. Defaults to 15.
x_pos (int): X coordinate to place text in (0 is left most). Defaults to 10.
Expand All @@ -55,7 +56,7 @@ def __init__(
"""
if text_to_add.strip() == "":
raise ValueError("Please provide valid text_to_add value")
if not font_name.endswith(".ttf"):
if font_name is not None and not font_name.endswith(".ttf"):
raise ValueError("The specified font must be a TrueType font with a .ttf extension")
self._text_to_add = text_to_add
self._font_name = font_name
Expand Down Expand Up @@ -91,10 +92,13 @@ def _load_font(self) -> FreeTypeFont:
Returns:
FreeTypeFont: The loaded font object. Falls back to Pillow's built-in default font on error.
"""
font_name = self._font_name
if font_name is None:
return cast("FreeTypeFont", ImageFont.load_default(size=self._font_size))
try:
return ImageFont.truetype(self._font_name, self._font_size)
return ImageFont.truetype(font_name, self._font_size)
except OSError:
logger.warning(f"Cannot open font resource: {self._font_name}. Using Pillow built-in default font.")
logger.warning(f"Cannot open font resource: {font_name}. Using Pillow built-in default font.")
return cast("FreeTypeFont", ImageFont.load_default(size=self._font_size))

def _add_text_to_image(self, image: Image.Image) -> Image.Image:
Expand Down
12 changes: 7 additions & 5 deletions tests/unit/converter/test_add_text_image_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,20 @@ def text_image_converter_sample_image_bytes():
return img_bytes.getvalue()


def test_add_text_image_converter_initialization():
def test_add_text_image_converter_initialization(caplog):
converter = AddTextImageConverter(
text_to_add="Sample text", font_name="helvetica.ttf", color=(255, 255, 255), font_size=20, x_pos=10, y_pos=10
text_to_add="Sample text", color=(255, 255, 255), font_size=20, x_pos=10, y_pos=10
)
assert converter._text_to_add == "Sample text"
assert converter._font_name == "helvetica.ttf"
assert converter._font_name is None
assert converter._color == (255, 255, 255)
assert converter._font_size == 20
assert converter._x_pos == 10
assert converter._y_pos == 10
assert converter._font is not None
assert type(converter._font) is ImageFont.FreeTypeFont
# The default (None) uses Pillow's built-in font directly, so no font-loading warning is emitted.
assert not any("Cannot open font resource" in record.message for record in caplog.records)


def test_add_text_image_converter_invalid_font():
Expand All @@ -40,7 +42,7 @@ def test_add_text_image_converter_invalid_font():

def test_add_text_image_converter_invalid_text_to_add():
with pytest.raises(ValueError):
AddTextImageConverter(text_to_add="", font_name="helvetica.ttf")
AddTextImageConverter(text_to_add="")


def test_add_text_image_converter_fallback_to_default_font(text_image_converter_sample_image_bytes, caplog):
Expand All @@ -66,7 +68,7 @@ def test_add_text_image_converter_fallback_to_default_font(text_image_converter_


def test_text_image_converter_add_text_to_image(text_image_converter_sample_image_bytes):
converter = AddTextImageConverter(text_to_add="Hello, World!", font_name="helvetica.ttf", color=(255, 255, 255))
converter = AddTextImageConverter(text_to_add="Hello, World!", color=(255, 255, 255))
image = Image.open(BytesIO(text_image_converter_sample_image_bytes))
try:
pixels_before = list(image.get_flattened_data())
Expand Down