def start():
    try:
        total = len(sys.argv)
        lt = list(sys.argv)
        if '-arg' in lt:
            # orginal_path = lt[0]
            # orginal_path = orginal_path[0:len(orginal_path)-6]
            # print(orginal_path)
            orginal_path = getpath(__file__)
            p = str(sys.argv)
            file_path = make_path(lt, total)
            os.chdir(file_path)
            # print(orginal_path)
            arg = all_args(lt)
            main(arg, orginal_path)
        else:
            arg = get_args(lt, len(lt))
            main(arg.strip(), orginal_path=os.getcwd())

    except Exception as e:
        # print(e)
        main(orginal_path=os.getcwd())
Exemplo n.º 2
0
    flag = False
    for i in range(1, length):
        if arg_list[i] == '-arg':
            break;
        if flag:
            path += ' '
        path += arg_list[i]
        flag = True
    return path


if __name__ == '__main__':
    check_if_first_time()
    try:
        length = len(sys.argv)
        arg_list = list(sys.argv)
        if '-arg' in arg_list:
            original_path = getpath(__file__)
            p = str(sys.argv)
            file_path = make_path(arg_list, length)
            arg = all_args(arg_list)
            # print(arg, file_path)
            main(arg, original_path)
        else:
            arg = get_args(arg_list, len(arg_list))
            main(arg, original_path=os.getcwd())
            # print(arg)

    except Exception as e:
        main(original_path=os.getcwd())
Exemplo n.º 3
0
from tools.ConfigParser import ConfigParser_manager as CM
from system.path import getpath
import os
from termcolor import cprint
from settings.settings import bot as bt
from settings.settings import interaction_setting as its
from settings.settings import update_bot
from tools.json_manager import JsonManager as JM

config_keys = ['-config', '-settings']
conf_path = os.path.join(getpath(__file__), 'settings.conf')
train_path = os.path.join(getpath(__file__), '.trained')

yes = ['yes', 'y']


class Config:
    obj = CM()
    lt = [
        'Bot', 'Interaction', 'Competitive Programming',
        'Features Installation', 'Training Mode'
    ]
    cp = [
        'Coder Name', 'Competitive companion port number',
        'Parse Problem with template', 'Template Path', 'Compiler'
    ]
    confirm_keys = ['y', 'yes', 'ok']

    def change_gender(self):
        pt = '-' * 22 + 'Gender Change' + '-' * 22
        cprint(pt, 'magenta')
Exemplo n.º 4
0
directories = {
    'assignment_attachment': None,
    'notes': None,
    'screenshot': None
}

credentials = {
    'lms': None,
    'icloud': None
}


DEBUG = True
LEARN = True
BROWSER = 'chrome'
conf_path  = os.path.join(getpath(__file__), 'settings.yaml')

try:
    obj = CM()
    section = 'bot'
    bot = obj.read(conf_path, section=section)
    section = 'interaction_setting'
    x = obj.read(conf_path, section=section)
    for i in interaction_setting:
        if x[i]:
            interaction_setting[i] = True
        else:
            interaction_setting[i]= False
    section = 'developer'
    x = obj.read(conf_path, section=section)
    if x['debug']:
