質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
PyInstaller

PyInstallerは、Pythonのスクリプトを一括でWindowsなどで動く実行可能ファイルに変換できるツールです。このツールを用いることで自作のPythonプログラムを別で使用する場合でもPythonをインストールする必要がありません。

Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

4865閲覧

google translate api を利用したpython 実行ファイルで grpc ssl認証に対するassertion failed が発生する

tomy-c

総合スコア179

PyInstaller

PyInstallerは、Pythonのスクリプトを一括でWindowsなどで動く実行可能ファイルに変換できるツールです。このツールを用いることで自作のPythonプログラムを別で使用する場合でもPythonをインストールする必要がありません。

Google API

Googleは多種多様なAPIを提供していて、その多くはウェブ開発者向けのAPIです。それらのAPIは消費者に人気なGoogleのサービス(Google Maps, Google Earth, AdSense, Adwords, Google Apps,YouTube等)に基づいています。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2019/07/23 07:08

※前回質問からの続きになります
https://teratail.com/questions/201443

現在pythonを使用し、google translate api v3beta1を利用した試作アプリを作っています。
前回のsys.pathエラーはなんとか回避できたのですが、pyinstallerで作成した実行ファイルを起動した際、今度は以下のようなエラーが発生してしまいます。

Exception ignored in:'grpc._cthon.cygrpc.ssl_roots_override_callback' E0723 (発生時刻) src/core/lib/security/seecurity_connector/ssl_utils.cc:453] assertion failed: pem_root_certs != nullptr

エラーの内容を調査したところ、stackoverflowやgithubにてssl認証が出来ていないというような内容の記事がいくつか見つかったためそこに記述されていた対処法をいくつか試してみましたがうまくいきませんでした。

ちなみにpyファイルをコンソールから直接起動する場合は正常に動作します。
このエラーを解消するにはどのような対応をすればよいのでしょうか。
御教唆お願い致します。

該当のソースコード

※前回から動作を少し変えました
引数1:翻訳したい内容
引数2:翻訳元の言語
引数3:翻訳先の言語

結果はcsvにutf-8で出力

python

1# coding: utf_8 2# https://cloud.google.com/translate/docs/quickstart-client-libraries-v3?hl=ja 3# pip install --upgrade google-cloud-translate -t "プロジェクトフォルダ/lib" 4 5# クライアントAPI gRPC通信している? 6# VSCodeではインタプリタを別途インストールしたpythonに変更しておくこと 7# (コンソールでの実行とVSCodeではデフォルトのインタプリタが異なり、ライブラリパスの参照先も異なる) 8# (pip でライブラリをinstallしている場合は特に影響がある? ※未確認) 9# https://code.visualstudio.com/docs/python/environments 10# VSCode → python 32bit 11# Ctrl + Shift + P → "Python: Select Interpreter" → Python3.7.4 64bit 12 13#デバッグ設定 lunch.json 14# https://stackoverflow.com/questions/54160948/how-to-fix-the-path-attribute-not-found-error-for-packages-installed-by-pi 15#{ 16# "name": "Python: Module", 17# "type": "python", 18# "request": "launch", 19# "module": "main", #エントリーポイントファイル名 (拡張子不要) 20# "console": "integratedTerminal" 21# }, 22 23# pyinsteller後の実行ファイル起動時、ライブラリが足りないとエラーが出る場合は 24# *.specファイルのpathexに必要なライブラリを全て記述して再度 pyinstaller する 25# https://codeday.me/jp/qa/20190404/548372.html 26# a = Analysis(['main.py'], 27# pathex=['path1',"path2","path3".........], 28# binaries=[], 29# datas=[], 30# hiddenimports=[], 31# ...... 32 33 34# 作成したプロジェクトの秘密鍵をインポート(環境変数に登録する方法は駄目だった) 35import inspect # デバッグ用 36import os 37import sys 38import csv #ファイル出力用 39 40 41#ライブラリへのパスを追加 42# ROOTPATH = os.path.dirname(__file__) 43ROOTPATH = os.path.dirname(sys.argv[0]) #pytinstaller では __file__は使用不可能 44LIBPATH = os.path.join(ROOTPATH, 'lib') 45sys.path.append(LIBPATH) 46 47# python上で環境変数を追加(google core import前に実行) 48os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'プロジェクト作成時に発行された秘密鍵.json' 49 50# SSL証明書のパス[※grpc\_cython\_credentials に入っていた証明書](pyファイル直接起動ならこの行とファイルは不要) 51# ※1 grpcのssl証明書の有効期限に注意(切れたらライブラリの更新が必要になるか、下記から取得) 52# ※2 証明書自体はここでも配布している(https://github.com/grpc/grpc/blob/master/etc/roots.pem) 53# https://qiita.com/akitooo/items/eb82a5f335d8ca9c9faf 54os.environ['REQUESTS_CA_BUNDLE'] = "./roots.pem" 55 56 57# デバッグ用(読み込んでいるディレクトリの確認) 58import pprint 59pprint.pprint(sys.path) 60 61# 無料なのはversion3のβ1版のみ 62from lib.google.cloud import translate_v3beta1 as translate 63client = translate.TranslationServiceClient() 64 65 66 67def main(): 68 #text = u'Hello, world!' 69 text = sys.argv[1] 70 #source = 'en-US' 71 source = sys.argv[2] 72 #target = 'fr' 73 target = sys.argv[3] 74 location = 'global' 75 76 parent = client.location_path('発行したプロジェクトのID', location) 77 78 # 国コードは以下参照 79 # https://ja.wikipedia.org/wiki/ISO_3166-1 80 response = client.translate_text( 81 parent=parent, 82 contents=[text], 83 mime_type='text/plain', # mime types: text/plain, text/html 84 source_language_code=source, 85 target_language_code=target) 86 87 # ファイル入出力でエンコードを合わせておくこと 88 f = open("./csv/output.csv", 'a', encoding="utf-8") 89 writer = csv.writer(f, lineterminator = "\n") 90 91 # ver3Beta1では一部言語の結果が8進数で返ってくる模様・・・→翻訳結果の指定方法がGoogle公式のコードと異なっていた 92 # translation.translated_textに翻訳結果が格納されていた。 93 for translation in response.translations: 94 95 # オブジェクトの中身表示 96 # print( inspect.getmembers( object) ) 97 print(u'Translated Text: {}'.format(translation.translated_text)) 98 99 # 文字列だけを出す場合は2次元配列化しておかないと一文字づつカンマ区切りで出力される(文字列が配列と解釈される) 100 writer.writerow([format(translation.translated_text)]) 101 102 #入力待ち 103 # input() 104 f.close() 105 106main()

