http://www.mediawiki.org/wiki/Special:Code/pywikipedia/10911
Revision: 10911
Author: xqt
Date: 2013-01-13 17:47:01 +0000 (Sun, 13 Jan 2013)
Log Message:
-----------
Some more PEP8 changes
Modified Paths:
--------------
trunk/pywikipedia/checkimages.py
Modified: trunk/pywikipedia/checkimages.py
===================================================================
--- trunk/pywikipedia/checkimages.py 2013-01-13 16:59:32 UTC (rev 10910)
+++ trunk/pywikipedia/checkimages.py 2013-01-13 17:47:01 UTC (rev 10911)
@@ -478,53 +478,52 @@
'zh': 'Category:版權申告模板',
}
-## Put None if you don't use this option or simply add nothing if en
-## is still None.
# Page where is stored the message to send as email to the users
emailPageWithText = {
- 'de':'Benutzer:ABF/D3',
+ 'de': 'Benutzer:ABF/D3',
}
# Title of the email
emailSubject = {
- 'de':'Problemen mit Deinem Bild auf der Deutschen Wikipedia',
+ '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:(.*?)\]\]']],
+ '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)
+# 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 start
+# 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', 'zh']
-# Ok, that's all. What is below, is the rest of code, now the code is fixed and it will run correctly in your project.
################################################################################
# <--------------------------- Change only above! ---------------------------> #
################################################################################
-# Error Classes
+
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.
"""
+
# Other common useful functions
def printWithTimeZone(message):
""" Function to print the messages followed by the TimeZone encoded
@@ -534,11 +533,15 @@
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])
+ 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()))
+ time_zone = unicode(time.strftime(u"%d %b %Y %H:%M:%S (UTC)",
+ time.gmtime()))
pywikibot.output(u"%s%s" % (message, time_zone))
+
class Global(object):
# default environment settings
# Command line configurable parameters
@@ -558,7 +561,7 @@
logFullError = True # Raise an error when the log is full
-class main:
+class checkImagesBot(object):
def __init__(self, site, logFulNumber=25000, sendemailActive=False,
duplicatesReport=False, logFullError=True):
""" Constructor, define some global variable """
@@ -580,8 +583,7 @@
self.pageAllowed = pywikibot.translate(self.site,
PageWithAllowedTemplates,
fallback=False)
- # Commento = Summary in italian
- self.commento = pywikibot.translate(self.site, msg_comm)
+ 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
@@ -591,7 +593,8 @@
botnick = bot[self.site.lang]
except KeyError:
raise pywikibot.NoUsername(
- u"You have to specify an username for your bot in this project in the user-config.py file.")
+ 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)
@@ -641,7 +644,7 @@
if commImage:
self.commImage = commImage
else:
- self.commImage = self.commento
+ self.commImage = self.comment
# Ok, done, let's loop.
while 1:
@@ -823,13 +826,16 @@
"""
lang = untaggedProject.split('.', 1)[0]
project = '.%s' % untaggedProject.split('.', 1)[1]
-
+
+ URL = u'http://toolserver.org/~daniel/WikiSense/UntaggedImages.php?'
if lang == 'commons':
- link = 'http://toolserver.org/~daniel/WikiSense/UntaggedImages.php?wikifam=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 = 'http://toolserver.org/~daniel/WikiSense/UntaggedImages.php?wikilang=%s&wiki…' % (lang, project, limit, limit)
+ 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)
+ 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:
@@ -838,7 +844,8 @@
else:
pywikibot.output(link)
raise NothingFound(
- u'Nothing found! Try to use the tool by yourself to be sure that it works!')
+ 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
@@ -938,7 +945,8 @@
""" 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)
+ 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 False # Image deleted, no hash found. Skip the image.
@@ -967,7 +975,9 @@
# Because it's on commons but someone has added something on your project.
return False
- elif re.findall(r'\bstemma\b', self.imageName.lower()) != [] and self.site.lang == 'it':
+ elif 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)
@@ -975,10 +985,15 @@
else:
# 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])
+ 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])
+ 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)
@@ -1001,9 +1016,11 @@
fallback=False)
dupComment_talk = pywikibot.translate(self.site, duplicates_comment_talk,
fallback=False)
- dupComment_image = pywikibot.translate(self.site, duplicates_comment_image,
+ dupComment_image = pywikibot.translate(self.site,
+ duplicates_comment_image,
fallback=False)
- duplicateRegex = r'\[\[:File:%s\]\] has the following duplicates' % re.escape(self.convert_to_url(self.imageName))
+ duplicateRegex = r'\[\[:File:%s\]\] has the following duplicates' \
+ % re.escape(self.convert_to_url(self.imageName))
imagePage = pywikibot.ImagePage(self.site, self.imageName)
hash_found = imagePage.getHash()
duplicates = self.site.getFilesFromAnHash(hash_found)
@@ -1013,18 +1030,21 @@
if len(duplicates) > 1:
if len(duplicates) == 2:
- pywikibot.output(u'%s has a duplicate! Reporting it...' % self.imageName)
+ pywikibot.output(u'%s has a duplicate! Reporting it...'
+ % self.imageName)
else:
- pywikibot.output(u'%s has %s duplicates! Reporting them...' % (self.imageName, len(duplicates) - 1))
+ pywikibot.output(u'%s has %s duplicates! Reporting them...'
+ % (self.imageName, len(duplicates) - 1))
if dupText and dupRegex:
- time_image_list = list()
- time_list = list()
+ time_image_list = []
+ time_list = []
for duplicate in duplicates:
DupePage = pywikibot.ImagePage(self.site, duplicate)
- if DupePage.urlname() != self.image.urlname() or self.timestamp == None:
+ if DupePage.urlname() != self.image.urlname() or \
+ self.timestamp is None:
self.timestamp = DupePage.getLatestUploader()[1]
data = time.strptime(self.timestamp, u"%Y-%m-%dT%H:%M:%SZ")
data_seconds = time.mktime(data)
@@ -1037,7 +1057,8 @@
images_to_tag_list = []
for duplicate in duplicates:
- if pywikibot.ImagePage(self.site, duplicate) == pywikibot.ImagePage(self.site, older_image):
+ if pywikibot.ImagePage(self.site, duplicate) \
+ == pywikibot.ImagePage(self.site, older_image):
continue # the older image, not report also this as duplicate
DupePage = pywikibot.ImagePage(self.site, duplicate)
try:
@@ -1046,24 +1067,35 @@
except pywikibot.NoPage:
continue # The page doesn't exists
- if not re.findall(dupRegex, DupPageText) and not re.findall(dupRegex, older_page_text):
- pywikibot.output(u'%s is a duplicate and has to be tagged...' % duplicate)
+ if not (re.findall(dupRegex, DupPageText) or
+ re.findall(dupRegex, older_page_text)):
+ pywikibot.output(
+ u'%s is a duplicate and has to be tagged...'
+ % duplicate)
images_to_tag_list.append(duplicate)
#if duplicate != duplicates[-1]:
- string += u"*[[:%s%s]]\n" % (self.image_namespace, duplicate)
+ string += u"*[[:%s%s]]\n" % (self.image_namespace,
+ duplicate)
#else:
# string += "*[[:%s%s]]" % (self.image_namespace, duplicate)
else:
- pywikibot.output(u"Already put the dupe-template in the files's page or in the dupe's page. Skip.")
+ pywikibot.output(
+ u"Already put the dupe-template in the files's page"
+ u" or in the dupe's page. Skip.")
return False # Ok - No problem. Let's continue the checking phase
older_image_ns = u'%s%s' % (self.image_namespace, older_image) # adding the namespace
only_report = False # true if the image are not to be tagged as dupes
# put only one image or the whole list according to the request
if u'__images__' in dupText:
- text_for_the_report = re.sub(r'__images__', r'\n%s*[[:%s]]\n' % (string, older_image_ns), dupText)
+ text_for_the_report = re.sub(r'__images__',
+ r'\n%s*[[:%s]]\n'
+ % (string, older_image_ns),
+ dupText)
else:
- text_for_the_report = re.sub(r'__image__', r'%s' % older_image_ns, dupText)
+ text_for_the_report = re.sub(r'__image__',
+ r'%s' % older_image_ns,
+ dupText)
# Two iteration: report the "problem" to the user only once (the last)
if len(images_to_tag_list) > 1:
@@ -1074,14 +1106,20 @@
only_report = True
break
# Delete the image in the list where we're write on
- text_for_the_report = re.sub(r'\n\*\[\[:%s\]\]' % re.escape(self.image_namespace + image_to_tag), '', text_for_the_report)
+ text_for_the_report = re.sub(
+ r'\n\*\[\[:%s\]\]'
+ % re.escape(self.image_namespace + image_to_tag),
+ '', text_for_the_report)
self.report(text_for_the_report, image_to_tag,
- commImage = dupComment_image, unver = True)
+ commImage=dupComment_image, unver=True)
if len(images_to_tag_list) != 0 and not only_report:
- already_reported_in_past = self.countEdits(u'File:%s' % images_to_tag_list[-1], self.botolist)
+ already_reported_in_past = self.countEdits(u'File:%s'
+ % images_to_tag_list[-1],
+ self.botolist)
image_to_resub = images_to_tag_list[-1]
- from_regex = r'\n\*\[\[:File:%s\]\]' % re.escape(self.convert_to_url(self.imageName))
+ from_regex = r'\n\*\[\[:File:%s\]\]' \
+ % re.escape(self.convert_to_url(self.imageName))
# Delete the image in the list where we're write on
text_for_the_report = re.sub(from_regex, '', text_for_the_report)
# if you want only one edit, the edit found should be more than 0 -> num - 1
@@ -1089,14 +1127,17 @@
only_report = True
else:
self.report(text_for_the_report, images_to_tag_list[-1],
- dupTalkText % (older_image_ns, string), dupTalkHead, commTalk = dupComment_talk,
- commImage = dupComment_image, unver = True)
+ dupTalkText % (older_image_ns, string),
+ dupTalkHead, commTalk = dupComment_talk,
+ commImage=dupComment_image, unver=True)
if self.duplicatesReport or only_report:
if only_report:
- repme = u"\n*[[:File:%s]] has the following duplicates ('''forced mode'''):" % self.convert_to_url(self.imageName)
+ repme = u"\n*[[:File:%s]] has the following duplicates ('''forced mode'''):" \
+ % self.convert_to_url(self.imageName)
else:
- repme = u"\n*[[:File:%s]] has the following duplicates:" % self.convert_to_url(self.imageName)
+ repme = u"\n*[[:File:%s]] has the following duplicates:" \
+ % self.convert_to_url(self.imageName)
for duplicate in duplicates:
if self.convert_to_url(duplicate) == self.convert_to_url(self.imageName):
@@ -1110,7 +1151,8 @@
return False # The image is a duplicate, it will be deleted. So skip the check-part, useless
return True # Ok - No problem. Let's continue the checking phase
- def report_image(self, image_to_report, rep_page = None, com = None, rep_text = None, addings = True, regex = None):
+ def report_image(self, image_to_report, rep_page=None, com=None,
+ rep_text=None, addings=True, regex=None):
""" Report the files to the report page when needed. """
if not rep_page:
rep_page = self.rep_page
@@ -1134,22 +1176,28 @@
if len(text_get) >= self.logFulNumber:
if self.logFullError:
- raise LogIsFull(u"The log page (%s) is full! Please delete the old files reported." % another_page.title())
+ raise LogIsFull(
+ u"The log page (%s) is full! Please delete the old files "
+ u"reported." % another_page.title())
else:
- pywikibot.output(u"The log page (%s) is full! Please delete the old files reported. Skip!" % another_page.title())
+ pywikibot.output(
+ u"The log page (%s) is full! Please delete the old files "
+ u" reported. Skip!" % another_page.title())
return True # Don't report, but continue with the check (we don't now if this is the first time we check this file or not)
# The talk page includes "_" between the two names, in this way i replace them to " "
n = re.compile(regex, re.UNICODE|re.DOTALL)
y = n.findall(text_get)
if y:
- pywikibot.output(u"%s is already in the report page." % image_to_report)
+ pywikibot.output(u"%s is already in the report page."
+ % image_to_report)
reported = False
else:
# Adding the log
if addings:
rep_text = rep_text % image_to_report # Adding the name of the image in the report if not done already
- another_page.put(text_get + rep_text, comment = com, force = True, minorEdit = False)
+ another_page.put(text_get + rep_text, comment=com, force=True,
+ minorEdit=False)
pywikibot.output(u"...Reported...")
reported = True
return reported
@@ -1166,14 +1214,16 @@
self.settingsData = list()
try:
testo = wikiPage.get()
- r = re.compile(r"<------- ------->\n"
+ r = re.compile(
+ r"<------- ------->\n"
"\*[Nn]ame ?= ?['\"](.*?)['\"]\n"
"\*([Ff]ind|[Ff]indonly)=(.*?)\n"
"\*[Ii]magechanges=(.*?)\n"
"\*[Ss]ummary=['\"](.*?)['\"]\n"
"\*[Hh]ead=['\"](.*?)['\"]\n"
"\*[Tt]ext ?= ?['\"](.*?)['\"]\n"
- "\*[Mm]ex ?= ?['\"]?([^\n]*?)['\"]?\n", re.UNICODE|re.DOTALL)
+ "\*[Mm]ex ?= ?['\"]?([^\n]*?)['\"]?\n",
+ re.UNICODE|re.DOTALL)
number = 1
for m in r.finditer(testo):
@@ -1190,14 +1240,17 @@
number += 1
if self.settingsData == list():
- pywikibot.output(u"You've set wrongly your settings, please take a look to the relative page. (run without them)")
+ pywikibot.output(
+ u"You've set wrongly your settings, please take a "
+ u"look to the relative page. (run without them)")
self.settingsData = None
except pywikibot.NoPage:
pywikibot.output(u"The settings' page doesn't exist!")
self.settingsData = None
except pywikibot.Error:
# Error? Settings = None
- pywikibot.output(u'Problems with loading the settigs, run without them.')
+ pywikibot.output(
+ u'Problems with loading the settigs, run without them.')
self.settingsData = None
self.some_problem = False
@@ -1206,10 +1259,9 @@
# Real-Time page loaded
if self.settingsData:
- pywikibot.output(u'\t >> Loaded the real-time page... <<')
- # No settings found, No problem, continue.
+ pywikibot.output(u'>> Loaded the real-time page... <<')
else:
- pywikibot.output(u'\t >> No additional settings found! <<')
+ pywikibot.output(u'>> No additional settings found! <<')
return self.settingsData # Useless, but it doesn't harm..
def load_licenses(self):
@@ -1232,17 +1284,18 @@
pywikibot.output(u'\n\t...Loading the licenses allowed...\n')
list_licenses = catlib.categoryAllPageObjectsAPI(catName)
if self.site.lang == 'commons':
- no_licenses_to_skip = catlib.categoryAllPageObjectsAPI('Category:License-related tags')
+ no_licenses_to_skip = catlib.categoryAllPageObjectsAPI(
+ 'Category:License-related tags')
for license_given in no_licenses_to_skip:
if license_given in list_licenses:
list_licenses.remove(license_given)
- pywikibot.output('') # blank line
+ pywikibot.output('')
- # Add the licenses set in the default page as licenses
- # to check
+ # Add the licenses set in the default page as licenses to check
if self.pageAllowed:
try:
- pageAllowedText = pywikibot.Page(self.site, self.pageAllowed).get()
+ pageAllowedText = pywikibot.Page(self.site,
+ self.pageAllowed).get()
except (pywikibot.NoPage, pywikibot.IsRedirectPage):
pageAllowedText = ''
@@ -1254,8 +1307,9 @@
def miniTemplateCheck(self, template):
"""
- Is the template given in the licenses allowed or in the licenses to skip?
- This function check this.
+ Check whether the given template given in the licenses allowed or in the
+ licenses to skip.
+
"""
if template in self.list_licenses: # the list_licenses are loaded in the __init__ (not to load them multimple times)
self.license_selected = template.title(withNamespace=False)
@@ -1275,9 +1329,11 @@
def templateInList(self):
"""
- The problem is the calls to the Mediawiki system because they can be pretty slow.
- While searching in a list of objects is really fast, so first of all let's see if
- we can find something in the info that we already have, then make a deeper check.
+ The problem is the calls to the Mediawiki system because they can be
+ pretty slow. While searching in a list of objects is really fast, so
+ first of all let's see if we can find something in the info that we
+ already have, then make a deeper check.
+
"""
for template in self.licenses_found:
result = self.miniTemplateCheck(template)
@@ -1296,37 +1352,49 @@
continue
def smartDetection(self):
- """ The bot instead of checking if there's a simple template in the
- image's description, checks also if that template is a license or
- something else. In this sense this type of check is smart.
- """
+ """The bot instead of checking if there's a simple template in the
+ image's description, checks also if that template is a license or
+ something else. In this sense this type of check is smart.
+
+ """
self.seems_ok = False
self.license_found = None
self.whiteTemplatesFound = False
- regex_find_licenses = re.compile(r'(?<!\{)\{\{(?:[Tt]emplate:|)([^{]+?)[|\n<}]', re.DOTALL)
+ regex_find_licenses = re.compile(
+ r'(?<!\{)\{\{(?:[Tt]emplate:|)([^{]+?)[|\n<}]', re.DOTALL)
# see below to understand the use of this regex
- regex_are_licenses = re.compile(r'(?<!\{)\{\{(?:[Tt]emplate:|)([^{]+?)\}\}', re.DOTALL)
+ regex_are_licenses = re.compile(
+ r'(?<!\{)\{\{(?:[Tt]emplate:|)([^{]+?)\}\}', re.DOTALL)
#dummy_edit = False
while 1:
self.hiddentemplates = self.loadHiddenTemplates()
self.licenses_found = self.image.getTemplates()
- templatesInTheImageRaw = regex_find_licenses.findall(self.imageCheckText)
+ templatesInTheImageRaw = regex_find_licenses.findall(
+ self.imageCheckText)
if not self.licenses_found and templatesInTheImageRaw:
# {{nameTemplate|something <- this is not a template, be sure that we haven't catch something like that.
licenses_TEST = regex_are_licenses.findall(self.imageCheckText)
if not self.licenses_found and licenses_TEST:
- raise pywikibot.Error("APIs seems down. No templates found with them but actually there are templates used in the image's page!")
+ raise pywikibot.Error(
+ "APIs seems down. No templates found with them but "
+ "actually there are templates used in the image's "
+ "page!")
self.allLicenses = list()
if not self.list_licenses:
- raise pywikibot.Error(u'No licenses allowed provided, add that option to the code to make the script working correctly')
+ raise pywikibot.Error(
+ u'No licenses allowed provided, add that option to the '
+ u'code to make the script working correctly')
# Found the templates ONLY in the image's description
for template_selected in templatesInTheImageRaw:
for templateReal in self.licenses_found:
- if self.convert_to_url(template_selected).lower().replace('template%3a', '') == \
- self.convert_to_url(templateReal.title()).lower().replace('template%3a', ''):
+ if self.convert_to_url(
+ template_selected).lower().replace('template%3a', '') \
+ == self.convert_to_url(
+ templateReal.title()).lower().replace('template%3a',
+ ''):
if templateReal not in self.allLicenses: # don't put the same template, twice.
self.allLicenses.append(templateReal)
# perform a dummy edit, sometimes there are problems with the Job queue
@@ -1369,9 +1437,11 @@
if self.some_problem:
if self.mex_used in self.imageCheckText:
- pywikibot.output(u'File already fixed. Skip.')
+ pywikibot.output(u'File already fixed. Skipping.')
else:
- pywikibot.output(u"The file's description for %s contains %s..." % (self.imageName, self.name_used))
+ pywikibot.output(
+ u"The file's description for %s contains %s..."
+ % (self.imageName, self.name_used))
if self.mex_used.lower() == 'default':
self.mex_used = self.unvertext
if self.imagestatus_used:
@@ -1379,22 +1449,32 @@
else:
reported = self.report_image(self.imageName)
if reported:
- #if self.imagestatus_used == True:
- self.report(self.mex_used, self.imageName, self.text_used, u"\n%s\n" % self.head_used, None, self.imagestatus_used, self.summary_used)
+ #if self.imagestatus_used:
+ self.report(self.mex_used, self.imageName, self.text_used,
+ u"\n%s\n" % self.head_used, None,
+ self.imagestatus_used, self.summary_used)
else:
pywikibot.output(u"Skipping the file...")
self.some_problem = False
else:
if not self.seems_ok and self.license_found:
- rep_text_license_fake = u"\n*[[:File:%s]] seems to have " % self.imageName + \
- "a ''fake license'', license detected: <nowiki>%s</nowiki>" % self.license_found
- regexFakeLicense = r"\* ?\[\[:File:%s\]\] seems to have " % (re.escape(self.imageName)) + \
- "a ''fake license'', license detected: <nowiki>%s</nowiki>$" % (re.escape(self.license_found))
- printWithTimeZone(u"%s seems to have a fake license: %s, reporting..." % (self.imageName, self.license_found))
- self.report_image(self.imageName, rep_text = rep_text_license_fake,
- addings = False, regex = regexFakeLicense)
+ rep_text_license_fake = u"\n*[[:File:%s]] seems to have " \
+ % self.imageName + \
+ "a ''fake license'', license detected: <nowiki>%s</nowiki>" \
+ % self.license_found
+ regexFakeLicense = r"\* ?\[\[:File:%s\]\] seems to have " \
+ % (re.escape(self.imageName)) + \
+ "a ''fake license'', license detected: <nowiki>%s</nowiki>$" \
+ % (re.escape(self.license_found))
+ printWithTimeZone(
+ u"%s seems to have a fake license: %s, reporting..."
+ % (self.imageName, self.license_found))
+ self.report_image(self.imageName,
+ rep_text=rep_text_license_fake,
+ addings=False, regex=regexFakeLicense)
elif self.license_found:
- printWithTimeZone(u"%s seems ok, license found: %s..." % (self.imageName, self.license_found))
+ printWithTimeZone(u"%s seems ok, license found: %s..."
+ % (self.imageName, self.license_found))
return (self.license_found, self.whiteTemplatesFound)
def load(self, raw):
@@ -1637,7 +1717,7 @@
#if p.exists(): <-- improve thebot, better to make as
# less call to the server as possible
# Here begins the check block.
- if brackets == True and license_found != None:
+ if brackets and not license_found is None:
# It works also without this... but i want only to be sure ^^
brackets = False
return True
@@ -1825,7 +1905,7 @@
return
# Reading the log of the new images if another generator is not given.
- if normal == True:
+ if normal:
if limit == 1:
pywikibot.output(u"Retrieving the latest file for checking...")
else:
@@ -1834,21 +1914,21 @@
# Main Loop
while True:
# Defing the Main Class.
- mainClass = main(site, sendemailActive=sendemailActive,
- duplicatesReport=duplicatesReport,
- logFullError=logFullError)
+ Bot = checkImagesBot(site, sendemailActive=sendemailActive,
+ duplicatesReport=duplicatesReport,
+ logFullError=logFullError)
# Untagged is True? Let's take that generator
- if untagged == True:
- generator = mainClass.untaggedGenerator(projectUntagged, limit)
+ if untagged:
+ generator = Bot.untaggedGenerator(projectUntagged, limit)
normal = False # Ensure that normal is False
# Normal True? Take the default generator
- if normal == True:
+ if normal:
generator = site.newimages(number = limit)
# if urlUsed and regexGen, get the source for the generator
- if urlUsed == True and regexGen == True:
- textRegex = site.getUrl(regexPageUrl, no_hostname = True)
+ if urlUsed and regexGen:
+ textRegex = site.getUrl(regexPageUrl, no_hostname=True)
# Not an url but a wiki page as "source" for the regex
- elif regexGen == True:
+ elif regexGen:
pageRegex = pywikibot.Page(site, regexPageName)
try:
textRegex = pageRegex.get()
@@ -1856,16 +1936,16 @@
pywikibot.output(u"%s doesn't exist!" % pageRegex.title())
textRegex = '' # No source, so the bot will quit later.
# If generator is the regex' one, use your own Generator using an url or page and a regex.
- if generator == 'regex' and regexGen == True:
- generator = mainClass.regexGenerator(regexpToUse, textRegex)
+ if generator == 'regex' and regexGen:
+ generator = Bot.regexGenerator(regexpToUse, textRegex)
# Ok, We (should) have a generator, so let's go on.
# Take the additional settings for the Project
- mainClass.takesettings()
+ Bot.takesettings()
# Not the main, but the most important loop.
#parsed = False
if wait:
# Let's sleep...
- generator = mainClass.wait(waitTime, generator, normal, limit)
+ generator = Bot.wait(waitTime, generator, normal, limit)
for image in generator:
# When you've a lot of image to skip before working use this workaround, otherwise
# let this commented, thanks. [ decoment also parsed = False if you want to use it
@@ -1876,7 +1956,7 @@
#else:
# parsed = True
# If the generator returns something that is not an image, simply skip it.
- if normal == False and regexGen == False:
+ if not (normal or regexGen):
if image_namespace.lower() not in image.title().lower() and \
image_old_namespace.lower() not in image.title().lower() \
and 'file:' not in image.title().lower():
@@ -1905,27 +1985,27 @@
pywikibot.output(u"%s is not a file, skipping..."
% image.title())
continue
- mainClass.setParameters(imageName, timestamp, uploader) # Setting the image for the main class
+ Bot.setParameters(imageName, timestamp, uploader) # Setting the image for the main class
# Skip block
- if skip == True:
- skip = mainClass.skipImages(skip_number, limit)
- if skip == True:
+ if skip:
+ skip = Bot.skipImages(skip_number, limit)
+ if skip:
continue
# Check on commons if there's already an image with the same name
- if commonsActive == True and site.family.name != "commons":
- response = mainClass.checkImageOnCommons()
- if response == False:
+ if commonsActive and site.family.name != "commons":
+ response = Bot.checkImageOnCommons()
+ if not response:
continue
# Check if there are duplicates of the image on the project selected
- if duplicatesActive == True:
- response2 = mainClass.checkImageDuplicated(duplicates_rollback)
- if response2 == False:
+ if duplicatesActive:
+ response2 = Bot.checkImageDuplicated(duplicates_rollback)
+ if not response2:
continue
- resultCheck = mainClass.checkStep()
+ resultCheck = Bot.checkStep()
if resultCheck:
continue
# A little block to perform the repeat or to break.
- if repeat == True:
+ if repeat:
printWithTimeZone(u"Waiting for %s seconds," % time_sleep)
time.sleep(time_sleep)
else:
http://www.mediawiki.org/wiki/Special:Code/pywikipedia/10903
Revision: 10903
Author: xqt
Date: 2013-01-13 15:15:02 +0000 (Sun, 13 Jan 2013)
Log Message:
-----------
L10N should never replaced by fallbacks;
some PEP8 changes
Modified Paths:
--------------
trunk/pywikipedia/checkimages.py
Modified: trunk/pywikipedia/checkimages.py
===================================================================
--- trunk/pywikipedia/checkimages.py 2013-01-13 15:01:53 UTC (rev 10902)
+++ trunk/pywikipedia/checkimages.py 2013-01-13 15:15:02 UTC (rev 10903)
@@ -70,7 +70,8 @@
image's problem.
---- Known issues/FIXMEs: ----
-* Clean the code, some passages are pretty difficult to understand if you're not the coder.
+* 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.
@@ -90,7 +91,8 @@
import re, time, urllib, urllib2, os, locale, sys, datetime
import wikipedia as pywikibot
-import config, pagegenerators, catlib, query, userlib
+import pagegenerators as pg
+import config, catlib, query, userlib
locale.setlocale(locale.LC_ALL, '')
@@ -104,19 +106,19 @@
# 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'{{DÜP}}',
- '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}}',
- 'zh' :u'{{subst:No license/auto}}',
+ 'commons': u'{{subst:nld}}',
+ 'ar': u'{{subst:لم}}',
+ 'de': u'{{DÜP}}',
+ '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}}',
+ 'zh': u'{{subst:No license/auto}}',
}
# Text that the bot will try to see if there's already or not. If there's a
@@ -126,217 +128,216 @@
# 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',],
- 'zh':[u'{{no source', u'{{unknown', u'{{No license',],
+ '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',],
+ 'zh': [u'{{no source', u'{{unknown', u'{{No license',],
}
# Summary for when the will add the no source
-comm = {
- 'ar' :u'بوت: التعليم على ملف مرفوع حديثا غير موسوم',
- 'commons':u'Bot: Marking newly uploaded untagged file',
- 'de' :u'Bot: Markierung als Bild ohne Lizenz',
- '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'தானியங்கி:காப்புரிமை வழங்கப்படா படிமத்தை சுட்டுதல்',
- 'zh' :u'機器人:標示新上傳且未包含必要資訊的檔案',
+msg_comm = {
+ 'ar': u'بوت: التعليم على ملف مرفوع حديثا غير موسوم',
+ 'commons': u'Bot: Marking newly uploaded untagged file',
+ 'de': u'Bot: Markierung als Bild ohne Lizenz',
+ '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'தானியங்கி:காப்புரிமை வழங்கப்படா படிமத்தை சுட்டுதல்',
+ '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',
- 'zh' :u'{{subst:welcome|sign=~~~~}}',
+ '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',
+ 'zh': u'{{subst:welcome|sign=~~~~}}',
}
# Summary that the bot use when it notify the problem with the image's license
-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'தானியங்கி:மூலம் வழங்கப்படா படிமத்தை சுட்டுதல்',
- 'zh' :u'機器人:告知用戶',
+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'தானியங்கி:மூலம் வழங்கப்படா படிமத்தை சுட்டுதல்',
+ '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 என்றக் கோப்பு நீட்சியைக் கொண்டுள்ளது.}}',
- 'zh' :u'{{delete|未知檔案格式%s}}',
+ '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 என்றக் கோப்பு நீட்சியைக் கொண்டுள்ளது.}}',
+ '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',
- 'zh' :u'\n==您上載的檔案格式可能有誤==\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',
+ '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]] இனங்காணப்படாத கோப்பு நீட்சியை கொண்டுள்ளது தயவு செய்து ஒரு முறை சரி பார்க்கவும் ~~~~',
+ '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]] இனங்காணப்படாத கோப்பு நீட்சியை கொண்டுள்ளது தயவு செய்து ஒரு முறை சரி பார்க்கவும் ~~~~',
'zh' :u'您好,你上傳的[[:File:%s]]無法被識別,請檢查您的檔案,謝謝。--~~~~',
}
# Summary of the delete immediately.
# (e.g: Adding {{db-meta|The file has .%s as extension.}})
-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',
- 'zh' :u'機器人: 正在新增 %s',
+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',
+ '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",
- 'commons':u"",# Nothing, the template has already the header inside.
- 'de' :u"\n== Bild ohne Lizenz ==\n",
- 'en' :u"\n== Image without license ==\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",
- 'ja' :u'',
- 'ko' :u'',
- 'fa' :u'',
- 'ta' :u'',
- 'zh' :u'',
+ 'ar': u"\n== صورة بدون ترخيص ==\n",
+ 'commons': u"",# Nothing, the template has already the header inside.
+ 'de': u"\n== Bild ohne Lizenz ==\n",
+ 'en': u"\n== Image without license ==\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",
+ 'ja': u'',
+ 'ko': u'',
+ 'fa': u'',
+ 'ta': u'',
+ 'zh': u'',
}
# 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 " + \
- "__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__ ~~~~~""",
- 'ar' :u"{{subst:مصدر الصورة|File:%s}} --~~~~",
- 'de' :u'\n{{subst:Benutzer:ABF/D2|%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}} ~~~~ ',
- 'zh' :u'\n{{subst:Uploadvionotice|File:%s}} ~~~~ ',
+ 'commons': u"\n{{subst:User:Filnik/untagged|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__ ~~~~~""",
+ 'ar': u"{{subst:مصدر الصورة|File:%s}} --~~~~",
+ 'de': u'\n{{subst:Benutzer:ABF/D2|%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}} ~~~~ ',
+ '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'],
- 'zh' :[u'Alexbot'],
+ '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'],
+ 'zh': [u'Alexbot'],
}
# The message that the bot will add the second time that find another license
# problem.
second_message_without_license = {
- '_default':None,
- '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__}} --~~~~',
+ '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 = {
- '_default':None,
- 'commons':u'User:Filbot/Settings',
- 'it':u'Progetto:Coordinamento/Immagini/Bot/Settings#Settings',
- 'zh':u"User:Alexbot/cisettings#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',
- 'zh' :u'User:Alexsh/checkimagereport',
+ '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',
+ 'zh': u'User:Alexsh/checkimagereport',
}
# Adding the date after the signature.
@@ -344,35 +345,35 @@
# The text added in the report
report_text = {
- 'commons':u"\n*[[:File:%s]] " + timeselected,
- 'ar':u"\n*[[:ملف:%s]] " + timeselected,
- 'de':u"\n*[[:Bild:%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,
- 'zh':u"\n*[[:File:%s]] " + timeselected,
+ '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,
+ 'zh': u"\n*[[:File:%s]] " + timeselected,
}
# The summary of the report
-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'தானியங்கி:பட்டியலை இற்றைப்படுத்தல்',
- 'zh' :u'機器人:更新記錄',
+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'தானியங்கி:பட்டியலை இற்றைப்படுத்தல்',
+ 'zh': u'機器人:更新記錄',
}
# If a template isn't a license but it's included on a lot of images, that can
@@ -385,44 +386,41 @@
# 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'],
- 'zh':[u'Template:Information'],
+ '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'],
+ 'zh': [u'Template:Information'],
}
# A page where there's a list of template to skip.
PageWithHiddenTemplates = {
- '_default':None,
'commons': u'User:Filbot/White_templates#White_templates',
- 'it':u'Progetto:Coordinamento/Immagini/Bot/WhiteTemplates',
+ '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 = {
- '_default':None,
'commons': u'User:Filbot/Allowed templates',
- 'it':u'Progetto:Coordinamento/Immagini/Bot/AllowedTemplates',
- 'ko':u'User:Kwjbot_IV/AllowedTemplates',
+ '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 = {
- '_default':None,
'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}} --~~~~",
+ '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.
@@ -430,45 +428,39 @@
# 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 = {
- '_default':None,
'commons': u'\n{{Dupe|__image__}}',
- 'it' : u'\n{{Progetto:Coordinamento/Immagini/Bot/Template duplicati|__images__}}',
+ 'it': u'\n{{Progetto:Coordinamento/Immagini/Bot/Template duplicati|__images__}}',
}
# Head of the message given to the author
duplicate_user_talk_head = {
- '_default':None,
- 'it' : u'\n\n== File doppio ==\n',
+ 'it': u'\n\n== File doppio ==\n',
}
# Message to put in the talk
duplicates_user_talk_text = {
- '_default':None,
'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__}} --~~~~",
+ '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 = {
- '_default':None,
'commons': u'Bot: Dupe file found',
- 'ar' : u'بوت: ملف مكرر تم العثور عليه',
- 'it' : u"Bot: Notifico il file doppio trovato",
+ 'ar': 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 = {
- '_default':None,
'commons': u'Bot: Tagging dupe file',
- 'ar' : u'بوت: وسم ملف مكرر',
- 'it' : u'Bot: File doppio, da cancellare',
+ 'ar': u'بوت: وسم ملف مكرر',
+ 'it': u'Bot: File doppio, da cancellare',
}
# Regex to detect the template put in the image's decription to find the dupe
duplicatesRegex = {
- '_default':None,
'commons': r'\{\{(?:[Tt]emplate:|)(?:[Dd]up(?:licat|)e|[Bb]ad[ _][Nn]ame)[|}]',
- 'it' : r'\{\{(?:[Tt]emplate:|)[Pp]rogetto:[Cc]oordinamento/Immagini/Bot/Template duplicati[|}]',
+ 'it': r'\{\{(?:[Tt]emplate:|)[Pp]rogetto:[Cc]oordinamento/Immagini/Bot/Template duplicati[|}]',
}
# Category with the licenses and / or with subcategories with the other licenses.
@@ -490,13 +482,11 @@
## is still None.
# Page where is stored the message to send as email to the users
emailPageWithText = {
- '_default':None,
'de':'Benutzer:ABF/D3',
}
# Title of the email
emailSubject = {
- '_default':None,
'de':'Problemen mit Deinem Bild auf der Deutschen Wikipedia',
}
@@ -504,7 +494,6 @@
# 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 = {
- '_default':None,
'commons':[['File Upload Bot (Magnus Manske)',
r'\|[Ss]ource=Transferred from .*?; transferred to Commons by \[\[User:(.*?)\]\]']],
}
@@ -512,13 +501,12 @@
# 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 = {
- '_default': None,
'it': ['Template:Immagine di servizio'],
}
# Add your project (in alphabetical order) if you want that the bot start
-project_inserted = [u'ar', u'commons', u'de', u'en', u'fa', u'ga', u'hu', u'it',
- u'ja', u'ko', u'ta', u'zh']
+project_inserted = ['ar', 'commons', 'de', 'en', 'fa', 'ga', 'hu', 'it', 'ja',
+ 'ko', 'ta', 'zh']
# Ok, that's all. What is below, is the rest of code, now the code is fixed and it will run correctly in your project.
################################################################################
@@ -571,26 +559,31 @@
class main:
- def __init__(self, site, logFulNumber = 25000, sendemailActive = False,
- duplicatesReport = False, logFullError = True):
+ def __init__(self, site, logFulNumber=25000, sendemailActive=False,
+ duplicatesRepor =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)
- self.rep_text = pywikibot.translate(self.site, report_text)
- self.com = pywikibot.translate(self.site, comm10)
- hiddentemplatesRaw = pywikibot.translate(self.site, HiddenTemplate)
+ 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 = [pywikibot.Page(self.site, tmp)
for tmp in hiddentemplatesRaw]
self.pageHidden = pywikibot.translate(self.site,
- PageWithHiddenTemplates)
+ PageWithHiddenTemplates,
+ fallback=False)
self.pageAllowed = pywikibot.translate(self.site,
- PageWithAllowedTemplates)
+ PageWithAllowedTemplates,
+ fallback=False)
# Commento = Summary in italian
self.commento = pywikibot.translate(self.site, comm)
# Adding the bot's nickname at the notification text if needed.
- botolist = pywikibot.translate(self.site, bot_list)
+ botolist = pywikibot.translate(self.site, bot_list, fallback=False)
project = pywikibot.getSite().family.name
self.project = project
bot = config.usernames[project]
@@ -627,7 +620,7 @@
self.uploader = uploader
def report(self, newtext, image_to_report, notification=None, head=None,
- notification2 = None, unver=True, commTalk=None, commImage=None):
+ notification2=None, unver=True, commTalk=None, commImage=None):
""" Function to make the reports easier. """
# Defining some useful variable for next...
self.image_to_report = image_to_report
@@ -736,23 +729,25 @@
self.report_image(self.image_to_report, self.rep_page, self.com,
repme)
return False
- upBots = pywikibot.translate(self.site, uploadBots)
+ 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))
+ 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, comm2)
- emailPageName = pywikibot.translate(self.site, emailPageWithText)
- emailSubj = pywikibot.translate(self.site, emailSubject)
+ 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:
@@ -784,11 +779,12 @@
testoattuale = self.talk_page.get()
except pywikibot.NoPage:
second_text = False
- testoattuale = pywikibot.translate(self.site, empty)
+ 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)
+ testoattuale = pywikibot.translate(self.site, empty, fallback=False)
if self.commTalk:
commentox = self.commTalk
else:
@@ -800,7 +796,7 @@
newText = testoattuale + self.head + self.notification
try:
- self.talk_page.put(newText, comment = commentox, minorEdit = False)
+ self.talk_page.put(newText, comment=commentox, minorEdit=False)
except pywikibot.LockedPage:
pywikibot.output(u'Talk page blocked, skip.')
@@ -948,34 +944,47 @@
return False # Image deleted, no hash found. Skip the image.
else:
commons_image_with_this_hash = commons_site.getFilesFromAnHash(hash_found)
- if commons_image_with_this_hash != [] and commons_image_with_this_hash != 'None':
- servTMP = pywikibot.translate(self.site, serviceTemplates)
+ if commons_image_with_this_hash != [] and \
+ commons_image_with_this_hash != 'None':
+ servTMP = pywikibot.translate(self.site, serviceTemplates,
+ fallback=False)
templatesInTheImage = self.image.getTemplates()
if servTMP != 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)
+ 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 # Problems? No, return True and 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...")
+ pywikibot.output(
+ u"But, the file doesn't exist on your project! Skip...")
# Problems? Yes! We have to skip the check part for that image
# Because it's on commons but someone has added something on your project.
return False
+
elif 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)
+ pywikibot.output(
+ u'%s has "stemma" inside, means that it\'s ok.'
+ % self.imageName)
return True # Problems? No, it's only not on commons but the image needs a check
+
else:
# 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 # Problems? No, return True
+ self.report_image(self.imageName,
+ self.rep_page, self.com, repme,
+ addings=False, regex=regexOnCommons)
+ return True
else:
- return True # Problems? No, return True
+ return True
def checkImageDuplicated(self, duplicates_rollback):
""" Function to check the duplicated files. """
@@ -983,12 +992,17 @@
# Skip the stub images
#if 'stub' in self.imageName.lower() and self.project == 'wikipedia' and self.site.lang == 'it':
# return True # Skip the stub, ok
- dupText = pywikibot.translate(self.site, duplicatesText)
- dupRegex = pywikibot.translate(self.site, duplicatesRegex)
- dupTalkHead = pywikibot.translate(self.site, duplicate_user_talk_head)
- dupTalkText = pywikibot.translate(self.site, duplicates_user_talk_text)
- dupComment_talk = pywikibot.translate(self.site, duplicates_comment_talk)
- dupComment_image = pywikibot.translate(self.site, duplicates_comment_image)
+ 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,
+ fallback=False)
+ dupComment_image = pywikibot.translate(self.site, duplicates_comment_image,
+ fallback=False)
duplicateRegex = r'\[\[:File:%s\]\] has the following duplicates' % re.escape(self.convert_to_url(self.imageName))
imagePage = pywikibot.ImagePage(self.site, self.imageName)
hash_found = imagePage.getHash()
@@ -1142,7 +1156,8 @@
def takesettings(self):
""" Function to take the settings from the wiki. """
- settingsPage = pywikibot.translate(self.site, page_with_settings)
+ settingsPage = pywikibot.translate(self.site, page_with_settings,
+ fallback=False)
try:
if not settingsPage:
self.settingsData = None
@@ -1210,7 +1225,8 @@
## gen = pagegenerators.CategorizedPageGenerator(cat)
## pages = [page for page in gen]
## list_licenses.extend(pages)
- catName = pywikibot.translate(self.site, category_with_licenses)
+ catName = pywikibot.translate(self.site, category_with_licenses,
+ fallback=False)
if not catName:
raise pywikibot.Error(u'No licenses allowed provided, add that option to the code to make the script working correctly')
pywikibot.output(u'\n\t...Loading the licenses allowed...\n')
@@ -1495,7 +1511,7 @@
def isTagged(self):
""" Understand if a file is already tagged or not. """
# Is the image already tagged? If yes, no need to double-check, skip
- for i in pywikibot.translate(self.site, txt_find):
+ for i in pywikibot.translate(self.site, txt_find, fallback=False):
# If there are {{ use regex, otherwise no (if there's not the {{ may not be a template
# and the regex will be wrong)
if '{{' in i:
@@ -1565,15 +1581,20 @@
delete = False
extension = self.imageName.split('.')[-1] # get the extension from the image's name
# Load the notification messages
- HiddenTN = pywikibot.translate(self.site, HiddenTemplateNotification)
- self.unvertext = pywikibot.translate(self.site, n_txt)
- di = pywikibot.translate(self.site, delete_immediately)
- dih = pywikibot.translate(self.site, delete_immediately_head)
- din = pywikibot.translate(self.site, delete_immediately_notification)
- nh = pywikibot.translate(self.site, nothing_head)
- nn = pywikibot.translate(self.site, nothing_notification)
- dels = pywikibot.translate(self.site, del_comm)
- smwl = pywikibot.translate(self.site, second_message_without_license)
+ HiddenTN = pywikibot.translate(self.site, HiddenTemplateNotification,
+ fallback=False)
+ self.unvertext = pywikibot.translate(self.site, n_txt, fallback=False)
+ di = pywikibot.translate(self.site, delete_immediately, fallback=False)
+ dih = pywikibot.translate(self.site, delete_immediately_head,
+ fallback=False)
+ din = pywikibot.translate(self.site, delete_immediately_notification,
+ fallback=False)
+ nh = pywikibot.translate(self.site, nothing_head, fallback=False)
+ nn = pywikibot.translate(self.site, nothing_notification,
+ fallback=False)
+ dels = pywikibot.translate(self.site, msg_del_comm)
+ smwl = pywikibot.translate(self.site, second_message_without_license,
+ fallback=False)
# Some formatting for delete immediately template
di = u'\n%s' % di
@@ -1649,6 +1670,7 @@
self.report(self.unvertext, self.imageName, notification, head, smwl)
return True
+
gbv = Global()
def checkbot():
@@ -1673,12 +1695,14 @@
for arg in pywikibot.handleArgs():
if arg.startswith('-limit'):
if len(arg) == 7:
- limit = int(pywikibot.input(u'How many files do you want to check?'))
+ limit = int(pywikibot.input(
+ u'How many files do you want to check?'))
else:
limit = int(arg[7:])
if arg.startswith('-time'):
if len(arg) == 5:
- time_sleep = int(pywikibot.input(u'How many seconds do you want runs to be apart?'))
+ time_sleep = int(pywikibot.input(
+ u'How many seconds do you want runs to be apart?'))
else:
time_sleep = int(arg[6:])
elif arg == '-break':
@@ -1700,35 +1724,42 @@
elif arg.startswith('-skip'):
if len(arg) == 5:
skip = True
- skip_number = int(pywikibot.input(u'How many files do you want to skip?'))
+ skip_number = int(pywikibot.input(
+ u'How many files do you want to skip?'))
elif len(arg) > 5:
skip = True
skip_number = int(arg[6:])
elif arg.startswith('-wait'):
if len(arg) == 5:
wait = True
- waitTime = int(pywikibot.input(u'How many time do you want to wait before checking the files?'))
+ waitTime = int(pywikibot.input(
+ u'How many time do you want to wait before checking the "
+ u'files?'))
elif len(arg) > 5:
wait = True
waitTime = int(arg[6:])
elif arg.startswith('-start'):
if len(arg) == 6:
- firstPageTitle = pywikibot.input(u'From witch page do you want to start?')
+ firstPageTitle = pywikibot.input(
+ u'From witch page do you want to start?')
elif len(arg) > 6:
firstPageTitle = arg[7:]
firstPageTitle = firstPageTitle.split(":")[1:]
- generator = pywikibot.getSite().allpages(start=firstPageTitle, namespace=6)
+ generator = pywikibot.getSite().allpages(start=firstPageTitle,
+ namespace=6)
repeat = False
elif arg.startswith('-page'):
if len(arg) == 5:
- regexPageName = str(pywikibot.input(u'Which page do you want to use for the regex?'))
+ regexPageName = str(pywikibot.input(
+ u'Which page do you want to use for the regex?'))
elif len(arg) > 5:
regexPageName = str(arg[6:])
repeat = False
regexGen = True
elif arg.startswith('-url'):
if len(arg) == 4:
- regexPageUrl = str(pywikibot.input(u'Which url do you want to use for the regex?'))
+ regexPageUrl = str(pywikibot.input(
+ u'Which url do you want to use for the regex?'))
elif len(arg) > 4:
regexPageUrl = str(arg[5:])
urlUsed = True
@@ -1736,7 +1767,8 @@
regexGen = True
elif arg.startswith('-regex'):
if len(arg) == 6:
- regexpToUse = str(pywikibot.input(u'Which regex do you want to use?'))
+ regexpToUse = str(pywikibot.input(
+ u'Which regex do you want to use?'))
elif len(arg) > 6:
regexpToUse = str(arg[7:])
generator = 'regex'
@@ -1746,20 +1778,24 @@
catName = str(pywikibot.input(u'In which category do I work?'))
elif len(arg) > 4:
catName = str(arg[5:])
- catSelected = catlib.Category(pywikibot.getSite(), 'Category:%s' % catName)
- generator = pagegenerators.CategorizedPageGenerator(catSelected)
+ catSelected = catlib.Category(pywikibot.getSite(),
+ 'Category:%s' % catName)
+ generator = pg.CategorizedPageGenerator(catSelected)
repeat = False
elif arg.startswith('-ref'):
if len(arg) == 4:
- refName = str(pywikibot.input(u'The references of what page should I parse?'))
+ refName = str(pywikibot.input(
+ u'The references of what page should I parse?'))
elif len(arg) > 4:
refName = str(arg[5:])
- generator = pagegenerators.ReferringPageGenerator(pywikibot.Page(pywikibot.getSite(), refName))
+ generator = pg.ReferringPageGenerator(
+ pywikibot.Page(pywikibot.getSite(), refName))
repeat = False
elif arg.startswith('-untagged'):
untagged = True
if len(arg) == 9:
- projectUntagged = str(pywikibot.input(u'In which project should I work?'))
+ projectUntagged = str(pywikibot.input(
+ u'In which project should I work?'))
elif len(arg) > 9:
projectUntagged = str(arg[10:])
@@ -1784,7 +1820,8 @@
# A little block-statement to ensure that the bot will not start with en-parameters
if site.lang not in project_inserted:
- pywikibot.output(u"Your project is not supported by this script. You have to edit the script and add it!")
+ pywikibot.output(u"Your project is not supported by this script.\n"
+ u"You have to edit the script and add it!")
return
# Reading the log of the new images if another generator is not given.
@@ -1792,12 +1829,14 @@
if limit == 1:
pywikibot.output(u"Retrieving the latest file for checking...")
else:
- pywikibot.output(u"Retrieving the latest %d files for checking..." % limit)
+ pywikibot.output(u"Retrieving the latest %d files for checking..."
+ % limit)
# Main Loop
- while 1:
+ while True:
# Defing the Main Class.
- mainClass = main(site, sendemailActive = sendemailActive,
- duplicatesReport = duplicatesReport, logFullError = logFullError)
+ mainClass = main(site, sendemailActive=sendemailActive,
+ duplicatesReport=duplicatesReport,
+ logFullError=logFullError)
# Untagged is True? Let's take that generator
if untagged == True:
generator = mainClass.untaggedGenerator(projectUntagged, limit)
@@ -1839,8 +1878,10 @@
# If the generator returns something that is not an image, simply skip it.
if normal == False and regexGen == False:
if image_namespace.lower() not in image.title().lower() and \
- image_old_namespace.lower() not in image.title().lower() and 'file:' not in image.title().lower():
- pywikibot.output(u'%s seems not an file, skip it...' % image.title())
+ image_old_namespace.lower() not in image.title().lower() \
+ and 'file:' not in image.title().lower():
+ pywikibot.output(u'%s seems not an file, skip it...'
+ % image.title())
continue
if normal:
imageData = image
@@ -1861,7 +1902,8 @@
try:
imageName = image.title().split(image_old_namespace)[1]
except IndexError:
- pywikibot.output(u"%s is not a file, skipping..." % image.title())
+ pywikibot.output(u"%s is not a file, skipping..."
+ % image.title())
continue
mainClass.setParameters(imageName, timestamp, uploader) # Setting the image for the main class
# Skip block
@@ -1893,11 +1935,14 @@
# Main loop will take all the (name of the) images and then i'll check them.
if __name__ == "__main__":
- old = datetime.datetime.strptime(str(datetime.datetime.utcnow()).split('.')[0], "%Y-%m-%d %H:%M:%S") #timezones are UTC
+ #timezones are UTC
+ old = datetime.datetime.strptime(
+ str(datetime.datetime.utcnow()).split('.')[0], "%Y-%m-%d %H:%M:%S")
try:
checkbot()
finally:
- final = datetime.datetime.strptime(str(datetime.datetime.utcnow()).split('.')[0], "%Y-%m-%d %H:%M:%S") #timezones are UTC
+ final = datetime.datetime.strptime(
+ str(datetime.datetime.utcnow()).split('.')[0], "%Y-%m-%d %H:%M:%S")
delta = final - old
secs_of_diff = delta.seconds
pywikibot.output("Execution time: %s" % secs_of_diff)