ddpo-pytorch/ddpo_pytorch/prompts.py

70 lines
1.8 KiB
Python
Raw Normal View History

2023-06-24 04:25:54 +02:00
from importlib import resources
2023-06-27 19:20:03 +02:00
import os
2023-06-24 04:25:54 +02:00
import functools
import random
import inflect
IE = inflect.engine()
ASSETS_PATH = resources.files("ddpo_pytorch.assets")
@functools.cache
2023-06-27 19:20:03 +02:00
def _load_lines(path):
"""
Load lines from a file. First tries to load from `path` directly, and if that doesn't exist, searches the
`ddpo_pytorch/assets` directory for a file named `path`.
"""
if not os.path.exists(path):
newpath = ASSETS_PATH.joinpath(path)
if not os.path.exists(newpath):
raise FileNotFoundError(f"Could not find {path} or ddpo_pytorch.assets/{path}")
path = newpath
with open(path, "r") as f:
2023-06-24 04:25:54 +02:00
return [line.strip() for line in f.readlines()]
2023-06-27 19:20:03 +02:00
def from_file(path, low=None, high=None):
prompts = _load_lines(path)[low:high]
return random.choice(prompts), {}
2023-06-24 04:25:54 +02:00
def imagenet_all():
2023-06-27 19:20:03 +02:00
return from_file("imagenet_classes.txt")
2023-06-24 04:25:54 +02:00
def imagenet_animals():
2023-06-27 19:20:03 +02:00
return from_file("imagenet_classes.txt", 0, 398)
2023-06-24 04:25:54 +02:00
def imagenet_dogs():
2023-06-27 19:20:03 +02:00
return from_file("imagenet_classes.txt", 151, 269)
2023-06-24 04:25:54 +02:00
2023-06-27 19:40:36 +02:00
def simple_animals():
return from_file("simple_animals.txt")
2023-06-24 04:25:54 +02:00
def nouns_activities(nouns_file, activities_file):
2023-06-27 19:20:03 +02:00
nouns = _load_lines(nouns_file)
activities = _load_lines(activities_file)
2023-06-24 04:25:54 +02:00
return f"{IE.a(random.choice(nouns))} {random.choice(activities)}", {}
def counting(nouns_file, low, high):
2023-06-27 19:20:03 +02:00
nouns = _load_lines(nouns_file)
2023-06-24 04:25:54 +02:00
number = IE.number_to_words(random.randint(low, high))
noun = random.choice(nouns)
plural_noun = IE.plural(noun)
prompt = f"{number} {plural_noun}"
metadata = {
"questions": [
f"How many {plural_noun} are there in this image?",
f"What animal is in this image?",
],
"answers": [
number,
noun,
],
}
return prompt, metadata