File size: 1,709 Bytes
76cdd30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
from gradio_client import Client, file

def normalize_detection_result(result):
    if isinstance(result, dict):
        return result.get("detections", [])
    if isinstance(result, list):
        return result
    return []

def call_space(space_name, image_path, prompt=""):
    if not space_name:
        return {"ok": False, "detections": [], "error": "Space not configured"}

    try:
        token = os.getenv("HF_TOKEN")
        client = Client(space_name, hf_token=token) if token else Client(space_name)

        try:
            result = client.predict(file(image_path), prompt, api_name="/predict")
        except TypeError:
            result = client.predict(file(image_path), api_name="/predict")

        return {
            "ok": True,
            "space": space_name,
            "detections": normalize_detection_result(result),
            "raw_result": result,
        }

    except Exception as e:
        return {
            "ok": False,
            "space": space_name,
            "detections": [],
            "error": str(e),
        }

def run_optional_ai_processors(image_path, prompt):
    processors = {
        "face": os.getenv("FACE_SPACE", ""),
        "eye": os.getenv("EYE_SPACE", ""),
        "ocr": os.getenv("OCR_SPACE", ""),
        "object": os.getenv("OBJECT_SPACE", ""),
        "segmentation": os.getenv("SEGMENTATION_SPACE", ""),
        "saliency": os.getenv("SALIENCY_SPACE", ""),
    }

    results = {}
    for name, space in processors.items():
        results[name] = call_space(space, image_path, prompt) if space else {
            "ok": False,
            "detections": [],
            "error": "Not configured",
        }

    return results