Browse Source

fix generate messages for default, extend tests

Loann Peurey 1 year ago
parent
commit
61a18ca7dc

+ 42 - 1
generate_messages/messages.py

@@ -124,6 +124,46 @@ def fill_template(template_key, messages, metrics_evolution, date, start_date, e
     
     return template
 
+def fill_default(messages, date, start_date, end_date):
+    """
+    given the full list of templates, the date to consider and the dates of the experiment,
+    takes the default messages template and fills it according to the keywords
+    :param messages: dictionary of templates (taken from yaml file)
+    :type messages: dict
+    :param date: date for wich to fill the template
+    :type date: datetime.datetime
+    :param start_date: date of the start of the experiment
+    :type start_date: datetime.datetime
+    :param duration_experiment: total duration of the experiment in days
+    :type duration_experiment: int
+    :return: filled default message
+    :rtype: str
+    """
+    template = messages['others']['fixed']['default']
+    
+    for msg_key in messages['others']['fixed']:
+        if msg_key == 'default': continue #skip default message as it is our base template (could lead to infinite loop of filling templates otherwise)
+        template = template.replace('#{}'.format(msg_key),messages['others']['fixed'][msg_key])
+                                    
+    if end_date <= start_date : raise ValueError('start_date {} should be before end_date {}'.format(start_date,end_date))
+    total_days = end_date - start_date
+    time_elapsed = date.date() - start_date.date()
+                                    
+    for msg_key in messages['others']['variable']:
+        nb_keys = len(messages['others']['variable'][msg_key].keys())
+        if nb_keys == 0 : raise ValueError('Message must have at least one version')
+        msg_fraction = 1 / nb_keys
+        time_fraction = time_elapsed.days / total_days.days
+        index = math.ceil(time_fraction / msg_fraction)
+        if index < 1 :index = 1 #if before the start of the experiment, use the first message
+        if index > nb_keys : index = nb_keys #if after the end of the experiment, use last message
+        #index = str(index)
+           
+        if index not in messages['others']['variable'][msg_key].keys() : raise ValueError('Could not find message : <others: variable : {} : {}> in yaml. Messages listed in a variable sentence shoud be 1, 2, ...'.format(msg_key,index))
+        
+        template = template.replace('#{}'.format(msg_key), messages['others']['variable'][msg_key][index])
+                                    
+    return template
 
 def build_messages(metrics_recordings, metrics_columns, message_file_path, date):
     """
@@ -173,7 +213,8 @@ def build_messages(metrics_recordings, metrics_columns, message_file_path, date)
         # Only one audio (first week), generated default message
         if len(metrics_grouped_item) == 1:
             recording_filename = metrics_grouped_item.iloc[0]['recording_filename']
-            message = metric_messages['fixed']['default']
+            message = fill_default(metric_messages, date_time, experiment_start_date, experiment_end_date)
+            #message = metric_messages['others']['fixed']['default']
         # More than one audio file: generate a message
         else:
             todays_row = sorted_metrics_grouped_items.iloc[0]

+ 2 - 0
tests/data/mockup_messages/messages_14000202.csv

@@ -0,0 +1,2 @@
+recording_filename;message
+14000202/100_xxx_14000202_000000.wav;Gracias por enviarnos el audio. Qué bueno que hayas tomado un rato para conversar con tu hijo/a. Comunicate con <<nombre-bebe>> en todas las oportunidades que tengas – esto le hará muy bien ahora y en el futuro.

+ 17 - 1
tests/test_generateMessages.py

@@ -53,11 +53,27 @@ def test_fill_template(key,yml,evol,truth, date):
     res = msg.fill_template(key,yml,evol,datet, start,end)
     #print(res)
     assert truth == res
+
+@pytest.mark.parametrize('yml,date,truth',[
+    (YAML,'20221101', 'Gracias por enviarnos el audio. Qué bueno que hayas tomado un rato para conversar con tu hijo/a. Comunicate con <<nombre-bebe>> en todas las oportunidades que tengas – esto le hará muy bien ahora y en el futuro.'), 
+    (YAML,'20221118', 'Gracias por enviarnos el audio. Qué bueno que hayas tomado un rato para conversar con tu hijo/a. Comunicate con <<nombre-bebe>> en todas las oportunidades que tengas – le ayudarás a desarrollar más su capacidad de expresarse.'), 
+    (YAML,'20221114', 'Gracias por enviarnos el audio. Qué bueno que hayas tomado un rato para conversar con tu hijo/a. Comunicate con <<nombre-bebe>> en todas las oportunidades que tengas – estarás contribuyendo a desarrollar más su cerebro.'), 
+    (YAML,'20221201', 'Gracias por enviarnos el audio. Qué bueno que hayas tomado un rato para conversar con tu hijo/a. Comunicate con <<nombre-bebe>> en todas las oportunidades que tengas – le ayudarás a estimular sus habilidades sociales.'), 
+     ])
+def test_fill_default(yml,truth, date):
+    start = datetime.datetime.strptime(YAML['start_date'],'%Y-%m-%d')
+    end = datetime.datetime.strptime(YAML['end_date'],'%Y-%m-%d')
+    datet = datetime.datetime.strptime(date,'%Y%m%d')
+    
+    res = msg.fill_default(yml,datet, start,end)
+    #print(res)
+    assert truth == res
   
 #dependent on get_metrics - fill_template
 @pytest.mark.parametrize('date,dateThrow',[
     ('20220117',False), 
-    ('20220207',False), 
+    ('20220207',False),
+    ('14000202',False), 
     ('2022-01-01',True),  
      ]) 
 def test_build_messages(date, dateThrow):