braidio 0.0.71__tar.gz → 0.0.73__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 (143) hide show
  1. {braidio-0.0.71 → braidio-0.0.73}/PKG-INFO +2 -1
  2. braidio-0.0.73/braidio/mcp/_docs.py +137 -0
  3. braidio-0.0.73/braidio/voice_library.py +256 -0
  4. {braidio-0.0.71 → braidio-0.0.73}/pyproject.toml +2 -2
  5. {braidio-0.0.71 → braidio-0.0.73}/tests/test_mcp.py +67 -16
  6. braidio-0.0.73/tests/test_voice_library.py +110 -0
  7. braidio-0.0.71/braidio/mcp/_docs.py +0 -183
  8. {braidio-0.0.71 → braidio-0.0.73}/.editorconfig +0 -0
  9. {braidio-0.0.71 → braidio-0.0.73}/.gitattributes +0 -0
  10. {braidio-0.0.71 → braidio-0.0.73}/.gitignore +0 -0
  11. {braidio-0.0.71 → braidio-0.0.73}/LICENSE +0 -0
  12. {braidio-0.0.71 → braidio-0.0.73}/README.md +0 -0
  13. {braidio-0.0.71 → braidio-0.0.73}/braidio/__init__.py +0 -0
  14. {braidio-0.0.71 → braidio-0.0.73}/braidio/_paths.py +0 -0
  15. {braidio-0.0.71 → braidio-0.0.73}/braidio/bodies/__init__.py +0 -0
  16. {braidio-0.0.71 → braidio-0.0.73}/braidio/bodies/_domain.py +0 -0
  17. {braidio-0.0.71 → braidio-0.0.73}/braidio/bodies/_render_nodes.py +0 -0
  18. {braidio-0.0.71 → braidio-0.0.73}/braidio/bodies/_tiers.py +0 -0
  19. {braidio-0.0.71 → braidio-0.0.73}/braidio/bodies/_video.py +0 -0
  20. {braidio-0.0.71 → braidio-0.0.73}/braidio/captions.py +0 -0
  21. {braidio-0.0.71 → braidio-0.0.73}/braidio/compose.py +0 -0
  22. {braidio-0.0.71 → braidio-0.0.73}/braidio/conversation.py +0 -0
  23. {braidio-0.0.71 → braidio-0.0.73}/braidio/cost.py +0 -0
  24. {braidio-0.0.71 → braidio-0.0.73}/braidio/data/skills/braidio/SKILL.md +0 -0
  25. {braidio-0.0.71 → braidio-0.0.73}/braidio/data/skills/braidio-commentary-video/SKILL.md +0 -0
  26. {braidio-0.0.71 → braidio-0.0.73}/braidio/defaults.py +0 -0
  27. {braidio-0.0.71 → braidio-0.0.73}/braidio/delivery.py +0 -0
  28. {braidio-0.0.71 → braidio-0.0.73}/braidio/downloads.py +0 -0
  29. {braidio-0.0.71 → braidio-0.0.73}/braidio/formats.py +0 -0
  30. {braidio-0.0.71 → braidio-0.0.73}/braidio/genre.py +0 -0
  31. {braidio-0.0.71 → braidio-0.0.73}/braidio/importing/__init__.py +0 -0
  32. {braidio-0.0.71 → braidio-0.0.73}/braidio/importing/__main__.py +0 -0
  33. {braidio-0.0.71 → braidio-0.0.73}/braidio/importing/_catalog.py +0 -0
  34. {braidio-0.0.71 → braidio-0.0.73}/braidio/importing/_manifest.py +0 -0
  35. {braidio-0.0.71 → braidio-0.0.73}/braidio/importing/_writer.py +0 -0
  36. {braidio-0.0.71 → braidio-0.0.73}/braidio/kinds.py +0 -0
  37. {braidio-0.0.71 → braidio-0.0.73}/braidio/mcp/__init__.py +0 -0
  38. {braidio-0.0.71 → braidio-0.0.73}/braidio/mcp/_guide.py +0 -0
  39. {braidio-0.0.71 → braidio-0.0.73}/braidio/mcp/_helpers.py +0 -0
  40. {braidio-0.0.71 → braidio-0.0.73}/braidio/mcp/_media.py +0 -0
  41. {braidio-0.0.71 → braidio-0.0.73}/braidio/mcp/credentials.py +0 -0
  42. {braidio-0.0.71 → braidio-0.0.73}/braidio/mcp/metering.py +0 -0
  43. {braidio-0.0.71 → braidio-0.0.73}/braidio/mcp/tools.py +0 -0
  44. {braidio-0.0.71 → braidio-0.0.73}/braidio/mcp/workspace.py +0 -0
  45. {braidio-0.0.71 → braidio-0.0.73}/braidio/multivoice.py +0 -0
  46. {braidio-0.0.71 → braidio-0.0.73}/braidio/music.py +0 -0
  47. {braidio-0.0.71 → braidio-0.0.73}/braidio/pacing.py +0 -0
  48. {braidio-0.0.71 → braidio-0.0.73}/braidio/project.py +0 -0
  49. {braidio-0.0.71 → braidio-0.0.73}/braidio/provenance.py +0 -0
  50. {braidio-0.0.71 → braidio-0.0.73}/braidio/relevance.py +0 -0
  51. {braidio-0.0.71 → braidio-0.0.73}/braidio/render.py +0 -0
  52. {braidio-0.0.71 → braidio-0.0.73}/braidio/rights.py +0 -0
  53. {braidio-0.0.71 → braidio-0.0.73}/braidio/script.py +0 -0
  54. {braidio-0.0.71 → braidio-0.0.73}/braidio/sources.py +0 -0
  55. {braidio-0.0.71 → braidio-0.0.73}/braidio/structure.py +0 -0
  56. {braidio-0.0.71 → braidio-0.0.73}/braidio/style.py +0 -0
  57. {braidio-0.0.71 → braidio-0.0.73}/braidio/textprep.py +0 -0
  58. {braidio-0.0.71 → braidio-0.0.73}/braidio/timeline.py +0 -0
  59. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/__init__.py +0 -0
  60. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_asset_refs.py +0 -0
  61. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_common.py +0 -0
  62. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_dialogue.py +0 -0
  63. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_episode.py +0 -0
  64. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_ingest.py +0 -0
  65. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_narration.py +0 -0
  66. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_segment.py +0 -0
  67. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_video_cut.py +0 -0
  68. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_video_panels.py +0 -0
  69. {braidio-0.0.71 → braidio-0.0.73}/braidio/transforms/_voice.py +0 -0
  70. {braidio-0.0.71 → braidio-0.0.73}/braidio/tts.py +0 -0
  71. {braidio-0.0.71 → braidio-0.0.73}/braidio/video.py +0 -0
  72. {braidio-0.0.71 → braidio-0.0.73}/braidio/weave.py +0 -0
  73. {braidio-0.0.71 → braidio-0.0.73}/braidio/weave_config.py +0 -0
  74. {braidio-0.0.71 → braidio-0.0.73}/conftest.py +0 -0
  75. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/Extraction and nw-App Design.md +0 -0
  76. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/research/commentary-formats-and-styles.md +0 -0
  77. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/research/conversational-vs-narration-tts.md +0 -0
  78. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/research/notebooklm-and-conversational-pacing.md +0 -0
  79. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/README.md +0 -0
  80. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/anti-platitude-checklist.md +0 -0
  81. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/commentary-voice-guide.md +0 -0
  82. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/_style-groups.md +0 -0
  83. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/amanda-dobbins.md +0 -0
  84. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/david-sims.md +0 -0
  85. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/griffin-newman.md +0 -0
  86. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/helen-molesworth.md +0 -0
  87. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/hrishikesh-hirway.md +0 -0
  88. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/jason-mantzoukas.md +0 -0
  89. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/john-mcwhorter.md +0 -0
  90. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/jon-caramanica.md +0 -0
  91. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/june-diane-raphael.md +0 -0
  92. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/karina-longworth.md +0 -0
  93. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/katy-hessel.md +0 -0
  94. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/louis-theroux.md +0 -0
  95. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/mallory-rubin.md +0 -0
  96. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/melvyn-bragg.md +0 -0
  97. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/michael-barbaro.md +0 -0
  98. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/nate-sloan-charlie-harding.md +0 -0
  99. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/paul-scheer.md +0 -0
  100. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/sean-fennessey.md +0 -0
  101. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/talk-art.md +0 -0
  102. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/style/voices/yasi-salek.md +0 -0
  103. {braidio-0.0.71 → braidio-0.0.73}/misc/docs/youtube_ingest_credentials.md +0 -0
  104. {braidio-0.0.71 → braidio-0.0.73}/tests/_audio.py +0 -0
  105. {braidio-0.0.71 → braidio-0.0.73}/tests/test_body_schema_stability.py +0 -0
  106. {braidio-0.0.71 → braidio-0.0.73}/tests/test_conversation.py +0 -0
  107. {braidio-0.0.71 → braidio-0.0.73}/tests/test_cost.py +0 -0
  108. {braidio-0.0.71 → braidio-0.0.73}/tests/test_credits_card.py +0 -0
  109. {braidio-0.0.71 → braidio-0.0.73}/tests/test_defaults.py +0 -0
  110. {braidio-0.0.71 → braidio-0.0.73}/tests/test_delivery.py +0 -0
  111. {braidio-0.0.71 → braidio-0.0.73}/tests/test_downloads.py +0 -0
  112. {braidio-0.0.71 → braidio-0.0.73}/tests/test_expressiveness.py +0 -0
  113. {braidio-0.0.71 → braidio-0.0.73}/tests/test_formats.py +0 -0
  114. {braidio-0.0.71 → braidio-0.0.73}/tests/test_genre_placement.py +0 -0
  115. {braidio-0.0.71 → braidio-0.0.73}/tests/test_importing.py +0 -0
  116. {braidio-0.0.71 → braidio-0.0.73}/tests/test_mcp_caller_key.py +0 -0
  117. {braidio-0.0.71 → braidio-0.0.73}/tests/test_media_auth.py +0 -0
  118. {braidio-0.0.71 → braidio-0.0.73}/tests/test_multivoice.py +0 -0
  119. {braidio-0.0.71 → braidio-0.0.73}/tests/test_music.py +0 -0
  120. {braidio-0.0.71 → braidio-0.0.73}/tests/test_namespaced_source.py +0 -0
  121. {braidio-0.0.71 → braidio-0.0.73}/tests/test_nw_app.py +0 -0
  122. {braidio-0.0.71 → braidio-0.0.73}/tests/test_pacing.py +0 -0
  123. {braidio-0.0.71 → braidio-0.0.73}/tests/test_packaging.py +0 -0
  124. {braidio-0.0.71 → braidio-0.0.73}/tests/test_render_settings.py +0 -0
  125. {braidio-0.0.71 → braidio-0.0.73}/tests/test_script.py +0 -0
  126. {braidio-0.0.71 → braidio-0.0.73}/tests/test_sources.py +0 -0
  127. {braidio-0.0.71 → braidio-0.0.73}/tests/test_structure.py +0 -0
  128. {braidio-0.0.71 → braidio-0.0.73}/tests/test_textprep_style.py +0 -0
  129. {braidio-0.0.71 → braidio-0.0.73}/tests/test_timeline.py +0 -0
  130. {braidio-0.0.71 → braidio-0.0.73}/tests/test_transforms.py +0 -0
  131. {braidio-0.0.71 → braidio-0.0.73}/tests/test_transforms_dialogue.py +0 -0
  132. {braidio-0.0.71 → braidio-0.0.73}/tests/test_transforms_episode_members.py +0 -0
  133. {braidio-0.0.71 → braidio-0.0.73}/tests/test_transforms_rights.py +0 -0
  134. {braidio-0.0.71 → braidio-0.0.73}/tests/test_transforms_secrets.py +0 -0
  135. {braidio-0.0.71 → braidio-0.0.73}/tests/test_transforms_structure.py +0 -0
  136. {braidio-0.0.71 → braidio-0.0.73}/tests/test_tts_api_key.py +0 -0
  137. {braidio-0.0.71 → braidio-0.0.73}/tests/test_video.py +0 -0
  138. {braidio-0.0.71 → braidio-0.0.73}/tests/test_video_bodies.py +0 -0
  139. {braidio-0.0.71 → braidio-0.0.73}/tests/test_video_footage.py +0 -0
  140. {braidio-0.0.71 → braidio-0.0.73}/tests/test_video_transforms.py +0 -0
  141. {braidio-0.0.71 → braidio-0.0.73}/tests/test_weave.py +0 -0
  142. {braidio-0.0.71 → braidio-0.0.73}/tests/test_weave_config.py +0 -0
  143. {braidio-0.0.71 → braidio-0.0.73}/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.71
