# This file was generated by the Tkinter Designer by <NAME>
# https://github.com/ParthJadhav/Tkinter-Designer
import analysis as an

import os
from tensorflow import keras
from pathlib import Path
import methods
# from tkinter import *
# Explicit imports to satisfy Flake8
from tkinter import *
import tkinter as tk
import numpy as np
import pandas as pd
import csv
import analysis as an
import methods
from matplotlib import pyplot as plt
import sys
import warnings
import math
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical

warnings.filterwarnings("ignore")
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")

modelc = keras.models.load_model("models/sdss/word/word_sdss_cnn_dataset_cpu_time.h5")
modele = keras.models.load_model("models/sdss/word/word_sdss_cnn_dataset_error.h5")
modela = keras.models.load_model("models/sdss/word/word_sdss_cnn_dataset_answer_size.h5")





from contextlib import contextmanager, redirect_stderr, redirect_stdout
from os import devnull


@contextmanager
def suppress_stdout_stderr():
    """A context manager that redirects stdout and stderr to devnull"""
    with open(devnull, 'w') as fnull:
        with redirect_stderr(fnull) as err, redirect_stdout(fnull) as out:
            yield (err, out)


def readSDSS():
    # used the dollar sign to denote the query statement due to confusion with the quotation marks
    data = pd.read_csv("SDSS_100K_d_mix.csv", delimiter=',', engine='python', encoding='latin1', quotechar="$",
                       error_bad_lines=False)
    return data


def drop_er(data):
    count = 0

    for i in data.rows:
        if i >= 99999999:
            data = data.drop([count])
        count += 1

    count = 0

    for i in data.busy:
        if i >= 100000000:
            data = data.drop([count])
        count += 1

    return data


data = readSDSS()
data = drop_er(data)
X_CONST = data.statement.values
workload_an = an.Analiser(data,True)
ch, b, c, d, e, f, g, h, i, j = workload_an.analisis(data)


def preprocess_for_neural_net_models_for_gui(X_train: np.array, token_level: str, ma=0):
    max_words = 3000
    if "word" in token_level:

        for i in range(0, X_train.shape[0]):
            if not isinstance(X_train[i], str):
                X_train[i] = str(X_train[i])

            X_train[i] = X_train[i].lower()
            # regular expression to replace all digits with <d> token but not alphanumerics
            X_train[i] = re.sub(r'\b[0-9]+\b|\s', ' <d> ', X_train[i])

        phrase_len = data.statement.apply(lambda p: len(str(p).split(' ')))
    else:
        for i in range(0, X_train.shape[0]):
            if not isinstance(X_train[i], str):
                X_train[i] = str(X_train[i])

            X_train[i] = X_train[i].lower()

        phrase_len = data.statement.apply(lambda p: len(str(p)))

    max_phrase_len = phrase_len.max()
    if ma != 0: max_phrase_len = ma

    tokenizer = Tokenizer(num_words=max_words, )

    tokenizer.fit_on_texts(X_train)
    X_train = tokenizer.texts_to_sequences(X_train)
    X_train = pad_sequences(X_train, maxlen=max_phrase_len)

    # accordingly shape the input shape
    X_train = np.asarray(X_train)
    X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)

    return X_train, tokenizer, max_phrase_len


X_t, keras_tokenizer, max_phrase_len = preprocess_for_neural_net_models_for_gui(X_CONST, "word")


