jostack-mdparse 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.
- jostack_mdparse/__init__.py +7 -0
- jostack_mdparse/cli.py +137 -0
- jostack_mdparse/extract.py +337 -0
- jostack_mdparse-0.1.0.dist-info/METADATA +124 -0
- jostack_mdparse-0.1.0.dist-info/RECORD +8 -0
- jostack_mdparse-0.1.0.dist-info/WHEEL +4 -0
- jostack_mdparse-0.1.0.dist-info/entry_points.txt +2 -0
- jostack_mdparse-0.1.0.dist-info/licenses/LICENSE +190 -0
jostack_mdparse/cli.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""CLI entry point for jostack-mdparse."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from jostack_mdparse import __version__, extract
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def main(argv: list[str] | None = None) -> None:
|
|
12
|
+
"""Main CLI entry point."""
|
|
13
|
+
parser = argparse.ArgumentParser(
|
|
14
|
+
prog="jostack-mdparse",
|
|
15
|
+
description="Markdown file parser and structured extraction tool",
|
|
16
|
+
)
|
|
17
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
18
|
+
|
|
19
|
+
subparsers = parser.add_subparsers(dest="command", help="Available commands")
|
|
20
|
+
|
|
21
|
+
# extract command
|
|
22
|
+
extract_parser = subparsers.add_parser(
|
|
23
|
+
"extract", help="Parse Markdown and output structured data"
|
|
24
|
+
)
|
|
25
|
+
_add_common_args(extract_parser)
|
|
26
|
+
_add_extract_options(extract_parser)
|
|
27
|
+
|
|
28
|
+
# toc command
|
|
29
|
+
toc_parser = subparsers.add_parser("toc", help="Print the table of contents (heading tree)")
|
|
30
|
+
_add_common_args(toc_parser)
|
|
31
|
+
toc_parser.add_argument(
|
|
32
|
+
"--heading-level",
|
|
33
|
+
default=None,
|
|
34
|
+
help="Filter by heading levels (comma-separated)",
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
# meta command
|
|
38
|
+
meta_parser = subparsers.add_parser("meta", help="Print frontmatter metadata as JSON")
|
|
39
|
+
_add_common_args(meta_parser)
|
|
40
|
+
|
|
41
|
+
args = parser.parse_args(argv)
|
|
42
|
+
|
|
43
|
+
if args.command is None:
|
|
44
|
+
parser.print_help()
|
|
45
|
+
sys.exit(1)
|
|
46
|
+
|
|
47
|
+
if args.command == "extract":
|
|
48
|
+
result = extract(
|
|
49
|
+
args.input,
|
|
50
|
+
output_dir=args.output_dir,
|
|
51
|
+
format=args.format,
|
|
52
|
+
quiet=args.quiet,
|
|
53
|
+
heading_level=args.heading_level,
|
|
54
|
+
sections=args.sections,
|
|
55
|
+
include_frontmatter=args.include_frontmatter,
|
|
56
|
+
strip_html=args.strip_html,
|
|
57
|
+
include_code_blocks=args.include_code_blocks,
|
|
58
|
+
include_toc=args.include_toc,
|
|
59
|
+
flatten_lists=args.flatten_lists,
|
|
60
|
+
section_separator=args.section_separator,
|
|
61
|
+
normalize_links=args.normalize_links,
|
|
62
|
+
)
|
|
63
|
+
print(result)
|
|
64
|
+
|
|
65
|
+
elif args.command == "toc":
|
|
66
|
+
result = extract(
|
|
67
|
+
args.input,
|
|
68
|
+
format=args.format,
|
|
69
|
+
quiet=args.quiet,
|
|
70
|
+
include_toc=True,
|
|
71
|
+
heading_level=args.heading_level,
|
|
72
|
+
)
|
|
73
|
+
print(result)
|
|
74
|
+
|
|
75
|
+
elif args.command == "meta":
|
|
76
|
+
result = extract(
|
|
77
|
+
args.input,
|
|
78
|
+
format="json",
|
|
79
|
+
quiet=args.quiet,
|
|
80
|
+
include_frontmatter=True,
|
|
81
|
+
)
|
|
82
|
+
print(result)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _add_common_args(parser: argparse.ArgumentParser) -> None:
|
|
86
|
+
"""Add common arguments shared across all commands."""
|
|
87
|
+
parser.add_argument("input", help="Path to Markdown file or directory")
|
|
88
|
+
parser.add_argument(
|
|
89
|
+
"-f",
|
|
90
|
+
"--format",
|
|
91
|
+
default="json",
|
|
92
|
+
choices=["json", "text", "html"],
|
|
93
|
+
help="Output format (default: json)",
|
|
94
|
+
)
|
|
95
|
+
parser.add_argument(
|
|
96
|
+
"-q",
|
|
97
|
+
"--quiet",
|
|
98
|
+
action="store_true",
|
|
99
|
+
default=False,
|
|
100
|
+
help="Suppress console logging output",
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _add_extract_options(parser: argparse.ArgumentParser) -> None:
|
|
105
|
+
"""Add extract-specific options from options.json."""
|
|
106
|
+
parser.add_argument("-o", "--output-dir", default=None, help="Output directory")
|
|
107
|
+
parser.add_argument(
|
|
108
|
+
"--heading-level", default=None, help="Filter by heading levels (comma-separated)"
|
|
109
|
+
)
|
|
110
|
+
parser.add_argument(
|
|
111
|
+
"-s", "--sections", default=None, help="Extract sections by heading text (comma-separated)"
|
|
112
|
+
)
|
|
113
|
+
parser.add_argument(
|
|
114
|
+
"--include-frontmatter", action="store_true", default=True, help="Include frontmatter"
|
|
115
|
+
)
|
|
116
|
+
parser.add_argument(
|
|
117
|
+
"--no-include-frontmatter", action="store_false", dest="include_frontmatter"
|
|
118
|
+
)
|
|
119
|
+
parser.add_argument("--strip-html", action="store_true", default=False, help="Strip HTML tags")
|
|
120
|
+
parser.add_argument(
|
|
121
|
+
"--include-code-blocks", action="store_true", default=True, help="Include code blocks"
|
|
122
|
+
)
|
|
123
|
+
parser.add_argument(
|
|
124
|
+
"--no-include-code-blocks", action="store_false", dest="include_code_blocks"
|
|
125
|
+
)
|
|
126
|
+
parser.add_argument(
|
|
127
|
+
"--include-toc", action="store_true", default=False, help="Add table of contents"
|
|
128
|
+
)
|
|
129
|
+
parser.add_argument(
|
|
130
|
+
"--flatten-lists", action="store_true", default=False, help="Flatten nested lists"
|
|
131
|
+
)
|
|
132
|
+
parser.add_argument(
|
|
133
|
+
"--section-separator", default=None, help="Section separator (use %%section-title%%)"
|
|
134
|
+
)
|
|
135
|
+
parser.add_argument(
|
|
136
|
+
"--normalize-links", action="store_true", default=False, help="Normalize relative links"
|
|
137
|
+
)
|
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
"""Core extraction logic for jostack-mdparse."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import re
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Optional, Union
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def extract(
|
|
15
|
+
input_path: Union[str, Path],
|
|
16
|
+
*,
|
|
17
|
+
output_dir: Optional[str] = None,
|
|
18
|
+
format: str = "json",
|
|
19
|
+
quiet: bool = False,
|
|
20
|
+
heading_level: Optional[str] = None,
|
|
21
|
+
sections: Optional[str] = None,
|
|
22
|
+
include_frontmatter: bool = True,
|
|
23
|
+
strip_html: bool = False,
|
|
24
|
+
include_code_blocks: bool = True,
|
|
25
|
+
include_toc: bool = False,
|
|
26
|
+
flatten_lists: bool = False,
|
|
27
|
+
section_separator: Optional[str] = None,
|
|
28
|
+
normalize_links: bool = False,
|
|
29
|
+
) -> str:
|
|
30
|
+
"""Extract structured data from a Markdown file.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
input_path: Path to the Markdown file or directory.
|
|
34
|
+
output_dir: Directory where output files are written.
|
|
35
|
+
format: Output format (json, text, html).
|
|
36
|
+
quiet: Suppress console logging output.
|
|
37
|
+
heading_level: Filter by heading levels (comma-separated).
|
|
38
|
+
sections: Extract only sections matching heading text (comma-separated).
|
|
39
|
+
include_frontmatter: Include YAML/TOML frontmatter in output.
|
|
40
|
+
strip_html: Strip inline HTML tags from Markdown content.
|
|
41
|
+
include_code_blocks: Include fenced code blocks in output.
|
|
42
|
+
include_toc: Add a generated table of contents to the output.
|
|
43
|
+
flatten_lists: Flatten nested lists into a single level.
|
|
44
|
+
section_separator: Separator between sections in text output.
|
|
45
|
+
normalize_links: Convert relative links to absolute.
|
|
46
|
+
|
|
47
|
+
Returns:
|
|
48
|
+
Extracted content as a string in the specified format.
|
|
49
|
+
"""
|
|
50
|
+
if quiet:
|
|
51
|
+
logging.disable(logging.CRITICAL)
|
|
52
|
+
|
|
53
|
+
path = Path(input_path)
|
|
54
|
+
if not path.exists():
|
|
55
|
+
raise FileNotFoundError(f"Input path not found: {input_path}")
|
|
56
|
+
|
|
57
|
+
if path.is_dir():
|
|
58
|
+
files = sorted(path.glob("**/*.md"))
|
|
59
|
+
if not files:
|
|
60
|
+
raise FileNotFoundError(f"No Markdown files found in: {input_path}")
|
|
61
|
+
results = [_extract_file(f, **_build_kwargs(locals())) for f in files]
|
|
62
|
+
combined = _combine_results(results, format)
|
|
63
|
+
else:
|
|
64
|
+
combined = _extract_file(path, **_build_kwargs(locals()))
|
|
65
|
+
|
|
66
|
+
if output_dir:
|
|
67
|
+
out_path = Path(output_dir)
|
|
68
|
+
out_path.mkdir(parents=True, exist_ok=True)
|
|
69
|
+
ext = {"json": ".json", "text": ".txt", "html": ".html"}.get(format, ".txt")
|
|
70
|
+
out_file = out_path / f"{path.stem}{ext}"
|
|
71
|
+
out_file.write_text(combined, encoding="utf-8")
|
|
72
|
+
logger.info("Output written to %s", out_file)
|
|
73
|
+
|
|
74
|
+
if quiet:
|
|
75
|
+
logging.disable(logging.NOTSET)
|
|
76
|
+
|
|
77
|
+
return combined
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _build_kwargs(local_vars: dict[str, Any]) -> dict[str, Any]:
|
|
81
|
+
"""Build kwargs dict from local variables, excluding non-option args."""
|
|
82
|
+
exclude = {
|
|
83
|
+
"input_path",
|
|
84
|
+
"path",
|
|
85
|
+
"output_dir",
|
|
86
|
+
"quiet",
|
|
87
|
+
"files",
|
|
88
|
+
"results",
|
|
89
|
+
"combined",
|
|
90
|
+
"f",
|
|
91
|
+
}
|
|
92
|
+
return {k: v for k, v in local_vars.items() if k not in exclude and not k.startswith("_")}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _extract_file(
|
|
96
|
+
file_path: Path,
|
|
97
|
+
*,
|
|
98
|
+
format: str = "json",
|
|
99
|
+
heading_level: Optional[str] = None,
|
|
100
|
+
sections: Optional[str] = None,
|
|
101
|
+
include_frontmatter: bool = True,
|
|
102
|
+
strip_html: bool = False,
|
|
103
|
+
include_code_blocks: bool = True,
|
|
104
|
+
include_toc: bool = False,
|
|
105
|
+
flatten_lists: bool = False,
|
|
106
|
+
section_separator: Optional[str] = None,
|
|
107
|
+
normalize_links: bool = False,
|
|
108
|
+
) -> str:
|
|
109
|
+
"""Extract structured data from a single Markdown file."""
|
|
110
|
+
content = file_path.read_text(encoding="utf-8")
|
|
111
|
+
|
|
112
|
+
frontmatter, body = _split_frontmatter(content)
|
|
113
|
+
parsed_sections = _parse_sections(body)
|
|
114
|
+
|
|
115
|
+
# Filter by heading level
|
|
116
|
+
if heading_level:
|
|
117
|
+
levels = {int(lv.strip()) for lv in heading_level.split(",")}
|
|
118
|
+
parsed_sections = [s for s in parsed_sections if s["level"] in levels]
|
|
119
|
+
|
|
120
|
+
# Filter by section name
|
|
121
|
+
if sections:
|
|
122
|
+
names = [n.strip().lower() for n in sections.split(",")]
|
|
123
|
+
parsed_sections = [
|
|
124
|
+
s for s in parsed_sections if any(n in s["title"].lower() for n in names)
|
|
125
|
+
]
|
|
126
|
+
|
|
127
|
+
# Strip HTML
|
|
128
|
+
if strip_html:
|
|
129
|
+
for s in parsed_sections:
|
|
130
|
+
s["content"] = re.sub(r"<[^>]+>", "", s["content"])
|
|
131
|
+
|
|
132
|
+
# Remove code blocks
|
|
133
|
+
if not include_code_blocks:
|
|
134
|
+
for s in parsed_sections:
|
|
135
|
+
s["content"] = re.sub(r"```[\s\S]*?```", "", s["content"]).strip()
|
|
136
|
+
|
|
137
|
+
# Flatten lists
|
|
138
|
+
if flatten_lists:
|
|
139
|
+
for s in parsed_sections:
|
|
140
|
+
s["content"] = _flatten_lists(s["content"])
|
|
141
|
+
|
|
142
|
+
# Normalize links
|
|
143
|
+
if normalize_links:
|
|
144
|
+
base_dir = str(file_path.parent)
|
|
145
|
+
for s in parsed_sections:
|
|
146
|
+
s["content"] = _normalize_links(s["content"], base_dir)
|
|
147
|
+
|
|
148
|
+
# Build TOC
|
|
149
|
+
toc = _build_toc(parsed_sections) if include_toc else None
|
|
150
|
+
|
|
151
|
+
# Format output
|
|
152
|
+
if format == "json":
|
|
153
|
+
return _format_json(file_path, frontmatter, parsed_sections, toc, include_frontmatter)
|
|
154
|
+
elif format == "html":
|
|
155
|
+
return _format_html(file_path, frontmatter, parsed_sections, toc, include_frontmatter)
|
|
156
|
+
else:
|
|
157
|
+
return _format_text(
|
|
158
|
+
file_path,
|
|
159
|
+
frontmatter,
|
|
160
|
+
parsed_sections,
|
|
161
|
+
toc,
|
|
162
|
+
include_frontmatter,
|
|
163
|
+
section_separator,
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _split_frontmatter(content: str) -> tuple[Optional[dict[str, Any]], str]:
|
|
168
|
+
"""Split YAML/TOML frontmatter from body."""
|
|
169
|
+
if content.startswith("---"):
|
|
170
|
+
parts = content.split("---", 2)
|
|
171
|
+
if len(parts) >= 3:
|
|
172
|
+
try:
|
|
173
|
+
# Simple YAML-like parsing (key: value)
|
|
174
|
+
fm: dict[str, Any] = {}
|
|
175
|
+
for line in parts[1].strip().splitlines():
|
|
176
|
+
if ":" in line:
|
|
177
|
+
key, _, value = line.partition(":")
|
|
178
|
+
fm[key.strip()] = value.strip()
|
|
179
|
+
return fm, parts[2].strip()
|
|
180
|
+
except Exception:
|
|
181
|
+
pass
|
|
182
|
+
return None, content
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _parse_sections(body: str) -> list[dict[str, Any]]:
|
|
186
|
+
"""Parse Markdown body into sections based on headings."""
|
|
187
|
+
sections: list[dict[str, Any]] = []
|
|
188
|
+
current: Optional[dict[str, Any]] = None
|
|
189
|
+
lines: list[str] = []
|
|
190
|
+
|
|
191
|
+
for line in body.splitlines():
|
|
192
|
+
heading_match = re.match(r"^(#{1,6})\s+(.+)$", line)
|
|
193
|
+
if heading_match:
|
|
194
|
+
if current is not None:
|
|
195
|
+
current["content"] = "\n".join(lines).strip()
|
|
196
|
+
sections.append(current)
|
|
197
|
+
level = len(heading_match.group(1))
|
|
198
|
+
title = heading_match.group(2).strip()
|
|
199
|
+
current = {"level": level, "title": title, "content": ""}
|
|
200
|
+
lines = []
|
|
201
|
+
else:
|
|
202
|
+
lines.append(line)
|
|
203
|
+
|
|
204
|
+
# Handle remaining content
|
|
205
|
+
if current is not None:
|
|
206
|
+
current["content"] = "\n".join(lines).strip()
|
|
207
|
+
sections.append(current)
|
|
208
|
+
elif lines:
|
|
209
|
+
content = "\n".join(lines).strip()
|
|
210
|
+
if content:
|
|
211
|
+
sections.append({"level": 0, "title": "", "content": content})
|
|
212
|
+
|
|
213
|
+
return sections
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _build_toc(sections: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
|
217
|
+
"""Build table of contents from sections."""
|
|
218
|
+
return [{"level": s["level"], "title": s["title"]} for s in sections if s["level"] > 0]
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _flatten_lists(content: str) -> str:
|
|
222
|
+
"""Flatten nested lists to a single level."""
|
|
223
|
+
result = []
|
|
224
|
+
for line in content.splitlines():
|
|
225
|
+
match = re.match(r"^(\s*)[-*+]\s+(.+)$", line)
|
|
226
|
+
if match:
|
|
227
|
+
result.append(f"- {match.group(2)}")
|
|
228
|
+
else:
|
|
229
|
+
result.append(line)
|
|
230
|
+
return "\n".join(result)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def _normalize_links(content: str, base_dir: str) -> str:
|
|
234
|
+
"""Convert relative links to absolute paths."""
|
|
235
|
+
|
|
236
|
+
def replace_link(m: re.Match[str]) -> str:
|
|
237
|
+
text, url = m.group(1), m.group(2)
|
|
238
|
+
if not url.startswith(("http://", "https://", "#", "mailto:")):
|
|
239
|
+
url = str(Path(base_dir) / url)
|
|
240
|
+
return f"[{text}]({url})"
|
|
241
|
+
|
|
242
|
+
return re.sub(r"\[([^\]]+)\]\(([^)]+)\)", replace_link, content)
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _format_json(
|
|
246
|
+
file_path: Path,
|
|
247
|
+
frontmatter: Optional[dict[str, Any]],
|
|
248
|
+
sections: list[dict[str, Any]],
|
|
249
|
+
toc: Optional[list[dict[str, Any]]],
|
|
250
|
+
include_frontmatter: bool,
|
|
251
|
+
) -> str:
|
|
252
|
+
"""Format output as JSON."""
|
|
253
|
+
result: dict[str, Any] = {"source": str(file_path)}
|
|
254
|
+
if include_frontmatter and frontmatter:
|
|
255
|
+
result["frontmatter"] = frontmatter
|
|
256
|
+
if toc:
|
|
257
|
+
result["toc"] = toc
|
|
258
|
+
result["sections"] = sections
|
|
259
|
+
return json.dumps(result, ensure_ascii=False, indent=2)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _format_text(
|
|
263
|
+
file_path: Path,
|
|
264
|
+
frontmatter: Optional[dict[str, Any]],
|
|
265
|
+
sections: list[dict[str, Any]],
|
|
266
|
+
toc: Optional[list[dict[str, Any]]],
|
|
267
|
+
include_frontmatter: bool,
|
|
268
|
+
section_separator: Optional[str] = None,
|
|
269
|
+
) -> str:
|
|
270
|
+
"""Format output as plain text."""
|
|
271
|
+
parts: list[str] = []
|
|
272
|
+
|
|
273
|
+
if include_frontmatter and frontmatter:
|
|
274
|
+
fm_lines = [f"{k}: {v}" for k, v in frontmatter.items()]
|
|
275
|
+
parts.append("\n".join(fm_lines))
|
|
276
|
+
|
|
277
|
+
if toc:
|
|
278
|
+
toc_lines = ["Table of Contents:"]
|
|
279
|
+
for entry in toc:
|
|
280
|
+
indent = " " * (entry["level"] - 1)
|
|
281
|
+
toc_lines.append(f"{indent}- {entry['title']}")
|
|
282
|
+
parts.append("\n".join(toc_lines))
|
|
283
|
+
|
|
284
|
+
for s in sections:
|
|
285
|
+
if section_separator and s["title"]:
|
|
286
|
+
sep = section_separator.replace("%section-title%", s["title"])
|
|
287
|
+
parts.append(sep)
|
|
288
|
+
if s["title"]:
|
|
289
|
+
parts.append(f"{'#' * s['level']} {s['title']}")
|
|
290
|
+
if s["content"]:
|
|
291
|
+
parts.append(s["content"])
|
|
292
|
+
|
|
293
|
+
return "\n\n".join(parts)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _format_html(
|
|
297
|
+
file_path: Path,
|
|
298
|
+
frontmatter: Optional[dict[str, Any]],
|
|
299
|
+
sections: list[dict[str, Any]],
|
|
300
|
+
toc: Optional[list[dict[str, Any]]],
|
|
301
|
+
include_frontmatter: bool,
|
|
302
|
+
) -> str:
|
|
303
|
+
"""Format output as HTML."""
|
|
304
|
+
parts: list[str] = ["<!DOCTYPE html>", "<html>", "<body>"]
|
|
305
|
+
|
|
306
|
+
if include_frontmatter and frontmatter:
|
|
307
|
+
parts.append("<dl>")
|
|
308
|
+
for k, v in frontmatter.items():
|
|
309
|
+
parts.append(f" <dt>{k}</dt><dd>{v}</dd>")
|
|
310
|
+
parts.append("</dl>")
|
|
311
|
+
|
|
312
|
+
if toc:
|
|
313
|
+
parts.append("<nav><ul>")
|
|
314
|
+
for entry in toc:
|
|
315
|
+
parts.append(f' <li class="level-{entry["level"]}">{entry["title"]}</li>')
|
|
316
|
+
parts.append("</ul></nav>")
|
|
317
|
+
|
|
318
|
+
for s in sections:
|
|
319
|
+
if s["title"]:
|
|
320
|
+
tag = f"h{min(s['level'], 6)}"
|
|
321
|
+
parts.append(f"<{tag}>{s['title']}</{tag}>")
|
|
322
|
+
if s["content"]:
|
|
323
|
+
paragraphs = s["content"].split("\n\n")
|
|
324
|
+
for p in paragraphs:
|
|
325
|
+
if p.strip():
|
|
326
|
+
parts.append(f"<p>{p.strip()}</p>")
|
|
327
|
+
|
|
328
|
+
parts.extend(["</body>", "</html>"])
|
|
329
|
+
return "\n".join(parts)
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _combine_results(results: list[str], format: str) -> str:
|
|
333
|
+
"""Combine multiple file results."""
|
|
334
|
+
if format == "json":
|
|
335
|
+
parsed = [json.loads(r) for r in results]
|
|
336
|
+
return json.dumps(parsed, ensure_ascii=False, indent=2)
|
|
337
|
+
return "\n\n---\n\n".join(results)
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: jostack-mdparse
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Markdown file parser and structured extraction tool
|
|
5
|
+
Project-URL: Repository, https://github.com/hyunhee-jo/jostack-mdparse
|
|
6
|
+
Project-URL: Issues, https://github.com/hyunhee-jo/jostack-mdparse/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/hyunhee-jo/jostack-mdparse/blob/main/CHANGELOG.md
|
|
8
|
+
Author: hyunhee-jo
|
|
9
|
+
License-Expression: Apache-2.0
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: cli,extraction,markdown,parser,structured-data
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Topic :: Text Processing :: Markup :: Markdown
|
|
19
|
+
Requires-Python: >=3.10
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
<!-- AI-AGENT-SUMMARY
|
|
23
|
+
name: jostack-mdparse
|
|
24
|
+
category: Markdown parser, structured extraction
|
|
25
|
+
license: MIT
|
|
26
|
+
solves: [Parse Markdown files into structured data, section-level extraction]
|
|
27
|
+
input: Markdown files (.md)
|
|
28
|
+
output: JSON, text, HTML
|
|
29
|
+
sdk: Python
|
|
30
|
+
requirements: Python 3.10+
|
|
31
|
+
key-differentiators: [CLI + Python API, section filtering, frontmatter extraction, options.json SsoT]
|
|
32
|
+
-->
|
|
33
|
+
|
|
34
|
+
# jostack-mdparse
|
|
35
|
+
|
|
36
|
+
[](https://github.com/hyunhee-jo/jostack-mdparse/actions/workflows/ci.yml)
|
|
37
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
38
|
+
[](https://www.python.org/downloads/)
|
|
39
|
+
|
|
40
|
+
Markdown file parser and structured extraction tool (CLI + Python API).
|
|
41
|
+
|
|
42
|
+
## Installation
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install jostack-mdparse
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Quick Start
|
|
49
|
+
|
|
50
|
+
### CLI
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
# Extract as JSON
|
|
54
|
+
jostack-mdparse extract README.md -f json
|
|
55
|
+
|
|
56
|
+
# Extract specific sections
|
|
57
|
+
jostack-mdparse extract docs/ -s "Installation,Usage" -f text
|
|
58
|
+
|
|
59
|
+
# Print table of contents
|
|
60
|
+
jostack-mdparse toc README.md
|
|
61
|
+
|
|
62
|
+
# Print frontmatter metadata
|
|
63
|
+
jostack-mdparse meta blog-post.md
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
### Python API
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
from jostack_mdparse import extract
|
|
70
|
+
|
|
71
|
+
# Basic extraction
|
|
72
|
+
result = extract("README.md", format="json")
|
|
73
|
+
|
|
74
|
+
# Filter by heading level
|
|
75
|
+
result = extract("docs/guide.md", heading_level="1,2", format="text")
|
|
76
|
+
|
|
77
|
+
# Extract specific sections
|
|
78
|
+
result = extract("README.md", sections="Usage", strip_html=True)
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Commands
|
|
82
|
+
|
|
83
|
+
| Command | Description |
|
|
84
|
+
|---------|-------------|
|
|
85
|
+
| `extract` | Parse Markdown and output structured data (JSON, text, HTML) |
|
|
86
|
+
| `toc` | Print the table of contents (heading tree) |
|
|
87
|
+
| `meta` | Print frontmatter metadata as JSON |
|
|
88
|
+
|
|
89
|
+
## Parameters
|
|
90
|
+
|
|
91
|
+
| Parameter | Type | Default | Description |
|
|
92
|
+
|-----------|------|---------|-------------|
|
|
93
|
+
| `output-dir` | `str` | `None` | Directory where output files are written |
|
|
94
|
+
| `format` | `str` | `"json"` | Output format: json, text, html |
|
|
95
|
+
| `quiet` | `bool` | `False` | Suppress console logging output |
|
|
96
|
+
| `heading-level` | `str` | `None` | Filter by heading levels (comma-separated) |
|
|
97
|
+
| `sections` | `str` | `None` | Extract sections by heading text (comma-separated) |
|
|
98
|
+
| `include-frontmatter` | `bool` | `True` | Include YAML/TOML frontmatter in output |
|
|
99
|
+
| `strip-html` | `bool` | `False` | Strip inline HTML tags |
|
|
100
|
+
| `include-code-blocks` | `bool` | `True` | Include fenced code blocks |
|
|
101
|
+
| `include-toc` | `bool` | `False` | Add generated table of contents |
|
|
102
|
+
| `flatten-lists` | `bool` | `False` | Flatten nested lists |
|
|
103
|
+
| `section-separator` | `str` | `None` | Separator between sections in text output |
|
|
104
|
+
| `normalize-links` | `bool` | `False` | Convert relative links to absolute |
|
|
105
|
+
|
|
106
|
+
## Development
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
# Install in development mode
|
|
110
|
+
pip install -e .
|
|
111
|
+
|
|
112
|
+
# Run tests
|
|
113
|
+
make test
|
|
114
|
+
|
|
115
|
+
# Run linting
|
|
116
|
+
make lint
|
|
117
|
+
|
|
118
|
+
# Format code
|
|
119
|
+
make format
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## License
|
|
123
|
+
|
|
124
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
jostack_mdparse/__init__.py,sha256=TgaUrnpDUMbByXtr1G8DQt5mDgMLockJFMDHQErxiBY,182
|
|
2
|
+
jostack_mdparse/cli.py,sha256=EEGMSNP03HENT46tRHHDDWrrRqltR8WZ5tQT97b64GA,4533
|
|
3
|
+
jostack_mdparse/extract.py,sha256=H51MoayFTP7LqXB2ITlRoZGUQj-QWSN7jsDWYwMqFTM,10998
|
|
4
|
+
jostack_mdparse-0.1.0.dist-info/METADATA,sha256=zqYHWmvnVp67BgYS92fGIZoz0kGHs7i0MuescUxY-WM,3903
|
|
5
|
+
jostack_mdparse-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
6
|
+
jostack_mdparse-0.1.0.dist-info/entry_points.txt,sha256=trtxIzsJVfGvE37cU2r7cQtJ5U5tmQGyvTM0VdJem14,61
|
|
7
|
+
jostack_mdparse-0.1.0.dist-info/licenses/LICENSE,sha256=1ne3lp-gb7pRBz-AKpp-8RpBdYKZ5UG394Q43fQx0lk,10709
|
|
8
|
+
jostack_mdparse-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work.
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to the Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by the Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding any notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 hyunhee-jo
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|