pandion commited on
Commit
e63aec6
Β·
verified Β·
1 Parent(s): 3a40c26

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -11
app.py CHANGED
@@ -136,23 +136,59 @@ def create_ephemeral_session(credentials: HTTPBasicCredentials = Depends(securit
136
  return data
137
 
138
  # Streamlit app
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  def start_token_server_once():
140
  if getattr(st.session_state, "_token_server_started", False):
141
  return
142
  st.session_state._token_server_started = True
143
 
144
  def _run():
145
- os.environ.setdefault("TOKEN_SERVER_PORT", "5050")
146
- uvicorn.run(
147
- app,
148
- host="0.0.0.0",
149
- port=int(os.getenv("TOKEN_SERVER_PORT", "5050")),
150
- log_level="warning",
151
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
 
153
  t = threading.Thread(target=_run, daemon=True)
154
  t.start()
155
 
 
 
 
 
 
 
 
 
 
156
  # Streamlit UI
157
  st.set_page_config(page_title="Catherine – Role-Play Voice Simulator", page_icon="🎀", layout="centered")
158
  st.title("Client Role-Play Voice Simulator (Catherine)")
@@ -166,9 +202,35 @@ missing_key = os.getenv("OPENAI_API_KEY") is None
166
  if missing_key:
167
  st.warning("Set environment variable OPENAI_API_KEY before starting.")
168
 
 
169
  start_token_server_once()
170
 
171
- # Embed the static client via iframe
172
- token_server_port = int(os.getenv("TOKEN_SERVER_PORT", "5050"))
173
- client_url = f"http://localhost:{token_server_port}/static/index.html"
174
- st.components.v1.iframe(client_url, height=760)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
  return data
137
 
138
  # Streamlit app
139
+ def find_available_port(start_port=5050, max_attempts=10):
140
+ """Find an available port starting from start_port"""
141
+ import socket
142
+
143
+ for port in range(start_port, start_port + max_attempts):
144
+ try:
145
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
146
+ s.bind(('0.0.0.0', port))
147
+ return port
148
+ except OSError:
149
+ continue
150
+ return None
151
+
152
  def start_token_server_once():
153
  if getattr(st.session_state, "_token_server_started", False):
154
  return
155
  st.session_state._token_server_started = True
156
 
157
  def _run():
158
+ # Find an available port
159
+ port = find_available_port(5050)
160
+ if port is None:
161
+ st.error("❌ No available ports found. Please close other applications using ports 5050-5059")
162
+ return
163
+
164
+ # Update the port in session state so the iframe uses the correct port
165
+ st.session_state.token_server_port = port
166
+
167
+ try:
168
+ uvicorn.run(
169
+ app,
170
+ host="0.0.0.0",
171
+ port=port,
172
+ log_level="warning",
173
+ )
174
+ except OSError as e:
175
+ if "address already in use" in str(e):
176
+ st.error(f"❌ Port {port} is already in use. Please close other applications or restart your browser.")
177
+ else:
178
+ st.error(f"❌ Server error: {e}")
179
 
180
  t = threading.Thread(target=_run, daemon=True)
181
  t.start()
182
 
183
+ def check_server_health(port):
184
+ """Check if the FastAPI server is running and healthy"""
185
+ try:
186
+ import requests
187
+ response = requests.get(f"http://localhost:{port}/health", timeout=1)
188
+ return response.status_code == 200
189
+ except:
190
+ return False
191
+
192
  # Streamlit UI
193
  st.set_page_config(page_title="Catherine – Role-Play Voice Simulator", page_icon="🎀", layout="centered")
194
  st.title("Client Role-Play Voice Simulator (Catherine)")
 
202
  if missing_key:
203
  st.warning("Set environment variable OPENAI_API_KEY before starting.")
204
 
205
+ # Start the server
206
  start_token_server_once()
207
 
208
+ # Get the port (either from session state or environment)
209
+ token_server_port = st.session_state.get("token_server_port", int(os.getenv("TOKEN_SERVER_PORT", "5050")))
210
+
211
+ # Use a placeholder while server starts
212
+ if "server_ready" not in st.session_state:
213
+ st.session_state.server_ready = False
214
+
215
+ # Check if server is ready
216
+ if not st.session_state.server_ready:
217
+ with st.spinner("Starting voice server..."):
218
+ import time
219
+ time.sleep(2) # Give server time to start
220
+ st.session_state.server_ready = check_server_health(token_server_port)
221
+
222
+ if st.session_state.server_ready:
223
+ # Server is ready, show the iframe
224
+ client_url = f"http://localhost:{token_server_port}/static/index.html"
225
+ st.components.v1.iframe(client_url, height=760)
226
+ else:
227
+ # Server not ready, show retry option
228
+ st.warning("Voice server is starting up...")
229
+ if st.button("πŸ”„ Retry Connection"):
230
+ st.session_state.server_ready = check_server_health(token_server_port)
231
+ st.rerun()
232
+
233
+ st.info("πŸ’‘ **Troubleshooting:** If this persists, try refreshing the page or running from command line: `streamlit run app.py`")
234
+
235
+ # Show port information for debugging
236
+ st.code(f"Trying to connect to port: {token_server_port}")