Example #1
0
async def __search_method2(texts, answers, reverse):
    """
    Return the answer with the maximum/minimum number of keyword occurrences in the texts.
    :param texts: List of text to analyze
    :param answers: List of answers
    :param reverse: True if the best answer occurs the least, False otherwise
    :return: Answer whose keywords occur most/least in the texts
    """
    print("Running method 2")
    counts = {
        answer: {keyword: 0
                 for keyword in search.find_keywords(answer)}
        for answer in answers
    }

    for text in texts:
        for keyword_counts in counts.values():
            for keyword in keyword_counts:
                keyword_counts[keyword] += len(re.findall(
                    f" {keyword} ", text))

    print(counts)
    counts_sum = {
        answer: sum(keyword_counts.values())
        for answer, keyword_counts in counts.items()
    }

    if not all(c == 0 for c in counts_sum.values()):
        return min(counts_sum, key=counts_sum.get) if reverse else max(
            counts_sum, key=counts_sum.get)
    return ""
Example #2
0
async def answer_question(question, original_answers):
    print("Searching")
    start = time.time()

    answers = []
    for ans in original_answers:
        answers.append(ans.translate(punctuation_to_none))
        answers.append(ans.translate(punctuation_to_space))
    answers = list(dict.fromkeys(answers))
    logging.info(question)
    logging.info(original_answers)

    question_lower = question.lower()

    reverse = "NOT" in question or\
              ("least" in question_lower and "at least" not in question_lower) or\
              "NEVER" in question

    quoted = re.findall('"([^"]*)"', question_lower)  # Get all words in quotes
    no_quote = question_lower
    for quote in quoted:
        no_quote = no_quote.replace(f"\"{quote}\"", "1placeholder1")

    question_keywords = search.find_keywords(no_quote)
    for quote in quoted:
        question_keywords[question_keywords.index("1placeholder1")] = quote

    logging.info(question_keywords)
    await asyncio.gather(
        search_method1_2_stub(question_keywords, answers, reverse),
        # search_method3_stub(question_keywords, quoted, question_lower, question, original_answers, reverse)
    )

    print(f"Search took {time.time() - start} seconds")
Example #3
0
async def answer_question(question, original_answers):
    print("Searching")
    start = time.time()

    answers = []
    for ans in original_answers:
        answers.append(ans.translate(punctuation_to_none))
        answers.append(ans.translate(punctuation_to_space))
    answers = list(dict.fromkeys(answers))
    print(answers)

    question_lower = question.lower()

    reverse = "NOT" in question or\
              ("least" in question_lower and "at least" not in question_lower) or\
              "NEVER" in question

    quoted = re.findall('"([^"]*)"', question_lower)  # Get all words in quotes
    no_quote = question_lower
    for quote in quoted:
        no_quote = no_quote.replace(f"\"{quote}\"", "1placeholder1")

    question_keywords = search.find_keywords(no_quote)
    for quote in quoted:
        question_keywords[question_keywords.index("1placeholder1")] = quote

    print(question_keywords)
    search_results = await search.search_google("+".join(question_keywords), 5)
    print(search_results)

    search_text = [x.translate(punctuation_to_none) for x in await search.get_clean_texts(search_results)]

    best_answer = await __search_method1(search_text, answers, reverse)
    if best_answer == "":
        best_answer = await __search_method2(search_text, answers, reverse)
    print(f"{Fore.GREEN}{best_answer}{Style.RESET_ALL}\n")

    # Get key nouns for Method 3
    key_nouns = set(quoted)

    if len(key_nouns) == 0:
        q_word_location = -1
        for q_word in ["what", "when", "who", "which", "whom", "where", "why", "how"]:
            q_word_location = question_lower.find(q_word)
            if q_word_location != -1:
                break

        if q_word_location > len(question) // 2 or q_word_location == -1:
            key_nouns.update(search.find_nouns(question, num_words=5))
        else:
            key_nouns.update(search.find_nouns(question, num_words=5, reverse=True))

        key_nouns -= {"type"}

    key_nouns = [noun.lower() for noun in key_nouns]
    print(f"Question nouns: {key_nouns}")
    answer3 = await __search_method3(list(set(question_keywords)), key_nouns, original_answers, reverse)
    print(f"{Fore.GREEN}{answer3}{Style.RESET_ALL}")

    print(f"Search took {time.time() - start} seconds")
