from os import name
import os
from flask import Flask, render_template, url_for, request, session, redirect
import pandas as pd
import csv
import numpy as np
from datetime import date, datetime
import datetime
from Recom import get_correlation_coefficents, rank_items, tannisyutoku, Similarity, Informative, Concentration, Credibility, kousinn,\
                  video_kousinn, Credibility_video, Video_Concentration, kousinn01, video_kousinn00, tannisyutoku0A, tannisyutoku0B,\
                  tannisyutoku0C, tannisyutoku0D, tannisyutoku1A, tannisyutoku1B, tannisyutoku1C, tannisyutoku2A,tannisyutoku2B,\
                  tannisyutoku3A, tannisyutoku4A, tannisyutoku4B, tannisyutoku5A, tannisyutoku5B, tannisyutoku5C, tannisyutoku6A,\
                  tannisyutoku6B, tannisyutoku6C, tannisyutoku6D, tannisyutoku6E, tannisyutoku6F
from hashlib import sha256
from model.models import Student
from model.database import db_session
import key
import requests
from bs4 import BeautifulSoup
import re
import urllib.parse

app = Flask(__name__)
app.secret_key = key.SECRET_KEY

teacher_df = pd.read_csv("Book1.csv",encoding="cp932", header=None)
kyouin = teacher_df[0].unique().tolist()

#最初のログイン画面（スタート画面）（最初にアクセスしたときに表示させる）
# ここでは，シラバス作成か，学生かを選択してもらう．
@app.route("/")
@app.route('/normal')
def normal():
    return render_template("normal.html")

@app.route('/teacher')
def teacher():
    return render_template('teacher.html', tantou_list = kyouin)

@app.route('/subject', methods=['GET', 'POST'])
def subject():
    tantou_name = request.form.get('tantousya')
    session['teacher'] = tantou_name

    df_tantou = teacher_df[teacher_df[0]==tantou_name]
    # 選択された名前の授業をリスト（kamoku）にいれる
    kamoku = df_tantou[1].tolist()

    return render_template('subject.html', tantou_name = tantou_name, kamoku = kamoku, name = tantou_name)

@app.route('/result', methods=['GET', 'POST'])
def result():
    #前ページで選択された教員の名前を保存（session['teacher]に）
    tantou_name = session['teacher']
    print(tantou_name)

    #選択された授業タイトル
    kamoku_name = request.form.get('tantou_subject')
    session['kamoku_name'] = kamoku_name
    print(kamoku_name)

    # 授業タイトルの英語版
    kamoku_eng = request.form.get('english_name')
    session['kamoku_eng'] = kamoku_eng

    # 科目区分
    subject_area = request.form.get('subject_area')
    session['subject_area'] = subject_area

    # 配当学年
    dividend_grade = request.form.get('dividend_grade')
    session['dividend_grade'] = dividend_grade

    # 職種
    occupation = request.form.get('occupation')
    session['occupation'] = occupation

    # 所属
    belong = request.form.get('belong')
    session['belong'] = belong

    # 開講学期
    semester = request.form.get('semester')
    session['semester'] = semester

    # 単位数
    units = request.form.get('units')
    session['units'] = units

    # 単位区分
    unit_area = request.form.get('unit_area')
    session['unit_area'] = unit_area

    # 関連する学習・教育目標
    educational_goal = request.form.get('educational_goal')
    session['educational_goal'] = educational_goal

    # 授業の目標/授業概要
    outline = request.form.get('outline')
    session['outline'] = outline

    # 学生の到達目標
    student_goal = request.form.get('student_goal')
    session['student_goal'] = student_goal

    #授業計画をリストで取得し，データフレームに
    text = request.form.getlist('item1')
    session['text'] = text
    # 授業計画の部分をデータフレームにする
    plan_df = pd.DataFrame(text)
    os.makedirs("csv_save", exist_ok=True)
    plan_df.to_csv("csv_save/"+kamoku_name+".csv", encoding='cp932', index=None,header=None)

    #キーワードをリストで取得し，データフレームに
    keyword = request.form.getlist('item2')
    true_keyword = list(filter(None, keyword))
    session['true_keyword'] = true_keyword
    # print(true_keyword)
    # key_df = pd.DataFrame(true_keyword)
    # df_key = key_df.to_html()

    # 成績評価基準
    evaluation = request.form.get('evaluation')
    session['evaluation'] = evaluation

    # 教科書・教材参考書等
    materials = request.form.get('materials')
    session['materials'] = materials

    # 関連科目・履修条件等
    requirements = request.form.get('requirements')
    session['requirements'] = requirements

    # 履修上の注意事項や学習上の助言
    notes = request.form.get('notes')
    session['notes'] = notes

    # 学生からの質問への対応方法
    responce = request.form.get('responce')
    session['responce'] = responce

    return render_template('syllabus.html', sub_name=kamoku_name,  teacher=tantou_name, kamoku_eng=kamoku_eng, subject_area=subject_area, dividend_grade=dividend_grade, occupation=occupation, belong=belong, semester=semester, units=units, unit_area=unit_area,\
                                            educational_goal=educational_goal,outline=outline, student_goal=student_goal, plan_df=text, keyword=true_keyword, evaluation=evaluation, materials=materials, requirements=requirements, notes=notes, responce=responce)


@app.route('/hozon', methods=['POST'])
def hozon():
    tantou_name = session['teacher']

    kamoku_name = session['kamoku_name']

    kamoku_eng = session['kamoku_eng']

    subject_area = session['subject_area']

    dividend_grade = session['dividend_grade']

    occupation = session['occupation']

    belong = session['belong']

    semester = session['semester']

    units = session['units']

    unit_area = session['unit_area']

    educational_goal = session['educational_goal']

    outline = session['outline']

    student_goal = session['student_goal']

    text = session['text']

    true_keyword = session['true_keyword']

    evaluation = session['evaluation']

    materials = session['materials']

    requirements = session['requirements']

    notes = session['notes']

    responce = session['responce']

    df_moto = pd.read_csv("moto_sylla.csv", encoding='cp932')
    df_moto.reset_index
    data_list = [kamoku_name, kamoku_eng, subject_area, dividend_grade, tantou_name, semester, units, unit_area, educational_goal, outline, student_goal, text, true_keyword, evaluation, materials, requirements, notes, responce]

    data_list[11] = '\n'.join(data_list[11])
    data_list[12] = ','.join(data_list[12])
    class_name = data_list[0]
    number = df_moto.index[df_moto['講義名称']==class_name][0]
    df_moto.loc[number,'講義名称']=data_list[0]
    df_moto.loc[number,"授業科目名（英語）"] = data_list[1]
    df_moto.loc[number,'科目区分'] = data_list[2]
    df_moto.loc[number,'配当学年'] = data_list[3]
    df_moto.loc[number,'代表教員名'] = data_list[4]
    df_moto.loc[number,'開講学期'] = data_list[5]
    df_moto.loc[number,'単位数'] = data_list[6]
    df_moto.loc[number,'単位区分'] = data_list[7]
    df_moto.loc[number,'関連する学習・教育目標'] = data_list[8]
    df_moto.loc[number,'授業の目標／授業概要'] = data_list[9]
    df_moto.loc[number,'学生の到達目標'] = data_list[10]
    df_moto.loc[number,'授業計画'] = data_list[11]
    df_moto.loc[number,'キーワード'] = data_list[12]
    df_moto.loc[number,'成績評価基準'] = data_list[13]
    df_moto.loc[number,'教科書・教材参考書等'] = data_list[14]
    df_moto.loc[number,'関連科目・履修条件等'] = data_list[15]
    df_moto.loc[number,'履修上の注意事項や学習上の助言'] = data_list[16]
    df_moto.loc[number,'学生からの質問への対応方法'] = data_list[17]

    df_moto.to_csv("syllabus.csv", encoding='cp932', index=False)

    ###################################################################
    # スクレイピングのところ
    os.makedirs("Tameshi", exist_ok=True)

    sub_title = pd.read_csv("csv_save/"+kamoku_name+".csv", encoding='cp932', header=None)
    sub_list =sub_title.iloc[:,0]
    # print(sub_list)

    hp_title = [[] for _ in range(len(sub_list))]
    hp_url = [[] for _ in range(len(sub_list))]

    for j in range(len(sub_list)):
        search_word = sub_list[j]
        pages_num = 15+1

        url = f'https://www.google.co.jp/search?hl=ja&num={pages_num}&q={search_word}'
        request =requests.get(url)

        soup = BeautifulSoup(request.text, 'html.parser')
        search_Results = soup.select('.kCrYT > a')
        search_title = soup.select('.BNeawe.vvjwJb.AP7Wnd')

        for i in range(len(sub_list)):
            #なんか変な文字が入るので除く       
            site_url = str(search_Results[i].get('href').split('&sa=U&')[0].replace('/url?q=', ''))
            #URLに日本語が含まれている場合、エンコードされているのでデコードする
            site_url = urllib.parse.unquote(urllib.parse.unquote(site_url))
        
            #いらない文字を削除
            site_title = str(search_title[i]).strip('<div class="BNeawe vvjwJb AP7Wnd">').strip('</')
            #URLに日本語が含まれている場合、エンコードされているのでデコードする
            site_title = urllib.parse.unquote(urllib.parse.unquote(site_title))
            
            #print(site_title)
            hp_title[j].append(site_title)
            hp_url[j].append(site_url)
        
        for i in range(len(sub_list)):
            df = pd.DataFrame({'HPtitle':hp_title[j],'HPurl':hp_url[j]})
            df.to_csv(f'Tameshi/kyouzai_{i}.csv',index=None,encoding='utf-8-sig')
    ###################################################################

    # こっちはhtmlで保存するようにする
    # 入力された状態のhtmlを html にいれる．
    html = render_template('true_syllabus.html', sub_name=kamoku_name,  teacher=tantou_name, kamoku_eng=kamoku_eng, subject_area=subject_area, dividend_grade=dividend_grade, occupation=occupation, belong=belong, semester=semester, units=units, unit_area=unit_area,\
                                            educational_goal=educational_goal,outline=outline, student_goal=student_goal, plan_df=text, keyword=true_keyword, evaluation=evaluation, materials=materials, requirements=requirements, notes=notes, responce=responce)
    
    os.makedirs("html_save", exist_ok=True)
    # 上で作成した html を aiueo.html という名前で保存する．（このaiueo.htmlを科目名に変更するかどうか）
    with open("html_save/aiueo.html",mode="w",encoding="utf-8") as f:
        f.write(str(html))

    return render_template('teacher.html', tantou_list = kyouin)



