Spaces:
Paused
Paused
File size: 7,460 Bytes
cea6160 1e330bd 67b8057 554a6f2 9abe70d 487c322 cc3c167 5b474cb bcbc057 5b474cb 9abe70d bed9a40 a212e09 bed9a40 554a6f2 cc3c167 bed9a40 ddf8ebd cec32e7 ddf8ebd 9abe70d 98777c8 cc3c167 98777c8 cc3c167 a3d4937 5b474cb 98777c8 cc3c167 a3d4937 9738fed 5b474cb cc3c167 5b474cb 98777c8 cc3c167 98777c8 cc3c167 98777c8 2aba367 9c35c94 2aba367 cec32e7 2aba367 a3d4937 2aba367 ddf8ebd fa42c92 2aba367 ddf8ebd 30eb562 2aba367 ddf8ebd 98777c8 487c322 2aba367 9abe70d 2aba367 9abe70d 98777c8 2aba367 bcbc057 98777c8 33377b9 ddf8ebd 98777c8 33377b9 98777c8 bcbc057 33377b9 98777c8 bcbc057 33377b9 98777c8 bcbc057 33377b9 98777c8 bcbc057 33377b9 98777c8 bcbc057 9abe70d 98777c8 cb14b48 98777c8 e2edca9 764f9ac e2edca9 9abe70d 98777c8 9abe70d cea6160 bed9a40 fa22b90 bed9a40 194aaac |
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 |
from flask import Flask, render_template, send_from_directory, send_file, request, jsonify
from flask_cors import CORS
import subprocess
import os
import io
from model.src.utils.arg_parser import eval_parse_args # Nuovo import corretto
import sys
from PIL import Image
import base64
import traceback
from model.src import eval
app = Flask(__name__)
CORS(app)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/generate-design', methods=['GET','POST'])
def generate_design():
#image_save_dir = "/api/model/assets/data/vitonhd/test/im_sketch"
text_file_path = "/api/model/assets/data/vitonhd/test/test_paired.txt"
try:
print("### Inizio generate_design ###") # Stampa per il debug
# Getting json
json_data_from_req = request.get_json()
if not json_data_from_req:
print("### JSON non ricevuto ###") # Stampa per il debug
return "Invalid or missing JSON data", 400
# Getting Image
if 'image' not in json_data_from_req:
print("### Nessuna immagine ricevuta ###") # Stampa per il debug
return "No image file in request", 400
print(json_data_from_req)
encoded_image = json_data_from_req['image']
try:
image_data = base64.b64decode(encoded_image)
image = Image.open(io.BytesIO(image_data))
print("### Immagine aperta con successo ###") # Stampa per il debug
except Exception as e:
print(f"### Errore nell'apertura dell'immagine: {str(e)} ###") # Stampa per il debug
return f"Failed to open the image: {str(e)}", 400
if 'vitonhd' in json_data_from_req:
dataset_name = 'vitonhd'
image_suffix = '_00.jpeg'
dataset_path = '/api/model/assets/data/vitonhd'
image_save_dir = os.path.join(dataset_path, 'test/im_sketch')
elif 'dresscode' in json_data_from_req:
dataset_name = 'dresscode'
image_suffix = '_1.jpeg'
body_part = json_data_from_req['body_part']
dataset_path = '/api/model/assets/data/dresscode'
sketch_path = f'/api/model/assets/data/dresscode/{body_part}'
image_save_dir = os.path.join(sketch_path, 'im_sketch')
else:
print("### Chiave 'vitonhd' o 'dresscode' non trovata nel JSON ###") # Stampa per il debug
return "Invalid JSON data, expected 'vitonhd' or 'dresscode'", 400
# Saving sketch in filesystem
model_key = list(json_data_from_req[dataset_name].keys())[0] # Es: "03191"
image_filename = f"{model_key}{image_suffix}" # Nome file immagine es: "03191_00.jpg"
print("###################################### NOME SKETCH: ", image_filename)
print("###################################### DIRECTORY DOVE LO SALVO: ", image_save_dir)
image_save_path = os.path.join(image_save_dir, image_filename)
image.save(image_save_path, format='JPEG')
# Elenca tutti i file nella directory
files_in_directory = os.listdir(image_save_dir)
# Stampa i file trovati
for file_name in files_in_directory:
print(file_name)
#with open(text_file_path, "w") as text_file:
# text_file.write(f"{image_filename} {image_filename}\n")
# Argomenti per eval.main
sys.argv = [
'eval.py',
'--dataset_path', dataset_path,
'--batch_size', '1',
'--mixed_precision', 'fp16',
'--num_workers_test', '4',
'--sketch_cond_rate', '0.2',
'--dataset', dataset_name,
'--start_cond_rate', '0.0',
'--test_order', 'paired'
]
print("### Esecuzione eval.main ###") # Stampa per il debug
import traceback
# Esecuzione del modello
try:
final_image = eval.main(json_data_from_req)
print("### eval.main eseguito con successo ###") # Stampa per il debug
except AttributeError as e:
print(f"### AttributeError: {str(e)} ###") # Stampa per il debug
return f"AttributeError: {traceback.format_exc()}", 500
except TypeError as e:
print(f"### TypeError: {str(e)} ###") # Stampa per il debug
return f"TypeError: {traceback.format_exc()}", 500
except ValueError as e:
print(f"### ValueError: {str(e)} ###") # Stampa per il debug
return f"ValueError: {traceback.format_exc()}", 500
except IOError as e:
print(f"### IOError: {str(e)} ###") # Stampa per il debug
return f"IOError: {traceback.format_exc()}", 500
except Exception as e:
print(f"### Unexpected error: {str(e)} ###") # Stampa per il debug
return f"Unexpected error: {traceback.format_exc()}", 500
# Salvataggio immagine e invio come risposta
img_io = io.BytesIO()
final_image.save(img_io, 'JPEG')
img_io.seek(0)
print("### Immagine finale pronta per il download ###") # Stampa per il debug
return send_file(img_io, mimetype='image/jpeg', as_attachment=True, download_name='inmemory_image.jpg')
except Exception as e:
print(f"### Errore globale: {str(e)} ###") # Stampa per il debug
return str(e), 500
@app.route('/test_post', methods=['POST'])
def test_post():
# Verifica se la richiesta è POST
if request.method == 'POST':
# Ottieni i dati dal corpo della richiesta
data = request.get_json()
# Se i dati non sono presenti o il formato non è corretto
if not data:
return jsonify({'message': 'Nessun dato ricevuto o dati non validi'}), 400
# Restituisci una risposta con i dati ricevuti
return jsonify({'message': 'POST funzionante', 'data_received': data}), 200
@app.route('/process-image', methods=['POST'])
def process_image():
try:
# Ottieni il JSON dalla richiesta
json_data = request.get_json()
if not json_data or 'image' not in json_data:
return "Invalid or missing JSON data", 400
# Decodifica l'immagine base64
encoded_image = json_data['image']
try:
image_data = base64.b64decode(encoded_image)
image = Image.open(io.BytesIO(image_data))
print("### Immagine aperta con successo ###") # Stampa per il debug
except Exception as e:
print(f"### Errore nell'apertura dell'immagine: {str(e)} ###") # Stampa per il debug
return f"Failed to open the image: {str(e)}", 400
# Elaborazione dell'immagine con PIL (ad esempio, convertiamo l'immagine in scala di grigi)
processed_image = image.convert("L") # Converti l'immagine in scala di grigi
# Salva l'immagine su un buffer
img_io = io.BytesIO()
processed_image.save(img_io, 'JPEG')
img_io.seek(0)
# Restituisci l'immagine come file scaricabile
return send_file(img_io, mimetype='image/jpeg', as_attachment=True, download_name='processed_image.jpg')
except Exception as e:
print(f"### Errore durante l'elaborazione dell'immagine: {str(e)} ###") # Stampa per il debug
return str(e), 500
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True) |