import warnings
warnings.filterwarnings('ignore')

from matplotlib.pyplot import figure
import numpy as np
import pandas as pd
import copy
import flask
import MeCab
import ipadic
import math
import datetime
from datetime import datetime as dt, timedelta
import statistics

##入力した学籍番号に対して，似たような学生のデータを使い，推薦科目を決める##

#Person関数で指定した学生とすべての学生の類似度を算出
# data_all_npは全ユーザのスコア， target_user_indexは予測したいユーザのインデックス
def get_correlation_coefficents(data_all_np, target_user_index):
    similarities = []
    target = data_all_np[target_user_index]

    for i, score in enumerate(data_all_np):
        # 共通の評価が少ない場合は除外(0じゃなかったら0を返す)
        indices = np.where(((target + 1) * (score + 1)) != 0)[0]
        if len(indices) < 3 or i == target_user_index:
            continue

        # 下の[0, 1]は求めた相関係数行列の0行1列目の数値を取得することを意味する．
        similarity = np.corrcoef(target[indices], score[indices])[0, 1]
        # 欠損値だった場合の処理
        if np.isnan(similarity):
            continue

        similarities.append((i, similarity))

    return sorted(similarities, key=lambda s: s[1], reverse=True)

#予測評価値を求める
def predict(data_all_np, similarities, target_user_index, target_item_index):
    target = data_all_np[target_user_index]

    avg_target = np.mean(target[np.where(target >= 0)])

    numerator = 0.0
    denominator = 0.0
    k = 0

    for similarity in similarities:
        # 類似度の上位10人の評価値を使う
        if k > 10 or similarity[1] <= 0.0:
            break

        score = data_all_np[similarity[0]]
        if score[target_item_index] >= 0:
            denominator += similarity[1]
            numerator += similarity[1] * (score[target_item_index] - np.mean(score[np.where(score >= 0)]))
            k += 1

    return avg_target + (numerator / denominator) if denominator > 0 else -1

#予測評価値をもとにランキング
def rank_items(data_all_np, similarities, target_user_index):
    rankings = []
    target = data_all_np[target_user_index]
    for i in range(113):
        # 既に取得済みの科目はスキップ
        if target[i] >= 0:
            continue

        rankings.append((i, predict(data_all_np, similarities, target_user_index, i)))

    return sorted(rankings, key=lambda r: r[1], reverse=True)


def tannisyutoku(sum,youkenn,data_all,rank,suisennkamoku,nondel_data_all,all_sum,df4,mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '0A']
        #print(zeroA_index_list)
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku0A(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '0A']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku0B(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '0B']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku0C(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '0C']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku0D(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '0D']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku1A(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '1A']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku1B(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '1B']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku1C(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '1C']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku2A(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '2A']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku2B(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '2B']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku3A(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '3A']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku4A(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '4A']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku4B(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '4B']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku5A(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '5A']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku5B(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '5B']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku5C(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '5C']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku5D(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '5D']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku6A(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '6A']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku6B(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '6B']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku6C(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '6C']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku6D(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '6D']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku6E(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '6E']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum

def tannisyutoku6F(sum, youkenn, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list):
    if sum < youkenn:
        zeroA_index_list = [i for i, x in enumerate(df4) if x == '6F']
        #履修,推薦していない科目の列番号一覧
        mirisyuu_index_list = []
        for i in range(len(mirisyuu_list)):
            mirisyuu_index_list.append(data_all.columns.get_loc(f'{mirisyuu_list[i]}'))
        #print(mirisyuu_index_list)

        #区分が0Aの科目リストと履修，推薦されていない科目のリストで共通する科目の列番号を取得
        A0_common_index = list(set(zeroA_index_list) & set(mirisyuu_index_list))
        #print(A0_common_index)
        zeroA_suisennkouho = []
        for i in range(len(A0_common_index)):
            for j in range(len(rank)):
                if rank[j][0] == A0_common_index[i]:
                    zeroA_suisennkouho.append(rank[j])
        zeroA_suisennkouho = sorted(zeroA_suisennkouho, reverse=True,key=lambda x: x[1])
        #卒業要件単位を満たすまで単位を取得
        i = 0
        while sum < youkenn:
            try:
                suisennkamoku.append(data_all.columns[zeroA_suisennkouho[i][0]])
                sum += nondel_data_all.iloc[2,zeroA_suisennkouho[i][0]]
                i += 1
            except IndexError:
                break
        all_sum += sum
    else:
        pass
    return all_sum