Example #4
0
async def answer_question(question, original_answers, q_number, q_count):
    print("Searching")
    start = time.time()

    answers = []
    for ans in original_answers:
        answers.append(ans.translate(punctuation_to_none))
        answers.append(ans.translate(punctuation_to_space))
    answers = list(dict.fromkeys(answers))
    print(answers)

    question_lower = question.lower()

    reverse = "NOT" in question or\
              ("least" in question_lower and "at least" not in question_lower) or\
              "NEVER" in question

    quoted = re.findall('"([^"]*)"', question_lower)  # Get all words in quotes
    no_quote = question_lower
    for quote in quoted:
        no_quote = no_quote.replace(f"\"{quote}\"", "1placeholder1")

    question_keywords = search.find_keywords(no_quote)
    for quote in quoted:
        question_keywords[question_keywords.index("1placeholder1")] = quote

    print(question_keywords)
    search_results = await search.search_google("+".join(question_keywords), 5)
    print(search_results)

    search_text = [
        x.translate(punctuation_to_none)
        for x in await search.get_clean_texts(search_results)
    ]

    best_answer, c = await __search_method1(search_text, answers, reverse)
    if best_answer == "":
        best_answer, c = await __search_method2(search_text, answers, reverse)

    if best_answer != "":
        print(f"{Fore.GREEN}{best_answer}{Style.RESET_ALL}\n")
        title = f"Question {q_number} out of {q_count} ============ Method1=============="
        answer = f"{c}\n **best answer: {best_answer}**"
        ans = Webhook(
            "https://discordapp.com/api/webhooks/454166751525994496/c1oeJxqmO_ysy0ricw78rPcTlDrpauISrxYKWe0-xyds7lUU1Z49JYFPa8QMEQPwSDru",
            color=111111)
        ans.set_title(title=title)
        ans.set_desc(answer)
        ans.post()
    # Get key nouns for Method 3
    key_nouns = set(quoted)

    q_word_location = search.find_q_word_location(question_lower)
    if len(key_nouns) == 0:
        if q_word_location > len(question) // 2 or q_word_location == -1:
            key_nouns.update(search.find_nouns(question, num_words=5))
        else:
            key_nouns.update(
                search.find_nouns(question, num_words=5, reverse=True))

        key_nouns -= {"type"}

    # Add consecutive capitalised words (Thanks talentoscope!)
    key_nouns.update(
        re.findall(
            "([A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+)", " ".join([
                w for idx, w in enumerate(question.split(" "))
                if idx != q_word_location
            ])))

    key_nouns = {noun.lower() for noun in key_nouns}
    print(f"Question nouns: {key_nouns}")
    answer3, k, n = await __search_method3(list(set(question_keywords)),
                                           key_nouns, original_answers,
                                           reverse)
    title = f"Question {q_number} out of {q_count} ============ Method2=============="
    answer = f"{k}\n{n}\n **best answer: {answer3}**"
    ans2 = Webhook(
        "https://discordapp.com/api/webhooks/454166751525994496/c1oeJxqmO_ysy0ricw78rPcTlDrpauISrxYKWe0-xyds7lUU1Z49JYFPa8QMEQPwSDru",
        color=111111)
    ans2.set_title(title=title)
    ans2.set_desc(answer)
    ans2.post()
    print(f"{Fore.GREEN}{answer3}{Style.RESET_ALL}")

    print(f"Search took {time.time() - start} seconds")
