import pywikibot
from pywikibot import pagegenerators as pg

commit=False
verbose=True
srclng='nl'        
    
def add2alias(wd,alias):
    if srclng in wd.aliases:
      if (not (alias in wd.aliases[srclng])):
        wd.aliases[srclng].append(alias)
    else:
        return([alias])
    return(wd.aliases[srclng])

def check_alias(wd, check4alias):
  if (srclng in wd.aliases):
    for alias in wd.aliases[srclng]:
      if (alias.upper()==check4alias.upper()):
        return(True)
  if (srclng in wd.labels):
    return(wd.labels[srclng].upper()==check4alias.upper())
  return(False)        


def wd_sparql_query(spq):
   generator=pg.WikidataSPARQLPageGenerator(spq,site=pywikibot.Site('wikidata','wikidata'))
   for wd in generator:
     try:
       wd.get(get_redirect=True)
       yield wd
     except:
       pass


def find_nicknames():
 #check if nickname is not simply the first name
 print('Zzzztart')
 for item in wd_sparql_query('select ?item ?nickname where {?item wdt:P1449 ?nickname}'):
    print('Item')
    for nickname in item.claims['P1449']:
      print('-Nickname')  
      nick=nickname.getTarget()
      #if (nick!=None):
      print(f'nickname: {nick.text}')
      #print(10/0)  
    
def find_birthnames():    
   for item in wd_sparql_query('select ?item where {?item wdt:P1477 ?geboortenaam}'):
     for birthname in item.claims['P1477']:
       t=birthname.getTarget()
       if t!=None:
        bn=t.text
        if not check_alias(item,bn):
          print(f'{item.title()}-{bn}')   
          if (srclng in item.labels):
            item.editAliases(aliases={srclng:add2alias(item,bn)},summary='alias from birthname')
          else:
            item.editEntity({'labels':{srclng:bn}},summary='label from birthname')


print('Start')
find_birthnames()
print('Klaar')
Start
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
Sleeping for 5.0 seconds, 2019-06-26 10:31:14
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
WARNING: wikibase-lexeme datatype is not supported yet.
Klaar
print('Nee')
Nee