File size: 3,927 Bytes
c3a814a
 
 
 
0fd032c
c3a814a
 
 
 
 
0fd032c
 
 
c3a814a
 
 
 
 
 
 
 
 
 
 
 
 
 
0fd032c
c3a814a
0fd032c
c3a814a
 
 
0fd032c
c3a814a
 
 
 
 
0fd032c
c3a814a
 
 
0fd032c
c3a814a
42bca7e
 
 
 
 
 
 
 
 
c3a814a
0fd032c
42bca7e
0fd032c
42bca7e
 
 
 
 
 
 
 
0fd032c
42bca7e
 
c3a814a
0fd032c
c3a814a
 
 
0fd032c
c3a814a
 
 
 
42bca7e
c3a814a
 
 
 
 
 
 
0fd032c
c3a814a
 
 
0fd032c
c3a814a
 
 
 
42bca7e
c3a814a
 
 
 
 
 
 
0fd032c
c3a814a
 
 
eb9d562
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
import os
import io
import wave
import struct
import logging
from flask import Flask, render_template, request, send_file, jsonify
from werkzeug.utils import secure_filename

app = Flask(__name__)

logging.basicConfig(level=logging.DEBUG)
logger = app.logger

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():
    logger.info("Processing file request received")
    if 'file' not in request.files:
        logger.error("No file part in the request")
        return jsonify({'error': 'No file part'}), 400
    file = request.files['file']
    if file.filename == '':
        logger.error("No selected file")
        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)
        logger.info(f"File saved: {filepath}")

        factor = int(request.form['factor'])
        is_decrypting = filename.lower().endswith('.mp3')
        logger.info(f"Processing file: {'deconverting' if is_decrypting else 'converting'} with factor {factor}")

        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'

            logger.info(f"File processed successfully. Output size: {len(output)} bytes")
            os.remove(filepath)
            logger.info(f"Temporary file removed: {filepath}")

            return send_file(
                io.BytesIO(output),
                mimetype=mimetype,
                as_attachment=True,
                download_name=output_filename
            )
        except Exception as e:
            logger.error(f"Error processing file: {str(e)}")
            os.remove(filepath)
            return jsonify({'error': str(e)}), 500

    logger.error("Invalid file type")
    return jsonify({'error': 'Invalid file type'}), 400

def convert_file(filepath, factor):
    logger.info(f"Converting file: {filepath}")
    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))
    
    logger.info(f"Conversion complete. Output size: {output.getbuffer().nbytes} bytes")
    return output.getvalue()

def deconvert_file(filepath, factor):
    logger.info(f"Deconverting file: {filepath}")
    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))
    
    logger.info(f"Deconversion complete. Output size: {output.getbuffer().nbytes} bytes")
    return output.getvalue()

if __name__ == '__main__':
    app.run(debug=True)