iT邦幫忙

0

無法接收回傳圖檔URL,顯示UnboundLocalError

  • 分享至 

  • xImage

我想在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
    ))
powerc iT邦新手 1 級 ‧ 2022-11-23 09:37:17 檢舉
你的變數名稱跟方法名稱寫一樣了,改其中一個
froce iT邦大師 1 級 ‧ 2022-11-23 09:46:34 檢舉
text_detected=text_detected(user.user_id)
把前面的text_detected換成其他的變數名應該就行了。

這是scope的問題,python直譯器會先在handle__message裡尋找變數,你定義了一個local var: text_detected,那python自然不會去外面尋找你定義的 global var的text_detected。

因為handle__message裡的text_detected是指local的,那 text_detected=text_detected(user.user_id) 這句就是會出問題。
簡單一點就是,這句的意思就是叫直譯器,你先指派一個 local var 叫 text_detected,他的值是 text_detected這個local var的執行結果,但在handle__message裡text_detected你根本就還沒指派,只是叫直譯器準備指派(初始化)

然後直譯器就會吐槽你在莊孝維,你現在才叫我初始化一個local var,那我要去哪裡生這個local var的執行結果給你。
@powerc
了解。魔鬼真的在細節裡。謝謝回覆!
@froce
哈哈,原來眉角在這裡,最後linebot 要回覆enduser訊息了,卻沒有計算值,難為直譯器了。謝謝您細心為新手解說!!
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答