"as" vague property migrator

Okay, going into new territoriy here.

The point of this tool is to try to migrate instances of Q1 P2 Q3 / P4 Q5 for given P2 and P4, and replace P4 with another P6.

import pywikibot
from pywikibot import pagegenerators as pg

wikidata_site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

with open('lead_actor.rq', 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

for item in generator:
    print(item)
Retrieving 16 pages from wikidata:wikidata.
[[wikidata:Q10571896]]
[[wikidata:Q27536704]]
[[wikidata:Q28531170]]
[[wikidata:Q27536694]]
[[wikidata:Q180214]]
[[wikidata:Q1765286]]
[[wikidata:Q747919]]
[[wikidata:Q28146833]]
[[wikidata:Q1768770]]
[[wikidata:Q1140439]]
[[wikidata:Q7024401]]
[[wikidata:Q7058806]]
[[wikidata:Q31270349]]
[[wikidata:Q79784]]
[[wikidata:Q15982347]]
[[wikidata:Q27964319]]

This count is different from the web query service because the generator counts unique items, whereas the web service counts unique statements.

#operate on the most recent one for testing
item_dict = item.get()
print(item_dict.keys())
dict_keys(['aliases', 'labels', 'descriptions', 'claims', 'sitelinks'])
print(item_dict['claims'])
{'P31': [<pywikibot.page.Claim object at 0x7f6a206ad1d0>], 'P345': [<pywikibot.page.Claim object at 0x7f6a206ad278>], 'P57': [<pywikibot.page.Claim object at 0x7f6a206ad390>], 'P162': [<pywikibot.page.Claim object at 0x7f6a206ad7b8>], 'P1040': [<pywikibot.page.Claim object at 0x7f6a206b4160>], 'P495': [<pywikibot.page.Claim object at 0x7f6a206b4588>], 'P58': [<pywikibot.page.Claim object at 0x7f6a206b4908>], 'P161': [<pywikibot.page.Claim object at 0x7f6a206b4b38>, <pywikibot.page.Claim object at 0x7f6a2063c208>], 'P1476': [<pywikibot.page.Claim object at 0x7f6a2063c588>], 'P2013': [<pywikibot.page.Claim object at 0x7f6a2063c860>], 'P344': [<pywikibot.page.Claim object at 0x7f6a2063c908>], 'P577': [<pywikibot.page.Claim object at 0x7f6a2063cd30>], 'P2603': [<pywikibot.page.Claim object at 0x7f6a2063cd68>], 'P2529': [<pywikibot.page.Claim object at 0x7f6a20643278>], 'P480': [<pywikibot.page.Claim object at 0x7f6a206434e0>], 'P3302': [<pywikibot.page.Claim object at 0x7f6a20643630>], 'P364': [<pywikibot.page.Claim object at 0x7f6a20643780>], 'P3995': [<pywikibot.page.Claim object at 0x7f6a20643a20>], 'P2671': [<pywikibot.page.Claim object at 0x7f6a20643b00>], 'P1889': [<pywikibot.page.Claim object at 0x7f6a20643b70>, <pywikibot.page.Claim object at 0x7f6a20643eb8>], 'P86': [<pywikibot.page.Claim object at 0x7f6a20643f98>], 'P2047': [<pywikibot.page.Claim object at 0x7f6a2064b0b8>], 'P725': [<pywikibot.page.Claim object at 0x7f6a2064b2e8>], 'P136': [<pywikibot.page.Claim object at 0x7f6a2064b588>], 'P1651': [<pywikibot.page.Claim object at 0x7f6a2064b8d0>]}
print(item_dict['claims']['P161'])
[<pywikibot.page.Claim object at 0x7f6a206b4b38>, <pywikibot.page.Claim object at 0x7f6a2063c208>]
dir(item_dict['claims']['P161'][1])
['SNAK_TYPES',
 'TARGET_CONVERTER',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_formatDataValue',
 '_formatValue',
 '_type',
 'addQualifier',
 'addSource',
 'addSources',
 'changeRank',
 'changeSnakType',
 'changeTarget',
 'fromJSON',
 'getID',
 'getRank',
 'getSnakType',
 'getSources',
 'getTarget',
 'getType',
 'has_qualifier',
 'hash',
 'id',
 'isQualifier',
 'isReference',
 'on_item',
 'qualifierFromJSON',
 'qualifiers',
 'rank',
 'referenceFromJSON',
 'removeQualifier',
 'removeQualifiers',
 'removeSource',
 'removeSources',
 'repo',
 'setRank',
 'setSnakType',
 'setTarget',
 'snak',
 'snaktype',
 'sources',
 'target',
 'target_equals',
 'toJSON',
 'type',
 'types',
 'value_types']
for claim_object in item_dict['claims']['P161']:
    print(claim_object)
    if 'P794' in claim_object.qualifiers:
        for qualifier_object in claim_object.qualifiers['P794']:
            qualifier_target = qualifier_object.getTarget()
            print(qualifier_target)
<pywikibot.page.Claim object at 0x7f6a206b4b38>
[[wikidata:Q1765879]]
<pywikibot.page.Claim object at 0x7f6a2063c208>
[[wikidata:Q14786283]]
for claim_object in item_dict['claims']['P161']:
    print(claim_object)
    if 'P794' in claim_object.qualifiers:
        for qualifier_object in claim_object.qualifiers['P794']:
            qualifier_target = qualifier_object.getTarget()
            print(qualifier_target)
<pywikibot.page.Claim object at 0x7f6a206b4b38>
[[wikidata:Q1765879]]
<pywikibot.page.Claim object at 0x7f6a2063c208>
[[wikidata:Q14786283]]
dir(qualifier_object)
['SNAK_TYPES',
 'TARGET_CONVERTER',
 '__class__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__le__',
 '__lt__',
 '__module__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 '__weakref__',
 '_formatDataValue',
 '_formatValue',
 '_type',
 'addQualifier',
 'addSource',
 'addSources',
 'changeRank',
 'changeSnakType',
 'changeTarget',
 'fromJSON',
 'getID',
 'getRank',
 'getSnakType',
 'getSources',
 'getTarget',
 'getType',
 'has_qualifier',
 'hash',
 'id',
 'isQualifier',
 'isReference',
 'on_item',
 'qualifierFromJSON',
 'qualifiers',
 'rank',
 'referenceFromJSON',
 'removeQualifier',
 'removeQualifiers',
 'removeSource',
 'removeSources',
 'repo',
 'setRank',
 'setSnakType',
 'setTarget',
 'snak',
 'snaktype',
 'sources',
 'target',
 'target_equals',
 'toJSON',
 'type',
 'types',
 'value_types']
print(qualifier_object.toJSON())
print(qualifier_object)
{'snaktype': 'value', 'property': 'P794', 'datatype': 'wikibase-item', 'datavalue': {'value': {'entity-type': 'item', 'numeric-id': 14786283}, 'type': 'wikibase-entityid'}, 'hash': 'fa12382f100fbaac37a4c878674c421d2f76f94d'}
<pywikibot.page.Claim object at 0x7f6a2063c5c0>
#make sure I know which item I'm testing on...
item.getID()
'Q27964319'
#okay put it together and do it!

#operate on the most recent one for testing
print('Now working on ', item.getID())
item_dict = item.get()

for claim_object in item_dict['claims']['P161']:
    claim_target = claim_object.getTarget()
    if 'P794' in claim_object.qualifiers:
        for qualifier_object in claim_object.qualifiers['P794']:
            qualifier_target = qualifier_object.getTarget()
            
            print('P161 ', claim_target, ' P794 ', qualifier_target)
            
            qualifier_dict = qualifier_object.toJSON()
            qualifier_dict['property'] =  'P2868' #set up the qualifier change
            
            print('Changing to P2868')
            
            new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
            claim_object.addQualifier(new_qualifier_object)
            #claim_object.removeQualifier(qualifier_object)
Now working on  Q27964319
P161  [[wikidata:Q27656034]]  P794  [[wikidata:Q1765879]]
Changing to P2868
WARNING: API warning (wbsetqualifier) of unknown format: {'messages': [{'name': 'wikibase-conflict-patched', 'parameters': [], 'html': {'*': 'Your edit was patched into the latest version.'}, 'type': 'warning'}]}
P161  [[wikidata:Q30528655]]  P794  [[wikidata:Q14786283]]
Changing to P2868

That seems to have worked for one item: Assumption. (diff)

But it replaced every P161 / P794 with P161 / P2868!

Next step:

  • Need to check that it's P794 -> Q1765879
  • Iterate over many articles with confirmations on whether to continue or skip
qualifier_target.get()['labels']['en']
'bit part'
qualifier_object.getTarget().getID()
'Q14786283'
import pywikibot
from pywikibot import pagegenerators as pg

wikidata_site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

with open('lead_actor.rq', 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

break_flag = 0

for item in generator:
    #operate on the most recent one for testing
    item_dict = item.get()
    item_label = ''
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
            
    print('Now working on ', item.getID(), ' ', item_label)
    

    for claim_object in item_dict['claims']['P161']:
        claim_target = claim_object.getTarget()
        claim_target_dict = claim_target.get()
        claim_target_label = ''
        if 'labels' in claim_target_dict:
            if 'en' in claim_target_dict['labels']:
                claim_target_label = claim_target_dict['labels']['en']
        
        if 'P794' in claim_object.qualifiers:
            for qualifier_object in claim_object.qualifiers['P794']:
                qualifier_target = qualifier_object.getTarget()
                if qualifier_target.getID() == 'Q1765879':
                    print('P161 ', claim_target, '(', claim_target_label, ')', ' P794 ', qualifier_target, ' change?')
                
                    acceptable_prompt_set = {'y', 'yes', 'n', 'no', 'break'}
                    promptbox = ''
                    while (promptbox not in acceptable_prompt_set):
                        promptbox = input()

                    if promptbox == 'y' or promptbox == 'yes':
                        qualifier_dict = qualifier_object.toJSON()
                        qualifier_dict['property'] =  'P2868' #set up the qualifier change
                        print('Changing to P2868')
                        new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
                        claim_object.addQualifier(new_qualifier_object)

                    elif promptbox == 'n' or promptbox == 'no':
                        print('Skipped')
                    elif promptbox == 'break':
                        break_flag = 1
                        break
                    else:
                        print('Error - Deryck made a mistake')

        if break_flag == 1:
            break
    if break_flag == 1:
        break

print('All done, thanks for using!')
Retrieving 14 pages from wikidata:wikidata.
Now working on  Q28531170   Friend of the World
P161  [[wikidata:Q28531164]] ( Nick Young )  P794  [[wikidata:Q1765879]]  change?
y
Changing to P2868
P161  [[wikidata:Q30070897]] ( Alexandra Slade )  P794  [[wikidata:Q1765879]]  change?
y
Changing to P2868
Now working on  Q27964319   Assumption
Now working on  Q1765286   Operation Thunderbolt
P161  [[wikidata:Q2091045]] ( Yehoram Gaon )  P794  [[wikidata:Q1765879]]  change?
break
All done, thanks for using!

Abstraction

Now it works, give it one degree of abstraction:

  • If (any item) [property] (any item) [qualifier property] (any item)
  • Offer to change [qualifier property] to [new qualifier property]
#input vars
main_property = 'P161'
qualifier_property = 'P794'
new_qualifier_property = 'P2868'
 
def getLabelFromObject(WDObject):
    item_dict = WDObject.get()
    item_label = False
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
    return item_label

def getLabelFromWDID(ID): #works for properties only. need separate function for items. why why why
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    item = pywikibot.PropertyPage(repo, ID)
    return getLabelFromObject(item)

main_property_label = getLabelFromWDID(main_property)
qualifier_property_label = getLabelFromWDID(qualifier_property)
new_qualifier_property_label = getLabelFromWDID(new_qualifier_property)

print(main_property_label)
print(qualifier_property_label)
print(new_qualifier_property_label)
cast member
as
subject has role
#input vars
main_property = 'P161'
qualifier_property = 'P794'
new_qualifier_property = 'P2868'
 
def getLabelFromObject(WDObject):
    item_dict = WDObject.get()
    item_label = False
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
    label = item_label
    if (label):
        return label
    else:
        return WDObject.getID()

def getLabelFromWDID(ID): #works for properties only. need separate function for items. why why why
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    item = pywikibot.PropertyPage(repo, ID)
    return getLabelFromObject(item)

main_property_label = getLabelFromWDID(main_property)
qualifier_property_label = getLabelFromWDID(qualifier_property)
new_qualifier_property_label = getLabelFromWDID(new_qualifier_property)

#start of actual script
import pywikibot
from pywikibot import pagegenerators as pg

wikidata_site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

with open('actor_roles.rq', 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

break_flag = 0

for item in generator:
    #operate on the most recent one for testing
    item_dict = item.get()
    item_label = getLabelFromObject(item)
            
    print('Now working on ', item.getID(), ' ', item_label)
    

    for claim_object in item_dict['claims'][main_property]:
        claim_target = claim_object.getTarget()
        claim_target_label = getLabelFromObject(claim_target)
        
        if qualifier_property in claim_object.qualifiers:
            for qualifier_object in claim_object.qualifiers[qualifier_property]:
                qualifier_target = qualifier_object.getTarget()
                qualifier_target_label = getLabelFromObject(qualifier_target)
                print(item_label, main_property_label, claim_target_label, 
                      qualifier_property_label, qualifier_target_label, 
                      'change to', new_qualifier_property_label, '?')

                acceptable_prompt_set = {'y', 'yes', 'n', 'no', 'break'}
                promptbox = ''
                while (promptbox not in acceptable_prompt_set):
                    promptbox = input()

                if promptbox == 'y' or promptbox == 'yes':
                    qualifier_dict = qualifier_object.toJSON()
                    qualifier_dict['property'] =  new_qualifier_property #set up the qualifier change
                    print('Changing to', new_qualifier_property_label)
                    new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
                    claim_object.addQualifier(new_qualifier_object)

                elif promptbox == 'n' or promptbox == 'no':
                    print('Skipped')
                elif promptbox == 'break':
                    break_flag = 1
                    break
                else:
                    print('Error - Deryck made a mistake')

        if break_flag == 1:
            break
    if break_flag == 1:
        break

print('All done, thanks for using!')
Retrieving 15 pages from wikidata:wikidata.
Now working on  Q28531170   Friend of the World
Friend of the World cast member Michael C. Burgess as supporting actor change to subject has role ?
y
Changing to subject has role
Friend of the World cast member Kathryn Schott as supporting actor change to subject has role ?
y
Changing to subject has role
Friend of the World cast member Luke Pensabene as bit part change to subject has role ?
n
Skipped
Friend of the World cast member Brian Patrick Butler as bit part change to subject has role ?
n
Skipped
Friend of the World cast member Daniel N. Butler as bit part change to subject has role ?
n
Skipped
Friend of the World cast member Kevin Smith as bit part change to subject has role ?
n
Skipped
Now working on  Q27536704   South of 8
South of 8 cast member Raye Richards as supporting actor change to subject has role ?
y
Changing to subject has role
South of 8 cast member Luke Pensabene as supporting actor change to subject has role ?
y
Changing to subject has role
South of 8 cast member Shane P. Allen as supporting actor change to subject has role ?
y
Changing to subject has role
South of 8 cast member Robert F. Nixon as bit part change to subject has role ?
n
Skipped
South of 8 cast member Daniel N. Butler as bit part change to subject has role ?
n
Skipped
South of 8 cast member Anthony Leone as bit part change to subject has role ?
n
Skipped
South of 8 cast member Michael C. Burgess as supporting actor change to subject has role ?
y
Changing to subject has role
South of 8 cast member Kerry Brent Hower as bit part change to subject has role ?
n
Skipped
South of 8 cast member Alexander Robinson as supporting actor change to subject has role ?
y
Changing to subject has role
South of 8 cast member Lolly Boroff as bit part change to subject has role ?
n
Skipped
South of 8 cast member Mike Egbert as bit part change to subject has role ?
n
Skipped
South of 8 cast member Cat Forrest as bit part change to subject has role ?
n
Skipped
South of 8 cast member D. Woods as extra change to subject has role ?
y
Changing to subject has role
South of 8 cast member Mark Anthony Cox as bit part change to subject has role ?
n
Skipped
South of 8 cast member Ryan Binse as bit part change to subject has role ?
n
Skipped
South of 8 cast member Liliana Moreno as extra change to subject has role ?
y
Changing to subject has role
South of 8 cast member Yvette Angulo as bit part change to subject has role ?
n
Skipped
South of 8 cast member Taylor Koster as bit part change to subject has role ?
n
Skipped
South of 8 cast member Tony Olmos as bit part change to subject has role ?
n
Skipped
South of 8 cast member Kelly Potts as bit part change to subject has role ?
n
Skipped
South of 8 cast member Chris Yarrow as extra change to subject has role ?
y
Changing to subject has role
South of 8 cast member Alejandra Yáñez as extra change to subject has role ?
y
Changing to subject has role
South of 8 cast member Belle Santillan as bit part change to subject has role ?
n
Skipped
South of 8 cast member Tony Gorodeckas as bit part change to subject has role ?
n
Skipped
Now working on  Q1674804   Carry On Screaming!
Carry On Screaming! cast member Gerald Thomas as voice actor change to subject has role ?
y
Changing to subject has role
Now working on  Q1765286   Operation Thunderbolt
Operation Thunderbolt cast member Yehoram Gaon as leading actor change to subject has role ?
y
Changing to subject has role
Operation Thunderbolt cast member Gila Almagor as leading actor change to subject has role ?
y
Changing to subject has role
Operation Thunderbolt cast member Assi Dayan as leading actor change to subject has role ?
y
Changing to subject has role
Operation Thunderbolt cast member Klaus Kinski as leading actor change to subject has role ?
y
Changing to subject has role
Operation Thunderbolt cast member Uzi Cohen as supporting actor change to subject has role ?
y
Changing to subject has role
Now working on  Q180214   Black Swan
Black Swan cast member Natalie Portman as leading actor change to subject has role ?
y
Changing to subject has role
Black Swan cast member Vincent Cassel as leading actor change to subject has role ?
y
Changing to subject has role
Black Swan cast member Mila Kunis as leading actor change to subject has role ?
y
Changing to subject has role
Now working on  Q747919   Asterix & Obelix: On Her Majesty's Service
Asterix & Obelix: On Her Majesty's Service cast member Gérard Depardieu as leading actor change to subject has role ?
y
Changing to subject has role
Asterix & Obelix: On Her Majesty's Service cast member Fabrice Luchini as leading actor change to subject has role ?
y
Changing to subject has role
Asterix & Obelix: On Her Majesty's Service cast member Catherine Deneuve as leading actor change to subject has role ?
y
Changing to subject has role
Now working on  Q28146833   Severus Snape and the Marauders
Severus Snape and the Marauders cast member Mick Ignis as leading actor change to subject has role ?
y
Changing to subject has role
Severus Snape and the Marauders cast member Garrett Schweighauser as leading actor change to subject has role ?
y
Changing to subject has role
Severus Snape and the Marauders cast member Kevin Allen as leading actor change to subject has role ?
y
Changing to subject has role
Severus Snape and the Marauders cast member Paul Stanko as leading actor change to subject has role ?
y
Changing to subject has role
Severus Snape and the Marauders cast member Zachary David as supporting actor change to subject has role ?
y
Changing to subject has role
Severus Snape and the Marauders cast member Dani Jae as supporting actor change to subject has role ?
y
Changing to subject has role
Severus Snape and the Marauders cast member Clayton Nemrow as bit part change to subject has role ?
n
Skipped
Now working on  Q1768770   Hamsun
Hamsun cast member Max von Sydow as leading actor change to subject has role ?
y
Changing to subject has role
Hamsun cast member Ghita Nørby as leading actor change to subject has role ?
y
Changing to subject has role
Hamsun cast member Anette Hoff as leading actor change to subject has role ?
y
Changing to subject has role
Hamsun cast member Sverre Anker Ousdal as leading actor change to subject has role ?
y
Changing to subject has role
Hamsun cast member Eindride Eidsvold as leading actor change to subject has role ?
y
Changing to subject has role
Hamsun cast member Gard B. Eidsvold as leading actor change to subject has role ?
y
Changing to subject has role
Hamsun cast member Åsa Söderling as leading actor change to subject has role ?
y
Changing to subject has role
Now working on  Q1140439   Finding Forrester
Finding Forrester cast member Sean Connery as leading actor change to subject has role ?
y
Changing to subject has role
Finding Forrester cast member Rob Brown as leading actor change to subject has role ?
y
Changing to subject has role
Finding Forrester cast member F. Murray Abraham as supporting actor change to subject has role ?
y
Changing to subject has role
Finding Forrester cast member Anna Paquin as supporting actor change to subject has role ?
y
Changing to subject has role
Finding Forrester cast member Busta Rhymes as supporting actor change to subject has role ?
y
Changing to subject has role
Finding Forrester cast member April Grace as supporting actor change to subject has role ?
y
Changing to subject has role
Finding Forrester cast member Michael Pitt as supporting actor change to subject has role ?
y
Changing to subject has role
Finding Forrester cast member Matt Damon as cameo appearance change to subject has role ?
n
Skipped
Now working on  Q7058806   Kathmandu (TV series)
Kathmandu (TV series) cast member Michael Moshonov as leading actor change to subject has role ?
y
Changing to subject has role
Kathmandu (TV series) cast member Nitzan Levratovski as leading actor change to subject has role ?
y
Changing to subject has role
Kathmandu (TV series) cast member Liron Levo as leading actor change to subject has role ?
y
Changing to subject has role
Kathmandu (TV series) cast member Doron Tavori as supporting actor change to subject has role ?
y
Changing to subject has role
Kathmandu (TV series) cast member Gal Gadot as leading actor change to subject has role ?
y
Changing to subject has role
Kathmandu (TV series) cast member Shimrit Lustig as supporting actor change to subject has role ?
y
Changing to subject has role
Kathmandu (TV series) cast member Tzahi Grad as supporting actor change to subject has role ?
y
Changing to subject has role
Kathmandu (TV series) cast member Q6782597 as supporting actor change to subject has role ?
y
Changing to subject has role
Now working on  Q7024401   Q7024401
Q7024401 cast member Ruth Gonzales as leading actor change to subject has role ?
y
Changing to subject has role
Now working on  Q31270349   Con Boys
Con Boys cast member Jon Maxwell as leading actor change to subject has role ?
break
All done, thanks for using!

This tool works... but oh wait, I gave everything the wrong qualifier!!!! It should be "object has role", not "subject has role"...

But the tool has been built so I can just go back and fix what I've done with the same tool!

#input vars
main_property = 'P161'
qualifier_property = 'P2868'
new_qualifier_property = 'P3831'
 
def getLabelFromObject(WDObject):
    item_dict = WDObject.get()
    item_label = False
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
    label = item_label
    if (label):
        return label
    else:
        return WDObject.getID()

def getLabelFromWDID(ID): #works for properties only. need separate function for items. why why why
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    item = pywikibot.PropertyPage(repo, ID)
    return getLabelFromObject(item)

main_property_label = getLabelFromWDID(main_property)
qualifier_property_label = getLabelFromWDID(qualifier_property)
new_qualifier_property_label = getLabelFromWDID(new_qualifier_property)

#start of actual script
import pywikibot
from pywikibot import pagegenerators as pg

wikidata_site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

with open('actor_roles.rq', 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

break_flag = 0

for item in generator:
    #operate on the most recent one for testing
    item_dict = item.get()
    item_label = getLabelFromObject(item)
            
    print('Now working on ', item.getID(), ' ', item_label)
    

    for claim_object in item_dict['claims'][main_property]:
        claim_target = claim_object.getTarget()
        claim_target_label = getLabelFromObject(claim_target)
        
        if qualifier_property in claim_object.qualifiers:
            for qualifier_object in claim_object.qualifiers[qualifier_property]:
                qualifier_target = qualifier_object.getTarget()
                qualifier_target_label = getLabelFromObject(qualifier_target)
                print(item_label, main_property_label, claim_target_label, 
                      qualifier_property_label, qualifier_target_label, 
                      'change to', new_qualifier_property_label, '?')

                acceptable_prompt_set = {'y', 'yes', 'n', 'no', 'break'}
                promptbox = ''
                while (promptbox not in acceptable_prompt_set):
                    promptbox = input()

                if promptbox == 'y' or promptbox == 'yes':
                    qualifier_dict = qualifier_object.toJSON()
                    qualifier_dict['property'] =  new_qualifier_property #set up the qualifier change
                    print('Changing to', new_qualifier_property_label)
                    new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
                    claim_object.addQualifier(new_qualifier_object)

                elif promptbox == 'n' or promptbox == 'no':
                    print('Skipped')
                elif promptbox == 'break':
                    break_flag = 1
                    break
                else:
                    print('Error - Deryck made a mistake')

        if break_flag == 1:
            break
    if break_flag == 1:
        break

print('All done, thanks for using!')
Retrieving 13 pages from wikidata:wikidata.
Now working on  Q28531170   Friend of the World
Friend of the World cast member Nick Young subject has role leading actor change to object has role ?
y
Changing to object has role
Friend of the World cast member Alexandra Slade subject has role leading actor change to object has role ?
y
Changing to object has role
Friend of the World cast member Michael C. Burgess subject has role supporting actor change to object has role ?
y
Changing to object has role
Friend of the World cast member Kathryn Schott subject has role supporting actor change to object has role ?
y
Changing to object has role
Now working on  Q27536704   South of 8
South of 8 cast member Brian Patrick Butler subject has role leading actor change to object has role ?
y
Changing to object has role
South of 8 cast member George Jac subject has role leading actor change to object has role ?
y
Changing to object has role
South of 8 cast member Jennifer Paredes subject has role leading actor change to object has role ?
y
Changing to object has role
South of 8 cast member Kathryn Schott subject has role leading actor change to object has role ?
y
Changing to object has role
South of 8 cast member Raye Richards subject has role supporting actor change to object has role ?
y
Changing to object has role
South of 8 cast member Luke Pensabene subject has role supporting actor change to object has role ?
y
Changing to object has role
South of 8 cast member Shane P. Allen subject has role supporting actor change to object has role ?
y
Changing to object has role
South of 8 cast member Michael C. Burgess subject has role supporting actor change to object has role ?
y
Changing to object has role
South of 8 cast member Alexander Robinson subject has role supporting actor change to object has role ?
y
Changing to object has role
South of 8 cast member D. Woods subject has role extra change to object has role ?
y
Changing to object has role
South of 8 cast member Liliana Moreno subject has role extra change to object has role ?
y
Changing to object has role
South of 8 cast member Chris Yarrow subject has role extra change to object has role ?
y
Changing to object has role
South of 8 cast member Alejandra Yáñez subject has role extra change to object has role ?
y
Changing to object has role
Now working on  Q10571896   Q10571896
Q10571896 cast member Eva Röse subject has role leading actor change to object has role ?
y
Changing to object has role
Q10571896 cast member Reuben Sallmander subject has role leading actor change to object has role ?
y
Changing to object has role
Q10571896 cast member Marika Lagercrantz subject has role leading actor change to object has role ?
y
Changing to object has role
Q10571896 cast member Benny Haag subject has role leading actor change to object has role ?
y
Changing to object has role
Q10571896 cast member Bibi Andersson subject has role leading actor change to object has role ?
y
Changing to object has role
Q10571896 cast member Hans Alfredson subject has role leading actor change to object has role ?
y
Changing to object has role
Now working on  Q27964319   Assumption
Assumption cast member Brian Patrick Butler subject has role leading actor change to object has role ?
y
Changing to object has role
Now working on  Q1765286   Operation Thunderbolt
Operation Thunderbolt cast member Yehoram Gaon subject has role leading actor change to object has role ?
y
Changing to object has role
Operation Thunderbolt cast member Gila Almagor subject has role leading actor change to object has role ?
y
Changing to object has role
Operation Thunderbolt cast member Assi Dayan subject has role leading actor change to object has role ?
y
Changing to object has role
Operation Thunderbolt cast member Klaus Kinski subject has role leading actor change to object has role ?
y
Changing to object has role
Operation Thunderbolt cast member Uzi Cohen subject has role supporting actor change to object has role ?
y
Changing to object has role
Now working on  Q180214   Black Swan
Black Swan cast member Natalie Portman subject has role leading actor change to object has role ?
y
Changing to object has role
Black Swan cast member Vincent Cassel subject has role leading actor change to object has role ?
y
Changing to object has role
Black Swan cast member Mila Kunis subject has role leading actor change to object has role ?
y
Changing to object has role
Now working on  Q747919   Asterix & Obelix: On Her Majesty's Service
Asterix & Obelix: On Her Majesty's Service cast member Gérard Depardieu subject has role leading actor change to object has role ?
y
Changing to object has role
Asterix & Obelix: On Her Majesty's Service cast member Fabrice Luchini subject has role leading actor change to object has role ?
y
Changing to object has role
Asterix & Obelix: On Her Majesty's Service cast member Catherine Deneuve subject has role leading actor change to object has role ?
y
Changing to object has role
Now working on  Q28146833   Severus Snape and the Marauders
Severus Snape and the Marauders cast member Mick Ignis subject has role leading actor change to object has role ?
y
Changing to object has role
Severus Snape and the Marauders cast member Garrett Schweighauser subject has role leading actor change to object has role ?
y
Changing to object has role
Severus Snape and the Marauders cast member Kevin Allen subject has role leading actor change to object has role ?
y
Changing to object has role
Severus Snape and the Marauders cast member Paul Stanko subject has role leading actor change to object has role ?
y
Changing to object has role
Severus Snape and the Marauders cast member Zachary David subject has role supporting actor change to object has role ?
y
Changing to object has role
Severus Snape and the Marauders cast member Dani Jae subject has role supporting actor change to object has role ?
y
Changing to object has role
Now working on  Q1768770   Hamsun
Hamsun cast member Max von Sydow subject has role leading actor change to object has role ?
y
Changing to object has role
Hamsun cast member Ghita Nørby subject has role leading actor change to object has role ?
y
Changing to object has role
Hamsun cast member Anette Hoff subject has role leading actor change to object has role ?
y
Changing to object has role
Hamsun cast member Sverre Anker Ousdal subject has role leading actor change to object has role ?
y
Changing to object has role
Hamsun cast member Eindride Eidsvold subject has role leading actor change to object has role ?
y
Changing to object has role
Hamsun cast member Gard B. Eidsvold subject has role leading actor change to object has role ?
y
Changing to object has role
Hamsun cast member Åsa Söderling subject has role leading actor change to object has role ?
y
Changing to object has role
Now working on  Q1140439   Finding Forrester
Finding Forrester cast member Sean Connery subject has role leading actor change to object has role ?
y
Changing to object has role
Finding Forrester cast member Rob Brown subject has role leading actor change to object has role ?
y
Changing to object has role
Finding Forrester cast member F. Murray Abraham subject has role supporting actor change to object has role ?
y
Changing to object has role
Finding Forrester cast member Anna Paquin subject has role supporting actor change to object has role ?
y
Changing to object has role
Finding Forrester cast member Busta Rhymes subject has role supporting actor change to object has role ?
y
Changing to object has role
Finding Forrester cast member April Grace subject has role supporting actor change to object has role ?
y
Changing to object has role
Finding Forrester cast member Michael Pitt subject has role supporting actor change to object has role ?
y
Changing to object has role
Now working on  Q7024401   Q7024401
Q7024401 cast member Ruth Gonzales subject has role leading actor change to object has role ?
y
Changing to object has role
Now working on  Q7058806   Kathmandu (TV series)
Kathmandu (TV series) cast member Michael Moshonov subject has role leading actor change to object has role ?
y
Changing to object has role
Kathmandu (TV series) cast member Nitzan Levratovski subject has role leading actor change to object has role ?
y
Changing to object has role
Kathmandu (TV series) cast member Liron Levo subject has role leading actor change to object has role ?
y
Changing to object has role
Kathmandu (TV series) cast member Doron Tavori subject has role supporting actor change to object has role ?
y
Changing to object has role
Kathmandu (TV series) cast member Gal Gadot subject has role leading actor change to object has role ?
y
Changing to object has role
Kathmandu (TV series) cast member Shimrit Lustig subject has role supporting actor change to object has role ?
y
Changing to object has role
Kathmandu (TV series) cast member Tzahi Grad subject has role supporting actor change to object has role ?
y
Changing to object has role
Kathmandu (TV series) cast member Q6782597 subject has role supporting actor change to object has role ?
y
Changing to object has role
Now working on  Q1674804   Carry On Screaming!
Carry On Screaming! cast member Gerald Thomas subject has role voice actor change to object has role ?
y
Changing to object has role
All done, thanks for using!
#input vars
main_property = 'P161'
qualifier_property = 'P794'
new_qualifier_property = 'P3831'
 
def getLabelFromObject(WDObject):
    item_dict = WDObject.get()
    item_label = False
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
    label = item_label
    if (label):
        return label
    else:
        return WDObject.getID()

def getLabelFromWDID(ID): #works for properties only. need separate function for items. why why why
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    item = pywikibot.PropertyPage(repo, ID)
    return getLabelFromObject(item)

main_property_label = getLabelFromWDID(main_property)
qualifier_property_label = getLabelFromWDID(qualifier_property)
new_qualifier_property_label = getLabelFromWDID(new_qualifier_property)

#start of actual script
import pywikibot
from pywikibot import pagegenerators as pg

wikidata_site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

with open('actor_roles.rq', 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

break_flag = 0

for item in generator:
    #operate on the most recent one for testing
    item_dict = item.get()
    item_label = getLabelFromObject(item)
            
    print('Now working on ', item.getID(), ' ', item_label)
    

    for claim_object in item_dict['claims'][main_property]:
        claim_target = claim_object.getTarget()
        claim_target_label = getLabelFromObject(claim_target)
        
        if qualifier_property in claim_object.qualifiers:
            for qualifier_object in claim_object.qualifiers[qualifier_property]:
                qualifier_target = qualifier_object.getTarget()
                qualifier_target_label = getLabelFromObject(qualifier_target)
                print(item_label, main_property_label, claim_target_label, 
                      qualifier_property_label, qualifier_target_label, 
                      'change to', new_qualifier_property_label, '?')

                acceptable_prompt_set = {'y', 'yes', 'n', 'no', 'break'}
                promptbox = ''
                while (promptbox not in acceptable_prompt_set):
                    promptbox = input()

                if promptbox == 'y' or promptbox == 'yes':
                    qualifier_dict = qualifier_object.toJSON()
                    qualifier_dict['property'] =  new_qualifier_property #set up the qualifier change
                    print('Changing to', new_qualifier_property_label)
                    new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
                    claim_object.addQualifier(new_qualifier_object)

                elif promptbox == 'n' or promptbox == 'no':
                    print('Skipped')
                    
                elif promptbox == 'break':
                    break_flag = 1
                    break
                else:
                    print('Error - Deryck made a mistake')

        if break_flag == 1:
            break
    if break_flag == 1:
        break

print('All done, thanks for using!')
Retrieving 4 pages from wikidata:wikidata.
Now working on  Q79784   Friends
Friends cast member Jennifer Aniston as leading actor change to object has role ?
y
Changing to object has role
Friends cast member Courteney Cox as leading actor change to object has role ?
y
Changing to object has role
Friends cast member Lisa Kudrow as leading actor change to object has role ?
y
Changing to object has role
Friends cast member Matt LeBlanc as leading actor change to object has role ?
y
Changing to object has role
Friends cast member Matthew Perry as leading actor change to object has role ?
y
Changing to object has role
Friends cast member David Schwimmer as leading actor change to object has role ?
y
Changing to object has role
Friends cast member James Michael Tyler as supporting actor change to object has role ?
y
Changing to object has role
Friends cast member Elliott Gould as guest appearance change to object has role ?
y
Changing to object has role
Friends cast member Christina Pickles as guest appearance change to object has role ?
y
Changing to object has role
Friends cast member Maggie Wheeler as guest appearance change to object has role ?
y
Changing to object has role
Now working on  Q15982347   Undateable
Undateable cast member Brent Morin as leading actor change to object has role ?
y
Changing to object has role
Undateable cast member Chris D'Elia as leading actor change to object has role ?
y
Changing to object has role
Now working on  Q27536694   The Phantom Hour
The Phantom Hour cast member Luke Pensabene as leading actor change to object has role ?
y
Changing to object has role
The Phantom Hour cast member Raye Richards as leading actor change to object has role ?
y
Changing to object has role
The Phantom Hour cast member Morgan K. Reynolds as bit part change to object has role ?
n
Skipped
The Phantom Hour cast member Dakota Ringer as bit part change to object has role ?
n
Skipped
The Phantom Hour cast member Brian Patrick Butler as supporting actor change to object has role ?
y
Changing to object has role
The Phantom Hour cast member Connor Riley Sullivan as leading actor change to object has role ?
y
Changing to object has role
Now working on  Q31270349   Con Boys
Con Boys cast member Jon Maxwell as leading actor change to object has role ?
y
Changing to object has role
Con Boys cast member Nick Young as supporting actor change to object has role ?
y
Changing to object has role
Con Boys cast member Yvette Angulo as supporting actor change to object has role ?
y
Changing to object has role
Con Boys cast member Gage Magosin as leading actor change to object has role ?
y
Changing to object has role
All done, thanks for using!

Put it all together into a ready-to-go script

#input vars
main_property = 'P161'
qualifier_property = 'P794'
new_qualifier_property = 'P453'
query_filename = 'qualifier_migrate.rq'
 
def getLabelFromObject(WDObject):
    item_dict = WDObject.get()
    item_label = False
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
    label = item_label
    if (label):
        return label
    else:
        return WDObject.getID()

def getLabelFromWDID(ID): #works for properties only. need separate function for items. why why why
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    item = pywikibot.PropertyPage(repo, ID)
    return getLabelFromObject(item)

main_property_label = getLabelFromWDID(main_property)
qualifier_property_label = getLabelFromWDID(qualifier_property)
new_qualifier_property_label = getLabelFromWDID(new_qualifier_property)

#start of actual script
import pywikibot
from pywikibot import pagegenerators as pg

wikidata_site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

with open(query_filename, 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

break_flag = 0

for item in generator:
    #operate on the most recent one for testing
    item_dict = item.get()
    item_label = getLabelFromObject(item)
            
    print('Now working on ', item.getID(), ' ', item_label)
    

    for claim_object in item_dict['claims'][main_property]:
        claim_target = claim_object.getTarget()
        claim_target_label = getLabelFromObject(claim_target)
        
        if qualifier_property in claim_object.qualifiers:
            for qualifier_object in claim_object.qualifiers[qualifier_property]:
                qualifier_target = qualifier_object.getTarget()
                qualifier_target_label = getLabelFromObject(qualifier_target)
                print(item_label, main_property_label, claim_target_label, 
                      qualifier_property_label, qualifier_target_label, 
                      'change to', new_qualifier_property_label, '?')

                acceptable_prompt_set = {'y', 'yes', 'n', 'no', 'break'}
                promptbox = ''
                while (promptbox not in acceptable_prompt_set):
                    promptbox = input()

                if promptbox == 'y' or promptbox == 'yes':
                    qualifier_dict = qualifier_object.toJSON()
                    qualifier_dict['property'] =  new_qualifier_property #set up the qualifier change
                    print('Changing to', new_qualifier_property_label)
                    new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
                    claim_object.addQualifier(new_qualifier_object)

                elif promptbox == 'n' or promptbox == 'no':
                    print('Skipped')
                    
                elif promptbox == 'break':
                    break_flag = 1
                    break
                else:
                    print('Error - Deryck made a mistake')

        if break_flag == 1:
            break
    if break_flag == 1:
        break

print('All done, thanks for using!')
Retrieving 46 pages from wikidata:wikidata.
Now working on  Q13734992   Ronflonflon
Ronflonflon cast member Wim T. Schippers as Jacques Plafond change to character role ?
y
Changing to character role
Now working on  Q28548958   A Hole in the Ground
A Hole in the Ground cast member Alejandra Yáñez as Daniela change to character role ?
y
Changing to character role
A Hole in the Ground cast member Chris Yarrow as Manny change to character role ?
y
Changing to character role
A Hole in the Ground cast member Brian Patrick Butler as Charlie change to character role ?
y
Changing to character role
Now working on  Q27664424   Autumn Dreams
Autumn Dreams cast member Jill Wagner as adult change to character role ?
y
Changing to character role
Autumn Dreams cast member Colin Egglesfield as adult change to character role ?
y
Changing to character role
Autumn Dreams cast member Eric Gustafsson as teenager change to character role ?
y
Changing to character role
Autumn Dreams cast member Ivy Matheson as teenager change to character role ?
y
Changing to character role
Autumn Dreams cast member Michael Karl Richards as adult change to character role ?
y
Changing to character role
Autumn Dreams cast member Matt Visser as teenager change to character role ?
y
Changing to character role
Now working on  Q2248985   Follow Me, Boys!
Follow Me, Boys! cast member Craig Hill as adult change to character role ?
y
Changing to character role
Follow Me, Boys! cast member William Reynolds as adult change to character role ?
y
Changing to character role
Follow Me, Boys! cast member Hank Brandt as adult change to character role ?

y
Changing to character role
Follow Me, Boys! cast member Willie Soo Hoo as adult change to character role ?
y
Changing to character role
Follow Me, Boys! cast member Dean Moray as child change to character role ?
y
Changing to character role
Follow Me, Boys! cast member Billy Booth as child change to character role ?
y
Changing to character role
Follow Me, Boys! cast member Ricky Kelman as child change to character role ?
y
Changing to character role
Follow Me, Boys! cast member Warren Hsieh as child change to character role ?
y
Changing to character role
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-59-097c7836b240> in <module>()
     52     for claim_object in item_dict['claims'][main_property]:
     53         claim_target = claim_object.getTarget()
---> 54         claim_target_label = getLabelFromObject(claim_target)
     55 
     56         if qualifier_property in claim_object.qualifiers:

<ipython-input-59-097c7836b240> in getLabelFromObject(WDObject)
      6 
      7 def getLabelFromObject(WDObject):
----> 8     item_dict = WDObject.get()
      9     item_label = False
     10     if 'labels' in item_dict:

AttributeError: 'NoneType' object has no attribute 'get'
if(claim_target):
    print('yes')
else:
    print('no')
no
type(claim_target)
NoneType

Okay. So sometimes there is a relevant claim but the claim has no target because the value is "none" (or "unknown", I guess)!

So I guess I just have to not try to get a label when the target evaluates as False...

#input vars
main_property = 'P725'
qualifier_property = 'P794'
new_qualifier_property = 'P3831'
query_filename = 'qualifier_migrate.rq'
 
def getLabelFromObject(WDObject):
    item_dict = WDObject.get()
    item_label = False
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
    label = item_label
    if (label):
        return label
    else:
        return WDObject.getID()

def getLabelFromWDID(ID): #works for properties only. need separate function for items. why why why
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    item = pywikibot.PropertyPage(repo, ID)
    return getLabelFromObject(item)

main_property_label = getLabelFromWDID(main_property)
qualifier_property_label = getLabelFromWDID(qualifier_property)
new_qualifier_property_label = getLabelFromWDID(new_qualifier_property)

#start of actual script
import pywikibot
from pywikibot import pagegenerators as pg

wikidata_site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

with open(query_filename, 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

break_flag = 0

for item in generator:
    #operate on the most recent one for testing
    item_dict = item.get()
    item_label = getLabelFromObject(item)
            
    print('Now working on ', item.getID(), ' ', item_label)
    

    for claim_object in item_dict['claims'][main_property]:
        claim_target = claim_object.getTarget()
        claim_target_label = getLabelFromObject(claim_target) if claim_target else '[none]'
        
        if qualifier_property in claim_object.qualifiers:
            for qualifier_object in claim_object.qualifiers[qualifier_property]:
                qualifier_target = qualifier_object.getTarget()
                qualifier_target_label = getLabelFromObject(qualifier_target) if qualifier_target else '[none]'
                print(item_label, main_property_label, claim_target_label, 
                      qualifier_property_label, qualifier_target_label, 
                      'change to', new_qualifier_property_label, '?')

                acceptable_prompt_set = {'y', 'yes', 'n', 'no', 'break'}
                promptbox = ''
                while (promptbox not in acceptable_prompt_set):
                    promptbox = input()

                if promptbox == 'y' or promptbox == 'yes':
                    qualifier_dict = qualifier_object.toJSON()
                    qualifier_dict['property'] =  new_qualifier_property #set up the qualifier change
                    print('Changing to', new_qualifier_property_label)
                    new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
                    claim_object.addQualifier(new_qualifier_object)

                elif promptbox == 'n' or promptbox == 'no':
                    print('Skipped')
                    
                elif promptbox == 'break':
                    break_flag = 1
                    break
                else:
                    print('Error - Deryck made a mistake')

        if break_flag == 1:
            break
    if break_flag == 1:
        break

print('All done, thanks for using!')
Retrieving 33 pages from wikidata:wikidata.
Now working on  Q27612300   Die Schöne und das Biest
Die Schöne und das Biest voice actor Friedrich Schoenfelder as narrator change to object has role ?
y
Changing to object has role
WARNING: API error badtoken: Invalid CSRF token.
Die Schöne und das Biest voice actor Peter Edelmann as singer change to object has role ?
y
Changing to object has role
Now working on  Q27067681   Schneewittchen und die sieben Zwerge
Schneewittchen und die sieben Zwerge voice actor Ursula Wolff as voice actor change to object has role ?
n
Skipped
Schneewittchen und die sieben Zwerge voice actor Susanne Tremper as singer change to object has role ?
n
Skipped
Now working on  Q27537065   Arielle, die Meerjungfrau
Arielle, die Meerjungfrau voice actor Ute Lemper as singer change to object has role ?
y
Changing to object has role
Now working on  Q218894   Pocahontas
Pocahontas voice actor Irene Bedard as voice actor change to object has role ?
y
Changing to object has role
Pocahontas voice actor Judy Kuhn as singer change to object has role ?
y
Changing to object has role
Pocahontas voice actor Jim Cummings as singer change to object has role ?
y
Changing to object has role
Now working on  Q27243358   Aristocats
Aristocats voice actor Wolfgang Völz as chef change to object has role ?
n
Skipped
Aristocats voice actor Benno Hoffmann as Q1785974 change to object has role ?
n
Skipped
Aristocats voice actor Reinhard Mey as Q1785974 change to object has role ?
break
All done, thanks for using!

This version might edit multiple pages, but detects the exact path first

#input vars
main_property = 'P725'
qualifier_property = 'P794'
new_qualifier_property = 'P453'
query_filename = 'qualifier_migrate.rq'
allowed_qualifier_targets = {}
 
def getLabelFromObject(WDObject):
    item_dict = WDObject.get()
    item_label = False
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
    label = item_label
    if (label):
        return label
    else:
        return WDObject.getID()

def getLabelFromWDID(ID): #works for properties only. need separate function for items. why why why
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    item = pywikibot.PropertyPage(repo, ID)
    return getLabelFromObject(item)

main_property_label = getLabelFromWDID(main_property)
qualifier_property_label = getLabelFromWDID(qualifier_property)
new_qualifier_property_label = getLabelFromWDID(new_qualifier_property)

#start of actual script
import pywikibot
from pywikibot import pagegenerators as pg

wikidata_site = pywikibot.Site("wikidata", "wikidata")
repo = site.data_repository()

with open(query_filename, 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

break_flag = 0

for item in generator:
    #operate on the most recent one for testing
    item_dict = item.get()
    item_label = getLabelFromObject(item)
            
    print('Now working on ', item.getID(), ' ', item_label)#, 'Ready? ("yes" to go, "break" to stop)')
    
    #promptbox = ''
    #while (promptbox not in acceptable_prompt_set):
    #    promptbox = input()
    #if promptbox == 'break' or promptbox == 'no':
    #    break

    for claim_object in item_dict['claims'][main_property]:
        claim_target = claim_object.getTarget()
        claim_target_label = getLabelFromObject(claim_target) if claim_target else '[none]'
        
        if qualifier_property in claim_object.qualifiers:
            for qualifier_object in claim_object.qualifiers[qualifier_property]:
                qualifier_target = qualifier_object.getTarget()
                if (len(allowed_qualifier_targets) > 0 and 
                    qualifier_target.getID() not in allowed_qualifier_targets):
                    continue
                    
                qualifier_target_label = getLabelFromObject(qualifier_target) if qualifier_target else '[none]'
                print(item_label, main_property_label, claim_target_label, 
                      qualifier_property_label, qualifier_target_label, 
                      'change to', new_qualifier_property_label, '!')

                acceptable_prompt_set = {'y', 'yes', 'n', 'no', 'break'}
                promptbox = ''
                while (promptbox not in acceptable_prompt_set):
                    promptbox = 'y' #dangerous

                if promptbox == 'y' or promptbox == 'yes':
                    qualifier_dict = qualifier_object.toJSON()
                    qualifier_dict['property'] =  new_qualifier_property #set up the qualifier change
                    print('Changing to', new_qualifier_property_label)
                    new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
                    claim_object.addQualifier(new_qualifier_object)

                elif promptbox == 'n' or promptbox == 'no':
                    print('Skipped')
                    
                elif promptbox == 'break':
                    break_flag = 1
                    break
                else:
                    print('Error - Deryck made a mistake')

        if break_flag == 1:
            break
    if break_flag == 1:
        break

print('All done, thanks for using!')
Retrieving 38 pages from wikidata:wikidata.
Now working on  Q179673   Beauty and the Beast
Beauty and the Beast voice actor Mickie McGowan as farmer change to character role !
Changing to character role
Now working on  Q27662139   Der König der Löwen
Der König der Löwen voice actor Frank-Lorenz Engel as adult change to character role !
Changing to character role
Der König der Löwen voice actor Cusch Jung as adult change to character role !
Changing to character role
Der König der Löwen voice actor Alexandra Marisa Wilcke as adult change to character role !
Changing to character role
Der König der Löwen voice actor Magdalena Turba as child change to character role !
Changing to character role
Der König der Löwen voice actor Manuel Straube as child change to character role !
Changing to character role
Der König der Löwen voice actor Julius Jellinek as child change to character role !
Changing to character role
Now working on  Q188439   Tangled
Tangled voice actor Nathan Greno as guard change to character role !
Changing to character role
Tangled voice actor Nathan Greno as Thug change to character role !
Changing to character role
Tangled voice actor Tim Mertens as guard change to character role !
Changing to character role
Now working on  Q27943184   Bärenbrüder
Bärenbrüder voice actor Gerald Schaale as Tamias change to character role !
Changing to character role
Bärenbrüder voice actor Michael Pan as Tamias change to character role !
Changing to character role
Bärenbrüder voice actor Constanze Harpen as bear change to character role !
Changing to character role
Bärenbrüder voice actor Sabine Arnhold as bear change to character role !
Changing to character role
Bärenbrüder voice actor Thomas Nero Wolff as bear change to character role !
Changing to character role
Bärenbrüder voice actor Luise Lunow as bear change to character role !
Changing to character role
Bärenbrüder voice actor Karl Schulz as ram change to character role !
Changing to character role
Bärenbrüder voice actor Eberhard Prüter as ram change to character role !
Changing to character role
Now working on  Q27134284   Dornröschen
Dornröschen voice actor Benno Hoffmann as henchman change to character role !
Changing to character role
Now working on  Q13091172   Big Hero 6
Big Hero 6 voice actor Abraham Benrubi as general officer change to character role !
Changing to character role
Big Hero 6 voice actor Billy Bush as news presenter change to character role !
Changing to character role
Big Hero 6 voice actor Daniel Howell as technician change to character role !
Changing to character role
Big Hero 6 voice actor Phil Lester as technician change to character role !
Changing to character role
Now working on  Q18647981   Moana
Moana voice actor Louise Bush as toddler change to character role !
Changing to character role
Now working on  Q27881730   Tarzan
Tarzan voice actor Max Felder as child change to character role !
Changing to character role
Tarzan voice actor Tim Schwarzmaier as child change to character role !
Changing to character role
Tarzan voice actor Ivar Combrinck as sea captain change to character role !
Changing to character role
Now working on  Q39722   The Rescuers
The Rescuers voice actor Ruth Buzzi as mouse change to character role !
Changing to character role
The Rescuers voice actor Ruth Buzzi as Germans change to character role !
Changing to character role
Now working on  Q27074692   Bambi
Bambi voice actor Michael Günther as youth change to character role !
Changing to character role
Bambi voice actor Horst Buchholz as adult change to character role !
Changing to character role
Bambi voice actor Frank Elstner as child change to character role !
Changing to character role
Now working on  Q190135   The Little Mermaid
The Little Mermaid voice actor Kimmy Robertson as mermaid change to character role !
Changing to character role
The Little Mermaid voice actor Kimmy Robertson as sister change to character role !
Changing to character role
The Little Mermaid voice actor Caroline Vasicek as mermaid change to character role !
Changing to character role
The Little Mermaid voice actor Caroline Vasicek as sister change to character role !
Changing to character role
Now working on  Q28035758   Zoomania
Zoomania voice actor Ben Hadad as jaguar change to character role !
Changing to character role
Now working on  Q28018871   Die Eiskönigin - Völlig unverfroren
Die Eiskönigin - Völlig unverfroren voice actor Friedrich G. Beckhaus as bishop change to character role !
Changing to character role
Die Eiskönigin - Völlig unverfroren voice actor [none] as child change to character role !
Changing to character role
Die Eiskönigin - Völlig unverfroren voice actor [none] as toddler change to character role !
Changing to character role
Die Eiskönigin - Völlig unverfroren voice actor Tommy Amper as troll change to character role !
Changing to character role
Die Eiskönigin - Völlig unverfroren voice actor Helmut Gauß as Hofmeister change to character role !
Changing to character role
Die Eiskönigin - Völlig unverfroren voice actor Axel Malzacher as Lord change to character role !
Changing to character role
Now working on  Q165512   One Hundred and One Dalmatians
One Hundred and One Dalmatians voice actor Paul Wexler as auto mechanic change to character role !
Changing to character role
One Hundred and One Dalmatians voice actor Basil Ruysdael as truck driver change to character role !
Changing to character role
Now working on  Q27642359   Aladdin
Aladdin voice actor Michael Chevalier as cave change to character role !
Changing to character role
Now working on  Q215518   Aladdin
Aladdin voice actor Frank Welker as cave change to character role !
Changing to character role
Now working on  Q184701   The Aristocats
The Aristocats voice actor Peter Renaday as milkman change to character role !
Changing to character role
The Aristocats voice actor Peter Renaday as chef change to character role !
Changing to character role
The Aristocats voice actor Peter Renaday as Q1785974 change to character role !
Changing to character role
The Aristocats voice actor Mel Blanc as frog change to character role !
Changing to character role
Now working on  Q27067691   Schneewittchen und die sieben Zwerge
Schneewittchen und die sieben Zwerge voice actor Kerstin Sanders-Dornseif as witch change to character role !
Changing to character role
Now working on  Q28891   Wreck-It Ralph
Wreck-It Ralph voice actor Adam Carolla as Wynnchel change to character role !
Changing to character role
Wreck-It Ralph voice actor Horatio Sanz as Duncan change to character role !
Changing to character role
Wreck-It Ralph voice actor Brian Kesinger as cyborg change to character role !
Changing to character role
Wreck-It Ralph voice actor Tucker Gilmore as fictional turtle change to character role !
Changing to character role
Now working on  Q27148028   101 Dalmatiner
101 Dalmatiner voice actor Ewald Wenck as parson change to character role !
Changing to character role
Now working on  Q202371   The Rescuers Down Under
The Rescuers Down Under voice actor Peter Greenwood as announcer change to character role !
Changing to character role
The Rescuers Down Under voice actor Peter Greenwood as aviator change to character role !
Changing to character role
Now working on  Q27837192   Der Glöckner von Notre Dame
Der Glöckner von Notre Dame voice actor Gerry Wolff as prisoner change to character role !
Changing to character role
Now working on  Q27916586   Lilo & Stitch
Lilo & Stitch voice actor Melanie Hinze as lifeguard change to character role !
Changing to character role
Now working on  Q134430   Snow White and the Seven Dwarfs
Snow White and the Seven Dwarfs voice actor Jimmy MacDonald as yodeler change to character role !
Changing to character role
Snow White and the Seven Dwarfs voice actor Swiss Family Fraunfelder as yodeler change to character role !
Changing to character role
Now working on  Q27928267   Der Schatzplanet
Der Schatzplanet voice actor Robert Stadlober as youth change to character role !
Changing to character role
Der Schatzplanet voice actor Moritz Günther as child change to character role !
Changing to character role
Der Schatzplanet voice actor Helmut Krauss as pirate change to character role !
Changing to character role
Der Schatzplanet voice actor Gudo Hoegel as pirate change to character role !
Changing to character role
Der Schatzplanet voice actor Manfred Erdmann as pirate change to character role !
Changing to character role
Der Schatzplanet voice actor Thomas Albus as police officer change to character role !
Changing to character role
Der Schatzplanet voice actor Michael Brennicke as police officer change to character role !
Changing to character role
Now working on  Q27537202   Arielle, die Meerjungfrau
Arielle, die Meerjungfrau voice actor Martina Duncker as mermaid change to character role !
Changing to character role
Arielle, die Meerjungfrau voice actor Martina Duncker as sister change to character role !
Changing to character role
Now working on  Q40302   The Fox and the Hound
The Fox and the Hound voice actor Mickey Rooney as adult change to character role !
Changing to character role
The Fox and the Hound voice actor Kurt Russell as adult change to character role !
Changing to character role
The Fox and the Hound voice actor Keith Coogan as child change to character role !
Changing to character role
The Fox and the Hound voice actor Corey Feldman as child change to character role !
Changing to character role
Now working on  Q27495379   Oliver & Co.
Oliver & Co. voice actor Monica Bielenstein as Rita change to character role !
Changing to character role
Now working on  Q27429772   Bernard und Bianca - Die Mäusepolizei
Bernard und Bianca - Die Mäusepolizei voice actor Joachim Pukasz as reporter change to character role !
Changing to character role
Now working on  Q27442520   Cap und Capper
Cap und Capper voice actor Thomas Danneberg as adult change to character role !
Changing to character role
Cap und Capper voice actor Randolf Kronberg as adult change to character role !
Changing to character role
Cap und Capper voice actor [none] as child change to character role !
Changing to character role
Cap und Capper voice actor [none] as child change to character role !
Changing to character role
Now working on  Q27104156   Peter Pan
Peter Pan voice actor Erna Haffner as squaw change to character role !
Changing to character role
Peter Pan voice actor Walter Bluhm as pirate change to character role !
Changing to character role
Now working on  Q27093871   Alice im Wunderland
Alice im Wunderland voice actor Victor Janson as Odobenus rosmarus change to character role !
Changing to character role
Alice im Wunderland voice actor Anneliese Würtz as Rosa change to character role !
Changing to character role
Alice im Wunderland voice actor Alice Treff as bird change to character role !
Changing to character role
Alice im Wunderland voice actor Pinto Colvig as Phoenicopterus change to character role !
Changing to character role
Now working on  Q28027861   Baymax - Riesiges Robowabohu
Baymax - Riesiges Robowabohu voice actor Uli Krohm as general officer change to character role !
Changing to character role
Baymax - Riesiges Robowabohu voice actor Christina-Ann Zalamea as Abigail Callaghan change to character role !
Changing to character role
Baymax - Riesiges Robowabohu voice actor Axel Malzacher as news presenter change to character role !
Changing to character role
Now working on  Q204662   The Sword in the Stone
The Sword in the Stone voice actor Tudor Owen as knight change to character role !
Changing to character role
Now working on  Q246283   Frozen
Frozen voice actor Robert Pine as bishop change to character role !
Changing to character role
Frozen voice actor Olivia Stubenrauch as child change to character role !
Changing to character role
Frozen voice actor Eva Bella as child change to character role !
Changing to character role
Frozen voice actor Spencer Lacey Ganus as teenager change to character role !
Changing to character role
Frozen voice actor Tyree Brown as child change to character role !
Changing to character role
Now working on  Q215365   Brother Bear
Brother Bear voice actor Pauley Perrette as Female Lover Bear change to character role !
Changing to character role
Brother Bear voice actor Bumper Robinson as Chipmunks change to character role !
Changing to character role
Now working on  Q27964319   Assumption
Assumption voice actor Cortney Palm as leading actor change to character role !
Changing to character role
Now working on  Q27868185   Mulan
Mulan voice actor Wolfgang Dehler as ancestor change to character role !
Changing to character role
Mulan voice actor Jörg Hengstler as Huns change to character role !
Changing to character role
Mulan voice actor Eberhard Prüter as ancestor change to character role !
Changing to character role
Mulan voice actor Michael Pan as ancestor change to character role !
Changing to character role
Mulan voice actor Kaspar Eichel as ancestor change to character role !
Changing to character role
All done, thanks for using!

Property migrator generic use box

#input vars
main_property = 'P108'
qualifier_property = 'P794'
new_qualifier_property = 'P39'
query_filename = 'qualifier_migrate.rq'
allowed_qualifier_targets = {'Q256698' , 'Q1154390' , 'Q1402736', 'Q1154390'} #leave empty for everything to be processed
edit_summary = '[[P:P794]] is deprecated, migrating ' + main_property + '/' + qualifier_property + ' to ' + '/' + new_qualifier_property
no_promptbox = 1 #set to 1 to operate on entire query automatically, 0 to prompt once per item

#start of actual script
import pywikibot
from pywikibot import pagegenerators as pg

site = pywikibot.Site("wikidata", "wikidata")
wikidata_site = site #compatibility stuff
repo = site.data_repository()    

def getLabelFromObject(WDObject):
    item_dict = WDObject.get()
    item_label = False
    if 'labels' in item_dict:
        if 'en' in item_dict['labels']:
            item_label = item_dict['labels']['en']
    label = item_label
    if (label):
        return label
    else:
        return WDObject.getID()

def getLabelFromWDID(ID): #works for properties only. need separate function for items. why why why
    site = pywikibot.Site("wikidata", "wikidata")
    repo = site.data_repository()
    item = pywikibot.PropertyPage(repo, ID)
    return getLabelFromObject(item)

main_property_label = getLabelFromWDID(main_property)
qualifier_property_label = getLabelFromWDID(qualifier_property)
new_qualifier_property_label = getLabelFromWDID(new_qualifier_property)

with open(query_filename, 'r') as query_file:
    QUERY = query_file.read()

generator = pg.WikidataSPARQLPageGenerator(QUERY, site=wikidata_site)
generator = site.preloadpages(generator, pageprops=True)

break_flag = 0

for item in generator:
    #operate on the most recent one for testing
    item_dict = item.get()
    item_label = getLabelFromObject(item)
            
    print('Now working on ', item.getID(), ' ', item_label)#, 'Ready? ("yes" to go, "break" to stop)')
    
    #promptbox = ''
    #while (promptbox not in acceptable_prompt_set):
    #    promptbox = input()
    #if promptbox == 'break' or promptbox == 'no':
    #    break

    for claim_object in item_dict['claims'][main_property]:
        claim_target = claim_object.getTarget()
        claim_target_label = getLabelFromObject(claim_target) if claim_target else '[none]'
        
        if qualifier_property in claim_object.qualifiers:
            for qualifier_object in claim_object.qualifiers[qualifier_property]:
                qualifier_target = qualifier_object.getTarget()
                if (len(allowed_qualifier_targets) > 0 and 
                    qualifier_target.getID() not in allowed_qualifier_targets):
                    continue
                    
                qualifier_target_label = getLabelFromObject(qualifier_target) if qualifier_target else '[none]'
                print(item_label, main_property_label, claim_target_label, 
                      qualifier_property_label, qualifier_target_label, 
                      'change to', new_qualifier_property_label, '!')

                acceptable_prompt_set = {'y', 'yes', 'n', 'no', 'break'}
                promptbox = ''
                if (no_promptbox == 1):
                    promptbox = 'yes'
                while (promptbox not in acceptable_prompt_set):
                    promptbox = input()  #becomes automatic if set to 'y'

                if promptbox == 'y' or promptbox == 'yes':
                    qualifier_dict = qualifier_object.toJSON()
                    qualifier_dict['property'] =  new_qualifier_property #set up the qualifier change
                    print('Changing to', new_qualifier_property_label)
                    new_qualifier_object = qualifier_object.qualifierFromJSON(site = wikidata_site, data = qualifier_dict)
                    claim_object.addQualifier(new_qualifier_object, summary=edit_summary)

                elif promptbox == 'n' or promptbox == 'no':
                    print('Skipped')
                    
                elif promptbox == 'break':
                    break_flag = 1
                    break
                else:
                    print('Error - Deryck made a mistake')

        if break_flag == 1:
            break
    if break_flag == 1:
        break

print('All done, thanks for using!')
Retrieving 37 pages from wikidata:wikidata.
Now working on  Q1729268   Karen Piepenbrink
Now working on  Q454594   Sixtinus Amama
Now working on  Q1618852   Hilmar Klinkott
Now working on  Q20512597   Q20512597
Now working on  Q1268371   Ralf von den Hoff
Now working on  Q5688749   Ángel Herrerín López
Ángel Herrerín López employer National University of Distance Education as academic tenure change to position held !
Changing to position held
Now working on  Q21045355   Virginia Kirkus
Now working on  Q1233445   Thomas Maria Weber
Now working on  Q616021   Matthieu Galey
Now working on  Q13129535   Lewis William Lewis
Now working on  Q2172342   Rudolf Anthes
Now working on  Q25820510   Evert Willem Hofstee
Evert Willem Hofstee employer University of Groningen as Privatdozent change to position held !
Changing to position held
Now working on  Q2343886   Stephan Steingräber
Now working on  Q18691583   Louis De Leenheer
Now working on  Q1427613   Miloš Kirschner
Now working on  Q23649548   Nele Schröder
Now working on  Q63415   Dirk Niebel
Now working on  Q24956520   Bart Leroy
Bart Leroy employer Ghent University as residency change to position held !
Changing to position held
Now working on  Q29907799   Q29907799
Now working on  Q7103134   Orlando Mejía Rivera
Orlando Mejía Rivera employer University of Caldas as academic tenure change to position held !
Changing to position held
Now working on  Q22002024   Stijn Baert
Stijn Baert employer Ghent University as academic tenure change to position held !
Changing to position held
Now working on  Q23894956   Anne Paulin
Now working on  Q15228478   Christof Berns
Now working on  Q75064   Kurt Wachsmuth
Now working on  Q25933216   Hans Beckman
Now working on  Q18155976   Antoine Petit
Now working on  Q28941339   Clara Jobs
Now working on  Q26162501   Meret Strothmann
Now working on  Q70795   Walter Anderson
Walter Anderson employer Kazan Federal University as Privatdozent change to position held !
Changing to position held
Now working on  Q1674488   Isolde Stark
Now working on  Q91901   Ernst Fabricius
Now working on  Q3155030   Isabelle Saporta
Now working on  Q21279770   Zarah Ziadi
Now working on  Q1492424   Marieluise Deißmann-Merten
Now working on  Q3629697   Augusto Rostagni
Augusto Rostagni employer University of Turin as Privatdozent change to position held !
Changing to position held
Now working on  Q813186   Beate Salje
Now working on  Q89217   Fritz Eichler
All done, thanks for using!