File size: 10,433 Bytes
82c705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"""
Advanced API endpoints for sentiment analysis
Includes model comparison, batch processing, and analytics
"""

from flask import Blueprint, request, jsonify
from typing import List, Dict, Any
import logging
import time
import sys
import os
from datetime import datetime

# Add parent directory to path for imports
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from advanced_model import get_advanced_analyzer, predict_advanced, predict_batch, get_model_stats
from config import config

logger = logging.getLogger('sentiment_analyzer.advanced_api')

# Create blueprint for advanced endpoints
advanced_bp = Blueprint('advanced', __name__, url_prefix='/api/v2')

@advanced_bp.route('/compare', methods=['POST'])
def compare_models():
    """Compare sentiment analysis across multiple models"""
    try:
        data = request.get_json()
        
        if not data or 'text' not in data:
            return jsonify({
                'error': 'Missing required field: text',
                'status': 'error'
            }), 400
        
        text = data['text'].strip()
        if not text or len(text) > config.MAX_TEXT_LENGTH:
            return jsonify({
                'error': f'Text must be between 1 and {config.MAX_TEXT_LENGTH} characters',
                'status': 'error'
            }), 400
        
        # Get models to use (default to all available)
        models = data.get('models', None)
        
        # Perform comparison
        result = predict_advanced(text, models)
        
        # Format response
        response = {
            'status': 'success',
            'text': result.text,
            'consensus': {
                'sentiment': result.consensus_sentiment,
                'confidence': round(result.average_confidence, 4),
                'agreement_score': round(result.agreement_score, 4)
            },
            'model_results': [
                {
                    'model': r.model_name,
                    'sentiment': r.sentiment,
                    'confidence': round(r.confidence, 4),
                    'processing_time': round(r.processing_time, 4)
                }
                for r in result.results
            ],
            'processing_time': round(result.processing_time, 4),
            'timestamp': datetime.now().isoformat()
        }
        
        logger.info(f"Model comparison completed for text length {len(text)}")
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error in model comparison: {e}")
        return jsonify({
            'error': 'Internal server error during model comparison',
            'status': 'error'
        }), 500

@advanced_bp.route('/batch', methods=['POST'])
def batch_analyze():
    """Analyze multiple texts in batch"""
    try:
        data = request.get_json()
        
        if not data or 'texts' not in data:
            return jsonify({
                'error': 'Missing required field: texts (array)',
                'status': 'error'
            }), 400
        
        texts = data['texts']
        if not isinstance(texts, list):
            return jsonify({
                'error': 'Field "texts" must be an array',
                'status': 'error'
            }), 400
        
        if len(texts) == 0:
            return jsonify({
                'error': 'At least one text is required',
                'status': 'error'
            }), 400
        
        if len(texts) > 50:  # Limit batch size
            return jsonify({
                'error': 'Maximum 50 texts allowed per batch',
                'status': 'error'
            }), 400
        
        # Validate all texts
        for i, text in enumerate(texts):
            if not isinstance(text, str):
                return jsonify({
                    'error': f'Text at index {i} must be a string',
                    'status': 'error'
                }), 400
            
            if len(text.strip()) == 0 or len(text) > config.MAX_TEXT_LENGTH:
                return jsonify({
                    'error': f'Text at index {i} must be between 1 and {config.MAX_TEXT_LENGTH} characters',
                    'status': 'error'
                }), 400
        
        # Get model to use
        model_key = data.get('model', None)
        
        # Process batch
        start_time = time.time()
        results = predict_batch(texts, model_key)
        total_time = time.time() - start_time
        
        # Format response
        response = {
            'status': 'success',
            'batch_size': len(texts),
            'results': [
                {
                    'index': i,
                    'text': texts[i],
                    'sentiment': r.sentiment,
                    'confidence': round(r.confidence, 4),
                    'processing_time': round(r.processing_time, 4)
                }
                for i, r in enumerate(results)
            ],
            'total_processing_time': round(total_time, 4),
            'average_processing_time': round(total_time / len(texts), 4),
            'timestamp': datetime.now().isoformat()
        }
        
        logger.info(f"Batch analysis completed for {len(texts)} texts")
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error in batch analysis: {e}")
        return jsonify({
            'error': 'Internal server error during batch analysis',
            'status': 'error'
        }), 500

