def main(): questions = [ { "type": "list", "message": "Select an action:", "choices": ["Upload", "Download", Choice(value=None, name="Exit")], "default": None, }, { "type": "list", "message": "Select regions:", "choices": [ Choice("ap-southeast-2", name="Sydney"), Choice("ap-southeast-1", name="Singapore"), Separator(), "us-east-1", "us-east-2", ], "multiselect": True, "transformer": lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected", "when": lambda result: result[0] is not None, }, ] result = prompt(questions=questions)
def main(): fruit = inquirer.rawlist( message="Pick your favourites:", choices=[ "Apple", "Orange", "Peach", "Cherry", "Melon", "Strawberry", "Grapes", ], default=3, multiselect=True, transformer=lambda result: ", ".join(result), validate=lambda result: len(result) > 1, invalid_message="Minimum 2 selections", ).execute() method = inquirer.rawlist( message="Select your preferred method:", choices=[ Choice(name="Delivery", value="dl"), Choice(name="Pick Up", value="pk"), Separator(line=15 * "*"), Choice(name="Car Park", value="cp"), Choice(name="Third Party", value="tp"), ], ).execute()
def getDeviceName() -> str: return inquirer.select( message='Select your device', choices=[ Choice('respeaker2', name='Respeaker 2'), Choice('respeaker4', name='Respeaker 4-mic array'), Choice('respeaker4MicLinearArray', name='Respeaker 4 mic linear array'), Choice('respeaker6MicArray', name='Respeaker 6 mic array') ] ).execute()
def main(): questions = [ { "type": "rawlist", "choices": [ "Apple", "Orange", "Peach", "Cherry", "Melon", "Strawberry", "Grapes", ], "message": "Pick your favourites:", "default": 3, "multiselect": True, "transformer": lambda result: ", ".join(result), "validate": lambda result: len(result) > 1, "invalid_message": "Minimum 2 selections", }, { "type": "rawlist", "choices": [ Choice(name="Delivery", value="dl"), Choice(name="Pick Up", value="pk"), Separator(line=15 * "*"), Choice(name="Car Park", value="cp"), Choice(name="Third Party", value="tp"), ], "message": "Select your preferred method:", }, ] result = prompt(questions)
def test_choice_multi(self): choice = [Choice(1), Choice(2), Choice(3, None, True)] default = 4 control = InquirerPyListControl( choices=choice, default=default, pointer=INQUIRERPY_POINTER_SEQUENCE, marker=INQUIRERPY_POINTER_SEQUENCE, session_result=None, multiselect=True, marker_pl=" ", ) self.assertEqual(control.selection, { "name": "1", "value": 1, "enabled": False }) self.assertEqual( control.choices, [ { "enabled": False, "name": "1", "value": 1 }, { "enabled": False, "name": "2", "value": 2 }, { "enabled": True, "name": "3", "value": 3 }, ], )
def main(): action = inquirer.select( message="Select an action:", choices=[ "Upload", "Download", Choice(value=None, name="Exit"), ], default=None, ).execute() if action: region = inquirer.select( message="Select regions:", choices=[ Choice("ap-southeast-2", name="Sydney"), Choice("ap-southeast-1", name="Singapore"), Separator(), "us-east-1", "us-east-2", ], multiselect=True, transformer=lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected", ).execute()
def uninstall(c): """卸载""" # if not c.config.sudo.password: # c.run('fab uninstall --prompt-for-sudo-password', echo=False) # return result = prompt([{ 'type': 'list', 'message': gettext('uninstall'), 'choices': ['node', 'python', Choice('', gettext('cancel'))] }]) if result[0] == 'python': hint('uninstall Python') c.run('brew uninstall [email protected]') c.sudo('rm -rf /usr/local/lib/python3.10/') if result[0] == 'node': hint('uninstall Node.js') c.run('brew uninstall node') c.sudo('rm -rf /usr/local/lib/node_modules/')
def install(c, pypi_mirror=True): """安装""" questions = [{ 'type': 'list', 'message': gettext('HTTP Proxy'), 'choices': ['127.0.0.1:7890', Choice('', 'No proxy')], 'name': 'proxy' }, { 'type': 'checkbox', 'message': gettext('install'), 'instruction': '(Space for select)', 'transformer': lambda result: ', '.join(result) if len(result) > 0 else '', 'validate': lambda result: len(result) > 0, 'invalid_message': 'should be at least 1 selection', 'choices': [ Separator(), Choice('android', 'Android'), Choice('ios', 'iOS / macOS'), Choice('java', 'Java'), Choice('python', 'Python'), Separator('-- Database ---'), Choice('mysql', 'MySQL'), Choice('redis', 'Redis'), Separator('-- Front-end --'), Choice('angular', 'Angular'), 'gulp', Separator('-- Apps -------'), Choice('apps', 'GitHub Desktop, Google Chrome, Postman, Visual Studio Code'), Separator('-- Fonts ------'), Choice('font-cascadia-code', 'Cascadia Code'), Choice('font-fira-code', 'Fira Code'), Separator('-- Others -----'), Choice('docker', 'Docker'), 'docsify' 'fastlane', Choice('mysqlworkbench', 'MySQL Workbench'), Separator() ], 'name': 'roles' }] # yapf: disable result = prompt(questions) proxy = result['proxy'] roles = result['roles'] if not roles: return if HTTP_PROXY != proxy: c.run(f'sed -i "" "s|HTTP_PROXY = \'{HTTP_PROXY}\'|HTTP_PROXY = \'{proxy}\'|g" fabfile.py') # if 'zh_CN' in locale.getdefaultlocale(): # hint('configure RubyGems') # c.run('gem sources --add https://mirrors.aliyun.com/rubygems/ --remove https://rubygems.org/') if 'android' in roles: hint('install Android Studio, ktlint') c.run('brew install --cask android-studio') c.run('brew install ktlint') if 'ios' in roles: hint('install CocoaPods, SwiftFormat, SwiftLint') c.run('brew install cocoapods swiftformat swiftlint') if 'java' in roles: hint('install OpenJDK') c.run('brew install openjdk') if 'python' in roles: hint('install Pipenv, Black, isort, Pylint, YAPF') c.run(f'pip install pipenv black isort pylint yapf{f" -i {PYPI_MIRROR}" if pypi_mirror else ""}') # 数据库 if 'mysql' in roles: hint('install MySQL') c.run('brew install mysql') if 'redis' in roles: hint('install Redis') c.run('brew install redis') # 前端 if 'angular' in roles or 'gulp' in roles: hint('install Node.js') c.run('brew install node') if 'zh_CN' in locale.getdefaultlocale(): hint('configure npm') c.run('npm config set registry https://registry.npmmirror.com') if 'angular' in roles: hint('install Angular CLI') c.run('npm install -g @angular/cli') if 'gulp' in roles: hint('install gulp-cli') c.run('npm install -g gulp-cli') if 'docsify' in roles: hint('install docsify-cli') c.run('npm install -g docsify-cli') # 应用 if 'apps' in roles: hint('install GitHub Desktop, Google Chrome, Postman, Visual Studio Code') c.run('brew install --cask github google-chrome postman visual-studio-code') # 字体 if 'font-cascadia-code' in roles: hint('install Cascadia Code') c.run('brew tap homebrew/cask-fonts') c.run('brew install --cask font-cascadia-code') if 'font-fira-code' in roles: hint('install Fira Code') c.run('brew tap homebrew/cask-fonts') c.run('brew install --cask font-fira-code') # 其他 if 'docker' in roles: hint('install Docker') c.run('brew install --cask docker') if 'fastlane' in roles: hint('install fastlane') c.run('brew install fastlane') if 'mysqlworkbench' in roles: hint('install MySQL Workbench') c.run('brew install --cask mysqlworkbench') cleanup(c)
from InquirerPy import inquirer from InquirerPy.base.control import Choice from InquirerPy.separator import Separator question1_choice = [ Separator(), Choice("ap-southeast-2", name="Sydney", enabled=True), Choice("ap-southeast-1", name="Singapore", enabled=False), Separator(), "us-east-1", "us-west-1", Separator(), ] def question2_choice(_): return [ "Apple", "Cherry", "Orange", "Peach", "Melon", "Strawberry", "Grapes", ] def main(): regions = inquirer.checkbox( message="Select regions:", choices=question1_choice,
from pathlib import Path from threading import Event, Thread from typing import Optional, Tuple from AliceCli.Version import Version IP_REGEX = re.compile(r'^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$') SSH: Optional[paramiko.SSHClient] = None CONNECTED_TO: str = '' ANIMATION_FLAG = Event() ANIMATION_THREAD: Optional[Thread] = None HIDDEN = '[hidden]' NO_EMPTY = 'Cannot be empty' COUNTRY_CODES = [ Choice('CH', name='Switzerland'), Choice('DE', name='Germany'), Choice('US', name='United States of America (the)'), Choice('AU', name='Australia'), Choice('GB', name='United Kingdom of Great Britain and Northern Ireland (the)'), Choice('FR', name='France'), Choice('IT', name='Italy'), Choice('PL', name='Poland'), Choice('PT', name='Portugal'), Choice('BR', name='Brazil'), Separator(), Choice('AF', name='Afghanistan'), Choice('AL', name='Albania'), Choice('DZ', name='Algeria'), Choice('AS', name='American Samoa'), Choice('AD', name='Andorra'),
def prepareSdCard(ctx: click.Context): # NOSONAR if not commons.isAdmin(): commons.returnToMainMenu(ctx=ctx, pause=True, message='You need admin rights for this, please restart Alice CLI with admin elevated rights.') return operatingSystem = platform.system().lower() balenaExecutablePath = getBalenaPath() flasherAvailable = balenaExecutablePath != None downloadsPath = Path.home() / 'Downloads' doFlash = inquirer.confirm( message='Do you want to flash your SD card with Raspberry PI OS?', default=False ).execute() installBalena = False if not flasherAvailable: installBalena = inquirer.confirm( message='balena-cli was not found on your system. It is required for working with SD cards, do you want to install it?', default=True ) if not flasherAvailable and not installBalena: commons.returnToMainMenu(ctx, pause=True, message='Well then, I cannot work with your SD card without the appropriate tool to do it') return elif not flasherAvailable and installBalena: commons.printInfo('Installing Balena-cli, please wait...') balenaVersion = 'v13.1.1' if operatingSystem == 'windows': url = f'https://github.com/balena-io/balena-cli/releases/download/{balenaVersion}/balena-cli-{balenaVersion}-windows-x64-installer.exe' elif operatingSystem == 'linux': url = f'https://github.com/balena-io/balena-cli/releases/download/{balenaVersion}/balena-cli-{balenaVersion}-linux-x64-standalone.zip' else: url = f'https://github.com/balena-io/balena-cli/releases/download/{balenaVersion}/balena-cli-{balenaVersion}-macOS-x64-installer.pkg' destination = downloadsPath / url.split('/')[-1] if destination.exists(): commons.printInfo(f'Skipping download, using existing: {destination}') else: commons.printInfo('Downloading...') doDownload(url=url, destination=destination) if operatingSystem == 'windows': commons.printInfo("Starting the installation, please follow the instructions and come back when it's done!") subprocess.Popen(str(destination).split(), shell=True) click.pause('Press a key when the installation process is done! Please close your terminal and restart it to continue the flashing process') exit(0) elif operatingSystem == 'linux': executablePath = Path(balenaExecutablePath) commons.printInfo(f"Install dir: {executablePath.parent}") commons.printInfo(f'Extracting {destination} to {executablePath.name}...') archive = zipfile.ZipFile(destination) archive.extractall() # extract to ./balena-cli/ i.e. sub dir of working directory. commons.printInfo('Setting ./balena-cli/balena as executable...') # set executable permission # from https://stackoverflow.com/questions/12791997/how-do-you-do-a-simple-chmod-x-from-within-python executablePath.chmod(509) # now shell `./balena-cli/balena version` works commons.printInfo('Adding ./balena-cli to PATH...') os.environ['PATH'] += os.pathsep + str(executablePath.parent) sysPath = os.environ['PATH'] commons.printInfo(f'New PATH: {sysPath}') click.pause('Installation Done. Press a key') else: click.pause('I have no idea how to install stuff on Mac, so I have downloaded the tool for you, please install it. Oh, and contact Psycho to let him know how to install a pkg file on Mac ;-)') exit(0) if doFlash: images = list() commons.printInfo('Checking for Raspberry PI OS images, please wait....') # Potential local files downloadsPath = Path.home() / 'Downloads' for file in downloadsPath.glob('*raspi*.zip'): images.append(str(file)) images.append('https://downloads.raspberrypi.org/raspios_lite_armhf/images/raspios_lite_armhf-2021-05-28/2021-05-07-raspios-buster-armhf-lite.zip') # Deactivated for now, we enforce Buster only! # directories = list() # Get a list of available images online # url = 'https://downloads.raspberrypi.org/raspios_lite_armhf/images/' # page = requests.get(url) # if page.status_code == 200: # soup = BeautifulSoup(page.text, features='html.parser') # directories = [url + node.get('href') for node in soup.find_all('a') if node.get('href').endswith('/')] # if directories: # directories.pop(0) # This is the return link, remove it... # # for directory in directories: # page = requests.get(directory) # if page.status_code == 200: # soup = BeautifulSoup(page.text, features='html.parser') # images.extend([directory + node.get('href') for node in soup.find_all('a') if node.get('href').endswith('.zip')]) commons.printInfo('Checking for available SD card drives, please wait....') drives = list() sdCards = getSdCards() for sdCard in sdCards: drives.append(Choice(sdCard, name=sdCard)) if not drives: commons.returnToMainMenu(ctx, pause=True, message='Please insert your SD card first') return image = inquirer.select( message='Select the image you want to flash. Keep in mind we only officially support the "Buster" Raspberry pi OS distro!', choices=images ).execute() drive = inquirer.select( message='Select your SD card drive', choices=drives ).execute() commons.printInfo("Flashing SD card, please wait") if image.startswith('https'): file = downloadsPath / image.split('/')[-1] doDownload(url=image, destination=file) else: file = image if operatingSystem == 'windows' or operatingSystem == 'linux': if operatingSystem == 'linux': # this only works on distros with "sudo" support. balenaCommand = f'sudo {balenaExecutablePath} local flash {str(file)} --drive {drive} --yes' else: balenaCommand = f'balena local flash {str(file)} --drive {drive} --yes'.split() subprocess.run(balenaCommand, shell=True) time.sleep(5) else: commons.returnToMainMenu(ctx, pause=True, message='Flashing only supported on Windows and Linux systems for now. If you have the knowledge to implement it on other systems, feel free to pull request!') return click.pause('Flashing complete. Please eject, unplug and replug your SD back, then press any key to continue...') ssid = inquirer.text( message='Enter the name of your Wifi network', validate=EmptyInputValidator(commons.NO_EMPTY) ).execute() password = inquirer.secret( message='Enter your Wifi network\'s key', transformer=lambda _: commons.HIDDEN ).execute() country = inquirer.select( message='Select your country. This is used for your Wi-Fi settings!', default='EN', choices=commons.COUNTRY_CODES ).execute() drives = list() drive = '' if operatingSystem == 'linux': # typically, boot partition is the first increment of SD device # e.g. on /dev/sda drive /dev/sda1 is "boot" and /dev/sda2 is "rootfs" # Lookup up the boot mount point path via lsblk sdCards = getSdCards() command = f'sudo lsblk -o PATH,FSTYPE,LABEL,MOUNTPOINT --json' output = subprocess.run(command, capture_output=True, shell=True).stdout.decode() blkDevices = json.loads(output) for device in blkDevices['blockdevices']: if device["path"].startswith(tuple(sdCards)) and device['fstype'] == 'vfat' and device['label'] == 'boot': drives.append(Choice(value=device, name=device['path'])) if len(drives) == 0: commons.printError(f'For some reason I cannot find the SD boot partition mount point {drive}.') commons.returnToMainMenu(ctx, pause=True, message="I'm really sorry, but I just can't continue without this info, sorry for wasting your time...") if len(drives) == 1: device = drives[0].value commons.printInfo(f'Auto-selected {device["path"]}.') drive = device else: j = 0 while len(drives) <= 0: j += 1 for dp in psutil.disk_partitions(): if 'rw,removable' not in dp.opts.lower(): continue drives.append(dp.device) if not drives: if j < 3: drives = list() commons.printError('For some reason I cannot find any writable SD partition. Please eject then unplug, replug your SD back and press any key to continue') click.pause() else: break if not drive: drive = inquirer.select( message='Please select the correct SD `boot` partition', choices=drives ).execute() needToUnmount = False mountDir = '' if operatingSystem == 'linux': # if device has not been mounted yet, mount in temp directory if drive['mountpoint'] is None: needToUnmount = True mountDir = tempfile.mkdtemp(prefix='alice-cli-mount-') command = f"sudo mount {drive['path']} {mountDir}" result = subprocess.run(command, capture_output=True, shell=True) if not result.returncode == 0: commons.printError(f"Could not mount {drive['path']} to {mountDir}.") commons.returnToMainMenu(ctx, pause=True) drive['mountpoint'] = mountDir commons.printInfo(f"Mounted {drive['path']} to {mountDir} temporarily.") else: commons.printInfo(f"{drive['path']} is already mounted to {drive['mountpoint']}.") drive = drive['mountpoint'] # Now let's enable SSH and Wi-Fi on boot. commons.printInfo('Adding ssh & wifi to SD boot....') sshFile = Path(drive, 'ssh') sshFile.unlink(missing_ok=True) sshFile.touch() content = f'country={country}\n' content += 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n' content += 'update_config=1\n' content += 'network={\n' content += f'\tssid="{ssid}"\n' content += '\tscan_ssid=1\n' content += f'\tpsk="{password}"\n' content += '\tkey_mgmt=WPA-PSK\n' content += '}' Path(drive, 'wpa_supplicant.conf').write_text(content) if operatingSystem == 'linux' and needToUnmount and mountDir: command = f'sudo umount {drive}' result = subprocess.run(command, capture_output=True, shell=True) if not result.returncode == 0: commons.printError(f'Could not unmount {drive}.') commons.returnToMainMenu(ctx, pause=True) commons.printInfo(f'Unmounted {drive}') # only deletes empty dirs, so if unmounting failed for whatever reasons, we don't destroy anything os.rmdir(mountDir) commons.returnToMainMenu(ctx, pause=True, message='SD card is ready. Please plug it in your device and boot it!')
def installAlice(ctx: click.Context, force: bool): click.secho('\nInstalling Alice!', fg='yellow') result = sshCmdWithReturn('test -d ~/ProjectAlice/ && echo "1"')[0].readline() if result: if not force: commons.printError('Alice seems to already exist on that host') confirm = inquirer.confirm( message='Erase and reinstall?', default=False ).execute() if confirm: commons.returnToMainMenu(ctx) return sshCmd('sudo systemctl stop ProjectAlice') sshCmd('sudo rm -rf ~/ProjectAlice') adminPinCode = inquirer.secret( message='Enter an admin pin code. It must be made of 4 characters, all digits only. (default: 1234)', default='1234', validate=lambda code: code.isdigit() and int(code) < 10000, invalid_message='Pin must be 4 numbers', transformer=lambda _: commons.HIDDEN ).execute() mqttHost = inquirer.text( message='Mqtt hostname', default='localhost', validate=EmptyInputValidator(commons.NO_EMPTY) ).execute() mqttPort = inquirer.number( message='Mqtt port', default=1883, validate=EmptyInputValidator(commons.NO_EMPTY) ).execute() activeLanguage = inquirer.select( message='What language should Alice be using?', default='en', choices=[ Choice('en', name='English'), Choice('de', name='German'), Choice('fr', name='French'), Choice('it', name='Italian'), Choice('pl', name='Polish'), ] ).execute() activeCountryCode = inquirer.select( message='Enter the country code to use.', default='EN', choices=commons.COUNTRY_CODES ).execute() releaseType = inquirer.select( message='What releases do you want to receive? If you are unsure, leave this to Stable releases!', default='master', choices=[ Choice('master', name='Stable releases'), Choice('rc', name='Release candidates'), Choice('beta', name='Beta releases'), Choice('alpha', name='Alpha releases') ] ).execute() audioDevice = inquirer.select( message='Select your audio hardware if listed', default='respeaker2', choices=[ Choice('respeaker2', name='Respeaker 2 mics'), Choice('respeaker4', name='Respeaker 4 mic array'), Choice('respeaker4MicLinear', name='Respeaker 4 mic linear array'), Choice('respeaker6', name='Respeaker 6 mic array'), Choice('respeaker7', name='Respeaker 7'), Choice('respeakerCoreV2', name='Respeaker Core version 2'), Choice('googleAIY', name='Google AIY'), Choice('googleAIY2', name='Google AIY 2'), Choice('matrixCreator', name='Matrix Creator'), Choice('matrixVoice', name='Matrix Voice'), Choice('ps3eye', name='PS3 Eye'), Choice('jabra410', name='Jabra 410'), Choice(None) ] ).execute() soundInstalled = inquirer.confirm( message='Did you already install your sound hardware using Alice CLI or confirmed it to be working?', default=False ).execute() installHLC = inquirer.confirm( message='Do you want to install HLC? HLC can pilot leds such as the ones on Respeakers to provide visual feedback.', default=False ).execute() advancedConfigs = inquirer.confirm( message='Do you want to set more advanced configs? If you do, DO NOT ABORT IN THE MIDDLE!', default=False ).execute() asr = 'coqui' tts = 'pico' awsAccessKey = '' awsSecretKey = '' googleServiceFile = '' shortReplies = False devMode = False githubUsername = '' githubToken = '' enableDataStoring = True skillAutoUpdate = True if advancedConfigs: asr = inquirer.select( message='Select the ASR engine you want to use', default='coqui', choices=[ Choice('coqui', name='Coqui'), Choice('snips', name='Snips (English only!)'), Choice('google', name='Google (Online!)'), Choice('deepspeech', name='Deepspeech'), Choice('pocketsphinx', name='PocketSphinx') ] ).execute() tts = inquirer.select( message='Select the TTS engine you want to use', default='pico', choices=[ Choice('pico', name='Coqui'), Choice('mycroft', name='Mycroft'), Choice('amazon', name='Amazon'), Choice('google', name='Google'), Choice('watson', name='Watson') ] ).execute() if tts == 'amazon': awsAccessKey = inquirer.secret( message='Enter your AWS access key', validate=EmptyInputValidator(commons.NO_EMPTY), transformer=lambda _: commons.HIDDEN ).execute() awsSecretKey = inquirer.secret( message='Enter your AWS secret key', validate=EmptyInputValidator(commons.NO_EMPTY), transformer=lambda _: commons.HIDDEN ).execute() if tts == 'google' or asr == 'google': googleServiceFile = inquirer.filepath( message='Enter your Google service file path', default='~/', validate=PathValidator(is_file=True, message='Input is not a file') ).execute() shortReplies = inquirer.confirm( message='Do you want Alice to use short replies?', default=False ).execute() devMode = inquirer.confirm( message='Do you want to activate the developer mode?', default=False ).execute() if devMode: githubUsername = inquirer.text( message='Enter your Github username. This is required for Dev Mode.', validate=EmptyInputValidator(commons.NO_EMPTY) ).execute() githubToken = inquirer.secret( message='Enter your Github access token. This is required for Dev Mode.', validate=EmptyInputValidator(commons.NO_EMPTY), transformer=lambda _: commons.HIDDEN ).execute() enableDataStoring = inquirer.confirm( message='Enable telemetry data storing?', default=True ).execute() skillAutoUpdate = inquirer.confirm( message='Enable skill auto update?', default=True ).execute() commons.waitAnimation() confFile = Path(Path.home(), '.pacli/projectalice.yaml') confFile.parent.mkdir(parents=True, exist_ok=True) updateSource = commons.getUpdateSource(releaseType) try: with requests.get(url=f'https://raw.githubusercontent.com/project-alice-assistant/ProjectAlice/{updateSource}/ProjectAlice.yaml', stream=True) as r: r.raise_for_status() with confFile.open('wb') as fp: for chunk in r.iter_content(chunk_size=8192): if chunk: fp.write(chunk) except Exception as e: commons.printError(f'Failed downloading ProjectAlice.yaml {e}') commons.returnToMainMenu(ctx, pause=True) with confFile.open(mode='r') as f: try: confs = yaml.safe_load(f) except yaml.YAMLError as e: commons.printError(f'Failed reading projectalice.yaml {e}') commons.returnToMainMenu(ctx, pause=True) confs['adminPinCode'] = str(int(adminPinCode)).zfill(4) confs['mqttHost'] = mqttHost confs['mqttPort'] = int(mqttPort) confs['activeLanguage'] = activeLanguage confs['activeCountryCode'] = activeCountryCode confs['useHLC'] = installHLC confs['aliceUpdateChannel'] = releaseType confs['skillsUpdateChannel'] = releaseType confs['ttsLanguage'] = f'{activeLanguage}-{activeCountryCode}' if soundInstalled: confs['installSound'] = False if audioDevice: confs['audioHardware'][audioDevice] = True else: confs['installSound'] = True confs['asr'] = asr confs['awsAccessKey'] = awsAccessKey confs['awsSecretKey'] = awsSecretKey confs['tts'] = tts confs['shortReplies'] = shortReplies confs['devMode'] = devMode confs['githubUsername'] = githubUsername confs['githubToken'] = githubToken confs['enableDataStoring'] = enableDataStoring confs['skillAutoUpdate'] = skillAutoUpdate if googleServiceFile and Path(googleServiceFile).exists(): confs['googleServiceFile'] = Path(googleServiceFile).read_text() if asr == 'google': confs['keepASROffline'] = False if tts in ['amazon', 'google', 'watson']: confs['keepTTSOffline'] = False with confFile.open(mode='w') as f: yaml.dump(confs, f) commons.printSuccess('Generated ProjectAlice.yaml') commons.printInfo('Updating system') sshCmd('sudo apt-get update') sshCmd('sudo apt-get install git -y') sshCmd('git config --global user.name "Han Oter"') sshCmd('git config --global user.email "*****@*****.**"') commons.printInfo('Cloning Alice') sshCmd('git clone https://github.com/project-alice-assistant/ProjectAlice.git ~/ProjectAlice') sftp = commons.SSH.open_sftp() sftp.put(str(confFile), '/home/pi/ProjectAlice/ProjectAlice.yaml') sftp.close() sshCmd('sudo rm /boot/ProjectAlice.yaml') sshCmd('sudo cp ~/ProjectAlice/ProjectAlice.yaml /boot/ProjectAlice.yaml') commons.printInfo('Start install process') sshCmd('cd ~/ProjectAlice/ && python3 main.py') commons.printSuccess('Alice has completed the basic installation! She\'s now working further to complete the installation, let\'s see what she does!') ctx.invoke(systemLogs)
def mainMenu(ctx: click.Context): global CHECKED, VERSION click.clear() if not CHECKED: result = subprocess.run('pip index versions projectalice-cli'.split(), capture_output=True, text=True) if 'error' not in result.stderr.lower(): regex = re.compile( r"INSTALLED:.*(?P<installed>[\d]+\.[\d]+\.[\d]+)\n.*LATEST:.*(?P<latest>[\d]+\.[\d]+\.[\d]+)" ) match = regex.search(result.stdout.strip()) if not match: click.secho(message='Failed checking CLI version\n', fg='red') else: installed = Version.fromString(match.group('installed')) latest = Version.fromString(match.group('latest')) if installed < latest: click.secho( f'Project Alice CLI version {str(installed)}\n', fg='red') click.secho( message= f'CLI version {str(latest)} is available, you should consider updating using `pip install projectalice-cli --upgrade`\n', fg='red') else: click.secho( f'Project Alice CLI version {str(installed)}\n', fg='green') VERSION = str(installed) else: click.secho(message='Failed checking CLI version\n', fg='red') CHECKED = True else: click.echo(f'Project Alice CLI version {VERSION}\n') action = inquirer.select( message='', default=None, choices=[ Separator(line='\n------- Network -------'), Choice(lambda: ctx.invoke(discover), name='Discover devices on network'), Choice(lambda: ctx.invoke(connect), name='Connect to a device'), Separator(line='\n------- Setup -------'), Choice(lambda: ctx.invoke(prepareSdCard), name='Prepare your SD card'), Choice(lambda: ctx.invoke(changePassword), name='Change device\'s password'), Choice(lambda: ctx.invoke(changeHostname), name='Set device\'s name'), Choice(lambda: ctx.invoke(installSoundDevice), name='Install your sound device'), Choice(lambda: ctx.invoke(soundTest), name='Sound test'), Choice(lambda: ctx.invoke(installAlice), name='Install Alice'), Separator(line='\n------- Service -------'), Choice(lambda: ctx.invoke(systemctl, option='start'), name='Start Alice'), Choice(lambda: ctx.invoke(systemctl, option='restart'), name='Restart Alice'), Choice(lambda: ctx.invoke(systemctl, option='stop'), name='Stop Alice'), Choice(lambda: ctx.invoke(systemctl, option='enable'), name='Enable Alice service'), Choice(lambda: ctx.invoke(systemctl, option='disable'), name='Disable Alice service'), Separator(line='\n------- Updates -------'), Choice(lambda: ctx.invoke(updateAlice), name='Update Alice'), Choice(lambda: ctx.invoke(updateSystem), name='Update system'), Choice(lambda: ctx.invoke(upgradeSystem), name='Upgrade system'), Separator(line='\n------- Logs -------'), Choice(lambda: ctx.invoke(reportBug), name='Enable bug report for next session'), Choice(lambda: ctx.invoke(aliceLogs), name='Check Alice logs'), Choice(lambda: ctx.invoke(systemLogs), name='Check system logs'), Separator(line='\n------- Tools -------'), Choice(lambda: ctx.invoke(reboot), name='Reboot device'), Choice(lambda: ctx.invoke(uninstallSoundDevice), name='Uninstall your sound device'), Choice(lambda: ctx.invoke(disableRespeakerLeds), name='Turn off Respeaker bright white leds'), Choice(lambda: sys.exit(0), name='Exit') ]).execute() action()