Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,19 +1,91 @@
|
|
1 |
-
import
|
2 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
time.sleep(0.05)
|
8 |
-
yield response[: i + 1]
|
9 |
|
|
|
10 |
demo = gr.ChatInterface(
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
|
|
|
|
17 |
)
|
18 |
|
19 |
-
|
|
|
|
|
|
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 |
+
|
14 |
+
if not API_KEY:
|
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,
|
30 |
+
)
|
31 |
+
|
32 |
+
# Constantes para el manejo de im谩genes
|
33 |
+
IMAGE_CACHE_DIRECTORY = "/tmp"
|
34 |
+
IMAGE_WIDTH = 512
|
35 |
+
CHAT_HISTORY = List[Tuple[Optional[Union[Tuple[str], str]], Optional[str]]]
|
36 |
+
|
37 |
+
# Funci贸n para preprocesar una imagen
|
38 |
+
def preprocess_image(image: Image.Image) -> Optional[Image.Image]:
|
39 |
+
"""Redimensiona una imagen manteniendo la relaci贸n de aspecto."""
|
40 |
+
if image:
|
41 |
+
image_height = int(image.height * IMAGE_WIDTH / image.width)
|
42 |
+
return image.resize((IMAGE_WIDTH, image_height))
|
43 |
+
|
44 |
+
# Funci贸n para almacenar una imagen en cach茅
|
45 |
+
def cache_pil_image(image: Image.Image) -> str:
|
46 |
+
"""Guarda la imagen como archivo JPEG en un directorio temporal."""
|
47 |
+
image_filename = f"{uuid.uuid4()}.jpeg"
|
48 |
+
os.makedirs(IMAGE_CACHE_DIRECTORY, exist_ok=True)
|
49 |
+
image_path = os.path.join(IMAGE_CACHE_DIRECTORY, image_filename)
|
50 |
+
image.save(image_path, "JPEG")
|
51 |
+
return image_path
|
52 |
+
|
53 |
+
# Funci贸n principal para manejar las respuestas del chat
|
54 |
+
def response(message, history):
|
55 |
+
"""Maneja la interacci贸n multimodal y env铆a texto e im谩genes al modelo."""
|
56 |
+
text_prompt = message["text"]
|
57 |
+
files = message["files"]
|
58 |
+
|
59 |
+
# Procesar im谩genes cargadas
|
60 |
+
image_prompts = []
|
61 |
+
if files:
|
62 |
+
for file in files:
|
63 |
+
image = Image.open(file).convert('RGB')
|
64 |
+
image_preview = preprocess_image(image)
|
65 |
+
if image_preview:
|
66 |
+
cache_pil_image(image)
|
67 |
+
image_prompts.append(image_preview) # Incluir en la lista de prompts
|
68 |
+
|
69 |
+
# Concatenar texto e im谩genes para el modelo
|
70 |
+
prompts = [text_prompt] + image_prompts
|
71 |
+
response = model.generate_content(prompts, stream=True, generation_config=generation_config)
|
72 |
|
73 |
+
# Generar respuesta paso a paso
|
74 |
+
for chunk in response:
|
75 |
+
yield chunk.text
|
|
|
|
|
76 |
|
77 |
+
# Crear la interfaz de usuario
|
78 |
demo = gr.ChatInterface(
|
79 |
+
response,
|
80 |
+
examples=[{"text": "Describe the image:", "files": []}],
|
81 |
+
multimodal=True,
|
82 |
+
textbox=gr.MultimodalTextbox(
|
83 |
+
file_count="multiple",
|
84 |
+
file_types=["image"],
|
85 |
+
sources=["upload", "microphone"],
|
86 |
+
),
|
87 |
)
|
88 |
|
89 |
+
# Lanzar la aplicaci贸n
|
90 |
+
if __name__ == "__main__":
|
91 |
+
demo.launch(debug=True, show_error=True)
|