update code

This commit is contained in:
lychang
2025-11-19 12:10:42 +08:00
parent 37c6ae9457
commit 8ff1b80be6
6 changed files with 1162 additions and 0 deletions

View File

@@ -5,6 +5,66 @@ from typing import Union, Optional
import sqlite3
from file import ObjectFileManager, LocalFileManager
import re
import html2text
import jinja2
import mammoth
def transform_docx2md(file_bytes: bytes, data: dict):
html_head = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
table, th, td {
border: 1px solid #000000;
border-collapse: collapse;
}
</style>
</head>
<body>"""
html_tail = """
</body>
</html>"""
result = mammoth.convert_to_html(file_bytes)
html = result.value
html = re.sub('<img.*?>', '', html)
c = re.compile(r'{(.*?)}')
ll = c.findall(html)
ta_list = []
for i in ll:
lc = i.split('+')
item_type = lc[1]
if item_type in ["TS", "TN", "TD"]:
if lc[0].split(".")[0] not in ta_list:
html = html.replace('{' + i + '}', '{{data["' + lc[0] + '"]}}')
else:
html = html.replace('{' + i + '}', '{{' + lc[0] + '}}')
elif item_type == "TP":
html = html.replace('{' + i + '}', '<img width="70%" src="data:image/jpeg;base64,{{data.' + lc[0] + '}}">')
elif item_type == "TC":
if lc[4] == "end":
html = html.replace('{' + i + '}', '\n{% endif %}\n')
if lc[4] == "start":
html = html.replace('{' + i + '}', '\n{% if data.' + lc[0] + '=="' + lc[3] + '" %}\n')
elif item_type == "TA":
ta_list.append(lc[0])
if lc[2] == "end":
html = html.replace('{' + i + '}</p></td></tr>', '\n</p></td></tr>{% endfor %}\n')
if lc[2] == "start":
html = html.replace('<tr><td><p>{' + i + '}',
'\n{% for ' + lc[0] + ' in data.' + lc[0] + ' %}\n<tr><td><p>')
else:
print(lc[0], lc)
html = jinja2.Template(html_head + html + html_tail).render(data=data)
markdown = html2text.html2text(html)
return html, markdown
class DatabaseManager: