-- coding: utf-8 --

This file is auto-generated, don't edit it. Thanks.

import sys import base64 import os

from typing import List

from alibabacloud_tea_openapi.client import Client as OpenApiClient from alibabacloud_tea_openapi import models as open_api_models from alibabacloud_tea_util import models as util_models from alibabacloud_openapi_util.client import Client as OpenApiUtilClient

class Sample: def init(self): pass

@staticmethod
def create_client(
    access_key_id: str,
    access_key_secret: str,
) -> OpenApiClient:
    """
    使用AK&SK初始化账号Client
    @param access_key_id:
    @param access_key_secret:
    @return: Client
    @throws Exception
    """
    config = open_api_models.Config(
        # 必填,您的 AccessKey ID,
        access_key_id=access_key_id,
        # 必填,您的 AccessKey Secret,
        access_key_secret=access_key_secret
    )
    # 访问的域名
    config.endpoint = f'documentautoml.cn-beijing.aliyuncs.com'
    return OpenApiClient(config)

@staticmethod
def create_api_info() -> open_api_models.Params:
    """
    API 相关
    @param path: params
    @return: OpenApi.Params
    """
    params = open_api_models.Params(
        # 接口名称,
        action='PredictTemplateModel',
        # 接口版本,
        version='2022-12-29',
        # 接口协议,
        protocol='HTTPS',
        # 接口 HTTP 方法,
        method='POST',
        auth_type='AK',
        style='RPC',
        # 接口 PATH,
        pathname=f'/',
        # 接口请求体内容格式,
        req_body_type='formData',
        # 接口响应体内容格式,
        body_type='json'
    )
    return params

@staticmethod
def main(
    args: List[str],
) -> None:
    # 工程代码泄露可能会导致AccessKey泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html
    client = Sample.create_client('LTAI4G1DuN8EfXdctDYZnbBG', 'fA8FdlPiT7cHErnZPmBID0xx7sbDn6')
    params = Sample.create_api_info()
    queries = {}
    queries['TaskId'] = 22091
    queries['BinaryToText'] = True
    runtime = util_models.RuntimeOptions()
    # 遍历文件夹中的所有图片
    folder_path = 'D:/1'
    result = ''
    for file_name in os.listdir(folder_path):
        if file_name.lower().endswith('.jpg') or file_name.lower().endswith('.png'):
            file_path = os.path.join(folder_path, file_name)
            with open(file_path, 'rb') as f:
                content = f.read()
                # 将图片内容转换为base64编码
                base64_content = base64.b64encode(content).decode('utf-8')
                body = {}
                body['Body'] = base64_content
                request = open_api_models.OpenApiRequest(
                    query=OpenApiUtilClient.query(queries),
                    body=body
                )
                # 调用API进行识别
                response = client.call_api(params, request, runtime)
                if response.get('status_code') == 200:
                    # 将识别结果保存到文本文件中
                    result += f'{file_name}:\n{response.body}\n\n'
    with open('1.txt', 'w', encoding='utf-8') as f:
        f.write(result)

@staticmethod
async def main_async(
    args: List[str],
) -> None:
    # 工程代码泄露可能会导致AccessKey泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考,建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/378659.html
    client = Sample.create_client('LTAI4G1DuN8EfXdctDYZnbBG', 'fA8FdlPiT7cHErnZPmBID0xx7sbDn6')
    params = Sample.create_api_info()
    queries = {}
    queries['TaskId'] = 22091
    queries['BinaryToText'] = True
    runtime = util_models.RuntimeOptions()
    # 遍历文件夹中的所有图片
    folder_path = 'D:/1'
    result = ''
    for file_name in os.listdir(folder_path):
        if file_name.lower().endswith('.jpg') or file_name.lower().endswith('.png'):
            file_path = os.path.join(folder_path, file_name)
            with open(file_path, 'rb') as f:
                content = f.read()
                # 将图片内容转换为base64编码
                base64_content = base64.b64encode(content).decode('utf-8')
                body = {}
                body['Body'] = base64_content
                request = open_api_models.OpenApiRequest(
                    query=OpenApiUtilClient.query(queries),
                    body=body
                )
                # 调用API进行识别
                response = await client.call_api_async(params, request, runtime)
                if response.status_code == 200:
                    # 将识别结果保存到文本文件中
                    result += f'{file_name}:\n{response.body}\n\n'
    with open('1.txt', 'w', encoding='utf-8') as f:
        f.write(result)

if name == 'main': Sample.main(sys.argv[1:])


原文地址: https://www.cveoy.top/t/topic/b58m 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录