Skip to content
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
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ dependencies = [
"platformdirs",
"dvc-studio-client>=0.21,<1",
"tabulate",
"websockets"
"websockets",
"tomli"
]

[project.optional-dependencies]
Expand Down
116 changes: 116 additions & 0 deletions src/datachain/script_meta.py
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:
Copy link
Member

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?

Copy link
Contributor Author

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 in Catalog when we run the scripts.

Copy link
Member

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?

with which we could get rid of that settings UI panel and user could c/p code easier between local and Studio.

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

"""
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)

Check warning on line 70 in src/datachain/script_meta.py

View check run for this annotation

Codecov / codecov/patch

src/datachain/script_meta.py#L70

Added line #L70 was not covered by tests

def get_file(self, name: str) -> Any:
return self.files.get(name)

Check warning on line 73 in src/datachain/script_meta.py

View check run for this annotation

Codecov / codecov/patch

src/datachain/script_meta.py#L73

Added line #L73 was not covered by tests

@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")

Check warning on line 87 in src/datachain/script_meta.py

View check run for this annotation

Codecov / codecov/patch

src/datachain/script_meta.py#L87

Added line #L87 was not covered by tests
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
103 changes: 103 additions & 0 deletions tests/unit/test_script_meta.py
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)"
)
Loading