Revision: 8547
Author: xqt
Date: 2010-09-13 09:55:15 +0000 (Mon, 13 Sep 2010)
Log Message:
-----------
remove debug stuff
Modified Paths:
--------------
trunk/pywikipedia/commonscat.py
Modified: trunk/pywikipedia/commonscat.py
===================================================================
--- trunk/pywikipedia/commonscat.py 2010-09-13 09:44:40 UTC (rev 8546)
+++ trunk/pywikipedia/commonscat.py 2010-09-13 09:55:15 UTC (rev 8547)
@@ -201,22 +201,7 @@
else:
(status, always) = self.addCommonscat(page)
return
- #####
- text = self.load(page)
- if not text:
- return
- ################################################################
- # NOTE: Here you can modify the text in whatever way you want. #
- ################################################################
-
- # If you find out that you do not want to edit this page, just return.
- # Example: This puts the text 'Test' at the beginning of the page.
- text = 'Test ' + text
-
- if not self.save(text, page, self.summary):
- pywikibot.output(u'Page %s not saved.' % page.title(asLink=True))
-
def load(self, page):
"""
Loads the given page, does some changes, and saves it.
@@ -457,10 +442,6 @@
commonscatNote = template[1][2]
else:
commonscatTarget = wikipediaPage.titleWithoutNamespace()
- print commonscatTemplate
- print commonscatTarget
- print commonscatLinktext
- print commonscatNote
return (commonscatTemplate, commonscatTarget, commonscatLinktext,
commonscatNote)
Revision: 8546
Author: xqt
Date: 2010-09-13 09:44:40 +0000 (Mon, 13 Sep 2010)
Log Message:
-----------
define commonscatBot to a class; keep link titles as requested with bug #2787057; change page.aslink() to page.title(asLink=True)
Modified Paths:
--------------
trunk/pywikipedia/commonscat.py
Modified: trunk/pywikipedia/commonscat.py
===================================================================
--- trunk/pywikipedia/commonscat.py 2010-09-13 04:53:26 UTC (rev 8545)
+++ trunk/pywikipedia/commonscat.py 2010-09-13 09:44:40 UTC (rev 8546)
@@ -45,6 +45,7 @@
#
# (C) Multichill, 2008-2009
+# (C) Xqt, 2010
# (C) Pywikipedia bot team, 2008-2010
#
# Distributed under the terms of the MIT license.
@@ -166,214 +167,348 @@
'th': u'บอต: เปลี่ยนลิงก์หมวดหมู่คอมมอนส์จาก [[:Commons:Category:%(oldcat)s|%(oldcat)s]] เป็น [[:Commons:Category:%(newcat)s|%(newcat)s]]',
}
-def getCommonscatTemplate (lang = None):
- '''
- Get the template name in a language. Expects the language code.
- Return as tuple containing the primary template and it's alternatives
- '''
- if lang in commonscatTemplates:
- return commonscatTemplates[lang]
- else:
- return commonscatTemplates[u'_default']
+class CommonscatBot:
-def skipPage(page):
- '''
- Do we want to skip this page?
- '''
- if page.site().language() in ignoreTemplates:
- templatesInThePage = page.templates()
- templatesWithParams = page.templatesWithParams()
- for template in ignoreTemplates[page.site().language()]:
- if type(template) != tuple:
- if template in templatesInThePage:
- return True
- else:
- for (inPageTemplate, param) in templatesWithParams:
- if inPageTemplate == template[0] \
- and template[1] in param[0]:
- return True
- return False
+ def __init__(self, generator, always, summary=None):
+ self.generator = generator
+ self.always = always
+ self.dry = False
+ if summary == None:
+ self.summary = pywikibot.translate(pywikibot.getSite(), msg_change)
+ else:
+ self.summary = summary
-def updateInterwiki (wikipediaPage = None, commonsPage = None):
- '''
- Update the interwiki's at commons from a wikipedia page. The bot just
- replaces the interwiki links at the commons page with the interwiki's from
- the wikipedia page. This should probably be more intelligent. We could use
- add all the interwiki's and remove duplicates. Or only remove language links
- if multiple language links to the same language exist.
+ def run(self):
+ for page in self.generator:
+ self.treat(page)
- This function is disabled for the moment untill i figure out what the best
- way is to update the interwiki's.
- '''
- interwikis = {}
- comment= u''
- interwikilist = wikipediaPage.interwiki()
- interwikilist.append(wikipediaPage)
+ def treat(self, page):
+ """
+ Loads the given page, does some changes, and saves it.
+ """
+ if not page.exists():
+ pywikibot.output(u'Page %s does not exist. Skipping.'
+ % page.title(asLink=True))
+ elif page.isRedirectPage():
+ pywikibot.output(u'Page %s is a redirect. Skipping.'
+ % page.title(asLink=True))
+ elif page.isCategoryRedirect():
+ pywikibot.output(u'Page %s is a category redirect. Skipping.'
+ % page.title(asLink=True))
+ elif page.isDisambig():
+ pywikibot.output(u'Page %s is a disambiguation. Skipping.'
+ % page.title(asLink=True))
+ else:
+ (status, always) = self.addCommonscat(page)
+ return
+ #####
+ text = self.load(page)
+ if not text:
+ return
- for interwikiPage in interwikilist:
- interwikis[interwikiPage.site()]=interwikiPage
- oldtext = commonsPage.get()
- # The commonssite object doesnt work with interwiki's
- newtext = pywikibot.replaceLanguageLinks(oldtext, interwikis,
- pywikibot.getSite(u'nl'))
- comment = u'Updating interwiki\'s from [[' + \
- wikipediaPage.site().language() + \
- u':' + wikipediaPage.title() + u']]'
+ ################################################################
+ # NOTE: Here you can modify the text in whatever way you want. #
+ ################################################################
- if newtext != oldtext:
- #This doesnt seem to work. Newtext has some trailing whitespace
- pywikibot.showDiff(oldtext, newtext)
- commonsPage.put(newtext=newtext, comment=comment)
+ # If you find out that you do not want to edit this page, just return.
+ # Example: This puts the text 'Test' at the beginning of the page.
+ text = 'Test ' + text
-def addCommonscat (page = None, summary = None, always = False):
- '''
- Take a page. Go to all the interwiki page looking for a commonscat template.
- When all the interwiki's links are checked and a proper category is found
- add it to the page.
- '''
- pywikibot.output(u'Working on ' + page.title());
- #Get the right templates for this page
- primaryCommonscat, commonscatAlternatives = getCommonscatTemplate(
- page.site().language())
- commonscatLink = getCommonscatLink (page)
- if commonscatLink:
- pywikibot.output(u'Commonscat template is already on %s'
- % page.title())
- (currentCommonscatTemplate, currentCommonscatTarget) = commonscatLink
- checkedCommonscatTarget = checkCommonscatLink(currentCommonscatTarget)
- if (currentCommonscatTarget==checkedCommonscatTarget):
- #The current commonscat link is good
- pywikibot.output(u'Commonscat link at %s to Category:%s is ok'
- % (page.title() , currentCommonscatTarget));
- return (True, always)
- elif checkedCommonscatTarget!=u'':
- #We have a new Commonscat link, replace the old one
- changeCommonscat(page, currentCommonscatTemplate,
- currentCommonscatTarget, primaryCommonscat,
- checkedCommonscatTarget)
- return (True, always)
+ if not self.save(text, page, self.summary):
+ pywikibot.output(u'Page %s not saved.' % page.title(asLink=True))
+
+ def load(self, page):
+ """
+ Loads the given page, does some changes, and saves it.
+ """
+ try:
+ # Load the page
+ text = page.get()
+ except pywikibot.NoPage:
+ pywikibot.output(u"Page %s does not exist; skipping."
+ % page.title(asLink=True))
+ except pywikibot.IsRedirectPage:
+ pywikibot.output(u"Page %s is a redirect; skipping."
+ % page.title(asLink=True))
else:
- #Commonscat link is wrong
- commonscatLink = findCommonscatLink(page)
- if (commonscatLink!=u''):
- changeCommonscat (page, currentCommonscatTemplate,
- currentCommonscatTarget, primaryCommonscat,
- commonscatLink)
- #else
- #Should i remove the commonscat link?
+ return text
+ return None
- elif skipPage(page):
- pywikibot.output("Found a template in the skip list. Skipping %s"
- % page.title());
- else:
- commonscatLink = findCommonscatLink(page)
- if (commonscatLink!=u''):
- textToAdd = u'{{' + primaryCommonscat + u'|' + commonscatLink + u'}}'
- (success, status, always) = add_text.add_text(page, textToAdd,
- summary, None, None,
- always);
- return (True, always);
+ def save(self, text, page, comment, minorEdit=True, botflag=True):
+ # only save if something was changed
+ if text != page.get():
+ # Show the title of the page we're working on.
+ # Highlight the title in purple.
+ pywikibot.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
+ % page.title())
+ # show what was changed
+ pywikibot.showDiff(page.get(), text)
+ pywikibot.output(u'Comment: %s' %comment)
+ if not self.dry:
+ if not self.always:
+ choice = pywikibot.inputChoice(
+ u'Do you want to accept these changes?',
+ ['Yes', 'No', 'Always', 'Quit'],
+ ['y', 'N', 'a', 'q'], 'N')
+ if choice == 'a':
+ always = True
+ elif choice == 'q':
+ import sys
+ sys.exit()
+ if self.always or choice == 'y':
+ try:
+ # Save the page
+ page.put(text, comment=comment,
+ minorEdit=minorEdit, botflag=botflag)
+ except pywikibot.LockedPage:
+ pywikibot.output(u"Page %s is locked; skipping."
+ % page.title(asLink=True))
+ except pywikibot.EditConflict:
+ pywikibot.output(
+ u'Skipping %s because of edit conflict'
+ % (page.title()))
+ except pywikibot.SpamfilterError, error:
+ pywikibot.output(
+u'Cannot change %s because of spam blacklist entry %s'
+ % (page.title(), error.url))
+ else:
+ return True
+ return False
- return (True, always);
-def changeCommonscat (page=None, oldtemplate=u'', oldcat=u'', newtemplate=u'',
- newcat=u''):
- '''
- Change the current commonscat template and target.
- '''
- newtext = re.sub(u'(?i)\{\{' + oldtemplate + u'\|?[^}]*\}\}',
- u'{{' + newtemplate + u'|' + newcat + u'}}',
- page.get())
- comment = pywikibot.translate(page.site(), msg_change) % {'oldcat':oldcat, 'newcat':newcat}
- pywikibot.showDiff(page.get(), newtext)
- page.put(newtext, comment)
+ def getCommonscatTemplate (self, lang = None):
+ '''
+ Get the template name in a language. Expects the language code.
+ Return as tuple containing the primary template and it's alternatives
+ '''
+ if lang in commonscatTemplates:
+ return commonscatTemplates[lang]
+ else:
+ return commonscatTemplates[u'_default']
-def findCommonscatLink (page=None):
- for ipage in page.interwiki():
- try:
- if(ipage.exists() and not ipage.isRedirectPage()
- and not ipage.isDisambig()):
- commonscatLink = getCommonscatLink (ipage)
- if commonscatLink:
- (currentCommonscatTemplate, possibleCommonscat) = commonscatLink
- checkedCommonscat = checkCommonscatLink(possibleCommonscat)
- if (checkedCommonscat!= u''):
- pywikibot.output(
- u"Found link for %s at [[%s:%s]] to %s."
- % (page.title(), ipage.site().language(),
- ipage.title(), checkedCommonscat))
- return checkedCommonscat
- except pywikibot.BadTitle:
- #The interwiki was incorrect
- return u''
- return u''
+ def skipPage(self, page):
+ '''
+ Do we want to skip this page?
+ '''
+ if page.site().language() in ignoreTemplates:
+ templatesInThePage = page.templates()
+ templatesWithParams = page.templatesWithParams()
+ for template in ignoreTemplates[page.site().language()]:
+ if type(template) != tuple:
+ if template in templatesInThePage:
+ return True
+ else:
+ for (inPageTemplate, param) in templatesWithParams:
+ if inPageTemplate == template[0] \
+ and template[1] in param[0]:
+ return True
+ return False
+ def updateInterwiki (self, wikipediaPage = None, commonsPage = None):
+ '''
+ Update the interwiki's at commons from a wikipedia page. The bot just
+ replaces the interwiki links at the commons page with the interwiki's from
+ the wikipedia page. This should probably be more intelligent. We could use
+ add all the interwiki's and remove duplicates. Or only remove language links
+ if multiple language links to the same language exist.
-def getCommonscatLink (wikipediaPage=None):
- '''
- Go through the page and return a tuple of (<templatename>, <target>)
- '''
- primaryCommonscat, commonscatAlternatives = getCommonscatTemplate(
- wikipediaPage.site().language())
- commonscatTemplate =u''
- commonscatTarget = u''
- #See if commonscat is present
+ This function is disabled for the moment untill i figure out what the best
+ way is to update the interwiki's.
+ '''
+ interwikis = {}
+ comment= u''
+ interwikilist = wikipediaPage.interwiki()
+ interwikilist.append(wikipediaPage)
- for template in wikipediaPage.templatesWithParams():
- if template[0]==primaryCommonscat \
- or template[0] in commonscatAlternatives:
- commonscatTemplate = template[0]
- if (len(template[1]) > 0):
- commonscatTarget = template[1][0]
+ for interwikiPage in interwikilist:
+ interwikis[interwikiPage.site()]=interwikiPage
+ oldtext = commonsPage.get()
+ # The commonssite object doesnt work with interwiki's
+ newtext = pywikibot.replaceLanguageLinks(oldtext, interwikis,
+ pywikibot.getSite(u'nl'))
+ comment = u'Updating interwiki\'s from [[' + \
+ wikipediaPage.site().language() + \
+ u':' + wikipediaPage.title() + u']]'
+
+ if newtext != oldtext:
+ #This doesnt seem to work. Newtext has some trailing whitespace
+ pywikibot.showDiff(oldtext, newtext)
+ commonsPage.put(newtext=newtext, comment=comment)
+
+ def addCommonscat (self, page):
+ '''
+ Take a page. Go to all the interwiki page looking for a commonscat template.
+ When all the interwiki's links are checked and a proper category is found
+ add it to the page.
+ '''
+ always = self.always
+ pywikibot.output(u'Working on ' + page.title());
+ #Get the right templates for this page
+ primaryCommonscat, commonscatAlternatives = self.getCommonscatTemplate(
+ page.site().language())
+ commonscatLink = self.getCommonscatLink (page)
+ if commonscatLink:
+ pywikibot.output(u'Commonscat template is already on %s'
+ % page.title())
+ (currentCommonscatTemplate, currentCommonscatTarget, LinkText, Note) = commonscatLink
+ checkedCommonscatTarget = self.checkCommonscatLink(currentCommonscatTarget)
+ if (currentCommonscatTarget==checkedCommonscatTarget):
+ #The current commonscat link is good
+ pywikibot.output(u'Commonscat link at %s to Category:%s is ok'
+ % (page.title() , currentCommonscatTarget));
+ return (True, always)
+ elif checkedCommonscatTarget!=u'':
+ #We have a new Commonscat link, replace the old one
+ self.changeCommonscat(page, currentCommonscatTemplate,
+ currentCommonscatTarget, primaryCommonscat,
+ checkedCommonscatTarget, LinkText, Note)
+ return (True, always)
else:
- commonscatTarget = wikipediaPage.titleWithoutNamespace()
- return (commonscatTemplate, commonscatTarget)
+ #Commonscat link is wrong
+ commonscatLink = self.findCommonscatLink(page)
+ if (commonscatLink!=u''):
+ self.changeCommonscat (page, currentCommonscatTemplate,
+ currentCommonscatTarget, primaryCommonscat,
+ commonscatLink)
+ #else
+ #Should i remove the commonscat link?
- return None
+ elif self.skipPage(page):
+ pywikibot.output("Found a template in the skip list. Skipping %s"
+ % page.title());
+ else:
+ commonscatLink = self.findCommonscatLink(page)
+ if (commonscatLink!=u''):
+ textToAdd = u'{{' + primaryCommonscat + u'|' + commonscatLink + u'}}'
+ (success, status, always) = add_text.add_text(page, textToAdd,
+ self.summary, None, None,
+ self.always);
+ return (True, always);
-def checkCommonscatLink (name = ""):
- '''
- This function will retun the name of a valid commons category
- If the page is a redirect this function tries to follow it.
- If the page doesnt exists the function will return an empty string
- '''
- if pywikibot.verbose:
- pywikibot.output("getCommonscat: " + name )
- try:
- #This can throw a pywikibot.BadTitle
- commonsPage = pywikibot.Page(pywikibot.getSite("commons", "commons"),
- "Category:" + name)
+ return (True, always);
- if not commonsPage.exists():
- if pywikibot.verbose:
- pywikibot.output(u"getCommonscat: The category doesnt exist.")
- return u''
- elif commonsPage.isRedirectPage():
- if pywikibot.verbose:
- pywikibot.output(u"getCommonscat: The category is a redirect")
- return checkCommonscatLink(
- commonsPage.getRedirectTarget().titleWithoutNamespace())
- elif "Category redirect" in commonsPage.templates():
- if pywikibot.verbose:
- pywikibot.output(
- u"getCommonscat: The category is a category redirect")
- for template in commonsPage.templatesWithParams():
- if ((template[0]=="Category redirect")
- and (len(template[1]) > 0)):
- return checkCommonscatLink(template[1][0])
- elif commonsPage.isDisambig():
- if pywikibot.verbose:
- pywikibot.output(
- u"getCommonscat: The category is disambiguation")
- return u''
+ def changeCommonscat (self, page=None, oldtemplate=u'', oldcat=u'', newtemplate=u'',
+ newcat=u'', linktitle=u'', description=u''):
+ ''' Change the current commonscat template and target. '''
+ if not linktitle and (page.title().lower() in oldcat.lower() or
+ oldcat.lower() in page.title().lower()):
+ linktitle = oldcat
+ if linktitle and newcat <> page.titleWithoutNamespace():
+ newtext = re.sub(u'(?i)\{\{%s\|?[^{}]*(?:\{\{.*\}\})?\}\}'
+ % oldtemplate,
+ u'{{%s|%s|%s}}' % (newtemplate, newcat, linktitle),
+ page.get())
+ elif newcat == page.titleWithoutNamespace():
+ newtext = re.sub(u'(?i)\{\{%s\|?[^{}]*(?:\{\{.*\}\})?\}\}'
+ % oldtemplate,
+ u'{{%s}}' % newtemplate,
+ page.get())
else:
- return commonsPage.titleWithoutNamespace()
- except pywikibot.BadTitle:
- #Funky title so not correct
+ newtext = re.sub(u'(?i)\{\{%s\|?[^{}]*(?:\{\{.*\}\})?\}\}'
+ %oldtemplate,
+ u'{{%s|%s}}' % (newtemplate, newcat),
+ page.get())
+ comment = pywikibot.translate(page.site(), msg_change) \
+ % {'oldcat':oldcat, 'newcat':newcat}
+ self.save(newtext, page, comment)
+
+ def findCommonscatLink (self, page=None):
+ for ipage in page.interwiki():
+ try:
+ if(ipage.exists() and not ipage.isRedirectPage()
+ and not ipage.isDisambig()):
+ commonscatLink = self.getCommonscatLink (ipage)
+ if commonscatLink:
+ (currentTemplate, possibleCommonscat, linkText, Note) = commonscatLink
+ checkedCommonscat = self.checkCommonscatLink(possibleCommonscat)
+ if (checkedCommonscat!= u''):
+ pywikibot.output(
+ u"Found link for %s at [[%s:%s]] to %s."
+ % (page.title(), ipage.site().language(),
+ ipage.title(), checkedCommonscat))
+ return checkedCommonscat
+ except pywikibot.BadTitle:
+ #The interwiki was incorrect
+ return u''
return u''
- except pywikibot.PageNotFound:
- return u''
+
+ def getCommonscatLink (self, wikipediaPage=None):
+ '''
+ Go through the page and return a tuple of (<templatename>, <target>)
+ '''
+ primaryCommonscat, commonscatAlternatives = self.getCommonscatTemplate(
+ wikipediaPage.site().language())
+ commonscatTemplate = u''
+ commonscatTarget = u''
+ commonscatLinktext = u''
+ commonscatNote = u''
+ #See if commonscat is present
+
+ for template in wikipediaPage.templatesWithParams():
+ if template[0]==primaryCommonscat \
+ or template[0] in commonscatAlternatives:
+ commonscatTemplate = template[0]
+ if (len(template[1]) > 0):
+ commonscatTarget = template[1][0]
+ if len(template[1]) > 1:
+ commonscatLinktext = template[1][1]
+ if len(template[1]) > 2:
+ commonscatNote = template[1][2]
+ else:
+ commonscatTarget = wikipediaPage.titleWithoutNamespace()
+ print commonscatTemplate
+ print commonscatTarget
+ print commonscatLinktext
+ print commonscatNote
+ return (commonscatTemplate, commonscatTarget, commonscatLinktext,
+ commonscatNote)
+
+ return None
+
+ def checkCommonscatLink (self, name = ""):
+ '''
+ This function will retun the name of a valid commons category
+ If the page is a redirect this function tries to follow it.
+ If the page doesnt exists the function will return an empty string
+ '''
+ if pywikibot.verbose:
+ pywikibot.output("getCommonscat: " + name )
+ try:
+ #This can throw a pywikibot.BadTitle
+ commonsPage = pywikibot.Page(pywikibot.getSite("commons", "commons"),
+ "Category:" + name)
+
+ if not commonsPage.exists():
+ if pywikibot.verbose:
+ pywikibot.output(u"getCommonscat: The category doesnt exist.")
+ return u''
+ elif commonsPage.isRedirectPage():
+ if pywikibot.verbose:
+ pywikibot.output(u"getCommonscat: The category is a redirect")
+ return checkCommonscatLink(
+ commonsPage.getRedirectTarget().titleWithoutNamespace())
+ elif "Category redirect" in commonsPage.templates():
+ if pywikibot.verbose:
+ pywikibot.output(
+ u"getCommonscat: The category is a category redirect")
+ for template in commonsPage.templatesWithParams():
+ if ((template[0]=="Category redirect")
+ and (len(template[1]) > 0)):
+ return self.checkCommonscatLink(template[1][0])
+ elif commonsPage.isDisambig():
+ if pywikibot.verbose:
+ pywikibot.output(
+ u"getCommonscat: The category is disambiguation")
+ return u''
+ else:
+ return commonsPage.titleWithoutNamespace()
+ except pywikibot.BadTitle:
+ #Funky title so not correct
+ return u''
+ except pywikibot.PageNotFound:
+ return u''
+
def main():
'''
Parse the command line arguments and get a pagegenerator to work on.
@@ -413,22 +548,9 @@
u'You have to specify the generator you want to use for the script!')
pregenerator = pagegenerators.PreloadingGenerator(generator)
+ bot = CommonscatBot(pregenerator, always, summary)
+ bot.run()
- for page in pregenerator:
- if not page.exists():
- pywikibot.output(u'Page %s does not exist. Skipping.'
- % page.aslink())
- elif page.isRedirectPage():
- pywikibot.output(u'Page %s is a redirect. Skipping.' % page.aslink())
- elif page.isCategoryRedirect():
- pywikibot.output(u'Page %s is a category redirect. Skipping.'
- % page.aslink())
- elif page.isDisambig():
- pywikibot.output(u'Page %s is a disambiguation. Skipping.'
- % page.aslink())
- else:
- (status, always) = addCommonscat(page, summary, always)
-
if __name__ == "__main__":
try:
main()
Revision: 8545
Author: xqt
Date: 2010-09-13 04:53:26 +0000 (Mon, 13 Sep 2010)
Log Message:
-----------
update from trunk
Modified Paths:
--------------
branches/rewrite/scripts/titletranslate.py
Modified: branches/rewrite/scripts/titletranslate.py
===================================================================
--- branches/rewrite/scripts/titletranslate.py 2010-09-13 04:52:47 UTC (rev 8544)
+++ branches/rewrite/scripts/titletranslate.py 2010-09-13 04:53:26 UTC (rev 8545)
@@ -2,6 +2,7 @@
#
# (C) Rob W.W. Hooft, 2003
# (C) Yuri Astrakhan, 2005
+# (C) Pywikipedia bot team, 2003-2010
#
# Distributed under the terms of the MIT license.
#
@@ -9,7 +10,7 @@
#
import re
-import pywikibot, time
+import pywikibot
import pywikibot.date as date
def translate(page, hints = None, auto = True, removebrackets = False):
@@ -22,7 +23,7 @@
site = page.site
if hints:
for h in hints:
- if h.find(':') == -1:
+ if ':' not in h:
# argument given as -hint:xy where xy is a language code
codes = h
newname = ''
@@ -34,7 +35,8 @@
# we're currently working on ...
ns = page.namespace()
if ns:
- newname = u'%s:%s' % (site.family.namespace('_default', ns), page.title(withNamespace=False))
+ newname = u'%s:%s' % (site.family.namespace('_default', ns),
+ page.title(withNamespace=False))
else:
# article in the main namespace
newname = page.title()
@@ -59,24 +61,41 @@
result.append(x)
else:
if pywikibot.verbose:
- pywikibot.output(u"Ignoring unknown language code %s"%newcode)
+ pywikibot.output(u"Ignoring unknown language code %s"
+ % newcode)
- # Autotranslate dates into all other languages, the rest will come from existing interwiki links.
+ # Autotranslate dates into all other languages, the rest will come from
+ # existing interwiki links.
if auto:
# search inside all dictionaries for this link
- dictName, value = date.getAutoFormat( page.site.code, page.title() )
+ dictName, value = date.getAutoFormat(page.site.code,
+ page.title())
if dictName:
- if not (dictName == 'yearsBC' and date.maxyearBC.has_key(page.site.code) and value > date.maxyearBC[page.site.code]) or (dictName == 'yearsAD' and date.maxyearAD.has_key(page.site.code) and value > date.maxyearAD[page.site.code]):
- pywikibot.output(u'TitleTranslate: %s was recognized as %s with value %d' % (page.title(),dictName,value))
+ if not (dictName == 'yearsBC' and
+ page.site.code in date.maxyearBC and
+ value > date.maxyearBC[page.site.code]) or \
+ (dictName == 'yearsAD' and
+ page.site.code in date.maxyearAD and
+ value > date.maxyearAD[page.site.code]):
+ pywikibot.output(
+ u'TitleTranslate: %s was recognized as %s with value %d'
+ % (page.title(), dictName, value))
for entryLang, entry in date.formats[dictName].iteritems():
if entryLang != page.site.code:
- if dictName == 'yearsBC' and date.maxyearBC.has_key(entryLang) and value > date.maxyearBC[entryLang]:
+ if dictName == 'yearsBC' and \
+ entryLang in date.maxyearBC and \
+ value > date.maxyearBC[entryLang]:
pass
- elif dictName == 'yearsAD' and date.maxyearAD.has_key(entryLang) and value > date.maxyearAD[entryLang]:
+ elif dictName == 'yearsAD' and \
+ entryLang in date.maxyearAD and \
+ value > date.maxyearAD[entryLang]:
pass
else:
newname = entry(value)
- x = pywikibot.Link( newname, pywikibot.getSite(code=entryLang, fam=site.family) )
+ x = pywikibot.Link(
+ newname,
+ pywikibot.getSite(code=entryLang,
+ fam=site.family))
if x not in result:
result.append(x) # add new page
return result
@@ -89,36 +108,28 @@
def getPoisonedLinks(pl):
"""Returns a list of known corrupted links that should be removed if seen
+
"""
result = []
-
- pywikibot.output( u'getting poisoned links for %s' % pl.title() )
-
- dictName, value = date.getAutoFormat( pl.site.code, pl.title() )
+ pywikibot.output(u'getting poisoned links for %s' % pl.title())
+ dictName, value = date.getAutoFormat(pl.site.code, pl.title())
if dictName is not None:
pywikibot.output( u'date found in %s' % dictName )
-
# errors in year BC
if dictName in date.bcFormats:
for fmt in bcDateErrors:
result.append( fmt % value )
-
# i guess this is like friday the 13th for the years
if value == 398 and dictName == 'yearsBC':
- appendFormatedDates( result, dictName, 399 )
-
+ appendFormatedDates(result, dictName, 399)
if dictName == 'yearsBC':
- appendFormatedDates( result, 'decadesBC', value )
- appendFormatedDates( result, 'yearsAD', value )
-
+ appendFormatedDates(result, 'decadesBC', value)
+ appendFormatedDates(result, 'yearsAD', value)
if dictName == 'yearsAD':
- appendFormatedDates( result, 'decadesAD', value )
- appendFormatedDates( result, 'yearsBC', value )
-
+ appendFormatedDates(result, 'decadesAD', value)
+ appendFormatedDates(result, 'yearsBC', value)
if dictName == 'centuriesBC':
- appendFormatedDates( result, 'decadesBC', value*100+1 )
-
+ appendFormatedDates(result, 'decadesBC', value * 100 + 1)
if dictName == 'centuriesAD':
- appendFormatedDates( result, 'decadesAD', value*100+1 )
-
+ appendFormatedDates(result, 'decadesAD', value * 100 + 1)
return result
Revision: 8544
Author: xqt
Date: 2010-09-13 04:52:47 +0000 (Mon, 13 Sep 2010)
Log Message:
-----------
PEP 8 cosmetics
Modified Paths:
--------------
branches/rewrite/scripts/upload.py
Modified: branches/rewrite/scripts/upload.py
===================================================================
--- branches/rewrite/scripts/upload.py 2010-09-13 04:51:17 UTC (rev 8543)
+++ branches/rewrite/scripts/upload.py 2010-09-13 04:52:47 UTC (rev 8544)
@@ -9,22 +9,23 @@
-noverify Do not ask for verification of the upload description if one
is given
-If any other arguments are given, the first is the URL or filename to
-upload, and the rest is a proposed description to go with the upload. If
-none of these are given, the user is asked for the file or URL to upload.
-The bot will then upload the image to the wiki.
+If any other arguments are given, the first is the URL or filename to upload,
+and the rest is a proposed description to go with the upload. If none of these
+are given, the user is asked for the file or URL to upload. The bot will then
+upload the image to the wiki.
-The script will ask for the location of an image, if not given as a
-parameter, and for a description.
+The script will ask for the location of an image, if not given as a parameter,
+and for a description.
"""
#
# (C) Rob W.W. Hooft, Andre Engels 2003-2004
+# (C) Pywikipedia bot team, 2003-2010
#
# Distributed under the terms of the MIT license.
#
__version__='$Id$'
+#
-
import os, sys, time
import urllib
import urlparse
@@ -59,7 +60,9 @@
self.uploadByUrl = uploadByUrl
def urlOK(self):
- "Return true iff self.url looks like an URL or an existing local file."
+ """Return true if self.url looks like an URL or an existing local file.
+
+ """
return "://" in self.url or os.path.exists(self.url)
def read_file_content(self):
@@ -133,7 +136,7 @@
if not self.keepFilename:
pywikibot.output(
u"The filename on the target wiki will default to: %s"
- % filename)
+ % filename)
# FIXME: these 2 belong somewhere else, presumably in family
forbidden = '/' # to be extended
allowed_formats = (u'gif', u'jpg', u'jpeg', u'mid', u'midi',
Revision: 8543
Author: xqt
Date: 2010-09-13 04:51:17 +0000 (Mon, 13 Sep 2010)
Log Message:
-----------
PEP 8 cosmetics
Modified Paths:
--------------
trunk/pywikipedia/titletranslate.py
Modified: trunk/pywikipedia/titletranslate.py
===================================================================
--- trunk/pywikipedia/titletranslate.py 2010-09-13 04:24:41 UTC (rev 8542)
+++ trunk/pywikipedia/titletranslate.py 2010-09-13 04:51:17 UTC (rev 8543)
@@ -2,6 +2,7 @@
#
# (C) Rob W.W. Hooft, 2003
# (C) Yuri Astrakhan, 2005
+# (C) Pywikipedia bot team, 2003-2010
#
# Distributed under the terms of the MIT license.
#
@@ -34,7 +35,8 @@
# we're currently working on ...
ns = page.namespace()
if ns:
- newname = u'%s:%s' % (site.family.namespace('_default', ns), page.titleWithoutNamespace())
+ newname = u'%s:%s' % (site.family.namespace('_default', ns),
+ page.titleWithoutNamespace())
else:
# article in the main namespace
newname = page.title()
@@ -59,24 +61,40 @@
result.append(x)
else:
if pywikibot.verbose:
- pywikibot.output(u"Ignoring unknown language code %s"%newcode)
+ pywikibot.output(u"Ignoring unknown language code %s"
+ % newcode)
- # Autotranslate dates into all other languages, the rest will come from existing interwiki links.
+ # Autotranslate dates into all other languages, the rest will come from
+ # existing interwiki links.
if auto:
# search inside all dictionaries for this link
- dictName, value = date.getAutoFormat( page.site().language(), page.title() )
+ dictName, value = date.getAutoFormat(page.site().language(),
+ page.title())
if dictName:
- if not (dictName == 'yearsBC' and page.site().language() in date.maxyearBC and value > date.maxyearBC[page.site().language()]) or (dictName == 'yearsAD' and page.site().language() in date.maxyearAD and value > date.maxyearAD[page.site().language()]):
- pywikibot.output(u'TitleTranslate: %s was recognized as %s with value %d' % (page.title(),dictName,value))
+ if not (dictName == 'yearsBC' and
+ page.site().language() in date.maxyearBC and
+ value > date.maxyearBC[page.site().language()]) or \
+ (dictName == 'yearsAD' and
+ page.site().language() in date.maxyearAD and
+ value > date.maxyearAD[page.site().language()]):
+ pywikibot.output(
+ u'TitleTranslate: %s was recognized as %s with value %d'
+ % (page.title(), dictName, value))
for entryLang, entry in date.formats[dictName].iteritems():
if entryLang != page.site().language():
- if dictName == 'yearsBC' and entryLang in date.maxyearBC and value > date.maxyearBC[entryLang]:
+ if dictName == 'yearsBC' and \
+ entryLang in date.maxyearBC and \
+ value > date.maxyearBC[entryLang]:
pass
- elif dictName == 'yearsAD' and entryLang in date.maxyearAD and value > date.maxyearAD[entryLang]:
+ elif dictName == 'yearsAD' and \
+ entryLang in date.maxyearAD and \
+ value > date.maxyearAD[entryLang]:
pass
else:
newname = entry(value)
- x = pywikibot.Page( pywikibot.getSite(code=entryLang, fam=site.family), newname )
+ x = pywikibot.Page(
+ pywikibot.getSite(code=entryLang,
+ fam=site.family), newname)
if x not in result:
result.append(x) # add new page
return result
@@ -89,36 +107,28 @@
def getPoisonedLinks(pl):
"""Returns a list of known corrupted links that should be removed if seen
+
"""
result = []
-
- pywikibot.output( u'getting poisoned links for %s' % pl.title() )
-
- dictName, value = date.getAutoFormat( pl.site().language(), pl.title() )
+ pywikibot.output(u'getting poisoned links for %s' % pl.title())
+ dictName, value = date.getAutoFormat(pl.site().language(), pl.title())
if dictName is not None:
pywikibot.output( u'date found in %s' % dictName )
-
# errors in year BC
if dictName in date.bcFormats:
for fmt in bcDateErrors:
result.append( fmt % value )
-
# i guess this is like friday the 13th for the years
if value == 398 and dictName == 'yearsBC':
- appendFormatedDates( result, dictName, 399 )
-
+ appendFormatedDates(result, dictName, 399)
if dictName == 'yearsBC':
- appendFormatedDates( result, 'decadesBC', value )
- appendFormatedDates( result, 'yearsAD', value )
-
+ appendFormatedDates(result, 'decadesBC', value)
+ appendFormatedDates(result, 'yearsAD', value)
if dictName == 'yearsAD':
- appendFormatedDates( result, 'decadesAD', value )
- appendFormatedDates( result, 'yearsBC', value )
-
+ appendFormatedDates(result, 'decadesAD', value)
+ appendFormatedDates(result, 'yearsBC', value)
if dictName == 'centuriesBC':
- appendFormatedDates( result, 'decadesBC', value*100+1 )
-
+ appendFormatedDates(result, 'decadesBC', value * 100 + 1)
if dictName == 'centuriesAD':
- appendFormatedDates( result, 'decadesAD', value*100+1 )
-
+ appendFormatedDates(result, 'decadesAD', value * 100 + 1)
return result
Revision: 8542
Author: xqt
Date: 2010-09-13 04:24:41 +0000 (Mon, 13 Sep 2010)
Log Message:
-----------
update from rewrite
Modified Paths:
--------------
trunk/pywikipedia/interwiki_graph.py
Modified: trunk/pywikipedia/interwiki_graph.py
===================================================================
--- trunk/pywikipedia/interwiki_graph.py 2010-09-13 04:20:11 UTC (rev 8541)
+++ trunk/pywikipedia/interwiki_graph.py 2010-09-13 04:24:41 UTC (rev 8542)
@@ -96,7 +96,7 @@
elif self.graph.get_edge(sourceLabel, targetLabel):
pywikibot.output(
u'BUG: Tried to create duplicate edge from %s to %s'
- % (refPage.aslink(), page.aslink()))
+ % (refPage.title(asLink=True), page.title(asLink=True)))
# duplicate edges would be bad because then get_edge() would
# give a list of edges, not a single edge when we handle the
# opposite edge.
Revision: 8541
Author: xqt
Date: 2010-09-13 04:20:11 +0000 (Mon, 13 Sep 2010)
Log Message:
-----------
import wikipedia as pywikibot for merging to rewrite branch
Modified Paths:
--------------
trunk/pywikipedia/upload.py
Modified: trunk/pywikipedia/upload.py
===================================================================
--- trunk/pywikipedia/upload.py 2010-09-12 18:09:11 UTC (rev 8540)
+++ trunk/pywikipedia/upload.py 2010-09-13 04:20:11 UTC (rev 8541)
@@ -6,26 +6,31 @@
-keep Keep the filename as is
-filename Target filename
- -noverify Do not ask for verification of the upload description if one is given
+ -noverify Do not ask for verification of the upload description if one
+ is given
-If any other arguments are given, the first is the URL or filename
-to upload, and the rest is a proposed description to go with the
-upload. If none of these are given, the user is asked for the
-file or URL to upload. The bot will then upload the image to the wiki.
+If any other arguments are given, the first is the URL or filename to upload,
+and the rest is a proposed description to go with the upload. If none of these
+are given, the user is asked for the file or URL to upload. The bot will then
+upload the image to the wiki.
The script will ask for the location of an image, if not given as a parameter,
and for a description.
"""
#
# (C) Rob W.W. Hooft, Andre Engels 2003-2004
+# (C) Pywikipedia bot team, 2003-2010
#
# Distributed under the terms of the MIT license.
#
__version__='$Id$'
+#
import os, sys, time
-import urllib, mimetypes
-import wikipedia, config, query
+import urllib
+import mimetypes
+import wikipedia as pywikibot
+import config, query
def post_multipart(site, address, fields, files, cookies):
"""
@@ -76,6 +81,7 @@
ignoreWarning - Set this to True if you want to upload even if another
file would be overwritten or another mistake would be
risked.
+
"""
self._retrieved = False
self.url = url
@@ -86,33 +92,33 @@
self.verifyDescription = verifyDescription
self.ignoreWarning = ignoreWarning
if config.upload_to_commons:
- self.targetSite = targetSite or wikipedia.getSite('commons', 'commons')
+ self.targetSite = targetSite or pywikibot.getSite('commons', 'commons')
else:
- self.targetSite = targetSite or wikipedia.getSite()
+ self.targetSite = targetSite or pywikibot.getSite()
self.targetSite.forceLogin()
self.uploadByUrl = uploadByUrl
def urlOK(self):
- '''
- Returns true iff the URL references an online site or an
- existing local file.
- '''
- return self.url != '' and ('://' in self.url or os.path.exists(self.url))
+ """Return true if self.url looks like an URL or an existing local file.
+ """
+ return "://" in self.url or os.path.exists(self.url)
+
def read_file_content(self):
+ """Return name of temp file in which remote file is saved."""
if not self._retrieved or self.uploadByUrl:
# Get file contents
- wikipedia.output(u'Reading file %s' % self.url)
+ pywikibot.output(u'Reading file %s' % self.url)
if '://' in self.url:
resume = False
dt = 15
while not self._retrieved:
- uo = wikipedia.MyURLopener
- headers = [('User-agent', wikipedia.useragent)]
+ uo = pywikibot.MyURLopener
+ headers = [('User-agent', pywikibot.useragent)]
if resume:
- wikipedia.output(u"Resume download...")
+ pywikibot.output(u"Resume download...")
headers.append(('Range', 'bytes=%s-' % rlen))
uo.addheaders = headers
@@ -138,18 +144,18 @@
content_len = int(content_len)
if rlen < content_len:
self._retrieved = False
- wikipedia.output(u"Connection closed at byte %s (%s left)" % (rlen, content_len))
+ pywikibot.output(u"Connection closed at byte %s (%s left)" % (rlen, content_len))
if accept_ranges and rlen > 0:
resume = True
- wikipedia.output(u"Sleeping for %d seconds..." % dt)
+ pywikibot.output(u"Sleeping for %d seconds..." % dt)
time.sleep(dt)
if dt <= 60:
dt += 15
elif dt < 360:
dt += 60
else:
- if wikipedia.verbose:
- wikipedia.output(u"WARNING: No check length to retrieved data is possible.")
+ if pywikibot.verbose:
+ pywikibot.output(u"WARNING: No check length to retrieved data is possible.")
else:
# Opening local files with MyURLopener would be possible, but we
# don't do it because it only accepts ASCII characters in the
@@ -159,9 +165,10 @@
file.close()
def process_filename(self):
+ """Return base filename portion of self.url"""
# Isolate the pure name
filename = self.url
-
+ # Filename may be either a local file path or a URL
if '/' in filename:
filename = filename.split('/')[-1]
@@ -174,15 +181,19 @@
if self.useFilename:
filename = self.useFilename
if not self.keepFilename:
- wikipedia.output(u"The filename on the target wiki will default to: %s" % filename)
- # ask newfn until it's valid
+ pywikibot.output(
+ u"The filename on the target wiki will default to: %s"
+ % filename)
ok = False
# FIXME: these 2 belong somewhere else, presumably in family
forbidden = '/' # to be extended
- allowed_formats = (u'gif', u'jpg', u'jpeg', u'mid', u'midi', u'ogg', u'png', u'svg', u'xcf', u'djvu')
+ allowed_formats = (u'gif', u'jpg', u'jpeg', u'mid', u'midi',
+ u'ogg', u'png', u'svg', u'xcf', u'djvu')
+ # ask until it's valid
while not ok:
ok = True
- newfn = wikipedia.input(u'Enter a better name, or press enter to accept:')
+ newfn = pywikibot.input(
+ u'Enter a better name, or press enter to accept:')
if newfn == "":
newfn = filename
ext = os.path.splitext(newfn)[1].lower().strip('.')
@@ -191,7 +202,7 @@
print "Invalid character: %s. Please try again" % c
ok = False
if ext not in allowed_formats and ok:
- choice = wikipedia.inputChoice(u"File format is not one of [%s], but %s. Continue?" % (u' '.join(allowed_formats), ext), ['yes', 'no'], ['y', 'N'], 'N')
+ choice = pywikibot.inputChoice(u"File format is not one of [%s], but %s. Continue?" % (u' '.join(allowed_formats), ext), ['yes', 'no'], ['y', 'N'], 'N')
if choice == 'n':
ok = False
if newfn != '':
@@ -200,25 +211,29 @@
# Replace them here to avoid an extra confirmation form
filename = filename.replace(' ', '_')
# A proper description for the submission.
- wikipedia.output(u"The suggested description is:")
- wikipedia.output(self.description)
+ pywikibot.output(u"The suggested description is:")
+ pywikibot.output(self.description)
if self.verifyDescription:
- newDescription = u''
- choice = wikipedia.inputChoice(u'Do you want to change this description?', ['Yes', 'No'], ['y', 'N'], 'n')
- if choice == 'y':
- import editarticle
- editor = editarticle.TextEditor()
- newDescription = editor.edit(self.description)
- # if user saved / didn't press Cancel
- if newDescription:
- self.description = newDescription
+ newDescription = u''
+ choice = pywikibot.inputChoice(
+ u'Do you want to change this description?',
+ ['Yes', 'No'], ['y', 'N'], 'n')
+ if choice == 'y':
+ import editarticle
+ editor = editarticle.TextEditor()
+ newDescription = editor.edit(self.description)
+ # if user saved / didn't press Cancel
+ if newDescription:
+ self.description = newDescription
return filename
-
- def upload_image(self, debug=False, sessionKey = 0):
- """Gets the image at URL self.url, and uploads it to the target wiki.
- Returns the filename which was used to upload the image.
- If the upload fails, the user is asked whether to try again or not.
- If the user chooses not to retry, returns null.
+
+ def upload_image(self, debug=False, sessionKey=0):
+ """Upload the image at self.url to the target wiki.
+
+ Return the filename that was used to upload the image.
+ If the upload fails, ask the user whether to try again or not.
+ If the user chooses not to retry, return null.
+
"""
if not self.targetSite.has_api() or self.targetSite.versionnumber() < 16:
return self._uploadImageOld(debug)
@@ -245,46 +260,46 @@
if self.ignoreWarning:
params['ignorewarnings'] = 1
- wikipedia.output(u'Uploading file to %s via API....' % self.targetSite)
+ pywikibot.output(u'Uploading file to %s via API....' % self.targetSite)
data = query.GetData(params, self.targetSite)
- if wikipedia.verbose:
- wikipedia.output("%s" % data)
+ if pywikibot.verbose:
+ pywikibot.output("%s" % data)
if 'error' in data: # error occured
errCode = data['error']['code']
- wikipedia.output("%s" % data)
+ pywikibot.output("%s" % data)
else:
data = data['upload']
if data['result'] == u'Warning': #upload success but return warning.
- wikipedia.output("Got warning message:")
+ pywikibot.output("Got warning message:")
for k,v in data['warnings'].iteritems():
if k == 'duplicate-archive':
- wikipedia.output("\tThe file is duplicate a deleted file %s." % v)
+ pywikibot.output("\tThe file is duplicate a deleted file %s." % v)
elif k == 'was-deleted':
- wikipedia.output("\tThis file was deleted for %s." % v)
+ pywikibot.output("\tThis file was deleted for %s." % v)
elif k == 'emptyfile':
- wikipedia.output("\tFile %s is an empty file." % v)
+ pywikibot.output("\tFile %s is an empty file." % v)
elif k == 'exists':
- wikipedia.output("\tFile %s is exists." % v)
+ pywikibot.output("\tFile %s is exists." % v)
elif k == 'duplicate':
- wikipedia.output("\tUploaded file is duplicate with %s." % v)
+ pywikibot.output("\tUploaded file is duplicate with %s." % v)
elif k == 'badfilename':
- wikipedia.output("\tTarget filename is invalid.")
+ pywikibot.output("\tTarget filename is invalid.")
elif k == 'filetype-unwanted-type':
- wikipedia.output("\tFile %s type is unwatched type." % v)
- answer = wikipedia.inputChoice(u"Do you want to ignore?", ['Yes', 'No'], ['y', 'N'], 'N')
+ pywikibot.output("\tFile %s type is unwatched type." % v)
+ answer = pywikibot.inputChoice(u"Do you want to ignore?", ['Yes', 'No'], ['y', 'N'], 'N')
if answer == "y":
self.ignoreWarning = 1
self.keepFilename = True
return self.upload_image(debug, sessionKey = data['sessionkey'])
else:
- wikipedia.output("Upload aborted.")
+ pywikibot.output("Upload aborted.")
return
elif data['result'] == u'Success': #No any warning, upload and online complete.
- wikipedia.output(u"Upload successful.")
+ pywikibot.output(u"Upload successful.")
return filename #data['filename']
@@ -322,11 +337,11 @@
try:
formdata[key] = formdata[key].encode(self.targetSite.encoding())
except (UnicodeEncodeError, UnicodeDecodeError):
- formdata[key] = wikipedia.UnicodeToAsciiHtml(formdata[key]).encode(self.targetSite.encoding())
+ formdata[key] = pywikibot.UnicodeToAsciiHtml(formdata[key]).encode(self.targetSite.encoding())
# don't upload if we're in debug mode
if not debug:
- wikipedia.output(u'Uploading file to %s...' % self.targetSite)
+ pywikibot.output(u'Uploading file to %s...' % self.targetSite)
if self.uploadByUrl:
# Just do a post with all the fields filled out
@@ -342,16 +357,16 @@
# an English interface, this detection will fail!
success_msg = self.targetSite.mediawiki_message('successfulupload')
if success_msg in returned_html or response.code == 302:
- wikipedia.output(u"Upload successful.")
+ pywikibot.output(u"Upload successful.")
# The following is not a good idea, because the server also gives a 200 when
# something went wrong.
#if response.code in [200, 302]:
- # wikipedia.output(u"Upload successful.")
+ # pywikibot.output(u"Upload successful.")
elif response.code == 301:
- wikipedia.output(u"Following redirect...")
+ pywikibot.output(u"Following redirect...")
address = response.getheader('Location')
- wikipedia.output(u"Changed upload address to %s. Please update %s.py" % (address, self.targetSite.family.__module__))
+ pywikibot.output(u"Changed upload address to %s. Please update %s.py" % (address, self.targetSite.family.__module__))
exec('self.targetSite.upload_address = lambda: %r' % address, locals(), globals())
return self.upload_image(debug)
else:
@@ -361,17 +376,17 @@
returned_html = returned_html[returned_html.index('<!-- start content -->') + 22: returned_html.index('<!-- end content -->')]
except:
pass
- wikipedia.output(u'%s\n\n' % returned_html)
- wikipedia.output(u'%i %s' % (response.code, response.msg))
+ pywikibot.output(u'%s\n\n' % returned_html)
+ pywikibot.output(u'%i %s' % (response.code, response.msg))
if self.targetSite.mediawiki_message('uploadwarning') in returned_html:
- answer = wikipedia.inputChoice(u"You have recevied an upload warning message. Ignore?", ['Yes', 'No'], ['y', 'N'], 'N')
+ answer = pywikibot.inputChoice(u"You have recevied an upload warning message. Ignore?", ['Yes', 'No'], ['y', 'N'], 'N')
if answer == "y":
self.ignoreWarning = 1
self.keepFilename = True
return self._uploadImageOld(debug)
else:
- answer = wikipedia.inputChoice(u'Upload of %s probably failed. Above you see the HTML page which was returned by MediaWiki. Try again?' % filename, ['Yes', 'No'], ['y', 'N'], 'N')
+ answer = pywikibot.inputChoice(u'Upload of %s probably failed. Above you see the HTML page which was returned by MediaWiki. Try again?' % filename, ['Yes', 'No'], ['y', 'N'], 'N')
if answer == "y":
return self._uploadImageOld(debug)
else:
@@ -381,24 +396,23 @@
def run(self):
while not self.urlOK():
if not self.url:
- wikipedia.output(u'No input filename given')
+ pywikibot.output(u'No input filename given')
else:
- wikipedia.output(u'Invalid input filename given. Try again.')
- self.url = wikipedia.input(u'File or URL where image is now:')
+ pywikibot.output(u'Invalid input filename given. Try again.')
+ self.url = pywikibot.input(u'File or URL where image is now:')
return self.upload_image()
-def main(args):
+
+def main(*args):
url = u''
description = []
keepFilename = False
useFilename = None
verifyDescription = True
- # call wikipedia.py function to process all global wikipedia args
+ # process all global bot args
# returns a list of non-global args, i.e. args for upload.py
- args = wikipedia.handleArgs()
-
- for arg in args:
+ for arg in pywikibot.handleArgs(*args):
if arg:
if arg.startswith('-keep'):
keepFilename = True
@@ -411,11 +425,13 @@
else:
description.append(arg)
description = u' '.join(description)
- bot = UploadRobot(url, description=description, useFilename=useFilename, keepFilename=keepFilename, verifyDescription=verifyDescription)
+ bot = UploadRobot(url, description=description, useFilename=useFilename,
+ keepFilename=keepFilename,
+ verifyDescription=verifyDescription)
bot.run()
if __name__ == "__main__":
try:
- main(sys.argv[1:])
+ main()
finally:
- wikipedia.stopme()
+ pywikibot.stopme()