Esempio n. 1
0
from importlib.metadata import version

import typer

from . import APP_NAME, console
from .styles import CustomHelpColorsCommand, CustomHelpColorsGroup

app = typer.Typer(
    name=APP_NAME,
    cls=CustomHelpColorsGroup,
    context_settings={"help_option_names": ["-h", "--help"]},
)


def version_callback(value: bool):
    if value:
        console.print(
            f"[bold green]{APP_NAME}[/bold green]: {version(APP_NAME)}")
        raise typer.Exit()


@app.callback()
def main(version: bool = typer.Option(
    False,
    "--version",
    callback=version_callback,
    is_eager=True,
    show_default=False,
    help="Display version information",
), ):
    pass
Esempio n. 2
0
# SOURCE https://python.plainenglish.io/how-to-create-a-cli-app-in-python-aea606509332

import typer
import os
from PIL import Image

cli = typer.Typer()


@cli.command()
def stats(filename: str):
	'''
	Show image info for FILENAME
	'''
	img = Image.open(filename)

	# Print properties
	typer.echo(f' Format:\t {img.format}')
	typer.echo(f'   Mode:\t {img.mode}')
	typer.echo(f'   Size:\t {img.size[0]} x {img.size[1]}')
	typer.echo(f'Palette:\t {img.palette}')
	typer.echo(f'Information:\t {img.info}')

@cli.command()
def statsdir(dirname: str):
	'''
	Show image info for a DIRECTORY
	'''

	images = os.listdir(dirname)
Esempio n. 3
0
File: cli.py Progetto: isratnisa/dgl
import typer
from ..pipeline import *
from ..model import *
from .config_cli import config_app
from .train_cli import train
from .export_cli import export

no_args_is_help = False
app = typer.Typer(no_args_is_help=no_args_is_help, add_completion=False)
app.add_typer(config_app, name="config", no_args_is_help=no_args_is_help)
app.command(help="Train the model", no_args_is_help=no_args_is_help)(train)
app.command(help="Export the python file from config", no_args_is_help=no_args_is_help)(export)

def main():
    app()

if __name__ == "__main__":
    app()
