idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
38,000 | def update ( self , delta_seconds ) : for obj in tuple ( self . current_tweens ) : for tween in tuple ( self . current_tweens [ obj ] ) : done = tween . update ( delta_seconds ) if done : self . current_tweens [ obj ] . remove ( tween ) if tween . on_complete : tween . on_complete ( tween . target ) if not self . current_tweens [ obj ] : del self . current_tweens [ obj ] return self . current_tweens | update tweeners . delta_seconds is time in seconds since last frame |
38,001 | def update ( self , ptime ) : delta = self . delta + ptime total_duration = self . delay + self . duration if delta > total_duration : delta = total_duration if delta < self . delay : pass elif delta == total_duration : for key , tweenable in self . tweenables : setattr ( self . target , key , tweenable . target_value ) else : fraction = self . ease ( ( delta - self . delay ) / ( total_duration - self . delay ) ) for key , tweenable in self . tweenables : res = tweenable . update ( fraction ) if isinstance ( res , float ) and self . round : res = int ( res ) setattr ( self . target , key , res ) if delta == total_duration or len ( self . tweenables ) == 0 : self . complete = True self . delta = delta if self . on_update : self . on_update ( self . target ) return self . complete | Update tween with the time since the last frame |
38,002 | def set_items ( self , items ) : res = [ ] max_value = max ( sum ( ( rec [ 1 ] for rec in items ) ) , 1 ) for key , val in items : res . append ( ( key , val , val * 1.0 / max_value ) ) self . _items = res | expects a list of key value to work with |
38,003 | def set_values ( self , values ) : self . values = values self . height = len ( self . values ) * 14 self . _max = max ( rec [ 1 ] for rec in values ) if values else dt . timedelta ( 0 ) | expects a list of 2 - tuples |
38,004 | def datetime_to_hamsterday ( civil_date_time ) : from hamster . lib . configuration import conf if civil_date_time . time ( ) < conf . day_start : hamster_date_time = civil_date_time - dt . timedelta ( days = 1 ) else : hamster_date_time = civil_date_time return hamster_date_time . date ( ) | Return the hamster day corresponding to a given civil datetime . |
38,005 | def hamsterday_time_to_datetime ( hamsterday , time ) : from hamster . lib . configuration import conf if time < conf . day_start : civil_date = hamsterday + dt . timedelta ( days = 1 ) else : civil_date = hamsterday return dt . datetime . combine ( civil_date , time ) | Return the civil datetime corresponding to a given hamster day and time . |
38,006 | def format_duration ( minutes , human = True ) : if isinstance ( minutes , dt . timedelta ) : minutes = duration_minutes ( minutes ) if not minutes : if human : return "" else : return "00:00" if minutes < 0 : return "NEGATIVE" hours = minutes / 60 minutes = minutes % 60 formatted_duration = "" if human : if minutes % 60 == 0 : formatted_duration += ( "%dh" ) % ( hours ) elif hours == 0 : formatted_duration += ( "%dmin" ) % ( minutes % 60.0 ) else : formatted_duration += ( "%dh %dmin" ) % ( hours , minutes % 60 ) else : formatted_duration += "%02d:%02d" % ( hours , minutes ) return formatted_duration | formats duration in a human readable format . accepts either minutes or timedelta |
38,007 | def duration_minutes ( duration ) : if isinstance ( duration , list ) : res = dt . timedelta ( ) for entry in duration : res += entry return duration_minutes ( res ) elif isinstance ( duration , dt . timedelta ) : return duration . total_seconds ( ) / 60 else : return duration | returns minutes from duration otherwise we keep bashing in same math |
38,008 | def locale_first_weekday ( ) : first_weekday = 6 try : process = os . popen ( "locale first_weekday week-1stday" ) week_offset , week_start = process . read ( ) . split ( '\n' ) [ : 2 ] process . close ( ) week_start = dt . date ( * time . strptime ( week_start , "%Y%m%d" ) [ : 3 ] ) week_offset = dt . timedelta ( int ( week_offset ) - 1 ) beginning = week_start + week_offset first_weekday = int ( beginning . strftime ( "%w" ) ) except : logger . warn ( "WARNING - Failed to get first weekday from locale" ) return first_weekday | figure if week starts on monday or sunday |
38,009 | def totals ( iter , keyfunc , sumfunc ) : data = sorted ( iter , key = keyfunc ) res = { } for k , group in groupby ( data , keyfunc ) : res [ k ] = sum ( [ sumfunc ( entry ) for entry in group ] ) return res | groups items by field described in keyfunc and counts totals using value from sumfunc |
38,010 | def dateDict ( date , prefix = "" ) : res = { } res [ prefix + "a" ] = date . strftime ( "%a" ) res [ prefix + "A" ] = date . strftime ( "%A" ) res [ prefix + "b" ] = date . strftime ( "%b" ) res [ prefix + "B" ] = date . strftime ( "%B" ) res [ prefix + "c" ] = date . strftime ( "%c" ) res [ prefix + "d" ] = date . strftime ( "%d" ) res [ prefix + "H" ] = date . strftime ( "%H" ) res [ prefix + "I" ] = date . strftime ( "%I" ) res [ prefix + "j" ] = date . strftime ( "%j" ) res [ prefix + "m" ] = date . strftime ( "%m" ) res [ prefix + "M" ] = date . strftime ( "%M" ) res [ prefix + "p" ] = date . strftime ( "%p" ) res [ prefix + "S" ] = date . strftime ( "%S" ) res [ prefix + "U" ] = date . strftime ( "%U" ) res [ prefix + "w" ] = date . strftime ( "%w" ) res [ prefix + "W" ] = date . strftime ( "%W" ) res [ prefix + "x" ] = date . strftime ( "%x" ) res [ prefix + "X" ] = date . strftime ( "%X" ) res [ prefix + "y" ] = date . strftime ( "%y" ) res [ prefix + "Y" ] = date . strftime ( "%Y" ) res [ prefix + "Z" ] = date . strftime ( "%Z" ) for i , value in res . items ( ) : res [ i ] = locale_to_utf8 ( value ) return res | converts date into dictionary having prefix for all the keys |
38,011 | def __get_tag_ids ( self , tags ) : db_tags = self . fetchall ( "select * from tags where name in (%s)" % "," . join ( [ "?" ] * len ( tags ) ) , tags ) changes = False set_complete = [ str ( tag [ "id" ] ) for tag in db_tags if tag [ "autocomplete" ] == "false" ] if set_complete : changes = True self . execute ( "update tags set autocomplete='true' where id in (%s)" % ", " . join ( set_complete ) ) found_tags = [ tag [ "name" ] for tag in db_tags ] add = set ( tags ) - set ( found_tags ) if add : statement = "insert into tags(name) values(?)" self . execute ( [ statement ] * len ( add ) , [ ( tag , ) for tag in add ] ) return self . __get_tag_ids ( tags ) [ 0 ] , True else : return db_tags , changes | look up tags by their name . create if not found |
38,012 | def __get_activity_by_name ( self , name , category_id = None , resurrect = True ) : if category_id : query = res = self . fetchone ( query , ( self . _unsorted_localized , name , category_id ) ) else : query = res = self . fetchone ( query , ( self . _unsorted_localized , name , ) ) if res : keys = ( 'id' , 'name' , 'deleted' , 'category' ) res = dict ( [ ( key , res [ key ] ) for key in keys ] ) res [ 'deleted' ] = res [ 'deleted' ] or False if res [ 'deleted' ] and resurrect : update = self . execute ( update , ( res [ 'id' ] , ) ) return res return None | get most recent preferably not deleted activity by it s name |
38,013 | def __get_category_id ( self , name ) : query = res = self . fetchone ( query , ( name , ) ) if res : return res [ 'id' ] return None | returns category by it s name |
38,014 | def __group_tags ( self , facts ) : if not facts : return facts grouped_facts = [ ] for fact_id , fact_tags in itertools . groupby ( facts , lambda f : f [ "id" ] ) : fact_tags = list ( fact_tags ) grouped_fact = fact_tags [ 0 ] keys = [ "id" , "start_time" , "end_time" , "description" , "name" , "activity_id" , "category" , "tag" ] grouped_fact = dict ( [ ( key , grouped_fact [ key ] ) for key in keys ] ) grouped_fact [ "tags" ] = [ ft [ "tag" ] for ft in fact_tags if ft [ "tag" ] ] grouped_facts . append ( grouped_fact ) return grouped_facts | put the fact back together and move all the unique tags to an array |
38,015 | def __squeeze_in ( self , start_time ) : query = fact = self . fetchone ( query , ( start_time , start_time , start_time - dt . timedelta ( hours = 12 ) , start_time , start_time , start_time + dt . timedelta ( hours = 12 ) ) ) end_time = None if fact : if start_time > fact [ "start_time" ] : self . execute ( "UPDATE facts SET end_time=? WHERE id=?" , ( start_time , fact [ "id" ] ) ) else : end_time = fact [ "start_time" ] return end_time | tries to put task in the given date if there are conflicts we will only truncate the ongoing task and replace it s end part with our activity |
38,016 | def __get_activities ( self , search ) : query = search = search . lower ( ) search = search . replace ( '\\' , '\\\\' ) . replace ( '%' , '\\%' ) . replace ( '_' , '\\_' ) activities = self . fetchall ( query , ( '%s%%' % search , ) ) return activities | returns list of activities for autocomplete activity names converted to lowercase |
38,017 | def __remove_activity ( self , id ) : query = "select count(*) as count from facts where activity_id = ?" bound_facts = self . fetchone ( query , ( id , ) ) [ 'count' ] if bound_facts > 0 : self . execute ( "UPDATE activities SET deleted = 1 WHERE id = ?" , ( id , ) ) else : self . execute ( "delete from activities where id = ?" , ( id , ) ) | check if we have any facts with this activity and behave accordingly if there are facts - sets activity to deleted = True else just remove it |
38,018 | def __remove_category ( self , id ) : affected_query = affected_ids = [ res [ 0 ] for res in self . fetchall ( affected_query , ( id , ) ) ] update = "update activities set category_id = -1 where category_id = ?" self . execute ( update , ( id , ) ) self . execute ( "delete from categories where id = ?" , ( id , ) ) self . __remove_index ( affected_ids ) | move all activities to unsorted and remove category |
38,019 | def __remove_index ( self , ids ) : if not ids : return ids = "," . join ( ( str ( id ) for id in ids ) ) self . execute ( "DELETE FROM fact_index where id in (%s)" % ids ) | remove affected ids from the index |
38,020 | def execute ( self , statement , params = ( ) ) : con = self . __con or self . connection cur = self . __cur or con . cursor ( ) if isinstance ( statement , list ) == False : statement = [ statement ] params = [ params ] for state , param in zip ( statement , params ) : logger . debug ( "%s %s" % ( state , param ) ) cur . execute ( state , param ) if not self . __con : con . commit ( ) cur . close ( ) self . register_modification ( ) | execute sql statement . optionally you can give multiple statements to save on cursor creation and closure |
38,021 | def run_fixtures ( self ) : self . start_transaction ( ) version = self . fetchone ( "SELECT version FROM version" ) [ "version" ] current_version = 9 if version < 8 : self . execute ( "ALTER TABLE activities ADD COLUMN search_name varchar2" ) activities = self . fetchall ( "select * from activities" ) statement = "update activities set search_name = ? where id = ?" for activity in activities : self . execute ( statement , ( activity [ 'name' ] . lower ( ) , activity [ 'id' ] ) ) self . execute ( "ALTER TABLE categories ADD COLUMN search_name varchar2" ) categories = self . fetchall ( "select * from categories" ) statement = "update categories set search_name = ? where id = ?" for category in categories : self . execute ( statement , ( category [ 'name' ] . lower ( ) , category [ 'id' ] ) ) if version < 9 : self . execute ( ) if version < current_version : self . execute ( "UPDATE version SET version = %d" % current_version ) print ( "updated database from version %d to %d" % ( version , current_version ) ) self . end_transaction ( ) | upgrade DB to hamster version |
38,022 | def current_fact_index ( self ) : facts_ids = [ fact . id for fact in self . facts ] return facts_ids . index ( self . current_fact . id ) | Current fact index in the self . facts list . |
38,023 | def chain ( * steps ) : if not steps : return def on_done ( sprite = None ) : chain ( * steps [ 2 : ] ) obj , params = steps [ : 2 ] if len ( steps ) > 2 : params [ 'on_complete' ] = on_done if callable ( obj ) : obj ( ** params ) else : obj . animate ( ** params ) | chains the given list of functions and object animations into a callback string . |
38,024 | def full_pixels ( space , data , gap_pixels = 1 ) : available = space - ( len ( data ) - 1 ) * gap_pixels res = [ ] for i , val in enumerate ( data ) : data_sum = sum ( data [ i : ] ) norm = val * 1.0 / data_sum w = max ( int ( round ( available * norm ) ) , 1 ) res . append ( w ) available -= w return res | returns the given data distributed in the space ensuring it s full pixels and with the given gap . this will result in minor sub - pixel inaccuracies . XXX - figure out where to place these guys as they are quite useful |
38,025 | def gdk ( self , color ) : c = self . parse ( color ) return gdk . Color . from_floats ( c ) | returns gdk . Color object of the given color |
38,026 | def contrast ( self , color , step ) : hls = colorsys . rgb_to_hls ( * self . rgb ( color ) ) if self . is_light ( color ) : return colorsys . hls_to_rgb ( hls [ 0 ] , hls [ 1 ] - step , hls [ 2 ] ) else : return colorsys . hls_to_rgb ( hls [ 0 ] , hls [ 1 ] + step , hls [ 2 ] ) | if color is dark will return a lighter one otherwise darker |
38,027 | def mix ( self , ca , cb , xb ) : r = ( 1 - xb ) * ca . red + xb * cb . red g = ( 1 - xb ) * ca . green + xb * cb . green b = ( 1 - xb ) * ca . blue + xb * cb . blue a = ( 1 - xb ) * ca . alpha + xb * cb . alpha return gdk . RGBA ( red = r , green = g , blue = b , alpha = a ) | Mix colors . |
38,028 | def set_line_style ( self , width = None , dash = None , dash_offset = 0 ) : if width is not None : self . _add_instruction ( "set_line_width" , width ) if dash is not None : self . _add_instruction ( "set_dash" , dash , dash_offset ) | change width and dash of a line |
38,029 | def _set_color ( self , context , r , g , b , a ) : if a < 1 : context . set_source_rgba ( r , g , b , a ) else : context . set_source_rgb ( r , g , b ) | the alpha has to changed based on the parent so that happens at the time of drawing |
38,030 | def arc ( self , x , y , radius , start_angle , end_angle ) : self . _add_instruction ( "arc" , x , y , radius , start_angle , end_angle ) | draw arc going counter - clockwise from start_angle to end_angle |
38,031 | def ellipse ( self , x , y , width , height , edges = None ) : steps = edges or max ( ( 32 , width , height ) ) / 2 angle = 0 step = math . pi * 2 / steps points = [ ] while angle < math . pi * 2 : points . append ( ( width / 2.0 * math . cos ( angle ) , height / 2.0 * math . sin ( angle ) ) ) angle += step min_x = min ( ( point [ 0 ] for point in points ) ) min_y = min ( ( point [ 1 ] for point in points ) ) self . move_to ( points [ 0 ] [ 0 ] - min_x + x , points [ 0 ] [ 1 ] - min_y + y ) for p_x , p_y in points : self . line_to ( p_x - min_x + x , p_y - min_y + y ) self . line_to ( points [ 0 ] [ 0 ] - min_x + x , points [ 0 ] [ 1 ] - min_y + y ) | draw perfect ellipse opposed to squashed circle . works also for equilateral polygons |
38,032 | def arc_negative ( self , x , y , radius , start_angle , end_angle ) : self . _add_instruction ( "arc_negative" , x , y , radius , start_angle , end_angle ) | draw arc going clockwise from start_angle to end_angle |
38,033 | def rectangle ( self , x , y , width , height , corner_radius = 0 ) : if corner_radius <= 0 : self . _add_instruction ( "rectangle" , x , y , width , height ) return if isinstance ( corner_radius , ( int , float ) ) : corner_radius = [ corner_radius ] * 4 corner_radius = [ min ( r , min ( width , height ) / 2 ) for r in corner_radius ] x2 , y2 = x + width , y + height self . _rounded_rectangle ( x , y , x2 , y2 , corner_radius ) | draw a rectangle . if corner_radius is specified will draw rounded corners . corner_radius can be either a number or a tuple of four items to specify individually each corner starting from top - left and going clockwise |
38,034 | def fill_area ( self , x , y , width , height , color , opacity = 1 ) : self . save_context ( ) self . rectangle ( x , y , width , height ) self . _add_instruction ( "clip" ) self . rectangle ( x , y , width , height ) self . fill ( color , opacity ) self . restore_context ( ) | fill rectangular area with specified color |
38,035 | def fill_stroke ( self , fill = None , stroke = None , opacity = 1 , line_width = None ) : if line_width : self . set_line_style ( line_width ) if fill and stroke : self . fill_preserve ( fill , opacity ) elif fill : self . fill ( fill , opacity ) if stroke : self . stroke ( stroke ) | fill and stroke the drawn area in one go |
38,036 | def create_layout ( self , size = None ) : if not self . context : raise Exception ( "Can not create layout without existing context!" ) layout = pangocairo . create_layout ( self . context ) font_desc = pango . FontDescription ( _font_desc ) if size : font_desc . set_absolute_size ( size * pango . SCALE ) layout . set_font_description ( font_desc ) return layout | utility function to create layout with the default font . Size and alignment parameters are shortcuts to according functions of the pango . Layout |
38,037 | def show_label ( self , text , size = None , color = None , font_desc = None ) : font_desc = pango . FontDescription ( font_desc or _font_desc ) if color : self . set_color ( color ) if size : font_desc . set_absolute_size ( size * pango . SCALE ) self . show_layout ( text , font_desc ) | display text . unless font_desc is provided will use system s default font |
38,038 | def _draw ( self , context , opacity ) : fresh_draw = len ( self . __new_instructions or [ ] ) > 0 if fresh_draw : self . paths = [ ] self . __instruction_cache = self . __new_instructions self . __new_instructions = [ ] else : if not self . __instruction_cache : return for instruction , args in self . __instruction_cache : if fresh_draw : if instruction in ( "new_path" , "stroke" , "fill" , "clip" ) : self . paths . append ( ( instruction , "path" , context . copy_path ( ) ) ) elif instruction in ( "save" , "restore" , "translate" , "scale" , "rotate" ) : self . paths . append ( ( instruction , "transform" , args ) ) if instruction == "set_color" : self . _set_color ( context , args [ 0 ] , args [ 1 ] , args [ 2 ] , args [ 3 ] * opacity ) elif instruction == "show_layout" : self . _show_layout ( context , * args ) elif opacity < 1 and instruction == "paint" : context . paint_with_alpha ( opacity ) else : getattr ( context , instruction ) ( * args ) | draw accumulated instructions in context |
38,039 | def find ( self , id ) : for sprite in self . sprites : if sprite . id == id : return sprite for sprite in self . sprites : found = sprite . find ( id ) if found : return found | breadth - first sprite search by ID |
38,040 | def traverse ( self , attr_name = None , attr_value = None ) : for sprite in self . sprites : if ( attr_name is None ) or ( attr_value is None and hasattr ( sprite , attr_name ) ) or ( attr_value is not None and getattr ( sprite , attr_name , None ) == attr_value ) : yield sprite for child in sprite . traverse ( attr_name , attr_value ) : yield child | traverse the whole sprite tree and return child sprites which have the attribute and it s set to the specified value . If falue is None will return all sprites that have the attribute |
38,041 | def log ( self , * lines ) : if getattr ( self , "debug" , False ) : print ( dt . datetime . now ( ) . time ( ) , end = ' ' ) for line in lines : print ( line , end = ' ' ) print ( ) | will print out the lines in console if debug is enabled for the specific sprite |
38,042 | def _add ( self , sprite , index = None ) : if sprite == self : raise Exception ( "trying to add sprite to itself" ) if sprite . parent : sprite . x , sprite . y = self . from_scene_coords ( * sprite . to_scene_coords ( ) ) sprite . parent . remove_child ( sprite ) if index is not None : self . sprites . insert ( index , sprite ) else : self . sprites . append ( sprite ) sprite . parent = self | add one sprite at a time . used by add_child . split them up so that it would be possible specify the index externally |
38,043 | def _sort ( self ) : self . __dict__ [ '_z_ordered_sprites' ] = sorted ( self . sprites , key = lambda sprite : sprite . z_order ) | sort sprites by z_order |
38,044 | def add_child ( self , * sprites ) : for sprite in sprites : self . _add ( sprite ) self . _sort ( ) self . redraw ( ) | Add child sprite . Child will be nested within parent |
38,045 | def all_child_sprites ( self ) : for sprite in self . sprites : for child_sprite in sprite . all_child_sprites ( ) : yield child_sprite yield sprite | returns all child and grandchild sprites in a flat list |
38,046 | def disconnect_child ( self , sprite , * handlers ) : handlers = handlers or self . _child_handlers . get ( sprite , [ ] ) for handler in list ( handlers ) : if sprite . handler_is_connected ( handler ) : sprite . disconnect ( handler ) if handler in self . _child_handlers . get ( sprite , [ ] ) : self . _child_handlers [ sprite ] . remove ( handler ) if not self . _child_handlers [ sprite ] : del self . _child_handlers [ sprite ] | disconnects from child event . if handler is not specified will disconnect from all the child sprite events |
38,047 | def _get_mouse_cursor ( self ) : if self . mouse_cursor is not None : return self . mouse_cursor elif self . interactive and self . draggable : return gdk . CursorType . FLEUR elif self . interactive : return gdk . CursorType . HAND2 | Determine mouse cursor . By default look for self . mouse_cursor is defined and take that . Otherwise use gdk . CursorType . FLEUR for draggable sprites and gdk . CursorType . HAND2 for interactive sprites . Defaults to scenes cursor . |
38,048 | def bring_to_front ( self ) : if not self . parent : return self . z_order = self . parent . _z_ordered_sprites [ - 1 ] . z_order + 1 | adjusts sprite s z - order so that the sprite is on top of it s siblings |
38,049 | def send_to_back ( self ) : if not self . parent : return self . z_order = self . parent . _z_ordered_sprites [ 0 ] . z_order - 1 | adjusts sprite s z - order so that the sprite is behind it s siblings |
38,050 | def blur ( self ) : scene = self . get_scene ( ) if scene and scene . _focus_sprite == self : scene . _focus_sprite = None | removes focus from the current element if it has it |
38,051 | def get_parents ( self ) : res = [ ] parent = self . parent while parent and isinstance ( parent , Scene ) == False : res . insert ( 0 , parent ) parent = parent . parent return res | returns all the parent sprites up until scene |
38,052 | def get_extents ( self ) : if self . _sprite_dirty : context = cairo . Context ( cairo . ImageSurface ( cairo . FORMAT_A1 , 0 , 0 ) ) context . transform ( self . get_matrix ( ) ) self . emit ( "on-render" ) self . __dict__ [ "_sprite_dirty" ] = False self . graphics . _draw ( context , 1 ) if not self . graphics . paths : self . graphics . _draw ( cairo . Context ( cairo . ImageSurface ( cairo . FORMAT_A1 , 0 , 0 ) ) , 1 ) if not self . graphics . paths : return None context = cairo . Context ( cairo . ImageSurface ( cairo . FORMAT_A1 , 0 , 0 ) ) clip_extents = None for parent in self . get_parents ( ) : context . transform ( parent . get_local_matrix ( ) ) if parent . graphics . paths : clip_regions = [ ] for instruction , type , path in parent . graphics . paths : if instruction == "clip" : context . append_path ( path ) context . save ( ) context . identity_matrix ( ) clip_regions . append ( context . fill_extents ( ) ) context . restore ( ) context . new_path ( ) elif instruction == "restore" and clip_regions : clip_regions . pop ( ) for ext in clip_regions : ext = get_gdk_rectangle ( int ( ext [ 0 ] ) , int ( ext [ 1 ] ) , int ( ext [ 2 ] - ext [ 0 ] ) , int ( ext [ 3 ] - ext [ 1 ] ) ) intersect , clip_extents = gdk . rectangle_intersect ( ( clip_extents or ext ) , ext ) context . transform ( self . get_local_matrix ( ) ) for instruction , type , path in self . graphics . paths : if type == "path" : context . append_path ( path ) else : getattr ( context , instruction ) ( * path ) context . identity_matrix ( ) ext = context . path_extents ( ) ext = get_gdk_rectangle ( int ( ext [ 0 ] ) , int ( ext [ 1 ] ) , int ( ext [ 2 ] - ext [ 0 ] ) , int ( ext [ 3 ] - ext [ 1 ] ) ) if clip_extents : intersect , ext = gdk . rectangle_intersect ( clip_extents , ext ) if not ext . width and not ext . height : ext = None self . __dict__ [ '_stroke_context' ] = context return ext | measure the extents of the sprite s graphics . |
38,053 | def check_hit ( self , x , y ) : extents = self . get_extents ( ) if not extents : return False if extents . x <= x <= extents . x + extents . width and extents . y <= y <= extents . y + extents . height : return self . _stroke_context is None or self . _stroke_context . in_fill ( x , y ) else : return False | check if the given coordinates are inside the sprite s fill or stroke path |
38,054 | def get_matrix ( self ) : if self . parent : return self . get_local_matrix ( ) * ( self . _prev_parent_matrix or self . parent . get_matrix ( ) ) else : return self . get_local_matrix ( ) | return sprite s current transformation matrix |
38,055 | def from_scene_coords ( self , x = 0 , y = 0 ) : matrix = self . get_matrix ( ) matrix . invert ( ) return matrix . transform_point ( x , y ) | Converts x y given in the scene coordinates to sprite s local ones coordinates |
38,056 | def stop_animation ( self , sprites ) : if isinstance ( sprites , list ) is False : sprites = [ sprites ] for sprite in sprites : self . tweener . kill_tweens ( sprite ) | stop animation without firing on_complete |
38,057 | def redraw ( self ) : if self . __drawing_queued == False : self . __drawing_queued = True self . _last_frame_time = dt . datetime . now ( ) gobject . timeout_add ( 1000 / self . framerate , self . __redraw_loop ) | Queue redraw . The redraw will be performed not more often than the framerate allows |
38,058 | def __redraw_loop ( self ) : self . queue_draw ( ) self . __drawing_queued = self . tweener and self . tweener . has_tweens ( ) return self . __drawing_queued | loop until there is nothing more to tween |
38,059 | def all_mouse_sprites ( self ) : def all_recursive ( sprites ) : if not sprites : return for sprite in sprites : if sprite . visible : yield sprite for child in all_recursive ( sprite . get_mouse_sprites ( ) ) : yield child return all_recursive ( self . get_mouse_sprites ( ) ) | Returns flat list of the sprite tree for simplified iteration |
38,060 | def get_sprite_at_position ( self , x , y ) : over = None for sprite in self . all_mouse_sprites ( ) : if sprite . interactive and sprite . check_hit ( x , y ) : over = sprite return over | Returns the topmost visible interactive sprite for given coordinates |
38,061 | def start_drag ( self , sprite , cursor_x = None , cursor_y = None ) : cursor_x , cursor_y = cursor_x or sprite . x , cursor_y or sprite . y self . _mouse_down_sprite = self . _drag_sprite = sprite sprite . drag_x , sprite . drag_y = self . _drag_sprite . x , self . _drag_sprite . y self . __drag_start_x , self . __drag_start_y = cursor_x , cursor_y self . __drag_started = True | start dragging given sprite |
38,062 | def pretty_print ( self , as_list = False , show_datetime = True ) : ppl = [ entry . pretty_print ( show_datetime ) for entry in self . entries ] if as_list : return ppl return u"\n" . join ( ppl ) | Return a Unicode string pretty print of the log entries . |
38,063 | def log ( self , message , severity = INFO , tag = u"" ) : entry = _LogEntry ( severity = severity , time = datetime . datetime . now ( ) , tag = tag , indentation = self . indentation , message = self . _sanitize ( message ) ) self . entries . append ( entry ) if self . tee : gf . safe_print ( entry . pretty_print ( show_datetime = self . tee_show_datetime ) ) return entry . time | Add a given message to the log and return its time . |
38,064 | def write ( self , path ) : with io . open ( path , "w" , encoding = "utf-8" ) as log_file : log_file . write ( self . pretty_print ( ) ) | Output the log to file . |
38,065 | def pretty_print ( self , show_datetime = True ) : if show_datetime : return u"[%s] %s %s%s: %s" % ( self . severity , gf . object_to_unicode ( self . time ) , u" " * self . indentation , self . tag , self . message ) return u"[%s] %s%s: %s" % ( self . severity , u" " * self . indentation , self . tag , self . message ) | Returns a Unicode string containing the pretty printing of a given log entry . |
38,066 | def _log ( self , message , severity = Logger . DEBUG ) : return self . logger . log ( message , severity , self . TAG ) | Log generic message |
38,067 | def log_exc ( self , message , exc = None , critical = True , raise_type = None ) : log_function = self . log_crit if critical else self . log_warn log_function ( message ) if exc is not None : log_function ( [ u"%s" , exc ] ) if raise_type is not None : raise_message = message if exc is not None : raise_message = u"%s : %s" % ( message , exc ) raise raise_type ( raise_message ) | Log exception and possibly raise exception . |
38,068 | def add_waveform ( self , waveform ) : if not isinstance ( waveform , PlotWaveform ) : self . log_exc ( u"waveform must be an instance of PlotWaveform" , None , True , TypeError ) self . waveform = waveform self . log ( u"Added waveform" ) | Add a waveform to the plot . |
38,069 | def add_timescale ( self , timescale ) : if not isinstance ( timescale , PlotTimeScale ) : self . log_exc ( u"timescale must be an instance of PlotTimeScale" , None , True , TypeError ) self . timescale = timescale self . log ( u"Added timescale" ) | Add a time scale to the plot . |
38,070 | def add_labelset ( self , labelset ) : if not isinstance ( labelset , PlotLabelset ) : self . log_exc ( u"labelset must be an instance of PlotLabelset" , None , True , TypeError ) self . labelsets . append ( labelset ) self . log ( u"Added labelset" ) | Add a set of labels to the plot . |
38,071 | def draw_png ( self , output_file_path , h_zoom = 5 , v_zoom = 30 ) : if not gf . file_can_be_written ( output_file_path ) : self . log_exc ( u"Cannot write to output file '%s'" % ( output_file_path ) , None , True , OSError ) widths = [ ls . width for ls in self . labelsets ] sum_height = sum ( [ ls . height for ls in self . labelsets ] ) if self . waveform is not None : widths . append ( self . waveform . width ) sum_height += self . waveform . height if self . timescale is not None : sum_height += self . timescale . height image_width = max ( widths ) image_height = sum_height image_width_px = image_width * h_zoom image_height_px = image_height * v_zoom self . log ( [ u"Building image with size (modules): %d %d" , image_width , image_height ] ) self . log ( [ u"Building image with size (px): %d %d" , image_width_px , image_height_px ] ) image_obj = Image . new ( "RGB" , ( image_width_px , image_height_px ) , color = PlotterColors . AUDACITY_BACKGROUND_GREY ) current_y = 0 if self . waveform is not None : self . log ( u"Drawing waveform" ) self . waveform . draw_png ( image_obj , h_zoom , v_zoom , current_y ) current_y += self . waveform . height timescale_y = current_y if self . timescale is not None : current_y += self . timescale . height for labelset in self . labelsets : self . log ( u"Drawing labelset" ) labelset . draw_png ( image_obj , h_zoom , v_zoom , current_y ) current_y += labelset . height if self . timescale is not None : self . log ( u"Drawing timescale" ) self . timescale . draw_png ( image_obj , h_zoom , v_zoom , timescale_y ) self . log ( [ u"Saving to file '%s'" , output_file_path ] ) image_obj . save ( output_file_path ) | Draw the current plot to a PNG file . |
38,072 | def text_bounding_box ( self , size_pt , text ) : if size_pt == 12 : mult = { "h" : 9 , "w_digit" : 5 , "w_space" : 2 } elif size_pt == 18 : mult = { "h" : 14 , "w_digit" : 9 , "w_space" : 2 } num_chars = len ( text ) return ( num_chars * mult [ "w_digit" ] + ( num_chars - 1 ) * mult [ "w_space" ] + 1 , mult [ "h" ] ) | Return the bounding box of the given text at the given font size . |
38,073 | def draw_png ( self , image , h_zoom , v_zoom , current_y ) : draw = ImageDraw . Draw ( image ) mws = self . rconf . mws pixels_per_second = int ( h_zoom / mws ) current_y_px = current_y * v_zoom font_height_pt = 18 font = ImageFont . truetype ( self . FONT_PATH , font_height_pt ) for i in range ( 0 , 1 + int ( self . max_time ) , self . time_step ) : begin_px = i * pixels_per_second left_px = begin_px - self . TICK_WIDTH right_px = begin_px + self . TICK_WIDTH top_px = current_y_px bottom_px = current_y_px + v_zoom draw . rectangle ( ( left_px , top_px , right_px , bottom_px ) , fill = PlotterColors . BLACK ) time_text = self . _time_string ( i ) left_px = begin_px + self . TICK_WIDTH + self . TEXT_MARGIN top_px = current_y_px + ( v_zoom - self . text_bounding_box ( font_height_pt , time_text ) [ 1 ] ) // 2 draw . text ( ( left_px , top_px ) , time_text , PlotterColors . BLACK , font = font ) | Draw this time scale to PNG . |
38,074 | def draw_png ( self , image , h_zoom , v_zoom , current_y ) : draw = ImageDraw . Draw ( image ) mws = self . rconf . mws rate = self . audio_file . audio_sample_rate samples = self . audio_file . audio_samples duration = self . audio_file . audio_length current_y_px = current_y * v_zoom half_waveform_px = ( self . height // 2 ) * v_zoom zero_y_px = current_y_px + half_waveform_px samples_per_pixel = int ( rate * mws / h_zoom ) pixels_per_second = int ( h_zoom / mws ) windows = len ( samples ) // samples_per_pixel if self . label is not None : font_height_pt = 18 font = ImageFont . truetype ( self . FONT_PATH , font_height_pt ) draw . text ( ( 0 , current_y_px ) , self . label , PlotterColors . BLACK , font = font ) for i in range ( windows ) : x = i * samples_per_pixel pos = numpy . clip ( samples [ x : ( x + samples_per_pixel ) ] , 0.0 , 1.0 ) mpos = numpy . max ( pos ) * half_waveform_px if self . fast : draw . line ( ( i , zero_y_px + mpos , i , zero_y_px - mpos ) , fill = PlotterColors . AUDACITY_DARK_BLUE , width = 1 ) else : neg = numpy . clip ( samples [ x : ( x + samples_per_pixel ) ] , - 1.0 , 0.0 ) spos = numpy . std ( pos ) * half_waveform_px sneg = numpy . std ( neg ) * half_waveform_px mneg = numpy . min ( neg ) * half_waveform_px draw . line ( ( i , zero_y_px - mneg , i , zero_y_px - mpos ) , fill = PlotterColors . AUDACITY_DARK_BLUE , width = 1 ) draw . line ( ( i , zero_y_px + sneg , i , zero_y_px - spos ) , fill = PlotterColors . AUDACITY_LIGHT_BLUE , width = 1 ) | Draw this waveform to PNG . |
38,075 | def print_result ( self , audio_len , start , end ) : msg = [ ] zero = 0 head_len = start text_len = end - start tail_len = audio_len - end msg . append ( u"" ) msg . append ( u"Head: %.3f %.3f (%.3f)" % ( zero , start , head_len ) ) msg . append ( u"Text: %.3f %.3f (%.3f)" % ( start , end , text_len ) ) msg . append ( u"Tail: %.3f %.3f (%.3f)" % ( end , audio_len , tail_len ) ) msg . append ( u"" ) zero_h = gf . time_to_hhmmssmmm ( 0 ) start_h = gf . time_to_hhmmssmmm ( start ) end_h = gf . time_to_hhmmssmmm ( end ) audio_len_h = gf . time_to_hhmmssmmm ( audio_len ) head_len_h = gf . time_to_hhmmssmmm ( head_len ) text_len_h = gf . time_to_hhmmssmmm ( text_len ) tail_len_h = gf . time_to_hhmmssmmm ( tail_len ) msg . append ( "Head: %s %s (%s)" % ( zero_h , start_h , head_len_h ) ) msg . append ( "Text: %s %s (%s)" % ( start_h , end_h , text_len_h ) ) msg . append ( "Tail: %s %s (%s)" % ( end_h , audio_len_h , tail_len_h ) ) msg . append ( u"" ) self . print_info ( u"\n" . join ( msg ) ) | Print result of SD . |
38,076 | def sync_map_leaves ( self , fragment_type = None ) : if ( self . sync_map is None ) or ( self . sync_map . fragments_tree is None ) : return [ ] return [ f for f in self . sync_map . leaves ( fragment_type ) ] | Return the list of non - empty leaves in the sync map associated with the task . |
38,077 | def output_sync_map_file ( self , container_root_path = None ) : if self . sync_map is None : self . log_exc ( u"The sync_map object has not been set" , None , True , TypeError ) if ( container_root_path is not None ) and ( self . sync_map_file_path is None ) : self . log_exc ( u"The (internal) path of the sync map has been set" , None , True , TypeError ) self . log ( [ u"container_root_path is %s" , container_root_path ] ) self . log ( [ u"self.sync_map_file_path is %s" , self . sync_map_file_path ] ) self . log ( [ u"self.sync_map_file_path_absolute is %s" , self . sync_map_file_path_absolute ] ) if ( container_root_path is not None ) and ( self . sync_map_file_path is not None ) : path = os . path . join ( container_root_path , self . sync_map_file_path ) elif self . sync_map_file_path_absolute : path = self . sync_map_file_path_absolute gf . ensure_parent_directory ( path ) self . log ( [ u"Output sync map to %s" , path ] ) eaf_audio_ref = self . configuration [ "o_eaf_audio_ref" ] head_tail_format = self . configuration [ "o_h_t_format" ] levels = self . configuration [ "o_levels" ] smil_audio_ref = self . configuration [ "o_smil_audio_ref" ] smil_page_ref = self . configuration [ "o_smil_page_ref" ] sync_map_format = self . configuration [ "o_format" ] self . log ( [ u"eaf_audio_ref is %s" , eaf_audio_ref ] ) self . log ( [ u"head_tail_format is %s" , head_tail_format ] ) self . log ( [ u"levels is %s" , levels ] ) self . log ( [ u"smil_audio_ref is %s" , smil_audio_ref ] ) self . log ( [ u"smil_page_ref is %s" , smil_page_ref ] ) self . log ( [ u"sync_map_format is %s" , sync_map_format ] ) self . log ( u"Calling sync_map.write..." ) parameters = { gc . PPN_TASK_OS_FILE_EAF_AUDIO_REF : eaf_audio_ref , gc . PPN_TASK_OS_FILE_HEAD_TAIL_FORMAT : head_tail_format , gc . PPN_TASK_OS_FILE_LEVELS : levels , gc . PPN_TASK_OS_FILE_SMIL_AUDIO_REF : smil_audio_ref , gc . PPN_TASK_OS_FILE_SMIL_PAGE_REF : smil_page_ref , } self . sync_map . write ( sync_map_format , path , parameters ) self . log ( u"Calling sync_map.write... done" ) return path | Output the sync map file for this task . |
38,078 | def _populate_audio_file ( self ) : self . log ( u"Populate audio file..." ) if self . audio_file_path_absolute is not None : self . log ( [ u"audio_file_path_absolute is '%s'" , self . audio_file_path_absolute ] ) self . audio_file = AudioFile ( file_path = self . audio_file_path_absolute , logger = self . logger ) self . audio_file . read_properties ( ) else : self . log ( u"audio_file_path_absolute is None" ) self . log ( u"Populate audio file... done" ) | Create the self . audio_file object by reading the audio file at self . audio_file_path_absolute . |
38,079 | def _populate_text_file ( self ) : self . log ( u"Populate text file..." ) if ( ( self . text_file_path_absolute is not None ) and ( self . configuration [ "language" ] is not None ) ) : parameters = { gc . PPN_TASK_IS_TEXT_FILE_IGNORE_REGEX : self . configuration [ "i_t_ignore_regex" ] , gc . PPN_TASK_IS_TEXT_FILE_TRANSLITERATE_MAP : self . configuration [ "i_t_transliterate_map" ] , gc . PPN_TASK_IS_TEXT_MPLAIN_WORD_SEPARATOR : self . configuration [ "i_t_mplain_word_separator" ] , gc . PPN_TASK_IS_TEXT_MUNPARSED_L1_ID_REGEX : self . configuration [ "i_t_munparsed_l1_id_regex" ] , gc . PPN_TASK_IS_TEXT_MUNPARSED_L2_ID_REGEX : self . configuration [ "i_t_munparsed_l2_id_regex" ] , gc . PPN_TASK_IS_TEXT_MUNPARSED_L3_ID_REGEX : self . configuration [ "i_t_munparsed_l3_id_regex" ] , gc . PPN_TASK_IS_TEXT_UNPARSED_CLASS_REGEX : self . configuration [ "i_t_unparsed_class_regex" ] , gc . PPN_TASK_IS_TEXT_UNPARSED_ID_REGEX : self . configuration [ "i_t_unparsed_id_regex" ] , gc . PPN_TASK_IS_TEXT_UNPARSED_ID_SORT : self . configuration [ "i_t_unparsed_id_sort" ] , gc . PPN_TASK_OS_FILE_ID_REGEX : self . configuration [ "o_id_regex" ] } self . text_file = TextFile ( file_path = self . text_file_path_absolute , file_format = self . configuration [ "i_t_format" ] , parameters = parameters , logger = self . logger ) self . text_file . set_language ( self . configuration [ "language" ] ) else : self . log ( u"text_file_path_absolute and/or language is None" ) self . log ( u"Populate text file... done" ) | Create the self . text_file object by reading the text file at self . text_file_path_absolute . |
38,080 | def _tree_to_string ( cls , root_element , xml_declaration = True , pretty_print = True ) : from lxml import etree return gf . safe_unicode ( etree . tostring ( root_element , encoding = "UTF-8" , method = "xml" , xml_declaration = xml_declaration , pretty_print = pretty_print ) ) | Return an lxml tree as a Unicode string . |
38,081 | def print_generic ( self , msg , prefix = None ) : if prefix is None : self . _log ( msg , Logger . INFO ) else : self . _log ( msg , prefix ) if self . use_sys : if ( prefix is not None ) and ( prefix in self . PREFIX_TO_PRINT_FUNCTION ) : self . PREFIX_TO_PRINT_FUNCTION [ prefix ] ( msg ) else : gf . safe_print ( msg ) | Print a message and log it . |
38,082 | def print_name_version ( self ) : if self . use_sys : self . print_generic ( u"%s v%s" % ( self . NAME , aeneas_version ) ) return self . exit ( self . HELP_EXIT_CODE ) | Print program name and version and exit . |
38,083 | def print_rconf_parameters ( self ) : if self . use_sys : self . print_info ( u"Available runtime configuration parameters:" ) self . print_generic ( u"\n" + u"\n" . join ( self . RCONF_PARAMETERS ) + u"\n" ) return self . exit ( self . HELP_EXIT_CODE ) | Print the list of runtime configuration parameters and exit . |
38,084 | def has_option ( self , target ) : if isinstance ( target , list ) : target_set = set ( target ) else : target_set = set ( [ target ] ) return len ( target_set & set ( self . actual_arguments ) ) > 0 | Return True if the actual arguments include the specified target option or if target is a list of options at least one of them . |
38,085 | def check_c_extensions ( self , name = None ) : if not gf . can_run_c_extension ( name = name ) : if name is None : self . print_warning ( u"Unable to load Python C Extensions" ) else : self . print_warning ( u"Unable to load Python C Extension %s" % ( name ) ) self . print_warning ( u"Running the slower pure Python code" ) self . print_warning ( u"See the documentation for directions to compile the Python C Extensions" ) return False return True | If C extensions cannot be run emit a warning and return False . Otherwise return True . If name is not None check just the C extension with that name . |
38,086 | def check_output_file ( self , path ) : if not gf . file_can_be_written ( path ) : self . print_error ( u"Unable to create file '%s'" % ( path ) ) self . print_error ( u"Make sure the file path is written/escaped correctly and that you have write permission on it" ) return False return True | If the given path cannot be written emit an error and return False . Otherwise return True . |
38,087 | def check_output_directory ( self , path ) : if not os . path . isdir ( path ) : self . print_error ( u"Directory '%s' does not exist" % ( path ) ) return False test_file = os . path . join ( path , u"file.test" ) if not gf . file_can_be_written ( test_file ) : self . print_error ( u"Unable to write inside directory '%s'" % ( path ) ) self . print_error ( u"Make sure the directory path is written/escaped correctly and that you have write permission on it" ) return False return True | If the given directory cannot be written emit an error and return False . Otherwise return True . |
38,088 | def is_safe ( self ) : self . log ( u"Checking if this container is safe" ) for entry in self . entries : if not self . is_entry_safe ( entry ) : self . log ( [ u"This container is not safe: found unsafe entry '%s'" , entry ] ) return False self . log ( u"This container is safe" ) return True | Return True if the container can be safely extracted that is if all its entries are safe False otherwise . |
38,089 | def entries ( self ) : self . log ( u"Getting entries" ) if not self . exists ( ) : self . log_exc ( u"This container does not exist. Wrong path?" , None , True , TypeError ) if self . actual_container is None : self . log_exc ( u"The actual container object has not been set" , None , True , TypeError ) return self . actual_container . entries | Return the sorted list of entries in this container each represented by its full path inside the container . |
38,090 | def find_entry ( self , entry , exact = True ) : if exact : self . log ( [ u"Finding entry '%s' with exact=True" , entry ] ) if entry in self . entries : self . log ( [ u"Found entry '%s'" , entry ] ) return entry else : self . log ( [ u"Finding entry '%s' with exact=False" , entry ] ) for ent in self . entries : if os . path . basename ( ent ) == entry : self . log ( [ u"Found entry '%s'" , ent ] ) return ent self . log ( [ u"Entry '%s' not found" , entry ] ) return None | Return the full path to the first entry whose file name equals the given entry path . |
38,091 | def read_entry ( self , entry ) : if not self . is_entry_safe ( entry ) : self . log ( [ u"Accessing entry '%s' is not safe" , entry ] ) return None if entry not in self . entries : self . log ( [ u"Entry '%s' not found in this container" , entry ] ) return None self . log ( [ u"Reading contents of entry '%s'" , entry ] ) try : return self . actual_container . read_entry ( entry ) except : self . log ( [ u"An error occurred while reading the contents of '%s'" , entry ] ) return None | Read the contents of an entry in this container and return them as a byte string . |
38,092 | def decompress ( self , output_path ) : self . log ( [ u"Decompressing the container into '%s'" , output_path ] ) if not self . exists ( ) : self . log_exc ( u"This container does not exist. Wrong path?" , None , True , TypeError ) if self . actual_container is None : self . log_exc ( u"The actual container object has not been set" , None , True , TypeError ) if not gf . directory_exists ( output_path ) : self . log_exc ( u"The output path is not an existing directory" , None , True , ValueError ) if not self . is_safe : self . log_exc ( u"This container contains unsafe entries" , None , True , ValueError ) self . actual_container . decompress ( output_path ) | Decompress the entire container into the given directory . |
38,093 | def compress ( self , input_path ) : self . log ( [ u"Compressing '%s' into this container" , input_path ] ) if self . file_path is None : self . log_exc ( u"The container path has not been set" , None , True , TypeError ) if self . actual_container is None : self . log_exc ( u"The actual container object has not been set" , None , True , TypeError ) if not gf . directory_exists ( input_path ) : self . log_exc ( u"The input path is not an existing directory" , None , True , ValueError ) gf . ensure_parent_directory ( input_path ) self . actual_container . compress ( input_path ) | Compress the contents of the given directory . |
38,094 | def exists ( self ) : return gf . file_exists ( self . file_path ) or gf . directory_exists ( self . file_path ) | Return True if the container has its path set and it exists False otherwise . |
38,095 | def _set_actual_container ( self ) : if self . container_format is None : self . log ( u"Inferring actual container format..." ) path_lowercased = self . file_path . lower ( ) self . log ( [ u"Lowercased file path: '%s'" , path_lowercased ] ) self . container_format = ContainerFormat . UNPACKED for fmt in ContainerFormat . ALLOWED_FILE_VALUES : if path_lowercased . endswith ( fmt ) : self . container_format = fmt break self . log ( u"Inferring actual container format... done" ) self . log ( [ u"Inferred format: '%s'" , self . container_format ] ) self . log ( u"Setting actual container..." ) class_map = { ContainerFormat . ZIP : ( _ContainerZIP , None ) , ContainerFormat . EPUB : ( _ContainerZIP , None ) , ContainerFormat . TAR : ( _ContainerTAR , "" ) , ContainerFormat . TAR_GZ : ( _ContainerTAR , ":gz" ) , ContainerFormat . TAR_BZ2 : ( _ContainerTAR , ":bz2" ) , ContainerFormat . UNPACKED : ( _ContainerUnpacked , None ) } actual_class , variant = class_map [ self . container_format ] self . actual_container = actual_class ( file_path = self . file_path , variant = variant , rconf = self . rconf , logger = self . logger ) self . log ( [ u"Actual container format: '%s'" , self . container_format ] ) self . log ( u"Setting actual container... done" ) | Set the actual container based on the specified container format . |
38,096 | def _synthesize_single_python_helper ( self , text , voice_code , output_file_path = None , return_audio_data = True ) : if len ( text ) == 0 : self . log ( u"len(text) is zero: returning 0.000" ) return ( True , ( TimeValue ( "0.000" ) , None , None , None ) ) voice_json_path = gf . safe_str ( gf . absolute_path ( "voice.json" , __file__ ) ) voice = speect . SVoice ( voice_json_path ) utt = voice . synth ( text ) audio = utt . features [ "audio" ] if output_file_path is None : self . log ( u"output_file_path is None => not saving to file" ) else : self . log ( u"output_file_path is not None => saving to file..." ) audio . save_riff ( gf . safe_str ( output_file_path ) ) self . log ( u"output_file_path is not None => saving to file... done" ) if not return_audio_data : self . log ( u"return_audio_data is True => return immediately" ) return ( True , None ) self . log ( u"return_audio_data is True => read and return audio data" ) waveform = audio . get_audio_waveform ( ) audio_sample_rate = int ( waveform [ "samplerate" ] ) audio_length = TimeValue ( audio . num_samples ( ) / audio_sample_rate ) audio_format = "pcm16" audio_samples = numpy . fromstring ( waveform [ "samples" ] , dtype = numpy . int16 ) . astype ( "float64" ) / 32768 return ( True , ( audio_length , audio_sample_rate , audio_format , audio_samples ) ) | This is an helper function to synthesize a single text fragment via a Python call . |
38,097 | def analyze ( self , config_string = None ) : try : if config_string is not None : self . log ( u"Analyzing container with the given config string" ) return self . _analyze_txt_config ( config_string = config_string ) elif self . container . has_config_xml : self . log ( u"Analyzing container with XML config file" ) return self . _analyze_xml_config ( config_contents = None ) elif self . container . has_config_txt : self . log ( u"Analyzing container with TXT config file" ) return self . _analyze_txt_config ( config_string = None ) else : self . log ( u"No configuration file in this container, returning None" ) except ( OSError , KeyError , TypeError ) as exc : self . log_exc ( u"An unexpected error occurred while analyzing" , exc , True , None ) return None | Analyze the given container and return the corresponding job object . |
38,098 | def _create_task ( self , task_info , config_string , sync_map_root_directory , job_os_hierarchy_type ) : self . log ( u"Converting config string to config dict" ) parameters = gf . config_string_to_dict ( config_string ) self . log ( u"Creating task" ) task = Task ( config_string , logger = self . logger ) task . configuration [ "description" ] = "Task %s" % task_info [ 0 ] self . log ( [ u"Task description: %s" , task . configuration [ "description" ] ] ) try : task . configuration [ "language" ] = parameters [ gc . PPN_TASK_LANGUAGE ] self . log ( [ u"Set language from task: '%s'" , task . configuration [ "language" ] ] ) except KeyError : task . configuration [ "language" ] = parameters [ gc . PPN_JOB_LANGUAGE ] self . log ( [ u"Set language from job: '%s'" , task . configuration [ "language" ] ] ) custom_id = task_info [ 0 ] task . configuration [ "custom_id" ] = custom_id self . log ( [ u"Task custom_id: %s" , task . configuration [ "custom_id" ] ] ) task . text_file_path = task_info [ 1 ] self . log ( [ u"Task text file path: %s" , task . text_file_path ] ) task . audio_file_path = task_info [ 2 ] self . log ( [ u"Task audio file path: %s" , task . audio_file_path ] ) task . sync_map_file_path = self . _compute_sync_map_file_path ( sync_map_root_directory , job_os_hierarchy_type , custom_id , task . configuration [ "o_name" ] ) self . log ( [ u"Task sync map file path: %s" , task . sync_map_file_path ] ) self . log ( u"Replacing placeholder in os_file_smil_audio_ref" ) task . configuration [ "o_smil_audio_ref" ] = self . _replace_placeholder ( task . configuration [ "o_smil_audio_ref" ] , custom_id ) self . log ( u"Replacing placeholder in os_file_smil_page_ref" ) task . configuration [ "o_smil_page_ref" ] = self . _replace_placeholder ( task . configuration [ "o_smil_page_ref" ] , custom_id ) self . log ( u"Returning task" ) return task | Create a task object from |
38,099 | def _compute_sync_map_file_path ( self , root , hierarchy_type , custom_id , file_name ) : prefix = root if hierarchy_type == HierarchyType . PAGED : prefix = gf . norm_join ( prefix , custom_id ) file_name_joined = gf . norm_join ( prefix , file_name ) return self . _replace_placeholder ( file_name_joined , custom_id ) | Compute the sync map file path inside the output container . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.