JeCabrera commited on
Commit
544ecfa
·
verified ·
1 Parent(s): c163d83

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -125
app.py CHANGED
@@ -1,128 +1,42 @@
1
- TITLE = """<h1 align="center">Gemini Playground ✨</h1>"""
2
- 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
- from PIL import Image
9
- import google.generativeai as genai
10
  import gradio as gr
11
- from dotenv import load_dotenv
12
-
13
- # Cargar las variables de entorno desde el archivo .env
14
- load_dotenv()
15
-
16
- print("google-generativeai:", genai.__version__)
17
-
18
- # Obtener la clave de la API de las variables de entorno
19
- GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
20
-
21
- # Verificar que la clave de la API esté configurada
22
- if not GOOGLE_API_KEY:
23
- raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
24
-
25
- # Configuración del modelo Gemini
26
- generation_config = {
27
- "temperature": 1,
28
- "top_p": 0.95,
29
- "top_k": 40,
30
- "max_output_tokens": 8192,
31
- "response_mime_type": "text/plain",
32
- }
33
-
34
- genai.configure(api_key=GOOGLE_API_KEY)
35
-
36
- model = genai.GenerativeModel(
37
- model_name="gemini-1.5-flash",
38
- generation_config=generation_config
39
- )
40
-
41
- # Inicializar la sesión de chat
42
- chat = model.start_chat(history=[])
43
-
44
- # Función para transformar el historial de Gradio al formato de Gemini
45
- def transform_history(history):
46
- new_history = []
47
- for chat_entry in history:
48
- new_history.append({"parts": [{"text": chat_entry[0]}], "role": "user"})
49
- new_history.append({"parts": [{"text": chat_entry[1]}], "role": "model"})
50
- return new_history
51
-
52
- # Función de respuesta que maneja el historial
53
- def bot_response(
54
- model_choice: str,
55
- system_instruction: str,
56
- text_prompt: str,
57
- chatbot: list,
58
- ) -> Tuple[list, str]:
59
- """
60
- Envía el mensaje al modelo, obtiene la respuesta y actualiza el historial.
61
- """
62
- if not text_prompt.strip():
63
- return chatbot, "Por favor, escribe un mensaje válido."
64
 
65
- # Transformar el historial al formato que espera Gemini
66
- transformed_history = transform_history(chatbot)
67
-
68
- # Configurar el modelo
69
- chat.history = transformed_history
70
-
71
- # Enviar el mensaje y obtener la respuesta
72
- response = chat.send_message(text_prompt)
73
- response.resolve()
74
-
75
- # Obtener el texto generado por el modelo
76
- generated_text = response.text
77
-
78
- # Actualizar el historial con la pregunta y la respuesta
79
- chatbot.append((text_prompt, generated_text))
80
-
81
- return chatbot, ""
82
-
83
- # Componentes de la interfaz
84
- chatbot_component = gr.Chatbot(label="Gemini", scale=2, height=300)
85
- text_input_component = gr.Textbox(placeholder="Escribe un mensaje...", show_label=False, scale=8)
86
- run_button_component = gr.Button(value="Enviar", variant="primary", scale=1)
87
- model_dropdown_component = gr.Dropdown(
88
- choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
89
- value="gemini-1.5-flash",
90
- label="Selecciona el modelo",
91
- scale=2
92
- )
93
- system_instruction_component = gr.Textbox(
94
- placeholder="Escribe una instrucción para el sistema...",
95
- label="Instrucción del sistema",
96
- scale=8,
97
- value="You are an assistant."
98
- )
99
-
100
- # Definir la interfaz
101
- with gr.Blocks() as demo:
102
- gr.HTML(TITLE)
103
- gr.HTML(SUBTITLE)
104
- with gr.Column():
105
- model_dropdown_component.render()
106
- chatbot_component.render()
107
  with gr.Row():
108
- text_input_component.render()
109
- run_button_component.render()
110
- with gr.Accordion("Instrucción del sistema", open=False):
111
- system_instruction_component.render()
112
-
113
- # Configurar eventos
114
- run_button_component.click(
115
- fn=bot_response,
116
- inputs=[model_dropdown_component, system_instruction_component, text_input_component, chatbot_component],
117
- outputs=[chatbot_component, text_input_component],
118
- )
119
-
120
- text_input_component.submit(
121
- fn=bot_response,
122
- inputs=[model_dropdown_component, system_instruction_component, text_input_component, chatbot_component],
123
- outputs=[chatbot_component, text_input_component],
124
- )
125
-
126
- # Lanzar la aplicación
127
- if __name__ == "__main__":
128
- demo.queue(max_size=99).launch(debug=True, show_error=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import gemini_gradio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
+ with gr.Blocks(fill_height=True) as demo:
5
+
6
+ gr.Markdown("**Note:** You need to use a SambaNova API key from [SambaNova Cloud](https://cloud.sambanova.ai/).")
7
+ with gr.Tab("Gemini"):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  with gr.Row():
9
+ gemini_model = gr.Dropdown(
10
+ choices=[
11
+ 'gemini-1.5-flash', # Fast and versatile performance
12
+ 'gemini-1.5-flash-8b', # High volume, lower intelligence tasks
13
+ 'gemini-1.5-pro', # Complex reasoning tasks
14
+ 'gemini-exp-1114' # Quality improvements
15
+ ],
16
+ value='gemini-1.5-pro', # Default to the most advanced model
17
+ label="Select Gemini Model",
18
+ interactive=True
19
+ )
20
+
21
+ gemini_interface = gr.load(
22
+ name=gemini_model.value,
23
+ src=gemini_gradio.registry,
24
+ fill_height=True,
25
+ chatbot=gr.Chatbot(height=250, type="messages")
26
+ )
27
+
28
+ def update_gemini_model(new_model):
29
+ return gr.load(
30
+ name=new_model,
31
+ src=gemini_gradio.registry,
32
+ fill_height=True,
33
+ chatbot=gr.Chatbot(height=250, type="messages")
34
+ )
35
+
36
+ gemini_model.change(
37
+ fn=update_gemini_model,
38
+ inputs=[gemini_model],
39
+ outputs=[gemini_interface]
40
+ )
41
+
42
+ demo.launch(ssr_mode=False)