Bikarhêner:Balyozxane/skrîpt/py/addnifûs.py

Ji Wîkîpediya, ensîklopediya azad.
"""
Şablona {{ş|Nifûsa tarîxî/wd}} li Komunên Fransayê zêde dike.
"""
import pywikibot
import re
from pywikibot import pagegenerators
from pywikibot.bot import SingleSiteBot, ConfigParserBot, AutomaticTWSummaryBot


def get_wikidata_id(site, title):
    page = pywikibot.Page(site, title)
    item = pywikibot.ItemPage.fromPage(page)
    if item.exists():
        return item
    else:
        return None


def count_props(item):
    item_dict = item.get()

    # Check if item has P1082 (population) property
    if 'P1082' in item_dict['claims']:
        p1082_claims = item_dict['claims']['P1082']
        population_count = len(p1082_claims)

        if population_count > 3:
            return True
        else:
            return False
    else:
        return False


def log_skipped(title):
    with open("addnifuslog.txt", "a", encoding="utf-8") as log_file:
        log_file.write(f"Skipped page: {title}\n")


class AppendTextBot(
    SingleSiteBot,
    ConfigParserBot,
    AutomaticTWSummaryBot,
):
    summary_key = 'basic-changing'
    use_redirects = False
    update_options = {
        'summary': "Bot: Şablona {{[[Şablon:Nifûsa tarîxî/wd|Nifûsa tarîxî/wd]]}} lê hat zêdekirin",
        'text': '',
        'top': False,
    }

    def treat_page(self) -> None:
        page = self.current_page
        site = page.site
        title = page.title()
        text = page.text
        wikidata_item = get_wikidata_id(site, title)
        if wikidata_item:
            print("Item found for:", title)
            result = count_props(wikidata_item)
            print("Population count result:", result)
            if result:
                # Filter sections
                sections = re.findall(r'==\s*(.*?)\s*==', text)
                print(str(sections))

                # Check if Gelhe or Gelhenasî sections exist
                has_gelhe_section = any(re.search(r'([Nn]if[ûu]s|[Gg]elhe)', section) for section in sections)
                has_gelhenasi_section = any(re.search(r'([Gg]elhenasî|Demografî)', section) for section in sections)

                # Skip the page if it contains Gelhe or Gelhenasî sections
                if has_gelhe_section or has_gelhenasi_section:
                    print("Skipping page as it contains Gelhe or Gelhenasî sections.")
                    return

                # Check if Binêre or Mijarên têkildar sections exist
                has_binere_section = any(re.search(r'[Bb]inêre', section) for section in sections)
                has_binere_section = any(re.search(r'Çavkanî', section) for section in sections)
                has_mijare_tekildar_section = any(re.search(r'[Mm]ijarên (din|têkildar)', section) for section in sections)

                # Add a new section before Binêre or Mijarên têkildar sections
                if has_binere_section or has_mijare_tekildar_section:
                    new_section_text = "\n== Nifûs ==\n{{Nifûsa tarîxî/wd}}\n{{Çepê paqij bike}}\n\n"
                    text = re.sub(r'(?===\s*[Bb]inêre|==\s*Çavkanî|==\s*[Mm]ijarên (têkildar|din))', new_section_text, text)
                    text = re.sub(r'\n\n\n*', '\n\n', text)
                    text = re.sub(r'^\n+', '', text)
                    text = re.sub(r'\{\{[cC]ommonscat-b}}', '{{Commonscat-biçûk}}', text)
                    text = re.sub(r'\|\s*wêne sernûçe\s*=', '| sernavê_wêne =', text)
                    # Define the pattern to find the text to replace
                    pattern = r'{{Erdnîgarî-şitil-Fransa}}\n?\n?{{Kontrola otorîteyê}}'

                    # Check if the pattern exists in the text
                    if re.search(pattern, text):
                        # If the pattern exists, perform the replacement
                        replacement = '{{Kontrola otorîteyê}}\n{{Fransa-erdnîgarî-şitil}}\n'
                        text = re.sub(pattern, replacement, text)
                    page.text = text
                    page.save(summary=self.opt.summary)
                else:
                    log_skipped(title)
                    return
            else:
                return

        else:
            return


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:
                value = pywikibot.input(f'Please enter a value for {option}')
            options[option] = value
        else:
            options[option] = True

    gen = gen_factory.getCombinedGenerator(preload=True)

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


if __name__ == '__main__':
    main()