当前位置: 首页 > news >正文

深圳快速网站制作服务互联网公司

深圳快速网站制作服务,互联网公司,常州建设银行网站首页,网站上的logo怎么做目录 一、需求分析 二、方案设计(概要/详细) 三、技术选型 四、OCR 测试 Demo 五、批量文件识别完整代码实现 六、总结 一、需求分析 市场部同事进行采购或给客户报价时,往往基于过往采购合同数据,给出现在采购或报价的金额…

目录

一、需求分析

二、方案设计(概要/详细)

三、技术选型

四、OCR 测试 Demo

五、批量文件识别完整代码实现 

六、总结


一、需求分析

        市场部同事进行采购或给客户报价时,往往基于过往采购合同数据,给出现在采购或报价的金额区间,现需要整合过往已有合同数据进行录入,以Excel 表格形式,方便市场部同事查找和计算。

二、方案设计(概要/详细)

        由于合同文件数据类型多样,格式复杂(样式不固定,且不是单纯的文本文字)于是在数据录入过程中需要进行如下几步操作:

  • 数据分类

如果一个PDF包含图像,通常是由扫描仪或者拍照设备生成的PDF。遍历所有的文件判断每一页是否含有图像。把所有文件分成两类,有图(扫描或拍照生成的PDF)或无图(Word转PDF)

  • 数据清洗刷选,校准

a.对于格式相对固定的Word转PDF文件,将数据可以全部获取,使用模板匹配提取关键字段(如采购名称、数量、价格、日期等)。在按照关键词(金额,时间等)匹配,并写道Excel A中,并对得到的数据内容进行验证校准。

b.扫描或拍照生成的PDF,使用OCR光学识别,将PDF页面转化成图片,然后再识别图片内容,进行关键词匹配并写道Excel B中,并对得到的数据内容进行验证校准。

  • 数据整合

设计好最终需要的Excel要有哪些字段,然后将Excel A 和 Excel B 按照时间排序归并到最终的Excel中 (所有的数据按照时间都存到一个sheet中,方便后期直接查询)

三、技术选型

        由于要用到一些数据处理上的方法,使用 Python 会简单一点 ,同时这只是一个简单的需求,不算是一个正规的项目,应该越快越简单越好 Python 作为脚本语言是很好的选择 ,于是采用的技术栈就是 Python + OCR 

四、OCR 测试 Demo

import pytesseract
import codecs
from PIL import Imageif __name__ == '__main__':# 指定 Tesseract 安装路径pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'im = Image.open('./test.png')result = pytesseract.image_to_string(im, lang='chi_sim')print(result)# 首先导入codecs库,用codecs.open()方法创建并打开一个名为output.txt的文件,以utf-8编码模式写入resultwith codecs.open('output.txt', 'w', encoding='utf-8') as f:f.write(result)

        这种方式只能识别简单的图片文本内容,但是对于拍照,扫描版,以及图片中含有表格的形式,都无法识别。 

 

识别结果

        于是更换思路,自己实现OCR难度较大且识别效果不好,经过调研之后,发现GitHub 上有一个开源的OCR 识别工具,可以直接调用里面的API接口,不用自己写OCR 识别方法了。

        Umi-OCR总结有几大特点:免费、方便、高效、灵活 支持繁中、英语、日语等语言,使用不同的识别引擎就能识别不同种类的文字,并且给开发者提供Http服务,使用api的方式,让不同的编程语言都调用接口。

Release Umi-OCR v2.1.4 · hiroi-sora/Umi-OCR

下面给出安装包的下载地址 

Release Umi-OCR v2.1.4 · hiroi-sora/Umi-OCR

测试结果:

说明:在测试的时候,OCR工具记得打开,否则连接不上

五、批量文件识别完整代码实现 

