Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,65 @@
|
|
1 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
|
3 |
-
|
4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from fastapi import FastAPI, Form
|
3 |
+
import pandas as pd
|
4 |
+
from starlette.responses import HTMLResponse
|
5 |
+
from tensorflow.keras.preprocessing.text import Tokenizer
|
6 |
+
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
7 |
+
import tensorflow as tf
|
8 |
+
import re
|
9 |
|
10 |
+
def preProcess_data(text): #cleaning the data
|
11 |
+
|
12 |
+
text = text.lower()
|
13 |
+
new_text = re.sub('[^a-zA-z0-9\s]','',text)
|
14 |
+
new_text = re.sub('rt', '', new_text)
|
15 |
+
return new_text
|
16 |
+
|
17 |
+
app = FastAPI()
|
18 |
+
|
19 |
+
data = pd.read_csv('archive/Sentiment.csv')
|
20 |
+
tokenizer = Tokenizer(num_words=2000, split=' ')
|
21 |
+
tokenizer.fit_on_texts(data['text'].values)
|
22 |
+
|
23 |
+
|
24 |
+
|
25 |
+
def my_pipeline(text): #pipeline
|
26 |
+
text_new = preProcess_data(text)
|
27 |
+
X = tokenizer.texts_to_sequences(pd.Series(text_new).values)
|
28 |
+
X = pad_sequences(X, maxlen=28)
|
29 |
+
return X
|
30 |
+
|
31 |
+
|
32 |
+
@app.get('/') #basic get view
|
33 |
+
def basic_view():
|
34 |
+
return {"WELCOME": "GO TO /docs route, or /post or send post request to /predict "}
|
35 |
+
|
36 |
+
|
37 |
+
|
38 |
+
@app.get('/predict', response_class=HTMLResponse) #data input by forms
|
39 |
+
def take_inp():
|
40 |
+
return '''<form method="post">
|
41 |
+
<input type="text" maxlength="28" name="text" value="Text Emotion to be tested"/>
|
42 |
+
<input type="submit"/>
|
43 |
+
</form>'''
|
44 |
+
|
45 |
+
|
46 |
+
|
47 |
+
@app.post('/predict') #prediction on data
|
48 |
+
def predict(text:str = Form(...)): #input is from forms
|
49 |
+
clean_text = my_pipeline(text) #cleaning and preprocessing of the texts
|
50 |
+
loaded_model = tf.keras.models.load_model('sentiment.h5') #loading the saved model
|
51 |
+
predictions = loaded_model.predict(clean_text) #making predictions
|
52 |
+
sentiment = int(np.argmax(predictions)) #index of maximum prediction
|
53 |
+
probability = max(predictions.tolist()[0]) #probability of maximum prediction
|
54 |
+
if sentiment==0: #assigning appropriate name to prediction
|
55 |
+
t_sentiment = 'negative'
|
56 |
+
elif sentiment==1:
|
57 |
+
t_sentiment = 'neutral'
|
58 |
+
elif sentiment==2:
|
59 |
+
t_sentiment='postive'
|
60 |
+
|
61 |
+
return { #returning a dictionary as endpoint
|
62 |
+
"ACTUALL SENTENCE": text,
|
63 |
+
"PREDICTED SENTIMENT": t_sentiment,
|
64 |
+
"Probability": probability
|
65 |
+
}
|