youngtsai commited on
Commit
6c33fca
·
verified ·
1 Parent(s): 1e645c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +17 -22
app.py CHANGED
@@ -1,23 +1,28 @@
1
  import gradio as gr
2
  import os
3
- import csv
4
- import requests
5
  from datetime import datetime
6
 
7
- # Install the groq package if it is not installed
8
  try:
9
  from groq import Groq
10
  except ImportError:
11
  os.system('pip install groq')
12
  from groq import Groq
13
 
14
- # Set up the Groq client with the secret key
15
  groq_key = os.getenv('groq_key')
16
  if not groq_key:
17
  raise ValueError("groq_key environment variable is not set")
18
 
19
  client = Groq(api_key=groq_key)
20
 
 
 
 
 
 
 
21
  class SimpleChatBot:
22
  def __init__(self):
23
  self.initial_prompt = [
@@ -49,38 +54,28 @@ class SimpleChatBot:
49
 
50
  chatbot = SimpleChatBot()
51
 
52
- # Function to log chat history to Google Sheet
53
  def log_to_sheet(user_message, bot_response):
54
- # Prepare the URL for Google Sheets API using the shared link
55
- sheet_url = "https://docs.google.com/spreadsheets/d/1BQ23fiiGu5wN4RmRC4XmrKS6qCWHuymlbsoLEEmEN_4/gviz/tq?tqx=out:csv"
56
-
57
- # Prepare the data row
58
- timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
59
- row = [timestamp, user_message, bot_response]
60
-
61
- # Append the row to the sheet using HTTP requests
62
  try:
63
- response = requests.post(sheet_url, data={'append': row})
64
- if response.status_code == 200:
65
- print("Logged to Google Sheet successfully.")
66
- else:
67
- print(f"Failed to log to Google Sheet: {response.status_code}")
68
  except Exception as e:
69
- print(f"Error while logging to Google Sheet: {e}")
70
 
71
- # Chatbot response function with logging
72
  def respond(message, chat_history):
73
  chat_history = [{"role": entry["role"], "content": entry["content"]} for entry in chat_history]
74
  response = chatbot.get_response(message, chat_history)
75
  chat_history.append({"role": "user", "content": message})
76
  chat_history.append({"role": "assistant", "content": response})
77
 
78
- # Log to Google Sheet
79
  log_to_sheet(message, response)
80
 
81
  return chat_history, ""
82
 
83
- # Gradio interface
84
  with gr.Blocks(title="簡單的Gradio聊天機器人") as demo:
85
  gr.Markdown("# 簡單的Gradio聊天機器人")
86
 
 
1
  import gradio as gr
2
  import os
3
+ import gspread
 
4
  from datetime import datetime
5
 
6
+ # 安裝並導入 groq 套件
7
  try:
8
  from groq import Groq
9
  except ImportError:
10
  os.system('pip install groq')
11
  from groq import Groq
12
 
13
+ # 設定 Groq API Key
14
  groq_key = os.getenv('groq_key')
15
  if not groq_key:
16
  raise ValueError("groq_key environment variable is not set")
17
 
18
  client = Groq(api_key=groq_key)
19
 
20
+ # 使用 gspread 連接 Google Sheet
21
+ sheet_url = "https://docs.google.com/spreadsheets/d/1BQ23fiiGu5wN4RmRC4XmrKS6qCWHuymlbsoLEEmEN_4/edit?usp=sharing"
22
+ gc = gspread.service_account() # 無需 Google Console 憑證時,可以跳過此步驟
23
+ sheet = gc.open_by_url(sheet_url).sheet1 # 獲取第一個工作表
24
+
25
+ # 定義簡單的 Chatbot
26
  class SimpleChatBot:
27
  def __init__(self):
28
  self.initial_prompt = [
 
54
 
55
  chatbot = SimpleChatBot()
56
 
57
+ # 記錄聊天內容到 Google Sheet
58
  def log_to_sheet(user_message, bot_response):
 
 
 
 
 
 
 
 
59
  try:
60
+ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
61
+ sheet.append_row([timestamp, user_message, bot_response])
62
+ print("Logged to Google Sheet successfully.")
 
 
63
  except Exception as e:
64
+ print(f"Error logging to Google Sheet: {e}")
65
 
66
+ # 定義回應邏輯
67
  def respond(message, chat_history):
68
  chat_history = [{"role": entry["role"], "content": entry["content"]} for entry in chat_history]
69
  response = chatbot.get_response(message, chat_history)
70
  chat_history.append({"role": "user", "content": message})
71
  chat_history.append({"role": "assistant", "content": response})
72
 
73
+ # 記錄到 Google Sheet
74
  log_to_sheet(message, response)
75
 
76
  return chat_history, ""
77
 
78
+ # 建立 Gradio 界面
79
  with gr.Blocks(title="簡單的Gradio聊天機器人") as demo:
80
  gr.Markdown("# 簡單的Gradio聊天機器人")
81