Spaces:
Sleeping
Sleeping
| # db_manager.py | |
| from supabase import create_client | |
| import config | |
| # 初始化 Supabase 連線 | |
| url = config.SUPABASE_URL | |
| key = config.SUPABASE_KEY | |
| # 💡 防呆檢查 | |
| if not url or not key: | |
| print("⚠️ 警告:SUPABASE_URL 或 KEY 尚未設定,將無法使用永久記憶功能!") | |
| supabase = None | |
| else: | |
| supabase = create_client(url, key) | |
| def get_user_tribe(user_id): | |
| """從雲端讀取使用者的族語選擇,找不到就預設阿美""" | |
| if not supabase: return "阿美" | |
| try: | |
| res = supabase.table("user_preferences").select("tribe").eq("user_id", user_id).execute() | |
| if res.data and len(res.data) > 0: | |
| return res.data[0]['tribe'] | |
| except Exception as e: | |
| print(f"❌ 讀取資料庫失敗: {e}") | |
| return "阿美" | |
| # db_manager.py 修正片段 | |
| def set_user_tribe(user_id, tribe, display_name="Unknown"): | |
| """將使用者的族語選擇與暱稱寫入雲端""" | |
| if not supabase: return False | |
| try: | |
| # 💡 加入 display_name 欄位 | |
| data = { | |
| "user_id": user_id, | |
| "tribe": tribe, | |
| "display_name": display_name | |
| } | |
| supabase.table("user_preferences").upsert(data).execute() | |
| return True | |
| except Exception as e: | |
| print(f"❌ 寫入資料庫失敗: {e}") | |
| return False | |
| # 💡 旗艦版新增:紀錄互動日誌 (供戰情室分析) | |
| def log_interaction(user_id, tribe, itype, query): | |
| """紀錄每一次的互動,包含類型與內容""" | |
| if not supabase: return | |
| try: | |
| data = { | |
| "user_id": user_id, | |
| "tribe": tribe, | |
| "interaction_type": itype, | |
| "query_content": query[:200] # 💡 紀錄前 200 字,對接資料庫的 query_content 欄位 | |
| } | |
| supabase.table("translation_logs").insert(data).execute() | |
| except Exception as e: | |
| print(f"❌ 紀錄 Log 失敗: {e}") | |
| # 💡 旗艦版新增:紀錄使用者的評分 (👍 好評 / 👎 負評) | |
| def log_feedback(user_id, tribe, feedback_type): | |
| """將使用者的 👍/👎 回饋寫入資料庫""" | |
| if not supabase: return | |
| try: | |
| data = { | |
| "user_id": user_id, | |
| "tribe": tribe, | |
| "interaction_type": f"feedback_{feedback_type}", | |
| "query_content": f"User gave {feedback_type} feedback" # 💡 這裡也必須對齊 query_content 欄位 | |
| } | |
| supabase.table("translation_logs").insert(data).execute() | |
| except Exception as e: | |
| print(f"❌ 紀錄回饋失敗: {e}") |