import sys

class HMMlearn:

    TransProbDict = {}
    EmissionProbDict = {}
    WordTagDict = {}
    ListOfTags = []

    def createListOfTags(self, trainingFile):
        with open(trainingFile, "r", encoding="utf8") as file:
            for line in file:
                line = line.rstrip()
                wordsWithTag = line.split(' ')
                start = 1
                for pair in wordsWithTag:
                    word_tag = pair.rsplit('/', 1)
                    word = word_tag[0]
                    tag = word_tag[1]

                    if tag not in self.ListOfTags:
                        self.ListOfTags.append(tag)

    def readTrainFile(self, trainingFile):

        self.createListOfTags(trainingFile)
        #print(len(self.ListOfTags))

        with open(trainingFile, "r", encoding="utf8") as file:
            for line in file:
                line = line.rstrip()
                wordsWithTag = line.split(' ')
                start = 1
                for pair in wordsWithTag:
                    word_tag = pair.rsplit('/', 1)
                    word = word_tag[0]
                    tag = word_tag[1]

                    #Transition Probabilities
                    if start == 1:
                        prevTag = "q0"

                    if prevTag in self.TransProbDict.keys():
                        dictOfSuccTags = self.TransProbDict[prevTag]
                        if tag in dictOfSuccTags.keys():
                            dictOfSuccTags[tag] = dictOfSuccTags[tag] + 1
                        else:
                            dictOfSuccTags[tag] = 1
                    else:
                        dictOfSuccTags = {}
                        dictOfSuccTags[tag] = 1
                        self.TransProbDict[prevTag] = dictOfSuccTags
                    prevTag = tag
                    start = 0

                    #Emission Probabilities
                    if tag in self.EmissionProbDict.keys():
                        dictOfWords = self.EmissionProbDict[tag]
                        if word in dictOfWords.keys():
                            dictOfWords[word] = dictOfWords[word] + 1
                        else:
                            dictOfWords[word] = 1
                        self.EmissionProbDict[tag] = dictOfWords
                    else:
                        dictOfWords = {}
                        dictOfWords[word] = 1
                        self.EmissionProbDict[tag] = dictOfWords

                    #TagsRelatedToWords
                    if word in self.WordTagDict:
                        listOfTags = self.WordTagDict[word]
                        if tag not in listOfTags:
                            listOfTags.append(tag)
                    else:
                        listOfTags = [tag]
                        self.WordTagDict[word] = listOfTags

            #print(self.TransProbDict)
            #print(self.EmissionProbDict)

            self.applySmoothing()

            for masterTag in self.TransProbDict.keys():
                dictOfTags = self.TransProbDict[masterTag]
                sum = 0
                for eachTag in dictOfTags:
                    sum = sum + dictOfTags[eachTag]
                #dictOfTags["Total"] = sum
                for eachTag in dictOfTags:
                    dictOfTags[eachTag] = dictOfTags[eachTag]/sum
                self.TransProbDict[masterTag] = dictOfTags

            for tag in self.EmissionProbDict.keys():
                dictOfWords = self.EmissionProbDict[tag]
                sum = 0
                for word in dictOfWords:
                    sum = sum + dictOfWords[word]
                #dictOfWords["Total"] = sum
                for word in dictOfWords:
                    dictOfWords[word] = dictOfWords[word]/sum
                self.EmissionProbDict[tag] = dictOfWords

            self.printModelFile()

    def applySmoothing(self):
        for tag in self.ListOfTags:
            if tag not in self.TransProbDict.keys():
                self.TransProbDict[tag] = {}

        for masterTag in self.TransProbDict.keys():
            dictOfTags = self.TransProbDict[masterTag]
            for childTag in dictOfTags.keys():
                num = dictOfTags[childTag]
                num = num + 1
                dictOfTags[childTag] = num

            for tag in self.ListOfTags:
                if tag not in dictOfTags.keys():
                    dictOfTags[tag] = 1

    def printModelFile(self):
        with open("hmmmodel.txt", "w") as text_file:
            outputDict = {}
            outputDict["TransitionProb"] = self.TransProbDict
            text_file.write(str(outputDict))
            text_file.write("\n")
            outputDict = {}
            outputDict["EmissionProb"] = self.EmissionProbDict
            text_file.write(str(outputDict))
            text_file.write("\n")
            outputDict = {}
            outputDict["WordTagDict"] = self.WordTagDict
            text_file.write(str(outputDict))

learnObject = HMMlearn()
learnObject.readTrainFile(sys.argv[1])
#learnObject.readTrainFile("catalan_corpus_train_tagged.txt")
#learnObject.readTrainFile("test.txt")


import matplotlib.pyplot as plt
import numpy as np

fig, axs = plt.subplots(nrows=3, ncols=1)

fs = 1000
frequency = 50

duration = 1
t = np.linspace(0.0, duration, int(duration * 1000))
amplitude = 1.0

signal = amplitude * np.sin(2 * np.pi * frequency * t)

axs[0].plot(t, signal)
axs[0].set_title("Semnal original")
axs[0].set_xlabel("Timp")
axs[0].set_ylabel("Amplitudine")

t_2 = t[::4]
signal_2 = signal[::4]

axs[1].plot(t_2, signal_2)
axs[1].set_title("Semnal decimat")
axs[1].set_xlabel("Timp")
axs[1].set_ylabel("Amplitudine")

t_3 = t_2[::4]
signal_3 = signal_2[::4]

axs[2].plot(t_3, signal_3)
axs[2].set_title("Semnal decimat")
axs[2].set_xlabel("Timp")
axs[2].set_ylabel("Amplitudine")

plt.tight_layout()
plt.savefig("ex7.pdf")
plt.show()


import common.settings as settings
import common.app as app
import common.qml_names as qml

# squish dependent
import names

@OnFeatureStart
def hook(context):
    start_neptune_ui_app_w_focus("console")

def find_homeWidgetGrid_app(app_name):
    """helper function"""
    good = False
    result = None

    found, app_idname = app.get_app_id(app_name)

    if found:
        object_name = qml.home_widget + app_idname
        grid_view = waitForObject(
            names.neptune_3_UI_Center_Console_widgetGrid_homepage_WidgetGrid)

        grid_entry = find_object_name_recursively(grid_view, object_name, 3)

        if grid_entry is not None:
            good = True
            result = grid_entry
    return good, (result, app_idname)

@Then("add widget was tapped")
def step(context):
    tapObject(waitForObject(names.neptune_3_UI_Center_Console_addWidgetButton_ToolButton))

@Then("the new widget dialogue appeared")
def step(context):
    test.compare(waitForObjectExists(names.neptune_3_UI_Center_Console_addWidgetPopupItem_AddWidgetPopup).enabled, True)
    test.compare(waitForObjectExists(names.neptune_3_UI_Center_Console_addWidgetPopupItem_AddWidgetPopup).visible, True)

@Then("the add widget popup should not be there after '|integer|' seconds of closing animation")
def step(context, seconds):
    snooze(seconds)
    addWidget_popup = names.neptune_3_UI_Center_Console_addWidgetPopupItem_AddWidgetPopup
    # test.compare(volume_popup.exists) something funny??
    try:
        waitForObjectExists(addWidget_popup, settings.G_WAIT_FOR_INEXISTANCE_MS)
    except Exception:
        test.compare(True, True, "add widget popup closed!")
    else:
        test.compare(True, False, "add widget popup is still there!")

@Then("the '|word|' widget is visible in the home screen")
def step(context, app_name):
    good, result = find_homeWidgetGrid_app(app_name)
    if good:
        widget, _id = result
        test.compare(widget.enabled, True)
        test.compare(widget.visible, True)
    else:
        test.fail("grid widget item of '" + app_name + "' not found!")

@When("add map is tapped")
def step(context):
    addWidgetItem_maps = waitForObject(names.widgetList_AddWidgets_Maps)
    tapObject(addWidgetItem_maps)

@Then("tapping close '|word|' widget")
def step(context, app_name):
    # update context, because map is now if not before loaded
    squish.snooze(1)
    app.update_all_contexts()

    # must switch to main_app
    app.switch_to_main_app()

    found, result = find_homeWidgetGrid_app(app_name)
    if found:
        grid_entry, app_idname = result
        close_name = qml.app_widget_close + app_idname
        close_obj = find_object_name_recursively(grid_entry, close_name, 3)

        if close_obj is not None and close_obj.visible:
            tapObject(close_obj)

@Then("the '|word|' widget disappeared in the home screen after '|integer|' seconds of animation")
def step(context, app_name, seconds):
    squish.snooze(seconds)
    found, result = find_homeWidgetGrid_app(app_name)
    if found:
        grid_entry, _id = result
        try:
            is_enabled = grid_entry.enabled
            is_visible = grid_entry.visible
        except Exception as e:
            test.fail("Something strange with the grid object: " + str(e))
        else:
            test.compare(False, not is_enabled or not is_visible,
                         "'" + app_name + "' widget not enabled or visible!")
    else:
        test.compare(True, True,
                     "'" + app_name + "' widget closed!")


import asyncio
from bilibili_api import live, user, Credential
import aioredis
import json
import os
import logging

# 你的凭证信息，参照bilibili_api的文档
CREDENTIAL = Credential(sessdata= "############",
                            bili_jct="############",
                            buvid3="############")

# 一些Constant
follower_add = 10
club_add = 10
base_count = 2

# 连接redis
async def connect_to_redis():
    pool = aioredis.ConnectionPool.from_url("redis://ip:port/0", encoding="utf-8", decode_responses=True)
    client = aioredis.Redis(connection_pool=pool)
    await client.set("my-key", "value")
    value = await client.get("my-key")
    print(value)
    return client

#F 发送到ChatGPT redis队列
async def save_danmaku_to_redis(redis, queue_name, user_id, username, avatar_url, message, is_admin):
    danmaku_data = {
        'user_id': user_id,
        'username': username,
        'avatar_url': avatar_url,
        'message': message,
        'is_admin': is_admin
    }
    res = await redis.lpush(queue_name, json.dumps(danmaku_data))
    print(res)

#F 存入头像、用户名到redis
async def save_user_to_redis(redis,  user_id, username, avatar_url):
    await redis.hset(f"userinfo:{user_id}", 'username', username)
    await redis.hset(f"userinfo:{user_id}", 'avatar', avatar_url)

#F 发送到语音redis队列
async def direct_chat_to_redis(redis, user_id, username, message, reply):
    danmaku_data = {
        'user_id': user_id,
        'username': username,
        'message': message,
        'reply': reply
    }
    res = await redis.lpush("chat", json.dumps(danmaku_data))
    print(res)

# 获取用户名、头像
async def get_user_info(user_id):
    _user = user.User(user_id)
    user_info = await _user.get_user_info()
    return user_info['name'], user_info['face']

def filter_danmaku(message):
    # 过滤包含特定字符的弹幕
    if any(char in message for char in "[]{}\\"):
        return False
    return True

