머신러닝 API 통합

1. 개요

이 Codelab에서는 몇 가지 머신러닝 API를 간단히 살펴봅니다. 다음이 사용됩니다.

  • Cloud Vision을 사용하여 이미지의 콘텐츠 이해
  • Cloud Speech-to-Text를 사용하여 오디오를 텍스트로 변환
  • Cloud Translation을 사용하여 임의의 문자열을 지원되는 언어로 번역
  • Cloud Natural Language를 사용하여 텍스트에서 정보 추출

빌드할 항목

오디오 녹음 파일이미지를 비교하여 서로의 관련성을 판단하는 파이프라인을 구성합니다. 다음은 이를 달성하는 방법을 간략하게 보여줍니다.

e6a57e5def315116.jpeg

학습할 내용

  • Vision, Speech-to-Text, Translation, Natural Language API 사용 방법
  • 코드 샘플을 찾을 수 있는 위치

필요한 항목

  • 브라우저(Chrome 또는 Firefox 등)
  • Python에 관한 기본 지식

2. 설정 및 요구사항

자습형 환경 설정

  1. Cloud 콘솔에 로그인하고 새 프로젝트를 만들거나 기존 프로젝트를 다시 사용합니다. 아직 Gmail이나 Google Workspace 계정이 없는 경우 계정을 만들어야 합니다.

96a9c957bc475304.png

b9a10ebdf5b5a448.png

a1e3c01a38fa61c2.png

모든 Google Cloud 프로젝트에서 고유한 이름인 프로젝트 ID를 기억하세요(위의 이름은 이미 사용되었으므로 사용할 수 없습니다). 이 ID는 나중에 이 Codelab에서 PROJECT_ID라고 부릅니다.

  1. 그런 후 Google Cloud 리소스를 사용할 수 있도록 Cloud Console에서 결제를 사용 설정해야 합니다.

이 Codelab 실행에는 많은 비용이 들지 않습니다. 이 가이드를 마친 후 비용이 결제되지 않도록 리소스 종료 방법을 알려주는 '삭제' 섹션의 안내를 따르세요. Google Cloud 신규 사용자는 300달러(USD) 상당의 무료 체험판 프로그램에 참여할 수 있습니다.

API 사용 설정

링크를 클릭하여 필요한 모든 API를 사용 설정할 수 있습니다. 이렇게 한 후에는 인증 설정 안내를 무시해도 됩니다. Google에서 곧 설정해 드릴 것입니다. 또는 각 API를 개별적으로 사용 설정할 수 있습니다. 이렇게 하려면 화면 왼쪽 상단의 메뉴 아이콘을 클릭합니다.

2bfc27ef9ba2ec7d.png

드롭다운에서 API 및 서비스를 선택하고 대시보드를 클릭합니다.

a9546a22581facd5.png

API 및 서비스 사용 설정을 클릭합니다.

eae7ff043d13a35.png

그런 다음 검색창에서 'vision'을 검색합니다. Google Cloud Vision API를 클릭합니다.

a47893f36372ae2f.png

사용 설정을 클릭하여 Cloud Vision API를 사용 설정합니다.

a24fd082a22030ad.png

사용 설정될 때까지 몇 초간 기다립니다. 사용 설정되면 다음이 표시됩니다.

633e58cbde1b74c6.png

동일한 프로세스를 반복하여 Cloud Speech, Cloud Translation, Cloud Natural Language API를 사용 설정합니다.

Cloud Shell

Google Cloud Shell은 클라우드에서 실행되는 명령줄 환경입니다. 이 Debian 기반 가상 머신은 필요한 모든 개발 도구 (gcloud, bq, git 등)와 함께 로드되며, 영구 5GB 홈 디렉터리를 제공합니다. Cloud Shell을 사용하여 머신러닝 API에 대한 요청을 만듭니다.

Cloud Shell을 시작하려면 헤더 바의 오른쪽 상단에 있는 'Google Cloud Shell 활성화' Screen Shot 2015-06-08 at 5.30.32 PM.png 아이콘을 클릭합니다.

24ef50000ca737a4.png

콘솔 하단에 있는 새 프레임 내에 Cloud Shell 세션이 열리면서 명령줄 프롬프트가 표시됩니다. user@project:~$ 프롬프트가 표시될 때까지 기다립니다.

선택사항: 코드 편집기

명령줄에 익숙한 정도에 따라 Cloud Shell 표시줄의 오른쪽 상단에 있는 '코드 편집기 실행' b885bf07bc1b02e5.png 아이콘을 클릭할 수 있습니다.

