Beispiel #1
0
    async def on_command_error(self, ctx, error):
        # The local handlers so far only catch bad arguments so we still
        # want to print the rest
        if (isinstance(error, commands.BadArgument) or
           isinstance(error, commands.errors.CheckFailure) or
           isinstance(error, commands.errors.MissingAnyRole) or
           isinstance(error, commands.errors.MissingRequiredArgument)) and \
           hasattr(ctx.command, 'on_error'):
            return

        if isinstance(error, commands.UserInputError):
            await ctx.send("Chyba ve vstupu")
            return

        if isinstance(error, commands.CommandNotFound):
            prefix = ctx.message.content[:1]
            if prefix not in config.ignored_prefixes:
                await ctx.send(messages.no_such_command)
            return

        if isinstance(error, commands.CommandOnCooldown):
            await ctx.send(utils.fill_message("spamming", user=ctx.author.id))
            return

        output = "Ignoring exception in command {}:\n".format(ctx.command)
        output += "".join(
            traceback.format_exception(type(error), error,
                                       error.__traceback__))
        channel = self.bot.get_channel(config.bot_dev_channel)
        print(output)
        output = utils.cut_string(output, 1900)
        if channel is not None:
            for message in output:
                await channel.send("```\n" + message + "\n```")
Beispiel #2
0
    async def on_error(self, error, item: disnake.ui.Item,
                       interaction: disnake.MessageInteraction):
        channel_out = interaction.bot.get_channel(config.bot_dev_channel)
        embed = disnake.Embed(
            title=
            f"Ignoring exception in interacion '{interaction.data.custom_id}'",
            color=0xFF0000)
        embed.add_field(name="Guild", value=interaction.guild)
        embed.add_field(name="Autor", value=interaction.author.display_name)
        embed.add_field(
            name="Expirace (UTC)",
            value=interaction.expires_at.strftime("%Y-%m-%d %H:%M:%S"))
        embed.add_field(name="Exception", value=error)
        embed.add_field(name="Zpráva",
                        value=interaction.message.jump_url,
                        inline=False)
        await channel_out.send(embed=embed)
        output = traceback.format_exc()
        output = utils.cut_string(output, 1900)
        for message in output:
            await channel_out.send(f"```\n{message}```")

        # remove interactions because of error
        self.clear_items()
        await self.message.edit(view=self)
Beispiel #3
0
async def on_error(event, *args, **kwargs):
    channel = bot.get_channel(int(Config.LOG_CHANNEL))
    output = traceback.format_exc()
    print(output)
    output = utils.cut_string(output, 1900)
    for message in output:
        await channel.send("```\n{}```".format(message))
def worker(n, files, classes, uclasses, colors, lock, conn):
    pbar = tqdm(files, position=n)
    uclasses = list(uclasses)
    n_colors, n_classes = len(colors), len(classes)
    for file in pbar:
        pbar.set_description(utils.cut_string(file))
        dir, name = os.path.dirname(file), os.path.splitext(
            os.path.basename(file))[0]
        mask = skimage.io.imread(os.path.join(dir, name + '.mask.png'))
        mask = mask.reshape(
            (*mask.shape, 1)) if len(mask.shape) <= 2 else mask[:, :, [0]]
        mask = mask.repeat(n_colors, axis=2) == colors
        ind = [i for i in range(n_classes) if mask[::, ::, i].any()]
        if ind:
            mask = mask[:, :, ind]
            for i in range(mask.shape[-1]):
                remove_small_objects(mask[:, :, i],
                                     connectivity=2,
                                     in_place=True)
            with lock:
                conn.send(
                    (file, ('image',
                            skimage.io.imread(file)[:, :, :3]), ('mask', mask),
                     ('class_id',
                      np.array([uclasses.index(i) + 1 for i in classes[ind]],
                               dtype='uint8'))))
    pbar.close()
