|
|
from fastapi.middleware.cors import CORSMiddleware |
|
|
from fastapi import FastAPI, Request, Header, BackgroundTasks, HTTPException, status |
|
|
from fastapi.staticfiles import StaticFiles |
|
|
from gradio_client import Client |
|
|
import json |
|
|
import os |
|
|
import requests |
|
|
import base64 |
|
|
|
|
|
from linebot import ( |
|
|
LineBotApi, WebhookHandler |
|
|
) |
|
|
from linebot.exceptions import ( |
|
|
InvalidSignatureError |
|
|
) |
|
|
from linebot.models import ( |
|
|
MessageEvent, TextMessage, ImageMessage, TextSendMessage, ImageSendMessage, AudioMessage |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
line_bot_api = LineBotApi(os.environ["CHANNEL_ACCESS_TOKEN"]) |
|
|
line_handler = WebhookHandler(os.environ["CHANNEL_SECRET"]) |
|
|
|
|
|
working_status = os.getenv("DEFALUT_TALKING", default = "true").lower() == "true" |
|
|
|
|
|
|
|
|
app = FastAPI() |
|
|
app.mount("/static", StaticFiles(directory="static"), name="static") |
|
|
|
|
|
|
|
|
server_url= 'ning8429-ragline.hf.space' |
|
|
api_img2text_url = 'https://ning8429-flask-docker.hf.space/predict' |
|
|
api_text2img_url = 'https://ning8429-flask-docker.hf.space/text2img' |
|
|
|
|
|
|
|
|
|
|
|
app.add_middleware( |
|
|
CORSMiddleware, |
|
|
allow_origins=["*"], |
|
|
allow_credentials=True, |
|
|
allow_methods=["*"], |
|
|
allow_headers=["*"], |
|
|
) |
|
|
|
|
|
|
|
|
@app.get("/") |
|
|
def root(): |
|
|
return {"title": "Line Bot"} |
|
|
|
|
|
|
|
|
@app.post("/webhook") |
|
|
async def webhook( |
|
|
request: Request, |
|
|
background_tasks: BackgroundTasks, |
|
|
x_line_signature=Header(None), |
|
|
): |
|
|
|
|
|
body = await request.body() |
|
|
try: |
|
|
|
|
|
background_tasks.add_task( |
|
|
line_handler.handle, body.decode("utf-8"), x_line_signature |
|
|
) |
|
|
except InvalidSignatureError: |
|
|
|
|
|
raise HTTPException(status_code=400, detail="Invalid signature") |
|
|
return "ok" |
|
|
|
|
|
|
|
|
@line_handler.add(MessageEvent, message=(ImageMessage, TextMessage)) |
|
|
def handle_message(event): |
|
|
global working_status |
|
|
|
|
|
|
|
|
if isinstance(event.message, ImageMessage): |
|
|
print(f"***** START 圖轉文 *****") |
|
|
|
|
|
|
|
|
line_bot_api.reply_message( |
|
|
event.reply_token, |
|
|
TextSendMessage(text="已成功接收您的圖片!正在為您搜尋寶寶名稱,請稍候片刻 😊") |
|
|
) |
|
|
|
|
|
|
|
|
try: |
|
|
message_content = line_bot_api.get_message_content(event.message.id) |
|
|
except Exception as e: |
|
|
print(f"Error fetching image content: {e}") |
|
|
|
|
|
|
|
|
input_name = 'input_'+event.message.id+'.jpg' |
|
|
path = './static/'+ input_name |
|
|
|
|
|
with open(path, 'wb') as fd: |
|
|
for chunk in message_content.iter_content(): |
|
|
print(f"Saving image to {path}") |
|
|
fd.write(chunk) |
|
|
|
|
|
img2_url='https://%s/static/'% server_url |
|
|
|
|
|
|
|
|
try: |
|
|
with open(path, 'rb') as image_file: |
|
|
|
|
|
files = {'image': image_file} |
|
|
data = { |
|
|
'message_id': event.message.id, |
|
|
"choice": "find_similar_words", |
|
|
"word": None, |
|
|
"top_k": 3 |
|
|
} |
|
|
|
|
|
|
|
|
response = requests.post(api_img2text_url, files=files, data=data) |
|
|
|
|
|
|
|
|
if response.status_code == 200: |
|
|
api_response = response.json() |
|
|
else: |
|
|
api_response = "Error calling FLASK API_response.status_code" |
|
|
|
|
|
except Exception as e: |
|
|
print(f"Error sending request to external API: {e}") |
|
|
api_response = "Error calling FLASK API_Exception" |
|
|
|
|
|
image_messages = [] |
|
|
|
|
|
|
|
|
|
|
|
for i, obj in enumerate(api_response['objects']): |
|
|
element = obj['element'] |
|
|
encoded_image = obj['images']['encoded_image'] |
|
|
description = obj['images']['description_list'].replace("\n", " ") |
|
|
|
|
|
print(f"===== 【{path}--> {element}】clip check: 【{description}】 =====") |
|
|
|
|
|
img_data = base64.b64decode(encoded_image) |
|
|
|
|
|
|
|
|
image_name = f"yolo_{event.message.id}_{i}.jpg" |
|
|
image_path = './static/' + image_name |
|
|
|
|
|
|
|
|
|
|
|
with open(image_path, 'wb') as file: |
|
|
file.write(img_data) |
|
|
|
|
|
|
|
|
output_url = f'https://{server_url}/static/{image_name}' |
|
|
|
|
|
|
|
|
image_messages.append( |
|
|
[ |
|
|
ImageSendMessage( |
|
|
original_content_url=output_url, |
|
|
preview_image_url=output_url |
|
|
), |
|
|
TextSendMessage(text=f"⬆ 這隻可能是💫~\n{description}") |
|
|
] |
|
|
) |
|
|
|
|
|
for message_group in image_messages: |
|
|
line_bot_api.push_message( |
|
|
event.source.user_id, |
|
|
message_group |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
elif isinstance(event.message, TextMessage): |
|
|
|
|
|
if event.message.text =="開始使用": |
|
|
|
|
|
line_bot_api.reply_message( |
|
|
event.reply_token, |
|
|
TextSendMessage(text="您好😊 請傳送寶寶照片找尋名字或是輸入關鍵字找尋圖片") |
|
|
) |
|
|
return |
|
|
|
|
|
|
|
|
line_bot_api.reply_message( |
|
|
event.reply_token, |
|
|
TextSendMessage(text="已成功接收您的搜尋文字!正在找尋對應的寶寶,請稍候片刻 😊") |
|
|
) |
|
|
|
|
|
|
|
|
text_message_content = event.message.text |
|
|
print(f"***** START 文轉圖 *****") |
|
|
|
|
|
|
|
|
try: |
|
|
data = { |
|
|
'message_id': event.message.id, |
|
|
"choice": "find_image_for_word", |
|
|
"word": text_message_content, |
|
|
"top_k": 3 |
|
|
} |
|
|
|
|
|
|
|
|
response = requests.post(api_text2img_url, data=data) |
|
|
|
|
|
|
|
|
if response.status_code == 200: |
|
|
api_response = response.json() |
|
|
|
|
|
|
|
|
encoded_image = api_response["encoded_image"] |
|
|
description = api_response["description"] |
|
|
|
|
|
print(f"===== 文轉圖 api_response:{api_response} =====") |
|
|
|
|
|
|
|
|
img_data = base64.b64decode(encoded_image) |
|
|
|
|
|
|
|
|
image_name = f"text2img_{event.message.id}.jpg" |
|
|
image_path = './static/' + image_name |
|
|
|
|
|
|
|
|
with open(image_path, 'wb') as file: |
|
|
file.write(img_data) |
|
|
|
|
|
|
|
|
output_url = f'https://{server_url}/static/{image_name}' |
|
|
|
|
|
|
|
|
line_bot_api.push_message( |
|
|
event.source.user_id, |
|
|
[ |
|
|
ImageSendMessage( |
|
|
original_content_url=output_url, |
|
|
preview_image_url=output_url |
|
|
), |
|
|
TextSendMessage(text=f"⬆️這是根據您的文字找到的寶寶💕\n{description}") |
|
|
] |
|
|
) |
|
|
else: |
|
|
line_bot_api.push_message( |
|
|
event.source.user_id, |
|
|
TextSendMessage(text="Error calling /text2img API: 非預期的狀態碼") |
|
|
) |
|
|
|
|
|
except Exception as e: |
|
|
print(f"Error sending request to external API: {e}") |
|
|
line_bot_api.push_message( |
|
|
event.source.user_id, |
|
|
TextSendMessage(text="Error calling FLASK API: 發送請求時出現異常") |
|
|
) |
|
|
|
|
|
else: |
|
|
|
|
|
line_bot_api.reply_message( |
|
|
event.reply_token, |
|
|
TextSendMessage(text="我們只接受圖片或文字訊息唷") |
|
|
) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__": |
|
|
|
|
|
uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|