File size: 32,448 Bytes
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
349ff65
 
 
 
 
 
 
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f63b719
 
 
 
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f63b719
 
 
478fd8c
 
 
 
 
 
 
 
 
 
 
f63b719
 
 
 
478fd8c
 
f63b719
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec04543
478fd8c
 
ec04543
478fd8c
 
ec04543
478fd8c
 
ec04543
478fd8c
 
ec04543
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec04543
478fd8c
 
ec04543
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec04543
478fd8c
 
ec04543
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec04543
478fd8c
 
ec04543
478fd8c
 
ec04543
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec04543
478fd8c
 
ec04543
478fd8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec04543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
478fd8c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
from create_new_formularios import get_sorted_date_keys
from pathlib import Path
from datetime import datetime
from create_new_usuarios import get_macros_from_string
import statistics

def query_formularios(data, query_list, debug=False, file_name=None):

    if file_name is not None:
        debug = True
        print(f"***************** file_name: {file_name} *****************")

    # Get date keys
    date_keys = get_sorted_date_keys(data)
    if debug: print(f"\n\n\ndate_keys: {date_keys}")

    # List of date keys that match the query
    date_keys_that_match = []

    # No data value
    no_data_value = "| no data"

    # Get all the keys in the query_list
    queries_list = []
    for query in query_list:
        queries_list.append(query)
    if debug:
        print("queries_list:")
        for query in queries_list:
            for key in query.keys():
                print(f"\tkey: {key}", end=" --> ")
                for second_key in query[key].keys():
                    print(f"{key}: {query[key][second_key]}", end=", ")
                print("")

    # For each date key get all the keys
    for date_key in date_keys:
        if debug: print(f"\n * date_key: {date_key}")

        # match is a boolean that will be true if the key is in query_dict
        match = False
        if debug: print(f"\tinitial match value: {match}")

        # Get all the keys in the data
        data_keys = data[date_key].keys()
        if debug: print(f"\tkeys: {data_keys}")

        # Find for each key if it is in query_dict
        for query in queries_list:
            # Get the query key
            query_key = list(query.keys())[0]

            # Get the query operator and value
            query_operator = query[query_key]['operator']
            is_operator_for_numbers = query_operator == '>' or query_operator == '<' or query_operator == '>=' or query_operator == '<='
            query_value = query[query_key]['value']
            type_of_query_value = type(query_value)
            is_query_value_string = type_of_query_value == str
            is_query_value_number = type_of_query_value == int or type_of_query_value == float

            # Check if the query key is in the data
            if query_key in data_keys:
                # Get the data value
                data_value = data[date_key][query_key]
                if isinstance(data_value, str):
                    data_value = data_value.lower()
                    data_value = data_value.replace('á', 'a')
                    data_value = data_value.replace('é', 'e')
                    data_value = data_value.replace('í', 'i')
                    data_value = data_value.replace('ó', 'o')
                    data_value = data_value.replace('ú', 'u')
                type_of_data_value = type(data_value)
                is_data_value_string = type_of_data_value == str
                is_data_value_number = type_of_data_value == int or type_of_data_value == float
                is_data_value_and_query_value_number = is_data_value_number and is_query_value_number
                is_data_value_and_query_value_string = is_data_value_string and is_query_value_string
                is_data_value_or_query_value_number = is_data_value_number or is_query_value_number
                is_data_value_or_query_value_string = is_data_value_string or is_query_value_string
                if debug: print(f"\t\tchecking \"{query_key}\" in data, query operator: \"{query_operator}\", query value: \"{query_value}\", data value: \"{data_value}\"")

                # Check if the data value matches the query value
                if query_operator == '==':
                    if query_value == data_value:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is equal to \"{data_value}\", match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT equal to \"{data_value}\", match: {match}")
                        break
                    # continue
                elif query_operator == '!=':
                    if query_value != data_value:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT equal to \"{data_value}\", match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT equal to \"{data_value}\", match: {match}")
                        break
                    # continue
                elif is_query_value_number and is_data_value_number and query_operator == '>':
                    if data_value > query_value:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is greater than \"{data_value}\", match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT greater than \"{data_value}\", match: {match}")
                        break
                    # continue
                elif is_query_value_number and is_data_value_number and query_operator == '<':
                    if data_value < query_value:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is less than \"{data_value}\", match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT less than \"{data_value}\", match: {match}")
                        break
                    # continue
                elif is_query_value_number and is_data_value_number and query_operator == '>=':
                    if data_value >= query_value:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is greater than or equal to \"{data_value}\", match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT greater than or equal to \"{data_value}\", match: {match}")
                        break
                    # continue
                elif is_query_value_number and is_data_value_number and query_operator == '<=':
                    if data_value <= query_value:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is less than or equal to \"{data_value}\", match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT less than or equal to \"{data_value}\", match: {match}")
                        break
                    # continue
                elif is_query_value_string and is_data_value_string and query_operator == 'in' or query_operator == 'contains':
                    if query_value in data_value or no_data_value in data_value:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is in \"{data_value}\", match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT in \"{data_value}\", match: {match}")
                        break
                    # continue
                elif is_query_value_string and is_data_value_string and (query_operator == 'NOT in' or query_operator == 'NOT contains'):
                    if query_value not in data_value or no_data_value in data_value:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT in \"{data_value}\", match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT in \"{data_value}\", match: {match}")
                        break
                    # continue
                elif query_operator == 'is null':
                    if data_value is None:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is null, match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT null, match: {match}")
                        break
                    # continue
                elif query_operator == 'is NOT null':
                    if data_value is not None:
                        match = True
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT null, match: {match}")
                    else:
                        match = False
                        if debug: print(f"\t\t\t\"{query_value}\" is NOT null, match: {match}")
                        break
                    # continue
                elif is_operator_for_numbers and is_data_value_or_query_value_string:
                    if is_data_value_string and is_query_value_string:
                        match = False
                        if debug: print(f"\t\t\toperator \"{query_operator}\" NOT supported, because data value is string and query value is string, match: {match}")
                        break
                    elif is_data_value_string and is_query_value_number:
                        match = False
                        if debug: print(f"\t\t\toperator \"{query_operator}\" NOT supported, because data value is string, match: {match}")
                        break
                    else:
                        match = False
                        if debug: print(f"\t\t\toperator \"{query_operator}\" NOT supported, because query value is number, match: {match}")
                        break
                else:
                    match = False
                    if debug: print(f"\t\t\toperator \"{query_operator}\" NOT supported, match: {match}")
                    break
                    # continue
            
        # If the match is true, add the date_key to the list
        if match:
            if debug: print(f"\t***** {query_key} matches, adding date_key: {date_key} *****")
            date_keys_that_match.append(date_key)
            if debug:
                print("\t dates that match:")
                for date_key in date_keys_that_match:
                    print(f"\t\t{date_key}")

    return date_keys_that_match

