Directory structure: └── mxbi-arckit/ ├── README.md ├── LICENSE ├── pyproject.toml ├── arckit/ │ ├── __init__.py │ ├── cli.py │ ├── data.py │ ├── importtool.py │ └── vis.py └── .github/ └── workflows/ └── pypi.yml ================================================ FILE: README.md ================================================ # arckit [![PyPI version](https://badge.fury.io/py/arckit.svg)](https://badge.fury.io/py/arckit) ![Example visualisation of ARC grids](./images/allgrids10.svg) Python and command-line tools for easily working with the ARC, ARC-AGI & ARC-AGI-2 datasets. ```bash pip install -U arckit ``` Arckit provides tools for loading the data in a friendly format (without a separate download!), visualizing the data with high-quality vector graphics, and evaluating models on the dataset. ✨ **NEW in v1.0:** Added ARC-AGI-2 & ARC Prize 2025 Data, updated evaluation ruleset. ## 🐍 Python API ### Loading the dataset ```python >>> import arckit >>> train_set, eval_set = arckit.load_data() # Load ARC-AGI-2 train/eval. >>> train_set, eval_set = arckit.load_data("kaggle") # Load ARC Prize 2025 >>> train_set, eval_set = arckit.load_data("arcagi") # Load latest ARC-AGI-1 # TaskSets are iterable and indexable >>> train_set >>> train_set[0] # Indexing can be done by task ID >>> train_set[0] == train_set['007bbfb7'] True # You can load specific tasks by ID >>> task = arckit.load_single('007bbfb7') ``` ### Interacting with tasks ```python >>> task.dataset 'train' >>> task.id '007bbfb7' ## Extracting task Grids >>> task.train # o task.test => List[Tuple[ndarray, ndarray]] # of input/output pairs >>> task.train[0][0] # input of 1st train example array([[0, 7, 7], [7, 7, 7], [0, 7, 7]]) # Tasks can be previewed (with colour!) in Python. >>> train_set[15].show() ┏━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━━━━━━━━━┳━━━━━━━━━━━┳━━┳━━━━━━━━┓ ┃ A-in 3x3 ┃ A-out 3x3 ┃ B-in 3x3 ┃ B-out 3x3 ┃ C-in 3x3 ┃ C-out 3x3 ┃ D-in 3x3 ┃ D-out 3x3 ┃ ┃ TA-in ┃ ┡━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━━━━━━━━━╇━━━━━━━━━━━╇━━╇━━━━━━━━┩ │ 3 1 2 │ 4 5 6 │ 2 3 8 │ 6 4 9 │ 5 8 6 │ 1 9 2 │ 9 4 2 │ 8 3 6 │ │ 8 1 3 │ │ 3 1 2 │ 4 5 6 │ 2 3 8 │ 6 4 9 │ 5 8 6 │ 1 9 2 │ 9 4 2 │ 8 3 6 │ │ 8 1 3 │ │ 3 1 2 │ 4 5 6 │ 2 3 8 │ 6 4 9 │ 5 8 6 │ 1 9 2 │ 9 4 2 │ 8 3 6 │ │ 8 1 3 │ └──────────┴───────────┴──────────┴───────────┴──────────┴───────────┴──────────┴───────────┴──┴────────┘ # Get task in original ARC format following fchollet's repo. >>> task.to_dict() => { "id": str, "train": List[{"input": List[List[int]], "output": List[List[int]]}], "test": List[{"input": List[List[int]], "output": List[List[int]]}] } ``` ### Scoring a submission file: To evaluate a submission in [Kaggle ARC format](https://www.kaggle.com/competitions/abstraction-and-reasoning-challenge/overview/evaluation): ```python >>> eval_set.score_submission( 'submission.csv', # Submission with two columns output_id,output in Kaggle fomrat topn=2, # How many predictions to consider (default: 2) return_correct=False # Whether to return a list of which tasks were solved ) ``` > **Note:** the default `topn` was changed from 3 to 2 in v1.0 to match changes in the official evaluation. ### Loading a specific dataset version The ARC-AGI datasets have had [several bugfixes](https://github.com/arcprize/ARC-AGI-2/blob/main/changelog.md) since original release. Additionally, a new ARC-AGI-2 dataset has been released for competitions starting in 2025. By default, the `latest` version of ARC-AGI-2 is loaded, but you can specify a `version` parameter to both `load_data` and `load_single` to load other datasets. **The version options are:** - `latest`, `arcagi2`: The latest version of the ARC-AGI-2 dataset (currently: `f3283f7`) - `arcagi`: The latest version of the ARC-AGI dataset (currently: `aa922be`) - `kaggle`, `kaggle2025`: The data for the 2025 Kaggle competition based on ARC-AGI-2 (currently: `kaggle250808`) - `kaggle2024`: The data for the 2024 Kaggle competition based on ARC-AGI (pinned) - `arc`, `kaggle2019`: The original ARC data, as in the 2019 Kaggle competition (pinned) > **Note:** You may wish to pin your data to a specific version number to avoid underlying data changes during research. To do this, use the most specific name available when loading data, or pin the installed version of `arckit` in your environment. ## 🖼️ Creating visualisations The `arckit.vis` submodule provides useful functions for creating vector graphics visualisations of tasks, using the `drawsvg` module. The docstrings for these functions provide more detailed information as well as additional options. ```python >>> import arckit.vis as vis >>> grid = vis.draw_grid(task.train['2013d3e2'][0], xmax=3, ymax=3, padding=.5, label='Example') >>> vis.output_drawing(grid, "images/grid_example.png") # svg/pdf/png ``` ![Example of arckit visualisation](./images/grid_example.png) When drawing tasks, arckit will intelligently resize all of the grids such that the total size of the illustration does not exceed the chosen width/height. ```python >>> task = vis.draw_task(train_set[0], width=10, height=6, label='Example') >>> vis.output_drawing(task, "images/arcshow_example.png") # svg/pdf/png ``` ![Example of arckit output](./images/arcsave_example.png) Alternatively, the `print_grid` function outputs a grid directly to the terminal without creating any files. ```python >>> task = train_set[0] # Get the first task >>> for i, (input_array, output_array) in enumerate(task.train): # Loop through the training examples >>> print(f"Training Example {i+1}") >>> print("Input:") >>> vis.print_grid(input_array) >>> print("Output:") >>> vis.print_grid(output_array) >>> print() ``` ## 💻 Command-line tools `arcshow` draws a visualisation of a specific task straight to the console: ![Example of arcshow command output (with colours)](./images/arcshow_example.png) `arcsave` saves a visualisation of a specific task to a file (pdf/svg/png), and is useful for inspecting tasks or producing high quality graphics showing specific tasks (e.g. for a paper). Tasks can be specified by their hex ID or by dataset, e.g. `train0`. ```bash usage: arcsave [-h] [--output OUTPUT] task_id width height Save a task to a image file. positional arguments: task_id The task id to save. Can either be a task ID or a string e.g. `train0` width The width of the output image height The height of the output image optional arguments: -h, --help show this help message and exit --output OUTPUT The output file to save to. Must end in .svg/.pdf/.png. By default, pdf is used. ``` ![Example of arcsave command output](./images/arcsave_example.png) ## 💡 Contributions Any relevant contributions are very welcome! Please feel free to open an issue or pull request, or drop me an email if you want to discuss any possible changes. ## 📜 Acknowledgements The ARC and ARC-AGI-2 datasets was graciously released by Francois Chollet under [Apache 2.0](https://github.com/fchollet/ARC/blob/master/LICENSE) and can be found in original format in [these](https://github.com/fchollet/ARC) [repositories](https://github.com/arcprize/ARC-AGI-2). The dataset is reproduced within the `arckit` package under the same license. ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: pyproject.toml ================================================ [build-system] requires = ["setuptools>=61.0", "wheel"] build-backend = "setuptools.build_meta" [project] name = "arckit" version = "1.0.1" # Remember to change in __init__.py description = "Tools for working with the Abstraction & Reasoning Corpus (ARC-AGI)" readme = "README.md" authors = [ {name = "Mikel Bober-Irizar", email = "mikel@mxbi.net"} ] license = "Apache-2.0" requires-python = ">=3.8" keywords = ["arc", "agi", "reasoning", "abstraction"] classifiers = [ "Development Status :: 5 - Production/Stable", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Topic :: Scientific/Engineering :: Artificial Intelligence", ] dependencies = [ "numpy", "rich", "drawsvg", ] [project.urls] Homepage = "https://github.com/mxbi/arckit" Repository = "https://github.com/mxbi/arckit" Issues = "https://github.com/mxbi/arckit/issues" [project.scripts] arctask = "arckit.cli:taskprint" arcsave = "arckit.cli:tasksave" [tool.setuptools.packages.find] include = ["arckit*"] exclude = ["arckit.__pycache__*"] [tool.setuptools.package-data] arckit = ["data/*.json"] [tool.setuptools.exclude-package-data] arckit = ["__pycache__/*", "*.py[co]"] ================================================ FILE: arckit/__init__.py ================================================ from .data import Task, load_data, fmt_grid, load_single from .vis import draw_grid, draw_task, output_drawing __version__ = "1.0.1" __version_info__ = (1, 0, 1) ================================================ FILE: arckit/cli.py ================================================ import sys import argparse from .data import load_single from .vis import draw_task, output_drawing def taskprint(): if len(sys.argv) < 2: print("Usage: arctask ") return task = load_single(sys.argv[1]) task.show() def tasksave(): parser = argparse.ArgumentParser(description='Save a task to a image file.') parser.add_argument('task_id', type=str, help='The task id to save. Can either be a task ID or a string e.g. `train0`') parser.add_argument('width', type=int, help='The width of the output image', default=20) parser.add_argument('height', type=int, help='The height of the output image', default=10) parser.add_argument('--output', type=str, help='The output file to save to. Must end in .svg/.pdf/.png. By default, pdf is used.', default=False, required=False) args = parser.parse_args() task = load_single(args.task_id) drawing = draw_task(task, width=args.width, height=args.height) out_fn = args.output or f'{task.id}_{drawing.width}x{drawing.height}.pdf' print(f'Drawn task {task.id} ({drawing.width}x{drawing.height}), saving to {out_fn}') output_drawing(drawing, out_fn) ================================================ FILE: arckit/data.py ================================================ import json import numpy as np import os import csv from rich import print from rich.panel import Panel from rich.table import Table from rich.text import Text def idx2chr(idx): return chr(idx + 65) def fmt_grid(grid, colour=True, spaces=True): grid_str = [] if not colour: for row in grid: if spaces == 'gpt': grid_str.append(''.join([' ' + str(x) for x in row])) elif spaces: grid_str.append(' '.join([str(x) for x in row])) else: grid_str.append(''.join([str(x) for x in row])) return "\n".join(grid_str) else: if spaces: cmap = dict({i: (str(i) + ' ', f"color({i})") for i in range(10)}, **{str(i): (str(i) + ' ', f"color({i})") for i in range(10)}) else: cmap = dict({i: (str(i), f"color({i})") for i in range(10)}, **{str(i): (str(i), f"color({i})") for i in range(10)}) for row in grid: grid_str += [cmap[digit] for digit in row] grid_str += ["\n"] return Text.assemble(*grid_str[:-1]) class Task: def __init__(self, id, train, test, dataset=None, version=None): self.dataset = dataset self.version = version self.id = id self.train = [(np.array(example['input']), np.array(example['output'])) for example in train] self.test = [(np.array(example['input']), np.array(example['output'])) for example in test] self.color_count = max def __lt__(self, other): return self.id < other.id def __hash__(self): return hash(self.id) @classmethod def from_json(cls, json_file): with open(json_file) as f: data = json.load(f) # train_examples = [(np.array(example['input']), np.array(example['output'])) for example in data['train']] # test_examples = [(np.array(example['input']), np.array(example['output'])) for example in data['test']] return cls(os.path.basename(json_file)[:-5], data['train'], data['test']) def __repr__(self): return f"" def show(self, answer=False): table = Table(title=repr(self), show_lines=True) data = [] for i, (input, output) in enumerate(self.train): data += [fmt_grid(input), fmt_grid(output)] ix, iy = input.shape ox, oy = output.shape table.add_column(f"{idx2chr(i)}-in {ix}x{iy}", justify="center", no_wrap=True) table.add_column(f"{idx2chr(i)}-out {ox}x{oy}", justify="center", no_wrap=True) data.append('') table.add_column("") for i, (input, output) in enumerate(self.test): table.add_column(f"T{idx2chr(i)}-in", justify="center", header_style="bold", no_wrap=True) if answer: table.add_column(f"T{idx2chr(i)}-out", justify="center", header_style="bold", no_wrap=True) data += [fmt_grid(input), fmt_grid(output)] else: data += [fmt_grid(input)] table.add_row(*data) print(table) return table def to_dict(self): return { "id": self.id, "train": [{"input": input.tolist(), "output": output.tolist()} for input, output in self.train], "test": [{"input": input.tolist(), "output": output.tolist()} for input, output in self.test] } def dreamcoder_format(self): # TODO: Separate out the train/test data # Currently, dreamcoder gets to search on the train examples too # This is included to keep compatibility with Simon's results, but should be corrected and written about grids = [] for inp, out in self.train: grids += [inp, out] for inp, out in self.test: grids += [inp, out] return {"name": self.id, "grids": grids} def scoreA(self, output): output = np.array(output).astype(int) if output.shape != self.test[0][1].shape: return False return (output == self.test[0][1]).all() def gpt_prompt(self, i_test, mode="chatgpt", include_completion=False, rot90=False, transpose=False, spaces=True): if mode == "chatgpt": prompt = "We are playing a game which involves transforming an input grid of digits into an output grid of digits. In general, digits form objects in 2D and the task is to perform some spatial transformation of these objects to go from the input grid to the output grid. All the information about the transformation is contained within the input pairs themselves, and your answer will only be correct if the output grid is exactly correct, so this is what I expect from you. I will begin by giving you several examples of input-output pairs. You will then be given a new input grid, and you must provide the corresponding output grid.\n" elif mode == "gpt3": # prompt = "We are playing a game which involves transforming an input grid of digits into an output grid of digits. Every below pair of grids contains the same transformation. In general, digits form objects in 2D and the task is to perform some spatial transformation of these objects to go from the input tile to the output tile. One such example of tiles is below.\n" prompt = "We are playing a game which involves transformaing a 2D input grid of digits into an output grid of digits. Every below pair of grids contains the same transformation (e.g. rotation, symmetry, manipulation of objects). Each Input grid is followed by an Output grid which applies the same transformation as previous Input/Output pairs. One such example is below.\n" else: raise ValueError(f"Unknown mode: {mode}") i = 1 for input, output in self.train: if rot90: input = np.rot90(input) output = np.rot90(output) if transpose: input = np.transpose(input) output = np.transpose(output) prompt += f"""Input {i}: {fmt_grid(input, colour=False, spaces=spaces)} Output {i}: {fmt_grid(output, colour=False, spaces=spaces)}\n """ i += 1 test_grid = self.test[i_test][0] if rot90: test_grid = np.rot90(test_grid) if transpose: test_grid = np.transpose(test_grid) prompt += f"Input {i}:\n" prompt += f"{fmt_grid(test_grid, colour=False, spaces=spaces)}" if mode == "gpt3": prompt += f"\nOutput {i}:" else: prompt += f"\nOutput {i}: (please provide the output grid only)\n" if include_completion: if rot90: output = np.rot90(self.test[i_test][1]) if transpose: output = np.transpose(self.test[i_test][1]) prompt += f"\n{fmt_grid(self.test[i_test][1], colour=False, spaces=spaces)}" return prompt class TaskSet: def __init__(self, tasks): tasks = sorted(tasks) self.tasks = tasks self.task_dict = {task.id: task for task in tasks} def __getitem__(self, item): if isinstance(item, slice): return TaskSet(self.tasks[item]) get = self.task_dict.get(item) if get is None: try: return self.tasks[item] except (TypeError, IndexError): raise KeyError(f"Task {item} not found") return get def __len__(self): return len(self.tasks) def __iter__(self): return iter(self.tasks) def __repr__(self): return f"" def score_submission(self,fn: str, topn=2, return_correct=False) -> int: """ Score a submission file, in Kaggle csv format Two columns: output_id,output """ from collections import defaultdict preds = defaultdict(list) with open(fn) as f: reader = csv.DictReader(f) for row in reader: task_id, test_num = row['output_id'].split('_') test_num = int(test_num) assert test_num == len(preds[task_id]), f'Predictions must be in order' # Predictions must be in order row_preds = row['output'].strip().split(' ') row_preds = row_preds[:topn] # max 3 preds try: array_preds = [] for p in row_preds: p = p.strip('|').split('|') p = [[int(x) for x in row] for row in p] array_preds.append(np.array(p)) except: raise ValueError(f'Could not parse prediction: {row_preds}') preds[task_id].append(array_preds) total_score = 0 correct = set() for task in self.tasks: test_examples = task.test assert len(test_examples) == len(preds[task.id]) score = 0 for ex, ex_preds in zip(test_examples, preds[task.id]): if any([np.array_equal(ex[1], pred) for pred in ex_preds]): score += 1 if score == len(test_examples): total_score += 1 correct.add(task.id) if return_correct: return total_score, correct else: return total_score def get_data_json(version): version = version.lower() if version in ['latest', 'arcagi2', 'f3283f7']: return json.load(open(f"{os.path.dirname(__file__)}/data/arcagi2_f3283f7.json")) elif version in ['arcagi', 'aa922be', 'arcagi1', 'arc-agi-1', 'arc-agi']: return json.load(open(f"{os.path.dirname(__file__)}/data/arcagi_aa922be.json")) elif version in ['kaggle', 'kaggle2025', 'kaggle250808']: return json.load(open(f"{os.path.dirname(__file__)}/data/kaggle2025_250808.json")) elif version in ['kaggle2024']: return json.load(open(f"{os.path.dirname(__file__)}/data/kaggle2024.json")) elif version in ['arc', 'kaggle2019']: return json.load(open(f"{os.path.dirname(__file__)}/data/arc1.json")) else: raise ValueError(f"Unknown ARC dataset version: {version}") def load_data(version='latest') -> tuple[TaskSet, TaskSet]: """ Load the ARC dataset from disk. Optionally, specify a specific version of the dataset to load. """ data = get_data_json(version) train_tasks = [] eval_tasks = [] for id, task in data['train'].items(): train_tasks.append(Task(id, task['train'], task['test'], 'train', version=version)) for id, task in data['eval'].items(): eval_tasks.append(Task(id, task['train'], task['test'], 'eval', version=version)) return TaskSet(train_tasks), TaskSet(eval_tasks) def load_single(id: str, version='latest') -> Task: """ Load a single task from disk. IDs are of the form 'train0', 'eval14', '007bbfb7', etc. Note that if iterating through tasks, it is more efficient to use load_data() and index into it. Optionally, specify a specific version of the dataset to load. """ data = get_data_json(version) # task = data['train'][id] # return Task(id, task['train'], task['test'], 'train' if id.startswith('train'): dataset_tasks = sorted(data['train'].items()) taskid, task = dataset_tasks[int(id[5:])] return Task(taskid, task['train'], task['test'], 'train', version=version) elif id.startswith('eval'): dataset_tasks = sorted(data['eval'].items()) taskid, task = dataset_tasks[int(id[4:])] return Task(taskid, task['train'], task['test'], 'eval', version=version) elif id in data['train']: task = data['train'][id] return Task(id, task['train'], task['test'], 'train', version=version) elif id in data['eval']: task = data['eval'][id] return Task(id, task['train'], task['test'], 'eval', version=version) else: raise ValueError(f"Unknown task id: {id}") if __name__ == "__main__": train_tasks, eval_tasks = load_data() print(train_tasks) print(eval_tasks) print(train_tasks["007bbfb7"]) for i in range(10): train_tasks[i].show() print(train_tasks["08ed6ac7"].gpt_prompt("gpt3")) ================================================ FILE: arckit/importtool.py ================================================ import glob import ujson # dumps minified by default import os import argparse def import_arc_agi_2(repo_path, commit_hash): train_files = sorted(glob.glob(f'{repo_path}/data/training/*.json')) eval_files = sorted(glob.glob(f'{repo_path}/data/evaluation/*.json')) print(f"Found {len(train_files)} train tasks, {len(eval_files)} eval tasks") data = {"train": {}, "eval": {}} for json_file in train_files: taskname = os.path.basename(json_file).split('.')[0] taskdata = ujson.load(open(json_file)) data['train'][taskname] = taskdata for json_file in eval_files: taskname = os.path.basename(json_file).split('.')[0] taskdata = ujson.load(open(json_file)) data['eval'][taskname] = taskdata output_path = f"{os.path.dirname(__file__)}/data/arcagi2_{commit_hash}.json" ujson.dump(data, open(output_path, "w")) def import_kaggle_2025(repo_path, id): train_challenges = ujson.load(open(f'{repo_path}/arc-agi_training_challenges.json', 'r')) eval_challenges = ujson.load(open(f'{repo_path}/arc-agi_evaluation_challenges.json', 'r')) train_solutions = ujson.load(open(f'{repo_path}/arc-agi_training_solutions.json', 'r')) eval_solutions = ujson.load(open(f'{repo_path}/arc-agi_evaluation_solutions.json', 'r')) # Populate the solutions into the challenges train_data = {} for challenge, challenge_data in train_challenges.items(): challenge_test = train_solutions[challenge] for i, test in enumerate(challenge_test): challenge_data['test'][i]['output'] = test train_data[challenge] = challenge_data eval_data = {} for challenge, challenge_data in eval_challenges.items(): challenge_test = eval_solutions[challenge] for i, test in enumerate(challenge_test): challenge_data['test'][i]['output'] = test eval_data[challenge] = challenge_data data = {"train": train_data, "eval": eval_data} output_path = f"{os.path.dirname(__file__)}/data/kaggle2025_{id}.json" ujson.dump(data, open(output_path, "w")) def compare_json(json1="arckit/data/kaggle2025_250808.json", json2="arckit/data/arcagi2_f3283f7.json"): json1 = ujson.load(open(json1, "r")) json2 = ujson.load(open(json2, "r")) assert len(json1['train']) == len(json2['train']) assert len(json1['eval']) == len(json2['eval']) for k, v in json1['train'].items(): if k not in json2['train']: print(k, "missing") if str(json2['train'][k]) != str(v): print(k, "not matching") for k, v in json2['eval'].items(): if k not in json1['eval']: print(k, "missing") if str(json1['eval'][k]) != str(v): print(k, "not matching") exit() if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--arcagi2', action="store_true") parser.add_argument('--kaggle2025', action="store_true") parser.add_argument('--repo-path') parser.add_argument('--id') args = parser.parse_args() if args.arcagi2: import_arc_agi_2(args.repo_path, args.id) elif args.kaggle2025: import_kaggle_2025(args.repo_path, args.id) else: print("Unknown importer.") ================================================ FILE: arckit/vis.py ================================================ import drawsvg import numpy as np import io import rich cmap = [ '#252525', # black '#0074D9', # blue '#FF4136', # red '#37D449', #2ECC40', # green '#FFDC00', # yellow '#E6E6E6', # grey '#F012BE', # pink '#FF871E', # orange '#54D2EB', #7FDBFF', # light blue '#8D1D2C',#870C25', # brown '#FFFFFF' ] bg_color = '#EEEFF6' # White def draw_grid(grid, xmax=10, ymax=10, padding=.5, extra_bottom_padding=0.5, group=False, add_size=True, label='', bordercol='#111111ff'): """ Draws a grid, Parameters ---------- grid : np.ndarray The grid to draw xmax : float, optional The maximum horizontal size of the drawing, by default 10 ymax : float, optional The maximum vertical size of the drawing, by default 10 padding : float, optional The padding around the grid, half on each side, by default .5 extra_bottom_padding : float, optional Extra padding at the bottom of the drawing, by default 0.5 This is used to draw the label group : bool, optional If enabled, return a drawsvg.Group to include within a bigger drawing Otherwise, return a drawsvg.Drawing (default) label : str, optional A label to draw at the bottom left of the drawing, by default '' This does not affect drawing of the size. bordercol : str, optional The colour of the border, by default '#111111ff' """ # Size is the total size of the LARGER axis. # With 0.5 cell padding, we consider the grid to be 1 unit larger than the number of cells # padding *= size # padding is proportional gridy, gridx = grid.shape # Calculate cell size based on the two restrictions # The actual cell size is the minimum of the two cellsize_x = xmax / gridx cellsize_y = ymax / gridy cellsize = min(cellsize_x, cellsize_y) xsize = gridx * cellsize ysize = gridy * cellsize line_thickness = 0.01 circle_radius = 0 border_width = 0.08 lt = line_thickness / 2 if group: drawing = drawsvg.Group() else: drawing = drawsvg.Drawing(xsize+padding, ysize+padding+extra_bottom_padding, origin=(-0.5*padding, -0.5*padding)) # Add background rectangle first drawing.append(drawsvg.Rectangle( -0.5*padding, -0.5*padding, # x, y position with extra padding xsize+padding, ysize+padding+extra_bottom_padding, # width, height with padding fill=bg_color # background color `bg_color` )) drawing.set_pixel_scale(40) # drawing = drawsvg.Group() for j, row in enumerate(grid): for i, cell in enumerate(row): drawing.append(drawsvg.Rectangle(i*cellsize+lt, j*cellsize+lt, cellsize-lt, cellsize-lt, fill=cmap[cell])) # white dot at each vertex if circle_radius > 0: for i in range(1, gridx): for j in range(1, gridy): drawing.append(drawsvg.Circle(i*cellsize, j*cellsize, circle_radius, fill='white')) # Add a border bw = border_width / 3 # slightly more than 2 to avoid white border drawing.append(drawsvg.Rectangle(-bw, -bw, xsize+bw*2, ysize+bw*2, fill='none', stroke=bordercol, stroke_width=border_width)) if not group: drawing.embed_google_font('Anuphan:wght@400;600;700', text=set(f'Input Output 0123456789x Test Task ABCDEFGHIJ? abcdefghjklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ')) # Write size on the bottom right # drawing.append(drawsvg.Text(text=f'{gridx}x{gridy}', x=-0.05, y=-0.25, font_size=padding/4, fill='black', text_anchor='start')) fontsize = (padding/2 + extra_bottom_padding)/2 if add_size: drawing.append(drawsvg.Text(text=f'{gridx}x{gridy}', x=xsize, y=ysize+fontsize*1.25+0, font_size=fontsize, fill='black', text_anchor='end', font_family='Anuphan')) if label: drawing.append(drawsvg.Text(text=label, x=-0.1*fontsize, y=ysize+fontsize*1.25+0, font_size=fontsize, fill='black', text_anchor='start', font_family='Anuphan', font_weight='600')) if group: # return group, origin, (xsize, ysize) return drawing, (-0.5*padding, -0.5*padding), (xsize+padding, ysize+padding+extra_bottom_padding) return drawing def draw_task(task, width=30, height=12, include_test=False, label=True, bordercols=['#111111ff', '#111111ff'], shortdesc=False): """ Plot an entire task vertically, fitting the desired dimensions. The output is displayed below the input, with an arrow in between. Note that dimensions are a best effort, you should check .width and .height on the output Parameters ---------- task : Task The task to plot width : float, optional The desired width of the drawing, by default 30 height : float, optional The desired height of the drawing, by default 12 include_test : bool, optional If enabled, include the test examples in the plot, by default False If set to 'all', ALSO include the output of the test examples label: bool, default True bordercols: list of str, default None """ padding = 0.5 bonus_padding = 0.25 io_gap = 0.4 ymax = (height - padding - bonus_padding - io_gap)/2 if include_test: examples = task.train + task.test else: examples = task.train n_train = len(task.train) paddingless_width = width - padding * len(examples) max_widths = np.zeros(len(examples)) # If any examples would exceed the height restriction, scale their width down and redistribute the space for i, (input_grid, output_grid) in enumerate(examples): input_grid_ratio = input_grid.shape[1] / input_grid.shape[0] output_grid_ratio = output_grid.shape[1] / output_grid.shape[0] max_ratio = max(input_grid_ratio, output_grid_ratio) # could be min xmax = ymax * max_ratio max_widths[i] = xmax # Allocate paddingless width to each example allocation = np.zeros_like(max_widths) increment = 0.01 for i in range(int(paddingless_width//increment)): incr = (allocation + increment) <= max_widths allocation[incr] += increment / incr.sum() drawlist = [] x_ptr = 0 y_ptr = 0 for i, (input_grid, output_grid) in enumerate(examples): if shortdesc: if i >= n_train: input_label = ''#f'T{i-n_train+1}' output_label = ''#f'T{i-n_train+1}' else: input_label = ''#f'I{i+1}' output_label = ''#f'O{i+1}' else: if i >= n_train: input_label = f'Test {i-n_train+1}' output_label = f'Test {i-n_train+1}' else: input_label = f'Input {i+1}' output_label = f'Output {i+1}' # input_label, output_label = '', '' input_grid, offset, (input_x, input_y) = draw_grid(input_grid, padding=padding, xmax=allocation[i], ymax=ymax, group=True, label=input_label, extra_bottom_padding=0.5, bordercol=bordercols[0]) output_grid, offset, (output_x, output_y) = draw_grid(output_grid, padding=padding, xmax=allocation[i], ymax=ymax, group=True, label=output_label, extra_bottom_padding=0.5, bordercol=bordercols[1]) drawlist.append(drawsvg.Use(input_grid, x=x_ptr + (allocation[i]+padding-input_x)/2 - offset[0], y=-offset[1])) # drawlist.append(drawsvg.Use(output_grid, x=x_ptr + (allocation[i]+padding-output_x)/2 - offset[0], y=ymax-offset[1]+2)) x_ptr += max(input_x, output_x) y_ptr = max(y_ptr, input_y) x_ptr = 0 y_ptr2 = 0 for i, (input_grid, output_grid) in enumerate(examples): if shortdesc: if i >= n_train: input_label = ''#f'T{i-n_train+1}' output_label = ''#f'T{i-n_train+1}' else: input_label = ''#f'I{i+1}' output_label = ''#f'O{i+1}' else: if i >= n_train: input_label = f'Test {i-n_train+1}' output_label = f'Test {i-n_train+1}' else: input_label = f'Input {i+1}' output_label = f'Output {i+1}' # input_label, output_label = '', '' input_grid, offset, (input_x, input_y) = draw_grid(input_grid, padding=padding, xmax=allocation[i], ymax=ymax, group=True, label=input_label, extra_bottom_padding=0.5, bordercol=bordercols[0]) output_grid, offset, (output_x, output_y) = draw_grid(output_grid, padding=padding, xmax=allocation[i], ymax=ymax, group=True, label=output_label, extra_bottom_padding=0.5, bordercol=bordercols[1]) # Down arrow drawlist.append(drawsvg.Line( x_ptr + input_x/2, y_ptr + padding - 0.6, x_ptr + input_x/2, y_ptr + padding + io_gap - 0.6, stroke_width=0.05, stroke='#888888')) drawlist.append(drawsvg.Line( x_ptr + input_x/2 - 0.15, y_ptr + padding + io_gap - 0.8, x_ptr + input_x/2, y_ptr + padding + io_gap - 0.6, stroke_width=0.05, stroke='#888888')) drawlist.append(drawsvg.Line( x_ptr + input_x/2 + 0.15, y_ptr + padding + io_gap - 0.8, x_ptr + input_x/2, y_ptr + padding + io_gap - 0.6, stroke_width=0.05, stroke='#888888')) if i < n_train or include_test == 'all': drawlist.append(drawsvg.Use(output_grid, x=x_ptr + (allocation[i]+padding-output_x)/2 - offset[0], y=y_ptr-offset[1]+io_gap)) else: # Add a question mark drawlist.append(drawsvg.Text( '?', x=x_ptr + (allocation[i]+padding)/2, y=y_ptr + output_y/2+bonus_padding, font_size=1, font_family='Anuphan', font_weight='700', fill='#333333', text_anchor='middle', alignment_baseline='middle', )) x_ptr += max(input_x, output_x) y_ptr2 = max(y_ptr2, y_ptr+output_y+io_gap) x_ptr = round(x_ptr, 1) y_ptr2 = round(y_ptr2, 1) d = drawsvg.Drawing(x_ptr, y_ptr2+0.2, origin=(0, 0)) d.append(drawsvg.Rectangle(0, 0, '100%', '100%', fill='#eeeff6')) d.embed_google_font('Anuphan:wght@400;600;700', text=set(f'Input Output 0123456789x Test Task ABCDEFGHIJ? abcdefghjklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ')) for item in drawlist: d.append(item) fontsize=0.3 d.append(drawsvg.Text(f"Task {task.id}", x=x_ptr-0.1, y=y_ptr2+0.1, font_size=fontsize, font_family='Anuphan', font_weight='600', fill='#666666', text_anchor='end', alignment_baseline='bottom')) d.set_pixel_scale(40) return d def output_drawing(d: drawsvg.Drawing, filename: str, context=None): if filename.endswith('.svg'): d.save_svg(filename) elif filename.endswith('.png'): d.save_png(filename) elif filename.endswith('.pdf'): buffer = io.StringIO() d.as_svg(output_file=buffer, context=context) import cairosvg cairosvg.svg2pdf(bytestring=buffer.getvalue(), write_to=filename) else: raise ValueError(f'Unknown file extension for {filename}') def print_grid(grid: np.ndarray): """ Print a grid to the terminal using rich library Parameters ---------- grid : np.ndarray the standard grid format for Task """ CELL_WIDTH = 2 def get_color(color_str): color_str = color_str.strip('#') return rich.color.Color.from_rgb(*bytes.fromhex(color_str)) # Translate 'cmap' to rich style with respective color as background rich_scmap = { i: rich.style.Style(bgcolor=get_color(color)) for i, color in enumerate(cmap) } # Create and populate rich table table = rich.table.Table.grid(expand=False) height, width = grid.shape # Add columns for x in range(width): table.add_column() table.columns[x]._cells = [''] * height table.rows = [rich.table.Row()] * height # Populate cells for y in range(height): for x in range(width): color_idx = grid[y, x] table.columns[x]._cells[y] = rich.text.Text(' ' * CELL_WIDTH, style=rich_scmap[color_idx]) rich.print(table) ================================================ FILE: .github/workflows/pypi.yml ================================================ name: Build & Release on: workflow_dispatch: inputs: environment: description: 'Choose PyPI environment' required: true default: 'test' type: choice options: - test - production push: jobs: build: name: Build wheel runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: ${{ inputs.python_version || '3.11' }} - name: Install build backend run: | python -m pip install --upgrade pip python -m pip install build - name: Build dists run: | python -m build - name: Upload dists artifact uses: actions/upload-artifact@v4 with: name: dist path: dist/ publish: name: Publish to PyPI needs: build runs-on: ubuntu-latest permissions: id-token: write if: github.event_name == 'workflow_dispatch' steps: - name: Download dists artifact uses: actions/download-artifact@v4 with: name: dist path: dist/ - name: Publish to TestPyPI if: inputs.environment == 'test' uses: pypa/gh-action-pypi-publish@release/v1 with: repository-url: https://test.pypi.org/legacy/ - name: Publish to Production PyPI if: inputs.environment == 'production' uses: pypa/gh-action-pypi-publish@release/v1