enemy7 commited on
Commit
e8568cf
ยท
1 Parent(s): 046e8b1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +428 -54
app.py CHANGED
@@ -1,61 +1,435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from flask import Flask
2
- from PIL import Image
3
- import numpy as np
 
 
4
  import tensorflow as tf
5
- import requests
6
- import io
7
 
8
- import os
 
9
 
10
- os.system("python3 -m http.server 7860 -b 0.0.0.0 &")
11
- # Initialize the Flask application
12
- app = Flask(__name__)
13
 
14
- # Load the trained model
15
- model = tf.keras.models.load_model('./save_model.h5',compile=False)
 
 
 
 
 
16
 
17
 
18
- @app.route('/')
19
- def aaa():
20
- return "hi"
21
-
22
- # Route for object detection
23
- @app.route('/detect-object/<id>', methods=['POST','GET'])
24
- def detect_pothole(id):
25
- # Get the image file from the request
26
- try :
27
- image_file = io.BytesIO(requests.get(f"https://firebasestorage.googleapis.com/v0/b/miniproj-2f595.appspot.com/o/{id}.jpg?alt=media&token=eca9d563-f526-4d9f-b443-72eb653b30d0").content)
28
-
29
- print(f"https://firebasestorage.googleapis.com/v0/b/miniproj-2f595.appspot.com/o/{id}.jpg?alt=media&token=eca9d563-f526-4d9f-b443-72eb653b30d0")
30
-
31
- # Load and preprocess the image
32
- image = Image.open(image_file)
33
- image = image.resize((64, 64))
34
- image = np.array(image)
35
- image = image / 255.0
36
- image = np.expand_dims(image, axis=0)
37
-
38
- # Debug statements
39
- print('Image shape:', image.shape)
40
- print('Image data:', image)
41
-
42
- # Make predictions
43
- result = model.predict(image)
44
-
45
- # Convert the prediction to a label
46
- if result[0][0] == 1:
47
- prediction = 'pothole'
48
- else:
49
- prediction = 'Normal'
50
-
51
- except :
52
- prediction = 'error'
53
-
54
- # Return the prediction as a JSON response
55
- response = {'prediction': prediction}
56
-
57
- return response
58
-
59
- # Run the Flask application
60
- if __name__ == '__main__':
61
- app.run()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # from flask import Flask
2
+ # from PIL import Image
3
+ # import numpy as np
4
+ # import tensorflow as tf
5
+ # import requests
6
+ # import io
7
+
8
+ # import os
9
+
10
+ # os.system("python3 -m http.server 7860 -b 0.0.0.0 &")
11
+ # # Initialize the Flask application
12
+ # app = Flask(__name__)
13
+
14
+ # # Load the trained model
15
+ # model = tf.keras.models.load_model('./save_model.h5',compile=False)
16
+
17
+
18
+ # @app.route('/')
19
+ # def aaa():
20
+ # return "hi"
21
+
22
+ # # Route for object detection
23
+ # @app.route('/detect-object/<id>', methods=['POST','GET'])
24
+ # def detect_pothole(id):
25
+ # # Get the image file from the request
26
+ # try :
27
+ # image_file = io.BytesIO(requests.get(f"https://firebasestorage.googleapis.com/v0/b/miniproj-2f595.appspot.com/o/{id}.jpg?alt=media&token=eca9d563-f526-4d9f-b443-72eb653b30d0").content)
28
+
29
+ # print(f"https://firebasestorage.googleapis.com/v0/b/miniproj-2f595.appspot.com/o/{id}.jpg?alt=media&token=eca9d563-f526-4d9f-b443-72eb653b30d0")
30
+
31
+ # # Load and preprocess the image
32
+ # image = Image.open(image_file)
33
+ # image = image.resize((64, 64))
34
+ # image = np.array(image)
35
+ # image = image / 255.0
36
+ # image = np.expand_dims(image, axis=0)
37
+
38
+ # # Debug statements
39
+ # print('Image shape:', image.shape)
40
+ # print('Image data:', image)
41
+
42
+ # # Make predictions
43
+ # result = model.predict(image)
44
+
45
+ # # Convert the prediction to a label
46
+ # if result[0][0] == 1:
47
+ # prediction = 'pothole'
48
+ # else:
49
+ # prediction = 'Normal'
50
+
51
+ # except :
52
+ # prediction = 'error'
53
+
54
+ # # Return the prediction as a JSON response
55
+ # response = {'prediction': prediction}
56
+
57
+ # return response
58
+
59
+ # # Run the Flask application
60
+ # if __name__ == '__main__':
61
+ # app.run()
62
+
63
+
64
+
65
  from flask import Flask
