| 1 | import secrets |
| 2 | |
| 3 | class IdentifierTool: |
| 4 | def __init__(self, method: str='order', existing_labels: dict[str]={}) -> None: |
| 5 | self.methods = { |
| 6 | 'order': self.get_identifier_in_order, |
| 7 | 'random': self.get_random_identifier, |
| 8 | } |
| 9 | |
| 10 | if method is None: |
| 11 | method = 'order' |
| 12 | |
| 13 | self.func = self.methods.get(method, None) |
| 14 | self.name = method |
| 15 | if self.func is None: |
| 16 | raise ValueError(f'Invalid method for identifier: {method}') |
| 17 | |
| 18 | self.reset(existing_labels) |
| 19 | |
| 20 | def reset(self, exists: dict[str]={}) -> None: |
| 21 | self.identifier = -1 |
| 22 | self.exists = {} if exists is None else exists |
| 23 | |
| 24 | def get_identifier_in_order(self) -> str: |
| 25 | def id2str(id: int) -> str: |
| 26 | if id < 26: |
| 27 | return chr(id + 65) |
| 28 | id -= 26 |
| 29 | c0 = id // 676 |
| 30 | c1 = (id // 26) % 26 |
| 31 | c2 = id % 26 |
| 32 | label = f'{chr(c1 + 65)}{chr(c2 + 65)}' |
| 33 | return label if c0 == 0 else f'{chr(c0 + 64)}{label}' |
| 34 | |
| 35 | self.identifier += 1 |
| 36 | label = id2str(self.identifier) |
| 37 | |
| 38 | while label in self.exists: |
| 39 | self.identifier += 1 |
| 40 | label = id2str(self.identifier) |
| 41 | |
| 42 | self.exists[label] = True |
| 43 | return label |
| 44 | |
| 45 | def get_random_identifier(self) -> str: |
| 46 | secret_generator = secrets.SystemRandom() |
| 47 | |
| 48 | def get_random_label(n: int=2) -> str: |
| 49 | tmp = '' |
| 50 | for _ in range(n): |
| 51 | tmp += chr(secret_generator.randint(65, 90)) |
| 52 | return tmp |
| 53 | |
| 54 | wc = 3 if len(self.exists) > 280 else 2 |
| 55 | |
| 56 | label = get_random_label(wc) |
| 57 | while label in self.exists: |
| 58 | label = get_random_label(wc) |
| 59 | |
| 60 | self.exists[label] = True |