-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathconcept_graph.py
More file actions
3371 lines (2893 loc) · 150 KB
/
concept_graph.py
File metadata and controls
3371 lines (2893 loc) · 150 KB
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import re
import itertools
import networkx as nx
from collections import Counter
import math
import unicodedata
# Import NLTK for lemmatization support
try:
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.corpus import wordnet, stopwords
NLTK_AVAILABLE = True
except ImportError:
NLTK_AVAILABLE = False
# Optional spaCy support for enhanced Spanish lemmatization
# Install with: pip install spacy && python -m spacy download es_core_news_sm
try:
import spacy
# Try to load Spanish model
try:
SPACY_ES = spacy.load("es_core_news_sm")
SPACY_ES_AVAILABLE = True
except OSError:
SPACY_ES = None
SPACY_ES_AVAILABLE = False
print("Info: Spanish spaCy model not found. Install with: python -m spacy download es_core_news_sm")
SPACY_AVAILABLE = True
except ImportError:
SPACY_AVAILABLE = False
SPACY_ES_AVAILABLE = False
SPACY_ES = None
# Initialize NLTK resources if available
if NLTK_AVAILABLE:
try:
nltk.data.find('tokenizers/punkt')
nltk.data.find('corpora/wordnet')
nltk.data.find('corpora/stopwords')
nltk.data.find('taggers/averaged_perceptron_tagger')
except LookupError:
# Download required NLTK data
import os
import tempfile
# Set NLTK data path to a temporary directory
nltk_data_dir = os.path.join(tempfile.gettempdir(), 'nltk_data')
nltk.data.path.append(nltk_data_dir)
try:
nltk.download('punkt', download_dir=nltk_data_dir, quiet=True)
nltk.download('wordnet', download_dir=nltk_data_dir, quiet=True)
nltk.download('stopwords', download_dir=nltk_data_dir, quiet=True)
nltk.download('averaged_perceptron_tagger', download_dir=nltk_data_dir, quiet=True)
nltk.download('omw-1.4', download_dir=nltk_data_dir, quiet=True)
except Exception as e:
print(f"Warning: Could not download NLTK data: {e}")
NLTK_AVAILABLE = False
# Helper for accent-insensitive comparisons
def normalize_word(word: str) -> str:
"""Return a lowercase, accent-free version of the given word."""
nfkd_form = unicodedata.normalize('NFD', word)
return ''.join(c for c in nfkd_form if unicodedata.category(c) != 'Mn').lower()
# Spanish language helpers
def get_spanish_stopwords():
"""Get comprehensive Spanish stopwords including common verbs and expressions."""
spanish_stopwords = {
# Articles
'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas',
# Prepositions
'a', 'ante', 'bajo', 'cabe', 'con', 'contra', 'de', 'del', 'desde', 'durante',
'en', 'entre', 'hacia', 'hasta', 'mediante', 'para', 'por', 'según', 'sin',
'so', 'sobre', 'tras', 'versus', 'vía',
# Conjunctions
'y', 'e', 'ni', 'o', 'u', 'pero', 'mas', 'sino', 'que', 'porque', 'pues',
'aunque', 'si', 'como', 'cuando', 'donde', 'mientras', 'ya',
# Common verbs (including past tense and participles)
'ser', 'estar', 'haber', 'tener', 'hacer', 'ir', 'venir', 'dar', 'decir',
'poder', 'deber', 'querer', 'saber', 'ver', 'poner', 'salir', 'llegar',
'pasar', 'seguir', 'quedar', 'creer', 'llevar', 'dejar', 'sentir', 'volver',
'encontrar', 'parecer', 'trabajar', 'empezar', 'esperar', 'buscar', 'existir',
# Past tense and participle forms
'fue', 'fue', 'era', 'había', 'tuvo', 'hizo', 'dijo', 'dijo', 'dicho',
'propuso', 'propuesto', 'estableció', 'establecido', 'indicó', 'indicado',
'mostró', 'mostrado', 'demostró', 'demostrado', 'observó', 'observado',
'consideró', 'considerado', 'sugirió', 'sugerido', 'planteó', 'planteado',
# Adverbs
'no', 'sí', 'también', 'tampoco', 'muy', 'más', 'menos', 'tan', 'tanto',
'bastante', 'poco', 'mucho', 'demasiado', 'algo', 'nada', 'todo', 'siempre',
'nunca', 'jamás', 'quizás', 'acaso', 'bien', 'mal', 'mejor', 'peor', 'ahora',
'antes', 'después', 'luego', 'entonces', 'aquí', 'ahí', 'allí', 'allá',
# Pronouns and determiners
'yo', 'tú', 'él', 'ella', 'nosotros', 'vosotros', 'ellos', 'ellas',
'me', 'te', 'se', 'nos', 'os', 'lo', 'la', 'le', 'les',
'mi', 'tu', 'su', 'nuestro', 'vuestro', 'este', 'esta', 'estos', 'estas',
'ese', 'esa', 'esos', 'esas', 'aquel', 'aquella', 'aquellos', 'aquellas',
# Time and quantity
'hoy', 'ayer', 'mañana', 'tarde', 'temprano', 'pronto', 'vez', 'veces',
'primer', 'primero', 'primera', 'segundo', 'tercero', 'último', 'última',
# Common adjectives and adverbs that add no meaning
'nuevo', 'nueva', 'viejo', 'vieja', 'grande', 'pequeño', 'pequeña',
'bueno', 'buena', 'malo', 'mala', 'mismo', 'misma', 'otro', 'otra',
'igual', 'diferente', 'similar', 'tal', 'cada', 'cualquier',
# Generic terms that don't add semantic value
'cosa', 'cosas', 'algo', 'nada', 'todo', 'alguien', 'nadie', 'todos',
'lugar', 'lugares', 'sitio', 'sitios', 'parte', 'partes', 'lado', 'lados',
'tiempo', 'tiempos', 'momento', 'momentos', 'vez', 'veces', 'tipo', 'tipos',
'forma', 'formas', 'manera', 'maneras', 'modo', 'modos', 'caso', 'casos',
}
return spanish_stopwords
def lemmatize_spanish_word(word, use_spacy=True):
"""
Enhanced Spanish lemmatization focusing on nouns and infinitive verbs.
Args:
word (str): Spanish word to lemmatize
use_spacy (bool): Whether to try spaCy first
Returns:
str: Lemmatized word
"""
word = word.lower().strip()
# Try spaCy first if available and enabled
if use_spacy and SPACY_ES_AVAILABLE:
try:
doc = SPACY_ES(word)
if doc and len(doc) > 0:
lemma = doc[0].lemma_
# For verbs, ensure we get infinitive form
if doc[0].pos_ == 'VERB' and not lemma.endswith(('ar', 'er', 'ir')):
# Try to get infinitive form if spaCy didn't provide it
pass # Fall through to rule-based approach
else:
return lemma
except Exception:
pass # Fall back to rule-based approach
# Enhanced rule-based Spanish lemmatization
# Common verb endings to infinitive mapping
verb_patterns = {
# Present tense indicative
'o': ['ar', 'er', 'ir'], # first person singular
'as': ['ar'], # second person singular -ar
'es': ['er', 'ir'], # second person singular -er/-ir
'a': ['ar'], # third person singular -ar
'e': ['er', 'ir'], # third person singular -er/-ir
'amos': ['ar'], # first person plural -ar
'áis': ['ar'], # second person plural -ar
'emos': ['er'], # first person plural -er
'éis': ['er'], # second person plural -er
'imos': ['ir'], # first person plural -ir
'ís': ['ir'], # second person plural -ir
'an': ['ar'], # third person plural -ar
'en': ['er', 'ir'], # third person plural -er/-ir
# Past tense (preterite)
'é': ['ar'], # first person singular -ar
'aste': ['ar'], # second person singular -ar
'ó': ['ar'], # third person singular -ar
'amos': ['ar'], # first person plural -ar (same as present)
'asteis': ['ar'], # second person plural -ar
'aron': ['ar'], # third person plural -ar
'í': ['er', 'ir'], # first person singular -er/-ir
'iste': ['er', 'ir'], # second person singular -er/-ir
'ió': ['er', 'ir'], # third person singular -er/-ir
'imos': ['er', 'ir'], # first person plural -er/-ir (same as present)
'isteis': ['er', 'ir'], # second person plural -er/-ir
'ieron': ['er', 'ir'], # third person plural -er/-ir
# Imperfect
'aba': ['ar'], # first/third person singular -ar
'abas': ['ar'], # second person singular -ar
'ábamos': ['ar'], # first person plural -ar
'abais': ['ar'], # second person plural -ar
'aban': ['ar'], # third person plural -ar
'ía': ['er', 'ir'], # first/third person singular -er/-ir
'ías': ['er', 'ir'], # second person singular -er/-ir
'íamos': ['er', 'ir'], # first person plural -er/-ir
'íais': ['er', 'ir'], # second person plural -er/-ir
'ían': ['er', 'ir'], # third person plural -er/-ir
# Participles and gerunds (convert to infinitive)
'ado': ['ar'], # past participle -ar
'ido': ['er', 'ir'], # past participle -er/-ir
'ando': ['ar'], # gerund -ar
'iendo': ['er', 'ir'], # gerund -er/-ir
}
# Try verb conjugation to infinitive conversion
for ending, infinitive_endings in verb_patterns.items():
if word.endswith(ending) and len(word) > len(ending) + 2:
stem = word[:-len(ending)]
# Try each possible infinitive ending
for inf_ending in infinitive_endings:
infinitive = stem + inf_ending
# Basic validation - infinitive should be longer than 3 chars
if len(infinitive) > 3:
return infinitive
break
# Noun/adjective plural to singular conversion
if word.endswith('s') and len(word) > 3:
if word.endswith('es'):
# Remove 'es' ending for words ending in consonant
singular = word[:-2]
if len(singular) > 2:
return singular
elif word.endswith(('as', 'os')):
# Remove 's' for words ending in vowel
singular = word[:-1]
if len(singular) > 2:
return singular
else:
# Simple 's' removal
singular = word[:-1]
if len(singular) > 2:
return singular
# Gender variations (standardize to masculine form when appropriate)
if word.endswith('a') and len(word) > 3:
# Don't change words that are naturally feminine or end in -ía, -ura, -ción, etc.
if not word.endswith(('ía', 'ura', 'ción', 'sión', 'dad', 'tad', 'tud')):
# Try changing 'a' to 'o' for potential masculine form
masculine = word[:-1] + 'o'
# This is a heuristic - in a production system you'd want a dictionary
return masculine
# Return original word if no lemmatization rules apply
return word
def get_stopwords(language='english'):
"""
Get stopwords for the specified language.
Args:
language (str): Language code ('english', 'spanish', 'es', 'español')
Returns:
set: Set of stopwords for the language
"""
if language.lower() in ['spanish', 'es', 'español']:
# Start with our comprehensive Spanish stopwords
spanish_stops = get_spanish_stopwords().copy() # Make a copy to avoid modifying original
# Add NLTK Spanish stopwords if available
if NLTK_AVAILABLE:
try:
nltk_spanish = set(stopwords.words('spanish'))
spanish_stops.update(nltk_spanish)
except Exception:
pass # Use our custom set only
return spanish_stops
else:
# English stopwords
english_stops = {
'the', 'and', 'a', 'an', 'to', 'of', 'in', 'for', 'on', 'with', 'at', 'by',
'from', 'up', 'about', 'into', 'over', 'after', 'under', 'above', 'below',
'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had',
'do', 'does', 'did', 'but', 'if', 'or', 'because', 'as', 'until', 'while',
'than', 'that', 'so', 'such', 'too', 'very', 'can', 'will', 'just', 'should',
'would', 'could', 'may', 'might', 'must', 'shall', 'ought', 'need', 'dare',
'used', 'ought', 'this', 'these', 'those', 'what', 'which', 'who', 'when',
'where', 'why', 'how', 'all', 'any', 'both', 'each', 'few', 'more', 'most',
'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so',
'than', 'too', 'very', 's', 't', 'can', 'will', 'just', 'don', 'should', 'now'
}
# Add NLTK English stopwords if available
if NLTK_AVAILABLE:
try:
nltk_english = set(stopwords.words('english'))
english_stops.update(nltk_english)
except Exception:
pass # Use our custom set only
return english_stops
# Extended stopwords including common academic and generic terms
STOPWORDS = {
# Articles and common words
'the','and','a','an','to','of','in','for','on','with','at','by','from','up','about','into','over','after',
'under','above','below','is','are','was','were','be','been','being','have','has','had','do','does','did',
'but','if','or','because','as','until','while','than','that','so','such','too','very','can','will','just',
'also','this','these','those','they','them','their','there','here','where','when','what','who','how','why',
'would','could','should','might','may','must','shall','need','get','got','go','went','come','came','see',
'saw','know','knew','think','thought','say','said','tell','told','make','made','take','took','give','gave',
'use','used','find','found','look','looked','work','worked','call','called','try','tried','ask','asked',
'seem','seemed','feel','felt','become','became','leave','left','put','set','turn','turned','move','moved',
'right','left','good','bad','new','old','first','last','long','short','high','low','big','small','large',
'great','little','own','other','another','same','different','each','every','all','some','any','many','much',
'more','most','less','few','several','both','either','neither','between','among','during','before','after',
'since','through','throughout','within','without','across','around','down','off','out','up','away','back',
'again','once','twice','never','always','often','sometimes','usually','really','quite','rather','pretty',
'only','even','still','yet','already','now','then','soon','later','early','late','today','tomorrow',
'yesterday','however','therefore','thus','hence','moreover','furthermore','nevertheless','nonetheless',
'meanwhile','otherwise','instead','besides','indeed','certainly','perhaps','maybe','probably','possibly',
'various','numerous','multiple','overall','specific',
# Pronouns (all forms)
'i','me','my','mine','myself','you','your','yours','yourself','yourselves','he','him','his','himself',
'she','her','hers','herself','it','its','itself','we','us','our','ours','ourselves','they','them',
'their','theirs','themselves','who','whom','whose','which','what','that','this','these','those',
# Demonstratives and quantifiers
'some','any','none','all','each','every','both','either','neither','one','two','three','four','five',
'six','seven','eight','nine','ten','many','much','few','little','several','enough','plenty',
# Common verbs that don't add semantic value
'am','being','been','have','has','had','do','does','did','will','would','could','should','might','may',
'can','must','shall','ought','need','dare','used','going','getting','making','taking','giving','coming',
'looking','working','trying','saying','telling','knowing','thinking','feeling','seeming','becoming',
# Generic nouns and adjectives
'thing','things','stuff','something','anything','everything','nothing','someone','anyone','everyone',
'no one','nobody','somebody','anybody','everybody','somewhere','anywhere','everywhere','nowhere',
'way','ways','time','times','place','places','part','parts','kind','kinds','type','types','sort','sorts',
'side','sides','end','ends','point','points','case','cases','fact','facts','example','examples',
'idea','ideas','reason','reasons','problem','problems','question','questions','answer','answers',
'number','numbers','group','groups','level','levels','area','areas','line','lines','word','words',
'name','names','year','years','day','days','week','weeks','month','months','hour','hours','minute','minutes',
# Common adjectives
'important','different','large','small','great','good','bad','high','low','long','short','big','little',
'old','new','young','early','late','best','worst','better','worse','first','last','next','previous',
'main','major','minor','special','general','particular','certain','sure','clear','possible','impossible',
'available','free','open','close','closed','easy','hard','difficult','simple','complex','basic','advanced',
# Temporal and spatial terms
'now','then','here','there','today','tomorrow','yesterday','before','after','during','while','since',
'until','although','though','unless','because','if','when','where','how','why','what','which','that',
# Numbers and ordinals
'zero','one','two','three','four','five','six','seven','eight','nine','ten','eleven','twelve','thirteen',
'fourteen','fifteen','sixteen','seventeen','eighteen','nineteen','twenty','thirty','forty','fifty',
'sixty','seventy','eighty','ninety','hundred','thousand','million','billion','first','second','third',
'fourth','fifth','sixth','seventh','eighth','ninth','tenth','last','next','another','other'
}
# Spanish stopwords for concept graph filtering
STOPWORDS_SPANISH = {
# Articles and determiners
'el','la','los','las','un','una','unos','unas','este','esta','estos','estas','ese','esa','esos','esas',
'aquel','aquella','aquellos','aquellas','mi','tu','su','nuestro','nuestra','nuestros','nuestras',
'vuestro','vuestra','vuestros','vuestras','mio','mia','mios','mias','tuyo','tuya','tuyos','tuyas',
'suyo','suya','suyos','suyas','mismo','misma','mismos','mismas','otro','otra','otros','otras',
# Pronouns
'yo','tu','el','ella','nosotros','nosotras','vosotros','vosotras','ellos','ellas','me','te','se',
'nos','os','le','lo','la','les','que','quien','quienes','cual','cuales','donde','cuando','como',
'por','para','con','sin','sobre','bajo','entre','durante','antes','despues','hasta','desde',
# Verbs (common auxiliary and modal verbs)
'ser','estar','haber','tener','hacer','ir','venir','dar','decir','poder','deber','querer','saber',
'ver','poner','salir','llegar','pasar','seguir','quedar','creer','llevar','dejar','sentir','volver',
'encontrar','parecer','trabajar','empezar','esperar','buscar','existir','entrar','hablar','abrir',
'cerrar','vivir','morir','nacer','crecer','aprender','enseñar','estudiar','leer','escribir','pensar',
'recordar','olvidar','conocer','reconocer','entender','comprender','explicar','preguntar','responder',
'ayudar','necesitar','usar','utilizar','servir','funcionar','cambiar','mejorar','empeorar','aumentar',
'disminuir','subir','bajar','caer','levantar','mover','parar','continuar','terminar','acabar','comenzar',
# Prepositions and conjunctions
'y','o','pero','sino','aunque','si','porque','ya','como','cuando','donde','mientras','hasta','desde',
'para','por','con','sin','sobre','bajo','ante','tras','durante','mediante','segun','contra','hacia',
'entre','a','de','en','que','no','ni','también','tampoco','solo','solamente','incluso','además',
'sin embargo','por tanto','por eso','entonces','luego','después','antes','ahora','ya','aún','todavía',
# Adverbs
'muy','más','menos','tan','tanto','bastante','poco','mucho','demasiado','algo','nada','todo','siempre',
'nunca','jamás','a veces','quizás','tal vez','posiblemente','probablemente','seguramente','claro',
'obviamente','realmente','verdaderamente','exactamente','aproximadamente','casi','apenas','solo',
'únicamente','especialmente','particularmente','generalmente','normalmente','habitualmente','frecuentemente',
'raramente','difícilmente','fácilmente','rápidamente','lentamente','bien','mal','mejor','peor',
# Adjectives (common descriptive)
'bueno','malo','grande','pequeño','nuevo','viejo','joven','mayor','menor','primero','último','siguiente',
'anterior','próximo','mismo','diferente','igual','similar','distinto','especial','normal','común',
'raro','extraño','importante','necesario','posible','imposible','fácil','difícil','simple','complejo',
'claro','oscuro','alto','bajo','largo','corto','ancho','estrecho','gordo','delgado','fuerte','débil',
'rápido','lento','caliente','frío','dulce','amargo','salado','ácido','suave','duro','blando','seco',
'húmedo','limpio','sucio','nuevo','usado','caro','barato','rico','pobre','libre','ocupado','lleno',
'vacío','abierto','cerrado','público','privado','nacional','internacional','local','general','particular',
# Numbers and quantifiers
'cero','uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez','once','doce','trece',
'catorce','quince','dieciséis','diecisiete','dieciocho','diecinueve','veinte','treinta','cuarenta','cincuenta',
'sesenta','setenta','ochenta','noventa','cien','mil','millón','billón','primero','segundo','tercero',
'cuarto','quinto','sexto','séptimo','octavo','noveno','décimo','algunos','varios','muchos','pocos',
'todos','ninguno','cada','cualquier','ambos','ningún','algún','cierto','cierta','ciertos','ciertas',
'numeroso','numerosa','numerosos','numerosas','diverso','diversa','diversos','diversas','usted','ustedes',
# Time and space
'hoy','ayer','mañana','ahora','antes','después','luego','entonces','pronto','tarde','temprano',
'siempre','nunca','a menudo','frecuentemente','raramente','aquí','allí','acá','allá','arriba',
'abajo','adelante','atrás','izquierda','derecha','cerca','lejos','dentro','fuera','encima','debajo',
'delante','detrás','al lado','alrededor','través','mediante','durante','mientras','hasta','desde',
# Common phrases and expressions
'por favor','gracias','perdón','disculpe','lo siento','de nada','por supuesto','claro que sí',
'tal vez','quizás','sin duda','por cierto','en realidad','en verdad','a propósito','por ejemplo',
'es decir','o sea','sin embargo','no obstante','por tanto','por eso','además','también','tampoco',
# Interrogatives and exclamatives
'qué','cuál','cuáles','quién','quiénes','cómo','cuándo','dónde','cuánto','cuánta','cuántos','cuántas',
'por qué','para qué','ah','oh','uf','ay','vaya','caramba','dios mío','por dios'
}
# Build accent-insensitive stopword sets using our improved functions
STOPWORDS_NORMALIZED = {normalize_word(w) for w in STOPWORDS}
STOPWORDS_SPANISH_NORMALIZED = {normalize_word(w) for w in get_spanish_stopwords()}
def get_wordnet_pos(treebank_tag):
"""Convert treebank POS tag to wordnet POS tag for lemmatization."""
if not NLTK_AVAILABLE:
return wordnet.NOUN # Default fallback
if treebank_tag.startswith('J'):
return wordnet.ADJ
elif treebank_tag.startswith('V'):
return wordnet.VERB
elif treebank_tag.startswith('N'):
return wordnet.NOUN
elif treebank_tag.startswith('R'):
return wordnet.ADV
else:
return wordnet.NOUN # Default
def detect_language(text):
"""Detect language of the text."""
# Simple heuristic based on common words
spanish_indicators = {
'el', 'la', 'de', 'que', 'y', 'en', 'un', 'es', 'se', 'no', 'te', 'lo', 'le',
'da', 'su', 'por', 'son', 'con', 'para', 'al', 'del', 'los', 'las', 'pero',
'español', 'hablar', 'hacer', 'trabajo', 'tiempo', 'persona', 'año', 'gobierno',
'propuso', 'dicho', 'estableció', 'indicó', 'mostró', 'demostró', 'observó'
}
words = text.lower().split()
spanish_count = sum(1 for word in words if normalize_word(word) in spanish_indicators)
# If more than 10% of words are Spanish indicators, consider it Spanish
if len(words) > 0 and spanish_count / len(words) > 0.1:
return 'spanish'
return 'english'
def lemmatize_word(word, language='english', enable_lemmatization=True):
"""
Enhanced lemmatization focusing on nouns and infinitive verbs.
Args:
word (str): Word to lemmatize
language (str): Language of the word ('english', 'spanish')
enable_lemmatization (bool): Whether to enable lemmatization
Returns:
str: Lemmatized word (noun form or infinitive for verbs)
"""
if not enable_lemmatization:
return word
# Spanish lemmatization
if language.lower() in ['spanish', 'es', 'español']:
return lemmatize_spanish_word(word, use_spacy=True)
# English lemmatization using NLTK
if not NLTK_AVAILABLE:
return word
try:
lemmatizer = WordNetLemmatizer()
# Get POS tag for better lemmatization
try:
tokens = nltk.word_tokenize(word)
if tokens:
pos_tags = nltk.pos_tag(tokens)
if pos_tags:
word_token, pos = pos_tags[0]
# Convert POS tag to WordNet format
wordnet_pos = get_wordnet_pos(pos)
# Special handling for verbs - always lemmatize to infinitive (base form)
if pos.startswith('VB'):
# For verbs, use noun lemmatization first, then verb
lemma = lemmatizer.lemmatize(word.lower(), pos='v') # verb infinitive
return lemma
# For nouns, use noun lemmatization
elif pos.startswith('NN'):
lemma = lemmatizer.lemmatize(word.lower(), pos='n') # noun singular
return lemma
# For other parts of speech, default to noun lemmatization
else:
lemma = lemmatizer.lemmatize(word.lower(), pos=wordnet_pos)
return lemma
except:
# Fallback to simple noun lemmatization
pass
# Simple lemmatization as fallback
return lemmatizer.lemmatize(word.lower())
except Exception as e:
# If lemmatization fails for any reason, return original word
return word
def lemmatize_terms(terms, language='english', enable_lemmatization=True):
"""
Lemmatize a list of terms if lemmatization is enabled.
"""
if not enable_lemmatization:
return terms
lemmatized = []
for term in terms:
if ' ' in term: # Multi-word terms - lemmatize each word
words = term.split()
lemmatized_words = [lemmatize_word(word, language, enable_lemmatization) for word in words]
lemmatized.append(' '.join(lemmatized_words))
else: # Single word
lemmatized.append(lemmatize_word(term, language, enable_lemmatization))
return lemmatized
def jenks_natural_breaks_simple(data, n_classes=3):
"""
Implementación simplificada del algoritmo de Jenks Natural Breaks
que no requiere numpy.
"""
if len(data) <= n_classes:
return sorted(set(data))
data = sorted(data)
n = len(data)
# Para datasets pequeños, usar percentiles
if n <= 10:
percentiles = [20, 50, 80][:n_classes-1]
breaks = []
for p in percentiles:
idx = int((p / 100.0) * (n - 1))
breaks.append(data[idx])
breaks = [data[0]] + breaks + [data[-1]]
return sorted(set(breaks))
# Algoritmo simplificado para datasets más grandes
# Dividir en clases aproximadamente iguales y optimizar
class_size = n // n_classes
breaks = [data[0]]
for i in range(1, n_classes):
start_idx = i * class_size
end_idx = min((i + 1) * class_size, n)
if start_idx < n:
# Buscar el mejor punto de corte en un rango
best_break = data[start_idx]
min_variance = float('inf')
for j in range(max(0, start_idx - 5), min(n, start_idx + 5)):
if j > 0 and j < n - 1:
# Calcular varianza aproximada
left_data = data[breaks[-1]:j] if len(breaks) > 1 else data[:j]
right_data = data[j:end_idx] if end_idx < n else data[j:]
if left_data and right_data:
left_var = variance(left_data)
right_var = variance(right_data)
total_var = left_var + right_var
if total_var < min_variance:
min_variance = total_var
best_break = data[j]
breaks.append(best_break)
breaks.append(data[-1])
return sorted(set(breaks))
def variance(data):
"""Calcula la varianza de una lista de datos."""
if len(data) <= 1:
return 0
mean = sum(data) / len(data)
return sum((x - mean) ** 2 for x in data) / len(data)
def percentile(data, p):
"""Calcula el percentil p de los datos."""
if not data:
return 0
sorted_data = sorted(data)
n = len(sorted_data)
index = (p / 100.0) * (n - 1)
if index == int(index):
return sorted_data[int(index)]
else:
lower = sorted_data[int(index)]
upper = sorted_data[int(index) + 1]
return lower + (upper - lower) * (index - int(index))
def calculate_network_diversity(G, node):
"""
Calcula la diversidad de conexiones de un nodo basada en
la entropía de Shannon de sus conexiones.
"""
neighbors = list(G.neighbors(node))
if len(neighbors) <= 1:
return 0
# Calcular pesos de las conexiones
weights = []
for neighbor in neighbors:
weight = G[node][neighbor].get('weight', 1.0)
weights.append(weight)
# Normalizar pesos
total_weight = sum(weights)
if total_weight == 0:
return 0
probs = [w / total_weight for w in weights]
# Calcular entropía de Shannon
entropy = -sum(p * math.log2(p) for p in probs if p > 0)
# Normalizar por el máximo posible (log2(n))
max_entropy = math.log2(len(neighbors)) if len(neighbors) > 1 else 1
return entropy / max_entropy
def extract_high_quality_terms(text, min_length=3, max_length=50, language='english', enable_lemmatization=True, max_text_length=200000, exclusions=None, inclusions=None):
"""
High-quality term extraction prioritizing compound terms and comprehensive coverage
Target: 80-90% quality for concept graphs
Enhanced with Spanish language support
"""
from collections import defaultdict
if exclusions is None:
exclusions = []
if inclusions is None:
inclusions = []
# Convert exclusions and inclusions to lowercase for case-insensitive matching
exclusions_lower = [exc.lower() for exc in exclusions]
inclusions_lower = [inc.lower() for inc in inclusions]
# Initialize language detection variables
spanish_count = 0
english_count = 0
# Detect language if not specified or auto
if language == 'auto':
language = detect_language(text)
elif language == 'english': # Default to checking for Spanish indicators
detected_lang = detect_language(text)
if detected_lang == 'spanish':
language = 'spanish'
# More generous text length limit for quality
if len(text) > max_text_length:
# Intelligent truncation preserving complete sentences
sentences = re.split(r'[.!?]+', text[:max_text_length])
if len(sentences) > 1:
text = '. '.join(sentences[:-1]) + '.'
else:
text = text[:max_text_length]
# Language-specific compound terms
compound_terms = {}
# Add Spanish compound terms if Spanish is detected
if language.lower() in ['spanish', 'es', 'español']:
spanish_compounds = {
# Spanish compound terms for technology and business
'inteligencia artificial': 'inteligencia_artificial',
'aprendizaje automático': 'aprendizaje_automatico',
'aprendizaje profundo': 'aprendizaje_profundo',
'redes neuronales': 'redes_neuronales',
'red neuronal': 'red_neuronal',
'procesamiento de lenguaje natural': 'procesamiento_lenguaje_natural',
'visión artificial': 'vision_artificial',
'visión por computadora': 'vision_computadora',
'ciencia de datos': 'ciencia_datos',
'ingeniería de software': 'ingenieria_software',
'gestión de bases de datos': 'gestion_bases_datos',
'base de datos': 'base_datos',
'computación en la nube': 'computacion_nube',
'ciberseguridad': 'ciberseguridad',
'seguridad informática': 'seguridad_informatica',
'internet de las cosas': 'internet_cosas',
'tecnología blockchain': 'tecnologia_blockchain',
'cadena de bloques': 'cadena_bloques',
'computación cuántica': 'computacion_cuantica',
'realidad virtual': 'realidad_virtual',
'realidad aumentada': 'realidad_aumentada',
'big data': 'big_data',
'computación en el borde': 'computacion_borde',
'arquitectura de microservicios': 'arquitectura_microservicios',
'transformación digital': 'transformacion_digital',
'comercio electrónico': 'comercio_electronico',
'redes sociales': 'redes_sociales',
'computación móvil': 'computacion_movil',
'experiencia de usuario': 'experiencia_usuario',
'interfaz de usuario': 'interfaz_usuario',
'desarrollo de software': 'desarrollo_software',
'desarrollo web': 'desarrollo_web',
'desarrollo móvil': 'desarrollo_movil',
'inteligencia de negocios': 'inteligencia_negocios',
'análisis de datos': 'analisis_datos',
'minería de datos': 'mineria_datos',
'almacén de datos': 'almacen_datos',
'automatización robótica': 'automatizacion_robotica',
'gestión de proyectos': 'gestion_proyectos',
'aseguramiento de calidad': 'aseguramiento_calidad',
'marketing digital': 'marketing_digital',
'experiencia del cliente': 'experiencia_cliente',
'privacidad de datos': 'privacidad_datos',
'control de acceso': 'control_acceso',
'detección de amenazas': 'deteccion_amenazas',
'integración continua': 'integracion_continua',
'despliegue continuo': 'despliegue_continuo',
'metodología ágil': 'metodologia_agil',
'prácticas devops': 'practicas_devops',
}
compound_terms.update(spanish_compounds)
# Add English compound terms for English or mixed content
if language.lower() not in ['spanish', 'es', 'español']:
english_compounds = {
# AI/ML Core
'artificial intelligence': 'artificial_intelligence',
'machine learning': 'machine_learning',
'deep learning': 'deep_learning',
'neural networks': 'neural_networks',
'neural network': 'neural_network',
'natural language processing': 'natural_language_processing',
'computer vision': 'computer_vision',
'reinforcement learning': 'reinforcement_learning',
'supervised learning': 'supervised_learning',
'unsupervised learning': 'unsupervised_learning',
'transfer learning': 'transfer_learning',
'generative ai': 'generative_ai',
'large language model': 'large_language_model',
'transformer model': 'transformer_model',
# Data & Analytics
'data science': 'data_science',
'big data': 'big_data',
'data analysis': 'data_analysis',
'data mining': 'data_mining',
'data visualization': 'data_visualization',
'predictive analytics': 'predictive_analytics',
'business intelligence': 'business_intelligence',
'data warehouse': 'data_warehouse',
'data lake': 'data_lake',
'data pipeline': 'data_pipeline',
# Software Development
'software engineering': 'software_engineering',
'software development': 'software_development',
'web development': 'web_development',
'mobile development': 'mobile_development',
'full stack': 'full_stack',
'frontend development': 'frontend_development',
'backend development': 'backend_development',
'api development': 'api_development',
'user interface': 'user_interface',
'user experience': 'user_experience',
'responsive design': 'responsive_design',
# Infrastructure & Systems
'cloud computing': 'cloud_computing',
'edge computing': 'edge_computing',
'quantum computing': 'quantum_computing',
'distributed computing': 'distributed_computing',
'parallel computing': 'parallel_computing',
'high performance computing': 'high_performance_computing',
'database management': 'database_management',
'system administration': 'system_administration',
'network security': 'network_security',
'information security': 'information_security',
# Emerging Technologies
'internet of things': 'internet_of_things',
'blockchain technology': 'blockchain_technology',
'virtual reality': 'virtual_reality',
'augmented reality': 'augmented_reality',
'mixed reality': 'mixed_reality',
'digital transformation': 'digital_transformation',
'automation technology': 'automation_technology',
'robotic process automation': 'robotic_process_automation',
# Architecture & Methodologies
'microservices architecture': 'microservices_architecture',
'service oriented architecture': 'service_oriented_architecture',
'event driven architecture': 'event_driven_architecture',
'domain driven design': 'domain_driven_design',
'test driven development': 'test_driven_development',
'continuous integration': 'continuous_integration',
'continuous deployment': 'continuous_deployment',
'agile methodology': 'agile_methodology',
'devops practices': 'devops_practices',
# Business & Management
'project management': 'project_management',
'product management': 'product_management',
'quality assurance': 'quality_assurance',
'change management': 'change_management',
'risk management': 'risk_management',
'performance monitoring': 'performance_monitoring',
'business process': 'business_process',
'digital marketing': 'digital_marketing',
'customer experience': 'customer_experience',
'social media': 'social_media',
'mobile computing': 'mobile_computing',
'e commerce': 'e_commerce',
# Security & Privacy
'cyber security': 'cyber_security',
'data privacy': 'data_privacy',
'identity management': 'identity_management',
'access control': 'access_control',
'threat detection': 'threat_detection',
'vulnerability assessment': 'vulnerability_assessment',
'penetration testing': 'penetration_testing',
'security audit': 'security_audit',
# Common variations and abbreviations
'ai': 'artificial_intelligence',
'ml': 'machine_learning',
'dl': 'deep_learning',
'nlp': 'natural_language_processing',
'cv': 'computer_vision',
'iot': 'internet_of_things',
'vr': 'virtual_reality',
'ar': 'augmented_reality',
'ui': 'user_interface',
'ux': 'user_experience',
'api': 'application_programming_interface',
'cms': 'content_management_system',
'crm': 'customer_relationship_management',
'erp': 'enterprise_resource_planning',
}
# Process text with compound term preservation
text_processed = text.lower()
# Replace compound terms with tokens (preserving order by length)
sorted_compounds = sorted(compound_terms.items(), key=lambda x: len(x[0]), reverse=True)
for compound, replacement in sorted_compounds:
pattern = r'\b' + re.escape(compound) + r'\b'
text_processed = re.sub(pattern, replacement, text_processed)
# Initialize term frequency counter
term_freq = Counter()
# Method 1: Extract preserved compound terms
for replacement in compound_terms.values():
count = len(re.findall(r'\b' + re.escape(replacement) + r'\b', text_processed))
if count > 0:
readable_term = replacement.replace('_', ' ')
term_freq[readable_term] = count
# Language-specific technical terms and stopwords
if language.lower() in ['spanish', 'es', 'español']:
# Enhanced Spanish stopwords (more comprehensive)
spanish_stopwords = {normalize_word(w) for w in {
# Articles
'el', 'la', 'los', 'las', 'un', 'una', 'unos', 'unas',
# Prepositions
'a', 'ante', 'bajo', 'cabe', 'con', 'contra', 'de', 'del', 'desde', 'durante',
'en', 'entre', 'hacia', 'hasta', 'mediante', 'para', 'por', 'según', 'sin',
'so', 'sobre', 'tras', 'versus', 'vía',
# Conjunctions
'y', 'e', 'ni', 'o', 'u', 'pero', 'mas', 'sino', 'que', 'porque', 'pues',
'aunque', 'si', 'como', 'cuando', 'donde', 'mientras', 'ya',
# Common verbs
'ser', 'estar', 'haber', 'tener', 'hacer', 'ir', 'venir', 'dar', 'decir',
'poder', 'deber', 'querer', 'saber', 'ver', 'poner', 'salir', 'llegar',
'pasar', 'seguir', 'quedar', 'creer', 'llevar', 'dejar', 'sentir', 'volver',
'encontrar', 'parecer', 'trabajar', 'empezar', 'esperar', 'buscar', 'existir',
# Adverbs
'no', 'sí', 'también', 'tampoco', 'muy', 'más', 'menos', 'tan', 'tanto',
'bastante', 'poco', 'mucho', 'demasiado', 'algo', 'nada', 'todo', 'siempre',
'nunca', 'jamás', 'quizás', 'acaso', 'bien', 'mal', 'mejor', 'peor', 'ahora',
'antes', 'después', 'luego', 'entonces', 'aquí', 'ahí', 'allí', 'allá',
# Pronouns and determiners
'yo', 'tú', 'él', 'ella', 'nosotros', 'vosotros', 'ellos', 'ellas',
'me', 'te', 'se', 'nos', 'os', 'lo', 'la', 'le', 'les',
'mi', 'tu', 'su', 'nuestro', 'vuestro', 'este', 'esta', 'estos', 'estas',
'ese', 'esa', 'esos', 'esas', 'aquel', 'aquella', 'aquellos', 'aquellas',
# Time and quantity
'hoy', 'ayer', 'mañana', 'tarde', 'temprano', 'pronto', 'vez', 'veces',
'primer', 'primero', 'primera', 'segundo', 'tercero', 'último', 'última',
# Common adjectives and adverbs that add no meaning
'nuevo', 'nueva', 'viejo', 'vieja', 'grande', 'pequeño', 'pequeña',
'bueno', 'buena', 'malo', 'mala', 'mismo', 'misma', 'otro', 'otra',
'igual', 'diferente', 'similar', 'tal', 'cada', 'cualquier',
}}
technical_terms = {
# Spanish technical vocabulary
'algoritmo', 'framework', 'biblioteca', 'servidor', 'cliente',
'frontend', 'backend', 'despliegue', 'pruebas', 'depuración',
'optimización', 'rendimiento', 'escalabilidad', 'seguridad', 'autenticación',
'autorización', 'cifrado', 'protocolo', 'interfaz', 'arquitectura',
'microservicios', 'monolito', 'contenedor', 'automatización',
'programación', 'codificación', 'desarrollo', 'ingeniería', 'tecnología',
'innovación', 'solución', 'plataforma', 'sistema', 'aplicación',
'software', 'hardware', 'red', 'internet', 'web', 'móvil',
'escritorio', 'nube', 'almacenamiento', 'memoria', 'procesador',
'análisis', 'analítica', 'visualización', 'dashboard', 'reporte',
'integración', 'migración', 'transformación', 'modernización',
'conjunto', 'modelo', 'entrenamiento', 'predicción', 'clasificación',
'regresión', 'agrupamiento', 'estadísticas', 'métricas', 'benchmark',
'flujo', 'proceso', 'procedimiento', 'metodología', 'estrategia',
'implementación', 'ejecución', 'monitoreo', 'evaluación', 'valoración',
'requerimiento', 'especificación', 'documentación', 'mantenimiento',
'soporte', 'servicio', 'cliente', 'usuario', 'stakeholder', 'equipo',
'estándar', 'cumplimiento', 'gobernanza', 'política', 'procedimiento',
'práctica', 'guía', 'recomendación', 'revisión', 'auditoría',
'certificación', 'validación', 'verificación', 'investigación',
'innovación', 'experimento', 'prototipo', 'piloto', 'prueba',
'concepto', 'factibilidad', 'estudio', 'investigación', 'descubrimiento',
}
else:
# English stopwords and technical terms (existing)
spanish_stopwords = set()
technical_terms = {
# Programming & Development
'algorithm', 'framework', 'library', 'database', 'server', 'client',
'frontend', 'backend', 'fullstack', 'deployment', 'testing', 'debugging',
'optimization', 'performance', 'scalability', 'security', 'authentication',
'authorization', 'encryption', 'protocol', 'interface', 'architecture',
'microservices', 'monolith', 'container', 'docker', 'kubernetes',
'automation', 'devops', 'pipeline', 'repository', 'version', 'control',
'programming', 'coding', 'development', 'engineering', 'technology',
'innovation', 'solution', 'platform', 'system', 'application',
'software', 'hardware', 'network', 'internet', 'web', 'mobile',
'desktop', 'cloud', 'storage', 'memory', 'processor', 'cpu', 'gpu',
# Data & Analytics
'analysis', 'analytics', 'visualization', 'dashboard', 'report',
'integration', 'migration', 'transformation', 'modernization',
'dataset', 'model', 'training', 'prediction', 'classification',
'regression', 'clustering', 'statistics', 'metrics', 'benchmark',
# Business & Process
'workflow', 'process', 'procedure', 'methodology', 'strategy',
'implementation', 'execution', 'monitoring', 'evaluation', 'assessment',
'requirement', 'specification', 'documentation', 'maintenance',
'support', 'service', 'customer', 'user', 'stakeholder', 'team',
# Quality & Standards
'standard', 'compliance', 'governance', 'policy', 'procedure',
'best', 'practice', 'guideline', 'recommendation', 'review',
'audit', 'certification', 'validation', 'verification', 'testing',
# Innovation & Research
'research', 'innovation', 'experiment', 'prototype', 'pilot',
'proof', 'concept', 'feasibility', 'study', 'investigation',
'discovery', 'breakthrough', 'advancement', 'progress', 'evolution',
}
# Extract technical terms
words = re.findall(r'\b[a-zA-Z]{3,}\b', text_processed)
for word in words:
if word in technical_terms and not word.endswith('_'):
term_freq[word] += 1
# Method 3: Enhanced extraction with language-specific stopwords
stopwords = get_stopwords(language)
if enable_lemmatization and NLTK_AVAILABLE:
try:
# Language-specific additional stopwords
if language.lower() in ['spanish', 'es', 'español']:
additional_stopwords = {
'usar', 'utilizar', 'hacer', 'crear', 'dar', 'tomar', 'ver', 'saber',
'pensar', 'trabajar', 'ayudar', 'necesitar', 'querer', 'gustar',
'manera', 'forma', 'cosa', 'tiempo', 'gente', 'persona', 'año',
'día', 'bueno', 'mejor', 'nuevo', 'viejo', 'grande', 'pequeño',
}
else:
additional_stopwords = {