File size: 7,147 Bytes
368e1c4
 
 
 
c9fd5f9
368e1c4
c9fd5f9
 
 
 
 
368e1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9fd5f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368e1c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c9fd5f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
from contextlib import asynccontextmanager
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Annotated
from typing import Any

from pydantic import BaseModel, Field

from genai_service import (
    generate_detection_analysis
)
import tensorflow as tf
from fastapi import (
    FastAPI,
    File,
    Form,
    HTTPException,
    UploadFile
)

from custom_layers import (
    AdaptiveAvgPool1D,
    AdaptiveAvgPool2D
)

from inference import predict_audio


# ============================================================
# CONFIGURATION
# ============================================================

MODEL_PATH = Path(
    "best_torchlike_mfcc_waveform_model.keras"
)

ALLOWED_EXTENSIONS = {
    ".wav",
    ".mp3",
    ".flac",
    ".ogg",
    ".m4a"
}

MAX_FILE_SIZE_MB = 20
MAX_FILE_SIZE_BYTES = (
    MAX_FILE_SIZE_MB
    * 1024
    * 1024
)

model: tf.keras.Model | None = None


# ============================================================
# LOAD MODEL ON STARTUP
# ============================================================

@asynccontextmanager
async def lifespan(app: FastAPI):
    global model

    if not MODEL_PATH.exists():
        raise FileNotFoundError(
            f"Model tidak ditemukan: {MODEL_PATH}"
        )

    print("Loading model...")

    model = tf.keras.models.load_model(
        MODEL_PATH,
        custom_objects={
            "AdaptiveAvgPool1D": AdaptiveAvgPool1D,
            "AdaptiveAvgPool2D": AdaptiveAvgPool2D
        },
        compile=False
    )

    print("Model loaded successfully.")

    yield

    model = None


# ============================================================
# FASTAPI APP
# ============================================================

app = FastAPI(
    title="Deepfake Audio Detection API",
    description=(
        "REST API untuk mendeteksi audio real atau fake "
        "menggunakan model MFCC + Waveform."
    ),
    version="1.0.0",
    lifespan=lifespan
)


# ============================================================
# GENERATIVE AI REQUEST SCHEMA
# ============================================================

class DetectionAnalysisRequest(BaseModel):
    prediction: str = Field(
        pattern="^(real|fake)$"
    )

    threshold: float = Field(
        ge=0.0,
        le=1.0
    )

    total_clips: int = Field(
        ge=1
    )

    real_clips: int = Field(
        ge=0
    )

    fake_clips: int = Field(
        ge=0
    )

    average_probability_real: float = Field(
        ge=0.0,
        le=1.0
    )

    average_probability_fake: float = Field(
        ge=0.0,
        le=1.0
    )

    
# ============================================================
# ROUTES
# ============================================================

@app.get("/")
def root():
    return {
        "message": "Deepfake Audio Detection API",
        "status": "running",
        "docs": "/docs",
        "predict_endpoint": "/predict",
        "default_threshold": 0.60
    }


@app.get("/health")
def health():
    return {
        "status": (
            "healthy"
            if model is not None
            else "model_not_loaded"
        ),
        "model_loaded": model is not None
    }


@app.post("/predict")
async def predict(
    file: Annotated[
        UploadFile,
        File(
            description=(
                "File audio dengan format WAV, MP3, "
                "FLAC, OGG, atau M4A."
            )
        )
    ],
    threshold: Annotated[
        float,
        Form(
            ge=0.0,
            le=1.0,
            description=(
                "Audio dianggap fake jika probability_fake "
                "lebih besar atau sama dengan threshold."
            )
        )
    ] = 0.60
):
    """
    Prediksi apakah audio termasuk real atau fake.

    Default threshold:
        0.60

    Threshold dapat diubah pada setiap request.
    """

    if model is None:
        raise HTTPException(
            status_code=503,
            detail="Model belum siap digunakan."
        )

    original_filename = file.filename or "uploaded_audio.wav"

    suffix = Path(
        original_filename
    ).suffix.lower()

    if suffix not in ALLOWED_EXTENSIONS:
        raise HTTPException(
            status_code=400,
            detail=(
                "Format audio tidak didukung. "
                "Gunakan WAV, MP3, FLAC, OGG, atau M4A."
            )
        )

    file_content = await file.read()

    if len(file_content) == 0:
        raise HTTPException(
            status_code=400,
            detail="File audio kosong."
        )

    if len(file_content) > MAX_FILE_SIZE_BYTES:
        raise HTTPException(
            status_code=413,
            detail=(
                f"Ukuran file terlalu besar. "
                f"Maksimal {MAX_FILE_SIZE_MB} MB."
            )
        )

    temp_path: Path | None = None

    try:
        with NamedTemporaryFile(
            delete=False,
            suffix=suffix
        ) as temp_file:
            temp_file.write(file_content)

            temp_path = Path(
                temp_file.name
            )

        result = predict_audio(
            model=model,
            file_path=temp_path,
            threshold=threshold
        )

        return {
            "filename": original_filename,
            **result
        }

    except ValueError as error:
        raise HTTPException(
            status_code=400,
            detail=str(error)
        ) from error

    except Exception as error:
        raise HTTPException(
            status_code=500,
            detail=f"Inference gagal: {str(error)}"
        ) from error

    finally:
        if (
            temp_path is not None
            and temp_path.exists()
        ):
            temp_path.unlink()


# ============================================================
# GENERATIVE AI ANALYSIS ENDPOINT
# ============================================================

@app.post("/generate-analysis")
def generate_analysis(
    request: DetectionAnalysisRequest
):
    """
    Membuat penjelasan hasil prediksi menggunakan Gemini API.

    Endpoint ini merupakan fitur sekunder.
    Label prediksi tetap berasal dari model TensorFlow.
    """

    if (
        request.real_clips
        + request.fake_clips
        != request.total_clips
    ):
        raise HTTPException(
            status_code=400,
            detail=(
                "Jumlah real_clips dan fake_clips "
                "harus sama dengan total_clips."
            )
        )

    try:
        analysis = generate_detection_analysis(
            detection_result=(
                request.model_dump()
            )
        )

        return {
            "prediction": request.prediction,
            "analysis": analysis
        }

    except RuntimeError as error:
        raise HTTPException(
            status_code=503,
            detail=str(error)
        ) from error

    except Exception as error:
        raise HTTPException(
            status_code=500,
            detail=(
                "Gagal membuat analisis AI: "
                f"{str(error)}"
            )
        ) from error