122345656878911101112131516171819201415161718192021222324262728293031252627282930373839403132333435443637383940495051525354414243444558464748495051525354606155565758636459606166676862636471726566747567686970787980818283847172867374757690919293949577979878798081828384100101102858687888910510610710810990919293941121131141151169596971191201211221231249899100101102126103104128105130131132133134135136137138139140141142143144145146147148149150106107108109110111112113114115152153154116117118119156157158159120121122161162163164165123124125126127128129130131132133134135136137167168169170171172173174175176177178179180181138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167183184185168169170171172188189190173174175176177178179180181182183184185186187192193188195196197189190191192193194195196197198199200201202203204205206207200201202203204205206207208209210208209210211212213214215216217212218219220215216221222223"""图表问答数据集审核系统 - Gradio 5.x 应用图表问答数据集审核系统 - Gradio 5.x 稳定版"""import gradio as grfrom data_manager import DataManager, data_managerfrom typing import Dict, List, Optional, Tuple, Anyfrom data_manager import data_manager # 假设你已经实例化了 data_managerimport jsonimport osimport base64from typing import Dict, List, Optional
# ============== 全局状态 ==============# ============== 全局状态管理 ==============
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 = -1 self.current_source = "" self.current_chart_type = "" self.current_chart_id = "" self.current_model = "" self.all_paths = [] self.current_index = -1 self.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 None def set_position(self, source: str, chart_type: str, chart_id: str, model: str): def set_position(self, source, chart_type, chart_id, model): self.current_source = source self.current_chart_type = chart_type self.current_chart_id = chart_id self.current_model = model for i, path in enumerate(self.all_paths): if (path['source'] == source and path['chart_type'] == chart_type and path['chart_id'] == chart_id and path['model'] == model): if (path['source'] == source and path['chart_type'] == chart_type and path['chart_id'] == chart_id and path['model'] == model): self.current_index = i break def navigate(self, direction: int) -> bool: def navigate(self, direction): new_index = self.current_index + direction if 0 <= new_index < len(self.all_paths): self.current_index = new_index path = 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 True return False return path['source'], path['chart_type'], path['chart_id'], path['model'] return None
state = AppState()
# ============== UI 更新函数 ==============# ============== 辅助逻辑 ==============
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>'
def update_chart_type_dropdown(source: str): state.current_source = source# ============== UI 事件处理 ==============
def on_source_change(source): structure = 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) types = list(structure.get('sources', {}).get(source, {}).get('chart_types', {}).keys()) return gr.update(choices=types, value=types[0] if types else None)
def update_chart_dropdown(source: str, chart_type: str): state.current_source = source state.current_chart_type = chart_typedef on_type_change(source, chart_type): charts = 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', []) models = structure.get('sources', {}).get(source, {}).get('chart_types', {}).get(chart_type, {}).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) gr.update(choices=charts, value=charts[0] if charts else None), gr.update(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):def load_data(source, chart_type, chart_id, model): if not all([source, chart_type, chart_id, model]): return [create_embedded_html(""), "### 请选择路径", "[]", "等待加载...", "请选择图表", "{}", gr.Radio(choices=[]), ""] 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) 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)} 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]) 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)] 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 [ 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}" 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 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="{}") with gr.Blocks(title="图表 QA 审核系统", theme=gr.themes.Default()) as app: # 隐藏状态存储 qa_store = gr.State("[]") review_store = gr.State("{}") gr.Markdown("# 📊 图表问答数据集审核系统") 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=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=4): # 右侧审核 with gr.Accordion("📝 元数据", open=False): label_display = gr.Markdown() with gr.Column(scale=1): stats_view = gr.Textbox(label="审核统计", interactive=False) progress_view = gr.Textbox(label="总进度", interactive=False) 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) with gr.Accordion("图表元数据", open=False): meta_view = gr.Markdown() 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="修改答案") 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") 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) 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 on_qa_select(sel, qa_json, rev_json): if not sel: return [""] * 8 qa_list = json.loads(qa_json) def switch_qa(sel, qa_json, rev_json): if not sel or qa_json == "[]": return [""] * 8 qas = json.loads(qa_json) revs = json.loads(rev_json) idx = int(sel.split(":")[0][1:]) - 1 qa = 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', '')] curr = 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] )
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) 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( 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]) 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 return app # 必须要 return app
if __name__ == "__main__": app = create_ui() app.launch(server_name="0.0.0.0", server_port=7860, show_api=False) 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