update handler for new output
Browse files2 unmodified lines3456781 unmodified line1011121314151613 unmodified lines30313233343536373823 unmodified lines62636465666723 unmodified lines919293949596121 unmodified lines21821922022122222322422528 unmodified lines25425525625725825926026121 unmodified lines28328428528628728828929 unmodified lines31932032132232332432532632732832933033111 unmodified lines3433443453462 unmodified linesimport numpy as npimport weakrefimport refrom utils import clean_str, clean_str_nopunctimport torch1 unmodified lineimport transformersfrom transformers import BertTokenizer, BertForSequenceClassificationtransformers.logging.set_verbosity_debug()13 unmodified linesself.endtime = endtimeself.transcript = weakref.ref(transcript) if transcript else Noneself.props = kwargsself.num_math_terms = Noneself.math_terms = Noneself.uptake = Noneself.reasoning = Noneself.question = None23 unmodified lines**self.props}def __repr__(self):return f"Utterance(speaker='{self.speaker}'," \f"text='{self.text}', uid={self.uid}," \23 unmodified linesdef length(self):return len(self.utterances)def to_dict(self):return {'utterances': [utterance.to_dict() for utterance in self.utterances],121 unmodified linesreturn_pooler_output=False)return outputclass FocusingQuestionModel:def __init__(self, device, tokenizer, input_builder, max_length=128, path=FOCUSING_QUESTION_MODEL):print("Loading models...")28 unmodified linesoutput = self.model(input_ids=instance["input_ids"],attention_mask=instance["attention_mask"],token_type_ids=instance["token_type_ids"])return outputdef load_math_terms():math_terms = []21 unmodified linesmatches = [match for match in matches if not any(match.start() in range(existing[0], existing[1]) for existing in matched_positions)]if len(matches) > 0:match_list.append(math_terms_dict[term])# Update existing match positionsmatched_positions.update((match.start(), match.end()) for match in matches)num_matches += len(matches)utt.num_math_terms = num_matches29 unmodified linestranscript.add_utterance(Utterance(**utt))print("Running inference on %d examples..." % transcript.length())uptake_speaker = params.pop("uptake_speaker", None)# Uptakeuptake_model = UptakeModel(self.device, self.tokenizer, self.input_builder)uptake_model.run_inference(transcript, min_prev_words=params['uptake_min_num_words'],uptake_speaker=uptake_speaker)# Reasoningreasoning_model = ReasoningModel(self.device, self.tokenizer, self.input_builder)11 unmodified linesrun_math_density(transcript)return transcript.to_dict()2 unmodified lines345678910111 unmodified line1314151617181913 unmodified lines33343536373839404142434445464723 unmodified lines71727374757677787980818283848586878889909123 unmodified lines115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200121 unmodified lines32232332432532632728 unmodified lines35635735835936036136221 unmodified lines38438538638738838939029 unmodified lines42042142242342442542642742842943043143211 unmodified lines4444454464474484494504514524534544554564574584594602 unmodified linesimport numpy as npimport weakrefimport reimport nltkfrom nltk.corpus import stopwordsnltk.download('stopwords')from utils import clean_str, clean_str_nopunctimport torch1 unmodified lineimport transformersfrom transformers import BertTokenizer, BertForSequenceClassificationfrom transformers.utils import loggingtransformers.logging.set_verbosity_debug()13 unmodified linesself.endtime = endtimeself.transcript = weakref.ref(transcript) if transcript else Noneself.props = kwargsself.role = Noneself.word_count = self.get_num_words()self.timestamp = [starttime, endtime]self.unit_measure = Noneself.aggregate_unit_measure = endtimeself.num_math_terms = Noneself.math_terms = None# momentsself.uptake = Noneself.reasoning = Noneself.question = None23 unmodified lines**self.props}def to_talk_timeline_dict(self):return{'speaker': self.speaker,'text': self.text,'uid': self.uid,'role': self.role,'timestamp': self.timestamp,'moments': {'reasoning': True if self.reasoning else False, 'questioning': True if self.question else False, 'uptake': True if self.uptake else False, 'focusingQuestion': True if self.focusing_question else False},'unitMeasure': self.unit_measure,'aggregateUnitMeasure': self.aggregate_unit_measure,'wordCount': self.word_count,'numMathTerms': self.num_math_terms,'mathTerms': self.math_terms}def __repr__(self):return f"Utterance(speaker='{self.speaker}'," \f"text='{self.text}', uid={self.uid}," \23 unmodified linesdef length(self):return len(self.utterances)def update_utterance_roles(self, uptake_speaker):for utt in self.utterances:if (utt.speaker == uptake_speaker):utt.role = 'teacher'else:utt.role = 'student'def get_talk_distribution_and_length(self, uptake_speaker):if ((uptake_speaker is None)):return Noneteacher_words = 0teacher_utt_count = 0student_words = 0student_utt_count = 0for utt in self.utterances:if (utt.speaker == uptake_speaker):utt.role = 'teacher'teacher_words += utt.get_num_words()teacher_utt_count += 1else:utt.role = 'student'student_words += utt.get_num_words()student_utt_count += 1teacher_percentage = round((teacher_words / (teacher_words + student_words)) * 100)student_percentage = 100 - teacher_percentageavg_teacher_length = teacher_words / teacher_utt_countavg_student_length = student_words / student_utt_countreturn {'teacher': teacher_percentage, 'student': student_percentage}, {'teacher': avg_teacher_length, 'student': avg_student_length}def get_word_cloud_dicts(self):teacher_dict = {}student_dict = {}uptake_teacher_dict = {}stop_words = stopwords.words('english')# stopwords = nltk.corpus.stopwords.word('english')# print("stopwords: ", stopwords)for utt in self.utterances:words = (utt.get_clean_text(remove_punct=True)).split(' ')for word in words:if word in stop_words: continueif utt.role == 'teacher':if word not in teacher_dict:teacher_dict[word] = 0teacher_dict[word] += 1if utt.uptake == 1:if word not in uptake_teacher_dict:uptake_teacher_dict[word] = 0uptake_teacher_dict[word] += 1else:if word not in student_dict:student_dict[word] = 0student_dict[word] += 1dict_list = []uptake_dict_list = []for word in uptake_teacher_dict.keys():uptake_dict_list.append({'text': word, 'value': uptake_teacher_dict[word], 'category': 'teacher'})for word in teacher_dict.keys():dict_list.append({'text': word, 'value': teacher_dict[word], 'category': 'teacher'})for word in student_dict.keys():dict_list.append({'text': word, 'value': student_dict[word], 'category': 'student'})sorted_dict_list = sorted(dict_list, key=lambda x: x['value'], reverse=True)sorted_uptake_dict_list = sorted(uptake_dict_list, key=lambda x: x['value'], reverse=True)return sorted_dict_list[:50], sorted_uptake_dict_list[:50]def get_talk_timeline(self):return [utterance.to_talk_timeline_dict() for utterance in self.utterances]def calculate_aggregate_word_count(self):unit_measures = [utt.unit_measure for utt in self.utterances]if None in unit_measures:aggregate_word_count = 0for utt in self.utterances:aggregate_word_count += utt.get_num_words()utt.unit_measure = utt.get_num_words()utt.aggregate_unit_measure = aggregate_word_countdef to_dict(self):return {'utterances': [utterance.to_dict() for utterance in self.utterances],121 unmodified linesreturn_pooler_output=False)return outputclass FocusingQuestionModel:def __init__(self, device, tokenizer, input_builder, max_length=128, path=FOCUSING_QUESTION_MODEL):print("Loading models...")28 unmodified linesoutput = self.model(input_ids=instance["input_ids"],attention_mask=instance["attention_mask"],token_type_ids=instance["token_type_ids"])return outputdef load_math_terms():math_terms = []21 unmodified linesmatches = [match for match in matches if not any(match.start() in range(existing[0], existing[1]) for existing in matched_positions)]if len(matches) > 0:match_list.append(math_terms_dict[term])# Update matched positionsmatched_positions.update((match.start(), match.end()) for match in matches)num_matches += len(matches)utt.num_math_terms = num_matches29 unmodified linestranscript.add_utterance(Utterance(**utt))print("Running inference on %d examples..." % transcript.length())logging.set_verbosity_info()# Uptakeuptake_model = UptakeModel(self.device, self.tokenizer, self.input_builder)uptake_speaker = params.pop("uptake_speaker", None)uptake_model.run_inference(transcript, min_prev_words=params['uptake_min_num_words'],uptake_speaker=uptake_speaker)# Reasoningreasoning_model = ReasoningModel(self.device, self.tokenizer, self.input_builder)11 unmodified linesrun_math_density(transcript)transcript.update_utterance_roles(uptake_speaker)transcript.calculate_aggregate_word_count()return_dict = {'talkDistribution': None, 'talkLength': None, 'talkMoments': None, 'commonTopWords': None, 'uptakeTopWords': None}talk_dist, talk_len = transcript.get_talk_distribution_and_length(uptake_speaker)return_dict['talkDistribution'] = talk_distreturn_dict['talkLength'] = talk_lentalk_moments = transcript.get_talk_timeline()return_dict['talkMoments'] = talk_momentsword_cloud, uptake_word_cloud = transcript.get_word_cloud_dicts()return_dict['commonTopWords'] = word_cloudreturn_dict['uptakeTopWords'] = uptake_word_cloudreturn return_dict
handler.py+123-9