code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def sort_constraints(constraints):
"""
Return a sorted sequence of unique GemConstraints.
"""
constraints = sorted(constraints, key=lambda gc: (gc.version, gc.op))
consts = []
for gc in constraints:
if gc in consts:
continue
consts.append(gc)
return consts |
Return a sorted sequence of unique GemConstraints.
| sort_constraints | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def tilde_comparator(version, requirement, trace=False):
"""
Return True if ``version`` GemVersion satisfies ``requirement`` GemVersion
according to the Rubygems tilde semantics.
"""
if trace:
print(f" tilde_comparator: version: {version!r}, requirement: {requirement!r}")
print(... |
Return True if ``version`` GemVersion satisfies ``requirement`` GemVersion
according to the Rubygems tilde semantics.
| tilde_comparator | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def __init__(self, *requirements):
"""
Initialize a GemRequirement from a sequence of ``requirements``
converted to a constraints sequence of GemConstraint.
"""
if not requirements:
self.constraints = (GemRequirement.DEFAULT_CONSTRAINT,)
else:
self... |
Initialize a GemRequirement from a sequence of ``requirements``
converted to a constraints sequence of GemConstraint.
| __init__ | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def from_string(cls, requirements):
"""
Return a GemRequirement build from a lockfile-style ``requirements``
string.
For example::
>>> gr1 = GemRequirement(">= 1.0.1", "~> 1.0")
>>> gr2 = GemRequirement.from_string(" (>= 1.0.1, ~> 1.0)")
>>> assert gr1 == gr2, (g... |
Return a GemRequirement build from a lockfile-style ``requirements``
string.
For example::
>>> gr1 = GemRequirement(">= 1.0.1", "~> 1.0")
>>> gr2 = GemRequirement.from_string(" (>= 1.0.1, ~> 1.0)")
>>> assert gr1 == gr2, (gr1, gr2)
| from_string | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def for_lockfile(self):
"""
Return a string representing this list of requirements suitable for use
in a lockfile.
For example::
>>> gr = GemRequirement(">= 1.0.1", "~> 1.0")
>>> gf_flf = gr.for_lockfile()
>>> assert gf_flf == " (~> 1.0, >= 1.0.1)", gf_flf
... |
Return a string representing this list of requirements suitable for use
in a lockfile.
For example::
>>> gr = GemRequirement(">= 1.0.1", "~> 1.0")
>>> gf_flf = gr.for_lockfile()
>>> assert gf_flf == " (~> 1.0, >= 1.0.1)", gf_flf
| for_lockfile | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def simplify(self):
"""
Return a new simplified GemRequirement with:
- sorted and unique constraints.
- where ~> constraints are replaced by simpler contrainsts.
"""
constraints = []
for const in self.constraints:
if const.op == "~>":
l... |
Return a new simplified GemRequirement with:
- sorted and unique constraints.
- where ~> constraints are replaced by simpler contrainsts.
| simplify | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def create(cls, reqs):
"""
Return a GemRequirement built from a single requirement string or a list
of requirement strings.
"""
if isinstance(reqs, list):
return cls(*reqs)
else:
return cls(reqs) |
Return a GemRequirement built from a single requirement string or a list
of requirement strings.
| create | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def parse(cls, requirement):
"""
Return a GemConstraint tuple of (operator string, GemVersion object)
parsed from a single ``requirement`` string such as "> 3.0". Also
accepts a two-tuple or list of ("op", "version") or a single GemVersion or a
GemConstraint).
"""
... |
Return a GemConstraint tuple of (operator string, GemVersion object)
parsed from a single ``requirement`` string such as "> 3.0". Also
accepts a two-tuple or list of ("op", "version") or a single GemVersion or a
GemConstraint).
| parse | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def satisfied_by(self, version, trace=False):
"""
Return True if the ``version`` GemVersion or version string or int
satisfies all the constraints of this requirement. Raise an
InvalidVersionError with an invalid ``version``.
"""
if trace:
print(f"\nis {self!r... |
Return True if the ``version`` GemVersion or version string or int
satisfies all the constraints of this requirement. Raise an
InvalidVersionError with an invalid ``version``.
| satisfied_by | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def tilde_requirements(self):
"""
Return a sorted sequence of all pessimistic "~>" GemConstraint.
"""
constraints = sort_constraints(self.constraints)
return [gc for gc in constraints if gc.op == "~>"] |
Return a sorted sequence of all pessimistic "~>" GemConstraint.
| tilde_requirements | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def get_tilde_constraints(constraint):
"""
Return a tuple of two GemConstraint representing the lower and upper
bound of a version range ``string`` that uses a tilde "~>" pessimistic operator.
Raise a ValueError if this is not a tilde range.
For example:
>>> lower_bound, upper_bound = get_tilde... |
Return a tuple of two GemConstraint representing the lower and upper
bound of a version range ``string`` that uses a tilde "~>" pessimistic operator.
Raise a ValueError if this is not a tilde range.
For example:
>>> lower_bound, upper_bound = get_tilde_constraints(GemConstraint("~>", GemVersion("1... | get_tilde_constraints | python | google/osv.dev | osv/third_party/univers/gem.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gem.py | Apache-2.0 |
def parse_version_and_revision(version_string):
"""
Return a tuple of (version string, revision int) given a ``version_string``.
"""
revision = 0
version = version_string
match = revision_regexp.search(version_string)
if match:
revision = int(match.group(1)[2:])
version = version_string[:match.spa... |
Return a tuple of (version string, revision int) given a ``version_string``.
| parse_version_and_revision | python | google/osv.dev | osv/third_party/univers/gentoo.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gentoo.py | Apache-2.0 |
def vercmp(ver1, ver2):
"""
Compare two versions ``ver1`` and ``ver2`` and return 0, 1, or -1 according
to the Python 2 cmp() semantics:
Compare the two objects x and y and return an integer according to the
outcome. The return value is negative if x < y, zero if x == y and
strictly positive if... |
Compare two versions ``ver1`` and ``ver2`` and return 0, 1, or -1 according
to the Python 2 cmp() semantics:
Compare the two objects x and y and return an integer according to the
outcome. The return value is negative if x < y, zero if x == y and
strictly positive if x > y.
| vercmp | python | google/osv.dev | osv/third_party/univers/gentoo.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/gentoo.py | Apache-2.0 |
def from_evr(s):
"""
Return an (E, V, R) tuple given a string by splitting
[e:]version-release into the three possible subcomponents.
Default epoch to 0, version and release to empty string if not specified.
>>> assert from_evr("1:11.13.2.0-1") == (1, "11.13.2.0", "1")
>>> assert from_evr("11.1... |
Return an (E, V, R) tuple given a string by splitting
[e:]version-release into the three possible subcomponents.
Default epoch to 0, version and release to empty string if not specified.
>>> assert from_evr("1:11.13.2.0-1") == (1, "11.13.2.0", "1")
>>> assert from_evr("11.13.2.0-1") == (0, "11.13.... | from_evr | python | google/osv.dev | osv/third_party/univers/rpm.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/rpm.py | Apache-2.0 |
def cmp(x, y):
"""
Replacement for built-in Python 2 function cmp that was removed in Python 3
From https://docs.python.org/2/library/functions.html?highlight=cmp#cmp :
Compare the two objects x and y and return an integer according to the
outcome. The return value is negative if x < y, zero ... |
Replacement for built-in Python 2 function cmp that was removed in Python 3
From https://docs.python.org/2/library/functions.html?highlight=cmp#cmp :
Compare the two objects x and y and return an integer according to the
outcome. The return value is negative if x < y, zero if x == y and
... | cmp | python | google/osv.dev | osv/third_party/univers/utils.py | https://github.com/google/osv.dev/blob/master/osv/third_party/univers/utils.py | Apache-2.0 |
def objname_for_bug(client: datastore.Client, bug: datastore.entity.Entity,
forced_bucket_name: str) -> dict:
"""Returns the GCS object details for a given Bug.
Args:
client: an initialized Cloud Datastore client.
bug: a Bug Cloud Datastore entity.
forced_bucket_name: bucket n... | Returns the GCS object details for a given Bug.
Args:
client: an initialized Cloud Datastore client.
bug: a Bug Cloud Datastore entity.
forced_bucket_name: bucket name (with optional colon-separated path) to
forcibly use.
Returns:
A dict with keys for the GCS uri, the bucket name and p... | objname_for_bug | python | google/osv.dev | tools/datafix/reimport_gcs_record.py | https://github.com/google/osv.dev/blob/master/tools/datafix/reimport_gcs_record.py | Apache-2.0 |
def url_for_project(project: str) -> str:
"""Returns the base URL for referencing a vulnerability in the project.
Args:
project: a string representing the project ID.
Returns:
A string URL base for appending vulnerability IDs to.
Raises:
UnexpectedSituation if called with an unsupported project I... | Returns the base URL for referencing a vulnerability in the project.
Args:
project: a string representing the project ID.
Returns:
A string URL base for appending vulnerability IDs to.
Raises:
UnexpectedSituation if called with an unsupported project ID.
| url_for_project | python | google/osv.dev | tools/datafix/reimport_gcs_record.py | https://github.com/google/osv.dev/blob/master/tools/datafix/reimport_gcs_record.py | Apache-2.0 |
def bucket_for_source(client: datastore.Client, source: str) -> str:
"""Returns the GCS bucket name for a given source.
Args:
client: an initialized Cloud Datastore client.
source: a string identifying the source to extract the GCS bucket name for.
Returns:
A string representing the GCS bucket name.... | Returns the GCS bucket name for a given source.
Args:
client: an initialized Cloud Datastore client.
source: a string identifying the source to extract the GCS bucket name for.
Returns:
A string representing the GCS bucket name.
Raises:
UnexpectedSituation if called for a source that isn't usin... | bucket_for_source | python | google/osv.dev | tools/datafix/reimport_gcs_record.py | https://github.com/google/osv.dev/blob/master/tools/datafix/reimport_gcs_record.py | Apache-2.0 |
def reset_object_modification(bucket_name: str, blob_name: str) -> None:
"""Resets a GCS object's creation time.
Makes a no-op patch ("gcloud object storage objects update" equivalent)
Args:
bucket_name: the name of the GCS bucket.
blob_name: the name of the object in the bucket.
"""
gcs_client = st... | Resets a GCS object's creation time.
Makes a no-op patch ("gcloud object storage objects update" equivalent)
Args:
bucket_name: the name of the GCS bucket.
blob_name: the name of the object in the bucket.
| reset_object_modification | python | google/osv.dev | tools/datafix/reimport_gcs_record.py | https://github.com/google/osv.dev/blob/master/tools/datafix/reimport_gcs_record.py | Apache-2.0 |
def reput_bugs(dryrun: bool, source: str, ids: list) -> None:
""" Reput all bugs from a given source."""
query = osv.Bug.query()
if ids:
result = [ndb.Key(query.kind, id) for id in ids[0]]
else:
query = query.filter(osv.Bug.source == source)
print(f"Running query {query.filters} "
f"on {qu... | Reput all bugs from a given source. | reput_bugs | python | google/osv.dev | tools/datafix/reput_bugs.py | https://github.com/google/osv.dev/blob/master/tools/datafix/reput_bugs.py | Apache-2.0 |
def get_relevant_ids() -> list[str]:
"""Retrieve the IDs that require refreshing.
1. FILLOUT this function to only return IDs that are necessary to update
"""
relevant_ids = []
query = osv.Bug.query()
# Examples:
# - Datastore query filters
# query = query.filter([osv.Bug.source == "ubuntu"])
#
... | Retrieve the IDs that require refreshing.
1. FILLOUT this function to only return IDs that are necessary to update
| get_relevant_ids | python | google/osv.dev | tools/datafix/reput_helper.py | https://github.com/google/osv.dev/blob/master/tools/datafix/reput_helper.py | Apache-2.0 |
def transform_bug(_: osv.Bug):
"""Transform bug in place.
2. FILLOUT this function to apply transformations before reputting the bug.
"""
# E.g. Set key to none to regenerate a new key
# bug.key = None | Transform bug in place.
2. FILLOUT this function to apply transformations before reputting the bug.
| transform_bug | python | google/osv.dev | tools/datafix/reput_helper.py | https://github.com/google/osv.dev/blob/master/tools/datafix/reput_helper.py | Apache-2.0 |
def refresh_ids(dryrun: bool, loadcache: str) -> None:
"""Update bugs IDs to the new format"""
relevant_ids = []
if loadcache:
with open(loadcache, 'r') as f:
relevant_ids = json.load(f)
else:
relevant_ids = get_relevant_ids()
# Store the state incase we cancel halfway to avoid having
# to d... | Update bugs IDs to the new format | refresh_ids | python | google/osv.dev | tools/datafix/reput_helper.py | https://github.com/google/osv.dev/blob/master/tools/datafix/reput_helper.py | Apache-2.0 |
def publish_update_message(project_id,
topic_id,
source,
path,
original_sha256,
deleted=False):
"""Publish a message to a Pub/Sub topic with the provided data as attributes.
Args:
... | Publish a message to a Pub/Sub topic with the provided data as attributes.
Args:
project_id: The ID of the GCP project.
topic_id: The ID of the Pub/Sub topic.
source: The record source ID.
path: The record path.
original_sha256: The original SHA256 checksum of the record.
deleted:... | publish_update_message | python | google/osv.dev | tools/datafix/request_worker_update_record.py | https://github.com/google/osv.dev/blob/master/tools/datafix/request_worker_update_record.py | Apache-2.0 |
def github_raw_url(repo_url, path):
"""Get a downloadable raw URL for a path in a github repo."""
parsed = urlparse(repo_url.removesuffix('.git'))
if parsed.hostname != 'github.com':
raise ValueError(f'{repo_url} is not a GitHub URL')
repo = '/'.join(parsed.path.split('/')[1:3])
return f'https://raw.gith... | Get a downloadable raw URL for a path in a github repo. | github_raw_url | python | google/osv.dev | tools/datafix/request_worker_update_record.py | https://github.com/google/osv.dev/blob/master/tools/datafix/request_worker_update_record.py | Apache-2.0 |
def request_url_update(record_url, project_id, source, path, timeout,
allow_delete):
"""Request a update based on a URL record."""
print(f'Trying: {record_url}')
response = requests.get(record_url, timeout=timeout)
original_sha256 = ''
deleted = False
try:
response.raise_for_statu... | Request a update based on a URL record. | request_url_update | python | google/osv.dev | tools/datafix/request_worker_update_record.py | https://github.com/google/osv.dev/blob/master/tools/datafix/request_worker_update_record.py | Apache-2.0 |
def DownloadSource(source: dict, directory: str, verbose: bool = False) -> None:
"""Download the source defined in the dictionary."""
if verbose:
print(f'Operating on: {pprint.pformat(source)}')
if source['type'] == 0:
DownloadGitSource(source, directory, verbose)
return
if source['type'] == 1:
... | Download the source defined in the dictionary. | DownloadSource | python | google/osv.dev | tools/source-sync/source_sync.py | https://github.com/google/osv.dev/blob/master/tools/source-sync/source_sync.py | Apache-2.0 |
def DownloadGCSSource(source: dict,
directory: str,
verbose: bool = False) -> None:
"""Download the files from a GCS-based source."""
storage_client = storage.Client()
# List all the blobs in the bucket.
blobs = list(
storage_client.list_blobs(
source[... | Download the files from a GCS-based source. | DownloadGCSSource | python | google/osv.dev | tools/source-sync/source_sync.py | https://github.com/google/osv.dev/blob/master/tools/source-sync/source_sync.py | Apache-2.0 |
def DownloadRESTSource(source: dict,
directory: str,
verbose: bool = False) -> None:
"""Download from a REST API-based source."""
os.makedirs(os.path.join(directory, source['name']), exist_ok=True)
r = requests.get(source['rest_api_url'], timeout=30)
for record in r... | Download from a REST API-based source. | DownloadRESTSource | python | google/osv.dev | tools/source-sync/source_sync.py | https://github.com/google/osv.dev/blob/master/tools/source-sync/source_sync.py | Apache-2.0 |
def validate_repository(repository, local=True):
"""Check the attributes of the source repo."""
sourcerepo_names = []
for repo in repository:
if args.verbose:
print(f'Validating: {repo}')
if repo['name'] == '' or repo['name'] is None or repo['name'] == 'null':
raise ValueError(f'... | Check the attributes of the source repo. | validate_repository | python | google/osv.dev | tools/sourcerepo-sync/source_sync.py | https://github.com/google/osv.dev/blob/master/tools/sourcerepo-sync/source_sync.py | Apache-2.0 |
def update_sourcerepo(repo, ds_repo):
"""Check the attributes of the source repo and update if needed."""
entity = None
for attr in repo:
#Check whether the attribute has changed
if attr not in ds_repo or repo[attr] == ds_repo[attr]:
continue
if entity is None:
key = client... | Check the attributes of the source repo and update if needed. | update_sourcerepo | python | google/osv.dev | tools/sourcerepo-sync/source_sync.py | https://github.com/google/osv.dev/blob/master/tools/sourcerepo-sync/source_sync.py | Apache-2.0 |
def download_url_to_directory(url: str,
directory: str,
filename: Optional[str] = None) -> Optional[str]:
"""
Downloads a URL to a specified directory.
Args:
url (str): The URL to download.
directory (str): The directory to save the ... |
Downloads a URL to a specified directory.
Args:
url (str): The URL to download.
directory (str): The directory to save the file to.
filename (str, optional): The filename to use. If None, the filename
is extracted from the URL. Defaults to None.
... | download_url_to_directory | python | google/osv.dev | vulnfeeds/cmd/debian-copyright-mirror/debian-copyright-mirror.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/cmd/debian-copyright-mirror/debian-copyright-mirror.py | Apache-2.0 |
def generate_curl_configuration(filelist: List[str]):
"""
Generates a curl configuration to download all of the files in filelist.
--output filename
url = https://url
Args:
filelist (List[str]): a list of files to download.
"""
url_base = 'https://metadata.ftp-master.debian.org/changelo... |
Generates a curl configuration to download all of the files in filelist.
--output filename
url = https://url
Args:
filelist (List[str]): a list of files to download.
| generate_curl_configuration | python | google/osv.dev | vulnfeeds/cmd/debian-copyright-mirror/debian-copyright-mirror.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/cmd/debian-copyright-mirror/debian-copyright-mirror.py | Apache-2.0 |
def execute_curl(configuration: str, directory: str):
"""
Execute curl with the supplied configuration in the specified directory.
Args:
configuration (str): path to configuration file.
directory (str): path to set current working directory to.
"""
os.makedirs(directory)
subprocess.run(... |
Execute curl with the supplied configuration in the specified directory.
Args:
configuration (str): path to configuration file.
directory (str): path to set current working directory to.
| execute_curl | python | google/osv.dev | vulnfeeds/cmd/debian-copyright-mirror/debian-copyright-mirror.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/cmd/debian-copyright-mirror/debian-copyright-mirror.py | Apache-2.0 |
def create_codename_to_version() -> typing.Dict[str, str]:
"""Returns the codename to version mapping"""
with request.urlopen(
'https://debian.pages.debian.net/distro-info-data/debian.csv') as csv:
df = pd.read_csv(csv, dtype=str)
# `series` appears to be `codename` but with all lowercase
result =... | Returns the codename to version mapping | create_codename_to_version | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/convert_debian.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/convert_debian.py | Apache-2.0 |
def parse_security_tracker_file(advisories: Advisories,
security_tracker_repo: str,
security_tracker_path: str):
"""Parses the security tracker files into the advisories object"""
codename_to_version = create_codename_to_version()
with open(
... | Parses the security tracker files into the advisories object | parse_security_tracker_file | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/convert_debian.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/convert_debian.py | Apache-2.0 |
def parse_webwml_files(advisories: Advisories, webwml_repo_path: str,
wml_file_sub_path: str):
"""Parses the webwml file into the advisories object"""
file_path_map = {}
for root, _, files in os.walk(
os.path.join(webwml_repo_path, wml_file_sub_path)):
for file in files:
fi... | Parses the webwml file into the advisories object | parse_webwml_files | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/convert_debian.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/convert_debian.py | Apache-2.0 |
def write_output(output_dir: str, advisories: Advisories):
"""Writes the advisory dict into individual json files"""
for dsa_id, advisory in advisories.items():
# Skip advisories that do not affect anything
if len(advisory.affected) == 0:
print('Skipping: ' + dsa_id + ' because no affected versions')
... | Writes the advisory dict into individual json files | write_output | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/convert_debian.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/convert_debian.py | Apache-2.0 |
def convert_debian(webwml_repo: str, security_tracker_repo: str,
output_dir: str, adv_type: AdvisoryType):
"""Convert Debian advisory data into OSV."""
advisories: Advisories = {}
if adv_type == AdvisoryType.DLA:
parse_security_tracker_file(advisories, security_tracker_repo,
... | Convert Debian advisory data into OSV. | convert_debian | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/convert_debian.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/convert_debian.py | Apache-2.0 |
def get_debian_sources_url(date: datetime, version: str):
"""Create an url for snapshot.debian.org"""
formatted_date = convert_datetime_to_str_datetime(date)
return DEBIAN_SNAPSHOT_URL.format(
date=formatted_date) + DEBIAN_SOURCES_URL_EXTENSION.format(
version=version) | Create an url for snapshot.debian.org | get_debian_sources_url | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/first_package_finder.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/first_package_finder.py | Apache-2.0 |
def parse_created_dates_and_set_time(date: str) -> datetime:
"""Parse created date in debian version csv to datetime plus one day"""
result = datetime.strptime(date, '%Y-%m-%d') + timedelta(days=1)
# Set minimum date to first debian snapshot
return max(result, FIRST_SNAPSHOT_DATE) | Parse created date in debian version csv to datetime plus one day | parse_created_dates_and_set_time | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/first_package_finder.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/first_package_finder.py | Apache-2.0 |
def load_sources(date: datetime, dist: str) -> typing.Dict[str, str]:
"""Load the sources file and store in a dictionary of {name: version}"""
with request.urlopen(get_debian_sources_url(date, dist)) as res:
decompressed = gzip.decompress(res.read()).decode('iso-8859-2')
package_version_dict = {}
curren... | Load the sources file and store in a dictionary of {name: version} | load_sources | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/first_package_finder.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/first_package_finder.py | Apache-2.0 |
def load_first_packages() -> pd.DataFrame:
"""Loads the dataframe containing the first version of packages per distro"""
codename_to_version: pd.DataFrame = retrieve_codename_to_version()
logging.info('Retrieved codename_to_version:\n%s', codename_to_version)
first_release_dates = zip(
codename_to_version... | Loads the dataframe containing the first version of packages per distro | load_first_packages | python | google/osv.dev | vulnfeeds/tools/debian/debian_converter/first_package_finder.py | https://github.com/google/osv.dev/blob/master/vulnfeeds/tools/debian/debian_converter/first_package_finder.py | Apache-2.0 |
def _draw_vertical_text(
text,
image_font,
text_color,
text_background_color,
character_spacing=2,
space_width=1,
):
"""Helper function to draw text vertically.
Ref: https://github.com/Belval/TextRecognitionDataGenerator/blob/7f4c782c33993d2b6f712d01e86a2f342025f2df/trdg/computer_text_ge... | Helper function to draw text vertically.
Ref: https://github.com/Belval/TextRecognitionDataGenerator/blob/7f4c782c33993d2b6f712d01e86a2f342025f2df/trdg/computer_text_generator.py
| _draw_vertical_text | python | Layout-Parser/layout-parser | src/layoutparser/visualization.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/visualization.py | Apache-2.0 |
def draw_transparent_box(
canvas: "Image",
blocks: Layout,
color_map: Dict = None,
alpha: float = 0.25,
) -> "Image":
"""Given the image, draw a series of transparent boxes based on the blocks,
coloring using the specified color_map.
"""
if color_map is None:
all_types = set([b.... | Given the image, draw a series of transparent boxes based on the blocks,
coloring using the specified color_map.
| draw_transparent_box | python | Layout-Parser/layout-parser | src/layoutparser/visualization.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/visualization.py | Apache-2.0 |
def draw_box(
canvas: Image.Image,
layout: Layout,
box_width: Optional[Union[List[int], int]] = None,
box_alpha: Optional[Union[List[float], float]] = None,
box_color: Optional[Union[List[str], str]] = None,
color_map: Optional[Dict] = None,
show_element_id: bool = False,
show_element_ty... | Draw the layout region on the input canvas(image).
Args:
canvas (:obj:`~np.ndarray` or :obj:`~PIL.Image.Image`):
The canvas to draw the layout boxes.
layout (:obj:`Layout` or :obj:`list`):
The layout of the canvas to show.
box_width (:obj:`int` or :obj:`List[int]`, o... | draw_box | python | Layout-Parser/layout-parser | src/layoutparser/visualization.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/visualization.py | Apache-2.0 |
def draw_text(
canvas,
layout,
arrangement: str = "lr",
font_size: Optional[int] = None,
font_path: Optional[str] = None,
text_color: Optional[str] = None,
text_background_color: Optional[str] = None,
text_background_alpha: Optional[float] = None,
vertical_text: bool = False,
wit... | Draw the (detected) text in the `layout` according to
their coordinates next to the input `canvas` (image) for better comparison.
Args:
canvas (:obj:`~np.ndarray` or :obj:`~PIL.Image.Image`):
The canvas to draw the layout boxes.
layout (:obj:`Layout` or :obj:`list`):
The... | draw_text | python | Layout-Parser/layout-parser | src/layoutparser/visualization.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/visualization.py | Apache-2.0 |
def to_dict(self) -> Dict[str, Any]:
"""
Generate a dictionary representation of the current object:
{
"block_type": <"interval", "rectangle", "quadrilateral"> ,
"non_empty_block_attr1": value1,
...
}
"""
data = {
... |
Generate a dictionary representation of the current object:
{
"block_type": <"interval", "rectangle", "quadrilateral"> ,
"non_empty_block_attr1": value1,
...
}
| to_dict | python | Layout-Parser/layout-parser | src/layoutparser/elements/base.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/base.py | Apache-2.0 |
def from_dict(cls, data: Dict[str, Any]) -> "BaseCoordElement":
"""Initialize an instance based on the dictionary representation
Args:
data (:obj:`dict`): The dictionary representation of the object
"""
assert (
cls._name == data["block_type"]
), f"Incom... | Initialize an instance based on the dictionary representation
Args:
data (:obj:`dict`): The dictionary representation of the object
| from_dict | python | Layout-Parser/layout-parser | src/layoutparser/elements/base.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/base.py | Apache-2.0 |
def sort(self, key=None, reverse=False, inplace=False) -> Optional["Layout"]:
"""Sort the list of blocks based on the given
Args:
key ([type], optional): key specifies a function of one argument that
is used to extract a comparison key from each list element.
Default... | Sort the list of blocks based on the given
Args:
key ([type], optional): key specifies a function of one argument that
is used to extract a comparison key from each list element.
Defaults to None.
reverse (bool, optional): reverse is a boolean value. If set to Tr... | sort | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout.py | Apache-2.0 |
def filter_by(self, other, soft_margin={}, center=False):
"""
Return a `Layout` object containing the elements that are in the `other` object.
Args:
other (:obj:`BaseCoordElement`):
The block to filter the current elements.
Returns:
:obj:`Layout`... |
Return a `Layout` object containing the elements that are in the `other` object.
Args:
other (:obj:`BaseCoordElement`):
The block to filter the current elements.
Returns:
:obj:`Layout`:
A new layout object after filtering.
| filter_by | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout.py | Apache-2.0 |
def shift(self, shift_distance):
"""
Shift all layout elements by user specified amounts on x and y axis respectively. If shift_distance is one
numeric value, the element will by shifted by the same specified amount on both x and y axis.
Args:
shift_distance (:obj:`numeric` ... |
Shift all layout elements by user specified amounts on x and y axis respectively. If shift_distance is one
numeric value, the element will by shifted by the same specified amount on both x and y axis.
Args:
shift_distance (:obj:`numeric` or :obj:`Tuple(numeric)` or :obj:`List[numer... | shift | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout.py | Apache-2.0 |
def pad(self, left=0, right=0, top=0, bottom=0, safe_mode=True):
"""Pad all layout elements on the four sides of the polygon with the user-defined pixels. If
safe_mode is set to True, the function will cut off the excess padding that falls on the negative
side of the coordinates.
Args:
... | Pad all layout elements on the four sides of the polygon with the user-defined pixels. If
safe_mode is set to True, the function will cut off the excess padding that falls on the negative
side of the coordinates.
Args:
left (:obj:`int`, `optional`, defaults to 0): The number of pixe... | pad | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout.py | Apache-2.0 |
def scale(self, scale_factor):
"""
Scale all layout element by a user specified amount on x and y axis respectively. If scale_factor is one
numeric value, the element will by scaled by the same specified amount on both x and y axis.
Args:
scale_factor (:obj:`numeric` or :obj... |
Scale all layout element by a user specified amount on x and y axis respectively. If scale_factor is one
numeric value, the element will by scaled by the same specified amount on both x and y axis.
Args:
scale_factor (:obj:`numeric` or :obj:`Tuple(numeric)` or :obj:`List[numeric]`)... | scale | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout.py | Apache-2.0 |
def get_homogeneous_blocks(self) -> List[BaseLayoutElement]:
"""Convert all elements into blocks of the same type based
on the type casting rule::
Interval < Rectangle < Quadrilateral < TextBlock
Returns:
List[BaseLayoutElement]:
A list of base layout el... | Convert all elements into blocks of the same type based
on the type casting rule::
Interval < Rectangle < Quadrilateral < TextBlock
Returns:
List[BaseLayoutElement]:
A list of base layout elements of the maximal compatible
type
| get_homogeneous_blocks | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout.py | Apache-2.0 |
def to_dataframe(self, enforce_same_type=False) -> pd.DataFrame:
"""Convert the layout object into the dataframe.
Warning: the page data won't be exported.
Args:
enforce_same_type (:obj:`bool`, optional):
If true, it will convert all the contained blocks to
... | Convert the layout object into the dataframe.
Warning: the page data won't be exported.
Args:
enforce_same_type (:obj:`bool`, optional):
If true, it will convert all the contained blocks to
the maximal compatible data type.
Defaults to False.
... | to_dataframe | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout.py | Apache-2.0 |
def height(self):
"""
Calculate the height of the interval. If the interval is along the x-axis, the height will be the
height of the canvas, otherwise, it will be the difference between the start and end point.
Returns:
:obj:`numeric`: Output the numeric value of the height... |
Calculate the height of the interval. If the interval is along the x-axis, the height will be the
height of the canvas, otherwise, it will be the difference between the start and end point.
Returns:
:obj:`numeric`: Output the numeric value of the height.
| height | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def width(self):
"""
Calculate the width of the interval. If the interval is along the y-axis, the width will be the
width of the canvas, otherwise, it will be the difference between the start and end point.
Returns:
:obj:`numeric`: Output the numeric value of the width.
... |
Calculate the width of the interval. If the interval is along the y-axis, the width will be the
width of the canvas, otherwise, it will be the difference between the start and end point.
Returns:
:obj:`numeric`: Output the numeric value of the width.
| width | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def coordinates(self):
"""
This method considers an interval as a rectangle and calculates the coordinates of the upper left
and lower right corners to define the interval.
Returns:
:obj:`Tuple(numeric)`:
Output the numeric values of the coordinates in a Tupl... |
This method considers an interval as a rectangle and calculates the coordinates of the upper left
and lower right corners to define the interval.
Returns:
:obj:`Tuple(numeric)`:
Output the numeric values of the coordinates in a Tuple of size four.
| coordinates | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def put_on_canvas(self, canvas):
"""
Set the height and the width of the canvas that the interval is on.
Args:
canvas (:obj:`Numpy array` or :obj:`BaseCoordElement` or :obj:`PIL.Image.Image`):
The base element that the interval is on. The numpy array should be the
... |
Set the height and the width of the canvas that the interval is on.
Args:
canvas (:obj:`Numpy array` or :obj:`BaseCoordElement` or :obj:`PIL.Image.Image`):
The base element that the interval is on. The numpy array should be the
format of `[height, width]`.
... | put_on_canvas | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def shift(self, shift_distance):
"""
Shift the interval by a user specified amount along the same axis that the interval is defined on.
Args:
shift_distance (:obj:`numeric`): The number of pixels used to shift the interval.
Returns:
:obj:`BaseCoordElement`: The ... |
Shift the interval by a user specified amount along the same axis that the interval is defined on.
Args:
shift_distance (:obj:`numeric`): The number of pixels used to shift the interval.
Returns:
:obj:`BaseCoordElement`: The shifted Interval object.
| shift | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def scale(self, scale_factor):
"""
Scale the layout element by a user specified amount the same axis that the interval is defined on.
Args:
scale_factor (:obj:`numeric`): The amount for downscaling or upscaling the element.
Returns:
:obj:`BaseCoordElement`: The ... |
Scale the layout element by a user specified amount the same axis that the interval is defined on.
Args:
scale_factor (:obj:`numeric`): The amount for downscaling or upscaling the element.
Returns:
:obj:`BaseCoordElement`: The scaled Interval object.
| scale | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def height(self):
"""
Return the user defined height, otherwise the height of its circumscribed rectangle.
Returns:
:obj:`numeric`: Output the numeric value of the height.
"""
if self._height is not None:
return self._height
return self.points[:,... |
Return the user defined height, otherwise the height of its circumscribed rectangle.
Returns:
:obj:`numeric`: Output the numeric value of the height.
| height | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def width(self):
"""
Return the user defined width, otherwise the width of its circumscribed rectangle.
Returns:
:obj:`numeric`: Output the numeric value of the width.
"""
if self._width is not None:
return self._width
return self.points[:, 0].ma... |
Return the user defined width, otherwise the width of its circumscribed rectangle.
Returns:
:obj:`numeric`: Output the numeric value of the width.
| width | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def crop_image(self, image):
"""
Crop the input image using the points of the quadrilateral instance.
Args:
image (:obj:`Numpy array`): The array of the input image.
Returns:
:obj:`Numpy array`: The array of the cropped image.
"""
return _warpPe... |
Crop the input image using the points of the quadrilateral instance.
Args:
image (:obj:`Numpy array`): The array of the input image.
Returns:
:obj:`Numpy array`: The array of the cropped image.
| crop_image | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def to_dict(self) -> Dict[str, Any]:
"""
Generate a dictionary representation of the current object::
{
"block_type": "quadrilateral",
"points": [
p[0,0], p[0,1],
p[1,0], p[1,1],
p[2,0], p[2,1],
... |
Generate a dictionary representation of the current object::
{
"block_type": "quadrilateral",
"points": [
p[0,0], p[0,1],
p[1,0], p[1,1],
p[2,0], p[2,1],
p[3,0], p[3,1]
]... | to_dict | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def to_dict(self) -> Dict[str, Any]:
"""
Generate a dictionary representation of the current textblock of the format::
{
"block_type": <name of self.block>,
<attributes of self.block combined with
non-empty self._features>
}
... |
Generate a dictionary representation of the current textblock of the format::
{
"block_type": <name of self.block>,
<attributes of self.block combined with
non-empty self._features>
}
| to_dict | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def from_dict(cls, data: Dict[str, Any]) -> "TextBlock":
"""Initialize the textblock based on the dictionary representation.
It generate the block based on the `block_type` and `block_attr`,
and loads the textblock specific features from the dict.
Args:
data (:obj:`dict`): T... | Initialize the textblock based on the dictionary representation.
It generate the block based on the `block_type` and `block_attr`,
and loads the textblock specific features from the dict.
Args:
data (:obj:`dict`): The dictionary representation of the object
| from_dict | python | Layout-Parser/layout-parser | src/layoutparser/elements/layout_elements.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/layout_elements.py | Apache-2.0 |
def polygon_area(xs: np.ndarray, ys: np.ndarray) -> float:
"""Calculate the area of polygons using
`Shoelace Formula <https://en.wikipedia.org/wiki/Shoelace_formula>`_.
Args:
xs (`np.ndarray`): The x coordinates of the points
ys (`np.ndarray`): The y coordinates of the points
"""
#... | Calculate the area of polygons using
`Shoelace Formula <https://en.wikipedia.org/wiki/Shoelace_formula>`_.
Args:
xs (`np.ndarray`): The x coordinates of the points
ys (`np.ndarray`): The y coordinates of the points
| polygon_area | python | Layout-Parser/layout-parser | src/layoutparser/elements/utils.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/elements/utils.py | Apache-2.0 |
def load_json(filename: str) -> Union[BaseLayoutElement, Layout]:
"""Load a JSON file and save it as a layout object with appropriate data types.
Args:
filename (str):
The name of the JSON file.
Returns:
Union[BaseLayoutElement, Layout]:
Based on the JSON file forma... | Load a JSON file and save it as a layout object with appropriate data types.
Args:
filename (str):
The name of the JSON file.
Returns:
Union[BaseLayoutElement, Layout]:
Based on the JSON file format, it will automatically parse
the type of the data and load ... | load_json | python | Layout-Parser/layout-parser | src/layoutparser/io/basic.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/io/basic.py | Apache-2.0 |
def load_dict(data: Union[Dict, List[Dict]]) -> Union[BaseLayoutElement, Layout]:
"""Load a dict of list of dict representations of some layout data,
automatically parse its type, and save it as any of BaseLayoutElement
or Layout datatype.
Args:
data (Union[Dict, List]):
A dict of l... | Load a dict of list of dict representations of some layout data,
automatically parse its type, and save it as any of BaseLayoutElement
or Layout datatype.
Args:
data (Union[Dict, List]):
A dict of list of dict representations of the layout data
Raises:
ValueError:
... | load_dict | python | Layout-Parser/layout-parser | src/layoutparser/io/basic.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/io/basic.py | Apache-2.0 |
def load_dataframe(df: pd.DataFrame, block_type: str = None) -> Layout:
"""Load the Layout object from the given dataframe.
Args:
df (pd.DataFrame):
block_type (str):
If there's no block_type column in the CSV file,
you must pass in a block_type variable such that layou... | Load the Layout object from the given dataframe.
Args:
df (pd.DataFrame):
block_type (str):
If there's no block_type column in the CSV file,
you must pass in a block_type variable such that layout parser
can appropriately detect the type of the layout elements.
... | load_dataframe | python | Layout-Parser/layout-parser | src/layoutparser/io/basic.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/io/basic.py | Apache-2.0 |
def extract_words_for_page(
page: pdfplumber.page.Page,
x_tolerance=1.5,
y_tolerance=2,
keep_blank_chars=False,
use_text_flow=True,
horizontal_ltr=True,
vertical_ttb=True,
extra_attrs=None,
) -> Layout:
"""The helper function used for extracting words from a pdfplumber page
objec... | The helper function used for extracting words from a pdfplumber page
object.
Returns:
Layout: a layout object representing all extracted pdf tokens on this page.
| extract_words_for_page | python | Layout-Parser/layout-parser | src/layoutparser/io/pdf.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/io/pdf.py | Apache-2.0 |
def load_pdf(
filename: str,
load_images: bool = False,
x_tolerance: int = 1.5,
y_tolerance: int = 2,
keep_blank_chars: bool = False,
use_text_flow: bool = True,
horizontal_ltr: bool = True,
vertical_ttb: bool = True,
extra_attrs: Optional[List[str]] = None,
dpi: int = DEFAULT_PD... | Load all tokens for each page from a PDF file, and save them
in a list of Layout objects with the original page order.
Args:
filename (str): The path to the PDF file.
load_images (bool, optional):
Whether load screenshot for each page of the PDF file.
When set to true, t... | load_pdf | python | Layout-Parser/layout-parser | src/layoutparser/io/pdf.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/io/pdf.py | Apache-2.0 |
def AutoLayoutModel(
config_path: str,
model_path: Optional[str] = None,
label_map: Optional[Dict] = None,
device: Optional[str] = None,
extra_config: Optional[Union[Dict, List]] = None,
) -> "BaseLayoutModel":
"""[summary]
Args:
config_path (:obj:`str`):
The path to the... | [summary]
Args:
config_path (:obj:`str`):
The path to the configuration file.
model_path (:obj:`str`, None):
The path to the saved weights of the model.
If set, overwrite the weights in the configuration file.
Defaults to `None`.
label_map (:o... | AutoLayoutModel | python | Layout-Parser/layout-parser | src/layoutparser/models/auto_layoutmodel.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/models/auto_layoutmodel.py | Apache-2.0 |
def detect(self, image):
"""Detect the layout of a given image.
Args:
image (:obj:`np.ndarray` or `PIL.Image`): The input image to detect.
Returns:
:obj:`~layoutparser.Layout`: The detected layout of the input image
"""
image = self.image_loader(image)
... | Detect the layout of a given image.
Args:
image (:obj:`np.ndarray` or `PIL.Image`): The input image to detect.
Returns:
:obj:`~layoutparser.Layout`: The detected layout of the input image
| detect | python | Layout-Parser/layout-parser | src/layoutparser/models/detectron2/layoutmodel.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/models/detectron2/layoutmodel.py | Apache-2.0 |
def _get_local_path(
self,
path: str,
force: bool = False,
cache_dir: Optional[str] = None,
**kwargs: Any,
) -> str:
"""
As paddle model stores all files in tar files, we need to extract them
and get the newly extracted folder path. This function rewri... |
As paddle model stores all files in tar files, we need to extract them
and get the newly extracted folder path. This function rewrites the base
function to support the following situations:
1. If the tar file is not downloaded, it will download the tar file,
extract it to t... | _get_local_path | python | Layout-Parser/layout-parser | src/layoutparser/models/paddledetection/catalog.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/models/paddledetection/catalog.py | Apache-2.0 |
def _resize_image(
image: np.ndarray, target_size: Tuple[int, int]
) -> Tuple[np.ndarray, np.ndarray]:
"""
Args:
image (np.ndarray): image (np.ndarray)
Returns:
image (np.ndarray): processed image (np.ndarray)
"""
origin_shape = image.shape[:2]
resize_h, resize_w = target_s... |
Args:
image (np.ndarray): image (np.ndarray)
Returns:
image (np.ndarray): processed image (np.ndarray)
| _resize_image | python | Layout-Parser/layout-parser | src/layoutparser/models/paddledetection/layoutmodel.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/models/paddledetection/layoutmodel.py | Apache-2.0 |
def load_predictor(
self,
model_dir,
device=None,
enable_mkldnn=False,
thread_num=10,
):
"""set AnalysisConfig, generate AnalysisPredictor
Args:
model_dir (str): root path of __model__ and __params__
device (str): cuda or cpu
Re... | set AnalysisConfig, generate AnalysisPredictor
Args:
model_dir (str): root path of __model__ and __params__
device (str): cuda or cpu
Returns:
predictor (PaddlePredictor): AnalysisPredictor
Raises:
ValueError: predict by TensorRT need enforce_cpu =... | load_predictor | python | Layout-Parser/layout-parser | src/layoutparser/models/paddledetection/layoutmodel.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/models/paddledetection/layoutmodel.py | Apache-2.0 |
def preprocess(self, image):
"""preprocess image
Args:
image (np.ndarray): image (np.ndarray)
Returns:
inputs (dict): input of model
"""
# resize image by target_size and max_size
image, scale_factor = _resize_image(image, self.target_size)
... | preprocess image
Args:
image (np.ndarray): image (np.ndarray)
Returns:
inputs (dict): input of model
| preprocess | python | Layout-Parser/layout-parser | src/layoutparser/models/paddledetection/layoutmodel.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/models/paddledetection/layoutmodel.py | Apache-2.0 |
def __init__(self, languages=None, ocr_image_decode_type=".png"):
"""Create a Google Cloud Vision OCR Agent.
Args:
languages (:obj:`list`, optional):
You can specify the language code of the documents to detect to improve
accuracy. The supported language and ... | Create a Google Cloud Vision OCR Agent.
Args:
languages (:obj:`list`, optional):
You can specify the language code of the documents to detect to improve
accuracy. The supported language and their code can be found on `this page
<https://cloud.google.c... | __init__ | python | Layout-Parser/layout-parser | src/layoutparser/ocr/gcv_agent.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/ocr/gcv_agent.py | Apache-2.0 |
def detect(
self,
image,
return_response=False,
return_only_text=False,
agg_output_level=None,
):
"""Send the input image for OCR.
Args:
image (:obj:`np.ndarray` or :obj:`str`):
The input image array or the name of the image file
... | Send the input image for OCR.
Args:
image (:obj:`np.ndarray` or :obj:`str`):
The input image array or the name of the image file
return_response (:obj:`bool`, optional):
Whether directly return the google cloud response.
Defaults to `False... | detect | python | Layout-Parser/layout-parser | src/layoutparser/ocr/gcv_agent.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/ocr/gcv_agent.py | Apache-2.0 |
def gather_text_annotations(response):
"""Convert the text_annotations from GCV output to an :obj:`Layout` object.
Args:
response (:obj:`AnnotateImageResponse`):
The returned Google Cloud Vision AnnotateImageResponse object.
Returns:
:obj:`Layout`: The r... | Convert the text_annotations from GCV output to an :obj:`Layout` object.
Args:
response (:obj:`AnnotateImageResponse`):
The returned Google Cloud Vision AnnotateImageResponse object.
Returns:
:obj:`Layout`: The reterived layout from the response.
| gather_text_annotations | python | Layout-Parser/layout-parser | src/layoutparser/ocr/gcv_agent.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/ocr/gcv_agent.py | Apache-2.0 |
def gather_full_text_annotation(response, agg_level):
"""Convert the full_text_annotation from GCV output to an :obj:`Layout` object.
Args:
response (:obj:`AnnotateImageResponse`):
The returned Google Cloud Vision AnnotateImageResponse object.
agg_level (:obj:`~... | Convert the full_text_annotation from GCV output to an :obj:`Layout` object.
Args:
response (:obj:`AnnotateImageResponse`):
The returned Google Cloud Vision AnnotateImageResponse object.
agg_level (:obj:`~GCVFeatureType`):
The layout level to aggregate t... | gather_full_text_annotation | python | Layout-Parser/layout-parser | src/layoutparser/ocr/gcv_agent.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/ocr/gcv_agent.py | Apache-2.0 |
def __init__(self, languages="eng", **kwargs):
"""Create a Tesseract OCR Agent.
Args:
languages (:obj:`list` or :obj:`str`, optional):
You can specify the language code(s) of the documents to detect to improve
accuracy. The supported language and their code c... | Create a Tesseract OCR Agent.
Args:
languages (:obj:`list` or :obj:`str`, optional):
You can specify the language code(s) of the documents to detect to improve
accuracy. The supported language and their code can be found on
`its github repo <https://g... | __init__ | python | Layout-Parser/layout-parser | src/layoutparser/ocr/tesseract_agent.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/ocr/tesseract_agent.py | Apache-2.0 |
def detect(
self, image, return_response=False, return_only_text=True, agg_output_level=None
):
"""Send the input image for OCR.
Args:
image (:obj:`np.ndarray` or :obj:`str`):
The input image array or the name of the image file
return_response (:obj:`... | Send the input image for OCR.
Args:
image (:obj:`np.ndarray` or :obj:`str`):
The input image array or the name of the image file
return_response (:obj:`bool`, optional):
Whether directly return all output (string and boxes
info) from Tesse... | detect | python | Layout-Parser/layout-parser | src/layoutparser/ocr/tesseract_agent.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/ocr/tesseract_agent.py | Apache-2.0 |
def gather_data(response, agg_level):
"""
Gather the OCR'ed text, bounding boxes, and confidence
in a given aggeragation level.
"""
assert isinstance(
agg_level, TesseractFeatureType
), f"Invalid agg_level {agg_level}"
res = response["data"]
df... |
Gather the OCR'ed text, bounding boxes, and confidence
in a given aggeragation level.
| gather_data | python | Layout-Parser/layout-parser | src/layoutparser/ocr/tesseract_agent.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/ocr/tesseract_agent.py | Apache-2.0 |
def generalized_connected_component_analysis_1d(
sequence: List[Any],
scoring_func: Callable[[Any, Any], int],
aggregation_func: Callable[[List[Any]], Any] = None,
default_score_value: int = 0,
) -> List[Any]:
"""Perform connected componenet analysis for any 1D sequence based on
the scoring func... | Perform connected componenet analysis for any 1D sequence based on
the scoring function and the aggregation function.
It will generate the adjacency_matrix for the 1D sequence object using
the provided `scoring_func` and find the connected componenets.
The `aggregation_func` will be used to aggregate al... | generalized_connected_component_analysis_1d | python | Layout-Parser/layout-parser | src/layoutparser/tools/shape_operations.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/tools/shape_operations.py | Apache-2.0 |
def simple_line_detection(
layout: Iterable[BaseLayoutElement], x_tolerance: int = 10, y_tolerance: int = 10
) -> List[BaseLayoutElement]:
"""Perform line detection based on connected component analysis.
The is_line_wise_close is the scoring function, which returns True
if the y-difference is smaller t... | Perform line detection based on connected component analysis.
The is_line_wise_close is the scoring function, which returns True
if the y-difference is smaller than the y_tolerance AND the
x-difference (the horizontal gap between two boxes) is also smaller
than the x_tolerance, and False otherwise.
... | simple_line_detection | python | Layout-Parser/layout-parser | src/layoutparser/tools/shape_operations.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/tools/shape_operations.py | Apache-2.0 |
def group_textblocks_based_on_category(
layout: Iterable[TextBlock], union_group: bool = True
) -> Union[List[TextBlock], List[List[TextBlock]]]:
"""Group textblocks based on their category (block.type).
Args:
layout (Iterable):
A list (or Layout) of BaseLayoutElement
union_grou... | Group textblocks based on their category (block.type).
Args:
layout (Iterable):
A list (or Layout) of BaseLayoutElement
union_group (bool):
Whether to union the boxes within each group.
Defaults to True.
Returns:
List[TextBlock]: When `union_group=Tr... | group_textblocks_based_on_category | python | Layout-Parser/layout-parser | src/layoutparser/tools/shape_operations.py | https://github.com/Layout-Parser/layout-parser/blob/master/src/layoutparser/tools/shape_operations.py | Apache-2.0 |
def set_riskfree_rate(self, rf):
"""
Set annual risk-free rate property and calculate properly annualized
monthly and daily rates. Then performance stats are recalculated.
Affects only this instance of the PerformanceStats.
Args:
* rf (float): Annual `risk-free rate ... |
Set annual risk-free rate property and calculate properly annualized
monthly and daily rates. Then performance stats are recalculated.
Affects only this instance of the PerformanceStats.
Args:
* rf (float): Annual `risk-free rate <https://www.investopedia.com/terms/r/risk-f... | set_riskfree_rate | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def set_date_range(self, start=None, end=None):
"""
Update date range of stats, charts, etc. If None then
the original date is used. So to reset to the original
range, just call with no args.
Args:
* start (date): start date
* end (end): end date
... |
Update date range of stats, charts, etc. If None then
the original date is used. So to reset to the original
range, just call with no args.
Args:
* start (date): start date
* end (end): end date
| set_date_range | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def display(self):
"""
Displays an overview containing descriptive stats for the Series
provided.
"""
print("Stats for %s from %s - %s" % (self.name, self.start, self.end))
if isinstance(self.rf, float):
print("Annual risk-free rate considered: %s" % (fmtp(sel... |
Displays an overview containing descriptive stats for the Series
provided.
| display | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def display_monthly_returns(self):
"""
Display a table containing monthly returns and ytd returns
for every year in range.
"""
data = [
[
"Year",
"Jan",
"Feb",
"Mar",
"Apr",
... |
Display a table containing monthly returns and ytd returns
for every year in range.
| display_monthly_returns | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def plot(self, freq=None, figsize=(15, 5), title=None, logy=False, **kwargs):
"""
Helper function for plotting the series.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure... |
Helper function for plotting the series.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* logy (boo... | plot | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def plot_histogram(self, freq=None, figsize=(15, 5), title=None, bins=20, **kwargs):
"""
Plots a histogram of returns given a return frequency.
Args:
* freq (str): Data frequency used for display purposes.
This will dictate the type of returns
(daily ... |
Plots a histogram of returns given a return frequency.
Args:
* freq (str): Data frequency used for display purposes.
This will dictate the type of returns
(daily returns, monthly, ...)
Refer to pandas docs for valid period strings.
... | plot_histogram | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def to_csv(self, sep=",", path=None):
"""
Returns a CSV string with appropriate formatting.
If path is not None, the string will be saved to file
at path.
Args:
* sep (char): Separator
* path (str): If None, CSV string returned. Else file written
... |
Returns a CSV string with appropriate formatting.
If path is not None, the string will be saved to file
at path.
Args:
* sep (char): Separator
* path (str): If None, CSV string returned. Else file written
to specified path.
| to_csv | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def set_riskfree_rate(self, rf):
"""
Set annual `risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ property and calculate properly annualized
monthly and daily rates. Then performance stats are recalculated.
Affects only those instances of PerformanceStats that ar... |
Set annual `risk-free rate <https://www.investopedia.com/terms/r/risk-freerate.asp>`_ property and calculate properly annualized
monthly and daily rates. Then performance stats are recalculated.
Affects only those instances of PerformanceStats that are children of
this GroupStats object... | set_riskfree_rate | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def set_date_range(self, start=None, end=None):
"""
Update date range of stats, charts, etc. If None then
the original date range is used. So to reset to the original
range, just call with no args.
Args:
* start (date): start date
* end (end): end date
... |
Update date range of stats, charts, etc. If None then
the original date range is used. So to reset to the original
range, just call with no args.
Args:
* start (date): start date
* end (end): end date
| set_date_range | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
def plot(self, freq=None, figsize=(15, 5), title=None, logy=False, **kwargs):
"""
Helper function for plotting the series.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure... |
Helper function for plotting the series.
Args:
* freq (str): Data frequency used for display purposes.
Refer to pandas docs for valid freq strings.
* figsize ((x,y)): figure size
* title (str): Title if default not appropriate
* logy (boo... | plot | python | pmorissette/ffn | ffn/core.py | https://github.com/pmorissette/ffn/blob/master/ffn/core.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.