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

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

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

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

Q&A

0回答

3226閲覧

pythonのpickleのEOFErrorで困っています。

YYYuto

総合スコア0

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Python

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

0グッド

0クリップ

投稿2021/10/23 03:38

編集2021/10/23 04:05

前提・実現したいこと

写真をOCRして読み取った文字からカレンダーに予定を追加するというアプリを作っています。
しかし、カレンダーに予定を追加する関数が動いてくれません。
pickleのところで間違っているようでうす。

発生している問題・エラーメッセージ

x

1127.0.0.1 - - [23/Oct/2021 12:27:46] "POST /post_img_test HTTP/1.1" 500 - 2Traceback (most recent call last): 3 File "/Users/yuto_shinohara/.pyenv/versions/3.8.6/lib/python3.8/site-packages/flask/app.py", line 2088, in __call__ 4 return self.wsgi_app(environ, start_response) 5 File "/Users/yuto_shinohara/.pyenv/versions/3.8.6/lib/python3.8/site-packages/flask/app.py", line 2073, in wsgi_app 6 response = self.handle_exception(e) 7 File "/Users/yuto_shinohara/.pyenv/versions/3.8.6/lib/python3.8/site-packages/flask/app.py", line 2070, in wsgi_app 8 response = self.full_dispatch_request() 9 File "/Users/yuto_shinohara/.pyenv/versions/3.8.6/lib/python3.8/site-packages/flask/app.py", line 1515, in full_dispatch_request 10 rv = self.handle_user_exception(e) 11 File "/Users/yuto_shinohara/.pyenv/versions/3.8.6/lib/python3.8/site-packages/flask/app.py", line 1513, in full_dispatch_request 12 rv = self.dispatch_request() 13 File "/Users/yuto_shinohara/.pyenv/versions/3.8.6/lib/python3.8/site-packages/flask/app.py", line 1499, in dispatch_request 14 return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) 15 File "/Users/yuto_shinohara/Documents/python/textdata/camender/server.py", line 76, in index 16 googlecalenderattach(txt) 17 File "/Users/yuto_shinohara/Documents/python/textdata/camender/server.py", line 128, in googlecalenderattach 18 creds = pickle.load(token) 19EOFError: Ran out of input

該当のソースコード

python

