7 unmodified lines89101112131437 unmodified lines5253545556575 unmodified lines636465666768697071727374757677787980818283848586878889907 unmodified lines98991001011021031041051061071081 unmodified line11011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215 unmodified lines1681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992006 unmodified lines2072082092102112122132144 unmodified lines21922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025129 unmodified lines2812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123131 unmodified line31531631731831932032132232311 unmodified lines3353363373383393403413423433443453463472 unmodified lines3503513523533543554 unmodified lines3603613623633643653663673683693703713 unmodified lines37537637737837938038127 unmodified lines4094104114124134144154164174184194204 unmodified lines4254264274284294301 unmodified line43243343443543643743843944044144244344444544644744844945079 unmodified lines53053153253353453553627 unmodified lines5645655665675685695705711 unmodified line57357457557657757857958058158258358458558658758858959059132 unmodified lines6246256266276286296306316326336346356366 unmodified lines6436446456466477 unmodified linesimport jsonimport osimport base64import tempfile# ============== 全局状态 ==============37 unmodified linesbreakdef navigate(self, direction: int) -> bool:new_index = self.current_index + directionif 0 <= new_index < len(self.all_paths):self.current_index = new_index5 unmodified linesreturn Truereturn False# 全局状态实例app_state = AppState()# 全局变量存储当前 QA 数据和审核记录current_qa_data = []current_reviews_data = {}# ============== UI 更新函数 ==============def update_chart_type_dropdown(source: str):"""更新图表类型下拉框"""app_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):"""更新图表和模型下拉框"""app_state.current_source = sourceapp_state.current_chart_type = chart_typecharts = data_manager.get_chart_list(source, chart_type)structure = data_manager.get_dataset_structure()7 unmodified linesdef create_embedded_html(html_content: str, chart_id: str = "") -> str:"""创建嵌入式的 HTML 显示"""if not html_content:return f"""<div style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:500px;color:#999;border:2px dashed #ddd;border-radius:12px;background:#fafafa;"><div style="font-size:48px;margin-bottom:16px;">📭</div><div style="font-size:18px;font-weight:500;">暂无图表内容</div><div style="font-size:14px;margin-top:8px;">图表 ID: {chart_id or '未知'}</div>1 unmodified line</div>"""html_bytes = html_content.encode('utf-8')html_base64 = base64.b64encode(html_bytes).decode('utf-8')return f"""<iframesrc="data:text/html;base64,{html_base64}"style="width:100%;height:650px;border:1px solid #e0e0e0;border-radius:8px;background:#fff;"sandbox="allow-scripts allow-same-origin"loading="lazy"></iframe>"""def load_chart_data(source: str, chart_type: str, chart_id: str, model: str):"""加载图表数据"""global current_qa_data, current_reviews_dataif not all([source, chart_type, chart_id, model]):current_qa_data = []current_reviews_data = {}return [create_embedded_html(""),"### 请在左侧选择图表","等待加载数据...","请在左侧选择图表",gr.Radio(choices=[], value=None),""]app_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)debug_info = f"📁 {source}/{chart_type}/{chart_id} | HTML: {len(html_content)} 字符"# 格式化标签信息15 unmodified lines# 获取 QA 列表qa_list = data_manager.get_qa_list(source, chart_type, model, chart_id)current_qa_data = [{"id": qa.id, "question": qa.question, "answer": qa.answer} for qa in qa_list]# 获取已有的审核记录current_reviews_data = {}for review in data_manager.get_reviews_by_chart(chart_id, model):current_reviews_data[review['qa_id']] = reviewprogress_text = f"当前: {app_state.current_index + 1} / {len(app_state.all_paths)} 个图表"stats = data_manager.get_review_stats()status_text = f"已审核: {stats['total']} | ✅正确: {stats['correct']} | ❌错误: {stats['incorrect']} | ✏️需修改: {stats['needs_modification']}"qa_choices = [f"Q{i+1}: {qa.question[:50]}..." for i, qa in enumerate(qa_list)] if qa_list else []return [embedded_html,label_text,status_text,progress_text,gr.Radio(choices=qa_choices, value=qa_choices[0] if qa_choices else None),debug_info]def navigate_prev():"""导航到上一个图表"""if app_state.navigate(-1):path = app_state.get_current_path()if path:return (gr.Dropdown(value=path['source']),6 unmodified linesdef navigate_next():"""导航到下一个图表"""if app_state.navigate(1):path = app_state.get_current_path()if path:return (gr.Dropdown(value=path['source']),4 unmodified linesreturn [gr.Dropdown(), gr.Dropdown(), gr.Dropdown(), gr.Dropdown()]def on_qa_selected(qa_index_str: str):"""QA 选择器变化时更新审核面板"""global current_qa_data, current_reviews_dataif not qa_index_str or not current_qa_data:return ["", "", gr.Radio(value="pending"), "", "", "", ""]try:index = int(qa_index_str.split(":")[0].replace("Q", "")) - 1qa = current_qa_data[index]review = current_reviews_data.get(qa['id'], {})return [qa['id'],qa['question'],qa['answer'],gr.Radio(value=review.get('status', 'pending')),review.get('issue_type', ''),review.get('modified_question', ''),review.get('modified_answer', ''),review.get('comment', '')]except Exception as e:print(f"Error in on_qa_selected: {e}")return ["", "", gr.Radio(value="pending"), "", "", "", ""]def save_review_handler(qa_id: str,chart_id: str,29 unmodified lines"reviewer": reviewer}data_manager.save_review(review_data)# 更新全局审核数据global current_reviews_datacurrent_reviews_data[qa_id] = review_datastats = data_manager.get_review_stats()return f"✅ 已保存! 总计: {stats['total']} | ✅正确: {stats['correct']} | ❌错误: {stats['incorrect']} | ✏️需修改: {stats['needs_modification']}"def export_reviews_handler():"""导出审核记录并返回文件路径供下载"""reviews = data_manager.get_all_reviews()if not reviews:return None, "❌ 暂无审核记录可导出"temp_dir = tempfile.gettempdir()output_path = os.path.join(temp_dir, "reviews_export.json")with open(output_path, 'w', encoding='utf-8') as f:json.dump(reviews, f, ensure_ascii=False, indent=2)stats = data_manager.get_review_stats()summary = f"✅ 导出成功!共 {len(reviews)} 条记录"return output_path, summary# ============== 创建 Gradio 界面 ==============1 unmodified linedef create_ui():"""创建 Gradio 界面"""custom_css = """.chart-container {min-height: 680px;}.control-panel {11 unmodified linesborder-radius: 4px;margin-top: 10px;}.export-section {background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);padding: 15px;border-radius: 8px;margin-top: 15px;}"""with gr.Blocks(2 unmodified linescss=custom_css) as app:# ==================== 标题栏 ====================gr.Markdown("""# 📊 图表问答数据集审核系统4 unmodified lines# ==================== 顶部状态栏 ====================with gr.Row():status_text = gr.Textbox(value="等待加载数据...",interactive=False,show_label=False,scale=2)progress_text = gr.Textbox(value="请在左侧选择图表",interactive=False,show_label=False,3 unmodified lines# ==================== 主内容区 ====================with gr.Row():# ===== 左侧:导航控制 =====with gr.Column(scale=1, min_width=280):gr.Markdown("### 📁 数据选择")source_dropdown = gr.Dropdown(27 unmodified linesprev_btn = gr.Button("⬅️ 上一个")next_btn = gr.Button("➡️ 下一个")# 导出区域gr.Markdown("### 📥 导出审核结果")with gr.Column(elem_classes=["export-section"]):export_btn = gr.Button("📤 生成导出文件", variant="secondary", size="sm")export_status = gr.Textbox(value="", interactive=False, show_label=False)download_file = gr.File(label="📥 点击下载", visible=False)# 审核人设置reviewer_input = gr.Textbox(4 unmodified lines# 调试信息debug_info = gr.Textbox(value="",interactive=False,show_label=False,1 unmodified line)# ===== 中间:图表展示 =====with gr.Column(scale=3, min_width=500):gr.Markdown("### 📈 图表展示")html_display = gr.HTML(value="<div style='text-align:center;padding:100px;color:#999;'>请选择图表</div>",elem_classes=["chart-container"])# ===== 右侧:标签信息和 QA 审核 =====with gr.Column(scale=2, min_width=400):gr.Markdown("### 📝 图表标签")label_display = gr.Markdown(value="暂无信息", elem_classes=["control-panel"])gr.Markdown("### ❓ 问答审核")# 当前选中的 QA 信息(隐藏)79 unmodified lines# 保存按钮save_btn = gr.Button("💾 保存审核结果", variant="primary")save_result = gr.Textbox(value="", visible=False)# ==================== 事件绑定 ====================27 unmodified linesfn=load_chart_data,inputs=[source_dropdown, chart_type_dropdown, chart_dropdown, model_dropdown],outputs=[html_display, label_display, status_text, progress_text,qa_selector, debug_info])1 unmodified linefn=load_chart_data,inputs=[source_dropdown, chart_type_dropdown, chart_dropdown, model_dropdown],outputs=[html_display, label_display, status_text, progress_text,qa_selector, debug_info])# QA 选择器变化 -> 更新审核面板qa_selector.change(fn=on_qa_selected,inputs=[qa_selector],outputs=[current_qa_id, qa_question_display, qa_answer_display,status_radio, issue_type_dropdown, modified_question,modified_answer, comment_textbox])32 unmodified linesoutputs=[save_result])# 导出审核记录export_btn.click(fn=export_reviews_handler,outputs=[download_file, export_status]).then(fn=lambda: gr.File(visible=True),outputs=[download_file])return app6 unmodified linesapp.launch(server_name="0.0.0.0",server_port=7860,share=False)7 unmodified lines891011121337 unmodified lines5152535455565758596061626364655 unmodified lines71727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161177 unmodified lines1251261271281291301311321331341351361371381391 unmodified line14114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319415 unmodified lines2102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462476 unmodified lines2542552562572582592602614 unmodified lines26626726826927027129 unmodified lines3013023033043053063073083093103113123133143153163171 unmodified line31932032132232332432532632732811 unmodified lines3403413423433443452 unmodified lines3483493503513523533543553563574 unmodified lines3623633643653663673683693703713723733743753 unmodified lines37938038138238338438527 unmodified lines4134144154164174184194204214 unmodified lines4264274284294304314321 unmodified line43443543643743843944044144244344444544644744844945045145245345445545645745879 unmodified lines53853954054154254354427 unmodified lines5725735745755765775785791 unmodified line58158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662732 unmodified lines6606616626636646656666676686696706716726 unmodified lines6796806816826837 unmodified linesimport jsonimport osimport base64# ============== 全局状态 ==============37 unmodified linesbreakdef navigate(self, direction: int) -> bool:"""导航到上一个或下一个图表Args:direction: 1 表示下一个,-1 表示上一个Returns:是否成功导航"""new_index = self.current_index + directionif 0 <= new_index < len(self.all_paths):self.current_index = new_index5 unmodified linesreturn Truereturn Falsestate = AppState()# ============== UI 更新函数 ==============def get_dataset_choices() -> Tuple[List[str], List[str], List[str], List[str]]:"""获取数据集的选择项"""structure = data_manager.get_dataset_structure()sources = list(structure.get('sources', {}).keys())chart_types = []charts = []models = []if state.current_source:source_data = structure['sources'].get(state.current_source, {})chart_types = list(source_data.get('chart_types', {}).keys())if state.current_chart_type:charts = data_manager.get_chart_list(state.current_source, state.current_chart_type)ct_data = source_data.get('chart_types', {}).get(state.current_chart_type, {})models = ct_data.get('models', [])return sources, chart_types, charts, modelsdef 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()7 unmodified linesdef create_embedded_html(html_content: str, chart_id: str = "") -> str:"""创建嵌入式的 HTML 显示使用 data URI 方式嵌入 HTML 内容到 iframe 中"""if not html_content:return f"""<div style="display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:400px;color:#999;border:2px dashed #ddd;border-radius:12px;background:#fafafa;"><div style="font-size:48px;margin-bottom:16px;">📭</div><div style="font-size:18px;font-weight:500;">暂无图表内容</div><div style="font-size:14px;margin-top:8px;">图表 ID: {chart_id or '未知'}</div>1 unmodified line</div>"""# 使用 base64 编码 HTML 内容,避免引号转义问题html_bytes = html_content.encode('utf-8')html_base64 = base64.b64encode(html_bytes).decode('utf-8')# 使用 data URIiframe_html = f"""<iframesrc="data:text/html;base64,{html_base64}"style="width:100%;height:500px;border:1px solid #e0e0e0;border-radius:8px;background:#fff;"sandbox="allow-scripts allow-same-origin"loading="lazy"></iframe>"""return iframe_htmldef load_chart_data(source: str, chart_type: str, chart_id: str, model: str):"""加载图表数据并返回所有 UI 更新Returns:包含所有 UI 组件更新值的元组"""if not all([source, chart_type, chart_id, model]):return [create_embedded_html(""), # html_display"### 请在左侧选择图表", # label_info"[]", # qa_data (JSON string)"等待加载数据...", # status_text"请在左侧选择图表", # progress_text"{}", # current_qa_reviews (JSON string)gr.Radio(choices=[], value=None), # qa_selector"" # debug_info]# 更新状态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', {})# 创建嵌入式 HTMLembedded_html = create_embedded_html(html_content, chart_id)# 调试信息debug_info = f"📁 {source}/{chart_type}/{chart_id} | HTML: {len(html_content)} 字符"# 格式化标签信息15 unmodified lines# 获取 QA 列表qa_list = data_manager.get_qa_list(source, chart_type, model, chart_id)# 获取已有的审核记录existing_reviews = {}for review in data_manager.get_reviews_by_chart(chart_id, model):existing_reviews[review['qa_id']] = review# 更新进度文本progress_text = f"当前: {state.current_index + 1} / {len(state.all_paths)} 个图表"# 状态文本stats = data_manager.get_review_stats()status_text = f"已审核: {stats['total']} | ✅正确: {stats['correct']} | ❌错误: {stats['incorrect']} | ✏️需修改: {stats['needs_modification']}"# QA 选择器选项qa_choices = [f"Q{i+1}: {qa.question[:50]}..." for i, qa in enumerate(qa_list)] if qa_list else []return [embedded_html, # html_displaylabel_text, # label_infojson.dumps([{"id": qa.id, "question": qa.question, "answer": qa.answer} for qa in qa_list]), # qa_data (JSON string)status_text, # status_textprogress_text, # progress_textjson.dumps(existing_reviews), # current_qa_reviews (JSON string)gr.Radio(choices=qa_choices, value=qa_choices[0] if qa_choices else None), # qa_selectordebug_info # debug_info]def navigate_prev():"""导航到上一个图表"""if state.navigate(-1):path = state.get_current_path()if path:return (gr.Dropdown(value=path['source']),6 unmodified linesdef navigate_next():"""导航到下一个图表"""if state.navigate(1):path = state.get_current_path()if path:return (gr.Dropdown(value=path['source']),4 unmodified linesreturn [gr.Dropdown(), gr.Dropdown(), gr.Dropdown(), gr.Dropdown()]def save_review_handler(qa_id: str,chart_id: str,29 unmodified lines"reviewer": reviewer}result = data_manager.save_review(review_data)# 返回更新后的统计stats = data_manager.get_review_stats()return f"✅ 已保存! 总计: {stats['total']} | ✅正确: {stats['correct']} | ❌错误: {stats['incorrect']} | ✏️需修改: {stats['needs_modification']}"def export_reviews_handler():"""导出审核记录"""output_path = data_manager.export_reviews("./reviews_export.json")return f"✅ 审核记录已导出至: {output_path}"# ============== 创建 Gradio 界面 ==============1 unmodified linedef create_ui():"""创建 Gradio 界面"""# 自定义 CSScustom_css = """.chart-container {min-height: 520px;}.control-panel {11 unmodified linesborder-radius: 4px;margin-top: 10px;}"""with gr.Blocks(2 unmodified linescss=custom_css) as app:# 隐藏的状态存储(使用 JSON 字符串)qa_data_json = gr.State(value="[]")current_reviews_json = gr.State(value="{}")# ==================== 标题栏 ====================gr.Markdown("""# 📊 图表问答数据集审核系统4 unmodified lines# ==================== 顶部状态栏 ====================with gr.Row():status_text = gr.Textbox(label="审核统计",value="等待加载数据...",interactive=False,show_label=False,scale=2)progress_text = gr.Textbox(label="进度",value="请在左侧选择图表",interactive=False,show_label=False,3 unmodified lines# ==================== 主内容区 ====================with gr.Row():# ===== 左侧:导航控制 =====with gr.Column(scale=1, min_width=250):gr.Markdown("### 📁 数据选择")source_dropdown = gr.Dropdown(27 unmodified linesprev_btn = gr.Button("⬅️ 上一个")next_btn = gr.Button("➡️ 下一个")# 导出按钮export_btn = gr.Button("📥 导出审核记录", variant="secondary")export_result = gr.Textbox(label="", visible=False)# 审核人设置reviewer_input = gr.Textbox(4 unmodified lines# 调试信息debug_info = gr.Textbox(label="调试信息",value="",interactive=False,show_label=False,1 unmodified line)# ===== 中间:图表展示 =====with gr.Column(scale=2, min_width=400):gr.Markdown("### 📈 图表展示")# HTML 图表展示(使用 iframe)html_display = gr.HTML(value="<div style='text-align:center;padding:50px;color:#999;'>请选择图表</div>",elem_classes=["chart-container"])# ===== 右侧:标签信息和 QA 审核 =====with gr.Column(scale=2, min_width=400):# 标签信息gr.Markdown("### 📝 图表标签")label_display = gr.Markdown(value="暂无信息",elem_classes=["control-panel"])# QA 审核区gr.Markdown("### ❓ 问答审核")# 当前选中的 QA 信息(隐藏)79 unmodified lines# 保存按钮save_btn = gr.Button("💾 保存审核结果", variant="primary")save_result = gr.Textbox(label="", visible=False)# ==================== 事件绑定 ====================27 unmodified linesfn=load_chart_data,inputs=[source_dropdown, chart_type_dropdown, chart_dropdown, model_dropdown],outputs=[html_display, label_display, qa_data_json, status_text, progress_text,current_reviews_json, qa_selector, debug_info])1 unmodified linefn=load_chart_data,inputs=[source_dropdown, chart_type_dropdown, chart_dropdown, model_dropdown],outputs=[html_display, label_display, qa_data_json, status_text, progress_text,current_reviews_json, qa_selector, debug_info])# QA 选择器变化 -> 更新审核面板def on_qa_selected(qa_index_str, qa_json, reviews_json):if not qa_index_str or not qa_json:return ["", "", "", gr.Radio(value="pending"), "", "", "", ""]try:qa_list = json.loads(qa_json)reviews = json.loads(reviews_json)# 解析索引index = int(qa_index_str.split(":")[0].replace("Q", "")) - 1qa = qa_list[index]# 检查是否有现有审核review = reviews.get(qa['id'], {})return [qa['id'], # current_qa_idqa['question'], # qa_question_displayqa['answer'], # qa_answer_displaygr.Radio(value=review.get('status', 'pending')), # status_radioreview.get('issue_type', ''), # issue_type_dropdownreview.get('modified_question', ''), # modified_questionreview.get('modified_answer', ''), # modified_answerreview.get('comment', '') # comment_textbox]except Exception as e:print(f"Error in on_qa_selected: {e}")return ["", "", "", gr.Radio(value="pending"), "", "", "", ""]qa_selector.change(fn=on_qa_selected,inputs=[qa_selector, qa_data_json, current_reviews_json],outputs=[current_qa_id, qa_question_display, qa_answer_display,status_radio, issue_type_dropdown, modified_question, modified_answer, comment_textbox])32 unmodified linesoutputs=[save_result])# 导出export_btn.click(fn=export_reviews_handler,outputs=[export_result]).then(fn=lambda: gr.Textbox(visible=True),outputs=[export_result])return app6 unmodified linesapp.launch(server_name="0.0.0.0",server_port=7860,share=True)
app.py+154-118