Spaces:
Running
Running
Update modules/morphosyntax/morphosyntax_interface.py
Browse files
modules/morphosyntax/morphosyntax_interface.py
CHANGED
|
@@ -6,9 +6,18 @@ from streamlit_antd_components import *
|
|
| 6 |
from streamlit.components.v1 import html
|
| 7 |
import base64
|
| 8 |
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
from ..utils.widget_utils import generate_unique_key
|
|
|
|
|
|
|
| 12 |
from ..database.morphosintax_mongo_db import store_student_morphosyntax_result
|
| 13 |
from ..database.chat_db import store_chat_history
|
| 14 |
from ..database.morphosintaxis_export import export_user_interactions
|
|
@@ -76,6 +85,172 @@ def display_morphosyntax_interface(lang_code, nlp_models, t):
|
|
| 76 |
else:
|
| 77 |
st.info(t['initial_message']) # Añade esta traducción a tu diccionario
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
# Botón de exportación
|
| 81 |
if st.button(morpho_t.get('export_button', 'Export Analysis')):
|
|
|
|
| 6 |
from streamlit.components.v1 import html
|
| 7 |
import base64
|
| 8 |
|
| 9 |
+
# Importar solo desde morphosyntax_process.py
|
| 10 |
+
from .morphosyntax_process import (
|
| 11 |
+
process_morphosyntactic_input,
|
| 12 |
+
format_analysis_results,
|
| 13 |
+
# También exportar desde aquí las constantes necesarias
|
| 14 |
+
POS_COLORS,
|
| 15 |
+
POS_TRANSLATIONS
|
| 16 |
+
)
|
| 17 |
|
| 18 |
from ..utils.widget_utils import generate_unique_key
|
| 19 |
+
|
| 20 |
+
|
| 21 |
from ..database.morphosintax_mongo_db import store_student_morphosyntax_result
|
| 22 |
from ..database.chat_db import store_chat_history
|
| 23 |
from ..database.morphosintaxis_export import export_user_interactions
|
|
|
|
| 85 |
else:
|
| 86 |
st.info(t['initial_message']) # Añade esta traducción a tu diccionario
|
| 87 |
|
| 88 |
+
def display_morphosyntax_results(result, lang_code, t):
|
| 89 |
+
if result is None:
|
| 90 |
+
st.warning(t['no_results']) # Añade esta traducción a tu diccionario
|
| 91 |
+
return
|
| 92 |
+
|
| 93 |
+
doc = result['doc']
|
| 94 |
+
advanced_analysis = result['advanced_analysis']
|
| 95 |
+
|
| 96 |
+
# Mostrar leyenda (código existente)
|
| 97 |
+
st.markdown(f"##### {t['legend']}")
|
| 98 |
+
legend_html = "<div style='display: flex; flex-wrap: wrap;'>"
|
| 99 |
+
for pos, color in POS_COLORS.items():
|
| 100 |
+
if pos in POS_TRANSLATIONS[lang_code]:
|
| 101 |
+
legend_html += f"<div style='margin-right: 10px;'><span style='background-color: {color}; padding: 2px 5px;'>{POS_TRANSLATIONS[lang_code][pos]}</span></div>"
|
| 102 |
+
legend_html += "</div>"
|
| 103 |
+
st.markdown(legend_html, unsafe_allow_html=True)
|
| 104 |
+
|
| 105 |
+
# Mostrar análisis de palabras repetidas (código existente)
|
| 106 |
+
word_colors = get_repeated_words_colors(doc)
|
| 107 |
+
with st.expander(t['repeated_words'], expanded=True):
|
| 108 |
+
highlighted_text = highlight_repeated_words(doc, word_colors)
|
| 109 |
+
st.markdown(highlighted_text, unsafe_allow_html=True)
|
| 110 |
+
|
| 111 |
+
# Mostrar estructura de oraciones
|
| 112 |
+
with st.expander(t['sentence_structure'], expanded=True):
|
| 113 |
+
for i, sent_analysis in enumerate(advanced_analysis['sentence_structure']):
|
| 114 |
+
sentence_str = (
|
| 115 |
+
f"**{t['sentence']} {i+1}** "
|
| 116 |
+
f"{t['root']}: {sent_analysis['root']} ({sent_analysis['root_pos']}) -- "
|
| 117 |
+
f"{t['subjects']}: {', '.join(sent_analysis['subjects'])} -- "
|
| 118 |
+
f"{t['objects']}: {', '.join(sent_analysis['objects'])} -- "
|
| 119 |
+
f"{t['verbs']}: {', '.join(sent_analysis['verbs'])}"
|
| 120 |
+
)
|
| 121 |
+
st.markdown(sentence_str)
|
| 122 |
+
|
| 123 |
+
# Mostrar análisis de categorías gramaticales # Mostrar análisis morfológico
|
| 124 |
+
col1, col2 = st.columns(2)
|
| 125 |
+
|
| 126 |
+
with col1:
|
| 127 |
+
with st.expander(t['pos_analysis'], expanded=True):
|
| 128 |
+
pos_df = pd.DataFrame(advanced_analysis['pos_analysis'])
|
| 129 |
+
|
| 130 |
+
# Traducir las etiquetas POS a sus nombres en el idioma seleccionado
|
| 131 |
+
pos_df['pos'] = pos_df['pos'].map(lambda x: POS_TRANSLATIONS[lang_code].get(x, x))
|
| 132 |
+
|
| 133 |
+
# Renombrar las columnas para mayor claridad
|
| 134 |
+
pos_df = pos_df.rename(columns={
|
| 135 |
+
'pos': t['grammatical_category'],
|
| 136 |
+
'count': t['count'],
|
| 137 |
+
'percentage': t['percentage'],
|
| 138 |
+
'examples': t['examples']
|
| 139 |
+
})
|
| 140 |
+
|
| 141 |
+
# Mostrar el dataframe
|
| 142 |
+
st.dataframe(pos_df)
|
| 143 |
+
|
| 144 |
+
with col2:
|
| 145 |
+
with st.expander(t['morphological_analysis'], expanded=True):
|
| 146 |
+
morph_df = pd.DataFrame(advanced_analysis['morphological_analysis'])
|
| 147 |
+
|
| 148 |
+
# Definir el mapeo de columnas
|
| 149 |
+
column_mapping = {
|
| 150 |
+
'text': t['word'],
|
| 151 |
+
'lemma': t['lemma'],
|
| 152 |
+
'pos': t['grammatical_category'],
|
| 153 |
+
'dep': t['dependency'],
|
| 154 |
+
'morph': t['morphology']
|
| 155 |
+
}
|
| 156 |
+
|
| 157 |
+
# Renombrar las columnas existentes
|
| 158 |
+
morph_df = morph_df.rename(columns={col: new_name for col, new_name in column_mapping.items() if col in morph_df.columns})
|
| 159 |
+
|
| 160 |
+
# Traducir las categorías gramaticales
|
| 161 |
+
morph_df[t['grammatical_category']] = morph_df[t['grammatical_category']].map(lambda x: POS_TRANSLATIONS[lang_code].get(x, x))
|
| 162 |
+
|
| 163 |
+
# Traducir las dependencias
|
| 164 |
+
dep_translations = {
|
| 165 |
+
'es': {
|
| 166 |
+
'ROOT': 'RAÍZ', 'nsubj': 'sujeto nominal', 'obj': 'objeto', 'iobj': 'objeto indirecto',
|
| 167 |
+
'csubj': 'sujeto clausal', 'ccomp': 'complemento clausal', 'xcomp': 'complemento clausal abierto',
|
| 168 |
+
'obl': 'oblicuo', 'vocative': 'vocativo', 'expl': 'expletivo', 'dislocated': 'dislocado',
|
| 169 |
+
'advcl': 'cláusula adverbial', 'advmod': 'modificador adverbial', 'discourse': 'discurso',
|
| 170 |
+
'aux': 'auxiliar', 'cop': 'cópula', 'mark': 'marcador', 'nmod': 'modificador nominal',
|
| 171 |
+
'appos': 'aposición', 'nummod': 'modificador numeral', 'acl': 'cláusula adjetiva',
|
| 172 |
+
'amod': 'modificador adjetival', 'det': 'determinante', 'clf': 'clasificador',
|
| 173 |
+
'case': 'caso', 'conj': 'conjunción', 'cc': 'coordinante', 'fixed': 'fijo',
|
| 174 |
+
'flat': 'plano', 'compound': 'compuesto', 'list': 'lista', 'parataxis': 'parataxis',
|
| 175 |
+
'orphan': 'huérfano', 'goeswith': 'va con', 'reparandum': 'reparación', 'punct': 'puntuación'
|
| 176 |
+
},
|
| 177 |
+
'en': {
|
| 178 |
+
'ROOT': 'ROOT', 'nsubj': 'nominal subject', 'obj': 'object',
|
| 179 |
+
'iobj': 'indirect object', 'csubj': 'clausal subject', 'ccomp': 'clausal complement', 'xcomp': 'open clausal complement',
|
| 180 |
+
'obl': 'oblique', 'vocative': 'vocative', 'expl': 'expletive', 'dislocated': 'dislocated', 'advcl': 'adverbial clause modifier',
|
| 181 |
+
'advmod': 'adverbial modifier', 'discourse': 'discourse element', 'aux': 'auxiliary', 'cop': 'copula', 'mark': 'marker',
|
| 182 |
+
'nmod': 'nominal modifier', 'appos': 'appositional modifier', 'nummod': 'numeric modifier', 'acl': 'clausal modifier of noun',
|
| 183 |
+
'amod': 'adjectival modifier', 'det': 'determiner', 'clf': 'classifier', 'case': 'case marking',
|
| 184 |
+
'conj': 'conjunct', 'cc': 'coordinating conjunction', 'fixed': 'fixed multiword expression',
|
| 185 |
+
'flat': 'flat multiword expression', 'compound': 'compound', 'list': 'list', 'parataxis': 'parataxis', 'orphan': 'orphan',
|
| 186 |
+
'goeswith': 'goes with', 'reparandum': 'reparandum', 'punct': 'punctuation'
|
| 187 |
+
},
|
| 188 |
+
'fr': {
|
| 189 |
+
'ROOT': 'RACINE', 'nsubj': 'sujet nominal', 'obj': 'objet', 'iobj': 'objet indirect',
|
| 190 |
+
'csubj': 'sujet phrastique', 'ccomp': 'complément phrastique', 'xcomp': 'complément phrastique ouvert', 'obl': 'oblique',
|
| 191 |
+
'vocative': 'vocatif', 'expl': 'explétif', 'dislocated': 'disloqué', 'advcl': 'clause adverbiale', 'advmod': 'modifieur adverbial',
|
| 192 |
+
'discourse': 'élément de discours', 'aux': 'auxiliaire', 'cop': 'copule', 'mark': 'marqueur', 'nmod': 'modifieur nominal',
|
| 193 |
+
'appos': 'apposition', 'nummod': 'modifieur numéral', 'acl': 'clause relative', 'amod': 'modifieur adjectival', 'det': 'déterminant',
|
| 194 |
+
'clf': 'classificateur', 'case': 'marqueur de cas', 'conj': 'conjonction', 'cc': 'coordination', 'fixed': 'expression figée',
|
| 195 |
+
'flat': 'construction plate', 'compound': 'composé', 'list': 'liste', 'parataxis': 'parataxe', 'orphan': 'orphelin',
|
| 196 |
+
'goeswith': 'va avec', 'reparandum': 'réparation', 'punct': 'ponctuation'
|
| 197 |
+
}
|
| 198 |
+
}
|
| 199 |
+
morph_df[t['dependency']] = morph_df[t['dependency']].map(lambda x: dep_translations[lang_code].get(x, x))
|
| 200 |
+
|
| 201 |
+
# Traducir la morfología
|
| 202 |
+
def translate_morph(morph_string, lang_code):
|
| 203 |
+
morph_translations = {
|
| 204 |
+
'es': {
|
| 205 |
+
'Gender': 'Género', 'Number': 'Número', 'Case': 'Caso', 'Definite': 'Definido',
|
| 206 |
+
'PronType': 'Tipo de Pronombre', 'Person': 'Persona', 'Mood': 'Modo',
|
| 207 |
+
'Tense': 'Tiempo', 'VerbForm': 'Forma Verbal', 'Voice': 'Voz',
|
| 208 |
+
'Fem': 'Femenino', 'Masc': 'Masculino', 'Sing': 'Singular', 'Plur': 'Plural',
|
| 209 |
+
'Ind': 'Indicativo', 'Sub': 'Subjuntivo', 'Imp': 'Imperativo', 'Inf': 'Infinitivo',
|
| 210 |
+
'Part': 'Participio', 'Ger': 'Gerundio', 'Pres': 'Presente', 'Past': 'Pasado',
|
| 211 |
+
'Fut': 'Futuro', 'Perf': 'Perfecto', 'Imp': 'Imperfecto'
|
| 212 |
+
},
|
| 213 |
+
'en': {
|
| 214 |
+
'Gender': 'Gender', 'Number': 'Number', 'Case': 'Case', 'Definite': 'Definite', 'PronType': 'Pronoun Type', 'Person': 'Person',
|
| 215 |
+
'Mood': 'Mood', 'Tense': 'Tense', 'VerbForm': 'Verb Form', 'Voice': 'Voice',
|
| 216 |
+
'Fem': 'Feminine', 'Masc': 'Masculine', 'Sing': 'Singular', 'Plur': 'Plural', 'Ind': 'Indicative',
|
| 217 |
+
'Sub': 'Subjunctive', 'Imp': 'Imperative', 'Inf': 'Infinitive', 'Part': 'Participle',
|
| 218 |
+
'Ger': 'Gerund', 'Pres': 'Present', 'Past': 'Past', 'Fut': 'Future', 'Perf': 'Perfect', 'Imp': 'Imperfect'
|
| 219 |
+
},
|
| 220 |
+
'fr': {
|
| 221 |
+
'Gender': 'Genre', 'Number': 'Nombre', 'Case': 'Cas', 'Definite': 'Défini', 'PronType': 'Type de Pronom',
|
| 222 |
+
'Person': 'Personne', 'Mood': 'Mode', 'Tense': 'Temps', 'VerbForm': 'Forme Verbale', 'Voice': 'Voix',
|
| 223 |
+
'Fem': 'Féminin', 'Masc': 'Masculin', 'Sing': 'Singulier', 'Plur': 'Pluriel', 'Ind': 'Indicatif',
|
| 224 |
+
'Sub': 'Subjonctif', 'Imp': 'Impératif', 'Inf': 'Infinitif', 'Part': 'Participe',
|
| 225 |
+
'Ger': 'Gérondif', 'Pres': 'Présent', 'Past': 'Passé', 'Fut': 'Futur', 'Perf': 'Parfait', 'Imp': 'Imparfait'
|
| 226 |
+
}
|
| 227 |
+
}
|
| 228 |
+
for key, value in morph_translations[lang_code].items():
|
| 229 |
+
morph_string = morph_string.replace(key, value)
|
| 230 |
+
return morph_string
|
| 231 |
+
|
| 232 |
+
morph_df[t['morphology']] = morph_df[t['morphology']].apply(lambda x: translate_morph(x, lang_code))
|
| 233 |
+
|
| 234 |
+
# Seleccionar y ordenar las columnas a mostrar
|
| 235 |
+
columns_to_display = [t['word'], t['lemma'], t['grammatical_category'], t['dependency'], t['morphology']]
|
| 236 |
+
columns_to_display = [col for col in columns_to_display if col in morph_df.columns]
|
| 237 |
+
|
| 238 |
+
# Mostrar el DataFrame
|
| 239 |
+
st.dataframe(morph_df[columns_to_display])
|
| 240 |
+
|
| 241 |
+
# Mostrar diagramas de arco (código existente)
|
| 242 |
+
with st.expander(t['arc_diagram'], expanded=True):
|
| 243 |
+
sentences = list(doc.sents)
|
| 244 |
+
arc_diagrams = []
|
| 245 |
+
for i, sent in enumerate(sentences):
|
| 246 |
+
st.subheader(f"{t['sentence']} {i+1}")
|
| 247 |
+
html = displacy.render(sent, style="dep", options={"distance": 100})
|
| 248 |
+
html = html.replace('height="375"', 'height="200"')
|
| 249 |
+
html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html)
|
| 250 |
+
html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"', lambda m: f'<g transform="translate({m.group(1)},50)"', html)
|
| 251 |
+
st.write(html, unsafe_allow_html=True)
|
| 252 |
+
arc_diagrams.append(html)
|
| 253 |
+
|
| 254 |
|
| 255 |
# Botón de exportación
|
| 256 |
if st.button(morpho_t.get('export_button', 'Export Analysis')):
|