Esempio n. 4
0
"""

import re
from collections import Counter, OrderedDict

import typer
from Bio import SeqIO

from cupcake import version_callback
from cupcake import cupcake_logger as logger

rex_pbid = re.compile(r"(PB.\d+).(\d+)")


app = typer.Typer(
    name="cupcake.sequence.group_ORF_sequences", help="De-duplicate ORF FAA file."
)


def dedup_ORFs(faa_filename, output_prefix, is_pbid):

    seq_dict = OrderedDict()  # ORF seq --> list of IDs

    pbid_counter = Counter()  # PB.X  --> counter  (not used if is_pbid is False)

    for r in SeqIO.parse(open(faa_filename), "fasta"):
        s = str(r.seq).upper()
        if s not in seq_dict:
            seq_dict[s] = []
        seq_dict[s].append(r.id)
Esempio n. 5
0
from pathlib import Path
from typing import Optional, Union

import typer

from github_secrets.app import GithubSecretsApp

cli = typer.Typer()
app: GithubSecretsApp

VERBOSE_DOC = 'Show additional output useful for debugging'


@cli.callback(invoke_without_command=True)
def start_app(ctx: typer.Context):
    """
    Github Secrets CLI
    """
    global app
    app = GithubSecretsApp()
    if not app.config.settings.config_location.exists():
        app.save()


profile_cli = typer.Typer(
    help="Manage the profile for working with secrets. Multiple profiles "
    "are supported to manage secrets and authentication separately")


@profile_cli.command(name="create")
def create_profile(
Esempio n. 6
0
import typer as ty
from single import _enums as enums
from single.server import start as start_

app = ty.Typer(help="This is the command line frontend for the single server.")


@app.command()
def start(
    port: int = ty.Option(25000, help="The port to broadcast to."),
    logging_level: enums.LoggingLevel = ty.Option("INFO",
                                                  help="The logging level."),
) -> None:
    """Use this command to start the server."""
    start_(port, logging_level)


if __name__ == "__main__":
    app()
Esempio n. 7
0
from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware
from app.routes import views
from app.core import auth
import typer  # typerCli
from indexer.indexer import db  # db class

app = FastAPI()

appTyper = typer.Typer()

# Set all CORS enabled origins
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(auth.router)
app.include_router(views.router)


# si hay error de elasticsearch utilizar
# sudo sysctl -w vm.max_map_count=262144


# updateDB from CLI
@appTyper.command()
def updateDB(namefile: str, index: str):
Esempio n. 8
0
        return None


###############################################################################
# pyrolab Main App
#
# COMMANDS
# --------
# pyrolab up
# pyrolab down
# pyrolab reload
# pyrolab ps
# pyrolab --version
###############################################################################

app = typer.Typer()

print(
    f"PyroLab  Copyright © 2020-{date.today().year}  BYU CamachoLab, PyroLab Project Contributors"
)
print("This program comes with ABSOLUTELY NO WARRANTY.")
print(
    "This is free software, and you are welcome to redistribute it under certain conditions."
)
print(
    "See the documentation for more information (https://pyrolab.readthedocs.io)."
)
print()


def _version_callback(value: bool = True) -> None:
Esempio n. 9
0
import typer
from typing import Optional
from .. import config


# Program

program = typer.Typer()


# Helpers


def version(value: bool):
    if value:
        typer.echo(config.VERSION)
        raise typer.Exit()


# Command


@program.callback()
def program_main(
    version: Optional[bool] = typer.Option(None, "--version", callback=version)
):
    """Describe, extract, validate and transform tabular data."""
    pass
Esempio n. 10
0

class Listable(str, Enum):
    env = "environments"
    graph = "graphs"


_type_help = "The type of object to list"
_json_help = "Output the object as JSON Lines"
_organization_help = "The name of the Patterns organization to use"
_environment_help = "The name of the Patterns environment to use"

_organization_option = Option("", "--organization", "-o", help=_organization_help)
_environment_option = Option("", "--environment", "-e", help=_environment_help)

list_command = typer.Typer(name="list", help="List objects of a given type")


@list_command.command()
def graphs(
    organization: str = Option("", help=_organization_help),
    print_json: bool = Option(False, "--json", help=_json_help),
):
    """List graphs"""
    ids = IdLookup(organization_name=organization)
    with abort_on_error("Error listing graphs"):
        gs = list(paginated_graphs(ids.organization_id))
    _print_objects(gs, print_json)


@list_command.command()
import typer
from Bio import SeqIO
from bx.intervals import Interval, IntervalTree

from cupcake import version_callback
from cupcake.sequence import BED, BioReaders
from cupcake.sequence.GFF import collapseGFFReader


class index_base(int, Enum):
    zero = (0, )
    one = 1


app = typer.Typer(
    name="cupcake.targeted.calc_probe_hit_from_sam",
    help="Calculate Probe Hit from SAM alignment + probe BED",
)


def get_probe_hit(tree, gene_info, r, is_gtf=False):
    """
    Given a dict tree (from read_probe_bed) and a GMAP SAM record
    Go through each exon and find probes that hit it

    Return: (number of probes hit), (total number of bases overlapping with probes), (genes seen)
    """
    probes_seen = set()
    genes_seen = set()
    base_hit = 0
    if is_gtf:
        r.sID, r.segments = r.chr, r.ref_exons
Esempio n. 12
0
from pathlib import Path
from typing import List, Optional

import typer

from eve_esi_jobs import do_workorder
from eve_esi_jobs.models import EsiJob, EsiWorkOrder
from eve_esi_jobs.typer_cli.cli_helpers import (
    FormatChoices,
    report_finished_task,
    validate_input_path,
    validate_output_path,
)
from eve_esi_jobs.typer_cli.observer import EsiObserver

app = typer.Typer(help="""Do jobs and workorders.""")
logger = logging.getLogger(__name__)


@app.command()
def job(
    ctx: typer.Context,
    path_in: str = typer.Argument(..., help="Path to the job file."),
    path_out: str = typer.Argument(
        "./tmp", help="Path to be prepended to the job output path."),
    dry_run: bool = typer.Option(
        False,
        "-d",
        "--dry-run",
        help="""
Not implemented yet.
Esempio n. 13
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import os
import os.path
import sys
import typer
from typing import List

paths = lambda: (v.rstrip("/") for v in os.environ["PATH"].split(":"))
app = typer.Typer(help="""PATH editor utility.

Expected usages:

if {cli} exists /usr/local/bin; then TODO; fi

export PATH="$({cli} add /usr/local/bin --unique)"
""".format(cli=os.path.basename(sys.argv[0])))


@app.command(name="list", help="Display all entries in PATH")
def ls():
    for p in paths(): print(p)


@app.command(help="Fail any provided value is not in PATH")
def exists(values: List[str]):
    raise typer.Exit(len(set(v.rstrip("/") for v in values) - set(paths())))


