ivanoctaviogaitansantos commited on
Commit
c7de00e
·
verified ·
1 Parent(s): 7d4cfdb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +147 -141
app.py CHANGED
@@ -1,149 +1,155 @@
1
- import gradio as gr
2
- import json
3
  import os
4
-
5
- PASSWORD_FILE = "password.txt"
6
- PROMPTS_FILE = "prompts.json"
7
-
8
- # Cargar prompts desde un archivo JSON si existe
9
- def cargar_prompts_desde_archivo():
10
- if os.path.exists(PROMPTS_FILE):
11
- with open(PROMPTS_FILE, 'r') as f:
12
- return json.load(f)
13
- else:
14
- # Prompts por defecto
15
- return {
16
- "secretaria": [
17
- {
18
- "name": "Cinemático oficina",
19
- "prompt": "Ultra photorealistic full body portrait of a confident blonde businesswoman dressed in an elegant secretary outfit, fitted white blouse, dark pencil skirt, silky black thigh-high stockings, and stilettos. Standing in a modern glass office with city skyline behind. Dramatic cinematic lighting, HDR, depth of field, highly detailed skin texture, professional business atmosphere, 8k, volumetric light --ar 9:16 --v 6 --q 2 --style raw",
20
- },
21
- {
22
- "name": "Editorial moda",
23
- "prompt": "Hyper realistic fashion photography of a blonde woman in a secretary-inspired outfit, high-waisted pencil skirt, white silk blouse slightly unbuttoned, sheer thigh-high stockings with lace tops, black high heels. Studio fashion editorial setting, Vogue magazine style, full body shot, high detail fabric textures, HDRI lighting, cinematic DOF, ray tracing reflections, lifelike colors, soft shadows, 16k render --ar 9:16 --v 6 --q 2",
24
- },
25
- {
26
- "name": "Oficina futurista",
27
- "prompt": "Photorealistic 8k full body portrait of a blonde woman in a sleek secretary-style outfit, fitted blouse, glossy pencil skirt, sheer thigh-high stockings with slight sheen, futuristic office environment with glass walls and neon lights. Global illumination, volumetric fog, reflective floor, cinematic composition, hyper detailed skin pores, realistic light refractions, PBR textures, HDR photograph look --ar 9:16 --v 6 --q 2 --s 800",
28
- },
29
- ]
30
- }
31
-
32
- # Guardar prompts en un archivo JSON
33
- def guardar_prompts_en_archivo(prompts_lib):
34
- with open(PROMPTS_FILE, 'w') as f:
35
- json.dump(prompts_lib, f, indent=4)
36
-
37
- prompts_lib = cargar_prompts_desde_archivo()
38
-
39
- favorites = []
40
-
41
- def guardar_contraseña(pw):
42
- if len(pw) != 4 or not pw.isdigit():
43
- return "La contraseña debe tener exactamente 4 dígitos"
44
- with open(PASSWORD_FILE, "w") as f:
45
- f.write(pw)
46
- return "Contraseña guardada correctamente. Ahora úsala para entrar."
47
-
48
- def cargar_contraseña():
49
- if not os.path.exists(PASSWORD_FILE):
50
  return None
