text:
import discord
import asyncio
import json
from collections import OrderedDict
import random
import numpy as np
from functools import partial
from discord.utils import get
from collections import namedtuple
from discord.ext import commands

class Marriage(commands.Cog):

    def __init__(self, client):
        self.client = client

        self.client.loop.create_task(self.save_users())

        with open('marry.json', 'r') as f:
            self.users = json.load(f)

    async def save_users(self):
        await self.client.wait_until_ready()
        while not self.client.is_closed():
            with open('marry.json', 'w') as f:
                if self.users:
                    json.dump(self.users, f, indent=4)

            await asyncio.sleep(3)

    @commands.Cog.listener()
    async def on_member_join(self, member):
        author_id = str(member.id)
        self.users[author_id] = {}
        self.users[author_id]['couple_id'] = 'None'
        self.users[author_id]['price'] = 1
        self.users[author_id]['gift1'] = 'None'
        self.users[author_id]['gift2'] = 'None'
        self.users[author_id]['gift3'] = 'None'
        self.users[author_id]['gift4'] = 'None'
        self.users[author_id]['gift5'] = 'None'
        self.users[author_id]['gift6'] = 'None'
        self.users[author_id]['gift7'] = 'None'
        self.users[author_id]['gift8'] = 'None'
        self.users[author_id]['gift9'] = 'None'
        self.users[author_id]['gift10'] = 'None'
        self.users[author_id]['gift11'] = 'None'
        self.users[author_id]['gift12'] = 'None'
        self.users[author_id]['gift13'] = 'None'
        self.users[author_id]['gift14'] = 'None'
        self.users[author_id]['gift15'] = 'None'
        self.users[author_id]['gift16'] = 'None'
        self.users[author_id]['gift17'] = 'None'
        self.users[author_id]['gift18'] = 'None'
        self.users[author_id]['gift19'] = 'None'
        self.users[author_id]['gift20'] = 'None'
        self.users[author_id]['gift21'] = 'None'
        self.users[author_id]['divorce_num'] = 0

    @commands.Cog.listener()
    async def on_message(self, message):

        author_id = str(message.author.id)

        if not author_id in self.users:
            self.users[author_id] = {}
            self.users[author_id]['couple_id'] = 'None'
            self.users[author_id]['price'] = 1
            self.users[author_id]['gift1'] = 'None'
            self.users[author_id]['gift2'] = 'None'
            self.users[author_id]['gift3'] = 'None'
            self.users[author_id]['gift4'] = 'None'
            self.users[author_id]['gift5'] = 'None'
            self.users[author_id]['gift6'] = 'None'
            self.users[author_id]['gift7'] = 'None'
            self.users[author_id]['gift8'] = 'None'
            self.users[author_id]['gift9'] = 'None'
            self.users[author_id]['gift10'] = 'None'
            self.users[author_id]['gift11'] = 'None'
            self.users[author_id]['gift12'] = 'None'
            self.users[author_id]['gift13'] = 'None'
            self.users[author_id]['gift14'] = 'None'
            self.users[author_id]['gift15'] = 'None'
            self.users[author_id]['gift16'] = 'None'
            self.users[author_id]['gift17'] = 'None'
            self.users[author_id]['gift18'] = 'None'
            self.users[author_id]['gift19'] = 'None'
            self.users[author_id]['gift20'] = 'None'
            self.users[author_id]['gift21'] = 'None'
            self.users[author_id]['divorce_num'] = 0

    @commands.command(name='marry', pass_context=True)
    async def marry(self, ctx, member: discord.Member):
        author_id = str(ctx.message.author.id)
        if not author_id in self.users:
            self.users[author_id] = {}
            self.users[author_id]['couple_id'] = 'None'
            self.users[author_id]['price'] = 1
            self.users[author_id]['gift1'] = 'None'
            self.users[author_id]['gift2'] = 'None'
            self.users[author_id]['gift3'] = 'None'
            self.users[author_id]['gift4'] = 'None'
            self.users[author_id]['gift5'] = 'None'
            self.users[author_id]['gift6'] = 'None'
            self.users[author_id]['gift7'] = 'None'
            self.users[author_id]['gift8'] = 'None'
            self.users[author_id]['gift9'] = 'None'
            self.users[author_id]['gift10'] = 'None'
            self.users[author_id]['gift11'] = 'None'
            self.users[author_id]['gift12'] = 'None'
            self.users[author_id]['gift13'] = 'None'
            self.users[author_id]['gift14'] = 'None'
            self.users[author_id]['gift15'] = 'None'
            self.users[author_id]['gift16'] = 'None'
            self.users[author_id]['gift17'] = 'None'
            self.users[author_id]['gift18'] = 'None'
            self.users[author_id]['gift19'] = 'None'
            self.users[author_id]['gift20'] = 'None'
            self.users[author_id]['gift21'] = 'None'
            self.users[author_id]['divorce_num'] = 0
        member_id = str(member.id)
        if not member_id in self.users:
            self.users[member_id] = {}
            self.users[member_id]['couple_id'] = 'None'
            self.users[member_id]['price'] = 1
            self.users[member_id]['gift1'] = 'None'
            self.users[member_id]['gift2'] = 'None'
            self.users[member_id]['gift3'] = 'None'
            self.users[member_id]['gift4'] = 'None'
            self.users[member_id]['gift5'] = 'None'
            self.users[member_id]['gift6'] = 'None'
            self.users[member_id]['gift7'] = 'None'
            self.users[member_id]['gift8'] = 'None'
            self.users[member_id]['gift9'] = 'None'
            self.users[member_id]['gift10'] = 'None'
            self.users[member_id]['gift11'] = 'None'
            self.users[member_id]['gift12'] = 'None'
            self.users[member_id]['gift13'] = 'None'
            self.users[member_id]['gift14'] = 'None'
            self.users[member_id]['gift15'] = 'None'
            self.users[member_id]['gift16'] = 'None'
            self.users[member_id]['gift17'] = 'None'
            self.users[member_id]['gift18'] = 'None'
            self.users[member_id]['gift19'] = 'None'
            self.users[member_id]['gift20'] = 'None'
            self.users[member_id]['gift21'] = 'None'
            self.users[author_id]['divorce_num'] = 0
        role = discord.utils.get(member.guild.roles, name="💍")
        author = ctx.message.author
        embedmarry = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        embedyee = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        embednii = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        embedalreadymarried = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        embedyoucantmarryyourselflmaoidiot = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        embedmarry.add_field(name='Свадьба :heart_exclamation: ',
                             value=f'{author.mention} предлагает вам свою руку и сердце! {member.mention}',
                             inline=False)
        embedmarry.add_field(name='Каков будет ваш ответ? :question: :thinking:  ',
                             value='Вы можете ответить с помощью **да** или **нет**, у вас есть целая минута, чтобы принять '
                                   'решение!',
                             inline=False)
        embedmarry.set_image(
            url='https://media1.tenor.com/images/69dbcb02b724d26644228a38e367d017/tenor.gif?itemid=14444888')
        embedyee.add_field(name='Удачная свадьба :heart:',
                           value=f'{author.mention} женился на {member.mention} ! Мои поздравления! ;) ')
        embedyee.set_image(
            url='https://cdn.discordapp.com/attachments/624296774747553808/642210564571004929/2c4259204e631b3e70cbd248331ac1e2.gif' or 'https://media1.tenor.com/images/ed8113a52d8517b31b4073b9ee9db314/tenor.gif?itemid=11767932')
        embednii.add_field(name='Свадьба неудачна :broken_heart: ',
                           value=f"{member.mention} отказалась(ся). Не плачь {author.mention} , найдешь кого-нибудь другого")
        embednii.set_image(
            url='https://cdn.discordapp.com/attachments/624296774747553808/642209594130694163/0caba0318aa667572c0ae30f34ecf8b62896aee5_hq.gif')
        embedalreadymarried.add_field(name='Вы уже женаты!',
                                      value=f'{author.mention} Вы уже женаты!')
        embedyoucantmarryyourselflmaoidiot.add_field(name='Свадьба неудачна :thinking:  :thinking: ',
                                                     value=f"Хмм?..На себе нельзя жениться, ты чего?")
        embedyoucantmarryyourselflmaoidiot.set_image(url='https://media1.giphy.com/media/GstlqgmrVgpuE/source.gif')

        if member == author:
            await ctx.send(embed=embedyoucantmarryyourselflmaoidiot)

        if self.users[author_id]['couple_id'] == member_id:
            await ctx.send(embed=embedalreadymarried)
        if (self.users[member_id]['couple_id'] != 'None' or self.users[author_id]['couple_id'] != 'None') and \
                self.users[author_id]['couple_id'] != member_id:
            await ctx.send('Сперва сделайте развод со своими партнерами')

        if role not in author.roles and role not in member.roles:
            if member != author:
                if self.users[author_id]['couple_id'] != member_id:
                    await ctx.send(embed=embedmarry)

                def check(message):
                    return message.content in (
                        'да', 'нет', 'Да', 'дА', 'ДА', 'Нет', 'нЕт', 'неТ', 'НЕт', 'НеТ', 'нЕТ', 'НЕТ')

                reply = await self.client.wait_for('message', check=check, timeout=30)
                if not reply or reply.content.casefold() == 'нет':
                    await ctx.send(embed=embednii)
                if not reply or reply.content.casefold() == 'да':
                    await ctx.send(embed=embedyee)
                    await discord.Member.add_roles(member, role)
                    await discord.Member.add_roles(author, role)
                    self.users[author_id]['couple_id'] = member_id
                    self.users[member_id]['couple_id'] = author_id

    @marry.error
    async def marry_timeout(self, ctx, error):
        if isinstance(error, commands.CommandInvokeError):
            embedtimeout = discord.Embed(
                color=discord.Colour.dark_purple()
            )
            embedtimeout.add_field(name='Оууууууууууу! :interrobang: ',
                                   value="Время свадьбы закончилось. Не беспокойтесь и попробуйте ещё раз!")
            embedtimeout.set_image(url='https://media3.giphy.com/media/uHJTtpE9WqfYc/source.gif')
            await ctx.send(embed=embedtimeout)
        if isinstance(error, commands.MissingRequiredArgument):
            embedmarryerror = discord.Embed(
                color=discord.Colour.dark_purple()
            )
            embedmarryerror.add_field(name='Ошибка',
                                      value=f' Укажите на ком хотите жениться. .marry @ \n Пример:')
            await ctx.send(embed=embedmarryerror)
            await ctx.send('```.marry @Clonexy700#3767```')

    @commands.command(pass_context=True)
    async def divorce(self, ctx):
        author_id = str(ctx.message.author.id)
        member = ctx.guild.get_member(int(self.users[author_id]['couple_id']))
        role = discord.utils.get(member.guild.roles, name="💍")
        author = ctx.message.author
        embeddivorce = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        embeddivorce.add_field(name='Развод :broken_heart:  :broccoli: ',
                               value=f'{author.mention} теперь больше не женаты с {member.mention}')
        embeddivorce.set_image(url="https://rabujoi.files.wordpress.com/2017/02/fuu62.jpg")
        embeddivorcefail = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        embeddivorcefail.add_field(name='Развод :broccoli:',
                                   value=f'{author.mention} не получилось развестись! Кажется ты или {member.mention} уже не женаты! ')
        embeddivorcefail.set_image(url='https://i.gifer.com/BtGB.gif')
        if role in author.roles and role in member.roles:
            await discord.Member.remove_roles(author, role)
            await discord.Member.remove_roles(member, role)
            member_id = self.users[author_id]['couple_id']
            self.users[member_id]['couple_id'] = 'None'
            self.users[author_id]['couple_id'] = 'None'
            self.users[author_id]['divorce_num'] += 1
            await ctx.send(embed=embeddivorce)
        else:
            await ctx.send(embed=embeddivorcefail)

    @commands.command(name='hentai', aliases=['ласкать', 'хентай'])
    async def hentai(self, ctx, member: discord.Member):
        msgend = [":spades:", ":clubs:", ":diamonds:", ":hearts:", ":fleur_de_lis:", ":black_heart:"]
        author = ctx.message.author
        author_id = str(ctx.message.author.id)
        member_id = str(member.id)
        if self.users[author_id]['couple_id'] == member_id:
            embedhentai = discord.Embed(
                color=discord.Colour.dark_purple()
            )
            hentaigifs = [
                "https://66.media.tumblr.com/e5921dae5876c00e1c3fcc0540ecab12/tumblr_opnxbzZbYT1sghvvyo1_500.gif",
                "https://i.pinimg.com/originals/fc/fa/b1/fcfab1d1656f5e9f859744ce999b35d5.gif",
                "https://ci.memecdn.com/1394312.gif",
                "https://lh3.googleusercontent.com/proxy/4N3f_aUCbDjN7Dcbvbd0xi1Fx1VNJsW_U4givReTfGarUG4S5-SFBAfpLa1BH0UaGbdQItlwQgqaErtORYcCmsUAtIYU9Z1xPw",
                "https://userdisk.webry.biglobe.ne.jp/020/046/94/N000/000/000/126525418193816203746_dat1265220059955.gif",
                "https://psv4.userapi.com/c610925/u259174237/docs/5e23102a51fa/3f74a54545774160611b83983fe8020c.gif?extra=xsXm8TuVauL_efYWOtBq1fhNRhqMvHTrxoauN58As_O2Nup80jf4VVVdB-z_6AflVR-bQRIO-U351o8_MauFbTRFbskG5jQbg073yy9tSDb1fEtF169xFrWq-fFoJz_1KVsOLxqrrdS8Zf8_QhMTpuA",
                "https://66.media.tumblr.com/32f890680919d5edb248cf6de10cd1cb/tumblr_nrdtcvHEhl1trw883o1_1280.gif",
                "https://x.imagefapusercontent.com/u/bvelasco/5823564/1635151298/gOqBNfD.gif",
                "https://66.media.tumblr.com/2bd84e6dcd5fcb76dbc0448ce7211cc1/tumblr_o5zxbaSKjE1rv1jano1_540.gif",
                "https://66.media.tumblr.com/3779148a1def9b5484ce33b873b02272/tumblr_nwjlolOMea1sz111so2_540.gif",
                "https://66.media.tumblr.com/05454f06a749373d72065dbdceadb50a/tumblr_ohbvseGCp81vkkt9ro1_1280.gif",
                "https://lh3.googleusercontent.com/proxy/vStpimmvo0WAaK6nk1SwgMtp7LlXPuleXsjuln82K80K3ZJ3SBOkz6F1u-KkmO1DKsJZs6k9ndgQ4aDmDcxUA84Lbh1vsODFjieODT_JzneyMAxD_RbpMpcdauaziRRlYBbvCMuv9FCyFbxrT3biqyN1WVv05swGG22wpSY3uQ",
                "https://lh3.googleusercontent.com/proxy/VFCSlrNEErwdJhkFVO5Sk9P3R-SWYcejlDrkQgwRmCqp5MJZCgqrmWS2Uah-WzMDgl80w0ljAYU-yiNqZJ2mYtg6lF03bjbZGkLE9rC2qKBAup_dtj3pM24kxI6M_Jife_ar45BtROxtq6MhJhPY1b0OiV8YGZFYKbFuusafuoaDtxtt",
                "https://2gifs.ru/images/p49.media.tumblr.com/544299c4e63878310a02957b5e5a133c/tumblr_nyw1ejWY2E1tlb937o1_500.gif",
                "https://cs6.pikabu.ru/images/big_size_comm_an/2014-05_3/14001629958442.gif",
                "https://img-4.poringa.net/poringa/img/8/1/E/1/B/E/FrankFolla/789.gif",
                "https://pbs.twimg.com/profile_images/855027348386701313/YIgX4cok_400x400.jpg",
                "https://lh3.googleusercontent.com/proxy/rNRpnzLDcrOdqA5UmT5BGXH0Wqhv-iE1bvB3D1bbhjRWesgyW8t6_RLvQhSOjMnJW77S_Xqyt_W-47ubVJgV668G7efQmvVcdqFPxdRBXJjnI10EWrOoepav3RdWhIYFKnQsPbA6YQ",
                "https://i.imgur.com/xuZ4dHi.gif"]
            embedhentai.add_field(name="Любовь :heart:",
                                  value=f"У {author.mention} и {member.mention} любовь. :heart: {random.choice(msgend)}")
            embedhentai.set_image(url=random.choice(hentaigifs))
            await ctx.send(embed=embedhentai)
        else:
            await ctx.send('Вы не женаты с данным человеком, поэтому не можете использовать данную команду')

    @commands.command(name='waifu', aliases=['вайфу', 'пара', 'жена'])
    async def waifu(self, ctx, member: discord.Member = None):
        emoji = self.client.get_emoji(676803534758477845)
        loli = self.client.get_emoji(680064619385192515)
        author = ctx.author if not member else member
        member_id = str(author.id)
        price = self.users[member_id]['price']
        if self.users[member_id]["couple_id"] == 'None':
            pair = 'None'
        else:
            pair = ctx.guild.get_member(int(self.users[member_id]['couple_id']))
            pair = pair.name
        waifu_menu = discord.Embed(
            color=discord.Colour.dark_purple(),
            timestamp=ctx.message.created_at,
            description=f'**Цена**\n{price}{emoji}\nВайфу {author.name}\n**Вместе с**\n{pair}\n Разводов {self.users[member_id]["divorce_num"]} :broken_heart:\n __**Подарки вайфу**__:'
        )
        waifu_menu.set_author(name=f'Вайфу {author.name}', icon_url=author.avatar_url)
        waifu_menu.set_thumbnail(url=author.avatar_url)
        gifts = 'Список всех ваших подарков: \n '
        if self.users[member_id]["gift1"] != 'None':
            waifu_menu.add_field(name='Трусы ', value=f':briefs: \n • {self.users[member_id]["gift1"]}', inline=True)
        if self.users[member_id]["gift2"] != 'None':
            waifu_menu.add_field(name='Лифчик ', value=f'🩱 \n • {self.users[member_id]["gift2"]}', inline=True)
        if self.users[member_id]["gift3"] != 'None':
            waifu_menu.add_field(name='Сапоги ', value=f'🥾 \n • {self.users[member_id]["gift3"]}', inline=True)
        if self.users[member_id]["gift4"] != 'None':
            waifu_menu.add_field(name='Котик ', value=f'🐱 \n • {self.users[member_id]["gift4"]}', inline=True)
        if self.users[member_id]["gift16"] != 'None':
            waifu_menu.add_field(name='Собачка ', value=f'🐶 \n • {self.users[member_id]["gift16"]}', inline=True)
        if self.users[member_id]["gift5"] != 'None':
            waifu_menu.add_field(name='Дом ', value=f'🏠 \n • {self.users[member_id]["gift5"]}', inline=True)
        if self.users[member_id]["gift6"] != 'None':
            waifu_menu.add_field(name='Манго ', value=f'🥭 \n • {self.users[member_id]["gift6"]}', inline=True)
        if self.users[member_id]["gift7"] != 'None':
            waifu_menu.add_field(name='Шарфик ', value=f'🧣 \n • {self.users[member_id]["gift7"]}', inline=True)
        if self.users[member_id]["gift17"] != 'None':
            waifu_menu.add_field(name='Носки ', value=f'🧦 \n • {self.users[member_id]["gift17"]}', inline=True)
        if self.users[member_id]["gift8"] != 'None':
            waifu_menu.add_field(name='Чулки ', value=f'🧦 \n • {self.users[member_id]["gift8"]}', inline=True)
        if self.users[member_id]["gift9"] != 'None':
            waifu_menu.add_field(name='Неко-уши ', value=f'👙 \n • {self.users[member_id]["gift9"]}', inline=True)
        if self.users[member_id]["gift10"] != 'None':
            waifu_menu.add_field(name='Хвостик ', value=f'👙 \n • {self.users[member_id]["gift10"]}', inline=True)
        if self.users[member_id]["gift11"] != 'None':
            waifu_menu.add_field(name='Кимоно ', value=f'👘 \n • {self.users[member_id]["gift11"]}', inline=True)
        if self.users[member_id]["gift18"] != 'None':
            waifu_menu.add_field(name='Костюм горничной ', value=f'👘 \n • {self.users[member_id]["gift18"]}',
                                 inline=True)
        if self.users[member_id]["gift12"] != 'None':
            waifu_menu.add_field(name='Ошейник ', value=f'👙 \n • {self.users[member_id]["gift12"]}', inline=True)
        if self.users[member_id]["gift13"] != 'None':
            waifu_menu.add_field(name='Очки ', value=f':eyeglasses: \n • {self.users[member_id]["gift13"]}',
                                 inline=True)
        if self.users[member_id]["gift14"] != 'None':
            waifu_menu.add_field(name='Лоли ', value=f'{loli} \n • {self.users[member_id]["gift14"]}', inline=True)
        if self.users[member_id]["gift15"] != 'None':
            waifu_menu.add_field(name='Чупа-Чупс ', value=f'🍭 \n • {self.users[member_id]["gift15"]}', inline=True)
        if self.users[member_id]["gift19"] != 'None':
            waifu_menu.add_field(name='Мишка ', value=f'🧸 \n • {self.users[member_id]["gift19"]}', inline=True)
        if self.users[member_id]["gift20"] != 'None':
            waifu_menu.add_field(name='Вино ', value=f':wine_glass: \n • {self.users[member_id]["gift20"]}', inline=True)
        if self.users[member_id]["gift21"] != 'None':
            waifu_menu.add_field(name='Торт ', value=f':birthday: \n • {self.users[member_id]["gift21"]}', inline=True)
        waifu_menu.set_footer(text=f'Запросил {ctx.author.name} \n (♥ω♥ ) ~♪')
        await ctx.send(embed=waifu_menu)

    @commands.command(name='gifts', aliases=['подарки', 'giftlist', 'мп', 'giftshop', 'пм'])
    async def gifts(self, ctx):
        emoji = self.client.get_emoji(676803534758477845)
        loli = self.client.get_emoji(680064619385192515)
        embed_gifts = discord.Embed(color=discord.Colour.dark_purple(), timestamp=ctx.message.created_at)
        embed_gifts.set_author(name='Подарки для вашей вайфу')
        embed_gifts.add_field(name='Трусы ', value=f':briefs: \n > 50 {emoji}', inline=True)
        embed_gifts.add_field(name='Лифчик', value=f'🩱 \n > 70 {emoji}', inline=True)
        embed_gifts.add_field(name='Сапоги', value=f'🥾 \n > 90 {emoji}', inline=True)
        embed_gifts.add_field(name='Кот', value=f'🐱 \n > 5000 {emoji}', inline=True)
        embed_gifts.add_field(name='Собака', value=f'🐶 \n > 5000 {emoji}', inline=True)
        embed_gifts.add_field(name='Дом', value=f'🏠 \n > 50000 {emoji}', inline=True)
        embed_gifts.add_field(name='Манго', value=f'🥭 \n > 20 {emoji}', inline=True)
        embed_gifts.add_field(name='Шарфик', value=f'🧣 \n > 60 {emoji}', inline=True)
        embed_gifts.add_field(name='Носки', value=f'🧦 \n > 300 {emoji}', inline=True)
        embed_gifts.add_field(name='Чулки', value=f'👙 \n > 600 {emoji}', inline=True)
        embed_gifts.add_field(name='Неко-уши', value=f'👙 \n > 800 {emoji}', inline=True)
        embed_gifts.add_field(name='Хвостик', value=f'👙 \n > 800 {emoji}', inline=True)
        embed_gifts.add_field(name='Кимоно', value=f'👘 \n > 1200 {emoji}', inline=True)
        embed_gifts.add_field(name='Костюм горничной', value=f'👘 \n > 2400 {emoji}', inline=True)
        embed_gifts.add_field(name='Ошейник', value=f'👙 \n > 2000 {emoji}', inline=True)
        embed_gifts.add_field(name='Очки', value=f':eyeglasses:  \n > 4000 {emoji}', inline=True)
        embed_gifts.add_field(name='Лоли', value=f'{loli} \n > 100000 {emoji}', inline=True)
        embed_gifts.add_field(name='Чупа-чупс', value=f'🍭 \n > 10 {emoji}', inline=True)
        embed_gifts.add_field(name='Мишка', value=f'🧸 \n > 2500 {emoji}', inline=True)
        embed_gifts.add_field(name='Вино', value=f':wine_glass: \n > 250 {emoji}', inline=True)
        embed_gifts.add_field(name='Торт', value=f':birthday: \n > 500 {emoji}', inline=True)
        embed_gifts.set_image(
            url='https://66.media.tumblr.com/c704b54b4390f2b2eef8d85c50d35dfd/tumblr_ofb1vtxYrF1th93f0o3_400.gif')
        embed_gifts.set_footer(text=f'запросил {ctx.author.name}')
        await ctx.send(embed=embed_gifts)

    @commands.command(name='gift', aliases=['подарить', 'гифт', 'п', 'подарок'])
    async def gift(self, ctx, member: discord.Member, gift=None, n: int = 1):
        loli = self.client.get_emoji(680064619385192515)
        member_id = str(member.id)
        author_id = str(ctx.author.id)
        embed_reply = discord.Embed(color=discord.Colour.dark_purple())
        gift = gift.casefold()

        if gift is None:
            def check(author):
                def inner_check(message):
                    return message.author == ctx.author and message.casefold().content in (
                        'трусы', 'лифчик', 'сапоги', 'кот', 'Собака', 'Дом', 'Манго', 'Шарфик', 'Носки', 'Чулки',
                        'Неко-уши', 'Хвостик', 'Кимоно', 'Ошейник', 'Лоли', 'Чупа-чупс', 'Костюм горничной', 'Очки', 'Мишка', 'Вино', 'Торт')

                return inner_check

            await ctx.send('Уточните пожалуйста подарок, который вы хотите отправить!')
        else:
            if gift == 'трусы':
                if self.client.currency[author_id]["money"] - 50 * n >= 0:
                    await self.client.unupdate_currency(author_id, 50 * n)
                    if self.users[member_id]["gift1"] == 'None':
                        self.users[member_id]["gift1"] = 0
                    self.users[member_id]["gift1"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 50 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Трусики '
                                                                    f':briefs:!')
            if gift == 'лифчик':
                if self.client.currency[author_id]["money"] - 70 * n >= 0:
                    await self.client.unupdate_currency(author_id, 70 * n)
                    if self.users[member_id]["gift2"] == 'None':
                        self.users[member_id]["gift2"] = 0
                    self.users[member_id]["gift2"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 70 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Лифчик '
                                                                    f'🩱!')
            if gift == 'сапоги':
                if self.client.currency[author_id]["money"] - 90 * n >= 0:
                    await self.client.unupdate_currency(author_id, 90 * n)
                    if self.users[member_id]["gift3"] == 'None':
                        self.users[member_id]["gift3"] = 0
                    self.users[member_id]["gift3"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 90 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Сапоги '
                                                                    f'🥾!')
            if gift == 'кот':
                if self.client.currency[author_id]["money"] - 5000 * n >= 0:
                    await self.client.unupdate_currency(author_id, 5000 * n)
                    if self.users[member_id]["gift4"] == 'None':
                        self.users[member_id]["gift4"] = 0
                    self.users[member_id]["gift4"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 5000 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Котика '
                                                                    f'🐱!')
            if gift == 'собака':
                if self.client.currency[author_id]["money"] - 5000 * n >= 0:
                    await self.client.unupdate_currency(author_id, 5000 * n)
                    if self.users[member_id]["gift16"] == 'None':
                        self.users[member_id]["gift16"] = 0
                    self.users[member_id]["gift16"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 5000 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Cобачку '
                                                                    f'🐶!')
            if gift == 'дом':
                if self.client.currency[author_id]["money"] - 50000 * n >= 0:
                    await self.client.unupdate_currency(author_id, 50000 * n)
                    if self.users[member_id]["gift5"] == 'None':
                        self.users[member_id]["gift5"] = 0
                    self.users[member_id]["gift5"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 50000 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Дом '
                                                                    f'🏠!')
            if gift == 'манго':
                if self.client.currency[author_id]["money"] - 20 * n >= 0:
                    await self.client.unupdate_currency(author_id, 20 * n)
                    if self.users[member_id]["gift6"] == 'None':
                        self.users[member_id]["gift6"] = 0
                    self.users[member_id]["gift6"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 20 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Манго '
                                                                    f'🥭!')
            if gift == 'шарфик':
                if self.client.currency[author_id]["money"] - 60 * n >= 0:
                    await self.client.unupdate_currency(author_id, 60 * n)
                    if self.users[member_id]["gift7"] == 'None':
                        self.users[member_id]["gift7"] = 0
                    self.users[member_id]["gift7"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 60 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Шарфик '
                                                                    f'🧣!')
            if gift == 'носки':
                if self.client.currency[author_id]["money"] - 300 * n >= 0:
                    await self.client.unupdate_currency(author_id, 300 * n)
                    if self.users[member_id]["gift17"] == 'None':
                        self.users[member_id]["gift17"] = 0
                    self.users[member_id]["gift17"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 300 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Носочки '
                                                                    f'🧦!')
            if gift == 'чулки':
                if self.client.currency[author_id]["money"] - 600 * n >= 0:
                    await self.client.unupdate_currency(author_id, 600 * n)
                    if self.users[member_id]["gift8"] == 'None':
                        self.users[member_id]["gift8"] = 0
                    self.users[member_id]["gift8"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 600 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Чулочки '
                                                                    f'👙!')
            if gift == 'неко-уши':
                if self.client.currency[author_id]["money"] - 800 * n >= 0:
                    await self.client.unupdate_currency(author_id, 800 * n)
                    if self.users[member_id]["gift9"] == 'None':
                        self.users[member_id]["gift9"] = 0
                    self.users[member_id]["gift9"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 800 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Неко-уши '
                                                                    f'👙!')
            if gift == 'хвостик':
                if self.client.currency[author_id]["money"] - 800 * n >= 0:
                    await self.client.unupdate_currency(author_id, 800 * n)
                    if self.users[member_id]["gift10"] == 'None':
                        self.users[member_id]["gift10"] = 0
                    self.users[member_id]["gift10"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 800 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Хвостик '
                                                                    f'👙!')
            if gift == 'кимоно':
                if self.client.currency[author_id]["money"] - 1200 * n >= 0:
                    await self.client.unupdate_currency(author_id, 1200 * n)
                    if self.users[member_id]["gift11"] == 'None':
                        self.users[member_id]["gift11"] = 0
                    self.users[member_id]["gift11"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 1200 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Кимоно '
                                                                    f'👘 !')
            if gift == 'костюм горничной':
                if self.client.currency[author_id]["money"] - 2400 * n >= 0:
                    await self.client.unupdate_currency(author_id, 2400 * n)
                    if self.users[member_id]["gift18"] == 'None':
                        self.users[member_id]["gift18"] = 0
                    self.users[member_id]["gift18"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 2400 * n
                    embed_reply.add_field(name='Вы подарили',
                                          value=f'{ctx.author.mention} подарил {member.mention} Костюм горничной '
                                                f'👘 !')
            if gift == 'ошейник':
                if self.client.currency[author_id]["money"] - 2000 * n >= 0:
                    await self.client.unupdate_currency(author_id, 2000 * n)
                    if self.users[member_id]["gift12"] == 'None':
                        self.users[member_id]["gift12"] = 0
                    self.users[member_id]["gift12"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 2000 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Ошейник '
                                                                    f'👙!')
            if gift == 'очки':
                if self.client.currency[author_id]["money"] - 4000 * n >= 0:
                    await self.client.unupdate_currency(author_id, 4000 * n)
                    if self.users[member_id]["gift13"] == 'None':
                        self.users[member_id]["gift13"] = 0
                    self.users[member_id]["gift13"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 4000 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Очечки '
                                                                    f':eyeglasses:!')
            if gift == 'лоли':
                if self.client.currency[author_id]["money"] - 100000 * n >= 0:
                    await self.client.unupdate_currency(author_id, 100000 * n)
                    if self.users[member_id]["gift14"] == 'None':
                        self.users[member_id]["gift14"] = 0
                    self.users[member_id]["gift14"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 100000 * n
                    embed_reply.add_field(name='Вы подарили', value=f'{ctx.author.mention} подарил {member.mention} Лольку '
                                                                    f'{loli}!')
            if gift == 'чупа-чупс':
                if self.client.currency[author_id]["money"] - 10 * n >= 0:
                    await self.client.unupdate_currency(author_id, 10 * n)
                    if self.users[member_id]["gift15"] == 'None':
                        self.users[member_id]["gift15"] = 0
                    self.users[member_id]["gift15"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 10 * n
                    embed_reply.add_field(name='Вы подарили',
                                          value=f'{ctx.author.mention} подарил {member.mention} Чупа-чупс 🍭!')
            if gift == 'мишка':
                if self.client.currency[author_id]["money"] - 2500 * n >= 0:
                    await self.client.unupdate_currency(author_id, 2500 * n)
                    if self.users[member_id]["gift19"] == 'None':
                        self.users[member_id]["gift19"] = 0
                    self.users[member_id]["gift19"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 2500 * n
                    embed_reply.add_field(name='Вы подарили',
                                          value=f'{ctx.author.mention} подарил {member.mention} Плюшевого мишку :teddy_bear: !')
            if gift == 'вино':
                if self.client.currency[author_id]["money"] - 250 * n >= 0:
                    await self.client.unupdate_currency(author_id, 250 * n)
                    if self.users[member_id]["gift20"] == 'None':
                        self.users[member_id]["gift20"] = 0
                    self.users[member_id]["gift20"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 250 * n
                    embed_reply.add_field(name='Вы подарили',
                                          value=f'{ctx.author.mention} подарил {member.mention} Винишко :wine_glass: !')
            if gift == 'торт':
                if self.client.currency[author_id]["money"] - 500 * n >= 0:
                    await self.client.unupdate_currency(author_id, 500 * n)
                    if self.users[member_id]["gift21"] == 'None':
                        self.users[member_id]["gift21"] = 0
                    self.users[member_id]["gift21"] += n
                    if self.users[member_id]["price"] == 1:
                        self.users[member_id]["price"] -= 1
                    self.users[member_id]["price"] += 500 * n
                    embed_reply.add_field(name='Вы подарили',
                                          value=f'{ctx.author.mention} подарил {member.mention} Тортик :birthday: !')
            await ctx.send(embed=embed_reply)

    @commands.command(name='ship', aliases=['шип', 'ебитес'], help=' ship 1st person with 2nd person')
    async def ship(self, ctx, member1: discord.Member, member2: discord.Member):
        role = discord.utils.get(member1.guild.roles, name="💍")
        empedship = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        empedship.add_field(name=':heart_eyes:  Ship :heart: ',
                            value=f' Шипперим {member1.mention} и {member2.mention} :smirk: ', inline=False)
        LovePossibility = random.randint(0, 100)
        LoveSymbolic = ["Между ними нет любви. ",
                        "▄ █ ",
                        "▄ █ █ ▄",
                        "▄ █ █ ▄ ▄ █",
                        "▄ █ █ ▄ ▄ █ ▄ █",
                        "▄ █ █ ▄ ▄ █ ▄ █ ▄ █ ▄",
                        "▄ █ █ ▄ ▄ █ ▄ █ ▄ █ ▄ █ ",
                        "▄ █ █ ▄ ▄ █ ▄ █ ▄ █ ▄ █ ▄ █",
                        "▄ █ █ ▄ ▄ █ ▄ █ ▄ █ ▄ █ ▄ █ ▆ ▅",
                        "▄ █ █ ▄ ▄ █ ▄ █ ▄ █ ▄ █ ▄ █ ▆ ▅ ▃",
                        "▄ █ █ ▄ ▄ █ ▄ █ ▄ █ ▄ █ ▄ █ ▆ ▅ ▃ ▂"]
        if member1 == member2:
            empedship.add_field(name=f'Ммм... Я думаю тут проблемка.',
                                value=f"Ты не можешь шипперить двух одинаковых людей.")
        if member1 != member2:
            if member2 or member1 != discord.User.bot:
                author_id = str(member1.id)
                member_id = str(member2.id)
                if role not in member1.roles or role not in member2.roles or self.users[author_id][
                    'couple_id'] != member_id:
                    if LovePossibility <= 5:
                        empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                            value=f'{LoveSymbolic[0]} {LovePossibility} % :broken_heart: ',
                                            inline=False)
                        empedship.set_image(
                            url='https://media1.tenor.com/images/2d432485a60674319ef423b643877ee4/tenor.gif?itemid=11302966')
                    if LovePossibility >= 6:
                        if LovePossibility <= 10:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[1]} __**{LovePossibility}%**__ :broken_heart: ',
                                                inline=False)
                            empedship.set_image(url='https://cdn42.picsart.com/171043668003202.gif?c256x256')
                    if LovePossibility >= 11:
                        if LovePossibility <= 19:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[2]} __**{LovePossibility}%**__ :black_heart: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/e375857e0f78c321b83040514b21a420/tenor.gif?itemid=13802170')
                    if LovePossibility >= 20:
                        if LovePossibility <= 29:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[3]} __**{LovePossibility}%**__ :black_heart: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/93f5876e82ae575a6c4b4613d57f6e29/tenor.gif?itemid=13665536')
                    if LovePossibility >= 30:
                        if LovePossibility <= 39:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[4]} __**{LovePossibility}%**__ :brown_heart: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/f0479ee873f30213a7a5579cc18da5d0/tenor.gif?itemid=12165912')
                    if LovePossibility >= 40:
                        if LovePossibility <= 49:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[5]} __**{LovePossibility}%**__ :hearts: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/93f5876e82ae575a6c4b4613d57f6e29/tenor.gif?itemid=13665536')
                    if LovePossibility >= 50:
                        if LovePossibility <= 59:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[6]} __**{LovePossibility}%**__ :heart_decoration: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/f0479ee873f30213a7a5579cc18da5d0/tenor.gif?itemid=12165912')
                    if LovePossibility >= 60:
                        if LovePossibility <= 69:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[7]} __**{LovePossibility}%**__ :blue_heart: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/4490d35d5950b90df2b7bccaf4f79922/tenor.gif?itemid=3478319')
                    if LovePossibility >= 70:
                        if LovePossibility <= 79:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[8]} __**{LovePossibility}%**__ :heartbeat: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/fb1aa76944c156acc494fff37ebdbcfa/tenor.gif?itemid=14521920')
                    if LovePossibility >= 80:
                        if LovePossibility <= 89:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[9]} __**{LovePossibility}%**__ :heart_exclamation: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/62a43e567137edec0d5231d5ec4b814b/tenor.gif?itemid=8955295')
                    if LovePossibility >= 90:
                        if LovePossibility <= 100:
                            empedship.add_field(name=f'Вероятность любви между {member1} и {member2} это :',
                                                value=f'{LoveSymbolic[10]} _**{LovePossibility}%**_ :heartpulse: ',
                                                inline=False)
                            empedship.set_image(
                                url='https://media1.tenor.com/images/8cab4f4c73547d077c56066461c40a5e/tenor.gif?itemid=12873196')
                author_id = str(member1.id)
                member_id = str(member2.id)
                if self.users[author_id]['couple_id'] == member_id:
                    if role in member1.roles and role in member2.roles:
                        empedship.add_field(name=f' {member1} и {member2} в любовных отношениях:',
                                            value=f"▄ █ █ ▄ ▄ █ ▄ █ ▄ █ ▄ █ ▄ █ ▆ ▅ ▃ ▂ _ **100%** :heartpulse: _\nОни "
                                                  f"женаты! Конечно "
                                                  f"же это любовь!")
                        empedship.set_image(
                            url='https://media1.tenor.com/images/8cbe0edadc12ca1056d5eb685a4c27f6/tenor.gif?itemid=14518537')
                await ctx.send(embed=empedship)

    @ship.error
    async def shiperror(self, ctx, error):
        if isinstance(error, commands.MissingRequiredArgument):
            embedmarryerror = discord.Embed(
                color=discord.Colour.dark_purple()
            )
            embedmarryerror.add_field(name='Ошибка синтаксиса команды',
                                      value=f' Пожалуйста идентифицируйте 1-го и 2-го пользователей. .ship @ @\n Пример:')
            await ctx.send(embed=embedmarryerror)
            await ctx.send('```.ship @Clonexy#3767 .Shiro ♣#9014```')

    @commands.command(name='waifunull', aliases=['waifureset', 'сбросвайфу', 'resetwaifu'])
    async def waifureset(self, ctx):
        author = ctx.author
        member_id = str(author.id)
        self.users[member_id]['price'] = 1
        self.users[member_id]['gift1'] = 'None'
        self.users[member_id]['gift2'] = 'None'
        self.users[member_id]['gift3'] = 'None'
        self.users[member_id]['gift4'] = 'None'
        self.users[member_id]['gift5'] = 'None'
        self.users[member_id]['gift6'] = 'None'
        self.users[member_id]['gift7'] = 'None'
        self.users[member_id]['gift8'] = 'None'
        self.users[member_id]['gift9'] = 'None'
        self.users[member_id]['gift10'] = 'None'
        self.users[member_id]['gift11'] = 'None'
        self.users[member_id]['gift12'] = 'None'
        self.users[member_id]['gift13'] = 'None'
        self.users[member_id]['gift14'] = 'None'
        self.users[member_id]['gift15'] = 'None'
        self.users[member_id]['gift16'] = 'None'
        self.users[member_id]['gift17'] = 'None'
        self.users[member_id]['gift18'] = 'None'
        self.users[member_id]['gift19'] = 'None'
        self.users[member_id]['gift20'] = 'None'
        self.users[member_id]['gift21'] = 'None'
        null = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        null.add_field(name='Ваша статистика',
                       value='Ваша статистика Вайфу была успешно обнулена по-вашему запросу, проверьте её с помощью команды .waifu !')
        await ctx.send(embed=null)

    @commands.command(name='waifutop', aliases=['топвайфу', 'вайфутоп', 'твайфу', 'лучшиевайфу', 'topwaifu'])
    async def waifutop(self, ctx):
        emoji = self.client.get_emoji(676803534758477845)
        kamo = ["(●♡∀♡)",
                "✿♥‿♥✿",
                "(♥ω♥ ) ~♪",
                "(｡･ω･｡)ﾉ♡",
                "(◍•ᴗ•◍)❤",
                "-ω(´•ω•｀)♡",
                "(◍•ᴗ•◍)♡ ✧*。",
                "( ◜◒◝ )♡",
                "(人 •͈ᴗ•͈)",
                "(´͈ ᵕ `͈ ♡°◌̊)",
                "(ღ˘⌣˘ღ)",
                "( ˘ ³˘)♥",
                "( ˘ ³˘)❤",
                "❣ (●❛3❛●)",
                "(っ˘з(˘⌣˘ )",
                "(◦˘ З(◦’ںˉ◦)♡",
                "(*-ω-)ω-*)"]
        with open('marry.json') as json_data:
            d = json.load(json_data)
            result = OrderedDict({k: v for k, v in sorted(d.items(), reverse=True, key=lambda i: i[1]["price"])})
        embed = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        for index, element in enumerate(result):
            try:
                user = await self.client.fetch_user(element)
                a = user.name
            except AttributeError:
                a = '?'
            embed.add_field(name=str(int(index + 1)),
                            value=f"``{random.choice(kamo)}`` | {a} - {result[element]['price']} {emoji}",
                            inline=False)
        await ctx.send(embed=embed)

    @commands.command(name='emojitest')
    async def testetetetetetetete(self, ctx):
        msg = discord.Embed(
            color=discord.Colour.dark_purple()
        )
        msg.add_field(name='Игровые роли:', value='_ _')
        msg = await ctx.send(embed=msg)
        reactions = [691522796970573856, 691523294515429377, 691523884675235960, 691524275454345286, 691525147445952583, 691525387473125376, 691525891100246027, 691526165566980176, 691526344919744513, 691526943006523441]
        for emoji_id in reactions:
            emoji = self.client.get_emoji(emoji_id)
            await msg.add_reaction(emoji)

