postloom 0.1.0__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.
Files changed (125) hide show
  1. postloom/__init__.py +37 -0
  2. postloom/__main__.py +18 -0
  3. postloom/about.py +137 -0
  4. postloom/adapters/__init__.py +1 -0
  5. postloom/adapters/clock.py +10 -0
  6. postloom/adapters/export/__init__.py +15 -0
  7. postloom/adapters/export/cypher.py +151 -0
  8. postloom/adapters/export/graphml.py +119 -0
  9. postloom/adapters/export/property_graph.py +239 -0
  10. postloom/adapters/export/rdf.py +640 -0
  11. postloom/adapters/llm/__init__.py +1 -0
  12. postloom/adapters/llm/anthropic.py +195 -0
  13. postloom/adapters/llm/base.py +320 -0
  14. postloom/adapters/llm/chat.py +67 -0
  15. postloom/adapters/llm/content.py +183 -0
  16. postloom/adapters/llm/embeddings.py +93 -0
  17. postloom/adapters/llm/gateway.py +134 -0
  18. postloom/adapters/llm/gemini.py +261 -0
  19. postloom/adapters/llm/http.py +105 -0
  20. postloom/adapters/llm/local_embeddings.py +82 -0
  21. postloom/adapters/llm/ollama.py +214 -0
  22. postloom/adapters/llm/openai_compat.py +329 -0
  23. postloom/adapters/llm/prompts.py +283 -0
  24. postloom/adapters/llm/providers.py +261 -0
  25. postloom/adapters/llm/structured.py +127 -0
  26. postloom/adapters/storage/__init__.py +0 -0
  27. postloom/adapters/storage/cached.py +283 -0
  28. postloom/adapters/storage/codec.py +229 -0
  29. postloom/adapters/storage/database.py +176 -0
  30. postloom/adapters/storage/journaled.py +108 -0
  31. postloom/adapters/storage/memory.py +154 -0
  32. postloom/adapters/storage/reviews.py +81 -0
  33. postloom/adapters/storage/search.py +241 -0
  34. postloom/adapters/storage/sqlite.py +245 -0
  35. postloom/adapters/storage/stamps.py +42 -0
  36. postloom/adapters/storage/usage.py +101 -0
  37. postloom/adapters/vault/__init__.py +0 -0
  38. postloom/adapters/vault/journal.py +114 -0
  39. postloom/adapters/vault/markdown_vault.py +520 -0
  40. postloom/adapters/vault/media_files.py +79 -0
  41. postloom/adapters/vault/notes.py +118 -0
  42. postloom/adapters/vault/reader.py +514 -0
  43. postloom/application/__init__.py +5 -0
  44. postloom/application/defaults.py +14 -0
  45. postloom/application/errors.py +41 -0
  46. postloom/application/ports/__init__.py +52 -0
  47. postloom/application/ports/chat.py +30 -0
  48. postloom/application/ports/clock.py +10 -0
  49. postloom/application/ports/embeddings.py +35 -0
  50. postloom/application/ports/extraction.py +121 -0
  51. postloom/application/ports/graph_export.py +40 -0
  52. postloom/application/ports/journal.py +28 -0
  53. postloom/application/ports/media.py +42 -0
  54. postloom/application/ports/repository.py +134 -0
  55. postloom/application/ports/reviews.py +60 -0
  56. postloom/application/ports/search_index.py +62 -0
  57. postloom/application/ports/thread_parser.py +44 -0
  58. postloom/application/ports/usage.py +68 -0
  59. postloom/application/ports/vault.py +201 -0
  60. postloom/application/use_cases/__init__.py +134 -0
  61. postloom/application/use_cases/ask_question.py +526 -0
  62. postloom/application/use_cases/browse_content.py +164 -0
  63. postloom/application/use_cases/curation.py +372 -0
  64. postloom/application/use_cases/discussions.py +272 -0
  65. postloom/application/use_cases/export_graph.py +106 -0
  66. postloom/application/use_cases/graph_view.py +126 -0
  67. postloom/application/use_cases/index_content.py +199 -0
  68. postloom/application/use_cases/ingest_article.py +309 -0
  69. postloom/application/use_cases/links.py +313 -0
  70. postloom/application/use_cases/media.py +191 -0
  71. postloom/application/use_cases/mentions.py +573 -0
  72. postloom/application/use_cases/overview.py +104 -0
  73. postloom/application/use_cases/people.py +215 -0
  74. postloom/application/use_cases/posts.py +265 -0
  75. postloom/application/use_cases/relations.py +285 -0
  76. postloom/application/use_cases/reply_drafts.py +195 -0
  77. postloom/application/use_cases/search_content.py +185 -0
  78. postloom/application/use_cases/seed_topics.py +34 -0
  79. postloom/application/use_cases/usage.py +130 -0
  80. postloom/application/use_cases/vault_sync.py +384 -0
  81. postloom/bootstrap.py +460 -0
  82. postloom/config.py +56 -0
  83. postloom/domain/__init__.py +6 -0
  84. postloom/domain/chunking.py +105 -0
  85. postloom/domain/content.py +143 -0
  86. postloom/domain/discussion.py +261 -0
  87. postloom/domain/entities.py +102 -0
  88. postloom/domain/errors.py +25 -0
  89. postloom/domain/graph.py +115 -0
  90. postloom/domain/media.py +153 -0
  91. postloom/domain/people.py +119 -0
  92. postloom/domain/provenance.py +58 -0
  93. postloom/domain/text.py +428 -0
  94. postloom/interfaces/__init__.py +4 -0
  95. postloom/interfaces/cli/__init__.py +0 -0
  96. postloom/interfaces/cli/doctor.py +179 -0
  97. postloom/interfaces/cli/main.py +729 -0
  98. postloom/interfaces/desktop/__init__.py +1 -0
  99. postloom/interfaces/desktop/icons/postloom.icns +0 -0
  100. postloom/interfaces/desktop/icons/postloom.ico +0 -0
  101. postloom/interfaces/desktop/icons/postloom.png +0 -0
  102. postloom/interfaces/desktop/ollama.py +196 -0
  103. postloom/interfaces/desktop/shortcuts.py +385 -0
  104. postloom/interfaces/web/__init__.py +1 -0
  105. postloom/interfaces/web/app.py +1077 -0
  106. postloom/interfaces/web/schemas.py +689 -0
  107. postloom/interfaces/web/static/app.js +3116 -0
  108. postloom/interfaces/web/static/fonts/Geist-Medium.woff2 +0 -0
  109. postloom/interfaces/web/static/fonts/Geist-OFL.txt +93 -0
  110. postloom/interfaces/web/static/fonts/Geist-Regular.woff2 +0 -0
  111. postloom/interfaces/web/static/fonts/Geist-SemiBold.woff2 +0 -0
  112. postloom/interfaces/web/static/fonts/SourceSerif4-OFL.md +93 -0
  113. postloom/interfaces/web/static/fonts/SourceSerif4Variable-Italic.ttf.woff2 +0 -0
  114. postloom/interfaces/web/static/fonts/SourceSerif4Variable-Roman.ttf.woff2 +0 -0
  115. postloom/interfaces/web/static/icon.svg +12 -0
  116. postloom/interfaces/web/static/index.html +81 -0
  117. postloom/interfaces/web/static/style.css +1028 -0
  118. postloom/interfaces/web/static/theme.js +16 -0
  119. postloom/py.typed +0 -0
  120. postloom/settings.py +437 -0
  121. postloom-0.1.0.dist-info/METADATA +405 -0
  122. postloom-0.1.0.dist-info/RECORD +125 -0
  123. postloom-0.1.0.dist-info/WHEEL +4 -0
  124. postloom-0.1.0.dist-info/entry_points.txt +2 -0
  125. postloom-0.1.0.dist-info/licenses/LICENSE.md +105 -0
