# -*- coding: utf-8 -*- import os import sqlite3 import json import threading import gradio as gr from fastapi import FastAPI, Request, HTTPException # ---------------------------------------------------------------------- # Database utilities # ---------------------------------------------------------------------- DB_PATH = "inventario.db" def init_db(): conn = sqlite3.connect(DB_PATH) cur = conn.cursor() cur.execute(""" CREATE TABLE IF NOT EXISTS productos ( id INTEGER PRIMARY KEY AUTOINCREMENT, nombre TEXT NOT NULL, cantidad INTEGER NOT NULL, precio REAL NOT NULL ) """) conn.commit() conn.close() def get_all_products(): conn = sqlite3.connect(DB_PATH) cur = conn.cursor() cur.execute("SELECT id, nombre, cantidad, precio FROM productos") rows = cur.fetchall() conn.close() return [ {"id": r[0], "nombre": r[1], "cantidad": r[2], "precio": r[3]} for r in rows ] def insert_product(nombre: str, cantidad: int, precio: float): conn = sqlite3.connect(DB_PATH) cur = conn.cursor() cur.execute( "INSERT INTO productos (nombre, cantidad, precio) VALUES (?, ?, ?)", (nombre, cantidad, precio) ) conn.commit() product_id = cur.lastrowid conn.close() return {"id": product_id, "nombre": nombre, "cantidad": cantidad, "precio": precio} # ---------------------------------------------------------------------- # FastAPI app (mounted on Gradio's internal server) # ---------------------------------------------------------------------- fastapi_app = FastAPI() @fastapi_app.get("/") async def root(): return { "message": "Bienvenido al Sistema de Gestion de Inventario", "docs": "/docs" } @fastapi_app.get("/productos") async def list_productos(): return get_all_products() @fastapi_app.post("/productos") async def create_producto(request: Request): try: data = await request.json() nombre = data["nombre"] cantidad = int(data["cantidad"]) precio = float(data["precio"]) except Exception as e: raise HTTPException(status_code=400, detail="JSON invalido") product = insert_product(nombre, cantidad, precio) return product # ---------------------------------------------------------------------- # Gradio UI # ---------------------------------------------------------------------- def refresh_table(): products = get_all_products() # Convert to list of lists for Dataframe component return [[p["id"], p["nombre"], p["cantidad"], p["precio"]] for p in products] def add_product(nombre, cantidad, precio): product = insert_product(nombre, int(cantidad), float(precio)) return f"Producto agregado con id {product['id']}", refresh_table() with gr.Blocks() as demo: gr.Markdown("# Sistema de Gestion de Inventario") with gr.Row(): nombre_input = gr.Textbox(label="Nombre", placeholder="Ejemplo: Lápiz") cantidad_input = gr.Number(label="Cantidad", precision=0) precio_input = gr.Number(label="Precio", precision=2) add_btn = gr.Button("Agregar Producto") status = gr.Textbox(label="Estado", interactive=False) product_table = gr.Dataframe( headers=["ID", "Nombre", "Cantidad", "Precio"], label="Productos", interactive=False ) refresh_btn = gr.Button("Actualizar Tabla") add_btn.click(add_product, inputs=[nombre_input, cantidad_input, precio_input], outputs=[status, product_table]) refresh_btn.click(fn=refresh_table, inputs=None, outputs=product_table) # ---------------------------------------------------------------------- # Mount FastAPI routes onto Gradio's internal server # ---------------------------------------------------------------------- # demo.server.app.mount("/", fastapi_app) # Removed: Blocks has no server attribute # ---------------------------------------------------------------------- # Initialize DB and launch # ---------------------------------------------------------------------- if __name__ == "__main__": init_db() demo.launch(server_name="0.0.0.0", server_port=7860)