Update app.py
Browse files
app.py
CHANGED
|
@@ -4,7 +4,7 @@ import json
|
|
| 4 |
import traceback
|
| 5 |
from datetime import datetime
|
| 6 |
from typing import Optional
|
| 7 |
-
|
| 8 |
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request, Depends
|
| 9 |
from fastapi.responses import StreamingResponse, JSONResponse
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
|
@@ -45,11 +45,8 @@ hf_client = InferenceClient(token=HF_TOKEN)
|
|
| 45 |
# ---------------------------------------------------------------------
|
| 46 |
# MongoDB setup
|
| 47 |
# ---------------------------------------------------------------------
|
| 48 |
-
MONGODB_URI =
|
| 49 |
-
|
| 50 |
-
raise RuntimeError("MONGODB_URI not set in environment variables")
|
| 51 |
-
|
| 52 |
-
DB_NAME = os.getenv("DB_NAME", "polaroid_db")
|
| 53 |
|
| 54 |
mongo = MongoClient(MONGODB_URI)
|
| 55 |
db = mongo[DB_NAME]
|
|
@@ -72,7 +69,7 @@ app.add_middleware(
|
|
| 72 |
# Auth dependency
|
| 73 |
# ---------------------------------------------------------------------
|
| 74 |
async def verify_firebase_token(request: Request):
|
| 75 |
-
"""
|
| 76 |
auth_header = request.headers.get("Authorization")
|
| 77 |
if not auth_header or not auth_header.startswith("Bearer "):
|
| 78 |
raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
|
|
@@ -99,11 +96,8 @@ class HealthResponse(BaseModel):
|
|
| 99 |
@app.get("/health", response_model=HealthResponse)
|
| 100 |
def health():
|
| 101 |
"""Public health check"""
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
return HealthResponse(status="ok", db=db.name, model="Qwen/Qwen-Image-Edit")
|
| 105 |
-
except Exception as e:
|
| 106 |
-
raise HTTPException(status_code=500, detail=f"DB ping failed: {e}")
|
| 107 |
|
| 108 |
|
| 109 |
@app.post("/generate")
|
|
@@ -113,78 +107,87 @@ async def generate(
|
|
| 113 |
image2: Optional[UploadFile] = File(None),
|
| 114 |
user=Depends(verify_firebase_token)
|
| 115 |
):
|
| 116 |
-
|
| 117 |
-
start_time = datetime.utcnow() # Start timer
|
| 118 |
|
| 119 |
try:
|
| 120 |
-
# Read first image
|
| 121 |
img1_bytes = await image1.read()
|
| 122 |
pil_img1 = Image.open(io.BytesIO(img1_bytes)).convert("RGB")
|
|
|
|
|
|
|
| 123 |
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
|
|
|
| 127 |
img2_bytes = await image2.read()
|
| 128 |
pil_img2 = Image.open(io.BytesIO(img2_bytes)).convert("RGB")
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
pil_output = hf_client.image_to_image(
|
| 142 |
image=combined_img,
|
| 143 |
prompt=prompt,
|
| 144 |
model="Qwen/Qwen-Image-Edit"
|
| 145 |
)
|
| 146 |
-
|
| 147 |
out_buf = io.BytesIO()
|
| 148 |
pil_output.save(out_buf, format="PNG")
|
| 149 |
out_bytes = out_buf.getvalue()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
user_email=user.get("email"),
|
| 157 |
-
)
|
| 158 |
-
|
| 159 |
-
# Calculate response time
|
| 160 |
-
end_time = datetime.utcnow()
|
| 161 |
-
response_time_ms = (end_time - start_time).total_seconds() * 1000
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
|
|
|
| 172 |
|
| 173 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
-
except Exception as e:
|
| 176 |
-
traceback.print_exc()
|
| 177 |
-
end_time = datetime.utcnow()
|
| 178 |
-
response_time_ms = (end_time - start_time).total_seconds() * 1000
|
| 179 |
-
try:
|
| 180 |
-
logs_collection.insert_one({
|
| 181 |
-
"timestamp": end_time,
|
| 182 |
-
"user": user.get("email") if user else "unknown",
|
| 183 |
-
"response_time_ms": response_time_ms
|
| 184 |
-
})
|
| 185 |
-
except Exception:
|
| 186 |
-
pass
|
| 187 |
-
raise HTTPException(status_code=500, detail=f"Processing failed: {e}")
|
| 188 |
|
| 189 |
|
| 190 |
@app.get("/image/{image_id}")
|
|
@@ -209,9 +212,11 @@ def get_image(image_id: str, download: Optional[bool] = False):
|
|
| 209 |
headers=headers
|
| 210 |
)
|
| 211 |
|
|
|
|
| 212 |
# ---------------------------------------------------------------------
|
| 213 |
# Run locally
|
| 214 |
# ---------------------------------------------------------------------
|
| 215 |
if __name__ == "__main__":
|
| 216 |
import uvicorn
|
| 217 |
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
|
|
|
|
|
|
| 4 |
import traceback
|
| 5 |
from datetime import datetime
|
| 6 |
from typing import Optional
|
| 7 |
+
import time
|
| 8 |
from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request, Depends
|
| 9 |
from fastapi.responses import StreamingResponse, JSONResponse
|
| 10 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 45 |
# ---------------------------------------------------------------------
|
| 46 |
# MongoDB setup
|
| 47 |
# ---------------------------------------------------------------------
|
| 48 |
+
MONGODB_URI = "mongodb+srv://harilogicgo_db_user:EpWocJKRpXau8eBW@images.nh9bx9l.mongodb.net/?appName=images"
|
| 49 |
+
DB_NAME = "polaroid_db"
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
mongo = MongoClient(MONGODB_URI)
|
| 52 |
db = mongo[DB_NAME]
|
|
|
|
| 69 |
# Auth dependency
|
| 70 |
# ---------------------------------------------------------------------
|
| 71 |
async def verify_firebase_token(request: Request):
|
| 72 |
+
"""Middleware-like dependency to verify Firebase JWT from Authorization header."""
|
| 73 |
auth_header = request.headers.get("Authorization")
|
| 74 |
if not auth_header or not auth_header.startswith("Bearer "):
|
| 75 |
raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
|
|
|
|
| 96 |
@app.get("/health", response_model=HealthResponse)
|
| 97 |
def health():
|
| 98 |
"""Public health check"""
|
| 99 |
+
mongo.admin.command("ping")
|
| 100 |
+
return HealthResponse(status="ok", db=db.name, model="Qwen/Qwen-Image-Edit")
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
|
| 103 |
@app.post("/generate")
|
|
|
|
| 107 |
image2: Optional[UploadFile] = File(None),
|
| 108 |
user=Depends(verify_firebase_token)
|
| 109 |
):
|
| 110 |
+
start_time = time.time() # ⬅️ Start timing
|
|
|
|
| 111 |
|
| 112 |
try:
|
|
|
|
| 113 |
img1_bytes = await image1.read()
|
| 114 |
pil_img1 = Image.open(io.BytesIO(img1_bytes)).convert("RGB")
|
| 115 |
+
except Exception as e:
|
| 116 |
+
raise HTTPException(status_code=400, detail=f"Failed to read first image: {e}")
|
| 117 |
|
| 118 |
+
pil_img2 = None
|
| 119 |
+
img2_bytes = None
|
| 120 |
+
if image2:
|
| 121 |
+
try:
|
| 122 |
img2_bytes = await image2.read()
|
| 123 |
pil_img2 = Image.open(io.BytesIO(img2_bytes)).convert("RGB")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
raise HTTPException(status_code=400, detail=f"Failed to read second image: {e}")
|
| 126 |
+
|
| 127 |
+
input1_id = fs.put(img1_bytes, filename=image1.filename, contentType=image1.content_type, role="input")
|
| 128 |
+
input2_id = None
|
| 129 |
+
if pil_img2:
|
| 130 |
+
input2_id = fs.put(img2_bytes, filename=image2.filename, contentType=image2.content_type, role="input")
|
| 131 |
+
|
| 132 |
+
# Combine images if needed
|
| 133 |
+
if pil_img2:
|
| 134 |
+
total_width = pil_img1.width + pil_img2.width
|
| 135 |
+
max_height = max(pil_img1.height, pil_img2.height)
|
| 136 |
+
combined_img = Image.new("RGB", (total_width, max_height))
|
| 137 |
+
combined_img.paste(pil_img1, (0, 0))
|
| 138 |
+
combined_img.paste(pil_img2, (pil_img1.width, 0))
|
| 139 |
+
else:
|
| 140 |
+
combined_img = pil_img1
|
| 141 |
+
|
| 142 |
+
# HuggingFace inference
|
| 143 |
+
try:
|
| 144 |
pil_output = hf_client.image_to_image(
|
| 145 |
image=combined_img,
|
| 146 |
prompt=prompt,
|
| 147 |
model="Qwen/Qwen-Image-Edit"
|
| 148 |
)
|
|
|
|
| 149 |
out_buf = io.BytesIO()
|
| 150 |
pil_output.save(out_buf, format="PNG")
|
| 151 |
out_bytes = out_buf.getvalue()
|
| 152 |
+
except Exception as e:
|
| 153 |
+
traceback.print_exc()
|
| 154 |
+
raise HTTPException(status_code=500, detail=f"Inference failed: {e}")
|
| 155 |
+
|
| 156 |
+
# Save output image
|
| 157 |
+
out_id = fs.put(
|
| 158 |
+
out_bytes,
|
| 159 |
+
filename=f"result_{input1_id}.png",
|
| 160 |
+
contentType="image/png",
|
| 161 |
+
prompt=prompt,
|
| 162 |
+
role="output",
|
| 163 |
+
input1_id=str(input1_id),
|
| 164 |
+
input2_id=str(input2_id) if input2_id else None,
|
| 165 |
+
user_email=user.get("email"),
|
| 166 |
+
)
|
| 167 |
|
| 168 |
+
# -------------------------------------------
|
| 169 |
+
# LOGGING WITH RESPONSE TIME (NEW ADDITION)
|
| 170 |
+
# -------------------------------------------
|
| 171 |
+
end_time = time.time()
|
| 172 |
+
response_time_ms = round((end_time - start_time) * 1000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
+
logs_collection.insert_one({
|
| 175 |
+
"timestamp": datetime.utcnow(),
|
| 176 |
+
"input1_id": str(input1_id),
|
| 177 |
+
"input2_id": str(input2_id) if input2_id else None,
|
| 178 |
+
"output_id": str(out_id),
|
| 179 |
+
"prompt": prompt,
|
| 180 |
+
"user": user.get("email"),
|
| 181 |
+
"response_time_ms": response_time_ms # <-- LOGGED HERE
|
| 182 |
+
})
|
| 183 |
+
# -------------------------------------------
|
| 184 |
|
| 185 |
+
return JSONResponse({
|
| 186 |
+
"output_image_id": str(out_id),
|
| 187 |
+
"user": user.get("email"),
|
| 188 |
+
"response_time_ms": response_time_ms
|
| 189 |
+
})
|
| 190 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 191 |
|
| 192 |
|
| 193 |
@app.get("/image/{image_id}")
|
|
|
|
| 212 |
headers=headers
|
| 213 |
)
|
| 214 |
|
| 215 |
+
|
| 216 |
# ---------------------------------------------------------------------
|
| 217 |
# Run locally
|
| 218 |
# ---------------------------------------------------------------------
|
| 219 |
if __name__ == "__main__":
|
| 220 |
import uvicorn
|
| 221 |
uvicorn.run("app:app", host="0.0.0.0", port=7860, reload=True)
|
| 222 |
+
|