@app.command(name="add", help="Add to the top of PATH provided values, and remove duplicates if asked")
Esempio n. 14
0
from rich.console import Console
from xvideos_dl import __version__
from xvideos_dl.xvideos_dl import (
    Process,
    download,
    get_videos_by_playlist_id,
    get_videos_from_play_page,
    get_videos_from_user_page,
    parse_playlist_id,
)

from . import constant as c

app = typer.Typer(
    name="xvideos-dl",
    help="CLI to download videos from https://xvideos.com",
    add_completion=False,
)
console = Console()


def version_callback(value: bool):
    """Prints the version of the package."""
    if value:
        console.print(f"[yellow]xvideos-dl[/] version: [bold blue]{__version__}[/]")
        raise typer.Exit()


@app.command(name="CLI to download videos from https://xvideos.com")
def main(
    urls: List[str] = typer.Argument(..., help="URL of the video web page."),
Esempio n. 15
0
import typer

sub_app = typer.Typer()

variable = "Some text"


@sub_app.command()
def hello(name: str = "World", age: int = typer.Option(0, help="The age of the user")):
    """
    Say Hello
    """
    typer.echo(f"Hello {name}")


@sub_app.command()
def hi(user: str = typer.Argument("World", help="The name of the user to greet")):
    """
    Say Hi
    """


@sub_app.command()
def bye():
    """
    Say bye
    """
    typer.echo("sub bye")


app = typer.Typer(help="Demo App", epilog="The end")
Esempio n. 16
0
import http
from collections import defaultdict
from datetime import datetime, timedelta
from typing import Optional

import typer
from pydantic import BaseModel
from pydantic.datetime_parse import parse_datetime

import tinvest as ti

openapi = typer.Typer()

DATETIME_HELP = (
    'Use one of [now, day, week, month, 6month, year] or any date-time format'
)


class OpenapiCtx(BaseModel):
    token: str = ''
    sandbox_token: str = ''
    use_sandbox: bool = False


class BaseApi:
    client: ti.SyncClient


def do_request(ctx: typer.Context, method, *args, **kwargs):
    if ctx.obj.use_sandbox:
        client = ti.SyncClient(ctx.obj.sandbox_token, use_sandbox=True)
Esempio n. 17
0
import random

from enum import Enum
from tqdm import tqdm as tq
from geomloss import SamplesLoss
from torch.nn import Sequential, Linear
from torch.nn import functional as F
from torch_geometric.utils import accuracy, precision, recall, f1_score
from pathlib import Path
from rdkit import Chem
from rdkit.Chem import Draw
from models import GNNExplainer_
from models.encoder import GCNN
from utils import get_split, get_dgn, mol_to_tox21_pyg, mol_to_esol_pyg, mol_from_smiles, morgan_count_fingerprint, x_map_tox21, mol_to_smiles, create_path, rdkit_fingerprint, morgan_bit_fingerprint

app = typer.Typer(add_completion=False)


def read_graphs(dataset_path: Path):
    labels = {}
    nx_graphs = {}
    for name in os.listdir(str(dataset_path)):
        if not name.endswith('gexf'):
            continue
        idx, label = name.split('.')[-3:-1]
        idx, label = int(idx), int(label)
        nx_graphs[idx] = nx.read_gexf(dataset_path / name)
        labels[idx] = label
    print('Found %d samples' % len(nx_graphs))
    return nx_graphs, labels
Esempio n. 18
0
import typer

from seq2rel_ds import cdr, dgm, docred, gda
from seq2rel_ds.common.util import set_seeds

set_seeds()

app = typer.Typer(
    help="Commands for preprocessing data to conform to the seq2rel format.", )
app.add_typer(cdr.app, name="cdr")
app.add_typer(dgm.app, name="dgm")
app.add_typer(docred.app, name="docred")
app.add_typer(gda.app, name="gda")

if __name__ == "__main__":
    app()
Esempio n. 19
0
"""
import os
import logging
from pathlib import Path

import typer

from rostran.core import exceptions
from rostran.core.format import (
    SourceTemplateFormat,
    TargetTemplateFormat,
    GeneratorFileFormat,
    convert_template_to_file_format,
)

app = typer.Typer(help=__doc__)
SOURCE_TEMPLATE_FORMAT_DEFAULT = typer.Option(SourceTemplateFormat.Auto,
                                              help="Source template format")
TARGET_TEMPLATE_FORMAT_DEFAULT = typer.Option(TargetTemplateFormat.Auto,
                                              help="Target template format")


@app.command()
def transform(
    source_path: str,
    source_format: SourceTemplateFormat = SOURCE_TEMPLATE_FORMAT_DEFAULT,
    target_path: str = typer.Option(None),
    target_format: TargetTemplateFormat = TARGET_TEMPLATE_FORMAT_DEFAULT,
):
    """
    Transform AWS CloudFormation/Terraform/Excel template to ROS template.
Esempio n. 20
0
from lightning.bot import LightningBot
from lightning.cli import guild, tools
from lightning.cli.utils import asyncd
from lightning.config import CONFIG
from lightning.utils.helpers import create_pool, run_in_shell

try:
    import uvloop
except ImportError:
    # Lol get f****d windows
    pass
else:
    uvloop.install()

parser = typer.Typer()
parser.add_typer(tools.parser, name="tools", help="Developer tools")
parser.add_typer(guild.parser, name="guild", help="Guild management commands")


@contextlib.contextmanager
def init_logging():
    try:
        max_file_size = 1000 * 1000 * 8
        file_handler = logging.handlers.RotatingFileHandler(
            filename="lightning.log", maxBytes=max_file_size, backupCount=10)
        log_format = logging.Formatter(
            '[%(asctime)s] %(name)s (%(filename)s:%(lineno)d) %(levelname)s: %(message)s'
        )
        file_handler.setFormatter(log_format)
Esempio n. 21
0
import typer

app = typer.Typer()
items_app = typer.Typer()
app.add_typer(items_app, name="items")
users_app = typer.Typer()
app.add_typer(users_app, name="users")


@items_app.command("create")
def items_create(item: str):
    typer.echo(f"Creating item: {item}")


@items_app.command("delete")
def items_delete(item: str):
    typer.echo(f"Deleting item: {item}")


@items_app.command("sell")
def items_sell(item: str):
    typer.echo(f"Selling item: {item}")


@users_app.command("create")
def users_create(user_name: str):
    typer.echo(f"Creating user: {user_name}")


@users_app.command("delete")
def users_delete(user_name: str):
Esempio n. 22
0
import pymongo
import typer

from apps.users.config import users_settings
from fastapi_mongodb.db import db_handler
from fastapi_mongodb.helpers import MakeAsync

__all__ = ["users_commands"]

users_commands = typer.Typer(name="users")


async def setup_app():
    await db_handler.create_collection(name=users_settings.USERS_COL)

    indexes = [
        pymongo.IndexModel(
            keys=[("email", pymongo.ASCENDING)],
            name="email",
            unique=True,
            background=True,
        )
    ]
    result = await db_handler.create_indexes(col_name=users_settings.USERS_COL, indexes=indexes)
    for index_name in result:
        typer.secho(
            message=f"Index: '{index_name}' for collection '{users_settings.USERS_COL}' created successfully.",
            fg=typer.colors.GREEN,
        )

Esempio n. 23
0
from globus_automate_client.cli.callbacks import (
    input_validator,
    principal_validator,
    url_validator_callback,
)
from globus_automate_client.cli.constants import OutputFormat
from globus_automate_client.cli.helpers import (
    output_format_option,
    process_input,
    verbosity_option,
)
from globus_automate_client.cli.rich_helpers import RequestRunner
from globus_automate_client.cli.rich_rendering import live_content
from globus_automate_client.client_helpers import create_action_client

app = typer.Typer(short_help="Manage Globus Automate Actions")


@app.command("introspect")
def action_introspect(
    action_url: str = typer.Option(
        ...,
        help="The url at which the target Action Provider is located.",
        prompt=True,
        callback=url_validator_callback,
    ),
    action_scope: str = typer.Option(
        None,
        help="The scope this Action Provider uses to authenticate requests.",
        callback=url_validator_callback,
    ),
Esempio n. 24
0
app = typer.Typer(
    cls=NaturalOrderGroup,
    help=f"""Run the DIRAC integration tests.

A local DIRAC setup can be created and tested by running:

\b
  ./integration_tests.py create

This is equivalent to running:

\b
  ./integration_tests.py prepare-environment
  ./integration_tests.py install-server
  ./integration_tests.py install-client
  ./integration_tests.py test-server
  ./integration_tests.py test-client

The test setup can be shutdown using:

\b
  ./integration_tests.py destroy

See below for additional subcommands which are useful during local development.

## Features

The currently known features and their default values are:

\b
  HOST_OS: {DEFAULT_HOST_OS!r}
  MYSQL_VER: {DEFAULT_MYSQL_VER!r}
  ES_VER: {DEFAULT_ES_VER!r}
  {(os.linesep + '  ').join(['%s: %r' % x for x in FEATURE_VARIABLES.items()])}

All features can be prefixed with "SERVER_" or "CLIENT_" to limit their scope.

## Extensions

Integration tests can be ran for extensions to DIRAC by specifying the module
name and path such as:

\b
  ./integration_tests.py create --extra-module MyDIRAC=/path/to/MyDIRAC

This will modify the setup process based on the contents of
`MyDIRAC/tests/.dirac-ci-config.yaml`. See the Vanilla DIRAC file for the
available options.

## Command completion

Command completion of typer based scripts can be enabled by running:

  typer --install-completion

After restarting your terminal you command completion is available using:

  typer ./integration_tests.py run ...
""",
)
Esempio n. 25
0
import typer


def callback():
    typer.echo("Running a command")


app = typer.Typer(callback=callback)


@app.callback()
def new_callback():
    typer.echo("Override callback, running a command")


@app.command()
def create(name: str):
    typer.echo(f"Creating user: {name}")


if __name__ == "__main__":
    app()
Esempio n. 26
0
import os
import readline
import signal
from typing import Final

import typer
import twitter
from tweet import settings
from rich.console import Console

APP_NAME: Final[str] = "tweet"

app: Final[typer.Typer] = typer.Typer(help="Tweet Only.")
console: Final[Console] = Console()
api: twitter.Api = twitter.Api(
    consumer_key=settings.CONSUMER_TOKEN,
    consumer_secret=settings.CONSUMER_SECRET,
    access_token_key=settings.ACCESS_TOKEN,
    access_token_secret=settings.ACCESS_SECRET,
)


def init_api() -> None:
    global api
    api = twitter.Api(
        consumer_key=settings.CONSUMER_TOKEN,
        consumer_secret=settings.CONSUMER_SECRET,
        access_token_key=settings.ACCESS_TOKEN,
        access_token_secret=settings.ACCESS_SECRET,
    )
Esempio n. 27
0
from pathlib import Path
from typing import Optional

import typer

from .core import RemoteRunner

app = typer.Typer(help='Jupyter Lab Port Forwarding Utility')


def version_callback(value: bool):
    from pkg_resources import get_distribution

    __version__ = get_distribution('jupyter_forward').version
    if value:
        typer.echo(f'Jupyter Forward CLI Version: {__version__}')
        raise typer.Exit()


@app.command()
def start(
    host: str,
    port: int = typer.Option(
        8888,
        help=(
            '''The local port the remote notebook server will be forwarded to. If not specified, defaults to 8888.'''
        ),
        show_default=True,
    ),
    conda_env: str = typer.Option(
        None,
Esempio n. 28
0
    """Run evolution."""
    ev = Evolution()
    date = moex.last_history_date()
    port = load_from_yaml(date)
    ev.evolve(port)


def dividends(ticker: str):
    """Get dividends status."""
    div_status.dividends_validation(ticker)


def optimize(date: str = typer.Argument(..., help="YYYY-MM-DD")):
    """Optimize portfolio."""
    port = load_from_yaml(date)
    opt = Optimizer(port)
    print(opt.portfolio)
    print(opt.metrics)
    print(opt)
    div_status.new_on_smart_lab(tuple(port.index[:-2]))


if __name__ == "__main__":
    app = typer.Typer(help="Run poptimizer subcommands.", add_completion=False)

    app.command()(evolve)
    app.command()(dividends)
    app.command()(optimize)

    app(prog_name="poptimizer")
Esempio n. 29
0
import subprocess

import typer
from typer.testing import CliRunner

from docs_src.options.name import tutorial003 as mod

runner = CliRunner()

app = typer.Typer()
app.command()(mod.main)


def test_option_help():
    result = runner.invoke(app, ["--help"])
    assert result.exit_code == 0
    assert "-n" in result.output
    assert "TEXT" in result.output
    assert "--user-name" not in result.output
    assert "--name" not in result.output


def test_call():
    result = runner.invoke(app, ["-n", "Camila"])
    assert result.exit_code == 0
    assert "Hello Camila" in result.output


def test_script():
    result = subprocess.run(
        ["coverage", "run", mod.__file__, "--help"],
Esempio n. 30
0
import typer

app = typer.Typer()

users_app = typer.Typer()
app.add_typer(users_app, name="users", help="Manage users in the app.")


@users_app.command()
def create(name: str):
    print(f"Creating user: {name}")


if __name__ == "__main__":
    app()