Skip to content

Wiki Tools

Collection of helper functions for pages, queries and wikitext.

CONDITION_PATTERN = re.compile('\\[\\[.*?\\]\\]', re.DOTALL) module-attribute

matches an SMW query condition, which may contain '|' as the disjunction operator and must therefore be removed before the parameters are split

LIMIT_PARAM_PATTERN = re.compile('^limit\\s*=\\s*(\\d+)$', re.IGNORECASE) module-attribute

matches a limit parameter of an SMW query, e.g. 'limit=100'

SearchParam

Bases: OswBaseModel

Search parameters for semantic and prefix search

Source code in src/osw/wiki_tools.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
class SearchParam(OswBaseModel):
    """Search parameters for semantic and prefix search"""

    query: Union[str, List[str]]
    parallel: Optional[bool] = None  # is set to true if query is a list longer than 5
    debug: Optional[bool] = False
    limit: Optional[int] = 1000
    """the result limit to apply, None to apply none and leave it to the wiki.
    Ignored by semantic_search for a query that sets 'limit=' itself, since SMW
    honours the last limit in the query string"""
    return_json: Optional[bool] = False
    return_meta: Optional[bool] = False
    """If True, semantic_search returns one SemanticSearchResult per query instead
    of a flat list of titles, so that a caller can report a truncated result set.
    Ignored when return_json is True, since the raw wiki response already carries
    the truncation signal"""

    def __init__(self, **data):
        super().__init__(**data)
        if not isinstance(self.query, list):
            self.query = [self.query]
        if len(self.query) > 5 and self.parallel is None:
            self.parallel = True
        if self.parallel is None:
            self.parallel = False

limit = 1000 class-attribute instance-attribute

the result limit to apply, None to apply none and leave it to the wiki. Ignored by semantic_search for a query that sets 'limit=' itself, since SMW honours the last limit in the query string

return_meta = False class-attribute instance-attribute

If True, semantic_search returns one SemanticSearchResult per query instead of a flat list of titles, so that a caller can report a truncated result set. Ignored when return_json is True, since the raw wiki response already carries the truncation signal

SemanticSearchResult

Bases: OswBaseModel

Result of a single semantic query, including whether the wiki truncated it

Source code in src/osw/wiki_tools.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
class SemanticSearchResult(OswBaseModel):
    """Result of a single semantic query, including whether the wiki truncated it"""

    query: str
    """the query as sent to the wiki, including any limit appended by
    semantic_search"""
    titles: List[str]
    """the page-title fulltext strings of the results that exist"""
    count: int
    """the number of results this response carried, before dropping
    non-existing pages, so it can be larger than len(titles). It is not the
    total number of matching pages on the wiki, which SMW does not report"""
    truncated: bool
    """True if the wiki reported further results beyond those returned"""
    next_offset: Optional[int] = None
    """the absolute offset at which the remaining results start, to be passed
    back as '|offset='. None for a complete result set. It says where to
    continue, not how many results remain"""

count instance-attribute

the number of results this response carried, before dropping non-existing pages, so it can be larger than len(titles). It is not the total number of matching pages on the wiki, which SMW does not report

next_offset = None class-attribute instance-attribute

the absolute offset at which the remaining results start, to be passed back as '|offset='. None for a complete result set. It says where to continue, not how many results remain

query instance-attribute

the query as sent to the wiki, including any limit appended by semantic_search

titles instance-attribute

the page-title fulltext strings of the results that exist

truncated instance-attribute

True if the wiki reported further results beyond those returned

Searches the content (wikitext) of pages. Equivalent to the following mediawiki API call api.php?action=query&list=search&srsearch=Star Wars.

See https://www.mediawiki.org/wiki/API:Search for details.

Parameters:

Name Type Description Default
site Site

Site object from mwclient lib

required
text Union[str, List[str], SearchParam]

Query text or instance of SearchParam

required

Returns:

Name Type Description
result Union[List[str], List[dict]]

With return_json=False (default): a flat list of page titles. With return_json=True: a list of raw MediaWiki search API response dicts, one per query (always a list, even for a single query).

