Ошибка API Cloud Video Intelligence 400 и 504 - PullRequest
1 голос
/ 24 апреля 2020

Когда я пытался вызвать Cloud Video Intelligence API для обнаружения c субтитров в локальном видеофайле . Всегда возвращалась ошибка 400 или 504, но использование газа в порядке. Я пытался настроить время ожидания в Конфигурация Cloud Video Intelligence, но она по-прежнему показывает ошибку 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)

Это отчет об ошибке:

    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
...