File size: 5,199 Bytes
3824dd3 b33697f 3824dd3 474dabe 03bc1dd 326ec62 3824dd3 474dabe c11400d 326ec62 3824dd3 474dabe 3824dd3 b33697f 474dabe b33697f 474dabe 326ec62 474dabe 326ec62 474dabe 3824dd3 474dabe 3824dd3 474dabe 3824dd3 474dabe 3824dd3 b33697f 4499de3 814fd19 4499de3 814fd19 4499de3 814fd19 4499de3 814fd19 4499de3 b33697f 4499de3 b33697f 4499de3 b33697f 3824dd3 b33697f 3824dd3 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
import gradio as gr
import pandas as pd
import re
from datetime import datetime
from hashlib import sha256
import os
from huggingface_hub import HfApi, hf_hub_download
from PIL import Image
import requests
from io import BytesIO
from huggingface_hub import HfApi
# Configuración
CSV_FILE = "registros_incidencias.csv"
PASSWORD_HASH = "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918"
REPO_ID = "IvanRes25/IMSS" # Cambiar por tu usuario/repo de HF
HF_TOKEN = os.getenv("IMSS") # Se autodetecta del Space
PRESTACIONES = [
"1. PROFESIONALIZACIÓN",
"2. ESTIMULOS DE PRODUCTIVIDAD",
"3. UNIFORMES",
"4. DESCUENTOS INJUSTIFICADOS",
"5. SEGURO DE VIDA",
"6. AHORRO SOLIDARIO",
"7. OTROS"
]
# Funciones para CSV
def cargar_csv():
try:
return pd.read_csv(hf_hub_download(
repo_id=REPO_ID,
filename=CSV_FILE,
repo_type="space",
token=os.getenv("IMSS")
))
except:
df = pd.DataFrame(columns=[
"Fecha_Registro", "Entidad", "Nombre",
"CURP", "Prestacion", "Quincena"
])
guardar_csv(df)
return df
def guardar_csv(df):
api = HfApi(token=HF_TOKEN)
api.upload_file(
path_or_fileobj="registros.csv",
path_in_repo="registros.csv",
repo_id=REPO_ID,
repo_type="space"
)
def guardar_registro(entidad, nombre, curp, prestacion, quincena):
if not all([entidad, nombre, curp, prestacion, quincena]):
return "⚠️ Todos los campos son obligatorios"
if not re.match(r'^[A-Z]{4}[0-9]{6}[HM][A-Z]{5}[A-Z0-9]{2}$', curp.upper()):
return "⚠️ CURP inválido"
try:
df = cargar_csv()
nuevo_registro = {
"Fecha_Registro": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"Entidad": entidad.strip().upper(),
"Nombre": nombre.strip().title(),
"CURP": curp.upper(),
"Prestacion": prestacion,
"Quincena": quincena
}
df = pd.concat([df, pd.DataFrame([nuevo_registro])], ignore_index=True)
guardar_csv(df)
return "✅ Registro guardado permanentemente"
except Exception as e:
return f"❌ Error: {str(e)}"
def verificar_credenciales(username, password):
return username == "admin" and sha256(password.encode()).hexdigest() == PASSWORD_HASH
# Interfaz
with gr.Blocks(title="Sistema de Captura") as app:
logged_in = gr.State(False)
with gr.Column(visible=True) as login_col:
# Intenta cargar la imagen local
try:
# Carga la imagen y redimensiona
img = Image.open("d5bb4c4a-f9e5-4c70-a53c-23b7dc3872a1.jpg")
img.thumbnail((300, 300)) # Ajusta el tamaño según necesites
# Muestra la imagen en la interfaz
gr.Image(
value=img, # Usamos la imagen directamente
label="",
show_label=False,
interactive=False
)
except Exception as e:
print(f"Error cargando imagen: {e}")
# Muestra un marcador de posición si falla
gr.Markdown("")
# Resto de tu interfaz de login
gr.Markdown("# Sistema de Captura de Incidencias")
username = gr.Textbox(label="Usuario") # 8 espacios (4 del with + 4 del componente)
password = gr.Textbox(label="Contraseña", type="password")
login_btn = gr.Button("Ingresar")
login_msg = gr.Textbox(label="Mensaje", interactive=False)
# Captura (mismo nivel que el bloque de login)
with gr.Column(visible=False) as captura_col:
gr.Markdown("## Captura de Datos")
entidad = gr.Textbox(label="Entidad Federativa")
nombre = gr.Textbox(label="Nombre completo")
curp = gr.Textbox(label="CURP")
prestacion = gr.Dropdown(PRESTACIONES, label="Prestación afectada")
quincena = gr.Textbox(label="Quincena (AAAA-MM-DD)")
submit_btn = gr.Button("Guardar")
resultado = gr.Textbox(label="Resultado")
logout_btn = gr.Button("Cerrar sesión")
# Eventos (también dentro de gr.Blocks)
def autenticar(user, pwd):
if verificar_credenciales(user, pwd):
return {
login_col: gr.update(visible=False),
captura_col: gr.update(visible=True),
login_msg: ""
}
return {
login_msg: "⚠️ Credenciales incorrectas"
}
def cerrar_sesion():
return {
login_col: gr.update(visible=True),
captura_col: gr.update(visible=False),
login_msg: ""
}
login_btn.click(
autenticar,
inputs=[username, password],
outputs=[login_col, captura_col, login_msg]
)
logout_btn.click(
cerrar_sesion,
outputs=[login_col, captura_col, login_msg]
)
submit_btn.click(
guardar_registro,
inputs=[entidad, nombre, curp, prestacion, quincena],
outputs=resultado
)
app.launch() |