Source code in src/osw/wiki_tools.py
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def content_search(
    site: mwclient.client.Site, text: Union[str, List[str], SearchParam]
) -> Union[List[str], List[dict]]:
    """Searches the content (wikitext) of pages. Equivalent to the following
    mediawiki API call api.php?action=query&list=search&srsearch=Star Wars.

    See https://www.mediawiki.org/wiki/API:Search for details.

    Parameters
    ----------
    site :
        Site object from mwclient lib
    text :
        Query text or instance of SearchParam

    Returns
    -------
    result:
        With ``return_json=False`` (default): a flat list of page titles. With
        ``return_json=True``: a list of raw MediaWiki ``search`` API response
        dicts, one per query (always a list, even for a single query).
    """
    if not isinstance(text, SearchParam):
        query = SearchParam(query=text)
    else:
        query = text

    def content_search_(single_text) -> Union[List[str], dict]:
        page_list = list()
        result = site.api(
            "query",
            list="search",
            srsearch=single_text,
            srlimit=query.limit,
            format="json",
        )
        if query.debug and len(result["query"]["search"]) == 0:
            print("No results")
        if query.return_json:
            return result

        for page in result["query"]["search"]:
            title = page["title"]
            if query.debug:
                print(title)
            page_list.append(title)
        return page_list

    if query.parallel:
        query_results = parallelize(
            func=content_search_, iterable=query.query, flush_at_end=query.debug
        )
    else:
        query_results = [content_search_(single_text=sq) for sq in query.query]

    if query.return_json:
        # Each entry of query_results is the raw API response dict for one query.
        # Do not flatten dicts; always return the list of responses (one per query),
        # even when only a single query was passed.
        return query_results

    return [item for sublist in query_results for item in sublist]

copy_list_of_wiki_pages(title_list, site0, site1, overwrite, callback=None)

Parameters:

Name Type Description Default
title_list list
required
site0 Site

Source site object from mwclient lib

required
site1 Site

Target site object from mwclient lib

required
overwrite bool

Whether to overwrite existing pages at target site

required
callback NoneType or function

Function passed over, to perform operation on the titles of the source pages and to be passed as title of the target pages. See examples below. Example functions: capitalize = lambda x: x.capitalize() def change_namespace(title, namespace): if ":" in namespace: namespace = namespace.split(":")[0] if ":" in title: splits = title.split(":") old_name = splits[1].capitalize() new_title = namespace + ":" + old_name else: new_title = namespace + ":" + title.capitalize() return new_title Examples of passing a function as parameter: callback = capitalize callback = lambda x: x.lower()

None

Returns:

Name Type Description
results_dict dict

Dictionary, containing the results of the copying operations

Source code in src/osw/wiki_tools.py
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
def copy_list_of_wiki_pages(title_list, site0, site1, overwrite, callback=None):
    """

    Parameters
    ----------
    title_list : list
    site0 : mwclient.client.Site
        Source site object from mwclient lib
    site1 : mwclient.client.Site
        Target site object from mwclient lib
    overwrite : bool
        Whether to overwrite existing pages at target site
    callback : NoneType or function
        Function passed over, to perform operation on the titles of the source pages and
        to be passed as title of the
        target pages. See examples below.
        Example functions:
            capitalize = lambda x: x.capitalize()
            def change_namespace(title, namespace):
                if ":" in namespace:
                    namespace = namespace.split(":")[0]
                if ":" in title:
                    splits = title.split(":")
                    old_name = splits[1].capitalize()
                    new_title = namespace + ":" + old_name
                else:
                    new_title = namespace + ":" + title.capitalize()
                return new_title
        Examples of passing a function as parameter:
            callback = capitalize
            callback = lambda x: x.lower()

    Returns
    -------
    results_dict : dict
        Dictionary, containing the results of the copying operations
    """

    success_list = list()
    fail_list = list()
    for title0 in title_list:
        if callback is None:
            title1 = title0
        else:
            title1 = callback(title0)
        success = copy_wiki_page(title0, title1, site0, site1, overwrite)
        if success:
            success_list.append(title1)
        else:
            fail_list.append(title1)
    results_dict = {
        "Successfully copied pages": success_list,
        "Pages failed to copy": fail_list,
    }
    return results_dict

