Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,7 +3,7 @@ SUBTITLE = """<h2 align="center">Play with Gemini Pro and Gemini Pro Vision</h2>
|
|
3 |
|
4 |
import os
|
5 |
import time
|
6 |
-
from typing import
|
7 |
|
8 |
import google.generativeai as genai
|
9 |
import gradio as gr
|
@@ -12,105 +12,70 @@ from dotenv import load_dotenv
|
|
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
|
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
|
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 |
-
|
63 |
):
|
64 |
"""
|
65 |
-
|
66 |
"""
|
67 |
-
|
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 "
|
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
|
100 |
-
text_input_component = gr.Textbox(placeholder="Escribe
|
|
|
101 |
model_dropdown_component = gr.Dropdown(
|
102 |
choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
|
103 |
-
value=
|
104 |
label="Selecciona el modelo",
|
|
|
105 |
)
|
106 |
system_instruction_component = gr.Textbox(
|
107 |
-
placeholder="
|
108 |
-
label="
|
109 |
-
|
|
|
110 |
)
|
111 |
-
run_button_component = gr.Button("Enviar")
|
112 |
|
113 |
-
#
|
114 |
with gr.Blocks() as demo:
|
115 |
gr.HTML(TITLE)
|
116 |
gr.HTML(SUBTITLE)
|
@@ -120,31 +85,22 @@ with gr.Blocks() as demo:
|
|
120 |
with gr.Row():
|
121 |
text_input_component.render()
|
122 |
run_button_component.render()
|
123 |
-
with gr.Accordion("
|
124 |
system_instruction_component.render()
|
125 |
|
126 |
-
#
|
127 |
run_button_component.click(
|
128 |
-
|
129 |
-
inputs=[
|
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 |
-
|
140 |
-
inputs=[
|
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 |
-
|
|
|
|
3 |
|
4 |
import os
|
5 |
import time
|
6 |
+
from typing import Optional
|
7 |
|
8 |
import google.generativeai as genai
|
9 |
import gradio as gr
|
|
|
12 |
# Cargar las variables de entorno desde el archivo .env
|
13 |
load_dotenv()
|
14 |
|
15 |
+
print("google-generativeai:", genai.__version__)
|
16 |
+
|
17 |
# Obtener la clave de la API de las variables de entorno
|
18 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
19 |
+
|
20 |
+
# Verificar que la clave de la API est茅 configurada
|
21 |
if not GOOGLE_API_KEY:
|
22 |
raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
|
23 |
|
24 |
+
# Configuraci贸n del modelo Gemini
|
25 |
genai.configure(api_key=GOOGLE_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
26 |
generation_config = genai.types.GenerationConfig(
|
27 |
temperature=0.7,
|
28 |
max_output_tokens=8192,
|
29 |
top_k=10,
|
30 |
top_p=0.9
|
31 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
32 |
|
33 |
+
# Funci贸n para manejar las respuestas del modelo
|
34 |
+
def bot_response(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
35 |
model_choice: str,
|
36 |
system_instruction: Optional[str],
|
37 |
+
text_prompt: str,
|
38 |
):
|
39 |
"""
|
40 |
+
Env铆a el mensaje al modelo y obtiene la respuesta.
|
41 |
"""
|
42 |
+
if not text_prompt.strip():
|
43 |
+
return None, "Por favor, escribe un mensaje v谩lido."
|
|
|
|
|
44 |
|
|
|
45 |
model = genai.GenerativeModel(
|
46 |
model_name=model_choice,
|
47 |
generation_config=generation_config,
|
48 |
+
system_instruction=system_instruction or "You are an assistant."
|
49 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
|
51 |
+
response = model.generate_content([text_prompt], stream=True, generation_config=generation_config)
|
52 |
+
generated_text = ""
|
53 |
+
|
54 |
+
for chunk in response:
|
55 |
+
for i in range(0, len(chunk.text), 10): # Mostrar texto en partes
|
56 |
+
section = chunk.text[i:i + 10]
|
57 |
+
generated_text += section
|
58 |
+
time.sleep(0.01)
|
59 |
+
yield text_prompt, generated_text
|
60 |
|
61 |
# Componentes de la interfaz
|
62 |
+
chatbot_component = gr.Chatbot(label="Gemini", scale=2, height=300)
|
63 |
+
text_input_component = gr.Textbox(placeholder="Escribe un mensaje...", show_label=False, scale=8)
|
64 |
+
run_button_component = gr.Button(value="Enviar", variant="primary", scale=1)
|
65 |
model_dropdown_component = gr.Dropdown(
|
66 |
choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
|
67 |
+
value="gemini-1.5-flash",
|
68 |
label="Selecciona el modelo",
|
69 |
+
scale=2
|
70 |
)
|
71 |
system_instruction_component = gr.Textbox(
|
72 |
+
placeholder="Escribe una instrucci贸n para el sistema...",
|
73 |
+
label="Instrucci贸n del sistema",
|
74 |
+
scale=8,
|
75 |
+
value="You are an assistant."
|
76 |
)
|
|
|
77 |
|
78 |
+
# Definir la interfaz
|
79 |
with gr.Blocks() as demo:
|
80 |
gr.HTML(TITLE)
|
81 |
gr.HTML(SUBTITLE)
|
|
|
85 |
with gr.Row():
|
86 |
text_input_component.render()
|
87 |
run_button_component.render()
|
88 |
+
with gr.Accordion("Instrucci贸n del sistema", open=False):
|
89 |
system_instruction_component.render()
|
90 |
|
91 |
+
# Configurar eventos
|
92 |
run_button_component.click(
|
93 |
+
fn=bot_response,
|
94 |
+
inputs=[model_dropdown_component, system_instruction_component, text_input_component],
|
|
|
|
|
|
|
|
|
|
|
95 |
outputs=[chatbot_component],
|
96 |
)
|
97 |
|
98 |
text_input_component.submit(
|
99 |
+
fn=bot_response,
|
100 |
+
inputs=[model_dropdown_component, system_instruction_component, text_input_component],
|
|
|
|
|
|
|
|
|
|
|
101 |
outputs=[chatbot_component],
|
102 |
)
|
103 |
|
104 |
# Lanzar la aplicaci贸n
|
105 |
+
if __name__ == "__main__":
|
106 |
+
demo.queue(max_size=99).launch(debug=True, show_error=True)
|