de00be9278baf7b8.png

서비스 계정

인증을 위해 서비스 계정이 필요합니다. 서비스 계정을 만들려면 [NAME] 을 원하는 서비스 계정 이름으로 바꾸고 Cloud Shell에서 다음 명령어를 실행합니다.

gcloud iam service-accounts create [NAME]

이제 서비스 계정을 사용하는 키를 생성해야 합니다. [FILE_NAME] 을 원하는 키 이름으로, [NAME] 을 위의 서비스 계정 이름으로, [PROJECT_ID] 를 프로젝트 ID로 바꿉니다. 다음 명령어는 키를 [FILE_NAME].json으로 만들어 다운로드합니다.

gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

서비스 계정을 사용하려면 변수 GOOGLE_APPLICATION_CREDENTIALS를 키의 경로로 설정해야 합니다. 이렇게 하려면 [PATH_TO_FILE] 및 [FILE_NAME]을 바꾼 후 다음 명령어를 실행합니다.

export GOOGLE_APPLICATION_CREDENTIALS=[PATH_TO_FILE]/[FILE_NAME].json

3. Cloud Vision

Python 클라이언트

Cloud Vision용 Python 클라이언트가 필요합니다. 설치하려면 Cloud Shell에 다음을 입력합니다.

pip install --upgrade google-cloud-vision --user

사용해 보기

Cloud Vision API의 코드 샘플을 살펴보겠습니다. 특정 이미지에 포함된 내용을 확인하고 싶습니다. detect.py가 이 작업에 유용해 보이므로 이를 가져오겠습니다. 한 가지 방법은 detect.py의 콘텐츠를 복사하고 Cloud Shell에서 vision.py라는 새 파일을 만든 후 모든 코드를 vision.py에 붙여넣는 것입니다. Cloud Shell 코드 편집기에서 수동으로 이 작업을 수행하거나 Cloud Shell에서 다음 curl 명령어를 실행할 수 있습니다.

curl https://raw.githubusercontent.com/GoogleCloudPlatform/python-docs-samples/master/vision/cloud-client/detect/detect.py -o vision.py

이 단계를 완료한 후 Cloud Shell에서 다음을 실행하여 API를 사용합니다.

python vision.py labels-uri gs://cloud-samples-data/ml-api-codelab/birds.jpg

분석된 이미지가 https://storage.googleapis.com/cloud-samples-data/ml-api-codelab/birds.jpg이므로 새와 타조에 관한 출력이 표시됩니다.

어떤 문제인가요?

vision.py에 2개의 인수를 전달했습니다.

  • labels-uri는 실행할 detect_labels_uri() 함수를 선택합니다.
  • gs://cloud-samples-data/ml-api-codelab/birds.jpg는 Google Cloud Storage에 있는 이미지의 위치이며 detect_labels_uri()uri로 전달됩니다.

detect_labels_uri()을 자세히 살펴보겠습니다. 삽입된 추가 의견을 확인합니다.

def detect_labels_uri(uri):
    """Detects labels in the file located in Google Cloud Storage or on the
    Web."""
    # relevant import from above
    # from google.cloud import vision

    # create ImageAnnotatorClient object
    client = vision.ImageAnnotatorClient()

    # create Image object
    image = vision.types.Image()

    # specify location of image
    image.source.image_uri = uri

    # get label_detection response by passing image to client
    response = client.label_detection(image=image)

    # get label_annotations portion of response
    labels = response.label_annotations
    print('Labels:')

    for label in labels:
        # print the label descriptions
        print(label.description)

4. Cloud Speech-to-Text

Python 클라이언트

Cloud Speech-to-Text용 Python 클라이언트가 필요합니다. 설치하려면 Cloud Shell에 다음을 입력합니다.

sudo pip install --upgrade google-cloud-speech

사용해 보기

Cloud Speech-to-Text 코드 샘플로 이동해 보겠습니다. 음성 오디오를 텍스트로 변환하는 데 관심이 있습니다. transcribe.py이 시작하기에 적합해 보이므로 이를 사용하겠습니다. transcribe.py의 콘텐츠를 복사하고 Cloud Shell에서 speech2text.py라는 새 파일을 만든 후 모든 코드를 speech2text.py에 붙여넣습니다. Cloud Shell 코드 편집기에서 수동으로 이 작업을 수행하거나 Cloud Shell에서 다음 curl 명령어를 실행할 수 있습니다.

