vumichien commited on
Commit
d9610ab
β€’
1 Parent(s): 21c3d29

Create new file

Browse files
Files changed (1) hide show
  1. app.py +93 -0
app.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import from_pretrained_keras
2
+ import numpy as np
3
+ import gradio as gr
4
+ import transformers
5
+
6
+ class BertSemanticDataGenerator(tf.keras.utils.Sequence):
7
+ """Generates batches of data."""
8
+ def __init__(
9
+ self,
10
+ sentence_pairs,
11
+ labels,
12
+ batch_size=batch_size,
13
+ shuffle=True,
14
+ include_targets=True,
15
+ ):
16
+ self.sentence_pairs = sentence_pairs
17
+ self.labels = labels
18
+ self.shuffle = shuffle
19
+ self.batch_size = batch_size
20
+ self.include_targets = include_targets
21
+ # Load our BERT Tokenizer to encode the text.
22
+ # We will use base-base-uncased pretrained model.
23
+ self.tokenizer = transformers.BertTokenizer.from_pretrained(
24
+ "bert-base-uncased", do_lower_case=True
25
+ )
26
+ self.indexes = np.arange(len(self.sentence_pairs))
27
+ self.on_epoch_end()
28
+
29
+ def __len__(self):
30
+ # Denotes the number of batches per epoch.
31
+ return len(self.sentence_pairs) // self.batch_size
32
+
33
+ def __getitem__(self, idx):
34
+ # Retrieves the batch of index.
35
+ indexes = self.indexes[idx * self.batch_size : (idx + 1) * self.batch_size]
36
+ sentence_pairs = self.sentence_pairs[indexes]
37
+
38
+ # With BERT tokenizer's batch_encode_plus batch of both the sentences are
39
+ # encoded together and separated by [SEP] token.
40
+ encoded = self.tokenizer.batch_encode_plus(
41
+ sentence_pairs.tolist(),
42
+ add_special_tokens=True,
43
+ max_length=max_length,
44
+ return_attention_mask=True,
45
+ return_token_type_ids=True,
46
+ pad_to_max_length=True,
47
+ return_tensors="tf",
48
+ )
49
+
50
+ # Convert batch of encoded features to numpy array.
51
+ input_ids = np.array(encoded["input_ids"], dtype="int32")
52
+ attention_masks = np.array(encoded["attention_mask"], dtype="int32")
53
+ token_type_ids = np.array(encoded["token_type_ids"], dtype="int32")
54
+
55
+ # Set to true if data generator is used for training/validation.
56
+ if self.include_targets:
57
+ labels = np.array(self.labels[indexes], dtype="int32")
58
+ return [input_ids, attention_masks, token_type_ids], labels
59
+ else:
60
+ return [input_ids, attention_masks, token_type_ids]
61
+
62
+ model = from_pretrained_keras("keras-io/bert-semantic-similarity")
63
+
64
+ def predict(sentence1, sentence2):
65
+ sentence_pairs = np.array([[str(sentence1), str(sentence2)]])
66
+ test_data = BertSemanticDataGenerator(
67
+ sentence_pairs, labels=None, batch_size=1, shuffle=False, include_targets=False,
68
+ )
69
+ proba = model.predict(test_data[0])[0]
70
+ idx = np.argmax(proba)
71
+ proba = f"{proba[idx]*100:.2f}%"
72
+ pred = labels[idx]
73
+ return f'These two sentence is {pred} with {proba} of probability'
74
+
75
+ inputs = [
76
+ gr.Audio(source = "upload", label='Upload audio file', type="filepath"),
77
+ ]
78
+
79
+ examples = [["Two women are observing something together.", "Two women are standing with their eyes closed."],
80
+ ["A smiling costumed woman is holding an umbrella", "A happy woman in a fairy costume holds an umbrella"],
81
+ ["A soccer game with multiple males playing", "Some men are playing a sport"],
82
+ ]
83
+
84
+ gr.Interface(
85
+ fn=predict,
86
+ title="Semantic Similarity with BERT",
87
+ description = "Natural Language Inference by fine-tuning BERT model on SNLI Corpus.)",
88
+ inputs=["text", "text"],
89
+ examples=examples,
90
+ outputs=gr.Textbox(label='Prediction'),
91
+ cache_examples=False,
92
+ article = "Author: <a href=\"https://huggingface.co/vumichien\">Vu Minh Chien</a>. Based on the keras example from <a href=\"https://keras.io/examples/nlp/semantic_similarity_with_bert/\">Mohamad Merchant</a>",
93
+ ).launch(debug=True, enable_queue=True)