Ejemplo n.º 1
0
def nonTechnicalKeywordSeelector(names,project):
    name_list = names.split(',')
    print("name list")
    print(name_list)
    db_list = []

    unique_filtered_word_nontech = set()
    for val in name_list:
        lower_case_value = val.lower()
        unique_filtered_word_nontech.add(lower_case_value)
        print(unique_filtered_word_nontech)
        print("error in yesterday")
    for value in unique_filtered_word_nontech:
        db_availability = ConnectionToNeo4j.getMatchingTopicsNonTech(value)
        print("error in now")
        if db_availability == True:
            db_list.append(value)
        print(db_list)
        print("it is printed")
    if len(db_list) > 0:
        db_string_list = ','.join(db_list)
        print(db_string_list)
        print("error in that")
        return  db_string_list
    else:
        db = "CV"
        project_tech_list = ConnectionToNeo4j.cvProjectTech(db,project)
        print("error in this")
        return project_tech_list
Ejemplo n.º 2
0
def change_difficulty_level(nodeId, langName):
    importlib.reload(vari)
    userId = vari.userId
    category1 = "easy"
    category2 = "medium"
    category3 = "hard"
    global diffi_new_level

    #checking whether it contains node the easy level
    diffList = ConnectionToNeo4j.getDifficultyList(userId, langName, category1)
    diffList = diffList.split(',')
    for val1 in diffList:
        if val1 == nodeId:
            diffi_new_level = "easy"
            return diffi_new_level

    #checking whether it contains node the medium level
    diffList2 = ConnectionToNeo4j.getDifficultyList(userId, langName,
                                                    category2)
    diffList2 = diffList2.split(',')
    for val2 in diffList2:
        if val2 == nodeId:
            diffi_new_level = "medium"
            return diffi_new_level

    #checking whether it contains node the hard level
    diffList3 = ConnectionToNeo4j.getDifficultyList(userId, langName,
                                                    category3)
    diffList3 = diffList3.split(',')
    for val3 in diffList3:
        if val3 == nodeId:
            diffi_new_level = "hard"
            return diffi_new_level
def ValidatingTechnical(userAnswer, dbAnswer, qno):

    sentence1 = userAnswer
    sentence2 = dbAnswer

    grammarMarks = WeightOfTheAnswer.process_content(sentence1)

    if len(sentence1.split()) == 0:
        ConnectionToNeo4j.sessionMarksStoring(vari.userId, "", qno, "0.0")
        return [0, 'None']

    else:

        stopWords = set(stopwords.words('english'))

        words1 = word_tokenize(sentence1)
        words2 = word_tokenize(sentence2)

        wordsFiltered1 = []
        wordsFiltered2 = []

        newSentence = ""

        for w in words1:
            if w not in stopWords:
                wordsFiltered1.append(w)
                newSentence = newSentence + " " + w

        for w in words2:
            if w not in stopWords:
                wordsFiltered2.append(w)

        marks = 0
        final_word = ""

        for word2 in wordsFiltered2:
            for word1 in wordsFiltered1:
                if word2 == word1:
                    marks += 1

        for word in wordsFiltered2:
            final_word = final_word + " " + word

        wordcountofdbanswer = len(final_word.split())
        print("before filtered:", sentence1)
        print("Loading..")
        print("after filtered:", final_word)
        print(marks)
        print(wordcountofdbanswer)
        finalmark = (marks / wordcountofdbanswer) + grammarMarks
        finalmark = "%.2f" % finalmark
        # finalmark = SequenceMatcher(None, wordsFiltered1, wordsFiltered2).ratio()
        importlib.reload(vari)

        ConnectionToNeo4j.sessionMarksStoring(vari.userId, "", qno, finalmark)

        return_Value = [finalmark, newSentence]

        return return_Value
Ejemplo n.º 4
0
def get_post_javascript_data():
    un = request.form['username']
    pw = request.form['password']


    dbpw = ConnectionToNeo4j.login(un)


    print(un)
    if pw == dbpw:
        open('userDetails.py', 'w').close()
        fruits = ["global results12\n", "results12 = 'yes'"]
        new_file = open("userDetails.py", mode="a+", encoding="utf-8")
        new_file.writelines(fruits)
        for line in new_file:
            print(line)

        new_file.close()

    else:
        open('userDetails.py', 'w').close()
        fruits = ["global results12\n", "results12 = 'no'"]
        new_file = open("userDetails.py", mode="a+", encoding="utf-8")
        new_file.writelines(fruits)
        for line in new_file:
            print(line)

        new_file.close()
Ejemplo n.º 5
0
def dingdong():
    print("shalalalallala")
    importlib.reload(vari)
    uid = vari.userId
    val = ConnectionToNeo4j.checkuserinnwadas(uid)
    result = {"myca": str(val)}
    return json.dumps(result)
Ejemplo n.º 6
0
def selectionbox():
    no = ConnectionToNeo4j.noofsessions()
    result = {}

    for x in range(0, int(no)):
        result['no'+str(x+1)] = "session"+str(x+1)

    return json.dumps(result)
def showHardSubjectNames():
    userid = vari.userId
    languageName = "python"
    # print(ConnectionToNeo4j.getHardList(userid, languageName))
    # print(type(ConnectionToNeo4j.getHardList(userid, languageName)))
    #
    ListConvert = (ConnectionToNeo4j.getHardList(userid, languageName))
    print(type(ListConvert))
    test = ListConvert.split()
    print(test)
    # test2 = int(test)
    # print(test2)
    # ListConvert2 = list(map(int, ListConvert))
    # print(ListConvert2)
    # print(' '.join(map(str, ListConvert)))

    # uu = np.ndarray.tolist(ListConvert2)
    # print(uu)
    # print(type(uu))

    # test = [4, 8, 11, 13, 14, 17, 26]

    # print(type(test))
    # print(test[0])
    # print(test[1])
    # print(test[2])
    # print(test[3])
    # print(len(test))

    jj = "You better to focus on this areas -> \n"

    if len(test) >= 1:
        element = 1
        # return ConnectionToNeo4j.showHardList(element)
        aa1 = ConnectionToNeo4j.showHardList(element)

    if len(test) >= 2:
        element = 2
        aa2 = ConnectionToNeo4j.showHardList(element)

    if len(test) >= 3:
        element = 3
        aa3 = ConnectionToNeo4j.showHardList(element)

    if len(test) >= 4:
        element = 4
        aa4 = ConnectionToNeo4j.showHardList(element)

    if len(test) >= 5:
        element = 5
        aa5 = ConnectionToNeo4j.showHardList(element)

    if len(test) >= 6:
        element = 6
        aa6 = ConnectionToNeo4j.showHardList(element)

    return jj, aa1, aa2, aa3, aa4, aa5, aa6
def ValidatingNonTechnical(answer, qno):

    answerwordcount = len(answer.split())

    stopWords = set(stopwords.words('english'))

    words1 = word_tokenize(answer)

    wordsFiltered1 = []

    newSentence = ""

    for w in words1:
        if w not in stopWords:
            wordsFiltered1.append(w)
            newSentence = newSentence + " " + w

    print("before filtered:", answer)
    print("Loading..")
    print("after filtered:", newSentence)

    importlib.reload(vari)
    if answerwordcount == 0:
        ConnectionToNeo4j.sessionMarksStoring(vari.userId, "", qno, '0')
        return [0, 'None']
    if answerwordcount < 20:
        ConnectionToNeo4j.sessionMarksStoring(vari.userId, "", qno, '0.5')
        return [0.5, newSentence]
    if answerwordcount > 20:
        ConnectionToNeo4j.sessionMarksStoring(vari.userId, "", qno, '1')
        return [1, newSentence]
Ejemplo n.º 9
0
def ValidatingNonTechnical(answer, qno):

    answerwordcount = len(answer.split())

    stopWords = set(stopwords.words('english'))

    words1 = word_tokenize(answer)

    wordsFiltered1 = []

    newSentence = ""

    for w in words1:
        if w not in stopWords:
            wordsFiltered1.append(w)
            newSentence = newSentence + " " + w

    if answerwordcount == 0:
        ConnectionToNeo4j.sessionMarksStoring(vari.userId, vari.sessionId, qno,
                                              '0')
        return ['None', '']
    if answerwordcount < 20:
        ConnectionToNeo4j.sessionMarksStoring(vari.userId, vari.sessionId, qno,
                                              '0.5')
        return [0.5, newSentence]
    if answerwordcount > 20:
        ConnectionToNeo4j.sessionMarksStoring(vari.userId, vari.sessionId, qno,
                                              '1')
        return [1, newSentence]