# start.html は学生用のログイン画面
@app.route("/start")
def start():
   status = request.args.get("status")
   return render_template("start.html",status=status)

#ログインするときに行う部分（データベースに登録されているかどうかの確認）
# 登録してあれば，推薦．　してないと，新規登録をしてもらうようにする．
@app.route("/login", methods=["POST"])
def login():
    user_name = request.form.get("user_name")
    password = request.form["password"]
    if len(user_name) == 0 or len(password) == 0:
        return redirect(url_for("start", status="no_text"))
    hashed_password = sha256((user_name + password + key.SALT).encode("utf-8")).hexdigest()
    
    user_found = False
    with open('user.csv','r') as check_file:
        reader = csv.reader(check_file)
        for row in reader:
            if row[0] == user_name:
                if row[1] == hashed_password:
                    session['user_name'] = user_name
                    user_found = True
                    break
                else:
                    user_found = True
                    status = "wrong_password"
                    break

    if user_found == True:
        return redirect(url_for('top'))
    else:
        status = "user_notfound"
        return redirect(url_for('start', status = status))

    # with open(file_path+'user.csv','r') as check_file:
    #     reader = csv.reader(check_file)
    #     if any([row[0] == user_name for row in reader]):
    #         if any(row[1] == hashed_password for row in reader]):
    
    # else:
    #     user_name = request.form.get("user_name")
    #     password = request.form["password"]
    #     hashed_password = sha256((user_name + password + key.SALT).encode("utf-8")).hexdigest()
    #     with open('user.csv','r') as check_file:
    #         reader = csv.reader(check_file)
    #         for row in reader:
                # if row[0] == user_name and row[1] == hashed_password:
                #     session['user_name'] = user_name
                #     return redirect(url_for('top'))
                # elif row[0] == user_name and row[1] != hashed_password:
                #     return redirect(url_for('start', status = "wrong_password"))
                # elif row[0] != user_name:
                #     return redirect(url_for('start', status = "user_notfound"))

                # row[0]が学籍番号，row[1]がハッシュ化パスワード
                # if user_name in row:
                #     print("存在します")
                #     if row[1] == hashed_password:
                #         session['user_name'] = user_name
                #         return redirect(url_for('top'))
                #     else:
                #         return redirect(url_for('start', status = "wrong_password"))
                
                # else:
                #     return redirect(url_for('start', status = "user_notfound"))


    #DB使う版
#    user_name = request.form["user_name"]
#    user = Student.query.filter_by(user_name=user_name).first()
#    if user:
#       password = request.form["password"]
#       hashed_password = sha256((user_name + password + key.SALT).encode("utf-8")).hexdigest()
#       if user.hashed_password == hashed_password:
#          session["user_name"] = user_name
#          # topのところに app.py の index 部分をいれる
#          return redirect(url_for("top"))
#       else:
#          return redirect(url_for("start",status="wrong_password"))
#    else:
#       return redirect(url_for("start",status="user_notfound"))

#新規登録のところ（GET）
@app.route("/newcomer")
def newcomer():
   status = request.args.get("status")
   return render_template("newcomer.html",status=status)

# 学籍番号，パスワードが入力されていないと 入力してください を返すようにする（POST）
@app.route("/registar", methods=["POST"])
def registar():
    user_name = request.form.get("user_name")
    password = request.form["password"]
    if len(user_name) == 0 or len(password) == 0:
        return redirect(url_for("newcomer", status="no_text"))
    hashed_password = sha256((user_name + password + key.SALT).encode("utf-8")).hexdigest()
    user_set = [user_name, hashed_password]
    # with open('user.csv', 'r') as check_file:
    #     reader = csv.reader(check_file)
    #     if any([row[0] == user_name for row in reader]):
    #         return redirect(url_for("newcomer", status="exist_user"))
    with open("user.csv", 'a', encoding="cp932") as user_file:
        writer = csv.writer(user_file)
        writer.writerow(user_set)
        session['user_name'] = user_name
    return redirect(url_for("get"))

    # DB使う版
    #   user = Student.query.filter_by(user_name=user_name).first()
    #   if user:
    #      # ユーザが登録されていたら，index部分に飛ばすようにするかも
    #      return redirect(url_for("newcomer",status="exist_user"))
    #   else:
    #      if len(request.form["password"]) == 0:
    #         #パスワードが空白の場合書き直す
    #         return redirect(url_for("newcomer", status="no_text"))
    #      else:   
    #         password = request.form["password"]
    #         hashed_password = sha256((user_name + password + key.SALT).encode("utf-8")).hexdigest()
    #         user = Student(user_name, hashed_password)
    #         print(user)
    #         try:
    #            db_session.add(user)
    #            db_session.commit()
    #         except:
    #            db_session.rollback()
    #         session["user_name"] = user_name
    #         return redirect(url_for("get"))

# ログアウト用
@app.route("/logout")
def logout():
   session.pop("user_name", None)
   return redirect(url_for("start",status="logout"))
      

# 成績入力させるところ (GET)
@app.route('/get',methods=['GET'])
def get():
   if "user_name" in session:
      name = session["user_name"]
      return render_template('grade_entry.html', title = '成績チェック(GET)', name = name, message='成績入力部分')
   else:
      return redirect(url_for("start", status = "logout"))

