braidio 0.0.72__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.
- {braidio-0.0.72 → braidio-0.0.74}/PKG-INFO +7 -1
- {braidio-0.0.72 → braidio-0.0.74}/braidio/__init__.py +11 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/data/skills/braidio/SKILL.md +2 -1
- braidio-0.0.74/braidio/markdown_script.py +354 -0
- braidio-0.0.74/braidio/mcp/_docs.py +137 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/mcp/_helpers.py +14 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/mcp/tools.py +43 -8
- {braidio-0.0.72 → braidio-0.0.74}/braidio/style.py +5 -0
- {braidio-0.0.72 → braidio-0.0.74}/pyproject.toml +5 -2
- braidio-0.0.74/tests/test_markdown_script.py +325 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_mcp.py +120 -16
- braidio-0.0.72/braidio/mcp/_docs.py +0 -183
- {braidio-0.0.72 → braidio-0.0.74}/.editorconfig +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/.gitattributes +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/.gitignore +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/LICENSE +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/README.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/_paths.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/bodies/__init__.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/bodies/_domain.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/bodies/_render_nodes.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/bodies/_tiers.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/bodies/_video.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/captions.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/compose.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/conversation.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/cost.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/data/skills/braidio-commentary-video/SKILL.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/defaults.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/delivery.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/downloads.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/formats.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/genre.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/importing/__init__.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/importing/__main__.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/importing/_catalog.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/importing/_manifest.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/importing/_writer.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/kinds.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/mcp/__init__.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/mcp/_guide.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/mcp/_media.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/mcp/credentials.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/mcp/metering.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/mcp/workspace.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/multivoice.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/music.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/pacing.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/project.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/provenance.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/relevance.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/render.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/rights.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/script.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/sources.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/structure.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/textprep.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/timeline.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/__init__.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_asset_refs.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_common.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_dialogue.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_episode.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_ingest.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_narration.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_segment.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_video_cut.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_video_panels.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/transforms/_voice.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/tts.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/video.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/voice_library.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/weave.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/braidio/weave_config.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/conftest.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/Extraction and nw-App Design.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/research/commentary-formats-and-styles.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/research/conversational-vs-narration-tts.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/research/notebooklm-and-conversational-pacing.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/README.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/anti-platitude-checklist.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/commentary-voice-guide.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/_style-groups.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/amanda-dobbins.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/david-sims.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/griffin-newman.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/helen-molesworth.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/hrishikesh-hirway.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/jason-mantzoukas.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/john-mcwhorter.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/jon-caramanica.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/june-diane-raphael.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/karina-longworth.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/katy-hessel.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/louis-theroux.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/mallory-rubin.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/melvyn-bragg.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/michael-barbaro.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/nate-sloan-charlie-harding.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/paul-scheer.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/sean-fennessey.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/talk-art.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/style/voices/yasi-salek.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/misc/docs/youtube_ingest_credentials.md +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/_audio.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_body_schema_stability.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_conversation.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_cost.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_credits_card.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_defaults.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_delivery.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_downloads.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_expressiveness.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_formats.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_genre_placement.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_importing.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_mcp_caller_key.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_media_auth.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_multivoice.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_music.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_namespaced_source.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_nw_app.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_pacing.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_packaging.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_render_settings.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_script.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_sources.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_structure.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_textprep_style.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_timeline.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_transforms.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_transforms_dialogue.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_transforms_episode_members.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_transforms_rights.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_transforms_secrets.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_transforms_structure.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_tts_api_key.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_video.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_video_bodies.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_video_footage.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_video_transforms.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_voice_library.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_weave.py +0 -0
- {braidio-0.0.72 → braidio-0.0.74}/tests/test_weave_config.py +0 -0
- {braidio-0.0.72 → 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.
|
|
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,11 +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'
|
|
52
|
+
Requires-Dist: graze>=0.1.45; extra == 'mcp'
|
|
49
53
|
Requires-Dist: lacing; extra == 'mcp'
|
|
54
|
+
Requires-Dist: markdown-it-py; extra == 'mcp'
|
|
55
|
+
Requires-Dist: mdit-py-plugins; extra == 'mcp'
|
|
50
56
|
Requires-Dist: nw>=0.0.65; extra == 'mcp'
|
|
51
57
|
Requires-Dist: py2mcp>=0.1.9; extra == 'mcp'
|
|
52
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
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""Document ingestion for the braidio MCP server: fetch a URI or accept text, then
|
|
2
|
+
extract plaintext so an agent can analyze source material into a Script.
|
|
3
|
+
|
|
4
|
+
Fetching is **SSRF-hardened** because the connector fetches user-supplied URLs
|
|
5
|
+
server-side on a shared production box. The guard is ``graze.guarded_fetch``'s (one
|
|
6
|
+
implementation for the fleet): http/https only on ports {80, 443}; every hop's
|
|
7
|
+
address is resolved once, checked as globally routable, and *pinned* — the socket
|
|
8
|
+
goes to exactly that address, so DNS rebinding cannot swap in an internal one; each
|
|
9
|
+
redirect hop is re-validated; the whole fetch is bounded by one wall-clock budget
|
|
10
|
+
and a byte cap. This module keeps only the braidio-facing contract: ``ValueError``
|
|
11
|
+
for every refusal (what the tools turn into a ``ToolError``) and a content type.
|
|
12
|
+
|
|
13
|
+
Extraction is content-type aware: HTML is stripped to text, PDF uses ``pypdf``
|
|
14
|
+
(page-capped), everything else is decoded as UTF-8.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import io
|
|
20
|
+
import ipaddress
|
|
21
|
+
import urllib.parse
|
|
22
|
+
from html.parser import HTMLParser
|
|
23
|
+
|
|
24
|
+
import graze
|
|
25
|
+
|
|
26
|
+
#: Fetch bounds (whole fetch, all hops).
|
|
27
|
+
MAX_BYTES = 10 * 1024 * 1024
|
|
28
|
+
MAX_REDIRECTS = 5
|
|
29
|
+
TOTAL_TIMEOUT_S = 25.0 # wall-clock budget for the whole fetch
|
|
30
|
+
ALLOWED_SCHEMES = ("http", "https")
|
|
31
|
+
ALLOWED_PORTS = frozenset({80, 443})
|
|
32
|
+
PDF_MAX_PAGES = 300
|
|
33
|
+
|
|
34
|
+
#: Identifies braidio to the origin server. Kept honest (no browser spoofing) so
|
|
35
|
+
#: operators can see, and rate-limit, what is fetching their documents.
|
|
36
|
+
USER_AGENT = "braidio-mcp/1.0"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _TextHTMLParser(HTMLParser):
|
|
40
|
+
"""Collect visible text from HTML, skipping <script>/<style>."""
|
|
41
|
+
|
|
42
|
+
def __init__(self):
|
|
43
|
+
super().__init__()
|
|
44
|
+
self._chunks: list[str] = []
|
|
45
|
+
self._skip = 0
|
|
46
|
+
|
|
47
|
+
def handle_starttag(self, tag, attrs):
|
|
48
|
+
if tag in ("script", "style"):
|
|
49
|
+
self._skip += 1
|
|
50
|
+
|
|
51
|
+
def handle_endtag(self, tag):
|
|
52
|
+
if tag in ("script", "style") and self._skip:
|
|
53
|
+
self._skip -= 1
|
|
54
|
+
|
|
55
|
+
def handle_data(self, data):
|
|
56
|
+
if not self._skip and data.strip():
|
|
57
|
+
self._chunks.append(data)
|
|
58
|
+
|
|
59
|
+
def text(self) -> str:
|
|
60
|
+
return " ".join(" ".join(self._chunks).split())
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _host_is_public(host: str, port: int) -> bool:
|
|
64
|
+
"""True only if every address ``host`` resolves to passes graze's public-only policy."""
|
|
65
|
+
try:
|
|
66
|
+
addresses = graze.system_resolver(host, port)
|
|
67
|
+
except OSError:
|
|
68
|
+
return False
|
|
69
|
+
return bool(addresses) and all(
|
|
70
|
+
graze.default_public_only(ipaddress.ip_address(a)) for a in addresses
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _validate_target(uri: str) -> None:
|
|
75
|
+
"""Reject a URI whose scheme/host/port isn't a public http(s) endpoint.
|
|
76
|
+
|
|
77
|
+
A pre-flight for callers that hand the URL to something else to fetch
|
|
78
|
+
(``download_audio`` -> yt-dlp); it cannot pin the address, ``fetch_uri`` can.
|
|
79
|
+
"""
|
|
80
|
+
parts = urllib.parse.urlparse(uri)
|
|
81
|
+
if parts.scheme not in ALLOWED_SCHEMES:
|
|
82
|
+
raise ValueError(f"only http/https URIs are supported, got {parts.scheme!r}")
|
|
83
|
+
port = parts.port or (443 if parts.scheme == "https" else 80)
|
|
84
|
+
if port not in ALLOWED_PORTS:
|
|
85
|
+
raise ValueError(f"port {port} is not allowed (only 80/443)")
|
|
86
|
+
if not parts.hostname or not _host_is_public(parts.hostname, port):
|
|
87
|
+
raise ValueError(f"refusing to fetch a non-public host: {parts.hostname!r}")
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def fetch_uri(uri: str, **fetch_options) -> tuple[bytes, str]:
|
|
91
|
+
"""Fetch a public http(s) URI (SSRF-hardened). Returns ``(bytes, content_type)``.
|
|
92
|
+
|
|
93
|
+
``fetch_options`` go to ``graze.guarded_open`` (``resolver``, ``connector``,
|
|
94
|
+
``is_allowed_address``, ...), overriding braidio's bounds; they are the test seam.
|
|
95
|
+
"""
|
|
96
|
+
options = dict(
|
|
97
|
+
allow_schemes=ALLOWED_SCHEMES,
|
|
98
|
+
allow_ports=ALLOWED_PORTS,
|
|
99
|
+
max_redirects=MAX_REDIRECTS,
|
|
100
|
+
timeout=TOTAL_TIMEOUT_S,
|
|
101
|
+
max_bytes=MAX_BYTES,
|
|
102
|
+
headers={"User-Agent": USER_AGENT},
|
|
103
|
+
)
|
|
104
|
+
try:
|
|
105
|
+
with graze.guarded_open(uri, **{**options, **fetch_options}) as resp:
|
|
106
|
+
ctype = (resp.headers.get("Content-Type") or "").split(";")[0].strip()
|
|
107
|
+
data = resp.read()
|
|
108
|
+
except graze.UnsafeTarget as err:
|
|
109
|
+
raise ValueError(str(err)) from err
|
|
110
|
+
except graze.HTTPStatusError as err:
|
|
111
|
+
raise ValueError(f"fetch failed: HTTP {err.status}") from err
|
|
112
|
+
except graze.GuardedFetchError as err:
|
|
113
|
+
raise ValueError(f"fetch failed: {err}") from err
|
|
114
|
+
return data, ctype.lower() or "application/octet-stream"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _pdf_text(data: bytes) -> str:
|
|
118
|
+
try:
|
|
119
|
+
from pypdf import PdfReader
|
|
120
|
+
except ImportError as exc: # pragma: no cover - optional dep
|
|
121
|
+
raise ValueError("PDF ingestion needs pypdf (pip install pypdf)") from exc
|
|
122
|
+
reader = PdfReader(io.BytesIO(data))
|
|
123
|
+
pages = list(reader.pages)[:PDF_MAX_PAGES] # cap work on an adversarial PDF
|
|
124
|
+
return "\n\n".join((page.extract_text() or "") for page in pages).strip()
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def extract_text(data: bytes, content_type: str) -> str:
|
|
128
|
+
"""Extract plaintext from ``data`` given its ``content_type``."""
|
|
129
|
+
ct = (content_type or "").lower()
|
|
130
|
+
if "pdf" in ct:
|
|
131
|
+
return _pdf_text(data)
|
|
132
|
+
text = data.decode("utf-8", "replace")
|
|
133
|
+
if "html" in ct or "xml" in ct:
|
|
134
|
+
parser = _TextHTMLParser()
|
|
135
|
+
parser.feed(text)
|
|
136
|
+
return parser.text()
|
|
137
|
+
return text
|
|
@@ -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
|
|
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
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
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":
|
|
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)
|