3to2 python script gpx2svg and adjust arg parser options for compatible inkscape extension
FossilOrigin-Name: 6c3d94e7524e3f2551c22e9d085f7cd2153cd76c3cc920d57e5bb0dc2d84c48e
This commit is contained in:
parent
f1ff4dd95f
commit
5bc7bdd70d
|
@ -16,8 +16,13 @@
|
|||
# You should have received a copy of the GNU General Public License along
|
||||
# with this program; if not, write to the Free Software Foundation, Inc.,
|
||||
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
|
||||
#
|
||||
# modified by monomono@disroot.org at 2019-08-05 for use on inkscape extension
|
||||
|
||||
__version__ = '@VERSION@'
|
||||
from __future__ import division
|
||||
from __future__ import absolute_import
|
||||
from io import open
|
||||
__version__ = u'@VERSION@'
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
|
@ -26,31 +31,31 @@ from xml.dom.minidom import parse as parseXml
|
|||
from os.path import abspath
|
||||
|
||||
def parseGpx(gpxFile):
|
||||
"""Get the latitude and longitude data of all track segments in a GPX file"""
|
||||
u"""Get the latitude and longitude data of all track segments in a GPX file"""
|
||||
|
||||
if gpxFile == '/dev/stdin':
|
||||
if gpxFile == u'/dev/stdin':
|
||||
gpxFile = sys.stdin
|
||||
|
||||
# Get the XML information
|
||||
try:
|
||||
gpx = parseXml(gpxFile)
|
||||
except IOError as error:
|
||||
print('Error while reading file: {}. Terminating.'.format(error), file = sys.stderr)
|
||||
except IOError, error:
|
||||
print >> sys.stderr, u'Error while reading file: {}. Terminating.'.format(error)
|
||||
sys.exit(1)
|
||||
except:
|
||||
print('Error while parsing XML data:', file = sys.stderr)
|
||||
print(sys.exc_info(), file = sys.stderr)
|
||||
print('Terminating.', file = sys.stderr)
|
||||
print >> sys.stderr, u'Error while parsing XML data:'
|
||||
print >> sys.stderr, sys.exc_info()
|
||||
print >> sys.stderr, u'Terminating.'
|
||||
sys.exit(1)
|
||||
|
||||
# Iterate over all tracks, track segments and points
|
||||
gpsData = []
|
||||
for track in gpx.getElementsByTagName('trk'):
|
||||
for trackseg in track.getElementsByTagName('trkseg'):
|
||||
for track in gpx.getElementsByTagName(u'trk'):
|
||||
for trackseg in track.getElementsByTagName(u'trkseg'):
|
||||
trackSegData = []
|
||||
for point in trackseg.getElementsByTagName('trkpt'):
|
||||
for point in trackseg.getElementsByTagName(u'trkpt'):
|
||||
trackSegData.append(
|
||||
(float(point.attributes['lon'].value), float(point.attributes['lat'].value))
|
||||
(float(point.attributes[u'lon'].value), float(point.attributes[u'lat'].value))
|
||||
)
|
||||
# Leave out empty segments
|
||||
if(trackSegData != []):
|
||||
|
@ -59,7 +64,7 @@ def parseGpx(gpxFile):
|
|||
return gpsData
|
||||
|
||||
def calcProjection(gpsData):
|
||||
"""Calculate a plane projection for a GPS dataset"""
|
||||
u"""Calculate a plane projection for a GPS dataset"""
|
||||
|
||||
projectedData = []
|
||||
for segment in gpsData:
|
||||
|
@ -72,7 +77,7 @@ def calcProjection(gpsData):
|
|||
return projectedData
|
||||
|
||||
def mercatorProjection(coord):
|
||||
"""Calculate the Mercator projection of a coordinate pair"""
|
||||
u"""Calculate the Mercator projection of a coordinate pair"""
|
||||
|
||||
# Assuming we're on earth, we have (according to GRS 80):
|
||||
r = 6378137.0
|
||||
|
@ -87,7 +92,7 @@ def mercatorProjection(coord):
|
|||
return x, y
|
||||
|
||||
def moveProjectedData(gpsData):
|
||||
"""Move a dataset to 0,0 and return it with the resulting width and height"""
|
||||
u"""Move a dataset to 0,0 and return it with the resulting width and height"""
|
||||
|
||||
# Find the minimum and maximum x and y coordinates
|
||||
minX = maxX = gpsData[0][0][0]
|
||||
|
@ -115,7 +120,7 @@ def moveProjectedData(gpsData):
|
|||
return movedGpsData, maxX - minX, maxY - minY
|
||||
|
||||
def searchCircularSegments(gpsData):
|
||||
"""Splits a GPS dataset to tracks that are circular and other tracks"""
|
||||
u"""Splits a GPS dataset to tracks that are circular and other tracks"""
|
||||
|
||||
circularSegments = []
|
||||
straightSegments = []
|
||||
|
@ -129,7 +134,7 @@ def searchCircularSegments(gpsData):
|
|||
return circularSegments, straightSegments
|
||||
|
||||
def combineSegmentPairs(gpsData):
|
||||
"""Combine segment pairs to one bigger segment"""
|
||||
u"""Combine segment pairs to one bigger segment"""
|
||||
|
||||
combinedData = []
|
||||
|
||||
|
@ -141,7 +146,7 @@ def combineSegmentPairs(gpsData):
|
|||
foundMatch = False
|
||||
|
||||
# Try to find a matching segment
|
||||
for i in range(len(gpsData)):
|
||||
for i in xrange(len(gpsData)):
|
||||
if firstTrackData[len(firstTrackData) - 1] == gpsData[i][0]:
|
||||
# There is a matching segment, so break here
|
||||
foundMatch = True
|
||||
|
@ -161,7 +166,7 @@ def combineSegmentPairs(gpsData):
|
|||
return searchCircularSegments(combinedData)
|
||||
|
||||
def combineSegments(gpsData):
|
||||
"""Combine all segments of a GPS dataset that can be combined"""
|
||||
u"""Combine all segments of a GPS dataset that can be combined"""
|
||||
|
||||
# Search for circular segments. We can't combine them with any other segment.
|
||||
circularSegments, remainingSegments = searchCircularSegments(gpsData)
|
||||
|
@ -185,23 +190,23 @@ def combineSegments(gpsData):
|
|||
return circularSegments + remainingSegments
|
||||
|
||||
def chronologyJoinSegments(gpsData):
|
||||
"""Join all segments to a big one in the order defined by the GPX file."""
|
||||
u"""Join all segments to a big one in the order defined by the GPX file."""
|
||||
joinedSegment = []
|
||||
for segment in gpsData:
|
||||
joinedSegment += segment
|
||||
return [joinedSegment]
|
||||
|
||||
def scaleCoords(coord, height, scale):
|
||||
"""Return a scaled pair of coordinates"""
|
||||
u"""Return a scaled pair of coordinates"""
|
||||
return coord[0] * scale, (coord[1] * -1 + height) * scale
|
||||
|
||||
def generateScaledSegment(segment, height, scale):
|
||||
"""Create the coordinate part of an SVG path string from a GPS data segment"""
|
||||
u"""Create the coordinate part of an SVG path string from a GPS data segment"""
|
||||
for coord in segment:
|
||||
yield scaleCoords(coord, height, scale)
|
||||
|
||||
def writeSvgData(gpsData, width, height, maxPixels, dropSinglePoints, outfile):
|
||||
"""Output the SVG data -- quick 'n' dirty, without messing around with dom stuff ;-)"""
|
||||
u"""Output the SVG data -- quick 'n' dirty, without messing around with dom stuff ;-)"""
|
||||
|
||||
# Calculate the scale factor we need to fit the requested maximal output size
|
||||
if width <= maxPixels and height <= maxPixels:
|
||||
|
@ -212,22 +217,22 @@ def writeSvgData(gpsData, width, height, maxPixels, dropSinglePoints, outfile):
|
|||
scale = maxPixels / height
|
||||
|
||||
# Open the requested output file or map to /dev/stdout
|
||||
if outfile != '/dev/stdout':
|
||||
if outfile != u'/dev/stdout':
|
||||
try:
|
||||
fp = open(outfile, 'w')
|
||||
except IOError as error:
|
||||
print("Can't open output file: {}. Terminating.".format(error), file = sys.stderr)
|
||||
fp = open(outfile, u'w')
|
||||
except IOError, error:
|
||||
print >> sys.stderr, u"Can't open output file: {}. Terminating.".format(error)
|
||||
sys.exit(1)
|
||||
else:
|
||||
fp = sys.stdout
|
||||
|
||||
# Header data
|
||||
fp.write( '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
|
||||
fp.write(('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
|
||||
'"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'))
|
||||
fp.write( '<!-- Created with gpx2svg {} -->\n'.format(__version__))
|
||||
fp.write(('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" '
|
||||
'width="{}px" height="{}px">\n').format(width * scale, height * scale))
|
||||
fp.write( u'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
|
||||
fp.write((u'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
|
||||
u'"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'))
|
||||
fp.write( u'<!-- Created with gpx2svg {} -->\n'.format(__version__))
|
||||
fp.write((u'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" '
|
||||
u'width="{}px" height="{}px">\n').format(width * scale, height * scale))
|
||||
|
||||
# Process all track segments and generate ids and path drawing commands for them
|
||||
|
||||
|
@ -250,36 +255,36 @@ def writeSvgData(gpsData, width, height, maxPixels, dropSinglePoints, outfile):
|
|||
|
||||
# Draw single points if requested
|
||||
if len(singlePoints) > 0:
|
||||
fp.write('<g>\n')
|
||||
fp.write(u'<g>\n')
|
||||
for segment in singlePoints:
|
||||
x, y = scaleCoords(segment[0], height, scale)
|
||||
fp.write(
|
||||
'<circle cx="{}" cy="{}" r="0.5" style="stroke:none;fill:black"/>\n'.format(x, y)
|
||||
u'<circle cx="{}" cy="{}" r="0.5" style="stroke:none;fill:black"/>\n'.format(x, y)
|
||||
)
|
||||
fp.write('</g>\n')
|
||||
fp.write(u'</g>\n')
|
||||
|
||||
# Draw all circular segments
|
||||
if len(circularSegments) > 0:
|
||||
fp.write('<g>\n')
|
||||
fp.write(u'<g>\n')
|
||||
for segment in circularSegments:
|
||||
fp.write('<path d="M')
|
||||
fp.write(u'<path d="M')
|
||||
for x, y in generateScaledSegment(segment, height, scale):
|
||||
fp.write(' {} {}'.format(x, y))
|
||||
fp.write(' Z" style="fill:none;stroke:black"/>\n')
|
||||
fp.write('</g>\n')
|
||||
fp.write(u' {} {}'.format(x, y))
|
||||
fp.write(u' Z" style="fill:none;stroke:black"/>\n')
|
||||
fp.write(u'</g>\n')
|
||||
|
||||
# Draw all un-closed paths
|
||||
if len(straightSegments) > 0:
|
||||
fp.write('<g>\n')
|
||||
fp.write(u'<g>\n')
|
||||
for segment in straightSegments:
|
||||
fp.write('<path d="M')
|
||||
fp.write(u'<path d="M')
|
||||
for x, y in generateScaledSegment(segment, height, scale):
|
||||
fp.write(' {} {}'.format(x, y))
|
||||
fp.write('" style="fill:none;stroke:black"/>\n')
|
||||
fp.write('</g>\n')
|
||||
fp.write(u' {} {}'.format(x, y))
|
||||
fp.write(u'" style="fill:none;stroke:black"/>\n')
|
||||
fp.write(u'</g>\n')
|
||||
|
||||
# Close the XML
|
||||
fp.write('</svg>\n')
|
||||
fp.write(u'</svg>\n')
|
||||
|
||||
# Close the file if necessary
|
||||
if fp != sys.stdout:
|
||||
|
@ -288,69 +293,74 @@ def writeSvgData(gpsData, width, height, maxPixels, dropSinglePoints, outfile):
|
|||
def main():
|
||||
# Setup the command line argument parser
|
||||
cmdArgParser = argparse.ArgumentParser(
|
||||
description = 'Convert GPX formatted geodata to Scalable Vector Graphics (SVG)',
|
||||
epilog = 'gpx2svg {} - http://nasauber.de/opensource/gpx2svg/'.format(__version__)
|
||||
description = u'Convert GPX formatted geodata to Scalable Vector Graphics (SVG)',
|
||||
epilog = u'gpx2svg {} - http://nasauber.de/opensource/gpx2svg/'.format(__version__)
|
||||
)
|
||||
cmdArgParser.add_argument(
|
||||
'-i', metavar = 'FILE', nargs = '?', type = str, default = '/dev/stdin',
|
||||
help = 'GPX input file (default: read from STDIN)'
|
||||
u'i', metavar = u'FILE', nargs = u'?', type = unicode, default = u'/dev/stdin',
|
||||
help = u'GPX input file (default: read from STDIN)'
|
||||
)
|
||||
cmdArgParser.add_argument(
|
||||
'-o', metavar = 'FILE', nargs = '?', type = str, default = '/dev/stdout',
|
||||
help = 'SVG output file (default: write to STDOUT)'
|
||||
u'--o', metavar = u'FILE', nargs = u'?', type = unicode, default = u'/dev/stdout',
|
||||
help = u'SVG output file (default: write to STDOUT)'
|
||||
)
|
||||
cmdArgParser.add_argument(
|
||||
'-m', metavar = 'PIXELS', nargs = '?', type = int, default = 3000,
|
||||
help = 'Maximum width or height of the SVG output in pixels (default: 3000)'
|
||||
u'--m', metavar = u'PIXELS', nargs = u'?', type = int, default = 3000,
|
||||
help = u'Maximum width or height of the SVG output in pixels (default: 3000)'
|
||||
)
|
||||
cmdArgParser.add_argument(
|
||||
'-d', action = 'store_true',
|
||||
help = 'Drop single points (default: draw a circle with 1px diameter)'
|
||||
u'--d',
|
||||
help = u'Drop single points (default: draw a circle with 1px diameter)'
|
||||
)
|
||||
cmdArgParser.add_argument(
|
||||
'-r', action = 'store_true',
|
||||
help = ('"Raw" conversion: Create one SVG path per track segment, don\'t try to combine '
|
||||
'paths that end with the starting point of another path')
|
||||
u'--r',
|
||||
help = (u'"Raw" conversion: Create one SVG path per track segment, don\'t try to combine '
|
||||
u'paths that end with the starting point of another path')
|
||||
)
|
||||
cmdArgParser.add_argument(
|
||||
'-j', action = 'store_true',
|
||||
help = ('Join all segments to a big one in the order of the GPX file. This can create an '
|
||||
'un-scattered path if the default combining algorithm does not work because there '
|
||||
'are no matching points across segments (implies -r)')
|
||||
u'--j',
|
||||
help = (u'Join all segments to a big one in the order of the GPX file. This can create an '
|
||||
u'un-scattered path if the default combining algorithm does not work because there '
|
||||
u'are no matching points across segments (implies -r)')
|
||||
)
|
||||
cmdArgParser.add_argument(
|
||||
u'--tab',
|
||||
help = (u'inkscape option')
|
||||
)
|
||||
|
||||
|
||||
# Get the given arguments
|
||||
cmdArgs = cmdArgParser.parse_args()
|
||||
|
||||
# Map "-" to STDIN or STDOUT
|
||||
if cmdArgs.i == '-':
|
||||
cmdArgs.i = '/dev/stdin'
|
||||
if cmdArgs.o == '-':
|
||||
cmdArgs.o = '/dev/stdout'
|
||||
if cmdArgs.i == u'-':
|
||||
cmdArgs.i = u'/dev/stdin'
|
||||
if cmdArgs.o == u'-':
|
||||
cmdArgs.o = u'/dev/stdout'
|
||||
|
||||
# Check if a given input or output file name is a relative representation of STDIN or STDOUT
|
||||
if cmdArgs.i != '/dev/stdin':
|
||||
if abspath(cmdArgs.i) == '/dev/stdin':
|
||||
cmdArgs.i = '/dev/stdin'
|
||||
if cmdArgs.o != '/dev/stdout':
|
||||
if abspath(cmdArgs.o) == '/dev/stdout':
|
||||
cmdArgs.o = '/dev/stdout'
|
||||
if cmdArgs.i != u'/dev/stdin':
|
||||
if abspath(cmdArgs.i) == u'/dev/stdin':
|
||||
cmdArgs.i = u'/dev/stdin'
|
||||
if cmdArgs.o != u'/dev/stdout':
|
||||
if abspath(cmdArgs.o) == u'/dev/stdout':
|
||||
cmdArgs.o = u'/dev/stdout'
|
||||
|
||||
# Get the latitude and longitude data from the given GPX file or STDIN
|
||||
gpsData = parseGpx(cmdArgs.i)
|
||||
|
||||
# Check if we actually _have_ data
|
||||
if gpsData == []:
|
||||
print('No data to convert. Terminating.', file = sys.stderr)
|
||||
print >> sys.stderr, u'No data to convert. Terminating.'
|
||||
sys.exit(1)
|
||||
|
||||
# Join all segments if requested by "-j"
|
||||
if cmdArgs.j:
|
||||
if bool(cmdArgs.j):
|
||||
gpsData = chronologyJoinSegments(gpsData)
|
||||
|
||||
# Try to combine all track segments that can be combined if not requested otherwise
|
||||
# Don't execute if all segments are already joined with "-j"
|
||||
if not cmdArgs.r and not cmdArgs.j:
|
||||
if not bool(cmdArgs.r) and not bool(cmdArgs.j):
|
||||
gpsData = combineSegments(gpsData)
|
||||
|
||||
# Calculate a plane projection for a GPS dataset
|
||||
|
@ -362,7 +372,7 @@ def main():
|
|||
gpsData, width, height = moveProjectedData(gpsData)
|
||||
|
||||
# Write the resulting SVG data to the requested output file or STDOUT
|
||||
writeSvgData(gpsData, width, height, cmdArgs.m, cmdArgs.d, cmdArgs.o)
|
||||
writeSvgData(gpsData, width, height, cmdArgs.m, bool(cmdArgs.d), cmdArgs.o)
|
||||
|
||||
if __name__ == '__main__':
|
||||
if __name__ == u'__main__':
|
||||
main()
|
|
@ -1,42 +1,30 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
|
||||
<_name>C2D Import</_name>
|
||||
<id>com.ClayJar.C2DImport</id>
|
||||
<dependency type="executable" location="extensions">c2d_input.py</dependency>
|
||||
<_name>GPX Import</_name>
|
||||
<id>mono.inkscape.pgx_input</id>
|
||||
<dependency type="executable" location="extensions">gpx2svg.py</dependency>
|
||||
<dependency type="executable" location="extensions">inkex.py</dependency>
|
||||
<param name="tab" type="notebook">
|
||||
<page name="options" _gui-text="Options">
|
||||
<_param name="as_paths" type="boolean" _gui-text="Import all shapes as paths.">true</_param>
|
||||
<_param name="inputhelp" type="description" xml:space="preserve">
|
||||
If you uncheck this option, circles and rectangles with
|
||||
"Square" or "Fillet" corners will be imported as shapes.
|
||||
All other objects are always imported as paths.</_param>
|
||||
<param name="sep1" type="description">-----------------------------------------------------------------</param>
|
||||
<_param name="textwarning" type="description" xml:space="preserve">
|
||||
NOTE: Text from older versions of Carbide Create may not be
|
||||
successfully imported. Simply open the C2D file in Carbide
|
||||
Create version 316 or later and save.</_param>
|
||||
<_param name="m" type="int" _gui-text="Maximum width or height of the SVG in pixels" min="0" max="100000">3000</_param>
|
||||
<_param name="d" type="boolean" _gui-text="Drop single points" _gui-description="Default: draw a circle with 1px diameter" >true</_param>
|
||||
<_param name="r" type="boolean" _gui-text="Raw conversion" _gui-description="Create on SVG path per track segment, don't try to combine paths that end with the starting piont of another path" >true</_param>
|
||||
<_param name="j" type="boolean" _gui-text="Join all segments" _gui-description="Join all segments to a big one in the order of the gpx file. This can create an oun-scattered path if the default combining algorthm does not work because there are no matching pints across segments (implies raw conversion)" >true</_param>
|
||||
</page>
|
||||
<page name="help" _gui-text="Help">
|
||||
<_param name="helptext" type="description" xml:space="preserve">
|
||||
Notes:
|
||||
- Grouping is preserved.
|
||||
- All objects are imported as paths (except as noted).
|
||||
- Rendered text (Carbide Create 316 or later) is imported.
|
||||
- A background rectangle showing the stock is added.
|
||||
- Toolpath information is not imported.
|
||||
|
||||
Homepage: https://github.com/ClayJarCom/C2DImport
|
||||
</_param>
|
||||
<_param name="helptext" type="description" xml:space="preserve">
|
||||
Homepage: https://efossils.somxslibres.net/fossil/user/mono/repository/inkgpx2svg/index
|
||||
based on gpx2svg: https://nasauber.de/opensource/gpx2svg/
|
||||
</_param>
|
||||
</page>
|
||||
</param>
|
||||
<input>
|
||||
<extension>.c2d</extension>
|
||||
<mimetype>image/x-carbide-create</mimetype>
|
||||
<_filetypename>Carbide Create file (*.c2d)</_filetypename>
|
||||
<_filetypetooltip>Import Carbide Create C2D Format</_filetypetooltip>
|
||||
<extension>.gpx</extension>
|
||||
<mimetype>application/gpx+xml</mimetype>
|
||||
<_filetypename>GPS eXchange Format (*.gpx)</_filetypename>
|
||||
<_filetypetooltip>Import GPX Format</_filetypetooltip>
|
||||
</input>
|
||||
<script>
|
||||
<command reldir="extensions" interpreter="python">c2d_input.py</command>
|
||||
<command reldir="extensions" interpreter="python">gpx2svg.py</command>
|
||||
</script>
|
||||
</inkscape-extension>
|
||||
|
|
Loading…
Reference in New Issue