def string_date_list_to_date_list(string_date_list):
    date_list = []
    for string_date in string_date_list:
        date_list.append(datetime.strptime(string_date, '%Y-%m-%d'))
    return date_list

def date_to_string(date):
    string_date = date.strftime('%Y-%m-%d')
    string_date = string_date.replace('-01', '-1')
    string_date = string_date.replace('-02', '-2')
    string_date = string_date.replace('-03', '-3')
    string_date = string_date.replace('-04', '-4')
    string_date = string_date.replace('-05', '-5')
    string_date = string_date.replace('-06', '-6')
    string_date = string_date.replace('-07', '-7')
    string_date = string_date.replace('-08', '-8')
    string_date = string_date.replace('-09', '-9')
    return string_date

def get_days_between_dates(date1, date2):
    if isinstance(date1, str):
        date1 = datetime.strptime(date1, '%Y-%m-%d')
    if isinstance(date2, str):
        date2 = datetime.strptime(date2, '%Y-%m-%d')
    return (date1 - date2).days

def query_usuarios(data, query_list, limit_days=8, debug=False):
    # Get date keys
    date_keys = get_sorted_date_keys(data)
    if debug: print(f"\tdate_keys: {date_keys}")

    # Format date_keys to date objects
    date_keys = string_date_list_to_date_list(date_keys)

    # Format query_list to date objects
    if debug: print(f"\tquery_list: {query_list}")
    query_list = string_date_list_to_date_list(query_list)

    # Create empty list to store the date_keys that match
    date_keys_that_match = []

    # Create empty list to store the macros differences date
    macros_differences_dates = []

    # Iterate for each query_list date
    for query_date in query_list:
        # Iterate for each date_key
        for date_key in date_keys:
            # Get the days between the query_date and the date_key
            days_between = get_days_between_dates(query_date, date_key)
            if days_between <= limit_days and days_between > 0:
                if debug: print(f"\tdays between form data {date_to_string(query_date)} and macros change data {date_to_string(date_key)}: {days_between}")

                # Add the date_key to the list and break the loop, because is first mach so is match with less days between dates
                date_keys_that_match.append(date_to_string(date_key))

                # Add the date_key to the macros_differences_dates list
                macros_differences_dates.append(date_to_string(query_date))

                break

    return date_keys_that_match, macros_differences_dates

