|
import os |
|
import time |
|
import uuid |
|
from PIL import Image |
|
import google.generativeai as genai |
|
import gradio as gr |
|
from dotenv import load_dotenv |
|
from typing import List, Tuple, Optional, Union |
|
|
|
|
|
load_dotenv() |
|
API_KEY = os.getenv("GOOGLE_API_KEY") |
|
|
|
if not API_KEY: |
|
raise ValueError("La clave de API 'GOOGLE_API_KEY' no est谩 configurada en el archivo .env") |
|
|
|
|
|
generation_config = { |
|
"temperature": 1, |
|
"top_p": 0.95, |
|
"top_k": 40, |
|
"max_output_tokens": 8192, |
|
"response_mime_type": "text/plain", |
|
} |
|
|
|
genai.configure(api_key=API_KEY) |
|
|
|
model = genai.GenerativeModel( |
|
model_name="gemini-1.5-flash", |
|
generation_config=generation_config, |
|
) |
|
|
|
|
|
chat = model.start_chat(history=[]) |
|
|
|
|
|
def transform_history(history): |
|
new_history = [] |
|
for chat in history: |
|
new_history.append({"parts": [{"text": chat[0]}], "role": "user"}) |
|
new_history.append({"parts": [{"text": chat[1]}], "role": "model"}) |
|
return new_history |
|
|
|
|
|
def response(message, history): |
|
global chat |
|
|
|
|
|
chat.history = transform_history(history) |
|
|
|
|
|
response = chat.send_message(message["text"]) |
|
|
|
return response.text |
|
|
|
|
|
IMAGE_CACHE_DIRECTORY = "/tmp" |
|
IMAGE_WIDTH = 512 |
|
CHAT_HISTORY = List[Tuple[Optional[Union[Tuple[str], str]], Optional[str]]] |
|
|
|
|
|
def preprocess_image(image: Image.Image) -> Optional[Image.Image]: |
|
if image: |
|
image_height = int(image.height * IMAGE_WIDTH / image.width) |
|
return image.resize((IMAGE_WIDTH, image_height)) |
|
|
|
|
|
def cache_pil_image(image: Image.Image) -> str: |
|
image_filename = f"{uuid.uuid4()}.jpeg" |
|
os.makedirs(IMAGE_CACHE_DIRECTORY, exist_ok=True) |
|
image_path = os.path.join(IMAGE_CACHE_DIRECTORY, image_filename) |
|
image.save(image_path, "JPEG") |
|
return image_path |
|
|
|
|
|
def upload(files: Optional[List[str]], chatbot: CHAT_HISTORY) -> CHAT_HISTORY: |
|
for file in files: |
|
image = Image.open(file).convert('RGB') |
|
image_preview = preprocess_image(image) |
|
if image_preview: |
|
|
|
gr.Image(image_preview).render() |
|
image_path = cache_pil_image(image) |
|
chatbot.append(((image_path,), None)) |
|
return chatbot |
|
|
|
|
|
def user(text_prompt: str, chatbot: CHAT_HISTORY): |
|
if text_prompt: |
|
chatbot.append((text_prompt, None)) |
|
return "", chatbot |
|
|
|
|
|
def bot( |
|
files: Optional[List[str]], |
|
model_choice: str, |
|
system_instruction: Optional[str], |
|
chatbot: CHAT_HISTORY |
|
): |
|
if not API_KEY: |
|
raise ValueError("GOOGLE_API_KEY is not set.") |
|
|
|
genai.configure(api_key=API_KEY) |
|
generation_config = genai.types.GenerationConfig( |
|
temperature=0.7, |
|
max_output_tokens=8192, |
|
top_k=10, |
|
top_p=0.9 |
|
) |
|
|
|
|
|
if not system_instruction: |
|
system_instruction = "1" |
|
|
|
text_prompt = [chatbot[-1][0]] if chatbot and chatbot[-1][0] and isinstance(chatbot[-1][0], str) else [] |
|
image_prompt = [preprocess_image(Image.open(file).convert('RGB')) for file in files] if files else [] |
|
|
|
model = genai.GenerativeModel( |
|
model_name=model_choice, |
|
generation_config=generation_config, |
|
system_instruction=system_instruction |
|
) |
|
|
|
|
|
response = model.generate_content(text_prompt + image_prompt, stream=True, generation_config=generation_config) |
|
|
|
chatbot[-1][1] = "" |
|
for chunk in response: |
|
for i in range(0, len(chunk.text), 10): |
|
section = chunk.text[i:i + 10] |
|
chatbot[-1][1] += section |
|
time.sleep(0.01) |
|
yield chatbot |
|
|
|
|
|
demo = gr.ChatInterface( |
|
bot, |
|
examples=[ |
|
{"text": "No files", "files": []} |
|
], |
|
multimodal=True, |
|
textbox=gr.MultimodalTextbox( |
|
file_count="multiple", |
|
file_types=["image"], |
|
sources=["upload", "microphone"] |
|
) |
|
) |
|
|
|
|
|
demo.launch() |
|
|