def get_res_neural_net(query: str):
    if not isinstance(query, str):
        return

    top_flag = False
    temp = query
    if "TOP" in temp:
        top_flag = True
        tok = temp.split(' ')
        for i in range(0, len(tok)):
            if "TOP" == tok[i]:
                ans_size = int(tok[i + 1])
                break

    to_be_predicted = query
    X_CONST[1] = query
    X_t, keras_tokenizer, max_phrase_len = preprocess_for_neural_net_models_for_gui(X_CONST, "word", 6013)
    to_be_predicted = X_t[1]
    """
    to_be_predicted = X_CONST[1]
    # to_be_predicted = to_be_predicted.lower()
    # regular expression to replace all digits with <d> token but not alphanumerics
    # to_be_predicted = re.sub(r'\b[0-9]+\b|\s', ' <d> ', to_be_predicted)

    to_be_predicted = keras_tokenizer.texts_to_sequences(to_be_predicted)

    ok = []
    for i in range(0, max_phrase_len):

        if i >= len(to_be_predicted):
            ok.append(0)
        else:
            if not to_be_predicted[i]:
                ok.append(0)
            else:
                ok.append(to_be_predicted[i][0])

    a = pad_sequences(to_be_predicted, maxlen=max_phrase_len)
    
    # accordingly shape the input shape
    print(ok, "\n")
    to_be_predicted = ok

    to_be_predicted = np.asarray(to_be_predicted)
    
    to_be_predicted = np.reshape(to_be_predicted, (1, max_phrase_len, 1))
    """
    print(to_be_predicted.shape)
    vector_for_pred = np.reshape(to_be_predicted, (1, to_be_predicted.shape[0], to_be_predicted.shape[1]))
    # print(vector_for_pred.shape)

    # -- CPU

    Y_pred_cpu = modelc.predict(vector_for_pred)

    # print(data.busy.values.max() )
    mstdc = 1.24  # # mean standard deviation of error in cpu time

    # rescaling
    Y_pred_low_cpu = np.exp(Y_pred_cpu - mstdc) - 1 + data.busy.values.min()

    Y_pred_high_cpu = np.exp(Y_pred_cpu + mstdc) - 1 + data.busy.values.min()

    # --Answer size

    Y_pred_a = modela.predict(vector_for_pred)

    # print(data.busy.values.max() )
    mstde = 1.81  # mean standard deviation of error in answer size
    # rescaling
    Y_pred_low_a = np.exp(Y_pred_a - mstde) - 1 + data.rows.values.min()

    Y_pred_high_a = np.exp(Y_pred_a + mstde) - 1 + data.rows.values.min()

    # --error

    Y_pred_e = modele.predict(vector_for_pred)
    Y_pred_e = np.argmax(Y_pred_e, axis=1)
    Y_pred_e = Y_pred_e[0]

    if Y_pred_low_cpu < 0:
        Y_pred_low_cpu = 0
    if Y_pred_high_cpu < 0:
        Y_pred_high_cpu = 0

    if Y_pred_low_a < 0:
        Y_pred_low_a = 0
    if Y_pred_high_a < 0:
        Y_pred_high_a = 0

    if Y_pred_low_cpu == 0 and Y_pred_high_cpu == 0:
        print("Y_pred is between: ", Y_pred_low_cpu, "seconds and ", Y_pred_high_cpu, "seconds")


    elif Y_pred_low_cpu == 0 and not isinstance(Y_pred_high_cpu, int):
        print("Y_pred is between: ", Y_pred_low_cpu, "seconds and ", Y_pred_high_cpu[0][0] / 2, "seconds")
        Y_pred_high_cpu = Y_pred_high_cpu[0][0] / 2

    elif not isinstance(Y_pred_low_cpu, int) and Y_pred_high_cpu == 0:
        print("Y_pred is between: ", Y_pred_low_cpu[0][0], "seconds and ", Y_pred_high_cpu, "seconds")
        Y_pred_low_cpu = Y_pred_low_cpu[0][0]

    else:
        print("Y_pred is between: ", Y_pred_low_cpu[0][0], "seconds and ", Y_pred_high_cpu[0][0], "seconds")
        Y_pred_low_cpu = Y_pred_low_cpu[0][0]
        Y_pred_high_cpu = Y_pred_high_cpu[0][0]

    if Y_pred_low_a == 0 and Y_pred_high_a == 0:
        print("Y_pred is between: ", Y_pred_low_a, "rows and ", Y_pred_high_a, "rows")

    if top_flag == True:
        Y_pred_low_a = Y_pred_high_a = ans_size

    elif Y_pred_low_a == 0 and not isinstance(Y_pred_high_a, int):
        print("Y_pred is between: ", Y_pred_low_a, "rows and ", Y_pred_high_a[0][0] / 2, "rows")
        Y_pred_high_a = Y_pred_high_a[0][0] / 2

    elif not isinstance(Y_pred_low_a, int) and Y_pred_high_a == 0:
        print("Y_pred is between: ", Y_pred_low_a[0][0], "rows and ", Y_pred_high_a, "rows")
        Y_pred_low_a = Y_pred_low_a[0][0]

    else:
        print("Y_pred is between: ", Y_pred_low_a[0][0], "rows and ", Y_pred_high_a[0][0], "rows")
        Y_pred_low_a = Y_pred_low_a[0][0]
        Y_pred_high_a = Y_pred_high_a[0][0]

    print("\n \n \n")
    return Y_pred_low_cpu, Y_pred_high_cpu, math.ceil(Y_pred_low_a), math.ceil(Y_pred_high_a), Y_pred_e


