-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfpc.py
More file actions
4777 lines (4281 loc) · 195 KB
/
fpc.py
File metadata and controls
4777 lines (4281 loc) · 195 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
#!/usr/bin/env python3
"""This script runs as FPCBot on Wikimedia Commons.
It counts the votes in featured picture nominations,
closes and archives finished nominations,
adds freshly promoted featured pictures to the gallery pages,
and informs uploaders and nominators about the success.
It also processes delisting nominations.
Programmed by Daniel78 at Commons.
Updated by Eatcha, KTC, Aristeas and other Commons users.
The script is based on Pywikibot. Therefore you can use it
with Pywikibot options (so-called global options);
to list them, use '-help:global' or run 'pwb.py -help'.
In addition, the script understands the following
command line arguments for tasks and (local) options:
Tasks:
-help Print this help and exit.
-info Print status and vote count info about current nominations.
-close Close, count votes and add results to finished nominations.
-park Park closed and verified nominations.
-test Test vote counting against an old log.
-checkgallery Test the gallery links in current nominations.
Options:
-auto Do not ask before committing edits to pages.
-dry Do not commit any edits, just print them.
-threads Use threads to speed things up
(must be used with '-auto' and/or '-dry').
-fpc Process candidates for featured picture status.
-delist Process candidates for delisting from featured picture status
(if neither '-fpc' nor '-delist' is used,
all candidates are processed).
-notime Avoid displaying timestamps in log output.
-match pattern Only operate on nominations matching this pattern.
"""
# Standard library imports
from __future__ import annotations
import sys
import abc
from collections.abc import Callable
from types import FrameType
from typing import Final, Literal, Type, ClassVar, NamedTuple
import signal
import datetime
import time
import re
import unicodedata
import urllib.parse
import threading
import traceback
# Third-party imports
import pywikibot
# CONSTANTS
# Namespaces, prefixes, page names, etc.
BOT_NAME: Final[str] = "FPCBot"
FILE_NAMESPACE: Final[str] = "File:"
USER_NAMESPACE: Final[str] = "User:"
USER_TALK_NAMESPACE: Final[str] = "User talk:"
FP_PREFIX: Final[str] = "Commons:Featured pictures/"
FPC_PAGE: Final[str] = "Commons:Featured picture candidates"
CAND_PREFIX: Final[str] = f"{FPC_PAGE}/"
CAND_LOG_PREFIX: Final[str] = f"{CAND_PREFIX}Log/"
CHRONO_ARCHIVE_PREFIX: Final[str] = f"{FP_PREFIX}chronological/"
CAND_LIST_PAGE_NAME: Final[str] = f"{CAND_PREFIX}candidate list"
TEST_LOG_PAGE_NAME: Final[str] = f"{CAND_LOG_PREFIX}January 2025"
GALLERY_LIST_PAGE_NAME: Final[str] = "Commons:Featured pictures, list"
FP_TALK_PAGE_NAME: Final[str] = "Commons talk:Featured picture candidates"
UNSORTED_HEADING: Final[str] = "Unsorted"
MAX_ENTRIES_PER_LOG_PART: Final[int] = 100
# Valid voting templates
# Taken from Commons:Polling_templates, including some common redirects
SUPPORT_TEMPLATES: Final[tuple[str, ...]] = (
"[Ss]upport",
"[Ss]upp?",
"[Ss]",
"[Vv]ote[ _]support",
"[Ss]trong[ _]support",
"[Ss]Support",
"[Ww]eak[ _]support",
"[Ww]eak[ _][Ss]",
"[Ww]Support",
# Variants and translations
"[Aa][ _]favore?",
"[Aa][ _]favuri",
"[Aa]poio",
"[AaÁá][ _]fabor",
"[Dd]estek",
"[Kk]yllä",
"[Oo]ui",
"[Pp]our",
"[Pp]ro",
"[Pp]RO",
"[Ss][Ff]or",
"[Ss]amþykkt",
"[Ss]im",
"[Ss]tödjer",
"[Ss]ubteno",
"[Ss]up",
"[Ss]í",
"[Tt]acaíocht",
"[Tt]ak",
"[Tt]aurä",
"[Vv]oor",
"[Yy]es",
"[Υυ]πέρ",
"[Зз]а",
"[Пп]адтрымліваю",
"דעב",
"เห็นด้วย",
"ჰო",
"支持",
"賛成",
"찬성",
)
OPPOSE_TEMPLATES: Final[tuple[str, ...]] = (
"[Oo]ppose",
"[Oo]pp",
"[Oo]",
"[Ss]trong[ _]oppose",
"[Ss]Oppose",
"[Ww]eak[ _]oppose",
"[Ww]eak[ _][Oo]",
"[Ww]eako",
# {{FPX contested}} is counted like a normal {{oppose}} vote
"FPX[ _]contested",
# Variants and translations
"[Cc]ontr[aeo]",
"[Cc]ontrario",
"[Cc]untrariu",
"[Dd]iscordo",
"[Dd]íliostaigh",
"[Ee]i",
"[Ee]n[ _]contra",
"[Ii][ _]gcoinne",
"[Kk]ar[sş]i",
"[Kk]ontra",
"[Kk]ontraŭi",
"[Ll]ivari",
"[Mm]autohe",
"[Mm]ot",
"[Nn]ein",
"[Nn]ie",
"[Nn]o",
"[Nn]ão",
"[Oo]pponera",
"[Ss]tödjer[ _]ej",
"[Tt]egen",
"[Áá][ _]móti",
"[Пп]ротив",
"[Сс]упраць",
"נגד",
"ไม่เห็นด้วย",
"反対",
"除外",
"반대",
)
NEUTRAL_TEMPLATES: Final[tuple[str, ...]] = (
"[Nn]eutral",
"[Nn]eu",
"[Nn]",
"[Vv]n",
# Variants and translations
"[Hh]lutlaus",
"[Nn]eodrach",
"[Nn]eutr[aeo]",
"[Nn]eutrale",
"[Nn]eŭtrala",
"[Nn]iutrali",
"[Nn]øytral",
"[Oo]partisk",
"[Tt]arafs[iı]z",
"[Вв]оздерживаюсь",
"[Вв]оздржан",
"[Нн]эўтральна",
"נמנע",
"เป็นกลาง",
"中立",
"중립",
)
DELIST_TEMPLATES: Final[tuple[str, ...]] = (
"[Dd]elist",
# There are no translated versions of this template.
# Don't add {{Remove}} or {{Del}}, they are for deletion discussions.
)
DELIST_AND_REPLACE_TEMPLATES: Final[tuple[str, ...]] = (
"[Dd]elistandreplace",
"[Dd]elist[ _]and[ _][Rr]eplace",
"[Dd]ar",
"[Dd]&R",
# There are no translated versions.
)
KEEP_TEMPLATES: Final[tuple[str, ...]] = (
"[Kk]eep",
"[Kk]",
"[Vv]ote[ _]keep",
"[Vv]keep",
"[Vv]k",
"[Ss]trong[ _]keep",
"[Ww]eak[ _]keep",
"[Ww]k",
"[Vv]wk",
# Variants and translations
"[Bb]ehalten",
"[Bb]ehold",
"[Bb]ehåll",
"[Cc]onserver",
"[Gg]arder",
"[Mm]antenere?",
"[Mm]anter",
"[Ss]avi",
"[Зз]адржи",
"เก็บ",
"保留",
"維持",
)
# Shared messages
NOMINATION_SUBPAGE_RENAMED: Final[str] = (
"Fixed nomination subpage name because it could cause problems "
"with [[Template:Assessments]] and other tools."
)
PLEASE_FIX_HINT: Final[str] = (
"Please check and fix this so that the bot can process the nomination."
)
PLEASE_RENAME_HINT: Final[str] = (
"Please rename [[{subpage}]] to a suitable name "
"so that the bot can process the nomination."
)
SERIOUS_PROBLEM_CHECK_PAGE: Final[str] = (
"This is a serious problem, please check that page."
)
PLEASE_CHECK_GALLERY_AND_SORT_FPS: Final[str] = (
"Please check that gallery page and add the new featured picture(s) "
"from the nomination to the appropriate gallery page."
)
LIST_INCLUDES_MISSING_SUBPAGE: Final[str] = (
"The candidate list [[{list}]] includes the nomination [[{subpage}]], "
"but that page does not exist. Perhaps the page has been renamed "
f"and the list needs to be updated. {PLEASE_FIX_HINT}"
)
COULD_NOT_READ_RECENT_FPS_LIST: Final[str] = (
f"The bot could not read [[{GALLERY_LIST_PAGE_NAME}|the list]] "
"of recent featured pictures: {exception}. "
"Please check the list page and fix it."
)
ADDING_FPS_TO_UNSORTED_SECTION: Final[str] = (
"Therefore one or more new featured pictures are added "
"to the ''Unsorted'' section at the bottom of [[{page}]]. "
"Please sort these images into the correct section."
)
CHECK_DELISTED_FP_AND_UPDATE_ASSESSMENTS: Final[str] = (
"Please check that page and update the parameters "
"of the {{{{tl|Assessments}}}} template: "
"replace <code>featured=1</code> by <code>featured=2</code> "
"and add or update the <code>com-nom</code> parameter "
"with the value <code>{subpage}</code>."
)
# Regular expressions
# Building patterns
CAND_PREFIX_PATTERN: Final[str] = CAND_PREFIX.replace(" ", r"[ _]")
MIDDLE_NOMINATION_NAME_PATTERN: Final[str] = (
r" *(?:[Rr]emoval */ *)?(?:[Ss]et */|(?:[Ff]ile|[Ii]mage) *:) *"
)
# Identify reasonably valid FP nomination subpage names
VALID_NOMINATION_NAME_START_REGEX: Final[re.Pattern] = re.compile(
f"^{CAND_PREFIX_PATTERN}{MIDDLE_NOMINATION_NAME_PATTERN}"
)
# Find or remove the candidate prefix
CAND_PREFIX_REGEX: Final[re.Pattern] = re.compile(CAND_PREFIX_PATTERN)
# Remove the middle part of nomination names (after deleting the prefix)
MIDDLE_NOMINATION_NAME_REGEX: Final[re.Pattern] = re.compile(
MIDDLE_NOMINATION_NAME_PATTERN
)
# Remove or replace the candidate prefix and the 'File:'/'Image:' namespace,
# plus any possible crap between the prefix and the namespace
# and faulty spaces before and after the namespace.
FULL_FILE_PREFIX_REGEX: Final[re.Pattern] = re.compile(
f"^{CAND_PREFIX_PATTERN}" + r".*?(?:[Ff]ile|[Ii]mage) *: *"
)
# Look for results using the old, text-based results format
# which was in use until August 2009. An example of such a line is:
# '''result:''' 3 support, 2 oppose, 0 neutral => not featured.
OBSOLETE_RESULT_REGEX: Final[re.Pattern] = re.compile(
r"'''[Rr]esult:'''\s+(\d+)\s+support,\s+(\d+)\s+oppose,\s+(\d+)\s+neutral"
r"\s*=>\s*((?:not )?featured)"
)
OBSOLETE_DELIST_RESULT_REGEX: Final[re.Pattern] = re.compile(
r"'''[Rr]esult:'''\s+(\d+)\s+delist,\s+(\d+)\s+keep,\s+(\d+)\s+neutral"
r"\s*=>\s*((?:not )?delisted)"
)
# Look for verified results using the new, template-based format
VERIFIED_RESULT_REGEX: Final[re.Pattern] = re.compile(
r"""
\{\{\s*FPC-results-reviewed\s*\|
\s*support\s*=\s*(\d+)\s*\| # (1) Support votes
\s*oppose\s*=\s*(\d+)\s*\| # (2) Oppose votes
\s*neutral\s*=\s*(\d+)\s*\| # (3) Neutral votes
\s*featured\s*=\s*(\w+)\s*\| # (4) Featured, should be 'yes'/'no'
\s*gallery\s*=\s*([^|\n]*) # (5) Gallery link (if featured)
(?:\|\s*alternative\s*=\s*([^|\n]*))? # (6) For candidates with alternatives:
.*?\}\} # name of the winning image
""",
flags=re.VERBOSE,
)
VERIFIED_DELIST_RESULT_REGEX: Final[re.Pattern] = re.compile(
r"""
\{\{\s*FPC-delist-results-reviewed\s*\|
\s*delist\s*=\s*(\d+)\s*\| # (1) Delist votes
\s*keep\s*=\s*(\d+)\s*\| # (2) Keep votes
\s*neutral\s*=\s*(\d+)\s*\| # (3) Neutral votes
\s*delisted\s*=\s*(\w+) # (4) Delisted, should be 'yes'/'no'
.*?\}\}
""",
flags=re.VERBOSE,
)
# Simple regexes which check just whether a certain template is present or not
COUNTED_TEMPLATE_REGEX: Final[re.Pattern] = re.compile(
r"\{\{\s*FPC-results-unreviewed.*?\}\}"
)
REVIEWED_TEMPLATE_REGEX: Final[re.Pattern] = re.compile(
r"\{\{\s*FPC-results-reviewed.*?\}\}"
)
DELIST_COUNTED_TEMPLATE_REGEX: Final[re.Pattern] = re.compile(
r"\{\{\s*FPC-delist-results-unreviewed.*?\}\}"
)
DELIST_REVIEWED_TEMPLATE_REGEX: Final[re.Pattern] = re.compile(
r"\{\{\s*FPC-delist-results-reviewed.*?\}\}"
)
# Find voting templates
VOTING_TEMPLATE_MODEL: Final[str] = r"\{\{\s*(?:%s)\s*(\|.*?)?\s*\}\}"
SUPPORT_VOTE_REGEX: Final[re.Pattern] = re.compile(
VOTING_TEMPLATE_MODEL % "|".join(SUPPORT_TEMPLATES)
)
OPPOSE_VOTE_REGEX: Final[re.Pattern] = re.compile(
VOTING_TEMPLATE_MODEL % "|".join(OPPOSE_TEMPLATES)
)
NEUTRAL_VOTE_REGEX: Final[re.Pattern] = re.compile(
VOTING_TEMPLATE_MODEL % "|".join(NEUTRAL_TEMPLATES)
)
DELIST_VOTE_REGEX: Final[re.Pattern] = re.compile(
VOTING_TEMPLATE_MODEL % "|".join(DELIST_TEMPLATES)
)
DELIST_AND_REPLACE_VOTE_REGEX: Final[re.Pattern] = re.compile(
VOTING_TEMPLATE_MODEL % "|".join(DELIST_AND_REPLACE_TEMPLATES)
)
KEEP_VOTE_REGEX: Final[re.Pattern] = re.compile(
VOTING_TEMPLATE_MODEL % "|".join(KEEP_TEMPLATES)
)
# Does the nomination contain a {{Withdraw(n)}}, {{FPX}} or {{FPD}} template?
WITHDRAWN_FPX_FPD_REGEX: Final[re.Pattern] = re.compile(
r"\{\{\s*([Ww](?:ithdrawn?|dn)|[Ff]P[XD])\s*(\|.*?)?\}\}"
)
# Does the nomination contain subheadings = subsections?
SECTION_REGEX: Final[re.Pattern] = re.compile(
r"^={1,4}.+={1,4}\s*$", flags=re.MULTILINE
)
# Find or count displayed images
IMAGES_REGEX: Final[re.Pattern] = re.compile(
# Because Mediawiki page names can't contain '|', '[', ']', etc.,
# capturing group 2 stops at the end of the actual image filename,
# regardless whether there is a '|...' or not.
r"(\[\[((?:[Ff]ile|[Ii]mage):[^|\]]+).*?\]\])"
)
# Look for a size specification in the image link
IMAGE_SIZE_REGEX: Final[re.Pattern] = re.compile(r"\|.*?(\d+)\s*px")
# Check if there is a 'thumb' parameter in the image link
IMAGE_THUMB_REGEX: Final[re.Pattern] = re.compile(r"\|\s*thumb\b")
# Search nomination for the username of the original creator
CREATOR_NAME_REGEX: Final[re.Pattern] = re.compile(
r"\{\{[Ii]nfo\}\}.+?"
r"[Cc]reated +(?:(?:and|\&) +(?:[a-z]+ +)?uploaded +)?by +"
r"\[\[[Uu]ser:([^|\]\n]+)[|\]]"
)
# Search for first entry in (or end of) <gallery>...</gallery> contents
GALLERY_ENTRY_START_REGEX: Final[re.Pattern] = re.compile(r">(?: *\n)*")
# Find the {{Assessments}} template on an image description page
# (sometimes people break it into several lines, so use '\s' and re.DOTALL)
ASSESSMENTS_TEMPLATE_REGEX: Final[re.Pattern] = re.compile(
r"\{\{\s*[Aa]ssessments\s*(\|.*?)\}\}", flags=re.DOTALL
)
# Find the associated <gallery> element right after the target subheading.
# Between subheading and <gallery> we allow only:
# 1. a single line (e.g. a 'See also' hint) which must not be a subheading,
# <gallery>, etc.; or
# 2. a comment which can span several lines.
ASSOC_GALLERY_ELEMENT_REGEX: Final[re.Pattern] = re.compile(
r"((?:[^<= \n][^\n]+\n\s*| *<!--.+?-->\s*)?<gallery\b[^>]*>)\s*", flags=re.DOTALL
)
# Find 'Featured pictures of/from/by ...' categories which must be removed
# if a FP is delisted. If the category is followed by a NL, remove it, too.
# NB: We must not touch project-specific categories like 'Featured pictures
# on Wikipedia, <language>', hence the negative lookahead assertion '(?!on )'.
TOPICAL_FP_CATEGORY_REGEX: Final[re.Pattern] = re.compile(
r"\[\[[Cc]ategory: *Featured (?:"
r"pictures (?!on ).+?"
r"|(?:[a-z -]+)?photo(?:graphs|graphy|s).*?"
r"|(?:diagrams|maps).*?"
r")\]\] *\n?"
)
# Other data
# Some frequent auxiliary character translations for sort keys
AUXILIARY_SORT_KEY_TRSL_TABLE: Final[dict[int, str]] = str.maketrans(
{"Æ": "AE", "Œ": "OE", "æ": "ae", "œ": "oe", "ß": "ss"}
)
# GLOBALS
# Apply all changes without asking the user
_g_auto: bool = False
# Dry run, do not save any changes
_g_dry: bool = False
# Use threads
_g_threads: bool = False
# Don't print timestamps in CLI/log output
_g_log_no_time: bool = False
# Process only nominations with a name matched by this pattern
_g_match_pattern: str = ""
# Flag that will be set to True if CTRL-C was pressed
_g_abort: bool = False
# Pywikibot Site object
_g_site: pywikibot.site.BaseSite | None = None
# Number of the current log part
_g_log_part_no: int | None = None
# CLASSES
class DataAlreadyPresentError(Exception):
"""The data we wanted to add are already present on the page.
This can happen if the process has previously been interrupted.
"""
pass
class CouldNotAddDataError(Exception):
"""Error during data insertion on a Commons page."""
pass
class CandidateTypesToProcess(NamedTuple):
"""Class keeping track of the types of nominations we want to process.
Attributes:
fp: Boolean indicating whether to process FP candidates or not.
delist: Boolean indicating whether to process delisting candidates.
"""
# Declare types of instance variables
fp: bool
delist: bool
def candidate_class(self, subpage_name: str) -> Type[Candidate] | None:
"""Find out if should we process a nomination, and with which class.
Args:
subpage_name: Full name of a nomination subpage.
Returns:
The correct Candidate subclass to be used for that nomination,
or None if we should not process that type of nomination.
"""
if re.search(r"/ *[Rr]emoval */", subpage_name):
return DelistCandidate if self.delist else None
# Default:
return FPCandidate if self.fp else None
def describe(self) -> str:
"""Summarize the types of candidates we want to process."""
types = [
entry[1] for entry in zip(self, self._fields) # pylint: disable=no-member
if entry[0]
]
return f"{', '.join(types)} candidates"
class ThreadCheckCandidate(threading.Thread):
"""A thread executing one of the bot's task on a single candidate."""
# Declare types of instance variables
_candidate: Candidate # The candidate/nomination handled in this thread
_check: Callable[[Candidate], None] # The method for the desired task
def __init__(
self,
candidate: Candidate,
check: Callable[[Candidate], None],
) -> None:
"""Initialize the thread.
Args:
candidate: The Candidate subclass object to process.
check: The Candidate class method which should be called.
"""
super().__init__()
self._candidate = candidate
self._check = check
def run(self) -> None:
"""Execute the desired task for the candidate."""
self._check(self._candidate)
self._candidate.clear_cache()
class Candidate(abc.ABC):
"""A featured picture candidate (nomination)
This abstract base class bundles all common attributes and methods.
All individual candidates (nominations) are represented by instances
of the concrete subclasses.
"""
# Define class constants
# (these are the values for a normal FP nomination,
# subclasses must adapt them as needed)
# Keyword for the title etc. of a successful nomination:
_SUCCESS_KEYWORD: ClassVar[str] = "featured"
# Keyword for the title etc. of a failed nomination:
_FAIL_KEYWORD: ClassVar[str] = "not featured"
# Compiled regex to find positive votes in the nomination:
_PRO_VOTE_REGEX: ClassVar[re.Pattern] = SUPPORT_VOTE_REGEX
# Compiled regex to find negative votes in the nomination:
_CONTRA_VOTE_REGEX: ClassVar[re.Pattern] = OPPOSE_VOTE_REGEX
# Compiled regex to find neutral votes in the nomination:
_NEUTRAL_VOTE_REGEX: ClassVar[re.Pattern] = NEUTRAL_VOTE_REGEX
# Compiled regex to find templates containing unreviewed results:
_COUNTED_RES_REGEX: ClassVar[re.Pattern] = COUNTED_TEMPLATE_REGEX
# Compiled regex to find templates containing reviewed results:
_REVIEWED_RES_REGEX: ClassVar[re.Pattern] = REVIEWED_TEMPLATE_REGEX
# Compiled regex to analyse the template with reviewed results:
_VERIFIED_RES_REGEX: ClassVar[re.Pattern] = VERIFIED_RESULT_REGEX
# Compiled regex to analyse the obsolete format for reviewed results:
_OBSOLETE_RES_REGEX: ClassVar[re.Pattern] = OBSOLETE_RESULT_REGEX
# Declare types of instance variables
_list_page_name: str # Name of the candidates list page on Commons
_page: pywikibot.Page # The nomination subpage for this candidate
_filtered_content: str | None # Text of the nomination w/o comments etc.
_creation_time: datetime.datetime | None # Creation time of the nomination
_days_old: int # How many days passed since the nomination was created?
_days_since_last_edit: int # How many days passed since it was edited?
_creator: str | None # Username of the creator of the nominated image
_uploader: dict[str, str] # Mapping: filename -> username of uploader
_nominator: str | None # Username of the creator of the nomination
_image_count: int | None # Count of (full-size) images in the nomination
_filename: str | None # Name of the nominated image, empty if not found
_alternative: str | None # If there are alternatives: selected image name
_set_files: list[str] | None # Names of nominated images (for set noms)
_pro: int # Count of pro votes
_con: int # Count of contra votes
_neu: int # Count of neutral votes
def __init__(self, page: pywikibot.Page, list_name: str) -> None:
"""Initialize the candidate object.
Although this is an abstract base class, the initializer is called
by the concrete subclasses.
Args:
page: A pywikibot.Page object for the nomination subpage.
list_name: A string with the name of the candidate list page.
"""
# Save passed values
self._list_page_name = list_name
self._page = page
# Set other instance variables to default values
self._filtered_content = None
self._creation_time = None
self._days_old = -1
self._days_since_last_edit = -1
self._creator = None
self._uploader: dict[str, str] = {}
self._nominator = None
self._image_count = None
self._filename = None
self._alternative = None
self._set_files = None
self._pro = -1
self._con = -1
self._neu = -1
@property
def page(self) -> pywikibot.Page:
"""Return the nomination subpage for this candidate."""
return self._page
def print_all_info(self) -> None:
"""Print a line with current status information about this candidate.
This method is used to generate the '-info' overview of all
open nominations.
"""
try:
self.count_votes()
out(
f"{self.cut_title()}: "
f"{self._type_code()} "
f"P:{self._pro:02d} "
f"C:{self._con:02d} "
f"N:{self._neu:02d} "
f"Do:{self.days_old():02d} "
f"De:{self.days_since_last_edit():02d} "
f"Se:{self.section_count():02d} "
f"Im:{self.image_count():02d} "
f"W:{y_n(bool(self.was_cancelled()))} "
f"S:{'?' if self.is_ignored() else y_n(self.is_passed())} "
f"({self.status_string()})"
)
except pywikibot.exceptions.NoPageError:
error(f"{self.cut_title()}: -- No such page --")
def filtered_content(self) -> str:
"""Return a filtered version of the wikitext of the nomination subpage.
The filtered version omits all comments, stricken text, code examples,
etc.; it is used for counting the votes etc., and cached because
we need it often. If you change the text of the nomination subpage,
call reset_filtered_content() to flag the cached version as outdated.
"""
if self._filtered_content is None:
self._filtered_content = filter_content(self._page.get(get_redirect=False))
return self._filtered_content
def reset_filtered_content(self) -> None:
"""Flag filtered content as outdated after changing page contents."""
self._filtered_content = None
def clear_cache(self) -> None:
"""Clear all cached page contents."""
self._page.clear_cache()
self._filtered_content = None
def creator(self, link: bool) -> str:
"""Return the name of the user who has originally created the image(s).
There is no generally applicable way to determine the creator.
Therefore nominators should use the phrase
'{{Info}} ... created by [[User:...]]'
on the nomination subpage in order to identify the original creator
(we also support some common variants, see the regex constant).
Args:
link: Pass True to get a link to the user page, False to get
just the plain username.
Returns:
If the expected phrase is found, the function returns the username
resp. a link to the user page, else just ''.
"""
if self._creator is None:
if match := CREATOR_NAME_REGEX.search(self.filtered_content()):
self._creator = match.group(1).replace("_", " ").strip()
else:
self._creator = ""
if self._creator and link:
return user_page_link(self._creator)
return self._creator
def uploader(self, filename: str, link: bool) -> str:
"""Return the name of the user who has originally uploaded the image.
This method works differently than nominator() because all files of
a set must have the same nominator, but can have different uploaders,
therefore we need to specify the individual filename.
Args:
filename: The name of the image on Commons.
link: Pass True to get a link to the user page, False to get
just the plain username.
Returns:
The username resp. a link to the user page; on errors 'Unknown'.
"""
try:
username = self._uploader[filename]
except KeyError:
username = oldest_revision_user(pywikibot.Page(_g_site, filename))
self._uploader[filename] = username
if username:
return user_page_link(username) if link else username
return "Unknown"
def nominator(self, link: bool) -> str:
"""Return the name of the user who has created the nomination subpage.
Args:
link: Pass True to get a link to the user page, False to get
just the plain username.
Returns:
The username resp. a link to the user page; on errors 'Unknown'.
"""
if self._nominator is None:
self._nominator = oldest_revision_user(self._page)
if self._nominator:
return user_page_link(self._nominator) if link else self._nominator
return "Unknown"
def is_set(self) -> bool:
"""Find out if this candidate is a set nomination."""
return re.search(r"/ *[Ss]et */", self._page.title()) is not None
def set_files(self) -> list[str]:
"""Return the names of all nominated images from a set nomination.
The method tries to retrieve the filenames from a <gallery> element
in the nomination subpage, checks if the individual files exist
and resolves any redirects.
Problems are reported on the FPC talk page.
For single-file nominations, use filename() instead.
Returns:
A list with the names of all nominated image files;
on errors the result is an empty list.
"""
# Use cached result if possible
if self._set_files is not None:
return self._set_files
# Change default value from None (meaning 'not retrieved yet')
# to an empty list (meaning 'files not OK'; used if we return early)
self._set_files = []
# Extract contents of the first <gallery>...</gallery> element
subpage_name = self._page.title()
cut_title = self.cut_title()
match = re.search(
r"<gallery[^>]*>(.+?)</gallery>",
self.filtered_content(),
flags=re.DOTALL,
)
if not match:
error(f"{cut_title}: (Error: no <gallery> in set nomination)")
ask_for_help(
f"In the set nomination [[{subpage_name}]], the bot "
"did not find the <code><nowiki><gallery></nowiki></code> "
"element with the nominated images. "
f"Perhaps the formatting is damaged. {PLEASE_FIX_HINT}"
)
return []
text_inside_gallery = match.group(1)
# First try to find files which are properly listed with 'File:'
# or 'Image:' prefix; they must be the first element on their line,
# but leading whitespace is tolerated:
files_list = re.findall(
r"^ *(?:[Ff]ile|[Ii]mage) *:([^\n|]+)",
text_inside_gallery,
flags=re.MULTILINE,
)
if not files_list:
# If we did not find a single file, let's try a casual search
# for lines which, ahem, seem to start with an image filename:
files_list = re.findall(
r"^ *([^|\n:<>\[\]]+\.(?:jpe?g|tiff?|png|svg|webp|xcf))",
text_inside_gallery,
flags=re.MULTILINE | re.IGNORECASE,
)
if not files_list:
# Still no files found, so we must skip this candidate
error(f"{cut_title}: (Error: found no images in set)")
ask_for_help(
f"The set nomination [[{subpage_name}]] seems to contain no images. "
f"Perhaps the formatting is damaged. {PLEASE_FIX_HINT}"
)
return []
# Format and check filenames, resolve any redirects
for i, filename in enumerate(files_list, start=0):
# Add (back) the 'File:' prefix (our search omits the prefixes)
filename = f"{FILE_NAMESPACE}{filename.replace('_', ' ').strip()}"
page = pywikibot.Page(_g_site, filename)
if not page.exists():
# File not found, skip this candidate
error(f"{cut_title}: (Error: can't find set image '{filename}')")
ask_for_help(
f"The set nomination [[{subpage_name}]] lists the image "
f"[[:{filename}]], but that image file does not exist. "
f"Perhaps it has been renamed or deleted. {PLEASE_FIX_HINT}"
)
return []
if page.isRedirectPage():
try:
page = page.getRedirectTarget()
except pywikibot.exceptions.PageRelatedError:
# Circular or invalid redirect etc., skip candidate
error(
f"{cut_title}: (Error: invalid redirect "
f"in set image '{filename}')"
)
ask_for_help(
f"The set nomination [[{subpage_name}]] lists the image "
f"[[:{filename}]], but the image page contains "
f"a circular or invalid redirect. {PLEASE_FIX_HINT}"
)
return []
if not page.exists():
# Broken redirect, skip candidate
error(
f"{cut_title}: (Error: broken redirect "
f"in set image '{filename}')"
)
ask_for_help(
f"The set nomination [[{subpage_name}]] lists the image "
f"[[:{filename}]], but the image page redirects to a file "
f"or page which does not exist. {PLEASE_FIX_HINT}"
)
return []
out(f"Resolved redirect: '{filename}' -> '{page.title()}'.")
filename = page.title() # Update filename.
files_list[i] = filename
# Save and return files list
self._set_files = files_list
return files_list
def find_gallery_of_file(self) -> str:
"""Find and polish the gallery link in the nomination subpage."""
if match := re.search(
r"Gallery[^\n]+?\[\[[Cc]ommons: ?[Ff]eatured[_ ]pictures ?\/([^\n\]]+)",
self.filtered_content(),
):
return clean_gallery_link(match.group(1))
return ""
def count_votes(self) -> None:
"""Count all votes in this nomination."""
if self._pro > -1:
return # Votes are already counted.
if text := self.filtered_content():
self._pro = len(self._PRO_VOTE_REGEX.findall(text))
self._con = len(self._CONTRA_VOTE_REGEX.findall(text))
self._neu = len(self._NEUTRAL_VOTE_REGEX.findall(text))
else:
error(f"Error - '{self._page.title()}' has no real content")
def was_cancelled(self, uppercase: bool = False) -> str | Literal[False]:
"""Find out if the nomination has been withdrawn, FPXed or FPDed.
Nominators can withdraw any of their nominations by adding
the template {{Withdraw}} to it.
Users can mark a nomination as hopeless with the {{FPX}} template
or deny a nomination (because the nominator has exceeded the limit
for simultaneous nominations) with the {{FPD}} template.
Args:
uppercase: Should the return value start with an uppercase letter
if it is a string?
Returns:
A short string which denotes that the nomination has been
withdrawn, FPXed or FPDed; or False if this is not the case.
"""
if result := WITHDRAWN_FPX_FPD_REGEX.search(self.filtered_content()):
# Distinguish templates on the basis of the name's last letter
match result.group(1)[-1]:
case "X":
return "FPXed"
case "D":
return "FPDed"
case _:
return "Withdrawn" if uppercase else "withdrawn"
return False
def rules_of_fifth_day(self) -> bool:
"""Find out if the rules of the 5th day apply to this nomination.
The rules of the 5th day allow to close a nomination already
at the 5th day after its creation if it is hopeless (less than two
support votes) or a clear winner (10 or more support votes,
no oppose votes). They do not apply to nominations with alternatives
because with them the voters' favour can change at any time.
"""
if self.days_old() < 5:
return False
# Rules of the fifth day don't apply to nominations with alternatives
if self.image_count() > 1:
return False
self.count_votes()
# First rule of the fifth day
if self._pro <= 1:
return True
# Second rule of the fifth day
if self._pro >= 10 and self._con == 0:
return True
# If we arrive here, no rule applies
return False
def close(self) -> None:
"""Close the nomination if it is finished.
If the nomination is finished, the function adds a provisional result
to the nomination subpage.
Withdrawn, FPXed and FPDed nominations are just moved to the FPC log.
"""
subpage_name = self._page.title()
cut_title = self.cut_title()
# First make sure that the page actually exists
if not self._page.exists():
error(f"{cut_title}: (Error: no such page?!)")
ask_for_help(
LIST_INCLUDES_MISSING_SUBPAGE.format(
list=self._list_page_name, subpage=subpage_name
)
)
return
# Close a withdrawn or FPXed/FPDed nomination if at least one full day
# has passed since the last edit
if reason := self.was_cancelled():
old_enough = self.days_since_last_edit() > 0
action = "closing" if old_enough else "but waiting a day"
out(f"{cut_title}: {reason}, {action}")
if old_enough:
self.move_to_log(reason)
return
# Is the nomination still active?
fifth_day = self.rules_of_fifth_day()
if not self.is_done() and not fifth_day:
out(f"{cut_title}: (still active, ignoring)")
return
# Is there any other reason not to close the nomination?
try:
filtered_text = self.filtered_content()
except pywikibot.exceptions.PageRelatedError as exc:
error(f"{cut_title}: (Error: is not readable)")
ask_for_help(
f"The bot could not read the nomination subpage [[{subpage_name}]]: "
f"{format_exception(exc)}. {PLEASE_FIX_HINT}"
)
return
if not filtered_text:
error(f"{cut_title}: (Error: has no real content)")
ask_for_help(
f"The nomination subpage [[{subpage_name}]] seems to be empty. "
f"{PLEASE_FIX_HINT}"
)
return
if re.search(r"\{\{\s*FPC-closed-ignored.*\}\}", filtered_text):
out(f"{cut_title}: (marked as ignored, so ignoring)")
return
if self._COUNTED_RES_REGEX.search(filtered_text):
out(f"{cut_title}: (needs review, ignoring)")
return
if self._REVIEWED_RES_REGEX.search(filtered_text):
out(f"{cut_title}: (already closed and reviewed, ignoring)")
return
# OK, we should close the nomination
if self.image_count() <= 1:
self.count_votes()
old_text = self._page.get(get_redirect=False)
new_text = old_text.rstrip() + "\n\n" + self.get_result_string()
if self.image_count() <= 1:
new_text = self.fix_heading(new_text)
# Save the new text of the nomination subpage
summary = self.get_close_edit_summary(fifth_day)
commit(old_text, new_text, self._page, summary)
self.reset_filtered_content()
def fix_heading(self, text: str, value: str | None = None) -> str:
"""Append a result keyword to the heading of the nomination subpage.
The function appends the keyword '(not) featured' or '(not) delisted'
to the heading of the nomination subpage, depending on the result.
It reports if the nomination does not start correctly with a heading.