copy_wiki_page(title0, title1, site0, site1, overwrite=True)

Parameters:

Name Type Description Default
title0 str

Title of the source page

required
title1 str

Title of the target page

required
site0 Site

Source site object from mwclient lib

required
site1 Site

Target site object from mwclient lib

required
overwrite bool

Whether to overwrite existing pages at target site

True

Returns:

Name Type Description
success bool
Source code in src/osw/wiki_tools.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
def copy_wiki_page(title0, title1, site0, site1, overwrite=True):
    """

    Parameters
    ----------
    title0 : str
        Title of the source page
    title1 : str
        Title of the target page
    site0 : mwclient.client.Site
        Source site object from mwclient lib
    site1 : mwclient.client.Site
        Target site object from mwclient lib
    overwrite : bool
        Whether to overwrite existing pages at target site

    Returns
    -------
    success: bool

    """
    if title0.lower() == title1.lower() and site0 == site1:
        # copy on it self = no action necessary
        success = True
    else:
        page0 = site0.pages[title0]
        content = page0.text()
        if overwrite:
            success = create_or_overwrite_wiki_page(title1, content, site1)
        else:
            search_result = search_wiki_page(title1, site1)
            if (
                search_result["Result"] and search_result["Exact match"]
            ):  # page already exists
                success = False
            else:
                # search_result["Result"] == True/False
                # search_result["Exact match"] == False
                success = create_or_overwrite_wiki_page(title1, content, site1)
    return success

create_or_overwrite_wiki_page(title, content, site)

Creates a page with the passed title and content. If the page already exists, the prior content is replaced with the passed content.

Parameters:

Name Type Description Default
title str

Title of the wiki page, e.g., User:Someone1234

required
content str
required
site Site

Site object from mwclient lib

required

Returns:

Name Type Description
success bool
Source code in src/osw/wiki_tools.py
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
def create_or_overwrite_wiki_page(title, content, site):
    """Creates a page with the passed title and content. If the page already exists,
    the prior content is replaced with the passed content.

    Parameters
    ----------
    title : str
        Title of the wiki page, e.g., User:Someone1234
    content : str
    site : mwclient.client.Site
        Site object from mwclient lib

    Returns
    -------
    success : bool
    """
    target_page = site.pages[title]
    target_page.edit(content, "[bot] create page")
    success = True
    return success

create_or_update_wiki_page_with_template(title, content, site, overwrite_with_empty=False)

Creates a wiki page with a template included in the content. If the page does already exist, the parameters within the template are update

Parameters:

Name Type Description Default
title str

Title of the wiki page, e.g., User:Someone1234

required
content str
required
site Site

Site object from mwclient lib

required
overwrite_with_empty bool

Decided whether a template parameter's value in an preexisting page is overwritten with an empty value

False

Returns:

Name Type Description
success bool
Source code in src/osw/wiki_tools.py
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
def create_or_update_wiki_page_with_template(
    title, content, site, overwrite_with_empty=False
):
    """Creates a wiki page with a template included in the content. If the page does
    already exist, the parameters within the template are update

    Parameters
    ----------
    title : str
        Title of the wiki page, e.g., User:Someone1234
    content : str
    site : mwclient.client.Site
        Site object from mwclient lib
    overwrite_with_empty : bool
        Decided whether a template parameter's value in an preexisting page is
        overwritten with an empty value

    Returns
    -------
    success : bool
    """
    search_result = search_wiki_page(title, site)
    if search_result["Result"]:
        existing_page = site.pages[title]
        existing_text = existing_page.text()
        # update the page's content (template only)
        updated_content = update_template_within_wikitext(
            text=existing_text,
            template_text=content,
            overwrite_with_empty=overwrite_with_empty,
        )
        success = create_or_overwrite_wiki_page(title, updated_content, site)
    else:
        # just create the page
        success = create_or_overwrite_wiki_page(title, content, site)
    return success

