8
8
import sys
9
9
import traceback
10
10
from typing import Callable , Dict , Iterable , List , Optional , Set , Tuple , Union
11
+ import logging
11
12
12
13
from . import __version__
13
14
from .projects import ChildProject
16
17
from .utils import Segment , intersect_ranges , path_is_parent , TimeInterval , series_to_datetime , find_lines_involved_in_overlap
17
18
18
19
20
+ # Create a logger for the module (file)
21
+ logger_annotations = logging .getLogger (__name__ )
22
+ # messages are propagated to the higher level logger (ChildProject), used in cmdline.py
23
+ logger_annotations .propagate = True
24
+
19
25
class AnnotationManager :
20
26
INDEX_COLUMNS = [
21
27
IndexColumn (
@@ -353,12 +359,7 @@ def read(self) -> Tuple[List[str], List[str]]:
353
359
return errors , warnings
354
360
355
361
def validate_annotation (self , annotation : dict ) -> Tuple [List [str ], List [str ]]:
356
- print (
357
- "validating {} from {}..." .format (
358
- annotation ["annotation_filename" ], annotation ["set" ]
359
- )
360
- )
361
-
362
+ logger_annotations .info ("Validating %s from %s..." , annotation ["annotation_filename" ], annotation ["set" ])
362
363
segments = IndexTable (
363
364
"segments" ,
364
365
path = os .path .join (
@@ -490,11 +491,12 @@ def _import_annotation(
490
491
if self .annotations [(self .annotations ['set' ] == annotation ['set' ]) &
491
492
(self .annotations ['annotation_filename' ] == annotation_filename )].shape [0 ] > 0 :
492
493
if overwrite_existing :
493
- print (f"Warning: annotation file { output_filename } will be overwritten" )
494
+ logger_annotations .warning ("Annotation file %s will be overwritten" , output_filename )
495
+
494
496
else :
495
497
error_filename = output_filename .replace ('\\ ' ,'/' )
496
498
annotation ["error" ] = f"annotation file { error_filename } already exists, to reimport it, use the overwrite_existing flag"
497
- print ( f "Error: { annotation ['error' ]} " )
499
+ logger_annotations . error ( "Error: %s" , annotation ['error' ])
498
500
annotation ["imported_at" ] = datetime .datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
499
501
return annotation
500
502
@@ -509,7 +511,8 @@ def _import_annotation(
509
511
if ovl_annots .shape [0 ] > 0 :
510
512
array_tup = list (ovl_annots [['set' ,'recording_filename' ,'range_onset' , 'range_offset' ]].itertuples (index = False , name = None ))
511
513
annotation ["error" ] = f"importation for set <{ annotation ['set' ]} > recording <{ annotation ['recording_filename' ]} > from { annotation ['range_onset' ]} to { annotation ['range_offset' ]} cannot continue because it overlaps with these existing annotation lines: { array_tup } "
512
- print (f"Error: { annotation ['error' ]} " )
514
+ logger_annotations .error ("Error: %s" , annotation ['error' ])
515
+ #(f"Error: {annotation['error']}")
513
516
annotation ["imported_at" ] = datetime .datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
514
517
return annotation
515
518
@@ -541,10 +544,7 @@ def _import_annotation(
541
544
)
542
545
except :
543
546
annotation ["error" ] = traceback .format_exc ()
544
- print (
545
- "an error occured while processing '{}'" .format (path ), file = sys .stderr
546
- )
547
- print (traceback .format_exc (), file = sys .stderr )
547
+ logger_annotations .error ("An error occurred while processing '%s'" , path , exc_info = True )
548
548
549
549
if df is None or not isinstance (df , pd .DataFrame ):
550
550
annotation ["imported_at" ] = datetime .datetime .now ().strftime ("%Y-%m-%d %H:%M:%S" )
@@ -654,9 +654,7 @@ def import_annotations(
654
654
655
655
builtin = input_processed [input_processed ["format" ].isin (converters .keys ())]
656
656
if not builtin ["format" ].map (lambda f : converters [f ].THREAD_SAFE ).all ():
657
- print (
658
- "warning: some of the converters do not support multithread importation; running on 1 thread"
659
- )
657
+ logger_annotations .warning ("warning: some of the converters do not support multithread importation; running on 1 thread" )
660
658
threads = 1
661
659
662
660
#if the input to import has overlaps in it, raise an error immediately, nothing will be imported
@@ -688,14 +686,15 @@ def import_annotations(
688
686
axis = 1 ,
689
687
inplace = True ,
690
688
)
689
+
691
690
if 'error' in imported .columns :
692
691
errors = imported [~ imported ["error" ].isnull ()]
693
692
imported = imported [imported ["error" ].isnull ()]
694
693
#when errors occur, separate them in a different csv in extra
695
694
if errors .shape [0 ] > 0 :
696
695
output = os .path .join (self .project .path , "extra" ,"errors_import_{}.csv" .format (datetime .datetime .now ().strftime ("%Y%m%d-%H%M%S" )))
697
696
errors .to_csv (output , index = False )
698
- print ( f "Errors summary exported to { output } " )
697
+ logger_annotations . info ( "Errors summary exported to %s" , output )
699
698
else :
700
699
errors = None
701
700
@@ -709,7 +708,7 @@ def import_annotations(
709
708
sets = set (input_processed ['set' ].unique ())
710
709
outdated_sets = self ._check_for_outdated_merged_sets (sets = sets )
711
710
for warning in outdated_sets :
712
- print ("warning: {}" . format ( warning ))
711
+ logger_annotations . warning ("warning: %s" , warning )
713
712
714
713
return (imported , errors )
715
714
@@ -763,19 +762,18 @@ def remove_set(self, annotation_set: str, recursive: bool = False):
763
762
path = os .path .join (
764
763
self .project .path , "annotations" , annotation_set , "converted"
765
764
)
766
-
767
765
try :
768
766
rmtree (path )
769
767
except :
770
- print ("could not delete '{} ', as it does not exist (yet?)" . format ( path ) )
768
+ logger_annotations . info ("could not delete '%s ', as it does not exist (yet?)" , path )
771
769
pass
772
770
773
771
self .annotations = self .annotations [self .annotations ["set" ] != annotation_set ]
774
772
self .write ()
775
-
773
+
776
774
outdated_sets = self ._check_for_outdated_merged_sets (sets = {annotation_set })
777
775
for warning in outdated_sets :
778
- print ("warning: {}" . format ( warning ) )
776
+ logger_annotations . warning ("warning: %s" , warning )
779
777
780
778
def rename_set (
781
779
self ,
@@ -1419,7 +1417,7 @@ def get_within_ranges(
1419
1417
)
1420
1418
1421
1419
if missing_data == "warn" :
1422
- print ( f "warning: { error_message } " )
1420
+ logger_annotations . warning ( "warning: %s" , error_message )
1423
1421
else :
1424
1422
raise Exception (error_message )
1425
1423
0 commit comments