# 成績，希望業種を入力（POST）
@app.route('/touroku', methods=['POST'])
def touroku():
    #リストを初期化することで，csvに追記する際に新しくする
    name = session["user_name"]
    usr_grade=[]

    edu1 = request.form.get('edu1'); edu2 = request.form.get('edu2'); eco1 = request.form.get('eco1'); soc1 = request.form.get('soc1'); law1 = request.form.get('law1'); sci_tech = request.form.get('sci_tech')

    env1 = request.form.get('env1'); japanese = request.form.get('japanese');compare1 = request.form.get('compare1'); health_sci_exe = request.form.get('health_sci_exe'); psycho1 = request.form.get('psycho1'); health_sci1 = request.form.get('health_sci1')

    math1 = request.form.get('math1'); math2 = request.form.get('math2'); psy1 = request.form.get('psy1'); psy2 = request.form.get('psy2'); chemi1 = request.form.get('chemi1'); chemi2 = request.form.get('chemi2')

    biology = request.form.get('biology'); phy1_exe = request.form.get('phy1_exe'); math_exe = request.form.get('math_exe'); chemi_exp = request.form.get('chemi_exp'); phy_exp = request.form.get('phy_exp'); ba_eng1 = request.form.get('ba_eng1')

    ba_eng2 = request.form.get('ba_eng2'); ba_eng3 = request.form.get('ba_eng3'); ba_eng4 = request.form.get('ba_eng4'); german1 = request.form.get('german1'); german2 = request.form.get('german2'); china1 = request.form.get('china1')

    china2 = request.form.get('china2'); career = request.form.get('career'); algebra1 = request.form.get('algebra1') ;algebra2 = request.form.get('algebra2'); info_math1 = request.form.get('info_math1'); info_math2 = request.form.get('info_math2')

    pro_stat = request.form.get('pro_stat'); complex_ana = request.form.get('complex_ana'); intro_info_sys = request.form.get('intro_info_sys'); com_base = request.form.get('com_base'); programming1 = request.form.get('programming1'); programming1_exe = request.form.get('programming1_exe')

    algo_data = request.form.get('algo_data'); electric_circuit = request.form.get('electric_circuit'); eco2 = request.form.get('eco2') ;soc2 = request.form.get('soc2'); law2 = request.form.get('law2'); env2 = request.form.get('env2')

    comm_logic = request.form.get('comm_logic'); litera1 = request.form.get('litera1'); compare2 = request.form.get('compare2'); psycho2 = request.form.get('psycho2'); ethics = request.form.get('ethics'); philo = request.form.get('philo')

    compre_eng1 = request.form.get('compre_eng1'); compre_eng2 = request.form.get('compre_eng2'); compre_eng3 = request.form.get('compre_eng3'); compre_eng4 = request.form.get('compre_eng4'); topic_semi1 = request.form.get('topic_semi1'); topic_semi2 = request.form.get('topic_semi2')

    diff_equ = request.form.get('diff_equ'); fourier = request.form.get('fourier'); info_theory = request.form.get('info_theory'); DSP = request.form.get('DSP'); elec_circuit = request.form.get('elec_circuit'); logic_circuit_base = request.form.get('logic_circuit_base')

    info_sys_exp1 = request.form.get('info_sys_exp1'); programming2 = request.form.get('programming2'); programming2_exe = request.form.get('programming2_exe'); programming3 = request.form.get('programming3'); programming3_exe = request.form.get('programming3_exe'); com_archi = request.form.get('com_archi')

    compiler = request.form.get('compiler'); com_net = request.form.get('com_net'); iot_sys = request.form.get('iot_sys'); commu_method = request.form.get('commu_method'); data_data = request.form.get('data_data'); image_processing = request.form.get('image_processing')

    const_japan = request.form.get('const_japan'); tech_soc = request.form.get('tech_soc'); toyama_japan = request.form.get('toyama_japan'); litera2 = request.form.get('litera2'); modern_his = request.form.get('modern_his'); inter_rela = request.form.get('inter_rela')

    comm_soc = request.form.get('comm_soc'); health_sci2 = request.form.get('health_sci2'); spe_eng1 = request.form.get('spe_eng1'); spe_eng2 = request.form.get('spe_eng2'); spe_eng3 = request.form.get('spe_eng3'); spe_eng4 = request.form.get('spe_eng4')

    presen = request.form.get('presen'); engi_ethic = request.form.get('engi_ethic'); business_manage = request.form.get('business_manage'); interA = request.form.get('interA'); interB = request.form.get('interB'); tech_eng = request.form.get('tech_eng')

    spe_info_sys = request.form.get('spe_info_sys'); info_sys_exp2 = request.form.get('info_sys_exp2'); grad_research1 = request.form.get('grad_research1'); iot_prog = request.form.get('iot_prog'); logic_circuit_app = request.form.get('logic_circuit_app'); embedded = request.form.get('embedded')

    prog_lan = request.form.get('prog_lan'); queueing = request.form.get('queueing'); soft_engi = request.form.get('soft_engi'); opera_sys = request.form.get('opera_sys'); hum_inter = request.form.get('hum_inter'); bioinfo = request.form.get('bioinfo')

    machine_learning = request.form.get('machine_learning'); nume_ana = request.form.get('nume_ana'); ope_sys = request.form.get('ope_sys'); info_global = request.form.get('info_global'); grad_research2 = request.form.get('grad_research2')

    # 就職希望の部分
    hope = request.form.get('industry_hope')

    usr_grade.extend([name, 
                        edu1, edu2, eco1, soc1, law1, sci_tech,
                        env1, japanese, compare1, health_sci_exe, psycho1, health_sci1,
                        math1, math2, psy1, psy2, chemi1, chemi2,
                        biology, phy1_exe, math_exe, chemi_exp, phy_exp, ba_eng1,
                        ba_eng2, ba_eng3, ba_eng4, german1, german2, china1,
                        china2, career, algebra1, algebra2, info_math1, info_math2,
                        pro_stat, complex_ana, intro_info_sys, com_base, programming1, programming1_exe,
                        algo_data, electric_circuit, eco2, soc2, law2, env2,
                        comm_logic, litera1, compare2, psycho2, ethics, philo,
                        compre_eng1, compre_eng2, compre_eng3, compre_eng4, topic_semi1, topic_semi2,
                        diff_equ, fourier, info_theory, DSP, elec_circuit, logic_circuit_base,
                        info_sys_exp1, programming2, programming2_exe, programming3, programming3_exe, com_archi,
                        compiler, com_net, iot_sys, commu_method, data_data, image_processing,
                        const_japan, tech_soc, toyama_japan, litera2, modern_his, inter_rela,
                        comm_soc, health_sci2, spe_eng1, spe_eng2, spe_eng3, spe_eng4,
                        presen, engi_ethic, business_manage, interA, interB, tech_eng,
                        spe_info_sys, info_sys_exp2, grad_research1, iot_prog, logic_circuit_app, embedded,
                        prog_lan, queueing, soft_engi, opera_sys, hum_inter, bioinfo,
                        machine_learning, nume_ana, ope_sys, info_global, grad_research2, hope])

    #入力されたデータを data.csv ファイルに保存する．
    with open('data.csv','a',encoding='cp932',newline='\n') as file:
        writer = csv.writer(file)
        writer.writerow(usr_grade)
    return redirect(url_for("top"))
    
    #    return render_template('grade_entry.html', title ='成績チェック(POST)', name = name, message ='入力ありがとう')



