1: import re
2: import ast
3: from openai import OpenAI
4: import copy
5: import pickle
6: import json
7: import random
8: from time import sleep
9: import numpy as np
10: import os
11: 
12: def get_API_client_cfg(model,temperature=0.0):
13:     """
14:     model= ["gpt-4o-mini","deepseek-chat"]
15:     """
16:     cfg_generation={"temperature":temperature,"model": model}
17:     from key import deepseek_key,openai_key
18: 
19:     if "deepseek" in model:
20:         client = OpenAI(api_key=deepseek_key, base_url="https://api.deepseek.com")
21: 
22:     if "gpt" in model.lower():
23:         client = OpenAI(api_key=openai_key)
24: 
25:     return client,cfg_generation
26: 
27: def merge_results(results):
28:     if isinstance(results, dict):
29:         return results
30:     all_results = {}
31:     for i in results:
32:         list_k = list(i['dict_response'].keys())
33:         for task_id in list_k:
34:             if not task_id in all_results:
35:                 all_results[task_id] = []
36:             for j in i['dict_response'][task_id]:
37:                 all_results[task_id].append(j)
38:                 
39:     return all_results
40: 
41: def to_formated_list(results):
42:     if isinstance(results, list):
43:         return results
44:     return [{"dict_response": results}]
45: 
46: def merged_dic_results(res1,res2):
47:     """
48:     merge two dict of results
49:     """
50:     for k,v in res2.items():
51:         if k in res1:
52:             res1[k]+=v
53:         else:
54:             res1[k]=v
55:     return res1
56: 
57: def get_dic_only_correct(dic_results):
58:     """
59:     Extracts only the correct responses from the given dictionary of results.
60:     
61:     Args:
62:         dic_results (dict): Dictionary containing results with keys as task IDs and values as lists of responses.
63:         
64:     Returns:
65:         dict: Dictionary with task IDs as keys and lists of correct responses as values.
66:     """
67:     dic_correct = {}
68:     for k, v in dic_results.items():
69:         for resp in v:
70:             if all(resp["correct_test_input"] + resp["correct_train_input"]):
71:                 if k not in dic_correct:
72:                     dic_correct[k] = []
73:                 dic_correct[k].append(resp)
74:     return dic_correct
75: 
76: def return_chat_format(message: str, system_prompt=None):
77:     """
78:     take a message and return the format for the chat
79:     """
80:     if system_prompt is None:
81:         system_prompt = "You are an AI assistant specialized in solving Abstract Reasoning Corpus (ARC-AGI) tasks by reasoning and generating Python code."
82:     return [{"role": "system", "content": system_prompt},
83:     {"role": "user", "content": message}]
84: 
85: 
86: def prompt2token_chat(tokenizer,prompts: list[str],tokenize=True, out_chat_format = False):
87:     """
88:     take a prompt and return the tokenized version in chat format
89:     """
90:     messages_list=[]
91:     for prompt in prompts:
92:         messages_list.append(return_chat_format(prompt))
93:     if out_chat_format:
94:         return messages_list
95:     return [tokenizer.apply_chat_template(messages, tokenize=tokenize,add_generation_prompt=True) for messages in messages_list]
96: 
97: def prompt2_chat(prompts: list[str]):
98:     """
99:     take a prompt and return the tokenized version in chat format
100:     """