async def handle_danmaku(danmaku):
    user_id = danmaku["data"]["info"][2][0]
    message = danmaku["data"]["info"][1]
    room_id = danmaku["room_display_id"]

    #以下是指令集
    if message.startswith("\\查询"):
        point = await redis.hget(f"point:{room_id}", user_id)
        if int(point) is None:
            point = 0
        danmaku = live.Danmaku(f"[当前剩余功德:{point}]")
        await live_info.send_danmaku(danmaku)
        return
    elif message.startswith("\\喵"):
        count = await redis.hget(f"freeTimes:{room_id}", user_id)
        if count is None:
            count = 0
        if int(count) > 3:
            return

        await redis.hincrby(f"freeTimes:{room_id}", user_id)
        await redis.hsetnx(f"point:{room_id}", user_id, 0)
        point = await redis.hincrby(f"point:{room_id}",user_id, 10)
        danmaku = live.Danmaku(f"[当前剩余功德:{point}]")
        await live_info.send_danmaku(danmaku)
        return

    elif message.startswith("\\今日次数"):
        res = await redis.zrank(f"dahanghai:{room_id}",user_id)
        # 大航海无限次
        if res is not None:
            danmaku = live.Danmaku(f"[剩余次数:无限]")
            await live_info.send_danmaku(danmaku)
        else:
            if (await redis.sismember(f"fanclub:{room_id}", user_id)) == 0:
                c1 = club_add
            if (await redis.sismember(f"followers:{room_id}", user_id)) == 0:
                c2 = follower_add
            speech_count = await redis.hincrby(f"count:{room_id}",user_id)
            speech_rest = c1 + c2 + base_count - speech_count
            point = await redis.hget(f"point:{room_id}",user_id)
            danmaku = live.Danmaku(f"[剩余次数{speech_rest},剩余功德{point}]")
            await live_info.send_danmaku(danmaku)

    # 过滤弹幕
    if not filter_danmaku(message):
        return

    # 获取用户名和头像URL，存入redis
    username, avatar_url = await get_user_info(user_id)
    save_user_to_redis(redis, user_id, username, avatar_url)

    #获取用户是否是大航海
    res = await redis.zrank(f"dahanghai:{room_id}",user_id)
    if res is None:
        c1 = 0
        c2 = 0
        await redis.hsetnx(f"count:{room_id}",user_id, 0)
        count = await redis.hincrby(f"count:{room_id}",user_id)

        # 粉丝团，关注追加
        if (await redis.sismember(f"fanclub:{room_id}", user_id)) == 1:
            c1 = club_add
        if (await redis.sismember(f"followers:{room_id}", user_id)) == 1:
            c2 = follower_add

        # 超额屏蔽, 10功德对话一次
        if count > base_count + c1 + c2:
            point = await redis.hget(f"point:{room_id}", user_id)
            if point is None or int(point) <= 0:
                danmaku = live.Danmaku(f"[剩余次数不足，请关注主播增加次数]")
                await live_info.send_danmaku(danmaku)
                return
            else:
                await redis.hincrby(f"point:{room_id}", user_id, -10)

        queue_name = 'normal_danmaku'
        is_guard = True
    else:
        queue_name = 'guard_danmaku'
        is_guard = True
    logger.info(f"GET A MESSAGE TO {queue_name}, userid={user_id}, username={username}, message={message}")

    #发送到chatgpt处理队列
    await save_danmaku_to_redis(redis, queue_name, user_id, username, avatar_url, message, is_guard)

async def welcome(info):
    user_id = info["data"]["data"]["uid"]
    username = info["data"]["data"]["uname"]

    # 获取用户名和头像URL
    message = f""
    reply = f"欢迎{username}来到{room_owner}的直播间，喵。"
    logger.info(reply)

    #发送一个欢迎进入的语音
    await direct_chat_to_redis(redis, user_id, username, message, reply)

async def gift_heard(info):
    room_id = info["room_display_id"]
    user_id = info["data"]["data"]["uid"]
    avatar_url = info["data"]["data"]["face"]
    giftName = info["data"]["data"]["giftName"]
    username = info["data"]["data"]["uname"]
    giftNum = info["data"]["data"]['num']
    # 电池数
    value = int(info["data"]["data"]['price'] / 10)
    save_user_to_redis(redis, user_id, username, avatar_url)

    # 获取用户名和头像URL
    message = f""
    reply = f"\\感谢{username}赠送的{giftNum}个{giftName}喵。"
    logger.info(reply)

    # 计算用户投喂
    await redis.hsetnx(f"point:{room_id}", user_id, 0)
    await redis.zincrby(f"cost:{room_id}", value, user_id)
    point = await redis.hincrby(f"point:{room_id}", user_id, value)

    #发送一个感谢投喂的语音
    await direct_chat_to_redis(redis, user_id, username, message, reply)

    #发送弹幕
    danmaku = live.Danmaku(f"[当前功德:{point}]")
    await live_info.send_danmaku(danmaku)

async def super_chat(info):
    room_id = info["room_display_id"]
    user_id = info["data"]["data"]["uid"]
    message = info["data"]["data"]["message"]
    username = info["data"]["data"]["user_info"]["uname"]
    avatar_url = info["data"]["data"]["user_info"]["face"]
    value = int(info["data"]["data"]["price"] * 100)
    save_user_to_redis(redis, user_id, username, avatar_url)
    is_guard = True
    queue_name = "superchat_danmaku"
    logger.info(f"GET A MESSAGE TO {queue_name}, userid={user_id}, username={username}, message={message}")

    # 计算用户投喂
    await redis.zincrby(f"cost:{room_id}", value, user_id)
    await redis.hsetnx(f"point:{room_id}", user_id, 0)
    await redis.hincrby(f"point:{room_id}", user_id, value)

    await save_danmaku_to_redis(redis, queue_name, user_id, username, message, is_guard)

async def main():
    # 直播间配置
    global live_info
    global logger
    global room_owner
    room_owner = "你的直播间名"
    room_id = 0 #你的直播间roomID
    live_room = live.LiveDanmaku(room_id)
    live_info = live.LiveRoom(room_id, credential=CREDENTIAL)

    # Log配置
    logger= logging.getLogger('my_logging')
    logger.setLevel(logging.INFO)
    proDir = os.path.split(os.path.realpath(__file__))[0]
    logPath = os.path.join(proDir, "getDanmaku.log")
    fh = logging.FileHandler(logPath, encoding='utf8')
    fh.setLevel(logging.INFO)
    logger.addHandler(fh)

    # 连接到Redis
    global redis
    redis = await connect_to_redis()

    # 监听弹幕事件
    live_room.add_event_listener("DANMU_MSG", handle_danmaku)
    live_room.add_event_listener("INTERACT_WORD", welcome)
    live_room.add_event_listener("SEND_GIFT", gift_heard)
    live_room.add_event_listener("SUPER_CHAT_MESSAGE", super_chat)

    # 连接到直播间
    await live_room.connect()

    # 无限循环
    while True:
        await asyncio.sleep(1)

asyncio.run(main())


import sys
import os
import shutil
import logging

_DATASET_DIR = ''
_BASE_DIR = './dataset'
_TRAIN_DIR = 'train'
_VALIDATION_DIR = 'validation'
_TEST_DIR = 'test'

def welcome():
    print('\n-------------------------------------------------------------\n' +
          'This script are used for creation training, validation and\n' +
          'testing data from datasets UTKFace and any others in future.\n' +
          'author: Igor Sitnikov\n' +
          'organization: AILabs\n' +
          '-------------------------------------------------------------\n')

def utkface_create_data(valid_dir=True, label_mask=0):
    try:
        print('UTKFace dataset\nlink: https://susanqq.github.io/UTKFace/\n')
        print('# Creation of folders...')

        if not os.path.exists(_BASE_DIR):
            os.mkdir(_BASE_DIR)

        train_dir = os.path.join(_BASE_DIR, _TRAIN_DIR)
        if not os.path.exists(train_dir):
            os.mkdir(train_dir)

        if (valid_dir):
            valid_dir = os.path.join(_BASE_DIR, _VALIDATION_DIR)
            if not os.path.exists(valid_dir):
                os.mkdir(valid_dir)

        test_dir = os.path.join(_BASE_DIR, _TEST_DIR)
        if not os.path.exists(test_dir):
            os.mkdir(test_dir)
        print("# Folders are created")

        files = os.listdir(_DATASET_DIR)
        train_indices = list(filter(lambda i: i % 4 != 0, range(len(files))))
        test_indices = list(filter(lambda i: i % 4 == 0, range(len(files))))
        valid_indices = list(filter(lambda i: i % 2 == 0, test_indices))
        test_indices = list(filter(lambda i: i % 2 != 0, test_indices))

        print("# Found {0} files".format(len(files)))
        print("# Copying of files...")

        for i in train_indices:
            print(i)
            copy_file(train_dir, files[i], label_mask)

        for i in valid_indices:
            copy_file(valid_dir, files[i], label_mask)

        for i in test_indices:
            copy_file(test_dir, files[i], label_mask)

        # with open("y_train.csv".format(_TRAIN_FOLDER), "w") as tr_f, open("y_test.csv".format(_TEST_FOLDER), "w") as t_f:
        #     for i in range(len(files)):
        #         print("{0}-th file is moving".format(i))
        #         old_filepath = os.path.join(_DATASET_FOLDER, files[i])
        #         if i % 4 == 0:
        #             new_filepath = os.path.join(_TEST_FOLDER, files[i])
        #             shutil.copy2(old_filepath, new_filepath)
        #             t_f.write(', '.join([files[i], files[i].split("_")[0]]))
        #             t_f.write('\n')
        #         else:
        #             new_filepath = os.path.join(_TRAIN_FOLDER, files[i])
        #             shutil.copy2(old_filepath, new_filepath)
        #             tr_f.write(', '.join([files[i], files[i].split("_")[0]]))
        #             tr_f.write('\n')

        print("# Creation of dataset is success")
    except Exception as err:
        logging.error("Error in creation of dataset: {0}".format(err))

def copy_file(base_path, filepath, label_mask):
    label_text = filepath.split("_")[label_mask]
    label_dir = os.path.join(base_path, label_text)
    if not os.path.exists(label_dir):
        os.mkdir(label_dir)

    src = os.path.join(_DATASET_DIR, filepath)
    dst = os.path.join(label_dir, filepath)
    shutil.copyfile(src, dst)

if __name__ == '__main__':
    welcome()
    args_num = len(sys.argv)
    if args_num >= 3 and args_num <= 4:
        dataset_title = sys.argv[1]
        _DATASET_DIR = sys.argv[2]
        valid_dir = True
        if args_num == 4:
            valid_dir = False

        if (dataset_title == 'utkface'):
            utkface_create_data(valid_dir=valid_dir)
    else:
        Exception('Usage: python dataset_creation_util.py' +
                  'utkface dataset_folder_path --no-valid-dir')


# -*- coding: utf-8 -*-
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time
user_agent = (
        "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) " +
        "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.57 Safari/537.36"
)

def run():
    option = webdriver.ChromeOptions()
    option.add_argument("--start-maximized")
    option.add_argument('user-agent=%s' % user_agent)
    # option.add_argument('--headless')
    driver = webdriver.Chrome(chrome_options=option)

    with open('keywords.txt', encoding='utf-8', mode='r') as f:
        keywords = f.readlines()
    f.close()
    copy_keywords = [x for x in keywords]
    # 枚举实时调用迭代对象,仍是按索引响应更改,要复制一个出来
    for i, keyword in enumerate(copy_keywords):
        time.sleep(1)
        driver.get(
            'https://www.baidu.com/s?wd={}&rsv_spt=1&rsv_iqid=0xe6f606930001524e&issp=1&f=3&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_enter=0&oq=%25E5%2585%2583%25E5%25B0%258A&rsv_t=ce4478l3gG9Hm0LrQ0p%2F%2FgGyyjfpRezBg4K5wYrtCd3JQHDgg79qOr8LU4I3KG9EDbXi&rsv_pq=aec5c8f70000f057&prefixsug=%25E5%2585%2583%25E5%25B0%258A&rsp=0'.format(
                keyword.strip()))
        # 等待到底部帮助加载完成
        WebDriverWait(driver, 10).until(lambda x: x.find_element_by_xpath('//div[@class="foot-inner"]'))
        try:
            WebDriverWait(driver, 2).until(lambda x: x.find_element_by_xpath('//div[@class="tip_head"]'))
            keywords.remove(keyword)
            with open('keywords.txt', encoding='utf-8', mode='w') as f_new:
                f_new.writelines(keywords)
            f_new.close()
            print('没有找到与"' + keyword.strip() + '"相关的网页')
            continue
        except Exception :
            pass

        try:
            count = str(driver.find_element_by_xpath(
                '//div[@class="c-span21 c-span-last"]//p//b').text)
            count = count.lstrip('找到相关结果数约').rstrip('个').replace(',', '')
            print(keyword.strip(), ' ', count)
            with open('result.txt', encoding='utf-8', mode='a') as f_out:
                f_out.write(keyword.strip() + ' ' + count + '\n')
            f_out.close()
            keywords.remove(keyword)
            with open('keywords.txt', encoding='utf-8', mode='w') as f_new:
                f_new.writelines(keywords)
            continue
        except Exception :
            pass
        try:
            count = str(driver.find_element_by_xpath(
                '//div[@class="op_site_domain_right c-span24 c-span-last"]//p//span//b').text)
            count = count.replace(',', '')
            print(keyword.strip(), count)
            with open('result.txt', encoding='utf-8', mode='a') as f_out:
                f_out.write(keyword.strip() + ' ' + count + '\n')
            f_out.close()
            keywords.remove(keyword)
            with open('keywords.txt', encoding='utf-8', mode='w') as f_new:
                f_new.writelines(keywords)
            continue
        except Exception :
            pass

if __name__ == '__main__':
    run()


#!/usr/bin/env python

import ConfigParser
import unittest

from server import ComicServer, CBRResource, IMAGE_FILE_EXTENSION_RE

