"""
HTML/Markdown 处理工具模块
提供 HTML 和 Markdown 内容的处理功能:
- 图片引用处理(转换为 base64)
- HTML 表格转换
- 表格解析
"""
import os
import base64
import pandas as pd
from io import StringIO
from html import unescape
from typing import List, Optional
import re
def find_image_in_multiple_locations(img_src: str, json_path: str) -> Optional[str]:
"""
在多个可能的位置查找图片文件
Args:
img_src: 图片源路径
json_path: JSON 文件路径(用于相对路径解析)
Returns:
找到的图片完整路径,如果未找到则返回 None
"""
json_dir = os.path.dirname(json_path)
# 可能的搜索路径
search_paths = [
# 相对于JSON文件的路径
os.path.join(json_dir, img_src),
# 相对于JSON文件父目录的路径
os.path.join(os.path.dirname(json_dir), img_src),
# imgs目录(常见的图片目录)
os.path.join(json_dir, 'imgs', os.path.basename(img_src)),
os.path.join(os.path.dirname(json_dir), 'imgs', os.path.basename(img_src)),
# images目录
os.path.join(json_dir, 'images', os.path.basename(img_src)),
os.path.join(os.path.dirname(json_dir), 'images', os.path.basename(img_src)),
# 同名目录
os.path.join(json_dir, os.path.splitext(os.path.basename(json_path))[0], os.path.basename(img_src)),
]
# 如果是绝对路径,也加入搜索
if os.path.isabs(img_src):
search_paths.insert(0, img_src)
# 查找存在的文件
for path in search_paths:
if os.path.exists(path):
return path
return None
def process_html_images(html_content: str, json_path: str) -> str:
"""
处理HTML内容中的图片引用,将本地图片转换为base64
Args:
html_content: HTML 内容
json_path: JSON 文件路径(用于相对路径解析)
Returns:
处理后的 HTML 内容(图片已转换为 base64)
"""
# 匹配HTML图片标签:
img_pattern = r'
]*src\s*=\s*["\']([^"\']+)["\'][^>]*/?>'
def replace_html_image(match):
full_tag = match.group(0)
img_src = match.group(1)
# 如果已经是base64或者网络链接,直接返回
if img_src.startswith('data:image') or img_src.startswith('http'):
return full_tag
# 增强的图片查找
full_img_path = find_image_in_multiple_locations(img_src, json_path)
# 尝试转换为base64
try:
if full_img_path and os.path.exists(full_img_path):
with open(full_img_path, 'rb') as img_file:
img_data = img_file.read()
# 获取文件扩展名确定MIME类型
ext = os.path.splitext(full_img_path)[1].lower()
mime_type = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.bmp': 'image/bmp',
'.webp': 'image/webp'
}.get(ext, 'image/jpeg')
# 转换为base64
img_base64 = base64.b64encode(img_data).decode('utf-8')
data_url = f"data:{mime_type};base64,{img_base64}"
# 替换src属性,保持其他属性不变
updated_tag = re.sub(
r'src\s*=\s*["\'][^"\']+["\']',
f'src="{data_url}"',
full_tag
)
return updated_tag
else:
# 文件不存在,显示详细的错误信息
error_content = f"""