ujwal55 commited on
Commit
72740e6
Β·
verified Β·
1 Parent(s): b6d5c35

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +92 -63
main.py CHANGED
@@ -2,9 +2,9 @@ import os
2
  import threading
3
  import uvicorn
4
  import subprocess
 
5
  import signal
6
  import sys
7
- import time
8
  from api import app as fastapi_app
9
 
10
  # Set environment variables for Streamlit
@@ -14,39 +14,66 @@ os.environ["STREAMLIT_SERVER_PORT"] = "8501"
14
  os.environ["STREAMLIT_SERVER_ADDRESS"] = "0.0.0.0"
15
  os.environ["STREAMLIT_GLOBAL_DISABLE_WATCHDOG_WARNING"] = "true"
16
 
17
- def run_fastapi():
18
- """Run FastAPI server"""
19
- # Get port from environment or use default
20
- fastapi_port = int(os.getenv('FASTAPI_PORT', 7861))
21
-
22
- # Try different ports if specified port is busy
23
- ports_to_try = [fastapi_port, 8000, 8080, 3000, 5000, 9000, 9001, 9002]
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
- for port in ports_to_try:
26
  try:
27
- print(f"πŸš€ Trying to start FastAPI on port {port}...")
28
- uvicorn.run(
29
- fastapi_app,
30
- host="0.0.0.0",
31
- port=port,
32
- log_level="info",
33
- access_log=False # Reduce log noise
34
- )
35
- break
36
- except OSError as e:
37
- if "Address already in use" in str(e):
38
- print(f"⚠️ Port {port} is busy, trying next...")
39
- continue
40
- else:
41
- print(f"❌ Error starting FastAPI on port {port}: {e}")
42
- continue
43
- else:
44
- print("❌ No available ports found for FastAPI!")
45
- sys.exit(1)
 
 
 
 
 
 
 
 
 
 
46
 
47
  def run_streamlit():
48
  """Run Streamlit app"""
49
  try:
 
 
 
 
50
  subprocess.run([
51
  "streamlit", "run", "app.py",
52
  "--server.port=8501",
@@ -55,57 +82,59 @@ def run_streamlit():
55
  "--global.disableWatchdogWarning=true",
56
  "--server.enableCORS=false",
57
  "--server.enableXsrfProtection=false",
58
- "--global.suppressDeprecationWarnings=true"
59
- ], check=True)
60
- except subprocess.CalledProcessError as e:
61
- print(f"❌ Error starting Streamlit: {e}")
62
- sys.exit(1)
63
-
64
- def signal_handler(signum, frame):
65
- """Handle shutdown signals"""
66
- print(f"\n⚠️ Received signal {signum}, shutting down services...")
67
- sys.exit(0)
68
 
69
  if __name__ == "__main__":
70
- # Set up signal handlers
71
  signal.signal(signal.SIGINT, signal_handler)
72
  signal.signal(signal.SIGTERM, signal_handler)
73
 
74
  print("πŸš€ Starting GitHub Activity Feed...")
75
- print("πŸ“‘ FastAPI webhook server will start on available port")
76
- print("πŸ–₯️ Streamlit dashboard will run on port 8501")
77
 
78
- # Add a small delay to prevent rapid restarts
79
- time.sleep(2)
80
-
81
- # Create threads for both services
82
- fastapi_thread = threading.Thread(target=run_fastapi, daemon=True, name="FastAPI")
83
- streamlit_thread = threading.Thread(target=run_streamlit, daemon=True, name="Streamlit")
84
-
85
- # Start FastAPI first
86
- fastapi_thread.start()
87
- time.sleep(3) # Give FastAPI time to start
88
 
89
- # Then start Streamlit
90
- streamlit_thread.start()
91
 
92
- print("βœ… Both services started successfully!")
93
-
94
- # Keep the main thread alive
95
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  while True:
97
  if not fastapi_thread.is_alive():
98
- print("❌ FastAPI thread died, restarting...")
99
- fastapi_thread = threading.Thread(target=run_fastapi, daemon=True, name="FastAPI")
100
  fastapi_thread.start()
101
 
102
  if not streamlit_thread.is_alive():
103
- print("❌ Streamlit thread died, restarting...")
104
- streamlit_thread = threading.Thread(target=run_streamlit, daemon=True, name="Streamlit")
105
  streamlit_thread.start()
106
 
107
- time.sleep(10) # Check every 10 seconds
108
 
109
  except KeyboardInterrupt:
110
- print("\n⚠️ Shutting down services...")
111
- sys.exit(0)
 
 
 
 
 
 
2
  import threading
3
  import uvicorn
4
  import subprocess
5
+ import time
6
  import signal
7
  import sys
 
8
  from api import app as fastapi_app
9
 
10
  # Set environment variables for Streamlit
 
14
  os.environ["STREAMLIT_SERVER_ADDRESS"] = "0.0.0.0"
