ocr_validator_layout.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. #!/usr/bin/env python3
  2. """
  3. OCR验证工具的布局管理模块
  4. 包含标准布局、滚动布局、紧凑布局的实现
  5. """
  6. import streamlit as st
  7. from pathlib import Path
  8. from PIL import Image
  9. from typing import Dict, List, Optional
  10. import plotly.graph_objects as go
  11. from typing import Tuple
  12. from ocr_validator_utils import (
  13. convert_html_table_to_markdown,
  14. parse_html_tables,
  15. draw_bbox_on_image,
  16. rotate_image_and_coordinates,
  17. get_ocr_tool_rotation_config # 新增导入
  18. )
  19. class OCRLayoutManager:
  20. """OCR布局管理器"""
  21. def __init__(self, validator):
  22. self.validator = validator
  23. self.config = validator.config
  24. self._rotated_image_cache = {} # 缓存旋转后的图像
  25. self._cache_max_size = 10 # 最大缓存数量
  26. def clear_image_cache(self):
  27. """清理所有图像缓存"""
  28. self._rotated_image_cache.clear()
  29. def clear_cache_for_image(self, image_path: str):
  30. """清理指定图像的所有缓存"""
  31. keys_to_remove = [key for key in self._rotated_image_cache.keys() if key.startswith(image_path)]
  32. for key in keys_to_remove:
  33. del self._rotated_image_cache[key]
  34. def get_cache_info(self) -> dict:
  35. """获取缓存信息"""
  36. return {
  37. 'cache_size': len(self._rotated_image_cache),
  38. 'cached_images': list(self._rotated_image_cache.keys()),
  39. 'max_size': self._cache_max_size
  40. }
  41. def _manage_cache_size(self):
  42. """管理缓存大小,超出限制时清理最旧的缓存"""
  43. if len(self._rotated_image_cache) > self._cache_max_size:
  44. # 删除最旧的缓存项(FIFO策略)
  45. oldest_key = next(iter(self._rotated_image_cache))
  46. del self._rotated_image_cache[oldest_key]
  47. def get_rotation_angle(self) -> float:
  48. """从OCR数据中获取旋转角度"""
  49. if self.validator.ocr_data:
  50. for item in self.validator.ocr_data:
  51. if isinstance(item, dict) and 'rotation_angle' in item:
  52. return item['rotation_angle']
  53. return 0.0
  54. def load_and_rotate_image(self, image_path: str) -> Optional[Image.Image]:
  55. """加载并根据需要旋转图像"""
  56. if not image_path or not Path(image_path).exists():
  57. return None
  58. # 检查缓存
  59. rotation_angle = self.get_rotation_angle()
  60. cache_key = f"{image_path}_{rotation_angle}"
  61. if cache_key in self._rotated_image_cache:
  62. return self._rotated_image_cache[cache_key]
  63. try:
  64. image = Image.open(image_path)
  65. # 如果需要旋转
  66. if rotation_angle != 0:
  67. # 获取OCR工具的旋转配置
  68. rotation_config = get_ocr_tool_rotation_config(self.validator.ocr_data, self.config)
  69. st.info(f"🔄 检测到文档旋转角度: {rotation_angle}°,正在处理图像和坐标...")
  70. st.info(f"📋 OCR工具配置: 坐标{'已预旋转' if rotation_config['coordinates_are_pre_rotated'] else '需要旋转'}")
  71. # 判断是否需要旋转坐标
  72. if rotation_config['coordinates_are_pre_rotated']:
  73. # PPStructV3: 坐标已经是旋转后的,只旋转图像
  74. if rotation_angle == 270:
  75. rotated_image = image.rotate(-90, expand=True) # 顺时针90度
  76. elif rotation_angle == 90:
  77. rotated_image = image.rotate(90, expand=True) # 逆时针90度
  78. elif rotation_angle == 180:
  79. rotated_image = image.rotate(180, expand=True) # 180度
  80. else:
  81. rotated_image = image.rotate(-rotation_angle, expand=True)
  82. # 坐标不需要变换,因为JSON中已经是正确的坐标
  83. self._rotated_image_cache[cache_key] = rotated_image
  84. self._manage_cache_size()
  85. return rotated_image
  86. else:
  87. # Dots OCR: 需要同时旋转图像和坐标
  88. # 收集所有bbox坐标
  89. all_bboxes = []
  90. text_to_bbox_map = {} # 记录文本到bbox索引的映射
  91. bbox_index = 0
  92. for text, info_list in self.validator.text_bbox_mapping.items():
  93. text_to_bbox_map[text] = []
  94. for info in info_list:
  95. all_bboxes.append(info['bbox'])
  96. text_to_bbox_map[text].append(bbox_index)
  97. bbox_index += 1
  98. # 旋转图像和坐标
  99. rotated_image, rotated_bboxes = rotate_image_and_coordinates(
  100. image, rotation_angle, all_bboxes,
  101. rotate_coordinates=rotation_config['coordinates_need_rotation']
  102. )
  103. # 更新bbox映射 - 使用映射关系确保正确对应
  104. for text, bbox_indices in text_to_bbox_map.items():
  105. for i, bbox_idx in enumerate(bbox_indices):
  106. if bbox_idx < len(rotated_bboxes) and i < len(self.validator.text_bbox_mapping[text]):
  107. self.validator.text_bbox_mapping[text][i]['bbox'] = rotated_bboxes[bbox_idx]
  108. # 缓存结果
  109. self._rotated_image_cache[cache_key] = rotated_image
  110. self._manage_cache_size()
  111. return rotated_image
  112. else:
  113. # 无需旋转,直接缓存原图
  114. self._rotated_image_cache[cache_key] = image
  115. self._manage_cache_size() # 检查并管理缓存大小
  116. return image
  117. except Exception as e:
  118. st.error(f"❌ 图像加载失败: {e}")
  119. return None
  120. def render_content_section(self, layout_type: str = "standard"):
  121. """渲染内容区域 - 统一方法"""
  122. st.header("📄 OCR识别内容")
  123. # 显示旋转信息
  124. # rotation_angle = self.get_rotation_angle()
  125. # if rotation_angle != 0:
  126. # st.info(f"📐 文档旋转角度: {rotation_angle}°")
  127. # 文本选择器
  128. if self.validator.text_bbox_mapping:
  129. text_options = ["请选择文本..."] + list(self.validator.text_bbox_mapping.keys())
  130. selected_index = st.selectbox(
  131. "选择要校验的文本",
  132. range(len(text_options)),
  133. format_func=lambda x: text_options[x][:50] + "..." if len(text_options[x]) > 50 else text_options[x],
  134. key=f"{layout_type}_text_selector"
  135. )
  136. if selected_index > 0:
  137. st.session_state.selected_text = text_options[selected_index]
  138. else:
  139. st.warning("没有找到可点击的文本")
  140. def render_md_content(self, layout_type: str):
  141. """渲染Markdown内容 - 统一方法"""
  142. if not self.validator.md_content:
  143. return None, None
  144. # 搜索功能
  145. search_term = st.text_input(
  146. "🔍 搜索文本内容",
  147. placeholder="输入关键词搜索...",
  148. key=f"{layout_type}_search"
  149. )
  150. display_content = self.validator.md_content
  151. if search_term:
  152. lines = display_content.split('\n')
  153. filtered_lines = [line for line in lines if search_term.lower() in line.lower()]
  154. display_content = '\n'.join(filtered_lines)
  155. if filtered_lines:
  156. st.success(f"找到 {len(filtered_lines)} 行包含 '{search_term}'")
  157. else:
  158. st.warning(f"未找到包含 '{search_term}' 的内容")
  159. # 渲染方式选择
  160. render_mode = st.radio(
  161. "选择渲染方式",
  162. ["HTML渲染", "Markdown渲染", "DataFrame表格", "原始文本"],
  163. horizontal=True,
  164. key=f"{layout_type}_render_mode"
  165. )
  166. return display_content, render_mode
  167. def render_content_by_mode(self, content: str, render_mode: str, font_size: int, layout_type: str):
  168. """根据渲染模式显示内容 - 统一方法"""
  169. if content is None or render_mode is None:
  170. return
  171. if render_mode == "HTML渲染":
  172. content_style = f"""
  173. <style>
  174. .{layout_type}-content-display {{
  175. font-size: {font_size}px !important;
  176. line-height: 1.4;
  177. color: #333333 !important;
  178. background-color: #fafafa !important;
  179. padding: 10px;
  180. border-radius: 5px;
  181. border: 1px solid #ddd;
  182. }}
  183. </style>
  184. """
  185. st.markdown(content_style, unsafe_allow_html=True)
  186. st.markdown(f'<div class="{layout_type}-content-display">{content}</div>', unsafe_allow_html=True)
  187. elif render_mode == "Markdown渲染":
  188. converted_content = convert_html_table_to_markdown(content)
  189. content_style = f"""
  190. <style>
  191. .{layout_type}-content-display {{
  192. font-size: {font_size}px !important;
  193. line-height: 1.4;
  194. color: #333333 !important;
  195. background-color: #fafafa !important;
  196. padding: 10px;
  197. border-radius: 5px;
  198. border: 1px solid #ddd;
  199. }}
  200. </style>
  201. """
  202. st.markdown(content_style, unsafe_allow_html=True)
  203. st.markdown(f'<div class="{layout_type}-content-display">{converted_content}</div>', unsafe_allow_html=True)
  204. elif render_mode == "DataFrame表格":
  205. if '<table' in content.lower():
  206. self.validator.display_html_table_as_dataframe(content)
  207. else:
  208. st.info("当前内容中没有检测到HTML表格")
  209. st.markdown(content, unsafe_allow_html=True)
  210. else: # 原始文本
  211. st.text_area(
  212. "MD内容预览",
  213. content,
  214. height=300,
  215. key=f"{layout_type}_text_area"
  216. )
  217. # 布局实现
  218. def create_standard_layout(self, font_size: int = 10, zoom_level: float = 1.0):
  219. """创建标准布局"""
  220. if zoom_level is None:
  221. zoom_level = self.config['styles']['layout']['default_zoom']
  222. # 主要内容区域
  223. layout = self.config['styles']['layout']
  224. left_col, right_col = st.columns([layout['content_width'], layout['sidebar_width']])
  225. with left_col:
  226. self.render_content_section("standard")
  227. # 显示内容
  228. if self.validator.md_content:
  229. display_content, render_mode = self.render_md_content("standard")
  230. self.render_content_by_mode(display_content, render_mode, font_size, "standard")
  231. with right_col:
  232. self.create_aligned_image_display(zoom_level, "compact")
  233. def create_compact_layout(self, font_size: int = 10, zoom_level: float = 1.0):
  234. """创建紧凑的对比布局"""
  235. # 主要内容区域
  236. layout = self.config['styles']['layout']
  237. left_col, right_col = st.columns([layout['content_width'], layout['sidebar_width']])
  238. with left_col:
  239. self.render_content_section("compact")
  240. # 只保留一个内容区域高度选择
  241. container_height = st.selectbox(
  242. "选择内容区域高度",
  243. [400, 600, 800, 1000, 1200],
  244. index=2,
  245. key="compact_content_height"
  246. )
  247. # 快速定位文本选择器(使用不同的key)
  248. if self.validator.text_bbox_mapping:
  249. text_options = ["请选择文本..."] + list(self.validator.text_bbox_mapping.keys())
  250. selected_index = st.selectbox(
  251. "快速定位文本",
  252. range(len(text_options)),
  253. format_func=lambda x: text_options[x][:30] + "..." if len(text_options[x]) > 30 else text_options[x],
  254. key="compact_quick_text_selector" # 使用不同的key
  255. )
  256. if selected_index > 0:
  257. st.session_state.selected_text = text_options[selected_index]
  258. # 自定义CSS样式
  259. st.markdown(f"""
  260. <style>
  261. .compact-content {{
  262. height: {container_height}px;
  263. overflow-y: auto;
  264. font-size: {font_size}px !important;
  265. line-height: 1.4;
  266. border: 1px solid #ddd;
  267. padding: 10px;
  268. background-color: #fafafa !important;
  269. font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  270. color: #333333 !important;
  271. }}
  272. .highlight-text {{
  273. background-color: #ffeb3b !important;
  274. padding: 2px 4px;
  275. border-radius: 3px;
  276. cursor: pointer;
  277. color: #333333 !important;
  278. }}
  279. .selected-highlight {{
  280. background-color: #4caf50 !important;
  281. color: white !important;
  282. }}
  283. </style>
  284. """, unsafe_allow_html=True)
  285. # 处理并显示OCR内容
  286. if self.validator.md_content:
  287. # 高亮可点击文本
  288. highlighted_content = self.validator.md_content
  289. for text in self.validator.text_bbox_mapping.keys():
  290. if len(text) > 2: # 避免高亮过短的文本
  291. css_class = "highlight-text selected-highlight" if text == st.session_state.selected_text else "highlight-text"
  292. highlighted_content = highlighted_content.replace(
  293. text,
  294. f'<span class="{css_class}" title="{text[:50]}...">{text}</span>'
  295. )
  296. st.markdown(
  297. f'<div class="compact-content">{highlighted_content}</div>',
  298. unsafe_allow_html=True
  299. )
  300. with right_col:
  301. # 修复的对齐图片显示
  302. self.create_aligned_image_display(zoom_level, "compact")
  303. def create_aligned_image_display(self, zoom_level: float = 1.0, layout_type: str = "aligned"):
  304. """创建与左侧对齐的图片显示 - 修复显示问题"""
  305. # 精确对齐CSS
  306. st.markdown(f"""
  307. <style>
  308. .aligned-image-container-{layout_type} {{
  309. margin-top: -70px;
  310. padding-top: 0px;
  311. }}
  312. .aligned-image-container-{layout_type} h1 {{
  313. margin-top: 0px !important;
  314. padding-top: 0px !important;
  315. }}
  316. /* 修复:确保Plotly图表容器没有额外边距 */
  317. .js-plotly-plot, .plotly {{
  318. margin: 0 !important;
  319. padding: 0 !important;
  320. }}
  321. </style>
  322. """, unsafe_allow_html=True)
  323. st.markdown(f'<div class="aligned-image-container-{layout_type}">', unsafe_allow_html=True)
  324. st.header("🖼️ 原图标注")
  325. # 图片控制选项
  326. col1, col2, col3 = st.columns(3)
  327. with col1:
  328. current_zoom = st.slider("图片缩放", 0.3, 2.0, zoom_level, 0.1, key=f"{layout_type}_zoom_level")
  329. with col2:
  330. show_all_boxes = st.checkbox("显示所有框", value=False, key=f"{layout_type}_show_all_boxes")
  331. with col3:
  332. fit_to_container = st.checkbox("适应容器", value=True, key=f"{layout_type}_fit_container")
  333. # 使用新的图像加载方法
  334. image = self.load_and_rotate_image(self.validator.image_path)
  335. if image:
  336. try:
  337. # 根据缩放级别调整图片大小
  338. new_width = int(image.width * current_zoom)
  339. new_height = int(image.height * current_zoom)
  340. resized_image = image.resize((new_width, new_height), Image.Resampling.LANCZOS)
  341. # 计算选中的bbox - 注意bbox已经是旋转后的坐标
  342. selected_bbox = None
  343. if st.session_state.selected_text and st.session_state.selected_text in self.validator.text_bbox_mapping:
  344. info = self.validator.text_bbox_mapping[st.session_state.selected_text][0]
  345. # bbox已经是旋转后的坐标,只需要应用缩放
  346. bbox = info['bbox']
  347. selected_bbox = [int(coord * current_zoom) for coord in bbox]
  348. # 收集所有框
  349. all_boxes = []
  350. if show_all_boxes:
  351. for text, info_list in self.validator.text_bbox_mapping.items():
  352. for info in info_list:
  353. bbox = info['bbox']
  354. if len(bbox) >= 4:
  355. scaled_bbox = [coord * current_zoom for coord in bbox]
  356. all_boxes.append(scaled_bbox)
  357. # 添加调试信息
  358. with st.expander("🔍 图像和坐标调试信息", expanded=False):
  359. rotation_angle = self.get_rotation_angle()
  360. rotation_config = get_ocr_tool_rotation_config(self.validator.ocr_data, self.config)
  361. col_debug1, col_debug2 = st.columns(2)
  362. with col_debug1:
  363. st.write("**图像信息:**")
  364. st.write(f"原始尺寸: {image.width} x {image.height}")
  365. st.write(f"缩放后尺寸: {resized_image.width} x {resized_image.height}")
  366. st.write(f"旋转角度: {rotation_angle}°")
  367. with col_debug2:
  368. st.write("**坐标信息:**")
  369. if selected_bbox:
  370. st.write(f"选中框: {selected_bbox}")
  371. st.write(f"总框数: {len(all_boxes)}")
  372. st.write(f"工具配置: {'预旋转' if rotation_config.get('coordinates_are_pre_rotated') else '需旋转'}")
  373. if st.session_state.selected_text:
  374. info = self.validator.text_bbox_mapping[st.session_state.selected_text][0]
  375. original_bbox = info['bbox']
  376. # 验证坐标是否在图像范围内
  377. x1, y1, x2, y2 = original_bbox[:4]
  378. in_bounds = (0 <= x1 < image.width and
  379. 0 <= x2 <= image.width and
  380. 0 <= y1 < image.height and
  381. 0 <= y2 <= image.height)
  382. color = "🟢" if in_bounds else "🔴"
  383. st.write(f"{color} 坐标范围检查: {in_bounds}")
  384. if not in_bounds:
  385. st.warning("⚠️ 坐标超出图像范围,可能存在坐标系问题")
  386. # 创建交互式图片
  387. fig = self.create_resized_interactive_plot(resized_image, selected_bbox, current_zoom, all_boxes)
  388. # 修复:使用合适的配置显示图表
  389. plot_config = {
  390. 'displayModeBar': True,
  391. 'modeBarButtonsToRemove': ['zoom2d', 'select2d', 'lasso2d', 'autoScale2d'],
  392. 'scrollZoom': True,
  393. 'doubleClick': 'reset'
  394. }
  395. st.plotly_chart(
  396. fig,
  397. use_container_width=fit_to_container,
  398. config=plot_config,
  399. key=f"{layout_type}_plot"
  400. )
  401. # 显示选中文本的详细信息
  402. if st.session_state.selected_text and st.session_state.selected_text in self.validator.text_bbox_mapping:
  403. st.subheader("📍 选中文本详情")
  404. info = self.validator.text_bbox_mapping[st.session_state.selected_text][0]
  405. bbox = info['bbox']
  406. info_col1, info_col2 = st.columns(2)
  407. with info_col1:
  408. st.write(f"**文本内容:** {st.session_state.selected_text[:30]}...")
  409. st.write(f"**类别:** {info['category']}")
  410. # 显示旋转信息
  411. rotation_angle = self.get_rotation_angle()
  412. if rotation_angle != 0:
  413. st.write(f"**旋转角度:** {rotation_angle}°")
  414. with info_col2:
  415. st.write(f"**位置:** [{', '.join(map(str, bbox))}]")
  416. if len(bbox) >= 4:
  417. st.write(f"**大小:** {bbox[2] - bbox[0]} x {bbox[3] - bbox[1]} px")
  418. # 错误标记功能
  419. col1, col2 = st.columns(2)
  420. with col1:
  421. if st.button("❌ 标记为错误", key=f"{layout_type}_mark_error"):
  422. st.session_state.marked_errors.add(st.session_state.selected_text)
  423. st.rerun()
  424. with col2:
  425. if st.button("✅ 取消错误标记", key=f"{layout_type}_unmark_error"):
  426. st.session_state.marked_errors.discard(st.session_state.selected_text)
  427. st.rerun()
  428. except Exception as e:
  429. st.error(f"❌ 图片处理失败: {e}")
  430. st.exception(e) # 显示完整的错误堆栈
  431. else:
  432. st.error("未找到对应的图片文件")
  433. if self.validator.image_path:
  434. st.write(f"期望路径: {self.validator.image_path}")
  435. st.markdown('</div>', unsafe_allow_html=True)
  436. def create_resized_interactive_plot(self, image: Image.Image, selected_bbox: Optional[List[int]], zoom_level: float, all_boxes: list[tuple]) -> go.Figure:
  437. """
  438. 创建可调整大小的交互式图片 - 修复图像显示和bbox对齐问题
  439. 图片,box坐标全部是已缩放,旋转后的坐标
  440. """
  441. fig = go.Figure()
  442. # 添加图片 - Plotly坐标系,原点在左下角
  443. fig.add_layout_image(
  444. dict(
  445. source=image,
  446. xref="x", yref="y",
  447. x=0, y=image.height, # 图片左下角在Plotly坐标系中的位置
  448. sizex=image.width,
  449. sizey=image.height,
  450. sizing="stretch",
  451. opacity=1.0,
  452. layer="below"
  453. )
  454. )
  455. # 显示所有bbox - 需要坐标转换
  456. if len(all_boxes) > 0:
  457. for bbox in all_boxes:
  458. if len(bbox) >= 4:
  459. x1, y1, x2, y2 = bbox[:4]
  460. # 转换为Plotly坐标系(翻转Y轴)
  461. plot_x1 = x1
  462. plot_x2 = x2
  463. plot_y1 = image.height - y2 # JSON的y2 -> Plotly的底部
  464. plot_y2 = image.height - y1 # JSON的y1 -> Plotly的顶部
  465. color = "rgba(0, 100, 200, 0.2)"
  466. fig.add_shape(
  467. type="rect",
  468. x0=plot_x1, y0=plot_y1,
  469. x1=plot_x2, y1=plot_y2,
  470. line=dict(color="blue", width=1),
  471. fillcolor=color,
  472. )
  473. # 高亮显示选中的bbox
  474. if selected_bbox and len(selected_bbox) >= 4:
  475. x1, y1, x2, y2 = selected_bbox[:4]
  476. # 转换为Plotly坐标系
  477. plot_x1 = x1
  478. plot_x2 = x2
  479. plot_y1 = image.height - y2 # 翻转Y坐坐标
  480. plot_y2 = image.height - y1 # 翻转Y坐标
  481. fig.add_shape(
  482. type="rect",
  483. x0=plot_x1, y0=plot_y1,
  484. x1=plot_x2, y1=plot_y2,
  485. line=dict(color="red", width=3),
  486. fillcolor="rgba(255, 0, 0, 0.3)",
  487. )
  488. # 修复:优化显示尺寸计算
  489. max_display_width = 800
  490. max_display_height = 600
  491. # 计算合适的显示尺寸,保持宽高比
  492. aspect_ratio = image.width / image.height
  493. if aspect_ratio > 1: # 宽图
  494. display_width = min(max_display_width, image.width)
  495. display_height = int(display_width / aspect_ratio)
  496. else: # 高图
  497. display_height = min(max_display_height, image.height)
  498. display_width = int(display_height * aspect_ratio)
  499. # 修复:设置合理的布局参数
  500. fig.update_layout(
  501. width=display_width,
  502. height=display_height,
  503. margin=dict(l=0, r=0, t=0, b=0), # 移除所有边距
  504. showlegend=False,
  505. plot_bgcolor='white',
  506. dragmode="pan",
  507. # 修复:X轴设置
  508. xaxis=dict(
  509. visible=False,
  510. range=[0, image.width],
  511. constrain="domain",
  512. fixedrange=False,
  513. autorange=False,
  514. showgrid=False,
  515. zeroline=False
  516. ),
  517. # 修复:Y轴设置,确保范围正确
  518. yaxis=dict(
  519. visible=False,
  520. range=[0, image.height], # 确保Y轴范围从0到图片高度
  521. constrain="domain",
  522. scaleanchor="x",
  523. scaleratio=1,
  524. fixedrange=False,
  525. autorange=False,
  526. showgrid=False,
  527. zeroline=False
  528. )
  529. )
  530. return fig