python - 发票识别

1. 环境准备

安装相关的库

pip3 install fitz -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install PyMuPDF -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install paddleocr -i https://pypi.tuna.tsinghua.edu.cn/simple
pip3 install paddlepaddle -i https://mirror.baidu.com/pypi/simple

2. 提取内容

  1. 发票号码
  2. 开票日期
  3. 销售方名称
  4. 销售方纳税人识别号
  5. 金额
import fitz
from paddleocr import PaddleOCR
from openpyxl import load_workbook

pdf = fitz.open('test.pdf')
page = pdf.load_page(0)  # 获取第0页
# 提高分辨率
pix = page.get_pixmap()
zoom_x = 8
zoom_y = 8
mat = fitz.Matrix(zoom_x, zoom_y)
pix = page.get_pixmap(matrix=mat, alpha=False)
pix.save('temp.png')

# for i in range(pdf.page_count):
#     page = pdf.load_page(i)  # 获取第i页
#     pix = page.get_pixmap()
#     zoom_x = 8
#     zoom_y = 8
#     mat = fitz.Matrix(zoom_x, zoom_y)
#     pix = page.get_pixmap(matrix=mat, alpha=False)
#     pix.save('temp.png')

ocr = PaddleOCR(use_angle_cls = True, use_gpu = False, lang='ch')
res = ocr.ocr('temp.png', cls=True)
invoice_dic = {}
for r in res[0]:
    text = r[1][0]
    if text.startswith('发票号码:'):
        invoice_dic.update({'number': text[5:]})
        print(f"number:{text[5:]}")
    if text.startswith('开票日期:'):
        invoice_dic.update({'date': text[5:]})
        print(f"date:{text[5:]}")
    if text.startswith('名称:'):
        if text.endswith('购买方名称'):
            continue
        invoice_dic.update({'name': text[3:]})
        print(f"name:{text[3:]}")
    if text.startswith('统一社会信用代码/纳税人识别号:'):
        if text.endswith('购买方统一社会信用代码/纳税人识别号'):
            continue
        invoice_dic.update({'id': text[16:]})
        print(f"id:{text[16:]}")
    if text.startswith('(小写)¥'):
        invoice_dic.update({'price': text[6:]})
        print(f"price:{text[6:]}")

提取出来后写入已有的xlsx文件
image

wb = load_workbook('test.xlsx') # 打开一个文件
ws = wb.active
nrow = ws.max_row # 取得行数
append_row = nrow + 1

ws.cell(append_row, 1).value = invoice_dic['number']
ws.cell(append_row, 2).value = invoice_dic['date']
ws.cell(append_row, 3).value = invoice_dic['name']
ws.cell(append_row, 4).value = invoice_dic['id']
ws.cell(append_row, 5).value = invoice_dic['price']

wb.save('test.xlsx')
posted @ 2023-07-16 10:52  wstong  阅读(823)  评论(0编辑  收藏  举报