Spaces:
Running
Running
Boilerplate Any Fastapi @ HF
Browse files- app.py +1 -25
- default.png +0 -0
- funciones.py +4 -72
- globales.py +1 -9
- herramientas.py +1 -96
- requirements.txt +0 -1
app.py
CHANGED
@@ -27,28 +27,4 @@ async def echo_image(image: UploadFile = File(...)):
|
|
27 |
if not image.content_type.startswith("image/"):
|
28 |
return {"error": "El archivo no es una imagen"}
|
29 |
contents = await image.read()
|
30 |
-
return StreamingResponse(BytesIO(contents), media_type=image.content_type)
|
31 |
-
|
32 |
-
@app.post("/genera-imagen/")
|
33 |
-
async def genera_imagen(platillo: str = Form(...)):
|
34 |
-
|
35 |
-
#Obtengo los segundos disponibles de procesamiento para saber si tengo GPU disponible de la capa gratuita o me voy a m茅todo cobrado.
|
36 |
-
seconds_available = herramientas.obtenSegundosDisponibles()
|
37 |
-
print(herramientas.imprimeTimeNow())
|
38 |
-
|
39 |
-
if seconds_available > globales.work_cost:
|
40 |
-
print("Usando GPU (capa gratuita)...")
|
41 |
-
resultado = funciones.genera_platillo_gpu(platillo)
|
42 |
-
if "Error" in resultado:
|
43 |
-
return resultado
|
44 |
-
else:
|
45 |
-
return FileResponse(resultado, media_type="image/png", filename="imagen.png")
|
46 |
-
else:
|
47 |
-
|
48 |
-
print("Usando Inference...")
|
49 |
-
resultado = funciones.genera_platillo_inference(platillo)
|
50 |
-
print("El resultado de inference es: ", resultado)
|
51 |
-
if type(resultado) is str:
|
52 |
-
return resultado
|
53 |
-
else:
|
54 |
-
return StreamingResponse(content=resultado, media_type="image/png")
|
|
|
27 |
if not image.content_type.startswith("image/"):
|
28 |
return {"error": "El archivo no es una imagen"}
|
29 |
contents = await image.read()
|
30 |
+
return StreamingResponse(BytesIO(contents), media_type=image.content_type)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
default.png
DELETED
Binary file (62.5 kB)
|
|
funciones.py
CHANGED
@@ -1,82 +1,14 @@
|
|
1 |
-
import io
|
2 |
import globales
|
3 |
import herramientas
|
4 |
-
import gradio_client
|
5 |
-
from huggingface_hub import InferenceClient
|
6 |
import conexion_firebase
|
7 |
|
8 |
-
def
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
kwargs = {
|
14 |
-
"prompt": prompt,
|
15 |
-
"api_name": "/infer"
|
16 |
-
}
|
17 |
-
|
18 |
-
try:
|
19 |
-
|
20 |
-
client = gradio_client.Client(globales.espacio, hf_token=globales.llave)
|
21 |
-
result = client.predict(**kwargs,
|
22 |
-
# prompt=prompt,
|
23 |
-
# negative_prompt="",
|
24 |
-
# seed=42,
|
25 |
-
# randomize_seed=True,
|
26 |
-
width=786,
|
27 |
-
height=568,
|
28 |
-
# guidance_scale=3.5,
|
29 |
-
# num_inference_steps=28,
|
30 |
-
# api_name="/infer"
|
31 |
-
)
|
32 |
-
|
33 |
-
#Cuando es GPU, debe de restar segundos disponibles de HF
|
34 |
-
herramientas.restaSegundosGPU(globales.work_cost)
|
35 |
-
|
36 |
-
print("Platillo generado:", platillo)
|
37 |
-
return result[0]
|
38 |
|
39 |
except Exception as e:
|
40 |
print("Excepci贸n: ", e)
|
41 |
# Opci贸n para regresar imagen gen茅rica. (ya no porque se env铆a desde backend.)
|
42 |
# return "default.png"
|
43 |
-
return '{"Error 500": e}'
|
44 |
-
|
45 |
-
|
46 |
-
def genera_platillo_inference(platillo):
|
47 |
-
|
48 |
-
print("Proveedor:", globales.proveedor)
|
49 |
-
modelo_actual = conexion_firebase.obtenDato('nowme', 'huggingface', 'modelo_actual')
|
50 |
-
modelo = modelo_actual
|
51 |
-
|
52 |
-
#print("Modelo:", modelo)
|
53 |
-
|
54 |
-
prompt = globales.previo + platillo
|
55 |
-
print("Platillo enviado:", platillo)
|
56 |
-
|
57 |
-
client = InferenceClient(
|
58 |
-
provider= globales.proveedor,
|
59 |
-
api_key=globales.llave
|
60 |
-
)
|
61 |
-
|
62 |
-
try:
|
63 |
-
image = client.text_to_image(
|
64 |
-
prompt,
|
65 |
-
model=modelo
|
66 |
-
)
|
67 |
-
|
68 |
-
except Exception as e:
|
69 |
-
print("Excepci贸n: ", e)
|
70 |
-
if "Gateway Time-out" in str(e):
|
71 |
-
print("GATEWAY TIME-OUT 馃拃")
|
72 |
-
modelo=globales.inferencia_backup
|
73 |
-
#Escribe en txt el nuevo modelo.
|
74 |
-
herramientas.modificaModeloActual(modelo)
|
75 |
-
return f"Error: {e}"
|
76 |
-
|
77 |
-
img_io = io.BytesIO()
|
78 |
-
image.save(img_io, "PNG")
|
79 |
-
img_io.seek(0)
|
80 |
-
print("Platillo generado:", platillo)
|
81 |
-
return img_io
|
82 |
-
|
|
|
|
|
1 |
import globales
|
2 |
import herramientas
|
|
|
|
|
3 |
import conexion_firebase
|
4 |
|
5 |
+
def funcion_generica(platillo):
|
6 |
|
7 |
+
try:
|
8 |
+
return "Hola"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
except Exception as e:
|
11 |
print("Excepci贸n: ", e)
|
12 |
# Opci贸n para regresar imagen gen茅rica. (ya no porque se env铆a desde backend.)
|
13 |
# return "default.png"
|
14 |
+
return '{"Error 500": e}'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
globales.py
CHANGED
@@ -1,13 +1,5 @@
|
|
1 |
import autenticacion
|
2 |
version = "0.0.0"
|
3 |
|
4 |
-
#previo = "Una fotograf铆a de un plato blanco con "
|
5 |
-
previo = "A photograph of a white plate with "
|
6 |
llave, servidor = autenticacion.defineAmbiente()
|
7 |
-
|
8 |
-
#espacio = "black-forest-labs/FLUX.1-dev"
|
9 |
-
#inferencia = "black-forest-labs/FLUX.1-dev"
|
10 |
-
#inferencia_backup = "black-forest-labs/FLUX.1-schnell"
|
11 |
-
proveedor = "hf-inference" #falai
|
12 |
-
work_cost = 6 #Los segundos que cuesta la generaci贸n de una imagen, para control de la capa gratuita.
|
13 |
-
quota = 300
|
|
|
1 |
import autenticacion
|
2 |
version = "0.0.0"
|
3 |
|
|
|
|
|
4 |
llave, servidor = autenticacion.defineAmbiente()
|
5 |
+
|
|
|
|
|
|
|
|
|
|
|
|
herramientas.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
import time
|
2 |
from datetime import datetime
|
3 |
from datetime import datetime
|
4 |
import conexion_firebase
|
@@ -20,56 +19,6 @@ def obtenUltimoTimestamp():
|
|
20 |
|
21 |
return resultado
|
22 |
|
23 |
-
def obtenSegundosDisponibles():
|
24 |
-
|
25 |
-
if esDiaSiguiente() == True:
|
26 |
-
renuevaSegundosDisponibles()
|
27 |
-
renuevaModeloPrincipal()
|
28 |
-
|
29 |
-
#Finalmente obten los segundos disponibles despu茅s de las operaciones.
|
30 |
-
return conexion_firebase.obtenDato('nowme', 'huggingface', segundos)
|
31 |
-
|
32 |
-
def renuevaSegundosDisponibles():
|
33 |
-
|
34 |
-
#Segundos de cuota total gratuita disponibles al momento.
|
35 |
-
quota_total = 300
|
36 |
-
conexion_firebase.editaDato('nowme', 'huggingface', segundos, quota_total)
|
37 |
-
renuevaTimestampActual()
|
38 |
-
|
39 |
-
def renuevaTimestampActual():
|
40 |
-
|
41 |
-
timestamp_actual = imprimeTimeNow()
|
42 |
-
conexion_firebase.editaDato('nowme', 'huggingface', last_timestamp, timestamp_actual)
|
43 |
-
|
44 |
-
def restaSegundosGPU(cuantos_segundos):
|
45 |
-
"""
|
46 |
-
Lee el n煤mero de segundos disponibles desde seconds_available.txt,
|
47 |
-
resta los segundos dados como par谩metro y guarda el nuevo valor en el archivo.
|
48 |
-
"""
|
49 |
-
|
50 |
-
segundos_disponibles = obtenSegundosDisponibles()
|
51 |
-
print("Segundos disponibles: ", segundos_disponibles)
|
52 |
-
|
53 |
-
# Restar los segundos
|
54 |
-
nuevos_segundos_disponibles = segundos_disponibles - cuantos_segundos
|
55 |
-
print("Segundos disponibles ahora: ", nuevos_segundos_disponibles)
|
56 |
-
conexion_firebase.editaDato('nowme', 'huggingface', segundos, nuevos_segundos_disponibles)
|
57 |
-
|
58 |
-
def modificaModeloActual(nuevo_modelo):
|
59 |
-
"""
|
60 |
-
Actualiza el archivo archivos/modelo_actual.txt con el modelo funcional en caso de
|
61 |
-
problemas con el actual.
|
62 |
-
"""
|
63 |
-
|
64 |
-
modelo_actual = conexion_firebase.obtenDato('nowme', 'huggingface', 'modelo_actual')
|
65 |
-
conexion_firebase.editaDato('nowme', 'huggingface', 'modelo_actual', nuevo_modelo)
|
66 |
-
print(f"Se actualiz贸 el modelo actual: {modelo_actual} por {nuevo_modelo}.")
|
67 |
-
|
68 |
-
def renuevaModeloPrincipal():
|
69 |
-
#Obten el modelo principal (default).
|
70 |
-
modelo_principal = conexion_firebase.obtenDato('nowme', 'huggingface', 'modelo_principal')
|
71 |
-
#Asignalo como modelo actual.
|
72 |
-
conexion_firebase.editaDato('nowme', 'huggingface', 'modelo_actual', modelo_principal)
|
73 |
|
74 |
def imprimeTimeNow():
|
75 |
"""
|
@@ -89,48 +38,4 @@ def imprimeTimeNow():
|
|
89 |
# El formato que deseas es "YYYY-MM-DD HH:MM:SS"
|
90 |
formatted_time = mexico_city_now.strftime("%Y-%m-%d %H:%M:%S")
|
91 |
|
92 |
-
return formatted_time
|
93 |
-
|
94 |
-
def esDiaSiguiente():
|
95 |
-
"""
|
96 |
-
Compara dos timestamps Unix y devuelve True si el d铆a de timestamp_actual
|
97 |
-
es diferente al d铆a de timestamp_registro.
|
98 |
-
|
99 |
-
Args:
|
100 |
-
timestamp_registro (int): Timestamp Unix del registro original (en segundos).
|
101 |
-
timestamp_actual (int): Timestamp Unix actual (en segundos).
|
102 |
-
|
103 |
-
Returns:
|
104 |
-
bool: True si el d铆a de timestamp_actual es diferente al d铆a de
|
105 |
-
timestamp_registro, False si es el mismo d铆a.
|
106 |
-
"""
|
107 |
-
|
108 |
-
#Obtiene el 煤ltimo registro de fecha de la base de firestore.
|
109 |
-
fecha_registro_dt = obtenUltimoTimestamp()
|
110 |
-
print("Primero, el 煤ltimo timestamp obtenido de base es: ", fecha_registro_dt)
|
111 |
-
print("Y su tipo es: ", type(fecha_registro_dt))
|
112 |
-
|
113 |
-
#Timestamp actual
|
114 |
-
#fecha_actual_dt = datetime.fromtimestamp(int(time.time()))
|
115 |
-
fecha_actual_dt = imprimeTimeNow()
|
116 |
-
print("Segundo, la fecha_actual_dt qued贸 como: ", fecha_actual_dt)
|
117 |
-
print("Y su tipo es: ", type(fecha_actual_dt))
|
118 |
-
|
119 |
-
|
120 |
-
formato = "%Y-%m-%d %H:%M:%S"
|
121 |
-
datetime_obj_1 = datetime.strptime(fecha_registro_dt, formato)
|
122 |
-
datetime_obj_2 = datetime.strptime(fecha_actual_dt, formato)
|
123 |
-
|
124 |
-
# Extraer solo la fecha de los objetos datetime
|
125 |
-
fecha_registro = datetime_obj_1.date()
|
126 |
-
#print("Primera extracci贸n: ", fecha_registro)
|
127 |
-
fecha_actual = datetime_obj_2.date()
|
128 |
-
#print("Segunda extracci贸n: ", fecha_actual)
|
129 |
-
|
130 |
-
|
131 |
-
# Verificar si las fechas son diferentes
|
132 |
-
resultado = fecha_actual > fecha_registro
|
133 |
-
print("Resultado de resta de fechas: ", resultado)
|
134 |
-
|
135 |
-
|
136 |
-
return resultado
|
|
|
|
|
1 |
from datetime import datetime
|
2 |
from datetime import datetime
|
3 |
import conexion_firebase
|
|
|
19 |
|
20 |
return resultado
|
21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
def imprimeTimeNow():
|
24 |
"""
|
|
|
38 |
# El formato que deseas es "YYYY-MM-DD HH:MM:SS"
|
39 |
formatted_time = mexico_city_now.strftime("%Y-%m-%d %H:%M:%S")
|
40 |
|
41 |
+
return formatted_time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
requirements.txt
CHANGED
@@ -1,6 +1,5 @@
|
|
1 |
fastapi
|
2 |
fastapi[standard]
|
3 |
-
huggingface_hub
|
4 |
gradio_client
|
5 |
Pillow
|
6 |
firebase_admin
|
|
|
1 |
fastapi
|
2 |
fastapi[standard]
|
|
|
3 |
gradio_client
|
4 |
Pillow
|
5 |
firebase_admin
|