################################
################################
################################
################################
##これより下の部分で評価とレビューをもとに点数計算する##
################################
################################
################################
################################

#類似度スコアの計算
def Similarity(df):
    text = df['text']
    sim_df = pd.DataFrame(index=df.index,columns=df.index)

    """
    def n_gram(target, n):
    # 基準を1文字(単語)ずつ ずらしながらn文字分抜き出す
        return [ target[idx:idx + n] for idx in range(len(target) - n + 1)]
    """

    bigram_set = [set() for _ in range(len(text))]
    for i in range(len(text)):
        target = str(text[i])
        bigram_set[i].update([ target[idx:idx + 2] for idx in range(len(target) - 2 + 1)])

    for i in range(len(sim_df.index)):
        for j in range(len(sim_df.columns)):
            if i == j:
                sim_df[i][j] =  0
            else:
                sim_df[i][j] =  5 * len(bigram_set[i].intersection(bigram_set[j]))/len(bigram_set[i].union(bigram_set[j]))

    S_score_norm = sim_df.max(axis=1)
    S_score_norm_list = S_score_norm.tolist()
    return S_score_norm_list

################################
################################

#情報度スコアの計算
def Informative(df):
    text = df['text']
    tagger = MeCab.Tagger()
    meisi_list = [[] for _ in range(len(text))]

    #それぞれのレビューの本分から名詞だけを抜き出す
    for i in range(len(text)):
        node = tagger.parseToNode(str(text[i]))
        node = node.next # 最初のnodeを飛ばす
        while node.next:
            # surface = 表層、入力文そのまま
            surface = node.surface
            # feature は詳細情報、形式はカンマ区切り
            # 例: 落ち-> 動詞,自立,*,*,一段,連用形,落ちる,オチ,オチ
            # 1番目のフィールドが基本品詞
            hinshi = node.feature.split(',')[0]
            # 今回分かち処理を確認できるようにあえて全部printする
            if hinshi == "名詞":
                #print("名詞", surface, sep="\t")
                meisi_list[i].append(surface)
            else:
                pass
            node = node.next

    I_score = [[]for _ in range(len(meisi_list))]

    for h in range(len(meisi_list)):
        dfterm = [0]  * len(meisi_list[h])

        for i in range(len(meisi_list)):
            for j in range(len(meisi_list[h])):
                if meisi_list[i].count(meisi_list[h][j]) == 1:
                    dfterm[j]+=1
                else:
                    pass

        n = len(text)
        a = 0

        for i in range(len(dfterm)):
            if dfterm[i] == 0:
                pass
            else:
                a += math.log(n/dfterm[i])

        I_score[h] = math.log(1 + a)

    I_score_norm = [[] for _ in range(len(I_score))]

    for i in range(len(I_score)):
        try:
            I_score_norm[i] = 5 * (1 - (I_score[i]/max(I_score)))
        except ZeroDivisionError:
            I_score_norm[i] = 0

    return I_score_norm

##############################
##############################