curl https://raw.githubusercontent.com/GoogleCloudPlatform/python-docs-samples/master/speech/cloud-client/transcribe.py -o speech2text.py

이 단계를 완료한 후 Cloud Shell에서 다음을 실행하여 API를 사용합니다.

python speech2text.py gs://cloud-samples-data/ml-api-codelab/tr-ostrich.wav

잘못된 인코딩과 샘플 헤르츠 비율에 관한 오류가 표시되어야 합니다. 걱정하지 마세요. 코드에서 transcribe_gcs()로 이동하여 RecognitionConfig()에서 encodingsampe_hertz_rate 설정을 삭제하세요. tr-ostrich.wav은 튀르키예어 음성 녹음이므로 언어 코드를'tr-TR'로 변경하세요.

config = types.RecognitionConfig(language_code='tr-TR')

이제 speech2text.py를 다시 실행합니다. 분석된 오디오가 https://storage.googleapis.com/cloud-samples-data/ml-api-codelab/tr-ostrich.wav이므로 출력은 터키어 텍스트여야 합니다.

어떤 상황인가요?

Google Cloud Storage에 있는 오디오 파일의 위치인 gs://cloud-samples-data/ml-api-codelab/tr-ostrich.wavspeech2text.py에 전달했습니다. 그러면 speech2text.pytranscribe_uri()gcs_uri로 전달됩니다.

수정된 transcribe_uri()를 자세히 살펴보겠습니다.

def transcribe_gcs(gcs_uri):
    """Transcribes the audio file specified by the gcs_uri."""

    from google.cloud import speech
    # enums no longer used
    # from google.cloud.speech import enums
    from google.cloud.speech import types

    # create ImageAnnotatorClient object
    client = speech.SpeechClient()

    # specify location of speech
    audio = types.RecognitionAudio(uri=gcs_uri)

    # set language to Turkish
    # removed encoding and sample_rate_hertz
    config = types.RecognitionConfig(language_code='tr-TR')

    # get response by passing config and audio settings to client
    response = client.recognize(config, audio)

    # Each result is for a consecutive portion of the audio. Iterate through
    # them to get the transcripts for the entire audio file.
    for result in response.results:
        # The first alternative is the most likely one for this portion.
        # get the transcript of the first alternative
        print(u'Transcript: {}'.format(result.alternatives[0].transcript))

5. Cloud Translation

Python 클라이언트

Cloud Translation용 Python 클라이언트가 필요합니다. 설치하려면 Cloud Shell에 다음을 입력합니다.

sudo pip install --upgrade google-cloud-translate

사용해 보기

이제 Cloud Translation 코드 샘플을 확인해 보겠습니다. 이 Codelab에서는 텍스트를 영어로 번역하려고 합니다. snippets.py이 우리가 원하는 것 같습니다. snippets.py의 콘텐츠를 복사하고 Cloud Shell에서 translate.py라는 새 파일을 만들어 모든 코드를 translate.py에 붙여넣습니다. Cloud Shell 코드 편집기에서 수동으로 이 작업을 수행하거나 Cloud Shell에서 다음 curl 명령어를 실행할 수 있습니다.

curl https://raw.githubusercontent.com/GoogleCloudPlatform/python-docs-samples/master/translate/cloud-client/snippets.py -o translate.py

이 단계를 완료한 후 Cloud Shell에서 다음을 실행하여 API를 사용합니다.

python translate.py translate-text en '你有沒有帶外套'

번역은 '외투 있어?'여야 합니다.

어떤 상황인가요?

translate.py에 3개의 인수를 전달했습니다.

  • translate-text는 실행할 translate_text() 함수를 선택합니다.
  • entranslate_text()target으로 전달되어 번역할 언어를 지정하는 역할을 합니다.
  • '你有沒有帶外套'은 번역할 문자열이며 translate_text()text로 전달됩니다.

translate_text()을 자세히 살펴보겠습니다. 추가된 댓글을 확인합니다.

def translate_text(target, text):
    """Translates text into the target language.

    Target must be an ISO 639-1 language code.
    See https://g.co/cloud/translate/v2/translate-reference#supported_languages
    """
    # relevant imports from above
    # from google.cloud import translate
    # import six

    # create Client object
    translate_client = translate.Client()

    # decode text if it's a binary type
    # six is a python 2 and 3 compatibility library
    if isinstance(text, six.binary_type):
        text = text.decode('utf-8')

    # get translation result by passing text and target language to client
    # Text can also be a sequence of strings, in which case this method
    # will return a sequence of results for each text.
    result = translate_client.translate(text, target_language=target)

    # print original text, translated text and detected original language
    print(u'Text: {}'.format(result['input']))
    print(u'Translation: {}'.format(result['translatedText']))
    print(u'Detected source language: {}'.format(
        result['detectedSourceLanguage']))

