Spaces:
Sleeping
Sleeping
""" | |
combined_app.py - A unified approach that runs both FastAPI and Streamlit in a single process. | |
This is specifically designed for Hugging Face Spaces deployments. | |
Uses lazy loading to avoid loading models during startup. | |
""" | |
import streamlit as st | |
import os | |
import sys | |
import threading | |
import time | |
from fastapi import FastAPI, Request | |
from fastapi.middleware.cors import CORSMiddleware | |
import uvicorn | |
import subprocess | |
# Use environment variable to determine if we're in Spaces | |
IS_SPACE = "SPACE_ID" in os.environ | |
# Import FastAPI app but avoid importing modules that load models | |
# This is critical to prevent infinite loops during deployment | |
os.environ["SKIP_MODEL_LOADING"] = "1" | |
# Now import the FastAPI app | |
from api_backend import app as fastapi_app | |
# Add a route for checking if the API is running | |
def api_status(): | |
return {"status": "API is running"} | |
def run_fastapi(): | |
"""Run the FastAPI app in a separate thread""" | |
port = int(os.getenv("API_PORT", 7860)) | |
# Start the FastAPI server | |
uvicorn.run(fastapi_app, host="0.0.0.0", port=port) | |
def run_streamlit(): | |
"""Run the Streamlit app as a subprocess""" | |
streamlit_cmd = [ | |
"streamlit", "run", "app.py", | |
"--server.port", "8501", | |
"--server.address", "0.0.0.0" | |
] | |
subprocess.run(streamlit_cmd) | |
def main(): | |
"""Main entry point for the combined app""" | |
print("Starting the combined FastAPI + Streamlit app...") | |
# Start FastAPI in a separate thread | |
fastapi_thread = threading.Thread(target=run_fastapi, daemon=True) | |
fastapi_thread.start() | |
# Give FastAPI a moment to start | |
time.sleep(2) | |
print("FastAPI started, now starting Streamlit...") | |
# Set environment variable for app.py to use the right API URL | |
os.environ["API_URL"] = "http://localhost:7860/process-image" | |
# Start Streamlit | |
run_streamlit() | |
if __name__ == "__main__": | |
main() |