class TestComicParser(unittest.TestCase):
    def setUp(self):
        config = ConfigParser.ConfigParser()
        config.read("comix.conf")
        self.cbr = ComicServer(config.get("basics", "directory"))

    def test_filename_cleaner(self):
        self.assertEqual("Best of the Brave and the Bold",
                         self.cbr._prep_title("Best of the Brave and the Bold (1988)"))

class TestCBRResource(unittest.TestCase):
    def test_file_filter(self):

        names = [
            "superman_-_whatever_happend_to_the_man_of_tomorrow_(alan_moore)\SupermanWHTTMoT-55 Whatever Happened To The Man of Tomorrow.jpg",
            "superman_-_whatever_happend_to_the_man_of_tomorrow_(alan_moore)\Thumbs.db",
            "superman_-_whatever_happend_to_the_man_of_tomorrow_(alan_moore)\\"
        ]
        results = [f for f in names if IMAGE_FILE_EXTENSION_RE.search(f)]
        self.assertEqual(1, len(results))
        self.assertEqual(names[0], results[0])

if __name__ == '__main__':
    unittest.main()


# bot.py
import os
import sys

import requests
# import tempfile

import re

import discord
from dotenv import load_dotenv

import openai
load_dotenv()

# Based on https://realpython.com/how-to-make-a-discord-bot-python/

DISCORD_MSG_LIMIT = 2000
OPENAI_HIST_LIMIT = 30

OPENAI_ERRORS = (openai.error.Timeout, openai.error.APIError, openai.error.APIConnectionError, openai.error.InvalidRequestError, openai.error.RateLimitError)

BOT_NAME = '@SmarterAdult'
CHAT_CHANNEL = 'bot-chat'

TOKEN = os.getenv('DISCORD_TOKEN')
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY')
openai.api_key = OPENAI_API_KEY

def help_text():
    return f"""
How to use this bot

Post in the channel #{CHAT_CHANNEL}. The bot will respond to each message.

There are some special commands as well:
!reprompt - gives the bot a new prompt to follow. Example: `!reprompt You are a 1930s radio announcer who always speaks in hyperbole and loves alliteration.`
!reroll - has the bot come up with a new answer to the last prompt.
!restart - resets the chat history for this server.
!help (!h) - shows this message
"""

token_dict = {}

def engine_for_server(server_id):
    global token_dict
    if server_id in token_dict and token_dict[server_id] > 0:
        return 'gpt-4-0613'
    else:
        return 'gpt-3.5-turbo-0613'

def token_pool_for_server(server_id):
    global token_dict
    if server_id in token_dict:
        return token_dict[server_id]
    else:
        return 0

def tokens_to_dollars(tokens):
    dollar_amount = tokens * 0.045 / 1000
    return format(dollar_amount, '.2f')

def dollars_to_tokens(dollars):
    return int(dollars / 0.045 * 1000)

def usage(server_id):
    global token_dict
    token_pool = token_pool_for_server(server_id)
    return f"""
Current engine: `{engine_for_server(server_id)}`
Remaining GPT-4 tokens: {token_pool} (about ${tokens_to_dollars(token_pool)})

This is a message from me, SmarterAdult - no GPT usage required.
"""

def paid(server_id, dollars):
    global token_dict
    if server_id not in token_dict:
        token_dict[server_id] = 0
    token_add = dollars_to_tokens(dollars)
    token_dict[server_id] += token_add
    return f"Great! ${dollars} was added to the tip jar.\n\n" + usage(server_id)

intents = discord.Intents.default()
intents.reactions = True
intents.message_content = True

client = discord.Client(intents=intents)

message_hist_dict = {}
prompt_dict = {}

async def flush_messages(response_text, channel):
    while response_text:
        await channel.send(response_text[:DISCORD_MSG_LIMIT])
        response_text = response_text[DISCORD_MSG_LIMIT:]

async def get_api_response(message, message_hist, first_prompt=None):
    messages = message_hist
    if first_prompt:
        messages = [{"role": "system", "content": first_prompt}] + messages
    response_text = None
    while response_text is None:
        try:
            server_id = message.channel.id
            engine = engine_for_server(server_id)
            completion = openai.ChatCompletion.create(
                model=engine,
                messages=messages
            )
            if engine == 'gpt-4-0613':
                token_usage = completion.usage.total_tokens
                token_dict[server_id] = max(0, token_dict[server_id] - token_usage)
                if token_dict[server_id] == 0:
                    await message.reply("You're now out of GPT-4 tokens. Switching to GPT-3.5.")
            print(completion)
            response_text = completion.choices[0].message.content
        except openai.error.InvalidRequestError as e:
            if message_hist: message_hist.pop(0)
            messages = message_hist
    return response_text

def is_reprompt(message_text):
    return message_text.strip().startswith("!reprompt") or message_text.strip().startswith("!gaslight")

@client.event
async def on_ready():
    print("Ready")

@client.event
async def on_message(message):
    global message_hist_dict
    global prompt_dict
    global token_dict

    # Only interact with messages in the ChatGPT channel
    if message.channel.name != CHAT_CHANNEL:
        return

    # Don't respond to self
    if message.author == client.user:
        return

    if not message.clean_content:
        return

    if message.channel.id not in message_hist_dict:
        message_hist_dict[message.channel.id] = []
    message_hist = message_hist_dict[message.channel.id]

    if message.channel.id not in prompt_dict:
        prompt_dict[message.channel.id] = None

    if message.channel.id not in token_dict:
        token_dict[message.channel.id] = 0

    if message.clean_content.strip() == '!help':
        await message.reply(help_text())
        return

    if message.clean_content.strip() == "!restart":
        message_hist_dict[message.channel.id] = []
        prompt_dict[message.channel.id] = None
        await message.reply("Chat history cleared")
        return

    if message.clean_content.strip() == "!hist":
        print(message_hist)
        return

    if message.clean_content.strip() == "!ping":
        await message.reply("Pong")
        return

    if message.clean_content.strip() == '!usage':
        await message.reply(usage(message.channel.id))
        return

    if message.clean_content.strip().startswith('!paid'):
        tokens = message.clean_content.strip().split(' ')
        if len(tokens) != 2 or not tokens[1].replace('$', '').isdigit():
            await message.reply("Please use the format `!paid $10` or `!paid 10` - whole dollars only!")
            return
        dollar_amount = int(tokens[1].replace('$', ''))
        await message.reply(paid(message.channel.id, dollar_amount))
        return

    if message.clean_content.strip() == "!reroll":
        message_hist.pop()
    else:
        input_text = message.clean_content
        message_author = 'user'
        if is_reprompt(input_text):
            message_author = 'system'
            input_text = input_text.replace('!reprompt', '').replace('!gaslight', '').strip()
            print(f"New prompt: <{input_text}>")
            prompt_dict[message.channel.id] = input_text
            await message.add_reaction('🫡')
        message_hist.append({"role": message_author, "content": input_text})
        if len(message_hist) > OPENAI_HIST_LIMIT : message_hist.pop(0)

        print(f"Input: <{input_text}>")
    await message.add_reaction('⏳')

    try:
        response_text = await get_api_response(message, message_hist, prompt_dict[message.channel.id])
        print(f"Output: <{response_text}>")
        message_hist.append({"role": "system", "content": response_text})
        await flush_messages(response_text, message.channel)
    except OPENAI_ERRORS as e:
        print(e)
        await message.reply(f"Oops, there was an OpenAI error: `{type(e).__name__}: {e}`")
    finally:
        await message.remove_reaction('⏳', client.user)
    return

client.run(TOKEN)


#! /usr/bin/python3
#
# white_yellow_cyan.py -- alternate three solid frame colors
# https://pillow.readthedocs.io/en/latest/releasenotes/3.4.0.html#append-images-to-gif
# https://github.com/python-pillow/Pillow/blob/master/src/PIL/GifImagePlugin.py

import os
from PIL import Image

w = 224*2
h = 224*2

def putdot(data, x, y, color=(255,255,255), size=(2,2)):
  """ Paint a rectangular group of pixels.
      Out of bounds operations are harmlessly ignored
  """
  for j in range(int(size[1])):
    for i in range(int(size[0])):
      try:
        data[int(x+i), int(y+j)] = color
      except:
        pass

frames = []

cols=[(255,255,255), (255,255,0), (0,255,255), (255,0,255)]

for i in range(1):
  for col in cols:
    im = Image.new("RGB", (w, h))
    pix = im.load()
    putdot(pix, 0, 0, color=col, size=(w,h))
    # BUG-Alert: The save() method computes the palette for all images from the first image. Need to show all colors there.
    for p in range(len(cols)):
      putdot(pix, w*3/4+2*p, h/2+2, color=cols[p])
    frames.append(im)

frames[0].save('gif/white_yellow_cyan_30fps.gif', format='GIF', append_images=frames[1:], save_all=True, duration=int(1000./30), loop=1)
frames[0].save('gif/white_yellow_cyan_25fps.gif', format='GIF', append_images=frames[1:], save_all=True, duration=int(1000./25), loop=1)
frames[0].save('gif/white_yellow_cyan_15fps.gif', format='GIF', append_images=frames[1:], save_all=True, duration=int(1000./15), loop=1)
frames[0].save('gif/white_yellow_cyan_10fps.gif', format='GIF', append_images=frames[1:], save_all=True, duration=int(1000./10), loop=1)
frames[0].save('gif/white_yellow_cyan_5fps.gif',  format='GIF', append_images=frames[1:], save_all=True, duration=int(1000./5),  loop=1)
frames[0].save('gif/white_yellow_cyan_2fps.gif',  format='GIF', append_images=frames[1:], save_all=True, duration=int(1000./2),  loop=1)


#!/usr/bin/env python3
#Author: Rohit Singh
#Date: 04/01/2019
#convert a .dat file to .csv, .vtk, .vtp and .pvd file for planar view of crack
#use this planar data in crackGen3D.py to calculate 3D view of crack based on crack opening value

import re
import os, sys
import vtk
import os
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
from collections import  defaultdict
from collections import OrderedDict

#creates required folder structure to save the files
def createfolder():
    try:
        if os.path.exists("./Crack Data"):
            return
        os.makedirs("./Crack Data")
        os.makedirs("./Crack Data/Plane")
        os.makedirs("./Crack Data/Plane/VTK")
        os.makedirs("./Crack Data/Plane/VTP")

        os.makedirs("./Crack Data/3D_UP")
        os.makedirs("./Crack Data/3D_UP/VTK")
        os.makedirs("./Crack Data/3D_UP/VTP")

        os.makedirs("./Crack Data/3D_DOWN")
        os.makedirs("./Crack Data/3D_DOWN/VTK")
        os.makedirs("./Crack Data/3D_DOWN/VTP")
    except:
        print("Could not create directory for storing output files")

#reads the data from the .dat input file.
#read is dependent on the data formatting in the input file so refer to the sample input file
def readData(file_path):
    with open(file_path, "r") as file:
        data=file.read()
    data_row= data.split("\n")
    data_formatted=""
    for row in data_row:
        row=row.strip(" ")
        row=re.sub("        ", ",", row)
        row = re.sub("    ", ",", row)
        data_formatted+=row+"\n"
    return data_formatted

#saves the input data in .csv format
def convertToCSV(data_formatted, no_of_stages):
    with open('Crack Data\crack_data.csv', mode='w') as file:
        file.write(data_formatted)

