Machine Learning API 통합

Machine Learning API 통합

이 Codelab 정보

subject최종 업데이트: 6월 30, 2021
account_circle작성자: Torry Yang

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 Console에 로그인하고 새 프로젝트를 만들거나 기존 프로젝트를 다시 사용합니다. 아직 Gmail이나 Google Workspace 계정이 없는 경우 계정을 만들어야 합니다.

9,699c957bc475304.png

b9a10ebdf5b5a447.png

A1e3c01a38fa61c2.png

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

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

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

API 사용 설정

이 링크를 클릭하여 필요한 모든 API를 사용 설정할 수 있습니다. 그런 다음 인증 설정에 대한 안내를 무시해도 됩니다. 잠시 후 설정하겠습니다. 또는 각 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을 사용하여 Machine Learning API에 대한 요청을 생성합니다.

Cloud Shell을 시작하려면 헤더 표시줄의 오른쪽 상단에 있는 'Google Cloud Shell 활성화' Screen Shot 2015-06-08 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을(를) 시작하는 것부터 즐거운 시간을 보낼 수 있습니다. transcript.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&#39'로 변경합니다.

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에서 오디오 파일의 위치인 speech2text.pygs://cloud-samples-data/ml-api-codelab/tr-ostrich.wav를 전달했습니다. 그런 다음 gcs_uritranscribe_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가 원하는 것 같습니다. snippet.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()에 전달됩니다.

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에 이러한 코드가 포함된 것 같습니다. snippet.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는 항목으로 \'자전거{/2}를 식별해야 합니다. 항목은 고유 명사 (유명 인사, 명소 등) 또는 공통 명사 (음식점, 경기장 등)일 수 있습니다.

어떤 상황인가요?

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

  • entity-text가 실행할 entities_text() 함수를 선택합니다.
  • ‘자전거를 떠났나요?’는 항목에 관한 분석 문자열이며 textentities_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 문

주석 처리를 삭제하고 import 문을 상단으로 이동합니다. speech.typeslanguage.types을 모두 가져오는 중입니다. 이렇게 하면 충돌이 발생하므로 transcribe_gcs()entities_text()의 각 개별 일치하는 항목을 삭제하고 각각 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

발견된 각 항목의 코드는 다음과 같이 출력되어야 합니다. '오디오'와 '이미지'는 모두 "를 포함합니다. 위의 예에서는 '오디오'와 '이미지'에 모두 '볼'이 포함됩니다.

보너스: 더 활용하기

시도해 볼 오디오 및 이미지 파일 위치가 더 있습니다.

8. 수고하셨습니다.

음성 API가 제공된 이미지에 대해 말하는지 여부를 결정하기 위해 네 가지 머신러닝 API를 살펴보고 통합해 보았습니다. 이 방법은 개선의 여지가 많습니다.

학습한 내용

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

다음 단계