15
  os.environ["STREAMLIT_GLOBAL_DISABLE_WATCHDOG_WARNING"] = "true"
16
 
17
+ # Global variables to track processes
18
+ fastapi_process = None
19
+ streamlit_process = None
20
+
21
+ def cleanup_processes():
22
+ """Clean up any existing processes"""
23
+ print("🧹 Cleaning up existing processes...")
24
+ os.system("pkill -f 'uvicorn'")
25
+ os.system("pkill -f 'streamlit'")
26
+ time.sleep(2)
27
+
28
+ def signal_handler(signum, frame):
29
+ """Handle shutdown signals"""
30
+ print(f"\n⚠️ Received signal {signum}, shutting down...")
31
+ cleanup_processes()
32
+ sys.exit(0)
33
+
34
+ def find_free_port(start_port, max_attempts=10):
35
+ """Find a free port starting from start_port"""
36
+ import socket
37
 
38
+ for port in range(start_port, start_port + max_attempts):
39
  try:
40
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
41
+ s.bind(('', port))
42
+ return port
43
+ except OSError:
44
+ continue
45
+ return None
46
+
47
+ def run_fastapi():
48
+ """Run FastAPI server"""
49
+ try:
50
+ # Find a free port for FastAPI
51
+ fastapi_port = find_free_port(7861)
52
+ if not fastapi_port:
53
+ fastapi_port = find_free_port(8000)
54
+
55
+ if not fastapi_port:
56
+ print("❌ No free ports found for FastAPI!")
57
+ return
58
+
59
+ print(f"πŸš€ Starting FastAPI on port {fastapi_port}...")
60
+ uvicorn.run(
61
+ fastapi_app,
62
+ host="0.0.0.0",
63
+ port=fastapi_port,
64
+ log_level="warning", # Reduce log verbosity
65
+ access_log=False
66
+ )
67
+ except Exception as e:
68
+ print(f"❌ FastAPI error: {e}")
69
 
70
  def run_streamlit():
71
  """Run Streamlit app"""
72
  try:
73
+ # Wait a bit for FastAPI to start
74
+ time.sleep(3)
75
+
76
+ print("πŸ–₯️ Starting Streamlit dashboard...")
77
  subprocess.run([
78
  "streamlit", "run", "app.py",
79
  "--server.port=8501",
 
82
  "--global.disableWatchdogWarning=true",
83
  "--server.enableCORS=false",
84
  "--server.enableXsrfProtection=false",
85
+ "--browser.gatherUsageStats=false"
86
+ ])
87
+ except Exception as e:
88
+ print(f"❌ Streamlit error: {e}")
 
 
 
 
 
 
89
 
90
  if __name__ == "__main__":
91
+ # Only set up signal handlers in main thread
92
  signal.signal(signal.SIGINT, signal_handler)
93
  signal.signal(signal.SIGTERM, signal_handler)
94
 
95
  print("πŸš€ Starting GitHub Activity Feed...")
 
 
96
 
97
+ # Clean up any existing processes first
98
+ cleanup_processes()
 
 
 
 
 
 
 
 
99
 
100
+ print("πŸ“‘ Starting FastAPI webhook server...")
101
+ print("πŸ–₯️ Starting Streamlit dashboard...")
102
 
 
 
 
103
  try:
104
+ # Create threads for both services
105
+ fastapi_thread = threading.Thread(target=run_fastapi, daemon=True)
106
+ streamlit_thread = threading.Thread(target=run_streamlit, daemon=True)
107
+
108
+ # Start FastAPI first
109
+ fastapi_thread.start()
110
+
111
+ # Wait a bit then start Streamlit
112
+ time.sleep(5)
113
+ streamlit_thread.start()
114
+
115
+ print("βœ… Both services started successfully!")
116
+ print("πŸ“‘ FastAPI webhook available")
117
+ print("πŸ–₯️ Streamlit dashboard available on port 8501")
118
+
119
+ # Keep the main thread alive and monitor services
120
  while True:
121
  if not fastapi_thread.is_alive():
122
+ print("⚠️ FastAPI thread died, restarting...")
123
+ fastapi_thread = threading.Thread(target=run_fastapi, daemon=True)
124
  fastapi_thread.start()
125
 
126
  if not streamlit_thread.is_alive():
127
+ print("⚠️ Streamlit thread died, restarting...")
128
+ streamlit_thread = threading.Thread(target=run_streamlit, daemon=True)
129
  streamlit_thread.start()
130
 
131
+ time.sleep(30) # Check every 30 seconds
132
 
133
  except KeyboardInterrupt:
134
+ print("\n⚠️ Received interrupt signal...")
135
+ cleanup_processes()
136
+ sys.exit(0)
137
+ except Exception as e:
138
+ print(f"❌ Unexpected error: {e}")
139
+ cleanup_processes()
140
+ sys.exit(1)