Spaces:
Runtime error
Runtime error
Merge branch 'feature-wormhole' into 'vlad'
Browse filesFiles changed (14)
- README.md+1-1
- app.py+45-3
- mathtext_fastapi/curriculum_mapper.pyAdded+183
- mathtext_fastapi/data/Rori_Framework_v1.xlsxAdded
- mathtext_fastapi/data/curriculum_framework_for_tests.xlsxAdded
- mathtext_fastapi/data/intent_classification_model.joblibAdded+3
- mathtext_fastapi/data/labeled_data.csvAdded+144
- mathtext_fastapi/data/text2int_results.csv+104-91
- mathtext_fastapi/global_state_manager.pyAdded+23
- mathtext_fastapi/intent_classification.pyAdded+52
- mathtext_fastapi/nlu.py+96-15
- mathtext_fastapi/v2_conversation_manager.pyAdded+257
- requirements.txt+10-7
- scripts/make_request.py+23-15
12345---title: Mathtext Fastapiemoji: 🐨colorFrom: bluecolorTo: red12345---title: Mathtext Wormholeemoji: 🐨colorFrom: bluecolorTo: red
14 unmodified lines1516171819202131 unmodified lines5354555657585926 unmodified lines8687888990913 unmodified lines959697989910010110214 unmodified linesfrom mathtext_fastapi.logging import prepare_message_data_for_loggingfrom mathtext_fastapi.conversation_manager import manage_conversation_responsefrom mathtext_fastapi.nlu import evaluate_message_with_nluapp = FastAPI()31 unmodified linesreturn JSONResponse(content=content)@app.post("/manager")async def programmatic_message_manager(request: Request):"""Calls conversation management function to determine the next state26 unmodified linesreturn JSONResponse(context)@app.post("/nlu")async def evaluate_user_message_with_nlu_api(request: Request):""" Calls nlu evaluation and returns the nlu_response3 unmodified linesOutput- int_data_dict or sent_data_dict: dict - the type of NLU run and result{'type':'integer', 'data': '8'}{'type':'sentiment', 'data': 'negative'}"""data_dict = await request.json()message_data = data_dict.get('message_data', '')14 unmodified lines15161718192021222331 unmodified lines5556575859606126 unmodified lines8889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321333 unmodified lines13713813914014114214314414 unmodified linesfrom mathtext_fastapi.logging import prepare_message_data_for_loggingfrom mathtext_fastapi.conversation_manager import manage_conversation_responsefrom mathtext_fastapi.v2_conversation_manager import manage_conversation_responsefrom mathtext_fastapi.nlu import evaluate_message_with_nlufrom mathtext_fastapi.nlu import run_intent_classificationapp = FastAPI()31 unmodified linesreturn JSONResponse(content=content)@app.post("/v1/manager")async def programmatic_message_manager(request: Request):"""Calls conversation management function to determine the next state26 unmodified linesreturn JSONResponse(context)@app.post("/v2/manager")async def programmatic_message_manager(request: Request):"""Calls conversation management function to determine the next stateInputrequest.body: dict - message data for the most recent user response{"author_id": "+47897891","contact_uuid": "j43hk26-2hjl-43jk-hnk2-k4ljl46j0ds09","author_type": "OWNER","message_body": "a test message","message_direction": "inbound","message_id": "ABJAK64jlk3-agjkl2QHFAFH","message_inserted_at": "2022-07-05T04:00:34.03352Z","message_updated_at": "2023-02-14T03:54:19.342950Z",}Outputcontext: dict - the information for the current state{"user": "47897891","state": "welcome-message-state","bot_message": "Welcome to Rori!","user_message": "","type": "ask"}"""data_dict = await request.json()context = manage_conversation_response(data_dict)return JSONResponse(context)@app.post("/intent-classification")def intent_classification_ep(content: Text = None):ml_response = run_intent_classification(content.content)content = {"message": ml_response}return JSONResponse(content=content)@app.post("/nlu")async def evaluate_user_message_with_nlu_api(request: Request):""" Calls nlu evaluation and returns the nlu_response3 unmodified linesOutput- int_data_dict or sent_data_dict: dict - the type of NLU run and result{'type':'integer', 'data': '8', 'confidence': 0}{'type':'sentiment', 'data': 'negative', 'confidence': 0.99}"""data_dict = await request.json()message_data = data_dict.get('message_data', '')
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183import numpy as npimport pandas as pdimport re
from pathlib import Path
def read_and_preprocess_spreadsheet(file_name): """ Creates a pandas dataframe from the curriculum overview spreadsheet """ DATA_DIR = Path(__file__).parent.parent / "mathtext_fastapi" / "data" / file_name script_df = pd.read_excel(DATA_DIR, engine='openpyxl') # Ensures the grade level columns are integers instead of floats script_df.columns = script_df.columns[:2].tolist() + script_df.columns[2:11].astype(int).astype(str).tolist() + script_df.columns[11:].tolist() script_df.fillna('', inplace=True) return script_df
def extract_skill_code(skill): """ Looks within a curricular skill description for its descriptive code
Input - skill: str - a brief description of a curricular skill
>>> extract_skill_code('A3.3.4 - Solve inequalities') 'A3.3.4' >>> extract_skill_code('A3.3.2 - Graph linear equations, and identify the x- and y-intercepts or the slope of a line') 'A3.3.2' """ pattern = r'[A-Z][0-9]\.\d+\.\d+' result = re.search(pattern, skill) return result.group()
def build_horizontal_transitions(script_df): """ Build a list of transitional relationships within a curricular skill
Inputs - script_df: pandas dataframe - an overview of the curriculum skills by grade level
Output - horizontal_transitions: array of arrays - transition data with label, from state, and to state
>>> script_df = read_and_preprocess_spreadsheet('curriculum_framework_for_tests.xlsx') >>> build_horizontal_transitions(script_df) [['right', 'N1.1.1_G1', 'N1.1.1_G2'], ['right', 'N1.1.1_G2', 'N1.1.1_G3'], ['right', 'N1.1.1_G3', 'N1.1.1_G4'], ['right', 'N1.1.1_G4', 'N1.1.1_G5'], ['right', 'N1.1.1_G5', 'N1.1.1_G6'], ['left', 'N1.1.1_G6', 'N1.1.1_G5'], ['left', 'N1.1.1_G5', 'N1.1.1_G4'], ['left', 'N1.1.1_G4', 'N1.1.1_G3'], ['left', 'N1.1.1_G3', 'N1.1.1_G2'], ['left', 'N1.1.1_G2', 'N1.1.1_G1'], ['right', 'N1.1.2_G1', 'N1.1.2_G2'], ['right', 'N1.1.2_G2', 'N1.1.2_G3'], ['right', 'N1.1.2_G3', 'N1.1.2_G4'], ['right', 'N1.1.2_G4', 'N1.1.2_G5'], ['right', 'N1.1.2_G5', 'N1.1.2_G6'], ['left', 'N1.1.2_G6', 'N1.1.2_G5'], ['left', 'N1.1.2_G5', 'N1.1.2_G4'], ['left', 'N1.1.2_G4', 'N1.1.2_G3'], ['left', 'N1.1.2_G3', 'N1.1.2_G2'], ['left', 'N1.1.2_G2', 'N1.1.2_G1']] """ horizontal_transitions = [] for index, row in script_df.iterrows(): skill_code = extract_skill_code(row['Knowledge or Skill'])
rightward_matches = [] for i in range(9): # Grade column current_grade = i+1 if row[current_grade].lower().strip() == 'x': rightward_matches.append(i) for match in rightward_matches: if rightward_matches[-1] != match: horizontal_transitions.append([ "right", f"{skill_code}_G{match}", f"{skill_code}_G{match+1}" ])
leftward_matches = [] for i in reversed(range(9)): current_grade = i if row[current_grade].lower().strip() == 'x': leftward_matches.append(i)
for match in leftward_matches: if leftward_matches[0] != match: horizontal_transitions.append([ "left", f"{skill_code}_G{match}", f"{skill_code}_G{match-1}" ])
return horizontal_transitions
def gather_all_vertical_matches(script_df): """ Build a list of transitional relationships within a grade level across skills
Inputs - script_df: pandas dataframe - an overview of the curriculum skills by grade level
Output - all_matches: array of arrays - represents skills at each grade level
>>> script_df = read_and_preprocess_spreadsheet('curriculum_framework_for_tests.xlsx') >>> gather_all_vertical_matches(script_df) [['N1.1.1', '1'], ['N1.1.2', '1'], ['N1.1.1', '2'], ['N1.1.2', '2'], ['N1.1.1', '3'], ['N1.1.2', '3'], ['N1.1.1', '4'], ['N1.1.2', '4'], ['N1.1.1', '5'], ['N1.1.2', '5'], ['N1.1.1', '6'], ['N1.1.2', '6']] """ all_matches = [] columns = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
for column in columns: for index, value in script_df[column].iteritems(): row_num = index + 1 if value == 'x': # Extract skill code skill_code = extract_skill_code( script_df['Knowledge or Skill'][row_num-1] )
all_matches.append([skill_code, column]) return all_matches
def build_vertical_transitions(script_df): """ Build a list of transitional relationships within a grade level across skills
Inputs - script_df: pandas dataframe - an overview of the curriculum skills by grade level
Output - vertical_transitions: array of arrays - transition data with label, from state, and to state
>>> script_df = read_and_preprocess_spreadsheet('curriculum_framework_for_tests.xlsx') >>> build_vertical_transitions(script_df) [['down', 'N1.1.1_G1', 'N1.1.2_G1'], ['down', 'N1.1.2_G1', 'N1.1.1_G1'], ['down', 'N1.1.1_G2', 'N1.1.2_G2'], ['down', 'N1.1.2_G2', 'N1.1.1_G2'], ['down', 'N1.1.1_G3', 'N1.1.2_G3'], ['down', 'N1.1.2_G3', 'N1.1.1_G3'], ['down', 'N1.1.1_G4', 'N1.1.2_G4'], ['down', 'N1.1.2_G4', 'N1.1.1_G4'], ['down', 'N1.1.1_G5', 'N1.1.2_G5'], ['down', 'N1.1.2_G5', 'N1.1.1_G5'], ['down', 'N1.1.1_G6', 'N1.1.2_G6'], ['up', 'N1.1.2_G6', 'N1.1.1_G6'], ['up', 'N1.1.1_G6', 'N1.1.2_G6'], ['up', 'N1.1.2_G5', 'N1.1.1_G5'], ['up', 'N1.1.1_G5', 'N1.1.2_G5'], ['up', 'N1.1.2_G4', 'N1.1.1_G4'], ['up', 'N1.1.1_G4', 'N1.1.2_G4'], ['up', 'N1.1.2_G3', 'N1.1.1_G3'], ['up', 'N1.1.1_G3', 'N1.1.2_G3'], ['up', 'N1.1.2_G2', 'N1.1.1_G2'], ['up', 'N1.1.1_G2', 'N1.1.2_G2'], ['up', 'N1.1.2_G1', 'N1.1.1_G1']] """ vertical_transitions = []
all_matches = gather_all_vertical_matches(script_df)
# Downward for index, match in enumerate(all_matches): skill = match[0] row_num = match[1] if all_matches[-1] != match: vertical_transitions.append([ "down", f"{skill}_G{row_num}", f"{all_matches[index+1][0]}_G{row_num}" ])
# Upward for index, match in reversed(list(enumerate(all_matches))): skill = match[0] row_num = match[1] if all_matches[0] != match: vertical_transitions.append([ "up", f"{skill}_G{row_num}", f"{all_matches[index-1][0]}_G{row_num}" ]) return vertical_transitions
def build_all_states(all_transitions): """ Creates an array with all state labels for the curriculum
Input - all_transitions: list of lists - all possible up, down, left, or right transitions in curriculum
Output - all_states: list - a collection of state labels (skill code and grade number) >>> all_transitions = [['right', 'N1.1.1_G1', 'N1.1.1_G2'], ['right', 'N1.1.1_G2', 'N1.1.1_G3'], ['right', 'N1.1.1_G3', 'N1.1.1_G4'], ['right', 'N1.1.1_G4', 'N1.1.1_G5'], ['right', 'N1.1.1_G5', 'N1.1.1_G6'], ['left', 'N1.1.1_G6', 'N1.1.1_G5'], ['left', 'N1.1.1_G5', 'N1.1.1_G4'], ['left', 'N1.1.1_G4', 'N1.1.1_G3'], ['left', 'N1.1.1_G3', 'N1.1.1_G2'], ['left', 'N1.1.1_G2', 'N1.1.1_G1'], ['right', 'N1.1.2_G1', 'N1.1.2_G2'], ['right', 'N1.1.2_G2', 'N1.1.2_G3'], ['right', 'N1.1.2_G3', 'N1.1.2_G4'], ['right', 'N1.1.2_G4', 'N1.1.2_G5'], ['right', 'N1.1.2_G5', 'N1.1.2_G6'], ['left', 'N1.1.2_G6', 'N1.1.2_G5'], ['left', 'N1.1.2_G5', 'N1.1.2_G4'], ['left', 'N1.1.2_G4', 'N1.1.2_G3'], ['left', 'N1.1.2_G3', 'N1.1.2_G2'], ['left', 'N1.1.2_G2', 'N1.1.2_G1'], ['down', 'N1.1.1_G1', 'N1.1.2_G1'], ['down', 'N1.1.2_G1', 'N1.1.1_G1'], ['down', 'N1.1.1_G2', 'N1.1.2_G2'], ['down', 'N1.1.2_G2', 'N1.1.1_G2'], ['down', 'N1.1.1_G3', 'N1.1.2_G3'], ['down', 'N1.1.2_G3', 'N1.1.1_G3'], ['down', 'N1.1.1_G4', 'N1.1.2_G4'], ['down', 'N1.1.2_G4', 'N1.1.1_G4'], ['down', 'N1.1.1_G5', 'N1.1.2_G5'], ['down', 'N1.1.2_G5', 'N1.1.1_G5'], ['down', 'N1.1.1_G6', 'N1.1.2_G6'], ['up', 'N1.1.2_G6', 'N1.1.1_G6'], ['up', 'N1.1.1_G6', 'N1.1.2_G6'], ['up', 'N1.1.2_G5', 'N1.1.1_G5'], ['up', 'N1.1.1_G5', 'N1.1.2_G5'], ['up', 'N1.1.2_G4', 'N1.1.1_G4'], ['up', 'N1.1.1_G4', 'N1.1.2_G4'], ['up', 'N1.1.2_G3', 'N1.1.1_G3'], ['up', 'N1.1.1_G3', 'N1.1.2_G3'], ['up', 'N1.1.2_G2', 'N1.1.1_G2'], ['up', 'N1.1.1_G2', 'N1.1.2_G2'], ['up', 'N1.1.2_G1', 'N1.1.1_G1']] >>> build_all_states(all_transitions) ['N1.1.1_G1', 'N1.1.1_G2', 'N1.1.1_G3', 'N1.1.1_G4', 'N1.1.1_G5', 'N1.1.1_G6', 'N1.1.2_G1', 'N1.1.2_G2', 'N1.1.2_G3', 'N1.1.2_G4', 'N1.1.2_G5', 'N1.1.2_G6'] """ all_states = [] for transition in all_transitions: for index, state in enumerate(transition): if index == 0: continue if state not in all_states: all_states.append(state) return all_states
def build_curriculum_logic(): script_df = read_and_preprocess_spreadsheet('Rori_Framework_v1.xlsx') horizontal_transitions = build_horizontal_transitions(script_df) vertical_transitions = build_vertical_transitions(script_df) all_transitions = horizontal_transitions + vertical_transitions all_states = build_all_states(all_transitions) return all_states, all_transitions123version https://git-lfs.github.com/spec/v1oid sha256:ea4954368c3b95673167ce347f2962b5508c4af295b6af58b6c11b3c1075b42esize 127903123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144Utterance,Labelskip this,skipthis is stupid,skipthis is stupid,harderthis is stupid,feedbackI'm done,exitquit,exitI don't know,hinthelp,hintcan I do something else?,main menuwhat's going on,rapport what's going on,main menutell me a joke,rapporttell me a joke,main menuSorry I don't understand,do not knowTen thousand,number1.234,number"10,000",number"123, 456",numbers"11, 12, 13",numbers"100, 200, 300",numbers"100, 200",numbersStop for a minute,waitBye bye,exitGood night,exitAm done,exitYes,yesHelp,helpIdiot,harderStop,exitI don't get it,hintMath,main menuMath,math topicTomorrow let do math,waitLater,waitPls i will continue pls,skipRori tell me now,helpharder,skipStop for now i wont to go to School,exitNext,nextOkay,okayGreat,affirmationGive me for example,exampleNo I want to learn algebraic expressions,algebraHi rori,greeting*help*,help*Next*,nextOkay nice,okayI don't know it,hintNex,nextI need a help,hintPlease can I ask your any math questions?,faqThe answer is 1,answerThe answer is 1,numberBut 0.8 is also same as . 8 so I was actually right,I'm rightWhat is the number system?,faqOk thanks,thanksI'm going to school now,exitLet's move to another topic,main menu"Ummanni sabaKebena bara kana galmi keenya inni guddaan bilisummaa qofa #Gabrummaan_ammaan booda_gaha namni hundi bakka jiru irraa kutatee ka,ee jira obboleewwan goototni keenya jiran haqa Kebenaaf jechaa jiru Guraandhala 29 booda walabummaa keenya labsina Dhugaa qabna Ni injifanna *** . Naannoo giddu galeessa Itoophiyaatti #Kebenaan aanaa addaati Kun murtoo ummata Kebenaa hundaati",spamYes it,yesU type fast,too fastI mean your typing is fast,too fastWhy do u type so fast,too fastUr typing is fast,too fastCan we go to a real work,harderI know all this,harderAnswer this,preambleAm tired,exitThis is not what I asked for,main menuBye,exit😱😱😂😂😂😡😰😰😰😒,spamGbxbxbcbcbbcbchcbchc,spamI want to solve math,math topicPleas let start with the fraction,fractions topicOkey,okayi need substraction,subtraction topicCan you please stop with me,exitAnother one,nextHarder or easy,main menuHard or easier,main menuJump topic,menuGot it,okayI didn't understand,don't knowDon't understand,don't knowExcuse me pls,hintLet stop for today,exitHelp and stop asking me stupid questions,Ykay,okayNot interested in solving this,menuStpo,exitHiiiiiii,greetingHi rori,greetingI've done this things before,harderWhich number my phone number,Unit,main menuNo ide,don't knowNo ide,hintNo idea,don't know🙈🤩😇🙏,spamThank u,thanksDo you know programming,faqDelete my number,unsubscribeSee u,exitCan I go for break ??,waitI wanna fuck,profanityEnough of this nw,exitCan we move to equations,equationsDo you know you are an idiot,insult3 digit number,number3 digit number,answerThree digit number,confident answerThree digit number,numberGood evening Rori,greeting89 Next,answer89 Next,number3 digit number,answerThree digit number,answerThis is too simple,harderAm not a kid,harderHey Miss Roribcan you ask me some question from Secondary 2,greetingHey Miss Roribcan you ask me some question from Secondary 2,faqHey Miss Roribcan you ask me some question from Secondary 2,main menudon't know,hintdon't know,easier𝑴𝒂𝒕𝒉,mathRori can you help me to gat value,I called but u are not picking up,0.3 answer,answerSorry rori was101,answerY is it 6,answerY is it 6,number0.3 answer,numberWhy 0.5,more explanationWhy 0.5,number6\nNext,NextHow is the answer is 11,more explanationHow comes we have 11,more explanationYes 6,answerYes 6,number6\nNext,numberHow is the answer is 11,numberHow comes we have 11,number1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192input,output,text2int,scorenotanumber,32202,32202,Truethis is not a number,32202,32202,Truefourteen,14,14,Trueforteen,14,14,Trueone thousand four hundred ninety two,1492,1492,Trueone thousand ninety two,1092,1092,TrueFourteen Hundred Ninety-Two,1492,1492,TrueFourteen Hundred,1400,1400,TrueNinety nine,99,99,Truefifteen thousand five hundred-sixty,15560,15560,Truethree hundred fifty,350,350,Trueone nine eight five,1985,1985,Truenineteen eighty-five,1985,1605,Falseoh one,1,1,Truesix oh 1,601,601,Truesex,6,6,Truesix,6,6,Trueeight oh,80,8,Falseeighty,80,80,Trueate,8,1,Falsedouble eight,88,32202,Falseeight three seven five three O nine,8375309,8375329,Falseeight three seven five three oh nine,8375309,8375309,Trueeight three seven five three zero nine,8375309,8375309,Trueeight three seven five three oh ni-ee-ine,8375309,837530611,Falsetwo eight,28,16,Falseseven oh eleven,7011,77,Falseseven elevens,77,77,Trueseven eleven,711,77,Falseninety nine oh five,9905,149,Falseseven 0 seven 0 seven 0 seven,7070707,7070707,True123 hundred,123000,223,False5 o 5,505,525,False15 o 5,1505,22,False15-o 5,1505,22,False15 o-5,1505,22,False911-thousand,911000,911000,Truetwenty-two twenty-two,2222,44,Falsetwenty-two twenty-twos,484,44,Falsefour eighty four,484,404,Falsefour eighties,320,72,Falsefour eighties and nine nineties,1130,243,Falseninety nine hundred and seventy seven,9977,276,Falseseven thousands,7000,7000,True2 hundreds,200,200,True99 thousands and one,99001,99001,True"forty-five thousand, seven hundred and nine",45709,1161,Falseeighty eight hundred eighty,8880,268,Falsea hundred hundred,10000,32202,Falsea hundred thousand,100000,32202,Falsea hundred million,100000000,32202,Falsenineteen ninety nine,1999,1809,Falseforteen twenty seven,1427,307,Falseseventeen-thousand and seventy two,17072,17072,Truetwo hundred and nine,209,209,Truetwo thousand ten,2010,2010,Truetwo thousand and ten,2010,2010,Truetwelve million,12000000,12000000,True8 billion,8000000000,8000000000,Truetwenty ten,2010,2010,Truethirty-two hundred,3200,3200,Truenine,9,9,Trueforty two,42,42,True1 2 three,123,123,Truefourtean,14,14,Trueone tousand four hundred ninty two,1492,1492,TrueFurteen Hundrd Ninety-Too,1492,1492,Trueforrteen,14,14,Truesevnteen-thosand and seventy two,17072,17072,Trueninety nine hundred ad seventy seven,9977,32202,Falseseven thusands,7000,7000,True2 hunreds,200,200,True99 tousands and one,99001,99001,Trueeighty ate hundred eighty,8880,261,Falsefourteen Hundred,1400,1400,True8 Bilion,8000000000,8000000,Falseone million three thousand one,1003001,1003001,Truefour million nine thousand seven,4009007,4009007,Truetwo million five hundred thousand,2500000,2001500,Falsetwo tousand ten,2010,2010,Truetwo thousand teen,2010,2007,Falsetvelve milion,12000000,12000000,Truetventy ten,2010,2010,Truetirty-twoo hunred,3200,3200,Truesevn thoosands,7000,7000,Truefive,5,5,Trueten,10,10,Trueone two three and ten,12310,51,FalseONE MILLion three hunded and fiv,1000305,1000305,True"50,500 and six",50506,50506,Trueone_million_and_five,1000005,1000005,True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105input,output,text2int,scorenotanumber,32202.0,32202.0,Truethis is not a number,32202.0,32202.0,Truefourteen,14.0,14.0,Trueforteen,14.0,14.0,Trueone thousand four hundred ninety two,1492.0,1492.0,Trueone thousand ninety two,1092.0,1092.0,TrueFourteen Hundred Ninety-Two,1492.0,1492.0,TrueFourteen Hundred,1400.0,1400.0,TrueNinety nine,99.0,99.0,Truefifteen thousand five hundred-sixty,15560.0,15560.0,Truethree hundred fifty,350.0,350.0,Trueone nine eight five,1985.0,1985.0,Truenineteen eighty-five,1985.0,1605.0,Falseoh one,1.0,1.0,Truesix oh 1,601.0,601.0,Truesex,6.0,6.0,Truesix,6.0,6.0,Trueeight oh,80.0,8.0,Falseeighty,80.0,80.0,Trueate,8.0,1.0,Falsedouble eight,88.0,8.0,Falseeight three seven five three O nine,8375309.0,8375319.0,Falseeight three seven five three oh nine,8375309.0,8375309.0,Trueeight three seven five three zero nine,8375309.0,8375309.0,Trueeight three seven five three oh ni-ee-ine,8375309.0,837530111.0,Falsetwo eight,28.0,16.0,Falseseven oh eleven,7011.0,77.0,Falseseven elevens,77.0,77.0,Trueseven eleven,711.0,77.0,Falseninety nine oh five,9905.0,149.0,Falseseven 0 seven 0 seven 0 seven,7070707.0,7070707.0,True123 hundred,123000.0,223.0,False5 o 5,505.0,515.0,False15 o 5,1505.0,21.0,False15-o 5,1505.0,21.0,False15 o-5,1505.0,21.0,False911-thousand,911000.0,911000.0,Truetwenty-two twenty-two,2222.0,44.0,Falsetwenty-two twenty-twos,484.0,44.0,Falsefour eighty four,484.0,404.0,Falsefour eighties,320.0,72.0,Falsefour eighties and nine nineties,1130.0,243.0,Falseninety nine hundred and seventy seven,9977.0,276.0,Falseseven thousands,7000.0,7000.0,True2 hundreds,200.0,200.0,True99 thousands and one,99001.0,99001.0,True"forty-five thousand, seven hundred and nine",45709.0,1161.0,Falseeighty eight hundred eighty,8880.0,268.0,Falsea hundred hundred,10000.0,100.0,Falsea hundred thousand,100000.0,100.0,Falsea hundred million,100000000.0,100.0,Falsenineteen ninety nine,1999.0,1809.0,Falseforteen twenty seven,1427.0,307.0,Falseseventeen-thousand and seventy two,17072.0,17072.0,Truetwo hundred and nine,209.0,209.0,Truetwo thousand ten,2010.0,2010.0,Truetwo thousand and ten,2010.0,2010.0,Truetwelve million,12000000.0,12000000.0,True8 billion,8000000000.0,8000000000.0,Truetwenty ten,2010.0,2010.0,Truethirty-two hundred,3200.0,3200.0,Truenine,9.0,9.0,Trueforty two,42.0,42.0,True1 2 three,123.0,123.0,Truefourtean,14.0,14.0,Trueone tousand four hundred ninty two,1492.0,1492.0,TrueFurteen Hundrd Ninety-Too,1492.0,1492.0,Trueforrteen,14.0,14.0,Truesevnteen-thosand and seventy two,17072.0,17072.0,Trueninety nine hundred ad seventy seven,9977.0,90.0,Falseseven thusands,7000.0,7000.0,True2 hunreds,200.0,200.0,True99 tousands and one,99001.0,99001.0,Trueeighty ate hundred eighty,8880.0,261.0,Falsefourteen Hundred,1400.0,1400.0,True8 Bilion,8000000000.0,8000000.0,Falseone million three thousand one,1003001.0,1003001.0,Truefour million nine thousand seven,4009007.0,4009007.0,Truetwo million five hundred thousand,2500000.0,2001500.0,Falsetwo tousand ten,2010.0,2010.0,Truetwo thousand teen,2010.0,2007.0,Falsetvelve milion,12000000.0,12000000.0,Truetventy ten,2010.0,2010.0,Truetirty-twoo hunred,3200.0,3200.0,Truesevn thoosands,7000.0,7000.0,Truefive,5.0,5.0,Trueten,10.0,10.0,Trueone two three and ten,12310.0,51.0,FalseONE MILLion three hunded and fiv,1000305.0,1000305.0,True"50,500 and six",50506.0,50506.0,Trueone_million_and_five,1000005.0,1000005.0,True2.0,2.0,2.0,True4.5,4.5,4.5,True12345.001,12345.001,12345.001,True7..0,7.0,7.0,True0.06,0.06,0.06,True"0,25",0.25,25.0,Falseo.45,0.45,32202.0,False0.1.2,0.12,32202.0,False0.00009,9e-05,9e-05,True0.01.,0.01,0.01,TrueI don't know 8,8.0,8.0,True"You're wrong it's not 20, it's 45",45.0,20.0,FalseI don't understand why it's 19,19.0,19.0,True
1234567891011121314151617181920212223from transitions import Machinefrom mathtext_fastapi.curriculum_mapper import build_curriculum_logic
all_states, all_transitions = build_curriculum_logic()
class GlobalStateManager(object): states = all_states
transitions = all_transitions
def __init__( self, initial_state='N1.1.1_G1', ): self.machine = Machine( model=self, states=GlobalStateManager.states, transitions=GlobalStateManager.transitions, initial=initial_state )
curriculum = GlobalStateManager()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152import numpy as npimport pandas as pd
from pathlib import Pathfrom sentence_transformers import SentenceTransformerfrom sklearn.linear_model import LogisticRegressionfrom joblib import dump, load
def pickle_model(model): DATA_DIR = Path(__file__).parent.parent / "mathtext_fastapi" / "data" / "intent_classification_model.joblib" dump(model, DATA_DIR)
def create_intent_classification_model(): encoder = SentenceTransformer('all-MiniLM-L6-v2') # path = list(Path.cwd().glob('*.csv')) DATA_DIR = Path(__file__).parent.parent / "mathtext_fastapi" / "data" / "labeled_data.csv"
print("DATA_DIR") print(f"{DATA_DIR}")
with open(f"{DATA_DIR}",'r', newline='', encoding='utf-8') as f: df = pd.read_csv(f) df = df[df.columns[:2]] df = df.dropna() X_explore = np.array([list(encoder.encode(x)) for x in df['Utterance']]) X = np.array([list(encoder.encode(x)) for x in df['Utterance']]) y = df['Label'] model = LogisticRegression(class_weight='balanced') model.fit(X, y, sample_weight=None)
print("MODEL") print(model)
pickle_model(model)
def retrieve_intent_classification_model(): DATA_DIR = Path(__file__).parent.parent / "mathtext_fastapi" / "data" / "intent_classification_model.joblib" model = load(DATA_DIR) return model
def predict_message_intent(message): encoder = SentenceTransformer('all-MiniLM-L6-v2') model = retrieve_intent_classification_model() tokenized_utterance = np.array([list(encoder.encode(message))]) predicted_label = model.predict(tokenized_utterance) predicted_probabilities = model.predict_proba(tokenized_utterance) confidence_score = predicted_probabilities.max()
return {"type": "intent", "data": predicted_label[0], "confidence": confidence_score}1234561 unmodified line89101112131415161718192021222324252627282930313233347 unmodified lines4243444546473 unmodified lines51525354555657585960616210 unmodified lines7374757677787980818283848586878889909192from mathtext_fastapi.logging import prepare_message_data_for_loggingfrom mathtext.sentiment import sentimentfrom mathtext.text2int import text2intimport re1 unmodified line""" Turns nlu results into an object to send back to Turn.ioInputs- type: str - the type of nlu run (integer or sentiment-analysis)- data: str - the student message- confidence: - the nlu confidence score (sentiment) or '' (integer)"""return {'type': type, 'data': data, 'confidence': confidence}def test_for_float_or_int(message_data, message_text):nlu_response = {}if type(message_text) == int or type(message_text) == float:nlu_response = build_nlu_response_object('integer', message_text, '')prepare_message_data_for_logging(message_data, nlu_response)return nlu_responsedef test_for_number_sequence(message_text_arr, message_data, message_text):nlu_response = {}if all(ele.isdigit() for ele in message_text_arr):nlu_response = build_nlu_response_object('integer',','.join(message_text_arr),'')prepare_message_data_for_logging(message_data, nlu_response)return nlu_response7 unmodified linesOutput- student_response_arr: list - a set of integers (32202 for error code)"""student_response_arr = []for student_response in message_text_arr:3 unmodified linesdef run_sentiment_analysis(message_text):# TODO: Add intent labelling here# TODO: Add logic to determine whether intent labeling or sentiment analysis is more appropriate (probably default to intent labeling)return sentiment(message_text)def evaluate_message_with_nlu(message_data):# Keeps system working with two different inputs - full and filtered @event objecttry:message_text = message_data['message_body']10 unmodified lines}message_text = message_data['message_body']number_api_resp = text2int(message_text.lower())if number_api_resp == 32202:sentiment_api_resp = sentiment(message_text)nlu_response = build_nlu_response_object('sentiment',sentiment_api_resp[0]['label'],sentiment_api_resp[0]['score'])else:nlu_response = build_nlu_response_object('integer',number_api_resp,'')prepare_message_data_for_logging(message_data, nlu_response)123456781 unmodified line10111213141516171819202122232425262728293031323334353637383940414243444546474849507 unmodified lines5859606162636465663 unmodified lines70717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113210 unmodified lines143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173from fuzzywuzzy import fuzzfrom mathtext_fastapi.logging import prepare_message_data_for_loggingfrom mathtext.sentiment import sentimentfrom mathtext.text2int import text2intfrom mathtext_fastapi.intent_classification import create_intent_classification_model, retrieve_intent_classification_model, predict_message_intentimport re1 unmodified line""" Turns nlu results into an object to send back to Turn.ioInputs- type: str - the type of nlu run (integer or sentiment-analysis)- data: str/int - the student message- confidence: - the nlu confidence score (sentiment) or '' (integer)>>> build_nlu_response_object('integer', 8, 0){'type': 'integer', 'data': 8, 'confidence': 0}>>> build_nlu_response_object('sentiment', 'POSITIVE', 0.99){'type': 'sentiment', 'data': 'POSITIVE', 'confidence': 0.99}"""return {'type': type, 'data': data, 'confidence': confidence}# def test_for_float_or_int(message_data, message_text):# nlu_response = {}# if type(message_text) == int or type(message_text) == float:# nlu_response = build_nlu_response_object('integer', message_text, '')# prepare_message_data_for_logging(message_data, nlu_response)# return nlu_responsedef test_for_number_sequence(message_text_arr, message_data, message_text):""" Determines if the student's message is a sequence of numbers>>> test_for_number_sequence(['1','2','3'], {"author_id": "57787919091", "author_type": "OWNER", "contact_uuid": "df78gsdf78df", "message_body": "I am tired", "message_direction": "inbound", "message_id": "dfgha789789ag9ga", "message_inserted_at": "2023-01-10T02:37:28.487319Z", "message_updated_at": "2023-01-10T02:37:28.487319Z"}, '1, 2, 3'){'type': 'integer', 'data': '1,2,3', 'confidence': 0}>>> test_for_number_sequence(['a','b','c'], {"author_id": "57787919091", "author_type": "OWNER", "contact_uuid": "df78gsdf78df", "message_body": "I am tired", "message_direction": "inbound", "message_id": "dfgha789789ag9ga", "message_inserted_at": "2023-01-10T02:37:28.487319Z", "message_updated_at": "2023-01-10T02:37:28.487319Z"}, 'a, b, c'){}"""nlu_response = {}if all(ele.isdigit() for ele in message_text_arr):nlu_response = build_nlu_response_object('integer',','.join(message_text_arr),0)prepare_message_data_for_logging(message_data, nlu_response)return nlu_response7 unmodified linesOutput- student_response_arr: list - a set of integers (32202 for error code)>>> run_text2int_on_each_list_item(['1','2','3'])[1, 2, 3]"""student_response_arr = []for student_response in message_text_arr:3 unmodified linesdef run_sentiment_analysis(message_text):""" Evaluates the sentiment of a student message>>> run_sentiment_analysis("I am tired")[{'label': 'NEGATIVE', 'score': 0.9997807145118713}]>>> run_sentiment_analysis("I am full of joy")[{'label': 'POSITIVE', 'score': 0.999882698059082}]"""# TODO: Add intent labelling here# TODO: Add logic to determine whether intent labeling or sentiment analysis is more appropriate (probably default to intent labeling)return sentiment(message_text)def run_intent_classification(message_text):""" Process a student's message using basic fuzzy text comparison>>> run_intent_classification("exit"){'type': 'intent', 'data': 'exit', 'confidence': 1.0}>>> run_intent_classification("exi"){'type': 'intent', 'data': 'exit', 'confidence': 0.86}>>> run_intent_classification("eas"){'type': 'intent', 'data': '', 'confidence': 0}>>> run_intent_classification("hard"){'type': 'intent', 'data': '', 'confidence': 0}>>> run_intent_classification("hardier"){'type': 'intent', 'data': 'harder', 'confidence': 0.92}"""label = ''ratio = 0nlu_response = {'type': 'intent', 'data': label, 'confidence': ratio}commands = ['easier','exit','harder','hint','next','stop',]for command in commands:ratio = fuzz.ratio(command, message_text.lower())if ratio > 80:nlu_response['data'] = commandnlu_response['confidence'] = ratio / 100return nlu_responsedef evaluate_message_with_nlu(message_data):""" Process a student's message using NLU functions and send the result>>> evaluate_message_with_nlu({"author_id": "57787919091", "author_type": "OWNER", "contact_uuid": "df78gsdf78df", "message_body": "8", "message_direction": "inbound", "message_id": "dfgha789789ag9ga", "message_inserted_at": "2023-01-10T02:37:28.487319Z", "message_updated_at": "2023-01-10T02:37:28.487319Z"}){'type': 'integer', 'data': 8, 'confidence': 0}>>> evaluate_message_with_nlu({"author_id": "57787919091", "author_type": "OWNER", "contact_uuid": "df78gsdf78df", "message_body": "I am tired", "message_direction": "inbound", "message_id": "dfgha789789ag9ga", "message_inserted_at": "2023-01-10T02:37:28.487319Z", "message_updated_at": "2023-01-10T02:37:28.487319Z"}){'type': 'sentiment', 'data': 'NEGATIVE', 'confidence': 0.9997807145118713}"""# Keeps system working with two different inputs - full and filtered @event objecttry:message_text = message_data['message_body']10 unmodified lines}message_text = message_data['message_body']# Run intent classification only for keywordsintent_api_response = run_intent_classification(message_text)if intent_api_response['data']:return intent_api_responsenumber_api_resp = text2int(message_text.lower())if number_api_resp == 32202:# Run intent classification with logistic regression modelpredicted_label = predict_message_intent(message_text)if predicted_label['confidence'] > 0.01:nlu_response = predicted_labelelse:# Run sentiment analysissentiment_api_resp = sentiment(message_text)nlu_response = build_nlu_response_object('sentiment',sentiment_api_resp[0]['label'],sentiment_api_resp[0]['score'])else:nlu_response = build_nlu_response_object('integer',number_api_resp,0)prepare_message_data_for_logging(message_data, nlu_response)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257import base64import copyimport dillimport osimport jsonimport jsonpickleimport pickleimport randomimport requestsimport mathtext_fastapi.global_state_manager as gsm
from dotenv import load_dotenvfrom mathtext_fastapi.nlu import evaluate_message_with_nlufrom mathtext_fastapi.math_quiz_fsm import MathQuizFSMfrom mathtext_fastapi.math_subtraction_fsm import MathSubtractionFSMfrom supabase import create_clientfrom transitions import Machine
from scripts.quiz.generators import start_interactive_mathfrom scripts.quiz.hints import generate_hint
load_dotenv()
SUPA = create_client( os.environ.get('SUPABASE_URL'), os.environ.get('SUPABASE_KEY'))
def pickle_and_encode_state_machine(state_machine): dump = pickle.dumps(state_machine) dump_encoded = base64.b64encode(dump).decode('utf-8') return dump_encoded
def manage_math_quiz_fsm(user_message, contact_uuid, type): fsm_check = SUPA.table('state_machines').select("*").eq( "contact_uuid", contact_uuid ).execute()
# This doesn't allow for when one FSM is present and the other is empty """ 1 data=[] count=None 2 data=[{'id': 29, 'contact_uuid': 'j43hk26-2hjl-43jk-hnk2-k4ljl46j0ds09', 'addition3': None, 'subtraction': None, 'addition':
- but problem is there is no subtraction , but it's assuming there's a subtration
Cases - make a completely new record - update an existing record with an existing FSM - update an existing record without an existing FSM """ print("MATH QUIZ FSM ACTIVITY") print("user_message") print(user_message) # Make a completely new entry if fsm_check.data == []: if type == 'addition': math_quiz_state_machine = MathQuizFSM() else: math_quiz_state_machine = MathSubtractionFSM() messages = [math_quiz_state_machine.response_text] dump_encoded = pickle_and_encode_state_machine(math_quiz_state_machine)
SUPA.table('state_machines').insert({ 'contact_uuid': contact_uuid, f'{type}': dump_encoded }).execute() # Update an existing record with a new state machine elif not fsm_check.data[0][type]: if type == 'addition': math_quiz_state_machine = MathQuizFSM() else: math_quiz_state_machine = MathSubtractionFSM() messages = [math_quiz_state_machine.response_text] dump_encoded = pickle_and_encode_state_machine(math_quiz_state_machine)
SUPA.table('state_machines').update({ f'{type}': dump_encoded }).eq( "contact_uuid", contact_uuid ).execute() # Update an existing record with an existing state machine elif fsm_check.data[0][type]: undump_encoded = base64.b64decode( fsm_check.data[0][type].encode('utf-8') ) math_quiz_state_machine = pickle.loads(undump_encoded)
math_quiz_state_machine.student_answer = user_message math_quiz_state_machine.correct_answer = str(math_quiz_state_machine.correct_answer) messages = math_quiz_state_machine.validate_answer() dump_encoded = pickle_and_encode_state_machine(math_quiz_state_machine) SUPA.table('state_machines').update({ f'{type}': dump_encoded }).eq( "contact_uuid", contact_uuid ).execute() return messages
def retrieve_microlesson_content(context_data, user_message, microlesson, contact_uuid): if context_data['local_state'] == 'addition-question-sequence' or \ user_message == 'add' or \ microlesson == 'addition': messages = manage_math_quiz_fsm(user_message, contact_uuid, 'addition')
if user_message == 'exit': state_label = 'exit' else: state_label = 'addition-question-sequence'
input_prompt = messages.pop() message_package = { 'messages': messages, 'input_prompt': input_prompt, 'state': state_label } elif context_data['local_state'] == 'subtraction-question-sequence' or \ user_message == 'subtract' or \ microlesson == 'subtraction': messages = manage_math_quiz_fsm(user_message, contact_uuid, 'subtraction')
if user_message == 'exit': state_label = 'exit' else: state_label = 'subtraction-question-sequence'
input_prompt = messages.pop()
message_package = { 'messages': messages, 'input_prompt': input_prompt, 'state': state_label } print("MICROLESSON CONTENT RESPONSE") print(message_package) return message_package
curriculum_lookup_table = { 'N1.1.1_G1': 'addition', 'N1.1.1_G2': 'subtraction'}
def lookup_local_state(next_state): microlesson = curriculum_lookup_table[next_state] return microlesson
def create_text_message(message_text, whatsapp_id): """ Fills a template with input values to send a text message to Whatsapp
Inputs - message_text: str - the content that the message should display - whatsapp_id: str - the message recipient's phone number
Outputs - message_data: dict - a preformatted template filled with inputs """ message_data = { "preview_url": False, "recipient_type": "individual", "to": whatsapp_id, "type": "text", "text": { "body": message_text } } return message_data
def manage_conversation_response(data_json): """ Calls functions necessary to determine message and context data """ print("V2 ENDPOINT")
user_message = '' # whatsapp_id = data_json['author_id'] message_data = data_json['message_data'] context_data = data_json['context_data'] whatsapp_id = message_data['author_id'] print("MESSAGE DATA") print(message_data) print("CONTEXT DATA") print(context_data) print("=================")
# nlu_response = evaluate_message_with_nlu(message_data)
# context_data = { # 'contact_uuid': 'abcdefg', # 'current_state': 'N1.1.1_G2', # 'user_message': '1', # 'local_state': '' # } print("STEP 1") print(data_json) if not context_data['current_state']: context_data['current_state'] = 'N1.1.1_G1'
curriculum_copy = copy.deepcopy(gsm.curriculum)
print("STEP 2") if context_data['user_message'] == 'easier': curriculum_copy.left() next_state = curriculum_copy.state elif context_data['user_message'] == 'harder': curriculum_copy.right() next_state = curriculum_copy.state else: next_state = context_data['current_state']
print("STEP 3") microlesson = lookup_local_state(next_state)
print("microlesson") print(microlesson)
microlesson_content = retrieve_microlesson_content(context_data, context_data['user_message'], microlesson, context_data['contact_uuid'])
headers = { 'Authorization': f"Bearer {os.environ.get('TURN_AUTHENTICATION_TOKEN')}", 'Content-Type': 'application/json' }
# Send all messages for the current state before a user input prompt (text/button input request) for message in microlesson_content['messages']: data = create_text_message(message, whatsapp_id)
print("data") print(data)
r = requests.post( f'https://whatsapp.turn.io/v1/messages', data=json.dumps(data), headers=headers )
print("STEP 4") # combine microlesson content and context_data object
updated_context = { "context": { "contact_id": whatsapp_id, "contact_uuid": context_data['contact_uuid'], "state": microlesson_content['state'], "bot_message": microlesson_content['input_prompt'], "user_message": user_message, "type": 'ask' } } return updated_context123456789101112dillen-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.1/en_core_web_sm-3.4.1-py3-none-any.whljsonpicklegit+ssh://git@gitlab.com/tangibleai/community/mathtext.git@main#egg=mathtextgit+ssh://git@gitlab.com/tangibleai/community/mathactive.git@vlad#egg=mathactivefastapipydanticrequestssentencepiecesupabasetransitionsuvicorn123456789101112131415dillen-core-web-sm @ https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.4.1/en_core_web_sm-3.4.1-py3-none-any.whlfuzzywuzzyjsonpicklemathtext @ git+https://gitlab.com/tangibleai/community/mathtext@mainfastapi==0.74.*openpyxlpydantic==1.10.*python-Levenshteinrequests==2.27.*sentencepiece==0.1.*sentence-transformerssupabasetransitionsuvicorn
21 unmodified lines2223242526272815 unmodified lines444546474849507 unmodified lines58596061626364656667686970717273747576777821 unmodified linesmessage_data = '{' + f'"author_id": "+57787919091", "author_type": "OWNER", "contact_uuid": "j43hk26-2hjl-43jk-hnk2-k4ljl46j0ds09", "message_body": "{message_text}", "message_direction": "inbound", "message_id": "4kl209sd0-a7b8-2hj3-8563-3hu4a89b32", "message_inserted_at": "2023-01-10T02:37:28.477940Z", "message_updated_at": "2023-01-10T02:37:28.487319Z"' + '}'# context_data = '{' + '"user":"", "state":"addition-question-sequence", "bot_message":"", "user_message":"{message_text}"' + '}'context_data = '{' + '"user":"", "state":"start-conversation", "bot_message":"", "user_message":"{message_text}"' + '}'# context_data = '{' + '"user":"", "state":"addition-question-sequence", "bot_message":"", "user_message":"{message_text}","text": "What is 2+3?","question_numbers": [4,3],"right_answer": 7,"number_correct": 2, "number_incorrect": 0, "hints_used": 0, "level": "easy"' + '}'15 unmodified linesprint(f"Case: {sample_answer}")b_string = add_message_text_to_sample_object(sample_answer)if endpoint == 'sentiment-analysis' or endpoint == 'text2int':request = requests.post(url=f'http://localhost:7860/{endpoint}',json={'content': sample_answer}7 unmodified linesprint(request)# run_simulated_request('sentiment-analysis', 'I reject it')# run_simulated_request('text2int', 'seven thousand nine hundred fifty seven')run_simulated_request('nlu', 'test message')run_simulated_request('nlu', 'eight')run_simulated_request('nlu', 'is it 8')run_simulated_request('nlu', 'can I know how its 0.5')run_simulated_request('nlu', 'eight, nine, ten')run_simulated_request('nlu', '8, 9, 10')run_simulated_request('nlu', '8')run_simulated_request('nlu', "I don't know")run_simulated_request('nlu', "I don't know eight")run_simulated_request('nlu', "I don't 9")run_simulated_request('nlu', "0.2")run_simulated_request('nlu', 'Today is a wonderful day')run_simulated_request('nlu', 'IDK 5?')# run_simulated_request('manager', '')# run_simulated_request('manager', 'add')# run_simulated_request('manager', 'subtract')21 unmodified lines222324252627282930313215 unmodified lines484950515253547 unmodified lines6263646566676869707172737475767778798081828384858621 unmodified linesmessage_data = '{' + f'"author_id": "+57787919091", "author_type": "OWNER", "contact_uuid": "j43hk26-2hjl-43jk-hnk2-k4ljl46j0ds09", "message_body": "{message_text}", "message_direction": "inbound", "message_id": "4kl209sd0-a7b8-2hj3-8563-3hu4a89b32", "message_inserted_at": "2023-01-10T02:37:28.477940Z", "message_updated_at": "2023-01-10T02:37:28.487319Z"' + '}'# context_data = '{' + '"user":"", "state":"addition-question-sequence", "bot_message":"", "user_message":"{message_text}"' + '}'# V1# context_data = '{' + '"user":"", "state":"start-conversation", "bot_message":"", "user_message":"{message_text}"' + '}'#V2context_data = '{' + '"contact_uuid": "j43hk26-2hjl-43jk-hnk2-k4ljl46j0ds09", "current_state":"", "local_state": "", "user_message":""' + '}'# context_data = '{' + '"user":"", "state":"addition-question-sequence", "bot_message":"", "user_message":"{message_text}","text": "What is 2+3?","question_numbers": [4,3],"right_answer": 7,"number_correct": 2, "number_incorrect": 0, "hints_used": 0, "level": "easy"' + '}'15 unmodified linesprint(f"Case: {sample_answer}")b_string = add_message_text_to_sample_object(sample_answer)if endpoint == 'sentiment-analysis' or endpoint == 'text2int' or endpoint =='intent-classification':request = requests.post(url=f'http://localhost:7860/{endpoint}',json={'content': sample_answer}7 unmodified linesprint(request)# run_simulated_request('intent-classification', 'exit')# run_simulated_request('intent-classification', "I'm not sure")# run_simulated_request('sentiment-analysis', 'I reject it')# run_simulated_request('text2int', 'seven thousand nine hundred fifty seven')# run_simulated_request('nlu', 'test message')# run_simulated_request('nlu', 'eight')# run_simulated_request('nlu', 'is it 8')# run_simulated_request('nlu', 'can I know how its 0.5')# run_simulated_request('nlu', 'eight, nine, ten')# run_simulated_request('nlu', '8, 9, 10')# run_simulated_request('nlu', '8')# run_simulated_request('nlu', "I don't know")# run_simulated_request('nlu', "I don't know eight")# run_simulated_request('nlu', "I don't 9")# run_simulated_request('nlu', "0.2")# run_simulated_request('nlu', 'Today is a wonderful day')# run_simulated_request('nlu', 'IDK 5?')run_simulated_request('v2/manager', '')run_simulated_request('v2/manager', '5')# run_simulated_request('manager', '')# run_simulated_request('manager', 'add')# run_simulated_request('manager', 'subtract')
README.md+1-1
app.py+45-3
mathtext_fastapi/curriculum_mapper.pyAdded+183
mathtext_fastapi/data/Rori_Framework_v1.xlsxAdded
mathtext_fastapi/data/curriculum_framework_for_tests.xlsxAdded
mathtext_fastapi/data/intent_classification_model.joblibAdded+3
mathtext_fastapi/data/labeled_data.csvAdded+144
mathtext_fastapi/data/text2int_results.csv+104-91
mathtext_fastapi/global_state_manager.pyAdded+23
mathtext_fastapi/intent_classification.pyAdded+52
mathtext_fastapi/nlu.py+96-15
mathtext_fastapi/v2_conversation_manager.pyAdded+257
requirements.txt+10-7
scripts/make_request.py+23-15