#parses thorugh the input data and generates the .vtk format for the input data
def convertToVTK(data_formatted, colormap, stage_to_extract):
    data_list=data_formatted.split("\n")
    header="# vtk DataFile Version 2.0 \n" \
            "Crack Data \n" \
            "ASCII \n" \
            "DATASET POLYDATA \n" \
            "POINTS"

    dataVTK = ""
    dataVTK+=header
    count=0
    stage=0
    skip=0
    no_points=0
    no_polygons=0
    no_triangles=0

    adjacent_faces=defaultdict(set)

    #specifying vertex positions-(x,y,z)
    for row in data_list:
        if row[:4] == "ZONE":
            stage += 1
        if(stage <stage_to_extract):
            skip+=1
        if(stage==stage_to_extract):
            if row[:4]=="ZONE":
                i=row.find("N=")
                no_points=int(row[i+2:i+row[i:].find(",")])+1
                j=row.find("E=")
                b=row[j:].find("\n")
                no_polygons = int(row[j + 2:])
                dataVTK+=" "+str(no_points)+" float \n" + \
                    "0.0000,0.0000,0.0000 \n"
                count=1
            else:
                if(count<no_points):
                    dataVTK+=row[:len(row)-row[::-1] .find(",")-1]+" \n"
                    count+=1
                else:
                    if(count == no_points):
                        dataVTK+="POLYGONS"
                        no_vertices=row.count(",")
                        temp = row.split(",")
                        if no_vertices==2:
                            no_triangles+=1
                            #create a dictionary with all adjacent vertices for the vertex
                            adjacent_faces[int(temp[0].strip())].add(int(temp[1].strip()))
                            adjacent_faces[int(temp[0].strip())].add(int(temp[2].strip()))
                            adjacent_faces[int(temp[1].strip())].add(int(temp[2].strip()))
                            adjacent_faces[int(temp[1].strip())].add(int(temp[0].strip()))
                            adjacent_faces[int(temp[2].strip())].add(int(temp[0].strip()))
                            adjacent_faces[int(temp[2].strip())].add(int(temp[1].strip()))
                        else:
                            adjacent_faces[int(temp[0].strip())].add(int(temp[3].strip()))
                            adjacent_faces[int(temp[0].strip())].add(int(temp[1].strip()))
                            adjacent_faces[int(temp[1].strip())].add(int(temp[0].strip()))
                            adjacent_faces[int(temp[1].strip())].add(int(temp[2].strip()))
                            adjacent_faces[int(temp[2].strip())].add(int(temp[1].strip()))
                            adjacent_faces[int(temp[2].strip())].add(int(temp[3].strip()))
                            adjacent_faces[int(temp[3].strip())].add(int(temp[2].strip()))
                            adjacent_faces[int(temp[3].strip())].add(int(temp[0].strip()))
                        dataVTK+=str(no_vertices+1)+","+row+" \n"
                        count+=1
                    else:
                        no_vertices = row.count(",")
                        temp = row.split(",")
                        if no_vertices==2:
                            no_triangles+=1
                            adjacent_faces[int(temp[0].strip())].add(int(temp[1].strip()))
                            adjacent_faces[int(temp[0].strip())].add(int(temp[2].strip()))
                            adjacent_faces[int(temp[1].strip())].add(int(temp[2].strip()))
                            adjacent_faces[int(temp[1].strip())].add(int(temp[0].strip()))
                            adjacent_faces[int(temp[2].strip())].add(int(temp[0].strip()))
                            adjacent_faces[int(temp[2].strip())].add(int(temp[1].strip()))
                        else:
                            adjacent_faces[int(temp[0].strip())].add(int(temp[3].strip()))
                            adjacent_faces[int(temp[0].strip())].add(int(temp[1].strip()))
                            adjacent_faces[int(temp[1].strip())].add(int(temp[0].strip()))
                            adjacent_faces[int(temp[1].strip())].add(int(temp[2].strip()))
                            adjacent_faces[int(temp[2].strip())].add(int(temp[1].strip()))
                            adjacent_faces[int(temp[2].strip())].add(int(temp[3].strip()))
                            adjacent_faces[int(temp[3].strip())].add(int(temp[2].strip()))
                            adjacent_faces[int(temp[3].strip())].add(int(temp[0].strip()))
                        dataVTK += str(no_vertices+1)+","+ row+" \n"
                        count += 1
            if count==no_points+no_polygons:
                break
    count=0

    #specifying vertex ordering for polygons
    index = dataVTK.find("POLYGONS")
    dataVTK=dataVTK[:(index+8)]+" "+str(no_polygons)+" "+str(no_polygons*5-no_triangles)+"\n" + dataVTK[index+8:]
    dataAtt ="POINT_DATA "+str(no_points)+" \n" \
            "SCALARS point_scalars float 1 \n" \
             "LOOKUP_TABLE my_table"+"\n"
    dataVTK += dataAtt
    dataVTK = re.sub(",", " ", dataVTK)
    scalar_val=[0.0]
    max_val=0

    #specifying scalar values at vertices
    for row in data_list:
        if(count==0):
            dataVTK +="0"+"\n"
            count+=1
        elif(count>skip and count-skip<no_points):
            n=len(row)
            val=float(row[n-row[::-1].find(",")+1:])
            scalar_val.append(val)
            if(val>max_val):
                max_val=val
            dataVTK+=str(val)+ " \n"
            count += 1
        else:
            count+=1

    #perform linear interpolation to determine scalar value at a vertex
    interpolated_scalars=set()
    last_color = 0
    for i in range(0, len(scalar_val)):
        neighbors=adjacent_faces[i]
        sum_scalars=scalar_val[i]
        count=1
        if(len(neighbors)!=0):
            for j in neighbors:
                if(j!=i):
                    sum_scalars+=scalar_val[j]
                    count+=1
            last_color=sum_scalars/(count)
        else:
            pass
        interpolated_scalars.add(last_color)

    #specifying color map for vertices
    dataVTK+="LOOKUP_TABLE my_table"+" "+str(len(interpolated_scalars))+"\n"

    interpolated_scalars=sorted(list(interpolated_scalars))
    max_val=max(interpolated_scalars)
    min_val=min(interpolated_scalars)
    for i in interpolated_scalars:
        color_val=(i-min_val)/(max_val-min_val)
        color=colormap(color_val)
        rgb=str(color[0])+" "+str(color[1])+" "+str(color[2])+" 1.0 \n"
        dataVTK+=rgb

    #store the formatted data in .vtk and .vtp format
    fileno=""
    if(stage_to_extract<10):
        fileno="0"+str(stage_to_extract)
    else:
        fileno=str(stage_to_extract)
    with open('Crack Data\Plane\VTK\crack_data_vtk'+ \
              fileno+'.vtk', mode='w') as file:
        file.write(dataVTK)

    vtkf='Crack Data\Plane\VTK\crack_data_vtk'+fileno+'.vtk'
    vtpf='Crack Data\Plane\VTP\crack_data_vtp'+fileno+'.vtp'
    vtk2vtp(vtkf, vtpf, binary=False)

#source: https://gist.github.com/thomasballinger/1281457
def vtk2vtp(invtkfile, outvtpfile, binary=False):
    """What it says on the label"""
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(invtkfile)

    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(outvtpfile)
    if binary:
        writer.SetFileTypeToBinary()
    writer.SetInputConnection(reader.GetOutputPort())
    writer.Update()

#link all.vtp files to produce a time varying data set
def createPVDFile(no_of_stages):
    header="<?xml version=\"1.0\"?> \n" \
                "<VTKFile type=\"Collection\" version=\"0.1\">\n" \
                    "  <Collection>\n"

    tail="  </Collection>\n" \
            "</VTKFile>\n"

    data=header

    for i in range(1,no_of_stages+1):
        if i<10:
            data += "    <DataSet timestep=\"" + str(i - 1) + "\" file=\"crack_data_vtp0" + str(i) + ".vtp\"/>\n"
        else:
            data += "    <DataSet timestep=\"" + str(i - 1) + "\" file=\"crack_data_vtp" + str(i) + ".vtp\"/>\n"

    data+=tail

    with open('D:\CS 6635 Vis or Data Sceince\Final Project\Crack Data\Plane\VTP\crack_data.pvd', mode='w') as file:
        file.write(data)

#create a cool to warm color map for the input data set based on max. crack opening
def createColorMap(data_formatted, no_of_stages):
    data_list=data_formatted.split("\n")
    scalar_val=[0]
    skip=0
    stage=0
    count=0
    for row in data_list:
        if row[:4] == "ZONE":
            stage += 1
        if(stage <no_of_stages):
            skip+=1
        if stage==no_of_stages:
            if row[:4] == "ZONE":
                i = row.find("N=")
                no_points = int(row[i + 2:i + row[i:].find(",")]) + 1
                count=1
            else:
                if (count < no_points):
                    n = len(row)
                    val = float(row[n - row[::-1].find(",") + 1:])
                    scalar_val.append(val)
                    count+=1
    max_val=max(scalar_val)
    min_val=min(scalar_val)
    range_val= len(set(scalar_val))
    for i in range(0, range_val):
        scalar_val[i]=(scalar_val[i]-min_val)/(max_val-min_val)
    color=cm.get_cmap('coolwarm', range_val)
    newcolors=color(np.linspace(0, 1, range_val))
    newcmp = ListedColormap(newcolors, name='CoolWarm')
    '''
    fg, ax = plt.subplots()
    psm = ax.pcolormesh(np.array([sorted(scalar_val)]), cmap=newcmp, rasterized=True, vmin=0, vmax=1)
    fg.colorbar(psm, ax=ax)
    plt.show()
    '''
    return newcmp

def main():
    no_of_stages = 98 #total number of stages of crack opening
    createfolder() #create folder structure
    data_formatted=readData("sp2_lc2_test_crack2.dat") #input file
    colormap=createColorMap(data_formatted,no_of_stages) #generate a colormap
    convertToCSV(data_formatted, no_of_stages) #convert to csv(optional)
    for i in range(1,no_of_stages+1):
        convertToVTK(data_formatted, colormap, i) #generate a .vtk and .vtp file for each stage
    createPVDFile(no_of_stages) #create a .pvd file linking all stages

if __name__ == '__main__':
    main()


from collections import defaultdict

import json
import os
import numpy as np
import torch
from torch.nn import functional as F
from torch.nn.utils.rnn import pad_sequence
from tqdm import tqdm
from clip.simple_tokenizer import SimpleTokenizer
from scipy.optimize import linear_sum_assignment

def clip_fp_alignment(batch, maxLen):
    new_fp_ali_list = []
    new_segment_num_list = []
    for ali in batch["fp_alignment"]:
        new_ali = ali[ali.nonzero()].squeeze(-1).clip(max=maxLen).unique()
        new_fp_ali_list.append(new_ali)
        new_segment_num_list.append(len(new_ali))

    new_fp_alignment = pad_sequence(new_fp_ali_list, batch_first=True).to(
        batch["fp_alignment"].device
    )
    new_segment_num = torch.LongTensor(new_segment_num_list).to(
        batch["fp_alignment"].device
    )
    batch.update({"fp_alignment": new_fp_alignment, "segment_num": new_segment_num})

def fix_random_crop_alginment(crop_idx, fp_alignment, segment_num, maxLen):
    if crop_idx is None:
        return fp_alignment, segment_num
    else:
        crop_idx = round(crop_idx / 50)
        maxFpLen = round(maxLen / 320)

    modified_ali = list(
        filter(
            lambda x: x - 1 >= crop_idx and x - 1 < crop_idx + maxFpLen, fp_alignment
        )
    )
    modified_ali.append(crop_idx + maxFpLen)
    modified_ali = torch.LongTensor(modified_ali).to(fp_alignment.device) - crop_idx
    modified_ali = modified_ali[modified_ali.nonzero()].squeeze(-1).unique()

    return modified_ali, len(modified_ali)

def random_crop_max_length(
    wav: torch.Tensor, max_len: int, orig_len: int = 1000000000
) -> torch.Tensor:
    """Randomly crop an audio feature sequence into max_len.

    Args:
        audio (torch.Tensor): Audio features (T, *)
        max_len (int): Maximum length.
        orig_len (int, optional): Original length of audio. Defaults to 1000000000.

    Returns:
        torch.Tensor: Cropped audio features.
    """
    audio_len = min(len(wav), orig_len)
    if audio_len <= max_len or max_len < 0:
        return wav[:audio_len]

    offset = np.random.randint(audio_len - max_len)
    return wav[offset : offset + max_len]

def get_keypadding_mask(max_length: int, data_lens: torch.Tensor) -> torch.Tensor:
    bsz = data_lens.shape[0]
    key_padding_mask = torch.ones([bsz, max_length])
    for mask, len in zip(key_padding_mask, data_lens):
        mask[:len] = 0.0
    key_padding_mask = key_padding_mask.type_as(data_lens).bool()

    return key_padding_mask

