ocr_validator_layout.py 26 KB

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