6. Cloud Natural Language

Python 클라이언트

Cloud Natural Language용 Python 클라이언트가 필요합니다. 설치하려면 Cloud Shell에 다음을 입력합니다.

sudo pip install --upgrade google-cloud-language

사용해 보기

마지막으로 Cloud Natural Language API 코드 샘플을 살펴보겠습니다. 텍스트에서 항목을 감지하려고 합니다. snippets.py에는 이 작업을 실행하는 코드가 포함된 것으로 보입니다. snippets.py의 콘텐츠를 복사하고 Cloud Shell에서 natural_language.py라는 새 파일을 만들어 모든 코드를 natural_language.py에 붙여넣습니다. Cloud Shell 코드 편집기에서 수동으로 이 작업을 수행하거나 Cloud Shell에서 다음 curl 명령어를 실행할 수 있습니다.

curl https://raw.githubusercontent.com/GoogleCloudPlatform/python-docs-samples/master/language/cloud-client/v1/snippets.py -o natural_language.py

이 단계를 완료한 후 Cloud Shell에서 다음을 실행하여 API를 사용합니다.

python natural_language.py entities-text 'where did you leave my bike'

API는 'bike'를 엔티티로 식별해야 합니다. 항목은 고유 명사 (유명 인사, 명소 등) 또는 보통 명사 (식당, 경기장 등)일 수 있습니다.

어떤 상황인가요?

natural_language.py에 2개의 인수를 전달했습니다.

  • entities-text는 실행할 entities_text() 함수를 선택합니다.
  • '내 자전거 어디에 뒀어?'는 항목을 분석할 문자열이며 entities_text()text로 전달됩니다.

entities_text()을 자세히 살펴보겠습니다. 삽입된 새 댓글을 확인합니다.

def entities_text(text):
    """Detects entities in the text."""
    # relevant imports from above
    # from google.cloud import language
    # from google.cloud.language import enums
    # from google.cloud.language import types
    # import six

    # create LanguageServiceClient object
    client = language.LanguageServiceClient()

    # decode text if it's a binary type
    # six is a python 2 and 3 compatibility library
    if isinstance(text, six.binary_type):
        text = text.decode('utf-8')

    # Instantiates a plain text document.
    document = types.Document(
        content=text,
        type=enums.Document.Type.PLAIN_TEXT)

    # Detects entities in the document. You can also analyze HTML with:
    #   document.type == enums.Document.Type.HTML
    entities = client.analyze_entities(document).entities

    # entity types from enums.Entity.Type
    entity_type = ('UNKNOWN', 'PERSON', 'LOCATION', 'ORGANIZATION',
                   'EVENT', 'WORK_OF_ART', 'CONSUMER_GOOD', 'OTHER')

    # print information for each entity found
    for entity in entities:
        print('=' * 20)
        print(u'{:<16}: {}'.format('name', entity.name))
        print(u'{:<16}: {}'.format('type', entity_type[entity.type]))
        print(u'{:<16}: {}'.format('metadata', entity.metadata))
        print(u'{:<16}: {}'.format('salience', entity.salience))
        print(u'{:<16}: {}'.format('wikipedia_url',
              entity.metadata.get('wikipedia_url', '-')))

7. 통합하기

무엇을 빌드하고 있는지 다시 한번 확인해 보겠습니다.

e6a57e5def315116.jpeg

이제 모든 내용을 합쳐 보겠습니다. solution.py 파일을 만들고 이전 단계에서 detect_labels_uri(), transcribe_gcs(), translate_text(), entities_text()를 복사하여 solution.py에 붙여넣습니다.

Import 문

가져오기 문을 주석 해제하고 맨 위로 이동합니다. speech.typeslanguage.types이 모두 가져와지고 있습니다. 이렇게 하면 충돌이 발생하므로 이를 삭제하고 transcribe_gcs()entities_text()에서 types의 각 개별 항목을 각각 speech.typeslanguage.types로 변경하겠습니다. 다음과 같은 결과가 표시됩니다.

from google.cloud import vision
from google.cloud import speech
from google.cloud import translate
from google.cloud import language
from google.cloud.language import enums
import six

