braidio 0.0.73__tar.gz → 0.0.74__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.
Files changed (144) hide show
  1. {braidio-0.0.73 → braidio-0.0.74}/PKG-INFO +6 -1
  2. {braidio-0.0.73 → braidio-0.0.74}/braidio/__init__.py +11 -0
  3. {braidio-0.0.73 → braidio-0.0.74}/braidio/data/skills/braidio/SKILL.md +2 -1
  4. braidio-0.0.74/braidio/markdown_script.py +354 -0
  5. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/_helpers.py +14 -0
  6. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/tools.py +43 -8
  7. {braidio-0.0.73 → braidio-0.0.74}/braidio/style.py +5 -0
  8. {braidio-0.0.73 → braidio-0.0.74}/pyproject.toml +5 -2
  9. braidio-0.0.74/tests/test_markdown_script.py +325 -0
  10. {braidio-0.0.73 → braidio-0.0.74}/tests/test_mcp.py +53 -0
  11. {braidio-0.0.73 → braidio-0.0.74}/.editorconfig +0 -0
  12. {braidio-0.0.73 → braidio-0.0.74}/.gitattributes +0 -0
  13. {braidio-0.0.73 → braidio-0.0.74}/.gitignore +0 -0
  14. {braidio-0.0.73 → braidio-0.0.74}/LICENSE +0 -0
  15. {braidio-0.0.73 → braidio-0.0.74}/README.md +0 -0
  16. {braidio-0.0.73 → braidio-0.0.74}/braidio/_paths.py +0 -0
  17. {braidio-0.0.73 → braidio-0.0.74}/braidio/bodies/__init__.py +0 -0
  18. {braidio-0.0.73 → braidio-0.0.74}/braidio/bodies/_domain.py +0 -0
  19. {braidio-0.0.73 → braidio-0.0.74}/braidio/bodies/_render_nodes.py +0 -0
  20. {braidio-0.0.73 → braidio-0.0.74}/braidio/bodies/_tiers.py +0 -0
  21. {braidio-0.0.73 → braidio-0.0.74}/braidio/bodies/_video.py +0 -0
  22. {braidio-0.0.73 → braidio-0.0.74}/braidio/captions.py +0 -0
  23. {braidio-0.0.73 → braidio-0.0.74}/braidio/compose.py +0 -0
  24. {braidio-0.0.73 → braidio-0.0.74}/braidio/conversation.py +0 -0
  25. {braidio-0.0.73 → braidio-0.0.74}/braidio/cost.py +0 -0
  26. {braidio-0.0.73 → braidio-0.0.74}/braidio/data/skills/braidio-commentary-video/SKILL.md +0 -0
  27. {braidio-0.0.73 → braidio-0.0.74}/braidio/defaults.py +0 -0
  28. {braidio-0.0.73 → braidio-0.0.74}/braidio/delivery.py +0 -0
  29. {braidio-0.0.73 → braidio-0.0.74}/braidio/downloads.py +0 -0
  30. {braidio-0.0.73 → braidio-0.0.74}/braidio/formats.py +0 -0
  31. {braidio-0.0.73 → braidio-0.0.74}/braidio/genre.py +0 -0
  32. {braidio-0.0.73 → braidio-0.0.74}/braidio/importing/__init__.py +0 -0
  33. {braidio-0.0.73 → braidio-0.0.74}/braidio/importing/__main__.py +0 -0
  34. {braidio-0.0.73 → braidio-0.0.74}/braidio/importing/_catalog.py +0 -0
  35. {braidio-0.0.73 → braidio-0.0.74}/braidio/importing/_manifest.py +0 -0
  36. {braidio-0.0.73 → braidio-0.0.74}/braidio/importing/_writer.py +0 -0
  37. {braidio-0.0.73 → braidio-0.0.74}/braidio/kinds.py +0 -0
  38. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/__init__.py +0 -0
  39. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/_docs.py +0 -0
  40. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/_guide.py +0 -0
  41. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/_media.py +0 -0
  42. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/credentials.py +0 -0
  43. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/metering.py +0 -0
  44. {braidio-0.0.73 → braidio-0.0.74}/braidio/mcp/workspace.py +0 -0
  45. {braidio-0.0.73 → braidio-0.0.74}/braidio/multivoice.py +0 -0
  46. {braidio-0.0.73 → braidio-0.0.74}/braidio/music.py +0 -0
  47. {braidio-0.0.73 → braidio-0.0.74}/braidio/pacing.py +0 -0
  48. {braidio-0.0.73 → braidio-0.0.74}/braidio/project.py +0 -0
  49. {braidio-0.0.73 → braidio-0.0.74}/braidio/provenance.py +0 -0
  50. {braidio-0.0.73 → braidio-0.0.74}/braidio/relevance.py +0 -0
  51. {braidio-0.0.73 → braidio-0.0.74}/braidio/render.py +0 -0
  52. {braidio-0.0.73 → braidio-0.0.74}/braidio/rights.py +0 -0
  53. {braidio-0.0.73 → braidio-0.0.74}/braidio/script.py +0 -0
  54. {braidio-0.0.73 → braidio-0.0.74}/braidio/sources.py +0 -0
  55. {braidio-0.0.73 → braidio-0.0.74}/braidio/structure.py +0 -0
  56. {braidio-0.0.73 → braidio-0.0.74}/braidio/textprep.py +0 -0
  57. {braidio-0.0.73 → braidio-0.0.74}/braidio/timeline.py +0 -0
  58. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/__init__.py +0 -0
  59. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_asset_refs.py +0 -0
  60. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_common.py +0 -0
  61. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_dialogue.py +0 -0
  62. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_episode.py +0 -0
  63. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_ingest.py +0 -0
  64. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_narration.py +0 -0
  65. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_segment.py +0 -0
  66. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_video_cut.py +0 -0
  67. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_video_panels.py +0 -0
  68. {braidio-0.0.73 → braidio-0.0.74}/braidio/transforms/_voice.py +0 -0
  69. {braidio-0.0.73 → braidio-0.0.74}/braidio/tts.py +0 -0
  70. {braidio-0.0.73 → braidio-0.0.74}/braidio/video.py +0 -0
  71. {braidio-0.0.73 → braidio-0.0.74}/braidio/voice_library.py +0 -0
  72. {braidio-0.0.73 → braidio-0.0.74}/braidio/weave.py +0 -0
  73. {braidio-0.0.73 → braidio-0.0.74}/braidio/weave_config.py +0 -0
  74. {braidio-0.0.73 → braidio-0.0.74}/conftest.py +0 -0
  75. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/Extraction and nw-App Design.md +0 -0
  76. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/research/commentary-formats-and-styles.md +0 -0
  77. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/research/conversational-vs-narration-tts.md +0 -0
  78. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/research/notebooklm-and-conversational-pacing.md +0 -0
  79. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/README.md +0 -0
  80. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/anti-platitude-checklist.md +0 -0
  81. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/commentary-voice-guide.md +0 -0
  82. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/_style-groups.md +0 -0
  83. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/amanda-dobbins.md +0 -0
  84. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/david-sims.md +0 -0
  85. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/griffin-newman.md +0 -0
  86. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/helen-molesworth.md +0 -0
  87. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/hrishikesh-hirway.md +0 -0
  88. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/jason-mantzoukas.md +0 -0
  89. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/john-mcwhorter.md +0 -0
  90. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/jon-caramanica.md +0 -0
  91. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/june-diane-raphael.md +0 -0
  92. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/karina-longworth.md +0 -0
  93. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/katy-hessel.md +0 -0
  94. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/louis-theroux.md +0 -0
  95. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/mallory-rubin.md +0 -0
  96. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/melvyn-bragg.md +0 -0
  97. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/michael-barbaro.md +0 -0
  98. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/nate-sloan-charlie-harding.md +0 -0
  99. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/paul-scheer.md +0 -0
  100. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/sean-fennessey.md +0 -0
  101. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/talk-art.md +0 -0
  102. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/style/voices/yasi-salek.md +0 -0
  103. {braidio-0.0.73 → braidio-0.0.74}/misc/docs/youtube_ingest_credentials.md +0 -0
  104. {braidio-0.0.73 → braidio-0.0.74}/tests/_audio.py +0 -0
  105. {braidio-0.0.73 → braidio-0.0.74}/tests/test_body_schema_stability.py +0 -0
  106. {braidio-0.0.73 → braidio-0.0.74}/tests/test_conversation.py +0 -0
  107. {braidio-0.0.73 → braidio-0.0.74}/tests/test_cost.py +0 -0
  108. {braidio-0.0.73 → braidio-0.0.74}/tests/test_credits_card.py +0 -0
  109. {braidio-0.0.73 → braidio-0.0.74}/tests/test_defaults.py +0 -0
  110. {braidio-0.0.73 → braidio-0.0.74}/tests/test_delivery.py +0 -0
  111. {braidio-0.0.73 → braidio-0.0.74}/tests/test_downloads.py +0 -0
  112. {braidio-0.0.73 → braidio-0.0.74}/tests/test_expressiveness.py +0 -0
  113. {braidio-0.0.73 → braidio-0.0.74}/tests/test_formats.py +0 -0
  114. {braidio-0.0.73 → braidio-0.0.74}/tests/test_genre_placement.py +0 -0
  115. {braidio-0.0.73 → braidio-0.0.74}/tests/test_importing.py +0 -0
  116. {braidio-0.0.73 → braidio-0.0.74}/tests/test_mcp_caller_key.py +0 -0
  117. {braidio-0.0.73 → braidio-0.0.74}/tests/test_media_auth.py +0 -0
  118. {braidio-0.0.73 → braidio-0.0.74}/tests/test_multivoice.py +0 -0
  119. {braidio-0.0.73 → braidio-0.0.74}/tests/test_music.py +0 -0
  120. {braidio-0.0.73 → braidio-0.0.74}/tests/test_namespaced_source.py +0 -0
  121. {braidio-0.0.73 → braidio-0.0.74}/tests/test_nw_app.py +0 -0
  122. {braidio-0.0.73 → braidio-0.0.74}/tests/test_pacing.py +0 -0
  123. {braidio-0.0.73 → braidio-0.0.74}/tests/test_packaging.py +0 -0
  124. {braidio-0.0.73 → braidio-0.0.74}/tests/test_render_settings.py +0 -0
  125. {braidio-0.0.73 → braidio-0.0.74}/tests/test_script.py +0 -0
  126. {braidio-0.0.73 → braidio-0.0.74}/tests/test_sources.py +0 -0
  127. {braidio-0.0.73 → braidio-0.0.74}/tests/test_structure.py +0 -0
  128. {braidio-0.0.73 → braidio-0.0.74}/tests/test_textprep_style.py +0 -0
  129. {braidio-0.0.73 → braidio-0.0.74}/tests/test_timeline.py +0 -0
  130. {braidio-0.0.73 → braidio-0.0.74}/tests/test_transforms.py +0 -0
  131. {braidio-0.0.73 → braidio-0.0.74}/tests/test_transforms_dialogue.py +0 -0
  132. {braidio-0.0.73 → braidio-0.0.74}/tests/test_transforms_episode_members.py +0 -0
  133. {braidio-0.0.73 → braidio-0.0.74}/tests/test_transforms_rights.py +0 -0
  134. {braidio-0.0.73 → braidio-0.0.74}/tests/test_transforms_secrets.py +0 -0
  135. {braidio-0.0.73 → braidio-0.0.74}/tests/test_transforms_structure.py +0 -0
  136. {braidio-0.0.73 → braidio-0.0.74}/tests/test_tts_api_key.py +0 -0
  137. {braidio-0.0.73 → braidio-0.0.74}/tests/test_video.py +0 -0
  138. {braidio-0.0.73 → braidio-0.0.74}/tests/test_video_bodies.py +0 -0
  139. {braidio-0.0.73 → braidio-0.0.74}/tests/test_video_footage.py +0 -0
  140. {braidio-0.0.73 → braidio-0.0.74}/tests/test_video_transforms.py +0 -0
  141. {braidio-0.0.73 → braidio-0.0.74}/tests/test_voice_library.py +0 -0
  142. {braidio-0.0.73 → braidio-0.0.74}/tests/test_weave.py +0 -0
  143. {braidio-0.0.73 → braidio-0.0.74}/tests/test_weave_config.py +0 -0
  144. {braidio-0.0.73 → braidio-0.0.74}/tests/test_wire_descriptions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: braidio
