Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/slugify/slugify.py: 21%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

161 statements  

1from __future__ import annotations 

2 

3import re 

4import unicodedata 

5from collections.abc import Iterable 

6from html.entities import name2codepoint 

7from importlib import import_module 

8from typing import Literal 

9 

10from ._legacy import slugify as _legacy_slugify, smart_truncate 

11 

12__all__ = ['slugify', 'smart_truncate', 'Backend', 'ReplacementStage', 'Algorithm'] 

13 

14 

15CHAR_ENTITY_PATTERN = re.compile(r'&(%s);' % '|'.join(name2codepoint)) 

16DECIMAL_PATTERN = re.compile(r'&#(\d+);') 

17MODERN_HEX_PATTERN = re.compile(r'&#[xX]([\da-fA-F]+);') 

18QUOTE_PATTERN = re.compile(r"[']+") 

19DISALLOWED_CHARS_PATTERN = re.compile(r'[^-a-zA-Z0-9]+') 

20DISALLOWED_UNICODE_CHARS_PATTERN = re.compile(r'[\W_]+') 

21DUPLICATE_DASH_PATTERN = re.compile(r'-{2,}') 

22NUMBERS_PATTERN = re.compile(r'(?<=\d),(?=\d)') 

23DEFAULT_SEPARATOR = '-' 

24# Zero-width non-joiner/joiner: spelling-significant inside words in Indic, 

25# Sinhala and Persian text (e.g. Sinhala "ශ්‍රී"), invisible noise elsewhere. 

26WORD_JOINERS = frozenset('\u200c\u200d') 

27# Python's \w excludes nonspacing/spacing combining marks (Mn/Mc), which split 

28# Devanagari, Tamil, Bengali, Thai, Arabic, Hebrew, etc. words apart. 

29COMBINING_MARK_CATEGORIES = frozenset(('Mn', 'Mc')) 

30 

31Backend = Literal['auto', 'text-unidecode', 'unidecode', 'anyascii'] 

32ReplacementStage = Literal['both', 'pre', 'post'] 

33Algorithm = Literal['legacy', 'modern'] 

34 

35 

36def _numeric_reference(match: re.Match[str], base: int) -> str: 

37 """Leave invalid references for ordinary filtering, independently of neighbors.""" 

38 try: 

39 value = int(match.group(1), base) 

40 if 0xD800 <= value <= 0xDFFF: 

41 return match.group(0) 

42 return chr(value) 

43 except (ValueError, OverflowError): 

44 return match.group(0) 

45 

46 

47def _decode_entities(text: str, entities: bool, decimal: bool, hexadecimal: bool) -> str: 

48 if entities: 

49 text = CHAR_ENTITY_PATTERN.sub(lambda m: chr(name2codepoint[m.group(1)]), text) 

50 if decimal: 

51 text = DECIMAL_PATTERN.sub(lambda m: _numeric_reference(m, 10), text) 

52 if hexadecimal: 

53 text = MODERN_HEX_PATTERN.sub(lambda m: _numeric_reference(m, 16), text) 

54 return text 

55 

56 

57def _transliterate(text: str, backend: Backend) -> str: 

58 # Every backend maps 7-bit ASCII to itself; skip importing one (text-unidecode's table is ~3 MB). 

59 if text.isascii(): 

60 return text 

61 if backend == 'auto': 

62 try: 

63 module = import_module('unidecode') 

64 except ModuleNotFoundError as error: 

65 if error.name != 'unidecode': 

66 raise 

67 module = import_module('text_unidecode') 

68 else: 

69 module = import_module(backend.replace('-', '_')) 

70 # These third-party modules share a string-to-string API; some are untyped. 

71 result: str = getattr(module, 'anyascii' if backend == 'anyascii' else 'unidecode')(text) 

72 return result 

73 

74 

75def _is_combining_mark(char: str) -> bool: 

76 # Variation selectors are Mn but select emoji/glyph styles, not spelling. 

77 if '\ufe00' <= char <= '\ufe0f' or '\U000e0100' <= char <= '\U000e01ef': 

78 return False 

79 return unicodedata.category(char) in COMBINING_MARK_CATEGORIES 

80 

81 

82def _replace_disallowed_unicode(text: str) -> str: 

83 """Modern Unicode-mode filter: [\\W_]+ -> '-', but keep words whole. 

84 

85 A combining mark is a word character when it continues a word; a ZWNJ/ZWJ 

86 is kept only between word parts. Identical to the plain [\\W_]+ filter 

87 for text without combining marks or joiners. 

88 """ 

