VeuReu commited on
Commit
84c4453
verified
1 Parent(s): 4f4a005

Delete remote_clients.py

Browse files
Files changed (1) hide show
  1. remote_clients.py +0 -96
remote_clients.py DELETED
@@ -1,96 +0,0 @@
1
- # ============================
2
- # File: remote_clients.py
3
- # ============================
4
- from __future__ import annotations
5
- from typing import Any, Dict, List, Optional
6
- import os, json, time
7
- import requests
8
- from tenacity import retry, stop_after_attempt, wait_exponential
9
-
10
- try:
11
- from gradio_client import Client as GradioClient
12
- except Exception: # pragma: no cover
13
- GradioClient = None # type: ignore
14
-
15
-
16
- class BaseRemoteClient:
17
- def __init__(self, base_url: str, use_gradio: bool = True, hf_token: Optional[str] = None, timeout: int = 120):
18
- self.base_url = base_url.rstrip("/")
19
- self.use_gradio = use_gradio and GradioClient is not None
20
- self.hf_token = hf_token or os.getenv("HF_TOKEN")
21
- self.timeout = timeout
22
- self._client = None
23
- if self.use_gradio:
24
- # GradioClient acepta base_url del Space p煤blico/privado
25
- headers = {"Authorization": f"Bearer {self.hf_token}"} if self.hf_token else None
26
- self._client = GradioClient(self.base_url, hf_token=self.hf_token, headers=headers)
27
-
28
- @retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=1, max=8))
29
- def _post_json(self, route: str, payload: Dict[str, Any]) -> Dict[str, Any]:
30
- url = f"{self.base_url}{route}"
31
- headers = {"Authorization": f"Bearer {self.hf_token}"} if self.hf_token else {}
32
- r = requests.post(url, json=payload, headers=headers, timeout=self.timeout)
33
- r.raise_for_status()
34
- return r.json()
35
-
36
-
37
- class InstructClient(BaseRemoteClient):
38
- """Cliente para Space de texto-instrucci贸n (schat)."""
39
- def generate(self, prompt: str, system: Optional[str] = None, **kwargs) -> str:
40
- if self.use_gradio and self._client:
41
- # Asume interfaz Gradio con un 煤nico campo de entrada de texto y devuelve texto.
42
- # Ajusta "predict" y par谩metros a tu Space real (inputs/outputs).
43
- out = self._client.predict(prompt, api_name="/predict")
44
- return str(out)
45
- # HTTP gen茅rico
46
- data = {"prompt": prompt, "system": system, **kwargs}
47
- res = self._post_json("/generate", data)
48
- return res.get("text", "")
49
-
50
-
51
- class VisionClient(BaseRemoteClient):
52
- """Cliente para Space de visi贸n (svision)."""
53
- def describe(self, image_paths: List[str], context: Optional[Dict[str, Any]] = None, **kwargs) -> List[str]:
54
- if self.use_gradio and self._client:
55
- # En muchos Spaces, Gradio acepta lista de im谩genes + texto JSON.
56
- out = self._client.predict(image_paths, json.dumps(context or {}), api_name="/predict")
57
- # Debe devolver lista de descripciones (una por imagen)
58
- if isinstance(out, str):
59
- try:
60
- return json.loads(out)
61
- except Exception:
62
- return [out]
63
- return list(out)
64
- data = {"images": image_paths, "context": context or {}, **kwargs}
65
- res = self._post_json("/describe", data)
66
- return res.get("descriptions", [])
67
-
68
-
69
- class ToolsClient(BaseRemoteClient):
70
- """Cliente para Space con tool-calling (stools)."""
71
- def chat(self, messages: List[Dict[str, str]], tools: Optional[List[Dict[str, Any]]] = None, **kwargs) -> Dict[str, Any]:
72
- if self.use_gradio and self._client:
73
- out = self._client.predict(json.dumps(messages), json.dumps(tools or []), api_name="/predict")
74
- if isinstance(out, str):
75
- try:
76
- return json.loads(out)
77
- except Exception:
78
- return {"text": out}
79
- return out
80
- data = {"messages": messages, "tools": tools or [], **kwargs}
81
- return self._post_json("/chat", data)
82
-
83
-
84
- class ASRClient(BaseRemoteClient):
85
- """Cliente para Space de ASR catal谩n (ars)."""
86
- def transcribe(self, audio_path: str, **kwargs) -> Dict[str, Any]:
87
- if self.use_gradio and self._client:
88
- out = self._client.predict(audio_path, api_name="/predict")
89
- if isinstance(out, str):
90
- return {"text": out}
91
- return out
92
- files = {"file": open(audio_path, "rb")}
93
- headers = {"Authorization": f"Bearer {self.hf_token}"} if self.hf_token else {}
94
- r = requests.post(f"{self.base_url}/transcribe", files=files, data=kwargs, headers=headers, timeout=self.timeout)
95
- r.raise_for_status()
96
- return r.json()