CoolFace
Apppublic

uxoxo/eb2ab

sourceHugging Faceapache-2.0updated 11mo agoView on Hugging Face
0likes
app_with_api.py142 linesDownload Raw Back to root
1"""2Unified entry point that runs both the Gradio UI and REST API on the same port.3This script creates a FastAPI app, mounts the REST API routes, and then mounts4the Gradio interface as a sub-application.5"""6 7import os8import sys9import argparse10from fastapi import FastAPI11from fastapi.middleware.cors import CORSMiddleware12import gradio as gr13 14# Add the current directory to the path for imports15sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))16 17# Import our REST API components18from api.routes import health, tts19from api.workers.tts_worker import start_worker20from api.storage import start_cleanup_thread21 22 23def create_unified_app():24    """25    Create a unified FastAPI app with both REST API and Gradio interface.26 27    Returns:28        FastAPI app with mounted routes and Gradio interface29    """30    # Create the main FastAPI app31    app = FastAPI(32        title="ebook2audiobook with REST API",33        description="Text-to-Speech conversion service with Gradio UI and REST API",34        version="1.0.0",35        docs_url="/api/v1/docs",36        redoc_url="/api/v1/redoc",37        openapi_url="/api/v1/openapi.json"38    )39 40    # Configure CORS41    cors_origins = os.environ.get("CORS_ORIGINS", "").split(",")42    cors_origins = [origin.strip() for origin in cors_origins if origin.strip()]43 44    if not cors_origins:45        cors_origins = ["*"]46        print("⚠️  CORS origins not configured. Allowing all origins.")47 48    app.add_middleware(49        CORSMiddleware,50        allow_origins=cors_origins,51        allow_credentials=True,52        allow_methods=["GET", "POST", "DELETE"],53        allow_headers=["Content-Type", "X-API-Key"],54    )55 56    # Mount REST API routes57    app.include_router(58        health.router,59        prefix="/api/v1",60        tags=["health"]61    )62    app.include_router(63        tts.router,64        prefix="/api/v1/tts",65        tags=["tts"]66    )67 68    # Start background workers69    print("🚀 Starting background workers...")70    start_worker()71    cleanup_interval = int(os.environ.get("CLEANUP_INTERVAL_SECONDS", "3600"))72    start_cleanup_thread(cleanup_interval)73 74    # Import and create the Gradio interface75    print("🎨 Creating Gradio interface...")76    from lib.functions import web_interface77 78    # Parse command line arguments for Gradio79    parser = argparse.ArgumentParser(description='ebook2audiobook with REST API')80    parser.add_argument('--share', action='store_true', help='Enable Gradio share link')81    parser.add_argument('--script_mode', default='full_docker', help='Script mode')82    parser.add_argument('--demo', action='store_true', help='Run in demo mode')83    parser.add_argument('--headless', action='store_true', help='Run headless (no GUI)')84 85    # Parse known args (ignore extras from uvicorn)86    args, unknown = parser.parse_known_args()87 88    # Create args dict for web_interface89    args_dict = {90        'script_mode': args.script_mode,91        'share': args.share,92        'is_gui_process': True,93    }94 95    # Create context for web_interface96    ctx = {}97 98    # The web_interface function creates and launches the Gradio app99    # We need to modify it to return the app instead of launching it100    # For now, we'll import app.py's main logic101 102    print("================================================================")103    print("           🚀 REST API + GRADIO UNIFIED SERVER")104    print("================================================================")105    print("  REST API endpoints:")106    print("  - Health: /api/v1/health")107    print("  - Test: /api/v1/test")108    print("  - Docs: /api/v1/docs")109    print("  - TTS Convert: /api/v1/tts/convert")110    print("  - TTS Status: /api/v1/tts/status/{job_id}")111    print("")112    print("  Gradio UI: / (root)")113    print("================================================================")114 115    return app116 117 118def main():119    """Main entry point"""120    import uvicorn121 122    # Get host and port from environment or defaults123    host = os.environ.get("API_HOST", "0.0.0.0")124    port = int(os.environ.get("API_PORT", "7860"))125 126    # Create the unified app127    app = create_unified_app()128 129    # For now, we need to run the original app.py which handles the Gradio interface130    # and we'll need to mount our API routes into it differently131    # Let's just import and run the original gradio app132    print("\n⚠️  Note: Running in hybrid mode - starting original Gradio app...")133    print("    API routes may not be available yet. Working on integration...\n")134 135    # Import and run the original app136    from app import main as app_main137    app_main()138 139 140if __name__ == "__main__":141    main()142