File size: 12,559 Bytes
21661b7 488899f 21661b7 488899f 21661b7 488899f 21661b7 488899f 21661b7 488899f 21661b7 488899f 21661b7 488899f 21661b7 488899f 21661b7 488899f dfee16e 21661b7 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 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 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 |
#modules/morphosyntax/morphosyntax_interface.py
import streamlit as st
from streamlit_float import *
from streamlit_antd_components import *
from streamlit.components.v1 import html
import base64
from .morphosyntax_process import process_morphosyntactic_input
from ..chatbot.chatbot import initialize_chatbot
from ..utils.widget_utils import generate_unique_key
from ..database.morphosintax_mongo_db import store_student_morphosyntax_result
from ..database.chat_db import store_chat_history
from ..database.morphosintaxis_export import export_user_interactions
import logging
logger = logging.getLogger(__name__)
def display_morphosyntax_analysis_interface(nlp_models, lang_code):
translations = {
'es': {
'title': "AIdeaText - Análisis morfológico y sintáctico",
'input_label': "Ingrese un texto para analizar (máximo 5,000 palabras",
'input_placeholder': "Esta funcionalidad le ayudará con dos competencias:\n"
"[1] \"Escribe diversos tipos de textos en su lengua materna\"\n"
"[2] \"Lee diversos tipos de textos escritos en su lengua materna\"\n\n"
"Ingrese su texto aquí para analizar...",
'analyze_button': "Analizar texto",
'repeated_words': "Palabras repetidas",
'legend': "Leyenda: Categorías gramaticales",
'arc_diagram': "Análisis sintáctico: Diagrama de arco",
'sentence': "Oración",
'success_message': "Análisis guardado correctamente.",
'error_message': "Hubo un problema al guardar el análisis. Por favor, inténtelo de nuevo.",
'warning_message': "Por favor, ingrese un texto para analizar.",
'initial_message': "Ingrese un texto y presione 'Analizar texto' para comenzar.",
'no_results': "No hay resultados disponibles. Por favor, realice un análisis primero.",
'pos_analysis': "Análisis de categorías gramaticales",
'morphological_analysis': "Análisis morfológico",
'sentence_structure': "Estructura de oraciones",
'word': "Palabra",
'count': "Cantidad",
'percentage': "Porcentaje",
'examples': "Ejemplos",
'lemma': "Lema",
'tag': "Etiqueta",
'dep': "Dependencia",
'morph': "Morfología",
'root': "Raíz",
'subjects': "Sujetos",
'objects': "Objetos",
'verbs': "Verbos",
'grammatical_category': "Categoría gramatical",
'dependency': "Dependencia",
'morphology': "Morfología"
},
'en': {
'title': "AIdeaText - Morphological and Syntactic Analysis",
'input_label': "Enter a text to analyze (max 5,000 words):",
'input_placeholder': "This functionality will help you with two competencies:\n"
"[1] \"Write various types of texts in your native language\"\n"
"[2] \"Read various types of written texts in your native language\"\n\n"
"Enter your text here to analyze...",
'analyze_button': "Analyze text",
'repeated_words': "Repeated words",
'legend': "Legend: Grammatical categories",
'arc_diagram': "Syntactic analysis: Arc diagram",
'sentence': "Sentence",
'success_message': "Analysis saved successfully.",
'error_message': "There was a problem saving the analysis. Please try again.",
'warning_message': "Please enter a text to analyze.",
'initial_message': "Enter a text and press 'Analyze text' to start.",
'no_results': "No results available. Please perform an analysis first.",
'pos_analysis': "Part of Speech Analysis",
'morphological_analysis': "Morphological Analysis",
'sentence_structure': "Sentence Structure",
'word': "Word",
'count': "Count",
'percentage': "Percentage",
'examples': "Examples",
'lemma': "Lemma",
'tag': "Tag",
'dep': "Dependency",
'morph': "Morphology",
'root': "Root",
'subjects': "Subjects",
'objects': "Objects",
'verbs': "Verbs",
'grammatical_category': "Grammatical category",
'dependency': "Dependency",
'morphology': "Morphology"
},
'fr': {
'title': "AIdeaText - Analyse morphologique et syntaxique",
'input_label': "Entrez un texte à analyser (max 5 000 mots) :",
'input_placeholder': "Cette fonctionnalité vous aidera avec deux compétences :\n"
"[1] \"Écrire divers types de textes dans votre langue maternelle\"\n"
"[2] \"Lire divers types de textes écrits dans votre langue maternelle\"\n\n"
"Entrez votre texte ici pour l'analyser...",
'analyze_button': "Analyser le texte",
'repeated_words': "Mots répétés",
'legend': "Légende : Catégories grammaticales",
'arc_diagram': "Analyse syntaxique : Diagramme en arc",
'sentence': "Phrase",
'success_message': "Analyse enregistrée avec succès.",
'error_message': "Un problème est survenu lors de l'enregistrement de l'analyse. Veuillez réessayer.",
'warning_message': "Veuillez entrer un texte à analyser.",
'initial_message': "Entrez un texte et appuyez sur 'Analyser le texte' pour commencer.",
'no_results': "Aucun résultat disponible. Veuillez d'abord effectuer une analyse.",
'pos_analysis': "Analyse des parties du discours",
'morphological_analysis': "Analyse morphologique",
'sentence_structure': "Structure des phrases",
'word': "Mot",
'count': "Nombre",
'percentage': "Pourcentage",
'examples': "Exemples",
'lemma': "Lemme",
'tag': "Étiquette",
'dep': "Dépendance",
'morph': "Morphologie",
'root': "Racine",
'subjects': "Sujets",
'objects': "Objets",
'verbs': "Verbes",
'grammatical_category': "Catégorie grammaticale",
'dependency': "Dépendance",
'morphology': "Morphologie"
}
}
t = translations[lang_code]
input_key = f"morphosyntax_input_{lang_code}"
if input_key not in st.session_state:
st.session_state[input_key] = ""
sentence_input = st.text_area(
t['input_label'],
height=150,
placeholder=t['input_placeholder'],
value=st.session_state[input_key],
key=f"text_area_{lang_code}",
on_change=lambda: setattr(st.session_state, input_key, st.session_state[f"text_area_{lang_code}"])
)
if st.button(t['analyze_button'], key=f"analyze_button_{lang_code}"):
current_input = st.session_state[input_key]
if current_input:
doc = nlp_models[lang_code](current_input)
# Análisis morfosintáctico avanzado
advanced_analysis = perform_advanced_morphosyntactic_analysis(current_input, nlp_models[lang_code])
# Guardar el resultado en el estado de la sesión
st.session_state.morphosyntax_result = {
'doc': doc,
'advanced_analysis': advanced_analysis
}
# Mostrar resultados
display_morphosyntax_results(st.session_state.morphosyntax_result, lang_code, t)
# Guardar resultados
if store_morphosyntax_result(
st.session_state.username,
current_input,
get_repeated_words_colors(doc),
advanced_analysis['arc_diagram'],
advanced_analysis['pos_analysis'],
advanced_analysis['morphological_analysis'],
advanced_analysis['sentence_structure']
):
st.success(t['success_message'])
else:
st.error(t['error_message'])
else:
st.warning(t['warning_message'])
elif 'morphosyntax_result' in st.session_state and st.session_state.morphosyntax_result is not None:
# Si hay un resultado guardado, mostrarlo
display_morphosyntax_results(st.session_state.morphosyntax_result, lang_code, t)
else:
st.info(t['initial_message']) # Añade esta traducción a tu diccionario
'''
if user_input:
# Añadir el mensaje del usuario al historial
st.session_state.morphosyntax_chat_history.append({"role": "user", "content": user_input})
# Procesar el input del usuario nuevo al 26-9-2024
response, visualizations, result = process_morphosyntactic_input(user_input, lang_code, nlp_models, t)
# Mostrar indicador de carga
with st.spinner(t.get('processing', 'Processing...')):
try:
# Procesar el input del usuario
response, visualizations, result = process_morphosyntactic_input(user_input, lang_code, nlp_models, t)
# Añadir la respuesta al historial
message = {
"role": "assistant",
"content": response
}
if visualizations:
message["visualizations"] = visualizations
st.session_state.morphosyntax_chat_history.append(message)
# Mostrar la respuesta más reciente
with st.chat_message("assistant"):
st.write(response)
if visualizations:
for i, viz in enumerate(visualizations):
st.markdown(f"**Oración {i+1} del párrafo analizado**")
st.components.v1.html(
f"""
<div style="width: 100%; overflow-x: auto; white-space: nowrap;">
<div style="min-width: 1200px;">
{viz}
</div>
</div>
""",
height=350,
scrolling=True
)
if i < len(visualizations) - 1:
st.markdown("---") # Separador entre diagramas
# Si es un análisis, guardarlo en la base de datos
if user_input.startswith('/analisis_morfosintactico') and result:
store_morphosyntax_result(
st.session_state.username,
user_input.split('[', 1)[1].rsplit(']', 1)[0], # texto analizado
result.get('repeated_words', {}),
visualizations,
result.get('pos_analysis', []),
result.get('morphological_analysis', []),
result.get('sentence_structure', [])
)
except Exception as e:
st.error(f"{t['error_processing']}: {str(e)}")
# Forzar la actualización de la interfaz
st.rerun()
# Botón para limpiar el historial del chat
if st.button(t['clear_chat'], key=generate_unique_key('morphosyntax', 'clear_chat')):
st.session_state.morphosyntax_chat_history = []
st.rerun()
'''
'''
############ MODULO PARA DEPURACIÓN Y PRUEBAS #####################################################
def display_morphosyntax_interface(lang_code, nlp_models, t):
st.subheader(t['morpho_title'])
text_input = st.text_area(
t['warning_message'],
height=150,
key=generate_unique_key("morphosyntax", "text_area")
)
if st.button(
t['results_title'],
key=generate_unique_key("morphosyntax", "analyze_button")
):
if text_input:
# Aquí iría tu lógica de análisis morfosintáctico
# Por ahora, solo mostraremos un mensaje de placeholder
st.info(t['analysis_placeholder'])
else:
st.warning(t['no_text_warning'])
###
#################################################
'''
|