def compute_dynamic_keyword_neighbors(
    model,
    K: int,
    retreival_type: str,
    outputs: dict,
    tokenEmbeddings: torch.Tensor,
    keyword_embeddings_list: list,
    gold_texts: list,
    feat_len_list: list,
    emb_pinv=None,
):
    hit_rate_list = []
    all_retok_outputs = []
    batch_size = model.config.data.dev_batch_size
    for b_idx, i in zip(
        range(len(outputs)),
        range(0, len(gold_texts), batch_size),
    ):
        _gold_texts = gold_texts[i : i + batch_size]
        _feat_len_list = feat_len_list[i : i + batch_size]
        gold_subword_toks_set = [
            set(model.clip.tokenizer.encode(_text)) for _text in _gold_texts
        ]

        b_instance_idx = 0
        for keyword_embeddings in keyword_embeddings_list[b_idx]:
            _bsz, _max_feat_len = (
                keyword_embeddings.shape[0],
                keyword_embeddings.shape[1],
            )

            if retreival_type == "pseudo_inverse":
                assert (
                    emb_pinv is not None
                ), f"You are using pseudo-inverse to retreive the keywords, please provide pseudo-inverse"
                kw_retrevial_score = (
                    emb_pinv.float()
                    @ keyword_embeddings.view(-1, model.subword_embd_dim)
                    .float()
                    .reshape(-1, model.subword_embd_dim)
                    .permute(1, 0)
                ).permute(1, 0)
            else:
                kw_retrevial_score = F.cosine_similarity(
                    keyword_embeddings.view(-1, model.subword_embd_dim, 1),
                    tokenEmbeddings.transpose(0, 1).unsqueeze(0),
                    dim=1,
                )
            _k_values, _k_indices = torch.topk(kw_retrevial_score, K)

            assert _k_values.shape == (
                _bsz * _max_feat_len,
                K,
            ), _k_values.shape
            _k_indices = _k_indices.view(_bsz, _max_feat_len, K)
            _k_values = _k_values.view(_bsz, _max_feat_len, K)

            for x in range(_bsz):
                _hit_rate = 0
                hit_kw = []
                tmp_outputs = {}
                _feat_len = _feat_len_list[b_instance_idx + x]
                _gold_subword_toks_set = gold_subword_toks_set[b_instance_idx + x]
                for _keyword_i in range(_feat_len):
                    tmp_outputs["keyword_{}".format(_keyword_i)] = []

                    # check if nearest K subword appears in gold text
                    top_k_toks = set(
                        [
                            model.clip.reducedl2Original[_ind.item()]
                            if model.clip.selected_text_emb_ids is not None
                            else _ind.item()
                            for _ind in _k_indices[x, _keyword_i]
                        ]
                    )

                    if bool(top_k_toks & _gold_subword_toks_set):
                        _hit_rate += 1 / _feat_len
                        hit_token_id = int(list(top_k_toks & _gold_subword_toks_set)[0])
                        hit_token = model.clip.tokenizer.decoder[
                            hit_token_id
                            if model.clip.selected_text_emb_ids is not None
                            else model.clip.reducedl2Original[hit_token_id]
                        ]
                        hit_kw.append(hit_token)

                    for _ind, _dist in zip(
                        _k_indices[x, _keyword_i], _k_values[x, _keyword_i]
                    ):
                        tmp_outputs["keyword_{}".format(_keyword_i)].append(
                            [
                                model.clip.tokenizer.decoder[
                                    model.clip.reducedl2Original[_ind.item()]
                                    if model.clip.selected_text_emb_ids is not None
                                    else _ind.item()
                                ],
                                _dist.item(),
                            ]
                        )

                hit_rate_list.append(_hit_rate)

                all_retok_outputs.append(
                    {
                        "gold": _gold_texts[b_instance_idx + x],
                        "neighbors": tmp_outputs,
                        "hit_kw": hit_kw,
                        "kw_hit_rate": _hit_rate,
                    }
                )
            b_instance_idx += _bsz

    return hit_rate_list, all_retok_outputs

def compute_fixed_keyword_neighbors(
    model,
    K: int,
    retreival_type: str,
    tokenEmbeddings: torch.Tensor,
    all_keyword_embeddings: torch.Tensor,
    gold_texts: list,
    emb_pinv=None,
):
    hit_rate_list = [0] * model.keyword_num
    kw_top_ret = [[] for _ in range(model.keyword_num)]
    all_retok_outputs = []
    batch_size = model.config.data.dev_batch_size

    for i in tqdm(range(0, len(gold_texts) + batch_size, batch_size)):
        _gold_texts = gold_texts[i : i + batch_size]
        _bsz = len(_gold_texts)
        if len(_gold_texts) == 0:
            break

        gold_subword_toks_set = [
            set(model.clip.tokenizer.encode(_text)) for _text in _gold_texts
        ]

        if retreival_type == "pseudo_inverse":
            assert (
                emb_pinv is not None
            ), f"You are using pseudo-inverse to retreive the keywords, please provide pseudo-inverse"
            kw_retrevial_score = (
                emb_pinv.float()
                @ all_keyword_embeddings[i : i + _bsz]
                .view(-1, model.subword_embd_dim)
                .float()
                .reshape(-1, model.subword_embd_dim)
                .permute(1, 0)
            ).permute(1, 0)
        else:
            kw_retrevial_score = F.cosine_similarity(
                all_keyword_embeddings[i : i + _bsz].view(
                    -1, model.subword_embd_dim, 1
                ),
                tokenEmbeddings.transpose(0, 1).unsqueeze(0),
                dim=1,
            )
        _k_values, _k_indices = torch.topk(kw_retrevial_score, K)

        assert _k_values.shape == (
            _bsz * model.keyword_num,
            K,
        ), _k_values.shape
        _k_indices = _k_indices.view(_bsz, model.keyword_num, K)
        _k_values = _k_values.view(_bsz, model.keyword_num, K)

        for x in range(_bsz):
            tmp_outputs = {}
            for _keyword_i in range(model.keyword_num):
                tmp_outputs["keyword_{}".format(_keyword_i)] = []

                # check if nearest K subword appears in gold text
                top_k_toks = set(
                    [
                        model.clip.reducedl2Original[_ind.item()]
                        if model.clip.selected_text_emb_ids is not None
                        else _ind.item()
                        for _ind in _k_indices[x, _keyword_i]
                    ]
                )
                if bool(top_k_toks & gold_subword_toks_set[x]):
                    hit_rate_list[_keyword_i] += 1
                    hit_token_id = int(list(top_k_toks & gold_subword_toks_set[x])[0])
                    kw_top_ret[_keyword_i].append(hit_token_id)

                for _ind, _dist in zip(
                    _k_indices[x, _keyword_i], _k_values[x, _keyword_i]
                ):
                    tmp_outputs["keyword_{}".format(_keyword_i)].append(
                        [
                            model.clip.tokenizer.decoder[
                                model.clip.reducedl2Original[_ind.item()]
                                if model.clip.selected_text_emb_ids is not None
                                else _ind.item()
                            ],
                            _dist.item(),
                        ]
                    )

            all_retok_outputs.append(
                {
                    "gold": gold_texts[x],
                    "neighbors": tmp_outputs,
                }
            )

    return hit_rate_list, kw_top_ret, all_retok_outputs

def compute_cos_alignments(model, all_retok_outputs, file_path):
    ENCODER, DECODER = SimpleTokenizer().encoder, SimpleTokenizer().decoder
    scores = []
    output = []

    for tokenize_ouput in tqdm(all_retok_outputs):
        gold_toks = SimpleTokenizer().encode(text=tokenize_ouput["gold"])
        gold_toks = [ model.clip.original2Reduced[tok] for tok in gold_toks[1:gold_toks.index(49407)] ]
        gold_toks = torch.LongTensor(gold_toks).to(model.device)

        all_pred_toks = []
        for neighbor in tokenize_ouput["neighbors"].values():
            all_pred_toks += [ ENCODER[kw[0]] for kw in neighbor ]
        all_pred_toks = [ model.clip.original2Reduced[tok] for tok in all_pred_toks ]
        all_pred_toks = torch.LongTensor(list(set(all_pred_toks))).to(model.device)

        gold_embd, pred_embd = model.clip.model.token_embedding(gold_toks), model.clip.model.token_embedding(all_pred_toks)
        pairwise_cos_similarity = F.normalize(gold_embd, dim=-1) @ F.normalize(pred_embd, dim=-1).T
        pairwise_cos_similarity = pairwise_cos_similarity.cpu().detach().numpy()

        row_ind, col_ind = linear_sum_assignment(pairwise_cos_similarity, maximize=True)
        assign_best_score_idx = np.argsort(pairwise_cos_similarity[row_ind, col_ind], axis=0)[::-1][:model.keyword_num]
        topk_gold_toks = [ model.clip.reducedl2Original[tok.item()] for tok in gold_toks[row_ind[assign_best_score_idx]] ]
        topk_pred_toks = [ model.clip.reducedl2Original[tok.item()] for tok in all_pred_toks[col_ind[assign_best_score_idx]] ]
        topk_gold_text = [ DECODER[tok] for tok in topk_gold_toks ]
        topk_pred_text = [ DECODER[tok] for tok in topk_pred_toks ]
        topk_scores = pairwise_cos_similarity[row_ind, col_ind][assign_best_score_idx]
        scores.append(topk_scores.mean(0))

        output.append(
            {
                "gold": tokenize_ouput["gold"],
                f"top{model.keyword_num}_gold_subwords": topk_gold_text,
                f"top{model.keyword_num}_pred_subwords": topk_pred_text,
                f"top{model.keyword_num}_scores": topk_scores.tolist(),
            }
        )

    with open(file_path, "w") as f:
        json.dump(output, f, indent=4)

    return scores


from flask import Flask, render_template, redirect
from flask_pymongo import PyMongo
import mission_to_mars

# initialize flask
app = Flask(__name__)

# initalize mongo connection with pymongo
mongo = PyMongo(app, uri='mongodb://localhost:27017/mars')

@app.route("/")
def home():
	# grab data from mongo database
	scraped_data = mongo.db.collection.find_one()

	# return template and data
	return render_template("index.html", scraped_data = scraped_data)

@app.route("/scrape")
def scrape_information():
	# run scrape function
	mars_data = mission_to_mars.scrape()

	# update Mongo database
	mongo.db.collection.update({}, mars_data, upsert=True)

	# return redirect to home page
	return redirect("/")

if __name__ == "__main__":
	app.run(debug=True)


import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
import torch
import numpy as np

from code.config import config

class ViralDataset(Dataset):
    def __init__(self, L, stride, max_len, min_len=0):
        super().__init__()
        data = np.load('data/viral.npz',allow_pickle=True)
        seqs = data['seq']
        lens = data['len']
        ids = data['id']
        self.seqs = seqs[(lens>=min_len)&(lens<max_len)]
        self.ids = ids[(lens>=min_len)&(lens<max_len)]
        self.lens = lens[(lens>=min_len)&(lens<max_len)]
        self.L = L
        self.alph = 4
        self.stride = stride
        self.max_len = max_len
        self.sid, self.pos = [], []
        for si,s in enumerate(self.seqs):
            for i in range(L,len(s),stride):
                self.pos.append(i-L)
                self.sid.append(si)

    def get_seq(self, i):
        si, idx = self.sid[i], self.pos[i]
        return self.seqs[si][idx:idx+self.L]

    def __len__(self):
        return len(self.sid)

    def __getitem__(self, i):
        s = self.get_seq(i)
        X = torch.from_numpy(s).type(torch.int64)
        X = F.one_hot(X, num_classes=self.alph)
        X.transpose_(0,1)
        X = X.float()
        return X, (self.sid[i], self.pos[i])

# fully decompresss seqs before training
# needs 20x more memory, but runs ~30% faster
class SeqDataset_decomp(Dataset):
    def __init__(self, seqs, ed, alph, L):
        super().__init__()
        self.ed = torch.tensor(ed, dtype=torch.float64) / L
        self.seqs = torch.tensor(seqs, dtype=torch.int64)
        self.X = F.one_hot(self.seqs, num_classes=alph)
        self.X.transpose_(2,3)
        self.X = self.X.float()

    def __len__(self):
        return len(self.ed)

    def __getitem__(self, i):
        return self.X[i][0], self.X[i][1], self.ed[i]

class SeqDataset(Dataset):
    def __init__(self, seqs, ed, alph, L):
        super().__init__()
        self.ed = torch.tensor(ed, dtype=torch.float64) / L
        self.seqs = seqs
        self.alph = alph

    def __len__(self):
        return len(self.ed)

    def __getitem__(self, i):
        X = torch.from_numpy(self.seqs[i]).type(torch.int64)
        X = F.one_hot(X, num_classes=self.alph)
        X.transpose_(1,2)
        X = X.float()
        return X[0], X[1], self.ed[i]

def load_mmseqs(src, N,L,alph):
    c = config['seqgen_dir']+"/{src}_{phase}_N{N}_L{L}_A{alph}.npz"
    train = np.load(c.format(phase="train",src=src, N=N,L=L,alph=alph))
    val = np.load(c.format(phase="val",src=src, N=N,L=L,alph=alph))
    return train, val

