7 unmodified lines89101111121337 unmodified lines5152535455565758596061626364655 unmodified lines71727366677468697071757677787980818283848586878889909192939495969798991001011027810310410510610710810911011111286871131141151161177 unmodified lines1251261271011281291301311321331341351051361371381391 unmodified line14114214314414514614711614814915015111915215315415515615715815916016112712816216316416516616716813113216913413513613713813917017117217317417517617717817918014218118218318418518618718818919019119219319415 unmodified lines2102112121712132141742152161762172182191782202212222232242252262272282291851861871881891902302312322332342352362372382392402412421961972432442452462476 unmodified lines2542552562102112572582592602614 unmodified lines26626726822222322422522622722822923023123223323423523623723823924024124224324424524624724826927027129 unmodified lines3013023032842852862872883043053063073083093103112952962972982993003013023033043053063073083093103123133143153163171 unmodified line31932032132232332432032532632732811 unmodified lines3403413423383393403413423433443433443452 unmodified lines3483493503513523533543553563574 unmodified lines3623633643653663673683693703713723733743753 unmodified lines37938038137838238338438527 unmodified lines4134144154124134144154164174164174184194204214 unmodified lines4264274284294304314321 unmodified line43443543643543743843944044143944244344444544644744844944645045145245345445545645745879 unmodified lines53853954053354154254354427 unmodified lines5725735745675685755765775785791 unmodified line58158258357657758458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962058462162262358758862462562662732 unmodified lines6606616626276636646656306666676326336686696706716726 unmodified lines6796806816466826837 unmodified linesimport jsonimport osimport base64import tempfile
# ============== 全局状态 ==============
37 unmodified lines break def navigate(self, direction: int) -> bool: """ 导航到上一个或下一个图表 Args: direction: 1 表示下一个,-1 表示上一个 Returns: 是否成功导航 """ new_index = self.current_index + direction if 0 <= new_index < len(self.all_paths): self.current_index = new_index5 unmodified lines return True return False
# 全局状态实例app_state = AppState()state = AppState()
# 全局变量存储当前 QA 数据和审核记录current_qa_data = []current_reviews_data = {}
# ============== 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, models
def update_chart_type_dropdown(source: str): """更新图表类型下拉框""" app_state.current_source = source state.current_source = 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)
def update_chart_dropdown(source: str, chart_type: str): """更新图表和模型下拉框""" app_state.current_source = source app_state.current_chart_type = chart_type state.current_source = source state.current_chart_type = chart_type charts = data_manager.get_chart_list(source, chart_type) structure = data_manager.get_dataset_structure()7 unmodified lines
def create_embedded_html(html_content: str, chart_id: str = "") -> str: """创建嵌入式的 HTML 显示""" """ 创建嵌入式的 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:500px;color:#999;border:2px dashed #ddd;border-radius:12px;background:#fafafa;"> 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') return f""" # 使用 data URI iframe_html = f""" <iframe src="data:text/html;base64,{html_base64}" style="width:100%;height:650px;border:1px solid #e0e0e0;border-radius:8px;background:#fff;" 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_html
def load_chart_data(source: str, chart_type: str, chart_id: str, model: str): """加载图表数据""" global current_qa_data, current_reviews_data """ 加载图表数据并返回所有 UI 更新 Returns: 包含所有 UI 组件更新值的元组 """ if not all([source, chart_type, chart_id, model]): current_qa_data = [] current_reviews_data = {} return [ create_embedded_html(""), "### 请在左侧选择图表", "等待加载数据...", "请在左侧选择图表", gr.Radio(choices=[], value=None), "" 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 ] # 更新状态 app_state.set_position(source, chart_type, chart_id, model) 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', {}) # 创建嵌入式 HTML 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 = {} existing_reviews = {} for review in data_manager.get_reviews_by_chart(chart_id, model): current_reviews_data[review['qa_id']] = review existing_reviews[review['qa_id']] = review # 更新进度文本 progress_text = f"当前: {app_state.current_index + 1} / {len(app_state.all_paths)} 个图表" 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, label_text, status_text, progress_text, gr.Radio(choices=qa_choices, value=qa_choices[0] if qa_choices else None), debug_info embedded_html, # html_display label_text, # label_info json.dumps([{"id": qa.id, "question": qa.question, "answer": qa.answer} for qa in qa_list]), # qa_data (JSON string) status_text, # status_text progress_text, # progress_text json.dumps(existing_reviews), # current_qa_reviews (JSON string) gr.Radio(choices=qa_choices, value=qa_choices[0] if qa_choices else None), # qa_selector debug_info # debug_info ]
def navigate_prev(): """导航到上一个图表""" if app_state.navigate(-1): path = app_state.get_current_path() if state.navigate(-1): path = state.get_current_path() if path: return ( gr.Dropdown(value=path['source']),6 unmodified lines
def navigate_next(): """导航到下一个图表""" if app_state.navigate(1): path = app_state.get_current_path() if state.navigate(1): path = state.get_current_path() if path: return ( gr.Dropdown(value=path['source']),4 unmodified lines return [gr.Dropdown(), gr.Dropdown(), gr.Dropdown(), gr.Dropdown()]
def on_qa_selected(qa_index_str: str): """QA 选择器变化时更新审核面板""" global current_qa_data, current_reviews_data if not qa_index_str or not current_qa_data: return ["", "", gr.Radio(value="pending"), "", "", "", ""] try: index = int(qa_index_str.split(":")[0].replace("Q", "")) - 1 qa = 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_data current_reviews_data[qa_id] = review_data 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(): """导出审核记录并返回文件路径供下载""" 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 """导出审核记录""" output_path = data_manager.export_reviews("./reviews_export.json") return f"✅ 审核记录已导出至: {output_path}"
# ============== 创建 Gradio 界面 ==============1 unmodified linedef create_ui(): """创建 Gradio 界面""" # 自定义 CSS custom_css = """ .chart-container { min-height: 680px; min-height: 520px; } .control-panel {11 unmodified lines border-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 lines css=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=280): with gr.Column(scale=1, min_width=250): gr.Markdown("### 📁 数据选择") source_dropdown = gr.Dropdown(27 unmodified lines prev_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) # 导出按钮 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=3, min_width=500): with gr.Column(scale=2, min_width=400): gr.Markdown("### 📈 图表展示") # HTML 图表展示(使用 iframe) html_display = gr.HTML( value="<div style='text-align:center;padding:100px;color:#999;'>请选择图表</div>", 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"]) 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(value="", visible=False) save_result = gr.Textbox(label="", visible=False) # ==================== 事件绑定 ==================== 27 unmodified lines fn=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 html_display, label_display, qa_data_json, status_text, progress_text, current_reviews_json, qa_selector, debug_info ] ) 1 unmodified line fn=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 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", "")) - 1 qa = qa_list[index] # 检查是否有现有审核 review = reviews.get(qa['id'], {}) return [ qa['id'], # current_qa_id qa['question'], # qa_question_display qa['answer'], # qa_answer_display gr.Radio(value=review.get('status', 'pending')), # status_radio review.get('issue_type', ''), # issue_type_dropdown review.get('modified_question', ''), # modified_question review.get('modified_answer', ''), # modified_answer review.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], 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 status_radio, issue_type_dropdown, modified_question, modified_answer, comment_textbox ] ) 32 unmodified lines outputs=[save_result] ) # 导出审核记录 # 导出 export_btn.click( fn=export_reviews_handler, outputs=[download_file, export_status] outputs=[export_result] ).then( fn=lambda: gr.File(visible=True), outputs=[download_file] fn=lambda: gr.Textbox(visible=True), outputs=[export_result] ) return app6 unmodified lines app.launch( server_name="0.0.0.0", server_port=7860, share=False share=True )app.py+154-118