File size: 7,281 Bytes
59f824e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c4808
 
 
 
 
 
59f824e
 
 
 
 
 
 
d7c4808
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59f824e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fcb4a0
 
cb0dba7
 
 
 
 
 
1fcb4a0
59f824e
 
1fcb4a0
 
 
 
59f824e
1fcb4a0
59f824e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import tempfile
import logging
from typing import Optional

from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware

from src.pipeline import DeceptionPipeline
from src.utils.config import get_default_config

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(
    title="Deception Analysis API", 
    description="API for Explainable Multimodal Deception Analysis for Mobile Apps"
)

# Enable CORS so the Flutter app can connect easily
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Global pipeline instance
pipeline = None

@app.on_event("startup")
async def startup_event():
    global pipeline
    try:
        logger.info("Initializing Deception ML Pipeline...")
        config = get_default_config()
        pipeline = DeceptionPipeline(config)
        
        # Load the pre-trained model if it exists
        model_path = os.path.join("models", "deception_model.pkl")
        if os.path.exists(model_path):
            pipeline.load_model(model_path)
            logger.info("Pre-trained model loaded successfully.")
            
            # Also load calibrator profiles
            calib_path = os.path.join("models", "subject_calibrator.json")
            if os.path.exists(calib_path):
                pipeline.calibrator.load_profiles(calib_path)
                logger.info(f"Loaded calibration profiles from {calib_path}")
        else:
            logger.warning(f"No pre-trained model found at {model_path}. You must generate it first!")
            
        logger.info("Pipeline initialized successfully.")
    except Exception as e:
        logger.error(f"Failed to initialize pipeline: {e}")

@app.post("/calibrate")
async def calibrate_subject_endpoint(
    file: UploadFile = File(...),
    subject_id: str = Form(...)
):
    if not pipeline:
        raise HTTPException(status_code=500, detail="ML Pipeline not initialized yet")

    # Create temporary directory
    temp_dir = tempfile.mkdtemp(prefix="deception_calib_")
    video_path = os.path.join(temp_dir, file.filename)

    try:
        # Save video
        with open(video_path, "wb") as f:
            content = await file.read()
            f.write(content)

        logger.info(f"CALIBRATING subject: {subject_id}")

        # Extract features from the TRUTHFUL video
        facial_df = pipeline.facial_extractor.process_video(video_path)
        
        # Extract audio features
        audio_temp = os.path.join(temp_dir, "audio.wav")
        from src.utils.io import extract_audio_from_video
        audio_path = extract_audio_from_video(video_path, audio_temp)
        audio_df = pipeline.audio_extractor.process_audio_segments(str(audio_path), segment_duration=2.0)

        # Fuse
        aligned_df = pipeline.fusion.align_features(facial_df, audio_df, video_fps=pipeline.config.features.fps)
        fused_df = pipeline.fusion.extract_fusion_features(aligned_df)

        # Add to subject calibrator
        pipeline.calibrator.add_subject_profile(subject_id, fused_df)
        
        # Save profiles to disk so they persist after restart
        calib_path = os.path.join("models", "subject_calibrator.json")
        pipeline.calibrator.save_profiles(calib_path)

        return {
            "status": "success",
            "message": f"Calibration complete for {subject_id}",
            "frames_analyzed": len(fused_df)
        }

    except Exception as e:
        logger.error(f"Calibration failed: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Calibration failed: {str(e)}")
    finally:
        try:
            if os.path.exists(video_path): os.remove(video_path)
            os.rmdir(temp_dir)
        except: pass

@app.post("/analyze")
async def analyze_video_endpoint(
    file: UploadFile = File(...),
    subject_id: Optional[str] = Form(None)
):
    if not pipeline:
        raise HTTPException(status_code=500, detail="ML Pipeline not initialized yet")

    # Create temporary directory for the uploaded video
    temp_dir = tempfile.mkdtemp(prefix="deception_api_")
    video_path = os.path.join(temp_dir, file.filename)

    try:
        # Save uploaded video to disk
        with open(video_path, "wb") as f:
            content = await file.read()
            f.write(content)

        logger.info(f"Analyzing video: {file.filename} (Subject: {subject_id})")

        # Run pipeline
        result = pipeline.analyze_video(
            video_path=video_path,
            subject_id=subject_id,
            generate_visualizations=False, # We don't need Matplotlib images, just JSON data
            output_dir=temp_dir
        )

        if "error" in result:
            raise HTTPException(status_code=400, detail=result["error"])

        # Format clean JSON response for the Flutter app
        raw_prob = result.get("deception_probability", 0.5)
        
        # PARANOID BOOST: Apply an aggressive power curve (p^0.3)
        # This shifts 0.1 -> 0.5 (making it deceptive) and 0.03 -> 0.35
        boosted_prob = float(pow(raw_prob, 0.3))
        
        # Lower the verdict threshold to 0.35 for high sensitivity
        verdict = "deceptive" if boosted_prob >= 0.35 else "truthful"

        response_data = {
            "status": "success",
            "prediction": verdict,
            "verdict": verdict, 
            "raw_probability": raw_prob,
            "probability": boosted_prob,
            "confidence": result.get("confidence", 0.0),
            "is_deceptive": verdict == "deceptive",
        }

        # Add temporal analysis (to draw the timeline graph in Flutter)
        if "temporal_analysis" in result:
            response_data["temporal"] = {
                "timestamps": result["temporal_analysis"].get("timestamps", []),
                "probabilities": result["temporal_analysis"].get("probability_trajectory", []),
                "suspicious_intervals": result["temporal_analysis"].get("suspicious_intervals", [])
            }

        # Add SHAP explainability (to draw the Feature Importance chart in Flutter)
        if "explanation" in result:
            fi = result["explanation"].get("feature_importance", {})
            top_indicators = [{"feature": k, "impact": v} for k, v in list(fi.items())[:5]]
            
            response_data["explanation"] = {
                "top_indicators": top_indicators,
                "feature_importance": fi,
                "behavioral_explanations": result["explanation"].get("behavioral_explanations", {})
            }

        return JSONResponse(content=response_data)

    except Exception as e:
        logger.error(f"Analysis failed: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")
    finally:
        # Clean up the heavy video file to save server storage
        try:
            if os.path.exists(video_path):
                os.remove(video_path)
            os.rmdir(temp_dir)
        except:
            pass

@app.get("/health")
async def health_check():
    return {"status": "online", "pipeline_ready": pipeline is not None}