Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,1130 +0,0 @@
|
|
| 1 |
-
import sys
|
| 2 |
-
import os
|
| 3 |
-
import json
|
| 4 |
-
import base64
|
| 5 |
-
import uuid
|
| 6 |
-
from datetime import datetime, timezone, timedelta
|
| 7 |
-
|
| 8 |
-
# 【終極防護設定】精準設定您的專屬網址,避免使用萬用字元 (*) 導致手機 Safari 阻擋連線
|
| 9 |
-
os.environ["GRADIO_CSRF_TRUST_ORIGINS"] = "https://schillercfk-ssys.hf.space"
|
| 10 |
-
|
| 11 |
-
# 【設定台北時區】確保雲端伺服器產生正確的台灣時間 (UTC+8)
|
| 12 |
-
TAIPEI_TZ = timezone(timedelta(hours=8))
|
| 13 |
-
|
| 14 |
-
try:
|
| 15 |
-
import gradio as gr
|
| 16 |
-
import pandas as pd
|
| 17 |
-
import subprocess
|
| 18 |
-
from fastapi import FastAPI, Request, HTTPException
|
| 19 |
-
from linebot import LineBotApi, WebhookHandler
|
| 20 |
-
from linebot.exceptions import InvalidSignatureError
|
| 21 |
-
from linebot.models import MessageEvent, TextMessage, TextSendMessage
|
| 22 |
-
import uvicorn
|
| 23 |
-
except ImportError as e:
|
| 24 |
-
print(f"❌ 啟動失敗:缺少必要的套件!請檢查 requirements.txt。詳細錯誤:{e}")
|
| 25 |
-
sys.exit(1)
|
| 26 |
-
|
| 27 |
-
# ----------------------------
|
| 28 |
-
# 📱 LINE Bot 設定區
|
| 29 |
-
# ----------------------------
|
| 30 |
-
RAW_ACCESS_TOKEN = "HadCmCBmnZtI4LjC1Ad2rBwGZX7x1jZu4A0DXCX+LIjt3SpQq0vVz1kh8U74GB2XPbRdgwfqvFcVRR+i0NodOZ2P6hPC5ZV8EuxPOt+WnAvTJ29P5UBoENQCVAxu/AuRP2xgYKNYOg5voggl73mfkgdB04t89/1O/w1cDnyilFU="
|
| 31 |
-
RAW_SECRET = "ae66c98db5eca3e75aff2ff28ef62f25"
|
| 32 |
-
|
| 33 |
-
WEB_ORDER_URL = "https://schillercfk-ssys.hf.space/?openExternalBrowser=1"
|
| 34 |
-
|
| 35 |
-
LINE_CHANNEL_ACCESS_TOKEN = RAW_ACCESS_TOKEN.replace(" ", "").strip()
|
| 36 |
-
LINE_CHANNEL_SECRET = RAW_SECRET.replace(" ", "").strip()
|
| 37 |
-
|
| 38 |
-
try:
|
| 39 |
-
line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN)
|
| 40 |
-
handler = WebhookHandler(LINE_CHANNEL_SECRET)
|
| 41 |
-
except Exception as e:
|
| 42 |
-
print(f"❌ LINE API 初始化失敗:{e}")
|
| 43 |
-
|
| 44 |
-
custom_api = FastAPI()
|
| 45 |
-
|
| 46 |
-
# ----------------------------
|
| 47 |
-
# 🛒 系統資料與動態設定 (菜單與密碼)
|
| 48 |
-
# ----------------------------
|
| 49 |
-
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 50 |
-
MENU_FILE = os.path.join(BASE_DIR, "menu.json")
|
| 51 |
-
PWD_FILE = os.path.join(BASE_DIR, "admin_pwd.json")
|
| 52 |
-
ORDERS_FILE = os.path.join(BASE_DIR, "orders.json")
|
| 53 |
-
BACKUP_FILE = os.path.join(BASE_DIR, "orders_backup.csv")
|
| 54 |
-
MENU_BACKUP_FILE = os.path.join(BASE_DIR, "menu_backup.csv")
|
| 55 |
-
|
| 56 |
-
def load_orders():
|
| 57 |
-
"""從檔案讀取訂單。如果 JSON 不存在,則自動嘗試從 CSV 備份中還原資料"""
|
| 58 |
-
loaded_data = []
|
| 59 |
-
|
| 60 |
-
if os.path.exists(ORDERS_FILE):
|
| 61 |
-
try:
|
| 62 |
-
with open(ORDERS_FILE, "r", encoding="utf-8") as f:
|
| 63 |
-
loaded_data = json.load(f)
|
| 64 |
-
except Exception as e:
|
| 65 |
-
print(f"讀取 orders.json 失敗: {e}")
|
| 66 |
-
|
| 67 |
-
if not loaded_data and os.path.exists(BACKUP_FILE):
|
| 68 |
-
if os.path.getsize(BACKUP_FILE) > 0:
|
| 69 |
-
try:
|
| 70 |
-
df = pd.read_csv(BACKUP_FILE)
|
| 71 |
-
df = df.fillna("")
|
| 72 |
-
loaded_data = df.to_dict('records')
|
| 73 |
-
|
| 74 |
-
for o in loaded_data:
|
| 75 |
-
o["單價"] = int(float(o.get("單價", 0) or 0))
|
| 76 |
-
o["成本"] = int(float(o.get("成本", 0) or 0))
|
| 77 |
-
o["數量"] = int(float(o.get("數量", 0) or 0))
|
| 78 |
-
o["總價"] = int(float(o.get("總價", 0) or 0))
|
| 79 |
-
o["總成本"] = int(float(o.get("總成本", 0) or 0))
|
| 80 |
-
if "時間" in o and "訂單時間" not in o:
|
| 81 |
-
o["時間"] = o["時間"]
|
| 82 |
-
|
| 83 |
-
with open(ORDERS_FILE, "w", encoding="utf-8") as f:
|
| 84 |
-
json.dump(loaded_data, f, ensure_ascii=False, indent=4)
|
| 85 |
-
|
| 86 |
-
except pd.errors.EmptyDataError:
|
| 87 |
-
print("⚠️ 備份檔是空的 (EmptyDataError),無法還原。")
|
| 88 |
-
except Exception as e:
|
| 89 |
-
print(f"❌ 從 CSV 還原失敗: {e}")
|
| 90 |
-
else:
|
| 91 |
-
print("⚠️ 備份檔 orders_backup.csv 是空白檔案 (0 byte),無法還原。")
|
| 92 |
-
|
| 93 |
-
return loaded_data
|
| 94 |
-
|
| 95 |
-
def save_orders():
|
| 96 |
-
"""將訂單儲存到 JSON 檔案中,確保資料不遺失"""
|
| 97 |
-
try:
|
| 98 |
-
with open(ORDERS_FILE, "w", encoding="utf-8") as f:
|
| 99 |
-
json.dump(orders_db, f, ensure_ascii=False, indent=4)
|
| 100 |
-
except Exception as e:
|
| 101 |
-
print(f"儲存訂單失敗: {e}")
|
| 102 |
-
|
| 103 |
-
# 初始化全域訂單資料庫
|
| 104 |
-
orders_db = load_orders()
|
| 105 |
-
|
| 106 |
-
def load_menu():
|
| 107 |
-
"""從檔案讀取菜單,支援 json 讀取與 csv 自動還原,包含分類、規格與備註"""
|
| 108 |
-
loaded_menu = {}
|
| 109 |
-
|
| 110 |
-
# 1. 優先讀取 JSON
|
| 111 |
-
if os.path.exists(MENU_FILE):
|
| 112 |
-
try:
|
| 113 |
-
with open(MENU_FILE, "r", encoding="utf-8") as f:
|
| 114 |
-
loaded_menu = json.load(f)
|
| 115 |
-
except Exception as e:
|
| 116 |
-
print(f"讀取菜單 JSON 失敗: {e}")
|
| 117 |
-
|
| 118 |
-
# 2. 若 JSON 無資料,嘗試從 CSV 備份還原
|
| 119 |
-
if not loaded_menu and os.path.exists(MENU_BACKUP_FILE):
|
| 120 |
-
if os.path.getsize(MENU_BACKUP_FILE) > 0:
|
| 121 |
-
try:
|
| 122 |
-
df = pd.read_csv(MENU_BACKUP_FILE)
|
| 123 |
-
for _, row in df.iterrows():
|
| 124 |
-
seq = int(row.get("流水號", 999))
|
| 125 |
-
val_enable = row.get("啟用", True)
|
| 126 |
-
if isinstance(val_enable, str):
|
| 127 |
-
enable = val_enable.lower() in ["true", "1", "yes", "是", "t"]
|
| 128 |
-
else:
|
| 129 |
-
enable = bool(val_enable)
|
| 130 |
-
|
| 131 |
-
cat = str(row.get("分類", "未分類")).strip()
|
| 132 |
-
if not cat: cat = "未分類"
|
| 133 |
-
|
| 134 |
-
item = str(row.get("品項", "")).strip()
|
| 135 |
-
spec = str(row.get("規格", "")).strip() if pd.notna(row.get("規格", "")) else ""
|
| 136 |
-
price = int(float(row.get("價格", 0) or 0))
|
| 137 |
-
cost = int(float(row.get("成本", 0) or 0))
|
| 138 |
-
note = str(row.get("備註", "")).strip() if pd.notna(row.get("備註", "")) else ""
|
| 139 |
-
|
| 140 |
-
if item and price > 0:
|
| 141 |
-
loaded_menu[item] = {"price": price, "cost": cost, "enable": enable, "seq": seq, "category": cat, "spec": spec, "note": note}
|
| 142 |
-
|
| 143 |
-
with open(MENU_FILE, "w", encoding="utf-8") as f:
|
| 144 |
-
json.dump(loaded_menu, f, ensure_ascii=False, indent=4)
|
| 145 |
-
except Exception as e:
|
| 146 |
-
print(f"從 CSV 還原菜單失敗: {e}")
|
| 147 |
-
|
| 148 |
-
# 3. 預設菜單兜底防呆
|
| 149 |
-
if not loaded_menu:
|
| 150 |
-
loaded_menu = {
|
| 151 |
-
"招牌咖啡": {"price": 80, "cost": 30, "enable": True, "seq": 1, "category": "☕ 咖啡飲品", "spec": "中杯", "note": ""},
|
| 152 |
-
"拿鐵咖啡": {"price": 100, "cost": 40, "enable": True, "seq": 2, "category": "☕ 咖啡飲品", "spec": "中杯", "note": ""},
|
| 153 |
-
"珍珠奶茶": {"price": 60, "cost": 20, "enable": True, "seq": 3, "category": "🧋 特調茶飲", "spec": "大杯", "note": ""},
|
| 154 |
-
"高山青茶": {"price": 40, "cost": 15, "enable": True, "seq": 4, "category": "🧋 特調茶飲", "spec": "大杯", "note": ""},
|
| 155 |
-
"手工餅乾": {"price": 50, "cost": 20, "enable": True, "seq": 5, "category": "🍪 美味點心", "spec": "一份", "note": ""}
|
| 156 |
-
}
|
| 157 |
-
else:
|
| 158 |
-
# 相容舊版資料:補齊可能缺少的欄位
|
| 159 |
-
for i, (k, v) in enumerate(loaded_menu.items()):
|
| 160 |
-
if isinstance(v, (int, float)):
|
| 161 |
-
loaded_menu[k] = {"price": int(v), "cost": 0, "enable": True, "seq": i+1, "category": "未分類", "spec": "", "note": ""}
|
| 162 |
-
else:
|
| 163 |
-
if "enable" not in v: v["enable"] = True
|
| 164 |
-
if "seq" not in v: v["seq"] = i + 1
|
| 165 |
-
if "category" not in v: v["category"] = "未分類"
|
| 166 |
-
if "spec" not in v: v["spec"] = ""
|
| 167 |
-
if "note" not in v: v["note"] = ""
|
| 168 |
-
|
| 169 |
-
return loaded_menu
|
| 170 |
-
|
| 171 |
-
def load_pwd():
|
| 172 |
-
"""從檔案讀取密碼,預設為 0000"""
|
| 173 |
-
if os.path.exists(PWD_FILE):
|
| 174 |
-
try:
|
| 175 |
-
with open(PWD_FILE, "r", encoding="utf-8") as f:
|
| 176 |
-
return json.load(f).get("password", "0000")
|
| 177 |
-
except Exception as e:
|
| 178 |
-
print(f"讀取密碼失敗,使用預設密碼 0000: {e}")
|
| 179 |
-
return "0000"
|
| 180 |
-
|
| 181 |
-
# 初始化全域變數
|
| 182 |
-
MENU = load_menu()
|
| 183 |
-
ADMIN_PASSWORD = load_pwd()
|
| 184 |
-
|
| 185 |
-
# 【新增前端分類輔助函數】:確保前後台排序與對應絕對精準
|
| 186 |
-
def get_frontend_menu_items():
|
| 187 |
-
enabled_items = sorted([(k, v) for k, v in MENU.items() if v.get("enable", True)], key=lambda x: x[1].get("seq", 999))
|
| 188 |
-
category_order = []
|
| 189 |
-
items_by_cat = {}
|
| 190 |
-
|
| 191 |
-
for item, details in enabled_items:
|
| 192 |
-
cat = details.get("category", "未分類")
|
| 193 |
-
cat = cat.strip() if cat.strip() else "未分類"
|
| 194 |
-
if cat not in category_order:
|
| 195 |
-
category_order.append(cat)
|
| 196 |
-
items_by_cat.setdefault(cat, []).append((item, details))
|
| 197 |
-
|
| 198 |
-
flat_list = []
|
| 199 |
-
for cat in category_order:
|
| 200 |
-
flat_list.extend(items_by_cat[cat])
|
| 201 |
-
|
| 202 |
-
return category_order, items_by_cat, flat_list
|
| 203 |
-
|
| 204 |
-
def get_menu_df():
|
| 205 |
-
"""產生包含流水號、啟用、分類等 8 個欄位的 DataFrame"""
|
| 206 |
-
sorted_menu = sorted(MENU.items(), key=lambda x: x[1].get("seq", 999))
|
| 207 |
-
|
| 208 |
-
data = []
|
| 209 |
-
for k, v in sorted_menu:
|
| 210 |
-
data.append([
|
| 211 |
-
v.get("seq", 999),
|
| 212 |
-
v.get("enable", True),
|
| 213 |
-
v.get("category", "未分類"),
|
| 214 |
-
k,
|
| 215 |
-
v.get("spec", ""),
|
| 216 |
-
v.get("price", 0),
|
| 217 |
-
v.get("cost", 0),
|
| 218 |
-
v.get("note", "")
|
| 219 |
-
])
|
| 220 |
-
|
| 221 |
-
max_seq = max([v.get("seq", 0) for v in MENU.values()]) if MENU else 0
|
| 222 |
-
|
| 223 |
-
for i in range(5):
|
| 224 |
-
data.append([max_seq + i + 1, False, "未分類", "", "", 0, 0, ""])
|
| 225 |
-
|
| 226 |
-
return pd.DataFrame(data, columns=["流水號", "啟用", "分類", "品項", "規格", "價格", "成本", "備註"])
|
| 227 |
-
|
| 228 |
-
def save_menu_to_file():
|
| 229 |
-
try:
|
| 230 |
-
with open(MENU_FILE, "w", encoding="utf-8") as f:
|
| 231 |
-
json.dump(MENU, f, ensure_ascii=False, indent=4)
|
| 232 |
-
except Exception as e:
|
| 233 |
-
print(f"儲存菜單失敗: {e}")
|
| 234 |
-
|
| 235 |
-
def save_pwd_to_file(new_pwd):
|
| 236 |
-
global ADMIN_PASSWORD
|
| 237 |
-
ADMIN_PASSWORD = new_pwd
|
| 238 |
-
try:
|
| 239 |
-
with open(PWD_FILE, "w", encoding="utf-8") as f:
|
| 240 |
-
json.dump({"password": new_pwd}, f, ensure_ascii=False, indent=4)
|
| 241 |
-
except Exception as e:
|
| 242 |
-
print(f"儲存密碼失敗: {e}")
|
| 243 |
-
|
| 244 |
-
def update_menu(df):
|
| 245 |
-
global MENU
|
| 246 |
-
new_menu = {}
|
| 247 |
-
|
| 248 |
-
for row in df.values.tolist():
|
| 249 |
-
# [0]流水號, [1]啟用, [2]分類, [3]品項, [4]規格, [5]價格, [6]成本, [7]備註
|
| 250 |
-
try: seq = int(float(row[0])) if pd.notna(row[0]) and str(row[0]).strip() else 999
|
| 251 |
-
except: seq = 999
|
| 252 |
-
|
| 253 |
-
val_enable = row[1]
|
| 254 |
-
if pd.isna(val_enable): enable = False
|
| 255 |
-
elif isinstance(val_enable, str): enable = str(val_enable).strip().lower() in ["true", "1", "yes", "是", "t"]
|
| 256 |
-
else: enable = bool(val_enable)
|
| 257 |
-
|
| 258 |
-
cat = str(row[2]).strip() if pd.notna(row[2]) and str(row[2]).strip() else "未分類"
|
| 259 |
-
item = str(row[3]).strip() if pd.notna(row[3]) and str(row[3]).strip() else ""
|
| 260 |
-
spec = str(row[4]).strip() if pd.notna(row[4]) else ""
|
| 261 |
-
|
| 262 |
-
try: price = int(float(row[5])) if pd.notna(row[5]) else 0
|
| 263 |
-
except: price = 0
|
| 264 |
-
|
| 265 |
-
try: cost = int(float(row[6])) if pd.notna(row[6]) else 0
|
| 266 |
-
except: cost = 0
|
| 267 |
-
|
| 268 |
-
note = str(row[7]).strip() if pd.notna(row[7]) else ""
|
| 269 |
-
|
| 270 |
-
if item and price > 0:
|
| 271 |
-
new_menu[item] = {"price": price, "cost": cost, "enable": enable, "seq": seq, "category": cat, "spec": spec, "note": note}
|
| 272 |
-
|
| 273 |
-
if not new_menu:
|
| 274 |
-
return gr.update(value="❌ 錯誤:菜單不能為空!"), get_menu_df(), gr.skip()
|
| 275 |
-
|
| 276 |
-
MENU.clear()
|
| 277 |
-
MENU.update(new_menu)
|
| 278 |
-
save_menu_to_file()
|
| 279 |
-
|
| 280 |
-
new_trigger = datetime.now(TAIPEI_TZ).timestamp()
|
| 281 |
-
return gr.update(value=f"✅ 菜單已成功更新!({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})"), get_menu_df(), new_trigger
|
| 282 |
-
|
| 283 |
-
def change_password(old_pwd, new_pwd):
|
| 284 |
-
if not new_pwd.strip():
|
| 285 |
-
return gr.update(value="❌ 新密碼不能為空白!")
|
| 286 |
-
if old_pwd != ADMIN_PASSWORD:
|
| 287 |
-
return gr.update(value="❌ 舊密碼輸入錯誤,請重新確認!")
|
| 288 |
-
|
| 289 |
-
save_pwd_to_file(new_pwd.strip())
|
| 290 |
-
return gr.update(value=f"✅ 密碼修改成功!下次登入請使用新密碼。({datetime.now(TAIPEI_TZ).strftime('%H:%M:%S')})")
|
| 291 |
-
|
| 292 |
-
# ----------------------------
|
| 293 |
-
# 🤖 LINE Bot 邏輯
|
| 294 |
-
# ----------------------------
|
| 295 |
-
@custom_api.post("/callback")
|
| 296 |
-
async def callback(request: Request):
|
| 297 |
-
signature = request.headers.get("X-Line-Signature", "")
|
| 298 |
-
body = await request.body()
|
| 299 |
-
body_str = body.decode("utf-8")
|
| 300 |
-
try:
|
| 301 |
-
handler.handle(body_str, signature)
|
| 302 |
-
except InvalidSignatureError:
|
| 303 |
-
raise HTTPException(status_code=400, detail="Invalid signature")
|
| 304 |
-
return "OK"
|
| 305 |
-
|
| 306 |
-
@handler.add(MessageEvent, message=TextMessage)
|
| 307 |
-
def handle_message(event):
|
| 308 |
-
user_msg = event.message.text.strip()
|
| 309 |
-
user_id = event.source.user_id
|
| 310 |
-
|
| 311 |
-
if "我要訂" in user_msg:
|
| 312 |
-
try:
|
| 313 |
-
parts = user_msg.split()
|
| 314 |
-
item = parts[1]
|
| 315 |
-
quantity = int(parts[2])
|
| 316 |
-
|
| 317 |
-
if item in MENU and MENU[item].get("enable", True):
|
| 318 |
-
price = MENU[item]["price"]
|
| 319 |
-
cost = MENU[item].get("cost", 0)
|
| 320 |
-
spec = MENU[item].get("spec", "")
|
| 321 |
-
|
| 322 |
-
order_note = f"來自 LINE 文字點餐"
|
| 323 |
-
if spec: order_note += f" ({spec})"
|
| 324 |
-
|
| 325 |
-
total = price * quantity
|
| 326 |
-
total_cost = cost * quantity
|
| 327 |
-
timestamp = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S")
|
| 328 |
-
order_id = str(uuid.uuid4())[:6].upper()
|
| 329 |
-
|
| 330 |
-
orders_db.append({
|
| 331 |
-
"訂單編號": order_id,
|
| 332 |
-
"時間": timestamp,
|
| 333 |
-
"預定交期": "盡快 (LINE)",
|
| 334 |
-
"取貨方式": "自取",
|
| 335 |
-
"送貨地點": "",
|
| 336 |
-
"顧客姓名": f"LINE用戶({user_id[-4:]})",
|
| 337 |
-
"商品": item,
|
| 338 |
-
"單價": price,
|
| 339 |
-
"成本": cost,
|
| 340 |
-
"數量": quantity,
|
| 341 |
-
"總價": total,
|
| 342 |
-
"總成本": total_cost,
|
| 343 |
-
"備註": order_note
|
| 344 |
-
})
|
| 345 |
-
|
| 346 |
-
save_orders()
|
| 347 |
-
|
| 348 |
-
reply_text = f"✅ 訂單成立!\n您訂購了 {item} x {quantity}。\n總金額為 {total} 元,請稍候為您準備!"
|
| 349 |
-
else:
|
| 350 |
-
active_items = [k for k, v in MENU.items() if v.get("enable", True)]
|
| 351 |
-
reply_text = f"❌ 找不到商品『{item}』,或該商品目前未提供!\n目前供應:{', '.join(active_items)}"
|
| 352 |
-
except Exception:
|
| 353 |
-
reply_text = "❌ 點餐格式錯誤。\n請確認格式為:『我要訂 招牌咖啡 1』"
|
| 354 |
-
|
| 355 |
-
else:
|
| 356 |
-
reply_text = f"歡迎光臨!☕\n\n���� 【網頁快速點餐】\n請點擊下方連結,系統將為您開啟點餐網頁:\n{WEB_ORDER_URL}\n\n💬 【文字點餐】\n您也可以直接輸入例如:『我要訂 拿鐵咖啡 2』 (注意中間要有空格喔!)"
|
| 357 |
-
|
| 358 |
-
try:
|
| 359 |
-
line_bot_api.reply_message(event.reply_token, TextSendMessage(text=reply_text))
|
| 360 |
-
except Exception as e:
|
| 361 |
-
print(f"回覆失敗: {e}")
|
| 362 |
-
|
| 363 |
-
# ----------------------------
|
| 364 |
-
# 💻 網頁後台邏輯
|
| 365 |
-
# ----------------------------
|
| 366 |
-
|
| 367 |
-
def get_customer_choices():
|
| 368 |
-
customers = []
|
| 369 |
-
for o in orders_db:
|
| 370 |
-
if o.get("顧客姓名") and o["顧客姓名"] not in customers:
|
| 371 |
-
customers.append(o["顧客姓名"])
|
| 372 |
-
return ["所有顧客"] + customers
|
| 373 |
-
|
| 374 |
-
def get_time_choices():
|
| 375 |
-
times = set()
|
| 376 |
-
for o in orders_db:
|
| 377 |
-
dt_str = o.get("時間", "") or o.get("訂單時間", "")
|
| 378 |
-
if len(dt_str) >= 10:
|
| 379 |
-
times.add(dt_str[:10])
|
| 380 |
-
times.add(dt_str[:7])
|
| 381 |
-
return ["所有時間"] + sorted(list(times), reverse=True)
|
| 382 |
-
|
| 383 |
-
def get_item_choices():
|
| 384 |
-
items = []
|
| 385 |
-
for o in orders_db:
|
| 386 |
-
if o.get("商品") and o["商品"] not in items:
|
| 387 |
-
items.append(o["商品"])
|
| 388 |
-
return ["所有商品"] + items
|
| 389 |
-
|
| 390 |
-
def get_delivery_choices():
|
| 391 |
-
deliveries = []
|
| 392 |
-
for o in orders_db:
|
| 393 |
-
d = o.get("預定交期", "")
|
| 394 |
-
if d and d not in deliveries:
|
| 395 |
-
deliveries.append(d)
|
| 396 |
-
return ["所有交期"] + deliveries
|
| 397 |
-
|
| 398 |
-
def get_orders_data(filter_name="所有顧客", filter_time="所有時間", filter_item="所有商品", filter_delivery="所有交期"):
|
| 399 |
-
filtered_db = orders_db
|
| 400 |
-
if filter_name != "所有顧客":
|
| 401 |
-
filtered_db = [o for o in filtered_db if o.get("顧客姓名") == filter_name]
|
| 402 |
-
if filter_time != "所有時間":
|
| 403 |
-
filtered_db = [o for o in filtered_db if o.get("時間", "").startswith(filter_time) or o.get("訂單時間", "").startswith(filter_time)]
|
| 404 |
-
if filter_item != "所有商品":
|
| 405 |
-
filtered_db = [o for o in filtered_db if o.get("商品") == filter_item]
|
| 406 |
-
if filter_delivery != "所有交期":
|
| 407 |
-
filtered_db = [o for o in filtered_db if o.get("預定交期") == filter_delivery]
|
| 408 |
-
|
| 409 |
-
if not filtered_db:
|
| 410 |
-
return [[""] * 13]
|
| 411 |
-
|
| 412 |
-
return [[
|
| 413 |
-
o.get("訂單編號", ""),
|
| 414 |
-
o.get("時間", "") or o.get("訂單時間", ""),
|
| 415 |
-
o.get("預定交期", ""),
|
| 416 |
-
o.get("取貨方式", "自取"),
|
| 417 |
-
o.get("送貨地點", ""),
|
| 418 |
-
o.get("顧客姓名", ""),
|
| 419 |
-
o.get("商品", ""),
|
| 420 |
-
o.get("單價", 0),
|
| 421 |
-
o.get("成本", 0),
|
| 422 |
-
o.get("數量", 0),
|
| 423 |
-
o.get("總價", 0),
|
| 424 |
-
o.get("總成本", 0),
|
| 425 |
-
o.get("備註", "")
|
| 426 |
-
] for o in filtered_db]
|
| 427 |
-
|
| 428 |
-
def get_revenue(filter_name="所有顧客", filter_time="所有時間", filter_item="所有商品", filter_delivery="所有交期"):
|
| 429 |
-
filtered_db = orders_db
|
| 430 |
-
if filter_name != "所有顧客":
|
| 431 |
-
filtered_db = [o for o in filtered_db if o.get("顧客姓名") == filter_name]
|
| 432 |
-
if filter_time != "所有時間":
|
| 433 |
-
filtered_db = [o for o in filtered_db if o.get("時間", "").startswith(filter_time) or o.get("訂單時間", "").startswith(filter_time)]
|
| 434 |
-
if filter_item != "所有商品":
|
| 435 |
-
filtered_db = [o for o in filtered_db if o.get("商品") == filter_item]
|
| 436 |
-
if filter_delivery != "所有交期":
|
| 437 |
-
filtered_db = [o for o in filtered_db if o.get("預定交期") == filter_delivery]
|
| 438 |
-
|
| 439 |
-
total_revenue = sum(order.get("總價", 0) for order in filtered_db)
|
| 440 |
-
total_cost = sum(order.get("總成本", 0) for order in filtered_db)
|
| 441 |
-
profit = total_revenue - total_cost
|
| 442 |
-
|
| 443 |
-
title_parts = []
|
| 444 |
-
if filter_name != "所有顧客": title_parts.append(f"【{filter_name}】")
|
| 445 |
-
if filter_time != "所有時間": title_parts.append(f"【{filter_time}】")
|
| 446 |
-
if filter_item != "所有商品": title_parts.append(f"【{filter_item}】")
|
| 447 |
-
if filter_delivery != "所有交期": title_parts.append(f"【{filter_delivery}】")
|
| 448 |
-
|
| 449 |
-
prefix = "💰 " + "".join(title_parts) + " 的總消費" if title_parts else "💰 目前總營收"
|
| 450 |
-
profit_prefix = "📈 篩選總毛利" if title_parts else "📈 目前總毛利"
|
| 451 |
-
|
| 452 |
-
return f"### {prefix}:NT$ {total_revenue} | {profit_prefix}:NT$ {profit}"
|
| 453 |
-
|
| 454 |
-
def refresh_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter):
|
| 455 |
-
c_choices = get_customer_choices()
|
| 456 |
-
if current_filter not in c_choices: current_filter = "所有顧客"
|
| 457 |
-
|
| 458 |
-
t_choices = get_time_choices()
|
| 459 |
-
if current_time_filter not in t_choices: current_time_filter = "所有時間"
|
| 460 |
-
|
| 461 |
-
i_choices = get_item_choices()
|
| 462 |
-
if current_item_filter not in i_choices: current_item_filter = "所有商品"
|
| 463 |
-
|
| 464 |
-
d_choices = get_delivery_choices()
|
| 465 |
-
if current_delivery_filter not in d_choices: current_delivery_filter = "所有交期"
|
| 466 |
-
|
| 467 |
-
return (
|
| 468 |
-
gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 469 |
-
gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 470 |
-
gr.update(choices=c_choices, value=current_filter),
|
| 471 |
-
gr.update(choices=t_choices, value=current_time_filter),
|
| 472 |
-
gr.update(choices=i_choices, value=current_item_filter),
|
| 473 |
-
gr.update(choices=d_choices, value=current_delivery_filter)
|
| 474 |
-
)
|
| 475 |
-
|
| 476 |
-
def restore_from_backup(current_filter, current_time_filter, current_item_filter, current_delivery_filter):
|
| 477 |
-
global orders_db, MENU
|
| 478 |
-
msg = ""
|
| 479 |
-
|
| 480 |
-
# 1. 還原訂單
|
| 481 |
-
if os.path.exists(BACKUP_FILE):
|
| 482 |
-
if os.path.getsize(BACKUP_FILE) == 0:
|
| 483 |
-
msg = "⚠️ 警告:雲端上的 orders_backup.csv 是一個空白檔案 (0 byte),沒有歷史資料可以還原!"
|
| 484 |
-
else:
|
| 485 |
-
try:
|
| 486 |
-
df = pd.read_csv(BACKUP_FILE)
|
| 487 |
-
df = df.fillna("")
|
| 488 |
-
loaded_data = df.to_dict('records')
|
| 489 |
-
|
| 490 |
-
for o in loaded_data:
|
| 491 |
-
o["單價"] = int(float(o.get("單價", 0) or 0))
|
| 492 |
-
o["成本"] = int(float(o.get("成本", 0) or 0))
|
| 493 |
-
o["數量"] = int(float(o.get("數量", 0) or 0))
|
| 494 |
-
o["總價"] = int(float(o.get("總價", 0) or 0))
|
| 495 |
-
o["總成本"] = int(float(o.get("總成本", 0) or 0))
|
| 496 |
-
if "時間" in o and "訂單時間" not in o:
|
| 497 |
-
o["時間"] = o["時間"]
|
| 498 |
-
|
| 499 |
-
orders_db = loaded_data
|
| 500 |
-
save_orders()
|
| 501 |
-
msg = f"✅ 成功從備份檔強制還原了 {len(orders_db)} 筆訂單!"
|
| 502 |
-
except pd.errors.EmptyDataError:
|
| 503 |
-
msg = "⚠️ 警告:雲端上的 orders_backup.csv 內容為空,無法解析資料!"
|
| 504 |
-
except Exception as e:
|
| 505 |
-
msg = f"❌ 還原訂單失敗,發生錯誤:{e}"
|
| 506 |
-
else:
|
| 507 |
-
msg = "⚠️ 找不到 orders_backup.csv 備份檔!請確認 Hugging Face 的 Files 頁籤中是否有此檔案。"
|
| 508 |
-
|
| 509 |
-
# 2. 還原菜單
|
| 510 |
-
new_trigger = datetime.now(TAIPEI_TZ).timestamp()
|
| 511 |
-
if os.path.exists(MENU_BACKUP_FILE) and os.path.getsize(MENU_BACKUP_FILE) > 0:
|
| 512 |
-
try:
|
| 513 |
-
m_df = pd.read_csv(MENU_BACKUP_FILE)
|
| 514 |
-
new_menu = {}
|
| 515 |
-
for _, row in m_df.iterrows():
|
| 516 |
-
seq = int(row.get("流水號", 999))
|
| 517 |
-
val_enable = row.get("啟用", True)
|
| 518 |
-
enable = val_enable.lower() in ["true", "1", "yes", "是", "t"] if isinstance(val_enable, str) else bool(val_enable)
|
| 519 |
-
cat = str(row.get("分類", "未分類")).strip()
|
| 520 |
-
if not cat: cat = "未分類"
|
| 521 |
-
item = str(row.get("品項", "")).strip()
|
| 522 |
-
spec = str(row.get("規格", "")).strip() if pd.notna(row.get("規格", "")) else ""
|
| 523 |
-
price = int(float(row.get("價格", 0) or 0))
|
| 524 |
-
cost = int(float(row.get("成本", 0) or 0))
|
| 525 |
-
note = str(row.get("備註", "")).strip() if pd.notna(row.get("備註", "")) else ""
|
| 526 |
-
|
| 527 |
-
if item and price > 0:
|
| 528 |
-
new_menu[item] = {"price": price, "cost": cost, "enable": enable, "seq": seq, "category": cat, "spec": spec, "note": note}
|
| 529 |
-
if new_menu:
|
| 530 |
-
MENU.clear()
|
| 531 |
-
MENU.update(new_menu)
|
| 532 |
-
save_menu_to_file()
|
| 533 |
-
msg += "\n✅ 菜單已成功從備份同步還原!"
|
| 534 |
-
except Exception as e:
|
| 535 |
-
msg += f"\n❌ 菜單還原失敗:{e}"
|
| 536 |
-
|
| 537 |
-
c_choices = get_customer_choices()
|
| 538 |
-
t_choices = get_time_choices()
|
| 539 |
-
i_choices = get_item_choices()
|
| 540 |
-
d_choices = get_delivery_choices()
|
| 541 |
-
|
| 542 |
-
if current_filter not in c_choices: current_filter = "所有顧客"
|
| 543 |
-
if current_time_filter not in t_choices: current_time_filter = "所有時間"
|
| 544 |
-
if current_item_filter not in i_choices: current_item_filter = "所有商品"
|
| 545 |
-
if current_delivery_filter not in d_choices: current_delivery_filter = "所有交期"
|
| 546 |
-
|
| 547 |
-
return (
|
| 548 |
-
gr.update(value=msg),
|
| 549 |
-
gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 550 |
-
gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 551 |
-
gr.update(choices=c_choices, value=current_filter),
|
| 552 |
-
gr.update(choices=t_choices, value=current_time_filter),
|
| 553 |
-
gr.update(choices=i_choices, value=current_item_filter),
|
| 554 |
-
gr.update(choices=d_choices, value=current_delivery_filter),
|
| 555 |
-
get_menu_df(),
|
| 556 |
-
new_trigger
|
| 557 |
-
)
|
| 558 |
-
|
| 559 |
-
def add_order(c_name, p_method, d_location, d_month, d_day, d_time, nts, *qty_args):
|
| 560 |
-
try:
|
| 561 |
-
c_name = str(c_name).strip() if c_name else ""
|
| 562 |
-
nts = str(nts).strip() if nts else ""
|
| 563 |
-
|
| 564 |
-
delivery_date = f"{d_month}{d_day} {d_time}" if d_time != "盡快" else "盡快"
|
| 565 |
-
|
| 566 |
-
quantities = []
|
| 567 |
-
for q in qty_args:
|
| 568 |
-
try:
|
| 569 |
-
quantities.append(int(q))
|
| 570 |
-
except:
|
| 571 |
-
quantities.append(0)
|
| 572 |
-
|
| 573 |
-
# 取得與前台絕對一致的平面化選單順序
|
| 574 |
-
_, _, flat_list = get_frontend_menu_items()
|
| 575 |
-
|
| 576 |
-
reset_qtys = [gr.update(value="0") for _ in range(len(flat_list))]
|
| 577 |
-
|
| 578 |
-
if not c_name:
|
| 579 |
-
return [gr.update(value="❌ 錯誤:請輸入顧客姓名")] + reset_qtys
|
| 580 |
-
|
| 581 |
-
timestamp = datetime.now(TAIPEI_TZ).strftime("%Y-%m-%d %H:%M:%S")
|
| 582 |
-
total_order_price = 0
|
| 583 |
-
items_desc = []
|
| 584 |
-
has_ordered_items = False
|
| 585 |
-
|
| 586 |
-
for i, qty in enumerate(quantities):
|
| 587 |
-
if qty > 0:
|
| 588 |
-
has_ordered_items = True
|
| 589 |
-
item, details = flat_list[i]
|
| 590 |
-
price = details["price"]
|
| 591 |
-
cost = details.get("cost", 0)
|
| 592 |
-
spec = details.get("spec", "")
|
| 593 |
-
|
| 594 |
-
item_note = f"({spec})" if spec else ""
|
| 595 |
-
|
| 596 |
-
total_price = price * qty
|
| 597 |
-
total_cost = cost * qty
|
| 598 |
-
total_order_price += total_price
|
| 599 |
-
|
| 600 |
-
order_id = str(uuid.uuid4())[:6].upper()
|
| 601 |
-
|
| 602 |
-
final_note = nts
|
| 603 |
-
if item_note:
|
| 604 |
-
final_note = f"{item_note} {nts}".strip()
|
| 605 |
-
|
| 606 |
-
orders_db.append({
|
| 607 |
-
"訂單編號": order_id,
|
| 608 |
-
"時間": timestamp,
|
| 609 |
-
"預定交期": delivery_date,
|
| 610 |
-
"取貨方式": p_method,
|
| 611 |
-
"送貨地點": d_location if p_method == "送貨" else "",
|
| 612 |
-
"顧客姓名": c_name,
|
| 613 |
-
"商品": item,
|
| 614 |
-
"單價": price,
|
| 615 |
-
"成本": cost,
|
| 616 |
-
"數量": qty,
|
| 617 |
-
"總價": total_price,
|
| 618 |
-
"總成本": total_cost,
|
| 619 |
-
"備註": final_note
|
| 620 |
-
})
|
| 621 |
-
|
| 622 |
-
desc = f"{item}{item_note}x{qty}"
|
| 623 |
-
items_desc.append(desc)
|
| 624 |
-
|
| 625 |
-
if not has_ordered_items:
|
| 626 |
-
return [gr.update(value="❌ 錯誤:請至少選擇一項商品的數量")] + reset_qtys
|
| 627 |
-
|
| 628 |
-
save_orders()
|
| 629 |
-
|
| 630 |
-
msg = f"✅ 成功新增訂單:{c_name} 訂購了 {', '.join(items_desc)},總計 {total_order_price} 元。取貨方式:{p_method}"
|
| 631 |
-
|
| 632 |
-
return [gr.update(value=msg)] + reset_qtys
|
| 633 |
-
|
| 634 |
-
except Exception as e:
|
| 635 |
-
err_msg = f"❌ 系統異常:{str(e)}"
|
| 636 |
-
_, _, flat_list = get_frontend_menu_items()
|
| 637 |
-
return [gr.update(value=err_msg)] + [gr.update(value="0") for _ in range(len(flat_list))]
|
| 638 |
-
|
| 639 |
-
def delete_single_order(order_id, current_filter, current_time_filter, current_item_filter, current_delivery_filter):
|
| 640 |
-
if order_id == "__CANCEL__":
|
| 641 |
-
return gr.update(), gr.update(), gr.update(), gr.update()
|
| 642 |
-
|
| 643 |
-
global orders_db
|
| 644 |
-
order_id = str(order_id).strip()
|
| 645 |
-
if not order_id:
|
| 646 |
-
return gr.update(value="❌ 錯誤:請輸入要刪除的訂單編號!"), gr.update(), gr.update(), gr.update()
|
| 647 |
-
|
| 648 |
-
original_len = len(orders_db)
|
| 649 |
-
orders_db = [o for o in orders_db if o.get("訂單編號") != order_id]
|
| 650 |
-
|
| 651 |
-
if len(orders_db) == original_len:
|
| 652 |
-
return gr.update(value=f"❌ 找不到訂單編號:{order_id}"), gr.update(), gr.update(), gr.update()
|
| 653 |
-
|
| 654 |
-
save_orders()
|
| 655 |
-
|
| 656 |
-
return (
|
| 657 |
-
gr.update(value=f"✅ 成功刪除訂單:{order_id}"),
|
| 658 |
-
gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 659 |
-
gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 660 |
-
gr.update(value="")
|
| 661 |
-
)
|
| 662 |
-
|
| 663 |
-
def clear_orders(filter_val):
|
| 664 |
-
if filter_val == "__CANCEL__":
|
| 665 |
-
return gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 666 |
-
|
| 667 |
-
orders_db.clear()
|
| 668 |
-
save_orders()
|
| 669 |
-
|
| 670 |
-
return (
|
| 671 |
-
gr.update(value="🗑️ 所有訂單已清空"),
|
| 672 |
-
gr.update(value=get_orders_data("所有顧客", "所有時間", "所有商品", "所有交期")),
|
| 673 |
-
gr.update(value=get_revenue("所有顧客", "所有時間", "所有商品", "所有交期")),
|
| 674 |
-
gr.update(choices=["所有顧客"], value="所有顧客"),
|
| 675 |
-
gr.update(choices=["所有時間"], value="所有時間"),
|
| 676 |
-
gr.update(choices=["所有商品"], value="所有商品"),
|
| 677 |
-
gr.update(choices=["所有交期"], value="所有交期")
|
| 678 |
-
)
|
| 679 |
-
|
| 680 |
-
def verify_password(pwd, current_filter, current_time_filter, current_item_filter, current_delivery_filter):
|
| 681 |
-
if pwd == ADMIN_PASSWORD:
|
| 682 |
-
c_choices = get_customer_choices()
|
| 683 |
-
if current_filter not in c_choices: current_filter = "所有顧客"
|
| 684 |
-
t_choices = get_time_choices()
|
| 685 |
-
if current_time_filter not in t_choices: current_time_filter = "所有時間"
|
| 686 |
-
i_choices = get_item_choices()
|
| 687 |
-
if current_item_filter not in i_choices: current_item_filter = "所有商品"
|
| 688 |
-
d_choices = get_delivery_choices()
|
| 689 |
-
if current_delivery_filter not in d_choices: current_delivery_filter = "所有交期"
|
| 690 |
-
|
| 691 |
-
return (
|
| 692 |
-
gr.update(visible=False),
|
| 693 |
-
gr.update(visible=True),
|
| 694 |
-
gr.update(value=""),
|
| 695 |
-
gr.update(choices=c_choices, value=current_filter),
|
| 696 |
-
gr.update(choices=t_choices, value=current_time_filter),
|
| 697 |
-
gr.update(choices=i_choices, value=current_item_filter),
|
| 698 |
-
gr.update(choices=d_choices, value=current_delivery_filter),
|
| 699 |
-
gr.update(value=get_orders_data(current_filter, current_time_filter, current_item_filter, current_delivery_filter)),
|
| 700 |
-
gr.update(value=get_revenue(current_filter, current_time_filter, current_item_filter, current_delivery_filter))
|
| 701 |
-
)
|
| 702 |
-
return gr.update(visible=True), gr.update(visible=False), gr.update(value="❌ **密碼錯誤。**"), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update()
|
| 703 |
-
|
| 704 |
-
def logout():
|
| 705 |
-
return gr.update(visible=True), gr.update(visible=False), gr.update(value=""), gr.update(value="")
|
| 706 |
-
|
| 707 |
-
def run_git_cmd(command):
|
| 708 |
-
result = subprocess.run(command, shell=True, text=True, capture_output=True)
|
| 709 |
-
if result.returncode == 0:
|
| 710 |
-
return True, f"✅ 成功: {command}\n> {result.stdout.strip()}"
|
| 711 |
-
return False, f"❌ 失敗: {command}\n> {result.stderr.strip()}"
|
| 712 |
-
|
| 713 |
-
def backup_and_push_to_github():
|
| 714 |
-
log_messages = ["🚀 開始備份...\n" + "-"*40]
|
| 715 |
-
|
| 716 |
-
if not orders_db:
|
| 717 |
-
df = pd.DataFrame(columns=["訂單編號", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"])
|
| 718 |
-
else:
|
| 719 |
-
export_data = []
|
| 720 |
-
for o in orders_db:
|
| 721 |
-
export_data.append({
|
| 722 |
-
"訂單編號": o.get("訂單編號", ""),
|
| 723 |
-
"訂單時間": o.get("時間", "") or o.get("訂單時間", ""),
|
| 724 |
-
"預定交期": o.get("預定交期", ""),
|
| 725 |
-
"取貨方式": o.get("取貨方式", "自取"),
|
| 726 |
-
"送貨地點": o.get("送貨地點", ""),
|
| 727 |
-
"顧客姓名": o.get("顧客姓名", ""),
|
| 728 |
-
"商品": o.get("商品", ""),
|
| 729 |
-
"單價": o.get("單價", 0),
|
| 730 |
-
"成本": o.get("成本", 0),
|
| 731 |
-
"數量": o.get("數量", 0),
|
| 732 |
-
"總價": o.get("總價", 0),
|
| 733 |
-
"總成本": o.get("總成本", 0),
|
| 734 |
-
"備註": o.get("備註", "")
|
| 735 |
-
})
|
| 736 |
-
df = pd.DataFrame(export_data)
|
| 737 |
-
|
| 738 |
-
backup_filename = os.path.join(BASE_DIR, "orders_backup.csv")
|
| 739 |
-
df.to_csv(backup_filename, index=False, encoding="utf-8-sig")
|
| 740 |
-
log_messages.append(f"💾 已儲存訂單至: {backup_filename}")
|
| 741 |
-
|
| 742 |
-
menu_df = get_menu_df()
|
| 743 |
-
menu_df.to_csv(MENU_BACKUP_FILE, index=False, encoding="utf-8-sig")
|
| 744 |
-
log_messages.append(f"💾 已儲存菜單備份至: {MENU_BACKUP_FILE}")
|
| 745 |
-
|
| 746 |
-
log_messages.append(f"💾 已儲存最新菜單至: {MENU_FILE}")
|
| 747 |
-
log_messages.append(f"💾 已儲存密碼設定至: {PWD_FILE}")
|
| 748 |
-
log_messages.append(f"💾 已儲存訂單資料庫至: {ORDERS_FILE}")
|
| 749 |
-
|
| 750 |
-
run_git_cmd('git config user.email "bot@example.com"')
|
| 751 |
-
run_git_cmd('git config user.name "AutoBackupBot"')
|
| 752 |
-
|
| 753 |
-
success, msg = run_git_cmd("git add .")
|
| 754 |
-
log_messages.append(msg)
|
| 755 |
-
|
| 756 |
-
commit_msg = f"自動備份: {datetime.now(TAIPEI_TZ).strftime('%Y-%m-%d %H:%M:%S')}"
|
| 757 |
-
success, msg = run_git_cmd(f'git commit -m "{commit_msg}"')
|
| 758 |
-
log_messages.append(msg)
|
| 759 |
-
|
| 760 |
-
if not success and ("nothing to commit" in msg or "無檔案要提交" in msg):
|
| 761 |
-
log_messages.append("ℹ️ 無變更。\n✅ 結束。")
|
| 762 |
-
return gr.update(value="\n\n".join(log_messages))
|
| 763 |
-
|
| 764 |
-
hf_token = os.environ.get("HF_TOKEN")
|
| 765 |
-
if hf_token:
|
| 766 |
-
repo_url = f"https://oauth2:{hf_token}@huggingface.co/spaces/schillercfk/ssys"
|
| 767 |
-
run_git_cmd(f"git remote set-url origin {repo_url}")
|
| 768 |
-
else:
|
| 769 |
-
log_messages.append("⚠️ 警告:未偵測到 HF_TOKEN!若上傳失敗請至 Settings 設定。")
|
| 770 |
-
|
| 771 |
-
success, msg = run_git_cmd("git push origin main")
|
| 772 |
-
log_messages.append(msg)
|
| 773 |
-
if success:
|
| 774 |
-
log_messages.append("🎉 雲端備份完成!")
|
| 775 |
-
else:
|
| 776 |
-
log_messages.append("❌ 上傳失敗:請檢查 Hugging Face 專案 Settings -> Variables and secrets 是否有設定具備 Write 權限的 HF_TOKEN。")
|
| 777 |
-
|
| 778 |
-
return gr.update(value="\n\n".join(log_messages))
|
| 779 |
-
|
| 780 |
-
def autofill_delete_target(evt: gr.SelectData, df_data):
|
| 781 |
-
try:
|
| 782 |
-
row_idx = evt.index[0]
|
| 783 |
-
order_id = df_data.iloc[row_idx, 0]
|
| 784 |
-
return str(order_id)
|
| 785 |
-
except:
|
| 786 |
-
return ""
|
| 787 |
-
|
| 788 |
-
# ----------------------------
|
| 789 |
-
# 🖥️ 網頁介面 (UI)
|
| 790 |
-
# ----------------------------
|
| 791 |
-
custom_css = """
|
| 792 |
-
.menu-row { border-bottom: 1px solid #e5e7eb; padding: 12px 0; align-items: center; flex-wrap: nowrap !important; gap: 8px !important; }
|
| 793 |
-
.action-btn {
|
| 794 |
-
font-size: 18px !important;
|
| 795 |
-
font-weight: bold !important;
|
| 796 |
-
border-radius: 8px !important;
|
| 797 |
-
padding: 0 !important;
|
| 798 |
-
width: 36px !important;
|
| 799 |
-
height: 36px !important;
|
| 800 |
-
min-width: 36px !important;
|
| 801 |
-
display: flex !important;
|
| 802 |
-
justify-content: center !important;
|
| 803 |
-
align-items: center !important;
|
| 804 |
-
flex-shrink: 0 !important;
|
| 805 |
-
cursor: pointer !important;
|
| 806 |
-
}
|
| 807 |
-
.qty-input {
|
| 808 |
-
min-width: 45px !important;
|
| 809 |
-
width: 45px !important;
|
| 810 |
-
flex-shrink: 0 !important;
|
| 811 |
-
border: none !important;
|
| 812 |
-
box-shadow: none !important;
|
| 813 |
-
background: transparent !important;
|
| 814 |
-
}
|
| 815 |
-
.qty-input input {
|
| 816 |
-
text-align: center !important;
|
| 817 |
-
font-size: 18px !important;
|
| 818 |
-
font-weight: bold !important;
|
| 819 |
-
pointer-events: none !important;
|
| 820 |
-
touch-action: none !important;
|
| 821 |
-
padding: 0 !important;
|
| 822 |
-
height: 36px !important;
|
| 823 |
-
background: transparent !important;
|
| 824 |
-
}
|
| 825 |
-
.github-log textarea { font-family: monospace; background-color: #1e1e1e; color: #00ff00; }
|
| 826 |
-
"""
|
| 827 |
-
|
| 828 |
-
head_js = """
|
| 829 |
-
<script>
|
| 830 |
-
if (window.location.search.includes("openExternalBrowser")) {
|
| 831 |
-
const newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname;
|
| 832 |
-
window.history.replaceState({path: newUrl}, "", newUrl);
|
| 833 |
-
}
|
| 834 |
-
</script>
|
| 835 |
-
"""
|
| 836 |
-
|
| 837 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="簡易訂單管理系統", css=custom_css, head=head_js) as demo_ui:
|
| 838 |
-
menu_trigger = gr.State(value=0)
|
| 839 |
-
|
| 840 |
-
gr.Markdown("<h1 style='text-align: center;'>🛒 簡易訂單管理系統 (LINE 整合版)</h1>")
|
| 841 |
-
|
| 842 |
-
with gr.Tabs():
|
| 843 |
-
with gr.TabItem("📝 現場/網頁新增訂單"):
|
| 844 |
-
@gr.render(inputs=[menu_trigger])
|
| 845 |
-
def render_order_form(trigger):
|
| 846 |
-
with gr.Row():
|
| 847 |
-
with gr.Column():
|
| 848 |
-
customer_name = gr.Textbox(label="顧客姓名", placeholder="請輸入姓名")
|
| 849 |
-
|
| 850 |
-
# --- 新增:取貨方式與地點選擇 ---
|
| 851 |
-
gr.Markdown("#### 📦 取貨方式與地點")
|
| 852 |
-
with gr.Row():
|
| 853 |
-
pickup_method = gr.Radio(choices=["自取", "送貨"], value="自取", label="取貨方式", interactive=True)
|
| 854 |
-
delivery_location = gr.Dropdown(
|
| 855 |
-
choices=["1樓大廳", "2樓辦公室", "警衛室", "A區", "B區"],
|
| 856 |
-
label="送貨地點",
|
| 857 |
-
visible=False,
|
| 858 |
-
allow_custom_value=True,
|
| 859 |
-
interactive=True,
|
| 860 |
-
info="請選擇或直接打字輸入地點" # 【修正點】:將不支援的 placeholder 替換為 info
|
| 861 |
-
)
|
| 862 |
-
|
| 863 |
-
# 綁定事件:當選擇送貨時才顯示地點欄位
|
| 864 |
-
def update_loc_vis(method):
|
| 865 |
-
return gr.update(visible=(method == "送貨"))
|
| 866 |
-
pickup_method.change(fn=update_loc_vis, inputs=[pickup_method], outputs=[delivery_location])
|
| 867 |
-
# --------------------------------
|
| 868 |
-
|
| 869 |
-
gr.Markdown("#### 🕒 預定交期")
|
| 870 |
-
with gr.Row():
|
| 871 |
-
current_month = datetime.now(TAIPEI_TZ).strftime("%m月")
|
| 872 |
-
current_day = datetime.now(TAIPEI_TZ).strftime("%d日")
|
| 873 |
-
|
| 874 |
-
delivery_month = gr.Dropdown(choices=[f"{i:02d}月" for i in range(1, 13)], label="月", value=current_month, interactive=True)
|
| 875 |
-
delivery_day = gr.Dropdown(choices=[f"{i:02d}日" for i in range(1, 32)], label="日", value=current_day, interactive=True)
|
| 876 |
-
|
| 877 |
-
time_choices = ["盡快"] + [f"{h:02d}:{m:02d}" for h in range(0, 24) for m in (0, 15, 30, 45)]
|
| 878 |
-
delivery_time = gr.Dropdown(choices=time_choices, label="時間", value="盡快", interactive=True)
|
| 879 |
-
|
| 880 |
-
gr.Markdown("#### 🛍️ 選擇商品與數量")
|
| 881 |
-
|
| 882 |
-
quantity_components = []
|
| 883 |
-
|
| 884 |
-
pic_dir = os.path.join(BASE_DIR, "pic")
|
| 885 |
-
if not os.path.exists(pic_dir):
|
| 886 |
-
os.makedirs(pic_dir, exist_ok=True)
|
| 887 |
-
|
| 888 |
-
category_order, items_by_cat, flat_list = get_frontend_menu_items()
|
| 889 |
-
|
| 890 |
-
if not category_order:
|
| 891 |
-
gr.Markdown("目前尚無提供商品,請至後台設定菜單。")
|
| 892 |
-
|
| 893 |
-
with gr.Tabs():
|
| 894 |
-
for cat in category_order:
|
| 895 |
-
with gr.TabItem(cat):
|
| 896 |
-
for item, details in items_by_cat[cat]:
|
| 897 |
-
price = details["price"]
|
| 898 |
-
spec = details.get("spec", "")
|
| 899 |
-
|
| 900 |
-
with gr.Row(elem_classes="menu-row"):
|
| 901 |
-
with gr.Column(scale=0, min_width=60):
|
| 902 |
-
found_img_path = None
|
| 903 |
-
for ext in ['.jpg', '.jpeg', '.png', '.JPG', '.PNG']:
|
| 904 |
-
temp_path = os.path.join(pic_dir, f"{item}{ext}")
|
| 905 |
-
if os.path.exists(temp_path):
|
| 906 |
-
found_img_path = temp_path
|
| 907 |
-
break
|
| 908 |
-
|
| 909 |
-
if found_img_path:
|
| 910 |
-
try:
|
| 911 |
-
with open(found_img_path, "rb") as img_file:
|
| 912 |
-
encoded_string = base64.b64encode(img_file.read()).decode('utf-8')
|
| 913 |
-
mime_type = "image/png" if found_img_path.lower().endswith(".png") else "image/jpeg"
|
| 914 |
-
|
| 915 |
-
img_html = f"""
|
| 916 |
-
<div style="width: 60px; height: 60px; border-radius: 8px; overflow: margin: 0 auto; pointer-events: none; background: white;">
|
| 917 |
-
<img src="data:{mime_type};base64,{encoded_string}" style="width: 100%; height: 100%; object-fit: cover; pointer-events: none;">
|
| 918 |
-
</div>
|
| 919 |
-
"""
|
| 920 |
-
gr.HTML(value=img_html)
|
| 921 |
-
except Exception as e:
|
| 922 |
-
first_char = item[0] if item else "品"
|
| 923 |
-
placeholder_html = f"""
|
| 924 |
-
<div style="width: 60px; height: 60px; background-color: #e2e8f0; color: #475569; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 24px; font-weight: bold; margin: 0 auto; pointer-events: none;">
|
| 925 |
-
{first_char}
|
| 926 |
-
</div>
|
| 927 |
-
"""
|
| 928 |
-
gr.HTML(value=placeholder_html)
|
| 929 |
-
else:
|
| 930 |
-
first_char = item[0] if item else "品"
|
| 931 |
-
placeholder_html = f"""
|
| 932 |
-
<div style="width: 60px; height: 60px; background-color: #e2e8f0; color: #475569; display: flex; align-items: center; justify-content: center; border-radius: 8px; font-size: 24px; font-weight: bold; margin: 0 auto; pointer-events: none;">
|
| 933 |
-
{first_char}
|
| 934 |
-
</div>
|
| 935 |
-
"""
|
| 936 |
-
gr.HTML(value=placeholder_html)
|
| 937 |
-
|
| 938 |
-
with gr.Column(scale=1, min_width=60):
|
| 939 |
-
spec_html = f"<span style='font-size: 0.85em; color: #ef4444; margin-left: 6px; padding: 2px 6px; background: #fee2e2; border-radius: 4px;'>{spec}</span>" if spec else ""
|
| 940 |
-
gr.Markdown(f"<div style='line-height: 1.2;'><strong>{item}</strong>{spec_html}<br><span style='color: gray; font-size: 0.9em;'>NT$ {price}</span></div>")
|
| 941 |
-
|
| 942 |
-
with gr.Column(scale=0, min_width=36):
|
| 943 |
-
minus_btn = gr.Button("➖", elem_classes="action-btn", variant="secondary")
|
| 944 |
-
with gr.Column(scale=0, min_width=45):
|
| 945 |
-
qty_box = gr.Textbox(value="0", show_label=False, interactive=True, elem_classes="qty-input", container=False)
|
| 946 |
-
with gr.Column(scale=0, min_width=36):
|
| 947 |
-
plus_btn = gr.Button("➕", elem_classes="action-btn", variant="secondary")
|
| 948 |
-
|
| 949 |
-
minus_btn.click(
|
| 950 |
-
fn=None, inputs=[qty_box], outputs=[qty_box],
|
| 951 |
-
js="(v) => { let n = parseInt(v || 0); return Math.max(0, n - 1).toString(); }"
|
| 952 |
-
)
|
| 953 |
-
plus_btn.click(
|
| 954 |
-
fn=None, inputs=[qty_box], outputs=[qty_box],
|
| 955 |
-
js="(v) => { let n = parseInt(v || 0); return (n + 1).toString(); }"
|
| 956 |
-
)
|
| 957 |
-
|
| 958 |
-
quantity_components.append(qty_box)
|
| 959 |
-
|
| 960 |
-
notes = gr.Textbox(label="備註", placeholder="例如:少冰微糖...")
|
| 961 |
-
submit_btn = gr.Button("🚀 送出訂單", variant="primary", size="lg")
|
| 962 |
-
status_msg = gr.Textbox(label="系統狀態", interactive=False)
|
| 963 |
-
|
| 964 |
-
# 將新增的參數加入 inputs_list 中
|
| 965 |
-
inputs_list = [customer_name, pickup_method, delivery_location, delivery_month, delivery_day, delivery_time, notes] + quantity_components
|
| 966 |
-
outputs_list = [status_msg] + quantity_components
|
| 967 |
-
|
| 968 |
-
submit_btn.click(fn=add_order, inputs=inputs_list, outputs=outputs_list)
|
| 969 |
-
|
| 970 |
-
with gr.TabItem("📊 系統管理與總覽"):
|
| 971 |
-
with gr.Column(visible=True) as login_pane:
|
| 972 |
-
gr.Markdown("### 🔒 系統管理員登入")
|
| 973 |
-
admin_pwd = gr.Textbox(label="請輸入密碼", type="password")
|
| 974 |
-
login_btn = gr.Button("登入", variant="primary")
|
| 975 |
-
login_status = gr.Markdown()
|
| 976 |
-
|
| 977 |
-
with gr.Column(visible=False) as overview_pane:
|
| 978 |
-
with gr.Row(elem_classes="menu-row"):
|
| 979 |
-
gr.Markdown("## ⚙️ 系統管理中心")
|
| 980 |
-
logout_btn = gr.Button("🚪 登出", size="sm", min_width=100)
|
| 981 |
-
|
| 982 |
-
with gr.Accordion("☁️ 雲端備份與還原 (點擊展開/收合)", open=True):
|
| 983 |
-
with gr.Row():
|
| 984 |
-
github_btn = gr.Button("🔄 備份至 GitHub", variant="primary")
|
| 985 |
-
restore_btn = gr.Button("📥 從備份還原", variant="secondary")
|
| 986 |
-
github_log_output = gr.Textbox(label="執行日誌", interactive=False, lines=2, elem_classes="github-log")
|
| 987 |
-
|
| 988 |
-
with gr.Tabs():
|
| 989 |
-
|
| 990 |
-
with gr.TabItem("📊 訂單詳細數據"):
|
| 991 |
-
revenue_display = gr.Markdown(value=get_revenue())
|
| 992 |
-
with gr.Row():
|
| 993 |
-
customer_filter = gr.Dropdown(choices=["所有顧客"], value="所有顧客", label="🔍 篩選顧客", interactive=True)
|
| 994 |
-
time_filter = gr.Dropdown(choices=["所有時間"], value="所有時間", label="📅 篩選訂單時間", interactive=True)
|
| 995 |
-
item_filter = gr.Dropdown(choices=["所有商品"], value="所有商品", label="🍔 篩選商品", interactive=True)
|
| 996 |
-
delivery_filter = gr.Dropdown(choices=["所有交期"], value="所有交期", label="🕒 篩選預定交期", interactive=True)
|
| 997 |
-
refresh_btn = gr.Button("🔄 抓取最新訂單", variant="secondary")
|
| 998 |
-
|
| 999 |
-
# 更新表格欄位,加入取貨方式與送貨地點
|
| 1000 |
-
orders_table = gr.Dataframe(value=get_orders_data(), headers=["訂單編號", "訂單時間", "預定交期", "取貨方式", "送貨地點", "顧客姓名", "商品", "單價", "成本", "數量", "總價", "總成本", "備註"], interactive=False)
|
| 1001 |
-
|
| 1002 |
-
gr.Markdown("---")
|
| 1003 |
-
gr.Markdown("### 🗑️ 刪除訂單管理")
|
| 1004 |
-
with gr.Row(elem_classes="menu-row"):
|
| 1005 |
-
with gr.Column(scale=2):
|
| 1006 |
-
delete_target = gr.Textbox(label="刪除單筆", placeholder="👉 點擊上方表格中的訂單,編號會自動帶入此處")
|
| 1007 |
-
with gr.Column(scale=1):
|
| 1008 |
-
delete_single_btn = gr.Button("🗑️ 刪除單筆", variant="stop")
|
| 1009 |
-
with gr.Column(scale=1):
|
| 1010 |
-
clear_btn = gr.Button("🚨 清空所有", variant="stop")
|
| 1011 |
-
|
| 1012 |
-
admin_status_msg = gr.Textbox(label="管理員狀態提示", interactive=False)
|
| 1013 |
-
|
| 1014 |
-
with gr.TabItem("📝 菜單管理"):
|
| 1015 |
-
gr.Markdown("✅ **設定流水號**:數字越小排越前面。<br>✅ **設定啟���**:打勾代表商品在點餐區可見,不打勾則隱藏但保留紀錄。<br>✅ **規格與備註**:可以標示商品尺寸,並在最後一欄留下內部備註。<br>⚠️ 修改完成後請務必點擊 **「💾 儲存菜單並更新」**。")
|
| 1016 |
-
|
| 1017 |
-
menu_table = gr.Dataframe(
|
| 1018 |
-
value=get_menu_df(),
|
| 1019 |
-
headers=["流水號", "啟用", "分類", "品項", "規格", "價格", "成本", "備註"],
|
| 1020 |
-
datatype=["number", "bool", "str", "str", "str", "number", "number", "str"],
|
| 1021 |
-
interactive=True,
|
| 1022 |
-
column_widths=["6%", "6%", "12%", "20%", "15%", "8%", "8%", "25%"]
|
| 1023 |
-
)
|
| 1024 |
-
save_menu_btn = gr.Button("💾 儲存菜單並更新", variant="primary")
|
| 1025 |
-
menu_status = gr.Markdown()
|
| 1026 |
-
|
| 1027 |
-
with gr.TabItem("🔑 安全性設定"):
|
| 1028 |
-
gr.Markdown("### 🔑 修改管理員密碼")
|
| 1029 |
-
with gr.Row():
|
| 1030 |
-
with gr.Column(scale=1):
|
| 1031 |
-
old_pwd_input = gr.Textbox(label="目前密碼", type="password", placeholder="請輸入舊密碼")
|
| 1032 |
-
with gr.Column(scale=1):
|
| 1033 |
-
new_pwd_input = gr.Textbox(label="新密碼", type="password", placeholder="請輸入新密碼")
|
| 1034 |
-
with gr.Column(scale=1, min_width=150):
|
| 1035 |
-
update_pwd_btn = gr.Button("💾 確認更新密碼", variant="primary")
|
| 1036 |
-
pwd_update_status = gr.Markdown()
|
| 1037 |
-
|
| 1038 |
-
# --- 後台事件綁定區 ---
|
| 1039 |
-
|
| 1040 |
-
login_btn.click(
|
| 1041 |
-
fn=verify_password,
|
| 1042 |
-
inputs=[admin_pwd, customer_filter, time_filter, item_filter, delivery_filter],
|
| 1043 |
-
outputs=[login_pane, overview_pane, login_status, customer_filter, time_filter, item_filter, delivery_filter, orders_table, revenue_display]
|
| 1044 |
-
)
|
| 1045 |
-
|
| 1046 |
-
admin_pwd.submit(
|
| 1047 |
-
fn=verify_password,
|
| 1048 |
-
inputs=[admin_pwd, customer_filter, time_filter, item_filter, delivery_filter],
|
| 1049 |
-
outputs=[login_pane, overview_pane, login_status, customer_filter, time_filter, item_filter, delivery_filter, orders_table, revenue_display]
|
| 1050 |
-
)
|
| 1051 |
-
|
| 1052 |
-
logout_btn.click(fn=logout, inputs=[], outputs=[login_pane, overview_pane, login_status, admin_pwd])
|
| 1053 |
-
|
| 1054 |
-
customer_filter.change(
|
| 1055 |
-
fn=lambda c, t, i, d: (gr.update(value=get_orders_data(c, t, i, d)), gr.update(value=get_revenue(c, t, i, d))),
|
| 1056 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter],
|
| 1057 |
-
outputs=[orders_table, revenue_display]
|
| 1058 |
-
)
|
| 1059 |
-
|
| 1060 |
-
time_filter.change(
|
| 1061 |
-
fn=lambda c, t, i, d: (gr.update(value=get_orders_data(c, t, i, d)), gr.update(value=get_revenue(c, t, i, d))),
|
| 1062 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter],
|
| 1063 |
-
outputs=[orders_table, revenue_display]
|
| 1064 |
-
)
|
| 1065 |
-
|
| 1066 |
-
item_filter.change(
|
| 1067 |
-
fn=lambda c, t, i, d: (gr.update(value=get_orders_data(c, t, i, d)), gr.update(value=get_revenue(c, t, i, d))),
|
| 1068 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter],
|
| 1069 |
-
outputs=[orders_table, revenue_display]
|
| 1070 |
-
)
|
| 1071 |
-
|
| 1072 |
-
delivery_filter.change(
|
| 1073 |
-
fn=lambda c, t, i, d: (gr.update(value=get_orders_data(c, t, i, d)), gr.update(value=get_revenue(c, t, i, d))),
|
| 1074 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter],
|
| 1075 |
-
outputs=[orders_table, revenue_display]
|
| 1076 |
-
)
|
| 1077 |
-
|
| 1078 |
-
refresh_btn.click(
|
| 1079 |
-
fn=refresh_data,
|
| 1080 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter],
|
| 1081 |
-
outputs=[orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter]
|
| 1082 |
-
)
|
| 1083 |
-
|
| 1084 |
-
restore_btn.click(
|
| 1085 |
-
fn=restore_from_backup,
|
| 1086 |
-
inputs=[customer_filter, time_filter, item_filter, delivery_filter],
|
| 1087 |
-
outputs=[admin_status_msg, orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter, menu_table, menu_trigger]
|
| 1088 |
-
)
|
| 1089 |
-
|
| 1090 |
-
orders_table.select(
|
| 1091 |
-
fn=autofill_delete_target,
|
| 1092 |
-
inputs=[orders_table],
|
| 1093 |
-
outputs=[delete_target]
|
| 1094 |
-
)
|
| 1095 |
-
|
| 1096 |
-
delete_single_btn.click(
|
| 1097 |
-
fn=delete_single_order,
|
| 1098 |
-
inputs=[delete_target, customer_filter, time_filter, item_filter, delivery_filter],
|
| 1099 |
-
outputs=[admin_status_msg, orders_table, revenue_display, delete_target],
|
| 1100 |
-
js="(target, c_filter, t_filter, i_filter, d_filter) => { if (!target) { return [target, c_filter, t_filter, i_filter, d_filter]; } return confirm('⚠️ 確認要刪除訂單編號 [' + target + '] 嗎?此動作無法復原!') ? [target, c_filter, t_filter, i_filter, d_filter] : ['__CANCEL__', c_filter, t_filter, i_filter, d_filter]; }"
|
| 1101 |
-
)
|
| 1102 |
-
|
| 1103 |
-
clear_btn.click(
|
| 1104 |
-
fn=clear_orders,
|
| 1105 |
-
inputs=[customer_filter],
|
| 1106 |
-
outputs=[admin_status_msg, orders_table, revenue_display, customer_filter, time_filter, item_filter, delivery_filter],
|
| 1107 |
-
js="(filter) => { return confirm('🚨 極度危險:確定要清空【所有】訂單資料嗎?此動作無法復原!') ? [filter] : ['__CANCEL__']; }"
|
| 1108 |
-
)
|
| 1109 |
-
|
| 1110 |
-
github_btn.click(fn=backup_and_push_to_github, inputs=[], outputs=[github_log_output])
|
| 1111 |
-
|
| 1112 |
-
save_menu_btn.click(
|
| 1113 |
-
fn=update_menu,
|
| 1114 |
-
inputs=[menu_table],
|
| 1115 |
-
outputs=[menu_status, menu_table, menu_trigger]
|
| 1116 |
-
)
|
| 1117 |
-
|
| 1118 |
-
update_pwd_btn.click(
|
| 1119 |
-
fn=change_password,
|
| 1120 |
-
inputs=[old_pwd_input, new_pwd_input],
|
| 1121 |
-
outputs=[pwd_update_status]
|
| 1122 |
-
)
|
| 1123 |
-
|
| 1124 |
-
# ----------------------------
|
| 1125 |
-
# 🚀 啟動伺服器
|
| 1126 |
-
# ----------------------------
|
| 1127 |
-
app = gr.mount_gradio_app(custom_api, demo_ui.queue(), path="/")
|
| 1128 |
-
|
| 1129 |
-
if __name__ == "__main__":
|
| 1130 |
-
uvicorn.run(app, host="0.0.0.0", port=7860, proxy_headers=True, forwarded_allow_ips="*")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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