Repository navigation
Expand file tree
/
Copy pathapi.py
More file actions
152 lines (122 loc) · 4.86 KB
/
Copy pathapi.py
File metadata and controls
152 lines (122 loc) · 4.86 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
"""
api.py
FastAPI wrapper around the CNN + RAG pipeline.
Usage: uvicorn api:app --reload
Curl example for testing:
curl -X POST "http://localhost:8000/predict" -F "file=@path/to/image.jpg"
"""
from pathlib import Path
from tempfile import gettempdir
from typing import Any
import shutil
import uuid
from fastapi import FastAPI, File, HTTPException, UploadFile # type: ignore[reportMissingImports]
from fastapi.middleware.cors import CORSMiddleware # type: ignore[reportMissingImports]
from fastapi.responses import JSONResponse # type: ignore[reportMissingImports]
from predict import load_model, predict
from rag import RAGPipeline
app = FastAPI(title="Deepfake Detection API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Lazy-loaded globals — loaded on first request, not at startup
_model: Any | None = None
_rag: RAGPipeline | None = None
def get_model() -> Any:
global _model
if _model is None:
_model = load_model()
return _model
def get_rag() -> RAGPipeline:
global _rag
if _rag is None:
_rag = RAGPipeline()
_rag.load()
return _rag
# health check endpoint
@app.get("/")
def root():
return {"status": "ok", "message": "Deepfake Detection API is running"}
# main predict endpoint
@app.post("/predict")
async def predict_image(file: UploadFile = File(...)):
"""Upload an image, get back label, confidence, and RAG explanation."""
filename = file.filename or ""
if not filename.lower().endswith((".jpg", ".jpeg", ".png")):
raise HTTPException(
status_code=400, detail="Invalid file type. Only jpg/jpeg/png allowed."
)
temporary_path = Path(gettempdir()) / f"{uuid.uuid4().hex}_{Path(filename).name}"
with open(temporary_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
try:
result = predict(str(temporary_path), get_model())
label = result["label"]
confidence = result["confidence"] / 100
# The verdict comes from the CNN alone. If the explanation step fails (Groq down, model retired,
# key expired), still return the verdict rather than a 500.
try:
explanation = get_rag().explain(label.upper(), confidence)
except Exception as error: # noqa: BLE001
print(f"explanation failed: {type(error).__name__}: {error}")
explanation = None
return JSONResponse(
{
"label": label,
"confidence": result["confidence"],
"explanation": explanation,
}
)
finally:
temporary_path.unlink(missing_ok=True)
# """
# api.py
# FastAPI wrapper around the CNN + RAG pipeline.
# Usage: uvicorn api:app --reload
# Curl example for testing:
# curl -X POST "http://localhost:8000/predict -F "file=@path/to/image.jpg"
# """
# from fastapi import FastAPI, File, UploadFile, HTTPException
# from fastapi.responses import JSONResponse
# import shutil
# import os
# import uuid # generates unique IDs for temp files so that parallel requests don't conflict/clash
# from predict import load_model, predict
# from rag import RAGPipeline
# app = FastAPI(title = "Deepfake Detection API")
# # Loading the model and RAG once at startup - not on every request
# model = load_model()
# rag = RAGPipeline()
# rag.load()
# # health check endpoint
# @app.get("/")
# def root():
# return {"status": "ok", "message": "Deepfake Detection API is running"}
# # main predict endpoint
# @app.post("/predict")
# async def predict_image(file: UploadFile = File(...)):
# """Upload an image, get back label, confidence, and RAG explanation."""
# # validate file type
# if not file.filename.endswith((".jpg", ".jpeg", ".png")):
# raise HTTPException(status_code=400, detail="Invalid file type. Only jpg/jpeg/png allowed.")
# # save uploaded file to a temp location
# temporary_path = f"/tmp/{uuid.uuid4().hex}_{file.filename}"
# with open(temporary_path, "wb") as buffer:
# shutil.copyfileobj(file.file, buffer) # streams the file to disk in chunks, instead of loading whole file into memory at once
# try:
# # Step 1: Xcepttion classifies the image
# result = predict(temporary_path, model)
# label = result['label']
# confidence = result['confidence'] / 100 # 0-1 for RAG prompt formatting
# # Step 2: RAG explains the prediction using research papers
# explanation = rag.explain(label.upper(), confidence) # upper for 'fake'/'real' to match prompt formatting 'FAKE'/'REAL'
# return JSONResponse({
# "label" : label,
# "confidence": result['confidence'],
# "explanation": explanation
# })
# finally:
# os.remove(temporary_path) # always runs, even if something above crashes. Ensures we don't fill up disk with temp files.