File size: 8,285 Bytes
c551c64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b06572a
 
 
 
 
 
 
 
 
c551c64
 
b06572a
c551c64
 
 
b06572a
 
 
 
c551c64
b06572a
 
 
 
 
 
c551c64
 
 
 
 
 
 
 
b06572a
 
 
 
 
 
 
 
 
c551c64
b06572a
 
c551c64
 
 
 
 
 
 
 
b06572a
c551c64
 
 
b06572a
c551c64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b06572a
 
c551c64
 
b06572a
 
c551c64
 
b06572a
 
 
c551c64
 
b06572a
 
 
 
 
 
 
 
 
c551c64
b06572a
 
91956a4
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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
# import tensorflow as tf
# import numpy as np
# import os
# import pandas as pd
# from flask import Flask, request, jsonify
# import joblib
# import sklearn
# import re
# from helpers.helper_functions import remove_html_tags, remove_url, remove_digits, remove_punc, lower
# from models import Model
# from werkzeug.exceptions import RequestEntityTooLarge

# # Configure TensorFlow logging
# os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
# os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'

# app = Flask(__name__)
# app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 * 1024  # 16 GB max-limit

# # Initialize model
# model = Model()

# # Define label mappings
# SENTIMENT_LABELS = ['negative', 'neutral', 'positive']
# EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']

# @app.route('/')
# def index():
#     return 'Model deployed successfully'

# @app.route('/predict', methods=['POST'])
# def predict():
#     try:
#         # Validate request
#         data = request.get_json()
#         if not data:
#             return jsonify({'error': 'No input provided'}), 400

#         # Handle array of objects
#         if isinstance(data, list):
#             texts = []
#             tweet_ids = []
#             for item in data:
#                 if not isinstance(item, dict) or 'text' not in item or 'id' not in item or not isinstance(item['text'], str):
#                     return jsonify({'error': f'Invalid object format: {item}. Each object must have "id" and "text" keys with a string value for "text"'}), 400
#                 texts.append(item['text'])
#                 tweet_ids.append(item['id'])
#         else:
#             return jsonify({'error': 'Input must be an array of objects'}), 400

#         results = []
#         for idx, text in enumerate(texts):
#             # Preprocess text for sentiment
#             text_sentiment = text
#             text_sentiment = remove_html_tags(text_sentiment)
#             text_sentiment = lower(text_sentiment)
            
#             # Preprocess text for emotion
#             text_emotion = text
#             text_emotion = remove_html_tags(text_emotion)
#             text_emotion = remove_url(text_emotion)
#             text_emotion = remove_digits(text_emotion)
#             text_emotion = remove_punc(text_emotion)

#             # Convert to tensors and get predictions
#             sentiment_tensor = tf.convert_to_tensor([text_sentiment])
#             emotion_tensor = tf.convert_to_tensor([text_emotion])
            
#             print(f"Sentiment tensor shape: {sentiment_tensor.shape}")
#             print(f"Emotion tensor shape: {emotion_tensor.shape}")
            
#             sentiment_pred, emotion_pred = model.predict(
#                 text_sentiment=sentiment_tensor,
#                 text_emotion=emotion_tensor
#             )
            
#             print(f"Sentiment prediction shape: {sentiment_pred.shape}")
#             print(f"Emotion prediction shape: {emotion_pred.shape}")
#             print(f"Sentiment prediction: {sentiment_pred}")
#             print(f"Emotion prediction: {emotion_pred}")

#             # Process predictions
#             sentiment_idx = int(np.argmax(sentiment_pred, axis=1)[0])
#             emotion_idx = int(np.argmax(emotion_pred, axis=1)[0])

#             print(f"Sentiment index: {sentiment_idx}")
#             print(f"Emotion index: {emotion_idx}")

#             # Create result object including tweet_id
#             result = {
#                 'id': tweet_ids[idx],  # Add the tweet_id
#                 'text': text,
#                 'sentiment': {
#                     'label': SENTIMENT_LABELS[sentiment_idx],
#                     'score': float(sentiment_pred[0][sentiment_idx]),
#                     'raw_scores': [float(score) for score in sentiment_pred[0]]
#                 },
#                 'emotion': {
#                     'label': EMOTION_LABELS[emotion_idx],
#                     'score': float(emotion_pred[0][emotion_idx]),
#                     'raw_scores': [float(score) for score in emotion_pred[0]]
#                 }
#             }
#             results.append(result)

