mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
Added CLI parameter to override specific style JSON values
This commit is contained in:
7 files changed
+2031
-1678
No files matched your search
+37
-4
@@ -46,15 +46,43 @@ DEFAULT_STYLE_PARAMS = {
|
||||
}
|
||||
|
||||
|
||||
def load_style_params(style_params_json, logger):
|
||||
def apply_style_overrides(style_params, overrides, logger):
|
||||
"""Recursively applies overrides to the style parameters."""
|
||||
for key, value in overrides.items():
|
||||
keys = key.split('.')
|
||||
current_level = style_params
|
||||
for i, k in enumerate(keys):
|
||||
if i == len(keys) - 1:
|
||||
if k in current_level:
|
||||
# Attempt to cast the value to the type of the existing value
|
||||
try:
|
||||
original_type = type(current_level[k])
|
||||
if original_type == bool:
|
||||
# Handle boolean conversion
|
||||
value = value.lower() in ('true', '1', 't', 'y', 'yes')
|
||||
else:
|
||||
value = original_type(value)
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.warning(f"Could not cast override value '{value}' for key '{key}' to original type. Using as string. Error: {e}")
|
||||
current_level[k] = value
|
||||
logger.info(f"Overrode style: {key} = {value}")
|
||||
else:
|
||||
logger.warning(f"Override key '{key}' not found in style parameters.")
|
||||
elif k in current_level and isinstance(current_level[k], dict):
|
||||
current_level = current_level[k]
|
||||
else:
|
||||
logger.warning(f"Override key part '{k}' not found or not a dictionary for key '{key}'.")
|
||||
break
|
||||
|
||||
|
||||
def load_style_params(style_params_json, style_overrides, logger):
|
||||
"""Loads style parameters from a JSON file or uses defaults."""
|
||||
style_params = {}
|
||||
if style_params_json:
|
||||
try:
|
||||
with open(style_params_json, "r") as f:
|
||||
style_params = json.loads(f.read())
|
||||
logger.info(f"Loaded style parameters from {style_params_json}")
|
||||
# You might want to add validation here to ensure the structure matches expectations
|
||||
return style_params
|
||||
except FileNotFoundError:
|
||||
logger.error(f"Style parameters configuration file not found: {style_params_json}")
|
||||
sys.exit(1)
|
||||
@@ -66,7 +94,12 @@ def load_style_params(style_params_json, logger):
|
||||
sys.exit(1)
|
||||
else:
|
||||
logger.info("No style parameters JSON file provided. Using default styles.")
|
||||
return DEFAULT_STYLE_PARAMS
|
||||
style_params = DEFAULT_STYLE_PARAMS
|
||||
|
||||
if style_overrides:
|
||||
apply_style_overrides(style_params, style_overrides, logger)
|
||||
|
||||
return style_params
|
||||
|
||||
def setup_title_format(style_params):
|
||||
"""Sets up the title format dictionary from style parameters."""
|
||||
|
||||
@@ -67,6 +67,7 @@ class KaraokePrep:
|
||||
subtitle_offset_ms=0,
|
||||
# Style Configuration
|
||||
style_params_json=None,
|
||||
style_overrides=None,
|
||||
# Add the new parameter
|
||||
skip_separation=False,
|
||||
# YouTube/Online Configuration
|
||||
@@ -124,13 +125,23 @@ class KaraokePrep:
|
||||
|
||||
# Style Config - Keep needed ones
|
||||
self.render_bounding_boxes = render_bounding_boxes # Passed to VideoGenerator
|
||||
self.style_params_json = style_params_json # Passed to LyricsProcessor
|
||||
self.style_params_json = style_params_json
|
||||
self.style_overrides = style_overrides
|
||||
self.temp_style_file = None
|
||||
|
||||
# YouTube/Online Config
|
||||
self.cookies_str = cookies_str # Passed to metadata extraction and file download
|
||||
|
||||
# Load style parameters using the config module
|
||||
self.style_params = load_style_params(self.style_params_json, self.logger)
|
||||
self.style_params = load_style_params(self.style_params_json, self.style_overrides, self.logger)
|
||||
|
||||
# If overrides were applied, write to a temp file and update the path
|
||||
if self.style_overrides:
|
||||
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".json") as temp_file:
|
||||
json.dump(self.style_params, temp_file, indent=2)
|
||||
self.temp_style_file = temp_file.name
|
||||
self.style_params_json = self.temp_style_file
|
||||
self.logger.info(f"Style overrides applied. Using temporary style file: {self.temp_style_file}")
|
||||
|
||||
# Set up title and end formats using the config module
|
||||
self.title_format = setup_title_format(self.style_params)
|
||||
@@ -199,6 +210,15 @@ class KaraokePrep:
|
||||
else:
|
||||
self.logger.debug(f"Overall output dir {self.output_dir} already exists")
|
||||
|
||||
def __del__(self):
|
||||
# Cleanup the temporary style file if it was created
|
||||
if self.temp_style_file and os.path.exists(self.temp_style_file):
|
||||
try:
|
||||
os.remove(self.temp_style_file)
|
||||
self.logger.debug(f"Removed temporary style file: {self.temp_style_file}")
|
||||
except OSError as e:
|
||||
self.logger.warning(f"Error removing temporary style file {self.temp_style_file}: {e}")
|
||||
|
||||
# Compatibility methods for tests - these call the new functions in metadata.py
|
||||
def extract_info_for_online_media(self, input_url=None, input_artist=None, input_title=None):
|
||||
"""Compatibility method that calls the function in metadata.py"""
|
||||
|
||||
@@ -215,6 +215,11 @@ async def async_main():
|
||||
"--style_params_json",
|
||||
help="Optional: Path to JSON file containing style configuration. Example: --style_params_json='/path/to/style_params.json'",
|
||||
)
|
||||
style_group.add_argument(
|
||||
"--style_override",
|
||||
action="append",
|
||||
help="Optional: Override a style parameter. Can be used multiple times. Example: --style_override 'intro.background_image=/path/to/new_image.png'",
|
||||
)
|
||||
|
||||
# Finalisation Configuration
|
||||
finalise_group = parser.add_argument_group("Finalisation Configuration")
|
||||
@@ -283,6 +288,17 @@ async def async_main():
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Process style overrides
|
||||
style_overrides = {}
|
||||
if args.style_override:
|
||||
for override in args.style_override:
|
||||
try:
|
||||
key, value = override.split("=", 1)
|
||||
style_overrides[key] = value
|
||||
except ValueError:
|
||||
logger.error(f"Invalid style override format: {override}. Must be in 'key=value' format.")
|
||||
sys.exit(1)
|
||||
|
||||
# Handle test email template case first
|
||||
if args.test_email_template:
|
||||
log_level = getattr(logging, args.log_level.upper())
|
||||
@@ -354,6 +370,7 @@ async def async_main():
|
||||
skip_transcription_review=args.skip_transcription_review,
|
||||
subtitle_offset_ms=args.subtitle_offset_ms,
|
||||
style_params_json=args.style_params_json,
|
||||
style_overrides=style_overrides,
|
||||
)
|
||||
# No await needed for constructor
|
||||
kprep = kprep_coroutine
|
||||
@@ -671,6 +688,7 @@ async def async_main():
|
||||
skip_transcription_review=args.skip_transcription_review,
|
||||
subtitle_offset_ms=args.subtitle_offset_ms,
|
||||
style_params_json=args.style_params_json,
|
||||
style_overrides=style_overrides,
|
||||
)
|
||||
# No await needed for constructor
|
||||
kprep = kprep_coroutine
|
||||
|
||||
Generated
+1892
-1671
File diff suppressed because it is too large.
Load diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "karaoke-gen"
|
||||
version = "0.61.1"
|
||||
version = "0.62.0"
|
||||
description = "Generate karaoke videos with synchronized lyrics. Handles the entire process from downloading audio and lyrics to creating the final video with title screens."
|
||||
authors = ["Andrew Beveridge <andrew@beveridge.uk>"]
|
||||
license = "MIT"
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
Current Stripe Setup: You mentioned you already have a Stripe Payment Link on nomadkaraoke.com. Can you share:
|
||||
What Stripe product/price ID is currently configured for the $2 payment?
|
||||
- I haven't created a product for this yet; depending on your guidance I can do so but I wanted to talk it through to understand how this will work first.
|
||||
- I have an existing product (prod_QJUtpNwZBpNOWz) and payment link (plink_1PSsYyJqOK5vtxo4A1gBQUUO) for my manual karaoke production workflow which is exposed to customers at https://buy.stripe.com/dR67sx4wZcdt2DC9AA and I don't want to modify this.
|
||||
|
||||
Do you want to keep using Payment Links or switch to Checkout Sessions?
|
||||
- Not sure, what are the pros/cons? I've found the Payment Link setup to be pretty easy to configure and use but I don't know much more about other Stripe offerings. Please guide me.
|
||||
|
||||
What's the current success/cancel URL setup?
|
||||
- Not sure, probably not set up yet, please guide me.
|
||||
|
||||
|
||||
Token Delivery: How do you want to deliver the access token to customers after payment?
|
||||
- Email them the token automatically?
|
||||
- Show token on a success page?
|
||||
Probably both; I'd like to make the user flow frictionless so after payment they should see a success page
|
||||
|
||||
Token Configuration: For the $2 payment, what should the token provide?
|
||||
How many uses? (1 video generation for $2?)
|
||||
Any expiration time?
|
||||
Any special description/branding?
|
||||
|
||||
|
||||
Domain Setup: Do you control the nomadkaraoke.com website, or is this a separate system? I need to understand how to:
|
||||
Modify the existing payment button
|
||||
Set up the success/failure flow
|
||||
Ensure the domains can communicate
|
||||
|
||||
|
||||
Stripe Environment: Are you ready to use live Stripe keys, or should we start with test mode?
|
||||
|
||||
|
||||
Email Service: Do you have any preferred email service (SendGrid, Mailgun, etc.) for sending tokens, or should I implement a simple SMTP solution?
|
||||
|
||||
@@ -87,6 +87,7 @@ def mock_base_args():
|
||||
subtitle_offset_ms=0,
|
||||
skip_transcription_review=False,
|
||||
style_params_json=None,
|
||||
style_override=None,
|
||||
enable_cdg=False,
|
||||
enable_txt=False,
|
||||
brand_prefix=None,
|
||||
@@ -655,3 +656,29 @@ async def test_clipboard_copy_failure(mock_copy, mock_exists, mock_chdir, mock_k
|
||||
call("http://share.link/fake"),
|
||||
call("http://youtu.be/fake")
|
||||
], any_order=True)
|
||||
|
||||
|
||||
@patch("karaoke_gen.utils.gen_cli.KaraokePrep")
|
||||
async def test_style_override_parsing(mock_kprep_class, mock_base_args):
|
||||
"""Test that --style_override arguments are parsed correctly."""
|
||||
mock_base_args.args = ["Artist", "Title"]
|
||||
mock_base_args.style_override = ["intro.background_image=new_image.png", "end.video_duration=10"]
|
||||
|
||||
mock_kprep_instance = MagicMock()
|
||||
mock_kprep_class.return_value = mock_kprep_instance
|
||||
mock_kprep_instance.process = AsyncMock(return_value=[MOCK_PREP_TRACK])
|
||||
|
||||
with patch("karaoke_gen.utils.gen_cli.argparse.ArgumentParser") as mock_parser, \
|
||||
patch("karaoke_gen.utils.gen_cli.os.chdir"), \
|
||||
patch("karaoke_gen.utils.gen_cli.os.path.exists", return_value=True), \
|
||||
patch("karaoke_gen.utils.gen_cli.KaraokeFinalise"):
|
||||
mock_parser.return_value.parse_args.return_value = mock_base_args
|
||||
await gen_cli.async_main()
|
||||
|
||||
mock_kprep_class.assert_called_once()
|
||||
prep_kwargs = mock_kprep_class.call_args.kwargs
|
||||
expected_overrides = {
|
||||
"intro.background_image": "new_image.png",
|
||||
"end.video_duration": "10"
|
||||
}
|
||||
assert prep_kwargs["style_overrides"] == expected_overrides
|
||||
Reference in new issue
Block a user