def train_val_datasets(src, N, L, alph):
    train_data, val_data = load_mmseqs(src=src, N=N,L=L,alph=alph)

    train_dataset = SeqDataset(train_data['seqs'], train_data['ed'],alph=alph, L=L)
    val_dataset = SeqDataset(val_data['seqs'],val_data['ed'],alph=alph, L=L)

    return train_dataset, val_dataset


# --*-- coding=utf-8 --*--
import sys
import time
import random
import logging
import importlib
from copy import deepcopy
from multiprocessing import Process

def supervise(target, arguments, process_num, process_check_frequency, log_name, tag):
    """
    arguments: tuple or list of args(ex: (arg1, arg2), [arg1, arg2])
    """
    if not isinstance(arguments, (tuple, list)):
        raise TypeError("Arguments is not a tuple or list")

    if (not isinstance(process_num, int)) or process_num < 0:
        raise TypeError("Process number must be positive integer")

    if process_check_frequency <= 0:
        raise ValueError("Process check frequency be positive")

    arguments = tuple(arguments)
    init_log(log_name)
    logger = logging.getLogger(log_name)
    processes = {}

    for i in range(process_num):
        process_name = 'Process_' + str(i + 1)
        p = Process(target=target, args=arguments)
        p.start()
        processes[process_name] = p
        logger.info('[%s]-[%s]-[%s] has been started' % (log_name, tag, process_name))

    while len(processes) > 0:
        time.sleep(process_check_frequency)

        process_list = deepcopy(list(processes.keys()))
        for process_name in process_list:
            p = processes[process_name]
            if p.exitcode is None:
                if not p.is_alive():
                    p_restart = Process(target=target, args=arguments)
                    p_restart.start()
                    processes[process_name] = p_restart
                    logger.error('[%s]-[%s]-[%s] aborted with exitcode None and has been restarted' % (
                        log_name, tag, process_name))
                else:
                    # logger.info('[%s] - [%s] running ok' % (log_name, process_name))
                    continue  # no error and loop continue

            elif p.exitcode == 0:
                logger.info('[%s]-[%s]-[%s] has been finished' % (log_name, tag, process_name))
                p.join()
                del processes[process_name]

            else:
                p_restart = Process(target=target, args=arguments)
                p_restart.start()
                processes[process_name] = p_restart
                logger.error(
                    '[%s]-[%s]-[%s] aborted with exitcode %s and has been restarted' % (
                        log_name, tag, process_name, p.exitcode))

    logger.info('All [%s] processes have been finished' % tag)

def supervisor(target, arguments=None, process_num=3, process_check_frequency=10, log_name='supervisor', tag='tag'):
    args = [target, arguments, process_num, process_check_frequency, log_name, tag]
    p = Process(target=supervise, args=args)
    p.start()

def test(test_arg):
    begin = time.time()
    while True:
        print(test_arg)
        time.sleep(random.randint(1, 20))
        current = time.time()
        if current - begin > 50:
            sys.exit(0)

def init_log(log_name):
    config = importlib.import_module('config')
    config.init_log(log_name)

if __name__ == '__main__':
    init_log('supervisor_test')
    supervise(test, ["zz"], 2, 10, 'supervisor_test')


import matplotlib.pyplot as plt
import sys
sys.path.append("..")
split_id = 4
if(split_id == 2):
    from Data.Dataset_2 import *
if (split_id == 3):
    from Data.Dataset_3 import *
if(split_id == 4):
    from Data.Dataset_4 import *
if(split_id == 5):
    from Data.Dataset_5 import *
from Data.SSIM import *
import os
from tqdm import tqdm
from CVAE_label_module import *
import csv
import shutil

name_list = ['E11.5', 'E13.5', 'E15.5', 'E18.5', 'P4', 'P14', 'P56']
shape_list = [(2099, 40, 75, 70), (2097, 69, 109, 89), (2088, 65, 132, 94), (2045, 40, 43, 67), (2073, 50, 43, 77), (2071, 50, 40, 68), (2079, 58, 41, 67)]
temp_list = [0, 1, 2, 3, 4, 5, 6]
id_list = [0, 1, 2, 3, 4, 5]
proportion_list = [0.005, 0.05, 0.1, 0.15, 0.2, 0.25]
name_model_list = []

def initialize_random_seed(seed=0):
    np.random.seed(seed)
    torch.random.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    random.seed(seed)
    torch.backends.cudnn.deterministic = True

path_data = './data_pred.csv'
if os.path.exists(path_data):
    # os.remove(path_data)
    f_data =  open(path_data, 'a', encoding='UTF8', newline='')
    writer_data = csv.writer(f_data)
else:
    header = ['name_dataset', 'split_id', 'seed', 'proportion', 'MSE', 'SSIM', 'PSNR']
    f_data =  open(path_data, 'w', encoding='UTF8', newline='')
    writer_data = csv.writer(f_data)
    writer_data.writerow(header)

path_average = './average_pred.csv'
if os.path.exists(path_average):
    # os.remove(path_average)
    f_average =  open(path_average, 'a', encoding='UTF8', newline='')
    writer_average = csv.writer(f_average)
else:
    header = ['name_dataset', 'split_id', 'proportion', 'MSE', 'SSIM', 'PSNR']
    f_average =  open(path_average, 'w', encoding='UTF8', newline='')
    writer_average = csv.writer(f_average)
    writer_average.writerow(header)

for name_id in temp_list:
    MSE_Sum = 0
    SSIM_Sum = 0
    PSNR_Sum = 0
    for id in id_list:
        name = name_list[name_id]
        shape = shape_list[name_id]
        # 模型保存
        path_model = './Checkpoint/'
        model_name = 'model_' + name + '_' + str(split_id) + '_' + str(id)  + '.t7'
        name_dataset = name

        # 模型参数
        num_classes = [shape[0], shape[1]]
        image_H = shape[2]
        image_W = shape[3]
        conv_dims = [32, 64, 128, 256]
        latent_dim = 128
        embedding_dim = 64

        # 训练参数
        if(split_id == 4 or split_id == 5):
            proportion = proportion_list[id]
        else:
            proportion = 0.1
        seed = id
        batch_size = 128
        squeeze = True
        device = 'cuda:2'
        beta = 0
        mode_generate = 1  # 0：同基因临近切片 1：直接随机采样生成
        initialize_random_seed(seed)

        # 定义模型
        model = CVAE_label(image_H, image_W, 1, conv_dims, latent_dim, num_classes, name_id, embedding_dim)

        # 加载训练好的模型参数
        checkpoint = torch.load(path_model + model_name)
        model.load_state_dict(checkpoint['model'])
        epochs_old = checkpoint['epochs']
        model = model.to(device)
        model.eval()

        # 抽取预测图片的频率
        sample_freq = 50

       # 预测测试集图片文件夹
        path_img = './Pictures_pred/' + name_dataset + '/' + str(split_id) + '/' +str(id)
        if not os.path.exists(path_img):
            os.makedirs(path_img)
        else:
            shutil.rmtree(path_img)
            os.makedirs(path_img)

        if not os.path.exists('./CSV_pred/'+ name_dataset+ '/'):
            os.makedirs('./CSV_pred/'+ name_dataset+ '/')
        path_csv = './CSV_pred/' + name_dataset + '/' + str(split_id) + '_' + str(id) + '.csv'
        if os.path.exists(path_csv):
            os.remove(path_csv)
        header = ['gene_id', 'slice_id', 'MSE', 'SSIM', 'PSNR']
        f_csv =  open(path_csv, 'w', encoding='UTF8', newline='')
        writer = csv.writer(f_csv)
        writer.writerow(header)

        # 抽取的切片id
        id_low = int((shape[1] / 2) - 5)
        id_high = int((shape[1] / 2) + 5)
        sample_id = [i for i in range(id_low, id_high, 1)]

        dataset_test = Brain_Dataset(mode='test', transform=None, name_id=name_id, seed=seed, proportion=proportion, squeeze=squeeze)
        test_loader = torch.utils.data.DataLoader(dataset_test, batch_size=batch_size, shuffle=False)

        # 取出训练集数据备用
        feature_train = dataset_test.feature_train
        label_train = dataset_test.label_train
        picture_num = dataset_test.__len__()

        loss_sum = 0
        MSE_sum = 0
        PSNR_sum = 0
        SSIM_sum = 0
        # pixel_max_list = []
        # pixel_min_list = []
        with torch.no_grad():
            for t, (images, labels) in enumerate(tqdm(test_loader)):
                input_size = labels.shape[0]

                images = images.to(device)

                label_slice = labels[:, 1].ravel()

                # 相同基因临近切片
                if (mode_generate == 0):
                    # 找到临近切片
                    label_train = np.array(label_train)
                    index_train = []
                    labels = np.array(labels)
                    labels0 = labels[:, 0]
                    labels1 = labels[:, 1]
                    label_train0 = label_train[:, 0]
                    label_train1 = label_train[:, 1]
                    for i in range(len(labels0)):
                        temp = np.argwhere(label_train0 == labels0[i])
                        min = 1000
                        index_temp = 0
                        for j in temp:
                            min_temp = (labels1[i] - label_train1[j]) ** 2
                            if (min_temp < min):
                                min = min_temp
                                index_temp = j
                        index_train.append(index_temp)
                    index_train = np.array(index_train)

                    feature_seed = feature_train[index_train].reshape(input_size, 1, image_H, image_W)
                    feature_seed = torch.tensor(feature_seed).to(device)

                    labels = torch.tensor(labels)

                    labels = labels.to(device)
                    xhat, mu, log_var = model(feature_seed, one_hot_0, one_hot_1, labels, image_H, image_W, input_size)

                    loss, kl_loss, recon_loss = model.compute_loss(images, xhat, mu, log_var, beta)
                    loss_sum = loss_sum + loss.cpu()*input_size

                # 随机采样生成
                if (mode_generate == 1):
                    labels = labels.to(device)
                    z = torch.randn(input_size, latent_dim).to(device)
                    xhat = model.generate(z, labels)

                sample_list = []
                for i in range(label_slice.shape[0]):
                    if label_slice[i] in sample_id:
                        sample_list.append(i)

                # pixel_max_list.append(torch.max(xhat).item())
                # pixel_min_list.append(torch.min(xhat).item())

                # max = max.ravel().to(device)
                # images = (images.reshape(input_size, -1) * max.reshape(-1, 1)).reshape(input_size, 1, image_H, image_W)
                # xhat = (xhat.reshape(input_size, -1) * max.reshape(-1, 1)).reshape(input_size, 1, image_H, image_W)

                loss_MSE = model.MSE_ori(images, xhat)
                MSE_sum = MSE_sum + loss_MSE.item()*input_size

                # 计算图片的分别MSE
                loss_MSE_sample = model.MSE_sample(images, xhat)

                # 计算图像平均PSNR
                PSNR_temp_sum = 0
                for g in range(input_size):
                    # psnr = 10 * torch.log10(max[g] * max[g] / loss_MSE_sample[g])
                    psnr = 10 * torch.log10(1 * 1 / loss_MSE_sample[g])
                    PSNR_temp_sum = PSNR_temp_sum + psnr
                PSNR_sum = PSNR_sum + PSNR_temp_sum.item()

                # 计算图像平均SSIM
                ssim = ssim_calculate(images, xhat, window_size = 7)
                SSIM_sum = SSIM_sum + ssim.item() * input_size

                # 采样图片的数值信息
                img_ori_sample = images[sample_list]
                img_pre_sample = xhat[sample_list]
                labels_sample = labels[sample_list]
                loss_MSE_sample = loss_MSE_sample[sample_list]

                if(t % sample_freq == 0):
                    # 将MSE写入.csv文件
                    for m in range(loss_MSE_sample.shape[0]):
                        row = [labels_sample[m][0].item(), labels_sample[m][1].item(), loss_MSE_sample[m].item()]
                        writer.writerow(row)

                    img_ori_sample = img_ori_sample.cpu().numpy()
                    img_pre_sample = img_pre_sample.cpu().numpy()
                    for j in range(labels_sample.shape[0]):
                        plt.imsave(path_img+'/'+str(labels_sample[j][0].item())+'_'+str(labels_sample[j][1].item())+'_pre'+'.png', img_pre_sample[j].squeeze(0))
                        plt.imsave(path_img+'/'+str(labels_sample[j][0].item())+'_'+str(labels_sample[j][1].item())+'_ori'+'.png', img_ori_sample[j].squeeze(0))

        # 输出分析结果
        MSE_average = MSE_sum / (picture_num)
        PSNR_average = PSNR_sum / picture_num
        SSIM_average = SSIM_sum / picture_num
        print(name_dataset, end =' ')
        print(str(seed)+':')
        print('After {} epoch, the average Pixel MSE loss is {}, PSNR is {}, SSIM is {}'.format(epochs_old, MSE_average, PSNR_average, SSIM_average))
        f_csv.close()

        row_data = [name_dataset, split_id, seed, proportion, MSE_average, SSIM_average, PSNR_average]
        writer_data.writerow(row_data)

        # pixel_max_list.sort()
        # pixel_min_list.sort()
        # print(pixel_max_list)
        # print(pixel_min_list)

        MSE_Sum = MSE_Sum + MSE_average
        SSIM_Sum = SSIM_Sum + SSIM_average
        PSNR_Sum = PSNR_Sum + PSNR_average

    MSE_Average = MSE_Sum / 5.0
    SSIM_Average = SSIM_Sum / 5.0
    PSNR_Average = PSNR_Sum / 5.0
    row_average = [name_dataset, split_id, proportion, MSE_Average, SSIM_Average, PSNR_Average]
    # writer_average.writerow(row_average)

