108 lines
3.6 KiB
Python
108 lines
3.6 KiB
Python
from fastapi import FastAPI, Request, status
|
||
from fastapi.responses import JSONResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
from fastapi.middleware.cors import CORSMiddleware
|
||
from sqlalchemy.exc import SQLAlchemyError
|
||
import logging
|
||
|
||
from apiApp.config import APP_TITLE, APP_VERSION, API_V1_PREFIX, UPLOAD_FOLDER, DATABASE_URL, PORT, HOST
|
||
from apiApp.database import engine, Base
|
||
from apiApp.routers import audio_router, recognition_router
|
||
from apiApp.routers.ai_conclusion_router import ai_conclusion_router
|
||
from apiApp.routers.audio_files_router import audio_files_router
|
||
from apiApp.routers.audio_management_router import audio_management_router
|
||
from apiApp.routers.external_audio import router as external_audio_router
|
||
|
||
print("✅ audio_management_router imported successfully")
|
||
|
||
# Настройка логирования
|
||
logging.basicConfig(level=logging.INFO)
|
||
logger = logging.getLogger(__name__)
|
||
|
||
# Создание FastAPI приложения
|
||
app = FastAPI(
|
||
title=APP_TITLE,
|
||
version=APP_VERSION,
|
||
docs_url=f"{API_V1_PREFIX}/docs",
|
||
redoc_url=f"{API_V1_PREFIX}/redoc",
|
||
openapi_url=f"{API_V1_PREFIX}/openapi.json"
|
||
)
|
||
|
||
# CORS middleware
|
||
app.add_middleware(
|
||
CORSMiddleware,
|
||
allow_origins=["*"],
|
||
allow_credentials=True,
|
||
allow_methods=["*"],
|
||
allow_headers=["*"],
|
||
)
|
||
|
||
|
||
# Глобальный обработчик ошибок SQLAlchemy
|
||
@app.exception_handler(SQLAlchemyError)
|
||
async def sqlalchemy_exception_handler(request: Request, exc: SQLAlchemyError):
|
||
logger.error(f"Database error: {exc}")
|
||
return JSONResponse(
|
||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||
content={"detail": "Database error occurred"},
|
||
)
|
||
|
||
|
||
# Создание таблиц
|
||
@app.on_event("startup")
|
||
async def startup_event():
|
||
"""Создание таблиц при запуске приложения"""
|
||
try:
|
||
Base.metadata.create_all(bind=engine)
|
||
logger.info("✅ Database tables created successfully")
|
||
except Exception as e:
|
||
logger.error(f"Error creating database tables: {e}")
|
||
|
||
|
||
# Подключение routers
|
||
app.include_router(audio_router, prefix=API_V1_PREFIX, tags=["audio"])
|
||
app.include_router(recognition_router, prefix=API_V1_PREFIX, tags=["recognition"])
|
||
app.include_router(ai_conclusion_router, prefix=API_V1_PREFIX, tags=["ai_conclusion"])
|
||
app.include_router(audio_files_router, prefix=API_V1_PREFIX, tags=["audio_files"])
|
||
app.include_router(external_audio_router, prefix=API_V1_PREFIX)
|
||
# audio_management_router с префиксом /audio для логической структуры
|
||
print("📝 Registering audio_management_router...")
|
||
app.include_router(audio_management_router, prefix="/api", tags=["audio_management"])
|
||
print("✅ audio_management_router registered at /audio/*")
|
||
|
||
# Статические файлы (для загрузки аудио)
|
||
app.mount("/uploads", StaticFiles(directory=str(UPLOAD_FOLDER)), name="uploads")
|
||
|
||
|
||
@app.get("/")
|
||
async def root():
|
||
return {
|
||
"application": APP_TITLE,
|
||
"version": APP_VERSION,
|
||
"status": "running"
|
||
}
|
||
|
||
|
||
@app.get("/health")
|
||
async def health_check():
|
||
return {"status": "healthy"}
|
||
|
||
@app.get("/routes")
|
||
async def list_routes():
|
||
"""Отладка: список всех роутов"""
|
||
from fastapi.routing import APIRoute
|
||
routes = []
|
||
for route in app.routes:
|
||
if isinstance(route, APIRoute):
|
||
routes.append({
|
||
"path": route.path,
|
||
"methods": list(route.methods),
|
||
"name": route.name
|
||
})
|
||
return {"routes": routes}
|
||
|
||
|
||
if __name__ == "__main__":
|
||
import uvicorn
|
||
uvicorn.run(app, host=HOST, port=PORT)
|