def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH / Path(path)


def printSomething(Y_pred_low_cpu, Y_pred_high_cpu, Y_pred_low_a, Y_pred_high_a, Y_pred_e):
    # if you want the button to disappear:
    # button.destroy() or button.pack_forget()
    error = ""
    if Y_pred_e == 0:
        error = "success"
    elif Y_pred_e == 1:
        error = "non severe error"
    elif Y_pred_e == 2:
        error = "severe error"

    label = Label(window,
                  text="---------The predicted CPU busy time (seconds) needed for this query can be found in the interval: [ {:.2f}, {:.2f} ]----------\n"
                       "---------The predicted answer size (rows returned) for this query can be found in the interval: [ {:.2f}, {:.2f} ]----------\n"
                       "---------The predicted error label for this query is: {}---------\n".format(
                      Y_pred_low_cpu, Y_pred_high_cpu, Y_pred_low_a, Y_pred_high_a,error))
    label.place(relx=0.5, rely=0.4, anchor='center')
    # this creates a new label to the GUI


def check_and_submit(event):
    label1.destroy()
    suppress_stdout_stderr()
    get_input = input_str.get()
    print("The input string is: " + get_input)

    Y_pred_low_cpu, Y_pred_high_cpu, Y_pred_low_a, Y_pred_high_a, Y_pred_e = get_res_neural_net(get_input)

    printSomething(Y_pred_low_cpu, Y_pred_high_cpu, Y_pred_low_a, Y_pred_high_a, Y_pred_e)
    input_str.set("")


window = Tk()
window.title("ESQL assistant")
window.geometry("690x374")
window.configure(bg="#FFFFFF")



input_str = tk.StringVar()

canvas = Canvas(
    window,
    bg="#8BB4C1",
    height=374,
    width=690,
    bd=0,
    highlightthickness=0,
    relief="ridge"
)

canvas.place(x=0, y=0)

entry_image_1 = PhotoImage(
    file=relative_to_assets("entry_1.png"))

entry_bg_1 = canvas.create_image(
    349.5,
    308.5,
    image=entry_image_1
)
entry_1 = Entry(textvariable=input_str,
                bd=0,
                bg="#E5E5E5",
                highlightthickness=0
                )
entry_1.place(
    x=46.0,
    y=279.0,
    width=607.0,
    height=57.0
)

canvas.create_text(
    43.0,
    19.0,
    anchor="nw",
    text="Hello! Welcome to ESQL virtual Query assistant\nPlease pose your query and we ll be on our way to help you!",
    fill="#000000",
    font=("Ruda Regular", 18 * -1)
)

label1 = Label(window,
               text="ANALYSIS OF PROPERTIES OF LOADED DATASET:\nnum of chars: {:d} \nnum of words: {:d}  \nnum of function calls: {:d}\nnum of joins: {:d}\nnum of unique table names: {:d}   \nnum of selected columns:  {:d}  \nnum of predicates: {:d}\nnumber of predicate table names: {:d}\nnumber of subqueries: {:d}\nnested aggregation: {:d} ".format(
                  ch, b, c, d, e, f, g, h, i, j))
label1.place(relx=0.5, rely=0.5, anchor='center')


button = tk.Button(window, text='Stop', width=25, command=window.destroy)
button.place(relx=0.5, rely=0.99, anchor ='s')


entry_1.bind('<Return>', check_and_submit)

window.resizable(False, False)
window.mainloop()

# This file was generated by the Tkinter Designer by <NAME>
# https://github.com/ParthJadhav/Tkinter-Designer
import analysis as an

import os
from tensorflow import keras
from pathlib import Path
import methods
# from tkinter import *
# Explicit imports to satisfy Flake8
from tkinter import *
import tkinter as tk
import numpy as np
import pandas as pd
import csv
import analysis as an
import methods
from matplotlib import pyplot as plt
import sys
import warnings
import math
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.utils import to_categorical

warnings.filterwarnings("ignore")
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")

modelc = keras.models.load_model("models/sdss/word/word_sdss_cnn_dataset_cpu_time.h5")
modele = keras.models.load_model("models/sdss/word/word_sdss_cnn_dataset_error.h5")
modela = keras.models.load_model("models/sdss/word/word_sdss_cnn_dataset_answer_size.h5")





