awacke1 commited on
Commit
5f75059
Β·
verified Β·
1 Parent(s): da22973

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -91
app.py CHANGED
@@ -1,4 +1,4 @@
1
- import gradio as gr
2
  import asyncio
3
  import websockets
4
  import uuid
@@ -29,7 +29,7 @@ def get_node_name():
29
  """🎲 Spins the wheel of fate to name our node - a random alias or user pick! 🏷️"""
30
  parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
31
  parser.add_argument('--node-name', type=str, default=None, help='Name for this chat node')
32
- parser.add_argument('--port', type=int, default=7860, help='Port to run the Gradio interface on')
33
  args = parser.parse_args()
34
  return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
35
 
@@ -122,77 +122,49 @@ async def start_websocket_server(host='0.0.0.0', port=8765):
122
  return server
123
 
124
  # Chat interface maker - the stage builder for our chat extravaganza! 🎭🏟️
125
- def create_gradio_interface(initial_username):
126
  """πŸ–ŒοΈ Sets up the chat stage with live updates and name-switching flair! 🌟"""
127
- with gr.Blocks(title=f"Chat Node: {NODE_NAME}", css=".chat-box { font-family: monospace; background: #1e1e1e; color: #d4d4d4; padding: 10px; border-radius: 5px; }") as demo:
128
- # Shared state - the magic memory box all clients peek into! πŸͺ„πŸ“¦
129
- chat_state = gr.State(value=load_chat())
130
-
131
- gr.Markdown(f"# Chat Node: {NODE_NAME}")
132
- gr.Markdown("Chat live, switch names, and keep the party going! πŸŽ‰")
133
-
134
- with gr.Row():
135
- with gr.Column(scale=3):
136
- chat_display = gr.Code(label="Chat History", language="markdown", lines=15, elem_classes=["chat-box"])
137
- with gr.Column(scale=1):
138
- user_list = gr.Dropdown(
139
- label="Switch User",
140
- choices=get_user_list(chat_state.value),
141
- value=initial_username,
142
- allow_custom_value=True # Let the initial username stick! 🎯
143
- )
144
-
145
- with gr.Row():
146
- username_input = gr.Textbox(label="Your Name", value=initial_username)
147
- message_input = gr.Textbox(label="Message", placeholder="Type your epic line here! ✍️")
148
- send_button = gr.Button("Send πŸš€")
149
-
150
- # Chat updater - the wizard keeping the chat spell alive! πŸ§™β€β™‚οΈβœ¨
151
- def update_chat(username, message, current_chat):
152
- """🎩 Conjures a fresh chat view with your latest quip - abracadabra! πŸŽ‡"""
153
- if message.strip():
154
- save_chat_entry(username, message)
155
- new_chat = load_chat()
156
- return new_chat, get_user_list(new_chat)
157
-
158
- # Name switcher - the shapeshifter swapping your chat persona! πŸ¦Έβ€β™‚οΈπŸŽ­
159
- def switch_user(new_username, current_chat):
160
- """πŸ¦„ Transforms you into a new chat hero - new name, same game! πŸ†"""
161
- return new_username, current_chat, get_user_list(current_chat)
162
-
163
- # Live chat persistence - the timekeeper syncing the chat clock! β°πŸ”„
164
- async def persist_chat():
165
- """⏳ Keeps the chat tome in sync, scribbling updates every few ticks! πŸ“"""
166
- while True:
167
- await asyncio.sleep(5) # Persist every 5 seconds
168
- with open(CHAT_FILE, 'r') as f:
169
- current = f.read()
170
- chat_state.value = current
171
-
172
- # Hook up the magic! 🎣
173
- send_button.click(
174
- fn=update_chat,
175
- inputs=[username_input, message_input, chat_state],
176
- outputs=[chat_display, user_list]
177
- )
178
- message_input.submit(
179
- fn=update_chat,
180
- inputs=[username_input, message_input, chat_state],
181
- outputs=[chat_display, user_list]
182
- )
183
- user_list.change(
184
- fn=switch_user,
185
- inputs=[user_list, chat_state],
186
- outputs=[username_input, chat_display, user_list]
187
- )
188
-
189
- # Start with the latest chat vibes! 🎡
190
- demo.load(lambda: (load_chat(), get_user_list(load_chat())), None, [chat_display, user_list])
191
-
192
- # Kick off the persistence dance! πŸ’ƒ
193
- asyncio.create_task(persist_chat())
194
-
195
- return demo
196
 
197
  # Main event - the ringmaster kicking off the chat circus! πŸŽͺ🀑
198
  async def main():
@@ -202,27 +174,11 @@ async def main():
202
  await start_websocket_server()
