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
chore: tidy up excel2lists, excel2resources, excel2properties (DEV-1352) #229
Merged
Merged
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
46c5ce7
edit
jnussbaum 76a78c3
fix openpyxl type annotations
jnussbaum 794ec99
improve unittests
jnussbaum 7b63827
improve unittests
jnussbaum 73782f3
adapt output format: return and save always as list[dict[str, Any]]
jnussbaum f4b3a32
fix e2e test
jnussbaum 46ababa
adapt reviewer's feedback
jnussbaum 867f74b
fix
jnussbaum File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
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,54 @@ | ||
import dataclasses | ||
from typing import Union, Optional | ||
import pandas as pd | ||
import regex | ||
from knora.dsplib.models.helpers import BaseError | ||
|
||
|
||
@dataclasses.dataclass(frozen=True) | ||
jnussbaum marked this conversation as resolved.
Show resolved
Hide resolved
|
||
class PropertyElement: | ||
""" | ||
A PropertyElement object carries more information about a property value than the value itself. | ||
The "value" is the value that could be passed to a method as plain string/int/float/bool. Use a PropertyElement | ||
instead to define more precisely what attributes your <text> tag (for example) will have. | ||
|
||
Args: | ||
value: This is the content that will be written between the <text></text> tags (for example) | ||
permissions: This is the permissions that your <text> tag (for example) will have | ||
comment: This is the comment that your <text> tag (for example) will have | ||
encoding: For <text> tags only. Can be "xml" or "utf8". | ||
jnussbaum marked this conversation as resolved.
Show resolved
Hide resolved
jnussbaum marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
Examples: | ||
See the difference between the first and the second example: | ||
|
||
>>> make_text_prop(":testproperty", "first text") | ||
<text-prop name=":testproperty"> | ||
<text encoding="utf8" permissions="prop-default"> | ||
first text | ||
</text> | ||
</text-prop> | ||
>>> make_text_prop(":testproperty", PropertyElement("first text", permissions="prop-restricted", encoding="xml")) | ||
<text-prop name=":testproperty"> | ||
<text encoding="xml" permissions="prop-restricted"> | ||
first text | ||
</text> | ||
</text-prop> | ||
""" | ||
value: Union[str, int, float, bool] | ||
permissions: str = "prop-default" | ||
comment: Optional[str] = None | ||
jnussbaum marked this conversation as resolved.
Show resolved
Hide resolved
|
||
encoding: Optional[str] = None | ||
jnussbaum marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
def __post_init__(self) -> None: | ||
if not any([ | ||
isinstance(self.value, int), | ||
isinstance(self.value, float) and pd.notna(self.value), # necessary because isinstance(np.nan, float) | ||
isinstance(self.value, bool), | ||
isinstance(self.value, str) and all([ | ||
regex.search(r"\p{L}|\d|_", self.value, flags=regex.UNICODE), | ||
not bool(regex.search(r"^(none|<NA>|-|n/a)$", self.value, flags=regex.IGNORECASE)) | ||
]) | ||
]): | ||
raise BaseError(f"'{self.value}' is not a valid value for a PropertyElement") | ||
if self.encoding not in ["utf8", "xml", None]: | ||
raise BaseError(f"'{self.encoding}' is not a valid encoding for a PropertyElement") |
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 |
---|---|---|
|
@@ -3,7 +3,6 @@ | |
import json | ||
import os | ||
import re | ||
import unicodedata | ||
from typing import Any, Union, Optional, Tuple | ||
|
||
import jsonschema | ||
|
@@ -13,6 +12,7 @@ | |
import regex | ||
|
||
from knora.dsplib.models.helpers import BaseError | ||
from knora.dsplib.utils.shared_methods import simplify_name | ||
jnussbaum marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
list_of_lists_of_previous_cell_values: list[list[str]] = [] | ||
"""Module level variable used to ensure that there are no duplicate node names""" | ||
|
@@ -236,30 +236,6 @@ def _make_json_lists_from_excel(excel_file_paths: list[str], verbose: bool = Fal | |
return finished_lists | ||
|
||
|
||
def simplify_name(value: str) -> str: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. moved to shared_methods.py |
||
""" | ||
Simplifies a given value in order to use it as node name | ||
|
||
Args: | ||
value: The value to be simplified | ||
|
||
Returns: | ||
str: The simplified value | ||
""" | ||
simplified_value = str(value).lower() | ||
|
||
# normalize characters (p.ex. ä becomes a) | ||
simplified_value = unicodedata.normalize("NFKD", simplified_value) | ||
|
||
# replace forward slash and whitespace with a dash | ||
simplified_value = re.sub("[/\\s]+", "-", simplified_value) | ||
|
||
# delete all characters which are not letters, numbers or dashes | ||
simplified_value = re.sub("[^A-Za-z0-9\\-]+", "", simplified_value) | ||
|
||
return simplified_value | ||
|
||
|
||
def validate_lists_section_with_schema( | ||
path_to_json_project_file: Optional[str] = None, | ||
lists_section: Optional[list[dict[str, Any]]] = None | ||
|
@@ -273,7 +249,7 @@ def validate_lists_section_with_schema( | |
lists_section: the "lists" section as Python object | ||
|
||
Returns: | ||
True if the list passed validation. Otherwise, a BaseError with a detailed error report is raised | ||
True if the "lists" section passed validation. Otherwise, a BaseError with a detailed error report is raised | ||
""" | ||
if bool(path_to_json_project_file) == bool(lists_section): | ||
raise BaseError("Validation of the 'lists' section works only if exactly one of the two arguments is given.") | ||
|
@@ -283,12 +259,12 @@ def validate_lists_section_with_schema( | |
if path_to_json_project_file: | ||
with open(path_to_json_project_file) as f: | ||
project = json.load(f) | ||
lists_section = project["project"]["lists"] | ||
lists_section = project["project"].get("lists") | ||
|
||
try: | ||
jsonschema.validate(instance={"lists": lists_section}, schema=lists_schema) | ||
except jsonschema.exceptions.ValidationError as err: | ||
raise BaseError(f'"Lists" section did not pass validation. The error message is: {err.message}\n' | ||
raise BaseError(f'"lists" section did not pass validation. The error message is: {err.message}\n' | ||
f'The error occurred at {err.json_path}') | ||
return True | ||
|
||
|
@@ -318,16 +294,16 @@ def _extract_excel_file_paths(excelfolder: str) -> list[str]: | |
return excel_file_paths | ||
|
||
|
||
def list_excel2json(excelfolder: str, outfile: str) -> None: | ||
def excel2lists(excelfolder: str, outfile: str) -> list[dict[str, Any]]: | ||
""" | ||
This method writes a JSON file with a "lists" section that can later be inserted into a JSON project file. | ||
Converts lists described in Excel files into a "lists" section that can be inserted into a JSON project file. | ||
|
||
Args: | ||
excelfolder: path to the folder containing the Excel file(s) | ||
outfile: path to the JSON file the output is written into | ||
|
||
Returns: | ||
None | ||
the "lists" section as Python list | ||
""" | ||
excel_file_paths = _extract_excel_file_paths(excelfolder) | ||
print("The following Excel files will be processed:") | ||
|
@@ -336,5 +312,7 @@ def list_excel2json(excelfolder: str, outfile: str) -> None: | |
validate_lists_section_with_schema(lists_section=finished_lists) | ||
|
||
with open(outfile, "w", encoding="utf-8") as fp: | ||
json.dump({"lists": finished_lists}, fp, indent=4, sort_keys=False, ensure_ascii=False) | ||
print("List was created successfully and written to file:", outfile) | ||
json.dump({"lists": finished_lists}, fp, indent=4, ensure_ascii=False) | ||
print('"lists" section was created successfully and written to file:', outfile) | ||
|
||
return finished_lists |
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
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.
To make excel2xml.py at least a bit shorter, I moved this class here.