Exemplo n.º 1
0
 def get_account(html):
     # print(html)
     element = etree.HTML(html)
     account_list = element.xpath('//div[@class="user"]/span/text()')
     if len(account_list) > 0:
         # print(account_list[0])
         set_config('account', {'current_account': account_list[0]})
Exemplo n.º 2
0
    async def set_temperature(self, new_temp, zapisz=True):
        czas = utils.czas()
        if zapisz is True and utils.get_config("piec_historia_temperatury", True) is True:
            if utils.dst_time()[0] > 2000:
                utils.set_config("piec_ostatnia_aktualizacja", czas, False)
        curr_temp = int(utils.get_config("piec_temperatura"))

        if curr_temp < new_temp <= (
                int(utils.get_config("piec_temperatura_max", 90)) - int(utils.get_config("piec_temperatura_wg", 5))):
            set_temp = new_temp + int(utils.get_config("piec_temperatura_wg", 5))
            await self.devices.move_servo(utils.map_temp_to_servo(set_temp))

            await uasyncio.sleep_ms(1000)

        elif curr_temp > new_temp >= (
                int(utils.get_config("piec_temperatura_min", 30)) + int(utils.get_config("piec_temperatura_wd", 2))):
            set_temp = new_temp - int(utils.get_config("piec_temperatura_wd", 2))
            await self.devices.move_servo(utils.map_temp_to_servo(set_temp))

            await uasyncio.sleep_ms(1000)

        await self.devices.move_servo(utils.map_temp_to_servo(new_temp))
        utils.set_config("piec_temperatura", int(new_temp))
        if zapisz is True and utils.get_config("piec_historia_temperatury", True) is True:
            if utils.dst_time()[0] > 2000:
                await utils.save_to_hist(new_temp, "piec.hist")

        await uasyncio.sleep_ms(150)
Exemplo n.º 3
0
def create_app(config='CTFd.config'):
    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(config)
        app.jinja_loader = ThemeLoader(os.path.join(app.root_path,
                                                    app.template_folder),
                                       followlinks=True)

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        url = make_url(app.config['SQLALCHEMY_DATABASE_URI'])
        if url.drivername == 'postgres':
            url.drivername = 'postgresql'

        db.init_app(app)

        try:
            if not (url.drivername.startswith('sqlite')
                    or database_exists(url)):
                create_database(url)
            db.create_all()
        except OperationalError:
            db.create_all()
        except ProgrammingError:  ## Database already exists
            pass
        else:
            db.create_all()

        app.db = db

        cache.init_app(app)
        app.cache = cache

        if not get_config('ctf_theme'):
            set_config('ctf_theme', 'original')

        #Session(app)

        from CTFd.views import views
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(admin)

        from CTFd.plugins import init_plugins

        init_plugins(app)

        return app
Exemplo n.º 4
0
 def on_pushButton_clicked(self):
     directory = QFileDialog.getExistingDirectory(caption='请选择下载位置',
                                                  directory='D:/')
     data = {'download': {'path': directory, 'default_path': 'D:/'}}
     # 把新的下载地址展示出来
     self.label_2.setText(directory)
     # 把新的下载地址写入配置文件
     set_config(data)
Exemplo n.º 5
0
def config():
    if request.method == 'POST':
        new_config = request.get_json()
        utils.set_config(new_config)
        print('Successfully updated config')

    config = utils.get_config()
    return jsonify(config)
Exemplo n.º 6
0
 def save_times(self, times):
     tms = {}
     print('save times', times)
     while times != '':
         r = times[0:10]
         times = times[10:]
         if r != '':
             key = r.split(" - ")[0]
             val = r.split(" - ")[1]
             tms[key] = int(val)
     print('save times done', tms)
     utils.set_config("piec_czasy", tms)
     del tms
def train_from_scratch(config, state, channel):
    # Model options
    save_model_dir = config[config.model].save_model_dir
    if save_model_dir == 'current':
        config[config.model].save_model_dir = './'
        save_model_dir = './'
        # to facilitate the use of cluster for multiple jobs
        save_path = './model_config.pkl'
    else:
        # run locally, save locally
        save_path = save_model_dir + 'model_config.pkl'
    print 'current save dir ', save_model_dir
    utils.create_dir_if_not_exist(save_model_dir)

    reload_ = config[config.model].reload_
    if reload_:
        print 'preparing reload'
        save_dir_backup = config[config.model].save_model_dir
        from_dir_backup = config[config.model].from_dir
        # never start retrain in the same folder
        assert save_dir_backup != from_dir_backup
        print 'save dir ', save_dir_backup
        print 'from_dir ', from_dir_backup
        print 'setting current model config with the old one'
        model_config_old = utils.load_pkl(from_dir_backup +
                                          '/model_config.pkl')
        utils.set_config(config, model_config_old)
        config[config.model].save_model_dir = save_dir_backup
        config[config.model].from_dir = from_dir_backup
        config[config.model].reload_ = True
    if config.erase_history:
        print 'erasing everything in ', save_model_dir
        os.system('rm %s/*' % save_model_dir)
    # for stdout file logging
    # sys.stdout = Unbuffered(sys.stdout, state.save_model_path + 'stdout.log')
    print 'saving model config into %s' % save_path
    utils.dump_pkl(config, save_path)
    # Also copy back from config into state.
    for key in config:
        setattr(state, key, config[key])
    model_type = config.model
    print 'Model Type: %s' % model_type
    print 'Command: %s' % ' '.join(sys.argv)

    t0 = time.time()
    print 'training an attention model'
    train(**state.attention)
    if channel:
        channel.save()
    print 'training time in total %.4f sec' % (time.time() - t0)
Exemplo n.º 8
0
Arquivo: app.py Projeto: hfutxqd/kinss
def setting():
    global SERVER_URL
    if request.method == 'GET':
        return render_template('setting.html',
                               title='设置',
                               url=get_config(currentPath))

    if request.method == 'POST':
        baseurl = request.form['baseurl']

        if baseurl:
            set_config(currentPath, baseurl)
            SERVER_URL = baseurl
            return 'Update successfully.click <a href=/login>here</a> to login.'
        else:
            return make_response("invalid param", 400)
