Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,4 +1,8 @@
|
|
| 1 |
import sys
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
|
| 3 |
try:
|
| 4 |
import gradio as gr
|
|
@@ -6,6 +10,7 @@ try:
|
|
| 6 |
from datetime import datetime
|
| 7 |
import subprocess
|
| 8 |
from fastapi import FastAPI, Request, HTTPException
|
|
|
|
| 9 |
from linebot import LineBotApi, WebhookHandler
|
| 10 |
from linebot.exceptions import InvalidSignatureError
|
| 11 |
from linebot.models import MessageEvent, TextMessage, TextSendMessage
|
|
@@ -34,6 +39,15 @@ except Exception as e:
|
|
| 34 |
|
| 35 |
custom_api = FastAPI()
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
# ----------------------------
|
| 38 |
# 🛒 系統資料與設定
|
| 39 |
# ----------------------------
|
|
@@ -100,34 +114,29 @@ def handle_message(event):
|
|
| 100 |
print(f"回覆失敗: {e}")
|
| 101 |
|
| 102 |
# ----------------------------
|
| 103 |
-
# 💻 網頁後台邏輯 (
|
| 104 |
# ----------------------------
|
| 105 |
-
def
|
| 106 |
-
"""回傳
|
| 107 |
if not orders_db:
|
| 108 |
-
return
|
| 109 |
-
return
|
| 110 |
|
| 111 |
def get_revenue():
|
| 112 |
total = sum(order["總價"] for order in orders_db)
|
| 113 |
return f"### 💰 目前總營收:NT$ {total}"
|
| 114 |
|
| 115 |
def refresh_data():
|
| 116 |
-
return
|
| 117 |
|
| 118 |
def add_order(c_name, q0, q1, q2, q3, q4, nts):
|
| 119 |
try:
|
| 120 |
-
# 強制轉型確保安全
|
| 121 |
c_name = str(c_name) if c_name else ""
|
| 122 |
nts = str(nts) if nts else ""
|
| 123 |
quantities = [q0, q1, q2, q3, q4]
|
| 124 |
|
| 125 |
if not c_name.strip():
|
| 126 |
-
return (
|
| 127 |
-
gr.update(value="❌ 錯誤:請輸入顧客姓名"),
|
| 128 |
-
gr.update(value=get_orders_df()),
|
| 129 |
-
gr.update(value=get_revenue())
|
| 130 |
-
)
|
| 131 |
|
| 132 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 133 |
total_order_price = 0
|
|
@@ -153,41 +162,25 @@ def add_order(c_name, q0, q1, q2, q3, q4, nts):
|
|
| 153 |
items_desc.append(f"{item}x{qty}")
|
| 154 |
|
| 155 |
if not has_ordered_items:
|
| 156 |
-
return (
|
| 157 |
-
gr.update(value="❌ 錯誤:請至少設定一項商品的數量(大於 0)"),
|
| 158 |
-
gr.update(value=get_orders_df()),
|
| 159 |
-
gr.update(value=get_revenue())
|
| 160 |
-
)
|
| 161 |
|
| 162 |
msg = f"✅ 成功新增訂單:{c_name.strip()} 訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。"
|
| 163 |
-
return (
|
| 164 |
-
gr.update(value=msg),
|
| 165 |
-
gr.update(value=get_orders_df()),
|
| 166 |
-
gr.update(value=get_revenue())
|
| 167 |
-
)
|
| 168 |
|
| 169 |
except Exception as e:
|
| 170 |
-
return (
|
| 171 |
-
gr.update(value=f"❌ 系統發生異常:{str(e)}"),
|
| 172 |
-
gr.update(value=get_orders_df()),
|
| 173 |
-
gr.update(value=get_revenue())
|
| 174 |
-
)
|
| 175 |
|
| 176 |
def clear_orders():
|
| 177 |
orders_db.clear()
|
| 178 |
-
return (
|
| 179 |
-
gr.update(value="🗑️ 所有訂單已清空"),
|
| 180 |
-
gr.update(value=get_orders_df()),
|
| 181 |
-
gr.update(value=get_revenue())
|
| 182 |
-
)
|
| 183 |
|
| 184 |
def verify_password(pwd):
|
| 185 |
if pwd == "0000":
|
| 186 |
-
return gr.update(visible=False), gr.update(visible=True),
|
| 187 |
-
return gr.update(visible=True), gr.update(visible=False),
|
| 188 |
|
| 189 |
def logout():
|
| 190 |
-
return gr.update(visible=True), gr.update(visible=False),
|
| 191 |
|
| 192 |
def run_git_cmd(command):
|
| 193 |
result = subprocess.run(command, shell=True, text=True, capture_output=True)
|
|
@@ -197,7 +190,12 @@ def run_git_cmd(command):
|
|
| 197 |
|
| 198 |
def backup_and_push_to_github():
|
| 199 |
log_messages = ["🚀 開始備份...\n" + "-"*40]
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
backup_filename = "orders_backup.csv"
|
| 203 |
df.to_csv(backup_filename, index=False, encoding="utf-8-sig")
|
|
@@ -212,13 +210,13 @@ def backup_and_push_to_github():
|
|
| 212 |
|
| 213 |
if not success and ("nothing to commit" in msg or "無檔案要提交" in msg):
|
| 214 |
log_messages.append("ℹ️ 無變更。\n✅ 結束。")
|
| 215 |
-
return
|
| 216 |
|
| 217 |
success, msg = run_git_cmd("git push origin main")
|
| 218 |
log_messages.append(msg)
|
| 219 |
if success:
|
| 220 |
log_messages.append("🎉 雲端備份完成!")
|
| 221 |
-
return
|
| 222 |
|
| 223 |
# ----------------------------
|
| 224 |
# 🖥️ 網頁介面 (UI)
|
|
@@ -267,7 +265,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統", css=cus
|
|
| 267 |
gr.Markdown("### ☁️ 雲端備份")
|
| 268 |
github_btn = gr.Button("🔄 備份至 GitHub", variant="primary")
|
| 269 |
|
| 270 |
-
orders_table = gr.Dataframe(value=
|
| 271 |
github_log_output = gr.Textbox(label="執行日誌", interactive=False, lines=4, elem_classes="github-log")
|
| 272 |
clear_btn = gr.Button("🗑️ 清空所有訂單", variant="stop")
|
| 273 |
|
|
@@ -284,9 +282,7 @@ with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統", css=cus
|
|
| 284 |
# ----------------------------
|
| 285 |
# 🚀 啟動伺服器
|
| 286 |
# ----------------------------
|
| 287 |
-
# 【
|
| 288 |
-
demo_ui.queue()
|
| 289 |
-
|
| 290 |
app = gr.mount_gradio_app(custom_api, demo_ui, path="/")
|
| 291 |
|
| 292 |
if __name__ == "__main__":
|
|
|
|
| 1 |
import sys
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
# 【關鍵修正 1】關閉 Gradio 嚴格的 CSRF 防護,避免在 HF Spaces 加上 FastAPI 後按鈕被阻擋
|
| 5 |
+
os.environ["GRADIO_CSRF_TRUST_ORIGINS"] = "*"
|
| 6 |
|
| 7 |
try:
|
| 8 |
import gradio as gr
|
|
|
|
| 10 |
from datetime import datetime
|
| 11 |
import subprocess
|
| 12 |
from fastapi import FastAPI, Request, HTTPException
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
from linebot import LineBotApi, WebhookHandler
|
| 15 |
from linebot.exceptions import InvalidSignatureError
|
| 16 |
from linebot.models import MessageEvent, TextMessage, TextSendMessage
|
|
|
|
| 39 |
|
| 40 |
custom_api = FastAPI()
|
| 41 |
|
| 42 |
+
# 【關鍵修正 2】加入跨域資源共用 (CORS) 中介軟體,確保按鈕送出的 API 請求不會被瀏覽器攔截
|
| 43 |
+
custom_api.add_middleware(
|
| 44 |
+
CORSMiddleware,
|
| 45 |
+
allow_origins=["*"],
|
| 46 |
+
allow_credentials=True,
|
| 47 |
+
allow_methods=["*"],
|
| 48 |
+
allow_headers=["*"],
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
# ----------------------------
|
| 52 |
# 🛒 系統資料與設定
|
| 53 |
# ----------------------------
|
|
|
|
| 114 |
print(f"回覆失敗: {e}")
|
| 115 |
|
| 116 |
# ----------------------------
|
| 117 |
+
# 💻 網頁後台邏輯 (全面改用純值傳遞,防止前端畫面凍結)
|
| 118 |
# ----------------------------
|
| 119 |
+
def get_orders_data():
|
| 120 |
+
"""【關鍵修正 3】回傳純 Python 二維陣列,取代 Pandas DataFrame,杜絕序列化崩潰問題"""
|
| 121 |
if not orders_db:
|
| 122 |
+
return []
|
| 123 |
+
return [[o["時間"], o["顧客姓名"], o["商品"], o["單價"], o["數量"], o["總價"], o["備註"]] for o in orders_db]
|
| 124 |
|
| 125 |
def get_revenue():
|
| 126 |
total = sum(order["總價"] for order in orders_db)
|
| 127 |
return f"### 💰 目前總營收:NT$ {total}"
|
| 128 |
|
| 129 |
def refresh_data():
|
| 130 |
+
return get_orders_data(), get_revenue()
|
| 131 |
|
| 132 |
def add_order(c_name, q0, q1, q2, q3, q4, nts):
|
| 133 |
try:
|
|
|
|
| 134 |
c_name = str(c_name) if c_name else ""
|
| 135 |
nts = str(nts) if nts else ""
|
| 136 |
quantities = [q0, q1, q2, q3, q4]
|
| 137 |
|
| 138 |
if not c_name.strip():
|
| 139 |
+
return "❌ 錯誤:請輸入顧客姓名", get_orders_data(), get_revenue()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 140 |
|
| 141 |
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 142 |
total_order_price = 0
|
|
|
|
| 162 |
items_desc.append(f"{item}x{qty}")
|
| 163 |
|
| 164 |
if not has_ordered_items:
|
| 165 |
+
return "❌ 錯誤:請至少設定一項商品的數量(大於 0)", get_orders_data(), get_revenue()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
msg = f"✅ 成功新增訂單:{c_name.strip()} 訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。"
|
| 168 |
+
return msg, get_orders_data(), get_revenue()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
|
| 170 |
except Exception as e:
|
| 171 |
+
return f"❌ 系統發生異常:{str(e)}", get_orders_data(), get_revenue()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
|
| 173 |
def clear_orders():
|
| 174 |
orders_db.clear()
|
| 175 |
+
return "🗑️ 所有訂單已清空", get_orders_data(), get_revenue()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
def verify_password(pwd):
|
| 178 |
if pwd == "0000":
|
| 179 |
+
return gr.update(visible=False), gr.update(visible=True), ""
|
| 180 |
+
return gr.update(visible=True), gr.update(visible=False), "❌ **密碼錯誤。**"
|
| 181 |
|
| 182 |
def logout():
|
| 183 |
+
return gr.update(visible=True), gr.update(visible=False), "", ""
|
| 184 |
|
| 185 |
def run_git_cmd(command):
|
| 186 |
result = subprocess.run(command, shell=True, text=True, capture_output=True)
|
|
|
|
| 190 |
|
| 191 |
def backup_and_push_to_github():
|
| 192 |
log_messages = ["🚀 開始備份...\n" + "-"*40]
|
| 193 |
+
|
| 194 |
+
# 只有這裡保留 pandas 供寫出 CSV 檔案使用
|
| 195 |
+
if not orders_db:
|
| 196 |
+
df = pd.DataFrame(columns=["時間", "顧客姓名", "商品", "單價", "數量", "總價", "備註"])
|
| 197 |
+
else:
|
| 198 |
+
df = pd.DataFrame(orders_db)
|
| 199 |
|
| 200 |
backup_filename = "orders_backup.csv"
|
| 201 |
df.to_csv(backup_filename, index=False, encoding="utf-8-sig")
|
|
|
|
| 210 |
|
| 211 |
if not success and ("nothing to commit" in msg or "無檔案要提交" in msg):
|
| 212 |
log_messages.append("ℹ️ 無變更。\n✅ 結束。")
|
| 213 |
+
return "\n\n".join(log_messages)
|
| 214 |
|
| 215 |
success, msg = run_git_cmd("git push origin main")
|
| 216 |
log_messages.append(msg)
|
| 217 |
if success:
|
| 218 |
log_messages.append("🎉 雲端備份完成!")
|
| 219 |
+
return "\n\n".join(log_messages)
|
| 220 |
|
| 221 |
# ----------------------------
|
| 222 |
# 🖥️ 網頁介面 (UI)
|
|
|
|
| 265 |
gr.Markdown("### ☁️ 雲端備份")
|
| 266 |
github_btn = gr.Button("🔄 備份至 GitHub", variant="primary")
|
| 267 |
|
| 268 |
+
orders_table = gr.Dataframe(value=get_orders_data(), headers=["時間", "顧客姓名", "商品", "單價", "數量", "總價", "備註"], interactive=False)
|
| 269 |
github_log_output = gr.Textbox(label="執行日誌", interactive=False, lines=4, elem_classes="github-log")
|
| 270 |
clear_btn = gr.Button("🗑️ 清空所有訂單", variant="stop")
|
| 271 |
|
|
|
|
| 282 |
# ----------------------------
|
| 283 |
# 🚀 啟動伺服器
|
| 284 |
# ----------------------------
|
| 285 |
+
# 【關鍵修正 4】移除了 .queue(),避免 WebSocket 在雲端環境中被錯誤阻擋,強迫回歸最穩定的 HTTP 連線
|
|
|
|
|
|
|
| 286 |
app = gr.mount_gradio_app(custom_api, demo_ui, path="/")
|
| 287 |
|
| 288 |
if __name__ == "__main__":
|