File size: 5,743 Bytes
aa24466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
FastAPI backend for Face Analysis HF Space.

Provides:
- Static file serving for the React SPA (from /app/dist)
- /api/norms — returns demographic ideal ranges (from HF Dataset or local fallback)
- /api/upload — stores analysis result to HF Storage Bucket
- /api/percentile — returns percentile rank from stored distribution
"""

import json
import os
import uuid
from pathlib import Path
from typing import Optional

from fastapi import FastAPI, HTTPException
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
from huggingface_hub import HfApi, create_commit, upload_file
from pydantic import BaseModel

app = FastAPI(title="Face Analysis API")

HF_TOKEN = os.environ.get("HF_TOKEN", "")
SPACE_ID = os.environ.get("SPACE_ID", "asterioskryos/face-analysis")
API = HfApi(token=HF_TOKEN) if HF_TOKEN else None

# ---------------------------------------------------------------------------
# Norms: loaded from HF Dataset or local fallback
# ---------------------------------------------------------------------------

NORMS_PATH = Path("/app/server/data/norms.json")
NORMS: dict = {}

def _load_norms():
    global NORMS
    if NORMS_PATH.exists():
        NORMS = json.loads(NORMS_PATH.read_text())
        return
    # Fallback: bundled defaults
    NORMS = {
        "caucasian": {
            "male": {},
            "female": {},
        },
        "african": {
            "male": {
                "nose.alarWidth": {"ideal_adj": 0.03, "mult_adj": 0.9},
                "nose.nasalTipRotation": {"ideal_adj": -5, "mult_adj": 1.0},
                "lips.upperToLowerRatio": {"ideal_adj": 0.05, "mult_adj": 0.9},
            },
            "female": {
                "nose.alarWidth": {"ideal_adj": 0.03, "mult_adj": 0.9},
                "nose.nasalTipRotation": {"ideal_adj": -3, "mult_adj": 1.0},
            },
        },
        "east-asian": {
            "male": {
                "eyes.eyeAspectRatio": {"ideal_adj": 0.02, "mult_adj": 0.95},
                "nose.nasofrontalAngle": {"ideal_adj": 5, "mult_adj": 1.0},
                "profile.facialConvexity": {"ideal_adj": 4, "mult_adj": 1.0},
            },
            "female": {
                "eyes.eyeAspectRatio": {"ideal_adj": 0.03, "mult_adj": 0.95},
                "nose.nasofrontalAngle": {"ideal_adj": 5, "mult_adj": 1.0},
                "profile.facialConvexity": {"ideal_adj": 4, "mult_adj": 1.0},
            },
        },
    }

_load_norms()

class NormsRequest(BaseModel):
    ethnicity: str = "caucasian"
    sex: str = "male"
    ageGroup: str = "20-30"

@app.post("/api/norms")
async def get_norms(req: NormsRequest):
    """Return per-metric ideal adjustments for a given demographic profile."""
    ethnic = NORMS.get(req.ethnicity, {})
    sex_table = ethnic.get(req.sex, {})
    return JSONResponse(content=sex_table)

# ---------------------------------------------------------------------------
# Upload to HF Storage Bucket
# ---------------------------------------------------------------------------

class UploadRequest(BaseModel):
    image_data: Optional[str] = None  # base64 encoded
    scores: dict = {}

@app.post("/api/upload")
async def upload_result(req: UploadRequest):
    """Store an analysis result to HF Storage Bucket for percentile tracking."""
    if not API:
        raise HTTPException(503, "HF API not configured (no token)")

    result_id = str(uuid.uuid4())[:8]
    result_path = f"results/{result_id}.json"

    payload = {
        "id": result_id,
        "scores": req.scores,
        "demographics": {
            "ethnicity": "unknown",
            "sex": "unknown",
            "ageGroup": "unknown",
        },
    }

    try:
        API.upload_file(
            path_or_fileobj=json.dumps(payload).encode(),
            path_in_repo=result_path,
            repo_id=SPACE_ID,
            repo_type="space",
        )
        return {"status": "ok", "id": result_id, "path": result_path}
    except Exception as e:
        raise HTTPException(500, f"Upload failed: {e}")

# ---------------------------------------------------------------------------
# Percentile (from stored results or simulated)
# ---------------------------------------------------------------------------

@app.get("/api/percentile")
async def get_percentile(score: float = 5.0):
    """Return approximate percentile rank for a given overall score."""
    # In production, query stored results for real percentile.
    # For now, approximate using a normal distribution centered on 5.5 with SD 1.5.
    import math
    z = (score - 5.5) / 1.5
    percentile = round(0.5 * (1 + math.erf(z / math.sqrt(2))) * 100, 1)
    return {"score": score, "percentile": percentile, "note": "Approximate (population model)"}

# ---------------------------------------------------------------------------
# Health / status
# ---------------------------------------------------------------------------

@app.get("/api/health")
async def health():
    return {"status": "ok", "api": "v1"}

# ---------------------------------------------------------------------------
# Static file serving for React SPA (Vite build output)
# ---------------------------------------------------------------------------

if Path("/app/dist").exists():
    app.mount("/", StaticFiles(directory="/app/dist", html=True), name="dist")
else:
    @app.get("/")
    async def root():
        return {"error": "Frontend not built. Run `npm run build` first."}

# ---------------------------------------------------------------------------
# Entrypoint
# ---------------------------------------------------------------------------

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)