A Claude Code plugin that turns a story into a finished anime
Ruby
Add the Ruby toolkit: Fal client, pipeline steps, episode tools and specs
Francesco 'makevoid' Canessafd4fd810ac33
diff --git a/skills/make-an-anime/scripts/.gitignore b/skills/make-an-anime/scripts/.gitignorenew file mode 100644index 0000000..1fc8445--- /dev/null+++ b/skills/make-an-anime/scripts/.gitignore@@ -0,0 +1,17 @@+output/+tmp/+specs/+node_modules/+.venv/+tools/vfx/.build/+.bundle/+audio/+.env++**/__pycache__/+*.pyc+**/prompts/e2e-*/+**/prompts/live-vfx-*/+**/prompts/anime-scene-*/+config/+**/prompts/anime-timeline-*/diff --git a/skills/make-an-anime/scripts/Gemfile b/skills/make-an-anime/scripts/Gemfilenew file mode 100644index 0000000..5f0a3e8--- /dev/null+++ b/skills/make-an-anime/scripts/Gemfile@@ -0,0 +1,5 @@+source "https://rubygems.org"+gem "excon", "~> 1.7"+gem "json", "~> 3.0"+gem "rake", "~> 13.4"+gem "rspec", "~> 3.13"diff --git a/skills/make-an-anime/scripts/Gemfile.lock b/skills/make-an-anime/scripts/Gemfile.locknew file mode 100644index 0000000..3d675a9--- /dev/null+++ b/skills/make-an-anime/scripts/Gemfile.lock@@ -0,0 +1,48 @@+GEM+ remote: https://rubygems.org/+ specs:+ diff-lcs (1.6.2)+ excon (1.7.1)+ logger+ json (3.0.2)+ logger (1.7.0)+ rake (13.4.2)+ rspec (3.13.2)+ rspec-core (~> 3.13.0)+ rspec-expectations (~> 3.13.0)+ rspec-mocks (~> 3.13.0)+ rspec-core (3.13.6)+ rspec-support (~> 3.13.0)+ rspec-expectations (3.13.5)+ diff-lcs (>= 1.2.0, < 2.0)+ rspec-support (~> 3.13.0)+ rspec-mocks (3.13.8)+ diff-lcs (>= 1.2.0, < 2.0)+ rspec-support (~> 3.13.0)+ rspec-support (3.13.7)++PLATFORMS+ arm64-darwin-25+ ruby++DEPENDENCIES+ excon (~> 1.7)+ json (~> 3.0)+ rake (~> 13.4)+ rspec (~> 3.13)++CHECKSUMS+ bundler (4.0.20) sha256=7978a8ac648767f5e635bc522445b79e80a52b907a39a36c2d8085ed6bc762ae+ diff-lcs (1.6.2) sha256=9ae0d2cba7d4df3075fe8cd8602a8604993efc0dfa934cff568969efb1909962+ excon (1.7.1) sha256=dd2d870eece1b5ce4e4f9efd938e67a69ccd8c003c3825b638b937e1082eaac2+ json (3.0.2) sha256=8e6d7e7b11384c21230430cef90b71f14849a34a1f4452796670f7c981bd19df+ logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203+ rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701+ rspec (3.13.2) sha256=206284a08ad798e61f86d7ca3e376718d52c0bc944626b2349266f239f820587+ rspec-core (3.13.6) sha256=a8823c6411667b60a8bca135364351dda34cd55e44ff94c4be4633b37d828b2d+ rspec-expectations (3.13.5) sha256=33a4d3a1d95060aea4c94e9f237030a8f9eae5615e9bd85718fe3a09e4b58836+ rspec-mocks (3.13.8) sha256=086ad3d3d17533f4237643de0b5c42f04b66348c28bf6b9c2d3f4a3b01af1d47+ rspec-support (3.13.7) sha256=0640e5570872aafefd79867901deeeeb40b0c9875a36b983d85f54fb7381c47c++BUNDLED WITH+ 4.0.20diff --git a/skills/make-an-anime/scripts/Rakefile b/skills/make-an-anime/scripts/Rakefilenew file mode 100644index 0000000..bd24742--- /dev/null+++ b/skills/make-an-anime/scripts/Rakefile@@ -0,0 +1,2 @@+require_relative "lib/tasks"+Toolkit::Tasks.installdiff --git a/skills/make-an-anime/scripts/lib/fal/client.rb b/skills/make-an-anime/scripts/lib/fal/client.rbnew file mode 100644index 0000000..7d31bb0--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/client.rb@@ -0,0 +1,150 @@+require "excon"+require "json"+require "uri"+require "logger"+require "fileutils"+require "digest"++module Fal+ class Error < StandardError; end++ class RequestError < Error+ attr_reader :status, :body++ def initialize(status, body)+ @status = status+ @body = body+ super("fal request failed (HTTP #{status}): #{body}")+ end+ end++ # Thin Excon wrapper around the fal queue API:+ # POST https://queue.fal.run/{endpoint_id} -> { request_id, status_url, response_url }+ # GET {status_url}?logs=1 -> { status: IN_QUEUE | IN_PROGRESS | COMPLETED }+ # GET {response_url} -> model output+ class Client+ QUEUE_HOST = "https://queue.fal.run".freeze+ STORAGE_INITIATE = "https://rest.alpha.fal.ai/storage/upload/initiate?storage_type=fal-cdn-v3".freeze++ attr_reader :logger++ def initialize(api_key: nil, logger: Logger.new($stderr), poll_interval: 3, timeout: 1800)+ @api_key = api_key || ENV["FAL_AI_API_KEY"]+ raise Error, 'Missing FAL_AI_API_KEY; configure the plugin or set this environment variable for local development' if @api_key.to_s.strip.empty?+ @logger = logger+ @poll_interval = poll_interval+ @timeout = timeout+ end++ # Submit + poll + fetch result. Returns [request_id, result_hash].+ def run(endpoint_id, input)+ require_relative "../workflow/approval"+ Workflow::Approval.new.check!+ require "digest"+ FileUtils.mkdir_p("output/requests")+ fingerprint = Digest::SHA256.hexdigest(JSON.generate([endpoint_id, input]))+ receipt = "output/requests/#{fingerprint}.json"+ File.open("#{receipt}.lock", File::CREAT | File::RDWR) do |lock|+ lock.flock(File::LOCK_EX)+ if File.exist?(receipt) && ENV["NEW_REQUEST"] != "1"+ submission = JSON.parse(File.read(receipt))+ # FORCE recomputes but deliberately resumes identical paid requests; say so, since a "retake" of an unchanged+ # prompt would otherwise silently return the same take.+ logger.warn("[fal] #{endpoint_id}: identical input, reusing receipt #{receipt} (same result). For a new take change the prompt or seed, or set NEW_REQUEST=1.") if ENV["FORCE"] == "1"+ else+ submission = submit(endpoint_id, input)+ File.write("#{receipt}.tmp", JSON.pretty_generate(submission))+ File.rename("#{receipt}.tmp", receipt)+ end+ request_id = submission.fetch("request_id")+ logger.info("[fal] #{endpoint_id} request_id=#{request_id}; receipt=#{receipt}")+ wait(submission.fetch("status_url"))+ return [request_id, get_json(submission.fetch("response_url"))]+ end+ end++ # Re-fetch a completed request's output (queue results are addressed by app id,+ # i.e. the first two path segments: fal-ai/nano-banana-2/edit -> fal-ai/nano-banana-2).+ def result(endpoint_id, request_id)+ get_json("#{QUEUE_HOST}/#{endpoint_id.split("/").first(2).join("/")}/requests/#{request_id}")+ end++ def submit(endpoint_id, input)+ request(:post, "#{QUEUE_HOST}/#{endpoint_id}", body: JSON.generate(input))+ end++ def wait(status_url)+ started = Time.now+ last_log = 0+ loop do+ status = get_json("#{status_url}?logs=1")+ logs = Array(status["logs"])+ logs[last_log..]&.each { |l| logger.info("[fal] #{l["message"]}") }+ last_log = logs.size+ case status["status"]+ when "COMPLETED"+ raise Error, "fal job failed: #{status["error"]}" if status["error"]+ return status+ when "IN_QUEUE"+ logger.info("[fal] queued (position #{status["queue_position"]})")+ end+ raise Error, "timed out after #{@timeout}s" if Time.now - started > @timeout+ sleep @poll_interval+ end+ end++ def get_json(url)+ request(:get, url)+ end++ # Upload a local file to fal CDN, returns a public URL usable as *_url input.+ def upload(path, content_type: Media.mime_type(path))+ FileUtils.mkdir_p("output/uploads")+ key = Digest::SHA256.hexdigest([Digest::SHA256.file(path).hexdigest, content_type].join(":"))+ cache = "output/uploads/#{key}.json"+ File.open("#{cache}.lock", File::CREAT | File::RDWR) do |lock|+ lock.flock(File::LOCK_EX)+ return JSON.parse(File.read(cache)).fetch("url") if File.file?(cache) && ENV["REFRESH_UPLOAD"] != "1"+ url = upload_uncached(path, content_type: content_type)+ File.write("#{cache}.tmp", JSON.generate(url: url))+ File.rename("#{cache}.tmp", cache)+ url+ end+ end++ def upload_uncached(path, content_type: Media.mime_type(path))+ init = request(:post, STORAGE_INITIATE,+ body: JSON.generate(content_type: content_type, file_name: File.basename(path)))+ resp = Excon.put(init.fetch("upload_url"),+ body: File.binread(path),+ headers: { "Content-Type" => content_type })+ raise RequestError.new(resp.status, resp.body) unless (200..299).cover?(resp.status)+ logger.info("[fal] uploaded #{path} -> #{init["file_url"]}")+ init.fetch("file_url")+ end++ # Download a fal CDN URL to a local path.+ def download(url, path)+ File.open(path, "wb") do |f|+ streamer = ->(chunk, _remaining, _total) { f.write(chunk) }+ resp = Excon.get(url, response_block: streamer, middlewares: Excon.defaults[:middlewares] + [Excon::Middleware::RedirectFollower])+ raise RequestError.new(resp.status, "download #{url}") unless resp.status == 200+ end+ logger.info("[fal] downloaded #{url} -> #{path}")+ path+ end++ private++ def request(method, url, body: nil)+ resp = Excon.new(url, read_timeout: 120, write_timeout: 300).request(+ method: method,+ body: body,+ headers: { "Authorization" => "Key #{@api_key}", "Content-Type" => "application/json", "Accept" => "application/json" },+ idempotent: method == :get, retry_limit: 3+ )+ raise RequestError.new(resp.status, resp.body) unless (200..299).cover?(resp.status)+ resp.body.empty? ? {} : JSON.parse(resp.body)+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/base.rb b/skills/make-an-anime/scripts/lib/fal/models/base.rbnew file mode 100644index 0000000..d65709a--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/base.rb@@ -0,0 +1,45 @@+module Fal+ module Models+ # Base for a single fal endpoint. Subclasses set ENDPOINT and DEFAULTS+ # and expose an intention-revealing method (generate / edit / animate ...).+ class Base+ Result = Struct.new(:request_id, :input, :output, keyword_init: true)++ def self.endpoint = self::ENDPOINT+ def self.defaults = const_defined?(:DEFAULTS) ? self::DEFAULTS : {}++ attr_reader :client++ def initialize(client: Fal::Client.new)+ @client = client+ end++ def call(**input)+ input = self.class.defaults.merge(input).compact+ validate!(input)+ request_id, output = client.run(self.class.endpoint, input)+ Result.new(request_id: request_id, input: input, output: output)+ end++ private++ # Validate input against the fetched OpenAPI spec (rake openapi:fetch).+ def validate!(input)+ path = Fal::OpenAPI.spec_path(self.class.endpoint)+ return unless File.exist?(path)+ schema = Fal::OpenAPI.load(self.class.endpoint).input_schema+ props = schema["properties"] || {}+ missing = Array(schema["required"]).map(&:to_sym) - input.keys+ raise ArgumentError, "#{self.class.endpoint}: missing #{missing.join(", ")}" if missing.any?+ input.each do |key, value|+ prop = props[key.to_s] or raise ArgumentError, "#{self.class.endpoint}: unknown param #{key}"+ if prop["enum"] && !prop["enum"].include?(value)+ raise ArgumentError, "#{self.class.endpoint}: #{key}=#{value.inspect} not in #{prop["enum"].inspect}"+ end+ raise ArgumentError, "#{key} < #{prop["minimum"]}" if prop["minimum"] && value.is_a?(Numeric) && value < prop["minimum"]+ raise ArgumentError, "#{key} > #{prop["maximum"]}" if prop["maximum"] && value.is_a?(Numeric) && value > prop["maximum"]+ end+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/demucs.rb b/skills/make-an-anime/scripts/lib/fal/models/demucs.rbnew file mode 100644index 0000000..b94ae4c--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/demucs.rb@@ -0,0 +1,16 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/fal-ai/demucs: music source separation into stems (vocals, drums, bass, other, …). The vocal stem drives+ # H3's lip-sync without the band, so the mouth rests in the singer's pauses (mv2-s7, Mom's lines).+ class Demucs < Base+ ENDPOINT = "fal-ai/demucs".freeze+ DEFAULTS = { model: "htdemucs_ft", output_format: "wav" }.freeze++ def separate(audio_url:, **opts)+ call(audio_url: audio_url, **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/eleven_music25.rb b/skills/make-an-anime/scripts/lib/fal/models/eleven_music25.rbnew file mode 100644index 0000000..183b0f2--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/eleven_music25.rb@@ -0,0 +1,22 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/elevenlabs/music/v2.5 — the episode score. Either a plain `prompt` (+ music_length_ms,+ # force_instrumental) or a `composition_plan: { chunks: [{ text, duration_ms, positive_styles, negative_styles,+ # context_adherence }] }` whose chunks follow the storyboard's beats (3–120 s each, at most 30).+ class ElevenMusic25 < Base+ ENDPOINT = "elevenlabs/music/v2.5".freeze+ DEFAULTS = { output_format: "mp3_48000_192" }.freeze++ # Same keyword shape as Music3#compose, so the Music step can call either model.+ def compose(prompt: nil, composition_plan: nil, duration: nil, lyrics: nil, seed: nil, **opts)+ if composition_plan+ call(composition_plan: composition_plan, seed: seed, **opts)+ else+ call(prompt: prompt, music_length_ms: duration && (duration * 1000).round, force_instrumental: lyrics.to_s.strip.empty?, **opts)+ end+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/eleven_tts_v4.rb b/skills/make-an-anime/scripts/lib/fal/models/eleven_tts_v4.rbnew file mode 100644index 0000000..1123114--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/eleven_tts_v4.rb@@ -0,0 +1,18 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/elevenlabs/tts/eleven-v4 — one character's line of dialogue or narration.+ # `voice` is an ElevenLabs voice name (Aria, Roger, Sarah, Laura, Charlie, George, Callum, River, Liam, Charlotte, Alice,+ # Matilda, Will, Jessica, Eric, Chris, Brian, Daniel, Lily, Bill, …) or voice ID. The text accepts audio tags such as+ # [whispering], [sleepy], [softly] and IPA in /slashes/. timestamps: true returns per-word timings for lip-sync and cues.+ class ElevenTtsV4 < Base+ ENDPOINT = "elevenlabs/tts/eleven-v4".freeze+ DEFAULTS = { output_format: "mp3_44100_192", timestamps: true, stability: 0.5, similarity_boost: 0.75 }.freeze++ def speak(text:, voice:, **opts)+ call(text: text, voice: voice, **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/gpt_image25.rb b/skills/make-an-anime/scripts/lib/fal/models/gpt_image25.rbnew file mode 100644index 0000000..0ee0914--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/gpt_image25.rb@@ -0,0 +1,18 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/openai/gpt-image-2.5/sunburst/text-to-image+ class GptImage25 < Base+ ENDPOINT = "openai/gpt-image-2.5/sunburst/text-to-image".freeze+ DEFAULTS = { quality: "xhigh", output_format: "png", num_images: 1 }.freeze+ # Explicit sizes (multiples of 16) matching nano-banana-2's 2K output, so generations compare 1:1.+ SIZES = { "16:9" => { width: 2752, height: 1536 } }.freeze++ # Same signature as NanoBanana2#generate; this endpoint has no seed param.+ def generate(prompt:, aspect_ratio: "16:9", seed: nil, **opts)+ call(prompt: prompt, image_size: SIZES.fetch(aspect_ratio), **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/gpt_image25_edit.rb b/skills/make-an-anime/scripts/lib/fal/models/gpt_image25_edit.rbnew file mode 100644index 0000000..54c3842--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/gpt_image25_edit.rb@@ -0,0 +1,15 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/openai/gpt-image-2.5/sunburst/edit — new frames of an existing character (keyframes).+ class GptImage25Edit < Base+ ENDPOINT = "openai/gpt-image-2.5/sunburst/edit".freeze+ DEFAULTS = { quality: "xhigh", output_format: "png", num_images: 1 }.freeze++ def edit(prompt:, image_urls:, aspect_ratio: "16:9", **opts)+ call(prompt: prompt, image_urls: image_urls, image_size: GptImage25::SIZES.fetch(aspect_ratio), **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/h3_max_image_to_video.rb b/skills/make-an-anime/scripts/lib/fal/models/h3_max_image_to_video.rbnew file mode 100644index 0000000..c4b4831--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/h3_max_image_to_video.rb@@ -0,0 +1,18 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/minimax/h3-max/image-to-video+ # Anime default: 768P native (H3 has no 720P tier; 480P/768P/1080P), the edit is upscaled to the 1080p delivery.+ # VIDEO_RES=1080P selects H3's latent refinement for a hero shot.+ class H3MaxImageToVideo < Base+ ENDPOINT = "minimax/h3-max/image-to-video".freeze+ DEFAULT_RES = "768P".freeze+ DEFAULTS = { resolution: DEFAULT_RES, prompt_expansion_mode: "disabled", enable_safety_checker: true }.freeze++ def animate(prompt:, image_url:, duration:, target_audio_url: nil, **opts)+ call(prompt: prompt, image_url: image_url, duration: duration, target_audio_url: target_audio_url, **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/music3.rb b/skills/make-an-anime/scripts/lib/fal/models/music3.rbnew file mode 100644index 0000000..4e0658f--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/music3.rb@@ -0,0 +1,15 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/minimax/music-3+ class Music3 < Base+ ENDPOINT = "minimax/music-3".freeze+ DEFAULTS = { num_inference_steps: 30, guidance_scale: 1.7 }.freeze++ def compose(prompt:, lyrics:, duration:, **opts)+ call(prompt: prompt, lyrics: lyrics, duration: duration, **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/nano_banana2.rb b/skills/make-an-anime/scripts/lib/fal/models/nano_banana2.rbnew file mode 100644index 0000000..b403db1--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/nano_banana2.rb@@ -0,0 +1,25 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/fal-ai/nano-banana-2 (text-to-image)+ class NanoBanana2 < Base+ ENDPOINT = "fal-ai/nano-banana-2".freeze+ DEFAULTS = { output_format: "png", resolution: "2K", num_images: 1 }.freeze++ def generate(prompt:, aspect_ratio: "16:9", **opts)+ call(prompt: prompt, aspect_ratio: aspect_ratio, **opts)+ end+ end++ # https://fal.ai/models/fal-ai/nano-banana-2/edit (image editing w/ reference images)+ class NanoBanana2Edit < Base+ ENDPOINT = "fal-ai/nano-banana-2/edit".freeze+ DEFAULTS = { output_format: "png", resolution: "2K", num_images: 1 }.freeze++ def edit(prompt:, image_urls:, aspect_ratio: "auto", **opts)+ call(prompt: prompt, image_urls: Array(image_urls), aspect_ratio: aspect_ratio, **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/stable_audio_sfx.rb b/skills/make-an-anime/scripts/lib/fal/models/stable_audio_sfx.rbnew file mode 100644index 0000000..d460884--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/stable_audio_sfx.rb@@ -0,0 +1,14 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/fal-ai/stable-audio-3/small/sfx/text-to-audio: short sound effects from a text prompt.+ class StableAudioSfx < Base+ ENDPOINT = "fal-ai/stable-audio-3/small/sfx/text-to-audio".freeze++ def generate(prompt:, **opts)+ call(prompt: prompt, **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/models/whisper.rb b/skills/make-an-anime/scripts/lib/fal/models/whisper.rbnew file mode 100644index 0000000..cbd3677--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/models/whisper.rb@@ -0,0 +1,15 @@+require_relative "base"++module Fal+ module Models+ # https://fal.ai/models/fal-ai/whisper — used in reviews to verify sung lyrics.+ class Whisper < Base+ ENDPOINT = "fal-ai/whisper".freeze+ DEFAULTS = { task: "transcribe", language: "en", chunk_level: "segment" }.freeze++ def transcribe(audio_url:, **opts)+ call(audio_url: audio_url, **opts)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal/openapi.rb b/skills/make-an-anime/scripts/lib/fal/openapi.rbnew file mode 100644index 0000000..d404090--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal/openapi.rb@@ -0,0 +1,63 @@+require "excon"+require "json"+require "fileutils"++module Fal+ # Fetches and summarizes fal queue OpenAPI specs:+ # https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=<id>+ class OpenAPI+ BASE = "https://fal.ai/api/openapi/queue/openapi.json".freeze++ attr_reader :endpoint_id, :spec++ def self.spec_path(endpoint_id, dir: "specs")+ File.join(dir, "#{endpoint_id.tr("/", "_")}.json")+ end++ def self.fetch(endpoint_id, dir: "specs")+ resp = Excon.get(BASE, query: { endpoint_id: endpoint_id })+ raise Error, "OpenAPI fetch failed for #{endpoint_id}: HTTP #{resp.status}" unless resp.status == 200+ FileUtils.mkdir_p(dir)+ File.write(spec_path(endpoint_id, dir: dir), JSON.pretty_generate(JSON.parse(resp.body)))+ load(endpoint_id, dir: dir)+ end++ def self.load(endpoint_id, dir: "specs")+ new(endpoint_id, JSON.parse(File.read(spec_path(endpoint_id, dir: dir))))+ end++ def initialize(endpoint_id, spec)+ @endpoint_id = endpoint_id+ @spec = spec+ end++ def schemas+ spec.dig("components", "schemas") || {}+ end++ def input_schema+ schemas.find { |name, _| name.end_with?("Input") }&.last || {}+ end++ def output_schema+ schemas.find { |name, _| name.end_with?("Output") }&.last || {}+ end++ # Human-readable summary of input params (name, type, default, enum, required).+ def summary+ required = Array(input_schema["required"])+ lines = ["# #{endpoint_id}", "## input"]+ (input_schema["properties"] || {}).each do |name, prop|+ type = prop["type"] || prop["anyOf"]&.map { |t| t["type"] || t["$ref"]&.split("/")&.last }&.join("|") || prop["$ref"]&.split("/")&.last || prop.dig("allOf", 0, "$ref")&.split("/")&.last+ enum = prop["enum"] ? " enum=#{prop["enum"].inspect}" : ""+ dflt = prop.key?("default") ? " default=#{prop["default"].inspect}" : ""+ range = [prop["minimum"] && "min=#{prop["minimum"]}", prop["maximum"] && "max=#{prop["maximum"]}"].compact.join(" ")+ lines << "- #{name}#{required.include?(name) ? "*" : ""} (#{type})#{enum}#{dflt} #{range}".rstrip+ lines << " #{prop["description"].to_s.gsub(/\s+/, " ")[0, 220]}" if prop["description"]+ end+ lines << "## output"+ (output_schema["properties"] || {}).each { |name, prop| lines << "- #{name} (#{prop["type"] || prop["$ref"]&.split("/")&.last || "object"})" }+ lines.join("\n")+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/fal_mv_gen.rb b/skills/make-an-anime/scripts/lib/fal_mv_gen.rbnew file mode 100644index 0000000..09c0b40--- /dev/null+++ b/skills/make-an-anime/scripts/lib/fal_mv_gen.rb@@ -0,0 +1,27 @@+$LOAD_PATH.unshift(__dir__)+require "uri"+Dir[File.join(__dir__, "media", "*.rb")].sort.each { |f| require f }+require "fal/client"+require "fal/openapi"+Dir[File.join(__dir__, "fal", "models", "*.rb")].sort.each { |f| require f }+require "pipeline/project"+require "pipeline/step"+require "pipeline/items_step"+require "pipeline/generation_config"+Dir[File.join(__dir__, "pipeline", "steps", "*.rb")].sort.each { |f| require f }+module Pipeline+ DEFAULT_RUN = "s01"+ ALL_STEPS = [Steps::RefBase, Steps::RefTorn, Steps::Dialogue, Steps::Music, Steps::Mix, Steps::Keyframes,+ Steps::Video, Steps::Shots, Steps::Clips, Steps::Overlay].freeze+ def self.section(at, frames)+ raise ArgumentError, "at and frames must be integer frame counts" unless at.is_a?(Integer) && at >= 0 && frames.is_a?(Integer) && frames > 0+ { music_from: "audio/song.wav", music_offset: at / 24.0, frames: frames, lyrics: [] }+ end++ # An anime scene: its own dialogue, score and soundtrack, `frames` long at 24fps (scenes are joined in order with media:concat).+ def self.scene(frames, **opts)+ raise ArgumentError, "frames must be a positive integer frame count" unless frames.is_a?(Integer) && frames > 0+ { frames: frames, upload_music: false, **opts }+ end+ GENERATIONS = GenerationConfig.new(ROOT).load.freeze+enddiff --git a/skills/make-an-anime/scripts/lib/media/anim.rb b/skills/make-an-anime/scripts/lib/media/anim.rbnew file mode 100644index 0000000..a3ac0e3--- /dev/null+++ b/skills/make-an-anime/scripts/lib/media/anim.rb@@ -0,0 +1,19 @@+require "json"+require_relative "shell"++module Media+ # Renders p5.js sketches to transparent PNG sequences with anim/render.mjs (headless Chrome via puppeteer-core).+ # Helpers live in tools/p5/lib/; selected project fonts in tools/p5/fonts/.+ class Anim < Shell+ RENDER = File.expand_path("../../tools/p5/render.mjs", __dir__)++ # data: { name => json_path } is exposed to the sketch as Anim.data(name). only: [frame indices] for previews.+ # Returns the renderer's summary ({ "out", "frames", "width", "height", "fps", "ms" }).+ def render(sketch, out, width:, height:, fps:, frames:, data: {}, only: nil)+ args = [RENDER, sketch, "--out", out, "--width", width, "--height", height, "--fps", fps, "--frames", frames]+ args += ["--only", only.join(",")] if only+ data.each { |name, path| args += ["--data", "#{name}=#{path}"] }+ JSON.parse(run("node", *args).lines.last)+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/media/ffmpeg.rb b/skills/make-an-anime/scripts/lib/media/ffmpeg.rbnew file mode 100644index 0000000..fe5ed9e--- /dev/null+++ b/skills/make-an-anime/scripts/lib/media/ffmpeg.rb@@ -0,0 +1,350 @@+require "json"+require_relative "shell"++module Media+ # ffmpeg / ffprobe wrapper for probing, review sheets and audio/video assembly.+ class FFmpeg < Shell+ def probe(path)+ JSON.parse(run("ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", path, quiet: true))+ end++ def duration(path)+ probe(path).dig("format", "duration").to_f+ end++ # Compact stream summary: { duration:, video: {w,h,fps,codec}, audio: {codec,rate,channels} }+ def summary(path)+ info = probe(path)+ v = info["streams"].find { |s| s["codec_type"] == "video" }+ a = info["streams"].find { |s| s["codec_type"] == "audio" }+ {+ duration: info.dig("format", "duration").to_f.round(3),+ size_mb: (info.dig("format", "size").to_f / 1_048_576).round(2),+ video: v && { codec: v["codec_name"], w: v["width"], h: v["height"], fps: fps(v["avg_frame_rate"]), frames: v["nb_frames"]&.to_i },+ audio: a && { codec: a["codec_name"], rate: a["sample_rate"].to_i, channels: a["channels"] }+ }.compact+ end++ # Grid of evenly spaced frames (default 5x2 = 10 frames) for visual review.+ def contact_sheet(video, out, cols: 5, rows: 2, width: 384)+ FileUtils.mkdir_p(File.dirname(out))+ n = cols * rows+ rate = n / duration(video)+ label = filter?("drawtext") ? ",drawtext=fontfile='#{FONT}':text='%{pts\\:hms}':x=6:y=6:fontsize=16:fontcolor=white:box=1:[email protected]" : ""+ run("ffmpeg", "-y", "-v", "error", "-i", video,+ "-vf", "fps=#{rate},scale=#{width}:-2#{label},tile=#{cols}x#{rows}:padding=4",+ "-frames:v", "1", out)+ out+ end++ # Whether this ffmpeg build has a filter (e.g. brew ffmpeg may lack drawtext/freetype).+ def filter?(name)+ @filters ||= run("ffmpeg", "-hide_banner", "-filters", quiet: true)+ @filters.match?(/^\s*\S+\s+#{Regexp.escape(name)}\s/)+ end++ # Dump frames at fps into dir (for python analysis).+ def extract_frames(video, dir, fps: 2, width: 512)+ FileUtils.mkdir_p(dir)+ run("ffmpeg", "-y", "-v", "error", "-i", video, "-vf", "fps=#{fps},scale=#{width}:-2", File.join(dir, "f_%03d.png"))+ Dir[File.join(dir, "f_*.png")].sort+ end++ def frame_at(video, seconds, out)+ FileUtils.mkdir_p(File.dirname(out))+ run("ffmpeg", "-y", "-v", "error", "-ss", seconds.to_s, "-i", video, "-frames:v", "1", out)+ out+ end++ # Close-up crop sequence of a region (e.g. the mouth) for lipsync review.+ def crop_strip(video, out, crop:, fps: 4, cols: 10, rows: 4)+ FileUtils.mkdir_p(File.dirname(out))+ run("ffmpeg", "-y", "-v", "error", "-i", video,+ "-vf", "fps=#{fps},crop=#{crop},scale=160:-2,tile=#{cols}x#{rows}:padding=2", "-frames:v", "1", out)+ out+ end++ def waveform(audio, out, size: "1600x300")+ run("ffmpeg", "-y", "-v", "error", "-i", audio, "-filter_complex", "showwavespic=s=#{size}:split_channels=0:colors=0x33ccff", "-frames:v", "1", out)+ out+ end++ def spectrogram(audio, out, size: "1600x512")+ run("ffmpeg", "-y", "-v", "error", "-i", audio, "-lavfi", "showspectrumpic=s=#{size}:legend=1:scale=log", out)+ out+ end++ def to_wav(audio, out, rate: 22_050)+ run("ffmpeg", "-y", "-v", "error", "-i", audio, "-ac", "1", "-ar", rate.to_s, out)+ out+ end++ # `seconds` of audio starting at `from` (shorter if the source ends first), 44.1k mp3.+ def cut_audio(audio, out, from:, seconds:)+ run("ffmpeg", "-y", "-v", "error", "-ss", from.round(3).to_s, "-i", audio, "-t", seconds.to_s, "-ar", "44100", "-b:a", "320k", out)+ out+ end++ # First audio stream of a video/audio file as 44.1k stereo wav (full quality, unlike to_wav),+ # optionally only `seconds` of it starting at `from`.+ def extract_audio(media, out, from: 0, seconds: nil)+ window = (from.positive? ? ["-ss", from.to_s] : [])+ length = seconds ? ["-t", seconds.to_s] : []+ run("ffmpeg", "-y", "-v", "error", *window, "-i", media, *length, "-vn", "-map", "0:a:0", "-ac", "2", "-ar", "44100", out)+ out+ end++ # Pad (with silence) or trim audio to exactly `seconds`, with a short fade-out (fade: 0 for none).+ def fit_audio(audio, out, seconds:, fade: 0.4)+ run("ffmpeg", "-y", "-v", "error", "-i", audio,+ "-af", "apad=whole_dur=#{seconds}#{",afade=t=out:st=#{seconds - fade}:d=#{fade}" if fade.positive?}",+ "-t", seconds.to_s, "-ar", "44100", "-b:a", "320k", out)+ out+ end++ # Replace video's audio with `audio` (video stream copied). shortest: false keeps every video frame when the audio is+ # already cut to the video's length (media:preview): -shortest stops at an AAC packet boundary and dropped the last+ # 4 frames of the 3373-frame full-song preview.+ def mux(video, audio, out, shortest: true)+ run("ffmpeg", "-y", "-v", "error", "-i", video, "-i", audio,+ "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", "256k", *("-shortest" if shortest), out)+ out+ end++ # Composite a transparent PNG sequence (<dir>/0000.png…, e.g. from Media::Anim) over `video`, keeping its audio.+ def overlay_frames(video, dir, out, fps:)+ run("ffmpeg", "-y", "-v", "error", "-i", video, "-framerate", fps.to_s, "-i", File.join(dir, "%04d.png"),+ "-filter_complex", "[0:v][1:v]overlay=0:0:format=auto:eof_action=pass,format=yuv420p[v]",+ "-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-crf", "16", "-preset", "medium", "-c:a", "copy", out)+ out+ end++ # YouTube 4K master: scaled (lanczos) to fill 3840x2160 (1928x1076 is a hair wider than 16:9: 15px cropped per side, no bars),+ # converted from the BT.601 matrix our untagged encodes use (swscale's default) to BT.709 and tagged as such, so YouTube shows the+ # sketch colours. x264 [email protected], closed 12-frame GOPs (half the frame rate, as YouTube asks), faststart; the audio is copied.+ def youtube_4k(video, out, crf: 16)+ scale = "scale=3870:2160:flags=lanczos+accurate_rnd+full_chroma_int:in_color_matrix=bt601:out_color_matrix=bt709:" \+ "in_range=tv:out_range=tv,crop=3840:2160,setsar=1,format=yuv420p"+ run("ffmpeg", "-y", "-v", "error", "-i", video, "-vf", scale, "-c:v", "libx264", "-preset", "slow", "-crf", crf.to_s,+ "-profile:v", "high", "-level:v", "5.1", "-tune", "animation", "-g", "12", "-bf", "2", "-flags", "+cgop",+ "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv",+ # libx264 only wrote the matrix from the flags above; this writes primaries + transfer into the stream too+ "-bsf:v", "h264_metadata=colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1:video_full_range_flag=0",+ "-c:a", "copy", "-movflags", "+faststart", out)+ out+ end++ # Twitter/X upload: the same fill-crop and BT.601 -> BT.709 conversion as youtube_4k, at 1920x1080 (1928x1076 -> 1935x1080, 7-8px+ # cropped per side). x264 [email protected], CRF capped at ~13 Mbps (X re-encodes; a clean, not huge, source survives best), 1s GOPs,+ # faststart; the audio is copied.+ def twitter_1080(video, out, crf: 17, maxrate: "13M")+ scale = "scale=1935:1080:flags=lanczos+accurate_rnd+full_chroma_int:in_color_matrix=bt601:out_color_matrix=bt709:" \+ "in_range=tv:out_range=tv,crop=1920:1080,setsar=1,format=yuv420p"+ run("ffmpeg", "-y", "-v", "error", "-i", video, "-vf", scale, "-c:v", "libx264", "-preset", "slow", "-crf", crf.to_s,+ "-maxrate", maxrate, "-bufsize", "26M", "-profile:v", "high", "-level:v", "4.2", "-tune", "animation", "-g", "24", "-bf", "2",+ "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv",+ "-bsf:v", "h264_metadata=colour_primaries=1:transfer_characteristics=1:matrix_coefficients=1:video_full_range_flag=0",+ "-c:a", "copy", "-movflags", "+faststart", out)+ out+ end++ # EBU R128 integrated loudness and true peak of a file's audio: { lufs:, true_peak: } (dB).+ # Mean level in dB of a stretch of a file's audio.+ def mean_volume(path, from, to)+ _, err, = Open3.capture3("ffmpeg", "-hide_banner", "-nostats", "-ss", from.to_s, "-to", to.to_s, "-i", path, "-af", "volumedetect", "-f", "null", "-")+ err[/mean_volume: (-?[\d.]+) dB/, 1]&.to_f+ end++ def loudness(path)+ _, err, status = Open3.capture3("ffmpeg", "-nostats", "-i", path, "-af", "ebur128=peak=true", "-f", "null", "-")+ raise Media::CommandError, "ffmpeg ebur128 failed on #{path}" unless status.success?+ summary = err[/Integrated loudness:.*\z/m].to_s+ { lufs: summary[/I:\s+(-?[\d.]+) LUFS/, 1].to_f, true_peak: summary[/Peak:\s+(-?[\d.]+) dBFS/, 1].to_f }+ end++ # Seconds of silence (below `db`) at the head of an audio file: where speech actually starts in a TTS take.+ def leading_silence(path, db: -40, min: 0.05)+ _, err, status = Open3.capture3("ffmpeg", "-nostats", "-i", path, "-af", "silencedetect=n=#{db}dB:d=#{min}", "-f", "null", "-")+ raise Media::CommandError, "ffmpeg silencedetect failed on #{path}" unless status.success?+ return 0.0 unless err[/silence_start: (-?[\d.e-]+)/, 1].to_f.abs < 0.01+ err[/silence_end: ([\d.]+)/, 1].to_f+ end++ # Copy of `video` with its audio raised or lowered by `db` (picture stream copied).+ def gain(video, out, db:, fade_in: 0, fade_out: 0)+ FileUtils.mkdir_p(File.dirname(out))+ fades = [("afade=t=in:d=#{fade_in}" if fade_in.positive?), ("afade=t=out:st=#{(duration(video) - fade_out).round(3)}:d=#{fade_out}" if fade_out.positive?)].compact+ run("ffmpeg", "-y", "-v", "error", "-i", video, "-map", "0", "-c:v", "copy", "-af", ["volume=#{db.round(2)}dB", *fades].join(","),+ "-c:a", "aac", "-b:a", "192k", out, quiet: true)+ out+ end++ # Frame number n of `video` as a still.+ def frame_index(video, n, out)+ FileUtils.mkdir_p(File.dirname(out))+ run("ffmpeg", "-y", "-v", "error", "-i", video, "-vf", "select=eq(n\\,#{n})", "-frames:v", "1", out, quiet: true)+ out+ end++ # Cut and join shots into one silent video at `fps`, sized like the first shot. segments: [{ path:, frames:,+ # skip: (source frames to drop first), retime: (squeeze the whole source into `frames`), keep: (use only the source's+ # first N frames, before the trim or retime), roll: [from, to] (degrees, clockwise: a virtual camera roll, eased, scaled+ # up just enough to hide the corners; p5 layers follow it with Anim.withRoll) }].+ # A stretched source can end a frame short of `frames` (fps drops the last stretched frame at EOF: a 72->96 retime+ # gave 95). Clone the last frame a little before the trim so a retimed shot is always exactly `frames`.+ PAD_END = "tpad=stop_mode=clone:stop=4"++ def concat_shots(segments, out, fps:, w: nil, h: nil)+ first = summary(segments.first[:path])[:video]+ size = "scale=#{w || first[:w]}:#{h || first[:h]}:flags=lanczos,setsar=1"+ chains = segments.each_with_index.map do |seg, i|+ timing = if seg[:retime] && seg[:keep]+ "fps=#{fps},trim=end_frame=#{seg[:keep]},setpts=(PTS-STARTPTS)*#{seg[:frames].fdiv(seg[:keep]).round(6)},fps=#{fps},#{PAD_END},trim=end_frame=#{seg[:frames]}"+ elsif seg[:retime]+ "setpts=(PTS-STARTPTS)*#{(seg[:frames].fdiv(fps) / duration(seg[:path])).round(6)},fps=#{fps},#{PAD_END},trim=end_frame=#{seg[:frames]}"+ else+ "fps=#{fps},trim=start_frame=#{seg[:skip].to_i}:end_frame=#{seg[:skip].to_i + seg[:frames]}"+ end+ "[#{i}:v]#{timing},setpts=PTS-STARTPTS,#{size}#{roll_filter(seg, w || first[:w], h || first[:h])}[v#{i}]"+ end+ graph = "#{chains.join(";")};#{segments.size.times.map { |i| "[v#{i}]" }.join}concat=n=#{segments.size}:v=1:a=0,format=yuv420p[v]"+ run("ffmpeg", "-y", "-v", "error", *segments.flat_map { |s| ["-i", s[:path]] },+ "-filter_complex", graph, "-map", "[v]", "-an", "-c:v", "libx264", "-crf", "14", "-preset", "medium", "-r", fps.to_s, out)+ out+ end++ # Overscan that keeps a w x h frame covered at `degrees` of roll.+ def self.roll_overscan(degrees, w, h)+ a = degrees.abs * Math::PI / 180+ Math.cos(a) + ([w, h].max.fdiv([w, h].min)) * Math.sin(a)+ end++ def roll_filter(seg, w, h)+ from, to = seg[:roll]+ return "" unless from+ zoom = self.class.roll_overscan([from.abs, to.abs].max, w, h)+ span = [seg[:frames] - 1, 1].max+ angle = "(#{from}+(#{to - from})*(3*pow(n/#{span}\\,2)-2*pow(n/#{span}\\,3)))*PI/180"+ ",scale=#{(w * zoom / 2).ceil * 2}:#{(h * zoom / 2).ceil * 2}:flags=bicubic,rotate=a=#{angle}:ow=#{w}:oh=#{h}:c=black,setsar=1"+ end++ # Join finished clips (video + audio) end to end, e.g. one generation per song section -> a long-form video.+ # Every clip is scaled/padded to the first clip's size and resampled to `fps`. audio: false joins the pictures only (for a+ # song laid over afterwards): with audio, concat starts each clip where the previous clip's AAC audio ends, a hair past its+ # video, and over four joins that skipped a whole frame (anim1..5 preview: 940 frames -> a gap at 800, 937 after the mux).+ def concat_videos(clips, out, fps: 24, audio: true)+ first = summary(clips.first)[:video]+ fit = "scale=#{first[:w]}:#{first[:h]}:force_original_aspect_ratio=decrease,pad=#{first[:w]}:#{first[:h]}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1,fps=#{fps},format=yuv420p"+ chains = clips.each_index.map { |i| "[#{i}:v]#{fit}[v#{i}]#{";[#{i}:a]aresample=44100,aformat=channel_layouts=stereo[a#{i}]" if audio}" }+ inputs = clips.each_index.map { |i| audio ? "[v#{i}][a#{i}]" : "[v#{i}]" }.join+ graph = "#{chains.join(";")};#{inputs}concat=n=#{clips.size}:v=1:a=#{audio ? 1 : 0}[v]#{"[a]" if audio}"+ codecs = audio ? ["-map", "[a]", "-c:a", "aac", "-b:a", "256k"] : ["-an"]+ run("ffmpeg", "-y", "-v", "error", *clips.flat_map { |c| ["-i", c] }, "-filter_complex", graph,+ "-map", "[v]", "-c:v", "libx264", "-crf", "16", "-preset", "medium", *codecs, out)+ out+ end++ # Lay clips on a silent timeline: lines [{ "path", "at" (seconds) }] -> one stereo 44.1k wav exactly `seconds` long.+ # No lines gives silence (a character's mouth track in a scene where they only narrate).+ # Lines may carry gain_db (a per-take level, applied before placement).+ def place_audio(lines, out, seconds:)+ if lines.empty?+ run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo", "-t", seconds.to_s, "-c:a", "pcm_s16le", out)+ return out+ end+ chains = lines.each_with_index.map do |l, i|+ ms = (l.fetch("at").to_f * 1000).round+ gain = l["gain_db"].to_f.zero? ? "" : ",volume=#{l["gain_db"].to_f}dB"+ # gate_s silences a take's head (a blip before the first word), keep_s cuts its tail, and inner makes a thought:+ # dry and close with a short room behind it, so it isn't heard as spoken in the scene.+ gain += ",afade=t=in:st=#{l["gate_s"].to_f}:d=0.02" if l["gate_s"]+ gain += ",afade=t=out:st=#{[l["keep_s"].to_f - 0.12, 0].max}:d=0.12,atrim=end=#{l["keep_s"].to_f}" if l["keep_s"]+ gain += ",highpass=f=160,aecho=0.8:0.8:60|120:0.28|0.16" if l["inner"]+ "[#{i}:a]aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo#{gain},adelay=#{ms}|#{ms}[a#{i}]"+ end+ graph = "#{chains.join(";")};#{lines.each_index.map { |i| "[a#{i}]" }.join}amix=inputs=#{lines.size}:normalize=0,apad=whole_dur=#{seconds}[out]"+ run("ffmpeg", "-y", "-v", "error", *lines.flat_map { |l| ["-i", l.fetch("path")] }, "-filter_complex", graph,+ "-map", "[out]", "-t", seconds.to_s, "-ar", "44100", "-c:a", "pcm_s16le", out)+ out+ end++ # Score ducked under dialogue (sidechain compression keyed by the dialogue), then limited; `seconds` long.+ # music_end: hard-cut the score there (smash cut) with a 30 ms fade.+ def duck_mix(music, dialogue, out, seconds:, music_db: -4, dialogue_db: 0, duck: true, music_end: nil, music_out: 0.03)+ cut = music_end ? ",afade=t=out:st=#{[music_end.to_f - music_out, 0].max}:d=#{music_out}" : "" # afade out leaves silence after it+ fmt = "aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo"+ inputs = ["-i", music]+ graph = if dialogue+ inputs += ["-i", dialogue]+ music_chain = "[0:a]#{fmt},volume=#{music_db}dB,apad=whole_dur=#{seconds}#{cut}[m]"+ voice_chain = "[1:a]#{fmt},volume=#{dialogue_db}dB,apad=whole_dur=#{seconds},asplit=2[d][key]"+ ducked = duck ? "[m][key]sidechaincompress=threshold=0.015:ratio=6:attack=25:release=450:makeup=1[md]" : "[key]anullsink;[m]anull[md]"+ "#{music_chain};#{voice_chain};#{ducked};[md][d]amix=inputs=2:normalize=0,alimiter=limit=0.93[out]"+ else+ "[0:a]#{fmt},volume=#{music_db}dB,apad=whole_dur=#{seconds}#{cut},alimiter=limit=0.93[out]"+ end+ run("ffmpeg", "-y", "-v", "error", *inputs, "-filter_complex", graph, "-map", "[out]", "-t", seconds.to_s,+ "-ar", "44100", "-c:a", "pcm_s16le", out)+ out+ end++ # Lengthen a score past its last note: the final second rings out as decaying echoes under a fade, so a scene held a+ # little longer lets the music release instead of stopping on the cut. Nothing before the last `release` seconds changes.+ def ring_out(audio, out, tail:, release: 0.25)+ length = duration(audio)+ fmt = "aresample=44100,aformat=sample_fmts=fltp:channel_layouts=stereo"+ body = "[0:a]#{fmt},asplit=2[a][b];[a]afade=t=out:st=#{length - release}:d=#{release},apad=whole_dur=#{length + tail}[m]"+ ring = "[b]atrim=start=#{length - 1.0},asetpts=PTS-STARTPTS,afade=t=in:d=0.02,apad=whole_dur=#{1.0 + tail}," \+ "aecho=0:0.9:140|280|420|560:0.6|0.45|0.32|0.22,afade=t=out:st=1.0:d=#{tail}," \+ "adelay=#{((length - 1.0) * 1000).round}:all=1[r]"+ run("ffmpeg", "-y", "-v", "error", "-i", audio, "-filter_complex", "#{body};#{ring};[m][r]amix=inputs=2:normalize=0,alimiter=limit=0.93[out]",+ "-map", "[out]", "-t", (length + tail).to_s, "-ar", "44100", "-c:a", "pcm_s16le", out)+ out+ end++ # A silent shot: an image held (Ken Burns zoom from zoom[0] to zoom[1] when given) or a solid colour, `frames` long.+ def still_video(out, frames:, fps: 24, w: 1920, h: 1080, image: nil, color: "#000000", zoom: nil)+ if image+ z0, z1 = zoom || [1, 1]+ step = (z1.to_f - z0.to_f) / [frames - 1, 1].max+ vf = "scale=#{w * 2}:#{h * 2},zoompan=z='#{z0}+#{step.round(6)}*on':x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':d=#{frames}:s=#{w}x#{h}:fps=#{fps},setsar=1,format=yuv420p"+ run("ffmpeg", "-y", "-v", "error", "-loop", "1", "-i", image, "-vf", vf, "-frames:v", frames.to_s, "-an",+ "-c:v", "libx264", "-crf", "14", "-preset", "medium", "-r", fps.to_s, out)+ else+ run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "color=c=#{color.sub("#", "0x")}:s=#{w}x#{h}:r=#{fps}", "-frames:v", frames.to_s,+ "-vf", "format=yuv420p", "-an", "-c:v", "libx264", "-crf", "14", "-preset", "medium", out)+ end+ out+ end++ # A still image held for `seconds` at `fps`, scaled to w×h, with `audio` muxed in (a plate for a sketch that animates everything).+ def still_plate(image, audio, out, seconds:, fps: 24, w: 1920, h: 1080)+ run("ffmpeg", "-y", "-v", "error", "-loop", "1", "-framerate", fps.to_s, "-i", image, "-i", audio,+ "-vf", "scale=#{w}:#{h},setsar=1,format=yuv420p", "-frames:v", (seconds * fps).round.to_s,+ "-c:v", "libx264", "-crf", "14", "-preset", "medium", "-c:a", "aac", "-b:a", "256k", "-t", seconds.to_s, out)+ out+ end++ # One frame (by index) of `video` with a transparent PNG composited on top, as a still.+ def overlay_still(video, frame, png, out)+ run("ffmpeg", "-y", "-v", "error", "-i", video, "-i", png,+ "-filter_complex", "[0:v]select=eq(n\\,#{frame})[b];[b][1:v]overlay=0:0", "-frames:v", "1", out, quiet: true)+ out+ end++ # Side-by-side comparison video (e.g. raw vs lipsynced), audio from `right`.+ def hstack(left, right, out, height: 540)+ run("ffmpeg", "-y", "-v", "error", "-i", left, "-i", right,+ "-filter_complex", "[0:v]scale=-2:#{height}[l];[1:v]scale=-2:#{height}[r];[l][r]hstack=inputs=2[v]",+ "-map", "[v]", "-map", "1:a?", "-c:v", "libx264", "-crf", "20", "-c:a", "aac", "-shortest", out)+ out+ end++ private++ def fps(rate)+ num, den = rate.to_s.split("/").map(&:to_f)+ den && den.positive? ? (num / den).round(2) : num+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/media/image_magick.rb b/skills/make-an-anime/scripts/lib/media/image_magick.rbnew file mode 100644index 0000000..402a0db--- /dev/null+++ b/skills/make-an-anime/scripts/lib/media/image_magick.rb@@ -0,0 +1,45 @@+require_relative "shell"++module Media+ # ImageMagick 7 (`magick`) wrapper for inspection and review boards.+ class ImageMagick < Shell+ def identify(path)+ w, h, fmt = run("magick", "identify", "-format", "%w %h %m", "#{path}[0]", quiet: true).split+ { w: w.to_i, h: h.to_i, format: fmt, aspect: (w.to_f / h.to_i).round(3) }+ end++ # Downscaled JPEG preview (keeps review images small enough to inspect).+ def preview(path, out, max: 1280)+ run("magick", path, "-resize", "#{max}x#{max}>", "-quality", "88", out)+ out+ end++ # Labeled side-by-side board: pairs = [[path, label], ...]+ def board(pairs, out, tile: "#{pairs.size}x1", width: 900)+ args = pairs.flat_map { |path, label| ["-label", label, path] }+ run("magick", "montage", "-font", FONT, *args, "-tile", tile, "-geometry", "#{width}x+8+8",+ "-pointsize", "22", "-background", "#222", "-fill", "white", out)+ out+ end++ # Images stacked top to bottom, each scaled to `width` (review boards: a photo row above one or more sheets).+ def stack(paths, out, width: 1800)+ run("magick", *paths.flat_map { |p| [p, "-resize", "#{width}x"] }, "-background", "#222", "-gravity", "north",+ "-splice", "0x8", "-append", "-quality", "88", out)+ out+ end++ # Grayscale-vs-color diff mask: white where pixels are low-saturation (line-art),+ # black where colored. Useful to eyeball the hand-drawn/colored split.+ # Share (0..1) of an RGBA image that is covered, i.e. its mean alpha.+ def alpha_coverage(path)+ run("magick", path, "-alpha", "extract", "-format", "%[fx:mean]", "info:", quiet: true).to_f+ end++ def saturation_mask(path, out, threshold: 12)+ run("magick", path, "-colorspace", "HSL", "-channel", "G", "-separate", "+channel",+ "-threshold", "#{threshold}%", "-negate", out)+ out+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/media/python.rb b/skills/make-an-anime/scripts/lib/media/python.rbnew file mode 100644index 0000000..a898d49--- /dev/null+++ b/skills/make-an-anime/scripts/lib/media/python.rb@@ -0,0 +1,46 @@+require "json"+require_relative "shell"++module Media+ # Runs analysis scripts in ./scripts with the local python3 (PIL + numpy)+ # and parses their JSON stdout.+ class Python < Shell+ SCRIPTS = File.expand_path("../../tools/python", __dir__)++ def executable = ENV["MV_PYTHON"] || (File.file?(File.expand_path(".venv/bin/python3")) ? File.expand_path(".venv/bin/python3") : "python3")++ def call(script, *args)+ JSON.parse(run(executable, File.join(SCRIPTS, script), *args, quiet: true))+ end++ # Share of low-saturation (hand-drawn / monochrome) vs colored pixels per image.+ def style_split(*images)+ call("style_split.py", *images)+ end++ # Camera move between two frames of a shot: { "zoom", "shift_x", "shift_y", "score", "camera" } (tools/python/camera_motion.py).+ def camera_motion(first, last)+ call("camera_motion.py", first, last)+ end++ # Per-frame position of a feature (box `size` centred at x, y in frame `from`) by template matching.+ def track_template(video, x, y, size, search = size, from = 0)+ call("track_template.py", video, x.to_s, y.to_s, size.to_s, search.to_s, from.to_s)+ end++ # Character cut out of a video/still into transparent PNGs in `out` (scripts/cutout.py): key "paper" or "green",+ # box [x, y, w, h], seed [x, y], frames, start, scale. Returns { "frames", "w", "h", "box", "scale" }.+ def cutout(source, out, key, box: nil, seed: nil, frames: nil, start: nil, scale: nil, low: nil)+ args = [source, out, key]+ args += ["--box", *box] if box+ args += ["--seed", *seed] if seed+ { "--frames" => frames, "--start" => start, "--scale" => scale, "--low" => low }.each { |flag, v| args += [flag, v] if v }+ call("cutout.py", *args.map(&:to_s))+ end++ # RMS loudness + vocal-band energy per window, for a mono wav.+ def audio_energy(wav, window: 0.5)+ call("audio_energy.py", wav, window.to_s)+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/media/sfx.rb b/skills/make-an-anime/scripts/lib/media/sfx.rbnew file mode 100644index 0000000..d399c8c--- /dev/null+++ b/skills/make-an-anime/scripts/lib/media/sfx.rb@@ -0,0 +1,100 @@+require "json"+require "yaml"+require "fileutils"+require_relative "shell"+require_relative "ffmpeg"++module Media+ # Sound effects over a finished video (the full-song preview). prompts/<name>/sfx.yml has+ # source: / out: the video to add sounds to (only read) and the new file+ # rel_db: default level of a cue, in dB relative to the music's loudness under it (−4 ≈ clearly audible, still under it)+# peak_db / max_gain_db: caps: a cue never peaks above peak_db (−6) nor gets boosted more than max_gain_db (+18)+ # sounds: { name => { prompt:, duration:, seed:, negative: } } generated with fal stable-audio-3 SFX (Fal::Models::StableAudioSfx),+ # or { tone: Hz, duration: }: a steady sine synthesized with ffmpeg (a monitor flatline; the model only makes rhythmic beeps)+ # cues: [{ at: song s, sound:, rel_db:, rate: (pitch/speed), len: (s, cut + fade), fade: (s) }, ...]+ # Sounds are cached in output/<name>/sounds/<sound>.wav with a sidecar json; a sound is generated again only when its prompt,+ # duration or seed changed (or FORCE=1 with ONLY=a,b). scripts/sfx_mix.py trims their leading silence, sets each cue's level+ # against the music in its window and limits the sum; the video stream is copied untouched.+ class Sfx < Shell+ ROOT = File.expand_path("../..", __dir__)++ attr_reader :name, :dir++ def initialize(name = ENV.fetch("SFX", "mv2-sfx"))+ @name = name+ @dir = File.join(ROOT, "output", name)+ FileUtils.mkdir_p(File.join(@dir, "sounds"))+ end++ def config = @config ||= YAML.safe_load_file(File.join(ROOT, "prompts", name, "sfx.yml"))+ def source = File.expand_path(config.fetch("source"), ROOT)+ def out = File.expand_path(config.fetch("out"), ROOT)+ def sounds = config.fetch("sounds")+ def wav(sound) = File.join(dir, "sounds", "#{sound}.wav")++ # Generate every sound that is missing or stale. only: names to force (with force: true).+ def generate(only: nil, force: false, client: nil)+ unknown = config.fetch("cues").map { |c| c.fetch("sound") }.uniq - sounds.keys+ raise "cues use undefined sounds: #{unknown.join(", ")}" if unknown.any?+ model = nil+ sounds.filter_map do |sound, spec|+ want = if spec["tone"]+ { "tone" => spec["tone"], "duration" => spec.fetch("duration", 2) }+ else+ { "prompt" => spec.fetch("prompt"), "duration" => spec.fetch("duration", 2), "seed" => spec["seed"],+ "negative_prompt" => spec["negative"] || config["negative"] }+ end+ meta = File.join(dir, "sounds", "#{sound}.json")+ have = File.exist?(meta) && File.exist?(wav(sound)) ? JSON.parse(File.read(meta)) : {}+ stale = have.slice(*want.keys) != want+ next unless stale || (force && (only.nil? || only.include?(sound)))+ if spec["tone"]+ # A steady sine (e.g. a monitor flatline, which the SFX model always turns into rhythmic beeps): synthesized, no fal call.+ run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "sine=frequency=#{want["tone"]}:sample_rate=48000:duration=#{want["duration"]}",+ "-af", "volume=-6dB,afade=t=in:d=0.004,afade=t=out:st=#{want["duration"] - 0.02}:d=0.02", "-ac", "2", wav(sound))+ File.write(meta, JSON.pretty_generate(want))+ next sound+ end+ warn "[sfx] #{sound} generating…"+ client ||= Fal::Client.new+ model ||= Fal::Models::StableAudioSfx.new(client: client)+ res = model.generate(prompt: want["prompt"], duration: want["duration"], seed: want["seed"],+ negative_prompt: want["negative_prompt"], output_format: "wav")+ client.download(res.output.dig("audio", "url"), wav(sound))+ File.write(meta, JSON.pretty_generate(want.merge("request_id" => res.request_id, "used_seed" => res.output["seed"],+ "url" => res.output.dig("audio", "url"))))+ sound+ end+ end++ # `voice_dip_db:` in sfx.yml: the cues dip under the scene's voice track, and their levels are read from the mix made+ # before any voice lift (03_mix_ref.wav, Steps::Mix), so a louder voice is not followed by louder effects.+ def voice_args+ dip = config["voice_dip_db"] or return []+ scene = File.dirname(source)+ voice = File.join(scene, "03_dialogue.wav")+ ref = File.join(scene, "03_mix_ref.wav")+ [*(File.exist?(ref) ? ["--level-ref", ref] : []), *(File.exist?(voice) ? ["--voice", voice, "--voice-dip-db", dip.to_s] : [])]+ end++ # Mix the cues over the source video's audio -> out (video copied). Returns [out, per-cue level report].+ def mix+ missing = config.fetch("cues").map { |c| c["sound"] }.uniq.reject { |s| File.exist?(wav(s)) }+ raise "sounds not generated yet (rake sfx:gen): #{missing.join(", ")}" if missing.any?+ cues = config.fetch("cues").map do |c|+ { "at" => c.fetch("at"), "wav" => wav(c.fetch("sound")), "sound" => c["sound"], "rel_db" => c.fetch("rel_db", config.fetch("rel_db", -4)),+ "rate" => c.fetch("rate", 1.0), "len" => c["len"], "fade" => c.fetch("fade", 0.05) }+ end+ File.write(path("cues.json"), JSON.pretty_generate(cues))+ music = path("music.wav")+ run("ffmpeg", "-y", "-v", "error", "-i", source, "-vn", "-ac", "2", "-ar", "48000", "-c:a", "pcm_s16le", music)+ report = JSON.parse(run(Media::Python.new.executable, File.join(ROOT, "tools", "python", "sfx_mix.py"), music, path("cues.json"), path("mix.wav"), *voice_args,+ "--floor-db", config.fetch("floor_db", -30).to_s, "--peak-db", config.fetch("peak_db", -6).to_s,+ "--max-gain-db", config.fetch("max_gain_db", 18).to_s, quiet: true))+ FFmpeg.new.mux(source, path("mix.wav"), out)+ [out, report]+ end++ def path(file) = File.join(dir, file)+ end+enddiff --git a/skills/make-an-anime/scripts/lib/media/shell.rb b/skills/make-an-anime/scripts/lib/media/shell.rbnew file mode 100644index 0000000..3b0fce6--- /dev/null+++ b/skills/make-an-anime/scripts/lib/media/shell.rb@@ -0,0 +1,35 @@+require "open3"+require "fileutils"+require "shellwords"++module Media+ class CommandError < StandardError; end++ MIME_TYPES = {+ ".png" => "image/png", ".jpg" => "image/jpeg", ".jpeg" => "image/jpeg", ".webp" => "image/webp",+ ".mp3" => "audio/mpeg", ".wav" => "audio/wav", ".m4a" => "audio/mp4",+ ".mp4" => "video/mp4", ".mov" => "video/quicktime", ".webm" => "video/webm"+ }.freeze++ # Explicit font file for magick labels / ffmpeg drawtext (no fontconfig default on macOS brew builds).+ FONT = [ENV["MEDIA_FONT"], "/System/Library/Fonts/Supplemental/Arial.ttf", "/Library/Fonts/Arial Unicode.ttf"]+ .compact.find { |f| File.exist?(f) }++ def self.mime_type(path)+ MIME_TYPES.fetch(File.extname(path).downcase, "application/octet-stream")+ end++ # Base for wrappers around local CLI tools (ffmpeg, magick, python3).+ class Shell+ def self.available?(bin)+ system("command -v #{bin.shellescape} > /dev/null 2>&1")+ end++ def run(*cmd, quiet: false)+ warn " $ #{cmd.shelljoin}" unless quiet+ out, err, status = Open3.capture3(*cmd.map(&:to_s))+ raise CommandError, "#{cmd.first} failed (#{status.exitstatus}):\n#{err[-2000..] || err}" unless status.success?+ out+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/media/sprite_components.rb b/skills/make-an-anime/scripts/lib/media/sprite_components.rbnew file mode 100644index 0000000..6edf66f--- /dev/null+++ b/skills/make-an-anime/scripts/lib/media/sprite_components.rb@@ -0,0 +1,16 @@+require_relative "python"++module Media+ # Preserve a seeded alpha silhouette while discarding detached marks in each frame.+ class SpriteComponents+ def keep(source, out, seed_x, seed_y)+ source = File.realpath(source)+ out = File.expand_path(out)+ resolved_out = File.exist?(out) ? File.realpath(out) : out+ raise ArgumentError, "Source and output must be different directories" if source == resolved_out+ x, y = Integer(seed_x), Integer(seed_y)+ raise ArgumentError, "Seed coordinates must be nonnegative integers" if x.negative? || y.negative?+ Python.new.call("keep_component.py", source, out, x.to_s, y.to_s)+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/media/vfx.rb b/skills/make-an-anime/scripts/lib/media/vfx.rbnew file mode 100644index 0000000..fc6941b--- /dev/null+++ b/skills/make-an-anime/scripts/lib/media/vfx.rb@@ -0,0 +1,119 @@+require "json"+require "yaml"+require_relative "shell"+require_relative "anim"+require_relative "ffmpeg"+require_relative "python"++module Media+ # Post-processing VFX over a finished video (the full-song preview): a cue list (prompts/<name>/cues.yml) drives+ # - vfx/ (Swift, Core Image): punch zoom shake whip mblur edgeblur glow flash dark rgb glitch tv, and+ # - prompts/<name>/05_lights.js (p5): leak flare glints, rendered only on their frames and screen-blended in by vfx/.+ # Output goes to output/<name>/ (analysis, cues.json, lights/, stills/, clips) and the cue file's `out:` (the full render).+ # The source video is only read: the VFX version is a new file.+ class Vfx < Shell+ ROOT = File.expand_path("../..", __dir__)+ PACKAGE = File.join(ROOT, "tools", "vfx")+ BIN = File.join(PACKAGE, ".build", "release", "mvfx")+ CORE_IMAGE = %w[punch zoom shake whip mblur edgeblur glow flash dark rgb glitch tv grain].freeze+ LIGHTS = %w[leak flare glints].freeze++ attr_reader :name, :dir++ def initialize(name = ENV.fetch("VFX", "run4-vfx"))+ @name = name+ @dir = File.join(ROOT, "output", name)+ FileUtils.mkdir_p(@dir)+ end++ def config = @config ||= YAML.safe_load_file(File.join(ROOT, "prompts", name, "cues.yml"))+ def source = File.expand_path(config.fetch("source"), ROOT)+ def out = File.expand_path(config.fetch("out"), ROOT)+ # The light sketch: cues.yml `lights:` (e.g. another revision's), else prompts/<name>/05_lights.js.+ def sketch = File.join(ROOT, config["lights"] || File.join("prompts", name, "05_lights.js"))+ def path(file) = File.join(dir, file)++ # Song beat grid + onsets (scripts/beats.py) and picture cuts (scripts/cuts.py) of the source, for placing cues.+ def analyze+ wav = FFmpeg.new.extract_audio(source, path("song.wav"))+ File.write(path("beats.json"), run(Media::Python.new.executable, File.join(Python::SCRIPTS, "beats.py"), wav, "24", quiet: true))+ File.write(path("cuts.json"), run(Media::Python.new.executable, File.join(Python::SCRIPTS, "cuts.py"), source, quiet: true))+ { beats: JSON.parse(File.read(path("beats.json"))), cuts: JSON.parse(File.read(path("cuts.json"))) }+ end++ def build+ run("swift", "build", "-c", "release", "--package-path", PACKAGE)+ BIN+ end++ # cues.yml -> output/<name>/cues.json (checked: known fx, integer f/dur, sorted by frame).+ def cues+ list = config.fetch("cues").map do |c|+ fx = c.fetch("fx")+ raise ArgumentError, "unknown fx #{fx.inspect} in #{c} (#{(CORE_IMAGE + LIGHTS).join(" ")})" unless (CORE_IMAGE + LIGHTS).include?(fx)+ raise ArgumentError, "cue needs integer f and dur: #{c}" unless c["f"].is_a?(Integer) && c["dur"].is_a?(Integer) && c["dur"].positive?+ c+ end.sort_by { |c| [c["f"], c["fx"]] }+ File.write(path("cues.json"), JSON.pretty_generate({ "cues" => list }))+ path("cues.json")+ end++ # Frames any light cue touches (clipped to the video), optionally only those in `among`.+ def light_frames(among = nil)+ total = frames+ set = JSON.parse(File.read(path("cues.json")))["cues"].select { |c| LIGHTS.include?(c["fx"]) }+ .flat_map { |c| ((c["f"] - c["pre"].to_i)...(c["f"] + c["dur"])).to_a }.select { |f| f >= 0 && f < total }.uniq.sort+ among ? set & among : set+ end++ # The p5 light layer for `only` frames (default: every frame a light cue touches) -> output/<name>/lights/NNNN.png.+ # Old light frames (all, or the `only` ones) are removed first, so a moved cue never leaves light behind.+ def lights(only = nil)+ frames_to_draw = light_frames(only)+ only ? FileUtils.rm_f(only.map { |f| path(format("lights/%04d.png", f)) }) : FileUtils.rm_rf(path("lights"))+ return path("lights") if frames_to_draw.empty?+ v = FFmpeg.new.summary(source)[:video]+ Anim.new.render(sketch, path("lights"), width: v[:w], height: v[:h], fps: 24, frames: frames, data: { vfx: path("cues.json") },+ only: frames_to_draw)+ path("lights")+ end++ # Stills of `list` frames with every effect -> output/<name>/stills/NNNN.png and a contact sheet stills.jpg (labelled by frame).+ def stills(list)+ cues+ lights(list)+ FileUtils.rm_rf(path("stills"))+ mvfx("--stills", path("stills"), "--only", list.join(","))+ pngs = list.sort.map { |f| path(format("stills/%04d.png", f)) }+ run("magick", "montage", *(["-font", FONT] if FONT), "-pointsize", "20", "-fill", "white", "-label", "%t", *pngs,+ "-tile", "4x", "-geometry", "640x358+4+4", "-background", "black", path("stills.jpg"))+ path("stills.jpg")+ end++ # Frames [from, to) with the song, as its own video -> output/<name>/clip_<from>_<to>.mp4.+ def clip(from, to)+ cues+ lights((from...to).to_a)+ mvfx("--out", path("clip_#{from}_#{to}.mp4"), "--from", from, "--to", to)+ path("clip_#{from}_#{to}.mp4")+ end++ # The whole video -> config `out` (the source's audio stream copied).+ def render+ cues+ lights+ mvfx("--out", out)+ out+ end++ def frames = @frames ||= FFmpeg.new.run("ffprobe", "-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries",+ "stream=nb_read_packets", "-of", "csv=p=0", source, quiet: true).to_i++ private++ def mvfx(*args)+ build if !File.exist?(BIN) || Dir[File.join(PACKAGE, "**", "*.swift")].any? { |f| File.mtime(f) > File.mtime(BIN) }+ JSON.parse(run(BIN, "--in", source, "--cues", path("cues.json"), "--lights", path("lights"), *args.map(&:to_s)).lines.last)+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/generation_config.rb b/skills/make-an-anime/scripts/lib/pipeline/generation_config.rbnew file mode 100644index 0000000..59e1ab1--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/generation_config.rb@@ -0,0 +1,29 @@+module Pipeline+ # The project's generations: config/generations.rb plus every config/generations/*.rb, each evaluated inside Pipeline+ # (so Steps::Shots, scene(480) … resolve) and returning a Hash of run name => generation. One file per scene or per cast+ # group lets several people or agents add runs at the same time without editing a shared file. A run defined in two+ # files is an error, never a silent override.+ class GenerationConfig+ def initialize(root)+ @root = root+ end++ def files+ main = File.join(@root, "config", "generations.rb")+ [main, *Dir[File.join(@root, "config", "generations", "*.rb")].sort].select { |f| File.file?(f) }+ end++ def load+ seen = {}+ files.each_with_object({}) do |file, all|+ runs = Pipeline.module_eval(File.read(file), file)+ raise ArgumentError, "#{file} must return a Hash of run => generation" unless runs.is_a?(Hash)+ runs.each do |name, generation|+ raise ArgumentError, "run #{name} is defined in both #{seen[name]} and #{file}" if seen[name]+ seen[name] = file+ all[name] = generation+ end+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/items_step.rb b/skills/make-an-anime/scripts/lib/pipeline/items_step.rbnew file mode 100644index 0000000..c658e37--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/items_step.rb@@ -0,0 +1,88 @@+require "yaml"++module Pipeline+ # A step made of several named fal generations (keyframes, shots) listed in a prompts/<run>/ YAML file.+ # run! generates the items that are missing or stale (#stale_item?); FORCE=1 regenerates all of them, or only ONLY=a,b.+ # Replaced items are copied to output/<RUN>/rejected/ and kept in the manifest's history.+ # Subclasses implement #specs ({ name => spec }), #generate(name, spec) -> item hash (with "path")+ # and #finish(items) -> step data (with :path, the step's deliverable).+ class ItemsStep < Step+ def run!(force: ENV["FORCE"] == "1")+ only = ENV["ONLY"]&.split(",")+ unknown = Array(only) - specs.keys+ raise "[#{key}] unknown ONLY=#{unknown.join(",")} (#{specs.keys.join(", ")})" if unknown.any?+ items = (project[key]&.dig("items") || {}).slice(*specs.keys)+ specs.each do |name, spec|+ next if only && !only.include?(name)+ next if items[name] && File.exist?(items[name]["path"]) && !stale_item?(name, spec, items[name]) && !(force && (only.nil? || only.include?(name)))+ archive_item!(name, items[name]) if items[name]+ warn "[#{key}] #{name} generating…"+ started = Time.now+ items[name] = generate(name, spec).transform_keys(&:to_s).merge("elapsed_s" => (Time.now - started).round(1))+ project.record(key, items: items) # keep progress if a later item fails+ end+ if (specs.keys - items.keys).empty?+ project.record(key, finish(items).merge(items: items, review: nil))+ else+ project.record(key, items: items, review: nil)+ end+ end++ # A cached item a subclass knows is out of date with its spec (e.g. a free local shot whose frames changed).+ def stale_item?(_name, _spec, _item) = false++ def adopt!(*) = raise("[#{key}] has several items; regenerate one with ONLY=<name> FORCE=1 rake gen:#{key}")+ def pick!(*) = adopt!++ protected++ # H3 inputs shared by the Shots and Clips steps: a keyframe (Keyframes step, "<run>/<name>" for another run's) or "ref_base" as an image url,+ # and the master song from `from` seconds (`seconds` long, shorter at the end), uploaded for H3.+ # H3 rejects audio under 2s, so a clip near the end of the song gets its tail padded with silence.+ def keyframe_url(name)+ return project.fetch!(:ref_base, :url) if name == "ref_base"+ return Project.new(name.delete_prefix("run:")).fetch!(:ref_base, :url) if name.start_with?("run:") # a location/character sheet run+ project.keyframe(name)["url"]+ end++ def song_url(name, from, seconds)+ audio = ffmpeg.cut_audio(project.fetch!(:music, :path), project.path("04_audio_#{name}.mp3"), from: from, seconds: seconds)+ audio = ffmpeg.fit_audio(audio, project.path("04_audio_#{name}_2s.mp3"), seconds: 2, fade: 0) if ffmpeg.duration(audio) < 2+ client.upload(audio)+ end++ # `seconds` of a Dialogue track from scene time `from`, uploaded as H3 target audio: track is a cast id (that+ # character's on-screen lines only) or "dialogue" (every line). Padded with silence to H3's 2 s minimum.+ def voice_url(name, track, from, seconds)+ data = project.fetch!(:dialogue, :path) && project[:dialogue]+ source = track == "dialogue" ? data["path"] : data.fetch("tracks").fetch(track) { raise "[#{key}] #{name}: no dialogue track #{track.inspect} (#{data["tracks"].keys.join(", ")})" }+ out = project.path("04_voice_#{name}.wav")+ ffmpeg.run("ffmpeg", "-y", "-v", "error", "-ss", from.round(4).to_s, "-i", source, "-t", seconds.to_s, "-ar", "44100", out)+ out = ffmpeg.fit_audio(out, project.path("04_voice_#{name}_2s.wav"), seconds: [seconds, 2].max, fade: 0) if ffmpeg.duration(out) < [seconds, 2].max - 0.02+ client.upload(out)+ end++ # prompts/<run>/<stem>.yml as { "name" => spec }. {{STYLE}} is expanded inside the parsed strings, never in the raw+ # YAML: the style text may contain quotes or colons that would break a quoted or plain scalar.+ def yaml(stem) = expand_strings(YAML.safe_load(File.read(project.prompt_path(stem))))++ def expand_strings(value)+ case value+ when String then project.expand(value)+ when Array then value.map { expand_strings(_1) }+ when Hash then value.transform_values { expand_strings(_1) }+ else value+ end+ end++ private++ def archive_item!(name, item)+ history = Array(project[key]&.dig("history"))+ dest = project.path("rejected", "#{key}_#{name}_#{history.count { |h| h["item"] == name } + 1}#{File.extname(item["path"])}")+ FileUtils.cp(item["path"], dest) if File.exist?(item["path"])+ project.record(key, history: history + [item.merge("item" => name, "archived" => dest)])+ warn "[#{key}] archived #{name} -> #{dest}"+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/project.rb b/skills/make-an-anime/scripts/lib/pipeline/project.rbnew file mode 100644index 0000000..fb7bf91--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/project.rb@@ -0,0 +1,104 @@+require "json"+require "fileutils"+require "time"++module Pipeline+ ROOT = File.expand_path("../..", __dir__)++ # One generation run: output/<run>/ with a manifest.json holding each step's+ # request_id, input, remote url and local file so steps can chain via rake.+ class Project+ attr_reader :name, :dir++ def initialize(name = ENV.fetch("RUN", DEFAULT_RUN))+ @name = name+ raise ArgumentError, 'RUN must contain only letters, digits, underscores and hyphens' unless name.match?(/\A[a-zA-Z0-9_-]+\z/)+ @dir = File.join(ROOT, "output", name)+ FileUtils.mkdir_p(dir)+ end++ def path(*parts)+ File.join(dir, *parts).tap { |p| FileUtils.mkdir_p(File.dirname(p)) }+ end++ def review_path(step, file)+ path("review", step.to_s, file)+ end++ def manifest+ File.exist?(manifest_path) ? JSON.parse(File.read(manifest_path)) : {}+ end++ def [](step)+ manifest[step.to_s]+ end++ # flock'd read-modify-write so steps can run in parallel processes.+ def record(step, data)+ File.open("#{manifest_path}.lock", File::CREAT | File::RDWR) do |lock|+ lock.flock(File::LOCK_EX)+ m = manifest+ m[step.to_s] = (m[step.to_s] || {}).merge(data.transform_keys(&:to_s)).merge("updated_at" => Time.now.iso8601)+ File.write("#{manifest_path}.tmp", JSON.pretty_generate(m))+ File.rename("#{manifest_path}.tmp", manifest_path)+ m[step.to_s]+ end+ end++ def fetch!(step, key)+ value = self[step]&.dig(key.to_s)+ raise "step '#{step}' has no '#{key}' yet — run `rake gen:#{step}` first (RUN=#{name})" unless value+ value+ end++ # A Keyframes item of this run, or of another run as "<run>/<keyframe>" (to reuse its framing, its green-screen pose or its paper).+ def keyframe(name)+ run, kf = name.include?("/") ? name.split("/", 2) : [nil, name]+ source = run ? Project.new(run) : self+ source.fetch!(:keyframes, :items).fetch(kf) { raise "no keyframe '#{kf}' in #{source.name} — add it to 02_keyframes.yml and run rake gen:keyframes" }+ end++ def generation+ GENERATIONS.fetch(name) { raise "unknown RUN=#{name} (#{GENERATIONS.keys.join(", ")}), add it to Pipeline::GENERATIONS" }+ end++ def steps = generation[:steps]+ def step?(step_class) = steps.include?(step_class)++ # Length of the song and the video, in seconds: `frames:` (at 24fps, for song sections on a shared frame grid) or `duration:`.+ def duration = generation[:frames] ? generation[:frames] / 24.0 : generation.fetch(:duration, 10)++ # Run this step's output is copied from (GENERATIONS import:), or nil.+ def import_source(step) = generation.fetch(:import, {})[step.to_sym]++ # prompts/<run>/<stem>.* — e.g. prompt("01_ref_base") reads 01_ref_base.txt or 01_ref_base.json.+ def prompt(stem) = expand(File.read(prompt_path(stem)))++ def prompt?(stem) = !Dir[File.join(ROOT, "prompts", name, "#{stem}.*")].empty?++ # The scene soundtrack: the Mix step's dialogue + score when present, else the Music step's audio.+ def soundtrack = self[:mix]&.dig("path") || fetch!(:music, :path)++ # The shared anime style bible (config/style.md), substituted for {{STYLE}} in every image and H3 prompt so one+ # paragraph keeps every character sheet, keyframe and shot in the same look.+ def self.style+ path = File.join(ROOT, "config", "style.md")+ File.file?(path) ? File.read(path).strip : nil+ end++ def expand(text)+ return text unless text.include?("{{STYLE}}")+ style = Project.style or raise "a prompt uses {{STYLE}} but config/style.md is missing"+ text.gsub("{{STYLE}}", style)+ end++ def prompt_path(stem)+ dir = File.join(ROOT, "prompts", name)+ Dir[File.join(dir, "#{stem}.*")].first or raise "no prompt #{stem}.* in #{dir}"+ end++ private++ def manifest_path = File.join(dir, "manifest.json")+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/reference_importer.rb b/skills/make-an-anime/scripts/lib/pipeline/reference_importer.rbnew file mode 100644index 0000000..e1ac7e3--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/reference_importer.rb@@ -0,0 +1,31 @@+require "digest"+require "uri"++module Pipeline+ # Reuse an approved identity already hosted by its original generation provider.+ # This does not upload the local reference or generate a new image.+ class ReferenceImporter+ def import(run:, image:, manifest:)+ original = JSON.parse(File.read(manifest)).fetch("ref_base")+ source_path = File.expand_path(original.fetch("path"), File.dirname(File.expand_path(manifest)))+ digest = Digest::SHA256.file(image).hexdigest+ unless digest == Digest::SHA256.file(source_path).hexdigest+ raise ArgumentError, "Reference bytes differ from the source manifest image; cannot reuse its URL"+ end+ url = URI(original.fetch("url"))+ raise ArgumentError, "Reference manifest must contain an HTTPS URL" unless url.is_a?(URI::HTTPS)+ project = Project.new(run)+ if project[:ref_base]+ current = project[:ref_base]+ return current if File.file?(current.fetch("path")) && Digest::SHA256.file(current["path"]).hexdigest == digest && current["url"] == url.to_s+ raise ArgumentError, "RUN=#{run} already has a different identity; import into a new versioned RUN"+ end+ target = project.path("01_ref_base#{File.extname(image)}")+ FileUtils.cp(image, target)+ project.record(:ref_base, path: target, url: url.to_s, endpoint: original["endpoint"],+ request_id: original["request_id"],+ provenance: { source_manifest: File.expand_path(manifest), sha256: digest,+ reused_hosted_reference: true })+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/step.rb b/skills/make-an-anime/scripts/lib/pipeline/step.rbnew file mode 100644index 0000000..73b7677--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/step.rb@@ -0,0 +1,117 @@+require "json"++module Pipeline+ # A pipeline stage. Subclasses implement:+ # #submit -> calls fal, returns Fal::Models::Base::Result+ # #materialize(result) -> downloads/post-processes a result, returns manifest data+ # #review -> local analysis (ffmpeg / magick / python), returns metrics hash+ # Splitting submit/materialize lets any past request_id be re-adopted (rake pick/adopt).+ class Step+ Result = Fal::Models::Base::Result++ attr_reader :project++ def self.key = name.split("::").last.gsub(/([a-z])([A-Z])/, '\1_\2').downcase.to_sym++ def initialize(project: Project.new, client: nil)+ @project = project+ @client = client+ end++ def key = self.class.key+ def done? = !!project[key]&.dig("path") && File.exist?(project[key]["path"])++ def run!(force: ENV["FORCE"] == "1")+ if done? && !force+ warn "[#{key}] already generated -> #{project[key]["path"]} (FORCE=1 to regenerate)"+ return project[key]+ end+ archive! if done?+ if (from = project.import_source(key))+ return import!(from)+ end+ warn "[#{key}] generating…"+ started = Time.now+ data = materialize(submit)+ project.record(key, data.merge(elapsed_s: (Time.now - started).round(1), review: nil))+ end++ # Make a previously completed fal request the current output (re-fetched from the queue).+ def adopt!(request_id)+ past = Array(project[key]&.dig("history")).find { |h| h["request_id"] == request_id } || {}+ archive! if done?+ output = client.result(endpoint, request_id)+ data = materialize(Result.new(request_id: request_id, input: past["input"], output: output))+ project.record(key, data.merge(review: nil))+ warn "[#{key}] adopted #{request_id} -> #{data[:path]}"+ end++ # Reuse another run's output for this step: same remote url, local files copied into this run.+ def import!(from)+ source = Project.new(from)[key] or raise "[#{key}] run '#{from}' has nothing to import (RUN=#{from} rake gen:#{key})"+ data = source.except("history", "updated_at").to_h do |k, v|+ next [k, v] unless k.end_with?("path") && v+ dest = project.path(File.basename(v))+ FileUtils.cp(v, dest)+ [k, dest]+ end+ warn "[#{key}] imported from #{from} -> #{data["path"]}"+ project.record(key, data.merge("imported_from" => from))+ end++ # rake pick[step,n] — adopt archived attempt n (1-based, see manifest history).+ def pick!(n)+ entry = Array(project[key]&.dig("history")).fetch(n - 1) { raise "no archived attempt #{n} for #{key}" }+ adopt!(entry.fetch("request_id"))+ end++ def review!+ raise "[#{key}] nothing to review, run `rake gen:#{key}` first" unless done?+ metrics = review+ File.write(project.review_path(key, "review.json"), JSON.pretty_generate(metrics))+ project.record(key, review: metrics.slice(:verdict, :checks))+ puts JSON.pretty_generate(metrics)+ metrics+ end++ protected++ def client = @client ||= Fal::Client.new+ def ffmpeg = @ffmpeg ||= Media::FFmpeg.new+ def magick = @magick ||= Media::ImageMagick.new+ def python = @python ||= Media::Python.new+ def seed = ENV["SEED"]&.to_i+ def endpoint = self.class::MODEL.endpoint++ # Common manifest fields for a fal result.+ def base_data(result)+ { request_id: result.request_id, endpoint: endpoint, input: result.input }+ end++ # Keep rejected attempts: copy of the primary file in output/<RUN>/rejected/ ++ # a full manifest snapshot (request_id, input, review) in history.+ def archive!+ entry = project[key]+ history = Array(entry["history"])+ if history.none? { |h| h["request_id"] == entry["request_id"] }+ dest = project.path("rejected", "#{key}_#{history.size + 1}#{File.extname(entry["path"])}")+ FileUtils.cp(entry["path"], dest)+ history += [entry.except("history").merge("archived" => dest)]+ project.record(key, history: history)+ warn "[#{key}] archived previous attempt -> #{dest}"+ end+ end++ def download(url, file)+ client.download(url, project.path(file))+ end++ # checks: { name => [ok?, detail] } -> verdict PASS / REVIEW+ def verdict(checks)+ {+ verdict: checks.values.all?(&:first) ? "PASS" : "REVIEW",+ checks: checks.transform_values { |ok, detail| "#{ok ? "ok" : "FAIL"} — #{detail}" }+ }+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/clips.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/clips.rbnew file mode 100644index 0000000..8d625d2--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/clips.rb@@ -0,0 +1,94 @@+module Pipeline+ module Steps+ # Step 4c — character sprites for a p5-animated section: each item is cut out of its background into a transparent PNG+ # sequence (output/<run>/04_clips/<name>/NNNN.png) that the overlay sketch loads with Anim.clip(name) and moves itself.+ # prompts/<run>/04_clips.yml lists the items; the source is one of+ # image / end_image (+ prompt) an H3 clip from keyframes (as in Shots); audio_at: <song seconds> pins the song from there,+ # so sprite frame i lip-syncs to song time audio_at + i/24; seconds: 5..15 (default 5);+ # audio: <cast id> drives the lip-sync with that character's mouth track from the Dialogue step, or+ # audio: <path> with another full-song-aligned track instead of the mix (a vocal+ # stem from `rake media:stems`, so the mouth rests in the singer's pauses), gate: <dB> silences it below+ # source: <path> an existing video in the repo+ # still: <keyframe> | <run>/<keyframe> | run:<run> a keyframe of this run or another, or another run's ref_base (a single frame)+ # and the cut-out options: key: paper | green (chroma background), box: [x, y, w, h] crop in source pixels,+ # seed: [x, y] a point on the character (paper key: only the part connected to it is kept), frames: how many (default all),+ # start: first frame, scale: resize factor, low: <0-255> a stricter green key for fire or glow cast on the green (default 25). RECUT=1 ONLY=<name> FORCE=1 re-cuts a downloaded H3 clip without a fal call.+ class Clips < ItemsStep+ MODEL = Fal::Models::H3MaxImageToVideo+ FPS = 24++ def specs = @specs ||= yaml("04_clips").to_h { |clip| [clip.fetch("name"), clip] }++ def generate(name, spec)+ source, generated = source_for(name, spec)+ dir = project.path("04_clips", name)+ FileUtils.rm_rf(dir)+ cut = python.cutout(source, dir, spec.fetch("key", "paper"), **spec.slice("box", "seed", "frames", "start", "scale", "low").transform_keys(&:to_sym))+ meta = cut.merge("dir" => dir.delete_prefix("#{ROOT}/"), "fps" => FPS, "audio_at" => spec["audio_at"], "source" => source)+ File.write(project.path("04_clips", "#{name}.json"), JSON.pretty_generate(meta))+ { path: project.path("04_clips", "#{name}.json"), source: source, frames: cut["frames"], **generated }+ end++ # Deliverable: a board of every sprite's first frame.+ def finish(items)+ pairs = items.map { |name, item| [File.join(ROOT, JSON.parse(File.read(item["path"]))["dir"], "0000.png"), "#{name} (#{item["frames"]}f)"] }+ { path: magick.board(pairs, project.path("04_clips.jpg"), tile: "4x", width: 480) }+ end++ def review+ items = project[key]["items"]+ coverage = items.to_h do |name, item|+ meta = JSON.parse(File.read(item["path"]))+ [name, (magick.alpha_coverage(File.join(ROOT, meta["dir"], "0000.png")) * 100).round(1)]+ end+ {+ board: project[key]["path"], coverage_pct: coverage,+ **verdict(coverage.to_h { |name, pct| ["#{name} cut out", [pct.between?(3, 90), "#{pct}% opaque, #{items[name]["frames"]} frames"]] })+ }+ end++ protected++ def endpoint = MODEL.endpoint++ private++ # [local file to cut out, manifest fields of the fal request when one was made]+ def source_for(name, spec)+ return [File.expand_path(spec["source"], ROOT), {}] if spec["source"]+ if (still = spec["still"])+ return [Project.new(still.delete_prefix("run:")).fetch!(:ref_base, :path), {}] if still.start_with?("run:")+ return [project.keyframe(still)["path"], {}]+ end+ # RECUT=1: cut the already-downloaded H3 clip again (new box/key/frames) instead of calling fal.+ prev = project[key]&.dig("items", name)+ if ENV["RECUT"] == "1" && prev&.dig("url") && File.exist?(local = project.path("04_clip_#{name}.mp4"))+ return [local, prev.slice("request_id", "input", "url").transform_keys(&:to_sym)]+ end+ seconds = spec.fetch("seconds", 5)+ audio = if spec["audio"] && spec["audio_at"] then stem_url(name, spec, seconds)+ elsif spec["audio_at"] then song_url(name, spec["audio_at"], seconds)+ end+ result = MODEL.new(client: client).animate(+ prompt: Shots.h3_prompt(project, spec), image_url: keyframe_url(spec.fetch("image")),+ end_image_url: spec["end_image"]&.then { |k| keyframe_url(k) }, target_audio_url: audio,+ duration: seconds, seed: seed, resolution: ENV.fetch("VIDEO_RES", MODEL::DEFAULT_RES)+ )+ url = result.output.fetch("video")["url"]+ [download(url, "04_clip_#{name}.mp4"), { request_id: result.request_id, input: result.input, url: url }]+ end++ # `seconds` of a full-song-aligned track (spec audio:) from this section's audio_at, as H3's target audio: the section's song offset+ # is added, and an optional gate (dB) turns the stem's bleed in the pauses into silence (H3 then closes the mouth there).+ def stem_url(name, spec, seconds)+ from = project.generation.fetch(:music_offset, 0) + spec["audio_at"]+ gate = spec["gate"] ? ["-af", "agate=threshold=#{10**(spec["gate"] / 20.0)}:ratio=9000:attack=1:release=40:range=0.001"] : []+ out = project.path("04_audio_#{name}.wav")+ ffmpeg.run("ffmpeg", "-y", "-v", "error", "-ss", from.round(4).to_s, "-i", project[:dialogue]&.dig("tracks", spec["audio"]) || File.expand_path(spec["audio"], ROOT), "-t", seconds.to_s,+ *gate, "-ar", "44100", out)+ out = ffmpeg.fit_audio(out, project.path("04_audio_#{name}_padded.wav"), seconds: 2, fade: 0) if ffmpeg.duration(out) < 2+ client.upload(out)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/dialogue.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/dialogue.rbnew file mode 100644index 0000000..985eb06--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/dialogue.rb@@ -0,0 +1,168 @@+require "yaml"++module Pipeline+ module Steps+ # Step 3a — the scene's voiced lines (ElevenLabs Eleven v4 via Fal), placed on the scene timeline.+ #+ # config/cast.yml (shared by every scene) casts one voice per character:+ # hero: { name: Hero, voice: Brian, stability: 0.45, similarity_boost: 0.8, ref: char-hero-v1 }+ # prompts/<run>/03_dialogue.yml lists the lines in any order:+ # - name: kid-asks # unique id, also the cache key (ONLY=kid-asks FORCE=1 regenerates one line)+ # character: kid # a cast.yml id+ # at: 3.6 # scene-local start time, seconds+ # text: "[sleepy] Dad… are you making a game?" # audio tags in [brackets] are performed, not spoken+ # vo: false # true: narration/off-screen; mixed, but never drives a mouth+ # subtitle: "Gatto! (Cat!)" # optional: what the subtitle shows instead of `text` (a gloss); not sent to TTS+ # gate_s: 0.28 # optional: silence the start of the take in the mix (a blip before the first word)+ # keep_s: 1.2 # optional: keep only this much of the take (a long tail of breath or silence)+ # inner: true # optional, with vo: a thought in the character's head, treated so it isn't heard as spoken+ # subtitle: " " # a blank subtitle: a laugh or breath with no caption, not counted as speech when levelling+ # gain_db: -5 # optional: level this take in the scene mix only (takes vary by ±8 dB); the mouth+ # # track keeps the raw take, so H3 inputs and their cache are untouched+ # Line records also carry speech_at: `at` plus the take's measured leading silence, where the voice actually starts+ # (subtitles start there; the TTS alignment is not trusted for this — after a long tag it put a word 1.1 s late).+ # # optional overrides: voice, stability, similarity_boost, seed, language_code+ #+ # Deliverables: 03_dialogue.wav (every line placed, scene length), 03_voice_<character>.wav (only that character's+ # on-screen lines, silent elsewhere: the H3 target audio for that character's shots, so the mouth rests while others+ # talk) and 03_dialogue_words.json (scene-local word cues [{w, s, e, character, line}] for subtitles and p5 timing).+ class Dialogue < ItemsStep+ MODEL = Fal::Models::ElevenTtsV4+ VOICE_KEYS = %w[stability similarity_boost seed language_code apply_text_normalization].freeze++ def self.cast(root = ROOT)+ path = File.join(root, "config", "cast.yml")+ raise "config/cast.yml is missing: cast one ElevenLabs voice per character first" unless File.file?(path)+ YAML.safe_load_file(path)+ end++ def cast = @cast ||= self.class.cast++ def specs+ @specs ||= yaml("03_dialogue").to_h do |line|+ name = line.fetch("name")+ raise ArgumentError, "line #{name}: unknown character #{line["character"].inspect} (cast: #{cast.keys.join(", ")})" unless cast.key?(line["character"])+ raise ArgumentError, "line #{name}: `at` must be a scene-local time in seconds" unless line["at"].is_a?(Numeric) && line["at"] >= 0+ [name, line]+ end+ end++ def generate(name, spec)+ voice = cast.fetch(spec.fetch("character"))+ opts = voice.slice(*VOICE_KEYS).merge(spec.slice(*VOICE_KEYS)).transform_keys(&:to_sym)+ result = MODEL.new(client: client).speak(text: spec.fetch("text"), voice: spec.fetch("voice", voice.fetch("voice")), **opts)+ url = result.output.fetch("audio").fetch("url")+ mp3 = download(url, "03_line_#{name}.mp3")+ wav = ffmpeg.extract_audio(mp3, project.path("03_line_#{name}.wav"))+ { request_id: result.request_id, input: result.input, url: url, path: wav, duration: ffmpeg.duration(wav).round(3),+ words: self.class.words(result.output["timestamps"]) }+ end++ def finish(items)+ length = project.duration+ lines = specs.map do |name, spec|+ item = items.fetch(name)+ { "name" => name, "character" => spec["character"], "text" => spec["text"], "at" => spec["at"].to_f,+ "end" => (spec["at"] + (spec["keep_s"] || item["duration"])).round(3), "vo" => !!spec["vo"], "path" => item["path"],+ "speech_at" => (spec["at"] + [ffmpeg.leading_silence(item["path"]), spec["gate_s"].to_f].max).round(3), "subtitle" => spec["subtitle"],+ "gate_s" => spec["gate_s"]&.to_f, "keep_s" => spec["keep_s"]&.to_f, "inner" => spec["inner"],+ "gain_db" => spec["gain_db"]&.to_f }.compact+ end.sort_by { |l| l["at"] }+ late = lines.select { |l| l["end"] > length + 0.05 }+ raise "lines end after the scene (#{length}s): #{late.map { |l| "#{l["name"]} ends #{l["end"]}s" }.join(", ")}; move `at` or lengthen the scene" if late.any?+ lines.group_by { |l| l["character"] }.each do |character, own|+ own.each_cons(2) do |a, b|+ raise "#{character} talks over themself: #{a["name"]} ends #{a["end"]}s, #{b["name"]} starts #{b["at"]}s" if b["at"] < a["end"]+ end+ end+ tracks = cast.keys.select { |c| lines.any? { |l| l["character"] == c } }.to_h do |character|+ own = lines.select { |l| l["character"] == character && !l["vo"] }.map { |l| l.except("gain_db") }+ [character, ffmpeg.place_audio(own, project.path("03_voice_#{character}.wav"), seconds: length)]+ end+ words = lines.flat_map do |l|+ self.class.spoken_words(items[l["name"]]["words"]).map { |w| w.merge("s" => (w["s"] + l["at"]).round(3), "e" => (w["e"] + l["at"]).round(3), "character" => l["character"], "line" => l["name"]) }+ end+ File.write(project.path("03_dialogue_words.json"), JSON.pretty_generate(words))+ File.write(project.path("03_dialogue_lines.json"), JSON.pretty_generate(lines.map { |l| l.except("path") }))+ { path: ffmpeg.place_audio(lines, project.path("03_dialogue.wav"), seconds: length), tracks: tracks,+ words: project.path("03_dialogue_words.json"), lines: project.path("03_dialogue_lines.json") }+ end++ # Local timing checks plus a paid Whisper pass per line, so a spoken audio tag or a dropped word is caught before animation.+ def review+ data = project[key]+ lines = JSON.parse(File.read(data["lines"]))+ whisper = Fal::Models::Whisper.new(client: client)+ heard = lines.to_h do |l|+ url = data.dig("items", l["name"], "url")+ text = url ? whisper.transcribe(audio_url: url).output["text"].to_s.strip : ""+ [l["name"], text]+ end+ checks = lines.to_h do |l|+ want = self.class.spoken(l["text"])+ got = self.class.spoken(heard[l["name"]])+ missing, extra = self.class.word_diff(want, got)+ ["#{l["name"]} (#{l["character"]}) says its text", [missing.size <= [1, want.size / 6].max && extra.size <= [1, want.size / 6].max,+ "heard #{heard[l["name"]].inspect}; missing #{missing.inspect}; extra #{extra.inspect}"]]+ end+ tracks = data["tracks"].transform_values { |p| ffmpeg.summary(p)[:duration] }+ checks["mouth tracks are scene length"] = [tracks.values.all? { |d| (d - project.duration).abs < 0.05 }, tracks.inspect]+ { lines: lines, heard: heard, **verdict(checks) }+ end++ # Normalised spoken words of a line: audio tags in [brackets] and IPA in /slashes/ removed.+ # Words missing from / added to a take, counted as multisets: a doubled phrase ("Software should be free. Software+ # should be free — free as in freedom.") is extra words even though every word is also in the script.+ def self.word_diff(want, got)+ w, g = want.tally, got.tally+ [w.flat_map { |k, n| [k] * [n - g.fetch(k, 0), 0].max }, g.flat_map { |k, n| [k] * [n - w.fetch(k, 0), 0].max }]+ end++ def self.spoken(text)+ text.to_s.gsub(/\[[^\]]*\]/, " ").gsub(%r{/[^/]*/}, " ").downcase.unicode_normalize(:nfkd).gsub(/[^a-z0-9' ]/, " ").split+ end++ # ElevenLabs timestamps -> [{ "w", "s", "e" }] per word. Accepts word entries ({text|word, start, end}) or the+ # character alignment ({characters, character_start_times_seconds, character_end_times_seconds}).+ # Word cues without performed audio tags ("[sleepy," "mumbling]") or punctuation-only tokens ("…", "—").+ def self.spoken_words(words)+ depth = 0+ Array(words).filter_map do |w|+ text = w["w"].to_s+ inside = depth.positive? || text.start_with?("[")+ depth += text.count("[") - text.count("]")+ depth = 0 if depth.negative?+ rest = text.include?("]") ? text.sub(/\A.*\]/, "") : ""+ next if inside && rest.empty?+ text = rest if inside+ next unless text.match?(/[\p{L}\p{N}]/)+ w.merge("w" => text)+ end+ end++ def self.words(timestamps)+ return [] if timestamps.nil?+ entries = timestamps.is_a?(Hash) ? [timestamps] : Array(timestamps)+ if entries.first.is_a?(Hash) && entries.first.key?("characters")+ # Streamed alignments arrive in chunks that can split a word ("M" | "inecraft"): join them first.+ chars = entries.flat_map { |a| a["characters"].zip(a["character_start_times_seconds"], a["character_end_times_seconds"]) }+ chars.chunk_while { |x, y| x[0] !~ /\s/ && y[0] !~ /\s/ }.reject { |run| run.first[0] =~ /\s/ }+ .map { |run| { "w" => run.map(&:first).join, "s" => run.first[1].to_f, "e" => run.last[2].to_f } }+ else+ entries.filter_map do |t|+ next unless t.is_a?(Hash)+ word = t["text"] || t["word"] || t["w"]+ first = t["start"] || t["s"] || t.dig("timestamp", 0)+ last = t["end"] || t["e"] || t.dig("timestamp", 1)+ next if word.to_s.strip.empty? || first.nil? || last.nil?+ { "w" => word.to_s.strip, "s" => first.to_f, "e" => last.to_f }+ end+ end+ end++ protected++ def endpoint = MODEL.endpoint+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/keyframes.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/keyframes.rbnew file mode 100644index 0000000..94227bb--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/keyframes.rb@@ -0,0 +1,52 @@+module Pipeline+ module Steps+ # Step 2b — new framings of the reference character (extreme close-up, reframed, other gaze...) for the Shots step:+ # prompts/<run>/02_keyframes.yml { name => edit prompt }, each sent with the ref_base image to gpt-image-2.5/edit.+ # A spec can also be { "prompt" => ..., "refs" => [run, ...] } to add other runs' ref_base images (a second character):+ # image_urls = [this run's ref_base, *those], so the prompt can say "the character in the second image".+ # "base" => <keyframe name> edits an earlier keyframe of this list instead of ref_base (same framing, new pose),+ # "base" => false sends only the refs (a keyframe without the singer), "base" => "<run>/<keyframe>" edits another run's keyframe.+ class Keyframes < ItemsStep+ MODEL = Fal::Models::GptImage25Edit++ def specs = yaml("02_keyframes")++ def generate(name, spec)+ spec = { "prompt" => spec } if spec.is_a?(String)+ refs = Array(spec["refs"]).map { |run| Project.new(run).fetch!(:ref_base, :url) }+ result = MODEL.new(client: client).edit(prompt: project.expand(spec.fetch("prompt")), image_urls: [*base_url(spec.fetch("base", "ref_base")), *refs])+ url = result.output.fetch("images").first["url"]+ { request_id: result.request_id, input: result.input, url: url, path: download(url, "02_kf_#{name}.png") }+ end++ # Deliverable: a labelled board of the reference + every keyframe.+ def finish(items)+ # A scene run has no ref_base of its own (its cast comes in through refs:), so the board starts at its keyframes.+ pairs = (project[:ref_base] ? [[project[:ref_base]["path"], "ref_base"]] : []) + items.map { |name, item| [item["path"], name] }+ { path: magick.board(pairs, project.path("02_keyframes.jpg"), tile: "2x", width: 960) }+ end++ def review+ items = project[key]["items"]+ info = items.transform_values { |item| magick.identify(item["path"]) }+ {+ board: project[key]["path"], images: info,+ **verdict(items.keys.to_h { |name| ["#{name} 16:9 >= 1920w", [(info[name][:aspect] - 1.778).abs < 0.05 && info[name][:w] >= 1920, "#{info[name][:w]}x#{info[name][:h]}"]] })+ }+ end++ protected++ def endpoint = MODEL.endpoint++ private++ def base_url(base)+ return if base == false+ return project.fetch!(:ref_base, :url) if base == "ref_base"+ return project.keyframe(base)["url"] if base.include?("/")+ project.fetch!(key, :items).fetch(base) { raise "[#{key}] base '#{base}' must be a keyframe listed before this one" }["url"]+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/mix.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/mix.rbnew file mode 100644index 0000000..072d7a7--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/mix.rb@@ -0,0 +1,57 @@+module Pipeline+ module Steps+ # Step 3c — the scene soundtrack (local, no Fal call): the score (Music step) ducked under the dialogue (Dialogue step),+ # limited, at the scene's exact length -> 03_mix.wav. Shots, Overlay and the final assembly use it via Project#soundtrack.+ # Generation option `mix: { music_db: -4, dialogue_db: 0, duck: true, music_end: 19.5 }`; music_end hard-cuts the score+ # (a smash cut) with a 30 ms fade, or over music_out seconds; ambience and spot effects are added later by sfx:mix.+ # voice_lift_db raises the voice over the bed and writes 03_mix_ref.wav without it (see Media::Sfx#voice_args).+ # A mix older than its score or dialogue file is stale and is rebuilt without FORCE (a music retake used to leave the+ # old mix in 03_mix.wav and final.mp4).+ class Mix < Step+ def done? = super && !stale?++ def stale?+ built = File.mtime(project[key]["path"])+ newer = [project[:music]&.dig("path"), project[:dialogue]&.dig("path")].compact.select { |p| File.exist?(p) && File.mtime(p) > built }+ warn "[#{key}] stale: #{newer.join(", ")} newer than the mix -> rebuilding" if newer.any?+ newer.any?+ end++ def submit+ Result.new(request_id: nil, input: settings, output: {})+ end++ def materialize(result)+ music = project.fetch!(:music, :path)+ dialogue = project[:dialogue]&.dig("path")+ opts = settings.except("voice_lift_db").transform_keys(&:to_sym)+ lift = settings["voice_lift_db"].to_f+ # The mix without the lift stays beside it: sfx:mix reads cue levels from it, so a louder voice keeps the effects where they were.+ ffmpeg.duck_mix(music, dialogue, project.path("03_mix_ref.wav"), seconds: project.duration, **opts) if lift.positive?+ out = ffmpeg.duck_mix(music, dialogue, project.path("03_mix.wav"), seconds: project.duration, **opts, dialogue_db: opts.fetch(:dialogue_db, 0) + lift)+ { request_id: nil, endpoint: "local:mix", input: result.input.merge("music" => music, "dialogue" => dialogue), path: out }+ end++ def review+ mix = project[key]["path"]+ summary = ffmpeg.summary(mix)+ energy = python.audio_energy(ffmpeg.to_wav(mix, project.review_path(key, "mix.wav")))+ {+ summary: summary, waveform: ffmpeg.waveform(mix, project.review_path(key, "waveform.png")),+ **verdict(+ "scene length" => [(summary[:duration] - project.duration).abs < 0.05, "#{summary[:duration]}s / #{project.duration}s"],+ "not silent" => [energy["windows"].count { |w| w["rms_db"] > -40 } >= energy["windows"].size * 0.5, "#{energy["windows"].count { |w| w["rms_db"] > -40 }}/#{energy["windows"].size} windows > -40dB"]+ )+ }+ end++ protected++ def endpoint = "local:mix"++ private++ def settings = { "music_db" => -4, "dialogue_db" => 0, "duck" => true }.merge(project.generation.fetch(:mix, {}).transform_keys(&:to_s))+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/music.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/music.rbnew file mode 100644index 0000000..5cb1ef7--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/music.rb@@ -0,0 +1,124 @@+module Pipeline+ module Steps+ # Step 3 — the sung hook (minimax/music-3), fitted to exactly project.duration seconds+ # and re-uploaded so the video step and the final mux use the same audio.+ # Generations with `import: { music: "run1" }` reuse that run's song instead, and+ # `music_from: <file>` cuts it from a local video/audio file (run4: the reference clip's song); with+ # `music_offset: <seconds>` only project.duration seconds from there (one section of a longer song).+ class Music < Step+ MODEL = Fal::Models::Music3++ # A fit whose source changed is stale and is re-fitted without FORCE: music_from added, removed or pointed+ # elsewhere after gen:music ran, or the shaped file rebuilt after the fit (a raw take once shipped because+ # music_from was set after the first gen:music). Mix then sees a newer score and rebuilds too.+ def done? = super && !stale?++ def stale?+ return false if project.import_source(key)++ rec = project[key]+ why = if rec["endpoint"] != endpoint then "source #{rec["endpoint"]} -> #{endpoint}"+ elsif source_file && File.exist?(source_file) && File.mtime(source_file) > File.mtime(rec["path"])+ "#{source_file} newer than the fit"+ end+ warn "[#{key}] stale: #{why} -> refitting" if why+ !why.nil?+ end++ # Anime score: prompts/<run>/03_score.json ({ "chunks": [...] } composition plan) or 03_score.txt (a prompt) uses+ # ElevenLabs Music v2.5, instrumental, scene length. Generation option music_fade: seconds of fade-out (default 0.4).+ def submit+ return extract(source_file) if source_file+ return score if project.prompt?("03_score")++ MODEL.new(client: client).compose(+ prompt: project.prompt("03_music_prompt"),+ lyrics: project.prompt("03_music_lyrics"),+ duration: project.duration, seed: seed+ )+ end++ def materialize(result)+ audio = result.output.fetch("audio")+ raw = if audio["path"]+ offset = project.generation[:music_offset]+ ffmpeg.extract_audio(audio["path"], project.path("03_music_raw.wav"), from: offset || 0, seconds: offset && project.duration)+ else+ download(audio["url"], "03_music_raw#{ext(audio["url"])}")+ end+ # A section of a longer song (music_offset) is not faded, so sections join back into the original track.+ fade = project.generation[:music_offset] ? 0 : project.generation.fetch(:music_fade, 0.4)+ fitted = ffmpeg.fit_audio(raw, project.path(format("03_music_%gs.wav", project.duration)), seconds: project.duration, fade: fade)+ base_data(result).merge(+ raw_url: audio["url"], raw_path: raw, model_duration: result.output["duration"], seed: result.output["seed"],+ path: fitted, url: project.generation.fetch(:upload_music, true) ? client.upload(fitted) : nil+ )+ end++ def review+ raw, fitted = project[key]["raw_path"], project[key]["path"]+ wav = ffmpeg.to_wav(raw, project.review_path(key, "raw.wav"))+ energy = python.audio_energy(wav)+ loud = energy["windows"].select { |w| w["rms_db"] > -30 }+ vocal = energy["windows"].select { |w| w["rms_db"] > -30 && w["vocal_ratio"] > 0.35 }+ transcript = transcribe+ words = transcript[:text].downcase.scan(/[a-z']+/)+ expected = project.generation.fetch(:lyrics, [])+ {+ transcript: transcript,+ raw: ffmpeg.summary(raw), fitted: ffmpeg.summary(fitted),+ waveform: ffmpeg.waveform(raw, project.review_path(key, "waveform.png")),+ spectrogram: ffmpeg.spectrogram(raw, project.review_path(key, "spectrogram.png")),+ energy_timeline: energy["windows"].map { |w| "#{w["t"]}s #{w["rms_db"]}dB v#{w["vocal_ratio"]}" },+ **verdict(+ "raw length ~#{project.duration}s" => [(energy["duration"] - project.duration).abs <= 2.5, "#{energy["duration"]}s raw"],+ "fitted exactly #{project.duration}s" => [(ffmpeg.duration(fitted) - project.duration).abs < 0.1, "#{ffmpeg.duration(fitted).round(2)}s"],+ "not silent" => [loud.size >= energy["windows"].size * 0.6, "#{loud.size}/#{energy["windows"].size} windows > -30dB"],+ "vocal band present" => [expected.empty? || vocal.size >= 3, "#{vocal.size} windows with strong 300-3400Hz share#{" (instrumental score: not required)" if expected.empty?}"],+ "no long silent tail" => [energy["silence_tail_s"] < 2.5, "#{energy["silence_tail_s"]}s"],+ "lyrics sung" => [(expected - words).empty?, "missing #{(expected - words).inspect}, whisper: #{transcript[:text].inspect}"]+ )+ }+ end++ protected++ def endpoint+ return "local:#{source_file}" if source_file+ project.prompt?("03_score") ? Fal::Models::ElevenMusic25.endpoint : super+ end++ private++ def source_file = project.generation[:music_from]++ def score+ file = project.prompt_path("03_score")+ model = Fal::Models::ElevenMusic25.new(client: client)+ if file.end_with?(".json")+ plan = JSON.parse(project.prompt("03_score"))+ total = plan.fetch("chunks").sum { |c| c.fetch("duration_ms") }+ raise ArgumentError, "03_score.json chunks total #{total}ms, longer than the #{project.duration}s scene" if total > project.duration * 1000 + 50+ model.compose(composition_plan: plan, seed: seed)+ else+ model.compose(prompt: project.prompt("03_score"), duration: project.duration)+ end+ end++ # A stand-in fal result pointing at the local file, so run!/materialize work unchanged.+ def extract(file)+ Result.new(request_id: nil, input: { file: file, offset: project.generation[:music_offset] }.compact,+ output: { "audio" => { "path" => File.expand_path(file, ROOT) } })+ end++ def ext(url) = File.extname(URI(url).path).then { |e| e.empty? ? ".mp3" : e }++ # Whisper transcript of the fitted master, with segment timestamps.+ def transcribe+ return { text: "", segments: [], skipped: "upload_music: false; local audio review only" } unless project[key]["url"]+ out = Fal::Models::Whisper.new(client: client).transcribe(audio_url: project[key]["url"]).output+ { text: out["text"].to_s.strip, segments: Array(out["chunks"]).map { |c| "#{c["timestamp"]&.join("-")}s #{c["text"].to_s.strip}" } }+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/overlay.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/overlay.rbnew file mode 100644index 0000000..48499dd--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/overlay.rb@@ -0,0 +1,154 @@+module Pipeline+ module Steps+ # Step 5 — motion-graphics overlay: the p5.js sketch prompts/<run>/05_overlay.js, rendered to a transparent+ # PNG sequence by anim/render.mjs and composited over the plate (video or shots step's final.mp4) -> final_overlay.mp4.+ # The sketch gets Whisper word timestamps of the song (Anim.data("words")) and, for every generation+ # `track: { name => [x, y, size, search, from_frame] }`, that feature's per-frame position (Anim.data(name)).+ # On a multi-shot plate it also gets the edit, Anim.data("shots") = [{ name, start_frame, frames }], to cut with the picture.+ # With a Clips step it gets the character sprites, Anim.data("clips") = { name => { dir, frames, w, h, audio_at, box, src } } (Anim.clip(name)),+ # and `plate: <keyframe>` (or "<run>/<keyframe>") in the generation makes the plate that keyframe held still (paper): the sketch animates everything else.+ class Overlay < Step+ MODEL = Fal::Models::Whisper+ OUT = "final_overlay.mp4".freeze++ # An anime scene (with a Dialogue step) already has scene-local word cues, and its score has no lyrics: the overlay+ # is entirely local. A music video transcribes the song with Whisper (paid).+ def run!(force: ENV["FORCE"] == "1")+ return super unless project[:dialogue]+ if done? && !force+ warn "[#{key}] already generated -> #{project[key]["path"]} (FORCE=1 to regenerate)"+ return project[key]+ end+ archive! if done?+ warn "[#{key}] rendering locally from the dialogue cues…"+ prepare!+ render!+ end++ def submit+ MODEL.new(client: client).transcribe(audio_url: project.fetch!(:music, :url), chunk_level: "word")+ end++ def materialize(result)+ words = Array(result.output["chunks"]).map { |c| { w: c["text"].to_s.strip, s: c.dig("timestamp", 0), e: c.dig("timestamp", 1) } }+ File.write(data_path(:words), JSON.pretty_generate(words))+ track!+ base_data(result).merge(render!)+ end++ # Reuse approved global word timings without another paid transcription.+ def prepare!(words_path = nil)+ if words_path.nil? && project[:dialogue]&.dig("words")+ # Dialogue word cues are already scene-local.+ FileUtils.cp(project[:dialogue]["words"], data_path(:words))+ track!+ return { words: data_path(:words), count: JSON.parse(File.read(data_path(:words))).size, source: "dialogue" }+ end+ raw = words_path ? JSON.parse(File.read(words_path)) : []+ chunks = raw.is_a?(Array) ? raw : raw.fetch("chunks") { raw.fetch("words", []) }+ offset = project.generation.fetch(:music_offset, 0)+ words = chunks.filter_map do |chunk|+ first = chunk["s"] || chunk.dig("timestamp", 0) || chunk["start"]+ last = chunk["e"] || chunk.dig("timestamp", 1) || chunk["end"]+ next unless first && last && last > offset && first < offset + project.duration+ { w: (chunk["w"] || chunk["text"] || chunk["word"]).to_s.strip,+ s: [first - offset, 0].max, e: [last - offset, project.duration].min }+ end+ File.write(data_path(:words), JSON.pretty_generate(words))+ track!+ { words: data_path(:words), count: words.size, local_offset: offset }+ end++ # Render all frames and composite, from the saved words.json / track files (no fal call): rake anim:overlay.+ def render!+ dir = project.path("05_overlay", "frames")+ FileUtils.rm_rf(dir)+ summary = anim.render(sketch, dir, **plate_format, data: data_files)+ path = ffmpeg.overlay_frames(plate, dir, project.path(OUT), fps: plate_format[:fps])+ data = { path: path, frames_dir: dir, sketch: sketch, render_ms: summary["ms"] }+ project.record(key, data.merge(review: nil))+ data+ end++ # Render only `frames` and composite each over its plate frame into one board: rake anim:preview[0,48,96].+ def preview!(frames)+ dir = project.path("05_overlay", "preview")+ prepare! if project[:dialogue]&.dig("words") && !File.file?(data_path(:words)) # a preview before the first overlay render+ anim.render(sketch, dir, **plate_format, data: data_files, only: frames)+ stills = frames.map do |i|+ [ffmpeg.overlay_still(plate, i, File.join(dir, format("%04d.png", i)), File.join(dir, format("still_%04d.jpg", i))),+ format("f%d %.2fs", i, i.to_f / plate_format[:fps])]+ end+ magick.board(stills, project.review_path(key, "preview.jpg"), tile: "#{[stills.size, 3].min}x", width: 960).tap { |b| puts b }+ end++ def review+ final = project[key]["path"]+ summary = ffmpeg.summary(final)+ frames = Dir[File.join(project[key]["frames_dir"], "*.png")].sort+ coverage = frames.each_slice(6).map(&:first).to_h { |f| [File.basename(f, ".png").to_i, (magick.alpha_coverage(f) * 100).round(1)] }+ compare = ffmpeg.hstack(reference, final, project.review_path(key, "reference_vs_overlay.mp4")) if reference+ {+ summary: summary, contact_sheet: ffmpeg.contact_sheet(final, project.review_path(key, "contact_sheet.jpg"), cols: 6, rows: 3),+ coverage_pct_by_frame: coverage, compare: compare,+ **verdict(+ "same length as plate" => [(summary[:duration] - ffmpeg.duration(plate)).abs < 0.05, "#{summary[:duration]}s"],+ "every plate frame rendered" => [frames.size == plate_format[:frames], "#{frames.size}/#{plate_format[:frames]} png"],+ "audio kept" => [summary.dig(:audio, :codec) == "aac", summary[:audio].inspect],+ "overlay present" => [coverage.values.count(&:positive?) >= coverage.size * 0.8, "#{coverage.values.count(&:positive?)}/#{coverage.size} sampled frames have graphics"],+ # a still plate is just paper: the sketch is the picture+ "plate not buried" => [still_plate? || coverage.values.max < 45, "max coverage #{coverage.values.max}%"]+ )+ }+ end++ protected++ def anim = @anim ||= Media::Anim.new++ private++ def sketch = project.prompt_path("05_overlay")+ # The video to draw on: a held keyframe (plate:), the multi-shot plate, or the single-shot video.+ def plate+ return project.fetch!(project.step?(Shots) ? :shots : :video, :path) unless still_plate?+ out = project.path("04_plate_still.mp4")+ return out if File.exist?(out)+ image = project.keyframe(project.generation[:plate])["path"]+ ffmpeg.still_plate(image, project.soundtrack, out, seconds: project.duration, fps: Clips::FPS)+ end++ def still_plate? = !!project.generation[:plate]+ def reference = project.generation[:reference]&.then { |f| File.join(ROOT, f) }+ def data_path(name) = project.path("05_overlay", "#{name}.json")+ def tracks = project.generation.fetch(:track, {})++ def data_files+ files = { words: data_path(:words), **tracks.keys.to_h { |name| [name, data_path(name)] } }+ files[:dialogue] = project[:dialogue]["lines"] if project[:dialogue]&.dig("lines") # Anim.data("dialogue"): [{name, character, text, at, end, vo}]+ if project.step?(Clips)+ clips = project.fetch!(:clips, :items).transform_values { |item| JSON.parse(File.read(item["path"])).slice("dir", "frames", "w", "h", "audio_at", "box", "src") }+ File.write(data_path(:clips), JSON.pretty_generate(clips))+ files[:clips] = data_path(:clips)+ end+ return files unless project.step?(Shots)+ shots = Shots.new(project: project).specs.map { |name, s| { name: name, start_frame: s["start_frame"], frames: s["frames"], roll: s["roll"] }.compact }+ File.write(data_path(:shots), JSON.pretty_generate(shots))+ files.merge(shots: data_path(:shots))+ end++ def track!+ tracks.each do |name, (x, y, size, search, from)|+ File.write(data_path(name), JSON.generate(python.track_template(plate, x, y, size, search || size, from || 0)))+ end+ end++ def plate_format+ @plate_format ||= ffmpeg.summary(plate).then do |s|+ { width: s.dig(:video, :w), height: s.dig(:video, :h), fps: s.dig(:video, :fps),+ frames: s.dig(:video, :frames) || (s[:duration] * s.dig(:video, :fps)).round }+ end+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/ref_base.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/ref_base.rbnew file mode 100644index 0000000..7c087e0--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/ref_base.rb@@ -0,0 +1,49 @@+module Pipeline+ module Steps+ # Step 1 — the singer reference frame (text-to-image, prompt = prompts/<run>/01_ref_base.*).+ # nano-banana-2 unless the generation sets image_model: (e.g. run3 uses gpt-image-2.5).+ class RefBase < Step+ MODEL = Fal::Models::GptImage25++ # A character sheet from reference photos: `photos: ["references/hero/front.png", ...]` (project-relative) are uploaded+ # and sent with the prompt to the Sunburst edit endpoint, which redraws the person in the approved anime style.+ def submit+ source = project.generation[:edit_from]+ photos = Array(project.generation[:photos])+ if source || photos.any?+ urls = photos.map { |p| client.upload(File.expand_path(p, ROOT)) }+ urls.unshift(source.include?("/") ? project.keyframe(source).fetch("url") : Project.new(source).fetch!(:ref_base, :url)) if source+ return model.new(client: client).edit(prompt: project.prompt("01_ref_base"), image_urls: urls)+ end+ model.new(client: client).generate(prompt: project.prompt("01_ref_base"), aspect_ratio: "16:9", seed: seed)+ end++ def materialize(result)+ image = result.output.fetch("images").first+ base_data(result).merge(url: image["url"], path: download(image["url"], "01_ref_base.png"),+ description: result.output["description"])+ end++ def review+ path = project[key]["path"]+ info = magick.identify(path)+ split = python.style_split(path)["images"].first+ preview = magick.preview(path, project.review_path(key, "preview.jpg"))+ checks = {+ "16:9 landscape" => [(info[:aspect] - 1.778).abs < 0.05, "aspect #{info[:aspect]}"],+ "resolution >= 1920w" => [info[:w] >= 1920, "#{info[:w]}x#{info[:h]}"]+ }+ # Only a base that gets torn open (run1) must be full color; run2's muted watercolor is mostly low-saturation.+ if project.step?(RefTorn)+ checks["mostly colored"] = [split["mono_pct"] < 35, "mono #{split["mono_pct"]}% (the base layer should be full color)"]+ end+ { image: info, style: split, preview: preview, **verdict(checks) }+ end++ protected++ def model = project.generation[:edit_from] || project.generation[:photos] ? Fal::Models::GptImage25Edit : project.generation.fetch(:image_model, MODEL)+ def endpoint = model.endpoint+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/ref_torn.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/ref_torn.rbnew file mode 100644index 0000000..270507b--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/ref_torn.rb@@ -0,0 +1,44 @@+module Pipeline+ module Steps+ # Step 2 — torn-paper reveal edit: colored illustration + line-art interiors+ # (nano-banana-2/edit, prompt = user YAML spec). This is the video's reference frame.+ class RefTorn < Step+ PREAMBLE = "Edit the provided reference image following this YAML specification exactly. " \+ "Output one image with the same framing and aspect ratio as the reference. " \+ "There must be exactly TWO separate torn-paper openings, each with visible ragged torn paper edges: " \+ "one across the chest, and a second one across the lower abdomen / skirt waistband, with a band of the " \+ "original colored illustration left intact between them. The face, the microphone and the hand holding it stay fully colored.\n\n".freeze++ MODEL = Fal::Models::NanoBanana2Edit++ def submit+ prompt = "#{PREAMBLE}```yaml\n#{project.prompt("02_ref_torn")}```"+ MODEL.new(client: client).edit(prompt: prompt, image_urls: [project.fetch!(:ref_base, :url)], seed: seed)+ end++ def materialize(result)+ image = result.output.fetch("images").first+ base_data(result).merge(url: image["url"], path: download(image["url"], "02_ref_torn.png"),+ description: result.output["description"])+ end++ def review+ base, torn = project[:ref_base]["path"], project[key]["path"]+ base_info, torn_info = magick.identify(base), magick.identify(torn)+ split = python.style_split(base, torn)["images"]+ mono_gain = (split[1]["mono_pct"] - split[0]["mono_pct"]).round(1)+ board = magick.board([[base, "base (colored)"], [torn, "torn-paper reveal"]], project.review_path(key, "compare.jpg"))+ mask = magick.saturation_mask(torn, project.review_path(key, "mono_mask.png"))+ {+ base: base_info, torn: torn_info, style: { base: split[0], torn: split[1], mono_gain_pct: mono_gain },+ compare: board, mono_mask: mask,+ **verdict(+ "same framing" => [(base_info[:aspect] - torn_info[:aspect]).abs < 0.02, "#{base_info[:aspect]} vs #{torn_info[:aspect]}"],+ "line-art area added" => [mono_gain >= 8, "mono +#{mono_gain}% vs base"],+ "still half colored" => [split[1]["mono_pct"].between?(15, 70), "mono #{split[1]["mono_pct"]}%"]+ )+ }+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/shots.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/shots.rbnew file mode 100644index 0000000..a2aa533--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/shots.rb@@ -0,0 +1,141 @@+module Pipeline+ module Steps+ # Step 4b — a scene's edit (the anime default). prompts/<run>/04_shots.yml lists the shots in edit order, each `frames` long:+ # image / end_image keyframe names (Keyframes step), "<run>/<keyframe>", "run:<run>" (that run's sheet/painting) or "ref_base"+ # prompt what happens: identity/style ({{STYLE}}), acting beats with timings, mouth, invariants+ # camera the camera move, sent to H3 as its own "Camera:" paragraph (see prompts.md "Camera language")+ # audio: <track> H3 target audio from this shot's position in the scene: a cast id (that character's mouth track from+ # the Dialogue step, silent while others speak), "dialogue" (all lines) or true (the full soundtrack)+ # seconds H3 generation length, fractional allowed (0.92..15, >= 2 with audio); default: the shot length+ # retime: true the whole H3 clip is squeezed into `frames` (fast camera moves; never with dialogue)+ # source_frames: N use only the take's first N frames (cut before a defect, e.g. invented lettering), then trim or+ # retime them to `frames`; the downloaded take stays whole, and a retake keeps the same cut point+ # roll: [from, to] a virtual camera roll over the shot, in degrees (clockwise), applied to the plate locally; layers+ # drawn in p5 follow it with Anim.withRoll(frame, fn) so sprites and background turn together+ # still: <keyframe> no generation: the keyframe held (zoom: [1.0, 1.06] for a slow push) — inserts, held drawings+ # color: "#05070a" no generation: a solid frame the overlay draws on (screens, title cards, smash-cut white)+ # from_run: <run> no generation: that run's video (same timeline) from this shot's position+ # The shots are cut, concatenated and muxed with the scene soundtrack (Mix, else Music) -> final.mp4 (the Overlay plate).+ class Shots < ItemsStep+ MODEL = Fal::Models::H3MaxImageToVideo+ FPS = 24+ GEN_SECONDS = 5 # default H3 length per shot (its minimum; max 15)++ def specs+ @specs ||= begin+ at = 0+ shots = yaml("04_shots")+ raise ArgumentError, "Shot frames must sum to section frames" unless shots.sum { |shot| shot.fetch("frames") } == (project.duration * FPS).round+ shots.to_h do |shot|+ spec = shot.merge("start_frame" => at)+ at += shot.fetch("frames")+ [shot.fetch("name"), spec]+ end+ end+ end++ # Held stills and colour inserts are rendered locally for free, so a cached one is rebuilt whenever its spec+ # changes (frames, colour, still, zoom) — no FORCE needed. A white card once kept its old 12 frames after its+ # frames were raised to 96 because a cached local shot counted as done. Items from before this record no spec:+ # those are compared by frame count only.+ def stale_item?(name, spec, item)+ return false unless spec["still"] || spec["color"]+ stale = item["spec"] ? item["spec"] != local_spec(spec) : ffmpeg.summary(item["path"]).dig(:video, :frames).to_i != spec["frames"]+ warn "[#{key}] #{name}: local shot spec changed -> rebuilding" if stale+ stale+ end++ def local_spec(spec) = spec.slice("frames", "color", "still", "zoom")++ def generate(name, spec)+ if (run = spec["from_run"])+ return { source: run, path: Project.new(run).fetch!(:video, :path) }+ end+ if spec["still"] || spec["color"]+ image = spec["still"] && keyframe_path(spec["still"])+ out = ffmpeg.still_video(project.path("04_shot_#{name}.mp4"), frames: spec["frames"], fps: FPS, image: image,+ color: spec.fetch("color", "#000000"), zoom: spec["zoom"])+ return { source: spec["still"] || spec["color"], path: out, spec: local_spec(spec) }+ end+ raise ArgumentError, "Never retime a talking or singing shot" if spec["audio"] && spec["retime"]+ seconds = spec.fetch("seconds") { default_seconds(spec) }+ raise ArgumentError, "shot #{name} needs more source frames (#{spec["frames"]} > #{seconds}s)" if !spec["retime"] && spec["frames"] > seconds * FPS+ raise ArgumentError, "shot #{name}: source_frames #{spec["source_frames"]} < frames #{spec["frames"]} needs retime: true" if spec["source_frames"] && !spec["retime"] && spec["source_frames"] < spec["frames"]+ audio = audio_url(name, spec, seconds) if spec["audio"]+ result = MODEL.new(client: client).animate(+ prompt: self.class.h3_prompt(project, spec), image_url: keyframe_url(spec.fetch("image")),+ end_image_url: spec["end_image"]&.then { |k| keyframe_url(k) }, target_audio_url: audio,+ duration: seconds, seed: seed, resolution: ENV.fetch("VIDEO_RES", MODEL::DEFAULT_RES)+ )+ url = result.output.fetch("video")["url"]+ { request_id: result.request_id, input: result.input, url: url, path: download(url, "04_shot_#{name}.mp4") }+ end++ # The H3 prompt: the shot prompt ({{STYLE}} expanded), then the camera direction as its own paragraph.+ def self.h3_prompt(project, spec)+ text = project.expand(spec.fetch("prompt")).strip+ camera = spec["camera"]+ camera = camera.map { |k, v| "#{k}: #{v}" }.join("; ") if camera.is_a?(Hash)+ camera ? "#{text}\n\nCamera: #{project.expand(camera).strip}" : text+ end++ def finish(items)+ segments = specs.map do |name, spec|+ { path: items[name]["path"], frames: spec["frames"], retime: spec["retime"], keep: spec["source_frames"],+ skip: spec["from_run"] ? spec["start_frame"] : 0, roll: spec["roll"] }+ end+ plate = ffmpeg.concat_shots(segments, project.path("04_plate.mp4"), fps: FPS, w: 1920, h: 1080) # 768P H3 shots upscaled to the 1080p delivery+ { path: ffmpeg.mux(plate, project.soundtrack, project.path("final.mp4"), shortest: false), plate: plate }+ end++ def review+ final = project[key]["path"]+ summary = ffmpeg.summary(final)+ frames = summary.dig(:video, :frames)+ want = specs.values.sum { |s| s["frames"] }+ cuts = specs.flat_map do |name, s|+ [[s["start_frame"], "#{name} first"], [s["start_frame"] + s["frames"] - 1, "#{name} last"]].map do |n, label|+ [ffmpeg.frame_index(final, n, project.review_path(key, "f#{n}.jpg")), "f#{n} #{label}"]+ end+ end+ # Frames each source must have: from_run sources are read from the shot's position, generated ones from 0.+ short = specs.reject do |name, s|+ s["retime"] || s["still"] || s["color"] || ffmpeg.summary(project[key]["items"][name]["path"]).dig(:video, :frames).to_i >= (s["from_run"] ? s["start_frame"] : 0) + s["frames"]+ end+ {+ summary: summary, contact_sheet: ffmpeg.contact_sheet(final, project.review_path(key, "contact_sheet.jpg"), cols: 6, rows: 3),+ cuts: magick.board(cuts, project.review_path(key, "cuts.jpg"), tile: "2x", width: 640),+ **verdict(+ "frames = shots total" => [frames == want, "#{frames}/#{want}"],+ "duration ~#{project.duration}s" => [(summary[:duration] - project.duration).abs < 0.1, "#{summary[:duration]}s"],+ "master audio muxed" => [summary.dig(:audio, :codec) == "aac", summary[:audio].inspect],+ "every shot long enough" => [short.empty?, short.empty? ? "ok" : "too short: #{short.keys.join(", ")}"]+ )+ }+ end++ protected++ def endpoint = MODEL.endpoint++ private++ # The shot's own length (H3 may add ~0.7 s), at least 2 s when audio is pinned, rounded up to 0.1 s.+ def default_seconds(spec)+ [(spec["frames"].fdiv(FPS) * 10).ceil / 10.0, spec["audio"] ? 2.0 : 1.0].max+ end++ def keyframe_path(name)+ return project.fetch!(:ref_base, :path) if name == "ref_base"+ return Project.new(name.delete_prefix("run:")).fetch!(:ref_base, :path) if name.start_with?("run:")+ project.keyframe(name)["path"]+ end++ def audio_url(name, spec, seconds)+ from = spec["start_frame"].fdiv(FPS)+ return song_url(name, from, seconds) if spec["audio"] == true+ voice_url(name, spec["audio"], from, seconds)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/pipeline/steps/video.rb b/skills/make-an-anime/scripts/lib/pipeline/steps/video.rbnew file mode 100644index 0000000..6f3ada1--- /dev/null+++ b/skills/make-an-anime/scripts/lib/pipeline/steps/video.rb@@ -0,0 +1,65 @@+module Pipeline+ module Steps+ # Step 4 — animate the reference frame into a singing shot+ # (minimax/h3-max/image-to-video, project.duration seconds) with the song pinned as soundtrack, then mux+ # the clean master audio into the final deliverable. No lipsync pass (see tmp/old/).+ class Video < Step+ MODEL = Fal::Models::H3MaxImageToVideo++ # END_KEYFRAME=0 disables pinning the last frame to the reference+ # (without it H3 drifts away from the reference style, e.g. "heals" run1's torn paper).+ def submit+ ref = project.fetch!(source, :url)+ MODEL.new(client: client).animate(+ prompt: project.prompt("04_video"),+ image_url: ref,+ end_image_url: (ref unless ENV["END_KEYFRAME"] == "0"),+ target_audio_url: project.fetch!(:music, :url),+ duration: project.duration, seed: seed,+ resolution: ENV.fetch("VIDEO_RES", MODEL::DEFAULT_RES)+ )+ end++ def materialize(result)+ video = result.output.fetch("video")+ raw = download(video["url"], "04_video_raw.mp4")+ base_data(result).merge(+ url: video["url"], raw_path: raw, path: ffmpeg.mux(raw, project[:music]["path"], project.path("final.mp4")),+ source: source, expanded_prompt: result.output["expanded_prompt"], timings: result.output["timings"]+ )+ end++ def review+ final = project[key]["path"]+ summary = ffmpeg.summary(final)+ sheet = ffmpeg.contact_sheet(final, project.review_path(key, "contact_sheet.jpg"))+ frames = ffmpeg.extract_frames(final, project.review_path(key, "frames"), fps: 2)+ ref = python.style_split(project[source]["path"])["images"].first+ split = python.style_split(*frames)+ monos = split["images"].map { |i| i["mono_pct"] }+ sats = split["images"].map { |i| i["mean_saturation"] }+ drift = (monos.max - monos.min).round(1)+ mono_gap = (split["mean_mono_pct"] - ref["mono_pct"]).round(1)+ sat_gap = (sats.sum / sats.size - ref["mean_saturation"]).round(3)+ {+ summary: summary, contact_sheet: sheet,+ style: { ref_mono_pct: ref["mono_pct"], frame_mono_pct: monos, mean: split["mean_mono_pct"], drift: drift,+ ref_saturation: ref["mean_saturation"], frame_saturation: sats },+ **verdict(+ "duration ~#{project.duration}s" => [(summary[:duration] - project.duration).abs < 0.6, "#{summary[:duration]}s"],+ "master audio muxed" => [summary.dig(:audio, :codec) == "aac" && summary.dig(:audio, :rate) == 44_100, summary[:audio].inspect],+ "resolution >= 720p" => [summary.dig(:video, :h).to_i >= 720, "#{summary.dig(:video, :w)}x#{summary.dig(:video, :h)}"],+ "reference style kept" => [mono_gap.abs <= [10, ref["mono_pct"] * 0.4].max, "frames #{split["mean_mono_pct"]}% mono vs ref #{ref["mono_pct"]}% (#{mono_gap}pp)"],+ "palette kept" => [sat_gap.abs < 0.08, "mean saturation #{sat_gap.positive? ? "+" : ""}#{sat_gap} vs ref #{ref["mean_saturation"]}"],+ "style stable" => [drift < 20, "mono drift #{drift}pp across frames"]+ )+ }+ end++ private++ # The frame H3 animates: run1's torn-paper collage, otherwise the base image.+ def source = project.step?(RefTorn) ? :ref_torn : :ref_base+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/tasks.rb b/skills/make-an-anime/scripts/lib/tasks.rbnew file mode 100644index 0000000..de5c140--- /dev/null+++ b/skills/make-an-anime/scripts/lib/tasks.rb@@ -0,0 +1,21 @@+require "rake"+require_relative "fal_mv_gen"+require_relative "toolkit/operations"+module Toolkit+ class Tasks+ extend Rake::DSL+ def self.install+ Operations::TASKS.each do |name, description|+ desc description+ task(name) { |_, args| Operations.new.call(name, args.extras) }+ end+ Pipeline::ALL_STEPS.each do |step|+ desc "Generate #{step.key}; Fal may charge (RUN=..., ONLY=..., FORCE=1)"+ task("gen:#{step.key}") { Operations.new.generate(step) }+ desc "Review #{step.key}; music review uses paid Whisper"+ task("review:#{step.key}") { step.new.review! }+ end+ task default: "pipeline:status"+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/toolkit/anime_review.rb b/skills/make-an-anime/scripts/lib/toolkit/anime_review.rbnew file mode 100644index 0000000..1742cff--- /dev/null+++ b/skills/make-an-anime/scripts/lib/toolkit/anime_review.rb@@ -0,0 +1,125 @@+require "json"+require "yaml"+require "fileutils"++module Toolkit+ # Anime review tools (all local, no Fal calls):+ #+ # review:likeness[run,...] one board per character sheet beside the reference photos it was made from; several runs+ # (e.g. v2,v3) are stacked so alternatives compare against the same photos.+ # review:camera per H3 shot of RUN: a frame strip, the measured camera move (zoom / pan / tilt between+ # the first and last frame) next to the directed `camera:` move, and a verdict hint.+ # dialogue:timeline RUN's shots and lines on one timeline with the checks that matter before animating:+ # every `audio:` shot contains its speaker's whole on-screen line, no on-screen line+ # crosses a cut, the shortest frame count each talking shot needs.+ class AnimeReview+ FPS = 24+ # A camera estimate below this match score is unreliable: strong parallax, a big character move or a morph.+ TRUST = 0.65++ def initialize(project = Pipeline::Project.new)+ @project = project+ end++ attr_reader :project++ def likeness(runs)+ runs = [project.name] if runs.empty?+ sheets = runs.map { |run| Pipeline::Project.new(run) }+ photos = sheets.flat_map { |p| reference_photos(p) }.uniq.first(8)+ raise ArgumentError, "no reference photos (generation photos:) for #{runs.join(", ")}" if photos.empty?+ dir = sheets.first.path("review")+ FileUtils.mkdir_p(dir)+ row = File.join(dir, "likeness_photos.jpg")+ magick.board(photos.each_with_index.map { |p, i| [p, "#{i + 1}. #{File.basename(p, ".*")[-16..] || File.basename(p, ".*")}"] }, row, width: 300)+ boards = sheets.map do |p|+ out = File.join(dir, "likeness_#{p.name}.jpg")+ magick.preview(p.fetch!(:ref_base, :path), out, max: 1800)+ out+ end+ out = File.join(dir, "likeness_#{runs.join("_vs_")}.jpg")+ magick.stack([row, *boards], out, width: 1800)+ { board: out, photos: photos, sheets: runs,+ check: "Front-view close-up vs the front photos first: face shape and width, eye size/lids, brows, nose, mouth, skin, build. Then hair, beard, glasses." }+ end++ def camera+ shots = Pipeline::Steps::Shots.new(project: project).specs+ dir = project.path("review", "camera")+ FileUtils.mkdir_p(dir)+ shots.filter_map do |name, spec|+ next if spec["still"] || spec["color"] || spec["from_run"]+ video = project.path("04_shot_#{name}.mp4")+ next unless File.file?(video)+ n = ffmpeg.summary(video).dig(:video, :frames) || (ffmpeg.duration(video) * FPS).round+ first = ffmpeg.frame_index(video, 0, File.join(dir, "#{name}_first.png"))+ last = ffmpeg.frame_index(video, [n - 1, 0].max, File.join(dir, "#{name}_last.png"))+ # ~4 fps (12 frames per 3 s row): dense enough to see an H3-inserted cut or a story action done early, which+ # neither the camera estimate nor frame-difference scores separate from normal character motion.+ strip = ffmpeg.contact_sheet(video, File.join(dir, "#{name}_strip.jpg"), cols: 12, rows: (n / 72.0).ceil.clamp(1, 4), width: 320)+ measured = python.camera_motion(first, last)+ directed = spec["camera"].is_a?(Hash) ? spec["camera"]["move"] : spec["camera"]+ { shot: name, directed: directed, measured: measured["camera"], zoom: measured["zoom"],+ shift: [measured["shift_x"], measured["shift_y"]], score: measured["score"],+ hint: hint(directed.to_s, measured), strip: strip, first: first, last: last }+ end+ end++ def timeline+ lines_path = project.path("03_dialogue_lines.json")+ raise ArgumentError, "run gen:dialogue first (#{lines_path})" unless File.file?(lines_path)+ lines = JSON.parse(File.read(lines_path))+ shots = Pipeline::Steps::Shots.new(project: project).specs.map do |name, s|+ { name: name, from: s["start_frame"] / FPS.to_f, to: (s["start_frame"] + s["frames"]) / FPS.to_f,+ frames: s["frames"], audio: s["audio"], kind: s["color"] ? "colour" : s["still"] ? "still" : "h3" }+ end+ issues = []+ rows = shots.map do |s|+ inside = lines.select { |l| l["at"] < s[:to] && l["end"] > s[:from] }+ if s[:audio].is_a?(String) && s[:audio] != "dialogue"+ own = inside.reject { |l| l["vo"] }.select { |l| l["character"] == s[:audio] }+ issues << "#{s[:name]}: audio #{s[:audio]} but none of their on-screen lines play here" if own.empty?+ own.each do |l|+ next if l["at"] >= s[:from] && l["end"] <= s[:to]+ issues << format("%s: %s's line %s (%.2f–%.2f s) crosses the shot (%.2f–%.2f s)", s[:name], s[:audio], l["name"], l["at"], l["end"], s[:from], s[:to])+ end+ end+ inside.reject { |l| l["vo"] }.each do |l|+ next if l["at"] >= s[:from] && l["end"] <= s[:to]+ issues << format("%s: on-screen line %s crosses a cut (%.2f–%.2f s); move the cut or the line", s[:name], l["name"], l["at"], l["end"])+ end+ need = s[:audio] ? ((inside.map { |l| l["end"] }.max || s[:from]) - s[:from] + 0.25) * FPS : nil+ { shot: s[:name], frames: s[:frames], seconds: format("%.2f–%.2f", s[:from], s[:to]), kind: s[:kind], audio: s[:audio],+ lines: inside.map { |l| format("%s%s %.2f–%.2f", l["name"], l["vo"] ? " (VO)" : "", l["at"], l["end"]) },+ min_frames_for_lines: need&.ceil }+ end+ { run: project.name, frames: shots.sum { _1[:frames] }, shots: rows, issues: issues.uniq, ok: issues.empty? }+ end++ private++ def reference_photos(p)+ Array(p.generation[:photos]).map { |f| File.expand_path(f, Pipeline::ROOT) }+ .reject { |f| f.include?("/output/") } # sheets passed as style references+ .select { |f| File.file?(f) }+ end++ def hint(directed, m)+ return "unreliable estimate (score #{m["score"]}): parallax or character motion — judge the strip by eye" if m["score"] < TRUST+ d = directed.downcase+ want = if d.match?(/push|dolly[- ]?in|zoom[- ]?in|track(ing)?[- ]?in/) then :in+ elsif d.match?(/pull|dolly[- ]?out|zoom[- ]?out|track(ing)?[- ]?out/) then :out+ elsif d.match?(/static|locked|no camera move/) then :static+ end+ got = m["zoom"] > 1.03 ? :in : m["zoom"] < 0.97 ? :out : :static+ moved = m["shift_x"].abs >= 0.02 || m["shift_y"].abs >= 0.02+ return "no comparable directed move" unless want+ return "matches" if want == got && (want != :static || !moved)+ "MISMATCH: directed #{want}, measured #{m["camera"]}"+ end++ def ffmpeg = @ffmpeg ||= Media::FFmpeg.new+ def python = @python ||= Media::Python.new+ def magick = @magick ||= Media::ImageMagick.new+ end+enddiff --git a/skills/make-an-anime/scripts/lib/toolkit/episode.rb b/skills/make-an-anime/scripts/lib/toolkit/episode.rbnew file mode 100644index 0000000..d54f729--- /dev/null+++ b/skills/make-an-anime/scripts/lib/toolkit/episode.rb@@ -0,0 +1,245 @@+require "fileutils"+require "json"+require "open3"+require "yaml"++module Toolkit+ # Episode-level tools (local, no Fal calls).+ #+ # scene:new[run,frames] scaffold a scene: prompts/<run>/ (dialogue, score, keyframes, shots, overlay templates),+ # prompts/<run>-sfx/sfx.yml and config/generations/<run>.rb. Never overwrites.+ # episode:preview[out,run,...] join scenes in order into one preview; with a single prefix argument (ep01) every+ # ep01-sNN run is used. Each scene contributes its most finished file:+ # final_sfx.mp4 > final_overlay.mp4 > final.mp4. Missing scenes are reported, not skipped silently.+ class Episode+ FINALS = %w[final_sfx.mp4 final_overlay.mp4 final.mp4].freeze++ def initialize(root: Pipeline::ROOT, ffmpeg: Media::FFmpeg.new)+ @root = root+ @ffmpeg = ffmpeg+ end++ # config/episodes/<prefix>.yml is the playing order when it exists; otherwise scenes play in number order.+ def runs_for(prefix)+ order = File.join(@root, "config", "episodes", "#{prefix}.yml")+ return YAML.safe_load_file(order) if File.file?(order)++ Dir[File.join(@root, "prompts", "#{prefix}-s[0-9]*")].map { File.basename(_1) }.grep(/\A#{Regexp.escape(prefix)}-s\d+\z/).sort+ end++ def final_for(run)+ FINALS.map { |f| File.join(@root, "output", run, f) }.find { |f| File.file?(f) }+ end++ # Scenes are mixed one at a time, so their loudness drifts (six scenes once spanned 3.3 LU); each scene's audio is moved+ # to `lufs` (EBU R128 integrated) before joining, never pushing its true peak above PEAK_CEILING. lufs: nil joins as is.+ # A scene with speech is moved so its voices sit at voice_db instead: levelling a whole scene pulled the loud ones down,+ # and a loud fight scene took its narrator line 7.8 dB under the other lines. The bed follows, within VOICE_GAIN.+ PEAK_CEILING = -1.0+ VOICE_GAIN = (-10.0..6.0)++ def level(picked, dir, lufs:, voice_db: nil, seams: false)+ last = picked.size - 1+ picked.each_with_index.map do |(run, file), i|+ next { path: file } unless lufs+ m = @ffmpeg.loudness(file)+ next { path: file, lufs: m[:lufs], gain_db: 0.0 } unless m[:lufs].finite? && m[:lufs] > -60 # a silent card+ fades = seams ? seam_fades(run, file, first: i.zero?, last: i == last) : { fade_in: 0, fade_out: 0 }+ speech = voice_db && speech_level(run, file)+ wanted = speech ? (voice_db - speech).clamp(VOICE_GAIN) : lufs - m[:lufs]+ db = [wanted, PEAK_CEILING - m[:true_peak]].min.round(2)+ plain = db.abs < 0.1 && fades.values.all?(&:zero?)+ { path: plain ? file : @ffmpeg.gain(file, File.join(dir, "#{run}.mp4"), db: db, **fades), lufs: m[:lufs], speech_db: speech, gain_db: db, **fades }+ end+ end++ # The median level of a scene's narrator lines, or of all its lines when it has no narrator. nil when nobody speaks.+ def speech_level(run, file)+ path = File.join(@root, "output", run, "03_dialogue_lines.json")+ return unless File.exist?(path)+ lines = JSON.parse(File.read(path))+ lines = lines["lines"] if lines.is_a?(Hash)+ lines = Array(lines).select { (_1["speech_at"] || _1["at"]) && _1["end"] && !_1["inner"] && _1["subtitle"] != " " }+ lines = lines.select { _1["vo"] } if lines.any? { _1["vo"] }+ levels = lines.filter_map { @ffmpeg.mean_volume(file, _1["speech_at"] || _1["at"], _1["end"]) }.sort+ levels[levels.size / 2] if levels.any?+ end++ # Every scene's track clearly ends and the next clearly starts. The fade-out takes the air after the last word and the+ # fade-in the air before the first, each kept off the voices; a scene that opens on a hit keeps its hit.+ SEAM = { out: (0.25..1.4), in: (0.15..0.7), hit: 0.02, clear: 0.12 }.freeze++ def seam_fades(run, file, first:, last:)+ seconds = @ffmpeg.duration(file)+ path = File.join(@root, "output", run, "03_dialogue_lines.json")+ lines = File.exist?(path) ? Array(JSON.parse(File.read(path))) : []+ end_at = lines.map { _1["end"].to_f }.max || 0.0+ start_at = lines.map { (_1["speech_at"] || _1["at"]).to_f }.min || seconds+ head = @ffmpeg.mean_volume(file, 0, 0.2).to_f+ body = @ffmpeg.mean_volume(file, 0.2, 1.2).to_f+ opens_on_a_hit = head > body - 1.0 && head > -30+ fade_in = opens_on_a_hit ? SEAM[:hit] : [(start_at - SEAM[:clear]).clamp(SEAM[:in]), [start_at - 0.02, SEAM[:hit]].max].min+ { fade_in: first ? 0 : fade_in.round(3), fade_out: last ? 0 : (seconds - end_at - SEAM[:clear]).clamp(SEAM[:out]).round(3) }+ end++ def preview(out, names, lufs: -23.0, voice_db: nil, seams: false)+ names = runs_for(names.first) if names.size == 1 && !names.first.match?(/-s\d+\z/)+ raise ArgumentError, "no scenes given" if names.empty?+ picked = names.to_h { |run| [run, final_for(run)] }+ missing = picked.select { |_, f| f.nil? }.keys+ raise ArgumentError, "no final video yet for: #{missing.join(", ")}" if missing.any?+ out = File.expand_path(out, @root)+ FileUtils.mkdir_p(File.dirname(out))+ leveled = level(picked, File.join(File.dirname(out), "#{File.basename(out, ".*")}_leveled"), lufs: lufs, voice_db: voice_db, seams: seams)+ @ffmpeg.concat_videos(leveled.map { _1[:path] }, out)+ scenes = picked.each_with_index.map do |(run, file), i|+ { run: run, file: file.delete_prefix("#{@root}/"), seconds: @ffmpeg.duration(file).round(2), **leveled[i].except(:path) }+ end+ { path: out, seconds: @ffmpeg.duration(out).round(2), lufs_target: lufs, scenes: scenes }+ end++ def seam_report(film, episode)+ rows = runs_for(episode).map { |run| [run, @ffmpeg.duration(final_for(run))] }+ list = File.join(@root, "tmp", "seams_#{episode}.json")+ FileUtils.mkdir_p(File.dirname(list))+ File.write(list, JSON.generate(rows))+ out, = Open3.capture2(Media::Python.new.executable, File.join(@root, "tools", "python", "audio_seams.py"), File.expand_path(film, @root), list)+ JSON.parse(out)+ end++ # A new soundtrack on a rendered scene: final_overlay.mp4's picture is copied, not rendered again.+ def reaudio(run)+ project = Pipeline::Project.new(run)+ video = project.path("final_overlay.mp4")+ temp = project.path("final_overlay.reaudio.mp4")+ @ffmpeg.mux(video, project.soundtrack, temp, shortest: false)+ FileUtils.mv(temp, video)+ { run: run, path: video, seconds: @ffmpeg.duration(video).round(3) }+ end++ # prompts/<name>/beats.yml -> cues.yml: cues written in scene frames (f: end is the cut into the next scene) become film+ # frames, read from the scene files the film is joined from, so a scene that grows can't leave a cue on the wrong beat.+ def vfx_cues(name)+ dir = File.join(@root, "prompts", name)+ spec = YAML.safe_load_file(File.join(dir, "beats.yml"))+ at = 0+ scenes = runs_for(spec.fetch("episode")).to_h do |run|+ frames = @ffmpeg.summary(final_for(run)).dig(:video, :frames)+ [run, { start: at, frames: frames }].tap { at += frames }+ end+ cues = spec.fetch("beats").map do |beat|+ scene = scenes.fetch(beat.fetch("run")) { raise ArgumentError, "#{beat["run"]} is not in #{spec["episode"]}" }+ local = beat.fetch("f") == "end" ? scene[:frames] : beat["f"]+ raise ArgumentError, "#{beat} is past the scene's #{scene[:frames]} frames" unless local.is_a?(Integer) && local <= scene[:frames]+ beat.except("run").merge("f" => scene[:start] + local)+ end+ File.write(File.join(dir, "cues.yml"), YAML.dump("source" => spec.fetch("source"), "out" => spec.fetch("out"), "cues" => cues))+ { name: name, cues: cues.size, film_frames: at }+ end++ # The score with a ring-out: output/<run>/03_score_tail.wav, to set as the run's music_from when its last shot is held longer.+ def score_tail(run, source, tail)+ out = File.join(@root, "output", run, "03_score_tail.wav")+ @ffmpeg.ring_out(File.expand_path(source, @root), out, tail: Float(tail))+ { run: run, path: out, seconds: @ffmpeg.duration(out).round(3) }+ end++ def scaffold(run, frames)+ frames = Integer(frames)+ raise ArgumentError, "run must look like ep01-s02" unless run.match?(/\A[a-z0-9]+-s\d+\z/)+ prompts = File.join(@root, "prompts", run)+ config = File.join(@root, "config", "generations", "#{run}.rb")+ sfx = File.join(@root, "prompts", "#{run}-sfx", "sfx.yml")+ existing = [prompts, config, sfx].select { File.exist?(_1) }+ raise ArgumentError, "already exists: #{existing.join(", ")}" if existing.any?+ FileUtils.mkdir_p([prompts, File.dirname(config), File.dirname(sfx)])+ SceneTemplate.new(run, frames).files.each { |name, body| File.write(File.join(prompts, name), body) }+ File.write(config, SceneTemplate.new(run, frames).generation)+ File.write(sfx, SceneTemplate.new(run, frames).sfx)+ { run: run, frames: frames, seconds: frames / 24.0, prompts: prompts, config: config, sfx: sfx,+ next: "write the prompts, then gen:dialogue -> dialogue:timeline -> gen:music -> gen:mix -> gen:keyframes -> gen:shots -> review:camera -> gen:overlay -> sfx:gen/sfx:mix" }+ end+ end++ # The starting files of a new anime scene; every value is a placeholder to replace.+ class SceneTemplate+ def initialize(run, frames)+ @run = run+ @frames = frames+ end++ def seconds = @frames / 24.0++ def generation+ <<~RUBY+ # #{@run}: #{seconds} s = #{@frames} frames. Evaluated inside Pipeline (see the skill's references/tasks.md).+ {+ "#{@run}" => {+ steps: [Steps::Dialogue, Steps::Music, Steps::Mix, Steps::Keyframes, Steps::Shots, Steps::Overlay],+ **scene(#{@frames}), music_fade: 0, mix: { music_db: -6, dialogue_db: 0, duck: true, music_end: #{seconds} }+ }+ }+ RUBY+ end++ def files+ {+ "03_dialogue.yml" => <<~YAML,+ # Lines in scene seconds. character: a config/cast.yml id; vo: true for narration (no mouth track).+ # A character never talks over themself; run dialogue:timeline after generating.+ - name: line-1+ character: CAST_ID+ at: 1.0+ text: "[tag] Line."+ YAML+ "03_score.json" => <<~JSON,+ {"chunks": [{"text": "[Instrumental]", "duration_ms": #{(seconds * 1000).round}, "positive_styles": ["STYLE"], "negative_styles": ["vocals", "lyrics"]}]}+ JSON+ "02_keyframes.yml" => <<~YAML,+ # One still per H3 shot (or per base it is edited from). refs: accepted sheet runs, in the order the prompt names them.+ key-1:+ base: false+ refs: [char-CAST-v1, loc-PLACE-v1]+ prompt: >-+ {{STYLE}} The person from image 1 … in the place of image 2 … Shot: … 16:9. No text, no other people.+ YAML+ "04_shots.yml" => <<~YAML,+ # Frames must sum to #{@frames}. image: keyframe | run:<sheet run>; color: "#rrggbb" insert; still: hold.+ # audio: <cast id> on the shot where that character speaks on screen. camera: one named move, stated end framing.+ - name: shot-1+ image: key-1+ frames: #{@frames}+ prompt: "{{STYLE}} What moves and how."+ camera: { move: "slow push-in (dolly in), no rotation", from: "medium shot", to: "medium close-up", timing: "whole shot, ease-in-out" }+ YAML+ "05_overlay.js" => <<~JS,+ // #{@run} overlay: subtitles and any readable screen (tools/p5/lib/screens.js). Generated images contain no text.+ Anim.sketch({+ async load() {+ this.f = await Anim.fonts({ sub: "sub.ttf", subItalic: "sub-italic.ttf" });+ this.lines = Anim.data("dialogue");+ },+ draw(t) {+ Anim.subtitles(t, this.lines, { font: this.f.sub, italic: this.f.subItalic });+ },+ });+ JS+ }+ end++ def sfx+ <<~YAML+ # #{@run} sound effects over the finished scene (Stable Audio SFX, paid; tones are local). Times in scene seconds.+ source: output/#{@run}/final_overlay.mp4+ out: output/#{@run}/final_sfx.mp4+ rel_db: -8+ peak_db: -6+ max_gain_db: 18+ sounds:+ ambience: {prompt: "PLACE ambience, no music, no voices", duration: 10, seed: 1}+ cues:+ - {at: 0.0, sound: ambience, rel_db: -12, len: #{seconds}, fade: 0.8}+ YAML+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/toolkit/fonts.rb b/skills/make-an-anime/scripts/lib/toolkit/fonts.rbnew file mode 100644index 0000000..ba42f25--- /dev/null+++ b/skills/make-an-anime/scripts/lib/toolkit/fonts.rb@@ -0,0 +1,37 @@+require "fileutils"+require "json"+require "digest"++module Toolkit+ class Fonts+ ROOTS = ["/System/Library/Fonts", "/Library/Fonts", File.expand_path("~/Library/Fonts")].freeze++ def list(roots = ROOTS)+ roots.flat_map { |root| Dir.glob(File.join(root, "**", "*")) }+ .select { |path| File.file?(path) && %w[.ttf .otf].include?(File.extname(path).downcase) }.uniq.sort+ end++ # JSON maps stable project filenames to selected absolute source paths.+ def copy(selection, project: Dir.pwd)+ map = JSON.parse(File.read(selection))+ raise ArgumentError, "Font selection must be a nonempty JSON object" unless map.is_a?(Hash) && !map.empty?+ destination = File.join(project, "tools/p5/fonts")+ files = map.map do |name, source|+ unless name == File.basename(name) && %w[.ttf .otf].include?(File.extname(name).downcase)+ raise ArgumentError, "Use a .ttf or .otf filename without directories: #{name}"+ end+ unless source.is_a?(String) && source.start_with?("/") && File.file?(source) && File.extname(source).downcase == File.extname(name).downcase+ raise ArgumentError, "Missing or incompatible absolute font source: #{source}"+ end+ target = File.join(destination, name)+ if File.exist?(target) && Digest::SHA256.file(source) != Digest::SHA256.file(target)+ raise ArgumentError, "Font already exists with different bytes; choose a new filename: #{target}"+ end+ [source, target]+ end+ FileUtils.mkdir_p(destination)+ files.each { |source, target| FileUtils.cp(source, target) unless File.exist?(target) }+ files.map { |source, target| { source: source, path: target, sha256: Digest::SHA256.file(target).hexdigest } }+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/toolkit/initializer.rb b/skills/make-an-anime/scripts/lib/toolkit/initializer.rbnew file mode 100644index 0000000..1337c14--- /dev/null+++ b/skills/make-an-anime/scripts/lib/toolkit/initializer.rb@@ -0,0 +1,58 @@+require "fileutils"+require "json"+module Toolkit+ class Initializer+ EXCLUDED = %w[node_modules .venv .bundle output tmp specs .build prompts config docs audio .skill __pycache__].freeze+ def initialize(runtime) = @runtime = runtime+ def examples_root+ [File.expand_path("../examples", @runtime), File.join(@runtime, ".skill", "examples")].find { File.directory?(_1) } || File.expand_path("../examples", @runtime)+ end+ def example_dir(name)+ raise ArgumentError, "Example names are plain words" unless name.match?(/\A[a-z0-9-]+\z/)+ dir = File.join(examples_root, name)+ raise ArgumentError, "No example #{name} in #{examples_root}" unless File.file?(File.join(dir, "story.md"))+ dir+ end+ def copy_tree(source, destination)+ FileUtils.mkdir_p(destination)+ Dir.children(source).each do |entry|+ next if EXCLUDED.include?(entry)+ src, dst = File.join(source, entry), File.join(destination, entry)+ File.directory?(src) ? copy_tree(src, dst) : FileUtils.cp(src, dst)+ end+ end+ # An anime project: the story/brief (--prompt-file or --story) is required; a soundtrack (--song) and a folder of character+ # reference photos (--references, copied to references/) are optional. Scores are usually generated per scene.+ # --example <name> starts from the skill's examples/<name>: its story, config, prompts and plan.+ def create(project:, prompt: nil, song: nil, references: nil, example: nil)+ bundled = example && example_dir(example)+ prompt ||= bundled && File.join(bundled, "story.md")+ raise ArgumentError, "init requires --project and --story (or --prompt-file)" unless project && prompt+ raise ArgumentError, "Story/prompt file missing" unless File.file?(prompt)+ raise ArgumentError, "Song file missing" if song && !File.file?(song)+ raise ArgumentError, "References directory missing" if references && !File.directory?(references)+ raise ArgumentError, "Project must be a new or empty directory" if File.exist?(project) && (!File.directory?(project) || !Dir.children(project).empty?)+ copy_tree(@runtime, project)+ origin = File.file?(File.expand_path("../SKILL.md", @runtime)) ? File.expand_path("..", @runtime) : File.join(@runtime, ".skill")+ if File.file?(File.join(origin, "SKILL.md"))+ target = File.join(project, ".skill")+ FileUtils.mkdir_p(target)+ %w[SKILL.md references assets examples].each { |entry| FileUtils.cp_r(File.join(origin, entry), target) if File.exist?(File.join(origin, entry)) }+ end+ %w[audio config docs prompts output].each { |d| FileUtils.mkdir_p(File.join(project, d)) }+ source = nil+ if song+ source = "audio/source#{File.extname(song)}"+ FileUtils.cp(song, File.join(project, source))+ end+ FileUtils.cp_r(File.join(references, "."), File.join(project, "references")) if references+ FileUtils.cp(prompt, File.join(project, "docs", "BRIEF.md"))+ File.write(File.join(project, "config/generations.rb"), "# Evaluated inside Pipeline; see the skill task reference.\n{}\n")+ File.write(File.join(project, "config/production.json"), JSON.pretty_generate(wave: 0, jobs: []))+ File.write(File.join(project, "config/project.json"), JSON.pretty_generate(song_source: source, fps: 24, references: references && "references"))+ %w[config prompts docs].each { |d| FileUtils.cp_r(File.join(bundled, d, "."), File.join(project, d)) if File.directory?(File.join(bundled, d)) } if bundled+ { project: project, references: references && "references", example: example,+ next: "setup; write config/style.md, config/cast.yml and docs/PLAN.md (episode storyboard) before approval#{"; audio:analyze[#{source},audio]" if source}" }+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/toolkit/mcp_server.rb b/skills/make-an-anime/scripts/lib/toolkit/mcp_server.rbnew file mode 100644index 0000000..ede5ed2--- /dev/null+++ b/skills/make-an-anime/scripts/lib/toolkit/mcp_server.rb@@ -0,0 +1,200 @@+require "json"+require "open3"+require "rbconfig"+require "securerandom"+require "thread"+require_relative "../workflow/approval"++module Toolkit+ # Only the Fal-facing recipes need the configured secret. Local setup, file+ # editing, and recording the user's approval stay in the ordinary Ruby CLI.+ class CredentialTasks+ TASKS = %w[doctor audio:transcribe media:stems media:upload sfx:gen+ pipeline:all adopt gen:ref_base gen:ref_torn gen:keyframes gen:video+ gen:shots gen:clips gen:music gen:dialogue gen:mix gen:overlay review:music review:dialogue review:likeness review:camera dialogue:timeline scene:new episode:preview].freeze+ OPTIONS = %w[RUN ONLY FORCE RECUT NEW_REQUEST VIDEO_RES SFX VFX REFRESH_UPLOAD].freeze+ OUTPUT_LIMIT = 20_000+ MAX_RUNNING = 10+ PLUGIN_KEY = "FAL_AI_API_KEY_PLUGIN"++ # The plugin option arrives under its own name: when it is unset Claude Code+ # passes "", which must not hide a FAL_AI_API_KEY exported by the launcher.+ def self.env_key(env = ENV)+ plugin = env[PLUGIN_KEY].to_s+ usable?(plugin) ? plugin : env["FAL_AI_API_KEY"].to_s+ end++ def self.usable?(key) = !key.strip.empty? && !key.include?("${user_config.")++ def initialize(entry: File.expand_path("../../mv.rb", __dir__), api_key: self.class.env_key)+ @entry, @api_key = entry, api_key.to_s+ @jobs, @lock = {}, Mutex.new+ end++ def configured? = self.class.usable?(@api_key)++ def start(project:, task:, options: {})+ raise ArgumentError, "Configure the plugin's FAL_AI_API_KEY, or set it in the environment when launching mcp.rb" unless configured? || task == "doctor"+ raise ArgumentError, "project must be an absolute initialized video project path" unless project.is_a?(String) && project.start_with?("/") && File.file?(File.join(project, "config/project.json"))+ project = File.realpath(project)+ runtime = File.realpath(File.dirname(@entry))+ raise ArgumentError, "Use a video project outside the installed toolkit" if project == runtime || project.start_with?(runtime + "/")+ match = task.is_a?(String) && /\A([a-z_:]+)(?:\[[^\]\r\n\x00]*\])?\z/.match(task)+ raise ArgumentError, "Unsupported task; use a documented Fal task or doctor" unless match && TASKS.include?(match[1])+ raise ArgumentError, "options must contain only supported string task options" unless options.is_a?(Hash) && options.all? { |key, value| OPTIONS.include?(key) && value.is_a?(String) && !value.include?("\0") }+ Workflow::Approval.new(root: project).check! unless task == "doctor"+ @lock.synchronize do+ raise ArgumentError, "Ten jobs are already running; wait for a job to finish" if @jobs.values.count { |j| j[:state] == "running" } >= MAX_RUNNING+ @jobs.delete(@jobs.find { |_, j| j[:state] != "running" }&.first) while @jobs.size >= 100+ id = SecureRandom.hex(12)+ # No shell command string, user-supplied executable, or secret argument.+ environment = OPTIONS.to_h { |key| [key, nil] }.merge(options).merge("FAL_AI_API_KEY" => configured? ? @api_key : nil, PLUGIN_KEY => nil)+ # Desktop MCP launchers can inherit a C/US-ASCII locale. Project text+ # and worker logs use UTF-8 regardless of the launcher's locale.+ stdin, output, waiter = Open3.popen2e(environment, RbConfig.ruby, "-EUTF-8", @entry,+ "--project", project, task, chdir: project, pgroup: true)+ stdin.close+ output.set_encoding(Encoding::UTF_8)+ job = { state: "running", output: "", waiter: waiter, started: Process.clock_gettime(Process::CLOCK_MONOTONIC) }+ @jobs[id] = job+ job[:reader] = Thread.new do+ begin+ output.each_line do |line|+ safe = redact(line.encode("UTF-8", invalid: :replace, undef: :replace))+ @lock.synchronize do+ combined = job[:output] + safe+ job[:output] = combined.length > OUTPUT_LIMIT ? combined[-OUTPUT_LIMIT..] : combined+ end+ end+ ensure+ output.close+ status = waiter.value+ @lock.synchronize do+ job[:exit_code] = status.exitstatus+ job[:state] = status.success? ? "completed" : "failed" if job[:state] == "running"+ end+ end+ end+ { job_id: id, state: "running", next: "Poll task_status with this job_id. Do not start the same paid task again while it is running." }+ end+ end++ def status(id)+ @lock.synchronize do+ job = @jobs.fetch(id) { raise ArgumentError, "Unknown job_id; after a server restart use the project's saved Fal receipts to resume" }+ { job_id: id, state: job[:state], exit_code: job[:exit_code], output: job[:output].dup }+ end+ end++ def cancel(id)+ @lock.synchronize do+ job = @jobs.fetch(id) { raise ArgumentError, "Unknown job_id" }+ if job[:state] == "running"+ stop(job)+ job[:state] = "cancelled"+ end+ end+ status(id).merge(note: "Stops local processing only. A submitted Fal request may still run and incur charges; its receipt remains in the project.")+ end++ def close+ @lock.synchronize { @jobs.each_value { |job| stop(job) if job[:state] == "running" } }+ @jobs.each_value { |job| job[:reader].join(2) }+ end++ def redact(text)+ @api_key.empty? ? text : text.gsub(@api_key, "[REDACTED]")+ end++ private++ def stop(job)+ Process.kill("TERM", -job[:waiter].pid) if job[:waiter].alive?+ rescue Errno::ESRCH+ # It completed between the status check and the signal.+ end+ end++ # Minimal MCP stdio transport; stdout contains JSON-RPC messages only.+ class McpServer+ PROTOCOLS = %w[2025-11-25 2025-06-18 2025-03-26 2024-11-05].freeze+ JOB_SCHEMA = { type: "object", properties: { job_id: { type: "string" } }, required: ["job_id"], additionalProperties: false }.freeze+ TOOLS = [+ { name: "credential_status", description: "Check whether the Fal API key is configured. Never returns its value.",+ inputSchema: { type: "object", properties: {}, additionalProperties: false }, annotations: { readOnlyHint: true, openWorldHint: false } },+ { name: "run_task", description: "Start a Fal-facing Ruby toolkit task in an initialized, trusted video project. May upload media and incur Fal charges. Recorded production approval covers necessary uploads and generation within budget across RUNs; do not ask again per scene. Project Ruby configuration is executable code. Returns immediately; poll task_status. Local setup and plan approval use the Ruby CLI.",+ inputSchema: { type: "object", properties: {+ project: { type: "string", description: "Absolute path of the initialized video project" },+ task: { type: "string", description: "One Rake task, e.g. gen:ref_base or audio:transcribe[audio/song.wav,audio/words.json]" },+ options: { type: "object", properties: CredentialTasks::OPTIONS.to_h { |name| [name, { type: "string" }] }, additionalProperties: false }+ }, required: %w[project task], additionalProperties: false }, annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true } },+ { name: "task_status", description: "Read a job's state, exit code and recent redacted output. Poll until completed or failed before accepting its asset.",+ inputSchema: JOB_SCHEMA, annotations: { readOnlyHint: true, openWorldHint: false } },+ { name: "cancel_task", description: "Stop a local task process. Does not cancel an already submitted Fal request or its charges.",+ inputSchema: JOB_SCHEMA, annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false } }+ ].freeze++ def initialize(input: $stdin, output: $stdout, tasks: CredentialTasks.new)+ @input, @output, @tasks = input, output, tasks+ # MCP's newline-delimited JSON is UTF-8, independent of Ruby's defaults.+ @input.set_encoding(Encoding::UTF_8)+ @output.set_encoding(Encoding::UTF_8)+ end++ def run+ @input.each_line do |line|+ request = JSON.parse(line)+ unless request.is_a?(Hash) && request["jsonrpc"] == "2.0" && request["method"].is_a?(String)+ send_error(nil, -32600, "Invalid request")+ next+ end+ next unless request.key?("id") # Notifications never receive a response.+ id, params = request["id"], request["params"] || {}+ result = case request["method"]+ when "initialize"+ requested = params["protocolVersion"]+ { protocolVersion: PROTOCOLS.include?(requested) ? requested : PROTOCOLS.first,+ capabilities: { tools: {} }, serverInfo: { name: "anime", version: "0.4.0" } }+ when "ping" then {}+ when "tools/list" then { tools: TOOLS }+ when "tools/call" then call_tool(params)+ else+ send_error(id, -32601, "Method not found")+ next+ end+ send_message(jsonrpc: "2.0", id: id, result: result)+ rescue JSON::ParserError+ send_error(nil, -32700, "Invalid JSON")+ rescue StandardError => e+ send_error(request.is_a?(Hash) ? request["id"] : nil, -32603, @tasks.redact(e.message))+ end+ ensure+ @tasks.close+ end++ private++ def call_tool(params)+ args = params.fetch("arguments", {})+ tool = TOOLS.find { |item| item[:name] == params["name"] }+ raise ArgumentError, "Unknown tool" unless tool+ schema = tool[:inputSchema]+ raise ArgumentError, "Invalid tool arguments" unless args.is_a?(Hash) && (args.keys - schema[:properties].keys.map(&:to_s)).empty? && Array(schema[:required]).all? { |key| args.key?(key) }+ value = case params["name"]+ when "credential_status" then { configured: @tasks.configured? }+ when "run_task" then @tasks.start(project: args.fetch("project"), task: args.fetch("task"), options: args.fetch("options", {}))+ when "task_status" then @tasks.status(args.fetch("job_id"))+ when "cancel_task" then @tasks.cancel(args.fetch("job_id"))+ end+ { content: [{ type: "text", text: JSON.generate(value) }] }+ rescue StandardError => e+ { isError: true, content: [{ type: "text", text: @tasks.redact(e.message) }] }+ end++ def send_error(id, code, message) = send_message(jsonrpc: "2.0", id: id, error: { code: code, message: message })+ def send_message(message)+ @output.puts(JSON.generate(message))+ @output.flush+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/toolkit/operations.rb b/skills/make-an-anime/scripts/lib/toolkit/operations.rbnew file mode 100644index 0000000..f3d64cf--- /dev/null+++ b/skills/make-an-anime/scripts/lib/toolkit/operations.rb@@ -0,0 +1,214 @@+require_relative "../workflow/approval"+require_relative "../workflow/waves"+require_relative "../workflow/journal"+require_relative "../pipeline/reference_importer"+require_relative "fonts"+require_relative "anime_review"+require_relative "episode"+module Toolkit+ class Operations+ TASKS = {+ "doctor" => "Check local tools; STRICT=1 fails on missing prerequisites",+ "setup" => "Install gems, npm packages and a local Python venv through Ruby",+ "fonts:list" => "List installed macOS TTF/OTF files, including Supplemental fonts (local)",+ "fonts:copy" => "Copy selected fonts into this video project: [selection.json] (local)",+ "openapi:fetch" => "Fetch current Fal input schemas (no generation)",+ "openapi:summary" => "Print saved Fal schema summaries",+ "plan:approve" => "Record actual user approval: NOTE='approved wording'",+ "audio:seams" => "Report abrupt audio: every scene join in a film and the score joints inside scenes: [film,episode] (local)",+ "work:next" => "Allocate/resume next dependency-ready wave; SIZE=2/3..4/4..8/6..10",+ "work:accept" => "Accept reviewed job: JOB=id EVIDENCE=review.md",+ "work:log" => "Append worker progress: AGENT=id EVENT=event MESSAGE=text; LOG_DIR optional",+ "work:watch" => "Show recent worker log entries; LOG_DIR and LIMIT optional",+ "pipeline:status" => "Show RUN's generated/reviewed steps",+ "review:likeness" => "Character sheet(s) beside their reference photos: [run,run2,...] (local)",+ "review:camera" => "Measured vs directed camera move for RUN's H3 shots, with frame strips (local)",+ "scene:new" => "Scaffold an anime scene: [run,frames] -> prompts/<run>/, prompts/<run>-sfx/, config/generations/<run>.rb (local)",+ "scene:reaudio" => "Put RUN's current mix on its rendered overlay: [run] (picture copied, local)",+ "scene:vfx" => "Film-frame cues from scene-frame beats: [vfx_name], prompts/<name>/beats.yml -> cues.yml (local)",+ "scene:tail" => "Ring a score out past its end -> output/<run>/03_score_tail.wav: [run,source,seconds] (local)",+ "episode:preview" => "Join scenes into one preview: [out.mp4,ep01] or [out.mp4,run,run,...]; each scene leveled to LUFS=-23 (LUFS=off to skip), or by its voices with VOICE_DB=-24; SEAMS=1 fades each scene's track out and in around its voices (local)",+ "dialogue:timeline" => "RUN's shots and lines on one timeline; checks talking shots and cuts (local)",+ "pipeline:all" => "Generate and review all configured steps of RUN",+ "anim:render" => "Render sketch: [sketch,out,frames,width,height] (local)",+ "anim:preview" => "Preview RUN's overlay frames: [0,48,96] (local)",+ "anim:overlay" => "Render RUN's saved overlay data (local)",+ "anim:prepare" => "Prepare local overlay cues from optional full-song [words.json], without Fal",+ "audio:analyze" => "Decode and analyze song beats/energy: [audio,out_dir] (local)",+ "audio:transcribe" => "Word timestamps with Fal Whisper: [audio,out.json] (paid)",+ "media:stems" => "Fal Demucs: [audio,out_dir,vocals,...] (paid)",+ "media:probe" => "Probe [path]",+ "media:sheet" => "Contact sheet [video,out.jpg]",+ "media:frames" => "Dense reference analysis [video,out_dir,fps,width]",+ "media:frame" => "Extract [video,seconds,out.png]",+ "media:cut" => "Cut reference video [video,out.mp4,start,seconds]",+ "media:cuts" => "Detect picture cuts [video,out.json] (Python)",+ "media:mouth" => "Mouth alignment [clip_dir,vocals.wav,song_start,x,y,w,h] (Python)",+ "media:cutout" => "Cut out sprite [source,out_dir,green|paper] (Python)",+ "media:keep_component" => "Keep seeded alpha silhouette [source_dir,out_dir,seed_x,seed_y] (Python)",+ "media:sprite_box" => "Detect sprite bounds [source,green|paper] (Python)",+ "media:split_row" => "Split a character sheet [source,out_prefix,x1,x2,...] (Python)",+ "media:track" => "Track template [video,out.json,x,y,size,search,from_frame]",+ "media:audio_cut" => "Cut audio [source,out.wav,start,seconds]",+ "media:style" => "Style analysis [image,...] (Python)",+ "media:concat" => "Concatenate unrelated clips [out.mp4,a.mp4,b.mp4,...]",+ "media:mux" => "Replace audio [video,audio,out.mp4]",+ "media:preview" => "Join contiguous sections with unbroken song [out.mp4,s01,s02,...]",+ "media:youtube" => "4K delivery [video,out.mp4] (local encode only)",+ "media:twitter" => "1080p delivery [video,out.mp4] (local encode only)",+ "media:upload" => "Upload [path] to Fal CDN",+ "ref:import" => "Reuse existing hosted identity [new_run,local_image,original_manifest.json] (no upload)",+ "vfx:build" => "Build Swift Core Image renderer (macOS)",+ "vfx:analyze" => "Analyze VFX source beats and cuts; VFX=name",+ "vfx:stills" => "Preview cued VFX frames [0,24,...]; VFX=name",+ "vfx:clip" => "Render VFX interval [from_frame,to_frame]; VFX=name",+ "vfx:render" => "Render complete VFX version; VFX=name",+ "sfx:gen" => "Generate/cache Fal SFX or local tones; SFX=name (paid for Fal)",+ "sfx:mix" => "Mix cued SFX against music (local); SFX=name",+ "history" => "List archived attempts [step]",+ "adopt" => "Recover completed Fal request [step,request_id]",+ "pick" => "Restore archived request [step,index]",+ "import" => "Copy step from another run [step,source_run]",+ "test" => "Run RSpec suite; PROFILE=all|core|media|swift|live"+ }.freeze+ def ff = @ff ||= Media::FFmpeg.new+ def py = @py ||= Media::Python.new+ def emit(value) = puts(JSON.pretty_generate(value))+ def endpoints = Fal::Models.constants.filter_map { |c| k = Fal::Models.const_get(c); k.endpoint if k.respond_to?(:endpoint) && k != Fal::Models::Base }.uniq+ def required(args, n)+ raise ArgumentError, "Need #{n} arguments; see ruby scripts/mv.rb --help or rake -T" if args.size < n+ args+ end+ def call(name, a)+ case name+ when "doctor" then doctor+ when "setup" then setup+ when "fonts:list" then emit Fonts.new.list+ when "fonts:copy" then required(a, 1); emit Fonts.new.copy(a[0])+ when "openapi:fetch" then endpoints.each { |id| Fal::OpenAPI.fetch(id); warn "fetched #{id}" }+ when "openapi:summary" then endpoints.each { |id| puts Fal::OpenAPI.load(id).summary if File.file?(Fal::OpenAPI.spec_path(id)) }+ when "review:likeness" then emit AnimeReview.new.likeness(a)+ when "review:camera" then emit AnimeReview.new.camera+ when "dialogue:timeline" then emit AnimeReview.new.timeline+ when "scene:new" then required(a, 2); emit Episode.new.scaffold(a[0], a[1])+ when "audio:seams" then required(a, 1); emit Episode.new.seam_report(a[0], a[1] || "ep01")+ when "scene:reaudio" then required(a, 1); emit Episode.new.reaudio(a[0])+ when "scene:vfx" then required(a, 1); emit Episode.new.vfx_cues(a[0])+ when "scene:tail" then required(a, 3); emit Episode.new.score_tail(a[0], a[1], a[2])+ when "episode:preview" then required(a, 2); emit Episode.new.preview(a[0], a.drop(1), lufs: ENV["LUFS"] == "off" ? nil : Float(ENV.fetch("LUFS", "-23")), voice_db: ENV["VOICE_DB"]&.then { Float(_1) }, seams: ENV["SEAMS"] == "1")+ when "plan:approve" then emit Workflow::Approval.new.record!(ENV["NOTE"])+ when "work:next" then Workflow::Approval.new.check!; emit Workflow::Waves.new.next!(ENV["SIZE"])+ when "work:accept" then emit Workflow::Waves.new.accept!(ENV.fetch("JOB"), ENV["EVIDENCE"])+ when "work:log" then emit Workflow::Journal.new.append(agent: ENV["AGENT"], event: ENV["EVENT"], message: ENV["MESSAGE"], artifact: ENV["ARTIFACT"], request_id: ENV["REQUEST_ID"])+ when "work:watch" then emit Workflow::Journal.new.snapshot(limit: Integer(ENV.fetch("LIMIT", "5")))+ when "pipeline:status" then emit Pipeline::Project.new.manifest+ when "pipeline:all" then Pipeline::Project.new.steps.each { |s| generate(s); s.new.review! }+ when "anim:render"+ required(a, 3); emit Media::Anim.new.render(a[0], a[1], frames: Integer(a[2]), width: Integer(a[3] || 1920), height: Integer(a[4] || 1080), fps: 24)+ when "anim:preview" then required(a, 1); Pipeline::Steps::Overlay.new.preview!(a.map { |x| Integer(x) })+ when "anim:overlay" then emit Pipeline::Steps::Overlay.new.render!+ when "anim:prepare" then emit Pipeline::Steps::Overlay.new.prepare!(a[0])+ when "audio:analyze" then required(a, 2); analyze_audio(*a)+ when "audio:transcribe"+ required(a, 2); c = Fal::Client.new; result = Fal::Models::Whisper.new(client: c).transcribe(audio_url: c.upload(a[0]), chunk_level: "word")+ FileUtils.mkdir_p(File.dirname(a[1])); File.write(a[1], JSON.pretty_generate(result.output)); emit(path: a[1], request_id: result.request_id)+ when "media:stems"+ required(a, 2); c = Fal::Client.new; stems = a.drop(2); stems = %w[vocals] if stems.empty?+ result = Fal::Models::Demucs.new(client: c).separate(audio_url: c.upload(a[0]), stems: stems)+ FileUtils.mkdir_p(a[1]); emit stems.map { |s| c.download(result.output.fetch(s).fetch("url"), File.join(a[1], "#{s}.wav")) }+ when "media:probe" then required(a, 1); emit ff.summary(a[0])+ when "media:sheet" then required(a, 2); emit ff.contact_sheet(*a)+ when "media:frames" then required(a, 2); emit ff.extract_frames(a[0], a[1], fps: Float(a[2] || 12), width: Integer(a[3] || 480))+ when "media:frame" then required(a, 3); emit ff.frame_at(a[0], Float(a[1]), a[2])+ when "media:cut"+ required(a, 4); ff.run("ffmpeg", "-y", "-v", "error", "-ss", a[2], "-i", a[0], "-t", a[3], "-c:v", "libx264", "-c:a", "aac", a[1]); emit(path: a[1])+ when "media:cuts"+ required(a, 2); result = py.call("cuts.py", a[0]); File.write(a[1], JSON.pretty_generate(result)); emit(path: a[1], cuts: result["cuts"])+ when "media:mouth"+ required(a, 7); result = py.run(py.executable, File.join(Media::Python::SCRIPTS, "mouth_sync.py"), *a); emit JSON.parse(result.lines.last)+ when "media:cutout" then required(a, 3); emit py.cutout(*a)+ when "media:keep_component" then required(a, 4); emit Media::SpriteComponents.new.keep(*a)+ when "media:sprite_box" then required(a, 2); emit py.call("sprite_box.py", *a)+ when "media:split_row" then required(a, 3); emit(summary: py.run(py.executable, File.join(Media::Python::SCRIPTS, "split_row.py"), *a))+ when "media:track"+ required(a, 5); result = py.track_template(a[0], Integer(a[2]), Integer(a[3]), Integer(a[4]), Integer(a[5] || a[4]), Integer(a[6] || 0)); File.write(a[1], JSON.pretty_generate(result)); emit(path: a[1])+ when "media:audio_cut" then required(a, 4); emit ff.extract_audio(a[0], a[1], from: Float(a[2]), seconds: Float(a[3]))+ when "media:style" then required(a, 1); emit py.style_split(*a)+ when "media:concat" then required(a, 2); emit ff.concat_videos(a.drop(1), a[0])+ when "media:mux" then required(a, 3); emit ff.mux(*a, shortest: false)+ when "media:preview" then required(a, 2); emit preview(a[0], a.drop(1))+ when "media:youtube" then required(a, 2); emit ff.youtube_4k(*a)+ when "media:twitter" then required(a, 2); emit ff.twitter_1080(*a)+ when "media:upload" then required(a, 1); emit(url: Fal::Client.new.upload(a[0]))+ when "ref:import" then required(a, 3); emit Pipeline::ReferenceImporter.new.import(run: a[0], image: a[1], manifest: a[2])+ when "vfx:build" then emit Media::Vfx.new.build+ when "vfx:analyze" then emit Media::Vfx.new.analyze+ when "vfx:stills" then required(a, 1); emit Media::Vfx.new.stills(a.map { |x| Integer(x) })+ when "vfx:clip" then required(a, 2); emit Media::Vfx.new.clip(*a.map { |x| Integer(x) })+ when "vfx:render" then emit Media::Vfx.new.render+ when "sfx:gen" then emit Media::Sfx.new.generate(only: ENV["ONLY"]&.split(","), force: ENV["FORCE"] == "1")+ when "sfx:mix" then emit Media::Sfx.new.mix+ when "history" then required(a, 1); emit Array(Pipeline::Project.new[a[0]]&.dig("history"))+ when "adopt" then required(a, 2); step(a[0]).new.adopt!(a[1])+ when "pick" then required(a, 2); step(a[0]).new.pick!(Integer(a[1]))+ when "import" then required(a, 2); step(a[0]).new.import!(a[1])+ when "test" then require_relative "test_runner"; TestRunner.new.run+ else raise ArgumentError, "Unknown task #{name}"+ end+ end+ def step(key) = Pipeline::ALL_STEPS.find { |s| s.key.to_s == key } || raise("Unknown step #{key}")+ def generate(klass)+ project = Pipeline::Project.new+ raise "#{klass.key} is not configured for RUN=#{project.name}" unless project.steps.include?(klass)+ File.open(project.path("worker.lock"), File::CREAT | File::RDWR) do |lock|+ raise "RUN=#{project.name} already has a worker" unless lock.flock(File::LOCK_EX | File::LOCK_NB)+ klass.new(project: project).run!+ end+ end+ def analyze_audio(source, out)+ FileUtils.mkdir_p(out)+ wav = ff.extract_audio(source, File.join(out, "song.wav"))+ beats = py.call("beats.py", wav, "24")+ energy = py.audio_energy(wav)+ File.write(File.join(out, "beats.json"), JSON.pretty_generate(beats))+ File.write(File.join(out, "energy.json"), JSON.pretty_generate(energy))+ emit(duration: ff.duration(wav), bpm: beats["bpm"], beats: File.join(out, "beats.json"), energy: File.join(out, "energy.json"))+ end+ def preview(out, names)+ runs = names.map { |n| Pipeline::Project.new(n) }+ runs.each_cons(2) do |left, right|+ a, b = left.generation, right.generation+ raise "Noncontiguous song sections: #{left.name} -> #{right.name}" unless a[:music_from] == b[:music_from] && a[:music_offset] && (a[:music_offset] + left.duration - b[:music_offset].to_f).abs < 1e-6+ end+ runs.each do |r|+ actual = ff.summary(r.path("final_overlay.mp4")).dig(:video, :frames)+ raise "#{r.name}: #{actual} frames, expected #{(r.duration * 24).round}" unless actual == (r.duration * 24).round+ end+ FileUtils.mkdir_p(File.dirname(out))+ first = runs.first.generation+ song = ff.extract_audio(first.fetch(:music_from), "#{out}.song.wav", from: first.fetch(:music_offset), seconds: runs.sum(&:duration))+ video = ff.concat_videos(runs.map { |r| r.path("final_overlay.mp4") }, "#{out}.video.mp4", audio: false)+ ff.mux(video, song, out, shortest: false)+ FileUtils.rm_f([song, video])+ out+ end+ def doctor+ bins = %w[ffmpeg ffprobe magick python3 node swift]+ checks = bins.to_h { |b| [b, Media::Shell.available?(b)] }+ checks["python_packages"] = system(py.executable, "-c", "import PIL, numpy", out: File::NULL, err: File::NULL)+ checks["node_packages"] = File.directory?("node_modules/p5") && File.directory?("node_modules/puppeteer-core")+ checks["chrome"] = [ENV["CHROME_PATH"], "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/usr/bin/google-chrome", "/usr/bin/chromium"].compact.any? { |p| File.file?(p) }+ checks["fal_key"] = !ENV["FAL_AI_API_KEY"].to_s.strip.empty?+ emit checks+ raise "Missing prerequisites; see references/testing.md and run setup" if ENV["STRICT"] == "1" && checks.values.any? { |v| !v }+ end+ def setup+ shell = Media::Shell.new+ shell.run(RbConfig.ruby, "-S", "bundle", "install")+ shell.run("npm", "ci")+ shell.run("python3", "-m", "venv", ".venv") unless File.directory?(".venv")+ shell.run(File.expand_path(".venv/bin/python3"), "-m", "pip", "install", "-r", "requirements.txt")+ doctor+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/toolkit/test_runner.rb b/skills/make-an-anime/scripts/lib/toolkit/test_runner.rbnew file mode 100644index 0000000..015d25c--- /dev/null+++ b/skills/make-an-anime/scripts/lib/toolkit/test_runner.rb@@ -0,0 +1,19 @@+require "rbconfig"+module Toolkit+ class TestRunner+ def run+ profile = ENV.fetch("PROFILE", "all")+ raise "PROFILE must be all, core, media, swift or live" unless %w[all core media swift live].include?(profile)+ if profile == "live"+ raise "Paid tests require LIVE_FAL=1, LIVE_SONG=/path/to/song.wav and LIVE_LYRICS='recognizable words'" unless ENV["LIVE_FAL"] == "1" && File.file?(ENV["LIVE_SONG"].to_s) && !ENV["LIVE_LYRICS"].to_s.strip.empty?+ end+ # Specs chdir into temporary workspaces; pin the toolkit's own venv so Python helpers keep numpy/PIL.+ venv = File.expand_path(".venv/bin/python3")+ ENV["MV_PYTHON"] ||= venv if File.file?(venv)+ args = [RbConfig.ruby, "-S", "rspec", "spec", "--format", "documentation"]+ args += profile == "all" ? ["--tag", "~live"] : ["--tag", profile]+ ok = system(*args)+ raise "RSpec failed for PROFILE=#{profile}; see failures above" unless ok+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/workflow/approval.rb b/skills/make-an-anime/scripts/lib/workflow/approval.rbnew file mode 100644index 0000000..f39d9ef--- /dev/null+++ b/skills/make-an-anime/scripts/lib/workflow/approval.rb@@ -0,0 +1,29 @@+require "json"+require "digest"+require "fileutils"+require "time"+module Workflow+ class Approval+ def initialize(root: Dir.pwd)+ @root = File.expand_path(root)+ end+ def path(relative) = File.join(@root, relative)+ def fingerprint+ raise "Write docs/PLAN.md with character prompts, scene prompts and costs first" unless File.file?(path("docs/PLAN.md"))+ Digest::SHA256.file(path("docs/PLAN.md")).hexdigest+ end+ def record!(note)+ raise ArgumentError, "NOTE must quote the user's explicit approval" if note.to_s.strip.empty?+ FileUtils.mkdir_p(path("config"))+ data = { plan_sha256: fingerprint, user_approval: note, recorded_at: Time.now.iso8601 }+ File.write(path("config/approval.json"), JSON.pretty_generate(data), encoding: "UTF-8")+ data+ end+ def check!+ raise "Plan approval missing. Present docs/PLAN.md and obtain the user's approval before paid work." unless File.file?(path("config/approval.json"))+ data = JSON.parse(File.read(path("config/approval.json"), encoding: "UTF-8"))+ raise "Plan changed since approval; obtain approval for the revised plan." unless data["plan_sha256"] == fingerprint+ true+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/workflow/journal.rb b/skills/make-an-anime/scripts/lib/workflow/journal.rbnew file mode 100644index 0000000..8088461--- /dev/null+++ b/skills/make-an-anime/scripts/lib/workflow/journal.rb@@ -0,0 +1,43 @@+require "json"+require "fileutils"+require "time"++module Workflow+ # Persistent, bounded progress reporting for real host-managed sub-agents.+ class Journal+ def initialize(dir = ENV.fetch("LOG_DIR", "logs"))+ @dir = File.expand_path(dir)+ end++ def append(agent:, event:, message:, artifact: nil, request_id: nil)+ raise ArgumentError, "AGENT must be a simple worker ID" unless agent.to_s.match?(/\A[a-zA-Z0-9_-]+\z/)+ raise ArgumentError, "EVENT and MESSAGE are required" if event.to_s.empty? || message.to_s.empty?+ entry = { time: Time.now.iso8601, agent: agent, event: event, message: message,+ artifact: artifact, request_id: request_id }.compact+ FileUtils.mkdir_p(@dir)+ File.open(File.join(@dir, "#{agent}.jsonl"), "a") do |file|+ file.flock(File::LOCK_EX)+ file.puts(JSON.generate(entry))+ file.flush+ end+ entry+ end++ def snapshot(limit: 5)+ raise ArgumentError, "LIMIT must be between 1 and 50" unless (1..50).cover?(limit)+ Dir[File.join(@dir, "*.jsonl")].sort.map do |path|+ entries = []+ File.open(path, "r") do |file|+ file.flock(File::LOCK_SH)+ file.each_line do |line|+ entries << JSON.parse(line)+ entries.shift if entries.size > limit+ end+ end+ { agent: File.basename(path, ".jsonl"), path: path,+ seconds_since_update: (Time.now - File.mtime(path)).round,+ entries: entries }+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/lib/workflow/waves.rb b/skills/make-an-anime/scripts/lib/workflow/waves.rbnew file mode 100644index 0000000..5e1f31c--- /dev/null+++ b/skills/make-an-anime/scripts/lib/workflow/waves.rb@@ -0,0 +1,65 @@+require "json"+require "fileutils"+module Workflow+ # The agent owns creative review and delegation. This class owns dependency/wave bookkeeping.+ class Waves+ FILE = "config/production.json"+ LIMITS = [2, 4, 8, 10].freeze+ def transaction+ File.open("#{FILE}.lock", File::CREAT | File::RDWR) do |lock|+ lock.flock(File::LOCK_EX)+ data = JSON.parse(File.read(FILE))+ validate!(data)+ result = yield data+ File.write("#{FILE}.tmp", JSON.pretty_generate(data))+ File.rename("#{FILE}.tmp", FILE)+ result+ end+ end+ def validate!(data)+ jobs = data.fetch("jobs")+ ids = jobs.map { |j| j.fetch("id") }+ raise "Duplicate job IDs" unless ids.uniq == ids+ jobs.each do |job|+ raise "Unknown job state" unless %w[pending running accepted].include?(job.fetch("state", "pending"))+ raise "Missing dependencies for #{job['id']}" unless (job.fetch("depends", []) - ids).empty?+ end+ end+ def next!(size = nil)+ transaction do |data|+ jobs = data.fetch("jobs")+ active = jobs.select { |j| j["state"] == "running" }+ next({ wave: data.fetch("wave", 0), jobs: active, resumed: true }) unless active.empty?+ wave = data.fetch("wave", 0)+ cap = LIMITS[[wave, 3].min]+ min = [2, 3, 4, 6][[wave, 3].min]+ n = size ? Integer(size) : cap+ raise "Wave #{wave + 1} size must be #{min}..#{cap}" unless (min..cap).cover?(n)+ accepted = jobs.select { |j| j["state"] == "accepted" }.map { |j| j["id"] }+ ready = jobs.select { |j| j.fetch("state", "pending") == "pending" && (j.fetch("depends", []) - accepted).empty? }+ picked = []+ ready.each do |job|+ # A worker exclusively owns a run (or resource, for non-run tasks).+ resource = job.fetch("resource", job["run"] || job["id"])+ next if picked.any? { |j| j.fetch("resource", j["run"] || j["id"]) == resource }+ picked << job+ break if picked.size == n+ end+ if picked.empty? && accepted.size != jobs.size+ raise "No jobs ready: check dependency cycles and states"+ end+ picked.each { |j| j["state"] = "running" }+ data["wave"] = wave + 1 unless picked.empty?+ { wave: data.fetch("wave", wave), jobs: picked, complete: accepted.size == jobs.size }+ end+ end+ def accept!(id, evidence)+ raise "EVIDENCE must name an existing review file" unless evidence && File.file?(evidence)+ transaction do |data|+ job = data["jobs"].find { |j| j["id"] == id } or raise "Unknown job #{id}"+ raise "Job #{id} is not in the active wave" unless job["state"] == "running"+ job.merge!("state" => "accepted", "evidence" => evidence)+ end+ end+ end+enddiff --git a/skills/make-an-anime/scripts/mcp.rb b/skills/make-an-anime/scripts/mcp.rbnew file mode 100644index 0000000..86e7e29--- /dev/null+++ b/skills/make-an-anime/scripts/mcp.rb@@ -0,0 +1,4 @@+#!/usr/bin/env ruby+# Start without Bundler so the plugin can connect before a video project is set up.+require_relative "lib/toolkit/mcp_server"+Toolkit::McpServer.new.run if $PROGRAM_NAME == __FILE__diff --git a/skills/make-an-anime/scripts/mv.rb b/skills/make-an-anime/scripts/mv.rbnew file mode 100644index 0000000..76b2270--- /dev/null+++ b/skills/make-an-anime/scripts/mv.rb@@ -0,0 +1,46 @@+#!/usr/bin/env ruby+require "optparse"+require "fileutils"+require "json"+require "rbconfig"+require "open3"+runtime = __dir__+options = {}+parser = OptionParser.new do |o|+ o.banner = "make-an-anime toolkit\nUsage: ruby scripts/mv.rb [--project DIR] TASK [task arguments]\n ruby scripts/mv.rb init --project DIR --story STORY.md [--references DIR] [--song FILE]\n ruby scripts/mv.rb init --project DIR --example shonen-battle\nRuby is the only execution entry. Tasks use ENV RUN/ONLY/FORCE/VFX/SFX."+ o.on("--project DIR", "Project workspace (defaults to bundled runtime)") { |v| options[:project] = File.expand_path(v) }+ o.on("--song FILE", "Local soundtrack for init") { |v| options[:song] = File.expand_path(v) }+ o.on("--prompt-file FILE", "--story FILE", "Story bible / creative brief for init") { |v| options[:prompt] = File.expand_path(v) }+ o.on("--example NAME", "Start init from a bundled example, e.g. shonen-battle") { |v| options[:example] = v }+ o.on("--references DIR", "Character reference photos for init (copied to references/)") { |v| options[:references] = File.expand_path(v) }+ o.on("-T", "List all rake tasks") { options[:list] = true }+ o.on("--help", "Show tasks and exit") { puts o; puts "Tasks: init, setup, doctor, test, plan:approve, work:next, work:accept, audio:analyze, audio:transcribe, media:stems, gen:<step>, review:<step>, gen:dialogue, gen:music, gen:mix, gen:keyframes, gen:shots, pipeline:all, anim:preview, anim:overlay, media:preview, sfx:gen, sfx:mix, vfx:render. Use -T for the complete rake task list.\nExit: 0 success; 1 task/runtime failure; 2 invalid CLI or missing input. No interactive shell prompts."; exit }+end+begin+ parser.parse!(ARGV)+ command = options[:list] ? "-T" : (ARGV.shift || "pipeline:status")+ if command == "init"+ require_relative "lib/toolkit/initializer"+ puts JSON.pretty_generate(Toolkit::Initializer.new(runtime).create(project: options[:project], song: options[:song], prompt: options[:prompt], references: options[:references], example: options[:example]))+ exit+ end+ project = options[:project] || runtime+ raise ArgumentError, "No project Rakefile in #{project}; use init first" unless File.file?(File.join(project, "Rakefile"))+ Dir.chdir(project)+ if command == "setup"+ # Bootstrap gems before loading any runtime dependencies.+ ok = system(RbConfig.ruby, "-S", "bundle", "install")+ raise "bundle install failed" unless ok+ end+ ENV["BUNDLE_GEMFILE"] = File.join(project, "Gemfile")+ require "bundler/setup"+ require "rake"+ args = command == "-T" ? ["-T"] : [command, *ARGV]+ Rake.application.run(args)+rescue OptionParser::ParseError, ArgumentError => e+ warn "Error: #{e.message}\n#{parser}"+ exit 2+rescue StandardError => e+ warn "Error: #{e.message}"+ exit 1+enddiff --git a/skills/make-an-anime/scripts/package-lock.json b/skills/make-an-anime/scripts/package-lock.jsonnew file mode 100644index 0000000..e43a794--- /dev/null+++ b/skills/make-an-anime/scripts/package-lock.json@@ -0,0 +1,528 @@+{+ "name": "make-an-anime-tools",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "make-an-anime-tools",+ "dependencies": {+ "p5": "^2.3.3",+ "puppeteer-core": "^25.12.0"+ }+ },+ "node_modules/@babel/runtime": {+ "version": "7.29.7",+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.29.7.tgz",+ "integrity": "sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==",+ "license": "MIT",+ "engines": {+ "node": ">=6.9.0"+ }+ },+ "node_modules/@davepagurek/bezier-path": {+ "version": "0.0.7",+ "resolved": "https://registry.npmjs.org/@davepagurek/bezier-path/-/bezier-path-0.0.7.tgz",+ "integrity": "sha512-CVlnCOrV1iy4Z12T756i9l4G6kF7r8uhlnb+xqDemAMmWQB+8Q0b+8VEqIiUfywgZDSiDr18Rm7pZlnA69rE8Q==",+ "license": "MIT"+ },+ "node_modules/@japont/unicode-range": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/@japont/unicode-range/-/unicode-range-1.0.0.tgz",+ "integrity": "sha512-BckHvA2XdjRBVAWe2uceNuRf78lBeI28kyWEbfr/Q2pE17POkwuZ6WWY/UMv8FL9iBxhW4xfDoNLM9UVZaTeUQ==",+ "license": "MIT"+ },+ "node_modules/@puppeteer/browsers": {+ "version": "3.2.3",+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-3.2.3.tgz",+ "integrity": "sha512-2Bt3m6dDAJqmZehn0wiXSYyQmuhyiHHZ7FjvrVaS1W2RoFGV6eCK71UvKYkNJjkwC1Q9nobjhvTMhLQztFVINA==",+ "license": "Apache-2.0",+ "dependencies": {+ "modern-tar": "^0.8.4",+ "yargs": "^18.0.0"+ },+ "bin": {+ "browsers": "lib/main-cli.js"+ },+ "engines": {+ "node": ">=22.12.0"+ },+ "peerDependencies": {+ "proxy-agent": ">=8.0.1",+ "yauzl": "^2.10.0 || ^3.4.0"+ },+ "peerDependenciesMeta": {+ "proxy-agent": {+ "optional": true+ },+ "yauzl": {+ "optional": true+ }+ }+ },+ "node_modules/acorn": {+ "version": "8.18.0",+ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",+ "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==",+ "license": "MIT",+ "bin": {+ "acorn": "bin/acorn"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/acorn-walk": {+ "version": "8.3.5",+ "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.5.tgz",+ "integrity": "sha512-HEHNfbars9v4pgpW6SO1KSPkfoS0xVOM/9UzkJltjlsHZmJasxg8aXkuZa7SMf8vKGIBhpUsPluQSqhJFCqebw==",+ "license": "MIT",+ "dependencies": {+ "acorn": "^8.11.0"+ },+ "engines": {+ "node": ">=0.4.0"+ }+ },+ "node_modules/ansi-regex": {+ "version": "6.3.0",+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.3.0.tgz",+ "integrity": "sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"+ }+ },+ "node_modules/ansi-styles": {+ "version": "6.2.3",+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",+ "license": "MIT",+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"+ }+ },+ "node_modules/chromium-bidi": {+ "version": "17.0.2",+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-17.0.2.tgz",+ "integrity": "sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==",+ "license": "Apache-2.0",+ "dependencies": {+ "mitt": "^3.0.1",+ "zod": "^3.24.1"+ },+ "engines": {+ "node": ">=20.19.0 <22.0.0 || >=22.12.0"+ },+ "peerDependencies": {+ "devtools-protocol": "*"+ }+ },+ "node_modules/chromium-bidi/node_modules/zod": {+ "version": "3.25.76",+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",+ "integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },+ "node_modules/cliui": {+ "version": "9.0.1",+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-9.0.1.tgz",+ "integrity": "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==",+ "license": "ISC",+ "dependencies": {+ "string-width": "^7.2.0",+ "strip-ansi": "^7.1.0",+ "wrap-ansi": "^9.0.0"+ },+ "engines": {+ "node": ">=20"+ }+ },+ "node_modules/cliui/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/colorjs.io": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/colorjs.io/-/colorjs.io-0.6.1.tgz",+ "integrity": "sha512-8lyR2wHzuIykCpqHKgluGsqQi5iDm3/a2IgP2GBZrasn2sBRkE4NOGsglZxWLs/jZQoNkmA/KM/8NV16rLUdBg==",+ "license": "MIT",+ "funding": {+ "type": "opencollective",+ "url": "https://opencollective.com/color"+ }+ },+ "node_modules/devtools-protocol": {+ "version": "0.0.1687809",+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1687809.tgz",+ "integrity": "sha512-t7kSb+UKYdyxcmqy98U2P86ne6rCve3DIJ4+lp54i/hhClgFuG35JrLj23rO14Jw3sWDsp7i+22QhNU0+/qk8g==",+ "license": "BSD-3-Clause"+ },+ "node_modules/emoji-regex": {+ "version": "10.6.0",+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",+ "license": "MIT"+ },+ "node_modules/escalade": {+ "version": "3.2.0",+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",+ "license": "MIT",+ "engines": {+ "node": ">=6"+ }+ },+ "node_modules/escodegen": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz",+ "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==",+ "license": "BSD-2-Clause",+ "dependencies": {+ "esprima": "^4.0.1",+ "estraverse": "^5.2.0",+ "esutils": "^2.0.2"+ },+ "bin": {+ "escodegen": "bin/escodegen.js",+ "esgenerate": "bin/esgenerate.js"+ },+ "engines": {+ "node": ">=6.0"+ },+ "optionalDependencies": {+ "source-map": "~0.6.1"+ }+ },+ "node_modules/esprima": {+ "version": "4.0.1",+ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",+ "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",+ "license": "BSD-2-Clause",+ "bin": {+ "esparse": "bin/esparse.js",+ "esvalidate": "bin/esvalidate.js"+ },+ "engines": {+ "node": ">=4"+ }+ },+ "node_modules/estraverse": {+ "version": "5.3.0",+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=4.0"+ }+ },+ "node_modules/esutils": {+ "version": "2.0.3",+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",+ "license": "BSD-2-Clause",+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/get-caller-file": {+ "version": "2.0.5",+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",+ "license": "ISC",+ "engines": {+ "node": "6.* || 8.* || >= 10.*"+ }+ },+ "node_modules/get-east-asian-width": {+ "version": "1.7.0",+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",+ "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",+ "license": "MIT",+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/gifenc": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/gifenc/-/gifenc-1.0.3.tgz",+ "integrity": "sha512-xdr6AdrfGBcfzncONUOlXMBuc5wJDtOueE3c5rdG0oNgtINLD+f2iFZltrBRZYzACRbKr+mSVU/x98zv2u3jmw==",+ "license": "MIT"+ },+ "node_modules/i18next": {+ "version": "19.9.2",+ "resolved": "https://registry.npmjs.org/i18next/-/i18next-19.9.2.tgz",+ "integrity": "sha512-0i6cuo6ER6usEOtKajUUDj92zlG+KArFia0857xxiEHAQcUwh/RtOQocui1LPJwunSYT574Pk64aNva1kwtxZg==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.12.0"+ }+ },+ "node_modules/i18next-browser-languagedetector": {+ "version": "4.3.1",+ "resolved": "https://registry.npmjs.org/i18next-browser-languagedetector/-/i18next-browser-languagedetector-4.3.1.tgz",+ "integrity": "sha512-KIToAzf8zwWvacgnRwJp63ase26o24AuNUlfNVJ5YZAFmdGhsJpmFClxXPuk9rv1FMI4lnc8zLSqgZPEZMrW4g==",+ "license": "MIT",+ "dependencies": {+ "@babel/runtime": "^7.5.5"+ }+ },+ "node_modules/libtess": {+ "version": "1.2.2",+ "resolved": "https://registry.npmjs.org/libtess/-/libtess-1.2.2.tgz",+ "integrity": "sha512-Nps8HPeVVcsmJxUvFLKVJcCgcz+1ajPTXDVAVPs6+giOQP4AHV31uZFFkh+CKow/bkB7GbZWKmwmit7myaqDSw==",+ "license": "SGI-B-2.0"+ },+ "node_modules/mitt": {+ "version": "3.0.1",+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",+ "license": "MIT"+ },+ "node_modules/modern-tar": {+ "version": "0.8.5",+ "resolved": "https://registry.npmjs.org/modern-tar/-/modern-tar-0.8.5.tgz",+ "integrity": "sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==",+ "license": "MIT",+ "engines": {+ "node": ">=18.0.0"+ }+ },+ "node_modules/omggif": {+ "version": "1.0.10",+ "resolved": "https://registry.npmjs.org/omggif/-/omggif-1.0.10.tgz",+ "integrity": "sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw==",+ "license": "MIT"+ },+ "node_modules/p5": {+ "version": "2.3.3",+ "resolved": "https://registry.npmjs.org/p5/-/p5-2.3.3.tgz",+ "integrity": "sha512-+zVz5JFp3sCLpLscTMOLoA0UEHV0dsHxngKVfMmeW1J2/IXvfFqCjNYZeIOtG4Lhfnpm7cu6446P6Ho64ihXfA==",+ "license": "LGPL-2.1",+ "dependencies": {+ "@davepagurek/bezier-path": "^0.0.7",+ "@japont/unicode-range": "^1.0.0",+ "acorn": "^8.15.0",+ "acorn-walk": "^8.3.4",+ "colorjs.io": "^0.6.0",+ "escodegen": "^2.1.0",+ "gifenc": "^1.0.3",+ "i18next": "^19.0.2",+ "i18next-browser-languagedetector": "^4.0.1",+ "libtess": "^1.2.2",+ "omggif": "^1.0.10",+ "pako": "^2.1.0",+ "zod": "^4.2.1"+ }+ },+ "node_modules/pako": {+ "version": "2.2.0",+ "resolved": "https://registry.npmjs.org/pako/-/pako-2.2.0.tgz",+ "integrity": "sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/puzrin"+ },+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodeca"+ }+ ],+ "license": "(MIT AND Zlib)"+ },+ "node_modules/puppeteer-core": {+ "version": "25.12.0",+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-25.12.0.tgz",+ "integrity": "sha512-z6LQUt5SH7jwGtGA+nMtJuEjZIsqPiwQ+EFHCYuVDQrJpvifNmmGuyDvTzAKPyFzihxgHc5f3aMzu2kn8Ps37A==",+ "license": "Apache-2.0",+ "dependencies": {+ "@puppeteer/browsers": "3.2.3",+ "chromium-bidi": "17.0.2",+ "devtools-protocol": "0.0.1687809",+ "typed-query-selector": "^2.12.2",+ "webdriver-bidi-protocol": "0.4.3",+ "ws": "^8.21.3"+ },+ "engines": {+ "node": ">=22.12.0"+ }+ },+ "node_modules/source-map": {+ "version": "0.6.1",+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",+ "license": "BSD-3-Clause",+ "optional": true,+ "engines": {+ "node": ">=0.10.0"+ }+ },+ "node_modules/string-width": {+ "version": "8.3.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz",+ "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==",+ "license": "MIT",+ "dependencies": {+ "get-east-asian-width": "^1.5.0",+ "strip-ansi": "^7.1.2"+ },+ "engines": {+ "node": ">=20"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/strip-ansi": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",+ "license": "MIT",+ "dependencies": {+ "ansi-regex": "^6.2.2"+ },+ "engines": {+ "node": ">=12"+ },+ "funding": {+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"+ }+ },+ "node_modules/typed-query-selector": {+ "version": "2.12.2",+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.2.tgz",+ "integrity": "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ==",+ "license": "MIT"+ },+ "node_modules/webdriver-bidi-protocol": {+ "version": "0.4.3",+ "resolved": "https://registry.npmjs.org/webdriver-bidi-protocol/-/webdriver-bidi-protocol-0.4.3.tgz",+ "integrity": "sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==",+ "license": "Apache-2.0"+ },+ "node_modules/wrap-ansi": {+ "version": "9.0.2",+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",+ "license": "MIT",+ "dependencies": {+ "ansi-styles": "^6.2.1",+ "string-width": "^7.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"+ }+ },+ "node_modules/wrap-ansi/node_modules/string-width": {+ "version": "7.2.0",+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",+ "license": "MIT",+ "dependencies": {+ "emoji-regex": "^10.3.0",+ "get-east-asian-width": "^1.0.0",+ "strip-ansi": "^7.1.0"+ },+ "engines": {+ "node": ">=18"+ },+ "funding": {+ "url": "https://github.com/sponsors/sindresorhus"+ }+ },+ "node_modules/ws": {+ "version": "8.21.3",+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",+ "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",+ "license": "MIT",+ "engines": {+ "node": ">=10.0.0"+ },+ "peerDependencies": {+ "bufferutil": "^4.0.1",+ "utf-8-validate": ">=5.0.2"+ },+ "peerDependenciesMeta": {+ "bufferutil": {+ "optional": true+ },+ "utf-8-validate": {+ "optional": true+ }+ }+ },+ "node_modules/y18n": {+ "version": "5.0.8",+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",+ "license": "ISC",+ "engines": {+ "node": ">=10"+ }+ },+ "node_modules/yargs": {+ "version": "18.2.0",+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-18.2.0.tgz",+ "integrity": "sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==",+ "license": "MIT",+ "dependencies": {+ "cliui": "^9.0.1",+ "escalade": "^3.1.1",+ "get-caller-file": "^2.0.5",+ "string-width": "^8.2.1",+ "y18n": "^5.0.5",+ "yargs-parser": "^22.0.0"+ },+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/yargs-parser": {+ "version": "22.0.0",+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-22.0.0.tgz",+ "integrity": "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==",+ "license": "ISC",+ "engines": {+ "node": "^20.19.0 || ^22.12.0 || >=23"+ }+ },+ "node_modules/zod": {+ "version": "4.6.5",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ }+ }+}diff --git a/skills/make-an-anime/scripts/package.json b/skills/make-an-anime/scripts/package.jsonnew file mode 100644index 0000000..76573d0--- /dev/null+++ b/skills/make-an-anime/scripts/package.json@@ -0,0 +1,10 @@+{+ "name": "make-an-anime-tools",+ "private": true,+ "type": "module",+ "description": "p5 backends invoked only through Ruby Media::Anim",+ "dependencies": {+ "p5": "^2.3.3",+ "puppeteer-core": "^25.12.0"+ }+}diff --git a/skills/make-an-anime/scripts/requirements.txt b/skills/make-an-anime/scripts/requirements.txtnew file mode 100644index 0000000..477f22c--- /dev/null+++ b/skills/make-an-anime/scripts/requirements.txt@@ -0,0 +1,2 @@+numpy>=2.0,<3+Pillow>=11,<13diff --git a/skills/make-an-anime/scripts/spec/anime_spec.rb b/skills/make-an-anime/scripts/spec/anime_spec.rbnew file mode 100644index 0000000..a28d2b1--- /dev/null+++ b/skills/make-an-anime/scripts/spec/anime_spec.rb@@ -0,0 +1,169 @@+require_relative "spec_helper"+require_relative "support/synthetic_anime_fal"+# Anime scene path with deterministic synthetic provider I/O: cast voices -> placed dialogue + per-character mouth tracks ->+# ElevenLabs score -> ducked mix -> shots (H3 with camera + character voice, held still, colour insert) -> 1080p plate.++RSpec.describe "Anime scene pipeline", :media do+ it "voices a cast, ducks the score under it and builds a camera-directed shot edit at 1080p" do+ image = character(file("kf.png"), width: 1920, height: 1080)+ voice = tone(file("voice.wav"), duration: 1.5)+ music = tone(file("music.wav"), duration: 4)+ movie = ff.still_plate(image, music, file("h3.mp4"), seconds: 3, w: 1366, h: 768)+ run = "anime-scene-#{Process.pid}"+ steps = Pipeline::Steps+ stub_const("Pipeline::GENERATIONS", { run => { steps: [steps::Dialogue, steps::Music, steps::Mix, steps::Keyframes, steps::Shots],+ **Pipeline.scene(96), mix: { music_end: 3.5 } } })+ project = Pipeline::Project.new(run)+ prompts = File.join(RT, "prompts", run); FileUtils.mkdir_p(prompts)+ File.write(File.join(prompts, "03_dialogue.yml"), YAML.dump([+ { "name" => "kid", "character" => "kid", "at" => 0.25, "text" => "[sleepy] hello there" },+ { "name" => "narrator", "character" => "dad", "at" => 2.0, "text" => "hello there", "vo" => true }+ ]))+ File.write(File.join(prompts, "03_score.json"), JSON.generate(chunks: [{ text: "[Instrumental]", duration_ms: 3500, positive_styles: ["soft piano"] }]))+ File.write(File.join(prompts, "02_keyframes.yml"), YAML.dump("bed" => { "base" => false, "prompt" => "{{STYLE}} Kid in bed" }))+ File.write(File.join(prompts, "04_shots.yml"), YAML.dump([+ { "name" => "talk", "image" => "bed", "frames" => 48, "audio" => "kid", "prompt" => "{{STYLE}} The kid lifts his head and talks.",+ "camera" => { "move" => "slow dolly-in", "from" => "medium shot", "to" => "medium close-up", "timing" => "0-2s, ease-out" } },+ { "name" => "hold", "still" => "bed", "frames" => 24, "zoom" => [1.0, 1.04] },+ { "name" => "screen", "color" => "#05070a", "frames" => 24 }+ ]))+ client = SyntheticAnimeFal.new(image: image, video: movie, voice: voice, music: music)+ with_workspace do |dir|+ stub_const("Pipeline::ROOT", RT)+ FileUtils.mkdir_p(File.join(RT, "config"))+ cast = File.join(RT, "config", "cast.yml")+ style = File.join(RT, "config", "style.md")+ saved = [cast, style].to_h { [_1, File.file?(_1) ? File.read(_1) : nil] } # RT is the real project: put its files back+ File.write(cast, YAML.dump("kid" => { "voice" => "Jessica", "stability" => 0.35 }, "dad" => { "voice" => "Brian" }))+ File.write(style, "Clean cel-shaded TV anime.")+ begin+ approve+ steps::Dialogue.new(project: project, client: client).run!+ steps::Music.new(project: project, client: client).run!+ steps::Mix.new(project: project, client: client).run!+ steps::Keyframes.new(project: project, client: client).run!+ steps::Shots.new(project: project, client: client).run!+ # A held still or colour insert whose spec changed is rebuilt locally without FORCE.+ File.write(File.join(prompts, "04_shots.yml"), YAML.dump(YAML.load_file(File.join(prompts, "04_shots.yml")).map do |sh|+ { "hold" => sh.merge("frames" => 12), "screen" => sh.merge("frames" => 36, "color" => "#ffffff") }.fetch(sh["name"], sh)+ end))+ steps::Shots.new(project: project, client: client).run!+ screen = project[:shots]["items"]["screen"]["path"]+ @local = [ff.summary(screen).dig(:video, :frames), ff.summary(project[:shots]["items"]["hold"]["path"]).dig(:video, :frames)]+ # A music retake makes the mix stale: Mix rebuilds it without FORCE.+ mix = steps::Mix.new(project: project, client: client)+ @fresh = mix.done?+ File.utime(Time.now - 60, Time.now - 60, project[:mix]["path"])+ @stale = !mix.done?+ mix.run!+ @rebuilt = mix.done?+ # A shaped score set with music_from after gen:music makes the fit stale: Music re-fits from it locally.+ Pipeline::GENERATIONS[run][:music_from] = music+ score = steps::Music.new(project: project, client: client)+ @music_stale = !score.done?+ score.run!+ @refit = [score.done?, project[:music]["endpoint"], mix.done?]+ review = Toolkit::AnimeReview.new(project)+ @timeline, @cam = review.timeline, review.camera+ ensure+ saved.each { |path, body| body ? File.write(path, body) : FileUtils.rm_f(path) }+ end+ end+ tts = client.calls.select { |e, _| e == Fal::Models::ElevenTtsV4.endpoint }+ expect(tts.map { |_, i| i[:voice] }).to eq(%w[Jessica Brian])+ expect(tts.first[1]).to include(stability: 0.35, timestamps: true)+ expect(client.calls.map(&:first)).to include(Fal::Models::ElevenMusic25.endpoint)+ d = project[:dialogue]+ expect(ff.duration(d["path"])).to be_within(0.03).of(4.0)+ expect(d["tracks"].keys).to contain_exactly("kid", "dad")+ words = JSON.parse(File.read(d["words"]))+ expect(words.first).to include("w" => "hello", "s" => 0.35, "character" => "kid")+ # The narrator is voice-over: the dad's mouth track stays silent where his line plays.+ dad = py.audio_energy(ff.to_wav(d["tracks"]["dad"], file("dad.wav")))+ expect(dad["windows"].map { |w| w["rms_db"] }.max).to be < -60+ expect(ff.duration(project[:mix]["path"])).to be_within(0.03).of(4.0)+ expect([@fresh, @stale, @rebuilt]).to eq([true, true, true])+ expect(@music_stale).to be(true)+ expect(@refit).to eq([true, "local:#{music}", false])+ kf = client.calls.find { |e, _| e == Fal::Models::GptImage25Edit.endpoint }+ expect(kf[1][:prompt]).to eq("Clean cel-shaded TV anime. Kid in bed")+ h3 = client.calls.select { |e, _| e.include?("image-to-video") }+ expect(h3.size).to eq(1) # still and colour shots make no model call, also when rebuilt after a spec change+ expect(@local).to eq([36, 12])+ expect(h3.first[1]).to include(resolution: "768P", duration: 2.0)+ expect(h3.first[1][:prompt]).to end_with("Camera: move: slow dolly-in; from: medium shot; to: medium close-up; timing: 0-2s, ease-out")+ expect(h3.first[1][:prompt]).to start_with("Clean cel-shaded TV anime. The kid")+ expect(client.uploads.last).to end_with("04_voice_talk.wav")+ final = ff.summary(project[:shots]["path"])+ expect(final.dig(:video, :frames)).to eq(96)+ expect([final.dig(:video, :w), final.dig(:video, :h)]).to eq([1920, 1080])+ timeline, cam = @timeline, @cam+ expect(timeline).to include(ok: true, frames: 96)+ expect(timeline[:shots].first).to include(shot: "talk", audio: "kid")+ expect(timeline[:shots].first[:lines].first).to start_with("kid ")+ expect(cam.map { _1[:shot] }).to eq(["talk"]) # still and colour shots have no camera to measure+ expect(cam.first).to include(measured: "static (no measurable camera move)", directed: "slow dolly-in")+ expect(cam.first[:hint]).to start_with("MISMATCH")+ end++ it "flags a talking shot whose speaker's line crosses the cut" do+ run = "anime-timeline-#{Process.pid}"+ stub_const("Pipeline::GENERATIONS", { run => { steps: [Pipeline::Steps::Shots], **Pipeline.scene(48) } })+ project = Pipeline::Project.new(run)+ prompts = File.join(RT, "prompts", run); FileUtils.mkdir_p(prompts)+ File.write(File.join(prompts, "04_shots.yml"), YAML.dump([+ { "name" => "a", "image" => "x", "frames" => 24, "audio" => "kid" },+ { "name" => "b", "image" => "x", "frames" => 24, "audio" => "dad" }+ ]))+ File.write(project.path("03_dialogue_lines.json"), JSON.generate([+ { "name" => "kid-line", "character" => "kid", "at" => 0.2, "end" => 1.4 },+ { "name" => "dad-line", "character" => "dad", "at" => 1.5, "end" => 1.9, "vo" => true }+ ]))+ t = Toolkit::AnimeReview.new(project).timeline+ expect(t[:ok]).to be(false)+ expect(t[:issues].join("\n")).to include("kid-line", "crosses", "b: audio dad but none of their on-screen lines")+ expect(t[:shots].first[:min_frames_for_lines]).to eq(40)+ end++ it "measures a push-in and a pan between two frames" do+ with_workspace do+ first = file("cam0.png")+ magick.run("magick", "-seed", "7", "-size", "960x540", "plasma:", "-blur", "0x2", first)+ magick.run("magick", first, "-gravity", "center", "-crop", "800x450+0+0", "+repage", "-resize", "960x540!", file("push.png"))+ magick.run("magick", first, "-crop", "840x540+120+0", "+repage", "-resize", "960x540!", file("pan.png"))+ push = py.camera_motion(first, file("push.png"))+ expect(push["zoom"]).to be_within(0.03).of(1.2)+ expect(push["camera"]).to start_with("push-in")+ pan = py.camera_motion(first, file("pan.png"))+ expect(pan["camera"]).to include("pan right")+ end+ end++ it "parses ElevenLabs character alignment into word cues and strips audio tags for review" do+ words = Pipeline::Steps::Dialogue.words({ "characters" => "Hi you".chars,+ "character_start_times_seconds" => [0, 0.1, 0.2, 0.3, 0.4, 0.5],+ "character_end_times_seconds" => [0.1, 0.2, 0.3, 0.4, 0.5, 0.6] })+ expect(words).to eq([{ "w" => "Hi", "s" => 0.0, "e" => 0.2 }, { "w" => "you", "s" => 0.3, "e" => 0.6 }])+ expect(Pipeline::Steps::Dialogue.spoken("[sleepy] Papa… are you making a game?")).to eq(%w[papa are you making a game])+ # A doubled phrase is extra even though each word is in the script.+ d = Pipeline::Steps::Dialogue+ want = d.spoken("Software should be free — free as in freedom.")+ expect(d.word_diff(want, d.spoken("Software should be free. Software should be free — free as in freedom."))).to eq([[], %w[software should be free]])+ expect(d.word_diff(want, d.spoken("Software should be free as in freedom"))).to eq([%w[free], []])+ end++ it "joins streamed alignment chunks that split a word" do+ chunk = ->(chars, t0) { { "characters" => chars, "character_start_times_seconds" => chars.each_index.map { t0 + _1 * 0.1 },+ "character_end_times_seconds" => chars.each_index.map { t0 + _1 * 0.1 + 0.1 } } }+ words = Pipeline::Steps::Dialogue.words([chunk.(["G", "o", " ", "M"], 0.0), chunk.(["i", "n", "e"], 0.4)])+ expect(words.map { _1["w"] }).to eq(%w[Go Mine])+ expect(words.last).to include("s" => be_within(1e-9).of(0.3), "e" => be_within(1e-9).of(0.7))+ end++ it "drops performed audio tags and punctuation-only tokens from subtitle cues" do+ words = [["[sleepy,", 0, 0.14], ["mumbling]", 0.16, 0.22], ["Papa", 0.24, 0.8], ["…", 0.8, 1.28], ["game?", 2.4, 3.04], ["[laughs]Ok", 3.1, 3.4]]+ .map { |w, s, e| { "w" => w, "s" => s, "e" => e } }+ expect(Pipeline::Steps::Dialogue.spoken_words(words).map { _1["w"] }).to eq(["Papa", "game?", "Ok"])+ end++enddiff --git a/skills/make-an-anime/scripts/spec/core_spec.rb b/skills/make-an-anime/scripts/spec/core_spec.rbnew file mode 100644index 0000000..920c5e5--- /dev/null+++ b/skills/make-an-anime/scripts/spec/core_spec.rb@@ -0,0 +1,176 @@+require_relative "spec_helper"+RSpec.describe "Skill contracts and Ruby entry", :core do+ it "loads valid metadata and resolves every bundled Markdown reference" do+ skill = File.read(File.join(SKILL, "SKILL.md"))+ front = YAML.safe_load(skill.split("---", 3)[1])+ expect(front.fetch("name")).to eq("make-an-anime")+ expect(front.fetch("description").length).to be > 30+ Dir[File.join(SKILL, "**", "*.md")].reject { |p| p.include?("node_modules") || p.include?("/tmp/") }.each do |path|+ File.read(path).scan(/\[[^\]]*\]\(([^)]+)\)/).flatten.each do |target|+ next if target.start_with?("https:", "http:", "#")+ expect(File.exist?(File.expand_path(target.split("#").first, File.dirname(path)))).to be(true), "Broken reference #{target} in #{path}"+ end+ end+ end+ it "shows help without credentials and lists executable tasks" do+ out, err, status = cli("--help", env: {"FAL_AI_API_KEY" => ""})+ expect(status.exitstatus).to eq(0), err+ expect(out).to include("--project", "Exit:")+ out, err, status = cli("-T")+ expect(status.exitstatus).to eq(0), err+ expect(out).to include("gen:ref_base", "media:mouth", "vfx:render", "test")+ end+ it "rejects incomplete intake without prompting or overwriting an existing project" do+ _, _, status = cli("init")+ expect(status.exitstatus).to eq(2)+ File.write(file("song.wav"), "fixture"); File.write(file("brief.md"), "Dancing robot")+ dir = file("project")+ out, err, status = cli("init", "--project", dir, "--song", file("song.wav"), "--prompt-file", file("brief.md"))+ expect(status.exitstatus).to eq(0), err+ expect(JSON.parse(out)["project"]).to eq(dir)+ expect(File.read(File.join(dir, "docs/BRIEF.md"))).to eq("Dancing robot")+ _, _, status = cli("init", "--project", dir, "--song", file("song.wav"), "--prompt-file", file("brief.md"))+ expect(status.exitstatus).to eq(2)+ end+ it "executes shell arguments literally, including spaces and shell metacharacters" do+ dangerous = "a path; $(touch SHOULD_NOT_EXIST) `x`"+ out = Media::Shell.new.run(RbConfig.ruby, "-e", "print ARGV.fetch(0)", dangerous, quiet: true)+ expect(out).to eq(dangerous)+ expect(File.exist?("SHOULD_NOT_EXIST")).to be(false)+ end+ it "surfaces a backend failure" do+ expect { Media::Shell.new.run(RbConfig.ruby, "-e", "STDERR.puts 'fixture failure'; exit 9", quiet: true) }.to raise_error(Media::CommandError, /fixture failure/)+ end+ it "invalidates approval when the creative plan changes" do+ with_workspace do+ expect { Workflow::Approval.new.check! }.to raise_error(/approval missing/)+ approve+ expect(Workflow::Approval.new.check!).to be(true)+ File.write("docs/PLAN.md", "Different cast and story")+ expect { Workflow::Approval.new.check! }.to raise_error(/Plan changed/)+ end+ end+ it "reads and records UTF-8 approval files independently of the locale" do+ with_workspace do+ approve+ File.write("docs/PLAN.md", "Bloom — 音楽", encoding: "UTF-8")+ note = "Approve wave 2 — café / 音楽"+ Workflow::Approval.new.record!(note)+ script = <<~RUBY+ # encoding: UTF-8+ require #{File.join(RT, "lib/workflow/approval").inspect}+ abort "Expected US-ASCII" unless Encoding.default_external == Encoding::US_ASCII+ approval = Workflow::Approval.new+ approval.check!+ approval.record!(#{note.inspect})+ approval.check!+ RUBY+ _, err, status = Open3.capture3({"LC_ALL" => "C", "LANG" => "C"}, RbConfig.ruby, "-EUS-ASCII", "-e", script)+ expect(status.success?).to be(true), err+ expect(JSON.parse(File.read("config/approval.json", encoding: "UTF-8"))["user_approval"]).to eq(note)+ end+ end+ it "allocates reviewed dependency waves 2,4,8,10,10 and resumes an active wave" do+ with_workspace do+ FileUtils.mkdir_p("config")+ jobs = 34.times.map { |i| {id: "j#{i}", run: "r#{i}", state: "pending", depends: []} }+ json("config/production.json", wave: 0, jobs: jobs)+ waves = Workflow::Waves.new+ File.write("review.md", "Reviewed fixture output")+ [2, 4, 8, 10, 10].each do |count|+ result = waves.next!+ expect(result[:jobs].size).to eq(count)+ expect(waves.next![:jobs]).to eq(result[:jobs])+ result[:jobs].each { |j| waves.accept!(j["id"], "review.md") }+ end+ expect(waves.next![:complete]).to be(true)+ end+ end+ it "waits for dependencies, prevents shared run ownership and detects cycles" do+ with_workspace do+ FileUtils.mkdir_p("config")+ json("config/production.json", jobs: [{id: "a", run: "shared"}, {id: "b", run: "shared"}, {id: "c", depends: ["a"]}])+ result = Workflow::Waves.new.next!+ expect(result[:jobs].map { |j| j["id"] }).to eq(["a"])+ json("config/production.json", jobs: [{id: "a", depends: ["b"]}, {id: "b", depends: ["a"]}])+ expect { Workflow::Waves.new.next! }.to raise_error(/No jobs ready/)+ end+ end+ it "refuses noncontiguous section assembly before touching media" do+ stub_const("Pipeline::GENERATIONS", {+ "test-a" => {steps: [], **Pipeline.section(0, 24)},+ "test-b" => {steps: [], **Pipeline.section(25, 24)}+ })+ expect { Toolkit::Operations.new.preview(file("out.mp4"), %w[test-a test-b]) }.to raise_error(/Noncontiguous/)+ end+end++RSpec.describe "Fal HTTP and model contracts", :core do+ it "caches CDN upload URLs by bytes and downloads real response bytes" do+ with_workspace do+ File.write("image.png", "test image bytes")+ Excon.defaults[:mock] = true+ calls = 0+ Excon.stub({method: :post, host: "rest.alpha.fal.ai"}) do+ calls += 1+ {status:200, body: JSON.generate(upload_url:"https://upload.test/file",file_url:"https://cdn.test/file")}+ end+ Excon.stub({method: :put, host:"upload.test"},{status:200,body:""})+ Excon.stub({method: :get, host:"cdn.test"},{status:200,body:"downloaded bytes"})+ client = Fal::Client.new(api_key:"fixture")+ expect(client.upload("image.png")).to eq("https://cdn.test/file")+ expect(client.upload("image.png")).to eq("https://cdn.test/file")+ expect(calls).to eq(1)+ client.download("https://cdn.test/file","download.png")+ expect(File.read("download.png")).to eq("downloaded bytes")+ end+ end+ it "keeps the receipt after a polling interruption and recovers without another POST" do+ with_workspace do+ approve+ client = Fal::Client.new(api_key:"fixture")+ expect(client).to receive(:submit).once.and_return({"request_id"=>"resume-1","status_url"=>"status","response_url"=>"result"})+ allow(client).to receive(:wait).and_raise(Fal::Error,"timeout")+ expect { client.run("test/endpoint",{prompt:"once"}) }.to raise_error(Fal::Error,/timeout/)+ allow(client).to receive(:wait).and_return(true)+ allow(client).to receive(:get_json).with("result").and_return({"ok"=>true})+ expect(client.run("test/endpoint",{prompt:"once"})).to eq(["resume-1",{"ok"=>true}])+ end+ end+ it "submits, polls, fetches and resumes identical paid requests without resubmitting" do+ with_workspace do+ approve+ Excon.defaults[:mock] = true+ submitted = []+ Excon.stub({method: :post, host: "queue.fal.run"}) do |req|+ submitted << JSON.parse(req[:body])+ {status: 200, body: JSON.generate(request_id: "job-1", status_url: "https://queue.fal.run/status", response_url: "https://queue.fal.run/result")}+ end+ Excon.stub({method: :get, path: "/status"}, {status: 200, body: '{"status":"COMPLETED"}'})+ Excon.stub({method: :get, path: "/result"}, {status: 200, body: '{"images":[{"url":"https://cdn.test/image.png"}]}'})+ client = Fal::Client.new(api_key: "test-only", poll_interval: 0)+ 2.times { expect(Fal::Models::GptImage25.new(client: client).generate(prompt: "fixture").request_id).to eq("job-1") }+ expect(submitted.size).to eq(1)+ expect(submitted.first).to include("quality" => "xhigh", "output_format" => "png")+ expect(Dir["output/requests/*.json"].size).to eq(1)+ end+ end+ it "validates endpoint inputs against a saved schema before submission" do+ with_workspace do+ path = Fal::OpenAPI.spec_path(Fal::Models::H3MaxImageToVideo.endpoint)+ json(path, components: {schemas: {Input: {required: ["prompt"], properties: {prompt: {type: "string"}, resolution: {enum: ["1080P"]}}}}})+ client = double("no network")+ expect(client).not_to receive(:run)+ expect { Fal::Models::H3MaxImageToVideo.new(client: client).animate(prompt: "x", image_url: "https://test/image", duration: 5, resolution: "bad") }.to raise_error(ArgumentError)+ end+ end+ it "surfaces terminal queue errors and never calls a paid endpoint before approval" do+ with_workspace do+ client = Fal::Client.new(api_key: "test-only", poll_interval: 0)+ expect(client).not_to receive(:submit)+ expect { client.run("test/model", {}) }.to raise_error(/approval missing/)+ allow(client).to receive(:get_json).and_return({"status" => "COMPLETED", "error" => "generation rejected"})+ expect { client.wait("https://test/status") }.to raise_error(Fal::Error, /generation rejected/)+ end+ end+enddiff --git a/skills/make-an-anime/scripts/spec/credentials_spec.rb b/skills/make-an-anime/scripts/spec/credentials_spec.rbnew file mode 100644index 0000000..8afd161--- /dev/null+++ b/skills/make-an-anime/scripts/spec/credentials_spec.rb@@ -0,0 +1,196 @@+require_relative "spec_helper"+require_relative "../lib/toolkit/mcp_server"+require "stringio"+require "timeout"++RSpec.describe "Configured Fal credentials and MCP delivery", :core do+ def prepared_project+ project = file("video project")+ FileUtils.mkdir_p(File.join(project, "config"))+ json(File.join(project, "config/project.json"), fps: 24)+ project+ end++ def task_runner(api_key: "test-only-secret")+ entry = file("server/fixture.rb")+ FileUtils.mkdir_p(File.dirname(entry))+ File.write(entry, <<~'RUBY')+ require "json"+ require "digest"+ task = ARGV.last+ if ENV["RUN"] == "utf8"+ puts JSON.generate(encoding: Encoding.default_external.name,+ approval: JSON.parse(File.read("config/approval.json"))["user_approval"])+ end+ if ENV["RUN"] == "wait"+ $stdout.sync = true+ puts "waiting"+ sleep 30+ end+ puts JSON.generate(key_digest: Digest::SHA256.hexdigest(ENV.fetch("FAL_AI_API_KEY", "")), task: task, run: ENV["RUN"], cwd: Dir.pwd)+ exit 7 if ENV["RUN"] == "fail"+ RUBY+ @runner = Toolkit::CredentialTasks.new(entry: entry, api_key: api_key)+ end++ def wait_for_job(runner, id)+ Timeout.timeout(5) do+ loop do+ value = runner.status(id)+ return value unless value[:state] == "running"+ sleep 0.01+ end+ end+ end++ after { @runner&.close }++ it "uses only explicit credentials or FAL_AI_API_KEY, with no key-file lookup" do+ ENV.delete("FAL_AI_API_KEY")+ ENV["FAL_KEY"] = "obsolete-test-key"+ expect(File).not_to receive(:read)+ expect { Fal::Client.new }.to raise_error(Fal::Error, /Missing FAL_AI_API_KEY/)+ ENV["FAL_AI_API_KEY"] = "configured-test-key"+ expect { Fal::Client.new }.not_to raise_error+ ENV["FAL_AI_API_KEY"] = " "+ expect { Fal::Client.new }.to raise_error(Fal::Error, /Missing FAL_AI_API_KEY/)+ expect { Fal::Client.new(api_key: "explicit-test-key") }.not_to raise_error+ end++ it "sends the configured value only to the toolkit child and preserves literal arguments" do+ ENV["RUN"] = "unrelated-parent-value"+ runner = task_runner+ project = prepared_project+ id = runner.start(project: project, task: "doctor")[:job_id]+ result = wait_for_job(runner, id)+ expect(result[:state]).to eq("completed")+ output = JSON.parse(result[:output])+ expect(output).to include("key_digest" => Digest::SHA256.hexdigest("test-only-secret"), "cwd" => project, "run" => nil)+ expect(result.to_json).not_to include("test-only-secret")+ expect(runner.redact("failure: test-only-secret")).to eq("failure: [REDACTED]")+ end++ it "rejects secret overrides, arbitrary tasks and uninitialized projects" do+ runner = task_runner+ project = prepared_project+ expect { runner.start(project: project, task: "doctor", options: {"FAL_AI_API_KEY" => "override"}) }.to raise_error(ArgumentError)+ expect { runner.start(project: project, task: "doctor; echo unexpected") }.to raise_error(ArgumentError)+ expect { runner.start(project: project, task: "setup") }.to raise_error(ArgumentError)+ expect { runner.start(project: fixtures, task: "doctor") }.to raise_error(ArgumentError)+ expect { runner.start(project: project, task: "doctor", options: {"RUN" => 2}) }.to raise_error(ArgumentError)+ end++ it "checks plan approval before passing the credential to an upload or generation task" do+ runner = task_runner+ project = prepared_project+ task = "media:upload[art with spaces.png]"+ expect { runner.start(project: project, task: task) }.to raise_error(/approval missing/i)+ FileUtils.mkdir_p(File.join(project, "docs"))+ File.write(File.join(project, "docs/PLAN.md"), "Mocked approval gate test")+ Workflow::Approval.new(root: project).record!("Test fixture consent")+ result = wait_for_job(runner, runner.start(project: project, task: task)[:job_id])+ expect(JSON.parse(result[:output])["task"]).to eq(task)+ File.write(File.join(project, "docs/PLAN.md"), "Changed")+ expect { runner.start(project: project, task: task) }.to raise_error(/Plan changed/)+ end++ it "reports missing configuration without exposing a placeholder as a real key" do+ runner = task_runner(api_key: "${user_config.FAL_AI_API_KEY}")+ expect(runner.configured?).to be(false)+ expect { runner.start(project: prepared_project, task: "gen:ref_base") }.to raise_error(/Configure the plugin/)+ result = wait_for_job(runner, runner.start(project: prepared_project, task: "doctor")[:job_id])+ expect(JSON.parse(result[:output])["key_digest"]).to eq(Digest::SHA256.hexdigest(""))+ end++ it "preserves UTF-8 approval, MCP arguments and worker output under a US-ASCII locale" do+ task_runner+ project = prepared_project + " — café"+ FileUtils.mv(prepared_project, project)+ FileUtils.mkdir_p(File.join(project, "docs"))+ File.write(File.join(project, "docs/PLAN.md"), "Bloom — 音楽", encoding: "UTF-8")+ note = "Approve wave 2 — café / 音楽"+ Workflow::Approval.new(root: project).record!(note)+ server = file("ascii_server.rb")+ File.write(server, <<~RUBY)+ require #{File.join(RT, "lib/toolkit/mcp_server").inspect}+ abort "Expected US-ASCII" unless Encoding.default_external == Encoding::US_ASCII+ tasks = Toolkit::CredentialTasks.new(entry: #{file("server/fixture.rb").inspect}, api_key: "fixture-only")+ Toolkit::McpServer.new(tasks: tasks).run+ RUBY+ task = "media:upload[art — café.png]"+ Open3.popen3({"LC_ALL" => "C", "LANG" => "C"}, RbConfig.ruby, "-EUS-ASCII", server) do |input, output, errors, waiter|+ rpc = lambda do |name, arguments|+ input.puts(JSON.generate(jsonrpc: "2.0", id: 1, method: "tools/call", params: {name: name, arguments: arguments}))+ input.flush+ response = JSON.parse(output.gets)+ expect(response).not_to have_key("error")+ expect(response.dig("result", "isError")).not_to be(true)+ JSON.parse(response.dig("result", "content", 0, "text"))+ end+ Timeout.timeout(5) do+ id = rpc.call("run_task", {project: project, task: task, options: {RUN: "utf8"}}).fetch("job_id")+ loop do+ result = rpc.call("task_status", {job_id: id})+ if result["state"] != "running"+ expect(result["state"]).to eq("completed")+ lines = result.fetch("output").lines.map { |line| JSON.parse(line) }+ expect(lines.first).to eq("encoding" => "UTF-8", "approval" => note)+ expect(lines.last).to include("task" => task, "cwd" => project)+ break+ end+ sleep 0.01+ end+ end+ ensure+ input.close unless input.closed?+ expect(errors.read).to eq("")+ expect(waiter.value.success?).to be(true)+ end+ end++ it "prefers the plugin option and falls back to an exported key when it is unset" do+ plugin = Toolkit::CredentialTasks::PLUGIN_KEY+ expect(Toolkit::CredentialTasks.env_key(plugin => "plugin-key", "FAL_AI_API_KEY" => "shell-key")).to eq("plugin-key")+ expect(Toolkit::CredentialTasks.env_key(plugin => "", "FAL_AI_API_KEY" => "shell-key")).to eq("shell-key")+ expect(Toolkit::CredentialTasks.env_key(plugin => "${user_config.FAL_AI_API_KEY}", "FAL_AI_API_KEY" => "shell-key")).to eq("shell-key")+ expect(Toolkit::CredentialTasks.env_key(plugin => "")).to eq("")+ end++ it "keeps simultaneous job options separate and reports task failure" do+ runner = task_runner+ project = prepared_project+ ids = %w[first fail].map { |run| runner.start(project: project, task: "doctor", options: {"RUN" => run})[:job_id] }+ results = ids.map { |id| wait_for_job(runner, id) }+ expect(results.map { |r| JSON.parse(r[:output])["run"] }).to eq(%w[first fail])+ expect(results.map { |r| r[:exit_code] }).to eq([0, 7])+ expect(results.last[:state]).to eq("failed")+ end++ it "cancels the local worker while explaining that submitted Fal work is separate" do+ runner = task_runner+ id = runner.start(project: prepared_project, task: "doctor", options: {"RUN" => "wait"})[:job_id]+ result = runner.cancel(id)+ expect(result[:state]).to eq("cancelled")+ expect(result[:note]).to include("may still run and incur charges")+ end++ it "speaks newline-delimited MCP and keeps credentials out of tool metadata and errors" do+ runner = task_runner+ messages = [+ {jsonrpc: "2.0", id: 1, method: "initialize", params: {protocolVersion: "2025-11-25"}},+ {jsonrpc: "2.0", method: "notifications/initialized"},+ {jsonrpc: "2.0", id: 2, method: "tools/list"},+ {jsonrpc: "2.0", id: 3, method: "tools/call", params: {name: "credential_status", arguments: {}}},+ {jsonrpc: "2.0", id: 4, method: "tools/call", params: {name: "task_status", arguments: {job_id: "unknown"}}}+ ]+ output = StringIO.new+ Toolkit::McpServer.new(input: StringIO.new(messages.map { |m| JSON.generate(m) }.join("\n") + "\n"), output: output, tasks: runner).run+ responses = output.string.lines.map { |line| JSON.parse(line) }+ expect(responses.map { |r| r["id"] }).to eq([1, 2, 3, 4])+ expect(responses.first.dig("result", "protocolVersion")).to eq("2025-11-25")+ expect(responses[1].dig("result", "tools").map { |t| t["name"] }).to include("run_task", "task_status")+ expect(JSON.parse(responses[2].dig("result", "content", 0, "text"))).to eq("configured" => true)+ expect(responses[3].dig("result", "isError")).to be(true)+ expect(output.string).not_to include("test-only-secret")+ end+enddiff --git a/skills/make-an-anime/scripts/spec/episode_spec.rb b/skills/make-an-anime/scripts/spec/episode_spec.rbnew file mode 100644index 0000000..023fbe1--- /dev/null+++ b/skills/make-an-anime/scripts/spec/episode_spec.rb@@ -0,0 +1,141 @@+require_relative "spec_helper"++RSpec.describe "Episode tools: modular generations and scene scaffold", :core do+ it "merges config/generations.rb with config/generations/*.rb and rejects a run defined twice" do+ Dir.mktmpdir("gen-") do |root|+ FileUtils.mkdir_p(File.join(root, "config", "generations"))+ File.write(File.join(root, "config", "generations.rb"), %({ "char-a" => { steps: [Steps::RefBase] } }))+ File.write(File.join(root, "config", "generations", "ep01-s02.rb"), %({ "ep01-s02" => { steps: [Steps::Shots], **scene(48) } }))+ runs = Pipeline::GenerationConfig.new(root).load+ expect(runs.keys).to eq(%w[char-a ep01-s02])+ expect(runs["ep01-s02"]).to include(frames: 48, steps: [Pipeline::Steps::Shots])+ File.write(File.join(root, "config", "generations", "dup.rb"), %({ "char-a" => {} }))+ expect { Pipeline::GenerationConfig.new(root).load }.to raise_error(ArgumentError, /char-a is defined in both/)+ end+ end++ it "scaffolds a scene whose generation, shot frames and score length agree, and never overwrites" do+ Dir.mktmpdir("scene-") do |root|+ episode = Toolkit::Episode.new(root: root)+ out = episode.scaffold("ep01-s02", 480)+ expect(out[:seconds]).to eq(20.0)+ gen = Pipeline::GenerationConfig.new(root).load.fetch("ep01-s02")+ expect(gen[:frames]).to eq(480)+ expect(gen[:mix][:music_end]).to eq(20.0)+ shots = YAML.safe_load_file(File.join(root, "prompts", "ep01-s02", "04_shots.yml"))+ expect(shots.sum { _1["frames"] }).to eq(480)+ score = JSON.parse(File.read(File.join(root, "prompts", "ep01-s02", "03_score.json")))+ expect(score["chunks"].sum { _1["duration_ms"] }).to eq(20_000)+ expect(YAML.safe_load_file(File.join(root, "prompts", "ep01-s02-sfx", "sfx.yml"))["out"]).to eq("output/ep01-s02/final_sfx.mp4")+ expect { episode.scaffold("ep01-s02", 480) }.to raise_error(ArgumentError, /already exists/)+ expect(episode.runs_for("ep01")).to eq(["ep01-s02"])+ end+ end++ it "plays scenes in the order of config/episodes/<prefix>.yml when it exists" do+ Dir.mktmpdir("order-") do |root|+ FileUtils.mkdir_p(File.join(root, "config", "episodes"))+ File.write(File.join(root, "config", "episodes", "ep01.yml"), %w[ep01-s02 ep01-s04 ep01-s03].to_yaml)+ expect(Toolkit::Episode.new(root: root).runs_for("ep01")).to eq(%w[ep01-s02 ep01-s04 ep01-s03])+ end+ end+end++RSpec.describe "Prompt YAML with the style bible", :core do+ it "expands {{STYLE}} after parsing, so a style with quotes and colons cannot break a quoted scalar" do+ Dir.mktmpdir("style-") do |root|+ stub_const("Pipeline::ROOT", root)+ FileUtils.mkdir_p([File.join(root, "config"), File.join(root, "prompts", "ep01-s09")])+ File.write(File.join(root, "config", "style.md"), "Keep the real person's likeness: cel shading, no text.")+ # A single-quoted scalar (what Psych writes for text with double quotes) broke when the raw file was expanded.+ File.write(File.join(root, "prompts", "ep01-s09", "02_keyframes.yml"), "k:\n prompt: '{{STYLE}} The boy''s snack \"thanks\"'\n")+ step = Pipeline::Steps::Keyframes.new(project: Pipeline::Project.new("ep01-s09"))+ expect(step.send(:yaml, "02_keyframes")["k"]["prompt"]).to eq(%(Keep the real person's likeness: cel shading, no text. The boy's snack "thanks"))+ end+ end+end++RSpec.describe "Episode preview", :media do+ it "joins each scene's most finished file in order and reports a scene with no final" do+ Dir.mktmpdir("ep-") do |root|+ a = File.join(root, "output", "ep01-s01"); b = File.join(root, "output", "ep01-s02")+ FileUtils.mkdir_p([a, b, File.join(root, "prompts", "ep01-s01"), File.join(root, "prompts", "ep01-s02")])+ img = character(file("ep.png"), width: 320, height: 180)+ ff.still_plate(img, tone(file("ep1.wav"), duration: 1), File.join(a, "final_overlay.mp4"), seconds: 1, w: 320, h: 180)+ ff.still_plate(img, tone(file("ep2.wav"), duration: 2), File.join(a, "final_sfx.mp4"), seconds: 2, w: 320, h: 180)+ episode = Toolkit::Episode.new(root: root)+ expect { episode.preview("output/p.mp4", ["ep01"]) }.to raise_error(ArgumentError, /ep01-s02/)+ quiet = ff.run("ffmpeg", "-y", "-v", "error", "-i", tone(file("ep3.wav"), duration: 1), "-af", "volume=-10dB", file("ep3q.wav"), quiet: true) && file("ep3q.wav")+ ff.still_plate(img, quiet, File.join(b, "final.mp4"), seconds: 1, w: 320, h: 180)+ out = episode.preview("output/p.mp4", ["ep01"])+ expect(out[:scenes].map { _1[:file] }).to eq(["output/ep01-s01/final_sfx.mp4", "output/ep01-s02/final.mp4"])+ expect(out[:seconds]).to be_within(0.1).of(3.0)+ # Each scene is moved to -23 LUFS: the 10 dB quieter scene gets ~10 dB more gain.+ out[:scenes].each { |sc| expect(sc[:lufs] + sc[:gain_db]).to be_within(0.5).of(-23.0) }+ expect(out[:scenes][1][:gain_db] - out[:scenes][0][:gain_db]).to be_within(1.5).of(10.0)+ expect(ff.loudness(File.join(root, "output", "p_leveled", "ep01-s02.mp4"))[:lufs]).to be_within(1.0).of(-23.0)++ # VFX beats in scene frames land on film frames, and `end` is the cut into the next scene.+ FileUtils.mkdir_p(File.join(root, "prompts", "ep01-vfx"))+ File.write(File.join(root, "prompts", "ep01-vfx", "beats.yml"), YAML.dump(+ "episode" => "ep01", "source" => "a.mp4", "out" => "b.mp4",+ "beats" => [{ "run" => "ep01-s02", "f" => 3, "fx" => "punch", "dur" => 2 }, { "run" => "ep01-s01", "f" => "end", "fx" => "dark", "dur" => 2 }]+ ))+ episode.vfx_cues("ep01-vfx")+ first = ff.summary(File.join(a, "final_sfx.mp4")).dig(:video, :frames)+ cues = YAML.safe_load_file(File.join(root, "prompts", "ep01-vfx", "cues.yml"))["cues"]+ expect(cues.map { _1["f"] }).to eq([first + 3, first])+ end+ end++ it "levels a scene with speech by its voices, and one without by its loudness" do+ Dir.mktmpdir("voice-") do |root|+ a = File.join(root, "output", "ep01-s01"); b = File.join(root, "output", "ep01-s02")+ FileUtils.mkdir_p([a, b, File.join(root, "prompts", "ep01-s01"), File.join(root, "prompts", "ep01-s02")])+ img = character(file("v.png"), width: 320, height: 180)+ ff.still_plate(img, tone(file("v1.wav"), duration: 2), File.join(a, "final_sfx.mp4"), seconds: 2, w: 320, h: 180)+ ff.still_plate(img, tone(file("v2.wav"), duration: 2), File.join(b, "final_sfx.mp4"), seconds: 2, w: 320, h: 180)+ File.write(File.join(a, "03_dialogue_lines.json"), JSON.generate([{ "at" => 0.2, "end" => 1.8, "vo" => true }]))+ out = Toolkit::Episode.new(root: root).preview("output/p.mp4", ["ep01"], voice_db: -24.0)+ with, without = out[:scenes]+ expect(with[:speech_db] + with[:gain_db]).to be_within(0.5).of(-24.0)+ expect(without[:speech_db]).to be_nil+ expect(without[:lufs] + without[:gain_db]).to be_within(0.5).of(-23.0)+ end+ end++ it "fades each scene's track around its voices, leaves the film's ends and a silent card alone, and ignores laughs and thoughts when levelling" do+ Dir.mktmpdir("seam-") do |root|+ runs = %w[ep01-s01 ep01-s02 ep01-s03 ep01-s04]+ dirs = runs.map { File.join(root, "output", _1) }+ FileUtils.mkdir_p(dirs + runs.map { File.join(root, "prompts", _1) })+ img = character(file("s.png"), width: 320, height: 180)+ silence = file("s_silence.wav")+ ff.run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "anullsrc=r=44100:cl=stereo", "-t", "2", silence, quiet: true)+ ff.still_plate(img, silence, File.join(dirs[0], "final_sfx.mp4"), seconds: 2, w: 320, h: 180)+ dirs[1..2].each_with_index { |dir, i| ff.still_plate(img, tone(file("s#{i}.wav"), duration: 4), File.join(dir, "final_sfx.mp4"), seconds: 4, w: 320, h: 180) }+ ff.still_plate(img, tone(file("s9.wav"), duration: 2), File.join(dirs[3], "final_sfx.mp4"), seconds: 2, w: 320, h: 180)+ File.write(File.join(dirs[1], "03_dialogue_lines.json"), JSON.generate([+ { "at" => 1.0, "end" => 2.0 }, { "at" => 2.0, "end" => 2.5, "subtitle" => " " }, { "at" => 2.5, "end" => 3.0, "vo" => true, "inner" => true }+ ]))+ out = Toolkit::Episode.new(root: root).preview("output/p.mp4", ["ep01"], voice_db: -24.0, seams: true)+ card, spoken, plain, ending = out[:scenes]+ expect(card[:gain_db]).to eq(0.0)+ expect(card[:fade_in]).to be_nil+ expect(spoken[:fade_out]).to be_within(0.01).of(0.88) # the air after the last line, kept 0.12 s off it+ expect(spoken[:speech_db]).not_to be_nil+ expect(plain[:fade_out]).to eq(1.4)+ expect(ending[:fade_out]).to eq(0)+ end+ end++ it "rings a score out past its end without touching what comes before, and keeps a mix without the voice lift" do+ music = tone(file("ring.wav"), duration: 3)+ out = ff.ring_out(music, file("ring_out.wav"), tail: 1.5)+ expect(ff.duration(out)).to be_within(0.05).of(4.5)+ voice = tone(file("voice.wav"), duration: 1)+ plain = ff.duck_mix(music, voice, file("plain.wav"), seconds: 3, duck: false, music_db: -60, dialogue_db: 0)+ lifted = ff.duck_mix(music, voice, file("lift.wav"), seconds: 3, duck: false, music_db: -60, dialogue_db: 6)+ expect(ff.loudness(lifted)[:lufs]).to be > ff.loudness(plain)[:lufs] + 3+ end+enddiff --git a/skills/make-an-anime/scripts/spec/fonts_spec.rb b/skills/make-an-anime/scripts/spec/fonts_spec.rbnew file mode 100644index 0000000..d24abae--- /dev/null+++ b/skills/make-an-anime/scripts/spec/fonts_spec.rb@@ -0,0 +1,39 @@+require_relative "spec_helper"++RSpec.describe Toolkit::Fonts, :core do+ subject(:fonts) { described_class.new }++ it "discovers supported font files recursively, ignoring collections and missing roots" do+ root = file("installed")+ FileUtils.mkdir_p(File.join(root, "Supplemental"))+ %w[face.TTF face.otf collection.ttc notes.txt].each { |name| File.write(File.join(root, "Supplemental", name), name) }+ expect(fonts.list([root, file("missing")]).map { |path| File.basename(path) }).to eq(%w[face.TTF face.otf])+ end++ it "copies only selected files unchanged, accepts spaces and commas, and allows identical reruns" do+ source = file("Selected face,variable.ttf")+ File.binwrite(source, "\x00\x01font bytes")+ File.write(file("unused.ttf"), "unused")+ json(file("fonts.json"), "title.ttf" => source)+ project = file("video project")+ result = fonts.copy(file("fonts.json"), project: project)+ expect(File.binread(result.first[:path])).to eq(File.binread(source))+ expect(result.first[:sha256]).to eq(Digest::SHA256.file(source).hexdigest)+ expect(Dir.children(File.join(project, "tools/p5/fonts"))).to eq(["title.ttf"])+ expect(fonts.copy(file("fonts.json"), project: project)).to eq(result)+ File.write(source, "replacement")+ expect { fonts.copy(file("fonts.json"), project: project) }.to raise_error(ArgumentError, /different bytes/)+ expect(File.binread(result.first[:path])).to eq("\x00\x01font bytes")+ end++ it "validates all selections before copying and rejects paths outside the font directory" do+ source = file("font.ttf")+ File.write(source, "font bytes")+ project = file("project")+ json(file("fonts.json"), "valid.ttf" => source, "missing.ttf" => file("absent.ttf"))+ expect { fonts.copy(file("fonts.json"), project: project) }.to raise_error(ArgumentError, /Missing/)+ expect(File.exist?(File.join(project, "tools/p5/fonts/valid.ttf"))).to be(false)+ json(file("fonts.json"), "../escape.ttf" => source)+ expect { fonts.copy(file("fonts.json"), project: project) }.to raise_error(ArgumentError, /without directories/)+ end+enddiff --git a/skills/make-an-anime/scripts/spec/journal_spec.rb b/skills/make-an-anime/scripts/spec/journal_spec.rbnew file mode 100644index 0000000..b6f2172--- /dev/null+++ b/skills/make-an-anime/scripts/spec/journal_spec.rb@@ -0,0 +1,17 @@+require_relative "spec_helper"++RSpec.describe "Sub-agent progress journal", :core do+ it "keeps separate worker histories and returns bounded, attributable updates" do+ with_workspace do+ journal = Workflow::Journal.new("logs")+ 7.times { |n| journal.append(agent: "scene-a", event: "progress", message: "step #{n}") }+ journal.append(agent: "scene-b", event: "submitted", message: "night scene", request_id: "fake-123")+ snapshot = journal.snapshot(limit: 2)+ expect(snapshot.map { |row| row[:agent] }).to eq(%w[scene-a scene-b])+ expect(snapshot.first[:entries].map { |row| row["message"] }).to eq(["step 5", "step 6"])+ expect(snapshot.last[:entries].first["request_id"]).to eq("fake-123")+ expect(File.readlines("logs/scene-a.jsonl").size).to eq(7)+ expect { journal.append(agent: "../escape", event: "bad", message: "bad") }.to raise_error(ArgumentError)+ end+ end+enddiff --git a/skills/make-an-anime/scripts/spec/live_spec.rb b/skills/make-an-anime/scripts/spec/live_spec.rbnew file mode 100644index 0000000..607835a--- /dev/null+++ b/skills/make-an-anime/scripts/spec/live_spec.rb@@ -0,0 +1,60 @@+require_relative "spec_helper"+RSpec.describe "Paid Fal and local finishing", :live do+ it "generates and edits a character, animates with vocals and verifies audio and VFX artifacts" do+ raise "Set LIVE_FAL=1 to authorize six paid model calls" unless ENV["LIVE_FAL"] == "1"+ song = File.expand_path(ENV.fetch("LIVE_SONG"))+ expected = ENV.fetch("LIVE_LYRICS").downcase.scan(/[a-z']+/)+ FileUtils.mkdir_p(fixtures)+ client = Fal::Client.new+ # The paid-test flag is explicit test authorization; production approval is not reused.+ Dir.chdir(fixtures) do+ FileUtils.mkdir_p("docs"); FileUtils.mkdir_p("config")+ File.write("docs/PLAN.md", "Paid test: one image, one edit, one H3 5s, one Whisper, one Demucs and one SFX. No rerolls.")+ Workflow::Approval.new.record!("LIVE_FAL=1 supplied by test operator")+ image_model = Fal::Models::GptImage25.new(client: client)+ generated = image_model.generate(prompt: "Hyper quality polished playful 2D music video character: red cartoon robot singer, expressive face with clear mouth, full body centered, flat green #00B140 background. No text, no extra characters, no green clothing.")+ image = client.download(generated.output.fetch("images").first.fetch("url"), file("identity.png"))+ expect(magick.identify(image)[:w]).to be >= 1920+ edited = Fal::Models::GptImage25Edit.new(client: client).edit(prompt: "The SAME robot character and style, same flat chroma green. Keep the face clearly visible, raise one hand in an expressive singing pose. Hyper quality polished detail, no text.", image_urls: [generated.output["images"][0]["url"]])+ client.download(edited.output["images"][0]["url"], file("pose.png"))+ input = ff.extract_audio(song, file("song.wav"), seconds: 5)+ input = ff.fit_audio(input, file("padded.wav"), seconds: 5, fade: 0) if ff.duration(input) < 5+ url = client.upload(input)+ transcript = Fal::Models::Whisper.new(client: client).transcribe(audio_url: url, chunk_level: "word")+ json(file("transcript.json"), transcript.output)+ heard = transcript.output.fetch("text").downcase.scan(/[a-z']+/)+ expect(heard & expected).not_to be_empty+ stem = Fal::Models::Demucs.new(client: client).separate(audio_url: url, stems: ["vocals"])+ vocals = client.download(stem.output.fetch("vocals").fetch("url"), file("vocals.wav"))+ expect(ff.duration(vocals)).to be_within(0.3).of(5)+ # Harness check only: 768P keeps this paid test cheap (5 s is the H3 minimum).+ # AI agents: when this spec runs inside a generated video project (not the plugin harness), change it back to 1080P:+ # drop `resolution: "768P"`, expect "1080P" and a clip height >= 1060. Never copy this 768P override into production calls.+ animation = Fal::Models::H3MaxImageToVideo.new(client: client).animate(prompt: "The SAME robot performs the supplied lyric with articulated mouth motion and expressive eyebrow/hand acting, perfect flat green, locked camera, entire face visible. Hyper quality very interesting and fun music video performance, no text.", image_url: edited.output["images"][0]["url"], duration: 5, resolution: "768P", target_audio_url: client.upload(vocals))+ clip = client.download(animation.output.fetch("video").fetch("url"), file("h3.mp4"))+ expect(animation.input[:resolution]).to eq("768P")+ expect(ff.summary(clip).dig(:video,:h)).to be >= 700+ expect(ff.duration(clip)).to be_within(0.3).of(5)+ sfx = Fal::Models::StableAudioSfx.new(client: client).generate(prompt: "One short cartoon pop, isolated, no voice or music", duration: 2)+ sound = client.download(sfx.output.fetch("audio").fetch("url"), file("pop.wav"))+ expect(ff.duration(sound)).to be > 0+ json(file("requests.json"), [generated, edited, transcript, stem, animation, sfx].map { |r| {request_id: r.request_id, input: r.input} })+ # Key the actual model clip, place at a controlled location, overlay and finish through Swift.+ meta = py.cutout(clip, file("sprites"), "green", frames: 24, scale: 0.3)+ coverage = magick.alpha_coverage(file("sprites/0000.png"))+ expect(coverage).to be_between(0.01,0.95)+ meta["dir"] = file("sprites").delete_prefix("#{RT}/")+ json(file("clips.json"), hero: meta)+ File.write(file("scene.js"), "Anim.sketch({async load(){this.s=await Anim.clip('hero')},draw(t){background('#263b59');this.s.draw(this.s.frame(t*24),240,90,160)}})")+ Media::Anim.new.render(file("scene.js"), file("frames"), width: 320, height: 180, fps: 24, frames: 24, data: {clips: file("clips.json")})+ base = ff.still_plate(image, input, file("plate.mp4"), seconds: 1, w: 320, h: 180)+ ff.overlay_frames(base, file("frames"), file("scene.mp4"), fps: 24)+ name = "live-vfx-#{Process.pid}"; dir = File.join(RT,"prompts",name); FileUtils.mkdir_p(dir)+ File.write(File.join(dir,"cues.yml"), YAML.dump({"source"=>file("scene.mp4"),"out"=>file("finished.mp4"),"cues"=>[{"fx"=>"dark","f"=>12,"dur"=>3,"amt"=>0.8}]}))+ Media::Vfx.new(name).render+ expect(ff.summary(file("finished.mp4")).dig(:video,:frames)).to eq(24)+ ff.frame_index(file("scene.mp4"),12,file("before.png")); ff.frame_index(file("finished.mp4"),12,file("after.png"))+ expect(mean_luma(file("after.png"))).to be < mean_luma(file("before.png")) * 0.5+ end+ end+enddiff --git a/skills/make-an-anime/scripts/spec/local_workflow_spec.rb b/skills/make-an-anime/scripts/spec/local_workflow_spec.rbnew file mode 100644index 0000000..f0bce9e--- /dev/null+++ b/skills/make-an-anime/scripts/spec/local_workflow_spec.rb@@ -0,0 +1,31 @@+require_relative "spec_helper"++RSpec.describe "Local soundtrack and prepared overlay", :media do+ it "renders a first overlay from existing global word timings without any Fal client" do+ song = tone(duration: 3)+ run = "e2e-local-#{Process.pid}-#{object_id}"+ project = Pipeline::Project.new(run)+ stub_const("Pipeline::GENERATIONS", { run => { steps: [Pipeline::Steps::Music, Pipeline::Steps::Keyframes, Pipeline::Steps::Overlay],+ **Pipeline.section(24, 4), music_from: song, upload_music: false, plate: "paper" } })+ expect(Fal::Client).not_to receive(:new)+ Pipeline::Steps::Music.new(project: project).run!+ expect(project[:music]["url"]).to be_nil+ expect(ff.duration(project[:music]["path"])).to be_within(0.002).of(4 / 24.0)+ plate = character+ project.record(:keyframes, items: { paper: { path: plate } })+ dir = File.join(RT, "prompts", run)+ FileUtils.mkdir_p(dir)+ File.write(File.join(dir, "05_overlay.js"), "Anim.sketch({draw(){background('#202060');fill('white');rect(20,20,120,120)}})")+ json(file("words.json"), chunks: [{text: "before", timestamp: [0.0,0.5]}, {text: "here", timestamp: [1.05,1.12]}, {text: "after", timestamp: [2,2.5]}])+ overlay = Pipeline::Steps::Overlay.new(project: project)+ expect(overlay.prepare!(file("words.json"))[:count]).to eq(1)+ words = JSON.parse(File.read(project.path("05_overlay", "words.json")))+ expect(words.first["s"]).to be_within(1e-6).of(0.05)+ result = overlay.render!+ expect(project[:overlay]["frames_dir"]).to eq(result[:frames_dir])+ expect(ff.summary(result[:path]).dig(:video,:frames)).to eq(4)+ sheet = file("new-review-directory/contact.jpg")+ ff.contact_sheet(result[:path], sheet, cols: 2, rows: 1, width: 160)+ expect(ff.summary(sheet).dig(:video, :w)).to be > 300+ end+enddiff --git a/skills/make-an-anime/scripts/spec/media_spec.rb b/skills/make-an-anime/scripts/spec/media_spec.rbnew file mode 100644index 0000000..835eb46--- /dev/null+++ b/skills/make-an-anime/scripts/spec/media_spec.rb@@ -0,0 +1,164 @@+require_relative "spec_helper"+RSpec.describe "Local media end to end", :media do+ it "executes the documented intake and audio-analysis task in a fresh project" do+ song = tone(duration: 3)+ File.write(file("brief.md"), "A robot band, visual puns and dramatic drop")+ destination = file("new project")+ _, err, status = cli("init", "--project", destination, "--song", song, "--prompt-file", file("brief.md"))+ expect(status.exitstatus).to eq(0), err+ out, err, status = cli("--project", destination, "audio:analyze[audio/source.wav,audio]")+ expect(status.exitstatus).to eq(0), err+ expect(JSON.parse(out)["duration"]).to be_within(0.01).of(3)+ expect(File.file?(File.join(destination,"tools/python/beats.py"))).to be(true)+ expect(File.file?(File.join(destination,".skill/SKILL.md"))).to be(true)+ expect(File.directory?(File.join(destination,"node_modules"))).to be(false)+ expect(File.directory?(File.join(destination,"tools/vfx/.build"))).to be(false)+ end+ it "renders typography, timing and graphics helpers without bundled font files" do+ result = Media::Anim.new.render(File.join(RT,"tools/p5/examples/smoke.js"), file("smoke"), width: 1920, height: 1080, fps: 24, frames: 48, only: [0,24,47])+ expect(result["frames"]).to eq(3)+ expect(magick.alpha_coverage(file("smoke/0024.png"))).to be > 0.03+ expect(File.binread(file("smoke/0000.png"))).not_to eq(File.binread(file("smoke/0047.png")))+ end+ it "isolates drawing state per frame, so a full render matches single-frame previews" do+ File.write(file("leak.js"), <<~JS)+ Anim.sketch({+ draw(t, frame) {+ if (frame === 0) { textAlign(RIGHT, TOP); fill(255, 0, 0); } // a helper that forgets to restore state+ textSize(60); text("LEFT", 0, 90); // default LEFT alignment draws on canvas+ },+ });+ JS+ Media::Anim.new.render(file("leak.js"), file("leak"), width: 320, height: 180, fps: 24, frames: 2)+ lit = ->(png) { Media::ImageMagick.new.run("magick", png, "-alpha", "extract", "-format", "%[fx:mean]", "info:", quiet: true).to_f }+ expect(lit.(file("leak/0001.png"))).to be > 0.01+ end++ it "starts a subtitle where the voice starts (speech_at), not at a silent take head or a late word cue" do+ take = file("take.wav")+ ff.run("ffmpeg", "-y", "-v", "error", "-i", tone(file("t.wav"), duration: 1), "-af", "adelay=700|700", take, quiet: true)+ expect(ff.leading_silence(take)).to be_within(0.05).of(0.7)+ expect(ff.leading_silence(tone(file("t2.wav"), duration: 1))).to eq(0.0)+ File.write(file("subs.js"), <<~JS)+ Anim.sketch({ draw(t) { background(0); Anim.subtitles(t, Anim.data("dialogue"), { font: "sans-serif" }); } });+ JS+ File.write(file("dialogue.json"), JSON.generate([{ name: "eat", text: "[tired] Eat, amore.", at: 0.0, speech_at: 0.5, end: 1.0 }]))+ # Misleading word cues (as ElevenLabs gave after a long tag) must not delay the subtitle: speech_at wins.+ File.write(file("words.json"), JSON.generate([{ w: "Eat", s: 0.9, e: 0.95, line: "eat" }, { w: "amore", s: 0.95, e: 1.0, line: "eat" }]))+ Media::Anim.new.render(file("subs.js"), file("subs"), width: 640, height: 360, fps: 24, frames: 24, only: [6, 18],+ data: { dialogue: file("dialogue.json"), words: file("words.json") })+ lit = ->(f) { magick.run("magick", f, "-colorspace", "gray", "-threshold", "50%", "-format", "%[fx:mean]", "info:", quiet: true).to_f }+ expect(lit.(file("subs/0006.png"))).to eq(0.0)+ expect(lit.(file("subs/0018.png"))).to be > 0.001+ # A `subtitle:` gloss is drawn instead of the spoken text (wider string -> more lit pixels).+ File.write(file("dialogue.json"), JSON.generate([{ name: "eat", text: "[tired] Eat, amore.", subtitle: "Eat, amore. (Eat, my love.)", at: 0.0, speech_at: 0.5, end: 1.0 }]))+ Media::Anim.new.render(file("subs.js"), file("subs2"), width: 640, height: 360, fps: 24, frames: 24, only: [18],+ data: { dialogue: file("dialogue.json"), words: file("words.json") })+ expect(lit.(file("subs2/0018.png"))).to be > lit.(file("subs/0018.png")) * 1.5+ end+ it "cuts a shot to its first source_frames and retimes them to the shot length" do+ src = file("take.mp4")+ ff.run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "testsrc2=size=320x180:rate=24:duration=2", "-pix_fmt", "yuv420p", src, quiet: true)+ out = ff.concat_shots([{ path: src, frames: 48, retime: true, keep: 24, skip: 0 }], file("kept.mp4"), fps: 24)+ expect(ff.summary(out).dig(:video, :frames)).to eq(48)+ diff = ->(a, b) { Open3.capture3("magick", "compare", "-metric", "RMSE", a, b, "null:")[1][/\(([\d.e-]+)\)/, 1].to_f }+ last = ff.frame_index(out, 47, file("kept_last.png"))+ src23 = ff.frame_index(src, 23, file("src23.png")); src47 = ff.frame_index(src, 47, file("src47.png"))+ expect(diff.(last, src23)).to be < diff.(last, src47)+ # An uneven stretch (72 kept frames -> 96) used to come out one frame short.+ odd = ff.concat_shots([{ path: src, frames: 96, retime: true, keep: 36, skip: 0 }, { path: src, frames: 20, retime: true }], file("odd.mp4"), fps: 24)+ expect(ff.summary(odd).dig(:video, :frames)).to eq(116)+ end+ it "levels a take by its gain_db when placing lines, leaving lines without one untouched" do+ take = tone(file("take.wav"), duration: 1)+ rms = lambda do |path, from|+ _, err, = Open3.capture3("ffmpeg", "-v", "info", "-ss", from.to_s, "-t", "0.8", "-i", path, "-af", "astats=measure_overall=RMS_level:measure_perchannel=0", "-f", "null", "-")+ err[/RMS level dB:\s*(-?[\d.]+)/, 1].to_f+ end+ out = ff.place_audio([{ "at" => 0.0, "path" => take }, { "at" => 2.0, "path" => take, "gain_db" => -6.0 }], file("placed.wav"), seconds: 3.5)+ expect(rms.(out, 2.1) - rms.(out, 0.1)).to be_within(0.3).of(-6.0)+ end+ it "detects audio duration, a real silent tail and vocal-band energy through Python" do+ song = tone(duration: 4)+ Toolkit::Operations.new.analyze_audio(song, file("analysis"))+ energy = JSON.parse(File.read(file("analysis/energy.json")))+ expect(energy["duration"]).to be_within(0.02).of(4)+ expect(energy["silence_tail_s"]).to be >= 0.5+ expect(energy["windows"].first["vocal_ratio"]).to be > 0.9+ beats = JSON.parse(File.read(file("analysis/beats.json")))+ expect(beats.fetch("beats")).not_to be_empty+ end+ it "finds a hard cut at the expected frame through Python" do+ ff.run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "color=black:s=320x180:r=24:d=1", "-f", "lavfi", "-i", "color=white:s=320x180:r=24:d=1", "-filter_complex", "[0:v][1:v]concat=n=2:v=1:a=0", "-c:v", "libx264", file("cuts.mp4"))+ data = py.call("cuts.py", file("cuts.mp4"))+ expect(data["cuts"].map { |c| c["f"] }).to include(24)+ expect(data["frames"]).to eq(48)+ end+ it "cuts out green, preserves the character and renders it at the intended p5 position" do+ meta = py.cutout(character, file("sprite"), "green")+ rgba = pixels(file("sprite/0000.png"))+ expect(rgba[0][3]).to eq(0)+ expect(rgba[90 * 320 + 160][3]).to be > 250+ meta["dir"] = file("sprite").delete_prefix("#{RT}/")+ json(file("clips.json"), hero: meta)+ File.write(file("scene.js"), <<~JS)+ Anim.sketch({+ async load() { this.hero = await Anim.clip('hero'); },+ draw(t, frame) { background('#102030'); this.hero.draw(this.hero.frame(0), 240, 90, 180); noStroke(); fill('#ffffff'); rect(8 + frame * 2, 8, 8, 8); }+ });+ JS+ renderer = Media::Anim.new+ renderer.render(file("scene.js"), file("frames"), width: 320, height: 180, fps: 24, frames: 24, data: {clips: file("clips.json")})+ png = pixels(file("frames/0000.png"))+ red = png.each_index.select { |i| r,g,b,_ = png[i]; r > 170 && g < 90 && b < 110 }+ xs = red.map { |i| i % 320 }; ys = red.map { |i| i / 320 }+ expect(xs.min).to be_within(3).of(208)+ expect(xs.max).to be_within(3).of(272)+ expect(ys.min).to be_within(3).of(36)+ expect(ys.max).to be_within(3).of(144)+ expect(Digest::SHA256.file(file("frames/0000.png")).hexdigest).not_to eq(Digest::SHA256.file(file("frames/0023.png")).hexdigest)+ renderer.render(file("scene.js"), file("repeat"), width: 320, height: 180, fps: 24, frames: 24, only: [0], data: {clips: file("clips.json")})+ expect(File.binread(file("repeat/0000.png"))).to eq(File.binread(file("frames/0000.png")))+ base = video(seconds: 1)+ ff.overlay_frames(base, file("frames"), file("scene.mp4"), fps: 24)+ info = ff.summary(file("scene.mp4"))+ expect(info.dig(:video, :frames)).to eq(24)+ expect(info.dig(:audio, :codec)).to eq("aac")+ end+ it "assembles contiguous sections without losing frames or the original soundtrack timing" do+ song = tone(duration: 2)+ runs = %w[e2e-join-a e2e-join-b]+ generations = runs.each_with_index.to_h { |name, i| [name, {steps: [], **Pipeline.section(i * 24, 24), music_from: song}] }+ stub_const("Pipeline::GENERATIONS", generations)+ runs.each do |run|+ project = Pipeline::Project.new(run)+ video(project.path("final_overlay.mp4"), audio: song, seconds: 1)+ end+ Toolkit::Operations.new.preview(file("joined.mp4"), runs)+ info = ff.summary(file("joined.mp4"))+ expect(info.dig(:video, :frames)).to eq(48)+ expect(info[:duration]).to be_within(0.06).of(2)+ original = ff.run("ffmpeg", "-v", "error", "-i", song, "-ac", "1", "-f", "s16le", "-", quiet: true).unpack("s<*")+ joined = ff.run("ffmpeg", "-v", "error", "-i", file("joined.mp4"), "-ac", "1", "-ar", "44100", "-f", "s16le", "-", quiet: true).unpack("s<*")+ size = [original.size, joined.size].min+ dot = original.take(size).zip(joined).sum { |x,y| x * y }+ norm = Math.sqrt(original.take(size).sum { |x| x*x } * joined.take(size).sum { |x| x*x })+ expect(dot / norm).to be > 0.98+ end+ it "mixes a timed sound effect, limits peaks and keeps the video frames" do+ source = video(seconds: 2)+ name = "e2e-sfx-#{Process.pid}"+ config_dir = File.join(RT, "prompts", name); FileUtils.mkdir_p(config_dir)+ File.write(File.join(config_dir, "sfx.yml"), YAML.dump({"source" => source, "out" => file("mixed.mp4"), "sounds" => {"beep" => {"tone" => 1200, "duration" => 0.3}}, "cues" => [{"sound" => "beep", "at" => 0.75, "rel_db" => -4}]}))+ service = Media::Sfx.new(name)+ service.generate(client: double("no Fal calls for tones"))+ out, report = service.mix+ expect(ff.summary(out).dig(:video, :frames)).to eq(48)+ expect(report).not_to be_empty+ dry = ff.run("ffmpeg", "-v", "error", "-i", source, "-ac", "1", "-ar", "48000", "-f", "s16le", "-", quiet: true).unpack("s<*")+ wet = ff.run("ffmpeg", "-v", "error", "-i", out, "-ac", "1", "-ar", "48000", "-f", "s16le", "-", quiet: true).unpack("s<*")+ expect(wet.map(&:abs).max).to be < 32767+ diff = ->(from, len) { wet.slice(from,len).zip(dry.slice(from,len)).sum { |a,b| (a-b).abs }.fdiv(len) }+ expect(diff.call(38_000, 5_000)).to be > diff.call(5_000, 5_000) * 3+ end+enddiff --git a/skills/make-an-anime/scripts/spec/pipeline_spec.rb b/skills/make-an-anime/scripts/spec/pipeline_spec.rbnew file mode 100644index 0000000..2a1c0f7--- /dev/null+++ b/skills/make-an-anime/scripts/spec/pipeline_spec.rb@@ -0,0 +1,105 @@+require_relative "spec_helper"+# Uses the real Client#run receipt/approval path, with deterministic synthetic provider I/O.+class SyntheticFal < Fal::Client+ attr_reader :calls+ def initialize(image:, video:)+ super(api_key: "fixture-only", poll_interval: 0)+ @image, @video, @calls, @results = image, video, [], {}+ end+ def submit(endpoint, input)+ id = "fixture-#{@calls.size}"+ @calls << [endpoint, input]+ @results[id] = endpoint.include?("image-to-video") ? {"video" => {"url" => "fixture://video"}} : {"images" => [{"url" => "fixture://image"}]}+ {"request_id" => id, "status_url" => id, "response_url" => id}+ end+ def wait(*) = true+ def get_json(id) = @results.fetch(id)+ def upload(path, **) = "fixture://#{File.basename(path)}"+ def download(url, path)+ FileUtils.cp(url == "fixture://video" ? @video : @image, path)+ path+ end+end+RSpec.describe "Character to animated scene pipeline", :media do+ it "creates an edited character identity version without overwriting the original" do+ image = character+ before = Digest::SHA256.file(image).hexdigest+ original = Pipeline::Project.new("e2e-original-#{Process.pid}")+ revised = Pipeline::Project.new("e2e-revised-#{Process.pid}")+ original.record(:ref_base, path: image, url: "fixture://approved-v1")+ stub_const("Pipeline::GENERATIONS", {revised.name => {steps:[Pipeline::Steps::RefBase], edit_from: original.name}})+ dir=File.join(RT,"prompts",revised.name); FileUtils.mkdir_p(dir)+ File.write(File.join(dir,"01_ref_base.txt"),"Keep the same character; change the hairstyle to approved v2")+ client = SyntheticFal.new(image:image,video:image)+ with_workspace do+ approve+ Pipeline::Steps::RefBase.new(project:revised,client:client).run!+ end+ expect(client.calls.first[0]).to eq(Fal::Models::GptImage25Edit.endpoint)+ expect(client.calls.first[1][:image_urls]).to eq(["fixture://approved-v1"])+ expect(Digest::SHA256.file(image).hexdigest).to eq(before)+ expect(revised[:ref_base]["path"]).not_to eq(image)+ end+ it "generates identity, edits a pose, supplies H3 vocals, cuts alpha and assembles placed animation" do+ image = character(file("identity.png"), width: 1920, height: 1080)+ song = tone(duration: 5)+ movie = video(file("animation.mp4"), audio: song, seconds: 5)+ run = "e2e-character-#{Process.pid}"+ generation = {steps: [Pipeline::Steps::RefBase, Pipeline::Steps::Keyframes, Pipeline::Steps::Clips], **Pipeline.section(0, 24)}+ stub_const("Pipeline::GENERATIONS", {run => generation})+ project = Pipeline::Project.new(run)+ prompt_dir = File.join(RT, "prompts", run); FileUtils.mkdir_p(prompt_dir)+ File.write(File.join(prompt_dir, "01_ref_base.txt"), "Expressive red robot character sheet; fixture")+ File.write(File.join(prompt_dir, "02_keyframes.yml"), YAML.dump({"pose" => {"prompt" => "Same robot, raise hand"}, "later" => {"prompt" => "Same robot, grin"}}))+ File.write(File.join(prompt_dir, "04_clips.yml"), YAML.dump([{"name" => "sing", "image" => "pose", "seconds" => 5, "key" => "green", "audio" => song, "audio_at" => 0, "frames" => 24, "prompt" => "Animate the same robot with clear singing mouth movements"}]))+ client = SyntheticFal.new(image: image, video: movie)+ with_workspace do+ approve+ base = Pipeline::Steps::RefBase.new(project: project, client: client)+ base.run!+ expect(base.review![:verdict]).to eq("PASS")+ base.run! # A completed asset skips another model call.+ expect(client.calls.size).to eq(1)+ ENV["ONLY"] = "pose"+ Pipeline::Steps::Keyframes.new(project: project, client: client).run!+ expect(project[:keyframes]["items"].keys).to eq(["pose"])+ ENV.delete("ONLY")+ Pipeline::Steps::Keyframes.new(project: project, client: client).run!+ Pipeline::Steps::Clips.new(project: project, client: client).run!+ end+ expect(client.calls[0][1][:quality]).to eq("xhigh")+ expect(client.calls[1][0]).to eq(Fal::Models::GptImage25Edit.endpoint)+ h3 = client.calls.last+ expect(h3[1]).to include(resolution: "768P", duration: 5)+ expect(h3[1][:target_audio_url]).to start_with("fixture://04_audio_")+ meta = JSON.parse(File.read(project[:clips]["items"]["sing"]["path"]))+ expect(meta["frames"]).to eq(24)+ json(file("clips.json"), sing: meta)+ File.write(file("scene.js"), "Anim.sketch({async load(){this.s=await Anim.clip('sing')},draw(t,f){this.s.draw(this.s.at(t),240,90,180); noStroke();fill('#ffffff');rect(10+f,10,8,8)}})")+ Media::Anim.new.render(file("scene.js"), file("rendered"), width: 320, height: 180, fps: 24, frames: 24, data: {clips: file("clips.json")})+ base = ff.still_plate(image, song, file("plate.mp4"), seconds: 1, w: 320, h: 180)+ ff.overlay_frames(base, file("rendered"), file("final.mp4"), fps: 24)+ expect(ff.summary(file("final.mp4")).dig(:video, :frames)).to eq(24)+ px = pixels(file("rendered/0000.png"))+ expect(px[90 * 320 + 240][3]).to be > 250+ expect(px[90 * 320 + 20][3]).to eq(0)+ end+ it "rejects singing retimes before any model call" do+ project = instance_double(Pipeline::Project)+ step = Pipeline::Steps::Shots.new(project: project, client: double("unused"))+ expect { step.generate("sing", {"audio" => true, "retime" => true}) }.to raise_error(ArgumentError, /Never retime/)+ end+ it "runs the mouth alignment diagnostic against synthetic mouth and vocal activity" do+ song = tone(duration: 2)+ dir = file("mouth"); FileUtils.mkdir_p(dir)+ 48.times do |i|+ # Vary mouth darkness with a known pattern; the final silent frames close fully.+ h = i < 36 ? (5 + i % 12) : 0+ magick.run("magick", "-size", "40x30", "xc:white", "-fill", "black", "-draw", "rectangle 10,10 30,#{10+h}", File.join(dir, format("%04d.png", i)), quiet: true)+ end+ raw = py.run(py.executable, File.join(Media::Python::SCRIPTS, "mouth_sync.py"), dir, song, "0", "5", "5", "30", "20", "--pauses", "1.5-2", quiet: true)+ data = JSON.parse(raw.lines.last)+ expect(data["best_lag"]).to be_between(-6,6)+ expect(data["pauses"].first["mean"]).to be < data["mouth_voiced"]+ end+enddiff --git a/skills/make-an-anime/scripts/spec/reference_importer_spec.rb b/skills/make-an-anime/scripts/spec/reference_importer_spec.rbnew file mode 100644index 0000000..208cc0b--- /dev/null+++ b/skills/make-an-anime/scripts/spec/reference_importer_spec.rb@@ -0,0 +1,20 @@+require_relative "spec_helper"++RSpec.describe "Existing character reference import", :core do+ it "copies a proven reference without uploads and refuses conflicting identity bytes" do+ File.write(file("source.png"), "synthetic reference fixture")+ File.write(file("copy.png"), "synthetic reference fixture")+ json(file("manifest.json"), ref_base: { path: file("source.png"), url: "https://cdn.test/identity.png",+ request_id: "original-id", endpoint: "test/image" })+ run = "e2e-reference-#{Process.pid}-#{object_id}"+ importer = Pipeline::ReferenceImporter.new+ expect(Fal::Client).not_to receive(:new)+ result = importer.import(run: run, image: file("copy.png"), manifest: file("manifest.json"))+ expect(File.read(result["path"])).to eq("synthetic reference fixture")+ expect(result["url"]).to eq("https://cdn.test/identity.png")+ expect(result["provenance"][:sha256] || result["provenance"]["sha256"]).to eq(Digest::SHA256.file(file("source.png")).hexdigest)+ expect(importer.import(run: run, image: file("copy.png"), manifest: file("manifest.json"))["path"]).to eq(result["path"])+ File.write(file("copy.png"), "a different identity")+ expect { importer.import(run: run, image: file("copy.png"), manifest: file("manifest.json")) }.to raise_error(ArgumentError, /differ/)+ end+enddiff --git a/skills/make-an-anime/scripts/spec/spec_helper.rb b/skills/make-an-anime/scripts/spec/spec_helper.rbnew file mode 100644index 0000000..459f486--- /dev/null+++ b/skills/make-an-anime/scripts/spec/spec_helper.rb@@ -0,0 +1,71 @@+require "rspec"+require "tmpdir"+require "fileutils"+require "json"+require "yaml"+require "rbconfig"+require "open3"+require "digest"+require_relative "../lib/fal_mv_gen"+require_relative "../lib/toolkit/operations"+RT = File.expand_path("..", __dir__)+SKILL = File.file?(File.expand_path("../SKILL.md", RT)) ? File.expand_path("..", RT) : File.join(RT, ".skill")+ENTRY = File.join(RT, "mv.rb")+module Fixtures+ def ff = @ff ||= Media::FFmpeg.new+ def py = @py ||= Media::Python.new+ def magick = @magick ||= Media::ImageMagick.new+ def fixtures+ @fixtures ||= FileUtils.mkdir_p(File.join(RT, "tmp", "rspec-#{Process.pid}-#{object_id}")).first+ end+ def file(name) = File.join(fixtures, name)+ def json(path, value)+ FileUtils.mkdir_p(File.dirname(path)); File.write(path, JSON.pretty_generate(value))+ end+ def tone(path = file("song.wav"), duration: 2)+ # Half a second of final silence makes detection and pause tests observable.+ ff.run("ffmpeg", "-y", "-v", "error", "-f", "lavfi", "-i", "sine=frequency=700:sample_rate=44100:duration=#{duration - 0.5}", "-af", "apad=whole_dur=#{duration}", "-t", duration, "-ac", "2", "-c:a", "pcm_s16le", path)+ path+ end+ def character(path = file("character.png"), width: 320, height: 180)+ magick.run("magick", "-size", "#{width}x#{height}", "xc:#00B140", "-fill", "#e02040", "-draw", "rectangle #{width * 0.4},#{height * 0.2} #{width * 0.6},#{height * 0.8}", path)+ path+ end+ def video(path = file("clip.mp4"), image: character, audio: tone, seconds: 2)+ ff.still_plate(image, audio, path, seconds: seconds, fps: 24, w: 320, h: 180)+ end+ def pixels(path)+ magick.run("magick", path, "-depth", "8", "rgba:-", quiet: true).bytes.each_slice(4).to_a+ end+ def mean_luma(path)+ magick.run("magick", path, "-colorspace", "gray", "-format", "%[fx:mean]", "info:", quiet: true).to_f+ end+ def approve+ FileUtils.mkdir_p("docs"); FileUtils.mkdir_p("config")+ File.write("docs/PLAN.md", "Synthetic test plan: local fixture media, no paid requests.\n")+ Workflow::Approval.new.record!("RSpec fixture approval; mocked network only")+ end+ def with_workspace+ Dir.mktmpdir("mv-spec-") { |dir| Dir.chdir(dir) { yield dir } }+ end+ def cli(*args, env: {})+ Open3.capture3(env, RbConfig.ruby, ENTRY, *args)+ end+end+RSpec.configure do |c|+ c.include Fixtures+ c.order = :defined+ c.before do+ @saved_env = ENV.to_h+ %w[RUN ONLY FORCE RECUT NEW_REQUEST VIDEO_RES].each { |k| ENV.delete(k) }+ end+ c.after do+ ENV.replace(@saved_env)+ Excon.stubs.clear+ Excon.defaults[:mock] = false+ end+ c.before(:suite) do+ Dir.chdir(RT)+ FileUtils.mkdir_p("tmp")+ end+enddiff --git a/skills/make-an-anime/scripts/spec/sprite_components_spec.rb b/skills/make-an-anime/scripts/spec/sprite_components_spec.rbnew file mode 100644index 0000000..66f434e--- /dev/null+++ b/skills/make-an-anime/scripts/spec/sprite_components_spec.rb@@ -0,0 +1,75 @@+require_relative "spec_helper"++RSpec.describe "Seeded sprite cleanup through the Ruby CLI", :media do+ def alpha_fixture+ source = file("source")+ FileUtils.mkdir_p(source)+ path = File.join(source, "0000.png")+ magick.run("magick", "-size", "160x100", "xc:none", "-fill", "rgba(230,40,90,0.35)",+ "-draw", "rectangle 11,17 33,59", "-fill", "rgba(230,40,90,0.8)",+ "-draw", "rectangle 12,18 32,58", "-font", Media::FONT,+ "-pointsize", "20", "-fill", "white", "-annotate", "+67+29", "TEXT", path)+ [source, path]+ end++ it "retains exact subject RGBA including soft alpha, removes detached text, and leaves the source unchanged" do+ source, path = alpha_fixture+ before = pixels(path)+ digest = Digest::SHA256.file(path).hexdigest+ out = file("clean")+ stdout, stderr, status = cli("media:keep_component[#{source},#{out},22,35]")+ expect(status.success?).to be(true), stderr+ report = JSON.parse(stdout)+ expect(report.fetch("frames")).to eq(1)+ expect(report.dig("metrics", 0, "removed_pixels")).to be > 0+ after = pixels(File.join(out, "0000.png"))+ subject = (17..59).flat_map { |y| (11..33).map { |x| y * 160 + x } }+ expect(after.values_at(*subject)).to eq(before.values_at(*subject))+ caption = (0...100).flat_map { |y| (60...160).map { |x| y * 160 + x } }+ expect(caption.count { |i| before[i][3].positive? }).to be > 0+ expect(caption.map { |i| after[i][3] }.uniq).to eq([0])+ expect(Digest::SHA256.file(path).hexdigest).to eq(digest)+ end++ it "rejects source overwrite, invalid coordinates and absent seed without publishing partial frames" do+ source, path = alpha_fixture+ digest = Digest::SHA256.file(path).hexdigest+ _, error, status = cli("media:keep_component[#{source},#{source},22,35]")+ expect(status.success?).to be(false)+ expect(error).to include("different directories")+ [["-1", "35", "nonnegative"], ["160", "35", "outside image bounds"],+ ["zero", "35", "invalid value"], ["0", "0", "component is absent"]].each do |x, y, message|+ out = file("invalid-#{x}-#{y}")+ _, error, status = cli("media:keep_component[#{source},#{out},#{x},#{y}]")+ expect(status.success?).to be(false)+ expect(error).to include(message)+ expect(File.exist?(out)).to be(false)+ end+ magick.run("magick", "-size", "160x100", "xc:none", File.join(source, "0001.png"))+ out = file("partial")+ _, error, status = cli("media:keep_component[#{source},#{out},22,35]")+ expect(status.success?).to be(false)+ expect(error).to include("0001.png", "component is absent")+ expect(File.exist?(out)).to be(false)+ expect(Digest::SHA256.file(path).hexdigest).to eq(digest)+ end+end++RSpec.describe "Sprite bounds through the Ruby CLI", :media do+ it "reports a green-screen character's box and seed as JSON for a still and a video" do+ still = character(width: 320, height: 180)+ [still, video(image: still)].each do |source|+ stdout, stderr, status = cli("media:sprite_box[#{source},green]")+ expect(status.success?).to be(true), stderr+ report = JSON.parse(stdout)+ x0, y0, x1, y1 = report.fetch("extent")+ expect(x0).to be_within(3).of(128)+ expect(x1).to be_within(3).of(192)+ expect(y0).to be_within(3).of(36)+ expect(y1).to be_within(3).of(144)+ bx, by, bw, bh = report.fetch("box")+ [[bx, x0 - 24], [by, y0 - 24], [bx + bw, x1 + 24], [by + bh, y1 + 24]].each { |got, want| expect(got).to be_within(1).of(want) }+ expect(report.fetch("seed")).to eq([(x0 + x1) / 2, (y0 + y1) / 2])+ end+ end+enddiff --git a/skills/make-an-anime/scripts/spec/support/synthetic_anime_fal.rb b/skills/make-an-anime/scripts/spec/support/synthetic_anime_fal.rbnew file mode 100644index 0000000..2e7aa4e--- /dev/null+++ b/skills/make-an-anime/scripts/spec/support/synthetic_anime_fal.rb@@ -0,0 +1,31 @@+# Deterministic provider I/O for pipeline specs: every paid endpoint answers with a local fixture.+class SyntheticAnimeFal < Fal::Client+ attr_reader :calls, :uploads+ def initialize(image:, video:, voice:, music:)+ super(api_key: "fixture-only", poll_interval: 0)+ @files = { "fixture://image" => image, "fixture://video" => video, "fixture://voice" => voice, "fixture://music" => music }+ @calls, @uploads, @results = [], [], {}+ end+ def submit(endpoint, input)+ id = "fixture-#{@calls.size}"+ @calls << [endpoint, input]+ @results[id] = case endpoint+ when /image-to-video/ then { "video" => { "url" => "fixture://video" } }+ when /tts/ then { "audio" => { "url" => "fixture://voice" },+ "timestamps" => [{ "text" => "hello", "start" => 0.1, "end" => 0.5 }, { "text" => "there", "start" => 0.6, "end" => 1.0 }] }+ when /music/ then { "audio" => { "url" => "fixture://music" } }+ else { "images" => [{ "url" => "fixture://image" }] }+ end+ { "request_id" => id, "status_url" => id, "response_url" => id }+ end+ def wait(*) = true+ def get_json(id) = @results.fetch(id)+ def upload(path, **)+ @uploads << path+ "fixture://upload/#{File.basename(path)}"+ end+ def download(url, path)+ FileUtils.cp(@files.fetch(url), path)+ path+ end+enddiff --git a/skills/make-an-anime/scripts/spec/swift_spec.rb b/skills/make-an-anime/scripts/spec/swift_spec.rbnew file mode 100644index 0000000..062b167--- /dev/null+++ b/skills/make-an-anime/scripts/spec/swift_spec.rb@@ -0,0 +1,36 @@+require_relative "spec_helper"+RSpec.describe "Swift VFX end to end", :swift do+ it "applies a cued effect to a character scene, preserves outside frames and audio" do+ raise "Swift VFX requires macOS 14+ (use PROFILE=media/core elsewhere)" unless RUBY_PLATFORM.include?("darwin")+ source = video+ sprite = character+ meta = py.cutout(sprite, file("sprites"), "green")+ meta["dir"] = file("sprites").delete_prefix("#{RT}/")+ json(file("clips.json"), hero: meta)+ File.write(file("scene.js"), "Anim.sketch({async load(){this.s=await Anim.clip('hero')},draw(t,f){background('#244060');this.s.draw(this.s.frame(0),240,90,180);fill('#ffffff');rect(10+f,10,8,8)}})")+ Media::Anim.new.render(file("scene.js"),file("frames"),width:320,height:180,fps:24,frames:48,data:{clips:file("clips.json")})+ source = ff.overlay_frames(source,file("frames"),file("composed.mp4"),fps:24)+ name = "e2e-vfx-#{Process.pid}"+ dir = File.join(RT, "prompts", name); FileUtils.mkdir_p(dir)+ config = {"source" => source, "out" => file("effect.mp4"), "lights" => "tools/p5/examples/lights.js", "cues" => [{"fx" => "dark", "f" => 12, "dur" => 6, "hold" => 3, "amt" => 0.9}, {"fx" => "flare", "f" => 36, "dur" => 3, "amt" => 1, "x" => 0.5, "y" => 0.5}]}+ File.write(File.join(dir, "cues.yml"), YAML.dump(config))+ service = Media::Vfx.new(name)+ service.render+ info = ff.summary(file("effect.mp4"))+ expect(info.dig(:video, :frames)).to eq(48)+ expect(info.dig(:audio, :codec)).to eq("aac")+ [0,12,30,36].each do |frame|+ ff.frame_index(source, frame, file("before#{frame}.png"))+ ff.frame_index(file("effect.mp4"), frame, file("after#{frame}.png"))+ end+ expect(mean_luma(file("after12.png"))).to be < mean_luma(file("before12.png")) * 0.3+ [0,30].each { |frame| expect(mean_luma(file("after#{frame}.png"))).to be_within(0.02).of(mean_luma(file("before#{frame}.png"))) }+ before_light = magick.run("magick", file("before36.png"), "-crop", "60x40+130+70", "-colorspace", "gray", "-format", "%[fx:mean]", "info:", quiet: true).to_f+ after_light = magick.run("magick", file("after36.png"), "-crop", "60x40+130+70", "-colorspace", "gray", "-format", "%[fx:mean]", "info:", quiet: true).to_f+ expect(after_light).to be > before_light + 0.05+ expect(Dir[File.join(service.path("lights"),"*.png")].size).to eq(3)+ config["cues"] = [{"fx" => "unknown", "f" => 1, "dur" => 1}]+ File.write(File.join(dir, "cues.yml"), YAML.dump(config))+ expect { Media::Vfx.new(name).render }.to raise_error(ArgumentError, /unknown fx/)+ end+end