Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,126 +3,148 @@ SUBTITLE = """<h2 align="center">Play with Gemini Pro and Gemini Pro Vision</h2>
|
|
3 |
|
4 |
import os
|
5 |
import time
|
6 |
-
import uuid
|
7 |
from typing import List, Tuple, Optional, Union
|
8 |
|
9 |
import google.generativeai as genai
|
10 |
import gradio as gr
|
11 |
-
from PIL import Image
|
12 |
from dotenv import load_dotenv
|
13 |
|
14 |
# Cargar las variables de entorno desde el archivo .env
|
15 |
load_dotenv()
|
16 |
|
17 |
-
print("google-generativeai:", genai.__version__)
|
18 |
-
|
19 |
# Obtener la clave de la API de las variables de entorno
|
20 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
21 |
-
|
22 |
-
# Verificar que la clave de la API est茅 configurada
|
23 |
if not GOOGLE_API_KEY:
|
24 |
raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
|
25 |
|
|
|
|
|
26 |
IMAGE_WIDTH = 512
|
27 |
-
CHAT_HISTORY = List[Tuple[Optional[
|
28 |
-
|
29 |
-
|
30 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
chatbot.append((text_prompt, None))
|
32 |
return "", chatbot
|
33 |
|
34 |
-
|
|
|
35 |
model_choice: str,
|
36 |
-
system_instruction: Optional[str],
|
37 |
-
chatbot: CHAT_HISTORY
|
38 |
):
|
|
|
|
|
|
|
|
|
|
|
39 |
if not GOOGLE_API_KEY:
|
40 |
raise ValueError("GOOGLE_API_KEY is not set.")
|
41 |
|
42 |
-
|
43 |
-
generation_config = genai.types.GenerationConfig(
|
44 |
-
temperature=0.7,
|
45 |
-
max_output_tokens=8192,
|
46 |
-
top_k=10,
|
47 |
-
top_p=0.9
|
48 |
-
)
|
49 |
-
|
50 |
-
# Usar el valor por defecto para system_instruction si est谩 vac铆o
|
51 |
-
if not system_instruction:
|
52 |
-
system_instruction = "1" # O puedes poner un valor predeterminado como "No system instruction provided."
|
53 |
-
|
54 |
-
text_prompt = [chatbot[-1][0]] if chatbot and chatbot[-1][0] and isinstance(chatbot[-1][0], str) else []
|
55 |
-
|
56 |
model = genai.GenerativeModel(
|
57 |
model_name=model_choice,
|
58 |
generation_config=generation_config,
|
59 |
-
system_instruction=system_instruction
|
60 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
61 |
|
62 |
-
|
|
|
63 |
|
64 |
-
|
65 |
-
for
|
66 |
-
|
67 |
-
|
68 |
-
chatbot[-1][1] += section
|
69 |
-
time.sleep(0.01)
|
70 |
-
yield chatbot
|
71 |
|
72 |
-
# Componente para el acorde贸n que contiene el cuadro de texto para la instrucci贸n del sistema
|
73 |
-
system_instruction_component = gr.Textbox(
|
74 |
-
placeholder="Enter system instruction...",
|
75 |
-
show_label=True,
|
76 |
-
scale=8
|
77 |
-
)
|
78 |
|
79 |
-
#
|
80 |
-
chatbot_component = gr.Chatbot(label=
|
81 |
-
|
82 |
-
|
83 |
-
model_choice_component = gr.Dropdown(
|
84 |
choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
|
85 |
-
value=
|
86 |
-
label="
|
87 |
-
scale=2
|
88 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
89 |
|
90 |
-
|
91 |
-
bot_inputs = [model_choice_component, system_instruction_component, chatbot_component]
|
92 |
-
|
93 |
-
# Definir la interfaz de usuario
|
94 |
with gr.Blocks() as demo:
|
95 |
gr.HTML(TITLE)
|
96 |
gr.HTML(SUBTITLE)
|
97 |
with gr.Column():
|
98 |
-
|
99 |
-
model_choice_component.render()
|
100 |
chatbot_component.render()
|
101 |
with gr.Row():
|
102 |
-
|
103 |
run_button_component.render()
|
104 |
-
|
105 |
-
# Crear el acorde贸n para la instrucci贸n del sistema al final
|
106 |
-
with gr.Accordion("System Instruction", open=False): # Acorde贸n cerrado por defecto
|
107 |
system_instruction_component.render()
|
108 |
|
|
|
109 |
run_button_component.click(
|
110 |
-
|
111 |
-
inputs=
|
112 |
-
outputs=[
|
113 |
-
queue=False
|
114 |
).then(
|
115 |
-
|
|
|
|
|
116 |
)
|
117 |
|
118 |
-
|
119 |
-
|
120 |
-
inputs=
|
121 |
-
outputs=[
|
122 |
-
queue=False
|
123 |
).then(
|
124 |
-
|
|
|
|
|
125 |
)
|
126 |
|
127 |
# Lanzar la aplicaci贸n
|
128 |
-
demo.queue(max_size=99).launch(debug=
|
|
|
3 |
|
4 |
import os
|
5 |
import time
|
|
|
6 |
from typing import List, Tuple, Optional, Union
|
7 |
|
8 |
import google.generativeai as genai
|
9 |
import gradio as gr
|
|
|
10 |
from dotenv import load_dotenv
|
11 |
|
12 |
# Cargar las variables de entorno desde el archivo .env
|
13 |
load_dotenv()
|
14 |
|
|
|
|
|
15 |
# Obtener la clave de la API de las variables de entorno
|
16 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
|
|
|
|
17 |
if not GOOGLE_API_KEY:
|
18 |
raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
|
19 |
|
20 |
+
# Configuraci贸n global
|
21 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
22 |
IMAGE_WIDTH = 512
|
23 |
+
CHAT_HISTORY = List[Tuple[Optional[str], Optional[str]]]
|
24 |
+
|
25 |
+
# Inicializar el modelo y la sesi贸n de chat
|
26 |
+
model_name_default = "gemini-1.5-flash"
|
27 |
+
generation_config = genai.types.GenerationConfig(
|
28 |
+
temperature=0.7,
|
29 |
+
max_output_tokens=8192,
|
30 |
+
top_k=10,
|
31 |
+
top_p=0.9
|
32 |
+
)
|
33 |
+
model = genai.GenerativeModel(model_name=model_name_default, generation_config=generation_config)
|
34 |
+
chat = model.start_chat(history=[])
|
35 |
+
|
36 |
+
|
37 |
+
def transform_history(history: CHAT_HISTORY):
|
38 |
+
"""
|
39 |
+
Transforma el historial del formato Gradio al formato esperado por Gemini.
|
40 |
+
"""
|
41 |
+
new_history = []
|
42 |
+
for user_input, model_response in history:
|
43 |
+
if user_input:
|
44 |
+
new_history.append({"parts": [{"text": user_input}], "role": "user"})
|
45 |
+
if model_response:
|
46 |
+
new_history.append({"parts": [{"text": model_response}], "role": "model"})
|
47 |
+
return new_history
|
48 |
+
|
49 |
+
|
50 |
+
def user_input_handler(text_prompt: str, chatbot: CHAT_HISTORY):
|
51 |
+
"""
|
52 |
+
Agrega la entrada del usuario al historial y retorna la interfaz actualizada.
|
53 |
+
"""
|
54 |
+
if text_prompt.strip():
|
55 |
chatbot.append((text_prompt, None))
|
56 |
return "", chatbot
|
57 |
|
58 |
+
|
59 |
+
def bot_response_handler(
|
60 |
model_choice: str,
|
61 |
+
system_instruction: Optional[str],
|
62 |
+
chatbot: CHAT_HISTORY,
|
63 |
):
|
64 |
+
"""
|
65 |
+
Genera la respuesta del modelo basado en el historial y devuelve la interfaz actualizada.
|
66 |
+
"""
|
67 |
+
global chat
|
68 |
+
|
69 |
if not GOOGLE_API_KEY:
|
70 |
raise ValueError("GOOGLE_API_KEY is not set.")
|
71 |
|
72 |
+
# Configurar el modelo y la instrucci贸n del sistema
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
73 |
model = genai.GenerativeModel(
|
74 |
model_name=model_choice,
|
75 |
generation_config=generation_config,
|
76 |
+
system_instruction=system_instruction or "Default instruction"
|
77 |
)
|
78 |
+
|
79 |
+
# Transformar el historial para la sesi贸n del chat
|
80 |
+
chat.history = transform_history(chatbot)
|
81 |
+
|
82 |
+
# Obtener el mensaje m谩s reciente
|
83 |
+
user_message = chatbot[-1][0] if chatbot and chatbot[-1][0] else ""
|
84 |
+
|
85 |
+
# Enviar el mensaje y procesar la respuesta
|
86 |
+
response = chat.send_message(user_message)
|
87 |
+
response.resolve()
|
88 |
|
89 |
+
# Actualizar el historial con la respuesta del modelo
|
90 |
+
chatbot[-1] = (user_message, response.text)
|
91 |
|
92 |
+
# Devolver la respuesta por fragmentos para simular la experiencia de escritura
|
93 |
+
for i in range(len(response.text)):
|
94 |
+
time.sleep(0.01)
|
95 |
+
yield chatbot
|
|
|
|
|
|
|
96 |
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
+
# Componentes de la interfaz
|
99 |
+
chatbot_component = gr.Chatbot(label="Gemini Chat", height=400)
|
100 |
+
text_input_component = gr.Textbox(placeholder="Escribe tu mensaje aqu铆...", show_label=False)
|
101 |
+
model_dropdown_component = gr.Dropdown(
|
|
|
102 |
choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
|
103 |
+
value=model_name_default,
|
104 |
+
label="Selecciona el modelo",
|
|
|
105 |
)
|
106 |
+
system_instruction_component = gr.Textbox(
|
107 |
+
placeholder="Instrucci贸n para el modelo...",
|
108 |
+
label="System Instruction",
|
109 |
+
optional=True,
|
110 |
+
)
|
111 |
+
run_button_component = gr.Button("Enviar")
|
112 |
|
113 |
+
# Layout de la interfaz
|
|
|
|
|
|
|
114 |
with gr.Blocks() as demo:
|
115 |
gr.HTML(TITLE)
|
116 |
gr.HTML(SUBTITLE)
|
117 |
with gr.Column():
|
118 |
+
model_dropdown_component.render()
|
|
|
119 |
chatbot_component.render()
|
120 |
with gr.Row():
|
121 |
+
text_input_component.render()
|
122 |
run_button_component.render()
|
123 |
+
with gr.Accordion("System Instruction", open=False):
|
|
|
|
|
124 |
system_instruction_component.render()
|
125 |
|
126 |
+
# Conexiones de eventos
|
127 |
run_button_component.click(
|
128 |
+
user_input_handler,
|
129 |
+
inputs=[text_input_component, chatbot_component],
|
130 |
+
outputs=[text_input_component, chatbot_component],
|
131 |
+
queue=False,
|
132 |
).then(
|
133 |
+
bot_response_handler,
|
134 |
+
inputs=[model_dropdown_component, system_instruction_component, chatbot_component],
|
135 |
+
outputs=[chatbot_component],
|
136 |
)
|
137 |
|
138 |
+
text_input_component.submit(
|
139 |
+
user_input_handler,
|
140 |
+
inputs=[text_input_component, chatbot_component],
|
141 |
+
outputs=[text_input_component, chatbot_component],
|
142 |
+
queue=False,
|
143 |
).then(
|
144 |
+
bot_response_handler,
|
145 |
+
inputs=[model_dropdown_component, system_instruction_component, chatbot_component],
|
146 |
+
outputs=[chatbot_component],
|
147 |
)
|
148 |
|
149 |
# Lanzar la aplicaci贸n
|
150 |
+
demo.queue(max_size=99).launch(debug=True, show_error=True)
|