create_site_object(domain, password_file='', credentials=None)

Parameters
domain :
    Domain of the OSW instance, as specifed in the yaml file
password_file :
    path to file with <username>

credentials : Dictionary with the credentials (username, password)

Returns
site : mwclient.client.Site
    Site object from mwclient lib
Source code in src/osw/wiki_tools.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def create_site_object(
    domain: str, password_file: Union[str, FilePath] = "", credentials: dict = None
) -> mwclient.client.Site:
    """
    Parameters
    ----------
    domain :
        Domain of the OSW instance, as specifed in the yaml file
    password_file :
        path to file with <username>\n<password>
    credentials :
        Dictionary with the credentials (username, password)
    Returns
    -------
    site : mwclient.client.Site
        Site object from mwclient lib
    """
    domain_dict = {
        "wiki-dev": {"Address": "wiki-dev.open-semantic-lab.org"},
        "onterface": {"Address": "onterface.open-semantic-lab.org:"},
    }
    if domain in domain_dict.keys():
        domain = domain_dict[domain]["Address"]

    site = mwclient.Site(domain, path="/w/")
    if credentials is None:
        credentials = read_credentials_from_yaml(password_file, domain)
    # else:
    #     credentials = credentials
    # Login with dictionary unpacking:
    # site.login(**credentials)
    # Explicit login:
    site.login(username=credentials["username"], password=credentials["password"])
    del credentials
    return site

delete_wiki_page(title, site, reason)

Deletes the wiki page with the passed title, if it was found (exact match!), otherwise returns False

Parameters:

Name Type Description Default
title str

Title of the wiki page, e.g., User:Someone1234

required
site Site

Site object from mwclient lib

required
reason str
required

Returns:

Name Type Description
success bool
Source code in src/osw/wiki_tools.py
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def delete_wiki_page(title, site, reason):
    """Deletes the wiki page with the passed title, if it was found (exact match!),
    otherwise returns False

    Parameters
    ----------
    title : str
        Title of the wiki page, e.g., User:Someone1234
    site : mwclient.client.Site
        Site object from mwclient lib
    reason : str

    Returns
    -------
    success : bool
    """
    try:
        page = site.pages[title]
        page.delete(reason=reason, watch=False, unwatch=True, oldimage=False)
        success = True
    except mwclient.errors.APIError:
        success = False
    return success

edit_wiki_page_with_content_merge(title, new_content, site, template_name)

Edits an existing wiki page, while merging the passed new content with the content of the existing page

Parameters:

Name Type Description Default
title str

Title of the wiki page, e.g., User:Someone1234

required
new_content str
required
site Site

Site object from mwclient lib

required
template_name str
required

Returns:

Name Type Description
success bool
Source code in src/osw/wiki_tools.py
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
def edit_wiki_page_with_content_merge(title, new_content, site, template_name):
    """Edits an existing wiki page, while merging the passed new content with the
    content of the existing page

    Parameters
    ----------
    title : str
        Title of the wiki page, e.g., User:Someone1234
    new_content : str
    site : mwclient.client.Site
        Site object from mwclient lib
    template_name : str

    Returns
    -------
    success : bool
    """
    search_result = search_wiki_page(title, site)
    if search_result["Result"]:
        source_page = site.pages[title]
        source_page_content = source_page.text()
        # todo: test function
        new_content = merge_wiki_page_text(
            new_content, source_page_content, template_name=template_name
        )
        target_page = site.pages[title]
        target_page.edit(new_content, "[bot] update of page content")
        success = True
    else:
        success = False
    return success

get_file_info_and_usage(site, title)

(For 'File' pages only) Get information about the file and its usage

Parameters:

Name Type Description Default
site Site

Site object from mwclient lib.

required
title Union[str, List[str], SearchParam]

Title(s) of the wiki page(s) or instance of SearchParam.

required

Returns:

Name Type Description
result List[Dict[str, Union[Dict[str, str], List[str]]]]

Dictionary with page titles as keys and nested dictionary with keys 'info' and 'usage'.

Notes

