Sushrut98 commited on
Commit
e8e7b8f
·
verified ·
1 Parent(s): 72c7316

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -0
app.py ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### 1. Imports and class names setup ###
2
+ import gradio as gr
3
+ import os
4
+ from transformers import BertForSequenceClassification
5
+ import torch
6
+ from transformers import BertTokenizer, BertModel, BertConfig
7
+ # from model import create_effnetb2_model
8
+ from timeit import default_timer as timer
9
+ # from typing import Tuple, Dict
10
+ examples = [
11
+ ["Basically there's a family where a little boy (Jake) thinks there's a zombie in his closet & his parents are fighting all the time.<br /><br />This movie is slower than a soap opera... and suddenly, Jake decides to become Rambo and kill the zombie.<br /><br />OK, first of all when you're going to make a film you must Decide if its a thriller or a drama! As a drama the movie is watchable. Parents are divorcing & arguing like in real life. And then we have Jake with his closet which totally ruins all the film! I expected to see a BOOGEYMAN similar movie, and instead i watched a drama with some meaningless thriller spots.<br /><br />3 out of 10 just for the well playing parents & descent dialogs. As for the shots with Jake: just ignore them."],
12
+ ["One of the other reviewers has mentioned that after watching just 1 Oz episode you'll be hooked. They are right, as this is exactly what happened with me.<br /><br />The first thing that struck me about Oz was its brutality and unflinching scenes of violence, which set in right from the word GO. Trust me, this is not a show for the faint hearted or timid. This show pulls no punches with regards to drugs, sex or violence. Its is hardcore, in the classic use of the word.<br /><br />It is called OZ as that is the nickname given to the Oswald Maximum Security State Penitentary. It focuses mainly on Emerald City, an experimental section of the prison where all the cells have glass fronts and face inwards, so privacy is not high on the agenda. Em City is home to many..Aryans, Muslims, gangstas, Latinos, Christians, Italians, Irish and more....so scuffles, death stares, dodgy dealings and shady agreements are never far away.<br /><br />I would say the main appeal of the show is due to the fact that it goes where other shows wouldn't dare. Forget pretty pictures painted for mainstream audiences, forget charm, forget romance...OZ doesn't mess around. The first episode I ever saw struck me as so nasty it was surreal, I couldn't say I was ready for it, but as I watched more, I developed a taste for Oz, and got accustomed to the high levels of graphic violence. Not just violence, but injustice (crooked guards who'll be sold out for a nickel, inmates who'll kill on order and get away with it, well mannered, middle class inmates being turned into prison bitches due to their lack of street skills or prison experience) Watching Oz, you may become comfortable with what is uncomfortable viewing....thats if you can get in touch with your darker side."]
13
+ ]
14
+ # Setup class names
15
+ # class_names = ["pizza", "steak", "sushi"]
16
+
17
+ ### 2. Model and transforms preparation ###
18
+ tokenizer = BertTokenizer.from_pretrained('bert-base-uncased',
19
+ do_lower_case=True)
20
+ # Create BERT model
21
+ model = BertForSequenceClassification.from_pretrained("bert-base-uncased",
22
+ num_labels=2,
23
+ output_attentions=False,
24
+ output_hidden_states=False)
25
+ model.load_state_dict(torch.load(f='finetuned_BERT_epoch_10.model', map_location=torch.device('cpu')))
26
+ ### 3. Predict function ###
27
+
28
+ # Create predict function
29
+ def predict(text) :
30
+ """Transforms and performs a prediction on Text.
31
+ """
32
+ # Start the timer
33
+ start_time = timer()
34
+ encoding = tokenizer.encode_plus(
35
+ text,
36
+ None,
37
+ add_special_tokens=True,
38
+ max_length=256,
39
+ pad_to_max_length=True,
40
+ return_token_type_ids=True,
41
+ return_tensors='pt'
42
+ )
43
+
44
+ model.eval()
45
+
46
+ loss_val_total = 0
47
+ predictions = []
48
+ # batch = tuple(prediction)
49
+
50
+ inputs = {'input_ids': encoding["input_ids"],
51
+ 'attention_mask': encoding["attention_mask"],
52
+ }
53
+
54
+ with torch.no_grad():
55
+ outputs = model(**inputs)
56
+
57
+ print(outputs)
58
+ # loss = outputs[0]
59
+ logits = outputs[0]
60
+ # loss_val_total += loss.item()
61
+
62
+ logits = logits.detach().cpu().numpy()
63
+ # print(logits)
64
+ # label_ids = inputs['labels'].cpu().numpy()
65
+ predictions.append(logits)
66
+ # true_vals.append(label_ids)
67
+
68
+ # loss_val_avg = loss_val_total/len(dataloader_val)
69
+
70
+ predictions = np.concatenate(predictions, axis=0)
71
+
72
+ preds_flat = np.argmax(predictions, axis=1).flatten()
73
+
74
+ if preds_flat==0:
75
+ prediction = "positive"
76
+ else:
77
+ prediction = "negative"
78
+
79
+ # Calculate the prediction time
80
+ pred_time = round(timer() - start_time, 5)
81
+
82
+ # Return the prediction dictionary and prediction time
83
+ return prediction, pred_time
84
+
85
+ ### 4. Gradio app ###
86
+
87
+ # Create title, description and article strings
88
+ title = "Sentiment Analysis"
89
+ description = "Using Bert to predict the movie review. Either positive or negative."
90
+
91
+ # Create examples list from "examples/" directory
92
+ # example_list = [["examples/" + example] for example in os.listdir("examples")]
93
+
94
+ # Create the Gradio demo
95
+ demo = gr.Interface(fn=predict, # mapping function from input to output
96
+ inputs=gr.Textbox(lines=5, max_lines=6, label="Input Text"),
97
+ outputs=["text",
98
+ gr.Number(label="Prediction time (s)")],
99
+ # Create examples list from "examples/" directory
100
+ examples=examples,
101
+ title=title,
102
+ description=description)
103
+
104
+ # Launch the demo!
105
+ demo.launch()