Skip to content

Commit

Permalink
In progress updates for unified translation system
Browse files Browse the repository at this point in the history
  • Loading branch information
timlinux committed Dec 17, 2014
1 parent 74913a2 commit 5876777
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 82 deletions.
10 changes: 10 additions & 0 deletions .dockerignore
@@ -0,0 +1,10 @@
.git
safe
realtime
i18n
safe_extras
scripts
docs
extras
resources
venv
54 changes: 1 addition & 53 deletions safe/__init__.py
Expand Up @@ -12,70 +12,18 @@
(at your option) any later version.
"""

__author__ = 'tim@kartoza.com'
__date__ = '10/01/2011'
__copyright__ = ('Copyright 2012, Australia Indonesia Facility for '
'Disaster Reduction')
import os

# Import the PyQt and QGIS libraries
# this import required to enable PyQt API v2
# noinspection PyUnresolvedReferences
import qgis # pylint: disable=W0611

from PyQt4.QtCore import (
QLocale,
QTranslator,
QCoreApplication,
QSettings)
from safe.common.exceptions import TranslationLoadError
from safe.utilities.i18n import locale, translation_file, load_translation


def locale():
"""Find out the two letter locale for the current session.
See if QGIS wants to override the system locale
and then see if we can get a valid translation file
for whatever locale is effectively being used.
:returns: ISO two letter code for the users's preferred locale.
:rtype: str
"""
override_flag = QSettings().value(
'locale/overrideFlag', True, type=bool)
if override_flag:
locale_name = QSettings().value('locale/userLocale', 'en_US', type=str)
else:
locale_name = QLocale.system().name()
# NOTES: we split the locale name because we need the first two
# character i.e. 'id', 'af, etc
locale_name = str(locale_name).split('_')[0]
return locale_name


def translation_file():
"""Get the path to the translation file.
:returns: Path to the translation.
"""
locale_name = locale()
root = os.path.abspath(os.path.join(os.path.dirname(__file__)))
translation_path = os.path.abspath(os.path.join(
root, os.path.pardir, 'i18n', 'inasafe_' + str(locale_name) + '.qm'))
return translation_path


def load_translation():
"""Load the translation file preferred by the user."""
path = translation_file()
if os.path.exists(path):
translator = QTranslator()
result = translator.load(path)
if not result:
message = 'Failed to load translation for %s' % path
raise TranslationLoadError(message)
# noinspection PyTypeChecker,PyCallByClass
QCoreApplication.installTranslator(translator)

load_translation()
3 changes: 1 addition & 2 deletions safe/common/minimum_needs.py
Expand Up @@ -9,10 +9,9 @@

from collections import OrderedDict
import json
import PyQt4.QtCore.QObject.tr as tr
from os.path import exists, dirname
from os import remove

from safe.utilities.i18n import tr

class MinimumNeeds(object):
"""A abstract class for handling the minimum needs.
Expand Down
44 changes: 25 additions & 19 deletions safe/common/utilities.py
Expand Up @@ -18,6 +18,8 @@
# pylint: enable=W0611

from safe.common.exceptions import VerificationError
from safe.utilities.i18n import locale


import logging
LOGGER = logging.getLogger('InaSAFE')
Expand Down Expand Up @@ -319,35 +321,39 @@ def format_int(x):
return x

# Quick solution for the moment
if lang == 'id':
if locale() == 'id':
# Replace commas with dots
s = s.replace(',', '.')
return s


def round_thousand(my_int):
def round_thousand(value):
"""Round an integer to the nearest thousand if my_int
is more than a thousand
"""
if my_int > 1000:
my_int = my_int // 1000 * 1000
return my_int
if value > 1000:
value = value // 1000 * 1000
return value


def humanize_min_max(min_value, max_value, interval):
"""Return humanize value format for max and min.
If the range between the max and min is less than one, the original
value will be returned.
Args:
* min_value
* max_value
* interval - (float): the interval between classes in the the
:param min_value: Minimum value
:type min_value: int, float
:param max_value: Maximim value
:type max_value: int, float
:param interval: The interval between classes in the
class list where the results will be used.
:type interval: float, int
Returns:
A two-tuple consisting of a string for min_value and a string for
:returns: A two-tuple consisting of a string for min_value and a string for
max_value.
:rtype: tuple
"""
current_interval = max_value - min_value
Expand All @@ -363,7 +369,7 @@ class list where the results will be used.
return humanize_min_value, humanize_max_value


