korupolujayanth2004 commited on
Commit
2527b07
Β·
1 Parent(s): a9bec9f

Update app.py

Browse files
Files changed (1) hide show
  1. frontend/app.py +26 -16
frontend/app.py CHANGED
@@ -4,24 +4,33 @@ import requests
4
  import uuid
5
  import codecs
6
  import time
 
7
 
8
- # === Page Configuration ===
 
 
 
 
9
  st.set_page_config(page_title="πŸ“„ Mario's Chat Kingdom", layout="centered")
10
  st.title("πŸ„ Chat with Mario πŸ€–")
11
 
12
- # === Session State Initialization ===
13
  # A unique ID for the current chat session, used to isolate data in the backend
14
  if "session_id" not in st.session_state:
15
  st.session_state.session_id = str(uuid.uuid4())
 
16
  # List to store the history of messages (user and assistant)
17
  if "chat_history" not in st.session_state:
18
  st.session_state.chat_history = []
 
19
  # List to store names of documents uploaded in the current session (for frontend display)
20
  if "uploaded_doc_names" not in st.session_state:
21
  st.session_state.uploaded_doc_names = []
 
22
  # Flag to track if we just reset the session
23
  if "session_reset" not in st.session_state:
24
  st.session_state.session_reset = False
 
25
  # Counter to force file uploader reset
26
  if "uploader_key" not in st.session_state:
27
  st.session_state.uploader_key = 0
@@ -33,7 +42,7 @@ def handle_end_chat():
33
  # Send a request to the FastAPI backend to delete session-specific data from Qdrant
34
  try:
35
  with st.spinner(f"🧹 Clearing data for session '{current_session_id}' from database..."):
36
- response = requests.post(f"http://localhost:8000/end_session?session_id={current_session_id}")
37
 
38
  if response.status_code == 200:
39
  st.success(f"βœ… Data for session '{current_session_id}' cleared from database. Wahoo!")
@@ -43,7 +52,7 @@ def handle_end_chat():
43
  st.error("❌ Mama mia! Could not connect to the backend server. Is it running? (Data might not have been cleared on backend)")
44
  except Exception as e:
45
  st.error(f"An unexpected error occurred during backend cleanup: {e}")
46
-
47
  # Reset frontend session state for a fresh start
48
  st.session_state.session_id = str(uuid.uuid4()) # Generate a completely new session ID
49
  st.session_state.chat_history = [] # Clear chat history
@@ -54,7 +63,7 @@ def handle_end_chat():
54
  # Rerun the app to update the UI and reflect the cleared state
55
  st.rerun()
56
 
57
- # === Document Upload Section ===
58
  st.subheader("πŸ“„ Upload a Document")
59
 
60
  # Use the uploader_key to force widget reset after session reset
@@ -77,7 +86,7 @@ if uploaded_file:
77
  }
78
  data = {"session_id": st.session_state.session_id}
79
  try:
80
- upload_response = requests.post("http://localhost:8000/upload_document", files=files, data=data)
81
  if upload_response.status_code == 200:
82
  st.success(f"βœ… Document '{uploaded_file.name}' uploaded and processed. It's-a me, ready!")
83
  # Add the document name to the session state for display
@@ -100,42 +109,43 @@ if st.session_state.uploaded_doc_names:
100
  st.write(f"- 🌟 {doc_name}")
101
  st.markdown("---")
102
 
103
- # === Chat History Display ===
104
  # Iterates through chat_history and displays messages
105
  for msg in st.session_state.chat_history:
106
  with st.chat_message(msg["role"]):
107
  label = "πŸ§‘β€πŸ’¬ **User:**" if msg["role"] == "user" else "πŸ„ **Mario:**"
108
  st.markdown(f"{label} {msg['content']}")
109
 
110
- # === Sidebar for Session Management ===
111
  with st.sidebar:
112
  st.markdown("### πŸ” Reset Session")
113
  st.write("Click below to clear all chat history and document data for this session!")
