alphg commited on
Commit
adb1220
·
verified ·
1 Parent(s): ed6a81c

Create api.py

Browse files
Files changed (1) hide show
  1. api.py +300 -0
api.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ import os
3
+ import subprocess
4
+ import zipfile
5
+ import base64
6
+ from flask import Flask, jsonify, request, send_file, make_response
7
+ import libtorrent as lt
8
+ from werkzeug.utils import secure_filename
9
+ from pdf2docx import Converter
10
+ import rarfile
11
+ from rembg import remove
12
+ from PIL import Image
13
+ from waitress import serve
14
+ from flask_cors import CORS, cross_origin
15
+ from whisper import load_model
16
+
17
+ app = Flask(__name__)
18
+ CORS(app)
19
+
20
+ ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'webp'])
21
+
22
+ leet_dict = {
23
+ 'a': '4',
24
+ 'e': '3',
25
+ 'i': '1',
26
+ 'o': '0',
27
+ 's': '5',
28
+ 't': '7',
29
+ 'A': '4',
30
+ 'E': '3',
31
+ 'I': '1',
32
+ 'O': '0',
33
+ 'S': '5',
34
+ 'T': '7'
35
+ }
36
+
37
+ app.config['UPLOAD_FOLDER'] = 'temp/'
38
+
39
+ if not os.path.exists(app.config['UPLOAD_FOLDER']):
40
+ os.makedirs(app.config['UPLOAD_FOLDER'])
41
+
42
+
43
+ @app.route('/')
44
+ def hello_world():
45
+ return jsonify({"status": "online"})
46
+
47
+
48
+ @app.route('/t2m', methods=['POST'])
49
+ @cross_origin(origin='*')
50
+ def convert_to_magnet():
51
+ if 'file' not in request.files:
52
+ return jsonify({"error": "No file part in the request"}), 400
53
+
54
+ file = request.files['file']
55
+ if file.filename == '':
56
+ return jsonify({"error": "No selected file"}), 400
57
+
58
+ torrent_data = file.read()
59
+
60
+ ti = lt.torrent_info(lt.bdecode(torrent_data))
61
+
62
+ magnet_link = lt.make_magnet_uri(ti)
63
+
64
+ return jsonify({"magnet_link": magnet_link})
65
+
66
+
67
+ @app.route('/m2t', methods=['POST'])
68
+ @cross_origin(origin='*')
69
+ def magnet_to_torrent():
70
+ if 'magnet_link' not in request.form:
71
+ return jsonify({"error": "No magnet_link in the request"}), 400
72
+
73
+ magnet_link = request.form['magnet_link']
74
+ dst = 'temp'
75
+
76
+ try:
77
+ params = lt.parse_magnet_uri(magnet_link)
78
+ params.save_path = dst
79
+
80
+ session = lt.session()
81
+ handle = session.add_torrent(params)
82
+
83
+ while not handle.has_metadata():
84
+ time.sleep(0.1)
85
+
86
+ torrent_info = handle.get_torrent_info()
87
+ torrent_file = lt.create_torrent(torrent_info)
88
+ torrent_path = os.path.join(dst, torrent_info.name() + ".torrent")
89
+ with open(torrent_path, "wb") as f:
90
+ f.write(lt.bencode(torrent_file.generate()))
91
+
92
+ response = send_file(torrent_path, as_attachment=True,
93
+ download_name=torrent_info.name() + ".torrent")
94
+ os.remove(torrent_path)
95
+
96
+ return response
97
+
98
+ except Exception as e:
99
+ return jsonify({"error": str(e)}), 500
100
+
101
+
102
+ @app.route('/w2p', methods=['POST'])
103
+ @cross_origin(origin='*')
104
+ def convert_word_to_pdf():
105
+ if 'file' not in request.files:
106
+ return {"error": "No file in the request"}, 400
107
+
108
+ file = request.files['file']
109
+ filename = secure_filename(file.filename)
110
+
111
+ filepath = os.path.join('temp', filename)
112
+ file.save(filepath)
113
+
114
+ output_pdf_path = os.path.join('temp', f"{filename.split('.')[0]}.pdf")
115
+
116
+ try:
117
+ subprocess.run(['libreoffice', '--headless', '--convert-to',
118
+ 'pdf', filepath, '--outdir', 'temp'], check=True)
119
+
120
+ response = send_file(output_pdf_path, as_attachment=True,
121
+ download_name=f"{filename.split('.')[0]}.pdf")
122
+
123
+ os.remove(filepath)
124
+ os.remove(output_pdf_path)
125
+
126
+ return response
127
+ except Exception as e:
128
+ return {"error": str(e)}, 500
129
+
130
+
131
+ @app.route('/p2w', methods=['POST'])
132
+ @cross_origin(origin='*')
133
+ def convert_pdf_to_word():
134
+ if 'file' not in request.files:
135
+ return {"error": "No file in the request"}, 400
136
+
137
+ file = request.files['file']
138
+ filename = secure_filename(file.filename)
139
+
140
+ filepath = os.path.join('temp', filename)
141
+ file.save(filepath)
142
+
143
+ output_word_path = os.path.join('temp', f"{filename.split('.')[0]}.docx")
144
+
145
+ try:
146
+ cv = Converter(filepath)
147
+ cv.convert(output_word_path, start=0, end=None)
148
+ cv.close()
149
+
150
+ response = send_file(output_word_path, as_attachment=True,
151
+ download_name=f"{filename.split('.')[0]}.docx")
152
+
153
+ os.remove(filepath)
154
+ os.remove(output_word_path)
155
+
156
+ return response
157
+ except Exception as e:
158
+ return {"error": str(e)}, 500
159
+
160
+
161
+ @app.route('/unzip', methods=['POST'])
162
+ @cross_origin(origin='*')
163
+ def upload_file():
164
+ if 'file' not in request.files:
165
+ return jsonify({"error": "No file in the request"}), 400
166
+
167
+ file = request.files['file']
168
+ filename = secure_filename(file.filename)
169
+ filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
170
+ file.save(filepath)
171
+
172
+ try:
173
+ if filename.endswith('.zip'):
174
+ unzip_file(filepath)
175
+ elif filename.endswith('.rar'):
176
+ unrar_file(filepath)
177
+ else:
178
+ return jsonify({"error": "Unsupported file type"}), 400
179
+
180
+ os.remove(filepath)
181
+
182
+ return jsonify({"message": "File unzipped successfully"}), 200
183
+ except Exception as e:
184
+ return jsonify({"error": str(e)}), 500
185
+
186
+
187
+ @app.route('/rmbg', methods=['POST'])
188
+ @cross_origin(origin='*')
189
+ def remback():
190
+ if 'file' not in request.files:
191
+ return 'No file part', 400
192
+ file = request.files['file']
193
+ if file.filename == '':
194
+ return 'No selected file', 400
195
+ if file and allowed_file(file.filename):
196
+ filename = secure_filename(file.filename)
197
+ file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
198
+ file.save(file_path)
199
+ output_filename = filename.split('.')[0] + "_rembg.png"
200
+ output_path = os.path.join(
201
+ app.config['UPLOAD_FOLDER'], output_filename)
202
+ remove_background(file_path, output_path)
203
+
204
+ response = send_file(output_path, mimetype='image/png')
205
+
206
+ os.remove(file_path)
207
+ os.remove(output_path)
208
+
209
+ return response
210
+ else:
211
+ return 'File type not allowed', 400
212
+
213
+
214
+ @app.route('/b64en', methods=['POST'])
215
+ @cross_origin(origin='*')
216
+ def encode_base64():
217
+ data = request.get_json()
218
+ if 'string' not in data:
219
+ return make_response(jsonify({'error': 'Missing string parameter'}), 400)
220
+ base64_data = base64.b64encode(
221
+ data['string'].encode('utf-8')).decode('utf-8')
222
+ return jsonify({'base64_data': base64_data})
223
+
224
+
225
+ @app.route('/b64de', methods=['POST'])
226
+ @cross_origin(origin='*')
227
+ def decode_base64():
228
+ data = request.get_json()
229
+ if 'string' not in data:
230
+ return make_response(jsonify({'error': 'Missing string parameter'}), 400)
231
+ try:
232
+ decoded_data = base64.b64decode(data['string']).decode('utf-8')
233
+ except Exception as _:
234
+ return make_response(jsonify({'error': 'Invalid base64 string'}), 400)
235
+ return jsonify({'decoded_data': decoded_data})
236
+
237
+
238
+ @app.route('/toleet', methods=['POST'])
239
+ def convert_to_leet():
240
+ data = request.get_json()
241
+ if 'text' not in data:
242
+ return jsonify({"error": "No text provided"}), 400
243
+
244
+ text = data['text']
245
+ leet_text = to_leet(text)
246
+ return jsonify({"leet_text": leet_text})
247
+
248
+
249
+ @app.route('/totext', methods=['POST'])
250
+ def speech_to_text():
251
+ audio_file = request.files['audio']
252
+ if audio_file:
253
+ filename = secure_filename(audio_file.filename)
254
+ audio_file.save(os.path.join('temp', filename))
255
+ else:
256
+ return {'error': 'No audio_file file provided'}, 400
257
+
258
+ model = load_model("tiny")
259
+
260
+ result = model.transcribe(f"temp/{filename}")
261
+
262
+ transcription = result["text"]
263
+
264
+ os.remove(f"temp/{filename}")
265
+
266
+ return jsonify({'transcription': transcription})
267
+
268
+
269
+ def unzip_file(filepath):
270
+ with zipfile.ZipFile(filepath, 'r') as zip_ref:
271
+ zip_ref.extractall(app.config['UPLOAD_FOLDER'])
272
+
273
+
274
+ def unrar_file(filepath):
275
+ with rarfile.RarFile(filepath, 'r') as rar_ref:
276
+ rar_ref.extractall(app.config['UPLOAD_FOLDER'])
277
+
278
+
279
+ def allowed_file(filename):
280
+ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
281
+
282
+
283
+ def remove_background(input_path, output_path):
284
+ input_img = Image.open(input_path)
285
+ output_img = remove(input_img)
286
+ output_img.save(output_path)
287
+
288
+
289
+ def to_leet(text):
290
+ leet_text = ""
291
+ for char in text:
292
+ if char in leet_dict:
293
+ leet_text += leet_dict[char]
294
+ else:
295
+ leet_text += char
296
+ return leet_text
297
+
298
+
299
+ if __name__ == '__main__':
300
+ serve(app, host='0.0.0.0', port=7860, threads=10)