JeCabrera commited on
Commit
8d45e13
verified
1 Parent(s): ac46ee5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +11 -142
app.py CHANGED
@@ -1,150 +1,19 @@
1
- import os
2
- import time
3
- import uuid
4
- from PIL import Image
5
- import google.generativeai as genai
6
  import gradio as gr
7
- from dotenv import load_dotenv
8
- from typing import List, Tuple, Optional, Union
9
-
10
- # Cargar las variables de entorno
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
- generation_config = {
19
- "temperature": 1,
20
- "top_p": 0.95,
21
- "top_k": 40,
22
- "max_output_tokens": 8192,
23
- "response_mime_type": "text/plain",
24
- }
25
-
26
- genai.configure(api_key=API_KEY)
27
-
28
- model = genai.GenerativeModel(
29
- model_name="gemini-1.5-flash",
30
- generation_config=generation_config,
31
- )
32
-
33
- # Inicializar la sesi贸n de chat
34
- chat = model.start_chat(history=[])
35
-
36
- # Funci贸n para transformar el historial de Gradio al formato de Gemini
37
- def transform_history(history):
38
- new_history = []
39
- for chat in history:
40
- new_history.append({"parts": [{"text": chat[0]}], "role": "user"})
41
- new_history.append({"parts": [{"text": chat[1]}], "role": "model"})
42
- return new_history
43
-
44
- # Funci贸n de respuesta que maneja el texto y los archivos multimodales
45
- def response(message, history):
46
- global chat
47
-
48
- # Transformar el historial al formato esperado por Gemini
49
- chat.history = transform_history(history)
50
-
51
- # Enviar el mensaje al modelo y obtener la respuesta
52
- response = chat.send_message(message["text"])
53
- # Eliminar la llamada a `response.resolve()` porque no es necesario.
54
- return response.text
55
-
56
- # Constantes y configuraciones
57
- IMAGE_CACHE_DIRECTORY = "/tmp"
58
- IMAGE_WIDTH = 512
59
- CHAT_HISTORY = List[Tuple[Optional[Union[Tuple[str], str]], Optional[str]]]
60
-
61
- # Funci贸n para preprocesar la imagen
62
- def preprocess_image(image: Image.Image) -> Optional[Image.Image]:
63
- if image:
64
- image_height = int(image.height * IMAGE_WIDTH / image.width)
65
- return image.resize((IMAGE_WIDTH, image_height))
66
-
67
- # Funci贸n para almacenar la imagen en el cach茅
68
- def cache_pil_image(image: Image.Image) -> str:
69
- image_filename = f"{uuid.uuid4()}.jpeg"
70
- os.makedirs(IMAGE_CACHE_DIRECTORY, exist_ok=True)
71
- image_path = os.path.join(IMAGE_CACHE_DIRECTORY, image_filename)
72
- image.save(image_path, "JPEG")
73
- return image_path
74
-
75
- # Funci贸n para cargar im谩genes
76
- def upload(files: Optional[List[str]], chatbot: CHAT_HISTORY) -> CHAT_HISTORY:
77
- for file in files:
78
- image = Image.open(file).convert('RGB')
79
- image_preview = preprocess_image(image)
80
- if image_preview:
81
- # Enviar la imagen procesada para su visualizaci贸n en Gradio
82
- gr.Image(image_preview).render()
83
- image_path = cache_pil_image(image)
84
- chatbot.append(((image_path,), None))
85
- return chatbot
86
-
87
- # Funci贸n para manejar el mensaje del usuario
88
- def user(text_prompt: str, chatbot: CHAT_HISTORY):
89
- if text_prompt:
90
- chatbot.append((text_prompt, None))
91
- return "", chatbot
92
-
93
- # Funci贸n para la respuesta del bot
94
- def bot(
95
- files: Optional[List[str]],
96
- model_choice: str,
97
- system_instruction: Optional[str], # Sistema de instrucciones opcional
98
- chatbot: CHAT_HISTORY
99
- ):
100
- if not API_KEY:
101
- raise ValueError("GOOGLE_API_KEY is not set.")
102
-
103
- genai.configure(api_key=API_KEY)
104
- generation_config = genai.types.GenerationConfig(
105
- temperature=0.7,
106
- max_output_tokens=8192,
107
- top_k=10,
108
- top_p=0.9
109
- )
110
-
111
- # Usar el valor por defecto para system_instruction si est谩 vac铆o
112
- if not system_instruction:
113
- system_instruction = "1" # O puedes poner un valor predeterminado como "No system instruction provided."
114
-
115
- text_prompt = [chatbot[-1][0]] if chatbot and chatbot[-1][0] and isinstance(chatbot[-1][0], str) else []
116
- image_prompt = [preprocess_image(Image.open(file).convert('RGB')) for file in files] if files else []
117
-
118
- model = genai.GenerativeModel(
119
- model_name=model_choice,
120
- generation_config=generation_config,
121
- system_instruction=system_instruction # Usar el valor por defecto si est谩 vac铆o
122
- )
123
-
124
- # Se debe usar la generaci贸n de contenido multimodal para procesar im谩genes y texto
125
- response = model.generate_content(text_prompt + image_prompt, stream=True, generation_config=generation_config)
126
 
127
- chatbot[-1][1] = ""
128
- for chunk in response:
129
- for i in range(0, len(chunk.text), 10):
130
- section = chunk.text[i:i + 10]
131
- chatbot[-1][1] += section
132
- time.sleep(0.01)
133
- yield chatbot
134
 
135
- # Crear la interfaz de Gradio
136
  demo = gr.ChatInterface(
137
- response, # Funci贸n de chat para manejar texto y archivos
138
- examples=[ # Ejemplos iniciales de mensajes
139
- {"text": "No files", "files": []}
 
 
140
  ],
141
- multimodal=True, # Activar la modalidad multimodal
142
- textbox=gr.MultimodalTextbox( # Configuraci贸n del cuadro de texto multimodal
143
- file_count="multiple", # Permitir m煤ltiples archivos
144
- file_types=["image"], # Aceptar solo im谩genes
145
- sources=["upload", "microphone"] # Fuentes de entrada: carga de archivos y micr贸fono
146
- )
147
  )
148
 
149
- # Iniciar la interfaz
150
  demo.launch()
 
 
 
 
 
 
1
  import gradio as gr
2
+ import time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
+ def echo(message, history, system_prompt, tokens):
5
+ response = f"System prompt: {system_prompt}\n Message: {message}."
6
+ for i in range(min(len(response), int(tokens))):
7
+ time.sleep(0.05)
8
+ yield response[: i + 1]
 
 
9
 
 
10
  demo = gr.ChatInterface(
11
+ echo,
12
+ type="messages",
13
+ additional_inputs=[
14
+ gr.Textbox("You are helpful AI.", label="System Prompt"),
15
+ gr.Slider(10, 100),
16
  ],
 
 
 
 
 
 
17
  )
18
 
 
19
  demo.launch()