def get_macros_differences(data, dates_list):
    macros_differences_list = []
    for date in dates_list:
        macros_differences_list.append(data[date]['diferencia_macros'])
    return macros_differences_list

def get_min_max_mean_mode_macros_differences(macros_differences_list):
    # Create list for each macro
    train_day_protein_list = []
    train_day_carbs_list = []
    train_day_fat_list = []
    intratrain_protein_list = []
    intratrain_carbs_list = []
    rest_day_protein_list = []
    rest_day_carbs_list = []
    rest_day_fat_list = []

    # Iterate over the macros differences list
    for macros_difference in macros_differences_list:
        # Get the macros difference as a list of integers
        macros_difference_int_list = get_macros_from_string(macros_difference)

        # Append the macros difference to the list
        train_day_protein_list.append(macros_difference_int_list[0])
        train_day_carbs_list.append(macros_difference_int_list[1])
        train_day_fat_list.append(macros_difference_int_list[2])
        intratrain_protein_list.append(macros_difference_int_list[3])
        intratrain_carbs_list.append(macros_difference_int_list[4])
        rest_day_protein_list.append(macros_difference_int_list[5])
        rest_day_carbs_list.append(macros_difference_int_list[6])
        rest_day_fat_list.append(macros_difference_int_list[7])
    
    # Get the min, max, mean and mode of the macros differences
    min_train_day_protein = min(train_day_protein_list)
    max_train_day_protein = max(train_day_protein_list)
    mean_train_day_protein = sum(train_day_protein_list) / len(train_day_protein_list)
    mode_train_day_protein = statistics.mode(train_day_protein_list)
    train_day_protein_std = (min_train_day_protein, max_train_day_protein, mean_train_day_protein, mode_train_day_protein)

    min_train_day_carbs = min(train_day_carbs_list)
    max_train_day_carbs = max(train_day_carbs_list)
    mean_train_day_carbs = sum(train_day_carbs_list) / len(train_day_carbs_list)
    mode_train_day_carbs = statistics.mode(train_day_carbs_list)
    train_day_carbs_std = (min_train_day_carbs, max_train_day_carbs, mean_train_day_carbs, mode_train_day_carbs)

    min_train_day_fat = min(train_day_fat_list)
    max_train_day_fat = max(train_day_fat_list)
    mean_train_day_fat = sum(train_day_fat_list) / len(train_day_fat_list)
    mode_train_day_fat = statistics.mode(train_day_fat_list)
    train_day_fat_std = (min_train_day_fat, max_train_day_fat, mean_train_day_fat, mode_train_day_fat)

    min_intratrain_protein = min(intratrain_protein_list)
    max_intratrain_protein = max(intratrain_protein_list)
    mean_intratrain_protein = sum(intratrain_protein_list) / len(intratrain_protein_list)
    mode_intratrain_protein = statistics.mode(intratrain_protein_list)
    intratrain_protein_std = (min_intratrain_protein, max_intratrain_protein, mean_intratrain_protein, mode_intratrain_protein)

    min_intratrain_carbs = min(intratrain_carbs_list)
    max_intratrain_carbs = max(intratrain_carbs_list)
    mean_intratrain_carbs = sum(intratrain_carbs_list) / len(intratrain_carbs_list)
    mode_intratrain_carbs = statistics.mode(intratrain_carbs_list)
    intratrain_carbs_std = (min_intratrain_carbs, max_intratrain_carbs, mean_intratrain_carbs, mode_intratrain_carbs)

    min_rest_day_protein = min(rest_day_protein_list)
    max_rest_day_protein = max(rest_day_protein_list)
    mean_rest_day_protein = sum(rest_day_protein_list) / len(rest_day_protein_list)
    mode_rest_day_protein = statistics.mode(rest_day_protein_list)
    rest_day_protein_std = (min_rest_day_protein, max_rest_day_protein, mean_rest_day_protein, mode_rest_day_protein)

    min_rest_day_carbs = min(rest_day_carbs_list)
    max_rest_day_carbs = max(rest_day_carbs_list)
    mean_rest_day_carbs = sum(rest_day_carbs_list) / len(rest_day_carbs_list)
    mode_rest_day_carbs = statistics.mode(rest_day_carbs_list)
    rest_day_carbs_std = (min_rest_day_carbs, max_rest_day_carbs, mean_rest_day_carbs, mode_rest_day_carbs)

    min_rest_day_fat = min(rest_day_fat_list)
    max_rest_day_fat = max(rest_day_fat_list)
    mean_rest_day_fat = sum(rest_day_fat_list) / len(rest_day_fat_list)
    mode_rest_day_fat = statistics.mode(rest_day_fat_list)
    rest_day_fat_std = (min_rest_day_fat, max_rest_day_fat, mean_rest_day_fat, mode_rest_day_fat)

    return train_day_protein_std, train_day_carbs_std, train_day_fat_std, intratrain_protein_std, intratrain_carbs_std, rest_day_protein_std, rest_day_carbs_std, rest_day_fat_std

