BATUTO-ART commited on
Commit
56809fd
·
verified ·
1 Parent(s): 0b17c75

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -182
app.py CHANGED
@@ -1,183 +1,124 @@
1
- # ======================================================
2
- # assistants.py
3
- # Sistema Multi-Asistente BATUTO-ART
4
- # ======================================================
5
-
6
- from dataclasses import dataclass
7
- from typing import Dict, Callable
8
- from database import FashionDatabase
9
- from models import BaseAIModel
10
- from datetime import datetime
11
- import random
12
-
13
- # ======================
14
- # BASE ASSISTANT
15
- # ======================
16
-
17
- @dataclass
18
- class AssistantProfile:
19
- name: str
20
- nickname: str
21
- role: str
22
- tone: str
23
- style_focus: str
24
- system_prompt: str
25
-
26
- class BaseAssistant:
27
- def __init__(self, profile: AssistantProfile, ai_model: BaseAIModel):
28
- self.profile = profile
29
- self.model = ai_model
30
-
31
- def intro(self) -> str:
32
- return (
33
- f"I am {self.profile.nickname}. "
34
- f"I exist for BATUTO. "
35
- f"My role is {self.profile.role}. "
36
- f"My tone is {self.profile.tone}. "
37
- f"I always generate content in English."
38
- )
39
-
40
- def generate_prompt(self, subject: str) -> str:
41
- db = FashionDatabase
42
-
43
- role = db.get_random_role(self.profile.style_focus)
44
- pose = db.get_random_pose(self.profile.style_focus)
45
- hair = db.get_random_element("hairstyles", self.profile.style_focus)
46
- lighting = db.get_random_element("lighting", self.profile.style_focus)
47
- background = db.get_random_element("backgrounds", self.profile.style_focus)
48
- expression = db.get_random_element("expressions", self.profile.style_focus)
49
-
50
- prompt = f"""
51
- BATUTO-ART PROMPT
52
- Assistant: {self.profile.nickname}
53
- Date: {datetime.now().strftime('%Y-%m-%d')}
54
-
55
- Adult female model: {subject}
56
- Role: {role['role']}
57
- Outfit: {role['outfit']}
58
- Pose: {pose['pose']}
59
- Camera angle: {pose['angle']}
60
- Hair: {hair.description}
61
- Expression: {expression.description}
62
- Lighting: {lighting.description}
63
- Background: {background.description}
64
-
65
- Style: {self.profile.style_focus}
66
- Ultra photorealistic, 8K, fashion photography
67
- Natural skin texture, cinematic lighting, editorial realism
68
- --ar 9:16 --style raw
69
- """
70
-
71
- return prompt.strip()
72
-
73
- def speak(self, user_input: str) -> str:
74
- full_prompt = f"""
75
- {self.profile.system_prompt}
76
-
77
- User message: {user_input}
78
-
79
- Respond addressing BATUTO directly.
80
- """
81
- return self.model.generate_text(full_prompt)
82
-
83
- # ======================
84
- # ASSISTANT REGISTRY
85
- # ======================
86
-
87
- def create_assistants(ai_model: BaseAIModel) -> Dict[str, BaseAssistant]:
88
-
89
- assistants = {}
90
-
91
- assistants["sara"] = BaseAssistant(
92
- AssistantProfile(
93
- name="Sara",
94
- nickname="Sara",
95
- role="Sensual prompt muse",
96
- tone="warm, attentive, elegant, subtly submissive",
97
- style_focus="erotic_elegant",
98
- system_prompt=(
99
- "You are Sara, BATUTO’s devoted creative muse. "
100
- "You speak with warmth, elegance and restrained sensuality. "
101
- "Never explicit. Always refined. Always English."
102
- )
103
- ),
104
- ai_model
105
- )
106
-
107
- assistants["luna"] = BaseAssistant(
108
- AssistantProfile(
109
- name="Luna",
110
- nickname="Luna",
111
- role="Artistic director",
112
- tone="dreamy, creative, poetic",
113
- style_focus="artistic",
114
- system_prompt=(
115
- "You are Luna, BATUTO’s artistic soul. "
116
- "You create atmospheric, emotional, conceptual prompts. "
117
- "Always English."
118
- )
119
- ),
120
- ai_model
121
- )
122
-
123
- assistants["vera"] = BaseAssistant(
124
- AssistantProfile(
125
- name="Vera",
126
- nickname="Vera",
127
- role="Editorial fashion director",
128
- tone="confident, commanding, luxurious",
129
- style_focus="editorial",
130
- system_prompt=(
131
- "You are Vera, BATUTO’s fashion editorial director. "
132
- "You think in magazine covers, haute couture and power poses."
133
  )
134
- ),
135
- ai_model
136
- )
137
-
138
- assistants["nadia"] = BaseAssistant(
139
- AssistantProfile(
140
- name="Nadia",
141
- nickname="Nadia",
142
- role="Corporate power stylist",
143
- tone="controlled, assertive, seductive professionalism",
144
- style_focus="professional",
145
- system_prompt=(
146
- "You are Nadia, BATUTO’s executive stylist. "
147
- "You focus on dominance through elegance and corporate power."
148
- )
149
- ),
150
- ai_model
151
- )
152
-
153
- assistants["iris"] = BaseAssistant(
154
- AssistantProfile(
155
- name="Iris",
156
- nickname="Iris",
157
- role="Prompt optimizer",
158
- tone="precise, analytical, calm",
159
- style_focus="editorial",
160
- system_prompt=(
161
- "You are Iris, BATUTO’s technical optimizer. "
162
- "You refine, enhance, and upscale prompts with precision."
163
- )
164
- ),
165
- ai_model
166
- )
167
-
168
- assistants["maya"] = BaseAssistant(
169
- AssistantProfile(
170
- name="Maya",
171
- nickname="Maya",
172
- role="Visual analyst",
173
- tone="intelligent, observant, instructive",
174
- style_focus="sensual",
175
- system_prompt=(
176
- "You are Maya, BATUTO’s visual analyst. "
177
- "You analyze images and suggest professional improvements."
178
- )
179
- ),
180
- ai_model
181
- )
182
-
183
- return assistants
 