51
- with open(PASSWORD_FILE, "r") as f:
52
- return f.read().strip()
53
-
54
- def verificar_password(pw):
55
- pw_guardada = cargar_contraseña()
56
- if pw_guardada is None:
57
- return "No hay contraseña registrada. Por favor crea una."
58
- if pw == pw_guardada:
59
- return "Acceso concedido"
60
- else:
61
- return "Contraseña incorrecta"
62
-
63
- def gestionar_password(pw, crear=False):
64
- if crear:
65
- return guardar_contraseña(pw)
66
- else:
67
- return verificar_password(pw)
68
-
69
- def agregar_prompt(categoria, nombre, texto):
70
- categoria = categoria.strip().lower()
71
- if not categoria:
72
- categoria = "sin_categoria"
73
- if categoria not in prompts_lib:
74
- prompts_lib[categoria] = []
75
- prompts_lib[categoria].append({
76
- "name": nombre if nombre else f"Nuevo {len(prompts_lib[categoria])+1}",
77
- "prompt": texto,
78
- })
79
- guardar_prompts_en_archivo(prompts_lib)
80
- return f"Prompt añadido en '{categoria}'"
81
-
82
- def mostrar_prompts(categoria, filtro=""):
83
- categoria = categoria.strip().lower()
84
- prompts = prompts_lib.get(categoria, [])
85
- rows = []
86
- for p in prompts:
87
- if filtro.lower() in p["prompt"].lower() or filtro.lower() in p["name"].lower():
88
- rows.append([p["name"], p["prompt"]])
89
- return rows
90
-
91
- def exportar_prompts(categoria):
92
- categoria = categoria.strip().lower()
93
- prompts = prompts_lib.get(categoria, [])
94
- contenido = ""
95
- for p in prompts:
96
- contenido += f"Nombre: {p['name']}\nPrompt: {p['prompt']}\n\n"
97
- return contenido
98
-
99
- with gr.Blocks(theme=gr.themes.Dark()) as demo:
100
- gr.Markdown("# BAT-@talogo_pro")
101
-
102
- with gr.Tab("Acceso"):
103
- estado = gr.Textbox(interactive=False)
104
- pass_input = gr.Textbox(label="Contraseña 4 dígitos", type="password", max_lines=1)
105
- crear_btn = gr.Button("Crear contraseña (solo la primera vez)")
106
- entrar_btn = gr.Button("Entrar")
107
-
108
- crear_btn.click(fn=lambda pw: gestionar_password(pw, crear=True), inputs=pass_input, outputs=estado)
109
- entrar_btn.click(fn=lambda pw: gestionar_password(pw, crear=False), inputs=pass_input, outputs=estado)
110
-
111
- with gr.Tab("Buscar y visualizar"):
112
- categoria_input = gr.Textbox(label="Categoría de outfit", placeholder="Ejemplo: secretaria")
113
- filtro_input = gr.Textbox(label="Palabra clave (opcional)", placeholder="Ejemplo: moda, secretaria...")
114
- buscar_btn = gr.Button("🔍 Buscar")
115
- resultado = gr.Dataframe(headers=["Nombre", "Prompt"])
116
- export_btn = gr.Button("Exportar TXT")
117
- output_txt = gr.Textbox(label="Prompts exportados", interactive=False)
118
-
119
- buscar_btn.click(
120
- fn=mostrar_prompts,
121
- inputs=[categoria_input, filtro_input],
122
- outputs=resultado
123
  )
124
- export_btn.click(
125
- fn=exportar_prompts,
126
- inputs=categoria_input,
127
- outputs=output_txt
128
- )
129
-
130
- with gr.Tab("Edición y agregado", visible=False) as edit_tab:
131
- categoria_new = gr.Textbox(label="Categoría nueva o existente", placeholder="Ejemplo: secretaria")
132
- nombre_new = gr.Textbox(label="Nombre del prompt", placeholder="Ejemplo: Estilo business moderno")
133
- prompt_new = gr.Textbox(label="Prompt (puedes pegar desde portapapeles)", lines=6)
134
- agregar_btn = gr.Button("Agregar a catálogo")
135
- confirmacion = gr.Textbox(label="", interactive=False)
136
-
137
- agregar_btn.click(
138
- fn=agregar_prompt,
139
- inputs=[categoria_new, nombre_new, prompt_new],
140
- outputs=confirmacion
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  )
 
 
 
142
 
143
- def mostrar_editor(mensaje):
144
- return gr.update(visible=(mensaje == "Acceso concedido"))
145
 
146
- estado.change(fn=mostrar_editor, inputs=estado, outputs=edit_tab)
 
 
147
 
148
- # Lanzar el demo
149
  demo.launch()
 
 
 
1
  import os
