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