我想在linebot中接收上傳至雲端空間後之回傳圖檔。
但可能寫的方式有誤,它出現了這樣的訊息:
UnboundLocalError: local variable 'text_detected' referenced before assignment
我猜測是否為參數兩邊不一致所產生的問題?......
新寫method 的參數,我設置為user_id,而在handle_content 中上傳file後,呼叫中的method裡參數,我設置為(user.user_id)。
但這兩邊,我沒辦法弄成一致(還是新手,有一些觀念不是太清楚,有誤地方,請多包涵)
附上截取程式碼如下:
def text_detected(user_id):
input_file=f"gs://img_platecapture/{user_id}.jpg"
with io.open(input_file, 'rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.text_detection(image=image)
if response.error.message:
raise Exception(
'{}\nFor more info on error messages, check: '
'https://cloud.google.com/apis/design/errors'.format(
response.error.message))
img = Image.open(input_file)
draw = ImageDraw.Draw(img)
font = ImageFont.truetype("simsun.ttc", 18)
for text in response.text_annotations[1::]:
ocr = text.description
bound=text.bounding_poly
draw.text((bound.vertices[0].x-25, bound.vertices[0].y-25),ocr,fill=(255,0,0),font=font)
draw.polygon(
[
bound.vertices[0].x,
bound.vertices[0].y,
bound.vertices[1].x,
bound.vertices[1].y,
bound.vertices[2].x,
bound.vertices[2].y,
bound.vertices[3].x,
bound.vertices[3].y,
],
None,
'yellow',
)
texts=response.text_annotations
a=str(texts[0].description.split())
b=re.sub(u"([^\u4e00-\u9fa5\u0030-u0039])","",a)
b1="".join(b)
print("偵測到的地址為:",b1)
return b1
@handler.add(MessageEvent, message=ImageMessage)
def handle__message(event):
message_content = line_bot_api.get_message_content(event.message.id)
user = line_bot_api.get_profile(event.source.user_id)
data=b''
for chunk in message_content.iter_content():
data+= chunk
bucket_name = 'img_platecapture'
bucket = storage_client.bucket(bucket_name)
blob = bucket.blob(f'{user.user_id}.jpg')
blob.upload_from_string(data)
text_detected=text_detected(user.user_id) ##這裡出現問題
line_bot_api.reply_message(
event.reply_token,
messages=TextSendMessage(
text=text_detected
))