Spaces:
Sleeping
Sleeping
#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 spacy | |
from spacy import displacy | |
import spacy_streamlit | |
import pandas as pd | |
import base64 | |
import re | |
from .morphosyntax_process import ( | |
process_morphosyntactic_input, | |
format_analysis_results, | |
perform_advanced_morphosyntactic_analysis, | |
get_repeated_words_colors, | |
highlight_repeated_words, | |
POS_COLORS, | |
POS_TRANSLATIONS | |
) | |
from ..utils.widget_utils import generate_unique_key | |
from ..database.morphosintax_mongo_db import store_student_morphosyntax_result | |
from ..database.chat_mongo_db import store_chat_history, get_chat_history | |
import logging | |
logger = logging.getLogger(__name__) | |
########################################################################### | |
import streamlit as st | |
from streamlit_float import * | |
from streamlit_antd_components import * | |
from streamlit.components.v1 import html | |
import spacy | |
from spacy import displacy | |
import spacy_streamlit | |
import pandas as pd | |
import base64 | |
import re | |
def display_morphosyntax_interface(lang_code, nlp_models, morpho_t): | |
try: | |
# CSS para mejorar la estabilidad y diseño | |
st.markdown(""" | |
<style> | |
.stTextArea textarea { | |
font-size: 1rem; | |
line-height: 1.5; | |
padding: 0.5rem; | |
border-radius: 0.375rem; | |
border: 1px solid #e2e8f0; | |
background-color: white; | |
} | |
.original-content { | |
background-color: #f8fafc; | |
padding: 1rem; | |
border-radius: 0.5rem; | |
margin-bottom: 1rem; | |
} | |
.iteration-content { | |
background-color: white; | |
padding: 1rem; | |
border-radius: 0.5rem; | |
border: 1px solid #e2e8f0; | |
} | |
.arc-diagram-container { | |
background-color: white; | |
padding: 1rem; | |
border-radius: 0.5rem; | |
box-shadow: 0 1px 3px rgba(0,0,0,0.1); | |
margin-top: 1rem; | |
} | |
</style> | |
""", unsafe_allow_html=True) | |
# Inicializar el estado | |
if 'morphosyntax_state' not in st.session_state: | |
st.session_state.morphosyntax_state = { | |
'has_original': False, | |
'original_text': '', | |
'original_analysis': None, | |
'current_text': '', | |
'iterations': [], | |
'analysis_count': 0 | |
} | |
# Texto original (si aún no se ha ingresado) | |
if not st.session_state.morphosyntax_state['has_original']: | |
st.markdown("### Original Text") | |
original_text = st.text_area( | |
"Enter your initial text", | |
key="original_text_input", | |
height=150 | |
) | |
col1, col2, col3 = st.columns([2,1,2]) | |
with col1: | |
if st.button( | |
"Set as Original Text", | |
type="primary", | |
use_container_width=True, | |
disabled=not bool(original_text.strip()) | |
): | |
# Procesar texto original | |
doc = nlp_models[lang_code](original_text) | |
analysis = perform_advanced_morphosyntactic_analysis( | |
original_text, | |
nlp_models[lang_code] | |
) | |
# Guardar estado original | |
st.session_state.morphosyntax_state.update({ | |
'has_original': True, | |
'original_text': original_text, | |
'original_analysis': { | |
'doc': doc, | |
'advanced_analysis': analysis | |
} | |
}) | |
# Guardar en base de datos | |
store_student_morphosyntax_result( | |
username=st.session_state.username, | |
text=original_text, | |
arc_diagrams=analysis['arc_diagrams'] | |
) | |
st.rerun() | |
# Mostrar contenido original y área de iteración | |
else: | |
# Sección Original | |
st.markdown("### Original Version") | |
with st.container(): | |
col1, col2 = st.columns([1,1]) | |
with col1: | |
st.markdown("#### Original Text") | |
st.markdown(f"<div class='original-content'>{st.session_state.morphosyntax_state['original_text']}</div>", | |
unsafe_allow_html=True) | |
with col2: | |
st.markdown("#### Original Analysis") | |
display_morphosyntax_results( | |
st.session_state.morphosyntax_state['original_analysis'], | |
lang_code, | |
morpho_t | |
) | |
# Separador | |
st.markdown("---") | |
# Sección de Iteración | |
st.markdown("### Current Iteration") | |
# Campo para la nueva versión | |
iteration_text = st.text_area( | |
"Modify your text", | |
value=st.session_state.morphosyntax_state.get('current_text', | |
st.session_state.morphosyntax_state['original_text']), | |
key=f"iteration_input_{st.session_state.morphosyntax_state['analysis_count']}", | |
height=150 | |
) | |
# Botón de análisis | |
col1, col2, col3 = st.columns([2,1,2]) | |
with col1: | |
analyze_button = st.button( | |
"Analyze Changes", | |
type="primary", | |
icon="🔍", | |
key=f"analyze_{st.session_state.morphosyntax_state['analysis_count']}", | |
disabled=not bool(iteration_text.strip()), | |
use_container_width=True | |
) | |
# Procesar nueva iteración | |
if analyze_button and iteration_text.strip(): | |
with st.spinner("Processing changes..."): | |
# Realizar análisis | |
doc = nlp_models[lang_code](iteration_text) | |
analysis = perform_advanced_morphosyntactic_analysis( | |
iteration_text, | |
nlp_models[lang_code] | |
) | |
# Actualizar estado | |
current_analysis = { | |
'doc': doc, | |
'advanced_analysis': analysis | |
} | |
# Guardar iteración | |
st.session_state.morphosyntax_state['iterations'].append({ | |
'text': iteration_text, | |
'analysis': current_analysis, | |
'timestamp': pd.Timestamp.now() | |
}) | |
st.session_state.morphosyntax_state['current_text'] = iteration_text | |
st.session_state.morphosyntax_state['analysis_count'] += 1 | |
# Guardar en base de datos | |
store_student_morphosyntax_result( | |
username=st.session_state.username, | |
text=iteration_text, | |
arc_diagrams=analysis['arc_diagrams'] | |
) | |
# Mostrar análisis actual | |
st.markdown("#### Current Analysis") | |
display_morphosyntax_results( | |
current_analysis, | |
lang_code, | |
morpho_t | |
) | |
# Mostrar historial de iteraciones | |
if st.session_state.morphosyntax_state['iterations']: | |
with st.expander("View Iteration History"): | |
for idx, iteration in enumerate(reversed(st.session_state.morphosyntax_state['iterations']), 1): | |
st.markdown(f"**Iteration {idx} - {iteration['timestamp'].strftime('%H:%M:%S')}**") | |
st.markdown(f"```\n{iteration['text']}\n```") | |
display_morphosyntax_results( | |
iteration['analysis'], | |
lang_code, | |
morpho_t | |
) | |
st.markdown("---") | |
except Exception as e: | |
logger.error(f"Error general en display_morphosyntax_interface: {str(e)}") | |
st.error("Se produjo un error. Por favor, intente de nuevo.") | |
# El resto del código permanece igual... | |
#########################################################################3 | |
def display_morphosyntax_results(result, lang_code, morpho_t): | |
""" | |
Muestra solo el análisis sintáctico con diagramas de arco. | |
""" | |
if result is None: | |
st.warning(morpho_t.get('no_results', 'No results available')) | |
return | |
doc = result['doc'] | |
# Análisis sintáctico (diagramas de arco) | |
st.markdown(f"### {morpho_t.get('arc_diagram', 'Syntactic analysis: Arc diagram')}") | |
with st.container(): | |
sentences = list(doc.sents) | |
for i, sent in enumerate(sentences): | |
with st.container(): | |
st.subheader(f"{morpho_t.get('sentence', 'Sentence')} {i+1}") | |
try: | |
html = displacy.render(sent, style="dep", options={ | |
"distance": 100, | |
"arrow_spacing": 20, | |
"word_spacing": 30 | |
}) | |
# Ajustar dimensiones del SVG | |
html = html.replace('height="375"', 'height="200"') | |
html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html) | |
html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"', | |
lambda m: f'<g transform="translate({m.group(1)},50)"', html) | |
# Envolver en un div con clase para estilos | |
html = f'<div class="arc-diagram-container">{html}</div>' | |
st.write(html, unsafe_allow_html=True) | |
except Exception as e: | |
logger.error(f"Error rendering sentence {i}: {str(e)}") | |
st.error(f"Error displaying diagram for sentence {i+1}") |