urban-json-html 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 black beard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: urban-json-html
3
+ Version: 0.1.0
4
+ Summary: Plugin urban-json : conversion HTML vers JSON (loadhtml).
5
+ Author-email: Gael Beard <gaelgael5@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gaelgael5/Jslt
8
+ Project-URL: Repository, https://github.com/gaelgael5/Jslt
9
+ Keywords: json,transform,template,jslt,html,plugin
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Text Processing :: Markup
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: urban-json
26
+ Dynamic: license-file
27
+
28
+ # urban-json-html
29
+
30
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : **HTML vers JSON** dans les
31
+ templates, via `loadhtml(chemin_ou_url)` (port de `ServiceHtml`, .NET). Aucune
32
+ dépendance : `html.parser` de la bibliothèque standard.
33
+
34
+ ```bash
35
+ pip install urban-json-html
36
+ ```
37
+
38
+ Forme produite (celle du .NET, HtmlAgilityPack) :
39
+
40
+ ```json
41
+ { "#id": "#document", "content": { "#id": "p", "class": "x", "content": "#text: Bonjour" } }
42
+ ```
43
+
44
+ - élément → `{"#id": balise, attributs…, "content": enfant | [enfants]}` ;
45
+ - texte → `"#text: …"` (blancs seuls ignorés, entités conservées) ;
46
+ - commentaire et `<!DOCTYPE>` → `"#comment: …"`.
47
+
48
+ `loadhtml` accepte un fichier (chemin ou URI `file://`) ou une URL `http(s)://`
49
+ (délai de 30 s). Attention aux URL issues de données non fiables (SSRF).
@@ -0,0 +1,22 @@
1
+ # urban-json-html
2
+
3
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : **HTML vers JSON** dans les
4
+ templates, via `loadhtml(chemin_ou_url)` (port de `ServiceHtml`, .NET). Aucune
5
+ dépendance : `html.parser` de la bibliothèque standard.
6
+
7
+ ```bash
8
+ pip install urban-json-html
9
+ ```
10
+
11
+ Forme produite (celle du .NET, HtmlAgilityPack) :
12
+
13
+ ```json
14
+ { "#id": "#document", "content": { "#id": "p", "class": "x", "content": "#text: Bonjour" } }
15
+ ```
16
+
17
+ - élément → `{"#id": balise, attributs…, "content": enfant | [enfants]}` ;
18
+ - texte → `"#text: …"` (blancs seuls ignorés, entités conservées) ;
19
+ - commentaire et `<!DOCTYPE>` → `"#comment: …"`.
20
+
21
+ `loadhtml` accepte un fichier (chemin ou URI `file://`) ou une URL `http(s)://`
22
+ (délai de 30 s). Attention aux URL issues de données non fiables (SSRF).
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "urban-json-html"
7
+ dynamic = ["version"]
8
+ description = "Plugin urban-json : conversion HTML vers JSON (loadhtml)."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Gael Beard", email = "gaelgael5@gmail.com" }]
14
+ keywords = ["json", "transform", "template", "jslt", "html", "plugin"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.9",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Software Development :: Libraries :: Python Modules",
26
+ "Topic :: Text Processing :: Markup",
27
+ "Typing :: Typed",
28
+ ]
29
+ dependencies = [
30
+ "urban-json",
31
+ ]
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/gaelgael5/Jslt"
35
+ Repository = "https://github.com/gaelgael5/Jslt"
36
+
37
+ # Découverte automatique par urban-json : installer ce paquet suffit à exposer ses fonctions.
38
+ [project.entry-points."urban_json.functions"]
39
+ html = "urban_json_html:register"
40
+
41
+ [tool.setuptools.dynamic]
42
+ version = { attr = "urban_json_html.__version__" }
43
+
44
+ [tool.setuptools.packages.find]
45
+ where = ["src"]
46
+
47
+ [tool.setuptools.package-data]
48
+ urban_json_html = ["py.typed"]
49
+
50
+ [tool.pytest.ini_options]
51
+ testpaths = ["tests"]
52
+ pythonpath = ["src"]
53
+
54
+ [tool.ruff]
55
+ line-length = 100
56
+ src = ["src", "tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,166 @@
1
+ """Plugin urban-json : conversion HTML vers JSON (``loadhtml``).
2
+
3
+ Port de ``ServiceHtml`` / ``HtmlToJson`` (.NET, HtmlAgilityPack) avec le
4
+ ``html.parser`` de la bibliothèque standard, sans dépendance. Forme produite,
5
+ identique au .NET :
6
+
7
+ * élément -> ``{"#id": balise, <attributs>…, "content": enfant | [enfants]}``
8
+ (``content`` absent sans enfant, valeur seule pour un enfant unique) ;
9
+ * texte -> ``"#text: <texte brut>"``, ignoré s'il n'est fait que de blancs ;
10
+ * commentaire et ``<!DOCTYPE>`` -> ``"#comment: <!-- … -->"`` (HtmlAgilityPack
11
+ range la déclaration DOCTYPE parmi les commentaires) ;
12
+ * racine -> ``{"#id": "#document", …}``.
13
+
14
+ Comme HtmlAgilityPack, le texte garde ses entités telles quelles (``&amp;``) et
15
+ la casse d'origine des balises est conservée. Écarts : les noms d'attributs sont
16
+ mis en minuscules et leurs valeurs décodées (``html.parser`` le fait toujours) ;
17
+ un chemin relatif est accepté (le .NET exigeait un chemin absolu ou une URI).
18
+
19
+ Découvert automatiquement via l'entry point ``urban_json.functions``.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ import re
26
+ from html.parser import HTMLParser
27
+ from typing import Any
28
+ from urllib.parse import unquote, urlparse
29
+
30
+ from urban_json import JsltError
31
+
32
+ __version__ = "0.1.0"
33
+
34
+ __all__ = ["execute_loadhtml", "html_to_json", "register"]
35
+
36
+ #: Délai maximal (secondes) pour charger une page distante.
37
+ DEFAULT_TIMEOUT = 30.0
38
+
39
+ # Éléments HTML sans contenu ni balise fermante.
40
+ _VOID = {
41
+ "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta",
42
+ "param", "source", "track", "wbr",
43
+ }
44
+ _TAG_NAME = re.compile(r"<\s*([^\s/>]+)")
45
+
46
+
47
+ class _Node:
48
+ __slots__ = ("attrs", "children", "name")
49
+
50
+ def __init__(self, name: str, attrs: list[tuple[str, str | None]]) -> None:
51
+ self.name = name
52
+ self.attrs = attrs
53
+ self.children: list[Any] = []
54
+
55
+
56
+ class _TreeBuilder(HTMLParser):
57
+ def __init__(self) -> None:
58
+ super().__init__(convert_charrefs=False)
59
+ self.root = _Node("#document", [])
60
+ self.stack = [self.root]
61
+
62
+ def _append(self, item: Any) -> None:
63
+ self.stack[-1].children.append(item)
64
+
65
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
66
+ raw = self.get_starttag_text() or ""
67
+ match = _TAG_NAME.match(raw)
68
+ node = _Node(match.group(1) if match else tag, attrs)
69
+ self._append(node)
70
+ if tag not in _VOID:
71
+ self.stack.append(node)
72
+
73
+ def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
74
+ raw = self.get_starttag_text() or ""
75
+ match = _TAG_NAME.match(raw)
76
+ self._append(_Node(match.group(1) if match else tag, attrs))
77
+
78
+ def handle_endtag(self, tag: str) -> None:
79
+ # Ferme jusqu'à la balise ouverte correspondante ; une fermante orpheline est ignorée.
80
+ for depth in range(len(self.stack) - 1, 0, -1):
81
+ if self.stack[depth].name.lower() == tag:
82
+ del self.stack[depth:]
83
+ return
84
+
85
+ def handle_data(self, data: str) -> None:
86
+ self._append(("#text", data))
87
+
88
+ def handle_entityref(self, name: str) -> None:
89
+ self._append(("#text", f"&{name};"))
90
+
91
+ def handle_charref(self, name: str) -> None:
92
+ self._append(("#text", f"&#{name};"))
93
+
94
+ def handle_comment(self, data: str) -> None:
95
+ self._append(("#comment", f"<!--{data}-->"))
96
+
97
+ def handle_decl(self, decl: str) -> None:
98
+ self._append(("#comment", f"<!{decl}>"))
99
+
100
+
101
+ def _merge_text(children: list[Any]) -> list[Any]:
102
+ """Recolle les morceaux de texte consécutifs (le parseur coupe sur les entités)."""
103
+ merged: list[Any] = []
104
+ for child in children:
105
+ if isinstance(child, tuple) and child[0] == "#text" and merged and isinstance(merged[-1], tuple) \
106
+ and merged[-1][0] == "#text":
107
+ merged[-1] = ("#text", merged[-1][1] + child[1])
108
+ else:
109
+ merged.append(child)
110
+ return merged
111
+
112
+
113
+ def _to_json(item: Any) -> Any:
114
+ if isinstance(item, tuple):
115
+ kind, text = item
116
+ return f"{kind}: {text}" if text.strip() else None
117
+ result: dict[str, Any] = {"#id": item.name}
118
+ for name, value in item.attrs:
119
+ result.setdefault(name, value if value is not None else "")
120
+ children = [c for c in (_to_json(child) for child in _merge_text(item.children)) if c is not None]
121
+ if len(children) == 1:
122
+ result["content"] = children[0]
123
+ elif children:
124
+ result["content"] = children
125
+ return result
126
+
127
+
128
+ def html_to_json(payload: str) -> dict:
129
+ """Convertit un texte HTML en JSON (forme ``HtmlToJson`` du .NET)."""
130
+ builder = _TreeBuilder()
131
+ builder.feed(payload)
132
+ builder.close()
133
+ return _to_json(builder.root)
134
+
135
+
136
+ def _fetch_url(url: str) -> str:
137
+ """Charge une page distante. Point d'injection pour les tests."""
138
+ from urllib.request import Request, urlopen
139
+
140
+ request = Request(url, headers={"User-Agent": "urban-json-html"})
141
+ with urlopen(request, timeout=DEFAULT_TIMEOUT) as response:
142
+ charset = response.headers.get_content_charset() or "utf-8"
143
+ return response.read().decode(charset, errors="replace")
144
+
145
+
146
+ def execute_loadhtml(ctx: Any, path: Any = None) -> dict:
147
+ if not path:
148
+ raise JsltError("loadhtml : le chemin ou l'URL de la page est requis")
149
+ location = str(path)
150
+ parsed = urlparse(location)
151
+ if parsed.scheme in ("http", "https"):
152
+ return html_to_json(_fetch_url(location))
153
+ file_path = unquote(parsed.path) if parsed.scheme == "file" else location
154
+ if not os.path.isfile(file_path):
155
+ raise JsltError(f"loadhtml : page HTML introuvable {file_path!r}")
156
+ with open(file_path, encoding="utf-8-sig", errors="replace") as handle:
157
+ return html_to_json(handle.read())
158
+
159
+
160
+ def register(registry: Any) -> None:
161
+ """Enregistre ``loadhtml``."""
162
+ registry.register(
163
+ "loadhtml",
164
+ execute_loadhtml,
165
+ description="Charge une page HTML (fichier ou URL http/https) et la convertit en JSON {#id, attributs, content}",
166
+ )
File without changes
@@ -0,0 +1,49 @@
1
+ Metadata-Version: 2.4
2
+ Name: urban-json-html
3
+ Version: 0.1.0
4
+ Summary: Plugin urban-json : conversion HTML vers JSON (loadhtml).
5
+ Author-email: Gael Beard <gaelgael5@gmail.com>
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/gaelgael5/Jslt
8
+ Project-URL: Repository, https://github.com/gaelgael5/Jslt
9
+ Keywords: json,transform,template,jslt,html,plugin
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.9
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Classifier: Topic :: Text Processing :: Markup
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.9
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: urban-json
26
+ Dynamic: license-file
27
+
28
+ # urban-json-html
29
+
30
+ Plugin [urban-json](https://github.com/gaelgael5/Jslt) : **HTML vers JSON** dans les
31
+ templates, via `loadhtml(chemin_ou_url)` (port de `ServiceHtml`, .NET). Aucune
32
+ dépendance : `html.parser` de la bibliothèque standard.
33
+
34
+ ```bash
35
+ pip install urban-json-html
36
+ ```
37
+
38
+ Forme produite (celle du .NET, HtmlAgilityPack) :
39
+
40
+ ```json
41
+ { "#id": "#document", "content": { "#id": "p", "class": "x", "content": "#text: Bonjour" } }
42
+ ```
43
+
44
+ - élément → `{"#id": balise, attributs…, "content": enfant | [enfants]}` ;
45
+ - texte → `"#text: …"` (blancs seuls ignorés, entités conservées) ;
46
+ - commentaire et `<!DOCTYPE>` → `"#comment: …"`.
47
+
48
+ `loadhtml` accepte un fichier (chemin ou URI `file://`) ou une URL `http(s)://`
49
+ (délai de 30 s). Attention aux URL issues de données non fiables (SSRF).
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/urban_json_html/__init__.py
5
+ src/urban_json_html/py.typed
6
+ src/urban_json_html.egg-info/PKG-INFO
7
+ src/urban_json_html.egg-info/SOURCES.txt
8
+ src/urban_json_html.egg-info/dependency_links.txt
9
+ src/urban_json_html.egg-info/entry_points.txt
10
+ src/urban_json_html.egg-info/requires.txt
11
+ src/urban_json_html.egg-info/top_level.txt
12
+ tests/test_html.py
@@ -0,0 +1,2 @@
1
+ [urban_json.functions]
2
+ html = urban_json_html:register
@@ -0,0 +1 @@
1
+ urban_json_html
@@ -0,0 +1,95 @@
1
+ """loadhtml — port de ServiceHtml (HtmlAgilityPack -> JSON)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+ from urban_json import FunctionRegistry, JsltError, JsltTemplate
9
+
10
+ from urban_json_html import html_to_json, register
11
+
12
+
13
+ @pytest.fixture(scope="module")
14
+ def registry() -> FunctionRegistry:
15
+ reg = FunctionRegistry()
16
+ register(reg)
17
+ return reg
18
+
19
+
20
+ def test_structure_element_attributs_contenu() -> None:
21
+ out = html_to_json('<div id="a" class="x"><p>Bonjour</p><p>le <b>monde</b></p></div>')
22
+ assert out == {
23
+ "#id": "#document",
24
+ "content": {
25
+ "#id": "div", "id": "a", "class": "x",
26
+ "content": [
27
+ {"#id": "p", "content": "#text: Bonjour"},
28
+ {"#id": "p", "content": ["#text: le ", {"#id": "b", "content": "#text: monde"}]},
29
+ ],
30
+ },
31
+ }
32
+
33
+
34
+ def test_texte_blanc_ignore_commentaire_et_doctype() -> None:
35
+ out = html_to_json("<!DOCTYPE html>\n<p> <!-- note --> </p>")
36
+ assert out["content"] == [
37
+ "#comment: <!DOCTYPE html>",
38
+ {"#id": "p", "content": "#comment: <!-- note -->"},
39
+ ]
40
+
41
+
42
+ def test_elements_vides_et_casse_des_balises() -> None:
43
+ out = html_to_json('<DIV>a<br>b<IMG src="x.png"></DIV>')
44
+ assert out["content"] == {
45
+ "#id": "DIV",
46
+ "content": ["#text: a", {"#id": "br"}, "#text: b", {"#id": "IMG", "src": "x.png"}],
47
+ }
48
+
49
+
50
+ def test_balise_non_fermee_et_attribut_sans_valeur() -> None:
51
+ out = html_to_json("<ul><li>1<li>2</ul><input disabled>")
52
+ assert out["content"][0]["#id"] == "ul"
53
+ assert out["content"][1] == {"#id": "input", "disabled": ""}
54
+
55
+
56
+ def test_entites_conservees_comme_html_agility_pack() -> None:
57
+ assert html_to_json("<p>a &amp; b</p>")["content"]["content"] == "#text: a &amp; b"
58
+
59
+
60
+ def test_loadhtml_fichier(registry, tmp_path: Path) -> None:
61
+ page = tmp_path / "p.html"
62
+ page.write_text("<h1>Titre</h1>", encoding="utf-8")
63
+ template = JsltTemplate.parse('{ "r": loadhtml($.p) }')
64
+ out = template.transform({"p": str(page)}, functions=registry)["r"]
65
+ assert out["content"] == {"#id": "h1", "content": "#text: Titre"}
66
+
67
+
68
+ def test_loadhtml_uri_fichier(registry, tmp_path: Path) -> None:
69
+ page = tmp_path / "p.html"
70
+ page.write_text("<i>x</i>", encoding="utf-8")
71
+ template = JsltTemplate.parse('{ "r": loadhtml($.p) }')
72
+ assert template.transform({"p": page.as_uri()}, functions=registry)["r"]["content"]["#id"] == "i"
73
+
74
+
75
+ def test_loadhtml_url(registry, monkeypatch) -> None:
76
+ import urban_json_html
77
+
78
+ monkeypatch.setattr(urban_json_html, "_fetch_url", lambda url: "<em>web</em>")
79
+ template = JsltTemplate.parse('{ "r": loadhtml("https://exemple.test/page") }')
80
+ assert template.transform({}, functions=registry)["r"]["content"] == {"#id": "em", "content": "#text: web"}
81
+
82
+
83
+ @pytest.mark.parametrize("value", [None, "/chemin/absent.html"])
84
+ def test_loadhtml_erreurs(registry, value) -> None:
85
+ template = JsltTemplate.parse('{ "r": loadhtml($.p) }')
86
+ with pytest.raises(JsltError, match="loadhtml"):
87
+ template.transform({"p": value}, functions=registry)
88
+
89
+
90
+ def test_catalogue_et_decouverte(registry) -> None:
91
+ from urban_json import default_registry, load_plugins
92
+
93
+ assert len(registry.catalog()[0]["description"]) >= 15
94
+ load_plugins()
95
+ assert "loadhtml" in default_registry