File size: 8,223 Bytes
adb1220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import time
import os
import subprocess
import zipfile
import base64
from flask import Flask, jsonify, request, send_file, make_response
import libtorrent as lt
from werkzeug.utils import secure_filename
from pdf2docx import Converter
import rarfile
from rembg import remove
from PIL import Image
from waitress import serve
from flask_cors import CORS, cross_origin
from whisper import load_model

app = Flask(__name__)
CORS(app)

ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'webp'])

leet_dict = {
    'a': '4',
    'e': '3',
    'i': '1',
    'o': '0',
    's': '5',
    't': '7',
    'A': '4',
    'E': '3',
    'I': '1',
    'O': '0',
    'S': '5',
    'T': '7'
}

app.config['UPLOAD_FOLDER'] = 'temp/'

if not os.path.exists(app.config['UPLOAD_FOLDER']):
    os.makedirs(app.config['UPLOAD_FOLDER'])


@app.route('/')
def hello_world():
    return jsonify({"status": "online"})


@app.route('/t2m', methods=['POST'])
@cross_origin(origin='*')
def convert_to_magnet():
    if 'file' not in request.files:
        return jsonify({"error": "No file part in the request"}), 400

    file = request.files['file']
    if file.filename == '':
        return jsonify({"error": "No selected file"}), 400

    torrent_data = file.read()

    ti = lt.torrent_info(lt.bdecode(torrent_data))

    magnet_link = lt.make_magnet_uri(ti)

    return jsonify({"magnet_link": magnet_link})


@app.route('/m2t', methods=['POST'])
@cross_origin(origin='*')
def magnet_to_torrent():
    if 'magnet_link' not in request.form:
        return jsonify({"error": "No magnet_link in the request"}), 400

    magnet_link = request.form['magnet_link']
    dst = 'temp'

    try:
        params = lt.parse_magnet_uri(magnet_link)
        params.save_path = dst

        session = lt.session()
        handle = session.add_torrent(params)

        while not handle.has_metadata():
            time.sleep(0.1)

        torrent_info = handle.get_torrent_info()
        torrent_file = lt.create_torrent(torrent_info)
        torrent_path = os.path.join(dst, torrent_info.name() + ".torrent")
        with open(torrent_path, "wb") as f:
            f.write(lt.bencode(torrent_file.generate()))

        response = send_file(torrent_path, as_attachment=True,
                             download_name=torrent_info.name() + ".torrent")
        os.remove(torrent_path)

        return response

    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/w2p', methods=['POST'])
@cross_origin(origin='*')
def convert_word_to_pdf():
    if 'file' not in request.files:
        return {"error": "No file in the request"}, 400

    file = request.files['file']
    filename = secure_filename(file.filename)

    filepath = os.path.join('temp', filename)
    file.save(filepath)

    output_pdf_path = os.path.join('temp', f"{filename.split('.')[0]}.pdf")

    try:
        subprocess.run(['libreoffice', '--headless', '--convert-to',
                       'pdf', filepath, '--outdir', 'temp'], check=True)

        response = send_file(output_pdf_path, as_attachment=True,
                             download_name=f"{filename.split('.')[0]}.pdf")

        os.remove(filepath)
        os.remove(output_pdf_path)

        return response
    except Exception as e:
        return {"error": str(e)}, 500


@app.route('/p2w', methods=['POST'])
@cross_origin(origin='*')
def convert_pdf_to_word():
    if 'file' not in request.files:
        return {"error": "No file in the request"}, 400

    file = request.files['file']
    filename = secure_filename(file.filename)

    filepath = os.path.join('temp', filename)
    file.save(filepath)

    output_word_path = os.path.join('temp', f"{filename.split('.')[0]}.docx")

    try:
        cv = Converter(filepath)
        cv.convert(output_word_path, start=0, end=None)
        cv.close()

        response = send_file(output_word_path, as_attachment=True,
                             download_name=f"{filename.split('.')[0]}.docx")

        os.remove(filepath)
        os.remove(output_word_path)

        return response
    except Exception as e:
        return {"error": str(e)}, 500


@app.route('/unzip', methods=['POST'])
@cross_origin(origin='*')
def upload_file():
    if 'file' not in request.files:
        return jsonify({"error": "No file in the request"}), 400

    file = request.files['file']
    filename = secure_filename(file.filename)
    filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
    file.save(filepath)

    try:
        if filename.endswith('.zip'):
            unzip_file(filepath)
        elif filename.endswith('.rar'):
            unrar_file(filepath)
        else:
            return jsonify({"error": "Unsupported file type"}), 400

        os.remove(filepath)

        return jsonify({"message": "File unzipped successfully"}), 200
    except Exception as e:
        return jsonify({"error": str(e)}), 500


@app.route('/rmbg', methods=['POST'])
@cross_origin(origin='*')
def remback():
    if 'file' not in request.files:
        return 'No file part', 400
    file = request.files['file']
    if file.filename == '':
        return 'No selected file', 400
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)
        output_filename = filename.split('.')[0] + "_rembg.png"
        output_path = os.path.join(
            app.config['UPLOAD_FOLDER'], output_filename)
        remove_background(file_path, output_path)

        response = send_file(output_path, mimetype='image/png')

        os.remove(file_path)
        os.remove(output_path)

        return response
    else:
        return 'File type not allowed', 400


@app.route('/b64en', methods=['POST'])
@cross_origin(origin='*')
def encode_base64():
    data = request.get_json()
    if 'string' not in data:
        return make_response(jsonify({'error': 'Missing string parameter'}), 400)
    base64_data = base64.b64encode(
        data['string'].encode('utf-8')).decode('utf-8')
    return jsonify({'base64_data': base64_data})


@app.route('/b64de', methods=['POST'])
@cross_origin(origin='*')
def decode_base64():
    data = request.get_json()
    if 'string' not in data:
        return make_response(jsonify({'error': 'Missing string parameter'}), 400)
    try:
        decoded_data = base64.b64decode(data['string']).decode('utf-8')
    except Exception as _:
        return make_response(jsonify({'error': 'Invalid base64 string'}), 400)
    return jsonify({'decoded_data': decoded_data})


@app.route('/toleet', methods=['POST'])
def convert_to_leet():
    data = request.get_json()
    if 'text' not in data:
        return jsonify({"error": "No text provided"}), 400

    text = data['text']
    leet_text = to_leet(text)
    return jsonify({"leet_text": leet_text})


@app.route('/totext', methods=['POST'])
def speech_to_text():
    audio_file = request.files['audio']
    if audio_file:
        filename = secure_filename(audio_file.filename)
        audio_file.save(os.path.join('temp', filename))
    else:
        return {'error': 'No audio_file file provided'},  400

    model = load_model("tiny")

    result = model.transcribe(f"temp/{filename}")

    transcription = result["text"]

    os.remove(f"temp/{filename}")

    return jsonify({'transcription': transcription})


def unzip_file(filepath):
    with zipfile.ZipFile(filepath, 'r') as zip_ref:
        zip_ref.extractall(app.config['UPLOAD_FOLDER'])


def unrar_file(filepath):
    with rarfile.RarFile(filepath, 'r') as rar_ref:
        rar_ref.extractall(app.config['UPLOAD_FOLDER'])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS


def remove_background(input_path, output_path):
    input_img = Image.open(input_path)
    output_img = remove(input_img)
    output_img.save(output_path)


def to_leet(text):
    leet_text = ""
    for char in text:
        if char in leet_dict:
            leet_text += leet_dict[char]
        else:
            leet_text += char
    return leet_text


if __name__ == '__main__':
    serve(app, host='0.0.0.0', port=7860, threads=10)