2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

画像やPDFにある英語のテキストを翻訳するアプリを作ってみた

Last updated at Posted at 2023-09-01

はじめに

エンジニアは分からないことがあればググることが一般的ですが
海外のサイトを読む際、テキスト翻訳ツールは便利ですが、画像やPDFに埋め込まれたテキストをどうしますか?
この記事では、画像やPDF内の英語テキストを簡単に翻訳するアプリを作成する方法を紹介します。

今回作成したコードです
https://github.com/takuya-wooooo/translate-image-and-pdf

環境情報

Python:3.11.4
virtualenv:20.19.0
PyPDF2:3.0.1
pytesseract:0.3.10
Pillow:10.0.0
mtranslate:1.8

画像認識OCRはOpenCVではなくPillowというライブラリを使用しています。
シンプルにコードを書けます。

ディレクトリ構成

root/
 ├ image/
 │  └ (対象の画像/PDFファイル) 
 └ app.py

コード

app.py
import os
import PyPDF2
import pytesseract
from PIL import Image
from mtranslate import translate

"""
この関数では、PIL(Python Imaging Library)を使用して画像を開き、
Tesseract OCRでテキストを抽出します。
PILを選んだ理由は、シンプルで直感的なAPIを提供し、前処理が簡単な点です。
"""
# 画像からテキストを抽出
def get_text_from_image(image_path):
    try:
        img = Image.open(image_path)
        # 画像からテキストを抽出
        text = pytesseract.image_to_string(img, lang='eng')
        return text
    except Exception as e:
        print(f"画像からテキストを抽出できませんでした: {e}")
        return None

# PDFファイルからテキストを抽出
def get_text_from_pdf(pdf_path):
    try:
        pdf_file = open(pdf_path, 'rb')
        pdf_reader = PyPDF2.PdfFileReader(pdf_file)
        text = ''
        for page_num in range(pdf_reader.numPages):
            page = pdf_reader.getPage(page_num)
            text += page.extractText()
        return text
    except Exception as e:
        print(f"PDFファイルからテキストを抽出できませんでした: {e}")
        return None

# テキストを翻訳
def translate_text(text, target_lang='ja'):
    try:
        translated_text = translate(text, target_lang)
        return translated_text
    except Exception as e:
        print(f"テキストの翻訳に失敗しました: {e}")
        return None

# ファイルを取得
data_dir = 'image' 
files = os.listdir(data_dir)

for file in files:
    file_path = os.path.join(data_dir, file)
    file_extension = os.path.splitext(file)[1].lower()  # ファイルの拡張子を取得し小文字に変換
    
    if file_extension in ('.jpeg', '.jpg', '.png'):
        # .jpegや.jpgや.pngファイルの場合の処理
        extracted_text = get_text_from_image(file_path)
        if extracted_text:
            translated_text = translate_text(extracted_text)
            if translated_text:
                print("抽出されたテキスト:")
                print(extracted_text)
                print("\n翻訳されたテキスト:")
                print(translated_text)
        
    elif file_extension == '.pdf':
        # .pdfファイルの場合の処理
        print(f"PDFファイルを処理: {file}")
        extracted_text = get_text_from_pdf(file_path)
        if extracted_text:
            translated_text = translate_text(extracted_text)
            if translated_text:
                print("抽出されたテキスト:")
                print(extracted_text)
                print("\n翻訳されたテキスト:")
                print(translated_text)
        
    else:
        # 上記以外のファイルの場合
        print(f"ファイルの形式が間違っています: {file}")

実行結果

お寿司の画像を読み込んでみます。
813-8139504_this-png-file-is-about-english-salmon-text.jpeg
(https://www.pngkit.com/view/u2t4t4y3u2o0w7y3_this-png-file-is-about-english-salmon-text/ より引用)

$ python app.py 
抽出されたテキスト:
QA QS

Salmon Shrimp Tuna Squid


翻訳されたテキスト:
QA QS

サーモン・エビ・マグロ・イカ

画像の中のテキストの「Salmon Shrimp Tuna Squid」が翻訳されています
翻訳結果は問題ないです

おわりに

画像認識するアプリは実務で作成したことないので玄人の方から何を言われるか不明ですが、初心者なりに作成してみました。
個人開発で画像認識にはOpenCVをしようしていましたが、今回は気分転換でPillowというライブラリを使用しました。
画像認識にはOpenCVが強力ですが、PillowはOpenCVよりコードをシンプルに書くことができ、前処理が簡単に作成できたりと良い点がありました。
皆さんも遊びでコードを書くときは普段使用しているライブラリを使用せずに他のライブラリを使用してみると何か発見があるかと思います。

この記事が役に立ったと思ったら、いいねやストックをお願いします!

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?