db_router.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. from fastapi import APIRouter
  2. from supabase import create_client, Client
  3. from dotenv import load_dotenv
  4. import os
  5. from datetime import datetime
  6. from random import choice
  7. from openai import OpenAI
  8. from typing import Annotated
  9. from pydantic import Field
  10. client = OpenAI()
  11. load_dotenv()
  12. # supaspace 連線
  13. url: str = os.environ.get('SUPABASE_URL')
  14. key: str = os.environ.get('SUPABASE_KEY')
  15. supabase: Client = create_client(url, key)
  16. dbRouter = APIRouter()
  17. @dbRouter.get("/click")
  18. def add_click_time():
  19. try:
  20. response = supabase.table('click_time').select("*").execute()
  21. click_time = response.data[0]['click_time'] + 1
  22. data, count = supabase.table('click_time') \
  23. .update({'click_time':click_time,'update_time':str(datetime.now())})\
  24. .eq('id', 1)\
  25. .execute()
  26. return {"state":"success","click_time" : click_time}
  27. except Exception as e:
  28. return {"state":str(e)}
  29. @dbRouter.get("/find_brand")
  30. def find_brand(keyword:str = None,language :str = "ch",page_num : int = None,page_amount: int = None,search_name : str = None):
  31. if keyword is None :
  32. query = supabase.table('101_brand').select('*').eq("language", language)
  33. else :
  34. keyword_list = keyword.split(",")
  35. query= supabase.table('101_brand').select('*').eq("language", language)
  36. for keyword_tmp in keyword_list :
  37. query = query.like('tags', f'%{keyword_tmp}%')
  38. if search_name:
  39. query = query.like('name', f'%{search_name}%')
  40. result,_ = query.execute()
  41. count = len(result[1])
  42. if page_num and page_amount :
  43. offset = (page_num - 1) * page_amount
  44. query = query.range(offset, offset + page_amount-1)
  45. try:
  46. data,_ = query.execute()
  47. result = []
  48. for shop in data[1] :
  49. json = {
  50. "type" : shop["type"],
  51. "info" : shop
  52. }
  53. if language != "ch" :
  54. if shop["floor"] == "館外" :
  55. json["info"]["floor"] = "outside"
  56. result.append(json)
  57. return {"state":"success","all_num" : count,"data" : result}
  58. except Exception as e:
  59. return {"state":"fail","message" :str(e)}
  60. @dbRouter.get("/arviews")
  61. def arviews(start:str,end:str,language:str = "ch"):
  62. try :
  63. data, count = supabase.table('101_arviews')\
  64. .select('*')\
  65. .eq('start_loc', start) \
  66. .like('tour_place', f'%{end}%') \
  67. .execute()
  68. result :str
  69. words :str
  70. if len(data[1]) != 0:
  71. if language == "ch" :
  72. result = data[1][0]["url"]
  73. words = data[1][0]["words"]
  74. else:
  75. result = data[1][0]["en_url"]
  76. words = data[1][0]["en_words"]
  77. else :
  78. result = "no this route"
  79. return {"state":"success","url" : result,"words" : words}
  80. except Exception as e:
  81. return {"state":"fail","message" :str(e)}
  82. @dbRouter.get("/static_tickets")
  83. async def static_tickets(is_Chinese : int = None):
  84. try:
  85. data =None
  86. if is_Chinese :
  87. data, count = supabase.table('101_ticket')\
  88. .select('*')\
  89. .in_('id', [1,3,6,7])\
  90. .execute()
  91. else :
  92. data, count = supabase.table('101_ticket')\
  93. .select('*')\
  94. .in_('id', [182,183,180])\
  95. .execute()
  96. result = []
  97. for shop in data[1] :
  98. json = {
  99. "type" : shop["type"],
  100. "info" : shop
  101. }
  102. result.append(json)
  103. return {"state":"success","result" : result}
  104. except Exception as e:
  105. return {"state":"fail","message" :str(e)}
  106. @dbRouter.get("/ad/{type}")
  107. def read_root(type:str,language :str = "ch"):
  108. keyword1 :str
  109. keyword2 :str
  110. if type == "美食伴手禮":
  111. keyword1 = "餐飲"
  112. keyword2 = "伴手禮"
  113. else :
  114. keyword1 = "住宿"
  115. keyword2 = "伴手禮"
  116. data, count = supabase.table('101_brand')\
  117. .select('*')\
  118. .eq("floor","館外")\
  119. .eq("language", language)\
  120. .or_(f"tags.ilike.%{keyword1}%,tags.ilike.%{keyword2}%")\
  121. .execute()
  122. result = data[1]
  123. # 從結果中隨機選擇一筆資料
  124. random_row = choice(result)
  125. if language != "ch" :
  126. if random_row["floor"] == "館外" :
  127. random_row["floor"] = "outside"
  128. #print(random_row)
  129. return {"data": random_row}
  130. @dbRouter.post("/message_not_in_cache")
  131. def message_not_in_cache(question :str ,answer :str,client_id : str = "0" ):
  132. try:
  133. data, count = supabase.table('client_message').select('*').eq("question",question).execute()
  134. if len(data[1]) != 0 :
  135. return {"state": 200 , "message" : "have saved"}
  136. data, count = supabase.table('client_message').insert({"client_id": client_id, "question": question,"answer":answer}).execute()
  137. return {"state": 200 , "message" : "success"}
  138. except Exception as e:
  139. return {"state": 500 , "message" : str(e)}
  140. from pydantic import BaseModel, EmailStr
  141. import base64
  142. import pickle
  143. from email.mime.text import MIMEText
  144. from google.auth.transport.requests import Request
  145. from google.oauth2.credentials import Credentials
  146. from google_auth_oauthlib.flow import InstalledAppFlow
  147. from googleapiclient.discovery import build
  148. import os
  149. SCOPES = ['https://www.googleapis.com/auth/gmail.send']
  150. class dataform(BaseModel):
  151. title: str
  152. content: str
  153. client_name: str
  154. gender: str
  155. email: EmailStr
  156. phone: str
  157. type:str
  158. def send_email(to_email,from_email,message):
  159. creds = None
  160. # 如果存在 token.pickle 文件,讀取
  161. if os.path.exists('token.pickle'):
  162. with open('token.pickle', 'rb') as token:
  163. creds = pickle.load(token)
  164. # 如果沒有有效的憑據,就進行登入
  165. if not creds or not creds.valid:
  166. if creds and creds.expired and creds.refresh_token:
  167. creds.refresh(Request())
  168. else:
  169. flow = InstalledAppFlow.from_client_secrets_file(
  170. 'credentials.json', SCOPES)
  171. creds = flow.run_local_server(port=0)
  172. # 保存憑據
  173. with open('token.pickle', 'wb') as token:
  174. pickle.dump(creds, token)
  175. service = build('gmail', 'v1', credentials=creds)
  176. # 設定郵件
  177. message = MIMEText(message)
  178. message['to'] = to_email
  179. message['from'] = from_email
  180. message['subject'] = '101 ai客服 表單新資料'
  181. raw = base64.urlsafe_b64encode(message.as_bytes()).decode()
  182. # 發送郵件
  183. try:
  184. message = service.users().messages().send(userId='me', body={'raw': raw}).execute()
  185. print(f'已發送郵件: {message["id"]}')
  186. return "success"
  187. except Exception as error:
  188. print(f'發送郵件時出錯: {error}')
  189. return "fail"
  190. @dbRouter.post("/insert_table")
  191. def insert_table(data: dataform):
  192. try:
  193. response,count = supabase.table('lost_property').insert(data.dict()).execute()
  194. email_content = f"問題類別:{response[1][0]['type']}\n標題:{response[1][0]['title']}\n內容:{response[1][0]['content']}\n姓名:{response[1][0]['client_name']}\n性別:{response[1][0]['gender']}\n電子郵件:{response[1][0]['email']}\n聯絡電話:{response[1][0]['phone']}\n"
  195. try:
  196. send_email("steven@choozmo.com","mia@choozmo.com",str(email_content)) # mallservice@tfc101.com.tw
  197. except Exception as e:
  198. print(str(e))
  199. return {"state": 200 ,"message": "資料已成功提交"}
  200. except Exception as e:
  201. return {"state": 500 , "message" : str(e)}
  202. @dbRouter.post("/video_save_into_cache")
  203. def message_not_in_cache(video_name : Annotated[str, Field(description="檔案請丟進/home/mia/101/static/video_cache/others/資料夾裡")],client_message_id :str = None,question:str = None):
  204. try:
  205. data = []
  206. if client_message_id :
  207. data, count = supabase.table('client_message').select('*').eq("id",client_message_id).execute()
  208. elif question:
  209. data, count = supabase.table('client_message').select('*').eq("question",question).execute()
  210. info = data[1][0]
  211. response = supabase.table('video_cache').insert({"question": info["question"],"answer":info["answer"],"video_url":f"/static/video_cache/others/{video_name}"}).execute()
  212. response = supabase.table('client_message').delete().eq('id', info["id"]).execute()
  213. return {"state": 200 , "message" : "success"}
  214. except Exception as e:
  215. return {"state": 500 , "message" : str(e)}
  216. from sherry.semantic_search import ask_question
  217. @dbRouter.post("/video_cache")
  218. def video_cache(client_message :str ):
  219. try:
  220. # data, count = supabase.table('video_cache').select('*').like('question', f'%{client_message}%').execute()
  221. # if len(data[1]) == 0 :
  222. # return {"state": 500 , "message" : "no data"}
  223. # return {"state": 200 , "message" : data[1]}
  224. result = ask_question(client_message)
  225. if result == None :
  226. return {"state": 500 , "message" : "no data"}
  227. return {"state": 200 , "message" : result }
  228. except Exception as e:
  229. return {"state": 500 , "message" : str(e)}