File size: 3,546 Bytes
682f218
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56affb1
31dc405
 
 
73e5fda
31dc405
 
 
 
 
56affb1
3fecc43
31dc405
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73e5fda
682f218
da343b8
 
 
73e5fda
da343b8
 
 
 
 
 
73e5fda
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import numpy as np
import pandas as pd
import re
from keras.models import load_model
import gradio as gr

# Load the model and data
model = load_model("text_prediction_model.h5")
train = pd.read_csv("train.csv", usecols=[2])

# Preprocess the text datas
text = train["text"].str.lower() # convert to lowercase
text = text.str.replace("[^a-z ]", "") # remove punctuation and numbers
text = text.str.split() # split into words

# Create a vocabulary of unique words
vocab = set()
for words in text:
  vocab.update(words)
vocab = sorted(vocab)
vocab_size = len(vocab)
print(f"Vocabulary size: {vocab_size}")

# Create a word to index mapping
word_to_index = {word: i for i, word in enumerate(vocab)}
index_to_word = {i: word for i, word in enumerate(vocab)}

# Convert text to sequences of indices
sequences = []
for words in text:
  indices = [word_to_index[word] for word in words]
  sequences.append(indices)

# Define the sequence length and the number of words to predict
seq_length = 5 # the number of words to use as input
pred_length = 1 # the number of words to predict as output

# Create input and output sequences
X = [] # input sequences
y = [] # output sequences
for seq in sequences:
  for i in range(0, len(seq) - seq_length - pred_length + 1, pred_length):
    X.append(seq[i:i+seq_length])
    y.append(seq[i+seq_length:i+seq_length+pred_length])

X = np.array(X) # convert to numpy array
y = np.array(y) # convert to numpy array
X = X[:100000]
y = y[:100000]

# Define a function to generate text using the model

def generate_text(start_text):
  # Check if the start text is not None and has a non-empty string value
  if start_text is not None and start_text.strip():
    # Convert the start text to a sequence of indices
    input_seq = [word_to_index[word] for word in start_text.split()]
    input_seq = np.array(input_seq).reshape(1, -1)

    # Generate words using the model until reaching the desired length or an end token
    output_text = start_text + " "
    end_tokens = [".", "?", "!"] # tokens that indicate the end of a sentence
    num_words = len(start_text.split())
    for i in range(1):
      # Predict the next word using the model
      output_seq = model.predict(input_seq)
      output_word = index_to_word[np.argmax(output_seq)]

      # Append the output word to the output text and update the input sequence
      output_text += output_word + " "
      input_seq = np.append(input_seq, [[word_to_index[output_word]]], axis=1)
      input_seq = input_seq[:, -seq_length:] # keep only the last seq_length words

      # Stop if the output word is an end token
      if output_word in end_tokens:
        break
    
    return output_text
  else:
    # Return an error message if the start text is None or empty
    return "Please provide a valid start text."


# Create a Gradio interface for the model
interface = gr.Interface(
  fn=generate_text, # the function that connects the input and output
  inputs=gr.inputs.Textbox(lines=2, label="Start Text"), # the input type and label
  outputs=gr.outputs.Label(label="Generated Text"), # the output type and label
  title="Text Prediction Model", # the title of the interface
  description="A Keras LSTM model that predicts the next word given a start text.", # the description of the interface
  examples=[["the patient has a history"], ["the diagnosed patient had a history of vomiting and the cure was to take"], ["he complained of severe pain in his right"]], # some example inputs to show on the interface
)

# Launch the interface
interface.launch()