File size: 20,598 Bytes
21661b7
 
 
 
 
58c9737
 
 
 
21661b7
ccf055d
988c451
4fe3aeb
a90c0ad
 
7563cd4
 
 
 
 
 
a90c0ad
988c451
21661b7
a90c0ad
 
21661b7
 
 
 
 
 
 
34ce6da
5142737
 
c0d0a84
 
 
 
5142737
c0d0a84
1396937
c0d0a84
 
488899f
 
 
21661b7
c0d0a84
488899f
c0d0a84
488899f
c0d0a84
488899f
cf5b64f
 
488899f
21661b7
c0d0a84
 
cf5b64f
 
c0d0a84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d4a6cb3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0d0a84
cf5b64f
c0d0a84
 
 
 
 
cf5b64f
c0d0a84
cf5b64f
f90de2b
 
a90c0ad
ac1df45
0db7797
 
 
 
 
 
 
 
 
a90c0ad
28786d1
a90c0ad
 
 
 
 
28786d1
4cb0838
a90c0ad
 
 
 
 
 
 
28786d1
a90c0ad
4cb0838
a90c0ad
 
 
 
4cb0838
a90c0ad
 
28786d1
 
 
 
 
a90c0ad
 
 
 
 
 
 
eefaf48
a90c0ad
 
 
 
 
 
 
ccd38a8
 
 
 
a90c0ad
ccd38a8
a90c0ad
 
 
 
ccd38a8
36b3639
a90c0ad
e0f1eca
36b3639
e1b8d97
36b3639
 
 
 
 
e1b8d97
 
36b3639
1dc68d7
e1b8d97
36b3639
 
 
 
39f1b08
 
36b3639
39f1b08
 
 
 
 
 
 
 
 
 
 
 
36b3639
39f1b08
 
 
 
 
 
 
 
 
 
 
36b3639
39f1b08
 
 
 
 
 
 
 
 
36b3639
39f1b08
36b3639
39f1b08
 
36b3639
39f1b08
 
 
 
 
 
 
 
 
 
36b3639
39f1b08
 
 
 
 
 
 
36b3639
39f1b08
 
 
 
 
 
 
 
36b3639
39f1b08
 
 
 
36b3639
39f1b08
 
36b3639
39f1b08
 
1dc68d7
a90c0ad
 
ccd38a8
a90c0ad
 
 
ccd38a8
a90c0ad
 
 
 
 
 
 
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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#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

