Spaces:
Running
Running
Depuración
Browse files- app.py +14 -14
- archivos/last_timestamp.txt +1 -1
- archivos/seconds_available.txt +1 -1
- funciones.py +12 -17
- herramientas.py +12 -10
app.py
CHANGED
|
@@ -1,13 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import FastAPI, Form
|
| 2 |
from fastapi import FastAPI, File, UploadFile
|
| 3 |
from fastapi.responses import StreamingResponse, FileResponse
|
| 4 |
-
from io import BytesIO
|
| 5 |
-
import funciones, globales
|
| 6 |
-
import herramientas
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
-
@app.post("/echo-image/"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
async def echo_image(image: UploadFile = File(...)):
|
| 12 |
if not image.content_type.startswith("image/"):
|
| 13 |
return {"error": "El archivo no es una imagen"}
|
|
@@ -18,26 +22,22 @@ async def echo_image(image: UploadFile = File(...)):
|
|
| 18 |
@app.post("/genera-imagen/")
|
| 19 |
async def genera_imagen(platillo: str = Form(...)):
|
| 20 |
|
| 21 |
-
#Obtengo
|
| 22 |
seconds_available = herramientas.obtenSegundosDisponibles()
|
| 23 |
-
print("Los segundos disponibles
|
| 24 |
-
|
| 25 |
-
|
| 26 |
if seconds_available > globales.work_cost:
|
| 27 |
-
print("GPU...")
|
| 28 |
resultado = funciones.genera_platillo_gpu(platillo)
|
| 29 |
if "Error" in resultado:
|
| 30 |
return resultado
|
| 31 |
else:
|
| 32 |
return FileResponse(resultado, media_type="image/png", filename="imagen.png")
|
| 33 |
else:
|
| 34 |
-
print("Inference...")
|
| 35 |
resultado = funciones.genera_platillo_inference(platillo)
|
| 36 |
print("El resultado de inference es: ", resultado)
|
| 37 |
-
print("Y su type es: ", type(resultado))
|
| 38 |
if type(resultado) is str:
|
| 39 |
return '{"Error":"500"}'
|
| 40 |
else:
|
| 41 |
-
return StreamingResponse(content=resultado, media_type="image/png")
|
| 42 |
-
|
| 43 |
-
|
|
|
|
| 1 |
+
import herramientas
|
| 2 |
+
from io import BytesIO
|
| 3 |
+
import funciones, globales
|
| 4 |
from fastapi import FastAPI, Form
|
| 5 |
from fastapi import FastAPI, File, UploadFile
|
| 6 |
from fastapi.responses import StreamingResponse, FileResponse
|
|
|
|
|
|
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
| 10 |
+
@app.post("/echo-image/",
|
| 11 |
+
tags=["Test"],
|
| 12 |
+
description="Descripción",
|
| 13 |
+
summary="Summary"
|
| 14 |
+
)
|
| 15 |
async def echo_image(image: UploadFile = File(...)):
|
| 16 |
if not image.content_type.startswith("image/"):
|
| 17 |
return {"error": "El archivo no es una imagen"}
|
|
|
|
| 22 |
@app.post("/genera-imagen/")
|
| 23 |
async def genera_imagen(platillo: str = Form(...)):
|
| 24 |
|
| 25 |
+
#Obtengo los segundos disponibles de procesamiento para saber si tengo GPU disponible de la capa gratuita o me voy a método cobrado.
|
| 26 |
seconds_available = herramientas.obtenSegundosDisponibles()
|
| 27 |
+
print("Los segundos de procesamiento disponibles el día de hoy son: ", seconds_available)
|
| 28 |
+
|
|
|
|
| 29 |
if seconds_available > globales.work_cost:
|
| 30 |
+
print("Usando GPU (capa gratuita)...")
|
| 31 |
resultado = funciones.genera_platillo_gpu(platillo)
|
| 32 |
if "Error" in resultado:
|
| 33 |
return resultado
|
| 34 |
else:
|
| 35 |
return FileResponse(resultado, media_type="image/png", filename="imagen.png")
|
| 36 |
else:
|
| 37 |
+
print("Usando Inference...")
|
| 38 |
resultado = funciones.genera_platillo_inference(platillo)
|
| 39 |
print("El resultado de inference es: ", resultado)
|
|
|
|
| 40 |
if type(resultado) is str:
|
| 41 |
return '{"Error":"500"}'
|
| 42 |
else:
|
| 43 |
+
return StreamingResponse(content=resultado, media_type="image/png")
|
|
|
|
|
|
archivos/last_timestamp.txt
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
1745452456
|
archivos/seconds_available.txt
CHANGED
|
@@ -1 +1 @@
|
|
| 1 |
-
|
|
|
|
| 1 |
+
288
|
funciones.py
CHANGED
|
@@ -1,13 +1,12 @@
|
|
| 1 |
-
from huggingface_hub import InferenceClient
|
| 2 |
-
import gradio_client
|
| 3 |
import io
|
| 4 |
import globales
|
| 5 |
import herramientas
|
|
|
|
|
|
|
| 6 |
|
| 7 |
def genera_platillo_gpu(platillo):
|
| 8 |
|
| 9 |
prompt = globales.previo + platillo
|
| 10 |
-
|
| 11 |
print("Platillo generado:", platillo)
|
| 12 |
|
| 13 |
kwargs = {
|
|
@@ -19,7 +18,7 @@ def genera_platillo_gpu(platillo):
|
|
| 19 |
|
| 20 |
client = gradio_client.Client(globales.espacio, hf_token=globales.llave)
|
| 21 |
result = client.predict(**kwargs
|
| 22 |
-
|
| 23 |
# negative_prompt="",
|
| 24 |
# seed=42,
|
| 25 |
# randomize_seed=True,
|
|
@@ -33,27 +32,25 @@ def genera_platillo_gpu(platillo):
|
|
| 33 |
#Cuando es GPU, debe de restar segundos disponibles de HF
|
| 34 |
herramientas.restaSegundosGPU(globales.work_cost)
|
| 35 |
|
| 36 |
-
print("Resultado regresado en result[0] es: ", result[0])
|
| 37 |
-
|
| 38 |
return result[0]
|
| 39 |
|
| 40 |
except Exception as e:
|
| 41 |
print("Excepción es: ", e)
|
|
|
|
| 42 |
# return "default.png"
|
| 43 |
-
return '{"Error":
|
| 44 |
-
return "Hola, error gpu..."
|
| 45 |
|
| 46 |
|
| 47 |
def genera_platillo_inference(platillo):
|
| 48 |
|
|
|
|
| 49 |
print("Platillo generado:", platillo)
|
| 50 |
-
|
| 51 |
client = InferenceClient(
|
| 52 |
provider= globales.proveedor,
|
| 53 |
api_key=globales.llave
|
| 54 |
-
)
|
| 55 |
-
|
| 56 |
-
prompt = globales.previo + platillo
|
| 57 |
|
| 58 |
try:
|
| 59 |
image = client.text_to_image(
|
|
@@ -63,21 +60,19 @@ def genera_platillo_inference(platillo):
|
|
| 63 |
#guidance_scale=7.5,
|
| 64 |
#num_inference_steps=50,
|
| 65 |
#width=1024, #El default es 1024 x 1024 y quizá 1024*768, el max es 1536.
|
| 66 |
-
#height=1024 #El límite de replicate es 1024.
|
| 67 |
-
|
| 68 |
)
|
| 69 |
|
| 70 |
img_io = io.BytesIO()
|
| 71 |
image.save(img_io, "PNG")
|
| 72 |
img_io.seek(0)
|
| 73 |
-
|
| 74 |
return img_io
|
| 75 |
|
| 76 |
except Exception as e:
|
| 77 |
print("Excepción es: ", e)
|
|
|
|
| 78 |
# with open("default.png", "rb") as default_image_file:
|
| 79 |
# img_io_default = io.BytesIO(default_image_file.read())
|
| 80 |
# img_io_default.seek(0)
|
| 81 |
# return img_io_default
|
| 82 |
-
return '{"Error":"500"}'
|
| 83 |
-
return "Hola error inference..."
|
|
|
|
|
|
|
|
|
|
| 1 |
import io
|
| 2 |
import globales
|
| 3 |
import herramientas
|
| 4 |
+
import gradio_client
|
| 5 |
+
from huggingface_hub import InferenceClient
|
| 6 |
|
| 7 |
def genera_platillo_gpu(platillo):
|
| 8 |
|
| 9 |
prompt = globales.previo + platillo
|
|
|
|
| 10 |
print("Platillo generado:", platillo)
|
| 11 |
|
| 12 |
kwargs = {
|
|
|
|
| 18 |
|
| 19 |
client = gradio_client.Client(globales.espacio, hf_token=globales.llave)
|
| 20 |
result = client.predict(**kwargs
|
| 21 |
+
# prompt=prompt,
|
| 22 |
# negative_prompt="",
|
| 23 |
# seed=42,
|
| 24 |
# randomize_seed=True,
|
|
|
|
| 32 |
#Cuando es GPU, debe de restar segundos disponibles de HF
|
| 33 |
herramientas.restaSegundosGPU(globales.work_cost)
|
| 34 |
|
| 35 |
+
print("Resultado regresado en result[0] es: ", result[0])
|
|
|
|
| 36 |
return result[0]
|
| 37 |
|
| 38 |
except Exception as e:
|
| 39 |
print("Excepción es: ", e)
|
| 40 |
+
# Opción para regresar imagen genérica.
|
| 41 |
# return "default.png"
|
| 42 |
+
return '{"Error 500": e}'
|
|
|
|
| 43 |
|
| 44 |
|
| 45 |
def genera_platillo_inference(platillo):
|
| 46 |
|
| 47 |
+
prompt = globales.previo + platillo
|
| 48 |
print("Platillo generado:", platillo)
|
| 49 |
+
|
| 50 |
client = InferenceClient(
|
| 51 |
provider= globales.proveedor,
|
| 52 |
api_key=globales.llave
|
| 53 |
+
)
|
|
|
|
|
|
|
| 54 |
|
| 55 |
try:
|
| 56 |
image = client.text_to_image(
|
|
|
|
| 60 |
#guidance_scale=7.5,
|
| 61 |
#num_inference_steps=50,
|
| 62 |
#width=1024, #El default es 1024 x 1024 y quizá 1024*768, el max es 1536.
|
| 63 |
+
#height=1024 #El límite de replicate es 1024.
|
|
|
|
| 64 |
)
|
| 65 |
|
| 66 |
img_io = io.BytesIO()
|
| 67 |
image.save(img_io, "PNG")
|
| 68 |
img_io.seek(0)
|
|
|
|
| 69 |
return img_io
|
| 70 |
|
| 71 |
except Exception as e:
|
| 72 |
print("Excepción es: ", e)
|
| 73 |
+
# Opción de envío de imagen genérica.
|
| 74 |
# with open("default.png", "rb") as default_image_file:
|
| 75 |
# img_io_default = io.BytesIO(default_image_file.read())
|
| 76 |
# img_io_default.seek(0)
|
| 77 |
# return img_io_default
|
| 78 |
+
return '{"Error":"500"}'
|
|
|
herramientas.py
CHANGED
|
@@ -1,17 +1,15 @@
|
|
| 1 |
import os
|
| 2 |
-
import socket
|
| 3 |
import time
|
| 4 |
-
import
|
| 5 |
|
| 6 |
def obtenAccesoHF():
|
| 7 |
if local_check():
|
| 8 |
-
print("Estoy en
|
| 9 |
import bridges
|
| 10 |
llave = bridges.llave
|
| 11 |
else:
|
| 12 |
-
print("Estoy en
|
| 13 |
llave = os.getenv("llave")
|
| 14 |
-
|
| 15 |
print("Ésto es llave:", llave)
|
| 16 |
|
| 17 |
return llave
|
|
@@ -22,11 +20,12 @@ def local_check():
|
|
| 22 |
#r-moibe-nowme
|
| 23 |
print("Dentro de local_check... , el hostname es: ", hostname)
|
| 24 |
|
|
|
|
| 25 |
if "-nowme" in hostname:
|
| 26 |
-
print("Ejecutando en el servidor")
|
| 27 |
return False
|
| 28 |
else:
|
| 29 |
-
print("Ejecutando en local")
|
| 30 |
return True
|
| 31 |
|
| 32 |
def obtenUltimoTimestamp():
|
|
@@ -87,7 +86,10 @@ def obtenSegundosDisponibles():
|
|
| 87 |
print(f"Error: El contenido del archivo '{archivo_ruta}' no es un número entero válido.")
|
| 88 |
return
|
| 89 |
|
| 90 |
-
def renuevaSegundosDisponibles():
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
print("Estoy en renuevaSegundosDisponibles...")
|
| 93 |
|
|
@@ -96,8 +98,8 @@ def renuevaSegundosDisponibles():
|
|
| 96 |
# Guardar el nuevo número en el archivo
|
| 97 |
try:
|
| 98 |
with open(archivo_ruta, 'w') as archivo:
|
| 99 |
-
archivo.write(str(
|
| 100 |
-
print(f"Se renovaron los {
|
| 101 |
renuevaTimestampActual()
|
| 102 |
except Exception as e:
|
| 103 |
print(f"Error al escribir en el archivo '{archivo_ruta}': {e}")
|
|
|
|
| 1 |
import os
|
|
|
|
| 2 |
import time
|
| 3 |
+
import socket
|
| 4 |
|
| 5 |
def obtenAccesoHF():
|
| 6 |
if local_check():
|
| 7 |
+
print("Estoy en entorno Local...")
|
| 8 |
import bridges
|
| 9 |
llave = bridges.llave
|
| 10 |
else:
|
| 11 |
+
print("Estoy en entorno Remoto...")
|
| 12 |
llave = os.getenv("llave")
|
|
|
|
| 13 |
print("Ésto es llave:", llave)
|
| 14 |
|
| 15 |
return llave
|
|
|
|
| 20 |
#r-moibe-nowme
|
| 21 |
print("Dentro de local_check... , el hostname es: ", hostname)
|
| 22 |
|
| 23 |
+
#Estoy usando el nombre de la app para identificar que estoy corriendola en HF.
|
| 24 |
if "-nowme" in hostname:
|
| 25 |
+
print("Ejecutando api en el servidor.")
|
| 26 |
return False
|
| 27 |
else:
|
| 28 |
+
print("Ejecutando api en local.")
|
| 29 |
return True
|
| 30 |
|
| 31 |
def obtenUltimoTimestamp():
|
|
|
|
| 86 |
print(f"Error: El contenido del archivo '{archivo_ruta}' no es un número entero válido.")
|
| 87 |
return
|
| 88 |
|
| 89 |
+
def renuevaSegundosDisponibles():
|
| 90 |
+
|
| 91 |
+
#Segundos de cuota total gratuita disponibles al momento.
|
| 92 |
+
quota_total = 300
|
| 93 |
|
| 94 |
print("Estoy en renuevaSegundosDisponibles...")
|
| 95 |
|
|
|
|
| 98 |
# Guardar el nuevo número en el archivo
|
| 99 |
try:
|
| 100 |
with open(archivo_ruta, 'w') as archivo:
|
| 101 |
+
archivo.write(str(quota_total))
|
| 102 |
+
print(f"Se renovaron los {quota_total} segundos disponibles.")
|
| 103 |
renuevaTimestampActual()
|
| 104 |
except Exception as e:
|
| 105 |
print(f"Error al escribir en el archivo '{archivo_ruta}': {e}")
|