from contextlib import contextmanager, redirect_stderr, redirect_stdout
from os import devnull


@contextmanager
def suppress_stdout_stderr():
    """A context manager that redirects stdout and stderr to devnull"""
    with open(devnull, 'w') as fnull:
        with redirect_stderr(fnull) as err, redirect_stdout(fnull) as out:
            yield (err, out)


def readSDSS():
    # used the dollar sign to denote the query statement due to confusion with the quotation marks
    data = pd.read_csv("SDSS_100K_d_mix.csv", delimiter=',', engine='python', encoding='latin1', quotechar="$",
                       error_bad_lines=False)
    return data


def drop_er(data):
    count = 0

    for i in data.rows:
        if i >= 99999999:
            data = data.drop([count])
        count += 1

    count = 0

    for i in data.busy:
        if i >= 100000000:
            data = data.drop([count])
        count += 1

    return data


data = readSDSS()
data = drop_er(data)
X_CONST = data.statement.values
workload_an = an.Analiser(data,True)
ch, b, c, d, e, f, g, h, i, j = workload_an.analisis(data)


def preprocess_for_neural_net_models_for_gui(X_train: np.array, token_level: str, ma=0):
    max_words = 3000
    if "word" in token_level:

        for i in range(0, X_train.shape[0]):
            if not isinstance(X_train[i], str):
                X_train[i] = str(X_train[i])

            X_train[i] = X_train[i].lower()
            # regular expression to replace all digits with <d> token but not alphanumerics
            X_train[i] = re.sub(r'\b[0-9]+\b|\s', ' <d> ', X_train[i])

        phrase_len = data.statement.apply(lambda p: len(str(p).split(' ')))
    else:
        for i in range(0, X_train.shape[0]):
            if not isinstance(X_train[i], str):
                X_train[i] = str(X_train[i])

            X_train[i] = X_train[i].lower()

        phrase_len = data.statement.apply(lambda p: len(str(p)))

    max_phrase_len = phrase_len.max()
    if ma != 0: max_phrase_len = ma

    tokenizer = Tokenizer(num_words=max_words, )

    tokenizer.fit_on_texts(X_train)
    X_train = tokenizer.texts_to_sequences(X_train)
    X_train = pad_sequences(X_train, maxlen=max_phrase_len)

    # accordingly shape the input shape
    X_train = np.asarray(X_train)
    X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)

    return X_train, tokenizer, max_phrase_len


X_t, keras_tokenizer, max_phrase_len = preprocess_for_neural_net_models_for_gui(X_CONST, "word")


