tictacsync 1.0.1a0__py3-none-any.whl → 1.1.0a0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of tictacsync might be problematic. Click here for more details.

tictacsync/mamsync.py ADDED
@@ -0,0 +1,387 @@
1
+
2
+ # I know, the following is ugly, but I need those try's to
3
+ # run the command in my dev setting AND from
4
+ # a deployment set-up... surely I'm setting
5
+ # things wrong [TODO]: find why and clean up this mess
6
+
7
+ try:
8
+ from . import yaltc
9
+ from . import device_scanner
10
+ from . import timeline
11
+ from . import multi2polywav
12
+ from . import mamconf
13
+ except:
14
+ import yaltc
15
+ import device_scanner
16
+ import timeline
17
+ import multi2polywav
18
+ import mamconf
19
+
20
+ import argparse, tempfile, configparser
21
+ from loguru import logger
22
+ from pathlib import Path
23
+ # import os, sys
24
+ import os, sys, sox, platformdirs, shutil, filecmp
25
+ from rich.progress import track
26
+ # from pprint import pprint
27
+ from rich.console import Console
28
+ # from rich.text import Text
29
+ from rich.table import Table
30
+ from rich import print
31
+ from pprint import pprint, pformat
32
+ import numpy as np
33
+
34
+ DEL_TEMP = False
35
+ # CONF_FILE = 'mamsync.cfg'
36
+ # LOG_FILE = 'mamdone.txt'
37
+
38
+ av_file_extensions = \
39
+ """MOV webm mkv flv flv vob ogv ogg drc gif gifv mng avi MTS M2TS TS mov qt
40
+ wmv yuv rm rmvb viv asf amv mp4 m4p m4v mpg mp2 mpeg mpe mpv mpg mpeg m2v
41
+ m4v svi 3gp 3g2 mxf roq nsv flv f4v f4p f4a f4b 3gp aa aac aax act aiff alac
42
+ amr ape au awb dss dvf flac gsm iklax ivs m4a m4b m4p mmf mp3 mpc msv nmf
43
+ ogg oga mogg opus ra rm raw rf64 sln tta voc vox wav wma wv webm 8svx cda""".split()
44
+
45
+ logger.remove()
46
+ # logger.add(sys.stdout, level="DEBUG")
47
+ # logger.add(sys.stdout, filter=lambda r: r["function"] == "main")
48
+ # logger.add(sys.stdout, filter=lambda r: r["function"] == "_write_ISOs")
49
+
50
+ def process_single(file, args):
51
+ # argument is a single file
52
+ m = device_scanner.media_at_path(None, Path(file))
53
+ if args.plotting:
54
+ print('\nPlots can be zoomed and panned...')
55
+ print('Close window for next one.')
56
+ a_rec = yaltc.Recording(m, do_plots=args.plotting)
57
+ time = a_rec.get_start_time()
58
+ # time = a_rec.get_start_time(plots=args.plotting)
59
+ if time != None:
60
+ frac_time = int(time.microsecond / 1e2)
61
+ d = '%s.%s'%(time.strftime("%Y-%m-%d %H:%M:%S"),frac_time)
62
+ if args.terse:
63
+ print('%s UTC:%s pulse: %i in chan %i'%(file, d, a_rec.sync_position,
64
+ a_rec.TicTacCode_channel))
65
+ else:
66
+ print('\nRecording started at [gold1]%s[/gold1] UTC'%d)
67
+ print('true sample rate: [gold1]%.3f Hz[/gold1]'%a_rec.true_samplerate)
68
+ print('first sync at [gold1]%i[/gold1] samples in channel %i'%(a_rec.sync_position,
69
+ a_rec.TicTacCode_channel))
70
+ print('N.B.: all results are precise to the displayed digits!\n')
71
+ else:
72
+ if args.terse:
73
+ print('%s UTC: None'%(file))
74
+ else:
75
+ print('Start time couldnt be determined')
76
+ sys.exit(1)
77
+
78
+ def process_lag_adjustement(media_object):
79
+ # trim channels that are lagging (as stated in tracks.txt)
80
+ # replace the old file, and rename the old one with .wavbk
81
+ # if .wavbk exist, process was done already, so dont process
82
+ # returns nothing
83
+ lags = media_object.device.tracks.lag_values
84
+ logger.debug('will process %s lags'%[lags])
85
+ channels = timeline._sox_split_channels(media_object.path)
86
+ # add bk to file on filesystem, but media_object.path is unchanged (?)
87
+ backup_name = str(media_object.path) + 'bk'
88
+ if Path(backup_name).exists():
89
+ logger.debug('%s exists, so return now.'%backup_name)
90
+ return
91
+ media_object.path.replace(backup_name)
92
+ logger.debug('channels %s'%channels)
93
+ def _trim(lag, chan_file):
94
+ # for lag
95
+ if lag == None:
96
+ return chan_file
97
+ else:
98
+ logger.debug('process %s for lag of %s'%(chan_file, lag))
99
+ sox_transform = sox.Transformer()
100
+ sox_transform.trim(float(lag)*1e-3)
101
+ output_fh = tempfile.NamedTemporaryFile(suffix='.wav', delete=DEL_TEMP)
102
+ out_file = timeline._pathname(output_fh)
103
+ input_file = timeline._pathname(chan_file)
104
+ logger.debug('sox in and out files: %s %s'%(input_file, out_file))
105
+ logger.debug('calling sox_transform.build()')
106
+ status = sox_transform.build(input_file, out_file, return_output=True )
107
+ logger.debug('sox.build exit code %s'%str(status))
108
+ return output_fh
109
+ new_channels = [_trim(*e) for e in zip(lags, channels)]
110
+ logger.debug('new_channels %s'%new_channels)
111
+ trimmed_multichanfile = timeline._sox_combine(new_channels)
112
+ logger.debug('trimmed_multichanfile %s'%timeline._pathname(trimmed_multichanfile))
113
+ Path(timeline._pathname(trimmed_multichanfile)).replace(media_object.path)
114
+
115
+ def copy_to_syncedroot(raw_root, synced_root):
116
+ # args are str
117
+ # copy dirs and non AV files
118
+ logger.debug(f'raw_root {raw_root}')
119
+ logger.debug(f'synced_root {synced_root}')
120
+ for raw_path in Path(raw_root).rglob('*'):
121
+ ext = raw_path.suffix[1:]
122
+ is_DS_Store = raw_path.name == '.DS_Store'# mac os
123
+ if ext not in av_file_extensions and not is_DS_Store:
124
+ logger.debug(f'raw_path: {raw_path}')
125
+ # dont copy WAVs either, they will be in ISOs
126
+ # synced_path = Path(synced_root)/str(raw_path)[1:] # cant join abs. paths
127
+ rel = raw_path.relative_to(raw_root)
128
+ logger.debug(f'relative path {rel}')
129
+ synced_path = Path(synced_root)/Path(raw_root).name/rel
130
+ logger.debug(f'synced_path: {synced_path}')
131
+ if raw_path.is_dir():
132
+ synced_path.mkdir(parents=True, exist_ok=True)
133
+ continue
134
+ # if here, it's a file
135
+ if not synced_path.exists():
136
+ print(f'will mirror non AV file {synced_path}')
137
+ logger.debug(f'will mirror non AV file at {synced_path}')
138
+ shutil.copy2(raw_path, synced_path)
139
+ continue
140
+ # file exists, check if same
141
+ same = filecmp.cmp(raw_path, synced_path, shallow=False)
142
+ logger.debug(f'copy exists of:\n{raw_path}\n{synced_path}')
143
+ if not same:
144
+ print(f'file changed, copying again\n{raw_path}')
145
+ shutil.copy2(raw_path, synced_path)
146
+ else:
147
+ logger.debug('same content, next')
148
+ continue # next raw_path in loop
149
+
150
+ def copy_raw_root_tree_to_sndroot(raw_root, snd_root):
151
+ # args are str
152
+ # copy only tree structure, no files
153
+ for raw_path in Path(raw_root).rglob('*'):
154
+ synced_path = Path(snd_root)/str(raw_path)[1:] # cant join abs. paths
155
+ if raw_path.is_dir():
156
+ synced_path.mkdir(parents=True, exist_ok=True)
157
+
158
+
159
+
160
+ def new_parser():
161
+ parser = argparse.ArgumentParser()
162
+ parser.add_argument('--resync',
163
+ action='store_true',
164
+ dest='resync',
165
+ help='Resync previously done clips.')
166
+ parser.add_argument(
167
+ "sub_dir",
168
+ type=str,
169
+ nargs='?',
170
+ help="Sub directory to scan, should under RAWROOT."
171
+ )
172
+ parser.add_argument('--terse',
173
+ action='store_true',
174
+ dest='terse',
175
+ help='Terse output')
176
+ # parser.add_argument('--isos', # default True in mamsync
177
+ # action='store_true',
178
+ # dest='write_ISOs',
179
+ # help='Cut ISO sound files')
180
+ parser.add_argument('-t','--timelineoffset',
181
+ nargs=1,
182
+ default=['00:00:00:00'],
183
+ dest='timelineoffset',
184
+ help='When processing multicam, where to place clips on NLE timeline (HH:MM:SS:FF)')
185
+ return parser
186
+
187
+ def clear_log():
188
+ # clear the file logging clips already synced
189
+ data_dir = platformdirs.user_data_dir('mamsync', 'plutz', ensure_exists=True)
190
+ log_file = Path(data_dir)/mamconf.LOG_FILE
191
+ print('Clearing log file of synced clips: "%s"'%log_file)
192
+ with open(log_file, 'w') as fh:
193
+ fh.write('done:\n')
194
+
195
+ def main():
196
+ parser = new_parser()
197
+ args = parser.parse_args()
198
+ logger.debug(f'arguments from argparse {args}')
199
+ roots_strings = mamconf.get_proj(False)
200
+ roots_pathlibPaths = [Path(s) for s in mamconf.get_proj(False)]
201
+ logger.debug(f'roots_strings from mamconf.get_proj {roots_strings}')
202
+ logger.debug(f'roots_pathlibPaths from mamconf.get_proj {roots_pathlibPaths}')
203
+ # check all have values, except for PROXIES, the last one
204
+ if any([r == '' for r in roots_strings][:-1]):
205
+ print("Can't sync if some folders are not set:")
206
+ mamconf.print_out_conf(*mamconf.get_proj())
207
+ print('Bye.')
208
+ sys.exit(0)
209
+ # because optional PROXIES folder '' yields a '.' path, exclude it
210
+ for r in [rp for rp in roots_pathlibPaths if rp != Path('.')]:
211
+ if not r.is_absolute():
212
+ print(f'\rError: folder {r} must be an absolute path. Bye')
213
+ sys.exit(0)
214
+ if not r.exists():
215
+ print(f'\rError: folder {r} does not exist. Bye')
216
+ sys.exit(0)
217
+ if not r.is_dir():
218
+ print(f'\rError: path {r} is not a folder. Bye')
219
+ sys.exit(0)
220
+ raw_root, synced_root, snd_root, _ = roots_pathlibPaths
221
+ if args.sub_dir != None:
222
+ top_dir = args.sub_dir
223
+ logger.debug(f'sub _dir: {args.sub_dir}')
224
+ if not Path(top_dir).exists():
225
+ print(f"\rError: folder {top_dir} doesn't exist, bye.")
226
+ sys.exit(0)
227
+ else:
228
+ top_dir = raw_root
229
+ if args.resync:
230
+ clear_log()
231
+ # go, mamsync!
232
+ copy_to_syncedroot(raw_root, synced_root)
233
+ # copy_raw_root_tree_to_sndroot(raw_root, snd_root) # why?
234
+ multi2polywav.poly_all(top_dir)
235
+ scanner = device_scanner.Scanner(top_dir, stay_silent=args.terse)
236
+ scanner.scan_media_and_build_devices_UID(synced_root=synced_root)
237
+ for m in scanner.found_media_files:
238
+ if m.device.tracks:
239
+ if not all([lv == None for lv in m.device.tracks.lag_values]):
240
+ logger.debug('%s has lag_values %s'%(
241
+ m.path, m.device.tracks.lag_values))
242
+ # any lag for a channel is specified by user in tracks.txt
243
+ process_lag_adjustement(m)
244
+ audio_REC_only = all([m.device.dev_type == 'REC' for m
245
+ in scanner.found_media_files])
246
+ if not args.terse:
247
+ if scanner.input_structure == 'ordered':
248
+ print('\nDetected structured folders')
249
+ # if scanner.top_dir_has_multicam:
250
+ # print(', multicam')
251
+ # else:
252
+ # print()
253
+ else:
254
+ print('\nDetected loose structure')
255
+ if scanner.CAM_numbers() > 1:
256
+ print('\nNote: different CAMs are present, will sync audio for each of them but if you want to set their')
257
+ print('respective timecode for NLE timeline alignement you should regroup clips by CAM under their own DIR.')
258
+ print('\nFound [gold1]%i[/gold1] media files '%(
259
+ len(scanner.found_media_files)), end='')
260
+ print('from [gold1]%i[/gold1] devices:\n'%(
261
+ scanner.get_devices_number()))
262
+ all_devices = scanner.get_devices()
263
+ for dev in all_devices:
264
+ dt = 'Camera' if dev.dev_type == 'CAM' else 'Recorder'
265
+ print('%s [gold1]%s[/gold1] with files:'%(dt, dev.name), end = ' ')
266
+ medias = scanner.get_media_for_device(dev)
267
+ for m in medias[:-1]: # last printed out of loop
268
+ print('[gold1]%s[/gold1]'%m.path.name, end=', ')
269
+ print('[gold1]%s[/gold1]'%medias[-1].path.name)
270
+ a_media = medias[0]
271
+ # check if all audio recorders have same sampling freq
272
+ freqs = [dev.sampling_freq for dev in all_devices if dev.dev_type == 'REC']
273
+ same = np.isclose(np.std(freqs),0)
274
+ logger.debug('sampling freqs from audio recorders %s, same:%s'%(freqs, same))
275
+ if not same:
276
+ print('some audio recorders have different sampling frequencies:')
277
+ print(freqs)
278
+ print('resulting in undefined results: quitting...')
279
+ quit()
280
+ print()
281
+ recordings = [yaltc.Recording(m, do_plots=False) for m
282
+ in scanner.found_media_files]
283
+ recordings_with_time = [
284
+ rec
285
+ for rec in recordings
286
+ if rec.get_start_time()
287
+ ]
288
+ if not args.terse:
289
+ table = Table(title="tictacsync results")
290
+ table.add_column("Recording\n", justify="center", style='gold1')
291
+ table.add_column("TTC chan\n (1st=#0)", justify="center", style='gold1')
292
+ # table.add_column("Device\n", justify="center", style='gold1')
293
+ table.add_column("UTC times\nstart:end", justify="center", style='gold1')
294
+ table.add_column("Clock drift\n(ppm)", justify="right", style='gold1')
295
+ # table.add_column("SN ratio\n(dB)", justify="center", style='gold1')
296
+ table.add_column("Date\n", justify="center", style='gold1')
297
+ rec_WO_time = [
298
+ rec.AVpath.name
299
+ for rec in recordings
300
+ if rec not in recordings_with_time]
301
+ if rec_WO_time:
302
+ print('No time found for: ',end='')
303
+ [print(rec, end=' ') for rec in rec_WO_time]
304
+ print('\n')
305
+ for r in recordings_with_time:
306
+ date = r.get_start_time().strftime("%y-%m-%d")
307
+ start_HHMMSS = r.get_start_time().strftime("%Hh%Mm%Ss")
308
+ end_MMSS = r.get_end_time().strftime("%Mm%Ss")
309
+ times_range = start_HHMMSS + ':' + end_MMSS
310
+ table.add_row(
311
+ str(r.AVpath.name),
312
+ str(r.TicTacCode_channel),
313
+ # r.device,
314
+ times_range,
315
+ # '%.6f'%(r.true_samplerate/1e3),
316
+ '%2i'%(r.get_samplerate_drift()),
317
+ # '%.0f'%r.decoder.SN_ratio,
318
+ date
319
+ )
320
+ console = Console()
321
+ console.print(table)
322
+ print()
323
+ n_devices = scanner.get_devices_number()
324
+ if len(recordings_with_time) < 2:
325
+ if not args.terse:
326
+ print('\nNothing to sync, exiting.\n')
327
+ sys.exit(1)
328
+ matcher = timeline.Matcher(recordings_with_time)
329
+ matcher.scan_audio_for_each_videoclip()
330
+ if not matcher.mergers:
331
+ if not args.terse:
332
+ print('\nNothing to sync, bye.\n')
333
+ sys.exit(1)
334
+ if scanner.input_structure != 'ordered':
335
+ print('Warning, can\'t run mamsync without structured folders: [gold1]--isos[/gold1] option ignored.\n')
336
+ print('Merging...')
337
+ asked_ISOs = True # par defaut
338
+ dont_write_cam_folder = False # write them
339
+ for merger in matcher.mergers:
340
+ merger._build_audio_and_write_video(top_dir,
341
+ dont_write_cam_folder,
342
+ asked_ISOs,
343
+ synced_root = synced_root,
344
+ snd_root = snd_root,
345
+ raw_root = raw_root)
346
+ if not args.terse:
347
+ print("\n")
348
+ # find out where files were written
349
+ # a_merger = matcher.mergers[0]
350
+ # log file
351
+ p = Path(platformdirs.user_data_dir('mamsync', 'plutz'))/mamconf.LOG_FILE
352
+ log_filehandle = open(p, 'a')
353
+ for merger in matcher.mergers:
354
+ print('[gold1]%s[/gold1]'%merger.videoclip.AVpath.name, end='')
355
+ for audio in merger.get_matched_audio_recs():
356
+ print(' + [gold1]%s[/gold1]'%audio.AVpath.name, end='')
357
+ new_file = merger.videoclip.final_synced_file.parts
358
+ final_p = merger.videoclip.final_synced_file
359
+ nameAnd2Parents = Path('').joinpath(*final_p.parts[-2:])
360
+ print(' became [gold1]%s[/gold1]'%nameAnd2Parents)
361
+ # add full path to log file
362
+ log_filehandle.write(f'{merger.videoclip.AVpath}\n')
363
+ # matcher._build_otio_tracks_for_cam()
364
+ log_filehandle.close()
365
+ matcher.set_up_clusters() # multicam
366
+ matcher.shrink_gaps_between_takes(args.timelineoffset)
367
+ logger.debug('matcher.multicam_clips_clusters %s'%
368
+ pformat(matcher.multicam_clips_clusters))
369
+ # clusters is list of {'end': t1, 'start': t2, 'vids': [r1,r3]}
370
+ # really_clusters is True if one of them has len() > 1
371
+ really_clusters = any([len(cl['vids']) > 1 for cl
372
+ in matcher.multicam_clips_clusters])
373
+ if really_clusters:
374
+ if scanner.input_structure == 'loose':
375
+ print('\nThere are synced multicam clips but without structured folders')
376
+ print('they were not grouped together under the same folder.')
377
+ else:
378
+ matcher.move_multicam_to_dir(raw_root=raw_root, synced_root=synced_root)
379
+ else:
380
+ logger.debug('not really a multicam cluster, nothing to move')
381
+ sys.exit(0)
382
+
383
+ if __name__ == '__main__':
384
+ main()
385
+
386
+
387
+
@@ -31,7 +31,7 @@ def print_grby(grby):
31
31
  def wav_recursive_scan(top_directory):
