import re import requests from fastapi import FastAPI, HTTPException from pydantic import BaseModel from dotenv import load_dotenv import os from fake_useragent import UserAgent from fastapi.responses import RedirectResponse # Load environment variables load_dotenv() # Get environment variables API_URL = os.getenv("API_URL") MODEL = os.getenv("MODEL") Origin = os.getenv("ORIGIN") # Initialize FastAPI app with custom documentation URLs app = FastAPI( title="Roast API", description="API for generating custom roasts. For more details, visit [Roast API Documentation](https://roastapi-docs.netlify.app/).", version="1.0.0", docs_url="/docs", openapi_url="/openapi.json" ) class RoastRequest(BaseModel): content: str def fetch_roasts(content: str): ua = UserAgent() headers = { 'origin': Origin, 'user-agent': ua.random, 'accept': '*/*', 'accept-encoding': 'gzip, deflate, br, zstd', 'accept-language': 'en-US,en;q=0.9,en-IN;q=0.8', } try: # Make API request with a 30-second timeout response = requests.post( API_URL, headers=headers, data={'content': content, 'model': MODEL}, timeout=30 # Add timeout here ) response.raise_for_status() # Raises HTTPError for bad responses # Parse the result and extract roasts result = response.json().get('result', '') roasts = re.findall(r'(.*?)', result) return roasts except requests.exceptions.Timeout: raise HTTPException(status_code=504, detail="The request timed out.") except requests.exceptions.RequestException as e: raise HTTPException(status_code=503, detail=f"Network error: {e}") except KeyError as e: raise HTTPException(status_code=500, detail=f"Response format error: {e}") except Exception as e: raise HTTPException(status_code=500, detail=f"Unexpected error: {e}") @app.get("/", include_in_schema=False) async def root(): return RedirectResponse(url="https://roastapi-docs.netlify.app/") @app.post("/generate-roasts/") async def generate_roasts(request: RoastRequest): roasts = fetch_roasts(request.content) if not roasts: raise HTTPException(status_code=404, detail="No roasts found.") return {"roasts": roasts} if __name__ == "__main__": import uvicorn print("Starting FastAPI server...") uvicorn.run(app, host="0.0.0.0", port=8000)