@app.route('/top')
def top():
   if "user_name" in session:
      # 入力された学籍番号を name に入れておく（文字列）
      name = session["user_name"]
      session['user'] = name

      # 業種ありのものを，業種部分削って結合する（フラグ部分はまだ実装していない）
      nondel_data2017 = pd.read_csv("kai_2017_04.csv", encoding="cp932")
      nondel_data2017 = nondel_data2017.drop(nondel_data2017.columns[-1], axis=1)
      nondel_data2018 = pd.read_csv("kai_2018_04.csv", encoding="cp932").drop([0, 1, 2])#dropで必要のない行を削除する
      nondel_data2018 = nondel_data2018.drop(nondel_data2018.columns[-1], axis=1)
      nondel_data2019 = pd.read_csv("kai_2019_04.csv", encoding="cp932").drop([0, 1, 2])#dropで必要のない行を削除する
      nondel_data2019 = nondel_data2019.drop(nondel_data2019.columns[-1], axis=1)
      # 3年分合わせたデータ（上から古い学籍番号の人）
      nondel_data_all = pd.concat([nondel_data2017, nondel_data2018, nondel_data2019], axis=0, sort = False).drop('学籍番号', axis=1)

      # 必選別，単位数，配当学年を削ったやつ
      data2017 = pd.read_csv('kai_2017_04.csv', encoding='cp932').drop([0, 1, 2])
      data2018 = pd.read_csv('kai_2018_04.csv', encoding='cp932').drop([0, 1, 2])
      data2019 = pd.read_csv('kai_2019_04.csv', encoding='cp932').drop([0, 1, 2])

      # 過去の学生のデータ(今回は2017年と2018年の2年分)，2018と2017年のデータを縦に連結する
      data_kako = pd.concat([data2017, data2018, data2019], axis=0, sort = False)

      # ユーザが成績入力した際に出力される csvファイル
      user_data = pd.read_csv("data.csv",encoding="cp932", header=None)

      # 入力された学籍番号と成績・希望業種データを抽出
      data_ima = user_data[user_data[0].isin([int(name)])]
      data_ima.columns = data_kako.columns

      # 入力したユーザの希望業種の数値を抽出する
      industry = data_ima.iat[-1,-1]

      # ユーザの希望業種に応じて，それと同じ学生のデータを使用する
      if industry == 1:
         data_kako = data_kako[data_kako.loc[:,"業種"]==1]
      elif industry == 2:
         data_kako = data_kako[data_kako.loc[:,"業種"]==2]
      elif industry == 3:
         data_kako = data_kako[data_kako.loc[:,"業種"]==3]
      elif industry == 4:
         data_kako = data_kako[data_kako.loc[:,"業種"]==4]
      elif industry == 5:
         data_kako = data_kako[data_kako.loc[:,"業種"]==5]
      elif industry == 6:
         data_kako = data_kako[data_kako.loc[:,"業種"]==6]
      elif industry == 7:
         data_kako = data_kako[data_kako.loc[:,"業種"]==7]
      elif industry == 8:
         data_kako = data_kako[data_kako.loc[:,"業種"]==8]
      elif industry == 0:
         pass   
      
      # 過去の学生データとユーザのデータを結合（ユーザデータは一番上）
      data_gutya = pd.concat([data_ima, data_kako], axis=0, sort=False)  # 学籍番号付きのデータ

      # 列名指定で 業種 列を削除（最終列）
      # data_gutya.drop("業種", axis=1)

      # 名前指定じゃなくて最終列指定で削除
      data_gutya = data_gutya.drop(data_gutya.columns[-1],axis=1)

      # 学籍番号とってNaNを-1埋めしたデータ （履修していない科目に -1 を入れる）
      data_all = data_gutya.reset_index(drop=True).drop('学籍番号', axis=1).fillna(-1)  

      # いったんnumpyに（data_allの中身を）
      data_all_np = data_all.values

      #上のやつのコピーを data_all_calc に入れる
      data_all_calc = data_all_np.copy()

      #data_all_calcの-1以外のものを全て0に書き換える（履修した科目のものを 0 にして，履修していないものに -1 をいれている状態）
      data_all_calc[data_all_calc != -1] = 0

      # np.abs(data_all_cals)で data_all_calcの絶対値をとる．（ -1 → 1 になる →　履修していないものに 1 が立つようになる）
      # columnsには授業名を入れる
      # それらをデータフレームにして，data_train にいれる
      data_train = pd.DataFrame(np.abs(data_all_calc), columns=data_all.columns)

      #対象ユーザの部分を取得する（data_train_user にいれる）
      data_train_user = data_train[:1]

      # 科目数分繰り返す
      # 対象ユーザーの落単科目（data_all.iloc[0,i] == 0）に対して，0 を 1 に変える
      #　　→未履修科目と落単科目に対して 1 を立て，履修済み科目に対しては 0 を立てる
      for i in range(len(data_all.columns)):
         if data_all.iloc[0, i] == 0:
            data_train_user = data_train_user.replace({f'{data_train_user.columns[i]}': {0: 1}})
      
      # 区分のリスト
      df4 = ["0A", "0A", "0B", "0B", "0B", "0B", "0B", "0C", "0C", "0D", "0D", "0D", "1A", "1A", "1A", "1A", "1B", "1B", "1B", "1A", "1C",
            "1C", "1A", "2A", "2A", "2A", "2A", "2B", "2B", "2B", "2B", "3A", "4A", "4A", "4A", "4A", "4A", "4A", "4B", "5A", "5A", "5A",
            "5B", "5C", "0B", "0B", "0B", "0B", "0C", "0C", "0C", "0D", "0D", "0D", "2A", "2A", "2A", "2A", "3A", "3A", "4A", "4A", "5B",
            "5B", "5C", "5C", "5D", "6A", "6A", "6A", "6A", "6B", "6B", "6C", "6C", "6C", "6D", "6E", "0B", "0B", "0B", "0C", "0C", "0C",
            "0D", "0D", "2A", "2A", "2A", "2A", "3A", "3A", "3A", "3A", "3A", "3A", "5D", "5D", "5D", "6A", "6B", "6B", "6B", "6C", "6D",
            "6D", "6E", "6E", "6F", "6F", "6F", "6F", "5D"]

      # zero：総合科目
      zero = 19; zeroA = 2; zeroB = 2; zeroC = 2; zeroD = 2
      # iti：基礎科目
      iti = 13; itiA = 10; itiB = 2; itiC = 1
      # ni：外国語科目
      ni = 12; niA = 10; niB = 2
      # kyouyou：教養全体 ＝ 44
      kyouyou = zero + iti + ni
      # sann：キャリア形成科目
      sannA = 7
      # senmon：卒業研究２を除いた専門科目
      senmon = 71
      # yonn：専門基礎科目
      yonnA = 10; yonnB = 2
      # go：専門共通科目
      goA = 5; goB = 4; goC = 4; goD = 8
      # roku：専門科目
      rokuA = 5; rokuB = 6; rokuC = 4; rokuD = 2; rokuE = 2; rokuF = 4
      # sotuken：卒業研究２
      sotuken = 8
      # senmon_all：専門全部で必要な単位数 = 79
      senmon_all =senmon + sotuken 
      # all_all：全体の単位数
      all_all = 140

      zero_sum = 0; zeroA_sum = 0; zeroB_sum = 0 ; zeroC_sum = 0; zeroD_sum = 0
      iti_sum = 0; itiA_sum = 0; itiB_sum = 0; itiC_sum = 0
      niA_sum = 0; niB_sum = 0
      sannA_sum = 0
      yonnA_sum = 0; yonnB_sum = 0
      goA_sum = 0; goB_sum = 0; goC_sum = 0; goD_sum = 0
      rokuA_sum = 0; rokuB_sum = 0; rokuC_sum = 0; rokuD_sum = 0; rokuE_sum = 0; rokuF_sum = 0

      #現在の単位数を確認
      for i in range(len(data_train_user.columns)):
      # 履修済みor推薦済みの時（data_train_user.iloc[0,i] == 0）
      # nodel_data_all.iloc[2,i] は取得できる単位数が入っている
         if data_train_user.iloc[0,i] == 0:
            if df4[i] == '0A':
                  zeroA_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '0B':
                  zeroB_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '0C':
                  zeroC_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '0D':
                  zeroD_sum += nondel_data_all.iloc[2,i] 
            elif df4[i] == '1A':
                  itiA_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '1B':
                  itiB_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '1C':
                  itiC_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '2A':
                  niA_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '2B':
                  niB_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '3A':
                  sannA_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '4A':
                  yonnA_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '4B':
                  yonnB_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '5A':
                  goA_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '5B':
                  goB_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '5C':
                  goC_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '5D':
                  goD_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '6A':
                  rokuA_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '6B':
                  rokuB_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '6C':
                  rokuC_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '6D':
                  rokuD_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '6E':
                  rokuE_sum += nondel_data_all.iloc[2,i]
            elif df4[i] == '6F':
                  rokuF_sum += nondel_data_all.iloc[2,i]
            else:
                  pass
         else:
            pass

      all_sum = zeroA_sum + zeroB_sum + zeroC_sum +zeroD_sum + itiA_sum +itiB_sum + itiC_sum + niA_sum + niB_sum +\
                  sannA_sum + yonnA_sum + yonnB_sum + goA_sum + goB_sum + goC_sum + rokuA_sum + rokuB_sum + rokuC_sum +\
                     rokuD_sum + rokuE_sum + rokuF_sum
      
      # 現在の取得単位数を now_all_sum にコピーする
      now_all_sum = all_sum.copy()

      # 0番目のユーザ(対象ユーザ)
      target_user_index = 0 

      # Person関数で指定した学生とすべての学生の類似度を算出する
      # 学籍番号とってNaNを-1埋めしたデータ （履修していない科目に -1 を入れる）と target_user_index を使用する
      similarities = get_correlation_coefficents(data_all_np, target_user_index)

      # 予測評価値をもとにランキング(予測評価値も求める)
      rank = rank_items(data_all_np, similarities, target_user_index)

      # rank（予測評価値をもとにランキングしたもの）をデータフレームにする（index と predict を columns にする）
      rank_df = pd.DataFrame(rank,columns=['index','predict'])

      # rank_df の index部分を科目名に変化させる
      for i in range(len(rank_df.index)):
         rank_df = rank_df.replace({'index':{rank_df.iloc[i,0]:data_all.columns[rank_df.iloc[i,0]]}})

      mirisyuu_list = []#まだ履修していない科目リスト(予測評価順)
      for i in range(len(rank)):
         mirisyuu_list.append(data_all.columns[rank[i][0]])
      # print(mirisyuu_list)
         
      suisennkamoku = []#情報推薦する科目一覧
      #とりあえず必修科目と予測評価値が3以上の科目は推薦リストに追加
      for i in range(len(rank)): 
         #nondel_data_all.iloc[0,rank[i][0]] == 1 は必選別で１のもの（必修の科目）
         if nondel_data_all.iloc[0,rank[i][0]] == 1:
            suisennkamoku.append(mirisyuu_list[i])
         elif rank[i][1] >= 3:
            suisennkamoku.append(mirisyuu_list[i])
         else:
            pass

      #推薦科目として提示した科目を未履修リストから削除
      for i in range(len(suisennkamoku)):
         mirisyuu_list.remove(suisennkamoku[i])    

      #落胆した科目を未履修リストの最後尾に追加
      for i in range(len(data_all.columns)):
         #ここは落単した科目を mirisyuu_listに追加する
         if data_all.iloc[target_user_index,i] == 0:
            mirisyuu_list.append(data_all.columns[i])

      # 取得済み or 推薦済み の科目に0が入った配列
      for i in range(len(suisennkamoku)):
         data_train_user = data_train_user.replace({f'{suisennkamoku[i]}':{1:0}})
      
      all_sum=tannisyutoku0A(zeroA_sum, zeroA, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku0B(zeroB_sum, zeroB, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku0C(zeroC_sum, zeroC, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku0D(zeroD_sum, zeroD, data_all,rank, suisennkamoku, nondel_data_all ,all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku1A(itiA_sum, itiA, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku1B(itiB_sum, itiB, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku1C(itiC_sum, itiC, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku2A(niA_sum, niA, data_all, rank, suisennkamoku,nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku2B(niB_sum, niB, data_all, rank, suisennkamoku,nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku3A(sannA_sum, sannA, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku4A(yonnA_sum, yonnB, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku4B(yonnB_sum, yonnB, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku5A(goA_sum, goA, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku5B(goB_sum, goB, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku5C(goC_sum, goC, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku6A(rokuA_sum, rokuA, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku6B(rokuB_sum, rokuB, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku6C(rokuC_sum, rokuC, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku6D(rokuD_sum, rokuD, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku6E(rokuE_sum, rokuE, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)
      all_sum=tannisyutoku6F(rokuF_sum, rokuF, data_all, rank, suisennkamoku, nondel_data_all, all_sum, df4, mirisyuu_list)

      #推薦科目として提示した科目を未履修リストから削除
      for i in range(len(suisennkamoku)):
         try:
            mirisyuu_list.remove(suisennkamoku[i])
         except ValueError:
            i += 1
         #print(mirisyuu_list)

      #取得済みor推薦済みの科目に0が入った配列
      for i in range(len(suisennkamoku)):
         data_train_user = data_train_user.replace({f'{suisennkamoku[i]}':{1:0}})

      #この時点で取得予定単位数が卒業要件単位を満たしていなければ,suisennkamokuにmirisyuu_listを追加していく（上から）
      # それを，all_sum が all_all を超えるまで続ける
      if all_sum < all_all:
         i = 0
         while all_sum < all_all:
            suisennkamoku.append(mirisyuu_list[i])
            all_sum += nondel_data_all.iloc[2,data_all.columns.get_loc(f'{mirisyuu_list[i]}')]
            i += 1

      suisenn_10 = []
      suisenn_11 = []
      suisenn_20 = []
      suisenn_21 = []
      suisenn_30 = []
      suisenn_31 = []
      suisenn_40 = []
      
      for i in range(len(suisennkamoku)):
         # suisennkamokuの科目の配当学年が 10 のとき，suisenn_10 に suisennkamoku の科目を追加する
         if nondel_data_all.iloc[1,data_all.columns.get_loc(f'{suisennkamoku[i]}')] == 10:
            suisenn_10.append(suisennkamoku[i])
         # suisennkamokuの科目の配当学年が 11 のとき，suisenn_11 に suisennkamoku の科目を追加する
         elif nondel_data_all.iloc[1,data_all.columns.get_loc(f'{suisennkamoku[i]}')] == 11:
            suisenn_11.append(suisennkamoku[i])
         # suisennkamokuの科目の配当学年が 20 のとき，suisenn_20 に suisennkamoku の科目を追加する
         elif nondel_data_all.iloc[1,data_all.columns.get_loc(f'{suisennkamoku[i]}')] == 20:
            suisenn_20.append(suisennkamoku[i])
         # suisennkamokuの科目の配当学年が 21 のとき，suisenn_21 に suisennkamoku の科目を追加する
         elif nondel_data_all.iloc[1,data_all.columns.get_loc(f'{suisennkamoku[i]}')] == 21:
            suisenn_21.append(suisennkamoku[i])
         # suisennkamokuの科目の配当学年が 30 のとき，suisenn_30 に suisennkamoku の科目を追加する
         elif nondel_data_all.iloc[1,data_all.columns.get_loc(f'{suisennkamoku[i]}')] == 30:
            suisenn_30.append(suisennkamoku[i])
         # suisennkamokuの科目の配当学年が 31 のとき，suisenn_31 に suisennkamoku の科目を追加する
         elif nondel_data_all.iloc[1,data_all.columns.get_loc(f'{suisennkamoku[i]}')] == 31:
            suisenn_31.append(suisennkamoku[i])
         # suisennkamokuの科目の配当学年が 40 のとき，suisenn_40 に suisennkamoku の科目を追加する
         elif nondel_data_all.iloc[1,data_all.columns.get_loc(f'{suisennkamoku[i]}')] == 40:
            suisenn_40.append(suisennkamoku[i])
         else:
            pass

      # list型
      suisenn_all = suisenn_10 + suisenn_11 + suisenn_20 + suisenn_21 + suisenn_30 +suisenn_31 + suisenn_40
      print(len(suisenn_all))
      # list → データフレーム
    #   suisenn_all_df = pd.DataFrame(suisenn_10 + suisenn_11 + suisenn_20 + suisenn_21 + suisenn_30 +suisenn_31 + suisenn_40)
            
      suisenn_all_url = []
      suisenn_all_name  = []

      for i in range(len(suisenn_all)):
         if suisenn_all[i] == ('IoTシステムデザイン'):
            suisenn_all_name.append('IoTシステムデザイン')
            suisenn_all_url.append('IoTsystem')
            
\
            
         else:
            pass

      # index.htmlに表示する部分を設定する
      data_html = user_data[user_data[0].isin([int(name)])]
      data_html.columns = data_kako.columns
      data_html = data_html.drop(data_html.columns[-1], axis=1)
      data_html = data_html.replace({-1:"履修なし", 0: "落単or不可", 1:"C", 2:"B", 3:"A", 4:"S"})
      user_T = data_html.T
      
      # df_Tには data.csvから対象のユーザのデータを変換し，転置したもの
      return render_template("index.html", name=name, data = user_T.to_html(header=None),\
                              suisenn_all_url = suisenn_all_url, suisenn_all_name = suisenn_all_name)
   else:
      return redirect(url_for('start'))



#######################################################################################################
#############################################IoTシステムデザイン########################################
#######################################################################################################
@app.route("/IoTsystem")
def IoTsystem():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []

    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    return render_template('/IoTシステムデザイン/IoTsystem_syr.html', 
                            key_word1 = keyword[0],
                            key_word2 = keyword[1],
                            key_word3 = keyword[2],
                            key_word4 = keyword[3]
                            )

###########キーワード1つ目########################
#################################################
@app.route("/IoTsystem01")
def IoTsystem01():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])
    
    #HP
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv",encoding="cp932")

    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []

    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    number = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{number[i]}"').index)))
    
    update_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv", encoding="cp932")
    score_list=[]
    #Credibility_scoreをscore_listに追加する（上から３つ）
    for i in range(3):
        score_list.append(update_df.iat[i,3])
    

    #youtubeについて
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding='cp932')
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_Review.csv',encoding='cp932')

    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']

    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))

    video_update_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_update_df.iat[i,4])


    return render_template("/IoTシステムデザイン/IoTsystem01.html", title= keyword[0],
            kyouzai_title1 = kyouzai_title_list[0], kyouzai_url1 = kyouzai_url_list[0],
            kyouzai_title2 = kyouzai_title_list[1], kyouzai_url2 = kyouzai_url_list[1],
            kyouzai_title3 = kyouzai_title_list[2], kyouzai_url3 = kyouzai_url_list[2],
            mihyouka_title1 = mihyouka_kyouzai_title_list[0], mihyouka_url1 = mihyouka_kyouzai_url_list[0],
            mihyouka_title2 = mihyouka_kyouzai_title_list[1], mihyouka_url2 = mihyouka_kyouzai_url_list[1],
            mihyouka_title3 = mihyouka_kyouzai_title_list[2], mihyouka_url3 = mihyouka_kyouzai_url_list[2],
            length1 = length[0], length2=length[1], length3=length[2],
            video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
            video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
            video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
            mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
            mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
            mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
            mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
            video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
            score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
            video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
            )

@app.route('/IoTsystem01_Review',methods = ["post"])
def IoTsystem01_Review():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv', encoding="cp932")
    number = int(request.form['number'])
    HPnumber = kyouzaiDB.iloc[number,2]
    HPtitle = kyouzaiDB.iloc[number,0]
    HPurl = kyouzaiDB.iloc[number,1]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #レビューした学籍番号を取得
    #studentnumber = session["user"]
    studentnumber = "2155016"

    #レビューした日付と時間を取得する
    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    #date = dtt.strftime("%Y/%#m/$#d %H:%M") 
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    #上で取得したデータを review_list に保存する
    review_list = [HPtitle, HPurl, HPnumber, studentnumber, evaluation, text, date]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv","a",encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_list)

    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv",encoding="cp932")
    saveDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv"

    S_score_norm = Similarity(df)
    I_score_norm = Informative(df)
    C_score_norm = Concentration(df)  
    Credibility_score, Ave_score = Credibility(S_score_norm, I_score_norm, C_score_norm, HPnumber, df)
    review_score = [HPtitle, HPurl, HPnumber, studentnumber, evaluation, text, date, Credibility_score, Ave_score]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_score.csv", "a", encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)

    #Youtube
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding="cp932")
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_Review.csv',encoding='cp932')
    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']
    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))


    kyouzai_title_list, kyouzai_url_list, mihyouka_kyouzai_title_list, mihyouka_kyouzai_url_list, length =\
         kousinn01(kyouzaiDB, Credibility_score, HPnumber,df,saveDB)
    kousinn_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv",encoding="cp932")
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])

    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem01.html",title = keyword[0],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0], mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1], mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2], mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0], length2=length[1], length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3S = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )

@app.route("/IoTsystem01_mihyouka_Review", methods=["POST"])
def IoTsystem01_mihyouka_Review():
    ##キーワード取得のための部分##
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])
    ############################

    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv', encoding="cp932")
    number = int(request.form['number'])
    #index = list(kyouzaiDB.reset_index().query(f'Credibility_score == "{np.nan}"').index)
    index = list(kyouzaiDB.reset_index().query(f'Credibility_score.isnull()').index)
    HPnumber = kyouzaiDB.iloc[index[number],2]
    HPtitle = kyouzaiDB.iloc[index[number],0]
    HPurl = kyouzaiDB.iloc[index[number],1]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    review_list = [HPtitle,HPurl,HPnumber,studentnumber,evaluation,text,date]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv","a",encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_list)
    #評価によって並べ替える
    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv",encoding="cp932")
    saveDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv"


    #Youtube
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv', encoding="cp932")
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_Review.csv',encoding='cp932')

    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']

    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))


    S_score_norm = Similarity(df)
    I_score_norm = Informative(df)
    C_score_norm = Concentration(df)
    Credibility_score,Ave_score = Credibility(S_score_norm,I_score_norm,C_score_norm,HPnumber,df)
    review_score = [HPtitle,HPurl,HPnumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_score.csv", "a", encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)

    kyouzai_title_list,kyouzai_url_list,mihyouka_kyouzai_title_list,mihyouka_kyouzai_url_list,length =\
         kousinn01(kyouzaiDB,Credibility_score,HPnumber,df,saveDB)

    kousinn_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv",encoding="cp932")
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])
    
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])  

    return render_template("/IoTシステムデザイン/IoTsystem01.html",title = keyword[0],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3S = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )

@app.route('/IoTsystem01_video',methods =["post"])
def IoTsystem01_video():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding='cp932')
    number = int(request.form['number'])
    Youtubenumber = youtubeDB.iloc[number,2]
    Youtubetitel = youtubeDB.iloc[number,0]
    Youtubeurl = youtubeDB.iloc[number,1]
    Youtubeid = youtubeDB.iloc[number,3]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']
    
    #レビューした学籍番号を取得
    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    #date = dtt.strftime("%Y/%#m/$#d %H:%M") 
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    video_review = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Youtubeid]

    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_Review.csv','a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(video_review)
    
    video_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_Review.csv',encoding='cp932')
    save_videoDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv"

    S_score_norm = Similarity(video_df)
    I_score_norm = Informative(video_df)
    C_score_norm = Concentration(video_df)
    Credibility_score, Ave_score = Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df)
    review_score = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]
    
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_score.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)
    
    ##HP##
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv",encoding='cp932')
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    a = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{a[i]}"').index)))
    
    
    kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv',encoding='cp932')
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])

    video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length =\
         video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB)
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem01.html",title = keyword[0],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2])

