import pywikibot
from pywikibot import pagegenerators as pg
#import csv

def wd_from_file(usefilename):
  repo=pywikibot.Site('wikidata','wikidata').data_repository()
  csvfile=open(usefilename,'r')
  for alllines in csvfile:
    qitem=alllines[alllines.find('Q'):alllines.find(',')]
    if (len(qitem)>0):
      try:
        wditem=pywikibot.ItemPage(repo,qitem)
        wditem.get(get_redirect=True)
      except:
        pass
      yield wditem

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

count=0
repo=pywikibot.Site('wikidata','wikidata').data_repository()
#for item in wd_from_file('query.csv'):
for item in wd_sparql_query('SELECT DISTINCT ?item WHERE { VALUES ?description { \'kategorisida\'@sv \'wikipedia-kategori\'@sv \'wikipedia kategori\'@sv \'kategori\'@sv \'\'@sv } . ?item wdt:P31 wd:Q4167836; schema:description ?description . }'):
  if ('sv' in item.descriptions):
     if (item.descriptions['sv'].lower() in ['kategorisida','wikipedia-kategori','','wikipedia kategori','kategori','']): 
        print(item.title())
        count+=1
        wddata={}
        try:
          wddata.update({'descriptions':{'sv':'Wikimedia-kategori'}})
          item.editEntity(wddata,summary='https://www.wikidata.org/w/index.php?title=Wikidata:Bot_requests&oldid=1007509180 Wikimedia-kategori')
        except:
          pass
        #print(1/0)

print(f'Done: {count} found')