JeCabrera commited on
Commit
b2b0e4b
·
verified ·
1 Parent(s): fabf5df

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -35
app.py CHANGED
@@ -1,6 +1,3 @@
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
@@ -11,22 +8,21 @@ 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_CACHE_DIRECTORY = "/tmp"
27
  IMAGE_WIDTH = 512
28
  CHAT_HISTORY = List[Tuple[Optional[Union[Tuple[str], str]], Optional[str]]]
29
 
 
 
 
 
30
  def preprocess_image(image: Image.Image) -> Optional[Image.Image]:
31
  if image:
32
  image_height = int(image.height * IMAGE_WIDTH / image.width)
@@ -39,6 +35,16 @@ def cache_pil_image(image: Image.Image) -> str:
39
  image.save(image_path, "JPEG")
40
  return image_path
41
 
 
 
 
 
 
 
 
 
 
 
42
  def upload(files: Optional[List[str]], chatbot: CHAT_HISTORY) -> CHAT_HISTORY:
43
  for file in files:
44
  image = Image.open(file).convert('RGB')
@@ -57,7 +63,7 @@ def user(text_prompt: str, chatbot: CHAT_HISTORY):
57
  def bot(
58
  files: Optional[List[str]],
59
  model_choice: str,
60
- system_instruction: Optional[str], # Sistema de instrucciones opcional
61
  chatbot: CHAT_HISTORY
62
  ):
63
  if not GOOGLE_API_KEY:
@@ -71,37 +77,31 @@ def bot(
71
  top_p=0.9
72
  )
73
 
74
- # Usar el valor por defecto para system_instruction si está vacío
75
  if not system_instruction:
76
- system_instruction = "1" # O puedes poner un valor predeterminado como "No system instruction provided."
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
- response = model.generate_content(text_prompt + image_prompt, stream=True, generation_config=generation_config)
 
 
 
88
 
89
- chatbot[-1][1] = ""
90
  for chunk in response:
91
  for i in range(0, len(chunk.text), 10):
92
  section = chunk.text[i:i + 10]
93
- chatbot[-1][1] += section
94
  time.sleep(0.01)
95
  yield chatbot
96
 
97
- # Componente para el acordeón que contiene el cuadro de texto para la instrucción del sistema
98
  system_instruction_component = gr.Textbox(
99
  placeholder="Enter system instruction...",
100
  show_label=True,
101
  scale=8
102
  )
103
 
104
- # Definir los componentes de entrada y salida
105
  chatbot_component = gr.Chatbot(label='Gemini', bubble_full_width=False, scale=2, height=300)
106
  text_prompt_component = gr.Textbox(placeholder="Message...", show_label=False, autofocus=True, scale=8)
107
  upload_button_component = gr.UploadButton(label="Upload Images", file_count="multiple", file_types=["image"], scale=1)