def setup(client):
    client.add_cog(Marriage(client))


text:
import matplotlib.pyplot as plt
import numpy as np
from open_spiel.python.project.part_2 import path_file

########
# PATH #
########
path = "data/"
path1 = path + "rcfr_1000_iterations_ITER"
path2 = path + "rcfr_1000_iterations_EXPL"

########
# PLOT #
########
plt.plot(
    np.loadtxt(path1 + "0.txt"),
    [i*10**3 for i in np.loadtxt(path2 + "0.txt")],
    label="infinite data storage"
)
plt.plot(
    np.loadtxt(path1 + "1.txt"),
    [i*10**3 for i in np.loadtxt(path2 + "1.txt")],
    label="bootstrap"
)
plt.plot(
    np.loadtxt(path1 + "2.txt"),
    [i*10**3 for i in np.loadtxt(path2 + "2.txt")],
    label="reservoir buffer"
)
plt.xlabel("Iterations", fontweight="bold")
plt.ylabel("Exploitability (mbb/g)", fontweight="bold")
plt.loglog()
plt.legend()
plt.title("RCFR in Leduc poker: Storage", fontweight="bold")
plt.savefig("rcfr_storage_leduc"
            + path_file.plot_type,
            bbox_inches="tight")
plt.show()

ext: py

