Sfx Common
src.xil_pipeline.sfx_common
Shared SFX library utilities.
Provides common functions for managing a shared SFX asset library and
generating episode-specific stems. Both XILU002_generate_SFX.py and
XILP002_producer.py delegate to this module to avoid code
duplication and to ensure that each unique sound effect is generated only
once into the shared SFX/ directory.
Module Attributes
SFX_DIR: Default path for the shared SFX asset library.
SFX_EDIT_FIELDS
module-attribute
SFX_EDIT_FIELDS = ('volume_percentage', 'ramp_in_seconds', 'ramp_out_seconds', 'play_duration', 'source')
sfx_dir
Return the per-show SFX directory, falling back to flat SFX/ if the slug subdir is absent.
Source code in src/xil_pipeline/sfx_common.py
run_banner
Context manager that prints a start header and end trailer.
Usage:
Args:
script_name: Override the script name shown in the banner.
Defaults to ``os.path.basename(sys.argv[0])``.
Source code in src/xil_pipeline/sfx_common.py
slugify_effect_key
Convert direction text to a filesystem-safe slug.
Rules
- Lowercase the entire string.
- Replace
': '(colon-space) with'_'(category separator). - Replace remaining non-alphanumeric characters with
'-'. - Collapse multiple consecutive hyphens.
- Strip leading/trailing hyphens.
- Truncate to
_MAX_SLUG_LENchars; append an 8-char SHA-256 suffix when truncated to avoid collisions between long similar keys.
Examples:
>>> slugify_effect_key("BEAT")
'beat'
>>> slugify_effect_key("SFX: DOOR OPENS, BELL CHIMES")
'sfx_door-opens-bell-chimes'
Source code in src/xil_pipeline/sfx_common.py
file_nonempty
Return True if path exists and has a non-zero size.
Uses a single os.stat() call to avoid a TOCTOU race between
an existence check and a separate size check.
Parameters:
-
path(str) –Filesystem path to test.
Returns:
-
bool–Trueif the file exists andst_size > 0,Falseotherwise.
Source code in src/xil_pipeline/sfx_common.py
resolve_source_path
Resolve a declared source to a real file, or None if absent.
Relative paths resolve against the workspace root rather than the current
directory, so source: "SFX/<slug>/file.mp3" works regardless of where
the command was run from.
Accented filenames are also tried in both Unicode normalizations. Í
can be a single codepoint (NFC) or I plus a combining acute (NFD);
the two are different byte strings and therefore different paths, but they
look identical, so a config written in one form silently fails to find an
asset stored in the other. Configs are normalized to NFC on load, but the
filesystem may hold either — filenames created on macOS are typically NFD.
Parameters:
-
source(str) –The
sourcefield from an :class:SfxEntry.
Returns:
-
str | None–The real path of the matched file, or
Nonewhen nothing matches.
Source code in src/xil_pipeline/sfx_common.py
shared_sfx_path
Return the shared library file path for an effect key.
Model-generated assets are tagged with the backend name so audio from
different generators can coexist in the same SFX/ library without one
silently shadowing another. The default backend (elevenlabs) keeps the
plain, historical filename for backward compatibility; other backends get a
.<backend> infix. Backend-independent assets (silence, source
copies) should always pass the default so they are never regenerated on a
backend switch.
Parameters:
-
sfx_dir(str) –Base directory for shared SFX assets.
-
effect_key(str) –Direction text key (e.g.
'BEAT'). -
backend(str, default:'elevenlabs') –Generating backend name. Only
'elevenlabs'is generatable now; other names still resolve so trial-era assets stay reachable.
Returns:
-
str–Full path like
SFX/beat.mp3(elevenlabs) or -
str–SFX/sfx_door-opens.audioldm2.mp3(a removed trial backend).
Source code in src/xil_pipeline/sfx_common.py
tag_mp3
tag_mp3(path: str, show: str = 'Sample Show', title: str | None = None, artist: str | None = None, lyrics: str | None = None, comments: str | None = None, cover_art_path: str | None = None) -> None
Write ID3 metadata tags to an MP3 file.
Sets Album, Genre, and Year. Optionally sets Title, Artist, Lyrics, and cover art (APIC front-cover frame).
Parameters:
-
path(str) –Path to the MP3 file.
-
show(str, default:'Sample Show') –Album name (default
"Sample Show"). -
title(str | None, default:None) –Optional TIT2 title tag (e.g. the effect key or dialogue song label).
-
artist(str | None, default:None) –Optional TPE1 artist tag (e.g. the speaker's full name).
-
lyrics(str | None, default:None) –Optional USLT unsynchronised lyrics tag (full dialogue text).
-
cover_art_path(str | None, default:None) –Optional path to a PNG or JPEG image to embed as the front-cover APIC frame. Silently skipped if the file does not exist.
Source code in src/xil_pipeline/sfx_common.py
read_sfx_grade
Return 'accurate'/'rejected' from path's XIL_GRADE frame, else ''.
Never raises — a missing file, missing ID3 header, or unknown value all
read as ungraded ('').
Source code in src/xil_pipeline/sfx_common.py
write_sfx_grade
Set (or clear) path's XIL_GRADE frame. status in {accurate, rejected, ''}.
All other ID3 frames are preserved; only the grade frame is replaced/removed.
Source code in src/xil_pipeline/sfx_common.py
sfx_edits_path
Return the edit-journal path for an SFX config: sfx_X.json → sfx_X_edits.jsonl.
append_sfx_edit
Append one edit record to the journal beside sfx_path.
Parameters:
-
sfx_path(str) –Path of the SFX config the edit was applied to.
-
key(str) –Effect key (the direction text) that was edited.
-
fields(dict) –Editable-field values;
Nonemeans "clear this override".
Source code in src/xil_pipeline/sfx_common.py
append_sfx_defaults_edit
Append one category-defaults edit record to the journal beside sfx_path.
Same append mechanics as :func:append_sfx_edit, but the record carries
"scope": "defaults" and no "key" — :func:replay_sfx_edits
applies it to data["defaults"] instead of a single effect entry.
Parameters:
-
sfx_path(str) –Path of the SFX config the edit was applied to.
-
fields(dict) –Prefixed defaults keys (e.g.
music_volume_percentage) to set;Nonemeans "clear this default".
Source code in src/xil_pipeline/sfx_common.py
replay_sfx_edits
Reapply journaled edits to the SFX config at sfx_path.
Records are applied in journal order (last write wins), with the same
semantics as the timeline-editor save route: None removes the
override, any other value sets it. Keys absent from the current
effects dict are still created (a renamed direction leaves a
harmless orphan) but reported so the caller can warn. Records with
"scope": "defaults" (from :func:append_sfx_defaults_edit) are
applied to data["defaults"] instead and never produce orphans;
records without a "scope" field (all pre-existing journals) are
treated as per-cue edits, unchanged.
Parameters:
-
sfx_path(str) –SFX config to update in place.
-
dry_run(bool, default:False) –When True, compute but do not write.
Returns:
Source code in src/xil_pipeline/sfx_common.py
456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 | |
tag_wav
tag_wav(path: str, show: str = 'Sample Show', title: str | None = None, artist: str | None = None) -> None
Write ID3 metadata tags to a WAV file.
Sets Album, Genre, and Year. Optionally sets Title and Artist.
Parameters:
-
path(str) –Path to the WAV file.
-
show(str, default:'Sample Show') –Album name (default
"Sample Show"). -
title(str | None, default:None) –Optional TIT2 title tag (e.g. the layer name).
-
artist(str | None, default:None) –Optional TPE1 artist tag.
Source code in src/xil_pipeline/sfx_common.py
ensure_shared_sfx
ensure_shared_sfx(effect_key: str, effect: SfxEntry, sfx_dir: str, defaults: dict, client: ElevenLabs | None = None, show: str = 'Sample Show', backend: SfxBackend | None = None) -> str
Ensure the shared SFX asset exists, generating if needed.
For type='silence' effects, generates silent audio locally via
pydub. For type='sfx' effects, generates audio via the supplied
backend (ElevenLabs API or local AudioLDM 2). In both cases, ID3
metadata tags (Album, Genre, Year, Title) are written to the resulting MP3.
Model-generated type='sfx' assets are stored under a backend-tagged
filename (e.g. sfx_door-opens.audioldm2.mp3) so audio from different
generators can coexist; silence and source copies keep the plain
name and are never regenerated on a backend switch.
Parameters:
-
effect_key(str) –Direction text key.
-
effect(SfxEntry) –The
SfxEntrymodel instance. -
sfx_dir(str) –Shared SFX library directory.
-
defaults(dict) –Config-level defaults (e.g.
prompt_influence). -
client(ElevenLabs | None, default:None) –ElevenLabs client instance. Used only when backend is
None(a default :class:ElevenLabsSfxBackendis built from it). -
show(str, default:'Sample Show') –Show name for the Album ID3 tag.
-
backend(SfxBackend | None, default:None) –SFX generation backend. Defaults to an ElevenLabs backend wrapping client for backward compatibility.
Returns:
-
str–The path to the shared asset file.
Raises:
-
ValueError–If the effect requires model generation but no usable backend/client is available.
Source code in src/xil_pipeline/sfx_common.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 | |
place_episode_stem
Copy a shared SFX asset to an episode stem location.
Parameters:
-
shared_path(str) –Path to the shared asset in
SFX/. -
stem_path(str) –Destination path in
stems/<TAG>/.
Returns:
Source code in src/xil_pipeline/sfx_common.py
load_sfx_entries
load_sfx_entries(script_json_path: str, sfx_json_path: str, max_duration: float | None = None, direction_types: set[str] | None = None, local_only: bool = False, sfx_dir: str | None = None) -> list[dict]
Load direction entries matched against an SFX configuration.
Reads the parsed script and SFX config, returning only direction
entries whose text field has a matching key in the SFX effects
mapping.
Parameters:
-
script_json_path(str) –Path to the parsed script JSON.
-
sfx_json_path(str) –Path to the SFX configuration JSON.
-
max_duration(float | None, default:None) –If set, exclude effects with
duration_secondsexceeding this value. -
direction_types(set[str] | None, default:None) –If set, only include entries whose
direction_typeis in this set (e.g.{"SFX", "BEAT"}).Noneincludes all categories. -
local_only(bool, default:False) –If
True, skip effects that would require an API call — i.e.type == "sfx", nosourcefile, and not already present in the sharedSFX/directory. Silence entries and source-backed entries are always included.
Returns:
-
list[dict]–A list of SFX entry dicts with
seq,text,direction_type, -
list[dict]–stem_name,sfx_type,section, andscene.
Source code in src/xil_pipeline/sfx_common.py
687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 | |
generate_sfx
generate_sfx(sfx_entries: list[dict], sfx_config: dict, stems_dir: str, sfx_dir: str | None = None, client: ElevenLabs | None = None, start_from: int = 1, backend: SfxBackend | None = None) -> None
Generate SFX stems via a two-phase shared-library workflow.
Phase 1 — For each unique effect key, ensure the shared asset exists in sfx_dir (generate via the backend or silence if missing).
Phase 2 — For each script entry, copy the shared asset to the episode stems directory with the sequence-numbered filename.
Parameters:
-
sfx_entries(list[dict]) –SFX entry dicts from :func:
load_sfx_entries. -
sfx_config(dict) –Raw SFX config dict.
-
stems_dir(str) –Episode stems output directory.
-
sfx_dir(str | None, default:None) –Shared SFX library directory.
-
client(ElevenLabs | None, default:None) –ElevenLabs client (used when backend is
None). -
start_from(int, default:1) –Only process entries with
seq >= start_from. -
backend(SfxBackend | None, default:None) –SFX generation backend. Defaults to an ElevenLabs backend wrapping client.
Source code in src/xil_pipeline/sfx_common.py
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 | |
dry_run_sfx
dry_run_sfx(sfx_entries: list[dict], sfx_config: dict, stems_dir: str, sfx_dir: str | None = None, backend_name: str = 'elevenlabs') -> None
Preview SFX generation showing status and credit estimates.
Each entry is classified as one of:
- EXISTS — episode stem already in stems/<TAG>/
- CACHED — shared asset in SFX/, will be copied (no generation)
- NEW — needs generation to SFX/, then copy
Parameters:
-
sfx_entries(list[dict]) –SFX entry dicts from :func:
load_sfx_entries. -
sfx_config(dict) –Raw SFX config dict.
-
stems_dir(str) –Episode stems directory.
-
sfx_dir(str | None, default:None) –Shared SFX library directory.
-
backend_name(str, default:'elevenlabs') –SFX backend (
'elevenlabs'). Model assets are matched against the backend-tagged filename, and local backends report generation as free instead of an API credit estimate.
Source code in src/xil_pipeline/sfx_common.py
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 | |