3
+ Version: 0.0.73
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
@@ -46,6 +46,7 @@ Provides-Extra: mcp
46
46
  Requires-Dist: dol>=0.3.57; extra == 'mcp'
47
47
  Requires-Dist: falaw[fal]; extra == 'mcp'
48
48
  Requires-Dist: fastmcp; extra == 'mcp'
49
+ Requires-Dist: graze>=0.1.45; extra == 'mcp'
49
50
  Requires-Dist: lacing; extra == 'mcp'
50
51
  Requires-Dist: nw>=0.0.65; extra == 'mcp'
51
52
  Requires-Dist: py2mcp>=0.1.9; extra == 'mcp'
@@ -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
@@ -0,0 +1,256 @@
1
+ """Voice-pool sourcing and curation from the ElevenLabs shared Voice Library.
2
+
3
+ The premade pools in :mod:`braidio.multivoice` are the safe default. For a large
4
+ "many people / interviews" cast, the shared Voice Library has thousands of
5
+ voices of uneven quality, so they go through a pipeline before use:
6
+
7
+ 1. :func:`fetch_shared_voices` pages through ``GET /v1/shared-voices``;
8
+ 2. :func:`curate` keeps the ones fit for narration (use case, language,
9
+ popularity, notice period, an explicit deny list);
10
+ 3. :func:`dedup_voices` drops near-identical entries;
11
+ 4. :func:`diverse_pool` picks ``n`` voices spread across gender, accent and age,
12
+ returned as :class:`~braidio.multivoice.Voice` so ``assign_voices`` and
13
+ ``render_multivoice`` take them unchanged.
14
+
15
+ The network edge is the ``get_page`` keyword (``params -> response dict``); the
16
+ default calls the API with ``$ELEVENLABS_API_KEY``, and tests pass a fake. A
17
+ shared voice may have to be added to the account's library
18
+ (``POST /v1/voices/add/{public_owner_id}/{voice_id}``) before TTS can use it;
19
+ :class:`SharedVoice` keeps ``public_owner_id`` for that step.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import os
26
+ import random
27
+ import re
28
+ import urllib.parse
29
+ import urllib.request
30
+ from collections.abc import Callable, Iterable, Iterator
31
+ from dataclasses import dataclass, field
32
+
33
+ from braidio.multivoice import Voice
34
+
35
+ SHARED_VOICES_URL = "https://api.elevenlabs.io/v1/shared-voices"
36
+ DFLT_PAGE_SIZE = 100 # the API's maximum
37
+ NARRATION_USE_CASES = ("narrative_story", "conversational", "informative_educational")
38
+
39
+ GetPage = Callable[[dict], dict]
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class SharedVoice:
44
+ """One shared-library voice, with the fields curation needs."""
45
+
46
+ voice_id: str
47
+ name: str
48
+ public_owner_id: str = ""
49
+ gender: str = "" # "male" | "female" | "neutral" | ""
50
+ age: str = "" # "young" | "middle_aged" | "old" | ""
51
+ accent: str = ""
52
+ language: str = ""
53
+ use_case: str = ""
54
+ descriptive: str = ""
55
+ category: str = ""
56
+ cloned_by_count: int = 0
57
+ usage_character_count_1y: int = 0
58
+ notice_period: int | None = None # days before the owner may withdraw it
59
+ free_users_allowed: bool = True
60
+ preview_url: str = ""
61
+ extra: dict = field(default_factory=dict, compare=False, repr=False)
62
+
63
+ @classmethod
64
+ def from_api(cls, d: dict) -> SharedVoice:
65
+ known = {f for f in cls.__dataclass_fields__ if f != "extra"}
66
+ kw = {k: d[k] for k in known if d.get(k) is not None}
67
+ return cls(**kw, extra={k: v for k, v in d.items() if k not in known})
68
+
69
+ def to_voice(self) -> Voice:
70
+ """As a :class:`~braidio.multivoice.Voice` (gender ``M``/``F``/``N``)."""
71
+ gender = {"male": "M", "female": "F"}.get(self.gender.lower(), "N")
72
+ note = ", ".join(x for x in (self.age.replace("_", " "), self.descriptive) if x)
73
+ return Voice(self.voice_id, self.name, gender, self.accent, note)
74
+
75
+
76
+ def http_get_page(
77
+ params: dict, *, api_key: str | None = None, timeout: float = 30
78
+ ) -> dict:
79
+ """One page of ``GET /v1/shared-voices`` (the default ``get_page``)."""
80
+ key = (
81
+ api_key
82
+ or os.environ.get("ELEVENLABS_API_KEY")
83
+ or os.environ.get("ELEVEN_API_KEY")
84
+ )
85
+ if not key:
86
+ raise RuntimeError(
87
+ "Set ELEVENLABS_API_KEY to browse the shared Voice Library "
88
+ "(https://elevenlabs.io/app/settings/api-keys)."
89
+ )
90
+ params = {
91
+ k: str(v).lower() if isinstance(v, bool) else v for k, v in params.items()
92
+ }
93
+ url = f"{SHARED_VOICES_URL}?{urllib.parse.urlencode(params, doseq=True)}"
94
+ req = urllib.request.Request(url, headers={"xi-api-key": key})
95
+ with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310 - fixed https host
96
+ return json.load(r)
97
+
98
+
99
+ def fetch_shared_voices(
100
+ *,
101
+ max_voices: int = 500,
102
+ page_size: int = DFLT_PAGE_SIZE,
103
+ get_page: GetPage | None = None,
104
+ **filters,
105
+ ) -> Iterator[SharedVoice]:
106
+ """Yield shared voices, page by page, until ``max_voices`` or the end.
107
+
108
+ ``filters`` are passed as API query parameters (e.g. ``language="en"``,
109
+ ``use_cases=["narrative_story"]``, ``gender="female"``, ``sort="cloned_by_count"``).
110
+ """
111
+ get_page = get_page or http_get_page
112
+ page_size = min(page_size, max_voices)
113
+ n, page = 0, 0
114
+ while n < max_voices:
115
+ body = get_page({**filters, "page_size": page_size, "page": page})
116
+ if not body.get("voices"):
117
+ return # an empty page ends the listing whatever ``has_more`` says
118
+ for d in body["voices"]:
119
+ yield SharedVoice.from_api(d)
120
+ n += 1
121
+ if n >= max_voices:
122
+ return
123
+ if not body.get("has_more"):
124
+ return
125
+ page += 1
126
+
127
+
128
+ def curate(
129
+ voices: Iterable[SharedVoice],
130
+ *,
131
+ use_cases: Iterable[str] | None = NARRATION_USE_CASES,
132
+ languages: Iterable[str] | None = ("en",),
133
+ min_cloned_by: int = 0,
134
+ min_usage_1y: int = 0,
135
+ min_notice_days: int | None = None,
136
+ free_users_only: bool = False,
137
+ deny_ids: Iterable[str] = (),
138
+ allow_ids: Iterable[str] | None = None,
139
+ ) -> list[SharedVoice]:
140
+ """Voices fit for narration, most-used first. ``None`` disables a filter.
141
+
142
+ ``allow_ids`` (an audition allowlist) keeps only those ids; ``deny_ids``
143
+ drops voices auditioned as unfit. ``min_notice_days`` keeps only voices
144
+ their owner cannot withdraw at short notice (protects a long production); an
145
+ unknown notice period counts as 0, so it is dropped. ``languages`` match on
146
+ the code before any region (``"en-US"`` is ``"en"``).
147
+ """
148
+ use_cases = set(use_cases) if use_cases is not None else None
149
+ languages = set(languages) if languages is not None else None
150
+ deny, allow = set(deny_ids), set(allow_ids) if allow_ids is not None else None
151
+
152
+ def keep(v: SharedVoice) -> bool:
153
+ return (
154
+ (use_cases is None or v.use_case in use_cases)
155
+ and (languages is None or v.language.split("-")[0].lower() in languages)
156
+ and v.cloned_by_count >= min_cloned_by
157
+ and v.usage_character_count_1y >= min_usage_1y
158
+ and (min_notice_days is None or (v.notice_period or 0) >= min_notice_days)
159
+ and (not free_users_only or v.free_users_allowed)
160
+ and v.voice_id not in deny
161
+ and (allow is None or v.voice_id in allow)
162
+ )
163
+
164
+ kept = [v for v in voices if keep(v)]
165
+ return sorted(kept, key=lambda v: (-v.usage_character_count_1y, -v.cloned_by_count))
166
+
167
+
168
+ def _base_name(name: str) -> str:
169
+ """``"Brian - deep narrator v2"`` / ``"Brian (v2)"`` → ``"brian"``: the name before
170
+ any qualifier, with a trailing version token dropped."""
171
+ head = re.split(r"\s+[-–—|]\s+|[(:,|]", name.strip().lower(), maxsplit=1)[0]
172
+ return re.sub(r"\s+v?\d+$", "", head).strip()
173
+
174
+
175
+ def dedup_voices(
176
+ voices: Iterable[SharedVoice], *, key: Callable[[SharedVoice], tuple] | None = None
177
+ ) -> list[SharedVoice]:
178
+ """Drop near-identical voices, keeping the first of each group (order = rank).
179
+
180
+ Default key: same owner, base name, gender and accent — the shape of an
181
+ owner re-uploading one voice under variants. Pass ``key`` to tighten or
182
+ loosen (e.g. an embedding-cluster id once a quality gate exists).
183
+ """
184
+ key = key or (
185
+ lambda v: (
186
+ v.public_owner_id or v.voice_id,
187
+ _base_name(v.name),
188
+ v.gender,
189
+ v.accent,
190
+ )
191
+ )
192
+ seen, out = set(), []
193
+ for v in voices:
194
+ k = key(v)
195
+ if k not in seen:
196
+ seen.add(k)
197
+ out.append(v)
198
+ return out
199
+
200
+
201
+ def diverse_pool(
202
+ voices: Iterable[SharedVoice],
203
+ n: int,
204
+ *,
205
+ spread: tuple[str, ...] = ("gender", "accent", "age"),
206
+ seed: int | None = 0,
207
+ ) -> list[Voice]:
208
+ """``n`` voices spread as evenly as possible over the ``spread`` attributes.
209
+
210
+ Round-robins over the ``spread[0]`` groups (gender: an even M/F split
211
+ when ``n`` is even), and within each group prefers attribute values not yet
212
+ used, so the pool differs in accent and age too. Values are compared
213
+ case-insensitively; voices with no ``spread[0]`` value (or a gender other
214
+ than male/female) only fill places the main groups cannot. Input order is
215
+ the preference order (pass :func:`curate`'s ranking); ``seed`` only picks
216
+ which group goes first.
217
+ """
218
+ rng = random.Random(seed)
219
+
220
+ def val(v: SharedVoice, a: str) -> str:
221
+ return str(getattr(v, a) or "").lower()
222
+
223
+ groups: dict[str, list[SharedVoice]] = {}
224
+ fill: list[SharedVoice] = []
225
+ for v in voices:
226
+ g = val(v, spread[0]) if spread else "all"
227
+ if not g or (spread[0] == "gender" and g not in ("male", "female")):
228
+ fill.append(v)
229
+ else:
230
+ groups.setdefault(g, []).append(v)
231
+ total = sum(map(len, groups.values())) + len(fill)
232
+ if n > total:
233
+ raise ValueError(f"asked for {n} voices, only {total} curated")
234
+ order = sorted(groups)
235
+ rng.shuffle(order)
236
+ if fill:
237
+ groups["\0fill"] = fill
238
+ order.append("\0fill") # reached only once the main groups run dry
239
+ used: dict[str, set] = {a: set() for a in spread[1:]}
240
+ picked: list[SharedVoice] = []
241
+ while len(picked) < n:
242
+ live = [g for g in order if groups[g]]
243
+ main_left = any(groups[g] for g in order if g != "\0fill")
244
+ for g in live:
245
+ if len(picked) == n or (g == "\0fill" and main_left):
246
+ continue
247
+ cands = groups[g]
248
+ best = min(
249
+ range(len(cands)),
250
+ key=lambda i: (sum(val(cands[i], a) in used[a] for a in used), i),
251
+ )
252
+ v = cands.pop(best)
253
+ for a in used:
254
+ used[a].add(val(v, a))
255
+ picked.append(v)
256
+ return [v.to_voice() for v in picked]
@@ -6,7 +6,7 @@ build-backend = "hatchling.build"
6
6
 
7
7
  [project]
8
8
  name = "braidio"
9
- version = "0.0.71"
9
+ version = "0.0.73"
10
10
  description = "Weave narration with extracted media segments into audiovisual productions"
11
11
  readme = "README.md"
12
12
  requires-python = ">=3.10"
@@ -136,7 +136,7 @@ nw-app = ["lacing", "nw>=0.0.65", "falaw[fal]"]
136
136
  # older dol without it.
137
137
  # nw>=0.0.58: see the nw-app note above (the `secrets=` seam, braidio#58; the
138
138
  # 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"]
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"]
140
140
  # The importer (`braidio.importing`): a finished commentary production ->
141
141
  # a real project graph. Needs the nw-app layer (it writes annotations) plus
142
142
  # `illustration` for licence normalization.
@@ -931,33 +931,84 @@ def test_oneshot_render_resolves_asset_id(monkeypatch):
931
931
  def test_docs_rejects_disallowed_port(monkeypatch):
932
932
  from braidio.mcp import _docs
933
933
 
934
- monkeypatch.setattr(_docs, "_host_is_public", lambda h: True)
934
+ monkeypatch.setattr(_docs, "_host_is_public", lambda h, port: True)
935
935
  with pytest.raises(ValueError, match="port"):
936
936
  _docs._validate_target("http://example.com:8080/x")
937
937
  _docs._validate_target("https://example.com/x") # 443 default is fine
938
938
 
939
939
 
940
- def test_docs_redirect_to_private_is_rejected(monkeypatch):
941
- # The CRITICAL fix: a public URL that 302s to an internal host must be refused,
942
- # and the internal target must never be fetched.
943
- import urllib.error
944
- import urllib.request as ureq
940
+ def _scripted_connector(responses, hops):
941
+ """A graze ``connector`` seam: records the pinned address, serves canned HTTP."""
942
+ import socket
943
+ import threading
945
944
 
945
+ def connect(address, timeout):
946
+ hops.append(address[0])
947
+ response = responses[len(hops) - 1]
948
+ client, server = socket.socketpair()
949
+
950
+ def serve():
951
+ server.recv(65536)
952
+ server.sendall(response)
953
+ server.close()
954
+
955
+ threading.Thread(target=serve, daemon=True).start()
956
+ return client
957
+
958
+ return connect
959
+
960
+
961
+ def test_docs_redirect_to_private_is_rejected():
962
+ # A public URL that 302s to an internal host must be refused, and the internal
963
+ # target must never be connected to.
946
964
  from braidio.mcp import _docs
947
965
 
948
- monkeypatch.setattr(_docs, "_host_is_public", lambda h: h != "127.0.0.1")
949
966
  hops = []
950
-
951
- def fake_open(self, req, data=None, timeout=None):
952
- hops.append(req.full_url)
953
- raise urllib.error.HTTPError(
954
- req.full_url, 302, "redir", {"Location": "http://127.0.0.1/secret"}, None
967
+ redirect = b"HTTP/1.1 302 Found\r\nLocation: http://127.0.0.1/secret\r\n\r\n"
968
+ with pytest.raises(ValueError, match="not allowed|non-public|refus"):
969
+ _docs.fetch_uri(
970
+ "http://public.example/start",
971
+ resolver=lambda host, port: (
972
+ ["93.184.216.34"] if host == "public.example" else [host]
973
+ ),
974
+ connector=_scripted_connector([redirect], hops),
955
975
  )
976
+ assert hops == ["93.184.216.34"] # never connected to the private target
956
977
 
957
- monkeypatch.setattr(ureq.OpenerDirector, "open", fake_open)
958
- with pytest.raises(ValueError):
959
- _docs.fetch_uri("http://public.example/start")
960
- assert hops == ["http://public.example/start"] # never fetched the private target
978
+
979
+ def test_docs_fetch_pins_the_address_it_validated():
980
+ # DNS rebinding: the resolver answers public the first time, internal after.
981
+ # The connection must go to the address that was checked, with one lookup.
982
+ from braidio.mcp import _docs
983
+
984
+ lookups, hops = [], []
985
+
986
+ def rebinding_resolver(host, port):
987
+ lookups.append(host)
988
+ return ["93.184.216.34"] if len(lookups) == 1 else ["127.0.0.1"]
989
+
990
+ body = b"HTTP/1.1 200 OK\r\nContent-Type: Text/Plain; charset=utf-8\r\nContent-Length: 2\r\n\r\nhi"
991
+ data, ctype = _docs.fetch_uri(
992
+ "http://rebind.example/x",
993
+ resolver=rebinding_resolver,
994
+ connector=_scripted_connector([body], hops),
995
+ )
996
+ assert (data, ctype) == (b"hi", "text/plain")
997
+ assert hops == ["93.184.216.34"] and len(lookups) == 1
998
+
999
+
1000
+ def test_docs_fetch_enforces_the_byte_cap(monkeypatch):
1001
+ from braidio.mcp import _docs
1002
+
1003
+ monkeypatch.setattr(_docs, "MAX_BYTES", 10) # braidio's own cap must reach graze
1004
+
1005
+ body = b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n\r\n" + b"x" * 100
1006
+ with pytest.raises(ValueError, match="limit"):
1007
+ _docs.fetch_uri(
1008
+ "http://big.example/x",
1009
+ resolver=lambda host, port: ["93.184.216.34"],
1010
+ connector=_scripted_connector([body], []),
1011
+ )
961
1012
 
962
1013
 
963
1014
  @_NW
@@ -0,0 +1,110 @@
1
+ """Shared Voice Library sourcing + curation (API-free: a fake ``get_page``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import pytest
6
+
7
+ from braidio.multivoice import Voice, assign_voices
8
+ from braidio.voice_library import (
9
+ SharedVoice,
10
+ curate,
11
+ dedup_voices,
12
+ diverse_pool,
13
+ fetch_shared_voices,
14
+ http_get_page,
15
+ )
16
+
17
+
18
+ def _v(i, gender="male", accent="american", age="young", **kw):
19
+ return {"voice_id": f"v{i}", "name": f"Voice{i}", "public_owner_id": f"o{i}",
20
+ "gender": gender, "accent": accent, "age": age, "language": "en",
21
+ "use_case": "narrative_story", "cloned_by_count": 100 - i,
22
+ "usage_character_count_1y": 1000 - i, "rate": 1.0, **kw}
23
+
24
+
25
+ def _pages(items, size):
26
+ calls = []
27
+
28
+ def get_page(params):
29
+ calls.append(params)
30
+ p, s = params["page"], params["page_size"]
31
+ chunk = items[p * s: (p + 1) * s]
32
+ return {"voices": chunk, "has_more": (p + 1) * s < len(items)}
33
+
34
+ get_page.calls = calls
35
+ return get_page
36
+
37
+
38
+ def test_fetch_pages_until_end_and_caps():
39
+ get = _pages([_v(i) for i in range(5)], 2)
40
+ got = list(fetch_shared_voices(get_page=get, page_size=2, language="en"))
41
+ assert [v.voice_id for v in got] == ["v0", "v1", "v2", "v3", "v4"]
42
+ assert [c["page"] for c in get.calls] == [0, 1, 2] and get.calls[0]["language"] == "en"
43
+ assert got[0].extra == {"rate": 1.0}
44
+ assert len(list(fetch_shared_voices(get_page=_pages([_v(i) for i in range(5)], 2),
45
+ page_size=2, max_voices=3))) == 3
46
+
47
+
48
+ def test_curate_filters_and_ranks():
49
+ vs = [SharedVoice.from_api(d) for d in (
50
+ _v(1), _v(2, use_case="characters_animation"), _v(3, language="fr"),
51
+ _v(4, cloned_by_count=1), _v(5, notice_period=30), _v(0),
52
+ )]
53
+ assert [v.voice_id for v in curate(vs)] == ["v0", "v1", "v4", "v5"]
54
+ assert [v.voice_id for v in curate(vs, min_cloned_by=10, deny_ids=["v0"])] == ["v1", "v5"]
55
+ assert [v.voice_id for v in curate(vs, min_notice_days=7)] == ["v5"]
56
+ assert [v.voice_id for v in curate(vs, allow_ids=["v1"])] == ["v1"]
57
+ assert len(curate(vs, use_cases=None, languages=None)) == 6
58
+
59
+
60
+ def test_dedup_owner_variants():
61
+ a = SharedVoice.from_api({**_v(1), "name": "Brian - deep", "public_owner_id": "o"})
62
+ b = SharedVoice.from_api({**_v(2), "name": "Brian (v2)", "public_owner_id": "o"})
63
+ c = SharedVoice.from_api({**_v(3), "name": "Brian", "public_owner_id": "other"})
64
+ assert dedup_voices([a, b, c]) == [a, c]
65
+
66
+
67
+ def test_diverse_pool_balances_gender_and_accents():
68
+ vs = [SharedVoice.from_api(_v(i, gender=g, accent=acc)) for i, (g, acc) in enumerate(
69
+ [("male", "american")] * 3 + [("female", "american")] * 3
70
+ + [("male", "british"), ("female", "australian")]
71
+ )]
72
+ pool = diverse_pool(vs, 4)
73
+ assert all(isinstance(v, Voice) for v in pool)
74
+ assert sorted(v.gender for v in pool) == ["F", "F", "M", "M"]
75
+ assert {v.accent for v in pool} == {"american", "british", "australian"}
76
+ assert diverse_pool(vs, 4) == pool # seeded
77
+ assert len(assign_voices(10, pool, seed=1)) == 10 # plugs into casting
78
+ with pytest.raises(ValueError, match="only 8"):
79
+ diverse_pool(vs, 9)
80
+
81
+
82
+ def test_default_fetch_needs_key(monkeypatch):
83
+ monkeypatch.delenv("ELEVENLABS_API_KEY", raising=False)
84
+ monkeypatch.delenv("ELEVEN_API_KEY", raising=False)
85
+ with pytest.raises(RuntimeError, match="ELEVENLABS_API_KEY"):
86
+ http_get_page({})
87
+
88
+
89
+ def test_fetch_stops_on_empty_page_with_has_more():
90
+ get = lambda params: {"voices": [], "has_more": True} # noqa: E731
91
+ assert list(fetch_shared_voices(get_page=get)) == []
92
+
93
+
94
+ def test_dedup_keeps_distinct_titled_names_and_ownerless():
95
+ sv = lambda i, name, owner="o": SharedVoice.from_api( # noqa: E731
96
+ {**_v(i), "name": name, "public_owner_id": owner})
97
+ a, b = sv(1, "Dr. Smith"), sv(2, "Dr. Jones")
98
+ assert dedup_voices([a, b]) == [a, b]
99
+ c, d = sv(3, "Anna", ""), sv(4, "Anna", "")
100
+ assert dedup_voices([c, d]) == [c, d]
101
+ assert dedup_voices([sv(5, "Anna v2"), sv(6, "Anna - warm")]) == [sv(5, "Anna v2")]
102
+
103
+
104
+ def test_neutral_voices_only_fill_and_case_insensitive():
105
+ vs = [SharedVoice.from_api(_v(i, gender=g)) for i, g in enumerate(
106
+ ["Male", "male", "female", "neutral", ""])]
107
+ pool = diverse_pool(vs, 4)
108
+ assert sorted(v.gender for v in pool[:3]) == ["F", "M", "M"] and pool[3].gender == "N"
109
+ assert [v.voice_id for v in curate(
110
+ [SharedVoice.from_api(_v(1, language="en-US"))])] == ["v1"]