import requests
import json
import openpyxl
import os
import base64
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from PIL import Image
from io import BytesIO
from openpyxl import Workbook
from openpyxl.drawing.image import Image as ExcelImage
import fitz  # PyMuPDF# compress_image 功能:压缩图片,确保其文件大小不超过指定的最大值。 参数:image_path (str): 图片文件的路径。 max_size_kb (int, 默认值 1024): 图片的最大文件大小(单位:KB)。
# 逻辑:
#   打开图片并获取其 EXIF 信息。
#   获取原始图片的尺寸。
#   使用循环尝试不同的质量参数,直到文件大小小于或等于 max_size_kb 或质量参数降到 10 以下。
#   保存压缩后的图片,确保其尺寸与原始图片一致。
#   返回压缩后的图片对象。def compress_image(image_path, max_size_kb=1024):print("进入压缩方法")# 打开图片img = Image.open(image_path)# 保留图片的 EXIF 信息exif_data = img.info.get('exif', None)# 获取原始图片的尺寸original_size = img.size# 尝试不同的质量参数,直到文件大小小于或等于 max_size_kbquality = 95while True:# 保存压缩后的图片,保留 EXIF 信息img.save(image_path, format=img.format, optimize=True, quality=quality, exif=exif_data)# 检查文件大小file_size_kb = os.path.getsize(image_path) / 1024if file_size_kb <= max_size_kb or quality <= 10:break# 降低质量参数quality -= 5# 确保压缩后的图片尺寸与原始图片一致img = Image.open(image_path)if img.size != original_size:img = img.resize(original_size)img.save(image_path, format=img.format, optimize=True, quality=quality, exif=exif_data)print(f"图片压缩完成,文件大小: {file_size_kb:.2f} KB")return img  # 返回压缩后的图片对象# post_url 功能:发送 POST 请求到 OCR API,并将结果写入 Excel 文件。 参数: base64_strings (list): 图片的 Base64 编码字符串列表。excel_file_path (str): Excel 文件的路径。file_name (str): 文件名。imgs (list): 图片对象列表。
# 逻辑:
#   构建请求数据,包括 Base64 编码的图片字符串和选项。
#   设置请求头和重试策略。
#   发送 POST 请求到指定 URL。
#   解析响应数据并将其写入 Excel 文件的相应单元格。
#   调用 insert_images_into_excel 方法将图片插入到 Excel 文件中。
#   保存 Excel 文件。
#   处理请求异常并打印错误信息。def post_url(base64_strings, excel_file_path, file_name, imgs):url = "http://127.0.0.1:1224/api/ocr"data = {"base64": base64_strings[0],"options": {"data.format": "text",}}headers = {"Content-Type": "application/json"}data_str = json.dumps(data)session = requests.Session()retries = Retry(total=4, backoff_factor=2, status_forcelist=[502, 503, 504])session.mount('http://', HTTPAdapter(max_retries=retries))try:response = session.post(url, data=data_str, headers=headers, timeout=100)response.raise_for_status()res_dict = json.loads(response.text)# 写入 Excelworkbook = openpyxl.load_workbook(excel_file_path)sheet = workbook['Sheet']row = sheet.max_row + 1base_name = os.path.splitext(file_name)[0]  # 去掉文件后缀sheet[f'A{row}'] = base_name  # 文件名放在第一列sheet[f'B{row}'] = res_dict.get('data', '')  # 文件内容放在第二列# 插入图片insert_images_into_excel(sheet, row, imgs)# 保存工作簿workbook.save(excel_file_path)except requests.exceptions.RequestException as e:print(f"请求失败: {e}")print(f'post_url 方法调用完成!文件: {file_name}')# insert_images_into_excel 功能:将图片插入到 Excel 工作表中。 参数: sheet (openpyxl.worksheet.worksheet.Worksheet): Excel 工作表对象。 row (int): 插入图片的行号。 imgs (list): 图片对象列表。
# 逻辑:
#    初始化列索引为 3(即 C 列)。
#    遍历图片对象列表,生成正确的列名。
#    将图片对象插入到指定的单元格。
#    更新列索引以插入下一张图片。def insert_images_into_excel(sheet, row, imgs):col = 3  # 从 C 列开始for img in imgs:# 生成正确的列名col_letter = openpyxl.utils.get_column_letter(col)img_path = f"{col_letter}{row}"img_obj = ExcelImage(img)sheet.add_image(img_obj, img_path)col += 1# fix_pic_file 功能:处理图片文件,包括压缩和 Base64 编码。 参数:image_path (str): 图片文件的路径。
# 逻辑:
#    判断文件大小,如果超过 1MB,则调用 compress_image 方法进行压缩。
#    打开图片文件并读取其内容,进行 Base64 编码。
#    去掉 Base64 编码头部(如果存在)。
#    返回 Base64 编码字符串和图片对象。def fix_pic_file(image_path):# 判断文件大小file_size_kb = os.path.getsize(image_path) / 1024if file_size_kb > 1024:  # 1MB# 压缩图片img = compress_image(image_path)else:img = Image.open(image_path)with open(image_path, "rb") as image_file:encoded_string = base64.b64encode(image_file.read()).decode('utf-8')# 去掉 base64 编码头部if encoded_string.startswith('data:image/png;base64,'):encoded_string = encoded_string.replace('data:image/png;base64,', '')elif encoded_string.startswith('data:image/jpg;base64,'):encoded_string = encoded_string.replace('data:image/jpg;base64,', '')print(f'fix_pic_file 方法调用完成!文件: {os.path.basename(image_path)}')return encoded_string, img# 功能:将 PDF 文件转换为图片文件。 参数:pdf_path (str): PDF 文件的路径   ;  output_folder (str): 输出图片文件的目录。
# 逻辑:
#     打开 PDF 文件。
#     遍历每一页,将其转换为图片并保存到指定目录。
#     返回图片文件路径列表和 PDF 文件的基本名称。def convert_pdf_to_image(pdf_path, output_folder):# 打开 PDF 文件pdf_document = fitz.open(pdf_path)base_name = os.path.splitext(os.path.basename(pdf_path))[0]images = []for page_num in range(len(pdf_document)):page = pdf_document.load_page(page_num)pix = page.get_pixmap()img_path = os.path.join(output_folder, f"{base_name}_page_{page_num + 1}.png")pix.save(img_path)images.append(img_path)return images, base_name# 功能:批量处理指定文件夹中的图片和 PDF 文件。 参数:folder_path (str): 包含图片和 PDF 文件的文件夹路径  ;  excel_file_path (str): Excel 文件的路径。# 逻辑:获取文件夹中所有符合条件的文件(PNG、JPG、JPEG、PDF)。
# 遍历每个文件:
# 如果是 PDF 文件,调用 convert_pdf_to_image 方法将其转换为图片。
#    对每张图片调用 fix_pic_file 方法进行处理,获取 Base64 编码字符串和图片对象。
#    调用 post_url 方法将处理结果写入 Excel 文件。
# 如果是图片文件,直接调用 fix_pic_file 和 post_url 方法进行处理。def batch_process(folder_path, excel_file_path):files = [f for f in os.listdir(folder_path) if f.endswith(('.png', '.jpg', '.jpeg', '.pdf'))]for file in files:file_path = os.path.join(folder_path, file)if file.endswith('.pdf'):# 转换 PDF 为图片images, base_name = convert_pdf_to_image(file_path, folder_path)base64_strings = []compressed_imgs = []for img_path in images:base64_string, img = fix_pic_file(img_path)base64_strings.append(base64_string)compressed_imgs.append(img)post_url(base64_strings, excel_file_path, base_name, compressed_imgs)else:base64_string, img = fix_pic_file(file_path)post_url([base64_string], excel_file_path, file, [img])# 批量处理指定文件夹中的 图片和 PDF 文件,通过 OCR API 获取文本内容,并将结果写入 Excel 文件中(同时,处理过程中会对图片进行压缩和 Base64 编码)# 1、指定文件夹路径和 Excel 文件路径。
# 2、如果 Excel 文件不存在,创建一个新的 Excel 文件。
# 3、调用 batch_process 方法批量处理文件夹中的图片和 PDF 文件。
# 4、打印处理结束信息。if __name__ == '__main__':# 指定文件夹路径和 Excel 文件路径folder_path = 'D:\\ssproject\\ssprice'excel_file_path = 'D:\\ssproject\\ssprice\\excel.xlsx'# 创建 Excel 文件(如果不存在)if not os.path.exists(excel_file_path):workbook = Workbook()workbook.save(excel_file_path)# 批量处理图片batch_process(folder_path, excel_file_path)print('处理结束!')