def ai(msg, orginal_path):
    """ Little ai for reacting to the msg.
        Written by Saurav-Paul"""
    logger.debug('Processing with ai')
    msg = msg.replace('  ', ' ')
    msg = msg.replace(bot['name'], '')
    msg = msg.replace(bot['name'].lower(), '')
    msg = msg.replace(bot['name'].capitalize(), '')
    reply = "I don't know what to do, sir ."
    # print('you said ' , msg, bot['name'])
    if if_cp_type(msg):
        return 'Good luck sir.'
    if if_config_type(msg):
        return 'Good luck sir.'
    if if_shell_type(msg):
        return 'Good luck sir.'
    if if_run_type(msg):
        return 'Good luck sir.'
    if if_credit_type(msg):
        return 'Good luck sir.'
    else:
        try:
            msg = msg.strip().lower()
            for line in data:
                if is_matched(msg, line, 95):
                    reply = data[line]
                    return reply
            # logger.info('Not found in common data')
            # from history
            try:
                f = getpath(__file__) + '.learnt'
                history = JsonManager.json_read(f)
                for line in history:
                    if is_matched(msg, line, 95):
                        logging.info('Learnt this before')
                        return history[line]

            except:
                logging.error("Can't read history file")
            if (check(msg, ['change dir', 'change directory', 'chdir', '-cd'],
                      100)):
                # print(os.getcwd())
                cprint('Enter the path: ', 'cyan', end='')
                path = input()
                os.chdir(path)
                return 'Directory changed.'
            if check(msg, youtube_play):
                msg = rep(msg, youtube_play)
                logger.info(msg)
                find_goto_address(msg)
                reply = 'Enjoy sir. :D'
            elif check(msg, goto_keys):
                msg = rep(msg, goto_keys)
                find_goto_address(msg)
                reply = 'check browser'
                notify('Check Browser', ':D', t=5)
            elif check(msg, youtube):
                msg = rep(msg, youtube)
                search_youtube(msg)
                reply = 'check browser.'
                notify('Check Browser', ':D', t=5)
            elif check(msg, wiki):
                msg = rep(msg, wiki)
                # search_wiki(msg)
                msg = 'en.wikipedia.org ' + msg
                find_goto_address(msg)
                reply = 'check browser.'
                notify('Check Browser', ':D', t=5)
            elif msg == 'download':
                cprint('Enter the url : ', 'cyan', end='')
                url = input()
                wget_downloader(url)
                reply = 'Done.'
            elif check(msg, google):
                msg = rep(msg, google)
                # print('here = ',msg)
                search_google(msg)
                reply = 'check browser.'
                notify('Check Browser', ':D', t=5)
            elif check(msg, install_keys):
                msg = rep(msg, install_keys)
                reply = install(msg)
            elif check(msg, calc_keys):
                msg = rep(msg, calc_keys)
                reply = google_calculation(msg)
                if reply == "sorry":
                    search_google(msg)
                    reply = "check browser"
                    notify('Check Browser', ':D', t=5)
            else:
                if 0 and 'cmd:' in msg or '-s' in msg:
                    msg = rep(msg, {'cmd:'})
                    msg = rep(msg, {'-s'})
                    command_sep()
                    command(msg.lower())
                    command_sep()
                    reply = 'done sir'
                else:
                    try:
                        f = train_path
                        history = JsonManager.json_read(f)
                        for line in history:
                            if is_matched(msg, line, 95):
                                logging.info('You have trained this before.')
                                return history[line]

                    except:
                        logger.info("Can't read trained data")

                    t = time.time()
                    reply = ask_question(msg)
                    t = time.time() - t
                    logger.info(str(t) + ' sec')
                    # cprint(t,'red')
                    ok = True
                    for word in should_not_learn:
                        if word in msg.lower() or word in reply.lower():
                            ok = False
                            break

                    if ok:
                        logger.info('reply -> ' + reply)
                        if LEARN == False:
                            cprint(
                                "(Automatically LEARN MODE is disable)Enter y to learn : ",
                                'red',
                                attrs=['bold'],
                                end='')
                            learn = input('')
                        else:
                            learn = 'y'
                        if learn.lower() == 'y':
                            try:
                                history.update({msg: reply})
                                JsonManager.json_write(f, history)
                                logger.info('Learnt')
                            except Exception as e:
                                logger.info(
                                    "Exception while writing learnt : " + e)
            return reply
        except Exception as e:
            logger.info('Getting some error in ai')
            logger.info(e)
            return reply
Exemplo n.º 6
0
from tools.configParser import ConfigParser_manager as CM
from system.path import getpath
import os
from termcolor import cprint
from settings.setting import bot as bt
from settings.setting import interaction_setting as its
from settings.setting import update_bot
from tools.json_manager import JsonManager as JM

config_keys = ['-config', '-settings']
conf_path = os.path.join(getpath(__file__), 'settings.yaml')
default_path = os.path.join(getpath(__file__), 'default.yaml')
train_path = os.path.join(getpath(__file__), '.trained')

yes = ['yes', 'y']


# noinspection PyMethodMayBeStatic,PyBroadException,DuplicatedCode
class Config:
    export_file_name = 'ai_virtual_assistant_configs.yaml'
    obj = CM()
    lt = [
        'Bot', 'Interaction', 'Compiler Options', 'Features Installation',
        'Training Mode', 'Export/Import settings'
    ]
    confirm_keys = ['y', 'yes', 'ok']

    def change_gender(self):
        """
        change Gender of bot
        """
import os
from system.path import getpath

todo_file_path = os.path.join(getpath(__file__), 'todolist.todo')


class TODO:
    def list(self):
        pass


if __name__ == "__main__":
    print(todo_file_path)