def get_res_neural_net(query: str):
    if not isinstance(query, str):
        return

    top_flag = False
    temp = query
    if "TOP" in temp:
        top_flag = True
        tok = temp.split(' ')
        for i in range(0, len(tok)):
            if "TOP" == tok[i]:
                ans_size = int(tok[i + 1])
                break

    to_be_predicted = query
    X_CONST[1] = query
    X_t, keras_tokenizer, max_phrase_len = preprocess_for_neural_net_models_for_gui(X_CONST, "word", 6013)
    to_be_predicted = X_t[1]
    """
    to_be_predicted = X_CONST[1]
    # to_be_predicted = to_be_predicted.lower()
    # regular expression to replace all digits with <d> token but not alphanumerics
    # to_be_predicted = re.sub(r'\b[0-9]+\b|\s', ' <d> ', to_be_predicted)

    to_be_predicted = keras_tokenizer.texts_to_sequences(to_be_predicted)

    ok = []
    for i in range(0, max_phrase_len):

        if i >= len(to_be_predicted):
            ok.append(0)
        else:
            if not to_be_predicted[i]:
                ok.append(0)
            else:
                ok.append(to_be_predicted[i][0])

    a = pad_sequences(to_be_predicted, maxlen=max_phrase_len)
    
    # accordingly shape the input shape
    print(ok, "\n")
    to_be_predicted = ok

    to_be_predicted = np.asarray(to_be_predicted)
    
    to_be_predicted = np.reshape(to_be_predicted, (1, max_phrase_len, 1))
    """
    print(to_be_predicted.shape)
    vector_for_pred = np.reshape(to_be_predicted, (1, to_be_predicted.shape[0], to_be_predicted.shape[1]))
    # print(vector_for_pred.shape)

    # -- CPU

    Y_pred_cpu = modelc.predict(vector_for_pred)

    # print(data.busy.values.max() )
    mstdc = 1.24  # # mean standard deviation of error in cpu time

    # rescaling
    Y_pred_low_cpu = np.exp(Y_pred_cpu - mstdc) - 1 + data.busy.values.min()

    Y_pred_high_cpu = np.exp(Y_pred_cpu + mstdc) - 1 + data.busy.values.min()

    # --Answer size

    Y_pred_a = modela.predict(vector_for_pred)

    # print(data.busy.values.max() )
    mstde = 1.81  # mean standard deviation of error in answer size
    # rescaling
    Y_pred_low_a = np.exp(Y_pred_a - mstde) - 1 + data.rows.values.min()

    Y_pred_high_a = np.exp(Y_pred_a + mstde) - 1 + data.rows.values.min()

    # --error

    Y_pred_e = modele.predict(vector_for_pred)
    Y_pred_e = np.argmax(Y_pred_e, axis=1)
    Y_pred_e = Y_pred_e[0]

    if Y_pred_low_cpu < 0:
        Y_pred_low_cpu = 0
    if Y_pred_high_cpu < 0:
        Y_pred_high_cpu = 0

    if Y_pred_low_a < 0:
        Y_pred_low_a = 0
    if Y_pred_high_a < 0:
        Y_pred_high_a = 0

    if Y_pred_low_cpu == 0 and Y_pred_high_cpu == 0:
        print("Y_pred is between: ", Y_pred_low_cpu, "seconds and ", Y_pred_high_cpu, "seconds")


    elif Y_pred_low_cpu == 0 and not isinstance(Y_pred_high_cpu, int):
        print("Y_pred is between: ", Y_pred_low_cpu, "seconds and ", Y_pred_high_cpu[0][0] / 2, "seconds")
        Y_pred_high_cpu = Y_pred_high_cpu[0][0] / 2

    elif not isinstance(Y_pred_low_cpu, int) and Y_pred_high_cpu == 0:
        print("Y_pred is between: ", Y_pred_low_cpu[0][0], "seconds and ", Y_pred_high_cpu, "seconds")
        Y_pred_low_cpu = Y_pred_low_cpu[0][0]

    else:
        print("Y_pred is between: ", Y_pred_low_cpu[0][0], "seconds and ", Y_pred_high_cpu[0][0], "seconds")
        Y_pred_low_cpu = Y_pred_low_cpu[0][0]
        Y_pred_high_cpu = Y_pred_high_cpu[0][0]

    if Y_pred_low_a == 0 and Y_pred_high_a == 0:
        print("Y_pred is between: ", Y_pred_low_a, "rows and ", Y_pred_high_a, "rows")

    if top_flag == True:
        Y_pred_low_a = Y_pred_high_a = ans_size

    elif Y_pred_low_a == 0 and not isinstance(Y_pred_high_a, int):
        print("Y_pred is between: ", Y_pred_low_a, "rows and ", Y_pred_high_a[0][0] / 2, "rows")
        Y_pred_high_a = Y_pred_high_a[0][0] / 2

    elif not isinstance(Y_pred_low_a, int) and Y_pred_high_a == 0:
        print("Y_pred is between: ", Y_pred_low_a[0][0], "rows and ", Y_pred_high_a, "rows")
        Y_pred_low_a = Y_pred_low_a[0][0]

    else:
        print("Y_pred is between: ", Y_pred_low_a[0][0], "rows and ", Y_pred_high_a[0][0], "rows")
        Y_pred_low_a = Y_pred_low_a[0][0]
        Y_pred_high_a = Y_pred_high_a[0][0]

    print("\n \n \n")
    return Y_pred_low_cpu, Y_pred_high_cpu, math.ceil(Y_pred_low_a), math.ceil(Y_pred_high_a), Y_pred_e


def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH / Path(path)


def printSomething(Y_pred_low_cpu, Y_pred_high_cpu, Y_pred_low_a, Y_pred_high_a, Y_pred_e):
    # if you want the button to disappear:
    # button.destroy() or button.pack_forget()
    error = ""
    if Y_pred_e == 0:
        error = "success"
    elif Y_pred_e == 1:
        error = "non severe error"
    elif Y_pred_e == 2:
        error = "severe error"

    label = Label(window,
                  text="---------The predicted CPU busy time (seconds) needed for this query can be found in the interval: [ {:.2f}, {:.2f} ]----------\n"
                       "---------The predicted answer size (rows returned) for this query can be found in the interval: [ {:.2f}, {:.2f} ]----------\n"
                       "---------The predicted error label for this query is: {}---------\n".format(
                      Y_pred_low_cpu, Y_pred_high_cpu, Y_pred_low_a, Y_pred_high_a,error))
    label.place(relx=0.5, rely=0.4, anchor='center')
    # this creates a new label to the GUI


