From 3923ac967fe0906dd3a072e5a3ed4d6d8f33e6f9 Mon Sep 17 00:00:00 2001 From: oobabooga <112222186+oobabooga@users.noreply.github.com> Date: Fri, 17 Feb 2023 14:30:39 -0300 Subject: [PATCH] Create a cache for profile pictures (in RAM) This is a performance optimization. --- modules/html_generator.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/modules/html_generator.py b/modules/html_generator.py index 18d6faad..6cf2d713 100644 --- a/modules/html_generator.py +++ b/modules/html_generator.py @@ -6,12 +6,16 @@ This is a library for formatting GPT-4chan and chat outputs as nice HTML. import base64 import copy +import os import re from io import BytesIO from pathlib import Path from PIL import Image +# This is to store chat profile pictures as base64-encoded thumbnails +image_cache = {} + def generate_basic_html(s): css = """ .container { @@ -182,11 +186,16 @@ def generate_4chan_html(f): return output def image_to_base64(path): - img = Image.open(path) - img.thumbnail((100, 100)) - img_buffer = BytesIO() - img.convert('RGB').save(img_buffer, format='PNG') - return base64.b64encode(img_buffer.getvalue()).decode("utf-8") + mtime = os.stat(path).st_mtime + + if (path in image_cache and mtime != image_cache[path][0]) or (path not in image_cache): + img = Image.open(path) + img.thumbnail((100, 100)) + img_buffer = BytesIO() + img.convert('RGB').save(img_buffer, format='PNG') + image_cache[path] = [mtime, base64.b64encode(img_buffer.getvalue()).decode("utf-8")] + + return image_cache[path][1] def generate_chat_html(history, name1, name2, character): css = """