Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,29 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import tensorflow as tf
|
| 2 |
import numpy as np
|
| 3 |
import os
|
| 4 |
import pandas as pd
|
| 5 |
from flask import Flask, request, jsonify
|
| 6 |
-
import joblib
|
| 7 |
-
import sklearn
|
| 8 |
-
import re
|
| 9 |
from helpers.helper_functions import remove_html_tags, remove_url, remove_digits, remove_punc, lower
|
| 10 |
from models import Model
|
| 11 |
from werkzeug.exceptions import RequestEntityTooLarge
|
| 12 |
|
| 13 |
-
# Configure TensorFlow logging
|
| 14 |
-
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
| 15 |
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
app = Flask(__name__)
|
| 18 |
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 * 1024 # 16 GB max-limit
|
| 19 |
|
| 20 |
-
# Initialize model
|
| 21 |
model = Model()
|
| 22 |
|
| 23 |
# Define label mappings
|
| 24 |
SENTIMENT_LABELS = ['negative', 'neutral', 'positive']
|
| 25 |
EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
@app.route('/')
|
| 28 |
def index():
|
| 29 |
return 'Model deployed successfully'
|
|
@@ -33,72 +160,50 @@ def predict():
|
|
| 33 |
try:
|
| 34 |
# Validate request
|
| 35 |
data = request.get_json()
|
| 36 |
-
if not data:
|
| 37 |
-
return jsonify({'error': 'No input provided'}), 400
|
| 38 |
-
|
| 39 |
-
# Handle array of objects
|
| 40 |
-
if isinstance(data, list):
|
| 41 |
-
texts = []
|
| 42 |
-
tweet_ids = []
|
| 43 |
-
for item in data:
|
| 44 |
-
if not isinstance(item, dict) or 'text' not in item or 'id' not in item or not isinstance(item['text'], str):
|
| 45 |
-
return jsonify({'error': f'Invalid object format: {item}. Each object must have "id" and "text" keys with a string value for "text"'}), 400
|
| 46 |
-
texts.append(item['text'])
|
| 47 |
-
tweet_ids.append(item['id'])
|
| 48 |
-
else:
|
| 49 |
return jsonify({'error': 'Input must be an array of objects'}), 400
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
text_emotion = text
|
| 60 |
-
text_emotion = remove_html_tags(text_emotion)
|
| 61 |
-
text_emotion = remove_url(text_emotion)
|
| 62 |
-
text_emotion = remove_digits(text_emotion)
|
| 63 |
-
text_emotion = remove_punc(text_emotion)
|
| 64 |
-
|
| 65 |
-
# Convert to tensors and get predictions
|
| 66 |
-
sentiment_tensor = tf.convert_to_tensor([text_sentiment])
|
| 67 |
-
emotion_tensor = tf.convert_to_tensor([text_emotion])
|
| 68 |
-
|
| 69 |
-
print(f"Sentiment tensor shape: {sentiment_tensor.shape}")
|
| 70 |
-
print(f"Emotion tensor shape: {emotion_tensor.shape}")
|
| 71 |
-
|
| 72 |
-
sentiment_pred, emotion_pred = model.predict(
|
| 73 |
-
text_sentiment=sentiment_tensor,
|
| 74 |
-
text_emotion=emotion_tensor
|
| 75 |
-
)
|
| 76 |
-
|
| 77 |
-
print(f"Sentiment prediction shape: {sentiment_pred.shape}")
|
| 78 |
-
print(f"Emotion prediction shape: {emotion_pred.shape}")
|
| 79 |
-
print(f"Sentiment prediction: {sentiment_pred}")
|
| 80 |
-
print(f"Emotion prediction: {emotion_pred}")
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
-
# Create result object including tweet_id
|
| 90 |
result = {
|
| 91 |
-
'id': tweet_ids[idx],
|
| 92 |
-
'text':
|
| 93 |
'sentiment': {
|
| 94 |
'label': SENTIMENT_LABELS[sentiment_idx],
|
| 95 |
-
'score': float(sentiment_pred[
|
| 96 |
-
'raw_scores': [float(score) for score in sentiment_pred
|
| 97 |
},
|
| 98 |
'emotion': {
|
| 99 |
'label': EMOTION_LABELS[emotion_idx],
|
| 100 |
-
'score': float(emotion_pred[
|
| 101 |
-
'raw_scores': [float(score) for score in emotion_pred
|
| 102 |
}
|
| 103 |
}
|
| 104 |
results.append(result)
|
|
@@ -107,10 +212,8 @@ def predict():
|
|
| 107 |
|
| 108 |
except RequestEntityTooLarge:
|
| 109 |
return jsonify({'error': 'Request Entity Too Large'}), 413
|
| 110 |
-
except IndexError as e:
|
| 111 |
-
return jsonify({'error': f'IndexError: {str(e)}'}), 500
|
| 112 |
except Exception as e:
|
| 113 |
-
return jsonify({'error': f'Unexpected error: {str(e)}'}),
|
| 114 |
|
| 115 |
if __name__ == '__main__':
|
| 116 |
app.run(host='0.0.0.0' ,port=7860, debug=False)
|
|
|
|
| 1 |
+
# import tensorflow as tf
|
| 2 |
+
# import numpy as np
|
| 3 |
+
# import os
|
| 4 |
+
# import pandas as pd
|
| 5 |
+
# from flask import Flask, request, jsonify
|
| 6 |
+
# import joblib
|
| 7 |
+
# import sklearn
|
| 8 |
+
# import re
|
| 9 |
+
# from helpers.helper_functions import remove_html_tags, remove_url, remove_digits, remove_punc, lower
|
| 10 |
+
# from models import Model
|
| 11 |
+
# from werkzeug.exceptions import RequestEntityTooLarge
|
| 12 |
+
|
| 13 |
+
# # Configure TensorFlow logging
|
| 14 |
+
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
| 15 |
+
# os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 16 |
+
|
| 17 |
+
# app = Flask(__name__)
|
| 18 |
+
# app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 * 1024 # 16 GB max-limit
|
| 19 |
+
|
| 20 |
+
# # Initialize model
|
| 21 |
+
# model = Model()
|
| 22 |
+
|
| 23 |
+
# # Define label mappings
|
| 24 |
+
# SENTIMENT_LABELS = ['negative', 'neutral', 'positive']
|
| 25 |
+
# EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
|
| 26 |
+
|
| 27 |
+
# @app.route('/')
|
| 28 |
+
# def index():
|
| 29 |
+
# return 'Model deployed successfully'
|
| 30 |
+
|
| 31 |
+
# @app.route('/predict', methods=['POST'])
|
| 32 |
+
# def predict():
|
| 33 |
+
# try:
|
| 34 |
+
# # Validate request
|
| 35 |
+
# data = request.get_json()
|
| 36 |
+
# if not data:
|
| 37 |
+
# return jsonify({'error': 'No input provided'}), 400
|
| 38 |
+
|
| 39 |
+
# # Handle array of objects
|
| 40 |
+
# if isinstance(data, list):
|
| 41 |
+
# texts = []
|
| 42 |
+
# tweet_ids = []
|
| 43 |
+
# for item in data:
|
| 44 |
+
# if not isinstance(item, dict) or 'text' not in item or 'id' not in item or not isinstance(item['text'], str):
|
| 45 |
+
# return jsonify({'error': f'Invalid object format: {item}. Each object must have "id" and "text" keys with a string value for "text"'}), 400
|
| 46 |
+
# texts.append(item['text'])
|
| 47 |
+
# tweet_ids.append(item['id'])
|
| 48 |
+
# else:
|
| 49 |
+
# return jsonify({'error': 'Input must be an array of objects'}), 400
|
| 50 |
+
|
| 51 |
+
# results = []
|
| 52 |
+
# for idx, text in enumerate(texts):
|
| 53 |
+
# # Preprocess text for sentiment
|
| 54 |
+
# text_sentiment = text
|
| 55 |
+
# text_sentiment = remove_html_tags(text_sentiment)
|
| 56 |
+
# text_sentiment = lower(text_sentiment)
|
| 57 |
+
|
| 58 |
+
# # Preprocess text for emotion
|
| 59 |
+
# text_emotion = text
|
| 60 |
+
# text_emotion = remove_html_tags(text_emotion)
|
| 61 |
+
# text_emotion = remove_url(text_emotion)
|
| 62 |
+
# text_emotion = remove_digits(text_emotion)
|
| 63 |
+
# text_emotion = remove_punc(text_emotion)
|
| 64 |
+
|
| 65 |
+
# # Convert to tensors and get predictions
|
| 66 |
+
# sentiment_tensor = tf.convert_to_tensor([text_sentiment])
|
| 67 |
+
# emotion_tensor = tf.convert_to_tensor([text_emotion])
|
| 68 |
+
|
| 69 |
+
# print(f"Sentiment tensor shape: {sentiment_tensor.shape}")
|
| 70 |
+
# print(f"Emotion tensor shape: {emotion_tensor.shape}")
|
| 71 |
+
|
| 72 |
+
# sentiment_pred, emotion_pred = model.predict(
|
| 73 |
+
# text_sentiment=sentiment_tensor,
|
| 74 |
+
# text_emotion=emotion_tensor
|
| 75 |
+
# )
|
| 76 |
+
|
| 77 |
+
# print(f"Sentiment prediction shape: {sentiment_pred.shape}")
|
| 78 |
+
# print(f"Emotion prediction shape: {emotion_pred.shape}")
|
| 79 |
+
# print(f"Sentiment prediction: {sentiment_pred}")
|
| 80 |
+
# print(f"Emotion prediction: {emotion_pred}")
|
| 81 |
+
|
| 82 |
+
# # Process predictions
|
| 83 |
+
# sentiment_idx = int(np.argmax(sentiment_pred, axis=1)[0])
|
| 84 |
+
# emotion_idx = int(np.argmax(emotion_pred, axis=1)[0])
|
| 85 |
+
|
| 86 |
+
# print(f"Sentiment index: {sentiment_idx}")
|
| 87 |
+
# print(f"Emotion index: {emotion_idx}")
|
| 88 |
+
|
| 89 |
+
# # Create result object including tweet_id
|
| 90 |
+
# result = {
|
| 91 |
+
# 'id': tweet_ids[idx], # Add the tweet_id
|
| 92 |
+
# 'text': text,
|
| 93 |
+
# 'sentiment': {
|
| 94 |
+
# 'label': SENTIMENT_LABELS[sentiment_idx],
|
| 95 |
+
# 'score': float(sentiment_pred[0][sentiment_idx]),
|
| 96 |
+
# 'raw_scores': [float(score) for score in sentiment_pred[0]]
|
| 97 |
+
# },
|
| 98 |
+
# 'emotion': {
|
| 99 |
+
# 'label': EMOTION_LABELS[emotion_idx],
|
| 100 |
+
# 'score': float(emotion_pred[0][emotion_idx]),
|
| 101 |
+
# 'raw_scores': [float(score) for score in emotion_pred[0]]
|
| 102 |
+
# }
|
| 103 |
+
# }
|
| 104 |
+
# results.append(result)
|
| 105 |
+
|
| 106 |
+
# return jsonify({'results': results})
|
| 107 |
+
|
| 108 |
+
# except RequestEntityTooLarge:
|
| 109 |
+
# return jsonify({'error': 'Request Entity Too Large'}), 413
|
| 110 |
+
# except IndexError as e:
|
| 111 |
+
# return jsonify({'error': f'IndexError: {str(e)}'}), 500
|
| 112 |
+
# except Exception as e:
|
| 113 |
+
# return jsonify({'error': f'Unexpected error: {str(e)}'}), 400
|
| 114 |
+
|
| 115 |
+
# if __name__ == '__main__':
|
| 116 |
+
# app.run(host='0.0.0.0' ,port=7860, debug=False)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
|
| 120 |
import tensorflow as tf
|
| 121 |
import numpy as np
|
| 122 |
import os
|
| 123 |
import pandas as pd
|
| 124 |
from flask import Flask, request, jsonify
|
|
|
|
|
|
|
|
|
|
| 125 |
from helpers.helper_functions import remove_html_tags, remove_url, remove_digits, remove_punc, lower
|
| 126 |
from models import Model
|
| 127 |
from werkzeug.exceptions import RequestEntityTooLarge
|
| 128 |
|
| 129 |
+
# Configure TensorFlow logging and GPU
|
| 130 |
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress warnings
|
| 131 |
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
| 132 |
+
physical_devices = tf.config.list_physical_devices('GPU')
|
| 133 |
+
if physical_devices:
|
| 134 |
+
tf.config.experimental.set_memory_growth(physical_devices[0], True)
|
| 135 |
|
| 136 |
app = Flask(__name__)
|
| 137 |
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 * 1024 # 16 GB max-limit
|
| 138 |
|
| 139 |
+
# Initialize model globally
|
| 140 |
model = Model()
|
| 141 |
|
| 142 |
# Define label mappings
|
| 143 |
SENTIMENT_LABELS = ['negative', 'neutral', 'positive']
|
| 144 |
EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']
|
| 145 |
|
| 146 |
+
# Vectorized preprocessing function
|
| 147 |
+
def preprocess_batch(texts, for_emotion=False):
|
| 148 |
+
df = pd.Series(texts)
|
| 149 |
+
df = df.apply(remove_html_tags).str.lower()
|
| 150 |
+
if for_emotion:
|
| 151 |
+
df = df.apply(remove_url).apply(remove_digits).apply(remove_punc)
|
| 152 |
+
return df.tolist()
|
| 153 |
+
|
| 154 |
@app.route('/')
|
| 155 |
def index():
|
| 156 |
return 'Model deployed successfully'
|
|
|
|
| 160 |
try:
|
| 161 |
# Validate request
|
| 162 |
data = request.get_json()
|
| 163 |
+
if not data or not isinstance(data, list):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
return jsonify({'error': 'Input must be an array of objects'}), 400
|
| 165 |
|
| 166 |
+
# Extract texts and IDs
|
| 167 |
+
texts = []
|
| 168 |
+
tweet_ids = []
|
| 169 |
+
for item in data:
|
| 170 |
+
if not isinstance(item, dict) or 'text' not in item or 'id' not in item or not isinstance(item['text'], str):
|
| 171 |
+
return jsonify({'error': f'Invalid object format: {item}'}), 400
|
| 172 |
+
texts.append(item['text'])
|
| 173 |
+
tweet_ids.append(item['id'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
+
# Batch preprocessing
|
| 176 |
+
texts_sentiment = preprocess_batch(texts, for_emotion=False)
|
| 177 |
+
texts_emotion = preprocess_batch(texts, for_emotion=True)
|
| 178 |
|
| 179 |
+
# Convert to tensors and ensure tf.string dtype
|
| 180 |
+
sentiment_tensor = tf.convert_to_tensor(texts_sentiment, dtype=tf.string)
|
| 181 |
+
emotion_tensor = tf.convert_to_tensor(texts_emotion, dtype=tf.string)
|
| 182 |
+
|
| 183 |
+
# Batch inference
|
| 184 |
+
sentiment_preds, emotion_preds = model.predict(
|
| 185 |
+
text_sentiment=sentiment_tensor,
|
| 186 |
+
text_emotion=emotion_tensor
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# Process predictions
|
| 190 |
+
results = []
|
| 191 |
+
for idx, (sentiment_pred, emotion_pred) in enumerate(zip(sentiment_preds, emotion_preds)):
|
| 192 |
+
sentiment_idx = int(np.argmax(sentiment_pred))
|
| 193 |
+
emotion_idx = int(np.argmax(emotion_pred))
|
| 194 |
|
|
|
|
| 195 |
result = {
|
| 196 |
+
'id': tweet_ids[idx],
|
| 197 |
+
'text': texts[idx],
|
| 198 |
'sentiment': {
|
| 199 |
'label': SENTIMENT_LABELS[sentiment_idx],
|
| 200 |
+
'score': float(sentiment_pred[sentiment_idx]),
|
| 201 |
+
'raw_scores': [float(score) for score in sentiment_pred]
|
| 202 |
},
|
| 203 |
'emotion': {
|
| 204 |
'label': EMOTION_LABELS[emotion_idx],
|
| 205 |
+
'score': float(emotion_pred[emotion_idx]),
|
| 206 |
+
'raw_scores': [float(score) for score in emotion_pred]
|
| 207 |
}
|
| 208 |
}
|
| 209 |
results.append(result)
|
|
|
|
| 212 |
|
| 213 |
except RequestEntityTooLarge:
|
| 214 |
return jsonify({'error': 'Request Entity Too Large'}), 413
|
|
|
|
|
|
|
| 215 |
except Exception as e:
|
| 216 |
+
return jsonify({'error': f'Unexpected error: {str(e)}'}), 500
|
| 217 |
|
| 218 |
if __name__ == '__main__':
|
| 219 |
app.run(host='0.0.0.0' ,port=7860, debug=False)
|