114
  if st.button("End Chat"):
115
  handle_end_chat() # Call the function to manage session reset
116
 
117
- # === Chat Input Box (Always at the bottom) ===
118
  question = st.chat_input("Ask Mario something...")
119
 
120
- # === Handle User Input and Get LLM Response ===
121
  if question:
122
  # Display user's question immediately
123
  st.chat_message("user").markdown(f"πŸ§‘β€πŸ’¬ **User:** {question}")
124
  st.session_state.chat_history.append({"role": "user", "content": question})
125
-
126
  with st.chat_message("assistant"):
127
  with st.spinner("πŸ€– Mario is thinking... Wahoo!"):
128
  try:
129
  # Make a GET request to the FastAPI /chat endpoint
130
- response = requests.get("http://localhost:8000/chat", params={
131
  "question": question,
132
  "session_id": st.session_state.session_id
133
  }, stream=True, timeout=180) # Increased timeout for potentially longer LLM responses
134
-
135
  # Process the streaming response from the backend
136
  decoder = codecs.getincrementaldecoder("utf-8")()
137
  full_response = ""
138
  placeholder = st.empty() # Placeholder for streaming text
 
139
  for chunk in response.iter_content(chunk_size=1):
140
  if chunk:
141
  token = decoder.decode(chunk)
@@ -143,14 +153,14 @@ if question:
143
  # Update the placeholder with the streamed text and a typing cursor
144
  placeholder.markdown(f"πŸ„ **Mario:** {full_response}β–Œ")
145
  time.sleep(0.02) # Small delay for typing effect
146
-
147
  # Display the final, complete response
148
  placeholder.markdown(f"πŸ„ **Mario:** {full_response}")
149
  st.session_state.chat_history.append({"role": "assistant", "content": full_response})
150
-
151
  except requests.exceptions.ConnectionError:
152
  st.error("❌ Bowser must have cut the connection! Could not connect to the backend server. Is it running?")
153
  except requests.exceptions.Timeout:
154
  st.error("⏳ Mario took too long to respond. The pipe timed out!")
155
  except Exception as e:
156
- st.error(f"An unexpected problem occurred while Mario was chatting: {e}")
 
4
  import uuid
5
  import codecs
6
  import time
7
+ import os
8
 
9
+ # = Configuration =
10
+ # Use environment variable for backend URL; fallback to localhost for local development
11
+ BACKEND_URL = os.getenv('BACKEND_URL', 'http://localhost:8000')
12
+
13
+ # = Page Configuration =
14
  st.set_page_config(page_title="πŸ“„ Mario's Chat Kingdom", layout="centered")
15
  st.title("πŸ„ Chat with Mario πŸ€–")
16
 
17
+ # = Session State Initialization =
18
  # A unique ID for the current chat session, used to isolate data in the backend
19
  if "session_id" not in st.session_state:
20
  st.session_state.session_id = str(uuid.uuid4())
21
+
22
  # List to store the history of messages (user and assistant)
23
  if "chat_history" not in st.session_state:
24
  st.session_state.chat_history = []
25
+
26
  # List to store names of documents uploaded in the current session (for frontend display)
27
  if "uploaded_doc_names" not in st.session_state:
28
  st.session_state.uploaded_doc_names = []
29
+
30
  # Flag to track if we just reset the session
31
  if "session_reset" not in st.session_state:
32
  st.session_state.session_reset = False
33
+
34
  # Counter to force file uploader reset
35
  if "uploader_key" not in st.session_state:
36
  st.session_state.uploader_key = 0
 
42
  # Send a request to the FastAPI backend to delete session-specific data from Qdrant
43
  try:
44
  with st.spinner(f"🧹 Clearing data for session '{current_session_id}' from database..."):
45
+ response = requests.post(f"{BACKEND_URL}/end_session?session_id={current_session_id}")
46
 
47
  if response.status_code == 200:
48
  st.success(f"βœ… Data for session '{current_session_id}' cleared from database. Wahoo!")
 