Exemplo n.º 9
0
def create_app(config='CTFd.config'):
    app = Flask(__name__)
    with app.app_context():
        app.config.from_object(config)
        app.jinja_loader = ThemeLoader(os.path.join(app.root_path,
                                                    app.template_folder),
                                       followlinks=True)

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        ## sqlite database creation is relative to the script which causes issues with serve.py
        if not database_exists(
                app.config['SQLALCHEMY_DATABASE_URI']
        ) and not app.config['SQLALCHEMY_DATABASE_URI'].startswith('sqlite'):
            create_database(app.config['SQLALCHEMY_DATABASE_URI'])

        db.init_app(app)
        db.create_all()

        app.db = db

        if not get_config('ctf_theme'):
            set_config('ctf_theme', 'original')

        #Session(app)

        from CTFd.views import views
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin
        from CTFd.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)
        app.register_blueprint(admin)

        return app
Exemplo n.º 10
0
def _test(train_args, pretrain_args, args):
    """Test saved model on specified speakers."""
    print('Testing', ', '.join(args.speakers), '...')

    # update args with new test args
    test_args = utils.set_new_args(train_args, args)
    # get test data and id_to_word lookup
    _, _, test_data, id_to_word = data_reader.get_data(test_args)
    # set configurations/hyperparameters for model
    _, test_config = utils.set_config(test_args, id_to_word)

    # model requires init embed but this will be overridden by restored model
    init_embed = utils.init_embedding(id_to_word,
                                      dim=test_args.embed_size,
                                      init_scale=test_args.init_scale,
                                      embed_path=test_args.embed_path)

    with tf.Graph().as_default():
        with tf.name_scope('Test'):
            with tf.variable_scope('Model', reuse=None):
                m_test = model.Model(test_args,
                                     is_training=False,
                                     config=test_config,
                                     init_embed=init_embed,
                                     name='Test')
                m_test.build_graph()

        init = tf.global_variables_initializer()

        # if pretrained, must create dict to initialize TF Saver
        if bool(pretrain_args):
            # get trainable variables and convert to dict for Saver
            reuse_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
            reuse_vars_dict = dict([(var.op.name, var) for var in reuse_vars])
            # create saver for TF session (see function for addl details)
            saver = utils.create_tf_saver(args, pretrain_args, reuse_vars_dict)
        else:
            saver = tf.train.Saver()

        with tf.Session() as sess:
            sess.run(init)
            print('Restoring model...')
            saver.restore(sess, test_args.load_path)

            # test model on specified speakers
            for test_ind, test_speaker in enumerate(test_args.speakers):
                for train_ind, train_speaker in enumerate(train_args.speakers):
                    print('Testing {0} with {1} model'.format(
                        test_speaker, train_speaker))
                    test_perplexity = _run_epoch(sess, m_test, test_args,
                                                 test_data, train_ind,
                                                 test_ind)
                    print('Test Perplexity: {0:.3f}'.format(test_perplexity))
Exemplo n.º 11
0
def _generate(train_args, pretrain_args, args):
    """Restore trained model and use to generate sample text."""
    # update args with new generate args
    gen_args = utils.set_new_args(train_args, args)
    # get id_to_word lookup
    _, _, _, id_to_word = data_reader.get_data(gen_args)
    # # get hyperparameters corresponding to text generation
    gen_config, _ = utils.set_config(gen_args, id_to_word)

    # model requires init embed but this will be overridden by restored model
    init_embed = utils.init_embedding(id_to_word,
                                      dim=gen_args.embed_size,
                                      init_scale=gen_args.init_scale,
                                      embed_path=gen_args.embed_path)

    with tf.Graph().as_default():
        # use Train name scope as this contains trained model parameters
        with tf.name_scope('Train'):
            with tf.variable_scope('Model', reuse=None):
                m_gen = model.Model(gen_args,
                                    is_training=False,
                                    config=gen_config,
                                    init_embed=init_embed,
                                    name='Generate')
                m_gen.build_graph()

        init = tf.global_variables_initializer()

        # if pretrained, must create dict to initialize TF Saver
        if bool(pretrain_args):
            # get trainable variables and convert to dict for Saver
            reuse_vars = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)
            reuse_vars_dict = dict([(var.op.name, var) for var in reuse_vars])
            # create saver for TF session (see function for addl details)
            saver = utils.create_tf_saver(args, pretrain_args, reuse_vars_dict)
        else:
            saver = tf.train.Saver()

        with tf.Session() as sess:
            sess.run(init)
            print('Restoring model...')
            saver.restore(sess, gen_args.load_path)

            # generate text for all specified speakers
            for gen_ind, gen_speaker in enumerate(gen_args.speakers):
                print('Generating text for {0}'.format(gen_speaker))
                for train_ind, train_speaker in enumerate(train_args.speakers):
                    if gen_speaker == train_speaker:
                        generate_text(sess, m_gen, id_to_word, train_ind,
                                      args.temp)
Exemplo n.º 12
0
def setup():
    if not utils.is_setup():
        if request.method == "POST":
            username = request.form['name']
            password = bcrypt.hashpw(request.form.get('password').encode('utf-8'), bcrypt.gensalt())
            admin = User(username=username,password=password,role="all")
            syslog_ip = Config(key="syslog_ip", value=None)
            syslog_port = Config(key="syslog_port", value=None)
            db.session.add(admin)
	    db.session.add(syslog_ip)
	    db.session.add(syslog_port)
            db.session.commit()
            installed = utils.set_config('installed', True)
            return redirect('/')
        else:
            return render_template('register.html')
    else:
        return redirect('/')
