Skip to content

Commit c8cd4e5

Browse files
committed
do not trim off recording file extension when naming generated files
1 parent ca3985b commit c8cd4e5

15 files changed

Lines changed: 187 additions & 220 deletions

app/post-process.py

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
#!/usr/bin/env python3
2+
13
import sys
24
import ast
35
import os
@@ -25,9 +27,7 @@
2527

2628
M.init(None, os.path.join(__dir__, "configuration.py"), False)
2729

28-
wavfile_noext = M.trim_ext(wavfile)
29-
30-
with open(wavfile_noext+"-classify.log",'r') as fid:
30+
with open(wavfile+"-classify.log",'r') as fid:
3131
for line in fid:
3232
if "labels: " in line:
3333
m=re.search('labels: (.+)',line)
@@ -40,13 +40,13 @@
4040

4141
if delete_wavs:
4242
for label in labels:
43-
fullpath = wavfile_noext+'-'+label+'.wav'
43+
fullpath = wavfile+'-'+label+'.wav'
4444
os.remove(fullpath)
4545
print("deleting ", fullpath)
4646

4747
durations = {}
4848
counts = {}
49-
with open(wavfile_noext+'-predicted-1.0pr.csv') as fid:
49+
with open(wavfile+'-predicted-1.0pr.csv') as fid:
5050
csvreader = csv.reader(fid)
5151
for row in csvreader:
5252
if row[4] not in durations:
@@ -55,7 +55,7 @@
5555
durations[row[4]] += (int(row[2]) - int(row[1]))
5656
counts[row[4]] += 1
5757

58-
with open(wavfile_noext+"-post-process.csv",'w') as fid:
58+
with open(wavfile+"-post-process.csv",'w') as fid:
5959
fid.write("wavfile,label,duration ("+M.context_time_units+"),num events\n")
6060
for label in durations.keys():
6161
fid.write(os.path.basename(wavfile)+','+
@@ -64,8 +64,8 @@
6464
str(counts[label])+'\n')
6565

6666
if delete_logs:
67-
os.remove(wavfile_noext+'-classify.log')
68-
os.remove(wavfile_noext+'-ethogram.log')
69-
os.remove(wavfile_noext+'-post-process.log')
67+
os.remove(wavfile+'-classify.log')
68+
os.remove(wavfile+'-ethogram.log')
69+
os.remove(wavfile+'-post-process.log')
7070

7171
print(str(datetime.now())+": finish time")

src/classify

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def main():
8484

8585
load_audio_read_plugin(FLAGS.audio_read_plugin, FLAGS.audio_read_plugin_kwargs)
8686
load_video_read_plugin(FLAGS.video_read_plugin, FLAGS.video_read_plugin_kwargs)
87-
from lib import audio_read, video_read, trim_ext
87+
from lib import audio_read, video_read
8888

8989
with open(FLAGS.model_labels, 'r') as fid:
9090
model_labels = fid.read().splitlines()
@@ -255,13 +255,11 @@ def main():
255255
else:
256256
adjusted_probability = probability_matrix[:,ch]
257257
waveform = adjusted_probability*np.iinfo(np.int16).max
258-
withoutext = trim_ext(FLAGS.wav)
259-
filename = withoutext+'-'+labels[ch]+'.wav'
258+
filename = FLAGS.wav+'-'+labels[ch]+'.wav'
260259
wavfile.write(filename, int(sample_rate), waveform.astype('int16'))
261260
else:
262261
waveform = probability_matrix * np.iinfo(np.int16).max
263-
withoutext = trim_ext(FLAGS.wav)
264-
filename = withoutext+'-.wav'
262+
filename = FLAGS.wav+'-.wav'
265263
wavfile.write(filename, int(sample_rate), waveform.astype('int16'))
266264

267265
if __name__ == '__main__':

