@auscera/cleoedits 0.0.0-stage → 0.1.0

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 (230) hide show
  1. package/README.md +62 -2
  2. package/cli.mjs +149 -0
  3. package/lib/dependencies.mjs +384 -0
  4. package/lib/run.mjs +114 -0
  5. package/lib/workspace.mjs +167 -0
  6. package/package.json +240 -3
  7. package/workspace/.agents/skills/cleoedits/SKILL.md +29 -0
  8. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/audiogram.json +41 -0
  9. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/facebook.json +48 -0
  10. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/linkedin.json +48 -0
  11. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/podcast.json +23 -0
  12. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/reels.json +48 -0
  13. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/shorts.json +48 -0
  14. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/tiktok.json +48 -0
  15. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/x.json +48 -0
  16. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube-shorts.json +48 -0
  17. package/workspace/.agents/skills/cleoedits/assets/ffmpeg_templates/youtube.json +48 -0
  18. package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/LICENSE-SimpleIcons +30 -0
  19. package/workspace/.agents/skills/cleoedits/assets/reel_effects/assets/logos.json +1 -0
  20. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Anton-Regular.ttf +0 -0
  21. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/ArchivoBlack-Regular.ttf +0 -0
  22. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/InstrumentSerif-Italic.ttf +0 -0
  23. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Inter.ttf +0 -0
  24. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/LICENSE-PermanentMarker.txt +202 -0
  25. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Montserrat.ttf +0 -0
  26. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Anton.txt +93 -0
  27. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-ArchivoBlack.txt +93 -0
  28. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-InstrumentSerif.txt +93 -0
  29. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Inter.txt +93 -0
  30. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Montserrat.txt +93 -0
  31. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-PlayfairDisplay.txt +93 -0
  32. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-Poppins.txt +93 -0
  33. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/OFL-SpaceMono.txt +93 -0
  34. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PermanentMarker-Regular.ttf +0 -0
  35. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay-Italic.ttf +0 -0
  36. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/PlayfairDisplay.ttf +0 -0
  37. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Black.ttf +0 -0
  38. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-Bold.ttf +0 -0
  39. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/Poppins-ExtraBold.ttf +0 -0
  40. package/workspace/.agents/skills/cleoedits/assets/reel_effects/fonts/SpaceMono-Bold.ttf +0 -0
  41. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-MediaPipe +218 -0
  42. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/LICENSE-YuNet +21 -0
  43. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/NOTICE.md +4 -0
  44. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/selfie_segmenter.tflite +0 -0
  45. package/workspace/.agents/skills/cleoedits/assets/reel_effects/models/yunet.onnx +0 -0
  46. package/workspace/.agents/skills/cleoedits/assets/video_styles/LICENSE +21 -0
  47. package/workspace/.agents/skills/cleoedits/assets/video_styles/audio-app-ui/STYLE.md +65 -0
  48. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/STYLE.md +53 -0
  49. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/index.html +328 -0
  50. package/workspace/.agents/skills/cleoedits/assets/video_styles/blueprint/studio.js +57 -0
  51. package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/STYLE.md +65 -0
  52. package/workspace/.agents/skills/cleoedits/assets/video_styles/data-story/index.html +575 -0
  53. package/workspace/.agents/skills/cleoedits/assets/video_styles/design-app-ui/STYLE.md +68 -0
  54. package/workspace/.agents/skills/cleoedits/assets/video_styles/editor-ui/STYLE.md +73 -0
  55. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/STYLE.md +54 -0
  56. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/index.html +189 -0
  57. package/workspace/.agents/skills/cleoedits/assets/video_styles/editorial-paper/studio.js +57 -0
  58. package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/STYLE.md +64 -0
  59. package/workspace/.agents/skills/cleoedits/assets/video_styles/explainer-diagram/index.html +620 -0
  60. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/STYLE.md +55 -0
  61. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/index.html +238 -0
  62. package/workspace/.agents/skills/cleoedits/assets/video_styles/graphite-ui/studio.js +57 -0
  63. package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/STYLE.md +66 -0
  64. package/workspace/.agents/skills/cleoedits/assets/video_styles/growing-city/index.html +602 -0
  65. package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/STYLE.md +66 -0
  66. package/workspace/.agents/skills/cleoedits/assets/video_styles/ink-line/index.html +777 -0
  67. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/STYLE.md +56 -0
  68. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/index.html +186 -0
  69. package/workspace/.agents/skills/cleoedits/assets/video_styles/midnight-grid/studio.js +57 -0
  70. package/workspace/.agents/skills/cleoedits/assets/video_styles/motion-app-ui/STYLE.md +68 -0
  71. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/STYLE.md +56 -0
  72. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/index.html +244 -0
  73. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-cut/studio.js +57 -0
  74. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/STYLE.md +67 -0
  75. package/workspace/.agents/skills/cleoedits/assets/video_styles/paper-world/index.html +663 -0
  76. package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/STYLE.md +59 -0
  77. package/workspace/.agents/skills/cleoedits/assets/video_styles/particle-field/index.html +395 -0
  78. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/STYLE.md +52 -0
  79. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/index.html +194 -0
  80. package/workspace/.agents/skills/cleoedits/assets/video_styles/poster-pop/studio.js +57 -0
  81. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/STYLE.md +58 -0
  82. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/index.html +242 -0
  83. package/workspace/.agents/skills/cleoedits/assets/video_styles/risograph/studio.js +57 -0
  84. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/STYLE.md +53 -0
  85. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/index.html +138 -0
  86. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-grid/studio.js +57 -0
  87. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/STYLE.md +63 -0
  88. package/workspace/.agents/skills/cleoedits/assets/video_styles/swiss-kinetic/index.html +599 -0
  89. package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/STYLE.md +65 -0
  90. package/workspace/.agents/skills/cleoedits/assets/video_styles/time-travel/index.html +1297 -0
  91. package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/STYLE.md +69 -0
  92. package/workspace/.agents/skills/cleoedits/assets/video_styles/weather-widget/index.html +674 -0
  93. package/workspace/.agents/skills/cleoedits/references/audio-clearervoice-elevenlabs.md +11 -0
  94. package/workspace/.agents/skills/cleoedits/references/ffmpeg-and-reels.md +15 -0
  95. package/workspace/.agents/skills/cleoedits/references/hyperframes-workflows.md +13 -0
  96. package/workspace/.agents/skills/cleoedits/references/kdenlive-cli-and-mcp.md +12 -0
  97. package/workspace/.agents/skills/cleoedits/references/motion-design-pipeline.md +7 -0
  98. package/workspace/.agents/skills/cleoedits/references/motion-taste-emil.md +5 -0
  99. package/workspace/.agents/skills/cleoedits/references/playwright-demo-capture.md +9 -0
  100. package/workspace/.agents/skills/cleoedits/references/remotion-workflows.md +13 -0
  101. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/LICENSE +21 -0
  102. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_ass_overlay.py +399 -0
  103. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/__init__.py +235 -0
  104. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/alpha.py +560 -0
  105. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/asr.py +1237 -0
  106. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/color.py +540 -0
  107. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/decision.py +2452 -0
  108. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/drawtext.py +290 -0
  109. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emit.py +1309 -0
  110. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/emoji.py +518 -0
  111. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/fonts.py +875 -0
  112. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing.py +263 -0
  113. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/pacing_edit.py +432 -0
  114. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/probe.py +1613 -0
  115. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/runner.py +3994 -0
  116. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/text.py +73 -0
  117. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/timeline.py +721 -0
  118. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_common/wrap.py +981 -0
  119. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_contract.py +2454 -0
  120. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_platforms.py +258 -0
  121. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.html +754 -0
  122. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_review.py +258 -0
  123. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/_smartcut.py +450 -0
  124. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/audio.py +867 -0
  125. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/background.py +136 -0
  126. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/batch.py +1409 -0
  127. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/broll.py +282 -0
  128. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/caption.py +2207 -0
  129. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/check.py +815 -0
  130. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/color.py +695 -0
  131. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/crop.py +91 -0
  132. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cropdetect.py +214 -0
  133. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/cut.py +2076 -0
  134. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/deinterlace.py +90 -0
  135. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/denoise.py +94 -0
  136. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/export.py +1033 -0
  137. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/fit.py +729 -0
  138. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/freeze.py +197 -0
  139. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/graphics.py +920 -0
  140. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/grid.py +235 -0
  141. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/insert.py +142 -0
  142. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/join.py +1083 -0
  143. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/look.py +475 -0
  144. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loop.py +395 -0
  145. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/loudness.py +397 -0
  146. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/metadata.py +416 -0
  147. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/multicam.py +414 -0
  148. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/overlay.py +766 -0
  149. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/pad.py +121 -0
  150. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/probe.py +145 -0
  151. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/proxy.py +93 -0
  152. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/redact.py +162 -0
  153. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/render.py +2424 -0
  154. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/report.py +354 -0
  155. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/reverse.py +114 -0
  156. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/scenes.py +439 -0
  157. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sequence.py +285 -0
  158. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/silence.py +945 -0
  159. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/speedramp.py +193 -0
  160. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sphere.py +137 -0
  161. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/stabilize.py +141 -0
  162. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/straighten.py +120 -0
  163. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/sync.py +500 -0
  164. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/verify.py +411 -0
  165. package/workspace/.agents/skills/cleoedits/scripts/ffmpeg/waveform.py +502 -0
  166. package/workspace/.agents/skills/cleoedits/scripts/kdenlive_builder.py +284 -0
  167. package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-claude-motion +21 -0
  168. package/workspace/.agents/skills/cleoedits/scripts/motion/LICENSE-motion-design +21 -0
  169. package/workspace/.agents/skills/cleoedits/scripts/motion/_media.py +43 -0
  170. package/workspace/.agents/skills/cleoedits/scripts/motion/pacing_check.py +90 -0
  171. package/workspace/.agents/skills/cleoedits/scripts/motion/storyboard.py +77 -0
  172. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/LICENSE +26 -0
  173. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/fx.py +2717 -0
  174. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/logos.py +194 -0
  175. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/sfx.py +105 -0
  176. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/trim.py +99 -0
  177. package/workspace/.agents/skills/cleoedits/scripts/reel_effects/words.py +60 -0
  178. package/workspace/.claude/commands/blender-3d.md +12 -0
  179. package/workspace/.claude/commands/business-short-form-reels.md +12 -0
  180. package/workspace/.claude/commands/color-grade.md +12 -0
  181. package/workspace/.claude/commands/cutout-grid-reel.md +12 -0
  182. package/workspace/.claude/commands/depth-ui-reel.md +12 -0
  183. package/workspace/.claude/commands/explainer-panel-reel.md +12 -0
  184. package/workspace/.claude/commands/freeze-frame.md +12 -0
  185. package/workspace/.claude/commands/glass-graph.md +12 -0
  186. package/workspace/.claude/commands/over-the-shoulder.md +12 -0
  187. package/workspace/.claude/commands/personal-short-form-reels.md +12 -0
  188. package/workspace/.claude/commands/ranking-format.md +12 -0
  189. package/workspace/.claude/commands/relight.md +12 -0
  190. package/workspace/.claude/commands/reverse-engineer.md +12 -0
  191. package/workspace/.claude/commands/text-behind.md +12 -0
  192. package/workspace/.claude/commands/tier-list.md +12 -0
  193. package/workspace/.claude-plugin/plugin.json +8 -0
  194. package/workspace/.npmignore +15 -0
  195. package/workspace/AGENTS.md +30 -0
  196. package/workspace/README.md +63 -0
  197. package/workspace/assets/fonts/TikTokSans-OFL.txt +93 -0
  198. package/workspace/assets/fonts/TikTokSans-Variable.ttf +0 -0
  199. package/workspace/assets/luts/clean_warm.cube +4917 -0
  200. package/workspace/assets/luts/golden_hour.cube +4917 -0
  201. package/workspace/assets/luts/moody_dark.cube +4917 -0
  202. package/workspace/assets/luts/teal_orange.cube +4917 -0
  203. package/workspace/assets/sfx/NOTICE.txt +1 -0
  204. package/workspace/assets/sfx/click.wav +0 -0
  205. package/workspace/assets/sfx/pop.wav +0 -0
  206. package/workspace/assets/sfx/riser.wav +0 -0
  207. package/workspace/assets/sfx/whoosh.wav +0 -0
  208. package/workspace/generators/hyperframes/index.html +39 -0
  209. package/workspace/generators/hyperframes/package.json +15 -0
  210. package/workspace/generators/hyperframes/pnpm-lock.yaml +1181 -0
  211. package/workspace/generators/hyperframes/pnpm-workspace.yaml +10 -0
  212. package/workspace/generators/remotion/eslint.config.mjs +3 -0
  213. package/workspace/generators/remotion/package.json +36 -0
  214. package/workspace/generators/remotion/pnpm-lock.yaml +4179 -0
  215. package/workspace/generators/remotion/pnpm-workspace.yaml +10 -0
  216. package/workspace/generators/remotion/remotion.config.ts +13 -0
  217. package/workspace/generators/remotion/src/Root.tsx +52 -0
  218. package/workspace/generators/remotion/src/index.css +1 -0
  219. package/workspace/generators/remotion/src/index.ts +4 -0
  220. package/workspace/generators/remotion/tsconfig.json +15 -0
  221. package/workspace/pipeline/scripts/_codec.py +28 -0
  222. package/workspace/pipeline/scripts/ai_media_api.py +109 -0
  223. package/workspace/pipeline/scripts/blender_render.py +166 -0
  224. package/workspace/pipeline/scripts/composite.py +49 -0
  225. package/workspace/pipeline/scripts/melt.sh +68 -0
  226. package/workspace/pipeline/scripts/normalize_audio.py +39 -0
  227. package/workspace/pipeline/scripts/person_matte.py +216 -0
  228. package/workspace/pipeline/scripts/record_demo.py +69 -0
  229. package/workspace/pipeline/scripts/whisper_cut.py +98 -0
  230. package/workspace-manifest.json +908 -0