f_data.close()
f_average.close()


# 문제: https://school.programmers.co.kr/learn/courses/30/lessons/42889
from collections import Counter
def solution(N, stages):
    answer = []
    stages = Counter(stages)
    stages = sorted(stages.items())

    scores = dict()
    for i in range(N+1):
        scores[i+1] = 0

    for i in range(len(stages)):
        # 분모 구하기
        denominator = 0
        for j in range(i, len(stages)):
            denominator += stages[j][1]

        # 실패율 구하기: scores[스테이지] = 클리어X / 도달한 사람 수
        scores[stages[i][0]] = stages[i][1] / denominator

    sort_score = sorted(scores.items(), key = lambda x: x[1], reverse = True)

    if sort_score[0][0] == N+1:
        del sort_score[0]

    for i in range(N):
        answer.append(sort_score[i][0])

    return answer


import argparse
import math

def is_pos_num(x, try_float):
    if x is None:
        return False
    try:
        x_num = float(x) if try_float else int(x)
        return x_num >= 0
    except ValueError:
        return False

def valid_args(t_, p_, n_, i_, a_):
    if (t_ != "diff" and t_ != "annuity") or not is_pos_num(i_, True):
        return False
    count = (p_ is not None) + (n_ is not None) + (a_ is not None)
    if (t_ == "diff" and a_ is not None) or count != 2:
        return False
    if p_ is not None and not is_pos_num(p_, False):
        return False
    if n_ is not None and not is_pos_num(n_, False):
        return False
    if a_ is not None and not is_pos_num(a_, False):
        return False
    return True

parser = argparse.ArgumentParser()
parser.add_argument("--type")
parser.add_argument("--principal")
parser.add_argument("--periods")
parser.add_argument("--interest")
parser.add_argument("--payment")
args = parser.parse_args()

t = args.type
p = args.principal
n = args.periods
i = args.interest
a = args.payment

if not valid_args(t, p, n, i, a):
    print("Incorrect parameters")
else:
    i = float(i) / 1200
    a = int(a) if a else None
    p = int(p) if p else None
    n = int(n) if n else None
    if t == "diff":
        total_payment = 0
        for m in range(1, n + 1):
            payment = math.ceil(p / n + i * (p - (p * (m - 1)) / n))
            total_payment += payment
            print(f"Month {m}: payment is {payment}")
        print(f"\nOverpayment = {total_payment - p}")
    else:
        if not p:
            p = math.floor(a / ((i * (1 + i) ** n) / ((1 + i) ** n - 1)))
            print(f"Your loan principal = {p}!")
        elif not a:
            a = math.ceil(p * (i * (1 + i) ** n) / ((1 + i) ** n - 1))
            print(f"Your monthly payment = {a}!")
        else:
            n = math.ceil(math.log(a / (a - i * p), 1 + i))
            years = n // 12
            months = n % 12
            time = "" if years == 0 else f"{years} years"
            if years and months:
                time += " and "
            time += f"{months} months" if months else ""
            print(f"It will take {time} to repay this loan!")
        print(f"Overpayment = {a * n - p}")


import json
import socketserver
import threading
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
from io import BytesIO
import depthai as dai
import cv2
from PIL import Image
from pathlib import Path
import numpy as np
import pickle
import select
import socket
import argparse
from helpers.server_classes import TCPServerRequest, VideoStreamHandler, ThreadedHTTPServer

"""
   Parsing arguments
"""

parser = argparse.ArgumentParser()
parser.add_argument("-d", "--device", help="Choose host: \n0 - delta simulation\n1 - real delta",
                    type=int, choices=[0, 1], default=0)
parser.add_argument("-i", "--ip", help="Set http and json servers ip-s. The default ip would be localhost",
                    type=str, default='localhost')
parser.add_argument("-p", "--preview", help="Choose preview: \n0 - preview off\n1 - preview on",
                    type=int, choices=[0, 1], default=1)
parser.add_argument("-D", "--depth", help="Choose depth: \n0 - depth off\n1 - depth on",
                    type=int, choices=[0, 1], default=1)

args = parser.parse_args()

if args.device == 0:
    delta_host, delta_port = "127.0.0.1", 2137
else:
    delta_host, delta_port = "192.168.0.155", 10

IPAddress = args.ip

if args.preview:
    previewBool = True
else:
    previewBool = False

if args.depth:
    depthBool = True
else:
    depthBool = False

# PORTS
HTTP_SERVER_PORT = 8090
HTTP_SERVER_PORT2 = 8080
if depthBool:
    HTTP_SERVER_PORT3 = 8070
JSON_PORT = 8060

"""
    Define pipeline & nodes
"""

pipeline = dai.Pipeline()

if depthBool:
    camRgb = pipeline.create(dai.node.ColorCamera)
    detectionNetwork = pipeline.create(dai.node.YoloSpatialDetectionNetwork)
    monoLeft = pipeline.create(dai.node.MonoCamera)
    monoRight = pipeline.create(dai.node.MonoCamera)
    stereo = pipeline.create(dai.node.StereoDepth)
else:
    camRgb = pipeline.create(dai.node.ColorCamera)
    detectionNetwork = pipeline.create(dai.node.YoloDetectionNetwork)

# outputs nodes
if depthBool:
    nnNetworkOut = pipeline.create(dai.node.XLinkOut)
    xoutNN = pipeline.create(dai.node.XLinkOut)
    xoutRgb = pipeline.create(dai.node.XLinkOut)
    xoutDepth = pipeline.create(dai.node.XLinkOut)

    xoutRgb.setStreamName("rgb")
    xoutNN.setStreamName("detections")
    nnNetworkOut.setStreamName("nnNetwork")
    xoutDepth.setStreamName("depth")
else:
    xoutNN = pipeline.create(dai.node.XLinkOut)
    xoutRgb = pipeline.create(dai.node.XLinkOut)

    xoutRgb.setStreamName("rgb")
    xoutNN.setStreamName("detections")

"""
    Define pipeline nodes properties
"""

# nodes properties
camRgb.setPreviewSize(416, 416)
camRgb.setResolution(dai.ColorCameraProperties.SensorResolution.THE_1080_P)
camRgb.setInterleaved(False)
camRgb.setColorOrder(dai.ColorCameraProperties.ColorOrder.BGR)
camRgb.setFps(40)

if depthBool:
    monoLeft.setResolution(dai.MonoCameraProperties.SensorResolution.THE_400_P)
    monoLeft.setCamera("left")
    monoRight.setResolution(dai.MonoCameraProperties.SensorResolution.THE_400_P)
    monoRight.setCamera("right")

    # setting node configs
    stereo.setDefaultProfilePreset(dai.node.StereoDepth.PresetMode.HIGH_DENSITY)

    # Align depth map to the perspective of RGB camera, on which inference is done
    stereo.setDepthAlign(dai.CameraBoardSocket.CAM_A)
    stereo.setOutputSize(monoLeft.getResolutionWidth(), monoLeft.getResolutionHeight())
    stereo.setSubpixel(True)

"""
    Configure Yolo NN model
"""

# blob model path
detectionNetwork.setBlobPath(Path("config/yoloModel.blob"))

# open NN config
configPath = Path("config/yoloConfig.json")

if not configPath.exists():
    raise ValueError(f"Path {configPath} does not exist!")

print("Loading Yolo config...")
with open(configPath) as file:
    config = json.load(file)
nnConfig = config["nn_config"]
if nnConfig:
    print("Successfully loaded config")

if depthBool:
    # spatial Yolo detection parameters
    detectionNetwork.input.setBlocking(False)
    detectionNetwork.setBoundingBoxScaleFactor(0.5)
    detectionNetwork.setDepthLowerThreshold(100) # Min 10 centimeters
    detectionNetwork.setDepthUpperThreshold(5000) # Max 5 meters

# configure Yolo
detectionNetwork.setNumClasses(nnConfig["NN_specific_metadata"]["classes"])
detectionNetwork.setCoordinateSize(nnConfig["NN_specific_metadata"]["coordinates"])
detectionNetwork.setAnchors(nnConfig["NN_specific_metadata"]["anchors"])
detectionNetwork.setAnchorMasks(nnConfig["NN_specific_metadata"]["anchor_masks"])
detectionNetwork.setIouThreshold(nnConfig["NN_specific_metadata"]["iou_threshold"])
detectionNetwork.setConfidenceThreshold(nnConfig["NN_specific_metadata"]["confidence_threshold"])

# get labels
labels = config["mappings"]["labels"]

"""
    Link pipeline nodes
"""
if depthBool:
    monoLeft.out.link(stereo.left)
    monoRight.out.link(stereo.right)

    stereo.depth.link(detectionNetwork.inputDepth)

    camRgb.preview.link(detectionNetwork.input)

    detectionNetwork.passthrough.link(xoutRgb.input)  # TODO should be sync with detection ?
    detectionNetwork.passthroughDepth.link(xoutDepth.input)
    detectionNetwork.outNetwork.link(nnNetworkOut.input)
    detectionNetwork.out.link(xoutNN.input)

else:
    camRgb.preview.link(detectionNetwork.input)
    detectionNetwork.passthrough.link(xoutRgb.input)
    detectionNetwork.out.link(xoutNN.input)

"""
    Start servers
"""

# start TCP data server (JSON)
try:
    server_TCP = socketserver.TCPServer(("127.0.0.1", JSON_PORT), TCPServerRequest)
    th = threading.Thread(target=server_TCP.serve_forever)
    th.daemon = True
    th.start()
except Exception as e:
    print(e)

# start MJPEG HTTP Servers
try:
    server_HTTP = ThreadedHTTPServer((args.ip, HTTP_SERVER_PORT), VideoStreamHandler)
    th2 = threading.Thread(target=server_HTTP.serve_forever)
    th2.daemon = True
    th2.start()
except Exception as e:
    print(e)

try:
    server_HTTP2 = ThreadedHTTPServer((args.ip, HTTP_SERVER_PORT2), VideoStreamHandler)
    th3 = threading.Thread(target=server_HTTP2.serve_forever)
    th3.daemon = True
    th3.start()
except Exception as e:
    print(e)

if depthBool:
    try:
        server_HTTP3 = ThreadedHTTPServer((args.ip, HTTP_SERVER_PORT3), VideoStreamHandler)
        th4 = threading.Thread(target=server_HTTP3.serve_forever)
        th4.daemon = True
        th4.start()
    except Exception as e:
        print(e)

