Package miopia :: Package util :: Module ConfigurationManager
[hide private]
[frames] | no frames]

Source Code for Module miopia.util.ConfigurationManager

  1  ''' 
  2  @author: david.vilares 
  3  ''' 
  4  import os 
  5  import yaml 
  6  import re 
  7  import codecs 
  8  from collections import defaultdict 
  9   
10 -class ConfigurationManager(object):
11 ''' 12 classdocs 13 ''' 14 __config = {} 15 __parameters = {} 16 __default_conf_file = "/etc/miopia_conf.yaml"#os.path.dirname(os.path.abspath(__file__))+os.sep+os.path.pardir+os.sep+'miopia_conf.yaml' 17 #__default_conf_file = os.path.dirname(os.path.abspath(__file__))+os.sep+os.path.pardir+os.sep+'miopia_conf.yaml' 18 __uniqueInstance = None 19 __lang = 'es' 20
21 - def __new__(self, *args, **kargs):
22 """ 23 Singleton 24 """ 25 if self.__uniqueInstance is None: 26 self.__uniqueInstance = object.__new__(self, *args, **kargs) 27 return self.__uniqueInstance
28
29 - def __init__(self, 30 config_file = None, 31 yaml_config=None, lang = 'es'):
32 ''' 33 Constructor 34 ''' 35 self.__lang = lang 36 if yaml_config != None: 37 self.__config = yaml_config 38 else: 39 if config_file != None: 40 self.__config = yaml.load(open(config_file,'r')) 41 else: 42 self.__config = yaml.load(open(self.__default_conf_file,'r'))
43
44 - def getParameter(self,parameter, lang=None):
45 if lang==None: 46 lang=self.__lang 47 48 if 'config_'+lang in self.__config and parameter in self.__config['config_'+lang]: 49 value = self.__config['config_'+lang][parameter] 50 else: 51 if parameter in self.__config['default']: 52 value = self.__config['default'][parameter] 53 else: 54 value = None 55 56 #substiutute relative paths with absolute paths 57 if re.match('^path_',parameter): 58 rootpath = self.getParameter("ROOTPATH", lang) 59 if rootpath != None and value!= None: 60 value = re.sub(r'^ROOTPATH', rootpath, value) 61 62 return value
63 64 #def readLemmaD
65 - def readLemmaDict(self, path, encoding="utf-8"):
66 words = codecs.open(path,encoding=encoding).readlines() 67 68 D = defaultdict(defaultdict) 69 for word in words: 70 columns = word.split('\t') 71 if len(columns) == 3: 72 D[columns[0]][columns[1]] = columns[2][0:len(columns[2])-1] 73 return D
74
75 - def readSODict(self,path,encoding="utf-8"):
76 d = self.readTsvDict(path, encoding) 77 for k in d: 78 d[k] = float(d[k]) 79 return d
80
81 - def readTsvDict(self, path, encoding="utf-8"):
82 dictionary = {} 83 try: 84 lines = codecs.open(path,encoding=encoding).readlines() 85 for line in lines: 86 cols = line.split('\t') 87 cols = [ c.replace('\n'.encode(),''.encode()) for c in cols if c not in ['\n','']] 88 if len(cols)>0 and cols[0]!='\n': 89 if len(cols) == 1: 90 dictionary[cols[0]] = '' 91 elif len(cols) == 2: 92 dictionary[cols[0]] = cols[1] 93 else: 94 dictionary[cols[0]] = cols[1:] 95 except Exception as e: 96 print path, len(dictionary) 97 print "EXCEPTION:",e 98 return dictionary 99 return dictionary
100