Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -3,8 +3,7 @@ SUBTITLE = """<h2 align="center">Play with Gemini Pro and Gemini Pro Vision</h2>
|
|
3 |
|
4 |
import os
|
5 |
import time
|
6 |
-
import
|
7 |
-
from typing import List, Tuple, Optional, Union
|
8 |
|
9 |
import google.generativeai as genai
|
10 |
import gradio as gr
|
@@ -18,145 +17,135 @@ 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 |
-
|
|
|
|
|
|
|
|
|
27 |
IMAGE_WIDTH = 512
|
28 |
-
CHAT_HISTORY = List[Tuple[Optional[
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
def bot(
|
58 |
files: Optional[List[str]],
|
59 |
model_choice: str,
|
60 |
-
system_instruction:
|
61 |
-
chatbot: CHAT_HISTORY
|
62 |
):
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
genai.configure(api_key=GOOGLE_API_KEY)
|
67 |
-
generation_config = genai.types.GenerationConfig(
|
68 |
-
temperature=0.7,
|
69 |
-
max_output_tokens=8192,
|
70 |
-
top_k=10,
|
71 |
-
top_p=0.9
|
72 |
-
)
|
73 |
|
74 |
-
#
|
75 |
-
if
|
76 |
-
|
77 |
-
|
78 |
-
text_prompt = [chatbot[-1][0]] if chatbot and chatbot[-1][0] and isinstance(chatbot[-1][0], str) else []
|
79 |
-
image_prompt = [preprocess_image(Image.open(file).convert('RGB')) for file in files] if files else []
|
80 |
-
|
81 |
-
model = genai.GenerativeModel(
|
82 |
-
model_name=model_choice,
|
83 |
-
generation_config=generation_config,
|
84 |
-
system_instruction=system_instruction # Usar el valor por defecto si est谩 vac铆o
|
85 |
-
)
|
86 |
|
87 |
-
|
|
|
88 |
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
94 |
time.sleep(0.01)
|
95 |
yield chatbot
|
96 |
|
97 |
-
#
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
|
|
109 |
model_choice_component = gr.Dropdown(
|
110 |
choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
|
111 |
value="gemini-1.5-flash",
|
112 |
label="Select Model",
|
113 |
-
scale=2
|
114 |
)
|
|
|
115 |
|
116 |
-
user_inputs = [text_prompt_component, chatbot_component]
|
117 |
-
bot_inputs = [upload_button_component, model_choice_component, system_instruction_component, chatbot_component]
|
118 |
|
119 |
-
#
|
120 |
with gr.Blocks() as demo:
|
121 |
gr.HTML(TITLE)
|
122 |
gr.HTML(SUBTITLE)
|
123 |
-
with gr.
|
124 |
-
# Campo de selecci贸n de modelo arriba
|
125 |
model_choice_component.render()
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
# Crear el acorde贸n para la instrucci贸n del sistema al final
|
133 |
-
with gr.Accordion("System Instruction", open=False): # Acorde贸n cerrado por defecto
|
134 |
-
system_instruction_component.render()
|
135 |
|
136 |
run_button_component.click(
|
137 |
-
fn=
|
138 |
-
inputs=
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
|
|
|
|
|
|
143 |
)
|
144 |
|
145 |
text_prompt_component.submit(
|
146 |
-
fn=
|
147 |
-
inputs=
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
upload_button_component.upload(
|
155 |
-
fn=upload,
|
156 |
-
inputs=[upload_button_component, chatbot_component],
|
157 |
outputs=[chatbot_component],
|
158 |
-
queue=False
|
159 |
)
|
160 |
|
161 |
# Lanzar la aplicaci贸n
|
162 |
-
demo.queue(max_size=99).launch(debug=
|
|
|
3 |
|
4 |
import os
|
5 |
import time
|
6 |
+
from typing import List, Tuple, Optional
|
|
|
7 |
|
8 |
import google.generativeai as genai
|
9 |
import gradio as gr
|
|
|
17 |
|
18 |
# Obtener la clave de la API de las variables de entorno
|
19 |
GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
|
|
|
|
|
20 |
if not GOOGLE_API_KEY:
|
21 |
raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
|
22 |
|
23 |
+
# Configurar la API de Google Generative AI
|
24 |
+
genai.configure(api_key=GOOGLE_API_KEY)
|
25 |
+
|
26 |
+
# Variables globales
|
27 |
+
chat = None # Sesi贸n de chat
|
28 |
IMAGE_WIDTH = 512
|
29 |
+
CHAT_HISTORY = List[Tuple[Optional[str], Optional[str]]]
|
30 |
+
|
31 |
+
|
32 |
+
def preprocess_image(image: Image.Image) -> str:
|
33 |
+
"""Preprocesar la imagen y convertirla a texto descriptivo."""
|
34 |
+
return "Image processed successfully."
|
35 |
+
|
36 |
+
|
37 |
+
def transform_history(history: CHAT_HISTORY) -> List[dict]:
|
38 |
+
"""Transformar el historial de Gradio al formato requerido por Gemini."""
|
39 |
+
transformed = []
|
40 |
+
for user_msg, model_msg in history:
|
41 |
+
if user_msg:
|
42 |
+
transformed.append({"role": "user", "content": user_msg})
|
43 |
+
if model_msg:
|
44 |
+
transformed.append({"role": "model", "content": model_msg})
|
45 |
+
return transformed
|
46 |
+
|
47 |
+
|
48 |
+
def initialize_chat(model_name: str):
|
49 |
+
"""Inicializar una sesi贸n de chat con el modelo seleccionado."""
|
50 |
+
global chat
|
51 |
+
model = genai.GenerativeModel(model_name=model_name)
|
52 |
+
chat = model.start_chat(history=[])
|
53 |
+
|
54 |
+
|
55 |
+
def bot_with_logic(
|
56 |
+
text_prompt: str,
|
|
|
|
|
57 |
files: Optional[List[str]],
|
58 |
model_choice: str,
|
59 |
+
system_instruction: str,
|
60 |
+
chatbot: CHAT_HISTORY,
|
61 |
):
|
62 |
+
"""L贸gica del chatbot para manejar texto, im谩genes o ambos."""
|
63 |
+
global chat
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
64 |
|
65 |
+
# Inicializar la sesi贸n de chat si no existe
|
66 |
+
if chat is None:
|
67 |
+
initialize_chat(model_choice)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
+
# Configurar la instrucci贸n del sistema
|
70 |
+
chat.system_instruction = system_instruction or "You are a helpful assistant."
|
71 |
|
72 |
+
# Caso 1: Solo texto
|
73 |
+
if text_prompt and not files:
|
74 |
+
response = chat.send_message(text_prompt)
|
75 |
+
response.resolve()
|
76 |
+
|
77 |
+
chatbot.append((text_prompt, ""))
|
78 |
+
for i in range(len(response.text)):
|
79 |
+
chatbot[-1] = (text_prompt, response.text[: i + 1])
|
80 |
time.sleep(0.01)
|
81 |
yield chatbot
|
82 |
|
83 |
+
# Caso 2: Solo im谩genes o texto + im谩genes
|
84 |
+
elif files:
|
85 |
+
image_descriptions = [preprocess_image(Image.open(file)) for file in files]
|
86 |
+
combined_prompt = f"{text_prompt}\n" + "\n".join(image_descriptions) if text_prompt else "\n".join(
|
87 |
+
image_descriptions
|
88 |
+
)
|
89 |
+
|
90 |
+
response = chat.send_message(combined_prompt)
|
91 |
+
response.resolve()
|
92 |
+
|
93 |
+
chatbot.append((text_prompt or "[Images Uploaded]", ""))
|
94 |
+
for i in range(len(response.text)):
|
95 |
+
chatbot[-1] = (text_prompt or "[Images Uploaded]", response.text[: i + 1])
|
96 |
+
time.sleep(0.01)
|
97 |
+
yield chatbot
|
98 |
|
99 |
+
|
100 |
+
# Componentes de Gradio
|
101 |
+
chatbot_component = gr.Chatbot(label="Gemini Chat", height=400)
|
102 |
+
text_prompt_component = gr.Textbox(placeholder="Enter your message here...", show_label=False)
|
103 |
+
upload_button_component = gr.UploadButton(label="Upload Images", file_count="multiple", file_types=["image"])
|
104 |
+
run_button_component = gr.Button(value="Run", variant="primary")
|
105 |
model_choice_component = gr.Dropdown(
|
106 |
choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
|
107 |
value="gemini-1.5-flash",
|
108 |
label="Select Model",
|
|
|
109 |
)
|
110 |
+
system_instruction_component = gr.Textbox(placeholder="Enter system instruction...", label="System Instruction")
|
111 |
|
|
|
|
|
112 |
|
113 |
+
# Crear la interfaz
|
114 |
with gr.Blocks() as demo:
|
115 |
gr.HTML(TITLE)
|
116 |
gr.HTML(SUBTITLE)
|
117 |
+
with gr.Row():
|
|
|
118 |
model_choice_component.render()
|
119 |
+
chatbot_component.render()
|
120 |
+
with gr.Row():
|
121 |
+
text_prompt_component.render()
|
122 |
+
upload_button_component.render()
|
123 |
+
run_button_component.render()
|
124 |
+
system_instruction_component.render()
|
|
|
|
|
|
|
125 |
|
126 |
run_button_component.click(
|
127 |
+
fn=bot_with_logic,
|
128 |
+
inputs=[
|
129 |
+
text_prompt_component,
|
130 |
+
upload_button_component,
|
131 |
+
model_choice_component,
|
132 |
+
system_instruction_component,
|
133 |
+
chatbot_component,
|
134 |
+
],
|
135 |
+
outputs=[chatbot_component],
|
136 |
)
|
137 |
|
138 |
text_prompt_component.submit(
|
139 |
+
fn=bot_with_logic,
|
140 |
+
inputs=[
|
141 |
+
text_prompt_component,
|
142 |
+
upload_button_component,
|
143 |
+
model_choice_component,
|
144 |
+
system_instruction_component,
|
145 |
+
chatbot_component,
|
146 |
+
],
|
|
|
|
|
|
|
147 |
outputs=[chatbot_component],
|
|
|
148 |
)
|
149 |
|
150 |
# Lanzar la aplicaci贸n
|
151 |
+
demo.queue(max_size=99).launch(debug=True, show_error=True)
|