1from __future__ import print_function 2from flask import Flask, jsonify, request 3from PIL import Image 4import json 5import base64 6from io import BytesIO 7import matplotlib.pyplot as plt 8import copy 9import numpy as np 10import cv2 11import pyocr 12import pyocr.builders 13import datetime 14import os.path 15from googleapiclient.discovery import build 16from google_auth_oauthlib.flow import InstalledAppFlow 17from google.auth.transport.requests import Request 18from google.oauth2.credentials import Credentials 19import pickle 20 21 22tools = pyocr.get_available_tools() 23if len(tools) == 0: 24 print("No OCR tool found") 25 sys.exit(1) 26tool = tools[0] 27print("Will use tool '%s'" % (tool.get_name())) 28langs = tool.get_available_languages() 29print("Available languages: %s" % ", ".join(langs)) 30 31app = Flask(__name__) 32 33SCOPES = ['https://www.googleapis.com/auth/calendar'] 34@app.route("/post_img_test", methods=["GET", "POST"]) 35def index(): 36 # json_data = request.get_json() # POSTされたjsonを取得 37 # dict_data = json.loads(json_data) # jsonを辞書に変換 38 img_stream = base64.b64decode(request.form["img"]) 39 cols = int(request.form["COLS"]) 40 rows = int(request.form["ROWS"]) 41 42 img_array = np.asarray(bytearray(img_stream),dtype=np.uint8) 43 img = cv2.imdecode(img_array,1) 44 h,w,c = img.shape 45 print(h,w,c) 46 img2 = copy.deepcopy(img) 47 48 directions = ["UL","UR","LL","LR"] 49 positions = [] 50 51 for dire in directions: 52 pos = request.form[dire].split(",")#場所取得 53 print(pos) 54 positions.append([int(float(pos[0]))+w//2, h//2-int(float(pos[1]))]) 55 cv2.circle(img,positions[-1],10,(255,255,255),thickness=-1)#場所チェック 56 57 cv2.imwrite('result_checking.png',img) 58 59 #射影変換後のサイズ 60 after_w = max(positions,key=lambda x:x[0])[0]-min(positions,key=lambda x:x[0])[0] 61 after_h = max(positions,key=lambda x:x[1])[1]-min(positions,key=lambda x:x[1])[1] 62 63 #射影変換 64 pts=np.float32([[0,0],[after_w,0],[0,after_h],[after_w,after_h]]) 65 M = cv2.getPerspectiveTransform(np.float32(positions),pts) 66 dst = cv2.warpPerspective(img2,M,(after_w,after_h)) 67 68 #射影変換を保存 69 cv2.imwrite('result.png',dst) 70 71 imgs = chuncks(dst,rows,cols) 72 for i in range(len(imgs)): 73 imgs[i] = noizclear(imgs[i]) 74 global txt 75 txt = tool.image_to_string(cv2pil(imgs[i]),lang='jpn',builder=pyocr.builders.TextBuilder(tesseract_layout=6)) 76 googlecalenderattach(txt) 77 return 'ok' 78#画像のノイズを消す。 79def noizclear(img): 80 resize_to = (img.shape[0]*10,img.shape[1]*10) # Rescale the image more than 300 dpi 81 block_size = 147 # Block size for adaptive thresholding. This should be positive and odd value more than 1. 82 C = 31 # The constant to subtract from mean or weighted mean 83 threshold = 140 # The threshold for simple thresholding 84 open_ksize = (5, 5) # The kernel size to remove white patch in black region 85 close_ksize = (3, 3) # The kernel size to remove black patch in white region 86 blur_ksize = (5, 5) # The Gaussian kernel size to set blur. This should be positive and odd value 87 #img = cv2.imread('result.png') 88 img_generated = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 89 img_resized = cv2.resize(img_generated, resize_to, interpolation = cv2.INTER_LINEAR) 90 img_adaptive = cv2.adaptiveThreshold(img_resized, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, block_size, C) 91 img_morph_open = cv2.morphologyEx(img_adaptive, cv2.MORPH_OPEN, np.ones(open_ksize, np.uint8)) 92 img_morph_close = cv2.morphologyEx(img_morph_open, cv2.MORPH_CLOSE, np.ones(close_ksize, np.uint8)) 93 result, img_OTSU = cv2.threshold(img_resized, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) 94 img_blur = cv2.GaussianBlur(img_OTSU, blur_ksize, cv2.BORDER_CONSTANT) 95 result, img_OTSU2 = cv2.threshold(img_blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) 96 img_bitwise = cv2.bitwise_or(img_OTSU2, img_morph_close) 97 return img_bitwise 98#画像を切り分ける。 99def chuncks(dst,rows,cols): 100 chunk_lst = [] 101 for row_img in np.array_split(dst,rows,axis=0): 102 for chunk in np.array_split(row_img,cols,axis=1): 103 chunk_lst.append(chunk) 104 print(len(chunk_lst)) 105 106 return chunk_lst 107 108def cv2pil(image): 109 ''' OpenCV型 -> PIL型 ''' 110 new_image = image.copy() 111 if new_image.ndim == 2: # モノクロ 112 pass 113 elif new_image.shape[2] == 3: # カラー 114 new_image = cv2.cvtColor(new_image, cv2.COLOR_BGR2RGB) 115 elif new_image.shape[2] == 4: # 透過 116 new_image = cv2.cvtColor(new_image, cv2.COLOR_BGRA2RGBA) 117 new_image = Image.fromarray(new_image) 118 return new_image 119 return jsonify(response) 120#googleカレンダーに追加 121def googlecalenderattach(txt): 122 creds = None 123 # The file token.pickle stores the user's access and refresh tokens, and is 124 # created automatically when the authorization flow completes for the first 125 # time. 126 if os.path.exists('token.pickle'): 127 with open('token.pickle', 'rb') as token: 128 creds = pickle.load(token) 129 # If there are no (valid) credentials available, let the user log in. 130 if not creds or not creds.valid: 131 if creds and creds.expired and creds.refresh_token: 132 creds.refresh(Request()) 133 else: 134 flow = InstalledAppFlow.from_client_secrets_file( 135 'credentials.json', SCOPES) 136 creds = flow.run_local_server(port=0) 137 # Save the credentials for the next run 138 with open('token.pickle', 'wb') as token: 139 pickle.dump(creds, token) 140 141 service = build('calendar', 'v3', credentials=creds) 142 143 event = { 144 'summary': 'a', 145 'start': { 146 'date': datetime.date(2021,11,30).strftime(r'%Y-%m-%d'), 147 'timeZone': 'Japan', 148 }, 149 'end': { 150 'date': datetime.date(2021,11,30).strftime(r'%Y-%m-%d'), 151 'timeZone': 'Japan', 152 }, 153 } 154 event = service.events().insert(calendarId='自分のカレンダーIDを入力',body=event).execute() 155 print (event['id']) 156 157 158 159 160if __name__ == "__main__": 161 app.debug = True 162 app.run(host='127.0.0.1',port=5000) 163

試したこと

調べたところ、解決できそうな情報は見つかりませんでした。

補足情報(FW/ツールのバージョンなど)

python 3.8.6
Google Calender Apiを使っています.
https://developers.google.com/calendar/api/quickstart/python?hl=ja

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

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

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

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

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

退会済みユーザー

退会済みユーザー

2021/10/24 00:36

> if os.path.exists('token.pickle'): > with open('token.pickle', 'rb') as token: とあるので、ファイルは恐らくあるのだと思いますが、中身が空っぽということはありませんか?
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問