#集中性スコア
def Concentration(df):

    df_a = df.loc[:,['evaluation','date']]

    for i in range(len(df_a.index)):
        #print(df_a.iat[i,1])
        df_a.iat[i,1] = datetime.datetime.strptime(df_a.iat[i,1], '%Y/%m/%d %H:%M')

    df_i = df_a.set_index('date')

    #aaa = df_i[f'{date} 00:00:00':f'{date} 23:59:59']
    #print(aaa)

    df_s = df_i.sort_index()

    #evaluation が５のものを取り出す
    df_aaa = df_s.query('evaluation == 5')

    pd.set_option('display.max_rows', 10000)

    #日付ごとに評価値５のものの個数を出力する
    #例：2022-02-14では評価値５のレビューが5回あった， 2022-02-15では評価値５のレビューが1回
    #それを，データフレームに入れる → NANの部分が全て０になる
    df_n = pd.DataFrame(df_aaa.resample('D').size())
    #print(df_n)
    #print("========================")


    #インデックスを振り直す
    df_r = df_n.reset_index()
    #print(df_r)
    #print("-----------")

    #２列目の全部の行を取得する ⇨ 日付データは取得しない
    y = df_r.iloc[:,1]

    #MACD = (時系列値の過去f期間の移動指数平均) - (時系列値の過去s期間の移動指数平均)
    #Signal = (MACD値の過去t期間の移動指数平均)
    #Histgram = MACD - Signal
    f = 4
    s = 8
    t = 5

    # n = 157
    n = len(y)
    macd_list = []
    signal_list = []
    histgram_list = []

    for i in range(n):
        if i < f:
            macd_list.append(0)
            signal_list.append(0)
            histgram_list.append(0)
        else :
            macd = sum(y[i-f+1:i+1])/len(y[i-f+1:i+1]) - sum(y[max(0,i-s):i+1])/len(y[max(0,i-s):i+1])
            macd_list.append(macd)
            signal = sum(macd_list[max(0,i-t+1):i+1])/len(macd_list[max(0,i-t+1):i+1])
            signal_list.append(signal)
            histgram = macd - signal
            histgram_list.append(histgram)

    #len(my) = 157
    my = np.array(histgram_list)
    #print(my)

    ave = np.average(my)
    std = np.std(my)
    sikiiti = ave + 3 * std
    #print(sikiiti)

    time = []
    for i in range(len(my)):
        if my[i] > sikiiti:
            #print(df_n.index[i].strftime('%Y-%m-%d'))
            time.append(df_n.index[i].strftime('%Y-%m-%d'))
            #print(df_s[df_n.index[i].strftime('%Y/%m/%d'):df_n.index[i].strftime('%Y/%m/%d')])
        else:
            pass

    #print(time)

    # len(time) = 4 #
    #C_score_norm =[]
    C_score_norm =[0]*len(df_i)

    if len(time) == 0:
        for i in range(len(df_s)):
            C_score_norm.append(0)
    else:
        for h in range(len(time)):
            date = time[h]
            #print(date)

            #df_iから対象となるdateのデータを取得する
            aaa = df_i[f'{date} 00:00:00':f'{date} 23:59:59']
            #print(aaa)

            # 15T = 15分ごと
            # aaaを15分ごとに刻む
            df_n = pd.DataFrame(aaa.resample('15T').size())
            #print(df_n)

            # df_nのインデックスを振り直す
            df_r = df_n.reset_index()

            # df_rから評価値の部分だけ取得する
            y = df_r.iloc[:,1]
            #print(y)

            n = len(y)
            #print(n)
            macd_list = []
            signal_list = []
            histgram_list = []

            for i in range(n):
                if i < f:
                    macd_list.append(0)
                    signal_list.append(0)
                    histgram_list.append(0)
                else :
                    macd = sum(y[i-f+1:i+1])/len(y[i-f+1:i+1]) - sum(y[max(0,i-s):i+1])/len(y[max(0,i-s):i+1])
                    macd_list.append(macd)
                    signal = sum(macd_list[max(0,i-t+1):i+1])/len(macd_list[max(0,i-t+1):i+1])
                    signal_list.append(signal)
                    histgram = macd - signal
                    histgram_list.append(histgram)
            my = np.array(histgram_list)

            ave = np.average(my)
            std = np.std(my)
            sikiiti = ave + 3 * std

            #print(sikiiti)

            target_time = []

            #print(my)

            for i in range(len(my)):
                if my[i] > sikiiti:
                    target_time.append(df_n.index[i].strftime('%Y-%m-%d %H:%M:%S'))
                    #print(target_time)
                else:
                    pass

            #print(len(target_time))

            time_new = []
            size = []
            C_score = []

            for i in range(len(target_time)):
                time_new.append(datetime.datetime.strptime(target_time[i], '%Y-%m-%d %H:%M:%S'))#datetime型に変換
                size.append(len(df_i[f'{time_new[i]}':f'{time_new[i]+datetime.timedelta(minutes=15)}']))
                C_score.append(math.log(size[i]))

            C_score_max = max(C_score, default = C_score)
            #print(C_score)

            #C_score_norm = []
            # for j in range(len(time_new)):
            #     for i in range(len(df_i)):
            #         if time_new[j] < df_i.index[i] < time_new[j]+datetime.timedelta(minutes=15):
            #             C_score_norm.append(5 * C_score[j] / C_score_max)
            #         else:
            #             C_score_norm.append(0)

            #print(len(time_new))
            if len(time_new) >= 1:
                for j in range(len(time_new)):
                    for i in range(len(df_i)):
                        if time_new[j] < df_i.index[i] < time_new[j]+datetime.timedelta(minutes=15):
                            #C_score_norm.append(5 * C_score[j] / C_score_max)
                            C_score_norm[i] = (5 * C_score[j] / C_score_max)
                        else:
                            #C_score_norm.append(0)
                            C_score_norm[i] = 0
            else:
                pass

    return C_score_norm

