-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
136 lines (107 loc) · 3.68 KB
/
main.py
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
# importing packages
from fastapi import FastAPI
import uvicorn
import numpy as np
import pickle
import pandas as pd
import string
import nltk
from nltk.stem import WordNetLemmatizer
import contractions
from nltk.corpus import stopwords
from fastapi.responses import HTMLResponse
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(max_features=5000)
nltk.download('wordnet') # Download WordNet data
wnl = WordNetLemmatizer()
w = []
c = []
def create_new_features(text):
words = text.split()
char_len = 0
for word in words:
char_len += len(word)
w.append(len(words))
c.append(char_len)
return (len(words), char_len)
nltk.download('stopwords')
import re
def remove_emoji(string):
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
"]+", flags=re.UNICODE)
return emoji_pattern.sub(r'', string)
from nltk.stem import WordNetLemmatizer
nltk.download('wordnet') # Download WordNet data
wnl = WordNetLemmatizer()
def preprocess_text(text):
#remove html tags
text = re.compile(r'<[^>]+>').sub('', text)
# convert to lower case
text = text.lower()
# expand contractions
text = contractions.fix(text)
# remove punctuations
text = text.translate(str.maketrans('','', string.punctuation))
# remove numbers
text = ''.join([i for i in text if not i.isdigit()])
# remove stop words
text = ' '.join([word for word in text.split() if word not in (stopwords.words('english'))])
# perform stemming
text = text.split()
words = []
for word in text:
words.append(wnl.lemmatize(word))
text = ' '.join(words)
# remove emoji
text = remove_emoji(text)
# remove extra spaces
text = ' '.join(text.split())
return text
# creating api name
app = FastAPI()
pickle_in = open("model.pkl","rb")
classifier = pickle.load(pickle_in)
# Index route, opens automatically on http//127.0.0.1:1111
@app.get("/", response_class=HTMLResponse)
def get_message():
original_message = "Welcome To my 2nd project\nI am Saurav, the creator of the project\nmy mail id: [email protected]"
lines = original_message.split("\n")
formatted_message = "<br>".join(lines)
return formatted_message
@app.post('/predict')
def predict_emotion(text: str):
result = ''
try:
text = preprocess_text(text)
word_len, char_len = create_new_features(text)
text_features = cv.transform([text])
text_features_dense = text_features.toarray()
zero_arr = np.array([0])
one_arr = np.array([1])
char_len_arr = np.array([char_len])
word_len_arr = np.array([word_len])
if text_features_dense.ndim > 1:
text_features_dense = np.squeeze(text_features_dense)
features = np.hstack((text_features_dense, zero_arr, one_arr, char_len_arr, word_len_arr))
features = features.reshape(1, -1)
# Predict sentiment
prediction = classifier.predict(features)
if prediction < 5:
result = "not satisfied"
elif prediction == 5:
result = "Neutral"
else:
result = "Satisfied"
return {
'prediction': result
}
except Exception as e:
return {"error": str(e)}
if __name__ == "__main__":
uvicorn.run(app, host='127.0.0.1', port=1111)