Hunyuan-OCR-WEBUI功能扩展:从单张识别到批量处理的完整教程
Hunyuan-OCR-WEBUI功能扩展从单张识别到批量处理的完整教程1. 引言在日常工作中我们经常需要处理大量图片中的文字信息。无论是扫描的文档、拍摄的票据还是截图中的文字内容传统的手动录入方式效率低下且容易出错。腾讯混元OCR作为一款强大的文字识别工具其官方WebUI虽然功能强大但默认只支持单张图片识别无法满足批量处理的需求。本教程将带你一步步扩展Hunyuan-OCR-WEBUI的功能实现从单张识别到批量处理的完整解决方案。通过这个改造你将能够一次性上传多张图片进行批量识别在界面上直观管理所有待处理的图片自动保存所有识别结果并导出为结构化文件大幅提升OCR处理效率节省宝贵时间整个过程不需要修改OCR模型本身而是通过前端界面和后端逻辑的扩展来实现。即使你不是专业开发者只要按照本教程的步骤操作也能顺利完成功能扩展。2. 环境准备与项目分析2.1 基础环境确认在开始之前请确保你已经通过CSDN星图镜像广场部署了Hunyuan-OCR-WEBUI服务并能够正常访问7860端口的Web界面。你需要准备已部署的Hunyuan-OCR-WEBUI服务代码编辑器如VSCode通过Jupyter或SSH连接到运行环境基本的Python和前端知识HTML/JavaScript2.2 原项目结构分析首先我们需要找到WebUI的主程序文件。通常它位于/root/Hunyuan-OCR-WEBUI/app.py或者类似的路径。用编辑器打开这个文件你会看到类似以下的核心结构import gradio as gr from ocr_model import HunyuanOCRModel model HunyuanOCRModel() def recognize_text(image_path): # 调用OCR模型识别图片中的文字 result model.predict(image_path) return result # 创建Gradio界面 with gr.Blocks() as demo: gr.Markdown(# Hunyuan OCR WebUI) with gr.Row(): with gr.Column(): image_input gr.Image(labelUpload Image, typefilepath) submit_btn gr.Button(Submit) with gr.Column(): text_output gr.Textbox(labelOCR Result, lines20) submit_btn.click(fnrecognize_text, inputsimage_input, outputstext_output) demo.launch(server_port7860)从代码可以看出原版界面非常简单一个图片上传组件、一个提交按钮和一个结果显示文本框。我们的目标是扩展这个结构支持多文件处理和批量识别。3. 实现批量图片上传功能3.1 改造上传组件Gradio的gr.File组件原生支持多文件上传我们将用它替换原来的gr.Image组件with gr.Blocks() as demo: gr.Markdown(# 混元OCR批量处理工具) with gr.Row(): with gr.Column(scale1): # 使用File组件替代Image组件 file_input gr.File( label上传图片支持多选, file_types[image], file_countmultiple, # 允许多选 typefilepath ) upload_status gr.Markdown(等待上传...) with gr.Column(scale2): # 创建图片预览区域 gallery gr.Gallery( label已上传图片, show_labelTrue, columns4, heightauto )3.2 添加上传处理逻辑我们需要一个函数来处理上传事件更新图片预览和状态信息import os def handle_upload(files): 处理文件上传返回图片路径列表和状态信息 if not files: return [], 未选择文件 image_paths [] for file in files: # 验证文件类型 if not file.name.lower().endswith((.png, .jpg, .jpeg)): continue image_paths.append(file.name) status f成功上传 {len(image_paths)} 张图片 if image_paths else 未上传有效图片 return image_paths, status # 绑定上传事件 file_input.change( fnhandle_upload, inputsfile_input, outputs[gallery, upload_status] )3.3 添加图片管理功能为了让用户能够选择要识别的图片我们添加一个下拉选择框with gr.Row(): selected_image gr.Dropdown( label选择要识别的图片, choices[], interactiveTrue ) clear_btn gr.Button(清空列表, variantsecondary) # 更新选择框选项的函数 def update_selection(image_paths): if image_paths: choices [(os.path.basename(path), path) for path in image_paths] return gr.Dropdown(choiceschoices, valueimage_paths[0]) return gr.Dropdown(choices[], valueNone) # 清空功能 def clear_all(): return [], [], gr.Dropdown(choices[], valueNone), 已清空所有图片 clear_btn.click( fnclear_all, outputs[file_input, gallery, selected_image, upload_status] )4. 实现批量识别功能4.1 修改识别函数支持批量处理我们需要修改原来的recognize_text函数使其能够处理多张图片def batch_recognize(image_paths): 批量识别多张图片中的文字 if not image_paths: return 未选择图片 all_results [] for img_path in image_paths: try: result model.predict(img_path) filename os.path.basename(img_path) all_results.append(f {filename} \n{result}\n\n) except Exception as e: all_results.append(f {img_path} 识别失败 \n错误: {str(e)}\n\n) return .join(all_results)4.2 添加批量识别按钮和进度显示在界面中添加批量处理相关组件with gr.Row(): batch_btn gr.Button(批量识别所有图片, variantprimary) progress gr.Textbox(label处理进度, interactiveFalse) # 绑定批量识别事件 batch_btn.click( fnbatch_recognize, inputsgallery, outputstext_output )5. 增强结果导出功能5.1 添加多种导出格式支持我们将提供TXT、Word和Excel三种导出格式with gr.Row(): export_txt_btn gr.Button(导出为TXT) export_docx_btn gr.Button(导出为Word) export_xlsx_btn gr.Button(导出为Excel) export_status gr.Markdown()5.2 实现导出函数import datetime from docx import Document import pandas as pd def export_as_txt(ocr_text): 导出为TXT文件 if not ocr_text.strip(): return None, 导出失败识别结果为空 timestamp datetime.datetime.now().strftime(%Y%m%d_%H%M%S) filename focr_results_{timestamp}.txt filepath f/tmp/{filename} with open(filepath, w, encodingutf-8) as f: f.write(ocr_text) return filepath, fTXT文件已生成: {filename} def export_as_docx(ocr_text): 导出为Word文件 doc Document() doc.add_paragraph(ocr_text) timestamp datetime.datetime.now().strftime(%Y%m%d_%H%M%S) filename focr_results_{timestamp}.docx filepath f/tmp/{filename} doc.save(filepath) return filepath, fWord文件已生成: {filename} def export_as_xlsx(ocr_text): 导出为Excel文件 # 简单处理将每张图片的结果作为一行 entries [] current_entry {文件名: , 内容: } for line in ocr_text.split(\n): if line.startswith() and line.endswith(): if current_entry[文件名]: entries.append(current_entry) current_entry {文件名: line.strip( ), 内容: } else: current_entry[内容] line \n if current_entry[文件名]: entries.append(current_entry) df pd.DataFrame(entries) timestamp datetime.datetime.now().strftime(%Y%m%d_%H%M%S) filename focr_results_{timestamp}.xlsx filepath f/tmp/{filename} df.to_excel(filepath, indexFalse) return filepath, fExcel文件已生成: {filename}5.3 绑定导出事件export_txt_btn.click( fnexport_as_txt, inputstext_output, outputs[gr.File(label下载TXT), export_status] ) export_docx_btn.click( fnexport_as_docx, inputstext_output, outputs[gr.File(label下载Word), export_status] ) export_xlsx_btn.click( fnexport_as_xlsx, inputstext_output, outputs[gr.File(label下载Excel), export_status] )6. 完整功能测试与优化6.1 测试批量处理流程启动修改后的WebUIpython app.py访问http://服务器IP:7860上传多张图片5-10张点击批量识别所有图片检查识别结果是否包含所有图片的内容尝试各种导出格式确认文件内容正确6.2 添加进度提示为了提升用户体验我们可以添加处理进度提示def batch_recognize_with_progress(image_paths): 带进度提示的批量识别 total len(image_paths) progress_msgs [] results [] for i, img_path in enumerate(image_paths, 1): progress_msgs.append(f正在处理 {i}/{total}: {os.path.basename(img_path)}) try: result model.predict(img_path) results.append(f {os.path.basename(img_path)} \n{result}\n\n) except Exception as e: results.append(f {os.path.basename(img_path)} 识别失败 \n错误: {str(e)}\n\n) # 更新进度 yield \n.join(progress_msgs), .join(results) yield \n.join(progress_msgs [处理完成]), .join(results) # 修改按钮绑定 batch_btn.click( fnbatch_recognize_with_progress, inputsgallery, outputs[progress, text_output] )7. 总结通过本教程我们成功将Hunyuan-OCR-WEBUI从单张图片识别扩展为完整的批量处理工具主要实现了以下功能多文件上传支持一次性上传多张图片并在界面中预览管理批量识别一键识别所有上传图片中的文字内容多种导出格式支持将识别结果导出为TXT、Word和Excel格式进度提示实时显示处理进度提升用户体验这些改进使得Hunyuan-OCR在实际工作中的实用性大大增强特别是在需要处理大量图片的场景下效率提升显著。你可以在此基础上继续扩展比如添加自动命名规则、结果后处理如去除空格、格式化等功能。获取更多AI镜像想探索更多AI镜像和应用场景访问 CSDN星图镜像广场提供丰富的预置镜像覆盖大模型推理、图像生成、视频生成、模型微调等多个领域支持一键部署。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2426433.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!