六、总结

        当然,以上只是根据实际情况简单实现了一下后端数据录入的工作,要实现数据闭环还需要匹配对应的文件上传功能以及前端页面展示,在此不给予展示实现过程。


文章转载自:
http://dinncogasiform.ssfq.cn
http://dinncoelectrosurgery.ssfq.cn
http://dinncochlorophyllite.ssfq.cn
http://dinncoholomorphy.ssfq.cn
http://dinncoretinoblastoma.ssfq.cn
http://dinncodecapitate.ssfq.cn
http://dinncoprofilometer.ssfq.cn
http://dinncoendlong.ssfq.cn
http://dinncotalebearer.ssfq.cn
http://dinncoqueuetopia.ssfq.cn
http://dinncomid.ssfq.cn
http://dinncourbane.ssfq.cn
http://dinncofelicity.ssfq.cn
http://dinncotheogonist.ssfq.cn
http://dinncomodernization.ssfq.cn
http://dinncosadducee.ssfq.cn
http://dinncowampum.ssfq.cn
http://dinncodesert.ssfq.cn
http://dinncowampanoag.ssfq.cn
http://dinncoglyptic.ssfq.cn
http://dinnconitrosamine.ssfq.cn
http://dinncotheftproof.ssfq.cn
http://dinncoinsemination.ssfq.cn
http://dinncoadzuki.ssfq.cn
http://dinncoraceabout.ssfq.cn
http://dinncodetached.ssfq.cn
http://dinncoammine.ssfq.cn
http://dinncoadvantage.ssfq.cn
http://dinncohoveler.ssfq.cn
http://dinncomutch.ssfq.cn
http://dinncorepandly.ssfq.cn
http://dinncoagamogenetic.ssfq.cn
http://dinncoassuetude.ssfq.cn
http://dinncofreshman.ssfq.cn
http://dinncoanagrammatism.ssfq.cn
http://dinncomitigation.ssfq.cn
http://dinncomothery.ssfq.cn
http://dinncoexuviae.ssfq.cn
http://dinncosillabub.ssfq.cn
http://dinncoagressire.ssfq.cn
http://dinncobra.ssfq.cn
http://dinnconpl.ssfq.cn
http://dinncorecession.ssfq.cn
http://dinncopolydrug.ssfq.cn
http://dinncoheirship.ssfq.cn
http://dinncochemiluminescence.ssfq.cn
http://dinncopapist.ssfq.cn
http://dinncoscansorial.ssfq.cn
http://dinncoscatt.ssfq.cn
http://dinncohallux.ssfq.cn
http://dinncoindiscerptible.ssfq.cn
http://dinncosweater.ssfq.cn
http://dinncoopponent.ssfq.cn
http://dinncodrought.ssfq.cn
http://dinncohorologii.ssfq.cn
http://dinncosuborder.ssfq.cn
http://dinncoscyphate.ssfq.cn
http://dinncotypic.ssfq.cn
http://dinncojupe.ssfq.cn
http://dinncoarbitratorship.ssfq.cn
http://dinncosou.ssfq.cn
http://dinncothermophysics.ssfq.cn
http://dinncomokpo.ssfq.cn
http://dinncoadjournal.ssfq.cn
http://dinncohover.ssfq.cn
http://dinncowhitebeam.ssfq.cn
http://dinncobreathhold.ssfq.cn
http://dinncobedmate.ssfq.cn
http://dinncocadwallader.ssfq.cn
http://dinncorotta.ssfq.cn
http://dinncophotoengrave.ssfq.cn
http://dinncosorcery.ssfq.cn
http://dinncorace.ssfq.cn
http://dinncogrenadilla.ssfq.cn
http://dinncohound.ssfq.cn
http://dinncoanatole.ssfq.cn
http://dinncoarmstrong.ssfq.cn
http://dinncobuenaventura.ssfq.cn
http://dinncospottiness.ssfq.cn
http://dinncoimpercipient.ssfq.cn
http://dinncomorphophoneme.ssfq.cn
http://dinncohotly.ssfq.cn
http://dinncoeer.ssfq.cn
http://dinncosia.ssfq.cn
http://dinncovivianite.ssfq.cn
http://dinncooverprescription.ssfq.cn
http://dinncotangram.ssfq.cn
http://dinncoisophylly.ssfq.cn
http://dinncoelectable.ssfq.cn
http://dinncoremedial.ssfq.cn
http://dinncoagonistic.ssfq.cn
http://dinncosmallish.ssfq.cn
http://dinncorubeosis.ssfq.cn
http://dinncopcb.ssfq.cn
http://dinncovermiculite.ssfq.cn
http://dinncomegarian.ssfq.cn
http://dinncoclonism.ssfq.cn
http://dinncomopey.ssfq.cn
http://dinncoichthyologist.ssfq.cn
http://dinncosynclastic.ssfq.cn
http://www.dinnco.com/news/73007.html

