Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

#!/usr/bin/python 

# -*- coding: utf-8 -*- 

""" 

Find monuments where a commons category exists, but no link is in the list yet. 

 

Usage: 

# loop through all countries 

python missing_commonscat_links.py 

# work on specific country-lang 

python missing_commonscat_links.py -countrycode:XX -langcode:YY 

""" 

from collections import OrderedDict 

 

import pywikibot 

 

import common as common 

import monuments_config as mconfig 

from database_connection import ( 

close_database_connection, 

connect_to_commons_database, 

connect_to_monuments_database 

) 

from statistics_table import StatisticsTable 

 

_logger = "missing_commonscat" 

 

 

def processCountry(countryconfig, conn, cursor, conn2, cursor2): 

"""Work on a single country.""" 

if not countryconfig.get('missingCommonscatPage'): 

# missingCommonscatPage not set, just skip silently. 

return { 

'config': countryconfig, 

'cmt': 'skipped: no missingCommonscatPage' 

} 

if not countryconfig.get('commonsTrackerCategory'): 

# commonsTrackerCategory not set, just skip silently. 

return { 

'config': countryconfig, 

'cmt': 'skipped: no commonsTrackerCategory' 

} 

 

if countryconfig.get('type') == 'sparql': 

# This script does not (yet) work for SPARQL sources, skip silently 

return { 

'config': countryconfig, 

'cmt': 'skipped: cannot handle sparql' 

} 

 

commonscatField = lookupSourceField(u'commonscat', countryconfig) 

if not commonscatField: 

# Field is missing. Something is seriously wrong, but we just skip it 

# silently 

return { 

'config': countryconfig, 

'cmt': 'skipped: no template field matched to commonscat!!' 

} 

 

missingCommonscatPage = countryconfig.get('missingCommonscatPage') 

commonsTrackerCategory = countryconfig.get( 

'commonsTrackerCategory'). replace(u' ', u'_') 

 

withoutCommonscat = getMonumentsWithoutCommonscat( 

countryconfig.get('country'), countryconfig.get('lang'), conn, cursor) 

commonscats = getMonumentCommonscats( 

commonsTrackerCategory, conn2, cursor2) 

 

pywikibot.log(u'withoutCommonscat {num} elements'.format( 

num=len(withoutCommonscat))) 

pywikibot.log(u'commonscats {num} elements'.format( 

num=len(withoutCommonscat))) 

 

missing_commonscat = group_missing_commonscat_by_source( 

commonscats, withoutCommonscat, countryconfig) 

 

site = pywikibot.Site(countryconfig.get('lang'), u'wikipedia') 

page = pywikibot.Page(site, missingCommonscatPage) 

iw_links = getInterwikisMissingCommonscatPage( 

countryconfig.get('country'), countryconfig.get('lang')) 

totals = output_country_report( 

missing_commonscat, commonscatField, page, iw_links) 

 

return { 

'report_page': page, 

'config': countryconfig, 

'total_cats': totals['cats'], 

'total_pages': totals['pages'] 

} 

 

 

def output_country_report(missing_commonscat, commonscat_field, report_page, 

iw_links=None, max_cats=1000): 

""" 

Format and output the missing commonscats data for a a single country. 

 

@param missing_commonscat: the output of group_missing_commonscat_by_source 

@param commonscat_field: the template field used for adding a commonscat 

@param report_page: pywikibot.Page to which the report should be written 

@param iw_links: any interwiki links to append to the page. 

@param max_cats: the max number of categories to report to a page. Defaults 

to 1000. Note that actual number of images may be slightly higher in 

order to ensure all entries in a given list are presented. 

""" 

# People can add a /header template for with more info 

central_page = ':c:Commons:Monuments_database/Missing_commonscat_links' 

text = common.instruction_header(central_page) 

total_pages = 0 

totalCategories = 0 

 

if not missing_commonscat: 

text += common.done_message(central_page, 'missing commonscat') 

else: 

for source_page, cats in missing_commonscat.iteritems(): 

total_pages += 1 

if totalCategories < max_cats: 

text += u'=== {0} ===\n'.format(source_page) 

for (cat_name, monument_id) in cats: 

