Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

API_server.py 3.6 KB

You have to be logged in to leave a comment. Sign In
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
132
133
134
135
136
137
138
139
140
141
142
  1. #! /usr/bin/env python3
  2. # coding: utf-8
  3. import os
  4. import joblib
  5. from flask import Flask, request, jsonify
  6. import pathlib
  7. import html
  8. import preprocessor as tweet_preprocessor
  9. import spacy
  10. # import cv2
  11. # import tflite_runtime.interpreter as tflite
  12. import tensorflow as tf
  13. from tensorflow import keras
  14. # import numpy as np
  15. try:
  16. from tensorflow.keras.layers import TextVectorization
  17. except ImportError:
  18. from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
  19. app = Flask(__name__)
  20. # --- Load Spacy ---
  21. print("Load spaCy lemmatizer")
  22. nlp = spacy.load('en_core_web_sm')
  23. def tokenize(text):
  24. # tokenisation
  25. tokens = nlp(text)
  26. print("tokens:", tokens)
  27. # lemmatize
  28. lemmas = [x.lemma_ for x in tokens]
  29. print("lemmas:", lemmas)
  30. return " ".join(lemmas)
  31. def preprocess_txt(string):
  32. print("PRE01:", string)
  33. # suppression des majuscules
  34. text = string.lower()
  35. # suppression des espaces au début et à la fin des textes
  36. text = text.strip()
  37. print("PRE02:", text)
  38. text = html.unescape(text)
  39. print("PRE03:", text)
  40. tweet_preprocessor.set_options(tweet_preprocessor.OPT.MENTION, tweet_preprocessor.OPT.RESERVED, tweet_preprocessor.OPT.EMOJI)
  41. text = tweet_preprocessor.clean(text)
  42. print("PRE04:", text)
  43. tweet_preprocessor.set_options(tweet_preprocessor.OPT.URL)
  44. text = tweet_preprocessor.tokenize(text)
  45. print("PRE05:", text)
  46. lemmas = tokenize(text)
  47. print("PRE06:", lemmas)
  48. return lemmas
  49. # --- Load TextVectorizer ---
  50. print("Load TextVectorizer Model")
  51. TV_config, TV_weigths = joblib.load(pathlib.Path("models", "SelectedTextVectorizerModel.bin"))
  52. text_vectorization = TextVectorization.from_config(TV_config)
  53. # You have to call `adapt` with some dummy data (BUG in Keras)
  54. # text_vectorization.adapt(tf.data.Dataset.from_tensor_slices(["xyz"]))
  55. text_vectorization.set_weights(TV_weigths)
  56. # --- Load TF Model ---
  57. print("Load Classification Model")
  58. model = keras.models.load_model("models/SelectedModel.keras")
  59. # --- Load TF-Lite model using an interpreter
  60. # interpreter = tflite.Interpreter(model_path="models/model1extra.tflite")
  61. # interpreter.allocate_tensors()
  62. # input_index = interpreter.get_input_details()[0]["index"]
  63. # output_index = interpreter.get_output_details()[0]["index"]
  64. @app.route("/")
  65. def index():
  66. return "Hello world !<br>The 'Twitter Sentiment Analysis API' server is up."
  67. @app.route("/predict", methods=["POST"])
  68. def predict():
  69. try:
  70. print("--- Collect >>>> ", request.data)
  71. raw_txt = str(request.data)
  72. except Exception as e:
  73. print("Error:", e)
  74. # Preprocess string
  75. txt = preprocess_txt(raw_txt)
  76. # Apply TextVectorizer
  77. print("--- TextVectorization")
  78. txt = text_vectorization(txt)
  79. # Convert to Tensor
  80. print("--- Convert to tensor")
  81. ready_txt = tf.convert_to_tensor([txt])
  82. # Apply model
  83. print("--- Predict")
  84. pred = model.predict(ready_txt)
  85. if pred[0] > 0.474: # best threshold found
  86. label = "Positive"
  87. pred_value = float(pred[0])
  88. else:
  89. label = "Negative"
  90. pred_value = 1.0 - float(pred[0])
  91. # Return values
  92. return jsonify(
  93. f"The predicted label is **{label.upper()}** with the following probability: {pred_value*100.0:.2f}%"
  94. )
  95. print("Server ready")
  96. if __name__ == "__main__":
  97. # print("ICI on y va ")
  98. # raw_txt = tf.convert_to_tensor(["I hate it", "I love it"])
  99. # raw_txt = text_vectorization(raw_txt)
  100. # print(model.predict(raw_txt))
  101. current_port = int(os.environ.get("PORT") or 5000)
  102. app.run(debug=True, host="0.0.0.0", port=current_port)
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...