-
Notifications
You must be signed in to change notification settings - Fork 3
feat: support JSON schema #63
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
e007f0f
feat: support JSON schema
njzjz 9e820e7
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 103da40
fix typing
njzjz 2c6a79c
add tests for _convert_types
njzjz 84a16e1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 88a2a3c
allow $schema
njzjz 047a4ec
handle Variant choice alias
njzjz 7697058
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,158 @@ | ||
"""Generate JSON schema from a given dargs.Argument.""" | ||
|
||
from __future__ import annotations | ||
|
||
from typing import Any | ||
|
||
from dargs.dargs import Argument, _Flags | ||
|
||
try: | ||
from typing import get_origin | ||
except ImportError: | ||
from typing_extensions import get_origin | ||
|
||
|
||
def generate_json_schema(argument: Argument, id: str = "") -> dict: | ||
"""Generate JSON schema from a given dargs.Argument. | ||
|
||
Parameters | ||
---------- | ||
argument : Argument | ||
The argument to generate JSON schema. | ||
id : str, optional | ||
The URL of the schema, by default "". | ||
|
||
Returns | ||
------- | ||
dict | ||
The JSON schema. Use :func:`json.dump` to save it to a file | ||
or :func:`json.dumps` to get a string. | ||
|
||
Examples | ||
-------- | ||
Dump the JSON schema of DeePMD-kit to a file: | ||
|
||
>>> from dargs.json_schema import generate_json_schema | ||
>>> from deepmd.utils.argcheck import gen_args | ||
>>> import json | ||
>>> from dargs import Argument | ||
>>> a = Argument("DeePMD-kit", dtype=dict, sub_fields=gen_args()) | ||
>>> schema = generate_json_schema(a) | ||
>>> with open("deepmd.json", "w") as f: | ||
... json.dump(schema, f, indent=2) | ||
""" | ||
schema = { | ||
"$schema": "https://json-schema.org/draft/2020-12/schema", | ||
"$id": id, | ||
"title": argument.name, | ||
**_convert_single_argument(argument), | ||
} | ||
return schema | ||
|
||
|
||
def _convert_single_argument(argument: Argument) -> dict: | ||
"""Convert a single argument to JSON schema. | ||
|
||
Parameters | ||
---------- | ||
argument : Argument | ||
The argument to convert. | ||
|
||
Returns | ||
------- | ||
dict | ||
The JSON schema of the argument. | ||
""" | ||
data = { | ||
"description": argument.doc, | ||
"type": list({_convert_types(tt) for tt in argument.dtype}), | ||
} | ||
if argument.default is not _Flags.NONE: | ||
data["default"] = argument.default | ||
properties = { | ||
**{ | ||
nn: _convert_single_argument(aa) | ||
for aa in argument.sub_fields.values() | ||
for nn in (aa.name, *aa.alias) | ||
}, | ||
**{ | ||
vv.flag_name: { | ||
"type": "string", | ||
"enum": list(vv.choice_dict.keys()) + list(vv.choice_alias.keys()), | ||
"default": vv.default_tag, | ||
"description": vv.doc, | ||
} | ||
for vv in argument.sub_variants.values() | ||
}, | ||
} | ||
required = [ | ||
aa.name | ||
for aa in argument.sub_fields.values() | ||
if not aa.optional and not aa.alias | ||
] + [vv.flag_name for vv in argument.sub_variants.values() if not vv.optional] | ||
allof = [ | ||
{ | ||
"if": { | ||
"oneOf": [ | ||
{ | ||
"properties": {vv.flag_name: {"const": kkaa}}, | ||
} | ||
for kkaa in (kk, *aa.alias) | ||
], | ||
"required": [vv.flag_name] | ||
if not (vv.optional and vv.default_tag == kk) | ||
else [], | ||
}, | ||
"then": _convert_single_argument(aa), | ||
} | ||
for vv in argument.sub_variants.values() | ||
for kk, aa in vv.choice_dict.items() | ||
] | ||
allof += [ | ||
{"oneOf": [{"required": [nn]} for nn in (aa.name, *aa.alias)]} | ||
for aa in argument.sub_fields.values() | ||
if not aa.optional and aa.alias | ||
] | ||
if not argument.repeat: | ||
data["properties"] = properties | ||
data["required"] = required | ||
if allof: | ||
data["allOf"] = allof | ||
else: | ||
data["items"] = { | ||
"type": "object", | ||
"properties": properties, | ||
"required": required, | ||
} | ||
if allof: | ||
data["items"]["allOf"] = allof | ||
return data | ||
|
||
|
||
def _convert_types(T: type | Any | None) -> str: | ||
"""Convert a type to JSON schema type. | ||
|
||
Parameters | ||
---------- | ||
T : type | Any | None | ||
The type to convert. | ||
|
||
Returns | ||
------- | ||
str | ||
The JSON schema type. | ||
""" | ||
# string, number, integer, object, array, boolean, null | ||
if T is None or T is type(None): | ||
return "null" | ||
elif T is str: | ||
return "string" | ||
elif T in (int, float): | ||
return "number" | ||
elif T is bool: | ||
return "boolean" | ||
elif T is list or get_origin(T) is list: | ||
return "array" | ||
elif T is dict or get_origin(T) is dict: | ||
return "object" | ||
raise ValueError(f"Unknown type: {T}") | ||
njzjz marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
## Generate JSON schema from an argument | ||
|
||
One can use {func}`dargs.json_schema_generate_json_schema` to generate [JSON schema](https://json-schema.org/). | ||
|
||
```py | ||
import json | ||
|
||
from dargs import Argument | ||
from dargs.json_schema import generate_json_schema | ||
from deepmd.utils.argcheck import gen_args | ||
|
||
|
||
a = Argument("DeePMD-kit", dtype=dict, sub_fields=gen_args()) | ||
schema = generate_json_schema(a) | ||
with open("deepmd.json", "w") as f: | ||
json.dump(schema, f, indent=2) | ||
``` | ||
|
||
JSON schema can be used in several JSON editors. For example, in [Visual Studio Code](https://code.visualstudio.com/), you can [configure JSON schema](https://code.visualstudio.com/docs/languages/json#_json-schemas-and-settings) in the project `settings.json`: | ||
|
||
```json | ||
{ | ||
"json.schemas": [ | ||
{ | ||
"fileMatch": [ | ||
"/**/*.json" | ||
], | ||
"url": "./deepmd.json" | ||
} | ||
] | ||
} | ||
``` | ||
|
||
VS Code also allows one to [specify the JSON schema in a JSON file](https://code.visualstudio.com/docs/languages/json#_mapping-in-the-json) with the `$schema` key. | ||
To be compatible, dargs will not throw an error for `$schema` in the strict mode even if `$schema` is not defined in the argument. | ||
|
||
```json | ||
{ | ||
"$schema": "./deepmd.json", | ||
"model": {} | ||
} | ||
``` |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
from __future__ import annotations | ||
|
||
import json | ||
import unittest | ||
|
||
from jsonschema import validate | ||
|
||
from dargs.json_schema import _convert_types, generate_json_schema | ||
|
||
from .dpmdargs import example_json_str, gen_args | ||
|
||
|
||
class TestJsonSchema(unittest.TestCase): | ||
def test_json_schema(self): | ||
args = gen_args() | ||
schema = generate_json_schema(args) | ||
data = json.loads(example_json_str) | ||
validate(data, schema) | ||
|
||
def test_convert_types(self): | ||
self.assertEqual(_convert_types(int), "number") | ||
self.assertEqual(_convert_types(str), "string") | ||
self.assertEqual(_convert_types(float), "number") | ||
self.assertEqual(_convert_types(bool), "boolean") | ||
self.assertEqual(_convert_types(None), "null") | ||
self.assertEqual(_convert_types(type(None)), "null") | ||
self.assertEqual(_convert_types(list), "array") | ||
self.assertEqual(_convert_types(dict), "object") | ||
with self.assertRaises(ValueError): | ||
_convert_types(set) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.