src/congruence

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -166,15 +166,8 @@ def main():
166166
thresholds=set()
167167
for wavdir in wavdirs:
168168
for wavfile in wavdirs[wavdir]:
169-
if has_rec[wavfile] == "False":
170-
wavfile_noext = os.path.splitext(wavfile)[0]
171-
else:
172-
tmp = wavfile.split('-')
173-
withext, rec = '-'.join(tmp[:-1]), tmp[-1]
174-
wavfile_noext = os.path.splitext(withext)[0]+'-'+rec
175-
176169
if not labels:
177-
with open(os.path.join(FLAGS.basepath,wavdir,wavfile_noext+'-ethogram.log'), 'r') as fid:
170+
with open(os.path.join(FLAGS.basepath,wavdir,wavfile+'-ethogram.log'), 'r') as fid:
178171
for line in fid:
179172
if line.startswith('logdir: '):
180173
m=re.search('logdir: (.*)',line)
@@ -194,7 +187,7 @@ def main():
194187
thresholds_file)
195188

196189
audio_tic_rate_probabilities, half_stride_sec, probability_matrix = \
197-
read_probabilities(os.path.join(FLAGS.basepath, wavdir, wavfile_noext), labels)
190+
read_probabilities(os.path.join(FLAGS.basepath, wavdir, wavfile), labels)
198191
for threshold in np.linspace(0, 1, num=FLAGS.nprobabilities+2)[1:-1]:
199192
features, start_tics, stop_tics = discretize_probabilities(probability_matrix,
200193
threshold,
@@ -205,7 +198,7 @@ def main():
205198
if len(features)>0:
206199
thresholds.add(str(threshold)+'th')
207200
filename = os.path.join(FLAGS.basepath, wavdir,
208-
wavfile_noext+'-predicted-'+str(threshold)+'th.csv')
201+
wavfile+'-predicted-'+str(threshold)+'th.csv')
209202
temp_files.append(filename)
210203
isort = np.argsort(start_tics)
211204
with open(filename,'w') as fid:
@@ -506,7 +499,7 @@ def main():
506499
pool.close()
507500

508501
def to_csv(intervals, csvbase, whichset):
509-
filename = os.path.splitext(csvbase)[0]+'-disjoint-'+whichset+'.csv'
502+
filename = csvbase+'-disjoint-'+whichset+'.csv'
510503
with open(os.path.join(FLAGS.topath,filename), 'w') as fid:
511504
csvwriter = csv.writer(fid, lineterminator='\n')
512505
for ilabel,label in enumerate(timestamps.keys()):

src/detect-plugins/template.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def main():
6464
print('%s = %s' % (key, flags[key]))
6565

6666
load_audio_read_plugin(FLAGS.audio_read_plugin, FLAGS.audio_read_plugin_kwargs)
67-
from lib import audio_read, trim_ext
67+
from lib import audio_read
6868

6969
hyperparameter1 = int(FLAGS.parameters["my-simple-textbox"])
7070

@@ -75,7 +75,7 @@ def main():
7575
amplitude = scipy.signal.medfilt(song)
7676

7777
basename = os.path.basename(FLAGS.filename)
78-
with open(trim_ext(FLAGS.filename)+'-detected.csv', 'w') as fid:
78+
with open(FLAGS.filename+'-detected.csv', 'w') as fid:
7979
csvwriter = csv.writer(fid, lineterminator='\n')
8080
for i in range(1,len(amplitude)-1):
8181
if amplitude[i] > hyperparameter1:

src/detect-plugins/time-freq-threshold.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def main():
100100
add_plugins_to_path(srcdir)
101101

102102
load_audio_read_plugin(FLAGS.audio_read_plugin, FLAGS.audio_read_plugin_kwargs)
103-
from lib import audio_read, trim_ext
103+
from lib import audio_read
104104

105105
time_sigma_signal, time_sigma_noise = [int(x) for x in FLAGS.parameters['time_sigma'].split(',')]
106106

@@ -229,7 +229,7 @@ def bool2stamp(song_morphed, scale):
229229

230230