試したこと

1・下記を参考にプログラムに証明書ファイル(roots.pem)の参照を追加しました。
https://stackoverflow.com/questions/17158529/fixing-ssl-certificate-error-in-exe-compiled-with-py2exe-or-pyinstaller/34227183#34227183
結果:pemファイルの設置なども確認して実行しましたが同じエラーが発生

2・下記を参考にspecファイルのdatasにpemファイルのパスを追加(ssl証明書を実行ファイルに組み込もうとしました)
https://github.com/googleapis/google-cloud-python/issues/5774
結果:pyinstallerの実行そのものでエラーが発生。(ログ取り忘れたので後で追加します)
その時のspecファイルは下記になります

# -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['main.py'], pathex=['C:\Users\"ユーザー名"\Documents\google_translate_test1', 'c:\Users\"ユーザー名"\.vscode\extensions\ms-python.python-2019.6.24221\pythonFiles', 'C:\Users\"ユーザー名"\AppData\Local\Programs\Python\Python37\python37.zip', 'C:\Users\"ユーザー名"\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\"ユーザー名"\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\"ユーザー名"\AppData\Local\Programs\Python\Python37', 'C:\Users\"ユーザー名"\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\"ユーザー名"\AppData\Local\Programs\Python\Python37\lib\site-packages', 'C:\Users\"ユーザー名"\Documents\google_translate_test1\lib' ], binaries=[], datas=[ ('roots.pem', 'grpc/_cython/_credentials/'), ], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='main', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True )

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

自己解決しました。
試したことの2・specファイルのdatasにpemファイルのパスを追加
のpemがケアレスミスでpenになっていました。

修正後pyinstaller実行が成功し、その後、実行ファイルが正常に動作しました。
※必要なファイル(json、出力先ディレクトリ、引数)を用意した上での実行です。

ソースコードも少し修正しました

python

