#!/usr/bin/env python3"""Bot to add images to Wikidata items.The image is extracted from the page_props. For this to be available thePageImages extension(https://www.mediawiki.org/wiki/Extension:PageImages) needs to beinstalled.The following options are provided:-always Don't prompt to make changes, just do them.-property The property to add. Should be of type commonsMedia.Usage: python pwb.py illustrate_wikidata <some generator>¶ms;"""## (C) Pywikibot team, 2013-2024## Distributed under the terms of MIT license.#from__future__importannotationsimportpywikibotfrompywikibotimportWikidataBot,pagegeneratorsdocuReplacements={'¶ms;':pagegenerators.parameterHelp}# noqa: N816
[docs]classIllustrateRobot(WikidataBot):"""A bot to add Wikidata image claims."""update_options={'property':'P18',}def__init__(self,**kwargs)->None:"""Initializer."""super().__init__(**kwargs)self.cacheSources()claim=pywikibot.Claim(self.repo,self.opt.property)ifclaim.type!='commonsMedia':raiseValueError(f'{self.opt.property} is of type {claim.type},'' should be commonsMedia')
[docs]deftreat_page_and_item(self,page,item)->None:"""Treat a page / item."""pywikibot.info('Found '+item.title())imagename=page.properties().get('page_image_free')ifnotimagename:returnclaims=item.get().get('claims')ifself.opt.propertyinclaims:pywikibot.info(f'Item {item.title()} already contains image 'f'({self.opt.property})')returnnewclaim=pywikibot.Claim(self.repo,self.opt.property)commonssite=pywikibot.Site('commons')imagelink=pywikibot.Link(imagename,source=commonssite,default_namespace=6)image=pywikibot.FilePage(imagelink)ifimage.isRedirectPage():image=pywikibot.FilePage(image.getRedirectTarget())ifnotimage.exists():pywikibot.info(f"{image} doesn't exist so I can't link to it")returnnewclaim.setTarget(image)# A generator might yield pages from multiple sitesself.user_add_claim(item,newclaim,page.site)
[docs]defmain(*args:str)->None:"""Process command line arguments and invoke bot. If args is an empty list, sys.argv is used. :param args: command line arguments """# Process global args and prepare generator args parserlocal_args=pywikibot.handle_args(args)generator_factory=pagegenerators.GeneratorFactory()options={}forarginlocal_args:opt,_,value=arg.partition(':')ifopt=='-property':options['property']=valueorpywikibot.input('Please enter the property you want to add:')elifopt=='-always':options[opt[1:]]=Trueelse:generator_factory.handle_arg(arg)options['generator']=generator_factory.getCombinedGenerator(preload=True)bot=IllustrateRobot(**options)bot.run()