Purple exclamation mark.svg Planning the future of Botwiki! - Help us bring Botwiki up to date, contribute to our strategy discussion, add bot scripts, and contribute manuals, guides, and tutorials! Almost anything related to bots, particularly those used to edit mediawiki, is welcome.

Red exclamation mark.svg UNABLE TO EDIT? - We've experienced attacks by spambots lately and now require you to confirm your e-mail before you can edit (go to your preferences, enter an e-mail address, and request a confirmation e-mail, then go to your e-mail and click on the confirmation link). We also require new accounts to make a few edits and wait a few minutes before before you can create a page; however, if this is a problem contact us in #botwiki and we can manually confirm your account. Sorry for the inconvenience.

Python:Screencopy.py

From Botwiki
Jump to: navigation, search
#!/usr/bin/env python
#-*- coding:utf-8 -*-
 
#
# (C) FiloSottile, 2010
#
# Distributed under the terms of the CC-GNU GPL License.
#
 
import wikipedia
import sys, webbrowser
import re
import catlib
from datetime import datetime
 
rec_templates = {'Film' : 'film',
                 'Fumetto e animazione' : 'cartone',
                 'ProgrammaTV' : 'tv', 'FictionTV' : 'tv',
                 'Gamebox' : 'videogioco',
                 'Software' : 'software', 'Infobox Software': 'software',
                 'Album' : 'video musicale',
                 'Spettacolo teatrale': 'teatro'}
 
categoria = 'Categoria:Screenshot copyrighted'
 
editSummary = 'Bot: fix {{Screenshot Copyrighted}} - categoria "%s" - [[Utente:BotSottile/Task#screencopy.py]]'
 
logpage = 'Utente:BotSottile/risultati/screencopy'
 
def capitalize(s):
    return (s[0].upper() + s[1:]).strip().replace('_', ' ')
 
class ScreenBot():
    def __init__(self, cat):
        self.images = cat.articles()
        #self.images = [wikipedia.ImagePage(wikipedia.getSite(), u'File:Ale e Franz - È tanto che aspetti.png')]
        self.acceptall = False
        self.log = ([], [], [])
 
    def run(self):
        for image in self.images:
            if not image.isImage(): continue
            wikipedia.output(u"\n\n>>> \03{lightpurple}%s\03{default} <<<"
                                 % image.titleWithoutNamespace())
            using = list(wikipedia.ImagePage.usingPages(image))
            if len(using) != 1:
                wikipedia.output('\03{lightred}' + image.aslink() + '\03{default} used in more than one page or none at all')
                us = list(u.aslink() for u in using)
                self.log[0].append((image.aslink().replace('[[', '[[:'), us))
                continue
            templates = []
            othertl = []
            for tl in using[0].templatesWithParams():
                r = re.escape(image.titleWithoutNamespace()).replace('\ ', '***$$$***')     \
                                                            .replace('_', '***$$$***')      \
                                                            .replace('***$$$***', '[ _]')
                r = '[' + r[0].lower() + r[0].upper() + ']' + r[1:]
                #print r
                r = re.compile(r)
                if r.search(str(tl[1])):
                    if capitalize(tl[0]) in rec_templates.keys():
                        templates.append(tl[0])
                    else:
                        othertl.append(tl[0])
            if len(templates) != 1:
                if not othertl:
                    wikipedia.output('In \03{lightred}' + using[0].aslink() + '\03{default} there are more than one recognized template or none at all')
                    self.log[1].append((image.aslink().replace('[[', '[[:'), using[0].aslink()))
                    continue
                else:
                    wikipedia.output('In ' + using[0].aslink() + ' is/are used this/these template {{\03{lightred}' + '"\03{default}}}, {{\03{lightred}"'.join(othertl) + '\03{default}}}')
                    self.log[2].append((image.aslink().replace('[[', '[[:'), using[0].aslink(), \
                                       '{{tl|' + '}}<br />{{tl|'.join(othertl) + '}}'))
                    continue
            template = templates[0]
            category = rec_templates[capitalize(template)]
            wikipedia.output(u"Page: {{\03{lightblue}%s\03{default}}} - Template: {{\03{lightblue}%s\03{default}}}" \
                                                                    % (using[0].aslink(), template))
            text = image.get()
            param  = ''
            for tl in image.templatesWithParams():
                if capitalize(tl[0]) == 'Screenshot Copyrighted' or capitalize(tl[0]) == 'Screenshot copyrighted':
                    if len(tl[1]) > 0 and tl[1][0] != '': param = tl[1][0]
            new = re.sub(r'\{\{[sS]creenshot [Cc]opyrighted[^\}]*\}\}', '{{Screenshot Copyrighted|%s|%s}}' %(param, category), text)
            wikipedia.showDiff(text, new)
 
            if self.acceptall and new != text:
                try:
                    image.put(new, editSummary % category)
                    continue
                except wikipedia.EditConflict:
                    wikipedia.output(u'Skipping %s because of edit conflict'
                                     % (image.title(),))
                except wikipedia.SpamfilterError, e:
                    wikipedia.output(
                        u'Cannot change %s because of blacklist entry %s'
                        % (image.title(), e.url))
                except wikipedia.PageNotSaved, error:
                    wikipedia.output(u'Error putting page: %s'
                                     % (error.args,))
                except wikipedia.LockedPage:
                    wikipedia.output(u'Skipping %s (locked page)'
                                     % (image.title(),))
 
            while True:
                choice = wikipedia.inputChoice(
                            u'Do you want to accept these changes?',
                            ['Yes', 'No', 'open in Browser', 'All', "Quit"],
                            ['y', 'N', 'b', 'a', 'q'], 'N')
                if choice == 'b':
                    webbrowser.open("http://%s%s" % (
                        image.site().hostname(),
                        image.site().nice_get_address(image.title())
                    ))
                    wikipedia.input("Press Enter when finished in browser.")
                    text = image.get(get_redirect=True, force=True)
                    continue
                if choice == 'q':
                    return
                if choice == 'y':
                    image.put_async(new, editSummary % category)
                if choice == 'a':
                    image.put_async(new, editSummary % category)
                    self.acceptall = True
                # choice must be 'N'
                break
        self.put_log()
    def put_log(self):
        res = '==[[Utente:BotSottile/Task#screencopy.py]] - %s==\n\n' % datetime.now().strftime("%d %B %Y %I:%M%p")
        righe = list(e[0] + ': ' + ', '.join(e[1]) for e in self.log[0])
        res += "=== Immagini non usate in una sola pagina ===\n* "
        res += "\n* ".join(righe)
        righe = list(': '.join(e) for e in self.log[1])
        res += "\n\n=== Immagini non usate in template ===\n* "
        res += "\n* ".join(righe)
        righe = list(' || '.join(e) for e in self.log[2])
        res += """
 
=== Immagini usate in template sconosciuti ===
{| class="wikitable sortable"
! Immagine !! pagina !! template
|-
| """
        res += "\n|-\n| ".join(righe)
        res += "\n|}"
        wikipedia.Page(wikipedia.getSite(), logpage).put(res, 'Bot: risultato [[Utente:BotSottile/Task#screencopy.py]]')
 
if __name__ == "__main__":
    try:
        site = wikipedia.getSite()
        category = catlib.Category(site, categoria)
        bot = ScreenBot(category)
        bot.run()
    finally:
        try: bot.put_log()
        except: pass
        wikipedia.stopme()
Personal tools
Share