JeCabrera commited on
Commit
6d41bc7
verified
1 Parent(s): 84e07f0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +3 -37
app.py CHANGED
@@ -23,39 +23,15 @@ GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY")
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)
33
- return image.resize((IMAGE_WIDTH, image_height))
34
-
35
- def cache_pil_image(image: Image.Image) -> str:
36
- image_filename = f"{uuid.uuid4()}.jpeg"
37
- os.makedirs(IMAGE_CACHE_DIRECTORY, exist_ok=True)
38
- image_path = os.path.join(IMAGE_CACHE_DIRECTORY, image_filename)
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')
45
- image_preview = preprocess_image(image)
46
- if image_preview:
47
- gr.Image(image_preview).render()
48
- image_path = cache_pil_image(image)
49
- chatbot.append(((image_path,), None))
50
- return chatbot
51
-
52
  def user(text_prompt: str, chatbot: CHAT_HISTORY):
53
  if text_prompt:
54
  chatbot.append((text_prompt, None))
55
  return "", chatbot
56
 
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
@@ -76,15 +52,14 @@ def bot(
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:
@@ -104,7 +79,6 @@ system_instruction_component = gr.Textbox(
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)
108
  run_button_component = gr.Button(value="Run", variant="primary", scale=1)
109
  model_choice_component = gr.Dropdown(
110
  choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
@@ -114,7 +88,7 @@ model_choice_component = gr.Dropdown(
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
  # Definir la interfaz de usuario
120
  with gr.Blocks() as demo:
@@ -126,7 +100,6 @@ with gr.Blocks() as demo:
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
@@ -151,12 +124,5 @@ with gr.Blocks() as demo:
151
  fn=bot, inputs=bot_inputs, outputs=[chatbot_component],
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=False, show_error=True)
 
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[Union[Tuple[str], str]], Optional[str]]]
28
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  def user(text_prompt: str, chatbot: CHAT_HISTORY):
30
  if text_prompt:
31
  chatbot.append((text_prompt, None))
32
  return "", chatbot
33
 
34
  def bot(
 
35
  model_choice: str,
36
  system_instruction: Optional[str], # Sistema de instrucciones opcional
37
  chatbot: CHAT_HISTORY
 
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
+ response = model.generate_content(text_prompt, stream=True, generation_config=generation_config)
63
 
64
  chatbot[-1][1] = ""
65
  for chunk in response:
 
79
  # Definir los componentes de entrada y salida
80
  chatbot_component = gr.Chatbot(label='Gemini', bubble_full_width=False, scale=2, height=300)
81
  text_prompt_component = gr.Textbox(placeholder="Message...", show_label=False, autofocus=True, scale=8)
 
82
  run_button_component = gr.Button(value="Run", variant="primary", scale=1)
83
  model_choice_component = gr.Dropdown(
84
  choices=["gemini-1.5-flash", "gemini-2.0-flash-exp", "gemini-1.5-pro"],
 
88
  )
89
 
90
  user_inputs = [text_prompt_component, chatbot_component]
91
+ bot_inputs = [model_choice_component, system_instruction_component, chatbot_component]
92
 
93
  # Definir la interfaz de usuario
94
  with gr.Blocks() as demo:
 
100
  chatbot_component.render()
101
  with gr.Row():
102
  text_prompt_component.render()
 
103
  run_button_component.render()
104
 
105
  # Crear el acorde贸n para la instrucci贸n del sistema al final
 
124
  fn=bot, inputs=bot_inputs, outputs=[chatbot_component],
125
  )
126
 
 
 
 
 
 
 
 
127
  # Lanzar la aplicaci贸n
128
  demo.queue(max_size=99).launch(debug=False, show_error=True)