Exemplo n.º 13
0
def build_data(audio_data_path_list, text_list, train_or_test):
    configs = get_config()

    if train_or_test == "train":
        # 基于文本按照某种mode切分文本
        mode = configs["preprocess"]["text_process_mode"]
        process_text_list = get_process_text_list(text_list, mode)
        
        if configs["train"]["if_is_first_train"]:
            text_int_sequences, tokenizer = tokenize(process_text_list)

            # 获取音频和文本的最大length,从而进行数据补齐
            max_input_length = get_max_audio_length(audio_data_path_list, configs["other"]["n_mfcc"])
            max_label_length = get_max_label_length(text_int_sequences)

            # 若为初次训练则将构建的字典集合写入json文件
            index_word_path = configs["other"]["index_word_path"]
            with open(index_word_path, 'w', encoding="utf-8") as f:
                json.dump(tokenizer.index_word, f, ensure_ascii=False, indent=4)
            word_index_path = configs["other"]["word_index_path"]
            with open(word_index_path, 'w', encoding="utf-8") as f:
                json.dump(tokenizer.word_index, f, ensure_ascii=False, indent=4)
            
            set_config("model", "dense_units", len(tokenizer.index_word)+2 )
            set_config("preprocess", "max_input_length", max_input_length)
            set_config("preprocess", "max_label_length", max_label_length)
            # 将是否为初次加载改为false
            set_config("train", "if_is_first_train", False)

        else:
            # 不是初次训练就基于初次训练时写入的word_index构建文本
            word_index = get_word_index()
            text_int_sequences = get_text_int_sequences(process_text_list, word_index)
        
        label_length_list = [[len(text_int)] for text_int in text_int_sequences]
        return audio_data_path_list, text_int_sequences, label_length_list
    else:
        # 测试模块只需要文本字符串list即可
        return audio_data_path_list, text_list
Exemplo n.º 14
0
def _train(args, pretrain_args):
    """Train the language model.

    Creates train/valid/test models, runs training epochs, saves model and
    writes results to database if specified.
    """
    start_time = time.time()
    print('Training', ', '.join(args.speakers), '...')

    # randomly sample validation set monte_carlo_cv_num times
    for num in range(args.monte_carlo_cv_num):
        # get seed used to sub-sample validation dataset (use 42 for 1st run)
        seed = utils.get_seed(num)

        # get train/valid/test data and convert to sequences
        train_data, valid_data, test_data, id_to_word = data_reader.get_data(
            args, seed=seed)
        # set configurations/hyperparameters for model
        config, test_config = utils.set_config(args, id_to_word)

        # initialize word embeddings
        init_embed = utils.init_embedding(id_to_word,
                                          dim=args.embed_size,
                                          init_scale=args.init_scale,
                                          embed_path=args.embed_path)

        with tf.Graph().as_default():
            # initializer used to initialize TensorFlow variables
            initializer = tf.random_uniform_initializer(
                -config['init_scale'], config['init_scale'])
            # create Train model
            with tf.name_scope('Train'):
                with tf.variable_scope('Model',
                                       reuse=None,
                                       initializer=initializer):
                    m_train = model.Model(args,
                                          is_training=True,
                                          config=config,
                                          init_embed=init_embed,
                                          name='Train')
                    m_train.build_graph()

            # create Valid model
            with tf.name_scope('Valid'):
                with tf.variable_scope('Model',
                                       reuse=True,
                                       initializer=initializer):
                    m_valid = model.Model(args,
                                          is_training=False,
                                          config=config,
                                          init_embed=init_embed,
                                          name='Valid')
                    m_valid.build_graph()

            # create Test model
            with tf.name_scope('Test'):
                with tf.variable_scope('Model',
                                       reuse=True,
                                       initializer=initializer):
                    m_test = model.Model(args,
                                         is_training=False,
                                         config=test_config,
                                         init_embed=init_embed,
                                         name='Test')
                    m_test.build_graph()

            # create summaries to be viewed in TensorBoard
            tb_summaries = utils.TensorBoardSummaries()
            tb_summaries.create_ops()

            init = tf.global_variables_initializer()

            # if pretrained, must create dict to initialize TF Saver
            if bool(pretrain_args):
                # get trainable variables and convert to dict for Saver
                reuse_vars = tf.get_collection(
                    tf.GraphKeys.TRAINABLE_VARIABLES)
                reuse_vars_dict = dict([(var.op.name, var)
                                        for var in reuse_vars])
                # create saver for TF session (see function for addl details)
                saver = utils.create_tf_saver(args, pretrain_args,
                                              reuse_vars_dict)
            else:
                saver = tf.train.Saver()

            # ppls dict has perplexities that are stored in results database
            ppls = {}
            ppls, _ = _update_ppls(ppls, initialize=True)

            with tf.Session() as sess:
                sess.run(init)

                if args.load_path != '':
                    print('Restoring model...')
                    saver.restore(sess, args.load_path)

                for epoch in range(config['max_epoch']):
                    print('Epoch: {0} Learning rate: {1:.3f}\n'.format(
                        epoch + 1, sess.run(m_train.lr)))
                    for i, speaker in enumerate(args.speakers):
                        print('Training {0} ...'.format(speaker))

                        # run epoch on training data
                        train_perplexity = _run_epoch(
                            sess,
                            m_train,
                            args,
                            train_data,
                            i,
                            tb_summaries,
                            id_to_word,
                            train_op=m_train.train_op,
                            verbose=True)
                        print('Epoch: {0} Train Perplexity: {1:.3f}'.format(
                            epoch + 1, train_perplexity))
                        ppls, _ = _update_ppls(ppls,
                                               epoch=epoch + 1,
                                               speaker=speaker,
                                               ppl=train_perplexity,
                                               dataset='train')

                        print('Validating...')
                        # run epoch on validation data
                        valid_perplexity = _run_epoch(sess,
                                                      m_valid,
                                                      args,
                                                      valid_data,
                                                      i,
                                                      tb_summaries,
                                                      id_to_word,
                                                      verbose=True)
                        print('Epoch: {0} Valid Perplexity: {1:.3f}'.format(
                            epoch + 1, valid_perplexity))
                        ppls, improved = _update_ppls(ppls,
                                                      epoch=epoch + 1,
                                                      speaker=speaker,
                                                      ppl=valid_perplexity,
                                                      dataset='valid')

                        if improved:
                            # save model if valid ppl is lower than current
                            # best valid ppl
                            if args.save_path != '':
                                print('Saving model to {0}.'.format(
                                    args.save_path))
                                saver.save(sess, args.save_path)

                for i, speaker in enumerate(args.speakers):
                    print('Testing {0} ...'.format(speaker))
                    print('Restoring best model for testing...')
                    saver.restore(sess, args.save_path)
                    # run model on test data
                    test_perplexity = _run_epoch(sess, m_test, args, test_data,
                                                 i)
                    ppls['test_ppl_' + speaker] = test_perplexity
                    print('Test Perplexity: {0:.3f}'.format(test_perplexity))

            if args.insert_db == 'True':
                # write params/config/results to sql database
                results_db.insert_results(args, config, start_time, ppls)
