-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdebug_app.py
More file actions
172 lines (149 loc) · 6.17 KB
/
Copy pathdebug_app.py
File metadata and controls
172 lines (149 loc) · 6.17 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
"""
Debug version of the Flask app with enhanced error reporting
Run this to test the application and get detailed error information
"""
from flask import Flask, render_template, request, jsonify
import os
import traceback
import sys
app = Flask(__name__)
app.config['DEBUG'] = True
@app.route('/')
def index():
return '''
<h1>Debug Mode - Mood Prediction API</h1>
<h2>Test Endpoints:</h2>
<ul>
<li><a href="/health">Health Check</a></li>
<li><a href="/test-imports">Test Imports</a></li>
</ul>
<h2>Upload Test:</h2>
<form action="/predict" method="post" enctype="multipart/form-data">
<input type="file" name="audio" accept="audio/*" required>
<button type="submit">Upload and Predict</button>
</form>
'''
@app.route('/health')
def health():
"""Health check with detailed diagnostic information"""
health_info = {
'status': 'checking...',
'python_version': sys.version,
'working_directory': os.getcwd(),
'files': {
'model.pth': os.path.exists('model.pth'),
'label_encoder.pkl': os.path.exists('label_encoder.pkl'),
'predict_mood.py': os.path.exists('predict_mood.py'),
'music_mood_therapy_prototype.py': os.path.exists('music_mood_therapy_prototype.py')
},
'imports': {},
'model_info': {}
}
# Test imports
imports_to_test = ['torch', 'librosa', 'numpy', 'joblib', 'sklearn']
for imp in imports_to_test:
try:
__import__(imp)
health_info['imports'][imp] = 'OK'
except Exception as e:
health_info['imports'][imp] = f'FAILED: {str(e)}'
# Test custom module imports
try:
from predict_mood import predict_mood, _load_artifacts
health_info['imports']['predict_mood'] = 'OK'
# Test model loading
try:
model, encoder = _load_artifacts()
health_info['model_info']['model_loaded'] = True
health_info['model_info']['encoder_classes'] = len(getattr(encoder, 'classes_', []))
except Exception as e:
health_info['model_info']['model_load_error'] = str(e)
health_info['model_info']['model_loaded'] = False
except Exception as e:
health_info['imports']['predict_mood'] = f'FAILED: {str(e)}'
# Determine overall status
all_files_exist = all(health_info['files'].values())
imports_ok = all('OK' in status for status in health_info['imports'].values())
model_loaded = health_info['model_info'].get('model_loaded', False)
if all_files_exist and imports_ok and model_loaded:
health_info['status'] = 'healthy'
return jsonify(health_info)
else:
health_info['status'] = 'unhealthy'
return jsonify(health_info), 500
@app.route('/test-imports')
def test_imports():
"""Test all imports and return detailed information"""
import subprocess
import sys
# Run the test script if it exists
if os.path.exists('test_imports.py'):
try:
result = subprocess.run([sys.executable, 'test_imports.py'],
capture_output=True, text=True, timeout=30)
return f"<pre>{result.stdout}\n{result.stderr}</pre>"
except Exception as e:
return f"<pre>Error running test_imports.py: {e}</pre>"
else:
return "<pre>test_imports.py not found</pre>"
@app.route('/predict', methods=['POST'])
def predict_debug():
"""Debug version of predict endpoint"""
debug_info = {
'request_info': {
'method': request.method,
'content_type': request.content_type,
'files': list(request.files.keys()) if request.files else []
},
'steps': [],
'errors': []
}
try:
debug_info['steps'].append("Starting prediction process")
# Check file
file = request.files.get('audio')
if not file or not file.filename:
debug_info['errors'].append("No audio file provided")
return jsonify({'success': False, 'error': 'No audio file provided', 'debug': debug_info}), 400
debug_info['steps'].append(f"File received: {file.filename}")
# Try to import predict_mood
try:
from predict_mood import predict_mood
debug_info['steps'].append("predict_mood imported successfully")
except Exception as e:
debug_info['errors'].append(f"Failed to import predict_mood: {str(e)}")
return jsonify({'success': False, 'error': 'Import failed', 'debug': debug_info}), 500
# Save file
from werkzeug.utils import secure_filename
filename = secure_filename(file.filename)
upload_folder = 'static/uploads'
os.makedirs(upload_folder, exist_ok=True)
filepath = os.path.join(upload_folder, filename)
file.save(filepath)
debug_info['steps'].append(f"File saved to: {filepath}")
# Try prediction
try:
result = predict_mood(filepath)
debug_info['steps'].append(f"Prediction completed: {result.get('mood', 'Unknown')}")
return jsonify({
'success': True,
'mood': result.get('mood', 'Unknown'),
'confidence': result.get('confidence', 0),
'debug': debug_info
})
except Exception as e:
debug_info['errors'].append(f"Prediction failed: {str(e)}")
debug_info['traceback'] = traceback.format_exc()
return jsonify({'success': False, 'error': 'Prediction failed', 'debug': debug_info}), 500
except Exception as e:
debug_info['errors'].append(f"Unexpected error: {str(e)}")
debug_info['traceback'] = traceback.format_exc()
return jsonify({'success': False, 'error': 'Unexpected error', 'debug': debug_info}), 500
if __name__ == '__main__':
print("=" * 50)
print("DEBUG MODE - Enhanced Error Reporting")
print("=" * 50)
print(f"Working directory: {os.getcwd()}")
print(f"Python version: {sys.version}")
print("=" * 50)
app.run(debug=True, host='127.0.0.1', port=5001)