IAMTFRMZA commited on
Commit
c0332bf
·
verified ·
1 Parent(s): f9476ac

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +25 -31
app.py CHANGED
@@ -3,15 +3,16 @@ from openai import OpenAI
3
  import time
4
  import datetime
5
  import os
 
6
 
7
- # Securely get credentials from Hugging Face secrets
8
  generated_user = os.getenv("User")
9
  generated_password = os.getenv("Password")
10
  openai_key = os.getenv("openai_key")
11
 
12
- # Streamlit app configuration
13
- st.set_page_config(page_title="Carfind.co.za AI Assistant")
14
- st.title("Carfind.co.za AI Assistant")
15
  st.caption("Chat with Carfind.co.za and find your next car fast")
16
 
17
  # Initialize authentication state
@@ -20,11 +21,10 @@ if "authenticated" not in st.session_state:
20
 
21
  # Login screen
22
  if not st.session_state.authenticated:
23
- st.subheader("Login")
24
  username = st.text_input("Username")
25
  password = st.text_input("Password", type="password")
26
 
27
- # Auto-login once both fields are filled
28
  if username and password:
29
  if username == generated_user and password == generated_password:
30
  st.session_state.authenticated = True
@@ -38,31 +38,30 @@ if not st.session_state.authenticated:
38
  else:
39
  st.divider()
40
 
41
- # Display chat history
42
  if "messages" not in st.session_state:
43
  st.session_state["messages"] = []
44
 
45
- for message in st.session_state.messages:
46
- role = message["role"]
47
- content = message["content"]
48
- st.chat_message(role).write(content)
 
49
 
50
- # Add Clear Chat button next to input field
51
- clear_col, input_col = st.columns([1, 8])
52
- with clear_col:
53
- if st.button("🧹 Clear Chat"):
54
- st.session_state.messages = []
55
- st.success("Chat history cleared.")
56
 
57
- with input_col:
58
  user_input = st.chat_input("Type your message here...")
59
 
60
- # Check for OpenAI key
 
 
 
 
61
  if openai_key:
62
  client = OpenAI(api_key=openai_key)
63
  ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
64
 
65
- # Save chat transcript (backend only)
66
  def save_transcript(messages):
67
  with open("chat_logs.txt", "a") as log:
68
  log.write(f"\n--- New Chat ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n")
@@ -70,30 +69,26 @@ else:
70
  log.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
71
  log.write("--- End Chat ---\n")
72
 
73
- # Handle user input and keep sticky experience
74
  if user_input:
75
  st.session_state.messages.append({"role": "user", "content": user_input})
76
- st.chat_message("user").write(user_input)
 
77
 
78
  try:
79
- # Start OpenAI chat thread
80
  thread = client.beta.threads.create()
81
  thread_id = thread.id
82
 
83
- # Send user message
84
  client.beta.threads.messages.create(
85
  thread_id=thread_id,
86
  role="user",
87
  content=user_input
88
  )
89
 
90
- # Trigger assistant response
91
  run = client.beta.threads.runs.create(
92
  thread_id=thread_id,
93
  assistant_id=ASSISTANT_ID
94
  )
95
 
96
- # Wait for assistant completion
97
  while True:
98
  run_status = client.beta.threads.runs.retrieve(
99
  thread_id=thread_id,
@@ -103,19 +98,18 @@ else:
103
  break
104
  time.sleep(1)
105
 
106
- # Retrieve assistant message
107
  messages = client.beta.threads.messages.list(thread_id=thread_id)
108
  assistant_message = messages.data[0].content[0].text.value
109
 
110
- # Display and store the assistant’s response
111
- st.chat_message("assistant").write(assistant_message)
112
  st.session_state.messages.append({"role": "assistant", "content": assistant_message})
113
 
114
- # Save chat log
 
 
115
  save_transcript(st.session_state.messages)
116
 
117
  except Exception as e:
118
  st.error(f"An error occurred: {str(e)}")
 
119
  else:
120
  st.error("OpenAI key not found. Please ensure it is set as a Hugging Face secret.")
121
-
 
3
  import time
4
  import datetime
5
  import os
6
+ from streamlit_extras.stylable_container import stylable_container
7
 
8
+ # Securely get credentials
9
  generated_user = os.getenv("User")
10
  generated_password = os.getenv("Password")
11
  openai_key = os.getenv("openai_key")
12
 
13
+ # Streamlit page config
14
+ st.set_page_config(page_title="Carfind.co.za AI Assistant", layout="wide")
15
+ st.title("🚗 Carfind.co.za AI Assistant")
16
  st.caption("Chat with Carfind.co.za and find your next car fast")
17
 
18
  # Initialize authentication state
 
21
 
22
  # Login screen
23
  if not st.session_state.authenticated:
24
+ st.subheader("🔐 Login")
25
  username = st.text_input("Username")
26
  password = st.text_input("Password", type="password")
27
 
 
28
  if username and password:
29
  if username == generated_user and password == generated_password:
30
  st.session_state.authenticated = True
 
38
  else:
39
  st.divider()
40
 
 
41
  if "messages" not in st.session_state:
42
  st.session_state["messages"] = []
43
 
44
+ # Chat display with smooth scrolling
45
+ with stylable_container("chat-container", css="overflow-y: auto; height: 70vh; padding: 10px;"):
46
+ for message in st.session_state.messages:
47
+ with st.chat_message(message["role"]):
48
+ st.markdown(message["content"], unsafe_allow_html=True)
49
 
50
+ # Input row with Clear button as an icon
51
+ col_input, col_clear = st.columns([8, 1])
 
 
 
 
52
 
53
+ with col_input:
54
  user_input = st.chat_input("Type your message here...")
55
 
56
+ with col_clear:
57
+ if st.button("🗑️", help="Clear chat"):
58
+ st.session_state.messages = []
59
+ st.rerun()
60
+
61
  if openai_key:
62
  client = OpenAI(api_key=openai_key)
63
  ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
64
 
 
65
  def save_transcript(messages):
66
  with open("chat_logs.txt", "a") as log:
67
  log.write(f"\n--- New Chat ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n")
 
69
  log.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
70
  log.write("--- End Chat ---\n")
71
 
 
72
  if user_input:
73
  st.session_state.messages.append({"role": "user", "content": user_input})
74
+ with st.chat_message("user"):
75
+ st.markdown(user_input)
76
 
77
  try:
 
78
  thread = client.beta.threads.create()
79
  thread_id = thread.id
80
 
 
81
  client.beta.threads.messages.create(
82
  thread_id=thread_id,
83
  role="user",
84
  content=user_input
85
  )
86
 
 
87
  run = client.beta.threads.runs.create(
88
  thread_id=thread_id,
89
  assistant_id=ASSISTANT_ID
90
  )
91
 
 
92
  while True:
93
  run_status = client.beta.threads.runs.retrieve(
94
  thread_id=thread_id,
 
98
  break
99
  time.sleep(1)
100
 
 
101
  messages = client.beta.threads.messages.list(thread_id=thread_id)
102
  assistant_message = messages.data[0].content[0].text.value
103
 
 
 
104
  st.session_state.messages.append({"role": "assistant", "content": assistant_message})
105
 
106
+ with st.chat_message("assistant"):
107
+ st.markdown(assistant_message, unsafe_allow_html=True)
108
+
109
  save_transcript(st.session_state.messages)
110
 
111
  except Exception as e:
112
  st.error(f"An error occurred: {str(e)}")
113
+
114
  else:
115
  st.error("OpenAI key not found. Please ensure it is set as a Hugging Face secret.")