File size: 7,030 Bytes
21661b7
 
 
 
 
 
988c451
71a69e2
988c451
21661b7
 
 
 
 
 
 
 
34ce6da
5142737
 
 
1396937
988c451
21661b7
488899f
 
 
21661b7
488899f
1396937
488899f
1396937
488899f
988c451
488899f
21661b7
1396937
988c451
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
488899f
988c451
488899f
1396937
488899f
988c451
 
 
 
 
 
 
 
 
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
#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, format_analysis_results

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_interface(lang_code, nlp_models, t):
    """
    Interfaz para el análisis morfosintáctico
    """
    morpho_t = t.get('MORPHOSYNTACTIC', {})
    st.title(morpho_t.get('title', 'AIdeaText - Morphological Analysis'))

    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(
        morpho_t.get('morpho_input_label', 'Enter text to analyze:'),
        height=150,
        placeholder=morpho_t.get('morpho_input_placeholder', 'Enter your text here...'),
        value=st.session_state[input_key],
        key=f"text_area_{lang_code}"
    )

    if st.button(morpho_t.get('analyze_button', 'Analyze'), key=f"analyze_button_{lang_code}"):
        if sentence_input:
            # Usar el proceso morfosintáctico actualizado
            result = process_morphosyntactic_input(
                sentence_input,
                lang_code,
                nlp_models,
                t
            )

            if result['success']:
                # Formatear y mostrar resultados
                formatted_results = format_analysis_results(result, t)
                
                # Mostrar texto resaltado si está disponible
                if formatted_results['highlighted_text']:
                    st.markdown(formatted_results['highlighted_text'], unsafe_allow_html=True)
                
                # Mostrar el análisis formateado
                st.markdown(formatted_results['formatted_text'])
                
                # Mostrar visualizaciones
                if formatted_results['visualizations']:
                    for i, viz in enumerate(formatted_results['visualizations']):
                        st.markdown(f"**{morpho_t.get('sentence', 'Sentence')} {i+1}**")
                        st.components.v1.html(viz, height=370, scrolling=True)
                        if i < len(formatted_results['visualizations']) - 1:
                            st.markdown("---")
            else:
                st.error(result['message'])
        else:
            st.warning(morpho_t.get('warning_message', 'Please enter a text to analyze.'))

    # Botón de exportación
    if st.button(morpho_t.get('export_button', 'Export Analysis')):
        pdf_buffer = export_user_interactions(st.session_state.username, 'morphosyntax')
        st.download_button(
            label=morpho_t.get('download_pdf', 'Download PDF'),
            data=pdf_buffer,
            file_name="morphosyntax_analysis.pdf",
            mime="application/pdf"
        )

'''
    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'])
###
#################################################
'''