![見出し画像](https://assets.st-note.com/production/uploads/images/65875528/rectangle_large_type_2_ca2a1c94a8fa021820836a7358dbf26c.png?width=1200)
Pythonで作るGUI付き翻訳支援アプリの作成 Part8:初期設定とGUIイベント処理の実装
初期設定とGUIイベント処理の実装
deepl.pyとconfig.initが作成出来ましたので、main.pyに戻りプログラムの初期設定とGUIイベント処理を実装していきます。
プログラムの初期設定
main.pyに初期設定を実装していきます。プログラムの初期設定は以下の3つです。
設定ファイルの読み込み
最初に表示するウィンドウの指定
deepLの使用量をウィンドウに反映
コードは以下の通りとなります。
import PySimpleGUI as sg
import configparser
import gui
import deepl
def main():
# 設定を読み込む。
config = configparser.ConfigParser()
config.read('config.ini')
config_deepl = config['deepL']
# 最初に表示するウィンドウを指定する。
window = gui.main_window()
# deepLの使用量を取得しウィンドウに表示させる。
gui.get_usage(window, config_deepl)
最初の4行 import関係は変更ありません。def main():内を詳しくみていきます。以下の2行は、先ほど作成したconfig.iniファイルを変数configに読み込みます。3行目では、config ['deepL']として変数configのdeepLセクションの情報を変数config_deeplに格納しています。
config = configparser.ConfigParser()
config.read('config.ini')
config_deepl = config['deepL']
変数config_deeplには、以下の情報が入っています。
auth_key = ご自身のAPI認証キー
translate_ep = https://api-free.deepl.com/v2/translate
usage_ep = https://api-free.deepl.com/v2/usage
次に、最初に表示するメイン画面を指定します。
window = gui.main_window()
そして、deepLの使用量を取得してウィンドウに反映します。この処理をgui.get_usage()関数としてこれから作成します。作成する前に引数を検討します。メイン画面に使用量を反映させたいので、windowを第一引数とします。次に、deepL APIにアクセスして使用量を確認する必要があります。そのための情報としてconfig_deeplを第2引数として与えます。
gui.get_usage()関数の作成
gui.pyを開きget_usage()関数を作成していきます。コードは以下の通りとなります。仮引数はwindowとconfigとなります。
def get_usage(window, config):
count_result = deepl.char_cnt(config)
if count_result is None:
sg.popup('APIキーを確認して下さい')
else:
count_used = count_result['character_count']
count_limit = count_result['character_limit']
bar_used = count_used/count_limit * 100
output_txt = str(count_used) + ' / ' + str(count_limit) + '文字'
window['-usage_bar-'].update(bar_used)
window['-Char_cnt-'].update(output_txt)
関数内の1行目で、deepl.py内のchar_cnt()関数を呼び出して、その結果を変数count_resultに受けます。
count_result = deepl.char_cnt(config)
ここで、deepLの技術資料によればcount_resultには以下の情報が格納されることになります。今回は、character_countとcharacter_limitを使います。
![](https://assets.st-note.com/img/1637147616753-5E2tyiVY38.png?width=1200)
APIキー間違いなどで、Noneが返された場合はポップアップでAPIキーを確認するようにメッセージも表示させます。
count_result = deepl.char_cnt(config)
if count_result is None:
sg.popup('APIキーを確認して下さい')
count_resultがNoneではない場合、値を取得する事が出来ていますのでcount_result['character_count']として現在のdeepL使用量(文字数)を変数count_usedに格納します。同様に使用限度(Freeプランであれば500000文字)をcount_result['character_limit']として、変数count_limitに格納します。
count_used = count_result['character_count']
count_limit = count_result['character_limit']
bar_usedには、使用率の割合を計算して代入します。これは、メインウィンドウでプログレスバーを使って使用率を視覚的に見やすくするためです。次に変数output_txtは、使用率の詳細(数字)を表示させる文字列を作成してれています。
bar_used = count_used/count_limit * 100
output_txt = str(count_used) + ' / ' + str(count_limit) + '文字'
最後に、これらの2つの変数をプログレスバーkey = ‘-usage_bar-’とテキストエリアkey = ‘-Char_cnt-’にupdateで反映させます。
window['-usage_bar-'].update(bar_used)
window['-Char_cnt-'].update(output_txt)
GUIイベント処理の実装
実装するイベントは以下の3つです。
event == '-run_deepl-': deepL翻訳&逆翻訳の実行
event == '-config-': deepL設定画面への切り替え
event == '-config_update-': 設定ファイルの更新
deepL翻訳&逆翻訳の実行イベント
このイベントは、ユーザーが入力した翻訳したい原文を変数messageに取り込むところから始まります。最終的なコードは以下の通りです。
if event == '-run_deepl-':
message = values['-original_text-']
# DeepL翻訳実行
lng = deepl.lang_set(message)
trans_result = deepl.translate(message, t_lang=lng['target'],
s_lang=lng['source'], config=config_deepl)
# DeepL翻訳結果の逆翻訳実行
lng = deepl.lang_set(trans_result)
back_trans_result = deepl.translate(trans_result, t_lang=lng['target'],
s_lang=lng['source'], config=config_deepl)
window['-translated_text-'].print(trans_result)
window['-back_trans_text-'].print(back_trans_result)
gui.get_usage(window, config_deepl)
ユーザーが入力した翻訳したい原文は、メイン画面のテキストエリア key = ‘-original_text-‘から取得して変数messageに取り込みます。
message = values['-original_text-']
次に、受け取った原文messageをdeepl.lang_set(message)を呼び出して翻訳元の言語コードと翻訳先の言語コードをlngに辞書型で受け取ります。日本語→英語に翻訳したい場合は、lng = {'target': "EN", 'source': "JA"}となります。
lng = deepl.lang_set(message)
そしてdeepl.translate()関数を呼び出してdeepL翻訳をAPIを叩いて実行します。translate()関数には4つの引数が必要でした。それぞれの引数をコードのように渡して、翻訳結果を変数trans_resultに格納します。
trans_result = deepl.translate(message, t_lang=lng['target'],
s_lang=lng['source'], config=config_deepl)
次は、deepL翻訳した文を再度deepLで逆翻訳させます。英作文などでは、逆翻訳をすると自分の伝えたい意図がしっかりと翻訳されているか確認出来ます。この処理も基本的に先ほどと同じ処理を繰り返しています。説明は、割愛します。
# DeepL翻訳結果の逆翻訳実行
lng = deepl.lang_set(trans_result)
back_trans_result = deepl.translate(trans_result, t_lang=lng['target'],
s_lang=lng['source'], config=config_deepl)
DeepL翻訳と逆翻訳の結果をメイン画面に反映させます。こちらも特に問題ないと思いますので説明は割愛します。
window['-translated_text-'].print(trans_result)
window['-back_trans_text-'].print(back_trans_result)
最後に、翻訳後はDeepL使用量が減っていますので使用量のところをアップデートしましょう。
gui.get_usage(window, config_deepl)
これで、deepL翻訳&逆翻訳の実装が出来ました。逆翻訳が不要な場合は、逆翻訳の部分をコメントアウトして下さい。もしくはメイン画面にラジオボタンもしくはトグルボタンなどを設定して、逆翻訳有無をユーザーに選択させるのも良いかもしれません。
deepL設定画面への切り替え
メイン画面からdeepL設定画面へ切り替えるイベント処理を実装します。メイン画面の歯車の画像にkey = '-config-' を割り当てていました。このボタンを押すと、deepL設定画面に画面が切り替わるようにします。
まずは、メイン画面をwindow.close()で閉じます。そして、設定画面を新しいウィンドウとしてwindow = gui.config_window(config_deepl)で指定します。ここで、変数config_deeplを引数として渡します。
if event == '-config-':
window.close()
window = gui.config_window(config_deepl)
設定ファイルの更新
設定画面の更新ボタン key = '-config_update-'が押された際に、設定ファイルconfig.iniが更新されるようにしていきます。コードは以下の通りです。
if event == '-config_update-':
edit = configparser.ConfigParser()
edit.read('config.ini')
edit_deepl = edit["deepL"]
edit_deepl["auth_key"] = values['-deepL_API-']
with open('config.ini', 'w') as configfile:
edit.write(configfile)
window.close()
config.read('config.ini')
window = gui.main_window()
config_deepl = config['deepL']
gui.get_usage(window, config_deepl)
変数editにconfig.iniを読み込み、変数edit_deeplにdeepLセクションの情報を格納します。
edit = configparser.ConfigParser()
edit.read('config.ini')
edit_deepl = edit["deepL"]
deepL設定画面では、テキストエリアkey = -deepL_API-の値でAPIキーを変更出来るようにしています。この値をedit_deepl["auth_key"] 格納します。
edit_deepl["auth_key"] = values['-deepL_API-']
このままでは、config.iniファイルは更新されませんのでファイルを開いて更新します。
with open('config.ini', 'w') as configfile:
edit.write(configfile)
更新が終わったら、deepL設定画面を閉じてメイン画面に切り替わるようにします。この際、config.iniを再度読み込んでdeepL使用量もアップデートするようにします。
window.close()
config.read('config.ini')
window = gui.main_window()
config_deepl = config['deepL']
gui.get_usage(window, config_deepl)
以上で、初期設定とGUIイベント処理の実装は完了です。これでプログラムは完成となります。deepL API Freeは無料です。GUI付きデスクトップアプリにWepAPIを組み合わせれば、本当に色々な事が出来るようになります。
記事が参考になりましたら、❤️を押していただけると励みになります😊