repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_documentation_string stringlengths 1 47.2k | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|
pallets/pallets-sphinx-themes | src/pallets_sphinx_themes/themes/click/domain.py | ExampleRunner.run_example | def run_example(self, source):
"""Run commands by executing the given code, returning the lines
of input and output. The code should be a series of the
following functions:
* :meth:`invoke`: Invoke a command, adding env vars, input,
and output to the output.
* ``... | python | def run_example(self, source):
"""Run commands by executing the given code, returning the lines
of input and output. The code should be a series of the
following functions:
* :meth:`invoke`: Invoke a command, adding env vars, input,
and output to the output.
* ``... | Run commands by executing the given code, returning the lines
of input and output. The code should be a series of the
following functions:
* :meth:`invoke`: Invoke a command, adding env vars, input,
and output to the output.
* ``println(text="")``: Add a line of text to ... | https://github.com/pallets/pallets-sphinx-themes/blob/1d4517d76dd492017f17acd7f72e82e40a1f1bc6/src/pallets_sphinx_themes/themes/click/domain.py#L165-L192 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | setup | def setup(
*,
verbose: bool = False,
quiet: bool = False,
color: str = "auto",
title: str = "auto",
timestamp: bool = False
) -> None:
""" Configure behavior of message functions.
:param verbose: Whether :func:`debug` messages should get printed
:param quiet: Hide every message exce... | python | def setup(
*,
verbose: bool = False,
quiet: bool = False,
color: str = "auto",
title: str = "auto",
timestamp: bool = False
) -> None:
""" Configure behavior of message functions.
:param verbose: Whether :func:`debug` messages should get printed
:param quiet: Hide every message exce... | Configure behavior of message functions.
:param verbose: Whether :func:`debug` messages should get printed
:param quiet: Hide every message except :func:`warning`, :func:`error`, and
:func:`fatal`
:param color: Choices: 'auto', 'always', or 'never'. Whether to color output.
... | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L52-L70 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | process_tokens | def process_tokens(
tokens: Sequence[Token], *, end: str = "\n", sep: str = " "
) -> Tuple[str, str]:
""" Returns two strings from a list of tokens.
One containing ASCII escape codes, the other
only the 'normal' characters
"""
# Flatten the list of tokens in case some of them are of
# class... | python | def process_tokens(
tokens: Sequence[Token], *, end: str = "\n", sep: str = " "
) -> Tuple[str, str]:
""" Returns two strings from a list of tokens.
One containing ASCII escape codes, the other
only the 'normal' characters
"""
# Flatten the list of tokens in case some of them are of
# class... | Returns two strings from a list of tokens.
One containing ASCII escape codes, the other
only the 'normal' characters | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L187-L206 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | message | def message(
*tokens: Token,
end: str = "\n",
sep: str = " ",
fileobj: FileObj = sys.stdout,
update_title: bool = False
) -> None:
""" Helper method for error, warning, info, debug
"""
if using_colorama():
global _INITIALIZED
if not _INITIALIZED:
colorama.ini... | python | def message(
*tokens: Token,
end: str = "\n",
sep: str = " ",
fileobj: FileObj = sys.stdout,
update_title: bool = False
) -> None:
""" Helper method for error, warning, info, debug
"""
if using_colorama():
global _INITIALIZED
if not _INITIALIZED:
colorama.ini... | Helper method for error, warning, info, debug | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L245-L266 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | fatal | def fatal(*tokens: Token, **kwargs: Any) -> None:
""" Print an error message and call ``sys.exit`` """
error(*tokens, **kwargs)
sys.exit(1) | python | def fatal(*tokens: Token, **kwargs: Any) -> None:
""" Print an error message and call ``sys.exit`` """
error(*tokens, **kwargs)
sys.exit(1) | Print an error message and call ``sys.exit`` | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L269-L272 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | error | def error(*tokens: Token, **kwargs: Any) -> None:
""" Print an error message """
tokens = [bold, red, "Error:"] + list(tokens) # type: ignore
kwargs["fileobj"] = sys.stderr
message(*tokens, **kwargs) | python | def error(*tokens: Token, **kwargs: Any) -> None:
""" Print an error message """
tokens = [bold, red, "Error:"] + list(tokens) # type: ignore
kwargs["fileobj"] = sys.stderr
message(*tokens, **kwargs) | Print an error message | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L275-L279 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | warning | def warning(*tokens: Token, **kwargs: Any) -> None:
""" Print a warning message """
tokens = [brown, "Warning:"] + list(tokens) # type: ignore
kwargs["fileobj"] = sys.stderr
message(*tokens, **kwargs) | python | def warning(*tokens: Token, **kwargs: Any) -> None:
""" Print a warning message """
tokens = [brown, "Warning:"] + list(tokens) # type: ignore
kwargs["fileobj"] = sys.stderr
message(*tokens, **kwargs) | Print a warning message | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L282-L286 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | info_section | def info_section(*tokens: Token, **kwargs: Any) -> None:
""" Print an underlined section name """
# We need to know the length of the section:
process_tokens_kwargs = kwargs.copy()
process_tokens_kwargs["color"] = False
no_color = _process_tokens(tokens, **process_tokens_kwargs)
info(*tokens, **... | python | def info_section(*tokens: Token, **kwargs: Any) -> None:
""" Print an underlined section name """
# We need to know the length of the section:
process_tokens_kwargs = kwargs.copy()
process_tokens_kwargs["color"] = False
no_color = _process_tokens(tokens, **process_tokens_kwargs)
info(*tokens, **... | Print an underlined section name | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L303-L310 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | info_1 | def info_1(*tokens: Token, **kwargs: Any) -> None:
""" Print an important informative message """
info(bold, blue, "::", reset, *tokens, **kwargs) | python | def info_1(*tokens: Token, **kwargs: Any) -> None:
""" Print an important informative message """
info(bold, blue, "::", reset, *tokens, **kwargs) | Print an important informative message | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L313-L315 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | dot | def dot(*, last: bool = False, fileobj: Any = None) -> None:
""" Print a dot without a newline unless it is the last one.
Useful when you want to display a progress with very little
knowledge.
:param last: whether this is the last dot (will insert a newline)
"""
end = "\n" if last else ""
... | python | def dot(*, last: bool = False, fileobj: Any = None) -> None:
""" Print a dot without a newline unless it is the last one.
Useful when you want to display a progress with very little
knowledge.
:param last: whether this is the last dot (will insert a newline)
"""
end = "\n" if last else ""
... | Print a dot without a newline unless it is the last one.
Useful when you want to display a progress with very little
knowledge.
:param last: whether this is the last dot (will insert a newline) | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L328-L337 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | info_count | def info_count(i: int, n: int, *rest: Token, **kwargs: Any) -> None:
""" Display a counter before the rest of the message.
``rest`` and ``kwargs`` are passed to :func:`info`
Current index should start at 0 and end at ``n-1``, like in ``enumerate()``
:param i: current index
:param n: total number ... | python | def info_count(i: int, n: int, *rest: Token, **kwargs: Any) -> None:
""" Display a counter before the rest of the message.
``rest`` and ``kwargs`` are passed to :func:`info`
Current index should start at 0 and end at ``n-1``, like in ``enumerate()``
:param i: current index
:param n: total number ... | Display a counter before the rest of the message.
``rest`` and ``kwargs`` are passed to :func:`info`
Current index should start at 0 and end at ``n-1``, like in ``enumerate()``
:param i: current index
:param n: total number of items | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L340-L353 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | info_progress | def info_progress(prefix: str, value: float, max_value: float) -> None:
""" Display info progress in percent.
:param value: the current value
:param max_value: the max value
:param prefix: the prefix message to print
"""
if sys.stdout.isatty():
percent = float(value) / max_value * 100... | python | def info_progress(prefix: str, value: float, max_value: float) -> None:
""" Display info progress in percent.
:param value: the current value
:param max_value: the max value
:param prefix: the prefix message to print
"""
if sys.stdout.isatty():
percent = float(value) / max_value * 100... | Display info progress in percent.
:param value: the current value
:param max_value: the max value
:param prefix: the prefix message to print | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L356-L368 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | debug | def debug(*tokens: Token, **kwargs: Any) -> None:
""" Print a debug message.
Messages are shown only when ``CONFIG["verbose"]`` is true
"""
if not CONFIG["verbose"] or CONFIG["record"]:
return
message(*tokens, **kwargs) | python | def debug(*tokens: Token, **kwargs: Any) -> None:
""" Print a debug message.
Messages are shown only when ``CONFIG["verbose"]`` is true
"""
if not CONFIG["verbose"] or CONFIG["record"]:
return
message(*tokens, **kwargs) | Print a debug message.
Messages are shown only when ``CONFIG["verbose"]`` is true | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L371-L378 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | indent_iterable | def indent_iterable(elems: Sequence[str], num: int = 2) -> List[str]:
"""Indent an iterable."""
return [" " * num + l for l in elems] | python | def indent_iterable(elems: Sequence[str], num: int = 2) -> List[str]:
"""Indent an iterable."""
return [" " * num + l for l in elems] | Indent an iterable. | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L381-L383 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | indent | def indent(text: str, num: int = 2) -> str:
"""Indent a piece of text."""
lines = text.splitlines()
return "\n".join(indent_iterable(lines, num=num)) | python | def indent(text: str, num: int = 2) -> str:
"""Indent a piece of text."""
lines = text.splitlines()
return "\n".join(indent_iterable(lines, num=num)) | Indent a piece of text. | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L386-L389 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | message_for_exception | def message_for_exception(exception: Exception, message: str) -> Sequence[Token]:
""" Returns a tuple suitable for cli_ui.error()
from the given exception.
(Traceback will be part of the message, after
the ``message`` argument)
Useful when the exception occurs in an other thread
than the main o... | python | def message_for_exception(exception: Exception, message: str) -> Sequence[Token]:
""" Returns a tuple suitable for cli_ui.error()
from the given exception.
(Traceback will be part of the message, after
the ``message`` argument)
Useful when the exception occurs in an other thread
than the main o... | Returns a tuple suitable for cli_ui.error()
from the given exception.
(Traceback will be part of the message, after
the ``message`` argument)
Useful when the exception occurs in an other thread
than the main one. | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L425-L444 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | ask_string | def ask_string(*question: Token, default: Optional[str] = None) -> Optional[str]:
"""Ask the user to enter a string.
"""
tokens = get_ask_tokens(question)
if default:
tokens.append("(%s)" % default)
info(*tokens)
answer = read_input()
if not answer:
return default
return ... | python | def ask_string(*question: Token, default: Optional[str] = None) -> Optional[str]:
"""Ask the user to enter a string.
"""
tokens = get_ask_tokens(question)
if default:
tokens.append("(%s)" % default)
info(*tokens)
answer = read_input()
if not answer:
return default
return ... | Ask the user to enter a string. | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L468-L478 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | ask_password | def ask_password(*question: Token) -> str:
"""Ask the user to enter a password.
"""
tokens = get_ask_tokens(question)
info(*tokens)
answer = read_password()
return answer | python | def ask_password(*question: Token) -> str:
"""Ask the user to enter a password.
"""
tokens = get_ask_tokens(question)
info(*tokens)
answer = read_password()
return answer | Ask the user to enter a password. | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L481-L487 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | ask_choice | def ask_choice(
*prompt: Token, choices: List[Any], func_desc: Optional[FuncDesc] = None
) -> Any:
"""Ask the user to choose from a list of choices.
:return: the selected choice
``func_desc`` will be called on every list item for displaying
and sorting the list. If not given, will default to
t... | python | def ask_choice(
*prompt: Token, choices: List[Any], func_desc: Optional[FuncDesc] = None
) -> Any:
"""Ask the user to choose from a list of choices.
:return: the selected choice
``func_desc`` will be called on every list item for displaying
and sorting the list. If not given, will default to
t... | Ask the user to choose from a list of choices.
:return: the selected choice
``func_desc`` will be called on every list item for displaying
and sorting the list. If not given, will default to
the identity function.
Will loop until:
* the user enters a valid index
* or leaves the pr... | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L493-L535 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | ask_yes_no | def ask_yes_no(*question: Token, default: bool = False) -> bool:
"""Ask the user to answer by yes or no"""
while True:
tokens = [green, "::", reset] + list(question) + [reset]
if default:
tokens.append("(Y/n)")
else:
tokens.append("(y/N)")
info(*tokens)
... | python | def ask_yes_no(*question: Token, default: bool = False) -> bool:
"""Ask the user to answer by yes or no"""
while True:
tokens = [green, "::", reset] + list(question) + [reset]
if default:
tokens.append("(Y/n)")
else:
tokens.append("(y/N)")
info(*tokens)
... | Ask the user to answer by yes or no | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L538-L554 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | did_you_mean | def did_you_mean(message: str, user_input: str, choices: Sequence[str]) -> str:
""" Given a list of choices and an invalid user input, display the closest
items in the list that match the input.
"""
if not choices:
return message
else:
result = {
difflib.SequenceMatcher(... | python | def did_you_mean(message: str, user_input: str, choices: Sequence[str]) -> str:
""" Given a list of choices and an invalid user input, display the closest
items in the list that match the input.
"""
if not choices:
return message
else:
result = {
difflib.SequenceMatcher(... | Given a list of choices and an invalid user input, display the closest
items in the list that match the input. | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L608-L621 |
TankerHQ/python-cli-ui | cli_ui/__init__.py | Timer.stop | def stop(self) -> None:
""" Stop the timer and emit a nice log """
end_time = datetime.datetime.now()
elapsed_time = end_time - self.start_time
elapsed_seconds = elapsed_time.seconds
hours, remainder = divmod(int(elapsed_seconds), 3600)
minutes, seconds = divmod(remainder... | python | def stop(self) -> None:
""" Stop the timer and emit a nice log """
end_time = datetime.datetime.now()
elapsed_time = end_time - self.start_time
elapsed_seconds = elapsed_time.seconds
hours, remainder = divmod(int(elapsed_seconds), 3600)
minutes, seconds = divmod(remainder... | Stop the timer and emit a nice log | https://github.com/TankerHQ/python-cli-ui/blob/4c9928827cea06cf80e6a1f5bd86478d8566863f/cli_ui/__init__.py#L592-L605 |
OCR-D/core | ocrd_models/ocrd_models/utils.py | xmllint_format | def xmllint_format(xml):
"""
Pretty-print XML like ``xmllint`` does.
Arguments:
xml (string): Serialized XML
"""
parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True)
document = ET.fromstring(xml, parser)
return ('%s\n%s' % ('<?xml version="1.0" en... | python | def xmllint_format(xml):
"""
Pretty-print XML like ``xmllint`` does.
Arguments:
xml (string): Serialized XML
"""
parser = ET.XMLParser(resolve_entities=False, strip_cdata=False, remove_blank_text=True)
document = ET.fromstring(xml, parser)
return ('%s\n%s' % ('<?xml version="1.0" en... | Pretty-print XML like ``xmllint`` does.
Arguments:
xml (string): Serialized XML | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/utils.py#L10-L19 |
OCR-D/core | ocrd/ocrd/resolver.py | Resolver.download_to_directory | def download_to_directory(self, directory, url, basename=None, overwrite=False, subdir=None):
"""
Download a file to the workspace.
Early Shortcut: If url is a file://-URL and that file is already in the directory, keep it there.
If basename is not given but subdir is, assume user know... | python | def download_to_directory(self, directory, url, basename=None, overwrite=False, subdir=None):
"""
Download a file to the workspace.
Early Shortcut: If url is a file://-URL and that file is already in the directory, keep it there.
If basename is not given but subdir is, assume user know... | Download a file to the workspace.
Early Shortcut: If url is a file://-URL and that file is already in the directory, keep it there.
If basename is not given but subdir is, assume user knows what she's doing and use last URL segment as the basename.
If basename is not given and no subdir is giv... | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/resolver.py#L20-L84 |
OCR-D/core | ocrd/ocrd/resolver.py | Resolver.workspace_from_url | def workspace_from_url(self, mets_url, dst_dir=None, clobber_mets=False, mets_basename=None, download=False, baseurl=None):
"""
Create a workspace from a METS by URL.
Sets the mets.xml file
Arguments:
mets_url (string): Source mets URL
dst_dir (string, None): Ta... | python | def workspace_from_url(self, mets_url, dst_dir=None, clobber_mets=False, mets_basename=None, download=False, baseurl=None):
"""
Create a workspace from a METS by URL.
Sets the mets.xml file
Arguments:
mets_url (string): Source mets URL
dst_dir (string, None): Ta... | Create a workspace from a METS by URL.
Sets the mets.xml file
Arguments:
mets_url (string): Source mets URL
dst_dir (string, None): Target directory for the workspace
clobber_mets (boolean, False): Whether to overwrite existing mets.xml. By default existing mets.xml... | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/resolver.py#L86-L151 |
OCR-D/core | ocrd/ocrd/resolver.py | Resolver.workspace_from_nothing | def workspace_from_nothing(self, directory, mets_basename='mets.xml', clobber_mets=False):
"""
Create an empty workspace.
"""
if directory is None:
directory = tempfile.mkdtemp(prefix=TMP_PREFIX)
if not exists(directory):
makedirs(directory)
mets_... | python | def workspace_from_nothing(self, directory, mets_basename='mets.xml', clobber_mets=False):
"""
Create an empty workspace.
"""
if directory is None:
directory = tempfile.mkdtemp(prefix=TMP_PREFIX)
if not exists(directory):
makedirs(directory)
mets_... | Create an empty workspace. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/resolver.py#L153-L170 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_xml_base.py | OcrdXmlDocument.to_xml | def to_xml(self, xmllint=False):
"""
Serialize all properties as pretty-printed XML
Args:
xmllint (boolean): Format with ``xmllint`` in addition to pretty-printing
"""
root = self._tree.getroot()
ret = ET.tostring(ET.ElementTree(root), pretty_print=True)
... | python | def to_xml(self, xmllint=False):
"""
Serialize all properties as pretty-printed XML
Args:
xmllint (boolean): Format with ``xmllint`` in addition to pretty-printing
"""
root = self._tree.getroot()
ret = ET.tostring(ET.ElementTree(root), pretty_print=True)
... | Serialize all properties as pretty-printed XML
Args:
xmllint (boolean): Format with ``xmllint`` in addition to pretty-printing | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_xml_base.py#L37-L48 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_cli | def workspace_cli(ctx, directory, mets_basename, backup):
"""
Working with workspace
"""
ctx.obj = WorkspaceCtx(os.path.abspath(directory), mets_basename, automatic_backup=backup) | python | def workspace_cli(ctx, directory, mets_basename, backup):
"""
Working with workspace
"""
ctx.obj = WorkspaceCtx(os.path.abspath(directory), mets_basename, automatic_backup=backup) | Working with workspace | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L32-L36 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_clone | def workspace_clone(ctx, clobber_mets, download, mets_url, workspace_dir):
"""
Create a workspace from a METS_URL and return the directory
METS_URL can be a URL, an absolute path or a path relative to $PWD.
If WORKSPACE_DIR is not provided, creates a temporary directory.
"""
workspace = ctx.re... | python | def workspace_clone(ctx, clobber_mets, download, mets_url, workspace_dir):
"""
Create a workspace from a METS_URL and return the directory
METS_URL can be a URL, an absolute path or a path relative to $PWD.
If WORKSPACE_DIR is not provided, creates a temporary directory.
"""
workspace = ctx.re... | Create a workspace from a METS_URL and return the directory
METS_URL can be a URL, an absolute path or a path relative to $PWD.
If WORKSPACE_DIR is not provided, creates a temporary directory. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L75-L91 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_create | def workspace_create(ctx, clobber_mets, directory):
"""
Create a workspace with an empty METS file in DIRECTORY.
Use '.' for $PWD"
"""
workspace = ctx.resolver.workspace_from_nothing(
directory=os.path.abspath(directory),
mets_basename=ctx.mets_basename,
clobber_mets=clobber... | python | def workspace_create(ctx, clobber_mets, directory):
"""
Create a workspace with an empty METS file in DIRECTORY.
Use '.' for $PWD"
"""
workspace = ctx.resolver.workspace_from_nothing(
directory=os.path.abspath(directory),
mets_basename=ctx.mets_basename,
clobber_mets=clobber... | Create a workspace with an empty METS file in DIRECTORY.
Use '.' for $PWD" | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L101-L113 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_add_file | def workspace_add_file(ctx, file_grp, file_id, mimetype, page_id, force, local_filename):
"""
Add a file LOCAL_FILENAME to METS in a workspace.
"""
workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup)
if not local_filen... | python | def workspace_add_file(ctx, file_grp, file_id, mimetype, page_id, force, local_filename):
"""
Add a file LOCAL_FILENAME to METS in a workspace.
"""
workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup)
if not local_filen... | Add a file LOCAL_FILENAME to METS in a workspace. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L127-L148 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_find | def workspace_find(ctx, file_grp, mimetype, page_id, file_id, output_field, download):
"""
Find files.
"""
workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename)
for f in workspace.mets.find_files(
ID=file_id,
fileGrp=file_grp,
... | python | def workspace_find(ctx, file_grp, mimetype, page_id, file_id, output_field, download):
"""
Find files.
"""
workspace = Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename)
for f in workspace.mets.find_files(
ID=file_id,
fileGrp=file_grp,
... | Find files. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L174-L189 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_backup_add | def workspace_backup_add(ctx):
"""
Create a new backup
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.add() | python | def workspace_backup_add(ctx):
"""
Create a new backup
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.add() | Create a new backup | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L267-L272 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_backup_list | def workspace_backup_list(ctx):
"""
List backups
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
for b in backup_manager.list():
print(b) | python | def workspace_backup_list(ctx):
"""
List backups
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
for b in backup_manager.list():
print(b) | List backups | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L276-L282 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_backup_restore | def workspace_backup_restore(ctx, choose_first, bak):
"""
Restore backup BAK
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.restore(bak, choose_first) | python | def workspace_backup_restore(ctx, choose_first, bak):
"""
Restore backup BAK
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.restore(bak, choose_first) | Restore backup BAK | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L288-L293 |
OCR-D/core | ocrd/ocrd/cli/workspace.py | workspace_backup_undo | def workspace_backup_undo(ctx):
"""
Restore the last backup
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.undo() | python | def workspace_backup_undo(ctx):
"""
Restore the last backup
"""
backup_manager = WorkspaceBackupManager(Workspace(ctx.resolver, directory=ctx.directory, mets_basename=ctx.mets_basename, automatic_backup=ctx.automatic_backup))
backup_manager.undo() | Restore the last backup | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/workspace.py#L297-L302 |
OCR-D/core | ocrd_validators/ocrd_validators/json_validator.py | extend_with_default | def extend_with_default(validator_class):
"""
Add a default-setting mechanism to a ``jsonschema`` validation class.
"""
validate_properties = validator_class.VALIDATORS["properties"]
def set_defaults(validator, properties, instance, schema):
"""
Set defaults in subschemas
""... | python | def extend_with_default(validator_class):
"""
Add a default-setting mechanism to a ``jsonschema`` validation class.
"""
validate_properties = validator_class.VALIDATORS["properties"]
def set_defaults(validator, properties, instance, schema):
"""
Set defaults in subschemas
""... | Add a default-setting mechanism to a ``jsonschema`` validation class. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/json_validator.py#L11-L28 |
OCR-D/core | ocrd_validators/ocrd_validators/json_validator.py | JsonValidator.validate | def validate(obj, schema):
"""
Validate an object against a schema
Args:
obj (dict):
schema (dict):
"""
if isinstance(obj, str):
obj = json.loads(obj)
return JsonValidator(schema)._validate(obj) | python | def validate(obj, schema):
"""
Validate an object against a schema
Args:
obj (dict):
schema (dict):
"""
if isinstance(obj, str):
obj = json.loads(obj)
return JsonValidator(schema)._validate(obj) | Validate an object against a schema
Args:
obj (dict):
schema (dict): | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/json_validator.py#L43-L53 |
OCR-D/core | ocrd_validators/ocrd_validators/json_validator.py | JsonValidator._validate | def _validate(self, obj):
"""
Do the actual validation
Arguments:
obj (dict): object to validate
Returns: ValidationReport
"""
report = ValidationReport()
if not self.validator.is_valid(obj):
for v in self.validator.iter_errors(obj):
... | python | def _validate(self, obj):
"""
Do the actual validation
Arguments:
obj (dict): object to validate
Returns: ValidationReport
"""
report = ValidationReport()
if not self.validator.is_valid(obj):
for v in self.validator.iter_errors(obj):
... | Do the actual validation
Arguments:
obj (dict): object to validate
Returns: ValidationReport | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/json_validator.py#L65-L78 |
OCR-D/core | ocrd/ocrd/processor/base.py | run_processor | def run_processor(
processorClass,
ocrd_tool=None,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
): # pylint: disable=too-man... | python | def run_processor(
processorClass,
ocrd_tool=None,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
): # pylint: disable=too-man... | Create a workspace for mets_url and run processor through it
Args:
parameter (string): URL to the parameter | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/processor/base.py#L18-L74 |
OCR-D/core | ocrd/ocrd/processor/base.py | run_cli | def run_cli(
executable,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
):
"""
Create a workspace for mets_url and run MP CLI ... | python | def run_cli(
executable,
mets_url=None,
resolver=None,
workspace=None,
page_id=None,
log_level=None,
input_file_grp=None,
output_file_grp=None,
parameter=None,
working_dir=None,
):
"""
Create a workspace for mets_url and run MP CLI ... | Create a workspace for mets_url and run MP CLI through it | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/processor/base.py#L76-L105 |
OCR-D/core | ocrd/ocrd/processor/base.py | Processor.input_files | def input_files(self):
"""
List the input files
"""
return self.workspace.mets.find_files(fileGrp=self.input_file_grp, pageId=self.page_id) | python | def input_files(self):
"""
List the input files
"""
return self.workspace.mets.find_files(fileGrp=self.input_file_grp, pageId=self.page_id) | List the input files | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/processor/base.py#L153-L157 |
OCR-D/core | ocrd_modelfactory/ocrd_modelfactory/__init__.py | page_from_image | def page_from_image(input_file):
"""
Create `OcrdPage </../../ocrd_models/ocrd_models.ocrd_page.html>`_
from an `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_
representing an image (i.e. should have ``mimetype`` starting with ``image/``).
Arguments:
* input_file (OcrdFile):
... | python | def page_from_image(input_file):
"""
Create `OcrdPage </../../ocrd_models/ocrd_models.ocrd_page.html>`_
from an `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_
representing an image (i.e. should have ``mimetype`` starting with ``image/``).
Arguments:
* input_file (OcrdFile):
... | Create `OcrdPage </../../ocrd_models/ocrd_models.ocrd_page.html>`_
from an `OcrdFile </../../ocrd_models/ocrd_models.ocrd_file.html>`_
representing an image (i.e. should have ``mimetype`` starting with ``image/``).
Arguments:
* input_file (OcrdFile): | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_modelfactory/ocrd_modelfactory/__init__.py#L33-L58 |
OCR-D/core | ocrd_modelfactory/ocrd_modelfactory/__init__.py | page_from_file | def page_from_file(input_file):
"""
Create a new PAGE-XML from a METS file representing a PAGE-XML or an image.
Arguments:
* input_file (OcrdFile):
"""
# print("PARSING PARSING '%s'" % input_file)
if input_file.mimetype.startswith('image'):
return page_from_image(input_file)
... | python | def page_from_file(input_file):
"""
Create a new PAGE-XML from a METS file representing a PAGE-XML or an image.
Arguments:
* input_file (OcrdFile):
"""
# print("PARSING PARSING '%s'" % input_file)
if input_file.mimetype.startswith('image'):
return page_from_image(input_file)
... | Create a new PAGE-XML from a METS file representing a PAGE-XML or an image.
Arguments:
* input_file (OcrdFile): | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_modelfactory/ocrd_modelfactory/__init__.py#L60-L72 |
OCR-D/core | ocrd_utils/ocrd_utils/__init__.py | concat_padded | def concat_padded(base, *args):
"""
Concatenate string and zero-padded 4 digit number
"""
ret = base
for n in args:
if is_string(n):
ret = "%s_%s" % (ret, n)
else:
ret = "%s_%04i" % (ret, n + 1)
return ret | python | def concat_padded(base, *args):
"""
Concatenate string and zero-padded 4 digit number
"""
ret = base
for n in args:
if is_string(n):
ret = "%s_%s" % (ret, n)
else:
ret = "%s_%04i" % (ret, n + 1)
return ret | Concatenate string and zero-padded 4 digit number | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/__init__.py#L57-L67 |
OCR-D/core | ocrd_utils/ocrd_utils/__init__.py | points_from_xywh | def points_from_xywh(box):
"""
Constructs a polygon representation from a rectangle described as a dict with keys x, y, w, h.
"""
x, y, w, h = box['x'], box['y'], box['w'], box['h']
# tesseract uses a different region representation format
return "%i,%i %i,%i %i,%i %i,%i" % (
x, y,
... | python | def points_from_xywh(box):
"""
Constructs a polygon representation from a rectangle described as a dict with keys x, y, w, h.
"""
x, y, w, h = box['x'], box['y'], box['w'], box['h']
# tesseract uses a different region representation format
return "%i,%i %i,%i %i,%i %i,%i" % (
x, y,
... | Constructs a polygon representation from a rectangle described as a dict with keys x, y, w, h. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/__init__.py#L85-L96 |
OCR-D/core | ocrd_utils/ocrd_utils/__init__.py | points_from_y0x0y1x1 | def points_from_y0x0y1x1(yxyx):
"""
Constructs a polygon representation from a rectangle described as a list [y0, x0, y1, x1]
"""
y0 = yxyx[0]
x0 = yxyx[1]
y1 = yxyx[2]
x1 = yxyx[3]
return "%s,%s %s,%s %s,%s %s,%s" % (
x0, y0,
x1, y0,
x1, y1,
x0, y1
) | python | def points_from_y0x0y1x1(yxyx):
"""
Constructs a polygon representation from a rectangle described as a list [y0, x0, y1, x1]
"""
y0 = yxyx[0]
x0 = yxyx[1]
y1 = yxyx[2]
x1 = yxyx[3]
return "%s,%s %s,%s %s,%s %s,%s" % (
x0, y0,
x1, y0,
x1, y1,
x0, y1
) | Constructs a polygon representation from a rectangle described as a list [y0, x0, y1, x1] | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/__init__.py#L98-L111 |
OCR-D/core | ocrd_utils/ocrd_utils/__init__.py | points_from_x0y0x1y1 | def points_from_x0y0x1y1(xyxy):
"""
Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1]
"""
x0 = xyxy[0]
y0 = xyxy[1]
x1 = xyxy[2]
y1 = xyxy[3]
return "%s,%s %s,%s %s,%s %s,%s" % (
x0, y0,
x1, y0,
x1, y1,
x0, y1
) | python | def points_from_x0y0x1y1(xyxy):
"""
Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1]
"""
x0 = xyxy[0]
y0 = xyxy[1]
x1 = xyxy[2]
y1 = xyxy[3]
return "%s,%s %s,%s %s,%s %s,%s" % (
x0, y0,
x1, y0,
x1, y1,
x0, y1
) | Constructs a polygon representation from a rectangle described as a list [x0, y0, x1, y1] | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/__init__.py#L113-L126 |
OCR-D/core | ocrd_utils/ocrd_utils/__init__.py | polygon_from_points | def polygon_from_points(points):
"""
Constructs a numpy-compatible polygon from a page representation.
"""
polygon = []
for pair in points.split(" "):
x_y = pair.split(",")
polygon.append([float(x_y[0]), float(x_y[1])])
return polygon | python | def polygon_from_points(points):
"""
Constructs a numpy-compatible polygon from a page representation.
"""
polygon = []
for pair in points.split(" "):
x_y = pair.split(",")
polygon.append([float(x_y[0]), float(x_y[1])])
return polygon | Constructs a numpy-compatible polygon from a page representation. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/__init__.py#L128-L136 |
OCR-D/core | ocrd_utils/ocrd_utils/__init__.py | unzip_file_to_dir | def unzip_file_to_dir(path_to_zip, output_directory):
"""
Extract a ZIP archive to a directory
"""
z = ZipFile(path_to_zip, 'r')
z.extractall(output_directory)
z.close() | python | def unzip_file_to_dir(path_to_zip, output_directory):
"""
Extract a ZIP archive to a directory
"""
z = ZipFile(path_to_zip, 'r')
z.extractall(output_directory)
z.close() | Extract a ZIP archive to a directory | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/__init__.py#L146-L152 |
OCR-D/core | ocrd_utils/ocrd_utils/__init__.py | xywh_from_points | def xywh_from_points(points):
"""
Constructs an dict representing a rectangle with keys x, y, w, h
"""
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
minx = sys.maxsize
miny = sys.maxsize
maxx = 0
maxy = 0
for xy in xys:
if xy[0] < minx:
m... | python | def xywh_from_points(points):
"""
Constructs an dict representing a rectangle with keys x, y, w, h
"""
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
minx = sys.maxsize
miny = sys.maxsize
maxx = 0
maxy = 0
for xy in xys:
if xy[0] < minx:
m... | Constructs an dict representing a rectangle with keys x, y, w, h | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/__init__.py#L154-L178 |
OCR-D/core | ocrd_validators/ocrd_validators/ocrd_zip_validator.py | OcrdZipValidator._validate_profile | def _validate_profile(self, bag):
"""
Validate against OCRD BagIt profile (bag-info fields, algos etc)
"""
if not self.profile_validator.validate(bag):
raise Exception(str(self.profile_validator.report)) | python | def _validate_profile(self, bag):
"""
Validate against OCRD BagIt profile (bag-info fields, algos etc)
"""
if not self.profile_validator.validate(bag):
raise Exception(str(self.profile_validator.report)) | Validate against OCRD BagIt profile (bag-info fields, algos etc) | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/ocrd_zip_validator.py#L44-L49 |
OCR-D/core | ocrd_validators/ocrd_validators/ocrd_zip_validator.py | OcrdZipValidator._validate_bag | def _validate_bag(self, bag, **kwargs):
"""
Validate BagIt (checksums, payload.oxum etc)
"""
failed = None
try:
bag.validate(**kwargs)
except BagValidationError as e:
failed = e
# for d in e.details:
# if isinstance(d,... | python | def _validate_bag(self, bag, **kwargs):
"""
Validate BagIt (checksums, payload.oxum etc)
"""
failed = None
try:
bag.validate(**kwargs)
except BagValidationError as e:
failed = e
# for d in e.details:
# if isinstance(d,... | Validate BagIt (checksums, payload.oxum etc) | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/ocrd_zip_validator.py#L51-L66 |
OCR-D/core | ocrd_validators/ocrd_validators/ocrd_zip_validator.py | OcrdZipValidator.validate | def validate(self, skip_checksums=False, skip_bag=False, skip_unzip=False, skip_delete=False, processes=2):
"""
Validate an OCRD-ZIP file for profile, bag and workspace conformance
Arguments:
skip_bag (boolean): Whether to skip all checks of manifests and files
skip_chec... | python | def validate(self, skip_checksums=False, skip_bag=False, skip_unzip=False, skip_delete=False, processes=2):
"""
Validate an OCRD-ZIP file for profile, bag and workspace conformance
Arguments:
skip_bag (boolean): Whether to skip all checks of manifests and files
skip_chec... | Validate an OCRD-ZIP file for profile, bag and workspace conformance
Arguments:
skip_bag (boolean): Whether to skip all checks of manifests and files
skip_checksums (boolean): Whether to omit checksum checks but still check basic BagIt conformance
skip_unzip (boolean): Wheth... | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/ocrd_zip_validator.py#L68-L105 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_page_generateds.py | quote_xml | def quote_xml(inStr):
"Escape markup chars, but do not modify CDATA sections."
if not inStr:
return ''
s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
s2 = ''
pos = 0
matchobjects = CDATA_pattern_.finditer(s1)
for mo in matchobjects:
s3 = s1[pos:mo.start()]
... | python | def quote_xml(inStr):
"Escape markup chars, but do not modify CDATA sections."
if not inStr:
return ''
s1 = (isinstance(inStr, BaseStrType_) and inStr or '%s' % inStr)
s2 = ''
pos = 0
matchobjects = CDATA_pattern_.finditer(s1)
for mo in matchobjects:
s3 = s1[pos:mo.start()]
... | Escape markup chars, but do not modify CDATA sections. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_page_generateds.py#L478-L493 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_page_generateds.py | parseString | def parseString(inString, silence=False):
'''Parse a string, create the object tree, and export it.
Arguments:
- inString -- A string. This XML fragment should not start
with an XML declaration containing an encoding.
- silence -- A boolean. If False, export the object.
Returns -- The root ... | python | def parseString(inString, silence=False):
'''Parse a string, create the object tree, and export it.
Arguments:
- inString -- A string. This XML fragment should not start
with an XML declaration containing an encoding.
- silence -- A boolean. If False, export the object.
Returns -- The root ... | Parse a string, create the object tree, and export it.
Arguments:
- inString -- A string. This XML fragment should not start
with an XML declaration containing an encoding.
- silence -- A boolean. If False, export the object.
Returns -- The root object in the tree. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_page_generateds.py#L9470-L9493 |
OCR-D/core | ocrd/ocrd/cli/ocrd_tool.py | ocrd_tool_tool_parse_params | def ocrd_tool_tool_parse_params(ctx, parameters, json):
"""
Parse parameters with fallback to defaults and output as shell-eval'able assignments to params var.
"""
if parameters is None or parameters == "":
parameters = {}
else:
with open(parameters, 'r') as f:
parameters... | python | def ocrd_tool_tool_parse_params(ctx, parameters, json):
"""
Parse parameters with fallback to defaults and output as shell-eval'able assignments to params var.
"""
if parameters is None or parameters == "":
parameters = {}
else:
with open(parameters, 'r') as f:
parameters... | Parse parameters with fallback to defaults and output as shell-eval'able assignments to params var. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/ocrd_tool.py#L117-L135 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_agent.py | OcrdAgent.othertype | def othertype(self, othertype):
"""
Set the ``OTHERTYPE`` attribute value.
"""
if othertype is not None:
self._el.set('TYPE', 'OTHER')
self._el.set('OTHERTYPE', othertype) | python | def othertype(self, othertype):
"""
Set the ``OTHERTYPE`` attribute value.
"""
if othertype is not None:
self._el.set('TYPE', 'OTHER')
self._el.set('OTHERTYPE', othertype) | Set the ``OTHERTYPE`` attribute value. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_agent.py#L75-L81 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_agent.py | OcrdAgent.otherrole | def otherrole(self, otherrole):
"""
Get the ``OTHERROLE`` attribute value.
"""
if otherrole is not None:
self._el.set('ROLE', 'OTHER')
self._el.set('OTHERROLE', otherrole) | python | def otherrole(self, otherrole):
"""
Get the ``OTHERROLE`` attribute value.
"""
if otherrole is not None:
self._el.set('ROLE', 'OTHER')
self._el.set('OTHERROLE', otherrole) | Get the ``OTHERROLE`` attribute value. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_agent.py#L106-L112 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_agent.py | OcrdAgent.name | def name(self):
"""
Get the ``mets:name`` element value.
"""
el_name = self._el.find('mets:name', NS)
if el_name is not None:
return el_name.text | python | def name(self):
"""
Get the ``mets:name`` element value.
"""
el_name = self._el.find('mets:name', NS)
if el_name is not None:
return el_name.text | Get the ``mets:name`` element value. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_agent.py#L115-L121 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_agent.py | OcrdAgent.name | def name(self, name):
"""
Get the ``mets:name`` element value.
"""
if name is not None:
el_name = self._el.find('mets:name', NS)
if el_name is None:
el_name = ET.SubElement(self._el, TAG_METS_NAME)
el_name.text = name | python | def name(self, name):
"""
Get the ``mets:name`` element value.
"""
if name is not None:
el_name = self._el.find('mets:name', NS)
if el_name is None:
el_name = ET.SubElement(self._el, TAG_METS_NAME)
el_name.text = name | Get the ``mets:name`` element value. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_agent.py#L124-L132 |
OCR-D/core | ocrd_validators/ocrd_validators/parameter_validator.py | ParameterValidator.validate | def validate(self, *args, **kwargs): # pylint: disable=arguments-differ
"""
Validate a parameter dict against a parameter schema from an ocrd-tool.json
Args:
obj (dict):
schema (dict):
"""
return super(ParameterValidator, self)._validate(*args, **kwargs) | python | def validate(self, *args, **kwargs): # pylint: disable=arguments-differ
"""
Validate a parameter dict against a parameter schema from an ocrd-tool.json
Args:
obj (dict):
schema (dict):
"""
return super(ParameterValidator, self)._validate(*args, **kwargs) | Validate a parameter dict against a parameter schema from an ocrd-tool.json
Args:
obj (dict):
schema (dict): | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/parameter_validator.py#L15-L23 |
OCR-D/core | ocrd_validators/ocrd_validators/page_validator.py | handle_inconsistencies | def handle_inconsistencies(node, strictness, strategy, report):
"""
Check whether the text results on an element is consistent with its child element text results.
"""
if isinstance(node, PcGtsType):
node = node.get_Page()
elif isinstance(node, GlyphType):
return report
_, tag, ... | python | def handle_inconsistencies(node, strictness, strategy, report):
"""
Check whether the text results on an element is consistent with its child element text results.
"""
if isinstance(node, PcGtsType):
node = node.get_Page()
elif isinstance(node, GlyphType):
return report
_, tag, ... | Check whether the text results on an element is consistent with its child element text results. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/page_validator.py#L58-L90 |
OCR-D/core | ocrd_validators/ocrd_validators/page_validator.py | concatenate_children | def concatenate_children(node, concatenate_with, strategy):
"""
Concatenate children of node according to https://ocr-d.github.io/page#consistency-of-text-results-on-different-levels
"""
_, _, getter, concatenate_with = [x for x in _HIERARCHY if isinstance(node, x[0])][0]
tokens = [get_text(x, strat... | python | def concatenate_children(node, concatenate_with, strategy):
"""
Concatenate children of node according to https://ocr-d.github.io/page#consistency-of-text-results-on-different-levels
"""
_, _, getter, concatenate_with = [x for x in _HIERARCHY if isinstance(node, x[0])][0]
tokens = [get_text(x, strat... | Concatenate children of node according to https://ocr-d.github.io/page#consistency-of-text-results-on-different-levels | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/page_validator.py#L92-L98 |
OCR-D/core | ocrd_validators/ocrd_validators/page_validator.py | get_text | def get_text(node, strategy):
"""
Get the most confident text results, either those with @index = 1 or the first text results or empty string.
"""
textEquivs = node.get_TextEquiv()
if not textEquivs:
log.debug("No text results on %s %s", node, node.id)
return ''
# elif strategy ... | python | def get_text(node, strategy):
"""
Get the most confident text results, either those with @index = 1 or the first text results or empty string.
"""
textEquivs = node.get_TextEquiv()
if not textEquivs:
log.debug("No text results on %s %s", node, node.id)
return ''
# elif strategy ... | Get the most confident text results, either those with @index = 1 or the first text results or empty string. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/page_validator.py#L100-L114 |
OCR-D/core | ocrd_validators/ocrd_validators/page_validator.py | set_text | def set_text(node, text, strategy):
"""
Set the most confident text results, either those with @index = 1, the first text results or add new one.
"""
text = text.strip()
textEquivs = node.get_TextEquiv()
if not textEquivs:
node.add_TextEquiv(TextEquivType(Unicode=text))
# elif strat... | python | def set_text(node, text, strategy):
"""
Set the most confident text results, either those with @index = 1, the first text results or add new one.
"""
text = text.strip()
textEquivs = node.get_TextEquiv()
if not textEquivs:
node.add_TextEquiv(TextEquivType(Unicode=text))
# elif strat... | Set the most confident text results, either those with @index = 1, the first text results or add new one. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/page_validator.py#L116-L131 |
OCR-D/core | ocrd_validators/ocrd_validators/page_validator.py | PageValidator.validate | def validate(filename=None, ocrd_page=None, ocrd_file=None, strictness='strict', strategy='index1'):
"""
Validates a PAGE file for consistency by filename, OcrdFile or passing OcrdPage directly.
Arguments:
filename (string): Path to PAGE
ocrd_page (OcrdPage): OcrdPage in... | python | def validate(filename=None, ocrd_page=None, ocrd_file=None, strictness='strict', strategy='index1'):
"""
Validates a PAGE file for consistency by filename, OcrdFile or passing OcrdPage directly.
Arguments:
filename (string): Path to PAGE
ocrd_page (OcrdPage): OcrdPage in... | Validates a PAGE file for consistency by filename, OcrdFile or passing OcrdPage directly.
Arguments:
filename (string): Path to PAGE
ocrd_page (OcrdPage): OcrdPage instance
ocrd_file (OcrdFile): OcrdFile instance wrapping OcrdPage
strictness (string): 'strict', '... | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/page_validator.py#L139-L161 |
OCR-D/core | ocrd_validators/ocrd_validators/page_validator.py | PageValidator._validate | def _validate(self):
"""
Do the actual validation
"""
if self.strictness == 'off':
return self.report
handle_inconsistencies(self.page, self.strictness, self.strategy, self.report)
return self.report | python | def _validate(self):
"""
Do the actual validation
"""
if self.strictness == 'off':
return self.report
handle_inconsistencies(self.page, self.strictness, self.strategy, self.report)
return self.report | Do the actual validation | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/page_validator.py#L177-L184 |
OCR-D/core | ocrd/ocrd/decorators.py | ocrd_cli_options | def ocrd_cli_options(f):
"""
Implement MP CLI.
Usage::
import ocrd_click_cli from ocrd.utils
@click.command()
@ocrd_click_cli
def cli(mets_url):
print(mets_url)
"""
params = [
click.option('-m', '--mets', help="METS URL to validate"),
cl... | python | def ocrd_cli_options(f):
"""
Implement MP CLI.
Usage::
import ocrd_click_cli from ocrd.utils
@click.command()
@ocrd_click_cli
def cli(mets_url):
print(mets_url)
"""
params = [
click.option('-m', '--mets', help="METS URL to validate"),
cl... | Implement MP CLI.
Usage::
import ocrd_click_cli from ocrd.utils
@click.command()
@ocrd_click_cli
def cli(mets_url):
print(mets_url) | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/decorators.py#L47-L73 |
OCR-D/core | ocrd_validators/ocrd_validators/report.py | ValidationReport.to_xml | def to_xml(self):
"""
Serialize to XML.
"""
body = ''
for k in ['warning', 'error', 'notice']:
for msg in self.__dict__[k + 's']:
body += '\n <%s>%s</%s>' % (k, msg, k)
return '<report valid="%s">%s\n</report>' % ("true" if self.is_valid else ... | python | def to_xml(self):
"""
Serialize to XML.
"""
body = ''
for k in ['warning', 'error', 'notice']:
for msg in self.__dict__[k + 's']:
body += '\n <%s>%s</%s>' % (k, msg, k)
return '<report valid="%s">%s\n</report>' % ("true" if self.is_valid else ... | Serialize to XML. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/report.py#L46-L54 |
OCR-D/core | ocrd_validators/ocrd_validators/report.py | ValidationReport.merge_report | def merge_report(self, otherself):
"""
Merge another report into this one.
"""
self.notices += otherself.notices
self.warnings += otherself.warnings
self.errors += otherself.errors | python | def merge_report(self, otherself):
"""
Merge another report into this one.
"""
self.notices += otherself.notices
self.warnings += otherself.warnings
self.errors += otherself.errors | Merge another report into this one. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_validators/ocrd_validators/report.py#L74-L80 |
OCR-D/core | ocrd/ocrd/cli/process.py | process_cli | def process_cli(log_level, mets, page_id, tasks):
"""
Process a series of tasks
"""
log = getLogger('ocrd.cli.process')
run_tasks(mets, log_level, page_id, tasks)
log.info("Finished") | python | def process_cli(log_level, mets, page_id, tasks):
"""
Process a series of tasks
"""
log = getLogger('ocrd.cli.process')
run_tasks(mets, log_level, page_id, tasks)
log.info("Finished") | Process a series of tasks | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/process.py#L20-L27 |
OCR-D/core | ocrd/ocrd/cli/zip.py | bag | def bag(directory, mets_basename, dest, identifier, in_place, manifestation_depth, mets, base_version_checksum, tag_file, skip_zip, processes):
"""
Bag workspace as OCRD-ZIP at DEST
"""
resolver = Resolver()
workspace = Workspace(resolver, directory=directory, mets_basename=mets_basename)
worksp... | python | def bag(directory, mets_basename, dest, identifier, in_place, manifestation_depth, mets, base_version_checksum, tag_file, skip_zip, processes):
"""
Bag workspace as OCRD-ZIP at DEST
"""
resolver = Resolver()
workspace = Workspace(resolver, directory=directory, mets_basename=mets_basename)
worksp... | Bag workspace as OCRD-ZIP at DEST | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/zip.py#L40-L58 |
OCR-D/core | ocrd/ocrd/cli/zip.py | spill | def spill(directory, src):
"""
Spill/unpack OCRD-ZIP bag at SRC to DEST
SRC must exist an be an OCRD-ZIP
DEST must not exist and be a directory
"""
resolver = Resolver()
workspace_bagger = WorkspaceBagger(resolver)
workspace = workspace_bagger.spill(src, directory)
print(workspace) | python | def spill(directory, src):
"""
Spill/unpack OCRD-ZIP bag at SRC to DEST
SRC must exist an be an OCRD-ZIP
DEST must not exist and be a directory
"""
resolver = Resolver()
workspace_bagger = WorkspaceBagger(resolver)
workspace = workspace_bagger.spill(src, directory)
print(workspace) | Spill/unpack OCRD-ZIP bag at SRC to DEST
SRC must exist an be an OCRD-ZIP
DEST must not exist and be a directory | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/zip.py#L71-L81 |
OCR-D/core | ocrd/ocrd/cli/zip.py | validate | def validate(src, **kwargs):
"""
Validate OCRD-ZIP
SRC must exist an be an OCRD-ZIP, either a ZIP file or a directory.
"""
resolver = Resolver()
validator = OcrdZipValidator(resolver, src)
report = validator.validate(**kwargs)
print(report)
if not report.is_valid:
sys.exit(1... | python | def validate(src, **kwargs):
"""
Validate OCRD-ZIP
SRC must exist an be an OCRD-ZIP, either a ZIP file or a directory.
"""
resolver = Resolver()
validator = OcrdZipValidator(resolver, src)
report = validator.validate(**kwargs)
print(report)
if not report.is_valid:
sys.exit(1... | Validate OCRD-ZIP
SRC must exist an be an OCRD-ZIP, either a ZIP file or a directory. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/cli/zip.py#L94-L105 |
OCR-D/core | ocrd/ocrd/workspace_backup.py | WorkspaceBackupManager.restore | def restore(self, chksum, choose_first=False):
"""
Restore mets.xml to previous state
"""
log = getLogger('ocrd.workspace_backup.restore')
bak = None
candidates = glob(join(self.backup_directory, '%s*' % chksum))
if not candidates:
log.error("No backup... | python | def restore(self, chksum, choose_first=False):
"""
Restore mets.xml to previous state
"""
log = getLogger('ocrd.workspace_backup.restore')
bak = None
candidates = glob(join(self.backup_directory, '%s*' % chksum))
if not candidates:
log.error("No backup... | Restore mets.xml to previous state | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace_backup.py#L49-L68 |
OCR-D/core | ocrd/ocrd/workspace_backup.py | WorkspaceBackupManager.add | def add(self):
"""
Create a backup in <self.backup_directory>
"""
log = getLogger('ocrd.workspace_backup.add')
mets_str = self.workspace.mets.to_xml()
chksum = _chksum(mets_str)
backups = self.list()
if backups and backups[0].chksum == chksum:
... | python | def add(self):
"""
Create a backup in <self.backup_directory>
"""
log = getLogger('ocrd.workspace_backup.add')
mets_str = self.workspace.mets.to_xml()
chksum = _chksum(mets_str)
backups = self.list()
if backups and backups[0].chksum == chksum:
... | Create a backup in <self.backup_directory> | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace_backup.py#L70-L88 |
OCR-D/core | ocrd/ocrd/workspace_backup.py | WorkspaceBackupManager.list | def list(self):
"""
List all backups as WorkspaceBackup objects, sorted descending by lastmod.
"""
backups = []
for d in glob(join(self.backup_directory, '*')):
backups.append(WorkspaceBackup.from_path(d))
backups.sort(key=lambda b: b.lastmod, reverse=True)
... | python | def list(self):
"""
List all backups as WorkspaceBackup objects, sorted descending by lastmod.
"""
backups = []
for d in glob(join(self.backup_directory, '*')):
backups.append(WorkspaceBackup.from_path(d))
backups.sort(key=lambda b: b.lastmod, reverse=True)
... | List all backups as WorkspaceBackup objects, sorted descending by lastmod. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace_backup.py#L90-L98 |
OCR-D/core | ocrd/ocrd/workspace_backup.py | WorkspaceBackupManager.undo | def undo(self):
"""
Restore to last version
"""
log = getLogger('ocrd.workspace_backup.undo')
backups = self.list()
if backups:
last_backup = backups[0]
self.restore(last_backup.chksum, choose_first=True)
else:
log.info("No back... | python | def undo(self):
"""
Restore to last version
"""
log = getLogger('ocrd.workspace_backup.undo')
backups = self.list()
if backups:
last_backup = backups[0]
self.restore(last_backup.chksum, choose_first=True)
else:
log.info("No back... | Restore to last version | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace_backup.py#L100-L110 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_page.py | to_xml | def to_xml(el):
"""
Serialize ``pc:PcGts`` document
"""
sio = StringIO()
el.export(sio, 0, name_='PcGts', namespacedef_='xmlns:pc="%s"' % NAMESPACES['page'])
return '<?xml version="1.0" encoding="UTF-8"?>\n' + sio.getvalue() | python | def to_xml(el):
"""
Serialize ``pc:PcGts`` document
"""
sio = StringIO()
el.export(sio, 0, name_='PcGts', namespacedef_='xmlns:pc="%s"' % NAMESPACES['page'])
return '<?xml version="1.0" encoding="UTF-8"?>\n' + sio.getvalue() | Serialize ``pc:PcGts`` document | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_page.py#L56-L62 |
OCR-D/core | ocrd_utils/ocrd_utils/logging.py | getLevelName | def getLevelName(lvl):
"""
Get (numerical) python logging level for (string) spec-defined log level name.
"""
lvl = _ocrdLevel2pythonLevel.get(lvl, lvl)
return logging.getLevelName(lvl) | python | def getLevelName(lvl):
"""
Get (numerical) python logging level for (string) spec-defined log level name.
"""
lvl = _ocrdLevel2pythonLevel.get(lvl, lvl)
return logging.getLevelName(lvl) | Get (numerical) python logging level for (string) spec-defined log level name. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/logging.py#L36-L41 |
OCR-D/core | ocrd_utils/ocrd_utils/logging.py | setOverrideLogLevel | def setOverrideLogLevel(lvl):
"""
Override all logger filter levels to include lvl and above.
- Set root logger level
- iterates all existing loggers and sets their log level to ``NOTSET``.
Args:
lvl (string): Log level name.
"""
if lvl is None:
return
logging.info('Ov... | python | def setOverrideLogLevel(lvl):
"""
Override all logger filter levels to include lvl and above.
- Set root logger level
- iterates all existing loggers and sets their log level to ``NOTSET``.
Args:
lvl (string): Log level name.
"""
if lvl is None:
return
logging.info('Ov... | Override all logger filter levels to include lvl and above.
- Set root logger level
- iterates all existing loggers and sets their log level to ``NOTSET``.
Args:
lvl (string): Log level name. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/logging.py#L43-L65 |
OCR-D/core | ocrd_utils/ocrd_utils/logging.py | getLogger | def getLogger(*args, **kwargs):
"""
Wrapper around ``logging.getLogger`` that respects `overrideLogLevel <#setOverrideLogLevel>`_.
"""
logger = logging.getLogger(*args, **kwargs)
if _overrideLogLevel is not None:
logger.setLevel(logging.NOTSET)
return logger | python | def getLogger(*args, **kwargs):
"""
Wrapper around ``logging.getLogger`` that respects `overrideLogLevel <#setOverrideLogLevel>`_.
"""
logger = logging.getLogger(*args, **kwargs)
if _overrideLogLevel is not None:
logger.setLevel(logging.NOTSET)
return logger | Wrapper around ``logging.getLogger`` that respects `overrideLogLevel <#setOverrideLogLevel>`_. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/logging.py#L67-L74 |
OCR-D/core | ocrd_utils/ocrd_utils/logging.py | initLogging | def initLogging():
"""
Sets logging defaults
"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s.%(msecs)03d %(levelname)s %(name)s - %(message)s',
datefmt='%H:%M:%S')
logging.getLogger('').setLevel(logging.INFO)
# logging.getLogger('ocrd.resolver').setLevel... | python | def initLogging():
"""
Sets logging defaults
"""
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s.%(msecs)03d %(levelname)s %(name)s - %(message)s',
datefmt='%H:%M:%S')
logging.getLogger('').setLevel(logging.INFO)
# logging.getLogger('ocrd.resolver').setLevel... | Sets logging defaults | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_utils/ocrd_utils/logging.py#L78-L107 |
OCR-D/core | ocrd/ocrd/workspace_bagger.py | WorkspaceBagger.bag | def bag(self,
workspace,
ocrd_identifier,
dest=None,
ocrd_mets='mets.xml',
ocrd_manifestation_depth='full',
ocrd_base_version_checksum=None,
processes=1,
skip_zip=False,
in_place=False,
tag_files=None... | python | def bag(self,
workspace,
ocrd_identifier,
dest=None,
ocrd_mets='mets.xml',
ocrd_manifestation_depth='full',
ocrd_base_version_checksum=None,
processes=1,
skip_zip=False,
in_place=False,
tag_files=None... | Bag a workspace
See https://ocr-d.github.com/ocrd_zip#packing-a-workspace-as-ocrd-zip
Arguments:
workspace (ocrd.Workspace): workspace to bag
ord_identifier (string): Ocrd-Identifier in bag-info.txt
dest (string): Path of the generated OCRD-ZIP.
ord_mets... | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace_bagger.py#L104-L180 |
OCR-D/core | ocrd/ocrd/workspace_bagger.py | WorkspaceBagger.spill | def spill(self, src, dest):
"""
Spill a workspace, i.e. unpack it and turn it into a workspace.
See https://ocr-d.github.com/ocrd_zip#unpacking-ocrd-zip-to-a-workspace
Arguments:
src (string): Path to OCRD-ZIP
dest (string): Path to directory to unpack data fold... | python | def spill(self, src, dest):
"""
Spill a workspace, i.e. unpack it and turn it into a workspace.
See https://ocr-d.github.com/ocrd_zip#unpacking-ocrd-zip-to-a-workspace
Arguments:
src (string): Path to OCRD-ZIP
dest (string): Path to directory to unpack data fold... | Spill a workspace, i.e. unpack it and turn it into a workspace.
See https://ocr-d.github.com/ocrd_zip#unpacking-ocrd-zip-to-a-workspace
Arguments:
src (string): Path to OCRD-ZIP
dest (string): Path to directory to unpack data folder to | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace_bagger.py#L182-L233 |
OCR-D/core | ocrd/ocrd/workspace.py | Workspace.download_url | def download_url(self, url, **kwargs):
"""
Download a URL to the workspace.
Args:
url (string): URL to download to directory
**kwargs : See :py:mod:`ocrd.resolver.Resolver`
Returns:
The local filename of the downloaded file
"""
if sel... | python | def download_url(self, url, **kwargs):
"""
Download a URL to the workspace.
Args:
url (string): URL to download to directory
**kwargs : See :py:mod:`ocrd.resolver.Resolver`
Returns:
The local filename of the downloaded file
"""
if sel... | Download a URL to the workspace.
Args:
url (string): URL to download to directory
**kwargs : See :py:mod:`ocrd.resolver.Resolver`
Returns:
The local filename of the downloaded file | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace.py#L58-L71 |
OCR-D/core | ocrd/ocrd/workspace.py | Workspace.download_file | def download_file(self, f):
"""
Download a :py:mod:`ocrd.model.ocrd_file.OcrdFile` to the workspace.
"""
# os.chdir(self.directory)
# log.info('f=%s' % f)
oldpwd = os.getcwd()
try:
os.chdir(self.directory)
if is_local_filename(f.url):
... | python | def download_file(self, f):
"""
Download a :py:mod:`ocrd.model.ocrd_file.OcrdFile` to the workspace.
"""
# os.chdir(self.directory)
# log.info('f=%s' % f)
oldpwd = os.getcwd()
try:
os.chdir(self.directory)
if is_local_filename(f.url):
... | Download a :py:mod:`ocrd.model.ocrd_file.OcrdFile` to the workspace. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace.py#L73-L93 |
OCR-D/core | ocrd/ocrd/workspace.py | Workspace.add_file | def add_file(self, file_grp, content=None, **kwargs):
"""
Add an output file. Creates an :class:`OcrdFile` to pass around and adds that to the
OcrdMets OUTPUT section.
"""
log.debug(
'outputfile file_grp=%s local_filename=%s content=%s',
file_grp,
... | python | def add_file(self, file_grp, content=None, **kwargs):
"""
Add an output file. Creates an :class:`OcrdFile` to pass around and adds that to the
OcrdMets OUTPUT section.
"""
log.debug(
'outputfile file_grp=%s local_filename=%s content=%s',
file_grp,
... | Add an output file. Creates an :class:`OcrdFile` to pass around and adds that to the
OcrdMets OUTPUT section. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace.py#L95-L129 |
OCR-D/core | ocrd/ocrd/workspace.py | Workspace.save_mets | def save_mets(self):
"""
Write out the current state of the METS file.
"""
log.info("Saving mets '%s'" % self.mets_target)
if self.automatic_backup:
WorkspaceBackupManager(self).add()
with open(self.mets_target, 'wb') as f:
f.write(self.mets.to_xml... | python | def save_mets(self):
"""
Write out the current state of the METS file.
"""
log.info("Saving mets '%s'" % self.mets_target)
if self.automatic_backup:
WorkspaceBackupManager(self).add()
with open(self.mets_target, 'wb') as f:
f.write(self.mets.to_xml... | Write out the current state of the METS file. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace.py#L131-L139 |
OCR-D/core | ocrd/ocrd/workspace.py | Workspace.resolve_image_exif | def resolve_image_exif(self, image_url):
"""
Get the EXIF metadata about an image URL as :class:`OcrdExif`
Args:
image_url (string) : URL of image
Return
:class:`OcrdExif`
"""
files = self.mets.find_files(url=image_url)
if files:
... | python | def resolve_image_exif(self, image_url):
"""
Get the EXIF metadata about an image URL as :class:`OcrdExif`
Args:
image_url (string) : URL of image
Return
:class:`OcrdExif`
"""
files = self.mets.find_files(url=image_url)
if files:
... | Get the EXIF metadata about an image URL as :class:`OcrdExif`
Args:
image_url (string) : URL of image
Return
:class:`OcrdExif` | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace.py#L141-L159 |
OCR-D/core | ocrd/ocrd/workspace.py | Workspace.resolve_image_as_pil | def resolve_image_as_pil(self, image_url, coords=None):
"""
Resolve an image URL to a PIL image.
Args:
coords (list) : Coordinates of the bounding box to cut from the image
Returns:
Image or region in image as PIL.Image
"""
files = self.mets.find... | python | def resolve_image_as_pil(self, image_url, coords=None):
"""
Resolve an image URL to a PIL image.
Args:
coords (list) : Coordinates of the bounding box to cut from the image
Returns:
Image or region in image as PIL.Image
"""
files = self.mets.find... | Resolve an image URL to a PIL image.
Args:
coords (list) : Coordinates of the bounding box to cut from the image
Returns:
Image or region in image as PIL.Image | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd/ocrd/workspace.py#L161-L196 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_exif.py | OcrdExif.to_xml | def to_xml(self):
"""
Serialize all properties as XML
"""
ret = '<exif>'
for k in self.__dict__:
ret += '<%s>%s</%s>' % (k, self.__dict__[k], k)
ret += '</exif>'
return ret | python | def to_xml(self):
"""
Serialize all properties as XML
"""
ret = '<exif>'
for k in self.__dict__:
ret += '<%s>%s</%s>' % (k, self.__dict__[k], k)
ret += '</exif>'
return ret | Serialize all properties as XML | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_exif.py#L42-L50 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_file.py | OcrdFile.basename_without_extension | def basename_without_extension(self):
"""
Get the ``os.path.basename`` of the local file, if any, with extension removed.
"""
ret = self.basename.rsplit('.', 1)[0]
if ret.endswith('.tar'):
ret = ret[0:len(ret)-4]
return ret | python | def basename_without_extension(self):
"""
Get the ``os.path.basename`` of the local file, if any, with extension removed.
"""
ret = self.basename.rsplit('.', 1)[0]
if ret.endswith('.tar'):
ret = ret[0:len(ret)-4]
return ret | Get the ``os.path.basename`` of the local file, if any, with extension removed. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_file.py#L61-L68 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_file.py | OcrdFile.pageId | def pageId(self):
"""
Get the ID of the physical page this file manifests.
"""
if self.mets is None:
raise Exception("OcrdFile %s has no member 'mets' pointing to parent OcrdMets" % self)
return self.mets.get_physical_page_for_file(self) | python | def pageId(self):
"""
Get the ID of the physical page this file manifests.
"""
if self.mets is None:
raise Exception("OcrdFile %s has no member 'mets' pointing to parent OcrdMets" % self)
return self.mets.get_physical_page_for_file(self) | Get the ID of the physical page this file manifests. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_file.py#L87-L93 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_file.py | OcrdFile.pageId | def pageId(self, pageId):
"""
Set the ID of the physical page this file manifests.
"""
if pageId is None:
return
if self.mets is None:
raise Exception("OcrdFile %s has no member 'mets' pointing to parent OcrdMets" % self)
self.mets.set_physical_pag... | python | def pageId(self, pageId):
"""
Set the ID of the physical page this file manifests.
"""
if pageId is None:
return
if self.mets is None:
raise Exception("OcrdFile %s has no member 'mets' pointing to parent OcrdMets" % self)
self.mets.set_physical_pag... | Set the ID of the physical page this file manifests. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_file.py#L96-L104 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_file.py | OcrdFile.url | def url(self):
"""
Get the ``xlink:href`` of this file.
"""
el_FLocat = self._el.find(TAG_METS_FLOCAT)
if el_FLocat is not None:
return el_FLocat.get("{%s}href" % NS["xlink"])
return '' | python | def url(self):
"""
Get the ``xlink:href`` of this file.
"""
el_FLocat = self._el.find(TAG_METS_FLOCAT)
if el_FLocat is not None:
return el_FLocat.get("{%s}href" % NS["xlink"])
return '' | Get the ``xlink:href`` of this file. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_file.py#L131-L138 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_file.py | OcrdFile.url | def url(self, url):
"""
Set the ``xlink:href`` of this file.
"""
if url is None:
return
el_FLocat = self._el.find('mets:FLocat', NS)
if el_FLocat is None:
el_FLocat = ET.SubElement(self._el, TAG_METS_FLOCAT)
el_FLocat.set("{%s}href" % NS["x... | python | def url(self, url):
"""
Set the ``xlink:href`` of this file.
"""
if url is None:
return
el_FLocat = self._el.find('mets:FLocat', NS)
if el_FLocat is None:
el_FLocat = ET.SubElement(self._el, TAG_METS_FLOCAT)
el_FLocat.set("{%s}href" % NS["x... | Set the ``xlink:href`` of this file. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_file.py#L141-L150 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.empty_mets | def empty_mets():
"""
Create an empty METS file from bundled template.
"""
tpl = METS_XML_EMPTY.decode('utf-8')
tpl = tpl.replace('{{ VERSION }}', VERSION)
tpl = tpl.replace('{{ NOW }}', '%s' % datetime.now())
return OcrdMets(content=tpl.encode('utf-8')) | python | def empty_mets():
"""
Create an empty METS file from bundled template.
"""
tpl = METS_XML_EMPTY.decode('utf-8')
tpl = tpl.replace('{{ VERSION }}', VERSION)
tpl = tpl.replace('{{ NOW }}', '%s' % datetime.now())
return OcrdMets(content=tpl.encode('utf-8')) | Create an empty METS file from bundled template. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L33-L40 |
OCR-D/core | ocrd_models/ocrd_models/ocrd_mets.py | OcrdMets.unique_identifier | def unique_identifier(self):
"""
Get the unique identifier by looking through ``mods:identifier``
See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details.
"""
for t in IDENTIFIER_PRIORITY:
found = self._tree.getroot().find('.//mod... | python | def unique_identifier(self):
"""
Get the unique identifier by looking through ``mods:identifier``
See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details.
"""
for t in IDENTIFIER_PRIORITY:
found = self._tree.getroot().find('.//mod... | Get the unique identifier by looking through ``mods:identifier``
See `specs <https://ocr-d.github.io/mets#unique-id-for-the-document-processed>`_ for details. | https://github.com/OCR-D/core/blob/57e68c578526cb955fd2e368207f5386c459d91d/ocrd_models/ocrd_models/ocrd_mets.py#L60-L69 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.