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

#!/usr/bin/env python3
"""
python pwb.py updatewin -file:mytools.py -s:'fix'
"""
import requests
import mwparserfromhell
import pywikibot
from pywikibot.tools import first_lower, first_upper
from typing import List, Union


def ucfirst(wikicode) -> str:
    """
    :param wikicode: text parsed by mwparserfromhell
    :return: First char uppercase string stripped. Use first_upper for other strings
    """
    return first_upper(str(wikicode).strip())


def lcfirst(wikicode) -> str:
    """
    :param wikicode: text parsed by mwparserfromhell
    :return: First char lowercase string stripped Use first_lower for other strings
    """
    return first_lower(str(wikicode).strip())


def get_sitelinks(qid: str, lang_codes: Union[str, List[str]]) -> dict:
    """
    Retrieve sitelinks for the specified Wikidata QID and language codes.

    :param qid: Wikidata QID
    :param lang_codes: String or list of language codes (without 'wiki' suffix). If a single language code is provided as a string, 'wiki' suffix will be appended automatically.
    :return: If ['ku', 'en'] send, returns dictionary with kuwiki, enwiki
    """
    url = f"https://www.wikidata.org/w/api.php"
    params = {
        "action": "wbgetentities",
        "format": "json",
        "ids": qid,
        "props": "sitelinks"
    }

    # Convert lang_codes to a list if it's a string
    if isinstance(lang_codes, str):
        lang_codes = [lang_codes]

    try:
        # Sending the API request
        response = requests.get(url, params=params)
        data = response.json()
        result = {}
        # Extracting titles of sitelinks for each language code
        if 'sitelinks' in data['entities'][qid]:
            sitelinks = data['entities'][qid]['sitelinks']
            for lang_code in lang_codes:
                lang_code_with_wiki = lang_code + 'wiki'
                site_data = sitelinks.get(lang_code_with_wiki, None)
                result[lang_code_with_wiki] = site_data['title'] if site_data else None
            return result
        else:
            return {lang_code + 'wiki': None for lang_code in lang_codes}
    except Exception as e:
        print(f"An error occurred: {e}")
        return {lang_code + 'wiki': None for lang_code in lang_codes}


# from #https://github.com/ashotjanibekyan/WikiPyScripts/blob/master/helpers.py
def without_comments(wiki_text):
    if wiki_text is None:
        return None
    wikicode = mwparserfromhell.parse(wiki_text)
    for node in wikicode.nodes[:]:
        if isinstance(node, mwparserfromhell.nodes.Comment):
            wikicode.remove(node)
    return str(wikicode).strip()


# from #https://github.com/ashotjanibekyan/WikiPyScripts/blob/master/helpers.py
def contains_category(page: pywikibot.Page, category_title: str) -> bool:
    if not page or not page.exists():
        return False

    for category in page.categories():
        if category.title(with_ns=False) == category_title:
            return True

    return False


# from #https://github.com/ashotjanibekyan/WikiPyScripts/blob/master/helpers.py
def matrix_to_wikitable(matrix):
    text = '{| class="wikitable sortable"\n'
    text += '!' + '!!'.join(matrix[0]) + '\n'
    for i in range(1, len(matrix)):
        if isinstance(matrix[i], list) and len(matrix[i]) == len(matrix[0]):
            row = (str(x) if x or x == 0 else ' ' for x in matrix[i])
            text += '|-\n|' + '||'.join(row) + '\n'
    text += '|}'
    return text