Exemplo n.º 8
0
def ai(msg):
    """
    config, setting
    basic questions
    lms_keys
    wiki, youtube, google
    goto
    install, calculate
    screenshot
    calendar
    time, date
    login lms
    get incomp ass / quiz data
    play game (rock paper)
    toss a coin

    """
    logger.debug("called assistant")
    msg = msg.replace('  ', ' ').strip().lower()
    msg.replace(bot['name'], '')
    reply = 'don\'t know what to do sir'

    if if_config_type(msg):
        return 'Good luck sir.'
    try:
        for line in data:
            if is_matched(msg, line, 100):
                reply = data[line]
                return reply
        if check(msg, youtube_play):
            msg = rep(msg, youtube_play)
            logger.info(msg)
            url = "https://www.youtube.com/results?search_query=" + msg
            webbrowser.get().open(url)
            reply = 'Enjoy sir. '

        elif check(msg, goto_keys):
            msg = rep(msg, goto_keys)
            url = "https://" + msg
            webbrowser.get().open(url)
            reply = "Here is what I found for " + msg + "on google"
        elif check(msg, youtube):
            msg = rep(msg, youtube_play)
            logger.info(msg)
            url = "https://www.youtube.com/results?search_query=" + msg
            webbrowser.get().open(url)
            reply = 'Enjoy sir. '
        elif check(msg, wiki):
            msg = rep(msg, wiki)
            reply = tell_me_about(msg)
        elif check(msg, google):
            msg = rep(msg, google)
            url = "https://google.com/search?q=" + msg
            webbrowser.get().open(url)
            reply = "Here is what I found for" + msg + "on google"
        elif check(msg, install_keys):
            msg = rep(msg, install_keys)
            reply = install(msg)
        elif check(msg, ["capture", "my screen", "screenshot"]):
            try:
                myScreenshot = pyautogui.screenshot()
                path = get_directory(
                    'screenshot'
                ) / f'{datetime.datetime.now().timestamp()}-screenshot.png'
                myScreenshot.save(path)  # todo get proper directory
                reply = 'screen shot saved'
            except Exception as e:
                print(e)
        elif check(msg, CALENDAR_STRS):
            # print("calendar")
            date = get_date(msg)
            if date:
                for event in g_calendar.get_events(date):
                    reply = event
                return reply

            else:
                reply = "Sorry sir, didn't get that"
                return reply
        elif check(msg, calc_keys):
            msg = rep(msg, calc_keys)
            opr = msg.split()[1]
            if opr == '+' or opr == 'plus':
                reply = str(int(msg.split()[0]) + int(msg.split()[2]))
            elif opr == '-' or opr == "minus":
                reply = str(int(msg.split()[0]) - int(msg.split()[2]))
            elif opr == 'multiply' or 'x':
                reply = str(int(msg.split()[0]) * int(msg.split()[2]))
            elif opr == 'divide':
                reply = str(int(msg.split()[0]) / int(msg.split()[2]))
            elif opr == 'power':
                reply = str(int(msg.split()[0])**int(msg.split()[2]))
            else:
                reply = "Wrong Operator"
        elif check(msg, TIME_STRS):

            t = time.ctime().split(" ")[3].split(":")[0:2]
            hours = str(abs(12 - int(t[0])))
            minutes = t[1]
            am_pm = "AM" if int(t[0]) < 12 else "PM"
            t = hours + ":" + minutes + " " + am_pm
            reply = f"Sir, time is {t}"
        elif check(msg, DATE_STRS):

            t = time.ctime().split(" ")

            date = t[2]
            month = datetime.date.today().month

            reply = f"Sir, today is {date} {MONTHS[month - 1]}"
        elif check(msg, ["where am i", "my location"]):
            try:
                Ip_info = requests.get(
                    'https://geolocation-db.com/json/').json()
                loc = Ip_info['state']
                reply = f"You must be somewhere in {loc}, {Ip_info['country_name']}"
            except Exception:
                reply = "Unable to get your location"

        elif check(msg, ["send email", "send an email"
                         "email to ", "mail to"]):
            reply = "Email feature is not setup yet"
            pass

        elif check(msg, ['launch', 'run']):
            msg = rep(msg, ['launch', 'run'])
            print(msg)
            if CurrentOs == "Linux":
                subprocess.Popen(msg)
            else:
                subprocess.Popen(f'{msg}.exe')
            reply = f"Launching {msg}"

        # specials cases

        elif check(msg, lms_keys):
            d = threading.Thread(name='login_lms',
                                 target=VisitLms.login_to_lms)
            d.setDaemon(True)
            d.start()
            reply = "Logging in to lms "

        elif check(msg, incomp_ass_quiz_keys, need=50):

            if msg.find('of') != -1 or msg.find('for') != -1:
                if msg.find('of') != -1:
                    course = msg.split('of')[1].strip()
                else:
                    course = msg.split('for')[1].strip()
                    cprint(
                        f"Sir, Fetching all Incomplete assignments and quizzes of {course}",
                        'blue')

                VisitLms.get_incomplete_assignments_and_quizzes(course)
                reply = "Done."

            else:
                VisitLms.get_incomplete_assignments_and_quizzes()
                cprint(
                    f"Sir, Fetching all Incomplete assignments and quizzes from lms",
                    'blue')
                reply = "Done"

        elif check(msg, ["play game", "rock paper", "start game"]):
            speak("Choose among rock, paper and scissor")
            choice = get_input()
            moves = ["rock", "paper", "scissor"]
            cmove = random.choice(moves)
            pmove = choice

            speak("The computer chose " + cmove)
            speak("You chose " + pmove)

            if pmove == cmove:
                reply = "the match is draw"
            elif pmove == "rock" and cmove == "scissor":
                reply = "Player wins"
            elif pmove == "rock" and cmove == "paper":
                reply = "Computer wins"
            elif pmove == "paper" and cmove == "rock":
                reply = "Player wins"
            elif pmove == "paper" and cmove == "scissor":
                reply = "Computer wins"
            elif pmove == "scissor" and cmove == "paper":
                reply = "Player wins"
            elif pmove == "scissor" and cmove == "rock":
                reply = "Computer wins"

        elif check(msg, ["toss a coin", "flip a coin"]):
            moves = ["head", "tails"]
            cmove = random.choice(moves)
            reply = f"Its {cmove.title()}"

        else:
            """ run with arguments """
            if 'cmd:' in msg or '-s' in msg:
                msg = rep(msg, {'cmd:'})
                msg = rep(msg, {'-s'})
                command_sep()
                command(msg.lower())
                command_sep()
                reply = 'done sir'
            else:
                f = None

                try:
                    f = getpath(__file__) + '.learnt'
                    history = JsonManager.json_read(f)
                    for line in history:
                        if is_matched(msg, line, 95):
                            logger.info('Learnt this before')
                            return history[line]

                except FileNotFoundError:
                    logger.error("Can't read history file")

                try:
                    ft = train_path
                    history = JsonManager.json_read(ft)
                    for line in history:
                        if is_matched(msg, line, 95):
                            logger.info('You have trained this before.')
                            return history[line]

                except FileNotFoundError:
                    logger.info("Can't read trained data")
                t = time.time()
                reply = assistant.ask_question(msg)
                t = time.time() - t
                logger.info(str(t) + ' sec')

                ok = True
                for word in should_not_learn:
                    if word in msg.lower() or word in reply.lower():
                        ok = False
                        break
                if ok:
                    logger.info('reply -> ' + reply)
                    if not LEARN:
                        cprint(
                            "(Automatically LEARN MODE is disable)Enter y to learn : ",
                            'red',
                            attrs=['bold'],
                            end='')
                        learn = input('')
                    else:
                        learn = 'y'
                    if learn.lower() == 'y':
                        try:
                            history = JsonManager.json_read(f)
                            history.update({msg: reply})
                            JsonManager.json_write(f, history)
                            logger.info('Learnt')
                        except Exception as e:
                            logger.info("Exception while writing learnt : " +
                                        str(e))
        return reply
    except Exception as e:
        logger.error(f"getting some error in ai {e}")
        logger.info('Getting some error in ai')
        logger.info(str(e))
        return reply
Exemplo n.º 9
0
import os
from tools.ConfigParser import ConfigParser_manager as CM 
from system.path import getpath
from termcolor import cprint

conf_path = os.path.join(getpath(__file__),'settings.conf')
default_path = os.path.join(getpath(__file__),'default.conf')
export_file_name = 'ai_virtual_assistant_configs.conf'

def import_settings():
    if not os.path.exists(export_file_name):
        return False
    else :
        cprint(' Export file exists. Do you want import(y/n) : ','cyan',end='')
        confirm = input()
        positive = ['y', 'yes', 'ok', 'okay']
        if confirm.lower() in positive :
            from settings.settings import all_sections
            try :
                obj = CM()
                for section in all_sections :
                    data = obj.read(export_file_name,section = section)
                    conf_data = obj.read(conf_path,section = section)

                    for key in conf_data:
                        try :
                            x = data[key]
                            conf_data[key] = x
                        except:
                            pass
                    obj.update(conf_path,conf_data,section = section)