marklas 0.4.4__tar.gz → 0.4.6__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: marklas
3
- Version: 0.4.4
3
+ Version: 0.4.6
4
4
  Summary: Bidirectional converter between GitHub Flavored Markdown and Atlassian Document Format
5
5
  Author: byExist
6
6
  Author-email: byExist <jongbeom.kwon@gmail.com>
@@ -138,11 +138,10 @@ Markdown is significantly more compact than ADF JSON — critical for LLM-based
138
138
 
139
139
  | | ADF JSON | Markdown (annotated) | Markdown (plain) |
140
140
  | --- | --- | --- | --- |
141
- | Tokens | 102,706 | 33,343 | 12,454 |
142
- | Bytes | 625 KB | 99 KB | 38 KB |
143
- | **Reduction** | — | **3.1x / 6.3x** | **8.2x / 16.5x** |
141
+ | Tokens | 243,217 | 76,541 | 41,744 |
142
+ | **Reduction** | — | **3.2x** | **5.8x** |
144
143
 
145
- *Measured on a real Confluence page using GPT-4o tokenizer (tiktoken).*
144
+ *Measured on 7 real Confluence pages (pretty-printed JSON) using GPT-4o tokenizer (tiktoken).*
146
145
 
147
146
  ## Notes
148
147
 
@@ -119,11 +119,10 @@ Markdown is significantly more compact than ADF JSON — critical for LLM-based
119
119
 
120
120
  | | ADF JSON | Markdown (annotated) | Markdown (plain) |
121
121
  | --- | --- | --- | --- |
122
- | Tokens | 102,706 | 33,343 | 12,454 |
123
- | Bytes | 625 KB | 99 KB | 38 KB |
124
- | **Reduction** | — | **3.1x / 6.3x** | **8.2x / 16.5x** |
122
+ | Tokens | 243,217 | 76,541 | 41,744 |
123
+ | **Reduction** | — | **3.2x** | **5.8x** |
125
124
 
126
- *Measured on a real Confluence page using GPT-4o tokenizer (tiktoken).*
125
+ *Measured on 7 real Confluence pages (pretty-printed JSON) using GPT-4o tokenizer (tiktoken).*
127
126
 
128
127
  ## Notes
129
128
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "marklas"
3
- version = "0.4.4"
3
+ version = "0.4.6"
4
4
  description = "Bidirectional converter between GitHub Flavored Markdown and Atlassian Document Format"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -554,13 +554,127 @@ def _parse_annotated_layout_column(token: dict[str, Any]) -> blocks.LayoutColumn
554
554
  # ---------------------------------------------------------------------------
555
555
 
556
556
 
