IAMTFRMZA commited on
Commit
fb4fbbe
ยท
verified ยท
1 Parent(s): 9447cb8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +77 -43
app.py CHANGED
@@ -10,11 +10,44 @@ generated_user = os.getenv("User")
10
  generated_password = os.getenv("Password")
11
  openai_key = os.getenv("openai_key")
12
 
13
- # Streamlit app configuration
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
19
  if "authenticated" not in st.session_state:
20
  st.session_state.authenticated = False
@@ -41,11 +74,11 @@ else:
41
 
42
  st.divider()
43
 
44
- # Display chat history
45
  for i, msg in enumerate(st.session_state["messages"]):
46
- message(msg["content"], is_user=(msg["role"] == "user"), key=str(i))
 
47
 
48
- # Chat input with clear chat icon
49
  col_input, col_clear = st.columns([10, 1])
50
 
51
  with col_input:
@@ -54,56 +87,57 @@ else:
54
  with col_clear:
55
  if st.button("๐Ÿ—‘๏ธ", help="Clear chat"):
56
  st.session_state.messages = []
57
- st.experimental_rerun()
58
 
59
  # Handle OpenAI assistant
60
  if user_input and openai_key:
61
  st.session_state.messages.append({"role": "user", "content": user_input})
62
 
63
- client = OpenAI(api_key=openai_key)
64
- ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
65
-
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")
69
- for msg in messages:
70
- log.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
71
- log.write("--- End Chat ---\n")
72
-
73
- try:
74
- thread = client.beta.threads.create()
75
- thread_id = thread.id
76
-
77
- client.beta.threads.messages.create(
78
- thread_id=thread_id,
79
- role="user",
80
- content=user_input
81
- )
82
-
83
- run = client.beta.threads.runs.create(
84
- thread_id=thread_id,
85
- assistant_id=ASSISTANT_ID
86
- )
87
-
88
- while True:
89
- run_status = client.beta.threads.runs.retrieve(
90
  thread_id=thread_id,
91
- run_id=run.id
92
  )
93
- if run_status.status == "completed":
94
- break
95
- time.sleep(1)
96
 
97
- messages_response = client.beta.threads.messages.list(thread_id=thread_id)
98
- assistant_reply = messages_response.data[0].content[0].text.value
 
 
 
 
 
 
 
 
 
99
 
100
- st.session_state.messages.append({"role": "assistant", "content": assistant_reply})
101
- save_transcript(st.session_state.messages)
102
 
103
- st.experimental_rerun()
104
 
105
- except Exception as e:
106
- st.error(f"An error occurred: {str(e)}")
107
 
108
  elif not openai_key:
109
  st.error("OpenAI key not found. Please ensure it is set as a Hugging Face secret.")
 
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
+ # Theme toggle
19
+ if "theme" not in st.session_state:
20
+ st.session_state.theme = "dark"
21
+
22
+ toggle = st.toggle("Switch to Light Mode")
23
+ if toggle:
24
+ st.session_state.theme = "light"
25
+ else:
26
+ st.session_state.theme = "dark"
27
+
28
+ if st.session_state.theme == "light":
29
+ st.markdown(
30
+ """
31
+ <style>
32
+ body { background-color: #f0f0f0; color: #000; }
33
+ .chat-bubble-user { background-color: #d1e7dd; color: #000; }
34
+ .chat-bubble-assistant { background-color: #f8d7da; color: #000; }
35
+ </style>
36
+ """,
37
+ unsafe_allow_html=True
38
+ )
39
+ else:
40
+ st.markdown(
41
+ """
42
+ <style>
43
+ body { background-color: #0e0e0e; color: #fff; }
44
+ .chat-bubble-user { background-color: #004085; color: #fff; }
45
+ .chat-bubble-assistant { background-color: #155724; color: #fff; }
46
+ </style>
47
+ """,
48
+ unsafe_allow_html=True
49
+ )
50
+
51
  # Initialize authentication state
52
  if "authenticated" not in st.session_state:
53
  st.session_state.authenticated = False
 
74
 
75
  st.divider()
76
 
77
+ # Display chat history with colored bubbles
78
  for i, msg in enumerate(st.session_state["messages"]):
79
+ bubble_class = "chat-bubble-user" if msg["role"] == "user" else "chat-bubble-assistant"
80
+ message(msg["content"], is_user=(msg["role"] == "user"), key=str(i), avatar_style="adventurer")
81
 
 
82
  col_input, col_clear = st.columns([10, 1])
83
 
84
  with col_input:
 
87
  with col_clear:
88
  if st.button("๐Ÿ—‘๏ธ", help="Clear chat"):
89
  st.session_state.messages = []
90
+ st.rerun()
91
 
92
  # Handle OpenAI assistant
93
  if user_input and openai_key:
94
  st.session_state.messages.append({"role": "user", "content": user_input})
95
 
96
+ with st.spinner("Thinking and typing... ๐Ÿ’ฌ"):
97
+ client = OpenAI(api_key=openai_key)
98
+ ASSISTANT_ID = "asst_5gQR21fOsmHil11FGBzEArA7"
99
+
100
+ def save_transcript(messages):
101
+ with open("chat_logs.txt", "a") as log:
102
+ log.write(f"\n--- New Chat ({datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}) ---\n")
103
+ for msg in messages:
104
+ log.write(f"{msg['role'].capitalize()}: {msg['content']}\n")
105
+ log.write("--- End Chat ---\n")
106
+
107
+ try:
108
+ thread = client.beta.threads.create()
109
+ thread_id = thread.id
110
+
111
+ client.beta.threads.messages.create(
112
+ thread_id=thread_id,
113
+ role="user",
114
+ content=user_input
115
+ )
116
+
117
+ run = client.beta.threads.runs.create(
 
 
 
 
 
118
  thread_id=thread_id,
119
+ assistant_id=ASSISTANT_ID
120
  )
 
 
 
121
 
122
+ while True:
123
+ run_status = client.beta.threads.runs.retrieve(
124
+ thread_id=thread_id,
125
+ run_id=run.id
126
+ )
127
+ if run_status.status == "completed":
128
+ break
129
+ time.sleep(1)
130
+
131
+ messages_response = client.beta.threads.messages.list(thread_id=thread_id)
132
+ assistant_reply = messages_response.data[0].content[0].text.value
133
 
134
+ st.session_state.messages.append({"role": "assistant", "content": assistant_reply})
135
+ save_transcript(st.session_state.messages)
136
 
137
+ st.rerun()
138
 
139
+ except Exception as e:
140
+ st.error(f"An error occurred: {str(e)}")
141
 
142
  elif not openai_key:
143
  st.error("OpenAI key not found. Please ensure it is set as a Hugging Face secret.")