66
+ from flask import render_template
67
+ import random
68
+ from flask import Flask, request
69
+ import pandas as pd
70
  import tensorflow as tf
71
+ import tensorflow_hub as hub
72
+ import numpy as np
73
 
74
+ import nltk
75
+ from nltk.corpus import stopwords
76
 
77
+ import emoji
78
+ import re
79
+ from sklearn.pipeline import Pipeline
80
 
81
+ MAX_LENGTH = 50
82
+ MAX_CURRENCY_FLAG = 2
83
+ MAX_SPAM_WORDS = 1
84
+ MAX_EMOJI = 2
85
+ MAX_CONATANS = 1
86
+ MAX_EMAIL= 1
87
+ MAX_PHONE = 1
88
 
89
 
90
+ class RemoveStopWordsPunctuation:
91
+ def fit(self, x, y=None):
92
+ return self
93
+
94
+ def __remove_punctuation_stopwords(self, text):
95
+ pattern = re.compile("[{}]".format(re.escape("!\"#&'()*,-/:;<=>?[\\]^_`{|}~")))
96
+ text = " ".join(
97
+ [
98
+ word.strip()
99
+ for word in pattern.sub(" ", text.lower()).split()
100
+ if word not in set(stopwords.words("english"))
101
+ ]
102
+ )
103
+ return text
104
+
105
+ def transform(self, df):
106
+ df["Comment"] = df["Comment"].apply(self.__remove_punctuation_stopwords)
107
+ return df
108
+
109
+
110
+ class AddLengthFlag:
111
+ def fit(self, x, y=None):
112
+ return self
113
+
114
+ def transform(self, X):
115
+ X["length"] = X["Comment"].str.len().astype(np.float32) / MAX_LENGTH
116
+ return X
117
+
118
+
119
+ class AddCurrencyFlag:
120
+ def __init__(self) -> None:
121
+ self.currency_symbols = ["โ‚ค", "โ‚จ", "โ‚ฌ", "โ‚น", "โ‚ฟ", "$"]
122
+ self.pattern = "([\$โ‚คโ‚จโ‚ฌโ‚นโ‚ฟ]+ *[0-9]* *[\.,]?[0-9]*)|([0-9]* *[\.,]?[0-9]* *[\$โ‚คโ‚จโ‚ฌโ‚นโ‚ฟ]+)"
123
+
124
+ def fit(self, x, y=None):
125
+ return self
126
+
127
+ def __add_currency_count(self, text):
128
+ return len(re.findall(self.pattern, text)) / MAX_CURRENCY_FLAG
129
+
130
+ # def __add_currency_count(self,text):
131
+ # return sum(text.count(symbol) for symbol in self.currency_symbols )
132
+
133
+ def transform(self, df):
134
+ df["currency"] = df["Comment"].apply(self.__add_currency_count).astype(np.float32)
135
+ return df
136
+
137
+
138
+ class AddSpamWordsFlag:
139
+ def __init__(self) -> None:
140
+ self.spam_words = [
141
+ "morning",
142
+ "good"
143
+ "urgent",
144
+ "exclusive",
145
+ "limited time",
146
+ "free",
147
+ "guaranteed",
148
+ "act now",
149
+ "discount",
150
+ "special offer",
151
+ "prize",
152
+ "instant",
153
+ "cash",
154
+ "save",
155
+ "win",
156
+ "best",
157
+ "secret",
158
+ "incredible",
159
+ "congratulations",
160
+ "approved",
161
+ "risk free",
162
+ "hidden",
163
+ "bonus",
164
+ "sale",
165
+ "amazing",
166
+ "extra cash",
167
+ "opportunity",
168
+ "easy",
169
+ "double your",
170
+ "best price",
171
+ "cash back",
172
+ "deal",
173
+ "earn",
174
+ "money",
175
+ "no obligation",
176
+ "profit",
177
+ "results",
178
+ "exciting",
179
+ "unbelievable",
180
+ "jackpot",
181
+ "fantastic",
182
+ "instant access",
183
+ "million dollars",
184
+ "discounted",
185
+ "last chance",
186
+ "exclusive offer",
187
+ "big savings",
188
+ "limited offer",
189
+ "free trial",
190
+ "special promotion",
191
+ "secret revealed",
192
+ "valuable",
193
+ "money-back guarantee",
194
+ "lowest price",
195
+ "save money",
196
+ "make money",
197
+ "no risk",
198
+ "exclusive deal",
199
+ "limited supply",
200
+ "huge",
201
+ "incredible offer",
202
+ "prize winner",
203
+ "earn extra income",
204
+ "limited spots",
205
+ "new offer",
206
+ "best deal",
207
+ "don't miss out",
208
+ "great savings",
209
+ "top offer",
210
+ "double your income",
211
+ "discount code",
212
+ "fast cash",
213
+ "top-rated",
214
+ "best value",
215
+ "no cost",
216
+ "elite",
217
+ "act fast",
218
+ "unbeatable",
219
+ "cash prize",
220
+ "limited availability",
221
+ "special discount",
222
+ "quick cash",
223
+ "no catch",
224
+ "instant approval",
225
+ "big discount",
226
+ "easy money",
227
+ "insider",
228
+ "invitation",
229
+ "free shipping",
230
+ "huge discount",
231
+ "extra income",
232
+ "secret formula",
233
+ "no strings attached",
234
+ "money-making",
235
+ "dream come true",
236
+ "massive",
237
+ "free gift",
238
+ "incredible opportunity",
239
+ "risk-free trial",
240
+ "instant money",
241
+ "special price",
242
+ "no purchase necessary",
243
+ "now",
244
+ ]
245
+
246
+ def fit(self, x, y=None):
247
+ return self
248
+
249
+ def __add_currency_count(self, text):
250
+ return float(sum(text.count(symbol) for symbol in self.spam_words) / MAX_SPAM_WORDS)
251
+
252
+ def transform(self, df):
253
+ df["spam_word"] = df["Comment"].apply(self.__add_currency_count).astype(np.float32)
254
+ return df
255
+
256
+
257
+ class AddEmojiFlag:
258
+ def __init__(self) -> None:
259
+ self.emoji_symbols = "[๐Ÿ’ญ|๐Ÿ”|๐Ÿ†—|๐ŸŽ‰|๐ŸŽŠ|๐Ÿ“ฏ|๐Ÿ™Œ|๐Ÿ˜‚|๐Ÿ’ธ|๐Ÿ‘‰|๐Ÿ“ข|๐Ÿš€|๐Ÿ’ฒ|๐Ÿ’ฃ|๐Ÿ”ฑ|๐Ÿ’ผ|๐Ÿ†™|โณ|โœจ|๐Ÿ’Œ|๐Ÿ’Ž|๐Ÿ†•|๐Ÿ”ž|๐Ÿ’ก|๐Ÿ’ฐ|๐Ÿ‘‘|โญ|๐ŸŒŸ|๐ŸŽค|โšก|๐Ÿ“ˆ|๐Ÿ’ต|๐Ÿ†|๐Ÿ’ช|๐Ÿ”“|๐Ÿ†“|๐ŸŽฐ|โŒš|๐Ÿšจ|๐Ÿ’ข|๐Ÿ“ฎ|๐Ÿ”ฅ|๐ŸŽˆ|๐ŸŽฅ|๐Ÿ””|๐Ÿ’ฏ|๐ŸŽถ|๐Ÿ”—|๐ŸŽ|๐Ÿ“š|๐Ÿ”Š|๐Ÿ‘|๐Ÿ‘|๐Ÿ“ฑ|๐Ÿ“|๐Ÿค‘|๐Ÿ…|๐Ÿ”’|๐Ÿ“ฃ|๐Ÿ’ฅ]"
260
+
261
+ def fit(self, x, y=None):
262
+ return self
263
+
264
+ def __add_currency_count(self, text):
265
+ return float(len(re.findall(self.emoji_symbols, text)) / MAX_EMOJI)
266
+
267
+ def transform(self, df):
268
+ df["emoji"] = df["Comment"].apply(self.__add_currency_count).astype(np.float32)
269
+ return df
270
+
271
+
272
+ class AddContainFlag:
273
+ def fit(self, x, y=None):
274
+ return self
275
+
276
+ def __add_first_count(self, text):
277
+ pattern = "[0-9]*%|T&C"
278
+ return len(re.findall(pattern, text))
279
+
280
+ def __add_second_count(self, text):
281
+ pattern = "(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?"
282
+ return len(re.findall(pattern, text))
283
+
284
+ def transform(self, df):
285
+ df["contain"] = df["Comment"].apply(self.__add_first_count)
286
+ df["contain"] = df["contain"] + df["Comment"].apply(self.__add_second_count)
287
+ df['contain'] = df['contain'].astype(np.float32) / MAX_CONATANS
288
+ return df
289
+
290
+
291
+ class AddEmailFlag:
292
+ def fit(self, x, y=None):
293
+ return self
294
+
295
+ def __add_email_count(self, text):
296
+ pattern = "[\w]+@[\w]+\.\w+"
297
+ return float(len(re.findall(pattern, text)) /MAX_EMAIL)
298
+
299
+ def transform(self, df):
300
+ df["email"] = df["Comment"].apply(self.__add_email_count).astype(np.float32)
301
+ return df
302
+
303
+
304
+ class AddPhoneFlag:
305
+ def fit(self, x, y=None):
306
+ return self
307
+
308
+ def __add_phone_no_count(self, text):
309
+ pattern = "\+?[0-9]?[0-9]? ?0?[0-9]{10}"
310
+ return len(re.findall(pattern, text))
311
+
312
+ def __add_phone_no_count_1(self, text):
313
+ pattern = "\+?[0-9]?\d{3}[ -]?\d{3}[ -]?\d{4}"
314
+ return len(re.findall(pattern, text))
315
+
316
+ def transform(self, df):
317
+ df["phone"] = df["Comment"].apply(self.__add_phone_no_count)
318
+ df["phone"] = df["phone"] + df["Comment"].apply(self.__add_phone_no_count_1)
319
+ df["phone"] = df["phone"].astype(np.float32) / MAX_PHONE
320
+
321
+
322
+ return df
323
+
324
+
325
+ class RemovePhoneLinkEmail:
326
+ def fit(self, x, y=None):
327
+ return self
328
+
329
+ def __remove(self, text):
330
+ text = re.sub("\$[0-9]*([\.,][0-9]{2})*\$?", "", text)
331
+ text = re.sub("\+?[0-9]?[0-9]? ?0?[0-9]{10}", "", text)
332
+ text = re.sub("\+?[0-9]?\d{3}[ -]?\d{3}[ -]?\d{4}", "", text)
333
+ text = re.sub(
334
+ r"(https:\/\/www\.|http:\/\/www\.|https:\/\/|http:\/\/)?[a-zA-Z0-9]{2,}(\.[a-zA-Z0-9]{2,})(\.[a-zA-Z0-9]{2,})?",
335
+ "",
336
+ text,
337
+ )
338
+ text = re.sub(r"[\w]+@[\w]+\.\w+", "", text)
339
+ text = emoji.replace_emoji(text)
340
+ return text
341
+
342
+ def transform(self, df):
343
+ df["Comment"] = df["Comment"].apply(self.__remove)
344
+ return df
345
+
346
+
347
+ class LemmatizeText:
348
+ def __init__(self):
349
+ self.lemmatizer = nltk.WordNetLemmatizer()
350
+
351
+ def fit(self, X, y=None):
352
+ return self
353
+
354
+ def __lemmatize_text(self, text):
355
+ return " ".join(
356
+ [self.lemmatizer.lemmatize(word) for word in re.split("\W+", text)]
357
+ ).strip()
358
+
359
+ def transform(self, df):
360
+ df["Comment"] = df["Comment"].map(lambda text: self.__lemmatize_text(text))
361
+ return df
362
+
363
+
364
+
365
+ pipe = Pipeline([
366
+
367
+ ("AddCurrencyFlag",AddCurrencyFlag()),
368
+ ("AddSpamWordsFlag",AddSpamWordsFlag()),
369
+ ("AddEmojiFlag",AddEmojiFlag()),
370
+ ("AddContainFlag",AddContainFlag()),
371
+ ("AddEmailFlag",AddEmailFlag()),
372
+ ("AddPhoneFlag",AddPhoneFlag()),
373
+
374
+ ("RemovePhoneLinkEmail",RemovePhoneLinkEmail()),
375
+ ("RemoveStopWordsPunctuation",RemoveStopWordsPunctuation()),
376
+
377
+ ("LemmatizeText",LemmatizeText()),
378
+
379
+ ("AddLengthFlag",AddLengthFlag()),
380
+
381
+
382
+ ])
383
+ model = tf.keras.models.load_model('spam-model.h5', custom_objects={'KerasLayer':hub.KerasLayer})
384
+
385
+ def precidt(msg):
386
+ if type(msg) is str:
387
+ df = pd.DataFrame([msg],columns=["Comment"])
388
+ elif type(msg) is list:
389
+ df = pd.DataFrame(msg,columns=["Comment"])
390
+ else:
391
+ return []
392
+
393
+ df = pipe.transform(df)
394
+ table = df
395
+ df = {
396
+ "Comment": tf.convert_to_tensor(df["Comment"],dtype=tf.string),
397
+ "Length": tf.convert_to_tensor(df["length"], dtype=tf.float32),
398
+ "Currency": tf.convert_to_tensor(df["currency"], dtype=tf.float32),
399
+ "Spam Words": tf.convert_to_tensor(df["spam_word"], dtype=tf.float32),
400
+ "Emoji": tf.convert_to_tensor(df["emoji"], dtype=tf.float32),
401
+ "Contain": tf.convert_to_tensor(df["contain"], dtype=tf.float32),
402
+ "Email": tf.convert_to_tensor(df["email"], dtype=tf.float32),
403
+ "Phone": tf.convert_to_tensor(df["phone"], dtype=tf.float32)
404
+ }
405
+ return [ i for i in model.predict(df).reshape(-1,) ],table
406
+
407
+
408
+
409
+ app = Flask(__name__,template_folder="templates")
410
+
411
+ @app.route("/")
412
+ def hello():
413
+ return render_template('index.html')
414
+
415
+
416
+ @app.route("/api/data", methods=["POST"])
417
+ def main():
418
+ data = request.get_json()['text']
419
+
420
+ value = precidt(data)[0]
421
+
422
+ if (value > 85)
423
+ score = "Poor"
424
+
425
+ elif (value >50)
426
+ score = "Okay"
427
+
428
+ else
429
+ score = "Great"
430
+
431
+ return {"value": "{:.2f} % Spam".format(value) , "score" : "<span class='text-poor'>{score}</span>"}
432
+
433
+
434
+ app.run()
435
+