557
- def _br_to_linebreak(tok: dict[str, Any]) -> dict[str, Any]:
558
- if tok.get("type") == "inline_html" and tok["raw"].strip().lower() in (
559
- "<br>",
560
- "<br/>",
561
- "<br />",
562
- ):
557
+ _HTML_CELL_BLOCK_MAP: dict[str, str] = {
558
+ "blockquote": "blockQuote",
559
+ "h1": "heading",
560
+ "h2": "heading",
561
+ "h3": "heading",
562
+ "h4": "heading",
563
+ "h5": "heading",
564
+ "h6": "heading",
565
+ "ul": "bulletList",
566
+ "ol": "orderedList",
567
+ "code": "codeBlock",
568
+ }
569
+
570
+ _HTML_CELL_VOID_MAP: dict[str, str] = {
571
+ "hr": "thematicBreak",
572
+ }
573
+
574
+
575
+ def _match_html_cell_blocks(tokens: list[dict[str, Any]]) -> list[dict[str, Any]]:
576
+ """Match HTML open/close tag pairs for known block types into annotated-style tokens."""
577
+ result: list[dict[str, Any]] = []
578
+ i = 0
579
+ while i < len(tokens):
580
+ tok = tokens[i]
581
+ if tok.get("_annotated"):
582
+ result.append(tok)
583
+ i += 1
584
+ continue
585
+ if tok.get("type") == "inline_html":
586
+ tag = _extract_html_open_tag(tok["raw"])
587
+ if tag and tag in _HTML_CELL_VOID_MAP:
588
+ result.append(
589
+ {
590
+ "type": _HTML_CELL_VOID_MAP[tag],
591
+ "attrs": {},
592
+ "children": [],
593
+ "_annotated": True,
594
+ }
595
+ )
596
+ i += 1
597
+ continue
598
+ if tag and tag in _HTML_CELL_BLOCK_MAP:
599
+ close_idx = _find_html_close_idx(tokens, i + 1, tag)
600
+ if close_idx is not None:
601
+ attrs: dict[str, Any] = {}
602
+ block_type = _HTML_CELL_BLOCK_MAP[tag]
603
+ if block_type == "heading":
604
+ attrs["level"] = int(tag[1])
605
+ elif block_type == "orderedList":
606
+ start = _extract_html_attr(tok["raw"], "start")
607
+ if start is not None:
608
+ attrs["start"] = int(start)
609
+ result.append(
610
+ {
611
+ "type": block_type,
612
+ "attrs": attrs,
613
+ "children": tokens[i + 1 : close_idx],
614
+ "_annotated": True,
615
+ }
616
+ )
617
+ i = close_idx + 1
618
+ continue
619
+ result.append(tok)
620
+ i += 1
621
+ return result
622
+
623
+
624
+ def _extract_html_open_tag(raw: str) -> str | None:
625
+ """Extract tag name from an opening HTML tag, or None."""
626
+ s = raw.strip().lower()
627
+ if not s.startswith("<") or s.startswith("</"):
628
+ return None
629
+ # e.g. <blockquote>, <ol start="2">
630
+ tag = s.lstrip("<").split(">")[0].split()[0].rstrip("/")
631
+ return tag if tag else None
632
+
633
+
634
+ _HTML_ATTR_RE = re.compile(r"""(\w+)\s*=\s*(?:"([^"]*)"|'([^']*)')""")
635
+
636
+
637
+ def _extract_html_attr(raw: str, name: str) -> str | None:
638
+ """Extract a named attribute value from an HTML open tag."""
639
+ for m in _HTML_ATTR_RE.finditer(raw):
640
+ if m.group(1).lower() == name.lower():
641
+ return m.group(2) if m.group(2) is not None else m.group(3)
642
+ return None
643
+
644
+
645
+ def _find_html_close_idx(
646
+ tokens: list[dict[str, Any]], start: int, tag: str
647
+ ) -> int | None:
648
+ """Find matching close tag index, handling nesting."""
649
+ depth = 1
650
+ for i in range(start, len(tokens)):
651
+ tok = tokens[i]
652
+ if tok.get("_annotated"):
653
+ continue
654
+ if tok.get("type") == "inline_html":
655
+ raw = tok["raw"].strip().lower()
656
+ if (
657
+ raw.startswith(f"<{tag}")
658
+ and raw.endswith(">")
659
+ and not raw.startswith(f"</{tag}")
660
+ ):
661
+ depth += 1
662
+ elif raw == f"</{tag}>":
663
+ depth -= 1
664
+ if depth == 0:
665
+ return i
666
+ return None
667
+
668
+
669
+ def _classify_br(tok: dict[str, Any]) -> dict[str, Any]:
670
+ """Classify ``<br>`` variants: ``<br>`` → block separator, ``<br/>`` → linebreak (hardBreak)."""
671
+ if tok.get("type") != "inline_html":
672
+ return tok
673
+ raw = tok["raw"].strip().lower()
674
+ if raw == "<br/>":
563
675
  return {"type": "linebreak"}
676
+ if raw == "<br>":
677
+ return {"type": "block_separator"}
564
678
  return tok