###########################
###########################

###video版の集中性スコア#####
def Video_Concentration(df):

    df_a = df.loc[:,['evaluation','date']]

    for i in range(len(df_a.index)):
        #print(df_a.iat[i,1])
        df_a.iat[i,1] = datetime.datetime.strptime(df_a.iat[i,1], '%Y-%m-%d %H:%M:%S')

    df_i = df_a.set_index('date')

    #aaa = df_i[f'{date} 00:00:00':f'{date} 23:59:59']
    #print(aaa)

    df_s = df_i.sort_index()

    #evaluation が５のものを取り出す
    df_aaa = df_s.query('evaluation == 5')

    pd.set_option('display.max_rows', 10000)

    #日付ごとに評価値５のものの個数を出力する
    #例：2022-02-14では評価値５のレビューが5回あった， 2022-02-15では評価値５のレビューが1回
    #それを，データフレームに入れる → NANの部分が全て０になる
    df_n = pd.DataFrame(df_aaa.resample('D').size())
    #print(df_n)
    #print("========================")


    #インデックスを振り直す
    df_r = df_n.reset_index()
    #print(df_r)
    #print("-----------")

    #２列目の全部の行を取得する ⇨ 日付データは取得しない
    y = df_r.iloc[:,1]

    f = 4
    s = 8
    t = 5

    # n = 157
    n = len(y)
    macd_list = []
    signal_list = []
    histgram_list = []

    for i in range(n):
        if i < f:
            macd_list.append(0)
            signal_list.append(0)
            histgram_list.append(0)
        else :
            macd = sum(y[i-f+1:i+1])/len(y[i-f+1:i+1]) - sum(y[max(0,i-s):i+1])/len(y[max(0,i-s):i+1])
            macd_list.append(macd)
            signal = sum(macd_list[max(0,i-t+1):i+1])/len(macd_list[max(0,i-t+1):i+1])
            signal_list.append(signal)
            histgram = macd - signal
            histgram_list.append(histgram)

    #len(my) = 157
    my = np.array(histgram_list)
    #print(my)

    ave = np.average(my)
    std = np.std(my)
    sikiiti = ave + 3 * std
    #print(sikiiti)

    time = []
    for i in range(len(my)):
        if my[i] > sikiiti:
            #print(df_n.index[i].strftime('%Y-%m-%d'))
            time.append(df_n.index[i].strftime('%Y-%m-%d'))
            #print(df_s[df_n.index[i].strftime('%Y/%m/%d'):df_n.index[i].strftime('%Y/%m/%d')])
        else:
            pass

    #print(time)

    # len(time) = 4 #
    #C_score_norm =[]
    C_score_norm =[0]*len(df_i)

    if len(time) == 0:
        for i in range(len(df_s)):
            C_score_norm.append(0)
    else:
        for h in range(len(time)):
            date = time[h]
            #print(date)

            #df_iから対象となるdateのデータを取得する
            aaa = df_i[f'{date} 00:00:00':f'{date} 23:59:59']
            #print(aaa)

            # 15T = 15分ごと
            # aaaを15分ごとに刻む
            df_n = pd.DataFrame(aaa.resample('15T').size())
            #print(df_n)

            # df_nのインデックスを振り直す
            df_r = df_n.reset_index()

            # df_rから評価値の部分だけ取得する
            y = df_r.iloc[:,1]
            #print(y)

            n = len(y)
            #print(n)
            macd_list = []
            signal_list = []
            histgram_list = []

            for i in range(n):
                if i < f:
                    macd_list.append(0)
                    signal_list.append(0)
                    histgram_list.append(0)
                else :
                    macd = sum(y[i-f+1:i+1])/len(y[i-f+1:i+1]) - sum(y[max(0,i-s):i+1])/len(y[max(0,i-s):i+1])
                    macd_list.append(macd)
                    signal = sum(macd_list[max(0,i-t+1):i+1])/len(macd_list[max(0,i-t+1):i+1])
                    signal_list.append(signal)
                    histgram = macd - signal
                    histgram_list.append(histgram)
            my = np.array(histgram_list)

            ave = np.average(my)
            std = np.std(my)
            sikiiti = ave + 3 * std

            #print(sikiiti)

            target_time = []

            #print(my)

            for i in range(len(my)):
                if my[i] > sikiiti:
                    target_time.append(df_n.index[i].strftime('%Y-%m-%d %H:%M:%S'))
                    #print(target_time)
                else:
                    pass

            #print(len(target_time))

            time_new = []
            size = []
            C_score = []

            for i in range(len(target_time)):
                time_new.append(datetime.datetime.strptime(target_time[i], '%Y-%m-%d %H:%M:%S'))#datetime型に変換
                size.append(len(df_i[f'{time_new[i]}':f'{time_new[i]+datetime.timedelta(minutes=15)}']))
                C_score.append(math.log(size[i]))

            C_score_max = max(C_score, default = C_score)
            #print(C_score)

            #print(len(time_new))
            if len(time_new) >= 1:
                for j in range(len(time_new)):
                    for i in range(len(df_i)):
                        if time_new[j] < df_i.index[i] < time_new[j]+datetime.timedelta(minutes=15):
                            #C_score_norm.append(5 * C_score[j] / C_score_max)
                            C_score_norm[i] = (5 * C_score[j] / C_score_max)
                        else:
                            #C_score_norm.append(0)
                            C_score_norm[i] = 0
            else:
                pass

    return C_score_norm

