''' This is a library for formatting GPT-4chan and chat outputs as nice HTML. ''' import os import re from pathlib import Path import markdown from PIL import Image # This is to store the paths to the thumbnails of the profile pictures image_cache = {} def generate_basic_html(s): with open(Path(__file__).resolve().parent / '../css/html_readable_style.css', 'r') as f: css = f.read() s = '\n'.join([f'

{line}

' for line in s.split('\n')]) s = f'
{s}
' return s def process_post(post, c): t = post.split('\n') number = t[0].split(' ')[1] if len(t) > 1: src = '\n'.join(t[1:]) else: src = '' src = re.sub('>', '>', src) src = re.sub('(>>[0-9]*)', '\\1', src) src = re.sub('\n', '
\n', src) src = f'
{src}\n' src = f'Anonymous No.{number}\n{src}' return src def generate_4chan_html(f): with open(Path(__file__).resolve().parent / '../css/html_4chan_style.css', 'r') as f: css = f.read() posts = [] post = '' c = -2 for line in f.splitlines(): line += "\n" if line == '-----\n': continue elif line.startswith('--- '): c += 1 if post != '': src = process_post(post, c) posts.append(src) post = line else: post += line if post != '': src = process_post(post, c) posts.append(src) for i in range(len(posts)): if i == 0: posts[i] = f'
{posts[i]}
\n' else: posts[i] = f'
{posts[i]}
\n' output = '' output += f'
' for post in posts: output += post output += '
' output = output.split('\n') for i in range(len(output)): output[i] = re.sub(r'^(>(.*?)(
|))', r'\1', output[i]) output[i] = re.sub(r'^
(>(.*?)(
|))', r'
\1', output[i]) output = '\n'.join(output) return output def get_image_cache(path): cache_folder = Path("cache") if not cache_folder.exists(): cache_folder.mkdir() 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((200, 200)) output_file = Path(f'cache/{path.name}_cache.png') img.convert('RGB').save(output_file, format='PNG') image_cache[path] = [mtime, output_file.as_posix()] return image_cache[path][1] def load_html_image(paths): for str_path in paths: path = Path(str_path) if path.exists(): return f'' return '' def generate_chat_html(history, name1, name2, character): with open(Path(__file__).resolve().parent / '../css/html_cai_style.css', 'r') as f: css = f.read() output = f'
' img_bot = load_html_image([f"characters/{character}.{ext}" for ext in ['png', 'jpg', 'jpeg']] + ["img_bot.png","img_bot.jpg","img_bot.jpeg"]) img_me = load_html_image(["img_me.png", "img_me.jpg", "img_me.jpeg"]) for i,_row in enumerate(history[::-1]): row = [markdown.markdown(re.sub(r"(.)```", r"\1\n```", entry), extensions=['fenced_code']) for entry in _row] output += f"""
{img_bot}
{name2}
{row[1]}
""" if not (i == len(history)-1 and len(row[0]) == 0): output += f"""
{img_me}
{name1}
{row[0]}
""" output += "
" return output