@@ -0,0 +1,981 @@
1
+ """Text measurement, caption line breaking and the size that fits the cue: the per-character
2
+ advance table, the phrase/measured wrapper and fit_size(). Pure -- no subprocess, no probe.
3
+ Split out of _common.text in the refactor after 1.17.3; every body is byte-identical.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import unicodedata
8
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
9
+ from _common.emoji import emoji_clusters
10
+ from _common.fonts import char_script, detect_script
11
+
12
+
13
+ # --------------------------------------------------------------------------- text measurement (1.12)
14
+ # Moved here in 1.15 so graphics.py's ASS route and the emoji placement share caption.py's table.
15
+ # Average advance width per character, in em (a fraction of the font size). Proportional Latin text
16
+ # averages a bit over half an em; CJK and Thai are drawn on a full-width grid; Arabic/Hebrew and
17
+ # Devanagari sit in between. These are deliberately averages, not per-glyph metrics: measuring the
18
+ # real advance needs a font parser (no stdlib one) and would still be wrong for libass's own
19
+ # shaping, while a cue wrapped from an average is right to within a character on every line.
20
+ # (Latin is measured per character from LATIN_EM below, not from this average.)
21
+ ADVANCE_EM = {"ja": 1.0, "zh": 1.0, "ko": 1.0, "th": 1.0, "hi": 0.7, "ar": 0.6, "he": 0.6,
22
+ "ru": 0.55, "el": 0.55, "latin": 0.55}
23
+
24
+
25
+ # Scripts written without spaces: a line breaks between any two characters.
26
+ # Scripts a line may break inside a run of, one character at a time. Thai is deliberately NOT
27
+ # here since 1.16.1: it writes no space inside a phrase, and without a dictionary the wrapper
28
+ # cannot see where one word ends -- every character-level break it took in eval 17 landed inside
29
+ # a word. A Thai run is therefore one atom, broken only at the spaces (or the manual `|`) the
30
+ # writer put there; an over-long run stays long on its own line, the rule long Latin words
31
+ # already follow.
32
+ # Korean is NOT here: it is written with spaces between words (eojeol), so a Hangul run is a word
33
+ # like a Latin one -- broken at its spaces, and cut inside only by _slice_atom's escape hatch.
34
+ # Per-character atoms broke `시작|합니다` and, once a pass moved the break, joined the halves
35
+ # with no space (`늦지마세요`) while the result said text_unchanged.
36
+ NO_SPACE_SCRIPTS = ("ja", "zh")
37
+
38
+
39
+ # Per-character Latin advances in em, read off DejaVu Sans (the default caption family, and close
40
+ # enough to any other proportional sans for a wrap) and rounded UP: a capital runs 0.56-0.99 em
41
+ # against the single 0.55 average that used to stand for all of Latin, so an all-caps caption --
42
+ # the style most burn-ins use -- overflowed the safe area and was silently re-wrapped by libass
43
+ # past --max-lines. Rounding up is the safe direction: libass re-wraps a too-long line, it never
44
+ # un-wraps a short one. Characters outside the table fall back by class (0.7 uppercase/digit,
45
+ # 0.57 lowercase and anything else Latin-ish).
46
+ LATIN_EM = {
47
+ ' ': 0.32, '!': 0.41, '"': 0.46, '#': 0.84, '$': 0.64, '%': 0.96, '&': 0.78, "'": 0.28,
48
+ '(': 0.4, ')': 0.4, '*': 0.5, '+': 0.84, ',': 0.32, '-': 0.37, '.': 0.32, '/': 0.34, '0': 0.64,
49
+ '1': 0.64, '2': 0.64, '3': 0.64, '4': 0.64, '5': 0.64, '6': 0.64, '7': 0.64, '8': 0.64,
50
+ '9': 0.64, ':': 0.34, ';': 0.34, '<': 0.84, '=': 0.84, '>': 0.84, '?': 0.54, '@': 1.0,
51
+ 'A': 0.69, 'B': 0.69, 'C': 0.7, 'D': 0.78, 'E': 0.64, 'F': 0.58, 'G': 0.78, 'H': 0.76,
52
+ 'I': 0.3, 'J': 0.3, 'K': 0.66, 'L': 0.56, 'M': 0.87, 'N': 0.75, 'O': 0.79, 'P': 0.61,
53
+ 'Q': 0.79, 'R': 0.7, 'S': 0.64, 'T': 0.62, 'U': 0.74, 'V': 0.69, 'W': 0.99, 'X': 0.69,
54
+ 'Y': 0.62, 'Z': 0.69, '[': 0.4, '\\': 0.34, ']': 0.4, '^': 0.84, '_': 0.5, '`': 0.5, 'a': 0.62,
55
+ 'b': 0.64, 'c': 0.55, 'd': 0.64, 'e': 0.62, 'f': 0.36, 'g': 0.64, 'h': 0.64, 'i': 0.28,
56
+ 'j': 0.28, 'k': 0.58, 'l': 0.28, 'm': 0.98, 'n': 0.64, 'o': 0.62, 'p': 0.64, 'q': 0.64,
57
+ 'r': 0.42, 's': 0.53, 't': 0.4, 'u': 0.64, 'v': 0.6, 'w': 0.82, 'x': 0.6, 'y': 0.6, 'z': 0.53,
58
+ '{': 0.64, '|': 0.34, '}': 0.64, '~': 0.84
59
+ }
60
+
61
+
62
+ # Thai and Lao write some vowels BEFORE the consonant they belong to: the break must not land
63
+ # between them and the base that follows.
64
+ LEADING_VOWELS = set(range(0x0E40, 0x0E45)) | set(range(0x0EC0, 0x0EC5))
65
+
66
+
67
+ def _is_mark(ch: str) -> bool:
68
+ """A character that hangs off the one before it: a combining mark (any script) or one of the
69
+ Thai/Lao vowel signs and tone marks, which are Mn/Mc but carry no combining class."""
70
+ return unicodedata.combining(ch) != 0 or unicodedata.category(ch) in ("Mn", "Mc")
71
+
72
+
73
+ def _char_em(ch: str) -> float:
74
+ # CJK punctuation and the fullwidth forms (、。,!? and U+FF01-FF60) are drawn on the same
75
+ # full-width grid as the ideographs they sit between, even though they are not "Han" to a
76
+ # script detector -- measuring them as Latin under-counts a wrapped CJK line by a character.
77
+ cp = ord(ch)
78
+ # A combining mark is drawn on top of (or under) its base and advances the pen by nothing:
79
+ # charging it a full em wrapped Thai and Devanagari lines far shorter than they needed to be.
80
+ if unicodedata.combining(ch) != 0 or unicodedata.category(ch) in ("Mn", "Cf"):
81
+ # "Cf" catches ZWJ/ZWNJ: an Indic joiner is orthography, and it advances the pen by
82
+ # nothing -- charging it a full em (it used to count as "emoji") shrank a Hindi line.
83
+ return 0.0
84
+ if 0x3000 <= cp <= 0x303F or 0xFF01 <= cp <= 0xFF60 or 0xFFE0 <= cp <= 0xFFE6:
85
+ return 1.0
86
+ script = char_script(ch)
87
+ if script == "emoji":
88
+ # 1.15: an emoji is drawn (or reserved) at a full em box, not at Latin's 0.57 -- counting
89
+ # it as Latin overflowed the safe area on an emoji-heavy line.
90
+ return 1.0
91
+ if script == "latin":
92
+ if ch in LATIN_EM:
93
+ return LATIN_EM[ch]
94
+ if ch.isupper() or ch.isdigit():
95
+ return 0.7
96
+ return 0.57
97
+ return ADVANCE_EM.get(script, 0.55)
98
+
99
+
100
+ def text_width_em(text: str, emoji_em: float = 1.0) -> float:
101
+ """Width of `text` in em, from the per-script average advance table. `emoji_em` is what one
102
+ emoji cluster costs (--emoji-scale), so a wrap counts the box that will actually be drawn."""
103
+ total = 0.0
104
+ spans = {i: len(c) for i, c in emoji_clusters(text)}
105
+ i = 0
106
+ while i < len(text):
107
+ if i in spans:
108
+ total += emoji_em
109
+ i += spans[i]
110
+ continue
111
+ total += _char_em(text[i])
112
+ i += 1
113
+ return total
114
+
115
+
116
+ # --------------------------------------------------------------- caption line breaking (1.16)
117
+ # Lifted out of caption.py in 1.16.0 so graphics.py can wrap the same way (caption.py keeps the
118
+ # names it exported, re-imported from here). The whole breaker is pure: a string in, a list of
119
+ # lines out, no subprocess and no probe, which is what makes the eval regression corpus cheap
120
+ # to lock down in unit tests.
121
+
122
+ # How much of the frame width a caption line may use. libass's own default SRT margins are 10 of a
123
+ # 384-wide script (2.6 % a side); 5 % a side is the safe area every platform check in this repo uses.
124
+ SAFE_WIDTH_FRACTION = 0.9
125
+ # ORPHAN_MIN_EM: one full-width CJK/Thai character plus a hair. A last line narrower than this is a
126
+ # single stranded character -- eval 14's th1 (a lone 'ล') and dl3 (a lone '行').
127
+ ORPHAN_MIN_EM = 1.1
128
+
129
+ WRAP_MODES = ("phrase", "measured")
130
+
131
+ # R3's Japanese preference table. These are *preferences* applied only among positions that
132
+ # already fit the line, so the table can never make a line too wide or change the line count.
133
+ #
134
+ # JA_PARTICLES is a "do not strand at the start of a line" table, which is the direction kinsoku
135
+ # practice actually goes: a particle is enclitic -- it attaches to the word BEFORE it and marks
136
+ # that word's role -- so a line beginning with は or が reads as a fragment torn off its phrase.
137
+ # A break AFTER a particle is therefore preferred (the particle stays with what it marks) and a
138
+ # break BEFORE one is forbidden. The list is the eight case/topic particles named in the 1.16.0
139
+ # task brief (は が を に で と の へ) plus も や から まで より, which a reader of Japanese would
140
+ # add for the same reason. It is a judgement call with no upstream source; treat it as tunable
141
+ # data, not as grammar.
142
+ JA_PARTICLES = "はがをにでとのへもや" # a break AFTER one of these is preferred, BEFORE one forbidden
143
+ # The multi-character members of the same table. They are matched as whole strings against the
144
+ # text on each side of a candidate break -- putting them in the character string above turned
145
+ # か, ら, ま, で, よ and り into one-character particles of their own, which none of them is.
146
+ JA_PARTICLE_WORDS = ("から", "まで", "より")
147
+ JA_SENTENCE_END = "。、!?」』),;:" # a break AFTER one of these is preferred (A54: ,;: too)
148
+ # Characters that may never start a line: small kana, the prolonged sound mark, closing brackets
149
+ # and the Japanese punctuation that hangs on the end of the line before it.
150
+ # A54 (#457): the fullwidth comma, semicolon, colon and full stop Chinese uses, and the closing
151
+ # brackets of both, are on the same table: a line that opens with ',' is the same fault as one
152
+ # that opens with '、'.
153
+ JA_NO_LINE_START = "ぁぃぅぇぉっゃゅょァィゥェォッャュョーヽヾゝゞ、。!?)」』】〕》’”%,;:.〉]}〗"
154
+ JA_NO_LINE_END = "(「『【〔《‘“〈[{〖" # ... and the ones that may never end a line
155
+
156
+ # R4. Function words belong to the phrase that FOLLOWS them: an article or preposition begins the
157
+ # noun phrase it governs, so a break before one is the good break (the word opens the next line
158
+ # with its phrase) and a break after one is the bad break (it is stranded at the end of a line,
159
+ # away from what it governs). Both directions are scored, which is what makes the rule decide
160
+ # rather than merely veto. Frozen data, matched case-folded on the atom with its punctuation
161
+ # stripped; six languages because those are the Latin-script languages the eval corpus covers. A
162
+ # word in several sets means the same thing structurally in each, so the union is used when no
163
+ # --lang was given.
164
+ FUNCTION_WORDS = {
165
+ "en": {"a", "an", "the", "of", "to", "in", "on", "at", "for", "with", "by", "from", "and",
166
+ "or", "as", "is", "it", "its", "this", "that", "into", "than", "but", "so"},
167
+ "es": {"el", "la", "los", "las", "un", "una", "unos", "unas", "de", "del", "al", "en", "con",
168
+ "por", "para", "y", "o", "que", "su", "sus", "lo", "se", "es"},
169
+ "pt": {"o", "a", "os", "as", "um", "uma", "de", "do", "da", "dos", "das", "em", "no", "na",
170
+ "nos", "nas", "com", "por", "para", "e", "que", "se", "ao", "aos"},
171
+ "fr": {"le", "la", "les", "un", "une", "de", "du", "des", "à", "au", "aux", "en", "dans",
172
+ "et", "ou", "que", "qui", "ce", "ces", "son", "sa", "ses", "par", "pour", "avec", "sur"},
173
+ "de": {"der", "die", "das", "ein", "eine", "einen", "einem", "einer", "den", "dem", "des",
174
+ "zu", "in", "im", "auf", "mit", "und", "oder", "von", "vom", "für", "aus", "an"},
175
+ "it": {"il", "lo", "la", "i", "gli", "le", "un", "una", "uno", "di", "del", "della", "da",
176
+ "in", "nel", "con", "per", "e", "che", "su", "al", "ai"},
177
+ }
178
+ _FUNCTION_WORDS_ANY = frozenset().union(*FUNCTION_WORDS.values())
179
+
180
+ # Penalty scores. Only the ordering matters; 1.0 means "never choose this if anything else fits".
181
+ PENALTY_FORBIDDEN = 1.0
182
+ PENALTY_OKURIGANA = 0.9 # between a kanji stem and the hiragana that inflects it
183
+ PENALTY_FUNCTION_WORD = 0.8 # R4: the line before the break ends in an article/preposition
184
+ PENALTY_IDEOGRAPHS = 0.6 # between two kanji: no evidence either way, mildly discouraged
185
+ PENALTY_NEUTRAL = 0.5 # between two content words, or two characters with nothing to say
186
+ PENALTY_FUNCTION_WORD_START = 0.2 # R4: the next line opens with the article/preposition it governs
187
+ PENALTY_PARTICLE = 0.2 # R3: after a particle, so the particle stays with the word it marks
188
+ PENALTY_SENTENCE_END = 0.0 # R3: after 。、!? -- the one break a reader expects
189
+
190
+ _HYPHENS = ("-", "‐") # ‑ (non-breaking hyphen) is deliberately NOT here
191
+
192
+
193
+ # Common caption vocabulary with a clear internal boundary. Keep this small: it is
194
+ # a phrase-wrap hint, not a dictionary or a general Chinese segmenter.
195
+ _CHINESE_WORDS = frozenset(("视频", "視頻", "影片", "效果", "功能", "字幕", "剪辑", "剪輯",
196
+ "画面", "畫面", "音频", "音頻", "声音", "聲音"))
197
+
198
+
199
+ def _protect_chinese_words(text: str, mode: str, lang: "Optional[str]") -> bool:
200
+ return (mode == "phrase" and any(word in text for word in _CHINESE_WORDS)
201
+ and detect_script(text, lang) == "zh")
202
+
203
+
204
+ def _atoms(line: str, *, chinese: bool = False) -> "List[Tuple[str, bool]]":
205
+ """Break a line into the smallest pieces a wrap may separate -- one atom per CJK/Thai
206
+ character, one per emoji cluster, one per whitespace-delimited word otherwise -- each with
207
+ whether a space stood before it in the original. The flag is what puts the text back together
208
+ exactly as written: "Hello 世界" keeps its space, "世界です" gains none."""
209
+ out: "List[Tuple[str, bool]]" = []
210
+ word = ""
211
+ spaced = False # a space stands before the atom being built
212
+ pending = False # a space stands before the NEXT atom
213
+ attach_next = False # a leading Thai/Lao vowel is waiting for its base consonant
214
+ # An emoji cluster is one atom: a wrap must never land inside a ZWJ sequence, a flag pair or
215
+ # between a base and its skin-tone modifier (the same rule combining marks already follow).
216
+ clusters = {i: len(cl) for i, cl in emoji_clusters(line)}
217
+ i = 0
218
+ while i < len(line):
219
+ ch = line[i]
220
+ if i in clusters:
221
+ cluster = line[i:i + clusters[i]]
222
+ if word:
223
+ out.append((word, spaced))
224
+ word = ""
225
+ out.append((cluster, pending))
226
+ pending = False
227
+ attach_next = False
228
+ i += clusters[i]
229
+ continue
230
+ i += 1
231
+ if char_script(ch) in NO_SPACE_SCRIPTS:
232
+ if word:
233
+ out.append((word, spaced))
234
+ word = ""
235
+ if (out and not pending and _is_ideograph(ch) and out[-1][0][-1:] == ch
236
+ and out[-1][0][-2:-1] != ch):
237
+ # a repeated ideograph is one word -- Chinese verb reduplication (看看 "have a look",
238
+ # 试试 "give it a try", 想想 "think it over") and words like 人人: the pair is one atom,
239
+ # as a katakana run already is (a reader of 3.10.0 saw 看|看 split across two lines).
240
+ # The merge is capped at TWO characters: an uncapped run (哈哈哈哈哈哈 in a caption) was
241
+ # one unbreakable atom, hard-sliced at the column edge. A longer run is pairs (哈哈|哈哈|哈),
242
+ # and break_penalty still scores a break between them PENALTY_FORBIDDEN, so it is a cost
243
+ # the wrapper may pay, not a wall. Compared on the atom's tail, so an opening bracket the
244
+ # pair carries ((看 + 看) still merges, and a closing mark between the two (「看」看) does not
245
+ out[-1] = (out[-1][0] + ch, out[-1][1])
246
+ elif chinese and out and not pending and out[-1][0][-1:] + ch in _CHINESE_WORDS:
247
+ out[-1] = (out[-1][0] + ch, out[-1][1])
248
+ elif out and not pending and _is_katakana_run(ch) and _is_katakana_run(out[-1][0][-1]):
249
+ # a katakana word (タイミング, コンピューター) is one atom: eval 17 saw タイ|ミング
250
+ out[-1] = (out[-1][0] + ch, out[-1][1])
251
+ elif out and (attach_next or _is_mark(ch)):
252
+ # never break between a base and the mark (or the leading vowel) that belongs to
253
+ # it: the line would start with an orphaned tone mark or vowel sign
254
+ out[-1] = (out[-1][0] + ch, out[-1][1])
255
+ else:
256
+ out.append((ch, pending))
257
+ pending = False
258
+ attach_next = ord(ch) in LEADING_VOWELS
259
+ elif ch.isspace():
260
+ if word:
261
+ out.append((word, spaced))
262
+ word = ""
263
+ pending = True
264
+ else:
265
+ if not word:
266
+ spaced, pending = pending, False
267
+ word += ch
268
+ if word:
269
+ out.append((word, spaced))
270
+ return out
271
+
272
+
273
+ def _split_hyphens(atoms: "List[Tuple[str, bool]]") -> "List[Tuple[str, bool]]":
274
+ """R1's one addition to the atom list: a hyphenated token may break *after* its hyphen.
275
+
276
+ "end-to-end" becomes `end-` / `to-` / `end`, each piece carrying the space flag of the token
277
+ it came from for the first piece and False for the rest, so _join() puts it back with no space
278
+ at all. A hyphen that is the first or last character of the token (`-5`, `well-`) is never a
279
+ break point: the guard is that both sides must be non-empty."""
280
+ out: "List[Tuple[str, bool]]" = []
281
+ for atom, spaced in atoms:
282
+ if len(atom) < 3 or not any(h in atom[1:-1] for h in _HYPHENS):
283
+ out.append((atom, spaced))
284
+ continue
285
+ piece = ""
286
+ first = True
287
+ for i, ch in enumerate(atom):
288
+ piece += ch
289
+ if ch in _HYPHENS and 0 < i < len(atom) - 1:
290
+ out.append((piece, spaced if first else False))
291
+ piece = ""
292
+ first = False
293
+ if piece:
294
+ out.append((piece, spaced if first else False))
295
+ return out
296
+
297
+
298
+ def _slice_atom(atom: str, max_em: float) -> "List[str]":
299
+ """The escape hatch (1.18.4): hard-slice a single atom that is wider than `max_em` all by
300
+ itself -- a word or run with no break point the wrapper may use, and that STILL does not fit
301
+ even alone on its own line. Nothing else in this file may ever chop an atom mid-character;
302
+ this is the one place that does, and only once every other mechanism (wrapping, then
303
+ caption.py's --min-size shrink) has already failed to make it fit.
304
+
305
+ No dictionary, no hyphenation library: an existing hyphen is preferred as the cut (the same
306
+ break R1 already allows), then whatever is left is cut again at exactly the widest prefix
307
+ that still measures within `max_em`, one character at a time. The characters themselves are
308
+ never rewritten -- every piece concatenates back to the original atom exactly.
309
+
310
+ Iterative, and each piece measures only the prefixes up to the first that is too wide (a
311
+ prefix is never narrower than a shorter one): the recursive form measured every prefix of the
312
+ remaining atom for each piece it cut, so a 1 KB hyphenated cue took seconds and 4 KB minutes
313
+ (A11, #465), in caption.py's own process, which --timeout (a limit on each ffmpeg call) does
314
+ not bound. The pieces are the ones the recursive form cut."""
315
+ pieces: "List[str]" = []
316
+ rest = atom
317
+ while True:
318
+ # latest hyphen whose left side still fits -- keeps the left half as large as possible;
319
+ # a rest whose every prefix fits, itself included, is the last piece
320
+ cut = 0
321
+ for end in range(1, len(rest) + 1):
322
+ if text_width_em(rest[:end]) > max_em:
323
+ break
324
+ if 1 <= end - 1 <= len(rest) - 2 and rest[end - 1] in _HYPHENS:
325
+ cut = end
326
+ else:
327
+ return pieces + [rest]
328
+ if not cut:
329
+ break
330
+ pieces.append(rest[:cut])
331
+ rest = rest[cut:]
332
+ cur = ""
333
+ for ch in rest:
334
+ candidate = cur + ch
335
+ if cur and text_width_em(candidate) > max_em:
336
+ pieces.append(cur)
337
+ cur = ch
338
+ else:
339
+ cur = candidate
340
+ if cur:
341
+ pieces.append(cur)
342
+ return pieces or [atom]
343
+
344
+
345
+ def _join(left: str, atom: str, spaced: bool) -> str:
346
+ """Put an atom back on a line, restoring the space that stood before it."""
347
+ if not left:
348
+ return atom
349
+ return left + (" " if spaced else "") + atom
350
+
351
+
352
+ def _break_spaced(first: str, second: str) -> bool:
353
+ """A guess at whether a space stood at the break between these two wrapped lines, from the
354
+ scripts on each side. The wrapper's own passes do not use it: the greedy fill records the real
355
+ answer per break (`gaps`) and every pass carries it along, because a script cannot tell -- a
356
+ Japanese cue written with spaces (`はい そうです`) lost one whenever a pass moved a break that
357
+ stood at a space. Kept as the fallback for a caller that has only the two strings."""
358
+ if not first or not second:
359
+ return False
360
+ return char_script(first[-1]) not in NO_SPACE_SCRIPTS and char_script(second[0]) not in NO_SPACE_SCRIPTS \
361
+ and char_script(first[-1]) != "emoji" and char_script(second[0]) != "emoji"
362
+
363
+
364
+ def _is_kana(ch: str) -> bool:
365
+ return 0x3040 <= ord(ch) <= 0x30FF
366
+
367
+
368
+ def _is_katakana_run(ch: str) -> bool:
369
+ """Katakana proper plus the prolonged-sound mark: the characters one loan word is made of."""
370
+ cp = ord(ch)
371
+ return (0x30A1 <= cp <= 0x30FA) or cp == 0x30FC or (0x31F0 <= cp <= 0x31FF) or (0xFF66 <= cp <= 0xFF9F)
372
+
373
+
374
+ def _is_hiragana(ch: str) -> bool:
375
+ return 0x3040 <= ord(ch) <= 0x309F
376
+
377
+
378
+ def _is_ideograph(ch: str) -> bool:
379
+ cp = ord(ch)
380
+ return 0x3400 <= cp <= 0x4DBF or 0x4E00 <= cp <= 0x9FFF or 0xF900 <= cp <= 0xFAFF
381
+
382
+
383
+ def _is_weak_line(line: str) -> "bool":
384
+ """A line no reader should be given on its own (R2).
385
+
386
+ 1.15 asked only "is the last line one atom narrower than ORPHAN_MIN_EM", which a full-width
387
+ character passes: dl3 still showed a lone `2` and a stranded `行`. Three cases instead, any of
388
+ which makes a line too thin to stand alone:
389
+ - a single character narrower than ORPHAN_MIN_EM (1.15's rule, kept);
390
+ - nothing but digits, punctuation and symbols, at most two characters ("2", "--");
391
+ - a single kana, whatever its width -- a kana is a full em and passes the width test, but a
392
+ line holding one is a syllable, not a word.
393
+ """
394
+ stripped = (line or "").strip()
395
+ if not stripped:
396
+ return True
397
+ if len(stripped) == 1 and text_width_em(stripped) < ORPHAN_MIN_EM:
398
+ return True
399
+ if len(stripped) <= 2 and all(unicodedata.category(c)[0] in "NPS" for c in stripped):
400
+ return True
401
+ if len(stripped) == 1 and char_script(stripped) == "ja" and _is_kana(stripped):
402
+ return True
403
+ return False
404
+
405
+
406
+ def _function_words(lang: "Optional[str]") -> "frozenset":
407
+ """R4's table for this language. An unknown or absent language gets the union of the six sets:
408
+ a token that appears in several of them is the same kind of word in each, which is why the
409
+ rule is a penalty and not a refusal."""
410
+ key = (lang or "").strip().lower().replace("_", "-").split("-")[0]
411
+ if key in FUNCTION_WORDS:
412
+ return frozenset(FUNCTION_WORDS[key])
413
+ return _FUNCTION_WORDS_ANY
414
+
415
+
416
+ def _bare_word(atom: str) -> str:
417
+ return "".join(c for c in (atom or "") if c.isalpha() or c == "'").strip("'").lower()
418
+
419
+
420
+ def _particle_starts(text: str) -> bool:
421
+ """Does `text` begin with a particle -- one character, or one of the two-character ones?"""
422
+ if not text:
423
+ return False
424
+ return text[0] in JA_PARTICLES or text.startswith(JA_PARTICLE_WORDS)
425
+
426
+
427
+ def _particle_ends(text: str) -> bool:
428
+ """Does `text` end with a particle? `から` counts, a bare `ら` does not."""
429
+ if not text:
430
+ return False
431
+ return text[-1] in JA_PARTICLES or text.endswith(JA_PARTICLE_WORDS)
432
+
433
+
434
+ def break_penalty(prev_char: str, next_char: str, lang: "Optional[str]" = None,
435
+ before: str = "", after: str = "") -> float:
436
+ """How bad a break between these two characters is, 0.0 (preferred) to 1.0 (forbidden).
437
+
438
+ Only consulted among break positions that already fit `max_em`, so a preference can never
439
+ widen a line or change the line count. Japanese gets the particle half of the table -- a break
440
+ AFTER a particle is preferred and a break BEFORE one forbidden, because a particle attaches to
441
+ the word before it; Chinese gets only the sentence-end and forbidden halves, because particles
442
+ are Japanese grammar.
443
+
444
+ `before`/`after` are the text on each side of the break when the caller has it, which is what
445
+ lets the two-character particles (から/まで/より) be matched as words. Without them only the
446
+ single-character table applies."""
447
+ if not prev_char or not next_char:
448
+ return PENALTY_NEUTRAL
449
+ script = (lang or "").strip().lower().replace("_", "-").split("-")[0]
450
+ if script not in ("ja", "zh"):
451
+ # A kana on either side settles it: only Japanese has them, and char_script() reads a bare
452
+ # Han character as Chinese, which used to switch the particle rules off for exactly the
453
+ # break they exist to judge (`...が|決まる` -- kana before, kanji after).
454
+ if _is_kana(prev_char) or _is_kana(next_char):
455
+ script = "ja"
456
+ else:
457
+ script = char_script(next_char)
458
+ if script not in ("ja", "zh"):
459
+ script = char_script(prev_char)
460
+ if next_char in JA_NO_LINE_START or prev_char in JA_NO_LINE_END or _is_mark(next_char):
461
+ return PENALTY_FORBIDDEN
462
+ if prev_char == next_char and _is_ideograph(prev_char):
463
+ # a repeated ideograph is one word (reduplication: 看看, 试试, 想想): a break inside it is a
464
+ # break inside a word, whatever language the cue declares. The atomiser keeps a pair
465
+ # together (capped at two); this scores a break between the pairs of a longer run, and
466
+ # covers callers that score a break directly
467
+ return PENALTY_FORBIDDEN
468
+ if script not in ("ja", "zh"):
469
+ return PENALTY_NEUTRAL
470
+ if prev_char in JA_SENTENCE_END:
471
+ return PENALTY_SENTENCE_END
472
+ if script == "ja" and _particle_starts(after or next_char):
473
+ # a particle may not open a line: it belongs to the word before it (kinsoku)
474
+ return PENALTY_FORBIDDEN
475
+ if script == "ja" and _particle_ends(before or prev_char):
476
+ return PENALTY_PARTICLE
477
+ if script == "ja" and _is_ideograph(prev_char) and _is_hiragana(next_char):
478
+ # okurigana: 決|まる is inside a word even though neither half is a "word" on its own
479
+ return PENALTY_OKURIGANA
480
+ if _is_ideograph(prev_char) and _is_ideograph(next_char):
481
+ return PENALTY_IDEOGRAPHS
482
+ return PENALTY_NEUTRAL
483
+
484
+
485
+ def _cut_penalty(atoms: "Sequence[Tuple[str, bool]]", cut: int, lang: "Optional[str]") -> float:
486
+ """The penalty of breaking `atoms` before index `cut`."""
487
+ prev_atom = atoms[cut - 1][0]
488
+ next_atom = atoms[cut][0]
489
+ if not prev_atom or not next_atom:
490
+ return PENALTY_NEUTRAL
491
+ if atoms[cut][1]:
492
+ # a space stood here: a spaced script, so R4 is the rule that applies, in both directions
493
+ if all(not ch.isalnum() for ch in next_atom):
494
+ return PENALTY_FORBIDDEN # never strand punctuation at the start of a line
495
+ words = _function_words(lang)
496
+ if _bare_word(prev_atom) in words:
497
+ return PENALTY_FUNCTION_WORD # stranded at the end of a line, away from its noun
498
+ if _bare_word(next_atom) in words:
499
+ return PENALTY_FUNCTION_WORD_START # opens the next line with the phrase it governs
500
+ return PENALTY_NEUTRAL
501
+ if prev_atom.endswith(_HYPHENS):
502
+ return PENALTY_NEUTRAL # R1: a hyphen is a legitimate break point
503
+ # the text on each side, so a two-character particle (から/まで/より) is seen as one
504
+ before = "".join(a for a, _sp in atoms[:cut])
505
+ after = "".join(a for a, _sp in atoms[cut:])
506
+ return break_penalty(prev_atom[-1], next_atom[0], lang, before=before, after=after)
507
+
508
+
509
+ def best_break(atoms: "Sequence[Tuple[str, bool]]", max_em: float,
510
+ lang: "Optional[str]" = None) -> "Optional[int]":
511
+ """The index to break `atoms` at so they become two lines, or None when none fits.
512
+
513
+ Among every position whose two halves both fit `max_em`, the one minimising
514
+ (penalty, widest line, |width difference|) wins: R1-R4 choose first, and 1.15's
515
+ minimise-the-widest-line rule breaks the ties it used to decide alone."""
516
+ best = None
517
+ for cut in range(1, len(atoms)):
518
+ a = b = ""
519
+ for atom, sp in atoms[:cut]:
520
+ a = _join(a, atom, sp)
521
+ for atom, sp in atoms[cut:]:
522
+ b = _join(b, atom, sp)
523
+ wa, wb = text_width_em(a), text_width_em(b)
524
+ if max(wa, wb) > max_em:
525
+ continue
526
+ if _is_weak_line(a) or _is_weak_line(b):
527
+ continue
528
+ key = (_cut_penalty(atoms, cut, lang), max(wa, wb), abs(wa - wb))
529
+ if best is None or key < best[0]:
530
+ best = (key, cut)
531
+ return None if best is None else best[1]
532
+
533
+
534
+ def _gaps(lines: "List[str]", gaps: "Optional[List[bool]]") -> "List[bool]":
535
+ """The per-break space flags a pass reads and updates: the caller's list (updated in place, so
536
+ the next pass sees the moved breaks), or the _break_spaced() guess when the caller has none."""
537
+ if gaps is None:
538
+ return [_break_spaced(a, b) for a, b in zip(lines, lines[1:])]
539
+ if len(gaps) != max(len(lines) - 1, 0):
540
+ raise ValueError("gaps must hold one flag per break")
541
+ return gaps
542
+
543
+
544
+ def _fix_orphans(lines: "List[str]", max_em: float,
545
+ gaps: "Optional[List[bool]]" = None, kinsoku: bool = False,
546
+ *, chinese: bool = False) -> "List[str]":
547
+ """No last line that is a single stranded atom.
548
+
549
+ Greedy wrapping leaves one character alone whenever the line before it filled exactly: eval 14
550
+ produced a Thai cue ending in a lone `ล` and a Japanese one ending in a lone `行`. While the
551
+ last line is one atom narrower than ORPHAN_MIN_EM, the last atom of the line above moves down
552
+ onto it -- but only while the result still fits and the line above does not become an orphan
553
+ itself, so a two-word cue is never made worse. `kinsoku` (phrase mode) moves a punctuation
554
+ mark down only with the character it closes (_kinsoku_atoms)."""
555
+ lines = list(lines)
556
+ gaps = _gaps(lines, gaps)
557
+ for _ in range(len(lines)):
558
+ if len(lines) < 2:
559
+ break
560
+ tail = _atoms(lines[-1], chinese=chinese)
561
+ if len(tail) != 1 or text_width_em(lines[-1]) >= ORPHAN_MIN_EM:
562
+ break
563
+ prev = _atoms(lines[-2], chinese=chinese)
564
+ if kinsoku:
565
+ prev = _kinsoku_atoms(prev)
566
+ if len(prev) < 2:
567
+ break
568
+ moved, spaced = prev[-1]
569
+ new_prev = ""
570
+ for atom, sp in prev[:-1]:
571
+ new_prev = _join(new_prev, atom, sp)
572
+ new_last = _join(moved, tail[0][0], gaps[-1])
573
+ if text_width_em(new_last) > max_em or text_width_em(new_prev) < ORPHAN_MIN_EM:
574
+ break
575
+ lines[-2], lines[-1] = new_prev, new_last
576
+ gaps[-1] = spaced
577
+ return lines
578
+
579
+
580
+ def _fix_weak_lines(lines: "List[str]", max_em: float,
581
+ gaps: "Optional[List[bool]]" = None, *, chinese: bool = False) -> "List[str]":
582
+ """R2, generalised: _fix_orphans run at *every* boundary, against _is_weak_line.
583
+
584
+ 1.15 only ever looked at the last line, so a stranded digit or kana in the middle of a
585
+ three-line cue survived. Walking upward from the last line, while a line is weak the last atom
586
+ of the line above moves down onto it -- with 1.15's two guards intact (the result must still
587
+ fit, and the line above must not itself become weak), so the line count never changes. A
588
+ punctuation mark moves down only with the character it closes (_kinsoku_atoms, A54)."""
589
+ lines = list(lines)
590
+ gaps = _gaps(lines, gaps)
591
+ for i in range(len(lines) - 1, 0, -1):
592
+ for _ in range(len(lines)):
593
+ if not _is_weak_line(lines[i]):
594
+ break
595
+ prev = _kinsoku_atoms(_atoms(lines[i - 1], chinese=chinese))
596
+ if len(prev) < 2:
597
+ break
598
+ moved, spaced = prev[-1]
599
+ new_prev = ""
600
+ for atom, sp in prev[:-1]:
601
+ new_prev = _join(new_prev, atom, sp)
602
+ new_last = _join(moved, lines[i], gaps[i - 1])
603
+ if text_width_em(new_last) > max_em or _is_weak_line(new_prev) \
604
+ or text_width_em(new_prev) < ORPHAN_MIN_EM:
605
+ break
606
+ lines[i - 1], lines[i] = new_prev, new_last
607
+ gaps[i - 1] = spaced
608
+ return lines
609
+
610
+
611
+ def _rebalance(lines: "List[str]", max_em: float,
612
+ gaps: "Optional[List[bool]]" = None) -> "List[str]":
613
+ """Move each break to the one that minimises the widest line of the pair, without changing the
614
+ line count.
615
+
616
+ Greedy wrapping fills line 1 to the brim and leaves line 2 short, which is what split eval 14's
617
+ `"A third line the tool times for me"` mid-phrase. Only spaced scripts are rebalanced: a
618
+ non-spaced script has no phrase structure in its atom list, so moving the break there only
619
+ moves the ragged edge. A break is never placed before a punctuation-only atom."""
620
+ if len(lines) < 2:
621
+ return lines
622
+ out = list(lines)
623
+ gaps = _gaps(out, gaps)
624
+ for i in range(len(out) - 1):
625
+ first, second = out[i], out[i + 1]
626
+ tail_atoms = _atoms(second)
627
+ if tail_atoms:
628
+ tail_atoms[0] = (tail_atoms[0][0], gaps[i])
629
+ atoms = _atoms(first) + tail_atoms
630
+ if not atoms or any(char_script(ch) in NO_SPACE_SCRIPTS for ch in first + second):
631
+ continue
632
+ best = None
633
+ for cut in range(1, len(atoms)):
634
+ if not atoms[cut][1]:
635
+ continue # only break where a space stood
636
+ if all(not ch.isalnum() for ch in atoms[cut][0]):
637
+ continue # never strand punctuation at the start of a line
638
+ a = b = ""
639
+ for atom, sp in atoms[:cut]:
640
+ a = _join(a, atom, sp)
641
+ for atom, sp in atoms[cut:]:
642
+ b = _join(b, atom, sp)
643
+ wa, wb = text_width_em(a), text_width_em(b)
644
+ if max(wa, wb) > max_em:
645
+ continue
646
+ key = (max(wa, wb), abs(wa - wb))
647
+ if best is None or key < best[0]:
648
+ best = (key, a, b, atoms[cut][1])
649
+ if best is not None:
650
+ out[i], out[i + 1] = best[1], best[2]
651
+ gaps[i] = best[3]
652
+ return out
653
+
654
+
655
+ def _rebalance_phrase(lines: "List[str]", max_em: float, lang: "Optional[str]",
656
+ gaps: "Optional[List[bool]]" = None, *, chinese: bool = False) -> "Tuple[List[str], int]":
657
+ """_rebalance with R1-R4 deciding, for every script rather than spaced ones only.
658
+
659
+ Returns the new lines and how many breaks a phrase rule moved away from the position 1.15's
660
+ widest-line rule alone would have chosen -- the `phrase_breaks` count in the result."""
661
+ if len(lines) < 2:
662
+ return list(lines), 0
663
+ out = list(lines)
664
+ gaps = _gaps(out, gaps)
665
+ moved = 0
666
+ for i in range(len(out) - 1):
667
+ first, second = out[i], out[i + 1]
668
+ tail_atoms = _atoms(second, chinese=chinese)
669
+ if tail_atoms:
670
+ tail_atoms[0] = (tail_atoms[0][0], gaps[i])
671
+ atoms = _split_hyphens(_atoms(first, chinese=chinese) + tail_atoms)
672
+ if chinese:
673
+ atoms = _kinsoku_atoms(atoms)
674
+ if len(atoms) < 2:
675
+ continue
676
+ cut = best_break(atoms, max_em, lang)
677
+ if cut is None:
678
+ continue
679
+ a = b = ""
680
+ for atom, sp in atoms[:cut]:
681
+ a = _join(a, atom, sp)
682
+ for atom, sp in atoms[cut:]:
683
+ b = _join(b, atom, sp)
684
+ if (a, b) != (first, second):
685
+ moved += 1
686
+ out[i], out[i + 1] = a, b
687
+ gaps[i] = atoms[cut][1]
688
+ return out, moved
689
+
690
+
691
+ def _kinsoku_atoms(atoms: "List[Tuple[str, bool]]") -> "List[Tuple[str, bool]]":
692
+ """The atom list with each no-line-start character joined to the atom before it, and each
693
+ no-line-end character to the atom after it, where no space stands between them.
694
+
695
+ The phrase passes only ever choose among breaks that fit, so a forbidden break the greedy fill
696
+ had already taken stayed whenever no pass reconsidered it: a cue of three lines or more, or
697
+ the pieces of a cue split past --max-lines, opened a line with '、', ',' or '。' (A54, #457).
698
+ Joined, the fill carries the character before the punctuation onto the next line with it."""
699
+ split: "List[Tuple[str, bool]]" = []
700
+ for atom, spaced in atoms:
701
+ # the atomiser reads a run of CJK punctuation as one Latin word ('。('): part it where a
702
+ # closing mark meets an opening one, so each half can join its own neighbour
703
+ start = 0
704
+ for k in range(1, len(atom)):
705
+ if atom[k - 1] in JA_NO_LINE_START and atom[k] in JA_NO_LINE_END:
706
+ split.append((atom[start:k], spaced if start == 0 else False))
707
+ start = k
708
+ split.append((atom[start:], spaced if start == 0 else False))
709
+ out: "List[Tuple[str, bool]]" = []
710
+ for atom, spaced in split:
711
+ if out and not spaced and (atom[0] in JA_NO_LINE_START or out[-1][0][-1] in JA_NO_LINE_END):
712
+ out[-1] = (out[-1][0] + atom, out[-1][1])
713
+ else:
714
+ out.append((atom, spaced))
715
+ return out
716
+
717
+
718
+ def _greedy_chunks(raw: str, max_em: float, *, slice_overlong: bool = False,
719
+ sliced: "Optional[List[int]]" = None,
720
+ gaps: "Optional[List[bool]]" = None, kinsoku: bool = False,
721
+ chinese: bool = False) -> "List[str]":
722
+ """The greedy fill on its own: the line count every mode must keep.
723
+
724
+ `slice_overlong` (off by default -- only caption.py's final burn-in pass turns it on, never
725
+ fit_size()'s search) is the escape hatch: an atom that lands alone on a line and is STILL
726
+ wider than `max_em` -- a fitting atom never reaches this branch, so a Thai phrase or a
727
+ katakana run that already fits is completely untouched -- is hard-sliced by _slice_atom()
728
+ instead of kept whole. `sliced`, when given, gets one entry (the number of extra lines that
729
+ one atom produced) per atom actually sliced, which is how the caller counts
730
+ `broken_inside_word` without re-deriving it from the output lines.
731
+
732
+ `gaps`, when given, is filled with one flag per break: did a space stand there in `raw`? The
733
+ passes in _balance() carry it, so a break they move keeps (or drops) exactly that space.
734
+
735
+ `kinsoku` (phrase mode) never breaks before a no-line-start or after a no-line-end character
736
+ (_kinsoku_atoms); `measured` keeps 1.15's fill."""
737
+ current = ""
738
+ current_gap = False # did a space stand before `current`'s first atom
739
+ chunk: "List[str]" = []
740
+ breaks: "List[bool]" = []
741
+
742
+ def emit(line: str, gap_before: bool) -> None:
743
+ if chunk:
744
+ breaks.append(gap_before)
745
+ chunk.append(line)
746
+
747
+ def start_line(atom: str, spaced: bool) -> "Tuple[str, bool]":
748
+ """The new current line opening with `atom`, sliced first when it is too wide alone."""
749
+ if slice_overlong and text_width_em(atom) > max_em:
750
+ pieces = _slice_atom(atom, max_em)
751
+ if sliced is not None and len(pieces) > 1:
752
+ sliced.append(len(pieces) - 1)
753
+ if len(pieces) > 1:
754
+ emit(pieces[0], spaced)
755
+ for piece in pieces[1:-1]:
756
+ emit(piece, False)
757
+ return pieces[-1], False
758
+ return atom, spaced
759
+
760
+ atoms = _atoms(raw, chinese=chinese)
761
+ for atom, spaced in (_kinsoku_atoms(atoms) if kinsoku else atoms):
762
+ if not current:
763
+ current, current_gap = start_line(atom, spaced)
764
+ continue
765
+ candidate = _join(current, atom, spaced)
766
+ if text_width_em(candidate) > max_em:
767
+ emit(current, current_gap)
768
+ current, current_gap = start_line(atom, spaced)
769
+ else:
770
+ current = candidate
771
+ if current:
772
+ emit(current, current_gap)
773
+ if gaps is not None:
774
+ gaps[:] = breaks
775
+ return chunk
776
+
777
+
778
+ def _balance(chunk: "List[str]", max_em: float, mode: str, lang: "Optional[str]",
779
+ gaps: "Optional[List[bool]]" = None, *, chinese: bool = False) -> "List[str]":
780
+ """The post-passes for one greedy chunk, in the mode's own order. Never changes the count:
781
+ a pass that would is discarded, exactly as 1.15 did."""
782
+ if len(chunk) < 2:
783
+ return chunk
784
+ gaps = list(gaps) if gaps is not None else None
785
+ if mode == "measured":
786
+ fixed = _fix_orphans(chunk, max_em, gaps)
787
+ rebalanced = _rebalance(fixed, max_em, list(gaps) if gaps is not None else None)
788
+ else:
789
+ fixed = _fix_orphans(chunk, max_em, gaps, kinsoku=True, chinese=chinese)
790
+ fixed = _fix_weak_lines(fixed, max_em, gaps, chinese=chinese)
791
+ later = list(gaps) if gaps is not None else None
792
+ rebalanced, _moved = _rebalance_phrase(fixed, max_em, lang, later, chinese=chinese)
793
+ rebalanced = _fix_weak_lines(rebalanced, max_em, later, chinese=chinese)
794
+ if len(rebalanced) == len(chunk):
795
+ return rebalanced
796
+ return fixed if len(fixed) == len(chunk) else chunk
797
+
798
+
799
+ def wrap_text(text: str, max_em: float, *, balance: bool = True, mode: str = "phrase",
800
+ lang: "Optional[str]" = None, slice_overlong: bool = False,
801
+ sliced: "Optional[List[int]]" = None) -> "List[str]":
802
+ """Wrap `text` to lines no wider than `max_em` em, keeping the manual breaks it already has.
803
+
804
+ An atom wider than the whole line (one very long word) is left alone on its line rather than
805
+ cut mid-word: an over-long line is readable, a chopped word is not.
806
+
807
+ `mode="phrase"` (the default since 1.16) then applies the four phrase rules -- never inside a
808
+ word or across a hyphen's wrong side (R1), no line that is a lone digit, punctuation or kana
809
+ (R2), Japanese/Chinese breaks preferred at sentence ends and after particles, never before one
810
+ and never inside a word (R3), and an article or preposition kept with the phrase it governs by
811
+ preferring the break before it and avoiding the break after it (R4). `mode="measured"` is
812
+ 1.15's behaviour exactly: no one-character orphan line, and a break chosen only to minimise the
813
+ widest line. Neither mode ever changes the number of lines the greedy fill produced.
814
+ """
815
+ lines: "List[str]" = []
816
+ chinese = _protect_chinese_words(text, mode, lang)
817
+ for raw in text.split("\n"):
818
+ if not raw.strip():
819
+ continue
820
+ gaps: "List[bool]" = []
821
+ chunk = _greedy_chunks(raw, max_em, slice_overlong=slice_overlong, sliced=sliced, gaps=gaps,
822
+ kinsoku=mode == "phrase", chinese=chinese)
823
+ lines.extend(_balance(chunk, max_em, mode, lang, gaps, chinese=chinese) if balance else chunk)
824
+ return lines or [text]
825
+ def wrap_variants(text: str, max_em: float, *, mode: str = "phrase",
826
+ lang: "Optional[str]" = None, slice_overlong: bool = False,
827
+ sliced: "Optional[List[int]]" = None) -> "Tuple[List[str], List[str], List[str]]":
828
+ """`(wrapped, greedy, measured)` for one cue from a single greedy fill.
829
+
830
+ layout_cues needs all three -- `wrapped` is what is burnt in, `greedy` is what `rebalanced`
831
+ counts against and `measured` what `phrase_breaks` counts against -- and used to call
832
+ wrap_text() three times, re-running the atomiser and the greedy fill each time. The fill is
833
+ the same for every mode, so it is done once here and only the post-passes are repeated.
834
+ `measured` is the same list object as `wrapped` when that is already the mode.
835
+ """
836
+ wrapped: "List[str]" = []
837
+ greedy: "List[str]" = []
838
+ measured: "List[str]" = []
839
+ chinese = _protect_chinese_words(text, mode, lang)
840
+ for raw in text.split("\n"):
841
+ if not raw.strip():
842
+ continue
843
+ gaps: "List[bool]" = []
844
+ chunk = _greedy_chunks(raw, max_em, slice_overlong=slice_overlong, sliced=sliced, gaps=gaps,
845
+ kinsoku=mode == "phrase", chinese=chinese)
846
+ greedy.extend(chunk)
847
+ wrapped.extend(_balance(list(chunk), max_em, mode, lang, gaps, chinese=chinese))
848
+ if mode == "measured":
849
+ measured.extend(chunk)
850
+ else:
851
+ # 1.15's wrap fills without the kinsoku joins (A54), so it is filled on its own
852
+ plain_gaps: "List[bool]" = []
853
+ plain = _greedy_chunks(raw, max_em, slice_overlong=slice_overlong, gaps=plain_gaps)
854
+ measured.extend(_balance(plain, max_em, "measured", None, plain_gaps))
855
+ if not greedy:
856
+ greedy = [text]
857
+ return (wrapped or [text], greedy, measured or [text])
858
+
859
+
860
+ # --- caption size that fits the cue (1.17) -------------------------------------------------
861
+ # The legibility floor: 4.5 % of the frame height, ass_units(0.045) = 13 against the 288-line
862
+ # ASS script grid. One floor for every destination -- 87 px of type on a 1920-tall frame, above
863
+ # the ~3.5 % where mobile legibility bottoms out and where the platforms' own caption UIs sit.
864
+ # Nothing per-platform is measured, so nothing per-platform is claimed. (The eval-17 cues happen
865
+ # to land exactly on it: 13 is the smallest size at which every one of them fits two lines.)
866
+ MIN_CAPTION_FRACTION = 0.045
867
+ ASS_SCRIPT_HEIGHT = 288 # caption.py's --size/--margin reference grid; mirrors _platforms
868
+
869
+
870
+ def line_em_for_size(size: float, play_w: "Optional[int]", play_h: "Optional[int]", *,
871
+ safe_fraction: float = SAFE_WIDTH_FRACTION,
872
+ script_height: int = ASS_SCRIPT_HEIGHT) -> "Optional[float]":
873
+ """How many em fit on one caption line at `size`, or None without geometry.
874
+
875
+ `size` is in ASS points against a `script_height`-line script (what libass's force_style
876
+ uses), so the rendered pixel size is size * play_h / script_height. This is the one width
877
+ formula: caption.py::max_line_em and fit_size() both call it.
878
+ """
879
+ if not play_w or not play_h or not size:
880
+ return None
881
+ size_px = size * play_h / float(script_height)
882
+ if size_px <= 0:
883
+ return None
884
+ return (play_w * safe_fraction) / size_px
885
+
886
+
887
+ def fit_size(cues, *, size: int, min_size: "Optional[int]" = None, max_lines: int = 2,
888
+ play_w: "Optional[int]" = None, play_h: "Optional[int]" = None,
889
+ safe_fraction: float = SAFE_WIDTH_FRACTION, mode: str = "phrase",
890
+ lang: "Optional[str]" = None, script_height: int = ASS_SCRIPT_HEIGHT,
891
+ step: int = 1, scope: str = "file") -> "Dict[str, Any]":
892
+ """The largest size in [min_size, size] at which every cue wraps to <= max_lines lines.
893
+
894
+ Pure: strings and integers in, a dict out. No ffmpeg, no ffprobe, no I/O -- the caption size
895
+ is a text-measurement decision, and measuring it must not need a subprocess.
896
+
897
+ `cues` is an iterable of cue texts (or of (start, end, text) tuples, as caption.py holds
898
+ them before layout). Returns
899
+ {"size", "floor", "requested", "scope", "shrunk", "fits", "per_cue", "max_em", "steps"}.
900
+
901
+ The search is a linear walk downwards, not a bisection, and deliberately so:
902
+ len(wrap_text(t, max_em)) is NOT guaranteed monotone in max_em under the phrase rules -- a
903
+ rebalance that is discarded at one width can be applied at the next -- and a non-monotone
904
+ predicate breaks bisection. 24 -> 13 is at most twelve iterations of pure string work.
905
+
906
+ `scope="cue"` returns one size per cue index in `per_cue`, with `size` the minimum of them;
907
+ the caller writes a per-cue {\\fsN} override. The default is `scope="file"`: a caption track
908
+ whose type size changes from cue to cue reads as a mistake, and one measured line width per
909
+ file is what makes the wrap behaviour reproducible.
910
+ """
911
+ # `texts` stays parallel to `cues`: a blank cue becomes None rather than being dropped, so
912
+ # per_cue[i] always refers to the caller's cue i. caption.py indexes layout by these keys.
913
+ texts: "List[Optional[str]]" = []
914
+ for cue in cues or []:
915
+ if isinstance(cue, (tuple, list)):
916
+ raw = cue[2] if len(cue) > 2 else cue[-1]
917
+ else:
918
+ raw = cue
919
+ texts.append(raw if raw and str(raw).strip() else None)
920
+ measurable = [t for t in texts if t is not None]
921
+ requested = int(size)
922
+ floor = int(min_size) if min_size is not None else ass_units_local(MIN_CAPTION_FRACTION,
923
+ script_height)
924
+ floor = max(1, min(floor, requested))
925
+ step = max(1, int(step))
926
+ result: "Dict[str, Any]" = {"size": requested, "floor": floor, "requested": requested,
927
+ "scope": scope, "shrunk": 0, "fits": True, "per_cue": {},
928
+ "max_em": None, "steps": 0}
929
+ em_at = lambda sz: line_em_for_size(sz, play_w, play_h, safe_fraction=safe_fraction,
930
+ script_height=script_height)
931
+ base_em = em_at(requested)
932
+ result["max_em"] = base_em
933
+ if not measurable or base_em is None or max_lines < 1:
934
+ # No geometry means no measurable width: leave the size exactly as asked.
935
+ return result
936
+
937
+ def lines_at(text: str, sz: int) -> int:
938
+ em = em_at(sz)
939
+ if em is None:
940
+ return 1
941
+ return len(wrap_text(text, em, mode=mode, lang=lang))
942
+
943
+ over_at_requested = [t for t in measurable if lines_at(t, requested) > max_lines]
944
+ result["shrunk"] = len(over_at_requested)
945
+
946
+ def best_for(subset) -> "Tuple[int, bool]":
947
+ """(largest size in [floor, requested] fitting every text in `subset`, did it fit)."""
948
+ sz = requested
949
+ while sz >= floor:
950
+ result["steps"] += 1
951
+ if all(lines_at(t, sz) <= max_lines for t in subset):
952
+ return sz, True
953
+ sz -= step
954
+ return floor, all(lines_at(t, floor) <= max_lines for t in subset)
955
+
956
+ if scope == "cue":
957
+ per_cue = {}
958
+ fits_all = True
959
+ for i, t in enumerate(texts):
960
+ if t is None:
961
+ per_cue[i] = requested # a blank cue draws nothing; it constrains nothing
962
+ continue
963
+ sz, ok = best_for([t])
964
+ per_cue[i] = sz
965
+ fits_all = fits_all and ok
966
+ result["per_cue"] = per_cue
967
+ sized = [v for i, v in per_cue.items() if texts[i] is not None]
968
+ result["size"] = min(sized) if sized else requested
969
+ result["fits"] = fits_all
970
+ else:
971
+ sz, ok = best_for(measurable)
972
+ result["size"] = sz
973
+ result["fits"] = ok
974
+ result["max_em"] = em_at(result["size"])
975
+ return result
976
+
977
+
978
+ def ass_units_local(fraction: float, script_height: int = ASS_SCRIPT_HEIGHT) -> int:
979
+ """`fraction` of the frame height in ASS units. Mirrors _platforms.ass_units, kept here so
980
+ _common.text stays importable without the scripts/ top level on sys.path."""
981
+ return int(round(fraction * script_height))