def init_font_and_image()

in web-app-pix2info-python/src/backend/render.py [0:0]


def init_font_and_image(demo: Demo):
    demo.border_width = int(0.003 * demo.input_width)

    options = demo.options
    expand_image = options.barcodes or options.entities
    needs_font = expand_image or options.fields or demo.show_confidence
    if not needs_font:
        demo.text_height_min = 0
        demo.text_height_median = 0
        demo.font_min = None
        demo.font_median = None
        demo.text_outline_width = 0
        demo.text_padding = 0
        return

    img_max_x, img_max_y = demo.input_width - 1, demo.input_height - 1
    heights = [
        layout_height(item.layout, img_max_x, img_max_y) for item in demo.page.tokens
    ]
    demo.text_height_min = min(heights)
    demo.text_height_median = statistics.median_low(heights)
    demo.font_min = ImageFont.truetype(FONT_FAMILY, size=demo.text_height_min)
    demo.font_median = ImageFont.truetype(FONT_FAMILY, size=demo.text_height_median)
    text_outline_width = int(demo.text_height_median * TEXT_OUTLINE_HEIGHT_RATIO + 0.5)
    text_outline_width = max(text_outline_width, TEXT_OUTLINE_MIN_WIDTH)
    demo.text_outline_width = text_outline_width
    demo.text_padding = int(demo.text_height_median * TEXT_PADDING_TEXT_H_RATIO + 0.5)

    # Image may need to be expanded to display additional information on the right side
    if not expand_image:
        return
    coords = [(x, y) for _, _, (_, _, x, y), _, _, _ in callout_info(demo)]
    if not coords:
        return

    max_x, max_y = cast(tuple[int, int], map(max, zip(*coords)))
    demo.image_crop_box = (
        demo.page_crop_box[0],
        demo.page_crop_box[1],
        max_x + CROP_MARGIN,
        max(max_y + CROP_MARGIN, demo.page_crop_box[3]),
    )
    max_x = demo.image_crop_box[2]
    max_y = demo.image_crop_box[3]
    pad_w, pad_h = max(0, max_x - img_max_x), max(0, max_y - img_max_y)
    if pad_w == 0 and pad_h == 0:
        return

    padded = Image.new(
        demo.image.mode,
        (demo.image.width + pad_w, demo.image.height + pad_h),
        PADDING_BG_COLOR,
    )
    padded.paste(demo.image)
    demo.image = padded