###########################

#信頼性スコアの計算（HP教材版）
def Credibility(S_score_norm,I_score_norm,C_score_norm,HPnumber,df):
    F_score = []
    index = []
    print(df.query(f'Hpnumber == {HPnumber}').index)
    index = df.query(f'Hpnumber == {HPnumber}').index
    sum = 0
    for i in range(len(index)):
        F_score.append((S_score_norm[index[i]]+I_score_norm[index[i]]+C_score_norm[index[i]])/3)
        sum += df.at[index[i],'evaluation']
    Ave_score = sum/len(index)

    #F_score_score = Credibility_score のこと
    #F_scoreの平均値を求める : statistics.mean(F_score)
    if statistics.mean(F_score) == 0:
        F_cre_score = 0
    else:
        F_cre_score = Ave_score/statistics.mean(F_score)
    #print(F_cre_score)

    return F_cre_score,Ave_score

#信頼性スコアの計算(ビデオ教材版)
def Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df):
    F_score = []
    index = []
    index = video_df.query(f'Youtubenumber == {Youtubenumber}').index
    sum = 0
    # print(S_score_norm)
    # print(I_score_norm)
    # print(C_score_norm)
    for i in range(len(index)):
        F_score.append((S_score_norm[index[i]]+I_score_norm[index[i]]+C_score_norm[index[i]])/3)
        sum += video_df.at[index[i],'evaluation']
    Ave_score = sum/len(index)

    if statistics.mean(F_score) == 0:
        F_cre_score = 0
    else:
        F_cre_score = Ave_score/statistics.mean(F_score)


    return F_cre_score,Ave_score


