-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
222 lines (185 loc) · 7.21 KB
/
Copy pathapp.py
File metadata and controls
222 lines (185 loc) · 7.21 KB
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
from flask import Flask, request, jsonify
from flask_cors import CORS
import os
import traceback
from dotenv import load_dotenv
from models.sentiment_analyzer import SentimentAnalyzer
from models.fact_checker import FactChecker
from models.image_analyzer import ImageAnalyzer
from models.video_analyzer import VideoAnalyzer
from models.url_analyzer import URLAnalyzer
load_dotenv()
app = Flask(__name__)
CORS(app)
# Enable debug logging
app.config['DEBUG'] = os.getenv('FLASK_ENV', 'development') == 'development'
# Initialize models
sentiment_analyzer = SentimentAnalyzer()
fact_checker = FactChecker()
image_analyzer = ImageAnalyzer()
video_analyzer = VideoAnalyzer()
url_analyzer = URLAnalyzer()
@app.route('/api/health', methods=['GET'])
def health_check():
"""Health check endpoint"""
return jsonify({
'status': 'healthy',
'message': 'Sentiment Analysis API is running'
})
@app.route('/api/analyze', methods=['POST'])
def analyze_text():
"""
Analyze text for sentiment and truthfulness
Expected JSON: {"text": "your text here", "type": "text|image|video|url", "url": "optional"}
"""
try:
data = request.get_json()
if not data:
return jsonify({
'error': 'No data provided'
}), 400
input_type = data.get('type', 'text')
text = ''
extraction_info = {}
# Extract text based on input type
if input_type == 'text':
text = data.get('text', '')
if not text or len(text.strip()) == 0:
return jsonify({
'error': 'Text cannot be empty'
}), 400
elif input_type == 'image':
image_url = data.get('url', '')
if not image_url:
return jsonify({
'error': 'Image URL is required'
}), 400
# Analyze image
image_result = image_analyzer.analyze_image(image_url)
extraction_info = image_result
if not image_result['success']:
return jsonify({
'error': image_result.get('error', 'Image analysis failed'),
'details': image_result
}), 400
text = image_result['text']
if not text or len(text.strip()) == 0:
return jsonify({
'error': 'No text found in image',
'details': image_result
}), 400
elif input_type == 'video':
video_url = data.get('url', '')
if not video_url:
return jsonify({
'error': 'Video URL is required'
}), 400
# Analyze video
video_result = video_analyzer.analyze_video(video_url)
extraction_info = video_result
if not video_result['success']:
return jsonify({
'error': video_result.get('error', 'Video analysis failed'),
'details': video_result
}), 400
text = video_result['text']
if not text or len(text.strip()) == 0:
return jsonify({
'error': 'No transcript available for this video',
'details': video_result
}), 400
elif input_type == 'url':
page_url = data.get('url', '')
if not page_url:
return jsonify({
'error': 'URL is required'
}), 400
# Analyze URL
url_result = url_analyzer.analyze_url(page_url)
extraction_info = url_result
if not url_result['success']:
return jsonify({
'error': url_result.get('error', 'URL analysis failed'),
'details': url_result
}), 400
text = url_result['text']
if not text or len(text.strip()) == 0:
return jsonify({
'error': 'No content found at URL',
'details': url_result
}), 400
else:
return jsonify({
'error': f'Unsupported input type: {input_type}',
'supported_types': ['text', 'image', 'video', 'url']
}), 400
# Perform sentiment analysis
sentiment_result = sentiment_analyzer.analyze(text)
# Perform fact checking
fact_result = fact_checker.check(text)
# Combine results
result = {
'input_type': input_type,
'text': text[:500] + '...' if len(text) > 500 else text, # Truncate for display
'full_text_length': len(text),
'sentiment': sentiment_result,
'factCheck': fact_result,
'overall': {
'sentiment_label': sentiment_result['label'],
'sentiment_score': sentiment_result['score'],
'truthfulness': fact_result['label'],
'confidence': fact_result['confidence']
}
}
# Add extraction info if available
if extraction_info:
result['extraction'] = {
'success': extraction_info.get('success', False),
'metadata': extraction_info.get('metadata', {})
}
return jsonify(result), 200
except Exception as e:
# Log the full error for debugging
print(f"ERROR in analyze_text: {str(e)}")
print(traceback.format_exc())
return jsonify({
'error': f'Analysis failed: {str(e)}',
'type': type(e).__name__,
'details': str(e) if app.config['DEBUG'] else None
}), 500
@app.route('/api/batch-analyze', methods=['POST'])
def batch_analyze():
"""
Analyze multiple texts
Expected JSON: {"texts": ["text1", "text2", ...]}
"""
try:
data = request.get_json()
if not data or 'texts' not in data:
return jsonify({
'error': 'Missing texts field in request'
}), 400
texts = data['texts']
if not isinstance(texts, list) or len(texts) == 0:
return jsonify({
'error': 'texts must be a non-empty array'
}), 400
results = []
for text in texts:
if text and len(text.strip()) > 0:
sentiment_result = sentiment_analyzer.analyze(text)
fact_result = fact_checker.check(text)
results.append({
'text': text,
'sentiment': sentiment_result,
'factCheck': fact_result
})
return jsonify({'results': results}), 200
except Exception as e:
return jsonify({
'error': f'Batch analysis failed: {str(e)}'
}), 500
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
debug = os.getenv('FLASK_ENV', 'development') == 'development'
app.run(host='0.0.0.0', port=port, debug=debug)