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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#modules/morphosyntax/morphosyntax_interface.py
|
| 2 |
+
|
| 3 |
+
import streamlit as st
|
| 4 |
+
from streamlit_float import *
|
| 5 |
+
from streamlit_antd_components import *
|
| 6 |
+
from streamlit.components.v1 import html
|
| 7 |
+
import spacy
|
| 8 |
+
from spacy import displacy
|
| 9 |
+
import spacy_streamlit
|
| 10 |
+
import pandas as pd
|
| 11 |
+
import base64
|
| 12 |
+
import re
|
| 13 |
+
|
| 14 |
+
from .morphosyntax_process import (
|
| 15 |
+
process_morphosyntactic_input,
|
| 16 |
+
format_analysis_results,
|
| 17 |
+
perform_advanced_morphosyntactic_analysis,
|
| 18 |
+
get_repeated_words_colors,
|
| 19 |
+
highlight_repeated_words,
|
| 20 |
+
POS_COLORS,
|
| 21 |
+
POS_TRANSLATIONS
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
from ..utils.widget_utils import generate_unique_key
|
| 25 |
+
from ..database.morphosintax_mongo_db import store_student_morphosyntax_result
|
| 26 |
+
from ..database.chat_mongo_db import store_chat_history, get_chat_history
|
| 27 |
+
|
| 28 |
+
import logging
|
| 29 |
+
logger = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def display_morphosyntax_interface(lang_code, nlp_models, morpho_t):
|
| 33 |
+
try:
|
| 34 |
+
# Inicializar el estado si no existe
|
| 35 |
+
if 'morphosyntax_state' not in st.session_state:
|
| 36 |
+
st.session_state.morphosyntax_state = {
|
| 37 |
+
'analysis_count': 0,
|
| 38 |
+
'current_text': '', # Almacenar el texto actual
|
| 39 |
+
'last_analysis': None,
|
| 40 |
+
'needs_update': False # Flag para actualizaci贸n
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
# Campo de entrada de texto que mantiene su valor
|
| 44 |
+
text_key = "morpho_text_input"
|
| 45 |
+
|
| 46 |
+
# Funci贸n para manejar cambios en el texto
|
| 47 |
+
def on_text_change():
|
| 48 |
+
st.session_state.morphosyntax_state['current_text'] = st.session_state[text_key]
|
| 49 |
+
st.session_state.morphosyntax_state['needs_update'] = True
|
| 50 |
+
|
| 51 |
+
# Recuperar el texto anterior si existe
|
| 52 |
+
default_text = st.session_state.morphosyntax_state.get('current_text', '')
|
| 53 |
+
|
| 54 |
+
sentence_input = st.text_area(
|
| 55 |
+
morpho_t.get('morpho_input_label', 'Enter text to analyze'),
|
| 56 |
+
value=default_text, # Usar el texto guardado
|
| 57 |
+
height=150,
|
| 58 |
+
key=text_key,
|
| 59 |
+
on_change=on_text_change,
|
| 60 |
+
placeholder=morpho_t.get('morpho_input_placeholder', 'Enter your text here...')
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# Bot贸n de an谩lisis
|
| 64 |
+
col1, col2, col3 = st.columns([2,1,2])
|
| 65 |
+
with col1:
|
| 66 |
+
analyze_button = st.button(
|
| 67 |
+
morpho_t.get('morpho_analyze_button', 'Analyze Morphosyntax'),
|
| 68 |
+
key=f"morpho_button_{st.session_state.morphosyntax_state['analysis_count']}",
|
| 69 |
+
type="primary",
|
| 70 |
+
icon="馃攳",
|
| 71 |
+
disabled=not bool(sentence_input.strip()),
|
| 72 |
+
use_container_width=True
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
# Procesar an谩lisis solo cuando sea necesario
|
| 76 |
+
if (analyze_button or st.session_state.morphosyntax_state['needs_update']) and sentence_input.strip():
|
| 77 |
+
try:
|
| 78 |
+
with st.spinner(morpho_t.get('processing', 'Processing...')):
|
| 79 |
+
doc = nlp_models[lang_code](sentence_input)
|
| 80 |
+
advanced_analysis = perform_advanced_morphosyntactic_analysis(
|
| 81 |
+
sentence_input,
|
| 82 |
+
nlp_models[lang_code]
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
st.session_state.morphosyntax_result = {
|
| 86 |
+
'doc': doc,
|
| 87 |
+
'advanced_analysis': advanced_analysis
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
# Solo guardar en DB si fue un click en el bot贸n
|
| 91 |
+
if analyze_button:
|
| 92 |
+
if store_student_morphosyntax_result(
|
| 93 |
+
username=st.session_state.username,
|
| 94 |
+
text=sentence_input,
|
| 95 |
+
arc_diagrams=advanced_analysis['arc_diagrams']
|
| 96 |
+
):
|
| 97 |
+
st.success(morpho_t.get('success_message', 'Analysis saved successfully'))
|
| 98 |
+
st.session_state.morphosyntax_state['analysis_count'] += 1
|
| 99 |
+
|
| 100 |
+
st.session_state.morphosyntax_state['needs_update'] = False
|
| 101 |
+
|
| 102 |
+
# Mostrar resultados en un contenedor espec铆fico
|
| 103 |
+
with st.container():
|
| 104 |
+
display_morphosyntax_results(
|
| 105 |
+
st.session_state.morphosyntax_result,
|
| 106 |
+
lang_code,
|
| 107 |
+
morpho_t
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
except Exception as e:
|
| 111 |
+
logger.error(f"Error en an谩lisis morfosint谩ctico: {str(e)}")
|
| 112 |
+
st.error(morpho_t.get('error_processing', f'Error processing text: {str(e)}'))
|
| 113 |
+
|
| 114 |
+
# Mostrar resultados previos si existen
|
| 115 |
+
elif 'morphosyntax_result' in st.session_state and st.session_state.morphosyntax_result:
|
| 116 |
+
with st.container():
|
| 117 |
+
display_morphosyntax_results(
|
| 118 |
+
st.session_state.morphosyntax_result,
|
| 119 |
+
lang_code,
|
| 120 |
+
morpho_t
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
except Exception as e:
|
| 124 |
+
logger.error(f"Error general en display_morphosyntax_interface: {str(e)}")
|
| 125 |
+
st.error("Se produjo un error. Por favor, intente de nuevo.")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def display_morphosyntax_results(result, lang_code, morpho_t):
|
| 130 |
+
"""
|
| 131 |
+
Muestra solo el an谩lisis sint谩ctico con diagramas de arco.
|
| 132 |
+
"""
|
| 133 |
+
if result is None:
|
| 134 |
+
st.warning(morpho_t.get('no_results', 'No results available'))
|
| 135 |
+
return
|
| 136 |
+
|
| 137 |
+
doc = result['doc']
|
| 138 |
+
|
| 139 |
+
# An谩lisis sint谩ctico (diagramas de arco)
|
| 140 |
+
st.markdown(f"### {morpho_t.get('arc_diagram', 'Syntactic analysis: Arc diagram')}")
|
| 141 |
+
|
| 142 |
+
with st.container():
|
| 143 |
+
sentences = list(doc.sents)
|
| 144 |
+
for i, sent in enumerate(sentences):
|
| 145 |
+
with st.container():
|
| 146 |
+
st.subheader(f"{morpho_t.get('sentence', 'Sentence')} {i+1}")
|
| 147 |
+
try:
|
| 148 |
+
html = displacy.render(sent, style="dep", options={
|
| 149 |
+
"distance": 100,
|
| 150 |
+
"arrow_spacing": 20,
|
| 151 |
+
"word_spacing": 30
|
| 152 |
+
})
|
| 153 |
+
# Ajustar dimensiones del SVG
|
| 154 |
+
html = html.replace('height="375"', 'height="200"')
|
| 155 |
+
html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html)
|
| 156 |
+
html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"',
|
| 157 |
+
lambda m: f'<g transform="translate({m.group(1)},50)"', html)
|
| 158 |
+
|
| 159 |
+
# Envolver en un div con clase para estilos
|
| 160 |
+
html = f'<div class="arc-diagram-container">{html}</div>'
|
| 161 |
+
st.write(html, unsafe_allow_html=True)
|
| 162 |
+
except Exception as e:
|
| 163 |
+
logger.error(f"Error rendering sentence {i}: {str(e)}")
|
| 164 |
+
st.error(f"Error displaying diagram for sentence {i+1}")
|