Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,5 @@
|
|
1 |
import os
|
|
|
2 |
import uuid
|
3 |
from typing import List, Tuple, Optional, Union
|
4 |
from PIL import Image
|
@@ -9,168 +10,221 @@ from dotenv import load_dotenv
|
|
9 |
# Cargar las variables de entorno desde el archivo .env
|
10 |
load_dotenv()
|
11 |
|
12 |
-
|
|
|
|
|
13 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
|
|
|
|
14 |
if not GOOGLE_API_KEY:
|
15 |
raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
|
26 |
-
|
27 |
-
def preprocess_image(image: Image.Image) -> Optional[Image.Image]:
|
28 |
-
if image:
|
29 |
-
image_height = int(image.height * IMAGE_WIDTH / image.width)
|
30 |
-
return image.resize((IMAGE_WIDTH, image_height))
|
31 |
-
|
32 |
-
# Función para guardar imágenes en caché
|
33 |
-
def cache_pil_image(image: Image.Image) -> str:
|
34 |
-
image_filename = f"{uuid.uuid4()}.jpeg"
|
35 |
-
os.makedirs(IMAGE_CACHE_DIRECTORY, exist_ok=True)
|
36 |
-
image_path = os.path.join(IMAGE_CACHE_DIRECTORY, image_filename)
|
37 |
-
image.save(image_path, "JPEG")
|
38 |
-
return image_path
|
39 |
|
40 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
def bot_response(
|
42 |
model_choice: str,
|
43 |
system_instruction: str,
|
44 |
text_prompt: str,
|
45 |
-
chatbot:
|
46 |
-
) -> Tuple[
|
|
|
|
|
|
|
47 |
if not text_prompt.strip():
|
48 |
return chatbot, "Por favor, escribe un mensaje válido."
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
generation_config={
|
53 |
-
"temperature": 1,
|
54 |
-
"top_p": 0.95,
|
55 |
-
"top_k": 40,
|
56 |
-
"max_output_tokens": 8192,
|
57 |
-
},
|
58 |
-
)
|
59 |
-
chat = model.start_chat(history=chatbot)
|
60 |
-
chat.system_instruction = system_instruction
|
61 |
|
62 |
-
|
|
|
|
|
|
|
|
|
63 |
response.resolve()
|
64 |
|
65 |
-
|
|
|
|
|
|
|
|
|
|
|
66 |
return chatbot, ""
|
67 |
|
68 |
-
#
|
69 |
-
def
|
70 |
-
if
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
return chatbot
|
78 |
|
79 |
-
def
|
80 |
-
text_prompt:
|
81 |
-
|
|
|
|
|
|
|
|
|
82 |
model_choice: str,
|
83 |
-
system_instruction: str,
|
84 |
-
chatbot:
|
85 |
):
|
86 |
-
if not
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
"max_output_tokens": 8192,
|
96 |
-
"top_k": 10,
|
97 |
-
"top_p": 0.9,
|
98 |
-
},
|
99 |
)
|
100 |
-
chat = model.start_chat(history=chatbot)
|
101 |
-
chat.system_instruction = system_instruction
|
102 |
|
103 |
-
if
|
104 |
-
|
105 |
-
if files:
|
106 |
-
images = [cache_pil_image(preprocess_image(Image.open(file.name))) for file in files]
|
107 |
-
chatbot.append((f"Uploaded images: {', '.join(images)}", ""))
|
108 |
|
109 |
-
|
110 |
-
|
111 |
|
112 |
-
|
113 |
-
|
|
|
|
|
|
|
114 |
|
115 |
-
|
116 |
-
def build_interface():
|
117 |
-
with gr.Blocks() as demo:
|
118 |
-
gr.HTML(TITLE)
|
119 |
-
gr.HTML(SUBTITLE)
|
120 |
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
)
|
127 |
-
|
128 |
-
system_instruction_1 = gr.Textbox(
|
129 |
-
placeholder="Escribe una instrucción para el sistema...",
|
130 |
-
label="Instrucción del sistema",
|
131 |
-
value="You are an assistant.",
|
132 |
-
)
|
133 |
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
)
|
143 |
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
)
|
150 |
-
chatbot_2 = gr.Chatbot(label="Gemini", height=300)
|
151 |
-
system_instruction_2 = gr.Textbox(
|
152 |
-
placeholder="Escribe una instrucción para el sistema...",
|
153 |
-
label="Instrucción del sistema",
|
154 |
)
|
155 |
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
fn=
|
168 |
-
inputs=[
|
169 |
-
outputs=[
|
170 |
)
|
171 |
|
172 |
-
|
|
|
|
|
|
|
|
|
173 |
|
174 |
-
|
175 |
-
demo = build_interface()
|
176 |
-
demo.launch(debug=True)
|
|
|
1 |
import os
|
2 |
+
import time
|
3 |
import uuid
|
4 |
from typing import List, Tuple, Optional, Union
|
5 |
from PIL import Image
|
|
|
10 |
# Cargar las variables de entorno desde el archivo .env
|
11 |
load_dotenv()
|
12 |
|
13 |
+
print("google-generativeai:", genai.__version__)
|
14 |
+
|
15 |
+
# Obtener la clave de la API de las variables de entorno
|
16 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
17 |
+
|
18 |
+
# Verificar que la clave de la API esté configurada
|
19 |
if not GOOGLE_API_KEY:
|
20 |
raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
|
21 |
|
22 |
+
# Configuración del modelo Gemini
|
23 |
+
generation_config = {
|
24 |
+
"temperature": 1,
|
25 |
+
"top_p": 0.95,
|
26 |
+
"top_k": 40,
|
27 |
+
"max_output_tokens": 8192,
|
28 |
+
"response_mime_type": "text/plain",
|
29 |
+
}
|
30 |
|
31 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
+
# Inicializar los modelos para ambas pestañas
|
34 |
+
model_with_images = genai.GenerativeModel(
|
35 |
+
model_name="gemini-1.5-flash",
|
36 |
+
generation_config=generation_config
|
37 |
+
)
|
38 |
+
|
39 |
+
model_text_only = genai.GenerativeModel(
|
40 |
+
model_name="gemini-1.5-flash",
|
41 |
+
generation_config=generation_config
|
42 |
+
)
|
43 |
+
|
44 |
+
# Inicializar la sesión de chat para el chatbot sin imágenes
|
45 |
+
chat_text_only = model_text_only.start_chat(history=[])
|
46 |
+
|
47 |
+
# Función para transformar el historial de Gradio al formato de Gemini
|
48 |
+
def transform_history(history):
|
49 |
+
new_history = []
|
50 |
+
for chat_entry in history:
|
51 |
+
new_history.append({"parts": [{"text": chat_entry[0]}], "role": "user"})
|
52 |
+
new_history.append({"parts": [{"text": chat_entry[1]}], "role": "model"})
|
53 |
+
return new_history
|
54 |
+
|
55 |
+
# Función de respuesta que maneja el historial para el chatbot sin imágenes
|
56 |
def bot_response(
|
57 |
model_choice: str,
|
58 |
system_instruction: str,
|
59 |
text_prompt: str,
|
60 |
+
chatbot: list,
|
61 |
+
) -> Tuple[list, str]:
|
62 |
+
"""
|
63 |
+
Envía el mensaje al modelo, obtiene la respuesta y actualiza el historial.
|
64 |
+
"""
|
65 |
if not text_prompt.strip():
|
66 |
return chatbot, "Por favor, escribe un mensaje válido."
|
67 |
|
68 |
+
# Transformar el historial al formato que espera Gemini
|
69 |
+
transformed_history = transform_history(chatbot)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
+
# Configurar el modelo
|
72 |
+
chat_text_only.history = transformed_history
|
73 |
+
|
74 |
+
# Enviar el mensaje y obtener la respuesta
|
75 |
+
response = chat_text_only.send_message(text_prompt)
|
76 |
response.resolve()
|
77 |
|
78 |
+
# Obtener el texto generado por el modelo
|
79 |
+
generated_text = response.text
|
80 |
+
|
81 |
+
# Actualizar el historial con la pregunta y la respuesta
|
82 |
+
chatbot.append((text_prompt, generated_text))
|
83 |
+
|
84 |
return chatbot, ""
|
85 |
|
86 |
+
# Funciones para manejar el chatbot con imágenes
|
87 |
+
def preprocess_image(image: Image.Image) -> Optional[Image.Image]:
|
88 |
+
if image:
|
89 |
+
image_height = int(image.height * 512 / image.width)
|
90 |
+
return image.resize((512, image_height))
|
91 |
+
|
92 |
+
def cache_pil_image(image: Image.Image) -> str:
|
93 |
+
image_filename = f"{uuid.uuid4()}.jpeg"
|
94 |
+
os.makedirs("/tmp", exist_ok=True)
|
95 |
+
image_path = os.path.join("/tmp", image_filename)
|
96 |
+
image.save(image_path, "JPEG")
|
97 |
+
return image_path
|
98 |
+
|
99 |
+
def upload(files: Optional[List[str]], chatbot: list) -> list:
|
100 |
+
for file in files:
|
101 |
+
image = Image.open(file).convert('RGB')
|
102 |
+
image_preview = preprocess_image(image)
|
103 |
+
if image_preview:
|
104 |
+
gr.Image(image_preview).render()
|
105 |
+
image_path = cache_pil_image(image)
|
106 |
+
chatbot.append(((image_path,), None))
|
107 |
return chatbot
|
108 |
|
109 |
+
def user(text_prompt: str, chatbot: list):
|
110 |
+
if text_prompt:
|
111 |
+
chatbot.append((text_prompt, None))
|
112 |
+
return "", chatbot
|
113 |
+
|
114 |
+
def bot(
|
115 |
+
files: Optional[List[str]],
|
116 |
model_choice: str,
|
117 |
+
system_instruction: Optional[str],
|
118 |
+
chatbot: list
|
119 |
):
|
120 |
+
if not GOOGLE_API_KEY:
|
121 |
+
raise ValueError("GOOGLE_API_KEY is not set.")
|
122 |
+
|
123 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
124 |
+
generation_config = genai.types.GenerationConfig(
|
125 |
+
temperature=0.7,
|
126 |
+
max_output_tokens=8192,
|
127 |
+
top_k=10,
|
128 |
+
top_p=0.9
|
|
|
|
|
|
|
|
|
129 |
)
|
|
|
|
|
130 |
|
131 |
+
if not system_instruction:
|
132 |
+
system_instruction = "1"
|
|
|
|
|
|
|
133 |
|
134 |
+
text_prompt = [chatbot[-1][0]] if chatbot and chatbot[-1][0] and isinstance(chatbot[-1][0], str) else []
|
135 |
+
image_prompt = [preprocess_image(Image.open(file).convert('RGB')) for file in files] if files else []
|
136 |
|
137 |
+
model_with_images = genai.GenerativeModel(
|
138 |
+
model_name=model_choice,
|
139 |
+
generation_config=generation_config,
|
140 |
+
system_instruction=system_instruction
|
141 |
+
)
|
142 |
|
143 |
+
response = model_with_images.generate_content(text_prompt + image_prompt, stream=True, generation_config=generation_config)
|
|
|
|
|
|
|
|
|
144 |
|
145 |
+
chatbot[-1][1] = ""
|
146 |
+
for chunk in response:
|
147 |
+
for i in range(0, len(chunk.text), 10):
|
148 |
+
section = chunk.text[i:i + 10]
|
149 |
+
chatbot[-1][1] += section
|
150 |
+
time.sleep(0.01)
|
151 |
+
yield chatbot
|
|
|
|
|
|
|
|
|
|
|
152 |
|
153 |
+
# Interfaces
|
154 |
+
TITLE = """<h1 align="center">Gemini Playground ✨</h1>"""
|
155 |
+
SUBTITLE = """<h2 align="center">Play with Gemini Pro and Gemini Pro Vision</h2>"""
|
156 |
|
157 |
+
# Componentes comunes
|
158 |
+
chatbot_component_with_images = gr.Chatbot(label='Gemini with Images', scale=2, height=300)
|
159 |
+
chatbot_component_text_only = gr.Chatbot(label='Gemini Text Only', scale=2, height=300)
|
160 |
+
text_prompt_component = gr.Textbox(placeholder="Message...", show_label=False, autofocus=True, scale=8)
|
161 |
+
run_button_component = gr.Button(value="Run", variant="primary", scale=1)
|
162 |
+
upload_button_component = gr.UploadButton(label="Upload Images", file_count="multiple", file_types=["image"], scale=1)
|
163 |
+
model_choice_component = gr.Dropdown(
|
164 |
+
choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
|
165 |
+
value="gemini-1.5-flash",
|
166 |
+
label="Select Model",
|
167 |
+
scale=2
|
168 |
+
)
|
169 |
+
system_instruction_component = gr.Textbox(
|
170 |
+
placeholder="Enter system instruction...",
|
171 |
+
show_label=True,
|
172 |
+
scale=8
|
173 |
+
)
|
174 |
+
|
175 |
+
with gr.Blocks() as demo:
|
176 |
+
gr.HTML(TITLE)
|
177 |
+
gr.HTML(SUBTITLE)
|
178 |
+
with gr.Tabs():
|
179 |
+
with gr.TabItem("Chatbot with Images"):
|
180 |
+
with gr.Column():
|
181 |
+
model_choice_component.render()
|
182 |
+
chatbot_component_with_images.render()
|
183 |
+
with gr.Row():
|
184 |
+
text_prompt_component.render()
|
185 |
+
upload_button_component.render()
|
186 |
+
run_button_component.render()
|
187 |
+
with gr.Accordion("System Instruction", open=False):
|
188 |
+
system_instruction_component.render()
|
189 |
+
|
190 |
+
run_button_component.click(
|
191 |
+
fn=user,
|
192 |
+
inputs=[text_prompt_component, chatbot_component_with_images],
|
193 |
+
outputs=[text_prompt_component, chatbot_component_with_images],
|
194 |
+
queue=False
|
195 |
+
).then(
|
196 |
+
fn=bot,
|
197 |
+
inputs=[upload_button_component, model_choice_component, system_instruction_component, chatbot_component_with_images],
|
198 |
+
outputs=[chatbot_component_with_images],
|
199 |
)
|
200 |
|
201 |
+
upload_button_component.upload(
|
202 |
+
fn=upload,
|
203 |
+
inputs=[upload_button_component, chatbot_component_with_images],
|
204 |
+
outputs=[chatbot_component_with_images],
|
205 |
+
queue=False
|
|
|
|
|
|
|
|
|
|
|
206 |
)
|
207 |
|
208 |
+
with gr.TabItem("Chatbot Text Only"):
|
209 |
+
with gr.Column():
|
210 |
+
model_choice_component.render()
|
211 |
+
chatbot_component_text_only.render()
|
212 |
+
with gr.Row():
|
213 |
+
text_prompt_component.render()
|
214 |
+
run_button_component.render()
|
215 |
+
with gr.Accordion("System Instruction", open=False):
|
216 |
+
system_instruction_component.render()
|
217 |
+
|
218 |
+
run_button_component.click(
|
219 |
+
fn=bot_response,
|
220 |
+
inputs=[model_choice_component, system_instruction_component, text_prompt_component, chatbot_component_text_only],
|
221 |
+
outputs=[chatbot_component_text_only, text_prompt_component],
|
222 |
)
|
223 |
|
224 |
+
text_prompt_component.submit(
|
225 |
+
fn=bot_response,
|
226 |
+
inputs=[model_choice_component, system_instruction_component, text_prompt_component, chatbot_component_text_only],
|
227 |
+
outputs=[chatbot_component_text_only, text_prompt_component],
|
228 |
+
)
|
229 |
|
230 |
+
demo.queue(max_size=99).launch(debug=True, show_error=True)
|
|
|
|