🙌

Cloud Translation API を使った自動 PDF 翻訳を実現してみた

2025/02/05に公開
1

初めに

こんにちは。クラウドエース第三開発部の王です。
グローバル化が進む現代、多言語対応の重要性がますます増しています。企業や組織では、異なる言語での文書管理や共有が求められる場面が増加しており、迅速かつ正確な翻訳が不可欠です。しかし、膨大な数の PDF ファイルを手作業で翻訳するのは、時間やコストの面で非効率的です。

そこで本記事では、Google Cloud Translation API を活用し、PDF ファイルの翻訳を自動化する方法をご紹介します。Cloud Storage、Cloud Functions、そして Cloud Translation API を組み合わせたアーキテクチャを構築し、PDF ファイルをアップロードするだけで自動的に翻訳が行われる仕組みを作ります。

アーキテクチャ概要

このプロジェクトのアーキテクチャは以下のようになります。

  1. Cloud Storage: 入力用バケットに PDF ファイルをアップロード。
  2. Cloud Functions: ストレージイベントをトリガーとして、Cloud Translation API を呼び出し、翻訳を実行。
  3. Cloud Storage: 出力用バケットに翻訳後の PDF ファイルを保存。

構成図

実現手順

1. Cloud Storage バケットの作成

最初に、Google Cloud Console または gcloud CLI を使用して 2 つの Cloud Storage バケットを作成します。

  • 入力用バケット(例: pdf-input-japanese
    アップロードされた元の PDF ファイルを保存します。

  • 出力用バケット(例: pdf-output-english
    翻訳後の PDF ファイルを保存します。

以下は gcloud コマンドを使った例です:

gcloud storage buckets create gs://pdf-input-japanese --location=${REGION}
gcloud storage buckets create gs://pdf-output-english --location=${REGION}

2. Cloud Function のコードを書く

次に、Cloud Functions で使用する Python コードを作成します。このコードは、Cloud Storage イベントをトリガーに、Cloud Translation API を使用してPDFを翻訳します。このコードは、Google Cloud の公式ドキュメント ドキュメントの翻訳関数を Cloud Storage にトリガー を基に作成されています。

from cloudevents.http import CloudEvent
from google.cloud import translate_v3beta1 as translate
import functions_framework

# Triggered by a change in a Cloud Storage bucket
@functions_framework.cloud_event
def translate_pdf_jp_en(cloud_event: CloudEvent):
    """Triggered by a new file upload in the input bucket to translate PDFs."""
    
    # Extract event data
    data = cloud_event.data

    event_id = cloud_event["id"]
    event_type = cloud_event["type"]

    input_bucket_name = data["bucket"]
    input_file_name = data["name"]

    # Validate file type
    if not input_file_name.endswith(".pdf"):
        print(f"Skipping non-PDF file: {input_file_name}")
        return

    print(f"Processing file: {input_file_name} from bucket: {input_bucket_name}, Event ID: {event_id}, Event type: {event_type}")

    # Environment variables
    project_id = "${PROJECT_ID}"
    location = "global"
    output_bucket_name = "pdf-output-english"

    # Initialize clients
    translation_client = translate.TranslationServiceClient()

    # Input and output GCS URIs
    input_gcs_uri = f"gs://{input_bucket_name}/{input_file_name}"
    output_gcs_uri_prefix = f"gs://{output_bucket_name}/"

    # Translation API request configuration
    document_input_config = {
        "gcs_source": {
            "input_uri": input_gcs_uri
        },
        "mime_type": "application/pdf"
    }
    document_output_config = {
        "gcs_destination": {
            "output_uri_prefix": output_gcs_uri_prefix
        }
    }

    request = {
        "parent": f"projects/{project_id}/locations/{location}",
        "document_input_config": document_input_config,
        "document_output_config": document_output_config,
        "source_language_code": "ja",  # Input Language(例:Japanese)
        "target_language_code": "en",  # Input Language(例:English)
    }

    try:
        # Perform the document translation
        response = translation_client.translate_document(request)
        print(f"document translated to: {response.document_translation.mime_type}")
    except Exception as e:
        print(f"Error during translation: {e}")

3. Cloud Functionのデプロイ

関数をデプロイする前に、重要な注意点があります。こちらの ドキュメント記載 によりますと、Cloud Storage の機能を使用するには、Cloud Storage サービスアカウントに pubsub.publisher ロールを付与することが必要です。この設定を行わないと権限不足のエラーが発生する可能性があります。以下のコマンドで権限を付与してください:

SERVICE_ACCOUNT=$(gcloud storage service-agent --project=${PROJECT_ID})

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member serviceAccount:${SERVICE_ACCOUNT} \
  --role roles/pubsub.publisher

上記の手順を完了した後で、gcloud CLIを使用して、作成したコードを Cloud Functions にデプロイします。

gcloud functions deploy translatePdfFunction \
    --gen2 \
    --runtime=python312 \
    --project=${PROJECT_ID} \
    --region=${REGION} \
    --source=. \
    --entry-point=translate_pdf_jp_en \
    --trigger-event-filters="type=google.cloud.storage.object.v1.finalized" \
    --trigger-event-filters="bucket=${INPUT_BUCKET_NAME}"

4. PDFファイルをアップロードして動作確認

以下のコマンドを使用して、入力用バケットに PDF ファイルをアップロードし、翻訳処理が自動的に開始されます。

gcloud storage cp sample.pdf gs://pdf-input-japanese/

処理が完了すると、翻訳後の PDF ファイルが出力用バケットに保存されます。
出力バケットを開くと、以下のように翻訳済みの PDF が生成されていることを確認できます。

出力用バケット

また、以下のコマンドを使用して、出力バケット内のファイル一覧を確認できます。

gcloud storage ls gs://pdf-output-english

最後に

この記事では、Cloud Translation API を活用して PDF ファイルの翻訳を自動化する方法を解説しました。このソリューションは、多言語対応が求められる業務で特に役立ちます。ぜひ試してみてください。

1

Discussion