Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Refactoring/dry #224

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<a href="https://sonarcloud.io/dashboard?id=yoda"><img src="https://sonarcloud.io/api/project_badges/measure?project=yoda&metric=alert_status&template=FLAT" alt="SonarCloud Quality Status"></a>
<a href="https://manparvesh.mit-license.org/"><img src="https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square" alt="License"></a>
<a href="https://github.com/yoda-pa/yoda"><img src="https://img.shields.io/badge/version-0.3.0-blue.svg?style=flat-square" alt="Project status"></a>
<a href="https://github.com/ambv/black"><img src="https://img.shields.io/badge/code%20style-black-000000.svg" alt="Code style: black"></a>

<p>Wise and powerful personal assistant, available in your nearest terminal</p><br>

Expand Down
32 changes: 16 additions & 16 deletions modules/__init__.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
__all__ = [
'alias',
'asciiator',
'chat',
'dev',
'love',
'diary',
'money',
'learn',
'setup',
'life',
'util',
'food',
'goals',
'gif',
'people',
'entertainment'
"alias",
"asciiator",
"chat",
"dev",
"love",
"diary",
"money",
"learn",
"setup",
"life",
"util",
"food",
"goals",
"gif",
"people",
"entertainment",
]
34 changes: 21 additions & 13 deletions modules/alias.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,22 @@
ALIAS_CONFIG_FILE_PATH = get_config_file_paths()["ALIAS_CONFIG_FILE_PATH"]
ALIAS_CONFIG_FOLDER_PATH = get_folder_path_from_file_path(ALIAS_CONFIG_FILE_PATH)


class Alias(click.Group):

_aliases = {}

def __init__(self, *args, **kwargs):
create_folder(ALIAS_CONFIG_FOLDER_PATH)
try:
with open(ALIAS_CONFIG_FOLDER_PATH + '/alias.txt', 'r') as f:
with open(ALIAS_CONFIG_FOLDER_PATH + "/alias.txt", "r") as f:
lines = f.readlines()
for i in range(1, len(lines), 2):
Alias._aliases[lines[i].strip('\n')] = lines[i - 1].strip('\n').split()
Alias._aliases[lines[i].strip("\n")] = (
lines[i - 1].strip("\n").split()
)
except:
fo = open(ALIAS_CONFIG_FOLDER_PATH + '/alias.txt', 'w')
fo = open(ALIAS_CONFIG_FOLDER_PATH + "/alias.txt", "w")
fo.close()
super(Alias, self).__init__(*args, **kwargs)

Expand All @@ -32,7 +35,6 @@ def __init__(self, *args, **kwargs):
# args[0].insert(0, command)
# return super(Alias, self).__call__(*args, **kwargs)


def get_command(self, ctx, cmd_name):
ctx.obj = []
cmd = click.Group.get_command(self, ctx, cmd_name)
Expand All @@ -45,6 +47,7 @@ def get_command(self, ctx, cmd_name):

return None


def alias_checker(ctx, param, value):
if value is None or len(value) == 0:
pass
Expand All @@ -60,15 +63,17 @@ def alias_checker(ctx, param, value):
ctx.obj.append(value)
return None


@click.group()
def alias():
"""
For creating aliases to cumbersome commands
"""


