-
Notifications
You must be signed in to change notification settings - Fork 104
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
Inline script metadata #913
Open
ilongin
wants to merge
7
commits into
main
Choose a base branch
from
ilongin/776-inline-script-metadata
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+221
−1
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
8950762
added script meta class to parse script meta information from comment
ilongin 54e528c
added comments
ilongin c0c9d0f
adding unit tests
ilongin aefd129
fixing lint
ilongin 7116fe3
Merge branch 'main' into ilongin/776-inline-script-metadata
ilongin 8f8cbba
updated regex
ilongin 10460e8
added tomli instead of using tomllib
ilongin 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 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 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,116 @@ | ||
import re | ||
from dataclasses import dataclass | ||
from typing import Any, Optional | ||
|
||
import tomli | ||
|
||
|
||
class ScriptMetaParsingError(Exception): | ||
def __init__(self, message): | ||
super().__init__(message) | ||
|
||
|
||
@dataclass | ||
class ScriptMeta: | ||
""" | ||
Class that is parsing inline script metadata to get some basic information for | ||
running datachain script like python version, dependencies, files etc. | ||
Inline script metadata must follow the format described in https://packaging.python.org/en/latest/specifications/inline-script-metadata/#inline-script-metadata. | ||
Example of script with inline metadata: | ||
# /// script | ||
# requires-python = ">=3.12" | ||
# | ||
# dependencies = [ | ||
# "pandas < 2.1.0", | ||
# "numpy == 1.26.4" | ||
# ] | ||
# | ||
# [tools.datachain.workers] | ||
# num_workers = 3 | ||
# | ||
# [tools.datachain.files] | ||
# image1 = "s3://ldb-public/image1.jpg" | ||
# file1 = "s3://ldb-public/file.pdf" | ||
# | ||
# [tools.datachain.params] | ||
# min_length_sec = 1 | ||
# cache = false | ||
# | ||
# /// | ||
|
||
import sys | ||
import pandas as pd | ||
|
||
print(f"Python version: {sys.version_info}") | ||
print(f"Pandas version: {pd.__version__}") | ||
|
||
""" | ||
|
||
python_version: Optional[str] | ||
dependencies: list[str] | ||
files: dict[str, str] | ||
params: dict[str, Any] | ||
num_workers: Optional[int] = None | ||
|
||
def __init__( | ||
self, | ||
python_version: Optional[str] = None, | ||
dependencies: Optional[list[str]] = None, | ||
files: Optional[dict[str, str]] = None, | ||
params: Optional[dict[str, Any]] = None, | ||
num_workers: Optional[int] = None, | ||
): | ||
self.python_version = python_version | ||
self.dependencies = dependencies or [] | ||
self.files = files or {} | ||
self.params = params or {} | ||
self.num_workers = num_workers | ||
|
||
def get_param(self, name: str) -> Any: | ||
return self.params.get(name) | ||
|
||
def get_file(self, name: str) -> Any: | ||
return self.files.get(name) | ||
|
||
@staticmethod | ||
def read_inline_meta(script: str) -> Optional[dict]: | ||
"""Converts inline script metadata to dict with all found data""" | ||
regex = ( | ||
r"(?m)^# \/\/\/ (?P<type>[a-zA-Z0-9-]+)[ \t]*$[\r\n|\r|\n]" | ||
"(?P<content>(?:^#(?:| .*)$[\r\n|\r|\n])+)^# \\/\\/\\/[ \t]*$" | ||
) | ||
name = "script" | ||
matches = list( | ||
filter(lambda m: m.group("type") == name, re.finditer(regex, script)) | ||
) | ||
if len(matches) > 1: | ||
raise ValueError(f"Multiple {name} blocks found") | ||
if len(matches) == 1: | ||
content = "".join( | ||
line[2:] if line.startswith("# ") else line[1:] | ||
for line in matches[0].group("content").splitlines(keepends=True) | ||
) | ||
return tomli.loads(content) | ||
return None | ||
|
||
@staticmethod | ||
def parse(script: str) -> Optional["ScriptMeta"]: | ||
""" | ||
Method that is parsing inline script metadata from datachain script and | ||
instantiating ScriptMeta class with found data. If no inline metadata is | ||
found, it returns None | ||
""" | ||
try: | ||
meta = ScriptMeta.read_inline_meta(script) | ||
if not meta: | ||
return None | ||
custom = meta.get("tools", {}).get("datachain", {}) | ||
return ScriptMeta( | ||
python_version=meta.get("requires-python"), | ||
dependencies=meta.get("dependencies"), | ||
num_workers=custom.get("workers", {}).get("num_workers"), | ||
files=custom.get("files"), | ||
params=custom.get("params"), | ||
) | ||
except Exception as e: | ||
raise ScriptMetaParsingError(f"Error when parsing script meta: {e}") from e |
This file contains 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,103 @@ | ||
import pytest | ||
|
||
from datachain.script_meta import ScriptMeta, ScriptMetaParsingError | ||
|
||
|
||
def test_parsing_all_fields(): | ||
script = """ | ||
# /// script | ||
# requires-python = ">=3.12" | ||
# | ||
# dependencies = [ | ||
# "pandas < 2.1.0", | ||
# "numpy == 1.26.4" | ||
# ] | ||
# | ||
# [tools.datachain.workers] | ||
# num_workers = 3 | ||
# | ||
# [tools.datachain.files] | ||
# image1 = "s3://ldb-public/image1.jpg" | ||
# file1 = "s3://ldb-public/file.pdf" | ||
# | ||
# [tools.datachain.params] | ||
# min_length_sec = 1 | ||
# cache = false | ||
# | ||
# /// | ||
import sys | ||
import pandas as pd | ||
|
||
print(f"Python version: {sys.version_info}") | ||
print(f"Pandas version: {pd.__version__}") | ||
""" | ||
assert ScriptMeta.parse(script) == ScriptMeta( | ||
python_version=">=3.12", | ||
dependencies=["pandas < 2.1.0", "numpy == 1.26.4"], | ||
files={ | ||
"image1": "s3://ldb-public/image1.jpg", | ||
"file1": "s3://ldb-public/file.pdf", | ||
}, | ||
params={"min_length_sec": 1, "cache": False}, | ||
num_workers=3, | ||
) | ||
|
||
|
||
def test_parsing_no_metadata(): | ||
script = """ | ||
import sys | ||
import pandas as pd | ||
|
||
print(f"Python version: {sys.version_info}") | ||
print(f"Pandas version: {pd.__version__}") | ||
""" | ||
|
||
assert ScriptMeta.parse(script) is None | ||
|
||
|
||
def test_parsing_empty(): | ||
script = """ | ||
# /// script | ||
# /// | ||
import sys | ||
import pandas as pd | ||
|
||
print(f"Python version: {sys.version_info}") | ||
print(f"Pandas version: {pd.__version__}") | ||
""" | ||
|
||
assert ScriptMeta.parse(script) is None | ||
|
||
|
||
def test_parsing_only_python_version(): | ||
script = """ | ||
# /// script | ||
# requires-python = ">=3.12" | ||
# /// | ||
import sys | ||
import pandas as pd | ||
|
||
print(f"Python version: {sys.version_info}") | ||
print(f"Pandas version: {pd.__version__}") | ||
""" | ||
assert ScriptMeta.parse(script) == ScriptMeta( | ||
python_version=">=3.12", dependencies=[], files={}, params={}, num_workers=None | ||
) | ||
|
||
|
||
def test_error_when_parsing(): | ||
script = """ | ||
# /// script | ||
# dependencies = [} | ||
# /// | ||
import sys | ||
import pandas as pd | ||
|
||
print(f"Python version: {sys.version_info}") | ||
print(f"Pandas version: {pd.__version__}") | ||
""" | ||
with pytest.raises(ScriptMetaParsingError) as excinfo: | ||
ScriptMeta.parse(script) | ||
assert str(excinfo.value) == ( | ||
"Error when parsing script meta: Invalid value (at line 1, column 17)" | ||
) |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ilongin what is the long term plan for this class?
can we put this information into an existing Query class / table?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Long term plan is to use it for parsing env data from script itself with which we could get rid of that settings UI panel and user could c/p code easier between local and Studio.
I'm not sure what did you mean by putting information into existing Query class. Did you mean
DatasetQuery
? I would keep it like this and use it inCatalog
when we run the scripts.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I see. Sorry, disregard the "put somewhere" part - it's not relevant for now. So, we won't use it atm, right? Should we postpone merging this until we have a clear feature that requires it?
so, is the next step - using this info in Studio and / or CLI (is this code even needed to run it in CLI?) ... I'm just not sure if we should be merging code that we won't use