565
679
 
566
680
 
@@ -569,43 +683,74 @@ def _parse_cell_blocks(tokens: list[dict[str, Any]]) -> list[blocks.Block]:
569
683
 
570
684
  Uses annotation matching to group tokens, then dispatches each group.
571
685
  Unannotated tokens become Paragraph (plain GFM).
686
+ ``<br>`` = block separator, ``<br/>`` = hardBreak (linebreak).
572
687
  """
573
- # Rewrite <br> inline_html → linebreak before annotation matching so that
574
- # HardBreak survives inside annotated paragraph children.
575
- rewritten = [_br_to_linebreak(t) for t in tokens]
576
- matched = _match_cell_annotations(rewritten)
688
+ matched = _match_html_cell_blocks(_match_cell_annotations(tokens))
577
689
  result: list[blocks.Block] = []
578
690
  loose: list[dict[str, Any]] = []
579
691
 
580
692
  def _flush_loose() -> None:
581
693
  if not loose:
582
694
  return
583
- # linebreak-only loose tokens are block separators — skip them
584
- if all(t.get("type") == "linebreak" for t in loose):
585
- loose.clear()
586
- return
587
695
  children = _parse_inlines(loose)
588
696
  if children:
589
697
  result.append(blocks.Paragraph(children=children))
590
698
  loose.clear()
591
699
 
700
+ _CELL_BLOCK_TAGS = {
701
+ "paragraph",
702
+ "codeBlock",
703
+ "blockQuote",
704
+ "heading",
705
+ "thematicBreak",
706
+ "bulletList",
707
+ "orderedList",
708
+ "panel",
709
+ "expand",
710
+ "nestedExpand",
711
+ "taskList",
712
+ "decisionList",
713
+ "mediaSingle",
714
+ "mediaGroup",
715
+ "blockCard",
716
+ "embedCard",
717
+ "extension",
718
+ "bodiedExtension",
719
+ "syncBlock",
720
+ "bodiedSyncBlock",
721
+ }
722
+
592
723
  for tok in matched:
593
- if tok.get("_annotated"):
724
+ if tok.get("_annotated") and tok["type"] in _CELL_BLOCK_TAGS:
594
725
  _flush_loose()
595
726
  block = _parse_cell_block(tok)
596
727
  result.append(block)
597
- else:
728
+ elif tok.get("_annotated"):
729
+ # Inline annotation (e.g. status, mention) — keep as loose tokens
598
730
  loose.append(tok)
731
+ else:
732
+ classified = _classify_br(tok)
733
+ if classified.get("type") == "block_separator":
734
+ _flush_loose()
735
+ else:
736
+ loose.append(classified)
599
737
 
600
738
  _flush_loose()
601
739
  return result
602
740
 
603
741
 
742
+ def _br_to_linebreak(tok: dict[str, Any]) -> dict[str, Any]:
743
+ """Convert ``<br/>`` to linebreak inside annotated children."""
744
+ if tok.get("type") == "inline_html" and tok["raw"].strip().lower() == "<br/>":
745
+ return {"type": "linebreak"}
746
+ return tok
747
+
748
+
604
749
  def _parse_cell_block(token: dict[str, Any]) -> blocks.Block:
605
750
  """Dispatch an annotation-matched cell token to the appropriate handler."""
606
751
  tag = token["type"]
607
752
  attrs = token.get("attrs", {})
608
- inner = token.get("children", [])
753
+ inner = [_br_to_linebreak(t) for t in token.get("children", [])]
609
754
 
610
755
  match tag:
611
756
  case "paragraph":
@@ -200,7 +200,7 @@ def _render_list_item_body(children: list[blocks.Block], tight: bool) -> str:
200
200
  continue
201
201
  rendered = _render_block(child)
202
202
  parts.append(rendered)
203
- body = "\n\n".join(parts)
203
+ body = "\n".join(parts)
204
204
  lines = body.split("\n")
205
205
  if len(lines) > 1:
206
206
  return (
@@ -257,8 +257,7 @@ def _render_table_row(row: list[blocks.TableCell], col_count: int) -> str:
257
257
 
258
258
  def _render_table_cell(cell: blocks.TableCell) -> str:
259
259
  parts = [_render_cell_block(c) for c in cell.children]
260
- sep = "" if _annotate_ctx.get() else "<br>"
261
- return _escape_cell_pipe(sep.join(parts))
260
+ return _escape_cell_pipe("<br>".join(parts))
262
261
 
263
262
 
264
263
  def _escape_cell_pipe(text: str) -> str:
@@ -482,40 +481,44 @@ def _render_cell_block(node: blocks.Block) -> str:
482
481
 
483
482
  def _render_cell_inlines(nodes: list[inlines.Inline]) -> str:
484
483
  return "".join(
485
- "<br>" if isinstance(node, inlines.HardBreak) else _render_inline(node)
484
+ "<br/>" if isinstance(node, inlines.HardBreak) else _render_inline(node)
486
485
  for node in nodes
487
486
  )
488
487
 
489
488
 
490
489
  def _render_cell_paragraph(node: blocks.Paragraph) -> str:
491
490
  content = _render_cell_inlines(node.children)
492
- return _annotate_inline(
493
- node,
494
- content,
495
- align=node.alignment,
496
- indentation=node.indentation,
497
- )
491
+ if node.alignment or node.indentation:
492
+ return _annotate_inline(
493
+ node,
494
+ content,
495
+ align=node.alignment,
496
+ indentation=node.indentation,
497
+ )
498
+ return content.strip()
498
499
 
499
500
 
500
501
  def _render_cell_code_block(node: blocks.CodeBlock) -> str:
501
502
  code = node.code.replace("\n", "<br>")
502
503
  html = f"<code>{code}</code>"
503
- return _annotate_inline(node, html, language=node.language)
504
+ if node.language:
505
+ return _annotate_inline(node, html, language=node.language)
506
+ return html
504
507
 
505
508
 
506
509
  def _render_cell_blockquote(node: blocks.BlockQuote) -> str:
507
510
  inner = "<br>".join(_render_cell_block(c) for c in node.children)
508
- return _annotate_inline(node, f"<blockquote>{inner}</blockquote>")
511
+ return f"<blockquote>{inner}</blockquote>"
509
512
 
510
513
 
511
514
  def _render_cell_heading(node: blocks.Heading) -> str:
512
515
  tag = f"h{node.level}"
513
516
  inner = _render_cell_inlines(node.children)
514
- return _annotate_inline(node, f"<{tag}>{inner}</{tag}>", level=node.level)
517
+ return f"<{tag}>{inner}</{tag}>"
515
518
 
516
519
 
517
520
  def _render_cell_rule() -> str:
518
- return _annotate_inline(blocks.ThematicBreak(), "<hr>")
521
+ return "<hr>"
519
522
 
520
523
 
521
524
  def _render_cell_list(node: blocks.BulletList | blocks.OrderedList) -> str:
@@ -529,10 +532,7 @@ def _render_cell_list(node: blocks.BulletList | blocks.OrderedList) -> str:
529
532
  for item in node.items:
530
533
  body = "<br>".join(_render_cell_block(c) for c in item.children)
531
534
  items.append(f"<li>{body}</li>")
532
- html = f"<{tag}{start_attr}>{''.join(items)}</{tag}>"
533
- if isinstance(node, blocks.OrderedList) and node.start != 1:
534
- return _annotate_inline(node, html, start=node.start)
535
- return _annotate_inline(node, html)
535
+ return f"<{tag}{start_attr}>{''.join(items)}</{tag}>"
536
536
 
537
537
 
538
538
  def _render_cell_panel(node: blocks.Panel) -> str:
File without changes
File without changes
File without changes