Arni1ntares commited on
Commit
d8a3500
Β·
verified Β·
1 Parent(s): 54fabc9

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +145 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,147 @@
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 os
 
 
2
  import streamlit as st
3
+ from transformers import pipeline
4
+ import datetime
5
+ import pyttsx3
6
+ import tempfile
7
+ import speech_recognition as sr
8
 
9
+ st.set_page_config(page_title="Winner Chat", layout="wide", initial_sidebar_state="expanded")
10
+
11
+ # Sidebar: Model selector + Dark mode
12
+ st.sidebar.title("βš™οΈ Settings")
13
+ model_name = st.sidebar.selectbox("Choose model", ["Arni1ntares/Winner", "gpt2", "distilgpt2"])
14
+ dark_mode = st.sidebar.toggle("πŸŒ™ Dark Mode")
15
+ enable_tts = st.sidebar.toggle("πŸ”Š Enable Voice Output")
16
+ enable_mic = st.sidebar.toggle("πŸŽ™οΈ Enable Voice Input")
17
+
18
+ # Voice recognizer
19
+ recognizer = sr.Recognizer()
20
+
21
+ @st.cache_resource(show_spinner="Loading model...")
22
+ def load_model(model_name):
23
+ return pipeline("text-generation", model=model_name)
24
+
25
+ pipe = load_model(model_name)
26
+
27
+ # Init TTS
28
+ tts = pyttsx3.init()
29
+ tts.setProperty('rate', 165)
30
+
31
+ # Custom CSS for message bubbles and dark mode
32
+ def add_css():
33
+ css = """
34
+ <style>
35
+ .user-msg {
36
+ background-color: #DCF8C6;
37
+ padding: 0.5em 1em;
38
+ border-radius: 10px;
39
+ margin: 0.3em 0;
40
+ }
41
+ .bot-msg {
42
+ background-color: #F1F0F0;
43
+ padding: 0.5em 1em;
44
+ border-radius: 10px;
45
+ margin: 0.3em 0;
46
+ }
47
+ .avatar {
48
+ width: 30px; height: 30px; border-radius: 50%;
49
+ display: inline-block; vertical-align: middle;
50
+ }
51
+ .msg-container {
52
+ display: flex;
53
+ align-items: flex-start;
54
+ gap: 10px;
55
+ }
56
+ .bubble-container {
57
+ max-width: 80%;
58
+ }
59
+ </style>
60
+ """
61
+ if dark_mode:
62
+ css += """
63
+ <style>
64
+ body {
65
+ background-color: #0e1117;
66
+ color: white;
67
+ }
68
+ .bot-msg {
69
+ background-color: #2c2f36;
70
+ color: white;
71
+ }
72
+ .user-msg {
73
+ background-color: #005c4b;
74
+ color: white;
75
+ }
76
+ </style>
77
+ """
78
+ st.markdown(css, unsafe_allow_html=True)
79
+
80
+ add_css()
81
+
82
+ st.title("πŸ€– Winner Chat – Enhanced UI")
83
+
84
+ # Init chat state
85
+ if "messages" not in st.session_state:
86
+ st.session_state.messages = []
87
+
88
+ # Display chat history
89
+ for msg in st.session_state.messages:
90
+ avatar = "πŸ§‘" if msg["role"] == "user" else "πŸ€–"
91
+ bubble_class = "user-msg" if msg["role"] == "user" else "bot-msg"
92
+ with st.container():
93
+ st.markdown(f"""
94
+ <div class="msg-container">
95
+ <div class="avatar">{avatar}</div>
96
+ <div class="bubble-container"><div class="{bubble_class}">{msg['content']}</div></div>
97
+ </div>
98
+ """, unsafe_allow_html=True)
99
+
100
+ # Voice input
101
+ user_input = ""
102
+ if enable_mic:
103
+ st.subheader("πŸŽ™οΈ Voice Input")
104
+ mic_button = st.button("Start Listening")
105
+ if mic_button:
106
+ with sr.Microphone() as source:
107
+ st.info("Listening...")
108
+ audio = recognizer.listen(source)
109
+ try:
110
+ user_input = recognizer.recognize_google(audio)
111
+ st.success(f"You said: {user_input}")
112
+ except Exception as e:
113
+ st.error(f"Error: {e}")
114
+ else:
115
+ user_input = st.chat_input("Type your message...")
116
+
117
+ if user_input:
118
+ # Save user input
119
+ st.session_state.messages.append({"role": "user", "content": user_input})
120
+
121
+ with st.spinner("Thinking..."):
122
+ full_prompt = "\n".join(
123
+ [f"{m['role']}: {m['content']}" for m in st.session_state.messages]
124
+ )
125
+ result = pipe(full_prompt, max_new_tokens=200, temperature=0.7)[0]["generated_text"]
126
+ response = result.replace(full_prompt, "").strip()
127
+
128
+ st.session_state.messages.append({"role": "assistant", "content": response})
129
+
130
+ if enable_tts:
131
+ tts.say(response)
132
+ tts.runAndWait()
133
+
134
+ st.experimental_rerun()
135
+
136
+ # Export conversation
137
+ st.sidebar.markdown("---")
138
+ if st.sidebar.button("πŸ“₯ Export Chat"):
139
+ now = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
140
+ fname = f"chat_{now}.txt"
141
+ text = "\n".join([f"{m['role']}: {m['content']}" for m in st.session_state.messages])
142
+ with tempfile.NamedTemporaryFile(delete=False, mode="w", suffix=".txt") as f:
143
+ f.write(text)
144
+ st.sidebar.download_button("Download Chat", text, file_name=fname, mime="text/plain")
145
+
146
+ st.markdown("---")
147
+ st.caption("πŸ›  Built with Streamlit, Hugging Face, and πŸ’› for AI.")