231231
basename = os.path.basename(FLAGS.filename)
232-
with open(trim_ext(FLAGS.filename)+'-detected.csv', 'w') as fid:
232+
with open(FLAGS.filename+'-detected.csv', 'w') as fid:
233233
csvwriter = csv.writer(fid, lineterminator='\n')
234234
for i in intervals_time_signal:
235235
csvwriter.writerow([basename,i[1],i[2],'detected','time'+i[3]])

src/ethogram

Lines changed: 5 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -39,26 +39,17 @@ try:
3939
audio_tic_rate=float(audio_tic_rate)
4040

4141
wavpath, wavname = os.path.split(wav_file)
42-
if has_rec == "False":
43-
if not os.path.isfile(wav_file):
44-
print('cannot find WAV file')
45-
exit()
46-
wavname_noext = os.path.splitext(wavname)[0]
47-
else:
48-
tmp = wavname.split('-')
49-
withext, rec = '-'.join(tmp[:-1]), tmp[-1]
50-
wavname_noext = os.path.splitext(withext)[0]+'-'+rec
51-
if not os.path.isfile(os.path.join(wavpath, withext)):
52-
print('cannot find WAV file')
53-
exit()
42+
if not os.path.isfile(wav_file):
43+
print('cannot find WAV file')
44+
exit()
5445

5546
precision_recall_ratios, thresholds = read_thresholds(logdir, model, thresholds_file)
5647

5748
labels = [x[0] for x in thresholds]
5849
thresholds = np.array([x[1:] for x in thresholds], dtype=np.float64)
5950

6051
audio_tic_rate_probabilities, half_stride_sec, probability_matrix = \
61-
read_probabilities(os.path.join(wavpath, wavname_noext), labels)
52+
read_probabilities(os.path.join(wavpath, wavname), labels)
6253

6354
for ithreshold in range(len(precision_recall_ratios)):
6455
features, start_tics, stop_tics = discretize_probabilities(probability_matrix,
@@ -68,7 +59,7 @@ try:
6859
half_stride_sec,
6960
audio_tic_rate)
7061
filename = os.path.join(wavpath,
71-
wavname_noext+'-predicted-'+precision_recall_ratios[ithreshold]+'pr.csv')
62+
wavname+'-predicted-'+precision_recall_ratios[ithreshold]+'pr.csv')
7263
isort = np.argsort(start_tics)
7364
with open(filename,'w') as fid:
7465
csvwriter = csv.writer(fid, lineterminator='\n')

src/gui/controller.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -937,10 +937,10 @@ def pbfile_succeeded(pbfile, reftime):
937937
return recent_file_exists(pbfile, reftime, True)
938938