52
  st.error("❌ Mama mia! Could not connect to the backend server. Is it running? (Data might not have been cleared on backend)")
53
  except Exception as e:
54
  st.error(f"An unexpected error occurred during backend cleanup: {e}")
55
+
56
  # Reset frontend session state for a fresh start
57
  st.session_state.session_id = str(uuid.uuid4()) # Generate a completely new session ID
58
  st.session_state.chat_history = [] # Clear chat history
 
63
  # Rerun the app to update the UI and reflect the cleared state
64
  st.rerun()
65
 
66
+ # = Document Upload Section =
67
  st.subheader("πŸ“„ Upload a Document")
68
 
69
  # Use the uploader_key to force widget reset after session reset
 
86
  }
87
  data = {"session_id": st.session_state.session_id}
88
  try:
89
+ upload_response = requests.post(f"{BACKEND_URL}/upload_document", files=files, data=data)
90
  if upload_response.status_code == 200:
91
  st.success(f"βœ… Document '{uploaded_file.name}' uploaded and processed. It's-a me, ready!")
92
  # Add the document name to the session state for display
 
109
  st.write(f"- 🌟 {doc_name}")
110
  st.markdown("---")
111
 
112
+ # = Chat History Display =
113
  # Iterates through chat_history and displays messages
114
  for msg in st.session_state.chat_history:
115
  with st.chat_message(msg["role"]):
116
  label = "πŸ§‘β€πŸ’¬ **User:**" if msg["role"] == "user" else "πŸ„ **Mario:**"
117
  st.markdown(f"{label} {msg['content']}")
118
 
119
+ # = Sidebar for Session Management =
120
  with st.sidebar:
121
  st.markdown("### πŸ” Reset Session")
122
  st.write("Click below to clear all chat history and document data for this session!")
123
  if st.button("End Chat"):
124
  handle_end_chat() # Call the function to manage session reset
125
 
126
+ # = Chat Input Box (Always at the bottom) =
127
  question = st.chat_input("Ask Mario something...")
128
 
129
+ # = Handle User Input and Get LLM Response =
130
  if question:
131
  # Display user's question immediately
132
  st.chat_message("user").markdown(f"πŸ§‘β€πŸ’¬ **User:** {question}")
133
  st.session_state.chat_history.append({"role": "user", "content": question})
134
+
135
  with st.chat_message("assistant"):
136
  with st.spinner("πŸ€– Mario is thinking... Wahoo!"):
137
  try:
138
  # Make a GET request to the FastAPI /chat endpoint
139
+ response = requests.get(f"{BACKEND_URL}/chat", params={
140
  "question": question,
141
  "session_id": st.session_state.session_id
142
  }, stream=True, timeout=180) # Increased timeout for potentially longer LLM responses
143
+
144
  # Process the streaming response from the backend
145
  decoder = codecs.getincrementaldecoder("utf-8")()
146
  full_response = ""
147
  placeholder = st.empty() # Placeholder for streaming text
148
+
149
  for chunk in response.iter_content(chunk_size=1):
150
  if chunk:
151
  token = decoder.decode(chunk)
 
153
  # Update the placeholder with the streamed text and a typing cursor
154
  placeholder.markdown(f"πŸ„ **Mario:** {full_response}β–Œ")
155
  time.sleep(0.02) # Small delay for typing effect
156
+
157
  # Display the final, complete response
158
  placeholder.markdown(f"πŸ„ **Mario:** {full_response}")
159
  st.session_state.chat_history.append({"role": "assistant", "content": full_response})
160
+
161
  except requests.exceptions.ConnectionError:
162
  st.error("❌ Bowser must have cut the connection! Could not connect to the backend server. Is it running?")
163
  except requests.exceptions.Timeout:
164
  st.error("⏳ Mario took too long to respond. The pipe timed out!")
165
  except Exception as e:
166
+ st.error(f"An unexpected problem occurred while Mario was chatting: {e}")