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

87 lines
2.7 KiB
Python
Raw Normal View History

2023-04-19 07:41:39 +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
2023-04-19 07:41:39 +00:00
from .http import download_to_cache
web_render = Config('web_render')
web_render_local = 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
async def image_table_render(table: Union[ImageTable, List[ImageTable]], save_source=True, use_local=True):
if not web_render_local:
if not web_render:
Logger.warn('[Webrender] Webrender is not configured.')
return False
use_local = False
2021-11-08 16:09:06 +00:00
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>"""
2023-01-19 14:31:02 +00:00
html = {'content': tblst + css, 'width': w, 'mw': False}
2022-04-23 14:22:56 +00:00
if save_source:
2022-06-12 07:07:53 +00:00
fname = random_cache_path() + '.html'
2023-03-04 08:51:56 +00:00
with open(fname, 'w', encoding='utf-8') as fi:
2022-04-23 14:22:56 +00:00
fi.write(tblst + css)
2023-02-07 18:45:40 +00:00
pic = False
try:
2023-02-07 18:45:40 +00:00
pic = await download_to_cache(web_render_local if use_local else web_render, method='POST', headers={
'Content-Type': 'application/json',
2023-02-07 18:45:40 +00:00
}, post_data=json.dumps(html), request_private_ip=True)
except aiohttp.ClientConnectorError:
2023-03-01 17:50:56 +00:00
if use_local:
pic = await download_to_cache(web_render, method='POST', headers={
'Content-Type': 'application/json',
}, post_data=json.dumps(html), request_private_ip=True)
else:
return False
return pic
2021-11-08 16:09:06 +00:00
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
__all__ = ['ImageTable', 'image_table_render']