File size: 9,290 Bytes
ee5caf5
5203a97
 
 
 
 
 
4f9d716
 
 
 
5203a97
 
 
 
2d075b0
5203a97
 
 
 
83d0100
 
 
 
 
 
 
 
5203a97
83d0100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5203a97
 
 
ee5caf5
 
 
 
 
 
 
5203a97
ee5caf5
 
 
 
5203a97
ee5caf5
 
 
5203a97
ee5caf5
 
 
5203a97
ee5caf5
 
 
 
 
 
5203a97
ee5caf5
5203a97
ee5caf5
 
 
5203a97
 
 
 
ee5caf5
 
 
 
5203a97
ee5caf5
 
 
 
 
 
 
5203a97
 
 
 
ee5caf5
 
 
 
 
 
 
5203a97
46c149e
ee5caf5
 
 
 
46c149e
ee5caf5
46c149e
 
 
 
 
 
 
 
 
 
 
 
 
 
ee5caf5
46c149e
 
 
ee5caf5
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
# modules/text_analysis/discourse_analysis.py
import streamlit as st
import spacy
import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import logging

logger = logging.getLogger(__name__)

from .semantic_analysis import (
    create_concept_graph,
    visualize_concept_graph,
    identify_key_concepts,
    get_stopwords,
    POS_COLORS,
    POS_TRANSLATIONS,
    ENTITY_LABELS
)
#####################
# Define colors for grammatical categories
POS_COLORS = {
    'ADJ': '#FFA07A', 'ADP': '#98FB98', 'ADV': '#87CEFA', 'AUX': '#DDA0DD',
    'CCONJ': '#F0E68C', 'DET': '#FFB6C1', 'INTJ': '#FF6347', 'NOUN': '#90EE90',
    'NUM': '#FAFAD2', 'PART': '#D3D3D3', 'PRON': '#FFA500', 'PROPN': '#20B2AA',
    'SCONJ': '#DEB887', 'SYM': '#7B68EE', 'VERB': '#FF69B4', 'X': '#A9A9A9',
}

POS_TRANSLATIONS = {
    'es': {
        'ADJ': 'Adjetivo', 'ADP': 'Preposición', 'ADV': 'Adverbio', 'AUX': 'Auxiliar',
        'CCONJ': 'Conjunción Coordinante', 'DET': 'Determinante', 'INTJ': 'Interjección',
        'NOUN': 'Sustantivo', 'NUM': 'Número', 'PART': 'Partícula', 'PRON': 'Pronombre',
        'PROPN': 'Nombre Propio', 'SCONJ': 'Conjunción Subordinante', 'SYM': 'Símbolo',
        'VERB': 'Verbo', 'X': 'Otro',
    },
    'en': {
        'ADJ': 'Adjective', 'ADP': 'Preposition', 'ADV': 'Adverb', 'AUX': 'Auxiliary',
        'CCONJ': 'Coordinating Conjunction', 'DET': 'Determiner', 'INTJ': 'Interjection',
        'NOUN': 'Noun', 'NUM': 'Number', 'PART': 'Particle', 'PRON': 'Pronoun',
        'PROPN': 'Proper Noun', 'SCONJ': 'Subordinating Conjunction', 'SYM': 'Symbol',
        'VERB': 'Verb', 'X': 'Other',
    },
    'fr': {
        'ADJ': 'Adjectif', 'ADP': 'Préposition', 'ADV': 'Adverbe', 'AUX': 'Auxiliaire',
        'CCONJ': 'Conjonction de Coordination', 'DET': 'Déterminant', 'INTJ': 'Interjection',
        'NOUN': 'Nom', 'NUM': 'Nombre', 'PART': 'Particule', 'PRON': 'Pronom',
        'PROPN': 'Nom Propre', 'SCONJ': 'Conjonction de Subordination', 'SYM': 'Symbole',
        'VERB': 'Verbe', 'X': 'Autre',
    }
}

