コード例 #1
0
def mail(msg):
    try:
        emails = get_config('mail')
        auth = get_config('auth')
    except (IOError):
        print(
            '\n\nAn existing mail and/or auth configuration file could not be found at:\n'
            + os.getcwd() + '\config\n\n')
        sys.exit(0)

    port = 465
    sender = str(auth[0])
    password = str(auth[1])

    message = MIMEMultipart("alternative")
    message["Subject"] = "Camera Down!"
    message["From"] = sender

    text = """\
        Hello,
        {}""".format(msg)

    html = """\
        <html>
            <body>
                <p>Hello,<br>
                    {}
                </p>
            </body>
        </html>
    """.format(msg)

    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')

    message.attach(part1)
    message.attach(part2)

    context = ssl.create_default_context()
    with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as server:

        try:
            server.login(sender, password)
        except (smtplib.SMTPAuthenticationError):
            print(
                '\n\nAn invalid auth configuration file has been found. Now exiting...\n\n'
            )
            sys.exit(1)

        for x in range(0, int(len(emails))):
            message["To"] = emails[x]
            try:
                server.sendmail(sender, emails[x], message.as_string())
            except smtplib.SMTPRecipientsRefused:
                print(
                    '\n\nAn invalid mail configuration file has been found. Now exiting...\n\n'
                )
                sys.exit(1)
コード例 #2
0
ファイル: predict.py プロジェクト: dgketchum/itype
def main(params):
    config = get_config(**vars(params))

    checkpoint_dir = os.path.join(params.checkpoint, 'checkpoints')
    figures_dir = os.path.join(params.checkpoint, 'figures')
    checkpoint = [os.path.join(checkpoint_dir, x) for x in os.listdir(checkpoint_dir)][0]

    model = UNet.load_from_checkpoint(checkpoint_path=checkpoint)
    model.freeze()
    model.hparams.dataset_folder = '/media/nvm/itype_/pth_snt/2019'
    model.hparams.batch_size = 1

    if params.metrics:
        trainer = Trainer(
            precision=16,
            gpus=config.device_ct,
            num_nodes=config.node_ct,
            log_every_n_steps=5)

        trainer.test(model)

    loader = model.val_dataloader()
    for i, (x, y) in enumerate(loader):
        out = model(x)
        pred = out.argmax(1)
        x, y, pred = x.squeeze().numpy(), y.squeeze().numpy(), pred.squeeze().numpy()
        fig = os.path.join(figures_dir, '{}.png'.format(i))
        plot_prediction(x, y, pred, model.mode, out_file=fig)
コード例 #3
0
ファイル: train.py プロジェクト: dgketchum/itype
def main(params):

    config = get_config(**vars(params))

    model = UNet(**vars(config))

    log_dir = prepare_output(config)
    logger = TensorBoardLogger(log_dir, name='log')

    checkpoint_callback = ModelCheckpoint(dirpath=os.path.join(
        log_dir, 'checkpoints'),
                                          save_top_k=1,
                                          save_last=True,
                                          monitor='val_acc',
                                          verbose=True)

    lr_monitor = LearningRateMonitor(logging_interval='epoch')

    accelerator = 'ddp' if config.device_ct > 1 else None

    trainer = Trainer(precision=16,
                      min_epochs=50,
                      accelerator=accelerator,
                      gpus=config.device_ct,
                      num_nodes=config.node_ct,
                      callbacks=[checkpoint_callback, lr_monitor],
                      progress_bar_refresh_rate=params.progress,
                      log_every_n_steps=5,
                      logger=logger)

    trainer.fit(model)
コード例 #4
0
ファイル: xai_arg_num.py プロジェクト: qingbol/x_func_args
def main(options):
    config_info = get_config(options)
    # config_info = configure.get_config()
    time_str = time.strftime("%Y%m%d-%H%M")
    file_all = "./log/log_all_" + \
        str(config_info['feature_num']) + "_" + time_str + ".txt"
    file_acc = "./log/log_acc" + \
        str(config_info['feature_num']) + "_" + time_str + ".txt"
    # file_acc = "./log/log_acc.txt"
    xai_func = XaiFunction(config_info, file_all, file_acc)
    with xai_func:
        xai_func.workfolow()
コード例 #5
0
def load_model(nb_name,
               train_batches,
               dev_batches,
               word_to_idx,
               bow_idxs,
               nucleus=None,
               seed=None,
               backup=False):
    config = get_config(nb_name)
    config = update_config(config, train_batches, dev_batches, word_to_idx,
                           bow_idxs)
    if nucleus is not None: config.nucleus = nucleus
    if seed is not None: config.seed = seed
    if backup:
        config.dir_model = config.dir_model.replace('atttglm/', 'backup/')

    model = config.Model(config)
    return model
