kos-cloud 1.0.0b1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- kos_cloud/__init__.py +79 -0
- kos_cloud/_client.py +792 -0
- kos_cloud/_errors.py +179 -0
- kos_cloud/_http.py +330 -0
- kos_cloud/_types.py +253 -0
- kos_cloud/py.typed +0 -0
- kos_cloud-1.0.0b1.dist-info/METADATA +173 -0
- kos_cloud-1.0.0b1.dist-info/RECORD +12 -0
- kos_cloud-1.0.0b1.dist-info/WHEEL +5 -0
- kos_cloud-1.0.0b1.dist-info/licenses/LICENSE +201 -0
- kos_cloud-1.0.0b1.dist-info/licenses/NOTICE +4 -0
- kos_cloud-1.0.0b1.dist-info/top_level.txt +1 -0
kos_cloud/_client.py
ADDED
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
"""The KOS Cloud client: submit models, wait for them and read their results."""
|
|
2
|
+
|
|
3
|
+
import gzip
|
|
4
|
+
import ipaddress
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import sys
|
|
10
|
+
import threading
|
|
11
|
+
import time
|
|
12
|
+
import urllib.parse
|
|
13
|
+
import uuid
|
|
14
|
+
import warnings
|
|
15
|
+
from collections.abc import Mapping
|
|
16
|
+
from typing import Any, Callable, Dict, List, Optional, Union
|
|
17
|
+
|
|
18
|
+
from . import _http
|
|
19
|
+
from ._errors import (SUPPORT, AuthenticationError, EmailNotVerifiedError, InsufficientBalanceError,
|
|
20
|
+
JobCancelledError, JobFailedError, JobModelTooLargeError, KosCloudError,
|
|
21
|
+
MachineNotAvailableError, ModelTooLargeError, NetworkError, PreviewGateError, RateLimitError,
|
|
22
|
+
TimeLimitError, WaitTimeoutError)
|
|
23
|
+
from ._types import FINAL_STATES, Balance, Catalog, Job, Result
|
|
24
|
+
|
|
25
|
+
log = logging.getLogger("kos_cloud")
|
|
26
|
+
|
|
27
|
+
DEFAULT_BASE_URL = "https://katsenia.com/api/v1/"
|
|
28
|
+
_SIN_CLAVE = ("no API key: set the KOS_API_KEY environment variable or pass api_key= (API keys are created in your "
|
|
29
|
+
"KOS Cloud account)")
|
|
30
|
+
_COMPUERTA = (f"the site answered with its preview gate instead of the API. Requests with an API key should pass it: "
|
|
31
|
+
f"check that the key is set and, if it is, write to {SUPPORT}")
|
|
32
|
+
_ESPERAS = {"test_server_busy": "the test server is busy", "class_busy": "all machines of this tier are busy"}
|
|
33
|
+
|
|
34
|
+
ProgressArg = Union[bool, None, Callable[[str], Any]]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _version():
|
|
38
|
+
from . import __version__
|
|
39
|
+
return __version__
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _id_de(job) -> str:
|
|
43
|
+
"""El id de un trabajo: de un `Job`, de un dict de la API o de un texto."""
|
|
44
|
+
if isinstance(job, Job):
|
|
45
|
+
valor = job.id
|
|
46
|
+
elif isinstance(job, Mapping):
|
|
47
|
+
valor = job.get("id")
|
|
48
|
+
else:
|
|
49
|
+
valor = job
|
|
50
|
+
if not isinstance(valor, str) or not valor.strip():
|
|
51
|
+
raise TypeError("give a job id (str) or a Job")
|
|
52
|
+
return valor.strip()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _ruta_trabajo(job_id, resto=""):
|
|
56
|
+
return "jobs/" + urllib.parse.quote(job_id, safe="") + resto
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _es_bucle_local(anfitrion):
|
|
60
|
+
if anfitrion == "localhost" or anfitrion.endswith(".localhost"):
|
|
61
|
+
return True
|
|
62
|
+
try:
|
|
63
|
+
return ipaddress.ip_address(anfitrion).is_loopback
|
|
64
|
+
except ValueError:
|
|
65
|
+
return False
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ---------------------------------------------------------------- el modelo que se envía
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _compresion(cabeza: bytes) -> Optional[str]:
|
|
72
|
+
"""La compresión por la firma de los primeros bytes, como la reconoce el servicio."""
|
|
73
|
+
if cabeza[:2] == b"\x1f\x8b":
|
|
74
|
+
return "gzip"
|
|
75
|
+
if cabeza[:3] == b"BZh":
|
|
76
|
+
return "bzip2"
|
|
77
|
+
if cabeza[:6] == b"\xfd7zXZ\x00":
|
|
78
|
+
return "xz"
|
|
79
|
+
if cabeza[:4] == b"PK\x03\x04":
|
|
80
|
+
return "zip"
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _es_modelo_kos(objeto) -> bool:
|
|
85
|
+
"""Si es un `kos.Model`, sin importar `kos`: quien tiene uno ya lo importó."""
|
|
86
|
+
kos = sys.modules.get("kos")
|
|
87
|
+
clase = getattr(kos, "Model", None) if kos is not None else None
|
|
88
|
+
if isinstance(clase, type) and isinstance(objeto, clase):
|
|
89
|
+
return True
|
|
90
|
+
tipo = type(objeto)
|
|
91
|
+
modulo = getattr(tipo, "__module__", "") or ""
|
|
92
|
+
return tipo.__name__ == "Model" and (modulo == "kos" or modulo.startswith("kos."))
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class _Envio:
|
|
96
|
+
"""Lo que se sube: un texto (va como JSON `model_text`) o un archivo (multipart, campo `model`).
|
|
97
|
+
|
|
98
|
+
`por_subir` son los bytes que viajan; `sin_comprimir`, el tamaño del modelo sin comprimir cuando se sabe (un
|
|
99
|
+
archivo comprimido no se abre: el servicio lo revisa). Un archivo se lee después de revisar los límites.
|
|
100
|
+
"""
|
|
101
|
+
|
|
102
|
+
def __init__(self, texto=None, datos=None, ruta=None, nombre_archivo="model", por_subir=0, sin_comprimir=None,
|
|
103
|
+
comprimido=False):
|
|
104
|
+
self.texto = texto
|
|
105
|
+
self.datos = datos
|
|
106
|
+
self.ruta = ruta
|
|
107
|
+
self.nombre_archivo = nombre_archivo
|
|
108
|
+
self.por_subir = por_subir
|
|
109
|
+
self.sin_comprimir = sin_comprimir
|
|
110
|
+
self.comprimido = comprimido
|
|
111
|
+
|
|
112
|
+
def bytes(self) -> bytes:
|
|
113
|
+
if self.datos is None and self.ruta is not None:
|
|
114
|
+
with open(self.ruta, "rb") as f:
|
|
115
|
+
self.datos = f.read()
|
|
116
|
+
self.por_subir = len(self.datos)
|
|
117
|
+
return self.datos
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _envio_de(model) -> _Envio:
|
|
121
|
+
if isinstance(model, str) and ("\n" in model or "\r" in model):
|
|
122
|
+
datos = model.encode("utf-8")
|
|
123
|
+
if not model.strip():
|
|
124
|
+
raise ValueError("the model text is empty")
|
|
125
|
+
return _Envio(texto=model, por_subir=len(datos), sin_comprimir=len(datos))
|
|
126
|
+
if isinstance(model, (str, os.PathLike)):
|
|
127
|
+
ruta = os.fspath(model)
|
|
128
|
+
if isinstance(ruta, bytes):
|
|
129
|
+
ruta = os.fsdecode(ruta)
|
|
130
|
+
if not os.path.isfile(ruta):
|
|
131
|
+
pista = "" if os.path.exists(ruta) else (
|
|
132
|
+
"; to send LP or MPS text, pass a string with line breaks" if isinstance(model, str) else "")
|
|
133
|
+
raise FileNotFoundError(f"no such model file: {ruta!r}{pista}")
|
|
134
|
+
tamano = os.path.getsize(ruta)
|
|
135
|
+
with open(ruta, "rb") as f:
|
|
136
|
+
cabeza = f.read(8)
|
|
137
|
+
comprimido = _compresion(cabeza) is not None
|
|
138
|
+
return _Envio(ruta=ruta, nombre_archivo=os.path.basename(ruta) or "model", por_subir=tamano,
|
|
139
|
+
sin_comprimir=None if comprimido else tamano, comprimido=comprimido)
|
|
140
|
+
if isinstance(model, (bytes, bytearray, memoryview)):
|
|
141
|
+
datos = bytes(model)
|
|
142
|
+
if not datos:
|
|
143
|
+
raise ValueError("the model is empty")
|
|
144
|
+
comprimido = _compresion(datos[:8]) is not None
|
|
145
|
+
return _Envio(datos=datos, por_subir=len(datos), sin_comprimir=None if comprimido else len(datos),
|
|
146
|
+
comprimido=comprimido)
|
|
147
|
+
if _es_modelo_kos(model):
|
|
148
|
+
escribe = getattr(model, "to_string", None)
|
|
149
|
+
if not callable(escribe):
|
|
150
|
+
raise TypeError("this kos.Model has no to_string(); install a newer kos-solver "
|
|
151
|
+
"(pip install --pre --upgrade kos-solver)")
|
|
152
|
+
texto = escribe("mps")
|
|
153
|
+
if not isinstance(texto, str) or not texto.strip():
|
|
154
|
+
raise ValueError("kos.Model.to_string('mps') gave no model text")
|
|
155
|
+
plano = texto.encode("utf-8")
|
|
156
|
+
# Se sube como MPS comprimido con gzip: viaja mucho más chico (mtime=0: los reintentos mandan lo mismo).
|
|
157
|
+
datos = gzip.compress(plano, compresslevel=6, mtime=0)
|
|
158
|
+
return _Envio(datos=datos, nombre_archivo="model.mps.gz", por_subir=len(datos), sin_comprimir=len(plano),
|
|
159
|
+
comprimido=True)
|
|
160
|
+
raise TypeError("model must be a file path (str or PathLike), LP or MPS text (a str with line breaks), bytes, "
|
|
161
|
+
"or a kos.Model (pip install kos-cloud[kos]); got " + type(model).__name__)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def _nombre_seguro(nombre: str) -> str:
|
|
165
|
+
"""Un nombre de archivo que cabe entre comillas en Content-Disposition."""
|
|
166
|
+
limpio = "".join("_" if ch in '"\\\r\n' or ord(ch) < 32 else ch for ch in nombre)
|
|
167
|
+
return limpio or "model"
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _multipart(campos: Dict[str, Any], datos: bytes, nombre_archivo: str):
|
|
171
|
+
"""El cuerpo multipart/form-data del envío: los campos de texto y el archivo en `model`, tal cual."""
|
|
172
|
+
textos = {}
|
|
173
|
+
for clave, valor in campos.items():
|
|
174
|
+
if isinstance(valor, bool):
|
|
175
|
+
textos[clave] = "true" if valor else "false"
|
|
176
|
+
elif isinstance(valor, (dict, list)):
|
|
177
|
+
textos[clave] = json.dumps(valor, ensure_ascii=False, allow_nan=False)
|
|
178
|
+
else:
|
|
179
|
+
textos[clave] = str(valor)
|
|
180
|
+
while True:
|
|
181
|
+
limite = "kos-cloud-" + uuid.uuid4().hex
|
|
182
|
+
marca = limite.encode("ascii")
|
|
183
|
+
if marca not in datos and not any(marca in v.encode("utf-8") for v in textos.values()):
|
|
184
|
+
break
|
|
185
|
+
partes = []
|
|
186
|
+
for clave, valor in textos.items():
|
|
187
|
+
partes.append(f'--{limite}\r\nContent-Disposition: form-data; name="{clave}"\r\n\r\n'.encode("utf-8")
|
|
188
|
+
+ valor.encode("utf-8") + b"\r\n")
|
|
189
|
+
partes.append(f'--{limite}\r\nContent-Disposition: form-data; name="model"; '
|
|
190
|
+
f'filename="{_nombre_seguro(nombre_archivo)}"\r\n'
|
|
191
|
+
f"Content-Type: application/octet-stream\r\n\r\n".encode("utf-8") + datos + b"\r\n")
|
|
192
|
+
partes.append(f"--{limite}--\r\n".encode("ascii"))
|
|
193
|
+
return b"".join(partes), f"multipart/form-data; boundary={limite}"
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _limite_en(params) -> Optional[float]:
|
|
197
|
+
"""El time_limit que va dentro de `params` (el servicio lo usa si no viene aparte), o None."""
|
|
198
|
+
for clave, valor in (params or {}).items():
|
|
199
|
+
if isinstance(clave, str) and clave.strip().lower() == "time_limit" and not isinstance(valor, bool):
|
|
200
|
+
try:
|
|
201
|
+
numero = float(valor)
|
|
202
|
+
except (TypeError, ValueError):
|
|
203
|
+
return None
|
|
204
|
+
return numero if math.isfinite(numero) else None
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _segundos(valor, nombre):
|
|
209
|
+
if isinstance(valor, bool) or not isinstance(valor, (int, float)):
|
|
210
|
+
raise TypeError(f"{nombre} must be a number of seconds")
|
|
211
|
+
if not math.isfinite(valor) or valor <= 0:
|
|
212
|
+
raise ValueError(f"{nombre} must be a positive number of seconds")
|
|
213
|
+
return valor
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
# ---------------------------------------------------------------- el avance
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
class _Avance:
|
|
220
|
+
"""Adónde va el avance de una espera: nada, la consola (stderr) o una función que recibe cada trozo del registro."""
|
|
221
|
+
|
|
222
|
+
def __init__(self, progress: ProgressArg):
|
|
223
|
+
if progress is None or progress is False:
|
|
224
|
+
self.funcion, self.consola = None, False
|
|
225
|
+
elif progress is True:
|
|
226
|
+
self.funcion, self.consola = self._a_consola, True
|
|
227
|
+
elif callable(progress):
|
|
228
|
+
self.funcion, self.consola = progress, False
|
|
229
|
+
else:
|
|
230
|
+
raise TypeError("progress must be True, False or a function that takes a str")
|
|
231
|
+
|
|
232
|
+
@staticmethod
|
|
233
|
+
def _a_consola(texto):
|
|
234
|
+
# sys.stderr se busca en cada escritura: sirve con contextlib.redirect_stderr y en los cuadernos.
|
|
235
|
+
sys.stderr.write(texto)
|
|
236
|
+
sys.stderr.flush()
|
|
237
|
+
|
|
238
|
+
def registro(self, texto):
|
|
239
|
+
if self.funcion is not None and texto:
|
|
240
|
+
self.funcion(texto)
|
|
241
|
+
|
|
242
|
+
def estado(self, trabajo: Dict[str, Any]):
|
|
243
|
+
if not self.consola:
|
|
244
|
+
return
|
|
245
|
+
ident, estado = trabajo.get("id"), trabajo.get("state")
|
|
246
|
+
if estado == "queued":
|
|
247
|
+
detalle = []
|
|
248
|
+
if isinstance(trabajo.get("queue_position"), int):
|
|
249
|
+
detalle.append(f"position {trabajo['queue_position']}")
|
|
250
|
+
if trabajo.get("waiting_reason"):
|
|
251
|
+
detalle.append(_ESPERAS.get(trabajo["waiting_reason"], str(trabajo["waiting_reason"])))
|
|
252
|
+
linea = f"job {ident} is queued" + (f" ({', '.join(detalle)})" if detalle else "")
|
|
253
|
+
elif estado == "running":
|
|
254
|
+
clase = trabajo.get("machine_class") or {}
|
|
255
|
+
linea = f"job {ident} is running" + (f" on {clase['id']}" if isinstance(clase, dict) and
|
|
256
|
+
clase.get("id") else "")
|
|
257
|
+
else:
|
|
258
|
+
resultado = trabajo.get("result")
|
|
259
|
+
estado_kos = resultado.get("status") if isinstance(resultado, dict) else None
|
|
260
|
+
linea = f"job {ident} {estado}" + (f" ({estado_kos})" if estado_kos else "")
|
|
261
|
+
self._a_consola(f"kos-cloud: {linea}\n")
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _avisa(texto):
|
|
265
|
+
"""Una línea en stderr que nunca falla (sin stderr, como con pythonw, o con stderr cerrado, no se escribe)."""
|
|
266
|
+
try:
|
|
267
|
+
sys.stderr.write(texto)
|
|
268
|
+
sys.stderr.flush()
|
|
269
|
+
except Exception: # noqa: BLE001
|
|
270
|
+
pass
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
# ---------------------------------------------------------------- el cliente
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
class Client:
|
|
277
|
+
"""A client of the KOS Cloud API.
|
|
278
|
+
|
|
279
|
+
Args:
|
|
280
|
+
api_key: the API key (``kos_…``). By default, the ``KOS_API_KEY`` environment variable. It is sent only in
|
|
281
|
+
the ``Authorization`` header to the API's own host, and never printed: not in ``repr``, errors or logs.
|
|
282
|
+
base_url: the API, by default ``KOS_CLOUD_URL`` or ``https://katsenia.com/api/v1/``.
|
|
283
|
+
timeout: seconds to wait for each HTTP response (long polls add their own wait to it).
|
|
284
|
+
|
|
285
|
+
Requests that are safe to repeat (reads and cancellations) are retried on network errors, 502/503/504 and 429
|
|
286
|
+
(following ``Retry-After`` up to a cap); a submission is retried only with its own ``Idempotency-Key``, so a
|
|
287
|
+
retry never creates a second job.
|
|
288
|
+
"""
|
|
289
|
+
|
|
290
|
+
# Reintentos: cuántos, la primera pausa (se dobla hasta 8 s) y la espera más larga de un Retry-After que se acepta.
|
|
291
|
+
max_retries = 5
|
|
292
|
+
backoff_seconds = 0.5
|
|
293
|
+
max_retry_after = 60.0
|
|
294
|
+
# La consulta larga: los segundos que el servicio retiene cada pregunta. En Windows una lectura de socket no se
|
|
295
|
+
# corta con Ctrl+C: preguntas más cortas para que la cancelación llegue pronto.
|
|
296
|
+
poll_seconds = 5 if os.name == "nt" else 30
|
|
297
|
+
# Entre dos preguntas que vuelven al tiro sin nada que mostrar (registro que nadie lee, o un servicio que no retiene
|
|
298
|
+
# la pregunta) pasa al menos esto.
|
|
299
|
+
min_poll_interval = 1.0
|
|
300
|
+
# Lo que se espera el estado final de un trabajo cancelado con Ctrl+C, y cuánto vale el catálogo guardado.
|
|
301
|
+
cancel_wait_seconds = 10.0
|
|
302
|
+
catalog_ttl = 300.0
|
|
303
|
+
|
|
304
|
+
def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: float = 60):
|
|
305
|
+
clave = api_key if api_key is not None else os.environ.get("KOS_API_KEY")
|
|
306
|
+
if clave is not None and not isinstance(clave, str):
|
|
307
|
+
raise TypeError("api_key must be a str")
|
|
308
|
+
clave = (clave or "").strip()
|
|
309
|
+
if clave and not (clave.isascii() and clave.isprintable()):
|
|
310
|
+
raise AuthenticationError("the API key has characters that cannot go in an HTTP header (it must be "
|
|
311
|
+
"printable ASCII)", "invalid_api_key")
|
|
312
|
+
self._key = _http.Secret(clave)
|
|
313
|
+
base = base_url if base_url is not None else (os.environ.get("KOS_CLOUD_URL") or DEFAULT_BASE_URL)
|
|
314
|
+
partes = urllib.parse.urlsplit(str(base).strip())
|
|
315
|
+
if partes.scheme not in ("http", "https") or not partes.hostname or partes.query or partes.fragment:
|
|
316
|
+
raise ValueError(f"base_url must be an http or https URL without query, like {DEFAULT_BASE_URL}")
|
|
317
|
+
camino = partes.path if partes.path.endswith("/") else partes.path + "/"
|
|
318
|
+
self.base_url = urllib.parse.urlunsplit((partes.scheme, partes.netloc, camino, "", ""))
|
|
319
|
+
if partes.scheme == "http" and not _es_bucle_local(partes.hostname):
|
|
320
|
+
warnings.warn("kos-cloud: base_url uses plain http to another machine: the API key travels unencrypted",
|
|
321
|
+
stacklevel=2)
|
|
322
|
+
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not timeout > 0:
|
|
323
|
+
raise ValueError("timeout must be a positive number of seconds")
|
|
324
|
+
self.timeout = float(timeout)
|
|
325
|
+
agente = f"kos-cloud/{_version()} python/{sys.version_info[0]}.{sys.version_info[1]}"
|
|
326
|
+
self._agente = agente
|
|
327
|
+
self._http = _http.Transport(self.base_url, self._key, agente, self.max_retries, self.backoff_seconds,
|
|
328
|
+
self.max_retry_after)
|
|
329
|
+
self._catalogo = None
|
|
330
|
+
self._catalogo_en = 0.0
|
|
331
|
+
self._cerrojo = threading.Lock()
|
|
332
|
+
|
|
333
|
+
def __repr__(self) -> str:
|
|
334
|
+
return f"Client(base_url={self.base_url!r}, api_key={'<set>' if self._key else '<missing>'})"
|
|
335
|
+
|
|
336
|
+
# ------------------------------------------------------------ peticiones
|
|
337
|
+
|
|
338
|
+
def _origen_web(self) -> str:
|
|
339
|
+
partes = urllib.parse.urlsplit(self.base_url)
|
|
340
|
+
return f"{partes.scheme}://{partes.netloc}"
|
|
341
|
+
|
|
342
|
+
def _limpia(self, valor):
|
|
343
|
+
"""Quita la clave de un texto o de los textos de un objeto (por si una respuesta la trajera de vuelta)."""
|
|
344
|
+
clave = self._key.reveal()
|
|
345
|
+
if not clave:
|
|
346
|
+
return valor
|
|
347
|
+
if isinstance(valor, str):
|
|
348
|
+
return valor.replace(clave, "<hidden>")
|
|
349
|
+
if isinstance(valor, dict):
|
|
350
|
+
return {self._limpia(k): self._limpia(v) for k, v in valor.items()}
|
|
351
|
+
if isinstance(valor, list):
|
|
352
|
+
return [self._limpia(v) for v in valor]
|
|
353
|
+
return valor
|
|
354
|
+
|
|
355
|
+
def _pide(self, metodo, camino, consulta=None, cuerpo=None, tipo=None, cabeceras=None, clave="required",
|
|
356
|
+
reintentos=_http.SEGURO, plazo=None, max_reintentos=None, acepta="application/json", hasta=None):
|
|
357
|
+
"""Una petición a la API; un estado que no es 2xx sale como el error tipado que le corresponde."""
|
|
358
|
+
if clave == "required" and not self._key:
|
|
359
|
+
raise AuthenticationError(_SIN_CLAVE, "no_api_key")
|
|
360
|
+
url = urllib.parse.urljoin(self.base_url, camino)
|
|
361
|
+
if consulta:
|
|
362
|
+
url += "?" + urllib.parse.urlencode({k: v for k, v in consulta.items() if v is not None})
|
|
363
|
+
todas = {"User-Agent": self._agente, "Accept": acepta}
|
|
364
|
+
if tipo:
|
|
365
|
+
todas["Content-Type"] = tipo
|
|
366
|
+
todas.update(cabeceras or {})
|
|
367
|
+
self._http.max_reintentos, self._http.espera_base = self.max_retries, self.backoff_seconds
|
|
368
|
+
self._http.max_retry_after = self.max_retry_after
|
|
369
|
+
try:
|
|
370
|
+
respuesta = self._http.pide(metodo, url, cuerpo, todas, con_clave=clave != "none",
|
|
371
|
+
plazo=plazo or self.timeout, reintentos=reintentos, seguir=metodo == "GET",
|
|
372
|
+
max_reintentos=max_reintentos, hasta=hasta)
|
|
373
|
+
except KosCloudError as e:
|
|
374
|
+
e.message = self._limpia(e.message)
|
|
375
|
+
e.args = (e.message,)
|
|
376
|
+
raise
|
|
377
|
+
if not 200 <= respuesta.status < 300:
|
|
378
|
+
raise self._error(respuesta)
|
|
379
|
+
return respuesta
|
|
380
|
+
|
|
381
|
+
def _json(self, metodo, camino, **opciones) -> Dict[str, Any]:
|
|
382
|
+
respuesta = self._pide(metodo, camino, **opciones)
|
|
383
|
+
datos = respuesta.json()
|
|
384
|
+
if not isinstance(datos, dict):
|
|
385
|
+
raise KosCloudError(f"the API sent something that is not a JSON object for {camino}", "invalid_response",
|
|
386
|
+
respuesta.status)
|
|
387
|
+
return datos
|
|
388
|
+
|
|
389
|
+
def _error(self, respuesta) -> KosCloudError:
|
|
390
|
+
"""El error tipado de una respuesta de error de la API (o de lo que está delante de ella)."""
|
|
391
|
+
estado = respuesta.status
|
|
392
|
+
datos = respuesta.json()
|
|
393
|
+
error = datos.get("error") if isinstance(datos, dict) else None
|
|
394
|
+
codigo, mensaje, detalle = None, "", {}
|
|
395
|
+
if isinstance(error, dict):
|
|
396
|
+
codigo = error.get("code") if isinstance(error.get("code"), str) else None
|
|
397
|
+
mensaje = error.get("message") if isinstance(error.get("message"), str) else ""
|
|
398
|
+
detalle = error.get("details") if isinstance(error.get("details"), dict) else {}
|
|
399
|
+
mensaje, detalle = self._limpia(mensaje), self._limpia(detalle)
|
|
400
|
+
if not mensaje:
|
|
401
|
+
mensaje = f"the API answered HTTP {estado} {respuesta.reason}".strip()
|
|
402
|
+
basica = "basic" in (respuesta.header("WWW-Authenticate") or "").lower()
|
|
403
|
+
if codigo == "preview_gate" or (estado == 401 and codigo is None and basica):
|
|
404
|
+
return PreviewGateError(_COMPUERTA, "preview_gate", estado, detalle)
|
|
405
|
+
if codigo == "unauthenticated" or estado == 401:
|
|
406
|
+
return AuthenticationError(mensaje, codigo or "unauthenticated", estado, detalle)
|
|
407
|
+
if codigo == "insufficient_balance" or estado == 402:
|
|
408
|
+
enlace = detalle.get("top_up_url")
|
|
409
|
+
if not (isinstance(enlace, str) and enlace.startswith(("https://", "http://"))):
|
|
410
|
+
enlace = self._origen_web() + "/buy.html"
|
|
411
|
+
return InsufficientBalanceError(f"{mensaje.rstrip('.')}. Top up at {enlace}", codigo or
|
|
412
|
+
"insufficient_balance", estado, detalle, top_up_url=enlace)
|
|
413
|
+
if codigo == "email_not_verified":
|
|
414
|
+
return EmailNotVerifiedError(mensaje, codigo, estado, detalle)
|
|
415
|
+
if codigo in ("payload_too_large", "decompressed_too_large", "storage_quota", "model_too_large") \
|
|
416
|
+
or estado == 413:
|
|
417
|
+
return ModelTooLargeError(mensaje, codigo or "payload_too_large", estado, detalle)
|
|
418
|
+
if codigo == "machine_not_available":
|
|
419
|
+
return MachineNotAvailableError(mensaje, codigo, estado, detalle)
|
|
420
|
+
parametros = detalle.get("parameters") if isinstance(detalle.get("parameters"), list) else []
|
|
421
|
+
if codigo == "invalid_parameter" and any(isinstance(p, dict) and p.get("name") == "time_limit"
|
|
422
|
+
for p in parametros):
|
|
423
|
+
return TimeLimitError(mensaje, codigo, estado, detalle)
|
|
424
|
+
if estado == 429:
|
|
425
|
+
espera = _http.retry_after(respuesta)
|
|
426
|
+
if espera is None and isinstance(detalle.get("retry_after"), (int, float)) \
|
|
427
|
+
and not isinstance(detalle.get("retry_after"), bool):
|
|
428
|
+
espera = float(detalle["retry_after"])
|
|
429
|
+
return RateLimitError(mensaje, codigo or "rate_limited", estado, detalle, retry_after=espera)
|
|
430
|
+
if estado in (502, 503, 504):
|
|
431
|
+
return NetworkError(mensaje, codigo or f"http_{estado}", estado, detalle)
|
|
432
|
+
return KosCloudError(mensaje, codigo or f"http_{estado}", estado, detalle)
|
|
433
|
+
|
|
434
|
+
# ------------------------------------------------------------ catálogo
|
|
435
|
+
|
|
436
|
+
def classes(self, model_bytes: Optional[int] = None, kind: Optional[str] = None) -> Catalog:
|
|
437
|
+
"""The machine tiers the API offers (``GET classes``), with their prices and limits.
|
|
438
|
+
|
|
439
|
+
With ``model_bytes`` (and ``kind``: ``"lp"`` or ``"mip"``) the catalog also says which tier the API suggests
|
|
440
|
+
for such a model (``Catalog.suggested``). No API key is needed.
|
|
441
|
+
"""
|
|
442
|
+
catalogo = Catalog(self._json("GET", "classes", consulta={"model_bytes": model_bytes, "kind": kind},
|
|
443
|
+
clave="optional"))
|
|
444
|
+
if model_bytes is None and kind is None:
|
|
445
|
+
with self._cerrojo:
|
|
446
|
+
self._catalogo, self._catalogo_en = catalogo, time.monotonic()
|
|
447
|
+
return catalogo
|
|
448
|
+
|
|
449
|
+
def _catalogo_para_revisar(self) -> Optional[Catalog]:
|
|
450
|
+
"""El catálogo para revisar un envío antes de subirlo; None si no se pudo leer (lo revisa el servicio)."""
|
|
451
|
+
with self._cerrojo:
|
|
452
|
+
if self._catalogo is not None and time.monotonic() - self._catalogo_en < self.catalog_ttl:
|
|
453
|
+
return self._catalogo
|
|
454
|
+
try:
|
|
455
|
+
catalogo = Catalog(self._json("GET", "classes", clave="optional", reintentos=_http.NADA))
|
|
456
|
+
except KosCloudError as e:
|
|
457
|
+
log.debug("kos-cloud: the catalog could not be read (%s); the service checks the limits", e)
|
|
458
|
+
return None
|
|
459
|
+
with self._cerrojo:
|
|
460
|
+
self._catalogo, self._catalogo_en = catalogo, time.monotonic()
|
|
461
|
+
return catalogo
|
|
462
|
+
|
|
463
|
+
def _revisa(self, tier, envio: _Envio, time_limit):
|
|
464
|
+
"""Los límites del nivel antes de subir nada: el tamaño del modelo y de la subida, y el límite de tiempo."""
|
|
465
|
+
catalogo = self._catalogo_para_revisar()
|
|
466
|
+
if catalogo is None:
|
|
467
|
+
return
|
|
468
|
+
clase = catalogo.get(tier if tier is not None else catalogo.default)
|
|
469
|
+
if clase is None:
|
|
470
|
+
return
|
|
471
|
+
if not clase.selectable:
|
|
472
|
+
raise MachineNotAvailableError(f"the machine tier {clase.id!r} cannot be selected for jobs",
|
|
473
|
+
"machine_not_available", None, {"machine": clase.id})
|
|
474
|
+
maximo = clase.limits.get("model_bytes")
|
|
475
|
+
if isinstance(maximo, int) and envio.sin_comprimir is not None and envio.sin_comprimir > maximo:
|
|
476
|
+
raise ModelTooLargeError(f"the model has {envio.sin_comprimir} bytes and the {clase.id} tier takes up "
|
|
477
|
+
f"to {maximo} bytes: choose a larger tier", "model_too_large", None,
|
|
478
|
+
{"max_bytes": maximo, "bytes": envio.sin_comprimir, "machine": clase.id})
|
|
479
|
+
subida = catalogo.upload_bytes
|
|
480
|
+
if isinstance(subida, int) and envio.por_subir > subida:
|
|
481
|
+
pista = "" if envio.comprimido else ": compress it (gzip, bzip2, xz or zip) and send the file"
|
|
482
|
+
raise ModelTooLargeError(f"the upload has {envio.por_subir} bytes and the limit is {subida} bytes{pista}",
|
|
483
|
+
"payload_too_large", None, {"max_bytes": subida, "bytes": envio.por_subir})
|
|
484
|
+
tope = clase.limits.get("time_limit_max")
|
|
485
|
+
if time_limit is not None and isinstance(tope, (int, float)) and not isinstance(tope, bool) \
|
|
486
|
+
and time_limit > tope:
|
|
487
|
+
raise TimeLimitError(f"time_limit is {time_limit:g} s and the {clase.id} tier allows up to {tope:g} s",
|
|
488
|
+
"invalid_parameter", None, {"max": tope, "machine": clase.id,
|
|
489
|
+
"parameters": [{"name": "time_limit",
|
|
490
|
+
"code": "invalid_value"}]})
|
|
491
|
+
|
|
492
|
+
# ------------------------------------------------------------ envío
|
|
493
|
+
|
|
494
|
+
def submit(self, model, *, tier: Optional[str] = None, time_limit: Optional[float] = None,
|
|
495
|
+
params: Optional[Mapping] = None, profile: Optional[str] = None, keep_model: Optional[bool] = None,
|
|
496
|
+
prove_objective: Optional[bool] = None, certificate: Optional[bool] = None,
|
|
497
|
+
name: Optional[str] = None, format: Optional[str] = None, check_limits: bool = True) -> Job:
|
|
498
|
+
"""Submit a model and return its `Job` at once, without waiting.
|
|
499
|
+
|
|
500
|
+
Args:
|
|
501
|
+
model: a file path (``str`` or ``PathLike``: ``.mps``, ``.lp``, or compressed ``.gz``, ``.bz2``,
|
|
502
|
+
``.xz``, ``.zip``, sent as it is), LP or MPS text (a ``str`` with line breaks), ``bytes`` (a file's
|
|
503
|
+
contents), or a ``kos.Model`` (sent as gzip-compressed MPS).
|
|
504
|
+
tier: the machine tier (``medium``, ``large``…; see `classes`). By default, the API's.
|
|
505
|
+
time_limit: seconds for the solve.
|
|
506
|
+
params: KOS parameters, ``{"name": value}``.
|
|
507
|
+
profile: a KOS parameter profile.
|
|
508
|
+
keep_model: keep the model in the cloud to solve it again later.
|
|
509
|
+
prove_objective: for an LP, prove the objective in exact arithmetic (the cloud does by default).
|
|
510
|
+
certificate: ask for the certificate of an LP.
|
|
511
|
+
name: a name for the job.
|
|
512
|
+
format: ``"mps"`` or ``"lp"`` when the name or contents do not say.
|
|
513
|
+
check_limits: check the size and ``time_limit`` against the tier before uploading (the service checks
|
|
514
|
+
them again).
|
|
515
|
+
|
|
516
|
+
Ctrl+C during the upload stops it; if it comes after the service received the whole model, the job may
|
|
517
|
+
have been created and keeps running: look for it with `jobs`.
|
|
518
|
+
|
|
519
|
+
Raises:
|
|
520
|
+
ModelTooLargeError, TimeLimitError, MachineNotAvailableError: before uploading, when the catalog says
|
|
521
|
+
the model or the time limit does not fit the tier; or from the API.
|
|
522
|
+
AuthenticationError, InsufficientBalanceError, EmailNotVerifiedError, RateLimitError, NetworkError,
|
|
523
|
+
KosCloudError.
|
|
524
|
+
"""
|
|
525
|
+
envio = _envio_de(model)
|
|
526
|
+
if time_limit is not None:
|
|
527
|
+
try:
|
|
528
|
+
time_limit = _segundos(time_limit, "time_limit")
|
|
529
|
+
except ValueError as e:
|
|
530
|
+
raise TimeLimitError(str(e), "invalid_parameter", None,
|
|
531
|
+
{"parameters": [{"name": "time_limit", "code": "invalid_value"}]}) from None
|
|
532
|
+
if params is not None and not isinstance(params, Mapping):
|
|
533
|
+
raise TypeError("params must be a dict of KOS parameters")
|
|
534
|
+
if check_limits:
|
|
535
|
+
self._revisa(tier, envio, time_limit if time_limit is not None else _limite_en(params))
|
|
536
|
+
campos: Dict[str, Any] = {}
|
|
537
|
+
for clave, valor in (("machine", tier), ("time_limit", time_limit), ("profile", profile),
|
|
538
|
+
("params", dict(params) if params else None), ("keep_model", keep_model),
|
|
539
|
+
("prove_objective", prove_objective), ("certificate", certificate), ("name", name),
|
|
540
|
+
("format", format)):
|
|
541
|
+
if valor is not None:
|
|
542
|
+
campos[clave] = bool(valor) if clave in ("keep_model", "prove_objective", "certificate") else valor
|
|
543
|
+
if envio.texto is not None:
|
|
544
|
+
cuerpo = json.dumps(dict(campos, model_text=envio.texto), ensure_ascii=False,
|
|
545
|
+
allow_nan=False).encode("utf-8")
|
|
546
|
+
tipo = "application/json"
|
|
547
|
+
else:
|
|
548
|
+
cuerpo, tipo = _multipart(campos, envio.bytes(), envio.nombre_archivo)
|
|
549
|
+
# Una clave por envío, la misma en sus reintentos: el servicio responde el mismo trabajo a una repetición.
|
|
550
|
+
llave = str(uuid.uuid4())
|
|
551
|
+
datos = self._json("POST", "jobs", cuerpo=cuerpo, tipo=tipo, cabeceras={"Idempotency-Key": llave},
|
|
552
|
+
reintentos=_http.IDEMPOTENTE)
|
|
553
|
+
trabajo = datos.get("job")
|
|
554
|
+
if not isinstance(trabajo, dict) or not isinstance(trabajo.get("id"), str) or not trabajo["id"]:
|
|
555
|
+
raise KosCloudError("the API did not return the submitted job", "invalid_response")
|
|
556
|
+
return Job(trabajo)
|
|
557
|
+
|
|
558
|
+
# ------------------------------------------------------------ espera
|
|
559
|
+
|
|
560
|
+
def wait(self, job, *, wait_timeout: Optional[float] = None, progress: ProgressArg = False,
|
|
561
|
+
cancel_on_interrupt: bool = True) -> Job:
|
|
562
|
+
"""Wait until the job ends (``finished``, ``failed`` or ``cancelled``) and return it.
|
|
563
|
+
|
|
564
|
+
It uses the API's long poll. With ``progress=True`` the log is written to stderr as it arrives (and a line
|
|
565
|
+
when the job is queued, starts and ends); a function instead receives each piece of the log text.
|
|
566
|
+
|
|
567
|
+
Ctrl+C: on ``KeyboardInterrupt`` while waiting, the job is cancelled cleanly (``POST jobs/{id}/cancel``), its
|
|
568
|
+
final state awaited for up to ~10 s, and the ``KeyboardInterrupt`` raised again. It does not ask, so it
|
|
569
|
+
behaves the same in scripts and notebooks. ``cancel_on_interrupt=False`` leaves the job running.
|
|
570
|
+
|
|
571
|
+
Args:
|
|
572
|
+
wait_timeout: the most seconds to wait; then `WaitTimeoutError` (the job keeps running).
|
|
573
|
+
"""
|
|
574
|
+
ident = _id_de(job)
|
|
575
|
+
avance = _Avance(progress)
|
|
576
|
+
if wait_timeout is not None:
|
|
577
|
+
wait_timeout = _segundos(wait_timeout, "wait_timeout")
|
|
578
|
+
try:
|
|
579
|
+
return self._espera(ident, avance, wait_timeout)
|
|
580
|
+
except KeyboardInterrupt:
|
|
581
|
+
if cancel_on_interrupt:
|
|
582
|
+
self._cancela_por_interrupcion(ident)
|
|
583
|
+
raise
|
|
584
|
+
|
|
585
|
+
def _espera(self, ident, avance: _Avance, plazo_total) -> Job:
|
|
586
|
+
estado, registro, eventos = "", 0, 0
|
|
587
|
+
limite = None if plazo_total is None else time.monotonic() + plazo_total
|
|
588
|
+
while True:
|
|
589
|
+
espera = self.poll_seconds
|
|
590
|
+
# Un trabajo ya terminado sólo vacía lo que queda de su registro: no tiene plazo.
|
|
591
|
+
if limite is not None and estado not in FINAL_STATES:
|
|
592
|
+
queda = limite - time.monotonic()
|
|
593
|
+
if queda <= 0:
|
|
594
|
+
raise WaitTimeoutError(f"job {ident} did not end within {plazo_total:g} s (it is {estado}); it "
|
|
595
|
+
"keeps running: wait again or cancel it", ident)
|
|
596
|
+
espera = max(1, min(espera, int(math.ceil(queda))))
|
|
597
|
+
inicio = time.monotonic()
|
|
598
|
+
datos = self._json("GET", _ruta_trabajo(ident, "/updates"),
|
|
599
|
+
consulta={"wait": espera, "log": registro, "events": eventos, "state": estado},
|
|
600
|
+
plazo=self.timeout + espera)
|
|
601
|
+
trabajo = datos.get("job")
|
|
602
|
+
if not isinstance(trabajo, dict):
|
|
603
|
+
raise KosCloudError("the API sent an update without the job", "invalid_response")
|
|
604
|
+
parte = datos.get("log") if isinstance(datos.get("log"), dict) else {}
|
|
605
|
+
texto = parte.get("text") if isinstance(parte.get("text"), str) else ""
|
|
606
|
+
# Un trozo del registro cuenta sólo si el cursor avanzó: un servicio que repite lo mismo no se muestra
|
|
607
|
+
# dos veces ni deja la espera girando.
|
|
608
|
+
siguiente = parte.get("offset")
|
|
609
|
+
if not (isinstance(siguiente, int) and not isinstance(siguiente, bool) and siguiente > registro):
|
|
610
|
+
texto = ""
|
|
611
|
+
else:
|
|
612
|
+
registro = siguiente
|
|
613
|
+
novedades = datos.get("events") if isinstance(datos.get("events"), dict) else {}
|
|
614
|
+
if isinstance(novedades.get("offset"), int) and not isinstance(novedades.get("offset"), bool) \
|
|
615
|
+
and novedades["offset"] > eventos:
|
|
616
|
+
eventos = novedades["offset"]
|
|
617
|
+
nuevo = trabajo.get("state")
|
|
618
|
+
if not isinstance(nuevo, str):
|
|
619
|
+
raise KosCloudError("the API sent an update without the job state", "invalid_response")
|
|
620
|
+
cambio = nuevo != estado
|
|
621
|
+
if cambio and nuevo not in FINAL_STATES:
|
|
622
|
+
avance.estado(trabajo)
|
|
623
|
+
avance.registro(texto)
|
|
624
|
+
estado = nuevo
|
|
625
|
+
if estado in FINAL_STATES:
|
|
626
|
+
# Con avance, lo que queda del registro sale antes de volver, y el estado final al último.
|
|
627
|
+
if avance.funcion is None or not texto:
|
|
628
|
+
avance.estado(trabajo)
|
|
629
|
+
return Job(trabajo)
|
|
630
|
+
continue
|
|
631
|
+
pausa = 0.0
|
|
632
|
+
pedida = datos.get("retry_after")
|
|
633
|
+
tardo = time.monotonic() - inicio
|
|
634
|
+
if isinstance(pedida, (int, float)) and not isinstance(pedida, bool) and pedida > 0:
|
|
635
|
+
pausa = min(float(pedida), 30.0)
|
|
636
|
+
elif not cambio and tardo < self.min_poll_interval and (avance.funcion is None or not texto):
|
|
637
|
+
pausa = self.min_poll_interval - tardo
|
|
638
|
+
if pausa > 0:
|
|
639
|
+
if limite is not None:
|
|
640
|
+
pausa = min(pausa, max(0.0, limite - time.monotonic()))
|
|
641
|
+
time.sleep(pausa)
|
|
642
|
+
|
|
643
|
+
def _cancela_por_interrupcion(self, ident):
|
|
644
|
+
"""Ctrl+C durante la espera: cancela el trabajo, espera su estado final un rato y avisa en stderr. Nada de
|
|
645
|
+
esto lanza otra excepción: el KeyboardInterrupt lo vuelve a lanzar wait()."""
|
|
646
|
+
# Todo (la cancelación, sus reintentos y la espera del estado final) cabe en cancel_wait_seconds.
|
|
647
|
+
limite = time.monotonic() + self.cancel_wait_seconds
|
|
648
|
+
_avisa(f"\nkos-cloud: interrupted: cancelling job {ident}\n")
|
|
649
|
+
try:
|
|
650
|
+
trabajo = self._trabajo_rapido("POST", _ruta_trabajo(ident, "/cancel"), limite, b"{}")
|
|
651
|
+
while not trabajo.is_final and time.monotonic() + 0.5 < limite:
|
|
652
|
+
time.sleep(0.5)
|
|
653
|
+
trabajo = self._trabajo_rapido("GET", _ruta_trabajo(ident), limite)
|
|
654
|
+
except KeyboardInterrupt:
|
|
655
|
+
_avisa(f"kos-cloud: interrupted again; job {ident} may still be running: kos_cloud.cancel({ident!r})\n")
|
|
656
|
+
return
|
|
657
|
+
except Exception as e: # noqa: BLE001 — nada reemplaza al KeyboardInterrupt
|
|
658
|
+
_avisa(f"kos-cloud: could not cancel job {ident} ({type(e).__name__}: {e}); cancel it with "
|
|
659
|
+
f"kos_cloud.cancel({ident!r})\n")
|
|
660
|
+
return
|
|
661
|
+
if trabajo.state == "finished":
|
|
662
|
+
# KOS paró al pedírselo y entregó lo que tenía (estado `interrupted`).
|
|
663
|
+
_avisa(f"kos-cloud: job {ident} is finished" + (f" ({trabajo.status})" if trabajo.status else "")
|
|
664
|
+
+ f"; what it found: kos_cloud.result({ident!r})\n")
|
|
665
|
+
elif trabajo.is_final:
|
|
666
|
+
_avisa(f"kos-cloud: job {ident} is {trabajo.state}\n")
|
|
667
|
+
else:
|
|
668
|
+
_avisa(f"kos-cloud: job {ident} is still {trabajo.state}; the cancellation is on its way\n")
|
|
669
|
+
|
|
670
|
+
def _trabajo_rapido(self, metodo, camino, hasta, cuerpo=None) -> Job:
|
|
671
|
+
datos = self._json(metodo, camino, cuerpo=cuerpo, tipo="application/json" if cuerpo is not None else None,
|
|
672
|
+
plazo=self.timeout, hasta=hasta)
|
|
673
|
+
if not isinstance(datos.get("job"), dict):
|
|
674
|
+
raise KosCloudError("the API did not return the job", "invalid_response")
|
|
675
|
+
return Job(datos["job"])
|
|
676
|
+
|
|
677
|
+
# ------------------------------------------------------------ resultado
|
|
678
|
+
|
|
679
|
+
def result(self, job, *, wait_timeout: Optional[float] = None, progress: ProgressArg = False, log: bool = False,
|
|
680
|
+
certificate: bool = False, solution: bool = True, cancel_on_interrupt: bool = True) -> Result:
|
|
681
|
+
"""Wait for the job (as `wait`, with the same Ctrl+C behavior) and return its `Result`.
|
|
682
|
+
|
|
683
|
+
Args:
|
|
684
|
+
log: also download the log (``Result.log``).
|
|
685
|
+
certificate: also download the LP certificate, if the job has one (``Result.certificate``).
|
|
686
|
+
solution: download the values, duals and reduced costs (``Result.values``…); ``False`` skips it.
|
|
687
|
+
|
|
688
|
+
Raises:
|
|
689
|
+
JobFailedError: the job failed (a `ModelTooLargeError` too when its error is ``model_too_large``).
|
|
690
|
+
JobCancelledError: the job was cancelled.
|
|
691
|
+
WaitTimeoutError: ``wait_timeout`` passed.
|
|
692
|
+
"""
|
|
693
|
+
final = self.wait(job, wait_timeout=wait_timeout, progress=progress, cancel_on_interrupt=cancel_on_interrupt)
|
|
694
|
+
ident = final.id
|
|
695
|
+
if final.state == "failed":
|
|
696
|
+
error = final.error if isinstance(final.error, dict) else {}
|
|
697
|
+
codigo = error.get("code")
|
|
698
|
+
mensaje = f"job {ident} failed: {error.get('message') or codigo or 'no reason given'}"
|
|
699
|
+
clase = JobModelTooLargeError if codigo == "model_too_large" else JobFailedError
|
|
700
|
+
raise clase(mensaje, codigo, final.data)
|
|
701
|
+
if final.state == "cancelled":
|
|
702
|
+
raise JobCancelledError(f"job {ident} was cancelled", final.data)
|
|
703
|
+
valores = duales = reducidos = None
|
|
704
|
+
resumen = final.result if isinstance(final.result, dict) else {}
|
|
705
|
+
if solution and resumen.get("has_solution", True) is not False:
|
|
706
|
+
datos = self._descarga_json(_ruta_trabajo(ident, "/solution.json"))
|
|
707
|
+
if datos is not None:
|
|
708
|
+
valores, reducidos, duales = {}, {}, {}
|
|
709
|
+
columnas, filas = datos.get("columns"), datos.get("rows")
|
|
710
|
+
for c in columnas if isinstance(columnas, list) else []:
|
|
711
|
+
if isinstance(c, dict) and isinstance(c.get("name"), str):
|
|
712
|
+
valores[c["name"]] = c.get("value")
|
|
713
|
+
if "reduced_cost" in c:
|
|
714
|
+
reducidos[c["name"]] = c["reduced_cost"]
|
|
715
|
+
for f in filas if isinstance(filas, list) else []:
|
|
716
|
+
if isinstance(f, dict) and isinstance(f.get("name"), str) and "dual" in f:
|
|
717
|
+
duales[f["name"]] = f["dual"]
|
|
718
|
+
texto = None
|
|
719
|
+
if log:
|
|
720
|
+
respuesta = self._descarga(_ruta_trabajo(ident, "/log"), "text/plain")
|
|
721
|
+
texto = respuesta.body.decode("utf-8", "replace") if respuesta is not None else None
|
|
722
|
+
certificado = None
|
|
723
|
+
if certificate and final.has_certificate is not False:
|
|
724
|
+
certificado = self._descarga_json(_ruta_trabajo(ident, "/certificate"))
|
|
725
|
+
return Result(final.data, valores, duales, reducidos, texto, certificado)
|
|
726
|
+
|
|
727
|
+
def _descarga(self, camino, acepta):
|
|
728
|
+
"""Una descarga (puede venir por una URL firmada); None si no existe (404)."""
|
|
729
|
+
try:
|
|
730
|
+
return self._pide("GET", camino, acepta=acepta)
|
|
731
|
+
except KosCloudError as e:
|
|
732
|
+
if e.status == 404 and e.code in ("not_found", "http_404"):
|
|
733
|
+
return None
|
|
734
|
+
raise
|
|
735
|
+
|
|
736
|
+
def _descarga_json(self, camino):
|
|
737
|
+
respuesta = self._descarga(camino, "application/json")
|
|
738
|
+
if respuesta is None:
|
|
739
|
+
return None
|
|
740
|
+
datos = respuesta.json()
|
|
741
|
+
if not isinstance(datos, dict):
|
|
742
|
+
raise KosCloudError(f"the download of {camino} is not a JSON object", "invalid_response")
|
|
743
|
+
return datos
|
|
744
|
+
|
|
745
|
+
def solve(self, model, *, tier: Optional[str] = None, time_limit: Optional[float] = None,
|
|
746
|
+
params: Optional[Mapping] = None, profile: Optional[str] = None, keep_model: Optional[bool] = None,
|
|
747
|
+
prove_objective: Optional[bool] = None, certificate: bool = False, name: Optional[str] = None,
|
|
748
|
+
format: Optional[str] = None, check_limits: bool = True, wait_timeout: Optional[float] = None,
|
|
749
|
+
progress: ProgressArg = False, log: bool = False, solution: bool = True,
|
|
750
|
+
cancel_on_interrupt: bool = True) -> Result:
|
|
751
|
+
"""Submit a model, wait for it and return its `Result`: `submit` followed by `result`.
|
|
752
|
+
|
|
753
|
+
Ctrl+C while waiting cancels the job cleanly and raises ``KeyboardInterrupt`` again (see `wait`).
|
|
754
|
+
|
|
755
|
+
Example::
|
|
756
|
+
|
|
757
|
+
r = client.solve("model.mps", tier="medium", time_limit=600)
|
|
758
|
+
print(r.status, r.objective, r.values["x"])
|
|
759
|
+
"""
|
|
760
|
+
trabajo = self.submit(model, tier=tier, time_limit=time_limit, params=params, profile=profile,
|
|
761
|
+
keep_model=keep_model, prove_objective=prove_objective,
|
|
762
|
+
certificate=True if certificate else None, name=name, format=format,
|
|
763
|
+
check_limits=check_limits)
|
|
764
|
+
return self.result(trabajo, wait_timeout=wait_timeout, progress=progress, log=log, certificate=certificate,
|
|
765
|
+
solution=solution, cancel_on_interrupt=cancel_on_interrupt)
|
|
766
|
+
|
|
767
|
+
# ------------------------------------------------------------ trabajos y saldo
|
|
768
|
+
|
|
769
|
+
def jobs(self, limit: int = 25, state: Union[str, List[str], None] = None, offset: int = 0) -> List[Job]:
|
|
770
|
+
"""The account's jobs, newest first. ``state`` filters by one state or a list of states."""
|
|
771
|
+
if isinstance(state, (list, tuple)):
|
|
772
|
+
state = ",".join(state)
|
|
773
|
+
datos = self._json("GET", "jobs", consulta={"limit": limit, "offset": offset or None, "state": state})
|
|
774
|
+
return [Job(j) for j in datos.get("jobs") or [] if isinstance(j, dict)]
|
|
775
|
+
|
|
776
|
+
def job(self, job) -> Job:
|
|
777
|
+
"""One job, with its state and result summary."""
|
|
778
|
+
datos = self._json("GET", _ruta_trabajo(_id_de(job)))
|
|
779
|
+
if not isinstance(datos.get("job"), dict):
|
|
780
|
+
raise KosCloudError("the API did not return the job", "invalid_response")
|
|
781
|
+
return Job(datos["job"])
|
|
782
|
+
|
|
783
|
+
def cancel(self, job) -> Job:
|
|
784
|
+
"""Cancel a queued or running job and return it (its state may still be ``running`` for a moment)."""
|
|
785
|
+
datos = self._json("POST", _ruta_trabajo(_id_de(job), "/cancel"), cuerpo=b"{}", tipo="application/json")
|
|
786
|
+
if not isinstance(datos.get("job"), dict):
|
|
787
|
+
raise KosCloudError("the API did not return the job", "invalid_response")
|
|
788
|
+
return Job(datos["job"])
|
|
789
|
+
|
|
790
|
+
def balance(self) -> Balance:
|
|
791
|
+
"""The balance of the account (``GET billing``), in dollars."""
|
|
792
|
+
return Balance(self._json("GET", "billing"))
|