Here naverokê

Bikarhêner:Balyozxane/skrîpt/py/replaceParams.py

Ji Wîkîpediya, ensîklopediya azad.
"""
Replaces parameter aliases with the parameter defined in the TemplateData. Only for templates listed at [[Bikarhêner:Balyozxane/skrîpt/json/replaceParams.json]]
To-do:
1. Template name might not match if it starts with lowercase.
2. Use redirects instead of listing them in the json. Json should only use the list of templates
"""
import pywikibot
from pywikibot import pagegenerators
from pywikibot.bot import SingleSiteBot, ConfigParserBot, AutomaticTWSummaryBot
import json
import re
import mwparserfromhell
import requests


class AppendTextBot(
    SingleSiteBot,
    ConfigParserBot,
    AutomaticTWSummaryBot,
):
    summary_key = 'basic-changing'
    use_redirects = False

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        # Fetch JSON content from the specified page
        json_page = pywikibot.Page(self.site, "Bikarhêner:Balyozxane/skrîpt/json/replaceParams.json")
        self.json_content = json_page.text
        print("JSON Content:", self.json_content)

        # Load JSON content into a dictionary
        try:
            self.parameter_conversions = json.loads(self.json_content)
            self.alias_templates = self.parameter_conversions.get('templates', {})
            print("Alias Templates:", str(self.alias_templates))
        except json.JSONDecodeError as e:
            pywikibot.error(f"Error decoding JSON content: {e}")
            self.parameter_conversions = {}

    def treat_page(self) -> None:
        page = self.current_page
        print("Current Page:", page)
        if not page.exists():
            pywikibot.error(f"Skipping {page.title()} since it does not exist")
            return

        text = page.text
        wikicode = mwparserfromhell.parse(text)
        print("WikiCode:", wikicode)

        # Iterate through each template in the page
        for template in wikicode.filter_templates():
            print("Processing Template:", template)
            # Check if the template name matches any of the citation templates
            if self.should_process_template(template):
                print("Template should be processed")
                self.replace_template_name(template)
                self.replace_aliases(template)

        new_text = str(wikicode)
        print("New Text:", new_text)
        if new_text != text:
            page.text = new_text
            print("Page Text:", page.text)
            page.save(summary="Replace template parameter aliases with parameter names")

    def should_process_template(self, template):
        """Checks if a template should be processed based on self.cite_templates."""
        template_name = template.name
        template_name_lower = template_name.strip().lower()
        print("Template Name Lower:", template_name_lower)
        for key, value in self.alias_templates.items():
            if (
                    key.lower() == template_name_lower
                    or value.lower() == template_name_lower
            ):
                return True
        return False

    @staticmethod
    def get_template_data(template_title):
        url = "https://ku.wikipedia.org/w/api.php"
        params = {
            "action": "templatedata",
            "titles": f"Template:{template_title}",
            "format": "json"
        }

        response = requests.get(url, params=params)
        print("API Response:", response)

        if response.status_code == 200:
            data = response.json()
            print("API Data:", data)
            pages_data = data.get('pages', {})
            page_number = next(iter(pages_data))  # Get the first (and only) key in pages_data
            print("Page Number:", page_number)
            params_data = pages_data[page_number].get('params', {})

            alias_dict = {}
            for param_name, param_info in params_data.items():
                aliases = param_info.get('aliases', [])
                for alias in aliases:
                    alias_dict[alias] = param_name

            print("Alias Dictionary:", alias_dict)
            return alias_dict
        else:
            print("Error:", response.status_code)
            return {}

    def replace_template_name(self, template):
        template_name = template.name.strip()
        print("Template Name:", template_name)
        try:
            new_template_name = self.alias_templates[template_name]
            print("New Template Name:", new_template_name)
            template.name = f'{new_template_name}\n'
            print("Template After Replacement:", template)
        except KeyError:
            pass

    def replace_aliases(self, template):
        template_name = template.name.strip()
        print("Template Name for Aliases:", template_name)
        alias_dict = self.get_template_data(template_name)
        print("Alias Dictionary:", alias_dict)

        if not alias_dict:
            print("No template data")
            return text

        for param in template.params:
            # Check if the parameter name is an alias
            param_name_stripped = param.name.strip()
            print("Param Name Stripped:", param_name_stripped)
            if param_name_stripped in alias_dict:
                # Get the corresponding parameter name from the alias dictionary
                new_param_name = alias_dict[param_name_stripped]
                # Adjust the length of the new parameter name to match the original length
                new_param_name = new_param_name.ljust(len(param.name))
                # Replace the parameter name
                param.name = new_param_name
                print("New Param Name:", new_param_name)


def main(*args: str) -> None:
    local_args = pywikibot.handle_args(args)
    gen_factory = pagegenerators.GeneratorFactory()
    local_args = gen_factory.handle_args(local_args)

    options = {'text': ''}

    for arg in local_args:
        option, _, value = arg.partition(':')
        if option in ('summary', 'text'):
            if not value:
                pywikibot.input(f'Please enter a value for {option}')
            options[option] = value
        else:
            options[option] = True

    gen = gen_factory.getCombinedGenerator(preload=True)
    print("Generator:", gen)

    if not pywikibot.bot.suggest_help(missing_generator=not gen):
        bot = AppendTextBot(generator=gen, **options)
        bot.run()


if __name__ == '__main__':
    main()