Spaces:
Sleeping
Sleeping
Commit Β·
714ebad
1
Parent(s): 9058a71
fix(runtime): Implement graceful shutdown and robust process management
Browse files7 unmodified lines89101112131415161718192021222324252620 unmodified lines474849505152535455561 unmodified line585960617 unmodified lines# --- CONFIGURATION ---RUN_INTERVAL_SECONDS = 30# --- NEW HELPER FUNCTION ---def live_countdown(duration_seconds: int):"""Displays a live, overwriting countdown in the terminal for the specified duration."""for i in range(duration_seconds, 0, -1):# The \r moves the cursor to the beginning of the line.# The end="" prevents print from adding a new line.# Padding with spaces ensures the previous line is fully overwritten.print(f"Next run in {i} seconds... \r", end="")time.sleep(1)# Print a blank line to clear the countdown text at the endprint(" " * 40, end="\r")async def main_loop():"""20 unmodified linesrun_analytics()print("Analytics engine run complete.")# --- Wait for the next run with a live countdown ---print(f"--- Pipeline run finished. ---")print("===========================================")live_countdown(RUN_INTERVAL_SECONDS) # <--- UPDATED CALLprint("-" * 30)1 unmodified linetry:asyncio.run(main_loop())except KeyboardInterrupt:print("\nπ Application shutting down. Goodbye!")7 unmodified lines8910111213141516171819202122232425262720 unmodified lines484950515253545556571 unmodified line59606162637 unmodified lines# --- CONFIGURATION ---RUN_INTERVAL_SECONDS = 30# --- NEW ASYNC HELPER FUNCTION ---async def live_countdown(duration_seconds: int):"""Displays a live, non-blocking countdown in the terminal."""for i in range(duration_seconds, 0, -1):print(f"Next run in {i} seconds... \r", end="")try:# Non-blocking sleepawait asyncio.sleep(1)except asyncio.CancelledError:# Allows clean cancellationbreakprint(" " * 40, end="\r") # Clear the countdown lineasync def main_loop():"""20 unmodified linesrun_analytics()print("Analytics engine run complete.")# --- Wait for the next run with a live async countdown ---print(f"--- Pipeline run finished. ---")print("===========================================")await live_countdown(RUN_INTERVAL_SECONDS) # <--- ASYNC CALLprint("-" * 30)1 unmodified linetry:asyncio.run(main_loop())except KeyboardInterrupt:# Instant shutdown now worksprint("\nπ Application shutting down gracefully. Goodbye!")
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# run.pyimport subprocessimport sysimport osimport signalimport atexit
bg_process = None
def cleanup(): """Ensure background process is terminated on script exit.""" global bg_process if bg_process and bg_process.poll() is None: print("\nπ Terminating background data pipeline...") # On Unix-like systems (like Hugging Face), os.kill is more reliable try: os.kill(bg_process.pid, signal.SIGTERM) bg_process.wait(timeout=5) except (ProcessLookupError, subprocess.TimeoutExpired): print("β οΈ Force killing background process...") bg_process.kill() print("β
Pipeline terminated.")
def run_command(command, description): """Runs a setup command and exits if it fails.""" print(f"π {description}...") # Use sys.executable to ensure we use the python from the correct venv result = subprocess.run([sys.executable, "-m", command], capture_output=True, text=True) if result.returncode != 0: print(f"β ERROR: {description} failed.") print(result.stderr) sys.exit(result.returncode) print(f"β
{description} complete.")
def main(): # Register the cleanup function to be called on any script exit atexit.register(cleanup)
# Initialize and Seed run_command("database.database_setup", "Initializing database") run_command("scripts.seed_db", "Seeding initial data")
# Start the background data pipeline print("π‘ Starting background data pipeline...") global bg_process bg_process = subprocess.Popen([sys.executable, "main.py"]) print(f"β
Data pipeline started with PID: {bg_process.pid}")
# Start the Streamlit app (this is the main blocking process) print("π Starting Streamlit dashboard...") # Note: Hugging Face uses port 7860 by default. 8501 is fine for local. subprocess.run(["streamlit", "run", "app.py", "--server.port", "8501", "--server.headless", "true"])
if __name__ == "__main__": main()1234567891011121314151617#!/bin/bash
# Step 1: Initialize the database structureecho "π Initializing database..."python database/database_setup.py
# Step 2: Seed the database with initial historical dataecho "π± Seeding initial data..."python scripts/seed_db.py
# Step 3: Start the background data pipelineecho "π‘ Starting data pipeline in the background..."python main.py &
# Step 4: Start the Streamlit app in the foregroundecho "π Starting Streamlit dashboard..."streamlit run app.py --server.port 7860main.py+14-12
run.pyAdded+55
run.shDeleted-17