Ejemplo n.º 10
0
def chart(a):
    print(a[7:])

    val = ConnectionToNeo4j.getsessionmarks(a[7:])


    result = {"no1":"session1","no2":"session2"}

    print(val)
    print(result)


    return json.dumps(val)
def adding_diff_level_val_list(userId, user_diff, db_diff, random_table,
                               diff_level):
    level_list = ConnectionToNeo4j.getdiffLevelList(userId, user_diff, db_diff,
                                                    random_table, diff_level)
    level_list_str = str(level_list)
    print("hello i got the list")
    print(level_list)

    diff_list = level_list.split(',')
    print("hello in the diff level selector")
    diff_list = list(map(int, diff_list))
    print(diff_list)
    return (diff_list)
def validation(subsection, typer, treetype, qno):
    print("checking=" + qno + "=gooog=" + subsection + "=goog=" + typer +
          "=goog=" + treetype)

    r = sr.Recognizer()
    audio = "Audio/" + MostRecentAudioFileAccess.MostRecentAudioClip()
    cmd = 'ffmpeg -i ' + audio + ' -f segment -segment_time 13 -c copy Audio/answer_creation_purposes/out%03d.wav'
    os.system(cmd)
    marks = "No"

    longstext = ""

    path, dirs, files = next(os.walk("Audio/answer_creation_purposes"))
    file_count = len(files)
    range_value = file_count
    print('Loading..')
    # importlib.reload(Audio.answer_creation_purposes)
    for x in range(0, range_value):
        audio = 'Audio/answer_creation_purposes/out00' + str(x) + '.wav'

        with sr.AudioFile(str(audio)) as source:
            audio = r.record(source)

        try:
            text = r.recognize_google(audio)
            if x == 0:
                longstext = text
            else:
                longstext = longstext + " " + text

        except Exception as e:
            print(e)
    #
    filelist = glob.glob("Audio/answer_creation_purposes/*.wav")
    for file in filelist:
        os.remove(file)

    #

    # if longstext == "":
    #     longstext = "empty audio"

    if typer == "technical":
        valuefromdb = ConnectionToNeo4j.getValueFromdb(subsection, treetype)
        marks = AnswerValidating.ValidatingTechnical(longstext, valuefromdb,
                                                     qno)
    if typer == "nontechnical":
        marks = AnswerValidating.ValidatingNonTechnical(longstext, qno)

    return marks
Ejemplo n.º 13
0
def rewardForQuestion(languageName, nodeId, difficultyLevel):
    # languageName = "python"
    # nodeId = 10
    # difficultyLevel = "medium"

    userid = vari.userId

    facial = 10  #have to remove
    voice = 10  #have to remove
    answer = 20  #have to remove

    total = (facial + voice + answer)

    print("Total = ", total)
    total = int(total)

    if (0 < total <= 20):
        state = 1
        print("State = ", state)

    elif (21 < total <= 40):
        state = 2
        print("State = ", state)

    elif (41 < total <= 60):
        state = 3
        print("State = ", state)

    elif (61 < total <= 80):
        state = 4
        print("State = ", state)

    else:
        state = 5
        print("State = ", state)

    # -----------------------------------------------------------------------------------
    # Get the latest updated q-table from ontology - only for shown

    print("@@@@@This part for get from ontology@@@@@@@@@@@@@@@@@@@@@@@@@")
    print("It is updated correctly \n",
          ConnectionToNeo4j.createQtable1(languageName))
    print(type(ConnectionToNeo4j.createQtable1(languageName)))
    print("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")

    # data = R
    print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")

    # Get the String array matrix from ontology - split
    I = np.array(ConnectionToNeo4j.createQtable1(languageName)).tolist()
    Z = I.split(" ")
    print("Z-spit krapu 1 \n", Z)
    print(type(Z))

    # to remove the []
    number = " ".join(Z)
    print("this remove[] \n", number)
    print(type(number))

    print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")

    # H = [float(i) if '.' in i else int(i) for i in number]
    # H = np.asfarray(number,float)
    # print("This str - float")
    # print(type(H))
    # Re-change it into 5,5 array
    # qTableCreated = H.reshape(5,5)
    # print(type(qTableCreated))
    # print(qTableCreated)

    # change it into matrix
    # R = np.matrix(number)
    # print(type(R))
    # print(R)

    R = np.matrix([[64.0, 64.0, 64.0, 64.0, 64.0],
                   [64.0, 64.0, 64.0, 64.0, 64.0],
                   [64.0, 64.0, 64.0, 64.0, 64.0],
                   [64.0, 64.0, 64.0, 64.0, 64.0],
                   [64.0, 64.0, 64.0, 64.0, 64.0]])
    # try:
    #     I = float(ConnectionToNeo4j.createQtable1(languageName))
    #     R = np.matrix(I)
    # except ValueError:
    #     print("That is not a valid number of miles")

    # matrix = open(fname).read()
    # matrix = [item.split('\n') for item in matrix.split('\n')]
    # R = matrix.reshape((matrix.shape[0], 5))

    # print("Get from text file-latest updated \n", R)

    print("----------------------------------------------")
    # Q matrix
    Q = np.matrix(np.zeros([5, 5]))

    if state == 1:
        R[0, 4] = total
    elif state == 2:
        R[1, 3] = total
    elif state == 3:
        R[2, 2] = total
    elif state == 4:
        R[3, 1] = total
    else:
        R[4, 0] = total

    # Gamma (learning parameter).
    gamma = 0.8

    # Initial state
    if state == 5:
        initial_state = 4
    else:
        initial_state = state

    # initial_state = state
    # This function returns all available actions in the state given as an argument
    def available_actions(state):
        current_state_row = R[state, ]
        av_act = np.where(current_state_row >= 0)[1]
        return av_act

    # Get available actions in the current state
    available_act = available_actions(initial_state)

    # This function chooses at random which action to be performed within the range
    def sample_next_action(available_actions_range):
        next_action = int(np.random.choice(available_act, 1))
        return next_action

    # Sample next action to be performed
    action = sample_next_action(available_act)

    # This function updates the Q matrix
    def update(current_state, action, gamma):
        max_index = np.where(Q[action, ] == np.max(Q[action, ]))[1]

        if max_index.shape[0] > 1:
            max_index = int(np.random.choice(max_index, size=1))
        else:
            max_index = int(max_index)
        max_value = Q[action, max_index]

        # Q learning formula
        Q[current_state, action] = R[current_state, action] + gamma * max_value

    # Update Q matrix
    update(initial_state, action, gamma)

    # -------------------------------------------------------------------------------
    # Create the reward value

    # iterarte the process
    for i in range(100):
        current_state = np.random.randint(0, int(Q.shape[0]))
        available_act = available_actions(current_state)
        action = sample_next_action(available_act)
        update(current_state, action, gamma)
    print("-----------------------")
    print("New updated one \n", Q)
    print("-----------------------")
    # ----------------------------------------------------------------------------------------------------------------
    # Save the Q-metrix in text file

    print(" Maximum value:")
    print(np.max(Q))
    T = Q * 100 / np.max(Q)
    print("^^^^^^^^^^^^^^^^^^^^^^^^^^")
    print(T)
    np.savetxt('../Database/text.txt', T, fmt='%f')

    print("-----New - 6-----------------------------------------")
    # -------------------------------------------------------
    # send to ontology

    qTableCreated = str(T)

    ConnectionToNeo4j.sendQtable(languageName, qTableCreated)
    # -------------------------------------------------------------------------------
    print("------New - 7----------------------------------------")
    # convert to probability value

    if state == 3:
        convertProb = "{0:.0f}%".format((np.max(Q) / 10) - 11)
        # convertProb = getProb - 10.0
        print("Precentage of difficulty - ", convertProb)
    else:
        convertProb = "{0:.0f}%".format(np.max(Q) / 10)
        print("Precentage of difficulty - ", convertProb)

    # --send to precentage value to ontology--------------
    print(type(convertProb))

    convertProb2 = int(convertProb.strip("%"))
    print(convertProb2)

    # --identify the state--------------
    print("------New - 8----------------------------------------")
    if convertProb2 <= 15:
        rewardState = "hard"
    elif convertProb2 <= 30:
        rewardState = "medium"
    else:
        rewardState = "easy"

    print(rewardState)
    print(type(rewardState))

    # --update the ontology---------------------------
    print(
        "-------New - 9- update the existing list--------------------------------------"
    )

    print(
        ConnectionToNeo4j.getDifficultyList(userid, languageName,
                                            difficultyLevel))

    getDiffList = str(
        ConnectionToNeo4j.getDifficultyList(userid, languageName,
                                            difficultyLevel))
    print("get existing list", getDiffList)
    print(type(getDiffList))

    print("########exiting list 1 gattaa \n")

    getDiffList2 = getDiffList.split(',')
    getDiffList2.remove(str(nodeId))
    getDiffList3 = list(map(int, getDiffList2))
    print("this removed node and int it", getDiffList3)
    print(type(getDiffList3))
    str_getDiffList3 = ','.join(str(e) for e in getDiffList3)
    print("This is converted str", str_getDiffList3)
    print(type(str_getDiffList3))

    print("#######now get the new list to update exiting one \n")

    # update the existing category with new value
    ConnectionToNeo4j.sendExistingDifficultyList(userid, languageName,
                                                 difficultyLevel,
                                                 str_getDiffList3)

    print(
        "-------New - 10- update the new list--------------------------------------"
    )

    # get the new category list

    getNewList = ConnectionToNeo4j.getNewRewardList(userid, languageName,
                                                    rewardState)
    print(ConnectionToNeo4j.getNewRewardList(userid, languageName,
                                             rewardState))
    print(type(getNewList))
    print(type(nodeId))

    str_nodeId = str(nodeId)
    print(type(str_nodeId))

    getnewList = getNewList.split(',')
    print("1", getnewList)
    getnewList.append(str_nodeId)
    print("append new nod = ", getnewList)
    # getDiffList4 =  [int(i) for i in appendNewNode]
    # print("this append and transfer int  ", getDiffList4)
    # print(type(getDiffList4))
    str_getDiffList4 = ','.join(str(e) for e in getnewList)
    print("This is converted str", str_getDiffList4)
    print(type(str_getDiffList4))

    print("Now it appended \n", str_getDiffList4)

    # send to the new list to the new category

    ConnectionToNeo4j.sendNewDifficultyList(userid, languageName, rewardState,
                                            str_getDiffList4)
    print(type(str_getDiffList4))