560: 
561: def check_resp_ok(resp: Dict[str, List[Any]],task=None) -> bool:
562:     try:
563:         # correct_train = np.sum(resp["correct_train_input"])>=1
564:         # Combine both lists to avoid duplicate code
565:         all_grids = resp["predicted_test_output"] + resp["predicted_train_output"]
566: 
567:         # Use list comprehension instead of loops
568:         if not all(check_one_out(grid) for grid in all_grids):
569:             return False
570:         
571:         if task is not None:
572:             # check if test output is not just background
573: 
574:             has_only_background_output= np.sum([not(np.any(task["train"][i]["output"])) for i in range(len(task["train"]))])>=1
575:             list_pred_test= [not(np.any(resp["predicted_test_output"][i])) for i in range(len(resp["predicted_test_output"]))]
576:             if np.all(list_pred_test) and not has_only_background_output:
577:                 # print("test output is just background")
578:                 return False
579: 
580:             list_train_input=[task["train"][i]["input"] for i in range(len(task["train"]))]
581:             list_train_output=[task["train"][i]["output"] for i in range(len(task["train"]))]
582:             
583:             # remove task if all predicted train output are similar
584:             mean_dist_predicted_output_example = np.mean(compute_inter_grid_metrics(resp["predicted_train_output"], grid_distance))
585:             mean_dist_train_output_example = np.mean(compute_inter_grid_metrics(list_train_output, grid_distance))
586:             if mean_dist_predicted_output_example < min(0.2,mean_dist_train_output_example):
587:                 return False
588:             
589:             # check if output is not the same as input
590:             list_check_id = [(resp["predicted_train_output"][i]==list_train_input[i]) for i in range(len(resp["predicted_train_output"]))]
591:             list_check_id_given_io = [(list_train_output[i]==list_train_input[i]) for i in range(len(list_train_output))]
592: 
593:             # if 30% grids are the same as input rm
594:             if np.mean(list_check_id)>max(0.3,np.mean(list_check_id_given_io)):
595:                 return False
596:         return True
597:         
598:     except Exception:
599:         return False
600: 
601: def check_one_out(out: List[List[int]], debug: bool = False) -> bool:
602:     """Check if puzzle is valid"""
603:     try:
604:         # Quick validation checks
605:         if not out or not out[0]:  # Check for empty grid
606:             return False
607:             
608:         x_size, y_size = len(out), len(out[0])
609:         if x_size > 40 or y_size > 40:  # Size validation
610:             return False
611:             
612:         # Convert to numpy array once and use it for type checking
613:         grid = np.array(out)
614:         if grid.dtype not in (np.int32, np.int64):  # Check if all elements are integers
615:                 # check if all values are in [0,1,2,3,4,5,6,7,8,9]
616:             grid = grid.astype(int)
617:         if not np.all((0 <= grid) & (grid <= 9)):
618:             return False
619:             
620:         # No need to store shape variables if not used
621:         # _ = grid.shape
622:         x_shape,y_shape = grid.shape
623: 
624:         # Hash check (if still needed)
625:         hash(tuple(map(tuple, out)))
626:         
627:         return True
628:         
629:     except Exception:  # Catch any conversion errors
630:         return False
631: 
632: import numpy as np
633: 
634: def grid_distance(grid1, grid2, background=True):
635:     """
636:     Compute distance between two grids using Hamming distance on padded grids
637:     
638:     Args:
639:         grid1: First grid (numpy array)
640:         grid2: Second grid (numpy array)
641:     Returns:
642:         float: Normalized distance between 0 and 1
643:     """
644:     if isinstance(grid1, list):
645:         grid1 = np.array(grid1)
646:     if isinstance(grid2, list):
647:         grid2 = np.array(grid2)
648:     def pad_grids(grid1, grid2):
649:         max_rows = max(grid1.shape[0], grid2.shape[0])
650:         max_cols = max(grid1.shape[1], grid2.shape[1])
651:         padded_grid1 = np.pad(grid1, ((0, max_rows - grid1.shape[0]), 
652:                                      (0, max_cols - grid1.shape[1])), 'constant',constant_values=-1)
653:         padded_grid2 = np.pad(grid2, ((0, max_rows - grid2.shape[0]), 
654:                                      (0, max_cols - grid2.shape[1])), 'constant',constant_values=-1)
655:         return padded_grid1, padded_grid2
656:     
657:     # Pad both grids to same dimensions
658:     padded_grid1, padded_grid2 = pad_grids(grid1, grid2)
659:     if background:
660:         # Create mask for non-background positions
661:         mask = (padded_grid1 != 0) | (padded_grid2 != 0)
662:         
663:         # Calculate Hamming distance ignoring background pixels
664:         hamming_dist = np.sum((padded_grid1[mask] != padded_grid2[mask]))
665:         # Count total non-background positions for normalization
666:         total_non_background = np.sum(mask)
667:         # Avoid division by zero
668:         normalized_dist = hamming_dist / total_non_background if total_non_background > 0 else 0.0
669: 
670:     else:
671:         # Calculate Hamming distance (number of positions where grids differ)
672:         hamming_dist = np.sum(padded_grid1 != padded_grid2)
673:         
674:         # Normalize by total size of padded grids
675:         normalized_dist = hamming_dist / padded_grid1.size
676:     return normalized_dist
677: 
678: def compute_inter_grid_metrics(list_grid,metric):
679:     """
680:     Compute distances between all pairs of grids in the list
681:     
682:     Args:
683:         list_grid: List of numpy arrays (grids)
684:     Returns:
685:         list of tuples: (grid1_index, grid2_index, distance)
686:     """
687: 
688: 
689:     num_grids = len(list_grid)
690:     inter_grid_distances = []
691: 
692:     for i in range(num_grids):
693:         for j in range(i + 1, num_grids):
694:             distance = metric(list_grid[i], list_grid[j])
695:             inter_grid_distances.append(distance)
696: 
697:     return inter_grid_distances
698: 
699: def give_n_majority_vote_v2(task_responses, n_output=2, c=1000,return_responses=False):
700:     """ compared to v1, given all test output combined whereas v1 was majority voting for each test output independently"""
701: 
702:     len_test = len(task_responses[0]["predicted_test_output"])
703:     
704:     # Initialize the response structure
705:     list_response = [{
706:         "predicted_test_output": [[] for _ in range(len_test)],
707:         "correct_test_input": [False for _ in range(len_test)],
708:         "majority_vote": 0
709:     } for _ in range(n_output)]
710:     
711:     # Collect all valid responses across all test cases
712:     all_valid_responses = []
713:     
714:     for response_idx, response in enumerate(task_responses):
715:         valid_response = {
716:             "outputs": [], 
717:             "corrections": [], 
718:             "train_accuracy": np.mean(response["correct_train_input"]),
719:             "original_idx": response_idx  # Store the original index
720:         }
721:         
722:         # Process all test outputs for this response
723:         valid = True
724:         for id_test in range(len_test):
725:             output = response["predicted_test_output"][id_test]
726:             try:
727:                 output = np.array(output).tolist()
728:                 # Store the output and its correctness
729:                 valid_response["outputs"].append(serialize_list(output))
730:                 valid_response["corrections"].append(response["correct_test_input"][id_test])
731:             except:
732:                 # If any test case fails, consider the entire response invalid
733:                 valid = False
734:                 break
735:                 
736:         if valid:
737:             all_valid_responses.append(valid_response)
738:     
739:     # Count occurrences of complete response patterns
740:     response_counts = {}
741:     response_weights = {}
742:     response_originals = {}
743:     pattern_to_original_idxs = {}  # Now storing lists of indices
744:     
745:     for valid_response in all_valid_responses:
746:         # Create a tuple of all outputs to use as a key
747:         response_key = tuple(valid_response["outputs"])
748:         
749:         if response_key in response_counts:
750:             response_counts[response_key] += 1
751:             response_weights[response_key] += 1 + c * valid_response["train_accuracy"]
752:             # Add this response's index to the list for this pattern
753:             pattern_to_original_idxs[response_key].append(valid_response["original_idx"])
754:         else:
755:             response_counts[response_key] = 1
756:             response_weights[response_key] = 1 + c * valid_response["train_accuracy"]
757:             # Store the original outputs and corrections
758:             response_originals[response_key] = {
759:                 "outputs": [deserialize_list(out) for out in valid_response["outputs"]],
760:                 "corrections": valid_response["corrections"]
761:             }
762:             # Initialize the list of indices for this pattern
763:             pattern_to_original_idxs[response_key] = [valid_response["original_idx"]]
764:     
765:     # Get top n_output patterns based on weights
766:     top_patterns = sorted(response_weights.items(), key=lambda x: x[1], reverse=True)[:n_output]
767:     
768:     # Fill the response structure with the top patterns
769:     for i, (pattern, weight) in enumerate(top_patterns):
770:         if i < n_output:
771:             original_data = response_originals[pattern]
772:             
773:             for id_test in range(len_test):
774:                 list_response[i]["predicted_test_output"][id_test] = original_data["outputs"][id_test]
775:                 list_response[i]["correct_test_input"][id_test] = original_data["corrections"][id_test]
776:             list_response[i]["majority_vote"] = response_counts[pattern]
777:             list_response[i]["weight"] = weight
778:     
779:     # Get all original responses for each of the top patterns
780:     top_original_responses = []
781:     for pattern, weight in top_patterns:
782:         if pattern in pattern_to_original_idxs:
783:             # Get all responses that match this pattern
784:             pattern_responses = [task_responses[idx] for idx in pattern_to_original_idxs[pattern]]
785:             top_original_responses.append({"weight":weight,"response":pattern_responses})
786:     if return_responses:
787:         return list_response, top_original_responses
788:     else:
789:         return list_response
790:     
791: 
792: # Helper functions
793: def serialize_list(lst):
794:     """Convert a nested list to a tuple for hashing"""
795:     if isinstance(lst, list):
796:         return tuple(serialize_list(item) for item in lst)
797:     return lst
798: 
799: def deserialize_list(tpl):
800:     """Convert a nested tuple back to a list"""
801:     if isinstance(tpl, tuple):
802:         return [deserialize_list(item) for item in tpl]
803:     return tpl
804: 
805: def weighted_sample(list_original_resp, N):
806:     """
807:     Sample N items from multiple categories based on category weights and item quality.
808:     
809:     Args:
810:         list_original_resp: List of dictionaries, each with 'weight' and 'response' keys.
811:                            Format: [{"weight": w1, "response": [{"correct_train_input": [True,False,...], ...}, ...]}, ...]
812:                            Each response is a dictionary with at least a 'quality' key.
813:         N: Number of samples to return
814:         
815:     Returns:
816:         List of sampled responses
817:     """
818:     def compute_quality(response):
819:         return np.mean(np.array(response["correct_train_input"])*1000)
820:     # Extract weights and normalize them
821:     weights = [item["weight"] for item in list_original_resp]
822:     total_weight = sum(weights)
823:     normalized_weights = [w / total_weight for w in weights]
824:     
825:     # Calculate how many samples to take from each unique output 
826:     category_counts = np.random.multinomial(N, normalized_weights)
827:     
828:     sampled_responses = []
829:     
830:     # Sample from each category according to its allocated count
831:     for i, count in enumerate(category_counts):
832:         category_responses = list_original_resp[i]["response"]
833:         
834:         # Skip empty categories or when count is 0
835:         if count == 0 or not category_responses:
836:             continue
837:             
838:         # Extract quality scores for this category's responses
839:         quality_scores = [compute_quality(resp)+ 1e-10 for resp in category_responses]
840:         