@app.route('/IoTsystem01_mihyouka_video',methods =["post"])
def IoTsystem01_mihyouka_video():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding='cp932')
    number = int(request.form['number'])
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    Youtubenumber = youtubeDB.iloc[video_index[number],2]
    Youtubetitel = youtubeDB.iloc[video_index[number],0]
    Youtubeurl = youtubeDB.iloc[video_index[number],1]
    Youtubeid = youtubeDB.iloc[video_index[number],3]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    date = dtt.strftime("%Y/%-m/%-d %H:%M")

    video_review = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Youtubeid]
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_Review.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(video_review)

    video_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_Review.csv", encoding="cp932")
    save_videoDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv"
    
    S_score_norm = Similarity(video_df)
    I_score_norm = Informative(video_df)
    C_score_norm = Concentration(video_df)
    Credibility_score,Ave_score = Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df)
    review_score = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]
    
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_score.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)
    
    ##HP##
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/review_prac.csv',encoding='cp932')
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    a = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{a[i]}"').index)))
    
    
    kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/kyouzaiDB.csv',encoding='cp932')
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])
    
    video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length =\
         video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB)
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai0/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem01.html",title = keyword[0],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )


###########キーワード2つ目########################
#################################################
@app.route("/IoTsystem02")
def IoTsystem02():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])
    
    #HP
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_prac.csv",encoding="cp932")

    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []

    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    number = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{number[i]}"').index)))
    
    update_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv", encoding="cp932")
    score_list=[]
    #Credibility_scoreをscore_listに追加する（上から３つ）
    for i in range(3):
        score_list.append(update_df.iat[i,3])
    

    #youtubeについて
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding='cp932')
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_Review.csv',encoding='cp932')

    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']

    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))

    video_update_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_update_df.iat[i,4])


    return render_template("/IoTシステムデザイン/IoTsystem02.html", title= keyword[1],
            kyouzai_title1 = kyouzai_title_list[0], kyouzai_url1 = kyouzai_url_list[0],
            kyouzai_title2 = kyouzai_title_list[1], kyouzai_url2 = kyouzai_url_list[1],
            kyouzai_title3 = kyouzai_title_list[2], kyouzai_url3 = kyouzai_url_list[2],
            mihyouka_title1 = mihyouka_kyouzai_title_list[0], mihyouka_url1 = mihyouka_kyouzai_url_list[0],
            mihyouka_title2 = mihyouka_kyouzai_title_list[1], mihyouka_url2 = mihyouka_kyouzai_url_list[1],
            mihyouka_title3 = mihyouka_kyouzai_title_list[2], mihyouka_url3 = mihyouka_kyouzai_url_list[2],
            length1 = length[0], length2=length[1], length3=length[2],
            video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
            video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
            video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
            mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
            mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
            mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
            mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
            video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
            score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
            video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
            )