@alias.command()
@click.argument('orig_cmd', nargs=1)
@click.argument('alias_cmd', nargs=1)
@click.argument("orig_cmd", nargs=1)
@click.argument("alias_cmd", nargs=1)
def new(orig_cmd, alias_cmd):
"""
Alias a new command \n\n
Expand All @@ -87,17 +92,20 @@ def new(orig_cmd, alias_cmd):
click.echo("Aliasing failed - Alias must not contain spaces")
return
if alias_cmd in Alias._aliases.keys():
click.echo("Aliasing failed - Alias name already exists. Use alias delete to remove it")
click.echo(
"Aliasing failed - Alias name already exists. Use alias delete to remove it"
)
return
if orig_cmd and alias_cmd:
create_folder(ALIAS_CONFIG_FOLDER_PATH)
with open(ALIAS_CONFIG_FOLDER_PATH + '/alias.txt', 'a') as f:
f.write(orig_cmd + '\n' + alias_cmd + '\n')
with open(ALIAS_CONFIG_FOLDER_PATH + "/alias.txt", "a") as f:
f.write(orig_cmd + "\n" + alias_cmd + "\n")
Alias._aliases[alias_cmd] = orig_cmd
click.echo("Aliased %s as %s" % (orig_cmd, alias_cmd))


@alias.command()
@click.argument('alias', nargs=1)
@click.argument("alias", nargs=1)
def delete(alias):
"""
Delete an alias \n\n
Expand All @@ -108,9 +116,9 @@ def delete(alias):
return
del Alias._aliases[alias]
create_folder(ALIAS_CONFIG_FOLDER_PATH)
with open(ALIAS_CONFIG_FOLDER_PATH + '/alias.txt', 'w') as f:
with open(ALIAS_CONFIG_FOLDER_PATH + "/alias.txt", "w") as f:
for key in Alias._aliases.keys():
f.write(' '.join(Alias._aliases[key]) + '\n' + key + '\n')
f.write(" ".join(Alias._aliases[key]) + "\n" + key + "\n")


@alias.command()
Expand All @@ -121,4 +129,4 @@ def show():
"""
click.echo("alias_command : original_command")
for key in Alias._aliases.keys():
click.echo(key + " : " + ' '.join(Alias._aliases[key]))
click.echo(key + " : " + " ".join(Alias._aliases[key]))
27 changes: 19 additions & 8 deletions modules/asciiator.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
from PIL import Image
ASCII_CHARS = ['#', '?', '%', '.', 'S', '+', '.', '*', ':', ',', '@']

ASCII_CHARS = ["#", "?", "%", ".", "S", "+", ".", "*", ":", ",", "@"]


def handle_image_conversion(image_filepath):
image = None
try:
image = Image.open(image_filepath)
except Exception as e:
print("Unable to open image file {image_filepath}.".format(image_filepath=image_filepath))
print(
"Unable to open image file {image_filepath}.".format(
image_filepath=image_filepath
)
)
print(e)
return
new_width = 100
range_width = 25
(original_width, original_height) = image.size
aspect_ratio = original_height/float(original_width)
aspect_ratio = original_height / float(original_width)
new_height = int(aspect_ratio * new_width)
image = image.resize((new_width, new_height)).convert('L')
pixels_to_chars = "".join([ASCII_CHARS[pixel_value/range_width] for pixel_value in
list(image.getdata())])
image_ascii = [pixels_to_chars[index: index + new_width] for index in
xrange(0, len(pixels_to_chars), new_width)]
image = image.resize((new_width, new_height)).convert("L")
pixels_to_chars = "".join(
[
ASCII_CHARS[pixel_value / range_width]
for pixel_value in list(image.getdata())
]
)
image_ascii = [
pixels_to_chars[index : index + new_width]
for index in xrange(0, len(pixels_to_chars), new_width)
]
return "\n".join(image_ascii)


Expand Down
26 changes: 10 additions & 16 deletions modules/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,29 +19,23 @@

from . import config

CLIENT_ACCESS_TOKEN = os.environ.get('API_AI_TOKEN', config.API_AI_TOKEN)
CLIENT_ACCESS_TOKEN = os.environ.get("API_AI_TOKEN", config.API_AI_TOKEN)
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
request = ai.text_request()
request.session_id = os.environ.get(
'API_AI_SESSION_ID', config.API_AI_SESSION_ID)
request.session_id = os.environ.get("API_AI_SESSION_ID", config.API_AI_SESSION_ID)

QUOTE_API_URL = 'https://api.forismatic.com/api/1.0/'
QUOTE_API_URL = "https://api.forismatic.com/api/1.0/"


def process(input_string):
"""
minimal chat bot
:param input_string:
"""
if 'inspire' in input_string:
send_data = {
'method': 'getQuote',
'format': 'json',
'lang': 'en',
'key': ""
}
hdr = {'User-Agent': "Magic Browser"}
full_url = QUOTE_API_URL + '?' + urllib.parse.urlencode(send_data)
if "inspire" in input_string:
send_data = {"method": "getQuote", "format": "json", "lang": "en", "key": ""}
hdr = {"User-Agent": "Magic Browser"}
full_url = QUOTE_API_URL + "?" + urllib.parse.urlencode(send_data)
response = urlopen(Request(full_url, headers=hdr))
response = response.read()
output = json.loads(response)
Expand All @@ -55,10 +49,10 @@ def process(input_string):
response = request.getresponse().read()
except socket.gaierror:
# if the user is not connected to internet don't give a response
click.echo(chalk.red('Yoda cannot sense the internet right now!'))
click.echo(chalk.red("Yoda cannot sense the internet right now!"))
sys.exit(1)

output = json.loads(response.decode('utf-8'))
output = json.loads(response.decode("utf-8"))
answer = output["result"]["fulfillment"]["speech"]
click.echo(chalk.blue('Yoda speaks:'))
click.echo(chalk.blue("Yoda speaks:"))
click.echo(answer)
54 changes: 37 additions & 17 deletions modules/config.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import os.path

API_AI_TOKEN = 'caca38e8d99d4ea6bd9ffa9a8be15ff9'
API_AI_SESSION_ID = 'dd60fde7-c6ab-4f38-9487-7300c42b4916'
API_AI_TOKEN = "caca38e8d99d4ea6bd9ffa9a8be15ff9"
API_AI_SESSION_ID = "dd60fde7-c6ab-4f38-9487-7300c42b4916"
# this is where yoda's config will be stored
YODA_CONFIG_FILE_PATH = os.path.join(os.path.expanduser('~'), '.yodaconfig')
YODA_CONFIG_FILE_PATH = os.path.join(os.path.expanduser("~"), ".yodaconfig")

DEFAULT_CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.yoda')
DEFAULT_CONFIG_PATH = os.path.join(os.path.expanduser("~"), ".yoda")


def update_config_path(new_path):
Expand All @@ -16,7 +16,7 @@ def update_config_path(new_path):
"""
if len(new_path) == 0:
new_path = DEFAULT_CONFIG_PATH
with open(YODA_CONFIG_FILE_PATH, 'w') as config_file:
with open(YODA_CONFIG_FILE_PATH, "w") as config_file:
config_file.write(new_path)
return new_path