ENTITY_LABELS = {
    'es': {
        "Personas": "lightblue",
        "Lugares": "lightcoral",
        "Inventos": "lightgreen",
        "Fechas": "lightyellow",
        "Conceptos": "lightpink"
    },
    'en': {
        "People": "lightblue",
        "Places": "lightcoral",
        "Inventions": "lightgreen",
        "Dates": "lightyellow",
        "Concepts": "lightpink"
    },
    'fr': {
        "Personnes": "lightblue",
        "Lieux": "lightcoral",
        "Inventions": "lightgreen",
        "Dates": "lightyellow",
        "Concepts": "lightpink"
    }
}

CUSTOM_STOPWORDS = {
    'es': {
        # Artículos
        'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas',
        # Preposiciones comunes
        'a', 'ante', 'bajo', 'con', 'contra', 'de', 'desde', 'en',
        'entre', 'hacia', 'hasta', 'para', 'por', 'según', 'sin',
        'sobre', 'tras', 'durante', 'mediante',
        # Conjunciones
        'y', 'e', 'ni', 'o', 'u', 'pero', 'sino', 'porque',
        # Pronombres
        'yo', 'tú', 'él', 'ella', 'nosotros', 'vosotros', 'ellos',
        'ellas', 'este', 'esta', 'ese', 'esa', 'aquel', 'aquella',
        # Verbos auxiliares comunes
        'ser', 'estar', 'haber', 'tener',
        # Palabras comunes en textos académicos
        'además', 'también', 'asimismo', 'sin embargo', 'no obstante',
        'por lo tanto', 'entonces', 'así', 'luego', 'pues',
        # Números escritos
        'uno', 'dos', 'tres', 'primer', 'primera', 'segundo', 'segunda',
        # Otras palabras comunes
        'cada', 'todo', 'toda', 'todos', 'todas', 'otro', 'otra',
        'donde', 'cuando', 'como', 'que', 'cual', 'quien',
        'cuyo', 'cuya', 'hay', 'solo', 'ver', 'si', 'no',
        # Símbolos y caracteres especiales
        '#', '@', '/', '*', '+', '-', '=', '$', '%'
    },
    'en': {
        # Articles
        'the', 'a', 'an',
        # Common prepositions
        'in', 'on', 'at', 'by', 'for', 'with', 'about', 'against',
        'between', 'into', 'through', 'during', 'before', 'after',
        'above', 'below', 'to', 'from', 'up', 'down', 'of',
        # Conjunctions
        'and', 'or', 'but', 'nor', 'so', 'for', 'yet',
        # Pronouns
        'i', 'you', 'he', 'she', 'it', 'we', 'they', 'this',
        'that', 'these', 'those', 'my', 'your', 'his', 'her',
        # Auxiliary verbs
        'be', 'am', 'is', 'are', 'was', 'were', 'been', 'have',
        'has', 'had', 'do', 'does', 'did',
        # Common academic words
        'therefore', 'however', 'thus', 'hence', 'moreover',
        'furthermore', 'nevertheless',
        # Numbers written
        'one', 'two', 'three', 'first', 'second', 'third',
        # Other common words
        'where', 'when', 'how', 'what', 'which', 'who',
        'whom', 'whose', 'there', 'here', 'just', 'only',
        # Symbols and special characters
        '#', '@', '/', '*', '+', '-', '=', '$', '%'
    },
    'fr': {
        # Articles
        'le', 'la', 'les', 'un', 'une', 'des',
        # Prepositions
        'à', 'de', 'dans', 'sur', 'en', 'par', 'pour', 'avec',
        'sans', 'sous', 'entre', 'derrière', 'chez', 'avant',
        # Conjunctions
        'et', 'ou', 'mais', 'donc', 'car', 'ni', 'or',
        # Pronouns
        'je', 'tu', 'il', 'elle', 'nous', 'vous', 'ils',
        'elles', 'ce', 'cette', 'ces', 'celui', 'celle',
        # Auxiliary verbs
        'être', 'avoir', 'faire',
        # Academic words
        'donc', 'cependant', 'néanmoins', 'ainsi', 'toutefois',
        'pourtant', 'alors',
        # Numbers
        'un', 'deux', 'trois', 'premier', 'première', 'second',
        # Other common words
        'où', 'quand', 'comment', 'que', 'qui', 'quoi',
        'quel', 'quelle', 'plus', 'moins',
        # Symbols
        '#', '@', '/', '*', '+', '-', '=', '$', '%'
    }
}

