123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216"""图表问答数据集审核系统 - Gradio 5.x 应用"""import gradio as grfrom data_manager import DataManager, data_managerfrom typing import Dict, List, Optional, Tuple, Anyimport jsonimport osimport base64# ============== 全局状态 ==============class AppState:def __init__(self):self.current_source: str = ""self.current_chart_type: str = ""self.current_chart_id: str = ""self.current_model: str = ""self.all_paths: List[Dict] = []self.current_index: int = -1self.refresh_paths()def refresh_paths(self):self.all_paths = data_manager.get_all_chart_paths()def get_current_path(self) -> Optional[Dict]:if 0 <= self.current_index < len(self.all_paths):return self.all_paths[self.current_index]return Nonedef set_position(self, source: str, chart_type: str, chart_id: str, model: str):self.current_source = sourceself.current_chart_type = chart_typeself.current_chart_id = chart_idself.current_model = modelfor i, path in enumerate(self.all_paths):if (path['source'] == source andpath['chart_type'] == chart_type andpath['chart_id'] == chart_id andpath['model'] == model):self.current_index = ibreakdef navigate(self, direction: int) -> bool:new_index = self.current_index + directionif 0 <= new_index < len(self.all_paths):self.current_index = new_indexpath = self.all_paths[new_index]self.current_source = path['source']self.current_chart_type = path['chart_type']self.current_chart_id = path['chart_id']self.current_model = path['model']return Truereturn Falsestate = AppState()# ============== UI 更新函数 ==============def update_chart_type_dropdown(source: str):state.current_source = sourcestructure = data_manager.get_dataset_structure()chart_types = list(structure.get('sources', {}).get(source, {}).get('chart_types', {}).keys())return gr.Dropdown(choices=chart_types, value=chart_types[0] if chart_types else None)def update_chart_dropdown(source: str, chart_type: str):state.current_source = sourcestate.current_chart_type = chart_typecharts = data_manager.get_chart_list(source, chart_type)structure = data_manager.get_dataset_structure()ct_data = structure.get('sources', {}).get(source, {}).get('chart_types', {}).get(chart_type, {})models = ct_data.get('models', [])return (gr.Dropdown(choices=charts, value=charts[0] if charts else None),gr.Dropdown(choices=models, value=models[0] if models else None))def create_embedded_html(html_content: str, chart_id: str = "") -> str:if not html_content:return f'<div style="display:flex;min-height:750px;align-items:center;justify-content:center;background:#fafafa;border:2px dashed #ddd;">暂无图表内��� (ID: {chart_id})</div>'html_base64 = base64.b64encode(html_content.encode('utf-8')).decode('utf-8')return f'<iframe src="data:text/html;base64,{html_base64}" style="width:100%;height:750px;border:1px solid #e0e0e0;background:#fff;" sandbox="allow-scripts allow-same-origin"></iframe>'def load_chart_data(source: str, chart_type: str, chart_id: str, model: str):if not all([source, chart_type, chart_id, model]):return [create_embedded_html(""), "### 请选择路径", "[]", "等待加载...", "请选择图表", "{}", gr.Radio(choices=[]), ""]state.set_position(source, chart_type, chart_id, model)chart_data = data_manager.get_chart_data(source, chart_type, chart_id)html_content = chart_data.get('html_content', '')label_info = chart_data.get('label_info', {})embedded_html = create_embedded_html(html_content, chart_id)label_text = f"| 属性 | 值 |\n|---|---|\n" + "\n".join([f"| **{k}** | {v} |" for k, v in label_info.items()])qa_list = data_manager.get_qa_list(source, chart_type, model, chart_id)existing_reviews = {r['qa_id']: r for r in data_manager.get_reviews_by_chart(chart_id, model)}stats = data_manager.get_review_stats()status_msg = f"已审核: {stats['total']} | ✅正确: {stats['correct']} | ❌错误: {stats['incorrect']}"progress_msg = f"进度: {state.current_index + 1} / {len(state.all_paths)}"qa_choices = [f"Q{i+1}: {qa.question[:40]}..." for i, qa in enumerate(qa_list)]return [embedded_html, label_text,json.dumps([{"id": qa.id, "question": qa.question, "answer": qa.answer} for qa in qa_list]),status_msg, progress_msg, json.dumps(existing_reviews),gr.Radio(choices=qa_choices, value=qa_choices[0] if qa_choices else None),f"Path: {source}/{chart_type}/{chart_id}"]def export_reviews_handler():output_path = data_manager.export_reviews("./reviews_export.json")return gr.update(value=output_path, visible=True)# ============== 创建 Gradio 界面 ==============def create_ui():custom_css = ".chart-container { min-height: 750px; } .nav-row { background: #f8f9fa; padding: 10px; border-radius: 8px; }"with gr.Blocks(title="图表问答数据集审核系统", theme=gr.themes.Soft(), css=custom_css) as app:# 内部状态qa_data_json = gr.State(value="[]")current_reviews_json = gr.State(value="{}")gr.Markdown("# 📊 图表问答数据集审核系统")# 顶部导航with gr.Row():status_text = gr.Textbox(label="统计", interactive=False, scale=2)progress_text = gr.Textbox(label="进度", interactive=False, scale=1)with gr.Row(elem_classes=["nav-row"]):source_drop = gr.Dropdown(label="数据来源", choices=[], allow_custom_value=True)type_drop = gr.Dropdown(label="图表类型", choices=[], allow_custom_value=True)id_drop = gr.Dropdown(label="图表 ID", choices=[], allow_custom_value=True)model_drop = gr.Dropdown(label="模型", choices=[], allow_custom_value=True)reviewer = gr.Textbox(label="审核人", value="admin")with gr.Row():prev_btn = gr.Button("⬅️ 上一个")next_btn = gr.Button("➡️ 下一个")export_btn = gr.Button("📦 导出记录", variant="secondary")download_file = gr.File(label="下载导出的 JSON", visible=False)# 主体:左右排版with gr.Row():with gr.Column(scale=6): # 左侧图表html_display = gr.HTML(elem_classes=["chart-container"])debug_info = gr.Markdown()with gr.Column(scale=4): # 右侧审核with gr.Accordion("📝 元数据", open=False):label_display = gr.Markdown()qa_selector = gr.Radio(label="选择问答对")current_qa_id = gr.Textbox(visible=False)orig_q = gr.Textbox(label="原始问题", interactive=False, lines=2)orig_a = gr.Textbox(label="原始答案", interactive=False)gr.Markdown("---")status_radio = gr.Radio(label="判定结果", choices=[("✅ 正确", "correct"), ("❌ 错误", "incorrect"), ("✏️ 需修改", "needs_modification")], value="correct")issue_type = gr.Dropdown(label="错误类型", choices=["答案错误", "问题模糊", "图文不符", "其他"])mod_q = gr.Textbox(label="修改问题", lines=2)mod_a = gr.Textbox(label="修改答案")comment = gr.Textbox(label="备注")save_btn = gr.Button("💾 保存当前审核", variant="primary")save_msg = gr.Textbox(label="系统提示", visible=False)# --- 事件绑定 ---def init_dataset():s = list(data_manager.get_dataset_structure().get('sources', {}).keys())return gr.update(choices=s, value=s[0] if s else None)app.load(fn=init_dataset, outputs=[source_drop])source_drop.change(fn=update_chart_type_dropdown, inputs=[source_drop], outputs=[type_drop])type_drop.change(fn=update_chart_dropdown, inputs=[source_drop, type_drop], outputs=[id_drop, model_drop])load_args = dict(fn=load_chart_data, inputs=[source_drop, type_drop, id_drop, model_drop], outputs=[html_display, label_display, qa_data_json, status_text, progress_text, current_reviews_json, qa_selector, debug_info])id_drop.change(**load_args)model_drop.change(**load_args)def on_qa_select(sel, qa_json, rev_json):if not sel: return [""] * 8qa_list = json.loads(qa_json)revs = json.loads(rev_json)idx = int(sel.split(":")[0][1:]) - 1qa = qa_list[idx]r = revs.get(qa['id'], {})return [qa['id'], qa['question'], qa['answer'], r.get('status', 'correct'), r.get('issue_type', ''), r.get('modified_question', ''), r.get('modified_answer', ''), r.get('comment', '')]qa_selector.change(fn=on_qa_select, inputs=[qa_selector, qa_data_json, current_reviews_json], outputs=[current_qa_id, orig_q, orig_a, status_radio, issue_type, mod_q, mod_a, comment])# 导航nav_out = [source_drop, type_drop, id_drop, model_drop]prev_btn.click(fn=lambda: (state.navigate(-1), *[gr.update(value=v) for v in [state.current_source, state.current_chart_type, state.current_chart_id, state.current_model]])[1:], outputs=nav_out)next_btn.click(fn=lambda: (state.navigate(1), *[gr.update(value=v) for v in [state.current_source, state.current_chart_type, state.current_chart_id, state.current_model]])[1:], outputs=nav_out)save_btn.click(fn=lambda *args: (data_manager.save_review({"qa_id": args[0], "chart_id": args[1], "source": args[2], "chart_type": args[3], "model": args[4],"original_question": args[5], "original_answer": args[6], "status": args[7],"modified_question": args[8], "modified_answer": args[9], "issue_type": args[10],"comment": args[11], "reviewer": args[12]}), "✅ 已保存记录")[1],inputs=[current_qa_id, id_drop, source_drop, type_drop, model_drop, orig_q, orig_a, status_radio, mod_q, mod_a, issue_type, comment, reviewer],outputs=[save_msg]).then(fn=lambda: gr.update(visible=True), outputs=[save_msg])export_btn.click(fn=export_reviews_handler, outputs=[download_file])return app # <--- 关键点:确保在这里 returnif __name__ == "__main__":app = create_ui()app.launch(server_name="0.0.0.0", server_port=7860, show_api=False)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""图表问答数据集审核系统 - Gradio 5.x 稳定版"""import gradio as grfrom data_manager import data_manager # 假设你已经实例化了 data_managerimport jsonimport base64from typing import Dict, List, Optional# ============== 全局状态管理 ==============class AppState:def __init__(self):self.current_source = ""self.current_chart_type = ""self.current_chart_id = ""self.current_model = ""self.all_paths = []self.current_index = -1self.refresh_paths()def refresh_paths(self):self.all_paths = data_manager.get_all_chart_paths()def set_position(self, source, chart_type, chart_id, model):self.current_source = sourceself.current_chart_type = chart_typeself.current_chart_id = chart_idself.current_model = modelfor i, path in enumerate(self.all_paths):if (path['source'] == source and path['chart_type'] == chart_type andpath['chart_id'] == chart_id and path['model'] == model):self.current_index = ibreakdef navigate(self, direction):new_index = self.current_index + directionif 0 <= new_index < len(self.all_paths):self.current_index = new_indexpath = self.all_paths[new_index]return path['source'], path['chart_type'], path['chart_id'], path['model']return Nonestate = AppState()# ============== 辅助逻辑 ==============def create_embedded_html(html_content: str) -> str:if not html_content:return '<div style="height:600px;display:flex;align-items:center;justify-content:center;background:#eee;">请选择图表进行加载</div>'# 使用 Base64 嵌入以避免跨域和字符编码问题html_base64 = base64.b64encode(html_content.encode('utf-8')).decode('utf-8')return f'<iframe src="data:text/html;base64,{html_base64}" style="width:100%;height:700px;border:none;background:white;"></iframe>'# ============== UI 事件处理 ==============def on_source_change(source):structure = data_manager.get_dataset_structure()types = list(structure.get('sources', {}).get(source, {}).get('chart_types', {}).keys())return gr.update(choices=types, value=types[0] if types else None)def on_type_change(source, chart_type):charts = data_manager.get_chart_list(source, chart_type)structure = data_manager.get_dataset_structure()models = structure.get('sources', {}).get(source, {}).get('chart_types', {}).get(chart_type, {}).get('models', [])return (gr.update(choices=charts, value=charts[0] if charts else None),gr.update(choices=models, value=models[0] if models else None))def load_data(source, chart_type, chart_id, model):if not all([source, chart_type, chart_id, model]):return ["", "", "[]", "等待选择...", "0/0", "{}", gr.update(choices=[]), "未选择"]state.set_position(source, chart_type, chart_id, model)chart_data = data_manager.get_chart_data(source, chart_type, chart_id)qa_list = data_manager.get_qa_list(source, chart_type, model, chart_id)reviews = {r['qa_id']: r for r in data_manager.get_reviews_by_chart(chart_id, model)}stats = data_manager.get_review_stats()# 构造返回值html_frame = create_embedded_html(chart_data.get('html_content', ''))label_md = "\n".join([f"- **{k}**: {v}" for k, v in chart_data.get('label_info', {}).items()])qa_json = json.dumps([{"id": q.id, "question": q.question, "answer": q.answer} for q in qa_list])stats_msg = f"✅{stats['correct']} | ❌{stats['incorrect']} | 总{stats['total']}"progress_msg = f"{state.current_index + 1} / {len(state.all_paths)}"qa_choices = [f"Q{i+1}: {q.question[:30]}..." for i, q in enumerate(qa_list)]return [html_frame, label_md, qa_json, stats_msg, progress_msg,json.dumps(reviews), gr.update(choices=qa_choices, value=qa_choices[0] if qa_choices else None),f"{source}/{chart_type}/{chart_id}"]# ============== 界面构建 ==============def create_ui():with gr.Blocks(title="图表 QA 审核系统", theme=gr.themes.Default()) as app:# 隐藏状态存储qa_store = gr.State("[]")review_store = gr.State("{}")gr.Markdown("# 📊 图表问答数据集审核")with gr.Row():with gr.Column(scale=3):with gr.Row():source_drop = gr.Dropdown(label="数据源", choices=[], allow_custom_value=True)type_drop = gr.Dropdown(label="类型", choices=[], allow_custom_value=True)id_drop = gr.Dropdown(label="图表 ID", choices=[], allow_custom_value=True)model_drop = gr.Dropdown(label="模型", choices=[], allow_custom_value=True)html_view = gr.HTML()path_display = gr.Text(label="当前路径", interactive=False)with gr.Column(scale=1):stats_view = gr.Textbox(label="审核统计", interactive=False)progress_view = gr.Textbox(label="总进度", interactive=False)with gr.Accordion("图表元数据", open=False):meta_view = gr.Markdown()gr.Markdown("### 审核区")qa_select = gr.Radio(label="选择题目", choices=[])curr_qa_id = gr.Text(visible=False)q_text = gr.Textbox(label="问题", interactive=False, lines=2)a_text = gr.Textbox(label="答案", interactive=False)status_radio = gr.Radio(label="判定",choices=[("正确", "correct"), ("错误", "incorrect"), ("改后通过", "modified")],value="correct")issue_type = gr.Dropdown(label="错误类型", choices=["无", "答案错误", "问题模糊", "图表读取失败"])mod_q = gr.Textbox(label="修改问题(选填)")mod_a = gr.Textbox(label="修改答案(选填)")comment = gr.Textbox(label="备注")save_btn = gr.Button("💾 保存审核", variant="primary")with gr.Row():prev_btn = gr.Button("⬅️ 上一个")next_btn = gr.Button("➡️ 下一个")export_btn = gr.Button("📦 导出 JSON")download_file = gr.File(label="下载地址", visible=False)# --- 交互绑定 ---# 初始化def init_ui():structure = data_manager.get_dataset_structure()sources = list(structure.get('sources', {}).keys())return gr.update(choices=sources, value=sources[0] if sources else None)app.load(init_ui, outputs=[source_drop])# 联动逻辑source_drop.change(on_source_change, inputs=[source_drop], outputs=[type_drop])type_drop.change(on_type_change, inputs=[source_drop, type_drop], outputs=[id_drop, model_drop])# 加载数据load_inputs = [source_drop, type_drop, id_drop, model_drop]load_outputs = [html_view, meta_view, qa_store, stats_view, progress_view, review_store, qa_select, path_display]id_drop.change(load_data, inputs=load_inputs, outputs=load_outputs)model_drop.change(load_data, inputs=load_inputs, outputs=load_outputs)# 题目切换def switch_qa(sel, qa_json, rev_json):if not sel or qa_json == "[]": return [""] * 8qas = json.loads(qa_json)revs = json.loads(rev_json)idx = int(sel.split(":")[0][1:]) - 1curr = qas[idx]r = revs.get(curr['id'], {})return [curr['id'], curr['question'], curr['answer'],r.get('status', 'correct'), r.get('issue_type', '无'),r.get('modified_question', ''), r.get('modified_answer', ''),r.get('comment', '')]qa_select.change(switch_qa,inputs=[qa_select, qa_store, review_store],outputs=[curr_qa_id, q_text, a_text, status_radio, issue_type, mod_q, mod_a, comment])# 导航def nav(direction):res = state.navigate(direction)if res:return [gr.update(value=v) for v in res]return [gr.update() for _ in range(4)]prev_btn.click(lambda: nav(-1), outputs=load_inputs)next_btn.click(lambda: nav(1), outputs=load_inputs)# 保存def save_handler(q_id, c_id, src, tp, mdl, o_q, o_a, stat, m_q, m_a, it, cmt):data_manager.save_review({"qa_id": q_id, "chart_id": c_id, "source": src, "chart_type": tp, "model": mdl,"original_question": o_q, "original_answer": o_a, "status": stat,"modified_question": m_q, "modified_answer": m_a, "issue_type": it, "comment": cmt})return "已保存"save_btn.click(save_handler,inputs=[curr_qa_id, id_drop, source_drop, type_drop, model_drop, q_text, a_text, status_radio, mod_q, mod_a, issue_type, comment],outputs=[gr.Textbox(visible=False)] # 仅触发)export_btn.click(fn=lambda: gr.update(value=data_manager.export_reviews(), visible=True),outputs=[download_file])return app # 必须要 return appif __name__ == "__main__":demo = create_ui()# show_api=False 是解决那个 TypeError 的关键demo.launch(server_name="0.0.0.0", server_port=7860, show_api=False)
app.py+157-150