Query to reproduce: action=query format=json prop=imageinfo|fileusage titles=File%3AOSW857d85031d85425aa94db8b4720e84b7.png &iiprop=timestamp%7Cuser&fulimit=5000"

Resources

Use the sandbox to design and test the queries: https://demo.open-semantic-lab.org/wiki/Special:ApiSandbox

Source code in src/osw/wiki_tools.py
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
def get_file_info_and_usage(
    site: mwclient.client.Site, title: Union[str, List[str], SearchParam]
) -> List[Dict[str, Union[Dict[str, str], List[str]]]]:
    """(For 'File' pages only) Get information about the file and its usage

    Parameters
    ----------
    site:
        Site object from mwclient lib.
    title:
        Title(s) of the wiki page(s) or instance of SearchParam.

    Returns
    -------
    result:
        Dictionary with page titles as keys and nested dictionary with keys 'info' and
        'usage'.

    Notes
    -----
    Query to reproduce:
        action=query
        format=json
        prop=imageinfo|fileusage
        titles=File%3AOSW857d85031d85425aa94db8b4720e84b7.png
        &iiprop=timestamp%7Cuser&fulimit=5000"

    Resources
    ---------
    Use the sandbox to design and test the queries:
    https://demo.open-semantic-lab.org/wiki/Special:ApiSandbox
    """
    if not isinstance(title, SearchParam):
        query = SearchParam(query=title, debug=False)
    else:  # SearchParam
        query = title

    def get_file_info_and_usage_(single_title):
        api_request_result = site.api(
            action="query",
            format="json",
            prop="imageinfo|fileusage",
            titles=single_title,
            iiprop="timestamp|user",
            fulimit=query.limit,
        )
        using_pages = []
        file_info = {
            "title": single_title,
            "author": "File not found or no creation logged",
            "timestamp": "File not found or no creation logged",
            "editor": [],
            "editing_timestamp": [],
        }

        if len(api_request_result["query"]["pages"]) == 0:
            if query.debug:
                _logger.debug(f"Page not found: '{single_title}'!")
        else:
            image_info: List[Dict[str, str]] = []
            file_usage: List[Dict[str, Union[str, int]]] = []
            for _page_id, page_dict in api_request_result["query"]["pages"].items():
                if page_dict["title"] == single_title:
                    image_info = page_dict.get("imageinfo", [])
                    file_usage = page_dict.get("fileusage", [])
            if len(image_info) != 0:
                file_info["author"] = image_info[0]["user"]
                file_info["timestamp"] = image_info[0]["timestamp"]
                for ii in image_info:
                    file_info["editor"].append(ii["user"])
                    file_info["editing_timestamp"].append(ii["timestamp"])
            if file_usage is not None:
                for fu_page_dict in file_usage:
                    using_pages.append(fu_page_dict["title"])
            if query.debug:
                _logger.debug(f"File info for '{single_title}' retrieved.")
        return {"info": file_info, "usage": using_pages}

    if query.parallel:
        api_request_results = parallelize(
            func=get_file_info_and_usage_,
            iterable=query.query,
            flush_at_end=query.debug,
        )
    else:
        api_request_results = [
            get_file_info_and_usage_(single_title=st) for st in query.query
        ]

    return api_request_results

get_query_limit(query)

Returns the limit an SMW ask query sets itself, None if it sets none

Parameters:

Name Type Description Default
query str

an SMW ask query string, e.g. '[[Category:Item]]|?Name|limit=2'

required

Returns:

Name Type Description
result Optional[int]

the limit the query asks for, or None if the query does not set one or sets one that is not a number

Source code in src/osw/wiki_tools.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def get_query_limit(query: str) -> Optional[int]:
    """Returns the limit an SMW ask query sets itself, None if it sets none

    Parameters
    ----------
    query :
        an SMW ask query string, e.g. '[[Category:Item]]|?Name|limit=2'

    Returns
    -------
    result:
        the limit the query asks for, or None if the query does not set one or
        sets one that is not a number
    """
    limit = None
    for parameter in CONDITION_PATTERN.sub("", query).split("|"):
        match = LIMIT_PARAM_PATTERN.match(parameter.strip())
        if match:
            # SMW honours the last limit in the query string
            limit = int(match.group(1))
    return limit