89 if text.isascii(): # No marks or joiners possible: keep the fast C regex path. 

90 return DISALLOWED_UNICODE_CHARS_PATTERN.sub(DEFAULT_SEPARATOR, text) 

91 chars: list[str] = [] 

92 in_word = False 

93 last = len(text) - 1 

94 for index, char in enumerate(text): 

95 if char.isalnum(): # Same definition as str-pattern \w, minus '_'. 

96 in_word = True 

97 elif in_word and _is_combining_mark(char): 

98 pass 

99 elif in_word and char in WORD_JOINERS and index < last and ( 

100 text[index + 1].isalnum() or _is_combining_mark(text[index + 1])): 

101 pass 

102 else: 

103 in_word = False 

104 char = DEFAULT_SEPARATOR 

105 chars.append(char) 

106 return ''.join(chars) 

107 

108 

109def _modern_truncate(text: str, max_length: int, word_boundary: bool, separator: str, save_order: bool) -> str: 

110 """Budget internal dash-separated tokens before mapping output delimiters. 

111 

112 Output delimiters may also occur in words; never strip or split emitted text. 

113 Post replacements retain the historical global dash-to-separator mapping. 

114 """ 

115 if max_length <= 0: 

116 return text.replace(DEFAULT_SEPARATOR, separator) 

117 output_length = len(text) + text.count(DEFAULT_SEPARATOR) * (len(separator) - 1) 

118 if output_length <= max_length: 

119 return text.replace(DEFAULT_SEPARATOR, separator) 

120 tokens = text.split(DEFAULT_SEPARATOR) 

121 if word_boundary: 

122 words: list[str] = [] 

123 length = 0 

124 previous_index = 0 

125 first_word = True 

126 for index, word in enumerate(tokens): 

127 if not word: 

128 continue 

129 # Keep the full delimiter run attached to each retained word. 

130 # Skipping an oversized first word must not add a leading delimiter. 

131 delimiter = separator * (index - previous_index) if words or first_word else '' 

132 previous_index = index 

133 first_word = False 

134 next_length = length + len(delimiter) + len(word) 

135 if next_length <= max_length: 

136 words.append(delimiter + word) 

137 length = next_length 

138 elif save_order: 

139 break 

140 if words: 

141 return ''.join(words) 

142 # A hard cut may shorten a word but must not emit a partial/trailing delimiter. 

143 parts: list[str] = [] 

144 length = 0 

145 previous_index = 0 

146 for index, word in enumerate(tokens): 

147 if not word: 

148 continue 

149 # Keep repeated delimiters with the next nonempty word until it fits. 

150 delimiter = separator * (index - previous_index) 

151 remaining = max_length - length - len(delimiter) 

152 if remaining <= 0: 

153 break 

154 # A cut must not leave an invisible joiner dangling at the end. 

155 parts.append(delimiter + word[:remaining].rstrip(''.join(WORD_JOINERS))) 

156 length += len(delimiter) + min(len(word), remaining) 

157 previous_index = index 

158 if len(word) > remaining: 

159 break 

160 return ''.join(parts) 

161 

162 

163def _modern_slugify( 

164 text: str | bytes | bytearray, 

165 entities: bool, 

166 decimal: bool, 

167 hexadecimal: bool, 

168 max_length: int, 

169 word_boundary: bool, 

170 separator: str, 

171 save_order: bool, 

172 stopwords: Iterable[str], 

173 regex_pattern: re.Pattern[str] | str | None, 

174 lowercase: bool, 

175 replacements: Iterable[Iterable[str]], 

176 allow_unicode: bool, 

177 replacement_stage: ReplacementStage, 

178 backend: Backend, 

179) -> str: 

180 # bool is an int subclass: legacy silently treats max_length=True as 1. 

181 # Modern rejects it, and a non-str separator, up front. 

182 if isinstance(max_length, bool) or not isinstance(max_length, int): 

183 raise TypeError(f"max_length must be an int, not {type(max_length).__name__}") 

184 if not isinstance(separator, str): 

185 raise TypeError(f"separator must be str, not {type(separator).__name__}") 

186 if not isinstance(text, str): 

187 if not isinstance(text, (bytes, bytearray)): 

188 raise TypeError(f'text must be str, bytes or bytearray, not {type(text).__name__}') 

189 text = text.decode('utf-8', 'ignore') 

190 if replacement_stage not in ('both', 'pre', 'post'): 

191 raise ValueError("replacement_stage must be 'both', 'pre' or 'post'") 

192 if backend not in ('auto', 'text-unidecode', 'unidecode', 'anyascii'): 

193 raise ValueError("backend must be 'auto', 'text-unidecode', 'unidecode' or 'anyascii'") 

194 

195 # Materialize rules once: consumption of an iterator would affect output. 

196 rules = tuple((old, new) for old, new in replacements) if replacements else () 

197 if rules and replacement_stage in ('both', 'pre'): 

198 for old, new in rules: 

199 text = text.replace(old, new) 

200 

201 text = _decode_entities(text, entities, decimal, hexadecimal) 

202 text = QUOTE_PATTERN.sub(DEFAULT_SEPARATOR, text) 

203 if allow_unicode: 

204 text = unicodedata.normalize('NFKC', text) 

205 else: 

206 text = _transliterate(unicodedata.normalize('NFKD', text), backend) 

207 text = unicodedata.normalize('NFKC' if allow_unicode else 'NFKD', text) 

208 if lowercase: 

209 text = text.lower() 

210 text = QUOTE_PATTERN.sub('', text) 

211 text = NUMBERS_PATTERN.sub('', text) 

212 if regex_pattern: 

213 text = re.sub(regex_pattern, DEFAULT_SEPARATOR, text) 

214 elif allow_unicode: 

215 text = _replace_disallowed_unicode(text) 

216 else: 

217 text = DISALLOWED_CHARS_PATTERN.sub(DEFAULT_SEPARATOR, text) 

218 text = DUPLICATE_DASH_PATTERN.sub(DEFAULT_SEPARATOR, text).strip(DEFAULT_SEPARATOR) 

219 

220 if stopwords: 

221 excluded = {word.lower() if lowercase else word for word in stopwords} 

222 text = DEFAULT_SEPARATOR.join(word for word in text.split(DEFAULT_SEPARATOR) if word not in excluded) 

223 if rules and replacement_stage in ('both', 'post'): 

224 for old, new in rules: 

225 text = text.replace(old, new) 

226 

227 return _modern_truncate(text, max_length, word_boundary, separator, save_order) 

228 

229 

230def slugify( 

231 text: str | bytes | bytearray, 

232 entities: bool = True, 

233 decimal: bool = True, 

234 hexadecimal: bool = True, 

235 max_length: int = 0, 

236 word_boundary: bool = False, 

237 separator: str = DEFAULT_SEPARATOR, 

238 save_order: bool = False, 

239 stopwords: Iterable[str] = (), 

240 regex_pattern: re.Pattern[str] | str | None = None, 

241 lowercase: bool = True, 

242 replacements: Iterable[Iterable[str]] = (), 

243 allow_unicode: bool = False, 

244 *, 

245 replacement_stage: ReplacementStage = 'both', 

246 backend: Backend = 'auto', 

247 algorithm: Algorithm = 'legacy', 

248) -> str: 

249 """Make a slug with the legacy output pipeline by default, permanently. 

250 

251 algorithm='legacy' (the default) dispatches to the frozen legacy pipeline in 

252 slugify._legacy, which must never change. algorithm='modern' opts into early 

253 entity decoding, reusable iterator rules, stable stopword membership, a final 

254 emitted-character length budget, and up-front argument type validation. 

255 Bytes and bytearray are decoded as UTF-8, ignoring invalid bytes. 

256 replacements are ordered literal rules, before and after cleanup by default; 

257 replacement_stage selects 'pre', 'post' or 'both'. Post rules are unfiltered. 

258 regex_pattern matches disallowed characters; stopwords match internal words. 

259 allow_unicode uses NFKC without transliteration. backend='auto' prefers 

260 installed Unidecode, falling back to text-unidecode; explicit choices do not 

261 fall back. All new controls are keyword-only. 

262 """ 

263 if algorithm not in ('legacy', 'modern'): 

264 raise ValueError("algorithm must be 'legacy' or 'modern'") 

265 if algorithm == 'legacy': 

266 return _legacy_slugify( 

267 text, entities, decimal, hexadecimal, max_length, word_boundary, 

268 separator, save_order, stopwords, regex_pattern, lowercase, 

269 replacements, allow_unicode, 

270 replacement_stage=replacement_stage, backend=backend) 

271 return _modern_slugify( 

272 text, entities, decimal, hexadecimal, max_length, word_boundary, 

273 separator, save_order, stopwords, regex_pattern, lowercase, 

274 replacements, allow_unicode, replacement_stage, backend)