-
Notifications
You must be signed in to change notification settings - Fork 0
/
checkimages.py
1959 lines (1776 loc) · 85.9 KB
/
checkimages.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/python
# -*- coding: utf-8 -*-
"""
Script to check recently uploaded files. This script checks if a file
description is present and if there are other problems in the image's
description.
This script will have to be configured for each language. Please submit
translations as addition to the pywikipediabot framework.
Everything that needs customisation is indicated by comments.
This script understands the following command-line arguments:
-limit The number of images to check (default: 80)
-commons The Bot will check if an image on Commons has the same name
and if true it reports the image.
-duplicates[:#] Checking if the image has duplicates (if arg, set how many
rollback wait before reporting the image in the report
instead of tag the image) default: 1 rollback.
-duplicatesreport Report the duplicates in a log *AND* put the template in
the images.
-sendemail Send an email after tagging.
-break To break the bot after the first check (default: recursive)
-time[:#] Time in seconds between repeat runs (default: 30)
-wait[:#] Wait x second before check the images (default: 0)
-skip[:#] The bot skip the first [:#] images (default: 0)
-start[:#] Use allpages() as generator
(it starts already form File:[:#])
-cat[:#] Use a category as generator
-regex[:#] Use regex, must be used with -url or -page
-page[:#] Define the name of the wikipage where are the images
-url[:#] Define the url where are the images
-untagged[:#] Use daniel's tool as generator:
http://toolserver.org/~daniel/WikiSense/UntaggedImages.php
-nologerror If given, this option will disable the error that is risen
when the log is full.
---- Instructions for the real-time settings ----
* For every new block you have to add:
<------- ------->
In this way the Bot can understand where the block starts in order to take the
right parameter.
* Name= Set the name of the block
* Find= Use it to define what search in the text of the image's description,
while
Findonly= search only if the exactly text that you give is in the image's
description.
* Summary= That's the summary that the bot will use when it will notify the
problem.
* Head= That's the incipit that the bot will use for the message.
* Text= This is the template that the bot will use when it will report the
image's problem.
---- Known issues/FIXMEs: ----
* Clean the code, some passages are pretty difficult to understand if you're not
the coder.
* Add the "catch the language" function for commons.
* Fix and reorganise the new documentation
* Add a report for the image tagged.
"""
#
# (C) Kyle/Orgullomoore, 2006-2007 (newimage.py)
# (C) Siebrand Mazeland, 2007-2010
# (C) Filnik, 2007-2011
# (C) Pywikipedia team, 2007-2013
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id$'
#
import re
import time
import datetime
import locale
import urllib
import wikipedia as pywikibot
import pagegenerators as pg
import catlib
import config
import query
import userlib
locale.setlocale(locale.LC_ALL, '')
###############################################################################
# <--------------------------- Change only below! --------------------------->#
###############################################################################
# NOTE: in the messages used by the Bot if you put __botnick__ in the text, it
# will automatically replaced with the bot's nickname.
# That's what you want that will be added. (i.e. the {{no source}} with the
# right day/month/year )
n_txt = {
'commons': u'{{subst:nld}}',
'ar': u'{{subst:لم}}',
'de': u'{{Dateiüberprüfung}}',
'en': u'{{subst:nld}}',
'fa': u'{{جا:حق تکثیر تصویر نامعلوم}}',
'fr': u'{{subst:lid}}',
'ga': u'{{subst:Ceadúnas de dhíth}}',
'hu': u'{{nincslicenc|~~~~~}}',
'it': u'{{subst:unverdata}}',
'ja': u'{{subst:Nld}}',
'ko': u'{{subst:nld}}',
'ta': u'{{subst:nld}}',
'ur': u'{{subst:حقوق نسخہ تصویر نامعلوم}}',
'zh': u'{{subst:No license/auto}}',
}
# Text that the bot will try to see if there's already or not. If there's a
# {{ I'll use a regex to make a better check.
# This will work so:
# '{{no license' --> '\{\{(?:template:)?no[ _]license ?(?:\||\n|\}|/) ?' (case
# insensitive).
# If there's not a {{ it will work as usual (if x in Text)
txt_find = {
'commons': [u'{{no license', u'{{no license/en',
u'{{nld', u'{{no permission', u'{{no permission since'],
'ar': [u'{{لت', u'{{لا ترخيص'],
'de': [u'{{DÜP', u'{{Düp', u'{{Dateiüberprüfung'],
'en': [u'{{nld', u'{{no license'],
'fa': [u'{{حق تکثیر تصویر نامعلوم'],
'ga': [u'{{Ceadúnas de dhíth', u'{{Ceadúnas de dhíth'],
'hu': [u'{{nincsforrás', u'{{nincslicenc'],
'it': [u'{{unverdata', u'{{unverified'],
'ja': [u'{{no source', u'{{unknown',
u'{{non free', u'<!--削除についての議論が終了するまで'],
'ta': [u'{{no source', u'{{nld', u'{{no license'],
'ko': [u'{{출처 없음', u'{{라이선스 없음', u'{{Unknown'],
'ur': [u'{{ناحوالہ', u'{{اجازہ نامعلوم', u'{{Di-no'],
'zh': [u'{{no source', u'{{unknown', u'{{No license'],
}
# Summary for when the will add the no source
msg_comm = {
'ar': u'بوت: التعليم على ملف مرفوع حديثا غير موسوم',
'commons': u'Bot: Marking newly uploaded untagged file',
'de': u'Bot: Markiere mit {{[[Wikipedia:Dateiüberprüfung/Anleitung|DÜP]]}},'
u' da keine Lizenzvorlage gefunden — bitte nicht entfernen,'
u' Informationen bald auf der Benutzerdiskussion des Uploaders.',
'en': u'Bot: Marking newly uploaded untagged file',
'fa': u'ربات: حق تکثیر تصویر تازه بارگذاری شده نامعلوم است.',
'ga': u'Róbó: Ag márcáil comhad nua-uaslódáilte gan ceadúnas',
'hu': u'Robot: Frissen feltöltött licencsablon nélküli fájl megjelölése',
'it': u"Bot: Aggiungo unverified",
'ja': u'ロボットによる:著作権情報なしの画像をタグ',
'ko': u'로봇:라이선스 없음',
'ta': u'தானியங்கி:காப்புரிமை வழங்கப்படா படிமத்தை சுட்டுதல்',
'ur': u'روبالہ:نشان زدگی جدید زبراثقال شدہ املاف',
'zh': u'機器人:標示新上傳且未包含必要資訊的檔案',
}
# When the Bot find that the usertalk is empty is not pretty to put only the
# no source without the welcome, isn't it?
empty = {
'commons': u'{{subst:welcome}}\n~~~~\n',
'ar': u'{{ترحيب}}\n~~~~\n',
'de': u'{{subst:willkommen}} ~~~~',
'en': u'{{welcome}}\n~~~~\n',
'fa': u'{{جا:خوشامدید|%s}}',
'fr': u'{{Bienvenue nouveau\n~~~~\n',
'ga': u'{{subst:Fáilte}} - ~~~~\n',
'hu': u'{{subst:Üdvözlet|~~~~}}\n',
'it': u'<!-- inizio template di benvenuto -->\n{{subst:Benvebot}}\n~~~~\n<!-- fine template di benvenuto -->',
'ja': u'{{subst:Welcome/intro}}\n{{subst:welcome|--~~~~}}\n',
'ko': u'{{환영}}--~~~~\n',
'ta': u'{{welcome}}\n~~~~\n',
'ur': u'{{خوش آمدید}}\n~~~~\n',
'zh': u'{{subst:welcome|sign=~~~~}}',
}
# Summary that the bot use when it notify the problem with the image's license
msg_comm2 = {
'ar': u'بوت: طلب معلومات المصدر.',
'commons': u'Bot: Requesting source information.',
'de': u'Bot:Notify User',
'en': u'Robot: Requesting source information.',
'fa': u'ربات: درخواست منبع تصویر',
'ga': u'Róbó: Ag iarraidh eolais foinse.',
'it': u"Bot: Notifico l'unverified",
'hu': u'Robot: Forrásinformáció kérése',
'ja': u'ロボットによる:著作権情報明記のお願い',
'ko': u'로봇:라이선스 정보 요청',
'ta': u'தானியங்கி:மூலம் வழங்கப்படா படிமத்தை சுட்டுதல்',
'ur': u'روبالہ:درخواست ماخذ تصویر',
'zh': u'機器人:告知用戶',
}
# if the file has an unknown extension it will be tagged with this template.
# In reality, there aren't unknown extension, they are only not allowed...
delete_immediately = {
'commons': u"{{speedy|The file has .%s as extension. Is it ok? Please check.}}",
'ar': u"{{شطب|الملف له .%s كامتداد.}}",
'en': u"{{db-meta|The file has .%s as extension.}}",
'fa': u"{{حذف سریع|تصویر %s اضافی است.}}",
'ga': u"{{scrios|Tá iarmhír .%s ar an comhad seo.}}",
'hu': u'{{azonnali|A fájlnak .%s a kiterjesztése}}',
'it': u'{{cancella subito|motivo=Il file ha come estensione ".%s"}}',
'ja': u'{{db|知らないファイルフォーマット %s}}',
'ko': u'{{delete|잘못된 파일 형식 (.%s)}}',
'ta': u'{{delete|இந்தக் கோப்பு .%s என்றக் கோப்பு நீட்சியைக் கொண்டுள்ளது.}}',
'ur': u"{{سریع حذف شدگی|اس ملف میں .%s بطور توسیع موجود ہے۔ }}",
'zh': u'{{delete|未知檔案格式%s}}',
}
# The header of the Unknown extension's message.
delete_immediately_head = {
'commons': u"\n== Unknown extension! ==\n",
'ar': u"\n== امتداد غير معروف! ==\n",
'en': u"\n== Unknown extension! ==\n",
'fa': u"\n==بارگذاری تصاویر موجود در انبار==\n",
'ga': u"\n== Iarmhír neamhaithnid! ==\n",
'fr': u'\n== Extension inconnue ==\n',
'hu': u'\n== Ismeretlen kiterjesztésű fájl ==\n',
'it': u'\n\n== File non specificato ==\n',
'ko': u'\n== 잘못된 파일 형식 ==\n',
'ta': u'\n== இனங்காணப்படாத கோப்பு நீட்சி! ==\n',
'ur': u"\n== نامعلوم توسیع! ==\n",
'zh': u'\n==您上載的檔案格式可能有誤==\n',
}
# Text that will be add if the bot find a unknown extension.
delete_immediately_notification = {
'ar': u'الملف [[:File:%s]] يبدو أن امتداده خاطيء, من فضلك تحقق. ~~~~',
'commons': u'The [[:File:%s]] file seems to have a wrong extension, please check. ~~~~',
'en': u'The [[:File:%s]] file seems to have a wrong extension, please check. ~~~~',
'fa': u'به نظر میآید تصویر [[:تصویر:%s]] مسیر نادرستی داشته باشد لطفا بررسی کنید.~~~~',
'ga': u'Tá iarmhír mícheart ar an comhad [[:File:%s]], scrúdaigh le d\'thoil. ~~~~',
'fr': u'Le fichier [[:File:%s]] semble avoir une mauvaise extension, veuillez vérifier. ~~~~',
'hu': u'A [[:Kép:%s]] fájlnak rossz a kiterjesztése, kérlek ellenőrízd. ~~~~',
'it': u'{{subst:Progetto:Coordinamento/Immagini/Bot/Messaggi/Ext|%s|__botnick__}} --~~~~',
'ko': u'[[:그림:%s]]의 파일 형식이 잘못되었습니다. 확인 바랍니다.--~~~~',
'ta': u'[[:படிமம்:%s]] இனங்காணப்படாத கோப்பு நீட்சியை கொண்டுள்ளது தயவு செய்து ஒரு முறை சரி பார்க்கவும் ~~~~',
'ur': u'ملف [[:File:%s]] کی توسیع شاید درست نہیں ہے، براہ کرم جانچ لیں۔ ~~~~',
'zh': u'您好,你上傳的[[:File:%s]]無法被識別,請檢查您的檔案,謝謝。--~~~~',
}
# Summary of the delete immediately.
# (e.g: Adding {{db-meta|The file has .%s as extension.}})
msg_del_comm = {
'ar': u'بوت: إضافة %s',
'commons': u'Bot: Adding %s',
'en': u'Bot: Adding %s',
'fa': u'ربات: اضافه کردن %s',
'ga': u'Róbó: Cuir %s leis',
'fr': u'Robot : Ajouté %s',
'hu': u'Robot:"%s" hozzáadása',
'it': u'Bot: Aggiungo %s',
'ja': u'ロボットによる: 追加 %s',
'ko': u'로봇 : %s 추가',
'ta': u'Bot: Adding %s',
'ur': u'روبالہ: اضافہ %s',
'zh': u'機器人: 正在新增 %s',
}
# This is the most important header, because it will be used a lot. That's the
# header that the bot will add if the image hasn't the license.
nothing_head = {
'ar': u"\n== صورة بدون ترخيص ==\n",
'de': u"\n== Bild ohne Lizenz ==\n",
'en': u"\n== Image without license ==\n",
'fa': u"\n== تصویر بدون اجازہ ==\n",
'ga': u"\n== Comhad gan ceadúnas ==\n",
'fr': u"\n== Fichier sans licence ==\n",
'hu': u"\n== Licenc nélküli kép ==\n",
'it': u"\n\n== File senza licenza ==\n",
'ur': u"\n== تصویر بدون اجازہ ==\n",
}
# That's the text that the bot will add if it doesn't find the license.
# Note: every __botnick__ will be repleaced with your bot's nickname (feel free not to use if you don't need it)
nothing_notification = {
'commons': u"\n{{subst:User:Filnik/untagged|File:%s}}\n\n''This message was '''added automatically by " + \
u"__botnick__''', if you need some help about it, please read the text above again and follow the links in it," + \
u"if you still need help ask at the [[File:Human-help-browser.svg|18px|link=Commons:Help desk|?]] '''[[Commons:Help desk|->]]" + \
u"[[Commons:Help desk]]''' in any language you like to use.'' --__botnick__ ~~~~~""",
'ar': u"{{subst:مصدر الصورة|File:%s}} --~~~~",
'en': u"{{subst:image source|File:%s}} --~~~~",
'fa': u"{{جا:اخطار نگاره|%s}}",
'ga': u"{{subst:Foinse na híomhá|File:%s}} --~~~~",
'hu': u"{{subst:adjforrást|Kép:%s}} \n Ezt az üzenetet ~~~ automatikusan helyezte el a vitalapodon, kérdéseddel fordulj a gazdájához, vagy a [[WP:KF|Kocsmafalhoz]]. --~~~~",
'it': u"{{subst:Progetto:Coordinamento/Immagini/Bot/Messaggi/Senza licenza|%s|__botnick__}} --~~~~",
'ja': u"\n{{subst:Image copyright|File:%s}}--~~~~",
'ko': u'\n{{subst:User:Kwjbot IV/untagged|%s}} --~~~~',
'ta': u'\n{{subst:Di-no license-notice|படிமம்:%s}} ~~~~ ',
'ur': u"{{subst:ماخذ تصویر|File:%s}}--~~~~",
'zh': u'\n{{subst:Uploadvionotice|File:%s}} ~~~~ ',
}
# This is a list of what bots used this script in your project.
# NOTE: YOUR Botnick is automatically added. It's not required to add it twice.
bot_list = {
'commons': [u'Siebot', u'CommonsDelinker', u'Filbot', u'John Bot',
u'Sz-iwbot', u'ABFbot'],
'de': [u'Xqbot'],
'en': [u'OrphanBot'],
'fa': [u'Amirobot'],
'ga': [u'AllieBot'],
'it': [u'Filbot', u'Nikbot', u'.snoopyBot.'],
'ja': [u'Alexbot'],
'ko': [u'Kwjbot IV'],
'ta': [u'TrengarasuBOT'],
'ur': [u'Shuaib-bot', u'Tahir-bot', u'SAMI.bot'],
'zh': [u'Alexbot'],
}
# The message that the bot will add the second time that find another license
# problem.
second_message_without_license = {
'hu': u'\nSzia! Úgy tűnik a [[:Kép:%s]] képpel is hasonló a probléma, mint az előbbivel. Kérlek olvasd el a [[WP:KÉPLIC|feltölthető képek]]ről szóló oldalunk, és segítségért fordulj a [[WP:KF-JO|Jogi kocsmafalhoz]]. Köszönöm --~~~~',
'it': u':{{subst:Progetto:Coordinamento/Immagini/Bot/Messaggi/Senza licenza2|%s|__botnick__}} --~~~~',
}
# You can add some settings to wikipedia. In this way, you can change them
# without touching the code. That's useful if you are running the bot on
# Toolserver.
page_with_settings = {
'commons': u'User:Filbot/Settings',
'it': u'Progetto:Coordinamento/Immagini/Bot/Settings#Settings',
'zh': u"User:Alexbot/cisettings#Settings",
}
# The bot can report some images (like the images that have the same name of an
# image on commons) This is the page where the bot will store them.
report_page = {
'commons': u'User:Filbot/Report',
'de': u'Benutzer:Xqbot/Report',
'en': u'User:Filnik/Report',
'fa': u'کاربر:Amirobot/گزارش تصویر',
'ga': u'User:AllieBot/ReportImages',
'hu': u'User:Bdamokos/Report',
'it': u'Progetto:Coordinamento/Immagini/Bot/Report',
'ja': u'User:Alexbot/report',
'ko': u'User:Kwjbot IV/Report',
'ta': u'User:Trengarasu/commonsimages',
'ur': u'صارف:محمد شعیب/درخواست تصویر',
'zh': u'User:Alexsh/checkimagereport',
}
# Adding the date after the signature.
timeselected = u' ~~~~~'
# The text added in the report
report_text = {
'commons': u"\n*[[:File:%s]] " + timeselected,
'ar': u"\n*[[:ملف:%s]] " + timeselected,
'de': u"\n*[[:Datei:%s]] " + timeselected,
'en': u"\n*[[:File:%s]] " + timeselected,
'fa': u"n*[[:پرونده:%s]] " + timeselected,
'ga': u"\n*[[:File:%s]] " + timeselected,
'hu': u"\n*[[:Kép:%s]] " + timeselected,
'it': u"\n*[[:File:%s]] " + timeselected,
'ja': u"\n*[[:File:%s]] " + timeselected,
'ko': u"\n*[[:그림:%s]] " + timeselected,
'ta': u"\n*[[:படிமம்:%s]] " + timeselected,
'ur': u"\n*[[:تصویر:%s]] " + timeselected,
'zh': u"\n*[[:File:%s]] " + timeselected,
}
# The summary of the report
msg_comm10 = {
'commons': u'Bot: Updating the log',
'ar': u'بوت: تحديث السجل',
'de': u'Bot: schreibe Log',
'en': u'Bot: Updating the log',
'fa': u'ربات: بهروزرسانی سیاهه',
'fr': u'Robot: Mise à jour du journal',
'ga': u'Róbó: Log a thabhairt suas chun dáta',
'hu': u'Robot: A napló frissítése',
'it': u'Bot: Aggiorno il log',
'ja': u'ロボットによる:更新',
'ko': u'로봇:로그 업데이트',
'ta': u'தானியங்கி:பட்டியலை இற்றைப்படுத்தல்',
'ur': u'روبالہ: تجدید نوشتہ',
'zh': u'機器人:更新記錄',
}
# If a template isn't a license but it's included on a lot of images, that can
# be skipped to analyze the image without taking care of it. (the template must
# be in a list)
# Warning: Don't add template like "en, de, it" because they are already in
# (added in the code, below
# Warning 2: The bot will use regex, make the names compatible, please (don't
# add "Template:" or {{because they are already put in the regex).
# Warning 3: the part that use this regex is case-insensitive (just to let you
# know..)
HiddenTemplate = {
'commons': [u'Template:Information'], # Put the other in the page on the project defined below
'ar': [u'Template:معلومات'],
'de': [u'Template:Information'],
'en': [u'Template:Information'],
'fa': [u'الگو:اطلاعات'],
'fr': [u'Template:Information'],
'ga': [u'Template:Information'],
'hu': [u'Template:Információ', u'Template:Enwiki', u'Template:Azonnali'],
'it': [u'Template:EDP', u'Template:Informazioni file',
u'Template:Information', u'Template:Trademark',
u'Template:Permissionotrs'], # Put the other in the page on the project defined below
'ja': [u'Template:Information'],
'ko': [u'Template:그림 정보'],
'ta': [u'Template:Information'],
'ur': [u'Template:معلومات'],
'zh': [u'Template:Information'],
}
# A page where there's a list of template to skip.
PageWithHiddenTemplates = {
'commons': u'User:Filbot/White_templates#White_templates',
'it': u'Progetto:Coordinamento/Immagini/Bot/WhiteTemplates',
'ko': u'User:Kwjbot_IV/whitetemplates/list',
}
# A page where there's a list of template to consider as licenses.
PageWithAllowedTemplates = {
'commons': u'User:Filbot/Allowed templates',
'de': u'Benutzer:Xqbot/Lizenzvorlagen',
'it': u'Progetto:Coordinamento/Immagini/Bot/AllowedTemplates',
'ko': u'User:Kwjbot_IV/AllowedTemplates',
}
# Template added when the bot finds only an hidden template and nothing else.
# Note: every __botnick__ will be repleaced with your bot's nickname
# (feel free not to use if you don't need it)
HiddenTemplateNotification = {
'commons': u"""\n{{subst:User:Filnik/whitetemplate|File:%s}}\n\n''This message was added automatically by __botnick__, if you need some help about it please read the text above again and follow the links in it, if you still need help ask at the [[File:Human-help-browser.svg|18px|link=Commons:Help desk|?]] '''[[Commons:Help desk|→]] [[Commons:Help desk]]''' in any language you like to use.'' --__botnick__ ~~~~~""",
'it': u"{{subst:Progetto:Coordinamento/Immagini/Bot/Messaggi/Template_insufficiente|%s|__botnick__}} --~~~~",
'ko': u"\n{{subst:User:Kwj2772/whitetemplates|%s}} --~~~~",
}
# In this part there are the parameters for the dupe images.
# Put here the template that you want to put in the image to warn that it's a
# dupe. put __image__ if you want only one image, __images__ if you want the
# whole list
duplicatesText = {
'commons': u'\n{{Dupe|__image__}}',
'de': u'{{NowCommons}}',
'it': u'\n{{Progetto:Coordinamento/Immagini/Bot/Template duplicati|__images__}}',
}
# Head of the message given to the author
duplicate_user_talk_head = {
'it': u'\n\n== File doppio ==\n',
}
# Message to put in the talk
duplicates_user_talk_text = {
'commons': u'{{subst:User:Filnik/duplicates|File:%s|File:%s}}', # FIXME: it doesn't exist
'it': u"{{subst:Progetto:Coordinamento/Immagini/Bot/Messaggi/Duplicati|%s|%s|__botnick__}} --~~~~",
}
# Comment used by the bot while it reports the problem in the uploader's talk
duplicates_comment_talk = {
'commons': u'Bot: Dupe file found',
'ar': u'بوت: ملف مكرر تم العثور عليه',
'fa': u'ربات: تصویر تکراری یافت شد',
'it': u"Bot: Notifico il file doppio trovato",
}
# Comment used by the bot while it reports the problem in the image
duplicates_comment_image = {
'commons': u'Bot: Tagging dupe file',
'de': u'Bot: Datei liegt auf Commons',
'ar': u'بوت: وسم ملف مكرر',
'fa': u'ربات: برچسب زدن بر تصویر تکراری',
'it': u'Bot: File doppio, da cancellare',
}
# Regex to detect the template put in the image's decription to find the dupe
duplicatesRegex = {
'commons': r'\{\{(?:[Tt]emplate:|)(?:[Dd]up(?:licat|)e|[Bb]ad[ _][Nn]ame)[|}]',
'de': r'\{\{[nN](?:C|ow(?: c|[cC])ommons)[\|\}',
'it': r'\{\{(?:[Tt]emplate:|)[Pp]rogetto:[Cc]oordinamento/Immagini/Bot/Template duplicati[|}]',
}
# Category with the licenses and / or with subcategories with the other
# licenses.
category_with_licenses = {
'commons': 'Category:License tags',
'ar': 'تصنيف:قوالب حقوق الصور',
'de': 'Kategorie:Vorlage:Lizenz für Bilder',
'en': 'Category:Wikipedia image copyright templates',
'fa': u'رده:الگوهای حق تکثیر پرونده',
'ga': 'Catagóir:Clibeanna cóipchirt d\'íomhánna',
'it': 'Categoria:Template Licenze copyright',
'ja': 'Category:画像の著作権表示テンプレート',
'ko': '분류:위키백과 그림 저작권 틀',
'ta': 'Category:காப்புரிமை வார்ப்புருக்கள்',
'ur': u'زمرہ:ویکیپیڈیا سانچہ جات حقوق تصاویر',
'zh': 'Category:版權申告模板',
}
# Page where is stored the message to send as email to the users
emailPageWithText = {
#'de': 'Benutzer:ABF/D3',
}
# Title of the email
emailSubject = {
#'de': 'Problemen mit Deinem Bild auf der Deutschen Wikipedia',
}
# Seems that uploaderBots aren't interested to get messages regarding the
# files that they upload.. strange, uh?
# Format: [[user,regex], [user,regex]...] the regex is needed to match the user
# where to send the warning-msg
uploadBots = {
'commons': [['File Upload Bot (Magnus Manske)',
r'\|[Ss]ource=Transferred from .*?; transferred to Commons by \[\[User:(.*?)\]\]']],
}
# Service images that don't have to be deleted and/or reported has a template
# inside them (you can let this param as None)
serviceTemplates = {
'it': ['Template:Immagine di servizio'],
}
# Add your project (in alphabetical order) if you want that the bot starts
project_inserted = ['ar', 'commons', 'de', 'en', 'fa', 'ga', 'hu', 'it', 'ja',
'ko', 'ta', 'ur', 'zh']
################################################################################
# <--------------------------- Change only above! ---------------------------> #
################################################################################
class LogIsFull(pywikibot.Error):
"""An exception indicating that the log is full and the Bot cannot add
other data to prevent Errors.
"""
class NothingFound(pywikibot.Error):
""" An exception indicating that a regex has return [] instead of results.
"""
def printWithTimeZone(message):
""" Function to print the messages followed by the TimeZone encoded
correctly.
"""
if message[-1] != ' ':
message = '%s ' % unicode(message)
if locale.getlocale()[1]:
time_zone = unicode(time.strftime(u"%d %b %Y %H:%M:%S (UTC)",
time.gmtime()),
locale.getlocale()[1])
else:
time_zone = unicode(time.strftime(u"%d %b %Y %H:%M:%S (UTC)",
time.gmtime()))
pywikibot.output(u"%s%s" % (message, time_zone))
class checkImagesBot(object):
def __init__(self, site, logFulNumber=25000, sendemailActive=False,
duplicatesReport=False, logFullError=True):
""" Constructor, define some global variable """
self.site = site
self.logFullError = logFullError
self.logFulNumber = logFulNumber
self.rep_page = pywikibot.translate(self.site, report_page,
fallback=False)
self.rep_text = pywikibot.translate(self.site, report_text,
fallback=False)
self.com = pywikibot.translate(self.site, msg_comm10)
hiddentemplatesRaw = pywikibot.translate(self.site, HiddenTemplate,
fallback=False)
self.hiddentemplates = set([pywikibot.Page(self.site, tmp)
for tmp in hiddentemplatesRaw])
self.pageHidden = pywikibot.translate(self.site,
PageWithHiddenTemplates,
fallback=False)
self.pageAllowed = pywikibot.translate(self.site,
PageWithAllowedTemplates,
fallback=False)
self.comment = pywikibot.translate(self.site, msg_comm)
# Adding the bot's nickname at the notification text if needed.
botolist = pywikibot.translate(self.site, bot_list, fallback=False)
project = pywikibot.getSite().family.name
self.project = project
bot = config.usernames[project]
try:
botnick = bot[self.site.lang]
except KeyError:
raise pywikibot.NoUsername(
u"You have to specify an username for your bot in this project "
u"in the user-config.py file.")
self.botnick = botnick
botolist.append(botnick)
self.botolist = botolist
self.sendemailActive = sendemailActive
self.skip_list = []
self.duplicatesReport = duplicatesReport
self.image_namespace = u"File:"
# Load the licenses only once, so do it once
self.list_licenses = self.load_licenses()
def setParameters(self, imageName):
""" Function to set parameters, now only image but maybe it can be used
for others in "future"
"""
self.imageName = imageName
self.image = pywikibot.ImagePage(self.site, self.imageName)
self.timestamp = None
self.uploader = None
def report(self, newtext, image_to_report, notification=None, head=None,
notification2=None, unver=True, commTalk=None, commImage=None):
""" Function to make the reports easier. """
self.image_to_report = image_to_report
self.newtext = newtext
self.head = head or u''
self.notification = notification
self.notification2 = notification2
if self.notification:
self.notification = re.sub(r'__botnick__', self.botnick,
notification)
if self.notification2:
self.notification2 = re.sub(r'__botnick__', self.botnick,
notification2)
self.commTalk = commTalk
self.commImage = commImage or self.comment
while True:
try:
resPutMex = self.tag_image(unver)
except pywikibot.NoPage:
pywikibot.output(u"The page has been deleted! Skip!")
break
except pywikibot.EditConflict:
pywikibot.output(u"Edit conflict! Skip!")
break
else:
if not resPutMex:
break
if self.notification:
try:
self.put_mex_in_talk()
except pywikibot.EditConflict:
pywikibot.output(u"Edit Conflict! Retrying...")
try:
self.put_mex_in_talk()
except:
pywikibot.output(
u"Another error... skipping the user..")
break
else:
break
else:
break
def uploadBotChangeFunction(self, reportPageText, upBotArray):
"""Detect the user that has uploaded the file through the upload bot"""
regex = upBotArray[1]
results = re.findall(regex, reportPageText)
if results:
luser = results[0]
return luser
else:
# we can't find the user, report the problem to the bot
return upBotArray[0]
def tag_image(self, put=True):
""" Function to add the template in the image and to find out
who's the user that has uploaded the file.
"""
# Get the image's description
reportPageObject = pywikibot.ImagePage(self.site, self.image_to_report)
try:
reportPageText = reportPageObject.get()
except pywikibot.NoPage:
pywikibot.output(u'%s has been deleted...' % self.imageName)
return
# You can use this function also to find only the user that
# has upload the image (FixME: Rewrite a bit this part)
if put:
pywikibot.showDiff(reportPageText,
self.newtext + "\n" + reportPageText)
pywikibot.output(self.commImage)
try:
reportPageObject.put(self.newtext + "\n" + reportPageText,
comment=self.commImage)
except pywikibot.LockedPage:
pywikibot.output(u'File is locked. Skipping.')
return
# paginetta it's the image page object.
try:
if reportPageObject == self.image and self.uploader:
nick = self.uploader
else:
nick = reportPageObject.getLatestUploader()[0]
except pywikibot.NoPage:
pywikibot.output(
u"Seems that %s has only the description and not the file..."
% self.image_to_report)
repme = u"\n*[[:File:%s]] problems '''with the APIs'''"
self.report_image(self.image_to_report, self.rep_page, self.com,
repme)
return
upBots = pywikibot.translate(self.site, uploadBots, fallback=False)
luser = pywikibot.url2link(nick, self.site, self.site)
if upBots:
for upBot in upBots:
if upBot[0] == luser:
luser = self.uploadBotChangeFunction(reportPageText, upBot)
talk_page = pywikibot.Page(self.site,
u"%s:%s" % (self.site.namespace(3), luser))
self.talk_page = talk_page
self.luser = luser
return True
def put_mex_in_talk(self):
""" Function to put the warning in talk page of the uploader."""
commento2 = pywikibot.translate(self.site, msg_comm2)
emailPageName = pywikibot.translate(self.site, emailPageWithText,
fallback=False)
emailSubj = pywikibot.translate(self.site, emailSubject, fallback=False)
if self.notification2:
self.notification2 = self.notification2 % self.image_to_report
else:
self.notification2 = self.notification
second_text = False
# Getting the talk page's history, to check if there is another
# advise...
# The try block is used to prevent error if you use an old
# wikipedia.py's version.
try:
testoattuale = self.talk_page.get()
history = self.talk_page.getLatestEditors(limit=10)
latest_user = history[0]["user"]
pywikibot.output(
u'The latest user that has written something is: %s'
% latest_user)
for i in self.botolist:
if latest_user == i:
second_text = True
# A block to prevent the second message if the bot also
# welcomed users...
if history[0]['timestamp'] == history[-1]['timestamp']:
second_text = False
except pywikibot.IsRedirectPage:
pywikibot.output(
u'The user talk is a redirect, trying to get the right talk...')
try:
self.talk_page = self.talk_page.getRedirectTarget()
testoattuale = self.talk_page.get()
except pywikibot.NoPage:
second_text = False
testoattuale = pywikibot.translate(self.site, empty,
fallback=False)
except pywikibot.NoPage:
pywikibot.output(u'The user page is blank')
second_text = False
testoattuale = pywikibot.translate(self.site, empty, fallback=False)
if self.commTalk:
commentox = self.commTalk
else:
commentox = commento2
if second_text:
newText = u"%s\n\n%s" % (testoattuale, self.notification2)
else:
newText = testoattuale + self.head + self.notification
try:
self.talk_page.put(newText, comment=commentox, minorEdit=False)
except pywikibot.LockedPage:
pywikibot.output(u'Talk page blocked, skip.')
if emailPageName and emailSubj:
emailPage = pywikibot.Page(self.site, emailPageName)
try:
emailText = emailPage.get()
except (pywikibot.NoPage, pywikibot.IsRedirectPage):
return
if self.sendemailActive:
text_to_send = re.sub(r'__user-nickname__', r'%s'
% self.luser, emailText)
emailClass = userlib.User(self.site, self.luser)
try:
emailClass.sendMail(emailSubj, text_to_send)
except userlib.UserActionRefuse:
pywikibot.output("User is not mailable, aborted")
return
def untaggedGenerator(self, untaggedProject, limit):
""" Generator that yield the files without license. It's based on a
tool of the toolserver.
"""
lang = untaggedProject.split('.', 1)[0]
project = '.%s' % untaggedProject.split('.', 1)[1]
URL = u'http://toolserver.org/~daniel/WikiSense/UntaggedImages.php?'
if lang == 'commons':
link = URL + \
'wikifam=commons.wikimedia.org&since=-100d&until=&img_user_text=&order=img_timestamp&max=100&order=img_timestamp&format=html'
else:
link = URL + \
'wikilang=%s&wikifam=%s&order=img_timestamp&max=%s&ofs=0&max=%s' \
% (lang, project, limit, limit)
text = self.site.getUrl(link, no_hostname=True)
results = re.findall(r"<td valign='top' title='Name'><a href='http://.*?\.org/w/index\.php\?title=(.*?)'>.*?</a></td>",
text)
if results:
for result in results:
wikiPage = pywikibot.ImagePage(self.site, result)
yield wikiPage
else:
pywikibot.output(link)
raise NothingFound(
u'Nothing found! Try to use the tool by yourself to be sure '
u'that it works!')
def regexGenerator(self, regexp, textrun):
""" Generator used when an user use a regex parsing a page to yield the
results
"""
regex = re.compile(r'%s' % regexp, re.UNICODE | re.DOTALL)
results = regex.findall(textrun)
for image in results:
yield pywikibot.ImagePage(self.site, image)
def loadHiddenTemplates(self):
""" Function to load the white templates """
# A template as {{en is not a license! Adding also them in the
# whitelist template...
for langK in pywikibot.Family(u'wikipedia').langs.keys():
self.hiddentemplates.add(pywikibot.Page(self.site,
u'Template:%s' % langK))
# Hidden template loading
if self.pageHidden:
try:
pageHiddenText = pywikibot.Page(self.site,
self.pageHidden).get()
except (pywikibot.NoPage, pywikibot.IsRedirectPage):
pageHiddenText = ''
for element in self.load(pageHiddenText):
self.hiddentemplates.add(pywikibot.Page(self.site, element))
return self.hiddentemplates
def returnOlderTime(self, listGiven, timeListGiven):
""" Get some time and return the oldest of them """
usage = False
num = 0
num_older = None
max_usage = 0
for element in listGiven:
imageName = element[1]
imagePage = pywikibot.ImagePage(self.site, imageName)
imageUsage = [page for page in imagePage.usingPages()]
if len(imageUsage) > 0 and len(imageUsage) > max_usage:
max_usage = len(imageUsage)
num_older = num
num += 1
if num_older:
return listGiven[num_older][1]
for element in listGiven:
time = element[0]
imageName = element[1]
not_the_oldest = False
for time_selected in timeListGiven:
if time > time_selected:
not_the_oldest = True
break
if not not_the_oldest:
return imageName
def convert_to_url(self, page):
# Function stolen from wikipedia.py
"""The name of the page this Page refers to, in a form suitable for the
URL of the page.
"""
title = page.replace(u" ", u"_")
encodedTitle = title.encode(self.site.encoding())
return urllib.quote(encodedTitle)
def countEdits(self, pagename, userlist):
"""Function to count the edit of a user or a list of users in a page."""
# self.botolist
if type(userlist) == str:
userlist = [userlist]
page = pywikibot.Page(self.site, pagename)
history = page.getVersionHistory()
user_list = list()
for data in history:
user_list.append(data[2])
number_edits = 0
for username in userlist:
number_edits += user_list.count(username)
return number_edits
def checkImageOnCommons(self):
""" Checking if the file is on commons """
pywikibot.output(u'Checking if [[%s]] is on commons...'
% self.imageName)
commons_site = pywikibot.getSite('commons', 'commons')
regexOnCommons = r"\[\[:File:%s\]\] is also on '''Commons''': \[\[commons:File:.*?\]\](?: \(same name\)|)$" \
% re.escape(self.imageName)
hash_found = self.image.getHash()
if not hash_found:
return # Image deleted, no hash found. Skip the image.
commons_image_with_this_hash = commons_site.getFilesFromAnHash(hash_found)
if commons_image_with_this_hash and \
commons_image_with_this_hash is not 'None':
servTMP = pywikibot.translate(self.site, serviceTemplates,
fallback=False)
templatesInTheImage = self.image.getTemplates()
if servTMP is not None:
for template in servTMP:
if pywikibot.Page(self.site,
template) in templatesInTheImage:
pywikibot.output(
u"%s is on commons but it's a service image."
% self.imageName)
return True # continue with the check-part
pywikibot.output(u'%s is on commons!' % self.imageName)
on_commons_text = self.image.getImagePageHtml()
if u"<div class='sharedUploadNotice'>" in on_commons_text:
pywikibot.output(
u"But, the file doesn't exist on your project! Skip...")
# We have to skip the check part for that image because
# it's on commons but someone has added something on your
# project.
return
if re.findall(r'\bstemma\b', self.imageName.lower()) and \
self.site.lang == 'it':
pywikibot.output(
u'%s has "stemma" inside, means that it\'s ok.'
% self.imageName)
return True # It's not only on commons but the image needs a check
# the second usually is a url or something like that.
# Compare the two in equal way, both url.
if self.convert_to_url(self.imageName) \
== self.convert_to_url(commons_image_with_this_hash[0]):
repme = u"\n*[[:File:%s]] is also on '''Commons''': [[commons:File:%s]] (same name)" \
% (self.imageName, commons_image_with_this_hash[0])
else:
repme = u"\n*[[:File:%s]] is also on '''Commons''': [[commons:File:%s]]" \
% (self.imageName, commons_image_with_this_hash[0])
self.report_image(self.imageName, self.rep_page, self.com, repme,
addings=False, regex=regexOnCommons)
return True
def checkImageDuplicated(self, duplicates_rollback):
""" Function to check the duplicated files. """
dupText = pywikibot.translate(self.site, duplicatesText, fallback=False)
dupRegex = pywikibot.translate(self.site, duplicatesRegex,
fallback=False)
dupTalkHead = pywikibot.translate(self.site, duplicate_user_talk_head,
fallback=False)
dupTalkText = pywikibot.translate(self.site, duplicates_user_talk_text,
fallback=False)
dupComment_talk = pywikibot.translate(self.site,
duplicates_comment_talk,