Beispiel #5
0
    async def on_command_error(self, ctx, error):
        # The local handlers so far only catch bad arguments so we still
        # want to print the rest
        if isinstance(error, disnake.errors.DiscordServerError):
            return
        if isinstance(error, sqlalchemy.exc.InternalError):
            session.rollback()
            return
        if (isinstance(error, commands.BadArgument)
                or isinstance(error, commands.errors.CheckFailure)
                or isinstance(error, commands.errors.MissingAnyRole)
                or isinstance(error, commands.errors.MissingRequiredArgument)
            ) and hasattr(ctx.command, "on_error"):
            return

        if isinstance(error, commands.UserInputError):
            await ctx.send(
                "Chyba ve vstupu, jestli vstup obsahuje `\"` nahraď je za `'`")
            return

        if isinstance(error, commands.CommandNotFound):
            prefix = ctx.message.content[:1]
            if prefix not in config.ignored_prefixes:
                await ctx.send(Messages.no_such_command)
            return

        if isinstance(error, commands.CommandOnCooldown):
            await ctx.send(utils.fill_message("spamming", user=ctx.author.id))
            return

        if isinstance(error, utils.NotHelperPlusError):
            await ctx.send(Messages.helper_plus_only)
            return

        output = "".join(
            traceback.format_exception(type(error), error,
                                       error.__traceback__))
        embed = disnake.Embed(
            title=f"Ignoring exception in command {ctx.command}",
            color=0xFF0000)
        embed.add_field(name="Zpráva", value=ctx.message.content[:1000])
        embed.add_field(name="Autor", value=str(ctx.author))
        if ctx.guild and ctx.guild.id != config.guild_id:
            embed.add_field(name="Guild", value=ctx.guild.name)
        embed.add_field(name="Link", value=ctx.message.jump_url, inline=False)

        channel = self.bot.get_channel(config.bot_dev_channel)

        # send context of command with personal information to DM
        if ctx.command.name == "diplom":
            channel_ctx = self.bot.get_user(config.admin_ids[0])
        else:
            channel_ctx = channel
        await channel_ctx.send(embed=embed)

        output = utils.cut_string(output, 1900)
        if channel is not None:
            for message in output:
                await channel.send(f"```\n{message}\n```")
Beispiel #6
0
async def on_error(event, *args, **kwargs):
    channel = bot.get_channel(config.bot_dev_channel)
    output = traceback.format_exc()
    print(output)
    if channel is not None:
        output = utils.cut_string(output, 1900)
        for message in output:
            await channel.send("```\n{}```".format(message))
Beispiel #7
0
async def on_error(event, *args, **kwargs):
    channel_out = bot.get_channel(config.bot_dev_channel)
    output = traceback.format_exc()
    print(output)

    embeds = []
    guild = None
    for arg in args:
        if arg.guild_id:
            guild = bot.get_guild(arg.guild_id)
            event_guild = guild.name
            channel = guild.get_channel(arg.channel_id)
            message = await channel.fetch_message(arg.message_id)
            message = message.content[:1000]
        else:
            event_guild = "DM"
            message = arg.message_id

        user = bot.get_user(arg.user_id)
        if not user:
            user = arg.user_id
        else:
            channel = bot.get_channel(arg.channel_id)
            if channel:
                message = await channel.fetch_message(arg.message_id)
                if message.content:
                    message = message.content[:1000]
                else:
                    embeds.extend(message.embeds)
                    message = "Embed v předchozí zprávě"
            else:
                message = arg.message_id
            user = str(user)
        embed = Embed(title=f"Ignoring exception in event '{event}'", color=0xFF0000)
        embed.add_field(name="Zpráva", value=message, inline=False)
        if arg.guild_id != config.guild_id:
            embed.add_field(name="Guild", value=event_guild)

        if arg.member:
            reaction_from = str(arg.member)
        else:
            reaction_from = user
        embed.add_field(name="Reakce od", value=reaction_from)
        embed.add_field(name="Reaction", value=arg.emoji)
        embed.add_field(name="Typ", value=arg.event_type)
        if arg.guild_id:
            link = f"https://discord.com/channels/{arg.guild_id}/{arg.channel_id}/{arg.message_id}"
            embed.add_field(name="Link", value=link, inline=False)
        embeds.append(embed)

    if channel_out is not None:
        output = utils.cut_string(output, 1900)
        for embed in embeds:
            await channel_out.send(embed=embed)
        for message in output:
            await channel_out.send(f"```\n{message}```")
Beispiel #8
0
    async def pull(self, ctx: commands.Context):
        message: Message = await ctx.send('Pulling')

        pull_result = await self.git.pull(ctx)
        pull_parts = utils.cut_string(pull_result, 1900)

        await message.edit(content=f'```{pull_parts[0]}```')

        for part in pull_parts[1:]:
            await ctx.send(f'```{part}```')
def function(n, images, backgrounds, args):
	pbar = tqdm(images, position=n)
	for file in pbar:
		pbar.set_description(utils.cut_string(file))
		img = Image.open(file)
		p = os.path.join(args.output, os.path.dirname(file))
		n = os.path.splitext(os.path.basename(file))[0]
		for back, name in backgrounds:
			apply_background(noise(back.resize(img.size, Image.ANTIALIAS)), img, os.path.join(p, './{}_{}.png'.format(n, name)))
		if args.mask:
			Image.frombytes('1', img.size, np.packbits(np.array(img)[::,::,3].astype(bool), axis=1)).save(os.path.join(p, './{}.mask'.format(n)), 'png')
		for i in range(args.random_backgrounds):
			apply_background(Image.fromarray(np.random.randint(0, 256, (*img.size, 3), 'uint8')), img, os.path.join(p, './{}_{}.png'.format(n, i)))
		if args.rebackground:
			backgrounds = choose_backgrounds(args.backgrounds, args.backgrounds_number)
