def process(): input_path = generate_random_filename("jpg") output_path = generate_random_filename("png") try: url = request.json["url"] download(url, input_path) jpeg_str = open(input_path, "rb").read() orignal_im = Image.open(BytesIO(jpeg_str)) resized_im, seg_map = run(orignal_im, True) drawSegment(resized_im, seg_map, output_path) callback = send_file(output_path, mimetype='image/png') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([ input_path, output_path ])
def process(): input_path = generate_random_filename(upload_directory, "jpg") output_path = generate_random_filename(upload_directory, "jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) else: url = request.json["url"] download(url, input_path) results = [] image = cv2.imread(input_path) gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imwrite(output_path, gray_image) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])
def process(): input_path = generate_random_filename(upload_directory, "jpg") output_path = generate_random_filename(result_directory, "jpg") try: url = request.json["url"] download(url, input_path) with tf.Session(config=tf.ConfigProto( allow_soft_placement=True)) as sess: gan = UGATIT(sess, args) gan.build_model() gan.test_endpoint_init() gan.test_endpoint(input_path, output_path) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])
def process(): input_path = generate_random_filename(upload_directory, "jpg") output_path = generate_random_filename(upload_directory, "jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) else: url = request.json["url"] download(url, input_path) results = runner(input_path) return results, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])
def process(): input_path = generate_random_filename(upload_directory, "jpg") output_path = generate_random_filename(upload_directory, "jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) else: url = request.json["url"] download(url, input_path) deblur.test(args.height, args.width, input_path, output_path) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])
def process(): input_path = generate_random_filename(upload_directory, "jpg") output_path = generate_random_filename(result_directory, "jpg") try: # todo: detect image type from extension if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) else: url = request.json["url"] download(url, input_path) img = Image.open(input_path) img = img.convert('RGB') lr_img = np.array(img) # sr_img = rdn.predict(lr_img) if lr_img.shape[0] >= 360 or lr_img.shape[1] >= 640 else rrdn.predict(lr_img) sr_img = rrdn.predict(lr_img) # sr_img = rdn.predict(lr_img) im = Image.fromarray(sr_img) im.save(output_path, "JPEG") callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])
def process(): if 'file' not in request.files: flash('No file part') return redirect('/') submitted_file = request.files['file'] if submitted_file.filename == '': flash('No selected file') return redirect('/') if submitted_file and allowed_file(submitted_file.filename): filename = secure_filename(submitted_file.filename) input_path = os.path.join(app.config['UPLOAD_FOLDER'], 'deoldified_' + filename) submitted_file.save(input_path) render_factor = int(request.form.get('render_factor', 10)) try: if is_video(input_path): output_path = os.path.join(results_video_directory, os.path.basename(input_path)) return process_video(input_path, output_path, render_factor) output_path = os.path.join(results_img_directory, os.path.basename(input_path)) return process_image(input_path, output_path, render_factor) finally: clean_all([input_path, output_path]) return redirect('/')
def process_image(): input_path = generate_random_filename(upload_directory,"jpeg") output_path = os.path.join(results_img_directory, os.path.basename(input_path)) try: url = request.json["source_url"] render_factor = 35 #int(request.json["render_factor"]) download(url, input_path) try: image_colorizer.plot_transformed_image(path=input_path, figsize=(20,20), render_factor=render_factor, display_render_factor=True, compare=False) except: convertToJPG(input_path) image_colorizer.plot_transformed_image(path=input_path, figsize=(20,20), render_factor=render_factor, display_render_factor=True, compare=False) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except DownloadPrecheckFailed as e: return jsonify({'message': str(e)}), 400 except: traceback.print_exc() return jsonify({'message': 'inference error'}), 500 finally: pass clean_all([ input_path, output_path ])
def process_image(): input_path = generate_random_filename(upload_directory, "jpeg") output_path = os.path.join(results_img_directory, os.path.basename(input_path)) try: url = request.json["source_url"] # render_factor = 35 #int(request.json["render_factor"]) download(url, input_path) run(input_path) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except DownloadPrecheckFailed as e: return jsonify({'message': str(e)}), 400 except: traceback.print_exc() return jsonify({'message': 'inference error'}), 500 finally: pass clean_all([input_path, output_path])
def detect(): input_path = generate_random_filename(upload_directory, "jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) else: url = request.json["url"] download(url, input_path) results = [] image = face_recognition.load_image_file(input_path) locations = face_recognition.face_locations(image) for location in locations: results.append({ 'y-top': location[0], 'x-top': location[1], 'y-bottom': location[2], 'x-bottom': location[3] }) return json.dumps(results), 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path])
def detect(): input_path = generate_random_filename(upload_directory,"jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) else: url = request.json["url"] download(url, input_path) results = [] nudity = classify(input_path) results.append({"nudity": str(True),"score": "{0:.4f}".format(nudity)}) results.append({"nudity": str(False), "score": "{0:.4f}".format(1-nudity)}) return json.dumps(results), 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([ input_path ])
def process(): input_path = generate_random_filename(upload_directory,"jpg") output_path = generate_random_filename(result_directory,"jpg") try: url = request.json["url"] download(url, input_path) img = Image.open(input_path) img = img.convert('RGB') lr_img = np.array(img) sr_img = rdn.predict(lr_img) im = Image.fromarray(sr_img) im.save(output_path, "JPEG") callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([ input_path, output_path ])
def process(): input_path = generate_random_filename(upload_directory, "jpg") output_path = generate_random_filename(result_directory, "jpg") try: url = request.json["url"] download(url, input_path) try: detecter = FaceCropper() detecter.generate(input_path, input_path, 20, False) # print("face_crop") except: im = Image.open(input_path) width, height = im.size print(im.size) center_x = width / 2 center_y = height / 2 box_size = min(width, height) print(box_size) left = center_x - box_size / 2 top = center_y - box_size / 2 width = box_size height = box_size box = (left, top, left + width, top + height) area = im.crop(box) area = im.convert("RGB") area.save(input_path, "JPEG", quality=80, optimize=True, progressive=True) print("image_crop") gan.test_endpoint(input_path, output_path) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])
def process_image(): input_path = generate_random_filename(upload_directory, "jpeg") output_path = os.path.join(results_img_directory, os.path.basename(input_path)) print(request.files) try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) try: render_factor = request.form.getlist('render_factor')[0] except: render_factor = 30 else: url = request.json["url"] download(url, input_path) try: render_factor = request.json["render_factor"] except: render_factor = 30 try: image_colorizer.plot_transformed_image( path=input_path, out_path=output_path, figsize=(20, 20), render_factor=int(render_factor), display_render_factor=True, compare=False) except: convertToJPG(input_path) image_colorizer.plot_transformed_image( path=input_path, out_path=output_path, figsize=(20, 20), render_factor=int(render_factor), display_render_factor=True, compare=False) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: pass clean_all([input_path, output_path])
def process(): input_path = generate_random_filename(upload_directory,"jpg") output_path = generate_random_filename(upload_directory,"jpg") try: url = request.json["url"] # phone: iphone, blackberr or sony phone = request.json["phone"] # resolution: orig,high,medium,small,tiny resolution = request.json["resolution"] download(url, input_path) # get the specified image resolution IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_SIZE = utils.get_specified_res(res_sizes, phone, resolution) # create placeholders for input images x_ = tf.placeholder(tf.float32, [None, IMAGE_SIZE]) x_image = tf.reshape(x_, [-1, IMAGE_HEIGHT, IMAGE_WIDTH, 3]) # generate enhanced image enhanced = resnet(x_image) with tf.Session(config=config) as sess: saver = tf.train.Saver() saver.restore(sess, "models_orig/" + phone + "_orig") image = np.float16(misc.imresize(misc.imread(filename), res_sizes[phone])) / 255 image_crop = utils.extract_crop(image, resolution, phone, res_sizes) image_crop_2d = np.reshape(image_crop, [1, IMAGE_SIZE]) enhanced_2d = sess.run(enhanced, feed_dict={x_: image_crop_2d}) enhanced_image = np.reshape(enhanced_2d, [IMAGE_HEIGHT, IMAGE_WIDTH, 3]) misc.imsave(filename, enhanced_image) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([ input_path, output_path ])
def detect(): input_path = generate_random_filename(upload_directory, "jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) try: top_k = request.form.getlist('top_k')[0] except: top_k = 5 else: url = request.json["url"] download(url, input_path) try: top_k = request.json["top_k"] except: top_k = 5 results = [] img = tfms(Image.open(input_path)).unsqueeze(0) model.eval() with torch.no_grad(): outputs = model(img) for idx in torch.topk(outputs, k=int(top_k)).indices.squeeze(0).tolist(): prob = torch.softmax(outputs, dim=1)[0, idx].item() labels = [x.strip() for x in labels_map[idx].split(',')] results.append({ 'label': labels[0], 'labels': labels, 'score': '{p:.2f}%'.format(p=prob * 100) }) return json.dumps(results), 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path])
def process_image(): input_path = generate_random_filename(upload_directory,"jpeg") output_path = os.path.join(results_img_directory, os.path.basename(input_path)) try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) try: render_factor = request.form.getlist('render_factor')[0] except: render_factor = 30 else: url = request.json["url"] download(url, input_path) try: render_factor = request.json["render_factor"] except: render_factor = 30 result = None try: result = image_colorizer.get_transformed_image(input_path, render_factor=render_factor, post_process=True, watermarked=True) except: convertToJPG(input_path) result = image_colorizer.get_transformed_image(input_path, render_factor=render_factor, post_process=True, watermarked=True) finally: if result is not None: result.save(output_path, quality=95) result.close() callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: pass clean_all([ input_path, output_path ])
def rotate(): input_path = generate_random_filename(upload_directory,"jpg") output_path = generate_random_filename(upload_directory,"jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) cropping = request.form.getlist('cropping')[0] angle = int(request.form.getlist('angle')[0]) else: url = request.json["url"] download(url, input_path) angle = int(request.json["angle"]) cropping = request.json["cropping"] cropping = cropping.lower() in ['true', '1', 't', 'y', 'yes'] convertToJPG(input_path) if cropping: img = Image.open(input_path) img = img.rotate(angle) img.save(output_path) else: M = imageio.imread(input_path) img = rotate_image(M, angle) imageio.imwrite(output_path, img) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([ input_path, output_path ])
def detect(): try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) model = request.form.getlist('model')[0] else: url = request.json["url"] download(url, input_path) image = cv2.imread(input_path) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray_thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1] gray_blur = cv2.medianBlur(gray, 3) filename_thresh = filename + "_tresh.png" filename_blur = filename + "_blur.png" cv2.imwrite(filename_thresh, gray_thresh) cv2.imwrite(filename_blur, gray_blur) results.append({ "type": "default", "text": pytesseract.image_to_string(Image.open(filename_thresh)) }) results.append({ "type": "denoising", "text": pytesseract.image_to_string(Image.open(filename_blur)) }) return json.dumps(results), 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, filename_thresh, filename_blur])
def detect(): input_path = generate_random_filename(upload_directory,"jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) try: nb_colors = int(request.form.getlist('nb_colors')[0]) except: nb_colors = 5 else: url = request.json["url"] download(url, input_path) nb_colors = int(request.json["nb_colors"]) results = [] colors = colorgram.extract(input_path, nb_colors) for color in colors: results.append({ 'R': color.rgb.r, 'G': color.rgb.g, 'B': color.rgb.b, 'H': color.hsl.h, 'S': color.hsl.s, 'L': color.hsl.l, 'HEX': '#%02x%02x%02x' % (color.rgb.r, color.rgb.g, color.rgb.b) }) return json.dumps(results), 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([ input_path ])
def process(): input_path = generate_random_filename(upload_directory, "jpg") output_path = generate_random_filename(upload_directory, "jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) else: url = request.json["url"] download(url, input_path) sigma = 50 results = [] image = face_recognition.load_image_file(input_path) locations = face_recognition.face_locations(image) image = io.imread(input_path) for location in locations: startY = location[0] endY = location[2] startX = location[1] endX = location[3] image = blur(image, startX, endX, startY, endY, sigma=sigma) io.imsave(output_path, image) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])
def process(): input_path = generate_random_filename(upload_directory, "mp3") folder_random = str(uuid4()) output_path = '/src/output/' + folder_random create_directory(output_path) zip_output_path = generate_random_filename(upload_directory, "zip") try: url = request.json["url"] #2stems or 4stems or 5stems nb_stems = request.json["nb_stems"] download(url, input_path) separator = separators[int(nb_stems)] waveform, rate = load_audio(input_path) result = separator.separate(waveform) zip = ZipFile(zip_output_path + '.zip', 'w') for instrument, data in result.items(): save_audio(output_path, instrument, data, rate) for (root, dirs, files) in os.walk(output_path): with ZipFile(zip_output_path, 'w') as zip: for file in files: print(file) zip.write(output_path + '/' + file, basename(file)) callback = send_file(zip_output_path, mimetype='application/zip') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path, zip_output_path])
def detect(): input_path = generate_random_filename(upload_directory,"jpg") output_path = generate_random_filename(upload_directory, "jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) else: url = request.json["url"] download(url, input_path) results = [] bgr_img = cv.imread(input_path) bgr_img = cv.resize(bgr_img, (img_width, img_height), cv.INTER_CUBIC) rgb_img = cv.cvtColor(bgr_img, cv.COLOR_BGR2RGB) rgb_img = np.expand_dims(rgb_img, 0) with graph.as_default(): preds = model.predict(rgb_img) prob = np.max(preds) class_id = np.argmax(preds) results.append({'label': class_names[class_id][0][0], 'score': '{:.4}'.format(prob)}) callback = json.dumps(results) return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([ input_path ])
def flip(): input_path = generate_random_filename(upload_directory,"jpg") output_path = generate_random_filename(upload_directory,"jpg") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) mode = request.form.getlist('mode')[0] else: url = request.json["url"] download(url, input_path) mode = request.json["mode"] convertToJPG(input_path) img = Image.open(input_path) if mode == 'horizontal': img = img.transpose(Image.FLIP_LEFT_RIGHT) else: img = img.transpose(Image.FLIP_TOP_BOTTOM) img.save(output_path) callback = send_file(output_path, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([ input_path, output_path ])
def process_image(): input_path = generate_random_filename(upload_directory, "jpeg") output_path = os.path.join(results_img_directory, os.path.basename(input_path)) try: url = request.json["source_url"] render_factor = int(request.json["render_factor"]) download(url, input_path) try: image_colorizer.plot_transformed_image(path=input_path, figsize=(20, 20), render_factor=render_factor, watermarked=False) except: convertToJPG(input_path) image_colorizer.plot_transformed_image(path=input_path, figsize=(20, 20), render_factor=render_factor, watermarked=False) return_data = io.BytesIO() with open(output_path, 'rb') as fo: return_data.write(fo.read()) return_data.seek(0) callback = send_file(return_data, mimetype='image/jpeg') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: pass clean_all([input_path, output_path])
def process(): input_path = generate_random_filename(upload_directory, "jpg") try: url = request.json["url"] download(url, input_path) image = resize_img(input_path) image = Variable(torch.FloatTensor([image])) predicted = '<START> ' for di in range(9999): sequence = id_for_word(star_text) decoder_input = Variable(torch.LongTensor([sequence])).view(1, -1) features = encoder(image) outputs, hidden = decoder(features, decoder_input, hidden) topv, topi = outputs.data.topk(1) ni = topi[0][0][0] word = word_for_id(ni) if word is None: continue predicted += word + ' ' star_text = word print(predicted) if word == '<END>': break compiler = Compiler('default') compiled_website = compiler.compile(predicted.split()) return json.dumps(compiled_website), 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path])
def process_video(): input_path = generate_random_filename(upload_directory, "mp4") output_path = os.path.join(results_video_directory, os.path.basename(input_path)) try: url = request.json["source_url"] render_factor = int(request.json["render_factor"]) video_path = video_colorizer.colorize_from_url( source_url=url, file_name=input_path, render_factor=render_factor) callback = send_file(output_path, mimetype='application/octet-stream') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])
def process_video(): input_path = generate_random_filename(upload_directory, "mp4") output_path = os.path.join(results_video_directory, os.path.basename(input_path)) try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) try: render_factor = request.form.getlist('render_factor')[0] except: render_factor = 30 else: url = request.json["url"] download(url, input_path) try: render_factor = request.json["render_factor"] except: render_factor = 30 video_path = video_colorizer.colorize_from_url( source_url=url, file_name=input_path, render_factor=render_factor) callback = send_file(output_path, mimetype="application/octet-stream") return callback, 200 except: traceback.print_exc() return {"message": "input error"}, 400 finally: clean_all([input_path, output_path])
def detect(): input_path = generate_random_filename(upload_directory, "jpg") try: url = request.json["url"] download(url, input_path) results = [] x = np.array( data_helper.turn_file_to_vectors( input_path, file_vector_size=defs.file_characters_truncation_limit, breakup=False)) with graph.as_default(): y = model.predict(x) result = model.predict_proba(x) for i in range(0, len(defs.langs)): if (y[0][i] > 0.5): results.append({ "language": defs.langs[i], "score": round(100 * y[0][i]) }) return json.dumps(results), 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path])
def process(): input_path = generate_random_filename(upload_directory, "jpg") output_path = generate_random_filename(result_directory, "png") try: if 'file' in request.files: file = request.files['file'] if allowed_file(file.filename): file.save(input_path) model = request.form.getlist('model')[0] else: url = request.json["url"] download(url, input_path) model = request.json["model"] if prewarm: segmentation(model, input_path, output_path) else: p = Process(target=segmentation, args=(model, input_path, output_path)) p.start() p.join() # this blocks until the process terminates callback = send_file(output_path, mimetype='image/png') return callback, 200 except: traceback.print_exc() return {'message': 'input error'}, 400 finally: clean_all([input_path, output_path])