INIFanalitica commited on
Commit
c5ce46c
1 Parent(s): 6cd31c7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +98 -0
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ from deep_translator import GoogleTranslator
3
+ import google.generativeai as palm
4
+ import re
5
+
6
+ # L.A.U.R.A: Lingüista Artificial Unificada de Respuestas Automaticas
7
+
8
+ error_flag = False # Global variable to track error display
9
+
10
+ def clean_text(text):
11
+ # Clean punctuation and special characters using regular expressions
12
+ cleaned_text = re.sub(r'[^a-zA-Z0-9\s]', '', text)
13
+ return cleaned_text
14
+
15
+ def translate_text(text, target_language='en'):
16
+ translator = GoogleTranslator(source='auto', target=target_language)
17
+ translation = translator.translate(text)
18
+ return translation
19
+
20
+ def generate_response(cleaned_input, model):
21
+ global error_flag # Use the global error_flag variable
22
+
23
+ try:
24
+ # Generate response using the model
25
+ completion = palm.generate_text(
26
+ model=model,
27
+ prompt=cleaned_input,
28
+ temperature=0,
29
+ max_output_tokens=1000,
30
+ )
31
+
32
+ # Translate the response to Spanish without modifying it
33
+ translated_output = translate_text(completion.result, target_language='es')
34
+
35
+ return translated_output
36
+
37
+ except Exception as e:
38
+ error_message = str(e)
39
+ if "text must be a valid text with maximum 5000 character" in error_message and not error_flag:
40
+ error_response = ("La pregunta que está realizando puede que vaya en contra de las políticas de Google Bard e INIF. "
41
+ "Por favor, reformule su pregunta sin temas no permitidos o pregunte algo diferente. "
42
+ "Para más información consulte: https://policies.google.com/terms/generative-ai/use-policy "
43
+ "o www.inif.com.co/laura-chatbot/use-policy")
44
+ st.error(error_response)
45
+ error_flag = True # Set the error_flag to True after displaying the error message
46
+ return error_response
47
+ else:
48
+ 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."
49
+ st.error(error_response)
50
+ return error_response
51
+
52
+ def main():
53
+ st.title("Chatbot INIF - L.A.U.R.A.")
54
+ palm.configure(api_key='AIzaSyCezVerubEzQc9JHz3V8hofpAlSIJXGxFQ')
55
+
56
+ # Select the model that supports text generation
57
+ models = [m for m in palm.list_models() if 'generateText' in m.supported_generation_methods]
58
+ if not models:
59
+ st.error("No hay modelos disponibles para la generación de texto. Verifica tu configuración o inténtalo más tarde.")
60
+ st.stop()
61
+
62
+ model = models[0].name
63
+
64
+ st.write("Bienvenido al Chatbot informativo del Instituto Nacional de Investigación y Prevención del Fraude (INIF).")
65
+
66
+ # User input
67
+ user_input = st.text_input("Pregunta:")
68
+
69
+ if st.button("Obtener Respuesta"):
70
+ # Translate the question to English
71
+ translated_input = translate_text(user_input, target_language='en')
72
+
73
+ # Clean the translated text of special characters
74
+ cleaned_input = clean_text(translated_input)
75
+
76
+ # Exit if the cleaned text is empty
77
+ if not cleaned_input:
78
+ st.warning("Texto ingresado no válido. Inténtalo de nuevo.")
79
+ st.stop()
80
+
81
+ # Add the command to act as an INIF informative chatbot
82
+ cleaned_input = (
83
+ "Acts as an informative data analyst female chatbot called L.A.U.R.A working for a fraud prevention company called the National Institute of Fraud Research and Prevention (INIF). www.inif.com.co"
84
+ " Your task is to answer the following question. do not put or use fictional information, only give accurate and true information, as a scientist will do it"
85
+ " if you dont know something, just say it, dont invent nothing. The question you must respond to is as follows: " + cleaned_input
86
+ )
87
+
88
+ # Generate the response
89
+ translated_output = generate_response(cleaned_input, model)
90
+
91
+ # Display the generated response in green or red based on the content
92
+ if "La pregunta que está realizando puede que vaya en contra de las políticas de Google Bard e INIF." in translated_output:
93
+ st.error(translated_output)
94
+ else:
95
+ st.success(translated_output)
96
+
97
+ if __name__ == "__main__":
98
+ main()