idx int64 0 252k | question stringlengths 48 5.28k | target stringlengths 5 1.23k |
|---|---|---|
236,800 | def set ( self , addr , values ) : addr -= self . _start_addr end = addr + len ( values ) if not 0 <= addr <= end <= len ( self . _data ) : addr += self . _start_addr raise IndexError ( "Invalid address range [{:#06x} - {:#06x}]" . format ( addr , addr + len ( values ) ) ) self . _data [ addr : end ] = values | Write list values to addr memory location in DataBank . |
236,801 | def from_bytearray ( self , stream ) : fmt = '>HHHBB' size_header = struct . calcsize ( fmt ) if len ( stream ) < size_header : raise EOFError ( self . transaction_id , self . protocol_id , self . length , self . unit_id , self . fcode ) = struct . unpack ( fmt , bytes ( stream [ : size_header ] ) ) size_total = size_h... | Constructs this frame from input data stream consuming as many bytes as necessary from the beginning of the stream . |
236,802 | def to_bytearray ( self ) : header = bytearray ( struct . pack ( '>HHHBB' , self . transaction_id , self . protocol_id , self . length , self . unit_id , self . fcode ) ) return header + self . data | Convert this frame into its bytearray representation . |
236,803 | def is_valid ( self ) : conditions = [ self . protocol_id == 0 , 2 <= self . length <= 260 , len ( self . data ) == self . length - 2 , ] return all ( conditions ) | Check integrity and validity of this frame . |
236,804 | def create_exception ( self , code ) : frame = deepcopy ( self ) frame . length = 3 frame . fcode += 0x80 frame . data = bytearray ( chr ( code ) ) return frame | Create an exception frame based on this frame . |
236,805 | def create_response ( self , data = None ) : frame = deepcopy ( self ) if data is not None : frame . data = data frame . length = 2 + len ( frame . data ) return frame | Create a response frame based on this frame . |
236,806 | def _all_expander ( fringe , iteration , viewer ) : expanded_neighbors = [ node . expand ( local_search = True ) for node in fringe ] if viewer : viewer . event ( 'expanded' , list ( fringe ) , expanded_neighbors ) list ( map ( fringe . extend , expanded_neighbors ) ) | Expander that expands all nodes on the fringe . |
236,807 | def beam ( problem , beam_size = 100 , iterations_limit = 0 , viewer = None ) : return _local_search ( problem , _all_expander , iterations_limit = iterations_limit , fringe_size = beam_size , random_initial_states = True , stop_when_no_better = iterations_limit == 0 , viewer = viewer ) | Beam search . |
236,808 | def _first_expander ( fringe , iteration , viewer ) : current = fringe [ 0 ] neighbors = current . expand ( local_search = True ) if viewer : viewer . event ( 'expanded' , [ current ] , [ neighbors ] ) fringe . extend ( neighbors ) | Expander that expands only the first node on the fringe . |
236,809 | def beam_best_first ( problem , beam_size = 100 , iterations_limit = 0 , viewer = None ) : return _local_search ( problem , _first_expander , iterations_limit = iterations_limit , fringe_size = beam_size , random_initial_states = True , stop_when_no_better = iterations_limit == 0 , viewer = viewer ) | Beam search best first . |
236,810 | def hill_climbing ( problem , iterations_limit = 0 , viewer = None ) : return _local_search ( problem , _first_expander , iterations_limit = iterations_limit , fringe_size = 1 , stop_when_no_better = True , viewer = viewer ) | Hill climbing search . |
236,811 | def hill_climbing_stochastic ( problem , iterations_limit = 0 , viewer = None ) : return _local_search ( problem , _random_best_expander , iterations_limit = iterations_limit , fringe_size = 1 , stop_when_no_better = iterations_limit == 0 , viewer = viewer ) | Stochastic hill climbing . |
236,812 | def hill_climbing_random_restarts ( problem , restarts_limit , iterations_limit = 0 , viewer = None ) : restarts = 0 best = None while restarts < restarts_limit : new = _local_search ( problem , _first_expander , iterations_limit = iterations_limit , fringe_size = 1 , random_initial_states = True , stop_when_no_better ... | Hill climbing with random restarts . |
236,813 | def _exp_schedule ( iteration , k = 20 , lam = 0.005 , limit = 100 ) : return k * math . exp ( - lam * iteration ) | Possible scheduler for simulated_annealing based on the aima example . |
236,814 | def simulated_annealing ( problem , schedule = _exp_schedule , iterations_limit = 0 , viewer = None ) : return _local_search ( problem , _create_simulated_annealing_expander ( schedule ) , iterations_limit = iterations_limit , fringe_size = 1 , stop_when_no_better = iterations_limit == 0 , viewer = viewer ) | Simulated annealing . |
236,815 | def _create_genetic_expander ( problem , mutation_chance ) : def _expander ( fringe , iteration , viewer ) : fitness = [ x . value for x in fringe ] sampler = InverseTransformSampler ( fitness , fringe ) new_generation = [ ] expanded_nodes = [ ] expanded_neighbors = [ ] for _ in fringe : node1 = sampler . sample ( ) no... | Creates an expander that expands the bests nodes of the population crossing over them . |
236,816 | def genetic ( problem , population_size = 100 , mutation_chance = 0.1 , iterations_limit = 0 , viewer = None ) : return _local_search ( problem , _create_genetic_expander ( problem , mutation_chance ) , iterations_limit = iterations_limit , fringe_size = population_size , random_initial_states = True , stop_when_no_bet... | Genetic search . |
236,817 | def _local_search ( problem , fringe_expander , iterations_limit = 0 , fringe_size = 1 , random_initial_states = False , stop_when_no_better = True , viewer = None ) : if viewer : viewer . event ( 'started' ) fringe = BoundedPriorityQueue ( fringe_size ) if random_initial_states : for _ in range ( fringe_size ) : s = p... | Basic algorithm for all local search algorithms . |
236,818 | def actions ( self , state ) : rows = string_to_list ( state ) row_e , col_e = find_location ( rows , 'e' ) actions = [ ] if row_e > 0 : actions . append ( rows [ row_e - 1 ] [ col_e ] ) if row_e < 2 : actions . append ( rows [ row_e + 1 ] [ col_e ] ) if col_e > 0 : actions . append ( rows [ row_e ] [ col_e - 1 ] ) if ... | Returns a list of the pieces we can move to the empty space . |
236,819 | def is_attribute ( method , name = None ) : if name is None : name = method . __name__ method . is_attribute = True method . name = name return method | Decorator for methods that are attributes . |
236,820 | def load ( cls , filepath ) : with open ( filepath , "rb" ) as filehandler : classifier = pickle . load ( filehandler ) if not isinstance ( classifier , Classifier ) : raise ValueError ( "Pickled object is not a Classifier" ) return classifier | Loads a pickled version of the classifier saved in filepath |
236,821 | def tree_to_str ( root ) : xs = [ ] for value , node , depth in iter_tree ( root ) : template = "{indent}" if node is not root : template += "case={value}\t" if node . attribute is None : template += "result={result} -- P={prob:.2}" else : template += "split by {split}:\t" + "(partial result={result} -- P={prob:.2})" l... | Returns a string representation of a decision tree with root node root . |
236,822 | def save ( self , filepath ) : if not filepath or not isinstance ( filepath , str ) : raise ValueError ( "Invalid filepath" ) with open ( filepath , "wb" ) as filehandler : pickle . dump ( self , filehandler ) | Saves the classifier to filepath . Because this classifier needs to save the dataset it must be something that can be pickled and not something like an iterator . |
236,823 | def _max_gain_split ( self , examples ) : gains = self . _new_set_of_gain_counters ( ) for example in examples : for gain in gains : gain . add ( example ) winner = max ( gains , key = lambda gain : gain . get_gain ( ) ) if not winner . get_target_class_counts ( ) : raise ValueError ( "Dataset is empty" ) return winner | Returns an OnlineInformationGain of the attribute with max gain based on examples . |
236,824 | def backtrack ( problem , variable_heuristic = '' , value_heuristic = '' , inference = True ) : assignment = { } domains = deepcopy ( problem . domains ) if variable_heuristic == MOST_CONSTRAINED_VARIABLE : variable_chooser = _most_constrained_variable_chooser elif variable_heuristic == HIGHEST_DEGREE_VARIABLE : variab... | Backtracking search . |
236,825 | def _most_constrained_variable_chooser ( problem , variables , domains ) : return sorted ( variables , key = lambda v : len ( domains [ v ] ) ) [ 0 ] | Choose the variable that has less available values . |
236,826 | def _highest_degree_variable_chooser ( problem , variables , domains ) : return sorted ( variables , key = lambda v : problem . var_degrees [ v ] , reverse = True ) [ 0 ] | Choose the variable that is involved on more constraints . |
236,827 | def _count_conflicts ( problem , assignment , variable = None , value = None ) : return len ( _find_conflicts ( problem , assignment , variable , value ) ) | Count the number of violated constraints on a given assignment . |
236,828 | def _find_conflicts ( problem , assignment , variable = None , value = None ) : if variable is not None and value is not None : assignment = deepcopy ( assignment ) assignment [ variable ] = value conflicts = [ ] for neighbors , constraint in problem . constraints : if all ( n in assignment for n in neighbors ) : if no... | Find violated constraints on a given assignment with the possibility of specifying a new variable and value to add to the assignment before checking . |
236,829 | def _least_constraining_values_sorter ( problem , assignment , variable , domains ) : def update_assignment ( value ) : new_assignment = deepcopy ( assignment ) new_assignment [ variable ] = value return new_assignment values = sorted ( domains [ variable ] [ : ] , key = lambda v : _count_conflicts ( problem , assignme... | Sort values based on how many conflicts they generate if assigned . |
236,830 | def _backtracking ( problem , assignment , domains , variable_chooser , values_sorter , inference = True ) : from simpleai . search . arc import arc_consistency_3 if len ( assignment ) == len ( problem . variables ) : return assignment pending = [ v for v in problem . variables if v not in assignment ] variable = varia... | Internal recursive backtracking algorithm . |
236,831 | def _min_conflicts_value ( problem , assignment , variable ) : return argmin ( problem . domains [ variable ] , lambda x : _count_conflicts ( problem , assignment , variable , x ) ) | Return the value generate the less number of conflicts . In case of tie a random value is selected among this values subset . |
236,832 | def min_conflicts ( problem , initial_assignment = None , iterations_limit = 0 ) : assignment = { } if initial_assignment : assignment . update ( initial_assignment ) else : for variable in problem . variables : value = _min_conflicts_value ( problem , assignment , variable ) assignment [ variable ] = value iteration =... | Min conflicts search . |
236,833 | def convert_to_binary ( variables , domains , constraints ) : def wdiff ( vars_ ) : def diff ( variables , values ) : hidden , other = variables if hidden . startswith ( 'hidden' ) : idx = vars_ . index ( other ) return values [ 1 ] == values [ 0 ] [ idx ] else : idx = vars_ . index ( hidden ) return values [ 0 ] == va... | Returns new constraint list all binary using hidden variables . |
236,834 | def boltzmann_exploration ( actions , utilities , temperature , action_counter ) : utilities = [ utilities [ x ] for x in actions ] temperature = max ( temperature , 0.01 ) _max = max ( utilities ) _min = min ( utilities ) if _max == _min : return random . choice ( actions ) utilities = [ math . exp ( ( ( u - _min ) / ... | returns an action with a probability depending on utilities and temperature |
236,835 | def mkconstraints ( ) : constraints = [ ] for j in range ( 1 , 10 ) : vars = [ "%s%d" % ( i , j ) for i in uppercase [ : 9 ] ] constraints . extend ( ( c , const_different ) for c in combinations ( vars , 2 ) ) for i in uppercase [ : 9 ] : vars = [ "%s%d" % ( i , j ) for j in range ( 1 , 10 ) ] constraints . extend ( (... | Make constraint list for binary constraint problem . |
236,836 | def precision ( classifier , testset ) : hit = 0 total = 0 for example in testset : if classifier . classify ( example ) [ 0 ] == classifier . target ( example ) : hit += 1 total += 1 if total == 0 : raise ValueError ( "Empty testset!" ) return hit / float ( total ) | Runs the classifier for each example in testset and verifies that the classification is correct using the target . |
236,837 | def kfold ( dataset , problem , method , k = 10 ) : if k <= 1 : raise ValueError ( "k argument must be at least 2" ) dataset = list ( dataset ) random . shuffle ( dataset ) trials = 0 positive = 0 for i in range ( k ) : train = [ x for j , x in enumerate ( dataset ) if j % k != i ] test = [ x for j , x in enumerate ( d... | Does a k - fold on dataset with method . This is it randomly creates k - partitions of the dataset and k - times trains the method with k - 1 parts and runs it with the partition left . After all this returns the overall success ratio . |
236,838 | def actions ( self , state ) : 'actions are index where we can make a move' actions = [ ] for index , char in enumerate ( state ) : if char == '_' : actions . append ( index ) return actions | actions are index where we can make a move |
236,839 | def actions ( self , s ) : return [ a for a in self . _actions if self . _is_valid ( self . result ( s , a ) ) ] | Possible actions from a state . |
236,840 | def _is_valid ( self , s ) : return ( ( s [ 0 ] >= s [ 1 ] or s [ 0 ] == 0 ) ) and ( ( 3 - s [ 0 ] ) >= ( 3 - s [ 1 ] ) or s [ 0 ] == 3 ) and ( 0 <= s [ 0 ] <= 3 ) and ( 0 <= s [ 1 ] <= 3 ) | Check if a state is valid . |
236,841 | def result ( self , s , a ) : if s [ 2 ] == 0 : return ( s [ 0 ] - a [ 1 ] [ 0 ] , s [ 1 ] - a [ 1 ] [ 1 ] , 1 ) else : return ( s [ 0 ] + a [ 1 ] [ 0 ] , s [ 1 ] + a [ 1 ] [ 1 ] , 0 ) | Result of applying an action to a state . |
236,842 | def arc_consistency_3 ( domains , constraints ) : arcs = list ( all_arcs ( constraints ) ) pending_arcs = set ( arcs ) while pending_arcs : x , y = pending_arcs . pop ( ) if revise ( domains , ( x , y ) , constraints ) : if len ( domains [ x ] ) == 0 : return False pending_arcs = pending_arcs . union ( ( x2 , y2 ) for ... | Makes a CSP problem arc consistent . |
236,843 | def expand ( self , local_search = False ) : new_nodes = [ ] for action in self . problem . actions ( self . state ) : new_state = self . problem . result ( self . state , action ) cost = self . problem . cost ( self . state , action , new_state ) nodefactory = self . __class__ new_nodes . append ( nodefactory ( state ... | Create successors . |
236,844 | def step ( self , viewer = None ) : "This method evolves one step in time" if not self . is_completed ( self . state ) : for agent in self . agents : action = agent . program ( self . percept ( agent , self . state ) ) next_state = self . do_action ( self . state , action , agent ) if viewer : viewer . event ( self . s... | This method evolves one step in time |
236,845 | def breadth_first ( problem , graph_search = False , viewer = None ) : return _search ( problem , FifoList ( ) , graph_search = graph_search , viewer = viewer ) | Breadth first search . |
236,846 | def depth_first ( problem , graph_search = False , viewer = None ) : return _search ( problem , LifoList ( ) , graph_search = graph_search , viewer = viewer ) | Depth first search . |
236,847 | def limited_depth_first ( problem , depth_limit , graph_search = False , viewer = None ) : return _search ( problem , LifoList ( ) , graph_search = graph_search , depth_limit = depth_limit , viewer = viewer ) | Limited depth first search . |
236,848 | def iterative_limited_depth_first ( problem , graph_search = False , viewer = None ) : solution = None limit = 0 while not solution : solution = limited_depth_first ( problem , depth_limit = limit , graph_search = graph_search , viewer = viewer ) limit += 1 if viewer : viewer . event ( 'no_more_runs' , solution , 'retu... | Iterative limited depth first search . |
236,849 | def uniform_cost ( problem , graph_search = False , viewer = None ) : return _search ( problem , BoundedPriorityQueue ( ) , graph_search = graph_search , node_factory = SearchNodeCostOrdered , graph_replace_when_better = True , viewer = viewer ) | Uniform cost search . |
236,850 | def greedy ( problem , graph_search = False , viewer = None ) : return _search ( problem , BoundedPriorityQueue ( ) , graph_search = graph_search , node_factory = SearchNodeHeuristicOrdered , graph_replace_when_better = True , viewer = viewer ) | Greedy search . |
236,851 | def _search ( problem , fringe , graph_search = False , depth_limit = None , node_factory = SearchNode , graph_replace_when_better = False , viewer = None ) : if viewer : viewer . event ( 'started' ) memory = set ( ) initial_node = node_factory ( state = problem . initial_state , problem = problem ) fringe . append ( i... | Basic search algorithm base of all the other search algorithms . |
236,852 | def _get_tree_paths ( tree , node_id , depth = 0 ) : if node_id == _tree . TREE_LEAF : raise ValueError ( "Invalid node_id %s" % _tree . TREE_LEAF ) left_child = tree . children_left [ node_id ] right_child = tree . children_right [ node_id ] if left_child != _tree . TREE_LEAF : left_paths = _get_tree_paths ( tree , le... | Returns all paths through the tree as list of node_ids |
236,853 | def extract_keywords_from_text ( self , text ) : sentences = nltk . tokenize . sent_tokenize ( text ) self . extract_keywords_from_sentences ( sentences ) | Method to extract keywords from the text provided . |
236,854 | def extract_keywords_from_sentences ( self , sentences ) : phrase_list = self . _generate_phrases ( sentences ) self . _build_frequency_dist ( phrase_list ) self . _build_word_co_occurance_graph ( phrase_list ) self . _build_ranklist ( phrase_list ) | Method to extract keywords from the list of sentences provided . |
236,855 | def _build_word_co_occurance_graph ( self , phrase_list ) : co_occurance_graph = defaultdict ( lambda : defaultdict ( lambda : 0 ) ) for phrase in phrase_list : for ( word , coword ) in product ( phrase , phrase ) : co_occurance_graph [ word ] [ coword ] += 1 self . degree = defaultdict ( lambda : 0 ) for key in co_occ... | Builds the co - occurance graph of words in the given body of text to compute degree of each word . |
236,856 | def _build_ranklist ( self , phrase_list ) : self . rank_list = [ ] for phrase in phrase_list : rank = 0.0 for word in phrase : if self . metric == Metric . DEGREE_TO_FREQUENCY_RATIO : rank += 1.0 * self . degree [ word ] / self . frequency_dist [ word ] elif self . metric == Metric . WORD_DEGREE : rank += 1.0 * self .... | Method to rank each contender phrase using the formula |
236,857 | def _generate_phrases ( self , sentences ) : phrase_list = set ( ) for sentence in sentences : word_list = [ word . lower ( ) for word in wordpunct_tokenize ( sentence ) ] phrase_list . update ( self . _get_phrase_list_from_words ( word_list ) ) return phrase_list | Method to generate contender phrases given the sentences of the text document . |
236,858 | def _retain_centroids ( numbers , thres ) : numbers . sort ( ) prev = - 1 ret = [ ] for n in numbers : if prev < 0 or n - prev > thres : ret . append ( n ) prev = n return ret | Only keep one number for each cluster within thres of each other |
236,859 | def _split_vlines_hlines ( lines ) : vlines , hlines = [ ] , [ ] for line in lines : ( vlines if line . x1 - line . x0 < 0.1 else hlines ) . append ( line ) return vlines , hlines | Separates lines into horizontal and vertical ones |
236,860 | def _npiter ( arr ) : for a in np . nditer ( arr , flags = [ "refs_ok" ] ) : c = a . item ( ) if c is not None : yield c | Wrapper for iterating numpy array |
236,861 | def get_normalized_grid ( self ) : log = logging . getLogger ( __name__ ) mega_rows = [ ] for row_id , row in enumerate ( self . _grid ) : subrow_across_cell = defaultdict ( list ) for col_id , cell in enumerate ( row ) : cell . texts . sort ( key = cmp_to_key ( reading_order ) ) log . debug ( "=" * 50 ) for m in cell ... | Analyzes subcell structure |
236,862 | def _mark_grid_bounds ( self , plane , region_bbox ) : vbars = np . zeros ( [ self . num_rows , self . num_cols + 1 ] , dtype = np . bool ) hbars = np . zeros ( [ self . num_rows + 1 , self . num_cols ] , dtype = np . bool ) def closest_idx ( arr , elem ) : left = bisect . bisect_left ( arr , elem ) - 1 right = bisect ... | Assume all lines define a complete grid over the region_bbox . Detect which lines are missing so that we can recover merged cells . |
236,863 | def vectorize ( e , tolerance = 0.1 ) : tolerance = max ( tolerance , e . linewidth ) is_high = e . height > tolerance is_wide = e . width > tolerance if is_wide and not is_high : return ( e . width , 0.0 ) if is_high and not is_wide : return ( 0.0 , e . height ) | vectorizes the pdf object s bounding box min_width is the width under which we consider it a line instead of a big rectangle |
236,864 | def aligned ( e1 , e2 ) : return ( any ( close ( c1 , c2 ) for c1 , c2 in zip ( e1 . bbox , e2 . bbox ) ) or x_center_aligned ( e1 , e2 ) or y_center_aligned ( e1 , e2 ) ) | alignment is determined by two boxes having one exactly the same attribute which could mean parallel perpendicularly forming a corner etc . |
236,865 | def bound_bboxes ( bboxes ) : group_x0 = min ( map ( lambda l : l [ x0 ] , bboxes ) ) group_y0 = min ( map ( lambda l : l [ y0 ] , bboxes ) ) group_x1 = max ( map ( lambda l : l [ x1 ] , bboxes ) ) group_y1 = max ( map ( lambda l : l [ y1 ] , bboxes ) ) return ( group_x0 , group_y0 , group_x1 , group_y1 ) | Finds the minimal bbox that contains all given bboxes |
236,866 | def bound_elems ( elems ) : group_x0 = min ( map ( lambda l : l . x0 , elems ) ) group_y0 = min ( map ( lambda l : l . y0 , elems ) ) group_x1 = max ( map ( lambda l : l . x1 , elems ) ) group_y1 = max ( map ( lambda l : l . y1 , elems ) ) return ( group_x0 , group_y0 , group_x1 , group_y1 ) | Finds the minimal bbox that contains all given elems |
236,867 | def intersect ( a , b ) : if a [ x0 ] == a [ x1 ] or a [ y0 ] == a [ y1 ] : return False if b [ x0 ] == b [ x1 ] or b [ y0 ] == b [ y1 ] : return False return a [ x0 ] <= b [ x1 ] and b [ x0 ] <= a [ x1 ] and a [ y0 ] <= b [ y1 ] and b [ y0 ] <= a [ y1 ] | Check if two rectangles intersect |
236,868 | def reading_order ( e1 , e2 ) : b1 = e1 . bbox b2 = e2 . bbox if round ( b1 [ y0 ] ) == round ( b2 [ y0 ] ) or round ( b1 [ y1 ] ) == round ( b2 [ y1 ] ) : return float_cmp ( b1 [ x0 ] , b2 [ x0 ] ) return float_cmp ( b1 [ y0 ] , b2 [ y0 ] ) | A comparator to sort bboxes from top to bottom left to right |
236,869 | def xy_reading_order ( e1 , e2 ) : b1 = e1 . bbox b2 = e2 . bbox if round ( b1 [ x0 ] ) == round ( b2 [ x0 ] ) : return float_cmp ( b1 [ y0 ] , b2 [ y0 ] ) return float_cmp ( b1 [ x0 ] , b2 [ x0 ] ) | A comparator to sort bboxes from left to right top to bottom |
236,870 | def column_order ( b1 , b2 ) : ( top , left , bottom ) = ( 1 , 2 , 3 ) if round ( b1 [ top ] ) == round ( b2 [ top ] ) or round ( b1 [ bottom ] ) == round ( b2 [ bottom ] ) : return float_cmp ( b1 [ left ] , b2 [ left ] ) return float_cmp ( b1 [ top ] , b2 [ top ] ) | A comparator that sorts bboxes first by columns where a column is made up of all bboxes that overlap then by vertical position in each column . |
236,871 | def merge_intervals ( elems , overlap_thres = 2.0 ) : overlap_thres = max ( 0.0 , overlap_thres ) ordered = sorted ( elems , key = lambda e : e . x0 ) intervals = [ ] cur = [ - overlap_thres , - overlap_thres ] for e in ordered : if e . x0 - cur [ 1 ] > overlap_thres : if cur [ 1 ] > 0.0 : intervals . append ( cur ) cu... | Project in x axis Sort by start Go through segments and keep max x1 |
236,872 | def predict_heatmap ( pdf_path , page_num , model , img_dim = 448 , img_dir = "tmp/img" ) : if not os . path . isdir ( img_dir ) : print ( "\nCreating image folder at {}" . format ( img_dir ) ) os . makedirs ( img_dir ) pdf_name = os . path . splitext ( os . path . basename ( pdf_path ) ) [ 0 ] img_path = os . path . j... | Return an image corresponding to the page of the pdf documents saved at pdf_path . If the image is not found in img_dir this function creates it and saves it in img_dir . |
236,873 | def do_intersect ( bb1 , bb2 ) : if bb1 [ 0 ] + bb1 [ 2 ] < bb2 [ 0 ] or bb2 [ 0 ] + bb2 [ 2 ] < bb1 [ 0 ] : return False if bb1 [ 1 ] + bb1 [ 3 ] < bb2 [ 1 ] or bb2 [ 1 ] + bb2 [ 3 ] < bb1 [ 1 ] : return False return True | Helper function that returns True if two bounding boxes overlap . |
236,874 | def get_bboxes ( img , mask , nb_boxes = 100 , score_thresh = 0.5 , iou_thresh = 0.2 , prop_size = 0.09 , prop_scale = 1.2 , ) : min_size = int ( img . shape [ 0 ] * prop_size * img . shape [ 1 ] * prop_size ) scale = int ( img . shape [ 0 ] * prop_scale ) img_lbl , regions = selectivesearch . selective_search ( img , ... | Uses selective search to generate candidate bounding boxes and keeps the ones that have the largest iou with the predicted mask . |
236,875 | def _print_dict ( elem_dict ) : for key , value in sorted ( elem_dict . iteritems ( ) ) : if isinstance ( value , collections . Iterable ) : print ( key , len ( value ) ) else : print ( key , value ) | Print a dict in a readable way |
236,876 | def _font_of_mention ( m ) : for ch in m : if isinstance ( ch , LTChar ) and ch . get_text ( ) . isalnum ( ) : return ( ch . fontname , _font_size_of ( ch ) ) return ( None , 0 ) | Returns the font type and size of the first alphanumeric char in the text or None if there isn t any . |
236,877 | def _allowed_char ( c ) : c = ord ( c ) if c < 0 : return False if c < 128 : return _ascii_allowed [ c ] return True | Returns whether the given unicode char is allowed in output |
236,878 | def keep_allowed_chars ( text ) : return "" . join ( " " if c == "\n" else c for c in text . strip ( ) if _allowed_char ( c ) ) | Cleans the text for output |
236,879 | def paint_path ( self , gstate , stroke , fill , evenodd , path ) : shape = "" . join ( x [ 0 ] for x in path ) prev_split = 0 for i in range ( len ( shape ) ) : if shape [ i ] == "m" and prev_split != i : self . paint_single_path ( gstate , stroke , fill , evenodd , path [ prev_split : i ] ) prev_split = i if shape [ ... | Converting long paths to small segments each time we m = Move or h = ClosePath for polygon |
236,880 | def paint_single_path ( self , gstate , stroke , fill , evenodd , path ) : if len ( path ) < 2 : return shape = "" . join ( x [ 0 ] for x in path ) pts = [ ] for p in path : for i in range ( 1 , len ( p ) , 2 ) : pts . append ( apply_matrix_pt ( self . ctm , ( p [ i ] , p [ i + 1 ] ) ) ) if self . line_only_shape . mat... | Converting a single path draw command into lines and curves objects |
236,881 | def traverse_layout ( root , callback ) : callback ( root ) if isinstance ( root , collections . Iterable ) : for child in root : traverse_layout ( child , callback ) | Tree walker and invokes the callback as it traverse pdf object tree |
236,882 | def get_near_items ( tree , tree_key ) : try : yield tree . floor_item ( tree_key ) except KeyError : pass try : yield tree . ceiling_item ( tree_key ) except KeyError : pass | Check both possible neighbors for key in a binary tree |
236,883 | def align_add ( tree , key , item , align_thres = 2.0 ) : for near_key , near_list in get_near_items ( tree , key ) : if abs ( key - near_key ) < align_thres : near_list . append ( item ) return tree [ key ] = [ item ] | Adding the item object to a binary tree with the given key while allow for small key differences close_enough_func that checks if two keys are within threshold |
236,884 | def collect_table_content ( table_bboxes , elems ) : table_contents = [ [ ] for _ in range ( len ( table_bboxes ) ) ] prev_content = None prev_bbox = None for cid , c in enumerate ( elems ) : if isinstance ( c , LTAnno ) : if prev_content is not None : prev_content . append ( c ) continue if prev_bbox is not None and i... | Returns a list of elements that are contained inside the corresponding supplied bbox . |
236,885 | def project_onto ( objs , axis , min_gap_size = 4.0 ) : if axis == "x" : axis = 0 if axis == "y" : axis = 1 axis_end = axis + 2 if axis == 0 : objs . sort ( key = lambda o : o . x0 ) else : objs . sort ( key = lambda o : o . y0 ) intervals = [ ] groups = [ ] start_i = 0 start = objs [ 0 ] . bbox [ axis ] end = objs [ 0... | Projects object bboxes onto the axis and return the unioned intervals and groups of objects in intervals . |
236,886 | def draw_rect ( self , bbox , cell_val ) : new_x0 = int ( bbox [ x0 ] ) new_y0 = int ( bbox [ y0 ] ) new_x1 = max ( new_x0 + 1 , int ( bbox [ x1 ] ) ) new_y1 = max ( new_y0 + 1 , int ( bbox [ y1 ] ) ) self . grid [ new_x0 : new_x1 , new_y0 : new_y1 ] = cell_val | Fills the bbox with the content values Float bbox values are normalized to have non - zero area |
236,887 | def parse_layout ( elems , font_stat , combine = False ) : boxes_segments = elems . segments boxes_curves = elems . curves boxes_figures = elems . figures page_width = elems . layout . width boxes = elems . mentions avg_font_pts = get_most_common_font_pts ( elems . mentions , font_stat ) width = get_page_width ( boxes ... | Parses pdf texts into a hypergraph grouped into rows and columns and then output |
236,888 | def merge_nodes ( nodes , plane , page_stat , merge_indices ) : to_be_removed = set ( ) for inner_idx in range ( len ( nodes ) ) : inner = nodes [ inner_idx ] outers = [ ] outers_indices = [ ] for outer_idx in range ( len ( nodes ) ) : outer = nodes [ outer_idx ] if outer is inner or outer in to_be_removed : continue i... | Merges overlapping nodes |
236,889 | def _get_cols ( row_content ) : cols = [ ] subcell_col = [ ] prev_bar = None for _coord , item in row_content : if isinstance ( item , LTTextLine ) : subcell_col . append ( item ) else : if prev_bar : bar_ranges = ( prev_bar , item ) col_items = subcell_col if subcell_col else [ None ] cols . extend ( [ bar_ranges , co... | Counting the number columns based on the content of this row |
236,890 | def _one_contains_other ( s1 , s2 ) : return min ( len ( s1 ) , len ( s2 ) ) == len ( s1 & s2 ) | Whether one set contains the other |
236,891 | def is_table ( self ) : if self . type_counts [ "text" ] < 6 or "figure" in self . type_counts : return False for e in self . elems : if elem_type ( e ) == "curve" and e . height * e . width > 100 : return False if ( self . sum_elem_bbox / ( self . height * self . width ) ) > self . table_area_threshold : return False ... | Count the node s number of mention al ignment in both axes to determine if the node is a table . |
236,892 | def get_grid ( self ) : mentions , lines = _split_text_n_lines ( self . elems ) mentions . sort ( key = lambda m : ( m . yc_grid , m . xc ) ) grid = Grid ( mentions , lines , self ) return grid | Standardize the layout of the table into grids |
236,893 | def lazy_load_font ( font_size = default_font_size ) : if font_size not in _font_cache : if _platform . startswith ( "darwin" ) : font_path = "/Library/Fonts/Arial.ttf" elif _platform . startswith ( "linux" ) : font_path = "/usr/share/fonts/truetype/ubuntu-font-family/UbuntuMono-R.ttf" elif _platform . startswith ( "wi... | Lazy loading font according to system platform |
236,894 | def render_debug_img ( file_name , page_num , elems , nodes = [ ] , scaler = 1 , print_segments = False , print_curves = True , print_table_bbox = True , print_text_as_rect = True , ) : height = scaler * int ( elems . layout . height ) width = scaler * int ( elems . layout . width ) debug_img , draw = create_img ( ( 0 ... | Shows an image rendering of the pdf page along with debugging info printed |
236,895 | def _partition_estimators ( n_estimators , n_jobs ) : if n_jobs == - 1 : n_jobs = min ( cpu_count ( ) , n_estimators ) else : n_jobs = min ( n_jobs , n_estimators ) n_estimators_per_job = ( n_estimators // n_jobs ) * np . ones ( n_jobs , dtype = np . int ) n_estimators_per_job [ : n_estimators % n_jobs ] += 1 starts = ... | Private function used to partition estimators between jobs . |
236,896 | def _parallel_build_estimators ( n_estimators , ensemble , X , y , cost_mat , seeds , verbose ) : n_samples , n_features = X . shape max_samples = ensemble . max_samples max_features = ensemble . max_features if ( not isinstance ( max_samples , ( numbers . Integral , np . integer ) ) and ( 0.0 < max_samples <= 1.0 ) ) ... | Private function used to build a batch of estimators within a job . |
236,897 | def _parallel_predict ( estimators , estimators_features , X , n_classes , combination , estimators_weight ) : n_samples = X . shape [ 0 ] pred = np . zeros ( ( n_samples , n_classes ) ) n_estimators = len ( estimators ) for estimator , features , weight in zip ( estimators , estimators_features , estimators_weight ) :... | Private function used to compute predictions within a job . |
236,898 | def _create_stacking_set ( estimators , estimators_features , estimators_weight , X , combination ) : n_samples = X . shape [ 0 ] valid_estimators = np . nonzero ( estimators_weight ) [ 0 ] n_valid_estimators = valid_estimators . shape [ 0 ] X_stacking = np . zeros ( ( n_samples , n_valid_estimators ) ) for e in range ... | Private function used to create the stacking training set . |
236,899 | def _fit_bmr_model ( self , X , y ) : self . f_bmr = BayesMinimumRiskClassifier ( ) X_bmr = self . predict_proba ( X ) self . f_bmr . fit ( y , X_bmr ) return self | Private function used to fit the BayesMinimumRisk model . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.