Python 3.x 云视频智能API错误400&;504

Python 3.x 云视频智能API错误400&;504,python-3.x,google-api,video-intelligence-api,Python 3.x,Google Api,Video Intelligence Api,当我试图调用云视频智能API来检测本地视频文件中的字幕时。它总是返回错误400或504,但使用gas是可以的。我尝试在云视频智能配置中调整超时,但它仍然显示错误400,参数无效 这是我检测视频字幕的python代码: """This application demonstrates detection subtitles in video using the Google Cloud API. Usage Examples: use video in google cloud sto

当我试图调用云视频智能API来检测本地视频文件中的字幕时。它总是返回错误400或504,但使用gas是可以的。我尝试在云视频智能配置中调整超时,但它仍然显示错误400,参数无效

这是我检测视频字幕的python代码:

"""This application demonstrates detection subtitles in video using the Google Cloud API.

Usage Examples:

    use video in google cloud storge:
        python analyze.py text_gcs gs://"video path"
    use video in computer:
        python analyze.py text_file video.mp4

"""

import argparse
import io
from google.cloud import videointelligence
from google.cloud.videointelligence import enums


def video_detect_text_gcs(input_uri):
    # [START video_detect_text_gcs]
    """Detect text in a video stored on GCS."""
    from google.cloud import videointelligence

    video_client = videointelligence.VideoIntelligenceServiceClient()
    features = [videointelligence.enums.Feature.TEXT_DETECTION]
    config = videointelligence.types.TextDetectionConfig(language_hints=["zh-TW","en-US"])
    video_context = videointelligence.types.VideoContext(text_detection_config=config)

    operation = video_client.annotate_video(input_uri=input_uri, features=features, video_context=video_context)

    print("\nSubtitle detecting......")
    result = operation.result(timeout=300)

    # The first result is retrieved because a single video was processed.
    annotation_result = result.annotation_results[0]
    subtitle_data=[ ]
    for text_annotation in annotation_result.text_annotations:
        text_segment = text_annotation.segments[0]
        start_time = text_segment.segment.start_time_offset
        frame = text_segment.frames[0]
        vertex=frame.rotated_bounding_box.vertices[0]
        if text_segment.confidence > 0.95 and vertex.y >0.7:
         lists=[text_annotation.text,start_time.seconds+ start_time.nanos * 1e-9,vertex.y]
         subtitle_data=subtitle_data+[lists]
    length=len(subtitle_data)
    subtitle_sort=sorted(subtitle_data,key = lambda x: (x[1],x[2]))
    i=0
    subtitle=[ ]
    while i<length :
        subtitle=subtitle+[subtitle_sort[i][0]]
        i=i+1

    with open("subtitle.txt",mode="w",encoding="utf-8") as file:
       for x in subtitle:
            file.write(x+'\n')




def video_detect_text(path):
    # [START video_detect_text]
    """Detect text in a local video."""
    from google.cloud import videointelligence

    video_client = videointelligence.VideoIntelligenceServiceClient()
    features = [videointelligence.enums.Feature.TEXT_DETECTION]
    video_context = videointelligence.types.VideoContext()

    with io.open(path, "rb") as file:
        input_content = file.read()

    operation = video_client.annotate_video(
        input_content=input_content,  # the bytes of the video file
        features=features,
        video_context=video_context
    )
    print("\nSubtitle detecting......")
    result = operation.result(timeout=300)

    # The first result is retrieved because a single video was processed.
    annotation_result = result.annotation_results[0]
    subtitle_data=[ ]
    for text_annotation in annotation_result.text_annotations:
        text_segment = text_annotation.segments[0]
        start_time = text_segment.segment.start_time_offset
        frame = text_segment.frames[0]
        vertex=frame.rotated_bounding_box.vertices[0]
        if text_segment.confidence > 0.95 and vertex.y >0.7:
         lists=[text_annotation.text,start_time.seconds+ start_time.nanos * 1e-9,vertex.y]
         subtitle_data=subtitle_data+[lists]
    length=len(subtitle_data)
    subtitle_sort=sorted(subtitle_data,key = lambda x: (x[1],x[2]))
    i=0
    subtitle=[ ]
    while i<length :
        subtitle=subtitle+[subtitle_sort[i][0]]
        i=i+1

    with open("subtitle.txt",mode="w",encoding="utf-8") as file:
       for x in subtitle:
            file.write(x+'\n')



if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
    )
    subparsers = parser.add_subparsers(dest="command")

    detect_text_parser = subparsers.add_parser(
        "text_gcs", help=video_detect_text_gcs.__doc__
    )
    detect_text_parser.add_argument("path")

    detect_text_file_parser = subparsers.add_parser(
        "text_file", help=video_detect_text.__doc__
    )
    detect_text_file_parser.add_argument("path")



    args = parser.parse_args()


    if args.command == "text_gcs":
        video_detect_text_gcs(args.path)
    if args.command == "text_file":
        video_detect_text(args.path)
”此应用程序演示使用Google Cloud API在视频中检测字幕。
用法示例:
在谷歌云存储中使用视频:
python analyze.py text_gcs gs://“视频路径”
在计算机中使用视频:
python analyze.py text_文件video.mp4
"""
导入argparse
输入io
从google.cloud导入视频智能
从google.cloud.videointelligence导入枚举
def视频检测文本gcs(输入uri):
#[启动视频\u检测\u文本\u gcs]
“”“检测存储在GCS上的视频中的文本。”“”
从google.cloud导入视频智能
video\u client=videointelligence.VideoIntelligenceServiceClient()
features=[videointelligence.enums.Feature.TEXT\u检测]
config=videointelligence.types.TextDetectionConfig(语言提示=[“zh-TW”,“en-US”])
video\u context=videointelligence.types.VideoContext(text\u detection\u config=config)
操作=视频\客户端。注释\视频(输入\ uri=输入\ uri,功能=功能,视频\上下文=视频\上下文)
打印(“\n标题检测…”)
结果=操作。结果(超时=300)
#检索第一个结果是因为处理了单个视频。
注释结果=结果。注释结果[0]
副标题_数据=[]
对于批注结果中的文本批注。文本批注:
text\u段=text\u注释。段[0]
开始时间=文本段。段。开始时间偏移
帧=文本\段。帧[0]
顶点=帧。旋转的边界框。顶点[0]
如果text_segment.confidence>0.95且vertex.y>0.7:
lists=[text\u annotation.text,start\u time.seconds+start\u time.nanos*1e-9,vertex.y]
字幕数据=字幕数据+[列表]
长度=长度(副标题数据)
subtitle_sort=排序(subtitle_数据,key=lambda x:(x[1],x[2]))
i=0
副标题=[]
当i 0.95和vertex.y>0.7时:
lists=[text\u annotation.text,start\u time.seconds+start\u time.nanos*1e-9,vertex.y]
字幕数据=字幕数据+[列表]
长度=长度(副标题数据)
subtitle_sort=排序(subtitle_数据,key=lambda x:(x[1],x[2]))
i=0
副标题=[]