@@ -116,21 +116,17 @@ model_choice_component = gr.Dropdown(
116
  user_inputs = [text_prompt_component, chatbot_component]
117
  bot_inputs = [upload_button_component, model_choice_component, system_instruction_component, chatbot_component]
118
 
119
- # Definir la interfaz de usuario
120
  with gr.Blocks() as demo:
121
  gr.HTML(TITLE)
122
  gr.HTML(SUBTITLE)
123
  with gr.Column():
124
- # Campo de selección de modelo arriba
125
  model_choice_component.render()
126
  chatbot_component.render()
127
  with gr.Row():
128
  text_prompt_component.render()
129
  upload_button_component.render()
130
  run_button_component.render()
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(
@@ -158,5 +154,4 @@ with gr.Blocks() as demo:
158
  queue=False
159
  )
160
 
161
- # Lanzar la aplicación
162
  demo.queue(max_size=99).launch(debug=False, show_error=True)
 
 
 
 
1
  import os
2
  import time
3
  import uuid
 
8
  from PIL import Image
9
  from dotenv import load_dotenv
10
 
11
+ # Load environment variables
12
  load_dotenv()
13
 
14
+ # Constants
15
+ TITLE = """<h1 align="center">Gemini Playground ✨</h1>"""
16
+ SUBTITLE = """<h2 align="center">Play with Gemini Pro and Gemini Pro Vision</h2>"""
17
  GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
 
 
 
 
 
18
  IMAGE_CACHE_DIRECTORY = "/tmp"
19
  IMAGE_WIDTH = 512
20
  CHAT_HISTORY = List[Tuple[Optional[Union[Tuple[str], str]], Optional[str]]]
21
 
22
+ # Check API key
23
+ if not GOOGLE_API_KEY:
24
+ raise ValueError("GOOGLE_API_KEY is not set in environment variables.")
25
+
26
  def preprocess_image(image: Image.Image) -> Optional[Image.Image]:
27
  if image:
28
  image_height = int(image.height * IMAGE_WIDTH / image.width)
 
35
  image.save(image_path, "JPEG")
36
  return image_path
37
 
38
+ def transform_history(history: CHAT_HISTORY):
39
+ """Transform Gradio history into Gemini-compatible format."""
40
+ new_history = []
41
+ for chat in history:
42
+ if chat[0]:
43
+ new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
44
+ if chat[1]:
45
+ new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
46
+ return new_history
47
+
48
  def upload(files: Optional[List[str]], chatbot: CHAT_HISTORY) -> CHAT_HISTORY:
49
  for file in files:
50
  image = Image.open(file).convert('RGB')
 
63
  def bot(
64
  files: Optional[List[str]],
65
  model_choice: str,
66
+ system_instruction: Optional[str],
67
  chatbot: CHAT_HISTORY
68
  ):
69
  if not GOOGLE_API_KEY:
 
77
  top_p=0.9
78
  )
79
 
 
80
  if not system_instruction:
81
+ system_instruction = "Default system instruction."
82
+
83
+ text_prompt = [chat[0] for chat in chatbot if isinstance(chat[0], str)]
84
+ chat = genai.Chat(model=model_choice, messages=transform_history(chatbot))
 
 
 
 
 
 
85
 
86
+ response = chat.send_message(
87
+ text_prompt[-1] if text_prompt else "", # Use the last user message
88
+ system_instruction=system_instruction
89
+ )
90
 
91
+ chatbot[-1] = (chatbot[-1][0], "")
92
  for chunk in response:
93
  for i in range(0, len(chunk.text), 10):
94
  section = chunk.text[i:i + 10]
95
+ chatbot[-1] = (chatbot[-1][0], chatbot[-1][1] + section)
96
  time.sleep(0.01)
97
  yield chatbot
98
 
 
99
  system_instruction_component = gr.Textbox(
100
  placeholder="Enter system instruction...",
101
  show_label=True,
102
  scale=8
103
  )
104
 
 
105
  chatbot_component = gr.Chatbot(label='Gemini', bubble_full_width=False, scale=2, height=300)
106
  text_prompt_component = gr.Textbox(placeholder="Message...", show_label=False, autofocus=True, scale=8)
107
  upload_button_component = gr.UploadButton(label="Upload Images", file_count="multiple", file_types=["image"], scale=1)
 
116
  user_inputs = [text_prompt_component, chatbot_component]
117
  bot_inputs = [upload_button_component, model_choice_component, system_instruction_component, chatbot_component]
118
 
 
119
  with gr.Blocks() as demo:
120
  gr.HTML(TITLE)
121
  gr.HTML(SUBTITLE)
122
  with gr.Column():
 
123
  model_choice_component.render()
124
  chatbot_component.render()
125
  with gr.Row():
126
  text_prompt_component.render()
127
  upload_button_component.render()
128
  run_button_component.render()
129
+ with gr.Accordion("System Instruction", open=False):
 
 
130
  system_instruction_component.render()
131
 
132
  run_button_component.click(
 
154
  queue=False
155
  )
156
 
 
157
  demo.queue(max_size=99).launch(debug=False, show_error=True)