File size: 3,533 Bytes
49a46c9
 
 
 
 
 
 
 
c63cbf0
 
 
 
49a46c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c63cbf0
 
49a46c9
 
 
 
 
 
c63cbf0
 
 
eaa52cd
c63cbf0
 
eaa52cd
 
 
 
c63cbf0
 
 
 
eaa52cd
 
 
 
 
 
 
 
 
 
c63cbf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49a46c9
 
 
 
 
 
 
 
 
 
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
import os
import requests
import cv2
import numpy as np

BASE_URL = os.environ.get(
    "ID_API_URL",
    "http://127.0.0.1:8082"
).rstrip("/")
# ponytail: tolerate /api suffix (website env has it, this code adds it)
if BASE_URL.endswith("/api"):
    BASE_URL = BASE_URL[:-len("/api")]

ENDPOINTS = {
    "id": f"{BASE_URL}/api/check_id",
    "credit": f"{BASE_URL}/api/check_credit",
    "mrz": f"{BASE_URL}/api/check_mrz",
}


def _load_image(image):
    if image is None:
        return None
    if isinstance(image, str):
        img = cv2.imread(image)
        if img is None:
            return None
        return img
    return image


def _check_document(image, endpoint_key: str) -> dict:
    img = _load_image(image)
    if img is None:
        return {"error": "No image provided"}

    success, img_encoded = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 95])
    if not success:
        return {"error": "Failed to encode image"}

    url = ENDPOINTS.get(endpoint_key)
    if not url:
        return {"error": f"Unknown endpoint: {endpoint_key}"}

    try:
        response = requests.post(
            url,
            files={"image": ("image.jpg", img_encoded.tobytes(), "image/jpeg")},
            timeout=30
        )
        response.raise_for_status()
        return response.json()
    except requests.exceptions.ConnectionError as e:
        return {"error": f"Cannot connect to server at {BASE_URL}: {e}. Make sure the SDK server is running."}
    except requests.exceptions.Timeout:
        return {"error": "Request timed out"}
    except requests.exceptions.RequestException as e:
        return {"error": f"API request failed: {str(e)}"}


def diagnose() -> dict:
    # ponytail: one function shows where HF->server path breaks
    import socket
    import time
    from urllib.parse import urlparse
    out = {"base_url": BASE_URL, "endpoints": ENDPOINTS}
    try:
        out["egress_ip"] = requests.get("https://api.ipify.org", timeout=10).text
    except Exception as e:
        out["egress_ip"] = f"FAIL: {type(e).__name__}: {e}"
    try:
        p = urlparse(BASE_URL)
        host, port = p.hostname, p.port or (443 if p.scheme == "https" else 80)
        out["dns"] = socket.gethostbyname(host)
        for probe_port, key in [(80, "tcp_80"), (443, "tcp_443")]:
            try:
                t0 = time.time()
                s = socket.create_connection((host, probe_port), timeout=10)
                out[key] = f"ok {time.time()-t0:.2f}s"
                s.close()
            except Exception as e:
                out[key] = f"FAIL: {type(e).__name__}: {e}"
        if out.get("tcp_443", "").startswith("FAIL"):
            return out
    except Exception as e:
        out["tcp_443"] = f"FAIL: {type(e).__name__}: {e}"
        return out
    try:
        r = requests.get(BASE_URL, timeout=10)
        out["https_get_root"] = f"{r.status_code}: {r.text[:120]}"
    except Exception as e:
        out["https_get_root"] = f"FAIL: {type(e).__name__}: {e}"
    try:
        r = requests.post(ENDPOINTS["id"], files={"image": ("t.jpg", b"not-an-image", "image/jpeg")}, timeout=15)
        out["https_post_check_id"] = f"{r.status_code}: {r.text[:200]}"
    except Exception as e:
        out["https_post_check_id"] = f"FAIL: {type(e).__name__}: {e}"
    return out


def check_id(image) -> dict:
    return _check_document(image, "id")


def check_credit(image) -> dict:
    return _check_document(image, "credit")


def check_mrz(image) -> dict:
    return _check_document(image, "mrz")