versereel 0.1.1__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.
@@ -0,0 +1,16 @@
1
+ name: test
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ runs-on: ubuntu-latest
6
+ strategy:
7
+ matrix:
8
+ python: ["3.10", "3.12"]
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ - uses: actions/setup-python@v5
12
+ with:
13
+ python-version: ${{ matrix.python }}
14
+ - run: sudo apt-get update && sudo apt-get install -y ffmpeg fonts-noto-core fonts-noto-extra fontconfig
15
+ - run: pip install -e ".[dev,mcp]"
16
+ - run: pytest -q
@@ -0,0 +1,6 @@
1
+ .venv/
2
+ __pycache__/
3
+ *.egg-info/
4
+ dist/
5
+ out/
6
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 versereel contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,126 @@
1
+ Metadata-Version: 2.5
2
+ Name: versereel
3
+ Version: 0.1.1
4
+ Summary: Turn poems and quotes into calm text-only vertical videos with original, royalty-free ambient music. Latin and right-to-left scripts (Urdu Nastaliq). CLI, Python API, MCP server and Claude Code skill.
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Keywords: ambient-music,mcp,nastaliq,poetry,royalty-free,shorts,urdu,video
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: numpy>=1.24
10
+ Requires-Dist: pillow>=10
11
+ Requires-Dist: soundfile>=0.12
12
+ Provides-Extra: dev
13
+ Requires-Dist: pytest>=8; extra == 'dev'
14
+ Provides-Extra: mcp
15
+ Requires-Dist: mcp>=1.2; extra == 'mcp'
16
+ Description-Content-Type: text/markdown
17
+
18
+ # versereel
19
+
20
+ Turn a poem or quote into a calm, text-only vertical video (Shorts, Reels, TikTok) with **original ambient music that is synthesised from scratch**: no stock tracks, no samples, nothing to license.
21
+
22
+ - Works with **Urdu Nastaliq** and other right-to-left scripts (Arabic, Persian, Hebrew), as well as Latin text.
23
+ - Text fades in stanza by stanza over a soft paper-and-watercolour background that drifts slowly.
24
+ - Ships as a **CLI**, a **Python API**, an **MCP server** and a **Claude Code skill**.
25
+ - Pure Python plus `ffmpeg`. No GPU, no API keys, no network (except the optional Wikisource fetch).
26
+
27
+ <p align="center"><img src="https://raw.githubusercontent.com/ali-saad-khan/versereel/main/docs/demo.gif" alt="versereel demo" width="270"></p>
28
+
29
+ Built for a calm-poetry Shorts channel, where the same code produced over a hundred videos before it was cleaned up and released.
30
+
31
+ ## Install
32
+
33
+ ```bash
34
+ pip install "versereel[mcp]" # drop [mcp] if you do not need the MCP server
35
+ ```
36
+
37
+ You also need `ffmpeg` on your PATH. Fonts are looked up on your system and are not bundled; for Urdu install *Noto Nastaliq Urdu* (Debian/Ubuntu: `sudo apt install fonts-noto-extra`).
38
+
39
+ ## Use it
40
+
41
+ ```bash
42
+ # 1. From a JSON spec
43
+ versereel render examples/dickinson-hope.json -o hope.mp4
44
+
45
+ # 2. From plain text (blank line = new stanza)
46
+ printf 'Thou hast made me endless,\nsuch is thy pleasure.\n' | versereel render --title "Gitanjali 1" \
47
+ --author "Rabindranath Tagore" --credit "Public domain" -o gitanjali.mp4
48
+
49
+ # 3. Urdu, right to left
50
+ versereel render examples/iqbal-akhtar-e-subh.json -o iqbal.mp4
51
+
52
+ # 4. Just the music
53
+ versereel bed --seconds 45 --seed my-seed -o bed.wav
54
+
55
+ # 5. Fetch public-domain text from Wikisource
56
+ versereel fetch "Poems: Second Series (Dickinson)/Hope" --author "Emily Dickinson" > hope.json
57
+ versereel render hope.json -o hope.mp4
58
+ ```
59
+
60
+ Check whether a poem fits in a Short (60 s limit) without rendering: add `--dry-run`.
61
+
62
+ ### Spec format
63
+
64
+ ```json
65
+ {
66
+ "title": "Hope",
67
+ "author": "Emily Dickinson",
68
+ "lang": "en",
69
+ "stanzas": [["line one", "line two"], ["next stanza"]],
70
+ "credit": ["Emily Dickinson (1830-1886), public domain", "Original music: versereel"]
71
+ }
72
+ ```
73
+
74
+ `lang` of `ur`, `ar`, `fa`, `he` (and similar) turns on right-to-left layout.
75
+
76
+ ### Python
77
+
78
+ ```python
79
+ from versereel import Poem, render, write_bed
80
+
81
+ render(Poem("Hope", [["Hope is the thing with feathers", "That perches in the soul,"]], author="Emily Dickinson"), "hope.mp4")
82
+ write_bed("bed.wav", seconds=40, seed="rainy-sunday")
83
+ ```
84
+
85
+ ### MCP server
86
+
87
+ ```json
88
+ { "mcpServers": { "versereel": { "command": "versereel-mcp" } } }
89
+ ```
90
+
91
+ Tools: `check_environment`, `plan_poem`, `render_poem`, `make_music_bed`, `fetch_poem`.
92
+
93
+ ### Claude Code skill
94
+
95
+ Copy `skill/versereel/` to `~/.claude/skills/versereel/`. It walks the assistant through the rights check, fitting a Short, rendering and reviewing.
96
+
97
+ ## About the music
98
+
99
+ `make_bed` builds slow pad chords (Cmaj7, Am7, Fmaj7, G6 voicings, gently detuned), sparse pentatonic bell notes and a long FFT reverb, then low-passes it. The same seed always gives the same piece and different seeds are transposed and re-timed, so a channel's videos do not all sound identical. It is deliberately calm background music, not a composition tool.
100
+
101
+ ## Rights and responsibility
102
+
103
+ versereel makes files; **you** are responsible for what you publish.
104
+
105
+ - Use texts that are public domain where you publish (often: author died 70+ years ago) or that you have permission to use. Do not use modern song lyrics.
106
+ - Wikisource transcriptions are CC BY-SA; `fetch` returns a credit line you should keep.
107
+ - The music is original and synthesised, but platforms differ on how they treat synthesised audio, so read the rules of wherever you post.
108
+ - Fonts are not bundled. Noto fonts are under the SIL Open Font License.
109
+
110
+ ## Develop
111
+
112
+ ```bash
113
+ git clone https://github.com/ali-saad-khan/versereel && cd versereel
114
+ uv venv && uv pip install -e ".[dev,mcp]"
115
+ pytest
116
+ ```
117
+
118
+ A render takes about 30 seconds for a 30 second video (most of it is ffmpeg compositing).
119
+
120
+ ## Author
121
+
122
+ Built by Saad Ali Khan, a full stack and AI engineer. Portfolio: [saadconsulting.tech](https://saadconsulting.tech). Available for freelance work on AI tooling, MCP servers and automation.
123
+
124
+ ## Licence
125
+
126
+ MIT
@@ -0,0 +1,109 @@
1
+ # versereel
2
+
3
+ Turn a poem or quote into a calm, text-only vertical video (Shorts, Reels, TikTok) with **original ambient music that is synthesised from scratch**: no stock tracks, no samples, nothing to license.
4
+
5
+ - Works with **Urdu Nastaliq** and other right-to-left scripts (Arabic, Persian, Hebrew), as well as Latin text.
6
+ - Text fades in stanza by stanza over a soft paper-and-watercolour background that drifts slowly.
7
+ - Ships as a **CLI**, a **Python API**, an **MCP server** and a **Claude Code skill**.
8
+ - Pure Python plus `ffmpeg`. No GPU, no API keys, no network (except the optional Wikisource fetch).
9
+
10
+ <p align="center"><img src="https://raw.githubusercontent.com/ali-saad-khan/versereel/main/docs/demo.gif" alt="versereel demo" width="270"></p>
11
+
12
+ Built for a calm-poetry Shorts channel, where the same code produced over a hundred videos before it was cleaned up and released.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install "versereel[mcp]" # drop [mcp] if you do not need the MCP server
18
+ ```
19
+
20
+ You also need `ffmpeg` on your PATH. Fonts are looked up on your system and are not bundled; for Urdu install *Noto Nastaliq Urdu* (Debian/Ubuntu: `sudo apt install fonts-noto-extra`).
21
+
22
+ ## Use it
23
+
24
+ ```bash
25
+ # 1. From a JSON spec
26
+ versereel render examples/dickinson-hope.json -o hope.mp4
27
+
28
+ # 2. From plain text (blank line = new stanza)
29
+ printf 'Thou hast made me endless,\nsuch is thy pleasure.\n' | versereel render --title "Gitanjali 1" \
30
+ --author "Rabindranath Tagore" --credit "Public domain" -o gitanjali.mp4
31
+
32
+ # 3. Urdu, right to left
33
+ versereel render examples/iqbal-akhtar-e-subh.json -o iqbal.mp4
34
+
35
+ # 4. Just the music
36
+ versereel bed --seconds 45 --seed my-seed -o bed.wav
37
+
38
+ # 5. Fetch public-domain text from Wikisource
39
+ versereel fetch "Poems: Second Series (Dickinson)/Hope" --author "Emily Dickinson" > hope.json
40
+ versereel render hope.json -o hope.mp4
41
+ ```
42
+
43
+ Check whether a poem fits in a Short (60 s limit) without rendering: add `--dry-run`.
44
+
45
+ ### Spec format
46
+
47
+ ```json
48
+ {
49
+ "title": "Hope",
50
+ "author": "Emily Dickinson",
51
+ "lang": "en",
52
+ "stanzas": [["line one", "line two"], ["next stanza"]],
53
+ "credit": ["Emily Dickinson (1830-1886), public domain", "Original music: versereel"]
54
+ }
55
+ ```
56
+
57
+ `lang` of `ur`, `ar`, `fa`, `he` (and similar) turns on right-to-left layout.
58
+
59
+ ### Python
60
+
61
+ ```python
62
+ from versereel import Poem, render, write_bed
63
+
64
+ render(Poem("Hope", [["Hope is the thing with feathers", "That perches in the soul,"]], author="Emily Dickinson"), "hope.mp4")
65
+ write_bed("bed.wav", seconds=40, seed="rainy-sunday")
66
+ ```
67
+
68
+ ### MCP server
69
+
70
+ ```json
71
+ { "mcpServers": { "versereel": { "command": "versereel-mcp" } } }
72
+ ```
73
+
74
+ Tools: `check_environment`, `plan_poem`, `render_poem`, `make_music_bed`, `fetch_poem`.
75
+
76
+ ### Claude Code skill
77
+
78
+ Copy `skill/versereel/` to `~/.claude/skills/versereel/`. It walks the assistant through the rights check, fitting a Short, rendering and reviewing.
79
+
80
+ ## About the music
81
+
82
+ `make_bed` builds slow pad chords (Cmaj7, Am7, Fmaj7, G6 voicings, gently detuned), sparse pentatonic bell notes and a long FFT reverb, then low-passes it. The same seed always gives the same piece and different seeds are transposed and re-timed, so a channel's videos do not all sound identical. It is deliberately calm background music, not a composition tool.
83
+
84
+ ## Rights and responsibility
85
+
86
+ versereel makes files; **you** are responsible for what you publish.
87
+
88
+ - Use texts that are public domain where you publish (often: author died 70+ years ago) or that you have permission to use. Do not use modern song lyrics.
89
+ - Wikisource transcriptions are CC BY-SA; `fetch` returns a credit line you should keep.
90
+ - The music is original and synthesised, but platforms differ on how they treat synthesised audio, so read the rules of wherever you post.
91
+ - Fonts are not bundled. Noto fonts are under the SIL Open Font License.
92
+
93
+ ## Develop
94
+
95
+ ```bash
96
+ git clone https://github.com/ali-saad-khan/versereel && cd versereel
97
+ uv venv && uv pip install -e ".[dev,mcp]"
98
+ pytest
99
+ ```
100
+
101
+ A render takes about 30 seconds for a 30 second video (most of it is ffmpeg compositing).
102
+
103
+ ## Author
104
+
105
+ Built by Saad Ali Khan, a full stack and AI engineer. Portfolio: [saadconsulting.tech](https://saadconsulting.tech). Available for freelance work on AI tooling, MCP servers and automation.
106
+
107
+ ## Licence
108
+
109
+ MIT
Binary file
@@ -0,0 +1,10 @@
1
+ {
2
+ "title": "Hope",
3
+ "author": "Emily Dickinson",
4
+ "lang": "en",
5
+ "stanzas": [
6
+ ["“Hope” is the thing with feathers", "That perches in the soul,", "And sings the tune without the words,", "And never stops at all,"],
7
+ ["And sweetest in the gale is heard;", "And sore must be the storm", "That could abash the little bird", "That kept so many warm."]
8
+ ],
9
+ "credit": ["Emily Dickinson (1830–1886), public domain", "Original music: versereel"]
10
+ }
@@ -0,0 +1,10 @@
1
+ {
2
+ "title": "اخترِ صُبح",
3
+ "author": "علامہ اقبال",
4
+ "lang": "ur",
5
+ "stanzas": [
6
+ ["ستارہ صبح کا روتا تھا اور یہ کہتا تھا", "مِلی نگاہ مگر فرصتِ نظر نہ ملی"],
7
+ ["ہوئی ہے زندہ دمِ آفتاب سے ہر شے", "اماں مجھی کو تہِ دامنِ سحَر نہ ملی"]
8
+ ],
9
+ "credit": ["Allama Iqbal (1877–1938), public domain", "Original music: versereel"]
10
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "title": "Gitanjali 1",
3
+ "author": "Rabindranath Tagore",
4
+ "lang": "en",
5
+ "stanzas": [
6
+ ["Thou hast made me endless,", "such is thy pleasure.", "This frail vessel thou emptiest again and again,", "and fillest it ever with fresh life."]
7
+ ],
8
+ "credit": ["Rabindranath Tagore (1861–1941), public domain", "Original music: versereel"]
9
+ }
@@ -0,0 +1,27 @@
1
+ [project]
2
+ name = "versereel"
3
+ version = "0.1.1"
4
+ description = "Turn poems and quotes into calm text-only vertical videos with original, royalty-free ambient music. Latin and right-to-left scripts (Urdu Nastaliq). CLI, Python API, MCP server and Claude Code skill."
5
+ readme = "README.md"
6
+ license = { text = "MIT" }
7
+ requires-python = ">=3.10"
8
+ dependencies = ["numpy>=1.24", "pillow>=10", "soundfile>=0.12"]
9
+ keywords = ["poetry", "shorts", "ambient-music", "mcp", "video", "urdu", "nastaliq", "royalty-free"]
10
+
11
+ [project.optional-dependencies]
12
+ mcp = ["mcp>=1.2"]
13
+ dev = ["pytest>=8"]
14
+
15
+ [project.scripts]
16
+ versereel = "versereel.cli:main"
17
+ versereel-mcp = "versereel.mcp_server:main"
18
+
19
+ [build-system]
20
+ requires = ["hatchling"]
21
+ build-backend = "hatchling.build"
22
+
23
+ [tool.hatch.build.targets.wheel]
24
+ packages = ["src/versereel"]
25
+
26
+ [tool.pytest.ini_options]
27
+ testpaths = ["tests"]
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: versereel
3
+ description: Turn a poem, quote or short text into a calm vertical video (YouTube Shorts, Reels, TikTok) with original royalty-free ambient music. Handles Urdu, Arabic, Persian and Hebrew right to left, including Nastaliq. Use for "make a Short from this poem", "quote video", "text-only poetry video", "royalty-free ambient music", or "Urdu poetry video".
4
+ ---
5
+
6
+ # versereel
7
+
8
+ Makes text-only 1080x1920 videos: paper-and-watercolour background, the text fading in stanza by stanza, and an original ambient bed (pad chords, soft bells, reverb) synthesised from scratch. No samples, no stock music, so there is nothing to license.
9
+
10
+ ## Set up (once)
11
+
12
+ ```
13
+ pip install "versereel[mcp]" # needs ffmpeg on PATH
14
+ versereel render --help
15
+ ```
16
+
17
+ Fonts are found on the system, not bundled. For Urdu install "Noto Nastaliq Urdu" (Debian/Ubuntu: `fonts-noto-extra`). Run the MCP tool `check_environment`, or `python -c "from versereel.fonts import find_font; print(find_font('ur'))"`, to confirm.
18
+
19
+ To use it as an MCP server, add to your MCP config: `{"mcpServers": {"versereel": {"command": "versereel-mcp"}}}`.
20
+
21
+ ## Workflow
22
+
23
+ 1. **Check the rights first.** Only use text that is public domain in the user's country (usually author dead 70+ years) or that the user wrote or has permission to use. Do not use modern song lyrics or recent poetry. If unsure, ask the user.
24
+ 2. **Get the text.** From the user, or `versereel fetch "<Wikisource page>" --lang en|ur|...` (MCP: `fetch_poem`). Wikisource transcriptions are CC BY-SA, so keep the credit line that `fetch` returns. If the page is a list of versions, the error lists the pages to try.
25
+ 3. **Fit a Short.** A Short must be 60 seconds or less. Run `versereel render spec.json -o x.mp4 --dry-run` (MCP: `plan_poem`). Roughly 8 to 12 lines fits. Split longer poems into several Shorts at stanza breaks.
26
+ 4. **Write the spec** (JSON): `title`, `author`, `lang` (`en`, `ur`, ...), `stanzas` (list of lists of lines), `credit` (list of small closing lines: author dates, "public domain", text source).
27
+ 5. **Render**: `versereel render spec.json -o out/name.mp4` (MCP: `render_poem`). Takes about 30 seconds per video. Add `--no-music` for silence, `--seed` to change the music.
28
+ 6. **Look at it.** Extract a frame (`ffmpeg -ss 10 -i out/name.mp4 -frames:v 1 f.png`) and check the text is not clipped and Urdu letters are joined. Never publish without the user watching it.
29
+
30
+ ## Music only
31
+
32
+ `versereel bed -o bed.wav --seconds 45 --seed my-seed` (MCP: `make_music_bed`) writes a calm ambient WAV that is safe for any video. The same seed always makes the same piece.
33
+
34
+ ## Notes
35
+
36
+ - Keep one poem per video; do not shorten or alter a poem's wording.
37
+ - Always show attribution (`credit`). The music is original and synthesised, but platforms differ on how they treat synthesised audio, so check the rules of wherever you post.
38
+ - Uploading is out of scope: this tool makes the file, you decide how and when to post.
@@ -0,0 +1,6 @@
1
+ """versereel: calm text-only poem and quote videos with original ambient music."""
2
+ from .bed import make_bed, write_bed
3
+ from .render import Poem, render
4
+
5
+ __version__ = "0.1.1"
6
+ __all__ = ["Poem", "render", "make_bed", "write_bed", "__version__"]
@@ -0,0 +1,33 @@
1
+ """Procedural paper-and-watercolour background. No image files needed."""
2
+ from __future__ import annotations
3
+
4
+ import random
5
+
6
+ import numpy as np
7
+ from PIL import Image, ImageFilter
8
+
9
+ _PALETTE = [(176, 205, 214), (222, 196, 170), (190, 205, 180), (206, 190, 205), (225, 205, 175)]
10
+
11
+
12
+ def make_background(seed: str | int, size: tuple[int, int] = (1300, 2200)) -> Image.Image:
13
+ """Warm paper grain with a few soft washes of colour. Larger than the frame so it can drift slowly."""
14
+ w, h = size
15
+ rnd = random.Random(str(seed))
16
+ rng = np.random.default_rng(rnd.randrange(2**32))
17
+ # paper: warm off-white with fine grain plus a few low-frequency fibres
18
+ grain = rng.normal(0, 1, (h, w)).astype(np.float32)
19
+ fine = np.asarray(Image.fromarray(((grain * 40) + 128).clip(0, 255).astype(np.uint8)).filter(ImageFilter.GaussianBlur(0.8)), dtype=np.float32) - 128
20
+ coarse = np.asarray(Image.fromarray(((rng.normal(0, 1, (h // 8, w // 8)) * 40) + 128).clip(0, 255).astype(np.uint8))
21
+ .resize((w, h), Image.BICUBIC).filter(ImageFilter.GaussianBlur(6)), dtype=np.float32) - 128
22
+ base = np.array([247, 241, 229], dtype=np.float32)
23
+ paper = np.clip(base + (fine * 0.12 + coarse * 0.10)[..., None], 0, 255) / 255
24
+ # soft washes
25
+ wash = Image.new("RGB", (w, h), (255, 255, 255))
26
+ for _ in range(5):
27
+ blob = Image.new("L", (w, h), 0)
28
+ cx, cy, r = rnd.randint(100, w - 100), rnd.randint(150, h - 150), rnd.randint(260, 460)
29
+ from PIL import ImageDraw
30
+ ImageDraw.Draw(blob).ellipse((cx - r, cy - r * 1.3, cx + r, cy + r * 1.3), fill=150)
31
+ wash = Image.composite(Image.new("RGB", (w, h), rnd.choice(_PALETTE)), wash, blob.filter(ImageFilter.GaussianBlur(170)))
32
+ out = np.clip(np.asarray(wash, dtype=np.float32) / 255 * paper * 1.04, 0, 1)
33
+ return Image.fromarray((out * 255).astype(np.uint8))
@@ -0,0 +1,92 @@
1
+ """Original ambient music bed: slow pad chords, sparse soft bell notes and a long reverb.
2
+
3
+ Everything is synthesised from sine waves with numpy. There are no samples and no third-party music,
4
+ so the output has nothing to license. The same seed always gives the same piece.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import zlib
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import soundfile as sf
13
+
14
+ SR = 44100
15
+ # Open voicings: Cmaj7, Am7, Fmaj7, G6-ish (MIDI note numbers).
16
+ _CHORDS = [[48, 55, 59, 64], [45, 52, 60, 64], [41, 48, 57, 64], [43, 50, 59, 65]]
17
+ _PENTATONIC = [72, 74, 76, 79, 81, 84]
18
+
19
+
20
+ def _one_pole_lowpass(x: np.ndarray, cutoff: float, sr: int) -> np.ndarray:
21
+ a = np.exp(-2 * np.pi * cutoff / sr)
22
+ try: # fast path when scipy is around
23
+ from scipy.signal import lfilter
24
+ return lfilter([1 - a], [1, -a], x)
25
+ except ImportError:
26
+ y = np.empty_like(x)
27
+ acc = 0.0
28
+ for i in range(len(x)):
29
+ acc = (1 - a) * x[i] + a * acc
30
+ y[i] = acc
31
+ return y
32
+
33
+
34
+ def make_bed(seconds: float, seed: str | int = "versereel", sr: int = SR) -> np.ndarray:
35
+ """Return a stereo float32 array (n, 2) of `seconds` of ambient music, peak-normalised to 1.0."""
36
+ if seconds <= 0:
37
+ raise ValueError("seconds must be positive")
38
+ h = zlib.crc32(str(seed).encode())
39
+ rng = np.random.default_rng(h)
40
+ shift = [0, 2, -3, 3, -5, 5][h % 6] # transposition, so different seeds sound different
41
+ seg = 8.0 + (h >> 3) % 4 # seconds per chord
42
+ n = int(seconds * sr)
43
+ t = np.arange(n) / sr
44
+ mid = lambda m: 440 * 2 ** ((m + shift - 69) / 12)
45
+
46
+ pad = np.zeros(n)
47
+ for k in range(int(seconds / seg) + 2):
48
+ chord = _CHORDS[k % 4]
49
+ a, b = int(k * seg * sr), min(n, int((k + 1) * seg * sr + 4 * sr))
50
+ if a >= n:
51
+ break
52
+ tt = t[a:b] - k * seg
53
+ env = np.minimum(1, tt / 3.5) * np.minimum(1, (seg + 4 - tt) / 4.0)
54
+ for m in chord:
55
+ for det in (-0.12, 0.0, 0.12): # gentle detune for a wide, slow chorus
56
+ f = mid(m) * 2 ** (det / 12)
57
+ w = np.sin(2 * np.pi * f * tt) + .35 * np.sin(4 * np.pi * f * tt) + .12 * np.sin(6 * np.pi * f * tt)
58
+ pad[a:b] += w * env * (.5 + .5 * np.sin(2 * np.pi * (.07 + .01 * m % 3) * tt + m))
59
+
60
+ bells = np.zeros(n)
61
+ x = min(3.0, seconds / 4)
62
+ while x < seconds - 2:
63
+ f = mid(int(rng.choice(_PENTATONIC)))
64
+ a = int(x * sr)
65
+ length = min(n - a, int(4.5 * sr))
66
+ tt = np.arange(length) / sr
67
+ bells[a:a + length] += (np.sin(2 * np.pi * f * tt) + .25 * np.sin(2 * np.pi * 2.01 * f * tt)) \
68
+ * np.exp(-tt / 1.3) * np.minimum(1, tt / .01)
69
+ x += rng.uniform(3.2, 6.5)
70
+
71
+ mix = pad / max(1e-9, np.abs(pad).max()) * .8 + bells / max(1e-9, np.abs(bells).max()) * .28
72
+ ir_len = int(3.2 * sr) # reverb: decaying noise impulse, convolved by FFT
73
+ ir = rng.standard_normal(ir_len) * np.exp(-np.arange(ir_len) / (.9 * sr))
74
+ ir /= np.abs(ir).sum() / 8
75
+ nfft = 1 << int(np.ceil(np.log2(n + ir_len)))
76
+ wet = np.fft.irfft(np.fft.rfft(mix, nfft) * np.fft.rfft(ir, nfft))[:n]
77
+ mix = .45 * mix + .55 * wet / max(1e-9, np.abs(wet).max()) * np.abs(mix).max()
78
+
79
+ y = _one_pole_lowpass(mix, 2600, sr)
80
+ y *= np.minimum(1, t / 2.0) * np.minimum(1, (seconds - t) / 3.0) # fade in and out
81
+ y /= max(1e-9, np.abs(y).max())
82
+ delay = int(.012 * sr) # tiny Haas delay on one side for width
83
+ return np.stack([y, np.roll(y, delay)], 1).astype("float32")
84
+
85
+
86
+ def write_bed(path: str | Path, seconds: float, seed: str | int = "versereel", db: float = -7.0, sr: int = SR) -> Path:
87
+ """Write a WAV bed. `db` is the peak level in dBFS (negative)."""
88
+ path = Path(path)
89
+ path.parent.mkdir(parents=True, exist_ok=True)
90
+ data = make_bed(seconds, seed, sr) * float(10 ** (min(db, 0.0) / 20))
91
+ sf.write(path, data, sr)
92
+ return path
@@ -0,0 +1,68 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from . import __version__
9
+ from .bed import write_bed
10
+ from .render import Poem, plan, render, text_to_stanzas
11
+
12
+
13
+ def _poem_from_args(a) -> Poem:
14
+ if a.spec:
15
+ return Poem.from_dict(json.loads(Path(a.spec).read_text(encoding="utf-8")))
16
+ text = Path(a.text_file).read_text(encoding="utf-8") if a.text_file else sys.stdin.read()
17
+ return Poem(title=a.title or "", author=a.author or "", lang=a.lang, stanzas=text_to_stanzas(text),
18
+ credit=[a.credit] if a.credit else [])
19
+
20
+
21
+ def main(argv: list[str] | None = None) -> int:
22
+ try:
23
+ return _main(argv)
24
+ except (LookupError, ValueError, FileNotFoundError, RuntimeError) as e:
25
+ print(f"versereel: {e}", file=sys.stderr)
26
+ return 1
27
+
28
+
29
+ def _main(argv: list[str] | None) -> int:
30
+ p = argparse.ArgumentParser(prog="versereel", description="Calm text-only poem videos with original ambient music.")
31
+ p.add_argument("--version", action="version", version=__version__)
32
+ sub = p.add_subparsers(dest="cmd", required=True)
33
+
34
+ r = sub.add_parser("render", help="render a poem to a 1080x1920 MP4")
35
+ r.add_argument("spec", nargs="?", help="JSON spec file (title, author, lang, stanzas, credit)")
36
+ r.add_argument("--text-file", help="plain text; a blank line starts a new stanza (default: read stdin)")
37
+ r.add_argument("--title"); r.add_argument("--author"); r.add_argument("--credit")
38
+ r.add_argument("--lang", default="en", help="language code; ur/ar/fa/he render right to left")
39
+ r.add_argument("-o", "--out", required=True)
40
+ r.add_argument("--no-music", action="store_true"); r.add_argument("--music-db", type=float, default=-7.0)
41
+ r.add_argument("--font"); r.add_argument("--seed")
42
+ r.add_argument("--dry-run", action="store_true", help="print the planned length and font, do not render")
43
+
44
+ b = sub.add_parser("bed", help="write an ambient music bed as WAV")
45
+ b.add_argument("-o", "--out", required=True); b.add_argument("--seconds", type=float, default=30)
46
+ b.add_argument("--seed", default="versereel"); b.add_argument("--db", type=float, default=-7.0)
47
+
48
+ f = sub.add_parser("fetch", help="fetch a poem from Wikisource and print it as a JSON spec")
49
+ f.add_argument("title"); f.add_argument("--lang", default="en"); f.add_argument("--author", default="")
50
+
51
+ a = p.parse_args(argv)
52
+ if a.cmd == "bed":
53
+ print(write_bed(a.out, a.seconds, a.seed, a.db))
54
+ elif a.cmd == "fetch":
55
+ from .sources import fetch_wikisource
56
+ print(json.dumps(fetch_wikisource(a.title, a.lang).as_poem_dict(a.author), ensure_ascii=False, indent=1))
57
+ else:
58
+ poem = _poem_from_args(a)
59
+ if a.dry_run:
60
+ t = plan(poem, a.font)
61
+ print(f"{t['seconds']:.1f}s, font size {t['font_size']}, {len(t['pages'])} page(s), font {t['font']}")
62
+ return 0
63
+ print(render(poem, a.out, music=not a.no_music, music_db=a.music_db, font=a.font, seed=a.seed))
64
+ return 0
65
+
66
+
67
+ if __name__ == "__main__":
68
+ raise SystemExit(main())
@@ -0,0 +1,49 @@
1
+ """Find fonts without bundling any. Override with the `font` argument or VERSEREEL_FONT / VERSEREEL_FONT_BOLD."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+ from pathlib import Path
8
+
9
+ RTL_LANGS = {"ur", "ar", "fa", "he", "ps", "sd", "yi"}
10
+
11
+ _PREFS = {
12
+ "ur": ["Noto Nastaliq Urdu", "Jameel Noori Nastaleeq", "Noto Naskh Arabic"],
13
+ "ar": ["Noto Naskh Arabic", "Amiri", "DejaVu Sans"],
14
+ "fa": ["Noto Naskh Arabic", "Vazirmatn", "DejaVu Sans"],
15
+ "he": ["Noto Serif Hebrew", "DejaVu Serif"],
16
+ "default": ["Noto Serif", "Georgia", "Liberation Serif", "DejaVu Serif"],
17
+ }
18
+
19
+
20
+ def _fc_match(family: str, bold: bool) -> str | None:
21
+ if not shutil.which("fc-match"):
22
+ return None
23
+ pattern = f"{family}:weight=bold" if bold else f"{family}:style=Regular"
24
+ try:
25
+ out = subprocess.run(["fc-match", "-f", "%{family}|%{file}", pattern], capture_output=True, text=True, timeout=10).stdout
26
+ except (OSError, subprocess.TimeoutExpired):
27
+ return None
28
+ fam, _, file = out.partition("|")
29
+ # fc-match always answers; accept only a real match of the family we asked for.
30
+ return file if file and family.lower() in fam.lower() and Path(file).exists() else None
31
+
32
+
33
+ def find_font(lang: str = "en", bold: bool = False, override: str | None = None) -> str:
34
+ """Return a font file path for `lang`. Raises FileNotFoundError with install advice if none is found."""
35
+ explicit = override or os.environ.get("VERSEREEL_FONT_BOLD" if bold else "VERSEREEL_FONT")
36
+ if explicit:
37
+ if not Path(explicit).exists():
38
+ raise FileNotFoundError(f"font not found: {explicit}")
39
+ return explicit
40
+ for family in _PREFS.get(lang, []) + _PREFS["default"]:
41
+ found = _fc_match(family, bold)
42
+ if found:
43
+ return found
44
+ for p in ("/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf" if bold else "/usr/share/fonts/truetype/dejavu/DejaVuSerif.ttf",
45
+ "/System/Library/Fonts/Supplemental/Georgia.ttf", "C:/Windows/Fonts/georgia.ttf"):
46
+ if Path(p).exists():
47
+ return p
48
+ hint = " Install 'Noto Nastaliq Urdu' (fonts-noto-extra on Debian/Ubuntu)." if lang == "ur" else ""
49
+ raise FileNotFoundError(f"no usable font for lang={lang!r}.{hint} Or pass font=/path/to/font.ttf")
@@ -0,0 +1,65 @@
1
+ """MCP server (stdio). Install with `pip install "versereel[mcp]"`, run `versereel-mcp`."""
2
+ from __future__ import annotations
3
+
4
+ import shutil
5
+ from pathlib import Path
6
+
7
+ from .bed import write_bed
8
+ from .render import Poem, plan, render
9
+
10
+
11
+ def build_server():
12
+ try: # mcp >= 2
13
+ from mcp.server.mcpserver import MCPServer as _Server
14
+ except ImportError: # mcp 1.x
15
+ from mcp.server.fastmcp import FastMCP as _Server
16
+
17
+ mcp = _Server("versereel")
18
+
19
+ @mcp.tool()
20
+ def check_environment() -> dict:
21
+ """Report whether ffmpeg and the fonts needed for English and Urdu are available."""
22
+ from .fonts import find_font
23
+ info = {"ffmpeg": shutil.which("ffmpeg")}
24
+ for lang in ("en", "ur"):
25
+ try:
26
+ info[f"font_{lang}"] = find_font(lang)
27
+ except FileNotFoundError as e:
28
+ info[f"font_{lang}"] = f"MISSING: {e}"
29
+ return info
30
+
31
+ @mcp.tool()
32
+ def plan_poem(title: str, stanzas: list[list[str]], lang: str = "en") -> dict:
33
+ """Estimate the video length and layout of a poem without rendering. Use it to check it fits in a Short (<= 58 s)."""
34
+ t = plan(Poem(title=title, stanzas=stanzas, lang=lang))
35
+ return {"seconds": round(t["seconds"], 1), "pages": len(t["pages"]), "font_size": t["font_size"], "fits_short": t["seconds"] <= 58}
36
+
37
+ @mcp.tool()
38
+ def render_poem(title: str, stanzas: list[list[str]], output_path: str, author: str = "", lang: str = "en",
39
+ credit: list[str] | None = None, music: bool = True, seed: str = "") -> str:
40
+ """Render a poem or quote to a vertical 1080x1920 MP4 with original ambient music. `lang` ur/ar/fa/he renders right to left.
41
+ Put attribution (source, licence) in `credit`; it is shown at the end. Returns the video path."""
42
+ poem = Poem(title=title, stanzas=stanzas, author=author, lang=lang, credit=credit or [])
43
+ return str(render(poem, Path(output_path).expanduser(), music=music, seed=seed or None))
44
+
45
+ @mcp.tool()
46
+ def make_music_bed(output_path: str, seconds: float = 30.0, seed: str = "versereel", db: float = -7.0) -> str:
47
+ """Synthesise royalty-free ambient music (WAV). Nothing sampled, nothing to license. Same seed, same piece."""
48
+ return str(write_bed(Path(output_path).expanduser(), seconds, seed, db))
49
+
50
+ @mcp.tool()
51
+ def fetch_poem(title: str, lang: str = "en") -> dict:
52
+ """Fetch a poem from Wikisource. Returns stanzas, url and a credit line. Check the author's public-domain status before publishing."""
53
+ from .sources import fetch_wikisource
54
+ f = fetch_wikisource(title, lang)
55
+ return {"title": f.title, "stanzas": f.stanzas, "url": f.url, "lang": f.lang, "credit": f.credit}
56
+
57
+ return mcp
58
+
59
+
60
+ def main() -> None:
61
+ build_server().run()
62
+
63
+
64
+ if __name__ == "__main__":
65
+ main()
@@ -0,0 +1,215 @@
1
+ """Render a poem or quote into a vertical (1080x1920) text-only video with an original ambient bed."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ import tempfile
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ import soundfile as sf
14
+ from PIL import Image, ImageDraw, ImageFont
15
+
16
+ from .background import make_background
17
+ from .bed import write_bed
18
+ from .fonts import RTL_LANGS, find_font
19
+
20
+ W, H = 1080, 1920
21
+ INK = (58, 44, 38, 255)
22
+ SOFT = (110, 92, 80, 255)
23
+ MAX_SHORT_SECONDS = 58.0 # YouTube Shorts allow up to 60 s; stay clear of the edge
24
+ PAGE_MAX_LINES = 6
25
+
26
+
27
+ @dataclass
28
+ class Poem:
29
+ """What to show. `stanzas` is a list of stanzas, each a list of lines."""
30
+ title: str
31
+ stanzas: list[list[str]]
32
+ author: str = ""
33
+ lang: str = "en"
34
+ credit: list[str] = field(default_factory=list) # small lines at the end, e.g. "Public domain" or the source
35
+ slug: str = ""
36
+
37
+ @property
38
+ def rtl(self) -> bool:
39
+ return self.lang.split("-")[0].lower() in RTL_LANGS
40
+
41
+ @classmethod
42
+ def from_dict(cls, d: dict) -> "Poem":
43
+ stanzas = d.get("stanzas")
44
+ if stanzas is None and "text" in d:
45
+ stanzas = text_to_stanzas(d["text"])
46
+ if not stanzas:
47
+ raise ValueError("poem needs 'stanzas' (list of list of lines) or 'text'")
48
+ stanzas = [[str(x).strip() for x in s if str(x).strip()] for s in stanzas]
49
+ return cls(title=d.get("title", ""), stanzas=[s for s in stanzas if s], author=d.get("author", ""),
50
+ lang=d.get("lang", "en"), credit=list(d.get("credit", [])), slug=d.get("slug", ""))
51
+
52
+
53
+ def text_to_stanzas(text: str) -> list[list[str]]:
54
+ """Blank line = new stanza."""
55
+ return [[ln.strip() for ln in block.splitlines() if ln.strip()] for block in re.split(r"\n\s*\n", text.strip()) if block.strip()]
56
+
57
+
58
+ def _slugify(s: str) -> str:
59
+ return re.sub(r"[^\w]+", "-", s, flags=re.UNICODE).strip("-").lower()[:40] or "poem"
60
+
61
+
62
+ class _Text:
63
+ """Measures and draws one line of text, handling right-to-left scripts word by word."""
64
+
65
+ def __init__(self, rtl: bool, lang: str):
66
+ self.rtl, self.lang = rtl, lang
67
+ self._probe = ImageDraw.Draw(Image.new("RGBA", (10, 10)))
68
+
69
+ def _kw(self) -> dict:
70
+ return {"direction": "rtl", "language": self.lang} if self.rtl else {}
71
+
72
+ def width(self, text: str, font: ImageFont.FreeTypeFont) -> float:
73
+ if not self.rtl:
74
+ return self._probe.textlength(text, font=font)
75
+ words = text.split()
76
+ return sum(self._probe.textlength(w, font=font, **self._kw()) for w in words) + font.size * 0.42 * max(0, len(words) - 1)
77
+
78
+ def draw_lines(self, lines, y, font, fill, lh, centre=W) -> Image.Image:
79
+ img = Image.new("RGBA", (W, H), (0, 0, 0, 0))
80
+ d = ImageDraw.Draw(img)
81
+ for ln in lines:
82
+ if self.rtl:
83
+ x = (centre + self.width(ln, font)) / 2 # right edge; words are placed right to left with a clear gap
84
+ for w in ln.split():
85
+ x -= self._probe.textlength(w, font=font, **self._kw())
86
+ d.text((x, y), w, font=font, fill=fill, **self._kw())
87
+ x -= font.size * 0.42
88
+ else:
89
+ d.text(((centre - self.width(ln, font)) / 2, y), ln, font=font, fill=fill)
90
+ y += lh
91
+ return img
92
+
93
+
94
+ def plan(poem: Poem, font_path: str | None = None) -> dict:
95
+ """Work out font size, pages and timings without rendering. Returns the timeline summary."""
96
+ text = _Text(poem.rtl, poem.lang)
97
+ fp = find_font(poem.lang, override=font_path)
98
+ size = 66
99
+ while True:
100
+ font = ImageFont.truetype(fp, size)
101
+ if max(text.width(ln, font) for s in poem.stanzas for ln in s) <= 930 or size <= 40:
102
+ break
103
+ size -= 2
104
+ pages, cur, n = [], [], 0
105
+ for s in poem.stanzas:
106
+ if cur and n + len(s) > PAGE_MAX_LINES:
107
+ pages.append(cur)
108
+ cur, n = [], 0
109
+ cur.append(s)
110
+ n += len(s)
111
+ pages.append(cur)
112
+ lead, tail, t = 3.0, 4.0, 3.0
113
+ for pi, page in enumerate(pages):
114
+ for si, s in enumerate(page):
115
+ t += 2.6 + 1.5 * len(s) + (1.6 if si == len(page) - 1 else 0)
116
+ if pi < len(pages) - 1:
117
+ t += 0.6 + 1.4
118
+ return {"font": fp, "font_size": size, "pages": pages, "seconds": t + tail, "lead": lead, "tail": tail}
119
+
120
+
121
+ def render(poem: Poem | dict, out: str | Path, music: bool = True, music_db: float = -7.0, font: str | None = None,
122
+ seed: str | int | None = None, workdir: str | Path | None = None, keep_work: bool = False,
123
+ fps: int = 30, preset: str = "veryfast") -> Path:
124
+ """Render `poem` to an MP4 at `out` and return the path. Raises ValueError if it is too long for a Short."""
125
+ poem = Poem.from_dict(poem) if isinstance(poem, dict) else poem
126
+ ffmpeg = os.environ.get("VERSEREEL_FFMPEG") or shutil.which("ffmpeg")
127
+ if not ffmpeg:
128
+ raise RuntimeError("ffmpeg not found. Install it, or set VERSEREEL_FFMPEG.")
129
+ out = Path(out)
130
+ out.parent.mkdir(parents=True, exist_ok=True)
131
+ seed = seed if seed is not None else (poem.slug or _slugify(poem.title))
132
+ tl = plan(poem, font)
133
+ if tl["seconds"] > MAX_SHORT_SECONDS:
134
+ raise ValueError(f"{tl['seconds']:.0f}s is too long for a Short (max {MAX_SHORT_SECONDS:.0f}s): shorten the poem")
135
+
136
+ work = Path(workdir) if workdir else Path(tempfile.mkdtemp(prefix="versereel-"))
137
+ work.mkdir(parents=True, exist_ok=True)
138
+ try:
139
+ text = _Text(poem.rtl, poem.lang)
140
+ fn = ImageFont.truetype(tl["font"], tl["font_size"])
141
+ size = tl["font_size"]
142
+ lh, gap = int(size * 2.25 if poem.rtl else size * 1.55), int(size * 1.1)
143
+ make_background(seed).save(work / "bg.png")
144
+
145
+ layers, t = [], tl["lead"]
146
+ for pi, page in enumerate(tl["pages"]):
147
+ height = sum(len(s) for s in page) * lh + gap * (len(page) - 1)
148
+ y = 330 + (1260 - height) // 2 + 40
149
+ items = []
150
+ for si, s in enumerate(page):
151
+ p = work / f"p{pi}s{si}.png"
152
+ items.append((_save(text.draw_lines(s, y, fn, INK, lh), p), t))
153
+ t += 2.6 + 1.5 * len(s) + (1.6 if si == len(page) - 1 else 0)
154
+ y += len(s) * lh + gap
155
+ out_t = t + 0.6 if pi < len(tl["pages"]) - 1 else None
156
+ layers += [(loc, tin, out_t, 1.2) for loc, tin in items]
157
+ if out_t:
158
+ t = out_t + 1.4
159
+ total = tl["seconds"]
160
+
161
+ header = []
162
+ if poem.author:
163
+ bold = find_font(poem.lang, bold=True, override=None) if not font else font
164
+ header.append((_save(text.draw_lines([poem.author], 150, ImageFont.truetype(bold, 64), (48, 36, 30, 255), 150), work / "by.png"), 0.5, None, 1.4))
165
+ if poem.title and len(poem.title) < 40:
166
+ header.append((_save(text.draw_lines([poem.title], 290, ImageFont.truetype(tl["font"], 44), SOFT, 100), work / "title.png"), 1.2, None, 1.2))
167
+ credit_lines = poem.credit or []
168
+ credit = []
169
+ if credit_lines:
170
+ img = Image.new("RGBA", (W, H), (0, 0, 0, 0))
171
+ d = ImageDraw.Draw(img)
172
+ cf = ImageFont.truetype(find_font("en"), 28)
173
+ for i, tx in enumerate(credit_lines):
174
+ d.text(((W - d.textlength(tx, font=cf)) / 2, 1700 + i * 44), tx, font=cf, fill=SOFT)
175
+ credit.append((_save(img, work / "credit.png"), total - 3.4, None, 1.2))
176
+
177
+ inputs = ["-loop", "1", "-framerate", str(fps), "-t", f"{total:.2f}", "-i", str(work / "bg.png")]
178
+ fc = [f"[0:v]crop={W}:{H}:'110+90*sin(t/9)':'140+90*cos(t/11)',fade=t=in:st=0:d=1.2,"
179
+ f"fade=t=out:st={total - 1.5:.2f}:d=1.5,format=yuv420p[b0]"]
180
+ last = "b0"
181
+ for k, ((path, x, y), t_in, t_out, fade) in enumerate(header + layers + credit, start=1):
182
+ inputs += ["-loop", "1", "-framerate", str(fps), "-t", f"{total:.2f}", "-i", str(path)]
183
+ f = f"[{k}:v]format=rgba,fade=t=in:st={t_in:.2f}:d={fade}:alpha=1"
184
+ if t_out:
185
+ f += f",fade=t=out:st={t_out:.2f}:d=1.0:alpha=1"
186
+ fc += [f + f"[l{k}]", f"[{last}][l{k}]overlay={x}:{y}:format=yuv420[o{k}]"]
187
+ last = f"o{k}"
188
+ fc.append(f"[{last}]format=yuv420p[vout]")
189
+ silent = work / "silent.mp4"
190
+ _run([ffmpeg, "-v", "error", "-y", *inputs, "-filter_complex", ";".join(fc), "-map", "[vout]", "-t", f"{total:.2f}",
191
+ "-r", str(fps), "-c:v", "libx264", "-preset", preset, "-crf", "19", "-pix_fmt", "yuv420p", str(silent)])
192
+ if music:
193
+ wav = write_bed(work / "bed.wav", total, seed, music_db)
194
+ else:
195
+ wav = work / "bed.wav"
196
+ sf.write(wav, np.zeros((int(total * 44100), 2), dtype="float32"), 44100)
197
+ _run([ffmpeg, "-v", "error", "-y", "-i", str(silent), "-i", str(wav), "-map", "0:v", "-map", "1:a", "-c:v", "copy",
198
+ "-c:a", "aac", "-b:a", "192k", "-shortest", "-movflags", "+faststart", str(out)])
199
+ finally:
200
+ if not keep_work and not workdir:
201
+ shutil.rmtree(work, ignore_errors=True)
202
+ return out
203
+
204
+
205
+ def _save(img: Image.Image, path: Path) -> tuple[Path, int, int]:
206
+ """Save only the non-transparent box of a full-frame layer; return (path, x, y) so ffmpeg composites a small image."""
207
+ box = img.getbbox() or (0, 0, 1, 1)
208
+ img.crop(box).save(path)
209
+ return path, box[0], box[1]
210
+
211
+
212
+ def _run(cmd: list[str]) -> None:
213
+ r = subprocess.run(cmd, capture_output=True, text=True)
214
+ if r.returncode:
215
+ raise RuntimeError(f"ffmpeg failed: {r.stderr.strip()[-600:]}")
@@ -0,0 +1,79 @@
1
+ """Fetch poem text from Wikisource (any language edition).
2
+
3
+ Check the licence yourself before publishing a film: a poem is usually public domain once its author has been dead long
4
+ enough in your country, but Wikisource's own transcription and layout are CC BY-SA. `Fetched.credit` gives you a
5
+ ready attribution line to show in the video or description.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import urllib.parse
12
+ import urllib.request
13
+ from dataclasses import dataclass
14
+ from html import unescape
15
+
16
+ from .render import text_to_stanzas
17
+
18
+ UA = "versereel/0.1 (https://github.com/ali-saad-khan/versereel)"
19
+
20
+
21
+ @dataclass
22
+ class Fetched:
23
+ title: str
24
+ stanzas: list[list[str]]
25
+ url: str
26
+ lang: str
27
+ credit: str
28
+
29
+ def as_poem_dict(self, author: str = "") -> dict:
30
+ return {"title": self.title, "author": author, "lang": self.lang, "stanzas": self.stanzas, "credit": [self.credit]}
31
+
32
+
33
+ def clean_wikitext(raw: str) -> str:
34
+ m = re.search(r"<poem[^>]*>(.*?)</poem>", raw, re.S)
35
+ body = m.group(1) if m else raw
36
+ body = re.sub(r"\{\{[^{}]*\}\}", "", body) # templates
37
+ body = re.sub(r"\[\[(?:[^|\]]*\|)?([^\]]*)\]\]", r"\1", body) # [[link|text]] -> text
38
+ body = re.sub(r"<[^>]+>", "", body) # html tags
39
+ body = re.sub(r"'{2,}", "", body) # bold / italic marks
40
+ return body.strip()
41
+
42
+
43
+ def html_to_poem_text(html: str) -> str:
44
+ """Pull poem text out of rendered Wikisource HTML (handles transcluded pages that raw wikitext cannot)."""
45
+ blocks = re.findall(r'<div class="poem">(.*?)</div>\s*(?=<|$)', html, re.S) or re.findall(r"<poem[^>]*>(.*?)</poem>", html, re.S)
46
+ if not blocks:
47
+ return ""
48
+ out = []
49
+ for b in blocks:
50
+ b = re.sub(r"<style.*?</style>", "", b, flags=re.S)
51
+ b = re.sub(r"<sup[^>]*class=\"reference\".*?</sup>", "", b, flags=re.S)
52
+ b = re.sub(r"[ \t]*<br\s*/?>[ \t]*\n?", "\n", b)
53
+ b = re.sub(r"</p>\s*<p[^>]*>", "\n\n", b)
54
+ b = re.sub(r"<[^>]+>", "", b)
55
+ b = re.sub(r"\n{3,}", "\n\n", unescape(b)).strip()
56
+ first, _, rest = b.partition(" ") # drop-cap openings often arrive as "HOPE is the thing..."
57
+ if len(first) > 1 and first.isupper() and rest and not rest.split(" ")[0].isupper():
58
+ b = first.capitalize() + " " + rest
59
+ out.append(b)
60
+ return "\n\n".join(x for x in out if x)
61
+
62
+
63
+ def fetch_wikisource(title: str, lang: str = "en", timeout: float = 30) -> Fetched:
64
+ """Download one Wikisource page and split it into stanzas (blank line = stanza break)."""
65
+ api = f"https://{lang}.wikisource.org/w/api.php"
66
+ q = urllib.parse.urlencode({"action": "parse", "page": title, "prop": "text|displaytitle", "format": "json",
67
+ "redirects": 1, "formatversion": 2, "disableeditsection": 1})
68
+ with urllib.request.urlopen(urllib.request.Request(f"{api}?{q}", headers={"User-Agent": UA}), timeout=timeout) as r:
69
+ data = json.load(r)
70
+ if "error" in data:
71
+ raise LookupError(f"no Wikisource page {title!r} on {lang}.wikisource.org")
72
+ page_title, html = data["parse"]["title"], data["parse"]["text"]
73
+ stanzas = text_to_stanzas(html_to_poem_text(html))
74
+ if not stanzas:
75
+ links = list(dict.fromkeys(re.findall(r'<a href="/wiki/([^"#?]+)"[^>]*title="([^"]+)"', html)))
76
+ hint = "; ".join(t for _, t in links[:6])
77
+ raise LookupError(f"{page_title!r} has no poem text (it may be a list of versions or an index)." + (f" Try: {hint}" if hint else ""))
78
+ url = f"https://{lang}.wikisource.org/wiki/{urllib.parse.quote(page_title.replace(' ', '_'))}"
79
+ return Fetched(page_title, stanzas, url, lang, f"Text: Wikisource (CC BY-SA), {url}")
@@ -0,0 +1,72 @@
1
+ import shutil
2
+ import subprocess
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from versereel import Poem, make_bed, render
8
+ from versereel.render import plan, text_to_stanzas
9
+ from versereel.sources import clean_wikitext
10
+
11
+ HAVE_FFMPEG = shutil.which("ffmpeg") is not None
12
+
13
+
14
+ def test_text_to_stanzas_splits_on_blank_lines():
15
+ assert text_to_stanzas("a\nb\n\nc\n") == [["a", "b"], ["c"]]
16
+
17
+
18
+ def test_bed_is_deterministic_stereo_and_normalised():
19
+ a, b = make_bed(6, "seed-1"), make_bed(6, "seed-1")
20
+ assert a.shape == (6 * 44100, 2)
21
+ assert np.array_equal(a, b)
22
+ assert abs(float(np.abs(a).max()) - 1.0) < 1e-3
23
+ assert not np.array_equal(a, make_bed(6, "seed-2"))
24
+
25
+
26
+ def test_bed_rejects_nonpositive_length():
27
+ with pytest.raises(ValueError):
28
+ make_bed(0)
29
+
30
+
31
+ def test_rtl_languages():
32
+ assert Poem("t", [["x"]], lang="ur").rtl
33
+ assert Poem("t", [["x"]], lang="ar-EG").rtl
34
+ assert not Poem("t", [["x"]], lang="en").rtl
35
+
36
+
37
+ def test_from_dict_requires_text():
38
+ with pytest.raises(ValueError):
39
+ Poem.from_dict({"title": "x"})
40
+ assert Poem.from_dict({"title": "x", "text": "a\n\nb"}).stanzas == [["a"], ["b"]]
41
+
42
+
43
+ def test_plan_pages_and_length():
44
+ p = Poem("t", [["a", "b", "c", "d"], ["e", "f", "g"]])
45
+ t = plan(p)
46
+ assert len(t["pages"]) == 2 and 10 < t["seconds"] < 58
47
+
48
+
49
+ def test_too_long_for_a_short(tmp_path):
50
+ p = Poem("t", [[f"line {i}"] * 4 for i in range(20)])
51
+ with pytest.raises(ValueError, match="too long"):
52
+ render(p, tmp_path / "x.mp4")
53
+
54
+
55
+ def test_clean_wikitext_strips_markup():
56
+ raw = "intro<poem>\n'''Bold''' [[Link|text]] {{tpl}}<br/>\nline two\n</poem>"
57
+ assert clean_wikitext(raw) == "Bold text \nline two"
58
+
59
+
60
+ @pytest.mark.skipif(not HAVE_FFMPEG, reason="needs ffmpeg")
61
+ def test_end_to_end_render(tmp_path):
62
+ out = render(Poem("Test", [["One short line."]], author="Someone", credit=["Public domain"]), tmp_path / "t.mp4", preset="ultrafast")
63
+ probe = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "stream=width,height,codec_name", "-of", "csv=p=0", str(out)],
64
+ capture_output=True, text=True).stdout
65
+ assert "h264,1080,1920" in probe and "aac" in probe
66
+
67
+
68
+ def test_html_to_poem_text_stanzas_and_dropcap():
69
+ from versereel.sources import html_to_poem_text
70
+ html = ('<div class="poem">\n<p><style>.x{}</style>HOPE is the thing <br />\nThat perches here, <br />\n</p>\n'
71
+ '<p>And sings a tune <br />\nAnd never stops <br />\n</p>\n</div>')
72
+ assert html_to_poem_text(html) == "Hope is the thing\nThat perches here,\n\nAnd sings a tune\nAnd never stops"