auranexus / main.py
Ahmed766's picture
Upload main.py with huggingface_hub
a6f41e6 verified
from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Optional, List
import uuid
from datetime import datetime
import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from core.ai_gateway import AIGateway, ModelProvider
from core.security import get_current_user, create_access_token, get_password_hash, verify_password
from database.models import User, ContentItem, ScheduledPost
from database.session import get_db
from services.content_studio import ContentStudioService
from utils.text_processing import optimize_content, extract_keywords
app = FastAPI(
title="AuraNexus AI Content Orchestration Platform",
description="Open-source platform for AI-powered content creation and distribution",
version="0.1.0"
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize services
ai_gateway = AIGateway()
content_studio = ContentStudioService(ai_gateway)
class Token(BaseModel):
access_token: str
token_type: str
class TokenData(BaseModel):
username: Optional[str] = None
class UserCreate(BaseModel):
username: str
email: str
password: str
class UserOut(BaseModel):
id: str
username: str
email: str
created_at: datetime
class ContentGenerationRequest(BaseModel):
topic: str
content_type: str
platform: str
provider: Optional[ModelProvider] = ModelProvider.LOCAL_LLAMA
class ContentGenerationResponse(BaseModel):
id: str
title: str
content_type: str
generated_content: str
platform_specific_variants: dict
tags: List[str]
created_at: datetime
class OptimizationRequest(BaseModel):
content_id: str
optimization_type: str
@app.on_event("startup")
def startup_event():
from database.models import create_tables
create_tables()
@app.get("/")
async def root():
return {"message": "Welcome to AuraNexus AI Content Orchestration Platform"}
@app.post("/api/v1/auth/register", response_model=UserOut)
async def register(user: UserCreate, db=Depends(get_db)):
# Check if user already exists
existing_user = db.query(User).filter(User.username == user.username).first()
if existing_user:
raise HTTPException(status_code=400, detail="Username already registered")
existing_email = db.query(User).filter(User.email == user.email).first()
if existing_email:
raise HTTPException(status_code=400, detail="Email already registered")
# Create new user
hashed_password = get_password_hash(user.password)
db_user = User(
username=user.username,
email=user.email,
hashed_password=hashed_password
)
db.add(db_user)
db.commit()
db.refresh(db_user)
return UserOut(
id=db_user.id,
username=db_user.username,
email=db_user.email,
created_at=db_user.created_at
)
@app.post("/api/v1/auth/token", response_model=Token)
async def login(username: str, password: str, db=Depends(get_db)):
user = db.query(User).filter(User.username == username).first()
if not user or not verify_password(password, user.hashed_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Bearer"},
)
access_token = create_access_token(data={"sub": user.id})
return {"access_token": access_token, "token_type": "bearer"}
@app.post("/api/v1/content/generate", response_model=ContentGenerationResponse)
async def generate_content(
request: ContentGenerationRequest,
current_user: User = Depends(get_current_user),
db=Depends(get_db)
):
"""
Generate content using AI models
"""
try:
content_item = await content_studio.generate_content(
topic=request.topic,
content_type=request.content_type,
platform=request.platform,
user_id=current_user.id,
db=db
)
return ContentGenerationResponse(
id=content_item.id,
title=content_item.title,
content_type=content_item.content_type,
generated_content=content_item.generated_content,
platform_specific_variants=content_item.platform_specific_variants,
tags=content_item.tags,
created_at=content_item.created_at
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Content generation failed: {str(e)}")
@app.post("/api/v1/content/optimize")
async def optimize_existing_content(
request: OptimizationRequest,
current_user: User = Depends(get_current_user),
db=Depends(get_db)
):
"""
Optimize existing content
"""
try:
content_item = await content_studio.optimize_content(
content_id=request.content_id,
optimization_type=request.optimization_type,
db=db
)
return {
"id": content_item.id,
"optimized_content": content_item.generated_content,
"updated_at": content_item.updated_at
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Content optimization failed: {str(e)}")
@app.get("/api/v1/content/my", response_model=List[ContentGenerationResponse])
async def get_my_content(
current_user: User = Depends(get_current_user),
db=Depends(get_db)
):
"""
Get all content items for the current user
"""
content_items = db.query(ContentItem).filter(ContentItem.owner_id == current_user.id).all()
return [
ContentGenerationResponse(
id=item.id,
title=item.title,
content_type=item.content_type,
generated_content=item.generated_content,
platform_specific_variants=item.platform_specific_variants,
tags=item.tags,
created_at=item.created_at
)
for item in content_items
]
@app.post("/api/v1/generate/text")
async def generate_text_only(request: ContentGenerationRequest, current_user: User = Depends(get_current_user)):
"""
Generate text content only
"""
try:
prompt = content_studio._create_content_prompt(
request.topic,
request.content_type,
request.platform
)
generated_text = await ai_gateway.generate_text(
prompt=prompt,
provider=request.provider
)
return {"generated_text": generated_text}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Text generation failed: {str(e)}")
@app.get("/api/v1/models")
async def list_available_models(current_user: User = Depends(get_current_user)):
"""
List available AI models
"""
available_models = [provider.value for provider in ai_gateway.models.keys()]
return {"available_models": available_models}
@app.get("/api/v1/health")
async def health_check():
return {"status": "healthy", "timestamp": datetime.utcnow()}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)