@advanced_bp.route('/models', methods=['GET'])
def get_models():
    """Get information about available models"""
    try:
        analyzer = get_advanced_analyzer()
        available_models = analyzer.get_available_models()
        performance_stats = get_model_stats()
        
        models_info = []
        for model_key in available_models:
            model_config = analyzer.model_configs[model_key]
            stats = performance_stats.get(model_key, {})
            
            models_info.append({
                'key': model_key,
                'name': model_config['name'],
                'supported_labels': list(model_config['label_mapping'].values()),
                'performance': {
                    'total_predictions': stats.get('total_predictions', 0),
                    'average_processing_time': round(stats.get('average_processing_time', 0), 4),
                    'error_rate': round(stats.get('error_rate', 0), 4),
                    'load_time': round(stats.get('load_time', 0), 4)
                }
            })
        
        response = {
            'status': 'success',
            'total_models': len(models_info),
            'models': models_info,
            'timestamp': datetime.now().isoformat()
        }
        
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error getting models info: {e}")
        return jsonify({
            'error': 'Internal server error getting models information',
            'status': 'error'
        }), 500

@advanced_bp.route('/analytics', methods=['GET'])
def get_analytics():
    """Get analytics and performance statistics"""
    try:
        performance_stats = get_model_stats()
        
        # Calculate overall statistics
        total_predictions = sum(stats.get('total_predictions', 0) for stats in performance_stats.values())
        total_errors = sum(stats.get('total_errors', 0) for stats in performance_stats.values())
        
        if total_predictions > 0:
            overall_error_rate = total_errors / (total_predictions + total_errors)
            avg_processing_time = sum(
                stats.get('average_processing_time', 0) * stats.get('total_predictions', 0)
                for stats in performance_stats.values()
            ) / total_predictions
        else:
            overall_error_rate = 0
            avg_processing_time = 0
        
        response = {
            'status': 'success',
            'overall_stats': {
                'total_predictions': total_predictions,
                'total_errors': total_errors,
                'overall_error_rate': round(overall_error_rate, 4),
                'average_processing_time': round(avg_processing_time, 4)
            },
            'model_performance': performance_stats,
            'timestamp': datetime.now().isoformat()
        }
        
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error getting analytics: {e}")
        return jsonify({
            'error': 'Internal server error getting analytics',
            'status': 'error'
        }), 500

@advanced_bp.route('/test-models', methods=['POST'])
def test_models():
    """Test all models with a sample text"""
    try:
        data = request.get_json()
        text = data.get('text', 'This is a test message for model comparison.')
        
        if len(text) > config.MAX_TEXT_LENGTH:
            return jsonify({
                'error': f'Text must not exceed {config.MAX_TEXT_LENGTH} characters',
                'status': 'error'
            }), 400
        
        # Test all models
        result = predict_advanced(text)
        
        response = {
            'status': 'success',
            'test_text': text,
            'results': {
                'consensus': {
                    'sentiment': result.consensus_sentiment,
                    'confidence': round(result.average_confidence, 4),
                    'agreement_score': round(result.agreement_score, 4)
                },
                'individual_models': [
                    {
                        'model': r.model_name,
                        'sentiment': r.sentiment,
                        'confidence': round(r.confidence, 4),
                        'processing_time': round(r.processing_time, 4),
                        'status': 'success' if r.sentiment != 'Error' else 'error'
                    }
                    for r in result.results
                ],
                'total_processing_time': round(result.processing_time, 4)
            },
            'timestamp': datetime.now().isoformat()
        }
        
        return jsonify(response)
        
    except Exception as e:
        logger.error(f"Error testing models: {e}")
        return jsonify({
            'error': 'Internal server error testing models',
            'status': 'error'
        }), 500