You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python新手求助:如何将Azure Function转换为常规Python脚本并本地运行?

将Azure Function文档分析脚本转换为本地Python脚本

以下是转换完成的本地可运行Python脚本,保留原功能同时适配本地环境:

import logging
import json
import re
import uuid

from azure.ai.formrecognizer import DocumentAnalysisClient
from azure.core.credentials import AzureKeyCredential
from azure.storage.blob import BlockBlobService, PublicAccess

# 配置日志,本地运行输出到控制台
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

def upload_blob(account_name, container_name, account_key, blob_name):
    # 创建Blob服务客户端
    blob_service_client = BlockBlobService(
        account_name=account_name,
        account_key=account_key)
    # 设置容器权限为公开(方便Form Recognizer访问)
    blob_service_client.set_container_acl(container_name, public_access=PublicAccess.Container)
    # 生成Blob的公开访问URL
    blob_url = blob_service_client.make_blob_url(container_name, blob_name)
    return blob_url

def delete_blob(account_name, container_name, account_key, blob_name):
    blob_service_client = BlockBlobService(
        account_name=account_name,
        account_key=account_key)
    # 从容器中删除指定Blob
    blob_service_client.delete_blob(container_name, blob_name)

def search_value(kvs, search_key):
    # 忽略大小写搜索键值对中的目标键
    for key, value in kvs.items():
        if re.search(search_key, key, re.IGNORECASE):
            return value

def analyze_general_documents(endpoint, api_key, doc_url):
    # 初始化文档分析客户端
    document_analysis_client = DocumentAnalysisClient(
        endpoint=endpoint, credential=AzureKeyCredential(api_key)
    )
    # 开始分析文档(从URL)
    poller = document_analysis_client.begin_analyze_document_from_url("prebuilt-document", doc_url)
    result = poller.result()
    
    kvs = {}
    # 清理文档内容(去除换行符)
    content = result.content.replace("\n", "").replace("\r", "").strip()
    # 提取文档中的键值对
    for kv_pair in result.key_value_pairs:
        if kv_pair.key and kv_pair.value:
            key = kv_pair.key.content
            val = kv_pair.value.content
            kvs[key] = val
    return content, kvs

def main():
    try:
        # --------------------------
        # 请在这里填写你的Azure服务参数
        # --------------------------
        endpoint = "你的Form Recognizer服务端点"
        api_key = "你的Form Recognizer API密钥"
        account_name = "你的Azure存储账户名"
        container_name = "你的存储容器名"
        account_key = "你的存储账户密钥"
        
        # --------------------------
        # 请在这里设置要处理的Blob名称和搜索键
        # --------------------------
        blob_name = "要分析的文档Blob名称(比如example.pdf)"
        search_keys = ["需要搜索的键1", "需要搜索的键2"]

        logger.info(f"搜索键列表: {search_keys}")

        # 生成Blob的公开访问URL
        logger.info("生成Blob访问URL")
        blob_url = upload_blob(account_name, container_name, account_key, blob_name)
        logger.info(f"Blob URL: {blob_url}")

        # 分析文档并提取键值对
        logger.info("开始分析文档")
        content, kvs = analyze_general_documents(endpoint, api_key, blob_url)
        logger.info(f"提取到的键值对: {kvs}")

        # 根据搜索键筛选结果
        search_results = {}
        for search_key in search_keys:
            val = search_value(kvs, search_key)
            if val:
                search_results[search_key] = val
        logger.info(f"搜索结果: {search_results}")

        # 删除Blob(如果不需要删除可以注释掉这一行)
        delete_blob(account_name, container_name, account_key, blob_name)
        logger.info("已删除目标Blob")

        # 输出最终结果
        print("\n=== 最终搜索结果 ===")
        print(json.dumps(search_results, ensure_ascii=False, indent=2))

    except Exception as e:
        logger.error(f"运行出错: {str(e)}")
        print(f"错误信息: {str(e)}")

if __name__ == "__main__":
    main()

主要修改点:

  • 移除Azure Functions依赖:删除import azure.functions as func,替换HTTP请求逻辑为本地参数配置和控制台输出
  • 添加日志配置:通过logging.basicConfig设置控制台日志输出,方便本地调试
  • 简化参数输入:将原函数中从HTTP请求获取的参数,改为直接在代码中配置(添加明确注释提示填写)
  • 替换返回逻辑:将func.HttpResponse改为控制台打印结果,适配本地运行场景
  • 优化代码可读性:添加中文注释说明每个步骤,调整键值对提取逻辑(确保键和值都存在才添加)

使用步骤:

  1. 安装依赖包:运行pip install azure-ai-formrecognizer azure-storage-blob
  2. 填写代码中的Azure服务参数:包括Form Recognizer端点、密钥,以及存储账户的相关信息
  3. 设置要处理的Blob名称和需要搜索的键列表
  4. 运行脚本:执行python 脚本文件名.py

内容的提问来源于stack exchange,提问作者a_python_newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 12:50:21