Spaces:
Sleeping
Sleeping
import google.generativeai as genai | |
import gradio as gr | |
import numpy as np | |
import PIL.Image | |
import pandas as pd | |
import io | |
genai.configure(api_key="AIzaSyA7tPavobVN5_3-BJ0qhFT5HVjO4V19QWk") | |
def ImageChat(image): | |
# Configuración de la personalidad del sistema | |
system_prompt = "Sólo puedes responder en idioma español: Sí o No." | |
# Lista de preguntas preconfiguradas | |
questions = [ | |
"¿La persona está utilizando auriculares?", | |
"¿La persona está utilizando capucha o algo que le cubra la cabeza?", | |
"¿Existe dinero como monedas o billetes que estén el piso?", | |
"¿La persona se encuentra interactuando con su teléfono móvil?" | |
] | |
# load model | |
model = genai.GenerativeModel("gemini-1.5-flash") | |
# check image file and convert to a Numpy array | |
try: | |
if isinstance(image, np.ndarray): | |
img = PIL.Image.fromarray(image) | |
else: | |
img = PIL.Image.open(io.BytesIO(image.read())) | |
except Exception as e: | |
return str(e) | |
# Initialize results list | |
results = [] | |
# Process each question | |
for question in questions: | |
full_prompt = f"{system_prompt}\n\n{question}" | |
response = model.generate_content([full_prompt, img]) | |
results.append(response.text) | |
# Create a DataFrame to display results as a table | |
df = pd.DataFrame({"Pregunta": questions, "Respuesta": results}) | |
return df | |
def load_image(image_path): | |
with open(image_path, "rb") as image_file: | |
return image_file.read() | |
# Preloaded images | |
preloaded_images = { | |
"Imagen Ejemplo 1": "chat_with_image.png", | |
"Imagen Ejemplo 2": "chatwithimg_2.jpg", | |
"Imagen Ejemplo 3": "chatwithimg3.png" | |
} | |
def get_selected_image(image_name): | |
return load_image(preloaded_images[image_name]) | |
# Define Gradio interface | |
image_selector = gr.Radio( | |
choices=list(preloaded_images.keys()), | |
label="Selecciona una imagen" | |
) | |
image_display = gr.Image(label="Imagen", type="file") | |
def update_image(selected_image_name): | |
image_data = get_selected_image(selected_image_name) | |
return gr.Image.update(value=image_data) | |
image_selector.change(fn=update_image, inputs=image_selector, outputs=image_display) | |
app = gr.Interface( | |
fn=ImageChat, | |
inputs=image_display, | |
outputs=gr.Dataframe(headers=["Pregunta", "Respuesta"], label="Resultados"), | |
title="Análisis de Imagen", | |
theme="Taithrah/Minimal" | |
) | |
gr.Interface( | |
fn=lambda: "Selecciona una imagen del carrusel y haz clic en 'Submit' para analizarla.", | |
inputs=[image_selector, image_display], | |
outputs="text" | |
).launch() | |