python调用腾讯云接口,实现财务发票混贴模式下,批量识别并转存excel表格的功能

一、腾讯云文字识别OCR接口:通用票据识别(高级版),识别效果图(转载于腾讯云官网):

在这里插入图片描述

二、准备工作

1、安装python,本文用PyCharm演示代码。

2、注册腾讯云(需要实名认证),获取API访问密匙:SecretId和SecretKey:

在这里插入图片描述
在这里插入图片描述

3、申请腾讯云免费使用额度,每月可免费识别1000张混贴财务发票:

在这里插入图片描述

4、阅读api接口参数说明文档:

在这里插入图片描述
在这里插入图片描述

5、准备文件夹用于存放待识别的混贴发票

在这里插入图片描述

三、python代码调试

1、以下代码用于识别发票大类type为3的增值税发票,发票子类型包括增值税纸质专票、增值税纸质普票、增值税电子专票、增值税电子普票、区块链电子发票、增值税电子普通发票(通行费):

import json
import base64
import os
import pandas
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.ocr.v20181119 import ocr_client, models

PNG_path = r'C:\Users\Administrator\Desktop\invoices'  # 文件夹路径
list01 = os.listdir(PNG_path)

cred = credential.Credential("SecretId", "SecretKey")
httpProfile = HttpProfile()
httpProfile.endpoint = "ocr.tencentcloudapi.com"
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
client = ocr_client.OcrClient(cred, "ap-guangzhou", clientProfile)
req = models.RecognizeGeneralInvoiceRequest()

SingleInvoiceInfos = []
SingleInvoiceInfos2 = []
newary = []

for ids in list01:
    print(ids)
    try:
        with open(os.path.join(PNG_path, ids), 'rb') as fp:
            file_content = fp.read()
            image_base64 = base64.b64encode(file_content)
        params = {
            "ImageBase64": str(image_base64, encoding="utf-8"),
        }
        req.from_json_string(json.dumps(params))
        resp = client.RecognizeGeneralInvoice(req)

        result1 = json.loads(resp.to_json_string())
        # print(result1)

        for item in result1['MixedInvoiceItems']:
            if item['Type'] == 3:
                VatInvoiceName = item['SubType']
                # print(item['SingleInvoiceInfos'][VatInvoiceName])
                # SingleInvoiceInfos.append(item['SingleInvoiceInfos'])
                # print(item['SingleInvoiceInfos'])
                newary.append({'发票文件名': ids,
                               '发票类别-腾讯云':VatInvoiceName,
                               '发票种类': item['SingleInvoiceInfos'][VatInvoiceName]['Title'],
                               '发票代码': item['SingleInvoiceInfos'][VatInvoiceName]['Code'],
                               '发票号码': item['SingleInvoiceInfos'][VatInvoiceName]['Number'],
                               '开票日期': item['SingleInvoiceInfos'][VatInvoiceName]['Date'],
                               '校验码': item['SingleInvoiceInfos'][VatInvoiceName]['CheckCode'],
                               '合计金额': item['SingleInvoiceInfos'][VatInvoiceName]['PretaxAmount'],
                               '合计税额': item['SingleInvoiceInfos'][VatInvoiceName]['Tax'],
                               '价税合计(小写)': item['SingleInvoiceInfos'][VatInvoiceName]['Total'],
                               '价税合计(大写)': item['SingleInvoiceInfos'][VatInvoiceName]['TotalCn'],
                               '购买方名称': item['SingleInvoiceInfos'][VatInvoiceName]['Buyer'],
                               '购买方纳税人识别号': item['SingleInvoiceInfos'][VatInvoiceName]['BuyerTaxID'],
                               '购买方地址及电话': item['SingleInvoiceInfos'][VatInvoiceName]['BuyerAddrTel'],
                               '购买方银行及账户': item['SingleInvoiceInfos'][VatInvoiceName]['BuyerBankAccount'],
                               '销售方名称': item['SingleInvoiceInfos'][VatInvoiceName]['Seller'],
                               '销售方纳税人识别号': item['SingleInvoiceInfos'][VatInvoiceName]['SellerTaxID'],
                               '销售方地址及电话': item['SingleInvoiceInfos'][VatInvoiceName]['SellerAddrTel'],
                               '销售方银行及账户': item['SingleInvoiceInfos'][VatInvoiceName]['SellerBankAccount'],
                               '收款人': item['SingleInvoiceInfos'][VatInvoiceName]['Receiptor'],
                               '复核人': item['SingleInvoiceInfos'][VatInvoiceName]['Reviewer'],
                               '开票人': item['SingleInvoiceInfos'][VatInvoiceName]['Issuer'],
                               '备注': item['SingleInvoiceInfos'][VatInvoiceName]['Remark']})

    except TencentCloudSDKException as err:
        print(err)

print(newary)

newsdf = pandas.DataFrame(newary,
                          columns=['发票文件名', '发票类别-腾讯云', '发票种类', '发票代码', '发票号码', '开票日期', '校验码', '合计金额', '合计税额', '价税合计(小写)', '价税合计(大写)', '购买方名称',
                                   '购买方纳税人识别号', '购买方地址及电话', '购买方银行及账户', '销售方名称', '销售方纳税人识别号', '销售方地址及电话', '销售方银行及账户',
                                   '收款人', '复核人', '开票人', '备注'])
newsdf.to_excel('增值税发票信息统计' + '-' + '腾讯云API接口-发票与其他单据混贴' + '.xlsx')

2、发票识别数据转存excel后,最终结果如下图:

在这里插入图片描述

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
实现基于Python发票批量识别并录入到Excel表格,需要以下步骤: 1. 安装OCR库:在Python中,可以使用Tesseract、PyOCR等OCR库进行文字识别。需要先安装相应的OCR库和语言包。 2. 批量读取发票图片:使用Python中的os库批量读取指定文件夹下的所有发票图片。 3. 图片预处理:对于不同的图片,需要进行不同的预处理,包括二值化、去噪、切割等。 4. 文字识别:使用OCR库对图片进行文字识别,获取发票的信息。 5. 将信息写入Excel表格:使用Python中的pandas库将发票信息写入Excel表格。 下面是一个简单的代码示例: ```python import os import pytesseract import cv2 import pandas as pd # 设置OCR库路径 pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files (x86)\Tesseract-OCR\tesseract.exe' # 读取发票图片 img_folder = r'C:\invoices' img_files = os.listdir(img_folder) # 定义数据框 data = pd.DataFrame(columns=['Invoice Number', 'Date', 'Amount']) # 循环处理每张图片 for img_file in img_files: # 读取图片 img_path = os.path.join(img_folder, img_file) img = cv2.imread(img_path) # 图片预处理 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) opened = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) # 文字识别 text = pytesseract.image_to_string(opened, lang='chi_sim') # 解析发票信息 invoice_number = '' date = '' amount = '' # TODO: 根据实际情况解析发票信息 # 将信息添加到数据框 data = data.append({'Invoice Number': invoice_number, 'Date': date, 'Amount': amount}, ignore_index=True) # 将数据框写入Excel表格 data.to_excel('invoices.xlsx', index=False) ``` 需要注意的是,发票信息的解析需要根据实际情况进行调整,例如需要根据发票的格式进行切割和匹配。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值