Archived
1
0
Fork 0
This repository has been archived on 2024-04-26. You can view files and clone it, but cannot push or open issues or pull requests.
akari-bot/core/utils/image_table.py

78 lines
2.3 KiB
Python
Raw Normal View History

2021-11-08 16:09:06 +00:00
import os
2021-11-12 14:25:53 +00:00
import re
2021-11-08 16:09:06 +00:00
import traceback
2022-01-07 15:50:43 +00:00
from html import escape
2021-11-08 16:09:06 +00:00
from typing import List, Union
import aiohttp
2021-11-12 14:25:53 +00:00
import ujson as json
2021-11-08 16:09:06 +00:00
from tabulate import tabulate
from config import Config
2022-01-20 13:31:50 +00:00
from core.logger import Logger
2022-06-12 07:07:53 +00:00
from .cache import random_cache_path
2021-11-08 16:09:06 +00:00
2022-08-21 03:22:45 +00:00
web_render = Config('web_render_local')
2021-11-08 16:09:06 +00:00
class ImageTable:
def __init__(self, data, headers):
self.data = data
self.headers = headers
2022-04-23 14:22:56 +00:00
async def image_table_render(table: Union[ImageTable, List[ImageTable]], save_source=False):
2021-11-08 16:09:06 +00:00
if not web_render:
return False
try:
tblst = []
if isinstance(table, ImageTable):
table = [table]
max_width = 500
for tbl in table:
d = []
for row in tbl.data:
cs = []
for c in row:
2022-01-07 16:27:57 +00:00
cs.append(re.sub(r'\n', '<br>', escape(c)))
2021-11-08 16:09:06 +00:00
d.append(cs)
w = len(tbl.headers) * 500
if w > max_width:
max_width = w
tblst.append(re.sub(r'<table>|</table>', '', tabulate(d, tbl.headers, tablefmt='unsafehtml')))
tblst = '<table>' + '\n'.join(tblst) + '</table>'
css = """
<style>table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid rgba(0,0,0,0.05);
font-size: 0.8125rem;
font-weight: 500;
}
th, td {
padding: 15px;
text-align: left;
}</style>"""
html = {'content': tblst + css, 'width': w}
2022-04-23 14:22:56 +00:00
if save_source:
2022-06-12 07:07:53 +00:00
fname = random_cache_path() + '.html'
2022-04-23 14:22:56 +00:00
with open(fname, 'w') as fi:
fi.write(tblst + css)
2022-06-12 07:07:53 +00:00
picname = random_cache_path() + '.jpg'
2021-11-08 16:09:06 +00:00
if os.path.exists(picname):
os.remove(picname)
async with aiohttp.ClientSession() as session:
async with session.post(web_render, headers={
'Content-Type': 'application/json',
}, data=json.dumps(html)) as resp:
with open(picname, 'wb+') as jpg:
jpg.write(await resp.read())
return picname
except Exception:
2022-01-20 13:31:50 +00:00
Logger.error(traceback.format_exc())
2021-11-08 16:09:06 +00:00
return False
2022-06-12 07:07:53 +00:00
2022-08-10 09:54:07 +00:00
__all__ = ['ImageTable', 'image_table_render', 'web_render']