Spaces:
Running
Running
Automatización de renovaciones de tiempos y modelos en todos los servers
Browse files- app.py +2 -28
- autenticacion.py +15 -13
- funciones.py +3 -9
- globales.py +2 -17
- herramientas.py +49 -61
app.py
CHANGED
@@ -32,8 +32,7 @@ async def echo_image(image: UploadFile = File(...)):
|
|
32 |
@app.post("/genera-imagen/")
|
33 |
async def genera_imagen(platillo: str = Form(...)):
|
34 |
|
35 |
-
seconds_available = herramientas.obtenSegundosDisponibles()
|
36 |
-
|
37 |
print(herramientas.imprimeTimeNow())
|
38 |
|
39 |
if seconds_available > globales.work_cost:
|
@@ -51,29 +50,4 @@ async def genera_imagen(platillo: str = Form(...)):
|
|
51 |
if type(resultado) is str:
|
52 |
return resultado
|
53 |
else:
|
54 |
-
return StreamingResponse(content=resultado, media_type="image/png")
|
55 |
-
|
56 |
-
# @app.post("/procesador-lotes/")
|
57 |
-
# async def procesa_lote(platillo: str = Form(...)):
|
58 |
-
|
59 |
-
# print("Servicio Secundario de Procesamiento de Lotes")
|
60 |
-
# seconds_available = herramientas.obtenSegundosDisponibles()
|
61 |
-
# #seconds_available = 0
|
62 |
-
# print(herramientas.imprimeTimeNow())
|
63 |
-
|
64 |
-
# if seconds_available > globales.work_cost:
|
65 |
-
# print("Usando GPU (capa gratuita)...")
|
66 |
-
# resultado = funciones.genera_platillo_gpu(platillo)
|
67 |
-
# if "Error" in resultado:
|
68 |
-
# return resultado
|
69 |
-
# else:
|
70 |
-
# return FileResponse(resultado, media_type="image/png", filename="imagen.png")
|
71 |
-
# else:
|
72 |
-
|
73 |
-
# print("Usando Inference...")
|
74 |
-
# resultado = funciones.genera_platillo_inference(platillo)
|
75 |
-
# print("El resultado de inference es: ", resultado)
|
76 |
-
# if type(resultado) is str:
|
77 |
-
# return resultado
|
78 |
-
# else:
|
79 |
-
# return StreamingResponse(content=resultado, media_type="image/png")
|
|
|
32 |
@app.post("/genera-imagen/")
|
33 |
async def genera_imagen(platillo: str = Form(...)):
|
34 |
|
35 |
+
seconds_available = herramientas.obtenSegundosDisponibles()
|
|
|
36 |
print(herramientas.imprimeTimeNow())
|
37 |
|
38 |
if seconds_available > globales.work_cost:
|
|
|
50 |
if type(resultado) is str:
|
51 |
return resultado
|
52 |
else:
|
53 |
+
return StreamingResponse(content=resultado, media_type="image/png")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
autenticacion.py
CHANGED
@@ -1,27 +1,29 @@
|
|
1 |
import os
|
2 |
import socket
|
3 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
def defineAmbiente():
|
5 |
if local_check():
|
6 |
print("Entorno Local...")
|
7 |
import bridges
|
8 |
llave = bridges.llave #Acceso a HF
|
9 |
servidor = "moibe" #o Sosa Jhons, depende de donde deduciras el tiempo de gpu cuando pruebas en local.
|
|
|
10 |
else:
|
11 |
print("Entorno remoto listo...")
|
12 |
llave = os.getenv("llave") #Acceso a HF
|
13 |
servidor = os.getenv("servidor")
|
14 |
print("El servidor remoto es: ", servidor)
|
15 |
-
|
16 |
-
|
17 |
-
def local_check():
|
18 |
-
hostname = socket.gethostname()
|
19 |
-
#r-moibe-nowme
|
20 |
-
print("Hostname: ", hostname)
|
21 |
-
#Estoy usando el nombre de la app para identificar que estoy corriendola en HF. #Ésto independiente al servidor en uso.
|
22 |
-
if "-nowme" in hostname:
|
23 |
-
print("Ejecutando api en el servidor.")
|
24 |
-
return False
|
25 |
-
else:
|
26 |
-
print("Ejecutando api en local.")
|
27 |
-
return True
|
|
|
1 |
import os
|
2 |
import socket
|
3 |
|
4 |
+
def local_check():
|
5 |
+
hostname = socket.gethostname()
|
6 |
+
#r-moibe-nowme
|
7 |
+
print("Hostname: ", hostname)
|
8 |
+
#Estoy usando el nombre de la app para identificar que estoy corriendola en HF. #Ésto independiente al servidor en uso.
|
9 |
+
if "-nowme" in hostname:
|
10 |
+
print("Ejecutando api en el servidor.")
|
11 |
+
return False
|
12 |
+
else:
|
13 |
+
print("Ejecutando api en local.")
|
14 |
+
return True
|
15 |
+
|
16 |
def defineAmbiente():
|
17 |
if local_check():
|
18 |
print("Entorno Local...")
|
19 |
import bridges
|
20 |
llave = bridges.llave #Acceso a HF
|
21 |
servidor = "moibe" #o Sosa Jhons, depende de donde deduciras el tiempo de gpu cuando pruebas en local.
|
22 |
+
hora_renovacion = 17
|
23 |
else:
|
24 |
print("Entorno remoto listo...")
|
25 |
llave = os.getenv("llave") #Acceso a HF
|
26 |
servidor = os.getenv("servidor")
|
27 |
print("El servidor remoto es: ", servidor)
|
28 |
+
hora_renovacion = os.getenv("hora_renovacion")
|
29 |
+
return llave, servidor, hora_renovacion
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
funciones.py
CHANGED
@@ -32,8 +32,7 @@ def genera_platillo_gpu(platillo):
|
|
32 |
print(f"La configuración completa para '{espacio_aleatorio_elegido}' es: {configuracion_espacio}")
|
33 |
|
34 |
client = gradio_client.Client(configuracion_espacio['ruta'], hf_token=globales.llave)
|
35 |
-
|
36 |
-
|
37 |
result = client.predict(
|
38 |
#**kwargs,
|
39 |
prompt=prompt,
|
@@ -93,10 +92,7 @@ def genera_platillo_inference(platillo):
|
|
93 |
provider= provedor_seleccionado,
|
94 |
model=configuracion_modelo['ruta'],
|
95 |
api_key=globales.llave
|
96 |
-
)
|
97 |
-
|
98 |
-
print("Cree cliente: ", client)
|
99 |
-
time.sleep(0)
|
100 |
|
101 |
try:
|
102 |
image = client.text_to_image(
|
@@ -114,9 +110,7 @@ def genera_platillo_inference(platillo):
|
|
114 |
print("Excepción: ", e)
|
115 |
if "Gateway Time-out" in str(e):
|
116 |
print("GATEWAY TIME-OUT 💀")
|
117 |
-
|
118 |
-
#Escribe en txt el nuevo modelo.
|
119 |
-
#herramientas.modificaModeloActual(modelo)
|
120 |
error_impreso = f"Error: {e}"
|
121 |
print(error_impreso)
|
122 |
raise HTTPException(
|
|
|
32 |
print(f"La configuración completa para '{espacio_aleatorio_elegido}' es: {configuracion_espacio}")
|
33 |
|
34 |
client = gradio_client.Client(configuracion_espacio['ruta'], hf_token=globales.llave)
|
35 |
+
|
|
|
36 |
result = client.predict(
|
37 |
#**kwargs,
|
38 |
prompt=prompt,
|
|
|
92 |
provider= provedor_seleccionado,
|
93 |
model=configuracion_modelo['ruta'],
|
94 |
api_key=globales.llave
|
95 |
+
)
|
|
|
|
|
|
|
96 |
|
97 |
try:
|
98 |
image = client.text_to_image(
|
|
|
110 |
print("Excepción: ", e)
|
111 |
if "Gateway Time-out" in str(e):
|
112 |
print("GATEWAY TIME-OUT 💀")
|
113 |
+
|
|
|
|
|
114 |
error_impreso = f"Error: {e}"
|
115 |
print(error_impreso)
|
116 |
raise HTTPException(
|
globales.py
CHANGED
@@ -1,9 +1,8 @@
|
|
1 |
import autenticacion
|
2 |
-
version = "1.1.1" #Medición de segundos de procesamiento para cada servidor.
|
3 |
|
4 |
#previo = "Una fotografía de un plato blanco con "
|
5 |
-
previo = "A
|
6 |
-
llave, servidor = autenticacion.defineAmbiente()
|
7 |
|
8 |
|
9 |
# espacio = [
|
@@ -24,17 +23,3 @@ proveedor_back = "fal-ai"
|
|
24 |
work_cost = 1 #Los segundos que cuesta la generación de una imagen, para control de la capa gratuita.
|
25 |
inference_cost = 1
|
26 |
quota = 1500
|
27 |
-
|
28 |
-
|
29 |
-
SERVER_NAMES = {
|
30 |
-
"google_us": "Google US Server",
|
31 |
-
#"azure_lite": "Azure Lite Supercomputer Server",
|
32 |
-
#"artemis" : "Artemis GPU Super cluster",
|
33 |
-
#"nb_dr" : "NebulaDrive Tensor Server",
|
34 |
-
#"pixelnet" : "PixelNet NPU Server",
|
35 |
-
#"nsfw_core" : "NSFW-Core: Uncensored Server",
|
36 |
-
|
37 |
-
#"nsfw_core_2" : "NSFW-Core: Uncensored Server 2",
|
38 |
-
#"nsfw_core_3" : "NSFW-Core: Uncensored Server 3",
|
39 |
-
#"nsfw_core_4" : "NSFW-Core: Uncensored Server 4",
|
40 |
-
}
|
|
|
1 |
import autenticacion
|
|
|
2 |
|
3 |
#previo = "Una fotografía de un plato blanco con "
|
4 |
+
previo = "A pic of a white plate with a visually appealing culinary dish of "
|
5 |
+
llave, servidor, hora_renovacion = autenticacion.defineAmbiente()
|
6 |
|
7 |
|
8 |
# espacio = [
|
|
|
23 |
work_cost = 1 #Los segundos que cuesta la generación de una imagen, para control de la capa gratuita.
|
24 |
inference_cost = 1
|
25 |
quota = 1500
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
herramientas.py
CHANGED
@@ -1,37 +1,31 @@
|
|
1 |
-
import
|
2 |
-
import globales
|
3 |
import pytz
|
4 |
import random
|
5 |
-
|
|
|
|
|
|
|
6 |
|
7 |
-
servidor = globales.servidor
|
8 |
|
9 |
-
|
10 |
|
11 |
def obtenUltimoTimestamp():
|
12 |
"""
|
13 |
Obtiene el último timestamp de renovación guardado.
|
14 |
"""
|
15 |
resultado = conexion_firebase.obtenDato('nowme', servidor, 'timestamp')
|
16 |
-
print("Obten último timestamp obtenido: ", resultado)
|
17 |
|
18 |
return resultado
|
19 |
|
20 |
def obtenSegundosDisponibles():
|
21 |
|
22 |
-
|
23 |
-
renuevaSegundosDisponibles()
|
24 |
-
#renuevaModeloPrincipal() El modelo principal ya se renueva directo en base.
|
25 |
|
26 |
#Finalmente obten los segundos disponibles después de las operaciones.
|
27 |
return conexion_firebase.obtenDato('nowme', servidor, 'segundos')
|
28 |
|
29 |
def obtenSegundosDisponiblesInference():
|
30 |
|
31 |
-
# if esDiaSiguiente() == True:
|
32 |
-
# renuevaSegundosDisponibles()
|
33 |
-
# renuevaModeloPrincipal()
|
34 |
-
|
35 |
#Finalmente obten los segundos disponibles después de las operaciones.
|
36 |
return conexion_firebase.obtenDato('nowme', servidor, 'inferencias')
|
37 |
|
@@ -45,7 +39,6 @@ def renuevaSegundosDisponibles():
|
|
45 |
def renuevaTimestampActual():
|
46 |
|
47 |
timestamp_actual = imprimeTimeNowFixed16h()
|
48 |
-
print("Ésto es el timestamp now de la renovación...: ", timestamp_actual)
|
49 |
conexion_firebase.editaDato('nowme', servidor, 'timestamp', timestamp_actual)
|
50 |
|
51 |
def restaSegundosGPU(cuantos_segundos):
|
@@ -55,8 +48,7 @@ def restaSegundosGPU(cuantos_segundos):
|
|
55 |
"""
|
56 |
|
57 |
segundos_disponibles = obtenSegundosDisponibles()
|
58 |
-
|
59 |
-
|
60 |
# Restar los segundos
|
61 |
nuevos_segundos_disponibles = segundos_disponibles - cuantos_segundos
|
62 |
print("Segundos disponibles ahora: ", nuevos_segundos_disponibles)
|
@@ -69,8 +61,7 @@ def restaSegundosInference(cuantos_segundos):
|
|
69 |
"""
|
70 |
|
71 |
segundos_disponibles = obtenSegundosDisponiblesInference()
|
72 |
-
|
73 |
-
|
74 |
# Restar los segundos
|
75 |
nuevos_segundos_disponibles = segundos_disponibles - cuantos_segundos
|
76 |
print("Segundos disponibles ahora en restaSegundosInference: ", nuevos_segundos_disponibles)
|
@@ -84,13 +75,7 @@ def modificaModeloActual(nuevo_modelo):
|
|
84 |
|
85 |
modelo_actual = conexion_firebase.obtenDato('nowme', servidor, 'modelo_actual')
|
86 |
conexion_firebase.editaDato('nowme', servidor, 'modelo_actual', nuevo_modelo)
|
87 |
-
print(f"Se actualizó el modelo actual: {modelo_actual} por {nuevo_modelo}.")
|
88 |
|
89 |
-
# def renuevaModeloPrincipal():
|
90 |
-
# #Obten el modelo principal (default).
|
91 |
-
# modelo_principal = conexion_firebase.obtenDato('nowme', servidor, 'modelo_principal')
|
92 |
-
# #Asignalo como modelo actual.
|
93 |
-
# conexion_firebase.editaDato('nowme', servidor, 'modelo_actual', modelo_principal)
|
94 |
|
95 |
def imprimeTimeNow():
|
96 |
"""
|
@@ -145,53 +130,56 @@ def imprimeTimeNowFixed16h():
|
|
145 |
|
146 |
return formatted_time
|
147 |
|
148 |
-
def
|
149 |
-
"""
|
150 |
-
Compara dos timestamps Unix y devuelve True si el día de timestamp_actual
|
151 |
-
es diferente al día de timestamp_registro.
|
152 |
-
|
153 |
-
Args:
|
154 |
-
timestamp_registro (int): Timestamp Unix del registro original (en segundos).
|
155 |
-
timestamp_actual (int): Timestamp Unix actual (en segundos).
|
156 |
-
|
157 |
-
Returns:
|
158 |
-
bool: True si el día de timestamp_actual es diferente al día de
|
159 |
-
timestamp_registro, False si es el mismo día.
|
160 |
-
"""
|
161 |
|
162 |
#Obtiene el último registro de fecha de la base de firestore.
|
163 |
-
fecha_registro_dt = obtenUltimoTimestamp()
|
164 |
-
|
165 |
-
print("Primero, el último timestamp obtenido de base es: ", fecha_registro_dt)
|
166 |
-
print("Y su tipo es: ", type(fecha_registro_dt))
|
167 |
|
168 |
#Timestamp actual
|
169 |
-
fecha_actual_dt = imprimeTimeNow()
|
170 |
-
print("Segundo, la fecha_actual_dt quedó como: ", fecha_actual_dt)
|
171 |
-
print("Y su tipo es: ", type(fecha_actual_dt))
|
172 |
|
173 |
-
|
174 |
formato = "%Y-%m-%d %H:%M:%S"
|
175 |
-
datetime_obj_1 = datetime.strptime(fecha_registro_dt, formato)
|
176 |
-
datetime_obj_2 = datetime.strptime(fecha_actual_dt, formato)
|
177 |
-
|
178 |
# Extraer solo la fecha de los objetos datetime
|
179 |
fecha_registro = datetime_obj_1.date()
|
180 |
-
|
181 |
fecha_actual = datetime_obj_2.date()
|
182 |
-
|
183 |
-
|
|
|
|
|
|
|
184 |
|
185 |
# Verificar si las fechas son diferentes
|
186 |
resultado = fecha_actual > fecha_registro
|
187 |
-
print("Resultado de resta de fechas: ", resultado)
|
188 |
-
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
196 |
|
197 |
-
return
|
|
|
1 |
+
import time
|
|
|
2 |
import pytz
|
3 |
import random
|
4 |
+
import globales
|
5 |
+
import conexion_firebase
|
6 |
+
from datetime import datetime
|
7 |
+
import time
|
8 |
|
|
|
9 |
|
10 |
+
servidor = globales.servidor
|
11 |
|
12 |
def obtenUltimoTimestamp():
|
13 |
"""
|
14 |
Obtiene el último timestamp de renovación guardado.
|
15 |
"""
|
16 |
resultado = conexion_firebase.obtenDato('nowme', servidor, 'timestamp')
|
|
|
17 |
|
18 |
return resultado
|
19 |
|
20 |
def obtenSegundosDisponibles():
|
21 |
|
22 |
+
siEsDiaSiguienteRenueva()
|
|
|
|
|
23 |
|
24 |
#Finalmente obten los segundos disponibles después de las operaciones.
|
25 |
return conexion_firebase.obtenDato('nowme', servidor, 'segundos')
|
26 |
|
27 |
def obtenSegundosDisponiblesInference():
|
28 |
|
|
|
|
|
|
|
|
|
29 |
#Finalmente obten los segundos disponibles después de las operaciones.
|
30 |
return conexion_firebase.obtenDato('nowme', servidor, 'inferencias')
|
31 |
|
|
|
39 |
def renuevaTimestampActual():
|
40 |
|
41 |
timestamp_actual = imprimeTimeNowFixed16h()
|
|
|
42 |
conexion_firebase.editaDato('nowme', servidor, 'timestamp', timestamp_actual)
|
43 |
|
44 |
def restaSegundosGPU(cuantos_segundos):
|
|
|
48 |
"""
|
49 |
|
50 |
segundos_disponibles = obtenSegundosDisponibles()
|
51 |
+
|
|
|
52 |
# Restar los segundos
|
53 |
nuevos_segundos_disponibles = segundos_disponibles - cuantos_segundos
|
54 |
print("Segundos disponibles ahora: ", nuevos_segundos_disponibles)
|
|
|
61 |
"""
|
62 |
|
63 |
segundos_disponibles = obtenSegundosDisponiblesInference()
|
64 |
+
|
|
|
65 |
# Restar los segundos
|
66 |
nuevos_segundos_disponibles = segundos_disponibles - cuantos_segundos
|
67 |
print("Segundos disponibles ahora en restaSegundosInference: ", nuevos_segundos_disponibles)
|
|
|
75 |
|
76 |
modelo_actual = conexion_firebase.obtenDato('nowme', servidor, 'modelo_actual')
|
77 |
conexion_firebase.editaDato('nowme', servidor, 'modelo_actual', nuevo_modelo)
|
|
|
78 |
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
def imprimeTimeNow():
|
81 |
"""
|
|
|
130 |
|
131 |
return formatted_time
|
132 |
|
133 |
+
def siEsDiaSiguienteRenueva():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
#Obtiene el último registro de fecha de la base de firestore.
|
136 |
+
fecha_registro_dt = obtenUltimoTimestamp()
|
137 |
+
print("Obtuve el último timestamp: ", fecha_registro_dt)
|
|
|
|
|
138 |
|
139 |
#Timestamp actual
|
140 |
+
fecha_actual_dt = imprimeTimeNow()
|
|
|
|
|
141 |
|
|
|
142 |
formato = "%Y-%m-%d %H:%M:%S"
|
143 |
+
datetime_obj_1 = datetime.strptime(fecha_registro_dt, formato)
|
144 |
+
datetime_obj_2 = datetime.strptime(fecha_actual_dt, formato)
|
145 |
+
|
146 |
# Extraer solo la fecha de los objetos datetime
|
147 |
fecha_registro = datetime_obj_1.date()
|
148 |
+
print("Primera extracción: ", fecha_registro)
|
149 |
fecha_actual = datetime_obj_2.date()
|
150 |
+
print("Segunda extracción: ", fecha_actual)
|
151 |
+
|
152 |
+
# Experimento de extracción de horas:
|
153 |
+
hora_registro = datetime_obj_1.time()
|
154 |
+
print("Hora Primera extracción: ", hora_registro)
|
155 |
|
156 |
# Verificar si las fechas son diferentes
|
157 |
resultado = fecha_actual > fecha_registro
|
158 |
+
print("Resultado de resta de fechas: ", resultado)
|
159 |
+
|
160 |
+
print("Las fechas son del tipo: ", type(fecha_registro))
|
161 |
+
diferencia = fecha_actual - fecha_registro
|
162 |
+
print("Diferencia.days es: ", diferencia.days)
|
163 |
+
|
164 |
+
if resultado == True:
|
165 |
+
print("El resultado es True, aquí checaríamos la hora.")
|
166 |
+
if diferencia.days > 1:
|
167 |
+
print("Renovación directa por distancia superior a 1 día...")
|
168 |
+
print("Renovando segundos.")
|
169 |
+
renuevaSegundosDisponibles()
|
170 |
+
renuevaTimestampActual()
|
171 |
+
else: #Si la diferencia es de un solo día entonces si debe checar si ya rebaso la hora de renovación del servidor.
|
172 |
+
hora_actual = datetime_obj_2.time()
|
173 |
+
print("Hora Segunda extracción: ", hora_actual)
|
174 |
+
print("La hora exacta es: ", hora_actual.hour)
|
175 |
+
print("La hora renovación es: ", globales.hora_renovacion)
|
176 |
+
if hora_actual.hour > globales.hora_renovacion:
|
177 |
+
print("Renovando segundos.")
|
178 |
+
renuevaSegundosDisponibles()
|
179 |
+
renuevaTimestampActual()
|
180 |
+
else:
|
181 |
+
print("La hora aún no llega al límite, no renovará.")
|
182 |
+
else:
|
183 |
+
print("El resultado es false, no renovará...")
|
184 |
|
185 |
+
return resultado
|