-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
197 lines (163 loc) · 5.85 KB
/
Copy pathapp.py
File metadata and controls
197 lines (163 loc) · 5.85 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
from flask import Flask, request, jsonify, render_template
import os
import uuid
import threading
import time
from datetime import datetime
from video_visualizer import VideoMusicVisualizer
app = Flask(__name__)
# Global job tracking
jobs = {}
class JobStatus:
def __init__(self, job_id):
self.job_id = job_id
self.status = 'pending'
self.progress = 0
self.message = 'Job created'
self.output_file = None
self.error = None
self.created_at = time.time()
def generate_visualization_worker(job_id, audio_path, output_path, width, height, fps, include_audio, text_line1, text_line2):
"""Background worker to generate visualization"""
try:
job = jobs[job_id]
job.status = 'processing'
job.message = 'Initializing visualizer'
# Create visualizer
visualizer = VideoMusicVisualizer(width=width, height=height, fps=fps, text_line1=text_line1, text_line2=text_line2)
job.message = 'Loading audio file'
job.progress = 10
# Load audio
if not visualizer.load_audio(audio_path):
job.status = 'failed'
job.error = 'Failed to load audio file'
# Clear memory before returning
visualizer.audio_data = None
visualizer.spectrum_data = []
return
job.message = 'Rendering visualization'
job.progress = 30
# Progress callback for real-time updates
def update_progress(progress):
job.progress = int(progress)
# Render video
audio_for_output = audio_path if include_audio else None
if visualizer.render_video(output_path, audio_for_output, update_progress):
job.status = 'completed'
job.progress = 100
job.message = 'Visualization completed successfully'
job.output_file = output_path
else:
job.status = 'failed'
job.error = 'Failed to render video'
# Clear heavy data objects to free memory
visualizer.audio_data = None
visualizer.spectrum_data = []
except Exception as e:
job.status = 'failed'
job.error = str(e)
@app.route('/api/visualize', methods=['POST'])
def create_visualization():
"""Create visualization from local audio file"""
data = request.get_json()
if not data or 'audio_path' not in data:
return jsonify({'error': 'audio_path is required'}), 400
audio_path = data['audio_path']
if not os.path.exists(audio_path):
return jsonify({'error': 'Audio file not found'}), 404
# Extract parameters with defaults
output_path = data.get('output_path', f'visualization_{uuid.uuid4()}.mp4')
width = data.get('width', 1920)
height = data.get('height', 1080)
fps = data.get('fps', 50)
include_audio = data.get('include_audio', True)
text_line1 = data.get('text_line1')
text_line2 = data.get('text_line2')
# Generate job ID
job_id = str(uuid.uuid4())
# Create job status
jobs[job_id] = JobStatus(job_id)
# Start background processing
thread = threading.Thread(
target=generate_visualization_worker,
args=(job_id, audio_path, output_path, width, height, fps, include_audio, text_line1, text_line2)
)
thread.daemon = True
thread.start()
return jsonify({
'job_id': job_id,
'status': 'pending',
'message': 'Visualization job started',
'output_path': output_path
})
@app.route('/api/status/<job_id>', methods=['GET'])
def get_job_status(job_id):
"""Get status of visualization job"""
if job_id not in jobs:
return jsonify({'error': 'Job not found'}), 404
job = jobs[job_id]
response = {
'job_id': job_id,
'status': job.status,
'progress': job.progress,
'message': job.message,
'created_at': job.created_at
}
if job.output_file:
response['output_file'] = job.output_file
if job.error:
response['error'] = job.error
return jsonify(response)
@app.route('/api/jobs', methods=['GET'])
def list_jobs():
"""List all jobs"""
job_list = []
for job_id, job in jobs.items():
job_info = {
'job_id': job_id,
'status': job.status,
'progress': job.progress,
'message': job.message,
'created_at': job.created_at
}
if job.output_file:
job_info['output_file'] = job.output_file
job_list.append(job_info)
return jsonify({'jobs': job_list})
@app.route('/api/health', methods=['GET'])
def health_check():
"""Health check endpoint"""
return jsonify({
'status': 'healthy',
'service': 'Music Visualizer API',
'version': '1.0.0'
})
@app.route('/')
def index():
"""Simple API documentation"""
return render_template('index.html')
@app.route('/jobs')
def jobs_dashboard():
"""Jobs dashboard with server-side rendering"""
# Convert jobs to list with formatted data
job_list = []
for job_id, job in jobs.items():
job_data = {
'job_id': job_id,
'status': job.status,
'progress': job.progress,
'message': job.message,
'created_at': job.created_at,
'output_file': job.output_file,
'error': job.error
}
job_list.append(job_data)
# Sort by creation time (newest first)
job_list.sort(key=lambda x: x['created_at'], reverse=True)
return render_template('jobs.html', jobs=job_list)
# Add custom filter for datetime formatting
@app.template_filter('strftime')
def strftime_filter(timestamp):
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)