import re import requests from fastapi import FastAPI, HTTPException from pydantic import BaseModel from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Get environment variables API_URL = os.getenv("API_URL") MODEL = os.getenv("MODEL") Origin = os.getenv("ORIGIN") app = FastAPI() class RoastRequest(BaseModel): content: str def fetch_roasts(content: str): try: # Make API request response = requests.post( API_URL, headers={'origin': Origin}, data={'content': content, 'model': MODEL} ) 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.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.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)