Kendra 를 이용하여 영문 이미지에서 텍스트를 추출하고 번역하여 한국어로 검색하는 방법

3분 분량
콘텐츠 수준: 고급
0

해당 기사에서는 영문 이미지를 Rekognition으로 인식한후 Amazon Translate를 이용하여 한글로 번역한후 Kendra에서 검색할 수 있는 솔루션을 설명해드립니다.

사용사례

Amazon Kendra는 여러 데이터 소스에 존재하는 문서와 텍스트 유형의 데이터를 크롤링하여 검색 결과에 반영하는 지능형 검색 엔진 서비스입니다. 데이터를 추출하거나 데이터 소스 연결을 위한 커넥터를 만들거나 인덱스에 대한 튜닝 작업을 구현할 필요 없이, 몇 번의 클릭만으로 검색 인덱스를 생성하고 바로 쿼리할 수 있습니다. 실제 비즈니스의 자료는 텍스트에 그치지 않고 음성, 영상, 이미지등으로 다양합니다. 이러한 다양한 데이터에서 텍스트를 추출하여 검색할 수 있으면 자료를 활용하는 효율성이 증가할 것 입니다.

전제조건

  • Kendra가 지원되는 리전에 S3 버킷을 생성합니다( 아래의 예시의 경우 싱가폴 리전에 생성하였습니다.)
  • Python IDE가 존재해야합니다.
  • AWS Cli를 통해서 아래의 권한을 가진 IAM 사용자로 자격증명이 되어 있어야 합니다.
    • S3 FullAcess, RekognitionFullAccess, TranslateFullAccess

1단계 : Recognition으로 텍스트 추출 및 번역 후 S3에 파일 업로드

  • Pycharm과 같은 Python IDE를 실행시킵니다.
  • 아래의 코드를 붙여넣기 한뒤 <>로 되어있는 부분을 환경에 맞게 수정합니다. [1][2]
import boto3

s3_client = boto3.client('s3')
rekognition_client = boto3.client('rekognition')
translate_client = boto3.client('translate')

local_image_path = '<영문 이미지가 저장되어있는 절대 경로>'

with open(local_image_path, 'rb') as image_file:
    image_bytes = image_file.read()

response = rekognition_client.detect_text(
    Image={
        'Bytes': image_bytes
    }
)
lst=[]
for item in response['TextDetections']:
    lst.append(item['DetectedText'])
file_contents=' '.join(lst)

target_language_code = 'ko' 

response = translate_client.translate_text(
Text=file_contents,
SourceLanguageCode='en', 
TargetLanguageCode=target_language_code
)
translated_text = response['TranslatedText']

bucket_name = '<버킷 이름>'
file_name = '<S3 에 저장할 파일명>'

s3_client.put_object(Bucket=bucket_name, Key=file_name, Body=translated_text)

2단계: Kendra 인덱스 생성하기 [3]

  • 인덱스는 Amazon Kendra가 지원되는 싱가포르 리전에 생성합니다.
  • [Index name]에 원하는 인덱스 명을 입력합니다.
  • [IAM role]은 [Create a new role]로 선택하고 인덱스의 AmazonKendra- 를 포함한 역할 이름을 입력합니다.
  • 원하는 [Developer] 에디션을 클릭하고 [Create]를 클릭합니다.

Enter image description here

3단계: Kendra IAM역할 설정

  • [IAM],[IAM 역할]에서 AmazonKendra- 로 검색하여 역할을 찾습니다.
  • [Add permissions],[Create inline policy]를 클릭하여 아래의 JSON을 고객님의 환경에 맞게 수정하여 넣습니다.
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": [
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::BUCKET_NAME/*"
            ],
            "Effect": "Allow"
        },
        {
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::BUCKET_NAME"
            ],
            "Effect": "Allow"
        },
        {
            "Effect": "Allow",
            "Action": [
                "kendra:BatchPutDocument",
                "kendra:BatchDeleteDocument"
            ],
            "Resource": [
                "arn:aws:kendra:REGION:ACCOUNT_NUMBER:index/KENDRA_INDEX_ID"
            ]
        }
    ]
}

4단계: Kendra Datasource 설정

  • Amazon Kendra에서 만들어둔 index를 클릭합니다.
  • 좌측 패널에서 [Data management],[Data sources]를 클릭합니다.
  • [Data source name]를 입력하고 [Language]는 Korean (ko) 을 선택합니다.
  • [IAM role]에는 위에서 생성한 IAM Role을 입력합니다.
  • [Sync scope]의 [Enter the data source location]에 s3://BUCKET_NAME 을 입력합니다.
  • [Sync run schedule]의 [Frequency]는 [Run on demand]로 선택합니다.
  • 나머지 설정의 경우 기본적인 설정을 유지한채 데이터 소스를 생성합니다.

5단계: kendra에서 데이터 검색

  • Amazon Kendra 인덱스로 돌아와서 좌측 패널의 [Data sources]를 클릭하고 S3 데이터 소스를 선택합니다
  • [Sync now]를 클릭하여 업로드 된 객체를 크롤링합니다.
  • Sync의 상태가 Completed로 되면 좌측 패널에서 [Search indexed content]를 클릭합니다.
  • 우측의 [스패너], Language: Korean(ko), Query suggestion source: Query history 로 설정한뒤 저장합니다.
  • 검색창에서 검색할 수 있습니다.

Enter image description here

참고

[1] Rekognition : detect_text

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/rekognition/client/detect_text.html

[2] Translate: translate_text

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/translate/client/translate_text.html

[3] Amazon Kendra로 모든 유형의 자료 검색 구축하기 [1부-인덱스 생성과 문서 검색]

https://aws.amazon.com/ko/blogs/tech/building-search-foralltype-amazon-kendra/