File size: 3,556 Bytes
12832d8
b10856a
 
f6b1e89
12832d8
b10856a
 
cfdd7b3
e627b57
6fdf170
 
385aed6
bfa2a8d
c3bf14b
 
d8f52d8
 
 
 
78be6d7
d8f52d8
 
 
78be6d7
 
 
 
d8f52d8
 
78be6d7
 
 
 
d8f52d8
78be6d7
d8f52d8
 
 
 
 
 
12832d8
34caeeb
 
 
 
6fdf170
 
 
78be6d7
6fdf170
29f5dfb
f6b1e89
 
 
 
 
 
 
 
 
 
 
fb62834
385aed6
78be6d7
fb62834
6fdf170
ee25b7a
12832d8
b10856a
 
 
 
78be6d7
a50f65d
78be6d7
 
a50f65d
78be6d7
 
a50f65d
78be6d7
b10856a
 
78be6d7
 
 
 
b10856a
78be6d7
 
bfa2a8d
78be6d7
 
bfa2a8d
78be6d7
 
 
 
 
 
 
b10856a
12832d8
78be6d7
b10856a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
import os
from pathlib import Path
import mimetypes

from utils import log
from chat_handler import router as chat_router  # ← start_session & chat
from admin_routes import router as admin_router, start_cleanup_task
from spark_startup import run_in_thread
from session import session_store, start_session_cleanup

from config_provider import ConfigProvider

# ===================== Environment Setup =====================
def setup_environment():
    """Setup environment based on deployment"""
    cfg = ConfigProvider.get()
    
    log("=" * 60)
    log(f"πŸš€ Flare Starting")
    log(f"πŸ€– LLM Provider: {cfg.global_config.llm_provider.name}")
    log(f"πŸ”Š TTS Provider: {cfg.global_config.tts_provider.name}")
    log(f"🎀 STT Provider: {cfg.global_config.stt_provider.name}")
    log("=" * 60)
    
    # Check if running in HuggingFace Space
    if os.environ.get("SPACE_ID"):
        log("☁️  Running in HuggingFace Space")
        log("πŸ“Œ Using environment secrets for API keys")
    else:
        log("🏒 Local/On-Premise deployment")
        if not Path(".env").exists():
            log("⚠️  WARNING: .env file not found!")
            log("πŸ“Œ Copy .env.example to .env and configure it")

# Run setup
setup_environment()

# Fix MIME types for JavaScript files
mimetypes.add_type("application/javascript", ".js")
mimetypes.add_type("text/css", ".css")

app = FastAPI(
    title="Flare Orchestration Service",
    version="0.1.0",
    description="LLM-driven intent & API flow engine",
)

# CORS for development
if os.getenv("ENVIRONMENT") == "development":
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["http://localhost:4200"],  # Angular dev server
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    log("πŸ”§ CORS enabled for development")
    
run_in_thread()
start_cleanup_task()  # Activity log cleanup
start_session_cleanup()  # Session cleanup

# ---------------- Core chat/session routes --------------------------
app.include_router(chat_router, prefix="/api")

# ---------------- Admin API routes ----------------------------------
app.include_router(admin_router)

# ---------------- Serve Angular UI if exists ------------------------
ui_path = Path(__file__).parent / "ui" / "dist" / "flare-ui"

if ui_path.exists():
    log(f"πŸ“ Serving UI from: {ui_path}")
    
    # Serve static files
    app.mount("/assets", StaticFiles(directory=ui_path / "assets"), name="assets")
    
    # Catch-all route for Angular routing
    @app.get("/{full_path:path}")
    async def serve_angular(full_path: str):
        """Serve Angular app for all non-API routes"""
        # Skip API routes
        if full_path.startswith("api/"):
            return {"error": "API endpoint not found"}
        
        # Serve index.html for all routes (Angular will handle routing)
        return FileResponse(ui_path / "index.html")
else:
    log("⚠️  UI not found - only API endpoints available")
    
    @app.get("/")
    def root():
        return {
            "service": "Flare Orchestration Service",
            "version": "0.1.0",
            "status": "running",
            "ui": "not available - build Angular UI first"
        }

if __name__ == "__main__":
    log("🌐 Starting Flare backend on port 7860...")
    uvicorn.run(app, host="0.0.0.0", port=7860)