Usuari:CobainBot/scripts/caquotes/template inclusion counter.py

'''
Copyright 2020 Carles Paredes Lanau <carlesparedes@gmail.com>
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.

Updated by Coet <coet.cawiki@gmail.com> at 2023/01/09.
'''

import pywikibot
import re

from datetime import datetime


class CountTemplateInclusions:
    def __init__(self):
        self.debug = True
        self.edit = False
        self.templates = {
            'Dita': 'Template:NUMBEROFPROVERBS',
            'Frase feta': 'Template:NUMBEROFSETPHRASES',
            'Cita': 'Template:NUMBEROFQUOTES',
            'Endevinalla': 'Template:NUMBEROFRIDDLES'
        }
        self.site = pywikibot.Site('ca', 'wikiquote', 'CobainBot')

    def verbose(self, message):
        if self.debug:
            print(message)

    def run(self):
        self.site.login()
        self.verbose(f"[{datetime.now():%H:%M:%S}] starting...")
        head = r'\{{2}'
        tail = r'\}{2}'
        for template, output in self.templates.items():
            page = pywikibot.Page(self.site, f'Template:{template}')
            total = 0
            pattern = f'{head}(?:{template}|{template.lower()})(.*?){tail}'
            for pg in page.embeddedin(namespaces=0, content=True):
                pg.text = re.sub(r'\{{2}sfn\|(?:.*?)\}{2}', '', pg.text)
                template_uses = re.findall(pattern, pg.text, re.S)
                total += len(template_uses)
                for use in template_uses:
                    template_uses = re.findall(r'[Vv]ariant\d{0,2}\s*=\s*(.+?)\n', use, re.S)
                    total += len(template_uses)
            target_page = pywikibot.Page(self.site, output)
            text = target_page.get()
            self.verbose(f"[{datetime.now():%H:%M:%S}] {output} old: {text} new: {total}")
            old_text_is_number = re.match(r'^\d+$', text)
            text_has_changed = old_text_is_number and total != int(text)
            if text_has_changed and self.edit:
                comment = f"Actualitzant el nombre d'inclusions de la plantilla, abans: {text}, ara: {total}"
                target_page.put(f'{total}', summary=comment, minor=True)
        self.verbose(f"[{datetime.now():%H:%M:%S}] finished.")


if __name__ == '__main__':
    template_counter = CountTemplateInclusions()
    template_counter.edit = True
    template_counter.debug = False  
    template_counter.run()