203
 
204
  # Grab username from URL or roll the dice! 🎲
205
- initial_username = os.environ.get("QUERY_STRING", "").split("username=")[-1] if "username=" in os.environ.get("QUERY_STRING", "") else random.choice(FUN_USERNAMES)
 
206
  print(f"Welcoming {initial_username} to the chat bash!")
207
 
208
- interface = create_gradio_interface(initial_username)
209
-
210
- # URL param magic - the gatekeeper checking your VIP pass! 🎟️
211
- from starlette.middleware.base import BaseHTTPMiddleware
212
- class UsernameMiddleware(BaseHTTPMiddleware):
213
- async def dispatch(self, request, call_next):
214
- """πŸ”‘ Snags your name from the URL VIP list - exclusive entry! 🎩"""
215
- query_params = dict(request.query_params)
216
- if "username" in query_params and query_params["username"] in FUN_USERNAMES:
217
- global initial_username
218
- initial_username = query_params["username"]
219
- return await call_next(request)
220
-
221
- app = gr.routes.App.create_app(interface)
222
- app.add_middleware(UsernameMiddleware)
223
-
224
- import uvicorn
225
- await uvicorn.Server(uvicorn.Config(app, host="0.0.0.0", port=port)).serve()
226
 
227
  if __name__ == "__main__":
228
  asyncio.run(main())
 
1
+ import streamlit as st
2
  import asyncio
3
  import websockets
4
  import uuid
 
29
  """🎲 Spins the wheel of fate to name our node - a random alias or user pick! 🏷️"""
30
  parser = argparse.ArgumentParser(description='Start a chat node with a specific name')
31
  parser.add_argument('--node-name', type=str, default=None, help='Name for this chat node')
32
+ parser.add_argument('--port', type=int, default=8501, help='Port to run the Streamlit interface on') # Default Streamlit port
33
  args = parser.parse_args()
34
  return args.node_name or f"node-{uuid.uuid4().hex[:8]}", args.port
35
 
 
122
  return server
123
 
124
  # Chat interface maker - the stage builder for our chat extravaganza! 🎭🏟️
125
+ def create_streamlit_interface(initial_username):
126
  """πŸ–ŒοΈ Sets up the chat stage with live updates and name-switching flair! 🌟"""
127
+ # Custom CSS for a sleek chat box
128
+ st.markdown("""
129
+ <style>
130
+ .chat-box {
131
+ font-family: monospace;
132
+ background: #1e1e1e;
133
+ color: #d4d4d4;
134
+ padding: 10px;
135
+ border-radius: 5px;
136
+ height: 400px;
137
+ overflow-y: auto;
138
+ }
139
+ </style>
140
+ """, unsafe_allow_html=True)
141
+
142
+ # Title and intro
143
+ st.title(f"Chat Node: {NODE_NAME}")
144
+ st.markdown("Chat live, switch names, and keep the party going! πŸŽ‰")
145
+
146
+ # Session state to persist username
147
+ if 'username' not in st.session_state:
148
+ st.session_state.username = initial_username
149
+
150
+ # Chat display
151
+ chat_content = load_chat()
152
+ st.markdown(f"<div class='chat-box'>{chat_content}</div>", unsafe_allow_html=True)
153
+
154
+ # User switcher
155
+ user_list = get_user_list(chat_content)
156
+ new_username = st.selectbox("Switch User", user_list + [st.session_state.username], index=len(user_list))
157
+ if new_username != st.session_state.username:
158
+ st.session_state.username = new_username
159
+
160
+ # Message input and send
161
+ message = st.text_input("Message", placeholder="Type your epic line here! ✍️")
162
+ if st.button("Send πŸš€") and message.strip():
163
+ save_chat_entry(st.session_state.username, message)
164
+ st.rerun() # Trigger a rerun to refresh the chat
165
+
166
+ # Auto-refresh every second for live updates
167
+ st.markdown("<script>window.setTimeout(() => window.location.reload(), 1000);</script>", unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
168
 
169
  # Main event - the ringmaster kicking off the chat circus! πŸŽͺ🀑
170
  async def main():
 
174
  await start_websocket_server()
175
 
176
  # Grab username from URL or roll the dice! 🎲
177
+ query_params = st.query_params if hasattr(st, 'query_params') else {} # Streamlit 1.20+ syntax
178
+ initial_username = query_params.get("username", random.choice(FUN_USERNAMES)) if query_params else random.choice(FUN_USERNAMES)
179
  print(f"Welcoming {initial_username} to the chat bash!")
180
 
181
+ create_streamlit_interface(initial_username)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
182
 
183
  if __name__ == "__main__":
184
  asyncio.run(main())