#         return jsonify({'results': results})

#     except RequestEntityTooLarge:
#         return jsonify({'error': 'Request Entity Too Large'}), 413
#     except IndexError as e:
#         return jsonify({'error': f'IndexError: {str(e)}'}), 500
#     except Exception as e:
#         return jsonify({'error': f'Unexpected error: {str(e)}'}), 400

# if __name__ == '__main__':
#     app.run(host='0.0.0.0' ,port=7860, debug=False)



import tensorflow as tf
import numpy as np
import os
import pandas as pd
from flask import Flask, request, jsonify
from helpers.helper_functions import remove_html_tags, remove_url, remove_digits, remove_punc, lower
from models import Model
from werkzeug.exceptions import RequestEntityTooLarge

# Configure TensorFlow logging and GPU
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'  # Suppress warnings
os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
physical_devices = tf.config.list_physical_devices('GPU')
if physical_devices:
    tf.config.experimental.set_memory_growth(physical_devices[0], True)

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 * 1024  # 16 GB max-limit

# Initialize model globally
model = Model()

# Define label mappings
SENTIMENT_LABELS = ['negative', 'neutral', 'positive']
EMOTION_LABELS = ['sadness', 'joy', 'love', 'anger', 'fear', 'surprise']

# Vectorized preprocessing function
def preprocess_batch(texts, for_emotion=False):
    df = pd.Series(texts)
    df = df.apply(remove_html_tags).str.lower()
    if for_emotion:
        df = df.apply(remove_url).apply(remove_digits).apply(remove_punc)
    return df.tolist()

@app.route('/')
def index():
    return 'Model deployed successfully'

@app.route('/predict', methods=['POST'])
def predict():
    try:
        # Validate request
        data = request.get_json()
        if not data or not isinstance(data, list):
            return jsonify({'error': 'Input must be an array of objects'}), 400

        # Extract texts and IDs
        texts = []
        tweet_ids = []
        for item in data:
            if not isinstance(item, dict) or 'text' not in item or 'id' not in item or not isinstance(item['text'], str):
                return jsonify({'error': f'Invalid object format: {item}'}), 400
            texts.append(item['text'])
            tweet_ids.append(item['id'])

        # Batch preprocessing
        texts_sentiment = preprocess_batch(texts, for_emotion=False)
        texts_emotion = preprocess_batch(texts, for_emotion=True)

        # Convert to tensors and ensure tf.string dtype
        sentiment_tensor = tf.convert_to_tensor(texts_sentiment, dtype=tf.string)
        emotion_tensor = tf.convert_to_tensor(texts_emotion, dtype=tf.string)

        # Batch inference
        sentiment_preds, emotion_preds = model.predict(
            text_sentiment=sentiment_tensor,
            text_emotion=emotion_tensor
        )

        # Process predictions
        results = []
        for idx, (sentiment_pred, emotion_pred) in enumerate(zip(sentiment_preds, emotion_preds)):
            sentiment_idx = int(np.argmax(sentiment_pred))
            emotion_idx = int(np.argmax(emotion_pred))

            result = {
                'id': tweet_ids[idx],
                'text': texts[idx],
                'sentiment': {
                    'label': SENTIMENT_LABELS[sentiment_idx],
                    'score': float(sentiment_pred[sentiment_idx]),
                    'raw_scores': [float(score) for score in sentiment_pred]
                },
                'emotion': {
                    'label': EMOTION_LABELS[emotion_idx],
                    'score': float(emotion_pred[emotion_idx]),
                    'raw_scores': [float(score) for score in emotion_pred]
                }
            }
            results.append(result)

        return jsonify({'results': results})

    except RequestEntityTooLarge:
        return jsonify({'error': 'Request Entity Too Large'}), 413
    except Exception as e:
        return jsonify({'error': f'Unexpected error: {str(e)}'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0' ,port=7860, debug=False)