i400表示您向服务器发送的请求未被接受。504表示服务器在返回响应之前超时。这有帮助吗?400表示您向服务器发送的请求未被接受。504表示服务器在返回响应之前超时。这有用吗?
    Ghuang@/Users/Ghuang/Documents/GitHub/Video-subtitles-detection$ python3 analyze.py text_file video.mp4
Traceback (most recent call last):
  File "/Users/Ghuang/Library/Python/3.7/lib/python/site-packages/google/api_core/grpc_helpers.py", line 57, in error_remapped_callable
    return callable_(*args, **kwargs)
  File "/Users/Ghuang/Library/Python/3.7/lib/python/site-packages/grpc/_channel.py", line 826, in __call__
    return _end_unary_response_blocking(state, call, False, None)
  File "/Users/Ghuang/Library/Python/3.7/lib/python/site-packages/grpc/_channel.py", line 729, in _end_unary_response_blocking
    raise _InactiveRpcError(state)
grpc._channel._InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
    status = StatusCode.DEADLINE_EXCEEDED
    details = "Deadline Exceeded"
    debug_error_string = "{"created":"@1587691109.677447000","description":"Error received from peer ipv4:172.217.24.10:443","file":"src/core/lib/surface/call.cc","file_line":1056,"grpc_message":"Deadline Exceeded","grpc_status":4}"
>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "analyze.py", line 144, in <module>
    video_detect_text(args.path)
  File "analyze.py", line 90, in video_detect_text
    video_context=video_context
  File "/Library/Python/3.7/site-packages/google/cloud/videointelligence_v1/gapic/video_intelligence_service_client.py", line 303, in annotate_video
    request, retry=retry, timeout=timeout, metadata=metadata
  File "/Users/Ghuang/Library/Python/3.7/lib/python/site-packages/google/api_core/gapic_v1/method.py", line 143, in __call__
    return wrapped_func(*args, **kwargs)
  File "/Users/Ghuang/Library/Python/3.7/lib/python/site-packages/google/api_core/retry.py", line 286, in retry_wrapped_func
    on_error=on_error,
  File "/Users/Ghuang/Library/Python/3.7/lib/python/site-packages/google/api_core/retry.py", line 184, in retry_target
    return target()
  File "/Users/Ghuang/Library/Python/3.7/lib/python/site-packages/google/api_core/timeout.py", line 214, in func_with_timeout
    return func(*args, **kwargs)
  File "/Users/Ghuang/Library/Python/3.7/lib/python/site-packages/google/api_core/grpc_helpers.py", line 59, in error_remapped_callable
    six.raise_from(exceptions.from_grpc_error(exc), exc)
  File "<string>", line 3, in raise_from
google.api_core.exceptions.DeadlineExceeded: 504 Deadline Exceeded