def clustering_esfuerzo_dieta_response(response, debug=False):
    # Options:
    #     No entiendo la calculadora, quiero menús tipo, cárgame 4|I: 2
	#     No costó nada|A: 1504
	#     Costó demasiado, súbeme macros|D: 28
	#     Costó, pero me adapto a nuevos ajustes|C: 331
	#     Iba a coger menús tipo, pero al final por precio no|D: 13
	#     Costó demasiado, bájame macros|D: 42
	#     No entiendo la calculadora, quiero menús tipo, cárgame 2|I: 3
    # 
    # Clustering:
    #     0 (No data): 
    #         No entiendo la calculadora, quiero menús tipo, cárgame 4|I: 2 | No data
    #         Iba a coger menús tipo, pero al final por precio no|D: 13 | No data
    #         No entiendo la calculadora, quiero menús tipo, cárgame 2|I: 3 | No data
    #     1 (costó subir macros): 
    #         Costó demasiado, súbeme macros|D: 28 | costo subir macros
    #     2 (costó bajar macros): 
    #         Costó demasiado, bájame macros|D: 42 | costo bajar macros
    #     3 (costó y me adapto a nuevos ajustes): 
    #         Costó, pero me adapto a nuevos ajustes|C: 331 | costo y me adapto a nuevos ajustes
    #     4 (no costó): 
    #         No costó nada|A: 1504 | no costo

    if " | No data".lower() in response.lower() or 'no data'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> no data")
        return 'no data'
    elif " | costo subir macros".lower() in response.lower() or 'costo subir macros'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> costo subir macros")
        return 'costo subir macros'
    elif " | costo bajar macros".lower() in response.lower() or 'costo bajar macros'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> costo bajar macros")
        return 'costo bajar macros'
    elif " | costo y me adapto a nuevos ajustes".lower() in response.lower() or 'costo y me adapto a nuevos ajustes'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> costo y me adapto a nuevos ajustes")
        return 'costo y me adapto a nuevos ajustes'
    elif " | no costo".lower() in response.lower() or 'no costo'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> no costo")
        return 'no costo'
    else:
        if debug: print(f"\t\t{response} -> no data")
        return 'no data'

