File size: 1,046 Bytes
90df8a1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import requests
import os

# βœ… Secure HF API Token (Stored in Hugging Face Space Secrets)
HF_API_TOKEN = os.getenv("HF_API_TOKEN")

# βœ… Private Inference Endpoint URL
INFERENCE_API_URL = "https://z1lobj44dbdikcgy.eu-west-1.aws.endpoints.huggingface.cloud"

# βœ… Define a non-secret API key expected from the model
VALID_MODEL_API_KEY = os.getenv("VALID_MODEL_API_KEY")

def detect_objects(image, api_key):
    """Validates API key before processing request."""
    
    # βœ… Reject unauthorized requests
    if api_key != VALID_MODEL_API_KEY:
        return {"error": "Unauthorized request"}

    # βœ… Forward request to the private inference endpoint with secret HF token
    headers = {"Authorization": f"Bearer {HF_API_TOKEN}"}
    files = {"image": image}

    response = requests.post(INFERENCE_API_URL, headers=headers, files=files)
    return response.json()

# βœ… Public Space, but API key is required for access
iface = gr.Interface(fn=detect_objects, inputs=["image", "text"], outputs="json")
iface.launch()