dfernandezl12 commited on
Commit
a0e0645
·
verified ·
1 Parent(s): fa48d0a

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -112
main.py DELETED
@@ -1,112 +0,0 @@
1
- import os
2
- import numpy as np
3
- import tensorflow as tf
4
- from tensorflow.keras import layers, models
5
- from flask import Flask, request, jsonify, render_template
6
- from PIL import Image
7
- import io
8
- from datasets import load_dataset
9
-
10
- # ------------------------------
11
- # Configuración
12
- # ------------------------------
13
- MODEL_PATH = "modelo.keras" # Extensión .keras (Keras 3)
14
- IMG_SIZE = (64, 64)
15
-
16
- def build_model():
17
- model = models.Sequential([
18
- layers.Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3)),
19
- layers.MaxPooling2D((2, 2)),
20
- layers.Conv2D(64, (3, 3), activation='relu'),
21
- layers.Flatten(),
22
- layers.Dense(64, activation='relu'),
23
- layers.Dense(1, activation='sigmoid') # 1 = blanco, 0 = negro
24
- ])
25
- model.compile(optimizer='adam',
26
- loss='binary_crossentropy',
27
- metrics=['accuracy'])
28
- return model
29
-
30
- def train_and_save_model():
31
- print("Cargando dataset FairFace...")
32
- ds = load_dataset("HuggingFaceM4/FairFace", "0.25")
33
-
34
- # Filtrar solo razas "Blanco" (0) y "Negro" (1)
35
- def filter_white_black(example):
36
- return example['race'] in [0, 1]
37
-
38
- ds_filtered = ds['train'].filter(filter_white_black)
39
-
40
- # Preparar imágenes y etiquetas
41
- images = []
42
- labels = []
43
- for item in ds_filtered:
44
- img = item['image'].convert('RGB').resize(IMG_SIZE)
45
- images.append(np.array(img) / 255.0)
46
- labels.append(1.0 if item['race'] == 0 else 0.0)
47
-
48
- X = np.array(images)
49
- y = np.array(labels)
50
-
51
- print(f"Datos cargados: {len(X)} imágenes (blancas: {sum(y)}, negras: {len(y)-sum(y)})")
52
-
53
- # Entrenar modelo
54
- model = build_model()
55
- print("Entrenando clasificador racial...")
56
- model.fit(X, y, epochs=5, batch_size=32, validation_split=0.2, verbose=1)
57
-
58
- # Guardar en formato Keras 3 (.keras)
59
- model.save(MODEL_PATH)
60
- print(f"Modelo guardado como {MODEL_PATH}")
61
- return model
62
-
63
- # Cargar modelo con reintento si falla
64
- def load_or_train_model():
65
- if os.path.exists(MODEL_PATH):
66
- try:
67
- model = tf.keras.models.load_model(MODEL_PATH)
68
- print("Modelo cargado desde disco")
69
- return model
70
- except Exception as e:
71
- print(f"Error al cargar modelo: {e}")
72
- print("Eliminando modelo corrupto y reentrenando...")
73
- os.remove(MODEL_PATH) # borra el archivo corrupto
74
- return train_and_save_model()
75
- else:
76
- return train_and_save_model()
77
-
78
- model = load_or_train_model()
79
-
80
- # ------------------------------
81
- # Aplicación Flask
82
- # ------------------------------
83
- app = Flask(__name__)
84
-
85
- def predecir_raza(imagen_bytes):
86
- img = Image.open(io.BytesIO(imagen_bytes)).convert('RGB')
87
- img = img.resize(IMG_SIZE)
88
- img_array = np.array(img) / 255.0
89
- img_array = np.expand_dims(img_array, axis=0)
90
- prediccion = model.predict(img_array, verbose=0)[0][0]
91
- return "blanca" if prediccion >= 0.5 else "negra"
92
-
93
- @app.route('/')
94
- def index():
95
- return render_template('index.html')
96
-
97
- @app.route('/predict', methods=['POST'])
98
- def predict():
99
- if 'image' not in request.files:
100
- return jsonify({'error': 'No se encontró ninguna imagen'}), 400
101
- file = request.files['image']
102
- if file.filename == '':
103
- return jsonify({'error': 'Nombre de archivo vacío'}), 400
104
- try:
105
- imagen_bytes = file.read()
106
- raza = predecir_raza(imagen_bytes)
107
- return jsonify({'raza': raza})
108
- except Exception as e:
109
- return jsonify({'error': str(e)}), 500
110
-
111
- if __name__ == '__main__':
112
- app.run(debug=True, host='0.0.0.0', port=5000)