返回

Video Intelligence API 403 权限拒绝?别担心,这里有解决方案!

python

Video Intelligence API 403 权限拒绝:解决方法指南

简介

在使用 Google Cloud Platform (GCP) 的 Video Intelligence API 时,你可能遇到过令人沮丧的“403 权限拒绝”错误。这可能是由于各种原因造成的,包括权限问题、防火墙设置和 API 版本不兼容。本指南将详细介绍这些错误背后的原因,并提供一步步的解决方案,以帮助你解决问题并继续使用 API。

错误原因

  • 权限不足: 你可能没有授予你的服务帐户访问 Video Intelligence API 的必要权限。
  • 防火墙规则: 你的网络防火墙可能阻止了对 API 端点的访问。
  • API 版本不兼容: 你可能使用的是不再受支持的 API 版本(例如 v1)。

解决方案

1. 启用 Video Intelligence API

  • 前往 GCP Console 并确保 Video Intelligence API 已启用。

2. 授予服务帐户权限

  • 授予你的服务帐户“视频智能 API Admin”角色。

3. 检查防火墙规则

  • 确保允许从你的网络访问 video-intelligence.googleapis.comvideo-intelligence.googleapis.com:443

4. 更新 API 版本

  • 如果你是使用 v1 版本的 API,请迁移到 v1p3beta1 版本。

代码示例

在更新权限、防火墙规则和 API 版本后,以下 Python 代码示例展示了如何使用 Video Intelligence API 分析视频文件的露骨内容:

import io
from google.cloud import videointelligence_v1p3beta1 as videointelligence

# path = 'path_to_file'

config = videointelligence.StreamingVideoConfig(
    feature=(videointelligence.StreamingFeature.STREAMING_EXPLICIT_CONTENT_DETECTION)
)

# Set the chunk size to 5MB (recommended less than 10MB).
chunk_size = 5 * 1024 * 1024

stream = []
with io.open(path, "rb") as video_file:
    while True:
        data = video_file.read(chunk_size)
        if not data:
            break
        stream.append(data)

def stream_generator():
    yield config_request
    for chunk in stream:
        yield videointelligence.StreamingAnnotateVideoRequest(input_content=chunk)

requests = stream_generator()

client = videointelligence.StreamingVideoIntelligenceServiceClient()
responses = client.streaming_annotate_video(requests, timeout=600)

# Process responses.
explicit_annotations = responses.annotation_results.explicit_annotation.frames
if explicit_annotations:
    for annotation in explicit_annotations:
        # Each annotation has one frame, which has a timeoffset.
        frame = annotation.time_offset
        time_offset = frame.seconds + frame.microseconds / 1e6

        pornography_likelihood = videointelligence.Likelihood(annotation.pornography_likelihood)
        print("{}s: {} (likelihood: {})".format(time_offset, pornography_likelihood, annotation.pornography_likelihood))

结论

通过遵循这些步骤并更新你的权限、防火墙规则和 API 版本,你应该能够解决 Video Intelligence API 中的“403 权限拒绝”错误。祝你顺利使用该 API,并提取有价值的视频见解。

常见问题解答

  • 我仍然收到“403 权限拒绝”错误,怎么办?

检查你的网络连接、防火墙设置和 GCP 项目状态。

  • 我使用的是 v1 版本的 API,该如何迁移?

参考官方迁移指南进行迁移:https://cloud.google.com/video-intelligence/docs/sdks/python-docs

  • 我在更新防火墙规则时遇到困难,有什么建议?

创建新的防火墙规则,并确保允许所有必要端口的出入站连接。

  • 我无法授予服务帐户权限,我需要做什么?

确保你拥有必要的权限,并授予服务帐户“视频智能 API Admin”角色。

  • 使用 Video Intelligence API 时,我应该注意什么其他问题?

留意 API 的限制和定价,并使用最佳实践来优化你的使用。