Standard query. Equivalent to the following mediawiki API call api.php?action=query&list=prefixsearch&pssearch=Star Wars.

See https://www.mediawiki.org/wiki/API:Prefixsearch for details.

Parameters:

Name Type Description Default
site Site

Site object from mwclient lib

required
text Union[str, SearchParam]

Query text or instance of SearchParam

required

Returns:

Name Type Description
result Union[List[str], List[dict]]

With return_json=False (default): a flat list of page titles. With return_json=True: a list of raw MediaWiki prefixsearch API response dicts, one per query (always a list, even for a single query).

Source code in src/osw/wiki_tools.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def prefix_search(
    site: mwclient.client.Site, text: Union[str, SearchParam]
) -> Union[List[str], List[dict]]:
    """Standard query. Equivalent to the following mediawiki API call
    api.php?action=query&list=prefixsearch&pssearch=Star Wars.

    See https://www.mediawiki.org/wiki/API:Prefixsearch for details.

    Parameters
    ----------
    site :
        Site object from mwclient lib
    text :
        Query text or instance of SearchParam

    Returns
    -------
    result:
        With ``return_json=False`` (default): a flat list of page titles. With
        ``return_json=True``: a list of raw MediaWiki ``prefixsearch`` API response
        dicts, one per query (always a list, even for a single query).
    """
    if not isinstance(text, SearchParam):
        query = SearchParam(query=text)
    else:
        query = text

    def prefix_search_(single_text) -> Union[List[str], dict]:
        page_list = list()
        result = site.api(
            "query",
            list="prefixsearch",
            pssearch=single_text,
            pslimit=query.limit,
            format="json",
        )
        if query.debug and len(result["query"]["prefixsearch"]) == 0:
            _logger.debug("No results")
        if query.return_json:
            return result

        for page in result["query"]["prefixsearch"]:
            title = page["title"]
            if query.debug:
                _logger.debug(title)
            page_list.append(title)
        return page_list

    if query.parallel:
        query_results = parallelize(
            func=prefix_search_, iterable=query.query, flush_at_end=query.debug
        )
    else:
        query_results = [prefix_search_(single_text=sq) for sq in query.query]

    if query.return_json:
        # Each entry of query_results is the raw API response dict for one query.
        # Do not flatten dicts; always return the list of responses (one per query),
        # even when only a single query was passed.
        return query_results

    return [item for sublist in query_results for item in sublist]

read_credentials_from_yaml(password_file, domain=None)

Reads credentials from a yaml file

Parameters:

Name Type Description Default
password_file Union[str, FilePath]

Path to the yaml file with the credentials.

required
domain str

Domain of the OSW instance, as specifed in the yaml file.

None

Returns:

Name Type Description
credentials dict

Dictionary with the credentials, expected to contain keys 'username' and 'password'.

Source code in src/osw/wiki_tools.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
def read_credentials_from_yaml(
    password_file: Union[str, FilePath], domain: str = None
) -> dict:
    """Reads credentials from a yaml file

    Parameters
    ----------
    password_file :
        Path to the yaml file with the credentials.
    domain:
        Domain of the OSW instance, as specifed in the yaml file.

    Returns
    -------
    credentials :
        Dictionary with the credentials, expected to
        contain keys 'username' and 'password'.
    """
    if password_file != "":
        with open(password_file) as stream:
            try:
                accounts = yaml.safe_load(stream)
                if domain is not None and domain in accounts.keys():
                    domain = domain
                elif len(accounts.keys()) > 0:
                    domain = next(iter(accounts.keys()))
                    if len(accounts.keys()) > 0:
                        domain = next(iter(accounts.keys()))
                user = accounts[domain]["username"]
                password = accounts[domain]["password"]
            except yaml.YAMLError as exc:
                _logger.error(exc)
    else:
        user = input("Enter bot username (username@botname)")
        password = getpass.getpass("Enter bot password")
    return {"username": user, "password": password}

read_domains_from_credentials_file(cred_filepath)

