AIdeaText commited on
Commit
895b4c4
·
verified ·
1 Parent(s): dfee16e

Update modules/text_analysis/morpho_analysis.py

Browse files
modules/text_analysis/morpho_analysis.py CHANGED
@@ -1,5 +1,7 @@
1
  import spacy
 
2
  from spacy import displacy
 
3
  from streamlit.components.v1 import html
4
  import base64
5
 
@@ -88,74 +90,111 @@ POS_TRANSLATIONS = {
88
  }
89
  }
90
 
91
- def generate_arc_diagram(doc):
92
- arc_diagrams = []
93
- for sent in doc.sents:
94
- words = [token.text for token in sent]
95
- # Calculamos el ancho del SVG basado en la longitud de la oración
96
- svg_width = max(600, len(words) * 120)
97
- # Altura fija para cada oración
98
- svg_height = 350 # Controla la altura del SVG
99
-
100
- # Renderizamos el diagrama de dependencias
101
- html = displacy.render(sent, style="dep", options={
102
- "add_lemma":False, # Introduced in version 2.2.4, this argument prints the lemma’s in a separate row below the token texts.
103
- "arrow_spacing": 12, #This argument is used for adjusting the spacing between arrows in px to avoid overlaps.
104
- "arrow_width": 2, #This argument is used for adjusting the width of arrow head in px.
105
- "arrow_stroke": 2, #This argument is used for adjusting the width of arrow path in px.
106
- "collapse_punct": True, #It attaches punctuation to the tokens.
107
- "collapse_phrases": False, # This argument merges the noun phrases into one token.
108
- "compact":False, # If you will take this argument as true, you will get the “Compact mode” with square arrows that takes up less space.
109
- "color": "#ffffff",
110
- "bg": "#0d6efd",
111
- "compact": False, #Put the value of this argument True, if you want to use fine-grained part-of-speech tags (Token.tag_), instead of coarse-grained tags (Token.pos_).
112
- "distance": 100, # Aumentamos la distancia entre palabras
113
- "fine_grained": False, #Put the value of this argument True, if you want to use fine-grained part-of-speech tags (Token.tag_), instead of coarse-grained tags (Token.pos_).
114
- "offset_x": 55, # This argument is used for spacing on left side of the SVG in px.
115
- "word_spacing": 25, #This argument is used for adjusting the vertical spacing between words and arcs in px.
116
- })
117
-
118
- # Ajustamos el tamaño del SVG y el viewBox
119
- html = re.sub(r'width="(\d+)"', f'width="{svg_width}"', html)
120
- html = re.sub(r'height="(\d+)"', f'height="{svg_height}"', html)
121
- html = re.sub(r'<svg', f'<svg viewBox="0 0 {svg_width} {svg_height}"', html)
122
-
123
- #html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html)
124
- #html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"', lambda m: f'<g transform="translate({m.group(1)},50)"', html)
125
-
126
- # Movemos todo el contenido hacia abajo
127
- #html = html.replace('<g', f'<g transform="translate(50, {svg_height - 200})"')
128
-
129
- # Movemos todo el contenido hacia arriba para eliminar el espacio vacío en la parte superior
130
- html = re.sub(r'<g transform="translate\((\d+),(\d+)\)"',
131
- lambda m: f'<g transform="translate({m.group(1)},10)"', html)
132
-
133
-
134
- # Ajustamos la posición de las etiquetas de las palabras
135
- html = html.replace('dy="1em"', 'dy="-1em"')
136
 
137
- # Ajustamos la posición de las etiquetas POS
138
- html = html.replace('dy="0.25em"', 'dy="-3em"')
139
-
140
- # Aumentamos el tamaño de la fuente para las etiquetas POS
141
- html = html.replace('.displacy-tag {', '.displacy-tag { font-size: 14px;')
142
-
143
- # Rotamos las etiquetas de las palabras para mejorar la legibilidad
144
- #html = html.replace('class="displacy-label"', 'class="displacy-label" transform="rotate(30)"')
145
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
146
  arc_diagrams.append(html)
147
  return arc_diagrams
148
- ##################################################################################################################################
149
-
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  def perform_advanced_morphosyntactic_analysis(text, nlp):
 
 
 
152
  doc = nlp(text)
153
  return {
154
  'pos_analysis': get_detailed_pos_analysis(doc),
155
  'morphological_analysis': get_morphological_analysis(doc),
156
  'sentence_structure': get_sentence_structure_analysis(doc),
157
- 'arc_diagrams': generate_arc_diagram(doc),
158
- 'repeated_words': get_repeated_words_colors(doc)
159
  }
160
-
161
- __all__ = ['perform_advanced_morphosyntactic_analysis']
 
 
1
  import spacy
2
+ from collections import Counter
3
  from spacy import displacy
4
+ import re
5
  from streamlit.components.v1 import html
6
  import base64
7
 
 
90
  }
91
  }
92
 