reason: import numpy


text:
import numpy as np

def document_vectorizer(corpus, model, num_features):
    """
    This averages all the word embeddings in the tweet.
    This function averages all the word embeddings in the tweet.

    corpus: String text corpus
    Model: Model to use
    num_features: Int, the number of features to use

    """
    vocabulary = set(model.wv.index_to_key)

    def average_word_vectors(words, model, vocabulary, num_features):
        feature_vector = np.zeros((num_features,), dtype="float64")
        nwords = 0.

        for word in words:
            if word in vocabulary:
                nwords += 1
                feature_vector = np.add(feature_vector, model.wv[word])
        if nwords:
            feature_vector = np.divide(feature_vector, nwords)

        return feature_vector

    features = [average_word_vectors(tokenized_sentence, model, vocabulary, num_features)
                for tokenized_sentence in corpus]

    return np.array(features)

def document_vectorizer_glove(corpus, model, num_features):
    """
    This function averages all the word embeddings based on the glove model.

    corpus: String text corpus
    Model: Model to use
    num_features: Int, the number of features to use

    returns: numpy array

    """
    vocabulary = set(model.index_to_key)

    def average_word_vectors(words, model, vocabulary, num_features):
        feature_vector = np.zeros((num_features,), dtype="float64")
        nwords = 0.

        for word in words:
            if word in vocabulary:
                nwords += 1
                feature_vector = np.add(feature_vector, model[word])
        if nwords:
            feature_vector = np.divide(feature_vector, nwords)

        return feature_vector

    features = [average_word_vectors(tokenized_sentence, model, vocabulary, num_features)
                for tokenized_sentence in corpus]

    return np.array(features)

