INIFanalitica commited on
Commit
c870a21
1 Parent(s): 3fd216a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -101
app.py CHANGED
@@ -1,108 +1,114 @@
1
  import streamlit as st
2
- from deep_translator import GoogleTranslator
3
- import google.generativeai as genai
4
- import re
5
  import textwrap
6
- from IPython.display import display, Markdown
7
-
8
- # MAX Chatbot
9
-
10
- error_flag = False # Global variable to track error display
11
-
12
- def clean_text(text):
13
- # Clean punctuation and special characters using regular expressions
14
- cleaned_text = re.sub(r'[^a-zA-Z0-9\s]', '', text)
15
- return cleaned_text
16
-
17
- def translate_text(text, target_language='en'):
18
- translator = GoogleTranslator(source='auto', target=target_language)
19
- translation = translator.translate(text)
20
- return translation
21
-
22
- def generate_response(cleaned_input, model):
23
- global error_flag # Use the global error_flag variable
24
-
25
- try:
26
- # Generate response using the model
27
- response = model.generate_content(cleaned_input, stream=True)
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.title("MAX Chatbot - INIF")
56
- genai.configure(api_key='AIzaSyA4k6JoFNZsf8L1ixLMMRjEMoBPns5SHZk') # Replace with your Gemini API key
57
-
58
- # Choose the Gemini model
59
- model = genai.GenerativeModel('gemini-pro')
60
-
61
- st.write("Bienvenido al Chatbot informativo del Instituto Nacional de Investigación y Prevención del Fraude (INIF).")
62
-
63
- # User input
64
- user_input = st.text_input("Pregunta:")
65
-
66
- if st.button("Obtener Respuesta"):
67
- # Translate the question to English
68
- translated_input = translate_text(user_input, target_language='en')
69
-
70
- # Clean the translated text of special characters
71
- cleaned_input = clean_text(translated_input)
72
-
73
- # Exit if the cleaned text is empty
74
- if not cleaned_input:
75
- st.warning("Texto ingresado no válido. Inténtalo de nuevo.")
76
- st.stop()
77
-
78
- # Additional information about INIF
79
- additional_info = (
80
- "Trabajamos para empresarios y colaboradores de cualquier industria que buscan combatir el fraude que impacta negativamente la reputación y la economía de sus organizaciones y del país.\n"
81
- "Somos una empresa privada que trabaja con la industria bancaria y aseguradora."
82
- )
83
-
84
- # Add the command to act as an INIF informative chatbot
85
- bot_command = (
86
- "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. "
87
- "If you have questions related to fraud or prevention, feel free to ask. For inquiries about other topics, I'll redirect you to the fraud prevention context."
88
- f"\n\n{additional_info}"
89
- "\n\nContact Information for INIF:"
90
- "\nPhone: +57 317 638 94 71"
91
- "\nEmail: atencionalcliente@inif.com.co"
92
- "\n\nOur Mission:"
93
- "\nTo be the most reliable engine of knowledge, research, and information in Colombia, capable of preventing and combating fraud through synergy between our team and companies."
94
- "\n\nOur Vision:"
95
- "\nTo lead the construction of a more honest culture, allowing us to progress as a society."
96
- )
97
-
98
- # Generate the response
99
- translated_output = generate_response(bot_command + cleaned_input, model)
100
-
101
- # Display the generated response in green or red based on the content
102
- if "La pregunta que está realizando puede que vaya en contra de las políticas de Google Bard e INIF." in translated_output:
103
- st.error(translated_output)
104
- else:
105
- st.success(translated_output)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()