AdityaAdaki commited on
Commit
c071803
·
1 Parent(s): feee5aa
Files changed (1) hide show
  1. app.py +44 -5
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from flask import Flask, render_template, request, jsonify, send_from_directory
2
  import os
3
  import tempfile
4
  import atexit
@@ -18,33 +18,49 @@ import base64
18
  from concurrent.futures import ThreadPoolExecutor
19
  import asyncio
20
  from flask_compress import Compress
 
 
21
 
22
  # Create uploads directory in the static folder instead of using tempfile
23
  UPLOAD_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'uploads')
24
  if not os.path.exists(UPLOAD_DIR):
25
  os.makedirs(UPLOAD_DIR, exist_ok=True)
26
 
 
27
  app = Flask(__name__, static_folder='static')
 
 
28
  app.config['UPLOAD_FOLDER'] = UPLOAD_DIR
29
  app.config['MAX_CONTENT_LENGTH'] = 200 * 1024 * 1024 # 200MB max file size
30
  app.config['MAX_FILES'] = 10 # Maximum number of files that can be uploaded at once
31
 
32
- ALLOWED_EXTENSIONS = {'mp3', 'wav', 'ogg', 'flac'} # Added FLAC support
33
- FILE_LIFETIME = timedelta(hours=1) # Files will be deleted after 1 hour
 
 
 
 
 
 
 
 
34
 
35
- # Store file creation times
 
 
36
  file_timestamps = {}
37
 
38
  # Configure logging
39
  logging.basicConfig(level=logging.INFO)
40
  logger = logging.getLogger(__name__)
41
 
42
- THREAD_POOL = ThreadPoolExecutor(max_workers=8) # Increased from 4 to 8
43
 
44
  def allowed_file(filename):
45
  return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
46
 
47
  # Optimize metadata extraction
 
48
  def extract_metadata(filepath):
49
  try:
50
  audio = File(filepath, easy=True) # Added easy=True for faster loading
@@ -87,7 +103,9 @@ def extract_metadata(filepath):
87
  def favicon():
88
  return send_from_directory('static', 'favicon.ico', mimetype='image/x-icon')
89
 
 
90
  @app.route('/')
 
91
  def index():
92
  return render_template('index.html', title="Soundscape - 3D Music Visualizer")
93
 
@@ -124,6 +142,20 @@ def request_entity_too_large(error):
124
  'error': 'File too large. Maximum total size is 200MB'
125
  }), 413
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  @app.route('/upload', methods=['POST'])
128
  def upload_file():
129
  logger.info('Upload request received')
@@ -165,6 +197,9 @@ def upload_file():
165
  # Process metadata in parallel
166
  metadata = extract_metadata(filepath)
167
 
 
 
 
168
  return {
169
  'filename': file.filename,
170
  'success': True,
@@ -213,5 +248,9 @@ def add_header(response):
213
  response.headers['Cache-Control'] = 'public, max-age=300'
214
  return response
215
 
 
 
 
 
216
  if __name__ == '__main__':
217
  app.run(host='0.0.0.0', port=7860)
 
1
+ from flask import Flask, render_template, request, jsonify, send_from_directory, make_response
2
  import os
3
  import tempfile
4
  import atexit
 
18
  from concurrent.futures import ThreadPoolExecutor
19
  import asyncio
20
  from flask_compress import Compress
21
+ from flask_caching import Cache
22
+ import hashlib
23
 
24
  # Create uploads directory in the static folder instead of using tempfile
25
  UPLOAD_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static', 'uploads')
26
  if not os.path.exists(UPLOAD_DIR):
27
  os.makedirs(UPLOAD_DIR, exist_ok=True)
28
 
29
+ # Initialize Flask app once with all configurations
30
  app = Flask(__name__, static_folder='static')
31
+
32
+ # Add all app configs
33
  app.config['UPLOAD_FOLDER'] = UPLOAD_DIR
34
  app.config['MAX_CONTENT_LENGTH'] = 200 * 1024 * 1024 # 200MB max file size
35
  app.config['MAX_FILES'] = 10 # Maximum number of files that can be uploaded at once
36
 
37
+ # Add cache config
38
+ cache_config = {
39
+ "DEBUG": True,
40
+ "CACHE_TYPE": "SimpleCache",
41
+ "CACHE_DEFAULT_TIMEOUT": 300
42
+ }
43
+ app.config.from_mapping(cache_config)
44
+
45
+ # Initialize cache
46
+ cache = Cache(app)
47
 
48
+ # Rest of your constants
49
+ ALLOWED_EXTENSIONS = {'mp3', 'wav', 'ogg', 'flac'}
50
+ FILE_LIFETIME = timedelta(hours=1)
51
  file_timestamps = {}
52
 
53
  # Configure logging
54
  logging.basicConfig(level=logging.INFO)
55
  logger = logging.getLogger(__name__)
56
 
57
+ THREAD_POOL = ThreadPoolExecutor(max_workers=8)
58
 
59
  def allowed_file(filename):
60
  return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
61
 
62
  # Optimize metadata extraction
63
+ @cache.memoize(timeout=3600) # Cache for 1 hour
64
  def extract_metadata(filepath):
65
  try:
66
  audio = File(filepath, easy=True) # Added easy=True for faster loading
 
103
  def favicon():
104
  return send_from_directory('static', 'favicon.ico', mimetype='image/x-icon')
105
 
106
+ # Cache the index page
107
  @app.route('/')
108
+ @cache.cached(timeout=300) # Cache for 5 minutes
109
  def index():
110
  return render_template('index.html', title="Soundscape - 3D Music Visualizer")
111
 
 
142
  'error': 'File too large. Maximum total size is 200MB'
143
  }), 413
144
 
145
+ # Cache static file responses
146
+ @app.route('/static/<path:filename>')
147
+ @cache.cached(timeout=3600) # Cache for 1 hour
148
+ def serve_static(filename):
149
+ response = make_response(send_from_directory('static', filename))
150
+
151
+ # Add cache control headers
152
+ response.headers['Cache-Control'] = 'public, max-age=3600'
153
+ response.headers['ETag'] = hashlib.md5(
154
+ str(time.time()).encode()
155
+ ).hexdigest()
156
+
157
+ return response
158
+
159
  @app.route('/upload', methods=['POST'])
160
  def upload_file():
161
  logger.info('Upload request received')
 
197
  # Process metadata in parallel
198
  metadata = extract_metadata(filepath)
199
 
200
+ # Invalidate cache if needed
201
+ invalidate_metadata_cache(filepath)
202
+
203
  return {
204
  'filename': file.filename,
205
  'success': True,
 
248
  response.headers['Cache-Control'] = 'public, max-age=300'
249
  return response
250
 
251
+ # Add cache invalidation for uploaded files
252
+ def invalidate_metadata_cache(filepath):
253
+ cache.delete_memoized(extract_metadata, filepath)
254
+
255
  if __name__ == '__main__':
256
  app.run(host='0.0.0.0', port=7860)