max_stars_repo_name: AustinYunker/Twitter-Prediction

max_issues_repo_name: AustinYunker/Twitter-Prediction

max_forks_repo_name: AustinYunker/Twitter-Prediction


text:
"""
Mask R-CNN
Configurations and data loading code for MS COCO.

Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by Waleed Abdulla

------------------------------------------------------------

Usage: import the module (see Jupyter notebooks for examples), or run from
       the command line as such:

    # Train a new model starting from pre-trained COCO weights
    python3 coco.py train --dataset=/path/to/coco/ --model=coco

    # Train a new model starting from ImageNet weights. Also auto download COCO dataset
    python3 coco.py train --dataset=/path/to/coco/ --model=imagenet --download=True

    # Continue training a model that you had trained earlier
    python3 coco.py train --dataset=/path/to/coco/ --model=/path/to/weights.h5

    # Continue training the last model you trained
    python3 coco.py train --dataset=/path/to/coco/ --model=last

    # Run COCO evaluatoin on the last model you trained
    python3 coco.py evaluate --dataset=/path/to/coco/ --model=last
"""

import os
import sys
import time
import numpy as np
import glob

import zipfile
import urllib.request
import shutil
import imageio
import skimage.draw
import cv2
import datetime

# Root directory of the project
ROOT_DIR = os.path.abspath("../../")