Beispiel #10
0
    async def on_slash_command_error(
            self, inter: disnake.ApplicationCommandInteraction, error):
        if isinstance(error, disnake.errors.DiscordServerError):
            return

        if isinstance(error, sqlalchemy.exc.InternalError):
            session.rollback()
            return

        if isinstance(error, disnake.InteractionTimedOut):
            await inter.response.send_message(Messages.command_timed_out)
            return

        if isinstance(error, commands.CommandOnCooldown):
            await inter.response.send_message(
                utils.fill_message("spamming", user=inter.author.id))
            return

        url = f"https://discord.com/channels/{inter.guild_id}/{inter.channel_id}/{inter.id}"

        output = "".join(
            traceback.format_exception(type(error), error,
                                       error.__traceback__))
        embed = disnake.Embed(
            title=f"Ignoring exception in command {inter.data.name}",
            color=0xFF0000)
        embed.add_field(name="Zpráva", value=inter.filled_options)
        embed.add_field(name="Autor", value=str(inter.author))
        if inter.guild and inter.guild.id != config.guild_id:
            embed.add_field(name="Guild", value=inter.guild.name)
        embed.add_field(name="Link", value=url, inline=False)

        channel = self.bot.get_channel(config.bot_dev_channel)

        # send context of command with personal information to DM
        if inter.data.name == "diplom":
            channel_ctx = self.bot.get_user(config.admin_ids[0])
        else:
            channel_ctx = channel
        await channel_ctx.send(embed=embed)

        output = utils.cut_string(output, 1900)
        if channel is not None:
            for message in output:
                await channel.send(f"```\n{message}\n```")
Beispiel #11
0
args = parser.parse_args()


def save_frame(frame, path, name, i, r):
    if r:
        frame = frame[r[1]:r[1] + r[3], r[0]:r[0] + r[2]]
    path = os.path.join(path, str(c) + '.png')
    make_dirs(path)
    cv2.imwrite(path, frame)


f = io.StringIO()
pbar = tqdm(args.files, position=0)

for v in pbar:
    pbar.set_description(cut_string(v))
    vidcap = cv2.VideoCapture(v)
    name = os.path.splitext(os.path.basename(v))[0]
    path = os.path.join(args.output, name)
    s, image = vidcap.read()
    r, l = None, int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
    if args.roi:
        with stdout_redirector(f):
            r = list(cv2.selectROI(image))
        if args.width:
            diff = (args.width - r[2]) // 2
            r[0], r[2] = max(0, int(r[0] - diff)), args.width
        if args.height:
            diff = (args.height - r[3]) // 2
            r[1], r[3] = max(int(r[1] - diff), 0), args.height
    bar = tqdm(list(range(0, l, args.skip_frames)), position=1)
Beispiel #12
0
filters = tables.Filters(complevel=args.complevel, complib=args.complib)
file = utils.open_or_create_dataset_file(args.file, filters,
                                         ('image', 'mask', 'class_id'), True)

classes = file.root.classes[:]
new_classes = []
count = file.root.count[0]

annotations = glob.glob(os.path.join(args.directory, '**/*.json'),
                        recursive=True)
files = []

apbar = tqdm(annotations, position=0)
for annotation in apbar:
    apbar.set_description(utils.cut_string(annotation))

    path = os.path.dirname(annotation)
    annotation = json.load(open(annotation))

    pbar = tqdm(list(annotation['_via_img_metadata'].values()), position=1)
    for data in pbar:
        pbar.set_description(utils.cut_string(data['filename']))

        img_path = os.path.join(path, data['filename'])
        img = skimage.io.imread(img_path)

        l = len(data['regions'])
        mask = np.zeros(shape=(*img.shape[:-1], l)).astype(bool)
        class_ids = np.ndarray(l, dtype='uint8')
Beispiel #13
0
assert 0 <= args.train <= 1, 'Train weight must be in range [0, 1]'

poses = glob.glob(os.path.join(args.directory, '**/poses.txt'), recursive=True)
posestxt = [np.loadtxt(i) for i in poses]
images = [glob.iglob(os.path.join(os.path.dirname(i), '*.png')) for i in poses]

filters = tables.Filters(complevel=args.complevel, complib=args.complib)
file = utils.open_or_create_dataset_file(args.file, filters, ('image', 'val'),
                                         False)

count = file.root.count[0]

with tqdm(total=sum(i.shape[0] for i in posestxt)) as pbar:
    for pose_path, pose, files in zip(poses, posestxt, images):
        dirname = os.path.dirname(pose_path)
        pbar.set_description(utils.cut_string(dirname))
        class_id = args.classes.index(os.path.split(dirname)[1])
        for path in files:
            img = skimage.io.imread(path)
            if np.count_nonzero(img) >= args.threshold:
                img = img.reshape((*img.shape, 1))
                id = '_' + str(count)
                file.create_carray(file.root.image,
                                   id,
                                   obj=img,
                                   filters=filters)
                file.create_carray(
                    file.root.val,
                    id,
                    obj=np.concatenate([
                        pose[int(os.path.splitext(os.path.basename(path))[0])],