import os import io import wave import struct from flask import Flask, render_template, request, send_file, jsonify from werkzeug.utils import secure_filename app = Flask(__name__) UPLOAD_FOLDER = '/tmp' ALLOWED_EXTENSIONS = {'mp3', 'wav'} app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/') def index(): return render_template('index.html') @app.route('/process', methods=['POST']) def process_file(): if 'file' not in request.files: return jsonify({'error': 'No file part'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'error': 'No selected file'}), 400 if file and allowed_file(file.filename): filename = secure_filename(file.filename) filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename) file.save(filepath) factor = int(request.form['factor']) is_decrypting = filename.lower().endswith('.mp3') try: if is_decrypting: output = deconvert_file(filepath, factor) output_filename = 'deconverted_file.wav' mimetype = 'audio/wav' else: output = convert_file(filepath, factor) output_filename = 'converted_file.mp3' mimetype = 'audio/mpeg' os.remove(filepath) return send_file( io.BytesIO(output), mimetype=mimetype, as_attachment=True, download_name=output_filename ) except Exception as e: os.remove(filepath) return jsonify({'error': str(e)}), 500 return jsonify({'error': 'Invalid file type'}), 400 def convert_file(filepath, factor): with wave.open(filepath, 'rb') as wav_file: params = wav_file.getparams() frames = wav_file.readframes(wav_file.getnframes()) audio_data = struct.unpack(f'{len(frames)//params.sampwidth}h', frames) modified_data = [int(sample * factor / 100) for sample in audio_data] output = io.BytesIO() with wave.open(output, 'wb') as wav_output: wav_output.setparams(params) wav_output.writeframes(struct.pack(f'{len(modified_data)}h', *modified_data)) return output.getvalue() def deconvert_file(filepath, factor): with wave.open(filepath, 'rb') as wav_file: params = wav_file.getparams() frames = wav_file.readframes(wav_file.getnframes()) audio_data = struct.unpack(f'{len(frames)//params.sampwidth}h', frames) modified_data = [int(sample * 100 / factor) for sample in audio_data] output = io.BytesIO() with wave.open(output, 'wb') as wav_output: wav_output.setparams(params) wav_output.writeframes(struct.pack(f'{len(modified_data)}h', *modified_data)) return output.getvalue() if __name__ == '__main__': app.run(debug=True)