Spaces:
Sleeping
Sleeping
INIFanalitica
commited on
Commit
•
c870a21
1
Parent(s):
3fd216a
Update app.py
Browse files
app.py
CHANGED
@@ -1,108 +1,114 @@
|
|
1 |
import streamlit as st
|
2 |
-
from
|
3 |
-
import google.generativeai as genai
|
4 |
-
import re
|
5 |
import textwrap
|
6 |
-
|
7 |
-
|
8 |
-
#
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
# Display the generated response
|
30 |
-
full_response = ""
|
31 |
-
for chunk in response:
|
32 |
-
full_response += chunk.text
|
33 |
-
|
34 |
-
# Translate the response to Spanish without modifying it
|
35 |
-
translated_output = translate_text(full_response, target_language='es')
|
36 |
-
|
37 |
-
return translated_output
|
38 |
-
|
39 |
-
except Exception as e:
|
40 |
-
error_message = str(e)
|
41 |
-
if "text must be a valid text with maximum 5000 character" in error_message and not error_flag:
|
42 |
-
error_response = ("La pregunta que está realizando puede que vaya en contra de las políticas de Google Bard e INIF. "
|
43 |
-
"Por favor, reformule su pregunta sin temas no permitidos o pregunte algo diferente. "
|
44 |
-
"Para más información consulte: https://policies.google.com/terms/generative-ai/use-policy "
|
45 |
-
"o www.inif.com.co/laura-chatbot/use-policy")
|
46 |
-
st.error(error_response)
|
47 |
-
error_flag = True # Set the error_flag to True after displaying the error message
|
48 |
-
return error_response
|
49 |
-
else:
|
50 |
-
error_response = f"Error: {error_message}\nDisculpa, soy una inteligencia artificial que aún se encuentra en desarrollo y está en fase alfa. En este momento no puedo responder a tu pregunta adecuadamente, pero en el futuro seré capaz de hacerlo."
|
51 |
-
st.error(error_response)
|
52 |
-
return error_response
|
53 |
|
|
|
54 |
def main():
|
55 |
-
st.
|
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 |
-
|
100 |
-
|
101 |
-
|
102 |
-
if
|
103 |
-
|
104 |
-
|
105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
106 |
|
107 |
if __name__ == "__main__":
|
108 |
main()
|
|
|
1 |
import streamlit as st
|
2 |
+
from PIL import Image
|
|
|
|
|
3 |
import textwrap
|
4 |
+
import google.generativeai as genai
|
5 |
+
|
6 |
+
# Function to display formatted Markdown text
|
7 |
+
def to_markdown(text):
|
8 |
+
text = text.replace('•', ' *')
|
9 |
+
return textwrap.indent(text, '> ', predicate=lambda _: True)
|
10 |
+
|
11 |
+
# Function to generate content using Gemini API
|
12 |
+
def generate_gemini_content(prompt, model_name='gemini-pro-vision', image=None):
|
13 |
+
model = genai.GenerativeModel(model_name)
|
14 |
+
if not image:
|
15 |
+
st.warning("Por favor, agrega una imagen para usar el modelo gemini-pro-vision.")
|
16 |
+
return None
|
17 |
+
|
18 |
+
response = model.generate_content([prompt, image])
|
19 |
+
return response
|
20 |
+
|
21 |
+
# Function to generate response with Gemini and INIF context
|
22 |
+
def generate_response_with_context(user_input, model):
|
23 |
+
full_input = f"I am an informative data analyst chatbot named TERMINATOR, working for the National Institute of Fraud Research and Prevention (INIF), dedicated to fraud prevention and mitigation. {user_input}"
|
24 |
+
response = model.generate_content([full_input])
|
25 |
+
return response.candidates[0].content.parts[0].text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
+
# Streamlit app
|
28 |
def main():
|
29 |
+
st.set_page_config(page_title="Laura INIF Chatbot", page_icon="🤖")
|
30 |
+
st.title("Laura INIF Chatbot")
|
31 |
+
st.sidebar.title("Configuración de Laura INIF")
|
32 |
+
|
33 |
+
# Configurar la API key de Gemini (reemplazar con tu clave de API de Gemini)
|
34 |
+
genai.configure(api_key='TU_CLAVE_API_DE_GEMINI')
|
35 |
+
|
36 |
+
# Seleccionar el modelo Gemini
|
37 |
+
select_model = st.sidebar.selectbox("Selecciona el modelo", ["gemini-pro", "gemini-pro-vision"])
|
38 |
+
|
39 |
+
# Inicializar la sesión de chat
|
40 |
+
chat = genai.GenerativeModel(select_model).start_chat(history=[])
|
41 |
+
|
42 |
+
# Definir función para obtener respuesta del modelo Gemini
|
43 |
+
def get_response(messages):
|
44 |
+
response = chat.send_message(messages, stream=True)
|
45 |
+
return response
|
46 |
+
|
47 |
+
# Historial del chat
|
48 |
+
if "messages" not in st.session_state:
|
49 |
+
st.session_state["messages"] = []
|
50 |
+
|
51 |
+
messages = st.session_state["messages"]
|
52 |
+
|
53 |
+
# Mostrar mensajes del historial
|
54 |
+
if messages:
|
55 |
+
for message in messages:
|
56 |
+
role, parts = message.values()
|
57 |
+
if role.lower() == "user":
|
58 |
+
st.markdown(f"Tú: {parts[0]}")
|
59 |
+
elif role.lower() == "model":
|
60 |
+
st.markdown(f"Assistant: {to_markdown(parts[0])}")
|
61 |
+
|
62 |
+
# Entrada del usuario
|
63 |
+
user_input = st.text_area("Tú:")
|
64 |
+
|
65 |
+
# Get optional image input if the model selected is 'gemini-pro-vision'
|
66 |
+
image_file = None
|
67 |
+
if select_model == 'gemini-pro-vision':
|
68 |
+
image_file = st.file_uploader("Sube una imagen (si aplica):", type=["jpg", "jpeg", "png"])
|
69 |
+
|
70 |
+
# Display image if provided
|
71 |
+
if image_file:
|
72 |
+
st.image(image_file, caption="Imagen subida", use_column_width=True)
|
73 |
+
|
74 |
+
# Botón para enviar mensaje o generar contenido según el modelo seleccionado
|
75 |
+
if st.button("Enviar / Generar Contenido"):
|
76 |
+
if user_input:
|
77 |
+
messages.append({"role": "user", "parts": [user_input]})
|
78 |
+
if select_model == 'gemini-pro-vision':
|
79 |
+
# Modelo Gemini Vision Pro seleccionado
|
80 |
+
if not image_file:
|
81 |
+
st.warning("Por favor, proporciona una imagen para el modelo gemini-pro-vision.")
|
82 |
+
else:
|
83 |
+
image = Image.open(image_file)
|
84 |
+
response = generate_gemini_content(user_input, model_name=select_model, image=image)
|
85 |
+
if response:
|
86 |
+
if response.candidates:
|
87 |
+
parts = response.candidates[0].content.parts
|
88 |
+
generated_text = parts[0].text if parts else "No se generó contenido."
|
89 |
+
st.markdown(f"Assistant: {to_markdown(generated_text)}")
|
90 |
+
messages.append({"role": "model", "parts": [generated_text]})
|
91 |
+
else:
|
92 |
+
st.warning("No se encontraron candidatos en la respuesta.")
|
93 |
+
else:
|
94 |
+
# Otros modelos Gemini seleccionados
|
95 |
+
response = get_response(user_input)
|
96 |
+
|
97 |
+
# Mostrar respuesta del modelo solo una vez
|
98 |
+
res_text = ""
|
99 |
+
for chunk in response:
|
100 |
+
res_text += chunk.text
|
101 |
+
st.markdown(f"Assistant: {to_markdown(res_text)}")
|
102 |
+
messages.append({"role": "model", "parts": [res_text]})
|
103 |
+
|
104 |
+
# Incorporar la respuesta del modelo con contexto de INIF
|
105 |
+
if select_model == 'gemini-pro':
|
106 |
+
inif_model = genai.GenerativeModel('gemini-pro') # Usar el modelo de Gemini para INIF
|
107 |
+
inif_response = generate_response_with_context(user_input, inif_model)
|
108 |
+
st.success(inif_response)
|
109 |
+
|
110 |
+
# Actualizar historial de mensajes en la sesión de Streamlit
|
111 |
+
st.session_state["messages"] = messages
|
112 |
|
113 |
if __name__ == "__main__":
|
114 |
main()
|