text += ( 

u'* <nowiki>|</nowiki> {field} = ' 

u'[[:c:Category:{_name}|{name}]] - {id}\n'.format( 

field=commonscat_field, 

_name=cat_name, 

name=cat_name.replace(u'_', u' '), 

id=monument_id 

) 

) 

totalCategories += len(cats) 

else: 

totalCategories += len(cats) 

 

if totalCategories >= max_cats: 

text += ( 

u'<!-- Maximum number of categories reached: {max}, ' 

u'total of missing commonscat links: {total} -->\n'.format( 

max=max_cats, total=totalCategories)) 

comment = ( 

u'Commonscat links to be made in monument lists: ' 

u'{max} (list maximum reached), ' 

u'total of missing commonscat links: {total}'.format( 

max=max_cats, total=totalCategories)) 

else: 

comment = u'Commonscat links to be made in monument lists: {0}'.format( 

totalCategories) 

 

if iw_links: 

text += iw_links 

 

pywikibot.debug(text, _logger) 

common.save_to_wiki_or_local(report_page, comment, text) 

 

return { 

'cats': totalCategories, 

'pages': total_pages 

} 

 

 

def group_missing_commonscat_by_source(commonscats, withoutCommonscat, 

countryconfig): 

"""Identify all unused images and group them by source page and id.""" 

missing_commonscat = {} 

 

for catSortKey in sorted(commonscats.keys()): 

try: 

monumentId = common.get_id_from_sort_key( 

catSortKey, withoutCommonscat) 

except ValueError: 

pywikibot.warning(u'Got value error for {0}'.format(catSortKey)) 

continue 

 

if monumentId in withoutCommonscat: 

try: 

source_link = common.get_source_link( 

withoutCommonscat.get(monumentId), 

countryconfig.get('type')) 

if source_link not in missing_commonscat: 

missing_commonscat[source_link] = [] 

except ValueError: 

pywikibot.warning( 

u'Could not find source page for {0} ({1})'.format( 

monumentId, withoutCommonscat.get(monumentId))) 

continue 

 

missing_commonscat[source_link].append( 

(commonscats.get(catSortKey), monumentId)) 

 

return missing_commonscat 

 

 

def lookupSourceField(destination, countryconfig): 

"""Lookup the source field of a destination.""" 

for field in countryconfig.get('fields'): 

if field.get('dest') == destination: 

return field.get('source') 

 

 

def getInterwikisMissingCommonscatPage(countrycode, lang): 

"""Get interwiki link to missing_commonscat_page for the same country.""" 

result = u'' 

for (countrycode2, lang2), countryconfig in mconfig.countries.iteritems(): 

if countrycode == countrycode2 and lang != lang2: 

if countryconfig.get('missingCommonscatPage'): 

result += u'[[{lang}:{page}]]\n'.format( 

lang=lang2, 

page=countryconfig.get('missingCommonscatPage')) 

 

return result 

 

 

def getMonumentsWithoutCommonscat(countrycode, lang, conn, cursor): 

""" 

Retrieve all monuments in the database without commonscat. 

 

@return dict of monuments without commonscat with id as key and source 

(list) as value. 

""" 

result = {} 

 

query = ( 

u"SELECT id, source " 

u"FROM monuments_all " 

u"WHERE (commonscat IS NULL or commonscat='') " 

u"AND country=%s AND lang=%s") 

 

cursor.execute(query, (countrycode, lang)) 

 

while True: 

try: 

row = cursor.fetchone() 

(id, source) = row 

# To uppercase, same happens in the other list 

result[id.upper()] = source 

except TypeError: 

break 

 

return result 

 

 

def getMonumentCommonscats(commonsTrackerCategory, conn, cursor): 

""" 

Retrieve all commons categories in the tracking category. 

 

@return dict of commons categories with category_sort_key as key and 

category name as value. category_sort_key contains the monument id. 

""" 

query = ( 

u"SELECT page_title, cl_sortkey_prefix " 

u"FROM page " 

u"JOIN categorylinks ON page_id=cl_from " 

u"WHERE page_namespace=14 AND page_is_redirect=0 AND cl_to=%s") 

 

