Exemplo n.º 1
0
def download_image(url: str, path: str, silent: bool = False) -> str:
    """
    Downloads an image from a url

    returns the file path
    """
    try:
        res = requests.get(url)
    except:
        print(chalk.Chalk("red")("Failed to download image.", bold=True))
        return

    if "image" not in res.headers.get("content-type"):
        print(
            chalk.Chalk("yellow")("URL is not an image. Skipping.", bold=True))
        return

    with open(path, "wb") as f:
        f.write(res.content)
        if not silent:
            print(
                chalk.Chalk("green")("Image download finished: " + f.name,
                                     bold=True))

        f.close()

        return f.name
Exemplo n.º 2
0
def load_pokedex() -> dict:
    """Converts data/pokedex.json to dictionary"""
    try:
        pokedex = json.load(open("data/pokedex.json"))
        print(chalk.Chalk("cyan")("Pokedex loaded.", bold=True))
        return pokedex
    except:
        print(
            chalk.Chalk("red")(
                "Failed to load pokedex. Maybe it doesn't exist?.", bold=True))
Exemplo n.º 3
0
def calculate_hashes() -> None:
    """calculates the phashes for each pokemon image and stores them in pokedex.json"""
    for pokemon in pokedex:
        hash = imagehash.phash(Image.open(f"data/images/{pokemon['id']}.png"))
        pokemon["hash"] = str(hash)
        print(
            chalk.Chalk("green")(pokemon["name"] + "\t=> " + pokemon["hash"]))

    utils.update_pokedex(pokedex)
Exemplo n.º 4
0
def verify(ctx, as_json):
    """Veryfies if the changelog is in "keep-a-changlog" format.
    Use '--json' get JSON formatted output that can be easier integrated into CI workflows.
    Exit code is the number of identified errors.
    """
    kacl_changelog, kacl_changelog_filepath = load_changelog(ctx)
    kacl_changelog_filepath = os.path.basename(kacl_changelog_filepath)

    valid = kacl_changelog.is_valid()
    validation = kacl_changelog.validate()
    if as_json:
        validation_map = validation.convert_to_dict()
        click.echo(json.dumps(validation_map, sort_keys=True, indent=4))
    else:
        green = chalk.Chalk('green')
        red = chalk.Chalk('red')
        white = chalk.Chalk('white')
        bold = chalk.bold

        for error in validation.errors():
            start_char_pos, end_char_pos = error.position()

            char_indicator = start_char_pos
            if start_char_pos == None:
                char_indicator = 0

            click.echo(bold + kacl_changelog_filepath + ':' +
                       f'{error.line_number()}:{char_indicator}: ' + red +
                       'error: ' + white + error.error_message() + chalk.RESET)

            if error.line():
                click.echo(error.line())
                if start_char_pos != None and end_char_pos != None:
                    mark_length = end_char_pos - start_char_pos - 1
                    click.echo(' ' * start_char_pos + green + '^' + '~' *
                               (mark_length) + chalk.RESET)
        if not valid:
            click.echo(f'{len(validation.errors())} error(s) generated.')
        else:
            click.secho('Success', fg='green')

    if not valid:
        sys.exit(len(validation.errors()))
Exemplo n.º 5
0
async def on_message(message):
    if message.author == client.user:
        return

    if message.author.id == 365975655608745985 and message.embeds:
        embed = message.embeds[0]
        if embed.description.startswith("Guess"):
            found = pokehash.find_pokemon(embed.image.url, is_url=True)
            if not found:
                return print(chalk.Chalk("red")("Unable to find pokemon."))
            if helper_mode:
                await message.channel.send("It's a " + found[:3] + "...!")
            else:
                utils.send_message("p!catch " + found)
                utils.send_message("p!info latest")
Exemplo n.º 6
0
"""
WorldRIZe CLI
"""
import os, re, json, shutil, requests, string
import fire, chalk
from pathlib import Path
from dotenv import load_dotenv

pwd = Path(__file__).resolve().parent
env = pwd / '.env'
load_dotenv(env)
green, red = chalk.Chalk('green'), chalk.Chalk('red')

