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 urllib import urlencode
     30
     31  from translate.storage import xliff
     32  from translate.storage import oo
     33
     34  # TODO: support using one GSI file as template, another as input (for when English is in one and translation in another)
     35
     36
     37 -class oo2xliff:
     38
     39 -    def __init__(self, sourcelanguage, targetlanguage, blankmsgstr=False, long_keys=False):
     40          """construct an oo2xliff converter for the specified languages"""
     41          self.sourcelanguage = sourcelanguage
     42          self.targetlanguage = targetlanguage
     43          self.blankmsgstr = blankmsgstr
     44          self.long_keys = long_keys
     45
     46 -    def maketargetunit(self, part1, part2, translators_comment, key, subkey):
     47          """makes a base unit (.po or XLIFF) out of a subkey of two parts"""
     48          #TODO: Do better
     49          text1 = getattr(part1, subkey)
     50          if text1 == "":
     51              return None
     52          text2 = getattr(part2, subkey)
     53
     54          unit = xliff.xliffunit(text1)
     55          unit.target = text2
     56          if unit.target:
     57              unit.markfuzzy(False)
     58          else:
     59              unit.markfuzzy(True)
     60          unit.addlocation(key + "." + subkey)
     61          if getattr(translators_comment, subkey).strip() != "":
     62              unit.addnote(getattr(translators_comment, subkey), origin="developer")
     63          return unit
     64
     65 -    def convertelement(self, theoo):
     66          """convert an oo element into a list of base units (.po or XLIFF)"""
     67          if self.sourcelanguage in theoo.languages:
     68              part1 = theoo.languages[self.sourcelanguage]
     69          else:
     70              print >> sys.stderr, "/".join(theoo.lines[0].getkey()), "language not found: %s" % (self.sourcelanguage)
     71              return []
     72          if self.blankmsgstr:
     73              # use a blank part2
     74              part2 = oo.ooline()
     75          else:
     76              if self.targetlanguage in theoo.languages:
     77                  part2 = theoo.languages[self.targetlanguage]
     78              else:
     79                  # if the language doesn't exist, the translation is missing ... so make it blank
     80                  part2 = oo.ooline()
     81          if "x-comment" in theoo.languages:
     82              translators_comment = theoo.languages["x-comment"]
     83          else:
     84              translators_comment = oo.ooline()
     85          key = oo.makekey(part1.getkey(), self.long_keys)
     86          unitlist = []
     87          for subkey in ("text", "quickhelptext", "title"):
     88              unit = self.maketargetunit(part1, part2, translators_comment, key, subkey)
     89              if unit is not None:
     90                  unitlist.append(unit)
     91          return unitlist
     92
     93 -    def convertstore(self, theoofile, duplicatestyle="msgctxt"):
     94          """converts an entire oo file to a base class format (.po or XLIFF)"""
     95          thetargetfile = xliff.xlifffile()
     96          thetargetfile.setsourcelanguage(self.sourcelanguage)
     97          thetargetfile.settargetlanguage(self.targetlanguage)
     98          # create a header for the file
     99          bug_url = 'http://qa.openoffice.org/issues/enter_bug.cgi?%s' % \
    100                    urlencode({"subcomponent": "ui",
    101                               "comment": "",
    102                               "short_desc": "Localization issue in file: %s" % \
    103                                             theoofile.filename,
    104                               "component": "l10n",
    105                               "form_name": "enter_issue",
    106                              })
    107          # go through the oo and convert each element
    108          for theoo in theoofile.units:
    109              unitlist = self.convertelement(theoo)
    110              for unit in unitlist:
    111                  thetargetfile.addunit(unit)
    112          return thetargetfile
    113
    114
    115 -def verifyoptions(options):
    116      """verifies the commandline options"""
    117      if not options.targetlanguage:
    118          raise ValueError("You must specify the target language.")
    119
    120
    121 -def convertoo(inputfile, outputfile, templates, pot=False, sourcelanguage=None, targetlanguage=None, duplicatestyle="msgctxt", multifilestyle="single"):
    122      """reads in stdin using inputstore class, converts using convertorclass, writes to stdout"""
    123      inputstore = oo.oofile()
    124      if hasattr(inputfile, "filename"):
    125          inputfilename = inputfile.filename
    126      else:
    127          inputfilename = "(input file name not known)"
    128      inputstore.filename = inputfilename
    129      inputstore.parse(inputfile.read())
    130      if not sourcelanguage:
    131          testlangtype = targetlanguage or (inputstore and inputstore.languages[0]) or ""
    132          if testlangtype.isdigit():
    133              sourcelanguage = "01"
    134          else:
    135              sourcelanguage = "en-US"
    136      if not sourcelanguage in inputstore.languages:
    137          print >> sys.stderr, "Warning: sourcelanguage '%s' not found in inputfile '%s' (contains %s)" % (sourcelanguage, inputfilename, ", ".join(inputstore.languages))
    138      if not pot and targetlanguage and targetlanguage not in inputstore.languages:
    139          print >> sys.stderr, "Warning: targetlanguage '%s' not found in inputfile '%s' (contains %s)" % (targetlanguage, inputfilename, ", ".join(inputstore.languages))
    140      convertor = oo2xliff(sourcelanguage, targetlanguage, blankmsgstr=pot, long_keys=multifilestyle!="single")
    141      outputstore = convertor.convertstore(inputstore, duplicatestyle)
    142      if outputstore.isempty():
    143          return 0
    144      outputfile.write(str(outputstore))
    145      return 1
    146
    147
    148 -def main(argv=None):
    149      from translate.convert import convert
    150      formats = {"oo": ("xlf", convertoo), "sdf": ("xlf", convertoo)}
    151      # always treat the input as an archive unless it is a directory
    152      archiveformats = {(None, "input"): oo.oomultifile}
    153      parser = convert.ArchiveConvertOptionParser(formats, usepots=False, description=__doc__, archiveformats=archiveformats)
    154      parser.add_option("-l", "--language", dest="targetlanguage", default=None,
    155              help="set target language to extract from oo file (e.g. af-ZA)", metavar="LANG")
    156      parser.add_option("", "--source-language", dest="sourcelanguage", default=None,
    157              help="set source language code (default en-US)", metavar="LANG")
    158      parser.add_option("", "--nonrecursiveinput", dest="allowrecursiveinput", default=True, action="store_false", help="don't treat the input oo as a recursive store")
    159      parser.add_duplicates_option()
    160      parser.add_multifile_option()
    161      parser.passthrough.append("sourcelanguage")
    162      parser.passthrough.append("targetlanguage")
    163      parser.verifyoptions = verifyoptions
    164      parser.run(argv)
    165
    166
    167  if __name__ == '__main__':
    168      main()
    169