Example #5
0
async def answer_question(question, original_answers):
    print("Searching")
    start = time.time()

    answers = []
    for ans in original_answers:
        answers.append(ans.translate(punctuation_to_none))
        answers.append(ans.translate(punctuation_to_space))
    answers = list(dict.fromkeys(answers))
    print(answers)

    question_lower = question.lower()


    reverse = "NOT" in question or\
              ("least" in question_lower and "at least" not in question_lower) or\
              "NEVER" in question
    if reverse == False and "NICHT" in question or reverse == False and " kein" in question_lower:
        reverse = True
    else:
        reverse = False

    #Detecting Possible Inaccuracies#
    inaccurate = False
    for o in original_answers:
        if o.lower() in question_lower:
            inaccurate = True
    #################################

    quoted = re.findall('"([^"]*)"', question_lower)  # Get all words in quotes
    no_quote = question_lower
    for quote in quoted:
        no_quote = no_quote.replace("\"%s\"" % quote, "1placeholder1")

    question_keywords = search.find_keywords(no_quote)
    for quote in quoted:
        question_keywords[question_keywords.index("1placeholder1")] = quote

    print(question_keywords)
    search_results = await search.search_google("+".join(question_keywords), 7)
    print(search_results)

    search_text = [
        x.translate(punctuation_to_none)
        for x in await search.get_clean_texts(search_results)
    ]

    best_answer = await __search_method1(search_text, answers, reverse)
    toWrite = "\n" + question + "\n"
    if inaccurate == True:
        toWrite = toWrite + "*Bot Highly Likely To Pick Wrong Answer For This Question Due To Answer Being In Question*\n"
    if best_answer == "":
        toWrite = toWrite + "Method 1: *inconclusive*"

        best_answer, points = await __search_method2(search_text, answers,
                                                     reverse)
        best_answer, points = str(best_answer), str(points)
        if best_answer != "":

            toWrite = toWrite + "\nMethod 1.2: " + best_answer + "\n" + points
        else:
            toWrite = toWrite + "\nMethod 1.2: *inconclusive*\n" + points
    else:
        toWrite = toWrite + "\nMethod 1: " + best_answer

    with open("uk.txt", "w") as uk:
        uk.write(toWrite)

    start_new_thread(runW, (
        "https://discordapp.com/api/webhooks/463095598514438144/itml2ezy3zOenC_gOYmyJxoNzBfOjE1wMelFcg5cKFGA0kJmd88AFdPRffOGJNOCvixW",
        toWrite + " :white_check_mark: \n\n"))
    start_new_thread(runW, (
        "https://discordapp.com/api/webhooks/454396453474009098/S1VOpB5cOGMix4wyrmNEf17DYUQ3ey6UE7nR_zn1E1x1Rj7OzkBHzJj2G5ur2C2LBLT6",
        toWrite + " :white_check_mark: \n\n"))

    if best_answer != "":
        print(Fore.GREEN + best_answer + Style.RESET_ALL + "\n")
Example #6
0
async def answer_question(question, original_answers):
    print("Searching")
    start = time.time()

    answers = []
    for ans in original_answers:
        answers.append(ans.translate(punctuation_to_none))
        answers.append(ans.translate(punctuation_to_space))
    answers = list(dict.fromkeys(answers))
    print(answers)

    question_lower = question.lower()

    reverse = "NOT" in question or\
              ("least" in question_lower and "at least" not in question_lower) or\
              "NEVER" in question

    quoted = re.findall('"([^"]*)"', question_lower)  # Get all words in quotes
    no_quote = question_lower
    for quote in quoted:
        no_quote = no_quote.replace(f"\"{quote}\"", "1placeholder1")

    question_keywords = search.find_keywords(no_quote)
    for quote in quoted:
        question_keywords[question_keywords.index("1placeholder1")] = quote

    print(question_keywords)
    search_results = await search.search_google("+".join(question_keywords), 5)
    print(search_results)

    search_text = [
        x.translate(punctuation_to_none)
        for x in await search.get_clean_texts(search_results)
    ]

    awnser1 = await __search_method2(search_text, answers, reverse)
    if awnser1 != "":
        print(f"{Fore.GREEN}{awnser1}{Style.RESET_ALL}\n")

    # Get key nouns for Method 3
    key_nouns = set(quoted)

    q_word_location = search.find_q_word_location(question_lower)
    if len(key_nouns) == 0:
        if q_word_location > len(question) // 2 or q_word_location == -1:
            key_nouns.update(search.find_nouns(question, num_words=5))
        else:
            key_nouns.update(
                search.find_nouns(question, num_words=5, reverse=True))

        key_nouns -= {"type"}

    # Add consecutive capitalised words (Thanks talentoscope!)
    key_nouns.update(
        re.findall(
            "([A-Z][a-z]+(?=\s[A-Z])(?:\s[A-Z][a-z]+)+)", " ".join([
                w for idx, w in enumerate(question.split(" "))
                if idx != q_word_location
            ])))

    key_nouns = {noun.lower() for noun in key_nouns}
    print(f"Question nouns: {key_nouns}")
    answer3 = await __search_method3(list(set(question_keywords)), key_nouns,
                                     original_answers, reverse)
    print(f"{Fore.GREEN}{answer3}{Style.RESET_ALL}")

    print(f"Search took {time.time() - start} seconds")