2022-09-02 09:58:21 +00:00
|
|
|
import json
|
2023-06-14 15:48:41 +00:00
|
|
|
import platform
|
2017-03-18 12:01:16 +00:00
|
|
|
from pathlib import Path
|
2023-06-14 15:48:41 +00:00
|
|
|
from typing import Any, Dict, List, Optional, Union
|
|
|
|
|
💫 Replace ujson, msgpack and dill/pickle/cloudpickle with srsly (#3003)
Remove hacks and wrappers, keep code in sync across our libraries and move spaCy a few steps closer to only depending on packages with binary wheels 🎉
See here: https://github.com/explosion/srsly
Serialization is hard, especially across Python versions and multiple platforms. After dealing with many subtle bugs over the years (encodings, locales, large files) our libraries like spaCy and Prodigy have steadily grown a number of utility functions to wrap the multiple serialization formats we need to support (especially json, msgpack and pickle). These wrapping functions ended up duplicated across our codebases, so we wanted to put them in one place.
At the same time, we noticed that having a lot of small dependencies was making maintainence harder, and making installation slower. To solve this, we've made srsly standalone, by including the component packages directly within it. This way we can provide all the serialization utilities we need in a single binary wheel.
srsly currently includes forks of the following packages:
ujson
msgpack
msgpack-numpy
cloudpickle
* WIP: replace json/ujson with srsly
* Replace ujson in examples
Use regular json instead of srsly to make code easier to read and follow
* Update requirements
* Fix imports
* Fix typos
* Replace msgpack with srsly
* Fix warning
2018-12-03 00:28:22 +00:00
|
|
|
import srsly
|
2023-06-14 15:48:41 +00:00
|
|
|
from wasabi import MarkdownRenderer, Printer
|
2017-03-18 17:57:45 +00:00
|
|
|
|
2023-06-14 15:48:41 +00:00
|
|
|
from .. import about, util
|
2023-03-06 13:48:57 +00:00
|
|
|
from ..compat import importlib_metadata
|
2023-06-14 15:48:41 +00:00
|
|
|
from ._util import Arg, Opt, app, string_to_list
|
|
|
|
from .download import get_latest_version, get_model_filename
|
2017-03-18 12:01:16 +00:00
|
|
|
|
|
|
|
|
2020-06-21 11:44:00 +00:00
|
|
|
@app.command("info")
|
2020-06-21 19:35:01 +00:00
|
|
|
def info_cli(
|
2020-06-21 11:44:00 +00:00
|
|
|
# fmt: off
|
2020-09-03 11:13:03 +00:00
|
|
|
model: Optional[str] = Arg(None, help="Optional loadable spaCy pipeline"),
|
2020-06-21 11:44:00 +00:00
|
|
|
markdown: bool = Opt(False, "--markdown", "-md", help="Generate Markdown for GitHub issues"),
|
2020-06-21 22:57:28 +00:00
|
|
|
silent: bool = Opt(False, "--silent", "-s", "-S", help="Don't print anything (just return)"),
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 13:21:40 +00:00
|
|
|
exclude: str = Opt("labels", "--exclude", "-e", help="Comma-separated keys to exclude from the print-out"),
|
2022-09-02 09:58:21 +00:00
|
|
|
url: bool = Opt(False, "--url", "-u", help="Print the URL to download the most recent compatible version of the pipeline"),
|
2020-06-21 11:44:00 +00:00
|
|
|
# fmt: on
|
2020-01-01 12:15:46 +00:00
|
|
|
):
|
2018-11-30 19:16:14 +00:00
|
|
|
"""
|
2020-12-30 11:35:26 +00:00
|
|
|
Print info about spaCy installation. If a pipeline is specified as an argument,
|
2020-09-03 11:13:03 +00:00
|
|
|
print its meta information. Flag --markdown prints details in Markdown for easy
|
2020-02-18 16:20:17 +00:00
|
|
|
copy-pasting to GitHub issues.
|
2020-09-04 10:58:50 +00:00
|
|
|
|
2022-09-02 09:58:21 +00:00
|
|
|
Flag --url prints only the download URL of the most recent compatible
|
|
|
|
version of the pipeline.
|
|
|
|
|
2021-01-30 09:09:38 +00:00
|
|
|
DOCS: https://spacy.io/api/cli#info
|
2017-05-22 10:28:58 +00:00
|
|
|
"""
|
2020-12-30 11:05:58 +00:00
|
|
|
exclude = string_to_list(exclude)
|
2022-09-02 09:58:21 +00:00
|
|
|
info(
|
|
|
|
model,
|
|
|
|
markdown=markdown,
|
|
|
|
silent=silent,
|
|
|
|
exclude=exclude,
|
|
|
|
url=url,
|
|
|
|
)
|
2020-06-21 19:35:01 +00:00
|
|
|
|
|
|
|
|
|
|
|
def info(
|
2021-01-15 00:57:36 +00:00
|
|
|
model: Optional[str] = None,
|
|
|
|
*,
|
|
|
|
markdown: bool = False,
|
|
|
|
silent: bool = True,
|
2021-01-25 12:00:22 +00:00
|
|
|
exclude: Optional[List[str]] = None,
|
2022-09-02 09:58:21 +00:00
|
|
|
url: bool = False,
|
2020-06-21 19:35:01 +00:00
|
|
|
) -> Union[str, dict]:
|
|
|
|
msg = Printer(no_print=silent, pretty=not silent)
|
2021-01-23 10:21:43 +00:00
|
|
|
if not exclude:
|
|
|
|
exclude = []
|
2022-09-02 09:58:21 +00:00
|
|
|
if url:
|
|
|
|
if model is not None:
|
|
|
|
title = f"Download info for pipeline '{model}'"
|
|
|
|
data = info_model_url(model)
|
|
|
|
print(data["download_url"])
|
|
|
|
return data
|
|
|
|
else:
|
|
|
|
msg.fail("--url option requires a pipeline name", exits=1)
|
|
|
|
elif model:
|
2020-09-03 11:13:03 +00:00
|
|
|
title = f"Info about pipeline '{model}'"
|
2020-06-21 19:35:01 +00:00
|
|
|
data = info_model(model, silent=silent)
|
|
|
|
else:
|
|
|
|
title = "Info about spaCy"
|
2020-06-21 23:17:11 +00:00
|
|
|
data = info_spacy()
|
|
|
|
raw_data = {k.lower().replace(" ", "_"): v for k, v in data.items()}
|
2020-09-03 11:13:03 +00:00
|
|
|
if "Pipelines" in data and isinstance(data["Pipelines"], dict):
|
|
|
|
data["Pipelines"] = ", ".join(
|
|
|
|
f"{n} ({v})" for n, v in data["Pipelines"].items()
|
|
|
|
)
|
2020-12-30 11:05:58 +00:00
|
|
|
markdown_data = get_markdown(data, title=title, exclude=exclude)
|
2020-06-21 19:35:01 +00:00
|
|
|
if markdown:
|
2018-04-28 23:59:44 +00:00
|
|
|
if not silent:
|
2020-06-21 19:35:01 +00:00
|
|
|
print(markdown_data)
|
|
|
|
return markdown_data
|
|
|
|
if not silent:
|
2020-12-30 11:05:58 +00:00
|
|
|
table_data = {k: v for k, v in data.items() if k not in exclude}
|
2020-06-21 23:17:11 +00:00
|
|
|
msg.table(table_data, title=title)
|
|
|
|
return raw_data
|
2020-06-21 19:35:01 +00:00
|
|
|
|
|
|
|
|
🏷 Add Mypy check to CI and ignore all existing Mypy errors (#9167)
* 🚨 Ignore all existing Mypy errors
* 🏗 Add Mypy check to CI
* Add types-mock and types-requests as dev requirements
* Add additional type ignore directives
* Add types packages to dev-only list in reqs test
* Add types-dataclasses for python 3.6
* Add ignore to pretrain
* 🏷 Improve type annotation on `run_command` helper
The `run_command` helper previously declared that it returned an
`Optional[subprocess.CompletedProcess]`, but it isn't actually possible
for the function to return `None`. These changes modify the type
annotation of the `run_command` helper and remove all now-unnecessary
`# type: ignore` directives.
* 🔧 Allow variable type redefinition in limited contexts
These changes modify how Mypy is configured to allow variables to have
their type automatically redefined under certain conditions. The Mypy
documentation contains the following example:
```python
def process(items: List[str]) -> None:
# 'items' has type List[str]
items = [item.split() for item in items]
# 'items' now has type List[List[str]]
...
```
This configuration change is especially helpful in reducing the number
of `# type: ignore` directives needed to handle the common pattern of:
* Accepting a filepath as a string
* Overwriting the variable using `filepath = ensure_path(filepath)`
These changes enable redefinition and remove all `# type: ignore`
directives rendered redundant by this change.
* 🏷 Add type annotation to converters mapping
* 🚨 Fix Mypy error in convert CLI argument verification
* 🏷 Improve type annotation on `resolve_dot_names` helper
* 🏷 Add type annotations for `Vocab` attributes `strings` and `vectors`
* 🏷 Add type annotations for more `Vocab` attributes
* 🏷 Add loose type annotation for gold data compilation
* 🏷 Improve `_format_labels` type annotation
* 🏷 Fix `get_lang_class` type annotation
* 🏷 Loosen return type of `Language.evaluate`
* 🏷 Don't accept `Scorer` in `handle_scores_per_type`
* 🏷 Add `string_to_list` overloads
* 🏷 Fix non-Optional command-line options
* 🙈 Ignore redefinition of `wandb_logger` in `loggers.py`
* ➕ Install `typing_extensions` in Python 3.8+
The `typing_extensions` package states that it should be used when
"writing code that must be compatible with multiple Python versions".
Since SpaCy needs to support multiple Python versions, it should be used
when newer `typing` module members are required. One example of this is
`Literal`, which is available starting with Python 3.8.
Previously SpaCy tried to import `Literal` from `typing`, falling back
to `typing_extensions` if the import failed. However, Mypy doesn't seem
to be able to understand what `Literal` means when the initial import
means. Therefore, these changes modify how `compat` imports `Literal` by
always importing it from `typing_extensions`.
These changes also modify how `typing_extensions` is installed, so that
it is a requirement for all Python versions, including those greater
than or equal to 3.8.
* 🏷 Improve type annotation for `Language.pipe`
These changes add a missing overload variant to the type signature of
`Language.pipe`. Additionally, the type signature is enhanced to allow
type checkers to differentiate between the two overload variants based
on the `as_tuple` parameter.
Fixes #8772
* ➖ Don't install `typing-extensions` in Python 3.8+
After more detailed analysis of how to implement Python version-specific
type annotations using SpaCy, it has been determined that by branching
on a comparison against `sys.version_info` can be statically analyzed by
Mypy well enough to enable us to conditionally use
`typing_extensions.Literal`. This means that we no longer need to
install `typing_extensions` for Python versions greater than or equal to
3.8! 🎉
These changes revert previous changes installing `typing-extensions`
regardless of Python version and modify how we import the `Literal` type
to ensure that Mypy treats it properly.
* resolve mypy errors for Strict pydantic types
* refactor code to avoid missing return statement
* fix types of convert CLI command
* avoid list-set confustion in debug_data
* fix typo and formatting
* small fixes to avoid type ignores
* fix types in profile CLI command and make it more efficient
* type fixes in projects CLI
* put one ignore back
* type fixes for render
* fix render types - the sequel
* fix BaseDefault in language definitions
* fix type of noun_chunks iterator - yields tuple instead of span
* fix types in language-specific modules
* 🏷 Expand accepted inputs of `get_string_id`
`get_string_id` accepts either a string (in which case it returns its
ID) or an ID (in which case it immediately returns the ID). These
changes extend the type annotation of `get_string_id` to indicate that
it can accept either strings or IDs.
* 🏷 Handle override types in `combine_score_weights`
The `combine_score_weights` function allows users to pass an `overrides`
mapping to override data extracted from the `weights` argument. Since it
allows `Optional` dictionary values, the return value may also include
`Optional` dictionary values.
These changes update the type annotations for `combine_score_weights` to
reflect this fact.
* 🏷 Fix tokenizer serialization method signatures in `DummyTokenizer`
* 🏷 Fix redefinition of `wandb_logger`
These changes fix the redefinition of `wandb_logger` by giving a
separate name to each `WandbLogger` version. For
backwards-compatibility, `spacy.train` still exports `wandb_logger_v3`
as `wandb_logger` for now.
* more fixes for typing in language
* type fixes in model definitions
* 🏷 Annotate `_RandomWords.probs` as `NDArray`
* 🏷 Annotate `tok2vec` layers to help Mypy
* 🐛 Fix `_RandomWords.probs` type annotations for Python 3.6
Also remove an import that I forgot to move to the top of the module 😅
* more fixes for matchers and other pipeline components
* quick fix for entity linker
* fixing types for spancat, textcat, etc
* bugfix for tok2vec
* type annotations for scorer
* add runtime_checkable for Protocol
* type and import fixes in tests
* mypy fixes for training utilities
* few fixes in util
* fix import
* 🐵 Remove unused `# type: ignore` directives
* 🏷 Annotate `Language._components`
* 🏷 Annotate `spacy.pipeline.Pipe`
* add doc as property to span.pyi
* small fixes and cleanup
* explicit type annotations instead of via comment
Co-authored-by: Adriane Boyd <adrianeboyd@gmail.com>
Co-authored-by: svlandeg <sofie.vanlandeghem@gmail.com>
Co-authored-by: svlandeg <svlandeg@github.com>
2021-10-14 13:21:40 +00:00
|
|
|
def info_spacy() -> Dict[str, Any]:
|
2020-06-21 19:35:01 +00:00
|
|
|
"""Generate info about the current spaCy intallation.
|
|
|
|
|
|
|
|
RETURNS (dict): The spaCy info.
|
|
|
|
"""
|
2020-06-21 23:07:48 +00:00
|
|
|
all_models = {}
|
|
|
|
for pkg_name in util.get_installed_models():
|
|
|
|
package = pkg_name.replace("-", "_")
|
|
|
|
all_models[package] = util.get_package_version(pkg_name)
|
2020-06-21 19:35:01 +00:00
|
|
|
return {
|
2018-11-30 19:16:14 +00:00
|
|
|
"spaCy version": about.__version__,
|
2019-12-22 00:53:56 +00:00
|
|
|
"Location": str(Path(__file__).parent.parent),
|
2018-11-30 19:16:14 +00:00
|
|
|
"Platform": platform.platform(),
|
|
|
|
"Python version": platform.python_version(),
|
2020-09-03 11:13:03 +00:00
|
|
|
"Pipelines": all_models,
|
2018-11-30 19:16:14 +00:00
|
|
|
}
|
2017-03-18 12:01:16 +00:00
|
|
|
|
|
|
|
|
2020-06-21 19:35:01 +00:00
|
|
|
def info_model(model: str, *, silent: bool = True) -> Dict[str, Any]:
|
|
|
|
"""Generate info about a specific model.
|
|
|
|
|
|
|
|
model (str): Model name of path.
|
|
|
|
silent (bool): Don't print anything, just return.
|
|
|
|
RETURNS (dict): The model meta.
|
|
|
|
"""
|
|
|
|
msg = Printer(no_print=silent, pretty=not silent)
|
|
|
|
if util.is_package(model):
|
|
|
|
model_path = util.get_package_path(model)
|
|
|
|
else:
|
2020-12-30 11:05:58 +00:00
|
|
|
model_path = Path(model)
|
2020-06-21 19:35:01 +00:00
|
|
|
meta_path = model_path / "meta.json"
|
|
|
|
if not meta_path.is_file():
|
2020-09-03 11:13:03 +00:00
|
|
|
msg.fail("Can't find pipeline meta.json", meta_path, exits=1)
|
2020-06-21 19:35:01 +00:00
|
|
|
meta = srsly.read_json(meta_path)
|
|
|
|
if model_path.resolve() != model_path:
|
|
|
|
meta["source"] = str(model_path.resolve())
|
|
|
|
else:
|
|
|
|
meta["source"] = str(model_path)
|
2022-09-02 09:58:21 +00:00
|
|
|
download_url = info_installed_model_url(model)
|
|
|
|
if download_url:
|
|
|
|
meta["download_url"] = download_url
|
2020-09-24 12:32:35 +00:00
|
|
|
return {
|
|
|
|
k: v for k, v in meta.items() if k not in ("accuracy", "performance", "speed")
|
|
|
|
}
|
2020-06-21 19:35:01 +00:00
|
|
|
|
|
|
|
|
2022-09-02 09:58:21 +00:00
|
|
|
def info_installed_model_url(model: str) -> Optional[str]:
|
|
|
|
"""Given a pipeline name, get the download URL if available, otherwise
|
|
|
|
return None.
|
|
|
|
|
|
|
|
This is only available for pipelines installed as modules that have
|
|
|
|
dist-info available.
|
|
|
|
"""
|
|
|
|
try:
|
2023-03-06 13:48:57 +00:00
|
|
|
dist = importlib_metadata.distribution(model)
|
|
|
|
text = dist.read_text("direct_url.json")
|
|
|
|
if isinstance(text, str):
|
|
|
|
data = json.loads(text)
|
|
|
|
return data["url"]
|
2022-09-02 09:58:21 +00:00
|
|
|
except Exception:
|
2023-03-06 13:48:57 +00:00
|
|
|
pass
|
|
|
|
return None
|
2022-09-02 09:58:21 +00:00
|
|
|
|
2022-09-09 09:21:17 +00:00
|
|
|
|
2022-09-02 09:58:21 +00:00
|
|
|
def info_model_url(model: str) -> Dict[str, Any]:
|
|
|
|
"""Return the download URL for the latest version of a pipeline."""
|
|
|
|
version = get_latest_version(model)
|
|
|
|
|
|
|
|
filename = get_model_filename(model, version)
|
|
|
|
download_url = about.__download_url__ + "/" + filename
|
|
|
|
release_tpl = "https://github.com/explosion/spacy-models/releases/tag/{m}-{v}"
|
|
|
|
release_url = release_tpl.format(m=model, v=version)
|
|
|
|
return {"download_url": download_url, "release_url": release_url}
|
|
|
|
|
|
|
|
|
2021-01-15 00:57:36 +00:00
|
|
|
def get_markdown(
|
2021-01-30 01:52:33 +00:00
|
|
|
data: Dict[str, Any],
|
|
|
|
title: Optional[str] = None,
|
|
|
|
exclude: Optional[List[str]] = None,
|
2021-01-15 00:57:36 +00:00
|
|
|
) -> str:
|
2020-06-21 19:35:01 +00:00
|
|
|
"""Get data in GitHub-flavoured Markdown format for issues etc.
|
2018-12-01 03:55:48 +00:00
|
|
|
|
2021-01-30 01:52:33 +00:00
|
|
|
data (Dict[str, Any]): Label/value pairs.
|
|
|
|
title (str): Optional title, will be rendered as headline 2.
|
|
|
|
exclude (List[str]): Names of keys to exclude.
|
2020-06-21 19:35:01 +00:00
|
|
|
RETURNS (str): The Markdown string.
|
2018-12-01 03:55:48 +00:00
|
|
|
"""
|
2020-08-26 13:33:11 +00:00
|
|
|
md = MarkdownRenderer()
|
|
|
|
if title:
|
|
|
|
md.add(md.title(2, title))
|
|
|
|
items = []
|
2018-12-01 03:59:12 +00:00
|
|
|
for key, value in data.items():
|
2020-12-30 11:05:58 +00:00
|
|
|
if exclude and key in exclude:
|
2018-12-01 03:59:12 +00:00
|
|
|
continue
|
2020-12-30 11:05:58 +00:00
|
|
|
if isinstance(value, str):
|
|
|
|
try:
|
|
|
|
existing_path = Path(value).exists()
|
2021-01-15 00:57:36 +00:00
|
|
|
except Exception:
|
2020-12-30 11:05:58 +00:00
|
|
|
# invalid Path, like a URL string
|
|
|
|
existing_path = False
|
|
|
|
if existing_path:
|
|
|
|
continue
|
2020-08-26 13:33:11 +00:00
|
|
|
items.append(f"{md.bold(f'{key}:')} {value}")
|
|
|
|
md.add(md.list(items))
|
|
|
|
return f"\n{md.text}\n"
|