-
Notifications
You must be signed in to change notification settings - Fork 0
/
casechecker.py
797 lines (673 loc) · 30.4 KB
/
casechecker.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Script to enumerate all pages on the wiki and find all titles
with mixed latin and cyrilic alphabets.
"""
#
# (C) Pywikipedia bot team, 2006-2012
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id$'
#
# Permutations code was taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465
#
def xuniqueCombinations(items, n):
if n==0: yield []
else:
for i in xrange(len(items)):
for cc in xuniqueCombinations(items[i+1:], n-1):
yield [items[i]] + cc
# End of permutation code
#
#
# Windows Concole colors
# This code makes this script Windows ONLY!!!
# Feel free to adapt it to another platform
#
# Adapted from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496901
#
STD_OUTPUT_HANDLE= -11
FOREGROUND_BLUE = 0x01 # text color contains blue.
FOREGROUND_GREEN= 0x02 # text color contains green.
FOREGROUND_RED = 0x04 # text color contains red.
FOREGROUND_INTENSITY = 0x08 # text color is intensified.
BACKGROUND_BLUE = 0x10 # background color contains blue.
BACKGROUND_GREEN= 0x20 # background color contains green.
BACKGROUND_RED = 0x40 # background color contains red.
BACKGROUND_INTENSITY = 0x80 # background color is intensified.
FOREGROUND_WHITE = FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED
try:
import ctypes
std_out_handle = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
except:
std_out_handle = None
def SetColor(color):
if std_out_handle:
try:
return ctypes.windll.kernel32.SetConsoleTextAttribute(
std_out_handle, color)
except:
pass
if color == FOREGROUND_BLUE: print '(b:',
if color == FOREGROUND_GREEN: print '(g:',
if color == FOREGROUND_RED: print '(r:',
# end of console code
import os
import sys, query, re, codecs
import wikipedia as pywikibot
class CaseChecker( object ):
msgRename = {
'ar': u'تغيير اسم لحالة مخلوطة',
'en': u'mixed case rename',
'ru': u'[[ВП:КЛ]]',
}
msgDeleteRedirect = {
'en': u'This redirect contains identical looking Cyrillic and Latin letters in its title',
'ru': u'[[ВП:КЛ]] Перенаправление содержит смесь кириллицы и латиницы в названии',
}
textDeleteRedirect = {
'en': u'{{db-r3|bot=CaseChecker}}\n\nThis redirect used to point to %s',
'ru': u'{{Db-redirtypo|[[ВП:КЛ]] Перенаправление на %s содержало смесь кириллицы и латиницы в названии}}',
}
msgLinkReplacement = {
'en': u'Case Replacements',
'ar': u'استبدالات الحالة',
'ru': u'[[ВП:КЛ]]',
}
# These words are always in one language, even though they could be typed
# in both
alwaysInLocal = [ u'СССР', u'Как', u'как' ]
alwaysInLatin = [ u'II', u'III' ]
localUpperLtr = u'ЁІЇЎАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯҐ'
localLowerLtr = u'ёіїўабвгдежзийклмнопрстуфхцчшщъыьэюяґ'
localLtr = localUpperLtr + localLowerLtr
localSuspects = u'АВЕКМНОРСТХІЁЇаеорсухіёї'
latinSuspects = u'ABEKMHOPCTXIËÏaeopcyxiëï'
# possibly try to fix one character mistypes in an alternative keyboard
# layout
localKeyboard = u'йцукенгшщзфывапролдячсмить'
latinKeyboard = u'qwertyuiopasdfghjklzxcvbnm'
romanNumChars = u'IVXLMC'
# all letters that may be used as suffixes after roman numbers: "Iый"
romannumSuffixes = localLowerLtr
romanNumSfxPtrn = re.compile(
u'^[' + romanNumChars + ']+[' + localLowerLtr + ']+$')
whitelists = {
'ru': u'ВП:КЛ/Проверенные',
}
latLtr = u'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
lclClrFnt = u'<font color=green>'
latClrFnt = u'<font color=brown>'
suffixClr = u'</font>'
wordBreaker = re.compile(u'[ _\-/\|#[\]():]')
stripChars = u' \t,'
titles = True
links = False
aplimit = None
apfrom = u''
title = None
replace = False
stopAfter = -1
wikilog = None
wikilogfile = 'wikilog.txt'
failedTitles = 'failedTitles.txt'
nosuggestions = 'nosuggestions.txt'
doFailed = False
titleList = None
autonomous = False
namespaces = []
filterredir = 'nonredirects'
def __init__(self):
for arg in pywikibot.handleArgs():
if arg.startswith('-from'):
if arg.startswith('-from:'):
self.apfrom = arg[6:]
else:
self.apfrom = pywikibot.input(u'Which page to start from: ')
elif arg.startswith('-reqsize:'):
self.aplimit = int(arg[9:])
elif arg == '-links':
self.links = True
elif arg == '-linksonly':
self.links = True
self.titles = False
elif arg == '-replace':
self.replace = True
elif arg == '-redir':
self.filterredir = 'all'
elif arg == '-redironly':
self.filterredir = 'redirects'
elif arg.startswith('-limit:'):
self.stopAfter = int(arg[7:])
elif arg == '-autonomous' or arg == '-a':
self.autonomous = True
elif arg.startswith('-ns:'):
self.namespaces.append( int(arg[4:]) )
elif arg.startswith('-wikilog:'):
self.wikilogfile = arg[9:]
elif arg.startswith('-failedlog:'):
self.failedTitles = arg[11:]
elif arg == '-failed':
self.doFailed = True
else:
pywikibot.output(u'Unknown argument %s.' % arg)
pywikibot.showHelp()
pywikibot.stopme()
sys.exit()
if self.namespaces == [] and not self.doFailed:
if self.apfrom == u'':
# 0 should be after templates ns
self.namespaces = [14, 10, 12, 0]
else:
self.namespaces = [0]
if self.aplimit is None:
self.aplimit = 200 if self.links else 'max'
if not self.doFailed:
self.queryParams = { 'action' : 'query',
'generator' : 'allpages',
'gaplimit' : self.aplimit,
'gapfilterredir': self.filterredir}
else:
self.queryParams = { 'action' : 'query' }
if self.apfrom != u'': pywikibot.output(u'Argument "-from" is ignored with "-failed"')
propParam = 'info'
if self.links:
propParam += '|links|categories'
self.queryParams['pllimit'] = 'max'
self.queryParams['cllimit'] = 'max'
self.queryParams['prop'] = propParam
self.site = pywikibot.getSite()
if len(self.localSuspects) != len(self.latinSuspects):
raise ValueError(u'Suspects must be the same size')
if len(self.localKeyboard) != len(self.latinKeyboard):
raise ValueError(u'Keyboard info must be the same size')
if not os.path.isabs(self.wikilogfile):
self.wikilogfile = pywikibot.config.datafilepath(self.wikilogfile)
self.wikilog = self.OpenLogFile(self.wikilogfile)
if not os.path.isabs(self.failedTitles):
self.failedTitles = pywikibot.config.datafilepath(self.failedTitles)
if self.doFailed:
with codecs.open(self.failedTitles, 'r', 'utf-8') as f:
self.titleList = [self.Page(t) for t in f]
self.failedTitles += '.failed'
self.lclToLatDict = dict([(ord(self.localSuspects[i]),
self.latinSuspects[i])
for i in xrange(len(self.localSuspects))])
self.latToLclDict = dict([(ord(self.latinSuspects[i]),
self.localSuspects[i])
for i in xrange(len(self.localSuspects))])
if self.localKeyboard is not None:
self.lclToLatKeybDict = dict(
[(ord(self.localKeyboard[i]),
self.latinKeyboard[i])
for i in xrange(len(self.localKeyboard))])
self.latToLclKeybDict = dict(
[(ord(self.latinKeyboard[i]),
self.localKeyboard[i])
for i in xrange(len(self.localKeyboard))])
else:
self.lclToLatKeybDict = {}
self.latToLclKeybDict = {}
badPtrnStr = u'([%s][%s]|[%s][%s])' \
% (self.latLtr, self.localLtr, self.localLtr, self.latLtr)
self.badWordPtrn = re.compile(u'[%s%s]*%s[%s%s]*'
% (self.latLtr, self.localLtr,
badPtrnStr, self.latLtr,
self.localLtr))
# Get whitelist
self.knownWords = set()
self.seenUnresolvedLinks = set()
# TODO: handle "continue"
if self.site.lang in self.whitelists:
wlpage = self.whitelists[self.site.lang]
pywikibot.output(u'Loading whitelist from %s' % wlpage)
wlparams = {
'action' : 'query',
'prop' : 'links',
'titles' : wlpage,
'redirects' : '',
'indexpageids' : '',
'pllimit' : 'max',
}
data = query.GetData(wlparams)
if len(data['query']['pageids']) == 1:
pageid = data['query']['pageids'][0]
links = data['query']['pages'][pageid]['links']
allWords = [nn for n in links for nn in self.FindBadWords(n['title'])]
self.knownWords = set(allWords)
# kw = set()
# for w in allWords:
# if len(self.ProcessTitle(w)[1]) > 0:
# kw.add(w)
# self.knownWords = kw
else:
raise ValueError(u'The number of pageids is not 1')
pywikibot.output(u'Loaded whitelist with %i items' % len(self.knownWords))
if pywikibot.verbose and len(self.knownWords) > 0:
pywikibot.output(u'Whitelist: %s' % u', '.join([self.MakeLink(i, False) for i in self.knownWords]))
else:
pywikibot.output(u'Whitelist is not known for language %s'
% self.site.lang)
def RunQuery(self, params):
while True:
# Get data
data = query.GetData(params)
# Process received data
yield data
# Clear any continuations first
if 'clcontinue' in params: del params['clcontinue']
if 'plcontinue' in params: del params['plcontinue']
if 'query-continue' not in data:
if 'gapcontinue' in params: del params['gapcontinue']
break
qc = data['query-continue']
# First continue properties only, once done, continue with allpages
if 'categories' in qc or 'links' in qc:
if 'categories' in qc: params.update(qc['categories'])
if 'links' in qc: params.update(qc['links'])
elif 'allpages' in qc:
params.update(qc['allpages'])
else:
raise ValueError(u'Unexpected query-continue values: %s' % qc)
continue
def Run(self):
try:
self.lastLetter = ''
if not self.doFailed:
for namespace in self.namespaces:
self.currentTitle = None
self.queryParams['gapnamespace'] = namespace
self.queryParams['gapfrom'] = self.apfrom
for data in self.RunQuery(self.queryParams):
self.ProcessDataBlock(data)
else:
self.currentTitle = None
batchSize = 10
for batchStart in xrange(0, len(self.titleList), batchSize):
self.queryParams['titles'] = self.titleList[batchStart:batchStart+batchSize]
for data in self.RunQuery(self.queryParams):
self.ProcessDataBlock(data)
print "*" * 29, "Done"
except:
pywikibot.output(u'Exception at Title = %s, Next = %s' % (self.currentTitle, self.apfrom))
try:
import traceback
pywikibot.output(traceback.format_exc())
except:
pywikibot.output(u'Unable to print exception info')
raise
def ProcessDataBlock(self, data):
if 'query' not in data or 'pages' not in data['query']:
return
firstItem = True
for pageID, page in data['query']['pages'].iteritems():
printed = False
title = page['title']
self.currentTitle = title
if 'missing' in page:
continue
if firstItem:
if self.lastLetter != title[0]:
pywikibot.ui.output('Processing %s\n' % title)
self.lastLetter = title[0]
firstItem = False
if self.titles:
err = self.ProcessTitle(title)
if err:
changed = False
if self.replace:
if len(err[1]) == 1:
newTitle = err[1][0]
# choice = pywikibot.inputChoice(u'Move %s to %s?' % (title, newTitle), ['Yes', 'No'], ['y', 'n'])
editSummary = pywikibot.translate(self.site, self.msgRename)
dst = self.Page(newTitle)
if 'redirect' in page:
src = self.Page(title)
redir = src.getRedirectTarget()
redirTitle = redir.title(asLink = True, textlink = True)
if not dst.exists():
src.move(newTitle, editSummary, movesubpages=True)
changed = True
replErrors = False
for p in src.getReferences(follow_redirects = False):
if p.namespace() == 2:
continue
oldText = p.get(get_redirect = True)
newText = self.ReplaceLink(oldText, title, newTitle)
if not self.PutNewPage(p, newText, [self.MakeMoveSummary(title, newTitle)]):
replErrors = True
if not replErrors:
editSummary = pywikibot.translate(self.site, self.msgDeleteRedirect)
newText = pywikibot.translate(self.site, self.textDeleteRedirect) % redirTitle
src.put(newText, editSummary, minorEdit=False)
changed = True
elif not dst.exists():
src = self.Page(title)
if page['ns'] == 14:
import category
dst = self.Page(newTitle)
bot = category.CategoryMoveRobot(
src.title(withNamespace=False),
dst.title(withNamespace=False),
self.autonomous,
editSummary + u' ' + self.MakeMoveSummary(title, newTitle),
True)
bot.run()
else:
src.move(newTitle, editSummary, movesubpages=True)
changed = True
if not changed:
if len(err[1]) > 0:
self.AppendLineToLog(self.failedTitles, title)
else:
self.AddNoSuggestionTitle(title)
self.WikiLog(u"* " + err[0])
printed = True
if self.links:
allLinks = None
if 'links' in page:
allLinks = page['links']
if 'categories' in page:
if allLinks:
allLinks = allLinks + page['categories']
else:
allLinks = page['categories']
if allLinks:
pageObj = None
pageTxt = None
msg = []
foundSuggestions = False
for l in allLinks:
ltxt = l['title']
err = self.ProcessTitle(ltxt)
if err:
if len(err[1]) > 0:
foundSuggestions = True
elif self.AddNoSuggestionTitle(ltxt):
continue
newTitle = None
if self.replace:
newTitle = self.PickTarget(title, ltxt, err[1])
if newTitle:
if pageObj is None:
pageObj = self.Page(title)
pageTxt = pageObj.get()
msg.append(self.MakeMoveSummary(ltxt, newTitle))
pageTxt = self.ReplaceLink(pageTxt, ltxt, newTitle)
if not newTitle:
if not printed:
self.WikiLog(u"* %s: link to %s" % (self.MakeLink(title, False), err[0]))
printed = True
else:
self.WikiLog(u"** link to %s" % err[0])
if pageObj is not None:
if self.PutNewPage(pageObj, pageTxt, msg):
# done, no need to log anything
foundSuggestions = False
if foundSuggestions:
self.AppendLineToLog(self.failedTitles, title)
if self.stopAfter > 0:
self.stopAfter -= 1
if self.stopAfter == 0:
raise ValueError(u'Stopping because we are done')
def WikiLog(self, text):
pywikibot.output(text)
self.wikilog.write(text + u'\n')
self.wikilog.flush()
def FindBadWords(self, title):
for m in self.badWordPtrn.finditer(title):
yield title[m.span()[0] : m.span()[1]]
def ProcessTitle(self, title):
badWords = list(self.FindBadWords(title))
if len(badWords) > 0:
# Allow known words, allow any roman numerals with local suffixes
badWords = set([i for i in badWords if i not in self.knownWords and self.romanNumSfxPtrn.match(i) is not None])
if len(badWords) == 0 or self.Page(title).isImage():
return None
count = 0
ambigBadWords = set()
ambigBadWordsCount = 0
mapLcl = {}
mapLat = {}
for badWord in badWords:
# See if it would make sense to treat the whole word as either
# cyrilic or latin
mightBeLat = mightBeLcl = True
for l in badWord:
if l in self.localLtr:
if mightBeLat and l not in self.localSuspects:
mightBeLat = False
else:
if mightBeLcl and l not in self.latinSuspects:
mightBeLcl = False
if l not in self.latLtr: raise ValueError(u'Assert failed')
# Some words are well known and frequently mixed-typed
if mightBeLcl and mightBeLat:
if badWord in self.alwaysInLocal:
mightBeLat = False
elif badWord in self.alwaysInLatin:
mightBeLoc = False
if mightBeLcl:
mapLcl[badWord] = badWord.translate(self.latToLclDict)
if mightBeLat:
mapLat[badWord] = badWord.translate(self.lclToLatDict)
if mightBeLcl and mightBeLat:
ambigBadWords.add(badWord)
# Cannot do len(ambigBadWords) because they might be duplicates
ambigBadWordsCount += 1
if not mightBeLcl and not mightBeLat:
# try to match one of the knownWords
bwLen = len(badWord)
kw = [w for w in self.knownWords if len(w) == bwLen]
for p in xrange(bwLen):
if len(kw) == 0:
break
c = badWord[p]
co = ord(c)
if co in self.latToLclDict:
c2 = self.latToLclDict[co]
elif co in self.lclToLatDict:
c2 = self.lclToLatDict[co]
else:
c2 = None
kw = [w for w in kw if p < len(w) and (w[p] == c or (c2 is not None and w[p] == c2))]
if len(kw) > 1:
pywikibot.output(u"Word '%s' could be treated as more than one known words" % badWord)
elif len(kw) == 1:
mapLcl[badWord] = kw[0]
count += 1
infoText = self.MakeLink(title)
possibleAlternatives = []
if len(mapLcl) + len(mapLat) - ambigBadWordsCount < count:
# We cannot auto-translate - offer a list of suggested words
suggestions = mapLcl.values() + mapLat.values()
if len(suggestions) > 0:
infoText += u", word suggestions: " + u', '.join(
[self.ColorCodeWord(t) for t in suggestions])
else:
infoText += u", no suggestions"
else:
# Replace all unambiguous bad words
for k,v in mapLat.items() + mapLcl.items():
if k not in ambigBadWords:
title = title.replace(k,v)
if len(ambigBadWords) == 0:
# There are no ambiguity, we can safelly convert
possibleAlternatives.append(title)
infoText += u", convert to " + self.MakeLink(title)
else:
# Try to pick 0, 1, 2, ..., len(ambiguous words) unique
# combinations from the bad words list, and convert just the
# picked words to cyrilic, whereas making all other words as
# latin character.
for itemCntToPick in xrange(0, len(ambigBadWords)+1):
title2 = title
for uc in xuniqueCombinations(list(ambigBadWords),
itemCntToPick):
wordsToLat = ambigBadWords.copy()
for bw in uc:
title2 = title2.replace(bw, mapLcl[bw])
wordsToLat.remove(bw)
for bw in wordsToLat:
title2 = title2.replace(bw, mapLat[bw])
possibleAlternatives.append(title2)
if len(possibleAlternatives) > 0:
infoText += u", can be converted to " + u', '.join(
[self.MakeLink(t) for t in possibleAlternatives])
else:
infoText += u", no suggestions"
return (infoText, possibleAlternatives)
def PickTarget(self, title, original, candidates):
if len(candidates) == 0:
return None
if len(candidates) == 1:
return candidates[0]
pagesDontExist = []
pagesRedir = {}
pagesExist = []
for newTitle in candidates:
dst = self.Page(newTitle)
if not dst.exists():
pagesDontExist.append(newTitle)
elif dst.isRedirectPage():
pagesRedir[newTitle] = dst.getRedirectTarget().title()
else:
pagesExist.append(newTitle)
if len(pagesExist) == 1:
return pagesExist[0]
elif len(pagesExist) == 0 and len(pagesRedir) > 0:
if len(pagesRedir) == 1:
return pagesRedir.keys()[0]
t = None
for k,v in pagesRedir.iteritems():
if not t:
t = v # first item
elif t != v:
break
else:
# all redirects point to the same target
# pick the first one, doesn't matter what it is
return pagesRedir.keys()[0]
if not self.autonomous:
pywikibot.output(u'Could not auto-decide for page %s. Which link should be chosen?' % self.MakeLink(title, False))
pywikibot.output(u'Original title: ', newline=False)
self.ColorCodeWord(original + "\n", True)
count = 1
for t in candidates:
if t in pagesDontExist: msg = u'missing'
elif t in pagesRedir: msg = u'Redirect to ' + pagesRedir[t]
else: msg = u'page exists'
self.ColorCodeWord(u' %d: %s (%s)\n'
% (count, t, msg), True)
count += 1
answers = [str(i) for i in xrange(0, count)]
choice = int(pywikibot.inputChoice(
u'Which link to choose? (0 to skip)',
answers, [a[0] for a in answers]))
if choice > 0:
return candidates[choice-1]
return None
def ColorCodeWord(self, word, toScreen = False):
if not toScreen: res = u"<b>"
lastIsCyr = word[0] in self.localLtr
if lastIsCyr:
if toScreen: SetColor(FOREGROUND_GREEN)
else: res += self.lclClrFnt
else:
if toScreen: SetColor(FOREGROUND_RED)
else: res += self.latClrFnt
for l in word:
if l in self.localLtr:
if not lastIsCyr:
if toScreen: SetColor(FOREGROUND_GREEN)
else: res += self.suffixClr + self.lclClrFnt
lastIsCyr = True
elif l in self.latLtr:
if lastIsCyr:
if toScreen: SetColor(FOREGROUND_RED)
else: res += self.suffixClr + self.latClrFnt
lastIsCyr = False
if toScreen: pywikibot.output(l, newline=False)
else: res += l
if toScreen: SetColor(FOREGROUND_WHITE)
else: return res + self.suffixClr + u"</b>"
def AddNoSuggestionTitle(self, title):
if title in self.seenUnresolvedLinks:
return True
self.seenUnresolvedLinks.add(title)
params = {
'action' : 'query',
'list' : 'backlinks',
'bltitle' : title,
'bllimit' : '50',
}
data = query.GetData(params)
cl = 0
redirs = 0
if 'backlinks' in data['query']:
bl = data['query']['backlinks']
cl = len(bl)
redirs = len([i for i in bl if 'redirect' in i])
if cl > 0 and 'query-continue' in data:
count = '50+'
else:
count = str(cl if cl > 0 else 'no backlinks')
self.AppendLineToLog(self.nosuggestions, u'* %s (%s%s)' %
(self.MakeLink(title), count, u', %d redirects' % redirs if redirs > 0 else u''))
return False
def PutNewPage(self, pageObj, pageTxt, msg):
title = pageObj.title(asLink = True, textlink = True)
coloredMsg = u', '.join([self.ColorCodeWord(m) for m in msg])
if pageObj.get(get_redirect = True) == pageTxt:
self.WikiLog(u"* Error: Text replacement failed in %s (%s)" % (self.MakeLink(title, False), coloredMsg))
else:
pywikibot.output(u'Case Replacements: %s' % u', '.join(msg))
try:
pageObj.put(
pageTxt,
u'%s: %s'
% (pywikibot.translate(
self.site,
self.msgLinkReplacement),
u', '.join(msg)))
return True
except KeyboardInterrupt:
raise
except:
self.WikiLog(u"* Error: Could not save updated page %s (%s)" % (self.MakeLink(title, False), coloredMsg))
return False
def MakeMoveSummary(self, fromTitle, toTitle):
return u'[[%s]]→[[%s]]' % (fromTitle, toTitle)
def MakeLink(self, title, colorcode=True):
prf = u'' if self.Page(title).namespace() == 0 else u':'
cc = u'|««« %s »»»' % self.ColorCodeWord(title) if colorcode else u''
return u"[[%s%s%s]]" % (prf, title, cc)
def OpenLogFile(self, filename):
try:
return codecs.open(filename, 'a', 'utf-8')
except IOError:
return codecs.open(filename, 'w', 'utf-8')
def AppendLineToLog(self, filename, text):
with self.OpenLogFile(filename) as f:
f.write(text + u'\n')
def Page(self, title):
return pywikibot.Page(self.site, title)
def ReplaceLink(self, text, oldtxt, newtxt):
frmParts = [str.strip(self.stripChars) for str in self.wordBreaker.split(oldtxt)]
toParts = [str.strip(self.stripChars) for str in self.wordBreaker.split(newtxt)]
if len(frmParts) != len(toParts):
raise ValueError(u'Splitting parts do not match counts')
for i in xrange(0, len(frmParts)):
if len(frmParts[i]) != len(toParts[i]):
raise ValueError(u'Splitting parts do not match word length')
if len(frmParts[i]) > 0:
text = text.replace(frmParts[i][0].lower() + frmParts[i][1:], toParts[i][0].lower() + toParts[i][1:])
text = text.replace(frmParts[i][0].upper() + frmParts[i][1:], toParts[i][0].upper() + toParts[i][1:])
return text
if __name__ == "__main__":
try:
bot = CaseChecker()
bot.Run()
finally:
pywikibot.stopme()