def format_decimal(interval, my_number):
def format_decimal(interval, value):
"""Return formatted decimal according to interval decimal place
For example:
interval = 0.33 (two decimal places)
Expand All @@ -373,17 +379,17 @@ def format_decimal(interval, my_number):
If my_number is an integer return as is
"""
interval = get_significant_decimal(interval)
if isinstance(interval, Integral) or isinstance(my_number, Integral):
return format_int(int(my_number))
if isinstance(interval, Integral) or isinstance(value, Integral):
return format_int(int(value))
if interval != interval:
# nan
return str(my_number)
if my_number != my_number:
return str(value)
if value != value:
# nan
return str(my_number)
return str(value)
decimal_places = len(str(interval).split('.')[1])
my_number_int = str(my_number).split('.')[0]
my_number_decimal = str(my_number).split('.')[1][:decimal_places]
my_number_int = str(value).split('.')[0]
my_number_decimal = str(value).split('.')[1][:decimal_places]
if len(set(my_number_decimal)) == 1 and my_number_decimal[-1] == '0':
return my_number_int
return (format_int(int(my_number_int)) + get_decimal_separator() +
Expand Down
8 changes: 5 additions & 3 deletions safe/engine/interpolation.py
Expand Up @@ -9,11 +9,13 @@

from safe.gis.interpolation2d import interpolate_raster
from safe.common.utilities import verify
import PyQt4.QtCore.QObject.tr as tr
from safe.utilities.i18n import tr
from safe.gis.numerics import ensure_numeric
from safe.common.exceptions import InaSAFEError, BoundsError
from safe.gis.polygon import (inside_polygon,
clip_lines_by_polygons, clip_grid_by_polygons)
from safe.gis.polygon import (
inside_polygon,
clip_lines_by_polygons,
clip_grid_by_polygons)
from safe.storage.vector import Vector, convert_polygons_to_centroids
from safe.storage.utilities import geometry_type_to_string
from safe.storage.utilities import DEFAULT_ATTRIBUTE
Expand Down
File renamed without changes.
Expand Up @@ -17,7 +17,8 @@
exposure_definition,
unit_building_generic)
from safe.storage.vector import Vector
import PyQt4.QtCore.QObject.tr as tr, format_int
from safe.utilities.i18n import tr
from safe.common.utilities import format_int
from safe.common.tables import Table, TableRow
from safe.engine.interpolation import assign_hazard_values_to_exposure_data
from safe.impact_functions.impact_function_metadata import (
Expand Down
Expand Up @@ -4,7 +4,6 @@
import numpy
import logging

import PyQt4.QtCore.QObject.tr as tr
from safe.common.utilities import OrderedDict
from safe.defaults import (
get_defaults,
Expand Down Expand Up @@ -38,7 +37,7 @@
from safe.impact_functions.impact_function_metadata import (
ImpactFunctionMetadata)
from safe.gui.tools.minimum_needs.needs_profile import add_needs_parameters

from safe.utilities.i18n import tr

LOGGER = logging.getLogger('InaSAFE')

Expand Down
Expand Up @@ -31,7 +31,7 @@
)
from safe.impact_functions.earthquake.itb_earthquake_fatality_model import (
ITBFatalityFunction)
import PyQt4.QtCore.QObject.tr as tr
from safe.utilities.i18n import tr
from safe.gui.tools.minimum_needs.needs_profile import add_needs_parameters


Expand Down
51 changes: 50 additions & 1 deletion safe/utilities/i18n.py
@@ -1,4 +1,6 @@
from PyQt4.QtCore import QCoreApplication
import os
from PyQt4.QtCore import QCoreApplication, QSettings, QLocale, QTranslator
from safe import TranslationLoadError

__author__ = 'timlinux'

Expand All @@ -17,3 +19,50 @@ def tr(text):
"""
# noinspection PyCallByClass,PyTypeChecker,PyArgumentList
return QCoreApplication.translate('@default', text)


def locale():
"""Find out the two letter locale for the current session.
See if QGIS wants to override the system locale
and then see if we can get a valid translation file
for whatever locale is effectively being used.
:returns: ISO two letter code for the users's preferred locale.
:rtype: str
"""
override_flag = QSettings().value(
'locale/overrideFlag', True, type=bool)
if override_flag:
locale_name = QSettings().value('locale/userLocale', 'en_US', type=str)
else:
locale_name = QLocale.system().name()
# NOTES: we split the locale name because we need the first two
# character i.e. 'id', 'af, etc
locale_name = str(locale_name).split('_')[0]
return locale_name


def translation_file():
"""Get the path to the translation file.
:returns: Path to the translation.
"""
locale_name = locale()
root = os.path.abspath(os.path.join(os.path.dirname(__file__)))
translation_path = os.path.abspath(os.path.join(
root, os.path.pardir, 'i18n', 'inasafe_' + str(locale_name) + '.qm'))
return translation_path


def load_translation():
"""Load the translation file preferred by the user."""
path = translation_file()
if os.path.exists(path):
translator = QTranslator()
result = translator.load(path)
if not result:
message = 'Failed to load translation for %s' % path
raise TranslationLoadError(message)
# noinspection PyTypeChecker,PyCallByClass
QCoreApplication.installTranslator(translator)

0 comments on commit 5876777

Please sign in to comment.