HariLogicgo commited on
Commit
31384f7
·
1 Parent(s): 88e5de6

/api usage added

Browse files
Files changed (1) hide show
  1. app.py +32 -2
app.py CHANGED
@@ -7,6 +7,7 @@ import numpy as np
7
  import threading
8
  import subprocess
9
  import logging
 
10
 
11
  import insightface
12
  from insightface.app import FaceAnalysis
@@ -126,6 +127,18 @@ def verify_token(credentials: HTTPAuthorizationCredentials = Security(security))
126
  raise HTTPException(status_code=401, detail="Invalid or missing token")
127
  return credentials.credentials
128
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  # --------------------- Face Swap Pipeline ---------------------
130
  swap_lock = threading.Lock()
131
 
@@ -224,14 +237,18 @@ class FaceSwapRequest(BaseModel):
224
  source_id: str
225
  target_id: str
226
 
227
- @fastapi_app.post("/faceswap", dependencies=[Depends(verify_token)])
228
- async def perform_faceswap(request: FaceSwapRequest):
 
 
 
229
  try:
230
  src_stream = await fs_bucket.open_download_stream(ObjectId(request.source_id))
231
  src_bytes = await src_stream.read()
232
  tgt_stream = await fs_bucket.open_download_stream(ObjectId(request.target_id))
233
  tgt_bytes = await tgt_stream.read()
234
  except Exception:
 
235
  raise HTTPException(status_code=404, detail="Source or Target not found")
236
 
237
  src_array = np.frombuffer(src_bytes, np.uint8)
@@ -240,6 +257,7 @@ async def perform_faceswap(request: FaceSwapRequest):
240
  tgt_bgr = cv2.imdecode(tgt_array, cv2.IMREAD_COLOR)
241
 
242
  if src_bgr is None or tgt_bgr is None:
 
243
  raise HTTPException(status_code=400, detail="Invalid image data")
244
 
245
  src_rgb = cv2.cvtColor(src_bgr, cv2.COLOR_BGR2RGB)
@@ -247,12 +265,17 @@ async def perform_faceswap(request: FaceSwapRequest):
247
 
248
  final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
249
  if err:
 
250
  raise HTTPException(status_code=500, detail=err)
251
 
252
  with open(final_path, "rb") as f:
253
  final_bytes = f.read()
254
 
255
  result_id = await fs_bucket.upload_from_stream("enhanced.png", final_bytes, metadata={"type": "result"})
 
 
 
 
256
  return {"result_id": str(result_id)}
257
 
258
  @fastapi_app.get("/download/{result_id}", dependencies=[Depends(verify_token)])
@@ -269,6 +292,13 @@ async def download_result(result_id: str):
269
  headers={"Content-Disposition": "attachment; filename=result.png"}
270
  )
271
 
 
 
 
 
 
 
 
272
  # --------------------- Mount Gradio ---------------------
273
  fastapi_app = mount_gradio_app(fastapi_app, demo, path="/gradio")
274
 
 
7
  import threading
8
  import subprocess
9
  import logging
10
+ from datetime import datetime
11
 
12
  import insightface
13
  from insightface.app import FaceAnalysis
 
127
  raise HTTPException(status_code=401, detail="Invalid or missing token")
128
  return credentials.credentials
129
 
130
+ # --------------------- Logging Helper ---------------------
131
+ async def log_faceswap_hit(token: str, status: str = "success"):
132
+ if not database:
133
+ return
134
+ log_entry = {
135
+ "endpoint": "/faceswap",
136
+ "token": token,
137
+ "status": status,
138
+ "timestamp": datetime.utcnow()
139
+ }
140
+ await database.api_logs.insert_one(log_entry)
141
+
142
  # --------------------- Face Swap Pipeline ---------------------
143
  swap_lock = threading.Lock()
144
 
 
237
  source_id: str
238
  target_id: str
239
 
240
+ @fastapi_app.post("/faceswap")
241
+ async def perform_faceswap(
242
+ request: FaceSwapRequest,
243
+ credentials: HTTPAuthorizationCredentials = Security(security)
244
+ ):
245
  try:
246
  src_stream = await fs_bucket.open_download_stream(ObjectId(request.source_id))
247
  src_bytes = await src_stream.read()
248
  tgt_stream = await fs_bucket.open_download_stream(ObjectId(request.target_id))
249
  tgt_bytes = await tgt_stream.read()
250
  except Exception:
251
+ await log_faceswap_hit(credentials.credentials, status="not_found")
252
  raise HTTPException(status_code=404, detail="Source or Target not found")
253
 
254
  src_array = np.frombuffer(src_bytes, np.uint8)
 
257
  tgt_bgr = cv2.imdecode(tgt_array, cv2.IMREAD_COLOR)
258
 
259
  if src_bgr is None or tgt_bgr is None:
260
+ await log_faceswap_hit(credentials.credentials, status="bad_request")
261
  raise HTTPException(status_code=400, detail="Invalid image data")
262
 
263
  src_rgb = cv2.cvtColor(src_bgr, cv2.COLOR_BGR2RGB)
 
265
 
266
  final_img, final_path, err = face_swap_and_enhance(src_rgb, tgt_rgb)
267
  if err:
268
+ await log_faceswap_hit(credentials.credentials, status="failed")
269
  raise HTTPException(status_code=500, detail=err)
270
 
271
  with open(final_path, "rb") as f:
272
  final_bytes = f.read()
273
 
274
  result_id = await fs_bucket.upload_from_stream("enhanced.png", final_bytes, metadata={"type": "result"})
275
+
276
+ # ✅ Log successful request
277
+ await log_faceswap_hit(credentials.credentials, status="success")
278
+
279
  return {"result_id": str(result_id)}
280
 
281
  @fastapi_app.get("/download/{result_id}", dependencies=[Depends(verify_token)])
 
292
  headers={"Content-Disposition": "attachment; filename=result.png"}
293
  )
294
 
295
+ # --------------------- Stats Endpoint ---------------------
296
+ @fastapi_app.get("/stats", dependencies=[Depends(verify_token)])
297
+ async def get_stats(credentials: HTTPAuthorizationCredentials = Security(security)):
298
+ token = credentials.credentials
299
+ count = await database.api_logs.count_documents({"endpoint": "/faceswap", "token": token})
300
+ return {"token": token, "faceswap_calls": count}
301
+
302
  # --------------------- Mount Gradio ---------------------
303
  fastapi_app = mount_gradio_app(fastapi_app, demo, path="/gradio")
304