2
+ import gradio as gr
3
+ from hf_hub_cto import Repo
4
+ from hf_hub_cto.config import (
5
+ HF_TOKEN_FILE_PATH,
6
+ MAX_FILE_SIZE,
7
+ MAX_REPO_SIZE,
8
+ REPO_TYPES,
9
+ )
10
+ from hf_hub_cto.repo_info import RepoInfo
11
+ from hf_hub_cto.repo_utils import (
12
+ clone_repo,
13
+ delete_repo,
14
+ get_repo_info_df,
15
+ get_repo_files,
16
+ is_valid_file_size,
17
+ repo_file_upload,
18
+ repo_rename_file,
19
+ sync_repo,
20
+ )
21
+
22
+ # Initialize the huggingface hub repository
23
+ repo = Repo(
24
+ repo_id=os.getenv("REPO_ID"),
25
+ repo_type=os.getenv("REPO_TYPE"),
26
+ token=os.getenv("HF_TOKEN"),
27
+ local_dir=os.getenv("LOCAL_DIR"),
28
+ )
29
+
30
+ def get_session_info(session_id: str):
31
+ user_info = gr.LoginButton.get_user_info(session_id)
32
+ if not user_info:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  return None
34
+ return user_info
35
+
36
+
37
+ def set_repo_info(repo_id: str, repo_type: str, token: str):
38
+ repo_id_info = RepoInfo(repo_id=repo_id, repo_type=repo_type)
39
+ return gr.update(value=repo_id), gr.update(value=repo_type), gr.update(value=token), repo_id_info
40
+
41
+
42
+ def get_all_repos_df(session_id: str):
43
+ user_info = get_session_info(session_id)
44
+ if not user_info:
45
+ return gr.DataFrame(visible=False), gr.update(visible=True)
46
+
47
+ df = get_repo_info_df(user_info["name"], token=os.getenv("HF_TOKEN"))
48
+ df = df.sort_values(by="last_modified", ascending=False).reset_index(drop=True)
49
+ return gr.DataFrame(value=df, visible=True), gr.update(visible=False)
50
+
51
+
52
+ def handle_repo_selection(
53
+ evt: gr.SelectData,
54
+ repo_df: gr.DataFrame,
55
+ session_id: str,
56
+ ):
57
+ selected_row = repo_df.loc[evt.index[0]]
58
+ repo_id = selected_row["repoId"]
59
+ repo_type = selected_row["type"]
60
+ return (
61
+ gr.Textbox(value=repo_id),
62
+ gr.Textbox(value=repo_type),
63
+ gr.Button(visible=True),
64
+ gr.Button(visible=True),
65
+ gr.Button(visible=True),
66
+ )
67
+
68
+
69
+ def handle_create_repo(repo_id: str, repo_type: str):
70
+ try:
71
+ if repo_type == "Model":
72
+ Repo(repo_id, repo_type="model").create_repo()
73
+ elif repo_type == "Dataset":
74
+ Repo(repo_id, repo_type="dataset").create_repo()
75
+ else:
76
+ Repo(repo_id, repo_type="space").create_repo()
77
+ return "Repo creado exitosamente.", None
78
+ except Exception as e:
79
+ return None, str(e)
80
+
81
+
82
+ def handle_delete_repo(repo_id: str, repo_type: str, session_id: str):
83
+ user_info = get_session_info(session_id)
84
+ if not user_info:
85
+ return "Error: usuario no autenticado."
86
+ try:
87
+ delete_repo(
88
+ repo_id,
89
+ repo_type,
90
+ user_info["name"],
91
+ os.getenv("HF_TOKEN"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  )
93
+ return "Repo eliminado exitosamente."
94
+ except Exception as e:
95
+ return f"Error al eliminar el repositorio: {str(e)}"
96
+
97
+
98
+ def get_repo_contents(repo_id: str, repo_type: str):
99
+ files = get_repo_files(repo_id=repo_id, repo_type=repo_type, token=os.getenv("HF_TOKEN"))
100
+ return gr.DataFrame(value=files)
101
+
102
+
103
+ def handle_clone_repo(repo_id: str, repo_type: str):
104
+ try:
105
+ clone_repo(repo_id, repo_type)
106
+ return "Repositorio clonado exitosamente."
107
+ except Exception as e:
108
+ return f"Error al clonar el repositorio: {str(e)}"
109
+
110
+
111
+ def handle_sync_repo(repo_id: str, repo_type: str):
112
+ try:
113
+ sync_repo(repo_id, repo_type)
114
+ return "Repositorio sincronizado exitosamente."
115
+ except Exception as e:
116
+ return f"Error al sincronizar el repositorio: {str(e)}"
117
+
118
+
119
+ def handle_file_upload(
120
+ files: list, repo_id: str, repo_type: str, upload_folder: str
121
+ ):
122
+ try:
123
+ for file in files:
124
+ if not is_valid_file_size(file.size, MAX_FILE_SIZE):
125
+ raise ValueError(
126
+ f"El archivo {file.name} excede el límite de tamaño de {MAX_FILE_SIZE / (1024 ** 2)} MB."
127
+ )
128
+ repo_file_upload(
129
+ repo_id, repo_type, file.name, upload_folder, os.getenv("HF_TOKEN")
130
+ )
131
+ return "Archivos cargados exitosamente."
132
+ except Exception as e:
133
+ return f"Error al cargar archivos: {str(e)}"
134
+
135
+
136
+ def handle_rename_file(repo_id: str, repo_type: str, old_path: str, new_path: str):
137
+ try:
138
+ repo_rename_file(
139
+ repo_id,
140
+ repo_type,
141
+ old_path,
142
+ new_path,
143
+ os.getenv("HF_TOKEN"),
144
  )
145
+ return "Archivo renombrado exitosamente."
146
+ except Exception as e:
147
+ return f"Error al renombrar el archivo: {str(e)}"
148
 
149
+ # --- INTERFAZ DE USUARIO CON GRADIO ---
 
150
 
151
+ with gr.Blocks(theme=gr.themes.Base()) as demo:
152
+ # Resto del código de la interfaz de usuario...
153
+ pass
154
 
 
155
  demo.launch()