-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathupdater.py
executable file
·1871 lines (1462 loc) · 70.6 KB
/
updater.py
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
#!/usr/bin/python3
from __future__ import annotations
import re
import os
import sys
import csv
import copy as copy_
import json
import glob
import time
import click
import shutil
import enchant
import itertools
import inflection
import requests
import datetime
import operator
import functools
import numpy as np
import pandas as pd
from urllib import parse
import bs4
import warnings
from typing import cast, ClassVar, Generic, Match, Mapping, overload, TextIO, TypeVar
from collections.abc import ItemsView, Iterable, Iterator, Generator, MutableMapping
_term_columns = shutil.get_terminal_size().columns
# Annoying irrelevant pandas warning from .str.contains
warnings.filterwarnings('ignore', 'This pattern is interpreted as a regular expression, and has match groups')
# We’re parsing some xhtml
warnings.filterwarnings('ignore', "It looks like you're parsing an XML document using an HTML parser.")
class CFPNotFoundError(Exception):
pass
class CFPCheckError(Exception):
pass
def clean_print(*args, **kwargs):
""" Line print(), but first erase anything on the current line (e.g. a progress bar) """
if args and kwargs.get('file', sys.stdout).isatty():
if not hasattr(clean_print, '_clear_line'):
clean_print._clear_line = f'\r{" " * _term_columns}\r{{}}'
args = (clean_print._clear_line.format(args[0]), *args[1:])
print(*args, **kwargs)
T = TypeVar('T')
class PeekIter(Generic[T]):
""" Iterator that allows
Attributes:
_it: wrapped by this iterator
_ahead: stack of the next elements to be returned by __next__
"""
_it: Iterator[T]
_ahead: list[T]
def __init__(self, iterable: Iterator[T]):
super(PeekIter, self)
self._it = iterable
self._ahead = []
def __iter__(self) -> Iterator[T]:
return self
def __next__(self) -> T:
if self._ahead:
return self._ahead.pop(0)
else:
return next(self._it)
@overload
def peek(self) -> T:
...
@overload
def peek(self, n: int) -> list[T]:
...
def peek(self, n: int = 0) -> T | list[T]:
""" Returns next element(s) that will be returned from the iterator.
Args:
n: Number of positions to look ahead in the iterator.
Returns:
The next element if n = 0, or the list of the up to n next elements if n > 0.
Raises:
IndexError: There are no further elements (only if n = 0).
"""
if n < 0:
raise ValueError('n < 0 but can not peek back, only ahead')
try:
self._ahead.extend(next(self._it) for _ in range(n - len(self._ahead) + 1))
except RuntimeError:
pass
if n == 0:
return self._ahead[0]
else:
return self._ahead[:n]
class RequestWrapper:
""" Static wrapper of request.get() to implement caching and waiting between requests """
last_req_times: dict[str, float] = {}
use_cache: bool = True
delay: float = 0
@classmethod
def set_delay(cls, delay: float):
cls.delay = delay
@classmethod
def set_use_cache(cls, use_cache: bool):
cls.use_cache = use_cache
@classmethod
def wait(cls, url: str):
""" Wait until at least :attr:`~delay` seconds for the next same-domain request """
key = parse.urlsplit(url).netloc
now = time.time()
wait = cls.last_req_times.get(parse.urlsplit(url).netloc, 0) + cls.delay - now
cls.last_req_times[parse.urlsplit(url).netloc] = now + max(0, wait)
if wait >= 0:
time.sleep(wait)
@classmethod
def get_soup(cls, url: str, filename: str, **kwargs) -> bs4.BeautifulSoup:
""" Simple caching mechanism. Fetch a page from url and save it in filename.
If filename exists, return its contents instead.
kwargs are forwarded to :func:`requests.get`
"""
if cls.use_cache:
try:
with open(filename, 'r') as fh:
return bs4.BeautifulSoup(fh.read(), 'lxml')
except FileNotFoundError:
pass
cls.wait(url)
r = requests.get(url, **kwargs)
if cls.use_cache:
with open(filename, 'w') as fh:
print(r.text, file=fh)
return bs4.BeautifulSoup(r.text, 'lxml')
def normalize(string: str) -> str:
""" Singularize and lower casing of a word """
# Asia -> Asium and Meta -> Metum, really?
return inflection.singularize(string.lower()) if len(string) > 3 else string.lower()
class ConfMetaData:
""" Heuristic to reduce a conference title to a matchable set of words. """
# separators in an acronum
_sep = re.compile(r'[-_/ @&,.]+')
# associations, societies, institutes, etc. that organize conferences
_org = {
'ACIS': 'Association for Computer and Information Science', 'ACL': 'Association for Computational Linguistics',
'ACM': 'Association for Computing Machinery', 'ACS': 'Arab Computer Society', 'AoM': 'Academy of Management',
'CSI': 'Computer Society of Iran', 'DIMACS': 'Center for Discrete Mathematics and Theoretical Computer Science',
'ERCIM': 'European Research Consortium for Informatics and Mathematics', 'Eurographics': 'Eurographics',
'Euromicro': 'Euromicro', 'IADIS': 'International Association for the Development of the Information Society',
'IAPR': 'International Association for Pattern Recognition',
'IAVoSS': 'International Association for Voting Systems Sciences', 'ICSC': 'ICSC Interdisciplinary Research',
'IEEE': 'Institute of Electrical and Electronics Engineers',
'IET': 'Institution of Engineering and Technology',
'IFAC': 'International Federation of Automatic Control',
'IFIP': 'International Federation for Information Processing',
'IMA': 'Institute of Mathematics and its Applications', 'KES': 'KES International',
'MSRI': 'Mathematical Sciences Research Institute', 'RSJ': 'Robotics Society of Japan',
'SCS': 'Society for Modeling and Simulation International',
'SIAM': 'Society for Industrial and Applied Mathematics',
'SLKOIS': 'State Key Laboratory of Information Security',
'SIGOPT': 'DMV Special Interest Group in Optimization',
'SIGNLL': 'ACL Special Interest Group in Natural Language Learning',
'SPIE': 'International Society for Optics and Photonics',
'TC13': 'IFIP Technical Committee on Human–Computer Interaction',
'Usenix': 'Advanced Computing Systems Association', 'WIC': 'Web Intelligence Consortium',
}
# ACM Special Interest Groups
_sig = {
'ACCESS': 'Accessible Computing', 'ACT': 'Algorithms Computation Theory', 'Ada': 'Ada Programming Language',
'AI': 'Artificial Intelligence', 'APP': 'Applied Computing', 'ARCH': 'Computer Architecture',
'BED': 'Embedded Systems', 'Bio': 'Bioinformatics', 'CAS': 'Computers Society',
'CHI': 'Computer-Human Interaction', 'COMM': 'Data Communication', 'CSE': 'Computer Science Education',
'DA': 'Design Automation', 'DOC': 'Design Communication', 'ecom': 'Electronic Commerce',
'EVO': 'Genetic Evolutionary Computation', 'GRAPH': 'Computer Graphics Interactive Techniques',
'HPC': 'High Performance Computing', 'IR': 'Information Retrieval', 'ITE': 'Information Technology Education',
'KDD': 'Knowledge Discovery Data', 'LOG': 'Logic Computation', 'METRICS': 'Measurement Evaluation',
'MICRO': 'Microarchitecture', 'MIS': 'Management Information Systems',
'MOBILE': 'Mobility Systems, Users, Data Computing', 'MM': 'Multimedia', 'MOD': 'Management Data',
'OPS': 'Operating Systems', 'PLAN': 'Programming Languages', 'SAC': 'Security, Audit Control',
'SAM': 'Symbolic Algebraic Manipulation', 'SIM': 'Simulation Modeling', 'SOFT': 'Software Engineering',
'SPATIAL': 'SIGSPATIAL', 'UCCS': 'University College Computing Services', 'WEB': 'Hypertext Web',
'ART': 'Artificial Intelligence', # NB ART was renamed AI
}
_meeting_types = {'congress', 'conference', 'consortium', 'seminar', 'symposium', 'workshop', 'tutorial'}
_qualifiers = {
'american', 'asian', 'australasian', 'australian', 'annual', 'biennial', 'european', 'iberoamerican',
'international', 'joint', 'national',
}
_replace = {
# shortenings
'intl': 'international', 'conf': 'conference', 'dev': 'development',
# americanize
'visualisation': 'visualization', 'modelling': 'modeling', 'internationalisation': 'internationalization',
'defence': 'defense', 'standardisation': 'standardization', 'organisation': 'organization',
'optimisation': 'optimization,', 'realising': 'realizing', 'centre': 'center',
# encountered typos
'syste': 'system', 'computi': 'computing', 'artifical': 'artificial', 'librari': 'library',
'databa': 'database', 'conferen': 'conference', 'bioinformatic': 'bioinformatics', 'symposi': 'symposium',
'evoluti': 'evolution', 'proce': 'processes', 'provi': 'proving', 'techology': 'technology',
'bienniel': 'biennial', 'entertainme': 'entertainment', 'retriev': 'retrieval', 'engineeri': 'engineering',
'sigraph': 'siggraph', 'intelleligence': 'intelligence', 'simululation': 'simulation',
'inteligence': 'intelligence', 'manageme': 'management', 'applicatio': 'application',
'developme': 'development', 'cyberworl': 'cyberworld', 'scien': 'science', 'personalizati': 'personalization',
'computati': 'computation', 'implementati': 'implementation', 'languag': 'language', 'traini': 'training',
'servic': 'services', 'intenational': 'international', 'complexi': 'complexity', 'storytelli': 'storytelling',
'measureme': 'measurement', 'comprehensi': 'comprehension', 'synthe': 'synthesis', 'evaluatin': 'evaluation',
'intermational': 'international', 'internaltional': 'international', 'interational': 'international',
'technologi': 'technology', 'applciation': 'application',
}
# NB simple acronym management, only works while first word -> acronym mapping is unique
_acronyms = {''.join(word[0] for word in acr.split()): [normalize(word) for word in acr.split()] for acr in [
'call for papers', 'geographic information system', 'high performance computing', 'message passing interface',
'object oriented', 'operating system', 'parallel virtual machine', 'public key infrastructure',
'special interest group',
]}
# Computer Performance Evaluation ? Online Analytical Processing: OLAP? aspect-oriented programming ?
_tens = {'twenty', 'thirty', 'fourty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety'}
_ordinal = re.compile(r'[0-9]+(st|nd|rd|th)|(({tens})?(first|second|third|(four|fif|six|seven|eigh|nine?)th))|'
r'(ten|eleven|twelf|(thir|fourt|fif|six|seven|eigh|nine?)teen)th'
.format(tens = '|'.join(_tens)))
_ordinal_list = ('first', 'second', 'third', 'fourth', 'fifth', 'sixth')
_sigcmp = {normalize(f'SIG{group}'): group for group in _sig}
_orgcmp = {normalize(entity): entity for entity in _org}
_acronym_start = {words[0]: acr for acr, words in _acronyms.items()}
_sig_start = {normalize(desc.split()[0]): group for group, desc in _sig.items() if group != 'ART'}
_dict = enchant.DictWithPWL('EN_US', 'dict.txt')
_misspelled: dict[str, list[tuple[str, ...]]] = {}
acronym_words: list[str]
topic_keywords: list[str]
organisers: set[str]
number: set[str]
type_: set[str]
qualifiers: list[str]
call_type: str | None
__slots__ = ('acronym_words', 'topic_keywords', 'organisers', 'number', 'type_', 'qualifiers', 'call_type')
def __init__(self, title: str, conf_acronym: str, year: str | int = ''):
super().__init__()
self.acronym_words = self._sep.split(conf_acronym.lower())
self.topic_keywords = []
self.organisers = set()
self.number = set()
self.type_ = set()
self.qualifiers = []
self.classify_words(title, normalize(conf_acronym), str(year))
@classmethod
def word_pos(cls, word_list, match_set: str | set[str]):
if isinstance(match_set, str):
try:
return word_list.index(match_set)
except ValueError:
return None
else:
# max() to catch “X and Y” cases with both X and Y in the match set
found = set(word_list) & match_set
if not found:
return None
return max(word_list.index(word) for word in found)
def classify_call(self, normalized: str, *ignored: str):
# Match call types in normalized, to distinguish between multi-word expressions:
# call for posters, call for [full] papers, phd symposium, etc.
normalized_text = ' '.join(normalized)
try:
pos = normalized_text.index('call for ')
except ValueError:
call_for_text = []
else:
call_from = len(normalized_text[:pos].split()) + 2
# NB: account for call for <conf | year | conf year | confyear> [interesting bit]
while normalized[call_from] in {*ignored, ''.join(ignored)}:
call_from += 1
# Only look at a few next words
call_for_text = normalized[call_from:call_from + 5]
if not call_for_text:
return None
elif (pos := self.word_pos(call_for_text, 'paper')) is not None:
# NB. could still be “workshop paper” etc.
call_for_text = call_for_text[:pos]
call_type = 'paper'
elif (pos := self.word_pos(call_for_text, 'poster')) is not None:
call_for_text = call_for_text[:pos]
call_type = 'poster'
elif (pos := self.word_pos(call_for_text, 'proposal')) is not None:
call_for_text = call_for_text[:pos]
call_type = 'proposal'
elif (pos := self.word_pos(call_for_text, {'exhibitor', 'patron', 'sponsor', 'speaker', 'panel', 'volunteer', 'reviewer', 'editor'})) is not None:
call_for_text = call_for_text[:pos + 1]
call_type = 'speaker'
elif (pos := self.word_pos(call_for_text, {'submission', 'contribution', 'proceeding', 'chapter', 'result'})) is not None:
call_for_text = call_for_text[:pos + 1]
call_type = 'paper'
elif (pos := self.word_pos(call_for_text, {'forum', 'workshop', 'tutorial', 'competition', 'session', 'issue', 'track', 'contest', 'challenge', 'course', 'exhibition'})) is not None:
# NB. Conservatively assuming paper but calls here could also proposals of workshops etc.
call_for_text = call_for_text[:pos + 1]
call_type = 'paper'
elif (pos := self.word_pos(call_for_text, {'demo', 'demonstration'})) is not None:
call_for_text = call_for_text[:pos]
call_type = 'demo'
elif (pos := self.word_pos(call_for_text, {'student', 'phd', 'doctoral'})) is not None:
call_for_text = call_for_text[:pos + 2] # include next word
call_type = 'paper'
else:
return None
# refine papers if text contains student/phd/competition/etc, anything that is is not “main track”
if call_type != 'paper' or not call_for_text:
return call_type
if self.word_pos(call_for_text, {'student', 'phd', 'doctoral'}) is not None:
return 'student paper'
elif self.word_pos(call_for_text, {'workshop', 'tutorial', 'competition', 'contest', 'challenge', 'demo'}) is not None:
# NB. also other special tracks
return 'workshop paper'
else:
return 'paper'
def classify_words(self, string: str, *ignored: str):
# lower case, replace characters in dict by whitepace, repeated spaces will be removed by split()
normalized = [normalize(w) for w in string.translate({ord(c): ' ' for c in "-/&,():_~'\".[]|*@"}).split()]
self.call_type = self.classify_call(normalized, *ignored)
words = PeekIter(w for w in normalized if w not in {
'', 'the', 'on', 'for', 'of', 'in', 'and', 'its', *ignored, ''.join(ignored)
})
# semantically filter conference editors/organisations, special interest groups (sig...), etc.
for w in words:
# Only manually fix typos, afraid of over-correcting
try:
w = self._replace[w]
except KeyError:
pass
if w in self._orgcmp:
self.organisers.add(self._orgcmp[w])
continue
if w in self._meeting_types:
self.type_.add(w)
continue
# Also seen but risk colliding with topic words: Mini Conference, Working Conference
if w in self._qualifiers:
self.qualifiers.append(w)
continue
# Recompose acronyms
try:
acronym = self._acronym_start[w]
next_words = self._acronyms[acronym][1:]
if words.peek(len(next_words)) == next_words:
self.topic_keywords.append(normalize(acronym))
for _ in next_words:
next(words)
continue
# TODO some acronyms have special characters, e.g. A/V, which means they appear as 2 words
except (KeyError, IndexError):
pass
# Some specific attention brought to ACM special interest groups
if w.startswith('sig'):
try:
if len(w) > 3:
self.organisers.add('SIG' + self._sigcmp[w])
continue
sig = normalize('SIG' + next(words))
if sig in self._sigcmp:
self.organisers.add(self._sigcmp[sig])
continue
elif words.peek() in self._sig_start:
sig = self._sig_start[words.peek()]
next_words = [normalize(s) for s in self._sig[sig].split()][1:]
if next_words == words.peek(len(next_words)):
self.organisers.add('SIG' + sig)
for _ in next_words: next(words)
continue
except (KeyError, IndexError):
pass
# three-part management for ordinals, to handle joint/separate words: twenty-fourth, 10 th, etc.
if w in self._tens:
try:
m = self._ordinal.match(words.peek())
if m:
self.number.add(w + '-' + m.group(0))
next(words)
continue
except IndexError:
pass
if w.isnumeric():
try:
if words.peek() == inflection.ordinal(int(w)):
self.number.add(w + next(words))
continue
except IndexError:
pass
# Pure numeric
self.number.add(w)
continue
m = ConfMetaData._ordinal.match(w)
if m:
self.number.add(m.group(0))
continue
# anything surviving to this point surely describes the topic of the conference
self.topic_keywords.append(w)
# Log words marked as incorrect in misspellings - ad-hoc ignored words can be used as conf identifiers
if self._dict and not self._dict.check(w):
if self._dict.check(w.capitalize()) or self._dict.check(w.title()):
pass
elif w.endswith('um') and self._dict.check(f'{w[:-2]}a'.capitalize()):
pass # inflection overcorrects (often proper) nouns asia -> asium, malaysia -> malaysium, etc.
elif w not in (normalize(s).replace('-', '') for s in self._dict.suggest(w)):
self._misspelled.setdefault(w, []).append((*ignored, string))
def topic(self, sep: str = ' ') -> str:
return sep.join(self.topic_keywords).title()
@classmethod
def _set_diff(cls, left: set[str], right: set[str], require_common: bool = True) -> float:
""" Return an int quantifying the difference between the sets. Lower is better.
Penalize a bit for difference on a single side, more for differences on both sides, under the assumption that
partial information on one side is better than dissymetric information
"""
n_common = len(set(left) & set(right))
l = len(left) - n_common
r = len(right) - n_common
if require_common and l and r and not n_common:
return np.inf
else:
return l + r + 10 * l * r - 2 * n_common
@classmethod
def _list_diff(cls, left: list[str], right: list[str], require_common: bool = True) -> float:
""" Return a float quantifying the difference between the lists of words.
Uset the same as `~set_diff` and add penalties for dfferences in word order.
"""
# for 4 diffs => 4 + 0 -> 5, 3 + 1 -> 8, 2 + 2 -> 9
common = set(left) & set(right)
n_common = len(common)
n_l, n_r = len(left) - n_common, len(right) - n_common
l = [w for w in left if w in common]
r = [w for w in right if w in common]
try:
mid = round(sum(l.index(c) - r.index(c) for c in common) / len(common))
sort_diff = sum(abs(l.index(c) - r.index(c) - mid) for c in common) / n_common
except ZeroDivisionError:
sort_diff = 0
# disqualify if there is nothing in common
if require_common and left and right and not common:
return np.inf
else:
return n_l + n_r + 10 * n_l * n_r - 4 * n_common + sort_diff
@classmethod
def _acronym_diff(cls, left: list[str], right: list[str]) -> float:
""" Return a float quantifying the difference between lists of words in acronyms.
More specific than _list_diff as we always want the first word to be an exact match,
but we may reinterpret contiguous words as a single one.
"""
if left == right:
return -40 * len(left) * len(right)
# Special case se we don’t match e.g. IFIP SEC with IFIP-DSS: ignore leading word if it’s an organizer
# Note that an organiser name can be a conference name, e.g. usenix
left_org = len(left) > 1 and left[0] in cls._orgcmp
right_org = len(right) > 1 and right[0] in cls._orgcmp
# If both sides start with the same org name, compare ignoring it. Discount 2 (half a common word).
if left_org and right_org and left[0] == right[0]:
return cls._acronym_diff(left[1:], right[1:]) - 2
# If only one side starts with an org name, compare ignoring it unless it matches the name on the other side
# Add 1 (penalty for a dissymetric word)
elif left_org or right_org and left[0] != right[0]:
return cls._acronym_diff(left[int(left_org):], right[int(right_org):]) + 1
left_prefixes = {''.join(left[:n + 1]): n for n in range(len(left))}
right_prefixes = {''.join(right[:n + 1]): n for n in range(len(right))}
common = left_prefixes.keys() & right_prefixes.keys()
if not common:
return np.inf
prefix = max(common, key=len)
nsep_left_prefix = left_prefixes[prefix]
nsep_right_prefix = right_prefixes[prefix]
# penalty of 1 per ignored separator, 10 per ignored word
return nsep_left_prefix + nsep_right_prefix + 10 * cls._list_diff([prefix, *left[nsep_left_prefix + 1:]],
[prefix, *right[nsep_right_prefix + 1:]])
def _difference(self, other: ConfMetaData) -> tuple[float, float, float, float, float, float]:
""" Compare the two ConfMetaData instances and rate how similar they are. """
return (
self._acronym_diff(self.acronym_words, other.acronym_words),
self._set_diff(self.type_, other.type_),
self._set_diff(self.organisers, other.organisers),
self._list_diff(self.topic_keywords, other.topic_keywords),
self._list_diff(self.qualifiers, other.qualifiers, require_common=False) / 2,
self._set_diff(self.number, other.number)
)
def str_info(self) -> list[str]:
vals = []
if self.topic_keywords:
vals.append(f'topic=[{", ".join(self.topic_keywords)}]')
if self.organisers:
vals.append(f'organisers={{{", ".join(self.organisers)}}}')
if self.number:
vals.append(f'number={{{", ".join(self.number)}}}')
if self.type_:
vals.append(f'type={{{", ".join(self.type_)}}}')
if self.qualifiers:
vals.append(f'qualifiers={{{", ".join(self.qualifiers)}}}')
return vals
def __repr__(self) -> str:
return f'{type(self).__name__}({", ".join(self.str_info())})'
@functools.total_ordering
class Conference(ConfMetaData):
__slots__ = ('acronym', 'title', 'rank', 'ranksys', 'field')
# unified ranks from all used sources, lower is better
_ranks: ClassVar[dict[str, int]] = {rk: num for num, rk in enumerate('A++ A* A+ A A- B B- C D E'.split())}
title: str
acronym: str
ranksys: tuple[str | None, ...]
rank: tuple[str | None, ...]
field: str
def __init__(self, acronym: str, title: str, rank: str | None = None, ranksys: str | None = None,
field: str | None = None, **kwargs: int | str):
super(Conference, self).__init__(title, acronym, **kwargs)
self.title = title
self.acronym = acronym
self.ranksys = (ranksys if pd.notna(ranksys) else None,)
self.rank = (rank if pd.notna(rank) else None,)
self.field = field or '(missing)'
def ranksort(self) -> int:
""" Utility to sort the ranks based on the order we want (such ash A* < A). """
return min(len(self._ranks) if rank is None else self._ranks.get(rank, len(self._ranks)) for rank in self.rank)
@classmethod
def columns(cls) -> list[str]:
""" Return column titles for cfp data """
return ['Acronym', 'Title', 'Rank', 'Rank system', 'Field']
def values(self, sort: bool = False) -> tuple[str, str, int | tuple[str | None, ...], tuple[str | None, ...], str]:
""" What we'll show """
return (self.acronym, self.title, self.ranksort() if sort else self.rank, self.ranksys, self.field)
@classmethod
def from_series(cls, series: pd.Series[str]) -> Conference:
""" Convert from a series """
return cls(series['acronym'], series['title'], series['rank'], series['ranksys'], series['field'])
@classmethod
def merge(cls, left: Conference, right: Conference) -> Conference:
new = copy_.copy(left)
# In case we have matched different acronyms, keep the version with most separations/words
if len(left.acronym_words) < len(right.acronym_words):
new.acronym, new.acronym_words = right.acronym, right.acronym_words
new.rank = left.rank + right.rank
new.ranksys = left.ranksys + right.ranksys
return new
def __eq__(self, other: object) -> bool:
if not isinstance(other, self.__class__):
return NotImplemented
return self.values() == other.values()
def __lt__(self, other: Conference) -> bool:
return self.values(True) < other.values(True)
def str_info(self) -> list[str]:
vals = [f'{slot}={getattr(self, slot)}' for slot in self.__slots__ if getattr(self, slot) != '(missing)']
vals.extend(super().str_info())
return vals
class Dates(MutableMapping[str, T]):
__slots__ = ('abstract', 'submission', 'notification', 'camera_ready', 'conf_start', 'conf_end')
def __getitem__(self, key: str) -> T:
try:
return getattr(self, key)
except AttributeError:
raise KeyError(key) from None
def __setitem__(self, key: str, value: T):
setattr(self, key, value)
def __delitem__(self, key: str):
delattr(self, key)
def __len__(self) -> int:
return sum(hasattr(self, attr) for attr in self.__slots__)
def __iter__(self) -> Iterator[str]:
return iter(attr for attr in self.__slots__ if hasattr(self, attr))
def items(self) -> ItemsView[str, T]:
for attr in self.__slots__:
try:
val = getattr(self, attr)
except AttributeError:
pass
else:
yield attr, val
class CallForPapers(ConfMetaData):
_date_names = (
'Abstract Registration Due', 'Submission Deadline', 'Notification Due', 'Final Version Due', 'startDate',
'endDate',
)
_typical_delays = {
'abstract': (95, 250),
'camera_ready': (0, 120),
'notification': (20, 150),
'submission': (40, 250),
}
__slots__ = ('acronym', 'desc', 'dates', 'orig', 'url_cfp', 'year', 'link', 'id', 'date_errors')
_url_cfpsearch: ClassVar[str]
_fill_id: ClassVar[int] = sys.maxsize
_cache: ClassVar[dict[int, CallForPapers]] = {}
_errors: ClassVar[list] = []
empty_series: ClassVar[pd.Series] = pd.Series(None, index=__slots__)
acronym: str
id: int
desc: str
year: int
dates: Dates[datetime.datetime]
orig: Dates[bool]
link: str
url_cfp: str | None
date_errors: bool | None
# Hardcoding because we can modify cfps but it doesn’t trickle up to the search results
_hardcoded_exceptions = (
('ASPLOS', 2025, 3),
)
def __init__(self, acronym: str, year: int | str, id_: int, desc: str = '',
url_cfp: str | None = None, link: str | None = None):
# Initialize parent parsing with the description
super().__init__(desc, acronym, year)
self.acronym = acronym
self.id = id_
self.desc = desc
self.year = int(year)
self.dates = Dates()
self.orig = Dates()
self.link = link or '(missing)'
self.url_cfp = url_cfp
self.date_errors = None
@classmethod
def build(cls, acronym: str, year: int | str, id_: int | None = None, desc: str = '',
url_cfp: str | None = None, link: str | None = None):
cfp_id = CallForPapers._fill_id if id_ is None else id_
try:
return CallForPapers._cache[cfp_id]
except KeyError:
pass
cfp = cls(acronym, year, cfp_id, desc, url_cfp, link)
CallForPapers._cache.update({cfp_id: cfp})
if id_ is None:
CallForPapers._fill_id -= 1
return cfp
@classmethod
def all_built_cfps(cls) -> Mapping[int, CallForPapers]:
return cls._cache
def extrapolate_missing(self, prev_cfp: CallForPapers | None):
if pd.isna(prev_cfp) or prev_cfp is None:
return self
# NB: it isn't always year = this.year, e.g. the submission can be the year before the conference dates
year_shift = self.year - prev_cfp.year
assert year_shift > 0, 'Should only extrapolate from past conferences'
if self.link == '(missing)':
self.link = prev_cfp.link
if self.url_cfp is None:
self.url_cfp = prev_cfp.url_cfp
# direct extrapolations to previous cfp + year_shift
for field in ('conf_start', 'submission'):
if field in self.dates or field not in prev_cfp.dates:
continue
n = Dates.__slots__.index(field)
try:
self.dates[field] = prev_cfp.dates[field].replace(year=prev_cfp.dates[field].year + year_shift)
except ValueError:
assert prev_cfp.dates[field].month == 2 and prev_cfp.dates[field].day == 29
self.dates[field] = prev_cfp.dates[field].replace(year=prev_cfp.dates[field].year + year_shift, day=28)
self.orig[field] = False
# extrapolate by keeping offset with other date
extrapolate_from = {
'conf_start': {'conf_end', 'camera_ready'},
'submission': {'abstract', 'notification'},
}
for orig, fields in extrapolate_from.items():
if orig not in self.dates or orig not in prev_cfp.dates:
continue
for field in (fields - self.dates.keys()) & prev_cfp.dates.keys():
self.dates[field] = self.dates[orig] + (prev_cfp.dates[field] - prev_cfp.dates[orig])
self.orig[field] = False
return self
@classmethod
def _parse_search(cls, conf: Conference, year: int | str,
soup: bs4.BeautifulSoup) -> Iterator[tuple[str, str, int, str, int]]:
""" Generate the list of conferences from a search page.
Yields:
Info on the cfp from the search page: (acronym, name, unique id, url, number of missing dates/fields)
"""
raise NotImplementedError
def _parse_cfp(self, soup: bs4.BeautifulSoup):
""" Load the cfp infos from the page soup """
raise NotImplementedError
def fetch_cfp_data(self, debug: bool = False):
""" Parse a page from online source. Load all useful data about the conference. """
if self.date_errors is not None:
return self
self.date_errors = False
assert self.url_cfp is not None, 'By definition of a check and a fetched cfp'
f = f'cache/cfp_{self.acronym.replace("/", "_")}-{self.year}-{self.id}.html'
self._parse_cfp(RequestWrapper.get_soup(self.url_cfp, f))
try:
if warn := self.verify_conf_dates():
clean_print(warn)
CallForPapers._errors.append(f'{warn.replace(":", ";", 1)};{self.url_cfp};corrected')
except CFPCheckError as err:
clean_print(f'> {err}' if debug else err)
CallForPapers._errors.append(
f'{str(err).replace(":", ";", 1)}: no satisfying correction heuristic;{self.url_cfp};ignored'
)
self.date_errors = True
try:
if warn := self.verify_submission_dates():
clean_print(warn)
CallForPapers._errors.append(f'{warn.replace(":", ";", 1)};{self.url_cfp};corrected')
except CFPCheckError as err:
clean_print(f'> {err}' if debug else err)
CallForPapers._errors.append(
f'{str(err).replace(":", ";", 1)}: no satisfying correction heuristic;{self.url_cfp};ignored'
)
self.date_errors = True
return self
@classmethod
def _flip_day_month(cls, start: datetime.date, end: datetime.date):
""" Fix a classic error of writing mm-dd-yyyy instead of dd-mm-yyyy by flipping day and month
raises:
ValueError: Invalid dates (typically a day was over 12), or resulting dates don’t make sense
"""
flip_start = start.replace(day=start.month, month=start.day)
flip_end = end.replace(day=end.month, month=end.day)
if flip_start > flip_end or flip_end >= flip_start + datetime.timedelta(days=10):
raise ValueError('Resulting dates not fitting for conference interval')
return flip_start, flip_end
def verify_conf_dates(self) -> str | None:
""" Check coherence of conference start and end dates
returns:
A message describing fixed issues, if any
raises:
CPFCheckError: An error with no satisfying correction heuristic was encountered
"""
if not {'conf_start', 'conf_end'} <= self.dates.keys():
return None
err = []
nfixes = 0
start, end = self.dates['conf_start'], self.dates['conf_end']
# Assuming no conference over new year's eve, so year should match with both dates
if start.year != self.year or end.year != self.year:
err.append('not in correct year')
start, end = start.replace(year=self.year), end.replace(year=self.year)
nfixes += 1
if end < start:
err.append('end before start')
try:
start, end = self._flip_day_month(start, end)
except ValueError:
# if that'start no good, just swap start and end
end, start = start, end
nfixes += 1
if end - start > datetime.timedelta(days=20):
err.append('too far apart')
try:
start, end = self._flip_day_month(start, end)
except ValueError:
pass # Don’t increment nfixes
else:
nfixes += 1
if not err:
return None
diag = (f'{self.acronym} {self.year} ({self.dates["conf_start"]} -- {self.dates["conf_end"]}): '
f'Conferences dates are {" and ".join(err)}')
if nfixes < len(err):
raise CFPCheckError(diag)
# Use corrected dates, taking care to mark as guesses
self.dates.update({'conf_start': start, 'conf_end': end})
self.orig['conf_start'] = self.orig['conf_end'] = False
return f'{diag}: using {start} -- {end} instead'
def verify_submission_dates(self, delete_on_err: set[str] = {'camera_ready'}) -> str | None:
""" Check coherence of submission dates, in terms of delay from a deadline to conference start
returns:
A message describing fixed issues, if any
raises:
CPFCheckError: An error with no satisfying correction heuristic was encountered
"""
if 'conf_start' not in self.dates or not self._typical_delays.keys() & self.dates.keys():
return None
err = []
uncorrected = set()
corrected = dict()
start = self.dates['conf_start']
for name, deadline in ((name, date) for name, date in self.dates.items() if name in self._typical_delays):
# Only check that deadlines happen in the year before the conference start
delay = (start - deadline).days
if delay < 0:
err.append(f'{name} ({deadline}) after conference start')
elif delay > 440: # Accept deadlines up to 1 year and 2.5 months before conference
err.append(f'{name} ({deadline}) too long before conference')
else:
continue
# If shifting the year gets us into the “typical” delay, use that date and mark as a guess
# Typical mistake for a conf in the first half of year Y, all dates are reported as year Y
# even if they should be previous year.
shifted = deadline.replace(year=deadline.year + int(delay // 365.2425))
shifted_delay = start - shifted
lo, hi = self._typical_delays[name]
if hi >= shifted_delay.days >= lo:
corrected[name] = shifted
else:
err.append(f'{err.pop()} (shifted: {shifted_delay.days}d)')
uncorrected.add(name)
if not err:
return None
diag = (f'{self.acronym} {self.year} ({self.dates["conf_start"]} -- {self.dates["conf_end"]}): '
f'Submission dates issues: {" and ".join(err)}')
if uncorrected - delete_on_err:
raise CFPCheckError(diag)
# update with shifted dates and delete uncorrectable camera ready dates to avoid raising an error
self.dates.update(corrected)
self.orig.update({name: False for name in corrected})
delete_keys = uncorrected & delete_on_err
for key in delete_keys:
del self.dates[key]
fixes = [*(f'{name}={date}' for name, date in corrected.items()), *(f'no {name}' for name in delete_keys)]
return f'{diag}: using {", ".join(fixes)} instead'