Spaces:
Sleeping
Sleeping
Upload validation.py
Browse files- app/utils/validation.py +40 -0
app/utils/validation.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
from typing import Any
|
3 |
+
|
4 |
+
_TAG_RE = re.compile(r"^[A-Za-z0-9_\-]{1,64}$")
|
5 |
+
_DATASET_RE = re.compile(r"^[A-Za-z0-9_.\-]+\/[A-Za-z0-9_.\-]+$|^[A-Za-z0-9_.\-]+$")
|
6 |
+
|
7 |
+
class ValidationError(ValueError):
|
8 |
+
pass
|
9 |
+
|
10 |
+
def safe_tag(s: str) -> str:
|
11 |
+
if not isinstance(s, str):
|
12 |
+
raise ValidationError("Experiment tag must be a string")
|
13 |
+
if not _TAG_RE.match(s):
|
14 |
+
raise ValidationError("Experiment tag must be 1–64 chars: letters, numbers, _ or -")
|
15 |
+
return s
|
16 |
+
|
17 |
+
def safe_dataset_id(s: str) -> str:
|
18 |
+
if not isinstance(s, str):
|
19 |
+
raise ValidationError("Dataset id must be a string")
|
20 |
+
if not _DATASET_RE.match(s):
|
21 |
+
raise ValidationError("Dataset must look like 'owner/name' or a public name")
|
22 |
+
return s
|
23 |
+
|
24 |
+
def safe_float(x: Any, lo: float, hi: float, name: str) -> float:
|
25 |
+
try:
|
26 |
+
v = float(x)
|
27 |
+
except Exception:
|
28 |
+
raise ValidationError(f"{name} must be a number")
|
29 |
+
if not (lo <= v <= hi):
|
30 |
+
raise ValidationError(f"{name} must be in [{lo}, {hi}]")
|
31 |
+
return v
|
32 |
+
|
33 |
+
def safe_int(x: Any, lo: int, hi: int, name: str) -> int:
|
34 |
+
try:
|
35 |
+
v = int(x)
|
36 |
+
except Exception:
|
37 |
+
raise ValidationError(f"{name} must be an integer")
|
38 |
+
if not (lo <= v <= hi):
|
39 |
+
raise ValidationError(f"{name} must be in [{lo}, {hi}]")
|
40 |
+
return v
|