#kyouzaiDB ⇨ kyouzai.csv
def kousinn(kyouzaiDB,Credibility_score,HPnumber):
    #評価した教材のCredibility_scoreに，計算したCredibility_scoreを更新する
    kyouzaiDB.at[kyouzaiDB.query(f'Hpnumber == {HPnumber}').index[0],'Credibility_score'] = Credibility_score
    # Credibility_score順に並ぶ変える（高いスコアを一番上に）
    kyouzaiDB_sort = kyouzaiDB.sort_values('Credibility_score',ascending=False)
    #更新したkyouzaiDBをkyouzai.csvに更新する
    kyouzaiDB_sort.to_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv", index = None, encoding="cp932")
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    number = kyouzaiDB_sort['Hpnumber']
    #Credibility_scoreの値がNaNのインデックスを取得し，リストに入れる．
    index = list(kyouzaiDB_sort.query(f'Credibility_score.isnull()',engine='python').index)
    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv", encoding="cp932")

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB_sort.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB_sort.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB_sort.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB_sort.iloc[index[i],1])
        #length.append(len(list(df.query(f'Hpnumber == "{a[i]}"').index)))
        length.append(len(list(df.query(f'Hpnumber == {number[i]}').index)))
    return(kyouzai_title_list,kyouzai_url_list,mihyouka_kyouzai_title_list,mihyouka_kyouzai_url_list,length)

def kousinn01(kyouzaiDB,Credibility_score,HPnumber,df,saveDB):
    #評価した教材のCredibility_scoreに，計算したCredibility_scoreを更新する
    kyouzaiDB.at[kyouzaiDB.query(f'Hpnumber == {HPnumber}').index[0],'Credibility_score'] = Credibility_score
    # Credibility_score順に並ぶ変える（高いスコアを一番上に）
    kyouzaiDB_sort = kyouzaiDB.sort_values('Credibility_score',ascending=False)
    #更新したkyouzaiDBをkyouzai.csvに更新する
    # kyouzaiDB_sort.to_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv", index = None, encoding="cp932")
    kyouzaiDB_sort.to_csv(saveDB, index = None, encoding="cp932")
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    number = kyouzaiDB_sort['Hpnumber']
    #Credibility_scoreの値がNaNのインデックスを取得し，リストに入れる．
    index = list(kyouzaiDB_sort.query(f'Credibility_score.isnull()',engine='python').index)
    #df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv", encoding="cp932")

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB_sort.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB_sort.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB_sort.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB_sort.iloc[index[i],1])
        #length.append(len(list(df.query(f'Hpnumber == "{a[i]}"').index)))
        length.append(len(list(df.query(f'Hpnumber == {number[i]}').index)))
    return(kyouzai_title_list,kyouzai_url_list,mihyouka_kyouzai_title_list,mihyouka_kyouzai_url_list,length)

