import gradio as gr pair_dict = [] freq = [] def train_model(training_text): #Made by shardul funde #This code sucks,you know it and I know it. #Move on and call me an idiot later. lines = training_text.splitlines() for sentence1 in lines: if sentence1 == "stop the training": break sentence = list(map(str, sentence1.split())) for i in range(len(sentence) - 2): pair = [sentence[i], sentence[i + 1], sentence[i + 2]] if pair not in pair_dict: pair_dict.append(pair) freq.append(1) else: index = pair_dict.index(pair) freq[index] += 1 return "Pairs: " + str(pair_dict) + "\nFrequencies: " + str(freq) def autocomplete(user_input1, words): # If user_input1 equals "stop the program12", we terminate. if user_input1 == "stop the program12": return "Program terminated." user_input = list(map(str, user_input1.split())) words = int(words) result = [user_input[-2], user_input[-1]] output = "" for c in range(words): word_freq = [] for j in range(len(pair_dict)): word_freq_pair = [pair_dict[j][2], freq[j]] if ([pair_dict[j][0], pair_dict[j][1]] == result): word_freq.append(word_freq_pair) if not word_freq: return output + "\nNo matching word pairs found for autocompletion." word_count = word_freq[0][1] word = word_freq[0][0] for d in range(len(word_freq) - 1): if (word_freq[d + 1][1] > word_count): word_count = word_freq[d + 1][1] word = word_freq[d + 1][0] output += word + " " result = [result[-1], word] return output.strip() train_interface = gr.Interface( fn=train_model, inputs=gr.Textbox(lines=5, label="Enter training sentences (one per line). Type 'stop the training' on a line to finish."), outputs="text", title="Train N-Gram Model" ) predict_interface = gr.Interface( fn=autocomplete, inputs=[ gr.Textbox(label="Enter text for autocompletion"), gr.Number(label="No of words for autocompletion") ], outputs="text", title="N-Gram Autocomplete" ) gr.TabbedInterface([train_interface, predict_interface], ["Train", "Predict"]).launch()