Reads domains and credentials from a yaml file

Parameters:

Name Type Description Default
cred_filepath Union[str, FilePath]

Path to the yaml file with the credentials

required
Source code in src/osw/wiki_tools.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def read_domains_from_credentials_file(
    cred_filepath: Union[str, FilePath],
) -> Tuple[List[str], Dict[str, Dict[str, str]]]:
    """Reads domains and credentials from a yaml file

    Parameters
    ----------
    cred_filepath
        Path to the yaml file with the credentials

    Returns
    -------

    """
    with open(cred_filepath, encoding="utf-8") as stream_:
        try:
            accounts_dict = yaml.safe_load(stream_)
            # An empty file is parsed as None by yaml.safe_load, which would
            #  otherwise raise an AttributeError on the .keys() call below
            if accounts_dict is None:
                accounts_dict = {}
            domains_list = list(accounts_dict.keys())
            if len(domains_list) == 0:
                raise ValueError("No domain found in accounts.pwd.yaml!")
            return domains_list, accounts_dict
        except yaml.YAMLError as exc_:
            _logger.error(exc_)

search_redirection_sources(site, target_title, debug=False)

Returns a list of pages redirecting to the page with target_title per #REDIRECT [[target]] syntax

Parameters:

Name Type Description Default
site Site

Site object from mwclient lib

required
target_title str

Title of the target wiki page

required
debug bool

Whether to log debugging messages

False

Returns:

Name Type Description
page_list list of pages redirecting to the page with target_title
Source code in src/osw/wiki_tools.py
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
def search_redirection_sources(
    site: mwclient.client.Site, target_title: str, debug: bool = False
):
    """Returns a list of pages redirecting to the page with target_title per #REDIRECT
    [[target]] syntax

    Parameters
    ----------
    site :
        Site object from mwclient lib
    target_title :
        Title of the target wiki page
    debug:
        Whether to log debugging messages

    Returns
    -------
    page_list : list of pages redirecting to the page with target_title
    """
    page_list = []
    result = site.api("query", titles=target_title, prop="redirects", format="json")
    if len(result["query"]["pages"]) == 0:
        if debug:
            _logger.debug("No results")
    else:
        for page in result["query"]["pages"]:
            if "redirects" not in result["query"]["pages"][page]:
                if debug:
                    _logger.debug("No results")
            else:
                for redirecting_source in result["query"]["pages"][page]["redirects"]:
                    title = redirecting_source["title"]
                    page_list.append(title)
    return page_list

search_wiki_page(title, site)

Page search wrapper that adds exact match functionality with ignore-case on top of the prefix_search()'s functionality.

Parameters:

Name Type Description Default
title str

Title of the wiki page, e.g., User:Someone1234

required
site Site

Site object from mwclient lib

required

Returns:

Name Type Description
result_dict dict
Source code in src/osw/wiki_tools.py
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
def search_wiki_page(title: str, site: mwclient.client.Site):
    """Page search wrapper that adds exact match functionality with ignore-case on
    top of the  prefix_search()'s functionality.

    Parameters
    ----------
    title :
        Title of the wiki page, e.g., User:Someone1234
    site :
        Site object from mwclient lib

    Returns
    -------
    result_dict : dict
    """
    result = site.api(
        "query", list="prefixsearch", pssearch=title, pslimit=1000, format="json"
    )
    if len(result["query"]["prefixsearch"]) == 0:
        return {"Result": False, "List": list()}
    else:
        exact_match = False
        page_title_list = list()
        for page in result["query"]["prefixsearch"]:
            page_title = page["title"]
            page_title_list.append(page_title)
            if page_title.lower() == title.lower():
                exact_match = True
        result_dict = {
            "Result": True,
            "List": page_title_list,
            "Exact match": exact_match,
        }
        return result_dict

Semantic query

Parameters:

Name Type Description Default
site Site

Site object from mwclient lib

required
query Union[str, List[str], SearchParam]

(List of) query text(s) or instance of SearchParam. A query that sets limit= itself keeps that limit; SearchParam.limit is only appended to a query that does not, and only when it is not None.

