-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathplotter.py
executable file
·233 lines (191 loc) · 8.54 KB
/
plotter.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
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
#! /usr/bin/env python3
import svgwrite as svg
import xml.etree.ElementTree as et
import os, configparser, argparse, sys, platform, traceback
from PIL import Image
settings = {}
def cleanQuotes(path):
if (path.startswith('\'') and path.endswith('\'')) or (path.startswith('\"') and path.endswith('\"')):
return path[1:-1]
else:
return path
def parsearg():
parser = argparse.ArgumentParser(description='Plot images in image-label networks generated by Memespector script')
parser.add_argument('--configfile',
metavar="CONFIG_PATH",
nargs=1,
default='config.txt',
help='Receives string for path to config file. Use this in case you wish to override the default config file.'
)
return parser.parse_args()
def parseconfigfile(path="config.txt"):
global settings
configfile = configparser.ConfigParser()
try:
configfile.read(path)
except Exception:
raise
try:
settings['input'] = cleanQuotes(configfile.get('Input', 'InputGraph'))
settings['inimgdir'] = cleanQuotes(configfile.get('Input', 'InputImageFolder'))
settings['copyresized'] = configfile.getboolean('Output', 'CopyImagesResized')
settings['outimgdir'] = configfile.get('Output', 'ResizedImageFolderName')
settings['resizew'] = configfile.getint('Output', 'ResizeMaxWidth')
settings['resizeh'] = configfile.getint('Output', 'ResizeMaxHeight')
settings['dispw'] = configfile.getint('Output', 'ImageMaxDispWidth')
settings['disph'] = configfile.getint('Output', 'ImageMaxDispHeight')
settings['restrpage'] = configfile.getboolean('Output', 'RestricttoPage')
settings['outw'] = configfile.getint('Output', 'OutputWidth')
settings['outh'] = configfile.getint('Output', 'OutputHeight')
except Exception as exc:
print(exc)
sys.exit("\n**ERROR**\nCould not parse at least one of the settings from the config file. Please verify its contents carefully.")
def loadSettings():
args = parsearg()
parseconfigfile(args.configfile)
def main():
try:
print("\n-------------------------\nImage Network Plotter\n-------------------------")
loadSettings()
# ------------------------------------------
# Set internal variables
#-------------------------------------------
outputfilename = os.path.join(os.path.dirname(settings['input']), "visual_" + os.path.basename(settings['input']).split(".")[0] + ".svg")
imgresizedim = settings['resizew'], settings['resizeh']
imgdrawdim = settings['dispw'], settings['disph']
print("Input file:", settings['input'])
ingexf = et.parse(settings['input'])
# ------------------------------------------
# Create output dir
#-------------------------------------------
if settings['copyresized']:
if os.path.isabs(settings['outimgdir']):
outimgdir = settings['outimgdir']
else:
outimgdir = os.path.join(os.path.dirname(settings['input']), settings['outimgdir'])
if not os.path.exists(outimgdir):
os.makedirs(outimgdir)
# ------------------------------------------
# Parse GEXF and generate SVG
#-------------------------------------------
try:
inroot = ingexf.getroot()
ns = {'gexf' : "http://www.gexf.net/1.3" }
viz = {'viz' : "http://www.gexf.net/1.3/viz"}
except Exception as exc:
print(exc)
print("**ERROR**\nCould not parse GEXF.")
typeAttId = -1
linkAttId = -1
fileAttId = -1
graph = inroot.find("gexf:graph", ns)
if not graph:
sys.exit("\n**ERROR**\nCould not parse graph file.\n")
attributes = graph.find(".gexf:attributes",ns)
for att in attributes:
if att.get('title') == 'type':
typeAttId = att.get('id')
elif att.get('title') == 'link':
linkAttId = att.get('id')
elif att.get('title') == 'file':
fileAttId = att.get('id')
nodes = graph.find("gexf:nodes", ns)
# Find graph bounding box and count images
numnodes = 0
numimages = 0
minx = 0
maxx = 0
miny = 0
maxy = 0
for node in nodes:
numnodes += 1
typeAtt = node.find("gexf:attvalues/gexf:attvalue[@for=\'" + str(typeAttId) +"\']",ns)
if typeAtt.get('value') == "image":
numimages += 1
try:
inimgx = float(node.find("viz:position", viz).get('x'))
inimgy = float(node.find("viz:position", viz).get('y'))
except AttributeError:
sys.exit("\n\n**ERROR**\nGraph has not been spatialized. Could not find position data for the nodes\nOpen it in Gephi, apply spatialization algorithm and export to another file.\n")
except Exception:
raise
if inimgx < minx:
minx = inimgx
if inimgx > maxx:
maxx = inimgx
if inimgy < miny:
miny = inimgy
if inimgy > maxy:
maxy = inimgy
print("Graph contains", numnodes, "nodes.")
print("Plotting", numimages, "images.\n")
print("Minimum X:", minx)
print("Maximum X:", maxx)
print("Minimum Y:", miny)
print("Maximum Y:", maxy)
# --------
# Configure output conversion
inw = maxx - minx
inh = maxy - miny
if (inw/inh) >= (settings['outw']/settings['outh']):
# match width
outfactor = settings['outw'] / inw
else:
# match height
outfactor = settings['outh'] / inh
outw = inw * outfactor
outh = inh * outfactor
outx = (settings['outw'] - outw)/2
outy = (settings['outh'] - outh)/2
# --------
# Draw output
outsvg = svg.Drawing(outputfilename, (settings['outw'], settings['outh']), debug=True)
curimg = 1
for node in nodes:
typeAtt = node.find("gexf:attvalues/gexf:attvalue[@for=\'" + str(typeAttId) +"\']",ns)
if typeAtt.get('value') == "image":
print("\n\nDrawing image", curimg, "in", numimages)
curimg += 1
innodex = (float(node.find("viz:position", viz).get('x'))-minx)/inw
innodey = (float(node.find("viz:position", viz).get('y'))-miny)/inh
if settings['restrpage']:
outnodex = (innodex * outw) + outx
outnodey = (innodey * outh) + outy
else:
outnodex = innodex
outnodey = innodey
nodeid = node.get('id')
imgfile = node.find("gexf:attvalues/gexf:attvalue[@for=\'" + str(fileAttId) +"\']",ns).get('value')
linkUrl = node.find("gexf:attvalues/gexf:attvalue[@for=\'" + str(linkAttId) +"\']",ns).get('value')
print("\tImage file:", imgfile)
infile = os.path.join(settings['inimgdir'], imgfile)
try:
curimage = Image.open(infile)
except Exception:
print("\t**ATTENTION** Image could not be loaded.\n")
continue
if settings['copyresized']:
imgfp = os.path.join(outimgdir, imgfile)
print("\tResizing image...")
try:
curimage.thumbnail(imgresizedim, Image.ANTIALIAS)
curimage.save(imgfp)
except Exception as exc:
print("\t**ATTENTION** Problem resizing image.\n")
print(exc)
continue
else:
imgfp = infile
print("\tPlotting image...\n")
link = outsvg.add(outsvg.a(linkUrl,id=nodeid))
image = link.add(outsvg.image(imgfp, insert=(outnodex, outnodey), size=imgdrawdim))
outsvg.save(pretty=True)
except KeyboardInterrupt:
if outsvg:
outsvg.save(pretty=True)
print("\n\n**Script interrupted by user**\n\n")
except Exception:
traceback.print_exc(file=sys.stdout)
sys.exit(0)
if __name__ == "__main__":
main()