Spaces:
Running
Running
File size: 2,820 Bytes
88c5efb 500f371 4bde338 bc54a0a cb0053e aef709e cb0053e 4260be4 5ef5e82 6efed0c cb0053e c99083d 88c5efb 6efed0c cb0053e 6efed0c cb0053e 6efed0c 88c5efb cb0053e 88c5efb cb0053e c99083d cb0053e c99083d cb0053e 88c5efb cb0053e 88c5efb cb0053e c99083d cb0053e f9815f3 cb0053e c99083d f9815f3 6efed0c 88c5efb 6efed0c acaff10 6efed0c 88c5efb 6efed0c 88c5efb 6efed0c c99083d 88c5efb |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
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()
|