875:             
876:         sampled_responses.extend(samples)
877:     
878:     return sampled_responses
879: 
880: 
881: def get_number_of_solved_tasks_bis(dict_response, n_best_codes=2,c=1000,mv=True,N=-1):
882:     """
883:     Calculates the number of solved tasks based on different criteria.
884: 
885:     test_task_solved_real: Number of tasks solved by taking at most n_best_codes with the most correct train input-outputs
886:     and checking if they solve test examples.
887: 
888:     test_task_solved_oracle: Number of tasks solved, only checking test input-output pairs.
889: 
890:     train_task_solved_oracle: Number of tasks solved, only checking train input-output pairs.
891: 
892:     test_task_solved_with_all_train_correct: Number of tasks solved with all train input-output pairs correct and all test output correct.
893:     """
894:     test_task_solved_real_kaggle_mv = 0
895:     test_task_solved_oracle = 0
896:     train_task_solved_oracle = 0
897:     test_task_solved_oracle_kaggle=0
898:     test_task_solved_with_all_train_correct = 0
899:     n_responses = len(list(dict_response.values())[0])
900:     flage_mv=True
901:     for k,task_responses in dict_response.items():
902:         n_responses = max(n_responses,len(task_responses))
903:         if N != -1: 
904:             task_responses = task_responses[:N]
905: 
906:         try:
907:             if mv:
908:                 best_responses_mv=give_n_majority_vote_v2(task_responses, n_output=n_best_codes,c=c)
909:                 test_task_solved_real_kaggle_mv += define_correct_kaggle(best_responses_mv)[0]
910:         except Exception as e:
911:             if flage_mv:
912:                 print("error mv", e)
913:             flage_mv=False
914:    
915:         if any(all(response["correct_test_input"]) for response in task_responses):
916:             test_task_solved_oracle += 1
917: 
918:         test_task_solved_oracle_kaggle += define_correct_kaggle(task_responses)[0]
919: 
920:         if any(all(response["correct_train_input"]) for response in task_responses):
921:             train_task_solved_oracle += 1
922: 
923:         if any(all(response["correct_train_input"]) and all(response["correct_test_input"]) for response in task_responses):
924:             test_task_solved_with_all_train_correct += 1
925: 
926:     dic_all_res={
927:         "n_tasks": len(dict_response),
928:         "n_responses":n_responses,
929:         "test_task_solved_real_kaggle_mv": test_task_solved_real_kaggle_mv,
930:         "test_task_solved_oracle": test_task_solved_oracle, # Number of tasks solved, only checking test input-output pairs.
931:         "train_task_solved_oracle": train_task_solved_oracle, # Number of tasks solved, only checking train input-output pairs.
932:         "test_task_solved_oracle_kaggle": test_task_solved_oracle_kaggle,
933:         "test_task_solved_with_all_train_correct": test_task_solved_with_all_train_correct # Number of tasks solved with all train input-output pairs correct and all test output correct.
934:     }
935:     return dic_all_res
936: 
937: 
938: def get_info(dic_res,list_key_print=None):
939:     for k,v in dic_res.items():
940:         if list_key_print is None or k in list_key_print:
941:             print(k," :",v)
942: 
943: def define_correct_kaggle(task_responses):
944:     if len(task_responses)==0:
945:         return 0,0  
946:         
947:     len_test = len(task_responses[0]["correct_test_input"])
948:     correctness=[]
949:     for id_test in range(len_test):
950:         correctness.append(any(response["correct_test_input"][id_test] for response in task_responses))
951:     return np.mean(correctness),len_test
952: 
953: 
954: def give_n_majority_vote(task_responses, n_output=2,c=1000):
955:     len_test = len(task_responses[0]["predicted_test_output"])