Update modules/ui.py
Browse files- modules/ui.py +100 -19
modules/ui.py
CHANGED
@@ -1,59 +1,140 @@
|
|
1 |
# modules/ui.py
|
2 |
-
|
3 |
import streamlit as st
|
4 |
-
from
|
|
|
|
|
5 |
from .morpho_analysis import get_repeated_words_colors, highlight_repeated_words, POS_COLORS, POS_TRANSLATIONS
|
6 |
from .syntax_analysis import visualize_syntax
|
7 |
|
|
|
|
|
|
|
|
|
|
|
8 |
def display_chat_interface():
|
9 |
st.markdown("### Chat con AIdeaText")
|
10 |
|
11 |
-
# Initialize chat history if it doesn't exist
|
12 |
if 'chat_history' not in st.session_state:
|
13 |
st.session_state.chat_history = []
|
14 |
|
15 |
-
# Display chat history
|
16 |
for i, (role, text) in enumerate(st.session_state.chat_history):
|
17 |
if role == "user":
|
18 |
st.text_area(f"Tú:", value=text, height=50, key=f"user_message_{i}", disabled=True)
|
19 |
else:
|
20 |
st.text_area(f"AIdeaText:", value=text, height=50, key=f"bot_message_{i}", disabled=True)
|
21 |
|
22 |
-
# User input field
|
23 |
user_input = st.text_input("Escribe tu mensaje aquí:")
|
24 |
|
25 |
if st.button("Enviar"):
|
26 |
if user_input:
|
27 |
-
# Add user message to history
|
28 |
st.session_state.chat_history.append(("user", user_input))
|
29 |
-
|
30 |
-
# Get chatbot response (esta función debe estar definida en otro lugar)
|
31 |
response = get_chatbot_response(user_input)
|
32 |
-
|
33 |
-
# Add chatbot response to history
|
34 |
st.session_state.chat_history.append(("bot", response))
|
35 |
-
|
36 |
-
# Clear input field
|
37 |
st.experimental_rerun()
|
38 |
|
39 |
def display_student_progress(student_data):
|
40 |
st.success("Datos obtenidos exitosamente")
|
41 |
|
42 |
-
# Mostrar estadísticas generales
|
43 |
st.subheader("Estadísticas generales")
|
44 |
st.write(f"Total de entradas: {student_data['entries_count']}")
|
45 |
|
46 |
-
# Mostrar gráfico de conteo de palabras
|
47 |
st.subheader("Conteo de palabras por categoría")
|
48 |
st.bar_chart(student_data['word_count'])
|
49 |
|
50 |
-
# Mostrar entradas recientes
|
51 |
st.subheader("Entradas recientes")
|
52 |
-
for entry in student_data['entries'][:5]:
|
53 |
st.text_area(f"Entrada del {entry['timestamp']}", entry['text'], height=100)
|
54 |
|
55 |
def display_text_analysis_interface(nlp_models, lang_code):
|
56 |
-
|
57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
58 |
|
59 |
-
|
|
|
|
|
|
1 |
# modules/ui.py
|
|
|
2 |
import streamlit as st
|
3 |
+
from spacy import displacy
|
4 |
+
import re
|
5 |
+
from .database import get_student_data, store_analysis_result
|
6 |
from .morpho_analysis import get_repeated_words_colors, highlight_repeated_words, POS_COLORS, POS_TRANSLATIONS
|
7 |
from .syntax_analysis import visualize_syntax
|
8 |
|
9 |
+
def get_chatbot_response(input_text):
|
10 |
+
# Esta función debe ser implementada o importada de otro módulo
|
11 |
+
# Por ahora, retornamos un mensaje genérico
|
12 |
+
return "Lo siento, el chatbot no está disponible en este momento."
|
13 |
+
|
14 |
def display_chat_interface():
|
15 |
st.markdown("### Chat con AIdeaText")
|
16 |
|
|
|
17 |
if 'chat_history' not in st.session_state:
|
18 |
st.session_state.chat_history = []
|
19 |
|
|
|
20 |
for i, (role, text) in enumerate(st.session_state.chat_history):
|
21 |
if role == "user":
|
22 |
st.text_area(f"Tú:", value=text, height=50, key=f"user_message_{i}", disabled=True)
|
23 |
else:
|
24 |
st.text_area(f"AIdeaText:", value=text, height=50, key=f"bot_message_{i}", disabled=True)
|
25 |
|
|
|
26 |
user_input = st.text_input("Escribe tu mensaje aquí:")
|
27 |
|
28 |
if st.button("Enviar"):
|
29 |
if user_input:
|
|
|
30 |
st.session_state.chat_history.append(("user", user_input))
|
|
|
|
|
31 |
response = get_chatbot_response(user_input)
|
|
|
|
|
32 |
st.session_state.chat_history.append(("bot", response))
|
|
|
|
|
33 |
st.experimental_rerun()
|
34 |
|
35 |
def display_student_progress(student_data):
|
36 |
st.success("Datos obtenidos exitosamente")
|
37 |
|
|
|
38 |
st.subheader("Estadísticas generales")
|
39 |
st.write(f"Total de entradas: {student_data['entries_count']}")
|
40 |
|
|
|
41 |
st.subheader("Conteo de palabras por categoría")
|
42 |
st.bar_chart(student_data['word_count'])
|
43 |
|
|
|
44 |
st.subheader("Entradas recientes")
|
45 |
+
for entry in student_data['entries'][:5]:
|
46 |
st.text_area(f"Entrada del {entry['timestamp']}", entry['text'], height=100)
|
47 |
|
48 |
def display_text_analysis_interface(nlp_models, lang_code):
|
49 |
+
translations = {
|
50 |
+
'es': {
|
51 |
+
'title': "AIdeaText - Análisis morfológico y sintáctico",
|
52 |
+
'input_label': "Ingrese un texto para analizar (máx. 5,000 palabras):",
|
53 |
+
'input_placeholder': "El objetivo de esta aplicación es que mejore sus habilidades de redacción. Para ello, después de ingresar su texto y presionar el botón obtendrá tres vistas horizontales. La primera, le indicará las palabras que se repiten por categoría gramátical; la segunda, un diagrama de arco le indicara las conexiones sintácticas en cada oración; y la tercera, es un grafo en el cual visualizara la configuración de su texto.",
|
54 |
+
'analyze_button': "Analizar texto",
|
55 |
+
'repeated_words': "Palabras repetidas",
|
56 |
+
'legend': "Leyenda: Categorías gramaticales",
|
57 |
+
'arc_diagram': "Análisis sintáctico: Diagrama de arco",
|
58 |
+
'network_diagram': "Análisis sintáctico: Diagrama de red",
|
59 |
+
'sentence': "Oración"
|
60 |
+
},
|
61 |
+
'en': {
|
62 |
+
'title': "AIdeaText - Morphological and Syntactic Analysis",
|
63 |
+
'input_label': "Enter a text to analyze (max 5,000 words):",
|
64 |
+
'input_placeholder': "The goal of this app is for you to improve your writing skills. To do this, after entering your text and pressing the button you will get three horizontal views. The first will indicate the words that are repeated by grammatical category; second, an arc diagram will indicate the syntactic connections in each sentence; and the third is a graph in which you will visualize the configuration of your text.",
|
65 |
+
'analyze_button': "Analyze text",
|
66 |
+
'repeated_words': "Repeated words",
|
67 |
+
'legend': "Legend: Grammatical categories",
|
68 |
+
'arc_diagram': "Syntactic analysis: Arc diagram",
|
69 |
+
'network_diagram': "Syntactic analysis: Network diagram",
|
70 |
+
'sentence': "Sentence"
|
71 |
+
},
|
72 |
+
'fr': {
|
73 |
+
'title': "AIdeaText - Analyse morphologique et syntaxique",
|
74 |
+
'input_label': "Entrez un texte à analyser (max 5 000 mots) :",
|
75 |
+
'input_placeholder': "Le but de cette application est d'améliorer vos compétences en rédaction. Pour ce faire, après avoir saisi votre texte et appuyé sur le bouton vous obtiendrez trois vues horizontales. Le premier indiquera les mots répétés par catégorie grammaticale; deuxièmement, un diagramme en arcs indiquera les connexions syntaxiques dans chaque phrase; et le troisième est un graphique dans lequel vous visualiserez la configuration de votre texte.",
|
76 |
+
'analyze_button': "Analyser le texte",
|
77 |
+
'repeated_words': "Mots répétés",
|
78 |
+
'legend': "Légende : Catégories grammaticales",
|
79 |
+
'arc_diagram': "Analyse syntaxique : Diagramme en arc",
|
80 |
+
'network_diagram': "Analyse syntaxique : Diagramme de réseau",
|
81 |
+
'sentence': "Phrase"
|
82 |
+
}
|
83 |
+
}
|
84 |
+
|
85 |
+
t = translations[lang_code]
|
86 |
+
|
87 |
+
if 'input_text' not in st.session_state:
|
88 |
+
st.session_state.input_text = ""
|
89 |
+
|
90 |
+
sentence_input = st.text_area(t['input_label'], height=150, placeholder=t['input_placeholder'], value=st.session_state.input_text)
|
91 |
+
st.session_state.input_text = sentence_input
|
92 |
+
|
93 |
+
if st.button(t['analyze_button']):
|
94 |
+
if sentence_input:
|
95 |
+
doc = nlp_models[lang_code](sentence_input)
|
96 |
+
|
97 |
+
with st.expander(t['repeated_words'], expanded=True):
|
98 |
+
word_colors = get_repeated_words_colors(doc)
|
99 |
+
highlighted_text = highlight_repeated_words(doc, word_colors)
|
100 |
+
st.markdown(highlighted_text, unsafe_allow_html=True)
|
101 |
+
|
102 |
+
st.markdown(f"##### {t['legend']}")
|
103 |
+
legend_html = "<div style='display: flex; flex-wrap: wrap;'>"
|
104 |
+
for pos, color in POS_COLORS.items():
|
105 |
+
if pos in POS_TRANSLATIONS:
|
106 |
+
legend_html += f"<div style='margin-right: 10px;'><span style='background-color: {color}; padding: 2px 5px;'>{POS_TRANSLATIONS[pos]}</span></div>"
|
107 |
+
legend_html += "</div>"
|
108 |
+
st.markdown(legend_html, unsafe_allow_html=True)
|
109 |
+
|
110 |
+
with st.expander(t['arc_diagram'], expanded=True):
|
111 |
+
sentences = list(doc.sents)
|
112 |
+
arc_diagrams = []
|
113 |
+
for i, sent in enumerate(sentences):
|
114 |
+
st.subheader(f"{t['sentence']} {i+1}")
|
115 |
+
html = displacy.render(sent, style="dep", options={"distance": 100})
|
116 |
+
html = html.replace('height="375"', 'height="200"')
|
117 |
+
html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html)
|
118 |
+
html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"', lambda m: f'<g transform="translate({m.group(1)},50)"', html)
|
119 |
+
st.write(html, unsafe_allow_html=True)
|
120 |
+
arc_diagrams.append(html)
|
121 |
+
|
122 |
+
with st.expander(t['network_diagram'], expanded=True):
|
123 |
+
fig = visualize_syntax(sentence_input, nlp_models[lang_code], lang_code)
|
124 |
+
st.pyplot(fig)
|
125 |
+
|
126 |
+
if store_analysis_result(
|
127 |
+
st.session_state.username,
|
128 |
+
sentence_input,
|
129 |
+
word_colors,
|
130 |
+
arc_diagrams,
|
131 |
+
fig
|
132 |
+
):
|
133 |
+
st.success("Análisis guardado correctamente.")
|
134 |
+
else:
|
135 |
+
st.error("Hubo un problema al guardar el análisis. Por favor, inténtelo de nuevo.")
|
136 |
+
st.error(f"Falló el guardado del análisis. Username: {st.session_state.username}")
|
137 |
|
138 |
+
def display_teacher_interface():
|
139 |
+
st.write("Bienvenido, profesor. Aquí podrás ver el progreso de tus estudiantes.")
|
140 |
+
# Aquí puedes agregar la lógica para mostrar el progreso de los estudiantes
|