3to2 python script gpx2svg and adjust arg parser options for compatible inkscape extension

FossilOrigin-Name: 6c3d94e7524e3f2551c22e9d085f7cd2153cd76c3cc920d57e5bb0dc2d84c48e
This commit is contained in:
desarrollo 2019-08-06 04:05:26 +00:00
parent f1ff4dd95f
commit 5bc7bdd70d
3 changed files with 105 additions and 107 deletions

View File

@ -16,8 +16,13 @@
# You should have received a copy of the GNU General Public License along # 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., # with this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. # 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 argparse
import sys import sys
@ -26,31 +31,31 @@ from xml.dom.minidom import parse as parseXml
from os.path import abspath from os.path import abspath
def parseGpx(gpxFile): 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 gpxFile = sys.stdin
# Get the XML information # Get the XML information
try: try:
gpx = parseXml(gpxFile) gpx = parseXml(gpxFile)
except IOError as error: except IOError, error:
print('Error while reading file: {}. Terminating.'.format(error), file = sys.stderr) print >> sys.stderr, u'Error while reading file: {}. Terminating.'.format(error)
sys.exit(1) sys.exit(1)
except: except:
print('Error while parsing XML data:', file = sys.stderr) print >> sys.stderr, u'Error while parsing XML data:'
print(sys.exc_info(), file = sys.stderr) print >> sys.stderr, sys.exc_info()
print('Terminating.', file = sys.stderr) print >> sys.stderr, u'Terminating.'
sys.exit(1) sys.exit(1)
# Iterate over all tracks, track segments and points # Iterate over all tracks, track segments and points
gpsData = [] gpsData = []
for track in gpx.getElementsByTagName('trk'): for track in gpx.getElementsByTagName(u'trk'):
for trackseg in track.getElementsByTagName('trkseg'): for trackseg in track.getElementsByTagName(u'trkseg'):
trackSegData = [] trackSegData = []
for point in trackseg.getElementsByTagName('trkpt'): for point in trackseg.getElementsByTagName(u'trkpt'):
trackSegData.append( 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 # Leave out empty segments
if(trackSegData != []): if(trackSegData != []):
@ -59,7 +64,7 @@ def parseGpx(gpxFile):
return gpsData return gpsData
def calcProjection(gpsData): def calcProjection(gpsData):
"""Calculate a plane projection for a GPS dataset""" u"""Calculate a plane projection for a GPS dataset"""
projectedData = [] projectedData = []
for segment in gpsData: for segment in gpsData:
@ -72,7 +77,7 @@ def calcProjection(gpsData):
return projectedData return projectedData
def mercatorProjection(coord): 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): # Assuming we're on earth, we have (according to GRS 80):
r = 6378137.0 r = 6378137.0
@ -87,7 +92,7 @@ def mercatorProjection(coord):
return x, y return x, y
def moveProjectedData(gpsData): 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 # Find the minimum and maximum x and y coordinates
minX = maxX = gpsData[0][0][0] minX = maxX = gpsData[0][0][0]
@ -115,7 +120,7 @@ def moveProjectedData(gpsData):
return movedGpsData, maxX - minX, maxY - minY return movedGpsData, maxX - minX, maxY - minY
def searchCircularSegments(gpsData): 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 = [] circularSegments = []
straightSegments = [] straightSegments = []
@ -129,7 +134,7 @@ def searchCircularSegments(gpsData):
return circularSegments, straightSegments return circularSegments, straightSegments
def combineSegmentPairs(gpsData): def combineSegmentPairs(gpsData):
"""Combine segment pairs to one bigger segment""" u"""Combine segment pairs to one bigger segment"""
combinedData = [] combinedData = []
@ -141,7 +146,7 @@ def combineSegmentPairs(gpsData):
foundMatch = False foundMatch = False
# Try to find a matching segment # 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]: if firstTrackData[len(firstTrackData) - 1] == gpsData[i][0]:
# There is a matching segment, so break here # There is a matching segment, so break here
foundMatch = True foundMatch = True
@ -161,7 +166,7 @@ def combineSegmentPairs(gpsData):
return searchCircularSegments(combinedData) return searchCircularSegments(combinedData)
def combineSegments(gpsData): 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. # Search for circular segments. We can't combine them with any other segment.
circularSegments, remainingSegments = searchCircularSegments(gpsData) circularSegments, remainingSegments = searchCircularSegments(gpsData)
@ -185,23 +190,23 @@ def combineSegments(gpsData):
return circularSegments + remainingSegments return circularSegments + remainingSegments
def chronologyJoinSegments(gpsData): 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 = [] joinedSegment = []
for segment in gpsData: for segment in gpsData:
joinedSegment += segment joinedSegment += segment
return [joinedSegment] return [joinedSegment]
def scaleCoords(coord, height, scale): 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 return coord[0] * scale, (coord[1] * -1 + height) * scale
def generateScaledSegment(segment, 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: for coord in segment:
yield scaleCoords(coord, height, scale) yield scaleCoords(coord, height, scale)
def writeSvgData(gpsData, width, height, maxPixels, dropSinglePoints, outfile): 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 # Calculate the scale factor we need to fit the requested maximal output size
if width <= maxPixels and height <= maxPixels: if width <= maxPixels and height <= maxPixels:
@ -212,22 +217,22 @@ def writeSvgData(gpsData, width, height, maxPixels, dropSinglePoints, outfile):
scale = maxPixels / height scale = maxPixels / height
# Open the requested output file or map to /dev/stdout # Open the requested output file or map to /dev/stdout
if outfile != '/dev/stdout': if outfile != u'/dev/stdout':
try: try:
fp = open(outfile, 'w') fp = open(outfile, u'w')
except IOError as error: except IOError, error:
print("Can't open output file: {}. Terminating.".format(error), file = sys.stderr) print >> sys.stderr, u"Can't open output file: {}. Terminating.".format(error)
sys.exit(1) sys.exit(1)
else: else:
fp = sys.stdout fp = sys.stdout
# Header data # Header data
fp.write( '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n') fp.write( u'<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n')
fp.write(('<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" ' fp.write((u'<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" '
'"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n')) u'"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n'))
fp.write( '<!-- Created with gpx2svg {} -->\n'.format(__version__)) fp.write( u'<!-- Created with gpx2svg {} -->\n'.format(__version__))
fp.write(('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" ' fp.write((u'<svg xmlns="http://www.w3.org/2000/svg" version="1.1" '
'width="{}px" height="{}px">\n').format(width * scale, height * scale)) u'width="{}px" height="{}px">\n').format(width * scale, height * scale))
# Process all track segments and generate ids and path drawing commands for them # 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 # Draw single points if requested
if len(singlePoints) > 0: if len(singlePoints) > 0:
fp.write('<g>\n') fp.write(u'<g>\n')
for segment in singlePoints: for segment in singlePoints:
x, y = scaleCoords(segment[0], height, scale) x, y = scaleCoords(segment[0], height, scale)
fp.write( 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 # Draw all circular segments
if len(circularSegments) > 0: if len(circularSegments) > 0:
fp.write('<g>\n') fp.write(u'<g>\n')
for segment in circularSegments: for segment in circularSegments:
fp.write('<path d="M') fp.write(u'<path d="M')
for x, y in generateScaledSegment(segment, height, scale): for x, y in generateScaledSegment(segment, height, scale):
fp.write(' {} {}'.format(x, y)) fp.write(u' {} {}'.format(x, y))
fp.write(' Z" style="fill:none;stroke:black"/>\n') fp.write(u' Z" style="fill:none;stroke:black"/>\n')
fp.write('</g>\n') fp.write(u'</g>\n')
# Draw all un-closed paths # Draw all un-closed paths
if len(straightSegments) > 0: if len(straightSegments) > 0:
fp.write('<g>\n') fp.write(u'<g>\n')
for segment in straightSegments: for segment in straightSegments:
fp.write('<path d="M') fp.write(u'<path d="M')
for x, y in generateScaledSegment(segment, height, scale): for x, y in generateScaledSegment(segment, height, scale):
fp.write(' {} {}'.format(x, y)) fp.write(u' {} {}'.format(x, y))
fp.write('" style="fill:none;stroke:black"/>\n') fp.write(u'" style="fill:none;stroke:black"/>\n')
fp.write('</g>\n') fp.write(u'</g>\n')
# Close the XML # Close the XML
fp.write('</svg>\n') fp.write(u'</svg>\n')
# Close the file if necessary # Close the file if necessary
if fp != sys.stdout: if fp != sys.stdout:
@ -288,69 +293,74 @@ def writeSvgData(gpsData, width, height, maxPixels, dropSinglePoints, outfile):
def main(): def main():
# Setup the command line argument parser # Setup the command line argument parser
cmdArgParser = argparse.ArgumentParser( cmdArgParser = argparse.ArgumentParser(
description = 'Convert GPX formatted geodata to Scalable Vector Graphics (SVG)', description = u'Convert GPX formatted geodata to Scalable Vector Graphics (SVG)',
epilog = 'gpx2svg {} - http://nasauber.de/opensource/gpx2svg/'.format(__version__) epilog = u'gpx2svg {} - http://nasauber.de/opensource/gpx2svg/'.format(__version__)
) )
cmdArgParser.add_argument( cmdArgParser.add_argument(
'-i', metavar = 'FILE', nargs = '?', type = str, default = '/dev/stdin', u'i', metavar = u'FILE', nargs = u'?', type = unicode, default = u'/dev/stdin',
help = 'GPX input file (default: read from STDIN)' help = u'GPX input file (default: read from STDIN)'
) )
cmdArgParser.add_argument( cmdArgParser.add_argument(
'-o', metavar = 'FILE', nargs = '?', type = str, default = '/dev/stdout', u'--o', metavar = u'FILE', nargs = u'?', type = unicode, default = u'/dev/stdout',
help = 'SVG output file (default: write to STDOUT)' help = u'SVG output file (default: write to STDOUT)'
) )
cmdArgParser.add_argument( cmdArgParser.add_argument(
'-m', metavar = 'PIXELS', nargs = '?', type = int, default = 3000, u'--m', metavar = u'PIXELS', nargs = u'?', type = int, default = 3000,
help = 'Maximum width or height of the SVG output in pixels (default: 3000)' help = u'Maximum width or height of the SVG output in pixels (default: 3000)'
) )
cmdArgParser.add_argument( cmdArgParser.add_argument(
'-d', action = 'store_true', u'--d',
help = 'Drop single points (default: draw a circle with 1px diameter)' help = u'Drop single points (default: draw a circle with 1px diameter)'
) )
cmdArgParser.add_argument( cmdArgParser.add_argument(
'-r', action = 'store_true', u'--r',
help = ('"Raw" conversion: Create one SVG path per track segment, don\'t try to combine ' help = (u'"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'paths that end with the starting point of another path')
) )
cmdArgParser.add_argument( cmdArgParser.add_argument(
'-j', action = 'store_true', u'--j',
help = ('Join all segments to a big one in the order of the GPX file. This can create an ' help = (u'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 ' u'un-scattered path if the default combining algorithm does not work because there '
'are no matching points across segments (implies -r)') u'are no matching points across segments (implies -r)')
) )
cmdArgParser.add_argument(
u'--tab',
help = (u'inkscape option')
)
# Get the given arguments # Get the given arguments
cmdArgs = cmdArgParser.parse_args() cmdArgs = cmdArgParser.parse_args()
# Map "-" to STDIN or STDOUT # Map "-" to STDIN or STDOUT
if cmdArgs.i == '-': if cmdArgs.i == u'-':
cmdArgs.i = '/dev/stdin' cmdArgs.i = u'/dev/stdin'
if cmdArgs.o == '-': if cmdArgs.o == u'-':
cmdArgs.o = '/dev/stdout' cmdArgs.o = u'/dev/stdout'
# Check if a given input or output file name is a relative representation of STDIN or STDOUT # Check if a given input or output file name is a relative representation of STDIN or STDOUT
if cmdArgs.i != '/dev/stdin': if cmdArgs.i != u'/dev/stdin':
if abspath(cmdArgs.i) == '/dev/stdin': if abspath(cmdArgs.i) == u'/dev/stdin':
cmdArgs.i = '/dev/stdin' cmdArgs.i = u'/dev/stdin'
if cmdArgs.o != '/dev/stdout': if cmdArgs.o != u'/dev/stdout':
if abspath(cmdArgs.o) == '/dev/stdout': if abspath(cmdArgs.o) == u'/dev/stdout':
cmdArgs.o = '/dev/stdout' cmdArgs.o = u'/dev/stdout'
# Get the latitude and longitude data from the given GPX file or STDIN # Get the latitude and longitude data from the given GPX file or STDIN
gpsData = parseGpx(cmdArgs.i) gpsData = parseGpx(cmdArgs.i)
# Check if we actually _have_ data # Check if we actually _have_ data
if gpsData == []: if gpsData == []:
print('No data to convert. Terminating.', file = sys.stderr) print >> sys.stderr, u'No data to convert. Terminating.'
sys.exit(1) sys.exit(1)
# Join all segments if requested by "-j" # Join all segments if requested by "-j"
if cmdArgs.j: if bool(cmdArgs.j):
gpsData = chronologyJoinSegments(gpsData) gpsData = chronologyJoinSegments(gpsData)
# Try to combine all track segments that can be combined if not requested otherwise # 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" # 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) gpsData = combineSegments(gpsData)
# Calculate a plane projection for a GPS dataset # Calculate a plane projection for a GPS dataset
@ -362,7 +372,7 @@ def main():
gpsData, width, height = moveProjectedData(gpsData) gpsData, width, height = moveProjectedData(gpsData)
# Write the resulting SVG data to the requested output file or STDOUT # 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() main()

View File

@ -1,42 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension"> <inkscape-extension xmlns="http://www.inkscape.org/namespace/inkscape/extension">
<_name>C2D Import</_name> <_name>GPX Import</_name>
<id>com.ClayJar.C2DImport</id> <id>mono.inkscape.pgx_input</id>
<dependency type="executable" location="extensions">c2d_input.py</dependency> <dependency type="executable" location="extensions">gpx2svg.py</dependency>
<dependency type="executable" location="extensions">inkex.py</dependency> <dependency type="executable" location="extensions">inkex.py</dependency>
<param name="tab" type="notebook"> <param name="tab" type="notebook">
<page name="options" _gui-text="Options"> <page name="options" _gui-text="Options">
<_param name="as_paths" type="boolean" _gui-text="Import all shapes as paths.">true</_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="inputhelp" type="description" xml:space="preserve"> <_param name="d" type="boolean" _gui-text="Drop single points" _gui-description="Default: draw a circle with 1px diameter" >true</_param>
If you uncheck this option, circles and rectangles with <_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>
"Square" or "Fillet" corners will be imported as shapes. <_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>
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>
</page> </page>
<page name="help" _gui-text="Help"> <page name="help" _gui-text="Help">
<_param name="helptext" type="description" xml:space="preserve"> <_param name="helptext" type="description" xml:space="preserve">
Notes: Homepage: https://efossils.somxslibres.net/fossil/user/mono/repository/inkgpx2svg/index
- Grouping is preserved. based on gpx2svg: https://nasauber.de/opensource/gpx2svg/
- All objects are imported as paths (except as noted). </_param>
- 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>
</page> </page>
</param> </param>
<input> <input>
<extension>.c2d</extension> <extension>.gpx</extension>
<mimetype>image/x-carbide-create</mimetype> <mimetype>application/gpx+xml</mimetype>
<_filetypename>Carbide Create file (*.c2d)</_filetypename> <_filetypename>GPS eXchange Format (*.gpx)</_filetypename>
<_filetypetooltip>Import Carbide Create C2D Format</_filetypetooltip> <_filetypetooltip>Import GPX Format</_filetypetooltip>
</input> </input>
<script> <script>
<command reldir="extensions" interpreter="python">c2d_input.py</command> <command reldir="extensions" interpreter="python">gpx2svg.py</command>
</script> </script>
</inkscape-extension> </inkscape-extension>