Exemplo n.º 15
0
                    metavar="CONFIG_JSON_FILE",
                    help="Run only a specific test")

parser.add_argument("--clear-scheduled-tests",
                    dest="clear",
                    action="store_true",
                    help="Remove all scheduled tests from the database")

parser.add_argument(
    "--schedule-now",
    dest="schedule_now",
    action="store_true",
    help="Schedule all test requests NOW (ignoring the crontab)")

args = parser.parse_args()
CONFIG = utils.set_config(args.config)
# Stores all started servers
# servers = {'metric_id': server}
SERVERS = {}
# Stores all timers to cancel them afterwards
TIMERS = []

#get_tests_for_client("abcde")

# Initialize MongoClient
CLIENT = MongoClient(CONFIG["mongo"]["host"], CONFIG["mongo"]["port"])
MONGO_DATABASE = CLIENT[CONFIG["mongo"]["database"]]
TEST_COLLECTION = MONGO_DATABASE[CONFIG["mongo"]["test-collection"]]

logging.basicConfig(
    level=logging.DEBUG,
Exemplo n.º 16
0
def create_app(config='CTFd.config.Config'):
    app = CTFdFlask(__name__)
    with app.app_context():
        app.config.from_object(config)

        theme_loader = ThemeLoader(os.path.join(app.root_path, 'themes'),
                                   followlinks=True)
        app.jinja_loader = theme_loader

        from CTFd.models import db, Teams, Solves, Challenges, WrongKeys, Keys, Tags, Files, Tracking

        url = make_url(app.config['SQLALCHEMY_DATABASE_URI'])
        if url.drivername == 'postgres':
            url.drivername = 'postgresql'

        if url.drivername.startswith('mysql'):
            url.query['charset'] = 'utf8mb4'

        # Creates database if the database database does not exist
        if not database_exists(url):
            if url.drivername.startswith('mysql'):
                create_database(url, encoding='utf8mb4')
            else:
                create_database(url)

        # This allows any changes to the SQLALCHEMY_DATABASE_URI to get pushed back in
        # This is mostly so we can force MySQL's charset
        app.config['SQLALCHEMY_DATABASE_URI'] = str(url)

        # Register database
        db.init_app(app)

        # Register Flask-Migrate
        migrate.init_app(app, db)

        # Alembic sqlite support is lacking so we should just create_all anyway
        if url.drivername.startswith('sqlite'):
            db.create_all()
        else:
            if len(db.engine.table_names()) == 0:
                # This creates tables instead of db.create_all()
                # Allows migrations to happen properly
                migrate_upgrade()
            elif 'alembic_version' not in db.engine.table_names():
                # There is no alembic_version because CTFd is from before it had migrations
                # Stamp it to the base migration
                if confirm_upgrade():
                    migrate_stamp(revision='cb3cfcc47e2f')
                    run_upgrade()
                else:
                    exit()

        app.db = db
        app.VERSION = __version__

        cache.init_app(app)
        app.cache = cache

        update_check(force=True)

        version = utils.get_config('ctf_version')

        # Upgrading from an older version of CTFd
        if version and (StrictVersion(version) < StrictVersion(__version__)):
            if confirm_upgrade():
                run_upgrade()
            else:
                exit()

        if not version:
            utils.set_config('ctf_version', __version__)

        if not utils.get_config('ctf_theme'):
            utils.set_config('ctf_theme', 'core')

        from CTFd.views import views
        from CTFd.challenges import challenges
        from CTFd.scoreboard import scoreboard
        from CTFd.auth import auth
        from CTFd.admin import admin, admin_statistics, admin_challenges, admin_pages, admin_scoreboard, admin_keys, admin_teams
        from CTFd.utils import init_utils, init_errors, init_logs

        init_utils(app)
        init_errors(app)
        init_logs(app)

        app.register_blueprint(views)
        app.register_blueprint(challenges)
        app.register_blueprint(scoreboard)
        app.register_blueprint(auth)

        app.register_blueprint(admin)
        app.register_blueprint(admin_statistics)
        app.register_blueprint(admin_challenges)
        app.register_blueprint(admin_teams)
        app.register_blueprint(admin_scoreboard)
        app.register_blueprint(admin_keys)
        app.register_blueprint(admin_pages)

        from CTFd.plugins import init_plugins

        init_plugins(app)

        return app
Exemplo n.º 17
0
def run_upgrade():
    migrate_upgrade()
    utils.set_config('ctf_version', __version__)
Exemplo n.º 18
0
 def __init__(self, config_filename, pcap):
     self.config = utils.set_config(config_filename)
     self.pcap = pcap
     self.initial_run = True
     LOGGER.debug("Created client with config=(%s),pcap=(%s)" %
                  (config_filename, pcap))
def main(state, channel=None):
    utils.set_config(config, state)
    train_from_scratch(config, state, channel)
def play_game():
    print("Multi-Sudoku Game!")
    print("Welcome...")
    print("============================")
    while True:
        #Prints the grids
        utils.print_grids()
        #Read an input from the player
        grid_idx, i, j, v = read_input()
        #Set the input position with the value
        set_cell(grid_idx, i, j, v)
        #Check if the grid has a win state
        if check_win():
            #Prints the grids
            utils.print_grids()
            #Announcement of the final statement
            print('Congrats, You won!')
            break

while True:
    utils.contract_modes()
    utils.print_modes()
    utils.set_config()
    utils.grid_clear()
    update_vars()
    generate_grids()
    play_game()
    c = input('Play Again [Y/N] ')
    if c not in 'yY':
        break
Exemplo n.º 21
0
async def cb_handler(client: Client, query: CallbackQuery):
    with suppress(MessageIdInvalid, MessageNotModified, QueryIdInvalid):
        admins = await get_admins(Config.CHAT)
        if query.data.startswith("info"):
            me, you = query.data.split("_")
            text = "Join @subin_works"
            if you == "volume":
                await query.answer()
                await query.message.edit_reply_markup(
                    reply_markup=await volume_buttons())
                return
            if you == "player":
                if not Config.CALL_STATUS:
                    return await query.answer("Not Playing anything.",
                                              show_alert=True)
                await query.message.edit_reply_markup(
                    reply_markup=await get_buttons())
                await query.answer()
                return
            if you == "video":
                text = "Toggle your bot to Video / Audio Player."
            elif you == "shuffle":
                text = "Enable or disable auto playlist shuffling"
            elif you == "admin":
                text = "Enable to restrict the play command only for admins."
            elif you == "mode":
                text = "Enabling Non- stop playback will make the player running 24 / 7 and automatic startup when restarting. "
            elif you == "title":
                text = "Enable to edit the VideoChat title to Current playing song's title."
            elif you == "reply":
                text = "Choose whether to auto-reply messaged for userbot. "
            elif you == "videorecord":
                text = "Enable to record both video and audio, if disabled only audio will be recorded."
            elif you == "videodimension":
                text = "Choose the recording video's dimensions"
            elif you == "rectitle":
                text = "A custom title for your chat recordings, Use /rtitle command to set a title"
            elif you == "recdumb":
                text = "A channel to which all the recordings are forwarded. Make sure The User account is admin over there. Set one using /env or /config."
            await query.answer(text=text, show_alert=True)
            return

        elif query.data.startswith("help"):
            if query.message.chat.type != "private" and query.message.reply_to_message.from_user is None:
                return await query.answer(
                    "I cant help you here, since you are an anonymous admin, message me in private chat.",
                    show_alert=True)
            elif query.message.chat.type != "private" and query.from_user.id != query.message.reply_to_message.from_user.id:
                return await query.answer("Okda", show_alert=True)
            me, nyav = query.data.split("_")
            back = InlineKeyboardMarkup([
                [
                    InlineKeyboardButton("Back", callback_data="help_main"),
                    InlineKeyboardButton("Close", callback_data="close"),
                ],
            ])
            if nyav == 'main':
                reply_markup = InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(f"Play",
                                             callback_data='help_play'),
                        InlineKeyboardButton(f"Settings",
                                             callback_data=f"help_settings"),
                        InlineKeyboardButton(f"Recording",
                                             callback_data='help_record'),
                    ],
                    [
                        InlineKeyboardButton("Scheduling",
                                             callback_data="help_schedule"),
                        InlineKeyboardButton("Controling",
                                             callback_data='help_control'),
                        InlineKeyboardButton("Admins",
                                             callback_data="help_admin"),
                    ],
                    [
                        InlineKeyboardButton(f"Misc",
                                             callback_data='help_misc'),
                        InlineKeyboardButton("Config Vars",
                                             callback_data='help_env'),
                        InlineKeyboardButton("Close", callback_data="close"),
                    ],
                ])
                await query.message.edit(
                    "Showing help menu, Choose from the below options.",
                    reply_markup=reply_markup,
                    disable_web_page_preview=True)
            elif nyav == 'play':
                await query.message.edit(Config.PLAY_HELP,
                                         reply_markup=back,
                                         disable_web_page_preview=True)
            elif nyav == 'settings':
                await query.message.edit(Config.SETTINGS_HELP,
                                         reply_markup=back,
                                         disable_web_page_preview=True)
            elif nyav == 'schedule':
                await query.message.edit(Config.SCHEDULER_HELP,
                                         reply_markup=back,
                                         disable_web_page_preview=True)
            elif nyav == 'control':
                await query.message.edit(Config.CONTROL_HELP,
                                         reply_markup=back,
                                         disable_web_page_preview=True)
            elif nyav == 'admin':
                await query.message.edit(Config.ADMIN_HELP,
                                         reply_markup=back,
                                         disable_web_page_preview=True)
            elif nyav == 'misc':
                await query.message.edit(Config.MISC_HELP,
                                         reply_markup=back,
                                         disable_web_page_preview=True)
            elif nyav == 'record':
                await query.message.edit(Config.RECORDER_HELP,
                                         reply_markup=back,
                                         disable_web_page_preview=True)
            elif nyav == 'env':
                await query.message.edit(Config.ENV_HELP,
                                         reply_markup=back,
                                         disable_web_page_preview=True)
            return

        if not query.from_user.id in admins:
            await query.answer("😒 Played Joji.mp3", show_alert=True)
            return
        #scheduler stuffs
        if query.data.startswith("sch"):
            if query.message.chat.type != "private" and query.message.reply_to_message.from_user is None:
                return await query.answer(
                    "You cant use scheduling here, since you are an anonymous admin. Schedule from private chat.",
                    show_alert=True)
            if query.message.chat.type != "private" and query.from_user.id != query.message.reply_to_message.from_user.id:
                return await query.answer("Okda", show_alert=True)
            data = query.data
            today = datetime.datetime.now(IST)
            smonth = today.strftime("%B")
            obj = calendar.Calendar()
            thisday = today.day
            year = today.year
            month = today.month
            if data.startswith("sch_month"):
                none, none, yea_r, month_, day = data.split("_")
                if yea_r == "choose":
                    year = int(year)
                    months = [
                        "January", "February", "March", "April", "May", "June",
                        "July", "August", "September", "October", "November",
                        "December"
                    ]
                    button = []
                    button_ = []
                    k = 0
                    for month in months:
                        k += 1
                        year_ = year
                        if k < int(today.month):
                            year_ += 1
                            button_.append([
                                InlineKeyboardButton(
                                    text=f"{str(month)}  {str(year_)}",
                                    callback_data=f"sch_showdate_{year_}_{k}")
                            ])
                        else:
                            button.append([
                                InlineKeyboardButton(
                                    text=f"{str(month)}  {str(year_)}",
                                    callback_data=f"sch_showdate_{year_}_{k}")
                            ])
                    button = button + button_
                    button.append([
                        InlineKeyboardButton("Close", callback_data="schclose")
                    ])
                    await query.message.edit(
                        "Now Choose the month to schedule a voicechatㅤ ㅤㅤ",
                        reply_markup=InlineKeyboardMarkup(button))
                elif day == "none":
                    return
                else:
                    year = int(yea_r)
                    month = int(month_)
                    date = int(day)
                    datetime_object = datetime.datetime.strptime(
                        str(month), "%m")
                    smonth = datetime_object.strftime("%B")
                    button = []
                    if year == today.year and month == today.month and date == today.day:
                        now = today.hour
                    else:
                        now = 0
                    l = list()
                    for i in range(now, 24):
                        l.append(i)
                    splited = [l[i:i + 6] for i in range(0, len(l), 6)]
                    for i in splited:
                        k = []
                        for d in i:
                            k.append(
                                InlineKeyboardButton(
                                    text=f"{d}",
                                    callback_data=
                                    f"sch_day_{year}_{month}_{date}_{d}"))
                        button.append(k)
                    if month == today.month and date < today.day and year == today.year + 1:
                        pyear = year - 1
                    else:
                        pyear = year
                    button.append([
                        InlineKeyboardButton(
                            "Back",
                            callback_data=f"sch_showdate_{pyear}_{month}"),
                        InlineKeyboardButton("Close", callback_data="schclose")
                    ])
                    await query.message.edit(
                        f"Choose the hour of {date} {smonth} {year} to schedule  a voicechat.",
                        reply_markup=InlineKeyboardMarkup(button))

            elif data.startswith("sch_day"):
                none, none, year, month, day, hour = data.split("_")
                year = int(year)
                month = int(month)
                day = int(day)
                hour = int(hour)
                datetime_object = datetime.datetime.strptime(str(month), "%m")
                smonth = datetime_object.strftime("%B")
                if year == today.year and month == today.month and day == today.day and hour == today.hour:
                    now = today.minute
                else:
                    now = 0
                button = []
                l = list()
                for i in range(now, 60):
                    l.append(i)
                for i in range(0, len(l), 6):
                    chunk = l[i:i + 6]
                    k = []
                    for d in chunk:
                        k.append(
                            InlineKeyboardButton(
                                text=f"{d}",
                                callback_data=
                                f"sch_minute_{year}_{month}_{day}_{hour}_{d}"))
                    button.append(k)
                button.append([
                    InlineKeyboardButton(
                        "Back",
                        callback_data=f"sch_month_{year}_{month}_{day}"),
                    InlineKeyboardButton("Close", callback_data="schclose")
                ])
                await query.message.edit(
                    f"Choose minute of {hour}th hour on {day} {smonth} {year} to schedule Voicechat.",
                    reply_markup=InlineKeyboardMarkup(button))

            elif data.startswith("sch_minute"):
                none, none, year, month, day, hour, minute = data.split("_")
                year = int(year)
                month = int(month)
                day = int(day)
                hour = int(hour)
                minute = int(minute)
                datetime_object = datetime.datetime.strptime(str(month), "%m")
                smonth = datetime_object.strftime("%B")
                if year == today.year and month == today.month and day == today.day and hour == today.hour and minute <= today.minute:
                    await query.answer(
                        "I dont have a timemachine to go to past!!!.")
                    return
                final = f"{day}th {smonth} {year} at {hour}:{minute}"
                button = [[
                    InlineKeyboardButton(
                        "Confirm",
                        callback_data=
                        f"schconfirm_{year}-{month}-{day} {hour}:{minute}"),
                    InlineKeyboardButton(
                        "Back",
                        callback_data=f"sch_day_{year}_{month}_{day}_{hour}")
                ], [InlineKeyboardButton("Close", callback_data="schclose")]]
                data = Config.SCHEDULED_STREAM.get(
                    f"{query.message.chat.id}_{query.message.message_id}")
                if not data:
                    await query.answer("This schedule is expired",
                                       show_alert=True)
                if data['3'] == "telegram":
                    title = data['1']
                else:
                    title = f"[{data['1']}]({data['2']})"
                await query.message.edit(
                    f"Your Stream {title} is now scheduled to start on {final}\n\nClick Confirm to confirm the time.",
                    reply_markup=InlineKeyboardMarkup(button),
                    disable_web_page_preview=True)

            elif data.startswith("sch_showdate"):
                tyear = year
                none, none, year, month = data.split("_")
                datetime_object = datetime.datetime.strptime(month, "%m")
                thissmonth = datetime_object.strftime("%B")
                obj = calendar.Calendar()
                thisday = today.day
                year = int(year)
                month = int(month)
                m = obj.monthdayscalendar(year, month)
                button = []
                button.append([
                    InlineKeyboardButton(
                        text=f"{str(thissmonth)}  {str(year)}",
                        callback_data=f"sch_month_choose_none_none")
                ])
                days = ["Mon", "Tues", "Wed", "Thu", "Fri", "Sat", "Sun"]
                f = []
                for day in days:
                    f.append(
                        InlineKeyboardButton(text=f"{day}",
                                             callback_data=f"day_info_none"))
                button.append(f)
                for one in m:
                    f = []
                    for d in one:
                        year_ = year
                        if year == today.year and month == today.month and d < int(
                                today.day):
                            year_ += 1
                        if d == 0:
                            k = "\u2063"
                            d = "none"
                        else:
                            k = d
                        f.append(
                            InlineKeyboardButton(
                                text=f"{k}",
                                callback_data=f"sch_month_{year_}_{month}_{d}")
                        )
                    button.append(f)
                button.append(
                    [InlineKeyboardButton("Close", callback_data="schclose")])
                await query.message.edit(
                    f"Choose the day of the month you want to schedule the voicechat.\nToday is {thisday} {smonth} {tyear}. Chooosing a date preceeding today will be considered as next year {year+1}",
                    reply_markup=InlineKeyboardMarkup(button))

            elif data.startswith("schconfirm"):
                none, date = data.split("_")
                date = datetime.datetime.strptime(date, '%Y-%m-%d %H:%M')
                local_dt = IST.localize(date, is_dst=None)
                utc_dt = local_dt.astimezone(pytz.utc).replace(tzinfo=None)
                job_id = f"{query.message.chat.id}_{query.message.message_id}"
                Config.SCHEDULE_LIST.append({"job_id": job_id, "date": utc_dt})
                Config.SCHEDULE_LIST = sorted(Config.SCHEDULE_LIST,
                                              key=lambda k: k['date'])
                await schedule_a_play(job_id, utc_dt)
                await query.message.edit(
                    f"Succesfully scheduled to stream on <code> {date.strftime('%b %d %Y, %I:%M %p')} </code>"
                )
                await delete_messages(
                    [query.message, query.message.reply_to_message])

            elif query.data == 'schcancelall':
                await cancel_all_schedules()
                await query.message.edit(
                    "All Scheduled Streams are cancelled succesfully.")

            elif query.data == "schcancel":
                buttons = [[
                    InlineKeyboardButton('Yes, Iam Sure!!',
                                         callback_data='schcancelall'),
                    InlineKeyboardButton('No', callback_data='schclose'),
                ]]
                await query.message.edit(
                    "Are you sure that you want to cancel all the scheduled streams?",
                    reply_markup=InlineKeyboardMarkup(buttons))
            elif data == "schclose":
                await query.answer("Menu Closed")
                await query.message.delete()
                await query.message.reply_to_message.delete()

        elif query.data == "shuffle":
            if not Config.playlist:
                await query.answer("Playlist is empty.", show_alert=True)
                return
            await shuffle_playlist()
            await query.answer("Playlist shuffled.")
            await sleep(1)
            await query.message.edit_reply_markup(
                reply_markup=await get_buttons())

        elif query.data.lower() == "pause":
            if Config.PAUSE:
                await query.answer("Already Paused", show_alert=True)
            else:
                await pause()
                await query.answer("Stream Paused")
                await sleep(1)

            await query.message.edit_reply_markup(
                reply_markup=await get_buttons())

        elif query.data.lower() == "resume":
            if not Config.PAUSE:
                await query.answer("Nothing Paused to resume", show_alert=True)
            else:
                await resume()
                await query.answer("Redumed the stream")
                await sleep(1)
            await query.message.edit_reply_markup(
                reply_markup=await get_buttons())

        elif query.data == "skip":
            if not Config.playlist:
                await query.answer("No songs in playlist", show_alert=True)
            else:
                await query.answer("Trying to skip from playlist.")
                await skip()
                await sleep(1)
            if Config.playlist:
                title = f"<b>{Config.playlist[0][1]}</b>\nㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ"
            elif Config.STREAM_LINK:
                title = f"<b>Stream Using [Url]({Config.DATA['FILE_DATA']['file']})</b>ㅤ  ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ"
            else:
                title = f"<b>Streaming Startup [stream]({Config.STREAM_URL})</b> ㅤ ㅤ  ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ"
            await query.message.edit(f"<b>{title}</b>",
                                     disable_web_page_preview=True,
                                     reply_markup=await get_buttons())

        elif query.data == "replay":
            if not Config.playlist:
                await query.answer("No songs in playlist", show_alert=True)
            else:
                await query.answer("trying to restart player")
                await restart_playout()
                await sleep(1)
            await query.message.edit_reply_markup(
                reply_markup=await get_buttons())

        elif query.data.lower() == "mute":
            if Config.MUTED:
                await unmute()
                await query.answer("Unmuted stream")
            else:
                await mute()
                await query.answer("Muted stream")
            await sleep(1)
            await query.message.edit_reply_markup(
                reply_markup=await volume_buttons())

        elif query.data.lower() == 'seek':
            if not Config.CALL_STATUS:
                return await query.answer("Not Playing anything.",
                                          show_alert=True)
            #if not (Config.playlist or Config.STREAM_LINK):
            #return await query.answer("Startup stream cant be seeked.", show_alert=True)
            await query.answer("trying to seek.")
            data = Config.DATA.get('FILE_DATA')
            if not data.get('dur', 0) or \
                data.get('dur') == 0:
                return await query.answer(
                    "This is a live stream and cannot be seeked.",
                    show_alert=True)
            k, reply = await seek_file(10)
            if k == False:
                return await query.answer(reply, show_alert=True)
            await query.message.edit_reply_markup(
                reply_markup=await get_buttons())

        elif query.data.lower() == 'rewind':
            if not Config.CALL_STATUS:
                return await query.answer("Not Playing anything.",
                                          show_alert=True)
            #if not (Config.playlist or Config.STREAM_LINK):
            #return await query.answer("Startup stream cant be seeked.", show_alert=True)
            await query.answer("trying to rewind.")
            data = Config.DATA.get('FILE_DATA')
            if not data.get('dur', 0) or \
                data.get('dur') == 0:
                return await query.answer(
                    "This is a live stream and cannot be seeked.",
                    show_alert=True)
            k, reply = await seek_file(-10)
            if k == False:
                return await query.answer(reply, show_alert=True)
            await query.message.edit_reply_markup(
                reply_markup=await get_buttons())

        elif query.data == 'restart':
            if not Config.CALL_STATUS:
                if not Config.playlist:
                    await query.answer(
                        "Player is empty, starting STARTUP_STREAM.")
                else:
                    await query.answer('Resuming the playlist')
            await query.answer("Restrating the player")
            await restart()
            await query.message.edit(text=await get_playlist_str(),
                                     reply_markup=await get_buttons(),
                                     disable_web_page_preview=True)

        elif query.data.startswith("volume"):
            me, you = query.data.split("_")
            if you == "main":
                await query.message.edit_reply_markup(
                    reply_markup=await volume_buttons())
            if you == "add":
                if 190 <= Config.VOLUME <= 200:
                    vol = 200
                else:
                    vol = Config.VOLUME + 10
                if not (1 <= vol <= 200):
                    return await query.answer("Only 1-200 range accepted.")
                await volume(vol)
                Config.VOLUME = vol
                await query.message.edit_reply_markup(
                    reply_markup=await volume_buttons())
            elif you == "less":
                if 1 <= Config.VOLUME <= 10:
                    vol = 1
                else:
                    vol = Config.VOLUME - 10
                if not (1 <= vol <= 200):
                    return await query.answer("Only 1-200 range accepted.")
                await volume(vol)
                Config.VOLUME = vol
                await query.message.edit_reply_markup(
                    reply_markup=await volume_buttons())
            elif you == "back":
                await query.message.edit_reply_markup(
                    reply_markup=await get_buttons())

        elif query.data in [
                "is_loop", "is_video", "admin_only", "edit_title",
                "set_shuffle", "reply_msg", "set_new_chat", "record",
                "record_video", "record_dim"
        ]:
            if query.data == "is_loop":
                Config.IS_LOOP = set_config(Config.IS_LOOP)
                await query.message.edit_reply_markup(
                    reply_markup=await settings_panel())

            elif query.data == "is_video":
                Config.IS_VIDEO = set_config(Config.IS_VIDEO)
                await query.message.edit_reply_markup(
                    reply_markup=await settings_panel())
                data = Config.DATA.get('FILE_DATA')
                if not data \
                    or data.get('dur', 0) == 0:
                    await restart_playout()
                    return
                k, reply = await seek_file(0)
                if k == False:
                    await restart_playout()

            elif query.data == "admin_only":
                Config.ADMIN_ONLY = set_config(Config.ADMIN_ONLY)
                await query.message.edit_reply_markup(
                    reply_markup=await settings_panel())

            elif query.data == "edit_title":
                Config.EDIT_TITLE = set_config(Config.EDIT_TITLE)
                await query.message.edit_reply_markup(
                    reply_markup=await settings_panel())

            elif query.data == "set_shuffle":
                Config.SHUFFLE = set_config(Config.SHUFFLE)
                await query.message.edit_reply_markup(
                    reply_markup=await settings_panel())

            elif query.data == "reply_msg":
                Config.REPLY_PM = set_config(Config.REPLY_PM)
                await query.message.edit_reply_markup(
                    reply_markup=await settings_panel())

            elif query.data == "record_dim":
                if not Config.IS_VIDEO_RECORD:
                    return await query.answer(
                        "This cant be used for audio recordings")
                Config.PORTRAIT = set_config(Config.PORTRAIT)
                await query.message.edit_reply_markup(
                    reply_markup=(await recorder_settings()))
            elif query.data == 'record_video':
                Config.IS_VIDEO_RECORD = set_config(Config.IS_VIDEO_RECORD)
                await query.message.edit_reply_markup(
                    reply_markup=(await recorder_settings()))

            elif query.data == 'record':
                if Config.IS_RECORDING:
                    k, msg = await stop_recording()
                    if k == False:
                        await query.answer(msg, show_alert=True)
                    else:
                        await query.answer("Recording Stopped")
                else:
                    k, msg = await start_record_stream()
                    if k == False:
                        await query.answer(msg, show_alert=True)
                    else:
                        await query.answer("Recording started")
                await query.message.edit_reply_markup(
                    reply_markup=(await recorder_settings()))

            elif query.data == "set_new_chat":
                if query.from_user is None:
                    return await query.answer(
                        "You cant do scheduling here, since you are an anonymous admin. Schedule from private chat.",
                        show_alert=True)
                if query.from_user.id in Config.SUDO:
                    await query.answer("Setting up new CHAT")
                    chat = query.message.chat.id
                    if Config.IS_RECORDING:
                        await stop_recording()
                    await cancel_all_schedules()
                    await leave_call()
                    Config.CHAT = chat
                    Config.ADMIN_CACHE = False
                    await restart()
                    await query.message.edit("Succesfully Changed Chat")
                    await sync_to_db()
                else:
                    await query.answer("This can only be used by SUDO users",
                                       show_alert=True)
            if not Config.DATABASE_URI:
                await query.answer(
                    "No DATABASE found, this changes are saved temporarly and will be reverted on restart. Add MongoDb to make this permanant."
                )
        elif query.data.startswith("close"):
            if "sudo" in query.data:
                if query.from_user.id in Config.SUDO:
                    await query.message.delete()
                else:
                    await query.answer("This can only be used by SUDO users",
                                       show_alert=True)
            else:
                if query.message.chat.type != "private" and query.message.reply_to_message:
                    if query.message.reply_to_message.from_user is None:
                        pass
                    elif query.from_user.id != query.message.reply_to_message.from_user.id:
                        return await query.answer("Okda", show_alert=True)
                elif query.from_user.id in Config.ADMINS:
                    pass
                else:
                    return await query.answer("Okda", show_alert=True)
                await query.answer("Menu Closed")
                await query.message.delete()
        await query.answer()