##############################################################################################################
def get_stopwords(lang_code):
    """
    Obtiene el conjunto de stopwords para un idioma específico.
    Combina las stopwords de spaCy con las personalizadas.
    """
    try:
        nlp = spacy.load(f'{lang_code}_core_news_sm')
        spacy_stopwords = nlp.Defaults.stop_words
        custom_stopwords = CUSTOM_STOPWORDS.get(lang_code, set())
        return spacy_stopwords.union(custom_stopwords)
    except:
        return CUSTOM_STOPWORDS.get(lang_code, set())

#################
def compare_semantic_analysis(text1, text2, nlp, lang):
    """
    Realiza el análisis semántico comparativo entre dos textos
    Args:
        text1: Primer texto a analizar
        text2: Segundo texto a analizar
        nlp: Modelo de spaCy cargado
        lang: Código de idioma
    Returns:
        tuple: (fig1, fig2, key_concepts1, key_concepts2)
    """
    try:
        # Procesar los textos
        doc1 = nlp(text1)
        doc2 = nlp(text2)

        # Identificar conceptos clave con parámetros específicos
        key_concepts1 = identify_key_concepts(doc1, min_freq=2, min_length=3)
        key_concepts2 = identify_key_concepts(doc2, min_freq=2, min_length=3)

        # Crear y visualizar grafos
        G1 = create_concept_graph(doc1, key_concepts1)
        G2 = create_concept_graph(doc2, key_concepts2)

        fig1 = visualize_concept_graph(G1, lang)
        fig2 = visualize_concept_graph(G2, lang)
        
        # Limpiar títulos
        fig1.suptitle("")
        fig2.suptitle("")

        return fig1, fig2, key_concepts1, key_concepts2

    except Exception as e:
        logger.error(f"Error en compare_semantic_analysis: {str(e)}")
        raise

def create_concept_table(key_concepts):
    """
    Crea una tabla de conceptos clave con sus frecuencias
    Args:
        key_concepts: Lista de tuplas (concepto, frecuencia)
    Returns:
        pandas.DataFrame: Tabla formateada de conceptos
    """
    try:
        df = pd.DataFrame(key_concepts, columns=['Concepto', 'Frecuencia'])
        df['Frecuencia'] = df['Frecuencia'].round(2)
        return df
    except Exception as e:
        logger.error(f"Error en create_concept_table: {str(e)}")
        raise

def perform_discourse_analysis(text1, text2, nlp, lang):
    """
    Realiza el análisis completo del discurso
    Args:
        text1: Primer texto a analizar
        text2: Segundo texto a analizar
        nlp: Modelo de spaCy cargado
        lang: Código de idioma
    Returns:
        dict: Resultados del análisis
    """
    try:
        # Realizar análisis comparativo
        fig1, fig2, key_concepts1, key_concepts2 = compare_semantic_analysis(
            text1, text2, nlp, lang
        )

        # Crear tablas de resultados
        table1 = create_concept_table(key_concepts1)
        table2 = create_concept_table(key_concepts2)

        return {
            'graph1': fig1,
            'graph2': fig2,
            'key_concepts1': key_concepts1,
            'key_concepts2': key_concepts2,
            'table1': table1,
            'table2': table2,
            'success': True
        }

    except Exception as e:
        logger.error(f"Error en perform_discourse_analysis: {str(e)}")
        return {
            'success': False,
            'error': str(e)
        }