cursor.execute(query, (commonsTrackerCategory,)) 

 

return common.process_sort_key_query_result(cursor) 

 

 

def makeStatistics(statistics): 

"""Output the overall results of the bot as a nice wikitable.""" 

site = pywikibot.Site('commons', 'commons') 

page = pywikibot.Page( 

site, 

u'Commons:Monuments database/Missing commonscat links/Statistics') 

 

title_column = OrderedDict([ 

('code', 'country'), 

('lang', None), 

('total', None), 

('report_page', 'page'), 

('row template', None), 

('Commons template', None) 

]) 

table = StatisticsTable(title_column, ('total', )) 

 

for row in statistics: 

countryconfig = row.get('config') 

total_cats_or_cmt = row.get('total_cats') 

row_template = None 

commons_template = None 

report_page = None 

 

if row.get('total_cats') is None: 

total_cats_or_cmt = row.get('cmt') 

 

if countryconfig.get('type') != 'sparql': 

row_template = common.get_template_link( 

countryconfig.get('lang'), 

countryconfig.get('project', u'wikipedia'), 

countryconfig.get('rowTemplate'), 

site) 

 

if countryconfig.get('commonsTemplate'): 

commons_template = u'{{tl|%s}}' % ( 

countryconfig.get('commonsTemplate'), ) 

 

if row.get('report_page'): 

report_page = row.get('report_page').title( 

as_link=True, with_ns=False, insite=site) 

 

table.add_row({ 

'code': countryconfig.get('country'), 

'lang': countryconfig.get('lang'), 

'total': total_cats_or_cmt, 

'report_page': report_page, 

'row template': row_template, 

'Commons template': commons_template}) 

 

text = table.to_wikitext() 

 

comment = ( 

u'Updating missing commonscat links statistics. ' 

u'Total missing links: {total_cats}'.format( 

total_cats=table.get_sum('total'))) 

pywikibot.debug(text, _logger) 

common.save_to_wiki_or_local(page, comment, text) 

 

 

def main(): 

countrycode = u'' 

lang = u'' 

skip_wd = False 

conn = None 

cursor = None 

# Connect database, we need that 

(conn, cursor) = connect_to_monuments_database() 

(conn2, cursor2) = connect_to_commons_database() 

 

for arg in pywikibot.handleArgs(): 

option, sep, value = arg.partition(':') 

if option == '-countrycode': 

countrycode = value 

elif option == '-langcode': 

lang = value 

elif option == '-skip_wd': 

skip_wd = True 

else: 

raise Exception( 

u'Bad parameters. Expected "-countrycode", "-langcode", ' 

u'"-skip_wd" or pywikibot args. ' 

u'Found "{}"'.format(option)) 

 

if countrycode and lang: 

if not mconfig.countries.get((countrycode, lang)): 

pywikibot.warning( 

u'I have no config for countrycode "{code}" in language ' 

u'"{lang}"'.format(code=countrycode, lang=lang)) 

return False 

pywikibot.log( 

u'Working on countrycode "{code}" in language "{lang}"'.format( 

code=countrycode, lang=lang)) 

processCountry(mconfig.countries.get((countrycode, lang)), 

conn, cursor, conn2, cursor2) 

elif countrycode or lang: 

raise Exception(u'The "countrycode" and "langcode" arguments must ' 

u'be used together.') 

else: 

statistics = [] 

for (countrycode, lang), countryconfig in mconfig.filtered_countries( 

skip_wd=skip_wd): 

pywikibot.log( 

u'Working on countrycode "{code}" in language "{lang}"'.format( 

code=countrycode, lang=lang)) 

try: 

statistics.append(processCountry( 

countryconfig, conn, cursor, conn2, cursor2)) 

except Exception as e: 

pywikibot.error( 

u'Unknown error occurred when processing country ' 

u'{0} in lang {1}\n{2}'.format(countrycode, lang, str(e))) 

statistics.append({ 

'config': countryconfig, 

'cmt': 'failed: unexpected error during processing' 

}) 

continue 

makeStatistics(statistics) 

 

close_database_connection(conn, cursor) 

 

 

if __name__ == "__main__": 

pywikibot.log(u'Start of %s' % __file__) 

main()