Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,3 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
# Crear la interfaz de Gradio
|
2 |
demo = gr.Interface(
|
3 |
fn=handle_message, # Funci贸n de manejo de mensaje y archivos
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import uuid
|
4 |
+
import google.generativeai as genai
|
5 |
+
import gradio as gr
|
6 |
+
from PIL import Image
|
7 |
+
from dotenv import load_dotenv
|
8 |
+
|
9 |
+
# Cargar las variables de entorno
|
10 |
+
load_dotenv()
|
11 |
+
API_KEY = os.getenv("GOOGLE_API_KEY")
|
12 |
+
|
13 |
+
if not API_KEY:
|
14 |
+
raise ValueError("La clave de API 'GOOGLE_API_KEY' no est谩 configurada en el archivo .env")
|
15 |
+
|
16 |
+
# Configuraci贸n del modelo Gemini
|
17 |
+
generation_config = {
|
18 |
+
"temperature": 1,
|
19 |
+
"top_p": 0.95,
|
20 |
+
"top_k": 40,
|
21 |
+
"max_output_tokens": 8192,
|
22 |
+
"response_mime_type": "text/plain",
|
23 |
+
}
|
24 |
+
|
25 |
+
genai.configure(api_key=API_KEY)
|
26 |
+
|
27 |
+
model = genai.GenerativeModel(
|
28 |
+
model_name="gemini-1.5-flash",
|
29 |
+
generation_config=generation_config,
|
30 |
+
)
|
31 |
+
|
32 |
+
# Inicializar la sesi贸n de chat
|
33 |
+
chat = model.start_chat(history=[])
|
34 |
+
|
35 |
+
# Funci贸n para transformar el historial de Gradio al formato de Gemini
|
36 |
+
def transform_history(history):
|
37 |
+
new_history = []
|
38 |
+
for chat in history:
|
39 |
+
new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
|
40 |
+
new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
|
41 |
+
return new_history
|
42 |
+
|
43 |
+
# Funci贸n de respuesta que maneja el texto y los archivos multimodales
|
44 |
+
def response(message, history):
|
45 |
+
global chat
|
46 |
+
|
47 |
+
# Transformar el historial al formato esperado por Gemini
|
48 |
+
chat.history = transform_history(history)
|
49 |
+
|
50 |
+
# Enviar el mensaje al modelo y obtener la respuesta
|
51 |
+
response = chat.send_message(message["text"])
|
52 |
+
response.resolve()
|
53 |
+
|
54 |
+
# Mostrar la respuesta car谩cter por car谩cter
|
55 |
+
for i in range(len(response.text)):
|
56 |
+
time.sleep(0.01)
|
57 |
+
yield response.text[: i + 1]
|
58 |
+
|
59 |
+
# Funci贸n para manejar las im谩genes cargadas
|
60 |
+
def handle_uploaded_images(files):
|
61 |
+
"""Procesa las im谩genes cargadas, las redimensiona y las guarda"""
|
62 |
+
image_paths = []
|
63 |
+
for file in files:
|
64 |
+
image = Image.open(file.name).convert('RGB') # Abrir y convertir la imagen a RGB
|
65 |
+
image_height = int(image.height * 512 / image.width) # Mantener la proporci贸n
|
66 |
+
image_resized = image.resize((512, image_height)) # Redimensionar la imagen
|
67 |
+
image_filename = f"{uuid.uuid4()}.jpeg" # Crear un nombre 煤nico para la imagen
|
68 |
+
image_path = f"/tmp/{image_filename}" # Ruta de almacenamiento temporal
|
69 |
+
image_resized.save(image_path, "JPEG") # Guardar la imagen
|
70 |
+
image_paths.append(image_path) # Agregar la ruta al resultado
|
71 |
+
return image_paths
|
72 |
+
|
73 |
+
# Funci贸n para contar las im谩genes cargadas
|
74 |
+
def count_images(message, history):
|
75 |
+
num_images = len(message["files"]) # Contar las im谩genes cargadas en el mensaje actual
|
76 |
+
total_images = 0
|
77 |
+
for msg in history: # Contar todas las im谩genes en el historial
|
78 |
+
if isinstance(msg["content"], tuple): # Si el contenido es una tupla, es un archivo
|
79 |
+
total_images += 1
|
80 |
+
return f"You just uploaded {num_images} images, total uploaded: {total_images + num_images}"
|
81 |
+
|
82 |
+
# Funci贸n que maneja el texto y las im谩genes
|
83 |
+
def handle_message(message, history):
|
84 |
+
if message.get("files"):
|
85 |
+
# Procesar las im谩genes cargadas
|
86 |
+
image_paths = handle_uploaded_images(message["files"])
|
87 |
+
# A帽adir las im谩genes al historial
|
88 |
+
history.append((None, image_paths))
|
89 |
+
return history, count_images(message, history)
|
90 |
+
|
91 |
+
# Si no hay archivos, procesamos el mensaje como texto
|
92 |
+
return response(message, history)
|
93 |
+
|
94 |
# Crear la interfaz de Gradio
|
95 |
demo = gr.Interface(
|
96 |
fn=handle_message, # Funci贸n de manejo de mensaje y archivos
|