-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
75 lines (58 loc) · 1.66 KB
/
Copy pathmain.py
File metadata and controls
75 lines (58 loc) · 1.66 KB
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
import os
from datetime import datetime
from fastapi import FastAPI, UploadFile, File, Request
import httpx
import cloudinary
import cloudinary.uploader
from pymongo import MongoClient
from dotenv import load_dotenv
load_dotenv()
TEXT_API = os.getenv("TEXT_API")
IMAGE_API = os.getenv("IMAGE_API")
cloudinary.config(
cloud_name=os.getenv("CLOUDINARY_CLOUD_NAME"),
api_key=os.getenv("CLOUDINARY_API_KEY"),
api_secret=os.getenv("CLOUDINARY_API_SECRET"),
secure=True
)
mongo = MongoClient(os.getenv("MONGODB_URI"))
db = mongo[os.getenv("MONGODB_DB")]
images = db.images
texts = db.texts
app = FastAPI()
client = httpx.AsyncClient(
timeout=httpx.Timeout(20.0),
limits=httpx.Limits(max_keepalive_connections=10)
)
@app.post("/sentiment")
async def sentiment(request: Request):
data = await request.json()
text = data.get("text")
r = await client.post(TEXT_API, json={"text": text})
result = r.json()
texts.insert_one({
"text": text,
"sentiment": result.get("predicted_emotion"),
"result": result,
"created_at": datetime.utcnow()
})
return result
@app.post("/image-moderate")
async def image_moderate(file: UploadFile = File(...)):
content = await file.read()
r = await client.post(
IMAGE_API,
files={"file": (file.filename, content, file.content_type)}
)
upload = cloudinary.uploader.upload(
r.content,
folder="moderated_images",
resource_type="image"
)
images.insert_one({
"cloudinary_url": upload["secure_url"],
"created_at": datetime.utcnow()
})
return {
"cloudinary_url": upload["secure_url"]
}