93
+ #############################################################################################
94
+ def get_repeated_words_colors(doc):
95
+ word_counts = Counter(token.text.lower() for token in doc if token.pos_ != 'PUNCT')
96
+ repeated_words = {word: count for word, count in word_counts.items() if count > 1}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
+ word_colors = {}
99
+ for token in doc:
100
+ if token.text.lower() in repeated_words:
101
+ word_colors[token.text.lower()] = POS_COLORS.get(token.pos_, '#FFFFFF')
 
 
 
 
102
 
103
+ return word_colors
104
+
105
+ ######################################################################################################
106
+ def highlight_repeated_words(doc, word_colors):
107
+ highlighted_text = []
108
+ for token in doc:
109
+ if token.text.lower() in word_colors:
110
+ color = word_colors[token.text.lower()]
111
+ highlighted_text.append(f'<span style="background-color: {color};">{token.text}</span>')
112
+ else:
113
+ highlighted_text.append(token.text)
114
+ return ' '.join(highlighted_text)
115
+
116
+ #################################################################################################
117
+ def generate_arc_diagram(doc, lang_code):
118
+ sentences = list(doc.sents)
119
+ arc_diagrams = []
120
+ for sent in sentences:
121
+ html = displacy.render(sent, style="dep", options={"distance": 100})
122
+ html = html.replace('height="375"', 'height="200"')
123
+ html = re.sub(r'<svg[^>]*>', lambda m: m.group(0).replace('height="450"', 'height="300"'), html)
124
+ html = re.sub(r'<g [^>]*transform="translate\((\d+),(\d+)\)"', lambda m: f'<g transform="translate({m.group(1)},50)"', html)
125
  arc_diagrams.append(html)
126
  return arc_diagrams
 
 
127
 
128
+ #################################################################################################
129
+ def get_detailed_pos_analysis(doc):
130
+ """
131
+ Realiza un análisis detallado de las categorías gramaticales (POS) en el texto.
132
+ """
133
+ pos_counts = Counter(token.pos_ for token in doc)
134
+ total_tokens = len(doc)
135
+ pos_analysis = []
136
+ for pos, count in pos_counts.items():
137
+ percentage = (count / total_tokens) * 100
138
+ pos_analysis.append({
139
+ 'pos': pos,
140
+ 'count': count,
141
+ 'percentage': round(percentage, 2),
142
+ 'examples': [token.text for token in doc if token.pos_ == pos][:5] # Primeros 5 ejemplos
143
+ })
144
+ return sorted(pos_analysis, key=lambda x: x['count'], reverse=True)
145
+
146
+ #################################################################################################
147
+ def get_morphological_analysis(doc):
148
+ """
149
+ Realiza un análisis morfológico detallado de las palabras en el texto.
150
+ """
151
+ morphology_analysis = []
152
+ for token in doc:
153
+ if token.pos_ in ['NOUN', 'VERB', 'ADJ', 'ADV']: # Enfocarse en categorías principales
154
+ morphology_analysis.append({
155
+ 'text': token.text,
156
+ 'lemma': token.lemma_,
157
+ 'pos': token.pos_,
158
+ 'tag': token.tag_,
159
+ 'dep': token.dep_,
160
+ 'shape': token.shape_,
161
+ 'is_alpha': token.is_alpha,
162
+ 'is_stop': token.is_stop,
163
+ 'morph': str(token.morph)
164
+ })
165
+ return morphology_analysis
166
+
167
+ #################################################################################################
168
+ def get_sentence_structure_analysis(doc):
169
+ """
170
+ Analiza la estructura de las oraciones en el texto.
171
+ """
172
+ sentence_analysis = []
173
+ for sent in doc.sents:
174
+ sentence_analysis.append({
175
+ 'text': sent.text,
176
+ 'root': sent.root.text,
177
+ 'root_pos': sent.root.pos_,
178
+ 'num_tokens': len(sent),
179
+ 'num_words': len([token for token in sent if token.is_alpha]),
180
+ 'subjects': [token.text for token in sent if "subj" in token.dep_],
181
+ 'objects': [token.text for token in sent if "obj" in token.dep_],
182
+ 'verbs': [token.text for token in sent if token.pos_ == "VERB"]
183
+ })
184
+ return sentence_analysis
185
+
186
+ #################################################################################################
187
  def perform_advanced_morphosyntactic_analysis(text, nlp):
188
+ """
189
+ Realiza un análisis morfosintáctico avanzado del texto.
190
+ """
191
  doc = nlp(text)
192
  return {
193
  'pos_analysis': get_detailed_pos_analysis(doc),
194
  'morphological_analysis': get_morphological_analysis(doc),
195
  'sentence_structure': get_sentence_structure_analysis(doc),
196
+ 'arc_diagram': generate_arc_diagram(doc, nlp.lang)
 
197
  }
198
+
199
+ # Al final del archivo morph_analysis.py
200
+ __all__ = ['get_repeated_words_colors', 'highlight_repeated_words', 'generate_arc_diagram', 'perform_advanced_morphosyntactic_analysis', 'POS_COLORS', 'POS_TRANSLATIONS']