JeCabrera commited on
Commit
5010813
verified
1 Parent(s): 79155c3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +79 -16
app.py CHANGED
@@ -1,10 +1,13 @@
1
  import os
2
  import time
 
 
 
3
  import google.generativeai as genai
4
  import gradio as gr
5
  from dotenv import load_dotenv
6
 
7
- # Cargar las variables de entorno
8
  load_dotenv()
9
  API_KEY = os.getenv("GOOGLE_API_KEY")
10
 
@@ -12,16 +15,15 @@ if not API_KEY:
12
  raise ValueError("La clave de API 'GOOGLE_API_KEY' no est谩 configurada en el archivo .env")
13
 
14
  # Configuraci贸n del modelo Gemini
 
15
  generation_config = {
16
- "temperature": 1,
17
- "top_p": 0.95,
18
  "top_k": 40,
19
  "max_output_tokens": 8192,
20
  "response_mime_type": "text/plain",
21
  }
22
 
23
- genai.configure(api_key=API_KEY)
24
-
25
  model = genai.GenerativeModel(
26
  model_name="gemini-1.5-flash",
27
  generation_config=generation_config,
@@ -30,33 +32,94 @@ model = genai.GenerativeModel(
30
  # Inicializar la sesi贸n de chat
31
  chat = model.start_chat(history=[])
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  # Funci贸n para transformar el historial de Gradio al formato de Gemini
34
  def transform_history(history):
 
35
  new_history = []
36
  for chat in history:
37
- new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
38
- new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
 
 
39
  return new_history
40
 
41
- # Funci贸n de respuesta
42
  def response(message, history):
 
43
  global chat
44
 
45
  # Transformar el historial al formato esperado por Gemini
46
  chat.history = transform_history(history)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- # Enviar el mensaje al modelo y obtener la respuesta
49
- response = chat.send_message(message)
 
50
  response.resolve()
51
 
52
- # Mostrar la respuesta car谩cter por car谩cter
53
  for i in range(len(response.text)):
54
  time.sleep(0.01)
55
  yield response.text[: i + 1]
56
 
57
- # Configuraci贸n de la interfaz de Gradio
58
- gr.ChatInterface(
59
  response,
60
- title="Chat con Gemini 1.5 Flash",
61
- textbox=gr.Textbox(placeholder="Escribe tu pregunta para Gemini"),
62
- ).launch(debug=True)
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import time
3
+ import uuid
4
+ from typing import List, Tuple, Optional, Union
5
+ from PIL import Image
6
  import google.generativeai as genai
7
  import gradio as gr
8
  from dotenv import load_dotenv
9
 
10
+ # Cargar las variables de entorno desde el archivo .env
11
  load_dotenv()
12
  API_KEY = os.getenv("GOOGLE_API_KEY")
13
 
 
15
  raise ValueError("La clave de API 'GOOGLE_API_KEY' no est谩 configurada en el archivo .env")
16
 
17
  # Configuraci贸n del modelo Gemini
18
+ genai.configure(api_key=API_KEY)
19
  generation_config = {
20
+ "temperature": 0.7,
21
+ "top_p": 0.9,
22
  "top_k": 40,
23
  "max_output_tokens": 8192,
24
  "response_mime_type": "text/plain",
25
  }
26
 
 
 
27
  model = genai.GenerativeModel(
28
  model_name="gemini-1.5-flash",
29
  generation_config=generation_config,
 
32
  # Inicializar la sesi贸n de chat
33
  chat = model.start_chat(history=[])
34
 
35
+ # Constantes para el manejo de im谩genes
36
+ IMAGE_CACHE_DIRECTORY = "/tmp"
37
+ IMAGE_WIDTH = 512
38
+ CHAT_HISTORY = List[Tuple[Optional[Union[Tuple[str], str]], Optional[str]]]
39
+
40
+ # Funci贸n para preprocesar una imagen
41
+ def preprocess_image(image: Image.Image) -> Optional[Image.Image]:
42
+ """Redimensiona una imagen manteniendo la relaci贸n de aspecto."""
43
+ if image:
44
+ image_height = int(image.height * IMAGE_WIDTH / image.width)
45
+ return image.resize((IMAGE_WIDTH, image_height))
46
+
47
+ # Funci贸n para almacenar una imagen en cach茅
48
+ def cache_pil_image(image: Image.Image) -> str:
49
+ """Guarda la imagen como archivo JPEG en un directorio temporal."""
50
+ image_filename = f"{uuid.uuid4()}.jpeg"
51
+ os.makedirs(IMAGE_CACHE_DIRECTORY, exist_ok=True)
52
+ image_path = os.path.join(IMAGE_CACHE_DIRECTORY, image_filename)
53
+ image.save(image_path, "JPEG")
54
+ return image_path
55
+
56
  # Funci贸n para transformar el historial de Gradio al formato de Gemini
57
  def transform_history(history):
58
+ """Transforma el historial del formato de Gradio al formato que Gemini espera."""
59
  new_history = []
60
  for chat in history:
61
+ if chat[0]: # Mensaje del usuario
62
+ new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
63
+ if chat[1]: # Respuesta del modelo
64
+ new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
65
  return new_history
66
 
67
+ # Funci贸n principal para manejar las respuestas del chat
68
  def response(message, history):
69
+ """Maneja la interacci贸n multimodal y env铆a texto e im谩genes al modelo."""
70
  global chat
71
 
72
  # Transformar el historial al formato esperado por Gemini
73
  chat.history = transform_history(history)
74
+
75
+ # Obtener el texto del mensaje y las im谩genes cargadas
76
+ text_prompt = message["text"]
77
+ files = message["files"]
78
+
79
+ # Procesar im谩genes cargadas
80
+ image_prompts = [preprocess_image(Image.open(file).convert('RGB')) for file in files] if files else []
81
+ if files:
82
+ for file in files:
83
+ image = Image.open(file).convert('RGB')
84
+ image_preview = preprocess_image(image)
85
+ if image_preview:
86
+ # Guardar la imagen y obtener la ruta
87
+ image_path = cache_pil_image(image)
88
+ # Leer la imagen en formato binario para enviarla como Blob
89
+ with open(image_path, "rb") as img_file:
90
+ img_data = img_file.read()
91
+ # Crear un diccionario con los datos binarios y su tipo MIME
92
+ image_prompt = {
93
+ "mime_type": "image/jpeg",
94
+ "data": img_data
95
+ }
96
+ image_prompts.append(image_prompt)
97
+
98
+ # Aqu铆 podemos retornar el listado de `image_prompts` o las rutas
99
+ return image_prompts # Esto puede ser 煤til si luego quieres usar estos datos en otro lugar
100
 
101
+ # Combinar texto e im谩genes para el modelo
102
+ prompts = [text_prompt] + image_prompts
103
+ response = chat.send_message(prompts)
104
  response.resolve()
105
 
106
+ # Generar respuesta car谩cter por car谩cter para una experiencia m谩s fluida
107
  for i in range(len(response.text)):
108
  time.sleep(0.01)
109
  yield response.text[: i + 1]
110
 
111
+ # Crear la interfaz de usuario
112
+ demo = gr.ChatInterface(
113
  response,
114
+ examples=[{"text": "Describe the image:", "files": []}],
115
+ multimodal=True,
116
+ textbox=gr.MultimodalTextbox(
117
+ file_count="multiple",
118
+ file_types=["image"],
119
+ sources=["upload", "microphone"],
120
+ ),
121
+ )
122
+
123
+ # Lanzar la aplicaci贸n
124
+ if __name__ == "__main__":
125
+ demo.launch(debug=True, show_error=True)