File size: 2,447 Bytes
f5c2b96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import re
from fastapi import Request
import math

def get_ip(request: Request) -> str:
    forwarded = request.headers.get("X-Forwarded-For")
    if forwarded:
        return forwarded.split(",")[0].strip()
    return request.client.host if request.client else "unknown"

def is_default_key(key: str, default: str) -> bool:
    if not key or not default:
        return False
    return key.strip() == default.strip()

def get_cloudinary_creds(url: str) -> dict:
    if not url or not url.startswith("cloudinary://"):
        return {}
    try:
        creds = url.replace("cloudinary://", "")
        auth, cloud_name = creds.split("@")
        api_key, api_secret = auth.split(":")
        return {
            "cloud_name": cloud_name,
            "api_key": api_key,
            "api_secret": api_secret
        }
    except ValueError:
        return {}

def sanitize_filename(filename: str) -> str:
    if not filename:
        return "unnamed_file"
    return re.sub(r'[^a-zA-Z0-9_\-\.]', '_', filename)

def standardize_category_name(name: str) -> str:
    if not name:
        return "uncategorized"
    return re.sub(r'[^a-zA-Z0-9_\-]', '_', name.lower())

def to_list(vector) -> list[float]:
    try:
        return [float(x) for x in vector]
    except TypeError:
        return []

def url_to_public_id(url: str) -> str:
    if not url:
        return ""
    try:
        parts = url.split("/upload/")
        if len(parts) > 1:
            path = parts[1].split("/", 1)[-1]
            return path.rsplit(".", 1)[0]
        return ""
    except Exception:
        return ""

def cld_thumb_url(url: str) -> str:
    """Generates a fast-loading thumbnail preserving the original uncropped image."""
    if not url:
        return ""
    # c_limit,w_500 scales the image down for speed but keeps the entire original frame
    return url.replace("/upload/", "/upload/c_limit,w_500/")

import math

def face_ui_score(raw_score: float) -> float:
    """
    Converts raw cosine similarity into a mathematically calibrated 
    Probability of Match using a Sigmoid function (Platt Scaling).
    """
    # Shifted the center up to 0.50 (Standard strict threshold for ArcFace ResNet100)
    threshold = 0.50  
    
    # Increased 'k' to 18.0 to create a very sharp drop-off for imposters
    k = 18.0          
    
    probability = 1 / (1 + math.exp(-k * (raw_score - threshold)))
    
    return min(1.0, max(0.0, round(probability, 4)))