File size: 3,947 Bytes
4f002d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
test_api.py
───────────
Local ya deployed HF Space ko test karne ke liye.

Usage:
    # Local test (app.py chal raha ho)
    python test_api.py --url http://localhost:7860 --secret your_secret --image logo_test.jpg

    # HF Space test
    python test_api.py --url https://your-space.hf.space --secret your_secret --image logo_test.jpg
"""

import argparse
import base64
import json
import os
import sys
import time

import requests


def test_health(base_url: str) -> bool:
    print(f"[1/3] Health check β†’ {base_url}/health")
    try:
        r = requests.get(f"{base_url}/health", timeout=10)
        data = r.json()
        print(f"      Status: {data.get('status')} | Model loaded: {data.get('model_loaded')}")
        return data.get("status") == "ok"
    except Exception as e:
        print(f"      FAILED: {e}")
        return False


def test_auth_reject(base_url: str) -> None:
    print("[2/3] Auth rejection test (wrong secret)...")
    try:
        r = requests.post(
            f"{base_url}/extract-logo",
            headers={"X-Custom-Secret": "wrong_secret_12345"},
            files={"image": ("test.jpg", b"\xff\xd8\xff", "image/jpeg")},
            timeout=10,
        )
        if r.status_code == 401:
            print("      βœ“ Correctly rejected (401 Unauthorized)")
        else:
            print(f"      WARNING: Expected 401, got {r.status_code}")
    except Exception as e:
        print(f"      FAILED: {e}")


def test_extract(base_url: str, secret: str, image_path: str, fmt: str = "PNG") -> None:
    print(f"[3/3] Logo extraction β†’ {image_path}")

    if not os.path.exists(image_path):
        print(f"      ERROR: Image not found: {image_path}")
        return

    with open(image_path, "rb") as f:
        image_bytes = f.read()

    mime = "image/png" if image_path.lower().endswith(".png") else "image/jpeg"

    t0 = time.perf_counter()
    try:
        r = requests.post(
            f"{base_url}/extract-logo",
            headers={"X-Custom-Secret": secret},
            files={"image": (os.path.basename(image_path), image_bytes, mime)},
            params={"output_format": fmt},
            timeout=30,
        )
    except Exception as e:
        print(f"      FAILED: {e}")
        return

    elapsed = round((time.perf_counter() - t0) * 1000, 1)

    if r.status_code != 200:
        print(f"      ERROR {r.status_code}: {r.text}")
        return

    data = r.json()
    print(f"      βœ“ Success in {elapsed} ms (server: {data.get('elapsed_ms')} ms)")
    print(f"      Logos found: {data.get('count', 0)}")

    # Save cropped logos
    for i, logo in enumerate(data.get("logos", [])):
        out_path = f"logo_crop_{i+1}.png"
        img_bytes = base64.b64decode(logo["base64"])
        with open(out_path, "wb") as f:
            f.write(img_bytes)
        print(
            f"      Logo {i+1}: {logo['width']}x{logo['height']}px "
            f"| conf={logo['confidence']} | saved β†’ {out_path}"
        )

    if data.get("count", 0) == 0:
        print("      No logos detected. Try a different image or lower CONF_THRESHOLD.")


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--url",    default="http://localhost:7860", help="API base URL")
    parser.add_argument("--secret", required=True,                   help="APP_SECRET_KEY value")
    parser.add_argument("--image",  required=True,                   help="Path to test image")
    parser.add_argument("--format", default="PNG",
                        choices=["PNG", "JPEG", "TRANSPARENT"],      help="Output format")
    args = parser.parse_args()

    base_url = args.url.rstrip("/")
    ok = test_health(base_url)
    test_auth_reject(base_url)
    if ok:
        test_extract(base_url, args.secret, args.image, args.format)
    else:
        print("\nSkipping extraction test β€” server not healthy.")
        sys.exit(1)

    print("\nDone!")