Spaces:
Runtime error
Runtime error
Update main.py
Browse files
main.py
CHANGED
|
@@ -8,15 +8,94 @@ from linebot import LineBotApi, WebhookHandler
|
|
| 8 |
from linebot.exceptions import InvalidSignatureError
|
| 9 |
from linebot.models import MessageEvent, TextMessage, TextSendMessage, ImageSendMessage, AudioMessage
|
| 10 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
|
|
|
|
|
|
|
| 12 |
generation_config = genai.types.GenerationConfig(max_output_tokens=2048, temperature=0.2, top_p=0.5, top_k=16)
|
|
|
|
|
|
|
| 13 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 14 |
|
|
|
|
| 15 |
line_bot_api = LineBotApi(os.environ["CHANNEL_ACCESS_TOKEN"])
|
| 16 |
line_handler = WebhookHandler(os.environ["CHANNEL_SECRET"])
|
|
|
|
|
|
|
| 17 |
working_status = os.getenv("DEFALUT_TALKING", default = "true").lower() == "true"
|
| 18 |
|
|
|
|
| 19 |
app = FastAPI()
|
|
|
|
|
|
|
| 20 |
app.add_middleware(
|
| 21 |
CORSMiddleware,
|
| 22 |
allow_origins=["*"],
|
|
@@ -25,53 +104,111 @@ app.add_middleware(
|
|
| 25 |
allow_headers=["*"],
|
| 26 |
)
|
| 27 |
|
|
|
|
| 28 |
@app.get("/")
|
| 29 |
def root():
|
| 30 |
return {"title": "Line Bot"}
|
| 31 |
|
|
|
|
| 32 |
@app.post("/webhook")
|
| 33 |
async def webhook(
|
| 34 |
request: Request,
|
| 35 |
background_tasks: BackgroundTasks,
|
| 36 |
x_line_signature=Header(None),
|
| 37 |
):
|
|
|
|
| 38 |
body = await request.body()
|
| 39 |
try:
|
|
|
|
| 40 |
background_tasks.add_task(
|
| 41 |
line_handler.handle, body.decode("utf-8"), x_line_signature
|
| 42 |
)
|
| 43 |
except InvalidSignatureError:
|
|
|
|
| 44 |
raise HTTPException(status_code=400, detail="Invalid signature")
|
| 45 |
return "ok"
|
| 46 |
|
|
|
|
| 47 |
@line_handler.add(MessageEvent, message=TextMessage)
|
| 48 |
def handle_message(event):
|
| 49 |
global working_status
|
| 50 |
|
|
|
|
| 51 |
if event.type != "message" or event.message.type != "text":
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
|
|
|
| 54 |
elif event.message.text == "再見":
|
|
|
|
| 55 |
working_status = True
|
|
|
|
| 56 |
line_bot_api.reply_message(
|
| 57 |
event.reply_token,
|
| 58 |
-
TextSendMessage(text="Bye!")
|
|
|
|
| 59 |
return
|
| 60 |
|
|
|
|
| 61 |
elif working_status:
|
| 62 |
try:
|
|
|
|
| 63 |
prompt = event.message.text
|
|
|
|
| 64 |
completion = model.generate_content(prompt, generation_config=generation_config)
|
|
|
|
| 65 |
if (completion.parts[0].text != None):
|
|
|
|
| 66 |
out = completion.parts[0].text
|
| 67 |
else:
|
|
|
|
| 68 |
out = "Gemini沒答案!請換個說法!"
|
| 69 |
except:
|
|
|
|
| 70 |
out = "Gemini執行出錯!請換個說法!"
|
| 71 |
|
|
|
|
| 72 |
line_bot_api.reply_message(
|
| 73 |
event.reply_token,
|
| 74 |
TextSendMessage(text=out))
|
| 75 |
|
| 76 |
if __name__ == "__main__":
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
from linebot.exceptions import InvalidSignatureError
|
| 9 |
from linebot.models import MessageEvent, TextMessage, TextSendMessage, ImageSendMessage, AudioMessage
|
| 10 |
|
| 11 |
+
# genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
|
| 12 |
+
# generation_config = genai.types.GenerationConfig(max_output_tokens=2048, temperature=0.2, top_p=0.5, top_k=16)
|
| 13 |
+
# model = genai.GenerativeModel('gemini-1.5-flash')
|
| 14 |
+
|
| 15 |
+
# line_bot_api = LineBotApi(os.environ["CHANNEL_ACCESS_TOKEN"])
|
| 16 |
+
# line_handler = WebhookHandler(os.environ["CHANNEL_SECRET"])
|
| 17 |
+
# working_status = os.getenv("DEFALUT_TALKING", default = "true").lower() == "true"
|
| 18 |
+
|
| 19 |
+
# app = FastAPI()
|
| 20 |
+
# app.add_middleware(
|
| 21 |
+
# CORSMiddleware,
|
| 22 |
+
# allow_origins=["*"],
|
| 23 |
+
# allow_credentials=True,
|
| 24 |
+
# allow_methods=["*"],
|
| 25 |
+
# allow_headers=["*"],
|
| 26 |
+
# )
|
| 27 |
+
|
| 28 |
+
# @app.get("/")
|
| 29 |
+
# def root():
|
| 30 |
+
# return {"title": "Line Bot"}
|
| 31 |
+
|
| 32 |
+
# @app.post("/webhook")
|
| 33 |
+
# async def webhook(
|
| 34 |
+
# request: Request,
|
| 35 |
+
# background_tasks: BackgroundTasks,
|
| 36 |
+
# x_line_signature=Header(None),
|
| 37 |
+
# ):
|
| 38 |
+
# body = await request.body()
|
| 39 |
+
# try:
|
| 40 |
+
# background_tasks.add_task(
|
| 41 |
+
# line_handler.handle, body.decode("utf-8"), x_line_signature
|
| 42 |
+
# )
|
| 43 |
+
# except InvalidSignatureError:
|
| 44 |
+
# raise HTTPException(status_code=400, detail="Invalid signature")
|
| 45 |
+
# return "ok"
|
| 46 |
+
|
| 47 |
+
# @line_handler.add(MessageEvent, message=TextMessage)
|
| 48 |
+
# def handle_message(event):
|
| 49 |
+
# global working_status
|
| 50 |
+
|
| 51 |
+
# if event.type != "message" or event.message.type != "text":
|
| 52 |
+
# TextSendMessage(text="Event type error:[No message or the message does not contain text]")
|
| 53 |
+
|
| 54 |
+
# elif event.message.text == "再見":
|
| 55 |
+
# working_status = True
|
| 56 |
+
# line_bot_api.reply_message(
|
| 57 |
+
# event.reply_token,
|
| 58 |
+
# TextSendMessage(text="Bye!"))
|
| 59 |
+
# return
|
| 60 |
+
|
| 61 |
+
# elif working_status:
|
| 62 |
+
# try:
|
| 63 |
+
# prompt = event.message.text
|
| 64 |
+
# completion = model.generate_content(prompt, generation_config=generation_config)
|
| 65 |
+
# if (completion.parts[0].text != None):
|
| 66 |
+
# out = completion.parts[0].text
|
| 67 |
+
# else:
|
| 68 |
+
# out = "Gemini沒答案!請換個說法!"
|
| 69 |
+
# except:
|
| 70 |
+
# out = "Gemini執行出錯!請換個說法!"
|
| 71 |
+
|
| 72 |
+
# line_bot_api.reply_message(
|
| 73 |
+
# event.reply_token,
|
| 74 |
+
# TextSendMessage(text=out))
|
| 75 |
+
|
| 76 |
+
# if __name__ == "__main__":
|
| 77 |
+
# uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)
|
| 78 |
+
|
| 79 |
+
# 設定 Google AI API 金鑰
|
| 80 |
genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
|
| 81 |
+
|
| 82 |
+
# 設定生成文字的參數
|
| 83 |
generation_config = genai.types.GenerationConfig(max_output_tokens=2048, temperature=0.2, top_p=0.5, top_k=16)
|
| 84 |
+
|
| 85 |
+
# 使用 Gemini-1.5-flash 模型
|
| 86 |
model = genai.GenerativeModel('gemini-1.5-flash')
|
| 87 |
|
| 88 |
+
# 設定 Line Bot 的 API 金鑰和秘密金鑰
|
| 89 |
line_bot_api = LineBotApi(os.environ["CHANNEL_ACCESS_TOKEN"])
|
| 90 |
line_handler = WebhookHandler(os.environ["CHANNEL_SECRET"])
|
| 91 |
+
|
| 92 |
+
# 設定是否正在與使用者交談
|
| 93 |
working_status = os.getenv("DEFALUT_TALKING", default = "true").lower() == "true"
|
| 94 |
|
| 95 |
+
# 建立 FastAPI 應用程式
|
| 96 |
app = FastAPI()
|
| 97 |
+
|
| 98 |
+
# 設定 CORS,允許跨域請求
|
| 99 |
app.add_middleware(
|
| 100 |
CORSMiddleware,
|
| 101 |
allow_origins=["*"],
|
|
|
|
| 104 |
allow_headers=["*"],
|
| 105 |
)
|
| 106 |
|
| 107 |
+
# 處理根路徑請求
|
| 108 |
@app.get("/")
|
| 109 |
def root():
|
| 110 |
return {"title": "Line Bot"}
|
| 111 |
|
| 112 |
+
# 處理 Line Webhook 請求
|
| 113 |
@app.post("/webhook")
|
| 114 |
async def webhook(
|
| 115 |
request: Request,
|
| 116 |
background_tasks: BackgroundTasks,
|
| 117 |
x_line_signature=Header(None),
|
| 118 |
):
|
| 119 |
+
# 取得請求內容
|
| 120 |
body = await request.body()
|
| 121 |
try:
|
| 122 |
+
# 將處理 Line 事件的任務加入背景工作
|
| 123 |
background_tasks.add_task(
|
| 124 |
line_handler.handle, body.decode("utf-8"), x_line_signature
|
| 125 |
)
|
| 126 |
except InvalidSignatureError:
|
| 127 |
+
# 處理無效的簽章錯誤
|
| 128 |
raise HTTPException(status_code=400, detail="Invalid signature")
|
| 129 |
return "ok"
|
| 130 |
|
| 131 |
+
# 處理文字訊息事件
|
| 132 |
@line_handler.add(MessageEvent, message=TextMessage)
|
| 133 |
def handle_message(event):
|
| 134 |
global working_status
|
| 135 |
|
| 136 |
+
# 檢查事件類型和訊息類型
|
| 137 |
if event.type != "message" or event.message.type != "text":
|
| 138 |
+
# 回覆錯誤訊息
|
| 139 |
+
line_bot_api.reply_message(
|
| 140 |
+
event.reply_token,
|
| 141 |
+
TextSendMessage(text="Event type error:[No message or the message does not contain text]")
|
| 142 |
+
)
|
| 143 |
|
| 144 |
+
# 檢查使用者是否輸入 "再見"
|
| 145 |
elif event.message.text == "再見":
|
| 146 |
+
# 將 working_status 設定為 True,表示停止與使用者交談
|
| 147 |
working_status = True
|
| 148 |
+
# 回覆 "Bye!"
|
| 149 |
line_bot_api.reply_message(
|
| 150 |
event.reply_token,
|
| 151 |
+
TextSendMessage(text="Bye!")
|
| 152 |
+
)
|
| 153 |
return
|
| 154 |
|
| 155 |
+
# 檢查是否正��與使用者交談
|
| 156 |
elif working_status:
|
| 157 |
try:
|
| 158 |
+
# 取得使用者輸入的文字
|
| 159 |
prompt = event.message.text
|
| 160 |
+
# 使用 Gemini 模型生成文字
|
| 161 |
completion = model.generate_content(prompt, generation_config=generation_config)
|
| 162 |
+
# 檢查生成結果是否為空
|
| 163 |
if (completion.parts[0].text != None):
|
| 164 |
+
# 取得生成結果
|
| 165 |
out = completion.parts[0].text
|
| 166 |
else:
|
| 167 |
+
# 回覆 "Gemini沒答案!請換個說法!"
|
| 168 |
out = "Gemini沒答案!請換個說法!"
|
| 169 |
except:
|
| 170 |
+
# 處理錯誤
|
| 171 |
out = "Gemini執行出錯!請換個說法!"
|
| 172 |
|
| 173 |
+
# 回覆生成結果
|
| 174 |
line_bot_api.reply_message(
|
| 175 |
event.reply_token,
|
| 176 |
TextSendMessage(text=out))
|
| 177 |
|
| 178 |
if __name__ == "__main__":
|
| 179 |
+
# 啟動 FastAPI 應用程式
|
| 180 |
+
uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)
|
| 181 |
+
|
| 182 |
+
# 註解說明:
|
| 183 |
+
# import 導入必要的套件
|
| 184 |
+
# genai.configure 設定 Google AI API 金鑰
|
| 185 |
+
# generation_config 設定文字生成參數
|
| 186 |
+
# model 設定使用的 Gemini 模型
|
| 187 |
+
# line_bot_api 和 line_handler 設定 Line Bot API 和 webhook 處理器
|
| 188 |
+
# working_status 設定是否正在與使用者交談
|
| 189 |
+
# app 建立 FastAPI 應用程式
|
| 190 |
+
# app.add_middleware 設定 CORS
|
| 191 |
+
# @app.get("/") 處理根路徑請求
|
| 192 |
+
# @app.post("/webhook") 處理 Line Webhook 請求
|
| 193 |
+
# @line_handler.add(MessageEvent, message=TextMessage) 處理文字訊息事件
|
| 194 |
+
# if __name__ == "__main__": 啟動 FastAPI 應用程式
|
| 195 |
+
# 程式碼功能說明:
|
| 196 |
+
# 程式碼首先會導入必要的套件,並設定 Google AI API 金鑰、文字生成參數、Gemini 模型以及 Line Bot API。
|
| 197 |
+
# 接著會建立 FastAPI 應用程式,並設定 CORS。
|
| 198 |
+
# 程式碼會定義兩個函數:
|
| 199 |
+
# root() 處理根路徑請求,返回一個簡單的 JSON 訊息。
|
| 200 |
+
# webhook() 處理 Line Webhook 請求,將處理 Line 事件的任務加入背景工作,並處理無效的簽章錯誤。
|
| 201 |
+
# 程式碼還定義一個函數 handle_message() 來處理文字訊息事件,它會檢查事件類型和訊息類型,並根據使用者輸入執行不同的動作:
|
| 202 |
+
# 如果使用者輸入 "再見",則會將 working_status 設定為 True,表示停止與使用者交談,並回覆 "Bye!"。
|
| 203 |
+
# 如果正在與使用者交談,則會使用 Gemini 模型生成文字,並將結果回覆給使用者。
|
| 204 |
+
# 最後,程式碼會啟動 FastAPI 應用程式,開始監聽 HTTP 請求。
|
| 205 |
+
# 程式碼運行方式:
|
| 206 |
+
# 將程式碼存為 main.py 文件。
|
| 207 |
+
# 在環境變數中設定 GOOGLE_API_KEY、CHANNEL_ACCESS_TOKEN 和 CHANNEL_SECRET。
|
| 208 |
+
# 執行 uvicorn main:app --host 0.0.0.0 --port 7860 --reload 命令啟動 FastAPI 應用程式。
|
| 209 |
+
# 使用 Line 帳戶與 Line Bot 進行對話。
|
| 210 |
+
# 注意:
|
| 211 |
+
# 程式碼中使用 os.environ["GOOGLE_API_KEY"]、os.environ["CHANNEL_ACCESS_TOKEN"] 和 os.environ["CHANNEL_SECRET"] 來存取環境變數,需要先在環境變數中設定這些值。
|
| 212 |
+
# 程式碼中使用 uvicorn 執行 FastAPI 應用程式,需要先安裝 uvicorn 套件。
|
| 213 |
+
# 程式碼中使用 google.generativeai 套件,需要先安裝 google-generativeai 套件。
|
| 214 |
+
# 程式碼中使用 linebot 套件,需要先安裝 linebot 套件。
|