postloom/__init__.py ADDED
@@ -0,0 +1,37 @@
1
+ """postloom: a local-first knowledge graph of your LinkedIn writing and the people it reaches."""
2
+
3
+ import json
4
+ from importlib.metadata import PackageNotFoundError, distribution, version
5
+ from typing import cast
6
+
7
+ try:
8
+ __version__ = version("postloom")
9
+ except PackageNotFoundError: # running from a source checkout without installing
10
+ __version__ = "0.0.0+unknown"
11
+
12
+
13
+ def how_to_run(args: str) -> str:
14
+ """How to run a postloom command here, for messages: ``postloom start`` when it is
15
+ installed (``uvx``, ``uv tool``, ``pipx``), ``uv run postloom start`` in a source
16
+ checkout, where ``postloom`` alone isn't on the PATH."""
17
+ return f"uv run postloom {args}" if _from_source() else f"postloom {args}"
18
+
19
+
20
+ def _from_source() -> bool:
21
+ try:
22
+ raw = distribution("postloom").read_text("direct_url.json")
23
+ except PackageNotFoundError:
24
+ return True
25
+ if not raw:
26
+ return False
27
+ try:
28
+ info: object = json.loads(raw)
29
+ except ValueError:
30
+ return False
31
+ if not isinstance(info, dict):
32
+ return False
33
+ dir_info: object = cast(dict[str, object], info).get("dir_info")
34
+ return isinstance(dir_info, dict) and cast(dict[str, object], dir_info).get("editable") is True
35
+
36
+
37
+ __all__ = ["__version__", "how_to_run"]
postloom/__main__.py ADDED
@@ -0,0 +1,18 @@
1
+ """``python -m postloom``: what the desktop shortcuts run."""
2
+
3
+ try:
4
+ from postloom.interfaces.cli.main import main
5
+ except Exception: # broken install: no terminal may show this, so say it in a dialog
6
+ import traceback
7
+
8
+ from postloom.interfaces.desktop.shortcuts import record_failure, tell
9
+
10
+ log = record_failure(traceback.format_exc())
11
+ tell(
12
+ "postloom could not start",
13
+ f"Part of postloom didn't load. Running the install line again usually fixes this. "
14
+ f"Details: {log}",
15
+ )
16
+ raise SystemExit(1) from None
17
+
18
+ raise SystemExit(main())
postloom/about.py ADDED
@@ -0,0 +1,137 @@
1
+ """Who made postloom, under which license, and what it is built on.
2
+
3
+ Read from the installed package's metadata (pyproject.toml), so the app, the command line
4
+ and PyPI always say the same thing.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from dataclasses import dataclass
10
+ from importlib import metadata
11
+ from pathlib import Path
12
+
13
+ from postloom import __version__
14
+
15
+ REPOSITORY = "https://github.com/mdhabibi/postloom"
16
+ WEBSITE = "https://postloom-app.vercel.app/"
17
+ LICENSE_SUMMARY = (
18
+ "postloom is fair source. You can read, run, change and share the code for anything "
19
+ "except offering a competing commercial product or service; using it for your own "
20
+ "work, including your business, is allowed. Each release becomes Apache-2.0 two years "
21
+ "after it is published. The postloom name and logo aren't covered by the license."
22
+ )
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class Credit:
27
+ name: str
28
+ what: str
29
+ license: str
30
+ url: str
31
+
32
+
33
+ CREDITS: tuple[Credit, ...] = (
34
+ Credit(
35
+ "Geist",
36
+ "interface font, by Vercel",
37
+ "SIL Open Font License 1.1",
38
+ "https://github.com/vercel/geist-font",
39
+ ),
40
+ Credit(
41
+ "Source Serif 4",
42
+ "reading font, by Adobe",
43
+ "SIL Open Font License 1.1",
44
+ "https://github.com/adobe-fonts/source-serif",
45
+ ),
46
+ Credit(
47
+ "bge-small-en-v1.5",
48
+ "search by meaning in English, by BAAI",
49
+ "MIT",
50
+ "https://huggingface.co/BAAI/bge-small-en-v1.5",
51
+ ),
52
+ Credit(
53
+ "paraphrase-multilingual-MiniLM-L12-v2",
54
+ "search by meaning in 50+ languages",
55
+ "Apache-2.0",
56
+ "https://huggingface.co/sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
57
+ ),
58
+ Credit(
59
+ "FastEmbed",
60
+ "runs those models on your computer, by Qdrant",
61
+ "Apache-2.0",
62
+ "https://github.com/qdrant/fastembed",
63
+ ),
64
+ Credit(
65
+ "Starlette and Uvicorn", "the local web server", "BSD-3-Clause", "https://www.starlette.io"
66
+ ),
67
+ Credit("Pydantic", "checks what models and forms send", "MIT", "https://docs.pydantic.dev"),
68
+ Credit("PyYAML", "reads and writes note properties", "MIT", "https://pyyaml.org"),
69
+ Credit("SQLite", "the search index", "Public domain", "https://sqlite.org"),
70
+ )
71
+
72
+
73
+ @dataclass(frozen=True, slots=True)
74
+ class About:
75
+ name: str
76
+ version: str
77
+ description: str
78
+ author: str
79
+ license: str
80
+ license_summary: str
81
+ license_text: str
82
+ source: str
83
+ """The code on GitHub."""
84
+ website: str
85
+ issues: str
86
+ changelog: str
87
+ credits: tuple[Credit, ...]
88
+
89
+
90
+ def about() -> About:
91
+ try:
92
+ dist = metadata.distribution("postloom")
93
+ meta = dist.metadata
94
+ urls = dict(u.split(", ", 1) for u in meta.get_all("Project-URL") or [])
95
+ text = _license_text(dist)
96
+ return About(
97
+ name="postloom",
98
+ version=__version__,
99
+ description=meta["Summary"] or "",
100
+ author=meta["Author"] or "Dr. Mahdi Habibi",
101
+ license=meta["License-Expression"] or "FSL-1.1-ALv2",
102
+ license_summary=LICENSE_SUMMARY,
103
+ license_text=text,
104
+ source=urls.get("Source", REPOSITORY),
105
+ website=urls.get("Homepage", WEBSITE),
106
+ issues=urls.get("Issues", f"{REPOSITORY}/issues"),
107
+ changelog=urls.get("Changelog", f"{REPOSITORY}/blob/main/CHANGELOG.md"),
108
+ credits=CREDITS,
109
+ )
110
+ except metadata.PackageNotFoundError: # running from a source tree without installing
111
+ return About(
112
+ "postloom",
113
+ __version__,
114
+ "",
115
+ "Dr. Mahdi Habibi",
116
+ "FSL-1.1-ALv2",
117
+ LICENSE_SUMMARY,
118
+ _source_license(),
119
+ REPOSITORY,
120
+ WEBSITE,
121
+ f"{REPOSITORY}/issues",
122
+ f"{REPOSITORY}/blob/main/CHANGELOG.md",
123
+ CREDITS,
124
+ )
125
+
126
+
127
+ def _license_text(dist: metadata.Distribution) -> str:
128
+ for name in ("licenses/LICENSE.md", "LICENSE.md"):
129
+ text = dist.read_text(name)
130
+ if text:
131
+ return text
132
+ return _source_license()
133
+
134
+
135
+ def _source_license() -> str:
136
+ path = Path(__file__).resolve().parents[2] / "LICENSE.md"
137
+ return path.read_text(encoding="utf-8") if path.is_file() else ""
@@ -0,0 +1 @@
1
+ """Adapters: concrete implementations of the application ports (storage, LLMs, vault...)."""
@@ -0,0 +1,10 @@
1
+ from __future__ import annotations
2
+
3
+ from datetime import UTC, datetime
4
+
5
+
6
+ class SystemClock:
7
+ """The real clock, in UTC."""
8
+
9
+ def now(self) -> datetime:
10
+ return datetime.now(UTC)
@@ -0,0 +1,15 @@
1
+ """Formats the graph can be exported in."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from postloom.adapters.export.cypher import CypherFormat
6
+ from postloom.adapters.export.graphml import GraphMLFormat
7
+ from postloom.adapters.export.rdf import JsonLdFormat, TurtleFormat
8
+ from postloom.application.ports.graph_export import GraphFormat
9
+
10
+
11
+ def graph_formats() -> tuple[GraphFormat, ...]:
12
+ return (TurtleFormat(), JsonLdFormat(), CypherFormat(), GraphMLFormat())
13
+
14
+
15
+ __all__ = ["CypherFormat", "GraphMLFormat", "JsonLdFormat", "TurtleFormat", "graph_formats"]
@@ -0,0 +1,151 @@
1
+ """A Cypher script that loads the library into Neo4j (or Memgraph).
2
+
3
+ cypher-shell -u neo4j -p <password> -f postloom-graph.cypher
4
+
5
+ Every node gets the label ``Postloom`` plus its kind, and is MERGEd on ``id``; every
6
+ relationship is MERGEd on its ``key``. Running the same file again changes nothing, and
7
+ running a newer export updates what changed. Values are written as literals with every
8
+ string escaped, so nothing in your text can end a statement early.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import math
14
+ from collections import defaultdict
15
+ from collections.abc import Iterable, Sequence
16
+ from datetime import date, datetime
17
+ from typing import TypeVar, cast
18
+
19
+ from postloom.adapters.export.property_graph import PgNode, PgRelationship, property_graph
20
+ from postloom.application.ports.graph_export import ExportOptions
21
+ from postloom.application.ports.repository import GraphContents
22
+
23
+ _T = TypeVar("_T")
24
+
25
+ BATCH = 200
26
+ """Rows per UNWIND: large enough to load fast, small enough for any transaction size."""
27
+
28
+ HEADER = """\
29
+ // postloom graph export for Neo4j 5 (also loads in Memgraph).
30
+ //
31
+ // Load: cypher-shell -u neo4j -p <password> -f {filename}
32
+ // or Neo4j Browser with "Enable multi statement query editor" turned on.
33
+ // Every node has the label :Postloom and a unique `id` (the postloom id); relationships
34
+ // carry provenance: origin, grade (verified / asserted / rejected), producer, recorded_at.
35
+ // Loading twice changes nothing. To start over first:
36
+ // MATCH (n:Postloom) DETACH DELETE n;
37
+ //
38
+ // Try: MATCH (p:Person)-[:AUTHORED]->(:Comment)-[:COMMENTED_ON]->(:Post)-[:ANNOUNCES]->(a:Article)
39
+ // RETURN p.name, count(DISTINCT a) AS articles ORDER BY articles DESC LIMIT 10;
40
+ """
41
+
42
+
43
+ class CypherFormat:
44
+ name = "cypher"
45
+ title = "Cypher for Neo4j"
46
+ extension = "cypher"
47
+ media_type = "text/plain; charset=utf-8"
48
+
49
+ def write(self, graph: GraphContents, options: ExportOptions) -> bytes:
50
+ return cypher_script(graph, options).encode("utf-8")
51
+
52
+
53
+ def cypher_script(graph: GraphContents, options: ExportOptions) -> str:
54
+ pg = property_graph(graph, options)
55
+ parts = [
56
+ HEADER.format(filename="postloom-graph.cypher"),
57
+ "CREATE CONSTRAINT postloom_id IF NOT EXISTS FOR (n:Postloom) REQUIRE n.id IS UNIQUE;",
58
+ "",
59
+ ]
60
+ parts.extend(_node_statements(pg.nodes))
61
+ parts.extend(_relationship_statements(pg.relationships))
62
+ return "\n".join(parts) + "\n"
63
+
64
+
65
+ def _node_statements(nodes: Sequence[PgNode]) -> Iterable[str]:
66
+ by_labels: dict[tuple[str, ...], list[PgNode]] = defaultdict(list)
67
+ for node in nodes:
68
+ by_labels[node.labels].append(node)
69
+ for labels, group in by_labels.items():
70
+ label_set = "".join(f":{_name(label)}" for label in labels)
71
+ for chunk in batched(group, BATCH):
72
+ rows = ",\n ".join(literal(n.properties) for n in chunk)
73
+ yield (
74
+ f"UNWIND [\n {rows}\n] AS row\n"
75
+ f"MERGE (n:Postloom {{id: row.id}})\nSET n += row, n{label_set};\n"
76
+ )
77
+
78
+
79
+ def _relationship_statements(relationships: Sequence[PgRelationship]) -> Iterable[str]:
80
+ by_type: dict[str, list[PgRelationship]] = defaultdict(list)
81
+ for rel in relationships:
82
+ by_type[rel.type].append(rel)
83
+ for rel_type, group in by_type.items():
84
+ for chunk in batched(group, BATCH):
85
+ rows = ",\n ".join(
86
+ literal({"s": r.source, "t": r.target, "key": r.key, "p": r.properties})
87
+ for r in chunk
88
+ )
89
+ yield (
90
+ f"UNWIND [\n {rows}\n] AS row\n"
91
+ "MATCH (a:Postloom {id: row.s})\nMATCH (b:Postloom {id: row.t})\n"
92
+ f"MERGE (a)-[r:{_name(rel_type)} {{key: row.key}}]->(b)\nSET r += row.p;\n"
93
+ )
94
+
95
+
96
+ def batched(items: Sequence[_T], size: int) -> Iterable[Sequence[_T]]:
97
+ """``itertools.batched`` (Python 3.12+), for 3.11."""
98
+ for start in range(0, len(items), size):
99
+ yield items[start : start + size]
100
+
101
+
102
+ def literal(value: object) -> str:
103
+ """A Cypher literal for ``value``."""
104
+ if isinstance(value, bool):
105
+ return "true" if value else "false"
106
+ if isinstance(value, int):
107
+ return str(value)
108
+ if isinstance(value, float):
109
+ return repr(value) if math.isfinite(value) else "null"
110
+ if isinstance(value, datetime):
111
+ return f"datetime({string(value.isoformat())})"
112
+ if isinstance(value, date):
113
+ return f"date({string(value.isoformat())})"
114
+ if isinstance(value, str):
115
+ return string(value)
116
+ if isinstance(value, dict):
117
+ items = cast(dict[str, object], value).items()
118
+ return "{" + ", ".join(f"{_name(k)}: {literal(v)}" for k, v in items) + "}"
119
+ if isinstance(value, tuple | list):
120
+ return "[" + ", ".join(literal(v) for v in cast(Sequence[object], value)) + "]"
121
+ raise TypeError(f"no Cypher literal for {type(value).__name__}")
122
+
123
+
124
+ _ESCAPES = {
125
+ "\\": "\\\\",
126
+ "'": "\\'",
127
+ "\n": "\\n",
128
+ "\r": "\\r",
129
+ "\t": "\\t",
130
+ "\b": "\\b",
131
+ "\f": "\\f",
132
+ }
133
+
134
+
135
+ def string(text: str) -> str:
136
+ out: list[str] = []
137
+ for ch in text:
138
+ if ch in _ESCAPES:
139
+ out.append(_ESCAPES[ch])
140
+ elif ord(ch) < 0x20 or 0x7F <= ord(ch) < 0xA0 or ord(ch) in (0x2028, 0x2029):
141
+ out.append(f"\\u{ord(ch):04x}")
142
+ else:
143
+ out.append(ch)
144
+ return "'" + "".join(out) + "'"
145
+
146
+
147
+ def _name(name: str) -> str:
148
+ """A label, type or key: ours are plain words, but quote anything that isn't."""
149
+ if name.replace("_", "a").isalnum() and name.isascii() and not name[0].isdigit():
150
+ return name
151
+ return "`" + name.replace("`", "``") + "`"
@@ -0,0 +1,119 @@
1
+ """GraphML: opens in Gephi, yEd, Cytoscape, NetworkX, igraph, and Neo4j through
2
+ ``apoc.import.graphml(..., {readLabels: true})``.
3
+
4
+ Nodes carry ``labels`` in Neo4j's ``:Article`` form and ``label`` as their display name;
5
+ edges carry ``label`` as their type, which is what both Gephi and APOC read. Lists are
6
+ written as JSON, dates as ISO 8601 text.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import math
13
+ import xml.etree.ElementTree as ET
14
+ from datetime import date, datetime
15
+
16
+ from postloom.adapters.export.property_graph import Value, property_graph
17
+ from postloom.application.ports.graph_export import ExportOptions
18
+ from postloom.application.ports.repository import GraphContents
19
+
20
+ NS = "http://graphml.graphdrawing.org/xmlns"
21
+ SCHEMA = "http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"
22
+ XSI = "http://www.w3.org/2001/XMLSchema-instance"
23
+
24
+
25
+ class GraphMLFormat:
26
+ name = "graphml"
27
+ title = "GraphML for Gephi, yEd and NetworkX"
28
+ extension = "graphml"
29
+ media_type = "application/graphml+xml"
30
+
31
+ def write(self, graph: GraphContents, options: ExportOptions) -> bytes:
32
+ return graphml(graph, options)
33
+
34
+
35
+ def graphml(graph: GraphContents, options: ExportOptions) -> bytes:
36
+ pg = property_graph(graph, options)
37
+ node_rows = [{"labels": "".join(f":{x}" for x in n.labels), **n.properties} for n in pg.nodes]
38
+ edge_rows = [{"label": r.type, **r.properties} for r in pg.relationships]
39
+
40
+ ET.register_namespace("", NS)
41
+ ET.register_namespace("xsi", XSI)
42
+ root = ET.Element(f"{{{NS}}}graphml", {f"{{{XSI}}}schemaLocation": f"{NS} {SCHEMA}"})
43
+ keys: dict[tuple[str, str], str] = {}
44
+ for domain, rows in (("node", node_rows), ("edge", edge_rows)):
45
+ types: dict[str, str] = {}
46
+ for row in rows:
47
+ for name, value in row.items():
48
+ if name == "id" and domain == "node":
49
+ continue
50
+ types[name] = _widest(types.get(name), _type(value))
51
+ for name, kind in types.items():
52
+ key = f"{domain[0]}_{name}"
53
+ keys[(domain, name)] = key
54
+ attrs = {"id": key, "for": domain, "attr.name": name, "attr.type": kind}
55
+ ET.SubElement(root, f"{{{NS}}}key", attrs)
56
+
57
+ body = ET.SubElement(root, f"{{{NS}}}graph", {"id": "postloom", "edgedefault": "directed"})
58
+ for row in node_rows:
59
+ element = ET.SubElement(body, f"{{{NS}}}node", {"id": str(row["id"])})
60
+ _data(element, keys, "node", row)
61
+ for rel, row in zip(pg.relationships, edge_rows, strict=True):
62
+ attrs = {"id": rel.key, "source": rel.source, "target": rel.target}
63
+ element = ET.SubElement(body, f"{{{NS}}}edge", attrs)
64
+ _data(element, keys, "edge", row)
65
+
66
+ ET.indent(root, space=" ")
67
+ return ET.tostring(root, encoding="utf-8", xml_declaration=True) + b"\n"
68
+
69
+
70
+ def _data(
71
+ element: ET.Element, keys: dict[tuple[str, str], str], domain: str, row: dict[str, Value]
72
+ ) -> None:
73
+ for name, value in row.items():
74
+ if (domain, name) in keys:
75
+ ET.SubElement(element, f"{{{NS}}}data", {"key": keys[(domain, name)]}).text = _text(
76
+ value
77
+ )
78
+
79
+
80
+ def _type(value: Value) -> str:
81
+ if isinstance(value, bool):
82
+ return "boolean"
83
+ if isinstance(value, int):
84
+ return "long"
85
+ if isinstance(value, float):
86
+ return "double"
87
+ return "string"
88
+
89
+
90
+ def _widest(current: str | None, new: str) -> str:
91
+ if current is None or current == new:
92
+ return new
93
+ if {current, new} == {"long", "double"}:
94
+ return "double"
95
+ return "string"
96
+
97
+
98
+ def _text(value: Value) -> str:
99
+ if isinstance(value, bool):
100
+ return "true" if value else "false"
101
+ if isinstance(value, float):
102
+ return repr(value) if math.isfinite(value) else "NaN"
103
+ if isinstance(value, date | datetime):
104
+ return value.isoformat()
105
+ if isinstance(value, tuple):
106
+ return json.dumps(list(value), ensure_ascii=False)
107
+ return _xml_safe(str(value))
108
+
109
+
110
+ def _xml_safe(text: str) -> str:
111
+ """XML 1.0 can't hold most control characters, even escaped: drop them."""
112
+ return "".join(
113
+ ch
114
+ for ch in text
115
+ if ch in "\t\n\r"
116
+ or (0x20 <= ord(ch) <= 0xD7FF)
117
+ or (0xE000 <= ord(ch) <= 0xFFFD)
118
+ or ord(ch) >= 0x10000
119
+ )