결과 반환

출력하는 대신 함수가 결과를 반환하도록 합니다. 다음과 비슷한 내용이 표시됩니다.

# import statements

def detect_labels_uri(uri):
    # code

    # we only need the label descriptions
    label_descriptions = []
    for label in labels:
        label_descriptions.append(label.description)

    return label_descriptions

def transcribe_gcs(gcs_uri):
    # code

    # naive assumption that audio file is short
    return response.results[0].alternatives[0].transcript

def translate_text(target, text):
    # code

    # only interested in translated text
    return result['translatedText']

def entities_text(text):
    # code

    # we only need the entity names
    entity_names = []
    for entity in entities:
        entity_names.append(entity.name)

    return entity_names

함수 사용

이 모든 작업을 마친 후에는 이러한 함수를 호출할 수 있습니다. 지금 바로 해 보세요. 예를 들면 다음과 같습니다.

def compare_audio_to_image(audio, image):
    """Checks whether a speech audio is relevant to an image."""

    # speech audio -> text
    transcription = transcribe_gcs(audio)

    # text of any language -> english text
    translation = translate_text('en', transcription)

    # text -> entities
    entities = entities_text(translation)

    # image -> labels
    labels = detect_labels_uri(image)

    # naive check for whether entities intersect with labels
    has_match = False
    for entity in entities:
        if entity in labels:
            # print result for each match
            print('The audio and image both contain: {}'.format(entity))
            has_match = True

    # print if there are no matches
    if not has_match:
        print('The audio and image do not appear to be related.')

여러 언어 지원

이전에는 transcribe_gcs()에 튀르키예어를 하드 코딩했습니다. compare_audio_to_image()에서 언어를 지정할 수 있도록 변경해 보겠습니다. 필요한 변경사항은 다음과 같습니다.

def transcribe_gcs(language, gcs_uri):
    ...
    config = speech.types.RecognitionConfig(language_code=language)
def compare_audio_to_image(language, audio, image):
    transcription = transcribe_gcs(language, audio)

직접 해 보기

최종 코드는 이 GitHub 저장소solution.py에서 확인할 수 있습니다. 다음은 이를 가져오는 curl 명령어입니다.

curl https://raw.githubusercontent.com/googlecodelabs/integrating-ml-apis/master/solution.py -O

GitHub의 버전에는 argparse가 포함되어 있어 명령줄에서 다음을 허용합니다.

python solution.py tr-TR gs://cloud-samples-data/ml-api-codelab/tr-ball.wav gs://cloud-samples-data/ml-api-codelab/football.jpg

발견된 각 항목에 대해 코드에서 '오디오와 이미지에 모두 포함된 항목: '을 출력해야 합니다. 위의 예에서는 '오디오와 이미지에 모두 포함된 항목: ball'이 됩니다.

보너스: 더 많은 기능 사용해 보기

다음은 시도해 볼 수 있는 오디오 및 이미지 파일 위치입니다.

tr-TR 음성 샘플:gs://cloud-samples-data/ml-api-codelab/tr-ball.wavgs://cloud-samples-data/ml-api-codelab/tr-bike.wavgs://cloud-samples-data/ml-api-codelab/tr-jacket.wavgs://cloud-samples-data/ml-api-codelab/tr-ostrich.wav

de-DE 음성 샘플:gs://cloud-samples-data/ml-api-codelab/de-ball.wavgs://cloud-samples-data/ml-api-codelab/de-bike.wavgs://cloud-samples-data/ml-api-codelab/de-jacket.wavgs://cloud-samples-data/ml-api-codelab/de-ostrich.wav

이미지 샘플:gs://cloud-samples-data/ml-api-codelab/bicycle.jpggs://cloud-samples-data/ml-api-codelab/birds.jpggs://cloud-samples-data/ml-api-codelab/coat_rack.jpggs://cloud-samples-data/ml-api-codelab/football.jpg

8. 축하합니다.

네 가지 머신러닝 API를 살펴보고 통합하여 음성 샘플이 제공된 이미지를 설명하는지 확인했습니다. 이 파이프라인을 개선할 방법은 훨씬 더 많으므로 이는 시작에 불과합니다.

학습한 내용

  • Cloud Vision API에 요청 보내기
  • Cloud Speech-to-Text API에 요청하기
  • Cloud Translation API에 요청하기
  • Cloud Natural Language API에 요청하기
  • 위의 API를 모두 함께 사용

다음 단계