1# coding: utf_8 2# https://cloud.google.com/translate/docs/quickstart-client-libraries-v3?hl=ja 3# pip install --upgrade google-cloud-translate -t "プロジェクトフォルダ/lib" 4 5# クライアントAPI gRPC通信している? 6# VSCodeではインタプリタを別途インストールしたpythonに変更しておくこと 7# (コンソールでの実行とVSCodeではデフォルトのインタプリタが異なり、ライブラリパスの参照先も異なる) 8# (pip でライブラリをinstallしている場合は特に影響がある? ※未確認) 9# https://code.visualstudio.com/docs/python/environments 10# VSCode → python 32bit 11# Ctrl + Shift + P → "Python: Select Interpreter" → Python3.7.4 64bit 12 13# デバッグ設定 lunch.json 14# https://stackoverflow.com/questions/54160948/how-to-fix-the-path-attribute-not-found-error-for-packages-installed-by-pi 15#{ 16# "name": "Python: Module", 17# "type": "python", 18# "request": "launch", 19# "module": "main", #エントリーポイントファイル名 (拡張子不要) 20# "console": "integratedTerminal" 21# }, 22 23# pyinsteller後の実行ファイル起動時、ライブラリが足りないとエラーが出る場合は 24# *.specファイルのpathexに必要なライブラリを全て記述して再度 pyinstaller する 25# https://codeday.me/jp/qa/20190404/548372.html 26# https://github.com/googleapis/google-cloud-python/issues/5774 27# https://pythonhosted.org/PyInstaller/spec-files.html 28# a = Analysis(['main.py'], 29# pathex=['path1',"path2","path3".........], 30# binaries=[], 31# datas=[], 32# hiddenimports=[], 33# ...... 34 35 36# 作成したプロジェクトの秘密鍵をインポート(環境変数に登録する方法は駄目だった) 37import inspect # デバッグ用 38import os 39import sys 40import csv #ファイル出力用 41import logging #ログ出力 42 43 44#ライブラリへのパスを追加 45# ROOTPATH = os.path.dirname(__file__) 46ROOTPATH = os.path.dirname(sys.argv[0]) #pytinstaller では __file__は使用不可能 47LIBPATH = os.path.join(ROOTPATH, 'lib') 48sys.path.append(LIBPATH) 49 50# python上で環境変数を追加(google core import前に実行) 51os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './プロジェクト作成時に発行されたjsonファイル' 52 53# SSL証明書のパス[※grpc\_cython\_credentials に入っていた証明書](pyファイル直接起動ならこの行とファイルは不要) 54# ※1 grpcのssl証明書の有効期限に注意(切れたらライブラリの更新が必要になるか、下記から取得) 55# ※2 証明書自体はここでも配布している(https://github.com/grpc/grpc/blob/master/etc/roots.pem) 56# https://qiita.com/akitooo/items/eb82a5f335d8ca9c9faf 57# 実行ファイルでpem指定して組み込んでもここで参照を追加している場合はそちらを優先するため注意 58# os.environ['REQUESTS_CA_BUNDLE'] = "./roots.pem" 59 60 61# デバッグ用(読み込んでいるディレクトリの確認) 62import pprint 63pprint.pprint(sys.path) 64 65# 無料なのはversion3のβ1版のみ 66from lib.google.cloud import translate_v3beta1 as translate 67client = translate.TranslationServiceClient() 68 69# ログの出力名を設定(1) 70logger = logging.getLogger('ErrorLogging') 71# ログレベルの設定(2) 72logger.setLevel(10) 73# ログのファイル出力先を設定(3) 74fh = logging.FileHandler('error.log') 75logger.addHandler(fh) 76# ログのコンソール出力の設定(4) 77sh = logging.StreamHandler() 78logger.addHandler(sh) 79 80def main(): 81 try: 82 #text = u'Hello, world!' 83 text = sys.argv[1] 84 #source = 'en-US' 85 source = sys.argv[2] 86 #target = 'fr' 87 target = sys.argv[3] 88 location = 'global' 89 90 print('text=' + text) 91 print('source=' + source) 92 print('target=' + target) 93 94 parent = client.location_path('発行したプロジェクトのID', location) 95 96 # 国コードは以下参照 97 # https://ja.wikipedia.org/wiki/ISO_3166-1 98 response = client.translate_text( 99 parent=parent, 100 contents=[text], 101 mime_type='text/plain', # mime types: text/plain, text/html 102 source_language_code=source, 103 target_language_code=target) 104 105 # ファイル入出力でエンコードを合わせておくこと 106 f = open("./csv/output.csv", 'a', encoding="utf-8") 107 writer = csv.writer(f, lineterminator = "\n") 108 109 # ver3Beta1では一部言語の結果が8進数で返ってくる模様・・・→翻訳結果の指定方法がGoogle公式のコードと異なっていた 110 # translation.translated_textに翻訳結果が格納されていた。 111 for translation in response.translations: 112 113 # オブジェクトの中身表示 114 # print( inspect.getmembers( object) ) 115 print(u'Translated Text: {}'.format(translation.translated_text)) 116 117 # 文字列だけを出す場合は2次元配列化しておかないと一文字づつカンマ区切りで出力される(文字列が配列と解釈される) 118 writer.writerow([format(translation.translated_text)]) 119 120 #入力待ち 121 # input() 122 f.close() 123 except Exception as err: 124 #突貫ログファイル出力(traceback多分不要) 125 logger.exception('Error dosomething: %s', err) 126 import traceback 127 traceback.print_exc() 128 129main() 130

投稿2019/07/23 07:33

tomy-c

総合スコア179

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問