-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathprocessor.py
More file actions
690 lines (591 loc) · 34.3 KB
/
processor.py
File metadata and controls
690 lines (591 loc) · 34.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
import os
import shutil
import zipfile
from pathlib import Path
from typing import Callable, Optional, Dict, Any
from funscript import Funscript
from processing.speed_processing import convert_to_speed
from processing.basic_transforms import (
invert_funscript, map_funscript, limit_funscript,
normalize_funscript, mirror_up_funscript
)
from processing.combining import combine_funscripts
from processing.special_generators import make_volume_ramp
from processing.funscript_1d_to_2d import generate_alpha_beta_from_main
from processing.funscript_prostate_2d import generate_alpha_beta_prostate_from_main
from processing.motion_axis_generation import (
generate_motion_axes, copy_existing_axis_files, validate_motion_axis_config
)
from processing.phase_shift_generation import generate_all_phase_shifted_funscripts
class RestimProcessor:
def __init__(self, parameters: Dict[str, Any]):
self.params = parameters
self.temp_dir: Optional[Path] = None
self.input_path: Optional[Path] = None
self.output_dir: Optional[Path] = None
self.filename_only: str = ""
def _add_metadata(self, funscript: Funscript, file_type: str, description: str, additional_params: dict = None):
"""Add metadata to a generated funscript."""
from version import __version__, __app_name__, __url__
funscript.metadata = {
"creator": __app_name__,
"description": f"Generated by {__app_name__} v{__version__} - {description}",
"url": __url__,
"title": file_type.replace('_', ' ').title(),
"metadata": {
"generator": __app_name__,
"generator_version": __version__,
"file_type": file_type
}
}
# Add additional parameters to metadata
if additional_params:
funscript.metadata["metadata"].update(additional_params)
def process(self, input_file_path: str, progress_callback: Optional[Callable[[int, str], None]] = None) -> bool:
"""
Process the input funscript file and generate all output files.
Args:
input_file_path: Path to the input .funscript file
progress_callback: Optional callback function for progress updates (progress_percent, status_message)
Returns:
bool: True if processing completed successfully, False otherwise
"""
try:
self._update_progress(progress_callback, 0, "Initializing...")
# Setup
self.input_path = Path(input_file_path)
self.filename_only = self.input_path.stem
self._setup_directories()
# Create backup if in central mode with backups enabled
file_mgmt = self.params.get('file_management', {})
if file_mgmt.get('mode') == 'central':
if file_mgmt.get('create_backups', False):
self._create_backup(progress_callback)
else:
# Delete existing output files if backups are disabled
# This ensures fresh generation instead of reusing old files
self._delete_existing_output_files(progress_callback)
# Load main funscript
self._update_progress(progress_callback, 5, "Loading input file...")
main_funscript = Funscript.from_file(self.input_path)
# Execute processing pipeline
self._execute_pipeline(main_funscript, progress_callback)
# Cleanup if requested
if self.params['options']['delete_intermediary_files']:
self._update_progress(progress_callback, 95, "Cleaning up intermediary files...")
self._cleanup_intermediary_files()
self._update_progress(progress_callback, 100, "Processing complete!")
return True
except Exception as e:
self._update_progress(progress_callback, -1, f"Error: {str(e)}")
return False
def _setup_directories(self):
"""Create the temporary directory for intermediary files and set output directory."""
# Set output directory based on file management mode
file_mgmt = self.params.get('file_management', {})
mode = file_mgmt.get('mode', 'local')
if mode == 'central':
# Use central folder if specified
central_path = file_mgmt.get('central_folder_path', '').strip()
if central_path:
self.output_dir = Path(central_path)
# Ensure the output directory exists
self.output_dir.mkdir(parents=True, exist_ok=True)
else:
# Fallback to local mode if central path not set
self.output_dir = self.input_path.parent
else:
# Local mode: use input file directory
self.output_dir = self.input_path.parent
# Create temporary directory
self.temp_dir = self.input_path.parent / "funscript-temp"
self.temp_dir.mkdir(exist_ok=True)
def _cleanup_intermediary_files(self):
"""Remove the temporary directory and all its contents."""
if self.temp_dir and self.temp_dir.exists():
shutil.rmtree(self.temp_dir)
def _delete_existing_output_files(self, progress_callback: Optional[Callable]):
"""Delete existing restim files in central mode (when backups are disabled)."""
try:
# Collect all existing restim files for this input
existing_files = []
for file_path in self.output_dir.glob(f"{self.filename_only}.*.funscript"):
existing_files.append(file_path)
if not existing_files:
return # No existing files to delete
self._update_progress(progress_callback, 3, f"Cleaning {len(existing_files)} existing output files...")
# Delete the existing files
for file_path in existing_files:
file_path.unlink()
self._update_progress(progress_callback, 4, f"Deleted {len(existing_files)} old files")
except Exception as e:
# Log the error but don't fail the entire process
self._update_progress(progress_callback, -1, f"Warning: Failed to delete existing files: {str(e)}")
def _create_backup(self, progress_callback: Optional[Callable]):
"""Create backup zip of existing restim files in central mode before overwriting."""
try:
from datetime import datetime
# Collect all existing restim files for this input
backup_files = []
for file_path in self.output_dir.glob(f"{self.filename_only}.*.funscript"):
backup_files.append(file_path)
if not backup_files:
return # No existing files to backup
# Create backup filename with timestamp
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_zip_path = self.output_dir / f"{self.filename_only}.backup-{timestamp}.zip"
self._update_progress(progress_callback, 3, f"Creating backup: {backup_zip_path.name}")
# Create the backup zip file
with zipfile.ZipFile(backup_zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
for file_path in backup_files:
# Add file to zip with just the filename (no path)
zipf.write(file_path, file_path.name)
# Delete the original files after successful backup
for file_path in backup_files:
file_path.unlink()
self._update_progress(progress_callback, 4, f"Backup created with {len(backup_files)} files")
except Exception as e:
# Log the error but don't fail the entire process
self._update_progress(progress_callback, -1, f"Warning: Failed to create backup: {str(e)}")
def _update_progress(self, progress_callback: Optional[Callable], percent: int, message: str):
"""Update progress if callback is provided."""
if progress_callback:
progress_callback(percent, message)
def _get_temp_path(self, suffix: str) -> Path:
"""Get path for a temporary file."""
return self.temp_dir / f"{self.filename_only}.{suffix}.funscript"
def _get_output_path(self, suffix: str) -> Path:
"""Get path for a final output file."""
return self.output_dir / f"{self.filename_only}.{suffix}.funscript"
def _copy_if_exists(self, source_suffix: str, dest_suffix: str) -> bool:
"""Copy auxiliary file if it exists."""
source_path = self.input_path.parent / f"{self.filename_only}.{source_suffix}.funscript"
if source_path.exists():
dest_path = self._get_temp_path(dest_suffix)
shutil.copy2(source_path, dest_path)
return True
return False
def _output_file_exists(self, suffix: str) -> bool:
"""Check if an output file already exists in the output directory."""
output_path = self._get_output_path(suffix)
return output_path.exists()
def _copy_output_to_temp_if_exists(self, suffix: str) -> bool:
"""Copy existing output file to temp directory if it exists."""
output_path = self._get_output_path(suffix)
if output_path.exists():
dest_path = self._get_temp_path(suffix)
shutil.copy2(output_path, dest_path)
return True
return False
def _create_events_template(self, events_file_path: Path):
"""Create an empty events.yml template file with helpful comments."""
template_content = """# Custom Events File
# Add timed events to modify the generated funscript files.
# All time values are in MILLISECONDS.
# Event names must match definitions in config.event_definitions.yml
#
# Example event structure:
# events:
# - time: 60000 # Event at 1 minute (60,000 ms)
# name: edge # Event name from event_definitions.yml
# params: # Optional parameter overrides
# duration_ms: 15000
events:
# Add your custom events here
"""
try:
with open(events_file_path, 'w', encoding='utf-8') as f:
f.write(template_content)
except Exception as e:
# Don't fail the entire process if template creation fails
print(f"Warning: Failed to create events template: {str(e)}")
def _execute_pipeline(self, main_funscript: Funscript, progress_callback: Optional[Callable]):
"""Execute the complete processing pipeline."""
# Phase 1: Auxiliary File Preparation (10-20%)
self._update_progress(progress_callback, 10, "Preparing auxiliary files...")
# Check if we should overwrite existing output files
overwrite_existing = self.params.get('options', {}).get('overwrite_existing_files', False)
# Always reuse ramp and speed if they exist (they are intentionally provided)
# These are only generated in temp folder if not present
ramp_exists = self._copy_if_exists("ramp", "ramp")
speed_exists = self._copy_if_exists("speed", "speed")
# Copy alpha/beta files based on overwrite setting
# When overwrite=False: reuse existing alpha/beta from output directory if available
# When overwrite=True: regenerate alpha/beta even if they exist
alpha_exists = False if overwrite_existing else self._copy_output_to_temp_if_exists("alpha")
beta_exists = False if overwrite_existing else self._copy_output_to_temp_if_exists("beta")
# Generate speed early if needed for alpha/beta generation
speed_funscript = None
if not alpha_exists or not beta_exists:
# Need speed funscript for alpha/beta generation
if not speed_exists:
self._update_progress(progress_callback, 12, "Generating speed file for alpha/beta...")
speed_funscript = convert_to_speed(
main_funscript,
self.params['general']['speed_window_size'],
self.params['speed']['interpolation_interval']
)
speed_funscript.save_to_path(self._get_temp_path("speed"))
speed_exists = True
else:
speed_funscript = Funscript.from_file(self._get_temp_path("speed"))
# Always generate alpha and beta files (they are mandatory)
if not alpha_exists or not beta_exists:
self._update_progress(progress_callback, 15, "Generating alpha and beta files from main funscript...")
alpha_beta_config = self.params.get('alpha_beta_generation', {})
points_per_second = alpha_beta_config.get('points_per_second', 25)
algorithm = alpha_beta_config.get('algorithm', 'circular')
min_distance_from_center = alpha_beta_config.get('min_distance_from_center', 0.1)
speed_threshold_percent = alpha_beta_config.get('speed_threshold_percent', 50)
direction_change_probability = alpha_beta_config.get('direction_change_probability', 0.1)
alpha_funscript, beta_funscript = generate_alpha_beta_from_main(
main_funscript, speed_funscript, points_per_second, algorithm, min_distance_from_center, speed_threshold_percent, direction_change_probability
)
if not alpha_exists:
alpha_funscript.save_to_path(self._get_temp_path("alpha"))
alpha_exists = True
if not beta_exists:
beta_funscript.save_to_path(self._get_temp_path("beta"))
beta_exists = True
# Generate prostate alpha and beta files if prostate generation is enabled
if self.params.get('prostate_generation', {}).get('generate_prostate_files', True):
# Copy prostate files based on overwrite setting from output directory
# When overwrite=False: reuse existing prostate files if available
# When overwrite=True: regenerate prostate files even if they exist
alpha_prostate_exists = False if overwrite_existing else self._copy_output_to_temp_if_exists("alpha-prostate")
beta_prostate_exists = False if overwrite_existing else self._copy_output_to_temp_if_exists("beta-prostate")
if not alpha_prostate_exists or not beta_prostate_exists:
self._update_progress(progress_callback, 17, "Generating prostate alpha and beta files from main funscript...")
prostate_config = self.params.get('prostate_generation', {})
prostate_points_per_second = prostate_config.get('points_per_second', 25)
prostate_algorithm = prostate_config.get('algorithm', 'tear-shaped')
prostate_min_distance = prostate_config.get('min_distance_from_center', 0.5)
prostate_generate_from_inverted = prostate_config.get('generate_from_inverted', True)
alpha_prostate_funscript, beta_prostate_funscript = generate_alpha_beta_prostate_from_main(
main_funscript, prostate_points_per_second, prostate_algorithm,
prostate_min_distance, prostate_generate_from_inverted
)
if not alpha_prostate_exists:
alpha_prostate_funscript.save_to_path(self._get_temp_path("alpha-prostate"))
if not beta_prostate_exists:
beta_prostate_funscript.save_to_path(self._get_temp_path("beta-prostate"))
# Motion Axis Generation (18-19%)
if self.params.get('positional_axes', {}).get('generate_motion_axis', False):
self._update_progress(progress_callback, 18, "Generating motion axis files...")
motion_config = self.params.get('positional_axes', {})
# Validate configuration
config_errors = validate_motion_axis_config(motion_config)
if config_errors:
print(f"Motion axis configuration errors: {config_errors}")
else:
# Copy existing axis files first
enabled_axes = [axis for axis in ['e1', 'e2', 'e3', 'e4']
if motion_config.get(axis, {}).get('enabled', False)]
copied_files = copy_existing_axis_files(
self.input_path.parent,
self.temp_dir,
self.filename_only,
enabled_axes
)
# Generate any missing axis files
axes_to_generate = [axis for axis in enabled_axes if axis not in copied_files]
if axes_to_generate:
generate_config = {axis: motion_config[axis] for axis in axes_to_generate}
generated_files = generate_motion_axes(
main_funscript,
generate_config,
self.temp_dir,
self.filename_only
)
# Phase-Shifted Output Generation (19%) — handled independently per mode
axes_config = self.params.get('positional_axes', {})
# 3P (legacy) phase shift: alpha/beta
if axes_config.get('generate_legacy', False):
phase_shift_config = axes_config.get('phase_shift', {})
if phase_shift_config.get('enabled', False):
self._update_progress(progress_callback, 19, "Generating phase-shifted versions (3P)...")
print(f"3P phase shift enabled: delay={phase_shift_config.get('delay_percentage')}%")
funscripts_to_shift = {}
for key in ['alpha', 'beta']:
path = self._get_temp_path(key)
if path.exists():
funscripts_to_shift[key] = Funscript.from_file(path)
if funscripts_to_shift:
shifted = generate_all_phase_shifted_funscripts(
funscripts_to_shift, main_funscript,
phase_shift_config.get('delay_percentage', 10.0),
phase_shift_config.get('min_segment_duration', 0.25)
)
for key, funscript in shifted.items():
funscript.save_to_path(self._get_temp_path(key))
print(f" Saved phase-shifted file: {self._get_temp_path(key).name}")
else:
print(" Warning: No alpha/beta funscripts found to phase-shift (3P)")
# 4P (motion axis) phase shift: e1-e4
if axes_config.get('generate_motion_axis', False):
ma_phase_config = axes_config.get('motion_axis_phase_shift', axes_config.get('phase_shift', {}))
if ma_phase_config.get('enabled', False):
self._update_progress(progress_callback, 19, "Generating phase-shifted versions (4P)...")
print(f"4P phase shift enabled: delay={ma_phase_config.get('delay_percentage')}%")
funscripts_to_shift = {}
for axis in ['e1', 'e2', 'e3', 'e4']:
path = self._get_temp_path(axis)
if path.exists():
funscripts_to_shift[axis] = Funscript.from_file(path)
if funscripts_to_shift:
shifted = generate_all_phase_shifted_funscripts(
funscripts_to_shift, main_funscript,
ma_phase_config.get('delay_percentage', 10.0),
ma_phase_config.get('min_segment_duration', 0.25)
)
for key, funscript in shifted.items():
funscript.save_to_path(self._get_temp_path(key))
print(f" Saved phase-shifted file: {self._get_temp_path(key).name}")
else:
print(" Warning: No E1-E4 funscripts found to phase-shift (4P)")
# Phase 2: Core File Generation (20-40%)
self._update_progress(progress_callback, 20, "Generating speed file...")
# Generate speed if not already generated earlier
if not speed_exists and speed_funscript is None:
speed_funscript = convert_to_speed(
main_funscript,
self.params['general']['speed_window_size'],
self.params['speed']['interpolation_interval']
)
speed_funscript.save_to_path(self._get_temp_path("speed"))
elif speed_funscript is None:
speed_funscript = Funscript.from_file(self._get_temp_path("speed"))
# Invert speed
speed_inverted = invert_funscript(speed_funscript)
speed_inverted.save_to_path(self._get_temp_path("speed_inverted"))
self._update_progress(progress_callback, 25, "Generating acceleration file...")
# Generate acceleration from speed
accel_funscript = convert_to_speed(
speed_funscript,
self.params['general']['accel_window_size'],
self.params['speed']['interpolation_interval']
)
accel_funscript.save_to_path(self._get_temp_path("accel"))
self._update_progress(progress_callback, 30, "Generating volume ramp...")
# Generate volume ramp if not provided
if not ramp_exists:
ramp_percent_per_hour = self.params.get('volume', {}).get('ramp_percent_per_hour', 15)
ramp_funscript = make_volume_ramp(main_funscript, ramp_percent_per_hour)
ramp_funscript.save_to_path(self._get_temp_path("ramp"))
else:
ramp_funscript = Funscript.from_file(self._get_temp_path("ramp"))
# Invert ramp
ramp_inverted = invert_funscript(ramp_funscript)
ramp_inverted.save_to_path(self._get_temp_path("ramp_inverted"))
# Phase 3: Frequency Processing (40-50%)
self._update_progress(progress_callback, 40, "Processing frequency data...")
# Check if pulse_frequency already exists
if not overwrite_existing and self._output_file_exists("pulse_frequency"):
self._update_progress(progress_callback, 42, "Reusing existing pulse_frequency...")
pulse_frequency = Funscript.from_file(self._get_output_path("pulse_frequency"))
else:
# Load alpha funscript for pulse frequency generation
alpha_funscript = Funscript.from_file(self._get_temp_path("alpha"))
# Combine alpha with speed (no pre-mapping)
pulse_frequency_combined = combine_funscripts(
speed_funscript,
alpha_funscript,
self.params['frequency']['pulse_frequency_combine_ratio']
)
# Map the combined result to the pulse frequency range (min/max)
pulse_frequency = map_funscript(
pulse_frequency_combined,
self.params['frequency']['pulse_freq_min'],
self.params['frequency']['pulse_freq_max']
)
self._add_metadata(pulse_frequency, "pulse_frequency", "Pulse frequency modulation", {
"pulse_freq_min": self.params['frequency']['pulse_freq_min'],
"pulse_freq_max": self.params['frequency']['pulse_freq_max'],
"pulse_frequency_combine_ratio": self.params['frequency']['pulse_frequency_combine_ratio']
})
pulse_frequency.save_to_path(self._get_output_path("pulse_frequency"))
# Generate alpha-prostate output using inverted main funscript (only if enabled)
if self.params.get('prostate_generation', {}).get('generate_prostate_files', True):
main_inverted = invert_funscript(main_funscript)
self._add_metadata(main_inverted, "alpha-prostate", "Inverted main funscript for prostate stimulation")
main_inverted.save_to_path(self._get_output_path("alpha-prostate"))
else:
main_inverted = invert_funscript(main_funscript)
# Check if frequency already exists
if not overwrite_existing and self._output_file_exists("frequency"):
self._update_progress(progress_callback, 45, "Reusing existing frequency...")
frequency = Funscript.from_file(self._get_output_path("frequency"))
else:
# Primary frequency generation
frequency = combine_funscripts(
ramp_funscript,
speed_funscript,
self.params['frequency']['frequency_ramp_combine_ratio']
)
self._add_metadata(frequency, "frequency", "Primary frequency modulation", {
"frequency_ramp_combine_ratio": self.params['frequency']['frequency_ramp_combine_ratio']
})
frequency.save_to_path(self._get_output_path("frequency"))
# Phase 4: Volume Processing (50-70%)
self._update_progress(progress_callback, 50, "Processing volume data...")
# Check if volume already exists
if not overwrite_existing and self._output_file_exists("volume"):
self._update_progress(progress_callback, 52, "Reusing existing volume...")
volume = Funscript.from_file(self._get_output_path("volume"))
else:
# Standard volume
volume = combine_funscripts(
ramp_funscript,
speed_funscript,
self.params['volume']['volume_ramp_combine_ratio'],
self.params['general']['rest_level'],
self.params['general']['ramp_up_duration_after_rest']
)
# Volume normalization
if self.params['options']['normalize_volume']:
volume_not_normalized = volume.copy()
volume_not_normalized.save_to_path(self._get_temp_path("volume_not_normalized"))
volume = normalize_funscript(volume)
self._add_metadata(volume, "volume", "Standard volume control", {
"volume_ramp_combine_ratio": self.params['volume']['volume_ramp_combine_ratio'],
"rest_level": self.params['general']['rest_level'],
"ramp_up_duration_after_rest": self.params['general']['ramp_up_duration_after_rest'],
"normalized": self.params['options']['normalize_volume']
})
volume.save_to_path(self._get_output_path("volume"))
# Prostate volume (only if enabled)
if self.params.get('prostate_generation', {}).get('generate_prostate_files', True):
# Check if volume-prostate already exists
if not overwrite_existing and self._output_file_exists("volume-prostate"):
self._update_progress(progress_callback, 55, "Reusing existing volume-prostate...")
else:
prostate_volume = combine_funscripts(
ramp_funscript,
speed_funscript,
self.params['volume']['volume_ramp_combine_ratio'] * self.params['volume']['prostate_volume_multiplier'],
self.params['volume']['prostate_rest_level'],
self.params['general']['ramp_up_duration_after_rest']
)
self._add_metadata(prostate_volume, "volume-prostate", "Prostate volume control", {
"volume_ramp_combine_ratio": self.params['volume']['volume_ramp_combine_ratio'],
"prostate_volume_multiplier": self.params['volume']['prostate_volume_multiplier'],
"prostate_rest_level": self.params['volume']['prostate_rest_level'],
"ramp_up_duration_after_rest": self.params['general']['ramp_up_duration_after_rest']
})
prostate_volume.save_to_path(self._get_output_path("volume-prostate"))
# Phase 5: Pulse Parameters (70-90%)
self._update_progress(progress_callback, 70, "Processing pulse parameters...")
# Check if pulse_rise_time already exists
if not overwrite_existing and self._output_file_exists("pulse_rise_time"):
self._update_progress(progress_callback, 72, "Reusing existing pulse_rise_time...")
else:
# Generate pulse rise time using ramp_inverted and speed_inverted directly
# Simplified approach without beta dependency
pulse_rise_time = combine_funscripts(
ramp_inverted,
speed_inverted,
self.params['pulse']['pulse_rise_combine_ratio']
)
pulse_rise_time = map_funscript(
pulse_rise_time,
self.params['pulse']['pulse_rise_min'],
self.params['pulse']['pulse_rise_max']
)
self._add_metadata(pulse_rise_time, "pulse_rise_time", "Pulse rise time modulation", {
"pulse_rise_combine_ratio": self.params['pulse']['pulse_rise_combine_ratio'],
"pulse_rise_min": self.params['pulse']['pulse_rise_min'],
"pulse_rise_max": self.params['pulse']['pulse_rise_max']
})
pulse_rise_time.save_to_path(self._get_output_path("pulse_rise_time"))
# Check if pulse_width already exists
if not overwrite_existing and self._output_file_exists("pulse_width"):
self._update_progress(progress_callback, 75, "Reusing existing pulse_width...")
else:
# Generate pulse width using inverted original funscript
# Reuse main_inverted from alpha-prostate generation above
pulse_width_main = limit_funscript(
main_inverted,
self.params['pulse']['pulse_width_min'],
self.params['pulse']['pulse_width_max']
)
pulse_width_main.save_to_path(self._get_temp_path("pulse_width-main"))
# Combine with speed for final pulse width
pulse_width = combine_funscripts(
speed_funscript,
pulse_width_main,
self.params['pulse']['pulse_width_combine_ratio']
)
self._add_metadata(pulse_width, "pulse_width", "Pulse width modulation", {
"pulse_width_min": self.params['pulse']['pulse_width_min'],
"pulse_width_max": self.params['pulse']['pulse_width_max'],
"pulse_width_combine_ratio": self.params['pulse']['pulse_width_combine_ratio']
})
pulse_width.save_to_path(self._get_output_path("pulse_width"))
# Phase 6: Copy remaining outputs (90-95%)
self._update_progress(progress_callback, 90, "Finalizing outputs...")
# Copy alpha and beta to outputs if they exist
if alpha_exists:
shutil.copy2(self._get_temp_path("alpha"), self._get_output_path("alpha"))
if beta_exists:
shutil.copy2(self._get_temp_path("beta"), self._get_output_path("beta"))
# Copy prostate alpha and beta to outputs if they exist and prostate generation is enabled
if self.params.get('prostate_generation', {}).get('generate_prostate_files', True):
alpha_temp_path = self._get_temp_path("alpha-prostate")
if alpha_temp_path.exists():
shutil.copy2(alpha_temp_path, self._get_output_path("alpha-prostate"))
beta_temp_path = self._get_temp_path("beta-prostate")
if beta_temp_path.exists():
shutil.copy2(beta_temp_path, self._get_output_path("beta-prostate"))
axes_config = self.params.get('positional_axes', {})
# Copy motion axis files to outputs if 4P mode is enabled
if axes_config.get('generate_motion_axis', False):
for axis_name in ['e1', 'e2', 'e3', 'e4']:
if axes_config.get(axis_name, {}).get('enabled', False):
temp_path = self._get_temp_path(axis_name)
if temp_path.exists():
shutil.copy2(temp_path, self._get_output_path(axis_name))
# Copy phase-shifted outputs — 3P (legacy)
if axes_config.get('generate_legacy', False):
ps_config = axes_config.get('phase_shift', {})
if ps_config.get('enabled', False):
for suffix in ['alpha-2', 'beta-2']:
temp_path = self._get_temp_path(suffix)
if temp_path.exists():
shutil.copy2(temp_path, self._get_output_path(suffix))
# Copy phase-shifted outputs — 4P (motion axis)
if axes_config.get('generate_motion_axis', False):
ma_ps_config = axes_config.get('motion_axis_phase_shift', axes_config.get('phase_shift', {}))
if ma_ps_config.get('enabled', False):
for axis_name in ['e1', 'e2', 'e3', 'e4']:
if axes_config.get(axis_name, {}).get('enabled', False):
suffix = f"{axis_name}-2"
temp_path = self._get_temp_path(suffix)
if temp_path.exists():
shutil.copy2(temp_path, self._get_output_path(suffix))
# Create empty events.yml template if it doesn't exist
# Events file is always created in local directory (next to source .funscript)
events_file_path = self.input_path.parent / f"{self.filename_only}.events.yml"
if not events_file_path.exists():
self._create_events_template(events_file_path)
# Generate optional inverted files if enabled
if self.params['advanced']['enable_pulse_frequency_inversion']:
if not overwrite_existing and self._output_file_exists("pulse_frequency_inverted"):
self._update_progress(progress_callback, 92, "Reusing existing pulse_frequency_inverted...")
else:
pulse_freq_inverted = invert_funscript(pulse_frequency)
self._add_metadata(pulse_freq_inverted, "pulse_frequency_inverted", "Inverted pulse frequency modulation")
pulse_freq_inverted.save_to_path(self._get_output_path("pulse_frequency_inverted"))
if self.params['advanced']['enable_volume_inversion']:
if not overwrite_existing and self._output_file_exists("volume_inverted"):
self._update_progress(progress_callback, 93, "Reusing existing volume_inverted...")
else:
volume_inverted = invert_funscript(volume)
self._add_metadata(volume_inverted, "volume_inverted", "Inverted volume control")
volume_inverted.save_to_path(self._get_output_path("volume_inverted"))
if self.params['advanced']['enable_frequency_inversion']:
if not overwrite_existing and self._output_file_exists("frequency_inverted"):
self._update_progress(progress_callback, 94, "Reusing existing frequency_inverted...")
else:
freq_inverted = invert_funscript(frequency)
self._add_metadata(freq_inverted, "frequency_inverted", "Inverted frequency modulation")
freq_inverted.save_to_path(self._get_output_path("frequency_inverted"))