@app.route('/IoTsystem02_Review',methods = ["post"])
def IoTsystem02_Review():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv', encoding="cp932")
    number = int(request.form['number'])
    HPnumber = kyouzaiDB.iloc[number,2]
    HPtitle = kyouzaiDB.iloc[number,0]
    HPurl = kyouzaiDB.iloc[number,1]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #レビューした学籍番号を取得
    #studentnumber = session["user"]
    studentnumber = "2155016"

    #レビューした日付と時間を取得する
    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    # Windows環境
    #date = dtt.strftime("%Y/%#m/$#d %H:%M") 
    # Linux環境
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    #上で取得したデータを review_list に保存する
    review_list = [HPtitle, HPurl, HPnumber, studentnumber, evaluation, text, date]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_prac.csv","a",encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_list)

    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_prac.csv",encoding="cp932")
    saveDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv"

    S_score_norm = Similarity(df)
    I_score_norm = Informative(df)
    C_score_norm = Concentration(df)  
    Credibility_score, Ave_score = Credibility(S_score_norm, I_score_norm, C_score_norm, HPnumber, df)
    review_score = [HPtitle, HPurl, HPnumber, studentnumber, evaluation, text, date, Credibility_score, Ave_score]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_score.csv", "a", encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)

    #Youtube
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding="cp932")
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_Review.csv',encoding='cp932')
    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']
    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))


    kyouzai_title_list, kyouzai_url_list, mihyouka_kyouzai_title_list, mihyouka_kyouzai_url_list, length =\
         kousinn01(kyouzaiDB, Credibility_score, HPnumber,df,saveDB)
    kousinn_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv",encoding="cp932")
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])

    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem02.html",title = keyword[1],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0], mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1], mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2], mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0], length2=length[1], length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3S = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )

@app.route("/IoTsystem02_mihyouka_Review", methods=["POST"])
def IoTsystem02_mihyouka_Review():
    ##キーワード取得のための部分##
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])
    ############################

    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv', encoding="cp932")
    number = int(request.form['number'])
    #index = list(kyouzaiDB.reset_index().query(f'Credibility_score == "{np.nan}"').index)
    index = list(kyouzaiDB.reset_index().query(f'Credibility_score.isnull()').index)
    HPnumber = kyouzaiDB.iloc[index[number],2]
    HPtitle = kyouzaiDB.iloc[index[number],0]
    HPurl = kyouzaiDB.iloc[index[number],1]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    review_list = [HPtitle,HPurl,HPnumber,studentnumber,evaluation,text,date]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_prac.csv","a",encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_list)
    #評価によって並べ替える
    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_prac.csv",encoding="cp932")
    saveDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv"


    #Youtube
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv', encoding="cp932")
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_Review.csv',encoding='cp932')

    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']

    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))


    S_score_norm = Similarity(df)
    I_score_norm = Informative(df)
    C_score_norm = Concentration(df)
    Credibility_score,Ave_score = Credibility(S_score_norm,I_score_norm,C_score_norm,HPnumber,df)
    review_score = [HPtitle,HPurl,HPnumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_score.csv", "a", encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)

    kyouzai_title_list,kyouzai_url_list,mihyouka_kyouzai_title_list,mihyouka_kyouzai_url_list,length =\
         kousinn01(kyouzaiDB,Credibility_score,HPnumber,df,saveDB)

    kousinn_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv",encoding="cp932")
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])
    
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])
    

    return render_template("/IoTシステムデザイン/IoTsystem02.html",title = keyword[1],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3S = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )

@app.route('/IoTsystem02_video',methods =["post"])
def IoTsystem02_video():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding='cp932')
    number = int(request.form['number'])
    Youtubenumber = youtubeDB.iloc[number,2]
    Youtubetitel = youtubeDB.iloc[number,0]
    Youtubeurl = youtubeDB.iloc[number,1]
    Youtubeid = youtubeDB.iloc[number,3]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']
    
    #レビューした学籍番号を取得
    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    #date = dtt.strftime("%Y/%#m/$#d %H:%M") 
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    video_review = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Youtubeid]

    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_Review.csv','a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(video_review)
    
    video_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_Review.csv',encoding='cp932')
    save_videoDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv"

    S_score_norm = Similarity(video_df)
    I_score_norm = Informative(video_df)
    C_score_norm = Concentration(video_df)
    Credibility_score, Ave_score = Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df)
    review_score = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]
    
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_score.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)
    
    ##HP##
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_prac.csv",encoding='cp932')
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    a = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{a[i]}"').index)))
    
    
    kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv',encoding='cp932')
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])

    video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length =\
         video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB)
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem02.html",title = keyword[1],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2])

@app.route('/IoTsystem02_mihyouka_video',methods =["post"])
def IoTsystem02_mihyouka_video():
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding='cp932')
    number = int(request.form['number'])
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    Youtubenumber = youtubeDB.iloc[video_index[number],2]
    Youtubetitel = youtubeDB.iloc[video_index[number],0]
    Youtubeurl = youtubeDB.iloc[video_index[number],1]
    Youtubeid = youtubeDB.iloc[video_index[number],3]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    date = dtt.strftime("%Y/%-m/%-d %H:%M")

    video_review = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Youtubeid]
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_Review.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(video_review)

    video_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_Review.csv", encoding="cp932")
    save_videoDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv"
    
    S_score_norm = Similarity(video_df)
    I_score_norm = Informative(video_df)
    C_score_norm = Concentration(video_df)
    Credibility_score,Ave_score = Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df)
    review_score = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]
    
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_score.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)
    
    ##HP##
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/review_prac.csv',encoding='cp932')
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    a = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{a[i]}"').index)))
    
    
    kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/kyouzaiDB.csv',encoding='cp932')
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])
    
    video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length =\
         video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB)
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai1/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem02.html",
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[1],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )


###########キーワード3つ目########################
#################################################
@app.route("/IoTsystem03")
def IoTsystem03():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])
    
    #HP
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_prac.csv",encoding="cp932")

    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []

    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    number = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{number[i]}"').index)))
    
    update_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv", encoding="cp932")
    score_list=[]
    #Credibility_scoreをscore_listに追加する（上から３つ）
    for i in range(3):
        score_list.append(update_df.iat[i,3])
    

    #youtubeについて
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding='cp932')
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_Review.csv',encoding='cp932')

    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']

    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))

    video_update_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_update_df.iat[i,4])


    return render_template("/IoTシステムデザイン/IoTsystem03.html", title= keyword[2],
            kyouzai_title1 = kyouzai_title_list[0], kyouzai_url1 = kyouzai_url_list[0],
            kyouzai_title2 = kyouzai_title_list[1], kyouzai_url2 = kyouzai_url_list[1],
            kyouzai_title3 = kyouzai_title_list[2], kyouzai_url3 = kyouzai_url_list[2],
            mihyouka_title1 = mihyouka_kyouzai_title_list[0], mihyouka_url1 = mihyouka_kyouzai_url_list[0],
            mihyouka_title2 = mihyouka_kyouzai_title_list[1], mihyouka_url2 = mihyouka_kyouzai_url_list[1],
            mihyouka_title3 = mihyouka_kyouzai_title_list[2], mihyouka_url3 = mihyouka_kyouzai_url_list[2],
            length1 = length[0], length2=length[1], length3=length[2],
            video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
            video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
            video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
            mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
            mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
            mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
            mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
            video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
            score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
            video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
            )

