Update app.py
Browse files
app.py
CHANGED
|
@@ -1,17 +1,8 @@
|
|
| 1 |
import os
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
except ImportError:
|
| 7 |
-
os.system('pip install notion-client')
|
| 8 |
-
from notion_client import Client
|
| 9 |
-
|
| 10 |
-
try:
|
| 11 |
-
import pytz
|
| 12 |
-
except ImportError:
|
| 13 |
-
os.system('pip install pytz')
|
| 14 |
-
import pytz
|
| 15 |
|
| 16 |
# Install and import Groq
|
| 17 |
try:
|
|
@@ -20,107 +11,141 @@ except ImportError:
|
|
| 20 |
os.system('pip install groq')
|
| 21 |
from groq import Groq
|
| 22 |
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
from datetime import datetime
|
| 26 |
-
from typing import Optional
|
| 27 |
-
import traceback
|
| 28 |
-
|
| 29 |
-
# Set up logging with more detail
|
| 30 |
-
logging.basicConfig(
|
| 31 |
-
level=logging.DEBUG, # Changed to DEBUG for more detailed logs
|
| 32 |
-
format='%(asctime)s - %(levelname)s - %(message)s'
|
| 33 |
-
)
|
| 34 |
-
logger = logging.getLogger(__name__)
|
| 35 |
-
|
| 36 |
-
# Debug: Print environment variables (will be masked in logs)
|
| 37 |
-
logger.debug(f"NOTION_API_KEY exists: {'NOTION_API_KEY' in os.environ}")
|
| 38 |
-
logger.debug(f"NOTION_DB_ID exists: {'NOTION_DB_ID' in os.environ}")
|
| 39 |
-
logger.debug(f"NOTION_DB_ID value: {os.getenv('NOTION_DB_ID')}")
|
| 40 |
-
|
| 41 |
-
# Initialize clients with error handling
|
| 42 |
-
try:
|
| 43 |
-
groq_client = Groq(api_key=os.getenv('groq_key'))
|
| 44 |
-
logger.info("Groq client initialized successfully")
|
| 45 |
-
except Exception as e:
|
| 46 |
-
logger.error(f"Failed to initialize Groq client: {str(e)}")
|
| 47 |
-
raise
|
| 48 |
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
NOTION_DB_ID = os.getenv('NOTION_DB_ID')
|
| 56 |
-
|
| 57 |
-
if not NOTION_DB_ID:
|
| 58 |
-
raise ValueError("NOTION_DB_ID is not set in environment variables")
|
| 59 |
-
|
| 60 |
-
# Test Notion connection
|
| 61 |
-
try:
|
| 62 |
-
notion.databases.retrieve(NOTION_DB_ID)
|
| 63 |
-
logger.info("Successfully connected to Notion database")
|
| 64 |
-
except Exception as e:
|
| 65 |
-
logger.error(f"Failed to access Notion database: {str(e)}")
|
| 66 |
-
raise
|
| 67 |
-
|
| 68 |
-
except Exception as e:
|
| 69 |
-
logger.error(f"Failed to initialize Notion client: {str(e)}")
|
| 70 |
-
raise
|
| 71 |
-
|
| 72 |
-
def safe_text_truncate(text: str, max_length: int = 2000) -> str:
|
| 73 |
-
"""Safely truncate text to avoid Notion API limits"""
|
| 74 |
-
return text[:max_length] if text else ""
|
| 75 |
-
|
| 76 |
-
def log_to_notion(name: str, user_input: str, bot_response: str) -> Optional[dict]:
|
| 77 |
-
"""
|
| 78 |
-
Log chat interaction to Notion database with error handling
|
| 79 |
-
Returns the created page or None if failed
|
| 80 |
-
"""
|
| 81 |
try:
|
| 82 |
-
|
| 83 |
-
logger.debug(f"Using database ID: {NOTION_DB_ID}")
|
| 84 |
-
|
| 85 |
-
taipei_tz = pytz.timezone('Asia/Taipei')
|
| 86 |
-
current_time = datetime.now(taipei_tz).strftime("%Y-%m-%d %H:%M:%S")
|
| 87 |
-
|
| 88 |
-
# Truncate long texts to avoid Notion API limits
|
| 89 |
-
user_input_truncated = safe_text_truncate(user_input)
|
| 90 |
-
bot_response_truncated = safe_text_truncate(bot_response)
|
| 91 |
-
name_truncated = safe_text_truncate(name, 100)
|
| 92 |
-
|
| 93 |
-
# Debug log the data being sent
|
| 94 |
-
logger.debug(f"Preparing to send data to Notion:")
|
| 95 |
-
logger.debug(f"Name: {name_truncated}")
|
| 96 |
-
logger.debug(f"Timestamp: {current_time}")
|
| 97 |
-
logger.debug(f"User Input Length: {len(user_input_truncated)}")
|
| 98 |
-
logger.debug(f"Bot Response Length: {len(bot_response_truncated)}")
|
| 99 |
-
|
| 100 |
-
page = notion.pages.create(
|
| 101 |
parent={"database_id": NOTION_DB_ID},
|
| 102 |
properties={
|
| 103 |
"Name": {
|
| 104 |
-
"title": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
},
|
| 106 |
"Timestamp": {
|
| 107 |
-
"
|
|
|
|
|
|
|
| 108 |
},
|
| 109 |
"User Input": {
|
| 110 |
-
"rich_text": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
},
|
| 112 |
"Bot Response": {
|
| 113 |
-
"rich_text": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
}
|
| 115 |
}
|
| 116 |
)
|
| 117 |
-
|
| 118 |
-
logger.info(f"Successfully logged to Notion. Page ID: {page.get('id', 'unknown')}")
|
| 119 |
-
return page
|
| 120 |
-
|
| 121 |
except Exception as e:
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
from datetime import datetime
|
| 3 |
+
import pytz
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from notion_client import Client
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
# Install and import Groq
|
| 8 |
try:
|
|
|
|
| 11 |
os.system('pip install groq')
|
| 12 |
from groq import Groq
|
| 13 |
|
| 14 |
+
# Initialize Groq client with API key
|
| 15 |
+
client = Groq(api_key=os.getenv('groq_key'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
# Initialize Notion client
|
| 18 |
+
notion = Client(auth=os.getenv('NOTION_API_KEY'))
|
| 19 |
+
NOTION_DB_ID = os.getenv('NOTION_DB_ID')
|
| 20 |
+
|
| 21 |
+
def log_to_notion(name, user_message, bot_response):
|
| 22 |
+
"""Log conversation to Notion database"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
try:
|
| 24 |
+
notion.pages.create(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
parent={"database_id": NOTION_DB_ID},
|
| 26 |
properties={
|
| 27 |
"Name": {
|
| 28 |
+
"title": [
|
| 29 |
+
{
|
| 30 |
+
"text": {
|
| 31 |
+
"content": name
|
| 32 |
+
}
|
| 33 |
+
}
|
| 34 |
+
]
|
| 35 |
},
|
| 36 |
"Timestamp": {
|
| 37 |
+
"date": {
|
| 38 |
+
"start": datetime.now(pytz.UTC).isoformat()
|
| 39 |
+
}
|
| 40 |
},
|
| 41 |
"User Input": {
|
| 42 |
+
"rich_text": [
|
| 43 |
+
{
|
| 44 |
+
"text": {
|
| 45 |
+
"content": user_message
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
]
|
| 49 |
},
|
| 50 |
"Bot Response": {
|
| 51 |
+
"rich_text": [
|
| 52 |
+
{
|
| 53 |
+
"text": {
|
| 54 |
+
"content": bot_response
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
]
|
| 58 |
}
|
| 59 |
}
|
| 60 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
except Exception as e:
|
| 62 |
+
print(f"Error logging to Notion: {e}")
|
| 63 |
+
|
| 64 |
+
def process_message(message, history):
|
| 65 |
+
# Prepare the messages including history and new message
|
| 66 |
+
messages = [
|
| 67 |
+
{
|
| 68 |
+
"role": "system",
|
| 69 |
+
"content": "你是一個高中數學老師,使用的語言是英文。學生用中文問妳任何字彙,你都可以告訴他那個中文對應的英文和例句,以及在數學上的可能用法以及數學例題和解法。\n說明數學上的可能用法時,先用中文講一遍再用B1程度的英文複述一遍\n"
|
| 70 |
+
}
|
| 71 |
+
]
|
| 72 |
+
|
| 73 |
+
# Add chat history
|
| 74 |
+
for user_msg, bot_msg in history:
|
| 75 |
+
messages.append({"role": "user", "content": user_msg})
|
| 76 |
+
messages.append({"role": "assistant", "content": bot_msg})
|
| 77 |
+
|
| 78 |
+
# Add the new message
|
| 79 |
+
messages.append({"role": "user", "content": message})
|
| 80 |
+
|
| 81 |
+
# Get response from Groq
|
| 82 |
+
completion = client.chat.completions.create(
|
| 83 |
+
model="llama-3.3-70b-versatile",
|
| 84 |
+
messages=messages,
|
| 85 |
+
temperature=1,
|
| 86 |
+
max_tokens=1024,
|
| 87 |
+
top_p=1,
|
| 88 |
+
stream=True,
|
| 89 |
+
stop=None,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# Initialize response text
|
| 93 |
+
response_text = ""
|
| 94 |
+
|
| 95 |
+
# Stream the response
|
| 96 |
+
for chunk in completion:
|
| 97 |
+
delta_content = chunk.choices[0].delta.content
|
| 98 |
+
if delta_content is not None:
|
| 99 |
+
response_text += delta_content
|
| 100 |
+
yield response_text
|
| 101 |
+
|
| 102 |
+
# Create Gradio interface
|
| 103 |
+
with gr.Blocks() as demo:
|
| 104 |
+
name_input = gr.Textbox(
|
| 105 |
+
placeholder="請輸入您的名字...",
|
| 106 |
+
label="名字",
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
chatbot = gr.Chatbot(
|
| 110 |
+
height=600,
|
| 111 |
+
show_label=False,
|
| 112 |
+
container=True,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
msg = gr.Textbox(
|
| 116 |
+
placeholder="輸入您的問題...",
|
| 117 |
+
show_label=False,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
clear = gr.Button("清除對話")
|
| 121 |
+
|
| 122 |
+
def user(user_message, history):
|
| 123 |
+
return "", history + [[user_message, None]]
|
| 124 |
+
|
| 125 |
+
def bot(user_message, history, name):
|
| 126 |
+
history[-1][1] = ""
|
| 127 |
+
for response in process_message(history[-1][0], history[:-1]):
|
| 128 |
+
history[-1][1] = response
|
| 129 |
+
yield history
|
| 130 |
+
|
| 131 |
+
# Log the complete conversation to Notion after the response is complete
|
| 132 |
+
if history[-1][1]: # Only log if there's a response
|
| 133 |
+
log_to_notion(name, user_message, history[-1][1])
|
| 134 |
+
|
| 135 |
+
msg.submit(
|
| 136 |
+
user,
|
| 137 |
+
[msg, chatbot],
|
| 138 |
+
[msg, chatbot],
|
| 139 |
+
queue=False
|
| 140 |
+
).then(
|
| 141 |
+
bot,
|
| 142 |
+
[msg, chatbot, name_input],
|
| 143 |
+
chatbot
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
clear.click(lambda: None, None, chatbot, queue=False)
|
| 147 |
|
| 148 |
+
# Launch the app
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
demo.queue()
|
| 151 |
+
demo.launch()
|