def test_it_can_handle_multiple_instances_without_clashing(tmpdir): """:type tmpdir: py._path.local.LocalPath""" import json_config a_path = tmpdir.join('unique_file_a.json') b_path = tmpdir.join('unique_file_b.json') a = json_config.connect(a_path.strpath) b = json_config.connect(b_path.strpath) a['test'] = 'A success' b['test'] = 'B success' assert a['test'] == 'A success' assert b['test'] == 'B success' assert a is not b with a_path.open() as f: a_written = f.read() with b_path.open() as f: b_written = f.read() assert a_written != b_written assert a_written == '{\n "test": "A success"\n}' assert b_written == '{\n "test": "B success"\n}'
def __init__(self): recognizer = Recognizer() recognizer.dynamic_energy_threshold = False recognizer.energy_threshold = 1000 self.recognizer = recognizer self.microphone = Microphone() self.susi = susi try: res = requests.get('http://ip-api.com/json').json() self.susi.update_location(longitude=res['lon'], latitude=res['lat']) except ConnectionError as e: logging.error(e) self.config = json_config.connect('config.json') if self.config['hotword_engine'] == 'Snowboy': from main.hotword_engine import SnowboyDetector self.hotword_detector = SnowboyDetector() else: from main.hotword_engine import PocketSphinxDetector self.hotword_detector = PocketSphinxDetector() if self.config['wake_button'] == 'enabled': if self.config['device'] == 'RaspberryPi': from ..hardware_components import RaspberryPiWakeButton self.wake_button = RaspberryPiWakeButton() else: self.wake_button = None else: self.wake_button = None
def getMedia(search_query): """ :param search_query: String to search service for :return: """ media_models = [] cfg = json_config.connect("credentials.json") giphy_api_key = cfg["giphy"]["apiKey"] client = giphypop.Giphy(api_key=giphy_api_key) items = client.search(search_query) for item in items: # created = datetime.fromtimestamp(item.import_datetime).isoformat() created = "" attrs = { "name": item.id, "service": 'Giphy', "mediaURL": item.media_url, "source": item.url, "type": 'gif', "created": created, "thumbnailURL": item.fixed_width.downsampled.url, "credit": item.url, } media = MediaModel(attrs) media_models.append(media) return media_models
def speaker_config(): room_name = request.args.get('room_name') config = json_config.connect(config_json_file) config['room_name'] = room_name display_message = {"room_name": room_name} resp = jsonify(display_message) resp.status_code = 200 return resp
def reboot(): config = json_config.connect(config_json_file) # speaker_config room_name = request.form['room_name'] config['room_name'] = room_name # wifi_credentials wifi_ssid = request.form['wifissid'] wifi_password = request.form['wifipassd'] os.chdir(base_folder) subprocess.call([ 'sudo', 'bash', wifi_search_folder + '/wifi_search.sh', wifi_ssid, wifi_password ]) #nosec #pylint-disable type: ignore # auth auth = request.form['auth'] email = request.form['email'] password = request.form['password'] # config stt = request.form['stt'] tts = request.form['tts'] hotword = request.form['hotword'] wake = request.form['wake'] subprocess.Popen( ['sudo', 'python3', configuration_script, stt, tts, hotword, wake]) #nosec #pylint-disable type: ignore subprocess.call(['sudo', 'systemctl', 'daemon-reload']) #nosec #pylint-disable type: ignore subprocess.call( ['sudo', 'systemctl', 'disable', 'ss-python-flask.service']) #nosec #pylint-disable type: ignore subprocess.call( ['sudo', 'systemctl', 'enable', '*****@*****.**']) #nosec #pylint-disable type: ignore subprocess.call( ['sudo', 'systemctl', 'enable', 'ss-factory-daemon.service']) #nosec #pylint-disable type: ignore subprocess.Popen( ['sudo', 'bash', os.path.join(wifi_search_folder, 'rwap.sh')]) display_message = { "wifi": "configured", "room_name": room_name, "wifi_ssid": wifi_ssid, "auth": auth, "email": email, "stt": stt, "tts": tts, "hotword": hotword, "wake": wake, "message": "SUSI is rebooting" } resp = jsonify(display_message) resp.status_code = 200 return resp # pylint-enable
def __init__(self, renderer=None): try: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.setup(27, GPIO.OUT) GPIO.setup(22, GPIO.OUT) except ImportError: print("Only available for devices with GPIO ports ") except RuntimeError: pass recognizer = Recognizer() recognizer.dynamic_energy_threshold = False recognizer.energy_threshold = 1000 self.recognizer = recognizer self.microphone = Microphone() self.susi = susi self.renderer = renderer try: res = requests.get('http://ip-api.com/json').json() self.susi.update_location( longitude=res['lon'], latitude=res['lat'], country_name=res['country'], country_code=res['countryCode']) except ConnectionError as e: logging.error(e) self.config = json_config.connect('config.json') if self.config['usage_mode'] == 'authenticated': try: susi.sign_in(email=self.config['login_credentials']['email'], password=self.config['login_credentials']['password']) except Exception: print('Some error occurred in login. Check you login details in config.json') if self.config['hotword_engine'] == 'Snowboy': from main.hotword_engine.snowboy_detector import SnowboyDetector self.hotword_detector = SnowboyDetector() else: from main.hotword_engine.sphinx_detector import PocketSphinxDetector self.hotword_detector = PocketSphinxDetector() if self.config['WakeButton'] == 'enabled': print("\nSusi has the wake button enabled") if self.config['Device'] == 'RaspberryPi': print("\nSusi runs on a RaspberryPi") from ..hardware_components import RaspberryPiWakeButton self.wake_button = RaspberryPiWakeButton() else: print("\nSusi is not running on a RaspberryPi") self.wake_button = None else: print("\nSusi has the wake button disabled") self.wake_button = None
def setup_console_settings(qtbot): """ Load the config file. """ config = json_config.connect( "AlphaHooks/{}".format(MainWindow.SETTINGS_PATH) ) widget = ConsoleSettings(config) qtbot.addWidget(widget) return widget
def basic_config(tmpdir, mocker): """ :type tmpdir: py._path.local.LocalPath :type mocker: pytest_mock.MockFixture """ import json_config config = json_config.connect(tmpdir.join('basic_config.json').strpath) mocker.spy(config, u'save') return config
def __init__(self, working_dir): # TODO check for existing file? self.config = json_config.connect(working_dir + '/config.json') self.config.setdefault('data_base_dir', working_dir + '/susi_linux') self.config.setdefault('flite_speech_file_path', 'extras/cmu_us_slt.flitevox') self.config.setdefault('detection_bell_sound', 'extras/detection-bell.wav') self.config.setdefault('problem_sound', 'extras/problem.wav') self.config.setdefault('recognition_error_sound', 'extras/recognition-error.wav')
def submit_times_from_file(web_driver_wait: WebDriverWait, file: str = 'default', skip_days: list = None) -> None: if not skip_days: skip_days = list() schedule_config = json_config.connect( join(dirname(__file__), '..', 'config', 'schedules', file + '.json')) # Cycle through the dropdown and accept hours worked for unentered weekdays elems = web_driver_wait.until( expected_conditions.presence_of_all_elements_located( (By.CSS_SELECTOR, '#date > option'))) for i in range(0, len(elems)): elem = web_driver_wait.until( expected_conditions.presence_of_all_elements_located( (By.CSS_SELECTOR, '#date > option')))[i] date_text = elem.text # Day from the date (date_text) day = detect_day(date_text) # Time must not already be entered in eServices if date_text not in skip_days: if not schedule_config[day] or schedule_config[day] == -1: continue start_time = schedule_config[day]['start'] end_time = schedule_config[day]['end'] # Select the day elem.click() # Set the times web_driver_wait.until( expected_conditions.presence_of_element_located( (By.CSS_SELECTOR, '#startTime > option[value="' + start_time + '"]'))).click() web_driver_wait.until( expected_conditions.presence_of_element_located( (By.CSS_SELECTOR, '#endTime > option[value="' + end_time + '"]'))).click() # Add time web_driver_wait.until( expected_conditions.presence_of_element_located( (By.ID, 'timeSaveOrAddId'))).click() # So long as we're not on the last element, head back to the "add time" page to loop through again if elems[-1] != elem: web_driver_wait.until( expected_conditions.presence_of_element_located( (By.ID, 'addTime'))).click()
def test_it_can_handle_multiple_config_files(tmpdir, empty_config): import json_config a = json_config.connect(tmpdir.join('unique_file_a.json').strpath) b = json_config.connect(tmpdir.join('unique_file_b.json').strpath) a['test'] = 'A success' b['test'] = 'B success' empty_config['unique'] = 'empty_config success' assert a['test'] == 'A success' assert b['test'] == 'B success' assert a is not b empty_config.block() a.block() b.block() a_actual = json.load(open(tmpdir.join('unique_file_a.json').strpath)) b_actual = json.load(open(tmpdir.join('unique_file_b.json').strpath)) assert not a_actual == b_actual assert a_actual['test'] == 'A success' assert b_actual['test'] == 'B success'
def __init__(self, renderer=None): GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.setup(27, GPIO.OUT) GPIO.setup(22, GPIO.OUT) recognizer = Recognizer() recognizer.dynamic_energy_threshold = False recognizer.energy_threshold = 1000 self.recognizer = recognizer self.microphone = Microphone() self.susi = susi self.renderer = renderer try: res = requests.get('http://ip-api.com/json').json() self.susi.update_location(longitude=res['lon'], latitude=res['lat']) except ConnectionError as e: logging.error(e) self.config = json_config.connect('config.json') if self.config['usage_mode'] == 'authenticated': try: susi.sign_in( email=self.config['login_credentials']['email'], password=self.config['login_credentials']['password']) except Exception: print( 'Some error occurred in login. Check you login details in config.json' ) if self.config['hotword_engine'] == 'Snowboy': from main.hotword_engine import SnowboyDetector self.hotword_detector = SnowboyDetector() else: from main.hotword_engine import PocketSphinxDetector self.hotword_detector = PocketSphinxDetector() if self.config['wake_button'] == 'enabled': if self.config['device'] == 'RaspberryPi': from ..hardware_components import RaspberryPiWakeButton self.wake_button = RaspberryPiWakeButton() else: self.wake_button = None else: self.wake_button = None
def loaded_config(tmpdir, mocker): """ :type tmpdir: py._path.local.LocalPath :type mocker: pytest_mock.MockFixture """ import json_config config_asset = dir_tests('sample_assets', 'sample_config_small.json') loaded_config_file = tmpdir.join('sample_config_small.json') shutil.copyfile(config_asset, loaded_config_file.strpath) config = json_config.connect(loaded_config_file.strpath) mocker.spy(config, u'save') return config
def __init__(self): QMainWindow.__init__(self) self.resources = resources # Build Absolute Paths self.main_abs_path = os.path.dirname(__file__) self.settings_abs_path = os.path.join(self.main_abs_path, self.SETTINGS_PATH) # Make data folder if it doesn't exist if not os.path.isdir(self.DATA_PATH): os.mkdir(self.DATA_PATH) self.config = json_config.connect(self.settings_abs_path) self.ui = MainInterface(self, self.config) self.widgets = WidgetRunner(self.ui, self.config, self)
def test_readme_example(tmpdir): """:type tmpdir: py._path.local.LocalPath""" import json_config config = json_config.connect(tmpdir.join('categories.json').strpath) assert repr(config) == 'Connect({})' config['comics']['dc']['batman']['antagonists'] = [ 'Scarecrow', 'The Joker', 'Bane' ] config['comics']['marvel']['ironman']['antagonists'] = 'Ultron' serialize_expected = dedent(""" { "comics": { "dc": { "batman": { "antagonists": [ "Scarecrow", "The Joker", "Bane" ] } }, "marvel": { "ironman": { "antagonists": "Ultron" } } } } """)[1:-1] assert (config.serialize()) == serialize_expected with tmpdir.join('categories.json').open() as f: written = f.read() assert written == serialize_expected
def test_usage_example(tmpdir): """:type tmpdir: py._path.local.LocalPath""" import json_config config = json_config.connect(tmpdir.join('config.json').strpath) config['root'] = '/var/www/html/' assert str(config['root']) == '/var/www/html/' assert repr(config['root']) == "'/var/www/html/'" assert repr(config) == "Connect({'root': '/var/www/html/'})" with tmpdir.join('config.json').open() as f: written = f.read() expected = dedent(""" { "root": "/var/www/html/" } """)[1:-1] assert written == expected
def getMedia(search_query): """ :param search_query: String to search service for :return: """ media_models = [] cfg = json_config.connect("credentials.json") client_id = cfg["imgur"]["clientID"] client_secret = cfg["imgur"]["clientSecret"] client = ImgurClient(client_id, client_secret) items = client.gallery_search(search_query, sort="viral") for item in items: if item.is_album is True: continue created = datetime.fromtimestamp(item.datetime).isoformat() thumbnail_url = re.sub(r"(\.[a-z]{3,4})$", "m\\1", item.link) attrs = { "name": item.title, "service": 'Imgur', "mediaURL": item.link, "source": item.link, "type": 'image', "created": created, "thumbnailURL": thumbnail_url, "credit": 'http://imgur.com/user/' + item.account_url, } media = MediaModel(attrs) media_models.append(media) return media_models
def __init__(self): recognizer = Recognizer() recognizer.dynamic_energy_threshold = False recognizer.energy_threshold = 1000 self.recognizer = recognizer self.microphone = Microphone() self.susi = susi self.config = json_config.connect('config.json') if self.config['hotword_engine'] == 'Snowboy': from main.hotword_engine import SnowboyDetector self.hotword_detector = SnowboyDetector() else: from main.hotword_engine import PocketSphinxDetector self.hotword_detector = PocketSphinxDetector() if self.config['wake_button'] == 'enabled': if self.config['device'] == 'RaspberryPi': from ..hardware_components import RaspberryPiWakeButton self.wake_button = RaspberryPiWakeButton() else: self.wake_button = None else: self.wake_button = None
import re import uuid import os import subprocess import logging import requests import json_config import geocoder current_folder = os.path.dirname(os.path.abspath(__file__)) logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) config = json_config.connect('/home/pi/SUSI.AI/config.json') user = config['login_credentials']['email'] password = config['login_credentials']['password'] room = config['room_name'] def get_token(login, password): url = 'http://api.susi.ai/aaa/login.json?type=access-token' PARAMS = { 'login': login, 'password': password, } r1 = requests.get(url, params=PARAMS).json() return r1['access_token']
def main() -> None: config = json_config.connect( join(dirname(__file__), '..', 'config', 'config.json')) webdriver_driver = str.lower(config['webdriver']['driver'] or '') webdriver_path = config['webdriver']['path'] if not webdriver_path: print('Config Error: You must specify a valid webdriver path.') sys.exit(1) if webdriver_driver == 'chrome': browser = webdriver.Chrome(executable_path=webdriver_path) elif webdriver_driver == 'firefox': browser = webdriver.Firefox(executable_path=webdriver_path) elif webdriver_driver == 'edge': browser = webdriver.Edge(executable_path=webdriver_path) elif webdriver_driver == 'ie': browser = webdriver.Ie(executable_path=webdriver_path) elif webdriver_driver == 'safari': browser = webdriver.Safari(executable_path=webdriver_path) elif webdriver_driver == 'opera': browser = webdriver.Opera(executable_path=webdriver_path) elif webdriver_driver == 'phantomjs': browser = webdriver.PhantomJS(executable_path=webdriver_path) elif webdriver_driver == 'webkitgtk': browser = webdriver.WebKitGTK(executable_path=webdriver_path) else: print( 'Config Error: You must specify a valid supported webdriver. ' 'Options: chrome, firefox, edge, ie, safari, opera, phantomjs, webkitgtk' ) sys.exit(1) web_driver_wait = WebDriverWait( browser, float(config['webdriver']['timeout']) if config['webdriver']['timeout'] else 2) # MNSU eServices browser.get(config['eservices']['url']) # Login elem = web_driver_wait.until( expected_conditions.presence_of_element_located((By.ID, 'userName'))) username = config['eservices']['username'] if config['eservices'][ 'username'] else input('eServices Username:'******'password'))) pwd = config['eservices']['password'] if config['eservices'][ 'password'] else get_password_from_terminal(config) elem.send_keys(pwd + Keys.RETURN) web_driver_wait.until( expected_conditions.title_contains('Student Employment')) # Days where time has already been entered, so we don't go over them again (wasting time) days_entered = list() try: elems = web_driver_wait.until( expected_conditions.presence_of_all_elements_located( (By.CSS_SELECTOR, 'tbody > tr'))) except selenium_exceptions.TimeoutException: # if no time has been entered, selenium will timeout searching for elements elems = list() for elem in elems: txt = elem.find_element_by_css_selector('td').text if txt != 'Total Hours': days_entered.append(txt) standardize_dates(days_entered) # Go to the "add time" page elem = web_driver_wait.until( expected_conditions.presence_of_element_located((By.ID, 'addTime'))) elem.click() specific_file = input('Load from specific file? (empty for default.json, ' 'specify the filename without json extension):') if not specific_file: submit_times_from_file(web_driver_wait, skip_days=days_entered) else: submit_times_from_file(web_driver_wait, specific_file, days_entered) browser.quit()
def speaker_config(): room_name = request.args.get('room_name') config = json_config.connect(config_json_folder) config['room_name'] = room_name
#!/usr/bin/env python # coding=utf-8 import json_config import os config = json_config.connect('categories.json') config['comics']['dc']['batman']['antagonists'] = ['Scarecrow', 'The Joker', 'Bane'] config['comics']['marvel']['ironman']['antagonists'] = 'Ultron' print(config.serialize()) os.remove('categories.json')
def __init__(self, renderer=None): try: import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) GPIO.setup(27, GPIO.OUT) GPIO.setup(22, GPIO.OUT) except ImportError: logger.warning("This device doesn't have GPIO port") except RuntimeError as e: logger.error(e) pass thread1 = Thread(target=self.server_checker, name="Thread1") thread1.daemon = True thread1.start() recognizer = Recognizer() recognizer.dynamic_energy_threshold = False recognizer.energy_threshold = 1000 self.recognizer = recognizer self.microphone = Microphone() self.susi = susi self.renderer = renderer self.server_url = "https://127.0.0.1:4000" self.action_schduler = ActionScheduler() self.action_schduler.start() try: res = requests.get('http://ip-api.com/json').json() self.susi.update_location( longitude=res['lon'], latitude=res['lat'], country_name=res['country'], country_code=res['countryCode']) except ConnectionError as e: logger.error(e) self.config = json_config.connect('config.json') if self.config['usage_mode'] == 'authenticated': try: susi.sign_in(email=self.config['login_credentials']['email'], password=self.config['login_credentials']['password']) except Exception as e: logger.error('Some error occurred in login. Check you login details in config.json.\n%s', e) if self.config['hotword_engine'] == 'Snowboy': from ..hotword_engine.snowboy_detector import SnowboyDetector self.hotword_detector = SnowboyDetector() else: from ..hotword_engine.sphinx_detector import PocketSphinxDetector self.hotword_detector = PocketSphinxDetector() if self.config['WakeButton'] == 'enabled': logger.info("Susi has the wake button enabled") if self.config['Device'] == 'RaspberryPi': logger.info("Susi runs on a RaspberryPi") from ..hardware_components import RaspberryPiWakeButton self.wake_button = RaspberryPiWakeButton() else: logger.warning("Susi is not running on a RaspberryPi") self.wake_button = None else: logger.warning("Susi has the wake button disabled") self.wake_button = None
def __init__(self, conffile=None, data_dir="."): if 'XDG_CONFIG_HOME' in os.environ: confdir = os.path.join(os.environ['XDG_CONFIG_HOME'], "SUSI.AI") else: confdir = os.path.join(os.environ['HOME'], ".config", "SUSI.AI") if conffile: self.conffile = conffile else: self.conffile = os.path.join(confdir, "config.json") if not os.path.exists(confdir): os.makedirs(confdir) self.defaults = { 'roomname': { 'default': 'Office' }, 'language': { 'default': 'en_US' }, 'device': { 'default': 'Desktop' }, 'wakebutton': { 'default': 'enabled', 'options': ['enabled', 'disabled', 'not available'] }, 'stt': { 'default': 'google', 'options': [ 'google', 'watson', 'bing', 'pocketsphinx', 'deepspeech-local' ] }, 'tts': { 'default': 'google', 'options': ['google', 'watson', 'flite'] }, 'watson.stt.user': { 'default': '' }, 'watson.stt.pass': { 'default': '' }, 'watson.tts.user': { 'default': '' }, 'watson.tts.pass': { 'default': '' }, 'watson.tts.voice': { 'default': '' }, 'bing.api': { 'default': '' }, 'susi.user': { 'default': '' }, 'susi.pass': { 'default': '' }, 'susi.mode': { 'default': 'anonymous', 'options': ['anonymous', 'authenticated'] }, 'hotword.engine': { 'default': 'Snowboy', 'options': ['Snowboy', 'PocketSphinx'] }, 'hotword.model': { 'default': '' }, 'path.base': { 'default': '.' }, 'path.flite_speech': { 'default': 'susi_linux/extras/cmu_us_slt.flitevox' }, 'path.sound.detection': { 'default': 'susi_linux/extras/detection-bell.wav' }, 'path.sound.problem': { 'default': 'susi_linux/extras/problem.wav' }, 'path.sound.error.recognition': { 'default': 'susi_linux/extras/recognition-error.wav' }, 'path.sound.error.timeout': { 'default': 'susi_linux/extras/error-tada.wav' } } self.config = json_config.connect(self.conffile) for k, v in self.defaults.items(): self.config.setdefault(k, v['default']) self.susiai_path = os.path.realpath( os.path.join(os.path.dirname(os.path.realpath(__file__)), "../../.."))
""" Authentication Generator script for Susi Hardware. Run this script and input options to generate a file for using SUSI in authenticated mode To run this file use python3 authentication.py <choice_to_be authenticated> <email> <password> """ import json_config import sys config = json_config.connect('config.json') def authenticating(): """Method for setting authentication parameters in the configuration :return: None """ try: # choice = input('Do you wish to use SUSI in Authenticated Mode? (y/n)\n') choice = sys.argv[1] print(choice) if choice == 'y': # email = input('Enter SUSI Sign-in Email Address: ') email = sys.argv[2] print(email) # password = input('Enter SUSI Sign-in Password: '******'usage_mode'] = 'authenticated' config['login_credentials']['email'] = email config['login_credentials']['password'] = password elif choice == 'n': print('Setting anonymous mode as default') config['usage_mode'] = 'anonymous' else:
#!/usr/bin/env python # coding=utf-8 import json_config import os config = json_config.connect('categories.json') config['comics']['dc']['batman']['antagonists'] = [ 'Scarecrow', 'The Joker', 'Bane' ] config['comics']['marvel']['ironman']['antagonists'] = 'Ultron' print(config.serialize()) os.remove('categories.json')