Skip to content
Docs menu

Step 8: manifest and command line

Step 8 of 8

Record what was made, and take the scene from the command line.

Last, keep a record of what was made, and let people choose the scene from the command line. The manifest stores the session_id, which is what lets anyone download these files again later.

manifest = {"scene": scene, "mood": mood, "session_id": catalyst.session_id,
            "plumes_spent": spent, "files": files}
(out / "manifest.json").write_text(json.dumps(manifest, indent=2))

The command line takes:

Output
soundscape "<scene>" [--mood calm] [--out kit] [--music-seconds 30] [--background]

The whole program

One function, build_kit, does the work; main only parses arguments and turns errors into messages.

#!/usr/bin/env python3
import argparse, json, sys
from pathlib import Path
from falcore import (APIConnectionError, APIStatusError, AuthenticationError, Catalyst,
                     InvalidRequestError, QuotaExceededError, RateLimitError)

def ambience_prompts(scene, mood):
    return [f"{scene}, steady ambient bed, {mood} mood",
            f"{scene}, close detail sounds, {mood} mood",
            f"{scene}, distant background layers, {mood} mood"]

def build_kit(catalyst, scene, mood, out, music_seconds, background):
    out.mkdir(parents=True, exist_ok=True)
    spent = 0
    balance = catalyst.usage.get().plumes.remaining
    print(f"Balance: {balance} plumes")
    if balance <= 0:
        raise SystemExit("No plumes left. Ask your administrator to top up, or use a fal_test_ key.")

    prompts = ambience_prompts(scene, mood)
    print(f"Generating {len(prompts)} ambience layers...")
    sounds = catalyst.wave.generate(prompts=prompts, duration=8)
    spent += sounds.usage.plumes
    files = []
    for i, (prompt, f) in enumerate(zip(prompts, sounds.files), start=1):
        path = catalyst.download(f, out / f"ambience-{i}.mp3")
        files.append({"name": path.name, "role": "ambience", "prompt": prompt, "file_id": f.file_id})
        print(f"  saved {path}")

    music_prompt = f"{mood} underscore for: {scene}"
    print(f"Composing {music_seconds}s of music{' in the background' if background else ''}...")
    if background:
        job = catalyst.composer.compose(music_prompt, effort="low", duration=music_seconds, async_=True)
        env = job.wait(timeout=600, on_progress=lambda e: print(f"  music is {e.status}"))
        master = next(f for f in env.files if f.role == "master")
        spent += env.usage.plumes
    else:
        song = catalyst.composer.compose(music_prompt, effort="low", duration=music_seconds)
        master = song.master
        spent += song.usage.plumes
    path = catalyst.download(master, out / "music.mp3")
    files.append({"name": path.name, "role": "music", "prompt": music_prompt, "file_id": master.file_id})
    print(f"  saved {path}")

    manifest = {"scene": scene, "mood": mood, "session_id": catalyst.session_id, "plumes_spent": spent, "files": files}
    (out / "manifest.json").write_text(json.dumps(manifest, indent=2))
    print(f"Done. {spent} plumes spent. Manifest: {out / 'manifest.json'}")

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("scene")
    ap.add_argument("--mood", default="calm")
    ap.add_argument("--out", type=Path, default=Path("kit"))
    ap.add_argument("--music-seconds", type=int, default=30)
    ap.add_argument("--background", action="store_true")
    args = ap.parse_args()
    catalyst = Catalyst()
    try:
        build_kit(catalyst, args.scene, args.mood, args.out, args.music_seconds, args.background)
    except InvalidRequestError as e:   print(f"Check your input: {e.message}", file=sys.stderr)
    except AuthenticationError as e:   print(f"Your key was refused ({e.code}).", file=sys.stderr)
    except QuotaExceededError as e:    print(f"Out of plumes: {e.details}.", file=sys.stderr)
    except RateLimitError as e:        print(f"Try again in {e.retry_after or 'a few'} seconds.", file=sys.stderr)
    except APIConnectionError:         print("Could not reach the API.", file=sys.stderr)
    except APIStatusError as e:        print(f"API said {e.status} {e.code}; request {e.request_id}.", file=sys.stderr)
    else:
        return 0
    return 1

if __name__ == "__main__":
    raise SystemExit(main())