NCAkit / app.py
ismdrobiul489's picture
Test: Try gemma-3-27b-it model for chat
8f2ed57
"""
NCAkit - Neural Content Automation Toolkit
Main FastAPI Application with Modular Architecture
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import logging
from pathlib import Path
import sys
from config import config
from core.module_registry import registry
# Setup logging
logging.basicConfig(
level=config.log_level.upper(),
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler(sys.stdout)]
)
logger = logging.getLogger(__name__)
# Create FastAPI app
app = FastAPI(
title="NCAkit - Neural Content Automation Toolkit",
description="""
# NCAkit REST API
A modular toolkit for content automation with multiple feature modules.
## Available Modules
- 🎬 **Video Creator** - Create short-form videos with TTS, captions, and music
- 📱 More modules coming soon...
## How It Works
1. Each module has its own API prefix (e.g., `/api/video/`)
2. Modules are auto-discovered and registered on startup
3. Check `/api/modules` for list of available modules
""",
version="1.0.0",
contact={
"name": "NCAkit",
"url": "https://github.com/your-repo/ncakit"
}
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
async def startup_event():
"""Initialize all modules on startup"""
logger.info("Starting NCAkit...")
# Ensure directories exist
config.ensure_directories()
# Initialize HF Hub storage (optional)
if config.hf_repo:
from modules.shared.services.hf_storage import init_hf_storage
import os
hf_token = os.getenv("HF_TOKEN")
hf_storage = init_hf_storage(repo_id=config.hf_repo, token=hf_token)
if hf_storage.enabled:
logger.info(f"HF Cloud storage enabled: {config.hf_repo}")
else:
logger.warning("HF credentials set but storage failed to initialize")
# Register all modules
num_modules = registry.register_all(app, config)
logger.info(f"Loaded {num_modules} module(s)")
logger.info(f"NCAkit started successfully on port {config.port}")
@app.get("/health", tags=["System"])
async def health_check():
"""Health check endpoint"""
return {"status": "ok", "toolkit": "ncakit"}
@app.get("/api/modules", tags=["System"])
async def list_modules():
"""List all available modules"""
return {
"modules": registry.list_modules()
}
# ==========================================
# GEMINI CHATBOT TEST ENDPOINT
# ==========================================
from pydantic import BaseModel
import os
class ChatRequest(BaseModel):
message: str
@app.post("/api/chat", tags=["Chat"])
async def chat_with_gemini(request: ChatRequest):
"""
Test Gemini API connectivity.
Uses GEMINI_API_KEY from environment.
"""
try:
from google import genai
# Client gets API key from GEMINI_API_KEY environment variable
client = genai.Client()
response = client.models.generate_content(
model="gemma-3-27b-it",
contents=request.message
)
return {"reply": response.text}
except Exception as e:
logger.error(f"Gemini chat error: {e}")
return {"error": str(e)}
@app.get("/")
async def read_root():
"""Serve the web UI"""
static_path = Path(__file__).parent / "static" / "index.html"
if static_path.exists():
return FileResponse(static_path)
return {
"message": "NCAkit - Neural Content Automation Toolkit",
"docs": "/docs",
"modules": "/api/modules"
}
# Mount static files if they exist
static_dir = Path(__file__).parent / "static"
if static_dir.exists():
app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")
# Mount videos directory for direct access and streaming
videos_dir = config.videos_dir_path
if not videos_dir.exists():
videos_dir.mkdir(parents=True, exist_ok=True)
app.mount("/videos", StaticFiles(directory=str(videos_dir)), name="videos")
if __name__ == "__main__":
import uvicorn
uvicorn.run(
"app:app",
host="0.0.0.0",
port=config.port,
log_level=config.log_level.lower()
)