def check_and_submit(event):
    label1.destroy()
    suppress_stdout_stderr()
    get_input = input_str.get()
    print("The input string is: " + get_input)

    Y_pred_low_cpu, Y_pred_high_cpu, Y_pred_low_a, Y_pred_high_a, Y_pred_e = get_res_neural_net(get_input)

    printSomething(Y_pred_low_cpu, Y_pred_high_cpu, Y_pred_low_a, Y_pred_high_a, Y_pred_e)
    input_str.set("")


window = Tk()
window.title("ESQL assistant")
window.geometry("690x374")
window.configure(bg="#FFFFFF")



input_str = tk.StringVar()

canvas = Canvas(
    window,
    bg="#8BB4C1",
    height=374,
    width=690,
    bd=0,
    highlightthickness=0,
    relief="ridge"
)

canvas.place(x=0, y=0)

entry_image_1 = PhotoImage(
    file=relative_to_assets("entry_1.png"))

entry_bg_1 = canvas.create_image(
    349.5,
    308.5,
    image=entry_image_1
)
entry_1 = Entry(textvariable=input_str,
                bd=0,
                bg="#E5E5E5",
                highlightthickness=0
                )
entry_1.place(
    x=46.0,
    y=279.0,
    width=607.0,
    height=57.0
)

canvas.create_text(
    43.0,
    19.0,
    anchor="nw",
    text="Hello! Welcome to ESQL virtual Query assistant\nPlease pose your query and we ll be on our way to help you!",
    fill="#000000",
    font=("Ruda Regular", 18 * -1)
)

label1 = Label(window,
               text="ANALYSIS OF PROPERTIES OF LOADED DATASET:\nnum of chars: {:d} \nnum of words: {:d}  \nnum of function calls: {:d}\nnum of joins: {:d}\nnum of unique table names: {:d}   \nnum of selected columns:  {:d}  \nnum of predicates: {:d}\nnumber of predicate table names: {:d}\nnumber of subqueries: {:d}\nnested aggregation: {:d} ".format(
                  ch, b, c, d, e, f, g, h, i, j))
label1.place(relx=0.5, rely=0.5, anchor='center')


button = tk.Button(window, text='Stop', width=25, command=window.destroy)
button.place(relx=0.5, rely=0.99, anchor ='s')


entry_1.bind('<Return>', check_and_submit)

window.resizable(False, False)
window.mainloop()

# This file was generated by the Tkinter Designer by <NAME> # https://github.com/ParthJadhav/Tkinter-Designer # from tkinter import * # Explicit imports to satisfy Flake8 A context manager that redirects stdout and stderr to devnull # used the dollar sign to denote the query statement due to confusion with the quotation marks # regular expression to replace all digits with <d> token but not alphanumerics # accordingly shape the input shape to_be_predicted = X_CONST[1]     # to_be_predicted = to_be_predicted.lower()     # regular expression to replace all digits with <d> token but not alphanumerics     # to_be_predicted = re.sub(r'\b[0-9]+\b|\s', ' <d> ', to_be_predicted)      to_be_predicted = keras_tokenizer.texts_to_sequences(to_be_predicted)      ok = []     for i in range(0, max_phrase_len):          if i >= len(to_be_predicted):             ok.append(0)         else:             if not to_be_predicted[i]:                 ok.append(0)             else:                 ok.append(to_be_predicted[i][0])      a = pad_sequences(to_be_predicted, maxlen=max_phrase_len)          # accordingly shape the input shape     print(ok, "\n")     to_be_predicted = ok      to_be_predicted = np.asarray(to_be_predicted)          to_be_predicted = np.reshape(to_be_predicted, (1, max_phrase_len, 1)) # print(vector_for_pred.shape) # -- CPU # print(data.busy.values.max() ) # # mean standard deviation of error in cpu time # rescaling # --Answer size # print(data.busy.values.max() ) # mean standard deviation of error in answer size # rescaling # --error # if you want the button to disappear: # button.destroy() or button.pack_forget() # this creates a new label to the GUI