# Importar desde morphosyntax_process.py
from .morphosyntax_process import (
    process_morphosyntactic_input,
    format_analysis_results,
    perform_advanced_morphosyntactic_analysis,  # Añadir esta importación
    get_repeated_words_colors,                  # Y estas también
    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_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
    Args:
        lang_code: Código del idioma actual
        nlp_models: Modelos de spaCy cargados
        t: Diccionario de traducciones
    """
    # Obtener el diccionario de traducciones morfosintácticas
    morpho_t = t.get('MORPHOSYNTACTIC', {})
    
    # Inicializar el estado de la entrada
    input_key = f"morphosyntax_input_{lang_code}"
    if input_key not in st.session_state:
        st.session_state[input_key] = ""

    # Campo de entrada de texto
    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}",
        on_change=lambda: setattr(st.session_state, input_key, st.session_state[f"text_area_{lang_code}"])
    )

    # Botón de análisis
    if st.button(morpho_t.get('analyze_button', 'Analyze text'), key=f"analyze_button_{lang_code}"):
        current_input = st.session_state[input_key]
        if current_input:
            try:
                # Procesar el texto
                doc = nlp_models[lang_code](current_input)
                
                # Realizar análisis morfosintáctico
                advanced_analysis = perform_advanced_morphosyntactic_analysis(
                    current_input, 
                    nlp_models[lang_code]
                )    

                # Guardar 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, 
                    morpho_t  # Pasar morpho_t en lugar de t
                )

                # Guardar en la base de datos
                try:
                    if current_input:
                        # Extraer los diagramas de arco del análisis
                        doc = nlp_models[lang_code](current_input)
                        advanced_analysis = perform_advanced_morphosyntactic_analysis(current_input, nlp_models[lang_code])
                
                        # Guardar el análisis
                        if store_student_morphosyntax_result(
                            username=st.session_state.username,
                            text=current_input,
                            arc_diagrams=advanced_analysis['arc_diagram']
                        ):
                            st.success(morpho_t.get('success_message', 'Analysis saved successfully'))
                        else:
                            st.error(morpho_t.get('error_message', 'Error saving analysis'))
                
                 except Exception as e:
                     st.error(morpho_t.get('error_processing', f'Error processing text: {str(e)}'))
                 else:
                     st.warning(morpho_t.get('warning_message', 'Please enter a text to analyze'))
    
    # Mostrar resultados previos si existen
    elif 'morphosyntax_result' in st.session_state and st.session_state.morphosyntax_result is not None:
        display_morphosyntax_results(
            st.session_state.morphosyntax_result, 
            lang_code, 
            morpho_t  # Pasar morpho_t en lugar de t
        )
    else:
        st.info(morpho_t.get('morpho_initial_message', 'Enter text to begin analysis'))       


############################################################################################################
def display_morphosyntax_results(result, lang_code, t):
    """
    Muestra los resultados del análisis morfosintáctico.
    Args:
        result: Resultado del análisis
        lang_code: Código del idioma
        t: Diccionario de traducciones
    """
    # Obtener el diccionario de traducciones morfosintácticas
    morpho_t = t.get('MORPHOSYNTACTIC', {})
    
    if result is None:
        st.warning(morpho_t.get('no_results', 'No results available'))
        return

    doc = result['doc']
    advanced_analysis = result['advanced_analysis']
    
    # Mostrar leyenda
    st.markdown(f"##### {morpho_t.get('legend', 'Legend: Grammatical categories')}")
    legend_html = "<div style='display: flex; flex-wrap: wrap;'>"
    for pos, color in POS_COLORS.items():
        if pos in POS_TRANSLATIONS[lang_code]:
            legend_html += f"<div style='margin-right: 10px;'><span style='background-color: {color}; padding: 2px 5px;'>{POS_TRANSLATIONS[lang_code][pos]}</span></div>"
    legend_html += "</div>"
    st.markdown(legend_html, unsafe_allow_html=True)

    # Mostrar análisis de palabras repetidas
    word_colors = get_repeated_words_colors(doc)
    with st.expander(morpho_t.get('repeated_words', 'Repeated words'), expanded=True):
        highlighted_text = highlight_repeated_words(doc, word_colors)
        st.markdown(highlighted_text, unsafe_allow_html=True)
    
    # Mostrar estructura de oraciones
    with st.expander(morpho_t.get('sentence_structure', 'Sentence structure'), expanded=True):
        for i, sent_analysis in enumerate(advanced_analysis['sentence_structure']):
            sentence_str = (
                f"**{morpho_t.get('sentence', 'Sentence')} {i+1}** "  # Aquí está el cambio
                f"{morpho_t.get('root', 'Root')}: {sent_analysis['root']} ({sent_analysis['root_pos']}) -- "  # Y aquí
                f"{morpho_t.get('subjects', 'Subjects')}: {', '.join(sent_analysis['subjects'])} -- "  # Y aquí
                f"{morpho_t.get('objects', 'Objects')}: {', '.join(sent_analysis['objects'])} -- "  # Y aquí
                f"{morpho_t.get('verbs', 'Verbs')}: {', '.join(sent_analysis['verbs'])}"  # Y aquí
            )
            st.markdown(sentence_str)

    # Mostrar análisis de categorías gramaticales # Mostrar análisis morfológico
    col1, col2 = st.columns(2)
    
    with col1:
        with st.expander(morpho_t.get('pos_analysis', 'Part of speech'), expanded=True):
            pos_df = pd.DataFrame(advanced_analysis['pos_analysis'])
            
            # Traducir las etiquetas POS a sus nombres en el idioma seleccionado
            pos_df['pos'] = pos_df['pos'].map(lambda x: POS_TRANSLATIONS[lang_code].get(x, x))
            
            # Renombrar las columnas para mayor claridad
            pos_df = pos_df.rename(columns={
                'pos': morpho_t.get('grammatical_category', 'Grammatical category'),
                'count': morpho_t.get('count', 'Count'),
                'percentage': morpho_t.get('percentage', 'Percentage'),
                'examples': morpho_t.get('examples', 'Examples')
            })
                        
            # Mostrar el dataframe
            st.dataframe(pos_df)
    
    with col2:
        with st.expander(morpho_t.get('morphological_analysis', 'Morphological Analysis'), expanded=True):
            # 1. Crear el DataFrame inicial
            morph_df = pd.DataFrame(advanced_analysis['morphological_analysis'])
            
            # 2. Primero renombrar las columnas usando las traducciones de la interfaz
            column_mapping = {
                'text': morpho_t.get('word', 'Word'),
                'lemma': morpho_t.get('lemma', 'Lemma'),
                'pos': morpho_t.get('grammatical_category', 'Grammatical category'),
                'dep': morpho_t.get('dependency', 'Dependency'),
                'morph': morpho_t.get('morphology', 'Morphology')
            }
            
            # 3. Aplicar el renombrado
            morph_df = morph_df.rename(columns=column_mapping)
            
            # 4. Traducir las categorías gramaticales usando POS_TRANSLATIONS global
            grammatical_category = morpho_t.get('grammatical_category', 'Grammatical category')
            morph_df[grammatical_category] = morph_df[grammatical_category].map(lambda x: POS_TRANSLATIONS[lang_code].get(x, x))
    
            # 2.2 Traducir dependencias usando traducciones específicas
            dep_translations = {
                    
                'es': {
                    'ROOT': 'RAÍZ', 'nsubj': 'sujeto nominal', 'obj': 'objeto', 'iobj': 'objeto indirecto',
                    'csubj': 'sujeto clausal', 'ccomp': 'complemento clausal', 'xcomp': 'complemento clausal abierto',
                    'obl': 'oblicuo', 'vocative': 'vocativo', 'expl': 'expletivo', 'dislocated': 'dislocado',
                    'advcl': 'cláusula adverbial', 'advmod': 'modificador adverbial', 'discourse': 'discurso',
                    'aux': 'auxiliar', 'cop': 'cópula', 'mark': 'marcador', 'nmod': 'modificador nominal',
                    'appos': 'aposición', 'nummod': 'modificador numeral', 'acl': 'cláusula adjetiva',
                    'amod': 'modificador adjetival', 'det': 'determinante', 'clf': 'clasificador',
                    'case': 'caso', 'conj': 'conjunción', 'cc': 'coordinante', 'fixed': 'fijo',
                    'flat': 'plano', 'compound': 'compuesto', 'list': 'lista', 'parataxis': 'parataxis',
                    'orphan': 'huérfano', 'goeswith': 'va con', 'reparandum': 'reparación', 'punct': 'puntuación'
                },
                    
                'en': {
                    'ROOT': 'ROOT', 'nsubj': 'nominal subject', 'obj': 'object',
                    'iobj': 'indirect object', 'csubj': 'clausal subject', 'ccomp': 'clausal complement', 'xcomp': 'open clausal complement',
                    'obl': 'oblique', 'vocative': 'vocative', 'expl': 'expletive', 'dislocated': 'dislocated', 'advcl': 'adverbial clause modifier',
                    'advmod': 'adverbial modifier', 'discourse': 'discourse element', 'aux': 'auxiliary', 'cop': 'copula', 'mark': 'marker',
                    'nmod': 'nominal modifier', 'appos': 'appositional modifier', 'nummod': 'numeric modifier', 'acl': 'clausal modifier of noun',
                    'amod': 'adjectival modifier', 'det': 'determiner', 'clf': 'classifier', 'case': 'case marking',
                    'conj': 'conjunct', 'cc': 'coordinating conjunction', 'fixed': 'fixed multiword expression',
                    'flat': 'flat multiword expression', 'compound': 'compound', 'list': 'list', 'parataxis': 'parataxis', 'orphan': 'orphan',
                    'goeswith': 'goes with', 'reparandum': 'reparandum', 'punct': 'punctuation'
                },
                    
                'fr': {
                    'ROOT': 'RACINE', 'nsubj': 'sujet nominal', 'obj': 'objet', 'iobj': 'objet indirect',
                    'csubj': 'sujet phrastique', 'ccomp': 'complément phrastique', 'xcomp': 'complément phrastique ouvert', 'obl': 'oblique',
                    'vocative': 'vocatif', 'expl': 'explétif', 'dislocated': 'disloqué', 'advcl': 'clause adverbiale', 'advmod': 'modifieur adverbial',
                    'discourse': 'élément de discours', 'aux': 'auxiliaire', 'cop': 'copule', 'mark': 'marqueur', 'nmod': 'modifieur nominal',
                    'appos': 'apposition', 'nummod': 'modifieur numéral', 'acl': 'clause relative', 'amod': 'modifieur adjectival', 'det': 'déterminant',
                    'clf': 'classificateur', 'case': 'marqueur de cas', 'conj': 'conjonction', 'cc': 'coordination', 'fixed': 'expression figée',
                    'flat': 'construction plate', 'compound': 'composé', 'list': 'liste', 'parataxis': 'parataxe', 'orphan': 'orphelin',
                    'goeswith': 'va avec', 'reparandum': 'réparation', 'punct': 'ponctuation'
                }
            }
    
            dependency = morpho_t.get('dependency', 'Dependency')
            morph_df[dependency] = morph_df[dependency].map(lambda x: dep_translations[lang_code].get(x, x))
                
            morph_translations = {
                'es': {
                    'Gender': 'Género', 'Number': 'Número', 'Case': 'Caso', 'Definite': 'Definido',
                    'PronType': 'Tipo de Pronombre', 'Person': 'Persona', 'Mood': 'Modo',
                    'Tense': 'Tiempo', 'VerbForm': 'Forma Verbal', 'Voice': 'Voz',
                    'Fem': 'Femenino', 'Masc': 'Masculino', 'Sing': 'Singular', 'Plur': 'Plural',
                    'Ind': 'Indicativo', 'Sub': 'Subjuntivo', 'Imp': 'Imperativo', 'Inf': 'Infinitivo',
                    'Part': 'Participio', 'Ger': 'Gerundio', 'Pres': 'Presente', 'Past': 'Pasado',
                    'Fut': 'Futuro', 'Perf': 'Perfecto', 'Imp': 'Imperfecto'
                },
                    
                'en': {
                    'Gender': 'Gender', 'Number': 'Number', 'Case': 'Case', 'Definite': 'Definite', 'PronType': 'Pronoun Type', 'Person': 'Person',
                    'Mood': 'Mood', 'Tense': 'Tense', 'VerbForm': 'Verb Form', 'Voice': 'Voice',
                    'Fem': 'Feminine', 'Masc': 'Masculine', 'Sing': 'Singular', 'Plur': 'Plural', 'Ind': 'Indicative',
                    'Sub': 'Subjunctive', 'Imp': 'Imperative', 'Inf': 'Infinitive', 'Part': 'Participle',
                    'Ger': 'Gerund', 'Pres': 'Present', 'Past': 'Past', 'Fut': 'Future', 'Perf': 'Perfect', 'Imp': 'Imperfect'
                },
                    
                'fr': {
                    'Gender': 'Genre', 'Number': 'Nombre', 'Case': 'Cas', 'Definite': 'Défini', 'PronType': 'Type de Pronom',
                    'Person': 'Personne', 'Mood': 'Mode', 'Tense': 'Temps', 'VerbForm': 'Forme Verbale', 'Voice': 'Voix',
                    'Fem': 'Féminin', 'Masc': 'Masculin', 'Sing': 'Singulier', 'Plur': 'Pluriel', 'Ind': 'Indicatif',
                    'Sub': 'Subjonctif', 'Imp': 'Impératif', 'Inf': 'Infinitif', 'Part': 'Participe',
                    'Ger': 'Gérondif', 'Pres': 'Présent', 'Past': 'Passé', 'Fut': 'Futur', 'Perf': 'Parfait', 'Imp': 'Imparfait'
                }
            }            
    
            def translate_morph(morph_string, lang_code):
                for key, value in morph_translations[lang_code].items():
                    morph_string = morph_string.replace(key, value)
                return morph_string
                
            morphology = morpho_t.get('morphology', 'Morphology')
            morph_df[morphology] = morph_df[morphology].apply(lambda x: translate_morph(x, lang_code))
                
            # 7. Mostrar el DataFrame
            st.dataframe(morph_df)

            
    # Mostrar diagramas de arco (código existente)
    with st.expander(morpho_t.get('arc_diagram', 'Syntactic analysis: Arc diagram'), expanded=True):
        sentences = list(doc.sents)
        arc_diagrams = []
        for i, sent in enumerate(sentences):
            st.subheader(f"{morpho_t.get('sentence', 'Sentence')} {i+1}")
            html = displacy.render(sent, style="dep", options={"distance": 100})
            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)
            st.write(html, unsafe_allow_html=True)
            arc_diagrams.append(html)


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