Ejemplo n.º 14
0
def generate_cv_questions():
    global grammer_corrected_pr0ject_question
    db = "CV"
    db2= "project"
    db3 ="project_d"
    # node_Count = ConnectionToNeo4j.getNodeCount(db)
    lang = 'en'
    q_list = []
    pro_list = []
    count = 1
    session = 0
    typo = "nonested"
    typo2 = "nontechnical"
    answer_validity = 0


    global question_number
    question_number = 0

#generates questions from the three sections
    while count<=3:
        session = session + 1
        print("session")
        print(session)
        session_no_string = str(session)
        session_node_count = ConnectionToNeo4j.session_Node_Count(db,session_no_string)
        print("this is ")
        print(session_node_count)
        node_id = ConnectionToNeo4j.get_node_id(db,session_no_string)

        for id in range(node_id,session_node_count+node_id):
            q_list.append(str(id))
        print(q_list)

        print("node_count")
        print(session_node_count)

        for question_no in range(session_node_count):

            print("question number")
            print(question_no)
            random_que = random.choice(q_list)
            print("random que")
            print(random_que)
            #new pars



            non_technical_question = ConnectionToNeo4j.cvQuestionGen(db,random_que)
            q_list.remove(random_que)
            print(q_list)
            print("jokes"+non_technical_question)

            question_number = question_number + 1

            actual_question = QuestionCreator.gen_Question(non_technical_question,question_number)
            AyeshSilenceDetection.silence_detect1(question_number)

            # print(actual_question)
            # parser = GingerIt()
            # grammer_corrected_question_list = parser.parse(actual_question)
            # grammer_corrected_question = grammer_corrected_question_list.get("result")
            # TextToSpeechConverter.text_to_speech(grammer_corrected_question, lang)

            # print(question_number)
            # print("hiiiiiiiiiiiiiiiiii printing count")
            if random_que == "6":
                global technology_list
                tech = SpeachToText.validation("", typo2,typo,"question"+str(question_number))[1]

                tech = NestedQuestionCreator.keywordSelector("",tech.lstrip(),"1","")

                print(tech)
                print("tech printed")
                technology_list = NestedQuestionCreator.nonTechnicalKeywordSeelector(tech)
                print("hello tech")
                print(technology_list)

            #gets an input to ask questions
            if random_que=="5":
                # voice_record = AudioRecorder.audio_recorder(question_number)
                # answer_validity = SpeachToText.validation("", typo2, typo, "question" + str(question_number))[0]
                project_question = ""
                random_proj_que = ""
                print(vari.userId)
                pro = ConnectionToNeo4j.getProjects(vari.userId)
                print("pro")
                print(pro)
                print("pro")
                if not  pro:
                    random_proj_que = "final year project"
                    print(random_proj_que)
                else:
                    random_proj_que = random.choice(pro)
                    print(random_proj_que)
                print(random_proj_que)

                project_question = ConnectionToNeo4j.cvQuestionProjectGen(db2, db3, random_proj_que, userid)
                question_number = question_number + 1

                print("project question")
                print(project_question)
                print("project question")


                print(" pro length")

                print(len(pro_list))
                print(" pro length")

                actual_project_question = QuestionCreator.gen_Question(project_question,question_number)
                AyeshSilenceDetection.silence_detect1(question_number)



            print("after a while")



        q_list = []
        count = count+1
def silence_detect1(QNumber):

    #Passing parameters
    sessionNumber = vari.sessionId
    userId = vari.userId


    #outputFile =AudioRecorder.audio_recorder()
    #print(outputFile)


    from pydub import AudioSegment, silence
    list_of_files = glob.glob('../Audio/*.wav') # * means all if need specific format then *.csv
    latest_file = max(list_of_files, key=os.path.getctime)
    print (latest_file)

    myaudio = intro = AudioSegment.from_wav(latest_file)  # 'audio/output14.wav'

    silence = silence.detect_silence(myaudio, min_silence_len=1000, silence_thresh=-30)
    # start and the end point of silence and display number of silent part in brackets
    # convert to sec
    silence = [((start / 1000), (stop / 1000)) for start, stop in silence]
    #1 Start and end points of silence parts in milliseconds
    print('#1 Start and end points of silence parts in milliseconds')
    print(silence)

    #2 Gap between start and the end point of the each silent part of the audio
    silence_gap = [(((stop) - (start)) / 1000) for start, stop in silence]
    print('#2 Gap between start and the end point of the each silent part of the audio')
    print(silence_gap)

    #3 identify silence parts with more than 3 milliseconds
    silence_gap2 = sorted(i for i in silence_gap if i >= 0.003)
    print('#3 identify silence parts with more than 3 milliseconds')
    print(silence_gap2)

    #convert the silent parts with milisecons to seconds
    silence_gap_list = [i * 1000 for i in silence_gap2]
    #4 silence gaps with three decimal places
    myFormattedList2 = ['%.3f' % elem for elem in silence_gap_list]
    print('#4 silent gaps in seconds with 3 decimal places')
    print(myFormattedList2)

    totalSilent=list(map(float,myFormattedList2))
    sumOfsilents = sum(totalSilent)
    print('#5 summation of all silent parts that are having more than 3 seconds')
    print(sumOfsilents)
    marksForsilents=round(25-(sumOfsilents*1.25))
    print('#6 marks for the silent part for a question')
    print(marksForsilents)

