Spaces:
Running
Running
import gradio as gr | |
import os | |
import time | |
import google.generativeai as genai | |
from mimetypes import MimeTypes | |
# Configurar la API de Gemini | |
genai.configure(api_key=os.environ["GOOGLE_API_KEY"]) | |
def upload_and_process_file(file): | |
""" | |
Sube y procesa un archivo para usarlo con el modelo de Gemini. | |
""" | |
if isinstance(file, gr.inputs.File): | |
file_path = file.name # Obtener la ruta temporal del archivo | |
else: | |
raise ValueError("El archivo no se subi贸 correctamente.") | |
# Detectar el tipo MIME del archivo | |
mime = MimeTypes() | |
mime_type, _ = mime.guess_type(file_path) | |
if not mime_type: | |
raise ValueError("No se pudo determinar el tipo MIME del archivo.") | |
# Subir el archivo a Gemini | |
print(f"Subiendo el archivo '{file_path}' con MIME type '{mime_type}'...") | |
file = genai.upload_file(file_path, mime_type=mime_type) | |
print(f"Archivo subido: {file.display_name}, URI: {file.uri}") | |
# Esperar a que el archivo est茅 activo | |
wait_for_files_active([file]) | |
return file | |
def wait_for_files_active(files): | |
""" | |
Espera a que los archivos subidos a Gemini est茅n activos y listos para su uso. | |
""" | |
print("Esperando el procesamiento de los archivos...") | |
for file in files: | |
status = genai.get_file(file.name) | |
while status.state.name == "PROCESSING": | |
print(".", end="", flush=True) | |
time.sleep(5) | |
status = genai.get_file(file.name) | |
if status.state.name != "ACTIVE": | |
raise Exception(f"El archivo {file.name} no pudo procesarse correctamente.") | |
print("\nTodos los archivos est谩n listos.") | |
# Configuraci贸n del modelo generativo | |
generation_config = { | |
"temperature": 1, | |
"top_p": 0.95, | |
"top_k": 40, | |
"max_output_tokens": 8192, | |
"response_mime_type": "text/plain", | |
} | |
model = genai.GenerativeModel( | |
model_name="gemini-1.5-flash", | |
generation_config=generation_config, | |
) | |
def start_chat_with_file(file, user_input): | |
""" | |
Inicia una conversaci贸n con el modelo utilizando un archivo como entrada. | |
""" | |
chat_session = model.start_chat( | |
history=[ | |
{ | |
"role": "user", | |
"parts": [file], | |
}, | |
] | |
) | |
# Enviar mensaje al modelo | |
response = chat_session.send_message(user_input) | |
return response.text | |
# Interfaz de Gradio | |
def process_file(file, user_input): | |
processed_file = upload_and_process_file(file) | |
response = start_chat_with_file(processed_file, user_input) | |
return response | |
# Crear la interfaz de Gradio | |
iface = gr.Interface( | |
fn=process_file, | |
inputs=[gr.File(label="Sube tu archivo"), gr.Textbox(label="Escribe tu mensaje")], | |
outputs="text", | |
live=True | |
) | |
# Ejecutar la interfaz | |
iface.launch() | |