# Import Mask RCNN
sys.path.append(ROOT_DIR)  # To find local version of the library
from mrcnn.config import Config
from mrcnn import model as modellib, utils

# Path to trained weights file
COCO_WEIGHTS_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5")

# Directory to save logs and model checkpoints, if not provided
# through the command line argument --logs
DEFAULT_LOGS_DIR = os.path.join(ROOT_DIR, "logs")

############################################################
#  Configurations
############################################################

class SsndaConfig(Config):
    """Configuration for training on MS COCO.
    Derives from the base Config class and overrides values specific
    to the COCO dataset.
    """
    # Give the configuration a recognizable name
    NAME = "ssnda"

    # We use a GPU with 12GB memory, which can fit two images.
    # Adjust down if you use a smaller GPU.
    IMAGES_PER_GPU = 2

    # Uncomment to train on 8 GPUs (default is 1)
    # GPU_COUNT = 8

    # Number of classes (including background)
    NUM_CLASSES = 1 + 4  # SSNDa has 4 classes

    WIDTH = 256
    HEIGHT = 160

    SEG_DIRS = ['ball', 'ball0', 'goal_left_left', 'goal_left_right',
                'goal_left_top', 'goal_right_left', 'goal_right_right',
                'goal_right_top', 'NAO#0', 'NAO#1', 'NAO#2', 'NAO#3', 'NAO#4']
    SEG_CLASSES = np.array([2, 2, 1, 1, 1, 1, 1, 1, 4, 3, 3, 4, 4], dtype=np.int32)
    NUMBER_OBSTACLES = len(SEG_DIRS)

############################################################
#  Dataset
############################################################

class SsndaDataset(utils.Dataset):
    def load_ssnda(self, dataset_dir, subset, class_ids=None,
                  class_map=None, auto_download=False):
        """Load a subset of the SSNDa dataset.
        dataset_dir: The root directory of the SSNDa dataset.
        subset: What to load (train, val, minival, valminusminival)
        class_ids: If provided, only loads images that have the given classes.
        class_map: TODO: Not implemented yet. Supports maping classes from
            different datasets to the same class ID.
        return_ssnda: If True, returns the SSNDa object.
        auto_download: Automatically download and unzip SSNDa images and annotations
        """

        # if auto_download is True:
        #     self.auto_download(dataset_dir, subset)

        # ssnda = SSNDa("{}/annotations/instances_{}{}.json".format(dataset_dir, subset, year))
        # if subset == "minival" or subset == "valminusminival":
        #     subset = "val"
        # image_dir = "{}/{}{}".format(dataset_dir, subset, year)

        # # Load all classes or a subset?
        # if not class_ids:
        #     # All classes
        #     class_ids = sorted(coco.getCatIds())

        # # All images or a subset?
        # if class_ids:
        #     image_ids = []
        #     for id in class_ids:
        #         image_ids.extend(list(coco.getImgIds(catIds=[id])))
        #     # Remove duplicates
        #     image_ids = list(set(image_ids))
        # else:
        #     # All images
        #     image_ids = list(coco.imgs.keys())

        # # Add classes
        # for i in class_ids:
        #     self.add_class("coco", i, coco.loadCats(i)[0]["name"])

        # Add classes.
        self.add_class("ssnda", 1, "goal")
        self.add_class("ssnda", 2, "ball")
        self.add_class("ssnda", 3, "robot_team")
        self.add_class("ssnda", 4, "robot_opponent")

        # Train or validation dataset?
        assert subset in ["train", "val", ""]
        dataset_dir = os.path.join(dataset_dir, "")
        print(dataset_dir)

        # Add images
        images_path = sorted(glob.glob(os.path.join(dataset_dir, "", 'rgb', '*' + '.png')))
        for img_path in images_path:
            self.add_image(
                "ssnda",
                image_id=img_path,
                path=img_path,
                width=SsndaConfig.WIDTH,
                height=SsndaConfig.HEIGHT)
        # if return_ssnda:
        #     return ssnda

    def load_mask(self, image_id):
        """Load instance masks for the given image.

        Different datasets use different ways to store masks. This
        function converts the different mask format to one format
        in the form of a bitmap [height, width, instances].

        Returns:
        masks: A bool array of shape [height, width, instance count] with
            one mask per instance.
        class_ids: a 1D array of class IDs of the instance masks.
        """
        # If not a SSDNa image, delegate to parent class.
        image_info = self.image_info[image_id]
        if image_info["source"] != "ssnda":
            return super(SsndaDataset, self).load_mask(image_id)

         # Convert polygons to a bitmap mask of shape
        # [height, width, instance_count]
        info = self.image_info[image_id]
        mask = np.zeros([info["height"], info["width"], SsndaConfig.NUMBER_OBSTACLES],
                        dtype=np.uint8)
        rgb_path, img_name = os.path.split(info["path"])
        dataset_dir = os.path.split(rgb_path)[0]

        # Add segmentations to mask
        for i in range(len(SsndaConfig.SEG_DIRS)):
            seg_dir = os.path.join(dataset_dir, 'obstacles_seg', SsndaConfig.SEG_DIRS[i], img_name)
            mask[:, :, i] = self.get_bool_image(seg_dir, info)

        return mask, SsndaConfig.SEG_CLASSES

    def get_bool_image(self, img_dir, info):
        im = None
        try:
            im = imageio.imread(img_dir)[:, :, 0].astype(np.bool)
        except FileNotFoundError:
            im = np.zeros((info["height"], info["width"]), dtype=np.bool)

        return im

def train(model):
    """Train the model."""
    # Training dataset.
    dataset_train = SsndaDataset()
    dataset_train.load_ssnda(args.dataset, "train")
    dataset_train.prepare()

    # Validation dataset
    dataset_val = SsndaDataset()
    dataset_val.load_ssnda(args.dataset, "val")
    dataset_val.prepare()

    # *** This training schedule is an example. Update to your needs ***
    # Since we're using a very small dataset, and starting from
    # COCO trained weights, we don't need to train too long. Also,
    # no need to train all layers, just the heads should do it.
    print("Training network heads")
    model.train(dataset_train, dataset_val,
                learning_rate=config.LEARNING_RATE,
                epochs=30,
                layers='heads')

def color_splash(image, mask):
    """Apply color splash effect.
    image: RGB image [height, width, 3]
    mask: instance segmentation mask [height, width, instance count]

    Returns result image.
    """
    # Make a grayscale copy of the image. The grayscale copy still
    # has 3 RGB channels, though.
    gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255
    # Copy color pixels from the original color image where mask is set
    if mask.shape[-1] > 0:
        # We're treating all instances as one, so collapse the mask into one layer
        mask = (np.sum(mask, -1, keepdims=True) >= 1)
        splash = np.where(mask, image, gray).astype(np.uint8)
    else:
        splash = gray.astype(np.uint8)
    return splash

