3rdaiOhpinFully commited on
Commit
76cdd30
·
verified ·
1 Parent(s): 341549d

Create engine/hf_processors.py

Browse files
Files changed (1) hide show
  1. engine/hf_processors.py +57 -0
engine/hf_processors.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from gradio_client import Client, file
3
+
4
+ def normalize_detection_result(result):
5
+ if isinstance(result, dict):
6
+ return result.get("detections", [])
7
+ if isinstance(result, list):
8
+ return result
9
+ return []
10
+
11
+ def call_space(space_name, image_path, prompt=""):
12
+ if not space_name:
13
+ return {"ok": False, "detections": [], "error": "Space not configured"}
14
+
15
+ try:
16
+ token = os.getenv("HF_TOKEN")
17
+ client = Client(space_name, hf_token=token) if token else Client(space_name)
18
+
19
+ try:
20
+ result = client.predict(file(image_path), prompt, api_name="/predict")
21
+ except TypeError:
22
+ result = client.predict(file(image_path), api_name="/predict")
23
+
24
+ return {
25
+ "ok": True,
26
+ "space": space_name,
27
+ "detections": normalize_detection_result(result),
28
+ "raw_result": result,
29
+ }
30
+
31
+ except Exception as e:
32
+ return {
33
+ "ok": False,
34
+ "space": space_name,
35
+ "detections": [],
36
+ "error": str(e),
37
+ }
38
+
39
+ def run_optional_ai_processors(image_path, prompt):
40
+ processors = {
41
+ "face": os.getenv("FACE_SPACE", ""),
42
+ "eye": os.getenv("EYE_SPACE", ""),
43
+ "ocr": os.getenv("OCR_SPACE", ""),
44
+ "object": os.getenv("OBJECT_SPACE", ""),
45
+ "segmentation": os.getenv("SEGMENTATION_SPACE", ""),
46
+ "saliency": os.getenv("SALIENCY_SPACE", ""),
47
+ }
48
+
49
+ results = {}
50
+ for name, space in processors.items():
51
+ results[name] = call_space(space, image_path, prompt) if space else {
52
+ "ok": False,
53
+ "detections": [],
54
+ "error": "Not configured",
55
+ }
56
+
57
+ return results