32
32
  files_lower_case = Path(top_directory).rglob('*.wav')
33
33
  files_upper_case = Path(top_directory).rglob('*.WAV')
34
- files = list(files_lower_case) + list(files_upper_case)
34
+ files = set(list(files_lower_case) + list(files_upper_case))
35
35
  paths = [
36
36
  p
37
37
  for p in files
@@ -83,7 +83,9 @@ def build_poly_name(multifiles):
83
83
  def jump_metadata(from_file, to_file):
84
84
  tempfile_for_metadata = tempfile.NamedTemporaryFile(suffix='.wav', delete=True)
85
85
  tempfile_for_metadata = tempfile_for_metadata.name
86
- process_list = ['ffmpeg', '-loglevel', 'quiet', '-nostats', '-hide_banner', '-i', from_file, '-i', to_file, '-map_metadata', '0', '-c', 'copy', tempfile_for_metadata]
86
+ # ffmpeg -i 32ch-44100-bwf.wav -i onechan.wav -map 1 -map_metadata 0 -c copy outmeta.wav
87
+ process_list = ['ffmpeg', '-loglevel', 'quiet', '-nostats', '-hide_banner', '-i', from_file, '-i', to_file, '-map', '1',
88
+ '-map_metadata', '0', '-c', 'copy', tempfile_for_metadata]
87
89
  # ss = shlex.split("ffmpeg -i %s -i %s -map_metadata 0 -c copy %s"%(from_file, to_file, tempfile_for_metadata))
88
90
  # print(ss)
89
91
  # logger.debug('process %s'%process_list)