# connect to device and start pipeline
with dai.Device(pipeline) as device:
    print("DepthAI running.")
    print(f"Navigate to '{str(IPAddress)}:{str(HTTP_SERVER_PORT)}' for normal video stream.")
    print(f"Navigate to '{str(IPAddress)}:{str(HTTP_SERVER_PORT2)}' for warped video stream.")
    if depthBool:
        print(f"Navigate to '{str(IPAddress)}:{str(HTTP_SERVER_PORT3)}' for depth heatmap video stream.")
    print(f"Navigate to '{str(IPAddress)}:{str(JSON_PORT)}' for detection data in json format.")

    # load transformation matrix
    with open("perspectiveCalibration/calibration_result", "rb") as ifile:
        transformation_matrix = pickle.load(ifile)

    if depthBool:
        # output queues will be used to get the rgb frames and nn data from the outputs defined above
        previewQueue = device.getOutputQueue(name="rgb", maxSize=4, blocking=False)
        detectionNNQueue = device.getOutputQueue(name="detections", maxSize=4, blocking=False)
        depthQueue = device.getOutputQueue(name="depth", maxSize=4, blocking=False)
        networkQueue = device.getOutputQueue(name="nnNetwork", maxSize=4, blocking=False)
    else:
        previewQueue = device.getOutputQueue(name="rgb", maxSize=4, blocking=False)
        detectionNNQueue = device.getOutputQueue(name="detections", maxSize=4, blocking=False)

    startTime = time.monotonic()
    counter = 0
    fps = 0
    color = (255, 255, 255)

    while True:
        inPreview = previewQueue.get()
        inDet = detectionNNQueue.get()
        if depthBool:
            depthBool = depthQueue.get()
            inNN = networkQueue.get()

        frame = inPreview.getCvFrame()
        frame_copy = frame
        if depthBool:
            depthFrame = depthBool.getFrame()  # depthFrame values are in millimeters
            depth_downscaled = depthFrame[::4]
            min_depth = np.percentile(depth_downscaled[depth_downscaled != 0], 1)
            max_depth = np.percentile(depth_downscaled, 99)
            depthFrameColor = np.interp(depthFrame, (min_depth, max_depth), (0, 255)).astype(np.uint8)
            depthFrameColor = cv2.applyColorMap(depthFrameColor, cv2.COLORMAP_HOT)

        counter += 1
        current_time = time.monotonic()
        if (current_time - startTime) > 1:
            fps = counter / (current_time - startTime)
            counter = 0
            startTime = current_time

        detections = inDet.detections

        # If the detections is available, draw bounding boxes on it and show the frame
        height = frame.shape[0]
        width = frame.shape[1]

        # prepare dictionary for json format send
        send = {el: [] for el in labels}

        for detection in detections:

            # TODO delete?
            # if depthBool:
            #     roiData = detection.boundingBoxMapping
            #     roi = roiData.roi
            #     roi = roi.denormalize(depthFrameColor.shape[1], depthFrameColor.shape[0])
            #     topLeft = roi.topLeft()
            #     bottomRight = roi.bottomRight()
            #     xmin = int(topLeft.x)
            #     ymin = int(topLeft.y)
            #     xmax = int(bottomRight.x)
            #     ymax = int(bottomRight.y)

            # Denormalize bounding box
            x1 = int(detection.xmin * width)
            x2 = int(detection.xmax * width)
            y1 = int(detection.ymin * height)
            y2 = int(detection.ymax * height)

            try:
                label = labels[detection.label]
            except:
                label = detection.label

            # bbox middle coordinates
            bbox_x, bbox_y = int((x1 + x2) // 2), int((y1 + y2) // 2)
            if transformation_matrix.any():
                # if perspective calibration was done calculate detection (x,y) on warped img
                t_bbox_x, t_bbox_y, scale = np.matmul(transformation_matrix, np.float32([bbox_x, bbox_y, 1]))
                t_bbox_x, t_bbox_y = int(t_bbox_x / scale), int(t_bbox_y / scale)
            else:
                t_bbox_x, t_bbox_y = None, None

            if depthBool:
                cv2.putText(frame, str(label), (x1 + 10, y1 + 20), cv2.FONT_HERSHEY_TRIPLEX, 0.5, color)
                cv2.putText(frame, "{:.2f}".format(detection.confidence * 100), (x1 + 10, y1 + 35),
                            cv2.FONT_HERSHEY_TRIPLEX, 0.5, color)
                cv2.putText(frame, f"X: {int(detection.spatialCoordinates.x)} mm", (x1 + 10, y1 + 50),
                            cv2.FONT_HERSHEY_TRIPLEX, 0.5, color)
                cv2.putText(frame, f"Y: {int(detection.spatialCoordinates.y)} mm", (x1 + 10, y1 + 65),
                            cv2.FONT_HERSHEY_TRIPLEX, 0.5, color)
                cv2.putText(frame, f"Z: {int(detection.spatialCoordinates.z)} mm", (x1 + 10, y1 + 80),
                            cv2.FONT_HERSHEY_TRIPLEX, 0.5, color)

            else:
                cv2.putText(frame, str(label), (x1 + 10, y1 + 20), cv2.FONT_HERSHEY_TRIPLEX, 0.5, color)
                cv2.putText(frame, "{:.2f}".format(detection.confidence * 100), (x1 + 10, y1 + 35),
                            cv2.FONT_HERSHEY_TRIPLEX, 0.5, color)

            cv2.rectangle(frame, (x1, y1), (x2, y2), color, cv2.FONT_HERSHEY_SIMPLEX)

            # append "send" json file
            if depthBool:
                spatialXYZ = (detection.spatialCoordinates.x, detection.spatialCoordinates.y,
                                   detection.spatialCoordinates.z)
            else:
                spatialXYZ = (None, None, None)

            det = {"x_max": detection.xmax, "x_min": detection.xmin, "y_max": detection.ymax, "y_min": detection.ymin,
                   "middle": (bbox_x, bbox_y), "middle_transformed": (t_bbox_x, t_bbox_y), "conf": detection.confidence,
                   "spatial_xyz": spatialXYZ}
            send[label].append(det)

        # send birdview camera if perspective calibration was done
        if transformation_matrix.any():

            # transform frame
            transformed_frame = cv2.warpPerspective(frame_copy, transformation_matrix, (width, height))

            # draw circle for every bar recognized in new perspective
            for choclate_bar_name in send:
                for detected_bar in send[choclate_bar_name]:
                    coordinates = detected_bar["middle_transformed"]
                    cv2.circle(transformed_frame, coordinates, 5, (255, 255, 255), -1)
            server_HTTP2.frametosend = transformed_frame

        # encode json file and send it using TCP
        json_send = json.dumps(send)
        server_TCP.datatosend = json_send

        # send frames using http servers
        server_HTTP.frametosend = frame
        if depthBool:
            server_HTTP3.frametosend = depthFrameColor

        if previewBool:
            cv2.putText(frame, "NN fps: {:.2f}".format(fps), (2, frame.shape[0] - 4), cv2.FONT_HERSHEY_TRIPLEX, 0.4, color)
            cv2.putText(transformed_frame, "NN fps: {:.2f}".format(fps), (2, frame.shape[0] - 4), cv2.FONT_HERSHEY_TRIPLEX, 0.4, color)

            cv2.imshow("rgb", frame)
            cv2.imshow("Transformed frame", transformed_frame)

            if depthBool:
                cv2.imshow("depth", depthFrameColor)

        if cv2.waitKey(1) == ord('q'):
            break


from twitter_streamer import TwitterStreamer
from runManager import RunManager
from read_keywords import get_keywords

class Configuration:
    """Contains all parameters of the program."""

    def __init__(self):

        folder = 'data/'

        # CSV file name of collected tweets
        self.tweets_filename = folder + 'stream_tweets.csv'

        # To create a new file or append to an existing file.
        self.new_file = True

        # Number of tweets to collect. Set to None if infinite.
        self.nb_tweets_limit = None

        # Parameters for stream filter.
        keywords_filename = folder + 'keywords_1.txt'
        self.keywords = get_keywords(keywords_filename)
        self.languages = None

        # Number of tweets collected between each print of a stream's progression.
        self.stream_prints_interval = 1

if __name__ == '__main__':

    c = Configuration()
    rm = RunManager(c)

    streamer = TwitterStreamer(rm)
    streamer.stream_tweets(rm)


#Nome: Matheus Felipe Magalhães de Assis
#Matrícula: 19/0035242
#Disciplina: Estrutura de Dados
#E-mail: matheusfelipemdeassis@gmail.com

x , y = input().split()
x = int(x)
y = int(y)

#O símbolo % é o resto
if x%y == 0 or y%x == 0:
	print('Sao Multiplos')
else:
	print('Nao sao Multiplos')


import os
from typing import List

def _load_input():
    folder = os.path.dirname(__file__)
    input_file_path = os.path.join(folder, 'input.txt')
    with open(input_file_path, 'r') as f:
        data = [line.strip() for line in f.readlines()]
    return data

def main():
    data = [int(line) for line in _load_input()]
    window_start_idx = 0
    window_stop_idx = window_start_idx + 25
    incorrect_value = None
    while window_stop_idx < len(data):
        window = sorted(data[window_start_idx:window_stop_idx])
        current_value = data[window_stop_idx]
        found_sum = False
        for i in range(len(window)):
            for j in range(i + 1, len(window)):
                a = window[i]
                b = window[j]
                if a != b and (a + b == current_value):
                    found_sum = True
                    break
                elif a + b > current_value:
                    break
            if found_sum or 2 * window[i] > current_value:
                break
        if not found_sum:
            incorrect_value = current_value
            break
        window_start_idx += 1
        window_stop_idx += 1

    print(incorrect_value)

if __name__ == '__main__':
    main()


#!/usr/bin/python3
""" This module prints Inputted name by the User """

def say_my_name(first_name, last_name=""):
    """Checking if names are indeed strings """
    if type(first_name) != str:
        raise TypeError("first_name must be a string")
    if type(last_name) != str:
        raise TypeError("last_name must be a string")
    print("My name is {} {}".format(first_name, last_name))


import re
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.views.decorators.cache import never_cache
from tagging.models import Tag
from meetingtools.apps.archive.forms import TagArchiveForm
from meetingtools.apps.archive.models import publish_archive, Archive
from meetingtools.apps.room.models import Room
from meetingtools.multiresponse import redirect_to, respond_to

__author__ = 'leifj'

class HttpRedirect(object):
    pass

@login_required
def publish_sco(request,rid,sco_id):
    room = get_object_or_404(Room,pk=rid)
    acc = room.sco.sco_id
    ar = publish_archive(room,sco_id)
    return redirect_to("/room/%d/recordings#%d" % (rid,ar.sco.sco_id))

def _can_tag(request,tag):
    if tag in ('selfcleaning','cleaning','public','private'):
        return False,"'%s' is reserved" % tag
        # XXX implement access model for tags here soon
    return True,""

@never_cache
@login_required
def untag(request,rid,tag):
    ar = get_object_or_404(Archive,pk=rid)
    new_tags = []
    for t in Tag.objects.get_for_object(ar):
        if t.name != tag:
            new_tags.append(t.name)

    Tag.objects.update_tags(ar, ' '.join(new_tags))
    return redirect_to("/archive/%d/tag" % ar.id)

@never_cache
@login_required
def tag(request,rid):
    archive = get_object_or_404(Archive,pk=rid)
    if request.method == 'POST':
        form = TagArchiveForm(request.POST)
        if form.is_valid():
            for tag in re.split('[,\s]+',form.cleaned_data['tag']):
                tag = tag.strip()
                if tag:
                    ok,reason = _can_tag(request,tag)
                    if ok:
                        Tag.objects.add_tag(archive, tag)
                    else:
                        form._errors['tag'] = form.error_class([u'%s ... please choose another tag!' % reason])
    else:
        form = TagArchiveForm()

    tags = Tag.objects.get_for_object(archive)
    tn = "+".join([t.name for t in tags])
    return respond_to(request,
        {'text/html': "apps/archive/tag.html"},
        {'form': form,'formtitle': 'Add Tag','cancelname':'Done','submitname': 'Add Tag','archive': archive, 'tagstring': tn,'tags': tags})


#
# @lc app=leetcode.cn id=234 lang=python3
#
# [234] 回文链表
#

# @lc code=start
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def isPalindrome(self, head: ListNode) -> bool:
        slow = head
        fast = head
        arr = []
        while fast:
            arr.append(slow.val)
            slow = slow.next
            fast = fast.next
            if fast:
                fast = fast.next
            else:
                arr.pop()
        i = 1
        while slow:
            if slow.val != arr[-i]:
                return False
            slow = slow.next
            i += 1
        return True

# @lc code=end


from django.urls import path
from .views import *

app_name = 'api'

urlpatterns = [
    path('posts/', PostViewSet.as_view({'post': 'create'}), name='post-list'),
    path('posts/<int:pk>/', PostViewSet.as_view({'delete': 'destroy'}), name='post-detail'),
    path('posts/by-doctor/<int:doctor_id>/', PostViewSet.as_view({'get': 'list_by_doctor'}), name='post-list-by-doctor'),
    path('packeposts/', PostList.as_view(), name='post-list'),
    path('posts/<int:post_id>/like-dislike/', LikeDislikeView.as_view(), name='like-dislike'),
    path('posts/<int:post_id>/create-comment/', CommentView.as_view(), name='create-comment'),
    path('comments/<int:comment_id>/',CommentView.as_view(), name='delete-comment')
]

# http://localhost:8000/api/packeposts/?user_id=1