text-generation-webui/modules/html_generator.py

162 lines
4.9 KiB
Python
Raw Normal View History

2023-01-07 03:14:08 +01:00
'''
2023-01-16 20:35:45 +01:00
This is a library for formatting GPT-4chan and chat outputs as nice HTML.
2023-01-07 03:14:08 +01:00
'''
2023-02-23 18:41:42 +01:00
import os
2023-01-07 03:14:08 +01:00
import re
import markdown
from pathlib import Path
2023-01-07 03:14:08 +01:00
from PIL import Image
# This is to store the paths to the thumbnails of the profile pictures
image_cache = {}
2023-01-15 20:43:31 +01:00
def generate_basic_html(s):
2023-02-16 01:13:12 +01:00
css = """
.container {
max-width: 600px;
margin-left: auto;
margin-right: auto;
2023-02-18 03:08:34 +01:00
background-color: rgb(31, 41, 55);
2023-02-16 01:13:12 +01:00
padding:3em;
}
.container p {
2023-02-19 02:14:57 +01:00
font-size: 16px !important;
2023-02-18 03:08:34 +01:00
color: white !important;
2023-02-16 01:13:12 +01:00
margin-bottom: 22px;
2023-02-19 02:14:57 +01:00
line-height: 1.4 !important;
2023-02-16 01:13:12 +01:00
}
"""
s = '\n'.join([f'<p>{line}</p>' for line in s.split('\n')])
s = f'<style>{css}</style><div class="container">{s}</div>'
2023-01-15 20:43:31 +01:00
return s
2023-01-07 03:14:08 +01:00
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('>', '&gt;', src)
src = re.sub('(&gt;&gt;[0-9]*)', '<span class="quote">\\1</span>', src)
src = re.sub('\n', '<br>\n', src)
src = f'<blockquote class="message">{src}\n'
src = f'<span class="name">Anonymous </span> <span class="number">No.{number}</span>\n{src}'
return src
2023-01-11 05:10:11 +01:00
def generate_4chan_html(f):
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../css/html_4chan_style.css'), 'r') as f:
css = f.read()
2023-01-07 03:14:08 +01:00
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'<div class="op">{posts[i]}</div>\n'
else:
posts[i] = f'<div class="reply">{posts[i]}</div>\n'
output = ''
output += f'<style>{css}</style><div id="parent"><div id="container">'
2023-01-07 03:14:08 +01:00
for post in posts:
output += post
output += '</div></div>'
2023-01-07 03:14:08 +01:00
output = output.split('\n')
for i in range(len(output)):
2023-01-07 05:20:10 +01:00
output[i] = re.sub(r'^(&gt;(.*?)(<br>|</div>))', r'<span class="greentext">\1</span>', output[i])
output[i] = re.sub(r'^<blockquote class="message">(&gt;(.*?)(<br>|</div>))', r'<blockquote class="message"><span class="greentext">\1</span>', output[i])
2023-01-07 03:14:08 +01:00
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'<img src="file/{get_image_cache(path)}">'
return ''
def generate_chat_html(history, name1, name2, character):
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../css/html_chat_style.css'), 'r') as f:
css = f.read()
output = f'<style>{css}</style><div class="chat" id="chat">'
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"""
<div class="message">
<div class="circle-bot">
{img_bot}
</div>
<div class="text">
<div class="username">
{name2}
</div>
<div class="message-body">
{row[1]}
</div>
</div>
</div>
"""
2023-01-19 20:46:46 +01:00
if not (i == len(history)-1 and len(row[0]) == 0):
output += f"""
<div class="message">
<div class="circle-you">
2023-02-08 03:26:02 +01:00
{img_me}
2023-01-19 20:46:46 +01:00
</div>
<div class="text">
<div class="username">
{name1}
</div>
<div class="message-body">
{row[0]}
2023-01-19 20:46:46 +01:00
</div>
</div>
</div>
2023-01-19 20:46:46 +01:00
"""
output += "</div>"
return output