required

Returns:

Name Type Description
result Union[List[str], List[dict], List[SemanticSearchResult]]

With return_json=False and return_meta=False (default): a flat list of page-title fulltext strings. With return_json=True: a list of raw SMW ask result dicts, one per query (always a list, even for a single query). With return_meta=True: a list of SemanticSearchResult, one per query, which reports whether the wiki truncated the result set. return_json takes precedence if both are set.

Source code in src/osw/wiki_tools.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def semantic_search(
    site: mwclient.client.Site, query: Union[str, List[str], SearchParam]
) -> Union[List[str], List[dict], List[SemanticSearchResult]]:
    """Semantic query

    Parameters
    ----------
    site :
        Site object from mwclient lib
    query :
        (List of) query text(s) or instance of SearchParam. A query that sets
        ``limit=`` itself keeps that limit; ``SearchParam.limit`` is only
        appended to a query that does not, and only when it is not None.

    Returns
    -------
    result:
        With ``return_json=False`` and ``return_meta=False`` (default): a flat
        list of page-title fulltext strings. With ``return_json=True``: a list of
        raw SMW ``ask`` result dicts, one per query (always a list, even for a
        single query). With ``return_meta=True``: a list of SemanticSearchResult,
        one per query, which reports whether the wiki truncated the result set.
        ``return_json`` takes precedence if both are set.
    """
    if not isinstance(query, SearchParam):
        query = SearchParam(query=query)

    def semantic_search_(single_query):
        page_list = list()
        # SMW honours the last limit in the query string, so appending the
        # default would silently override a limit the caller wrote themselves.
        # A SearchParam limit of None asks for no limit at all, leaving the
        # wiki to apply its own default
        limit = get_query_limit(single_query)
        if limit is None and query.limit is not None:
            limit = query.limit
            single_query += f"|limit={limit}"
        result = site.api("ask", query=single_query, format="json")
        results = _ask_results_as_dict(result["query"]["results"])
        n = len(results)
        if query.debug:
            if n == 0:
                _logger.debug(f"Query '{single_query}' returned no results")
            else:
                _logger.debug(f"Query '{single_query}' returned {n} results")
        # SMW reports an incomplete result set with a top-level
        # 'query-continue-offset' holding the offset the remainder starts at,
        # and omits the key for a complete one. That replaces the earlier
        # comparison of the result count against the limit, which was wrong in
        # both directions: it could not see the wiki's own '$smwgQMaxLimit'
        # cap, and it reported a complete set of exactly 'limit' results as
        # truncated
        next_offset = result.get("query-continue-offset")
        truncated = next_offset is not None
        if truncated:
            _logger.warning(
                f"Query '{single_query}' returned {n} results and the wiki "
                f"reports further ones. Results are truncated - raise the "
                f"limit or page through with '|offset={next_offset}' to "
                f"retrieve the remainder."
            )
        if query.return_json:
            return result

        dropped = 0
        for page in results.values():
            title = page["fulltext"]
            exists = page["exists"]
            if "#" not in title and query.debug:
                _logger.debug(title)
                # original position of "page_list.append(title)" line
            if exists == "1":
                page_list.append(title)
            else:
                dropped += 1
        if dropped > 0:
            _logger.warning(
                f"Query '{single_query}': {dropped} of {n} results were dropped "
                f"because the wiki reported them as non-existing pages."
            )
        if query.return_meta:
            return SemanticSearchResult(
                query=single_query,
                titles=page_list,
                count=n,
                truncated=truncated,
                next_offset=next_offset,
            )
        return page_list

    if query.parallel:
        query_results = parallelize(
            func=semantic_search_, iterable=query.query, flush_at_end=query.debug
        )
    else:
        query_results = [semantic_search_(single_query=sq) for sq in query.query]

    if query.return_json or query.return_meta:
        # Each entry of query_results is the raw SMW result dict, or the
        # SemanticSearchResult, for one query. Do not flatten those; always
        # return one entry per query, even when only a single query was passed.
        return query_results

    return [item for sublist in query_results for item in sublist]