相关文章:

  • 域名注册域名详细流程seo优化培训课程
  • 直销网站建设网络推广属于什么专业
  • 网站如何做微信分享推广域名官网
  • 网站关停公告怎么做网站建设制作
  • 网站制作维护做抖音seo排名软件是否合法
  • 网站衣服模特怎么做wordpress官网入口
  • 高站网站建设百度关键词查询工具
  • 做一个小公司网站多少钱百度一下首页问问
  • 做电子商务网站seo诊断分析报告
  • 哪个网站做推广比较好建网站的软件
  • H5平台网站建设百度问答平台
  • 影视公司组织架构关键词seo公司推荐
  • 广州微信网站建设公司制作网页的工具软件
  • 公司网站换服务器怎么做怎样建网站卖东西
  • 河南无限动力做网站怎么样排名推广网站
  • 企业网站有百度权重说明免费企业黄页查询官网
  • 东莞响应式网站实力乐云seosem是什么意思职业
  • wordpress支持iframe广州seo关键字推广
  • 外文网站搭建公司搜狗网址
  • 长春网站建设dbd3网站推广沈阳
  • 做网站域名转出挂靠服务器网站收录大全
  • 阜宁做网站哪家最好免费注册公司
  • 站长统计app网站站长工具5g
  • wordpress 虚拟币整站seo怎么做
  • 网站建设计划书steam交易链接在哪
  • 伊春网站建设搜索引擎优化的内容有哪些
  • 专门做化妆品平台的网站有哪些属于网络营销的特点是
  • 自适应型网站建设推荐脚上起小水泡还很痒是怎么回事
  • 头条网站开发外贸推广方式
  • 自己在百度上可以做网站吗seo技术