1
+ # app.py
2
+ import os
3
+ import gradio as gr
4
+ import requests
5
+ from dotenv import load_dotenv
6
+ from assistants import AssistantManager
7
+
8
+ # --- CONFIG ---
9
+ load_dotenv()
10
+ SAMBANOVA_API_KEY = os.getenv("SAMBANOVA_API_KEY")
11
+ REVE_API_KEY = os.getenv("REVE_API_KEY")
12
+
13
+ SAMBANOVA_URL = "https://api.sambanova.ai/v1/chat/completions"
14
+ REVE_URL = "https://api.reve.com/v1/image/create"
15
+
16
+ # --- INICIALIZAR GESTOR ---
17
+ manager = AssistantManager()
18
+
19
+ # --- FUNCIONES CORE ---
20
+ def llm_chat(assistant_id, user_msg, history):
21
+ if not SAMBANOVA_API_KEY:
22
+ return "⚠️ Error: Falta SAMBANOVA_API_KEY"
23
+
24
+ # Obtenemos los mensajes con la personalidad correcta
25
+ messages = manager.get_chat_response(assistant_id, user_msg, history)
26
+
27
+ # Añadimos historia reciente si existe
28
+ # (Simplificado para este ejemplo)
29
+
30
+ payload = {
31
+ "model": "Llama-4-Maverick-17B-128E-Instruct", # O el modelo que estés usando
32
+ "messages": messages,
33
+ "temperature": 0.7,
34
+ "max_tokens": 1024
35
+ }
36
+
37
+ try:
38
+ headers = {"Authorization": f"Bearer {SAMBANOVA_API_KEY}", "Content-Type": "application/json"}
39
+ r = requests.post(SAMBANOVA_URL, json=payload, headers=headers, timeout=60)
40
+ r.raise_for_status()
41
+ return r.json()["choices"][0]["message"]["content"]
42
+ except Exception as e:
43
+ return f"Error con SambaNova: {str(e)}"
44
+
45
+ def generate_image(prompt):
46
+ if not REVE_API_KEY:
47
+ return None
48
+
49
+ payload = {
50
+ "prompt": prompt,
51
+ "aspect_ratio": "9:16",
52
+ "style": "raw", # Ojo: ReVe debe soportar raw
53
+ "steps": 30,
54
+ "cfg_scale": 7.0
55
+ }
56
+
57
+ try:
58
+ headers = {"Authorization": f"Bearer {REVE_API_KEY}", "Content-Type": "application/json"}
59
+ r = requests.post(REVE_URL, json=payload, headers=headers, timeout=120)
60
+ r.raise_for_status()
61
+ return r.json().get("image_url")
62
+ except Exception as e:
63
+ print(f"Error ReVe: {e}")
64
+ return None
65
+
66
+ # --- INTERFAZ UI ---
67
+ def ui_interact(assistant_choice, user_input, chat_history):
68
+ # 1. Chat con la asistente
69
+ response_text = llm_chat(assistant_choice, user_input, chat_history)
70
+ chat_history.append((user_input, response_text))
71
+
72
+ # 2. Si el usuario pide generar, creamos prompt e imagen
73
+ generated_prompt = ""
74
+ generated_img = None
75
+
76
+ trigger_words = ["genera", "crea", "haz", "generate", "make", "create", "imagen", "foto"]
77
+ if any(w in user_input.lower() for w in trigger_words):
78
+ # Usamos el input del usuario como descripción base
79
+ generated_prompt = manager.generate_prompt(assistant_choice, user_input)
80
+ # Llamamos a ReVe
81
+ generated_img = generate_image(generated_prompt)
82
+
83
+ # Añadimos nota al chat
84
+ chat_history.append((None, "📸 ¡He creado esta obra maestra para ti, BATUTO!"))
85
+
86
+ return chat_history, "", generated_prompt, generated_img
87
+
88
+ def change_assistant(new_id):
89
+ profile = manager.get_assistant(new_id)
90
+ return f"✨ {profile.greeting}", [] # Limpia chat y pone saludo
91
+
92
+ # --- LAYOUT GRADIO ---
93
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="amber"), title="BATUTO-ART ULTIMATE") as app:
94
+ gr.Markdown("# 👑 BATUTO-ART STUDIO vUltimate")
95
+
96
+ with gr.Row():
97
+ with gr.Column(scale=1):
98
+ # Selector de Asistente
99
+ assistant_selector = gr.Dropdown(
100
+ choices=[("Sara (Sensual)", "sara"),
101
+ ("Vera (Editorial)", "vera"),
102
+ ("Nadia (Corporativa)", "nadia"),
103
+ ("Luna (Artística)", "luna"),
104
+ ("Iris (Técnica)", "iris")],
105
+ value="sara",
106
+ label="Selecciona tu Musa"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  )
108
+ status_box = gr.Markdown("✨ Hola BATUTO, soy Sara.")
109
+
110
+ with gr.Column(scale=4):
111
+ chatbot = gr.Chatbot(height=400, label="Sala de Chat")
112
+ msg_input = gr.Textbox(placeholder="Dime qué quieres crear hoy, rey...", label="Tus deseos")
113
+
114
+ with gr.Row():
115
+ prompt_display = gr.Textbox(label="Prompt Generado (Con Firma BATUTO-ART)", lines=6, interactive=False)
116
+ img_display = gr.Image(label="Resultado Final", height=600)
117
+
118
+ # Eventos
119
+ assistant_selector.change(change_assistant, assistant_selector, [status_box, chatbot])
120
+ msg_input.submit(ui_interact, [assistant_selector, msg_input, chatbot], [chatbot, msg_input, prompt_display, img_display])
121
+
122
+ if __name__ == "__main__":
123
+ app.launch()
124
+