File size: 2,497 Bytes
60c72fe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
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'<roast>(.*?)</roast>', 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)