# #video版のcsvの更新(英語文法のみ)
def video_kousinn(youtubeDB,Credibility_score,Youtubenumber):
    youtubeDB.at[youtubeDB.query(f'Youtubenumber == {Youtubenumber}').index[0],'Credibility_score'] = Credibility_score
    youtubeDB_sort = youtubeDB.sort_values('Credibility_score',ascending=False)
    youtubeDB_sort.to_csv('app/Kamoku/EigoBunnpou/Kyouzai/video_kyouzai.csv',index=None, encoding='utf_8_sig')
    video_title_list = []
    video_url_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    video_id_list = []
    mihyouka_video_id_list = []
    video_length = []
    a = youtubeDB_sort['Youtubenumber']
    print(type(Credibility_score))
    index = list(youtubeDB_sort.query(f'Credibility_score == "{np.nan}"').index)
    #index = list(youtubeDB_sort.query(f'Credibility_score.insull()').index)
    df = pd.read_csv('app/Kamoku/EigoBunnpou/Kyouzai/video_Review.csv',encoding='utf-8')

    for i in range(10):
        video_title_list.append(youtubeDB_sort.iloc[i,0])
        video_url_list.append(youtubeDB_sort.iloc[i,1])
        mihyouka_video_title_list.append(youtubeDB.iloc[index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iloc[index[i],1])
        video_id_list.append(youtubeDB_sort.iloc[i,3])
        mihyouka_video_id_list.append(youtubeDB_sort.iloc[index[i],3])
        video_length.append(len(list(df.query(f'Youtubenumber == {a[i]}').index)))
    return(video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length)

def video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB):
    youtubeDB.at[youtubeDB.query(f'Youtubenumber == {Youtubenumber}').index[0],'Credibility_score'] = Credibility_score
    youtubeDB_sort = youtubeDB.sort_values('Credibility_score',ascending=False)
    youtubeDB_sort.to_csv(save_videoDB,index=None, encoding='cp932')
    video_title_list = []
    video_url_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    video_id_list = []
    mihyouka_video_id_list = []
    video_length = []
    a = youtubeDB_sort['Youtubenumber']
    #index = list(youtubeDB_sort.query(f'Credibility_score == "{np.nan}"').index)
    #index = list(youtubeDB_sort.query(f'Credibility_score.insull()').index)
    index = list(youtubeDB_sort.query(f'Credibility_score.isnull()',engine='python').index)
    #df = pd.read_csv('app/Kamoku/EigoBunnpou/Kyouzai/video_Review.csv',encoding='utf-8')

    for i in range(10):
        video_title_list.append(youtubeDB_sort.iloc[i,0])
        video_url_list.append(youtubeDB_sort.iloc[i,1])
        mihyouka_video_title_list.append(youtubeDB.iloc[index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iloc[index[i],1])
        video_id_list.append(youtubeDB_sort.iloc[i,3])
        mihyouka_video_id_list.append(youtubeDB_sort.iloc[index[i],3])
        video_length.append(len(list(video_df.query(f'Youtubenumber == {a[i]}').index)))
    return(video_title_list, video_url_list, mihyouka_video_title_list, mihyouka_video_url_list, video_id_list, mihyouka_video_id_list, video_length)




# def Kyouzai_0_Review(studentnumber,hyouka,num,kyouzai):
#     kyouzaiDB = pd.read_csv(f'app/Kamoku/ComputerNetWork/Kyouzai/{kyouzai}',encoding = "shift-jis").drop(columns='評価')#csv読み込み
#     HPtitle = kyouzaiDB.iloc[:,0:1]
#     HPurl = kyouzaiDB.iloc[:,1:2]
#     kyouzaiDB = kyouzaiDB.drop(columns=['HPtitle','HPurl'])
#     #print(kyouzaiDB)
#     kyouzaiDB.iloc[num,kyouzaiDB.columns.get_loc(f'{int(studentnumber)}')] = hyouka #ユーザーが評価した値を代入
#     hyoukadf = kyouzaiDB.mean(axis=1)
#     kyouzaiDB['評価'] = hyoukadf
#     kyouzaiDB_sort = pd.concat([HPtitel,HPurl,kyouzaiDB],axis=1)
#     kyouzaiDB_sort = kyouzaiDB_sort.sort_values('評価',ascending=False)
#     kyouzaiDB_sort.to_csv(f'app/Kamoku/ComputerNetWork/Kyouzai/{kyouzai}',index=None)
#     video_kyouzaiDB = pd.read_csv('app/Kamoku/ComputerNetWork/Kyouzai/video_kyouzai_0.csv')
#     kyouzai_title_list = []
#     kyouzai_url_list = []
#     hyouka_list = []
#     video_kyouzai_title_list = []
#     video_kyouzai_url_list = []
#     video_kyouzai_id_list = []
#     for i in range(len(kyouzaiDB_sort.index)):
#         kyouzai_title_list.append(kyouzaiDB_sort.iloc[i,0])
#         kyouzai_url_list.append(kyouzaiDB_sort.iloc[i,1])
#         hyouka_list.append(kyouzaiDB_sort.at[kyouzaiDB_sort.index[i],'評価'])
#     for i in range(len(video_kyouzaiDB.index)):
#         video_kyouzai_title_list.append(video_kyouzaiDB.iloc[i,0])
#         video_kyouzai_url_list.append(video_kyouzaiDB.iloc[i,1])
#         video_kyouzai_id_list.append(video_kyouzaiDB.iloc[i,2])
#     mihyouka_kyouzai_title_list = []
#     mihyouka_kyouzai_url_list = []
#     mihyouka_kyouzai_title_list.append(kyouzaiDB_sort.iloc[-1]['HPtitle'])
#     mihyouka_kyouzai_url_list.append(kyouzaiDB_sort.iloc[-1]['HPurl'])
#     mihyouka_kyouzai_title_list.append(kyouzaiDB_sort.iloc[-2]['HPtitle'])
#     mihyouka_kyouzai_url_list.append(kyouzaiDB_sort.iloc[-2]['HPurl'])


#     return(kyouzai_title_list,kyouzai_url_list,mihyouka_kyouzai_title_list,mihyouka_kyouzai_url_list,
#     hyouka_list,video_kyouzai_title_list,video_kyouzai_url_list,video_kyouzai_id_list)