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

运行Azure认知服务OCR报错:KeyError: 'VISION_ENDPOINT'

解决KeyError: 'VISION_ENDPOINT'问题

你的代码当前是从系统环境变量中读取Azure Computer Vision的端点和密钥,但你通过命令行参数-k和-e传递的值并没有被代码处理,导致找不到对应环境变量触发KeyError。以下是三种可行的解决方式:

方式1:修改代码接收命令行参数

使用Python的argparse模块解析命令行传入的参数,替换原本从环境变量读取的逻辑:

import argparse
import json
import os
import azure.ai.vision as sdk

# 新增:解析命令行参数
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--endpoint", required=True, help="Azure Vision Endpoint")
parser.add_argument("-k", "--key", required=True, help="Azure Vision Subscription Key")
args = parser.parse_args()

# 读取JSON文件(保留原有逻辑)
f = open("C:\\Users\\xxx\\xxx\\Documents\\ocr\\xxx.json")
data = json.load(f)
f.close()

# 使用命令行参数替换环境变量读取
service_options = sdk.VisionServiceOptions(args.endpoint, args.key)

# 以下保留原有代码逻辑
vision_source = sdk.VisionSource(
    url="https://learn.microsoft.com/azure/ai-services/computer-vision/media/quickstarts/presentation.png")

analysis_options = sdk.ImageAnalysisOptions()
analysis_options.features = (
    sdk.ImageAnalysisFeature.CAPTION |
    sdk.ImageAnalysisFeature.TEXT
)
analysis_options.language = "en"
analysis_options.gender_neutral_caption = True

image_analyzer = sdk.ImageAnalyzer(service_options, vision_source, analysis_options)
result = image_analyzer.analyze()

if result.reason == sdk.ImageAnalysisResultReason.ANALYZED:
    if result.caption is not None:
        print(" Caption:")
        print("   '{}', Confidence {:.4f}".format(result.caption.content, result.caption.confidence))
    if result.text is not None:
        print(" Text:")
        for line in result.text.lines:
            points_string = "{" + ", ".join([str(int(point)) for point in line.bounding_polygon]) + "}"
            print("   Line: '{}', Bounding polygon {}".format(line.content, points_string))
            for word in line.words:
                points_string = "{" + ", ".join([str(int(point)) for point in word.bounding_polygon]) + "}"
                print("     Word: '{}', Bounding polygon {}, Confidence {:.4f}"
                      .format(word.content, points_string, word.confidence))
else:
    error_details = sdk.ImageAnalysisErrorDetails.from_result(result)
    print(" Analysis failed.")
    print("   Error reason: {}".format(error_details.reason))
    print("   Error code: {}".format(error_details.error_code))
    print("   Error message: {}".format(error_details.message))

修改后,你可以继续用原来的命令行方式运行:

python sample.py -e "your_endpoint" -k "your_subscription_key"

方式2:设置系统环境变量后运行脚本

不需要修改代码,先在终端设置环境变量,再执行脚本:

Windows命令提示符(CMD)

set VISION_ENDPOINT=your_endpoint
set VISION_KEY=your_subscription_key
python sample.py

Windows PowerShell

$env:VISION_ENDPOINT="your_endpoint"
$env:VISION_KEY="your_subscription_key"
python sample.py

Linux/macOS终端

export VISION_ENDPOINT=your_endpoint
export VISION_KEY=your_subscription_key
python sample.py

方式3:临时硬编码参数(不推荐用于生产环境)

如果只是临时测试,可以直接在代码中替换环境变量读取的部分,注意不要把密钥提交到版本控制系统:

# 替换原有service_options的代码
service_options = sdk.VisionServiceOptions("your_endpoint", "your_subscription_key")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 17:57:32