3
- Version: 0.0.73
3
+ Version: 0.0.74
4
4
  Summary: Weave narration with extracted media segments into audiovisual productions
5
5
  Project-URL: Homepage, https://github.com/thorwhalen/braidio
6
6
  Project-URL: Repository, https://github.com/thorwhalen/braidio
@@ -42,12 +42,17 @@ Requires-Dist: falaw; extra == 'importing'
42
42
  Requires-Dist: illustration>=0.0.11; extra == 'importing'
43
43
  Requires-Dist: lacing; extra == 'importing'
44
44
  Requires-Dist: nw>=0.0.65; extra == 'importing'
45
+ Provides-Extra: markdown
46
+ Requires-Dist: markdown-it-py; extra == 'markdown'
47
+ Requires-Dist: mdit-py-plugins; extra == 'markdown'
45
48
  Provides-Extra: mcp
46
49
  Requires-Dist: dol>=0.3.57; extra == 'mcp'
47
50
  Requires-Dist: falaw[fal]; extra == 'mcp'
48
51
  Requires-Dist: fastmcp; extra == 'mcp'
49
52
  Requires-Dist: graze>=0.1.45; extra == 'mcp'
50
53
  Requires-Dist: lacing; extra == 'mcp'
54
+ Requires-Dist: markdown-it-py; extra == 'mcp'
55
+ Requires-Dist: mdit-py-plugins; extra == 'mcp'
51
56
  Requires-Dist: nw>=0.0.65; extra == 'mcp'
