code
stringlengths
114
1.05M
path
stringlengths
3
312
quality_prob
float64
0.5
0.99
learning_prob
float64
0.2
1
filename
stringlengths
3
168
kind
stringclasses
1 value
import requests from typing import Dict, List, Final from .base import API_BASE_URL API_MARKET_DATA_URL: Final[str] = API_BASE_URL + "/market_data" API_MARKET_DATA_ITEM_IDS_URL: Final[str] = API_MARKET_DATA_URL + "/item_ids.json" API_MARKET_DATA_ITEM_INFO_URL: Final[str] = API_MARKET_DATA_URL + "/item_info.json" API_MARKET_DATA_ITEMS_URL: Final[str] = API_MARKET_DATA_URL + "/items.json" def get_market_data_item_ids() -> Dict[str, str]: """Get the list of item IDs for which there is data. :return: The list of item IDs for which there is data. :rtype: Dict[str, str] :raises requests.HTTPError: If there is an error with the request. Usage:: >>> from relics_run_api import get_market_data_item_ids >>> get_market_data_item_ids() { "Secura Dual Cestra": "54aae292e7798909064f1575", "Creeping Bullseye": "54ca39abe7798915c1c11e10", "Mutalist Alad V Assassinate (Key)": "54d4c727e77989281cc7d753", ... } """ # Get the list of item IDs from the API response: Final[Response] = requests.get(API_MARKET_DATA_ITEM_IDS_URL) # Check for errors response.raise_for_status() # Return the list of item IDs return response.json() def get_market_data_item_info() -> Dict[str, dict]: """Get the list of item info for which there is data. :return: The list of item info for which there is data. :rtype: Dict[str, dict] :raises requests.HTTPError: If there is an error with the request. Usage:: >>> from relics_run_api import get_market_data_item_info >>> get_market_data_item_info() { "54aae292e7798909064f1575": { "set_items": [], "item_id": "54aae292e7798909064f1575", "tags": [ "syndicate", "weapon", "secondary" ], "mod_max_rank": null, "subtypes": [] }, ... } """ # Get the list of item info from the API response: Final[Response] = requests.get(API_MARKET_DATA_ITEM_INFO_URL) # Check for errors response.raise_for_status() # Return the list of item info return response.json() def get_market_data_items() -> List[Dict[str, str]]: """Get the list of items for which there is data in the API. :return: The list of items for which there is data in the API. :rtype: List[Dict[str, str]] :raises requests.HTTPError: If there is an error with the request. Usage:: >>> from relics_run_api import get_market_data_items >>> get_market_data_items() [ {'name': 'Axi A1'}, {'name': 'Axi A2'}, {'name': 'Axi A3'}, ... ] """ # Get the list of items from the API response: Final[Response] = requests.get(API_MARKET_DATA_ITEMS_URL) # Check for errors response.raise_for_status() # Return the list of items return response.json()
/relics_run_api-0.1.1.tar.gz/relics_run_api-0.1.1/relics_run_api/market_data.py
0.809201
0.196113
market_data.py
pypi
from datetime import date import re import requests from requests import Response from typing import Dict, Final, List, Union from .base import API_BASE_URL API_HISTORY_URL: Final[str] = API_BASE_URL + "/history" API_HISTORY_DATE_URL: Final[str] = API_HISTORY_URL + "/price_history_{date}.json" def get_history_dates() -> List[date]: """Get the list of dates for which there is data in the API. :return: The list of dates for which there is data in the API. :rtype: List[date] :raises requests.HTTPError: If there is an error with the request. Usage:: >>> from relics_run_api import get_history_dates >>> get_history_dates() [datetime.date(2023, 7, 2), datetime.date(2023, 7, 3), datetime.date(2023, 7, 4)] """ # Get the list of dates from the API response: Final[Response] = requests.get(API_HISTORY_URL) # Check for errors response.raise_for_status() # Get the content of the response content: Final[str] = response.text # Create the regex to match the dates date_regex = re.compile(r'href="price_history_(\d{4}-\d{2}-\d{2})\.json"') # Find all the dates dates: List[str] = date_regex.findall(content) # Convert the dates to date objects dates = [date.fromisoformat(date_string) for date_string in dates] # Sort the dates in ascending order dates.sort() # Return the dates return dates def get_history(date: date) -> Dict[str, List[Dict[str, Union[str, int, float]]]]: """Get the data for a given date from the API. :param date: The date for which to get the data. :type date: date :return: The data for the given date. :rtype: dict :raises requests.HTTPError: If there is an error with the request. Usage:: >>> from datetime import date >>> from relics_run_api import get_history >>> get_history(date=date(2023, 7, 2)) { 'Secura Dual Cestra': [ { 'datetime': '2023-07-02T00:00:00.000+00:00', 'volume': 8, 'min_price': 25, 'max_price': 40, 'open_price': 30, 'closed_price': 34, 'avg_price': 32.5, 'wa_price': 32.375, 'median': 30.0, 'moving_avg': 30.2, 'donch_top': 40, 'donch_bot': 20, 'id': '64a20ff4ca73520023c44a7f' }, { 'datetime': '2023-07-02T00:00:00.000+00:00', 'volume': 435, 'min_price': 10, 'max_price': 15, 'avg_price': 12.5, 'wa_price': 10.062, 'median': 13, 'order_type': 'buy', 'moving_avg': 21.6, 'id': '64a20ff4ca73520023c44a81' }, { 'datetime': '2023-07-02T00:00:00.000+00:00', 'volume': 117, 'min_price': 20, 'max_price': 45, 'avg_price': 32.5, 'wa_price': 32.846, 'median': 30, 'order_type': 'sell', 'moving_avg': 25.3, 'id': '64a20ff4ca73520023c44a80' } ], [...] } """ # Build the URL url: Final[str] = API_HISTORY_DATE_URL.format(date=date.isoformat()) # Get the data from the API response: Final[Response] = requests.get(url) # Check for errors response.raise_for_status() # Return the data return response.json()
/relics_run_api-0.1.1.tar.gz/relics_run_api-0.1.1/relics_run_api/history.py
0.867106
0.408395
history.py
pypi
import json import gzip import requests from requests import Response from typing import Any, Dict, Final from .base import API_BASE_URL API_INDEX_URL: Final[str] = API_BASE_URL + "/index" API_INDEX_INDEX_URL: Final[str] = API_INDEX_URL + "/index.json.gz" API_INDEX_PRICE_DATA_URL: Final[str] = API_INDEX_URL + "/price_data.json" API_INDEX_SUB_TYPE_DATA_URL: Final[str] = API_INDEX_URL + "/sub_type_data.json" def get_index() -> Dict[str, Any]: """Get the index from the API. :return: The index from the API. :rtype: dict :raises requests.HTTPError: If there is an error with the request. Usage:: >>> from relics_run_api import get_index >>> get_index() { 'relics': { 'Axi A1': { 'Nikana Prime Blueprint': 3, 'Akstiletto Prime Barrel': 2, 'Dual Kamas Prime Handle': 2, 'Trinity Prime Systems Blueprint': 1, 'Fragor Prime Head': 1, 'Braton Prime Stock': 1 }, ... }, 'non_vaulted': [ 'Axi G10', 'Lith S15', 'Neo S17', ... ], 'prices': { 'Frost Prime Set': 100.0, 'Hydroid Prime Set': 104.5, 'Zephyr Prime Chassis Blueprint': 5.5, ... }, 'ducats': { 'Odonata Prime Blueprint': 45, 'Odonata Prime Harness Blueprint': 15, 'Odonata Prime Systems Blueprint': 15, ... }, 'required_count': { 'Afuris Prime Barrel': 2, 'Afuris Prime Receiver': 2, 'Akbolto Prime Barrel': 2, ... }, 'types': { 'Kavasa Prime': 'Skins', 'Odonata Prime': 'Warframes', 'Equinox Prime': 'Warframes', ... } } """ # Get the index from the API response: Final[Response] = requests.get(API_INDEX_INDEX_URL) # Check for errors response.raise_for_status() # Get the content of the response content: Final[str] = response.content # Decompress the content decompressed_content: Final[str] = gzip.decompress(content) # Parse the content parsed_content: Final[Dict[str, Any]] = json.loads(decompressed_content) # Return the parsed content return parsed_content def get_index_price_data() -> Dict[str, Any]: """Get the price data from the API. :return: The price data from the API. :rtype: dict :raises requests.HTTPError: If there is an error with the request. Usage:: >>> from relics_run_api import get_index_price_data >>> get_index_price_data() { "Abating Link": "N/A", "Abating Link R0": 14.0, "Abating Link R3": 26.666666666666668, "Abundant Mutation": "N/A", "Abundant Mutation R0": 11.166666666666666, "Abundant Mutation R3": 15.5, ... } """ # Get the price data from the API response: Final[Response] = requests.get(API_INDEX_PRICE_DATA_URL) # Check for errors response.raise_for_status() # Return the price data return response.json() def get_index_sub_type_data() -> Dict[str, Any]: """Get the sub type data from the API. :return: The sub type data from the API. :rtype: dict :raises requests.HTTPError: If there is an error with the request. Usage:: >>> from relics_run_api import get_index_sub_type_data >>> get_index_sub_type_data() { "Creeping Bullseye": [ "R0", "R5" ], "Arcane Barrier": [ "R0", "R5" ], ... } """ # Get the sub type data from the API response: Final[Response] = requests.get(API_INDEX_SUB_TYPE_DATA_URL) # Check for errors response.raise_for_status() # Return the sub type data return response.json()
/relics_run_api-0.1.1.tar.gz/relics_run_api-0.1.1/relics_run_api/index.py
0.782122
0.24303
index.py
pypi
from scipy import sparse import numpy as np from sklearn.datasets import load_breast_cancer import matplotlib.pyplot as plt import seaborn as sns from sklearn.feature_selection import mutual_info_classif # chi2, f_classif from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.model_selection import cross_val_score import tqdm import reliefe def test_simple_benchmark(): sns.set_style("whitegrid") data_obj = load_breast_cancer() x = data_obj['data'] y = data_obj['target'] names = data_obj['feature_names'] # let's overfit, just for demo purposes reliefE_instance = reliefe.ReliefE(embedding_based_distances=True, verbose=True, use_average_neighbour=False, determine_k_automatically=False, mlc_distance="hamming") reliefE_instance.fit(x, y) reliefe_importances = reliefE_instance.feature_importances_ rf_model = RandomForestClassifier() rf_model.fit(x, y) rf = rf_model.feature_importances_ mutual_information = mutual_info_classif(x,y) sorted_rf = np.argsort(rf) sorted_mi = np.argsort(mutual_information) sorted_re = np.argsort(reliefe_importances) names = ["RF","MI","ReliefE"] indices = [sorted_rf,sorted_mi,sorted_re] output_struct = {} for name, indice_set in zip(names, indices): scores = [] indice_set = indice_set.tolist() print("Computing evaluations for: {}".format(name)) for j in tqdm.tqdm(range(len(indice_set))): selected_features = indice_set[0:j+1] subset = x[:,selected_features] clf = LogisticRegression(max_iter = 10000000, solver = "lbfgs") score = np.mean(cross_val_score(clf, subset, y, cv = 10)) scores.append((score,j+1)) output_struct[name] = scores print("Plotting ..") for k,v in output_struct.items(): indices = [] scores = [] for x,y in v: indices.append(y) scores.append(x) plt.plot(indices, scores, label = k) plt.xlabel("Top features") plt.ylabel("Performance (Accuracy)") plt.legend() plt.show() if __name__ == "__main__": test_simple_benchmark()
/reliefe-0.18.tar.gz/reliefe-0.18/examples/minimal_benchmark.py
0.456894
0.412944
minimal_benchmark.py
pypi
import datetime import os import re from pathlib import Path from typing import Dict from typing import List from typing import Tuple import click import semver import toml CHANGELOG = Path("CHANGELOG.md") PYPROJECT = Path("pyproject.toml") PYPROJECT_BUMP_CONFIG = (PYPROJECT, '(version = ")(.*)(")') EMPTY_PATCH = { "version": "UNRELEASED", "date": "YYYY-MM-DD\n", "release_notes": "\n### Added\n### Fixed\n### Changed\n\n", } RELEASE_CHOICES = { "1": { "description": "MAJOR version when you make incompatible API changes", "function": semver.bump_major, }, "2": { "description": "MINOR version when you add functionality in a backwards compatible manner", "function": semver.bump_minor, }, "3": { "description": "PATCH version when you make backwards compatible bug fixes", "function": semver.bump_patch, }, } PRERELEASE_CHOICES = { "4": { "description": "RELEASE version when you want to release this version", "function": semver.finalize_version, }, "5": { "description": "PRERELEASE version when you want to add a new prerelease", "function": semver.bump_prerelease, }, } # Type Definitions Releasenotes = Dict[str, str] Changelog = List[Releasenotes] def _get_date() -> str: return datetime.date.today().strftime("%Y-%m-%d") def load_changelog(changelog_file: Path = CHANGELOG) -> Changelog: """ Args: changelog_file: path to changelog in keepachangelog.com format Returns: List of releasenote dicts with the following fields: - version: Version number of the patch - date: Date of the patch - release_notes: Markdown formatted release_notes """ with changelog_file.open() as file: changelog = [] current_version = None for line in file: if line.startswith("## "): # Guarantees that only valid release_notes are added if current_version: changelog += [current_version] parts = line.split(" ") patch_version = parts[1] try: # Additional check in case no date is given and as such can not be parsed patch_date = parts[3] except IndexError: patch_date = "YYYY-MM-DD" current_version = { "version": patch_version, "date": patch_date, "release_notes": "", } else: if current_version: current_version["release_notes"] += line changelog += [current_version] return changelog def _format_release_notes(release_notes: Releasenotes) -> str: return f"## {release_notes['version']} - {release_notes['date']}{release_notes['release_notes']}" def save_changelog(changelog: Changelog, filename: Path): """ Args: changelog: Changelog in the same format as returned by load_changelog() filename: filepath under which the changelog will be saved """ click.echo("Saving changelog...") tmpfile = filename.with_suffix(".tmp") with tmpfile.open("w+") as file: for release in changelog: file.write(_format_release_notes(release)) tmpfile.rename(filename) def change_version_in_files( additional_file_edits: List[Tuple[Path, str]], version: str, dry_run: bool = False ): """ Args: additional_file_edits: List of tuples containing a filepath and a regexpr version: Changed Version dry_run: Flag to check if no edits should be made. Helpful when debugging the regular expression. """ for file, regexp in additional_file_edits: # Use tmpfile in case of crash, will replace original later # Careful when using, you need to guarantee that the whole line gets matched click.echo(f"Changes in {file} :") tmp_file = file.with_suffix(".tmp") with file.open("r") as realfile, tmp_file.open("w+") as tmpfile: if dry_run: click.echo(f"{regexp} finds: ") regexp = re.compile(regexp) for line in realfile: re.compile(regexp) line_match = regexp.match(line) if line_match: click.echo(f"\t{line[:-1]} -> ", nl=False) matches = list(line_match.groups()) matches[1] = version line = "".join(matches) + "\n" click.echo(line) tmpfile.write(line) if dry_run: tmp_file.unlink() else: tmp_file.rename(file) def ask_patchtype(project_current_version: str): click.echo(f"The current version is: {project_current_version}") click.echo("What kind of update do you want to make?") if semver.parse(project_current_version)["prerelease"]: RELEASE_CHOICES.update(PRERELEASE_CHOICES) for key, value in RELEASE_CHOICES.items(): click.echo( f"({key}) {value['function'](project_current_version)}\t - {value['description']}" ) click.echo("For more information visit https://semver.org/") patch_type = click.prompt("> ", type=click.Choice(RELEASE_CHOICES.keys())) patch_type = RELEASE_CHOICES[patch_type] return patch_type["function"](project_current_version) def _show_release_notes(release_notes: Releasenotes): click.echo(_format_release_notes(release_notes)) click.echo("-----") click.confirm( "This is how the new release_notes will look like. Do you want to continue?", abort=True, ) def get_version_and_name(pyproject_file: Path = PYPROJECT): with pyproject_file.open() as file: pyproject = toml.load(file) project_pyproject = pyproject["tool"]["poetry"] project_current_version = project_pyproject["version"] project_name = project_pyproject["name"] return project_current_version, project_name def _parse_file_edits(ctx, params, value): return [(Path(file_regex[0]), file_regex[1]) for file_regex in value] @click.command(help="Bump the version number for your project.") @click.option( "--project-dir", default=Path.cwd(), callback=lambda ctx, params, value: Path(value), help="Directory in which to look for the CHANGELOG.md and pyproject.toml", ) @click.option( "--additional-file-edits", "-f", nargs=2, multiple=True, callback=_parse_file_edits, help="Specify <file> <regex> for additional files and a corresponding regex where " "the version number needs to be bumped.", ) @click.option( "--dry-run", is_flag=True, default=False, help="Do a dry run to check if file edits work correctly without changing any files.", ) @click.option( "--prerelease", is_flag=True, default=False, help="Change new version to a prerelease.", ) def bump( project_dir: Path, additional_file_edits: List[str], dry_run: bool, prerelease: bool ): additional_file_edits.append(PYPROJECT_BUMP_CONFIG) # Change to the projects directory in a revertible way prevdir = Path.cwd() os.chdir(project_dir.resolve()) try: if dry_run: click.echo("It's a dry run.") click.echo("The following file edits would be made:") change_version_in_files( additional_file_edits, version="<NEWVER>", dry_run=True ) click.echo( "\nP.S. Be careful to capture the whole line, not captured parts will be deleted!" ) exit(0) project_current_version, project_name = get_version_and_name() new_version = ask_patchtype(project_current_version) if prerelease: new_version = semver.bump_prerelease(new_version) changelog = load_changelog(CHANGELOG) if changelog[0]["version"] != "UNRELEASED": raise SystemExit( "No new release_notes detected. (Start with '## UNRELEASED')" ) changelog[0]["version"] = new_version changelog[0]["date"] = _get_date() + "\n" _show_release_notes(changelog[0]) # Start of all permanent changes changelog.insert(0, EMPTY_PATCH) save_changelog(changelog, CHANGELOG) # Bump in all other files change_version_in_files(additional_file_edits, version=new_version) finally: os.chdir(prevdir)
/cli/bump.py
0.60288
0.169475
bump.py
pypi
.. image:: https://raw.githubusercontent.com/rte-france/relife/main/docs/_images/relife.png :width: 80 ReLife ====== ReLife is an open source Python library for asset management based on reliability theory and lifetime data analysis. - **Survival analysis**: non-parametric estimator (Kaplan-Meier), parametric estimator (Maximum Likelihood) and regression models (Accelerated Failure Time and Parametric Proportional Hazards) on left-truncated, right-censored and left-censored lifetime data. - **Reliability theory**: optimal age of replacement for time-based mainteance policy for one-cycle or infinite number of cycles, with exponential discounting. - **Renewal theory**: expected number of events, expected total costs or expected number of replacements for run-to-failures or age replacement policies. Installation ------------ From PyPI: .. code-block:: console pip3 install relife Documentation ------------- The official documentation is available at https://rte-france.github.io/relife/. Citing ------ .. code-block:: bibtex @misc{relife, author = {T. Guillon}, title = {ReLife: a Python package for asset management based on reliability theory and lifetime data analysis.}, year = {2022}, journal = {GitHub}, howpublished = {\url{https://github.com/rte-france/relife}}, } Credits ------- Icon made by `Freepik <https://www.freepik.com>`_ from `Flaticon <https://www.flaticon.com>`_. Getting Started =============== The following example shows the steps to develop a preventive maintenance policy by age on circuit breakers: 1. Perform a survival analysis on lifetime data, 2. Compute the optimal age of replacement, 3. Compute the expected total discounting costs and number of expected replacements for the next years. Survival analysis ----------------- The survival analysis is perfomed by computing the Kaplan-Meier estimator and fitting the parameters of a Weibull and a Gompertz distribution with the maximum likelihood estimator. .. code-block:: python import numpy as np import matplotlib.pyplot as plt from relife.datasets import load_circuit_breaker from relife import KaplanMeier, Weibull, Gompertz, AgeReplacementPolicy time, event, entry = load_circuit_breaker().astuple() km = KaplanMeier().fit(time,event,entry) weibull = Weibull().fit(time,event,entry) gompertz = Gompertz().fit(time,event,entry) The results of fitting the Weibull and Gompertz distributions are compared by looking at the attributes :code:`weibull.result.AIC` and :code:`gompertz.result.AIC`. The Gompertz distribution gives the best fit and will be chosen for the next step of the study. The code below plots the survival function obtained by the Kaplan-Meier estimator and the maximum likelihood estimator for the Weibull and Gompertz distributions. .. code-block:: python km.plot() weibull.plot() gompertz.plot() plt.xlabel('Age [year]') plt.ylabel('Survival probability') .. figure:: https://raw.githubusercontent.com/rte-france/relife/main/docs/_images/survival-analysis.png Optimal age of replacement -------------------------- We consider 3 circuit breakers with the following parameters: - the current ages of the circuit breakers are a0 = [15, 20, 25] years, - the preventive costs of replacement are evaluated cp = 10 k€, - the failure costs (e.g. lost energy) are evaluated cf = [900, 500, 100] k€, - the discount rate is rate = 0.04. .. code-block:: python a0 = np.array([15, 20, 25]).reshape(-1,1) cp = 10 cf = np.array([900, 500, 100]).reshape(-1,1) policy = AgeReplacementPolicy(gompertz, a0=a0, cf=cf, cp=cp, rate=0.04) policy.fit() policy.ar1, policy.ar Where `ar1` are the time left until the first replacement, whereas `ar` is the optimal age of replacement for the next replacements: .. code-block:: console (array([[10.06828465], [11.5204334 ], [22.58652687]]), array([[20.91858994], [25.54939328], [41.60855399]])) The optimal age of replacement minimizes the asymptotic expected equivalent annual cost. It represents the best compromise between replacement costs and the cost of the consequences of failure. .. code-block:: python a = np.arange(1,100,0.1) za = policy.asymptotic_expected_equivalent_annual_cost(a) za_opt = policy.asymptotic_expected_equivalent_annual_cost() plt.plot(a, za.T) for i, ar in enumerate(policy.ar): plt.scatter(ar, za_opt[i], c=f'C{i}', label=f" cf={cf[i,0]} k€, ar={ar[0]:0.1f} years") plt.xlabel('Age of preventive replacement [years]') plt.ylabel('Asymptotic expected equivalent annual cost [k€]') plt.legend() .. figure:: https://raw.githubusercontent.com/rte-france/relife/main/docs/_images/optimal-ages.png Budget and operations planning ------------------------------ For budgeting, the expected total discounted costs for the 3 circuit breakers are computed and we can plot the total annual discounted costs for the next 30 years, including costs of failures and costs of preventive replacements. .. code-block:: python dt = 0.5 step = int(1/dt) t = np.arange(0, 30+dt, dt) z = policy.expected_total_cost(t).sum(axis=0) y = t[::step][1:] q = np.diff(z[::step]) plt.bar(2020+y, q, align='edge', width=-0.8, alpha=0.8, color='C2') plt.xlabel('Year') plt.ylabel('Expected discounted annual cost in k€') .. figure:: https://raw.githubusercontent.com/rte-france/relife/main/docs/_images/annual-costs.png Then the total number of replacements are projected for the next 30 years. Failure replacements are counted separately in order to prevent and prepare the workload of the maintenance teams. .. code-block:: mt = policy.expected_total_cost(t, cf=1, cp=1, rate=0).sum(axis=0) mf = policy.expected_total_cost(t, cf=1, cp=0, rate=0).sum(axis=0) qt = np.diff(mt[::step]) qf = np.diff(mf[::step]) plt.bar(y+2020, qt, align='edge', width=-0.8, alpha=0.8, color='C1', label='all replacements') plt.bar(y+2020, qf, align='edge', width=-0.8, alpha=0.8, color='C0', label='failure replacements only') plt.xlabel('Years') plt.ylabel('Expected number of annual replacements') plt.legend() The figure shows the expected replacements for the very small sample of 3 circuit breakers. When the population of assets is large, the expected failure replacements is a useful information to build up a stock of materials. .. figure:: https://raw.githubusercontent.com/rte-france/relife/main/docs/_images/replacements.png
/relife-1.0.0.tar.gz/relife-1.0.0/README.rst
0.950846
0.757032
README.rst
pypi
# Reliquery ![GitHub release (latest by date including pre-releases)](https://img.shields.io/github/v/release/The-Dev-Effect/reliquery?include_prereleases) [![example workflow](https://github.com/The-Dev-Effect/reliquery/actions/workflows/main.yml/badge.svg)](https://github.com/The-Dev-Effect/reliquery/actions/workflows/main.yml) ## Science's Artifact Antiformat An anti-format storage tool aimed towards supporting scientists. Giving them the ability to store data how they want and where they want. Simplifying the storage of research materials making them easy to find and easy to share. ## Table of Contents 1. [Production](#prod) 2. [Development](#dev) 1. [Local install](#loc-ins) 3. [Example](#quick) 4. [HTML](#html) 5. [Images](#img) 6. [JSON](#json) 7. [Pandas DataFrame](#pd) 8. [Files](#files) 9. [Jupyter Notebooks](#notebooks) 10. [Query Relics](#query) 11. [Config](#config) 12. [File Storage](#file) 13. [S3 Storage](#s3) 14. [License](#lic) ## For production<a name="prod"></a> latest version 0.2.6 ``` pip install reliquery ``` ## For development<a name="dev"></a> ### Local Install<a name="loc-ins"></a> ``` cd reliquery pip install -e . ``` ### Quick Example Usage<a name="quick"></a> ```python from reliquery import Relic import numpy as np from IPython.display import HTML, Image r = Relic(name="quick", relic_type="tutorial") ones_array = np.ones((10, 10)) r.add_array("ones", ones_array) np.testing.assert_array_equal(r.get_array("ones"), ones_array) r.add_text("long_form", "Some long form text. This is something we can do NLP on later") r.add_tag({"pass": "yes"}) r.add_json("json", {"One":1, "Two": 2, "Three": 3}) print(r.describe()) ``` ### HTML supported<a name="html"></a> Add HTML as a string: ```python # Example r.add_html_string("welcome", "<div><p>Hello, World</p></div>") ``` Add HTML from a file path: ```python # Example r.add_html_from_path("figures", <path to html file>) ``` Get and display HTML using Reliquery: ```python # Read only S3 demo r_demo = Relic(name="intro", relic_type="tutorial", storage_name="demo") print(r_demo.list_html()) display(HTML(r_demo.get_html('nnmf2 resnet34.html'))) ``` ### Images supported<a name="img"></a> Add images by passing images as bytes: ```python # Example with open("image.png", "rb") as f: r.add_image("image-0.png", f.read()) ``` Get and display images: ```pyton print(r_demo.list_images()) display(Image(r_demo.get_image("reliquery").read())) ``` ### JSON supported<a name="json"></a> Add json by passing it in as a dictionary: ```python # Example r.add_json("json", {"First": 1, "Second": 2, "Third":3}) ``` List json ```python r.list_json() ``` Get json by taking the name and returning the dictionary ```python r.get_json("json") ``` ### Pandas DataFrame<a name="pd"></a> Note that json is used to serialize which comes with other caveats that can be found here: https://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.to_json.html ```python #Example d = { "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]), "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]), } df = pd.DataFrame(d) r.add_pandasdf("pandasdf", df) List pandasdf r.list_pandasdf() Get pandas dataframe by taking the name r.get_pandasdf("pandasdf") ``` ### Files <a name="files"></a> ```python #Example r.add_files_from_path("TestFileName", test_file_path) List files r.list_files() Get file r.get_file("TestFileName") Save file r.save_files_to_path("TestFile", path_to_save) ``` ### Jupyter Notebooks<a name="notebooks"></a> ```python #Example test_notebook = os.path.join(os.path.dirname(__file__), "notebook_test.ipynb") r.add_notebook_from_path("TestNotebook", test_notebook) List Notebooks notebook_list = r.list_notebooks() Get Notebook r.get_notebook("TestNotebook") Save Notebook to path path_to_save = os.path.join(tmp_path, "testnotebook.ipynb") r.save_notebook_to_path("TestNotebook", path_to_save) View Notebooka via HTML r.get_notebook_html(TestNotebook) ``` ### Query Relics<a name="query"></a> ```python from reliquery import Reliquery rel = Reliquery() relics = rel.get_relics_by_tag("pass", "yes") relics[0].describe() ``` ### Config<a name="config"></a> A json text file named config located in ~/reliquery <br /> Default looks like... ```json { "default": { "storage": { "type": "File", "args": { "root": "/home/user/reliquery" } } }, "demo": { "storage": { "type": "S3", "args": { "s3_signed": false, "s3_bucket": "reliquery", "prefix": "relics" } } } } ``` ## File Storage<a name="file"></a> With this configuration, the relic will be persisted to: <br /> /home/user/reliquery/relic_type/relic_name/data_type/data_name <br /> In the quick example that will be: <br /> /home/user/reliquery/reliquery/basic/relic_tutorial/arrays/ones <br /> ## S3 Storage<a name="s3"></a> s3_signed * true = uses current aws_cli configuration * false = uses the anonymous IAM role ## License<a name="lic"></a> Reliquery is free and open source! All code in this repository is dual-licensed under either: * MIT License ([LICENSE-MIT](docs/LICENSE-MIT) or [http://opensource.org/licenses/MIT](http://opensource.org/licenses/MIT)) * Apache License, Version 2.0 ([LICENSE-APACHE](docs/LICENSE-APACHE) or [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)) at your option. This means you can select the license you prefer. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
/reliquery-0.3.2.tar.gz/reliquery-0.3.2/README.md
0.566019
0.906322
README.md
pypi
import collections import abc __version__ = '0.4' DEFAULT_FLAG_NAME = '_is_loaded' DEFAULT_FUNCTION_NAME = 'reload' class ReloadedSet(collections.Set, metaclass=abc.ABCMeta): """ A reloaded set - like frozenset but can fetch new data in the function reload. To inheritance you need to make: :ivar _values: The value the set will look when doing staff. :type _values: any things that can be iterable like list, tuple, set or frozen set. :ivar _is_loaded: The flag that will check that the object is first load or not. :type _is_loaded: bool """ def __init__(self, flag_name: str=DEFAULT_FLAG_NAME, function_name: str=DEFAULT_FUNCTION_NAME): setattr(self, flag_name, False) inner_function_name = '_' + function_name @abc.abstractmethod def function(): getattr(self, inner_function_name)() setattr(self, flag_name, True) setattr(self, function_name, function) @property @abc.abstractmethod def _values(self): pass def __contains__(self, item): return item in self._values def __iter__(self): return iter(self._values) def __len__(self): return len(self._values) def issubset(self, other) -> bool: return frozenset(self) <= frozenset(other) def issuperset(self, other) -> bool: return frozenset(self) >= frozenset(other) def union(self, *others) -> frozenset: return frozenset(self).union(*others) def __or__(self, other) -> frozenset: return self.union(other) def intersection(self, *others) -> frozenset: return frozenset(self).intersection(*others) def __and__(self, other) -> frozenset: return self.intersection(other) def difference(self, *others) -> frozenset: return frozenset(self).difference(*others) def __sub__(self, other) -> frozenset: return self.difference(other) def symmetric_difference(self, other) -> frozenset: return frozenset(self).symmetric_difference(other) def __xor__(self, other) -> frozenset: return self.symmetric_difference(other) def load(flag_name: str=DEFAULT_FLAG_NAME, function_name: str=DEFAULT_FUNCTION_NAME): """ This decorator checking of the class was loaded and load it if needed. For lazy. """ def _decorator_wrapper(function): """ The real decorator :param function: The function to wrap. :return: The wrapped function. """ def _load_wrapper(self, *args): flag = getattr(self, flag_name) if not flag: reload_function = getattr(self, function_name) reload_function() return function(self, *args) return _load_wrapper return _decorator_wrapper
/reloaded-set-0.4.tar.gz/reloaded-set-0.4/reloaded_set/__init__.py
0.683525
0.214445
__init__.py
pypi
import json from reloadly_airtime.airtime.sdk.dto.Response.SimplifiedCountry import SimplifiedCountry from reloadly_airtime.airtime.sdk.enums.DenominationType import DenominationType from reloadly_airtime.airtime.sdk.dto.Response.FxRate import FxRate #Class that represents a Reloadly airtime operator object. Related to the {@link OperatorOperations} class Operator: def __init__(self): #Unique id assign to each operator. self.Id = 0 #Name of the mobile operator. self.name = '' #Whether the mobile operator is a prepaid data bundle. Prepaid bundles are a mixture of calls, data, #SMS and social media access which the users can purchase other than airtime credits self.bundle = False #Whether the operator is a prepaid data only self.data = False #Whether the operator is pin based self.pinBased = False #Whether the operator supports local amounts self.supportsLocalAmounts = False #Operator amount denomination type self.denominationType = DenominationType() #ISO-3 currency code of user account self.senderCurrencyCode = '' #User account currency symbol self.senderCurrencySymbol = '' #ISO-3 currency code of operator destination country self.destinationCurrencyCode = '' #Destination currency symbol self.destinationCurrencySymbol = '' #International discount assigned for this operator self.internationalDiscount = 0.0 #Local discount assigned for this operator self.localDiscount = 0.0 #Most popular international amount for this operator self.mostPopularInternationalAmount = 0.0 #Most popular local amount for this operator self.mostPopularLocalAmount = 0.0 #Operator's country self.country = SimplifiedCountry() #Current fx rate for this operator self.fxrate = FxRate() #Suggested whole amounts when denomination type is 'FIXED' self.suggestedAmounts = None #Suggested amounts map containing (amount in sender currency, amount in recipient currency) #when denomination type is 'FIXED' self.suggestedAmountsMap = None #Minimum amount when denomination type is 'RANGE' will be empty/null for 'FIXED' denomination type self.minAmount = 0.0 #Maximum amount when denomination type is 'RANGE', will be empty/null for 'FIXED' denomination type self.localMinAmount = 0.0 #Minimum local amount when denomination type is 'RANGE', will be empty/null for 'FIXED' #denomination type self.localMaxAmount = 0.0 #Maximum local amount when denomination type is 'RANGE', will be empty/null for 'FIXED' denomination self.maxAmount = 0.0 #Available operator amounts when denomination type is 'FIXED', will be empty/null for 'RANGE #denomination type self.fixedAmounts = None #Available operator local amounts when denomination type is 'FIXED', will be empty/null for 'RANGE #denomination type self.localFixedAmounts = None #International fixed amounts descriptions self.fixedAmountsDescriptions = None #Local fixed amounts descriptions self.localFixedAmountsDescriptions=None #Logo url of the mobile operator self.logoUrls = None #Available promotions for this operator if any self.promotions = None
/reloadly_airtime-1.1.2-py3-none-any.whl/reloadly_airtime/airtime/sdk/dto/Response/Operator.py
0.637708
0.350866
Operator.py
pypi
from reloadly_airtime.airtime.sdk.dto.Response import Operator from reloadly_airtime.airtime.sdk.dto.Response import OperatorFxRate from reloadly_core.core.internal.Filter.OperatorFilter import OperatorFilter from reloadly_airtime.airtime.sdk.Internal.FxRateRequest import FxRateRequest from reloadly_core.core.internal.dto.request.interfaces.Request import Request from reloadly_core.core.internal.util.Asserter import Asserter from reloadly_airtime.airtime.sdk.operation.BaseAirtimeOperation import BaseAirtimeOperation import http class OperatorOperations(BaseAirtimeOperation): END_POINT = "operators" PATH_SEGMENT_FX_RATE = "/fx-rate" PATH_SEGMENT_COUNTRIES = "/countries" PATH_SEGMENT_AUTO_DETECT = "/auto-detect" PATH_SEGMENT_AUTO_DETECT_PHONE = "/phone" def __init__(self, client, baseUrl : str, apiToken : str): self.baseUrl = baseUrl self.client = client self.apiToken = apiToken super().__init__(self.client, self.baseUrl, self.apiToken) def List_with_filter(self, Filter): return super().createGetRequest(super().buildFilters(Filter, self.END_POINT)) def List_without_filter(self): return super().createGetRequest(super().getBuilder(self.END_POINT)) def getById_with_filter(self,operatorId : int, Filter): self.validateOperatorId(operatorId) builder = super().buildFilters(Filter, self.END_POINT) builder = builder + "/" + str(operatorId) return super().createGetRequest(str(builder)) def getById_without_filter(self,operatorId : int): self.validateOperatorId(operatorId) builder = super().getBuilder(self.END_POINT) builder = builder + "/" + str(operatorId) return super().createGetRequest(str(builder)) def autoDetect(self,phone : str, countryCode , Filter): self.validatePhoneAndCountryCode(phone, countryCode) return super().createGetRequest(self.buildAutoDetectRequest(phone, countryCode, super().buildFilters(Filter, self.END_POINT))) def autoDetect(self,phone : str, countryCode): self.validatePhoneAndCountryCode(phone, countryCode) return super().createGetRequest(self.buildAutoDetectRequest(phone, countryCode, None)) def listByCountryCode_with_Filters(self,countryCode , Filter): Asserter().assertNotNull(countryCode, "Country code") builder = self.buildListByCountryCodeRequestUrl(countryCode, None) return super().createGetRequest(self.buildListByCountryCodeRequestUrl(countryCode, super().buildFilters(Filter, str(builder)))) def listByCountryCode_without_Filters(self, countryCode): Asserter().assertNotNull(countryCode, "Country code") return super().createGetRequest(self.buildListByCountryCodeRequestUrl(countryCode, None)) def calculateFxRate(self, operatorId : int, amount : float): self.validateOperatorId(operatorId) Asserter().assertNotNull(amount, "Amount") Asserter().assertGreaterThanZero(amount, "Amount") return super().createPostRequest(self.buildCalculateFxRateRequestUrl(operatorId), amount) def buildListByCountryCodeRequestUrl(self ,countryCode , builder : str): if builder == None: builder = super().getBuilder(self.END_POINT) return builder + self.PATH_SEGMENT_COUNTRIES + "/" + str(countryCode) def buildCalculateFxRateRequestUrl(self,operatorId : int): return super().getBuilder(self.END_POINT + self.PATH_SEGMENT_FX_RATE + "/" + str(operatorId)) def buildAutoDetectRequest(self,phone : str, countryCode, builder : str): if "+" not in str(phone): phone = int("+" + str(phone)) if builder == None: builder = super().getBuilder(self.END_POINT) return builder + self.PATH_SEGMENT_AUTO_DETECT + self.PATH_SEGMENT_AUTO_DETECT_PHONE + "/" + str(phone) + self.PATH_SEGMENT_COUNTRIES + "/" + str(countryCode) def validateOperatorId(self,operatorId : int): Asserter().assertNotNull(operatorId, "Operator id") Asserter().assertGreaterThanZero(operatorId, "Operator id") def validatePhoneAndCountryCode(self,phone : str, countryCode): Asserter().assertGreaterThanZero(phone, "Phone") Asserter().assertNotNull(countryCode, "Country code")
/reloadly_airtime-1.1.2-py3-none-any.whl/reloadly_airtime/airtime/sdk/operation/OperatorOperations.py
0.611382
0.179459
OperatorOperations.py
pypi
from reloadly_core.core.internal.Filter.QueryFilter import QueryFilter from reloadly_core.core.internal.util.Asserter import Asserter import datetime as datetime class TransactionHistoryFilter(QueryFilter): END_DATE = "endDate" START_DATE = "startDate" OPERATOR_ID = "operatorId" COUNTRY_CODE = "countryCode" OPERATOR_NAME = "operatorName" CUSTOM_IDENTIFIER = "customIdentifier" def getParameters(self): self.parameters = {} return self def withPage(self, pageNumber : int, pageSize : int): super().withPage(pageNumber,pageSize) return self.parameters """@param operatorId - Operator id to filter by * @return - TransactionHistoryFilter""" def operatorId(self, operatorId : int): Asserter().assertNotNull(operatorId, "Operator id") Asserter().assertGreaterThanZero(operatorId,"Operator id") self.parameters[self.OPERATOR_ID] = operatorId return self.parameters """ @param countryCode - Country code to filter by * @return - TransactionHistoryFilter""" def CountryCode(self, CountryCode): Asserter().assertNotNull(self.countryCode, "Country Code") self.parameters[self.COUNTRY_CODE] = self.countryCode.getAlpha2() return self.parameters """@param operatorName - Operator name to filter by * @return - TransactionHistoryFilter""" def operatorName(self, operatorName : str): Asserter().assertNotBlank(operatorName, "Operator name") self.parameters[self.OPERATOR_NAME] = operatorName return self.parameters """@param customIdentifier - Custom identifier to filter by * @return - TransactionHistoryFilter""" def customIdentifier(self, customIdentifier : str): Asserter().assertNotBlank(customIdentifier, "Custom identifier") self.parameters[self.CUSTOM_IDENTIFIER] = customIdentifier return self.parameters """@param startDate - Date range start date to filter by * @return - TransactionHistoryFilter""" def startDate(self, startDate = datetime.datetime.now()): Asserter().assertNotNull(startDate, "Start date") self.parameters[self.START_DATE] = startDate.strftime("%m/%d/%Y, %H:%M:%S") return self.parameters """@param endDate - Date range end date to filter by * @return - TransactionHistoryFilter""" def endDate(self, endDate = datetime.datetime.now()): Asserter().assertNotNull(endDate, "End date") self.parameters[self.END_DATE] = endDate.strftime("%m/%d/%Y, %H:%M:%S") return self.parameters
/reloadly_core-1.1.1.tar.gz/reloadly_core-1.1.1/reloadly_core/core/internal/Filter/TransactionHistoryFilter.py
0.525125
0.257118
TransactionHistoryFilter.py
pypi
# GiftCards API The implementation is based on the [GiftCards API Docs](https://docs.reloadly.com/giftcards/). ## Usage Create an `GiftcardAPI` instance by providing the Application details (client id & secret) from the [dashboard](https://www.reloadly.com/developers/api-settings). Some key things to keep in mind regarding the Airtime API : * The API has 2 environments, SANDBOX (for development & testing) and LIVE. `Environment.GIFTCARD` is used for the Live environmnent and `Environment.GIFTCARD_SANDBOX` is for the Sandbox. * If neither environment is specified, the SDK defaults to SANDBOX * Each environment has a set of credentials (client id & secret) that are different from the other.<br /> * SANBOX credentials can only be used for SANDBOX environment * LIVE credentials can only be used for LIVE environment * If not environment is specified the SDK defaults to SANDBOX * You MUST supply either the credentials, or an access token in order to call the API <br /><br /> As stated above, requests to the Airtime API require authentication/authorization, there are several options : ### Option 1 Set the client id & client secret; this is probably the most straight-forward or simplest way. An access token will be acquired automatically before the API call is made. ```python from reloadly_core.core.enums.Environment import Environment from reloadly_giftcard.giftcard.sdk.client.giftcardAPI import GiftCards giftcardAPI = GiftCards(clientId="*****", clientSecret="*****", environment=Environment.GIFTCARD_SANDBOX) response = giftcardAPI.products().List_without_filter() print (response) ``` ### Option 2 You may alternatively acquire an access token from the [AuthenticationAPI](https://github.com/reloadly/reloadly-sdk-python/blob/master/docs/authentication/USAGE.md) and then set it. ```python from reloadly_auth.authentication.client.AuthenticationAPI import AuthenticationAPI from reloadly_core.core.enums.Service import Service from reloadly_core.core.enums.Environment import Environment from reloadly_giftcard.giftcard.sdk.client.giftcardAPI import GiftCards sample = AuthenticationAPI() a = sample.clientCredentials(clientId="*****", clientSecret="*****" service=Service.GIFTCARD_SANDBOX).getAccessToken(Service.GIFTCARD_SANDBOX) giftcardAPI = GiftCards(accessToken = a, Environment.GIFTCARD_SANDBOX) response = giftcardAPI.products().List_without_filter() print (response) ``` **Note : Access tokens obtain for Reloadly APIs have a finite lifetime. [See the API docs](https://developers.reloadly.com/#authentication_auth_anc)** Using the example above has some benefits and drawbacks: #### Pro * API requests become efficient & performant. * Setting the access token skips the automatic token acquisition API calls that would have otherwise been made before each Airtime API service calls. #### Cons * However, because access tokens have a finite lifetime, you now have to manage or handle the expiration of the access token in your application code. * In the sample above, the AirtimeAPI will continue using the same access token until it expires. Therefore, the responsibility falls on you to handle token renewal when the token expires. ### Sample token expiration handling ```python from reloadly_core.core.enums.Environment import Environment from reloadly_giftcard.giftcard.sdk.client.giftcardAPI import GiftCards # Refresh token using AuthenticationAPI sample = AuthenticationAPI() a = sample.clientCredentials(clientId="*****", clientSecret="*****" service=Service.GIFTCARD_SANDBOX).getAccessToken(Service.GIFTCARD_SANDBOX) giftcardAPI = GiftCards(accessToken = a, Environment.GIFTCARD_SANDBOX) try: request = giftcardAPI.products().List_without_filter() if response['errorCode'] == "TOKEN_EXPIRED": response = giftcardAPI.refreshAccessToken(request) return response else: # add logic except: raise Exception("ReloadlyException") ``` ### Logging request & response To enable API request/response logging, set `enablelogging` to true when intiaiting the AirtimeAPI class ```python giftcardAPI = GiftCards(clientId="*****", clientSecret="*****", environment=Environment.GIFTCARD_SANDBOX, enablelogging=True) .... ``` ## Customizing The API Client Instance ### Configuring Timeouts Used to configure additional options, connect and read timeouts can be configured globally: ```python giftcardAPI = GiftCards( clientId="*****", clientSecret="*****", environment=Environment.GIFTCARD_SANDBOX, options = HttpOptions(readTimeout=60, writeTimeout=60, connectTimeout=60) ) .... ``` ### Proxy Configuration ```python proxyPort = 8085; # Your proxy port proxyUsername = "your-proxy-authentication-username"; # Optional proxy username if your proxy requires authentication proxyPassword = "your-proxy-authentication-password"; # Optional proxy password if your proxy requires authentication proxyHost = "you-proxy-host-name.com"; Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)); giftcardAPI = GiftCards( clientId="*****", clientSecret="*****", environment=Environment.GIFTCARD_SANDBOX, options = HttpOptions() ) .... .... # If proxy does NOT require authentication .... ``` ### Request latency telemetry By default, the library sends request latency telemetry to Reloadly. These numbers help Reloadly improve the overall latency of its API for all users. You can disable this behavior if you prefer: ```python giftcardAPI = GiftCards(clientId="*****", clientSecret="*****", environment=Environment.GIFTCARD_SANDBOX, enableTelemetry=False) .... ```
/reloadly_giftcard-1.1.6.tar.gz/reloadly_giftcard-1.1.6/README.md
0.411466
0.822403
README.md
pypi
from reloadly_core.core.internal.Filter.QueryFilter import QueryFilter from reloadly_core.core.internal.util.Asserter import Asserter import datetime as datetime class TransactionHistoryFilter(QueryFilter): END_DATE = "endDate" START_DATE = "startDate" OPERATOR_ID = "operatorId" COUNTRY_CODE = "countryCode" OPERATOR_NAME = "operatorName" CUSTOM_IDENTIFIER = "customIdentifier" def getParameters(self): self.parameters = {} return self def withPage(self, pageNumber : int, pageSize : int): super().withPage(pageNumber,pageSize) return self """@param operatorId - Operator id to filter by * @return - TransactionHistoryFilter""" def operatorId(self, operatorId : int): Asserter().assertNotNull(operatorId, "Operator id") Asserter().assertGreaterThanZero(operatorId,"Operator id") self.parameters[self.OPERATOR_ID] = operatorId return self """ @param countryCode - Country code to filter by * @return - TransactionHistoryFilter""" def CountryCode(self, CountryCode): Asserter().assertNotNull(self.countryCode, "Country Code") self.parameters[self.COUNTRY_CODE] = self.countryCode.getAlpha2() return self """@param operatorName - Operator name to filter by * @return - TransactionHistoryFilter""" def operatorName(self, operatorName : str): Asserter().assertNotBlank(operatorName, "Operator name") self.parameters[self.OPERATOR_NAME] = operatorName return self """@param customIdentifier - Custom identifier to filter by * @return - TransactionHistoryFilter""" def customIdentifier(self, customIdentifier : str): Asserter().assertNotBlank(customIdentifier, "Custom identifier") self.parameters[self.CUSTOM_IDENTIFIER] = customIdentifier return self """@param startDate - Date range start date to filter by * @return - TransactionHistoryFilter""" def startDate(self, startDate = datetime.datetime.now()): Asserter().assertNotNull(startDate, "Start date") self.parameters[self.START_DATE] = startDate.strftime("%m/%d/%Y, %H:%M:%S") return self """@param endDate - Date range end date to filter by * @return - TransactionHistoryFilter""" def endDate(self, endDate = datetime.datetime.now()): Asserter().assertNotNull(endDate, "End date") self.parameters[self.END_DATE] = endDate.strftime("%m/%d/%Y, %H:%M:%S") return self
/reloadly_giftcard-1.1.6.tar.gz/reloadly_giftcard-1.1.6/reloadly_giftcard/giftcard/sdk/Filter/TransactionHistoryFilter.py
0.546738
0.260143
TransactionHistoryFilter.py
pypi
from reloadly_giftcard.giftcard.sdk.dto.Response.Transaction import Transactions from reloadly_core.core.internal.dto.request.interfaces.Request import Request from reloadly_core.core.internal.Filter.QueryFilter import QueryFilter from reloadly_core.core.internal.util.Asserter import Asserter from reloadly_giftcard.giftcard.sdk.operation.BaseGiftCardOperation import BaseGiftCardOperation class OrderOperations(BaseGiftCardOperation): END_POINT = "orders" TRANSACTION_PATH = "transactions" CARD_PATH = "cards" def __init__(self, client, baseUrl : str, apiToken : str): self.client = client self.baseUrl = baseUrl self.apiToken = apiToken super().__init__(self.client, self.baseUrl, self.apiToken) def send(self, request): self.validateOrderRequest(request) return super().createPostRequest(super().getBuilder(self.END_POINT), request) def getCode(self, transactionId: int): self.validateTransactionId(transactionId) builder = super().getBuilder(self.END_POINT + "/" + self.TRANSACTION_PATH + "/" + str(transactionId) + "/" + self.CARD_PATH) return super().createGetRequest(str(builder)) def validateTransactionId(self, transactionId: int): Asserter().assertNotNull(transactionId, "Transaction Id") Asserter().assertGreaterThanZero(transactionId, "Transaction Id") def validateOrderRequest(self,request): Asserter().assertNotNull(request["unitPrice"], "unitPrice") Asserter().assertGreaterThanZero(request["unitPrice"], "unitPrice") Asserter().assertNotNull(request["quantity"], "quantity") Asserter().assertGreaterThanZero(request["quantity"], "quantity") Asserter().assertNotNull(request["productId"], "Product Id") Asserter().assertGreaterThanZero(request["productId"], "Product id") Asserter().assertNotNull(request["customIdentifier"], "customIdentifier") Asserter().assertValidEmail(request["recipientEmail"], "RecepientEmail") # todo, add redeem card codes here.
/reloadly_giftcard-1.1.6.tar.gz/reloadly_giftcard-1.1.6/reloadly_giftcard/giftcard/sdk/operation/OrderOperations.py
0.502686
0.150871
OrderOperations.py
pypi
from abc import ABC, abstractmethod from collections import defaultdict from pprint import pformat import threading import typing import weakref # Dependency Packages # Local Packages and Modules from . import core from . import formatting from . import handler class BaseLogger(ABC): """ Abstract base class for Logger objects. A logger that performs logging operations across its assigned handlers. """ def __init__(self, name:str, level:int=core.NOTSET): """ Initialize the class attribute(s). :param name: Unique identifier for the instance. :kwarg int level: Output logging level. """ self._name = str(name) self._level = int(level) self._lock = None self._d_handlers = defaultdict(list) self._disabled = False def __repr__(self) -> str: """Representation of the class.""" return f'<{self.__class__.__name__} {id(self)} "{self.name}"">' @property def name(self) -> str: """Unique identifier for the instance.""" return self._name @property def level(self) -> int: """ Output logging level. Only handlers associated to this logging level will log output. """ return self._level @level.setter def level(self, level:int): """ Value and type setter for the level property. :raise ValueError: If the given value is not valid. """ if not core.is_log_level_used(level): raise ValueError(f'Unknown logging level: {level}') with self.lock: self._level = level @property @abstractmethod def lock_id(self) -> str: """ Specific ID of the threading lock to use for the logger. This should be implemented by a logger sub-class for its own needs. """ pass @property def lock(self) -> threading.RLock: """Threading lock used by the logger.""" if not self._lock: self._lock = core.get_lock(self.lock_id) return self._lock @property def disabled(self) -> bool: """All logging output for the instance is disabled.""" return self._disabled or self.level == core.NOTSET @disabled.setter def disabled(self, disabled:bool): """Value and type setter for the disabled property.""" with self.lock: self._disabled = bool(disabled) def _log(self, msg, level, *args, **kwargs): """ Low-level routine that creates the LogRecord and actually forwards it to the handlers associated to logging level. :param level: Logging level of the message. :param msg: Message to log. :kwarg bool pretty: Use pretty formatting for the message. """ if not self.is_enabled_for(level): return pretty = kwargs.get('pretty') record = core.LogRecord(level, pformat(msg) if pretty else msg) with self.lock: for handler_ in self._d_handlers[level]: handler_.handle(record) def is_enabled_for(self, level:int) -> bool: """ A logger is not disabled and has handlers associated to at least the specified level. """ return (not self._disabled and level != core.NOTSET and level >= self.level ) def log(self, msg, *args, **kwargs): """ Log a message. If a level is not specified, this will use the instance's level. """ level = kwargs.pop('level', self.level) self._log(msg, level, *args, **kwargs) def debug(self, msg, *args, **kwargs): """ Log a debugging message. :param msg: Message to log. """ self._log(msg, core.DEBUG, *args, **kwargs) def info(self, msg, *args, **kwargs): """ Log a informational (typical print statement) message. :param msg: Message to log. """ self._log(msg, core.INFO, *args, **kwargs) def warning(self, msg, *args, **kwargs): """ Log a warning message. :param msg: Message to log. """ self._log(msg, core.WARNING, *args, **kwargs) def error(self, msg, *args, **kwargs): """ Log an error message. :param msg: Message to log. """ self._log(msg, core.ERROR, *args, **kwargs) def fatal(self, msg, *args, **kwargs): """ Log a fatal error message. :param msg: Message to log. """ self._log(msg, core.FATAL, *args, **kwargs) def has_handlers(self) -> bool: """True if the instance has any handler registered to a level.""" return any(len(x) for x in self._d_handlers.values()) def add_handler(self, handler_:handler.BaseHandler, level:int, **kwargs): """ Add a handler registered at a logging level. The handler will be available to all levels above the given level threshold. :param handler: Handler to use :param level: Level at which the handler should be registered. :kwarg bool level_only: Assign the handler only to the given level. :raise TypeError: For an invalid handler object. :raise ValueError: For invalid levels. """ level_only = kwargs.get('level_only') if not isinstance(handler_, handler.BaseHandler): raise TypeError('Argument must be a derivative of BaseHandler; ' f' got {type(handler_)}') if not core.is_log_level_used(level): raise ValueError(f'Unknown logging level: {level}') if level == core.NOTSET: raise ValueError('Cannot assign a handlers to NOTSET.') l_relevant_levels = [x for x in core.get_log_levels() if x >= level] with self.lock: if level_only: self._d_handlers[level].append(handler_) else: for lvl in l_relevant_levels: self._d_handlers[lvl].append(handler_) def remove_handler(self, handler_:handler.BaseHandler, **kwargs): """ Remove a handler from all levels it is relevant to for the instance. :param handler: Handler to remove :kwarg int level: Specific level from which to remove the handler. :raise TypeError: For handler arguments that are not valid objects. """ level = kwargs.get('level') if not isinstance(handler_, handler.BaseHandler): raise TypeError('Argument must be a derivative of BaseHandler; ' f'got {type(handler_)}') with self.lock: if level and handler_ in self._d_handlers[level]: self._d_handlers[level].remove(handler_) else: for lvl, l_handlers in self._d_handlers.copy().items(): if handler_ in l_handlers: self._d_handlers[lvl].remove(handler_) def remove_handlers(self, level:int=core.NOTSET): """ Remove all handlers from the instance or from a particular logging level. kwarg int level: Specific level to remove handlers from, or all levels if not given. :raise ValueError: For invalid level parameter. """ if not core.is_log_level_used(level): raise ValueError(f'Unknown logging level: {level}') with self.lock: if not level: self._d_handlers = defaultdict(list) else: self._d_handlers[level] = list() class _RootLogger(BaseLogger): """ Default logger that is used for module-level logging operations when no other logger has been created or prioritized. This logger will output to a standard output stream in the same manner as `print` calls. This class is intended for internal use only. """ def __init__(self): """Initialize the class attribute(s).""" super().__init__(self.__class__.__name__, level=core.INFO) @property def lock_id(self) -> str: """Specific ID of the threading lock to use for the handler.""" return self.name # ID for lock used by logger modifications LOGGER_LOCK_ID = '_logger' # Root logger instance. Internal use only. _root_logger = _RootLogger() _root_logger.add_handler(handler.StreamHandler(), core.INFO) DEFAULT_ROOT_ID = _root_logger.name _custom_root_id = None # Tracked logger objects. Internal use only. _wvd_loggers = weakref.WeakValueDictionary() _wvd_loggers[_root_logger.name] = _root_logger def get_logger(name=None) -> BaseLogger: """ Return a specific logger, or the root logger if no name is given. :kwarg str name: Name of the logger to retrieve. :raise ValueError: If the logger does not exist. """ global _custom_root_id if not name: name = _custom_root_id if _custom_root_id else DEFAULT_ROOT_ID with core.get_lock(LOGGER_LOCK_ID): try: _logger = _wvd_loggers[name] except KeyError as key_err: if _custom_root_id and key_err.args[0] == _custom_root_id: _custom_root_id = None _logger = _wvd_loggers[DEFAULT_ROOT_ID] else: raise ValueError(f'No such logger: {name}') return _logger def register_logger(new_logger:BaseLogger, as_root=False): """ Register a new logger with the module, allowing it to be retrievable with `get_logger`. :param new_logger: Logger instance to register. :kwarg bool as_root: Register the new logger as the logger to use for root logging calls instead of the module default. :raise TypeError: If the logger parameter is invalid. """ if not isinstance(new_logger, BaseLogger): raise TypeError(f'Not a sub-class of BaseLogger: {type(new_logger)}') global _custom_root_id with core.get_lock(LOGGER_LOCK_ID): if as_root: _custom_root_id = new_logger.name _wvd_loggers[new_logger.name] = new_logger def log(msg, level, *args, **kwargs): """ Log a message using the root logger. A level given as a keyword argument will be overwritten by the level argument. :param msg: Message to log. :param level: Logging level of the message. """ kwargs['level'] = level root_logger = get_logger() root_logger.log(msg, *args, **kwargs) def debug(msg, *args, **kwargs): """ Log a debugging message using the root logger. :param msg: Message to log. """ root_logger = get_logger() root_logger.debug(msg, *args, **kwargs) def info(msg, *args, **kwargs): """ Log a informational (typical print statement) message using the root logger. :param msg: Message to log. """ root_logger = get_logger() root_logger.info(msg, *args, **kwargs) def warning(msg, *args, **kwargs): """ Log a warning message using the root logger. :param msg: Message to log. """ root_logger = get_logger() root_logger.warning(msg, *args, **kwargs) def error(msg, *args, **kwargs): """ Log an error message using the root logger. :param msg: Message to log. """ root_logger = get_logger() root_logger.error(msg, *args, **kwargs) def fatal(msg, *args, **kwargs): """ Log a fatal error message using the root logger. :param msg: Message to log. """ root_logger = get_logger() root_logger.fatal(msg, *args, **kwargs)
/relogged-0.1.0-py3-none-any.whl/relog/logger.py
0.893623
0.179531
logger.py
pypi
from abc import ABC, abstractmethod import sys import threading import typing # Dependency Packages # Local Packages and Modules from . import core from . import formatting class Filter(typing.NamedTuple): """ Named tuple structure for Filter components. A filter function must return True or False to determine pass or fail, respectively. Passing on True prevents filter functions with no return value (i.e. `None`) from being considered a pass. """ func:typing.Callable[..., typing.Any] args:tuple = tuple() kwargs:dict = dict() class BaseHandler(ABC): """Base handler class.""" def __init__(self, **kwargs): """ Initialize the class attribute(s). Specifying a format string with or without format arguments will take precedence over specifying a formatter object. If none are specified, the handler will create a formatter using just the message output. :kwarg str name: Specific identifier for the handler :kwarg Formatter formatter: Specific formatter instance to use :kwarg str format_str: Format string, populated or unpopulated. :kwarg tuple format_args: Formatting arguments for the format string """ name = kwargs.get('name', '') formatter = kwargs.get('formatter') format_str = kwargs.get('format', '') format_args = kwargs.get('format_args', tuple()) if format_str and format_args: formatter = formatting.Formatter(format_str, *format_args) elif format_str and not format_args: formatter = formatting.Formatter(format_str) elif not formatter: formatter = formatting.Formatter('{}', formatting.MSG) self._name = name if name else id(self) self._lock = None self._l_filters = list() self.formatter = formatter def __repr__(self) -> str: """Representation of the class.""" return f'<{self.__class__.__name__} {self.name}>' @property @abstractmethod def lock_id(self) -> str: """ Specific ID of the threading lock to use for the handler. This should be implemented by a handler sub-class for its own needs. """ pass @property def lock(self) -> threading.RLock: """Threading lock used by the handler.""" if not self._lock: self._lock = core.get_lock(self.lock_id) return self._lock @property def name(self) -> str: """Specific identifier for the handler.""" return self._name @property def formatter(self) -> str: """Formatter instance that formats record text.""" return self._formatter @formatter.setter def formatter(self, formatter:formatting.Formatter): """ Value and type setter for the formatter property. :raise TypeError: If the given value is not of the correct type. """ if not isinstance(formatter, formatting.Formatter): raise TypeError( 'Can only assign Formatter objects to formatter attribute') self._formatter = formatter @property def format(self) -> str: """Format string used by the handler.""" return self._formatter.format @abstractmethod def emit(self, record:core.LogRecord): """ Emit a log record to its destination. This is the actual "logging" function that sends the formatted record to its IO destination. It should be called by `handle` instead of directly by other sources. This should be implemented by a handler sub-class for its own needs. :param record: Record to emit """ pass @abstractmethod def flush(self): """ Flush all logging output. This should be implemented by a handler for its own needs. """ pass def format_record(self, record:core.LogRecord) -> str: """ Create a formatted string of the record's contents, updated as needed. :param record: Record to format into a string. :returns: String formatted with formatting and record contents """ return self.formatter.format_record(record) def handle(self, record:core.LogRecord): """ Handle a log record by filtering it to determine whether or not it meets emission criteria. Emission criteria always consitutes all filters passing in order to emit the record. :param record: Record to handle. """ for nt_filter in self._l_filters: if not nt_filter.func(record, *nt_filter.args, **nt_filter.kwargs): return with self.lock: self.emit(record) def add_filter(self, new_filter:Filter): """ Add a record filter to the handler. :param new_filter: A function or Filter object to do the filtering. :raise TypeError: For an invalid filter argument. """ if not isinstance(new_filter, Filter): raise TypeError('Can only add Filter objects.') self._l_filters.append(new_filter) def remove_filter(self, old_filter:Filter): """ Remove a filter from the handler. :param old_filter: A function or Filter object to do the filtering. """ try: self._l_filters.remove(old_filter) except ValueError: pass class StreamHandler(BaseHandler): """ Handler class that logs records to an IO stream. :note: This class does not close the stream, as `sys.stdout` `sys.stderr` may be used. """ def __init__(self, **kwargs): """ Initialize the class attribute(s). :kwarg TextIOWrapper stream: IO stream used for the handler :kwarg str name: Custom name for the handler; otherwise `<stream>-<object ID>`. :raise ValueError: Invalid stream specified """ stream = kwargs.pop('stream', sys.stderr) name = kwargs.get('name') # Not unique to this init; check only if not self.is_valid_stream(stream): raise ValueError(f'Invalid IO stream: {stream}') super().__init__(**kwargs) self._stream = stream if not name: # Stream + id differentiates multiple stream handlers self._name = f'{self.name_for_stream(self.stream)}-{id(self)}' @property def lock_id(self) -> str: """Specific ID of the threading lock to use for the handler.""" return 'stdout' if self.stream == sys.stdout else 'stderr' @property def stream(self) -> str: """Stream used by the handler.""" return self._stream @staticmethod def is_valid_stream(stream) -> str: """Given stream is a valid stream source for the handler.""" return any(stream == x for x in [sys.stderr, sys.stdout]) @staticmethod def name_for_stream(stream) -> str: """Shorthand name for a given stream.""" if stream == sys.stdout: return 'stdout' elif stream == sys.stderr: return 'stderr' else: return 'unknown' def flush(self): """Flush the stream.""" with self.lock: if self.stream and hasattr(self.stream, 'flush'): self.stream.flush() def emit(self, record:core.LogRecord): """ Emit (print) a log record to its destination. :param record: Record to emit """ with self.lock: self.stream.write(f'{self.format_record(record)}\n') self.flush()
/relogged-0.1.0-py3-none-any.whl/relog/handler.py
0.764276
0.257589
handler.py
pypi
import time import typing # Dependency Packages # Local Packages and Modules from . import core # ID for lock used by format modifications FORMAT_LOCK_ID = '_format' class FormatStyle(typing.NamedTuple): """Valid formatting styles.""" name: str modern: str legacy: str def __str__(self): """String representation of the class.""" return self.modern class Formatter: """ Instance governing how record data and text get formatted into logging output. """ def __init__(self, *args, **kwargs): """ Initialize the class attribute(s). If no args are given, a format of just the message will be used. Otherwise, args should either be a sequence of a single populated string, or a sequence of an unpopulated string followed by the formatting styles to populate it with, in order, e.g.: Formatter('{0}...{n}', MSG, TIME, ...) :raise TypeError: If the format string is not a str type """ datefmt = str(kwargs.get('datefmt', '%Y-%m-%d %H:%M:%S')) with_msecs = kwargs.get('with_msecs', True) msec_delim = kwargs.get('msec_delim', ',') gmtime = kwargs.get('gmtime', False) self._datefmt = datefmt self._with_msecs = with_msecs self._msec_delim = msec_delim self._gmtime = gmtime with core.get_lock(FORMAT_LOCK_ID): self._d_fmts = {x.name:False for x in _l_formats} if not args: self._format = populate_unformatted('{}', MSG) self._d_fmts[MSG.name] = True return if not isinstance(args[0], str): raise TypeError( f"Expected format string; got type '{type(args[0])}'") if len(args) == 1: self._format = modernize_legacy_formats(args[0]) with core.get_lock(FORMAT_LOCK_ID): for fmt in _l_formats: self._d_fmts[fmt.name] = fmt.modern in self._format else: l_fmts = args[1:] raw_format = populate_unformatted(args[0], *l_fmts) self._format = modernize_legacy_formats(raw_format) self._d_fmts.update({x.name:True for x in l_fmts}) @property def format(self) -> str: """Format string to be populated by record text and data.""" return self._format def format_record(self, record:core.LogRecord) -> str: """ Create a formatted string of the record's contents, updated as needed. :param record: Record to format into a string. :returns: String formatted with formatting and record contents """ d_fmt_content = dict() if self._d_fmts[MSG.name]: d_fmt_content[MSG.name] = record.text if self._d_fmts[LVL.name]: d_fmt_content[LVL.name] = core.name_of_level(record.level) if self._d_fmts[LVLNO.name]: d_fmt_content[LVLNO.name] = record.level if self._d_fmts[TIME.name]: d_fmt_content[TIME.name] = self.format_time(record) if self._d_fmts[CREATED.name]: d_fmt_content[CREATED.name] = record.created if self._d_fmts[RELCR.name]: d_fmt_content[RELCR.name] = record.relative_created_ms return self.format.format(**d_fmt_content) def format_time(self, record:core.LogRecord, **kwargs) -> str: """ Create a formatted timestamp of the record's creation time. Default variables for formatting options can be overwritten at run time, OR this whole function can be re-implemented in a subclass of Formatter to gain extra specific functionality. See the `time` package documentation for specifics about formatting options and the difference between local and GM time for creating timestamps. :param record: Record to format into a string. :kwarg str datefmt: Format string for the timestamp. :kwarg bool with_msecs: Attach milliseconds to the timestamp. :kwarg bool gmtime: Use GM time for the time style. :return: Formatted time stamp of record creation time. """ datefmt = kwargs.get('datefmt', self._datefmt) with_msecs = kwargs.get('with_msecs', self._with_msecs) msec_delim = kwargs.get('msec_delim', self._msec_delim) gmtime = kwargs.get('gmtime', self._gmtime) if gmtime: current_time = time.gmtime(record.created) else: current_time = time.localtime(record.created) formatted_time = time.strftime(datefmt, current_time) if with_msecs: return f'{formatted_time}{msec_delim}{record.msecs:03}' return formatted_time # List of format styles. Internal use only. _l_formats = [ FormatStyle(name='time', modern='{time}', legacy='%(asctime)s'), FormatStyle(name='created', modern='{created}', legacy='%(created)f'), FormatStyle(name='file', modern='{file}', legacy='%(filename)s'), FormatStyle(name='func', modern='{func}', legacy='%(funcName)s'), FormatStyle(name='lvl', modern='{lvl}', legacy='%(levelname)s'), FormatStyle(name='lvlno', modern='{lvlno}', legacy='%(levelno)s'), FormatStyle(name='line', modern='{line}', legacy='%(lineno)d'), FormatStyle(name='msg', modern='{msg}', legacy='%(message)s'), FormatStyle(name='module', modern='{module}', legacy='%(module)s'), FormatStyle(name='msecs', modern='{msecs}', legacy='%(msecs)d'), FormatStyle(name='name', modern='{name}', legacy='%(name)s'), FormatStyle(name='path', modern='{path}', legacy='%(pathname)s'), FormatStyle(name='pid', modern='{pid}', legacy='%(process)d'), FormatStyle(name='proc', modern='{proc}', legacy='%(processName)s'), FormatStyle(name='relcr', modern='{relcr}', legacy='%(relativeCreated)d'), FormatStyle(name='thid', modern='{thid}', legacy='%(thread)d'), FormatStyle(name='thread', modern='{thread}', legacy='%(threadName)s'), ] # Global shorthand references to format styles. TIME = [x for x in _l_formats if x.name == 'time' ][0] CREATED = [x for x in _l_formats if x.name == 'created' ][0] FILE = [x for x in _l_formats if x.name == 'file' ][0] FUNC = [x for x in _l_formats if x.name == 'func' ][0] LVL = [x for x in _l_formats if x.name == 'lvl' ][0] LVLNO = [x for x in _l_formats if x.name == 'lvlno' ][0] LINE = [x for x in _l_formats if x.name == 'line' ][0] MSG = [x for x in _l_formats if x.name == 'msg' ][0] MODULE = [x for x in _l_formats if x.name == 'module' ][0] MSECS = [x for x in _l_formats if x.name == 'msecs' ][0] NAME = [x for x in _l_formats if x.name == 'name' ][0] PATH = [x for x in _l_formats if x.name == 'path' ][0] PID = [x for x in _l_formats if x.name == 'pid' ][0] PROC = [x for x in _l_formats if x.name == 'proc' ][0] RELCR = [x for x in _l_formats if x.name == 'relcr' ][0] THID = [x for x in _l_formats if x.name == 'thid' ][0] THREAD = [x for x in _l_formats if x.name == 'thread' ][0] def populate_unformatted(unformatted_str:str, *args) -> str: """ Format a given string with a list of FormatStyle objects and return the result. This assumes that the unformatted string is a string like those used with the `format` function, such as `'{} | {}'`, `'{0} | {1}'`, etc. :param unformatted_str: Desired format string containing format characters to be populated by the args iterable. :param args: Sequence of FormatStyle objects. :raise TypeError: If any arg is not the expected object. :returns: Formatted string """ if any(not isinstance(fmt_arg, FormatStyle) for fmt_arg in args): raise TypeError('Format arguments must be FormatStyle enumerations; ' f'got {tuple(type(arg) for arg in args)}') return unformatted_str.format(*(x.modern for x in args)) def modernize_legacy_formats(format_str:str) -> str: """ Replace any legacy format strings with this lib's "modern" versions. :param format_str: Format string to parse and replace. :returns: String re-formatted with modern format tags. """ with core.get_lock(FORMAT_LOCK_ID): for fmt in _l_formats: format_str = format_str.replace(fmt.legacy, fmt.modern) return format_str
/relogged-0.1.0-py3-none-any.whl/relog/formatting.py
0.768473
0.258829
formatting.py
pypi
# relogic [![Build Status](https://travis-ci.org/Impavidity/relogic.svg?branch=master)](https://travis-ci.org/Impavidity/relogic) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## Introduction This toolkit is for developing the Natural Language Processing (NLP) pipelines, including model design and development, model deployment and distributed computing. ## Preparation ```bash # clone the repo. git clone https://github.com/Impavidity/relogic.git # create data/raw_data folder, where raw datasets are stored. mkdir data/raw_data # create a folder for saving the logs. mkdir logs ``` ## Work Flow If you want to understand how relogic works, you can start from the [`relogic/main.py`](relogic/main.py), which is the entry of the training/evaluation process. If we start the model training, a [`Trainer`](relogic/logickit/training/trainer.py) object will be created. In the `Trainer`, `Task` objects will be initialized based on the argument `--task_names`. For example, if we want to create a new task for IR (Information Retrieval), we need to do the following steps. ### Data Processing - **Implement Dataflow.** You need to define the [`Example`](relogic/logickit/dataflow/pointwise.py), [`Feature`](relogic/logickit/dataflow/pointwise.py), [`Batch`]((relogic/logickit/dataflow/pointwise.py)) and [`Dataflow`](relogic/logickit/dataflow/pointwise.py) for your task. Here are several examples in [`relogic/logickit/dataflow/`](relogic/logickit/dataflow). After you implement the dataflow, you can implement test for the class -- you can refer to [`tests/dataflow/pointwise_test`](tests/dataflow/pointwise_test.py). ### Task definition - **Define the task type.** Currently we categorize the tasks into three types: classification, span_extraction, and tagging. For IR task, it can be categorized as classification problem, because we can use cross-entropy as loss function to train the model, and directly use the probability of softmax as ranking score. For NER task, it can be categorized as tagging problem. - **Implement module for the task.** Assume that we already obtain the contextual representation from encoder, the next step you need to do is to implement a task-specific module. Basically this module takes the contextual representation and some other arguments and do some magic, and then return the logits/final representation. - **Add your task.** You need to give a name for your task. After you implement this module, you just add this module under `get_module` function in, for example, [`classification task`](relogic/logickit/tasks/classification.py). Also, remember to add your task in function [`get_task`](relogic/logickit/tasks/__init__.py). Also, because slow process for migrating the code base, you also need to add your task in [`get_dataset`](relogic/logickit/dataset/labeled_data_loader.py) function. ### Loss Function - **Implement the loss function.** ### Evaluation - **Implement the scorer for your task.** - **Add your scorer.** ## Models There are several models are implemented in this toolkit and the instructions will be presented in this section. Basically there model are based on contextual encoder such as BERT. For more information, please refer to [Devlin et al.](https://arxiv.org/pdf/1810.04805.pdf) ### Named Entity Recognition ### Relation Extraction ### Semantic Role Labeling The Semantic Role Labeler is trained on CoNLL 2005, CoNLL 2009 and CoNLL 2012. Currently the model of CoNLL 2012 is available. #### How to use ```python from relogic.pipelines.core import Pipeline pipeline = Pipeline( component_names=["predicate_detection", "srl"], component_model_names= {"predicate_detection" : "spacy" ,"srl": "srl-conll12"}) from relogic.structures.sentence import Sentence sent = Sentence( text="The Lexington-Concord Sesquicentennial half dollar is a fifty-cent piece struck by the United States Bureau of the Mint in 1925 as a commemorative coin in honor of the 150th anniversary of the Battles of Lexington and Concord.") pipeline.execute([sent]) ``` You will observe the `srl_labels` in Sentence and their labels sequence matches with the sequence of the predicates, which is predicted with spacy pos tagger (we simply regard VERB as predicate). ### Cross-lingual Entity Matching over Knowledge Graphs ### Reading Comprehension ### End to End QA with Reading Comprehension ### Entity Linking The entity linking model is based on the Wikipedia and Baidu Baike anchors. #### How to use ```python from relogic.graphkit.linking.simple_entity_linker import SimpleEntityLinker linker = SimpleEntityLinker(["en_wikipedia", "zh_baike"]) linker.link("Obama", "en_wikipedia").ranked_uris linker.link("范冰冰", "zh_baike").ranked_uris ``` ## Adversarial Training The basic training procedure of adversarial training is as follows ```python # 5 discriminator update + 1 generator update if update_discriminator: real_encode = network(source_language_sample) fake_encode = network(target_language_sample) AdvAgent.update(real_encode["output"].detach(), fake_encode["output"].detach()) # Because we only consider to update discriminator if update_generator: optim.zero_grad() real_encode = network(source_language_sample) fake_encode = network(target_language_sample) adversarial_loss = AdvAgent.gen_loss(real_encode["output"], fake_encode["output"]) label_loss = cross_entropy_loss(real_encode["output"], gold_label) loss = label_loss + adversarial_loss loss.backward() clip_grad_norm_(network.parameters(), clip) optim.step() ``` ## Data Exploration It is recommended to use ```commandline cat data.json | jq . | less ``` to explore the data file. ## Documentation - What is the docsting style to follow? Refer to https://sphinxcontrib-napoleon.readthedocs.io/en/latest/# or https://learn-rst.readthedocs.io/zh_CN/latest/Sphinx简单入门.html - How to generate the documentation? ```bash cd docs make html # Open html file for checking open _build/html/index.html ``` - How to publish the documentation to website? I host the pages in another repo instead of another branch to make the code repo clean. ```bash git clone https://github.com/Impavidity/relogic-docs.git ``` And just copy the generated file in `_build/html` into the repo and commit. ```bash cp -r relogic/docs/_build/html/* relogic-docs cd relogic-docs git add * git commit -m "Update the pages" git push ``` And you can check the website here https://impavidity.github.io/relogic-docs ## Publish the code - How to publish the code to support `pip install`? Refer to https://packaging.python.org/tutorials/packaging-projects/. Here is the example to publish the package to test environment. ```bash # Generage dist directory. python setup.py sdist bdist_wheel # Distribute the package to test environment. python -m twine upload --repository-url https://test.pypi.org/legacy/ dist/* # Install newly uploaded package python -m pip install --index-url https://test.pypi.org/simple/ --no-deps relogic ``` To publish to permanent storage ```bash python -m twine upload dist/* pyhton -m pip install relogic ``` ## Citation If you use this package, please cite.
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/README.md
0.585101
0.94887
README.md
pypi
import tensorflow as tf from relogic.tpukit.training.trainer import Trainer flags = tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( "data_dir", None, "The input data dir. Should contain the .tsv files (or other data files) " "for the task.") flags.DEFINE_string( "bert_config_file", None, "The config json file corresponding to the pre-trained BERT model. " "This specifies the model architecture.") flags.DEFINE_string("task_name", None, "The name of the task to train.") flags.DEFINE_string("vocab_file", None, "The vocabulary file that the BERT model was trained on.") flags.DEFINE_string( "output_dir", None, "The output directory where the model checkpoints will be written.") ## Other parameters flags.DEFINE_string( "init_checkpoint", None, "Initial checkpoint (usually from a pre-trained BERT model).") flags.DEFINE_bool( "do_lower_case", True, "Whether to lower case the input text. Should be True for uncased " "models and False for cased models.") flags.DEFINE_integer( "max_seq_length", 128, "The maximum total input sequence length after WordPiece tokenization. " "Sequences longer than this will be truncated, and sequences shorter " "than this will be padded.") flags.DEFINE_bool("do_pretraining", False, "Whether to run pretraining") flags.DEFINE_bool("do_train", False, "Whether to run training.") flags.DEFINE_bool("do_eval", False, "Whether to run eval on the dev set.") flags.DEFINE_bool( "do_predict", False, "Whether to run the model in inference mode on the test set.") flags.DEFINE_integer("train_batch_size", 32, "Total batch size for training.") flags.DEFINE_integer("eval_batch_size", 8, "Total batch size for eval.") flags.DEFINE_integer("predict_batch_size", 8, "Total batch size for predict.") flags.DEFINE_integer("eval_dev_every", 50, "Do validation for every steps") flags.DEFINE_float("learning_rate", 5e-5, "The initial learning rate for Adam.") flags.DEFINE_float("num_train_epochs", 3.0, "Total number of training epochs to perform.") flags.DEFINE_integer("num_train_steps", 100000, "Number of training steps.") flags.DEFINE_integer("num_warmup_steps", 10000, "Number of warmup steps.") flags.DEFINE_float( "warmup_proportion", 0.1, "Proportion of training to perform linear learning rate warmup for. " "E.g., 0.1 = 10% of training.") flags.DEFINE_integer("save_checkpoints_steps", 1000, "How often to save the model checkpoint.") flags.DEFINE_integer("iterations_per_loop", 1000, "How many steps to make in each estimator call.") flags.DEFINE_bool("use_tpu", False, "Whether to use TPU or GPU/CPU.") tf.flags.DEFINE_string( "tpu_name", None, "The Cloud TPU to use for training. This should be either the name " "used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 " "url.") tf.flags.DEFINE_string( "tpu_zone", None, "[Optional] GCE zone where the Cloud TPU is located in. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string( "gcp_project", None, "[Optional] Project name for the Cloud TPU-enabled project. If not " "specified, we will attempt to automatically detect the GCE project from " "metadata.") tf.flags.DEFINE_string("master", None, "[Optional] TensorFlow master URL.") flags.DEFINE_integer( "num_tpu_cores", 8, "Only used if `use_tpu` is True. Total number of TPU cores to use.") tf.logging.set_verbosity(tf.logging.INFO) trainer = Trainer(FLAGS) trainer.train()
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/main_tpu.py
0.825343
0.38445
main_tpu.py
pypi
from relogic.tpukit.processors.data_processor import DataProcessor import os from relogic.tpukit.tokenizer import tokenization from relogic.tpukit.input_fn import InputExample class XnliProcessor(DataProcessor): """Processor for the XNLI data set.""" def __init__(self): self.language = "zh" def get_train_examples(self, data_dir): """See base class.""" lines = self._read_tsv( os.path.join(data_dir, "multinli", "multinli.train.%s.tsv" % self.language)) examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "train-%d" % (i) text_a = tokenization.convert_to_unicode(line[0]) text_b = tokenization.convert_to_unicode(line[1]) label = tokenization.convert_to_unicode(line[2]) if label == tokenization.convert_to_unicode("contradictory"): label = tokenization.convert_to_unicode("contradiction") examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples def get_dev_examples(self, data_dir): """See base class.""" lines = self._read_tsv(os.path.join(data_dir, "xnli.dev.tsv")) examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "dev-%d" % (i) language = tokenization.convert_to_unicode(line[0]) if language != tokenization.convert_to_unicode(self.language): continue text_a = tokenization.convert_to_unicode(line[6]) text_b = tokenization.convert_to_unicode(line[7]) label = tokenization.convert_to_unicode(line[1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples def get_labels(self): """See base class.""" return ["contradiction", "entailment", "neutral"] class MnliProcessor(DataProcessor): """Processor for the MultiNLI data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test") def get_labels(self): """See base class.""" return ["contradiction", "entailment", "neutral"] def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, tokenization.convert_to_unicode(line[0])) text_a = tokenization.convert_to_unicode(line[8]) text_b = tokenization.convert_to_unicode(line[9]) if set_type == "test": label = "contradiction" else: label = tokenization.convert_to_unicode(line[-1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples class MrpcProcessor(DataProcessor): """Processor for the MRPC data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") def get_labels(self): """See base class.""" return ["0", "1"] def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): if i == 0: continue guid = "%s-%s" % (set_type, i) text_a = tokenization.convert_to_unicode(line[3]) text_b = tokenization.convert_to_unicode(line[4]) if set_type == "test": label = "0" else: label = tokenization.convert_to_unicode(line[0]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) return examples class ColaProcessor(DataProcessor): """Processor for the CoLA data set (GLUE version).""" def get_train_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") def get_dev_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") def get_test_examples(self, data_dir): """See base class.""" return self._create_examples( self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") def get_labels(self): """See base class.""" return ["0", "1"] def _create_examples(self, lines, set_type): """Creates examples for the training and dev sets.""" examples = [] for (i, line) in enumerate(lines): # Only the test set has a header if set_type == "test" and i == 0: continue guid = "%s-%s" % (set_type, i) if set_type == "test": text_a = tokenization.convert_to_unicode(line[1]) label = "0" else: text_a = tokenization.convert_to_unicode(line[3]) label = tokenization.convert_to_unicode(line[1]) examples.append( InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) return examples
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/tpukit/processors/xnli.py
0.72526
0.329527
xnli.py
pypi
import torch from typing import List import itertools def block_orthogonal(tensor: torch.Tensor, split_sizes: List[int], gain: float = 1.0) -> None: """ An initializer which allows initializing model parameters in "blocks". This is helpful in the case of recurrent models which use multiple gates applied to linear projections, which can be computed efficiently if they are concatenated together. However, they are separate parameters which should be initialized independently. Parameters ---------- tensor : ``torch.Tensor``, required. A tensor to initialize. split_sizes : List[int], required. A list of length ``tensor.ndim()`` specifying the size of the blocks along that particular dimension. E.g. ``[10, 20]`` would result in the tensor being split into chunks of size 10 along the first dimension and 20 along the second. gain : float, optional (default = 1.0) The gain (scaling) applied to the orthogonal initialization. """ data = tensor.data sizes = list(tensor.size()) if any([a % b != 0 for a, b in zip(sizes, split_sizes)]): raise ValueError("tensor dimensions must be divisible by their respective " "split_sizes. Found size: {} and split_sizes: {}".format(sizes, split_sizes)) indexes = [list(range(0, max_size, split)) for max_size, split in zip(sizes, split_sizes)] # Iterate over all possible blocks within the tensor. for block_start_indices in itertools.product(*indexes): # A list of tuples containing the index to start at for this block # and the appropriate step size (i.e split_size[i] for dimension i). index_and_step_tuples = zip(block_start_indices, split_sizes) # This is a tuple of slices corresponding to: # tensor[index: index + step_size, ...]. This is # required because we could have an arbitrary number # of dimensions. The actual slices we need are the # start_index: start_index + step for each dimension in the tensor. block_slice = tuple([slice(start_index, start_index + step) for start_index, step in index_and_step_tuples]) data[block_slice] = torch.nn.init.orthogonal_(tensor[block_slice].contiguous(), gain=gain)
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/initializers.py
0.923648
0.696378
initializers.py
pypi
import torch import torch.nn as nn import torch.nn.functional as F class SimpleCNN(nn.Module): def __init__(self, num_of_conv, in_channels, out_channels, kernel_size, in_features, out_features=None, stride=1, dilation=1, groups=1, bias=True, active_func=F.relu, pooling=F.max_pool1d, dropout=0.5, padding_strategy="default", padding_list=None, fc_layer=True, include_map=False, k_max_pooling=False, k=1): """ :param num_of_conv: Follow kim cnn idea :param kernel_size: if is int type, then make it into list, length equals to num_of_conv if list type, then check the length of it, should has length of num_of_conv :param out_features: feature size """ super(SimpleCNN, self).__init__() if type(kernel_size) == int: kernel_size = [kernel_size] if len(kernel_size) != num_of_conv: print("Number of kernel_size should be same num_of_conv") exit(1) if padding_list == None: if padding_strategy == "default": padding_list = [(k_size - 1, 0) for k_size in kernel_size] self.include_map = include_map self.conv = nn.ModuleList([nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(k_size, in_features), stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias) for k_size, padding in zip(kernel_size, padding_list)]) self.pooling = pooling self.k_max_pooling = k_max_pooling self.k = k if k_max_pooling else 1 self.active_func = active_func self.fc_layer = fc_layer if fc_layer: self.dropout = nn.Dropout(dropout) self.fc = nn.Linear(num_of_conv * out_channels * self.k, out_features) def kmax_pooling(self, x, dim, k): index = x.topk(k, dim=dim)[1].sort(dim=dim)[0] return x.gather(dim, index) def forward(self, input): batch_size = input.size(0) if len(input.size()) == 3: input = input.unsqueeze(1) # input = (batch, in_channels, sent_len, word_dim) x_map = [self.active_func(conv(input)).squeeze(3) for conv in self.conv] # (batch, channel_output, ~=sent_len) * Ks if self.k_max_pooling: x = [self.kmax_pooling(i, 2, self.k).view(batch_size, -1) for i in x_map] else: x = [self.pooling(i, i.size(2)).squeeze(2) for i in x_map] # max-over-time pooling x = torch.cat(x, 1) # (batch, out_channels * Ks) if self.fc_layer: x = self.dropout(x) x = self.fc(x) if self.include_map == False: return x else: return x, x_map class SamCNN(nn.Module): def __init__(self, config, task_name, n_classes): super().__init__() self.sm_cnn = SimpleCNN( num_of_conv=1, in_channels=1, out_channels=config.output_channel, kernel_size=[config.kernel_size], in_features=config.word_embed_dim, out_features=config.hidden_size, active_func=nn.ReLU(), dropout=config.dropout, fc_layer=True ) self.projection = nn.Linear(config.hidden_size * 3, config.projection_size) self.batch_norm = nn.BatchNorm1d(config.projection_size) self.to_logits = nn.Sequential( nn.Tanh(), nn.Dropout(config.dropout), nn.Linear(config.projection_size, n_classes)) self.context_cnn = SimpleCNN( num_of_conv=1, in_channels=1, out_channels=config.output_channel, kernel_size=[config.kernel_size], in_features=config.word_embed_dim, out_features=config.hidden_size, active_func=nn.ReLU(), dropout=config.dropout, fc_layer=True ) self.cos = nn.CosineSimilarity(dim=1, eps=1e-6) def attn_context_ave(self, question_embed, answer_embed, batch_size): question_len = question_embed.size(1) answer_len = answer_embed.size(1) dimension = question_embed.size(2) question = torch.cat([question_embed.unsqueeze(2)] * answer_len, dim=2).view(-1, dimension) answer = torch.cat([answer_embed.unsqueeze(1)] * question_len, dim=1).view(-1, dimension) # (batch, question_len, answer_len, dim) attn_prob = self.cos(answer, question).unsqueeze(1) attn_answer = (answer * attn_prob).view(batch_size * question_len, answer_len, dimension) feature = self.context_cnn(attn_answer).view(batch_size, question_len, -1) feature = torch.sum(feature, dim=1) / question_len return feature def forward(self, *inputs, **kwargs): a_features = kwargs.pop("a_features") b_features = kwargs.pop("b_features") a_cnn_features = self.sm_cnn(a_features) b_cnn_features = self.sm_cnn(b_features) attention_features = self.attn_context_ave(a_features, b_features, a_features.size(0)) feat_comb = torch.cat([a_cnn_features, b_cnn_features, attention_features], dim=1) feat_comb = self.projection(feat_comb) if feat_comb.size(0) > 1: feat_comb = self.batch_norm(feat_comb) logits = self.to_logits(feat_comb) return logits
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/sam_cnn.py
0.927157
0.433862
sam_cnn.py
pypi
import torch import torch.nn as nn class SpanGCNModule(nn.Module): """ SpanGCN firstly extract span from text, and then label each span based on the learned representation of GCN """ def __init__(self, config, task_name, boundary_n_classes=None, label_n_classes=None): super(SpanGCNModule, self).__init__() self.config = config self.task_name = task_name self.boundary_n_classes = boundary_n_classes self.label_n_classes = label_n_classes if boundary_n_classes: self.to_boundary_logits = nn.Linear(config.hidden_size, self.boundary_n_classes) if label_n_classes: self.to_label_logits = nn.Linear(config.hidden_size * 2, self.label_n_classes) if config.use_gcn: pass else: pass self.padding = nn.Parameter(torch.zeros(config.hidden_size), requires_grad=False) self.ones = nn.Parameter(torch.ones(1, 1), requires_grad=False) def forward(self, input, predicate_span=None, bio_hidden=None, span_candidates=None, extra_args=None, **kwargs): """ Before this module, there is another module info aggregation :param input: Sentence Only, in batch :param predicate: Predicate Only, in batch :param bio_hidden: hidden vector for span prediction, can be None :param span_candidates: tuple, span_start, and span_end :param extra_args: strategy :return: labeling_logits Here we need to support three mode of inference 1. Span is given In this mode, sequence labeling and independent span generation modes are supported. span_logits = None, span_candidates = batch of span Another problem here is how to aggregate span. We need to specify span level and aggregate method - For token level span - Pooling - Average - Attentive - Head Tail Attentive - For phrase level span - Non-Hierarchy - Pooling - Average - Attentive - Head Tail Attentive - Hierarchy - Use Token level aggregate - Use Non-Hierarchy to aggregate again 2. Span is not given In this mode, dependent span generation mode is supported. span_logits = batch, span_candidates = None span candidates generate from span_logits. There are two logits need to be return This mode only have Phrase level span Aggregation After we have span representation, how to interact with predicate 1. If the span itself is predicate aware, do we need to add predicate information again ? So the experiments is on surface form aware or not. You can refer the IBM relation paper 2. If the span itself is not predicate aware, it will be trained faster. How to design a module to interact the argument and the predicate - Independent Classifier - Bilinear - GCN """ if bio_hidden: bio_logits = self.to_span_logits(bio_hidden) assert "label_mapping" in extra_args, "label_mapping does not in extra_args" span_candidates = get_candidate_span(bio_logits, extra_args["label_mapping"]) start_index, end_index = span_candidates # start_index, end_index = (batch, max_span_num) predicate_start_index, predicate_end_index = predicate_span # predicate_start_index, predicate_end_index = (batch) max_span_num = len(start_index[0]) # input (batch, sentence, dim) -> (batch, max_span_num, sentence, dim) expanded_input = input.unsqueeze(1).repeat(1, max_span_num, 1, 1) start_index_ = start_index.view(-1) end_index_ = end_index.view(-1) span_hidden = select_span(expanded_input.view(-1, expanded_input.size(-2), expanded_input.size(-1)), start_index_, end_index_, self.padding) predicate_hidden = select_span(input, predicate_start_index, predicate_end_index, self.padding) span_repr = self.aggregate(span_hidden, end_index_-start_index_) predicate_repr = self.aggregate(predicate_hidden, predicate_end_index-predicate_start_index) # (batch, dim) concat = torch.cat([span_repr, predicate_repr.unsqueeze(1).repeat(1, max_span_num, 1).view(-1, predicate_repr.size(-1))], dim=-1) label_logits = self.to_label_logits(concat) return label_logits.view(input.size(0), max_span_num, self.label_n_classes) def aggregate(self, hidden, lengths): """ Use average for now :param hidden: (batch, span_length, dim) :param lengths: (batch) :return: """ return torch.sum(hidden, 1) / torch.max( self.ones.repeat(lengths.size(0), 1).float(), lengths.unsqueeze(1).float()) def select_span(input, start_index, end_index, padding): """ Use for loop to select :param input: :param start_index: :param end_index: :param padding: :return: """ padded_tensor = [] max_span_size = torch.max(end_index - start_index) for idx, (start, end) in enumerate(zip(start_index, end_index)): padded_tensor.append( torch.cat( [torch.narrow(input[idx], 0, start, (end-start))] + ([padding.unsqueeze(0).repeat(max_span_size-(end-start), 1)] if max_span_size != (end-start) else []), dim=0)) # list of (max_span_size, dim) return torch.stack(padded_tensor) def get_candidate_span(bio_logits, label_mapping): """ Use python for now. Will consider a C++ binding later. :param bio_logits: (batch_size, sentence_length, 3) :param label_mappings: :return: """ preds_tags = bio_logits.argmax(-1).data.cpu().numpy() inv_label_mapping = {v: k for k, v in label_mapping.items()} batch_span_labels = [] max_span_num = 0 for sentence in bio_logits: # convert to understandable labels sentence_tags = [inv_label_mapping[i] for i in sentence] span_labels = [] last = 'O' start = -1 for i, tag in enumerate(sentence_tags): pos, _ = (None, 'O') if tag == 'O' else tag.split('-', 1) if (pos == 'S' or pos == 'B' or tag == 'O') and last != 'O': span_labels.append((start, i - 1, last.split('-')[-1])) if pos == 'B' or pos == 'S' or last == 'O': start = i last = tag if sentence_tags[-1] != 'O': span_labels.append((start, len(sentence_tags) - 1, sentence_tags[-1].split('-', 1)[-1])) max_span_num = max(len(span_labels), max_span_num) batch_span_labels.append(span_labels) batch_start_index = [] batch_end_index = [] for span_labels in batch_span_labels: start_index = [] end_index = [] for span_label in span_labels: start_index.append(span_label[0]) end_index.append(span_label[1]) start_index += (max_span_num - len(start_index)) * [0] end_index += (max_span_num - len(end_index)) * [0] # Just a placeholder, for loss computation, it will be ignored. batch_start_index.append(start_index) batch_end_index.append(end_index) start_ids = torch.tensor(batch_start_index, dtype=torch.long).to(bio_logits.device) end_ids = torch.tensor(batch_end_index, dtype=torch.long).to(bio_logits.device) return (start_ids, end_ids)
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/span_gcn.py
0.902939
0.449574
span_gcn.py
pypi
from typing import Tuple, Union import torch import torch.nn as nn from relogic.logickit.utils import utils class Pruner(nn.Module): """ This module scores and prunes items in a list using a parameterized scoring function and a threshold """ def __init__(self, scorer: nn.Module) -> None: super(Pruner, self).__init__() self.scorer = scorer def forward(self, embeddings: torch.FloatTensor, mask: torch.LongTensor, num_items_to_keep: Union[int, torch.LongTensor]) -> Tuple[torch.FloatTensor, torch.LongTensor, torch.LongTensor, torch.FloatTensor, torch.FloatTensor]: """ Args: embeddings: A tensor of shape (batch_size, num_items, embedding_size), containing an embedding for each item in the list that we want to prune. mask: A tensor of shape (batch_size, num_items), denoting unpadded elements of ``embeddings``. num_items_to_keep: If a tensor of shape (batch_size), specifies the number of items to keep for each individual sentence in minibatch. If an int, keep the same number of items for all sentences. """ batch_size = mask.size(0) if isinstance(num_items_to_keep, int): num_items_to_keep = num_items_to_keep * torch.ones([batch_size], dtype=torch.long, device=mask.device) max_items_to_keep = num_items_to_keep.max() # Shape (batch_size, num_items, 1) mask = mask.unsqueeze(-1) num_items = embeddings.size(1) # Shape (batch_size, num_items, 1) scores = self.scorer(embeddings) if scores.size(-1) != 1 or scores.dim() != 3: raise ValueError("The scorer passed to Pruner must produce a tensor of " "shape ({}, {}, 1), but found shpae {}".format(batch_size, num_items, scores.size())) scores = utils.replace_masked_values(scores, mask, -1e20) # can not support k as tensor. So for each sentence, we keep the same size k which is max. _, top_indices = scores.topk(max_items_to_keep, 1) # Mask based on the number of items to keep for each sentence top_indices_mask = utils.get_mask_from_sequence_lengths(num_items_to_keep, max_items_to_keep) top_indices_mask = top_indices_mask.byte() # Shape (batch, max_items_to_keep) top_indices = top_indices.squeeze(-1) fill_value, _ = top_indices.max(dim=1) fill_value = fill_value.unsqueeze(-1) top_indices = torch.where(top_indices_mask, top_indices, fill_value) top_indices, _ = torch.sort(top_indices, 1) flat_top_indices = utils.flatten_and_batch_shift_indices(top_indices, num_items) top_embeddings = utils.batched_index_select(embeddings, top_indices, flat_top_indices) sequence_mask = utils.batched_index_select(mask, top_indices, flat_top_indices) sequence_mask = sequence_mask.squeeze(-1).byte() top_mask = top_indices_mask & sequence_mask top_mask = top_mask.long() # Shape: (batch_size, max_num_items_to_keep, 1) top_scores = utils.batched_index_select(scores, top_indices, flat_top_indices) return top_embeddings, top_mask, top_indices, top_scores, scores
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/pruner.py
0.971375
0.639511
pruner.py
pypi
import torch import torch.nn as nn from relogic.logickit.utils import utils import torch.nn.functional as F class IRMatchingModule(nn.Module): def __init__(self, config, task_name, n_classes): super().__init__() self.config = config self.task_name = task_name if self.config.regression: self.n_classes = 1 else: self.n_classes = n_classes self.to_logits = nn.Sequential( nn.Linear(config.hidden_size * 2, config.hidden_size), nn.ReLU(), nn.Linear(config.hidden_size, self.n_classes) ) def forward(self, *inputs, **kwargs): features = kwargs.pop("features") text_a_indices = kwargs.pop("text_a_indices") text_b_indices = kwargs.pop("text_b_indices") text_a_mask = (text_a_indices > 0).float() text_b_mask = (text_b_indices > 0).float() text_a_lengths = torch.sum(text_a_mask, dim=-1) text_b_lengths = torch.sum(text_b_mask, dim=-1) batch_size = features.size(0) query_token_size = text_a_indices.size(1) doc_token_size = text_b_indices.size(1) query_vector = utils.batched_index_select_tensor(features, text_a_indices) # select query vector based on the query indices doc_vector = utils.batched_index_select_tensor(features, text_b_indices) # select doc vector based on the doc indices exp_query_vector = query_vector.unsqueeze(2).repeat(1, 1, doc_token_size, 1) # expand the query vector into the shape (batch_size, max_query_token_size, max_doc_token_size, dim) exp_doc_vector = doc_vector.unsqueeze(1).repeat(1, query_token_size, 1, 1) # expand the doc vector into the shape (batch_size, max_query_token_size, max_doc_token_size, dim) sim = F.cosine_similarity(exp_query_vector.view(-1, query_vector.size(-1)), exp_doc_vector.view(-1, doc_vector.size(-1))).view(batch_size, query_token_size, doc_token_size) # convert both tensors into (-1, dim) shape and compute the consine similarity between these two tensors # and then convert it back into (batch_size, max_query_token_size, max_doc_token_size) scaled_doc_vector = sim.unsqueeze(-1) * exp_doc_vector # scale the document vector exp_text_b_mask = text_b_mask.unsqueeze(1).repeat(1, query_token_size, 1).unsqueeze(-1) exp_text_b_lengths = text_b_lengths.unsqueeze(-1).repeat(1, query_token_size).unsqueeze(-1) per_query_token_based_doc_repr = torch.sum(scaled_doc_vector * exp_text_b_mask, dim=-2) / (exp_text_b_lengths + 1) # compute the average repr of document, this repr is based each query token exp_text_a_mask = text_a_mask.unsqueeze(-1) exp_text_a_lengths = text_a_lengths.unsqueeze(-1) query_based_doc_repr = torch.sum(per_query_token_based_doc_repr * exp_text_a_mask, dim=-2) / (exp_text_a_lengths + 1) # aggregate document repr based on all query tokens query_vector_avg = torch.sum(query_vector * exp_text_a_mask , dim=-2) / (exp_text_a_lengths + 1) # aggregate the query repr feat = torch.cat([query_vector_avg, query_based_doc_repr], dim=-1) logits = self.to_logits(feat) return logits
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/ir_matching.py
0.922539
0.429071
ir_matching.py
pypi
import torch from torch import nn import torch.nn.functional as F class SimpleCNN(nn.Module): def __init__(self, num_of_conv, in_channels, out_channels, kernel_size, in_features, out_features=None, stride=1, dilation=1, groups=1, bias=True, active_func=F.relu, pooling=F.max_pool1d, dropout=0.5, padding_strategy="default", padding_list=None, fc_layer=True, include_map=False): """ :param num_of_conv: Follow kim cnn idea :param kernel_size: if is int type, then make it into list, length equals to num_of_conv if list type, then check the length of it, should has length of num_of_conv :param out_features: feature size """ super(SimpleCNN, self).__init__() if type(kernel_size) == int: kernel_size = [kernel_size] if len(kernel_size) != num_of_conv: print("Number of kernel_size should be same num_of_conv") exit(1) if padding_list == None: if padding_strategy == "default": padding_list = [(k_size - 1, 0) for k_size in kernel_size] self.include_map = include_map self.conv = nn.ModuleList([nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=(k_size, in_features), stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias) for k_size, padding in zip(kernel_size, padding_list)]) self.pooling = pooling self.active_func = active_func self.fc_layer = fc_layer if fc_layer: self.dropout = nn.Dropout(dropout) self.fc = nn.Linear(num_of_conv * out_channels, out_features) def forward(self, input): if len(input.size()) == 3: input = input.unsqueeze(1) # input = (batch, in_channels, sent_len, word_dim) x_map = [self.active_func(conv(input)).squeeze(3) for conv in self.conv] # (batch, channel_output, ~=sent_len) * Ks x = [self.pooling(i, i.size(2)).squeeze(2) for i in x_map] # max-over-time pooling x = torch.cat(x, 1) # (batch, out_channels * Ks) if self.fc_layer: x = self.dropout(x) x = self.fc(x) if self.include_map == False: return x else: return x, x_map class CharCNN(SimpleCNN): """ Single CNN for char input: Tensor (batch, sent_len, word_len, char_dim) """ def forward(self, input): if len(input.size()) == 4: input = input.unsqueeze(2) # input = (batch, sent_len, in_channels, word_len, char_dim) x = torch.stack([super(CharCNN, self).forward(input[i, :, :, :, :]) for i in range(input.size(0))], dim=0) # x = (batch, sent_len, output_feature) return x
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/contextualizers/cnn.py
0.913162
0.448185
cnn.py
pypi
import torch.nn as nn import torch from relogic.logickit.utils import utils class SelfAttentiveSpanExtractor(nn.Module): def __init__(self, input_dim): super(SelfAttentiveSpanExtractor, self).__init__() self._global_attention = nn.Linear(input_dim, 1) def forward(self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> torch.FloatTensor: # Shape (batch_size, num_spans, 1) span_starts, span_ends = span_indices.split(1, dim=-1) span_ends = span_ends - 1 span_widths = span_ends - span_starts max_batch_span_width = span_widths.max().item() + 1 global_attention_logits = self._global_attention(sequence_tensor) # Shape: (1, 1, max_batch_span_width) max_span_range_indices = utils.get_range_vector(max_batch_span_width, sequence_tensor.device).view(1, 1, -1) span_mask = (max_span_range_indices <= span_widths).float() raw_span_indices = span_ends - max_span_range_indices span_mask = span_mask * (raw_span_indices >= 0).float() span_indices = torch.relu(raw_span_indices.float()).long() flat_span_indices = utils.flatten_and_batch_shift_indices(span_indices, sequence_tensor.size(1)) span_embeddings = utils.batched_index_select(sequence_tensor, span_indices, flat_span_indices) span_attention_logits = utils.batched_index_select(global_attention_logits, span_indices, flat_span_indices).squeeze(-1) span_attention_weights = utils.masked_softmax(span_attention_logits, span_mask) attended_text_embeddings = utils.weighted_sum(span_embeddings, span_attention_weights) if span_indices_mask is not None: return attended_text_embeddings * span_indices_mask.unsqueeze(-1).float() return attended_text_embeddings
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/span_extractors/self_attentive_span_extractor.py
0.901064
0.529081
self_attentive_span_extractor.py
pypi
import torch.nn as nn import torch from relogic.logickit.utils import utils class EndpointSpanExtractor(nn.Module): def __init__(self, input_dim: int, combination: str = "x,y", num_width_embeddings: int = None, span_width_embedding_dim: int = None, bucket_widths: bool = False) -> None: super(EndpointSpanExtractor, self).__init__() self._input_dim = input_dim self._combination = combination self._num_width_embeddings = num_width_embeddings self._bucket_widths = bucket_widths if num_width_embeddings is not None and span_width_embedding_dim is not None: self._span_width_embedding = nn.Embedding(num_width_embeddings, span_width_embedding_dim) elif not all([num_width_embeddings is None, span_width_embedding_dim is None]): raise ValueError("To use a span width embedding representation, you must" "specify both num_width_embeddings and span_width_embedding_dim.") else: self._span_width_embedding = None def forward(self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None): span_starts, span_ends = [index.squeeze(-1) for index in span_indices.split(1, dim=-1)] if span_indices_mask is not None: span_starts = span_starts * span_indices_mask.long() span_ends = span_ends * span_indices_mask.long() # The span is exclusive on the right, so the span_ends need to -1 start_embeddings = utils.batched_index_select(sequence_tensor, span_starts) inclusive_span_ends = torch.relu((span_ends - 1).float()).long() end_embeddings = utils.batched_index_select(sequence_tensor ,inclusive_span_ends) combined_tensors = torch.cat([start_embeddings, end_embeddings], dim=-1) if self._span_width_embedding is not None: # Embed the span widths and concatenate to the rest of the representations. if self._bucket_widths: span_widths = utils.bucket_values(span_ends - span_starts, num_total_buckets=self._num_width_embeddings) else: span_widths = span_ends - span_starts span_width_embeddings = self._span_width_embedding(span_widths) combined_tensors = torch.cat([combined_tensors, span_width_embeddings], dim=-1) if span_indices_mask is not None: return combined_tensors * span_indices_mask.unsqueeze(-1).float() return combined_tensors
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/span_extractors/endpoint_span_extractor.py
0.924679
0.316713
endpoint_span_extractor.py
pypi
import torch.nn as nn import torch from relogic.logickit.utils import utils class AttentiveSpanExtractor(nn.Module): def __init__(self, input_dim): super(AttentiveSpanExtractor, self).__init__() self._global_attention = nn.Linear(input_dim, 1) def forward(self, sequence_tensor: torch.FloatTensor, value_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> torch.FloatTensor: # Shape (batch_size, num_spans, 1) span_starts, span_ends = span_indices.split(1, dim=-1) span_ends = span_ends - 1 span_widths = span_ends - span_starts max_batch_span_width = span_widths.max().item() + 1 global_attention_logits = self._global_attention(sequence_tensor) # Shape: (1, 1, max_batch_span_width) max_span_range_indices = utils.get_range_vector(max_batch_span_width, sequence_tensor.device).view(1, 1, -1) span_mask = (max_span_range_indices <= span_widths).float() raw_span_indices = span_ends - max_span_range_indices span_mask = span_mask * (raw_span_indices >= 0).float() span_indices = torch.relu(raw_span_indices.float()).long() flat_span_indices = utils.flatten_and_batch_shift_indices(span_indices, sequence_tensor.size(1)) span_embeddings = utils.batched_index_select(value_tensor, span_indices, flat_span_indices) span_attention_logits = utils.batched_index_select(global_attention_logits, span_indices, flat_span_indices).squeeze(-1) span_attention_weights = utils.masked_softmax(span_attention_logits, span_mask) attended_text_embeddings = utils.weighted_sum(span_embeddings, span_attention_weights) if span_indices_mask is not None: return attended_text_embeddings * span_indices_mask.unsqueeze(-1).float() return attended_text_embeddings
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/span_extractors/attentive_span_extractor.py
0.889012
0.553626
attentive_span_extractor.py
pypi
import torch.nn as nn import torch from relogic.logickit.utils import utils class AverageSpanExtractor(nn.Module): def __init__(self, input_dim): super(AverageSpanExtractor, self).__init__() def forward(self, sequence_tensor: torch.FloatTensor, span_indices: torch.LongTensor, sequence_mask: torch.LongTensor = None, span_indices_mask: torch.LongTensor = None) -> torch.FloatTensor: # Shape (batch_size, num_spans, 1) span_starts, span_ends = span_indices.split(1, dim=-1) span_ends = span_ends - 1 span_widths = span_ends - span_starts max_batch_span_width = span_widths.max().item() + 1 # sequence_tensor (batch, length, dim) # global_attention_logits = self._global_attention(sequence_tensor) global_average_logits = torch.ones(sequence_tensor.size()[:2] + (1,)).float().to(sequence_tensor.device) # Shape: (1, 1, max_batch_span_width) max_span_range_indices = utils.get_range_vector(max_batch_span_width, sequence_tensor.device).view(1, 1, -1) span_mask = (max_span_range_indices <= span_widths).float() # (batch_size, num_spans, 1) - (1, 1, max_batch_span_width) raw_span_indices = span_ends - max_span_range_indices span_mask = span_mask * (raw_span_indices >= 0).float() span_indices = torch.relu(raw_span_indices.float()).long() flat_span_indices = utils.flatten_and_batch_shift_indices(span_indices, sequence_tensor.size(1)) span_embeddings = utils.batched_index_select(sequence_tensor, span_indices, flat_span_indices) span_attention_logits = utils.batched_index_select(global_average_logits, span_indices, flat_span_indices).squeeze(-1) span_attention_weights = utils.masked_softmax(span_attention_logits, span_mask) attended_text_embeddings = utils.weighted_sum(span_embeddings, span_attention_weights) if span_indices_mask is not None: return attended_text_embeddings * span_indices_mask.unsqueeze(-1).float() return attended_text_embeddings
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/modules/span_extractors/average_span_extractor.py
0.901217
0.556038
average_span_extractor.py
pypi
from dataclasses import dataclass @dataclass class GeneralConfig(object): """Model configuration for training and test. Args: mode (str): The trainer mode can be one of the following choice: "train", "dev", "eval", "finetune" output_dir (str): A full directory path for saving the model configuration, parameters and prediction dumps. restore_path (str): Model configuration and parameters will be restored from this full directory path. max_seq_length (int): Limited by the contextual model and GPU memory, the max sentence length is limited in this model. Default: 450. max_query_length (int): This is reserved for reading comprehension model. There are two components in reading comprehension model: query and paragraph. In the model, the query max length is limited by this argument. Default: 64. doc_stride (int): This is reserved for reading comprehension model. For long paragraph, it will be devided into several sub-paragraph by a sliding window whose window size is determined by the this argument. Default: 128. do_lower_case (bool): If True, convert the original text to lowercase. Default: False train_file (str): The file names of train file in :data:`raw_data_path`, segmented by ','. dev_file (str): The file names of dev file in :data:`raw_data_path`, segmented by ','. test_file (str): The file names of test file in :data:`raw_data_path`, segmented by ','. """ # IO mode: str output_dir: str restore_path: str max_seq_length: int = 450 max_query_length: int = 64 doc_stride: int = 128 do_lower_case: bool = False train_file: str = "train.json" dev_file: str = "dev.json" test_file: str = "test.json" # Task Definition # Task Related Configuration # Hyper-parameter # Training # Semi-supervised # Training def load_from_json(self, config): pass def load_from_namespace(self, config): pass def load_from_json_file(self, config_path): pass
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/base/config.py
0.818701
0.284607
config.py
pypi
""" Configuration base class and utilities.""" from __future__ import (absolute_import, division, print_function, unicode_literals) import copy import json import logging import os from io import open from relogic.utils.file_utils import cached_path, CONFIG_NAME logger = logging.getLogger(__name__) class PretrainedConfig(object): r""" Base class for all configuration classes. Handles a few parameters common to all models' configurations as well as methods for loading/downloading/saving configurations. Note: A configuration file can be loaded and saved to disk. Loading the configuration file and using this file to initialize a model does **not** load the model weights. It only affects the model's configuration. Class attributes (overridden by derived classes): - ``pretrained_config_archive_map``: a python ``dict`` of with `short-cut-names` (string) as keys and `url` (string) of associated pretrained model configurations as values. Parameters: ``finetuning_task``: string, default `None`. Name of the task used to fine-tune the model. This can be used when converting from an original (TensorFlow or PyTorch) checkpoint. ``num_labels``: integer, default `2`. Number of classes to use when the model is a classification model (sequences/tokens) ``output_attentions``: boolean, default `False`. Should the model returns attentions weights. ``output_hidden_states``: string, default `False`. Should the model returns all hidden-states. ``torchscript``: string, default `False`. Is the model used with Torchscript. """ pretrained_config_archive_map = {} def __init__(self, **kwargs): self.finetuning_task = kwargs.pop('finetuning_task', None) self.num_labels = kwargs.pop('num_labels', 2) self.output_attentions = kwargs.pop('output_attentions', False) self.output_hidden_states = kwargs.pop('output_hidden_states', False) self.output_past = kwargs.pop('output_past', True) # Not used by all models self.torchscript = kwargs.pop('torchscript', False) # Only used by PyTorch models self.use_bfloat16 = kwargs.pop('use_bfloat16', False) self.pruned_heads = kwargs.pop('pruned_heads', {}) def save_pretrained(self, save_directory): """ Save a configuration object to the directory `save_directory`, so that it can be re-loaded using the :func:`~transformers.PretrainedConfig.from_pretrained` class method. """ assert os.path.isdir(save_directory), "Saving path should be a directory where the model and configuration can be saved" # If we save using the predefined names, we can load using `from_pretrained` output_config_file = os.path.join(save_directory, CONFIG_NAME) self.to_json_file(output_config_file) logger.info("Configuration saved in {}".format(output_config_file)) @classmethod def from_pretrained(cls, pretrained_model_name_or_path, **kwargs): r""" Instantiate a :class:`~transformers.PretrainedConfig` (or a derived class) from a pre-trained model configuration. Parameters: pretrained_model_name_or_path: either: - a string with the `shortcut name` of a pre-trained model configuration to load from cache or download, e.g.: ``bert-base-uncased``. - a path to a `directory` containing a configuration file saved using the :func:`~transformers.PretrainedConfig.save_pretrained` method, e.g.: ``./my_model_directory/``. - a path or url to a saved configuration JSON `file`, e.g.: ``./my_model_directory/configuration.json``. cache_dir: (`optional`) string: Path to a directory in which a downloaded pre-trained model configuration should be cached if the standard cache should not be used. kwargs: (`optional`) dict: key/value pairs with which to update the configuration object after loading. - The values in kwargs of any keys which are configuration attributes will be used to override the loaded values. - Behavior concerning key/value pairs whose keys are *not* configuration attributes is controlled by the `return_unused_kwargs` keyword parameter. force_download: (`optional`) boolean, default False: Force to (re-)download the model weights and configuration files and override the cached versions if they exists. proxies: (`optional`) dict, default None: A dictionary of proxy servers to use by protocol or endpoint, e.g.: {'http': 'foo.bar:3128', 'http://hostname': 'foo.bar:4012'}. The proxies are used on each request. return_unused_kwargs: (`optional`) bool: - If False, then this function returns just the final configuration object. - If True, then this functions returns a tuple `(config, unused_kwargs)` where `unused_kwargs` is a dictionary consisting of the key/value pairs whose keys are not configuration attributes: ie the part of kwargs which has not been used to update `config` and is otherwise ignored. Examples:: # We can't instantiate directly the base class `PretrainedConfig` so let's show the examples on a # derived class: BertConfig config = BertConfig.from_pretrained('bert-base-uncased') # Download configuration from S3 and cache. config = BertConfig.from_pretrained('./test/saved_model/') # E.g. config (or model) was saved using `save_pretrained('./test/saved_model/')` config = BertConfig.from_pretrained('./test/saved_model/my_configuration.json') config = BertConfig.from_pretrained('bert-base-uncased', output_attention=True, foo=False) assert config.output_attention == True config, unused_kwargs = BertConfig.from_pretrained('bert-base-uncased', output_attention=True, foo=False, return_unused_kwargs=True) assert config.output_attention == True assert unused_kwargs == {'foo': False} """ cache_dir = kwargs.pop('cache_dir', None) force_download = kwargs.pop('force_download', False) proxies = kwargs.pop('proxies', None) return_unused_kwargs = kwargs.pop('return_unused_kwargs', False) if pretrained_model_name_or_path in cls.pretrained_config_archive_map: config_file = cls.pretrained_config_archive_map[pretrained_model_name_or_path] elif os.path.isdir(pretrained_model_name_or_path): config_file = os.path.join(pretrained_model_name_or_path, CONFIG_NAME) else: config_file = pretrained_model_name_or_path # redirect to the cache, if necessary try: resolved_config_file = cached_path(config_file, cache_dir=cache_dir, force_download=force_download, proxies=proxies) except EnvironmentError: if pretrained_model_name_or_path in cls.pretrained_config_archive_map: msg = "Couldn't reach server at '{}' to download pretrained model configuration file.".format( config_file) else: msg = "Model name '{}' was not found in model name list ({}). " \ "We assumed '{}' was a path or url to a configuration file named {} or " \ "a directory containing such a file but couldn't find any such file at this path or url.".format( pretrained_model_name_or_path, ', '.join(cls.pretrained_config_archive_map.keys()), config_file, CONFIG_NAME) raise EnvironmentError(msg) if resolved_config_file == config_file: logger.info("loading configuration file {}".format(config_file)) else: logger.info("loading configuration file {} from cache at {}".format( config_file, resolved_config_file)) # Load config config = cls.from_json_file(resolved_config_file) if hasattr(config, 'pruned_heads'): config.pruned_heads = dict((int(key), value) for key, value in config.pruned_heads.items()) # Update config with kwargs if needed to_remove = [] for key, value in kwargs.items(): if hasattr(config, key): setattr(config, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) logger.info("Model config %s", str(config)) if return_unused_kwargs: return config, kwargs else: return config @classmethod def from_dict(cls, json_object): """Constructs a `Config` from a Python dictionary of parameters.""" config = cls(vocab_size_or_config_json_file=-1) for key, value in json_object.items(): setattr(config, key, value) return config @classmethod def from_json_file(cls, json_file): """Constructs a `BertConfig` from a json file of parameters.""" with open(json_file, "r", encoding='utf-8') as reader: text = reader.read() return cls.from_dict(json.loads(text)) def __eq__(self, other): return self.__dict__ == other.__dict__ def __repr__(self): return str(self.to_json_string()) def to_dict(self): """Serializes this instance to a Python dictionary.""" output = copy.deepcopy(self.__dict__) return output def to_json_string(self): """Serializes this instance to a JSON string.""" return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" def to_json_file(self, json_file_path): """ Save this instance to a json file.""" with open(json_file_path, "w", encoding='utf-8') as writer: writer.write(self.to_json_string())
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/base/configuration_utils.py
0.88912
0.431405
configuration_utils.py
pypi
""" XLM configuration """ from __future__ import absolute_import, division, print_function, unicode_literals import json import logging import sys from io import open from relogic.logickit.base.configuration_utils import PretrainedConfig logger = logging.getLogger(__name__) XLM_PRETRAINED_CONFIG_ARCHIVE_MAP = { 'xlm-mlm-en-2048': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-en-2048-config.json", 'xlm-mlm-ende-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-ende-1024-config.json", 'xlm-mlm-enfr-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enfr-1024-config.json", 'xlm-mlm-enro-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enro-1024-config.json", 'xlm-mlm-tlm-xnli15-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-tlm-xnli15-1024-config.json", 'xlm-mlm-xnli15-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-xnli15-1024-config.json", 'xlm-clm-enfr-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-clm-enfr-1024-config.json", 'xlm-clm-ende-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-clm-ende-1024-config.json", 'xlm-mlm-17-1280': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-17-1280-config.json", 'xlm-mlm-100-1280': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-100-1280-config.json", } class XLMConfig(PretrainedConfig): """Configuration class to store the configuration of a `XLMModel`. Args: vocab_size_or_config_json_file: Vocabulary size of `inputs_ids` in `XLMModel`. d_model: Size of the encoder layers and the pooler layer. n_layer: Number of hidden layers in the Transformer encoder. n_head: Number of attention heads for each attention layer in the Transformer encoder. d_inner: The size of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder. ff_activation: The non-linear activation function (function or string) in the encoder and pooler. If string, "gelu", "relu" and "swish" are supported. untie_r: untie relative position biases attn_type: 'bi' for XLM, 'uni' for Transformer-XL dropout: The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler. max_position_embeddings: The maximum sequence length that this model might ever be used with. Typically set this to something large just in case (e.g., 512 or 1024 or 2048). initializer_range: The sttdev of the truncated_normal_initializer for initializing all weight matrices. layer_norm_eps: The epsilon used by LayerNorm. dropout: float, dropout rate. init: str, the initialization scheme, either "normal" or "uniform". init_range: float, initialize the parameters with a uniform distribution in [-init_range, init_range]. Only effective when init="uniform". init_std: float, initialize the parameters with a normal distribution with mean 0 and stddev init_std. Only effective when init="normal". mem_len: int, the number of tokens to cache. reuse_len: int, the number of tokens in the currect batch to be cached and reused in the future. bi_data: bool, whether to use bidirectional input pipeline. Usually set to True during pretraining and False during finetuning. clamp_len: int, clamp all relative distances larger than clamp_len. -1 means no clamping. same_length: bool, whether to use the same attention length for each token. """ pretrained_config_archive_map = XLM_PRETRAINED_CONFIG_ARCHIVE_MAP def __init__(self, vocab_size_or_config_json_file=30145, emb_dim=2048, n_layers=12, n_heads=16, dropout=0.1, attention_dropout=0.1, gelu_activation=True, sinusoidal_embeddings=False, causal=False, asm=False, n_langs=1, use_lang_emb=True, max_position_embeddings=512, embed_init_std=2048 ** -0.5, layer_norm_eps=1e-12, init_std=0.02, bos_index=0, eos_index=1, pad_index=2, unk_index=3, mask_index=5, is_encoder=True, finetuning_task=None, num_labels=2, summary_type='first', summary_use_proj=True, summary_activation=None, summary_proj_to_labels=True, summary_first_dropout=0.1, start_n_top=5, end_n_top=5, **kwargs): """Constructs XLMConfig. """ super(XLMConfig, self).__init__(**kwargs) if isinstance(vocab_size_or_config_json_file, str) or (sys.version_info[0] == 2 and isinstance(vocab_size_or_config_json_file, unicode)): with open(vocab_size_or_config_json_file, "r", encoding='utf-8') as reader: json_config = json.loads(reader.read()) for key, value in json_config.items(): self.__dict__[key] = value elif isinstance(vocab_size_or_config_json_file, int): self.n_words = vocab_size_or_config_json_file self.emb_dim = emb_dim self.n_layers = n_layers self.n_heads = n_heads self.dropout = dropout self.attention_dropout = attention_dropout self.gelu_activation = gelu_activation self.sinusoidal_embeddings = sinusoidal_embeddings self.causal = causal self.asm = asm self.n_langs = n_langs self.use_lang_emb = use_lang_emb self.layer_norm_eps = layer_norm_eps self.bos_index = bos_index self.eos_index = eos_index self.pad_index = pad_index self.unk_index = unk_index self.mask_index = mask_index self.is_encoder = is_encoder self.max_position_embeddings = max_position_embeddings self.embed_init_std = embed_init_std self.init_std = init_std self.finetuning_task = finetuning_task self.num_labels = num_labels self.summary_type = summary_type self.summary_use_proj = summary_use_proj self.summary_activation = summary_activation self.summary_proj_to_labels = summary_proj_to_labels self.summary_first_dropout = summary_first_dropout self.start_n_top = start_n_top self.end_n_top = end_n_top else: raise ValueError("First argument must be either a vocabulary size (int)" " or the path to a pretrained model config file (str)") @property def vocab_size(self): return self.n_words @vocab_size.setter def vocab_size(self, value): self.n_words = value @property def hidden_size(self): return self.emb_dim @property def num_attention_heads(self): return self.n_heads @property def num_hidden_layers(self): return self.n_layers
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/base/configuration_xlm.py
0.737158
0.185873
configuration_xlm.py
pypi
from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from typing import List, Dict, Tuple import torch from relogic.logickit.utils import create_tensor from relogic.logickit.tokenizer.tokenization import BertTokenizer class DependencyParsingExample(Example): """DependencyParsingExample """ def __init__(self, text, arcs=None, labels=None, lang=None): super(DependencyParsingExample, self).__init__() self.text = text self.raw_tokens = text.split() self.arcs = arcs self.labels = labels self.lang = lang self.label_padding = "X" def process(self, tokenizers: Dict, *inputs, **kwargs): for tokenizer in tokenizers.values(): if isinstance(tokenizer, BertTokenizer): self.text_tokens, self.text_is_head = tokenizer.tokenize(self.text) self.tokens = ["[CLS]"] + self.text_tokens + ["[SEP]"] self.segment_ids = [0] * (len(self.tokens)) self.is_head = [2] + self.text_is_head + [2] self.head_index = [idx for idx, value in enumerate(self.is_head) if value == 1] self.input_ids = tokenizer.convert_tokens_to_ids(self.tokens) self.input_mask = [1] * len(self.input_ids) if self.arcs is not None and self.labels is not None: label_mapping = kwargs.get("label_mapping") self.label_padding_id = label_mapping[self.label_padding] self.label_ids = [self.label_padding_id] * len(self.input_ids) self.arcs_ids = [-1] * len(self.input_ids) assert(len(self.labels) == len(self.arcs)) for idx, label, arc in zip(self.head_index, self.labels, self.arcs): self.label_ids[idx] = label_mapping[label] self.arcs_ids[idx] = arc else: self.label_ids = None self.arcs_ids = None if self.lang is not None: language_name2id = kwargs.get("language_name2id") if language_name2id is not None: self.lang_id = language_name2id[self.lang] @classmethod def from_structure(cls, structure): return cls(text=structure.text) @classmethod def from_json(cls, example): return cls(text=" ".join(example["tokens"]), arcs=example.get("arcs", None), labels=example.get("labels", None), lang=example.get("lang", None)) @property def len(self): return len(self.input_ids) class DependencyParsingFeature(Feature): """ Sequence Features """ def __init__(self, *inputs, **kwargs): super().__init__() self.input_ids = kwargs.pop("input_ids") self.input_mask = kwargs.pop("input_mask") self.segment_ids = kwargs.pop("segment_ids") self.is_head = kwargs.pop("is_head") self.arcs_ids = kwargs.pop("arcs_ids") self.label_ids = kwargs.pop("label_ids") self.lang_ids = kwargs.pop("lang_ids", None) class DependencyParsingMiniBatch(MiniBatch): def __init__(self, *inputs, **kwargs): super().__init__(*inputs, **kwargs) def generate_input(self, device, use_label): inputs = {} inputs["task_name"] = self.task_name inputs["input_ids"] = create_tensor(self.input_features, "input_ids", torch.long, device) inputs["input_mask"] = create_tensor(self.input_features, "input_mask", torch.long, device) inputs["segment_ids"] = create_tensor(self.input_features, "segment_ids", torch.long, device) inputs["input_head"] = create_tensor(self.input_features, "is_head", torch.long, device) if use_label: label_ids = create_tensor(self.input_features, "label_ids", torch.long, device) inputs["label_ids"] = label_ids arcs_ids = create_tensor(self.input_features, "arcs_ids", torch.long, device) inputs["arcs_ids"] = arcs_ids else: inputs["label_ids"] = None inputs["arcs_ids"] = None inputs["lang_ids"] = create_tensor(self.input_features, "lang_ids", torch.long, device) inputs["extra_args"] = {} return inputs class DependencyParsingDataFlow(DataFlow): def __init__(self, config, task_name, tokenizers, label_mapping): super().__init__(config, task_name, tokenizers, label_mapping) self._inv_label_mapping = {v: k for k, v in label_mapping.items()} @property def example_class(self): return DependencyParsingExample @property def minibatch_class(self): return DependencyParsingMiniBatch def process_example(self, example: DependencyParsingExample): example.process(tokenizers=self.tokenizers, label_mapping=self.label_mapping, language_name2id=None) def convert_examples_to_features(self, examples: List[DependencyParsingExample]): examples: List[DependencyParsingExample] features = [] max_token_length = max([example.len for example in examples]) for idx, example in enumerate(examples): padding = [0] * (max_token_length - example.len) input_ids = example.input_ids + padding input_mask = example.input_mask + padding segment_ids = example.segment_ids + padding is_head = example.is_head + [2] * (max_token_length - example.len) if example.label_ids is not None and example.arcs_ids is not None: label_ids = example.label_ids + [example.label_padding_id] * (max_token_length - example.len) arcs_ids = example.arcs_ids + [-1] * (max_token_length - example.len) else: label_ids = None arcs_ids = None features.append(DependencyParsingFeature( input_ids=input_ids, input_mask=input_mask, is_head=is_head, segment_ids=segment_ids, label_ids=label_ids, arcs_ids=arcs_ids)) return features
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/dataflow/dep.py
0.83508
0.340691
dep.py
pypi
from typing import List, Tuple import torch from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from relogic.logickit.utils import create_tensor from relogic.logickit.tokenizer import CustomizedBertTokenizer, RobertaXLMTokenizer class MixSentExample(Example): """MixSent Example contains the attributes and functionality for MixSent Semi-supervised Learning. """ def __init__( self, text_a: str, text_b: str, text_c: str, span_a, span_b, span_c_a, span_c_b): super().__init__() self.text_a = text_a self.a_raw_tokens = text_a.split() self.text_b = text_b self.b_raw_tokens = text_b.split() self.text_c = text_c self.c_raw_tokens = text_c.split() self.span_a = span_a self.span_b = span_b self.span_c_a = span_c_a self.span_c_b = span_c_b self.padding_id = 0 def process(self, tokenizers, *inputs, **kwargs): for tokenizer in tokenizers.values(): if isinstance(tokenizer, RobertaXLMTokenizer): (self.a_tokens, self.a_is_head, self.a_input_ids) = tokenizer.tokenize_and_add_placeholder_and_convert_to_ids(self.text_a, self.a_raw_tokens) (self.b_tokens, self.b_is_head, self.b_input_ids) = tokenizer.tokenize_and_add_placeholder_and_convert_to_ids(self.text_b, self.b_raw_tokens) (self.c_tokens, self.c_is_head, self.c_input_ids) = tokenizer.tokenize_and_add_placeholder_and_convert_to_ids(self.text_c, self.c_raw_tokens) self.a_segment_ids = [0] * len(self.a_tokens) self.b_segment_ids = [0] * len(self.b_tokens) self.c_segment_ids = [0] * len(self.c_tokens) self.a_head_index = [idx for idx, value in enumerate(self.a_is_head) if value == 1] self.b_head_index = [idx for idx, value in enumerate(self.b_is_head) if value == 1] self.c_head_index = [idx for idx, value in enumerate(self.c_is_head) if value == 1] self.a_input_mask = [1] * len(self.a_input_ids) self.b_input_mask = [1] * len(self.b_input_ids) self.c_input_mask = [1] * len(self.c_input_ids) self.span_a_selected_index = [self.a_head_index[index] for index in range(self.span_a[0], self.span_a[1])] self.span_b_selected_index = [self.b_head_index[index] for index in range(self.span_b[0], self.span_b[1])] self.span_c_a_selected_index = [self.c_head_index[index] for index in range(self.span_c_a[0], self.span_c_a[1])] self.span_c_b_selected_index = [self.c_head_index[index] for index in range(self.span_c_b[0], self.span_c_b[1])] self.padding_id = 1 @classmethod def from_structure(cls, structure): pass @classmethod def from_json(cls, example): if isinstance(example["text_a"], list): # TODO depends on the language! text_a = " ".join(example["text_a"]) text_b = " ".join(example["text_b"]) text_c = " ".join(example["text_c"]) elif isinstance(example["text_a"], str): text_a = example["text_a"] text_b = example["text_b"] text_c = example["text_c"] else: raise NotImplementedError("Unsupported data type {}".format(type(example["text_a"]))) return cls(text_a=text_a, text_b=text_b, text_c=text_c, span_a=example["span_a"], span_b=example["span_b"], span_c_a=example["span_c_a"], span_c_b=example["span_c_b"]) @property def len(self): return len(self.a_input_ids) + len(self.b_input_ids) + len(self.c_input_ids) @property def len_a(self): return len(self.a_input_ids) @property def len_b(self): return len(self.b_input_ids) @property def len_c(self): return len(self.c_input_ids) class MixSentFeature(Feature): """ """ def __init__(self, *inputs, **kwargs): super().__init__() self.a_input_ids = kwargs.pop("a_input_ids") self.b_input_ids = kwargs.pop("b_input_ids") self.c_input_ids = kwargs.pop("c_input_ids") self.a_segment_ids = kwargs.pop("a_segment_ids") self.b_segment_ids = kwargs.pop("b_segment_ids") self.c_segment_ids = kwargs.pop("c_segment_ids") self.a_is_head = kwargs.pop("a_is_head") self.b_is_head = kwargs.pop("b_is_head") self.c_is_head = kwargs.pop("c_is_head") self.a_input_mask = kwargs.pop("a_input_mask") self.b_input_mask = kwargs.pop("b_input_mask") self.c_input_mask = kwargs.pop("c_input_mask") self.span_a_selected_index = kwargs.pop("span_a_selected_index") self.span_b_selected_index = kwargs.pop("span_b_selected_index") self.span_c_a_selected_index = kwargs.pop("span_c_a_selected_index") self.span_c_b_selected_index = kwargs.pop("span_c_b_selected_index") class MixSentMiniBatch(MiniBatch): def __init__(self, *inputs, **kwargs): super().__init__(*inputs, **kwargs) def generate_input(self, device, use_label): inputs = {} inputs["task_name"] = self.task_name inputs["a_input_ids"] = create_tensor(self.input_features, "a_input_ids", torch.long, device) inputs["a_input_mask"] = create_tensor(self.input_features, "a_input_mask", torch.long, device) inputs["a_segment_ids"] = create_tensor(self.input_features, "a_segment_ids", torch.long, device) inputs["a_input_head"] = create_tensor(self.input_features, "a_is_head", torch.long, device) inputs["b_input_ids"] = create_tensor(self.input_features, "b_input_ids", torch.long, device) inputs["b_input_mask"] = create_tensor(self.input_features, "b_input_mask", torch.long, device) inputs["b_segment_ids"] = create_tensor(self.input_features, "b_segment_ids", torch.long, device) inputs["b_input_head"] = create_tensor(self.input_features, "b_is_head", torch.long, device) inputs["c_input_ids"] = create_tensor(self.input_features, "c_input_ids", torch.long, device) inputs["c_input_mask"] = create_tensor(self.input_features, "c_input_mask", torch.long, device) inputs["c_segment_ids"] = create_tensor(self.input_features, "c_segment_ids", torch.long, device) inputs["c_input_head"] = create_tensor(self.input_features, "c_is_head", torch.long, device) inputs["span_a_selected_index"] = create_tensor(self.input_features, "span_a_selected_index", torch.long, device) inputs["span_b_selected_index"] = create_tensor(self.input_features, "span_b_selected_index", torch.long, device) inputs["span_c_a_selected_index"] = create_tensor(self.input_features, "span_c_a_selected_index", torch.long, device) inputs["span_c_b_selected_index"] = create_tensor(self.input_features, "span_c_b_selected_index", torch.long, device) inputs["extra_args"] = {} return inputs class MixSentDataFlow(DataFlow): def __init__(self, config, task_name, tokenizers, label_mapping): super().__init__(config, task_name, tokenizers, label_mapping) @property def example_class(self): return MixSentExample @property def minibatch_class(self): return MixSentMiniBatch def process_example(self, example: MixSentExample): example.process(tokenizers=self.tokenizers) def convert_examples_to_features(self, examples: List[MixSentExample]): examples: List[MixSentExample] features = [] a_max_token_length = max([example.len_a for example in examples]) b_max_token_length = max([example.len_b for example in examples]) c_max_token_length = max([example.len_c for example in examples]) span_a_selected_index_max_length = max([len(example.span_a_selected_index) for example in examples]) span_b_selected_index_max_length = max([len(example.span_b_selected_index) for example in examples]) span_c_a_selected_index_max_length = max([len(example.span_c_a_selected_index) for example in examples]) span_c_b_selected_index_max_length = max([len(example.span_c_b_selected_index) for example in examples]) for idx, example in enumerate(examples): a_padding = [0] * (a_max_token_length - example.len_a) b_padding = [0] * (b_max_token_length - example.len_b) c_padding = [0] * (c_max_token_length - example.len_c) a_input_ids = example.a_input_ids + [example.padding_id] * (a_max_token_length - example.len_a) b_input_ids = example.b_input_ids + [example.padding_id] * (b_max_token_length - example.len_b) c_input_ids = example.c_input_ids + [example.padding_id] * (c_max_token_length - example.len_c) a_segment_ids = example.a_segment_ids + a_padding b_segment_ids = example.b_segment_ids + b_padding c_segment_ids = example.c_segment_ids + c_padding a_input_mask = example.a_input_mask + a_padding b_input_mask = example.b_input_mask + b_padding c_input_mask = example.c_input_mask + c_padding a_is_head = example.a_is_head + a_padding b_is_head = example.b_is_head + b_padding c_is_head = example.c_is_head + c_padding span_a_selected_index = example.span_a_selected_index + [0] * ( span_a_selected_index_max_length - len(example.span_a_selected_index)) span_b_selected_index = example.span_b_selected_index + [0] * ( span_b_selected_index_max_length - len(example.span_b_selected_index)) span_c_a_selected_index = example.span_c_a_selected_index + [0] * ( span_c_a_selected_index_max_length - len(example.span_c_a_selected_index)) span_c_b_selected_index = example.span_c_b_selected_index + [0] * ( span_c_b_selected_index_max_length - len(example.span_c_b_selected_index)) features.append( MixSentFeature( a_input_ids=a_input_ids, b_input_ids=b_input_ids, c_input_ids=c_input_ids, a_input_mask=a_input_mask, b_input_mask=b_input_mask, c_input_mask=c_input_mask, a_segment_ids=a_segment_ids, b_segment_ids=b_segment_ids, c_segment_ids=c_segment_ids, a_is_head=a_is_head, b_is_head=b_is_head, c_is_head=c_is_head, span_a_selected_index=span_a_selected_index, span_b_selected_index=span_b_selected_index, span_c_a_selected_index=span_c_a_selected_index, span_c_b_selected_index=span_c_b_selected_index)) return features
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/dataflow/mixsent.py
0.688783
0.408218
mixsent.py
pypi
import json from typing import List, Tuple, Dict import os import torch from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from relogic.logickit.tokenizer.tokenization import BertTokenizer from relogic.logickit.utils import create_tensor, filter_head_prediction class SingletonExample(Example): """SingletonExample contains the attributes and functionality of an Sentence Classification example. Args: text (str): A sentence string. labels (str or List[str]): A label string or a list of label string. """ def __init__(self, text, labels=None): super(SingletonExample, self).__init__() self.text = text self.raw_tokens = text.split() self.labels = labels def process(self, tokenizers: Dict, *inputs, **kwargs): """Process the Singleton Example.. """ for tokenizer in tokenizers.values(): if isinstance(tokenizer, BertTokenizer): # BERT process part self.text_tokens, self.text_is_head = tokenizer.tokenize(self.text) self.tokens = ["[CLS]"] + self.text_tokens + ["[SEP]"] self.segment_ids = [0] * (len(self.tokens)) self.is_head = [2] + self.text_is_head + [2] self.head_index = [idx for idx, value in enumerate(self.is_head) if value == 1] self.input_ids = tokenizer.convert_tokens_to_ids(self.tokens) self.input_mask = [1] * len(self.input_ids) if self.labels is not None: label_mapping = kwargs.get("label_mapping") if isinstance(self.labels, str): # Single Label Classfication self.label_ids = label_mapping[self.labels] elif isinstance(self.labels, list): # Multi Label Classification label_size = len(label_mapping) self.label_ids = [0] * label_size for label in self.labels: self.label_ids[label_mapping[label]] = 1 else: self.label_ids = None @classmethod def from_structure(cls, structure): return cls(text=structure.text) @classmethod def from_json(cls, example): return cls(text=" ".join(example["tokens"]), labels=example.get("labels", None)) @property def len(self): return len(self.input_ids) class SingletonFeature(Feature): """Singleton Features. """ def __init__(self, *inputs, **kwargs): super(SingletonFeature, self).__init__() self.input_ids = kwargs.pop("input_ids") self.input_mask = kwargs.pop("input_mask") self.segment_ids = kwargs.pop("segment_ids") self.is_head = kwargs.pop("is_head") self.label_ids = kwargs.pop("label_ids") class SingletonMiniBatch(MiniBatch): """ """ def __init__(self, *inputs, **kwargs): super(SingletonMiniBatch, self).__init__(*inputs, **kwargs) def generate_input(self, device, use_label): inputs = {} inputs["task_name"] = self.task_name inputs["input_ids"] = create_tensor(self.input_features, "input_ids", torch.long, device) inputs["input_mask"] = create_tensor(self.input_features, "input_mask", torch.long, device) inputs["segment_ids"] = create_tensor(self.input_features, "segment_ids", torch.long, device) inputs["input_head"] = create_tensor(self.input_features, "is_head", torch.long, device) if use_label: label_ids = create_tensor(self.input_features, "label_ids", torch.long, device) inputs["label_ids"] = label_ids else: inputs["label_ids"] = None # inputs["extra_args"] = { # "selected_non_final_layers": [10] # } inputs["extra_args"] = {} if self.config.tasks[self.task_name]["selected_non_final_layers"] is not None: inputs["extra_args"]["selected_non_final_layers"] = self.config.tasks[self.task_name]["selected_non_final_layers"] return inputs class SingletonDataFlow(DataFlow): def __init__(self, config, task_name, tokenizers, label_mapping): super(SingletonDataFlow, self).__init__(config, task_name, tokenizers, label_mapping) self._inv_label_mapping = {v: k for k, v in label_mapping.items()} @property def example_class(self): return SingletonExample @property def minibatch_class(self): return SingletonMiniBatch def process_example(self, example: SingletonExample): example.process(tokenizers=self.tokenizers, label_mapping=self.label_mapping) def convert_examples_to_features(self, examples: List[SingletonExample]): examples: List[SingletonExample] features = [] max_token_length = max([example.len for example in examples]) for idx, example in enumerate(examples): padding = [0] * (max_token_length - example.len) input_ids = example.input_ids + padding input_mask = example.input_mask + padding segment_ids = example.segment_ids + padding is_head = example.is_head + [2] * (max_token_length - example.len) if example.label_ids is not None: # We assume the label length is same as sequence length label_ids = example.label_ids else: label_ids = None features.append(SingletonFeature( input_ids=input_ids, input_mask=input_mask, is_head=is_head, segment_ids=segment_ids, label_ids=label_ids)) return features def decode_to_labels(self, preds, mb: MiniBatch): labels = [] for example, pred_logits in zip(mb.examples, preds): pred_probs = torch.sigmoid(pred_logits).data.cpu().numpy() pred_label = [] for idx, pred_prob in enumerate(pred_probs): if pred_prob > 0.5: pred_label.append(self._inv_label_mapping[idx]) labels.append(pred_label) return labels
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/dataflow/singleton.py
0.783988
0.354643
singleton.py
pypi
from typing import List import torch from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from relogic.logickit.tokenizer.tokenization import BertTokenizer from relogic.logickit.utils import create_tensor, truncate_seq_pair class PointwiseExample(Example): """Pointwise Example contains the attributes and functionality of a pointwise example. This class is mainly used for sentence pair classification task, such as information retrieval, sentence similarity, with cross-entropy loss function. In this example, we call the first sentence as text_a, and the second sentence as text_b. Args: guid (str): global unique identifier for this pair. This information is usually used in the ranking problem. text (str): """ def __init__(self, guid: str, text_a: str, text_b:str, label=None): super(PointwiseExample, self).__init__() self.guid = guid self.text_a = text_a self.text_b = text_b self.label = label def process(self, tokenizers, *inputs, regression=False, **kwargs): """Process the sentence pair. :param tokenizers: :param inputs: :param kwargs: :return: """ for tokenizer in tokenizers.values(): if isinstance(tokenizer, BertTokenizer): self.text_a_tokens, self.text_a_is_head = tokenizer.tokenize(self.text_a) self.text_b_tokens, self.text_b_is_head = tokenizer.tokenize(self.text_b) max_seq_length = kwargs.pop("max_seq_length", 512) truncate_seq_pair(self.text_a_tokens, self.text_b_tokens, max_seq_length - 3) truncate_seq_pair(self.text_a_is_head, self.text_b_is_head, max_seq_length - 3) self.tokens = ["[CLS]"] + self.text_a_tokens + ["[SEP]"] + self.text_b_tokens + ["[SEP]"] self.segment_ids = [0] * (len(self.text_a_tokens) + 2) + [1] * (len(self.text_b_tokens) + 1) self.is_head = [2] + self.text_a_is_head + [2] + self.text_b_is_head + [2] self.input_ids = tokenizer.convert_tokens_to_ids(self.tokens) self.input_mask = [1] * len(self.input_ids) self.text_a_indices = [] self.text_b_indices = [] for idx, ind in enumerate(self.text_a_is_head): if ind == 1: self.text_a_indices.append(idx + 1) for idx, ind in enumerate(self.text_b_is_head): if ind == 1: self.text_b_indices.append(idx + len(self.text_a_is_head) + 2) if self.label is not None: if regression: # Regression Problem with sigmoid loss function self.label_ids = float(self.label) else: label_mapping = kwargs.get("label_mapping") self.label_ids = label_mapping[self.label] @classmethod def from_structure(cls, structure): return cls(guid="", text_a=structure.text_a, text_b=structure.text_b) @classmethod def from_json(cls, example): """ """ if isinstance(example["text_a"], str) and isinstance(example["text_b"], str): return cls(guid="{}|{}".format(example.get("text_a_id", 0), example.get("text_b_id", 0)), text_a=example["text_a"], text_b=example["text_b"], label=example.get("label", None)) else: return cls(guid="{}|{}".format(example.get("text_a_id", 0), example.get("text_b_id", 0)), text_a=" ".join(example["text_a"]), text_b=" ".join(example["text_b"]), label=example.get("label", None)) @property def len(self): return len(self.input_ids) class PointwiseFeature(Feature): """ """ def __init__(self, *inputs, **kwargs): super(PointwiseFeature, self).__init__() # BERT based feature self.input_ids = kwargs.pop("input_ids") self.input_mask = kwargs.pop("input_mask") self.is_head = kwargs.pop("is_head") self.segment_ids = kwargs.pop("segment_ids") self.text_a_indices = kwargs.pop("text_a_indices") self.text_b_indices = kwargs.pop("text_b_indices") self.label_ids = kwargs.pop("label_ids") class PointwiseMiniBatch(MiniBatch): """ """ def __init__(self, *inputs, **kwargs): super(PointwiseMiniBatch, self).__init__(*inputs, **kwargs) def generate_input(self, device, use_label): """Generate tensors based on PointwiseFeatures """ # BERT based feature inputs = {} inputs["task_name"] = self.task_name inputs["input_ids"] = create_tensor(self.input_features, "input_ids", torch.long, device) inputs["input_mask"] = create_tensor(self.input_features, "input_mask", torch.long, device) inputs["segment_ids"] = create_tensor(self.input_features, "segment_ids", torch.long, device) inputs["input_head"] = create_tensor(self.input_features, "is_head", torch.long, device) inputs["text_a_indices"] = create_tensor(self.input_features, "text_a_indices", torch.long, device) inputs["text_b_indices"] = create_tensor(self.input_features, "text_b_indices", torch.long, device) if use_label: if self.config.regression: inputs["label_ids"] = create_tensor(self.input_features, "label_ids", torch.float, device) else: inputs["label_ids"] = create_tensor(self.input_features, "label_ids", torch.long, device) else: inputs["label_ids"] = None inputs["extra_args"] = {} if self.config.tasks[self.task_name]["selected_non_final_layers"] is not None: inputs["extra_args"]["selected_non_final_layers"] = self.config.tasks[self.task_name]["selected_non_final_layers"] return inputs class PointwiseDataFlow(DataFlow): """DataFlow implementation based on Pointwise task""" def __init__(self, config, task_name, tokenizers, label_mapping): super(PointwiseDataFlow, self).__init__(config, task_name, tokenizers, label_mapping) @property def example_class(self): return PointwiseExample @property def minibatch_class(self): return PointwiseMiniBatch def process_example(self, example: PointwiseExample): """Process Pointwise example""" example.process(tokenizers=self.tokenizers, label_mapping=self.label_mapping, regression=self.config.regression) def convert_examples_to_features(self, examples: List[PointwiseExample]): examples: List[PointwiseExample] features = [] # BERT based variables max_token_length = max([example.len for example in examples]) max_text_a_indices_length = max([len(example.text_a_indices) for example in examples]) max_text_b_indices_length = max([len(example.text_b_indices) for example in examples]) for idx, example in enumerate(examples): # BERT based feature process padding = [0] * (max_token_length - example.len) input_ids = example.input_ids + padding input_mask = example.input_mask + padding segment_ids = example.segment_ids + padding is_head = example.is_head + padding a_indices_padding = [0] * (max_text_a_indices_length - len(example.text_a_indices)) b_indices_padding = [0] * (max_text_b_indices_length - len(example.text_b_indices)) text_a_indices = example.text_a_indices + a_indices_padding text_b_indices = example.text_b_indices + b_indices_padding if hasattr(example, "label_ids"): label_ids = example.label_ids else: label_ids = None features.append( PointwiseFeature(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, is_head=is_head, text_a_indices=text_a_indices, text_b_indices=text_b_indices, label_ids=label_ids)) return features def decode_to_labels(self, preds, mbs: PointwiseMiniBatch): return preds
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/dataflow/pointwise.py
0.892767
0.38194
pointwise.py
pypi
from typing import List import torch from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from relogic.logickit.tokenizer.tokenization import BertTokenizer from relogic.logickit.utils import create_tensor, truncate_seq_pair class DocPointwiseExample(Example): """ """ def __init__(self, guid: str, text_a: str, text_bs: List[str], label=None, sent_label=None): super().__init__() self.guid = guid self.text_a = text_a self.text_bs = text_bs self.label = label self.sent_label = sent_label self.sent_num = len(self.text_bs) def process(self, tokenizers, *inputs, regression=False, **kwargs): for tokenizer in tokenizers.values(): if isinstance(tokenizer, BertTokenizer): self.text_a_tokens, self.text_a_is_head = tokenizer.tokenize(self.text_a) self.text_bs_tokens, self.text_bs_is_head = zip(*[tokenizer.tokenize(text_b) for text_b in self.text_bs]) max_seq_length = kwargs.pop("max_seq_length", 512) for i in range(self.sent_num): truncate_seq_pair(self.text_a_tokens, self.text_bs_tokens[i], max_seq_length - 3) truncate_seq_pair(self.text_a_is_head, self.text_bs_is_head[i], max_seq_length - 3) self.tokens_list = [] self.segment_ids_list = [] self.is_head_list = [] self.input_ids_list = [] self.input_mask_list = [] for i in range(self.sent_num): self.tokens_list.append(["[CLS]"] + self.text_a_tokens + ["[SEP]"] + self.text_bs_tokens[i] + ["[SEP]"]) self.segment_ids_list.append([0] * (len(self.text_a_tokens) + 2) + [1] * (len(self.text_bs_tokens[i]) + 1)) self.is_head_list.append([2] + self.text_a_is_head + [2] + self.text_bs_is_head[i] + [2]) self.input_ids_list.append(tokenizer.convert_tokens_to_ids(self.tokens_list[i])) self.input_mask_list.append([1] * len(self.input_ids_list[i])) if self.label is not None: if regression: # Regression Problem with sigmoid loss function self.label_ids = float(self.label) else: label_mapping = kwargs.get("label_mapping") self.label_ids = label_mapping[self.label] @classmethod def from_structure(cls, structure): return cls(guid="", text_a=structure.text_a, text_bs=structure.text_b) @classmethod def from_json(cls, example): return cls(guid="{}|{}".format(example.get("text_a_id", 0), example.get("text_b_id", 0)), text_a=example["text_a"], text_bs=example["text_b"], label=example.get("label", None)) @property def len(self): return 1 def _len(self, i): return len(self.input_ids_list[i]) class DocPointwiseFeature(Feature): def __init__(self, *inputs, **kwargs): super().__init__() self.input_ids = kwargs.pop("input_ids") self.input_mask = kwargs.pop("input_mask") self.segment_ids = kwargs.pop("segment_ids") self.label_ids = kwargs.pop("label_ids") class DocPointwiseMiniBatch(MiniBatch): def __init__(self, *inputs, **kwargs): super().__init__(*inputs, **kwargs) def generate_input(self, device, use_label): inputs = {} inputs["task_name"] = self.task_name inputs["input_ids"] = create_tensor(self.input_features, "input_ids", torch.long, device) inputs["input_mask"] = create_tensor(self.input_features, "input_mask", torch.long, device) inputs["segment_ids"] = create_tensor(self.input_features, "segment_ids", torch.long, device) inputs["input_head"] = create_tensor(self.input_features, "is_head", torch.long, device) if use_label: if self.config.regression: inputs["label_ids"] = create_tensor(self.input_features, "label_ids", torch.float, device) else: inputs["label_ids"] = create_tensor(self.input_features, "label_ids", torch.long, device) else: inputs["label_ids"] = None inputs["extra_args"] = {} return inputs class DocPointwiseDataFlow(DataFlow): def __init__(self, config, task_name, tokenizers, label_mapping): super().__init__(config, task_name, tokenizers, label_mapping) @property def example_class(self): return DocPointwiseExample @property def minibatch_class(self): return DocPointwiseMiniBatch def process_example(self, example: DocPointwiseExample): example.process(tokenizers=self.tokenizers, label_mapping=self.label_mapping, max_seq_length=self.config.max_seq_length, regression=self.config.regression) def convert_examples_to_features(self, examples: List[DocPointwiseExample]): examples: List[DocPointwiseExample] # Because we want to have batch operation on one example # So len(examples) == 1 features = [] assert len(examples) == 1, "We can only handle one example at a time for batching" example = examples[0] max_token_length = max([example._len(i) for i in range(example.sent_num)]) for idx in range(example.sent_num): padding = [0] * (max_token_length - example._len(idx)) input_ids = example.input_ids_list[idx] + padding input_mask = example.input_mask_list[idx] + padding segment_ids = example.segment_ids_list[idx] + padding if hasattr(example, "label_ids"): label_ids = example.label_ids else: label_ids = None features.append( DocPointwiseFeature(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, label_ids=label_ids)) return features def decode_to_labels(self, preds, mbs: DocPointwiseMiniBatch): return None
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/dataflow/doc_pointwise.py
0.862496
0.331012
doc_pointwise.py
pypi
from typing import List import torch from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from relogic.logickit.tokenizer.tokenization import BertTokenizer from relogic.logickit.utils import create_tensor, truncate_seq_pair class PairwiseExample(Example): """ text (str): query text text_p (str): positive example text_n (str): negative example """ def __init__(self, guid: str, text: str, p_guid: str=None, text_p:str=None, n_guid: str=None, text_n:str=None): super(PairwiseExample, self).__init__() self.guid = guid self.text = text self.p_guid = p_guid self.text_p = text_p self.n_guid = n_guid self.text_n = text_n def process(self, tokenizers, *inputs, **kwargs): for tokenizer in tokenizers.values(): if isinstance(tokenizer, BertTokenizer): max_seq_length = kwargs.pop("max_seq_length", 512) self.text_tokens, self.text_is_head = tokenizer.tokenize(self.text) self.text_tokens = self.text_tokens[:max_seq_length - 2] self.text_is_head = self.text_is_head[:max_seq_length - 2] self.tokens = ["[CLS]"] + self.text_tokens + ["[SEP]"] self.input_ids = tokenizer.convert_tokens_to_ids(self.tokens) self.input_mask = [1] * len(self.input_ids) self.segment_ids = [0] * len(self.input_ids) if self.text_p: self.text_p_tokens, self.text_p_is_head = tokenizer.tokenize(self.text_p) self.text_p_tokens = self.text_p_tokens[:max_seq_length - 2] self.text_p_is_head = self.text_p_is_head[:max_seq_length - 2] self.p_tokens = ["[CLS]"] + self.text_p_tokens + ["[SEP]"] self.p_input_ids = tokenizer.convert_tokens_to_ids(self.p_tokens) self.p_input_mask = [1] * len(self.p_input_ids) self.p_segment_ids = [0] * len(self.p_input_ids) if self.text_n: self.text_n_tokens, self.text_n_is_head = tokenizer.tokenize(self.text_n) self.text_n_tokens = self.text_n_tokens[:max_seq_length - 2] self.text_n_is_head = self.text_n_is_head[:max_seq_length - 2] self.n_tokens = ["[CLS]"] + self.text_n_tokens + ["[SEP]"] self.n_input_ids = tokenizer.convert_tokens_to_ids(self.n_tokens) self.n_input_mask = [1] * len(self.n_input_ids) self.n_segment_ids = [0] * len(self.n_input_ids) @classmethod def from_structure(cls, structure): return cls(guid="", text=structure.text) @classmethod def from_json(cls, example): return cls(guid=example.get("guid", None), text=example["text"], text_p=example.get("text_p", None), text_n=example.get("text_n", None), p_guid=example.get("p_guid", None), n_guid=example.get("n_guid", None)) @property def len(self): return len(self.tokens) @property def len_p(self): return len(self.p_tokens) @property def len_n(self): return len(self.n_tokens) class PairwiseFeature(Feature): """ """ def __init__(self, *inputs, **kwargs): super(PairwiseFeature, self).__init__() # BERT based feature self.input_ids = kwargs.pop("input_ids") self.input_mask = kwargs.pop("input_mask") self.segment_ids = kwargs.pop("segment_ids") self.p_input_ids = kwargs.pop("p_input_ids", None) self.p_input_mask = kwargs.pop("p_input_mask", None) self.p_segment_ids = kwargs.pop("p_segment_ids", None) self.n_input_ids = kwargs.pop("n_input_ids", None) self.n_input_mask = kwargs.pop("n_input_mask", None) self.n_segment_ids = kwargs.pop("n_segment_ids", None) class PairwiseMiniBatch(MiniBatch): def __init__(self, *inputs, **kwargs): super(PairwiseMiniBatch, self).__init__(*inputs, **kwargs) def generate_input(self, device, use_label): inputs = {} inputs["task_name"] = self.task_name inputs["input_ids"] = create_tensor(self.input_features, "input_ids", torch.long, device) inputs["input_mask"] = create_tensor(self.input_features, "input_mask", torch.long, device) inputs["segment_ids"] = create_tensor(self.input_features, "segment_ids", torch.long, device) inputs["p_input_ids"] = create_tensor(self.input_features, "p_input_ids", torch.long, device) inputs["p_input_mask"] = create_tensor(self.input_features, "p_input_mask", torch.long, device) inputs["p_segment_ids"] = create_tensor(self.input_features, "p_segment_ids", torch.long, device) inputs["n_input_ids"] = create_tensor(self.input_features, "n_input_ids", torch.long, device) inputs["n_input_mask"] = create_tensor(self.input_features, "n_input_mask", torch.long, device) inputs["n_segment_ids"] = create_tensor(self.input_features, "n_segment_ids", torch.long, device) inputs["is_inference"] = not use_label inputs["extra_args"] = {"target": -torch.ones(inputs["input_ids"].size(0)).to(device)} return inputs class PairwiseDataFlow(DataFlow): def __init__(self, config, task_name, tokenizers, label_mapping=None): super(PairwiseDataFlow, self).__init__(config, task_name, tokenizers, label_mapping) @property def example_class(self): return PairwiseExample @property def minibatch_class(self): return PairwiseMiniBatch def process_example(self, example: PairwiseExample): example.process(tokenizers=self.tokenizers, max_seq_length=self.config.max_seq_length) def convert_examples_to_features(self, examples: List[PairwiseExample]): examples: List[PairwiseExample] features = [] max_token_length = max([example.len for example in examples]) try: max_token_length_p = max([example.len_p for example in examples]) max_token_length_n = max([example.len_n for example in examples]) except: max_token_length_p = 0 max_token_length_n = 0 for idx, example in enumerate(examples): padding = [0] * (max_token_length - example.len) input_ids = example.input_ids + padding input_mask = example.input_mask + padding segment_ids = example.segment_ids + padding if max_token_length_p > 0 and max_token_length_n > 0: p_padding = [0] * (max_token_length_p - example.len_p) p_input_ids = example.p_input_ids + p_padding p_input_mask = example.p_input_mask + p_padding p_segment_ids = example.p_segment_ids + p_padding n_padding = [0] * (max_token_length_n - example.len_n) n_input_ids = example.n_input_ids + n_padding n_input_mask = example.n_input_mask + n_padding n_segment_ids = example.n_segment_ids + n_padding features.append( PairwiseFeature(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids, p_input_ids=p_input_ids, p_input_mask=p_input_mask, p_segment_ids=p_segment_ids, n_input_ids=n_input_ids, n_input_mask=n_input_mask, n_segment_ids=n_segment_ids)) else: features.append( PairwiseFeature(input_ids=input_ids, input_mask=input_mask, segment_ids=segment_ids)) return features
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/dataflow/pairwise.py
0.837138
0.303125
pairwise.py
pypi
from relogic.logickit.base.constants import (JOINT_SRL_TASK, PIPE_SRL_TASK, ECP_TASK, POINTWISE_TASK, IR_TASK, NER_TASK, SEQUENCE_LABELING_TASK, PARALLEL_MAPPING_TASK, PAIRWISE_TASK, PARALLEL_TEACHER_STUDENT_TASK, SEQUENCE_CLASSIFICATION_TASK, ENTITY_TYPE_CLASSIFICATION, DEP_PARSING_TASK, MIXSENT_TASK, LANGUAGE_IDENTIFICATION_IR, POS_TASK, DOCIR_TASK, LANGUAGE_IDENTIFICATION_SEQ, PREDICATE_DETECTION_TASK, IR_SIAMESE_TASK, IR_SAMCNN_TASK) from relogic.logickit.dataflow.dataflow import DataFlow, Example, Feature, MiniBatch from relogic.logickit.dataflow.srl import SRLDataFlow, SRLExample, SRLFeature, SRLMiniBatch from relogic.logickit.dataflow.ecp import ECPDataFlow, ECPExample, ECPFeature, ECPMiniBatch from relogic.logickit.dataflow.pointwise import PointwiseDataFlow, PointwiseExample, PointwiseFeature, PointwiseMiniBatch from relogic.logickit.dataflow.sequence import SequenceDataFlow, SequenceExample, SequenceFeature, SequenceMiniBatch from relogic.logickit.dataflow.parallel import ParallelDataFlow, ParallelExample, ParallelFeature, ParallelMiniBatch from relogic.logickit.dataflow.pairwise import PairwiseDataFlow, PairwiseExample, PairwiseFeature, PairwiseMiniBatch from relogic.logickit.dataflow.singleton import SingletonDataFlow, SingletonExample, SingletonFeature, SingletonMiniBatch from relogic.logickit.dataflow.dep import (DependencyParsingDataFlow, DependencyParsingExample, DependencyParsingFeature, DependencyParsingMiniBatch) from relogic.logickit.dataflow.mixsent import MixSentDataFlow, MixSentExample, MixSentFeature, MixSentMiniBatch from relogic.logickit.dataflow.doc_pointwise import (DocPointwiseDataFlow, DocPointwiseExample, DocPointwiseFeature, DocPointwiseMiniBatch) from relogic.logickit.dataflow.twins import TwinsDataFlow, TwinsExample, TwinsFeature, TwinsMiniBatch from relogic.common.prefix_map import PrefixMap task_to_dataflow_class_map = { PIPE_SRL_TASK: SRLDataFlow, JOINT_SRL_TASK: SRLDataFlow, ECP_TASK: ECPDataFlow, POINTWISE_TASK: PointwiseDataFlow, IR_TASK: PointwiseDataFlow, IR_SIAMESE_TASK: TwinsDataFlow, IR_SAMCNN_TASK: TwinsDataFlow, SEQUENCE_LABELING_TASK: SequenceDataFlow, POS_TASK: SequenceDataFlow, NER_TASK: SequenceDataFlow, PREDICATE_DETECTION_TASK: SequenceDataFlow, PARALLEL_MAPPING_TASK: ParallelDataFlow, PAIRWISE_TASK: PairwiseDataFlow, PARALLEL_TEACHER_STUDENT_TASK: ParallelDataFlow, SEQUENCE_CLASSIFICATION_TASK: SingletonDataFlow, ENTITY_TYPE_CLASSIFICATION: SingletonDataFlow, DEP_PARSING_TASK: DependencyParsingDataFlow, MIXSENT_TASK: MixSentDataFlow, LANGUAGE_IDENTIFICATION_IR: PointwiseDataFlow, LANGUAGE_IDENTIFICATION_SEQ: SingletonDataFlow, DOCIR_TASK: DocPointwiseDataFlow } TASK_TO_DATAFLOW_CLASS_MAP = PrefixMap(task_to_dataflow_class_map)
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/dataflow/__init__.py
0.674265
0.223292
__init__.py
pypi
from typing import List, Tuple import torch from relogic.logickit.dataflow import DataFlow, Example, Feature, MiniBatch from relogic.logickit.utils import create_tensor from transformers.tokenization_utils import PreTrainedTokenizer from relogic.logickit.tokenizer import FasttextTokenizer class TwinsExample(Example): """ Args: text_a (str): sentence in source language text_b (str): sentence in target language label (str) """ def __init__(self, guid: str, text_a: str, text_b: str, labels: str = None): super().__init__() self.guid = guid self.text_a = text_a self.text_b = text_b self.labels = labels self.padding_id = 0 def process(self, tokenizers, *inputs, **kwargs): """Process the sentence pair.""" for tokenizer in tokenizers.values(): if isinstance(tokenizer, PreTrainedTokenizer): self.text_a_tokens = tokenizer.tokenize(self.text_a) self.text_b_tokens = tokenizer.tokenize(self.text_b) self.text_a_tokens = self.text_a_tokens[:510] self.text_b_tokens = self.text_b_tokens[:510] self.a_tokens = ["[CLS]"] + self.text_a_tokens + ["[SEP]"] self.a_segment_ids = [0] * len(self.a_tokens) self.b_tokens = ["[CLS]"] + self.text_b_tokens + ["[SEP]"] self.b_segment_ids = [0] * len(self.b_tokens) self.a_input_ids = tokenizer.convert_tokens_to_ids(self.a_tokens) self.b_input_ids = tokenizer.convert_tokens_to_ids(self.b_tokens) self.a_input_mask = [1] * len(self.a_input_ids) self.b_input_mask = [1] * len(self.b_input_ids) if self.labels is not None: label_mapping = kwargs.get("label_mapping") if isinstance(self.labels, str): # Single Label Classfication self.label_ids = label_mapping[self.labels] elif isinstance(self.labels, list): # Multi Label Classification label_size = len(label_mapping) self.label_ids = [0] * label_size for label in self.labels: self.label_ids[label_mapping[label]] = 1 else: self.label_ids = None elif isinstance(tokenizer, FasttextTokenizer): self._a_text_tokens = tokenizer.tokenize(self.text_a) self._b_text_tokens = tokenizer.tokenize(self.text_b) self._a_input_token_ids = tokenizer.convert_tokens_to_ids(self._a_text_tokens) self._b_input_token_ids = tokenizer.convert_tokens_to_ids(self._b_text_tokens) self._a_input_token_mask = [True] * len(self._a_input_token_ids) self._b_input_token_mask = [True] * len(self._b_input_token_ids) if self.labels is not None: label_mapping = kwargs.get("label_mapping") if isinstance(self.labels, str): # Single Label Classfication self._label_ids = label_mapping[self.labels] elif isinstance(self.labels, list): # Multi Label Classification label_size = len(label_mapping) self._label_ids = [0] * label_size for label in self.labels: self._label_ids[label_mapping[label]] = 1 else: self._label_ids = None @classmethod def from_structure(cls, structure): return cls(guid="", text_a=structure.text_a, text_b=structure.text_b) @classmethod def from_json(cls, example): return cls(guid="{}|{}".format(example.get("text_a_id", 0), example.get("text_b_id", 0)), text_a=example["text_a"], text_b=example["text_b"], labels=example.get("label", None)) @property def len(self): return len(self.a_tokens) + len(self.b_tokens) @property def len_a(self): return len(self.a_tokens) @property def len_b(self): return len(self.b_tokens) @property def _len(self): return len(self._a_input_token_ids) + len(self._b_input_token_ids) @property def _len_a(self): return len(self._a_input_token_ids) @property def _len_b(self): return len(self._b_input_token_ids) class TwinsFeature(Feature): """Parallel Feature """ def __init__(self, *input, **kwargs): super().__init__() self.a_input_ids = kwargs.pop("a_input_ids") self.b_input_ids = kwargs.pop("b_input_ids") self.a_segment_ids = kwargs.pop("a_segment_ids") self.b_segment_ids = kwargs.pop("b_segment_ids") self.a_input_mask = kwargs.pop("a_input_mask") self.b_input_mask = kwargs.pop("b_input_mask") self.label_ids = kwargs.pop("label_ids") # Classical Feature self._a_input_token_ids = kwargs.pop("_a_input_token_ids") self._b_input_token_ids = kwargs.pop("_b_input_token_ids") self._a_token_length = kwargs.pop("_a_token_length") self._b_token_length = kwargs.pop("_b_token_length") self._label_ids = kwargs.pop("_label_ids") self._a_input_token_mask = kwargs.pop("_a_input_token_mask") self._b_input_token_mask = kwargs.pop("_b_input_token_mask") class TwinsMiniBatch(MiniBatch): def __init__(self, *inputs, **kwargs): super().__init__(*inputs, **kwargs) def generate_input(self, device, use_label): """Generate tensors based on Parallel Feature""" # BERT based features inputs = {} inputs["task_name"] = self.task_name inputs["a_input_ids"] = create_tensor(self.input_features, "a_input_ids", torch.long, device) inputs["b_input_ids"] = create_tensor(self.input_features, "b_input_ids", torch.long, device) inputs["a_input_mask"] = create_tensor(self.input_features, "a_input_mask", torch.long, device) inputs["b_input_mask"] = create_tensor(self.input_features, "b_input_mask", torch.long, device) inputs["a_segment_ids"] = create_tensor(self.input_features, "a_segment_ids", torch.long, device) inputs["b_segment_ids"] = create_tensor(self.input_features, "b_segment_ids", torch.long, device) if use_label: label_ids = create_tensor(self.input_features, "label_ids", torch.long, device) inputs["label_ids"] = label_ids else: inputs["label_ids"] = None inputs["extra_args"] = {} if self.config.tasks[self.task_name]["selected_non_final_layers"] is not None: inputs["extra_args"]["selected_non_final_layers"] = self.config.tasks[self.task_name]["selected_non_final_layers"] # Classical Features inputs["_a_input_token_ids"] = create_tensor(self.input_features, "_a_input_token_ids", torch.long, device) inputs["_b_input_token_ids"] = create_tensor(self.input_features, "_b_input_token_ids", torch.long, device) inputs["_a_token_length"] = create_tensor(self.input_features, "_a_token_length", torch.long, device) inputs["_b_token_length"] = create_tensor(self.input_features, "_b_token_length", torch.long, device) inputs["_a_input_token_mask"] = create_tensor(self.input_features, "_a_input_token_mask", torch.long, device) inputs["_b_input_token_mask"] = create_tensor(self.input_features, "_b_input_token_mask", torch.long, device) if use_label: _label_ids = create_tensor(self.input_features, "_label_ids", torch.long, device) inputs["_label_ids"] = _label_ids else: inputs["_label_ids"] = None return inputs class TwinsDataFlow(DataFlow): """DataFlow implementation based on Parallel Task""" def __init__(self, config, task_name, tokenizers, label_mapping): super().__init__(config, task_name, tokenizers, label_mapping) @property def example_class(self): return TwinsExample @property def minibatch_class(self): return TwinsMiniBatch def process_example(self, example: TwinsExample): example.process(tokenizers=self.tokenizers, label_mapping=self.label_mapping) def convert_examples_to_features(self, examples: List[TwinsExample]): examples: List[TwinsExample] features = [] try: a_max_token_length = max([example.len_a for example in examples]) b_max_token_length = max([example.len_b for example in examples]) except: a_max_token_length = None b_max_token_length = None try: _a_max_token_length = max([example._len_a for example in examples]) _b_max_token_length = max([example._len_b for example in examples]) except: _a_max_token_length = None _b_max_token_length = None for idx, example in enumerate(examples): if a_max_token_length is not None: a_padding = [0] * (a_max_token_length - example.len_a) b_padding = [0] * (b_max_token_length - example.len_b) a_input_ids = example.a_input_ids + [example.padding_id] * (a_max_token_length - example.len_a) b_input_ids = example.b_input_ids + [example.padding_id] * (b_max_token_length - example.len_b) a_segment_ids = example.a_segment_ids + a_padding b_segment_ids = example.b_segment_ids + b_padding a_input_mask = example.a_input_mask + a_padding b_input_mask = example.b_input_mask + b_padding if example.label_ids is not None: # We assume the label length is same as sequence length label_ids = example.label_ids else: label_ids = None else: (a_input_ids, b_input_ids, a_segment_ids, b_segment_ids, a_input_mask, b_input_mask, label_ids) = None, None, None, None, None, None, None if _a_max_token_length is not None: _a_input_token_ids = example._a_input_token_ids + [0] * (_a_max_token_length - example._len_a) _a_token_length = example._len_a _a_input_token_mask = example._a_input_token_mask + [False] * (_a_max_token_length - example._len_a) _b_input_token_ids = example._b_input_token_ids + [0] * (_b_max_token_length - example._len_b) _b_token_length = example._len_b _b_input_token_mask = example._b_input_token_mask + [False] * (_b_max_token_length - example._len_b) if example._label_ids is not None: _label_ids = example._label_ids else: _label_ids = None else: (_a_input_token_ids, _b_input_token_ids, _a_token_length, _b_token_length, _a_input_token_mask, _b_input_token_mask, _label_ids) = None, None, None, None, None, None, None features.append( TwinsFeature( a_input_ids=a_input_ids, b_input_ids=b_input_ids, a_input_mask=a_input_mask, b_input_mask=b_input_mask, a_segment_ids=a_segment_ids, b_segment_ids=b_segment_ids, label_ids=label_ids, _a_input_token_ids=_a_input_token_ids, _a_input_token_mask=_a_input_token_mask, _a_token_length=_a_token_length, _b_input_token_ids=_b_input_token_ids, _b_input_token_mask=_b_input_token_mask, _b_token_length=_b_token_length, _label_ids=_label_ids)) return features def decode_to_labels(self, preds, mbs: TwinsMiniBatch): return preds
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/dataflow/twins.py
0.834912
0.333476
twins.py
pypi
"""Tokenization classes for OpenAI GPT.""" from __future__ import (absolute_import, division, print_function, unicode_literals) import json import logging import os import re import sys import unicodedata from io import open import sacremoses as sm from relogic.logickit.tokenizer.tokenization_utils import PreTrainedTokenizer logger = logging.getLogger(__name__) VOCAB_FILES_NAMES = { 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', } PRETRAINED_VOCAB_FILES_MAP = { 'vocab_file': { 'xlm-mlm-en-2048': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-en-2048-vocab.json", 'xlm-mlm-ende-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-ende-1024-vocab.json", 'xlm-mlm-enfr-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enfr-1024-vocab.json", 'xlm-mlm-enro-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enro-1024-vocab.json", 'xlm-mlm-tlm-xnli15-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-tlm-xnli15-1024-vocab.json", 'xlm-mlm-xnli15-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-xnli15-1024-vocab.json", 'xlm-clm-enfr-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-clm-enfr-1024-vocab.json", 'xlm-clm-ende-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-clm-ende-1024-vocab.json", 'xlm-mlm-17-1280': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-17-1280-vocab.json", 'xlm-mlm-100-1280': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-100-1280-vocab.json", }, 'merges_file': { 'xlm-mlm-en-2048': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-en-2048-merges.txt", 'xlm-mlm-ende-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-ende-1024-merges.txt", 'xlm-mlm-enfr-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enfr-1024-merges.txt", 'xlm-mlm-enro-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enro-1024-merges.txt", 'xlm-mlm-tlm-xnli15-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-tlm-xnli15-1024-merges.txt", 'xlm-mlm-xnli15-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-xnli15-1024-merges.txt", 'xlm-clm-enfr-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-enfr-1024-merges.txt", 'xlm-clm-ende-1024': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-ende-1024-merges.txt", 'xlm-mlm-17-1280': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-17-1280-merges.txt", 'xlm-mlm-100-1280': "https://s3.amazonaws.com/models.huggingface.co/bert/xlm-mlm-100-1280-merges.txt", }, } PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = { 'xlm-mlm-en-2048': 512, 'xlm-mlm-ende-1024': 512, 'xlm-mlm-enfr-1024': 512, 'xlm-mlm-enro-1024': 512, 'xlm-mlm-tlm-xnli15-1024': 512, 'xlm-mlm-xnli15-1024': 512, 'xlm-clm-enfr-1024': 512, 'xlm-clm-ende-1024': 512, 'xlm-mlm-17-1280': 512, 'xlm-mlm-100-1280': 512, } PRETRAINED_INIT_CONFIGURATION = { 'xlm-mlm-en-2048': {"do_lowercase_and_remove_accent": True}, 'xlm-mlm-ende-1024': { "do_lowercase_and_remove_accent": True, "id2lang": { "0": "de", "1": "en"}, "lang2id": { "de": 0, "en": 1 }}, 'xlm-mlm-enfr-1024': { "do_lowercase_and_remove_accent": True, "id2lang": { "0": "en", "1": "fr"}, "lang2id": { "en": 0, "fr": 1 }}, 'xlm-mlm-enro-1024': { "do_lowercase_and_remove_accent": True, "id2lang": { "0": "en", "1": "ro"}, "lang2id": { "en": 0, "ro": 1 }}, 'xlm-mlm-tlm-xnli15-1024': { "do_lowercase_and_remove_accent": True, "id2lang": { "0": "ar", "1": "bg", "2": "de", "3": "el", "4": "en", "5": "es", "6": "fr", "7": "hi", "8": "ru", "9": "sw", "10": "th", "11": "tr", "12": "ur", "13": "vi", "14": "zh"}, "lang2id": { "ar": 0, "bg": 1, "de": 2, "el": 3, "en": 4, "es": 5, "fr": 6, "hi": 7, "ru": 8, "sw": 9, "th": 10, "tr": 11, "ur": 12, "vi": 13, "zh": 14 }}, 'xlm-mlm-xnli15-1024': { "do_lowercase_and_remove_accent": True, "id2lang": { "0": "ar", "1": "bg", "2": "de", "3": "el", "4": "en", "5": "es", "6": "fr", "7": "hi", "8": "ru", "9": "sw", "10": "th", "11": "tr", "12": "ur", "13": "vi", "14": "zh"}, "lang2id": { "ar": 0, "bg": 1, "de": 2, "el": 3, "en": 4, "es": 5, "fr": 6, "hi": 7, "ru": 8, "sw": 9, "th": 10, "tr": 11, "ur": 12, "vi": 13, "zh": 14 }}, 'xlm-clm-enfr-1024': { "do_lowercase_and_remove_accent": True, "id2lang": { "0": "en", "1": "fr"}, "lang2id": { "en": 0, "fr": 1 }}, 'xlm-clm-ende-1024': { "do_lowercase_and_remove_accent": True, "id2lang": { "0": "de", "1": "en"}, "lang2id": { "de": 0, "en": 1 }}, 'xlm-mlm-17-1280': {"do_lowercase_and_remove_accent": False, "id2lang": { "0": "ar", "1": "de", "2": "en", "3": "es", "4": "fr", "5": "hi", "6": "it", "7": "ja", "8": "ko", "9": "nl", "10": "pl", "11": "pt", "12": "ru", "13": "sv", "14": "tr", "15": "vi", "16": "zh" }, "lang2id": { "ar": 0, "de": 1, "en": 2, "es": 3, "fr": 4, "hi": 5, "it": 6, "ja": 7, "ko": 8, "nl": 9, "pl": 10, "pt": 11, "ru": 12, "sv": 13, "tr": 14, "vi": 15, "zh": 16}}, 'xlm-mlm-100-1280': {"do_lowercase_and_remove_accent": False, "id2lang": { "0": "af", "1": "als", "2": "am", "3": "an", "4": "ang", "5": "ar", "6": "arz", "7": "ast", "8": "az", "9": "bar", "10": "be", "11": "bg", "12": "bn", "13": "br", "14": "bs", "15": "ca", "16": "ceb", "17": "ckb", "18": "cs", "19": "cy", "20": "da", "21": "de", "22": "el", "23": "en", "24": "eo", "25": "es", "26": "et", "27": "eu", "28": "fa", "29": "fi", "30": "fr", "31": "fy", "32": "ga", "33": "gan", "34": "gl", "35": "gu", "36": "he", "37": "hi", "38": "hr", "39": "hu", "40": "hy", "41": "ia", "42": "id", "43": "is", "44": "it", "45": "ja", "46": "jv", "47": "ka", "48": "kk", "49": "kn", "50": "ko", "51": "ku", "52": "la", "53": "lb", "54": "lt", "55": "lv", "56": "mk", "57": "ml", "58": "mn", "59": "mr", "60": "ms", "61": "my", "62": "nds", "63": "ne", "64": "nl", "65": "nn", "66": "no", "67": "oc", "68": "pl", "69": "pt", "70": "ro", "71": "ru", "72": "scn", "73": "sco", "74": "sh", "75": "si", "76": "simple", "77": "sk", "78": "sl", "79": "sq", "80": "sr", "81": "sv", "82": "sw", "83": "ta", "84": "te", "85": "th", "86": "tl", "87": "tr", "88": "tt", "89": "uk", "90": "ur", "91": "uz", "92": "vi", "93": "war", "94": "wuu", "95": "yi", "96": "zh", "97": "zh_classical", "98": "zh_min_nan", "99": "zh_yue" }, "lang2id": { "af": 0, "als": 1, "am": 2, "an": 3, "ang": 4, "ar": 5, "arz": 6, "ast": 7, "az": 8, "bar": 9, "be": 10, "bg": 11, "bn": 12, "br": 13, "bs": 14, "ca": 15, "ceb": 16, "ckb": 17, "cs": 18, "cy": 19, "da": 20, "de": 21, "el": 22, "en": 23, "eo": 24, "es": 25, "et": 26, "eu": 27, "fa": 28, "fi": 29, "fr": 30, "fy": 31, "ga": 32, "gan": 33, "gl": 34, "gu": 35, "he": 36, "hi": 37, "hr": 38, "hu": 39, "hy": 40, "ia": 41, "id": 42, "is": 43, "it": 44, "ja": 45, "jv": 46, "ka": 47, "kk": 48, "kn": 49, "ko": 50, "ku": 51, "la": 52, "lb": 53, "lt": 54, "lv": 55, "mk": 56, "ml": 57, "mn": 58, "mr": 59, "ms": 60, "my": 61, "nds": 62, "ne": 63, "nl": 64, "nn": 65, "no": 66, "oc": 67, "pl": 68, "pt": 69, "ro": 70, "ru": 71, "scn": 72, "sco": 73, "sh": 74, "si": 75, "simple": 76, "sk": 77, "sl": 78, "sq": 79, "sr": 80, "sv": 81, "sw": 82, "ta": 83, "te": 84, "th": 85, "tl": 86, "tr": 87, "tt": 88, "uk": 89, "ur": 90, "uz": 91, "vi": 92, "war": 93, "wuu": 94, "yi": 95, "zh": 96, "zh_classical": 97, "zh_min_nan": 98, "zh_yue": 99 }}, } def get_pairs(word): """ Return set of symbol pairs in a word. word is represented as tuple of symbols (symbols being variable-length strings) """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char return pairs def lowercase_and_remove_accent(text): """ Lowercase and strips accents from a piece of text based on https://github.com/facebookresearch/XLM/blob/master/tools/lowercase_and_remove_accent.py """ text = ' '.join(text) text = text.lower() text = unicodedata.normalize("NFD", text) output = [] for char in text: cat = unicodedata.category(char) if cat == "Mn": continue output.append(char) return "".join(output).lower().split(' ') def replace_unicode_punct(text): ''' Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/replace-unicode-punctuation.perl ''' text = text.replace(',', ',') text = re.sub(r'。\s*', '. ', text) text = text.replace('、', ',') text = text.replace('”', '"') text = text.replace('“', '"') text = text.replace('∶', ':') text = text.replace(':', ':') text = text.replace('?', '?') text = text.replace('《', '"') text = text.replace('》', '"') text = text.replace(')', ')') text = text.replace('!', '!') text = text.replace('(', '(') text = text.replace(';', ';') text = text.replace('1', '"') text = text.replace('」', '"') text = text.replace('「', '"') text = text.replace('0', '0') text = text.replace('3', '3') text = text.replace('2', '2') text = text.replace('5', '5') text = text.replace('6', '6') text = text.replace('9', '9') text = text.replace('7', '7') text = text.replace('8', '8') text = text.replace('4', '4') text = re.sub(r'.\s*', '. ', text) text = text.replace('~', '~') text = text.replace('’', '\'') text = text.replace('…', '...') text = text.replace('━', '-') text = text.replace('〈', '<') text = text.replace('〉', '>') text = text.replace('【', '[') text = text.replace('】', ']') text = text.replace('%', '%') return text def remove_non_printing_char(text): ''' Port of https://github.com/moses-smt/mosesdecoder/blob/master/scripts/tokenizer/remove-non-printing-char.perl ''' output = [] for char in text: cat = unicodedata.category(char) if cat.startswith('C'): continue output.append(char) return "".join(output) def romanian_preprocessing(text): '''Sennrich's WMT16 scripts for Romanian preprocessing, used by model `xlm-mlm-enro-1024`''' # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/normalise-romanian.py text = text.replace("\u015e", "\u0218").replace("\u015f", "\u0219") text = text.replace("\u0162", "\u021a").replace("\u0163", "\u021b") # https://github.com/rsennrich/wmt16-scripts/blob/master/preprocess/remove-diacritics.py text = text.replace("\u0218", "S").replace("\u0219", "s") #s-comma text = text.replace("\u021a", "T").replace("\u021b", "t") #t-comma text = text.replace("\u0102", "A").replace("\u0103", "a") text = text.replace("\u00C2", "A").replace("\u00E2", "a") text = text.replace("\u00CE", "I").replace("\u00EE", "i") return text class XLMTokenizer(PreTrainedTokenizer): """ BPE tokenizer for XLM - Moses preprocessing & tokenization for most supported languages - Language specific tokenization for Chinese (Jieba), Japanese (KyTea) and Thai (PyThaiNLP) - (optionally) lower case & normalize all inputs text - argument ``special_tokens`` and function ``set_special_tokens``, can be used to add additional symbols \ (ex: "__classify__") to a vocabulary - `lang2id` attribute maps the languages supported by the model with their ids if provided (automatically set for pretrained vocabularies) - `id2lang` attributes does reverse mapping if provided (automatically set for pretrained vocabularies) - `do_lowercase_and_remove_accent` controle lower casing and accent (automatically set for pretrained vocabularies) """ vocab_files_names = VOCAB_FILES_NAMES pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self, vocab_file, merges_file, unk_token="<unk>", bos_token="<s>", sep_token="</s>", pad_token="<pad>", cls_token="</s>", mask_token="<special1>", additional_special_tokens=["<special0>", "<special1>", "<special2>", "<special3>", "<special4>", "<special5>", "<special6>", "<special7>", "<special8>", "<special9>"], lang2id=None, id2lang=None, do_lowercase_and_remove_accent=True, **kwargs): super(XLMTokenizer, self).__init__(unk_token=unk_token, bos_token=bos_token, sep_token=sep_token, pad_token=pad_token, cls_token=cls_token, mask_token=mask_token, additional_special_tokens=additional_special_tokens, **kwargs) # cache of sm.MosesPunctNormalizer instance self.cache_moses_punct_normalizer = dict() # cache of sm.MosesTokenizer instance self.cache_moses_tokenizer = dict() self.lang_with_custom_tokenizer = set(['zh', 'th', 'ja']) # True for current supported model (v1.2.0), False for XLM-17 & 100 self.do_lowercase_and_remove_accent = do_lowercase_and_remove_accent self.lang2id = lang2id self.id2lang = id2lang if lang2id is not None and id2lang is not None: assert len(lang2id) == len(id2lang) self.ja_word_tokenizer = None self.zh_word_tokenizer = None self.encoder = json.load(open(vocab_file, encoding="utf-8")) self.decoder = {v:k for k,v in self.encoder.items()} merges = open(merges_file, encoding='utf-8').read().split('\n')[:-1] merges = [tuple(merge.split()[:2]) for merge in merges] self.bpe_ranks = dict(zip(merges, range(len(merges)))) self.cache = {} def moses_punct_norm(self, text, lang): if lang not in self.cache_moses_punct_normalizer: punct_normalizer = sm.MosesPunctNormalizer(lang=lang) self.cache_moses_punct_normalizer[lang] = punct_normalizer else: punct_normalizer = self.cache_moses_punct_normalizer[lang] return punct_normalizer.normalize(text) def moses_tokenize(self, text, lang): if lang not in self.cache_moses_tokenizer: moses_tokenizer = sm.MosesTokenizer(lang=lang) self.cache_moses_tokenizer[lang] = moses_tokenizer else: moses_tokenizer = self.cache_moses_tokenizer[lang] return moses_tokenizer.tokenize(text, return_str=False, escape=False) def moses_pipeline(self, text, lang): text = replace_unicode_punct(text) text = self.moses_punct_norm(text, lang) text = remove_non_printing_char(text) return text def ja_tokenize(self, text): if self.ja_word_tokenizer is None: try: import Mykytea self.ja_word_tokenizer = Mykytea.Mykytea('-model %s/local/share/kytea/model.bin' % os.path.expanduser('~')) except (AttributeError, ImportError) as e: logger.error("Make sure you install KyTea (https://github.com/neubig/kytea) and it's python wrapper (https://github.com/chezou/Mykytea-python) with the following steps") logger.error("1. git clone git@github.com:neubig/kytea.git && cd kytea") logger.error("2. autoreconf -i") logger.error("3. ./configure --prefix=$HOME/local") logger.error("4. make && make install") logger.error("5. pip install kytea") raise e return list(self.ja_word_tokenizer.getWS(text)) @property def vocab_size(self): return len(self.encoder) def bpe(self, token): word = tuple(token[:-1]) + (token[-1] + '</w>',) if token in self.cache: return self.cache[token] pairs = get_pairs(word) if not pairs: return token+'</w>' while True: bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float('inf'))) if bigram not in self.bpe_ranks: break first, second = bigram new_word = [] i = 0 while i < len(word): try: j = word.index(first, i) new_word.extend(word[i:j]) i = j except: new_word.extend(word[i:]) break if word[i] == first and i < len(word)-1 and word[i+1] == second: new_word.append(first+second) i += 2 else: new_word.append(word[i]) i += 1 new_word = tuple(new_word) word = new_word if len(word) == 1: break else: pairs = get_pairs(word) word = ' '.join(word) if word == '\n </w>': word = '\n</w>' self.cache[token] = word return word def _tokenize(self, text, lang='en', bypass_tokenizer=False): """ Tokenize a string given language code. For Chinese, Japanese and Thai, we use a language specific tokenizerself. Otherwise, we use Moses. Details of tokenization: - [sacremoses](https://github.com/alvations/sacremoses): port of Moses - Install with `pip install sacremoses` - [pythainlp](https://github.com/PyThaiNLP/pythainlp): Thai tokenizer - Install with `pip install pythainlp` - [kytea](https://github.com/chezou/Mykytea-python): Japanese tokenizer, wrapper of [KyTea](https://github.com/neubig/kytea) - Install with the following steps: ``` git clone git@github.com:neubig/kytea.git && cd kytea autoreconf -i ./configure --prefix=$HOME/local make && make install pip install kytea ``` - [jieba](https://github.com/fxsjy/jieba): Chinese tokenizer * - Install with `pip install jieba` \* The original XLM used [Stanford Segmenter](https://nlp.stanford.edu/software/stanford-segmenter-2018-10-16.zip). However, the wrapper (`nltk.tokenize.stanford_segmenter`) is slow due to JVM overhead, and it will be deprecated. Jieba is a lot faster and pip-installable. Note there is some mismatch with the Stanford Segmenter. It should be fine if you fine-tune the model with Chinese supervisionself. If you want the same exact behaviour, use the original XLM [preprocessing script](https://github.com/facebookresearch/XLM/tree/master/tools) to tokenize the sentence externally, and set `bypass_tokenizer=True` to bypass the tokenizer. Args: - lang: ISO language code (default = 'en') (string). Languages should belong of the model supported languages. However, we don't enforce it. - bypass_tokenizer: Allow users to preprocess and tokenize the sentences externally (default = False) (bool). If True, we only apply BPE. Returns: List of tokens. """ if lang and self.lang2id and lang not in self.lang2id: logger.error("Supplied language code not found in lang2id mapping. Please check that your language is supported by the loaded pretrained model.") if bypass_tokenizer: text = text.split() elif lang not in self.lang_with_custom_tokenizer: text = self.moses_pipeline(text, lang=lang) # TODO: make sure we are using `xlm-mlm-enro-1024`, since XLM-100 doesn't have this step if lang == 'ro': text = romanian_preprocessing(text) text = self.moses_tokenize(text, lang=lang) elif lang == 'th': text = self.moses_pipeline(text, lang=lang) try: if 'pythainlp' not in sys.modules: from pythainlp.tokenize import word_tokenize as th_word_tokenize else: th_word_tokenize = sys.modules['pythainlp'].word_tokenize except (AttributeError, ImportError) as e: logger.error("Make sure you install PyThaiNLP (https://github.com/PyThaiNLP/pythainlp) with the following steps") logger.error("1. pip install pythainlp") raise e text = th_word_tokenize(text) elif lang == 'zh': try: if 'jieba' not in sys.modules: import jieba else: jieba = sys.modules['jieba'] except (AttributeError, ImportError) as e: logger.error("Make sure you install Jieba (https://github.com/fxsjy/jieba) with the following steps") logger.error("1. pip install jieba") raise e text = ' '.join(jieba.cut(text)) text = self.moses_pipeline(text, lang=lang) text = text.split() elif lang == 'ja': text = self.moses_pipeline(text, lang=lang) text = self.ja_tokenize(text) else: raise ValueError('It should not reach here') if self.do_lowercase_and_remove_accent and not bypass_tokenizer: text = lowercase_and_remove_accent(text) split_tokens = [] for token in text: if token: split_tokens.extend([t for t in self.bpe(token).split(' ')]) return split_tokens def _convert_token_to_id(self, token): """ Converts a token (str/unicode) in an id using the vocab. """ return self.encoder.get(token, self.encoder.get(self.unk_token)) def _convert_id_to_token(self, index): """Converts an index (integer) in a token (string/unicode) using the vocab.""" return self.decoder.get(index, self.unk_token) def convert_tokens_to_string(self, tokens): """ Converts a sequence of tokens (string) in a single string. """ out_string = ''.join(tokens).replace('</w>', ' ').strip() return out_string def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None): """ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoBERTa sequence has the following format: single sequence: <s> X </s> pair of sequences: <s> A </s></s> B </s> """ if token_ids_1 is None: return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] sep = [self.sep_token_id] cls = [self.cls_token_id] return cls + token_ids_0 + sep + token_ids_1 + sep def get_special_tokens_mask(self, token_ids_0, token_ids_1=None, already_has_special_tokens=False): """ Retrieves sequence ids from a token list that has no special tokens added. This method is called when adding special tokens using the tokenizer ``prepare_for_model`` or ``encode_plus`` methods. Args: token_ids_0: list of ids (must not contain special tokens) token_ids_1: Optional list of ids (must not contain special tokens), necessary when fetching sequence ids for sequence pairs already_has_special_tokens: (default False) Set to True if the token list is already formated with special tokens for the model Returns: A list of integers in the range [0, 1]: 0 for a special token, 1 for a sequence token. """ if already_has_special_tokens: if token_ids_1 is not None: raise ValueError("You should not supply a second sequence if the provided sequence of " "ids is already formated with special tokens for the model.") return list(map(lambda x: 1 if x in [self.sep_token_id, self.cls_token_id] else 0, token_ids_0)) if token_ids_1 is not None: return [1] + ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1] return [1] + ([0] * len(token_ids_0)) + [1] def create_token_type_ids_from_sequences(self, token_ids_0, token_ids_1=None): """ Creates a mask from the two sequences passed to be used in a sequence-pair classification task. An XLM sequence pair mask has the following format: 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 | first sequence | second sequence if token_ids_1 is None, only returns the first portion of the mask (0's). """ sep = [self.sep_token_id] cls = [self.cls_token_id] if token_ids_1 is None: return len(cls + token_ids_0 + sep) * [0] return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1] def save_vocabulary(self, save_directory): """Save the tokenizer vocabulary and merge files to a directory.""" if not os.path.isdir(save_directory): logger.error("Vocabulary path ({}) should be a directory".format(save_directory)) return vocab_file = os.path.join(save_directory, VOCAB_FILES_NAMES['vocab_file']) merge_file = os.path.join(save_directory, VOCAB_FILES_NAMES['merges_file']) with open(vocab_file, 'w', encoding='utf-8') as f: f.write(json.dumps(self.encoder, ensure_ascii=False)) index = 0 with open(merge_file, "w", encoding="utf-8") as writer: for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]): if index != token_index: logger.warning("Saving vocabulary to {}: BPE merge indices are not consecutive." " Please check that the tokenizer is not corrupted!".format(merge_file)) index = token_index writer.write(' '.join(bpe_tokens) + u'\n') index += 1 return vocab_file, merge_file
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/tokenizer/tokenization_xlm.py
0.479747
0.195249
tokenization_xlm.py
pypi
import logging import collections from relogic.logickit.tokenizer.tokenization import BasicTokenizer, load_vocab from relogic.utils.file_utils import cached_path logger = logging.getLogger(__name__) PRETRAINED_VECTOR_ARCHIVE_MAP = { 'wiki-news-300d-1M': "https://github.com/Impavidity/relogic/raw/master/relogic/logickit/vocabs/wiki-news-300d-1M.txt", 'aligned-fasttext-ar': "https://github.com/Impavidity/relogic/raw/master/relogic/logickit/vocabs/aligned-fasttext-ar.txt", 'aligned-fasttext-bn': "https://github.com/Impavidity/relogic/raw/master/relogic/logickit/vocabs/aligned-fasttext-bn.txt", 'aligned-fasttext-fr': "https://github.com/Impavidity/relogic/raw/master/relogic/logickit/vocabs/aligned-fasttext-fr.txt", 'aligned-fasttext-hi': "https://github.com/Impavidity/relogic/raw/master/relogic/logickit/vocabs/aligned-fasttext-hi.txt", 'aligned-fasttext-zh': "https://github.com/Impavidity/relogic/raw/master/relogic/logickit/vocabs/aligned-fasttext-zh.txt" } class FasttextTokenizer(object): """ """ def __init__(self, vocab_file, do_lower_case=True): self.vocab = load_vocab(vocab_file) self.ids_to_tokens = collections.OrderedDict( [(ids, tok) for tok, ids in self.vocab.items()]) self.basic_tokenizer = BasicTokenizer(do_lower_case=do_lower_case) def tokenize(self, text): # tokens, _ = self.basic_tokenizer.tokenize(text) tokens = text.split(" ") return tokens def convert_tokens_to_ids(self, tokens): """Converts a sequence of tokens into ids using the vocab.""" ids = [] for token in tokens: ids.append(self.vocab.get(token, 0)) return ids def convert_ids_to_tokens(self, ids): """Converts a sequence of ids in fasttext tokens using the vocab.""" tokens = [] for i in ids: tokens.append(self.ids_to_tokens[i]) return tokens @classmethod def from_pretrained(cls, pretrained_model_name_or_path, cache_dir=None, *inputs, **kwargs): if pretrained_model_name_or_path in PRETRAINED_VECTOR_ARCHIVE_MAP: vocab_file = PRETRAINED_VECTOR_ARCHIVE_MAP[pretrained_model_name_or_path] else: vocab_file = pretrained_model_name_or_path try: resolved_vocab_file = cached_path(vocab_file, cache_dir=cache_dir) except EnvironmentError: logger.error( "Model name '{}' was not found in model name list ({}). " "We assumed '{}' was a path or url but couldn't find any file " "associated to this path or url.".format( pretrained_model_name_or_path, ', '.join(PRETRAINED_VECTOR_ARCHIVE_MAP.keys()), vocab_file)) return None if resolved_vocab_file == vocab_file: logger.info("loading vocabulary file {}".format(vocab_file)) else: logger.info("loading vocabulary file {} from cache at {}".format( vocab_file, resolved_vocab_file)) tokenizer = cls(resolved_vocab_file, *inputs, **kwargs) return tokenizer
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/tokenizer/fasttext_tokenization.py
0.574395
0.185301
fasttext_tokenization.py
pypi
import torch.nn as nn import torch from relogic.logickit.modules.adversarial.discriminator import LR import numpy as np from relogic.logickit.base.configuration import AdversarialConfigs class Adversarial(nn.Module): def __init__(self, config: AdversarialConfigs): super().__init__() self.config = config if self.config.discriminator_type == "LR": self.discriminator = LR(config=config) else: NotImplementedError() print("Using Adversarial {}".format(config.type)) if config.type == "WGAN": pass if config.type == "GAN" or config.type == "GR": # Let make it adam for now. self.optim = torch.optim.Adam(self.discriminator.parameters(), lr=self.config.discriminator_lr) self.real = 1 self.fake = 0 if config.soft_label and config.type == "GAN": self.real = np.random.uniform(0.7, 1.0) self.fake = np.random.uniform(0.0, 0.3) print("The soft label is {} and {}".format(self.real, self.fake)) if config.type == "GR": self.criterion = nn.CrossEntropyLoss() else: self.criterion = nn.BCEWithLogitsLoss() def loss(self, input, label): output = self.discriminator(features=input) assert (output.dim() == 2) if self.config.type == "WGAN": loss = torch.mean(output) else: if self.config.type == "GAN": label = torch.empty(*output.size()).fill_(label).type_as(output) elif self.config.type == "GR": label = torch.empty(output.size(0)).fill_(label).type_as(output).long() loss = self.criterion(output, label) return output, loss def update(self, real_in, fake_in, real_id, fake_id): self.optim.zero_grad() if self.config.type == "GAN": real_id, fake_id = self.real, self.fake real_output, real_loss = self.loss(real_in, real_id) fake_output, fake_loss = self.loss(fake_in, fake_id) if self.config.type in ["GR", "GAN"]: loss = 0.5 * (real_loss + fake_loss) else: loss = fake_loss - real_loss loss.backward() self.optim.step() real_acc, fake_acc = 0, 0 if self.config.type in ["GR", "GAN"]: real_acc = self.accuracy(real_output, real_id) fake_acc = self.accuracy(fake_output, fake_id) return real_loss.item(), fake_loss.item(), real_acc, fake_acc def accuracy(self, output, label): if self.config.type == "GAN": if label > 0.5: preds = (torch.sigmoid(output) >= 0.5).long().cpu() else: preds = (torch.sigmoid(output) < 0.5).long().cpu() label = 1 labels = torch.LongTensor([label]) labels = labels.expand(*preds.size()) n_correct = preds.eq(labels).sum().item() acc = 1.0 * n_correct / output.size(0) return acc def gen_loss(self, real_in, fake_in, real_id, fake_id): """Functions to calculate loss to update the Generator. The basic idea is to minimize the loss that can confuse the Discriminator to make a wrong decision.""" if self.config.type == "GAN": _, loss = self.loss(fake_in, self.real) loss = self.config.scale * loss elif self.config.type == "WGAN": # clamp parameters to a cube for p in self.discriminator.parameters(): p.data.clamp_(self.config.clip_lower, self.config.clip_upper) _, loss = self.loss(fake_in, self.real) loss = -self.config.scale * loss else: raise NotImplementedError() return loss def forward(self, *input, **kwargs): raise NotImplementedError()
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/inference/adversarial.py
0.862858
0.286294
adversarial.py
pypi
from relogic.logickit.tasks.task import Task from relogic.logickit.dataset.labeled_data_loader import LabeledDataLoader from relogic.logickit.modules.matching_module import MatchingModule from relogic.logickit.modules.classification_module import ClassificationModule from relogic.logickit.modules.representation_module import RepresentationModule from relogic.logickit.modules.rel_extraction_module import RelExtractionModule from relogic.logickit.modules.agg_matching_module import AggMatchingModule from relogic.logickit.modules.ir_matching import IRMatchingModule from relogic.logickit.scorer.ranking_scorer import RecallScorer, CartesianMatchingRecallScorer, RetrievalScorer from relogic.logickit.scorer.classification_scorers import RelationF1Scorer, MultiClassAccuracyScorer from relogic.logickit.modules.sam_cnn import SamCNN from relogic.logickit.base.constants import IR_TASK, PAIRWISE_TASK, SINGLETON, ENTITY_TYPE_CLASSIFICATION, DOCIR_TASK, IR_SAMCNN_TASK class Classification(Task): def __init__(self, config, name, tokenizer=None): super(Classification, self).__init__( config, name, LabeledDataLoader(config, name, tokenizer)) self.n_classes = len(set(self.loader.label_mapping.values())) def get_module(self): if self.name in ["matching"]: return MatchingModule(self.config, self.name, self.n_classes) elif self.name in [IR_SAMCNN_TASK]: return SamCNN(self.config, self.name, self.n_classes) elif self.name.startswith(IR_TASK): if self.config.word_level_interaction: return IRMatchingModule(self.config, self.name, self.n_classes) else: return MatchingModule(self.config, self.name, self.n_classes) elif self.name.startswith(DOCIR_TASK): return AggMatchingModule(self.config, self.name, self.n_classes) elif self.name in ["pair_matching", PAIRWISE_TASK]: return RepresentationModule(self.config, self.name, self.config.repr_size) elif self.name in ["rel_extraction", SINGLETON]: return RelExtractionModule(self.config, self.name, self.n_classes) elif self.name in [ENTITY_TYPE_CLASSIFICATION]: return ClassificationModule(self.config, self.name, self.n_classes) def get_scorer(self, dump_to_file=None): if self.name in ["matching"]: return RecallScorer(self.loader.label_mapping, topk=self.config.topk, dump_to_file=dump_to_file) elif self.name.startswith(IR_TASK) or self.name.startswith(DOCIR_TASK): return RetrievalScorer( self.loader.label_mapping, qrels_file_path=self.config.qrels_file_path if isinstance(self.config.qrels_file_path, str) else self.config.tasks[self.name]["qrels_file_path"], dump_to_file=dump_to_file, regression=self.config.regression) elif self.name in ["rel_extraction"]: return RelationF1Scorer(self.loader.label_mapping, dump_to_file=dump_to_file) elif self.name in ["pair_matching", PAIRWISE_TASK]: return CartesianMatchingRecallScorer( topk=self.config.topk, qrels_file_path=self.config.qrels_file_path if isinstance(self.config.qrels_file_path, str) else self.config.tasks[self.name]["qrels_file_path"], dump_to_file=dump_to_file) elif self.name in [ENTITY_TYPE_CLASSIFICATION]: return MultiClassAccuracyScorer(self.loader.label_mapping, dump_to_file=dump_to_file, dataflow=self.loader.dataflow)
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/tasks/classification.py
0.650689
0.183027
classification.py
pypi
from relogic.logickit.scorer.scorer import Scorer import numpy as np class DepParsingScorer(Scorer): def __init__(self, label_mapping, dump_to_file=None): super().__init__() self.labeled_correct = 0.0 self.unlabeled_correct = 0.0 self.exact_labeled_correct = 0.0 self.exact_unlabeled_correct = 0.0 self.total_words = 0.0 self.total_sentences = 0.0 def _get_results(self): """ Returns ------- The accumulated metrics as a dictionary. """ unlabeled_attachment_score = 0.0 labeled_attachment_score = 0.0 unlabeled_exact_match = 0.0 labeled_exact_match = 0.0 if self.total_words > 0.0: unlabeled_attachment_score = float(self.unlabeled_correct) / float(self.total_words) labeled_attachment_score = float(self.labeled_correct) / float(self.total_words) if self.total_sentences > 0: unlabeled_exact_match = float(self.exact_unlabeled_correct) / float( self.total_sentences ) labeled_exact_match = float(self.exact_labeled_correct) / float(self.total_sentences) return [ ("total_sents", self.total_sentences), ("total_words", self.total_words), ("UAS", unlabeled_attachment_score * 100.0), ("LAS", labeled_attachment_score * 100.0), ("UEM", unlabeled_exact_match * 100.0), ("LEM", labeled_exact_match * 100.0), ] def update(self, mb, predictions, loss, extra_args): predicted_indices = predictions["heads"] predicted_labels = predictions["head_tags"] # We know there will be mask here masks = predictions["mask"] predicted_indices, predicted_labels, masks = self.unwrap_to_tensors(predicted_indices, predicted_labels, masks) for each_predicted_indices, each_predicted_labels, example, mask in zip(predicted_indices, predicted_labels, mb.examples, masks): gold_indices = np.array(example.arcs_ids[1:-1])[np.array(example.is_head[1:-1]) == 1] gold_label_ids = np.array(example.label_ids[1:-1])[np.array(example.is_head[1:-1]) == 1] each_predicted_indices = each_predicted_indices[1:][mask[1:] == 1].numpy() each_predicted_labels = each_predicted_labels[1:][mask[1:] == 1].numpy() assert(len(gold_indices) == len(each_predicted_indices)) correct_indices = (gold_indices == each_predicted_indices) correct_labels = (gold_label_ids == each_predicted_labels) correct_labels_and_indices = np.logical_and(correct_indices, correct_labels) exact_unlabeled_correct = (correct_indices.sum() == len(correct_indices)) exact_labeled_correct = (correct_labels_and_indices.sum() == len(correct_indices)) self.unlabeled_correct += correct_indices.sum() self.exact_unlabeled_correct += exact_unlabeled_correct self.labeled_correct += correct_labels_and_indices.sum() self.exact_labeled_correct += exact_labeled_correct self.total_sentences += 1 self.total_words += len(correct_indices) def get_loss(self): return 0
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/scorer/dep_parsing_scorer.py
0.724968
0.355285
dep_parsing_scorer.py
pypi
from relogic.logickit.scorer.scorer import Scorer from itertools import groupby import collections import json from relogic.logickit.scripts import squad_eval import os RawResult = collections.namedtuple("RawResult", ["start_logits", "end_logits"]) class SpanExtractionScorer(Scorer): def __init__(self, dataset, gold_answer_file, null_score_diff_threshold, dump_to_file=None): super(SpanExtractionScorer, self).__init__() self.guid_to_example = {} self.dataset_name = dataset # dataset_json = json.load(open("data/preprocessed_data/{}_dev.json".format(dataset))) dataset_json = json.load(open(gold_answer_file)) self.dataset = dataset_json['data'] self.null_score_diff_threshold = null_score_diff_threshold if dump_to_file: self.dump_to_file_path = os.path.join(dump_to_file["output_dir"], dump_to_file["task_name"] + "_dump.json") self.dump_to_null_odds_path = os.path.join(dump_to_file["output_dir"], dump_to_file["task_name"] + "_null_odds.json") self.dump_to_span_scores_path = os.path.join(dump_to_file["output_dir"], dump_to_file["task_name"] + "_span_scores.json") def update(self, mb, predictions, loss, extra_args): # Basically one example can map several features # How to map it back ? # 1. Build guid to example mapping # 2. Map the input_feature to example using guid for example in mb.examples: self.guid_to_example[example.guid] = example pair_group = groupby(zip(mb.input_features, predictions[0], predictions[1]), key=lambda pair: pair[0].guid) pair_group = {k: list(v) for k, v in pair_group} # {guid: list of pairs} for guid in pair_group.keys(): raw_features = [] raw_results = [] for item in pair_group[guid]: raw_features.append(item[0]) raw_results.append(RawResult(start_logits=item[1], end_logits=item[2])) self.guid_to_example[guid].write_predictions( raw_features=raw_features, raw_results=raw_results, n_best_size=20, with_negative=mb.task_name in ["squad20"]) def _get_results(self): assert self.dump_to_file_path is not None if self.dump_to_file_path: self.dump_to_file_handler = open(self.dump_to_file_path, 'w') self.dump_to_null_odds_handler = open(self.dump_to_null_odds_path, 'w') self.dump_to_span_scores_handler = open(self.dump_to_span_scores_path, 'w') prediction_json = {} for example in self.guid_to_example.values(): prediction_json[example.guid] = example.prediction json.dump(prediction_json, self.dump_to_file_path) if self.dataset_name in ["squad20"]: scores_diff_json = {} for example in self.guid_to_example.values(): scores_diff_json[example.guid] = example.scores_diff json.dump(scores_diff_json, self.dump_to_null_odds_handler) span_scores_json = {} for example in self.guid_to_example.values(): span_scores_json[example.guid] = example.span_score json.dump(span_scores_json, self.dump_to_span_scores_handler) return squad_eval(self.dataset_name)(self.dataset, prediction_json, self.null_score_diff_threshold) def get_loss(self): return 0
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/scorer/span_extraction_scorer.py
0.423339
0.197309
span_extraction_scorer.py
pypi
from __future__ import print_function from collections import Counter import string import re import argparse import json import sys def normalize_answer(s): """Lower text and remove punctuation, articles and extra whitespace.""" def remove_articles(text): return re.sub(r'\b(a|an|the)\b', ' ', text) def white_space_fix(text): return ' '.join(text.split()) def remove_punc(text): exclude = set(string.punctuation) return ''.join(ch for ch in text if ch not in exclude) def lower(text): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(s)))) def f1_score(prediction, ground_truth): prediction_tokens = normalize_answer(prediction).split() ground_truth_tokens = normalize_answer(ground_truth).split() common = Counter(prediction_tokens) & Counter(ground_truth_tokens) num_same = sum(common.values()) if num_same == 0: return 0 precision = 1.0 * num_same / len(prediction_tokens) recall = 1.0 * num_same / len(ground_truth_tokens) f1 = (2 * precision * recall) / (precision + recall) return f1 def exact_match_score(prediction, ground_truth): return (normalize_answer(prediction) == normalize_answer(ground_truth)) def metric_max_over_ground_truths(metric_fn, prediction, ground_truths): scores_for_ground_truths = [] for ground_truth in ground_truths: score = metric_fn(prediction, ground_truth) scores_for_ground_truths.append(score) return max(scores_for_ground_truths) def evaluate(dataset, predictions, na_prob_thresh=None): f1 = exact_match = total = 0 for article in dataset: for paragraph in article['paragraphs']: for qa in paragraph['qas']: total += 1 if qa['id'] not in predictions: message = 'Unanswered question ' + qa['id'] + \ ' will receive score 0.' print(message, file=sys.stderr) continue ground_truths = list(map(lambda x: x['text'], qa['answers'])) prediction = predictions[qa['id']] exact_match += metric_max_over_ground_truths(exact_match_score, prediction, ground_truths) f1 += metric_max_over_ground_truths(f1_score, prediction, ground_truths) exact_match = 100.0 * exact_match / total f1 = 100.0 * f1 / total return [('exact_match', exact_match), ('f1', f1)] if __name__ == '__main__': expected_version = '1.1' parser = argparse.ArgumentParser( description='Evaluation for SQuAD ' + expected_version) parser.add_argument('dataset_file', help='Dataset file') parser.add_argument('prediction_file', help='Prediction File') args = parser.parse_args() with open(args.dataset_file) as dataset_file: dataset_json = json.load(dataset_file) if (dataset_json['version'] != expected_version): print( 'Evaluation expects v-' + expected_version + ', but got dataset with v-' + dataset_json['version'], file=sys.stderr) dataset = dataset_json['data'] with open(args.prediction_file) as prediction_file: predictions = json.load(prediction_file) print(json.dumps(evaluate(dataset, predictions)))
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/scripts/squad11_eval.py
0.595963
0.408513
squad11_eval.py
pypi
from relogic.logickit.utils import get_span_labels import argparse from itertools import groupby import json from tqdm import tqdm import spacy from spacy.tokens import Doc class WhitespaceTokenizer(object): def __init__(self, vocab): self.vocab = vocab def __call__(self, text): words = text.split(' ') # All tokens 'own' a subsequent space character in this tokenizer spaces = [True] * len(words) return Doc(self.vocab, words=words, spaces=spaces) nlp = spacy.load("en_core_web_sm", disable=["parser", "ner"]) nlp.tokenizer = WhitespaceTokenizer(nlp.vocab) def main(json_file, dump_file): examples = [] with open(json_file) as fin: for line in fin: example = json.loads(line) example["key"] = " ".join(example["tokens"]) examples.append(example) agg_examples = segmentation(examples) with open(dump_file, 'w') as fout: for example in agg_examples: fout.write(json.dumps(example) + "\n") def segmentation(examples): groups = groupby(examples, key=lambda x: x["key"]) agg_examples = [] for group in tqdm(groups): text = group[0].split() segment_label = ["I"] * len(text) segment_label[0] = "B" sent = nlp(" ".join(text)) for idx, t in enumerate(sent): if t.pos_ == "ADP" or t.pos_ == "PUNCT": segment_label[idx] = 'B' if idx + 1 < len(text): segment_label[idx + 1] = 'B' for sub_item in group[1]: spans, _ = get_span_labels(sub_item["labels"], ignore_label=[]) for span in spans: segment_label[span[0]] = 'B' if len(text) > span[1] + 1: segment_label[span[1] + 1] = 'B' example = {} example["tokens"] = text example["segment_labels"] = segment_label agg_examples.append(example) return agg_examples if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--json_file") parser.add_argument("--dump_file") args = parser.parse_args() main(args.json_file, args.dump_file)
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/logickit/scripts/semantic_role_labeling/generate_segmentor.py
0.513425
0.173919
generate_segmentor.py
pypi
from typing import Dict, List, Union from relogic.structures.sentence import Sentence from relogic.structures.span import Span from relogic.structures.structure import Structure from relogic.structures.document import Document from relogic.structures.linkage_candidate import LinkageCandidate from relogic.graphkit.utils.similarity_function import jaccard_similarity from relogic.utils.file_utils import cached_path, RELOGIC_CACHE import os from zipfile import ZipFile import logging logger = logging.getLogger(__name__) # pylint: disable=invalid-name """ A quick hack """ from jnius import autoclass JString = autoclass('java.lang.String') JSearcher = autoclass('io.anserini.search.KGSearcher') """ End of quick hack """ INDEX_PATHS = { "en_wikipedia": "https://git.uwaterloo.ca/p8shi/data-server/raw/master/entity_linking_index_en.zip", "zh_baike": "https://git.uwaterloo.ca/p8shi/data-server/raw/master/entity_linking_index_zh.zip" } INDEX_LANGUAGE = { "en_wikipedia": "en", "zh_baike": "zh" } class SimpleEntityLinker(object): """Two step linking. Args: paths (Dict): The key is the name for the retriever, and value is the directory path to the Lucene index. """ def __init__(self, index_names: List, index_paths: Dict = None, index_language: Dict = None): self.index_names = index_names self.retrievers = {} if index_paths is not None and index_language is not None: INDEX_PATHS.update(index_paths) INDEX_LANGUAGE.update(index_language) for index_name in index_names: index_zip_or_dir_path = cached_path(INDEX_PATHS[index_name], cache_dir=RELOGIC_CACHE) if os.path.isdir(index_zip_or_dir_path): index_path = index_zip_or_dir_path else: index_path = index_zip_or_dir_path + "." + index_name if not os.path.exists(index_path): with ZipFile(index_zip_or_dir_path, 'r') as zipObj: zipObj.extractall(index_path) logger.info("Extract Index {} to {}".format(INDEX_PATHS[index_name], index_path)) self.retrievers[index_name] = JSearcher(JString(index_path)) self.retrievers[index_name].setLanguage(INDEX_LANGUAGE[index_name]) def entity_retrieval(self, mention: Span, name: str, candidate_size: int = 20): hits = self.retrievers[name].search( JString(mention.text.encode("utf-8")), JString("contents"), True, None, candidate_size) # Retrieve entity linking results from Anserini. # The data structure follows the definition in Anserini. # LinkageCandidate.from_hit need to follow the changes in Anserini. for i in range(len(hits)): mention.add_linkage_candidate(LinkageCandidate.from_hit(hits[i])) def rank(self, mention: Span, epsilon: float = 0.5): """Operate based on span, and change the results in position. 1. Sorted by retrieval score 2. Given score range [max_score - epsilon, max_score], aggregate the URIs from prior or/and alias_of 3. Convert the URI to string (process the URI or use the label of URI), and rank with the string # A quick hack for DBpedia or Wikidata. Args: mention (:data:`Span`): Mention with linkage candidates for ranking epsilon (float): Control the first layer score range from [max_score - epsilon, max_score] """ if mention.linkage_candidates: mention.linkage_candidates = sorted(mention.linkage_candidates, key=lambda x: self.similarity(x.text, mention.text), reverse=True) else: return max_score = mention.linkage_candidates[0].score # Aggregate first layer # Idempotence operation mention.first_layer_prior = {} for candidate in mention.linkage_candidates: if abs(candidate.score - max_score) < epsilon: # Go over the priors for uri, count in candidate.prior.items(): if uri: mention.first_layer_prior[uri] = mention.first_layer_prior.get(uri, 0) + count # Also consider the alias_of for uri in candidate.alias_of: if uri: mention.first_layer_prior[uri] = mention.first_layer_prior.get(uri, 0) + 1 # TODO: Here 1 is a hyper parameter # Sorted by the prior sorted_uris = sorted(mention.first_layer_prior.items(), key= lambda x: x[1], reverse=True) # TODO: Consider the two ranking together with weighted sum # Hard selection for the exact match # TODO: This is hard coded for DBpedia or Wikidata mention_text_to_uri = mention.text.lower().replace(" ", "_") fixed_sequence = [] for idx, item in enumerate(sorted_uris): # item = (uri, count) if mention_text_to_uri == item[0].lower(): fixed_sequence = [sorted_uris[idx]] + sorted_uris[:idx] + sorted_uris[idx+1:] break if len(fixed_sequence) > 0: mention.ranked_uris = fixed_sequence else: mention.ranked_uris = sorted_uris @staticmethod def similarity(x, y): return jaccard_similarity(x.lower().split(), y.lower().split()) def global_inference(self, inputs: Structure): """The global inference is to deal with mention boundary overlap. Due to imperfect entity detection, there will be some uncertain entities, causing the overlap of some entities. For example, in sentence 'Who painted The Storm on the Sea of Galilee', 'The Storm on the Sea of Galilee' and 'The Storm' are extracted as mentions at the same time due to different entity mention sources are aggregated. With global inference, duplicate/incorrect entity such as 'The Storm' will be removed because it is full substring of 'The Storm on the Sea of Galilee'. This process can not be done before linking, because we do not know which mention is better solely based on the surface form of the mention. With preliminary entity linking results, we can resolve these better. """ pass def link_span(self, span: Span, name: str): self.entity_retrieval(span, name=name) self.rank(span) def link(self, inputs: Union[str, Structure, List[Structure]], name:str): """Linking method. If the inputs is Sentence, then two steps linking is operated. If the inputs is a Span, then candidate retrieval is operated without global inference. """ if isinstance(inputs, str): span = Span(text=inputs) self.link_span(span, name=name) return span elif isinstance(inputs, Structure): if isinstance(inputs, Document): self.link(inputs.sentences, name=name) elif isinstance(inputs, Sentence): for span in inputs.spans: self.link_span(span, name=name) self.global_inference(inputs) elif isinstance(inputs, Span): self.link_span(inputs, name=name) else: raise ValueError("Item type {} is not supported".format(type(inputs))) elif isinstance(inputs, List): for item in inputs: self.link(item, name=name) else: raise ValueError("Item type {} is not supported".format(type(inputs)))
/relogic00-0.0.1.tar.gz/relogic00-0.0.1/relogic/graphkit/linking/simple_entity_linker.py
0.724188
0.249996
simple_entity_linker.py
pypi
# relpath 下の方に日本語の説明があります<br> 底下有中文解释。 ## Summary (Explanation in English) Features of this package 1. you can use the relative path intuitively - The standard relative path in python is not intuitive. 2. you can import various modules relatively - It can handle complex projects where the folders are nested. ## Usage #1: A basic example Example of getting the directory (location) of the python file itself ```python from relpath import rel2abs print(rel2abs("./")) # -> "(The directory this python file belongs to)" ``` ## Usage #2: A Practical Example A practical use case for this tool ``` . `-- project_folder |-- parts | |-- data.txt | `-- script_B.py `-- script_A.py ``` As shown above, consider a project with multiple python files. In `script_A.py`, we will use `script_B.py` as shown below. ```python # script_A.py # load script_B.py from parts.script_B import get_data print(get_data()) ``` In this case, if you try to refer to `"./data.txt"` relatively from `script_B.py`, as shown in the following code example, it will fail. (Note 1) ``` (Note 1) Strictly speaking, you can load it by specifying a relative path from `script_A.py`, but if the caller is changed to another location, it won't work properly and is not easy to maintain. To avoid this, we recommend using the `relpath` package. ``` ```python # script_B.py def get_data(): with open("./data.txt", "r") as f: # -> FileNotFoundError: [Errno 2] No such file or directory: './data.txt' return f.read() ``` On the other hand, you can use the `relpath` package and write the following to refer to `"./data.txt"` relatively. (Note 2) ```python # script_B.py from relpath import rel2abs def get_data(): with open(rel2abs("./data.txt"), "r") as f: # -> NO ERROR!! return f.read() ``` ``` (Note 2) The python specification of relative paths is not necessarily wrong. Under the python specification, a relative path is always interpreted with the first executed python file as the reference position. So users have to be aware of the position of the first executed python file when writing a relative path. On the other hand, the python specification has an advantage: if the file containing the path is moved, you don't have to change the path. The `relpath` package is just another way to give the programmer another option besides the python specification, so we recommend that you consider whether to use it or not depending on the situation. ``` ## Usage #3: Relative import example The `relpath` package provides an intuitive relative import of a module, as shown in the following example. ```python from relpath import add_import_path add_import_path("../") from my_module import some_function some_function() ``` Why do I need to write like the above example? Can't I just write `sys.path.append("../")`? As a matter of fact, `sys.path.append("../")` does not work well if your project folder has a complex hierarchical structure where one module is used from different locations. Therefore, it is recommended to use the `add_import_path` of the `relpath` package whenever you want to implement relative import. `add_import_path("../")` is internally equivalent to `sys.path.append(rel2abs("../"))`. --- ## 概要 (日本語) このパッケージでできること: 1. 直感的な相対パス参照ができる - pythonのパス参照の仕様は直感に反する 2. モジュールの相対importに使える - フォルダが多重で複雑なプロジェクトにも対応できる ## 使い方1: 基本的な例 下記は、pythonファイル自身の場所(ディレクトリ)を取得する例です。 ```python from relpath import rel2abs print(rel2abs("./")) # -> "(このpythonファイルが存在するディレクトリ)" ``` ## 使い方2: 実用的な例 このツールは、下記のような場合に真価を発揮します。 ``` . `-- project_folder |-- parts | |-- data.txt | `-- script_B.py `-- script_A.py ``` 上記のように、複数のpythonファイルからなるプロジェクトを考えます。 `script_A.py`の中では下記のように、`script_B.py`を利用します。 ```python # script_A.py # load script_B.py from parts.script_B import get_data print(get_data()) ``` この場合に、下記のコード例のように、 `script_B.py`から"./data.txt"を相対的に読み込もうとすると失敗します。(注1) ``` (注1) 厳密には、`script_A.py`からの相対パス指定をすれば読み込めますが、 呼び出し元が別の場所に変更された場合、正常に動作しなくなるので、メンテナンス性が悪くなります。 これを回避するため、`relpath`パッケージの利用を推奨します。 ``` ```python # script_B.py def get_data(): with open("./data.txt", "r") as f: # -> FileNotFoundError: [Errno 2] No such file or directory: './data.txt' return f.read() ``` そこで、`relpath`パッケージを使って下記のように書くと、 `"./data.txt"`を相対的に読み込めるようになります。(注2) ```python # script_B.py from relpath import rel2abs def get_data(): with open(rel2abs("./data.txt"), "r") as f: # -> NO ERROR!! return f.read() ``` ``` (注2) 相対パスに関するpythonの仕様は、必ずしも間違いというわけではありません。 pythonの仕様(相対パスの指定が、記述するファイルの場所に関わらず、常に最初の呼び出し元を基準として解釈される仕様)には、 プログラムを開発する中でもしファイル読み込み等の命令を記述する場所(ファイル)が変更になった場合でも、 パス指定方法の変更が不要になるという利点があります。 `relpath`パッケージは、pythonの仕様の他に、プログラマーにもう一つの選択肢を与える手段に過ぎないので、 状況に応じて利用の要否を検討することを推奨します。 ``` ## 使い方3: 相対importとしての利用 `relpath`パッケージを利用すると、下記の例のように、 モジュールの直感的な相対importを実現できます。 ```python from relpath import add_import_path add_import_path("../") from my_module import some_function some_function() ``` 上記の例を見ると、単に`sys.path.append("../")`としても動作するように思われます。 しかし、プロジェクトフォルダの階層構造が複雑で、1つのモジュールが別々の場所から使われるような場合には、`sys.path.append("../")`では対応できないことがあります。 そのため、相対importを実現したいときは、常に`relpath`パッケージの`add_import_path`を利用することを推奨します。 なお、`add_import_path("../")` は、内部的には`sys.path.append(rel2abs("../"))`と等価です。 --- ## 摘要 (中文解释) 本套餐的特点 1. 你可以直观地使用相对路径。 - python中标准的相对路径并不直观。 2. 可以相对导入各种模块 - 它可以处理文件夹嵌套的复杂项目。 ## 用法 #1: 一个基本的例子 获取python文件本身的目录(位置)的例子 ```python from relpath import rel2abs print(rel2abs("./")) # -> "(这个python文件所属的目录)" ``` ## 用法 #2: 一个实际例子 该工具的实际使用案例 ``` . `-- project_folder |-- parts | |-- data.txt | `-- script_B.py `-- script_A.py ``` 如上图所示,考虑一个有多个python文件的项目。 在`script_A.py`中,我们将使用`script_B.py`,如下所示。 ```python # script_A.py # load script_B.py from parts.script_B import get_data print(get_data()) ``` 在这种情况下,如果你试图从`script_B.py`中相对引用`"./data.txt"`,如下面的代码示例所示,它将失败。 (注1) ``` (注1) 严格来说,你可以通过指定`script_A.py`的相对路径来加载, 但如果调用者换到其他位置,就不能正常工作,而且不容易维护。 为了避免这种情况,我们建议使用`relpath`包。 ``` ```python # script_B.py def get_data(): with open("./data.txt", "r") as f: # -> FileNotFoundError: [Errno 2] No such file or directory: './data.txt' return f.read() ``` 另一方面,你可以使用`relpath`包,并写下以下内容来相对引用`"./data.txt"`。 (注2) ```python # script_B.py from relpath import rel2abs def get_data(): with open(rel2abs("./data.txt"), "r") as f: # -> NO ERROR!! return f.read() ``` ``` (注2) 相对路径的python规范不一定是错的。 在python规范下,相对路径总是被理解为相对于第一个执行的Python文件作为参考位置。 所以用户在写相对路径的时候,要注意第一个执行的python文件的位置。 另一方面,python规范至少有一个优点。 其优点是,当移动包含路径的文件时,不需要改变路径。 `relpath`包只是给程序员在python规范之外的另一种选择,所以建议大家根据实际情况考虑是否使用。 ``` ## 用法 #3: 相对导入示例 `relpath`包提供了一个直观的模块相对导入,如下例所示。 ```python from relpath import add_import_path add_import_path("../") from my_module import some_function some_function() ``` 为什么要写成上面的例子? 我不能直接写`sys.path.append("../")`吗? 事实上,如果你的项目文件夹具有复杂的层次结构,一个模块从不同的位置使用,`sys.path.append("../")`就不能很好地发挥作用。 因此,当你想实现相对导入时,建议使用`relpath`包中的`add_import_path`。 `add_import_path("../")`内部等同于`sys.path.append(rel2abs("../"))`。
/relpath-3.0.5.tar.gz/relpath-3.0.5/README.md
0.49585
0.918809
README.md
pypi
from relsa_serializer.tools_modules.work_with_function_module.dic_to_ast_module import unparse_ast_str from relsa_serializer.tools_modules.work_with_function_module.unserialize_funct_module import return_compiled_function from relsa_serializer.tools_modules.work_with_function_module.unserialize_funct_module import unparsed_funct def deserialize_from_dict(incoming_dict: dict, globals_from_main) -> object: """ Возвращает объект из универсального словаря """ if 'type' in incoming_dict and incoming_dict['type'] == 'class': return class_deserialize(incoming_dict, globals_from_main) elif 'type' in incoming_dict and incoming_dict['type'] == 'instance': return instance_deserialize(incoming_dict, globals_from_main) elif "<class 'function'>" in incoming_dict: return function_deserialize(incoming_dict, globals_from_main) if 'type' in incoming_dict and incoming_dict['type'] == 'list': return list_deserialize(incoming_dict) elif 'type' in incoming_dict and incoming_dict['type'] == 'tuple': return tuple_deserialize(incoming_dict) else: else_dict = dict() for item in incoming_dict.items(): if type(item[1]) == dict and 'value' in item[1]: else_dict[item[0]] = item[1]['value'] return else_dict def class_deserialize(incoming_dict: dict, globals_from_main): dict_as_obj = dict() for item in incoming_dict.items(): if type(item[1]) == dict and "<class 'function'>" in item[1]: unparsed_funct(unparse_ast_str(item[1]["<class 'function'>"])) unprs_fnct = return_compiled_function(unparse_ast_str(item[1]["<class 'function'>"]), globals_from_main) dict_as_obj[item[0]] = unprs_fnct constructed_class = type(f'{incoming_dict["class_name"]}', (object,), dict_as_obj) return constructed_class def instance_deserialize(incoming_dict: dict, globals_from_main): class_deserialized = deserialize_from_dict(incoming_dict['class'], globals_from_main) params_dict = dict() for item in incoming_dict.items(): if type(item[1]) == dict and 'value' in item[1]: params_dict[item[0]] = item[1]['value'] elif type(item[1]) == dict and 'type' in item[1] and item[1]['type'] == 'instance' and len( params_dict) != 0: if class_deserialized: for item_in_included in item[1].items(): if type(item_in_included) == tuple and 'value' in item_in_included[1]: params_dict[item_in_included[0]] = item_in_included[1]['value'] constructed_instance = class_deserialized(**params_dict) return constructed_instance def function_deserialize(incoming_dict: dict, globals_from_main): unparsed_funct(unparse_ast_str(incoming_dict["<class 'function'>"])) unprs_fnct = return_compiled_function(unparse_ast_str(incoming_dict["<class 'function'>"]), globals_from_main) return unprs_fnct def list_deserialize(incoming_dict: dict): out_list = list() for item in incoming_dict.items(): if 'value' in item[1]: out_list.append(type(item[1]['type'])(item[1]['value'])) return out_list def tuple_deserialize(incoming_dict: dict): out_tuple = tuple() for item in incoming_dict.items(): if 'value' in item[1]: out_tuple = list(out_tuple) out_tuple.append(type(item[1]['type'])(item[1]['value'])) out_tuple = tuple(out_tuple) return out_tuple
/relsa_serializer-1.0.0.tar.gz/relsa_serializer-1.0.0/relsa_serializer/tools_modules/return_to_normal_form.py
0.462716
0.182717
return_to_normal_form.py
pypi
from abc import ABCMeta, abstractmethod from itertools import groupby from operator import itemgetter from typing import Callable, Generic, Iterable, Iterator, Tuple, TypeVar __all__ = [ 'OneToManyChainer', 'relate_one_to_many', 'left_join', 'outer_join', 'inner_join', ] T = TypeVar('T') class _Peekable(Generic[T], Iterator[T]): """ An iterator where the current element can be fetched. When given an empty iterator, then only stops iteration. >>> peekable = _Peekable(iter([])) >>> bool(peekable) False >>> peekable.peek() Traceback (most recent call last): ... StopIteration >>> next(peekable) Traceback (most recent call last): ... StopIteration >>> for item in _Peekable(iter([])): ... item When given a filled iterator, then peeks and iterates it. >>> peekable = _Peekable(iter([1, 2])) >>> bool(peekable) True >>> peekable.peek() 1 >>> next(peekable) 1 >>> bool(peekable) True >>> peekable.peek() 2 >>> next(peekable) 2 >>> peekable.peek() Traceback (most recent call last): ... StopIteration >>> next(peekable) Traceback (most recent call last): ... StopIteration >>> for item in _Peekable(iter([1, 2])): ... item 1 2 Peeks values as lazyly as possible. >>> iterator = iter([1]) >>> _ = _Peekable(iterator) >>> for item in iterator: ... item 1 >>> iterator = iter([1, 2]) >>> peekable = _Peekable(iterator) >>> peekable.peek() 1 >>> next(peekable) 1 >>> for item in iterator: ... item 2 """ __NO_VALUE = object() def __init__(self, iterable: Iterable[T]): self._iterator = iter(iterable) self._current: object = self.__NO_VALUE # T or __NO_VALUE def peek(self) -> T: if self._current is self.__NO_VALUE: self._current = next(self._iterator) return self._current # type: ignore def __iter__(self) -> Iterator[T]: return self def __next__(self) -> T: current = self.peek() self._current = self.__NO_VALUE return current # type: ignore def __bool__(self) -> bool: try: self.peek() except StopIteration: return False return True # HACK: implemented for Python 3.6, may be replaced to use typing.Protocol. class _Comparable(metaclass=ABCMeta): """Protocol for annotating comparable types.""" @abstractmethod def __lt__(self, other) -> bool: ... @abstractmethod def __le__(self, other) -> bool: ... @abstractmethod def __gt__(self, other) -> bool: ... @abstractmethod def __ge__(self, other) -> bool: ... @abstractmethod def __eq__(self, other) -> bool: ... @abstractmethod def __ne__(self, other) -> bool: ... Key = TypeVar('Key', bound=_Comparable) Value = TypeVar('Value') Left = TypeVar('Left') Right = TypeVar('Right') _EMPTY_ITERABLE: Iterable = tuple() FIRST_ITEM_KEY = itemgetter(0) DEFAULT_KEY = FIRST_ITEM_KEY class _UnidirectionalFinder(Generic[Value, Key], Iterator[Iterator[Value]]): """ This class finds items in `iterable` unidirectionally and groups them by the given `key`. Note that the `Key` must be 'comparable' (supports `__lt__()` and `__gt__()`) and `iterable` must be sorted by `key`. Here are some normal cases. Collections are sorted by the first items. >>> iterable = [(0, 'a'), (1, 'b'), (1, 'c'), (2, 'd')] >>> finder = _UnidirectionalFinder(iterable, itemgetter(0)) >>> finder.has_items True >>> finder.current_key() 0 When given a waiting key, then finds items and groups them by the key. >>> list(finder.find(1)) [(1, 'b'), (1, 'c')] >>> finder.current_key() 2 When given passed keys, then cannot find items. >>> list(finder.find(1)) [] >>> list(finder.find(0)) [] When given too large keys, then cannot find items. Once given a too large key, the finder is exhausted. >>> list(finder.find(3)) [] >>> finder.has_items False >>> finder.current_key() Traceback (most recent call last): ... StopIteration When exhausted and given an existing key, then cannot find items. >>> list(finder.find(2)) [] Sequencial usage is also supported. >>> iterable = [(0, 'a'), (1, 'b'), (1, 'c'), (2, 'd'), (3, 'e')] >>> finder = _UnidirectionalFinder(iterable, itemgetter(0)) >>> finder.current_key() 0 >>> list(next(finder)) [(0, 'a')] >>> finder.current_key() 1 >>> list(next(finder)) [(1, 'b'), (1, 'c')] >>> finder.current_key() 2 >>> list(finder.find(3)) [(3, 'e')] >>> finder.current_key() Traceback (most recent call last): ... StopIteration >>> next(finder) Traceback (most recent call last): ... StopIteration Here are some seminormal cases. When given an empty collection, then cannot find any items. >>> finder = _UnidirectionalFinder([], itemgetter(0)) >>> finder.has_items False >>> list(finder.find(0)) [] >>> finder.current_key() Traceback (most recent call last): ... StopIteration When given a not sorted `iterable`, then stops finding at reverse-ordering segments. >>> iterable = [(0, 'a'), (2, 'b'), (1, 'c'), (3, 'd')] >>> finder = _UnidirectionalFinder(iterable, itemgetter(0)) >>> list(finder.find(1)) [] >>> finder.current_key() 2 >>> list(finder.find(2)) [(2, 'b')] >>> list(finder.find(3)) [(3, 'd')] """ def __init__( self, iterable: Iterable[Value], key: Callable[[Value], Key], ) -> None: """Initialize""" self._groups = _Peekable(groupby(iterable, key)) def find(self, key: Key) -> Iterator[Value]: """Find items that have the given key.""" self.seek_to(key) if not self.has_items: return iter(_EMPTY_ITERABLE) group_key, group_items = self._groups.peek() if group_key > key: return iter(_EMPTY_ITERABLE) next(self) return group_items def seek_to(self, key: Key) -> None: """Seek to the given key.""" try: while self._groups.peek()[0] < key: next(self._groups) except StopIteration: pass @property def has_items(self) -> bool: """Check if the iterator has items.""" return bool(self._groups) def current_key(self) -> Key: """ Returns the current key. When exhausted, then throws StopIteration. """ return self._groups.peek()[0] def __next__(self) -> Iterator[Value]: """ Returns the current value and move to the next. When exhausted, then throws StopIteration. """ return next(self._groups)[1] class OneToManyChainer(Generic[Left]): """ Relate `lhs` to one or more `rhs`. When given no `rhs`, then iterates the tuple of `lhs`. >>> lhs = [(0, 'a'), (1, 'b'), (2, 'c')] >>> chainer = OneToManyChainer(lhs) >>> for left in chainer.chain(): ... left ((0, 'a'),) ((1, 'b'),) ((2, 'c'),) When given `lhs`, `rhs1` and `rhs2`, then iterates the tuple of (`lhs`, `rhs1`, `rhs2`) >>> rhs1 = [(1, 's'), (2, 't'), (2, 'u'), (3, 'v')] >>> rhs2 = [('a', 'x'), ('a', 'y'), ('b', 'z')] >>> chainer = OneToManyChainer(lhs) >>> chainer.append(rhs1) >>> chainer.append(rhs2, lhs_key=itemgetter(1), rhs_key=itemgetter(0)) >>> for left, right1, right2 in chainer.chain(): ... left, list(right1), list(right2) ((0, 'a'), [], [('a', 'x'), ('a', 'y')]) ((1, 'b'), [(1, 's')], [('b', 'z')]) ((2, 'c'), [(2, 't'), (2, 'u')], []) """ def __init__(self, lhs: Iterable[Left]): self._lhs = lhs self._chain: list = [] def append( self, rhs: Iterable[Right], lhs_key: Callable[[Left], Key] = DEFAULT_KEY, rhs_key: Callable[[Right], Key] = DEFAULT_KEY, ) -> None: item = (lhs_key, _UnidirectionalFinder(rhs, rhs_key)) self._chain.append(item) def chain(self) -> Iterator[Tuple[Left, ...]]: return (self._next(item) for item in self._lhs) def _next(self, item: Left) -> Tuple[Left, ...]: rs = ( r_finder.find(lhs_key(item)) for lhs_key, r_finder in self._chain ) return (item, *rs) def relate_one_to_many( lhs: Iterable[Left], rhs: Iterable[Right], lhs_key: Callable[[Left], Key] = DEFAULT_KEY, rhs_key: Callable[[Right], Key] = DEFAULT_KEY, ) -> Iterator[Tuple[Left, Iterator[Right]]]: """ Relates `rhs` items to each `lhs` items. Note that: - `Key` must be 'comparable' (supports `__lt__()` and `__gt__()`). - `lhs` must be sorted by keys that `lhs_key` provides. - `rhs` must be sorted by keys that `rhs_key` provides. `lhs_key` and `rhs_key` are optional. When not given, then relates `rhs` to `lhs` by their first items (`left[0]` and `right[0]`). Here are some normal cases. These collections are sorted by the first items. >>> lhs = [(0, 'a'), (1, 'b'), (2, 'c')] >>> rhs = [(1, 's'), (2, 't'), (2, 'u'), (3, 'v')] When not given any keys, then relates `rhs` to `lhs` by their first items. >>> relations = relate_one_to_many(lhs, rhs) >>> for left, right in relations: ... left, list(right) ((0, 'a'), []) ((1, 'b'), [(1, 's')]) ((2, 'c'), [(2, 't'), (2, 'u')]) When given custom keys, then relates `rhs` to `lhs` by that keys. Note that the custom keys *must not* break the key ordering. >>> relations = relate_one_to_many( ... lhs, rhs, ... lhs_key=lambda l: l[0] * 2, ... rhs_key=lambda r: r[0] - 1) >>> for left, right in relations: ... left, list(right) ((0, 'a'), [(1, 's')]) ((1, 'b'), [(3, 'v')]) ((2, 'c'), []) Here are some seminormal cases. When given an empty `lhs`, then returns an empty iterator. >>> relations = relate_one_to_many([], [(1, 's')]) >>> list(relations) [] When given an empty `rhs`, then returns an iterator that relates nothing. >>> relations = relate_one_to_many([(1, 'a')], []) >>> for left, right in relations: ... left, list(right) ((1, 'a'), []) When given unordered `lhs`, then stops relationing at reverse-ordering segments. >>> lhs = [(0, 'a'), (2, 'b'), (1, 'c'), (4, 'd'), (3, 'e')] >>> rhs = [(1, 's'), (2, 't'), (2, 'u'), (3, 'v'), (4, 'w')] >>> relations = relate_one_to_many(lhs, rhs) >>> for left, right in relations: ... left, list(right) ((0, 'a'), []) ((2, 'b'), [(2, 't'), (2, 'u')]) ((1, 'c'), []) ((4, 'd'), [(4, 'w')]) ((3, 'e'), []) When given unordered `rhs`, then stops relationing at reverse-ordering segments. >>> lhs = [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')] >>> rhs = [(1, 's'), (3, 't'), (3, 'u'), (2, 'v'), (4, 'w')] >>> relations = relate_one_to_many(lhs, rhs) >>> for left, right in relations: ... left, list(right) ((0, 'a'), []) ((1, 'b'), [(1, 's')]) ((2, 'c'), []) ((3, 'd'), [(3, 't'), (3, 'u')]) ((4, 'e'), [(4, 'w')]) """ chainer = OneToManyChainer(lhs) chainer.append(rhs, lhs_key, rhs_key) return chainer.chain() # type: ignore def left_join( lhs: Iterable[Left], rhs: Iterable[Right], lhs_key: Callable[[Left], Key] = DEFAULT_KEY, rhs_key: Callable[[Right], Key] = DEFAULT_KEY, ) -> Iterator[Tuple[Iterator[Left], Iterator[Right]]]: """ Join two iterables like SQL left joining. While SQL left joining returns all the combinations, this returns the pair of items. The arguments are very similar to `relate_one_to_many`. See `relate_one_to_many` doc for more information. This function is equivalent to below: - Groups `lhs` by `lhs_key`. - Run `relate_one_to_many` with that group as `lhs` and `rhs`. Here are some normal cases. Note that the `right` can empty, like SQL left joining. >>> lhs = [(1, 'a'), (1, 'b'), (2, 'c'), (4, 'd')] >>> rhs = [(1, 's'), (1, 't'), (3, 'u'), (4, 'v')] >>> relations = left_join(lhs, rhs) >>> for left, right in relations: ... list(left), list(right) ([(1, 'a'), (1, 'b')], [(1, 's'), (1, 't')]) ([(2, 'c')], []) ([(4, 'd')], [(4, 'v')]) Custom keys are acceptable. >>> relations = left_join( ... lhs, rhs, ... lhs_key=lambda l: l[0] * 2, ... rhs_key=lambda r: r[0] + 1) >>> for left, right in relations: ... list(left), list(right) ([(1, 'a'), (1, 'b')], [(1, 's'), (1, 't')]) ([(2, 'c')], [(3, 'u')]) ([(4, 'd')], []) Here is a seminormal cases. When given empty `lhs`, returns the empty iterator. >>> relations = left_join([], [(1, 's')]) >>> list(relations) [] """ lhs_groups = groupby(lhs, lhs_key) relations = relate_one_to_many(lhs_groups, rhs, FIRST_ITEM_KEY, rhs_key) return ((left, right) for (_, left), right in relations) def outer_join( lhs: Iterable[Left], rhs: Iterable[Right], lhs_key: Callable[[Left], Key] = DEFAULT_KEY, rhs_key: Callable[[Right], Key] = DEFAULT_KEY, ) -> Iterator[Tuple[Iterator[Left], Iterator[Right]]]: """ Join two iterables preserving all existing keys. In contrast to `left_join`, this preserve keys that are only in `rhs`. The arguments are very similar to `relate_one_to_many`. See `relate_one_to_many` doc for more information. Here are some normal cases. Note that all existing keys are covered and both `left` and `right` can be empty. >>> lhs = [(1, 'a'), (1, 'b'), (2, 'c'), (4, 'd')] >>> rhs = [(1, 's'), (1, 't'), (3, 'u'), (4, 'v')] >>> relations = outer_join(lhs, rhs) >>> for left, right in relations: ... list(left), list(right) ([(1, 'a'), (1, 'b')], [(1, 's'), (1, 't')]) ([(2, 'c')], []) ([], [(3, 'u')]) ([(4, 'd')], [(4, 'v')]) When given custom keys, then joins by them. >>> relations = relate_one_to_many( ... lhs, rhs, ... lhs_key=lambda l: l[0] * 2, ... rhs_key=lambda r: r[0] + 1) >>> for left, right in relations: ... left, list(right) ((1, 'a'), [(1, 's'), (1, 't')]) ((1, 'b'), []) ((2, 'c'), [(3, 'u')]) ((4, 'd'), []) When given long tail `lhs`, then returns the empty tail for the right. >>> relations = outer_join([(1, 'a'), (2, 'b')], [(1, 's')]) >>> for left, right in relations: ... list(left), list(right) ([(1, 'a')], [(1, 's')]) ([(2, 'b')], []) When given long tail `rhs`, then returns the empty tail for the left. >>> relations = outer_join([(1, 'a')], [(1, 's'), (2, 't')]) >>> for left, right in relations: ... list(left), list(right) ([(1, 'a')], [(1, 's')]) ([], [(2, 't')]) Here are some seminormal cases. When given empty `lhs`, then returns an iterator that all left items are empty. >>> relations = outer_join([], [(1, 's')]) >>> for left, right in relations: ... list(left), list(right) ([], [(1, 's')]) When given empty `rhs`, then returns an iterator that all right items are empty >>> relations = outer_join([(1, 'a')], []) >>> for left, right in relations: ... list(left), list(right) ([(1, 'a')], []) """ lhs_finder = _UnidirectionalFinder(lhs, lhs_key) rhs_finder = _UnidirectionalFinder(rhs, rhs_key) while lhs_finder.has_items: if not rhs_finder.has_items: yield next(lhs_finder), iter(_EMPTY_ITERABLE) continue key_curr = min(lhs_finder.current_key(), rhs_finder.current_key()) yield lhs_finder.find(key_curr), rhs_finder.find(key_curr) while rhs_finder.has_items: yield iter(_EMPTY_ITERABLE), next(rhs_finder) def inner_join( lhs: Iterable[Left], rhs: Iterable[Right], lhs_key: Callable[[Left], Key] = DEFAULT_KEY, rhs_key: Callable[[Right], Key] = DEFAULT_KEY, ) -> Iterator[Tuple[Iterator[Left], Iterator[Right]]]: """ Join two iterables like SQL inner joining. This function's behavior is very similar to `left_join`. See `left_join` doc first. In contrast to `left_join`, `right` cannot be empty, like SQL inner joining. Here are some normal cases. >>> lhs = [(1, 'a'), (1, 'b'), (2, 'c'), (4, 'd')] >>> rhs = [(1, 's'), (1, 't'), (3, 'u'), (4, 'v')] >>> relations = inner_join(lhs, rhs) >>> for left, right in relations: ... list(left), list(right) ([(1, 'a'), (1, 'b')], [(1, 's'), (1, 't')]) ([(4, 'd')], [(4, 'v')]) Custom keys are acceptable. >>> relations = inner_join( ... lhs, rhs, ... lhs_key=lambda l: l[0] * 2, ... rhs_key=lambda r: r[0] + 1) >>> for left, right in relations: ... list(left), list(right) ([(1, 'a'), (1, 'b')], [(1, 's'), (1, 't')]) ([(2, 'c')], [(3, 'u')]) Here is a seminormal cases. When given empty `lhs`, returns the empty iterator. >>> relations = inner_join([], [(1, 's')]) >>> list(relations) [] """ left_joined = left_join(lhs, rhs, lhs_key, rhs_key) relations = ((left, _Peekable(right)) for left, right in left_joined) return ((left, right) for left, right in relations if right)
/reltools-1.0.0-py3-none-any.whl/reltools.py
0.930379
0.294621
reltools.py
pypi
import tensorflow as tf import numpy as np from .utils.storage import AnnParameters from .interfaces.interface_factory import InterfaceFactory class AnnModel: """Class for constructing optimization formulations for trained Artificial neural networks (ANNs) with Rectified linear unit (ReLU) activation functions. The formulation is embedded in optimization models defined by the user in the Pyomo or Gurobi modelling languages. """ def __init__(self, tf_model: tf.keras.Sequential, modeling_language: str, name: str = "ANN") -> None: """An AnnModel is constructed for a specific tensorflow.keras.Sequential model and the desired modelling Interface (eg. pyomo). The interface is initialized and weights and biases are extracted from the tensorflow model. Parameters ---------- tf_model: tensorflow Sequential model with layer type Dense using ReLU activation. modeling_language: Optimization modelling language that the model will be written in (eg. 'PYOMO', 'GUROBI'). name: String describing the ANN. """ self._network_type_check(tf_model) self.name = name self._modelingInterface = InterfaceFactory().create(modeling_language, name) self.networkParam = self._init_network_param(tf_model) self._inputIsConnected = False self._outputIsConnected = False self._paramIsLoaded = False def connect_network_input(self, opt_model, input_vars: list) -> None: """ Assigns the optimization model that the ANN is embedded in plus the ANN input variables (as a list). Connecting input variables is necessary before embedding the ANN. The input variable bounds will be used for bound tightening and should therefore be defined and finite. Parameters ---------- opt_model : Parent optimization model input_vars : List of input variables for the ANN. Make sure that the variables are listed in the same order as during training of the loaded ANN. """ if self._inputIsConnected: print("Warning: Overwriting network input.") self._modelingInterface.type_check(opt_model, "model") for var in input_vars: self._modelingInterface.type_check(var, "variable") assert (len(input_vars) == self.networkParam.input_dim) input_bounds = self._modelingInterface.get_variable_bounds(input_vars) self.networkParam.input_bounds = input_bounds self._modelingInterface.connect_network_input(opt_model=opt_model, input_vars=input_vars) self._inputIsConnected = True def connect_network_output(self, opt_model, output_vars: list) -> None: """ Assigns he ANN output variables (as a list). Parameters ---------- opt_model: Parent optimization model output_vars: List of output variables for the ANN. """ if self._outputIsConnected: print("Warning: Overwriting network output.") if not self._inputIsConnected: raise Exception('Network input has to be connected before network output.') for var in output_vars: self._modelingInterface.type_check(var, "variable") if len(output_vars) != self.networkParam.output_dim: raise Exception('The specified output dimension is not equal to the one implied by the currently loaded ' 'tensorflow model') self.networkParam.output_bounds = self._modelingInterface.get_variable_bounds(output_vars) # TODO: fbbt_backward_pass(self.network_param, output_bounds) - see Grimstad et. al Appendix self._modelingInterface.connect_network_output(opt_model=opt_model, output_vars=output_vars) self._outputIsConnected = True def embed_network_formulation(self, opt_model=None, input_vars=None, output_vars=None, mip_formulation: str = 'Big-M', bound_tightening_strategy: str = 'LP', node_time_limit: float = 1., use_full_model: bool = False, solver=None): """ Embeds an optimization formulation for the loaded ANN into the parent optimization variables. This defines the functional relationship output_variables = f_ANN(input_variables) in the parent model, by introducing auxiliary variables and constraints describing the ANN function. The auxiliary variables are automatically tightened according to the specified strategy. Parameters ---------- opt_model : Parent optimization model input_vars : Input variables for the ANN output_vars : Output variables for the ANN mip_formulation : Encodes the ReLU logic as MIP variables + constraints bound_tightening_strategy : Defines the method to compute bounds for the internal ANN variables node_time_limit : Time limit for each node during bound tightening use_full_model : Set to True, if the full parent model shall be used for bound tightening. solver : Solver object needed for some modelling interfaces (eg. Pyomo) """ if input_vars is not None: self.connect_network_input(opt_model=opt_model, input_vars=input_vars) if output_vars is not None: self.connect_network_output(opt_model=opt_model, output_vars=output_vars) if not (self._outputIsConnected and self._inputIsConnected): raise Exception("Input and output variables must be connected to the ANN model before embedding the " "formulation.") if not self._paramIsLoaded: self._fbbt_forward_pass() self._node_redundancy_check() self._modelingInterface.embed_network_formulation(opt_model=opt_model, ann_param=self.networkParam, mip_formulation=mip_formulation, bound_tightening_strategy=bound_tightening_strategy, node_time_limit=node_time_limit, use_parent_model=use_full_model, solver=solver) def _fbbt_forward_pass(self) -> None: """Computes feasibility-based bounds for the ANN variables. """ self.networkParam.LB[0] = self.networkParam.input_bounds[:, 0] self.networkParam.LB[0].shape = (self.networkParam.nodes_per_layer[0], 1) self.networkParam.UB[0] = self.networkParam.input_bounds[:, 1] self.networkParam.UB[0].shape = (self.networkParam.nodes_per_layer[0], 1) w_plus = [w.clip(min=0) for w in self.networkParam.weights] w_minus = [w.clip(max=0) for w in self.networkParam.weights] for i in range(1, self.networkParam.n_layers): tmp = np.matmul(np.transpose(w_plus[i - 1]), self.networkParam.UB[i - 1]) + np.matmul(np.transpose(w_minus[i - 1]), self.networkParam.LB[i - 1]) + \ self.networkParam.bias[i - 1] self.networkParam.UB[i] = tmp.clip(min=0) self.networkParam.M_plus[i - 1] = tmp tmp2 = np.matmul(np.transpose(w_plus[i - 1]), self.networkParam.LB[i - 1]) + np.matmul( np.transpose(w_minus[i - 1]), self.networkParam.UB[i - 1]) + self.networkParam.bias[i - 1] self.networkParam.M_minus[i - 1] = tmp2 if type(self.networkParam.output_bounds) == np.ndarray: # If the computed bounds improve on the given output bounds, they are updated assert (np.shape(self.networkParam.output_bounds) == (self.networkParam.nodes_per_layer[-1], 2)) for i in range(self.networkParam.nodes_per_layer[-1]): if self.networkParam.output_bounds[i, 0] > self.networkParam.M_minus[self.networkParam.n_layers - 2][i]: self.networkParam.M_minus[self.networkParam.n_layers - 2][i] = self.networkParam.output_bounds[i, 0] self.networkParam.LB[-1][i] = self.networkParam.output_bounds[i, 0] if self.networkParam.output_bounds[i, 1] < self.networkParam.M_plus[self.networkParam.n_layers - 2][i]: self.networkParam.M_plus[self.networkParam.n_layers - 2][i] = self.networkParam.output_bounds[i, 1] self.networkParam.UB[-1][i] = self.networkParam.output_bounds[i, 1] @staticmethod def _init_network_param(tf_model: tf.keras.Sequential) -> AnnParameters: """Extracts weights and biases from tensorflow model. Parameters ---------- tf_model : tensorflow Sequential model with layer type Dense using ReLU activation. Returns ------- NetworkParam : AnnParameters object storing all necessary ANN parameters """ nn_params = tf_model.get_weights() bias = nn_params[1::2] for bi in bias: bi.shape = (len(bi), 1) weights = nn_params[0::2] n_layers = len(bias) + 1 nodes_per_layer = np.array([np.shape(weights[i])[0] for i in range(len(weights))] + [len(bias[-1])]) # Big-M values m_plus = [np.zeros((len(b), 1)) for b in bias] m_minus = [np.zeros((len(b), 1)) for b in bias] # Variable bounds lb = [np.zeros((n, 1)) for n in nodes_per_layer] ub = [np.zeros((n, 1)) for n in nodes_per_layer] redundancy_matrix = [np.zeros((n, 1)) for n in nodes_per_layer[1:-1]] network_param = AnnParameters(n_layers=n_layers, nodes_per_layer=nodes_per_layer, input_dim=nodes_per_layer[0], output_dim=nodes_per_layer[-1], weights=weights, bias=bias, M_plus=m_plus, M_minus=m_minus, LB=lb, UB=ub, redundancy_matrix=redundancy_matrix) return network_param @staticmethod def _network_type_check(tf_model: tf.keras.Sequential) -> None: """Checks if tensorflow model has correct specifications Parameters ---------- tf_model : tensorflow Sequential model with Dense layers using ReLU activation. ------- """ if len(tf_model.layers) < 2: print('Warning: The tensorflow model does not appear to contain any hidden layers. This will lead to undefined behaviour.') for idx, layer in enumerate(tf_model.layers[:-1]): if not isinstance(layer, tf.keras.layers.Dense): raise Exception('Layer ' + str(idx) + ' of tensorflow model is not dense.') if layer.activation.__name__ != 'relu': raise Exception('Layer ' + str(idx) + ' of tensorflow model does not have ReLU activation') def _node_redundancy_check(self) -> None: """ Determines which nodes in the ANN are redundant based on the current variable bounds. Results are stored in networkParam.redundancy_matrix. Always active nodes are marked with +1, always inactive ones with -1, non-redundant nodes with 0. """ for i in range(1, self.networkParam.n_layers): for j in range(self.networkParam.nodes_per_layer[i]): if self.networkParam.M_plus[i - 1][j] <= 0: self.networkParam.redundancy_matrix[i - 1][j] = -1 elif self.networkParam.M_minus[i - 1][j] >= 0: self.networkParam.redundancy_matrix[i - 1][j] = 1 def save_param(self, filename: str = 'ann_parameters') -> None: """ Saves the current variable bounds of the ANN as .npy files. Use load_param to load results into an ANN model. Parameters ---------- filename: File path where parameters are saved. """ np.save(filename + '.npy', [self.networkParam.M_plus, self.networkParam.M_minus], allow_pickle=True) def load_param(self, tf_model: tf.keras.Sequential, filename: str) -> None: """ Loads ANN variable bounds from .npy file generated by save_param. Parameters ---------- tf_model: The tensorflow model associated with the save parameters. filename: File path of saved parameters. """ self._init_network_param(tf_model) data = np.load(filename, allow_pickle=True) self.networkParam.M_plus = data[0] self.networkParam.M_minus = data[1] self.networkParam.UB[1:] = self.networkParam.M_plus self._paramIsLoaded = True
/reluMIP-1.0.0.tar.gz/reluMIP-1.0.0/relumip/ann_model.py
0.87982
0.536009
ann_model.py
pypi
import io import json from dataclasses import dataclass from functools import cached_property from typing import Any, Dict, List class Node: def __hash__(self): return id(self) @dataclass class ListNode(Node): children: List[Node] @property def section(self): return self.children and all(child.section for child in self.children) @cached_property def length(self): child_lengths = sum(child.length for child in self.children) if len(self.children) == 0: return 2 else: return child_lengths + 2 * (len(self.children) - 1) + 4 @dataclass class Pair: key: str value: Node @property def section(self): return self.value.section @dataclass class DictNode(Node): children: List[Pair] section: bool = True @cached_property def length(self): child_lengths = sum( len(pair.key) + 3 + pair.value.length for pair in self.children ) if len(self.children) == 0: return 2 else: return child_lengths + 2 * (len(self.children) - 1) + 4 @dataclass class LeafNode(Node): value: Any section = False @cached_property def length(self): return len(json.dumps(self.value)) def parse_tree(data): if isinstance(data, dict): return DictNode([Pair(k, parse_tree(v)) for k, v in data.items()]) elif isinstance(data, list): return ListNode([parse_tree(v) for v in data]) else: return LeafNode(data) def write_horizontal_list(obj, output, indent, max_width): output.write("[ ") for i, child in enumerate(obj.children): if i != 0: output.write(", ") write_compound(0, child, output, indent, max_width) output.write(" ]") def write_horizontal_dict(obj, output, indent, max_width): output.write("{ ") for i, pair in enumerate(obj.children): key, child = pair.key, pair.value if child != LeafNode(None): if i != 0: output.write(", ") key_str = f"{key} = " output.write(key_str) write_compound(0, child, output, indent, max_width) output.write(" }") def write_vertical_list(current_indent, obj, output, indent, max_width): output.write("[\n") for i, child in enumerate(obj.children): child_indent = current_indent + indent output.write(" " * child_indent) write_compound(child_indent, child, output, indent, max_width) if i != len(obj.children): output.write(", ") output.write("\n") output.write(" " * current_indent) output.write("]") def write_vertical_dict(current_indent, obj, output, indent, max_width): output.write("{\n") for i, pair in enumerate(obj.children): key, child = pair.key, pair.value if child != LeafNode(None): if i != 0: output.write(",\n") child_indent = current_indent + indent output.write(" " * child_indent) key_str = f"{key} = " output.write(key_str) write_compound(child_indent, child, output, indent, max_width) output.write("\n") output.write(" " * current_indent) output.write("}") def write_compound(current_indent, obj, output, indent, max_width): vertical = current_indent + obj.length > max_width if isinstance(obj, ListNode) and vertical: write_vertical_list(current_indent, obj, output, indent, max_width) elif isinstance(obj, ListNode) and not vertical: write_horizontal_list(obj, output, indent, max_width) elif isinstance(obj, DictNode) and vertical: write_vertical_dict(current_indent, obj, output, indent, max_width) elif isinstance(obj, DictNode) and not vertical: write_horizontal_dict(obj, output, indent, max_width) else: write_leaf(obj, output) def write_child(current_indent, child, output, indent, max_width): if isinstance(child, LeafNode): write_leaf(child, output) output.write("\n") else: write_compound(current_indent, child, output, indent, max_width) output.write("\n") def write_leaf(leaf, output): if isinstance(leaf.value, str) and len(leaf.value) > 255: output.write('"""') output.write(leaf.value) output.write('"""') else: output.write(json.dumps(leaf.value)) def write_section(section, output, indent, max_width): for pair in section.children: key, child = pair.key, pair.value if child != LeafNode(None): output.write(f"{key} = ") write_child(0, child, output, indent, max_width) output.write("\n") def dump(data, f, indent=4, max_width=100): output = f tree = parse_tree(data) blank_section = DictNode([]) sections = [("", blank_section)] for pair in tree.children: key, value = pair.key, pair.value if value.section: if isinstance(value, DictNode): sections.append((f"[{key}]", value)) elif isinstance(value, ListNode): for child in value.children: sections.append((f"[[{key}]]", child)) else: blank_section.children.append(Pair(key, value)) for key, section in sections: if key: output.write(key) output.write("\n") write_section(section, output, indent, max_width) def dumps(data, indent=4, max_width=100): f = io.StringIO() dump(data, f, indent, max_width) return f.getvalue()
/relycomply_cli-0.5.0-py3-none-any.whl/relycomply_cli/cleartoml.py
0.653569
0.29972
cleartoml.py
pypi
import json import textwrap from contextlib import contextmanager from pathlib import Path import toml from graphql.type.definition import ( GraphQLEnumType, GraphQLNonNull, GraphQLScalarType, ) from .helpers import deep_get gql_folder = Path(__file__).parent / "gql" def first_item(dct): return list(dct.items())[0] def node_is_terminal(obj): if isinstance(obj, (GraphQLNonNull)): return node_is_terminal(obj.of_type) elif isinstance(obj, (GraphQLScalarType, GraphQLEnumType)): return True else: return False def generate_default_node(obj): if isinstance(obj, GraphQLScalarType): return "" keys = "\n".join( [key for key, field in obj.fields.items() if node_is_terminal(field.type)] ) return "{\n" + keys + "\n}" def generate_node(node_type, support_templates): gql_templates = support_templates["GQL"] node_type_name = str(node_type) if node_type_name in gql_templates: return gql_templates[node_type_name] return generate_default_node(node_type) def get_list_field_config(node_type, support_templates): list_fields = support_templates["ListFields"] default_fields = ["id", "name", "label", "description"] return list_fields.get(node_type, default_fields) def format_node_from_dicts(node): if node: fields = "\n".join( [f"{key} {format_node_from_dicts(value)}" for key, value in node.items()] ) return "{\n" + fields + "\n}\n" else: return "" def generate_list_node(node_type, support_templates): fields = get_list_field_config(node_type, support_templates) node = {} for field in fields: parts = field.split(".") root = node stem, leaf = parts[:-1], parts[-1] for part in stem: if part not in root: root[part] = {} root = root[part] root[leaf] = None return format_node_from_dicts(node) def filter_list_fields(result, node_type, support_templates): fields = get_list_field_config(node_type, support_templates) new_nodes = [] for edge in result["edges"]: node = edge["node"] row = {} for field in fields: field_parts = field.split(".") if field_parts[0] in node: collapsed = node[field_parts[0]] row[field] = deep_get(collapsed, field_parts[1:]) new_nodes.append(row) return new_nodes class IndentWriter: """ A simple utility to help with witing indented structures """ def __init__(self): self.buffer = [] self.level = 0 @contextmanager def indent(self): self.increment() yield self.decrement() @contextmanager def space(self): self("") yield self("") def increment(self): self.level += 1 def decrement(self): self.level -= 1 def __call__(self, content): if isinstance(content, str): self([content]) else: self.buffer.extend([" " * self.level + line for line in content]) def result(self): return "\n".join(self.buffer) def format_graphql(call_type, args, field_name, node_path, node_gql): """ Formats a graphQL statement based on its parts """ wrt = IndentWriter() # Strips off the edge braces and clears and empty lines node_gql_body = list( filter( lambda line: line, textwrap.dedent(node_gql.strip().strip("{").strip("}")).split("\n"), ) ) wrt(f"{call_type}(") with wrt.indent(): wrt([(f"${name}: {type}") for name, type in args]) wrt(") {") with wrt.space(): with wrt.indent(): wrt(f"{field_name}(") with wrt.indent(): wrt([(f"{name}: ${name}") for name, _ in args]) wrt(") {") with wrt.indent(): with wrt.space(): for part in node_path[:-1]: wrt(part + " {") wrt.increment() if node_gql_body: wrt(node_path[-1] + " {") with wrt.space(): with wrt.indent(): wrt(node_gql_body) wrt("}") else: wrt(node_path[-1]) for part in node_path[1:]: wrt.decrement() wrt("}") wrt("}") wrt("}") result = wrt.result() return result def generate_endpoint(call_type, client, support_templates, field_name): if call_type == "mutation": root = client.schema.mutation_type elif call_type in ("retrieve", "list"): root = client.schema.query_type else: raise Exception("Unknown call type") root_field = root.fields[field_name] args = [(arg_name, str(arg.type)) for arg_name, arg in root_field.args.items()] field_type = root_field.type if call_type == "mutation": root_return_key, root_return_field = first_item(field_type.fields) root_return_type = root_return_field.type return_node = generate_node(root_return_type, support_templates) return format_graphql( "mutation", args, field_name, [root_return_key], return_node ) elif call_type == "retrieve": # Basically this gets us edges.node while going through # all the NonNull and List Shit root_return_type = ( field_type.fields["edges"].type.of_type.of_type.fields["node"].type ) return_node = generate_node(root_return_type, support_templates) return format_graphql("query", args, field_name, ["edges", "node"], return_node) elif call_type == "list": # Basically this gets us edges.node while going through # all the NonNull and List Shit root_return_type = ( field_type.fields["edges"].type.of_type.of_type.fields["node"].type ) return_node = generate_list_node(root_return_type.name, support_templates) return format_graphql("query", args, field_name, ["edges", "node"], return_node)
/relycomply_cli-0.5.0-py3-none-any.whl/relycomply_cli/generate_gql.py
0.480722
0.175079
generate_gql.py
pypi
from gql import Client from gql.transport.requests import RequestsHTTPTransport import requests from relycomply_client.exceptions import RelyComplyClientException from .gql_generator import GQLGenerator from gql import gql from gql.transport.exceptions import TransportProtocolError, TransportQueryError from .credential_sources import StandardCredentials from littleutils import only import logging log = logging.getLogger(__name__) class RelyComplyGQLClient: """ A flexible and intelligent GraphQL client for RelyComply. This client will create methods that match the mutation sand queries of the RelyComply API, and expose them with familiar calling conventions. It also handles paging as well as simplifying the returned structures. Queries can be called with their lowerCase field name and any filter arguments as kwargs, e.g.: client.products(nameContain="ZA") # Will return a list of products client.products(nameContain="ZA", _iter=True) # Will return a lazy generator client.products(name="retailZA", _only=True) # Will return only the first object or None Mutations can be called in a similar way, but arguments will be lifted into the $input variable client.createProduct(name="retailZA", label="South African Retail) # Returns the created product The interface is automatically generated from the GQL schema as well as the CLI support templates. Thus it should always be in sync. """ def __init__(self, **kwargs): credentials = StandardCredentials(**kwargs) log.debug( f"Credentials: {', '.join([f'{k}={v}' for k,v in credentials.credentials().items()])}" ) # Normalise the url to deal with older config files url = credentials.get("url") url = url.rstrip("/") if url.endswith("/graphql"): url = url[:-8] # Setup a GQL client, pull creds from env transport = RequestsHTTPTransport( url=url + "/graphql/", verify=True, retries=3, headers={ "IMPERSONATE": credentials.get("impersonate"), "Authorization": f"Bearer {credentials.require('token')}", }, ) try: self.client = Client(transport=transport, fetch_schema_from_transport=True) with self.client as session: # This forces the system to grab the schema # GQL v3 lazily fetches teh schema, but that is no help because we need the schema # to setup the object dynamically pass except TransportProtocolError: raise RelyComplyClientException( f"Could not retrieve schema from the given url: {url}" ) except requests.exceptions.ConnectionError: raise RelyComplyClientException( f"Could not connect to the given url: {url}" ) except TypeError: raise RelyComplyClientException( "The server could not authenticate you, are you sure your token is correct." ) # Pull support templates self.templates = requests.get(url + "/cli/v1/support_templates/").json() self.schema = self.client.schema self.generator = GQLGenerator(self.schema, self.templates) self.mutation_fields = [] self.query_fields = [] self._attach_mutations() self._attach_queries() def _attach_mutations(self): for field in self.schema.mutation_type.fields.keys(): self._attach_mutation(field) def _attach_mutation(self, field): def mutation(**variables): return self.execute_mutation(field, variables) self.mutation_fields.append(field) setattr(self, field, mutation) def _attach_queries(self): for field in self.schema.query_type.fields.keys(): self._attach_query(field) def _attach_query(self, field): def query(_iter=False, _only=False, **variables): return self.execute_query(field, variables, _iter, _only) self.query_fields.append(field) setattr(self, field, query) def _collapse_edges(self, value): if isinstance(value, list): return [self._collapse_edges(child) for child in value] if isinstance(value, dict): replacement = {} for key, child in value.items(): if ( isinstance(child, dict) and len(child) == 1 and "edges" in child and isinstance(child["edges"], list) ): replacement[key] = [ self._collapse_edges(edge["node"]) for edge in child["edges"] ] else: replacement[key] = self._collapse_edges(child) return replacement else: return value def _only_value(self, result): return only(result.values()) def _execute(self, query, variables): result = self.client.execute(query, variable_values=variables) return self._only_value(result) def _endpoint_graphql(self, action, endpoint): return self.generator.generate_endpoint(action, endpoint) def _endpoint_table_graphql(self, action, endpoint): return self.generator.generate_table_endpoint(action, endpoint) def _execute_endpoint(self, action, endpoint, variables, table_mode=False): if table_mode: graphql = self._endpoint_table_graphql(action, endpoint) else: graphql = self._endpoint_graphql(action, endpoint) query = gql(graphql) try: return self._execute(query, variables) except TransportQueryError as e: errors = e.errors raise RelyComplyClientException(str(errors[0]["message"])) from e def execute_query(self, endpoint, variables, _iter=False, _only=False): if _only: try: return next(self._execute_query_iter(endpoint, variables)) except StopIteration: return None if _iter: return self._execute_query_iter(endpoint, variables) else: return list(self._execute_query_iter(endpoint, variables)) def execute_query_for_table(self, endpoint, variables): return self.generator.filter_list_fields( endpoint, self._execute_query_iter(endpoint, variables, table_mode=True) ) def _execute_query_iter(self, endpoint, variables, table_mode=False): after = None hasNextPage = True while hasNextPage: result = self._execute_endpoint( "query", endpoint, variables, table_mode=table_mode ) hasNextPage = result["pageInfo"]["hasNextPage"] for edge in result["edges"]: node = edge["node"] yield self._collapse_edges(node) if not hasNextPage: break else: after = result["pageInfo"]["endCursor"] variables["after"] = after def execute_mutation(self, endpoint, variables): result = self._execute_endpoint("mutation", endpoint, dict(input=variables)) return self._only_value(self._collapse_edges(result)) def graphql(self, graphql_query, variables, **kwargs): """ Execute a raw graphql query with the underlying client. No postprocessing will be done. This is useful because authentication credentials will be sorted out. kwargs will be passed through to the execute call of the raw client. """ query = gql(graphql_query) return self.client.execute(query, variable_values=variables, **kwargs)
/relycomply_client-0.13.3-py3-none-any.whl/relycomply_client/relycomply_gql_client.py
0.674908
0.180612
relycomply_gql_client.py
pypi
import io import json from dataclasses import dataclass from functools import cached_property from typing import Any, Dict, List class Node: def __hash__(self): return id(self) @dataclass class ListNode(Node): children: List[Node] @property def section(self): return self.children and all(child.section for child in self.children) @cached_property def length(self): child_lengths = sum(child.length for child in self.children) if len(self.children) == 0: return 2 else: return child_lengths + 2 * (len(self.children) - 1) + 4 @dataclass class Pair: key: str value: Node @property def section(self): return self.value.section @dataclass class DictNode(Node): children: List[Pair] section: bool = True @cached_property def length(self): child_lengths = sum( len(pair.key) + 3 + pair.value.length for pair in self.children ) if len(self.children) == 0: return 2 else: return child_lengths + 2 * (len(self.children) - 1) + 4 @dataclass class LeafNode(Node): value: Any section = False @cached_property def length(self): return len(json.dumps(self.value)) def parse_tree(data): if isinstance(data, dict): return DictNode([Pair(k, parse_tree(v)) for k, v in data.items()]) elif isinstance(data, list): return ListNode([parse_tree(v) for v in data]) else: return LeafNode(data) def write_horizontal_list(obj, output, indent, max_width): output.write("[ ") for i, child in enumerate(obj.children): if i != 0: output.write(", ") write_compound(0, child, output, indent, max_width) output.write(" ]") def write_horizontal_dict(obj, output, indent, max_width): output.write("{ ") for i, pair in enumerate(obj.children): key, child = pair.key, pair.value if child != LeafNode(None): if i != 0: output.write(", ") key_str = f"{key} = " output.write(key_str) write_compound(0, child, output, indent, max_width) output.write(" }") def write_vertical_list(current_indent, obj, output, indent, max_width): output.write("[\n") for i, child in enumerate(obj.children): child_indent = current_indent + indent output.write(" " * child_indent) write_compound(child_indent, child, output, indent, max_width) if i != len(obj.children): output.write(", ") output.write("\n") output.write(" " * current_indent) output.write("]") def write_vertical_dict(current_indent, obj, output, indent, max_width): output.write("{\n") for i, pair in enumerate(obj.children): key, child = pair.key, pair.value if child != LeafNode(None): if i != 0: output.write(",\n") child_indent = current_indent + indent output.write(" " * child_indent) key_str = f"{key} = " output.write(key_str) write_compound(child_indent, child, output, indent, max_width) output.write("\n") output.write(" " * current_indent) output.write("}") def write_compound(current_indent, obj, output, indent, max_width): vertical = current_indent + obj.length > max_width if isinstance(obj, ListNode) and vertical: write_vertical_list(current_indent, obj, output, indent, max_width) elif isinstance(obj, ListNode) and not vertical: write_horizontal_list(obj, output, indent, max_width) elif isinstance(obj, DictNode) and vertical: write_vertical_dict(current_indent, obj, output, indent, max_width) elif isinstance(obj, DictNode) and not vertical: write_horizontal_dict(obj, output, indent, max_width) else: write_leaf(obj, output) def write_child(current_indent, child, output, indent, max_width): if isinstance(child, LeafNode): write_leaf(child, output) output.write("\n") else: write_compound(current_indent, child, output, indent, max_width) output.write("\n") def write_leaf(leaf, output): if isinstance(leaf.value, str) and len(leaf.value) > 255: output.write('"""') output.write(leaf.value) output.write('"""') else: output.write(json.dumps(leaf.value)) def write_section(section, output, indent, max_width): for pair in section.children: key, child = pair.key, pair.value if child != LeafNode(None): output.write(f"{key} = ") write_child(0, child, output, indent, max_width) output.write("\n") def dump(data, f, indent=4, max_width=100): output = f tree = parse_tree(data) blank_section = DictNode([]) sections = [("", blank_section)] for pair in tree.children: key, value = pair.key, pair.value if value.section: if isinstance(value, DictNode): sections.append((f"[{key}]", value)) elif isinstance(value, ListNode): for child in value.children: sections.append((f"[[{key}]]", child)) else: blank_section.children.append(Pair(key, value)) for key, section in sections: if key: output.write(key) output.write("\n") write_section(section, output, indent, max_width) def dumps(data, indent=4, max_width=100): f = io.StringIO() dump(data, f, indent, max_width) return f.getvalue()
/relycomply_client-0.13.3-py3-none-any.whl/relycomply_client/cleartoml.py
0.653569
0.29972
cleartoml.py
pypi
# Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at remQte@fooobaaar.de. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see the FAQ at https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
/remqte-0.2.1.tar.gz/remqte-0.2.1/CODE_OF_CONDUCT.md
0.5794
0.679525
CODE_OF_CONDUCT.md
pypi
1 Introduction The ReMAP SDK has been created in the context of the ReMAP project inside the WP2, it enables the algorithms for prognostics and diagnostics to use the data coming from the airline nodes, this first version is focused on WP5. Only using this SDK the models will be able to has access to this data and the metadata describing the data sources created by the airline staff. This document and the design of this first ReMAP SDK version has been developed from the requirements collected in the document ReMAP ‘tasets for WP5’ describing the operations that algorithms within the ReMAP project need to interact with the data. The ReMAP SDK has been developed for python and can be found on the python repository PyPI. 2 SDK The ReMAP SDK is writen in python and designed to work inside the ReMAP platform to have access to the data and metadata, hence it must be used only inside the ReMAP platform, A testing environment will be developed including this public available python module. This version of the SDK has been developed in python and supports python 2 and python 3, following the requirements found for WP5, it can be found on the pip repository for python in the url https://pypi.org/project/remapSDK/. The SDK contains the python code for the SDK and some python code for demonstration including some data to perform the tests, these files are just for demonstration purposes and the data within this files does not come from any real aircraft component. 2.1 SDK Structure The SDK can be downloaded from PyPI in the url mentioned above, once downloaded you can find this folder structure: sdk | remapSDK | |- __init__.py #packaging file | |- remapSDK.py #python code | |- demo #demo folder | | |- __init__.py #packaging file | | |- test_remapSDK.py #demo code | | |- testing_env.py #demonstration environment | | |- data #data folder | | |- dataset.csv #data file in csv format | | |- tasks.csv #tasks file in csv format | | |- schedule.csv #schedule file in csv format | | |- metadata.json #metadata file in json format | | |- sdk_config.json #File containing SDK configuration information | | |- secret #File containing sdk configuration information |- README.MD #Description and usage of the module |- setup.py #Python packaging information for the module The files __init__.py are packaging files for python modules. The demo folder contains the python code to test the SDK and to simulate the ReMAP environment. The data folder contains fake data just for demonstration purposes. The ReMAP platform serves data files automatically to the SDK through the environment, for demonstrartion purposes the SDK expects to find these data files are provided under the demo directory, the information on these files is fake and does not come from any real aircraft. 2.2. SDK Methods As part of the security control, the models only can access the data using the functions of the ReMAP SDK. The SDK provides the methods needed to get any information related to the data set and the dataset itself. getStartTime () : timestamp - Returns the start timestamp defined for the dataset getEndTime (): timestamp - Returns the end timestamp defined for the dataset getTailNumber () : string - Returns the aircraft’s tail number for the dataset getParamPartNumber (ParamName) : string - Returns the part number for the parameter passed to the function getAircraft () : json - Returns the aircraft model for this dataset getMetadata (): metadata [] - Returns the JSON containing the metadata for the model. See Annex to see the json format getReplacements () : replacement [] - Returns the list of the replacements including parameter, part number and replacement date, if someone occurs. See annex to see the json format. getDataset () : String - Returns the route to the dataset file. Useful to retrieve the file and access directly to the information inside it. getSchedule () : String - Returns the route to the schedule file. Useful to retrieve the file and access directly to the information inside it. getTasks () : String - Returns the route to the tasks file. Useful to retrieve the file and access directly to the information inside it. sendOutput(jsonoutput) : json - Send the output of the model to the ReMAP platform to be stored, Returns the output sent with the mongo id of the database. This function expects a JSON with the following structure: { "rulUnit": "test_rul_unit", "rulValue": 5, "distributionType": "Normal", "distributionParameters": [ { name: "mean", value: 824 }, { name: "std", value: 13.2 } ], "confidenceInterval": { "min": 800, "max": 850 } } - rulUnit: String. Unit of the output eg. Flight cycles, flight hours - rulValue: Number. the value of the rul output with unit above, eg. 400 - distributionType: String. Type of distribution (Normal, Exponential…) - distributionParameters: Array. Array of distribution parameters - name: String - value: Number confidenceInterval: - min: Number. Confidence interval lower bound - max: Number. Confindence interval upper bound sendScheduleOutput(jsonoutput) : json - Send the output of the model to the ReMAP platform to be stored, Returns the output sent with the mongo id of the database. 3 SDK Installation The SDK has been developed in python3, it has been packaged as a python module and uploaded to PYPI (Python Pakage Index) to make it publicly available. It can be found in: https://pypi.org/project/remapSDK/. It is highly recommended to install always the latest version in the repository. To install the SDK we recommend to use Pip, a python Package magament tool, that helps to install and manage python modules, you can use a different one if you like. Before starting with the installation check that you have the correct python version and pip installed. Once you have this prerequisites, to intall the sdk type in your terminal: >> pip install 'remapSDK' To upgrade the latest version of the module: >>pip install --upgrade PackageName Once the module is installed with pip, you can start using it in your python script in you IDE. For more information about python modules installation visit: https://packaging.python.org/tutorials/installing-packages/ 4 SDK Usage Once you have installed python3 and the ReMAP SDK you can start creating your python script and using the SDK module to access the aircraft data and metadata. To use the Remap SDK it needs to be imported in your script, from remapSDK import remapSDK the remapSDK is the module to be imported from the remapSDK Folder. If the module has been installed with pip you do not need to change this import line, if you have moved or change the name of the folder containing the module, you will need to update this line. Create and SDK instance: The SDK is a python class and needs to be instatiated to be configured properly: remapSdk=remapSDK.Sdk() Once you have created an instance of the sdk class you can start using the methods in the sdk described in section 2.2. This is an example of using the sdk methods: start=remapSdk.getStartTime() print(start) end_date=remapSdk.getEndTime() print(end_date) tailno=remapSdk.getTailNumber() print(tailno) partNo=remapSdk.getParamPartNumber("param1") print(partNo) partNo=remapSdk.getMetadata() print(partNo) partNo=remapSdk.getReplacements() print(partNo) To export the result of the algorithm we need to create a json object with the output: this output json has a format described in section 2.2. Later, this json is passed as an argument to the sendOutput(json) method of the sdk as parameter. This method of the sdk sent this json to the ReMAP platform to be stored and returns the stored document in the database jsonoutput= { "rulUnit": "test_rul_unit", "rulValue": 5, "distributionType": "Normal", "distributionParameters": [ { "name": "mean", "value": 824 }, { "name": "std", "value": 13.2 } ], "confidenceInterval": { "min": 800, "max": 850 } } output=remapSdk.sendOutput( jsonoutput) print(output) 5 SDK Demo The ReMAP SDK has been developed to work in the ReMAP platform inside an environment with configuration files, its use outside the platform is discouraged as the ReMAP environment must be emuated not just the configuraiton files but also the APIs the SDK uses to interact, extract the authentication token and send the output. To ease and illustrate the use of the sdk a demo environment has been added to the sdk. This environment is recreated with two folders, data folder contains the configuration files the SDK needs to work, the tests folder contains two mains pyhton files besides the __init__.py, the testing_env.py file contains the python code to emulate the this environment, the test_remap.py file launch the SDK tests. Note that the testing environment runs a REST API Server on port 5000, you can change the port number inside this file. 6 SDK Requirements and dependencies The SDK has some requirements to work work with it. - Python3: It has been developed using this version of python. - Pip: This is the python package manager enabling us to install the SDK. - The SDK will NOT WORK outside the ReMAP platform The ReMAP SDK has some extra dependencies to work, they can be seen in the requirements.txt file under the root directory, in this file the modules required by the SDK are listed, and will be automatically installed when install the SDK with the pip install command: - Request The requests module allows the SDK to send HTTP requests using Python. This will allow the SDK to obtain the access token to for security environment and send the output to the ReMAP repository. - Flask Flask is a lightweight web application framework designed to make getting started quick and easy, with the ability to scale up to complex applications. The testing environment uses this module to emulate the ReMAP environment. This requirement is only for the demo and does not affect to the SDK.
/remapSDK-0.3.4.tar.gz/remapSDK-0.3.4/README.md
0.727975
0.842021
README.md
pypi
# Description: Document # Documentation: data_structures.txt import os.path import string import six from Remark.FileSystem import unixDirectoryName, unixRelativePath, fileExtension from Remark.DocumentType_Registry import documentType class Document(object): def __init__(self, relativeName): ''' Constructs a document-object for the given file. relativeName: The path to the file, relative to the document-tree's root-directory. ''' # The relative-path to the document, with respect to # the document-tree's root-directory. It is important # that the relative-name is in the unix-form. This is # being relied upon elsewhere (e.g. Gallery_Macro # creates an md5-digest from the relative-name; # this must be portable across operating systems). self.relativeName = unixDirectoryName(relativeName) # The relative-directory and the filename of the document. self.relativeDirectory, self.fileName = os.path.split(relativeName) # The file-name extension of this document, in lower-case # to enable case-insensitivity. self.extension = fileExtension(self.fileName).lower() # The document-type of this document. self.documentType = documentType(self.extension) # The parent-document of this document. self.parent = None # A map from document's relative-name (string) to a # document-object (Document). self.childSet = {} # A map from a tag-name (string) to a text # (list of strings). self.tagSet = {} # The predefined document-tags. self.setTag('description') self.setTag('detail') self.setTag('author') self.setTag('file_name', [self.fileName]) self.setTag('relative_name', [self.relativeName]) self.setTag('relative_directory', [self.relativeDirectory]) self.setTag('extension', [self.extension]) self.setTag('html_head') self.setTag('document_type', [self.documentType.name()]) # This will be filled in later, after the # description-tags have been parsed. self.setTag('link_description') # Whether the document should be generated. # By default the document is not generated; # the regeneration rules change this later. self.regenerate_ = False def setRegenerate(self, regenerate): self.regenerate_ = regenerate def regenerate(self): return self.regenerate_ def insertChild(self, child): ''' Inserts a new child-document for this document. A document can be only be linked to at most one parent-document. ''' assert child.parent == None self.childSet[child.relativeName] = child child.parent = self def setTag(self, tagName, text = ['']): ''' Associates text with a given tag-name. tagName (string): The name of the tag. It will be stripped of surrounding whitespace. text (list of strings): The text to associate to the tag-name. ''' assert isinstance(text, list) assert isinstance(tagName, six.string_types) self.tagSet[tagName.strip()] = text def tag(self, tagName, defaultText = ['']): ''' Returns the text associated with the given tag-name. If the tag-name is not found, returns the given default-value instead. tagName (string): The tag-name to find. It will be stripped of surrounding whitespace. ''' assert isinstance(tagName, six.string_types) return self.tagSet.get(tagName.strip(), defaultText) def tagString(self, tagName, default = ''): ''' Returns the tag-text associated with the given tag-name, such that the lines of the tag-text are joined together into a single string. ''' return ''.join(self.tag(tagName, [default])) def tagInteger(self, tagName, default = 0): ''' Returns the integer associated with the given tag-name. The tag-text is first interpreted as a single string, which is then converted to an integer. ''' if not tagName in self.tagSet: return default return int(self.tagString(tagName)) def linkDescription(self): ''' Returns the link-description of the document. returns: The link-description given by the document-type, if the document has a document-type. Otherwise the empty string. ''' type = self.documentType if type == None: return '' return self.documentType.linkDescription(self)
/remark-1.7.9.tar.gz/remark-1.7.9/Remark/Document.py
0.770292
0.34381
Document.py
pypi
# Description: Document type registry # Documentation: data_structures.txt from Remark.FileSystem import fileExtension, unixDirectoryName import six _associationSet = dict() _defaultDocumentType = None _documentTypeSet = dict() def setDefaultDocumentType(documentType): ''' Sets the default document-type. This document-type will be returned by documentType() in case an associated document-type can not be found. documentType (DocumentType or string): The document-type object to use as a default document-type. See also: documentType() ''' if isinstance(documentType, six.string_types): documentType = findDocumentType(documentType) global _defaultDocumentType _defaultDocumentType = documentType def registerDocumentType(name, documentType): _documentTypeSet[name] = documentType def findDocumentType(name): return _documentTypeSet.get(name) def associateDocumentType(inputExtension, documentType): ''' Associates the given filename-extension, or a set of filename-extensions, to the given document-type object. The filename-extension-key is always stored lower-case, so that we can be case-insensitive for it. inputExtension (string or list-of-strings): The file-extensions to associate to the given document-type. documentType (DocumentType or string): The document-type object to associate to the file-extensions. ''' if isinstance(documentType, six.string_types): documentType = findDocumentType(documentType) global _associationSet if isinstance(inputExtension, six.string_types): _associationSet[inputExtension.lower()] = documentType return for extension in inputExtension: associateDocumentType(extension, documentType) def strictDocumentType(inputExtension): ''' Returns the document-type object associated to a given filename-extension. The filename-extension comparison is case-insensitive. inputExtension (string): The file-extension for which to retrieve the document-type. returns (DocumentType): The associated document-type object, if such can be found. Otherwise None. ''' return _associationSet.get(inputExtension.lower()) def documentType(inputExtension): ''' Returns the document-type object associated to a given filename-extension. The filename-extension comparison is case-insensitive. inputExtension (string): The file-extension for which to retrieve the document-type. returns (DocumentType): The associated document-type object, if such can be found. Otherwise the default document-type object. ''' return _associationSet.get(inputExtension.lower(), _defaultDocumentType) def outputDocumentName(inputPath): ''' Returns the name of the output-document filename given the input-document filename. The output-document filename is decided by the document-type associated to the file-extension of the input-document filename. name (string): The path to the input-document. returns (string): The path to the output-document. ''' inputExtension = fileExtension(inputPath) type = documentType(inputExtension) outputPath = type.outputName(inputPath) return unixDirectoryName(outputPath)
/remark-1.7.9.tar.gz/remark-1.7.9/Remark/DocumentType_Registry.py
0.828315
0.313302
DocumentType_Registry.py
pypi
# Description: CppCode macro # Detail: Generates colored html from C++ source code. import string import re from Remark.Macro_Registry import registerMacro from Remark.FileSystem import unixRelativePath, unixDirectoryName, globalOptions, htmlRegion from pygments import highlight from pygments.lexers import CppLexer from pygments.formatters import HtmlFormatter class CppCode_Macro(object): def name(self): return 'CppCode' def expand(self, parameter, remark): # Extract the documentation for types and functions. text = self._extractDocumentation(parameter) # Hilight the text. hilightedText = highlight('\n'.join(parameter), CppLexer(), HtmlFormatter()) # Prepare for Remark output. hilightedText = hilightedText.split('\n') # Copy the source and replace the includes with links. includeRegex = re.compile(r'(#include[ \t]+(?:(?:&quot)|(?:&lt));)(.*)((?:(?:&quot)|(?:&gt));)') replacer = lambda match: self._linkConverter(match, remark) for line in hilightedText: # Replace include file names with links to source files. text.append(re.sub(includeRegex, replacer, line)) return htmlRegion(text) def expandOutput(self): return False def htmlHead(self, remark): return [] def postConversion(self, remark): None def _extractDocumentation(self, text): text = [] # linearText = "\n".join(text) # linearText.expandtabs(globalOptions().tabSize) # oneLineRegexStr = r'(?://!(.*)\n)' # multiLineRegexStr = r'(?:/\*![ \t]*(.*)\*/)' # documentRegex = re.compile( # oneLineRegexStr + r'|' + # multiLineRegexStr) return text def _linkConverter(self, regexMatch, remark): document = remark.document documentTree = remark.documentTree searchName = unixDirectoryName(regexMatch.group(2)) includeName = regexMatch.group(2) linkDocument, unique = documentTree.findDocument(searchName, document.relativeDirectory, checkShorter = False) if not unique: # We don't accept ambiguous links. remark.reportWarning('Include filename ' + searchName + ' is ambiguous. Skipping linking.', 'ambiguous-include') linkDocument = None if linkDocument == None: # No file was found. Skip linking. return regexMatch.group(0) linkName = unixRelativePath(document.relativeDirectory, linkDocument.relativeName) + '.htm' return regexMatch.group(1) + '<a href = "' + linkName + '">' + includeName + '</a>' + regexMatch.group(3).rstrip() registerMacro('CppCode', CppCode_Macro())
/remark-1.7.9.tar.gz/remark-1.7.9/Remark/Macros/CppCode_Macro.py
0.704364
0.225523
CppCode_Macro.py
pypi
import fnmatch import json import time import os.path import itertools import traceback from tempfile import NamedTemporaryFile from uuid import uuid4 from lazy import lazy from progress.bar import Bar from io import BytesIO import remarkable_fs.rM2svg try: from json import JSONDecodeError except ImportError: JSONDecodeError = ValueError class Node(object): """A document or collection on the reMarkable. Most of the properties below are read-write, but to persist any changes to the reMarkable, you must call save().""" def __init__(self, root, id, metadata): """Create a new Node object. Unless you are hacking on this module, you do not want to do this. Instead, you can get existing documents by indexing into the DocumentRoot, or create new ones with Collection.new_document or Collection.new_collection. For those hacking on this module, creating a node object requires the following steps: * The correct class must be chosen for the node (either Collection, Document or NewDocument). * An object of that class is created, passing in the DocumentRoot and the node's id and metadata (which is stored as a dict). A new id can be created using new_id(). Metadata can be read using DocumentRoot.read_metadata, or created using initial_metadata. * The node is registered using DocumentRoot.register_node(). * The node is added to the directory hierarchy by calling link(). This can only be called if the parent node has been created, which is why it is not done automatically. The easiest way to create a node is to write the metadata to the reMarkable, and then call DocumentRoot.load_node() to load it. That is what Collection.new_collection() does, for example.""" self.root = root self.id = id self.metadata = metadata self.modified = False if metadata is not None: self.file_name = self.name def __repr__(self): return "%s(%s, %s)" % \ (type(self).__name__, self.id, self.name) def link(self): """Add a node to the directory hierarchy. May only be called after the parent node has been loaded. Unless you are hacking on this module, you do not want this function.""" self.parent = self.root.find_node(self.metadata["parent"]) if self.parent is not None: self.parent.add_child(self) def _rw(name, doc): """Creates a property which references a metadata field. On update, the metadata is marked as being modified.""" def get(self): return self.metadata[name] def set(self, val): self.metadata["synced"] = False self.metadata["metadatamodified"] = True self.metadata["version"] += 1 self.metadata[name] = val self.modified = True return property(fget=get, fset=set, doc=doc) name = _rw("visibleName", "The document name.") deleted = _rw("deleted", "True if the document has been deleted.") data_modified = _rw("modified", "True if the data in the document has been modified.") pinned = _rw("pinned", "True if the document is bookmarked.") @property def metadata_modified(self): """True if the metadata of the document has been modified.""" return self.metadata["metadatamodified"] @property def size(self): """The approximate size of the document in bytes.""" return 0 @property def mtime(self): """The modification time of the document.""" if self.metadata is None: return time.time() else: return int(int(self.metadata["lastModified"])/1000) def save(self): """Write the document to the reMarkable if it has been changed.""" if self.modified: self.root.write_metadata(self.id, self.metadata) self.modified = False def rename(self, parent, file_name): """Rename the document. Arguments are the parent node and the new filename.""" self.parent.remove_child(self) self.name = strip_extension(file_name) self.file_name = file_name self.metadata["parent"] = parent.id self.parent = parent self.parent.add_child(self) self.save() def delete(self): """Delete the document.""" self.parent.remove_child(self) self.deleted = True self.save() class Collection(Node): """A reMarkable collection. You can index into a Collection as if it was a dict. The keys are filenames and the values are nodes.""" def __init__(self, root, id, metadata): super(Collection, self).__init__(root, id, metadata) self.children = {} self.children_pathnames = {} def new_collection(self, name): """Create a new collection. Returns the created node.""" id = new_id() metadata = initial_metadata(Collection.node_type(), name, self.id) self.root.write_metadata(id, metadata) self.root.write_content(id, {}) return self.root.load_node(id) def new_document(self, name): """Create a new document. Returns the created node. The document will not be written to the reMarkable until the node's save() method is called.""" id = new_id() metadata = initial_metadata(Document.node_type(), strip_extension(name), self.id) node = NewDocument(self.root, id, metadata, name) self.root.register_node(node) node.link() return node def add_child(self, child): """Add a node to this collection. Called by link(). Unless you are hacking on this module, you do not want this function.""" # Remove invalid chars name = child.file_name.replace("/", "-") # Disambiguate duplicate names e.g. Foo/bar, Foo-bar if name in self.children: for n in itertools.count(2): x = "%s (%d)" % (name, n) if x not in self.children: name = x break self.children[name] = child self.children_pathnames[child] = name def remove_child(self, child): """Remove a node from this collection. Called by rename() and delete(). Unless you are hacking on this module, you do not want this function.""" name = self.children_pathnames[child] del self.children[name] del self.children_pathnames[child] def get(self, file): """Look up a file in the collection. Returns a node, or None if not found.""" return self.children.get(file) def items(self): """Find all nodes in the collection.""" return self.children.items() def __repr__(self): return "%s(%s, %s, %s)" % \ (type(self).__name__, self.id, self.name, self.children) def __getitem__(self, key): return self.children[key] def __iter__(self): return iter(self.children) def __contains__(self, item): return item in self.children @staticmethod def node_type(): return "CollectionType" class DocumentRoot(Collection): """A collection representing the root of the reMarkable directory tree. Creating one of these will read in all metadata and construct the directory hierarchy. You can index into a DocumentRoot as if it was a dict. The keys are filenames and the values are nodes. You can also use find_node() to look up a node by id.""" def __init__(self, connection): """connection - a Connection object returned by remarkable_fs.connection.connect().""" super(DocumentRoot, self).__init__(self, "", None) self.nodes = {"": self} self.sftp = connection.sftp self.templates = {} paths = fnmatch.filter(self.sftp.listdir(), '*.metadata') bar = Bar("Reading document information", max=len(paths)) for path in paths: id, _ = os.path.splitext(path) self.load_node_without_linking(id) bar.next() for node in self.nodes.values(): node.link() bar.finish() def find_node(self, id): """Find a node by id. Returns None if not found.""" return self.nodes.get(id) @property def name(self): return "ROOT" def link(self): pass def load_node(self, id): """Read a node from the reMarkable and link it into the tree. Unless you are hacking on this module, you do not want this function.""" node = self.load_node_without_linking(id) if node is not None: node.link() return node def load_node_without_linking(self, id): """Read a node from the reMarkable, without linking it into the tree. Unless you are hacking on this module, you do not want this function.""" classes = [Document, Collection] classes_dict = {cls.node_type(): cls for cls in classes} metadata = json.loads(self.read_file(id + ".metadata").decode("utf-8")) try: cls = classes_dict[metadata["type"]] except KeyError: cls = Node try: node = cls(self, id, metadata) if not node.deleted: self.register_node(node) return node except (IOError, JSONDecodeError): traceback.print_exc() def register_node(self, node): """Register a node object. Unless you are hacking on this module, you do not want this function.""" self.nodes[node.id] = node def read_file(self, file): """Read a file from SFTP.""" return self.sftp.open(file, "rb").read() def write_file(self, file, data): """Write a file to SFTP.""" f = self.sftp.open(file, "wb") f.set_pipelined() f.write(memoryview(data)) def read_json(self, file): """Read a JSON file from SFTP and convert to a dict.""" return json.loads(self.read_file(file).decode("utf-8")) def write_json(self, file, value): """Write a JSON file from SFTP, given as a dict.""" self.write_file(file, json.dumps(value).encode("utf-8")) def read_metadata(self, id): """Read the metadata for a given id and convert to a dict.""" return self.read_json(id + ".metadata") def write_metadata(self, id, metadata): """Write the metadata for a given id, given as a dict.""" self.write_json(id + ".metadata", metadata) def read_content(self, id): """Read the .content file for a given id and convert to a dict.""" return self.read_json(id + ".content") def write_content(self, id, content): """Write the .content file for a given id, given as a dict.""" self.write_json(id + ".content", content) def read_template(self, name): """Read a particular template file. Returns a local filename.""" file = self.templates.get(name) if file is None: data = self.read_file("/usr/share/remarkable/templates/%s.png" % name) file = NamedTemporaryFile(suffix = ".png") file.write(data) file.flush() self.templates[name] = file return file.name class Document(Node): """A single document on the reMarkable.""" def __init__(self, root, id, metadata): super(Document, self).__init__(root, id, metadata) self.content = self.root.read_content(id) self.file_name = self.name + "." + self.file_type("pdf") self._size = self.root.sftp.stat(self.id + "." + self.file_type("lines")).st_size def file_type(self, default): """Return the type of file. If blank (corresponding to a .lines) file, returns default.""" return self.content["fileType"] or default @lazy def file(self): """A file handle to the file contents itself. If the file is a .lines file, this is auto-converted to PDF.""" ext = self.file_type("lines") file = self.root.sftp.open(self.id + "." + ext, "rb") if ext == "lines": templates = [] for template in self.root.read_file(self.id + ".pagedata").decode("utf-8").splitlines(): if template == "Blank": templates.append(None) else: templates.append(self.root.read_template(template)) file = convert_lines_file(file, templates) return file @property def size(self): return self._size def read(self, offset, length): """Read length bytes from position offset.""" self.file.seek(offset) return self.file.read(length) @staticmethod def node_type(): return "DocumentType" class NewDocument(Node): """A newly-created document, which (unlike an object of class Document) can be both read and written. On calling save(), the document is converted to PDF or EPUB (if necessary) and written to the remarkable. If the document could not be converted. an IOError is thrown. File names starting with a dot are not written to the reMarkable (they are treated as temporary files).""" def __init__(self, root, id, metadata, filename): super(NewDocument, self).__init__(root, id, metadata) self.modified = True self.buf = BytesIO() self.file_name = filename @property def size(self): return len(self.buf.getvalue()) def read(self, offset, length): """Read length bytes from position offset.""" return self.buf.getvalue()[offset:offset+length] def write(self, offset, data): """Read data to position offset.""" self.buf.seek(offset) self.buf.write(data) def truncate(self, length): """Truncate the file to a certain length.""" self.buf.truncate(length) def save(self): if not self.file_name.startswith(".") and not self.deleted: self.really_save() def really_save(self): # Don't save zero-size files - Finder creates them if self.modified and len(self.buf.getvalue()) > 0: try: (filetype, data) = convert_document(self.buf.getvalue()) except IOError: self.delete() raise self.root.write_content(self.id, {"fileType": filetype}) self.root.write_file(self.id + "." + filetype, data) super(NewDocument, self).save() def rename(self, parent, file_name): # If this file starts with a dot and now we want to rename it so it # doesn't, we can no longer treat it as a temporary file. if not file_name.startswith("."): self.really_save() super(NewDocument, self).rename(parent, file_name) def new_id(): """Generate a new document id.""" return str(uuid4()) def strip_extension(filename): """Remove the extension from a filename, if it is a recognised document type.""" name, ext = os.path.splitext(filename) if ext in [".pdf", ".djvu", ".ps", ".epub"]: return name return filename def initial_metadata(node_type, name, parent): """The .metadata for a newly-created node. node_type - value of 'type' field of .metadata file name - node name parent - parent id (not node object)""" return { "deleted": False, "lastModified": str(int(time.time()*1000)), "metadatamodified": True, "modified": True, "parent": parent, "pinned": False, "synced": False, "type": node_type, "version": 1, "visibleName": name } def convert_lines_file(file, templates): """Convert a .lines file to .pdf. file - input file as a file object templates - list of template filenames, one per page, each may be None. Returns output as a file object.""" outfile = NamedTemporaryFile(suffix = ".pdf", delete = False) outname = outfile.name outfile.close() remarkable_fs.rM2svg.lines2cairo(file, outname, templates) result = open(outname, "rb") try: os.unlink(outname) except OSError: # unlink will fail on windows pass return result def convert_document(data): """Convert a document to PDF or EPUB. Input is the document contents as a 'bytes'. Returns (filetype, converted contents) where filetype is either "pdf" or "epub" and converted contents is a 'bytes'. Raises IOError if the file could not be converted.""" convert = None if data.startswith(b"%PDF"): filetype = "pdf" elif data.startswith(b"AT&TFORM"): filetype = "pdf" suffix = ".djvu" convert = "ddjvu --format=pdf" elif data.startswith(b"%!PS-Adobe"): filetype = "pdf" suffix = ".ps" convert = "ps2pdf" elif data.startswith(b"PK"): filetype = "epub" else: raise IOError("Only PDF, epub, djvu and ps format files supported") if convert is not None: infile = NamedTemporaryFile(suffix = suffix) outfile = NamedTemporaryFile(suffix = ".pdf") infile.write(data) infile.flush() res = os.system("%s %s %s" % (convert, infile.name, outfile.name)) if res != 0: raise IOError("Could not run %s" % convert) data = outfile.read() return (filetype, data)
/remarkable-fs-0.1.2.tar.gz/remarkable-fs-0.1.2/remarkable_fs/documents.py
0.652795
0.214465
documents.py
pypi
from enum import Enum from functools import partial from itertools import chain, groupby from operator import itemgetter import click import fitz from shapely import ops from shapely.geometry import MultiPolygon, Polygon, box from .parsing import content_contains_highlight, highlighter_lines import os import textwrap from collections import defaultdict # TODO: Warn if highlights appear 'sloppy' mean diff from 100% area coverage on words? WordSelectionMethod = Enum("WordSelectionMethod", "CENTROID AREA_RATIO") DEFAULT_AREA_RATIO = 0.5 # TODO: Allow CLI control of this def word_is_highlighted(method, highlight_poly, word_box): """Check if the word box is highlighted by the given highlight polygon with the provided method. The centroid method is more robust against vertically drifting lines, especially as the text boxes tend to overlap and that can lead to more area that it would appear being selected. """ if method == WordSelectionMethod.CENTROID: return highlight_poly.contains(word_box.centroid) if method == WordSelectionMethod.AREA_RATIO: overlap = highlight_poly.intersection(word_box) overlap_ratio = overlap.area / word_box.area return overlap_ratio > DEFAULT_AREA_RATIO raise ValueError(f"Unknown word selection method: {method}") HighlightType = Enum("HighlightType", "TEXTUAL SELECTION") def classify_highlight(highlight_poly, clipping_area_threshold): """Determine if the highlight polygon is a textual selection, or a clipping selection. If the polygon has precisely one interior ring, and is of sufficient area we will consider it to be a clipping selection, otherwise it will be classified as textual. """ if len(highlight_poly.interiors) == 1: # TODO: The CropBox area can vary significantly. # Maybe use a ratio of the interior to the crop box area? if Polygon(highlight_poly.interiors[0]).area > clipping_area_threshold: return HighlightType.SELECTION return HighlightType.TEXTUAL def classify_highlights(polys, clipping_area_threshold): """Group the highlight polygons based on their classification.""" text_highlights = [] selection_highlights = [] for poly in polys: highlight_type = classify_highlight(poly, clipping_area_threshold) if highlight_type == HighlightType.TEXTUAL: text_highlights.append(poly) elif highlight_type == HighlightType.SELECTION: selection_highlights.append(poly) return text_highlights, selection_highlights def coordinate_transformer(page): """Provide a transformer that maps PDF graphics coordinates to Fitz coordinates (and back). PyMuPDF uses y=0 for the top of the page, but the PDF format (and our debug plotting code) use y=0 for the bottom of the page. We choose to make the PDFs into fitz coordinates because shapely makes such transformations very simple to express. """ def to_fitz_coord(x, y): # PyMuPDF uses y=0 for the top, but pdf uses y=0 for the bottom return x, page.CropBox[-1] - y return partial(ops.transform, to_fitz_coord) def extract_highlight_lines(doc, page): """Extract the highlighter line geometries from the page. All the real work is getting done in the parsing code, but it is important that we apply the coordinate transform immediately after the lines are extracted so we never have to deal with different coordinate spaces. """ polys = [] for xref in page._getContents(): # pylint: disable=protected-access if not doc.isStream(xref): continue content = doc.xrefStream(xref) if content_contains_highlight(content): polys.extend(highlighter_lines(content)) to_fitz_coords = coordinate_transformer(page) return [to_fitz_coords(poly) for poly in polys] def normalize_polys(geometry): """Turn MultiPolygons into their constituent geometries, and Polygons into singleton lists. When we take the union of all the highlight lines, we may get 1 or n distinct polygons. This is used to treat both cases identically. """ if geometry.geom_type == "MultiPolygon": return geometry.geoms if geometry.geom_type == "Polygon": return [geometry] raise ValueError(f"Unexpected geometry type: {geometry.geom_type}") def merge_highlight_lines(lines): """Take the union of the line geometries and break them into distinct polygons.""" union = ops.unary_union(lines) return normalize_polys(union) def extract_clips(selection_polys, page, clip_zoom): """Get Pixmaps for each of the given selection polygons.""" for selection_poly in selection_polys: # TODO: Enable masking by the interior of the poly selection_rect = fitz.Rect(*selection_poly.exterior.bounds) # TODO: Enable rendering without the yellow lines yield page.getPixmap( clip=selection_rect.round(), matrix=fitz.Matrix(clip_zoom, clip_zoom) ) def extract_text_highlights(text_highlights, page, word_selection_method, max_skip_len): """Extract the highlighted text with the provided method, allowing up to max_skip_len skips. If a highlight path wanders for a couple of words but then returns, it is annoying to have two distinct textual selections and also not know what the intermediate words are. Thus, we allow for the case where a couple words are skipped. It is unlikely that two intentionally distinct highlights are only seperated by a couple of words, and if they are it will cause much less harm to include more words than to exclude them. The algorithm to compute the selections is greatly complicated by this requirement however. It is certainly possible to refactor this into a single imperative loop, but after messing up the implementation with that approach several times I resorted to a somewhat ugly, but more easy to reason about implementation based on groupby. """ text_highlight = MultiPolygon(text_highlights) # NOTE: If the skip logic proves to be finnicky with adjacent, yet distinct polys, it is # possible to instead look at each polygon by itself instead of merging them all into one # mega MultiPolygon. words = page.getText("words") word_boxes = [ (word, box(x0, y0, x1, y1)) for x0, y0, x1, y1, word, _, _, _ in words ] is_highlighted = partial(word_is_highlighted, word_selection_method, text_highlight) runs = [ (is_selected, list(map(itemgetter(0), words))) for is_selected, words in groupby( word_boxes, key=lambda t: is_highlighted(t[1]) ) ] marked_skips = [ (is_selected or len(run) <= max_skip_len, run) for is_selected, run in runs ] merged_runs = [ list(chain.from_iterable(map(itemgetter(1), runs_to_merge))) for is_selected, runs_to_merge in groupby(marked_skips, key=itemgetter(0)) if is_selected ] return [" ".join(run) for run in merged_runs] def extract_highlights( doc, max_skip_len, word_selection_method, clip_area_threshold, clip_zoom, debug_render, ): page_text_highlights = defaultdict(list) page_clips = defaultdict(list) for page in doc: highlight_lines = extract_highlight_lines(doc, page) if not highlight_lines: continue highlight_polys = merge_highlight_lines(highlight_lines) text_highlight_polys, selection_highlight_polys = classify_highlights( highlight_polys, clip_area_threshold ) if debug_render: # pylint: disable=import-outside-toplevel import matplotlib.pyplot as plt debug_page(page, text_highlight_polys, selection_highlight_polys) plt.show() if selection_highlight_polys: selection_highlights = extract_clips( selection_highlight_polys, page, clip_zoom ) page_clips[page.number + 1].extend(selection_highlights) if text_highlight_polys: text_highlights = extract_text_highlights( text_highlight_polys, page, WordSelectionMethod[word_selection_method], max_skip_len, ) page_text_highlights[page.number + 1].extend(text_highlights) return dict(page_text_highlights), dict(page_clips) def debug_page(page, text_highlights, selection_highlights): """Plot the word boxes and highlights for a particular page. After calling this, you must still use plt.show() to see the result! We don't call it here to avoid blocking on each page, although that is still possible to do if you want. """ # pylint: disable=import-outside-toplevel,too-many-locals import matplotlib.pyplot as plt import descartes _, _, page_width, page_height = page.CropBox fig = plt.figure() ax = fig.gca() ax.set_xlim((0, page_width)) ax.set_ylim((0, page_height)) ax.set_aspect("equal") flip = coordinate_transformer(page) words = page.getText("words") word_boxes = [box(x0, y0, x1, y1) for x0, y0, x1, y1, word, _, _, _ in words] for word_box in word_boxes: word_patch = descartes.PolygonPatch(flip(word_box)) ax.add_patch(word_patch) for text_highlight in text_highlights: highlight_patch = descartes.PolygonPatch( flip(text_highlight), fc="yellow", alpha=0.5 ) ax.add_patch(highlight_patch) for selection_highlight in selection_highlights: selection_patch = descartes.PolygonPatch( flip(selection_highlight), fc="orange", alpha=0.7 ) ax.add_patch(selection_patch) @click.command() @click.argument("filename", type=click.Path(exists=True, dir_okay=False, readable=True)) @click.option( "--out", type=click.Path(), default=None, help="Directory for output. By default the filname without the PDF extension is used.", ) @click.option( "--max-skip-len", default=3, help="Number of words that can be skipped without being excluded from a highlight.", ) @click.option( "--word-selection-method", type=click.Choice([m.name for m in WordSelectionMethod], case_sensitive=False), default=WordSelectionMethod.CENTROID.name, help="How to determine if a particular word has been highlighted.", ) @click.option( "--clip-area-threshold", default=1000, help="How much area a clipping must enclose to be considered a clipping.", ) @click.option( "--clip-zoom", default=3, help="How much to zoom in for the rendering of a clip. Increase for better quality.", ) @click.option( "--yes", default=False, is_flag=True, help="WARNING: Potentially destructive! Answer yes to any interactive prompts.", ) @click.option( "--debug-render", is_flag=True, default=False, help="Render the highlights and text boxes for each page.", ) def main( filename, out, max_skip_len, word_selection_method, clip_area_threshold, clip_zoom, yes, debug_render, ): """Extract textual highlights and clippings from FILENAME.""" file_basename, ext = os.path.splitext(filename) if ext == "" and out is None: click.echo( "If the pdf has no extension, the output directory must be manually specified.", err=True, ) raise click.Abort() if ext != ".pdf" and not yes: click.confirm( f"Unexpected extension: {ext} - do you want to continue?", abort=True ) if out is None: out = file_basename + "-highlights" if os.path.isdir(out): if not yes: click.confirm( f"Output directory {out} already exists, overwrite any contents?", abort=True, ) else: os.mkdir(out) highlights_p = os.path.join(out, "highlights.txt") with fitz.open(filename) as doc, open(highlights_p, "w") as highlights_f: page_text_highlights, page_clips = extract_highlights( doc, max_skip_len, word_selection_method, clip_area_threshold, clip_zoom, debug_render, ) for page_num, text_highlights in page_text_highlights.items(): highlights_f.write(f"page {page_num}:\n") for highlight in text_highlights: block = textwrap.indent(textwrap.fill(highlight) + "\n\n", " " * 4) highlights_f.write(block) for page_num, clips in page_clips.items(): for i, clip in enumerate(clips): png_path = os.path.join(out, f"p{page_num}-c{i}.png") clip.writePNG(png_path) if __name__ == "__main__": main() # pylint: disable=no-value-for-parameter
/remarkable-highlights-0.1.3.tar.gz/remarkable-highlights-0.1.3/remarkable_highlights/extract.py
0.561455
0.415017
extract.py
pypi
from shapely.geometry import CAP_STYLE, JOIN_STYLE, LineString # NOTE: This is indeed, supposed to be a string # we care about the precision and don't wish to faff about w/ floats YELLOW = ("1", "0.952941", "0.658824") # RGB def content_contains_highlight(content): return "{} {} {} RG".format(*YELLOW).encode("utf-8") in content # All 'Path Construction Operators' # section 8.5.2 from https://www.adobe.com/content/dam/acom/en/devnet/pdf/PDF32000_2008.pdf PATH_OPS = [ "w", "J", "j", "M", "d", "ri", "i", "gs", "q", "Q", "cm", "m", "l", "c", "v", "y", "h", "re", "S", "s", "f", "F", "f*", "B", "B*", "b", "b*", "n", "W", "W*", "BT", "ET", "Tc", "Tw", "Tz", "TL", "Tf", "Tr", "Ts", "i", "Td", "TD", "Tm", "T*", "Tj", "TJ", "'", '"', "d0", "d1", "CS", "cs", "SC", "SCN", "sc", "scn", "G", "g", "RG", "rg", "K", "k", "sh", "BI", "ID", "EI", "Do", "MP", "DP", "BMC", "BDC", "EMC", "BX", "EX", ] def tokenize_graphics(raw_graphics_content): """Convert a raw graphics content stream into a sequence of operations and their arguments. PDF operations are in postfix position, so the easiest way to parse them is to use a stack. Arguments are added onto the stack until we see a valid operation code. When we see a valid operation, we pop all the arguments off of the stack and continue onto the next operation. To be safe, all Path Construction Operations have been included in PATH_OPS. However, there are indeed more operations defined in the PDF specification, and no effort is made to ensure that the arguments to the operations are valid. """ arg_stack = [] for token in raw_graphics_content.decode("utf-8").split(): if token in PATH_OPS: yield (token, arg_stack.copy()) arg_stack.clear() else: arg_stack.append(token) # It so happens that these numbers are the same, but we shant rely on that remaining the same! # This also is a nice way of documenting what the numbers actually mean. CAP_STYLES = {1: CAP_STYLE.round, 2: CAP_STYLE.flat, 3: CAP_STYLE.square} JOIN_STYLES = {1: JOIN_STYLE.round, 2: JOIN_STYLE.mitre, 3: JOIN_STYLE.bevel} def highlighter_lines(raw_graphics_content): """Render all highlighter lines into LineStrings. This function implements a (very) small subset of the PDF specification for drawing paths. Individual highlighter strokes are rendered into shapely LineString objects. Luckily for us, and almost certainly not due to coincidence, the semantics for defining LineString objects is nearly identical those of PDF paths. Here's an annotated example of a highlighter path pulled from a PDF: q -- push current graphics state onto the stack 1 0.952941 0.658824 RG -- set the stroking color to use in RGB 12.5480766 w -- set the line width (total width, not from centerline) 1 J -- set the line cap style to 'round' 1 j -- set the line join style to 'round' /FXE2 gs -- no idea what this does 1 0 0 1 0 0 cm -- set the current transformation matrix 0 0 m -- move the cursor without drawing a line 397.95938 614.77747 m -- move the cursor again, overriding the previous value 397.48959 615.17413 l -- add a straight line segment from the current point to this point 396.60797 615.76379 l -- do that many, many more times ... -- and a lot more times 51.715569 609.7724 l -- last time S -- stroke the path Q -- pop from the graphics state stack to restore the previous value Key assumptions: - the specified color is always exactly the same (even the precision) - the 'RG' operation setting the color appears before all other relevant operations - only straight lines are used (no curves!), this isn't the case for other markers - the transformation matrix (if specified) is always the identity matrix this is verified however, so if this assumption is violated there will be an error """ lines = [] current_line = [] width = None cap_style = None join_style = None for op, args in tokenize_graphics(raw_graphics_content): if (op, args) == ("RG", list(YELLOW)): current_line = [None] # To be overrode by the last m op elif current_line: if op == "m": # Move the draw position current_line[0] = (float(args[0]), float(args[1])) elif op == "j": i_join_style = int(args[0]) join_style = JOIN_STYLES[i_join_style] elif op == "J": i_cap_style = int(args[0]) cap_style = CAP_STYLES[i_cap_style] elif op == "w": width = float(args[0]) # Total width, will /2 later elif op == "l": current_line.append((float(args[0]), float(args[1]))) elif op == "S": # Finish the line # Make sure we got all the params we need to draw the line correctly assert ( width is not None ), "Expected to see a width for the stroke before stroke end." assert ( cap_style is not None ), "Expected to see a cap style before stroke end." assert ( join_style is not None ), "Expected to see a join style before stroke end." assert len(current_line) > 1, "Invalid line, not enough points." # Draw that thang yield LineString(current_line).buffer( width / 2, cap_style=cap_style, join_style=join_style ) # Reset the state current_line = None width = None cap_style = None join_style = None elif op == "cm": if args != ["1", "0", "0", "1", "0", "0"]: raise NotImplementedError( "Transform matrices are not implemented, but shouldn't be hard to implement" ) else: pass # We don't care about other operations
/remarkable-highlights-0.1.3.tar.gz/remarkable-highlights-0.1.3/remarkable_highlights/parsing.py
0.777638
0.51879
parsing.py
pypi
import logging from pynput.keyboard import Key from pynput.mouse import Button from pynput._util.xorg import X11Error from sortedcontainers import SortedDict log = logging.getLogger(__name__) class Mapping(object): def __init__(self, m, k): self.m = m self.k = k def action(self, key, release=True, reset_modifiers=True): """Returns action function to be called on a touch""" def action(): # FIXME: upstream pynput bug, caps_lock raises exception if mapped to mod key try: self.k.press(key) if release: self.k.release(key) if reset_modifiers: self.k.release(Key.shift) self.k.release(Key.ctrl) self.k.release(Key.alt) self.k.release(Key.shift_r) self.k.release(Key.ctrl_r) except X11Error: log.error(f"X11Error for key {key}") return action def call_action(self, x, y): """Look up coordinate in table and call action""" regions = self.regions() row_index = regions.bisect(y) # FIXME: should be a cleaner way to limit row_index to valid indices row_index = row_index if row_index < len(regions) else len(regions) - 1 row = regions[regions.keys()[row_index]] col_index = row.bisect(x) # FIXME: should be a cleaner way to limit col_index to valid indices col_index = col_index if col_index < len(row) else len(row) - 1 # call function row[row.keys()[col_index]]() class KeyboardMapping(Mapping): def regions(self): return SortedDict({ 260: SortedDict({ 1499: lambda: self.m.click(Button.left), 1872: lambda: self.m.scroll(0, 1) }), 519: SortedDict({ 1499: lambda: self.m.click(Button.left), 1872: lambda: self.m.scroll(0, -1) }), 779: SortedDict({ 1499: lambda: self.m.click(Button.left), 1872: lambda: self.m.click(Button.right) }), 903: SortedDict({ 126: self.action('`'), 251: self.action('1'), 376: self.action('2'), 500: self.action('3'), 625: self.action('4'), 750: self.action('5'), 874: self.action('6'), 1000: self.action('7'), 1125: self.action('8'), 1249: self.action('9'), 1374: self.action('0'), 1499: self.action('-'), 1623: self.action('='), 1872: self.action(Key.backspace) }), 1028: SortedDict({ 188: self.action(Key.tab), 314: self.action('q'), 438: self.action('w'), 563: self.action('e'), 688: self.action('r'), 813: self.action('t'), 937: self.action('y'), 1062: self.action('u'), 1187: self.action('i'), 1312: self.action('o'), 1436: self.action('p'), 1561: self.action('{'), 1686: self.action('}'), 1872: self.action('|') }), 1153: SortedDict({ 220: self.action(Key.caps_lock, release=False), 345: self.action('a'), 470: self.action('s'), 594: self.action('d'), 719: self.action('f'), 844: self.action('g'), 968: self.action('h'), 1093: self.action('j'), 1218: self.action('k'), 1343: self.action('l'), 1468: self.action(';'), 1598: self.action('\''), 1872: self.action(Key.enter) }), 1278: SortedDict({ 282: self.action(Key.shift, release=False, reset_modifiers=False), 407: self.action('z'), 531: self.action('x'), 657: self.action('c'), 781: self.action('v'), 906: self.action('b'), 1031: self.action('n'), 1155: self.action('m'), 1280: self.action(','), 1405: self.action('.'), 1530: self.action('/'), 1872: self.action(Key.shift_r, release=False, reset_modifiers=False) }), 1404: SortedDict({ 188: self.action(Key.ctrl, release=False, reset_modifiers=False), 313: self.action(Key.cmd), 500: self.action(Key.alt, release=False, reset_modifiers=False), 1250: self.action(Key.space), 1374: self.action(Key.esc), 1499: self.action(Key.left), 1623: self.action(Key.down), 1747: self.action(Key.up), 1872: self.action(Key.right) }), }) class ExampleMapping(Mapping): """Example mapping +--- x | | +-------------------+-+ --- y | | |o| | | a | b | | | |---------+---------|o| 1404 | | | | | | c | d |o| | +-------------------+-+ --- |-------1872--------| Coordinates defined in terms of image size: 1872 x 1404 """ def regions(self): return SortedDict({ 1404 // 2: SortedDict({ 1872 // 2: lambda: self.k.type('a'), 1872: lambda: self.k.type('b') }), 1404: SortedDict({ 1872 // 2: lambda: self.k.type('c'), 1872: lambda: self.k.type('d') }) })
/remarkable-keyboard-4.0.0.tar.gz/remarkable-keyboard-4.0.0/remarkable_keyboard/mappings.py
0.456168
0.220657
mappings.py
pypi
import logging import sys from screeninfo import get_monitors, Monitor from .codes import codes, types logging.basicConfig(format='%(message)s') log = logging.getLogger('remouse') wacom_max_y = 15725 wacom_max_x = 20967 def get_monitor(region, monitor_num, orientation): """ Get info of where we want to map the tablet to Args: region (boolean): whether to prompt the user to select a region monitor_num (int): index of monitor to use. Implies region=False orientation (str): Location of tablet charging port. ('top', 'bottom', 'left', 'right') Returns: screeninfo.Monitor (width, height): total size of all screens put together """ # compute size of box encompassing all screens max_x, max_y = 0, 0 for m in get_monitors(): x = m.x + m.width y = m.y + m.height max_x = max(x, max_x) max_y = max(y, max_y) if region: x, y, width, height = get_region(orientation) monitor = Monitor( x, y, width, height, name="Fake monitor from region selection" ) else: monitor = get_monitors()[monitor_num] log.debug(f"Chose monitor: {monitor}") log.debug(f"Screen size: ({max_x}, {max_y})") return monitor, (max_x, max_y) def get_region(orientation): """ Show tkwindow to user to select mouse bounds Args: orientation (str): Location of tablet charging port. ('top', 'bottom', 'left', 'right') Returns: x (int), y (int), width (int), height (int) """ try: import tkinter as tk from tkinter import ttk except ImportError: print( "Unable to import tkinter; please follow the instructions at https://tkdocs.com/tutorial/install.html to install it") sys.exit(1) window = tk.Tk() # A bit of an ugly hack to get this function to run synchronously # Ideally would use full async support, but this solution required minimal changes to rest of code window_bounds = None def on_click(): nonlocal window_bounds window_bounds = ( window.winfo_x(), window.winfo_y(), window.winfo_width(), window.winfo_height() ) window.destroy() confirm = ttk.Button( window, text="Resize and move this window, then click or press Enter", command=on_click ) confirm.grid(column=0, row=0, sticky=(tk.N, tk.S, tk.E, tk.W)) window.bind('<Return>', lambda _: on_click()) window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=1) window.attributes('-alpha', 0.5) window.title("Remarkable Mouse") if orientation == 'bottom' or orientation == 'top': window.geometry("702x936") else: window.geometry("936x702") # block here window.mainloop() if window_bounds is None: log.debug("Window closed without giving mouse range") sys.exit(1) return window_bounds # remap wacom coordinates to screen coordinates def remap(x, y, wacom_max_x, wacom_max_y, monitor_width, monitor_height, mode, orientation): if orientation == 'right': x, y = wacom_max_x - x, wacom_max_y - y if orientation == 'left': pass if orientation == 'top': x, y = wacom_max_y - y, x wacom_max_x, wacom_max_y = wacom_max_y, wacom_max_x if orientation == 'bottom': x, y = y, wacom_max_x - x wacom_max_x, wacom_max_y = wacom_max_y, wacom_max_x ratio_width, ratio_height = monitor_width / wacom_max_x, monitor_height / wacom_max_y if mode == 'fill': scaling_x = max(ratio_width, ratio_height) scaling_y = scaling_x elif mode == 'fit': scaling_x = min(ratio_width, ratio_height) scaling_y = scaling_x elif mode == 'stretch': scaling_x = ratio_width scaling_y = ratio_height else: raise NotImplementedError return ( scaling_x * (x - (wacom_max_x - monitor_width / scaling_x) / 2), scaling_y * (y - (wacom_max_y - monitor_height / scaling_y) / 2) ) # log evdev event to console def log_event(e_time, e_millis, e_type, e_code, e_value): log.debug('{}.{:0>6} - {: <9} {: <15} {: >6}'.format( e_time, e_millis, types[e_type], codes[e_type][e_code], e_value ))
/remarkable-mouse-7.1.1.tar.gz/remarkable-mouse-7.1.1/remarkable_mouse/common.py
0.646237
0.231766
common.py
pypi
types= {0: 'EV_SYN', 1: 'EV_KEY', 2: 'EV_REL', 3: 'EV_ABS', 4: 'EV_MSC', 5: 'EV_SW', 17: 'EV_LED', 18: 'EV_SND', 20: 'EV_REP', 21: 'EV_FF', 22: 'EV_PWR', 23: 'EV_FF_STATUS', 31: 'EV_MAX'} codes = {0: {0: 'SYN_REPORT', 1: 'SYN_CONFIG', 2: 'SYN_MT_REPORT', 3: 'SYN_DROPPED', 4: 'SYN_04', 5: 'SYN_05', 6: 'SYN_06', 7: 'SYN_07', 8: 'SYN_08', 9: 'SYN_09', 10: 'SYN_0A', 11: 'SYN_0B', 12: 'SYN_0C', 13: 'SYN_0D', 14: 'SYN_0E', 15: 'SYN_MAX'}, 1: {0: 'KEY_RESERVED', 1: 'KEY_ESC', 2: 'KEY_1', 3: 'KEY_2', 4: 'KEY_3', 5: 'KEY_4', 6: 'KEY_5', 7: 'KEY_6', 8: 'KEY_7', 9: 'KEY_8', 10: 'KEY_9', 11: 'KEY_0', 12: 'KEY_MINUS', 13: 'KEY_EQUAL', 14: 'KEY_BACKSPACE', 15: 'KEY_TAB', 16: 'KEY_Q', 17: 'KEY_W', 18: 'KEY_E', 19: 'KEY_R', 20: 'KEY_T', 21: 'KEY_Y', 22: 'KEY_U', 23: 'KEY_I', 24: 'KEY_O', 25: 'KEY_P', 26: 'KEY_LEFTBRACE', 27: 'KEY_RIGHTBRACE', 28: 'KEY_ENTER', 29: 'KEY_LEFTCTRL', 30: 'KEY_A', 31: 'KEY_S', 32: 'KEY_D', 33: 'KEY_F', 34: 'KEY_G', 35: 'KEY_H', 36: 'KEY_J', 37: 'KEY_K', 38: 'KEY_L', 39: 'KEY_SEMICOLON', 40: 'KEY_APOSTROPHE', 41: 'KEY_GRAVE', 42: 'KEY_LEFTSHIFT', 43: 'KEY_BACKSLASH', 44: 'KEY_Z', 45: 'KEY_X', 46: 'KEY_C', 47: 'KEY_V', 48: 'KEY_B', 49: 'KEY_N', 50: 'KEY_M', 51: 'KEY_COMMA', 52: 'KEY_DOT', 53: 'KEY_SLASH', 54: 'KEY_RIGHTSHIFT', 55: 'KEY_KPASTERISK', 56: 'KEY_LEFTALT', 57: 'KEY_SPACE', 58: 'KEY_CAPSLOCK', 59: 'KEY_F1', 60: 'KEY_F2', 61: 'KEY_F3', 62: 'KEY_F4', 63: 'KEY_F5', 64: 'KEY_F6', 65: 'KEY_F7', 66: 'KEY_F8', 67: 'KEY_F9', 68: 'KEY_F10', 69: 'KEY_NUMLOCK', 70: 'KEY_SCROLLLOCK', 71: 'KEY_KP7', 72: 'KEY_KP8', 73: 'KEY_KP9', 74: 'KEY_KPMINUS', 75: 'KEY_KP4', 76: 'KEY_KP5', 77: 'KEY_KP6', 78: 'KEY_KPPLUS', 79: 'KEY_KP1', 80: 'KEY_KP2', 81: 'KEY_KP3', 82: 'KEY_KP0', 83: 'KEY_KPDOT', 84: 'KEY_54', 85: 'KEY_ZENKAKUHANKAKU', 86: 'KEY_102ND', 87: 'KEY_F11', 88: 'KEY_F12', 89: 'KEY_RO', 90: 'KEY_KATAKANA', 91: 'KEY_HIRAGANA', 92: 'KEY_HENKAN', 93: 'KEY_KATAKANAHIRAGANA', 94: 'KEY_MUHENKAN', 95: 'KEY_KPJPCOMMA', 96: 'KEY_KPENTER', 97: 'KEY_RIGHTCTRL', 98: 'KEY_KPSLASH', 99: 'KEY_SYSRQ', 100: 'KEY_RIGHTALT', 101: 'KEY_LINEFEED', 102: 'KEY_HOME', 103: 'KEY_UP', 104: 'KEY_PAGEUP', 105: 'KEY_LEFT', 106: 'KEY_RIGHT', 107: 'KEY_END', 108: 'KEY_DOWN', 109: 'KEY_PAGEDOWN', 110: 'KEY_INSERT', 111: 'KEY_DELETE', 112: 'KEY_MACRO', 113: 'KEY_MUTE', 114: 'KEY_VOLUMEDOWN', 115: 'KEY_VOLUMEUP', 116: 'KEY_POWER', 117: 'KEY_KPEQUAL', 118: 'KEY_KPPLUSMINUS', 119: 'KEY_PAUSE', 120: 'KEY_SCALE', 121: 'KEY_KPCOMMA', 122: 'KEY_HANGEUL', 123: 'KEY_HANJA', 124: 'KEY_YEN', 125: 'KEY_LEFTMETA', 126: 'KEY_RIGHTMETA', 127: 'KEY_COMPOSE', 128: 'KEY_STOP', 129: 'KEY_AGAIN', 130: 'KEY_PROPS', 131: 'KEY_UNDO', 132: 'KEY_FRONT', 133: 'KEY_COPY', 134: 'KEY_OPEN', 135: 'KEY_PASTE', 136: 'KEY_FIND', 137: 'KEY_CUT', 138: 'KEY_HELP', 139: 'KEY_MENU', 140: 'KEY_CALC', 141: 'KEY_SETUP', 142: 'KEY_SLEEP', 143: 'KEY_WAKEUP', 144: 'KEY_FILE', 145: 'KEY_SENDFILE', 146: 'KEY_DELETEFILE', 147: 'KEY_XFER', 148: 'KEY_PROG1', 149: 'KEY_PROG2', 150: 'KEY_WWW', 151: 'KEY_MSDOS', 152: 'KEY_COFFEE', 153: 'KEY_ROTATE_DISPLAY', 154: 'KEY_CYCLEWINDOWS', 155: 'KEY_MAIL', 156: 'KEY_BOOKMARKS', 157: 'KEY_COMPUTER', 158: 'KEY_BACK', 159: 'KEY_FORWARD', 160: 'KEY_CLOSECD', 161: 'KEY_EJECTCD', 162: 'KEY_EJECTCLOSECD', 163: 'KEY_NEXTSONG', 164: 'KEY_PLAYPAUSE', 165: 'KEY_PREVIOUSSONG', 166: 'KEY_STOPCD', 167: 'KEY_RECORD', 168: 'KEY_REWIND', 169: 'KEY_PHONE', 170: 'KEY_ISO', 171: 'KEY_CONFIG', 172: 'KEY_HOMEPAGE', 173: 'KEY_REFRESH', 174: 'KEY_EXIT', 175: 'KEY_MOVE', 176: 'KEY_EDIT', 177: 'KEY_SCROLLUP', 178: 'KEY_SCROLLDOWN', 179: 'KEY_KPLEFTPAREN', 180: 'KEY_KPRIGHTPAREN', 181: 'KEY_NEW', 182: 'KEY_REDO', 183: 'KEY_F13', 184: 'KEY_F14', 185: 'KEY_F15', 186: 'KEY_F16', 187: 'KEY_F17', 188: 'KEY_F18', 189: 'KEY_F19', 190: 'KEY_F20', 191: 'KEY_F21', 192: 'KEY_F22', 193: 'KEY_F23', 194: 'KEY_F24', 195: 'KEY_C3', 196: 'KEY_C4', 197: 'KEY_C5', 198: 'KEY_C6', 199: 'KEY_C7', 200: 'KEY_PLAYCD', 201: 'KEY_PAUSECD', 202: 'KEY_PROG3', 203: 'KEY_PROG4', 204: 'KEY_DASHBOARD', 205: 'KEY_SUSPEND', 206: 'KEY_CLOSE', 207: 'KEY_PLAY', 208: 'KEY_FASTFORWARD', 209: 'KEY_BASSBOOST', 210: 'KEY_PRINT', 211: 'KEY_HP', 212: 'KEY_CAMERA', 213: 'KEY_SOUND', 214: 'KEY_QUESTION', 215: 'KEY_EMAIL', 216: 'KEY_CHAT', 217: 'KEY_SEARCH', 218: 'KEY_CONNECT', 219: 'KEY_FINANCE', 220: 'KEY_SPORT', 221: 'KEY_SHOP', 222: 'KEY_ALTERASE', 223: 'KEY_CANCEL', 224: 'KEY_BRIGHTNESSDOWN', 225: 'KEY_BRIGHTNESSUP', 226: 'KEY_MEDIA', 227: 'KEY_SWITCHVIDEOMODE', 228: 'KEY_KBDILLUMTOGGLE', 229: 'KEY_KBDILLUMDOWN', 230: 'KEY_KBDILLUMUP', 231: 'KEY_SEND', 232: 'KEY_REPLY', 233: 'KEY_FORWARDMAIL', 234: 'KEY_SAVE', 235: 'KEY_DOCUMENTS', 236: 'KEY_BATTERY', 237: 'KEY_BLUETOOTH', 238: 'KEY_WLAN', 239: 'KEY_UWB', 240: 'KEY_UNKNOWN', 241: 'KEY_VIDEO_NEXT', 242: 'KEY_VIDEO_PREV', 243: 'KEY_BRIGHTNESS_CYCLE', 244: 'KEY_BRIGHTNESS_AUTO', 245: 'KEY_DISPLAY_OFF', 246: 'KEY_WWAN', 247: 'KEY_RFKILL', 248: 'KEY_MICMUTE', 249: 'KEY_F9', 250: 'KEY_FA', 251: 'KEY_FB', 252: 'KEY_FC', 253: 'KEY_FD', 254: 'KEY_FE', 255: 'KEY_FF', 256: 'BTN_0', 257: 'BTN_1', 258: 'BTN_2', 259: 'BTN_3', 260: 'BTN_4', 261: 'BTN_5', 262: 'BTN_6', 263: 'BTN_7', 264: 'BTN_8', 265: 'BTN_9', 266: 'KEY_10A', 267: 'KEY_10B', 268: 'KEY_10C', 269: 'KEY_10D', 270: 'KEY_10E', 271: 'KEY_10F', 272: 'BTN_LEFT', 273: 'BTN_RIGHT', 274: 'BTN_MIDDLE', 275: 'BTN_SIDE', 276: 'BTN_EXTRA', 277: 'BTN_FORWARD', 278: 'BTN_BACK', 279: 'BTN_TASK', 280: 'KEY_118', 281: 'KEY_119', 282: 'KEY_11A', 283: 'KEY_11B', 284: 'KEY_11C', 285: 'KEY_11D', 286: 'KEY_11E', 287: 'KEY_11F', 288: 'BTN_TRIGGER', 289: 'BTN_THUMB', 290: 'BTN_THUMB2', 291: 'BTN_TOP', 292: 'BTN_TOP2', 293: 'BTN_PINKIE', 294: 'BTN_BASE', 295: 'BTN_BASE2', 296: 'BTN_BASE3', 297: 'BTN_BASE4', 298: 'BTN_BASE5', 299: 'BTN_BASE6', 300: 'KEY_12C', 301: 'KEY_12D', 302: 'KEY_12E', 303: 'BTN_DEAD', 304: 'BTN_SOUTH', 305: 'BTN_EAST', 306: 'BTN_C', 307: 'BTN_NORTH', 308: 'BTN_WEST', 309: 'BTN_Z', 310: 'BTN_TL', 311: 'BTN_TR', 312: 'BTN_TL2', 313: 'BTN_TR2', 314: 'BTN_SELECT', 315: 'BTN_START', 316: 'BTN_MODE', 317: 'BTN_THUMBL', 318: 'BTN_THUMBR', 319: 'KEY_13F', 320: 'BTN_TOOL_PEN', 321: 'BTN_TOOL_RUBBER', 322: 'BTN_TOOL_BRUSH', 323: 'BTN_TOOL_PENCIL', 324: 'BTN_TOOL_AIRBRUSH', 325: 'BTN_TOOL_FINGER', 326: 'BTN_TOOL_MOUSE', 327: 'BTN_TOOL_LENS', 328: 'BTN_TOOL_QUINTTAP', 329: 'BTN_STYLUS3', 330: 'BTN_TOUCH', 331: 'BTN_STYLUS', 332: 'BTN_STYLUS2', 333: 'BTN_TOOL_DOUBLETAP', 334: 'BTN_TOOL_TRIPLETAP', 335: 'BTN_TOOL_QUADTAP', 336: 'BTN_GEAR_DOWN', 337: 'BTN_GEAR_UP', 338: 'KEY_152', 339: 'KEY_153', 340: 'KEY_154', 341: 'KEY_155', 342: 'KEY_156', 343: 'KEY_157', 344: 'KEY_158', 345: 'KEY_159', 346: 'KEY_15A', 347: 'KEY_15B', 348: 'KEY_15C', 349: 'KEY_15D', 350: 'KEY_15E', 351: 'KEY_15F', 352: 'KEY_OK', 353: 'KEY_SELECT', 354: 'KEY_GOTO', 355: 'KEY_CLEAR', 356: 'KEY_POWER2', 357: 'KEY_OPTION', 358: 'KEY_INFO', 359: 'KEY_TIME', 360: 'KEY_VENDOR', 361: 'KEY_ARCHIVE', 362: 'KEY_PROGRAM', 363: 'KEY_CHANNEL', 364: 'KEY_FAVORITES', 365: 'KEY_EPG', 366: 'KEY_PVR', 367: 'KEY_MHP', 368: 'KEY_LANGUAGE', 369: 'KEY_TITLE', 370: 'KEY_SUBTITLE', 371: 'KEY_ANGLE', 372: 'KEY_FULL_SCREEN', 373: 'KEY_MODE', 374: 'KEY_KEYBOARD', 375: 'KEY_ASPECT_RATIO', 376: 'KEY_PC', 377: 'KEY_TV', 378: 'KEY_TV2', 379: 'KEY_VCR', 380: 'KEY_VCR2', 381: 'KEY_SAT', 382: 'KEY_SAT2', 383: 'KEY_CD', 384: 'KEY_TAPE', 385: 'KEY_RADIO', 386: 'KEY_TUNER', 387: 'KEY_PLAYER', 388: 'KEY_TEXT', 389: 'KEY_DVD', 390: 'KEY_AUX', 391: 'KEY_MP3', 392: 'KEY_AUDIO', 393: 'KEY_VIDEO', 394: 'KEY_DIRECTORY', 395: 'KEY_LIST', 396: 'KEY_MEMO', 397: 'KEY_CALENDAR', 398: 'KEY_RED', 399: 'KEY_GREEN', 400: 'KEY_YELLOW', 401: 'KEY_BLUE', 402: 'KEY_CHANNELUP', 403: 'KEY_CHANNELDOWN', 404: 'KEY_FIRST', 405: 'KEY_LAST', 406: 'KEY_AB', 407: 'KEY_NEXT', 408: 'KEY_RESTART', 409: 'KEY_SLOW', 410: 'KEY_SHUFFLE', 411: 'KEY_BREAK', 412: 'KEY_PREVIOUS', 413: 'KEY_DIGITS', 414: 'KEY_TEEN', 415: 'KEY_TWEN', 416: 'KEY_VIDEOPHONE', 417: 'KEY_GAMES', 418: 'KEY_ZOOMIN', 419: 'KEY_ZOOMOUT', 420: 'KEY_ZOOMRESET', 421: 'KEY_WORDPROCESSOR', 422: 'KEY_EDITOR', 423: 'KEY_SPREADSHEET', 424: 'KEY_GRAPHICSEDITOR', 425: 'KEY_PRESENTATION', 426: 'KEY_DATABASE', 427: 'KEY_NEWS', 428: 'KEY_VOICEMAIL', 429: 'KEY_ADDRESSBOOK', 430: 'KEY_MESSENGER', 431: 'KEY_DISPLAYTOGGLE', 432: 'KEY_SPELLCHECK', 433: 'KEY_LOGOFF', 434: 'KEY_DOLLAR', 435: 'KEY_EURO', 436: 'KEY_FRAMEBACK', 437: 'KEY_FRAMEFORWARD', 438: 'KEY_CONTEXT_MENU', 439: 'KEY_MEDIA_REPEAT', 440: 'KEY_10CHANNELSUP', 441: 'KEY_10CHANNELSDOWN', 442: 'KEY_IMAGES', 443: 'KEY_1BB', 444: 'KEY_NOTIFICATION_CENTER', 445: 'KEY_PICKUP_PHONE', 446: 'KEY_HANGUP_PHONE', 447: 'KEY_1BF', 448: 'KEY_DEL_EOL', 449: 'KEY_DEL_EOS', 450: 'KEY_INS_LINE', 451: 'KEY_DEL_LINE', 452: 'KEY_1C4', 453: 'KEY_1C5', 454: 'KEY_1C6', 455: 'KEY_1C7', 456: 'KEY_1C8', 457: 'KEY_1C9', 458: 'KEY_1CA', 459: 'KEY_1CB', 460: 'KEY_1CC', 461: 'KEY_1CD', 462: 'KEY_1CE', 463: 'KEY_1CF', 464: 'KEY_FN', 465: 'KEY_FN_ESC', 466: 'KEY_FN_F1', 467: 'KEY_FN_F2', 468: 'KEY_FN_F3', 469: 'KEY_FN_F4', 470: 'KEY_FN_F5', 471: 'KEY_FN_F6', 472: 'KEY_FN_F7', 473: 'KEY_FN_F8', 474: 'KEY_FN_F9', 475: 'KEY_FN_F10', 476: 'KEY_FN_F11', 477: 'KEY_FN_F12', 478: 'KEY_FN_1', 479: 'KEY_FN_2', 480: 'KEY_FN_D', 481: 'KEY_FN_E', 482: 'KEY_FN_F', 483: 'KEY_FN_S', 484: 'KEY_FN_B', 485: 'KEY_FN_RIGHT_SHIFT', 486: 'KEY_1E6', 487: 'KEY_1E7', 488: 'KEY_1E8', 489: 'KEY_1E9', 490: 'KEY_1EA', 491: 'KEY_1EB', 492: 'KEY_1EC', 493: 'KEY_1ED', 494: 'KEY_1EE', 495: 'KEY_1EF', 496: 'KEY_1F0', 497: 'KEY_BRL_DOT1', 498: 'KEY_BRL_DOT2', 499: 'KEY_BRL_DOT3', 500: 'KEY_BRL_DOT4', 501: 'KEY_BRL_DOT5', 502: 'KEY_BRL_DOT6', 503: 'KEY_BRL_DOT7', 504: 'KEY_BRL_DOT8', 505: 'KEY_BRL_DOT9', 506: 'KEY_BRL_DOT10', 507: 'KEY_1FB', 508: 'KEY_1FC', 509: 'KEY_1FD', 510: 'KEY_1FE', 511: 'KEY_1FF', 512: 'KEY_NUMERIC_0', 513: 'KEY_NUMERIC_1', 514: 'KEY_NUMERIC_2', 515: 'KEY_NUMERIC_3', 516: 'KEY_NUMERIC_4', 517: 'KEY_NUMERIC_5', 518: 'KEY_NUMERIC_6', 519: 'KEY_NUMERIC_7', 520: 'KEY_NUMERIC_8', 521: 'KEY_NUMERIC_9', 522: 'KEY_NUMERIC_STAR', 523: 'KEY_NUMERIC_POUND', 524: 'KEY_NUMERIC_A', 525: 'KEY_NUMERIC_B', 526: 'KEY_NUMERIC_C', 527: 'KEY_NUMERIC_D', 528: 'KEY_CAMERA_FOCUS', 529: 'KEY_WPS_BUTTON', 530: 'KEY_TOUCHPAD_TOGGLE', 531: 'KEY_TOUCHPAD_ON', 532: 'KEY_TOUCHPAD_OFF', 533: 'KEY_CAMERA_ZOOMIN', 534: 'KEY_CAMERA_ZOOMOUT', 535: 'KEY_CAMERA_UP', 536: 'KEY_CAMERA_DOWN', 537: 'KEY_CAMERA_LEFT', 538: 'KEY_CAMERA_RIGHT', 539: 'KEY_ATTENDANT_ON', 540: 'KEY_ATTENDANT_OFF', 541: 'KEY_ATTENDANT_TOGGLE', 542: 'KEY_LIGHTS_TOGGLE', 543: 'KEY_21F', 544: 'BTN_DPAD_UP', 545: 'BTN_DPAD_DOWN', 546: 'BTN_DPAD_LEFT', 547: 'BTN_DPAD_RIGHT', 548: 'KEY_224', 549: 'KEY_225', 550: 'KEY_226', 551: 'KEY_227', 552: 'KEY_228', 553: 'KEY_229', 554: 'KEY_22A', 555: 'KEY_22B', 556: 'KEY_22C', 557: 'KEY_22D', 558: 'KEY_22E', 559: 'KEY_22F', 560: 'KEY_ALS_TOGGLE', 561: 'KEY_ROTATE_LOCK_TOGGLE', 562: 'KEY_232', 563: 'KEY_233', 564: 'KEY_234', 565: 'KEY_235', 566: 'KEY_236', 567: 'KEY_237', 568: 'KEY_238', 569: 'KEY_239', 570: 'KEY_23A', 571: 'KEY_23B', 572: 'KEY_23C', 573: 'KEY_23D', 574: 'KEY_23E', 575: 'KEY_23F', 576: 'KEY_BUTTONCONFIG', 577: 'KEY_TASKMANAGER', 578: 'KEY_JOURNAL', 579: 'KEY_CONTROLPANEL', 580: 'KEY_APPSELECT', 581: 'KEY_SCREENSAVER', 582: 'KEY_VOICECOMMAND', 583: 'KEY_ASSISTANT', 584: 'KEY_KBD_LAYOUT_NEXT', 585: 'KEY_EMOJI_PICKER', 586: 'KEY_24A', 587: 'KEY_24B', 588: 'KEY_24C', 589: 'KEY_24D', 590: 'KEY_24E', 591: 'KEY_24F', 592: 'KEY_BRIGHTNESS_MIN', 593: 'KEY_BRIGHTNESS_MAX', 594: 'KEY_252', 595: 'KEY_253', 596: 'KEY_254', 597: 'KEY_255', 598: 'KEY_256', 599: 'KEY_257', 600: 'KEY_258', 601: 'KEY_259', 602: 'KEY_25A', 603: 'KEY_25B', 604: 'KEY_25C', 605: 'KEY_25D', 606: 'KEY_25E', 607: 'KEY_25F', 608: 'KEY_KBDINPUTASSIST_PREV', 609: 'KEY_KBDINPUTASSIST_NEXT', 610: 'KEY_KBDINPUTASSIST_PREVGROUP', 611: 'KEY_KBDINPUTASSIST_NEXTGROUP', 612: 'KEY_KBDINPUTASSIST_ACCEPT', 613: 'KEY_KBDINPUTASSIST_CANCEL', 614: 'KEY_RIGHT_UP', 615: 'KEY_RIGHT_DOWN', 616: 'KEY_LEFT_UP', 617: 'KEY_LEFT_DOWN', 618: 'KEY_ROOT_MENU', 619: 'KEY_MEDIA_TOP_MENU', 620: 'KEY_NUMERIC_11', 621: 'KEY_NUMERIC_12', 622: 'KEY_AUDIO_DESC', 623: 'KEY_3D_MODE', 624: 'KEY_NEXT_FAVORITE', 625: 'KEY_STOP_RECORD', 626: 'KEY_PAUSE_RECORD', 627: 'KEY_VOD', 628: 'KEY_UNMUTE', 629: 'KEY_FASTREVERSE', 630: 'KEY_SLOWREVERSE', 631: 'KEY_DATA', 632: 'KEY_ONSCREEN_KEYBOARD', 633: 'KEY_PRIVACY_SCREEN_TOGGLE', 634: 'KEY_SELECTIVE_SCREENSHOT', 635: 'KEY_27B', 636: 'KEY_27C', 637: 'KEY_27D', 638: 'KEY_27E', 639: 'KEY_27F', 640: 'KEY_280', 641: 'KEY_281', 642: 'KEY_282', 643: 'KEY_283', 644: 'KEY_284', 645: 'KEY_285', 646: 'KEY_286', 647: 'KEY_287', 648: 'KEY_288', 649: 'KEY_289', 650: 'KEY_28A', 651: 'KEY_28B', 652: 'KEY_28C', 653: 'KEY_28D', 654: 'KEY_28E', 655: 'KEY_28F', 656: 'KEY_MACRO1', 657: 'KEY_MACRO2', 658: 'KEY_MACRO3', 659: 'KEY_MACRO4', 660: 'KEY_MACRO5', 661: 'KEY_MACRO6', 662: 'KEY_MACRO7', 663: 'KEY_MACRO8', 664: 'KEY_MACRO9', 665: 'KEY_MACRO10', 666: 'KEY_MACRO11', 667: 'KEY_MACRO12', 668: 'KEY_MACRO13', 669: 'KEY_MACRO14', 670: 'KEY_MACRO15', 671: 'KEY_MACRO16', 672: 'KEY_MACRO17', 673: 'KEY_MACRO18', 674: 'KEY_MACRO19', 675: 'KEY_MACRO20', 676: 'KEY_MACRO21', 677: 'KEY_MACRO22', 678: 'KEY_MACRO23', 679: 'KEY_MACRO24', 680: 'KEY_MACRO25', 681: 'KEY_MACRO26', 682: 'KEY_MACRO27', 683: 'KEY_MACRO28', 684: 'KEY_MACRO29', 685: 'KEY_MACRO30', 686: 'KEY_2AE', 687: 'KEY_2AF', 688: 'KEY_MACRO_RECORD_START', 689: 'KEY_MACRO_RECORD_STOP', 690: 'KEY_MACRO_PRESET_CYCLE', 691: 'KEY_MACRO_PRESET1', 692: 'KEY_MACRO_PRESET2', 693: 'KEY_MACRO_PRESET3', 694: 'KEY_2B6', 695: 'KEY_2B7', 696: 'KEY_KBD_LCD_MENU1', 697: 'KEY_KBD_LCD_MENU2', 698: 'KEY_KBD_LCD_MENU3', 699: 'KEY_KBD_LCD_MENU4', 700: 'KEY_KBD_LCD_MENU5', 701: 'KEY_2BD', 702: 'KEY_2BE', 703: 'KEY_2BF', 704: 'BTN_TRIGGER_HAPPY1', 705: 'BTN_TRIGGER_HAPPY2', 706: 'BTN_TRIGGER_HAPPY3', 707: 'BTN_TRIGGER_HAPPY4', 708: 'BTN_TRIGGER_HAPPY5', 709: 'BTN_TRIGGER_HAPPY6', 710: 'BTN_TRIGGER_HAPPY7', 711: 'BTN_TRIGGER_HAPPY8', 712: 'BTN_TRIGGER_HAPPY9', 713: 'BTN_TRIGGER_HAPPY10', 714: 'BTN_TRIGGER_HAPPY11', 715: 'BTN_TRIGGER_HAPPY12', 716: 'BTN_TRIGGER_HAPPY13', 717: 'BTN_TRIGGER_HAPPY14', 718: 'BTN_TRIGGER_HAPPY15', 719: 'BTN_TRIGGER_HAPPY16', 720: 'BTN_TRIGGER_HAPPY17', 721: 'BTN_TRIGGER_HAPPY18', 722: 'BTN_TRIGGER_HAPPY19', 723: 'BTN_TRIGGER_HAPPY20', 724: 'BTN_TRIGGER_HAPPY21', 725: 'BTN_TRIGGER_HAPPY22', 726: 'BTN_TRIGGER_HAPPY23', 727: 'BTN_TRIGGER_HAPPY24', 728: 'BTN_TRIGGER_HAPPY25', 729: 'BTN_TRIGGER_HAPPY26', 730: 'BTN_TRIGGER_HAPPY27', 731: 'BTN_TRIGGER_HAPPY28', 732: 'BTN_TRIGGER_HAPPY29', 733: 'BTN_TRIGGER_HAPPY30', 734: 'BTN_TRIGGER_HAPPY31', 735: 'BTN_TRIGGER_HAPPY32', 736: 'BTN_TRIGGER_HAPPY33', 737: 'BTN_TRIGGER_HAPPY34', 738: 'BTN_TRIGGER_HAPPY35', 739: 'BTN_TRIGGER_HAPPY36', 740: 'BTN_TRIGGER_HAPPY37', 741: 'BTN_TRIGGER_HAPPY38', 742: 'BTN_TRIGGER_HAPPY39', 743: 'BTN_TRIGGER_HAPPY40', 744: 'KEY_2E8', 745: 'KEY_2E9', 746: 'KEY_2EA', 747: 'KEY_2EB', 748: 'KEY_2EC', 749: 'KEY_2ED', 750: 'KEY_2EE', 751: 'KEY_2EF', 752: 'KEY_2F0', 753: 'KEY_2F1', 754: 'KEY_2F2', 755: 'KEY_2F3', 756: 'KEY_2F4', 757: 'KEY_2F5', 758: 'KEY_2F6', 759: 'KEY_2F7', 760: 'KEY_2F8', 761: 'KEY_2F9', 762: 'KEY_2FA', 763: 'KEY_2FB', 764: 'KEY_2FC', 765: 'KEY_2FD', 766: 'KEY_2FE', 767: 'KEY_MAX'}, 2: {0: 'REL_X', 1: 'REL_Y', 2: 'REL_Z', 3: 'REL_RX', 4: 'REL_RY', 5: 'REL_RZ', 6: 'REL_HWHEEL', 7: 'REL_DIAL', 8: 'REL_WHEEL', 9: 'REL_MISC', 10: 'REL_RESERVED', 11: 'REL_WHEEL_HI_RES', 12: 'REL_HWHEEL_HI_RES', 13: 'REL_0D', 14: 'REL_0E', 15: 'REL_MAX'}, 3: {0: 'ABS_X', 1: 'ABS_Y', 2: 'ABS_Z', 3: 'ABS_RX', 4: 'ABS_RY', 5: 'ABS_RZ', 6: 'ABS_THROTTLE', 7: 'ABS_RUDDER', 8: 'ABS_WHEEL', 9: 'ABS_GAS', 10: 'ABS_BRAKE', 11: 'ABS_0B', 12: 'ABS_0C', 13: 'ABS_0D', 14: 'ABS_0E', 15: 'ABS_0F', 16: 'ABS_HAT0X', 17: 'ABS_HAT0Y', 18: 'ABS_HAT1X', 19: 'ABS_HAT1Y', 20: 'ABS_HAT2X', 21: 'ABS_HAT2Y', 22: 'ABS_HAT3X', 23: 'ABS_HAT3Y', 24: 'ABS_PRESSURE', 25: 'ABS_DISTANCE', 26: 'ABS_TILT_X', 27: 'ABS_TILT_Y', 28: 'ABS_TOOL_WIDTH', 29: 'ABS_1D', 30: 'ABS_1E', 31: 'ABS_1F', 32: 'ABS_VOLUME', 33: 'ABS_21', 34: 'ABS_22', 35: 'ABS_23', 36: 'ABS_24', 37: 'ABS_25', 38: 'ABS_26', 39: 'ABS_27', 40: 'ABS_MISC', 41: 'ABS_29', 42: 'ABS_2A', 43: 'ABS_2B', 44: 'ABS_2C', 45: 'ABS_2D', 46: 'ABS_RESERVED', 47: 'ABS_MT_SLOT', 48: 'ABS_MT_TOUCH_MAJOR', 49: 'ABS_MT_TOUCH_MINOR', 50: 'ABS_MT_WIDTH_MAJOR', 51: 'ABS_MT_WIDTH_MINOR', 52: 'ABS_MT_ORIENTATION', 53: 'ABS_MT_POSITION_X', 54: 'ABS_MT_POSITION_Y', 55: 'ABS_MT_TOOL_TYPE', 56: 'ABS_MT_BLOB_ID', 57: 'ABS_MT_TRACKING_ID', 58: 'ABS_MT_PRESSURE', 59: 'ABS_MT_DISTANCE', 60: 'ABS_MT_TOOL_X', 61: 'ABS_MT_TOOL_Y', 62: 'ABS_3E', 63: 'ABS_MAX'}, 4: {0: 'MSC_SERIAL', 1: 'MSC_PULSELED', 2: 'MSC_GESTURE', 3: 'MSC_RAW', 4: 'MSC_SCAN', 5: 'MSC_TIMESTAMP', 6: 'MSC_06', 7: 'MSC_MAX'}, 5: {0: 'SW_LID', 1: 'SW_TABLET_MODE', 2: 'SW_HEADPHONE_INSERT', 3: 'SW_RFKILL_ALL', 4: 'SW_MICROPHONE_INSERT', 5: 'SW_DOCK', 6: 'SW_LINEOUT_INSERT', 7: 'SW_JACK_PHYSICAL_INSERT', 8: 'SW_VIDEOOUT_INSERT', 9: 'SW_CAMERA_LENS_COVER', 10: 'SW_KEYPAD_SLIDE', 11: 'SW_FRONT_PROXIMITY', 12: 'SW_ROTATE_LOCK', 13: 'SW_LINEIN_INSERT', 14: 'SW_MUTE_DEVICE', 15: 'SW_PEN_INSERTED', 16: 'SW_MACHINE_COVER'}, 17: {0: 'LED_NUML', 1: 'LED_CAPSL', 2: 'LED_SCROLLL', 3: 'LED_COMPOSE', 4: 'LED_KANA', 5: 'LED_SLEEP', 6: 'LED_SUSPEND', 7: 'LED_MUTE', 8: 'LED_MISC', 9: 'LED_MAIL', 10: 'LED_CHARGING', 11: 'LED_0B', 12: 'LED_0C', 13: 'LED_0D', 14: 'LED_0E', 15: 'LED_MAX'}, 18: {0: 'SND_CLICK', 1: 'SND_BELL', 2: 'SND_TONE', 3: 'SND_03', 4: 'SND_04', 5: 'SND_05', 6: 'SND_06', 7: 'SND_MAX'}, 20: {0: 'REP_DELAY', 1: 'REP_PERIOD'}, 21: {0: 'FF_STATUS_STOPPED', 1: 'FF_STATUS_MAX', 2: 'FF_02', 3: 'FF_03', 4: 'FF_04', 5: 'FF_05', 6: 'FF_06', 7: 'FF_07', 8: 'FF_08', 9: 'FF_09', 10: 'FF_0A', 11: 'FF_0B', 12: 'FF_0C', 13: 'FF_0D', 14: 'FF_0E', 15: 'FF_0F', 16: 'FF_10', 17: 'FF_11', 18: 'FF_12', 19: 'FF_13', 20: 'FF_14', 21: 'FF_15', 22: 'FF_16', 23: 'FF_17', 24: 'FF_18', 25: 'FF_19', 26: 'FF_1A', 27: 'FF_1B', 28: 'FF_1C', 29: 'FF_1D', 30: 'FF_1E', 31: 'FF_1F', 32: 'FF_20', 33: 'FF_21', 34: 'FF_22', 35: 'FF_23', 36: 'FF_24', 37: 'FF_25', 38: 'FF_26', 39: 'FF_27', 40: 'FF_28', 41: 'FF_29', 42: 'FF_2A', 43: 'FF_2B', 44: 'FF_2C', 45: 'FF_2D', 46: 'FF_2E', 47: 'FF_2F', 48: 'FF_30', 49: 'FF_31', 50: 'FF_32', 51: 'FF_33', 52: 'FF_34', 53: 'FF_35', 54: 'FF_36', 55: 'FF_37', 56: 'FF_38', 57: 'FF_39', 58: 'FF_3A', 59: 'FF_3B', 60: 'FF_3C', 61: 'FF_3D', 62: 'FF_3E', 63: 'FF_3F', 64: 'FF_40', 65: 'FF_41', 66: 'FF_42', 67: 'FF_43', 68: 'FF_44', 69: 'FF_45', 70: 'FF_46', 71: 'FF_47', 72: 'FF_48', 73: 'FF_49', 74: 'FF_4A', 75: 'FF_4B', 76: 'FF_4C', 77: 'FF_4D', 78: 'FF_4E', 79: 'FF_4F', 80: 'FF_RUMBLE', 81: 'FF_PERIODIC', 82: 'FF_CONSTANT', 83: 'FF_SPRING', 84: 'FF_FRICTION', 85: 'FF_DAMPER', 86: 'FF_INERTIA', 87: 'FF_RAMP', 88: 'FF_SQUARE', 89: 'FF_TRIANGLE', 90: 'FF_SINE', 91: 'FF_SAW_UP', 92: 'FF_SAW_DOWN', 93: 'FF_CUSTOM', 94: 'FF_5E', 95: 'FF_5F', 96: 'FF_GAIN', 97: 'FF_AUTOCENTER', 98: 'FF_62', 99: 'FF_63', 100: 'FF_64', 101: 'FF_65', 102: 'FF_66', 103: 'FF_67', 104: 'FF_68', 105: 'FF_69', 106: 'FF_6A', 107: 'FF_6B', 108: 'FF_6C', 109: 'FF_6D', 110: 'FF_6E', 111: 'FF_6F', 112: 'FF_70', 113: 'FF_71', 114: 'FF_72', 115: 'FF_73', 116: 'FF_74', 117: 'FF_75', 118: 'FF_76', 119: 'FF_77', 120: 'FF_78', 121: 'FF_79', 122: 'FF_7A', 123: 'FF_7B', 124: 'FF_7C', 125: 'FF_7D', 126: 'FF_7E', 127: 'FF_MAX'}, 22: {}, 23: {}, 31: {}}
/remarkable-mouse-7.1.1.tar.gz/remarkable-mouse-7.1.1/remarkable_mouse/codes.py
0.477798
0.190498
codes.py
pypi
import time import os import struct import stat import logging logging.basicConfig(format='%(message)s') log = logging.getLogger('resim') def affine_map(x, a0, a1, b0, b1): """Map x in range (a0, a1) to (b0, b1) Args: x (float): input a0 (float): input range start a1 (float): input range start b0 (float): output range start b1 (float): output range start Returns: int: mapped coordinate """ return int(((x - a0) / a1) * (b1 - b0) + b0) def makefifo(path): """Make a fifo, delete existing fifo Args: path (str): path to new fifo """ if os.path.exists(path) and stat.S_ISFIFO(os.stat(path).st_mode): os.remove(path) os.mkfifo(path) return os.open(path, os.O_RDWR) # write evdev events to fifos def write_evdev(f, e_type, e_code, e_value): """Write evdev events to fifo Args: f (int): fd of fifo e_type (int): evdev event type e_code (int): evdev event code e_value (int): evdev event value """ log.debug("{} {} {} {}".format(f, e_type, e_code, e_value)) t = time.time_ns() t_seconds = int(t / 1e9) t_microseconds = int(t / 1e3 % 1e6) os.write( f, struct.pack( 'ILHHi', t_seconds, t_microseconds, e_type, e_code, e_value ) ) # ----- evdev codes ----- # see evdev_notes.md # tuples containing (type, code) code_sync = (0, 0, 0) codes_stylus = { 'toolpen': (1, 320), 'toolrubber': (1, 321), 'touch': (1, 330), 'stylus': (1, 331), 'stylus2': (1, 332), 'abs_x': (3, 0), 'abs_y': (3, 1), 'abs_pressure': (3, 24), 'abs_distance': (3, 25), 'abs_tilt_x': (3, 26), 'abs_tilt_y': (3, 27) } codes_touch = { 'abs_mt_distance': (3, 25), 'abs_mt_slot': (3, 47), 'abs_mt_touch_major': (3, 48), 'abs_mt_touch_minor': (3, 49), 'abs_mt_orientation': (3, 52), 'abs_mt_position_x': (3, 53), 'abs_mt_position_y': (3, 54), 'abs_mt_tracking_id': (3, 57), 'abs_mt_pressure': (3, 58) } codes_button = { 'home': (1, 102), 'left': (1, 105), 'right': (1, 106), 'power': (1, 116), 'wakeup': (1, 143) } stylus_max_x = 20967 stylus_max_y = 15725 touch_max_x = 767 touch_max_y = 1023
/remarkable_sim-1.0.6-py3-none-any.whl/remarkable_sim/evsim.py
0.790652
0.254903
evsim.py
pypi
# [Changelog](https://github.com/michaeljoseph/remarkable/releases) ## [0.3.1](https://github.com/michaeljoseph/remarkable/compare/0.3.0...0.3.1) * [4e69b29](https://github.com/michaeljoseph/remarkable/commit/4e69b29) Remark 0.5.6 for https://github.com/gnab/remark/issues/50 ## [0.3.0](https://github.com/michaeljoseph/remarkable/compare/0.2.2...0.3.0) * [260b840](https://github.com/michaeljoseph/remarkable/commit/260b840) Add wheel * [0ad816b](https://github.com/michaeljoseph/remarkable/commit/0ad816b) Refactor and limit verification * [f408ec6](https://github.com/michaeljoseph/remarkable/commit/f408ec6) Fix test fixtures * [0142402](https://github.com/michaeljoseph/remarkable/commit/0142402) Debug test failure * [73fe399](https://github.com/michaeljoseph/remarkable/commit/73fe399) Remark and reveal render template directories * [953397c](https://github.com/michaeljoseph/remarkable/commit/953397c) Update template references * [5d299eb](https://github.com/michaeljoseph/remarkable/commit/5d299eb) Add static assets ## [0.2.2](https://github.com/michaeljoseph/remarkable/compare/0.2.1...0.2.2) * [e2f38d1](https://github.com/michaeljoseph/remarkable/commit/e2f38d1) Test and lint aliases * [60b9575](https://github.com/michaeljoseph/remarkable/commit/60b9575) Generate filename from title and apply to template ## [0.2.1](https://github.com/michaeljoseph/remarkable/compare/0.2.0...0.2.1) * 50be64c travis-solo over tox * 31c2d18 Rm output folder * a2ea8e0 Drop pypy for now * 55b1d8e Travis solo is a local dev requirement * e640af9 Not a rest API * 59d6054 Slide note html * e83e9df Protocol neutral github js cdn * 417e7a0 Ignore travis-solo * 4fda434 Implement no-input * 2cbafd9 Travis solo * 0b50122 Autoenv * c252c17 Correct title * d3f7f9d Cdn most of the assets * 321ac98 Reveal slide notes * 73edd2a No input * 5de1aea Interpolate * 7b3d6c9 Indefinite article ends with 'n' before a word pronounced starting with a vowel * 695ed74 Give the project a "look" ## [0.2.0](https://github.com/michaeljoseph/remarkable/compare/0.1.0...0.2.0) * [ed4c745](https://github.com/michaeljoseph/remarkable/commit/ed4c745) Include presentation template directory * [1b116a5](https://github.com/michaeljoseph/remarkable/commit/1b116a5) Runtime dependency on snide ## [0.1.0](https://github.com/michaeljoseph/remarkable/compare/0.0.2...0.1.0) * [26fc527](https://github.com/michaeljoseph/remarkable/commit/26fc527) Update tests * [d6d3c46](https://github.com/michaeljoseph/remarkable/commit/d6d3c46) Title is required for reveal and optional for remark * [5fa36ed](https://github.com/michaeljoseph/remarkable/commit/5fa36ed) Linting * [a2d4e35](https://github.com/michaeljoseph/remarkable/commit/a2d4e35) Update cli usage in readme * [be96f92](https://github.com/michaeljoseph/remarkable/commit/be96f92) Update tests * [fc087b5](https://github.com/michaeljoseph/remarkable/commit/fc087b5) Update remark command * [b6ae6a2](https://github.com/michaeljoseph/remarkable/commit/b6ae6a2) Prompt for output directory deletion permission * [ad2029d](https://github.com/michaeljoseph/remarkable/commit/ad2029d) Simplify reveal command * [1f576be](https://github.com/michaeljoseph/remarkable/commit/1f576be) Remove output directory option * [f6c85fb](https://github.com/michaeljoseph/remarkable/commit/f6c85fb) Support for rendering a template directory * [9354d98](https://github.com/michaeljoseph/remarkable/commit/9354d98) Update remark command with new template location and support for output directory * [5cf369c](https://github.com/michaeljoseph/remarkable/commit/5cf369c) pep8 * [8fcd272](https://github.com/michaeljoseph/remarkable/commit/8fcd272) Add output directory param * [b853215](https://github.com/michaeljoseph/remarkable/commit/b853215) Standardise remark template * [8c43443](https://github.com/michaeljoseph/remarkable/commit/8c43443) Add reveal support files * [fc36c96](https://github.com/michaeljoseph/remarkable/commit/fc36c96) Cleanup * [e6897fc](https://github.com/michaeljoseph/remarkable/commit/e6897fc) Correct template name * [6acea1c](https://github.com/michaeljoseph/remarkable/commit/6acea1c) Parse slides with snide and pass as context * [53adf6b](https://github.com/michaeljoseph/remarkable/commit/53adf6b) Add reveal slide markup * [88a7fbe](https://github.com/michaeljoseph/remarkable/commit/88a7fbe) Update README with cli usage * [1762afa](https://github.com/michaeljoseph/remarkable/commit/1762afa) Add reveal template * [695599f](https://github.com/michaeljoseph/remarkable/commit/695599f) `templates` directory is the default * [6579e17](https://github.com/michaeljoseph/remarkable/commit/6579e17) Reveal tests * [f1dff79](https://github.com/michaeljoseph/remarkable/commit/f1dff79) Refactor remark handler * [576d2a4](https://github.com/michaeljoseph/remarkable/commit/576d2a4) Add reveal option and command handler * [4948ac3](https://github.com/michaeljoseph/remarkable/commit/4948ac3) Add helper methods * [78201b8](https://github.com/michaeljoseph/remarkable/commit/78201b8) Refactor markdown constant to base class * [4950d38](https://github.com/michaeljoseph/remarkable/commit/4950d38) Refactor and rename test case ## [0.0.2](https://github.com/michaeljoseph/remarkable/compare/0.0.1...0.0.2) * [c35a20e](https://github.com/michaeljoseph/remarkable/commit/c35a20e) Require linting and lint fixes * [df1be25](https://github.com/michaeljoseph/remarkable/commit/df1be25) We need Jinja * [94a88a1](https://github.com/michaeljoseph/remarkable/commit/94a88a1) Refactor and test remark rendering * [654f469](https://github.com/michaeljoseph/remarkable/commit/654f469) Rm boilerplate function * [300b811](https://github.com/michaeljoseph/remarkable/commit/300b811) Dedent markdown * [ba04f18](https://github.com/michaeljoseph/remarkable/commit/ba04f18) Refactor template rendering * [b8919a0](https://github.com/michaeljoseph/remarkable/commit/b8919a0) Fix manifest ## 0.0.1 * [90cb917](https://github.com/michaeljoseph/remarkable/commit/90cb917) Add changes * [c318cf8](https://github.com/michaeljoseph/remarkable/commit/c318cf8) Cleanup * [d6fa444](https://github.com/michaeljoseph/remarkable/commit/d6fa444) Add remark template * [c3f176c](https://github.com/michaeljoseph/remarkable/commit/c3f176c) Implement remark presentation * [9005d62](https://github.com/michaeljoseph/remarkable/commit/9005d62) Fix cookiecutter bug * [362d43c](https://github.com/michaeljoseph/remarkable/commit/362d43c) Fix documentation link * [794c6d3](https://github.com/michaeljoseph/remarkable/commit/794c6d3) First cut from cookiecutter template * [e601b25](https://github.com/michaeljoseph/remarkable/commit/e601b25) Initial commit
/remarkable-0.3.1.tar.gz/remarkable-0.3.1/CHANGELOG.md
0.583203
0.692704
CHANGELOG.md
pypi
from __future__ import annotations import argparse import datetime import json import os.path import re import sys from typing import Any, Callable, Dict, List, Mapping, Sequence, Set, Tuple, Union, cast import cbor2 # type: ignore import dateutil.parser import tomlkit import tomlkit.exceptions import tomlkit.items import umsgpack # type: ignore import yaml import yaml.parser import yaml.scanner __version__ = "0.17.0" FORMATS = ["cbor", "json", "msgpack", "toml", "yaml"] # === YAML === # An ordered dumper for PyYAML. class OrderedDumper(yaml.SafeDumper): pass def mapping_representer(dumper: Any, data: Any) -> Any: return dumper.represent_mapping( yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, data.items() ) OrderedDumper.add_representer(dict, mapping_representer) # Fix loss of time zone information in PyYAML. # http://stackoverflow.com/questions/13294186/can-pyyaml-parse-iso8601-dates class TimezoneLoader(yaml.SafeLoader): pass def timestamp_constructor(loader: Any, node: Any) -> datetime.datetime: return dateutil.parser.parse(node.value) loaders = [TimezoneLoader] for loader in loaders: loader.add_constructor("tag:yaml.org,2002:timestamp", timestamp_constructor) # === CLI === def argv0_to_format(argv0: str) -> Tuple[str, str]: possible_format = "(" + "|".join(FORMATS) + ")" match = re.search("^" + possible_format + "2" + possible_format, argv0) from_, to = match.groups() if match else ("", "") return from_, to def extension_to_format(path: str) -> str: _, ext = os.path.splitext(path) ext = ext[1:] if ext == "yml": ext = "yaml" return ext if ext in FORMATS else "" def parse_command_line(argv: List[str]) -> argparse.Namespace: # noqa: C901. defaults: Dict[str, Any] = { "json_indent": None, "ordered": True, "stringify": False, "yaml_options": {}, } me = os.path.basename(argv[0]) argv0_from, argv0_to = argv0_to_format(me) format_from_argv0 = argv0_to != "" parser = argparse.ArgumentParser( description="Convert between CBOR, JSON, MessagePack, TOML, and YAML." ) parser.add_argument("-v", "--version", action="version", version=__version__) input_group = parser.add_mutually_exclusive_group() input_group.add_argument("input", nargs="?", default="-", help="input file") input_group.add_argument( "-i", "--input", dest="input_flag", metavar="input", default=None, help="input file", ) if not format_from_argv0: parser.add_argument( "--if", "-if", "--input-format", dest="input_format", default="", help="input format", choices=FORMATS, ) if not format_from_argv0 or argv0_to == "json": parser.add_argument( "--json-indent", "--indent-json", dest="json_indent", metavar="n", type=int, default=defaults["json_indent"], help="JSON indentation", ) if not format_from_argv0 or argv0_to in {"json", "toml"}: parser.add_argument( "-k", "--stringify", dest="stringify", action="store_true", help=( "Turn into strings boolean, date-time, and null keys for JSON " "and TOML and null values for TOML" ), ) output_group = parser.add_mutually_exclusive_group() output_group.add_argument("output", nargs="?", default="-", help="output file") output_group.add_argument( "-o", "--output", dest="output_flag", metavar="output", default=None, help="output file", ) if not format_from_argv0: parser.add_argument( "--of", "-of", "--output-format", dest="output_format", default="", help="output format", choices=FORMATS, ) parser.add_argument( "-p", "--preserve-key-order", help=argparse.SUPPRESS, ) if not format_from_argv0 or argv0_to in {"json", "toml", "yaml"}: parser.add_argument( "-s", "--sort-keys", dest="ordered", action="store_false", help="sort JSON, TOML, YAML keys instead of preserving key order", ) parser.add_argument( "--unwrap", dest="unwrap", metavar="key", default=None, help="only output the data stored under the given key", ) parser.add_argument( "--wrap", dest="wrap", metavar="key", default=None, help="wrap the data in a map type with the given key", ) if not format_from_argv0 or argv0_to == "yaml": parser.add_argument( "--yaml-indent", dest="yaml_indent", metavar="n", type=int, default=2, help="YAML indentation", ) parser.add_argument( "--yaml-style", dest="yaml_style", default=None, help="YAML formatting style", choices=["", "'", '"', "|", ">"], ) def yaml_width(value: str) -> int: # This is theoretically compatible with LibYAML. return (1 << 32) - 1 if value.lower() == "inf" else int(value) parser.add_argument( "--yaml-width", dest="yaml_width", metavar="n", type=yaml_width, # Allow "inf". default=80, help="YAML line width for long strings", ) args = parser.parse_args(args=argv[1:]) # Use the positional input and output arguments. if args.input_flag is not None: args.input = args.input_flag if args.output_flag is not None: args.output = args.output_flag # Determine the implicit input and output format if possible. if format_from_argv0: args.input_format = argv0_from args.output_format = argv0_to else: if args.input_format == "": args.input_format = extension_to_format(args.input) if args.input_format == "": parser.error("Need an explicit input format") if args.output_format == "": args.output_format = extension_to_format(args.output) if args.output_format == "": parser.error("Need an explicit output format") for key, value in defaults.items(): vars(args).setdefault(key, value) # Wrap the yaml_* option. if "yaml_indent" in vars(args): vars(args)["yaml_options"] = { "default_style": args.yaml_style, "indent": args.yaml_indent, "width": args.yaml_width, } for key in ["yaml_indent", "yaml_style", "yaml_width"]: del vars(args)[key] return args # === Parser/serializer wrappers === def identity(x: Any) -> Any: return x def traverse( col: Any, dict_callback: Callable[[List[Tuple[Any, Any]]], Any] = lambda x: dict(x), list_callback: Callable[[List[Tuple[Any, Any]]], Any] = identity, key_callback: Callable[[Any], Any] = identity, instance_callbacks: Set[Tuple[type, Any]] = set(), default_callback: Callable[[Any], Any] = identity, ) -> Any: if isinstance(col, dict): res = dict_callback( [ ( key_callback(k), traverse( v, dict_callback, list_callback, key_callback, instance_callbacks, default_callback, ), ) for (k, v) in col.items() ] ) elif isinstance(col, list): res = list_callback( [ traverse( x, dict_callback, list_callback, key_callback, instance_callbacks, default_callback, ) for x in col ] ) else: for t, callback in instance_callbacks: if isinstance(col, t): res = callback(col) break else: res = default_callback(col) return res Document = Union[bool, bytes, datetime.datetime, Mapping, None, Sequence, str] def decode_json(input_data: bytes) -> Document: try: doc = json.loads( input_data.decode("utf-8"), ) return cast(Document, doc) except json.JSONDecodeError as e: msg = f"Cannot parse as JSON ({e})" raise ValueError(msg) def decode_msgpack(input_data: bytes) -> Document: try: doc = umsgpack.unpackb(input_data) return cast(Document, doc) except umsgpack.UnpackException as e: msg = f"Cannot parse as MessagePack ({e})" raise ValueError(msg) def decode_cbor(input_data: bytes) -> Document: try: doc = cbor2.loads(input_data) return cast(Document, doc) except cbor2.CBORDecodeError as e: msg = f"Cannot parse as CBOR ({e})" raise ValueError(msg) def decode_toml(input_data: bytes) -> Document: try: # Remove TOML Kit's custom classes. # https://github.com/sdispater/tomlkit/issues/43 doc = traverse( tomlkit.loads(input_data), instance_callbacks={ (tomlkit.items.Bool, bool), ( tomlkit.items.Date, lambda x: datetime.date( x.year, x.month, x.day, ), ), ( tomlkit.items.DateTime, lambda x: datetime.datetime( x.year, x.month, x.day, x.hour, x.minute, x.second, x.microsecond, x.tzinfo, ), ), (tomlkit.items.Float, float), (tomlkit.items.Integer, int), (tomlkit.items.String, str), ( tomlkit.items.Time, lambda x: datetime.time( x.hour, x.minute, x.second, x.microsecond, x.tzinfo, ), ), }, ) return cast(Document, doc) except tomlkit.exceptions.ParseError as e: msg = f"Cannot parse as TOML ({e})" raise ValueError(msg) def decode_yaml(input_data: bytes) -> Document: try: loader = TimezoneLoader doc = yaml.load(input_data, loader) return cast(Document, doc) except (yaml.scanner.ScannerError, yaml.parser.ParserError) as e: msg = f"Cannot parse as YAML ({e})" raise ValueError(msg) def decode(input_format: str, input_data: bytes) -> Document: decoder = { "cbor": decode_cbor, "json": decode_json, "msgpack": decode_msgpack, "toml": decode_toml, "yaml": decode_yaml, } if input_format not in decoder: msg = f"Unknown input format: {input_format}" raise ValueError(msg) return decoder[input_format](input_data) def reject_special_keys(key: Any) -> Any: if isinstance(key, bool): msg = "boolean key" raise TypeError(msg) if isinstance(key, datetime.datetime): msg = "date-time key" raise TypeError(msg) if key is None: msg = "null key" raise TypeError(msg) return key def stringify_special_keys(key: Any) -> Any: if isinstance(key, bool): return "true" if key else "false" if isinstance(key, datetime.datetime): return key.isoformat() if key is None: return "null" return str(key) def json_default(obj: Any) -> str: if isinstance(obj, datetime.datetime): return obj.isoformat() msg = f"{obj!r} is not JSON-serializable" raise TypeError(msg) def encode_json( data: Document, *, ordered: bool, indent: Union[bool, int, None], stringify: bool, ) -> str: if indent is True: indent = 2 separators = (",", ": " if indent else ":") key_callback = stringify_special_keys if stringify else reject_special_keys try: return ( json.dumps( traverse( data, key_callback=key_callback, ), default=json_default, ensure_ascii=False, indent=indent, separators=separators, sort_keys=not ordered, ) + "\n" ) except (TypeError, ValueError) as e: msg = f"Cannot convert data to JSON ({e})" raise ValueError(msg) def encode_msgpack(data: Document) -> bytes: try: return bytes(umsgpack.packb(data)) except umsgpack.UnsupportedTypeException as e: msg = f"Cannot convert data to MessagePack ({e})" raise ValueError(msg) def encode_cbor(data: Document) -> bytes: try: return bytes(cbor2.dumps(data)) except cbor2.CBOREncodeError as e: msg = f"Cannot convert data to CBOR ({e})" raise ValueError(msg) def encode_toml( data: Mapping[Any, Any], *, ordered: bool, stringify: bool, ) -> str: key_callback = stringify_special_keys if stringify else reject_special_keys def reject_null(x: Any) -> Any: if x is None: msg = "null values are not supported" raise TypeError(msg) return x def stringify_null(x: Any) -> Any: if x is None: return "null" return x default_callback = stringify_null if stringify else reject_null try: return tomlkit.dumps( traverse( data, key_callback=key_callback, default_callback=default_callback, ), sort_keys=not ordered, ) except AttributeError as e: if str(e) == "'list' object has no attribute 'as_string'": msg = ( "Cannot convert non-dictionary data to TOML; " 'use "wrap" to wrap it in a dictionary' ) raise ValueError(msg) else: raise e except (TypeError, ValueError) as e: msg = f"Cannot convert data to TOML ({e})" raise ValueError(msg) def encode_yaml(data: Document, *, ordered: bool, yaml_options: Dict[Any, Any]) -> str: dumper = OrderedDumper if ordered else yaml.SafeDumper try: return yaml.dump( data, None, dumper, allow_unicode=True, default_flow_style=False, encoding=None, **yaml_options, ) except yaml.representer.RepresenterError as e: msg = f"Cannot convert data to YAML ({e})" raise ValueError(msg) def encode( output_format: str, data: Document, *, json_indent: Union[int, None], ordered: bool, stringify: bool, yaml_options: Dict[Any, Any], ) -> bytes: if output_format == "json": encoded = encode_json( data, indent=json_indent, ordered=ordered, stringify=stringify, ).encode("utf-8") elif output_format == "msgpack": encoded = encode_msgpack(data) elif output_format == "toml": if not isinstance(data, Mapping): msg = ( f"Top-level value of type '{type(data).__name__}' cannot " "be encoded as TOML" ) raise TypeError(msg) encoded = encode_toml(data, ordered=ordered, stringify=stringify).encode( "utf-8" ) elif output_format == "yaml": encoded = encode_yaml(data, ordered=ordered, yaml_options=yaml_options).encode( "utf-8" ) elif output_format == "cbor": encoded = encode_cbor(data) else: msg = f"Unknown output format: {output_format}" raise ValueError(msg) return encoded # === Main === def run(argv: List[str]) -> None: args = parse_command_line(argv) remarshal( args.input, args.output, args.input_format, args.output_format, json_indent=args.json_indent, ordered=args.ordered, stringify=args.stringify, unwrap=args.unwrap, wrap=args.wrap, yaml_options=args.yaml_options, ) def remarshal( input: str, output: str, input_format: str, output_format: str, *, json_indent: Union[int, None] = None, ordered: bool = True, stringify: bool = False, transform: Union[Callable[[Document], Document], None] = None, unwrap: Union[str, None] = None, wrap: Union[str, None] = None, yaml_options: Dict[Any, Any] = {}, ) -> None: input_file = None output_file = None try: input_file = sys.stdin.buffer if input == "-" else open(input, "rb") output_file = sys.stdout.buffer if output == "-" else open(output, "wb") input_data = input_file.read() if not isinstance(input_data, bytes): msg = "input_data must be bytes" raise TypeError(msg) parsed = decode(input_format, input_data) if unwrap is not None: if not isinstance(parsed, Mapping): msg = ( f"Top-level value of type '{type(parsed).__name__}' " "cannot be unwrapped" ) raise TypeError(msg) parsed = parsed[unwrap] if wrap is not None: temp = {} temp[wrap] = parsed parsed = temp if transform: parsed = transform(parsed) encoded = encode( output_format, parsed, json_indent=json_indent, ordered=ordered, stringify=stringify, yaml_options=yaml_options, ) output_file.write(encoded) finally: if input_file is not None: input_file.close() if output != "-" and output_file is not None: output_file.close() def main() -> None: try: run(sys.argv) except KeyboardInterrupt: pass except (OSError, TypeError, ValueError) as e: print(f"Error: {e}", file=sys.stderr) # noqa: T201 sys.exit(1) if __name__ == "__main__": main()
/remarshal-0.17.0-py3-none-any.whl/remarshal.py
0.640186
0.175044
remarshal.py
pypi
import functools import io import numpy as np from PIL import Image from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml from pymatting.util.util import stack_images from scipy.ndimage.morphology import binary_erosion from .u2net import detect def alpha_matting_cutout( img, mask, foreground_threshold, background_threshold, erode_structure_size, base_size, ): size = img.size img.thumbnail((base_size, base_size), Image.LANCZOS) mask = mask.resize(img.size, Image.LANCZOS) img = np.asarray(img) mask = np.asarray(mask) # guess likely foreground/background is_foreground = mask > foreground_threshold is_background = mask < background_threshold # erode foreground/background structure = None if erode_structure_size > 0: structure = np.ones((erode_structure_size, erode_structure_size), dtype=np.int) is_foreground = binary_erosion(is_foreground, structure=structure) is_background = binary_erosion(is_background, structure=structure, border_value=1) # build trimap # 0 = background # 128 = unknown # 255 = foreground trimap = np.full(mask.shape, dtype=np.uint8, fill_value=128) trimap[is_foreground] = 255 trimap[is_background] = 0 # build the cutout image img_normalized = img / 255.0 trimap_normalized = trimap / 255.0 alpha = estimate_alpha_cf(img_normalized, trimap_normalized) foreground = estimate_foreground_ml(img_normalized, alpha) cutout = stack_images(foreground, alpha) cutout = np.clip(cutout * 255, 0, 255).astype(np.uint8) cutout = Image.fromarray(cutout) cutout = cutout.resize(size, Image.LANCZOS) return cutout def naive_cutout(img, mask): empty = Image.new("RGBA", (img.size), 0) cutout = Image.composite(img, empty, mask.resize(img.size, Image.LANCZOS)) return cutout @functools.lru_cache(maxsize=None) def get_model(model_name): if model_name == "u2netp": return detect.load_model(model_name="u2netp") if model_name == "u2net_human_seg": return detect.load_model(model_name="u2net_human_seg") if model_name == "carros": return detect.load_model(model_name="carros") else: return detect.load_model(model_name="u2net") def remove( data, model_name="u2net", alpha_matting=False, alpha_matting_foreground_threshold=240, alpha_matting_background_threshold=10, alpha_matting_erode_structure_size=10, alpha_matting_base_size=1000, ): model = get_model(model_name) img = Image.open(io.BytesIO(data)).convert("RGB") mask = detect.predict(model, np.array(img)).convert("L") if alpha_matting: try: cutout = alpha_matting_cutout( img, mask, alpha_matting_foreground_threshold, alpha_matting_background_threshold, alpha_matting_erode_structure_size, alpha_matting_base_size, ) except: cutout = naive_cutout(img, mask) else: cutout = naive_cutout(img, mask) bio = io.BytesIO() cutout.save(bio, "PNG") return bio.getbuffer(), mask.resize(img.size, Image.LANCZOS)
/rembg_cars-1.0.3.tar.gz/rembg_cars-1.0.3/src/rembg/bg.py
0.659186
0.412944
bg.py
pypi
import errno import os import sys import urllib.request import numpy as np import requests import torch import torch.nn as nn import torch.nn.functional as F import torchvision from hsh.library.hash import Hasher from PIL import Image from skimage import transform from torchvision import transforms from tqdm import tqdm from . import data_loader, u2net def download_file_from_google_drive(id, fname, destination): head, tail = os.path.split(destination) os.makedirs(head, exist_ok=True) URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params={"id": id}, stream=True) token = None for key, value in response.cookies.items(): if key.startswith("download_warning"): token = value break if token: params = {"id": id, "confirm": token} response = session.get(URL, params=params, stream=True) total = int(response.headers.get("content-length", 0)) with open(destination, "wb") as file, tqdm( desc=f"Downloading {tail} to {head}", total=total, unit="iB", unit_scale=True, unit_divisor=1024, ) as bar: for data in response.iter_content(chunk_size=1024): size = file.write(data) bar.update(size) def load_model(model_name: str = "u2net"): hasher = Hasher() if model_name == "u2netp": net = u2net.U2NETP(3, 1) path = os.environ.get( "U2NETP_PATH", os.path.expanduser(os.path.join("~", ".u2net", model_name + ".pth")), ) if ( not os.path.exists(path) or hasher.md5(path) != "e4f636406ca4e2af789941e7f139ee2e" ): download_file_from_google_drive( "1rbSTGKAE-MTxBYHd-51l2hMOQPT_7EPy", "u2netp.pth", path, ) elif model_name == "u2net": net = u2net.U2NET(3, 1) path = os.environ.get( "U2NET_PATH", os.path.expanduser(os.path.join("~", ".u2net", model_name + ".pth")), ) if ( not os.path.exists(path) or hasher.md5(path) != "347c3d51b01528e5c6c071e3cff1cb55" ): download_file_from_google_drive( "1ao1ovG1Qtx4b7EoskHXmi2E9rp5CHLcZ", "u2net.pth", path, ) elif model_name == "carros": net = u2net.U2NET(3, 1) path = os.environ.get( "U2NET_PATH", os.path.expanduser(os.path.join("~", ".u2net", model_name + ".pth")), ) elif model_name == "u2net_human_seg": net = u2net.U2NET(3, 1) path = os.environ.get( "U2NET_PATH", os.path.expanduser(os.path.join("~", ".u2net", model_name + ".pth")), ) if ( not os.path.exists(path) or hasher.md5(path) != "09fb4e49b7f785c9f855baf94916840a" ): download_file_from_google_drive( "1-Yg0cxgrNhHP-016FPdp902BR-kSsA4P", "u2net_human_seg.pth", path, ) else: print("Choose between u2net, u2net_human_seg or u2netp", file=sys.stderr) try: if torch.cuda.is_available(): net.load_state_dict(torch.load(path)) net.to(torch.device("cuda")) else: net.load_state_dict( torch.load( path, map_location="cpu", ) ) except FileNotFoundError: raise FileNotFoundError( errno.ENOENT, os.strerror(errno.ENOENT), model_name + ".pth" ) net.eval() return net def norm_pred(d): ma = torch.max(d) mi = torch.min(d) dn = (d - mi) / (ma - mi) return dn def preprocess(image): label_3 = np.zeros(image.shape) label = np.zeros(label_3.shape[0:2]) if 3 == len(label_3.shape): label = label_3[:, :, 0] elif 2 == len(label_3.shape): label = label_3 if 3 == len(image.shape) and 2 == len(label.shape): label = label[:, :, np.newaxis] elif 2 == len(image.shape) and 2 == len(label.shape): image = image[:, :, np.newaxis] label = label[:, :, np.newaxis] transform = transforms.Compose( [data_loader.RescaleT(320), data_loader.ToTensorLab(flag=0)] ) sample = transform({"imidx": np.array([0]), "image": image, "label": label}) return sample def predict(net, item): sample = preprocess(item) with torch.no_grad(): if torch.cuda.is_available(): inputs_test = torch.cuda.FloatTensor( sample["image"].unsqueeze(0).cuda().float() ) else: inputs_test = torch.FloatTensor(sample["image"].unsqueeze(0).float()) d1, d2, d3, d4, d5, d6, d7 = net(inputs_test) pred = d1[:, 0, :, :] predict = norm_pred(pred) predict = predict.squeeze() predict_np = predict.cpu().detach().numpy() img = Image.fromarray(predict_np * 255).convert("RGB") del d1, d2, d3, d4, d5, d6, d7, pred, predict, predict_np, inputs_test, sample return img
/rembg_cars-1.0.3.tar.gz/rembg_cars-1.0.3/src/rembg/u2net/detect.py
0.425605
0.222964
detect.py
pypi
import os import typing import moviepy.editor as mpy import numpy as np import requests import torch import torch.nn.functional import torch.nn.functional from hsh.library.hash import Hasher from tqdm import tqdm from .u2net import u2net DEVICE = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu') def iter_frames(path): return mpy.VideoFileClip(path).resize(height=320).iter_frames(dtype="uint8") class Net(torch.nn.Module): def __init__(self, model_name): super(Net, self).__init__() hasher = Hasher() model, hash_val, drive_target, env_var = { 'u2netp': (u2net.U2NETP, 'e4f636406ca4e2af789941e7f139ee2e', '1rbSTGKAE-MTxBYHd-51l2hMOQPT_7EPy', 'U2NET_PATH'), 'u2net': (u2net.U2NET, '09fb4e49b7f785c9f855baf94916840a', '1-Yg0cxgrNhHP-016FPdp902BR-kSsA4P', 'U2NET_PATH'), 'u2net_human_seg': (u2net.U2NET, '347c3d51b01528e5c6c071e3cff1cb55', '1ao1ovG1Qtx4b7EoskHXmi2E9rp5CHLcZ', 'U2NET_PATH') }[model_name] path = os.environ.get(env_var, os.path.expanduser(os.path.join("~", ".u2net", model_name + ".pth"))) net = model(3, 1) if not os.path.exists(path) or hasher.md5(path) != hash_val: head, tail = os.path.split(path) os.makedirs(head, exist_ok=True) URL = "https://docs.google.com/uc?export=download" session = requests.Session() response = session.get(URL, params={"id": drive_target}, stream=True) token = None for key, value in response.cookies.items(): if key.startswith("download_warning"): token = value break if token: params = {"id": drive_target, "confirm": token} response = session.get(URL, params=params, stream=True) total = int(response.headers.get("content-length", 0)) with open(path, "wb") as file, tqdm( desc=f"Downloading {tail} to {head}", total=total, unit="iB", unit_scale=True, unit_divisor=1024, ) as bar: for data in response.iter_content(chunk_size=1024): size = file.write(data) bar.update(size) net.load_state_dict(torch.load(path, map_location=torch.device(DEVICE))) net.to(device=DEVICE, dtype=torch.float32, non_blocking=True) net.eval() self.net = net def forward(self, block_input: torch.Tensor): image_data = block_input.permute(0, 3, 1, 2) original_shape = image_data.shape[2:] image_data = torch.nn.functional.interpolate(image_data, (320, 320), mode='bilinear') image_data = (image_data / 255 - 0.485) / 0.229 out = self.net(image_data)[:, 0:1] ma = torch.max(out) mi = torch.min(out) out = (out - mi) / (ma - mi) * 255 out = torch.nn.functional.interpolate(out, original_shape, mode='bilinear') out = out[:, 0] out = out.to(dtype=torch.uint8, device=torch.device('cpu'), non_blocking=True).detach() return out @torch.no_grad() def remove_many(image_data: typing.List[np.array], net: Net): image_data = np.stack(image_data) image_data = torch.as_tensor(image_data, dtype=torch.float32, device=DEVICE) return net(image_data).numpy()
/rembg_greenscreen-2.1.10-py3-none-any.whl/rembg/bg.py
0.797281
0.218815
bg.py
pypi
import requests import sys import re import json import base64 import os from remedy import exceptions class RemedyClient: """ A REST Client class for BMC Remedy ITSM. :param endpoint: Remedy endpoint. :type endpoint: str :param proxies: List of proxies :type proxies: dict :param username: Username :type username: str :param password: User password :type password: str """ def __init__(self, endpoint="", proxies=None, username="", password=""): self.endpoint = endpoint self.proxies = proxies self.username = username self.password = password self.endpoint_smartit = self.endpoint.replace('-restapi','-smartit') self.headers = {} self.authenticate() def query(self, uri, data=None, params=None, headers={}, method='GET'): """ Request the uri and returns the response. :param uri: Remedy API uri.. :type uri: str :param data: Request data. :type data: dict :param params: Request parameters. :type params: dict :param headers: Request headers. :type headers: dict :param method: HTTP method. :type method: str :returns: HTTP Status Code :rtype: integer """ url = f'{self.endpoint}{uri}' headers.update(self.headers) response = requests.request( method, url, data=data, params=params, headers=headers, proxies=self.proxies ) if response.status_code not in [200, 201, 204]: raise exceptions.RemedyError(f'{response.status_code} - {response.text}') try: return response.json() except: return response.text def close(self): """ Close the connection to BMC Remedy ITSM. :returns: HTTP Status Code :rtype: integer """ return self.delete_token() def authenticate(self): """ Authenticat against BMC Remedy ITSM. :returns: is_authenticated :rtype: bool """ token = self.get_token() self.token = f'AR-JWT {token}' self.headers = { 'Authorization': self.token } return True def is_authenticated(self): """ Returns if the client is authenticated :returns: is_authenticated :rtype: bool """ if not self.token: return False return True def get_token(self): """ Return token using the URI `api/jwt/login` and update the class instance attribute with that value. :returns: token :rtype: str """ uri = f'/api/jwt/login' params = [ ('username', self.username), ('password', self.password) ] headers = { 'Content-Type': 'application/x-www-form-urlencoded' } token = self.query(uri, method='POST', headers=headers, params=params) return token def delete_token(self): """ Delete token using the URI `api/jwt/logout` :returns: HTTP Status Code :rtype: int """ uri = f'/api/jwt/logout' headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } response = self.query(uri, method='POST', headers=headers) return response def get_form(self, form_name): """ Query Remedy form using the URI `/api/arsys/v1/entry/:form_name` :param form_name: Remedy form name :type form_name: str :returns: Form :rtype: dict """ uri = f'/api/arsys/v1/entry/{form_name}' headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } response = self.query(uri, method='GET', headers=headers) return response
/remedy-client-0.1.0.tar.gz/remedy-client-0.1.0/remedy/remedy.py
0.544559
0.153296
remedy.py
pypi
import json from collections import Counter, defaultdict from copy import deepcopy from dataclasses import dataclass, field from enum import Enum from functools import cached_property from itertools import groupby, islice from pathlib import Path from typing import Callable from typing import Counter as CounterType from typing import ( DefaultDict, Dict, Final, Iterable, List, Literal, NamedTuple, NewType, Optional, Set, Sized, Tuple, ) import numpy as np import numpy.typing as npt from tqdm import tqdm, trange _SMALL: Final[float] = 1e-10 SelectionMethod = Literal["frequency", "log_likelihood", "npmi"] class Lexeme(NamedTuple): word: Tuple[str, ...] ix: int def __repr__(self) -> str: return f"({self.word}|{self.ix})" LineIndex = NewType("LineIndex", int) TokenIndex = NewType("TokenIndex", int) @dataclass class LexemeData: lexemes_to_locations: DefaultDict[ Lexeme, Set[Tuple[LineIndex, TokenIndex]] ] = field(default_factory=lambda: defaultdict(set)) locations_to_lexemes: List[List[Lexeme]] = field(default_factory=list) lexemes_to_freqs: Dict[Lexeme, int] = field(default_factory=dict) @classmethod def from_corpus( cls, corpus: Iterable[Iterable[str]], progress_bar: bool = False ) -> "LexemeData": lexeme_data = cls() total: Optional[int] = len(corpus) if isinstance(corpus, Sized) else None corpus_iter = enumerate(corpus) if progress_bar: corpus_iter = tqdm( corpus_iter, desc="Creating LexemeData from Corpus", unit="line", total=total, ) for (line_ix, tokens) in corpus_iter: line_lexemes = [] for (word_ix, word) in enumerate(tokens): line_ix = LineIndex(line_ix) word_ix = TokenIndex(word_ix) lexeme = Lexeme(word=(word,), ix=0) loc = (line_ix, word_ix) lexeme_data.lexemes_to_locations[lexeme].add(loc) line_lexemes.append(lexeme) lexeme_data.locations_to_lexemes.append(line_lexemes) # Using this conditional prevents double counting merged lexemes. lexeme_data.lexemes_to_freqs = { k: len(v) for k, v in lexeme_data.lexemes_to_locations.items() if k.ix == 0 } return lexeme_data @property def corpus_length(self) -> int: """Returns number of lines in corpus: max(line_ix) + 1.""" return len(self.locations_to_lexemes) def render_corpus(self) -> List[List[Lexeme]]: return self.locations_to_lexemes def locations_to_root_lexemes(self, line: LineIndex) -> Dict[TokenIndex, Lexeme]: lexeme_dicts = self.locations_to_lexemes[line] return {TokenIndex(k): v for k, v in enumerate(lexeme_dicts) if v.ix == 0} Bigram = Tuple[Lexeme, Lexeme] def _count_bigram_line(*args): el1c = [b[0] for b in args] el2c = [b[1] for b in args] bc = [b for b in args] return (el1c, el2c, bc) @dataclass class BigramData: bigrams_to_freqs: CounterType[Bigram] = field(default_factory=Counter) bigrams_to_locations: Dict[Bigram, List[Tuple[LineIndex, TokenIndex]]] = field( default_factory=lambda: defaultdict(list) ) left_lex_freqs: CounterType[Lexeme] = field(default_factory=Counter) right_lex_freqs: CounterType[Lexeme] = field(default_factory=Counter) @classmethod def from_lexemes( cls, lexeme_data: LexemeData, progress_bar: bool = False ) -> "BigramData": bigram_data = cls() corpus_iter = range(lexeme_data.corpus_length) if progress_bar: corpus_iter = tqdm( corpus_iter, desc="Creating BigramData from LexemeData", unit="line", total=lexeme_data.corpus_length - 1, ) for line_ix in corpus_iter: line_lexeme_data = lexeme_data.locations_to_root_lexemes(LineIndex(line_ix)) line_items = line_lexeme_data.items() line_bigrams = [] for (left_ix, left), (_, right) in zip( line_items, islice(line_items, 1, None) ): bigram = (left, right) location = (LineIndex(line_ix), TokenIndex(left_ix)) bigram_data.bigrams_to_locations[bigram].append(location) line_bigrams.append(bigram) bigram_data.batch_add_bigrams(line_bigrams) return bigram_data def batch_add_bigrams(self, bigram_locations: List[Bigram]): el1s, el2s, bigrams = _count_bigram_line(*bigram_locations) self.left_lex_freqs.update(el1s) self.right_lex_freqs.update(el2s) self.bigrams_to_freqs.update(bigrams) @dataclass class WinnerInfo: bigram: Bigram merged_lexeme: Lexeme bigram_locations: List[Tuple[LineIndex, TokenIndex]] @classmethod def from_bigram_with_data( cls, bigram: Bigram, bigram_data: BigramData ) -> "WinnerInfo": el1_words = list(bigram[0].word) el2_words = list(bigram[1].word) all_words = el1_words + el2_words new_lexeme = Lexeme(word=tuple(all_words), ix=0) locations = sorted(bigram_data.bigrams_to_locations[bigram]) return cls(bigram=bigram, merged_lexeme=new_lexeme, bigram_locations=locations) def clean_bigram_locations(self) -> List[Tuple[LineIndex, TokenIndex]]: """This is greedily selecting correct bigrams from the candidate locations of bigrams. Why? Well, in the case of a sentence like (a, a, a), with winner = (a, a), we can only convert the first occurrence of this bigram and not the second, since the first occurence would be transformed into the bigram, the new bigram in the second position no longer exists - but could be a candidate for the next round if it is indeed that common of a pattern. A more complex example is with winner (a, b, a, b) in ((a, b), (a, b), (a, b)). Here is the same idea: once we merge the first occurence it is no longer available, even though it occurs later. """ clean_locations: List[Tuple[LineIndex, TokenIndex]] = [] for line, location in groupby(self.bigram_locations, key=lambda x: x[0]): exclude_token: Set[TokenIndex] = set() token_ix = [i[1] for i in location] for token in token_ix: if token in exclude_token: continue excludes = [i for i in token_ix if i < token + self.n_lexemes] exclude_token.update(excludes) clean_locations.append((line, token)) return clean_locations @property def n_lexemes(self) -> int: return len(self.merged_lexeme.word) @property def merge_token_count(self) -> int: # TODO: Optimize by putting in loop so we don't have to iterate here return len(self.clean_bigram_locations()) def merge_winner( winner: WinnerInfo, lexeme_data: LexemeData, bigram_data: BigramData ) -> Tuple[LexemeData, BigramData]: bigram_lines = set(i[0] for i in winner.clean_bigram_locations()) old_bigrams_lookup = { line_ix: list(lexeme_data.locations_to_root_lexemes(LineIndex(line_ix)).items()) for line_ix in bigram_lines } for (line_ix, word_ix) in winner.clean_bigram_locations(): for lexeme_index in range(winner.n_lexemes): pos = TokenIndex(word_ix + lexeme_index) old_lexeme = lexeme_data.locations_to_lexemes[line_ix][pos] lexeme = Lexeme(word=winner.merged_lexeme.word, ix=lexeme_index) lexeme_data.locations_to_lexemes[line_ix][pos] = lexeme lexeme_data.lexemes_to_locations[old_lexeme].remove((line_ix, pos)) lexeme_data.lexemes_to_locations[lexeme].add((line_ix, pos)) for line_ix, lexemes in old_bigrams_lookup.items(): old_bigrams = list( zip([l[1] for l in lexemes], islice([l[1] for l in lexemes], 1, None)) ) new_root_lexemes_items = list( lexeme_data.locations_to_root_lexemes(LineIndex(line_ix)).items() ) new_root_lexemes = list(lex for _, lex in new_root_lexemes_items) new_bigrams = list(zip(new_root_lexemes, islice(new_root_lexemes, 1, None))) bigram_data.bigrams_to_freqs.update(new_bigrams) bigram_data.left_lex_freqs.update([b[0] for b in new_bigrams]) bigram_data.right_lex_freqs.update([b[1] for b in new_bigrams]) bigram_data.bigrams_to_freqs.subtract(old_bigrams) bigram_data.left_lex_freqs.subtract([b[0] for b in old_bigrams]) bigram_data.right_lex_freqs.subtract([b[1] for b in old_bigrams]) for (left_ix, left), (_, right) in zip(lexemes, islice(lexemes, 1, None)): bigram = (left, right) location = (LineIndex(line_ix), TokenIndex(left_ix)) bigram_data.bigrams_to_locations[bigram].remove(location) for (left_ix, left), (_, right) in zip( new_root_lexemes_items, islice(new_root_lexemes_items, 1, None) ): bigram = (left, right) location = (LineIndex(line_ix), TokenIndex(left_ix)) bigram_data.bigrams_to_locations[bigram].append(location) lexeme_data.lexemes_to_freqs[winner.merged_lexeme] = winner.merge_token_count el1_freq = lexeme_data.lexemes_to_freqs[winner.bigram[0]] new_el1_freq = el1_freq - winner.merge_token_count lexeme_data.lexemes_to_freqs[winner.bigram[0]] = new_el1_freq el2_freq = lexeme_data.lexemes_to_freqs[winner.bigram[1]] new_el2_freq = el2_freq - winner.merge_token_count lexeme_data.lexemes_to_freqs[winner.bigram[1]] = new_el2_freq lexeme_data.lexemes_to_freqs = { k: v for k, v in lexeme_data.lexemes_to_freqs.items() if v != 0 } lexeme_data.lexemes_to_locations = defaultdict( set, {k: v for k, v in lexeme_data.lexemes_to_locations.items() if v != set()} ) bigram_data.bigrams_to_freqs = Counter( {k: v for k, v in bigram_data.bigrams_to_freqs.items() if v > 0} ) bigram_data.left_lex_freqs = Counter( {k: v for k, v in bigram_data.left_lex_freqs.items() if v > 0} ) bigram_data.right_lex_freqs = Counter( {k: v for k, v in bigram_data.right_lex_freqs.items() if v > 0} ) assert winner.bigram not in bigram_data.bigrams_to_freqs return lexeme_data, bigram_data # NamedTuple doesn't support cached_property @dataclass(frozen=True) class BigramFreqArrays: bigram_index: List[Bigram] bigram_freq_array: npt.NDArray[np.int_] el1_freq_array: npt.NDArray[np.int_] el2_freq_array: npt.NDArray[np.int_] @cached_property def bigram_count(self) -> np.int_: return self.bigram_freq_array.sum() @classmethod def from_bigram_data( cls, bigram_data: BigramData, min_count: int = 0 ) -> "BigramFreqArrays": length = len( [i for i in bigram_data.bigrams_to_freqs.values() if i >= min_count] ) bigram_freq_array = np.empty(length, dtype=np.int_) el1_freq_array = np.empty(length, dtype=np.int_) el2_freq_array = np.empty(length, dtype=np.int_) bigram_index = [] i = 0 for (bigram, freq) in bigram_data.bigrams_to_freqs.items(): if freq < min_count: continue bigram_freq_array[i] = freq l1 = bigram_data.left_lex_freqs[bigram[0]] el1_freq_array[i] = l1 l2 = bigram_data.right_lex_freqs[bigram[1]] el2_freq_array[i] = l2 bigram_index.append(bigram) i += 1 # manually count instead of enumerate return cls(bigram_index, bigram_freq_array, el1_freq_array, el2_freq_array) def calculate_winner_log_likelihood( bigram_data: BigramData, min_count: int = 0 ) -> Bigram: data = BigramFreqArrays.from_bigram_data(bigram_data, min_count=min_count) log_likelihoods = _calculate_log_likelihood(data) winner_ix = np.argmax(log_likelihoods) winner: Bigram = data.bigram_index[winner_ix] return winner def calculate_winner_npmi(bigram_data: BigramData, min_count: int = 0) -> Bigram: data = BigramFreqArrays.from_bigram_data(bigram_data, min_count=min_count) npmis = _calculate_npmi(data) winner_ix = np.argmax(npmis) winner: Bigram = data.bigram_index[winner_ix] return winner def calculate_winner_frequency(bigrams: BigramData, min_count: int = 0) -> Bigram: return bigrams.bigrams_to_freqs.most_common(1)[0][0] def _calculate_npmi(data: BigramFreqArrays) -> npt.NDArray[np.float_]: prob_ab = data.bigram_freq_array / data.bigram_count prob_a = data.el1_freq_array / data.bigram_count prob_b = data.el2_freq_array / data.bigram_count npmi = np.log(prob_ab / (prob_a * prob_b)) / -(np.log(prob_ab)) return npmi def _calculate_log_likelihood(data: BigramFreqArrays) -> npt.NDArray[np.float_]: # For reference, see also: nltk.collocations.BigramAssocMeasures, specifically _contingency # http://ecologyandevolution.org/statsdocs/online-stats-manual-chapter4.html obsA = data.bigram_freq_array obsB = data.el1_freq_array - obsA obsC = data.el2_freq_array - obsA obsD = data.bigram_count - obsA - obsB - obsC expA = ((obsA + obsB) * (obsA + obsC)) / data.bigram_count expB = ((obsA + obsB) * (obsB + obsD)) / data.bigram_count expC = ((obsC + obsD) * (obsA + obsC)) / data.bigram_count expD = ((obsC + obsD) * (obsB + obsD)) / data.bigram_count llA = obsA * np.log((obsA / (expA + _SMALL)) + _SMALL) llB = obsB * np.log((obsB / (expB + _SMALL)) + _SMALL) llC = obsC * np.log((obsC / (expC + _SMALL)) + _SMALL) llD = obsD * np.log((obsD / (expD + _SMALL)) + _SMALL) log_likelihood = 2.0 * (llA + llB + llC + llD) log_likelihood = np.where(llA > 0, log_likelihood, log_likelihood * -1.0) return log_likelihood SELECTION_METHODS: Dict[SelectionMethod, Callable[[BigramData, int], Bigram]] = { "log_likelihood": calculate_winner_log_likelihood, "frequency": calculate_winner_frequency, "npmi": calculate_winner_npmi, } ProgressBarOptions = Literal["all", "iterations", "none"] def run( corpus: List[List[str]], iterations: int, *, method: SelectionMethod = "log_likelihood", min_count: int = 0, output: Optional[Path] = None, progress_bar: ProgressBarOptions = "iterations", ) -> List[WinnerInfo]: """Run the remerge algorithm. Args: corpus (List[List[str]]): A corpus of already tokenized texts. iterations (int): The number of iterations to run the algorithm. Papers typically use >500. method (SelectionMethod, optional): One of "frequency", "log_likelihood", or "npmi". Defaults to "log_likelihood". min_count (int, optional): The minimum count required for a bigram to be included in the winner calculations. If choosing NPMI ("npmi") as the selection method, prefer using min_count because this measure is biased towards infrequent word pairs. Defaults to 0. output (Optional[Path], optional): A file path to output the winning merged lexemes as JSON. Defaults to None. progress_bar (ProgressBarOptions, optional): Verbosity of progress bar. "all" will display the lexeme and bigram construction progress each iteration plus total iteration progress. "iterations" will display progress on the total number of iterations. "none" has no output. Defaults to "iterations". Returns: List[WinnerInfo]: The winning bigram from each iteration. """ winners: List[WinnerInfo] = [] all_progress = progress_bar == "all" lexemes = LexemeData.from_corpus(corpus, progress_bar=all_progress) bigrams = BigramData.from_lexemes(lexemes, progress_bar=all_progress) winner_selection_function = SELECTION_METHODS[method] if output is not None: print(f"Outputting winning merged lexemes to '{output}'") iterations_iter = ( trange(iterations) if progress_bar in {"all", "iterations"} else range(iterations) ) for _ in iterations_iter: winning_bigram = winner_selection_function(bigrams, min_count) winner = WinnerInfo.from_bigram_with_data( bigram=winning_bigram, bigram_data=bigrams ) winners.append(winner) if output: winner_lexemes = {i: w.merged_lexeme.word for i, w in enumerate(winners)} output.write_text(json.dumps(winner_lexemes)) lexemes, bigrams = merge_winner(winner, lexemes, bigrams) if isinstance(iterations_iter, tqdm): lines = set(w[0] for w in winner.bigram_locations) pct_bgr = len(lines) / lexemes.corpus_length iterations_iter.set_postfix( { "last_winner": winner.merged_lexeme.word, "pct_bgr": f"{pct_bgr*100:.1f}%", } ) return winners
/remerge_mwe-0.2.1-py3-none-any.whl/remerge/core.py
0.840979
0.284265
core.py
pypi
Go directly to: - [**Installation**](https://github.com/m-guggenmos/remeta/blob/master/INSTALL.md) - [**Basic Usage**](https://github.com/m-guggenmos/remeta/blob/master/demo/basic_usage.ipynb) - [**Common use cases**](https://github.com/m-guggenmos/remeta/blob/master/demo/common_use_cases.ipynb) - [**Exotic use cases**](https://github.com/m-guggenmos/remeta/blob/master/demo/exotic_use_cases.ipynb) # ReMeta Toolbox The ReMeta toolbox allows researchers to estimate latent type 1 and type 2 parameters based on data of cognitive or perceptual decision-making tasks with two response categories. ### Minimal example Three types of data are required to fit a model: - `stimuli`: list/array of signed stimulus intensity values, where the sign codes the stimulus category and the absolute value codes the intensity. The stimuli should be normalized to [-1; 1], although there is a setting (`normalize_stimuli_by_max`) to auto-normalize stimuli. - `choices`: list/array of choices coded as 0 (or alternatively -1) for the negative stimuli category and 1 for the positive stimulus category. - `confidence`: list/array of confidence ratings. Confidence ratings must be normalized to [0; 1]. Discrete confidence ratings must be normalized accordingly (e.g., if confidence ratings are 1-4, subtract 1 and divide by 3). A minimal example would be the following: ```python # Minimal example import remeta stimuli, choices, confidence = remeta.load_dataset('simple') # load example dataset rem = remeta.ReMeta() rem.fit(stimuli, choices, confidence) ``` Output: ``` Loading dataset 'simple' which was generated as follows: ..Generative model: Metatacognitive noise type: noisy_report Metatacognitive noise distribution: truncated_norm Link function: probability_correct ..Generative parameters: noise_sens: 0.7 bias_sens: 0.2 noise_meta: 0.1 evidence_bias_mult_meta: 1.2 ..Characteristics: No. subjects: 1 No. samples: 1000 Type 1 performance: 78.5% Avg. confidence: 0.668 M-Ratio: 0.921 +++ Sensory level +++ Initial guess (neg. LL: 1902.65) [guess] noise_sens: 0.1 [guess] bias_sens: 0 Performing local optimization [final] noise_sens: 0.745 (true: 0.7) [final] bias_sens: 0.24 (true: 0.2) Final neg. LL: 461.45 Neg. LL using true params: 462.64 Total fitting time: 0.15 secs +++ Metacognitive level +++ Initial guess (neg. LL: 1938.81) [guess] noise_meta: 0.2 [guess] evidence_bias_mult_meta: 1 Grid search activated (grid size = 60) [grid] noise_meta: 0.15 [grid] evidence_bias_mult_meta: 1.4 Grid neg. LL: 1879.3 Grid runtime: 2.43 secs Performing local optimization [final] noise_meta: 0.102 (true: 0.1) [final] evidence_bias_mult_meta: 1.21 (true: 1.2) Final neg. LL: 1872.24 Neg. LL using true params: 1872.27 Total fitting time: 3.4 secs ``` Since the dataset is based on simulation, we know the true parameters (in brackets above) of the underlying generative model, which are indeed quite close to the fitted parameters. We can access the fitted parameters by invoking the `summary()` method on the `ReMeta` instance: ```python # Access fitted parameters result = rem.summary() for k, v in result.model.params.items(): print(f'{k}: {v:.3f}') ``` Ouput: ``` noise_sens: 0.745 bias_sens: 0.240 noise_meta: 0.102 evidence_bias_mult_meta: 1.213 ``` By default, the model fits parameters for type 1 noise (`noise_sens`) and a type 1 bias (`bias_sens`), as well as metacognitive 'type 2' noise (`noise_meta`) and a metacognitive bias (`evidence_bias_mult_meta`). Moreover, by default the model assumes that metacognitive noise occurs at the stage of the confidence report (setting `meta_noise_type='noisy_report'`), that observers aim at reporting probability correct with their confidence ratings (setting `meta_link_function='probability_correct'`) and that metacognitive noise can be described by a truncated normal distribution (setting `meta_noise_dist='truncated_norm'`). All settings can be changed via the `Configuration` object which is optionally passed to the `ReMeta` instance. For example: ```python cfg = remeta.Configuration() cfg.meta_noise_type = 'noisy_readout' rem = remeta.ReMeta(cfg) ... ``` ### Supported parameters _Type 1 parameters_: - `noise_sens`: type 1 noise - `bias_sens`: type 1 bias towards one of the two stimulus categories - `thresh_sens`: a (sensory) threshold, building on the assumption that a certain minimal stimulus intensity is required to elicit behavior; use only if there are stimulus intensities close to threshold - `noise_transform_sens`: parameter to specify stimulus-dependent type 1 noise (e.g. multiplicative noise) - `warping`: a nonlinear transducer parameter, allowing for nonlinear transformations of stimulus intensities- _Type 2 (metacognitive) parameters:_ - `noise_meta`: metacognitive noise - `evidence_bias_mult_meta`: multiplicative metacognitive bias applying at the level of evidence - `evidence_bias_add_meta`: additive metacognitive bias applying at the level of evidence - `confidence_bias_mult_meta`: multiplicative metacognitive bias applying at the level of confidence - `confidence_bias_add_meta`: additive metacognitive bias applying at the level of confidence - `noise_transform_meta`: (experimental) parameter to specify decision-value-dependent type 2 noise (e.g. multiplicative noise) - `criterion{i}_meta`: i-th confidence criterion (in case of a criterion-based link function) - `level{i}_meta`: i-th confidence level (in case of a criterion-based link function, confidence levels correspond to the confidence at the respective criteria) In addition, each parameter can be fitted in "duplex mode", such that separate values are fitted depending on the stimulus category (for type 1 parameters) or depending on the sign of the type 1 decision values (for type 2 parameters). A more detailed guide to use the toolbox is provided in the following Jupyter notebook: [**Basic Usage**](https://github.com/m-guggenmos/remeta/blob/master/demo/basic_usage.ipynb)
/remeta-0.1.8.tar.gz/remeta-0.1.8/README.md
0.778355
0.960287
README.md
pypi
import remi.gui from remi.gui import * import remi.gui as gui from threading import Timer # https://python-snap7.readthedocs.io/en/latest/util.html # https://github.com/gijzelaerr/python-snap7/blob/master/example/boolean.py class TimerWidget(Image): icon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACkAAAAvCAYAAAB+OePrAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAABswAAAbMBHmbrhwAAABl0RVh0U29mdHdhcmUAd3d3Lmlua3NjYXBlLm9yZ5vuPBoAAAkTSURBVFiFvZltcFTlFcd/594lb0JChCoUqsEiSLGWQkbbsdo4yMQZsluazlptB0sh3KShjtLOVOuo3daO1nbUDwqTuxuZiKPVItbsJsE3OvGtdipYo/JSwI5QZ0EwBAkhm83uPf2wu/EmbkhurP6/7DznPOec/5773PM8z7nCBFBdXX12QUGBpaoLRGSmqp4tIpOAQlUtEpEEMKCqgyJyXFUPi8gex3Hs9vb2Hq/xxMvkUChk7Ny581HgCuArXoOp6iHDMF5ZvHjxDaFQyBmvneElSFdX13QRqZoIQQAROU9Vq7q6uqZ7sTO9TN67d2/fhRde+KaIlAI+ESkECsZh2quqB0WkE7iltbV1t5e4nh63G8Fg0Ozv718CvJAlnReqehJYVlxcvHPLli3picSaMEkAv98/XUR2maZ5jmmaiAiGYeA4DqpKOp0mnU4fVdWFsVjso4nGmRDJNWvWzPX5fNc5jnONiHybM6xtVXVE5O/As8AT4XD4vc+VZH19/TWqeitwpVfbLFRVXxKRe8Lh8PPjNRpXoIaGhotVdaOqXjEBYqPhZVVtjEQiu8aaOBZJqa+v/5Wq3gVMyqN/X1W3G4bxT8dx/m2aZreInFbVEmC6qs5zHOdSEbkaOD+P/aCq3haJRO4D1DPJ9evXF586derPIvK9Eaq0qv5FRDaGw+HXcs79fn99LBazc5P8fv+3gHgsFjsEiGVZl6tqo4hcy6dL39PJZPLHLS0tiXxc8i741atXTzl9+vRzeQg+r6pfE5GfxOPxJK5/LyJ9QCXwJIDjOGXpdLooq9aenp639u/ffwNwMbB9hN/agoKCZxsbGyfn4/OpTAaDwYLy8vJ24GqXOCEi623bbsrOmdzf339zW1vb70eYLwfaAB8wrCb6/f5rgcJYLPYogGVZ64D7gEJ3EoCacDg8eEaSlmXZgOUSnTAMo6a7u/sf4yjGy7KBSoD+MeZiWdZ3gBgwdYiQyEbbtte55xkjjIIjCPY6jnN1U1PTawMDA5sCgcCXx4ibzP6OuVUGAoH7jhw50iUiy4DenFxVG+vr62vzkly1atVU4EGXzlHVYHNz806AGTNm1EWj0fgYsXOPKV8lGAYReTgajfbatr1DRK4Dhk5FqvrQjTfeOLTVDpGcNGnSHcC5Lif3RiKR53LjketkFIw7k+5Dhm3bHSJyv0s9c2Bg4PYhLgDr1q2bNjg4+D6Qe7veSyaTF3d3d//acZxH2tvb/zMOggCXAF3AHOD98RhUVVX5pkyZcuXcuXNf7+vr25W1BegDKsLh8EcGwODgYIOLIKp6W0tLS8IwjOaSkpKD4yQIZ85kGfAwcE4e3aUPPPBAv6re4ZKdpaprIVMqAG5wKd87ceLEVoDW1tb/eiAIo6/JWWRK0yIy2f4ucBqgs7MzBfwBYNasWU/G4/G7yGZTRFYC9xiWZX0dmOdy+MhEz33kz2QlsCNLEGAxcFU+41AolAI2u0QL6urqFvhEpEr1k21TRLYGAoGbVHVnLBZ79TOSXAE8RqZuAiSAVUD7SMPq6uqzCwsLFziO87RhGL9x8bnKAC5zzf3Qtu09wKaioqK3PBIcSfImYKuL4BEyR7wn8xkahlGiquc3Nze/AxxzqS7zqep8l6AL0Gg02svEkFuTvyCTxRx2kdkyR30Jt23b9gHweHb4NrAUQETmGwy/+Xk+NbtQXFZWtmnatGmUlJS4Cb4AXH4mgiOhqvtdw/MMwH2J6qmtrZ0ZCASWeWVYWlp695w5c4IVFRXMmzePoqIigE1kMvixF1+GYbgbCKU+hpeLZH9/v2ma5pjb2kj4fL7Zppk5JpqmSWFh4duJRGKNFx9+v/8xVX1IVQdc4kIfmXqVy+ZZ2bXxgVeSAwMDf+3p6VlaXl5e3tPTczydTt/t1Uc6nb7NNM1jwA9c4lM+4LiL5EyvjnPo6+t7PB6PHz169Kg/lUq1JhKJv3n10dHRcRDAsiw3j+M+4ABQkRXMBwgEAlNOnjzZn90Nxo1EIvEi8KJXciMhIvNdtfuAT0R2qWruFP4Ny7JK4vH4XVOnTn2Qz/a2e0IgEJibSqUmV1RUHEilUpe4VLt8juO8IiI3ZQUFInJlW1vbzV8UuRxSqdRkn89XOjg4WJVtI+bwslFQUNDJJ0UYVf3RF00QoKOj461oNPqyiFzvEieTyWSnsWHDhm4y95IcgrmFu3z58vIvkmhjY+MM4Pu5sapua2lpOWFkBw+75hYBvwwGg6ZhGM2hUMhTD9MrVqxYUZHbPNLp9K1AsUu9CbIn81AoZMTj8XeBBVll0nGcRc3NzXs+T4IAfr//PFW9YPbs2R85jvMmn2wu74bD4UsANbIkHRG502VbYBjG5mAwOJ4G6WdCLBY7NGfOnNcdx9nsIoiI3E62+TD0KG3bforha7OyvLx8A2QeSU1NjecdZDQEg8Fiv99/UY5PMplsAr6Z06tqh23brbnxsPXm8/nqgG6XqM6yrHufeeaZg+l0euP/i2QikbhAVavINMT+qKqrXOpjpmm67/7DG0dvvPHGycrKyneBH7r+wOVLliyZ5TjOlt27d6cBli9fvmDhwoWpvXv35m0w5UMoFDI6OzsVYN++fceqq6vfWbRokQ24uxUpVQ2Gw+F/uW0/9ebatt0B/Izhrbi68vLyV+vq6hYAGIZRqapevkDIjh07ngsGgybA2rVrFyaTydeA1a45qqr17rv+kPFoXi3LqgOaGJ7tJPCg4zh/am5u/jAnrKmpaQB629raHgOora2dmUwmf9vW1jb02ILBoFlWVjbdMIxbgJ8z/IiYEpEG27bdpXBsktl/XCMim4GRRb0f2Kqqj4vIS+Fw+LRbWVVV5SstLS2ORqO9K1euPKu4uLhKRK5X1VqG10GAblVdGYlEto3GY8x2dENDQ4XjOJsY5RoKJEXkHcdx9onIMVXtF5FiVf2SiMwn048crZS9CKwJh8OHzsRhvM15sSzreuB3wFfHaXMm7FfVOyORyBPjCu7FcygU8h0+fDjoOM5PRWQp3j77pYHtIrLp+PHjT3lpQEz4Y1NdXd25hmEszX6RuEhE5gJTyPR8Pibzqe6AiOwRkVdEZHtTU9PRicT6H1Vcp8nifY8WAAAAAElFTkSuQmCC" stop = True #the stop flag for the timer, when True the timer stops @property @gui.editor_attribute_decorator('WidgetSpecific','The Interval in milliseconds', int, {'default':0, 'min':0, 'max':65535, 'step':1}) def interval_milliseconds(self): return self.__interval_milliseconds @interval_milliseconds.setter def interval_milliseconds(self, v): self.__interval_milliseconds = v @property @gui.editor_attribute_decorator('WidgetSpecific','The autostart flag, if True the timer starts at creation', bool, {}) def autostart(self): return self.__autostart @autostart.setter def autostart(self, v): self.__autostart = v if self.__autostart: self.start() else: self.stop = True def __init__(self, interval_milliseconds=1000, autostart=True, *args, **kwargs): self.__interval_milliseconds = interval_milliseconds self.__autostart = autostart super(TimerWidget, self).__init__(self.icon, *args, **kwargs) self.style.update({'position':'absolute','left':'10px','top':'10px','width':'46px','height':'46px'}) self.stop = False if autostart: self.onelapsed() @gui.decorate_set_on_listener("(self, emitter)") @gui.decorate_event def onelapsed(self, *args): if not self.stop: Timer(self.interval_milliseconds/1000.0, self.onelapsed).start() self.stop = False return () def stop(self, *args): self.stop = True def start(self, *args): if self.stop: self.onelapsed()
/remi-2022.7.27-py3-none-any.whl/editor/widgets/toolbox_scheduling.py
0.432423
0.159512
toolbox_scheduling.py
pypi
from remin.solver import Solver, make_trainer from remin.residual import Residual, make_loader from remin.solver.residual_loss import EagerLoss from remin import func, callbacks from remin import domain as dm import torch import numpy as np from torch import nn from model import Wave device = torch.device("cuda" if torch.cuda.is_available() else "cpu") torch.set_default_device(device) torch.set_float32_matmul_precision('high') torch.manual_seed(0) np.random.seed(0) def pde_residual(u, t, x): u_t, u_x = func.grad(u, [t, x]) u_tt = func.grad(u_t, t)[0] u_xx = func.grad(u_x, x)[0] return u_tt - u_xx def ic0_residual(u, t, x): return func.grad(u, t)[0] def ic1_residual(u, t, x): return u - torch.sin(3 * torch.pi * x) def bc_residual(u, t, x): return u pde_col = dm.Time(0, 1) * dm.Line((0,), (1,), 1024) ic_col = dm.Time(0, 0) * dm.Line((0,), (1,), 1024) bc_col = dm.Time(0, 1) * ( dm.Point((0,), 1024) + dm.Point((1,), 1024) ) pde_res = Residual(pde_col, pde_residual) ic_res = Residual(ic_col, [ic0_residual, ic1_residual]) bc_res = Residual(bc_col, bc_residual) if __name__ == '__main__': model = Wave() loader = make_loader( [pde_res, ic_res, bc_res], fully_loaded=True ) epochs = 20000 lr = 5e-4 optimizer = torch.optim.Adam(model.parameters(), lr=lr) resloss = EagerLoss(nn.MSELoss()) metloss = EagerLoss(nn.HuberLoss()) trainer = make_trainer(loader, optimizer=optimizer, residual_loss=resloss, metric_loss=metloss) solver = Solver(model, 'wave_eager', 'outputs', trainer=trainer) solver.reset_callbacks( callbacks.TotalTimeCallback(), callbacks.SaveCallback(), callbacks.LogCallback(log_epoch=1000, log_progress=100), callbacks.PlotCallback(state='resloss', name='eager_ressloss.png'), callbacks.PlotCallback(state='metloss', name='eager_metloss.png') ) solver.fit(epochs)
/remin-0.2.6.tar.gz/remin-0.2.6/examples/wave/train.py
0.828627
0.371764
train.py
pypi
from remin.solver import Solver, make_trainer from remin.residual import Residual, make_loader from remin.solver.residual_loss import EagerLoss from remin import func, callbacks from remin import domain as dm import torch import numpy as np from torch import nn from model import Wave device = torch.device("cuda" if torch.cuda.is_available() else "cpu") torch.set_default_device(device) torch.set_float32_matmul_precision('high') torch.manual_seed(0) np.random.seed(0) def pde_residual(u, t, x): u_t, u_x = func.grad(u, [t, x]) u_tt = func.grad(u_t, t)[0] u_xx = func.grad(u_x, x)[0] return u_tt - u_xx def ic0_residual(u, t, x): return func.grad(u, t)[0] def ic1_residual(u, t, x): return u - torch.sin(3 * torch.pi * x) def bc_residual(u, t, x): return u pde_col = dm.Time(0, 1) * dm.Line((0,), (1,), 1024) ic_col = dm.Time(0, 0) * dm.Line((0,), (1,), 1024) bc_col = dm.Time(0, 1) * ( dm.Point((0,), 1024) + dm.Point((1,), 1024) ) pde_res = Residual(pde_col, pde_residual, batch_size=32) ic_res = Residual(ic_col, [ic0_residual, ic1_residual], batch_size=32) bc_res = Residual(bc_col, bc_residual, batch_size=32) if __name__ == '__main__': model = Wave() loader = make_loader( [pde_res, ic_res, bc_res], batched=True, ) epochs = 1000 lr = 5e-4 optimizer = torch.optim.Adam(model.parameters(), lr=lr) resloss = EagerLoss(nn.MSELoss()) metloss = EagerLoss(nn.HuberLoss()) trainer = make_trainer(loader, optimizer=optimizer, residual_loss=resloss, metric_loss=metloss) solver = Solver(model, 'wave_batched', 'outputs', trainer=trainer) solver.reset_callbacks( callbacks.TotalTimeCallback(), callbacks.SaveCallback(), callbacks.LogCallback(log_epoch=1000, log_progress=1), callbacks.PlotCallback(state='resloss', name='batched_ressloss.png'), callbacks.PlotCallback(state='metloss', name='batched_metloss.png') ) solver.fit(epochs)
/remin-0.2.6.tar.gz/remin-0.2.6/examples/wave/train_batched.py
0.840815
0.36232
train_batched.py
pypi
import logging from typing import Any, Callable, Optional logger = logging.getLogger(__name__) class Event: """The event class.""" def __init__( self, name: str, priority: float, interest_rate: float, callback: Optional[Callable[[], None]] = None, is_ready_fn: Optional[Callable[[], bool]] = None, is_completed_fn: Optional[Callable[[], bool]] = None, ) -> None: """Initialize an event. :param name: The name of the event. :param priority: The priority of the event (for determining its relative importance). :param interest_rate: The rate that the priority of the event grows each step it is pushed back past its original due date. :param callback: A function to be called when the event is run. :param is_ready_fn: A function to determine if the event is ready. If nothing is supplied, this will default to be true if the event has not been completed. :param is_completed_fn: A function to determine if the event has been completed. If nothing is supplied, this will default to be true if the callback has been called at least once. """ if priority <= 0: raise ValueError("Priority must be a positive number") if interest_rate < 0: raise ValueError("Interest should be a non-negative number") if is_ready_fn is None: is_ready_fn = self.is_due if is_completed_fn is None: is_completed_fn = self.is_called self.name: str = name self.priority: float = priority self._interest_rate: float = interest_rate self._callback: Optional[Callable] = callback self._is_ready_fn: Callable = is_ready_fn self._is_completed_fn: Callable = is_completed_fn self._callback_count: int = 0 def __str__(self) -> str: """Get a string with details of the current event.""" return f"{self.name:<15} (priority={self.priority:.2f})" def __eq__(self, other): """Check if two events are the same by comparing their names.""" return self.name == other.name def push_forward(self, steps: int = 1) -> None: """Increase the priority of event by applying interest. :param steps: The number of times to apply the interest rate to the event's priority. """ logger.debug(f"Push forward '{self.name}' by {steps} steps") if steps < 1: raise ValueError('Must push forward a positive number of steps') self.priority *= (1 + self._interest_rate) ** steps def is_due(self) -> bool: """Check if the event is due. :return: True if the completion function doesn't return true; false otherwise. """ return not self.is_completed() def is_called(self) -> bool: """Check if the event has been called. :return: True if the callback has been called at least once; false otherwise. """ return self._callback_count > 0 def callback(self) -> Any: """Call the event's callback. :return: Whatever the callback returns. """ logger.debug(f"Call callback for '{self.name}'") if self.is_ready(): self._callback_count += 1 if callable(self._callback): return self._try_run_args(self._callback) else: raise RuntimeError( f"Callback '{self.name}' called before it's ready") def is_ready(self) -> bool: """Check if an event is ready. :return: True if the ready function returns true and the event has not been completed; false otherwise. """ return ( self._try_run_args(self._is_ready_fn) and not self.is_completed() ) def is_completed(self) -> bool: """Check if an event has been completed. :return: True if the is completed function returns true; false otherwise. """ return self._try_run_args(self._is_completed_fn) def _try_run_args(self, fn) -> Any: """Try calling a function with and without the self arguement.""" try: return fn() except TypeError: pass try: return fn(self) except TypeError: pass raise TypeError("Function could not be run")
/remind-me-some-1.0.1.tar.gz/remind-me-some-1.0.1/remind_me_some/event.py
0.921957
0.4206
event.py
pypi
from datetime import datetime, date, timedelta from typing import Callable, Optional from remind_me_some.event import Event class Action(Event): """The action class.""" def __init__( self, name: str, due: date, priority: float, interest_rate: float, callback: Optional[Callable[[], None]] = None, is_ready_fn: Optional[Callable[[], bool]] = None, is_completed_fn: Optional[Callable[[], bool]] = None, ) -> None: """Initialize an action. :param name: The name of the action. :param due: The planned date for the action to be completed on. :param priority: The priority of the action (for determining its relative importance). :param interest_rate: The rate that the priority of the action grows each day it is pushed back past its original due date. :param callback: A function to be called when the action is run. :param is_ready_fn: A function to determine if the action is ready. If nothing is supplied this will default to be on or after the action's due date. :param is_completed_fn: A function to determine if the action has been completed. If nothing is supplied, this will default to be true if the callback has been called at least once. """ super().__init__( name=name, priority=priority, interest_rate=interest_rate, callback=callback, is_ready_fn=is_ready_fn, is_completed_fn=is_completed_fn, ) self.due: date = due def __str__(self) -> str: """Return string information for the current action.""" return ( f"{super().__str__()} => " f"{self.due} ({'READY' if self.is_ready() else 'NOT READY'})" ) def push_forward(self, days: int = 1) -> None: """Bump the due date of the current action and add interest. :param days: The number of days to bump the due date by. """ self.due += timedelta(days=days) super().push_forward(days) def is_due(self) -> bool: """Check if the current action is due. :return: True if the current date is the due date or after; False, otherwise. """ return datetime.now().date() >= self.due
/remind-me-some-1.0.1.tar.gz/remind-me-some-1.0.1/remind_me_some/action.py
0.951063
0.369002
action.py
pypi
from datetime import date import logging from typing import Callable, List from remind_me_some.action import Action from remind_me_some.goal import Goal from remind_me_some.schedule_actions import schedule_actions from remind_me_some.is_exclude_date import is_exclude_date logger = logging.getLogger(__name__) class ScheduleManager: """The schedule manager class.""" def __init__( self, max_actions_per_day: int = 1, is_exclude_date_fn: Callable[[date], bool] = is_exclude_date, ) -> None: """Initialize the schedule manager. :param max_actions_per_day: The max number of actions that should occur on any day. :param is_exclude_date_fn: A function that return True if a date should be excluded and false otherwise. This can be used to avoid scheduling actions on weekends, holidays, etc. """ self._max_actions_per_day = max_actions_per_day self._is_exclude_date_fn = is_exclude_date_fn self._goals: List[Goal] = [] self._actions: List[Action] = [] def __str__(self) -> str: """Get a string for data contained in the schedule manager. :return: A string with information on the instance. """ out = "" if self._actions: contents = self._actions out += "Actions:\n========\n" elif self._goals: contents = self._goals out += "Goals:\n======\n" else: return f'<Empty {self.__class__.__name__}>' for a in contents: out += f'{a}\n' return out @property def actions(self) -> List[Action]: """Get the active actions. :return: A list of active actions. """ return self._actions @property def goals(self) -> List[Goal]: """Get the current goals. :return: A list of current goals. """ return self._goals def add_goal(self, goal: Goal) -> None: """Add one new goal. :param goal: A goal to add. """ logger.debug(f"Goal '{goal.name}' added") if goal not in self._goals: self._goals.append(goal) def add_goals(self, *goals: Goal) -> None: """Add one or more new goals. :param goals: One or more goals. """ for g in goals: self.add_goal(g) def run(self) -> None: """Execute or complete ready actions.""" for action in self._actions: if action.is_ready(): logger.debug(f"Action '{action.name}' is ready") logger.info(f"Run callback for action '{action.name}'") action.callback() elif action.is_completed(): logger.debug(f"Action '{action.name}' is completed") goal = self._get_goal(action.name) goal.mark_as_completed() logger.info(f"Remove action completed '{action.name}'") self._actions.remove(action) def _get_goal(self, name: str) -> Goal: for g in self._goals: if g.name == name: return g raise ValueError(f"No goal '{name}' found") def update_schedule(self) -> None: """Update the schedule to balance actions.""" self._update_actions() schedule_actions( self._actions, max_actions_per_day=self._max_actions_per_day, is_exclude_date_fn=self._is_exclude_date_fn, ) def _update_actions(self): for goal in self._goals: if goal not in self._actions: logger.info(f"Creat action for goal '{goal.name}'") self._actions.append( goal.make_action() )
/remind-me-some-1.0.1.tar.gz/remind-me-some-1.0.1/remind_me_some/schedule_manager.py
0.912677
0.24971
schedule_manager.py
pypi
from datetime import datetime, date, timedelta import logging from typing import Callable, Optional from remind_me_some.event import Event from remind_me_some.action import Action logger = logging.getLogger(__name__) class Goal(Event): """The goal class.""" def __init__( self, name: str, frequency: timedelta, priority: float = 1.0, interest_rate: float = 0.05, last_completed: Optional[date] = None, callback: Optional[Callable] = None, is_ready_fn: Optional[Callable] = None, is_completed_fn: Optional[Callable] = None, ) -> None: """Initialize a goal object. Goal objects are used to create action objects at some frequency. Most of the information given to the goal object is used to create new action objects. :param name: The name of the event. :param frequency: How often this goal should be completed. :param priority: The starting priority an action this goal generates (for determining its relative importance). :param interest_rate: The rate that the priority of a generated action grows each day it is pushed back past its original due date. :param last_completed: The date that this goal was last completed. :param callback: A function to be called when a generated action is run. :param is_ready_fn: A function to determine if a generated action is ready. If nothing is supplied this will default to be on or after the action's due date. :param is_completed_fn: A function to determine if the generated action has been completed. If nothing is supplied, this will default to be true if the callback has been called at least once. """ super().__init__( name=name, priority=priority, interest_rate=interest_rate, callback=callback, is_ready_fn=is_ready_fn, is_completed_fn=is_completed_fn, ) self._frequency = frequency self._last_completed = last_completed def make_action(self) -> Action: """Generate a new action instance. :return: An action object. """ logger.debug(f"Make new action for goal '{self.name}'") if self._last_completed is not None: due = self._last_completed + self._frequency else: due = datetime.now().date() return Action( name=self.name, due=due, priority=self.priority, interest_rate=self._interest_rate, callback=self._callback, is_ready_fn=Action.is_due, is_completed_fn=Action.is_called, ) def mark_as_completed(self) -> None: """Set the last completed date to today's date.""" logger.debug(f"Update last completion of goal '{self.name}'") self._last_completed = datetime.now().date() @property def last_completed(self) -> Optional[date]: """Get the date when this goal was last completed. :return: The last date that this goal was completed or None, if it hasn't been completed yet. """ return self._last_completed
/remind-me-some-1.0.1.tar.gz/remind-me-some-1.0.1/remind_me_some/goal.py
0.951751
0.360742
goal.py
pypi
from datetime import datetime, date from typing import Any, Callable, Optional, List from remind_me_some.action import Action def schedule_actions( actions, max_actions_per_day: int = 1, days_to_push_forward: int = 1, is_schedule_actions_today: bool = True, is_exclude_date_fn: Optional[Callable] = None, ) -> None: """Schedule actions by their due date and priority. :param actions: Actions to be scheduled. This function modifies this list's order. :param max_actions_per_day: The highest number of actions you would like to have on any given day. :param days_to_push_forward: The number of days to push rescheduled actions forward. :param is_schedule_actions_today: Should actions be scheduled today or not. :param is_exclude_date_fn: A function that should take in a date and return true or false. The date will not have actions on it if this function returns true for it. """ def _return_false(_: Any): return False def _sort_actions(_actions: List[Action]): _actions.sort(key=lambda a: (a.due, -a.priority)) if max_actions_per_day <= 0: raise ValueError("Must have a positive max number of actions per day") if days_to_push_forward <= 0: raise ValueError( "Must have a positive number of days to reschedule actions") if is_exclude_date_fn is None: is_exclude_date_fn = _return_false elif not callable(is_exclude_date_fn): raise ValueError("Exclude date function must be callable") _sort_actions(actions) last_date: Optional[date] = None num_at_last_date: Optional[int] = None idx = 0 while idx < len(actions): action = actions[idx] if (is_schedule_actions_today and action.due < datetime.now().date()) \ or is_exclude_date_fn(action.due): action.push_forward(days_to_push_forward) _sort_actions(actions) continue if action.due == last_date: if num_at_last_date < max_actions_per_day: num_at_last_date += 1 idx += 1 else: action.push_forward(days_to_push_forward) _sort_actions(actions) else: last_date = action.due num_at_last_date = 1 idx += 1
/remind-me-some-1.0.1.tar.gz/remind-me-some-1.0.1/remind_me_some/schedule_actions.py
0.875095
0.346182
schedule_actions.py
pypi
from argparse import ArgumentParser from datetime import datetime from vobject import iCalendar from vobject.base import Component, readComponents def compare(first_in: Component, second_in: Component, second_out: Component) -> None: for (j, second) in enumerate(second_in.vevent_list): found = False for (i, first) in enumerate(first_in.vevent_list): wrong = False for attr in [ "summary", "location", "description", "recurrence_id", ]: if ( hasattr(first, attr) and first.contents.get(attr) and first.contents.get(attr)[0].value and not ( hasattr(second, attr) and second.contents.get(attr) and second.contents.get(attr)[0].value and first.contents.get(attr)[0].value == second.contents.get(attr)[0].value ) ): wrong = True break # ignore timezone when comparing dates (not supported by remind) if hasattr(first, "dtstart") and not ( hasattr(second, "dtstart") and ( ( isinstance(first.dtstart.value, datetime) and isinstance(second.dtstart.value, datetime) and first.dtstart.value.timestamp() == second.dtstart.value.timestamp() ) or first.dtstart.value == second.dtstart.value ) ): wrong = True if hasattr(first, "dtend"): if hasattr(second, "dtend") and ( ( isinstance(first.dtend.value, datetime) and isinstance(second.dtend.value, datetime) and first.dtend.value.timestamp() != second.dtend.value.timestamp() ) or first.dtend.value != second.dtend.value ): wrong = True elif ( hasattr(second, "duration") and first.dtend.value != second.dtstart.value + second.duration.value ): wrong = True elif not (hasattr(second, "dtend") or hasattr(second, "duration")): wrong = True if hasattr(first, "duration"): if ( hasattr(second, "duration") and first.duration.value != second.duration.value ): wrong = True elif ( hasattr(second, "dtend") and first.duration.value != second.dtend.value - second.dtstart.value ): wrong = True elif not (hasattr(second, "dtend") or hasattr(second, "duration")): wrong = True if hasattr(first, "rruleset") and first.rruleset: if ( hasattr(second, "rruleset") and second.rruleset and list(first.rruleset) != list(second.rruleset) ): wrong = True elif ( hasattr(second, "rdate") and second.rdate.value and list(first.rruleset) != second.rdate.value ): wrong = True elif not (hasattr(second, "rruleset") or hasattr(second, "rdate")): wrong = True if hasattr(first, "rdate") and first.rdate.value: if ( hasattr(second, "rdate") and second.rdate.value and first.rdate.value != second.rdate.value ): wrong = True elif ( hasattr(second, "rruleset") and second.rruleset and first.rdate.value != list(second.rruleset) ): wrong = True elif not (hasattr(second, "rruleset") or hasattr(second, "rdate")): wrong = True if wrong: continue found = True first_in.remove(first) print(f"matching {i} to {j}") if not found: second_out.add(second) def main() -> None: parser = ArgumentParser(description="Compare two iCalendar files semantically") parser.add_argument("first_input", help="First iCalendar file input") parser.add_argument("second_input", help="Second iCalendar file input") parser.add_argument("first_output", help="First iCalendar file output") parser.add_argument("second_output", help="Second iCalendar file output") args = parser.parse_args() with open(args.first_input, encoding="utf-8") as infile: first_cal = next(readComponents(infile)) with open(args.second_input, encoding="utf-8") as infile: second_cal = next(readComponents(infile)) second_out = iCalendar() compare(first_cal, second_cal, second_out) with open(args.first_output, "w", encoding="utf-8") as outfile: outfile.write(first_cal.serialize()) with open(args.second_output, "w", encoding="utf-8") as outfile: outfile.write(second_out.serialize()) if __name__ == "__main__": main()
/remind-0.18.0.tar.gz/remind-0.18.0/ics_compare.py
0.429669
0.193014
ics_compare.py
pypi
"""Python library to convert between Remind and iCalendar.""" from datetime import date, datetime, timedelta from hashlib import md5 from json import loads from os.path import expanduser, getmtime, isfile from re import DOTALL, findall, match from socket import getfqdn from subprocess import run from threading import Lock from time import time from typing import Any, Iterable, Optional, Union from zoneinfo import ZoneInfo from dateutil import rrule from vobject import iCalendar from vobject.base import Component, readOne class Remind: """Represents a collection of Remind files.""" def __init__( self, filename: str = None, localtz: Optional[ZoneInfo] = None, startdate: date = None, month: int = 15, alarm: timedelta = None, ) -> None: """Constructor. filename -- the remind file (included files will be used as well) localtz -- the timezone of the remind file startdate -- the date to start parsing, will be passed to remind month -- how many month to parse, will be passed to remind -s """ self._filename = filename if filename else expanduser("~/.reminders") self._localtz = localtz if localtz else ZoneInfo("localtime") self._startdate = startdate if startdate else date.today() - timedelta(weeks=12) self._month = month self._alarm = alarm if alarm else timedelta(minutes=-10) self._lock = Lock() self._reminders: dict[str, dict[str, Any]] = {} self._mtime = 0.0 def _parse_remind( self, filename: str, lines: str = "" ) -> dict[str, dict[str, Any]]: """Call remind and parse output into a dict. filename -- the remind file (included files will be used as well) lines -- used as stdin to remind (filename will be set to -) """ cmd = [ "remind", f"-ppp{self._month}", "-b2", "-y", "-df", filename, str(self._startdate), ] try: process = run(cmd, input=lines, capture_output=True, text=True) except FileNotFoundError as error: raise FileNotFoundError( "remind command not found, please install it" ) from error if "Unknown option" in process.stderr: raise OSError(f'Error running: {" ".join(cmd)}, maybe old remind version') if f"Can't open file: {filename}" in process.stderr: return {filename: {}} err = list(set(findall(r"Can't open file: (.*)", process.stderr))) if err: raise FileNotFoundError( f'include file(s): {", ".join(err)} not found (please use absolute paths)' ) reminders: dict[str, dict[str, Any]] = {} for source in list( set(findall(r"Caching file `(.*)' in memory", process.stderr)) ): reminders[source] = {} if isfile(source): # There is a race condition with the remind call above here. mtime = getmtime(source) if mtime > self._mtime: self._mtime = mtime for month in loads(process.stdout): for entry in month["entries"]: if "passthru" in entry: continue entry["uid"] = f"{entry['tags'].split(',')[-1][7:]}@{getfqdn()}" if "eventstart" in entry: dtstart: Union[datetime, date] = datetime.strptime( entry["eventstart"], "%Y-%m-%dT%H:%M" ).replace(tzinfo=self._localtz) else: dtstart = datetime.strptime(entry["date"], "%Y-%m-%d").date() if entry["uid"] in reminders[entry["filename"]]: if ( dtstart not in reminders[entry["filename"]][entry["uid"]]["dtstart"] ): reminders[entry["filename"]][entry["uid"]]["dtstart"].append( dtstart ) else: entry["dtstart"] = [dtstart] reminders[entry["filename"]][entry["uid"]] = entry return reminders @staticmethod def _interval(dates: list[date]) -> int: """Return the distance between all dates and 0 if they are different.""" interval = (dates[1] - dates[0]).days last = dates[0] for dat in dates[1:]: if (dat - last).days != interval: return 0 last = dat return interval @staticmethod def _gen_dtend_rrule(dtstarts: list[date], vevent: Component) -> None: """Generate an rdate or rrule from a list of dates and add it to the vevent.""" interval = Remind._interval(dtstarts) if interval > 0 and interval % 7 == 0: rset = rrule.rruleset() rset.rrule( rrule.rrule( freq=rrule.WEEKLY, interval=interval // 7, count=len(dtstarts) ) ) vevent.rruleset = rset elif interval > 1: rset = rrule.rruleset() rset.rrule( rrule.rrule(freq=rrule.DAILY, interval=interval, count=len(dtstarts)) ) vevent.rruleset = rset elif interval > 0: if isinstance(dtstarts[0], datetime): rset = rrule.rruleset() rset.rrule(rrule.rrule(freq=rrule.DAILY, count=len(dtstarts))) vevent.rruleset = rset else: vevent.add("dtend").value = dtstarts[-1] + timedelta(days=1) else: rset = rrule.rruleset() if isinstance(dtstarts[0], datetime): for dat in dtstarts: rset.rdate(dat) else: for dat in dtstarts: rset.rdate(datetime(dat.year, dat.month, dat.day)) # temporary set dtstart to a different date, so it's not # removed from rset by python-vobject works around bug in # Android: # https://github.com/rfc2822/davdroid/issues/340 vevent.dtstart.value = dtstarts[0] - timedelta(days=1) vevent.rruleset = rset vevent.dtstart.value = dtstarts[0] if not isinstance(dtstarts[0], datetime): vevent.add("dtend").value = dtstarts[0] + timedelta(days=1) def _gen_vevent(self, event: dict[str, Any], vevent: Component) -> None: """Generate vevent from given event.""" vevent.add("dtstart").value = event["dtstart"][0] msg = event["body"].strip().replace('["["]', "[") groups = match(r'%"(.*)%" (.*)', msg, DOTALL) if groups: msg = groups[1] vevent.add("description").value = groups[2] groups = match(r"^(.*) at (.*)$", msg) if groups: msg = groups[1] vevent.add("location").value = groups[2] vevent.add("dtstamp").value = datetime.fromtimestamp(self._mtime) vevent.add("summary").value = msg vevent.add("uid").value = event["uid"] if "tags" in event: tags = event["tags"].split(",")[:-1] classes = ["PUBLIC", "PRIVATE", "CONFIDENTIAL"] tag_class = [tag for tag in tags if tag in classes] if tag_class: vevent.add("class").value = tag_class[0] categories = [tag for tag in tags if tag not in classes] if categories: vevent.add("categories").value = categories if isinstance(event["dtstart"][0], datetime): if self._alarm != timedelta(): valarm = vevent.add("valarm") valarm.add("trigger").value = self._alarm valarm.add("action").value = "DISPLAY" valarm.add("description").value = msg if "eventduration" in event: vevent.add("duration").value = timedelta(minutes=event["eventduration"]) else: vevent.add("dtend").value = event["dtstart"][0] elif len(event["dtstart"]) == 1: vevent.add("dtend").value = event["dtstart"][0] + timedelta(days=1) if len(event["dtstart"]) > 1: Remind._gen_dtend_rrule(event["dtstart"], vevent) def _update(self) -> None: """Reload Remind files if the mtime is newer.""" update = not self._reminders now = time() if ( self._mtime > 0 and datetime.fromtimestamp(self._mtime).date() < datetime.fromtimestamp(now).date() ): update = True self._mtime = now with self._lock: for fname in self._reminders: if not isfile(fname) or getmtime(fname) > self._mtime: update = True break if update: self._reminders = self._parse_remind(self._filename) def get_filesnames(self) -> list[str]: """All filenames parsed by remind (including included files).""" self._update() return list(self._reminders.keys()) @staticmethod def _get_uid(line: str) -> str: """UID of a remind line.""" return f"{md5(line.strip().encode('utf-8')).hexdigest()}@{getfqdn()}" def get_uids(self, filename: str = "") -> list[str]: """UIDs of all reminders in the file excluding included files. If a filename is specified, only it's UIDs are return, otherwise all. filename -- the remind file """ self._update() if filename: if filename not in self._reminders: return [] return list(self._reminders[filename].keys()) return [uid for uids in self._reminders.values() for uid in uids] def _vobject_etag(self, filename: str, uid: str) -> tuple[str, Component, str]: """Return iCal object and etag of one Remind entry. filename -- the remind file uid -- the UID of the Remind line """ cal = iCalendar() self._gen_vevent(self._reminders[filename][uid], cal.add("vevent")) return uid, cal, self.get_etag(cal) def to_vobject_etag(self, filename: str, uid: str) -> tuple[Component, str]: """Return iCal object and etag of one Remind entry. filename -- the remind file uid -- the UID of the Remind line """ self._update() return self._vobject_etag(filename, uid)[1:3] def to_vobjects( self, filename: str, uids: Iterable[str] = None ) -> list[tuple[str, Component, str]]: """Return iCal objects and etags of all Remind entries in uids. filename -- the remind file uids -- the UIDs of the Remind lines (all if None) """ self._update() if not uids: uids = list(self._reminders[filename].keys()) return [self._vobject_etag(filename, uid) for uid in uids] def to_vobject(self, filename: str = "", uid: str = "") -> Component: """Return iCal object of Remind lines. If filename and UID are specified, the vObject only contains that event. If only a filename is specified, the vObject contains all events in the file. Otherwise the vObject contains all all objects of all files associated with the Remind object. filename -- the remind file uid -- the UID of the Remind line """ self._update() cal = iCalendar() if uid: self._gen_vevent(self._reminders[filename][uid], cal.add("vevent")) elif filename: for event in self._reminders[filename].values(): self._gen_vevent(event, cal.add("vevent")) else: for events in self._reminders.values(): for event in events.values(): self._gen_vevent(event, cal.add("vevent")) return cal def stdin_to_vobject(self, lines: str) -> Component: """Return iCal object of the Remind commands in lines.""" cal = iCalendar() for event in self._parse_remind("-", lines)["-"].values(): self._gen_vevent(event, cal.add("vevent")) return cal @staticmethod def _parse_rdate(rdates: list[date], repeat: int = 1) -> str: """Convert from iCal rdate to Remind trigdate syntax.""" trigdates = [ (rdate + timedelta(days=d)).strftime("trigdate()=='%Y-%m-%d'") for rdate in rdates for d in range(repeat) ] return f"SATISFY [{'||'.join(trigdates)}]" @staticmethod def _parse_rruleset(rruleset: Any, duration: timedelta) -> Union[str, list[str]]: """Convert from iCal rrule to Remind recurrence syntax.""" # pylint: disable=protected-access if duration.days > 1: return Remind._parse_rdate(rruleset._rrule[0], duration.days) if rruleset._rrule[0]._freq == 0: return [] weekdays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] rep = [] if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: rep.append("*1") elif rruleset._rrule[0]._freq == rrule.DAILY: rep.append(f"*{rruleset._rrule[0]._interval}") elif rruleset._rrule[0]._freq == rrule.WEEKLY: rep.append(f"*{(7 * rruleset._rrule[0]._interval)}") elif ( rruleset._rrule[0]._freq == rrule.MONTHLY and rruleset._rrule[0]._bymonthday ): rep.append(str(rruleset._rrule[0]._bymonthday[0])) elif ( rruleset._rrule[0]._freq == rrule.MONTHLY and rruleset._rrule[0]._bynweekday ): daynum, week = rruleset._rrule[0]._bynweekday[0] weekday = weekdays[daynum] rep.append(f"{weekday} {week * 7 - 6}") else: return Remind._parse_rdate(rruleset._rrule[0]) if rruleset._rrule[0]._byweekday and len(rruleset._rrule[0]._byweekday) > 1: daynums = set(range(7)) - set(rruleset._rrule[0]._byweekday) days = [weekdays[day] for day in daynums] rep.append(f"SKIP OMIT {' '.join(days)}") if rruleset._rrule[0]._until: rep.append( rruleset._rrule[0]._until.strftime("UNTIL %b %d %Y").replace(" 0", " ") ) elif rruleset._rrule[0]._count: rep.append(rruleset[-1].strftime("UNTIL %b %d %Y").replace(" 0", " ")) return rep @staticmethod def _event_duration(vevent: Component) -> timedelta: """Unify dtend and duration to the duration of the given vevent.""" if hasattr(vevent, "dtend"): return vevent.dtend.value - vevent.dtstart.value if hasattr(vevent, "duration") and vevent.duration.value: return vevent.duration.value return timedelta(0) @staticmethod def _gen_msg(vevent: Component, label: str, tail: str, sep: str) -> str: """Generate a Remind MSG from the given vevent.""" rem = ["MSG"] msg = [] if label: msg.append(label) if hasattr(vevent, "summary") and vevent.summary.value: msg.append(Remind._rem_clean(vevent.summary.value)) else: msg.append("empty reminder") if hasattr(vevent, "location") and vevent.location.value: msg.append(f"at {Remind._rem_clean(vevent.location.value)}") has_desc = hasattr(vevent, "description") and vevent.description.value.strip() if tail or has_desc: rem.append(f'%"{" ".join(msg)}%"') else: rem.append(" ".join(msg)) if tail: rem.append(tail) if has_desc: rem[-1] += sep + Remind._rem_clean(vevent.description.value).strip() return " ".join(rem) @staticmethod def _rem_clean(rem: str) -> str: """Cleanup string for Remind. Strip, transform newlines, and escape '[' in string so it's acceptable as a remind entry. """ return rem.strip().replace("%", "%%").replace("\n", "%_").replace("[", '["["]') @staticmethod def _abbr_tag(tag: str) -> str: """Transform a string so it's acceptable as a remind tag.""" return tag.replace(" ", "")[:48] def to_remind( self, vevent: Component, label: str = "", priority: str = "", tags: str = "", tail: str = "", sep: str = " ", postdate: str = "", posttime: str = "", ) -> str: """Generate a Remind command from the given vevent.""" remind = ["REM"] duration = Remind._event_duration(vevent) trigdates = None if hasattr(vevent, "rrule"): trigdates = Remind._parse_rruleset(vevent.rruleset, duration) dtstart = vevent.dtstart.value # If we don't get timezone information, handle it as a naive datetime. # See https://github.com/jspricke/python-remind/issues/2 for reference. if isinstance(dtstart, datetime) and dtstart.tzinfo: dtstart = dtstart.astimezone(self._localtz) dtend = None if hasattr(vevent, "dtend"): dtend = vevent.dtend.value if isinstance(dtend, datetime) and dtend.tzinfo: dtend = dtend.astimezone(self._localtz) if not hasattr(vevent, "rdate") and not isinstance(trigdates, str): if ( not hasattr(vevent, "rrule") or vevent.rruleset._rrule[0]._freq != rrule.MONTHLY ): remind.append(dtstart.strftime("%b %d %Y").replace(" 0", " ")) elif ( hasattr(vevent, "rrule") and vevent.rruleset._rrule[0]._freq == rrule.MONTHLY and trigdates ): remind.extend(trigdates) trigdates = dtstart.strftime("SATISFY [trigdate()>='%Y-%m-%d']") if postdate: remind.append(postdate) if priority: remind.append(f"PRIORITY {priority}") if isinstance(trigdates, list): remind.extend(trigdates) if type(dtstart) is date and duration.days > 1 and not hasattr(vevent, "rrule"): remind.append("*1") if dtend is not None: dtend -= timedelta(days=1) remind.append(dtend.strftime("UNTIL %b %d %Y").replace(" 0", " ")) if isinstance(dtstart, datetime): remind.append(dtstart.strftime("AT %H:%M").replace(" 0", " ")) if posttime: remind.append(posttime) if duration.total_seconds() > 0: hours, minutes = divmod(duration.total_seconds() / 60, 60) remind.append(f"DURATION {hours:.0f}:{minutes:02.0f}") if hasattr(vevent, "rdate"): remind.append(Remind._parse_rdate(vevent.rdate.value)) if hasattr(vevent, "class"): remind.append(f"TAG {Remind._abbr_tag(vevent.getChildValue('class'))}") if isinstance(trigdates, str): remind.append(trigdates) if tags: remind.extend([f"TAG {Remind._abbr_tag(tag) for tag in tags}"]) if hasattr(vevent, "categories_list"): for categories in vevent.categories_list: for category in categories.value: remind.append(f"TAG {Remind._abbr_tag(category)}") remind.append(Remind._gen_msg(vevent, label, tail, sep)) return " ".join(remind) + "\n" def to_reminders( self, ical: Component, label: str = "", priority: str = "", tags: str = "", tail: str = "", sep: str = " ", postdate: str = "", posttime: str = "", ) -> str: """Return Remind commands for all events of a iCalendar.""" if not hasattr(ical, "vevent_list"): return "" reminders = [ self.to_remind(vevent, label, priority, tags, tail, sep, postdate, posttime) for vevent in ical.vevent_list ] return "".join(reminders) def append_vobject(self, ical: Component, filename: str = "") -> str: """Append a Remind command generated from the iCalendar to the file.""" if not filename: filename = self._filename with self._lock: outdat = self.to_reminders(ical) with open(filename, "a", encoding="utf-8") as outfile: outfile.write(outdat) return Remind._get_uid(outdat) def remove(self, uid: str, filename: str = "") -> None: """Remove the Remind command with the uid from the file.""" if not filename: filename = self._filename uid = uid.split("@")[0] with self._lock: with open(filename, encoding="utf-8") as infile: rem = infile.readlines() for (index, line) in enumerate(rem): if uid == md5(line.strip().encode("utf-8")).hexdigest(): del rem[index] with open(filename, "w", encoding="utf-8") as outfile: outfile.writelines(rem) break def replace_vobject(self, uid: str, ical: Component, filename: str = "") -> str: """Update the Remind command with the uid in the file with the new iCalendar.""" if not filename: filename = self._filename uid = uid.split("@")[0] with self._lock: with open(filename, encoding="utf-8") as infile: rem = infile.readlines() for (index, line) in enumerate(rem): if uid == md5(line.strip().encode("utf-8")).hexdigest(): rem[index] = self.to_reminders(ical) new_uid = self._get_uid(rem[index]) with open(filename, "w", encoding="utf-8") as outfile: outfile.writelines(rem) return new_uid raise ValueError(f"Failed to find uid {uid} in {filename}") def move_vobject(self, uid: str, from_file: str, to_file: str) -> None: """Move the Remind command with the uid from from_file to to_file.""" uid = uid.split("@")[0] with self._lock: with open(from_file, encoding="utf-8") as infile: rem = infile.readlines() for (index, line) in enumerate(rem): if uid == md5(line.strip().encode("utf-8")).hexdigest(): del rem[index] with open(from_file, "w", encoding="utf-8") as outfile: outfile.writelines(rem) with open(to_file, "a", encoding="utf-8") as outfile: outfile.writelines(rem) break @staticmethod def get_meta() -> dict[str, str]: """Meta tags of the vObject collection.""" return {"tag": "VCALENDAR", "C:supported-calendar-component-set": "VEVENT"} def last_modified(self) -> float: """Last time the Remind files where parsed.""" self._update() return self._mtime @staticmethod def get_etag(vobject: Component) -> str: """Generate an etag for the given vobject. This sets the dtstamp to epoch 0 to generate a deterministic result as Remind doesn't save a dtstamp for every entry. And etag should only change if the other values actually change. """ vobject_copy = iCalendar() vobject_copy.copy(vobject) for vevent in vobject_copy.vevent_list: vevent.dtstamp.value = datetime.fromtimestamp(0) etag = md5() etag.update(vobject_copy.serialize().encode("utf-8")) return f'"{etag.hexdigest()}"' def rem2ics() -> None: """Command line tool to convert from Remind to iCalendar.""" # pylint: disable=maybe-no-member from argparse import ArgumentParser, FileType from sys import stdin, stdout from dateutil.parser import parse parser = ArgumentParser(description="Converter from Remind to iCalendar syntax.") parser.add_argument( "-s", "--startdate", type=lambda s: parse(s).date(), default=date.today() - timedelta(weeks=12), help="Start offset for remind call (default: -12 weeks)", ) parser.add_argument( "-m", "--month", type=int, default=15, help="Number of month to generate calendar beginning wit startdate (default: 15)", ) parser.add_argument( "-a", "--alarm", type=int, default=-10, help="Trigger time for the alarm before the event in minutes (default: -10)", ) parser.add_argument( "-z", "--zone", help="Timezone of Remind file (default: local timezone)" ) parser.add_argument( "infile", nargs="?", default=expanduser("~/.reminders"), help="The Remind file to process (default: ~/.reminders)", ) parser.add_argument( "outfile", nargs="?", type=FileType("w"), default=stdout, help="Output iCalendar file (default: stdout)", ) args = parser.parse_args() zone = ZoneInfo(args.zone) if args.zone else None if args.infile == "-": remind = Remind( args.infile, zone, args.startdate, args.month, timedelta(minutes=args.alarm) ) vobject = remind.stdin_to_vobject(stdin.read()) if vobject: args.outfile.write(vobject.serialize()) else: remind = Remind( args.infile, zone, args.startdate, args.month, timedelta(minutes=args.alarm) ) args.outfile.write(remind.to_vobject().serialize()) def ics2rem() -> None: """Command line tool to convert from iCalendar to Remind.""" from argparse import ArgumentParser, FileType from sys import stdin, stdout parser = ArgumentParser(description="Converter from iCalendar to Remind syntax.") parser.add_argument("-l", "--label", help="Label for every Remind entry") parser.add_argument( "-p", "--priority", type=int, help="Priority for every Remind entry (0..9999)" ) parser.add_argument( "-t", "--tag", action="append", help="Tag(s) for every Remind entry" ) parser.add_argument( "--tail", help='Text to append to every remind summary, following final %%"' ) parser.add_argument( "--sep", default=" ", help="String to separate summary (and tail) from description", ) parser.add_argument( "--postdate", help="String to follow the date in every Remind entry. " 'Useful for entering "back" and "delta" fields (see man remind).', ) parser.add_argument( "--posttime", help="String to follow the time in every timed Remind entry. " 'Useful for entering "tdelta" and "trepeat" fields (see man remind).', ) parser.add_argument( "-z", "--zone", help="Timezone of Remind file (default: local timezone)" ) parser.add_argument( "infile", nargs="?", type=FileType("r"), default=stdin, help="Input iCalendar file (default: stdin)", ) parser.add_argument( "outfile", nargs="?", type=FileType("w"), default=stdout, help="Output Remind file (default: stdout)", ) args = parser.parse_args() zone = ZoneInfo(args.zone) if args.zone else None vobject = readOne(args.infile.read()) rem = Remind(localtz=zone).to_reminders( vobject, args.label, args.priority, args.tag, args.tail, args.sep, args.postdate, args.posttime, ) args.outfile.write(rem)
/remind-0.18.0.tar.gz/remind-0.18.0/remind.py
0.800263
0.220552
remind.py
pypi
# remindmail - turns reminders written in terminal into emails; supports scheduled reminders ## features - easily manage your To Do list from anywhere in the terminal - schedule one-time or recurring reminders - create issues for your Jira board - schedule commands (your crontab can't run every 2 weeks as easily!) # notable dependencies - use `pip install -r requirements.md` to install all dependencies - Linux (Raspberry Pis work great!) - [cabinet](https://pypi.org/project/cabinet/) - used to store JSON data; specifically, used to store the `remind.md` path and other important variables - a unique, non-Gmail address specifically for this project - do not use an email address that you use in other areas of your life - do not re-use a password you've used anywhere else; use a unique password. - Python3 # setup ```bash python3 -m pip install remindmail # adjust path accordingly pip install -r /path/to/requirements.md cabinet config # cabinet must be configured properly ``` ## cabinet config - you need to install and configure [cabinet](https://github.com/tylerjwoodfin/cabinet) - initialize using `cabinet config`; see cabinet's README for details - in cabinet's `settings.json`, set the email information using the example below - note that Gmail will _not_ work due to their security restrictions. - it's very bad practice to store your password in plaintext; for this reason, never sync this file. - always use a unique email address specifically for this, and _especially_ use a unique password. - your settings.json file should look similar to this example: ``` { "path": { "remindmail": { "local": "/home/pi/remindmail" } }, "email": { "from": "YourUniqueAndNonGmailEmailAddress", "from_pw": "YourPassword", "from_name": "Your Name", "to": "RemindersSentToThisEmailAddress", "smtp_server": "your domain's smtp server", "imap_server": "your domain's imap server", "port": 465 } } ``` ## scheduling reminder checks - type "crontab -e" in the terminal - add the line below (without the >, without the #, replacing the path with your real path): - `0 * * * * remind generate` (every hour, generate based on remind.md) # usage - `-h` (or `--help`): Displays usage information. - `-ls` (or `-l` or `--list`): Lists all current reminders in `remind.md`. - `-g` (or `--generate`): Generates all reminders scheduled for today. - I recommend setting up a crontab (see [generate](##generate)) - `--later`: Emails reminders that are marked with `[any]` - `--show-tomorrow`: Lists reminders in remind.md that are marked with tomorrow's date in YYYY-MM-DD - `--sent-today`: Prints the number of reminders sent today (or yesterday, if before 4AM) - `--stats`: Prints usage statistics about RemindMail - `-o` (or `--offset`): Calculates the offset of a date (see [offset](##offset)) - `-e` (or `--edit`): Opens `remind.md` in vim - `-j` (or `--jira`): Sends your reminder to a new Jira task for your desired board (see [Jira](#jira)) ## Trello - `-b` (or `--board`): An argument; the name of the Trello board to use - `--list-name`: An argument; the name of the Trello list to use - `-ti` (or `--trello-items`): Prints items within a Trello list (accepts `-b` or `--board`, `--list-name`) - If a board is not specified, the user is prompted to choose one - If a list is not specified, the user is prompted to choose one - `-tl` (or `--trello-list`): Prints the lists within a Trello board (accepts `-b` or `--board`, `--list-name`) - If a board is not specified, the user is prompted to choose one - `-ta` (or `--trello-add`): Adds an item to a Trello list (accepts `-b` or `--board`, `--list-name`, `--item-name`) - If a board is not specified, the user is prompted to choose one - If a list is not specified, the user is prompted to choose one - If an item is not specified, the user is prompted to enter one ## list (-l, -ls, or --list) - lists all current reminders in `remind.md` ## generate (-g or --generate) - generates reminders from `remind.md` that match the condition in brackets, such as `[wed]` matching if today is Wednesday - it is highly recommended to schedule this in crontab (Linux, MacOS) by calling `crontab -e` and adding something like ``` # runs every hour at 5 minutes past the hour 5 * * * * python3 /path/to/site-packages/remind/remind.py -g ``` - reminders are generated only every 12 hours, but this can be overcome with `remind -g --force` - to test your `remind.md` without actually sending reminders, use `remind -g --dry-run` - this function requires use of SMTP; please ensure you've configured this correctly. ## later (--later) - emails reminders in `remind.md` marked with `[any]` ## edit (-e or --edit) - `remind edit` looks at the `path -> edit -> remind -> value` property in cabinet's settings.json: ``` { "path": { "edit": { "remind": { "value": "/fullpath/to/remind.md" } } } } ``` ## offset (-o or --offset) - `remind -o <type> <date (YYYY-MM-DD, optional)> <n>` - (`type` is day, week, month) - (`n` is 'every `n` days') - Take the results of this function and use it to add an offset. - If you want something to happen every 3 days starting tomorrow, use: - `remind -o day <tomorrow's date YYYY-MM-DD> 3` - If the answer is 2, then you can add this to remind.md: - [D%3+2] Description here ### how this is calculated - The Epoch time is the number of seconds since January 1, 1970, UTC. - For example, if the current time is 1619394350, then today is Sunday, April 25, 2021 at 11:45:50PM UTC. - The "week number" is calculated by {epochTime}/60/60/24/7. - 1619394350 /60/60/24/7 ~= 2677 - 2677 % 3 == 1, meaning scheduling a reminder for [W%3] would be sent last week, but not this week (or next week or the week after). ### examples - e.g. `remind -o day 2022-12-31 12` - (find offset for every 12 days intersecting 2022-12-31) - e.g. `remind -o week 2022-12-31 3` - (every 3 weeks intersecting 2022-12-31) - e.g. `remind -o month 2022-12-31 4` - (every 4 months intersecting 2022-12-31) - e.g. `remind -o day 5` - (every 5 days intersecting today) - e.g. `remind -o week 6` - (every 6 weeks intersecting today) - e.g. `remind -o month 7` - (every 7 months intersecting today)""" # logging - by defualt, remindmail's log path is set to `cabinet`'s default log - otherwise, you can set `path -> remindmail -> log` in `cabinet` (see Setup above) for a custom directory. # scheduling reminders with remind.md - this file is the heart of this tool, used for scheduling one-time or recurring reminders. - place the "good" example in the `remind.md example` section below in a file named `remind.md`. - reminders from the `remind.md` file will be emailed once the conditions are met. ## using colons to edit email body - any text after a colon (`:`) will be placed in the body of the email. ## using natural language to add to remind.md - `remind me to take out the trash` will immediately send an email upon confirmation - `remind to take out the trash tomorrow` will add `[YYYY-MM-DD]d take out the trash` upon confirmation (where `YYYY-MM-13` is the next day) - if it is before 3AM, the reminder will immediately send an email upon confirmation - `remind write essay: need to go to library` will immediately send an email with the subject `write essay` and body `need to go to library` upon confirmation - `remind me to take out the trash tomorrow` will add `[YYYY-MM-DD]d take out the trash` upon confirmation (where `YYYY-MM-DD` is tomorrow's date) - `remind me take out the trash on Thursday` will add `[thu]d take out the trash` upon confirmation - `remind to take out the trash on the 13th` will add `[YYYY-MM-13]d take out the trash` upon confirmation (where `YYYY-MM-13` is the next `13th`) - `remind go to the gym in 4 months` will add `[YYYY-MM-DD]d take out the trash` upon confirmation (where `YYYY-MM-DD` is 4 months from today) - `remind me spring is here in 6 weeks` will add `[YYYY-MM-DD]d spring is here` upon confirmation (where `YYYY-MM-DD` is 6 weeks from today) - `remind me to finish procrastinating in 5 days` will add `[YYYY-MM-DD]d finish procrastinating` upon confirmation (where `YYYY-MM-DD` is 5 days from today) - `remind me take out the trash every 2 weeks` will add `[W%2] take out the trash` upon confirmation - for recurring reminders, use `every n days`, `every n weeks`, or `every n months` - try other combinations, and feel free to contribute to the codebase for other scenarios! ### parse without time - some queries, like `remind me to buy 12 eggs` can be misinterpreted from the date parser library, and the confirmation may ask to schedule the reminder on the 12th of the month. - these edge cases aren't worth fixing, in the interest of preserving the ability for something like "remind me on the 12th to buy eggs" to continue working reliably. - in these situations, it's worth choosing `(p)arse without time`, which ignores any potential dates and asks to send the reminder immediately ## manually editing remind.md to schedule reminders ### days ``` [D%1] This reminder is sent every day. [D%4] This reminder is sent every 4 days. [mon] This reminder is sent if today is Monday. [Monday] This reminder is sent if today is Monday. [thu] This reminder is sent if today is Thursday. [Thursday]d This reminder is sent, then deleted, if today is Thursday. [D01] This reminder is sent if today is the 1st of the month. [D31]d This reminder is sent, then deleted, if today is the 31st of the month. [D31]c cd /foo/bar && rm -rf / # this reminder is a scheduled command. [3-5] This reminder is sent if today is March 5. [3/5]d This reminder is sent, then deleted, if today is March 5. [3/5]1 This reminder is sent, then deleted, if today is March 5. [2022-3-5]d This reminder is sent, then deleted, if today is March 5. [2022-3-5]c cd /foo/bar && rm -rf / # this reminder is a scheduled command. ``` ### weeks ``` [W%3] This reminder is sent if today is a Sunday of every third week, based on Epoch Time. See below... [thu%2] This reminder is sent every other Thursday. [thu%2+1] This reminder is sent every other Thursday (between the weeks of the line above). [W%3+1] This reminder is sent if today is a Sunday of every third week, _with an offset of 1_, meaning if [W%3] would normally be sent last week, it will be sent this week instead. ``` ### months ``` [M%5] This reminder is sent every 5 months (_not necessarily May and October! pay attention to offsets_) [M%2]d This reminder is sent at the next even-numbered month, then deleted. [M%2]c cd /foo/bar && rm -rf / # this reminder is a scheduled command. ``` ### one-time or n-time reminders ``` [4/23]3 This reminder will be sent if today is April 23, then converted into [4/23]2 [4/23]2 This reminder will be sent if today is April 23, then converted into [4/23]1 (same as [4/23]d) [4/23]1 This reminder is sent, then deleted, if today is April 23. [4/23]d This reminder is sent, then deleted, if today is April 23. [M%3]6 This reminder will be sent, then decremented, every 3 months, until it becomes [M%3]1 in approximately 18 months. [D%2]30 This reminder will be sent, then decremented, every other day, until it becomes [D%2]1 in approximately 2 months. ``` ### "any time" reminders for later ``` [any] This reminder requires manual removal from remind.md [any] You will be given a summary of [any] reminders when generateSummary() is called. [any] This can be called as `remind later` ``` It is recommended you add `remind later` as a scheduled crontab action. ### examples that won't work ``` [D50] Months only have up to 31 days. [D%3] d The 'd' operator must be immediately next to the ] symbol. [Y%5] Year is unsupported. (thu) You must use brackets. {thu} You must use brackets. [W%3] You must start reminders at the start of a newline. [W%3-1] This is invalid. To add an offset, you MUST use +. [W%3+4] An offset of 4 makes no sense and won't be triggered because [W%3+3] is the same thing as [W%3+0]. Use [W%3+1] instead. ``` ## calculating and scheduling "every n weeks", "every n days", "every n months" - see [offset](##offset) ## using "d" to set one-time reminders - an item with `]d`, such as `[D%5]d`, will add the reminder and remove it from remind.md, meaning it will only generate once until you add it again. - this is useful for scheduling a reminder in the future that you don't need to repeat. # Jira Integration RemindMail provides a barebones integration with Jira to create issues directly from the application. To enable this integration, you need to configure the required Jira settings in the Cabinet configuration file. ## configuration Before using the Jira integration, ensure that you have the following information available: - Jira project URL: The base URL of your Jira project. - Jira email: The email associated with your Jira account. - Jira API token: The API token generated for your Jira account. - obtain through [these instructions](https://support.atlassian.com/atlassian-account/docs/manage-api-tokens-for-your-atlassian-account/) - Jira project key: The key of the Jira project where you want to create issues. Using [Cabinet](https://pypi.org/project/cabinet/), set the values by running: ``` cabinet --put jira email <your Jira email> cabinet --put jira project-url <your project url, e.g. https://username.atlassian.net> cabinet --put jira project-key <your project key prefix that all issues have, e.g. USR> cabinet --put keys jira <your Jira API token> ``` Make sure to replace values in brackets with your own values. ## Usage ``` # creates a ticket (with prompts for description, label, issue type) remind -m this is a new ticket --jira # creates a ticket without prompts remind --jira "this is a story 4" -t task --desc "Testing description" --label "testing" # select '(j)' in confirmation menu remind -m this is a new jira ticket ``` After the issue has been created, a success message and link to the new issue will appear. ## Trello Integration ## configuration Before using the Trello integration, [obtain a Trello API Key](https://developer.atlassian.com/cloud/trello/guides/rest-api/authorization/). Using [Cabinet](https://pypi.org/project/cabinet/), set the API key by running: ``` cabinet --put keys trello <api key here> ``` Upon first running a Trello-related command, you will be prompted to authorize your application in the browser. ## usage ``` # prints all lists in the `Shopping` board remind -tl Shopping # prints all items from a list (interactive) remind -ti # prints all items from the `Tyler` list in the `Shopping` board remind -ti --board Shopping --list-name Tyler # select '(j)' in confirmation menu remind -m this is a new jira ticket ```
/remindmail-2023.7.9.3.tar.gz/remindmail-2023.7.9.3/README.md
0.724968
0.817975
README.md
pypi
class Reminder: """ A class representing a reminder. Attributes ---------- message : str The message for the reminder. next_date : date The date of the next occurrence of the reminder notes : str, optional Additional notes for the reminder (default is an empty string). is_recurring : bool, optional Indicates whether the reminder is recurring (default is False). Methods ------- message Getter and setter method for the message attribute. next_date Getter and setter method for the next_date attribute. notes Getter and setter method for the notes attribute. is_recurring Getter and setter method for the is_recurring attribute. """ def __init__(self, message, next_date, notes='', is_recurring=False): """ Initializes a new Reminder instance. Parameters ---------- message : str The message for the reminder. next_date : str The date of the next occurrence of the reminder in the format 'YYYY-MM-DD'. notes : str, optional Additional notes for the reminder (default is an empty string). is_recurring : bool, optional Indicates whether the reminder is recurring (default is False). """ self._message = message self._next_date = next_date self._notes = notes self._is_recurring = is_recurring @property def message(self): """Getter and setter method for the message attribute.""" return self._message @message.setter def message(self, value): self._message = value @property def next_date(self): """Getter and setter method for the next_date attribute.""" return self._next_date @next_date.setter def next_date(self, value): self._next_date = value @property def notes(self): """Getter and setter method for the notes attribute.""" return self._notes @notes.setter def notes(self, value): self._notes = value @property def is_recurring(self): """Getter and setter method for the is_recurring attribute.""" return self._is_recurring @is_recurring.setter def is_recurring(self, value): self._is_recurring = value
/remindmail-2023.7.9.3.tar.gz/remindmail-2023.7.9.3/src/remind/reminder.py
0.925609
0.546073
reminder.py
pypi
import logging import re import shutil import subprocess import unicodedata from dataclasses import dataclass from datetime import datetime from datetime import timezone from mmap import mmap from pathlib import Path from typing import Generator import cmarkgfm import jinja2 import magic import yaml from cmarkgfm.cmark import Options as cmarkgfmOptions from flask.wrappers import Request from frontmatter import load as frontmatter_load from PIL import Image from PIL import ImageOps jinja_env = jinja2.Environment( loader=jinja2.FileSystemLoader(Path(__file__).parent / "templates"), ) logger = logging.getLogger(__name__) @dataclass(kw_only=True) class BasePost: """Base class for post metadata.""" # pylint: disable=too-many-instance-attributes # The date the post was created date: datetime # The post directory on the file system fs_post_directory: Path # The markdown content of the post md_content: str # The post id post_id: str # A list of tags for the post tags: list[str] # The title of the post title: str # The author of the post author: str = "" # The next post url next: Path | None = None # The previous post url previous: Path | None = None def __post_init__(self) -> None: """Post init.""" if not self.author: self.author = "Unknown" @property def fs_media_dir(self) -> Path: """Get the full path to the image directory. Returns: The full path to the image directory. """ return self.fs_post_directory / "media" @property def fs_post_full_html_path(self) -> Path: """Get the full path to the post html file. Returns: The full path to the post html file. """ return self.fs_post_directory / "index.html" @dataclass(kw_only=True) class ExistingPost(BasePost): """Metadata for an existing post.""" # The image to use on the index index_image: str | None = None # The good url for the post post_url: Path | None = None # The url for the thumbnail image thumbnail_parent_url: Path | None = None # The url for the thumbnail image thumbnail_url: Path | None = None @property def author_index(self) -> str: """Get the author index url. Returns: The author index url. """ return f"{_slugify(self.author)}.html" def write_html(self) -> None: """Write the post to an HTML file.""" template = jinja_env.get_template("post.html.j2") html_content = _render_markdown(self.md_content) rendered = template.render(post=self, content=html_content) self.fs_post_full_html_path.write_text(rendered, encoding="utf-8") @dataclass(kw_only=True) class NewPost(BasePost): """Metadata for a post.""" # The filename for each attachment media_file_names: list[str] @property def fs_post_full_md_path(self) -> Path: """Get the full path to the post md file. Returns: The full path to the post md file. """ return self.fs_post_directory / "post.md" @property def md_header(self) -> str: """Convert the post metadata to a dictionary. This is needed when markdown and html files are generated. Returns: The post metadata as a dictionary. """ include = { "author": self.author, "date": str(self.date), "media_file_names": self.media_file_names, "post_id": self.post_id, "tags": self.tags, "title": self.title, } return yaml.dump(include, default_flow_style=False) # type: ignore[no-any-return] @property def relative_media_path(self) -> Path: """Get the relative path to the image directory. Returns: The relative path to the image directory. """ return self.fs_media_dir.relative_to(self.fs_post_directory) @property def relative_media_paths(self) -> list[Path]: """Get the relative paths to the images. Returns: The relative paths to the images. """ return [self.relative_media_path / media for media in self.media_file_names] def write_md(self) -> None: """Write the post to a markdown file.""" self.fs_post_full_md_path.write_text(self.md_content, encoding="utf-8") def _slugify(value: str, allow_unicode: bool = False) -> str: """Convert to ASCII if 'allow_unicode' is False. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. Args: value: The string to be converted. allow_unicode (bool): Whether to allow unicode characters. Returns: str: The converted string. """ if allow_unicode: value = unicodedata.normalize("NFKC", value) value = re.sub(r"[^\w\s-]", "", value, flags=re.U).strip().lower() return re.sub(r"[-\s]+", "-", value, flags=re.U) value = unicodedata.normalize("NFKD", value).encode("ascii", "ignore").decode("ascii") value = re.sub(r"[^\w\s-]", "", value).strip().lower() return re.sub(r"[-\s]+", "-", value) def _extract_tags(request: Request) -> list[str]: """Extract tags from flask request. Args: request: The Markdown content to extract tags from. Returns: The tags. """ form_keys = request.form.keys() # type: ignore[no-untyped-call] selected_tags = [key.split("-", 1)[1] for key in form_keys if key.startswith("tag-")] form_tags = request.form.get("tags", "") tag_list = [tag.strip() for tag in form_tags.split(",")] + selected_tags if not tag_list: tag_list = ["random"] tag_list = [tag.lower() for tag in tag_list if tag] return tag_list def _extract_images(post: NewPost, request: Request) -> None: """Extract images from flask request. Args: post: The post to extract images for. request: The Markdown content to extract images from. Raises: ValueError: If the image directory is not set. """ # pylint: disable=too-many-locals if not post.fs_media_dir: raise ValueError("fs_media_dir is not set") post.fs_media_dir.mkdir(exist_ok=True, parents=True) all_media = request.files.getlist("media") logger.debug(all_media) logger.debug(len(all_media)) for media in all_media: logger.debug(media) if not media: continue if not isinstance(media.filename, str): continue # Make minimal changes to the filename filename = media.filename.replace(" ", "_") media_path = post.fs_media_dir / filename media.save(media_path) logger.debug(media) mimetype = magic.from_file(media_path, mime=True) logger.debug(mimetype) if mimetype.startswith("image/"): eop = b"\x66\x74\x79\x70\x69\x73\x6F\x6D" with media_path.open("r+b") as image: mem_map = mmap(image.fileno(), 0) file_size = mem_map.size() place = mem_map.find(eop) place_lim = file_size - len(eop) if place in (-1, place_lim): post.media_file_names.append(filename) continue offset = place - 4 mem_map.seek(0) jpeg = mem_map.read(offset) mem_map.seek(offset) mp4 = mem_map.read(file_size) file_base = media_path.stem jpeg_path = post.fs_media_dir / ("ex_" + file_base + ".jpg") with jpeg_path.open("w+b") as jpeg_file: jpeg_file.write(jpeg) post.media_file_names.append(jpeg_path.name) mp4_orig_path = post.fs_media_dir / ("ex_orig_" + file_base + ".mp4") with mp4_orig_path.open("w+b") as mp4_file: mp4_file.write(mp4) mp4_h264_path = post.fs_media_dir / ("ex_h264_" + file_base + ".mp4") _subproc = subprocess.run( [ "ffmpeg", "-i", str(mp4_orig_path), "-map", "0:0", "-c:v", "libx264", "-crf", "18", "-c:a", "copy", str(mp4_h264_path), ], check=False, ) logger.debug(_subproc.stderr) logger.debug(_subproc.stdout) post.media_file_names.append(mp4_h264_path.name) else: post.media_file_names.append(filename) def _populate_post_metadata( md_glob: Generator[Path, None, None], site_dir: Path ) -> list[ExistingPost]: """Populate the metadata for all posts. Args: md_glob: The glob of markdown files. site_dir: The directory of the site. Returns: The list of posts. """ posts = [] for path in md_glob: parsed_post = frontmatter_load(path) date = datetime.fromisoformat(parsed_post["date"]) if not date.tzinfo: date = date.replace(tzinfo=timezone.utc) image_file_names = parsed_post.metadata.get("image_file_names", []) # Some older posts may not have the header information if not image_file_names: images = re.findall(r"!\[.*\]\((.*?\.(?:jpg|jpeg|png))?.*\)", parsed_post.content) image_file_names = [Path(image).name for image in images if image] # Some older posts have categories, convert to tags tags = parsed_post.metadata.get("tags", []) categories = parsed_post.metadata.get("categories", []) post = ExistingPost( author=parsed_post.get("author", ""), date=date, fs_post_directory=path.parent, md_content=parsed_post.content, post_id=path.parent.name, tags=tags + categories, title=parsed_post["title"], ) post.post_url = Path("/") / post.fs_post_full_html_path.relative_to(site_dir) if image_file_names: post.index_image = image_file_names[0] post.thumbnail_parent_url = Path("/") / post.fs_media_dir.relative_to(site_dir) posts.append(post) # Ensure we are ordered chronologically posts.sort(key=lambda x: x.date) return posts def _populate_post_next_previous(posts: list[ExistingPost], site_dir: Path) -> None: """Populate the next and previous metadata for all posts. Args: posts: The list of posts. site_dir: The directory of the site. """ for idx, post in enumerate(posts): if idx == 0: previous_post = posts[-1] else: previous_post = posts[idx - 1] post.previous = previous_post.fs_post_full_html_path.relative_to(site_dir) if idx == len(posts) - 1: next_post = posts[0] else: next_post = posts[idx + 1] post.next = next_post.fs_post_full_html_path.relative_to(site_dir) def _prune_post_list(post_id: str, posts: list[ExistingPost]) -> list[ExistingPost]: """Prune the list of posts to only include the post and the previous and next posts. Args: post_id: The id of the post to build. posts: The list of posts. Returns: The list of posts to build. """ found = [idx for idx, post in enumerate(posts) if post.post_id == post_id] if not found: return [] post_found = found[0] revise = [post_found] if post_found == 0: revise.append(len(posts) - 1) else: revise.append(post_found - 1) if post_found == len(posts) - 1: revise.append(0) else: revise.append(post_found + 1) return [posts[i] for i in revise] def _render_markdown(content: str) -> str: """Render Markdown to HTML. Args: content: The Markdown content to render. Returns: The rendered HTML. """ content = cmarkgfm.github_flavored_markdown_to_html( content, options=cmarkgfmOptions.CMARK_OPT_UNSAFE, ) return content def convert_all_html( site_dir: Path, post_id: str | None = None, ) -> tuple[list[ExistingPost], list[ExistingPost]]: """Convert all posts to html. Args: site_dir: The directory of the site. post_id: The name of the post to build. Returns: The number of posts built. """ posts_dir = site_dir / "posts" md_glob = posts_dir.rglob("*.md") all_posts = _populate_post_metadata(md_glob=md_glob, site_dir=site_dir) _populate_post_next_previous(posts=all_posts, site_dir=site_dir) if post_id: revise_posts = _prune_post_list(post_id=post_id, posts=all_posts) else: revise_posts = all_posts for post in revise_posts: post.write_html() return revise_posts, all_posts def initialize_new_post(request: Request, posts_dir: Path) -> NewPost: """Initialize a new post. Args: request: The request. posts_dir: The directory of the posts. Returns: The new post. """ now = datetime.now() now_iso = datetime.now(timezone.utc).astimezone().isoformat() post_id = f"{now_iso}_{_slugify(request.form['title'])}" # Make the directory for the post and images dir_path = posts_dir / str(now.year) / str(now.month).zfill(2) / post_id post = NewPost( author=request.form["author"], date=now, media_file_names=[], fs_post_directory=dir_path, md_content="", post_id=post_id, tags=_extract_tags(request), title=request.form.get("title", str(now_iso)), ) _extract_images(post=post, request=request) template = jinja_env.get_template("post.md.j2") mimes: dict[str, list[tuple[Path, str]]] = {} for media in post.media_file_names: path = post.fs_media_dir / media mime = magic.from_file(path, mime=True) mime_type, _mime_subtype = mime.split("/") if mime_type not in mimes: mimes[mime_type] = [] mimes[mime_type].append( ( post.relative_media_path / media, mime, ) ) post.md_content = template.render( content=request.form["content"], images=mimes.get("image", []), videos=mimes.get("video", []), md_header=post.md_header, ) return post def write_index(posts: list[ExistingPost], site_dir: Path) -> None: """Write the index file. Args: posts: The posts. site_dir: The directory of the site. """ path = site_dir / "index.html" template = jinja_env.get_template("index.html.j2") rendered = template.render(posts=posts, title="everything") path.write_text(rendered, encoding="utf-8") def write_tag_indices(posts: list[ExistingPost], site_dir: Path) -> None: """Write the tag files. Args: posts: The posts. site_dir: The directory of the site. """ tag_dir = site_dir / "tags" # Start with fresh tag indices shutil.rmtree(tag_dir, ignore_errors=True) all_tags: dict[str, list[ExistingPost]] = {} for post in posts: for tag in post.tags: if tag not in all_tags: all_tags[tag] = [] all_tags[tag].append(post) for tag, matching_posts in all_tags.items(): tag_index_path = Path(tag_dir) tag_index_path.mkdir(parents=True, exist_ok=True) path = tag_index_path / f"{_slugify(tag)}.html" template = jinja_env.get_template("index.html.j2") rendered = template.render(posts=matching_posts, title=tag) path.write_text(rendered, encoding="utf-8") def write_author_indices(posts: list[ExistingPost], site_dir: Path) -> None: """Write the author files. Args: posts: The posts. site_dir: The directory of the site. """ author_dir = site_dir / "authors" # Start with fresh author indices shutil.rmtree(author_dir, ignore_errors=True) all_authors: dict[str, list[ExistingPost]] = {} for post in posts: author = post.author if author not in all_authors: all_authors[author] = [] all_authors[author].append(post) for author, matching_posts in all_authors.items(): author_index_path = Path(author_dir) author_index_path.mkdir(parents=True, exist_ok=True) path = author_index_path / f"{_slugify(author)}.html" template = jinja_env.get_template("index.html.j2") rendered = template.render(posts=matching_posts, title=author) path.write_text(rendered, encoding="utf-8") def build_thumbnails(posts: list[ExistingPost]) -> None: """Build thumbnails for the post. Args: posts: The post to build thumbnails for. Raises: ValueError: If the thumbnail URL is not set. """ count = 0 for post in posts: image_dir = post.fs_media_dir index_image = post.index_image if not index_image: continue image_path = image_dir / index_image thumbnail_name = f"thumb_{index_image}" if post.thumbnail_parent_url is None: raise ValueError("Thumbnail URL not set") post.thumbnail_url = post.thumbnail_parent_url / thumbnail_name if not (image_dir / thumbnail_name).exists(): image = Image.open(image_path) # Rotate the in memory image correctly image = ImageOps.exif_transpose(image) image.thumbnail((1000, 1000), Image.ANTIALIAS) image.save(image_dir / thumbnail_name) count += 1 logger.debug("Built %s thumbnails", count)
/reminisce-0.0.7.tar.gz/reminisce-0.0.7/src/home_journal/utils.py
0.844873
0.15109
utils.py
pypi
import argparse import logging import os import shutil from importlib import resources from .run import run_server logger = logging.getLogger() def _list_tags(values: str) -> list[str]: """Split a comma separated list of tags. Args: values: A comma separated list of tags. Returns: A list of tags. """ return values.split(",") def _parse_args() -> argparse.Namespace: """Parse the command line arguments. Returns: The parsed arguments. """ parser = argparse.ArgumentParser() parser.add_argument( "-i", "--init", help="Initialize the site with css, js, and icons", action="store_true", ) parser.add_argument( "-l", "--log_level", type=str.lower, help="Log level", default="INFO", choices=["debug", "info", "warning", "error", "critical"], ) parser.add_argument( "-f", "--log_file", type=str, help="Log file", default=os.getcwd() + "/hj.log", ) parser.add_argument( "-p", "--port", type=int, help="Port to run the server on", default=8000, ) parser.add_argument( "-s", "--site_directory", type=str, help="Path to the site directory", required=True, ) parser.add_argument( "-t", "--tags", help="A list of tags for new posts", type=_list_tags, ) args = parser.parse_args() return args def _setup_logging(args: argparse.Namespace) -> None: """Set up the logging. Args: args: The parsed command line arguments. """ log_file = args.log_file file_handler = logging.FileHandler(log_file, mode="w") formatter = logging.Formatter( fmt="%(asctime)s %(levelname)s '%(name)s.%(funcName)s' %(message)s" ) file_handler.setFormatter(formatter) logger.addHandler(file_handler) level = logging.getLevelName(args.log_level.upper()) logger.setLevel(level) logger.info("Started") def _init_site(args: argparse.Namespace) -> None: """Initialize the site. Args: args: The parsed command line arguments. """ if args.init: logging.info("Initializing site") data_dir = [ entry for entry in resources.files("home_journal").iterdir() if entry.name == "site" ][0] shutil.copytree(str(data_dir), args.site_directory, dirs_exist_ok=True) logging.info("Site initialized") def main() -> None: """Run the app.""" args = _parse_args() _setup_logging(args) for arg in vars(args): logger.debug("%s: %s", arg, getattr(args, arg)) _init_site(args) run_server(args) if __name__ == "__main__": main()
/reminisce-0.0.7.tar.gz/reminisce-0.0.7/src/home_journal/cli.py
0.771069
0.174833
cli.py
pypi
"""Client and server classes corresponding to protobuf-defined services.""" import grpc import specialization_pb2 as specialization__pb2 class ISpecializationServiceStub(object): """Missing associated documentation comment in .proto file.""" def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.getSpecializationList = channel.unary_unary( '/remis.service.ISpecializationService/getSpecializationList', request_serializer=specialization__pb2.SpecializationRequest.SerializeToString, response_deserializer=specialization__pb2.SpecializationListResponse.FromString, ) self.getSpecializationById = channel.unary_unary( '/remis.service.ISpecializationService/getSpecializationById', request_serializer=specialization__pb2.SpecializationRequest.SerializeToString, response_deserializer=specialization__pb2.SpecializationResponse.FromString, ) class ISpecializationServiceServicer(object): """Missing associated documentation comment in .proto file.""" def getSpecializationList(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def getSpecializationById(self, request, context): """Missing associated documentation comment in .proto file.""" context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_ISpecializationServiceServicer_to_server(servicer, server): rpc_method_handlers = { 'getSpecializationList': grpc.unary_unary_rpc_method_handler( servicer.getSpecializationList, request_deserializer=specialization__pb2.SpecializationRequest.FromString, response_serializer=specialization__pb2.SpecializationListResponse.SerializeToString, ), 'getSpecializationById': grpc.unary_unary_rpc_method_handler( servicer.getSpecializationById, request_deserializer=specialization__pb2.SpecializationRequest.FromString, response_serializer=specialization__pb2.SpecializationResponse.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'remis.service.ISpecializationService', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,)) # This class is part of an EXPERIMENTAL API. class ISpecializationService(object): """Missing associated documentation comment in .proto file.""" @staticmethod def getSpecializationList(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/remis.service.ISpecializationService/getSpecializationList', specialization__pb2.SpecializationRequest.SerializeToString, specialization__pb2.SpecializationListResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata) @staticmethod def getSpecializationById(request, target, options=(), channel_credentials=None, call_credentials=None, insecure=False, compression=None, wait_for_ready=None, timeout=None, metadata=None): return grpc.experimental.unary_unary(request, target, '/remis.service.ISpecializationService/getSpecializationById', specialization__pb2.SpecializationRequest.SerializeToString, specialization__pb2.SpecializationResponse.FromString, options, channel_credentials, insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
/remisprotolib-1.0.1.tar.gz/remisprotolib-1.0.1/remis/specialization_pb2_grpc.py
0.733165
0.154089
specialization_pb2_grpc.py
pypi
import os import util from proxies import SongProxy try: import json except ImportError: import simplejson as json class Song(SongProxy): """ A Song object Attributes: id (str): Echo Nest Song ID title (str): Song Title artist_name (str): Artist Name artist_id (str): Artist ID audio_summary (dict): An Audio Summary dict song_hotttnesss (float): A float representing a song's hotttnesss artist_hotttnesss (float): A float representing a song's parent artist's hotttnesss artist_familiarity (float): A float representing a song's parent artist's familiarity artist_location (dict): A dictionary of strings specifying a song's parent artist's location, lattitude and longitude Create a song object like so: >>> s = song.Song('SOPEXHZ12873FD2AC7') """ def __init__(self, id, buckets=None, **kwargs): """ Song class Args: id (str): a song ID Kwargs: buckets (list): A list of strings specifying which buckets to retrieve Returns: A Song object Example: >>> s = song.Song('SOPEXHZ12873FD2AC7', buckets=['song_hotttnesss', 'artist_hotttnesss']) >>> s.song_hotttnesss 0.58602500000000002 >>> s.artist_hotttnesss 0.80329715999999995 >>> """ buckets = buckets or [] super(Song, self).__init__(id, buckets, **kwargs) def __repr__(self): return "<%s - %s>" % (self._object_type.encode('utf-8'), self.title.encode('utf-8')) def __str__(self): return self.title.encode('utf-8') def get_audio_summary(self, cache=True): """Get an audio summary of a song containing mode, tempo, key, duration, time signature, loudness, danceability, energy, and analysis_url. Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A dictionary containing mode, tempo, key, duration, time signature, loudness, danceability, energy and analysis_url keys. Example: >>> s = song.Song('SOGNMKX12B0B806320') >>> s.audio_summary {u'analysis_url': u'https://echonest-analysis.s3.amazonaws.com/TR/RnMKCg47J5LgQZr0SISyoPuRxKVQx3Z_YSuhVa/3/full.json?Signature=KBUbewLiP3sZ2X6rRZzXhrgh8fw%3D&Expires=1349809604&AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ', u'audio_md5': u'ca3fdfa72eed23d5ad89872c38cecc0e', u'danceability': 0.33712086491871546, u'duration': 470.70666999999997, u'energy': 0.58186979146361684, u'key': 0, u'liveness': 0.08676759933615498, u'loudness': -9.5960000000000001, u'mode': 1, u'speechiness': 0.036938896635994867, u'tempo': 126.949, u'time_signature': 4} >>> """ if not (cache and ('audio_summary' in self.cache)): response = self.get_attribute('profile', bucket='audio_summary') if response['songs'] and 'audio_summary' in response['songs'][0]: self.cache['audio_summary'] = response['songs'][0]['audio_summary'] else: self.cache['audio_summary'] = {} return self.cache['audio_summary'] audio_summary = property(get_audio_summary) def get_song_hotttnesss(self, cache=True): """Get our numerical description of how hottt a song currently is Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing hotttnesss. Example: >>> s = song.Song('SOLUHKP129F0698D49') >>> s.get_song_hotttnesss() 0.57344379999999995 >>> s.song_hotttnesss 0.57344379999999995 >>> """ if not (cache and ('song_hotttnesss' in self.cache)): response = self.get_attribute('profile', bucket='song_hotttnesss') self.cache['song_hotttnesss'] = response['songs'][0]['song_hotttnesss'] return self.cache['song_hotttnesss'] song_hotttnesss = property(get_song_hotttnesss) def get_song_type(self, cache=True): """Get the types of a song. Args: cache (boolean): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A list of strings, each representing a song type: 'christmas', for example. Example: >>> s = song.Song('SOQKVPH12A58A7AF4D') >>> s.song_type [u'christmas'] >>> """ if not (cache and ('song_type' in self.cache)): response = self.get_attribute('profile', bucket='song_type') if response['songs'][0].has_key('song_type'): self.cache['song_type'] = response['songs'][0]['song_type'] else: self.cache['song_type'] = [] return self.cache['song_type'] song_type = property(get_song_type) def get_artist_hotttnesss(self, cache=True): """Get our numerical description of how hottt a song's artist currently is Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing hotttnesss. Example: >>> s = song.Song('SOOLGAZ127F3E1B87C') >>> s.artist_hotttnesss 0.45645633000000002 >>> s.get_artist_hotttnesss() 0.45645633000000002 >>> """ if not (cache and ('artist_hotttnesss' in self.cache)): response = self.get_attribute('profile', bucket='artist_hotttnesss') self.cache['artist_hotttnesss'] = response['songs'][0]['artist_hotttnesss'] return self.cache['artist_hotttnesss'] artist_hotttnesss = property(get_artist_hotttnesss) def get_artist_familiarity(self, cache=True): """Get our numerical estimation of how familiar a song's artist currently is to the world Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing familiarity. Example: >>> s = song.Song('SOQKVPH12A58A7AF4D') >>> s.get_artist_familiarity() 0.639626025843539 >>> s.artist_familiarity 0.639626025843539 >>> """ if not (cache and ('artist_familiarity' in self.cache)): response = self.get_attribute('profile', bucket='artist_familiarity') self.cache['artist_familiarity'] = response['songs'][0]['artist_familiarity'] return self.cache['artist_familiarity'] artist_familiarity = property(get_artist_familiarity) def get_artist_location(self, cache=True): """Get the location of a song's artist. Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: An artist location object. Example: >>> s = song.Song('SOQKVPH12A58A7AF4D') >>> s.artist_location {u'latitude': 34.053489999999996, u'location': u'Los Angeles, CA', u'longitude': -118.24532000000001} >>> """ if not (cache and ('artist_location' in self.cache)): response = self.get_attribute('profile', bucket='artist_location') self.cache['artist_location'] = response['songs'][0]['artist_location'] return self.cache['artist_location'] artist_location = property(get_artist_location) def get_foreign_id(self, idspace='', cache=True): """Get the foreign id for this song for a specific id space Args: Kwargs: idspace (str): A string indicating the idspace to fetch a foreign id for. Returns: A foreign ID string Example: >>> s = song.Song('SOYRVMR12AF729F8DC') >>> s.get_foreign_id('CAGPXKK12BB06F9DE9') >>> """ idspace = util.map_idspace(idspace) if not (cache and ('foreign_ids' in self.cache) and filter(lambda d: d.get('catalog') == idspace, self.cache['foreign_ids'])): response = self.get_attribute('profile', bucket=['id:'+idspace]) rsongs = response['songs'] if len(rsongs) == 0: return None foreign_ids = rsongs[0].get("foreign_ids", []) self.cache['foreign_ids'] = self.cache.get('foreign_ids', []) + foreign_ids cval = filter(lambda d: d.get('catalog') == idspace, self.cache.get('foreign_ids')) return cval[0].get('foreign_id') if cval else None def get_song_discovery(self, cache=True): """ Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing a song's discovery rank. Example: >>> s = song.Song('SOQKVPH12A58A7AF4D') >>> s.get_song_discovery() 0.639626025843539 >>> s.song_discovery 0.639626025843539 >>> """ if not (cache and ('song_discovery' in self.cache)): response = self.get_attribute('profile', bucket='song_discovery') self.cache['song_discovery'] = response['songs'][0]['song_discovery'] return self.cache['song_discovery'] song_discovery = property(get_song_discovery) def get_song_currency(self, cache=True): """ Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing a song's currency rank. Example: >>> s = song.Song('SOQKVPH12A58A7AF4D') >>> s.get_song_currency() 0.639626025843539 >>> s.song_currency 0.639626025843539 >>> """ if not (cache and ('song_currency' in self.cache)): response = self.get_attribute('profile', bucket='song_currency') self.cache['song_currency'] = response['songs'][0]['song_currency'] return self.cache['song_currency'] song_currency = property(get_song_currency) def get_tracks(self, catalog, cache=True): """Get the tracks for a song given a catalog. Args: catalog (str): a string representing the catalog whose track you want to retrieve. Returns: A list of Track dicts. Example: >>> s = song.Song('SOWDASQ12A6310F24F') >>> s.get_tracks('7digital')[0] {u'catalog': u'7digital', u'foreign_id': u'7digital:track:8445818', u'id': u'TRJGNNY12903CC625C', u'preview_url': u'http://previews.7digital.com/clips/34/8445818.clip.mp3', u'release_image': u'http://cdn.7static.com/static/img/sleeveart/00/007/628/0000762838_200.jpg'} >>> """ if not (cache and ('tracks' in self.cache) and (catalog in [td['catalog'] for td in self.cache['tracks']])): kwargs = { 'bucket':['tracks', 'id:%s' % catalog], } response = self.get_attribute('profile', **kwargs) if not 'tracks' in self.cache: self.cache['tracks'] = [] # don't blow away the cache for other catalogs potential_tracks = response['songs'][0].get('tracks', []) existing_track_ids = [tr['foreign_id'] for tr in self.cache['tracks']] new_tds = filter(lambda tr: tr['foreign_id'] not in existing_track_ids, potential_tracks) self.cache['tracks'].extend(new_tds) return filter(lambda tr: tr['catalog']==util.map_idspace(catalog), self.cache['tracks']) def identify(filename=None, query_obj=None, code=None, artist=None, title=None, release=None, duration=None, genre=None, buckets=None, version=None, codegen_start=0, codegen_duration=30): """Identify a song. Args: Kwargs: filename (str): The path of the file you want to analyze (requires codegen binary!) query_obj (dict or list): A dict or list of dicts containing a 'code' element with an fp code code (str): A fingerprinter code artist (str): An artist name title (str): A song title release (str): A release name duration (int): A song duration genre (str): A string representing the genre buckets (list): A list of strings specifying which buckets to retrieve version (str): The version of the code generator used to generate the code codegen_start (int): The point (in seconds) where the codegen should start codegen_duration (int): The duration (in seconds) the codegen should analyze Example: >>> qo {'code': 'eJxlldehHSEMRFsChAjlAIL-S_CZvfaXXxAglEaBTen300Qu__lAyoJYhVQdXTvXrmvXdTsKZOqoU1q63QNydBGfOd1cGX3scpb1jEiWRLaPcJureC6RVkXE69jL8pGHjpP48pLI1m7r9oiEyBXvoVv45Q-5IhylYLkIRxGO4rp18ZpEOmpFPopwfJjL0u3WceO3HB1DIvJRnkQeO1PCLIsIjBWEzYaShq4pV9Z0KzDiQ8SbSNuSyBZPOOxIJKR7dauEmXwotxDCqllEAVZlrX6F8Y-IJ0e169i_HQaqslaVtTq1W-1vKeupImzrxWWVI5cPlw-XDxckN-3kyeXDm3jKmqv6PtB1gfH1Eey5qu8qvAuMC4zLfPv1l3aqviylJhytFhF0mzqs6aYpYU04mlqgKWtNjppwNKWubR2FowlHUws0gWmPi668dSHq6rOuPuhqgRcVKKM8s-fZS937nBe23iz3Uctx9607z-kLph1i8YZ8f_TfzLXseBh7nXy9nn1YBAg4Nwjp4AzTL23M_U3Rh0-sdDFtyspNOb1bYeZZqz2Y6TaHmXeuNmfFdTueLuvdsbOU9luvtIkl4vI5F_92PVprM1-sdJ_o9_Guc0b_WimpD_Rt1DFg0sY3wyw08e6jlqhjH3o76naYvzWqhX9rOv15Y7Ww_MIF8dXzw30s_uHO5PPDfUonnzq_NJ8J93mngAkIz5jA29SqxGwwvxQsih-sozX0zVk__RFaf_qyG9hb8dktZZXd4a8-1ljB-c5bllXOe1HqHplzeiN4E7q9ZRdmJuI73gBEJ_HcAxUm74PAVDNL47D6OAfzTHI0mHpXAmY60QNmlqjDfIPzwUDYhVnoXqtvZGrBdMi3ClQUQ8D8rX_1JE_In94CBXER4lrrw0H867ei8x-OVz8c-Osh5plzTOySpKIROmFkbn5xVuK784vTyPpS3OlcSjHpL16saZnm4Bk66hte9sd80Dcj02f7xDVrExjk32cssKXjmflU_SxXmn4Y9Ttued10YM552h5Wtt_WeVR4U6LPWfbIdW31J4JOXnpn4qhH7yE_pdBH9E_sMwbNFr0z0IW5NA8aOZhLmOh3zSVNRZwxiZc5pb8fikGzIf-ampJnCSb3r-ZPfjPuvLm7CY_Vfa_k7SCzdwHNg5mICTSHDxyBWmaOSyLQpPmCSXyF-eL7MHo7zNd668JMb_N-AJJRuMwrX0jNx7a8-Rj5oN6nyWoL-jRv4pu7Ue821TzU3MhvpD9Fo-XI', 'code_count': 151, 'low_rank': 0, 'metadata': {'artist': 'Harmonic 313', 'bitrate': 198, 'codegen_time': 0.57198400000000005, 'decode_time': 0.37954599999999999, 'duration': 226, 'filename': 'koln.mp3', 'genre': 'Electronic', 'given_duration': 30, 'release': 'When Machines Exceed Human Intelligence', 'sample_rate': 44100, 'samples_decoded': 661816, 'start_offset': 0, 'title': 'kln', 'version': 3.1499999999999999}, 'tag': 0} >>> song.identify(query_obj=qo) [<song - Köln>] >>> """ post, has_data, data = False, False, False if filename: if os.path.exists(filename): query_obj = util.codegen(filename, start=codegen_start, duration=codegen_duration) if query_obj is None: raise Exception("The filename specified: %s could not be decoded." % filename) else: raise Exception("The filename specified: %s does not exist." % filename) if query_obj and not isinstance(query_obj, list): query_obj = [query_obj] if filename: # check codegen results from file in case we had a bad result for q in query_obj: if 'error' in q: raise Exception(q['error'] + ": " + q.get('metadata', {}).get('filename', '')) if not (filename or query_obj or code): raise Exception("Not enough information to identify song.") kwargs = {} if code: has_data = True kwargs['code'] = code if title: kwargs['title'] = title if release: kwargs['release'] = release if duration: kwargs['duration'] = duration if genre: kwargs['genre'] = genre if buckets: kwargs['bucket'] = buckets if version: kwargs['version'] = version if query_obj and any(query_obj): has_data = True data = {'query':json.dumps(query_obj)} post = True if has_data: result = util.callm("%s/%s" % ('song', 'identify'), kwargs, POST=post, data=data) return [Song(**util.fix(s_dict)) for s_dict in result['response'].get('songs',[])] def search(title=None, artist=None, artist_id=None, combined=None, description=None, style=None, mood=None, results=None, start=None, max_tempo=None, min_tempo=None, max_duration=None, min_duration=None, max_loudness=None, min_loudness=None, artist_max_familiarity=None, artist_min_familiarity=None, artist_max_hotttnesss=None, artist_min_hotttnesss=None, song_max_hotttnesss=None, song_min_hotttnesss=None, mode=None, min_energy=None, max_energy=None, min_danceability=None, max_danceability=None, key=None, max_latitude=None, min_latitude=None, max_longitude=None, min_longitude=None, sort=None, buckets=None, limit=False, test_new_things=None, rank_type=None, artist_start_year_after=None, artist_start_year_before=None, artist_end_year_after=None, artist_end_year_before=None,song_type=None,min_song_currency=None,max_song_currency=None, min_song_discovery=None, max_song_discovery=None, max_acousticness=None, min_acousticness=None, max_liveness=None, min_liveness=None, max_speechiness=None, min_speechiness=None, max_valence=None, min_valence=None): """Search for songs by name, description, or constraint. Args: Kwargs: title (str): the name of a song artist (str): the name of an artist artist_id (str): the artist_id combined (str): the artist name and song title description (str): A string describing the artist and song style (str): A string describing the style/genre of the artist and song mood (str): A string describing the mood of the artist and song results (int): An integer number of results to return max_acousticness (float): The max acousticness of song results min_acousticness (float): The min acousticness of song results max_tempo (float): The max tempo of song results min_tempo (float): The min tempo of song results max_duration (float): The max duration of song results min_duration (float): The min duration of song results max_liveness (float): The max liveness of song results min_liveness (float): The min liveness of song results max_loudness (float): The max loudness of song results min_loudness (float): The min loudness of song results max_speechiness (float): The max speechiness of song results min_speechiess (float): The min speechiness of song results max_valence (float): The max valence of song results min_valence (float): The min valence of song results artist_max_familiarity (float): A float specifying the max familiarity of artists to search for artist_min_familiarity (float): A float specifying the min familiarity of artists to search for artist_max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for artist_min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for song_max_hotttnesss (float): A float specifying the max hotttnesss of songs to search for song_min_hotttnesss (float): A float specifying the max hotttnesss of songs to search for max_energy (float): The max energy of song results min_energy (float): The min energy of song results max_dancibility (float): The max dancibility of song results min_dancibility (float): The min dancibility of song results mode (int): 0 or 1 (minor or major) key (int): 0-11 (c, c-sharp, d, e-flat, e, f, f-sharp, g, a-flat, a, b-flat, b) max_latitude (float): A float specifying the max latitude of artists to search for min_latitude (float): A float specifying the min latitude of artists to search for max_longitude (float): A float specifying the max longitude of artists to search for min_longitude (float): A float specifying the min longitude of artists to search for sort (str): A string indicating an attribute and order for sorting the results buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets rank_type (str): A string denoting the desired ranking for description searches, either 'relevance' or 'familiarity artist_start_year_before (int): Returned songs's artists will have started recording music before this year. artist_start_year_after (int): Returned songs's artists will have started recording music after this year. artist_end_year_before (int): Returned songs's artists will have stopped recording music before this year. artist_end_year_after (int): Returned songs's artists will have stopped recording music after this year. song_type (string): A string or list of strings specifiying the type of song to search for. Returns: A list of Song objects Example: >>> results = song.search(artist='shakira', title='she wolf', buckets=['id:7digital', 'tracks'], limit=True, results=1) >>> results [<song - She Wolf>] >>> results[0].get_tracks('7digital')[0] {u'catalog': u'7digital', u'foreign_id': u'7digital:track:7854109', u'id': u'TRTOBSE12903CACEC4', u'preview_url': u'http://previews.7digital.com/clips/34/7854109.clip.mp3', u'release_image': u'http://cdn.7static.com/static/img/sleeveart/00/007/081/0000708184_200.jpg'} >>> """ limit = str(limit).lower() kwargs = locals() kwargs['bucket'] = buckets del kwargs['buckets'] result = util.callm("%s/%s" % ('song', 'search'), kwargs) return [Song(**util.fix(s_dict)) for s_dict in result['response']['songs']] def profile(ids=None, track_ids=None, buckets=None, limit=False): """get the profiles for multiple songs at once Args: ids (str or list): a song ID or list of song IDs Kwargs: buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets Returns: A list of term document dicts Example: >>> song_ids = ['SOBSLVH12A8C131F38', 'SOXMSGY1338A5D5873', 'SOJPHZO1376210AFE5', 'SOBHNKR12AB0186218', 'SOSJAHD13770F4D40C'] >>> songs = song.profile(song_ids, buckets=['audio_summary']) [<song - Say It Ain't So>, <song - Island In The Sun>, <song - My Name Is Jonas>, <song - Buddy Holly>] >>> songs[0].audio_summary {u'analysis_url': u'https://echonest-analysis.s3.amazonaws.com/TR/7VRBNguufpHAQQ4ZjJ0eWsIQWl2S2_lrK-7Bp2azHOvPN4VFV-YnU7uO0dXgYtOKT-MTEa/3/full.json?Signature=hmNghHwfEsA4JKWFXnRi7mVP6T8%3D&Expires=1349809918&AWSAccessKeyId=AKIAJRDFEY23UEVW42BQ', u'audio_md5': u'b6079b2b88f8265be8bdd5fe9702e05c', u'danceability': 0.64540643050283253, u'duration': 255.92117999999999, u'energy': 0.30711665772260549, u'key': 8, u'liveness': 0.088994423525370583, u'loudness': -9.7799999999999994, u'mode': 1, u'speechiness': 0.031970700260699259, u'tempo': 76.049999999999997, u'time_signature': 4} >>> """ kwargs = {} if ids: if not isinstance(ids, list): ids = [ids] kwargs['id'] = ids if track_ids: if not isinstance(track_ids, list): track_ids = [track_ids] kwargs['track_id'] = track_ids buckets = buckets or [] if buckets: kwargs['bucket'] = buckets if limit: kwargs['limit'] = 'true' result = util.callm("%s/%s" % ('song', 'profile'), kwargs) return [Song(**util.fix(s_dict)) for s_dict in result['response']['songs']]
/remix-2.4.0.tar.gz/remix-2.4.0/pyechonest/pyechonest/song.py
0.801237
0.193738
song.py
pypi
try: import json except ImportError: import simplejson as json import datetime import warnings import util from proxies import CatalogProxy, ResultList import artist, song # deal with datetime in json dthandler = lambda obj: obj.isoformat() if isinstance(obj, datetime.datetime) else None def create_catalog_by_name(name, T="general"): """ Creates a catalog object, with a given name. Does not check to see if the catalog already exists. Create a catalog object like """ result = util.callm("catalog/create", {}, POST=True, data={"name":name, "type":T}) result = result['response'] return Catalog(result['id'], **dict( (k,result[k]) for k in ('name', 'type'))) class Catalog(CatalogProxy): """ A Catalog object Attributes: id (str): Catalog ID name (str): Catalog Name read (list): A list of catalog items (objects if they are resolved, else dictionaries) feed (list): A list of dictionaries for news, blogs, reviews, audio, video for a catalog's artists Create an catalog object like so: >>> c = catalog.Catalog('CAGPXKK12BB06F9DE9') # get existing catalog >>> c = catalog.Catalog('test_song_catalog', 'song') # get existing or create new catalog """ def __init__(self, id, type=None, **kwargs): """ Create a catalog object (get a catalog by ID or get or create one given by name and type) Args: id (str): A catalog id or name Kwargs: type (str): 'song' or 'artist', specifying the catalog type Returns: A catalog object Example: >>> c = catalog.Catalog('my_songs', type='song') >>> c.id u'CAVKUPC12BCA792120' >>> c.name u'my_songs' >>> """ super(Catalog, self).__init__(id, type, **kwargs) def __repr__(self): return "<%s - %s>" % (self._object_type.encode('utf-8'), self.name.encode('utf-8')) def __str__(self): return self.name.encode('utf-8') def update(self, items): """ Update a catalog object Args: items (list): A list of dicts describing update data and action codes (see api docs) Kwargs: Returns: A ticket id Example: >>> c = catalog.Catalog('my_songs', type='song') >>> items [{'action': 'update', 'item': {'artist_name': 'dAn ThE aUtOmAtOr', 'disc_number': 1, 'genre': 'Instrumental', 'item_id': '38937DDF04BC7FC4', 'play_count': 5, 'release': 'Bombay the Hard Way: Guns, Cars & Sitars', 'song_name': 'Inspector Jay From Dehli', 'track_number': 9, 'url': 'file://localhost/Users/tylerw/Music/iTunes/iTunes%20Media/Music/Dan%20the%20Automator/Bombay%20the%20Hard%20Way_%20Guns,%20Cars%20&%20Sitars/09%20Inspector%20Jay%20From%20Dehli.m4a'}}] >>> ticket = c.update(items) >>> ticket u'7dcad583f2a38e6689d48a792b2e4c96' >>> c.status(ticket) {u'ticket_status': u'complete', u'update_info': []} >>> """ post_data = {} items_json = json.dumps(items, default=dthandler) post_data['data'] = items_json response = self.post_attribute("update", data=post_data) return response['ticket'] def status(self, ticket): """ Check the status of a catalog update Args: ticket (str): A string representing a ticket ID Kwargs: Returns: A dictionary representing ticket status Example: >>> ticket u'7dcad583f2a38e6689d48a792b2e4c96' >>> c.status(ticket) {u'ticket_status': u'complete', u'update_info': []} >>> """ return self.get_attribute_simple("status", ticket=ticket) def get_profile(self): """ Check the status of a catalog update Args: Kwargs: Returns: A dictionary representing ticket status Example: >>> c <catalog - test_song_catalog> >>> c.profile() {u'id': u'CAGPXKK12BB06F9DE9', u'name': u'test_song_catalog', u'pending_tickets': [], u'resolved': 2, u'total': 4, u'type': u'song'} >>> """ result = self.get_attribute("profile") return result['catalog'] profile = property(get_profile) def read_items(self, buckets=None, results=15, start=0,item_ids=None): """ Returns data from the catalog; also expanded for the requested buckets. This method is provided for backwards-compatibility Args: Kwargs: buckets (list): A list of strings specifying which buckets to retrieve results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of objects in the catalog; list contains additional attributes 'start' and 'total' Example: >>> c <catalog - my_songs> >>> c.read_items(results=1) [<song - Harmonice Mundi II>] >>> """ warnings.warn("catalog.read_items() is depreciated. Please use catalog.get_item_dicts() instead.") kwargs = {} kwargs['bucket'] = buckets or [] kwargs['item_id'] = item_ids or [] response = self.get_attribute("read", results=results, start=start, **kwargs) rval = ResultList([]) if item_ids: rval.start=0; rval.total=len(response['catalog']['items']) else: rval.start = response['catalog']['start'] rval.total = response['catalog']['total'] for item in response['catalog']['items']: new_item = None # song items if 'song_id' in item: item['id'] = item.pop('song_id') item['title'] = item.pop('song_name') request = item['request'] new_item = song.Song(**util.fix(item)) new_item.request = request # artist item elif 'artist_id' in item: item['id'] = item.pop('artist_id') item['name'] = item.pop('artist_name') request = item['request'] new_item = artist.Artist(**util.fix(item)) new_item.request = request # unresolved item else: new_item = item rval.append(new_item) return rval read = property(read_items) def get_item_dicts(self, buckets=None, results=15, start=0,item_ids=None): """ Returns data from the catalog; also expanded for the requested buckets Args: Kwargs: buckets (list): A list of strings specifying which buckets to retrieve results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of dicts representing objects in the catalog; list has additional attributes 'start' and 'total' Example: >>> c <catalog - my_songs> >>> c.read_items(results=1) [ { "artist_id": "AR78KRI1187B98E6F2", "artist_name": "Art of Noise", "date_added": "2012-04-02T16:50:02", "foreign_id": "CAHLYLR13674D1CF83:song:1000", "request": { "artist_name": "The Art Of Noise", "item_id": "1000", "song_name": "Love" }, "song_id": "SOSBCTO1311AFE7AE0", "song_name": "Love" } ] """ kwargs = {} kwargs['bucket'] = buckets or [] kwargs['item_id'] = item_ids or [] response = self.get_attribute("read", results=results, start=start, **kwargs) rval = ResultList(response['catalog']['items']) if item_ids: rval.start=0; rval.total=len(response['catalog']['items']) else: rval.start = response['catalog']['start'] rval.total = response['catalog']['total'] return rval item_dicts = property(get_item_dicts) def get_feed(self, buckets=None, since=None, results=15, start=0): """ Returns feed (news, blogs, reviews, audio, video) for the catalog artists; response depends on requested buckets Args: Kwargs: buckets (list): A list of strings specifying which feed items to retrieve results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of news, blogs, reviews, audio or video document dicts; Example: >>> c <catalog - my_artists> >>> c.get_feed(results=15) {u'date_found': u'2011-02-06T07:50:25', u'date_posted': u'2011-02-06T07:50:23', u'id': u'caec686c0dff361e4c53dceb58fb9d2f', u'name': u'Linkin Park \u2013 \u201cWaiting For The End\u201d + \u201cWhen They Come For Me\u201d 2/5 SNL', u'references': [{u'artist_id': u'ARQUMH41187B9AF699', u'artist_name': u'Linkin Park'}], u'summary': u'<span>Linkin</span> <span>Park</span> performed "Waiting For The End" and "When They Come For Me" on Saturday Night Live. Watch the videos below and pick up their album A Thousand Suns on iTunes, Amazon MP3, CD Social Bookmarking ... ', u'type': u'blogs', u'url': u'http://theaudioperv.com/2011/02/06/linkin-park-waiting-for-the-end-when-they-come-for-me-25-snl/'} >>> """ kwargs = {} kwargs['bucket'] = buckets or [] if since: kwargs['since']=since response = self.get_attribute("feed", results=results, start=start, **kwargs) rval = ResultList(response['feed']) return rval feed = property(get_feed) def delete(self): """ Deletes the entire catalog Args: Kwargs: Returns: The deleted catalog's id. Example: >>> c <catalog - test_song_catalog> >>> c.delete() {u'id': u'CAXGUPY12BB087A21D'} >>> """ return self.post_attribute("delete") def play(self, items, plays=None): return self.get_attribute("play", item=items, plays=plays) def skip(self, items, skips=None): return self.get_attribute("skip", item=items, skips=skips) def keyvalues(self): return self.get_attribute("keyvalues")['keyvalues'] def favorite(self, items, favorite=None): if favorite != None: favorite = str(favorite).lower() return self.get_attribute("favorite", item=items, favorite=favorite) def ban(self, items, ban=None): if ban != None: ban = str(ban).lower() return self.get_attribute("ban", item=items, ban=ban) def rate(self, items, rating=None): return self.get_attribute("rate", item=items, rating=rating) def get_catalog_by_name(name): """ Grabs a catalog by name, if its there on the api key. Otherwise, an error is thrown (mirroring the API) """ kwargs = { 'name' : name, } result = util.callm("%s/%s" % ('catalog', 'profile'), kwargs) return Catalog(**util.fix(result['response']['catalog'])) def list_catalogs(results=30, start=0): """ Returns list of all catalogs created on this API key Args: Kwargs: results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of catalog objects Example: >>> catalog.list_catalogs() [<catalog - test_artist_catalog>, <catalog - test_song_catalog>, <catalog - my_songs>] >>> """ result = util.callm("%s/%s" % ('catalog', 'list'), {'results': results, 'start': start}) cats = [Catalog(**util.fix(d)) for d in result['response']['catalogs']] start = result['response']['start'] total = result['response']['total'] return ResultList(cats, start, total)
/remix-2.4.0.tar.gz/remix-2.4.0/pyechonest/pyechonest/catalog.py
0.722331
0.223102
catalog.py
pypi
import util from proxies import ArtistProxy, ResultList from song import Song class Artist(ArtistProxy): """ An Artist object Attributes: id (str): Echo Nest Artist ID name (str): Artist Name audio (list): Artist audio biographies (list): Artist biographies blogs (list): Artist blogs familiarity (float): Artist familiarity hotttnesss (float): Artist hotttnesss images (list): Artist images news (list): Artist news reviews (list): Artist reviews similar (list): Similar Artists songs (list): A list of song objects terms (list): Terms for an artist urls (list): Artist urls video (list): Artist video years_active (list): A list of dictionaries containing start and stop years You create an artist object like this: >>> a = artist.Artist('ARH6W4X1187B99274F') >>> a = artist.Artist('the national') >>> a = artist.Artist('musicbrainz:artist:a74b1b7f-71a5-4011-9441-d0b5e4122711') """ def __init__(self, id, **kwargs): """ Artist class Args: id (str): an artistw ID Returns: An artist object Example: >>> a = artist.Artist('ARH6W4X1187B99274F', buckets=['hotttnesss']) >>> a.hotttnesss 0.80098515900997658 >>> """ super(Artist, self).__init__(id, **kwargs) def __repr__(self): return "<%s - %s>" % (self._object_type.encode('utf-8'), self.name.encode('utf-8')) def __str__(self): return self.name.encode('utf-8') def __cmp__(self, other): return cmp(self.id, other.id) def get_audio(self, results=15, start=0, cache=True): """Get a list of audio documents found on the web related to an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of audio document dicts; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('alphabeat') >>> a.get_audio()[0] {u'artist': u'Alphabeat', u'date': u'2010-04-28T01:40:45', u'id': u'70be4373fa57ac2eee8c7f30b0580899', u'length': 210.0, u'link': u'http://iamthecrime.com', u'release': u'The Beat Is...', u'title': u'DJ', u'url': u'http://iamthecrime.com/wp-content/uploads/2010/04/03_DJ_iatc.mp3'} >>> """ if cache and ('audio' in self.cache) and results==15 and start==0: return self.cache['audio'] else: response = self.get_attribute('audio', results=results, start=start) if results==15 and start==0: self.cache['audio'] = ResultList(response['audio'], 0, response['total']) return ResultList(response['audio'], start, response['total']) audio = property(get_audio) def get_biographies(self, results=15, start=0, license=None, cache=True): """Get a list of artist biographies Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting value for the result set license (str): A string specifying the desired license type Returns: A list of biography document dicts; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('britney spears') >>> bio = a.get_biographies(results=1)[0] >>> bio['url'] u'http://www.mtvmusic.com/spears_britney' >>> """ if cache and ('biographies' in self.cache) and results==15 and start==0 and license==None: return self.cache['biographies'] else: response = self.get_attribute('biographies', results=results, start=start, license=license) if results==15 and start==0 and license==None: self.cache['biographies'] = ResultList(response['biographies'], 0, response['total']) return ResultList(response['biographies'], start, response['total']) biographies = property(get_biographies) def get_blogs(self, results=15, start=0, cache=True, high_relevance=False): """Get a list of blog articles related to an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An ingteger starting value for the result set Returns: A list of blog document dicts; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('bob marley') >>> blogs = a.get_blogs(results=1,start=4) >>> blogs.total 4068 >>> blogs[0]['summary'] But the Kenyans I know relate to music about the same way Americans do. They like their Congolese afropop, and I've known some to be big fans of international acts like <span>Bob</span> <span>Marley</span> and Dolly Parton. They rarely talk about music that's indigenous in the way a South African or Malian or Zimbabwean would, and it's even rarer to actually hear such indigenous music. I do sometimes hear ceremonial chanting from the Maasai, but only when they're dancing for tourists. If East Africa isn't the most musical part ... " >>> """ if cache and ('blogs' in self.cache) and results==15 and start==0 and not high_relevance: return self.cache['blogs'] else: high_relevance = 'true' if high_relevance else 'false' response = self.get_attribute('blogs', results=results, start=start, high_relevance=high_relevance) if results==15 and start==0: self.cache['blogs'] = ResultList(response['blogs'], 0, response['total']) return ResultList(response['blogs'], start, response['total']) blogs = property(get_blogs) def get_familiarity(self, cache=True): """Get our numerical estimation of how familiar an artist currently is to the world Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A float representing familiarity. Example: >>> a = artist.Artist('frank sinatra') >>> a.get_familiarity() 0.65142555825947457 >>> a.familiarity 0.65142555825947457 >>> """ if not (cache and ('familiarity' in self.cache)): response = self.get_attribute('familiarity') self.cache['familiarity'] = response['artist']['familiarity'] return self.cache['familiarity'] familiarity = property(get_familiarity) def get_foreign_id(self, idspace='musicbrainz', cache=True): """Get the foreign id for this artist for a specific id space Args: Kwargs: idspace (str): A string indicating the idspace to fetch a foreign id for. Returns: A foreign ID string Example: >>> a = artist.Artist('fabulous') >>> a.get_foreign_id('7digital') u'7digital:artist:186042' >>> """ if not (cache and ('foreign_ids' in self.cache) and filter(lambda d: d.get('catalog') == idspace, self.cache['foreign_ids'])): response = self.get_attribute('profile', bucket=['id:'+idspace]) foreign_ids = response['artist'].get("foreign_ids", []) self.cache['foreign_ids'] = self.cache.get('foreign_ids', []) + foreign_ids cval = filter(lambda d: d.get('catalog') == util.map_idspace(idspace), self.cache.get('foreign_ids')) return cval[0].get('foreign_id') if cval else None def get_twitter_id(self, cache=True): """Get the twitter id for this artist if it exists Args: Kwargs: Returns: A twitter ID string Example: >>> a = artist.Artist('big boi') >>> a.get_twitter_id() u'BigBoi' >>> """ if not (cache and ('twitter' in self.cache)): response = self.get_attribute('twitter') self.cache['twitter'] = response['artist'].get('twitter') return self.cache['twitter'] def get_hotttnesss(self, cache=True): """Get our numerical description of how hottt an artist currently is Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: float: the hotttnesss value Example: >>> a = artist.Artist('hannah montana') >>> a.get_hotttnesss() 0.59906022155998995 >>> a.hotttnesss 0.59906022155998995 >>> """ if not (cache and ('hotttnesss' in self.cache)): response = self.get_attribute('hotttnesss') self.cache['hotttnesss'] = response['artist']['hotttnesss'] return self.cache['hotttnesss'] hotttnesss = property(get_hotttnesss) def get_images(self, results=15, start=0, license=None, cache=True): """Get a list of artist images Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting value for the result set license (str): A string specifying the desired license type Returns: A list of image document dicts; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('Captain Beefheart') >>> images = a.get_images(results=1) >>> images.total 49 >>> images[0]['url'] u'http://c4.ac-images.myspacecdn.com/images01/5/l_e1a329cdfdb16a848288edc6d578730f.jpg' >>> """ if cache and ('images' in self.cache) and results==15 and start==0 and license==None: return self.cache['images'] else: response = self.get_attribute('images', results=results, start=start, license=license) total = response.get('total') or 0 if results==15 and start==0 and license==None: self.cache['images'] = ResultList(response['images'], 0, total) return ResultList(response['images'], start, total) images = property(get_images) def get_news(self, results=15, start=0, cache=True, high_relevance=False): """Get a list of news articles found on the web related to an artist Args: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of news document dicts; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('Henry Threadgill') >>> news = a.news >>> news.total 41 >>> news[0]['name'] u'Jazz Journalists Association Announces 2010 Jazz Award Winners' >>> """ if cache and ('news' in self.cache) and results==15 and start==0 and not high_relevance: return self.cache['news'] else: high_relevance = 'true' if high_relevance else 'false' response = self.get_attribute('news', results=results, start=start, high_relevance=high_relevance) if results==15 and start==0: self.cache['news'] = ResultList(response['news'], 0, response['total']) return ResultList(response['news'], start, response['total']) news = property(get_news) def get_reviews(self, results=15, start=0, cache=True): """Get reviews related to an artist's work Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of review document dicts; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('Ennio Morricone') >>> reviews = a.reviews >>> reviews.total 17 >>> reviews[0]['release'] u'For A Few Dollars More' >>> """ if cache and ('reviews' in self.cache) and results==15 and start==0: return self.cache['reviews'] else: response = self.get_attribute('reviews', results=results, start=start) if results==15 and start==0: self.cache['reviews'] = ResultList(response['reviews'], 0, response['total']) return ResultList(response['reviews'], start, response['total']) reviews = property(get_reviews) def get_similar(self, results=15, start=0, buckets=None, limit=False, cache=True, max_familiarity=None, min_familiarity=None, \ max_hotttnesss=None, min_hotttnesss=None, min_results=None, reverse=False, artist_start_year_before=None, \ artist_start_year_after=None,artist_end_year_before=None,artist_end_year_after=None): """Return similar artists to this one Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting value for the result set max_familiarity (float): A float specifying the max familiarity of artists to search for min_familiarity (float): A float specifying the min familiarity of artists to search for max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for reverse (bool): A boolean indicating whether or not to return dissimilar artists (wrecommender). Defaults to False. Returns: A list of similar Artist objects Example: >>> a = artist.Artist('Sleater Kinney') >>> similars = a.similar[:5] >>> similars [<artist - Bikini Kill>, <artist - Pretty Girls Make Graves>, <artist - Huggy Bear>, <artist - Bratmobile>, <artist - Team Dresch>] >>> """ buckets = buckets or [] kwargs = {} if max_familiarity: kwargs['max_familiarity'] = max_familiarity if min_familiarity: kwargs['min_familiarity'] = min_familiarity if max_hotttnesss: kwargs['max_hotttnesss'] = max_hotttnesss if min_hotttnesss: kwargs['min_hotttnesss'] = min_hotttnesss if min_results: kwargs['min_results'] = min_results if buckets: kwargs['bucket'] = buckets if limit: kwargs['limit'] = 'true' if reverse: kwargs['reverse'] = 'true' if artist_start_year_before: kwargs['artist_start_year_before'] = artist_start_year_before if artist_start_year_after: kwargs['artist_start_year_after'] = artist_start_year_after if artist_end_year_before: kwargs['artist_end_year_before'] = artist_end_year_before if artist_end_year_after: kwargs['artist_end_year_after'] = artist_end_year_after if cache and ('similar' in self.cache) and results==15 and start==0 and (not kwargs): return [Artist(**util.fix(a)) for a in self.cache['similar']] else: response = self.get_attribute('similar', results=results, start=start, **kwargs) if results==15 and start==0 and (not kwargs): self.cache['similar'] = response['artists'] return [Artist(**util.fix(a)) for a in response['artists']] similar = property(get_similar) def get_songs(self, cache=True, results=15, start=0): """Get the songs associated with an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting value for the result set Results: A list of Song objects; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('Strokes') >>> a.get_songs(results=5) [<song - Fear Of Sleep>, <song - Red Light>, <song - Ize Of The World>, <song - Evening Sun>, <song - Juicebox>] >>> """ if cache and ('songs' in self.cache) and results==15 and start==0: if not isinstance(self.cache['songs'][0], Song): song_objects = [] for s in self.cache["songs"]: song_objects.append(Song(id=s['id'], title=s['title'], artist_name=self.name, artist_id=self.id)) self.cache['songs'] = song_objects return self.cache['songs'] else: response = self.get_attribute('songs', results=results, start=start) for s in response['songs']: s.update({'artist_id':self.id, 'artist_name':self.name}) songs = [Song(**util.fix(s)) for s in response['songs']] if results==15 and start==0: self.cache['songs'] = ResultList(songs, 0, response['total']) return ResultList(songs, start, response['total']) songs = property(get_songs) def get_terms(self, sort='weight', cache=True): """Get the terms associated with an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. sort (str): A string specifying the desired sorting type (weight or frequency) Results: A list of term document dicts Example: >>> a = artist.Artist('tom petty') >>> a.terms [{u'frequency': 1.0, u'name': u'heartland rock', u'weight': 1.0}, {u'frequency': 0.88569401860168606, u'name': u'jam band', u'weight': 0.9116501862732439}, {u'frequency': 0.9656145118557401, u'name': u'pop rock', u'weight': 0.89777934440040685}, {u'frequency': 0.8414744288140491, u'name': u'southern rock', u'weight': 0.8698567153186606}, {u'frequency': 0.9656145118557401, u'name': u'hard rock', u'weight': 0.85738022655218893}, {u'frequency': 0.88569401860168606, u'name': u'singer-songwriter', u'weight': 0.77427243392312772}, {u'frequency': 0.88569401860168606, u'name': u'rock', u'weight': 0.71158718989399083}, {u'frequency': 0.60874110500110956, u'name': u'album rock', u'weight': 0.69758668733499629}, {u'frequency': 0.74350792060935744, u'name': u'psychedelic', u'weight': 0.68457367494207944}, {u'frequency': 0.77213698386292873, u'name': u'pop', u'weight': 0.65039556639337293}, {u'frequency': 0.41747136183050298, u'name': u'bar band', u'weight': 0.54974975024767025}] >>> """ if cache and ('terms' in self.cache) and sort=='weight': return self.cache['terms'] else: response = self.get_attribute('terms', sort=sort) if sort=='weight': self.cache['terms'] = response['terms'] return response['terms'] terms = property(get_terms) def get_urls(self, cache=True): """Get the urls for an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Results: A url document dict Example: >>> a = artist.Artist('the unicorns') >>> a.get_urls() {u'amazon_url': u'http://www.amazon.com/gp/search?ie=UTF8&keywords=The Unicorns&tag=httpechonecom-20&index=music', u'aolmusic_url': u'http://music.aol.com/artist/the-unicorns', u'itunes_url': u'http://itunes.com/TheUnicorns', u'lastfm_url': u'http://www.last.fm/music/The+Unicorns', u'mb_url': u'http://musicbrainz.org/artist/603c5f9f-492a-4f21-9d6f-1642a5dbea2d.html', u'myspace_url': u'http://www.myspace.com/iwasbornunicorn'} >>> """ if not (cache and ('urls' in self.cache)): response = self.get_attribute('urls') self.cache['urls'] = response['urls'] return self.cache['urls'] urls = property(get_urls) def get_video(self, results=15, start=0, cache=True): """Get a list of video documents found on the web related to an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. results (int): An integer number of results to return start (int): An integer starting value for the result set Returns: A list of video document dicts; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('the vapors') >>> a.get_video(results=1, start=2) [{u'date_found': u'2009-12-28T08:27:48', u'id': u'd02f9e6dc7904f70402d4676516286b9', u'image_url': u'http://i1.ytimg.com/vi/p6c0wOFL3Us/default.jpg', u'site': u'youtube', u'title': u'The Vapors-Turning Japanese (rectangular white vinyl promo)', u'url': u'http://youtube.com/watch?v=p6c0wOFL3Us'}] >>> """ if cache and ('video' in self.cache) and results==15 and start==0: return self.cache['video'] else: response = self.get_attribute('video', results=results, start=start) if results==15 and start==0: self.cache['video'] = ResultList(response['video'], 0, response['total']) return ResultList(response['video'], start, response['total']) video = property(get_video) def get_years_active(self, cache=True): """Get a list of years active dictionaries for an artist Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A list of years active dictionaries; list contains additional attributes 'start' and 'total' Example: >>> a = artist.Artist('yelle') >>> a.get_years_active() [{ start: 2005 }] >>> """ if cache and ('years_active' in self.cache): return self.cache['years_active'] else: response = self.get_attribute('profile', bucket=['years_active']) self.cache['years_active'] = response['artist']['years_active'] return response['artist']['years_active'] years_active = property(get_years_active) def get_doc_counts(self, cache=True): """ Get the number of related documents of various types for the artist. The types include audio, biographies, blogs, images, news, reviews, songs, videos. Note that these documents can be retrieved by calling artist.<document type>, for example, artist.biographies. Args: Kwargs: cache (bool): A boolean indicating whether or not the cached value should be used (if available). Defaults to True. Returns: A dictionary with one key for each document type, mapped to an integer count of documents. Example: >>> a = artist.Artist("The Kinks") >>> a.get_doc_counts() {u'audio': 194, u'biographies': 9, u'blogs': 379, u'images': 177, u'news': 84, u'reviews': 110, u'songs': 499, u'videos': 340} >>> """ if not cache or not ('doc_counts' in self.cache): response = self.get_attribute("profile", bucket='doc_counts') self.cache['doc_counts'] = response['artist']['doc_counts'] return self.cache['doc_counts'] doc_counts = property(get_doc_counts) def search(name=None, description=None, style=None, mood=None, start=0, \ results=15, buckets=None, limit=False, \ fuzzy_match=False, sort=None, max_familiarity=None, min_familiarity=None, \ max_hotttnesss=None, min_hotttnesss=None, test_new_things=None, rank_type=None, \ artist_start_year_after=None, artist_start_year_before=None,artist_end_year_after=None,artist_end_year_before=None): """Search for artists by name, description, or constraint. Args: Kwargs: name (str): the name of an artist description (str): A string describing the artist style (str): A string describing the style/genre of the artist mood (str): A string describing the mood of the artist start (int): An integer starting value for the result set results (int): An integer number of results to return buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets fuzzy_match (bool): A boolean indicating whether or not to search for similar sounding matches (only works with name) max_familiarity (float): A float specifying the max familiarity of artists to search for min_familiarity (float): A float specifying the min familiarity of artists to search for max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for artist_start_year_before (int): Returned artists will have started recording music before this year. artist_start_year_after (int): Returned artists will have started recording music after this year. artist_end_year_before (int): Returned artists will have stopped recording music before this year. artist_end_year_after (int): Returned artists will have stopped recording music after this year. rank_type (str): A string denoting the desired ranking for description searches, either 'relevance' or 'familiarity' Returns: A list of Artist objects Example: >>> results = artist.search(name='t-pain') >>> results [<artist - T-Pain>, <artist - T-Pain & Lil Wayne>, <artist - T Pain & 2 Pistols>, <artist - Roscoe Dash & T-Pain>, <artist - Tony Moxberg & T-Pain>, <artist - Flo-Rida (feat. T-Pain)>, <artist - Shortyo/Too Short/T-Pain>] >>> """ limit = str(limit).lower() fuzzy_match = str(fuzzy_match).lower() kwargs = locals() kwargs['bucket'] = buckets or [] del kwargs['buckets'] """Search for artists""" result = util.callm("%s/%s" % ('artist', 'search'), kwargs) return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']] def top_hottt(start=0, results=15, buckets = None, limit=False): """Get the top hotttest artists, according to The Echo Nest Args: Kwargs: results (int): An integer number of results to return start (int): An integer starting value for the result set buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets Returns: A list of hottt Artist objects Example: >>> hot_stuff = artist.top_hottt() >>> hot_stuff [<artist - Deerhunter>, <artist - Sufjan Stevens>, <artist - Belle and Sebastian>, <artist - Glee Cast>, <artist - Linkin Park>, <artist - Neil Young>, <artist - Jimmy Eat World>, <artist - Kanye West>, <artist - Katy Perry>, <artist - Bruno Mars>, <artist - Lady Gaga>, <artist - Rihanna>, <artist - Lil Wayne>, <artist - Jason Mraz>, <artist - Green Day>] >>> """ buckets = buckets or [] kwargs = {} if start: kwargs['start'] = start if results: kwargs['results'] = results if buckets: kwargs['bucket'] = buckets if limit: kwargs['limit'] = 'true' """Get top hottt artists""" result = util.callm("%s/%s" % ('artist', 'top_hottt'), kwargs) return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']] def top_terms(results=15): """Get a list of the top overall terms Args: Kwargs: results (int): An integer number of results to return Returns: A list of term document dicts Example: >>> terms = artist.top_terms(results=5) >>> terms [{u'frequency': 1.0, u'name': u'rock'}, {u'frequency': 0.99054710039307992, u'name': u'electronic'}, {u'frequency': 0.96131624654034398, u'name': u'hip hop'}, {u'frequency': 0.94358477322411127, u'name': u'jazz'}, {u'frequency': 0.94023302416455468, u'name': u'pop rock'}] >>> """ kwargs = {} if results: kwargs['results'] = results """Get top terms""" result = util.callm("%s/%s" % ('artist', 'top_terms'), kwargs) return result['response']['terms'] def list_terms(type): """Get a list of best terms to use with search Args: Kwargs: type (str): the type of term to return, either 'mood' or 'style' Example: >>> best_terms = artist.list_terms('mood') >>> best_terms [{u'name': u'aggressive'}, {u'name': u'ambient'}, {u'name': u'angry'}, {u'name': u'angst-ridden'}, {u'name': u'bouncy'}, {u'name': u'calming'}, {u'name': u'carefree'}, etc.] """ kwargs = {'type': type} result = util.callm("%s/%s" % ('artist', 'list_terms'), kwargs) return result['response']['terms'] def list_genres(): """Get a list of best genres to use with genre-radio playlisting Args: Example: >>> best_terms = artist.list_genres() >>> best_terms [{u'name': u'pop'}, {u'name': u'rock'}, {u'name': u'country'}, """ kwargs = {} result = util.callm("%s/%s" % ('artist', 'list_genres'), kwargs) return result['response']['genres'] def similar(names=None, ids=None, start=0, results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None, max_hotttnesss=None, min_hotttnesss=None, seed_catalog=None,artist_start_year_before=None, \ artist_start_year_after=None,artist_end_year_before=None,artist_end_year_after=None): """Return similar artists to this one Args: Kwargs: ids (str/list): An artist id or list of ids names (str/list): An artist name or list of names results (int): An integer number of results to return buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets start (int): An integer starting value for the result set max_familiarity (float): A float specifying the max familiarity of artists to search for min_familiarity (float): A float specifying the min familiarity of artists to search for max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for seed_catalog (str): A string specifying the catalog similar artists are restricted to Returns: A list of similar Artist objects Example: >>> some_dudes = [artist.Artist('weezer'), artist.Artist('radiohead')] >>> some_dudes [<artist - Weezer>, <artist - Radiohead>] >>> sims = artist.similar(ids=[art.id for art in some_dudes], results=5) >>> sims [<artist - The Smashing Pumpkins>, <artist - Biffy Clyro>, <artist - Death Cab for Cutie>, <artist - Jimmy Eat World>, <artist - Nerf Herder>] >>> """ buckets = buckets or [] kwargs = {} if ids: if not isinstance(ids, list): ids = [ids] kwargs['id'] = ids if names: if not isinstance(names, list): names = [names] kwargs['name'] = names if max_familiarity is not None: kwargs['max_familiarity'] = max_familiarity if min_familiarity is not None: kwargs['min_familiarity'] = min_familiarity if max_hotttnesss is not None: kwargs['max_hotttnesss'] = max_hotttnesss if min_hotttnesss is not None: kwargs['min_hotttnesss'] = min_hotttnesss if seed_catalog is not None: kwargs['seed_catalog'] = seed_catalog if start: kwargs['start'] = start if results: kwargs['results'] = results if buckets: kwargs['bucket'] = buckets if limit: kwargs['limit'] = 'true' if artist_start_year_before: kwargs['artist_start_year_before'] = artist_start_year_before if artist_start_year_after: kwargs['artist_start_year_after'] = artist_start_year_after if artist_end_year_before: kwargs['artist_end_year_before'] = artist_end_year_before if artist_end_year_after: kwargs['artist_end_year_after'] = artist_end_year_after result = util.callm("%s/%s" % ('artist', 'similar'), kwargs) return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']] def extract(text='', start=0, results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None, max_hotttnesss=None, min_hotttnesss=None): """Extract artist names from a block of text. Args: Kwargs: text (str): The text to extract artists from start (int): An integer starting value for the result set results (int): An integer number of results to return buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets max_familiarity (float): A float specifying the max familiarity of artists to search for min_familiarity (float): A float specifying the min familiarity of artists to search for max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for Returns: A list of Artist objects Example: >>> results = artist.extract(text='i saw beyonce at burger king, she was eatin, she was eatin') >>> results >>> """ buckets = buckets or [] kwargs = {} kwargs['text'] = text if max_familiarity is not None: kwargs['max_familiarity'] = max_familiarity if min_familiarity is not None: kwargs['min_familiarity'] = min_familiarity if max_hotttnesss is not None: kwargs['max_hotttnesss'] = max_hotttnesss if min_hotttnesss is not None: kwargs['min_hotttnesss'] = min_hotttnesss if start: kwargs['start'] = start if results: kwargs['results'] = results if buckets: kwargs['bucket'] = buckets if limit: kwargs['limit'] = 'true' result = util.callm("%s/%s" % ('artist', 'extract'), kwargs) return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']] def suggest(q='', results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None, max_hotttnesss=None, min_hotttnesss=None): """Suggest artists based upon partial names. Args: Kwargs: q (str): The text to suggest artists from results (int): An integer number of results to return buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets max_familiarity (float): A float specifying the max familiarity of artists to search for min_familiarity (float): A float specifying the min familiarity of artists to search for max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for Returns: A list of Artist objects Example: >>> results = artist.suggest(text='rad') >>> results >>> """ buckets = buckets or [] kwargs = {} kwargs['q'] = q if max_familiarity is not None: kwargs['max_familiarity'] = max_familiarity if min_familiarity is not None: kwargs['min_familiarity'] = min_familiarity if max_hotttnesss is not None: kwargs['max_hotttnesss'] = max_hotttnesss if min_hotttnesss is not None: kwargs['min_hotttnesss'] = min_hotttnesss if results: kwargs['results'] = results if buckets: kwargs['bucket'] = buckets if limit: kwargs['limit'] = 'true' result = util.callm("%s/%s" % ('artist', 'suggest'), kwargs) return [Artist(**util.fix(a_dict)) for a_dict in result['response']['artists']]
/remix-2.4.0.tar.gz/remix-2.4.0/pyechonest/pyechonest/artist.py
0.756717
0.199055
artist.py
pypi
import urllib2 try: import json except ImportError: import simplejson as json import hashlib from proxies import TrackProxy import util import time # Seconds to wait for asynchronous track/upload or track/analyze jobs to complete. DEFAULT_ASYNC_TIMEOUT = 60 class Track(TrackProxy): """ Represents an audio file and its analysis from The Echo Nest. All public methods in this module return Track objects. Depending on the information available, a Track may have some or all of the following attributes: acousticness float: confidence the track is "acoustic" (0.0 to 1.0) analysis_url URL to retrieve the complete audio analysis (time expiring) analyzer_version str: e.g. '3.01a' artist str or None: artist name artist_id Echo Nest ID of artist, if known danceability float: relative danceability (0.0 to 1.0) duration float: length of track in seconds energy float: relative energy (0.0 to 1.0) id str: Echo Nest Track ID, e.g. 'TRTOBXJ1296BCDA33B' key int: between 0 (key of C) and 11 (key of B flat) inclusive liveness float: confidence the track is "live" (0.0 to 1.0) loudness float: overall loudness in decibels (dB) md5 str: 32-character checksum of the original audio file, if available mode int: 0 (major) or 1 (minor) song_id The Echo Nest song ID for the track, if known speechiness float: likelihood the track contains speech (0.0 to 1.0) status str: analysis status, e.g. 'complete' tempo float: overall BPM (beats per minute) time_signature beats per measure (e.g. 3, 4, 5, 7) title str or None: song title valence float: a range from negative to positive emotional content (0.0 to 1.0) The following attributes are available only after calling Track.get_analysis(): analysis_channels int: the number of audio channels used during analysis analysis_sample_rate int: the sample rate used during analysis bars list of dicts: timing of each measure beats list of dicts: timing of each beat codestring ENMFP code string code_version version of ENMFP code generator decoder audio decoder used by the analysis (e.g. ffmpeg) echoprintstring fingerprint string using Echoprint (http://echoprint.me) echoprint_version version of Echoprint code generator end_of_fade_in float: time in seconds track where fade-in ends key_confidence float: confidence that key detection was accurate meta dict: other track metainfo (bitrate, album, genre, etc.) mode_confidence float: confidence that mode detection was accurate num_samples int: total samples in the decoded track offset_seconds unused, always 0 sample_md5 str: 32-character checksum of the decoded audio file samplerate the audio sample rate detected in the file sections list of dicts: larger sections of song (chorus, bridge, solo, etc.) segments list of dicts: timing, pitch, loudness and timbre for each segment start_of_fade_out float: time in seconds where fade out begins synchstring string providing synchronization points throughout the track synch_version version of the synch string algorithm tatums list of dicts: the smallest metrical unit (subdivision of a beat) tempo_confidence float: confidence that tempo detection was accurate time_signature_confidence float: confidence that time_signature detection was accurate Each bar, beat, section, segment and tatum has a start time, a duration, and a confidence, in addition to whatever other data is given. Examples: >>> t = track.track_from_id('TRJSEBQ1390EC0B548') >>> t <track - Dark Therapy> >>> t = track.track_from_md5('96fa0180d225f14e9f8cbfffbf5eb81d') >>> t <track - Spoonful - Live At Winterland> >>> >>> t = track.track_from_filename('Piano Man.mp3') >>> t.meta AttributeError: 'Track' object has no attribute 'meta' >>> t.get_analysis() >>> t.meta {u'album': u'Piano Man', u'analysis_time': 8.9029500000000006, u'analyzer_version': u'3.1.3', u'artist': u'Billy Joel', u'bitrate': 160, u'detailed_status': u'OK', u'filename': u'/tmp/tmphrBQL9/fd2b524958548e7ecbaf758fb675fab1.mp3', u'genre': u'Soft Rock', u'sample_rate': 44100, u'seconds': 339, u'status_code': 0, u'timestamp': 1369400122, u'title': u'Piano Man'} >>> """ def __repr__(self): try: return "<%s - %s>" % (self._object_type.encode('utf-8'), self.title.encode('utf-8')) except AttributeError: # the title is None return "< Track >" def __str__(self): return self.title.encode('utf-8') def get_analysis(self): """ Retrieve the detailed analysis for the track, if available. Raises Exception if unable to create the detailed analysis. """ if self.analysis_url: try: # Try the existing analysis_url first. This expires shortly # after creation. try: json_string = urllib2.urlopen(self.analysis_url).read() except urllib2.HTTPError: # Probably the analysis_url link has expired. Refresh it. param_dict = dict(id = self.id) new_track = _profile(param_dict, DEFAULT_ASYNC_TIMEOUT) if new_track and new_track.analysis_url: self.analysis_url = new_track.analysis_url json_string = urllib2.urlopen(self.analysis_url).read() else: raise Exception("Failed to create track analysis.") analysis = json.loads(json_string) analysis_track = analysis.pop('track', {}) self.__dict__.update(analysis) self.__dict__.update(analysis_track) except Exception: #pylint: disable=W0702 # No detailed analysis found. raise Exception("Failed to create track analysis.") else: raise Exception("Failed to create track analysis.") def _wait_for_pending_track(trid, timeout): status = 'pending' param_dict = {'id': trid} param_dict['format'] = 'json' param_dict['bucket'] = 'audio_summary' start_time = time.time() end_time = start_time + timeout # counter for seconds to wait before checking track profile again. timeout_counter = 3 while status == 'pending' and time.time() < end_time: time.sleep(timeout_counter) result = util.callm('track/profile', param_dict) status = result['response']['track']['status'].lower() # Slowly increment to wait longer each time. timeout_counter += timeout_counter / 2 return result def _track_from_response(result, timeout): """ This is the function that actually creates the track object """ response = result['response'] status = response['track']['status'].lower() if status == 'pending': # Need to wait for async upload or analyze call to finish. result = _wait_for_pending_track(response['track']['id'], timeout) response = result['response'] status = response['track']['status'].lower() if not status == 'complete': track_id = response['track']['id'] if status == 'pending': raise Exception('%s: the operation didn\'t complete before the timeout (%d secs)' % (track_id, timeout)) else: raise Exception('%s: there was an error analyzing the track, status: %s' % (track_id, status)) else: # track_properties starts as the response dictionary. track_properties = response['track'] # 'id' and 'md5' are separated to construct the Track object. identifier = track_properties.pop('id') md5 = track_properties.pop('md5', None) # tracks from song api calls will not have an md5 # Pop off the audio_summary dict and make those keys attributes # of the Track. This includes things like tempo, energy, and loudness. track_properties.update(track_properties.pop('audio_summary')) return Track(identifier, md5, track_properties) def _upload(param_dict, timeout, data): """ Calls upload either with a local audio file, or a url. Returns a track object. """ param_dict['format'] = 'json' param_dict['wait'] = 'true' param_dict['bucket'] = 'audio_summary' result = util.callm('track/upload', param_dict, POST = True, socket_timeout = 300, data = data) return _track_from_response(result, timeout) def _profile(param_dict, timeout): param_dict['format'] = 'json' param_dict['bucket'] = 'audio_summary' result = util.callm('track/profile', param_dict) return _track_from_response(result, timeout) """ Below are convenience functions for creating Track objects, you should use them """ def _track_from_data(audio_data, filetype, timeout): param_dict = {} param_dict['filetype'] = filetype return _upload(param_dict, timeout, audio_data) def track_from_file(file_object, filetype, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False): """ Create a track object from a file-like object. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: file_object: a file-like Python object filetype: the file type. Supported types include mp3, ogg, wav, m4a, mp4, au force_upload: skip the MD5 shortcut path, force an upload+analysis Example: >>> f = open("Miaow-01-Tempered-song.mp3") >>> t = track.track_from_file(f, 'mp3') >>> t < Track > >>> """ if not force_upload: try: # Check if this file has already been uploaded. # This is much faster than uploading. md5 = hashlib.md5(file_object.read()).hexdigest() return track_from_md5(md5) except util.EchoNestAPIError: # Fall through to do a fresh upload. pass file_object.seek(0) return _track_from_data(file_object.read(), filetype, timeout) def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False): """ Create a track object from a filename. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: filename: A string containing the path to the input file. filetype: A string indicating the filetype; Defaults to None (type determined by file extension). force_upload: skip the MD5 shortcut path, force an upload+analysis Example: >>> t = track.track_from_filename("Miaow-01-Tempered-song.mp3") >>> t < Track > >>> """ filetype = filetype or filename.split('.')[-1] file_object = open(filename, 'rb') result = track_from_file(file_object, filetype, timeout, force_upload) file_object.close() return result def track_from_url(url, timeout=DEFAULT_ASYNC_TIMEOUT): """ Create a track object from a public http URL. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: url: A string giving the URL to read from. This must be on a public machine accessible by HTTP. Example: >>> t = track.track_from_url("http://www.miaowmusic.com/mp3/Miaow-01-Tempered-song.mp3") >>> t < Track > >>> """ param_dict = dict(url = url) return _upload(param_dict, timeout, data=None) def track_from_id(identifier, timeout=DEFAULT_ASYNC_TIMEOUT): """ Create a track object from an Echo Nest track ID. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: identifier: A string containing the ID of a previously analyzed track. Example: >>> t = track.track_from_id("TRWFIDS128F92CC4CA") >>> t <track - Let The Spirit> >>> """ param_dict = dict(id = identifier) return _profile(param_dict, timeout) def track_from_md5(md5, timeout=DEFAULT_ASYNC_TIMEOUT): """ Create a track object from an md5 hash. NOTE: Does not create the detailed analysis for the Track. Call Track.get_analysis() for that. Args: md5: A string 32 characters long giving the md5 checksum of a track already analyzed. Example: >>> t = track.track_from_md5('b8abf85746ab3416adabca63141d8c2d') >>> t <track - Neverwas Restored (from Neverwas Soundtrack)> >>> """ param_dict = dict(md5 = md5) return _profile(param_dict, timeout)
/remix-2.4.0.tar.gz/remix-2.4.0/pyechonest/pyechonest/track.py
0.638835
0.402921
track.py
pypi
import util from proxies import PlaylistProxy from song import Song import catalog import logging logger = logging.getLogger(__name__) def basic(type='artist-radio', artist_id=None, artist=None, song_id=None, song=None, track_id=None, dmca=False, results=15, buckets=None, limit=False,genres=None,): """Get a basic playlist Args: Kwargs: type (str): a string representing the playlist type ('artist-radio' or 'song-radio') artist_id (str): the artist_id to seed the playlist artist (str): the name of an artist to seed the playlist song_id (str): a song_id to seed the playlist song (str): the name of a song to seed the playlist track_id (str): the name of a track to seed the playlist dmca (bool): make the playlist dmca-compliant results (int): desired length of the playlist buckets (list): A list of strings specifying which buckets to retrieve limit (bool): Whether results should be restricted to any idspaces given in the buckets parameter """ limit = str(limit).lower() dmca = str(dmca).lower() kwargs = locals() kwargs['bucket'] = kwargs['buckets'] del kwargs['buckets'] kwargs['genre'] = kwargs['genres'] del kwargs['genres'] result = util.callm("%s/%s" % ('playlist', 'basic'), kwargs) return [Song(**util.fix(s_dict)) for s_dict in result['response']['songs']] def static(type='artist', artist_pick='song_hotttnesss-desc', variety=.5, artist_id=None, artist=None, song_id=None, track_id=None, description=None, style=None, mood=None, results=15, max_tempo=None, min_tempo=None, max_duration=None, min_duration=None, max_loudness=None, min_loudness=None, max_danceability=None, min_danceability=None, max_energy=None, min_energy=None, artist_max_familiarity=None, artist_min_familiarity=None, artist_max_hotttnesss=None, artist_min_hotttnesss=None, song_max_hotttnesss=None, song_min_hotttnesss=None, min_longitude=None, max_longitude=None, min_latitude=None, max_latitude=None, adventurousness=0.2, mode=None, key=None, buckets=None, sort=None, limit=False, seed_catalog=None, source_catalog=None, rank_type=None, test_new_things=None, artist_start_year_after=None, artist_start_year_before=None, artist_end_year_after=None, artist_end_year_before=None, dmca=False, distribution=None, song_type=None, genres=None): """Get a static playlist Args: Kwargs: type (str): a string representing the playlist type ('artist', 'artist-radio', ...) artist_pick (str): How songs should be chosen for each artist variety (float): A number between 0 and 1 specifying the variety of the playlist artist_id (str): the artist_id artist (str): the name of an artist song_id (str): the song_id track_id (str): the track id description (str): A string describing the artist and song style (str): A string describing the style/genre of the artist and song mood (str): A string describing the mood of the artist and song results (int): An integer number of results to return max_tempo (float): The max tempo of song results min_tempo (float): The min tempo of song results max_duration (float): The max duration of song results min_duration (float): The min duration of song results max_loudness (float): The max loudness of song results min_loudness (float): The min loudness of song results artist_max_familiarity (float): A float specifying the max familiarity of artists to search for artist_min_familiarity (float): A float specifying the min familiarity of artists to search for artist_max_hotttnesss (float): A float specifying the max hotttnesss of artists to search for artist_min_hotttnesss (float): A float specifying the max hotttnesss of artists to search for song_max_hotttnesss (float): A float specifying the max hotttnesss of songs to search for song_min_hotttnesss (float): A float specifying the max hotttnesss of songs to search for max_energy (float): The max energy of song results min_energy (float): The min energy of song results max_danceability (float): The max danceability of song results min_danceability (float): The min danceability of song results mode (int): 0 or 1 (minor or major) key (int): 0-11 (c, c-sharp, d, e-flat, e, f, f-sharp, g, a-flat, a, b-flat, b) max_latitude (float): A float specifying the max latitude of artists to search for min_latitude (float): A float specifying the min latitude of artists to search for max_longitude (float): A float specifying the max longitude of artists to search for min_longitude (float): A float specifying the min longitude of artists to search for adventurousness (float): A float ranging from 0 for old favorites to 1.0 for unheard music according to a seed_catalog sort (str): A string indicating an attribute and order for sorting the results buckets (list): A list of strings specifying which buckets to retrieve limit (bool): A boolean indicating whether or not to limit the results to one of the id spaces specified in buckets seed_catalog (str or Catalog): An Artist Catalog object or Artist Catalog id to use as a seed source_catalog (str or Catalog): A Catalog object or catalog id rank_type (str): A string denoting the desired ranking for description searches, either 'relevance' or 'familiarity' artist_start_year_before (int): Returned song's artists will have started recording music before this year. artist_start_year_after (int): Returned song's artists will have started recording music after this year. artist_end_year_before (int): Returned song's artists will have stopped recording music before this year. artist_end_year_after (int): Returned song's artists will have stopped recording music after this year. distribution (str): Affects the range of artists returned and how many songs each artist will have in the playlist relative to how similar they are to the seed. (wandering, focused) song_type (str): A string or list of strings of the type of songs allowed. The only valid song type at the moment is 'christmas'. Valid formats are 'song_type', 'song_type:true', 'song_type:false', or 'song_type:any'. Returns: A list of Song objects Example: >>> p = playlist.static(type='artist-radio', artist=['ida maria', 'florence + the machine']) >>> p [<song - Pickpocket>, <song - Self-Taught Learner>, <song - Maps>, <song - Window Blues>, <song - That's Not My Name>, <song - My Lover Will Go>, <song - Home Sweet Home>, <song - Stella & God>, <song - Don't You Want To Share The Guilt?>, <song - Forget About It>, <song - Dull Life>, <song - This Trumpet In My Head>, <song - Keep Your Head>, <song - One More Time>, <song - Knights in Mountain Fox Jackets>] >>> """ limit = str(limit).lower() if seed_catalog and isinstance(seed_catalog, catalog.Catalog): seed_catalog = seed_catalog.id if source_catalog and isinstance(source_catalog, catalog.Catalog): source_catalog = source_catalog.id dmca = str(dmca).lower() kwargs = locals() kwargs['bucket'] = kwargs['buckets'] or [] del kwargs['buckets'] kwargs['genre'] = kwargs['genres'] del kwargs['genres'] result = util.callm("%s/%s" % ('playlist', 'static'), kwargs) return [Song(**util.fix(s_dict)) for s_dict in result['response']['songs']] class Playlist(PlaylistProxy): """ A Dynamic Playlist object. http://developer.echonest.com/docs/v4/playlist.html#dynamic-create Attributes: Example: """ def __init__( self, session_id=None, type=None, artist_pick=None, variety=None, artist_id=None, artist=None, song_id=None, track_id=None, description=None, style=None, mood=None, max_tempo=None, min_tempo=None, max_duration=None, min_duration=None, max_loudness=None, min_loudness=None, max_danceability=None, min_danceability=None, max_energy=None, min_energy=None, artist_max_familiarity=None, artist_min_familiarity=None, artist_max_hotttnesss=None, artist_min_hotttnesss=None, song_max_hotttnesss=None, song_min_hotttnesss=None, min_longitude=None, max_longitude=None, min_latitude=None, max_latitude=None, adventurousness=None, mode=None, key=None, buckets=None, sort=None, limit=False, seed_catalog=None, source_catalog=None, rank_type=None, test_new_things=None, artist_start_year_after=None, artist_start_year_before=None, artist_end_year_after=None, artist_end_year_before=None, dmca=False, distribution=None, song_type=None, session_catalog=None,genres=None,): limit = str(limit).lower() dmca = str(dmca).lower() if isinstance(seed_catalog, catalog.Catalog): seed_catalog = seed_catalog.id super(Playlist, self).__init__( session_id=session_id, type=type, artist_pick=artist_pick, variety=variety, artist_id=artist_id, artist=artist, song_id=song_id, track_id=track_id, description=description, style=style, mood=mood, max_tempo=max_tempo, min_tempo=min_tempo, max_duration=max_duration, min_duration=min_duration, max_loudness=max_loudness, min_loudness=min_loudness, max_danceability=max_danceability, min_danceability=min_danceability, max_energy=max_energy, min_energy=min_energy, artist_max_familiarity=artist_max_familiarity, artist_min_familiarity=artist_min_familiarity, artist_max_hotttnesss=artist_max_hotttnesss, artist_min_hotttnesss=artist_min_hotttnesss, song_max_hotttnesss=song_max_hotttnesss, song_min_hotttnesss=song_min_hotttnesss, min_longitude=min_longitude, max_longitude=max_longitude, min_latitude=min_latitude, max_latitude=max_latitude, adventurousness=adventurousness, mode=mode, key=key, buckets=buckets, sort=sort, limit=limit, seed_catalog=seed_catalog, source_catalog=source_catalog, rank_type=rank_type, test_new_things=test_new_things, artist_start_year_after=artist_start_year_after, artist_start_year_before=artist_start_year_before, artist_end_year_after=artist_end_year_after, artist_end_year_before=artist_end_year_before, dmca=dmca, distribution=distribution, song_type=song_type, session_catalog=session_catalog, genres=genres ) def __repr__(self): return "<Dynamic Playlist - %s>" % self.session_id.encode('utf-8') def get_next_songs(self, results=None, lookahead=None): response = self.get_attribute( method='next', session_id=self.session_id, results=results, lookahead=lookahead ) self.cache['songs'] = response['songs'] self.cache['lookahead'] = response['lookahead'] if len(self.cache['songs']): songs = self.cache['songs'][:] songs = [Song(**util.fix(song)) for song in songs] return songs else: return None def get_current_songs(self): if not 'songs' in self.cache: self.get_next_songs(results=1) if len(self.cache['songs']): songs = self.cache['songs'][:] songs = [Song(**util.fix(song)) for song in songs] return songs else: return None def get_lookahead_songs(self): if not 'lookahead' in self.cache: return None if len(self.cache['lookahead']): lookahead = self.cache['lookahead'][:] lookahead = [Song(**util.fix(song)) for song in lookahead] return lookahead else: return None songs = property(get_current_songs) def info(self): return self.get_attribute("info", session_id=self.session_id) def delete(self): self.get_attribute("delete", session_id=self.session_id) return True def restart( self, type=None, artist_pick=None, variety=None, artist_id=None, artist=None, song_id=None, track_id=None, description=None, style=None, mood=None, max_tempo=None, min_tempo=None, max_duration=None, min_duration=None, max_loudness=None, min_loudness=None, max_danceability=None, min_danceability=None, max_energy=None, min_energy=None, artist_max_familiarity=None, artist_min_familiarity=None, artist_max_hotttnesss=None, artist_min_hotttnesss=None, song_max_hotttnesss=None, song_min_hotttnesss=None, min_longitude=None, max_longitude=None, min_latitude=None, max_latitude=None, adventurousness=None, mode=None, key=None, buckets=None, sort=None, limit=False, seed_catalog=None, source_catalog=None, rank_type=None, test_new_things=None, artist_start_year_after=None, artist_start_year_before=None, artist_end_year_after=None, artist_end_year_before=None, dmca=False, distribution=None, song_type=None, genres=None, ): limit = str(limit).lower() dmca = str(dmca).lower() if isinstance(seed_catalog, catalog.Catalog): seed_catalog = seed_catalog.id return self.get_attribute( method='restart', session_id=self.session_id, type=type, artist_pick=artist_pick, variety=variety, artist_id=artist_id, artist=artist, song_id=song_id, track_id=track_id, description=description, style=style, mood=mood, max_tempo=max_tempo, min_tempo=min_tempo, max_duration=max_duration, min_duration=min_duration, max_loudness=max_loudness, min_loudness=min_loudness, max_danceability=max_danceability, min_danceability=min_danceability, max_energy=max_energy, min_energy=min_energy, artist_max_familiarity=artist_max_familiarity, artist_min_familiarity=artist_min_familiarity, artist_max_hotttnesss=artist_max_hotttnesss, artist_min_hotttnesss=artist_min_hotttnesss, song_max_hotttnesss=song_max_hotttnesss, song_min_hotttnesss=song_min_hotttnesss, min_longitude=min_longitude, max_longitude=max_longitude, min_latitude=min_latitude, max_latitude=max_latitude, adventurousness=adventurousness, mode=mode, key=key, bucket=buckets, sort=sort, limit=limit, seed_catalog=seed_catalog, source_catalog=source_catalog, rank_type=rank_type, test_new_things=test_new_things, artist_start_year_after=artist_start_year_after, artist_start_year_before=artist_start_year_before, artist_end_year_after=artist_end_year_after, artist_end_year_before=artist_end_year_before, dmca=dmca, distribution=distribution, song_type=song_type, genres=genres, ) def steer( self, max_tempo=None, min_tempo=None, target_tempo=None, max_duration=None, min_duration=None, target_duration=None, max_loudness=None, min_loudness=None, target_loudness=None, max_danceability=None, min_danceability=None, target_danceability=None, max_energy=None, min_energy=None, target_energy=None, max_artist_familiarity=None, min_artist_familiarity=None, target_artist_familiarity=None, max_artist_hotttnesss=None, min_artist_hotttnesss=None, target_artist_hotttnesss=None, max_song_hotttnesss=None, min_song_hotttnesss=None, target_song_hotttnesss=None, more_like_this=None, less_like_this=None, adventurousness=None, variety=None, description=None, style=None, mood=None, song_type=None, genres=None ): response = self.get_attribute( method='steer', session_id=self.session_id, max_tempo=max_tempo, min_tempo=min_tempo, target_tempo=target_tempo, max_duration=max_duration, min_duration=min_duration, target_duration=target_duration, max_loudness=max_loudness, min_loudness=min_loudness, target_loudness=target_loudness, max_danceability=max_danceability, min_danceability=min_danceability, target_danceability=target_danceability, max_energy=max_energy, min_energy=min_energy, target_energy=target_energy, max_artist_familiarity=max_artist_familiarity, min_artist_familiarity=min_artist_familiarity, target_artist_familiarity=target_artist_familiarity, max_artist_hotttnesss=max_artist_hotttnesss, min_artist_hotttnesss=min_artist_hotttnesss, target_artist_hotttnesss=target_artist_hotttnesss, max_song_hotttnesss=max_song_hotttnesss, min_song_hotttnesss=min_song_hotttnesss, target_song_hotttnesss=target_song_hotttnesss, more_like_this=more_like_this, less_like_this=less_like_this, adventurousness=adventurousness, variety=variety, description=description, style=style, mood=mood, song_type=song_type, genres=genres, ) self.cache['lookahead'] = [] return True def feedback( self, ban_artist=None, ban_song=None, skip_song=None, favorite_artist=None, favorite_song=None, play_song=None, unplay_song=None, rate_song=None, invalidate_song=None, invalidate_artist=None, ): response = self.get_attribute( session_id=self.session_id, method='feedback', ban_artist=ban_artist, ban_song=ban_song, skip_song=skip_song, favorite_artist=favorite_artist, favorite_song=favorite_song, play_song=play_song, unplay_song=unplay_song, rate_song=rate_song, invalidate_song=invalidate_song, invalidate_artist=invalidate_artist, ) self.cache['lookahead'] = [] return True class DeprecationHelper(object): def __init__(self, new_target): self.new_target = new_target def _warn(self): from warnings import warn warn("BetaPlaylist is no longer in Beta and has been moved to Playlist", DeprecationWarning, stacklevel=2) logger.warn("BetaPlaylist is no longer in Beta and has been moved to Playlist") def __call__(self, *args, **kwargs): self._warn() return self.new_target(*args, **kwargs) def __getattr__(self, attr): self._warn() return getattr(self.new_target, attr) BetaPlaylist = DeprecationHelper(Playlist)
/remix-2.4.0.tar.gz/remix-2.4.0/pyechonest/pyechonest/playlist.py
0.740362
0.229449
playlist.py
pypi
import numpy as np from copy import deepcopy from utils import rows FUSION_INTERVAL = .06 # This is what we use in the analyzer AVG_PEAK_OFFSET = 0.025 # Estimated time between onset and peak of segment. def evaluate_distance(mat1, mat2): return np.linalg.norm(mat1.flatten() - mat2.flatten()) def timbre_whiten(mat): if rows(mat) < 2: return mat m = np.zeros((rows(mat), 12), dtype=np.float32) m[:,0] = mat[:,0] - np.mean(mat[:,0],0) m[:,0] = m[:,0] / np.std(m[:,0],0) m[:,1:] = mat[:,1:] - np.mean(mat[:,1:].flatten(),0) m[:,1:] = m[:,1:] / np.std(m[:,1:].flatten(),0) # use this! return m def get_central(analysis, member='segments'): """ Returns a tuple: 1) copy of the members (e.g. segments) between end_of_fade_in and start_of_fade_out. 2) the index of the first retained member. """ def central(s): return analysis.end_of_fade_in <= s.start and (s.start + s.duration) < analysis.start_of_fade_out members = getattr(analysis, member) ret = filter(central, members[:]) index = members.index(ret[0]) if ret else 0 return ret, index def get_mean_offset(segments, markers): if segments == markers: return 0 index = 0 offsets = [] try: for marker in markers: while segments[index].start < marker.start + FUSION_INTERVAL: offset = abs(marker.start - segments[index].start) if offset < FUSION_INTERVAL: offsets.append(offset) index += 1 except IndexError, e: pass return np.average(offsets) if offsets else AVG_PEAK_OFFSET def resample_features(data, rate='tatums', feature='timbre'): """ Resample segment features to a given rate within fade boundaries. @param data: analysis object. @param rate: one of the following: segments, tatums, beats, bars. @param feature: either timbre or pitch. @return A dictionary including a numpy matrix of size len(rate) x 12, a rate, and an index """ ret = {'rate': rate, 'index': 0, 'cursor': 0, 'matrix': np.zeros((1, 12), dtype=np.float32)} segments, ind = get_central(data.analysis, 'segments') markers, ret['index'] = get_central(data.analysis, rate) if len(segments) < 2 or len(markers) < 2: return ret # Find the optimal attack offset meanOffset = get_mean_offset(segments, markers) # Make a copy for local use tmp_markers = deepcopy(markers) # Apply the offset for m in tmp_markers: m.start -= meanOffset if m.start < 0: m.start = 0 # Allocate output matrix, give it alias mat for convenience. mat = ret['matrix'] = np.zeros((len(tmp_markers)-1, 12), dtype=np.float32) # Find the index of the segment that corresponds to the first marker f = lambda x: tmp_markers[0].start < x.start + x.duration index = (i for i,x in enumerate(segments) if f(x)).next() # Do the resampling try: for (i, m) in enumerate(tmp_markers): while segments[index].start + segments[index].duration < m.start + m.duration: dur = segments[index].duration if segments[index].start < m.start: dur -= m.start - segments[index].start C = min(dur / m.duration, 1) mat[i, 0:12] += C * np.array(getattr(segments[index], feature)) index += 1 C = min( (m.duration + m.start - segments[index].start) / m.duration, 1) mat[i, 0:12] += C * np.array(getattr(segments[index], feature)) except IndexError, e: pass # avoid breaking with index > len(segments) return ret
/remix-2.4.0.tar.gz/remix-2.4.0/examples/earworm/earworm_support.py
0.539469
0.653707
earworm_support.py
pypi
import numpy import os import random import time import echonest.remix.audio as audio usage = """ Usage: python cowbell.py <inputFilename> <outputFilename> <cowbellIntensity> <walkenIntensity> Example: python cowbell.py YouCanCallMeAl.mp3 YouCanCallMeCow.mp3 0.2 0.5 Reference: http://www.youtube.com/watch?v=ZhSkRHXTKlw """ # constants COWBELL_THRESHOLD = 0.85 COWBELL_OFFSET = -0.005 # samples soundsPath = "sounds/" cowbellSounds = map(lambda x: audio.AudioData(os.path.join(soundsPath, "cowbell%s.wav" % x), sampleRate=44100, numChannels=2), range(5)) walkenSounds = map(lambda x: audio.AudioData(os.path.join(soundsPath, "walken%s.wav" % x), sampleRate=44100, numChannels=2), range(16)) trill = audio.AudioData(os.path.join(soundsPath, "trill.wav"), sampleRate=44100, numChannels=2) def linear(input, in1, in2, out1, out2): return ((input-in1) / (in2-in1)) * (out2-out1) + out1 def exp(input, in1, in2, out1, out2, coeff): if (input <= in1): return out1 if (input >= in2): return out2 return pow( ((input-in1) / (in2-in1)) , coeff ) * (out2-out1) + out1 class Cowbell: def __init__(self, input_file): self.audiofile = audio.LocalAudioFile(input_file) self.audiofile.data *= linear(self.audiofile.analysis.loudness, -2, -12, 0.5, 1.5) * 0.75 def run(self, cowbell_intensity, walken_intensity, out): if cowbell_intensity != -1: self.cowbell_intensity = cowbell_intensity self.walken_intensity = walken_intensity t1 = time.time() sequence = self.sequence(cowbellSounds) print "Sequence and mixed in %g seconds" % (time.time() - t1) self.audiofile.encode(out) def sequence(self, chops): # add cowbells on the beats for beat in self.audiofile.analysis.beats: volume = linear(self.cowbell_intensity, 0, 1, 0.1, 0.3) # mix in cowbell on beat if self.cowbell_intensity == 1: self.mix(beat.start+COWBELL_OFFSET, seg=cowbellSounds[random.randint(0,1)], volume=volume) else: self.mix(beat.start+COWBELL_OFFSET, seg=cowbellSounds[random.randint(2,4)], volume=volume) # divide beat into quarters quarters = (numpy.arange(1,4) * beat.duration) / 4. + beat.start # mix in cowbell on quarters for quarter in quarters: volume = exp(random.random(), 0.5, 0.1, 0, self.cowbell_intensity, 0.8) * 0.3 pan = linear(random.random(), 0, 1, -self.cowbell_intensity, self.cowbell_intensity) if self.cowbell_intensity < COWBELL_THRESHOLD: self.mix(quarter+COWBELL_OFFSET, seg=cowbellSounds[2], volume=volume) else: randomCowbell = linear(random.random(), 0, 1, COWBELL_THRESHOLD, 1) if randomCowbell < self.cowbell_intensity: self.mix(start=quarter+COWBELL_OFFSET, seg=cowbellSounds[random.randint(0,1)], volume=volume) else: self.mix(start=quarter+COWBELL_OFFSET, seg=cowbellSounds[random.randint(2,4)], volume=volume) # add trills / walken on section changes for section in self.audiofile.analysis.sections[1:]: if random.random() > self.walken_intensity: sample = trill volume = 0.3 else: sample = walkenSounds[random.randint(0, len(walkenSounds)-1)] volume = 1.5 self.mix(start=section.start+COWBELL_OFFSET, seg=sample, volume=volume) def mix(self, start=None, seg=None, volume=0.3, pan=0.): # this assumes that the audios have the same frequency/numchannels startsample = int(start * self.audiofile.sampleRate) seg = seg[0:] seg.data *= (volume-(pan*volume), volume+(pan*volume)) # pan + volume if self.audiofile.data.shape[0] - startsample > seg.data.shape[0]: self.audiofile.data[startsample:startsample+len(seg.data)] += seg.data[0:] def main(inputFilename, outputFilename, cowbellIntensity, walkenIntensity ) : c = Cowbell(inputFilename) print 'cowbelling...' c.run(cowbellIntensity, walkenIntensity, outputFilename) if __name__ == '__main__': import sys try : inputFilename = sys.argv[1] outputFilename = sys.argv[2] cowbellIntensity = float(sys.argv[3]) walkenIntensity = float(sys.argv[4]) except : print usage sys.exit(-1) main(inputFilename, outputFilename, cowbellIntensity, walkenIntensity)
/remix-2.4.0.tar.gz/remix-2.4.0/examples/cowbell/cowbell.py
0.470493
0.173113
cowbell.py
pypi