Download bugfix_case_study/repro/truncate_fixed.py from protoneko/freelance-samples: direct link, hf CLI and curl.
- Browser
- Download file 2.3 kB
-
https://huggingface.co/datasets/protoneko/freelance-samples/resolve/main/bugfix_case_study/repro/truncate_fixed.py
- Command line
-
hf download hf://datasets/protoneko/freelance-samples/bugfix_case_study/repro/truncate_fixed.py
-
curl -L -o truncate_fixed.py https://huggingface.co/datasets/protoneko/freelance-samples/resolve/main/bugfix_case_study/repro/truncate_fixed.py
2.3 kB
| """Extracted verbatim from python-slugify (github.com/un33k/python-slugify). | |
| This is the `_modern_truncate` helper from slugify/slugify.py, isolated so the | |
| trailing-delimiter bug can be reproduced without the full package. The function | |
| body is copied exactly from the named commit; only the module docstring and the | |
| DEFAULT_SEPARATOR constant were added for standalone use. | |
| """ | |
| DEFAULT_SEPARATOR = '-' | |
| # Provenance: commit 8f9a550 (the fix) | |
| def truncate(text: str, max_length: int, word_boundary: bool, separator: str, save_order: bool) -> str: | |
| """Budget internal dash-separated tokens before mapping output delimiters. | |
| Output delimiters may also occur in words; never strip or split emitted text. | |
| Post replacements retain the historical global dash-to-separator mapping. | |
| """ | |
| if max_length <= 0: | |
| return text.replace(DEFAULT_SEPARATOR, separator) | |
| output_length = len(text) + text.count(DEFAULT_SEPARATOR) * (len(separator) - 1) | |
| if output_length <= max_length: | |
| return text.replace(DEFAULT_SEPARATOR, separator) | |
| tokens = text.split(DEFAULT_SEPARATOR) | |
| if word_boundary: | |
| words: list[str] = [] | |
| length = 0 | |
| for word in tokens: | |
| if not word: | |
| continue | |
| next_length = length + len(word) + (len(separator) if words else 0) | |
| if next_length <= max_length: | |
| words.append(word) | |
| length = next_length | |
| elif save_order: | |
| break | |
| if words: | |
| return separator.join(words) | |
| # A hard cut may shorten a word but must not emit a partial/trailing delimiter. | |
| parts: list[str] = [] | |
| length = 0 | |
| previous_index = 0 | |
| for index, word in enumerate(tokens): | |
| if not word: | |
| continue | |
| # Keep repeated delimiters with the next nonempty word until it fits. | |
| delimiter = separator * (index - previous_index) | |
| remaining = max_length - length - len(delimiter) | |
| if remaining <= 0: | |
| break | |
| parts.append(delimiter + word[:remaining]) | |
| length += len(delimiter) + min(len(word), remaining) | |
| previous_index = index | |
| if len(word) > remaining: | |
| break | |
| return ''.join(parts) | |