-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy path__init__.py
More file actions
77 lines (58 loc) · 2.62 KB
/
__init__.py
File metadata and controls
77 lines (58 loc) · 2.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import itertools
import random
from typing import Hashable
from . import dictionary
__all__ = ["generate_id", "num_combinations"]
system_random = random.SystemRandom()
def generate_id(
separator: str = "-",
seed: int | float | str | bytes | bytearray | None = None,
index: int | None = None,
) -> str:
"""
Generate a human readable ID in format: adjective-noun-NN
:param separator: The string to use to separate words
:param seed: The seed to use. The same seed will produce the same ID or index-based mapping
:param index: Optional non-negative integer providing a 1:1 mapping to an ID.
When provided, the mapping is deterministic and bijective for
all integers in range [0, total_combinations).
:return: A human readable ID
"""
# If a specific index is provided, use it for deterministic generation
if index is not None:
if not isinstance(index, int) or index < 0:
raise ValueError("index must be a non-negative integer if provided")
# Prepare category lists; if seed is provided, shuffle deterministically
if seed is not None:
rnd = random.Random(seed)
adjectives = tuple(rnd.sample(dictionary.adjectives, len(dictionary.adjectives)))
nouns = tuple(rnd.sample(dictionary.nouns, len(dictionary.nouns)))
else:
adjectives = dictionary.adjectives
nouns = dictionary.nouns
# Calculate total combinations: adjectives * nouns * 1000000 (for 000000-999999)
total = len(adjectives) * len(nouns) * 1000000
if index >= total:
raise ValueError(f"index out of range. Received {index}, max allowed is {total - 1}")
# Decompose index into adjective, noun, and number
number = index % 1000000
remaining = index // 1000000
noun_idx = remaining % len(nouns)
adj_idx = remaining // len(nouns)
adjective = adjectives[adj_idx]
noun = nouns[noun_idx]
return f"{adjective}{separator}{noun}{separator}{number:06d}"
# Random generation
random_obj = system_random
if seed is not None:
random_obj = random.Random(seed)
adjective = random_obj.choice(dictionary.adjectives)
noun = random_obj.choice(dictionary.nouns)
number = random_obj.randint(0, 999999)
return f"{adjective}{separator}{noun}{separator}{number:06d}"
def num_combinations() -> int:
"""
Return the total number of unique IDs possible.
Format uses adjective-noun-NNNNNN, so total = adjectives * nouns * 1000000.
"""
return len(dictionary.adjectives) * len(dictionary.nouns) * 1000000