LogoGeneration / main.py
utkarsh134's picture
Update main.py
732fc9e verified
Raw History Blame Contribute Delete
19.8 kB
from contextlib import asynccontextmanager
from typing import List, Optional
import uvicorn
import json
import logging
from fastapi import FastAPI, HTTPException, UploadFile, File, Form, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Dict, Any
# from mangum import Mangum
from app.services.banner_service import generate_banner
from app.services.custom_banner_desktop_service import generate_desktop_banner_v2
from app.services.custom_banner_mobile_service import generate_mobile_banner_v2
from app.services.custom_banner_ipad_service import generate_ipad_banner_v2
from app.services.bestnetwork_service import generate_network_banner
from app.services.byop_service import generate_byop_banner
from app.services.byop_unsplash_service import get_unsplash_byop_images
from app.services.custom_banner_service import generate_custom_banner
from app.services.custom_byop_service import generate_custom_byop_banner
from app.services.custom_network_service import generate_custom_network_banner
from app.services.logo_service import generate_logos
from app.services.network_unsplash_service import get_unsplash_network_images
from app.services.text_logo_service import generate_text_logos
from app.services.unsplash_service import get_unsplash_images
from app.services.ico_convert import convert_to_ico
from app.services.health_service import get_system_health
from app.services.single_icon_logo_service import generate_single_icon_logo
from app.services.single_text_logo_service import generate_single_text_logo
from app.services.upload_image_service import upload_file_as_is
from app.services.byop_unsplash_desktop_service import get_unsplash_byop_desktop_images
from app.services.byop_unsplash_mobile_service import get_unsplash_byop_mobile_images
from app.services.byop_unsplash_ipad_service import get_unsplash_byop_ipad_images
from app.services.network_unsplash_desktop_service import get_unsplash_network_desktop_images
from app.services.network_unsplash_mobile_service import get_unsplash_network_mobile_images
from app.services.network_unsplash_ipad_service import get_unsplash_network_ipad_images
from app.services.banner_unsplash_desktop_service import get_unsplash_desktop_banners
from app.services.banner_unsplash_ipad_service import get_unsplash_ipad_banners
from app.services.banner_unsplash_mobile_service import get_unsplash_mobile_banners
# Configure logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
@asynccontextmanager
async def lifespan(app: FastAPI):
yield
app = FastAPI(
title="Logo Generator API",
description="API for generating logos using Google Generative AI",
lifespan=lifespan,
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allows all origins
allow_credentials=True,
allow_methods=["*"], # Allows all methods
allow_headers=["*"], # Allows all headers
)
# handler = Mangum(
# app,
# lifespan="off",
# api_gateway_base_path="/",
# text_mime_types=["application/json", "multipart/form-data"]
# )
class LogoRequest(BaseModel):
brand_name: str
domain: str
primary_color: str
secondary_color: Optional[str] = None
tertiary_color: Optional[str] = None
class IconRequest(BaseModel):
svg_url: str
class BannerRequest(BaseModel):
brand_details: str
primary_color: str
class CustomBannerDeviceRequest(BaseModel):
prompt: str
brand_details: str
primary_color: str
class GeneralBannerRequest(BaseModel):
brand_details: str
class CustomBannerBaseRequest(BaseModel):
brand_name: str
domain: str
primary_color: str
description: str
# Specific request models for each device type
class CustomDesktopBannerRequest(CustomBannerBaseRequest):
pass
class CustomMobileBannerRequest(CustomBannerBaseRequest):
pass
class CustomIpadBannerRequest(CustomBannerBaseRequest):
pass
class UnsplashBannerRequest(BaseModel):
search_query: str
class ByopUnsplashRequest(BaseModel):
search_query: str
class NetworkUnsplashRequest(BaseModel):
search_query: str
class CustomBannerRequest(BaseModel):
prompt: str
brand_details: str
class Logo(BaseModel):
id: str
url: str
format: str
name: str
class LogoResponse(BaseModel):
logos: List[Logo]
class IcoConvertRequest(BaseModel):
filename: str
class HealthResponse(BaseModel):
"""Response model for health check endpoints"""
status: str
version: str
details: Dict[str, Any]
# @app.get("/")
# async def root():
# return {
# "message": "Logo Generator API is running. Use POST endpoints to create logos and banners."
# }
@app.get("/health", tags=["Health"])
async def def_health_check():
return {
"message": "Logo Generator API is running. Use POST endpoints to create logos and banners."
}
@app.post("/generate-icon-logo")
async def create_logo(request: LogoRequest):
try:
logo_results = generate_logos(
request.brand_name,
request.domain,
request.primary_color,
request.secondary_color,
request.tertiary_color,
)
return JSONResponse(content={"logos": logo_results})
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating logo: {str(e)}")
@app.post("/generate-text-logo")
async def create_text_logo(request: LogoRequest):
try:
logo_results = generate_text_logos(
request.brand_name,
request.domain,
request.primary_color,
request.secondary_color,
request.tertiary_color,
)
return JSONResponse(content={"logos": logo_results})
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error generating text logo: {str(e)}"
)
@app.post("/generate-banner")
async def create_banner(request: BannerRequest):
try:
banner_result = generate_banner(request.brand_details, request.primary_color)
return JSONResponse(content=banner_result)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error generating banner: {str(e)}"
)
@app.post("/desktop-banner")
async def create_desktop_banner(request: CustomBannerDeviceRequest):
try:
banner_result = generate_desktop_banner_v2(request.prompt, request.brand_details, request.primary_color)
return JSONResponse(content=banner_result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating desktop banner: {str(e)}")
@app.post("/mobile-banner")
async def create_mobile_banner(request: CustomBannerDeviceRequest):
try:
banner_result = generate_mobile_banner_v2(request.prompt, request.brand_details, request.primary_color)
return JSONResponse(content=banner_result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating mobile banner: {str(e)}")
@app.post("/ipad-banner")
async def create_ipad_banner(request: CustomBannerDeviceRequest):
try:
banner_result = generate_ipad_banner_v2(request.prompt, request.brand_details, request.primary_color)
return JSONResponse(content=banner_result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating iPad banner: {str(e)}")
@app.post("/get-unsplash-banner-desktop")
async def get_unsplash_banner_desktop(request: UnsplashBannerRequest):
try:
result = get_unsplash_desktop_banners(request.search_query)
return JSONResponse(content=result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching Unsplash desktop banner: {str(e)}")
@app.post("/get-unsplash-banner-ipad")
async def get_unsplash_banner_ipad(request: UnsplashBannerRequest):
try:
result = get_unsplash_ipad_banners(request.search_query)
return JSONResponse(content=result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching Unsplash iPad banner: {str(e)}")
@app.post("/get-unsplash-banner-mobile")
async def get_unsplash_banner_mobile(request: UnsplashBannerRequest):
try:
result = get_unsplash_mobile_banners(request.search_query)
return JSONResponse(content=result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching Unsplash mobile banner: {str(e)}")
# @app.post("/generate-custom-banner")
# async def create_custom_banner(request: CustomBannerRequest):
# try:
# banner_result = generate_custom_banner(
# request.brand_name, request.domain, request.description
# )
# return JSONResponse(content={"banner": banner_result})
# except Exception as e:
# raise HTTPException(
# status_code=500, detail=f"Error generating custom banner: {str(e)}"
# )
@app.post("/generate-network-banner")
async def create_network_banner(request: GeneralBannerRequest):
try:
banner_result = generate_network_banner(request.brand_details)
return JSONResponse(content=banner_result)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error generating network banner: {str(e)}"
)
@app.post("/get-network-banner-unsplash")
async def get_network_banner_images(request: NetworkUnsplashRequest):
try:
images = get_unsplash_network_images(request.search_query)
return JSONResponse(content=images)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/generate-custom-network-banner")
async def create_custom_network_banner(request: CustomBannerRequest):
try:
banner_result = generate_custom_network_banner(request.prompt, request.brand_details)
return JSONResponse(content=banner_result)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error generating custom network banner: {str(e)}"
)
@app.post("/generate-byop-banner")
async def create_byop_banner(request: GeneralBannerRequest):
try:
banner_result = generate_byop_banner(request.brand_details)
return JSONResponse(content=banner_result)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error generating BYOP banner: {str(e)}"
)
@app.post("/get-byop-banner-unsplash")
async def get_byop_banner_images(request: ByopUnsplashRequest):
try:
images = get_unsplash_byop_images(request.search_query)
return JSONResponse(content=images)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/generate-custom-byop-banner")
async def create_custom_byop_banner(request: CustomBannerRequest):
try:
banner_result = generate_custom_byop_banner(request.prompt, request.brand_details)
return JSONResponse(content=banner_result)
except Exception as e:
raise HTTPException(
status_code=500, detail=f"Error generating custom BYOP banner: {str(e)}"
)
@app.post("/convert-to-ico")
async def convert_image_to_ico(file: UploadFile = File(...)):
try:
result = await convert_to_ico(file)
return JSONResponse(content={"url": result["url"]})
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Error converting image to ICO: {str(e)}"
)
@app.get("/health/logo-service", tags=["Health"])
async def logo_service_health():
"""
Health check for logo generation service
"""
try:
health_status = await get_system_health()
required_services = ["google_ai", "image_processing", "reach_upload"]
service_status = all(
health_status["details"][service]["status"] == "healthy"
for service in required_services
)
if not service_status:
raise HTTPException(status_code=503, detail="Logo service dependencies unhealthy")
return {
"status": "healthy",
"service": "logo-generation",
"dependencies": {
service: health_status["details"][service]
for service in required_services
}
}
except Exception as e:
logger.error(f"Logo service health check failed: {str(e)}")
raise HTTPException(status_code=503, detail="Logo service unavailable")
@app.get("/health/banner-service", tags=["Health"])
async def banner_service_health():
"""
Health check for banner generation service
"""
try:
health_status = await get_system_health()
required_services = ["google_ai", "image_processing", "reach_upload"]
service_status = all(
health_status["details"][service]["status"] == "healthy"
for service in required_services
)
if not service_status:
raise HTTPException(status_code=503, detail="Banner service dependencies unhealthy")
return {
"status": "healthy",
"service": "banner-generation",
"dependencies": {
service: health_status["details"][service]
for service in required_services
}
}
except Exception as e:
logger.error(f"Banner service health check failed: {str(e)}")
raise HTTPException(status_code=503, detail="Banner service unavailable")
@app.get("/health/unsplash-service", tags=["Health"])
async def unsplash_service_health():
"""
Health check for Unsplash integration service
"""
try:
health_status = await get_system_health()
required_services = ["unsplash", "reach_upload"]
# Get detailed status of each required service
service_details = {
service: health_status["details"][service]
for service in required_services
}
# Check if any service is unhealthy
unhealthy_services = [
service for service, details in service_details.items()
if details["status"] != "healthy"
]
if unhealthy_services:
return JSONResponse(
status_code=503,
content={
"status": "unhealthy",
"service": "unsplash-integration",
"unhealthy_dependencies": unhealthy_services,
"details": service_details
}
)
return {
"status": "healthy",
"service": "unsplash-integration",
"dependencies": service_details,
"rate_limits": service_details["unsplash"].get("rate_limit_remaining", "unknown")
}
except Exception as e:
logger.error(f"Unsplash service health check failed: {str(e)}")
return JSONResponse(
status_code=503,
content={
"status": "unhealthy",
"service": "unsplash-integration",
"error": str(e),
"message": "Unsplash service health check failed"
}
)
@app.get("/health/ico-service", tags=["Health"])
async def ico_conversion_service_health():
"""
Health check for ICO conversion service
"""
try:
health_status = await get_system_health()
required_services = ["image_processing", "reach_upload"]
service_status = all(
health_status["details"][service]["status"] == "healthy"
for service in required_services
)
if not service_status:
raise HTTPException(status_code=503, detail="ICO conversion service dependencies unhealthy")
return {
"status": "healthy",
"service": "ico-conversion",
"dependencies": {
service: health_status["details"][service]
for service in required_services
}
}
except Exception as e:
logger.error(f"ICO conversion service health check failed: {str(e)}")
raise HTTPException(status_code=503, detail="ICO conversion service unavailable")
@app.post("/generate-single-icon-logo")
async def create_single_icon_logo(request: LogoRequest):
try:
logo_results = generate_single_icon_logo(
request.brand_name,
request.domain,
request.primary_color,
request.secondary_color,
request.tertiary_color,
)
return JSONResponse(content={"logos": logo_results["logos"]})
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating single icon logo: {str(e)}")
@app.post("/generate-single-text-logo")
async def create_single_text_logo(request: LogoRequest):
try:
logo_results = generate_single_text_logo(
request.brand_name,
request.domain,
request.primary_color,
request.secondary_color,
request.tertiary_color,
)
return JSONResponse(content={"logos": logo_results["logos"]})
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating single text logo: {str(e)}")
@app.post("/upload-image")
async def upload_image(file: UploadFile = File(...), file_type: str = Form(...)):
try:
result = await upload_file_as_is(file, file_type)
return JSONResponse(content=result)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error uploading image: {str(e)}")
@app.post("/get-byop-banner-unsplash-desktop")
async def get_byop_banner_unsplash_desktop(request: ByopUnsplashRequest):
try:
images = get_unsplash_byop_desktop_images(request.search_query)
return JSONResponse(content=images)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/get-byop-banner-unsplash-mobile")
async def get_byop_banner_unsplash_mobile(request: ByopUnsplashRequest):
try:
images = get_unsplash_byop_mobile_images(request.search_query)
return JSONResponse(content=images)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/get-byop-banner-unsplash-ipad")
async def get_byop_banner_unsplash_ipad(request: ByopUnsplashRequest):
try:
images = get_unsplash_byop_ipad_images(request.search_query)
return JSONResponse(content=images)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/get-network-banner-unsplash-desktop")
async def get_network_banner_unsplash_desktop(request: NetworkUnsplashRequest):
try:
images = get_unsplash_network_desktop_images(request.search_query)
return JSONResponse(content=images)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/get-network-banner-unsplash-mobile")
async def get_network_banner_unsplash_mobile(request: NetworkUnsplashRequest):
try:
images = get_unsplash_network_mobile_images(request.search_query)
return JSONResponse(content=images)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
@app.post("/get-network-banner-unsplash-ipad")
async def get_network_banner_unsplash_ipad(request: NetworkUnsplashRequest):
try:
images = get_unsplash_network_ipad_images(request.search_query)
return JSONResponse(content=images)
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))