Last active
April 7, 2022 11:47
-
-
Save charbonnierg/d8f8db68893b9a9cb366c287d8a6afb9 to your computer and use it in GitHub Desktop.
Text variants generation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
This is free and unencumbered software released into the public domain. | |
Anyone is free to copy, modify, publish, use, compile, sell, or | |
distribute this software, either in source code form or as a compiled | |
binary, for any purpose, commercial or non-commercial, and by any | |
means. | |
In jurisdictions that recognize copyright laws, the author or authors | |
of this software dedicate any and all copyright interest in the | |
software to the public domain. We make this dedication for the benefit | |
of the public at large and to the detriment of our heirs and | |
successors. We intend this dedication to be an overt act of | |
relinquishment in perpetuity of all present and future rights to this | |
software under copyright law. | |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, | |
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. | |
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR | |
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, | |
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR | |
OTHER DEALINGS IN THE SOFTWARE. | |
For more information, please refer to <http://unlicense.org/> | |
""" | |
from __future__ import annotations | |
import json | |
from typing import Callable, Dict, List, Union | |
def identity(string: str) -> str: | |
return string | |
class VariantTree: | |
def __init__( | |
self, | |
original: str, | |
transformer: Callable[[str], str] = identity, | |
width: int = 3, | |
depth: int = 3, | |
) -> None: | |
"""A class to perform variant generation. | |
Use the .fit() method to actually perform variant generation. | |
""" | |
self.width = width | |
self.depth = depth | |
self.original = original | |
self.transformer = transformer | |
self._levels: List[Dict[str, List[str]]] = [] | |
def dict(self) -> Dict[str, Union[List[str], Dict[str, List[str]]]]: | |
"""Return a dict representation of the tree. | |
Dict is empty until tree is fitted (fitting can be done using .fit() method) | |
""" | |
# Create dicts from bottom to top | |
_tree: Dict[str, Union[List[str], Dict[str, List[str]]]] = dict() | |
# Iterate from bottom to top | |
for level in reversed(self._levels): | |
# Create tree using bottom values | |
if not _tree: | |
_tree.update(level) | |
else: | |
# Create new tree | |
_tree = { | |
key: {subkey: _tree[subkey] for subkey in values} # type: ignore[misc] | |
for key, values in level.items() | |
} | |
return _tree | |
def __repr__(self) -> str: | |
"""String representation of the tree""" | |
return "Tree(" + json.dumps(self.dict(), indent=2) + ")" | |
def _apply_once(self, value: str) -> List[str]: | |
"""Apply transformation on a single value""" | |
return [self.transformer(value) for _ in range(self.width)] | |
def fit(self) -> VariantTree: | |
"""Fit the tree, I.E, generate variants""" | |
# Empty levels | |
self._levels = [] | |
# Get first variants | |
first_variants = self._apply_once(self.original) | |
# Append first level | |
self._levels.append({self.original: first_variants}) | |
# Keep track of remaining depth | |
remaining_depth = self.depth - 1 | |
# Loop while there is reamining depth | |
while remaining_depth >= 0: | |
# Initialize new level | |
new_level: Dict[str, List[str]] = {} | |
# Gather values from last levels | |
for values in self._levels[-1].values(): | |
for value in values: | |
new_variants = self._apply_once(value) | |
# FIXME: There might be a conflict here !! | |
# Because all keys are at the same level regardless of parent, | |
# if two ancestor lead to same text, the "oldest" will be forgotten | |
# Even indexing using tuple(ancestor, new_value) will not work | |
# We need an index | |
new_level[value] = new_variants | |
# Append new level | |
self._levels.append(new_level) | |
# Decrease remaining depth | |
remaining_depth -= 1 | |
# Return self | |
return self | |
if __name__ == "__main__": | |
import random | |
def transform(value: str) -> str: | |
value_list = list(value) | |
random.shuffle(value_list) | |
return "".join(value_list) | |
tree = VariantTree("Hello world!", transformer=transform, width=2, depth=2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment