smol-html 0.1.1__py3-none-any.whl → 0.1.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
smol_html/__init__.py CHANGED
@@ -1,4 +1,4 @@
1
1
  from smol_html.smol_html import SmolHtmlCleaner
2
2
 
3
3
  all = ["__version__", "SmolHtmlCleaner"]
4
- __version__ = "0.1.0"
4
+ __version__ = "0.1.0"
smol_html/smol_html.py CHANGED
@@ -1,328 +1,377 @@
1
- from __future__ import annotations
2
-
3
- import minify_html
4
- from bs4 import BeautifulSoup, Tag
5
- from lxml import html as lxml_html
6
- from lxml.html.clean import Cleaner
7
-
8
-
9
- # -------------------------
10
- # Public API
11
- # -------------------------
12
- class SmolHtmlCleaner:
13
- """
14
- Small, dependable HTML cleaner/minifier with sensible defaults.
15
-
16
- Parameters
17
- ----------
18
- non_text_to_keep : set of str, optional
19
- Tags preserved even if textless. Default includes meta/media/table/line-break tags.
20
- attr_stop_words : set of str, optional
21
- Attribute tokens indicating non-content scaffolding/UX. Default contains common UI tokens.
22
- remove_header_lists : bool, optional
23
- Prune links/lists inside ``<header>``. Default True.
24
- remove_footer_lists : bool, optional
25
- Prune links/lists inside ``<footer>``. Default True.
26
- minify : bool, optional
27
- Minify HTML output via ``minify_html``. Default True.
28
- minify_kwargs : dict, optional
29
- Extra args for ``minify_html.minify``. Default empty.
30
-
31
- lxml Cleaner parameters
32
- ----------------------
33
- meta : bool, optional
34
- Remove meta tags. Default False.
35
- page_structure : bool, optional
36
- Remove page structure tags (html, head, body). Default False.
37
- links : bool, optional
38
- Remove link tags. Default True.
39
- scripts : bool, optional
40
- Remove script tags. Default False.
41
- javascript : bool, optional
42
- Remove JavaScript content. Default True.
43
- comments : bool, optional
44
- Remove comments. Default True.
45
- style : bool, optional
46
- Remove style tags. Default True.
47
- processing_instructions : bool, optional
48
- Remove processing instructions. Default True.
49
- embedded : bool, optional
50
- Remove embedded content (object, embed, applet). Default True.
51
- frames : bool, optional
52
- Remove frame/iframe tags. Default True.
53
- forms : bool, optional
54
- Remove form tags. Default True.
55
- annoying_tags : bool, optional
56
- Remove tags considered annoying (blink, marquee, etc). Default True.
57
- kill_tags : set of str, optional
58
- Additional tags to remove. Default None.
59
- remove_unknown_tags : bool, optional
60
- Remove unknown tags. Default True.
61
- safe_attrs_only : bool, optional
62
- Only keep safe attributes. Default True.
63
- safe_attrs : set of str, optional
64
- Set of safe attributes to keep. Default is a sensible set.
65
-
66
- Notes
67
- -----
68
- Defaults and cleaning behavior are preserved; only the configuration surface
69
- moved from a dataclass to keyword-only parameters on the constructor.
70
- """
71
-
72
- def __init__(
73
- self,
74
- *,
75
- # Core behavior
76
- non_text_to_keep: set[str] = None,
77
- attr_stop_words: set[str] = None,
78
- remove_header_lists: bool = True,
79
- remove_footer_lists: bool = True,
80
- # Minify
81
- minify: bool = True,
82
- minify_kwargs: dict | None = None,
83
- # lxml Cleaner exposed explicitly (prefixed)
84
- meta: bool = False,
85
- page_structure: bool = False,
86
- links: bool = True,
87
- scripts: bool = False,
88
- javascript: bool = True,
89
- comments: bool = True,
90
- style: bool = True,
91
- processing_instructions: bool = True,
92
- embedded: bool = True,
93
- frames: bool = True,
94
- forms: bool = True,
95
- annoying_tags: bool = True,
96
- kill_tags: set[str] | None = None,
97
- remove_unknown_tags: bool = True,
98
- safe_attrs_only: bool = True,
99
- safe_attrs: set[str] = None,
100
- ):
101
- # Inline defaults identical to the prior CleanerConfig
102
- if safe_attrs is None:
103
- safe_attrs = {"href", "hreflang", "src", "srclang", "target", "alt", "kind", "type", "role", "abbr",
104
- "accept", "accept-charset", "datetime", "lang", "name", "rel", "title", "value", "content", "label",
105
- "item_type", "property", "itemprop"}
106
-
107
- if attr_stop_words is None:
108
- attr_stop_words = {"alert", "button", "checkbox", "dialog", "navigation", "tab", "tabpanel", "textbox",
109
- "menu", "banner", "form", "search", "progressbar", "radio", "slider", "comment", "nav", "sidebar",
110
- "breadcrumb", "dropdown", "menu-item", "toggle", "hamburger", "aside", "tooltip", "modal", "overlay",
111
- "popup", "advert", "hero", "utility", "login", "signup", "password", "email", "username"}
112
-
113
- if non_text_to_keep is None:
114
- non_text_to_keep = {"meta", "img", "picture", "figure", "figcaption", "video", "source", "audio", "table",
115
- "tr", "th", "td", "thead", "tbody", "tfoot", "caption", "br"}
116
-
117
- self.non_text_to_keep = non_text_to_keep
118
- self.attr_stop_words = attr_stop_words
119
- self.remove_header_lists = remove_header_lists
120
- self.remove_footer_lists = remove_footer_lists
121
- self.minify = minify
122
- self.minify_kwargs = dict(minify_kwargs or {})
123
-
124
- # Initialize lxml Cleaner with explicit kwargs gathered from parameters
125
- self._cleaner = Cleaner(
126
- meta=meta,
127
- page_structure=page_structure,
128
- links=links,
129
- scripts=scripts,
130
- javascript=javascript,
131
- comments=comments,
132
- style=style,
133
- processing_instructions=processing_instructions,
134
- embedded=embedded,
135
- frames=frames,
136
- forms=forms,
137
- annoying_tags=annoying_tags,
138
- kill_tags=kill_tags,
139
- remove_unknown_tags=remove_unknown_tags,
140
- safe_attrs_only=safe_attrs_only,
141
- safe_attrs=safe_attrs,
142
- )
143
-
144
- # -------------------------
145
- # User-friendly entry points
146
- # -------------------------
147
-
148
-
149
- def clean(self, *, raw_html: str | BeautifulSoup) -> str:
150
- """Clean and optionally minify HTML input.
151
-
152
- The cleaning pipeline applies pre-parse hooks (on strings), prunes elements
153
- by attribute stop words, sanitizes via lxml Cleaner, performs structural
154
- pruning of header/footer/body, then applies post-clean hooks.
155
-
156
- Parameters
157
- ----------
158
- raw_html : str or BeautifulSoup
159
- Raw HTML string or BeautifulSoup to be cleaned.
160
-
161
- Returns
162
- -------
163
- str
164
- Cleaned HTML as a string.
165
- """
166
-
167
- # Stage 0: hooks that operate on the raw string
168
- if isinstance(raw_html, str):
169
- soup = BeautifulSoup(raw_html or "", features="lxml")
170
- elif isinstance(raw_html, BeautifulSoup):
171
- soup = raw_html
172
- else:
173
- raise TypeError("raw_html must be a str or BeautifulSoup instance")
174
-
175
- # Stage 1: attribute-based pruning on the original soup
176
- # Remove small, likely non-content elements based on attribute tokens.
177
- self._strip_by_attribute_stop_words(soup=soup)
178
-
179
- # Stage 2: lxml cleaner pass (robust HTML sanitation)
180
- # Use lxml Cleaner to sanitize HTML, optionally minify afterwards.
181
- cleaned_html = self._lxml_clean(str(soup))
182
- clean_soup = BeautifulSoup(markup=cleaned_html, features="lxml")
183
-
184
- # Stage 3: structural pruning on header/body/footer of the cleaned soup
185
- self._prune_header_footer(clean_soup)
186
- self._prune_body(clean_soup)
187
- self._drop_empty_leaf_nodes(clean_soup)
188
-
189
- return str(clean_soup)
190
-
191
- # -------------------------
192
- # Internal helpers
193
- # -------------------------
194
- def _lxml_clean(self, html_str: str) -> str:
195
- """Sanitize and optionally minify HTML using lxml + minify_html.
196
-
197
- Parameters
198
- ----------
199
- html_str : str
200
- HTML markup to be cleaned.
201
-
202
- Returns
203
- -------
204
- str
205
- Cleaned (and possibly minified) HTML markup.
206
- """
207
- try:
208
- cleaned = self._cleaner.clean_html(html_str)
209
- return minify_html.minify(cleaned, **self.minify_kwargs) if self.minify else cleaned
210
- except ValueError as ex:
211
- # Handle encoding declaration edge-cases by round-tripping via lxml
212
- msg = (
213
- "Unicode strings with encoding declaration are not supported. "
214
- "Please use bytes input or XML fragments without declaration."
215
- )
216
- if str(ex) == msg:
217
- raw_bytes = html_str.encode("utf-8", errors="ignore")
218
- doc = lxml_html.fromstring(raw_bytes)
219
- cleaned = self._cleaner.clean_html(doc)
220
- rendered = lxml_html.tostring(cleaned, encoding="utf-8").decode("utf-8")
221
- return minify_html.minify(rendered, **self.minify_kwargs) if self.minify else rendered
222
- raise
223
-
224
- def _strip_by_attribute_stop_words(self, *, soup: BeautifulSoup) -> None:
225
- """Remove small, likely non-content elements by attribute tokens.
226
-
227
- Scans leaf-like descendants under ``<body>`` and collects elements whose
228
- ``id``, ``class``, ``role``, or ``item_type`` values contain any of the
229
- configured ``attr_stop_words`` tokens (case-insensitive), then decomposes
230
- them. Mirrors the baseline leaf-ness and concatenation behavior.
231
-
232
- Parameters
233
- ----------
234
- soup : BeautifulSoup
235
- Parsed document to prune in place.
236
- """
237
- body = soup.find("body") or soup
238
- to_decompose: list[Tag] = []
239
- for el in body.descendants:
240
- if not isinstance(el, Tag):
241
- continue
242
- attrs = el.attrs if isinstance(el.attrs, dict) else {}
243
- if not attrs:
244
- continue
245
- # Only prune simple leaf-ish nodes to avoid huge deletes unintentionally
246
- if sum(1 for _ in el.descendants) > 1:
247
- continue
248
- for name in ("id", "class", "role", "item_type"):
249
- val = attrs.get(name)
250
- if val is None:
251
- continue
252
- if isinstance(val, (list, tuple)):
253
- # Match baseline behavior: concatenate tokens without separator
254
- val_str = "".join(map(str, val))
255
- else:
256
- val_str = str(val)
257
- if any(sw in val_str.lower() for sw in self.attr_stop_words):
258
- to_decompose.append(el)
259
- break
260
- for el in to_decompose:
261
- el.decompose()
262
-
263
- def _prune_header_footer(self, soup: BeautifulSoup) -> None:
264
- """Prune likely navigational clutter inside header and footer.
265
-
266
- Removes common list-like elements and links inside ``<header>``/``<footer>``
267
- when the corresponding toggles are enabled.
268
- """
269
- header = soup.find("header")
270
- footer = soup.find("footer")
271
- if header and self.remove_header_lists:
272
- self._decompose_tags(header, {"a", "img", "ol", "ul", "li"})
273
- if footer and self.remove_footer_lists:
274
- self._decompose_tags(footer, {"a", "img", "ol", "ul", "li"})
275
-
276
- def _prune_body(self, soup: BeautifulSoup) -> None:
277
- body = soup.find("body") or soup
278
- always_remove = {
279
- "input", "textarea", "button", "select", "option", "optgroup", "datalist",
280
- "label", "fieldset", "legend", "output", "meter", "dialog", "form",
281
- "search", "progress", "svg", "canvas", "use", "nav", "object", "noscript",
282
- }
283
- to_decompose: list[Tag] = []
284
- for el in body.descendants:
285
- if not isinstance(el, Tag):
286
- continue
287
- if not isinstance(el.name, str):
288
- continue
289
- if el.name in self.non_text_to_keep:
290
- continue
291
- if el.name in always_remove:
292
- to_decompose.append(el)
293
- for el in to_decompose:
294
- el.decompose()
295
-
296
- def _drop_empty_leaf_nodes(self, soup: BeautifulSoup) -> None:
297
- """Iteratively remove empty leaves using the baseline's strict leaf check.
298
-
299
- Walks leaf nodes (no descendants) and removes those with no text content,
300
- excluding tags explicitly whitelisted in ``non_text_to_keep``.
301
- """
302
- body = soup.find("body") or soup
303
- while True:
304
- to_decompose: list[Tag] = []
305
- for el in body.descendants:
306
- if not isinstance(el, Tag):
307
- continue
308
- if not isinstance(el.name, str):
309
- continue
310
- if el.name in self.non_text_to_keep:
311
- continue
312
- # Baseline leaf check: element must have zero descendants at all
313
- if len(list(el.descendants)) != 0:
314
- continue
315
- # Remove if no text once stripped
316
- if (el.get_text() or "").strip():
317
- continue
318
- to_decompose.append(el)
319
- if not to_decompose:
320
- break
321
- for el in to_decompose:
322
- el.decompose()
323
-
324
- @staticmethod
325
- def _decompose_tags(root: Tag, names: set[str]) -> None:
326
- for el in list(root.descendants):
327
- if isinstance(el, Tag) and isinstance(el.name, str) and el.name in names:
328
- el.decompose()
1
+ from __future__ import annotations
2
+
3
+ import minify_html
4
+ from bs4 import BeautifulSoup, Tag
5
+ from lxml import html as lxml_html
6
+ from lxml.html.clean import Cleaner
7
+
8
+
9
+
10
+
11
+ # -------------------------
12
+ # Public API
13
+ # -------------------------
14
+ class SmolHtmlCleaner:
15
+ """
16
+ Small, dependable HTML cleaner/minifier with sensible defaults.
17
+
18
+ Parameters
19
+ ----------
20
+ non_text_to_keep : set of str, optional
21
+ Tags preserved even if textless. Default includes meta/media/table/line-break tags.
22
+ attr_stop_words : set of str, optional
23
+ Attribute tokens indicating non-content scaffolding/UX. Default contains common UI tokens.
24
+ remove_header_lists : bool, optional
25
+ Prune links/lists inside ``<header>``. Default True.
26
+ remove_footer_lists : bool, optional
27
+ Prune links/lists inside ``<footer>``. Default True.
28
+ minify : bool, optional
29
+ Minify HTML output via ``minify_html``. Default True.
30
+ minify_kwargs : dict, optional
31
+ Extra args for ``minify_html.minify``. Default empty.
32
+
33
+ lxml Cleaner parameters
34
+ ----------------------
35
+ meta : bool, optional
36
+ Remove meta tags. Default False.
37
+ page_structure : bool, optional
38
+ Remove page structure tags (html, head, body). Default False.
39
+ links : bool, optional
40
+ Remove link tags. Default True.
41
+ scripts : bool, optional
42
+ Remove script tags. Default False.
43
+ javascript : bool, optional
44
+ Remove JavaScript content. Default True.
45
+ comments : bool, optional
46
+ Remove comments. Default True.
47
+ style : bool, optional
48
+ Remove style tags. Default True.
49
+ processing_instructions : bool, optional
50
+ Remove processing instructions. Default True.
51
+ embedded : bool, optional
52
+ Remove embedded content (object, embed, applet). Default True.
53
+ frames : bool, optional
54
+ Remove frame/iframe tags. Default True.
55
+ forms : bool, optional
56
+ Remove form tags. Default True.
57
+ annoying_tags : bool, optional
58
+ Remove tags considered annoying (blink, marquee, etc). Default True.
59
+ kill_tags : set of str, optional
60
+ Additional tags to remove. Default None.
61
+ remove_unknown_tags : bool, optional
62
+ Remove unknown tags. Default True.
63
+ safe_attrs_only : bool, optional
64
+ Only keep safe attributes. Default True.
65
+ safe_attrs : set of str, optional
66
+ Set of safe attributes to keep. Default is a sensible set.
67
+
68
+ Notes
69
+ -----
70
+ Defaults and cleaning behavior are preserved; only the configuration surface
71
+ moved from a dataclass to keyword-only parameters on the constructor.
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ *,
77
+ # Core behavior
78
+ non_text_to_keep: set[str] = None,
79
+ attr_stop_words: set[str] = None,
80
+ remove_header_lists: bool = True,
81
+ remove_footer_lists: bool = True,
82
+ # Minify
83
+ minify: bool = True,
84
+ minify_kwargs: dict | None = None,
85
+ # lxml Cleaner exposed explicitly (prefixed)
86
+ meta: bool = False,
87
+ page_structure: bool = False,
88
+ links: bool = True,
89
+ scripts: bool = False,
90
+ javascript: bool = True,
91
+ comments: bool = True,
92
+ style: bool = True,
93
+ processing_instructions: bool = True,
94
+ embedded: bool = True,
95
+ frames: bool = True,
96
+ forms: bool = True,
97
+ annoying_tags: bool = True,
98
+ kill_tags: set[str] | None = None,
99
+ remove_unknown_tags: bool = True,
100
+ safe_attrs_only: bool = True,
101
+ safe_attrs: set[str] = None,
102
+ ):
103
+ # Inline defaults identical to the prior CleanerConfig
104
+ if safe_attrs is None:
105
+ safe_attrs = {"href", "hreflang", "src", "srclang", "target", "alt", "kind", "type", "role", "abbr",
106
+ "accept", "accept-charset", "datetime", "lang", "name", "rel", "title", "value", "content", "label",
107
+ "item_type", "property", "itemprop"}
108
+
109
+ if attr_stop_words is None:
110
+ attr_stop_words = {"alert", "button", "checkbox", "dialog", "navigation", "tab", "tabpanel", "textbox",
111
+ "menu", "banner", "form", "search", "progressbar", "radio", "slider", "comment", "nav", "sidebar",
112
+ "breadcrumb", "dropdown", "menu-item", "toggle", "hamburger", "aside", "tooltip", "modal", "overlay",
113
+ "popup", "advert", "hero", "utility", "login", "signup", "password", "email", "username"}
114
+
115
+ if non_text_to_keep is None:
116
+ non_text_to_keep = {"meta", "img", "picture", "figure", "figcaption", "video", "source", "audio", "table",
117
+ "tr", "th", "td", "thead", "tbody", "tfoot", "caption", "br"}
118
+
119
+ self.non_text_to_keep = non_text_to_keep
120
+ self.attr_stop_words = attr_stop_words
121
+ self.remove_header_lists = remove_header_lists
122
+ self.remove_footer_lists = remove_footer_lists
123
+ self.minify = minify
124
+ self.minify_kwargs = dict(minify_kwargs or {})
125
+
126
+ # Initialize lxml Cleaner with explicit kwargs gathered from parameters
127
+ self._cleaner = Cleaner(
128
+ meta=meta,
129
+ page_structure=page_structure,
130
+ links=links,
131
+ scripts=scripts,
132
+ javascript=javascript,
133
+ comments=comments,
134
+ style=style,
135
+ processing_instructions=processing_instructions,
136
+ embedded=embedded,
137
+ frames=frames,
138
+ forms=forms,
139
+ annoying_tags=annoying_tags,
140
+ kill_tags=kill_tags,
141
+ remove_unknown_tags=remove_unknown_tags,
142
+ safe_attrs_only=safe_attrs_only,
143
+ safe_attrs=safe_attrs,
144
+ )
145
+
146
+ # -------------------------
147
+ # User-friendly entry points
148
+ # -------------------------
149
+
150
+
151
+ def make_smol(self, *, raw_html: str | BeautifulSoup) -> str:
152
+ """Clean and optionally minify HTML input.
153
+
154
+ The cleaning pipeline applies pre-parse hooks (on strings), prunes elements
155
+ by attribute stop words, sanitizes via lxml Cleaner, performs structural
156
+ pruning of header/footer/body, then applies post-clean hooks.
157
+
158
+ Parameters
159
+ ----------
160
+ raw_html : str or BeautifulSoup
161
+ Raw HTML string or BeautifulSoup to be cleaned.
162
+
163
+ Returns
164
+ -------
165
+ str
166
+ Cleaned HTML as a string.
167
+ """
168
+
169
+ # Stage 0: hooks that operate on the raw string
170
+ if isinstance(raw_html, str):
171
+ soup = BeautifulSoup(raw_html or "", features="lxml")
172
+ elif isinstance(raw_html, BeautifulSoup):
173
+ soup = raw_html
174
+ else:
175
+ raise TypeError("raw_html must be a str or BeautifulSoup instance")
176
+
177
+ # Stage 1: attribute-based pruning on the original soup
178
+ # Remove small, likely non-content elements based on attribute tokens.
179
+ self._strip_by_attribute_stop_words(soup=soup)
180
+
181
+ # Stage 2: lxml cleaner pass (robust HTML sanitation)
182
+ # Use lxml Cleaner to sanitize HTML, optionally minify afterwards.
183
+ cleaned_html = self._lxml_clean(str(soup))
184
+ clean_soup = BeautifulSoup(markup=cleaned_html, features="lxml")
185
+
186
+ # Stage 3: structural pruning on header/body/footer of the cleaned soup
187
+ self._prune_header_footer(clean_soup)
188
+ self._prune_body(clean_soup)
189
+ self._drop_empty_leaf_nodes(clean_soup)
190
+
191
+ return str(clean_soup)
192
+
193
+
194
+ def make_smol_bytes(self, *,
195
+ raw_html: str | BeautifulSoup,
196
+ compression_level: int = 5,
197
+ ) -> bytes:
198
+ """Return cleaned HTML as bytes, optionally Brotli-compressed.
199
+
200
+ If ``compression_level`` is 0, returns UTF-8 encoded bytes without compression.
201
+ For ``compression_level`` > 0, compresses the bytes using Brotli.
202
+
203
+ Parameters
204
+ ----------
205
+ raw_html : str or BeautifulSoup
206
+ Raw HTML to clean.
207
+ compression_level : int, optional
208
+ Brotli quality/level. 0 disables compression. Default 11.
209
+ **cleaner_kwargs : dict
210
+ Optional keyword args forwarded to ``SmolHtmlCleaner``.
211
+
212
+ Returns
213
+ -------
214
+ bytes
215
+ Cleaned (and possibly compressed) HTML as bytes.
216
+ """
217
+ html = self.make_smol(raw_html=raw_html)
218
+ data = html.encode("utf-8")
219
+
220
+ if compression_level <= 0:
221
+ return data
222
+
223
+ try:
224
+ import brotli as _brotli # type: ignore
225
+ except Exception as exc: # pragma: no cover - import-time dependency
226
+ raise RuntimeError(
227
+ "Brotli is required for compression. Install 'brotli' or 'brotlicffi', "
228
+ "or call with compression_level=0."
229
+ ) from exc
230
+
231
+ # Prefer TEXT mode if available for HTML content; fall back gracefully.
232
+ mode = getattr(_brotli, "MODE_TEXT", None)
233
+ if mode is None:
234
+ mode = getattr(_brotli, "BROTLI_MODE_TEXT", None)
235
+
236
+ if mode is not None:
237
+ return _brotli.compress(data, quality=int(compression_level), mode=mode)
238
+ return _brotli.compress(data, quality=int(compression_level))
239
+
240
+ # -------------------------
241
+ # Internal helpers
242
+ # -------------------------
243
+ def _lxml_clean(self, html_str: str) -> str:
244
+ """Sanitize and optionally minify HTML using lxml + minify_html.
245
+
246
+ Parameters
247
+ ----------
248
+ html_str : str
249
+ HTML markup to be cleaned.
250
+
251
+ Returns
252
+ -------
253
+ str
254
+ Cleaned (and possibly minified) HTML markup.
255
+ """
256
+ try:
257
+ cleaned = self._cleaner.clean_html(html_str)
258
+ return minify_html.minify(cleaned, **self.minify_kwargs) if self.minify else cleaned
259
+ except ValueError as ex:
260
+ # Handle encoding declaration edge-cases by round-tripping via lxml
261
+ msg = (
262
+ "Unicode strings with encoding declaration are not supported. "
263
+ "Please use bytes input or XML fragments without declaration."
264
+ )
265
+ if str(ex) == msg:
266
+ raw_bytes = html_str.encode("utf-8", errors="ignore")
267
+ doc = lxml_html.fromstring(raw_bytes)
268
+ cleaned = self._cleaner.clean_html(doc)
269
+ rendered = lxml_html.tostring(cleaned, encoding="utf-8").decode("utf-8")
270
+ return minify_html.minify(rendered, **self.minify_kwargs) if self.minify else rendered
271
+ raise
272
+
273
+ def _strip_by_attribute_stop_words(self, *, soup: BeautifulSoup) -> None:
274
+ """Remove small, likely non-content elements by attribute tokens.
275
+
276
+ Scans leaf-like descendants under ``<body>`` and collects elements whose
277
+ ``id``, ``class``, ``role``, or ``item_type`` values contain any of the
278
+ configured ``attr_stop_words`` tokens (case-insensitive), then decomposes
279
+ them. Mirrors the baseline leaf-ness and concatenation behavior.
280
+
281
+ Parameters
282
+ ----------
283
+ soup : BeautifulSoup
284
+ Parsed document to prune in place.
285
+ """
286
+ body = soup.find("body") or soup
287
+ to_decompose: list[Tag] = []
288
+ for el in body.descendants:
289
+ if not isinstance(el, Tag):
290
+ continue
291
+ attrs = el.attrs if isinstance(el.attrs, dict) else {}
292
+ if not attrs:
293
+ continue
294
+ # Only prune simple leaf-ish nodes to avoid huge deletes unintentionally
295
+ if sum(1 for _ in el.descendants) > 1:
296
+ continue
297
+ for name in ("id", "class", "role", "item_type"):
298
+ val = attrs.get(name)
299
+ if val is None:
300
+ continue
301
+ if isinstance(val, (list, tuple)):
302
+ # Match baseline behavior: concatenate tokens without separator
303
+ val_str = "".join(map(str, val))
304
+ else:
305
+ val_str = str(val)
306
+ if any(sw in val_str.lower() for sw in self.attr_stop_words):
307
+ to_decompose.append(el)
308
+ break
309
+ for el in to_decompose:
310
+ el.decompose()
311
+
312
+ def _prune_header_footer(self, soup: BeautifulSoup) -> None:
313
+ """Prune likely navigational clutter inside header and footer.
314
+
315
+ Removes common list-like elements and links inside ``<header>``/``<footer>``
316
+ when the corresponding toggles are enabled.
317
+ """
318
+ header = soup.find("header")
319
+ footer = soup.find("footer")
320
+ if header and self.remove_header_lists:
321
+ self._decompose_tags(header, {"a", "img", "ol", "ul", "li"})
322
+ if footer and self.remove_footer_lists:
323
+ self._decompose_tags(footer, {"a", "img", "ol", "ul", "li"})
324
+
325
+ def _prune_body(self, soup: BeautifulSoup) -> None:
326
+ body = soup.find("body") or soup
327
+ always_remove = {
328
+ "input", "textarea", "button", "select", "option", "optgroup", "datalist",
329
+ "label", "fieldset", "legend", "output", "meter", "dialog", "form",
330
+ "search", "progress", "svg", "canvas", "use", "nav", "object", "noscript",
331
+ }
332
+ to_decompose: list[Tag] = []
333
+ for el in body.descendants:
334
+ if not isinstance(el, Tag):
335
+ continue
336
+ if not isinstance(el.name, str):
337
+ continue
338
+ if el.name in self.non_text_to_keep:
339
+ continue
340
+ if el.name in always_remove:
341
+ to_decompose.append(el)
342
+ for el in to_decompose:
343
+ el.decompose()
344
+
345
+ def _drop_empty_leaf_nodes(self, soup: BeautifulSoup) -> None:
346
+ """Iteratively remove empty leaves using the baseline's strict leaf check.
347
+
348
+ Walks leaf nodes (no descendants) and removes those with no text content,
349
+ excluding tags explicitly whitelisted in ``non_text_to_keep``.
350
+ """
351
+ body = soup.find("body") or soup
352
+ while True:
353
+ to_decompose: list[Tag] = []
354
+ for el in body.descendants:
355
+ if not isinstance(el, Tag):
356
+ continue
357
+ if not isinstance(el.name, str):
358
+ continue
359
+ if el.name in self.non_text_to_keep:
360
+ continue
361
+ # Baseline leaf check: element must have zero descendants at all
362
+ if len(list(el.descendants)) != 0:
363
+ continue
364
+ # Remove if no text once stripped
365
+ if (el.get_text() or "").strip():
366
+ continue
367
+ to_decompose.append(el)
368
+ if not to_decompose:
369
+ break
370
+ for el in to_decompose:
371
+ el.decompose()
372
+
373
+ @staticmethod
374
+ def _decompose_tags(root: Tag, names: set[str]) -> None:
375
+ for el in list(root.descendants):
376
+ if isinstance(el, Tag) and isinstance(el.name, str) and el.name in names:
377
+ el.decompose()
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: smol-html
3
- Version: 0.1.1
3
+ Version: 0.1.2
4
4
  Summary: Small, dependable HTML cleaner/minifier with sensible defaults
5
5
  Project-URL: Homepage, https://github.com/NosibleAI/smol-html
6
6
  Project-URL: Repository, https://github.com/NosibleAI/smol-html
@@ -22,12 +22,14 @@ Classifier: Programming Language :: Python :: 3.13
22
22
  Classifier: Topic :: Internet :: WWW/HTTP :: Indexing/Search
23
23
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
24
  Requires-Python: >=3.9
25
- Requires-Dist: beautifulsoup4>=4.13.5
26
- Requires-Dist: lxml[html-clean]>=6.0.1
27
- Requires-Dist: minify-html>=0.16.4
25
+ Requires-Dist: beautifulsoup4>=4.0.1
26
+ Requires-Dist: brotli>=0.5.2
27
+ Requires-Dist: lxml[html-clean]>=1.3.2
28
+ Requires-Dist: minify-html>=0.2.6
28
29
  Description-Content-Type: text/markdown
29
30
 
30
- ![Logo](https://github.com/NosibleAI/nosible-py/blob/main/docs/_static/readme.png?raw=true)
31
+ ![smol](smol.png)
32
+
31
33
 
32
34
  # smol-html
33
35
 
@@ -63,7 +65,7 @@ html = """
63
65
 
64
66
  # All constructor arguments are keyword-only and optional.
65
67
  cleaner = SmolHtmlCleaner()
66
- cleaned = cleaner.clean(raw_html=html)
68
+ cleaned = cleaner.make_smol(raw_html=html)
67
69
 
68
70
  print(cleaned)
69
71
  ```
@@ -89,7 +91,7 @@ Minimal:
89
91
  from smol_html import SmolHtmlCleaner
90
92
 
91
93
  cleaner = SmolHtmlCleaner()
92
- out = cleaner.clean(raw_html="<p>Hi <!-- note --> <a href='x'>link</a></p>")
94
+ out = cleaner.make_smol(raw_html="<p>Hi <!-- note --> <a href='x'>link</a></p>")
93
95
  ```
94
96
 
95
97
  Customize a few options:
@@ -103,7 +105,38 @@ cleaner = SmolHtmlCleaner(
103
105
  minify=True,
104
106
  )
105
107
 
106
- out = cleaner.clean(raw_html="<p>Hi</p>")
108
+ out = cleaner.make_smol(raw_html="<p>Hi</p>")
109
+ ```
110
+
111
+ ## Compressed Bytes Output
112
+
113
+ Produce compressed bytes using Brotli with `make_smol_bytes`
114
+
115
+
116
+ ```python
117
+ from smol_html import SmolHtmlCleaner
118
+ import brotli # only needed if you want to decompress here in the example
119
+
120
+ html = """
121
+ <html>
122
+ <body>
123
+ <div> Hello <span> world </span> </div>
124
+ </body>
125
+ </html>
126
+ """
127
+
128
+ cleaner = SmolHtmlCleaner()
129
+
130
+ # Get compressed bytes (quality 11 is strong compression)
131
+ compressed = cleaner.make_smol_bytes(raw_html=html, compression_level=11)
132
+
133
+ # Example: decompress back to text to inspect (optional)
134
+ decompressed = brotli.decompress(compressed).decode("utf-8")
135
+ print(decompressed)
136
+
137
+ # Or write compressed output directly to a file
138
+ with open("page.html.br", "wb") as f:
139
+ f.write(compressed)
107
140
  ```
108
141
 
109
142
  ## Parameter Reference
@@ -0,0 +1,6 @@
1
+ smol_html/__init__.py,sha256=L_Clggminog8SY3a9TiN57ZajkYAQmXqdY8TOGEut2A,112
2
+ smol_html/smol_html.py,sha256=f9VGdIS3PTKfce3WpRQlhwMf7OEYOUWOlip8DI3dGV4,15194
3
+ smol_html-0.1.2.dist-info/METADATA,sha256=RHzSayuHJ0JalYqWxrI3lWcLfI3gi6BGwi8hEEY0m3A,7747
4
+ smol_html-0.1.2.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ smol_html-0.1.2.dist-info/licenses/LICENSE,sha256=88yg3BujRGq8MYlWhbrzB2YMNWJaXnBck3c7l23labs,1089
6
+ smol_html-0.1.2.dist-info/RECORD,,
@@ -1,6 +0,0 @@
1
- smol_html/__init__.py,sha256=05SUWU4WVeAQgrzTdcQbH91vvQGx6V-oHgIpUtMBbGE,111
2
- smol_html/smol_html.py,sha256=QCGyi0uh5bz3ex_z1sP5BYxjTHEeZOejUDA3eM9a2lE,13115
3
- smol_html-0.1.1.dist-info/METADATA,sha256=SJAUtNXwpq4Qo0fdekcgUvPOapUTjWAonHZ27cyUFkc,7055
4
- smol_html-0.1.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
- smol_html-0.1.1.dist-info/licenses/LICENSE,sha256=88yg3BujRGq8MYlWhbrzB2YMNWJaXnBck3c7l23labs,1089
6
- smol_html-0.1.1.dist-info/RECORD,,