IAMTFRMZA commited on
Commit
691e8b4
·
verified ·
1 Parent(s): aad9375

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -18
app.py CHANGED
@@ -5,17 +5,16 @@ import os
5
  import pandas as pd
6
  from datetime import datetime
7
 
8
- # Get environment variables
9
  openai_key = os.getenv("openai_key")
10
  assistant_id = os.getenv("ASSISTANT_ID")
11
 
12
- # Load or create transcript file
13
  transcript_file = "transcripts.xlsx"
14
  if not os.path.exists(transcript_file):
15
  df = pd.DataFrame(columns=["timestamp", "thread_id", "role", "message"])
16
  df.to_excel(transcript_file, index=False)
17
 
18
- # Function to append to transcript
19
  def append_to_transcript(thread_id, role, message):
20
  df_existing = pd.read_excel(transcript_file)
21
  new_entry = pd.DataFrame({
@@ -27,33 +26,43 @@ def append_to_transcript(thread_id, role, message):
27
  updated_df = pd.concat([df_existing, new_entry], ignore_index=True)
28
  updated_df.to_excel(transcript_file, index=False)
29
 
30
- # Streamlit UI setup
31
  st.set_page_config(page_title="Carfind.co.za AI Assistant", layout="wide")
32
 
 
33
  st.markdown("""
34
  <style>
35
  .block-container {padding-top: 1rem; padding-bottom: 0rem;}
36
  header {visibility: hidden;}
37
  .st-emotion-cache-18ni7ap {visibility: hidden;}
38
- .stChatMessage { max-width: 85%; border-radius: 12px; padding: 8px; }
39
  .stChatMessage[data-testid="stChatMessage-user"] { background: #f0f0f0; color: #000000; }
40
  .stChatMessage[data-testid="stChatMessage-assistant"] { background: #D6E9FE; color: #000000; }
 
 
 
 
 
 
41
  </style>
42
  """, unsafe_allow_html=True)
43
 
 
44
  if "thread_id" not in st.session_state:
45
  st.session_state["thread_id"] = None
46
 
47
- input_col, clear_col = st.columns([8, 1])
 
 
48
  with input_col:
49
- user_input = st.text_input("", placeholder="Type your message here...", key="chat_input")
50
 
51
  with clear_col:
52
- if st.button("🗑️", help="Clear Chat"):
53
  st.session_state["thread_id"] = None
54
- st.success("Chat cleared.")
55
  st.rerun()
56
 
 
57
  if openai_key and assistant_id:
58
  client = OpenAI(api_key=openai_key)
59
 
@@ -85,27 +94,25 @@ if openai_key and assistant_id:
85
  )
86
 
87
  assistant_icon_html = "<img src='https://www.carfind.co.za/images/Carfind-Icon.svg' width='22' style='vertical-align:middle;'/>"
88
-
89
  messages_sorted = sorted(messages_response.data, key=lambda x: x.created_at, reverse=True)
 
90
  for msg in messages_sorted:
91
  if msg.role == "user":
92
  st.markdown(
93
- f"<div style='background-color:#f0f0f0; color:#000000; padding:10px; border-radius:8px; margin:5px 0;'>"
94
- f"👤 <strong>You:</strong> {msg.content[0].text.value}"
95
- f"</div>",
96
  unsafe_allow_html=True
97
  )
98
  else:
99
  response_text = msg.content[0].text.value
100
  append_to_transcript(st.session_state["thread_id"], "assistant", response_text)
101
  st.markdown(
102
- f"<div style='background-color:#D6E9FE; color:#000000; padding:10px; border-radius:8px; margin:5px 0;'>"
103
- f"{assistant_icon_html} <strong>Carfind Assistant:</strong> {response_text}"
104
- f"</div>",
105
  unsafe_allow_html=True
106
  )
107
 
108
  except Exception as e:
109
- st.error(f"An error occurred: {str(e)}")
110
  else:
111
- st.error("⚠️ OpenAI key or Assistant ID not found. Please ensure both are set as Hugging Face secrets.")
 
5
  import pandas as pd
6
  from datetime import datetime
7
 
8
+ # Load environment variables
9
  openai_key = os.getenv("openai_key")
10
  assistant_id = os.getenv("ASSISTANT_ID")
11
 
12
+ # Set up transcript log
13
  transcript_file = "transcripts.xlsx"
14
  if not os.path.exists(transcript_file):
15
  df = pd.DataFrame(columns=["timestamp", "thread_id", "role", "message"])
16
  df.to_excel(transcript_file, index=False)
17
 
 
18
  def append_to_transcript(thread_id, role, message):
19
  df_existing = pd.read_excel(transcript_file)
20
  new_entry = pd.DataFrame({
 
26
  updated_df = pd.concat([df_existing, new_entry], ignore_index=True)
27
  updated_df.to_excel(transcript_file, index=False)
28
 
29
+ # Configure page
30
  st.set_page_config(page_title="Carfind.co.za AI Assistant", layout="wide")
31
 
32
+ # Inject custom styling
33
  st.markdown("""
34
  <style>
35
  .block-container {padding-top: 1rem; padding-bottom: 0rem;}
36
  header {visibility: hidden;}
37
  .st-emotion-cache-18ni7ap {visibility: hidden;}
38
+ .stChatMessage { max-width: 85%; border-radius: 12px; padding: 8px; margin-bottom: 10px; }
39
  .stChatMessage[data-testid="stChatMessage-user"] { background: #f0f0f0; color: #000000; }
40
  .stChatMessage[data-testid="stChatMessage-assistant"] { background: #D6E9FE; color: #000000; }
41
+ div[data-testid="column"] button {
42
+ border: none;
43
+ background-color: transparent;
44
+ font-size: 1.4rem;
45
+ margin-top: 18px;
46
+ }
47
  </style>
48
  """, unsafe_allow_html=True)
49
 
50
+ # Initialize session
51
  if "thread_id" not in st.session_state:
52
  st.session_state["thread_id"] = None
53
 
54
+ # Inline layout for chat input + clear button
55
+ input_col, clear_col = st.columns([9, 1])
56
+
57
  with input_col:
58
+ user_input = st.chat_input("Type your message here...")
59
 
60
  with clear_col:
61
+ if st.button("🗑️", key="clear-chat", help="Clear Chat"):
62
  st.session_state["thread_id"] = None
 
63
  st.rerun()
64
 
65
+ # Chat logic
66
  if openai_key and assistant_id:
67
  client = OpenAI(api_key=openai_key)
68
 
 
94
  )
95
 
96
  assistant_icon_html = "<img src='https://www.carfind.co.za/images/Carfind-Icon.svg' width='22' style='vertical-align:middle;'/>"
 
97
  messages_sorted = sorted(messages_response.data, key=lambda x: x.created_at, reverse=True)
98
+
99
  for msg in messages_sorted:
100
  if msg.role == "user":
101
  st.markdown(
102
+ f"<div class='stChatMessage' data-testid='stChatMessage-user'>"
103
+ f"👤 <strong>You:</strong> {msg.content[0].text.value}</div>",
 
104
  unsafe_allow_html=True
105
  )
106
  else:
107
  response_text = msg.content[0].text.value
108
  append_to_transcript(st.session_state["thread_id"], "assistant", response_text)
109
  st.markdown(
110
+ f"<div class='stChatMessage' data-testid='stChatMessage-assistant'>"
111
+ f"{assistant_icon_html} <strong>Carfind Assistant:</strong> {response_text}</div>",
 
112
  unsafe_allow_html=True
113
  )
114
 
115
  except Exception as e:
116
+ st.error(f"An error occurred: {str(e)}")
117
  else:
118
+ st.error("⚠️ OpenAI key or Assistant ID not found. Please ensure both are set as Hugging Face secrets.")