Upload collections.py with huggingface_hub
Browse files- collections.py +12 -7
collections.py
CHANGED
|
@@ -4,7 +4,7 @@ from typing import Dict, List
|
|
| 4 |
|
| 5 |
from .artifact import Artifact
|
| 6 |
from .dataclass import AbstractField
|
| 7 |
-
from .random_utils import
|
| 8 |
|
| 9 |
|
| 10 |
class Collection(Artifact):
|
|
@@ -13,8 +13,8 @@ class Collection(Artifact):
|
|
| 13 |
def __getitem__(self, key):
|
| 14 |
try:
|
| 15 |
return self.items[key]
|
| 16 |
-
except LookupError:
|
| 17 |
-
raise LookupError(f"Cannot find item {
|
| 18 |
|
| 19 |
|
| 20 |
class ListCollection(Collection):
|
|
@@ -43,13 +43,18 @@ class ItemPicker(Artifact):
|
|
| 43 |
def __call__(self, collection: Collection):
|
| 44 |
try:
|
| 45 |
return collection[int(self.item)]
|
| 46 |
-
except (
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
return collection[self.item]
|
| 48 |
|
| 49 |
|
| 50 |
class RandomPicker(Artifact):
|
| 51 |
def __call__(self, collection: Collection):
|
| 52 |
if isinstance(collection, ListCollection):
|
| 53 |
-
return
|
| 54 |
-
|
| 55 |
-
return
|
|
|
|
|
|
| 4 |
|
| 5 |
from .artifact import Artifact
|
| 6 |
from .dataclass import AbstractField
|
| 7 |
+
from .random_utils import get_random
|
| 8 |
|
| 9 |
|
| 10 |
class Collection(Artifact):
|
|
|
|
| 13 |
def __getitem__(self, key):
|
| 14 |
try:
|
| 15 |
return self.items[key]
|
| 16 |
+
except LookupError as e:
|
| 17 |
+
raise LookupError(f"Cannot find item {key!r} in {self!r}") from e
|
| 18 |
|
| 19 |
|
| 20 |
class ListCollection(Collection):
|
|
|
|
| 43 |
def __call__(self, collection: Collection):
|
| 44 |
try:
|
| 45 |
return collection[int(self.item)]
|
| 46 |
+
except (
|
| 47 |
+
SyntaxError,
|
| 48 |
+
KeyError,
|
| 49 |
+
ValueError,
|
| 50 |
+
): # in case picking from a dictionary
|
| 51 |
return collection[self.item]
|
| 52 |
|
| 53 |
|
| 54 |
class RandomPicker(Artifact):
|
| 55 |
def __call__(self, collection: Collection):
|
| 56 |
if isinstance(collection, ListCollection):
|
| 57 |
+
return get_random().choice(list(collection.items))
|
| 58 |
+
if isinstance(collection, DictCollection):
|
| 59 |
+
return get_random().choice(list(collection.items.values()))
|
| 60 |
+
return None
|