python调用百度ai/腾讯云将图片/pdf识别为表格excel

百度AI

表格文字识别(异步接口)

图片转excel

百度ai官方文档:https://ai.baidu.com/ai-doc/OCR/Ik3h7y238
使用的是表格文字识别(异步接口),同步接口已经下线

在这里插入图片描述

import requests
import json
import base64
import time
'''
文档:https://ai.baidu.com/ai-doc/OCR/Ik3h7y238
'''

# 获取access_token地址:https://console.bce.baidu.com/ai/#/ai/ocr/app/list
def get_access_token():
    client_id = "xxxxxxxxxxxxxxxxxx" # 你的apikey
    client_secret = "xxxxxxxxxxxxxxxxxxxxxx" # 你的Secret Key
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(
        client_id, client_secret)
    response = requests.get(host).text
    data = json.loads(response)
    access_token = data['access_token']
    return access_token

# 获取识别结果
def get_info(access_token):
    request_url = "https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/request"
    # 二进制方式打开图片文件
    f = open('1.jpg', 'rb')
    img = base64.b64encode(f.read())  # base64编码
    params = {"image": img}
    request_url = request_url + "?access_token=" + access_token
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    response = requests.post(request_url, data=params, headers=headers)
    # if response:
    #     print(response.json())
    data_1 = response.json()
    return data_1


# 获取excel

def get_excel(requests_id, access_token):
    headers = {'content-type': 'application/x-www-form-urlencoded'}
    pargams = {
        'request_id': requests_id,
        'result_type': 'excel'
    }
    url = 'https://aip.baidubce.com/rest/2.0/solution/v1/form_ocr/get_request_result'
    url_all = url + "?access_token=" + access_token
    res = requests.post(url_all, headers=headers, params=pargams)  # 访问链接获取excel下载页
    info_1 = res.json()['result']['ret_msg']
    excel_url = res.json()['result']['result_data']
    excel_1 = requests.get(excel_url).content
    print(excel_1)
    with open('识别结果.xls', 'wb+') as f:
        f.write(excel_1)
    print(info_1)


def main():
    print('正在处理中请稍后')
    access_token = get_access_token()
    data_1 = get_info(access_token)
    try:
        requests_id = data_1['result'][0]['request_id']
        if requests_id != '':
            print('识别完成')
    except:
        print('识别错误')
    print('正在获取excel')
    time.sleep(10)  # 延时十秒让网页图片转excel完毕,excel量多的话,转化会慢,可以延时长一点
    get_excel(requests_id, access_token)


main()

表格文字识别V2

图片/pdf转excel通用

import requests
import json
import base64

CLIENT_ID = "xxxxxxxxxxxxxxxxx"  # 你的apikey,需要修改
CLIENT_SECRET = "xxxxxxxxxxxxxxxxxxxxx"  # 你的Secret Key,需要修改


# 获取access_token
def get_access_token():
    auth_url = 'https://aip.baidubce.com/oauth/2.0/token'
    params = {
        'grant_type': 'client_credentials',
        'client_id': CLIENT_ID,
        'client_secret': CLIENT_SECRET,
    }
    response = requests.post(auth_url, data=params)
    data = response.json()
    access_token = data.get('access_token')
    if not access_token:
        raise "请输入正确的client_id 和 client_secret"
    return access_token


def save_excel(b64_excel, excel_name):
    # 将base64编码的excel文件解码并保存为本地文件
    excel = base64.b64decode(b64_excel)
    with open(excel_name, 'wb') as f:
        f.write(excel)


def to_excel(file_path, excel_name):
    access_token = get_access_token()
    request_url = "https://aip.baidubce.com/rest/2.0/ocr/v1/table"

    # 以二进制方式打开图片文件,并将其转换为base64编码
    with open(file_path, 'rb') as f:
        file = base64.b64encode(f.read())
    ext = file_path.split('.')[-1]
    if ext in ['jpg', 'jpeg', 'png', 'bmp']:
        # 图片格式
        data = {
            "image": file,
            "return_excel": 'true',
        }
    elif ext == 'pdf':
        # pdf格式
        data = {
            "pdf_file": file,
            "return_excel": 'true',
        }
    headers = {'content-type': 'application/x-www-form-urlencoded'}

    # 发送POST请求进行表格文字识别
    response = requests.post(request_url, params={'access_token': access_token}, data=data, headers=headers)
    if response.ok:
        data = response.json()
        # 将返回的excel文件保存到本地
        save_excel(data.get('excel_file', ''), excel_name)
        print('转换完成')
    else:
        print('转换失败')