def clustering_objetivo_response(response, debug=False):
    # Options:
    #     definición (nada cambia)|A: 1031
    #     empezamos a definir (cambia)|C: 92
    #     perder peso (nada cambia)|A: 21
    #     volumen (nada cambia)|A: 688
    #     empezamos a coger volumen (cambia)|C: 78
    #     empezamos a coger volumen, sobre todo tren inferior (cambia)|C: 7
    #     empezamos a coger volumen, en todo el cuerpo (cambia)|C: 6
    # 
    # Clustering:
    #     0 (definición): 
    #         definición (nada cambia)|A: 1031 | definición
    #         empezamos a definir (cambia)|C: 92 | definición
    #         perder peso (nada cambia)|A: 21 | definición
    #     1 (volumen): 
    #         volumen (nada cambia)|A: 688 | volumen
    #         empezamos a coger volumen (cambia)|C: 78 | volumen
    #         empezamos a coger volumen, sobre todo tren inferior (cambia)|C: 7 | volumen
    #         empezamos a coger volumen, en todo el cuerpo (cambia)|C: 6 | volumen

    if " | definicion".lower() in response.lower() or 'definicion'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> definicion")
        return 'definicion'
    elif " | volumen".lower() in response.lower() or 'volumen'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> volumen")
        return 'volumen'
    else:
        if debug: print(f"\t\t{response} -> no data")
        return 'no data'

def clustering_entrenamiento_response(response, debug=False):
    # Options:
    #     Lo hice perfecto|A|10: 838
    #     He fallado algunos días, pero sí|B|5: 98
    #     Lesión importante: 16
    #     Lo hice prácticamente perfecto|A|8: 416
    #     Pequeña lesión: 63
    #     No hice nada, mantenemos la rutina un mes más|I|0: 64
    #     Alárgame la rutina una semana más|I|6: 32
    # 
    # Clustering:
    #     0 (bien): 
    #         Lo hice perfecto|A|10: 838 | bien
    #         He fallado algunos días, pero sí|B|5: 98 | bien
    #         Lo hice prácticamente perfecto|A|8: 416 | bien
    #     1 (mal): 
    #         Lesión importante: 16 | mal
    #         Pequeña lesión: 63 | mal
    #         No hice nada, mantenemos la rutina un mes más|I|0: 64 | mal
    #         Alárgame la rutina una semana más|I|6: 32 | mal
    
    if " | bien".lower() in response.lower() or 'bien'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> bien")
        return 'bien'
    elif " | mal".lower() in response.lower() or 'mal'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> mal")
        return 'mal'
    else:
        if debug: print(f"\t\t{response} -> no data")
        return 'no data'

def clustering_cumplimiento_dieta_response(response, debug=False):
    # Options:
    #     al 70%|B|6: 564
    #     regular, me cuesta llegar|C|5: 57
    #     Nada, mantén mis macros|I|0: 123
    #     casi perfecta|A|9: 610
    #     regular, me salto la dieta|C|4: 6
    #     Perfecta|A|10: 563
    # 
    # Clustering:
    #     0 (bien): 
    #         al 70%|B|6: 564 | bien
    #         casi perfecta|A|9: 610 | bien
    #         Perfecta|A|10: 563 | bien
    #     1 (regular): 
    #         regular, me cuesta llegar|C|5: 57 | regular
    #         regular, me salto la dieta|C|4: 6 | regular
    #     2 (mal): 
    #         Nada, mantén mis macros|I|0: 123 | mal

    if " | bien".lower() in response.lower() or 'bien'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> bien")
        return 'bien'
    elif " | regular".lower() in response.lower() or 'regular'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> regular")
        return 'regular'
    elif "nada" in response.lower() or 'mal'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> mal")
        return 'mal'
    else:
        if debug: print(f"\t\t{response} -> no data")
        return 'no data'

def clustering_compromiso_response(response, debug=False):
    # Options:
    #     Bueno, pero mejorable|B|7: 604
    #     Mal, pero a partir de ahora voy a por todas|C|0: 319
    #     Mal, demasiado exigente|D|0: 15
    #     Máximo|A|10: 985
    # 
    # Clustering:
    #     0 (bueno): 
    #         Bueno, pero mejorable|B|7: 604 | bueno
    #         Máximo|A|10: 985 | bueno
    #     1 (mal): 
    #         Mal, pero a partir de ahora voy a por todas|C|0: 319 | mal
    #         Mal, demasiado exigente|D|0: 15 | mal

    if " | bueno".lower() in response.lower() or 'bueno'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> bueno")
        return 'bueno'
    elif " | mal".lower() in response.lower() or 'mal'.lower() in response.lower():
        if debug: print(f"\t\t{response} -> mal")
        return 'mal'
    else:
        if debug: print(f"\t\t{response} -> no data")
        return 'no data'

