PARTHA181098 commited on
Commit
afc62f4
·
verified ·
1 Parent(s): 6be32d9

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +118 -18
src/streamlit_app.py CHANGED
@@ -1,8 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  import uuid
3
  import json
4
  import asyncio
5
  import websockets
 
 
 
6
 
7
  # ================= CONFIG =================
8
  MIDDLEWARE_WS = "wss://partha181098-middleware.hf.space/chat"
@@ -40,38 +125,54 @@ user_input = st.chat_input("Ask something...")
40
  async def ws_stream(user_text, placeholder):
41
  uri = f"{MIDDLEWARE_WS}?session_id={ss.session_id}"
42
 
43
- async with websockets.connect(uri) as ws:
44
- await ws.send(user_text)
45
 
46
- full_response = ""
 
 
47
 
48
- while True:
49
- raw = await ws.recv()
50
- payload = json.loads(raw)
 
 
51
 
52
- if payload["type"] == "security_warning":
53
- st.warning(payload["message"])
54
- return None
55
 
56
- if payload["type"] == "response":
57
- full_response += payload["content"]
58
- placeholder.markdown(full_response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- if payload["type"] == "complete":
61
- return full_response
62
 
63
  # ================= CHAT FLOW =================
64
  if user_input:
65
- # Store user message
66
  ss.messages.append({"role": "user", "content": user_input})
 
67
  with st.chat_message("user"):
68
  st.markdown(user_input)
69
 
70
  with st.chat_message("assistant"):
71
  placeholder = st.empty()
72
 
73
- # IMPORTANT: Streamlit-safe asyncio execution
74
- response = asyncio.new_event_loop().run_until_complete(
75
  ws_stream(user_input, placeholder)
76
  )
77
 
@@ -79,4 +180,3 @@ if user_input:
79
  ss.messages.append(
80
  {"role": "assistant", "content": response}
81
  )
82
-
 
1
+ # import streamlit as st
2
+ # import uuid
3
+ # import json
4
+ # import asyncio
5
+ # import websockets
6
+
7
+ # # ================= CONFIG =================
8
+ # MIDDLEWARE_WS = "wss://partha181098-middleware.hf.space/chat"
9
+
10
+ # st.set_page_config(page_title="Secure AI Chat", layout="centered")
11
+
12
+ # ss = st.session_state
13
+
14
+ # # ================= SESSION =================
15
+ # def new_session():
16
+ # ss.session_id = str(uuid.uuid4())
17
+ # ss.messages = []
18
+
19
+ # if "session_id" not in ss:
20
+ # new_session()
21
+
22
+ # if "messages" not in ss:
23
+ # ss.messages = []
24
+
25
+ # # ================= UI =================
26
+ # st.title("🔐 Secure AI Chatbot")
27
+
28
+ # if st.button("New Chat"):
29
+ # new_session()
30
+ # st.rerun()
31
+
32
+ # # Show chat history
33
+ # for msg in ss.messages:
34
+ # with st.chat_message(msg["role"]):
35
+ # st.markdown(msg["content"])
36
+
37
+ # user_input = st.chat_input("Ask something...")
38
+
39
+ # # ================= STREAM HANDLER =================
40
+ # async def ws_stream(user_text, placeholder):
41
+ # uri = f"{MIDDLEWARE_WS}?session_id={ss.session_id}"
42
+
43
+ # async with websockets.connect(uri) as ws:
44
+ # await ws.send(user_text)
45
+
46
+ # full_response = ""
47
+
48
+ # while True:
49
+ # raw = await ws.recv()
50
+ # payload = json.loads(raw)
51
+
52
+ # if payload["type"] == "security_warning":
53
+ # st.warning(payload["message"])
54
+ # return None
55
+
56
+ # if payload["type"] == "response":
57
+ # full_response += payload["content"]
58
+ # placeholder.markdown(full_response)
59
+
60
+ # if payload["type"] == "complete":
61
+ # return full_response
62
+
63
+ # # ================= CHAT FLOW =================
64
+ # if user_input:
65
+ # # Store user message
66
+ # ss.messages.append({"role": "user", "content": user_input})
67
+ # with st.chat_message("user"):
68
+ # st.markdown(user_input)
69
+
70
+ # with st.chat_message("assistant"):
71
+ # placeholder = st.empty()
72
+
73
+ # # IMPORTANT: Streamlit-safe asyncio execution
74
+ # response = asyncio.new_event_loop().run_until_complete(
75
+ # ws_stream(user_input, placeholder)
76
+ # )
77
+
78
+ # if response:
79
+ # ss.messages.append(
80
+ # {"role": "assistant", "content": response}
81
+ # )
82
+
83
  import streamlit as st
84
  import uuid
85
  import json
86
  import asyncio
87
  import websockets
88
+ import nest_asyncio
89
+
90
+ nest_asyncio.apply()
91
 
92
  # ================= CONFIG =================
93
  MIDDLEWARE_WS = "wss://partha181098-middleware.hf.space/chat"
 
125
  async def ws_stream(user_text, placeholder):
126
  uri = f"{MIDDLEWARE_WS}?session_id={ss.session_id}"
127
 
128
+ full_response = ""
 
129
 
130
+ try:
131
+ async with websockets.connect(uri) as ws:
132
+ await ws.send(user_text)
133
 
134
+ while True:
135
+ try:
136
+ raw = await ws.recv()
137
+ except websockets.exceptions.ConnectionClosed:
138
+ break
139
 
140
+ payload = json.loads(raw)
 
 
141
 
142
+ if payload["type"] == "ping":
143
+ continue
144
+
145
+ if payload["type"] == "security_warning":
146
+ st.warning(payload["message"])
147
+ return None
148
+
149
+ if payload["type"] == "response":
150
+ full_response += payload["content"]
151
+ placeholder.markdown(full_response)
152
+
153
+ if payload["type"] == "complete":
154
+ return full_response
155
+
156
+ if payload["type"] == "error":
157
+ st.error(payload["message"])
158
+ return None
159
+
160
+ except Exception as e:
161
+ st.error(f"WebSocket error: {e}")
162
+ return None
163
 
 
 
164
 
165
  # ================= CHAT FLOW =================
166
  if user_input:
 
167
  ss.messages.append({"role": "user", "content": user_input})
168
+
169
  with st.chat_message("user"):
170
  st.markdown(user_input)
171
 
172
  with st.chat_message("assistant"):
173
  placeholder = st.empty()
174
 
175
+ response = asyncio.get_event_loop().run_until_complete(
 
176
  ws_stream(user_input, placeholder)
177
  )
178
 
 
180
  ss.messages.append(
181
  {"role": "assistant", "content": response}
182
  )