Expand All @@ -33,16 +33,36 @@ def get_config_file_paths():
config_path_prefix = DEFAULT_CONFIG_PATH

return {
"USER_CONFIG_FILE_PATH": os.path.join(config_path_prefix, '.userconfig.yml'),
"LOVE_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'love/.loveconfig.yml'),
"MONEY_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'money/.moneyconfig.yml'),
"DIARY_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'diary/.diaryconfig.yml'),
"VOCABULARY_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'vocabulary/.vocabularyconfig.yml'),
"FLASHCARDS_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'flashcards/.flashcardsconfig.yml'),
"LIFE_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'life/.lifeconfig.yml'),
"IDEA_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'life/ideaconfig.txt'),
"ALIAS_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'alias/aliases.txt'),
"GOALS_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'goals/.goalsconfig.yml'),
"PEOPLE_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'people/.peopleconfig.yml'),
"KEYBINDINGS_CONFIG_FILE_PATH": os.path.join(config_path_prefix, 'software/.softwarekeybindingsconfig.yml')
"USER_CONFIG_FILE_PATH": os.path.join(config_path_prefix, ".userconfig.yml"),
"LOVE_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "love/.loveconfig.yml"
),
"MONEY_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "money/.moneyconfig.yml"
),
"DIARY_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "diary/.diaryconfig.yml"
),
"VOCABULARY_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "vocabulary/.vocabularyconfig.yml"
),
"FLASHCARDS_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "flashcards/.flashcardsconfig.yml"
),
"LIFE_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "life/.lifeconfig.yml"
),
"IDEA_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "life/ideaconfig.txt"
),
"ALIAS_CONFIG_FILE_PATH": os.path.join(config_path_prefix, "alias/aliases.txt"),
"GOALS_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "goals/.goalsconfig.yml"
),
"PEOPLE_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "people/.peopleconfig.yml"
),
"KEYBINDINGS_CONFIG_FILE_PATH": os.path.join(
config_path_prefix, "software/.softwarekeybindingsconfig.yml"
),
}
Loading