Safman commited on
Commit
d362f06
·
1 Parent(s): 7be0696

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -0
app.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import numpy as np
3
+ import pandas as pd
4
+ import re
5
+ from keras.models import load_model
6
+
7
+ # Load your model and data files from the Hub
8
+ model = load_model("https://huggingface.co/username/modelname/raw/main/text_prediction_model.h5")
9
+ train = pd.read_csv("https://huggingface.co/username/modelname/raw/main/train.csv", usecols=[2])
10
+
11
+ # Preprocess the text data
12
+ text = train["text"].str.lower() # convert to lowercase
13
+ text = text.str.replace("[^a-z ]", "") # remove punctuation and numbers
14
+ text = text.str.split() # split into words
15
+
16
+ # Create a vocabulary of unique words
17
+ vocab = set()
18
+ for words in text:
19
+ vocab.update(words)
20
+ vocab = sorted(vocab)
21
+ vocab_size = len(vocab)
22
+ print(f"Vocabulary size: {vocab_size}")
23
+
24
+ # Create a word to index mapping
25
+ word_to_index = {word: i for i, word in enumerate(vocab)}
26
+ index_to_word = {i: word for i, word in enumerate(vocab)}
27
+
28
+ # Define the sequence length and the number of words to predict
29
+ seq_length = 5 # the number of words to use as input
30
+ pred_length = 1 # the number of words to predict as output
31
+
32
+ # Define the prediction function
33
+ def generate_text(input_text):
34
+ # Convert the input text to a sequence of indices
35
+ input_seq = [word_to_index[word] for word in input_text.split()]
36
+ input_seq = np.array(input_seq).reshape(1, -1)
37
+
38
+ # Generate words using the model until reaching the desired length or an end token
39
+ output_text = input_text + " "
40
+ end_tokens = [".", "?", "!"] # tokens that indicate the end of a sentence
41
+
42
+ for i in range(50):
43
+ # Predict the next word using the model
44
+ output_seq = model.predict(input_seq)
45
+ output_word = index_to_word[np.argmax(output_seq)]
46
+
47
+ # Append the output word to the output text and update the input sequence
48
+ output_text += output_word + " "
49
+ input_seq = np.append(input_seq, [[word_to_index[output_word]]], axis=1)
50
+ input_seq = input_seq[:, -seq_length:] # keep only the last seq_length words
51
+
52
+ # Stop if the output word is an end token
53
+ if output_word in end_tokens:
54
+ break
55
+
56
+ return output_text
57
+
58
+ # Create the interface with a text input and a text output
59
+ interface = gr.Interface(
60
+ fn=generate_text,
61
+ inputs=gr.inputs.Textbox(lines=2, label="Input Text"),
62
+ outputs=gr.outputs.Textbox(label="Output Text")
63
+ )
64
+
65
+ # Launch the interface
66
+ interface.launch()