def clustering_diferencia_peso_response(diff, debug=False):
    diff_min = None
    diff_max = None
    if diff <= -5.0:
        if debug: print(f"\t\t-10 <= {diff} <= -5")
        diff_min = -10
        diff_max = -5
    elif diff <= -4.5:
        if debug: print(f"\t\t-5 <= {diff} <= -4.5")
        diff_min = -5
        diff_max = -4.5
    elif diff <= -4.0:
        if debug: print(f"\t\t-4.5 <= {diff} <= -4.0")
        diff_min = -4.5
        diff_max = -4.0
    elif diff <= -3.5:
        if debug: print(f"\t\t-4.0 <= {diff} <= -3.5")
        diff_min = -4.0
        diff_max = -3.5
    elif diff <= -3.0:
        if debug: print(f"\t\t-3.5 <= {diff} <= -3.0")
        diff_min = -3.5
        diff_max = -3.0
    elif diff <= -2.5:
        if debug: print(f"\t\t-3.0 <= {diff} <= -2.5")
        diff_min = -3.0
        diff_max = -2.5
    elif diff <= -2.0:
        if debug: print(f"\t\t-2.5 <= {diff} <= -2.0")
        diff_min = -2.5
        diff_max = -2.0
    elif diff <= -1.5:
        if debug: print(f"\t\t-2.0 <= {diff} <= -1.5")
        diff_min = -2.0
        diff_max = -1.5
    elif diff <= -1.0:
        if debug: print(f"\t\t-1.5 <= {diff} <= -1.0")
        diff_min = -1.5
        diff_max = -1.0
    elif diff <= -0.5:
        if debug: print(f"\t\t-1.0 <= {diff} <= -0.5")
        diff_min = -1.0
        diff_max = -0.5
    elif diff <= 0.0:
        if debug: print(f"\t\t-0.5 <= {diff} <= 0.0")
        diff_min = -0.5
        diff_max = 0.0
    elif diff <= 0.5:
        if debug: print(f"\t\t0.0 <= {diff} <= 0.5")
        diff_min = 0.0
        diff_max = 0.5
    elif diff <= 1.0:
        if debug: print(f"\t\t0.5 <= {diff} <= 1.0")
        diff_min = 0.5
        diff_max = 1.0
    elif diff <= 1.5:
        if debug: print(f"\t\t1.0 <= {diff} <= 1.5")
        diff_min = 1.0
        diff_max = 1.5
    elif diff <= 2.0:
        if debug: print(f"\t\t1.5 <= {diff} <= 2.0")
        diff_min = 1.5
        diff_max = 2.0
    elif diff <= 2.5:
        if debug: print(f"\t\t2.0 <= {diff} <= 2.5")
        diff_min = 2.0
        diff_max = 2.5
    elif diff <= 3.0:
        if debug: print(f"\t\t2.5 <= {diff} <= 3.0")
        diff_min = 2.5
        diff_max = 3.0
    elif diff <= 3.5:
        if debug: print(f"\t\t3.0 <= {diff} <= 3.5")
        diff_min = 3.0
        diff_max = 3.5
    elif diff <= 4.0:
        if debug: print(f"\t\t3.5 <= {diff} <= 4.0")
        diff_min = 3.5
        diff_max = 4.0
    elif diff <= 4.5:
        if debug: print(f"\t\t4.0 <= {diff} <= 4.5")
        diff_min = 4.0
        diff_max = 4.5
    elif diff <= 5.0:
        if debug: print(f"\t\t4.5 <= {diff} <= 5.0")
        diff_min = 4.5
        diff_max = 5.0
    else:
        if debug: print(f"\t\t{diff} -> no data")
        diff_min = None
        diff_max = None
    
    return diff_min, diff_max

