import io import re import streamlit as st import plotly.io as pio from utils.sanitize_code import sanitize_code import base64 def write_html(agents): report_agent = agents[-1] report_obj = report_agent.load_report() # Reportcore # 图像分析列表 analysis_list = agents[2].summary_fig_analysis_list() # 给 heading 加唯一 id heading_counter = {"count": 0} def _gen_id(text): heading_counter["count"] += 1 return f"sec-{heading_counter['count']}" # 遍历树 → 正文 & TOC toc_items, content_items = [], [] def _process_node(node): if node.type == "heading": sec_id = _gen_id(node.text) toc_items.append((sec_id, node.text, node.level)) content_items.append( f"{node.text}" ) for ch in node.children: _process_node(ch) elif node.type == "paragraph": parts = re.split(r'(\[FIG:\d+\])', node.text) html_parts = [] for part in parts: part = part.strip() if not part: continue if part.startswith("[FIG:") and part.endswith("]"): idx = int(part[5:-1]) fig_html = "" if 0 <= idx < len(analysis_list): fig_obj = analysis_list[idx].get("figure") try: buf = io.BytesIO() pio.write_image(fig_obj, buf, format="png") data = buf.getvalue() b64 = base64.b64encode(data).decode("utf-8") fig_html = f"
" except Exception as e: fig_html = f"

[图像插入失败: {e}]

" html_parts.append(fig_html) else: html_parts.append(f"

{part}

") content_items.append("".join(html_parts)) else: # root for ch in node.children: _process_node(ch) _process_node(report_obj.root) # TOC HTML toc_html = ["") # 拼接完整 HTML html_content = f"""
{''.join(content_items)}
""" report_agent.save_html(html_content) st.success("HTML 报告 (Tailwind 风格) 生成成功 ✅")