@app.route('/IoTsystem03_Review',methods = ["post"])
def IoTsystem03_Review():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv', encoding="cp932")
    number = int(request.form['number'])
    HPnumber = kyouzaiDB.iloc[number,2]
    HPtitle = kyouzaiDB.iloc[number,0]
    HPurl = kyouzaiDB.iloc[number,1]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #レビューした学籍番号を取得
    #studentnumber = session["user"]
    studentnumber = "2155016"

    #レビューした日付と時間を取得する
    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    #date = dtt.strftime("%Y/%#m/$#d %H:%M") 
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    #上で取得したデータを review_list に保存する
    review_list = [HPtitle, HPurl, HPnumber, studentnumber, evaluation, text, date]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_prac.csv","a",encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_list)

    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_prac.csv",encoding="cp932")
    saveDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv"

    S_score_norm = Similarity(df)
    I_score_norm = Informative(df)
    C_score_norm = Concentration(df)  
    Credibility_score, Ave_score = Credibility(S_score_norm, I_score_norm, C_score_norm, HPnumber, df)
    review_score = [HPtitle, HPurl, HPnumber, studentnumber, evaluation, text, date, Credibility_score, Ave_score]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_score.csv", "a", encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)

    #Youtube
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding="cp932")
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_Review.csv',encoding='cp932')
    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']
    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))


    kyouzai_title_list, kyouzai_url_list, mihyouka_kyouzai_title_list, mihyouka_kyouzai_url_list, length =\
         kousinn01(kyouzaiDB, Credibility_score, HPnumber,df,saveDB)
    kousinn_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv",encoding="cp932")
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])

    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem03.html",title = keyword[2],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0], mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1], mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2], mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0], length2=length[1], length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3S = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )

@app.route("/IoTsystem03_mihyouka_Review", methods=["POST"])
def IoTsystem03_mihyouka_Review():
    ##キーワード取得のための部分##
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])
    ############################

    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv', encoding="cp932")
    number = int(request.form['number'])
    #index = list(kyouzaiDB.reset_index().query(f'Credibility_score == "{np.nan}"').index)
    index = list(kyouzaiDB.reset_index().query(f'Credibility_score.isnull()').index)
    HPnumber = kyouzaiDB.iloc[index[number],2]
    HPtitle = kyouzaiDB.iloc[index[number],0]
    HPurl = kyouzaiDB.iloc[index[number],1]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    review_list = [HPtitle,HPurl,HPnumber,studentnumber,evaluation,text,date]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_prac.csv","a",encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_list)
    #評価によって並べ替える
    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_prac.csv",encoding="cp932")
    saveDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv"


    #Youtube
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv', encoding="cp932")
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_Review.csv',encoding='cp932')

    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']

    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))


    S_score_norm = Similarity(df)
    I_score_norm = Informative(df)
    C_score_norm = Concentration(df)
    Credibility_score,Ave_score = Credibility(S_score_norm,I_score_norm,C_score_norm,HPnumber,df)
    review_score = [HPtitle,HPurl,HPnumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_score.csv", "a", encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)

    kyouzai_title_list,kyouzai_url_list,mihyouka_kyouzai_title_list,mihyouka_kyouzai_url_list,length =\
         kousinn01(kyouzaiDB,Credibility_score,HPnumber,df,saveDB)

    kousinn_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv",encoding="cp932")
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])
    
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])
    

    return render_template("/IoTシステムデザイン/IoTsystem03.html",title = keyword[2],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3S = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )

@app.route('/IoTsystem03_video',methods =["post"])
def IoTsystem03_video():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding='cp932')
    number = int(request.form['number'])
    Youtubenumber = youtubeDB.iloc[number,2]
    Youtubetitel = youtubeDB.iloc[number,0]
    Youtubeurl = youtubeDB.iloc[number,1]
    Youtubeid = youtubeDB.iloc[number,3]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']
    
    #レビューした学籍番号を取得
    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    #date = dtt.strftime("%Y/%#m/$#d %H:%M") 
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    video_review = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Youtubeid]

    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_Review.csv','a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(video_review)
    
    video_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_Review.csv',encoding='cp932')
    save_videoDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv"

    S_score_norm = Similarity(video_df)
    I_score_norm = Informative(video_df)
    C_score_norm = Concentration(video_df)
    Credibility_score, Ave_score = Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df)
    review_score = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]
    
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_score.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)
    
    ##HP##
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_prac.csv",encoding='cp932')
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    a = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{a[i]}"').index)))
    
    
    kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv',encoding='cp932')
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])

    video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length =\
         video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB)
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem03.html",title = keyword[2],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2])

@app.route('/IoTsystem03_mihyouka_video',methods =["post"])
def IoTsystem03_mihyouka_video():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding='cp932')
    number = int(request.form['number'])
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    Youtubenumber = youtubeDB.iloc[video_index[number],2]
    Youtubetitel = youtubeDB.iloc[video_index[number],0]
    Youtubeurl = youtubeDB.iloc[video_index[number],1]
    Youtubeid = youtubeDB.iloc[video_index[number],3]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    date = dtt.strftime("%Y/%-m/%-d %H:%M")

    video_review = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Youtubeid]
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_Review.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(video_review)

    video_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_Review.csv", encoding="cp932")
    save_videoDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv"
    
    S_score_norm = Similarity(video_df)
    I_score_norm = Informative(video_df)
    C_score_norm = Concentration(video_df)
    Credibility_score,Ave_score = Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df)
    review_score = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]
    
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_score.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)
    
    ##HP##
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/review_prac.csv',encoding='cp932')
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    a = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{a[i]}"').index)))
    
    
    kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/kyouzaiDB.csv',encoding='cp932')
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])
    
    video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length =\
         video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB)
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai2/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem03.html",title = keyword[2],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )


###########キーワード4つ目########################
#################################################
@app.route("/IoTsystem04")
def IoTsystem04():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])
    
    #HP
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_prac.csv",encoding="cp932")

    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []

    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    number = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{number[i]}"').index)))
    
    update_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv", encoding="cp932")
    score_list=[]
    #Credibility_scoreをscore_listに追加する（上から３つ）
    for i in range(3):
        score_list.append(update_df.iat[i,3])
    

    #youtubeについて
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding='cp932')
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_Review.csv',encoding='cp932')

    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']

    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))

    video_update_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_update_df.iat[i,4])


    return render_template("/IoTシステムデザイン/IoTsystem04.html", title= keyword[3],
            kyouzai_title1 = kyouzai_title_list[0], kyouzai_url1 = kyouzai_url_list[0],
            kyouzai_title2 = kyouzai_title_list[1], kyouzai_url2 = kyouzai_url_list[1],
            kyouzai_title3 = kyouzai_title_list[2], kyouzai_url3 = kyouzai_url_list[2],
            mihyouka_title1 = mihyouka_kyouzai_title_list[0], mihyouka_url1 = mihyouka_kyouzai_url_list[0],
            mihyouka_title2 = mihyouka_kyouzai_title_list[1], mihyouka_url2 = mihyouka_kyouzai_url_list[1],
            mihyouka_title3 = mihyouka_kyouzai_title_list[2], mihyouka_url3 = mihyouka_kyouzai_url_list[2],
            length1 = length[0], length2=length[1], length3=length[2],
            video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
            video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
            video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
            mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
            mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
            mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
            mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
            video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
            score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
            video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
            )

@app.route('/IoTsystem04_Review',methods = ["post"])
def IoTsystem04_Review():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv', encoding="cp932")
    number = int(request.form['number'])
    HPnumber = kyouzaiDB.iloc[number,2]
    HPtitle = kyouzaiDB.iloc[number,0]
    HPurl = kyouzaiDB.iloc[number,1]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #レビューした学籍番号を取得
    #studentnumber = session["user"]
    studentnumber = "2155016"

    #レビューした日付と時間を取得する
    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    #date = dtt.strftime("%Y/%#m/$#d %H:%M") 
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    #上で取得したデータを review_list に保存する
    review_list = [HPtitle, HPurl, HPnumber, studentnumber, evaluation, text, date]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_prac.csv","a",encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_list)

    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_prac.csv",encoding="cp932")
    saveDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv"

    S_score_norm = Similarity(df)
    I_score_norm = Informative(df)
    C_score_norm = Concentration(df)  
    Credibility_score, Ave_score = Credibility(S_score_norm, I_score_norm, C_score_norm, HPnumber, df)
    review_score = [HPtitle, HPurl, HPnumber, studentnumber, evaluation, text, date, Credibility_score, Ave_score]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_score.csv", "a", encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)

    #Youtube
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding="cp932")
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_Review.csv',encoding='cp932')
    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']
    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))


    kyouzai_title_list, kyouzai_url_list, mihyouka_kyouzai_title_list, mihyouka_kyouzai_url_list, length =\
         kousinn01(kyouzaiDB, Credibility_score, HPnumber,df,saveDB)
    kousinn_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv",encoding="cp932")
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])

    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem04.html",title = keyword[3],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0], mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1], mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2], mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0], length2=length[1], length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3S = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )

