LoginSignup
0
1

More than 1 year has passed since last update.

DeepL API + PyMuPDF + PySimpleGUIで英文翻訳プログラムをGUI化してみた。

Posted at

概要

下のホームページで紹介されていたプログラムをGUIで操作できるように改造してみました。

今回目指したのは、
1.任意のPDFファイルをGUIで選択する
2.元のファイルと同じディレクトリにMarkdown形式で保存(〇〇.pdf->〇〇.md)
の2点です。

事前準備

  • Pythonと必要なライブラリ(後述)のインストール
  • DeepLのAPI取得:上記HPを参考にしてください

必要なライブラリ

  • PyMuPDF
  • PySimpleGUI
  • requests(エラーが出るようなら追加でインストール)

コード

# 必要なライブラリのインポート
import PySimpleGUI as sg
import fitz
import requests
import json

# PySimpleGUIの設定
font_size = 50

layout = [
    [sg.Text("PDFファイルを選択:", font=font_size),
     sg.InputText(key="-INPUTNAME-"),
     sg.FileBrowse(key="-INPUTFILE-")],
    [sg.Button("翻訳開始", key="-TRANSLATION-", font=font_size),
     sg.Button("CLEAR", key="-CLEAR-", font=font_size)]
]

window = sg.Window("Translation App", layout)

# プログラムを実行する
while True:
    event, values = window.read()

    # Get file name
    pdf_file_path = values["-INPUTNAME-"]
    output_file_path = str(pdf_file_path.split(".")[0]) + ".md"
    page_num = 1

    if event == "-TRANSLATION-":
        with fitz.open(pdf_file_path) as pdf_in:

            text = ""
            for page in pdf_in:
                page1 = page.get_text()

                data = {
                'auth_key': 'ここにはDeepLのAPIを入力してください',
                'text': page1.replace('-\n', '').replace('\n', ''),
                'target_lang': 'JA'
                }

                response = requests.post('https://api-free.deepl.com/v2/translate', data=data)
                d = json.loads(response.text)
                _text = f"""### Page{page_num}\n{d['translations'][0]['text']}\n"""
                text = text + _text
                page_num += 1

        with open(output_file_path, 'w', encoding='utf-8') as file:
                file.write(text)

        sg.popup("翻訳が完了しました。")
    
    # CLEARボタンを押した時には-INPUTFILENAME-を空にする
    if event == "-CLEAR-":
        window["-INPUTNAME-"].update("")

    if event == sg.WIN_CLOSED:
        break

window.close()


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