Bikarhêner:Balyozxane/skrîpt/py/kontrolabingehîn.py

import requests
import pywikibot
import time
import mwparserfromhell as mw

sirovetine = True


def print_sirove(sirove):
    if not sirovetine:
        print(sirove)


# Function to get the corresponding Kurdish title using the Wikidata API
def get_kuwiki_title(enwiki_title, kuwiki_cache):
    if enwiki_title in kuwiki_cache:
        print_sirove(f"Kurdish title for '{enwiki_title}' found in cache.")
        return kuwiki_cache[enwiki_title]

    url = f"https://www.wikidata.org/w/api.php?action=wbgetentities&sites=enwiki&titles={enwiki_title}&props=sitelinks&format=json"
    response = requests.get(url)
    data = response.json()
    entity = next(iter(data["entities"].values()))  # Get the first (and only) entity
    if "sitelinks" in entity and "kuwiki" in entity["sitelinks"]:
        kuwiki_title = entity["sitelinks"]["kuwiki"]["title"]
        kuwiki_cache[enwiki_title] = kuwiki_title  # Cache the Kurdish title
        print_sirove(f"Kurdish title for '{enwiki_title}' fetched: '{kuwiki_title}'")
        return kuwiki_title
    else:
        print_sirove(f"Kurdish title for '{enwiki_title}' not found.")
        return None


def log_problem(problem_message):
    print_sirove(f"Logging problem:{problem_message}")
    site = pywikibot.Site("ku", "wikipedia")
    page = pywikibot.Page(site, "Bikarhêner:Balyozbot/Xeletiyên gotarên bingehîn")

    # Load existing content
    page_text = page.text

    # Add the new log entry
    new_entry = f"* {problem_message}\n"
    updated_content = new_entry + page_text

    # Save the updated content to the page
    page.text = updated_content
    page.save(summary="Problemek hat qeydkirin")


def get_sinif(vital_title):
    print_sirove(f"Getting sinif for vital title: {vital_title}")
    site = pywikibot.Site("ku", "wikipedia")
    talk_page = pywikibot.Page(site, "Gotûbêj:{}".format(vital_title))
    if not talk_page.exists():
        log_problem(f"[[Gotûbêj:{vital_title}]] tine ye")
        return None

    text = talk_page.text
    wikicode = mw.parse(text)
    for template in wikicode.filter_templates():
        if template.name.strip().lower() == "kalika wîkîprojeyê":
            if not template.has("bingehîn"):
                log_problem(f"[[Gotûbêj:{vital_title}]] {{{{param|bingehîn}}}} bi kar nayîne.")
            if template.has("sinif"):
                sinif_value = template.get("sinif").value.strip()
                if sinif_value:  # Check if sinif_value is not empty
                    print_sirove(f"Sinif value found: {sinif_value}")
                    return sinif_value
                else:
                    print_sirove("Sinif value is empty")
                    return "Nesinifandî"
            else:
                print_sirove("Sinif parameter not found")
                return "Nesinifandî"

    # Log the problem if the template Kalika wîkîprojeyê is not found
    log_problem(f"[[Gotûbêj:{vital_title}]] şablona Kalika wîkîprojeyê bi kar nayîne")
    return None


def ku_page_exists(ku_page_title):
    print_sirove(f"Checking if ku page exists:{ku_page_title}")
    site = pywikibot.Site("ku", "wikipedia")
    page = pywikibot.Page(site, ku_page_title)
    return page.exists()


def update_summary_table(text, ikon_count, sinif):
    # Find the indices of the update comments
    start_index = text.find("<!-- update summary table:")
    end_index = text.find("<!-- update end: summary table -->")

    if start_index == -1 or end_index == -1:
        print_sirove("Update comments not found in the text.")
        return text

    # Construct the replacement text
    replacement_text = f"<!-- update summary table: The text between update comments will be automatically overwritten by the bot. -->\n"
    replacement_text += f"\nHemû {sum(ikon_count.values())} gotar. Ji bo statîstîkên berfirehtir binêrin [[Wîkîpediya:Wîkîproje Gotarên bingehîn/Statîstîk|Rûpela statîstîkê]].\n{{| class=\"wikitable sortable\"\n|-\n! Sinif !! #Gotar\n"
    for sinif_value in sorted(sinif,
                              key=lambda x: ('GB', 'GBA', 'B', 'C', 'Destpêkî', 'Şitil', 'Nesinifandî', 'Xwestî').index(
                                      x)):
        if sinif_value == "Xwestî":
            kategori = '<span title="Gotarên ku divê werin çêkirin">Xwestî</span>'
        elif sinif_value == 'Nesinifandî':
            kategori = f'[[:Kategorî:Gotarên bingehîn ên nehatine sinifandin|{sinif_value}]]'
        else:
            kategori = f'[[:Kategorî:Gotarên bingehîn ên Wîkîpediyayê bi sinifa {sinif_value}|{sinif_value}]]'
        if not ikon_count[sinif_value] == 0:
            replacement_text += f"|-\n| {{{{class/icon|{sinif_value}}}}} {kategori} || {ikon_count[sinif_value]}\n"

    replacement_text += "|}"
    replacement_text += "\n<!-- update end: summary table -->"

    # Replace the text between the update comments
    updated_text = text[:start_index] + replacement_text + text[end_index + len("<!-- update end: summary table -->"):]

    return updated_text