52
57
  Requires-Dist: py2mcp>=0.1.9; extra == 'mcp'
53
58
  Requires-Dist: pypdf; extra == 'mcp'
@@ -189,6 +189,13 @@ from braidio.captions import ( # noqa: F401
189
189
  format_srt,
190
190
  )
191
191
 
192
+ # --- markdown document -> narration beats (read-aloud) ---
193
+ from braidio.markdown_script import ( # noqa: F401
194
+ TagMismatch,
195
+ script_from_markdown,
196
+ untagged_differences,
197
+ )
198
+
192
199
  # --- text prep + style audit (reusable script helpers) ---
193
200
  from braidio.textprep import clean_ocr, strip_speaker_labels # noqa: F401
194
201
  from braidio.style import ( # noqa: F401
@@ -282,6 +289,10 @@ __all__ = [
282
289
  "HAS_NW",
283
290
  "HAS_VIDEO",
284
291
  "skills_dir",
292
+ # markdown read-aloud
293
+ "TagMismatch",
294
+ "script_from_markdown",
295
+ "untagged_differences",
285
296
  # captions
286
297
  "Cue",
287
298
  "captions_for",
@@ -41,7 +41,8 @@ spending if any of it is unclear.
41
41
  ```
42
42
  1. create_project("my-episode") # free
43
43
  2. ingest_document("my-episode", uri="https://…") # free — returns the text to analyze
44
- # (or text="…" for pasted content)
44
+ # (or text="…" for pasted content; as_beats=true on markdown returns a ready
45
+ # Script of narration beats to tag — braidio.script_from_markdown in Python)
45
46
  3. … you read that text and author a Script (see below) …
46
47
  4. estimate_cost(script) # free — always do this
47
48
  5. render_format("deep_dive", script) # [COSTED] → an mp3 url in your workspace
@@ -0,0 +1,354 @@
1
+ """Markdown → narration beats, for reading a written document aloud.
2
+
3
+ ``ingest_document`` returns plain text and no structure; reading an essay aloud
4
+ needs the structure (a title beat, longer pauses at headings, footnotes read at the
5
+ end) and the *speakable* text (no URLs, no emphasis markers, no image syntax). This
6
+ module owns that conversion so a read-aloud is one call:
7
+
8
+ >>> script = script_from_markdown("---\\ntitle: On Pace\\n---\\n# Part one\\n\\nSee [this](http://x.y) **now**.")
9
+ >>> [(b.style, b.text) for b in script.beats]
10
+ [('title', 'On Pace.'), ('heading', 'Part one'), ('para', 'See this now.')]
11
+
12
+ Parsing is delegated to ``markdown-it-py`` (CommonMark, plus the footnote and
13
+ front-matter plugins of ``mdit-py-plugins``), an optional dependency
14
+ (``pip install 'braidio[markdown]'``) imported only when a document is converted,
15
+ so ``import braidio`` never needs it. This module only maps the token stream to
16
+ beats.
17
+
18
+ Tagging (``[pause]``, ``[dryly]``) stays the author's job: the beats are plain
19
+ text an agent can tag, and :func:`untagged_differences` verifies that tagging
20
+ changed nothing but tags. The conversion is pure — no network, no TTS, no cost.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import re
26
+ from collections import Counter
27
+ from collections.abc import Iterable, Iterator, Mapping
28
+ from dataclasses import dataclass
29
+ from types import MappingProxyType
30
+
31
+ from braidio.script import Narration, Script
32
+ from braidio.style import audio_tags, strip_audio_tags
33
+
34
+ #: Seconds of silence before each kind of beat (``Narration.lead_gap_s``). Headings
35
+ #: breathe; the title starts the file; footnotes are set apart from the body.
36
+ #: Read-only: a partial ``gaps=`` is merged over it, never mutates it.
37
+ DEFAULT_GAPS: Mapping[str, float] = MappingProxyType(
38
+ {
39
+ "title": 0.0,
40
+ "heading": 1.3,
41
+ "para": 0.35,
42
+ "list_item": 0.2,
43
+ "quote": 0.5,
44
+ "footnote": 1.0,
45
+ }
46
+ )
47
+ #: Spoken before each footnote (they are read at the end, out of their context).
48
+ DEFAULT_FOOTNOTE_LEAD_IN = "A footnote."
49
+ FOOTNOTES_MODES = ("end", "drop")
50
+ IMAGES_MODES = ("drop", "caption")
51
+ #: The pip extra that carries the parser.
52
+ MARKDOWN_EXTRA = "braidio[markdown]"
53
+
54
+ #: Block containers whose paragraphs make ONE beat (an item, a footnote), vs.
55
+ #: containers whose paragraphs each make their own beat (a quote).
56
+ _CONTAINER_KIND = {
57
+ "list_item_open": "list_item",
58
+ "blockquote_open": "quote",
59
+ "footnote_open": "footnote",
60
+ }
61
+ _CONTAINER_CLOSE = {
62
+ "list_item_close",
63
+ "blockquote_close",
64
+ "footnote_close",
65
+ }
66
+ _ACCUMULATING = frozenset({"list_item", "footnote"})
67
+ _AUTOLINK_MARKUPS = frozenset({"autolink", "linkify"})
68
+ _TASK_MARKER = re.compile(r"^\[[ xX]\]\s+")
69
+ #: A bare URL in running text (not a link, so markdown-it keeps it as text); the
70
+ #: last character excludes sentence punctuation so "see https://x.y." keeps its dot.
71
+ _BARE_URL = re.compile(r"\s*\bhttps?://\S*[^\s.,;:!?)\]'\"]")
72
+ #: An unindented ``key: value`` front-matter line (nested/indented lines are not ours).
73
+ _FRONT_MATTER_LINE = re.compile(r"^([A-Za-z_][\w-]*):[ \t]*(.*)$")
74
+ #: YAML block-scalar indicators: the value is on the following lines, not this one.
75
+ _BLOCK_SCALAR = re.compile(r"^[>|][-+0-9]*$")
76
+ _SENTENCE_END = (".", "?", "!")
77
+ _WS = re.compile(r"\s+")
78
+ _NON_SLUG = re.compile(r"[^a-z0-9]+")
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class _Block:
83
+ kind: str # "heading" | "para" | "list_item" | "quote" | "footnote"
84
+ text: str
85
+
86
+
87
+ def _markdown_parser():
88
+ """A CommonMark parser with footnotes, front matter, tables and strikethrough."""
89
+ try:
90
+ from markdown_it import MarkdownIt
91
+ from mdit_py_plugins.footnote import footnote_plugin
92
+ from mdit_py_plugins.front_matter import front_matter_plugin
93
+ except ImportError as exc:
94
+ raise ImportError(
95
+ "script_from_markdown needs markdown-it-py and mdit-py-plugins: "
96
+ f"pip install '{MARKDOWN_EXTRA}'"
97
+ ) from exc
98
+ return (
99
+ MarkdownIt("commonmark")
100
+ .use(front_matter_plugin)
101
+ .use(footnote_plugin)
102
+ .enable(["table", "strikethrough"])
103
+ )
104
+
105
+
106
+ def _front_matter(tokens) -> dict[str, str]:
107
+ """Flat top-level ``key: value`` pairs from a leading front-matter token.
108
+
109
+ Indented lines (nested mappings) and block scalars (``title: >``) are skipped:
110
+ this is not a YAML parser, so it reads only what it can read correctly.
111
+ """
112
+ fm = next((t.content for t in tokens if t.type == "front_matter"), "")
113
+ matches = filter(None, map(_FRONT_MATTER_LINE.match, fm.splitlines()))
114
+ pairs = ((m.group(1).lower(), m.group(2).strip()) for m in matches)
115
+ return {k: v.strip("\"'") for k, v in pairs if v and not _BLOCK_SCALAR.match(v)}
116
+
117
+
118
+ def _inline_text(children: Iterable, *, keep_image_alt: bool) -> str:
119
+ """The words of an inline token run: markup, URLs, HTML and refs dropped."""
120
+ parts: list[str] = []
121
+ in_autolink = False
122
+ for t in children or ():
123
+ if t.type in ("link_open", "link_close") and t.markup in _AUTOLINK_MARKUPS:
124
+ in_autolink = t.type == "link_open"
125
+ elif in_autolink:
126
+ continue
127
+ elif t.type in ("text", "code_inline"):
128
+ parts.append(t.content)
129
+ elif t.type in ("softbreak", "hardbreak"):
130
+ parts.append(" ")
131
+ elif t.type == "image" and keep_image_alt:
132
+ parts.append(" " + _inline_text(t.children, keep_image_alt=True) + " ")
133
+ return _WS.sub(" ", _BARE_URL.sub("", "".join(parts))).strip()
134
+
135
+
136
+ def _blocks(tokens, *, keep_image_alt: bool) -> Iterator[_Block]:
137
+ """Map the block token stream to beats-to-be, in document order.
138
+
139
+ A paragraph is a ``para``, or takes the kind of its innermost container: every
140
+ paragraph of a list item joins into one block; each paragraph of a quote is
141
+ its own. Anything inside a footnote (lists and quotes included) joins that
142
+ footnote, so it never leaks into the body. Tables, code, rules and HTML
143
+ blocks are not read.
144
+ """
145
+ stack: list[tuple[str, list[str]]] = [] # (kind, accumulated texts)
146
+ in_heading = in_table = False
147
+
148
+ def footnote_frame():
149
+ return next((f for f in stack if f[0] == "footnote"), None)
150
+
151
+ def flush_top(*, closing: bool = False) -> Iterator[_Block]:
152
+ # A footnote is one block: only its own close flushes it.
153
+ if stack and stack[-1][0] == "footnote" and not closing:
154
+ return
155
+ if stack and stack[-1][1]:
156
+ kind, parts = stack[-1]
157
+ text = " ".join(parts)
158
+ parts.clear()
159
+ if kind == "list_item":
160
+ text = _TASK_MARKER.sub("", text)
161
+ yield _Block(kind, text)
162
+
163
+ for t in tokens:
164
+ if t.type in _CONTAINER_KIND:
165
+ yield from flush_top()
166
+ stack.append((_CONTAINER_KIND[t.type], []))
167
+ elif t.type in _CONTAINER_CLOSE:
168
+ yield from flush_top(closing=True)
169
+ stack.pop()
170
+ elif t.type in ("table_open", "table_close"):
171
+ in_table = t.type == "table_open"
172
+ elif t.type in ("heading_open", "heading_close"):
173
+ in_heading = t.type == "heading_open"
174
+ elif t.type == "inline" and not in_table:
175
+ text = _inline_text(t.children, keep_image_alt=keep_image_alt)
176
+ if not text:
177
+ continue
178
+ if (note := footnote_frame()) is not None:
179
+ note[1].append(text)
180
+ continue
181
+ kind = "heading" if in_heading else (stack[-1][0] if stack else "para")
182
+ if kind in _ACCUMULATING:
183
+ stack[-1][1].append(text)
184
+ else:
185
+ yield from flush_top()
186
+ yield _Block(kind, text)
187
+
188
+
189
+ def _respeller(respell: Mapping[str, str] | None):
190
+ """A function applying ``respell`` in one pass, longest key first.
191
+
192
+ One pass (a regex alternation), so a replacement is never itself re-matched by
193
+ a shorter key (``AGENTS.md`` → ``AGENTS dot M D`` must not then hit ``AGENTS``).
194
+ A key that starts (ends) with a word character only matches at a word boundary
195
+ there, so ``{"AI": "A I"}`` leaves ``SAID`` alone.
196
+ """
197
+ if not respell:
198
+ return lambda text: text
199
+
200
+ def bounded(key: str) -> str:
201
+ head = r"\b" if re.match(r"\w", key[:1]) else ""
202
+ tail = r"\b" if re.match(r"\w", key[-1:]) else ""
203
+ return head + re.escape(key) + tail
204
+
205
+ keys = sorted(respell, key=len, reverse=True)
206
+ pattern = re.compile("|".join(bounded(k) for k in keys))
207
+ return lambda text: pattern.sub(lambda m: respell[m.group(0)], text)
208
+
209
+
210
+ def _slug(text: str) -> str:
211
+ return _NON_SLUG.sub("-", text.lower()).strip("-") or "document"
212
+
213
+
214
+ def _check_modes(footnotes: str, images: str) -> None:
215
+ if footnotes not in FOOTNOTES_MODES:
216
+ raise ValueError(
217
+ f"footnotes must be one of {FOOTNOTES_MODES}, got {footnotes!r}"
218
+ )
219
+ if images not in IMAGES_MODES:
220
+ raise ValueError(f"images must be one of {IMAGES_MODES}, got {images!r}")
221
+
222
+
223
+ def _title_entry(meta: Mapping[str, str]) -> list[tuple[str, str]]:
224
+ """The spoken title beat (``title. subtitle.``), if front matter has a title."""
225
+ if not meta.get("title"):
226
+ return []
227
+
228
+ def terminated(text: str) -> str:
229
+ return text if text.endswith(_SENTENCE_END) else text + "."
230
+
231
+ parts = (meta["title"], meta.get("subtitle"))
232
+ return [("title", " ".join(terminated(p) for p in parts if p))]
233
+
234
+
235
+ def script_from_markdown(
236
+ md: str,
237
+ *,
238
+ voice: str | None = None,
239
+ title: str | None = None,
240
+ id_slug: str | None = None,
241
+ gaps: Mapping[str, float] = DEFAULT_GAPS,
242
+ respell: Mapping[str, str] | None = None,
243
+ footnotes: str = "end",
244
+ footnote_lead_in: str = DEFAULT_FOOTNOTE_LEAD_IN,
245
+ images: str = "drop",
246
+ ) -> Script:
247
+ """Turn a markdown document into a :class:`Script` of narration beats.
248
+
249
+ One beat per paragraph, heading, list item or quote paragraph.
250
+ ``Narration.style`` carries the kind (``title``/``heading``/``para``/
251
+ ``list_item``/``quote``/``footnote``), so the timeline reports headings and
252
+ footnotes separately, and ``lead_gap_s`` comes from ``gaps[kind]`` (a partial
253
+ ``gaps`` is merged over :data:`DEFAULT_GAPS`).
254
+
255
+ - Front matter ``title``/``subtitle`` become a title beat (``title=`` and the
256
+ first heading, as plain text, are the fallbacks for the script's name).
257
+ - ``images``: ``"drop"`` (default) or ``"caption"`` (read the alt text inline).
258
+ - ``footnotes``: ``"end"`` (default; each read after the body, in reference
259
+ order, behind ``footnote_lead_in``) or ``"drop"``. Markers are always removed.
260
+ - ``respell`` maps text as written to text as spoken (``{"BDUF": "B-DUF"}``),
261
+ applied to the beats only; the source markdown is untouched.
262
+ - Links keep their text; URLs are never read (autolinks and bare URLs are
263
+ dropped); emphasis and code markers are stripped; HTML, code blocks, tables
264
+ and rules are not read; entities are decoded.
265
+
266
+ Needs ``markdown-it-py`` + ``mdit-py-plugins`` (``braidio[markdown]``).
267
+ """
268
+ _check_modes(footnotes, images)
269
+ gap_of = {**DEFAULT_GAPS, **gaps}
270
+ tokens = _markdown_parser().parse(md.replace("\r\n", "\n").replace("\r", "\n"))
271
+ meta = _front_matter(tokens)
272
+ blocks = list(_blocks(tokens, keep_image_alt=images == "caption"))
273
+ first_heading = next((b.text for b in blocks if b.kind == "heading"), None)
274
+ name = title or meta.get("title") or first_heading or "Untitled"
275
+ entries = _title_entry(meta)
276
+ entries += [(b.kind, b.text) for b in blocks if b.kind != "footnote"]
277
+ if footnotes == "end":
278
+ entries += [
279
+ ("footnote", f"{footnote_lead_in} {b.text}")
280
+ for b in blocks
281
+ if b.kind == "footnote"
282
+ ]
283
+ respelled = _respeller(respell)
284
+ beats = [
285
+ Narration(respelled(text), voice=voice, lead_gap_s=gap_of[kind], style=kind)
286
+ for kind, text in entries
287
+ ]
288
+ return Script(title=name, id_slug=id_slug or _slug(name), beats=beats)
289
+
290
+
291
+ @dataclass(frozen=True)
292
+ class TagMismatch:
293
+ """A beat whose text changed by more than audio tags.
294
+
295
+ ``index`` is the narration beat's position; ``-1`` means the non-narration
296
+ beats (segments, dialogue, scene breaks) differ, with their counts as
297
+ ``before``/``after``.
298
+ """
299
+
300
+ index: int
301
+ before: str
302
+ after: str
303
+
304
+
305
+ def _narration_texts(script: Script) -> list[str]:
306
+ return [b.text for b in script.beats if isinstance(b, Narration)]
307
+
308
+
309
+ def _tag_only_change(old: str, new: str) -> bool:
310
+ """``new`` is ``old`` plus tags: same words, and no bracket token of ``old`` lost.
311
+
312
+ Without the second clause, a bracketed word already in the source
313
+ (``[note]``) would be stripped from both sides and its deletion missed.
314
+ """
315
+ lost = Counter(audio_tags(old)) - Counter(audio_tags(new))
316
+
317
+ def plain(text: str) -> str:
318
+ return _WS.sub(" ", strip_audio_tags(text)).strip()
319
+
320
+ return not lost and plain(old) == plain(new)
321
+
322
+
323
+ def untagged_differences(before: Script, after: Script) -> list[TagMismatch]:
324
+ """Where ``after`` differs from ``before`` by more than ``[audio tags]``.
325
+
326
+ Compares narration beat by beat (whitespace-insensitive, added tags ignored;
327
+ a bracket token already in ``before`` must survive). A different narration
328
+ count is reported as one mismatch at the first unmatched index; a different
329
+ count of non-narration beats as one mismatch at index ``-1``. Empty list ⇒
330
+ tagging changed nothing but tags.
331
+
332
+ >>> a = Script("t", "t", [Narration("Hello there.")])
333
+ >>> b = Script("t", "t", [Narration("[warmly] Hello there.")])
334
+ >>> untagged_differences(a, b)
335
+ []
336
+ """
337
+ old, new = _narration_texts(before), _narration_texts(after)
338
+ mismatches = [
339
+ TagMismatch(i, o, n)
340
+ for i, (o, n) in enumerate(zip(old, new))
341
+ if not _tag_only_change(o, n)
342
+ ]
343
+ if len(old) != len(new):
344
+ i = min(len(old), len(new))
345
+ mismatches.append(
346
+ TagMismatch(
347
+ i, old[i] if i < len(old) else "", new[i] if i < len(new) else ""
348
+ )
349
+ )
350
+ n_old = len(before.beats) - len(old)
351
+ n_new = len(after.beats) - len(new)
352
+ if n_old != n_new:
353
+ mismatches.append(TagMismatch(-1, str(n_old), str(n_new)))
354
+ return mismatches
@@ -90,6 +90,20 @@ def script_from_json(payload: Mapping[str, Any]):
90
90
  return Script(title=payload["title"], id_slug=payload["id_slug"], beats=beats)
91
91
 
92
92
 
93
+ def script_to_json(script) -> dict:
94
+ """The inverse of :func:`script_from_json`: a Script as its JSON envelope."""
95
+ from braidio import Dialogue, Narration, SceneBreak, SegmentBeat
96
+
97
+ types = {
98
+ Narration: "narration",
99
+ SegmentBeat: "segment",
100
+ Dialogue: "dialogue",
101
+ SceneBreak: "scene_break",
102
+ }
103
+ beats = [{"type": types[type(b)], **to_json(b)} for b in script.beats]
104
+ return {"title": script.title, "id_slug": script.id_slug, "beats": beats}
105
+
106
+
93
107
  def source_from_json(payload: Optional[Mapping[str, Any]]):
94
108
  """Build a :class:`braidio.TimedLineSegmentSource` from JSON, or ``None``.
95
109
 
@@ -22,7 +22,12 @@ import os
22
22
  import braidio # attr access (braidio.narrate, ...) so tests can monkeypatch
23
23
  from fastmcp.exceptions import ToolError
24
24
 
25
- from braidio.mcp._helpers import script_from_json, source_from_json, to_json
25
+ from braidio.mcp._helpers import (
26
+ script_from_json,
27
+ script_to_json,
28
+ source_from_json,
29
+ to_json,
30
+ )
26
31
  from braidio.rights import DEFAULT_PROFILE
27
32
  from braidio.mcp.credentials import caller_elevenlabs_key
28
33
  from braidio.mcp.metering import current_email
@@ -337,20 +342,47 @@ def project_status(project_id: str) -> dict:
337
342
  return {"project_id": project_id, "episodes": episodes}
338
343
 
339
344
 
345
+ #: Content types whose extracted text has lost its markdown structure, so
346
+ #: ``as_beats`` would read flattened prose as one paragraph per line.
347
+ _NOT_MARKDOWN_TYPES = ("pdf", "html", "xml")
348
+
349
+
350
+ def _markdown_beats(full: str, ctype: str, *, max_chars: int) -> tuple[dict, bool]:
351
+ """``full`` as a JSON script, cut to whole beats within ``max_chars``."""
352
+ if any(kind in (ctype or "").lower() for kind in _NOT_MARKDOWN_TYPES):
353
+ raise ToolError(
354
+ f"as_beats reads markdown or plain text, not {ctype!r}; "
355
+ "ingest without as_beats and author the beats from the text"
356
+ )
357
+ from dataclasses import replace
358
+
359
+ from braidio import script_from_markdown
360
+
361
+ script = script_from_markdown(full)
362
+ kept, total = [], 0
363
+ for beat in script.beats:
364
+ total += len(beat.text)
365
+ if total > max_chars:
366
+ break
367
+ kept.append(beat)
368
+ truncated = len(kept) < len(script.beats)
369
+ return script_to_json(replace(script, beats=kept)), truncated
370
+
371
+
340
372
  def ingest_document(
341
373
  project_id: str,
342
374
  uri: str | None = None,
343
375
  text: str | None = None,
344
376
  name: str | None = None,
345
377
  max_chars: int = 40000,
378
+ as_beats: bool = False,
346
379
  ) -> dict:
347
380
  """Ingest source material into a project so you can analyze it into a Script.
348
381
 
349
- Provide EITHER ``uri`` (a public http/https URL — PDF, HTML, or plain text) OR
350
- ``text`` (pasted content). The document is fetched (SSRF-guarded: public hosts
351
- only, size/time bounded), its plaintext extracted and stored in the project, and
352
- the text returned (up to ``max_chars``) for you to read and turn into narration /
353
- segment beats. Free — no synthesis.
382
+ Give ``uri`` (public http/https: PDF, HTML, text) OR ``text``. The plaintext is
383
+ stored and returned (up to ``max_chars``) to turn into beats. For a markdown
384
+ or text document to read aloud, ``as_beats=true`` returns a ready ``script`` of
385
+ narration beats instead (headings, footnotes) to tag. Free.
354
386
  """
355
387
  from braidio.mcp import _docs
356
388
 
@@ -369,6 +401,9 @@ def ingest_document(
369
401
  full = _docs.extract_text(data, ctype)
370
402
  except ValueError as exc:
371
403
  raise ToolError(str(exc)) from exc
404
+ script, truncated = None, len(full) > max_chars
405
+ if as_beats:
406
+ script, truncated = _markdown_beats(full, ctype, max_chars=max_chars)
372
407
 
373
408
  from hashlib import sha256
374
409
 
@@ -382,8 +417,8 @@ def ingest_document(
382
417
  "source": src,
383
418
  "content_type": ctype,
384
419
  "characters": len(full),
385
- "truncated": len(full) > max_chars,
386
- "text": full[:max_chars],
420
+ "truncated": truncated,
421
+ **({"script": script} if script else {"text": full[:max_chars]}),
387
422
  }
388
423
 
389
424
 
@@ -85,6 +85,11 @@ TAG_RATE_FLOOR = 1.5
85
85
  TAG_RATE_CEILING = 6.0
86
86
 
87
87
 
88
+ def strip_audio_tags(text: str) -> str:
89
+ """``text`` with every inline ``[audio tag]`` removed (tags only; spacing kept)."""
90
+ return _AUDIO_TAG_RE.sub("", text)
91
+
92
+
88
93
  def audio_tags(text: str) -> list[str]:
89
94
  """Every inline ``[audio tag]`` in ``text``, in order."""
90
95
  return _AUDIO_TAG_RE.findall(text)
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
 
7
7
  [project]
8
8
  name = "braidio"
9
- version = "0.0.73"
9
+ version = "0.0.74"
10
10
  description = "Weave narration with extracted media segments into audiovisual productions"
11
11
  readme = "README.md"
12
12
  requires-python = ">=3.10"
@@ -72,6 +72,9 @@ docs = [
72
72
  # nw.Project). `import braidio` never needs these — the layer loads only when
73
73
  # present (braidio.HAS_GRAPH / HAS_NW).
74
74
  graph = ["lacing"]
75
+ # The markdown reader (`braidio.script_from_markdown`): a markdown document ->
76
+ # narration beats. Imported only when a document is converted.
77
+ markdown = ["markdown-it-py", "mdit-py-plugins"]
75
78
  # The video layer (`braidio.video`): a Ken Burns film over caller-supplied stills,
76
79
  # muxed under a rendered episode. `burns` owns the pan/zoom motion; braidio owns
77
80
  # only where the cuts fall, which needs the beat timeline it already produces.
@@ -136,7 +139,7 @@ nw-app = ["lacing", "nw>=0.0.65", "falaw[fal]"]
136
139
  # older dol without it.
137
140
  # nw>=0.0.58: see the nw-app note above (the `secrets=` seam, braidio#58; the
138
141
  # asset-ref declarations `braidio.transforms` makes on import, nw#55).
139
- mcp = ["fastmcp", "py2mcp>=0.1.9", "pypdf", "dol>=0.3.57", "lacing", "nw>=0.0.65", "falaw[fal]", "yb[download]>=0.1.7", "graze>=0.1.45"]
142
+ mcp = ["fastmcp", "py2mcp>=0.1.9", "pypdf", "dol>=0.3.57", "lacing", "nw>=0.0.65", "falaw[fal]", "yb[download]>=0.1.7", "graze>=0.1.45", "markdown-it-py", "mdit-py-plugins"]
140
143
  # The importer (`braidio.importing`): a finished commentary production ->
141
144
  # a real project graph. Needs the nw-app layer (it writes annotations) plus
142
145
  # `illustration` for licence normalization.