PARTHA181098 commited on
Commit
5286ac5
·
verified ·
1 Parent(s): 6c53029

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +77 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,79 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import uuid
3
+ import json
4
+ import asyncio
5
+ import websockets
6
 
7
+ MIDDLEWARE_WS = "https://huggingface.co/spaces/PARTHA181098/middleware:7860/chat"
8
+
9
+ st.set_page_config(page_title="Secure AI Chat")
10
+
11
+ ss = st.session_state
12
+
13
+ # ------------------ SESSION ------------------
14
+ def new_session():
15
+ ss.session_id = str(uuid.uuid4())
16
+ ss.messages = []
17
+
18
+ if "session_id" not in ss:
19
+ new_session()
20
+
21
+ if "messages" not in ss:
22
+ ss.messages = []
23
+
24
+ # ------------------ UI ------------------
25
+ st.title("🔐 Secure Database Chatbot")
26
+
27
+ if st.button("New Chat"):
28
+ new_session()
29
+ st.rerun()
30
+
31
+ for msg in ss.messages:
32
+ with st.chat_message(msg["role"]):
33
+ st.write(msg["content"])
34
+
35
+ user_input = st.chat_input("Ask something...")
36
+
37
+ # ------------------ WS CLIENT ------------------
38
+ async def send_and_receive(user_text):
39
+ async with websockets.connect(
40
+ f"{MIDDLEWARE_WS}?session_id={ss.session_id}"
41
+ ) as ws:
42
+
43
+ await ws.send(user_text)
44
+
45
+ assistant_msg = ""
46
+
47
+ while True:
48
+ data = await ws.recv()
49
+ payload = json.loads(data)
50
+
51
+ if payload["type"] == "security_warning":
52
+ st.warning(payload["message"])
53
+ return
54
+
55
+ if payload["type"] == "response":
56
+ assistant_msg += payload["content"]
57
+ yield assistant_msg
58
+
59
+ if payload["type"] == "complete":
60
+ break
61
+
62
+ # ------------------ CHAT FLOW ------------------
63
+ if user_input:
64
+ ss.messages.append({"role": "user", "content": user_input})
65
+ with st.chat_message("user"):
66
+ st.write(user_input)
67
+
68
+ with st.chat_message("assistant"):
69
+ placeholder = st.empty()
70
+ full_response = {"text": ""}
71
+
72
+ async def runner():
73
+ async for chunk in send_and_receive(user_input):
74
+ full_response["text"] = chunk
75
+ placeholder.markdown(full_response["text"])
76
+
77
+ asyncio.run(runner())
78
+
79
+ ss.messages.append({"role": "assistant", "content": full_response})