forked from wikimedia/pywikibot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.py
executable file
·153 lines (120 loc) · 4.82 KB
/
image.py
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
#!/usr/bin/env python3
"""
This script can be used to change one image to another or remove an image.
Syntax:
python pwb.py image image_name [new_image_name]
If only one command-line parameter is provided then that image will be removed;
if two are provided, then the first image will be replaced by the second one on
all pages.
Command line options:
-summary: Provide a custom edit summary. If the summary includes spaces,
surround it with single quotes, such as:
-summary:'My edit summary'
-always Don't prompt to make changes, just do them.
-loose Do loose replacements. This will replace all occurrences of the name
of the image (and not just explicit image syntax). This should work
to catch all instances of the image, including where it is used as a
template parameter or in image galleries. However, it can also make
more mistakes. This only works with image replacement, not image
removal.
Examples
--------
The image "FlagrantCopyvio.jpg" is about to be deleted, so let's first remove
it from everything that displays it:
python pwb.py image FlagrantCopyvio.jpg
The image "Flag.svg" has been uploaded, making the old "Flag.jpg" obsolete:
python pwb.py image Flag.jpg Flag.svg
"""
#
# (C) Pywikibot team, 2013-2022
#
# Distributed under the terms of the MIT license.
#
from __future__ import annotations
import regex as re
import pywikibot
from pywikibot import i18n, pagegenerators
from pywikibot.bot import SingleSiteBot
from pywikibot.textlib import case_escape, ignore_case
from scripts.replace import ReplaceRobot as ReplaceBot
class ImageRobot(ReplaceBot):
"""This bot will replace or remove all occurrences of an old image."""
def __init__(self, generator, old_image: str,
new_image: str = '', **kwargs) -> None:
"""
Initializer.
:param generator: the pages to work on
:type generator: iterable
:param old_image: the title of the old image (without namespace)
:param new_image: the title of the new image (without namespace), or
None if you want to remove the image
"""
self.available_options.update({
'summary': None,
'loose': False,
})
SingleSiteBot.__init__(self, **kwargs)
self.old_image = old_image
self.new_image = new_image
param = {
'old': self.old_image,
'new': self.new_image,
'file': self.old_image,
}
summary = self.opt.summary or i18n.twtranslate(
self.site, 'image-replace' if self.new_image else 'image-remove',
param)
namespace = self.site.namespaces[6]
escaped = case_escape(namespace.case, self.old_image, underscore=True)
if not self.opt.loose or not self.new_image:
image_regex = re.compile(
r'\[\[ *(?:{})\s*:\s*{} *(?P<parameters>\|'
r'(?:[^\[\]]|\[\[[^\]]+\]\]|\[[^\]]+\])*|) *\]\]'
.format('|'.join(ignore_case(s) for s in namespace), escaped))
else:
image_regex = re.compile(r'' + escaped)
replacements = []
if not self.opt.loose and self.new_image:
replacements.append((image_regex,
'[[{}:{}\\g<parameters>]]'
.format(
self.site.namespaces.FILE.custom_name,
self.new_image)))
else:
replacements.append((image_regex, self.new_image))
super().__init__(generator, replacements,
always=self.opt.always,
site=self.site,
summary=summary)
def main(*args: str) -> None:
"""
Process command line arguments and invoke bot.
If args is an empty list, sys.argv is used.
:param args: command line arguments
"""
old_image = ''
new_image = ''
options = {}
for argument in pywikibot.handle_args(args):
arg, _, value = argument.partition(':')
if arg in ('-always', '-loose'):
options[arg[1:]] = True
elif arg == '-summary':
options[arg[1:]] = value or pywikibot.input(
'Choose an edit summary: ')
elif old_image:
new_image = arg
else:
old_image = arg
if old_image:
site = pywikibot.Site()
old_imagepage = pywikibot.FilePage(site, old_image)
gen = old_imagepage.using_pages()
preloading_gen = pagegenerators.PreloadingGenerator(gen)
bot = ImageRobot(preloading_gen, old_image, new_image,
site=site, **options)
bot.run()
else:
pywikibot.bot.suggest_help(missing_parameters=['old image'])
if __name__ == '__main__':
main()