def dieta_response(response_esfuerzo, response_cumplimiento, debug=False):
    # esfuerzo dieta:
    #     0 (No data): 
    #         No entiendo la calculadora, quiero menús tipo, cárgame 4|I: 2
    #         Iba a coger menús tipo, pero al final por precio no|D: 13
    #         No entiendo la calculadora, quiero menús tipo, cárgame 2|I: 3
    #     1 (costó subir macros): 
    #         Costó demasiado, súbeme macros|D: 28
    #     2 (costó bajar macros): 
    #         Costó demasiado, bájame macros|D: 42
    #     3 (costó y me adapto a nuevos ajustes): 
    #         Costó, pero me adapto a nuevos ajustes|C: 331
    #     4 (no costó): 
    #         No costó nada|A: 1504
    # compromiso dieta:
    #     0 (bien): 
    #         al 70%|B|6: 564
    #         casi ©|A|9: 610
    #         Perfecta|A|10: 563
    #     1 (regular): 
    #         regular, me cuesta llegar|C|5: 57
    #         regular, me salto la dieta|C|4: 6
    #     2 (mal): 
    #         Nada, mantén mis macros|I|0: 123

    esfuerzo_dieta_cluster = clustering_esfuerzo_dieta_response(response_esfuerzo, debug)
    cumplimiento_dieta_cluster = clustering_cumplimiento_dieta_response(response_cumplimiento, debug)

    if esfuerzo_dieta_cluster == 0:
        dieta_bien = cumplimiento_dieta_cluster == 0
        dieta_regular = cumplimiento_dieta_cluster == 1
        dieta_mal = cumplimiento_dieta_cluster == 2
    else:
        dieta_bien = esfuerzo_dieta_cluster == 4 and cumplimiento_dieta_cluster == 0
        dieta_regular = esfuerzo_dieta_cluster == 3 and cumplimiento_dieta_cluster == 1
        dieta_mal = (esfuerzo_dieta_cluster == 2 or esfuerzo_dieta_cluster == 1) and cumplimiento_dieta_cluster == 2
    
    if dieta_bien:
        return 0
    elif dieta_regular:
        return 1
    elif dieta_mal:
        return 2
    else:
        return 3

def make_query(cluster_esfuerzo_dieta, cluster_objetivo, cluster_entrenamiento, cluster_cumplimiento_dieta,
               cluster_compromiso, diff_peso_min, diff_peso_max,
               basic_query=False):
    if not basic_query:
        query = [
            {
                'esfuerzoParaCumplirDieta':
                    {
                        'operator': 'in',
                        'value': cluster_esfuerzo_dieta,
                    }
            },
            {
                'objetivo':
                    {
                        'operator': 'in',
                        'value': cluster_objetivo,
                    }
            },
            {
                'cumplimientoEntrenamiento':
                    {
                        'operator': 'in',
                        'value': cluster_entrenamiento,
                    }
            },
            {
                'cumplimientoDieta':
                    {
                        'operator': 'in',
                        'value': cluster_cumplimiento_dieta,
                    }
            },
            {
                'compromiso':
                    {
                        'operator': 'in',
                        'value': cluster_compromiso,
                    }
            },
            {
                'diferencia_peso':
                    {
                        'operator': '<=',
                        'value': diff_peso_max,
                    }
            },
            {
                'diferencia_peso':
                    {
                        'operator': '>=',
                        'value': diff_peso_min,
                    }
            }
        ]
    else:
        query = [
            {
                'objetivo':
                    {
                        'operator': 'in',
                        'value': cluster_objetivo,
                    }
            },
            {
                'cumplimientoEntrenamiento':
                    {
                        'operator': 'in',
                        'value': cluster_entrenamiento,
                    }
            },
            {
                'cumplimientoDieta':
                    {
                        'operator': 'in',
                        'value': cluster_cumplimiento_dieta,
                    }
            },
        ]

    if cluster_esfuerzo_dieta.lower() == 'costo subir macros'.lower() or cluster_esfuerzo_dieta.lower() == 'costo bajar macros'.lower():
        # Remove diferencia peso
        query.pop(6)
        query.pop(5)
        # Remove compromiso
        query.pop(4)
        # Remove cumplimiento dieta
        query.pop(3)
        # Remove cumplimiento entrenamiento
        query.pop(2)
        # Remove objetivo
        query.pop(1)
    elif cluster_esfuerzo_dieta.lower() == 'no data'.lower():
        # Remove esfuerzo dieta
        query.pop(0)
    
    return query