streamlit_ocr_validator.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. #!/usr/bin/env python3
  2. """
  3. 基于Streamlit的OCR可视化校验工具(主入口)
  4. """
  5. import streamlit as st
  6. from pathlib import Path
  7. import json
  8. from streamlit_validator_core import StreamlitOCRValidator
  9. from streamlit_validator_ui import (
  10. setup_page_config, create_data_source_selector, message_box
  11. )
  12. from streamlit_validator_table import display_html_table_as_dataframe
  13. from streamlit_validator_cross import (
  14. cross_validation_dialog, show_batch_cross_validation_results_dialog
  15. )
  16. from streamlit_validator_result import display_single_page_cross_validation
  17. from ocr_validator_utils import get_data_source_display_name
  18. from config_manager import load_config # 🎯 使用新配置管理器
  19. def reset_cross_validation_results():
  20. """重置交叉验证结果"""
  21. if 'cross_validation_batch_result' in st.session_state:
  22. st.session_state.cross_validation_batch_result = None
  23. print("🔄 数据源已变更,交叉验证结果已清空")
  24. def main():
  25. """主应用"""
  26. # 🎯 初始化配置管理器
  27. if 'config_manager' not in st.session_state:
  28. try:
  29. st.session_state.config_manager = load_config(config_dir="config")
  30. # 🎯 生成 OCRValidator 所需的配置
  31. st.session_state.validator_config = st.session_state.config_manager.to_validator_config()
  32. print("✅ 配置管理器初始化成功")
  33. print(f"📄 发现 {len(st.session_state.config_manager.list_documents())} 个文档配置")
  34. print(f"🔧 发现 {len(st.session_state.config_manager.list_ocr_tools())} 个 OCR 工具")
  35. except Exception as e:
  36. st.error(f"❌ 配置加载失败: {e}")
  37. st.stop()
  38. config_manager = st.session_state.config_manager
  39. validator_config = st.session_state.validator_config
  40. # 初始化应用
  41. if 'validator' not in st.session_state:
  42. # 🎯 直接传递配置字典给 OCRValidator
  43. validator = StreamlitOCRValidator(config_dict=validator_config)
  44. st.session_state.validator = validator
  45. setup_page_config(validator_config)
  46. # 页面标题
  47. st.title(validator_config['ui']['page_title'])
  48. # 初始化数据源追踪
  49. st.session_state.current_ocr_source = validator.current_source_key
  50. st.session_state.current_verify_source = validator.verify_source_key
  51. else:
  52. validator = st.session_state.validator
  53. if 'selected_text' not in st.session_state:
  54. st.session_state.selected_text = None
  55. st.session_state.compact_search_query = None
  56. if 'marked_errors' not in st.session_state:
  57. st.session_state.marked_errors = set()
  58. # 数据源选择器
  59. create_data_source_selector(validator)
  60. # ✅ 检测数据源是否变更
  61. ocr_source_changed = False
  62. verify_source_changed = False
  63. if 'current_ocr_source' in st.session_state:
  64. if st.session_state.current_ocr_source != validator.current_source_key:
  65. ocr_source_changed = True
  66. st.session_state.current_ocr_source = validator.current_source_key
  67. print(f"🔄 OCR数据源已切换到: {validator.current_source_key}")
  68. if 'current_verify_source' in st.session_state:
  69. if st.session_state.current_verify_source != validator.verify_source_key:
  70. verify_source_changed = True
  71. st.session_state.current_verify_source = validator.verify_source_key
  72. print(f"🔄 验证数据源已切换到: {validator.verify_source_key}")
  73. # ✅ 如果任一数据源变更,清空交叉验证结果
  74. if ocr_source_changed or verify_source_changed:
  75. reset_cross_validation_results()
  76. # 显示提示信息
  77. if ocr_source_changed and verify_source_changed:
  78. st.info("ℹ️ OCR数据源和验证数据源已变更,请重新运行交叉验证")
  79. elif ocr_source_changed:
  80. st.info("ℹ️ OCR数据源已变更,请重新运行交叉验证")
  81. elif verify_source_changed:
  82. st.info("ℹ️ 验证数据源已变更,请重新运行交叉验证")
  83. # 如果没有可用的数据源,提前返回
  84. if not validator.all_sources:
  85. st.warning("⚠️ 未找到任何数据源,请检查配置文件")
  86. # 🎯 显示配置信息帮助调试
  87. with st.expander("🔍 配置信息", expanded=True):
  88. st.write("**已加载的文档:**")
  89. docs = config_manager.list_documents()
  90. if docs:
  91. for doc in docs:
  92. doc_config = config_manager.get_document(doc)
  93. st.write(f"- **{doc}**")
  94. st.write(f" - 基础目录: `{doc_config.base_dir}`")
  95. st.write(f" - OCR 结果: {len([r for r in doc_config.ocr_results if r.enabled])} 个已启用")
  96. else:
  97. st.write("无")
  98. st.write("**已加载的 OCR 工具:**")
  99. tools = config_manager.list_ocr_tools()
  100. if tools:
  101. for tool in tools:
  102. tool_config = config_manager.get_ocr_tool(tool)
  103. st.write(f"- **{tool_config.name}** (`{tool}`)")
  104. else:
  105. st.write("无")
  106. st.write("**配置文件路径:**")
  107. st.code(str(config_manager.config_dir / "global.yaml"))
  108. st.write("**生成的数据源:**")
  109. data_sources = config_manager.get_data_sources()
  110. if data_sources:
  111. for ds in data_sources:
  112. st.write(f"- `{ds.name}`")
  113. st.write(f" - 工具: {ds.ocr_tool}")
  114. st.write(f" - 结果目录: {ds.ocr_out_dir}")
  115. st.write(f" - 图片目录: {ds.src_img_dir}")
  116. else:
  117. st.write("无")
  118. st.stop()
  119. # 文件选择区域
  120. with st.container(height=75, horizontal=True, horizontal_alignment='left', gap="medium"):
  121. if 'selected_file_index' not in st.session_state:
  122. st.session_state.selected_file_index = 0
  123. if validator.display_options:
  124. selected_index = st.selectbox(
  125. "选择OCR结果文件",
  126. range(len(validator.display_options)),
  127. format_func=lambda i: validator.display_options[i],
  128. index=st.session_state.selected_file_index,
  129. key="selected_selectbox",
  130. label_visibility="collapsed"
  131. )
  132. if selected_index != st.session_state.selected_file_index:
  133. st.session_state.selected_file_index = selected_index
  134. selected_file = validator.file_paths[selected_index]
  135. current_page = validator.file_info[selected_index]['page']
  136. page_input = st.number_input(
  137. "输入页码",
  138. placeholder="输入页码",
  139. label_visibility="collapsed",
  140. min_value=1,
  141. max_value=len(validator.display_options),
  142. value=current_page,
  143. step=1,
  144. key="page_input"
  145. )
  146. if page_input != current_page:
  147. for i, info in enumerate(validator.file_info):
  148. if info['page'] == page_input:
  149. st.session_state.selected_file_index = i
  150. selected_file = validator.file_paths[i]
  151. st.rerun()
  152. break
  153. if (st.session_state.selected_file_index >= 0
  154. and validator.selected_file_index != st.session_state.selected_file_index
  155. and selected_file):
  156. validator.selected_file_index = st.session_state.selected_file_index
  157. st.session_state.validator.load_ocr_data(selected_file)
  158. current_source_name = get_data_source_display_name(validator.current_source_config)
  159. st.success(f"✅ 已加载 {current_source_name} - 第{validator.file_info[st.session_state.selected_file_index]['page']}页")
  160. st.rerun()
  161. else:
  162. st.warning("当前数据源中未找到OCR结果文件")
  163. # ✅ 交叉验证按钮 - 添加数据源检查
  164. cross_validation_enabled = (
  165. validator.current_source_key != validator.verify_source_key
  166. and validator.image_path
  167. and validator.md_content
  168. )
  169. if st.button(
  170. "交叉验证",
  171. type="primary",
  172. icon=":material/compare_arrows:",
  173. disabled=not cross_validation_enabled,
  174. help="需要选择不同的OCR数据源和验证数据源" if not cross_validation_enabled else "开始批量交叉验证"
  175. ):
  176. cross_validation_dialog(validator)
  177. # ✅ 查看验证结果按钮 - 检查是否有验证结果
  178. has_validation_results = (
  179. 'cross_validation_batch_result' in st.session_state
  180. and st.session_state.cross_validation_batch_result is not None
  181. )
  182. if st.button(
  183. "查看验证结果",
  184. type="secondary",
  185. icon=":material/quick_reference_all:",
  186. disabled=not has_validation_results,
  187. help="暂无验证结果,请先运行交叉验证" if not has_validation_results else "查看批量验证结果"
  188. ):
  189. show_batch_cross_validation_results_dialog()
  190. # 显示当前数据源统计信息
  191. with st.expander("统� OCR工具计信息", expanded=False):
  192. stats = validator.get_statistics()
  193. col1, col2, col3, col4, col5 = st.columns(5)
  194. with col1:
  195. st.metric("📊 总文本块", stats['total_texts'])
  196. with col2:
  197. st.metric("🔗 可点击文本", stats['clickable_texts'])
  198. with col3:
  199. st.metric("❌ 标记错误", stats['marked_errors'])
  200. with col4:
  201. st.metric("✅ 准确率", f"{stats['accuracy_rate']:.1f}%")
  202. with col5:
  203. if validator.current_source_config:
  204. tool_id = validator.current_source_config['ocr_tool']
  205. # 🎯 从配置管理器获取工具名称
  206. tool_config = config_manager.get_ocr_tool(tool_id)
  207. tool_display = tool_config.name if tool_config else tool_id.upper()
  208. st.metric("🔧 OCR工具", tool_display)
  209. if stats['tool_info']:
  210. st.write("**详细信息:**", stats['tool_info'])
  211. # 🎯 显示当前文档和 OCR 结果信息
  212. if validator.current_source_config:
  213. source_name = validator.current_source_config['name']
  214. # 解析数据源名称,提取文档名(更精确的解析)
  215. parts = source_name.split('_', 1)
  216. doc_name = parts[0] if parts else source_name
  217. doc_config = config_manager.get_document(doc_name)
  218. if doc_config:
  219. st.write("**文档信息:**")
  220. st.write(f"- 文档名称: {doc_config.name}")
  221. st.write(f"- 基础目录: {doc_config.base_dir}")
  222. st.write(f"- 可用 OCR 工具: {len([r for r in doc_config.ocr_results if r.enabled])} 个")
  223. # 🎯 添加配置管理面板
  224. with st.expander("⚙️ 配置管理", expanded=False):
  225. col1, col2 = st.columns(2)
  226. with col1:
  227. st.subheader("📄 已加载文档")
  228. docs = config_manager.list_documents()
  229. for doc_name in docs:
  230. doc_config = config_manager.get_document(doc_name)
  231. enabled_count = len([r for r in doc_config.ocr_results if r.enabled])
  232. total_count = len(doc_config.ocr_results)
  233. with st.container():
  234. st.write(f"✅ **{doc_name}**")
  235. st.caption(f"📊 {enabled_count}/{total_count} 工具已启用")
  236. # 显示每个 OCR 工具的状态
  237. for ocr_result in doc_config.ocr_results:
  238. status_icon = "🟢" if ocr_result.enabled else "⚪"
  239. tool_config = config_manager.get_ocr_tool(ocr_result.tool)
  240. tool_name = tool_config.name if tool_config else ocr_result.tool
  241. st.caption(f" {status_icon} {tool_name} - {ocr_result.description or ocr_result.result_dir}")
  242. with col2:
  243. st.subheader("🔧 已加载 OCR 工具")
  244. tools = config_manager.list_ocr_tools()
  245. for tool_id in tools:
  246. tool_config = config_manager.get_ocr_tool(tool_id)
  247. with st.container():
  248. st.write(f"🔧 **{tool_config.name}**")
  249. st.caption(f"ID: `{tool_id}`")
  250. st.caption(f"描述: {tool_config.description}")
  251. tab1, tab2, tab3 = st.tabs(["📄 内容人工检查", "🔍 交叉验证结果", "📊 表格分析"])
  252. with tab1:
  253. validator.create_compact_layout(validator_config)
  254. with tab2:
  255. # ✅ 使用封装的函数显示单页交叉验证结果
  256. display_single_page_cross_validation(validator, validator_config)
  257. with tab3:
  258. st.header("📊 表格数据分析")
  259. if validator.md_content and '<table' in validator.md_content.lower():
  260. st.subheader("🔍 表格数据预览")
  261. display_html_table_as_dataframe(validator.md_content)
  262. else:
  263. st.info("当前OCR结果中没有检测到表格数据")
  264. if __name__ == "__main__":
  265. main()