def detect_and_color_splash(model, image_path=None, video_path=None):
    assert image_path or video_path

    # Image or video?
    if image_path:
        # Run model detection and generate the color splash effect
        print("Running on {}".format(args.image))
        # Read image
        image = skimage.io.imread(args.image)
        # Detect objects
        r = model.detect([image], verbose=1)[0]
        # Color splash
        splash = color_splash(image, r['masks'])
        # Save output
        file_name = "splash_{:%Y%m%dT%H%M%S}.png".format(datetime.datetime.now())
        skimage.io.imsave(file_name, splash)
    elif video_path:
        import cv2
        # Video capture
        vcapture = cv2.VideoCapture(video_path)
        width = int(vcapture.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(vcapture.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = vcapture.get(cv2.CAP_PROP_FPS)

        # Define codec and create video writer
        file_name = "splash_{:%Y%m%dT%H%M%S}.avi".format(datetime.datetime.now())
        vwriter = cv2.VideoWriter(file_name,
                                  cv2.VideoWriter_fourcc(*'MJPG'),
                                  fps, (width, height))

        count = 0
        success = True
        while success:
            print("frame: ", count)
            # Read next image
            success, image = vcapture.read()
            if success:
                # OpenCV returns images as BGR, convert to RGB
                image = image[..., ::-1]
                # Detect objects
                r = model.detect([image], verbose=0)[0]
                # Color splash
                splash = color_splash(image, r['masks'])
                # RGB -> BGR to save image to video
                splash = splash[..., ::-1]
                # Add image to video writer
                vwriter.write(splash)
                count += 1
        vwriter.release()
    print("Saved to ", file_name)

############################################################
#  Training
############################################################

if __name__ == '__main__':
    import argparse

    # Parse command line arguments
    parser = argparse.ArgumentParser(
        description='Train Mask R-CNN to detect SSNDa objects.')
    parser.add_argument("command",
                        metavar="<command>",
                        help="'train' or 'splash'")
    parser.add_argument('--dataset', required=False,
                        metavar="/path/to/balloon/dataset/",
                        help='Directory of the Balloon dataset')
    parser.add_argument('--weights', required=True,
                        default='',
                        metavar="/path/to/weights.h5",
                        help="Path to weights .h5 file or 'coco'")
    parser.add_argument('--logs', required=False,
                        default=DEFAULT_LOGS_DIR,
                        metavar="/path/to/logs/",
                        help='Logs and checkpoints directory (default=logs/)')
    parser.add_argument('--image', required=False,
                        metavar="path or URL to image",
                        help='Image to apply the color splash effect on')
    parser.add_argument('--video', required=False,
                        metavar="path or URL to video",
                        help='Video to apply the color splash effect on')
    args = parser.parse_args()

    # Validate arguments
    if args.command == "train":
        assert args.dataset, "Argument --dataset is required for training"
    elif args.command == "splash":
        assert args.image or args.video,\
               "Provide --image or --video to apply color splash"

    print("Weights: ", args.weights)
    print("Dataset: ", args.dataset)
    print("Logs: ", args.logs)

    # Configurations
    if args.command == "train":
        config = SsndaConfig()
    else:
        class InferenceConfig(SsndaConfig):
            # Set batch size to 1 since we'll be running inference on
            # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU
            GPU_COUNT = 1
            IMAGES_PER_GPU = 1
        config = InferenceConfig()
    config.display()

    # Create model
    if args.command == "train":
        model = modellib.MaskRCNN(mode="training", config=config,
                                  model_dir=args.logs)
    else:
        model = modellib.MaskRCNN(mode="inference", config=config,
                                  model_dir=args.logs)

    # Select weights file to load
    load_weights = True
    if args.weights.lower() == "coco":
        weights_path = COCO_WEIGHTS_PATH
        # Download weights file
        if not os.path.exists(weights_path):
            utils.download_trained_weights(weights_path)
    elif args.weights.lower() == "last":
        # Find last trained weights
        weights_path = model.find_last()
    elif args.weights.lower() == "imagenet":
        # Start from ImageNet trained weights
        weights_path = model.get_imagenet_weights()
    elif args.weights == "":
        load_weights = False
    else:
        weights_path = args.weights

    # Load weights
    if load_weights:
        print("Loading weights ", weights_path)
        if args.weights.lower() == "coco":
            # Exclude the last layers because they require a matching
            # number of classes
            model.load_weights(weights_path, by_name=True, exclude=[
                "mrcnn_class_logits", "mrcnn_bbox_fc",
                "mrcnn_bbox", "mrcnn_mask"])
        else:
            model.load_weights(weights_path, by_name=True)

    # Train or evaluate
    if args.command == "train":
        train(model)
    elif args.command == "splash":
        detect_and_color_splash(model, image_path=args.image,
                                video_path=args.video)
    else:
        print("'{}' is not recognized. "
              "Use 'train' or 'splash'".format(args.command))


text:
#!/usr/bin/env python3

# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import sys
import numpy as np
import faiss
from faiss_contrib.ondisk import merge_ondisk

#################################################################
# Small I/O functions
#################################################################

def ivecs_read(fname):
    a = np.fromfile(fname, dtype='int32')
    d = a[0]
    return a.reshape(-1, d + 1)[:, 1:].copy()

def fvecs_read(fname):
    return ivecs_read(fname).view('float32')

#################################################################
# Main program
#################################################################

stage = int(sys.argv[1])

tmpdir = '/tmp/'

if stage == 0:
    # train the index
    xt = fvecs_read("sift1M/sift_learn.fvecs")
    index = faiss.index_factory(xt.shape[1], "IVF4096,Flat")
    print("training index")
    index.train(xt)
    print("write " + tmpdir + "trained.index")
    faiss.write_index(index, tmpdir + "trained.index")

if 1 <= stage <= 4:
    # add 1/4 of the database to 4 independent indexes
    bno = stage - 1
    xb = fvecs_read("sift1M/sift_base.fvecs")
    i0, i1 = int(bno * xb.shape[0] / 4), int((bno + 1) * xb.shape[0] / 4)
    index = faiss.read_index(tmpdir + "trained.index")
    print("adding vectors %d:%d" % (i0, i1))
    index.add_with_ids(xb[i0:i1], np.arange(i0, i1))
    print("write " + tmpdir + "block_%d.index" % bno)
    faiss.write_index(index, tmpdir + "block_%d.index" % bno)

if stage == 5:

    print('loading trained index')
    # construct the output index
    index = faiss.read_index(tmpdir + "trained.index")

    block_fnames = [
        tmpdir + "block_%d.index" % bno
        for bno in range(4)
    ]

    merge_ondisk(index, block_fnames, tmpdir + "merged_index.ivfdata")

    print("write " + tmpdir + "populated.index")
    faiss.write_index(index, tmpdir + "populated.index")

if stage == 6:
    # perform a search from disk
    print("read " + tmpdir + "populated.index")
    index = faiss.read_index(tmpdir + "populated.index")
    index.nprobe = 16

    # load query vectors and ground-truth
    xq = fvecs_read("sift1M/sift_query.fvecs")
    gt = ivecs_read("sift1M/sift_groundtruth.ivecs")

    D, I = index.search(xq, 5)

    recall_at_1 = (I[:, :1] == gt[:, :1]).sum() / float(xq.shape[0])
    print("recall@1: %.3f" % recall_at_1)

max_stars_repo_name: bonezhang/faiss

max_issues_repo_name: bonezhang/faiss

max_forks_repo_name: bonezhang/faiss


text:
import csv
import datetime
import json
import time
from os.path import expanduser, exists
from zipfile import ZipFile

import numpy as np
from keras import backend as K
from keras.callbacks import ModelCheckpoint
from keras.layers import Embedding, Dense, Merge, BatchNormalization, TimeDistributed, Lambda
from keras.models import Sequential
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from keras.utils.data_utils import get_file
from sklearn.model_selection import train_test_split

KERAS_DATASETS_DIR = expanduser('~/.keras/datasets/')
POS_PAIRS_FILE = 'pos_count.txt'
NEG_PAIRS_FILE = 'neg_pair.txt'
GLOVE_ZIP_FILE_URL = 'http://nlp.stanford.edu/data/glove.840B.300d.zip'
GLOVE_ZIP_FILE = 'glove.840B.300d.zip'
GLOVE_FILE = 'glove.840B.300d.txt'
W1_TRAINING_DATA_FILE = 'w1_train.npy'
W2_TRAINING_DATA_FILE = 'w2_train.npy'
LABEL_TRAINING_DATA_FILE = 'label_train.npy'
NB_WORDS_DATA_FILE = 'nb_words.json'
MAX_NB_WORDS = 200000
MAX_SEQUENCE_LENGTH = 25
EMBEDDING_DIM = 300
MODEL_WEIGHTS_FILE = 'word_pairs_weights.h5'
VALIDATION_SPLIT = 0.1
TEST_SPLIT = 0.3
RNG_SEED = 13371447
NB_EPOCHS = 25

if exists(W1_TRAINING_DATA_FILE) and exists(W2_TRAINING_DATA_FILE) and exists(LABEL_TRAINING_DATA_FILE):
    w1_data = np.load(open(W1_TRAINING_DATA_FILE, 'rb'))
    w2_data = np.load(open(W2_TRAINING_DATA_FILE, 'rb'))
    labels = np.load(open(LABEL_TRAINING_DATA_FILE, 'rb'))

else:
    print("Data Pre-Processing")

    word1 = []
    word2 = []
    is_location = []
    with open(POS_PAIRS_FILE, encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile, delimiter='\t')
        for row in reader:
            word1.append(row[0])
            word2.append(row[1])
            is_location.append(1)

    with open(NEG_PAIRS_FILE, encoding='utf-8') as csvfile:
        reader = csv.reader(csvfile, delimiter='\t')
        for row in reader:
            word1.append(row[0])
            word2.append(row[1])
            is_location.append(0)
    print('Word pairs: %d' % len(word1))

    if not exists(KERAS_DATASETS_DIR + GLOVE_ZIP_FILE):
        zipfile = ZipFile(get_file(GLOVE_ZIP_FILE, GLOVE_ZIP_FILE_URL))
        zipfile.extract(GLOVE_FILE, path=KERAS_DATASETS_DIR)

    print("Processing", GLOVE_FILE)

    embeddings_index = {}
    with open(KERAS_DATASETS_DIR + GLOVE_FILE, encoding='utf-8') as f:
        for line in f:
            values = line.split(' ')
            word = values[0]
            embedding = np.asarray(values[1:], dtype='float32')
            embeddings_index[word] = embedding

    print('Word embeddings: %d' % len(embeddings_index))

    w1_data = []
    w2_data = []
    for w in word1:
        w1_data.append(embeddings_index[w])
    for w in word2:
        w2_data.append(embeddings_index[w])
    w1_data = np.array(w1_data)
    w2_data = np.array(w2_data)
    labels = np.array(is_location, dtype=int)

    print('Shape of word1 data tensor:', w1_data.shape)
    print('Shape of word2 data tensor:', w2_data.shape)
    print('Shape of label tensor:', labels.shape)

    np.save(open(W1_TRAINING_DATA_FILE, 'wb'), w1_data)
    np.save(open(W2_TRAINING_DATA_FILE, 'wb'), w2_data)
    np.save(open(LABEL_TRAINING_DATA_FILE, 'wb'), labels)

X = np.concatenate((w1_data, w2_data), axis=1)
y = labels
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=TEST_SPLIT, random_state=RNG_SEED)
# W1_train = X_train[:, 0]
# W2_train = X_train[:, 1]
# W_train = np.concatenate((W1_train, W2_train), axis=1)

# W1_test = X_test[:, 0]
# W2_test = X_test[:, 1]
# W_test = np.concatenate((W1_test, W2_test), axis=1)

# Q1 = Sequential()
# Q1.add(Dense(32, input_dim=EMBEDDING_DIM))
#
# Q2 = Sequential()
# Q2.add(Dense(32, input_dim=EMBEDDING_DIM))

model = Sequential()
# model.add(Merge([Q1, Q2], mode='concat'))
model.add(BatchNormalization(input_shape=(600,)))
model.add(Dense(200, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',
              optimizer='adam',
              metrics=['accuracy', 'precision', 'recall', 'fbeta_score'])

callbacks = [ModelCheckpoint(MODEL_WEIGHTS_FILE, monitor='val_acc', save_best_only=True)]

print("Starting training at", datetime.datetime.now())

t0 = time.time()
history = model.fit(X_train,
                    y_train,
                    nb_epoch=NB_EPOCHS,
                    validation_split=VALIDATION_SPLIT,
                    verbose=1,
                    callbacks=callbacks)
t1 = time.time()

print("Training ended at", datetime.datetime.now())

print("Minutes elapsed: %f" % ((t1 - t0) / 60.))

model.load_weights(MODEL_WEIGHTS_FILE)

loss, accuracy, precision, recall, fbeta_score = model.evaluate(X_test, y_test)
print('')
print('loss      = {0:.4f}'.format(loss))
print('accuracy  = {0:.4f}'.format(accuracy))
print('precision = {0:.4f}'.format(precision))
print('recall    = {0:.4f}'.format(recall))
print('F         = {0:.4f}'.format(fbeta_score))

max_stars_repo_name: adapt-sjtu/commonsense-locatednear


text:
import torch
import torch.nn as nn
import torch.optim as optim
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os, random, sys
import numpy as np
import matplotlib.pyplot as plt
import networks

#random seed
manualSeed = 1
np.random.seed(manualSeed)
random.seed(manualSeed)
torch.manual_seed(manualSeed)
if torch.cuda.is_available():
    torch.cuda.manual_seed(manualSeed)
    torch.cuda.manual_seed_all(manualSeed)
    torch.backends.cudnn.deterministic = True

device = 'cuda'
batch_size = 128
Z = 128
epochs = 1
T = 1

# Data
print('==> Preparing data..')
transform_train = transforms.Compose([
    transforms.ToTensor(),
])

trainset = torchvision.datasets.MNIST(
    root='./data', train=True, download=True, transform=transform_train)
trainloader = torch.utils.data.DataLoader(
    trainset, batch_size=batch_size, shuffle=True, num_workers=1)

# Model
print('==> Building model..')
model = networks.Memory(Z).to(device)

for m in model.modules():
    if isinstance(m, (nn.Conv2d, nn.Linear)):
        nn.init.orthogonal_(m.weight)

optimizer = optim.Adam(model.parameters(), lr=0.0001)

'''
# Load checkpoint.
print('==> Resuming from checkpoint..')
checkpoint = torch.load('./checkpoint_memory/ckpt.pth')
model.load_state_dict(checkpoint['model_state_dict'])
optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
'''

model.train()
# Training
for epoch in range(1):
    for batch_idx, (inputs,targets) in enumerate(trainloader):
        print('epoch: ', epoch, ' batch: ', batch_idx)

        inputs = inputs.to(device)
        x = torch.clamp(inputs, min=0.01, max=0.99)
        for layer in range(12):
            r = torch.zeros(x.shape, device=device)
            r.requires_grad_(True)

            fx = model.encoder[layer](x)

            for _ in range(T):
                fr = model.encoder[layer](r)
                cost = 0.5*torch.sum( (fx - fr)**2.0)
                r = r - torch.autograd.grad(cost, r, retain_graph=True, create_graph=True)[0]

            loss = 0.5*torch.sum( (x - r)**2.0)
            if layer == 0:
                r = torch.tanh(r)

            for p in model.encoder[layer].parameters():
                p.grad = torch.autograd.grad(loss, p, retain_graph=True, create_graph=True)[0]

            x = fx.detach()

        optimizer.step()

print('Saving..')
if not os.path.isdir('checkpoint_memory'):
    os.mkdir('checkpoint_memory')
torch.save({
        'model_state_dict': model.state_dict(),
        'optimizer_state_dict': optimizer.state_dict(),
        }, './checkpoint_memory/ckpt.pth')
print('done!')


text:
import numpy as np
import cv2
from single_colour_locate_HSV import *
# from closest_point import *
import closest_point2
import time

cap = cv2.VideoCapture("videos2/sample5.mov")

total_frames: int = 0
processing_time: float = 0
total_time: float = 0
scale_percent = 100

retval, img = cap.read()
width = int(img.shape[1] * scale_percent/100)
height = int(img.shape[0] * scale_percent/100)
dim = (width,height)
img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)

canvas = np.zeros(img.shape, dtype="uint8")
current_img = np.zeros(img.shape, dtype="uint8")

filename = "output-sample5.avi"
# out = cv2.VideoWriter(filename, cv2.VideoWriter_fourcc('M','J','P','G'), 5, (2*dim[0],dim[1]))

colour = (r_cl, y_cl, g_cl, c_cl, b_cl, m_cl)
colour_positions = dict()
body_points = {"left_wrist":(g_cl, c_cl, [], []), "left_elbow":(y_cl, c_cl, [], []), "left_shoulder":(y_cl, b_cl, [], [])}
# explanation for body_points data structure:
# key = point name
# assume val = body_points[key]
# val[0] = first colour = line colour
# val[1] = second colour = circle colour
# val[2] = list of centres
# val[3] = previous x and y. Once used, they will be cleared

# DONT ASK ME ABOUT THIS AFTER A MONTH.
# I WON"T REMEMBER HOW A SINGLE THING WORKS.

while True:
	c1 = 0
	c2 = 0

	retval, img = cap.read()

	if retval:
		time1 = time.process_time()

		img = cv2.resize(img, dim, interpolation=cv2.INTER_AREA)
		img = cv2.GaussianBlur(img, (3,3), 1.4)
		current_img = img

		for i in colour:
			colour_positions[i] = locate_with_colour(img, i)
			current_img = cv2.bitwise_and(current_img, colour_positions[i][0])

		for i in body_points:
			c1 = body_points[i][0]
			c2 = body_points[i][1]

			closest_point = closest_point2.closest_point_pair(colour_positions[c1][2], colour_positions[c2][2])
			if closest_point != -1:
				if closest_point[2] < 40:
					centre = (int((closest_point[0][0]+closest_point[1][0])/2),int((closest_point[0][1]+closest_point[1][1])/2))
					body_points[i][2].append((centre, total_frames))
					# cv2.circle(canvas, centre, 5, body_points[i][1], -1)
					if len(body_points[i][3]) > 0:
						cv2.line(canvas, centre, (body_points[i][3][0], body_points[i][3][1]), body_points[i][0], 2)
					body_points[i][3].clear()
					body_points[i][3].append(centre[0])
					body_points[i][3].append(centre[1])
				else:
					body_points[i][2].append((None, total_frames))
			else:
				body_points[i][2].append((None, total_frames))

		time2 = time.process_time() - time1

		cv2.putText(canvas,str(total_frames),(dim[0]-100, dim[1]-50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2)

		output_img = np.concatenate((current_img, canvas), axis=1)
		# cv2.imshow("output", output_img)
		# out.write(output_img)

		cv2.putText(canvas,str(total_frames),(dim[0]-100, dim[1]-50), cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 2)

		time3 = time.process_time() - time1

		k = cv2.waitKey(5) & 0xFF
		if k == 27:
			break

		total_frames+=1
		processing_time+=time2
		total_time+=time3

	else:
		break

	colour_positions.clear()

cap.release()
# out.release()
cv2.destroyAllWindows()

# canvas = cv2.flip(canvas, 0)
cv2.imwrite("output_img2.png", canvas)

print("Textual Data:")
print(body_points)
print("\nProcessing Information:")
print("\tStream Size: "+str(dim))
print("\tFrames Processed: "+str(total_frames))
print("\tProcessing Time (seconds): "+'{0:.2f}'.format(processing_time))
print("\tTotal Time (seconds): "+'{0:.2f}'.format(total_time))
print("\tProcessing Time per Frame (seconds): "+'{0:.2f}'.format(processing_time/total_frames))
print("\tTotal Time per Frame(seconds): "+'{0:.2f}'.format(total_time/total_frames))
print("\tAverage Processing FPS: "+'{0:.2f}'.format(total_frames/processing_time))
print("\tAverage FPS: "+'{0:.2f}'.format(total_frames/total_time))
exit()


text:
import argparse

import numpy as np
import pandas as pd

import ray

from xgboost_ray import RayDMatrix, train, RayParams
from xgboost_ray.data_sources.modin import MODIN_INSTALLED

def main(cpus_per_actor, num_actors):
    if not MODIN_INSTALLED:
        print("Modin is not installed or installed in a version that is not "
              "compatible with xgboost_ray (< 0.9.0).")
        return

    # Import modin after initializing Ray
    from modin.distributed.dataframe.pandas import from_partitions

    # Generate dataset
    x = np.repeat(range(8), 16).reshape((32, 4))
    # Even numbers --> 0, odd numbers --> 1
    y = np.tile(np.repeat(range(2), 4), 4)

    # Flip some bits to reduce max accuracy
    bits_to_flip = np.random.choice(32, size=6, replace=False)
    y[bits_to_flip] = 1 - y[bits_to_flip]

    data = pd.DataFrame(x)
    data["label"] = y

    # Split into 4 partitions
    partitions = [ray.put(part) for part in np.split(data, 4)]

    # Create modin df here
    modin_df = from_partitions(partitions, axis=0)

    train_set = RayDMatrix(modin_df, "label")

    evals_result = {}
    # Set XGBoost config.
    xgboost_params = {
        "tree_method": "approx",
        "objective": "binary:logistic",
        "eval_metric": ["logloss", "error"],
    }

    # Train the classifier
    bst = train(
        params=xgboost_params,
        dtrain=train_set,
        evals=[(train_set, "train")],
        evals_result=evals_result,
        ray_params=RayParams(
            max_actor_restarts=0,
            gpus_per_actor=0,
            cpus_per_actor=cpus_per_actor,
            num_actors=num_actors),
        verbose_eval=False,
        num_boost_round=10)

    model_path = "modin.xgb"
    bst.save_model(model_path)
    print("Final training error: {:.4f}".format(
        evals_result["train"]["error"][-1]))

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--address",
        required=False,
        type=str,
        help="the address to use for Ray")
    parser.add_argument(
        "--server-address",
        required=False,
        type=str,
        help="Address of the remote server if using Ray Client.")
    parser.add_argument(
        "--cpus-per-actor",
        type=int,
        default=1,
        help="Sets number of CPUs per xgboost training worker.")
    parser.add_argument(
        "--num-actors",
        type=int,
        default=4,
        help="Sets number of xgboost workers to use.")
    parser.add_argument(
        "--smoke-test", action="store_true", default=False, help="gpu")

    args, _ = parser.parse_known_args()

    if args.smoke_test:
        ray.init(num_cpus=args.num_actors + 1)
    elif args.server_address:
        ray.util.connect(args.server_address)
    else:
        ray.init(address=args.address)

    main(args.cpus_per_actor, args.num_actors)


text:
# (C) Copyright 2019 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Created on Sept 25, 2019

"""
Synthetic data set generation.

This module provides data suitable for testing the HEMM estimator and for
writing example notebooks.
"""

import numpy as np

def gen_outcomes(X, T, seed=0):
    """Synthetically generate outcome data from provided covariates and treatment assignment.

    Args:
        X: input covariates
        T: treatment assignment
        seed (int): seed to fix the random number generator

    Returns:
        y: observed outcomes
        mu1: true mean of treated group
        mu0: true mean of control group
        Z: indicator whether each sample belongs to positive enhanced or negative enhanced subgroup
    """
    np.random.seed(seed)
    n = X.shape[0]

    treated = np.where(T==1)[0]
    control = np.where(T==0)[0]

    pos = np.where(1-X[:, 1]<X[:, 0])[0]
    neg = np.where(X[:, 0]<=1-X[:, 1])[0]

    endist = (X[:, 0]-0.5 )**2 + (X[:, 1]-0.5 )**2

    posen = np.where(endist<0.1)[0]
    negen = np.where(endist>=0.1)[0]

    y   = np.zeros(n)
    mu1 = np.zeros(n)
    mu0 = np.zeros(n)

    treatposten  = list(set(treated)&set(pos)&set(posen))
    treatpostnen = list(set(treated)&set(pos)&set(negen))
    treatnegten  = list(set(treated)&set(neg)&set(posen))
    treatnegtnen = list(set(treated)&set(neg)&set(negen))
    controlpos   = list(set(control)&set(pos))
    controlneg   = list(set(control)&set(neg))

    y[treatposten]  = np.random.binomial(1, 0.8, len(treatposten))
    y[treatpostnen] = np.random.binomial(1, 0.6, len(treatpostnen))
    y[treatnegten]  = np.random.binomial(1, 0.6, len(treatnegten))
    y[treatnegtnen] = np.random.binomial(1, 0.4, len(treatnegtnen))
    y[controlpos]   = np.random.binomial(1, 0.4, len(controlpos))
    y[controlneg]   = np.random.binomial(1, 0.2, len(controlneg))

    mu0[pos]  = [0.4]*len(pos)
    mu0[neg]  = [0.2]*len(neg)

    posten  = list(set(pos)&set(posen))
    postnen = list(set(pos)&set(negen))
    negten  = list(set(neg)&set(posen))
    negtnen = list(set(neg)&set(negen))

    mu1[posten]  = [0.8]*len(posten)
    mu1[postnen] = [0.6]*len(postnen)
    mu1[negten]  = [0.6]*len(negten)
    mu1[negtnen] = [0.4]*len(negtnen)

    z = np.zeros(n)

    z[posen] = 1
    z[negen] = 0

    return y, mu1, mu0, z

def gen_treat(X, seed):
    """Generate treatment assignments for the given covariates.

    Args:
        X: input covariates
        seed: PRNG seed

    Returns:
        Individual treatment assignment.
    """
    np.random.seed(seed)

    less = np.where(X[:, 0]< 0.5)[0]
    more = np.where(X[:, 0]>=0.5)[0]

    treated = np.zeros(len(X))
    treated[more] = np.random.binomial(1, 0.6, len(more))
    treated[less] = np.random.binomial(1, 0.4, len(less))

    return treated

def gen_data(n, d, seed=0):
    """Generate outcome, treatment assignment and (d+1)-dimensional covariates for n samples.

    Args:
        n: desired number of samples.
        d: number of covariates.
        seed: PRNG seed

    Returns:
        X: generated covariates array, size = n x d+1
        T: generated treatment assignment
        Y: generated observed outcomes
        Z: generated indicator whether each sample belongs to positive enhanced or negative enhanced subgroup
        mu1: true mean counterfactual outcome under treatment
        mu0: true mean counterfactual outcome under control
    """
    np.random.seed(seed)

    treatment_group_size = n//2
    Xt = np.random.rand(treatment_group_size, d)
    Xc = np.random.rand(treatment_group_size, d)
    X = np.vstack([Xt, Xc])
    ones = np.array([np.ones(len(X))]).T
    X = np.hstack([X, ones])

    T = gen_treat(X, seed)

    Y, mu1, mu0, Z = gen_outcomes(X, T, seed)

    return X, T, Y, Z, mu1, mu0

def gen_montecarlo(n, d, num_repeats=100):
    """Generate synthetic train and test data (80:20 proportions).

    Args:
        n: desired number of samples.
        d: dimensionality of each samples (number of covariates) - 1
        num_repeats: number of subgroups to generate, each repeat will produce n covariates with dimension d + 1.

    Returns:
        Dictionary holding test and training data. Each data slot has the form:
            x: generated covariates array, size = n x d+1 x num_repeats
            t: generated treatment assignment for covariates, size = n x num_repeats
            yf: generated observed outcomes for each covariate, size = n x num_repeats
            Z: generated indicator whether each sample belongs to positive enhanced or negative enhanced subgroup.
               size = n x num_repeats
            mu1: true mean counterfactual outcome under treatment, size = n x num_repeats
            mu0: true mean counterfactual outcome under control, size = n x num_repeats
    """
    Xtr, Ttr, Ytr, Ztr, mu1tr, mu0tr = [], [], [], [], [], []
    Xte, Tte, Yte, Zte, mu1te, mu0te = [], [], [], [], [], []

    for repeat in range(num_repeats):
        X_, T_, Y_, Z_, mu1_, mu0_ = gen_data(n, d, repeat)

        # Of the n data points to generate, use 80% for training and 20% for testing.
        r = (4*n)//5

        X_tr, T_tr, Y_tr, Z_tr, mu1_tr, mu0_tr = X_[:r], T_[:r], Y_[:r], Z_[:r], mu1_[:r], mu0_[:r]
        X_te, T_te, Y_te, Z_te, mu1_te, mu0_te = X_[r:], T_[r:], Y_[r:], Z_[r:], mu1_[r:], mu0_[r:]

        Xtr.append(X_tr.T)
        Ttr.append(T_tr)
        Ytr.append(Y_tr)
        Ztr.append(Z_tr)
        mu1tr.append(mu1_tr)
        mu0tr.append(mu0_tr)

        Xte.append(X_te.T)
        Tte.append(T_te)
        Yte.append(Y_te)
        Zte.append(Z_te)
        mu1te.append(mu1_te)
        mu0te.append(mu0_te)

    data = {}
    data['TRAIN'] = {}
    data['TEST'] = {}

    data['TRAIN']['x'] = np.array(Xtr).T
    data['TRAIN']['t'] = np.array(Ttr).T
    data['TRAIN']['yf'] = np.array(Ytr).T
    data['TRAIN']['z'] = np.array(Ztr).T
    data['TRAIN']['mu1'] = np.array(mu1tr).T
    data['TRAIN']['mu0'] = np.array(mu0tr).T

    data['TEST']['x'] = np.array(Xte).T
    data['TEST']['t'] = np.array(Tte).T
    data['TEST']['yf'] = np.array(Yte).T
    data['TEST']['z'] = np.array(Zte).T
    data['TEST']['mu1'] = np.array(mu1te).T
    data['TEST']['mu0'] = np.array(mu0te).T

    return data

max_stars_repo_name: liranszlak/causallib


text:
# -*- coding: utf-8 -*-
import torch
import numpy as np
import torch.nn.functional as F

# 创建一个上三角矩阵：
#  1 1 1 1 1 1,.........1
#  1 1 1 1 1 1,.......1 0
#  1 1 1 1 1 1,.....1 0 0
#  ......
#  1 0 0 0 0 0 .........0

def get_mask(tscale):
    bm_mask = []
    for idx in range(tscale):
        mask_vector = [1 for i in range(tscale - idx)
                       ] + [0 for i in range(idx)]
        bm_mask.append(mask_vector)
    bm_mask = np.array(bm_mask, dtype=np.float32)
    return torch.Tensor(bm_mask)  # (100,100)的上三角矩阵

# pred_bm :(16,2,100,100)    gt_iou_map: (16,100,100)
# pred_start:(16,100)        gt_start:(16,100)
# pred_end:(16,100)          gt_end:(16,100)
# bm_mask: (100,100)

def bmn_loss_func(pred_bm, pred_start, pred_end, gt_iou_map, gt_start, gt_end, bm_mask):
    pred_bm_reg = pred_bm[:, 0].contiguous()  #(16,100,100)
    pred_bm_cls = pred_bm[:, 1].contiguous()  #(16,100,100)

    gt_iou_map = gt_iou_map * bm_mask  #(16,100,100)

    pem_reg_loss = pem_reg_loss_func(pred_bm_reg, gt_iou_map, bm_mask)  # 0.0411
    pem_cls_loss = pem_cls_loss_func(pred_bm_cls, gt_iou_map, bm_mask)  # 0.6933
    tem_loss = tem_loss_func(pred_start, pred_end, gt_start, gt_end)    # 1.3877

    loss = tem_loss + 10 * pem_reg_loss + pem_cls_loss
    return loss, tem_loss, pem_reg_loss, pem_cls_loss

def tem_loss_func(pred_start, pred_end, gt_start, gt_end):
    def bi_loss(pred_score, gt_label):  #(16,100),(16,100)
        pred_score = pred_score.view(-1)  # 1600
        gt_label = gt_label.view(-1)      # 1600
        pmask = (gt_label > 0.5).float()
        num_entries = len(pmask)   # 1600
        num_positive = torch.sum(pmask)  # 77
        ratio = num_entries / num_positive  # 20.77
        coef_0 = 0.5 * ratio / (ratio - 1)   #  0.5253
        coef_1 = 0.5 * ratio   # 10.3896
        epsilon = 0.000001  # 避免log陷入负无穷
        loss_pos = coef_1 * torch.log(pred_score + epsilon) * pmask
        loss_neg = coef_0 * torch.log(1.0 - pred_score + epsilon)*(1.0 - pmask)
        loss = -1 * torch.mean(loss_pos + loss_neg)
        return loss

    loss_start = bi_loss(pred_start, gt_start)  # 0.6937
    loss_end = bi_loss(pred_end, gt_end)  # 0.6939
    loss = loss_start + loss_end
    return loss

def pem_reg_loss_func(pred_score, gt_iou_map, mask):

    u_hmask = (gt_iou_map > 0.7).float()
    u_mmask = ((gt_iou_map <= 0.7) & (gt_iou_map > 0.3)).float()
    u_lmask = ((gt_iou_map <= 0.3) & (gt_iou_map > 0.)).float()
    u_lmask = u_lmask * mask

    num_h = torch.sum(u_hmask)  # 8136
    num_m = torch.sum(u_mmask)  # 32979
    num_l = torch.sum(u_lmask)  # 32900

    # 创建新的u_smmask和u_slmask为了平衡正负样本
    r_m = num_h / num_m  # 0.2473
    u_smmask = torch.Tensor(np.random.rand(*gt_iou_map.shape)).cuda()
    u_smmask = u_mmask * u_smmask
    u_smmask = (u_smmask > (1. - r_m)).float()  # (16,100,100)

    r_l = num_h / num_l  # 0.2476
    u_slmask = torch.Tensor(np.random.rand(*gt_iou_map.shape)).cuda()
    u_slmask = u_lmask * u_slmask
    u_slmask = (u_slmask > (1. - r_l)).float()  # (16,100,100)

    weights = u_hmask + u_smmask + u_slmask  # (16,100,100)

    loss = F.mse_loss(pred_score* weights, gt_iou_map* weights)
    loss = 0.5 * torch.sum(loss*torch.ones(*weights.shape).cuda()) / torch.sum(weights)

    return loss

def pem_cls_loss_func(pred_score, gt_iou_map, mask):  # pred_score = gt_iou_map = (16,100,100)

    pmask = (gt_iou_map > 0.9).float()
    nmask = (gt_iou_map <= 0.9).float()
    nmask = nmask * mask

    num_positive = torch.sum(pmask)  # 907
    num_negtive = torch.sum(nmask)  # 79893
    num_entries = num_positive + torch.sum(nmask)  # 80800
    ratio = num_entries / num_positive  # 89.0849
    coef_0 = 0.5 * ratio / (ratio - 1)  # 0.5057
    coef_1 = 0.5 * ratio  # 44.5424  让正样本的权重大些，因为正样本数量远小于负样本
    epsilon = 0.000001
    loss_pos = coef_1 * torch.log(pred_score + epsilon) * pmask   # (16,100,100)
    loss_neg = coef_0 * torch.log(1.0 - pred_score + epsilon) * nmask  # (16,100,100)
    loss = -1 * torch.sum(loss_pos + loss_neg) / num_entries
    return loss


text:
from .NewtonMethod import NewMeth
from .FstDiff import Jacobian
from .SecDiff import Hessian
from sympy import symbols, diff
from .GeneralDiff import Diff

#Symbol 2D vectors
x1 = symbols("x1")
x2 = symbols("x2")

reason: from sympy