コード例 #6
0
import socket
import json

from configure import get_config
from protocol import validate_request, make_response
from actions import resolve

config = get_config()
addr, port = config.get('addr'), config.get('port')

try:
    sock = socket.socket()
    sock.bind((addr, port))
    sock.listen(5)
    print(f'Server started at {addr}:{port}')

    while True:
        client, from_address = sock.accept()
        from_ip, from_port = from_address[0], from_address[1]
        print(f'Get connection from {from_ip}:{from_port}')

        b_request = client.recv(config.get('buffersize'))
        request = json.loads(b_request.decode())

        if validate_request(request):
            actions_name = request.get('action')
            controller = resolve(actions_name)

            if controller:
                try:
                    print(f'Client send valid request: {request}')
コード例 #7
0
    def encrypt_enchained(self, msg, recipient, remailers):
        """Encrypt a message, wrap it in commands for a mail2news instance,
        and encrypt it for each of a chain of remailers"""

        tmp_encrypted = str(self.encrypt(msg, recipient["fingerprint"]))

        prev_remailer = None

        for remailer in remailers:
            if prev_remailer:
                tmp_encrypted = self._wrap_for_remailer(
                    tmp_encrypted, prev_remailer)
            else:
                tmp_encrypted = self._wrap_for_aam(tmp_encrypted)

            tmp_encrypted = str(
                self.encrypt(tmp_encrypted, remailer["fingerprint"]))
            tmp_encrypted = "::\nEncrypted: PGP\n\n" + tmp_encrypted

            prev_remailer = remailer

        return tmp_encrypted


if __name__ == "__main__":
    from configure import get_config

    encryptor = MessageEndecryptor("*****@*****.**", [],
                                   get_config()["gpg-dir"])
    print(encryptor.recipients())
コード例 #8
0
ファイル: test_pbs.py プロジェクト: dgketchum/itype
def main(params):
    config = get_config(**vars(params))

    model = UNet(config)
    for k, v in model.hparams.items():
        print(k, v)
コード例 #9
0
def icmp(quiet):

    try:
        poll = get_config('poll')
        hosts = get_config('host')
    except IOError:
        print(
            '\n\nAn existing poll and/or host configuration file could not be found at:\n'
            + os.getcwd() + '/config\n\n')
        sys.exit(1)
    except json.decoder.JSONDecodeError:
        print(
            '\n\nAn invalid host configuration file has been found. Now exiting...\n\n'
        )
        sys.exit(1)

    print(
        '\n\n' + '#####################\n' + '#                   #\n' +
        '#   Polling Hosts   #\n' + '#                   #\n' +
        '#####################\n\n' + 'All hosts will be polled every',
        poll[0], 'second(s).\n' + 'Hosts will be marked as offline after',
        poll[1],
        'unanswered polls.\n' + 'To exit at any time, press CTRL+C.\n\n')

    index = [0] * len(hosts)

    while (True):
        for x in range(0, len(hosts)):
            if (os.name == 'nt'):
                r = subprocess.run(['ping', '-n', '1', hosts[x]],
                                   stdout=subprocess.DEVNULL)
            else:
                r = subprocess.run(['ping', '-c 1', '-w 3', hosts[x]],
                                   stdout=subprocess.DEVNULL)

            if (r.returncode != 0):
                index[x] += 1

                if (index[x] == 1):
                    if (quiet == False):
                        print('Camera', x + 1, ' @ ', hosts[x],
                              ' is offline!  Code: ', r.returncode)
                elif (index[x] == poll[1]):
                    if (quiet == False):
                        print('Camera', x + 1, ' @ ', hosts[x],
                              ' has been offline for', poll[1],
                              'polls! Email notification sent!  Code: ',
                              r.returncode)
                    msg = str('Camera ' + str(x + 1) + ' @ ' + str(hosts[x]) +
                              ' has been offline for ' + str(poll[1]) +
                              ' polls! Code: ' + str(r.returncode))
                    mail(msg)
                    log(msg)
                    #mysql_log(msg)

            elif (r.returncode == 0 and index[x] != 0):
                index[x] = 0
                if (quiet == False):
                    print('Camera', x + 1, ' @ ', hosts[x],
                          ' has come back online!')
        try:
            sleep(poll[0])
        except ValueError:
            print(
                '\n\nAn invalid poll configuration file has been found. Now exiting...\n\n'
            )
            sys.exit(1)