if __name__ == '__main__':
    img_path = '1.png'  # 要转换的图片文件名
    pdf_path = 'table.pdf'  # 要转换的pdf文件名
    to_excel(file_path=img_path, excel_name='out_pic.xlsx')  # 转换后的excel文件名
    to_excel(file_path=pdf_path, excel_name='out_pdf.xlsx')  # 转换后的excel文件名

在这里插入图片描述

腾讯云表格识别(V2)

表格识别(V2):https://cloud.tencent.com/document/product/866/49525

import base64
import json
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


def encode_image_to_base64(image_path):
    """将图像编码为 base64 字符串。"""
    with open(image_path, 'rb') as f:
        return base64.b64encode(f.read()).decode()


def save_base64_to_file(base64_data, file_path):
    """将 base64 字符串保存到文件。"""
    with open(file_path, 'wb') as f:
        f.write(base64.b64decode(base64_data))


def recognize_table_ocr(image_path, output_excel_path):
    try:
        # 实例化一个认证对象,入参需要传入腾讯云账户 SecretId 和 SecretKey
        # # 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
        cred = credential.Credential("这里填入SecretId", "这里填入SecretKey")
        # 实例化一个http选项
        httpProfile = HttpProfile()
        httpProfile.endpoint = "ocr.tencentcloudapi.com"

        # 实例化一个client选项
        clientProfile = ClientProfile()
        clientProfile.httpProfile = httpProfile
        # 实例化要请求产品的client对象
        client = ocr_client.OcrClient(cred, "ap-beijing", clientProfile)

        # 实例化一个请求对象
        req = models.RecognizeTableOCRRequest()
        file = encode_image_to_base64(image_path)
        params = {
            "ImageBase64": file
        }
        req.from_json_string(json.dumps(params))

        # 返回的resp是一个RecognizeTableOCRResponse的实例
        resp = client.RecognizeTableOCR(req)

        # 保存Base64 编码后的 Excel 数据到文件
        save_base64_to_file(resp.Data, output_excel_path)
        print(f"Excel 文件已保存到 {output_excel_path}")

    except TencentCloudSDKException as err:
        print(err)


# 使用示例
recognize_table_ocr('测试.png', 'output.xlsx')

  • 5
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
使用Python调用百度API并将结果保存为表格可以通过以下步骤实现: 1. 导入所需模块:首先,需要导入所需的Python模块,例如requests和pandas。requests模块用于发送HTTP请求,而pandas模块用于处理数据和创建表格。 2. 获取百度API的访问密钥:在百度API开放平台上注册并创建一个应用程序,然后获取访问密钥。将该密钥用于接下来的API调用。 3. 构建API请求:使用requests模块构建一个HTTP请求以调用百度API。根据所需的API类型和参数,可以构建不同的请求。例如,如果要调用百度地图API获取某个地区的信息,可以构建一个GET请求,并在URL中包含所需的参数。 4. 解析API响应:发送API请求后,会收到一个API响应。可以使用requests模块将响应解析为一个Python字典或JSON对象。 5. 创建表格并保存数据:使用pandas模块创建一个数据框(DataFrame)来保存API响应中的数据。可以使用pandas的方法和函数对数据框进行操作和转换,然后将结果保存为一个表格文件(如CSV、Excel等)。 6. 完善代码:处理可能出现的异常情况,例如网络连接错误或API调用限制等。可以使用try-except语句来捕获并处理这些异常。 7. 运行代码:运行Python脚本,将调用百度API并将结果保存为表格。 总结:使用Python调用百度API并将结果保存为表格需要以下步骤:导入所需模块、获取百度API的访问密钥、构建API请求、解析API响应、创建表格并保存数据、完善代码、运行代码。这样可以在Python环境中方便地调用百度API并将结果保存为表格

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞得更高肥尾沙鼠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值