#NEWLINE# def labeled_neighbor( self , obj , judge , back = False ) : #NEWLINE# #INDENT# 'Returns the id of the "closest" labeled object to the one provided.\n        Notes:\n            - By "closest", it\'s mean the distance of the id numbers.\n            - Works both for TextSegment and for IEDocument\n            - If back is True, it\'s picked the previous item, otherwise, the next one.\n            - It\'s assumed that the obj provided HAS labeled evidence already. If not,\n              it\'s not possible to determine what is next. In such case, the id of the\n              last labeled object will be returned.\n\n            - If asking "next" and obj is currently the last, his id will be returned.\n            - If asking "prev" and obj is currently the first, his id will be returned.\n        ' #NEWLINE# filters = dict ( judge__isnull = False , label__isnull = False , relation = obj ) #NEWLINE# if ( judge is not None ) : #NEWLINE# #INDENT# filters [ 'judge' ] = judge #NEWLINE# #UNINDENT# judge_labels = EvidenceLabel . objects . filter ( ** filters ) #NEWLINE# if isinstance ( obj , TextSegment ) : #NEWLINE# #INDENT# segments = self . _matching_text_segments ( ) #NEWLINE# segments = segments . filter ( evidence_relations__labels__relation = self ) #NEWLINE# candidates_with_label = judge_labels . values_list ( 'evidence_candidate__segment' , flat = True ) #NEWLINE# segments = segments . filter ( id__in = candidates_with_label ) . distinct ( ) #NEWLINE# ids = list ( segments . values_list ( 'id' , flat = True ) . order_by ( 'id' ) ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if isinstance ( obj , IEDocument ) : #NEWLINE# #INDENT# ids = sorted ( set ( judge_labels . values_list ( 'evidence_candidate__segment__document_id' , flat = True ) ) ) #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# ids = [ ] #NEWLINE# #UNINDENT# #UNINDENT# if ( not ids ) : #NEWLINE# #INDENT# return None #NEWLINE# #UNINDENT# try : #NEWLINE# #INDENT# base_idx = ids . index ( obj . id ) #NEWLINE# #UNINDENT# except ValueError : #NEWLINE# #INDENT# return ids [ ( - 1 ) ] #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# if back : #NEWLINE# #INDENT# if ( base_idx == 0 ) : #NEWLINE# #INDENT# return obj . id #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# return ids [ ( base_idx - 1 ) ] #NEWLINE# #UNINDENT# #UNINDENT# else : #NEWLINE# #INDENT# if ( base_idx == ( len ( ids ) - 1 ) ) : #NEWLINE# #INDENT# return obj . id #NEWLINE# #UNINDENT# else : #NEWLINE# #INDENT# return ids [ ( base_idx + 1 ) ]