Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, HTTPException, Request | |
| from fastapi.responses import JSONResponse | |
| import logging | |
| import os | |
| from typing import List | |
| from LoadBalancer import LoadBalancer | |
| from utils import is_valid_url | |
| CACHE_DIR = os.getenv("CACHE_DIR") | |
| TOKEN = os.getenv("TOKEN") | |
| REPO = os.getenv("REPO") | |
| app = FastAPI() | |
| async def startup_event(): | |
| global load_balancer | |
| load_balancer = LoadBalancer(cache_dir=CACHE_DIR, token=TOKEN, repo=REPO) | |
| def greet_json(): | |
| return {"Version": load_balancer.version} | |
| async def register_instance(request: Request): | |
| try: | |
| data = await request.json() | |
| if not data or "url" not in data: | |
| return JSONResponse(content={"error": "No URL provided"}, status_code=400) | |
| url = data["url"] | |
| if not is_valid_url(url): | |
| return JSONResponse(content={"error": "Invalid URL"}, status_code=400) | |
| # Register the instance | |
| load_balancer.register_instance(url) | |
| logging.info(f"Instance registered: {url}") | |
| return JSONResponse(content={"message": f"Instance {url} registered successfully"}, status_code=200) | |
| except Exception as e: | |
| logging.error(f"Error registering instance: {e}") | |
| return JSONResponse(content={"error": "Failed to register instance"}, status_code=500) | |
| async def get_file_structure(): | |
| return load_balancer.file_structure | |
| async def get_music_store(): | |
| return load_balancer.MUSIC_STORE | |
| async def get_all_music_api(): | |
| return load_balancer.get_all_music() | |
| async def get_instances(): | |
| return load_balancer.instances | |
| async def get_instances_health(): | |
| return load_balancer.instances_health | |
| async def get_music_api(file_name: str): | |
| """Endpoint to get the music file by title.""" | |
| if not file_name: | |
| raise HTTPException(status_code=400, detail="file_name parameter is required") | |
| # Check if the music file is already cached | |
| if file_name in load_balancer.MUSIC_STORE: | |
| url = load_balancer.MUSIC_STORE[file_name] | |
| return JSONResponse(content={"url": url}) | |
| music_path = load_balancer.find_music_path(file_name) | |
| if not music_path: | |
| raise HTTPException(status_code=404, detail="Music file not found") | |
| # Start the download in an instance | |
| response = load_balancer.download_music_to_best_instance(file_name=file_name) | |
| if response: | |
| return JSONResponse(content=response) | |