#After detecting the silence part of the audio clip it willmove to another folder vikum shold get the audio clip from that new folder.
    #path2 = 'D:/New Research/SmartInterviewer-Code/BackEnd/Database/movedAudio'
    #shutil.move(path1, path2)

    #passed from sarindi



    #------------------------------------------------------------
    string = "voiceq"
    questionNumber =QNumber
    questionOutput = string + str(questionNumber)
    print(questionOutput)
    print(type(questionOutput))

    #----------------------------------------------------
    qnumber = questionOutput
    voiceMark = str(marksForsilents)

    ConnectionToNeo4j.getQuestionNumberToSave(userId,sessionNumber,qnumber)




    ConnectionToNeo4j.saveVoiceMarks(userId,sessionNumber,qnumber, voiceMark)

    print(ConnectionToNeo4j.saveVoiceMarks(userId,sessionNumber,qnumber, voiceMark))
Ejemplo n.º 16
0
def generate_cv_questions():
    global grammer_corrected_pr0ject_question
    db = "CV"
    db2= "project"
    db3 ="project_d"
    # node_Count = ConnectionToNeo4j.getNodeCount(db)
    lang = 'en'
    q_list = []
    pro_list = []
    count = 1
    session = 0
    typo = "nonested"
    typo2 = "nontechnical"
    answer_validity = 0


    global question_number
    question_number = 0

    while count<=3:
        session = session + 1
        print("session")
        print(session)
        session_no_string = str(session)
        session_node_count = ConnectionToNeo4j.session_Node_Count(db,session_no_string)
        print("this is ")
        print(session_node_count)
        node_id = ConnectionToNeo4j.get_node_id(db,session_no_string)

        for id in range(node_id,session_node_count+node_id):
            q_list.append(str(id))
        print(q_list)

        print("node_count")
        print(session_node_count)

        for question_no in range(session_node_count):

            print("question number")
            print(question_no)
            random_que = random.choice(q_list)
            print("random que")
            print(random_que)
            #new pars



            non_technical_question = ConnectionToNeo4j.cvQuestionGen(db,random_que)
            q_list.remove(random_que)
            print(q_list)
            print("jokes"+non_technical_question)

            question_number = question_number + 1

            actual_question = QuestionCreator.gen_Question(non_technical_question,question_number)
            # print(actual_question)
            # parser = GingerIt()
            # grammer_corrected_question_list = parser.parse(actual_question)
            # grammer_corrected_question = grammer_corrected_question_list.get("result")
            # TextToSpeechConverter.text_to_speech(grammer_corrected_question, lang)

            # print(question_number)
            # print("hiiiiiiiiiiiiiiiiii printing count")



            if random_que=="5":
                # voice_record = AudioRecorder.audio_recorder(question_number)
                # answer_validity = SpeachToText.validation("", typo2, typo, "question" + str(question_number))[0]

                pro = ConnectionToNeo4j.getProjects(db, "5")
                # print(pro)
                for id in range (1,pro+1):
                    pro_list.append(str(id))
                # print(pro_list)


                random_proj_que = random.choice(pro_list)
                modify_random_proj_que = "p"+random_proj_que
                # print(modify_random_proj_que)

                project_question = ConnectionToNeo4j.cvQuestionProjectGen(db2,db3,modify_random_proj_que,userid)
                question_number = question_number + 1

                actual_project_question = QuestionCreator.gen_Question(project_question,question_number)
                # print(actual_project_question)
                # parser = GingerIt()
                # grammer_corrected_project_question_list = parser.parse(actual_project_question)
                # grammer_corrected_pr0ject_question = grammer_corrected_project_question_list.get("result")







                # TextToSpeechConverter.text_to_speech(grammer_corrected_pr0ject_question, lang)
                # print(question_number)
                # print("hiiiiiiiiiiiiiiiiii printing count")

                global technology_list
                tech = SpeachToText.validation("", typo2,typo,"question"+str(question_number))[1]

                tech = NestedQuestionCreator.keywordSelector("",tech.lstrip(),"1","")
                # print(tech)
                # print("tech printed")
                technology_list = NestedQuestionCreator.nonTechnicalKeywordSeelector(tech,modify_random_proj_que)
                # print("hello tech")
                # print(technology_list)
                # print("check validity")
                # answer_validity = input()

            print("after a while")

            # voice_record = AudioRecorder.audio_recorder(question_number)
            # answer_validity = SpeachToText.validation("", typo2,typo,"question"+str(question_number))[0]



            # while(answer_validity=="None" ):
            #     answer_validity = SpeachToText.validation("", typo2,typo,"question"+str(question_number))[0]




        q_list = []
        count = count+1
Ejemplo n.º 17
0
def keywordSelector(db,filtered_words_string,param,diff_level):
    db2 ="user_difficulty"
    db3 = "difficulty"
    db4 = "nested_difficulty"
    user_id = vari.userId
    print("diff_level")
    print(diff_level)
    print("diff_level")

    filtered_words_string = filtered_words_string.replace("'", " ")
    filtered_words = filtered_words_string.split(" ")
    print(filtered_words)
    print("filtered_words")


    global  topic_list
    topic_list = []

    global nested_keyword_list
    nested_keyword_list = []

    global nested_difficulty_list
    nested_difficulty_list = []

    global nes_keywords

    # print(filtered_words)
    unique_filtered_words = set()
    for val in filtered_words:
        lower_case_val = val.lower()
        unique_filtered_words.add(lower_case_val)
    print(unique_filtered_words)
    print("unique_filtered_words")

    for value in unique_filtered_words:
        if param == "2":
            print(db)
            print(value)
            topic_availability = ConnectionToNeo4j.getMatchingTopics(db,value)
            print(topic_availability)
            if topic_availability == True:
                topic_list.append(value)
        elif param == "1":
            topic_availability = ConnectionToNeo4j.getMatchingTopicsNonTech(value)
            print(topic_availability)
            if topic_availability == True:
                topic_list.append(value)
    print(topic_list)
    print("topic_list")
    # print(topic_list)
    if param == "1":
        topic_list = ",".join(topic_list)
        return topic_list


    if len(topic_list) > 0 and param=="2":
        for itt in range (len(topic_list)):
            random_keyword = random.choice(topic_list)
            nes_keywords=ConnectionToNeo4j.getMatchingNestedTopicId(db,random_keyword)
            print(random_keyword)
            print("random_keyword")
            nested_keyword_list = (nes_keywords.split(',' ))
            print(nested_keyword_list)
            print(nested_keyword_list)
            print("random_keyword")

            nes_diff_level = ConnectionToNeo4j.getNestedDiffLevelList(user_id,db2,db3,db4,db,diff_level)
            print("nes_diff_level")
            print(nes_diff_level)
            print("nes_diff_level")

            nested_difficulty_list = (nes_diff_level.split(',' ))


            print("nested_difficulty_list")
            print(nested_difficulty_list)
            print("nested_difficulty_list")

            selected_list = set(nested_difficulty_list) & set(nested_keyword_list)
            print("selected_list")
            print(selected_list)
            print("selected_list")
            selected_list = list(selected_list)
            print("selected_list")
            print(selected_list)
            print("selected_list")
            if not selected_list:
                return 0

            random_nes_que = random.choice(selected_list)
            print("random_nes_que")
            print(random_nes_que)
            print("random_nes_que")

            topic = ConnectionToNeo4j.getMatchingNestedTopic(db,random_keyword,random_nes_que)
            print("topic")
            print(topic)
            print("topic")

            return topic

    else:
        return 0
