Spaces:
Running
Running
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import requests
|
3 |
+
from fastapi import FastAPI, HTTPException
|
4 |
+
from pydantic import BaseModel
|
5 |
+
from dotenv import load_dotenv
|
6 |
+
import os
|
7 |
+
|
8 |
+
# Load environment variables
|
9 |
+
load_dotenv()
|
10 |
+
|
11 |
+
# Get environment variables
|
12 |
+
API_URL = os.getenv("API_URL")
|
13 |
+
MODEL = os.getenv("MODEL")
|
14 |
+
Origin = os.getenv("ORIGIN")
|
15 |
+
app = FastAPI()
|
16 |
+
|
17 |
+
class RoastRequest(BaseModel):
|
18 |
+
content: str
|
19 |
+
|
20 |
+
def fetch_roasts(content: str):
|
21 |
+
try:
|
22 |
+
# Make API request
|
23 |
+
response = requests.post(
|
24 |
+
API_URL,
|
25 |
+
headers={'origin': Origin},
|
26 |
+
data={'content': content, 'model': MODEL}
|
27 |
+
)
|
28 |
+
response.raise_for_status() # Raises HTTPError for bad responses
|
29 |
+
|
30 |
+
# Parse the result and extract roasts
|
31 |
+
result = response.json().get('result', '')
|
32 |
+
roasts = re.findall(r'<roast>(.*?)</roast>', result)
|
33 |
+
return roasts
|
34 |
+
|
35 |
+
except requests.exceptions.RequestException as e:
|
36 |
+
raise HTTPException(status_code=503, detail=f"Network error: {e}")
|
37 |
+
except KeyError as e:
|
38 |
+
raise HTTPException(status_code=500, detail=f"Response format error: {e}")
|
39 |
+
except Exception as e:
|
40 |
+
raise HTTPException(status_code=500, detail=f"Unexpected error: {e}")
|
41 |
+
|
42 |
+
@app.post("/generate-roasts/")
|
43 |
+
async def generate_roasts(request: RoastRequest):
|
44 |
+
roasts = fetch_roasts(request.content)
|
45 |
+
if not roasts:
|
46 |
+
raise HTTPException(status_code=404, detail="No roasts found.")
|
47 |
+
return {"roasts": roasts}
|
48 |
+
|
49 |
+
if __name__ == "__main__":
|
50 |
+
import uvicorn
|
51 |
+
print("Starting FastAPI server...")
|
52 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|