939939
def detect_succeeded(wavfile, reftime):
940-
logfile = M.trim_ext(wavfile)+'-detect.log'
940+
logfile = wavfile+'-detect.log'
941941
if not logfile_succeeded(logfile, reftime):
942942
return False
943-
csvfile = M.trim_ext(wavfile)+'-detected.csv'
943+
csvfile = wavfile+'-detected.csv'
944944
if not csvfile_succeeded(csvfile, reftime):
945945
return False
946946
return True
@@ -955,7 +955,7 @@ async def detect_actuate():
955955
async def _detect_actuate(i, wavfiles, threads, results):
956956
wavfile = wavfiles.pop(0)
957957
currtime = time.time()
958-
logfile = M.trim_ext(wavfile)+'-detect.log'
958+
logfile = wavfile+'-detect.log'
959959
jobid = generic_actuate(os.path.join("detect-plugins", M.detect_plugin+".py"),
960960
logfile,
961961
M.detect_where,
@@ -1010,8 +1010,7 @@ async def misses_actuate():
10101010
csvreader = csv.reader(fid)
10111011
row1 = next(csvreader)
10121012
wavfile = row1[0]
1013-
noext = os.path.join(basepath, os.path.splitext(wavfile)[0])
1014-
logfile = noext+'-misses.log'
1013+
logfile = os.path.join(basepath, wavfile)+'-misses.log'
10151014
jobid = generic_actuate("misses", logfile, \
10161015
M.misses_where,
10171016
M.misses_ncpu_cores,
@@ -1855,7 +1854,7 @@ def classify_succeeded(modeldir, wavfile, reftime):
18551854
with open(os.path.join(modeldir, 'labels.txt'), 'r') as fid:
18561855
labels = fid.read().splitlines()
18571856
for x in labels:
1858-
if not recent_file_exists(M.trim_ext(wavfile)+'-'+x+'.wav', reftime, True):
1857+
if not recent_file_exists(wavfile+'-'+x+'.wav', reftime, True):
18591858
return False
18601859
return True
18611860

@@ -1867,7 +1866,7 @@ async def _classify_actuate(wavfiles):
18671866
wavfile = wavfiles.pop(0)
18681867
currtime = time.time()
18691868
logdir, model, _, check_point = M.parse_model_file(V.model_file.value)
1870-
logfile = M.trim_ext(wavfile)+'-classify.log'
1869+
logfile = wavfile+'-classify.log'
18711870
args = ["--context="+V.context.value,
18721871
"--shiftby="+V.shiftby.value,
18731872
"--loss="+V.loss.value,
@@ -1928,7 +1927,7 @@ def ethogram_succeeded(modeldir, ckpt, wavfile, reftime):
19281927
row1 = next(csvreader)
19291928
precision_recalls = row1[1:]
19301929
for x in precision_recalls:
1931-
if not recent_file_exists(M.trim_ext(wavfile)+'-predicted-'+x+'pr.csv', reftime, True):
1930+
if not recent_file_exists(wavfile+'-predicted-'+x+'pr.csv', reftime, True):
19321931
return False
19331932
return True
19341933

@@ -1946,7 +1945,7 @@ async def _ethogram_actuate(i, wavfiles, threads, results):
19461945
thresholds_file = os.path.basename(V.model_file.value)
19471946
else:
19481947
thresholds_file = 'thresholds.ckpt-'+check_point+'.csv'
1949-
logfile = M.trim_ext(wavfile)+'-ethogram.log'
1948+
logfile = wavfile+'-ethogram.log'
19501949
jobid = generic_actuate("ethogram", logfile, M.ethogram_where,
19511950
M.ethogram_ncpu_cores,
19521951
M.ethogram_ngpu_cards,

src/gui/model.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def save_annotations():
8989
wavfiles = set()
9090
for sound in annotated_sounds:
9191
if not sound["label"]: continue
92-
wavfiles |= set([trim_ext(os.path.join(*sound["file"]))])
92+
wavfiles |= set([os.path.join(*sound["file"])])
9393
for wavfile in wavfiles:
9494
csvfile = wavfile+"-annotated-"+songexplorer_starttime+".csv"
9595
annotated_csvfiles_all.add(csvfile)
@@ -104,8 +104,7 @@ def save_annotations():
104104
corrected_sounds=[]
105105
for annotation in annotated_sounds:
106106
if annotation['label']!="" and not annotation['label'].isspace():
107-
wavfile_noext = trim_ext(os.path.join(*annotation['file']))
108-
csvwriters[wavfile_noext].writerow(
107+
csvwriters[os.path.join(*annotation['file'])].writerow(
109108
[annotation['file'][1],
110109
annotation['ticks'][0], annotation['ticks'][1],
111110
'annotated', annotation['label']])
@@ -119,8 +118,7 @@ def save_annotations():
119118
columns=['file','start','stop','kind','label'])
120119
wavfiles = set()
121120
for sound in corrected_sounds:
122-
wavfile_noext = trim_ext(os.path.join(*sound["file"]))
123-
wavfiles |= set([wavfile_noext])
121+
wavfiles |= set([os.path.join(*sound["file"])])
124122
for wavfile in wavfiles:
125123
wavdir, wavbase = os.path.split(wavfile)
126124
wavpath = os.path.join(V.groundtruth_folder.value, wavdir)
@@ -248,7 +246,7 @@ def init(_bokeh_document, _configuration_file, _use_aitch):
248246
global context_width_sec0, context_offset_sec0
249247
global xcluster, ycluster, zcluster, ndcluster, tic2pix_max, snippet_width_pix, ilayer, ispecies, iword, inohyphen, ikind, nlayers, layers, species, words, nohyphens, kinds, used_labels, snippets_gap_sec, snippets_tic, snippets_gap_tic, snippets_decimate_by, snippets_pix, snippets_gap_pix, context_decimate_by, context_width_tic, context_offset_tic, context_sound, isnippet, xsnippet, ysnippet, file_nframes, context_midpoint_tic, ilabel, used_sounds, used_starts_sorted, used_stops, iused_stops_sorted, annotated_sounds, annotated_starts_sorted, annotated_stops, iannotated_stops_sorted, annotated_csvfiles_all, nrecent_annotations, clustered_sounds, clustered_activations, used_recording2firstsound, clustered_starts_sorted, clustered_stops, iclustered_stops_sorted, songexplorer_starttime, history_stack, history_idx, wizard, action, function, statepath, state, file_dialog_root, file_dialog_filter, nearest_sounds, status_ticker_queue, waitfor_job, dfs, remaining_isounds
250248
global user_changed_recording, user_copied_parameters
251-
global audio_read, audio_read_exts, audio_read_rec2ch, audio_read_strip_rec, trim_ext
249+
global audio_read, audio_read_exts, audio_read_rec2ch, audio_read_strip_rec
252250
global video_read, detect_labels, doubleclick_annotation, context_data, context_data_istart, model, video_findfile
253251
global detect_parameters, doubleclick_parameters, model_parameters, cluster_parameters, augmentation_parameters
254252

@@ -270,7 +268,7 @@ def init(_bokeh_document, _configuration_file, _use_aitch):
270268

271269
load_audio_read_plugin(audio_read_plugin, audio_read_plugin_kwargs)
272270
load_video_read_plugin(video_read_plugin, video_read_plugin_kwargs)
273-
from lib import audio_read, audio_read_exts, audio_read_rec2ch, audio_read_strip_rec, video_read, trim_ext
271+
from lib import audio_read, audio_read_exts, audio_read_rec2ch, audio_read_strip_rec, video_read
274272

275273
sys.path.insert(0,os.path.dirname(detect_plugin))
276274
tmp = importlib.import_module(os.path.basename(detect_plugin))

src/gui/view.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1146,8 +1146,7 @@ def context_update():
11461146
M.file_nframes = np.shape(context_cache_data)[0]
11471147
probs = [None]*len(M.used_labels)
11481148
for ilabel,label in enumerate(M.used_labels):
1149-
prob_wavfile = M.trim_ext(os.path.join(groundtruth_folder.value,
1150-
*M.context_sound['file']))+'-'+label+'.wav'
1149+
prob_wavfile = os.path.join(groundtruth_folder.value, *M.context_sound['file'])+'-'+label+'.wav'
11511150
if os.path.isfile(prob_wavfile):
11521151
prob_tic_rate, probs[ilabel] = spiowav.read(prob_wavfile, mmap=True)
11531152
if istart+M.context_width_tic>0 and istart<M.file_nframes:

src/lib.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -51,15 +51,6 @@ def video_read(fullpath, start_frame=None, stop_frame=None):
5151
return video_read_module.video_read(fullpath, start_frame, stop_frame,
5252
**video_read_plugin_kwargs)
5353

54-
def trim_ext(wavfile):
55-
if len(audio_read_rec2ch(audio_read_strip_rec(wavfile))) > 1:
56-
tmp = wavfile.split('-')
57-
withext, rec = '-'.join(tmp[:-1]), tmp[-1]
58-
withoutext = os.path.splitext(withext)[0]+'-'+rec
59-
else:
60-
withoutext = os.path.splitext(wavfile)[0]
61-
return withoutext
62-
6354
def check_config(configuration_file):
6455
exec(open(configuration_file).read())
6556

0 commit comments

Comments
 (0)