File size: 6,779 Bytes
efeddde
 
 
 
 
 
 
 
 
 
 
 
62711a0
efeddde
 
 
62711a0
 
efeddde
 
 
 
 
 
 
 
 
 
 
 
62711a0
efeddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62711a0
efeddde
 
 
 
 
 
 
fb6c3fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
efeddde
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62711a0
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
import base64
import os
import uuid
from pathlib import Path
from typing import Optional

from fastapi import FastAPI, File, UploadFile, HTTPException, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
from pydantic import BaseModel

from app.pipeline import FaceIDPipeline
from blockchain.blockchain import LocalBlockchain

app = FastAPI(
    title="FaceID API",
    description="FaceID: Biometric Provenance, OSINT Social Attribution & Dual-Layer Blockchain Forensic API",
    version="2.0.0",
)

# Enable CORS for local development
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

pipeline = FaceIDPipeline()
local_chain = LocalBlockchain()

UPLOAD_DIR = Path("data/input")
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)

class Base64ImageRequest(BaseModel):
    image_base64: str
    write_blockchain: Optional[bool] = False
    threshold: Optional[float] = None
    top_k: Optional[int] = None

@app.get("/health")
@app.get("/api/health")
def health_check():
    valid, err = local_chain.is_valid_chain()
    return {
        "status": "online",
        "service": "FaceID Forensic API",
        "version": "2.0.0",
        "blockchain_layer1": {
            "valid": valid,
            "chain_length": len(local_chain),
        },
    }

@app.get("/api/diagnose")
def diagnose_system():
    diag = {}
    try:
        import psutil
        mem = psutil.virtual_memory()
        diag["memory_total_mb"] = round(mem.total / 1024 / 1024, 1)
        diag["memory_available_mb"] = round(mem.available / 1024 / 1024, 1)
    except Exception as e:
        diag["memory_error"] = str(e)

    diag["serpapi_configured"] = bool(os.getenv("SERPAPI_API_KEY") or os.getenv("SERPAPI_KEY"))
    diag["sepolia_rpc_configured"] = bool(os.getenv("RPC_URL"))
    diag["wallet_configured"] = bool(os.getenv("WALLET_ADDRESS"))
    diag["private_key_configured"] = bool(os.getenv("PRIVATE_KEY"))

    try:
        import cv2
        import numpy as np
        dummy = np.zeros((100, 100, 3), dtype=np.uint8)
        diag["opencv_numpy"] = "OK"
    except Exception as e:
        diag["opencv_numpy"] = str(e)

    try:
        valid, err = local_chain.is_valid_chain()
        diag["blockchain"] = {"valid": valid, "length": len(local_chain), "err": err}
    except Exception as e:
        diag["blockchain_error"] = str(e)

    try:
        enc = pipeline.face_encoder
        enc._load()
        emb, info = enc.get_embedding(dummy)
        diag["face_encoder"] = {"status": "OK", "model": enc.model_name, "info": info}
    except Exception as e:
        diag["face_encoder_error"] = str(e)

    try:
        df = pipeline.deepfake_classifier
        from PIL import Image
        pil_dummy = Image.fromarray(dummy)
        res = df.analyze(pil_dummy)
        diag["deepfake_classifier"] = {"status": "OK", "model": res.get("model")}
    except Exception as e:
        diag["deepfake_classifier_error"] = str(e)

    return diag

@app.post("/analyse")
@app.post("/api/verify")
async def analyse_image(
    file: UploadFile = File(...),
    write_blockchain: bool = False,
    threshold: Optional[float] = Query(None, description="Cosine similarity threshold"),
    top_k: Optional[int] = Query(None, description="Max candidate results to inspect"),
):
    """
    Primary investigative endpoint:
    Uploads an image, extracts 512-D ArcFace embedding, runs live Google Lens visual search,
    re-verifies candidate faces with cosine similarity, isolates social post URLs,
    runs ViT deepfake risk evaluation, deterministically hashes evidence,
    and logs to Layer 1 local blockchain (+ optional Layer 2 Sepolia).
    """
    try:
        file_ext = Path(file.filename).suffix or ".jpg"
        temp_filename = f"upload_{uuid.uuid4().hex[:8]}{file_ext}"
        temp_path = UPLOAD_DIR / temp_filename

        contents = await file.read()
        temp_path.write_bytes(contents)

        if threshold is not None:
            pipeline.similarity_threshold = float(threshold)

        result = pipeline.run(
            image_path=temp_path,
            write_blockchain=write_blockchain,
            max_results=top_k,
            verbose=False,
        )

        return JSONResponse(content=result)
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc))

@app.post("/api/verify-base64")
async def verify_image_base64(req: Base64ImageRequest):
    """
    Webcam live capture endpoint.
    """
    try:
        b64_data = req.image_base64
        if "," in b64_data:
            b64_data = b64_data.split(",", 1)[1]

        image_bytes = base64.b64decode(b64_data)
        temp_filename = f"webcam_{uuid.uuid4().hex[:8]}.jpg"
        temp_path = UPLOAD_DIR / temp_filename
        temp_path.write_bytes(image_bytes)

        if req.threshold is not None:
            pipeline.similarity_threshold = float(req.threshold)

        result = pipeline.run(
            image_path=temp_path,
            write_blockchain=req.write_blockchain,
            max_results=req.top_k,
            verbose=False,
        )

        return JSONResponse(content=result)
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc))

@app.get("/chain")
def get_blockchain_ledger():
    """
    Fetch the entire local cryptographically linked hash ledger and validation status.
    """
    valid, err = local_chain.is_valid_chain()
    return {
        "status": "VALID" if valid else "INVALID",
        "error": err,
        "chain_length": len(local_chain),
        "blocks": local_chain.get_chain(),
    }

@app.get("/verify/{evidence_hash}")
def verify_hash_in_chain(evidence_hash: str):
    """
    Verify if a specific SHA-256 evidence hash exists within a mathematically valid local block.
    """
    valid, err = local_chain.is_valid_chain()
    block = local_chain.verify_evidence_hash(evidence_hash)
    if not block:
        raise HTTPException(status_code=404, detail=f"Evidence hash {evidence_hash} not found in blockchain ledger.")

    return {
        "verified": valid,
        "match": True,
        "evidence_hash": evidence_hash,
        "block": block,
    }

# Mount static directory for forensic terminal web interface
static_dir = Path(__file__).parent / "static"
static_dir.mkdir(parents=True, exist_ok=True)
app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")

@app.get("/")
def serve_index():
    index_file = static_dir / "index.html"
    if index_file.exists():
        return FileResponse(str(index_file))
    return {"message": "FaceID Forensic API is running. Web UI not found."}