@app.route("/IoTsystem04_mihyouka_Review", methods=["POST"])
def IoTsystem04_mihyouka_Review():
    ##キーワード取得のための部分##
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])
    ############################

    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv', encoding="cp932")
    number = int(request.form['number'])
    #index = list(kyouzaiDB.reset_index().query(f'Credibility_score == "{np.nan}"').index)
    index = list(kyouzaiDB.reset_index().query(f'Credibility_score.isnull()').index)
    HPnumber = kyouzaiDB.iloc[index[number],2]
    HPtitle = kyouzaiDB.iloc[index[number],0]
    HPurl = kyouzaiDB.iloc[index[number],1]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    review_list = [HPtitle,HPurl,HPnumber,studentnumber,evaluation,text,date]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_prac.csv","a",encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_list)
    #評価によって並べ替える
    df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_prac.csv",encoding="cp932")
    saveDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv"


    #Youtube
    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv', encoding="cp932")
    video_review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_Review.csv',encoding='cp932')

    video_title_list = []
    video_url_list = []
    video_id_list = []
    mihyouka_video_title_list = []
    mihyouka_video_url_list = []
    mihyouka_video_id_list = []
    video_length = []
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    yo = youtubeDB['Youtubenumber']

    for i in range(3):
        video_title_list.append(youtubeDB.iat[i,0])
        video_url_list.append(youtubeDB.iat[i,1])
        video_id_list.append(youtubeDB.iat[i,3])
        mihyouka_video_title_list.append(youtubeDB.iat[video_index[i],0])
        mihyouka_video_url_list.append(youtubeDB.iat[video_index[i],1])
        mihyouka_video_id_list.append(youtubeDB.iat[video_index[i],3])
        video_length.append(len(list(video_review_df.query(f'Youtubenumber == "{yo[i]}"').index)))


    S_score_norm = Similarity(df)
    I_score_norm = Informative(df)
    C_score_norm = Concentration(df)
    Credibility_score,Ave_score = Credibility(S_score_norm,I_score_norm,C_score_norm,HPnumber,df)
    review_score = [HPtitle,HPurl,HPnumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]

    with open("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_score.csv", "a", encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)

    kyouzai_title_list,kyouzai_url_list,mihyouka_kyouzai_title_list,mihyouka_kyouzai_url_list,length =\
         kousinn01(kyouzaiDB,Credibility_score,HPnumber,df,saveDB)

    kousinn_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv",encoding="cp932")
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])
    
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])
    

    return render_template("/IoTシステムデザイン/IoTsystem04.html",title = keyword[3],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3S = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )

@app.route('/IoTsystem04_video',methods =["post"])
def IoTsystem04_video():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding='cp932')
    number = int(request.form['number'])
    Youtubenumber = youtubeDB.iloc[number,2]
    Youtubetitel = youtubeDB.iloc[number,0]
    Youtubeurl = youtubeDB.iloc[number,1]
    Youtubeid = youtubeDB.iloc[number,3]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']
    
    #レビューした学籍番号を取得
    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    #date = dtt.strftime("%Y/%#m/$#d %H:%M") 
    date = dtt.strftime("%Y/%-m/%-d %H:%M")
    video_review = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Youtubeid]

    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_Review.csv','a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(video_review)
    
    video_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_Review.csv',encoding='cp932')
    save_videoDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv"

    S_score_norm = Similarity(video_df)
    I_score_norm = Informative(video_df)
    C_score_norm = Concentration(video_df)
    Credibility_score, Ave_score = Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df)
    review_score = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]
    
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_score.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)
    
    ##HP##
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_prac.csv",encoding='cp932')
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    a = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{a[i]}"').index)))
    
    
    kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv',encoding='cp932')
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])

    video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length =\
         video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB)
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem04.html",title = keyword[3],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2])

@app.route('/IoTsystem04_mihyouka_video',methods =["post"])
def IoTsystem04_mihyouka_video():
    df_key = pd.read_csv("Kamoku/IoTシステムデザイン/IoTシステムデザイン.csv",encoding="cp932",names= ['key'])
    keyword = []
    for i in range(len(df_key)):
        keyword.append(df_key.loc[i,'key'])

    youtubeDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding='cp932')
    number = int(request.form['number'])
    video_index = list(youtubeDB.query(f'Credibility_score.isnull()',engine='python').index)
    Youtubenumber = youtubeDB.iloc[video_index[number],2]
    Youtubetitel = youtubeDB.iloc[video_index[number],0]
    Youtubeurl = youtubeDB.iloc[video_index[number],1]
    Youtubeid = youtubeDB.iloc[video_index[number],3]
    evaluation = int(request.form['evaluation'])
    text = request.form['text']

    #studentnumber = session["user"]
    studentnumber = "2155016"

    dt = datetime.datetime.now()
    dtt = dt.replace(microsecond=0)
    date = dtt.strftime("%Y/%-m/%-d %H:%M")

    video_review = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Youtubeid]
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_Review.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(video_review)

    video_df = pd.read_csv("Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_Review.csv", encoding="cp932")
    save_videoDB = "Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv"
    
    S_score_norm = Similarity(video_df)
    I_score_norm = Informative(video_df)
    C_score_norm = Concentration(video_df)
    Credibility_score,Ave_score = Credibility_video(S_score_norm,I_score_norm,C_score_norm,Youtubenumber,video_df)
    review_score = [Youtubetitel,Youtubeurl,Youtubenumber,studentnumber,evaluation,text,date,Credibility_score,Ave_score]
    
    with open('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_score.csv', 'a',encoding="cp932",newline='') as f:
        writer = csv.writer(f,delimiter=',')
        writer.writerow(review_score)
    
    ##HP##
    kyouzaiDB = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv', encoding="cp932")
    review_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/review_prac.csv',encoding='cp932')
    kyouzai_title_list = []
    kyouzai_url_list = []
    mihyouka_kyouzai_title_list = []
    mihyouka_kyouzai_url_list = []
    length = []
    index = list(kyouzaiDB.query(f'Credibility_score.isnull()',engine='python').index)
    a = kyouzaiDB['Hpnumber']

    for i in range(3):
        kyouzai_title_list.append(kyouzaiDB.iloc[i,0])
        kyouzai_url_list.append(kyouzaiDB.iloc[i,1])
        mihyouka_kyouzai_title_list.append(kyouzaiDB.iloc[index[i],0])
        mihyouka_kyouzai_url_list.append(kyouzaiDB.iloc[index[i],1])
        length.append(len(list(review_df.query(f'Hpnumber == "{a[i]}"').index)))
    
    
    kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/kyouzaiDB.csv',encoding='cp932')
    score_list = []
    for i in range(3):
        score_list.append(kousinn_df.iat[i,3])
    
    video_title_list,video_url_list,mihyouka_video_title_list,mihyouka_video_url_list,video_id_list,mihyouka_video_id_list,video_length =\
         video_kousinn00(youtubeDB,Credibility_score,Youtubenumber, video_df, save_videoDB)
    video_kousinn_df = pd.read_csv('Kamoku/IoTシステムデザイン/Kyouzai/kyouzai3/video_kyouzai.csv',encoding='cp932')
    video_score_list = []
    for i in range(3):
        video_score_list.append(video_kousinn_df.iat[i,4])

    return render_template("/IoTシステムデザイン/IoTsystem04.html",title = keyword[3],
    kyouzai_title1 = kyouzai_title_list[0],kyouzai_url1 = kyouzai_url_list[0],
    kyouzai_title2 = kyouzai_title_list[1],kyouzai_url2 = kyouzai_url_list[1],
    kyouzai_title3 = kyouzai_title_list[2],kyouzai_url3 = kyouzai_url_list[2],
    mihyouka_title1 = mihyouka_kyouzai_title_list[0],mihyouka_url1 = mihyouka_kyouzai_url_list[0],
    mihyouka_title2 = mihyouka_kyouzai_title_list[1],mihyouka_url2 = mihyouka_kyouzai_url_list[1],
    mihyouka_title3 = mihyouka_kyouzai_title_list[2],mihyouka_url3 = mihyouka_kyouzai_url_list[2],
    length1 = length[0],length2=length[1],length3=length[2],
    video_title1 = video_title_list[0],video_url1 = video_url_list[0],video_id1 = video_id_list[0],
    video_title2 = video_title_list[1],video_url2 = video_url_list[1],video_id2 = video_id_list[1],
    video_title3 = video_title_list[2],video_url3 = video_url_list[2],video_id3 = video_id_list[2],
    mihyouka_video_title1 = mihyouka_video_title_list[0],mihyouka_video_url1 = mihyouka_video_url_list[0],
    mihyouka_video_title2 = mihyouka_video_title_list[1],mihyouka_video_url2 = mihyouka_video_url_list[1],
    mihyouka_video_title3 = mihyouka_video_title_list[2],mihyouka_video_url3 = mihyouka_video_url_list[2],
    mihyouka_video_id1 = mihyouka_video_id_list[0],mihyouka_video_id2 = mihyouka_video_id_list[1],mihyouka_video_id3 = mihyouka_video_id_list[2],
    video_length1 = video_length[0],video_length2=video_length[1],video_length3=video_length[2],
    score1 = score_list[0],score2 = score_list[1],score3 = score_list[2],
    video_score1 = video_score_list[0],video_score2 = video_score_list[1],video_score3 = video_score_list[2]
    )
    
    
if __name__ == '__main__':
    app.run(debug = True)
