User:Eatcha/add-dnc-detect-if-cropped

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
# -*- coding: utf-8 -*-
import re
import pywikibot
from pywikibot import pagegenerators
"""
Copyright 2020 User:Eatcha

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
def commit(old_text, new_text, page, summary):
    """Show diff and submit text to page."""
    out("\nAbout to make changes at : '%s'" % page.title())
    pywikibot.showDiff(old_text, new_text)
    page.put(new_text, summary=summary, watchArticle=True, minorEdit=False)

def findEndOfTemplate(text, template):
    """Find end of any template, by Zitrax"""
    m = re.search(r"{{\s*%s" % template, text)
    if not m:
        return 0
    lvl = 0
    cp = m.start() + 2
    while cp < len(text):
        ns = text.find("{{", cp)
        ne = text.find("}}", cp)
        # If we see no end tag, we give up
        if ne == -1:
            return 0
        # Handle case when there are no more start tags
        if ns == -1:
            if not lvl:
                return ne + 2
            else:
                lvl -= 1
                cp = ne + 2
        elif not lvl and ne < ns:
            return ne + 2
        elif ne < ns:
            lvl -= 1
            cp = ne + 2
        else:
            lvl += 1
            cp = ns + 2
    # Apparently we never found it
    return 0

def out(text, newline=True, date=False, color=None):
    """Just output some text to the consoloe or log."""
    if color:
        text = "\03{%s}%s\03{default}" % (color, text)
    dstr = (
        "%s: " % datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
        if date
        else ""
    )
    pywikibot.stdout("%s%s" % (dstr, text), newline=newline)

def add_template(cat,summary):
    """Cheks if template present, if not adds it. """
    gen = pagegenerators.CategorizedPageGenerator(pywikibot.Category(SITE,cat))
    for file in gen:
        file_name = file.title()
        if file_name.startswith("File:"):
            page = pywikibot.Page(SITE, file_name)
            old_rev = page.oldest_revision
            if 'crop' in (old_rev.comment).lower():
                out('already cropped', color="white")
                continue
            old_text = page.get()
            if 'do not crop' in old_text.lower():
                out('already marked with DNC', color="white")
                continue
            if re.search(r"\{\{(?:|\s*)[Ss]pecimen", old_text):
                end = findEndOfTemplate(old_text, "[Ss]pecimen")
            else:
                end = findEndOfTemplate(old_text, "[Ii]nformation")
            
            new_text = (old_text[:end]+  "\n{{Do not crop}}\n" + old_text[end:])
            try:
                commit(old_text, new_text, page, summary,)
            except:
                continue

def main(*args):
    args = pywikibot.handle_args(*args)
    global SITE
    SITE = pywikibot.Site()

    summary = "Adding {{Do not crop}} template, requested by Pigsonthewing @ commons.wikimedia.org/w/index.php?title=Commons:Bots/Work_requests&oldid=414102776" # change this summary
    # change the categories in the array.
    cat_array = [
        "Type specimens of the Natural History Museum, London",
        "Lepidoptera of the Natural History Museum, London",
        "Hesperiidae of the Natural History Museum, London",
        "Lycaenidae of the Natural History Museum, London",
        "Nymphalidae of the Natural History Museum, London",
        "Papilionidae of the Natural History Museum, London",
        "Pieridae of the Natural History Museum, London",
        "Riodinidae of the Natural History Museum, London",
        "Ornithoptera (Birdwing) butterflies collection, Natural History Museum, London",
        "Trogonoptera (Birdwing) butterflies collection, Natural History Museum, London",
        "Troides (Birdwing) butterflies collection, Natural History Museum, London",
        "Siphonaptera of the Natural History Museum, London",
        ]
    for cat in cat_array:
        add_template(cat,summary)

if __name__ == "__main__":
  try:
    main()
  finally:
    pywikibot.stopme()