def process_page(page_title, kuwiki_cache):
    print("Processing page:", page_title)
    site = pywikibot.Site("ku", "wikipedia")
    page = pywikibot.Page(site, page_title)
    text = page.text
    wikicode = mw.parse(text)
    sinif = {'GB', 'GBA', 'B', 'C', 'Destpêkî', 'Şitil', 'Xwestî', 'Nesinifandî'}
    ikon_count = {value: 0 for value in sinif}  # Initialize count for each sinif value to 0

    for template in wikicode.filter_templates():

        if template.name.lower() == "lgb":

            if template.has("en"):
                en_page = template.get("en").value.strip()
                print_sirove(f"English page found:{en_page}")

                # îkona sinifê bi "Nesinifandî" lê zêde bike
                template.add("îkon", "Xwestî")
                ikon_count["Xwestî"] += 1  # Increment count for "Xwestî"

                # Niha şablonê kontrol bike
                if template.has(1):
                    vital_title = template.get(1).value.strip()
                    print_sirove(f"Vital title found:{vital_title}")
                    if ku_page_exists(vital_title):
                        log_problem(
                            f"[[{page_title}]]: Rûpela [[{vital_title}]] heye lê belê {{{{ş|lgb}}}} {{{{param|en}}}} bi kar tîne.")
                    else:
                        if vital_title == en_page:
                            template.remove(1)
                else:
                    if ku_page_exists(en_page):
                        log_problem(
                            f"[[{page_title}]]: Rûpela [[{en_page}]] heye lê belê {{{{ş|lgb}}}} param {{{{param|en}}}} bêyî param {{{{param|1}}}} bi kar tîne.")
                    else:
                        kuwiki_title = get_kuwiki_title(en_page, kuwiki_cache)
                        if kuwiki_title:
                            log_problem(
                                f"[[{page_title}]]: Li gorî wîkîdaneyê rûpela [[{kuwiki_title}]] heye lê belê param {{{{param|en}}}} ya şablona {{{{ş|lgb}}}} şûnda vî navî [[{en_page}]] bi kar tîne.")
            else:
                vital_title = template.get(1).value.strip()
                print_sirove(f"Vital title found: {vital_title}")
                sinif_value = get_sinif(vital_title)

                if sinif_value and sinif_value.lower() in {s.lower() for s in sinif}:
                    sinif_value = next(s for s in sinif if s.lower() == sinif_value.lower())
                    print_sirove(sinif_value)
                    template.add("îkon", sinif_value)
                    ikon_count[sinif_value] += 1  # Increment count for the sinif_value

    # print_sirove the count of each sinif value at the end
    print_sirove("Count of each sinif value for îkon:")
    for value, count in ikon_count.items():
        print_sirove(f"{value}: {count}")

    updated_wikicode = str(wikicode)
    updated_wikicode = update_summary_table(updated_wikicode, ikon_count, sinif)
    page.text = updated_wikicode
    page.save(summary="[[Bikarhêner:Balyozxane/skrîpt/py/kontrolabingehîn.py|Bot]]: Naverok hat kontrolkirin û îkon lê hat zêdekirin. Ji bo xeletiyan bnr. [[Bikarhêner:Balyozbot/Xeletiyên gotarên bingehîn|log]] ")


# List of pages to process

kuwiki_cache = {}
pages_list = [
        "Wîkîpediya:Gotarên bingehîn/Level/1",
        "Wîkîpediya:Gotarên bingehîn/Level/2",
        "Wîkîpediya:Gotarên bingehîn",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Biyolojî û zanistên sihetê",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Civak û zanistên civakî",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Cografya",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Felsefe û dîn",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Huner",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Jiyana rojane",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Matematîk",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Mirov",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Tarîx",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Teknolojî",
        "Wîkîpediya:Gotarên bingehîn/Level/4/Zanistên fizîkî"
]

# Process each page
for page_title in pages_list:
    process_page(page_title, kuwiki_cache)

print("\nDone at %s!" % (time.ctime()))