1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Google翻訳API ( #GCP ) が HTML翻訳でコードブロック内の改行やらインデントを壊しやがるので #python で泣く泣く対応したスクリプト例

Last updated at Posted at 2019-05-06

concept

  • <pre></pre> の中身を URLエンコードしておく
  • Google翻訳にかける
  • <pre></pre> の中身を URLデコードする

以上。

python

#!/usr/bin/env python3

# -*- coding: utf-8 -*-

import os, sys, requests, json, fileinput, re, uuid
import urllib.parse

resource_message = sys.stdin.read()

from_language = os.environ.get('FROM') if os.environ.get('FROM') else 'ja'
to_language = os.environ.get('TO') if os.environ.get('TO') else 'en'
translate_format = 'html'

def match_and_encode(match):
  return match.group(1) + urllib.parse.quote(match.group(2)) + match.group(3)

def convert_codeblocks(resource_message):
  resource_message = re.sub(r'(<pre>(?:<code>)?)(.+?)((?:</code>)?</pre>)', match_and_encode, resource_message, flags=re.DOTALL)

  return resource_message

def match_and_decode(match):
  return match.group(1) + urllib.parse.unquote(match.group(2)) + match.group(3)

def revert_codeblocks(resource_message):
  resource_message = re.sub(r'(<pre>(?:<code>)?)(.+?)((?:</code>)?</pre>)', match_and_decode, resource_message, flags=re.DOTALL)

  return resource_message

def google_translate(resource_message):
  data = {
    'q': resource_message,
    'source': from_language,
    'target': to_language,
    'format': translate_format
  }

  url = 'https://translation.googleapis.com/language/translate/v2'
  token = os.environ['TOKEN']

  headers = {
   'Authorization': 'Bearer {}'.format(token),
   'Content-Type': 'application/json',
  }

  res = requests.post(url, headers=headers, json=data)

  return(res.json()['data']['translations'][0]['translatedText'])

resource_message = convert_codeblocks(resource_message)
resource_message = google_translate(resource_message)
resource_message = revert_codeblocks(resource_message)

print(resource_message)

HTML

<h1>Title</h1>

plain text

<pre><code>
print('Not translate in codes')
print(1)
print(2)
</code></pre>

plain text

<pre><code>
def ex():
  print(4)
  print(5)
</code></pre>

exe

$ cat fixtures/english-codes.html | TOKEN=[GCP_TOKEN] FROM=en TO=ja ./translate-html-raw.py
<h1>タイトル</h1>平文<pre> <code>
print('Not translate in codes')
print(1)
print(2)
</code> </pre>平文<pre> <code>
def ex():
  print(4)
  print(5)
</code> </pre>

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?