Ejemplo n.º 18
0
def question_gen():
    #difficulty level  generation
    global changed_know_list
    changed_know_list = []

    db2 = "user"
    db3 = "session"

    global diff_level
    diff_level = "easy"

    session_db = "session"

    userId = vari.userId
    sessionId = vari.sessionId
    question_number = NonTechnicalQuestions.question_number

    global qprinted
    qprinted = 0

    global taking_list
    taking_list = []

    global prev1_ans_result
    prev1_ans_result = 0.2

    global prev2_ans_result
    prev2_ans_result = 0.2

    global prev1_que_count
    prev1_que_count = 5

    global prev2_que_count
    prev2_que_count = 6

    global user_diff
    user_diff = "user_difficulty"

    global db_diff
    db_diff = "difficulty"

    q_list = []
    lang = 'en'
    tech_keywords = NonTechnicalQuestions.technology_list
    print(tech_keywords)
    print("hey")
    global nested_question_ccount
    nested_question_ccount = 2

    splitted_table_list = (tech_keywords.split(','))
    print(splitted_table_list)
    print("list is printed")
    splitted_table_list_length = len(splitted_table_list)
    stable_splitted_table_list_length = len(splitted_table_list)
    print("length")
    print(splitted_table_list_length)

    split_list_length = stable_splitted_table_list_length
    itteration_val = int(11 / split_list_length)
    itteration_value = math.floor(itteration_val)

    # get the nested value count after filling technologies
    rem_nested_count = 11 - (split_list_length * itteration_value)
    nested_question_ccount = nested_question_ccount + rem_nested_count
    print(nested_question_ccount)
    print("this is theeeeeeeeeeeeeeerem_nested_count")

    print("itt")
    print(itteration_value)

    while splitted_table_list_length >= 1:

        random_table = random.choice(splitted_table_list)
        print(random_table)

        splitted_table_list_length = splitted_table_list_length - 1
        print("length")
        print(splitted_table_list_length)
        splitted_table_list.remove(random_table)
        print(splitted_table_list)

        technical_node_count = ConnectionToNeo4j.getTechNodeCount(random_table)
        print(technical_node_count)
        q_list = []
        for id in range(1, technical_node_count + 1):
            q_list.append(id)
        print(q_list)

        for itt in range(itteration_value):
            print(itt)
            print("my itteration")
            print(itt)

            # difficulty level  selection
            if prev1_ans_result >= 0.5 and prev2_ans_result >= 0.5:
                diff_level = DifficultyLevelSelector.increase_difficulty_level(
                    diff_level)
            elif prev1_ans_result < 0.5 and prev2_ans_result < 0.5:
                diff_level = DifficultyLevelSelector.decrease_difficulty_level(
                    diff_level)
            print(diff_level)

            # get the list of nodes according to the difficulty level
            taking_list = DifficultyLevelSelector.adding_diff_level_val_list(
                userId, user_diff, db_diff, random_table, diff_level)
            print(taking_list)
            print("hi i am the taking list")

            # comparing two lists to get the nodes that are in the q_list
            changed_know_list = set(q_list) & set(taking_list)
            print("i know it is hereeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
            print(changed_know_list)
            changed_know_list = list(changed_know_list)

            if not changed_know_list:
                changed_know_list = q_list

            random_que = random.choice(changed_know_list)
            print(random_que)
            random_que_string = str(random_que)
            print(random_que_string)
            technical_question = ConnectionToNeo4j.technical_question_keyword(
                random_table, random_que_string)
            print("qu")
            print(technical_question)
            changed_know_list = []
            q_list.remove(random_que)
            print(q_list)
            print(changed_know_list)
            question_number = question_number + 1

            actual_question = TechnicalQuestionCreators.gen_Question(
                technical_question, question_number, "nonnested")
            parser = GingerIt()
            # CreateReward.rewardForQuestion(random_table,random_que,diff_level)

            # TextToSpeechConverter.text_to_speech(actual_question,lang)
            qprinted = qprinted + 1
            print("qprint")
            print(qprinted)
            print("qprint")

            prev1_que_count = prev1_que_count + 1
            prev2_que_count = prev2_que_count + 1

            # answer_validity = test.test()
            # answer_validity = input()

            # while (answer_validity == "null"):
            # print(vik_test_codes.question(question_number))

            # answer_validity = test.test()
            #answer_validity = input()

            if itt > 1 and nested_question_ccount > 0:
                filtered_words_string = SpeachToText.validation(
                    technical_question, "technical", "nonested",
                    "question" + str(question_number))
                nested = NestedQuestionCreator.keywordSelector(
                    random_table, filtered_words_string[1].lstrip(), "2",
                    diff_level)
                if nested != 0:
                    print("nested keyword value")
                    print(nested)
                    question_number = question_number + 1

                    actual_question = TechnicalQuestionCreators.gen_Question(
                        nested, question_number, "nested")
                    # TextToSpeechConverter.text_to_speech(actual_question, lang)
                    print(actual_question)

                    qprinted = qprinted + 1
                    print("qprint")
                    print(qprinted)
                    print("qprint")

                    prev1_que_count = prev1_que_count + 1
                    prev2_que_count = prev2_que_count + 1

                    nested_question_ccount = nested_question_ccount - 1
                    print(nested)

                    # answer_validity = test.test()
                    # answer_validity =input()
                    #
                    # while (answer_validity == "null"):
                    #
                    #
                    #     # answer_validity = test.test()
                    #     answer_validity = input()
                else:
                    print("when ignores")
                print("true")

            else:
                print("false")

            if itt == itteration_value - 1 and splitted_table_list_length == 1 and nested_question_ccount > 0:
                itteration_value = itteration_value + nested_question_ccount
                nested_question_ccount == 0

            p1_qno = str(prev1_que_count)
            p1_send_question = "question" + p1_qno
            print(p1_qno)

            p2_qno = str(prev2_que_count)
            p2_send_question = "question" + p2_qno
            print(p1_qno)
            print("this is prev one")
            print(prev1_que_count)
            print("this is prev")
            print(prev2_que_count)

            print("nooooooooooooooooooooooooooo")
            if prev1_que_count == 7:
                prev1_ans_result = 0.2
                prev2_ans_result = ConnectionToNeo4j.getQuestionMarks(
                    db2, db3, userId, sessionId, p2_send_question)
                prev2_ans_result = float(prev2_ans_result)
            else:
                prev1_ans_result = ConnectionToNeo4j.getQuestionMarks(
                    db2, db3, userId, sessionId, p1_send_question)
                prev2_ans_result = ConnectionToNeo4j.getQuestionMarks(
                    db2, db3, userId, sessionId, p2_send_question)

                prev1_ans_result = float(prev1_ans_result)
                prev2_ans_result = float(prev2_ans_result)

            print("this is prev marksssssssssssss")
            print(prev1_ans_result)
            print(p1_send_question)
            print(question_number)
            print("this is prev marksssssssssssss")

            print("this is prev marksssssssssssss")
            print(prev2_ans_result)
            print(p2_send_question)
            print(question_number)
            print("this is prev marksssssssssssss")

            # techs = NonTechnicalQuestions.technology_list
    # print(techs)
    # lang = 'en'
    # q_list = []
    # for id in range(1,5):
    #     q_list.append(str(id))
    #
    # print(q_list)
    #
    # for question_no  in range(4):
    #     time.sleep(5)
    #     random_que = random.choice(q_list)
    #     technical_question=ConnectionToNeo4j.ontologyQuestionGen(random_que)
    #     q_list.remove(random_que)
    #     actual_question = "What is "+technical_question+"?"
    #     TextToSpeechConverter.text_to_speech(actual_question, lang)
    #     print(actual_question)
    #


# question_gen()
Ejemplo n.º 19
0
def get_post_javascript_data1():
    print("lalala")

    un = str(request.form['username'])
    pw = str(request.form['password'])
    email = str(request.form['email'])

    regUserId = ConnectionToNeo4j.register(un,pw,email)

    #adding difficulty db
    availableTechnicalNode = ConnectionToNeo4j.getExistingTechnologies()
    print(availableTechnicalNode)
    # regUserId = ConnectionToNeo4j.getLastCreatedUid()
    node = ConnectionToNeo4j.genUserDiffLevel(regUserId)

    # availableTechnicalNodeList = (availableTechnicalNode.split(','))
    for itt in availableTechnicalNode:
        technicalNodeCnt = ConnectionToNeo4j.getTechNodeCount(itt)
        print(technicalNodeCnt)

        nodeCountValue = int(technicalNodeCnt / 3)
        print(nodeCountValue)
        changingNodeCountValue = nodeCountValue
        remainingValue = technicalNodeCnt - (nodeCountValue * 3)
        print(remainingValue)
        easyNodes = ""
        mediumNodes = ""
        hardNodes = ""

        exactCount = technicalNodeCnt

        while changingNodeCountValue > 0:
            easyNodes = easyNodes + "," + str(exactCount)
            exactCount = exactCount - 1
            changingNodeCountValue = changingNodeCountValue - 1
        print(easyNodes)
        easyNodes = easyNodes[1:]
        print(easyNodes)

        changingNodeCountValue = nodeCountValue

        print("nooooooooooooooooooooooooooooooo")
        while changingNodeCountValue > 0:
            mediumNodes = mediumNodes + "," + str(exactCount)
            exactCount = exactCount - 1
            changingNodeCountValue = changingNodeCountValue - 1
        print(mediumNodes)
        mediumNodes = mediumNodes[1:]
        print(mediumNodes)

        print("nooooooooooooooooooooooooooooooo")

        changingNodeCountValue = nodeCountValue + remainingValue
        print(changingNodeCountValue)
        while changingNodeCountValue > 0:
            hardNodes = hardNodes + "," + str(exactCount)
            exactCount = exactCount - 1
            changingNodeCountValue = changingNodeCountValue - 1
        print(hardNodes)
        hardNodes = hardNodes[1:]
        print(hardNodes)
        restResult = ConnectionToNeo4j.addDifficultyLevelsForTech(regUserId, itt, easyNodes, mediumNodes, hardNodes)
        if itt == "python":
            neseasy = "NES_019,NES_018,NES_015,NES_013,NES_008"
            nesMedium = "NES_017,NES_016,NES_014,NES_011"
            nesHard = "NES_012,NES_009,NES_010"
            restResult2 = ConnectionToNeo4j.addDiffLevelNestedNodesForTech(regUserId, itt, neseasy, nesMedium,nesHard)
        if itt == "java":
            neseasy = "NES_001,NES_002"
            nesMedium = "NES_003,NES_005"
            nesHard = "NES_004,NES_006"
            restResult3 = ConnectionToNeo4j.addDiffLevelNestedNodesForTech(regUserId, itt, neseasy, nesMedium,nesHard)
Ejemplo n.º 20
0
def get_post_cv_javascript_data():
    print("hello ")

    fname = str(request.form['flname'])
    usage = str(request.form['uage'])
    usschool = str(request.form['uschool'])
    usuni = str(request.form['uuni'])
    usdob = str(request.form['udob'])
    usemail = str(request.form['uemail'])
    ustpno = str(request.form['utpno'])
    usweak = str(request.form['uweak'])
    usstrengh = str(request.form['ustrength'])
    usidlcmp = str(request.form['uidcomp'])
    usftech = str(request.form['ufmtech'])
    usproone = str(request.form['uproone'])
    ustech1 = str(request.form['utech1'])
    usprotwo = str(request.form['uprotwo'])
    ustech2 = str(request.form['utech2'])

    techsAvailable = []
    infoRetList = []
    finalFamiliarTechList = []
    techWord_list = usftech.split(',')
    for techWord in techWord_list:
        techWord = techWord.lower()
        availability_node = ConnectionToNeo4j.getMatchingTopicsNonTech1(techWord)
        print(techWord)
        print(availability_node)
        if availability_node == True:
            print("available")
            techsAvailable.append(techWord)
            print(techsAvailable)
        elif availability_node == False:
            print("not available")
            if techWord == "c#":
                techWord = "csharp"
            elif techWord == "c++":
                techWord = "cplusplus"
            elif techWord == "c":
                techWord = "cprogramming"

            infoList = inforetrievel.inforetrievel(techWord)
            infoRet = infoList[0]
            print("returning ")
            print(infoRet)
            print("returning ")

            technicalNodeCnt = infoList[1]
            print("returning node count ")
            print(technicalNodeCnt)
            print("returning node count ")

            if infoRet != "0":
                infoRet = infoRet.lower()
                print(infoRetList)
                infoRetList.append(infoRet)
                print(infoRetList)
                # ##########################################3 new

                nodeCountValue = int(technicalNodeCnt / 3)
                print(nodeCountValue)
                changingNodeCountValue = nodeCountValue
                remainingValue = technicalNodeCnt - (nodeCountValue * 3)
                print(remainingValue)
                easyNodes = ""
                mediumNodes = ""
                hardNodes = ""

                exactCount = technicalNodeCnt

                while changingNodeCountValue > 0:
                    easyNodes = easyNodes + "," + str(exactCount)
                    exactCount = exactCount - 1
                    changingNodeCountValue = changingNodeCountValue - 1
                print(easyNodes)
                easyNodes = easyNodes[1:]
                print(easyNodes)

                changingNodeCountValue = nodeCountValue

                print("nooooooooooooooooooooooooooooooo")
                while changingNodeCountValue > 0:
                    mediumNodes = mediumNodes + "," + str(exactCount)
                    exactCount = exactCount - 1
                    changingNodeCountValue = changingNodeCountValue - 1
                print(mediumNodes)
                mediumNodes = mediumNodes[1:]
                print(mediumNodes)

                print("nooooooooooooooooooooooooooooooo")

                changingNodeCountValue = nodeCountValue + remainingValue
                print(changingNodeCountValue)
                while changingNodeCountValue > 0:
                    hardNodes = hardNodes + "," + str(exactCount)
                    exactCount = exactCount - 1
                    changingNodeCountValue = changingNodeCountValue - 1
                print(hardNodes)
                hardNodes = hardNodes[1:]
                print(hardNodes)

                restResult = ConnectionToNeo4j.addDifficultyLevelsForSpecificTech(infoRet, easyNodes, mediumNodes,hardNodes)

                # ########################################## new

    importlib.reload(infowhat)
    open('Controller/infowhat.py', 'w').close()
    fruits = ["global valusa\n", "valusa = 'fn'\n"]
    new_file = open("Controller/infowhat.py", mode="a+", encoding="utf-8")
    new_file.writelines(fruits)
    for line in new_file:
        print(line)




    finalFamiliarTechList = techsAvailable +infoRetList
    print(finalFamiliarTechList)
    finalFamiliarTech = ','.join(finalFamiliarTechList)
    print(finalFamiliarTech)
    # while finalFamiliarTechList[0] == ',':
    #     print("in")
    #     finalFamiliarTechList = finalFamiliarTechList[1:]
    #     print(finalFamiliarTechList)
    # stringLength = len(finalFamiliarTechList) - 1
    # while finalFamiliarTechList[stringLength] == ',':
    #     print("hahaa")
    #     finalFamiliarTechList = finalFamiliarTechList[:stringLength]
    # print(finalFamiliarTechList)

    importlib.reload(vari)
    uid = vari.userId

    validation = ConnectionToNeo4j.checkuserinnwadas(uid)

    if validation != True:
        fresult = ConnectionToNeo4j.createNewCv(uid,fname,usage,usschool,usuni,usdob,usemail,ustpno,usweak,usstrengh,usidlcmp,finalFamiliarTech,usproone,ustech1,usprotwo,ustech2)

    print(fname)
    pythondata = {'val':'jaja'}
    return json.dumps(pythondata)
Ejemplo n.º 21
0
def rewardForQuestion(languageName, subName, nodeId, difficultyLevel):
    print(languageName)
    print(subName)
    print(nodeId)
    print(difficultyLevel)

    print("ANURUDDHA RESULTS")
    print(languageName)
    print(nodeId)
    print(difficultyLevel)
    print(subName)

    importlib.reload(vari)
    userid = vari.userId

    # print(vari.Ftesting1(aa))
    # print(vari.Vtesting1(bb))
    # print(vari.Atesting1(cc))

    # facial = vari.Ftesting1(aa) #have to remove
    # voice = vari.Vtesting1(bb) #have to remove
    # answer = vari.Atesting1(cc) #have to remove

    facial = 20  #have to remove
    voice = 20  #have to remove
    answer = 38  #have to remove

    total = (facial + voice + answer)

    print("Total = ", total)
    total = int(total)

    if (0 < total <= 20):
        state = 1
        print("State = ", state)

    elif (21 < total <= 40):
        state = 2
        print("State = ", state)

    elif (41 < total <= 60):
        state = 3
        print("State = ", state)

    elif (61 < total <= 80):
        state = 4
        print("State = ", state)

    else:
        state = 5
        print("State = ", state)

    # -----------------------------------------------------------------------------------
    # Get the latest updated q-table from ontology - only for shown

    print("--------Output 1-------------------------------------------")
    print("Latest updated q-table regarding asked knowledge area \n",
          ConnectionToNeo4j.createQtable1(languageName, subName))
    print(type(ConnectionToNeo4j.createQtable1(languageName, subName)))

    # data = R
    # print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")

    # Get the String array matrix from ontology - split
    # I = np.array(ConnectionToNeo4j.createQtable1(languageName, subName)).tolist()
    # Z = I.split(" ")
    QuestionAsked = "new"
    # print("Z-spit krapu 1 \n", Z)
    # print(type(Z)) --> Gives List

    # to remove the []
    # number = " ".join(Z)

    # print("this remove[] \n", number)
    # print(type(number)) --> Gives String

    if QuestionAsked == "existing":
        R = ConnectionToNeo4j.createQtable1(languageName, subName)

    else:
        R = np.matrix([[0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0],
                       [0.0, 0.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.0, 0.0, 0.0],
                       [0.0, 0.0, 0.0, 0.0, 0.0]])

    print(
        "------Rewarding process is starting----------------------------------------"
    )
    # Q matrix
    Q = np.matrix(np.zeros([5, 5]))

    if state == 5:
        R[0, 4] = total
    elif state == 4:
        R[1, 3] = total
    elif state == 3:
        R[2, 2] = total
    elif state == 2:
        R[3, 1] = total
    else:
        R[4, 0] = total

    # Gamma (learning parameter).
    gamma = 0.8

    # Initial state
    if state == 5:
        initial_state = 4
    else:
        initial_state = state

    # initial_state = state
    # This function returns all available actions in the state given as an argument
    def available_actions(state):
        current_state_row = R[state, ]
        av_act = np.where(current_state_row >= 0)[1]
        return av_act

    # Get available actions in the current state
    available_act = available_actions(initial_state)

    # This function chooses at random which action to be performed within the range
    def sample_next_action(available_actions_range):
        next_action = int(np.random.choice(available_act, 1))
        return next_action

    # Sample next action to be performed
    action = sample_next_action(available_act)

    # This function updates the Q matrix
    def update(current_state, action, gamma):
        max_index = np.where(Q[action, ] == np.max(Q[action, ]))[1]

        if max_index.shape[0] > 1:
            max_index = int(np.random.choice(max_index, size=1))
        else:
            max_index = int(max_index)
        max_value = Q[action, max_index]

        # Q learning formula - Reward Function
        Q[current_state, action] = R[current_state, action] + gamma * max_value

    # Update Q matrix
    update(initial_state, action, gamma)

    # -------------------------------------------------------------------------------
    # Create the reward value

    # iterarte the process
    for i in range(100):
        current_state = np.random.randint(0, int(Q.shape[0]))
        available_act = available_actions(current_state)
        action = sample_next_action(available_act)
        update(current_state, action, gamma)

    print("New q table \n", Q)

    # ----------------------------------------------------------------------------------------------------------------
    # Save the Q-metrix in text file

    print(" Maximum reward value:")
    print(np.max(Q))
    T = Q * 100 / np.max(Q)
    print("\n Convert q-table to precentage scale")
    print(T)
    print(type(T))
    # np.savetxt('Database/text.txt', T, fmt='%f')

    print("--------Output 2-------------------------------------------")
    print("Find the Difficulty level index, containing the max reward")

    newOne = np.unravel_index(np.argmax(T, axis=None), T.shape)
    # print(type(newOne)) --> Gives Tuple
    print(newOne)

    [m, n] = newOne
    print(n)
    # print(type(n)) --> Gives numpy.int32
    convertStr = str(n)
    # print(type(convertStr)) --> Gives String

    if convertStr == "0" or convertStr == "1":
        rewardState = "hard"

    elif convertStr == "2":
        rewardState = "medium"

    else:
        rewardState = "easy"

    print(rewardState)

    # -------------------------------------------------------
    # send to ontology

    # -------------------------------------------------------
    # send to ontology
    print("\n Then the updated q-table is sent to the ontology")

    qTableCreated = str(T)
    print(type(qTableCreated))

    ConnectionToNeo4j.sendQtable(languageName, subName, qTableCreated)
    # -------------------------------------------------------------------------------

    # --update the ontology---------------------------
    print("--------Output 3-------------------------------------------")
    print("Get the existing difficulty list \n")

    print(
        ConnectionToNeo4j.getDifficultyList(userid, languageName,
                                            difficultyLevel))

    getDiffList = str(
        ConnectionToNeo4j.getDifficultyList(userid, languageName,
                                            difficultyLevel))
    print(getDiffList)
    # print(type(getDiffList))

    getDiffList2 = getDiffList.split(',')
    getDiffList2.remove(str(nodeId))
    getDiffList3 = list(map(int, getDiffList2))
    print("then removed node and int it \n", getDiffList3)
    # print(type(getDiffList3)) --> Gives list
    str_getDiffList3 = ','.join(str(e) for e in getDiffList3)
    print("Convert to String to save \n", str_getDiffList3)
    # print(type(str_getDiffList3)) --> Gives string

    # update the existing category with new value
    ConnectionToNeo4j.sendExistingDifficultyList(userid, languageName,
                                                 difficultyLevel,
                                                 str_getDiffList3)

    print("\n --------Output 4-------------------------------------------")
    print("Get the new difficulty list to update \n")

    # get the new category list

    getNewList = ConnectionToNeo4j.getNewRewardList(userid, languageName,
                                                    rewardState)
    print(ConnectionToNeo4j.getNewRewardList(userid, languageName,
                                             rewardState))
    # print(type(getNewList)) --> Gives string
    # print(type(nodeId)) --> Gives Integer

    str_nodeId = str(nodeId)
    # print(type(str_nodeId)) --> Gives String

    getnewList = getNewList.split(',')
    getnewList.append(str_nodeId)
    print("append new nod = ", getnewList)

    str_getDiffList4 = ','.join(str(e) for e in getnewList)
    print("converted to string =", str_getDiffList4)

    print("Appended new list \n", str_getDiffList4)

    # send to the new list to the new category

    ConnectionToNeo4j.sendNewDifficultyList(userid, languageName, rewardState,
                                            str_getDiffList4)
Ejemplo n.º 22
0
def chartsa():

    val = ConnectionToNeo4j.getsessionmarks1()


    return json.dumps(val)
def question_gen():
    #difficulty level  generation
    global changed_know_list
    changed_know_list = []

    db2 = "user"
    db3 = "session"

    global diff_level
    diff_level = "easy"

    session_db = "session"
    importlib.reload(vari)
    userId = vari.userId
    sessionId = vari.sessionId
    question_number = NonTechnicalQuestions.question_number

    global qprinted
    qprinted = 0

    global taking_list
    taking_list= []

    global prev1_ans_result
    prev1_ans_result= 0.2

    global prev2_ans_result
    prev2_ans_result= 0.2

    global prev1_que_count
    # prev1_que_count = 5
    prev1_que_count = 6


    global prev2_que_count
    # prev2_que_count = 6
    prev2_que_count = 7

    global user_diff
    user_diff = "user_difficulty"

    global db_diff
    db_diff = "difficulty"
    global different_change_list
    different_change_list= "False"



    q_list = []
    lang = 'en'
    tech_keywords = NonTechnicalQuestions.technology_list
    print(tech_keywords)
    print("hey")
    global nested_question_ccount
    nested_question_ccount = 2
    global final_itteration_value



    #decide the count of questions that should be generated from one technology
    splitted_table_list = (tech_keywords.split(','))
    # splitted_table_list.append("java")

    print(splitted_table_list)
    print("list is printed")
    splitted_table_list_length = len(splitted_table_list)
    stable_splitted_table_list_length = len(splitted_table_list)
    print("length")
    print(splitted_table_list_length)

    split_list_length = stable_splitted_table_list_length
    itteration_val = int(11 / split_list_length)
    itteration_value = math.floor(itteration_val)

    final_itteration_value = itteration_value


    # get the nested value count after filling technologies
    rem_nested_count = 11 - (split_list_length * itteration_value)
    nested_question_ccount = nested_question_ccount + rem_nested_count
    print(nested_question_ccount)
    print("this is theeeeeeeeeeeeeeerem_nested_count")

    print("itt")
    print(itteration_value)


#selects a keyword from technology list
    while splitted_table_list_length >=1:


        random_table = random.choice(splitted_table_list)
        print(random_table)


        splitted_table_list_length = splitted_table_list_length-1
        print("length")
        print(splitted_table_list_length)
        splitted_table_list.remove(random_table)
        print(splitted_table_list)

        technical_node_count = ConnectionToNeo4j.getTechNodeCount(random_table)
        print(technical_node_count)
        q_list = []
        for id in range(1, technical_node_count + 1):
            q_list.append(id)
        print(q_list)

#generate questions according to question count
        # for itt in range(itteration_value):
        while itteration_value>0:
            print(itteration_value)
            print("my itteration")
            print(itteration_value)
            itteration_value = itteration_value-1


            p1_qno = str(prev1_que_count)
            p1_send_question = "question"+p1_qno
            print(p1_qno)

            p2_qno = str(prev2_que_count)
            p2_send_question = "question"+p2_qno
            print(p1_qno)
            print("this is prev one")
            print(prev1_que_count)
            print("this is prev")
            print(prev2_que_count)

            print("nooooooooooooooooooooooooooo")

            if  prev1_que_count != 6 and prev2_que_count != 7 and prev1_que_count == 7 and question_number < 20:

                prev1_ans_result = 0.2
                prev2_ans_result = ConnectionToNeo4j.getQuestionMarks(db2,db3,userId,sessionId,p2_send_question)
                prev2_ans_result = float(prev2_ans_result)
                print("javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                print(prev1_que_count)
                print(prev2_que_count)

                print("javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                print("this is prev marksssssssssssss")
                print(prev1_ans_result)
                print(p1_send_question)
                print(question_number)
                print("this is prev marksssssssssssss")

                print("this is prev marksssssssssssss")
                print(prev2_ans_result)
                print(p2_send_question)
                print(question_number)
                print("this is prev marksssssssssssss")

            elif prev1_que_count != 6 and prev2_que_count != 7 and question_number < 20 :

                prev1_ans_result = ConnectionToNeo4j.getQuestionMarks(db2,db3,userId,sessionId,p1_send_question)
                prev2_ans_result = ConnectionToNeo4j.getQuestionMarks(db2,db3,userId,sessionId,p2_send_question)

                prev1_ans_result = float(prev1_ans_result)
                prev2_ans_result = float(prev2_ans_result)
                print("javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                print(prev1_que_count)
                print(prev2_que_count)

                print("javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                print("this is prev marksssssssssssss")
                print(prev1_ans_result)
                print(p1_send_question)
                print(question_number)
                print("this is prev marksssssssssssss")

                print("this is prev marksssssssssssss")
                print(prev2_ans_result)
                print(p2_send_question)
                print(question_number)
                print("this is prev marksssssssssssss")

            if prev1_que_count != 6 and prev2_que_count != 7 and prev1_que_count == 7 and question_number < 20:

                prev1_ans_result = 0.2
                prev2_ans_result = ConnectionToNeo4j.getQuestionMarks(db2, db3, userId, sessionId, p2_send_question)
                prev2_ans_result = float(prev2_ans_result)
                print("javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                print(prev1_que_count)
                print(prev2_que_count)

                print("javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                print("this is prev marksssssssssssss")
                print(prev1_ans_result)
                print(p1_send_question)
                print(question_number)
                print("this is prev marksssssssssssss")

                print("this is prev marksssssssssssss")
                print(prev2_ans_result)
                print(p2_send_question)
                print(question_number)
                print("this is prev marksssssssssssss")

            elif prev1_que_count != 6 and prev2_que_count != 7 and question_number < 20 :

                prev1_ans_result = ConnectionToNeo4j.getQuestionMarks(db2, db3, userId, sessionId, p1_send_question)
                prev2_ans_result = ConnectionToNeo4j.getQuestionMarks(db2, db3, userId, sessionId, p2_send_question)

                prev1_ans_result = float(prev1_ans_result)
                prev2_ans_result = float(prev2_ans_result)
                print("javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                print(prev1_que_count)
                print(prev2_que_count)

                print("javaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
                print("this is prev marksssssssssssss")
                print(prev1_ans_result)
                print(p1_send_question)
                print(question_number)
                print("this is prev marksssssssssssss")

                print("this is prev marksssssssssssss")
                print(prev2_ans_result)
                print(p2_send_question)
                print(question_number)
                print("this is prev marksssssssssssss")

            # difficulty level  selection
            if prev1_ans_result >= 0.5 and prev2_ans_result >= 0.5 and QuesType.qTypeChange == 'change':
                diff_level = DifficultyLevelSelector.increase_difficulty_level(diff_level)
            elif prev1_ans_result < 0.5 and prev2_ans_result < 0.5 and QuesType.qTypeChange == 'change':
                diff_level = DifficultyLevelSelector.decrease_difficulty_level(diff_level)
            print(diff_level)

            if prev1_ans_result >= 0.5 and prev2_ans_result >= 0.5 and QuesType.qTypeChange == 'continueSame':
                diff_level = DifficultyLevelSelector.increase_difficulty_level(diff_level)

            print(diff_level)

            # get the list of nodes according to the difficulty level
            taking_list = DifficultyLevelSelector.adding_diff_level_val_list(userId, user_diff,db_diff, random_table, diff_level)
            print(taking_list)
            print(taking_list)
            print("hi i am the taking list")

            # comparing two lists to get the nodes that are in the q_list
            changed_know_list = set(q_list) & set(taking_list)
            print("i know it is hereeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
            print(changed_know_list)

            changed_know_list = list(changed_know_list)
            # changed_know_list = None

            if not changed_know_list:
                changed_know_list = q_list
                different_change_list = "True"

            print(changed_know_list)
            print(changed_know_list)
            print("changed_know_list")

            random_que = random.choice(changed_know_list)
            print(random_que)

            random_que_string = str(random_que)
            print(random_que_string)

            #changes the difficulty level if there are no nodes availabble for the exisisting difficulties
            if different_change_list == "True":
                diff_level = DifficultyLevelSelector.change_difficulty_level(random_que_string,random_table)
                print("diffffffffff")
                print(diff_level)
                print("difffffffffffffffffff")

            technical_question = ConnectionToNeo4j.technical_question_keyword(random_table,random_que_string)
            print("qu")
            print(technical_question)
            changed_know_list = []
            q_list.remove(random_que)
            print(q_list)
            print(changed_know_list)
            question_number = question_number+1


            actual_question = TechnicalQuestionCreators.gen_Question(technical_question,question_number,"nonnested")
            AyeshSilenceDetection.silence_detect1(question_number)

            parser = GingerIt()

            #creates the difficulty levels
            CreateReward.rewardForQuestion(random_table,random_que_string,random_que,diff_level)

             # TextToSpeechConverter.text_to_speech(actual_question,lang)
            qprinted = qprinted+1;
            print("qprint")
            print(qprinted)
            print("qprint")


            prev1_que_count = prev1_que_count+1
            prev2_que_count = prev2_que_count+1

            # answer_validity = test.test()
            # answer_validity = input()

            # while (answer_validity == "null"):
                # print(vik_test_codes.question(question_number))

                # answer_validity = test.test()
                #answer_validity = input()

            # if itt>1 and nested_question_ccount>0:

            #generates nested questions if keyword are available
            if itteration_value > 1 and nested_question_ccount > 0:

                filtered_words_string =SpeachToText.validation(technical_question, "technical","nonested","question"+str(question_number))
                nested = NestedQuestionCreator.keywordSelector(random_table,filtered_words_string[1].lstrip(),"2",diff_level)
                if nested != 0:
                    print("nested keyword value")
                    print(nested)
                    question_number = question_number + 1

                    actual_question = TechnicalQuestionCreators.gen_Question(nested,question_number,"nested")
                    AyeshSilenceDetection.silence_detect1(question_number)

                    # TextToSpeechConverter.text_to_speech(actual_question, lang)
                    print(actual_question)

                    qprinted = qprinted + 1;
                    print("qprint")
                    print(qprinted)
                    print("qprint")

                    prev1_que_count = prev1_que_count + 1
                    prev2_que_count = prev2_que_count + 1

                    nested_question_ccount = nested_question_ccount - 1
                    print(nested)

                else:
                    print("when ignores")
                print("true")

            else:
                print("false")

            #gets the correct question number for a sesson if no nested questions
            # if itt == itteration_value-1 and splitted_table_list_length == 1 and nested_question_ccount>0 :
            if  itteration_value == 1 and splitted_table_list_length == 0 and nested_question_ccount > 0:
                itteration_value = itteration_value + 1

                # itteration_value = itteration_value + nested_question_ccount
                nested_question_ccount = nested_question_ccount - 1
                print("it is trueeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")




            # if prev1_que_count == 7 and question_number<20:
            #get the result of the previous two questions




        itteration_value = final_itteration_value