translate.convert.oo2xliff

Package translate :: Package convert :: Module oo2xliff |
[hide private]
[frames] | no frames]

# Source Code for Module translate.convert.oo2xliff

      1  #!/usr/bin/env python
      2  # -*- coding: utf-8 -*-
      3  #
      4  # Copyright 2003-2008 Zuza Software Foundation
      5  #
      6  # This file is part of translate.
      7  #
      8  # translate is free software; you can redistribute it and/or modify
      9  # it under the terms of the GNU General Public License as published by
     10  # the Free Software Foundation; either version 2 of the License, or
     11  # (at your option) any later version.
     12  #
     13  # translate is distributed in the hope that it will be useful,
     14  # but WITHOUT ANY WARRANTY; without even the implied warranty of
     15  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16  # GNU General Public License for more details.
     17  #
     18  # You should have received a copy of the GNU General Public License
     19  # along with translate; if not, write to the Free Software
     20  # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     21  #
     22
     23  """convert an OpenOffice.org (SDF) localization file to XLIFF localization files
     24
     25  User documentation: http://translate.sourceforge.net/wiki/toolkit/oo2po
     26  """
     27
     28  import sys
     29  from translate.storage import xliff
     30  from translate.storage import oo
     31
     32  # TODO: support using one GSI file as template, another as input (for when English is in one and translation in another)
     33
     34 -class oo2xliff:
     35 -    def __init__(self, sourcelanguage, targetlanguage, blankmsgstr=False, long_keys=False):
     36          """construct an oo2xliff converter for the specified languages"""
     37          self.sourcelanguage = sourcelanguage
     38          self.targetlanguage = targetlanguage
     39          self.blankmsgstr = blankmsgstr
     40          self.long_keys = long_keys
     41
     42 -    def maketargetunit(self, part1, part2, translators_comment, key, subkey):
     43          """makes a base unit (.po or XLIFF) out of a subkey of two parts"""
     44          #TODO: Do better
     45          text1 = getattr(part1, subkey)
     46          if text1 == "":
     47              return None
     48          text2 = getattr(part2, subkey)
     49
     50          unit = xliff.xliffunit(text1)
     51          unit.target = text2
     52          if unit.target:
     53              unit.markfuzzy(False)
     54          else:
     55              unit.markfuzzy(True)
     56          unit.addlocation(key + "." + subkey)
     57          if getattr(translators_comment, subkey).strip() != "":
     58              unit.addnote(getattr(translators_comment, subkey), origin="developer")
     59          return unit
     60
     61 -    def convertelement(self, theoo):
     62          """convert an oo element into a list of base units (.po or XLIFF)"""
     63          if self.sourcelanguage in theoo.languages:
     64              part1 = theoo.languages[self.sourcelanguage]
     65          else:
     66              print >> sys.stderr, "/".join(theoo.lines[0].getkey()), "language not found: %s" % (self.sourcelanguage)
     67              return []
     68          if self.blankmsgstr:
     69              # use a blank part2
     70              part2 = oo.ooline()
     71          else:
     72              if self.targetlanguage in theoo.languages:
     73                  part2 = theoo.languages[self.targetlanguage]
     74              else:
     75                  # if the language doesn't exist, the translation is missing ... so make it blank
     76                  part2 = oo.ooline()
     77          if "x-comment" in theoo.languages:
     78              translators_comment = theoo.languages["x-comment"]
     79          else:
     80              translators_comment = oo.ooline()
     81          key = oo.makekey(part1.getkey(), self.long_keys)
     82          unitlist = []
     83          for subkey in ("text", "quickhelptext", "title"):
     84              unit = self.maketargetunit(part1, part2, translators_comment, key, subkey)
     85              if unit is not None:
     86                  unitlist.append(unit)
     87          return unitlist
     88
     89 -    def convertstore(self, theoofile, duplicatestyle="msgctxt"):
     90          """converts an entire oo file to a base class format (.po or XLIFF)"""
     91          thetargetfile = xliff.xlifffile()
     92          thetargetfile.setsourcelanguage(self.sourcelanguage)
     93          thetargetfile.settargetlanguage(self.targetlanguage)
     94          # create a header for the file
     95          bug_url = 'http://qa.openoffice.org/issues/enter_bug.cgi' + ('''?subcomponent=ui&comment=&short_desc=Localization issue in file: %(filename)s&component=l10n&form_name=enter_issue''' % {"filename": theoofile.filename}).replace(" ", "%20").replace(":", "%3A")
     96          # go through the oo and convert each element
     97          for theoo in theoofile.units:
     98              unitlist = self.convertelement(theoo)
     99              for unit in unitlist:
    100                  thetargetfile.addunit(unit)
    101          return thetargetfile
    102
    103 -def verifyoptions(options):
    104      """verifies the commandline options"""
    105      if not options.targetlanguage:
    106          raise ValueError("You must specify the target language.")
    107
    108 -def convertoo(inputfile, outputfile, templates, pot=False, sourcelanguage=None, targetlanguage=None, duplicatestyle="msgctxt", multifilestyle="single"):
    109      """reads in stdin using inputstore class, converts using convertorclass, writes to stdout"""
    110      inputstore = oo.oofile()
    111      if hasattr(inputfile, "filename"):
    112          inputfilename = inputfile.filename
    113      else:
    114          inputfilename = "(input file name not known)"
    115      inputstore.filename = inputfilename
    116      inputstore.parse(inputfile.read())
    117      if not sourcelanguage:
    118          testlangtype = targetlanguage or (inputstore and inputstore.languages[0]) or ""
    119          if testlangtype.isdigit():
    120              sourcelanguage = "01"
    121          else:
    122              sourcelanguage = "en-US"
    123      if not sourcelanguage in inputstore.languages:
    124          print >> sys.stderr, "Warning: sourcelanguage '%s' not found in inputfile '%s' (contains %s)" % (sourcelanguage, inputfilename, ", ".join(inputstore.languages))
    125      if not pot and targetlanguage and targetlanguage not in inputstore.languages:
    126          print >> sys.stderr, "Warning: targetlanguage '%s' not found in inputfile '%s' (contains %s)" % (targetlanguage, inputfilename, ", ".join(inputstore.languages))
    127      convertor = oo2xliff(sourcelanguage, targetlanguage, blankmsgstr=pot, long_keys=multifilestyle!="single")
    128      outputstore = convertor.convertstore(inputstore, duplicatestyle)
    129      if outputstore.isempty():
    130          return 0
    131      outputfile.write(str(outputstore))
    132      return 1
    133
    134 -def main(argv=None):
    135      from translate.convert import convert
    136      formats = {"oo":("xlf", convertoo), "sdf":("xlf", convertoo)}
    137      # always treat the input as an archive unless it is a directory
    138      archiveformats = {(None, "input"): oo.oomultifile}
    139      parser = convert.ArchiveConvertOptionParser(formats, usepots=False, description=__doc__, archiveformats=archiveformats)
    140      parser.add_option("-l", "--language", dest="targetlanguage", default=None,
    141              help="set target language to extract from oo file (e.g. af-ZA)", metavar="LANG")
    142      parser.add_option("", "--source-language", dest="sourcelanguage", default=None,
    143              help="set source language code (default en-US)", metavar="LANG")
    144      parser.add_option("", "--nonrecursiveinput", dest="allowrecursiveinput", default=True, action="store_false", help="don't treat the input oo as a recursive store")
    145      parser.add_duplicates_option()
    146      parser.add_multifile_option()
    147      parser.passthrough.append("sourcelanguage")
    148      parser.passthrough.append("targetlanguage")
    149      parser.verifyoptions = verifyoptions
    150      parser.run(argv)
    151
    152  if __name__ == '__main__':
    153      main()
    154