def locales():
    return ['en-us', 'en-au', 'en-uk', 'en-in']

def success(*args):
    print(f'{green("✔")} ', *args)

def info(*args):
    print(f'🔖 ', *args)

def error(*args):
    print(f'{red("✗")} ', *args)

def strip_brs(txt: str):
    lines = txt.split('\n')
    lines = [l for l in lines if l != '\n']
    return '\n'.join(lines).strip()

def generate_phrase_voices(phrase: object, out_dir: Path):
Exemplo n.º 7
0
   s, shell      Run a shell command as described in PROJECT/.necro.toml

See 'necro <command> --help' for more information on a specific command.
"""

import chalk
from docopt import docopt

from . import (raise_command, shell_command, fake_builder)

# pylint: disable=invalid-name
raise_module = fake_builder.fake_builder_raise
shell_module = fake_builder.fake_builder_shell

# pylint: disable=invalid-name
red = chalk.Chalk('red')
red_bold = red + chalk.utils.FontFormat('bold')
yellow = chalk.Chalk('yellow')


def runner():
    ''' parse args then call the right function '''
    args = docopt(__doc__, version='necro 0.0.2', options_first=True)

    argv = [args['<command>'], *args['<args>']]

    # the args to add to the build_obj
    return_code = 1

    if args['<command>'] in ['r', 'raise']:
        run_args = docopt(raise_command.__doc__, argv=argv)
Exemplo n.º 8
0
import sys

import discord
import chalk

import pokehash
import utils

client = discord.Client()

helper_mode = False
if "-h" in sys.argv:
    helper_mode = True
    print(chalk.Chalk("cyan")("Running in helper mode.", bold=True))


@client.event
async def on_ready():
    print("Gonna catch 'em all!")


@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.author.id == 365975655608745985 and message.embeds:
        embed = message.embeds[0]
        if embed.description.startswith("Guess"):
            found = pokehash.find_pokemon(embed.image.url, is_url=True)
            if not found:
Exemplo n.º 9
0
    """calculates the phashes for each pokemon image and stores them in pokedex.json"""
    for pokemon in pokedex:
        hash = imagehash.phash(Image.open(f"data/images/{pokemon['id']}.png"))
        pokemon["hash"] = str(hash)
        print(
            chalk.Chalk("green")(pokemon["name"] + "\t=> " + pokemon["hash"]))

    utils.update_pokedex(pokedex)


def find_pokemon(img: str, is_url: bool = False) -> str:
    """Returns the name of the pokemon from an image"""
    if is_url:
        img = utils.download_image(img, "data/temp.png", silent=True)

    search_hash = str(imagehash.phash(Image.open(img)))
    os.remove(img)

    for pokemon in pokedex:
        if search_hash == pokemon["hash"]:
            return pokemon["name"]


if __name__ == "__main__":
    found = find_pokemon(sys.argv[1])
    if found:
        utils.send_message("p!catch " + found)
        utils.send_message("p!info latest")
    else:
        print(chalk.Chalk("red")("Unable to find pokemon."))
Exemplo n.º 10
0
        if consecutive >= 4:
            return True
        else:
            consecutive = 1

class Player():
    def __init__(self, letter, color):
        self.name = input("What's your name?")
        if len(self.name) > 0:
            self.letter = self.name[0]
        else:
            self.letter = letter
        self.color = color

# Create our board and two players
board = Board()
player1 = Player("B", chalk.Chalk('blue'))
player2 = Player("R", chalk.Chalk('red'))


while not board.game_over:
    print(board)
    if board.moves_left % 2 == 0:
        if board.pick_move(player1):
            print(f"{player1.name} Wins")
    else:
        if board.pick_move(player2):
            print(f"{player2.name} Wins")

print(board)
print(f"{board.winner}!!! You win!")
Exemplo n.º 11
0
def update_pokedex(data: dict) -> None:
    """Saves to .json file"""
    with open("data/pokedex.json", "w") as f:
        json.dump(data, f)
        print(chalk.Chalk("cyan")("Pokedex updated.", bold=True))
        f.close()