from fastapi import FastAPI, Depends, HTTPException, status, File, UploadFile from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse, JSONResponse import os import shutil import uuid import json import urllib.request import ssl from sqlalchemy import create_engine, Column, Integer, String, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker, Session from pydantic import BaseModel from passlib.context import CryptContext from jose import JWTError, jwt from datetime import datetime, timedelta from typing import Optional, List class GenerateRequest(BaseModel): topic: str tone: str = "professional" platform: str = "linkedin" apiKey: Optional[str] = None # Configuration SECRET_KEY = "supersecretkeychangeinproduction" # In a real app, use env var ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES = 1440 # 24 hours DATABASE_URL = "sqlite:///./database.db" # Gemini Configuration GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "AIzaSyAVstZz3lSa6s5bGw6WIzCfTe7D4iuUwEo") GEMINI_MODEL = "gemini-1.5-flash" ssl_context = ssl.create_default_context() # --- Database Setup --- engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) Base = declarative_base() class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True, index=True) email = Column(String, unique=True, index=True) hashed_password = Column(String) full_name = Column(String, nullable=True) is_pro = Column(Integer, default=0) # 0 = False, 1 = True (SQLite friendly) upgrade_date = Column(DateTime, nullable=True) # Store Settings store_name = Column(String, nullable=True) store_address = Column(String, nullable=True) store_phone = Column(String, nullable=True) store_logo_url = Column(String, nullable=True) class Project(Base): __tablename__ = "projects" id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) description = Column(String, nullable=True) status = Column(String, default="Active") owner_id = Column(Integer, index=True) class Customer(Base): __tablename__ = "customers" id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) email = Column(String, unique=True, index=True) company = Column(String, nullable=True) status = Column(String, default="Active") owner_id = Column(Integer, index=True) class Product(Base): __tablename__ = "products" id = Column(Integer, primary_key=True, index=True) name = Column(String, index=True) brand = Column(String, index=True) # Marque sku = Column(String, unique=True, index=True) price = Column(Integer) # Price in cents stock = Column(Integer, default=0) category = Column(String, nullable=True) # Ex: Réfrigérateur, TV, Lave-linge specs = Column(String, nullable=True) # Ex: 55", 12kg, 400L warranty_months = Column(Integer, default=24) # Garantie energy_class = Column(String, nullable=True) # A+++, A, B, etc. owner_id = Column(Integer, index=True) class Sale(Base): __tablename__ = "sales" id = Column(Integer, primary_key=True, index=True) customer_id = Column(Integer, nullable=True) total_amount = Column(Integer) payment_method = Column(String) # Cash, Card, Installments date = Column(DateTime, default=datetime.utcnow) owner_id = Column(Integer, index=True) class SaleItem(Base): __tablename__ = "sale_items" id = Column(Integer, primary_key=True, index=True) sale_id = Column(Integer, index=True) product_id = Column(Integer, index=True) quantity = Column(Integer) unit_price = Column(Integer) class Invoice(Base): __tablename__ = "invoices" id = Column(Integer, primary_key=True, index=True) customer_id = Column(Integer, index=True) total_amount = Column(Integer) # Total in cents status = Column(String, default="Unpaid") # Unpaid, Paid, Overdue date = Column(DateTime, default=datetime.utcnow) owner_id = Column(Integer, index=True) Base.metadata.create_all(bind=engine) # --- Pydantic Models --- class UserCreate(BaseModel): email: str password: str full_name: Optional[str] = None class UserResponse(BaseModel): id: int email: str full_name: Optional[str] = None is_pro: bool = False upgrade_date: Optional[datetime] = None # Store settings store_name: Optional[str] = None store_address: Optional[str] = None store_phone: Optional[str] = None store_logo_url: Optional[str] = None class Config: from_attributes = True class ProjectCreate(BaseModel): name: str description: Optional[str] = None status: str = "Active" class ProjectResponse(BaseModel): id: int name: str description: Optional[str] = None status: str owner_id: int class Config: from_attributes = True class UserUpdate(BaseModel): full_name: Optional[str] = None email: Optional[str] = None store_name: Optional[str] = None store_address: Optional[str] = None store_phone: Optional[str] = None store_logo_url: Optional[str] = None class PasswordUpdate(BaseModel): current_password: str new_password: str class ForgotPasswordRequest(BaseModel): email: str class CustomerCreate(BaseModel): name: str email: str company: Optional[str] = None status: str = "Active" class CustomerResponse(BaseModel): id: int name: str email: str company: Optional[str] = None status: str owner_id: int class Config: from_attributes = True class ProductCreate(BaseModel): name: str brand: str sku: str price: int stock: int = 0 category: Optional[str] = None specs: Optional[str] = None warranty_months: int = 24 energy_class: Optional[str] = None class ProductUpdate(BaseModel): name: Optional[str] = None brand: Optional[str] = None sku: Optional[str] = None price: Optional[int] = None stock: Optional[int] = None category: Optional[str] = None specs: Optional[str] = None warranty_months: Optional[int] = None energy_class: Optional[str] = None class ProductResponse(BaseModel): id: int name: str brand: str sku: str price: int stock: int category: Optional[str] = None specs: Optional[str] = None warranty_months: int energy_class: Optional[str] = None owner_id: int class Config: from_attributes = True class SaleItemCreate(BaseModel): product_id: int quantity: int unit_price: int class SaleCreate(BaseModel): customer_id: Optional[int] = None payment_method: str items: list[SaleItemCreate] class SaleUpdate(BaseModel): total_amount: Optional[int] = None payment_method: Optional[str] = None customer_id: Optional[int] = None class SaleResponse(BaseModel): id: int total_amount: int payment_method: str date: datetime customer_id: Optional[int] = None class Config: from_attributes = True class ProductInfo(BaseModel): name: str brand: str sku: str class SaleItemDetail(BaseModel): id: int product_id: int quantity: int unit_price: int product: Optional[ProductInfo] = None class SaleDetailResponse(BaseModel): id: int total_amount: int payment_method: str date: datetime customer_id: Optional[int] = None items: list[SaleItemDetail] customer: Optional[CustomerResponse] = None class Config: from_attributes = True class InvoiceCreate(BaseModel): customer_id: int total_amount: int status: str = "Unpaid" class InvoiceResponse(BaseModel): id: int customer_id: int total_amount: int status: str date: datetime owner_id: int class Config: from_attributes = True class Token(BaseModel): access_token: str token_type: str # --- Security --- pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto") oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") def verify_password(plain_password, hashed_password): return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password): return pwd_context.hash(password) def create_access_token(data: dict, expires_delta: Optional[timedelta] = None): to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=15) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) return encoded_jwt # --- Dependencies --- def get_db(): db = SessionLocal() try: yield db finally: db.close() async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): credentials_exception = HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Could not validate credentials", headers={"WWW-Authenticate": "Bearer"}, ) try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id: str = payload.get("sub") if user_id is None: raise credentials_exception except JWTError: raise credentials_exception # We try to search by ID first (new system), then by email (compatibility) user = db.query(User).filter(User.id == user_id).first() if user is None: # Fallback for old tokens that used email as sub user = db.query(User).filter(User.email == user_id).first() if user is None: raise credentials_exception return user # --- FastAPI App --- app = FastAPI() # CORS (Allow Frontend to connect) # When `allow_credentials=True`, browsers reject Access-Control-Allow-Origin: '*'. # Specify the local origins used for development instead of using a wildcard. allowed_origins = [ "http://localhost:4173", "http://localhost:5173", "http://localhost:8000", "http://127.0.0.1:8000", "http://127.0.0.1:5173", "http://127.0.0.1:4173", ] app.add_middleware( CORSMiddleware, allow_origins=["*"], # Allow all origins for deployment allow_credentials=False, # Must be False when allow_origins is ["*"] allow_methods=["*"], allow_headers=["*"], ) # Ensure uploads directory exists UPLOAD_DIR = "uploads" if not os.path.exists(UPLOAD_DIR): os.makedirs(UPLOAD_DIR) app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads") @app.post("/register", response_model=UserResponse) def register(user: UserCreate, db: Session = Depends(get_db)): db_user = db.query(User).filter(User.email == user.email).first() if db_user: raise HTTPException(status_code=400, detail="Email already registered") hashed_password = get_password_hash(user.password) new_user = User(email=user.email, hashed_password=hashed_password, full_name=user.full_name) db.add(new_user) db.commit() db.refresh(new_user) return new_user @app.post("/token", response_model=Token) def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)): user = db.query(User).filter(User.email == form_data.username).first() if not user or not verify_password(form_data.password, user.hashed_password): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Incorrect email or password", headers={"WWW-Authenticate": "Bearer"}, ) access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) access_token = create_access_token( data={"sub": str(user.id)}, expires_delta=access_token_expires ) return {"access_token": access_token, "token_type": "bearer"} @app.get("/users/me", response_model=UserResponse) async def read_users_me(current_user: User = Depends(get_current_user)): return current_user @app.put("/users/me", response_model=UserResponse) def update_user(user_update: UserUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): update_data = user_update.dict(exclude_unset=True) for key, value in update_data.items(): if key == "email": existing = db.query(User).filter(User.email == value, User.id != current_user.id).first() if existing: raise HTTPException(status_code=400, detail="Email already taken") setattr(current_user, key, value) db.commit() db.refresh(current_user) return current_user @app.post("/users/me/logo") async def upload_logo(file: UploadFile = File(...), db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): # Validate file type if not file.content_type.startswith("image/"): raise HTTPException(status_code=400, detail="File must be an image") # Create unique filename file_ext = os.path.splitext(file.filename)[1] filename = f"{uuid.uuid4()}{file_ext}" file_path = os.path.join(UPLOAD_DIR, filename) # Save file with open(file_path, "wb") as buffer: shutil.copyfileobj(file.file, buffer) # Update user logo URL logo_url = f"http://localhost:8000/uploads/{filename}" current_user.store_logo_url = logo_url db.commit() db.refresh(current_user) return {"logo_url": logo_url} @app.put("/users/me/password") def change_password(password_data: PasswordUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): if not verify_password(password_data.current_password, current_user.hashed_password): raise HTTPException(status_code=400, detail="Mot de passe actuel incorrect") current_user.hashed_password = get_password_hash(password_data.new_password) db.commit() return {"message": "Mot de passe mis à jour avec succès"} @app.post("/forgot-password") def forgot_password(request: ForgotPasswordRequest, db: Session = Depends(get_db)): user = db.query(User).filter(User.email == request.email).first() if not user: # For security, we often return 200 even if user doesn't exist # but here we'll be explicit for the user experience as requested raise HTTPException(status_code=404, detail="Aucun compte trouvé avec cet email") # In a real app, send actual email here return {"message": f"Un lien de réinitialisation a été envoyé à {request.email}"} @app.post("/users/upgrade", response_model=UserResponse) def upgrade_user(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): current_user.is_pro = 1 current_user.upgrade_date = datetime.utcnow() db.commit() db.refresh(current_user) return current_user @app.post("/projects/", response_model=ProjectResponse) def create_project(project: ProjectCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): db_project = Project(**project.dict(), owner_id=current_user.id) db.add(db_project) db.commit() db.refresh(db_project) return db_project @app.get("/projects/", response_model=list[ProjectResponse]) def read_projects(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): projects = db.query(Project).filter(Project.owner_id == current_user.id).offset(skip).limit(limit).all() return projects @app.post("/customers/", response_model=CustomerResponse) def create_customer(customer: CustomerCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): existing = db.query(Customer).filter(Customer.email == customer.email).first() if existing: raise HTTPException(status_code=400, detail="Customer email already exists") db_customer = Customer(**customer.dict(), owner_id=current_user.id) db.add(db_customer) db.commit() db.refresh(db_customer) return db_customer @app.get("/customers/", response_model=list[CustomerResponse]) def read_customers(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): customers = db.query(Customer).filter(Customer.owner_id == current_user.id).offset(skip).limit(limit).all() return customers @app.delete("/customers/{customer_id}") def delete_customer(customer_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): customer = db.query(Customer).filter(Customer.id == customer_id, Customer.owner_id == current_user.id).first() if not customer: raise HTTPException(status_code=404, detail="Customer not found") db.delete(customer) db.commit() return {"message": "Customer deleted"} # --- Product Endpoints --- @app.post("/products/", response_model=ProductResponse) def create_product(product: ProductCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): db_product = Product(**product.dict(), owner_id=current_user.id) db.add(db_product) db.commit() db.refresh(db_product) return db_product @app.get("/products/", response_model=list[ProductResponse]) def read_products(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): return db.query(Product).filter(Product.owner_id == current_user.id).offset(skip).limit(limit).all() @app.delete("/products/{product_id}") def delete_product(product_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): product = db.query(Product).filter(Product.id == product_id, Product.owner_id == current_user.id).first() if not product: raise HTTPException(status_code=404, detail="Product not found") db.delete(product) db.commit() return {"message": "Product deleted"} @app.put("/products/{product_id}", response_model=ProductResponse) def update_product(product_id: int, product_update: ProductUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): db_product = db.query(Product).filter(Product.id == product_id, Product.owner_id == current_user.id).first() if not db_product: raise HTTPException(status_code=404, detail="Product not found") update_data = product_update.dict(exclude_unset=True) for key, value in update_data.items(): setattr(db_product, key, value) db.commit() db.refresh(db_product) return db_product # --- Invoice Endpoints --- @app.post("/invoices/", response_model=InvoiceResponse) def create_invoice(invoice: InvoiceCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): db_invoice = Invoice(**invoice.dict(), owner_id=current_user.id) db.add(db_invoice) db.commit() db.refresh(db_invoice) return db_invoice @app.get("/invoices/", response_model=list[InvoiceResponse]) def read_invoices(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): return db.query(Invoice).filter(Invoice.owner_id == current_user.id).offset(skip).limit(limit).all() @app.delete("/invoices/{invoice_id}") def delete_invoice(invoice_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): invoice = db.query(Invoice).filter(Invoice.id == invoice_id, Invoice.owner_id == current_user.id).first() if not invoice: raise HTTPException(status_code=404, detail="Invoice not found") db.delete(invoice) db.commit() return {"message": "Invoice deleted"} # --- POS / Sale Endpoints --- @app.post("/sales/", response_model=SaleResponse) def create_sale(sale: SaleCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): total = sum(item.unit_price * item.quantity for item in sale.items) db_sale = Sale( customer_id=sale.customer_id, total_amount=total, payment_method=sale.payment_method, owner_id=current_user.id ) db.add(db_sale) db.commit() db.refresh(db_sale) for item in sale.items: # Reduction du stock product = db.query(Product).filter(Product.id == item.product_id).first() if product: product.stock -= item.quantity db_item = SaleItem( sale_id=db_sale.id, product_id=item.product_id, quantity=item.quantity, unit_price=item.unit_price ) db.add(db_item) db.commit() return db_sale @app.get("/sales/", response_model=list[SaleResponse]) def read_sales(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): return db.query(Sale).filter(Sale.owner_id == current_user.id).order_by(Sale.date.desc()).all() @app.delete("/sales/{sale_id}") def delete_sale(sale_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): sale = db.query(Sale).filter(Sale.id == sale_id, Sale.owner_id == current_user.id).first() if not sale: raise HTTPException(status_code=404, detail="Sale not found") # Optionnel: Supprimer aussi les SaleItems db.query(SaleItem).filter(SaleItem.sale_id == sale_id).delete() db.delete(sale) db.commit() return {"message": "Sale deleted"} @app.put("/sales/{sale_id}", response_model=SaleResponse) def update_sale(sale_id: int, sale_update: SaleUpdate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): db_sale = db.query(Sale).filter(Sale.id == sale_id, Sale.owner_id == current_user.id).first() if not db_sale: raise HTTPException(status_code=404, detail="Sale not found") update_data = sale_update.dict(exclude_unset=True) for key, value in update_data.items(): setattr(db_sale, key, value) db.commit() db.refresh(db_sale) return db_sale @app.get("/sales/{sale_id}/details", response_model=SaleDetailResponse) def get_sale_details(sale_id: int, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)): sale = db.query(Sale).filter(Sale.id == sale_id, Sale.owner_id == current_user.id).first() if not sale: raise HTTPException(status_code=404, detail="Sale not found") # Fetch Items items = db.query(SaleItem).filter(SaleItem.sale_id == sale_id).all() # Attach product info to items details = [] for item in items: product = db.query(Product).filter(Product.id == item.product_id).first() details.append({ "id": item.id, "product_id": item.product_id, "quantity": item.quantity, "unit_price": item.unit_price, "product": { "name": product.name, "brand": product.brand, "sku": product.sku } if product else None }) # Fetch customer info customer = None if sale.customer_id: customer = db.query(Customer).filter(Customer.id == sale.customer_id).first() return { "id": sale.id, "total_amount": sale.total_amount, "payment_method": sale.payment_method, "date": sale.date, "customer_id": sale.customer_id, "items": details, "customer": customer } @app.get("/") def read_root(): # Serve portfolio index.html at root portfolio_index = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..", "interactive-portfolio", "index.html")) if os.path.exists(portfolio_index): return FileResponse(portfolio_index) return {"message": "SaaS Dashboard API is running!"} # Serve built frontend under /saas-dashboard/dist/ and return index.html for SPA routes DIST_DIR = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "dist")) @app.get("/saas-dashboard/dist") @app.get("/saas-dashboard/dist/") def saas_dist_root(): index_path = os.path.join(DIST_DIR, "index.html") if os.path.exists(index_path): return FileResponse(index_path) raise HTTPException(status_code=404, detail="Not found") @app.get("/saas-dashboard/dist/{full_path:path}") def saas_dist(full_path: str): # Prevent path traversal requested = os.path.normpath(os.path.join(DIST_DIR, full_path)) if not requested.startswith(DIST_DIR): raise HTTPException(status_code=404, detail="Not found") if os.path.exists(requested) and os.path.isfile(requested): return FileResponse(requested) # Fallback to index.html for client-side routing index_path = os.path.join(DIST_DIR, "index.html") if os.path.exists(index_path): return FileResponse(index_path) raise HTTPException(status_code=404, detail="Not found") # Mount assets directory so requests to /assets/* resolve when serving at root ASSETS_DIR = os.path.join(DIST_DIR, "assets") if os.path.exists(ASSETS_DIR): app.mount("/assets", StaticFiles(directory=ASSETS_DIR), name="assets") # Also mount portfolio assets so images and other files resolve PORTFOLIO_ASSETS_DIR = os.path.normpath(os.path.join(os.path.dirname(__file__), "..", "..", "assets")) if os.path.exists(PORTFOLIO_ASSETS_DIR): app.mount("/portfolio-assets", StaticFiles(directory=PORTFOLIO_ASSETS_DIR), name="portfolio-assets") # Serve vite.svg at root if present (some builds reference /vite.svg) VITE_SVG = os.path.join(DIST_DIR, "vite.svg") @app.get("/vite.svg") def serve_vite_svg(): if os.path.exists(VITE_SVG): return FileResponse(VITE_SVG) raise HTTPException(status_code=404, detail="Not found") # --- AI / Gemini Endpoints --- @app.get("/api/key") async def get_gemini_key(): # Return masked API key for UI display key = GEMINI_API_KEY masked = key[:10] + "..." + key[-4:] if len(key) > 14 else "***" return {"key": masked} @app.post("/api/generate") async def generate_content(request: GenerateRequest): try: # Use provided key or default api_key = request.apiKey if request.apiKey and request.apiKey.startswith("AIza") else GEMINI_API_KEY # Prompt Engineering system_prompt = "Tu es un expert en copywriting spécialisé dans les réseaux sociaux." if request.platform == 'linkedin': platform_info = """ Plateforme : LinkedIn (B2B, Professionnel). Format : 1. Accroche percutante. 2. Corps aéré. 3. Call to Action. Style : Ton d'autorité, focus valeur ajoutée, pas de hashtags inutiles.""" else: platform_info = """ Plateforme : Facebook (B2C, Engagement social/personnel). Format : 1. Une phrase d'ouverture courte et intrigante (souvent une question). 2. Un ton conversationnel et chaleureux, comme si vous parliez à des amis. 3. Utilisation d'emojis pour diviser le texte et apporter de la couleur. 4. Encouragez le partage d'opinions dans les commentaires. Style : Émotionnel, authentique, évitez le jargon "Corporate". Ajoutez 2-3 hashtags populaires à la fin.""" prompt = f"""{system_prompt} {platform_info} Sujet : "{request.topic}" Ton : {request.tone} Règles : - Longueur : 150-250 mots. - Langue : Français impeccable. - Pas de titre, commence direct par le texte.""" api_url = f'https://generativelanguage.googleapis.com/v1beta/models/{GEMINI_MODEL}:generateContent?key={api_key}' request_body = json.dumps({ 'contents': [{'parts': [{'text': prompt}]}] }).encode('utf-8') req = urllib.request.Request( api_url, data=request_body, headers={'Content-Type': 'application/json'}, method='POST' ) with urllib.request.urlopen(req, context=ssl_context) as api_response: result = json.loads(api_response.read().decode('utf-8')) if 'candidates' not in result or not result['candidates']: raise HTTPException(status_code=500, detail="Gemini failed to generate content") generated_text = result['candidates'][0]['content']['parts'][0]['text'] return {"text": generated_text} except Exception as e: print(f"Error in generate_content: {str(e)}") raise HTTPException(status_code=500, detail=str(e)) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8000)