-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathcomplexConstraint.py
More file actions
161 lines (138 loc) · 5.25 KB
/
complexConstraint.py
File metadata and controls
161 lines (138 loc) · 5.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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
63
64
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
101
102
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# licensed under CC-Zero: https://creativecommons.org/publicdomain/zero/1.0
import pywikibot
import requests
import json
import mwparserfromhell as mwparser
import time
import sys
import re
site = pywikibot.Site('wikidata', 'wikidata')
repo = site.data_repository()
template = 'Complex constraint'
blacklist = ['http://www.wikidata.org/entity/Q4115189', 'http://www.wikidata.org/entity/Q13406268', 'http://www.wikidata.org/entity/Q15397819', 'http://www.wikidata.org/entity/Q16943273', 'http://www.wikidata.org/entity/Q17339402']
all = []
maxQTemplate = 4000
def formatQP(val, qTemplateCnt):
if 'http://www.wikidata.org/entity/' not in val:
return val, qTemplateCnt
val = val.replace('http://www.wikidata.org/entity/', '')
if qTemplateCnt < maxQTemplate:
qTemplateCnt += 1
if val[0] == 'Q':
return '{{{{Q|{}}}}}'.format(val), qTemplateCnt
elif val[0] == 'P':
return '{{{{P|{}}}}}'.format(val), qTemplateCnt
else:
return val, qTemplateCnt
else:
if val[0] == 'Q':
return '[[{}]]'.format(val), qTemplateCnt
elif val[0] == 'P':
return '[[Property:{}]]'.format(val), qTemplateCnt
else:
return val, qTemplateCnt
def dictify(t):
data = {}
for param in t.params:
data[str(param.name).strip().lower()] = str(param.value).strip()
return data
def writeOverview():
row = u'{{{{TR complex constraint|p={property}\n|label={label}\n|description={description}\n|violations={violations}\n}}}}\n'
text = u'{{/header|' + time.strftime('%Y-%m-%d') + '}}\n\n'
for m in all:
text += row.format(**m)
text += u'{{/footer}}\n[[Category:Database reports|Complex Constraints]]'
page = pywikibot.Page(site, 'Wikidata:Database reports/Complex constraints')
page.put(text, summary='upd', minor=False)
def writeText(onePdata, property):
text = u'{{Complex constraint violations report|date=' + time.strftime('%Y-%m-%d %H:%M (%Z)') + '}}\n'
qTemplateCnt = 0
for m in onePdata:
text += '\n== '
text += m['label']
text += ' ==\n'
if m['description']:
text += m['description'] + '\n\n'
if m['violations'] == 0:
text += 'no results or query error\n\n'
else:
text += 'violations count: ' + str(m['violations']) + '\n\n'
res = sorted(m['result'], key=lambda x: (int(re.split('(\d+)', x[0])[1])))
if m['violations'] > 5000:
res = res[:5000]
for line in res:
for i in range(len(line)):
var, qTemplateCnt = formatQP(line[i], qTemplateCnt)
if i == 0:
text += '*'
elif i == 1:
text += ': '
else:
text += ', '
text += var
text += '\n'
page = pywikibot.Page(site, 'Wikidata:Database reports/Complex constraint violations/' + property)
page.put(text, summary='upd', minor=False)
def proceedOne(sparql):
result = []
try:
url = 'https://query.wikidata.org/bigdata/namespace/wdq/sparql'
headers = {'user-agent': 'DeltaBot Complex Constraints'}
payload = {
'query': sparql,
'format': 'json'
}
r = requests.get(url, params=payload, headers=headers)
data = r.json()
for m in data['results']['bindings']:
if m['item']['value'] in blacklist:
continue
line = [m['item']['value']]
for var in data['head']['vars']:
if var != 'item':
val = m[var]['value'].replace('T00:00:00Z', '')
line.append(val)
result.append(line)
except:
pass
return result
def onePropertyReport(page):
onePdata = []
code = mwparser.parse(page.get())
property = page.title().split(':')[1]
for t in code.filter_templates():
if t.name.strip() == template:
data = dictify(t)
data['property'] = property
data['sparql'] = data['sparql'].replace('{{!!}}', '||').replace('{{!}}', '|')
if not data['label'] or not data['sparql']:
continue
if data['label'] == '' or data['sparql'] == '':
continue
if not data['description']:
data['description'] = ''
data['result'] = proceedOne(data['sparql'])
data['violations'] = len(data['result'])
onePdata.append(data)
all.append(data)
writeText(onePdata, property)
def main():
if sys.argv[1] == 'all':
templatepage = pywikibot.Page(site, 'Template:'+template)
gen = templatepage.getReferences(only_template_inclusion=True, namespaces=[1, 121], content=True)
for page in gen:
try:
onePropertyReport(page)
except:
pass
writeOverview()
else:
if sys.argv[1][0] == 'P':
page = pywikibot.Page(site, 'Property_talk:'+sys.argv[1])
else:
page = pywikibot.Page(site, 'Talk:'+sys.argv[1])
onePropertyReport(page)
if __name__ == "__main__":
main()