Commit 36b4734bf364e99d87874d00d461c165dbf7748c

Authored by Erickson Silva
1 parent b559a77b
Exists in master and in 1 other branch devel

Deixa versao antiga como default

modules/c++/include/pyTradutor.h
@@ -1,31 +0,0 @@ @@ -1,31 +0,0 @@
1 -/**  
2 - * @author Erickson Silva  
3 - * @date 14/10/2013  
4 - *  
5 - */  
6 -  
7 -#include "Python.h"  
8 -#include "dprintf.h"  
9 -  
10 -#ifndef _PYTRADUTOR_H  
11 -#define _PYTRADUTOR_H  
12 -  
13 -namespace Tradutor {  
14 - class PyTradutor{  
15 - public:  
16 - PyTradutor();  
17 - ~PyTradutor();  
18 - char * convertStringToGlosa(const char * input);  
19 - PyObject * pName;  
20 - PyObject * pModule;  
21 - PyObject * pDict;  
22 - PyObject * pFunc;  
23 - PyObject * pArgs;  
24 - PyObject * pResult;  
25 - bool isRunning;  
26 - };  
27 -}  
28 -  
29 -#endif  
30 -  
31 -  
modules/c++/pyTradutor.cpp
@@ -1,58 +0,0 @@ @@ -1,58 +0,0 @@
1 -/**  
2 - * Essa classe invoca os metodos do tradutor em Python  
3 - * Onde efetua a tradução do texto passado por parametro  
4 - *  
5 - * @author Erickson Silva  
6 - * @date 14/10/2013  
7 - *  
8 - */  
9 -  
10 -  
11 -#include "pyTradutor.h"  
12 -  
13 -namespace Tradutor {  
14 - PyTradutor::PyTradutor() {  
15 - DPRINTF("Done!\n");  
16 - }  
17 - PyTradutor::~PyTradutor() {  
18 - Py_DECREF(pName);  
19 - Py_DECREF(pModule);  
20 - Py_DECREF(pDict);  
21 - Py_DECREF(pFunc);  
22 - Py_DECREF(pArgs);  
23 - Py_DECREF(pResult);  
24 - DDDPRINTF("PyTranslator finalized!\n");  
25 - }  
26 -  
27 -/**  
28 -* Traduz um texto (char * input) para uma string contendo a  
29 -* traducao para glosa  
30 -*  
31 -* @param input texto de entrada  
32 -* @return string contendo os tokens em glosa traduzidos.  
33 -**/  
34 - char * PyTradutor::convertStringToGlosa(const char * input) {  
35 - if(!isRunning){  
36 - Py_Initialize();  
37 - pName = PyString_FromString("ModuleTranslate");  
38 - assert(pName!=NULL);  
39 - pModule = PyImport_Import(pName);  
40 - PyErr_Print();  
41 - assert(pModule!=NULL);  
42 - pDict = PyModule_GetDict(pModule);  
43 - PyErr_Print();  
44 - assert(pDict!=NULL);  
45 - pFunc = PyDict_GetItemString(pDict, "iniciar");  
46 - PyErr_Print();  
47 - assert(pFunc!=NULL);  
48 - isRunning = 1;  
49 - }  
50 - pArgs = PyTuple_Pack(1,PyString_FromString(input));  
51 - PyErr_Print();  
52 - assert(pArgs!=NULL);  
53 - pResult = PyObject_CallObject(pFunc, pArgs);  
54 - PyErr_Print();  
55 - assert(pResult!=NULL);  
56 - return PyString_AsString(pResult);  
57 - }  
58 -}  
59 \ No newline at end of file 0 \ No newline at end of file
modules/python/translate.py
@@ -1,14 +0,0 @@ @@ -1,14 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -from Tradutor import *  
5 -  
6 -tradutor = Tradutor()  
7 -  
8 -def iniciar(x):  
9 - try:  
10 - text = x.decode("utf-8")  
11 - except:  
12 - text = x.decode("iso-8859-1")  
13 -  
14 - return tradutor.traduzir(text)  
src/AplicaRegras.py
@@ -1,161 +0,0 @@ @@ -1,161 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva  
5 -#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
6 -  
7 -#LAViD - Laboratório de Aplicações de Vídeo Digital  
8 -  
9 -from LeitorDicionarios import *  
10 -from Iterator import *  
11 -from StringAux import *  
12 -  
13 -class AplicaRegras(object):  
14 -  
15 - # inicializa todos as variaveis  
16 - def __init__(self):  
17 - self.__dicionarios = LeitorDicionarios()  
18 -  
19 - # retira artigos e preposicoes; passa verbos para infinitivo e verificar se há sinonimos  
20 - def simplificar(self, texto):  
21 - it = Iterator()  
22 - it.load(texto)  
23 - self.__ts = []  
24 - self.__verb = False  
25 - self.__adv = False;  
26 - self.__countVerb = 0  
27 - self.__countAdv = 0  
28 - while(it.hasNext()):  
29 - token = it.getAtualW()  
30 - tag = it.getAtualT()  
31 - self.__b = False  
32 - if self.__dicionarios.hasPalavraIgnorada(tag) == False: # verifica se nao eh artigo/preposicao  
33 -  
34 - #VERIFICA SE É ADVERBIO E CONTA A QUANTIDADE  
35 - if tag[:3] == "ADV":  
36 - self.__adv = True  
37 - self.__countAdv += 1  
38 -  
39 - if tag[:2] == "VB":  
40 -  
41 - #VERIFICA SE É VERBO NO INFINITIVO  
42 - if self.__dicionarios.hasVerboInfinitivo(token): # verifica se ha um verbo infinitivo desse token  
43 - verboInfinitivo = self.__dicionarios.getVerboInfinitivo(token) # se sim, adiciona numa string aux  
44 - self.__ts.append([verboInfinitivo,tag]) # caso contrario, adiciona so o verbo infinitivo msm  
45 - self.__b = True  
46 -  
47 - #VERIFICA SE É VERBO DE TEMPO E CONTA A QUANTIDADE  
48 - if tag == "VB-P" or tag == "VB-D" or tag == "VB-R":  
49 - self.__verb = True  
50 - self.__countVerb += 1  
51 -  
52 -  
53 - #VERIFICA SE É SUBTANTIVO COMUM DOS 2 GENEROS  
54 - if self.__dicionarios.hasSubst2Genero(token):  
55 - #del self.__ts[-1]  
56 - lenTicket = len(it.getAntT())  
57 - if ((self.__dicionarios.hasPalavraIgnorada(it.getAntT())) and (it.getAntT()[lenTicket-1:] == "F") or (it.getAntT()[lenTicket-3:] == "F-P")):  
58 - self.__ts.append(["MULHER ", "2GEN"])  
59 - self.__ts.append([token,tag])  
60 - else:  
61 - self.__ts.append(["HOMEM ", "2GEN"])  
62 - self.__ts.append([token,tag])  
63 - self.__b = True  
64 -  
65 - #VERIFICA SE É PLURAL  
66 - #if tag[-2:] == "-P":  
67 - # token = self.pluralAnalysis(token)  
68 -  
69 - #SE NÃO HOUVE NENHUM ALTERAÇÃO, OU SEJA, NÃO APLICOU NENHUMA REGRA, ADICIONA O TOKEN ORIGINAL  
70 - if self.__b == False: # verifica se nao encontrou nem verbo infinito ou sinonimo  
71 - self.__ts.append([token,tag])  
72 -  
73 - #SE ENCONTROU VERBO, ENTÃO ANALISA a SENTENCA NOVAMENTE (again?)  
74 - if self.__verb == True:  
75 - return self.verbalAnalysis(self.__ts)  
76 -  
77 - return self.__ts  
78 -  
79 -  
80 - # converte romano para numero  
81 - def auxConvert(self, tag):  
82 - try:  
83 - return roman_to_int(tag)  
84 - except:  
85 - return tag  
86 -  
87 - def verbalAnalysis(self, lista):  
88 - lv = []  
89 - it = Iterator()  
90 - it.load(lista)  
91 - hasFut = False  
92 - hasPas = False  
93 - count = 0  
94 - while(it.hasNext()):  
95 - token = it.getAtualW().upper()  
96 - tag = it.getAtualT()  
97 -  
98 - if(tag[:3] == "ADV"):  
99 - if (self.__dicionarios.hasTempoVerbal(token)):  
100 - it.reset()  
101 - #print "ADV: retornou lista original"  
102 - return lista  
103 -  
104 - if(tag == "VB-P"):  
105 - if (self.__countVerb > 1):  
106 - count += 1  
107 - #print "VB-P: Incrementou"  
108 - if(count == self.__countVerb):  
109 - #print "VB-P Adicionou " + token  
110 - lv.append([token,tag])  
111 - else:  
112 - #print "VB-P: retornou lista original"  
113 - it.reset()  
114 - return lista  
115 - elif(tag == "VB-D"):  
116 - count += 1  
117 - hasPas = True  
118 - #print "VB-D: Incrementou"  
119 - if(count == self.__countVerb):  
120 - #print "VB-D Adicionou " + token  
121 - lv.append([token,tag])  
122 - elif(tag == "VB-R"):  
123 - count += 1  
124 - hasFut = True  
125 - #print "VB-R: Incrementou"  
126 - if(count == self.__countVerb):  
127 - #print "VB-R Adicionou " + token  
128 - lv.append([token,tag])  
129 - else:  
130 - lv.append([token,tag])  
131 - if (hasFut):  
132 - lv.append(["FUTURO", "T-VB"])  
133 - elif (hasPas):  
134 - lv.append(["PASSADO", "T-VB"])  
135 - it.reset()  
136 - return lv  
137 -  
138 -  
139 - def pluralAnalysis(self, word):  
140 -  
141 - if(word[-3:] == "OES" or word[-2:] == "AES" or word[-2:] == "AOS"):  
142 - return word[0:-3]+"AO"  
143 - elif(word[-3:] == "RES" or word[-2:] == "ZES" or word[-2:] == "NES"):  
144 - return word[0:-2]  
145 - elif(word[-3:] == "SES"):  
146 - #TODO: Algumas palavras possuem marcações gráficas na raiz singular. Ex: Gás – Gases  
147 - return word[0:-2]  
148 - elif(word[-2:] == "NS"):  
149 - return word[0:-2]+"M"  
150 - elif(word[-3:] == "EIS"):  
151 - return word[0:-3]+"IL"  
152 - elif(word[-2:] == "IS"):  
153 - if(word[-3] == "A" or word[-3] == "E" or word[-3] == "O" or word[-3] == "U"):  
154 - return word[0:-2]+"L"  
155 - else:  
156 - return word  
157 - elif(word[-1] == "S"):  
158 - #TODO: Palavras paroxítonas ou proparoxítonas terminadas em S. Ex: lápis, vírus, tagênis, ônibus, etc  
159 - return word[0:-1]  
160 - else:  
161 - return word  
162 \ No newline at end of file 0 \ No newline at end of file
src/AplicaSinonimos.py
@@ -1,48 +0,0 @@ @@ -1,48 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva  
5 -#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
6 -  
7 -#LAViD - Laboratório de Aplicações de Vídeo Digital  
8 -  
9 -import os, csv, sys  
10 -from nltk.tree import *  
11 -from LeitorDicionarios import *  
12 -  
13 -class AplicaSinonimos(object):  
14 -  
15 - # Define e inicializa os atributos  
16 - def __init__(self):  
17 - self.__dicionarios = LeitorDicionarios()  
18 -  
19 - def sinonimosMorfologico(self, texto):  
20 - lista = texto  
21 - for i, elem in enumerate(lista):  
22 - token = self.verificaPalavra(elem[0])  
23 - listmp = list(elem)  
24 - listmp[0] = token  
25 - lista[i] = listmp  
26 - return lista  
27 -  
28 -  
29 - def dicionarioSinonimoFolhas(self, folhas):  
30 - dic = {}  
31 - for f in folhas:  
32 - token = self.verificaPalavra(f)  
33 - dic[f] = token  
34 - return dic  
35 -  
36 - def sinonimosSintatico(self, texto):  
37 - folhas = Tree.leaves(texto)  
38 - dic = self.dicionarioSinonimoFolhas(folhas)  
39 - stringTree = str(texto)  
40 - for t in folhas:  
41 - stringTree.replace(t, dic[t])  
42 - tree = Tree.fromstring(stringTree, brackets='()')  
43 - return tree  
44 -  
45 - def verificaPalavra(self, token):  
46 - if self.__dicionarios.hasSinonimo(token):  
47 - return self.__dicionarios.getSinonimo(token)  
48 - return token  
49 \ No newline at end of file 0 \ No newline at end of file
src/AplicadorRegras.py 0 → 100644
@@ -0,0 +1,60 @@ @@ -0,0 +1,60 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  5 +
  6 +import xml.etree.ElementTree as ET
  7 +import os
  8 +
  9 +class AplicadorRegras(object):
  10 +
  11 + # inicializacao das variaves
  12 + def __init__(self):
  13 + self.__tree = ET.parse('vlibras_user/vlibras-core/data/regras.xml')
  14 + self.__root = self.__tree.getroot()
  15 + self.__tAux = []
  16 + self.__dAux = {}
  17 +
  18 + # aplica as regras
  19 + def aplicarRegras(self, ts):
  20 + self.__n = len(ts) # quantidade de tokens
  21 + for i in range(0,self.__n):
  22 + self.__tAux.append(self.__n)
  23 + self.__name = self.getNameRule(ts) # todos os etiquetadores numa so string (ver linha 35)
  24 + for morpho in self.__root:
  25 + for rule in morpho.findall('rule'): # procura a tag rule
  26 + if rule.get('name') == self.__name: # procura o atributo name na tag rule (ver linha 17)
  27 + if rule.find('active').text == "true": # verifica se a regra esta ativa
  28 + self.__c = 0
  29 + for classe in rule.iter('class'): # for nas tags class
  30 + self.__dAux[self.__c] = int(classe.find('newpos').text) # preenche dicionario com a ordem atual e futura das palavras
  31 + self.__c += 1
  32 + self.__c = 0
  33 + for w,t in ts:
  34 + i = self.__dAux.get(self.__c) # pega o indice de onde ficara a palavra
  35 + self.__tAux[i] = ([w,t]) # preenche a lista com a palavra+etiqueta na posicao correta (segundo o arquivo regras.xml)
  36 + self.__c += 1
  37 + return self.__tAux # retorna nova lista (ordenada)
  38 + return ts # retorna a lista sem alteracoes (nao existe regra)
  39 +
  40 + def getNameRule(self, ts):
  41 + self.__name = ""
  42 + for w,t in ts:
  43 + if t[:2] != "VB":
  44 + self.__name += t
  45 + else:
  46 + self.__name += t[:2]
  47 + return self.__name
  48 +
  49 +
  50 +
  51 +
  52 +
  53 +
  54 +
  55 +
  56 +
  57 +
  58 +
  59 +
  60 +
src/Classificador.py 0 → 100644
@@ -0,0 +1,44 @@ @@ -0,0 +1,44 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  5 +
  6 +from Aelius import AnotaCorpus, Toqueniza, Extras
  7 +
  8 +class Classificador(object):
  9 +
  10 + # inicializacao das variaveis
  11 + def __init__(self):
  12 + self.__h = Extras.carrega("AeliusHunPos") # carrega o modelo de idioma (passado por parametro ao instanciar)
  13 +
  14 + def anotaSentencas(self, str):
  15 + self.__t = ""
  16 + self.__tokens = ""
  17 + #try:
  18 + # tokenizae
  19 + self.__tokens = Toqueniza.TOK_PORT.tokenize(str)
  20 +
  21 + # realiza a classificacao morfologica
  22 + self.__t = AnotaCorpus.anota_sentencas([self.__tokens],self.__h,'hunpos')
  23 +
  24 + return self.listClean(self.__t)
  25 + #except:
  26 + # print "Erro ao efetuar a classificação morfologica."
  27 +
  28 +
  29 + def listClean(self, l):
  30 + lClean = []
  31 + for w,t in l[0]:
  32 + lClean.append([w,t])
  33 + return lClean
  34 +
  35 + # faz a impressao (usado apenas pra testes)
  36 + def imprimeSentencas(self):
  37 + for w,t in self.t[0]:
  38 + print "%s_%s " % (w,t),
  39 +
  40 +
  41 +
  42 +
  43 +
  44 +
src/Iterator.py
1 #!/usr/bin/python 1 #!/usr/bin/python
2 # -*- coding: utf-8 -*- 2 # -*- coding: utf-8 -*-
3 3
4 -#Autor: Erickson Silva  
5 -#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com> 4 +#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
6 5
7 -#LAViD - Laboratório de Aplicações de Vídeo Digital 6 +from StringAux import *
8 7
9 class Iterator(object): 8 class Iterator(object):
10 9
@@ -36,22 +35,22 @@ class Iterator(object): @@ -36,22 +35,22 @@ class Iterator(object):
36 return self.__list[self.count] 35 return self.__list[self.count]
37 36
38 def getAtualW(self): 37 def getAtualW(self):
39 - return self.getToken(0)[0].upper() 38 + return remover_acentos(self.getToken(0)[0].upper().encode('utf-8'))
40 39
41 def getAtualT(self): 40 def getAtualT(self):
42 - return self.getToken(0)[1] 41 + return self.getToken(0)[1].upper().encode('utf-8')
43 42
44 def getProxW(self): 43 def getProxW(self):
45 - return self.getToken("+")[0].upper() 44 + return remover_acentos(self.getToken("+")[0].upper().encode('utf-8'))
46 45
47 def getProxT(self): 46 def getProxT(self):
48 - return self.getToken("+")[1] 47 + return self.getToken("+")[1].upper().encode('utf-8')
49 48
50 def getAntW(self): 49 def getAntW(self):
51 - return self.getToken("-")[0].upper() 50 + return remover_acentos(self.getToken("-")[0].upper().encode('utf-8'))
52 51
53 def getAntT(self): 52 def getAntT(self):
54 - return self.getToken("-")[1] 53 + return self.getToken("-")[1].upper().encode('utf-8')
55 54
56 def hasNext(self): 55 def hasNext(self):
57 if(self.count < self.size-1): 56 if(self.count < self.size-1):
src/LeitorDicionarios.py
@@ -1,139 +0,0 @@ @@ -1,139 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva  
5 -#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
6 -  
7 -#LAViD - Laboratório de Aplicações de Vídeo Digital  
8 -  
9 -import os, csv, sys  
10 -  
11 -class LeitorDicionarios(object):  
12 - #_iInstance = None  
13 -  
14 - #class Singleton:  
15 - # def __init__(self):  
16 - # self.LeitorDicionarios = None  
17 -  
18 - #def __init__( self ):  
19 - # if LeitorDicionarios._iInstance is None:  
20 - # LeitorDicionarios._iInstance = LeitorDicionarios.Singleton()  
21 -  
22 - # self._EventHandler_instance = LeitorDicionarios._iInstance  
23 -  
24 - #def __getattr__(self, aAttr):  
25 - # return getattr(self._iInstance, aAttr)  
26 -  
27 - #def __setattr__(self, aAttr, aValue):  
28 - # return setattr(self._iInstance, aAttr, aValue)  
29 -  
30 - # Define e inicializa os atributos  
31 - def __init__(self):  
32 - self.__path = "/home/erickson/vlibras-translate/data/"  
33 - self.__dicInf = {}  
34 - self.__dicSin = {}  
35 - self.__dicWords = {}  
36 - self.__dic2Gen = {}  
37 - self.__dicTemVerbs = {}  
38 - self.__fileDic = ''  
39 - self.carregarVerbosInfinitivos()  
40 - self.carregarSinonimos()  
41 - self.carregarPalavrasIgnoradas()  
42 - self.carregarSubst2Generos()  
43 - self.carregarTemposVerbais()  
44 -  
45 - # Abre o self.__fileDic que contem os verbos no infinitivo e preenche o dicionario com os mesmos  
46 - def carregarVerbosInfinitivos(self):  
47 - try:  
48 - self.__fileDic = csv.reader(open(self.__path+"dicPortGlosa.csv"), delimiter=";")  
49 - except IOError, (errno, strerror):  
50 - print "I/O error(%s): %s" % (errno, strerror)  
51 - print "carregarVerbosInfinitivos"  
52 -  
53 - for row in self.__fileDic:  
54 - if row[1] != "":  
55 - try:  
56 - self.__dicInf[row[0].decode("utf-8")] = row[1].decode("utf-8")  
57 - except UnicodeDecodeError:  
58 - self.__dicInf[row[0].decode('iso8859-1').encode('utf-8')] = row[1].decode('iso8859-1').encode('utf-8')  
59 -  
60 - # Abre o self.__fileDic que contem os sinonimos e preenche o dicionario com os mesmos  
61 - def carregarSinonimos(self):  
62 - try:  
63 - self.__fileDic = csv.reader(open(self.__path+"portuguesGlosa.csv"), delimiter=";")  
64 - except IOError, (errno, strerror):  
65 - print "I/O error(%s): %s" % (errno, strerror)  
66 - print "carregarSinonimos"  
67 -  
68 - for row in self.__fileDic:  
69 - if row[1] != "":  
70 - self.__dicSin[row[0].decode("utf-8")] = row[1].decode("utf-8")  
71 -  
72 -  
73 - # Abre o self.__fileDic que contem os tempos verbais  
74 - def carregarTemposVerbais(self):  
75 - try:  
76 - self.__fileDic = csv.reader(open(self.__path+"temposVerbais.csv"), delimiter=";")  
77 - except IOError, (errno, strerror):  
78 - print "I/O error(%s): %s" % (errno, strerror)  
79 - print "carregarTemposVerbais"  
80 -  
81 - for row in self.__fileDic:  
82 - self.__dicTemVerbs[row[0].decode("utf-8")] = row[0].decode("utf-8")  
83 -  
84 - # Abre o self.__fileDic que contem os artigos e preposicoes de acordo com o modelo de idioma passado na chamada e preenche o dicionario com os mesmos  
85 - def carregarPalavrasIgnoradas(self):  
86 - try:  
87 - self.__fileDic = csv.reader(open(self.__path+"hWordsRemove.csv"), delimiter=";")  
88 - except IOError, (errno, strerror):  
89 - print "I/O error(%s): %s" % (errno, strerror)  
90 - print "carregarPalavrasIgnoradas"  
91 -  
92 - for row in self.__fileDic:  
93 - self.__dicWords[row[0].decode("utf-8")] = row[0].decode("utf-8")  
94 -  
95 - # Abre o self.__fileDic que contem os substantivos que sao comuns dos 2 generos e preenche o dicionario com os mesmos  
96 - def carregarSubst2Generos(self):  
97 - try:  
98 - self.__fileDic = csv.reader(open(self.__path+"subs2Generos.csv"), delimiter=";")  
99 - except IOError, (errno, strerror):  
100 - print "I/O error(%s): %s" % (errno, strerror)  
101 - print "carregarSubst2Generos"  
102 -  
103 - for row in self.__fileDic:  
104 - self.__dic2Gen[row[0].decode("utf-8")] = row[0].decode("utf-8")  
105 -  
106 - # Retorna o dicionario dos verbos no infinitivo  
107 - def getVerboInfinitivo(self, token):  
108 - return self.__dicInf[token]  
109 -  
110 - # Retorna o dicionario dos sinonimos  
111 - def getSinonimo(self, token):  
112 - return self.__dicSin[token]  
113 -  
114 - # Retorna o dicionario dos artigos e preposicoes a serem removidos pelo simplificador  
115 - def getPalavraIgnorada(self, token):  
116 - return self.__dicWords[token]  
117 -  
118 - # Retorna o dicionario dos substantivos a serem analisados pelo simplificador  
119 - def getSubst2Generos(self, token):  
120 - return self.__dic2Gen[token]  
121 -  
122 - # Retorna o dicionario dos tempos verbais  
123 - def getTempoVerbal(self, token):  
124 - return self.__dicTemVerbs[token]  
125 -  
126 - def hasVerboInfinitivo(self, token):  
127 - return self.__dicInf.has_key(token)  
128 -  
129 - def hasSinonimo(self, token):  
130 - return self.__dicSin.has_key(token)  
131 -  
132 - def hasPalavraIgnorada(self, token):  
133 - return self.__dicWords.has_key(token)  
134 -  
135 - def hasSubst2Genero(self, token):  
136 - return self.__dic2Gen.has_key(token)  
137 -  
138 - def hasTempoVerbal(self, token):  
139 - return self.__dicTemVerbs.has_key(token)  
src/ModuleTranslate.py 0 → 100644
@@ -0,0 +1,14 @@ @@ -0,0 +1,14 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +from Tradutor import *
  5 +
  6 +tradutor = Tradutor()
  7 +
  8 +def iniciar(x):
  9 + try:
  10 + text = x.decode("utf-8")
  11 + except:
  12 + text = x.decode("iso-8859-1")
  13 +
  14 + return tradutor.traduzir(text)
src/Output.py 0 → 100644
@@ -0,0 +1,24 @@ @@ -0,0 +1,24 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  5 +
  6 +import sys
  7 +from Iterator import *
  8 +from StringAux import *
  9 +
  10 +class Output(object):
  11 +
  12 + # inicializa a variavel com o valor passado por paramentro ao instanciar
  13 + def __init__(self):
  14 + self.it = Iterator()
  15 +
  16 + # executa a saida
  17 + def executeOut(self, ts):
  18 + self.__glosa = []
  19 + self.it.load(ts)
  20 + while(self.it.hasNext()):
  21 + self.__glosa.append(self.it.getAtualW())
  22 + self.it.reset()
  23 + return ' '.join(self.__glosa)
  24 +
src/Simplificador.py 0 → 100644
@@ -0,0 +1,164 @@ @@ -0,0 +1,164 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  5 +
  6 +from WorkCSV import *
  7 +from Iterator import *
  8 +from StringAux import *
  9 +
  10 +class Simplificador(object):
  11 +
  12 + # inicializa todos as variaveis
  13 + def __init__(self):
  14 + self.it = Iterator()
  15 + self.__csv = WorkCSV()
  16 + self.__dicInf = {}
  17 + self.__dicSin = {}
  18 + self.__dicWords = {}
  19 + self.__dic2Gen = {}
  20 + self.__dicTemVerbs = {}
  21 + self.executeWorkCSV()
  22 +
  23 + # retira artigos e preposicoes; passa verbos para infinitivo e verificar se há sinonimos
  24 + def simplificar(self, texto):
  25 + self.__ts = []
  26 + self.it.load(texto)
  27 + self.__verb = False
  28 + self.__adv = False;
  29 + self.__countVerb = 0
  30 + self.__countAdv = 0
  31 + countWords = 0
  32 + while(self.it.hasNext()):
  33 + w = self.auxConvert(self.it.getAtualW())
  34 + t = self.it.getAtualT()
  35 + self.__b = False
  36 + if self.__dicWords.has_key(t) == False: # verifica se nao eh artigo/preposicao
  37 + wu = w.upper() # deixa o token maiusculo
  38 + #if t[:2] == "VB":
  39 + if t[-2:] == "-P":
  40 + wu = self.pluralAnalysis(w)
  41 + if t == "VB-P" or t == "VB-D" or t == "VB-R":
  42 + self.__verb = True
  43 + self.__countVerb += 1
  44 + if t[:3] == "ADV":
  45 + self.__adv = True
  46 + self.__countAdv += 1
  47 + if self.__dicInf.has_key(wu): # verifica se ha um verbo infinitivo desse token
  48 + sAux = self.__dicInf[wu] # se sim, adiciona numa string aux
  49 + if self.__dicSin.has_key(sAux): # verifica se ha um sinonimo para esse verbo infinitivo
  50 + self.__ts.append([self.__dicSin[sAux],t]) # se sim, entao adiciona na lista
  51 + self.__b = True
  52 + else:
  53 + self.__ts.append([sAux,t]) # caso contrario, adiciona so o verbo infinitivo msm
  54 + self.__b = True
  55 + if self.__b == False and self.__dicSin.has_key(wu): # verifica se nao foi encontrado verbo infinitivo e se ha sinonimo
  56 + self.__ts.append([self.__dicSin[wu],t]) # adiciona na o sinonimo lista
  57 + self.__b = True
  58 +
  59 + if self.__dic2Gen.has_key(wu):
  60 + del self.__ts[-1]
  61 + lenTicket = len(self.it.getAntT())
  62 + if ((self.__dicWords.has_key(self.it.getAntT())) and (self.it.getAntT()[lenTicket-1:] == "F") or (self.it.getAntT()[lenTicket-3:] == "F-P")):
  63 + self.__ts.append(["MULHER " + wu,t])
  64 + else:
  65 + self.__ts.append(["HOMEM " + wu,t])
  66 + self.__b = True
  67 + if self.__b == False: # verifica se nao encontrou nem verbo infinito ou sinonimo
  68 + self.__ts.append([wu,t])
  69 + countWords += 1
  70 + self.it.reset()
  71 + if self.__verb == True:
  72 + return self.verbalAnalysis(self.__ts)
  73 + return self.__ts
  74 +
  75 + # cria e recupera todos os dicionarios (verbos inf., sinonimos e artigos/preposicoes)
  76 + def executeWorkCSV(self):
  77 + self.__dicInf = self.__csv.getDicInf()
  78 + self.__dicSin = self.__csv.getDicSin()
  79 + self.__dicWords = self.__csv.getDicWords()
  80 + self.__dic2Gen = self.__csv.getDic2Gen()
  81 + self.__dicTemVerbs = self.__csv.getDicTemVerbs()
  82 +
  83 + # converte romano para numero
  84 + def auxConvert(self, t):
  85 + try:
  86 + return roman_to_int(t)
  87 + except:
  88 + return t
  89 +
  90 +
  91 + def verbalAnalysis(self, lista):
  92 + lv = []
  93 + self.it.load(lista)
  94 + hasFut = False
  95 + hasPas = False
  96 + count = 0
  97 + while(self.it.hasNext()):
  98 + w = self.it.getAtualW().upper()
  99 + t = self.it.getAtualT()
  100 +
  101 + if(t[:3] == "ADV"):
  102 + if (self.__dicTemVerbs.has_key(w)):
  103 + self.it.reset()
  104 + #print "ADV: retornou lista original"
  105 + return lista
  106 +
  107 + if(t == "VB-P"):
  108 + if (self.__countVerb > 1):
  109 + count += 1
  110 + #print "VB-P: Incrementou"
  111 + if(count == self.__countVerb):
  112 + #print "VB-P Adicionou " + w
  113 + lv.append([w,t])
  114 + else:
  115 + #print "VB-P: retornou lista original"
  116 + self.it.reset()
  117 + return lista
  118 + elif(t == "VB-D"):
  119 + count += 1
  120 + hasPas = True
  121 + #print "VB-D: Incrementou"
  122 + if(count == self.__countVerb):
  123 + #print "VB-D Adicionou " + w
  124 + lv.append([w,t])
  125 + elif(t == "VB-R"):
  126 + count += 1
  127 + hasFut = True
  128 + #print "VB-R: Incrementou"
  129 + if(count == self.__countVerb):
  130 + #print "VB-R Adicionou " + w
  131 + lv.append([w,t])
  132 + else:
  133 + lv.append([w,t])
  134 + if (hasFut):
  135 + lv.append(["FUTURO", "TVB"])
  136 + elif (hasPas):
  137 + lv.append(["PASSADO", "TVB"])
  138 + self.it.reset()
  139 + return lv
  140 +
  141 +
  142 + def pluralAnalysis(self, word):
  143 +
  144 + if(word[-3:] == "OES" or word[-2:] == "AES" or word[-2:] == "AOS"):
  145 + return word[0:-3]+"AO"
  146 + elif(word[-3:] == "RES" or word[-2:] == "ZES" or word[-2:] == "NES"):
  147 + return word[0:-2]
  148 + elif(word[-3:] == "SES"):
  149 + #TODO: Algumas palavras possuem marcações gráficas na raiz singular. Ex: Gás – Gases
  150 + return word[0:-2]
  151 + elif(word[-2:] == "NS"):
  152 + return word[0:-2]+"M"
  153 + elif(word[-3:] == "EIS"):
  154 + return word[0:-3]+"IL"
  155 + elif(word[-2:] == "IS"):
  156 + if(word[-3] == "A" or word[-3] == "E" or word[-3] == "O" or word[-3] == "U"):
  157 + return word[0:-2]+"L"
  158 + else:
  159 + return word
  160 + elif(word[-1] == "S"):
  161 + #TODO: Palavras paroxítonas ou proparoxítonas terminadas em S. Ex: lápis, vírus, tênis, ônibus, etc
  162 + return word[0:-1]
  163 + else:
  164 + return word
0 \ No newline at end of file 165 \ No newline at end of file
src/StringAux.py 0 → 100644
@@ -0,0 +1,83 @@ @@ -0,0 +1,83 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +from unicodedata import normalize
  5 +
  6 +ext = {1:"um", 2:"dois", 3:"três", 4:"quatro", 5:"cinco", 6:"seis", 7:"sete", 8:"oito", 9:"nove", 0:"zero"}
  7 +
  8 +def extenso(n):
  9 + strn = str(n)
  10 + sizen = len(strn)
  11 + tokens = []
  12 + for i in range (0, sizen):
  13 + x = int(strn[i])
  14 + tokens.append(ext[x])
  15 + return ' '.join(tokens)
  16 +
  17 +"""
  18 +def extenso(n):
  19 + strn = str(n)
  20 + sizen = len(strn)
  21 + tokens = []
  22 + for i in range (0, sizen):
  23 + tokens.append(strn[i])
  24 + return ' '.join(tokens)
  25 +"""
  26 +
  27 +def remover_acentos(txt):
  28 +
  29 + """ Devolve cópia de uma str substituindo os caracteres
  30 + acentuados pelos seus equivalentes não acentuados.
  31 +
  32 + ATENÇÃO: carateres gráficos não ASCII e não alfa-numéricos,
  33 + tais como bullets, travessões, aspas assimétricas, etc.
  34 + são simplesmente removidos!
  35 +
  36 + >>> remover_acentos('[ACENTUAÇÃO] ç: áàãâä! éèêë? íì&#297;îï, óòõôö; úù&#361;ûü.')
  37 + '[ACENTUACAO] c: aaaaa! eeee? iiiii, ooooo; uuuuu.'
  38 +
  39 + """
  40 + try:
  41 + return normalize('NFKD', txt.decode('utf-8')).encode('ASCII','ignore')
  42 + except:
  43 + return normalize('NFKD', txt.decode('iso-8859-1')).encode('ASCII','ignore')
  44 +
  45 +
  46 +def roman_to_int(input):
  47 + if not isinstance(input, type("")):
  48 + raise TypeError, "expected string, got %s" % type(input)
  49 + input = input.upper( )
  50 + nums = {'M':1000,
  51 + 'D':500,
  52 + 'C':100,
  53 + 'L':50,
  54 + 'X':10,
  55 + 'V':5,
  56 + 'I':1}
  57 + sum = 0
  58 + for i in range(len(input)):
  59 + try:
  60 + value = nums[input[i]]
  61 + if i+1 < len(input) and nums[input[i+1]] > value:
  62 + sum -= value
  63 + else: sum += value
  64 + except KeyError:
  65 + raise ValueError, 'input is not a valid Roman numeral: %s' % input
  66 +
  67 + if int_to_roman(sum) == input: return sum
  68 + else: raise ValueError, 'input is not a valid Roman numeral: %s' % input
  69 +
  70 +def int_to_roman(input):
  71 + if not isinstance(input, type(1)):
  72 + raise TypeError, "expected integer, got %s" % type(input)
  73 + if not 0 < input < 4000:
  74 + raise ValueError, "Argument must be between 1 and 3999"
  75 + ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
  76 + nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
  77 + result = []
  78 +
  79 + for i in range(len(ints)):
  80 + count = int(input / ints[i])
  81 + result.append(nums[i] * count)
  82 + input -= ints[i] * count
  83 + return ''.join(result)
0 \ No newline at end of file 84 \ No newline at end of file
src/Tradutor.py
1 #!/usr/bin/python 1 #!/usr/bin/python
2 # -*- coding: utf-8 -*- 2 # -*- coding: utf-8 -*-
3 3
4 -#Autor: Erickson Silva  
5 -#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com> 4 +#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
6 5
7 -#LAViD - Laboratório de Aplicações de Vídeo Digital 6 +from Classificador import *
  7 +from Simplificador import *
  8 +from AplicadorRegras import *
  9 +from Output import *
  10 +from StringAux import *
8 11
9 -import alexp  
10 -from AplicaSinonimos import *  
11 -from AplicaRegras import *  
12 12
13 -sin = AplicaSinonimos()  
14 -reg = AplicaRegras() 13 +class Tradutor(object):
15 14
  15 + def __init__(self):
  16 + #instanciando os objetos
  17 + self.__classificador = Classificador()
  18 + self.__simplificador = Simplificador()
  19 + self.__regras = AplicadorRegras()
  20 + self.__out = Output()
16 21
17 -def iniciarTraducao(texto):  
18 - textoDividido = texto.split(".")  
19 - for w in textoDividido:  
20 - if len(w) > 0:  
21 - gerarAnalise(w)  
22 22
23 -def gerarAnalise(sentenca):  
24 - '''tokens = alexp.toqueniza(sentenca)  
25 - etiquetadas = alexp.etiquetaSentenca(tokens)  
26 - analiseMorf = analiseMorfologica(etiquetadas)  
27 - print analiseMorf''' 23 + def traduzir(self, txt):
  24 + self.__tr = None
28 25
29 - analise = alexp.run(sentenca)  
30 -  
31 - if (isinstance(analise,type(None))):  
32 - analise = alexp.getAnaliseMorfologica()  
33 - print analiseMorfologica(analise)  
34 - else:  
35 - print analiseSintatica(analise) 26 + #faz a tokenizacao e a classificacao
  27 + self.__t = self.__classificador.anotaSentencas(txt)
36 28
  29 + #retira artigos e preposicoes
  30 + self.__ts = self.__simplificador.simplificar(self.__t)
  31 + self.__t = None
  32 +
  33 + #aplica as regras
  34 + #self.__tr = self.__regras.aplicarRegras(self.__ts)
  35 + #self.__ts = None
37 36
38 -def analiseMorfologica(sentenca):  
39 - proc = reg.simplificar(sentenca)  
40 - return sin.sinonimosMorfologico(proc)  
41 -  
42 -  
43 -def analiseSintatica(sentenca):  
44 - analise = sin.sinonimosSintatico(sentenca)  
45 - return analise  
46 \ No newline at end of file 37 \ No newline at end of file
  38 + #executa a saida
  39 + return self.__out.executeOut(self.__ts).encode("utf-8")
src/WorkCSV.py 0 → 100644
@@ -0,0 +1,125 @@ @@ -0,0 +1,125 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  5 +
  6 +import os, csv, sys
  7 +
  8 +class WorkCSV(object):
  9 + _iInstance = None
  10 +
  11 + class Singleton:
  12 + def __init__(self):
  13 + self.LeitorDicionarios = None
  14 +
  15 + def __init__( self ):
  16 + if LeitorDicionarios._iInstance is None:
  17 + LeitorDicionarios._iInstance = LeitorDicionarios.Singleton()
  18 +
  19 + self._EventHandler_instance = LeitorDicionarios._iInstance
  20 +
  21 + def __getattr__(self, aAttr):
  22 + return getattr(self._iInstance, aAttr)
  23 +
  24 + def __setattr__(self, aAttr, aValue):
  25 + return setattr(self._iInstance, aAttr, aValue)
  26 +
  27 + # Define e inicializa os atributos
  28 + def __init__(self):
  29 + self.__path = "vlibras_user/vlibras-core/data/"
  30 + self.__fileInf = ''
  31 + self.__dicInf = {}
  32 + self.__fileSin = ''
  33 + self.__dicSin = {}
  34 + self.__fileWords = ''
  35 + self.__dicWords = {}
  36 + self.__file2Gen = ''
  37 + self.__dic2Gen = {}
  38 + self.__fileTemVerbs = ''
  39 + self.__dicTemVerbs = {}
  40 + self.createDicInf()
  41 + self.createDicSin()
  42 + self.createDicWords()
  43 + self.createDic2Gen()
  44 + self.createDicTemVerbs()
  45 +
  46 + # Abre o arquivo que contem os verbos no infinitivo e preenche o dicionario com os mesmos
  47 + def createDicInf(self):
  48 + try:
  49 + self.__fileInf = csv.reader(open(self.__path+"dicPortGlosa.csv"), delimiter=";")
  50 + except IOError, (errno, strerror):
  51 + print "I/O error(%s): %s" % (errno, strerror)
  52 + print "createDicInf"
  53 +
  54 + for row in self.__fileInf:
  55 + if row[1] != "":
  56 + try:
  57 + self.__dicInf[row[0].decode("utf-8")] = row[1].decode("utf-8")
  58 + except UnicodeDecodeError:
  59 + self.__dicInf[row[0].decode('iso8859-1').encode('utf-8')] = row[1].decode('iso8859-1').encode('utf-8')
  60 +
  61 + # Abre o arquivo que contem os sinonimos e preenche o dicionario com os mesmos
  62 + def createDicSin(self):
  63 + try:
  64 + self.__fileSin = csv.reader(open(self.__path+"portuguesGlosa.csv"), delimiter=";")
  65 + except IOError, (errno, strerror):
  66 + print "I/O error(%s): %s" % (errno, strerror)
  67 + print "createDicSin"
  68 +
  69 + for row in self.__fileSin:
  70 + if row[1] != "":
  71 + self.__dicSin[row[0].decode("utf-8")] = row[1].decode("utf-8")
  72 +
  73 +
  74 + # Abre o arquivo que contem os tempos verbais
  75 + def createDicTemVerbs(self):
  76 + try:
  77 + self.__fileTemVerbs = csv.reader(open(self.__path+"temposVerbais.csv"), delimiter=";")
  78 + except IOError, (errno, strerror):
  79 + print "I/O error(%s): %s" % (errno, strerror)
  80 + print "createDicTemVerbs"
  81 +
  82 + for row in self.__fileTemVerbs:
  83 + self.__dicTemVerbs[row[0].decode("utf-8")] = row[0].decode("utf-8")
  84 +
  85 + # Abre o arquivo que contem os artigos e preposicoes de acordo com o modelo de idioma passado na chamada e preenche o dicionario com os mesmos
  86 + def createDicWords(self):
  87 + try:
  88 + self.__fileWords = csv.reader(open(self.__path+"hWordsRemove.csv"), delimiter=";")
  89 + except IOError, (errno, strerror):
  90 + print "I/O error(%s): %s" % (errno, strerror)
  91 + print "createDicWords"
  92 +
  93 + for row in self.__fileWords:
  94 + self.__dicWords[row[0].decode("utf-8")] = row[0].decode("utf-8")
  95 +
  96 + # Abre o arquivo que contem os substantivos que sao comuns dos 2 generos e preenche o dicionario com os mesmos
  97 + def createDic2Gen(self):
  98 + try:
  99 + self.__file2Gen = csv.reader(open(self.__path+"subs2Generos.csv"), delimiter=";")
  100 + except IOError, (errno, strerror):
  101 + print "I/O error(%s): %s" % (errno, strerror)
  102 + print "createDic2Gen"
  103 +
  104 + for row in self.__file2Gen:
  105 + self.__dic2Gen[row[0].decode("utf-8")] = row[0].decode("utf-8")
  106 +
  107 + # Retorna o dicionario dos verbos no infinitivo
  108 + def getDicInf(self):
  109 + return self.__dicInf
  110 +
  111 + # Retorna o dicionario dos sinonimos
  112 + def getDicSin(self):
  113 + return self.__dicSin
  114 +
  115 + # Retorna o dicionario dos artigos e preposicoes a serem removidos pelo simplificador
  116 + def getDicWords(self):
  117 + return self.__dicWords
  118 +
  119 + # Retorna o dicionario dos substantivos a serem analisados pelo simplificador
  120 + def getDic2Gen(self):
  121 + return self.__dic2Gen
  122 +
  123 + # Retorna o dicionario dos tempos verbais
  124 + def getDicTemVerbs(self):
  125 + return self.__dicTemVerbs
0 \ No newline at end of file 126 \ No newline at end of file
src/alexp.py
@@ -1,133 +0,0 @@ @@ -1,133 +0,0 @@
1 -#! /usr/bin/env python2.6  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#---------------------------------  
5 -  
6 -# Editado:  
7 -  
8 -#Autor: Erickson Silva  
9 -#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
10 -  
11 -#LAViD - Laboratório de Aplicações de Vídeo Digital  
12 -  
13 -#---------------------------------  
14 -  
15 -  
16 -# Donatus Brazilian Portuguese Parser  
17 -#  
18 -# Copyright (C) 2010-2013 Leonel F. de Alencar  
19 -#  
20 -# Author: Leonel F. de Alencar <leonel.de.alencar@ufc.br>  
21 -# Homepage: <http://www.leonel.profusehost.net/>  
22 -#  
23 -# Project's URL: <http://sourceforge.net/projects/donatus/>  
24 -# For license information, see LICENSE.TXT  
25 -#  
26 -# $Id: alexp.py $  
27 -  
28 -"""Este módulo contém funções que permitem utilizar o Aelius para etiquetar uma sentença, construindo entradas lexicais com base nas etiquetas atribuídas às palavras da sentença. Essas entradas lexicais são integradas em uma gramática CFG dada, que é transformada em um parser, utilizado para gerar uma árvore de estrutura sintagmática da sentença.  
29 -"""  
30 -import re, string,nltk,os  
31 -from Aelius.Extras import carrega  
32 -from Aelius import AnotaCorpus  
33 -  
34 -# definição de algumas variáveis globais para  
35 -# facilitar utilização das diferentes funções do módulo  
36 -  
37 -# sintaxe default em subpasta de nltk_data  
38 -DIR="/vlibras-translate/data/cfg.syn.nltk"  
39 -  
40 -# eventualmente será preciso incluir aqui outros sinais  
41 -# de pontuação, como o travessão  
42 -PUNCT=string.punctuation  
43 -  
44 -SENTENCA_ANOTADA=""  
45 -  
46 -  
47 -def toqueniza(s):  
48 - """Decodifica string utilizando utf-8, retornando uma lista de tokens em unicode.  
49 - """  
50 - decodificada=s.decode("utf-8")  
51 - return AnotaCorpus.TOK_PORT.tokenize(decodificada)  
52 -  
53 -def getAnaliseMorfologica():  
54 - return SENTENCA_ANOTADA  
55 -  
56 -def etiquetaSentenca(s):  
57 - """Aplica um dos etiquetadores do Aelius na etiquetagem da sentença dada como lista de tokens.  
58 - """  
59 - etiquetador = list((carrega("AeliusHunPos"),"nltk"))  
60 - anotada = AnotaCorpus.anota_sentencas([s],etiquetador,"hunpos")[0]  
61 - return anotada  
62 -  
63 -def geraEntradasLexicais(lista):  
64 - """Gera entradas lexicais no formato CFG do NLTK a partir de lista de pares constituídos de tokens e suas etiquetas.  
65 - """  
66 - entradas=[]  
67 - for e in lista:  
68 - # é necessário substituir símbolos como "-" e "+" do CHPTB  
69 - # que não são aceitos pelo NLTK como símbolos não terminais  
70 - c=re.sub(r"[-+]","_",e[1])  
71 - c=re.sub(r"\$","_S",c)  
72 - entradas.append("%s -> '%s'" % (c, e[0].lower()))  
73 - return entradas  
74 -  
75 -def corrigeAnotacao(lista):  
76 - """Esta função deverá corrigir alguns dos erros de anotação mais comuns do Aelius. No momento, apenas é corrigida VB-AN depois de TR.  
77 - """  
78 - i=1  
79 - while i < len(lista):  
80 - if lista[i][1] == "VB-AN" and lista[i-1][1].startswith("TR"):  
81 - lista[i]=(lista[i][0],"VB-PP")  
82 - i+=1  
83 -  
84 -# a função abaixo parece muito restritiva; talvez não seja necessário  
85 -# que o arquivo esteja no diretório nltk_data  
86 -def encontraArquivo(caminho=DIR):  
87 - """Encontra arquivo na pasta vlibras-translate.  
88 - """  
89 - home = os.path.expanduser("~")  
90 - path = os.path.realpath(home+caminho)  
91 - return path  
92 -  
93 -def extraiSintaxe(caminho=DIR):  
94 - """Extrai gramática armazenada em arquivo cujo caminho é definido relativamente ao diretório nltk_data.  
95 - """  
96 - arquivo=encontraArquivo(caminho)  
97 - if arquivo:  
98 - f=open(arquivo,"rU")  
99 - sintaxe=f.read()  
100 - f.close()  
101 - return sintaxe  
102 - else:  
103 - print "Arquivo %s não encontrado em nenhum dos diretórios de dados do NLTK:\n%s" % (caminho,"\n".join(nltk.data.path))  
104 -  
105 -  
106 -def analisaSentenca(sentenca):  
107 - """Retorna lista de árvores de estrutura sintagmática para a sentença dada sob a forma de uma lista de tokens, com base na gramática CFG cujo caminho é especificado como segundo argumento da função. Esse caminho é relativo à pasta nltk_data da instalação local do NLTK. A partir da etiquetagem morfossintática da sentença são geradas entradas lexicais que passam a integrar a gramática CFG. O caminho da gramática e o parser gerado são armazenados como tupla na variável ANALISADORES.  
108 - """  
109 - parser=constroiAnalisador(sentenca)  
110 - codificada=[w.encode("utf-8") for w in sentenca]  
111 - trees=parser.parse_one(codificada)  
112 - return trees  
113 -  
114 -def constroiAnalisador(s):  
115 - """Constrói analisador a partir de uma única sentença não anotada, dada como lista de tokens, e uma lista de regras sintáticas no formato CFG, armazenadas em arquivo. Esta função tem um bug, causado pela maneira como o Aelius etiqueta sentenças usando o módulo ProcessaNomesProprios: quando a sentença se inicia por paravra com inicial minúscula, essa palavra não é incorporada ao léxico, mas a versão com inicial maiúscula.  
116 - """  
117 - global SENTENCA_ANOTADA  
118 - SENTENCA_ANOTADA=etiquetaSentenca(s)  
119 - corrigeAnotacao(SENTENCA_ANOTADA)  
120 - entradas=geraEntradasLexicais(SENTENCA_ANOTADA)  
121 - lexico="\n".join(entradas)  
122 - gramatica="%s\n%s" % (extraiSintaxe(DIR).strip(),lexico)  
123 - cfg=nltk.CFG.fromstring(gramatica)  
124 - return nltk.ChartParser(cfg)  
125 -  
126 -def exibeArvores(arvores):  
127 - """Função 'wrapper' para a função de exibição de árvores do NLTK"""  
128 - nltk.draw.draw_trees(*arvores)  
129 -  
130 -def run(sentenca):  
131 - tokens=toqueniza(sentenca)  
132 - trees=analisaSentenca(tokens)  
133 - return trees  
134 \ No newline at end of file 0 \ No newline at end of file
src/new/AplicaRegras.py 0 → 100644
@@ -0,0 +1,161 @@ @@ -0,0 +1,161 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva
  5 +#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  6 +
  7 +#LAViD - Laboratório de Aplicações de Vídeo Digital
  8 +
  9 +from LeitorDicionarios import *
  10 +from Iterator import *
  11 +from StringAux import *
  12 +
  13 +class AplicaRegras(object):
  14 +
  15 + # inicializa todos as variaveis
  16 + def __init__(self):
  17 + self.__dicionarios = LeitorDicionarios()
  18 +
  19 + # retira artigos e preposicoes; passa verbos para infinitivo e verificar se há sinonimos
  20 + def simplificar(self, texto):
  21 + it = Iterator()
  22 + it.load(texto)
  23 + self.__ts = []
  24 + self.__verb = False
  25 + self.__adv = False;
  26 + self.__countVerb = 0
  27 + self.__countAdv = 0
  28 + while(it.hasNext()):
  29 + token = it.getAtualW()
  30 + tag = it.getAtualT()
  31 + self.__b = False
  32 + if self.__dicionarios.hasPalavraIgnorada(tag) == False: # verifica se nao eh artigo/preposicao
  33 +
  34 + #VERIFICA SE É ADVERBIO E CONTA A QUANTIDADE
  35 + if tag[:3] == "ADV":
  36 + self.__adv = True
  37 + self.__countAdv += 1
  38 +
  39 + if tag[:2] == "VB":
  40 +
  41 + #VERIFICA SE É VERBO NO INFINITIVO
  42 + if self.__dicionarios.hasVerboInfinitivo(token): # verifica se ha um verbo infinitivo desse token
  43 + verboInfinitivo = self.__dicionarios.getVerboInfinitivo(token) # se sim, adiciona numa string aux
  44 + self.__ts.append([verboInfinitivo,tag]) # caso contrario, adiciona so o verbo infinitivo msm
  45 + self.__b = True
  46 +
  47 + #VERIFICA SE É VERBO DE TEMPO E CONTA A QUANTIDADE
  48 + if tag == "VB-P" or tag == "VB-D" or tag == "VB-R":
  49 + self.__verb = True
  50 + self.__countVerb += 1
  51 +
  52 +
  53 + #VERIFICA SE É SUBTANTIVO COMUM DOS 2 GENEROS
  54 + if self.__dicionarios.hasSubst2Genero(token):
  55 + #del self.__ts[-1]
  56 + lenTicket = len(it.getAntT())
  57 + if ((self.__dicionarios.hasPalavraIgnorada(it.getAntT())) and (it.getAntT()[lenTicket-1:] == "F") or (it.getAntT()[lenTicket-3:] == "F-P")):
  58 + self.__ts.append(["MULHER ", "2GEN"])
  59 + self.__ts.append([token,tag])
  60 + else:
  61 + self.__ts.append(["HOMEM ", "2GEN"])
  62 + self.__ts.append([token,tag])
  63 + self.__b = True
  64 +
  65 + #VERIFICA SE É PLURAL
  66 + #if tag[-2:] == "-P":
  67 + # token = self.pluralAnalysis(token)
  68 +
  69 + #SE NÃO HOUVE NENHUM ALTERAÇÃO, OU SEJA, NÃO APLICOU NENHUMA REGRA, ADICIONA O TOKEN ORIGINAL
  70 + if self.__b == False: # verifica se nao encontrou nem verbo infinito ou sinonimo
  71 + self.__ts.append([token,tag])
  72 +
  73 + #SE ENCONTROU VERBO, ENTÃO ANALISA a SENTENCA NOVAMENTE (again?)
  74 + if self.__verb == True:
  75 + return self.verbalAnalysis(self.__ts)
  76 +
  77 + return self.__ts
  78 +
  79 +
  80 + # converte romano para numero
  81 + def auxConvert(self, tag):
  82 + try:
  83 + return roman_to_int(tag)
  84 + except:
  85 + return tag
  86 +
  87 + def verbalAnalysis(self, lista):
  88 + lv = []
  89 + it = Iterator()
  90 + it.load(lista)
  91 + hasFut = False
  92 + hasPas = False
  93 + count = 0
  94 + while(it.hasNext()):
  95 + token = it.getAtualW().upper()
  96 + tag = it.getAtualT()
  97 +
  98 + if(tag[:3] == "ADV"):
  99 + if (self.__dicionarios.hasTempoVerbal(token)):
  100 + it.reset()
  101 + #print "ADV: retornou lista original"
  102 + return lista
  103 +
  104 + if(tag == "VB-P"):
  105 + if (self.__countVerb > 1):
  106 + count += 1
  107 + #print "VB-P: Incrementou"
  108 + if(count == self.__countVerb):
  109 + #print "VB-P Adicionou " + token
  110 + lv.append([token,tag])
  111 + else:
  112 + #print "VB-P: retornou lista original"
  113 + it.reset()
  114 + return lista
  115 + elif(tag == "VB-D"):
  116 + count += 1
  117 + hasPas = True
  118 + #print "VB-D: Incrementou"
  119 + if(count == self.__countVerb):
  120 + #print "VB-D Adicionou " + token
  121 + lv.append([token,tag])
  122 + elif(tag == "VB-R"):
  123 + count += 1
  124 + hasFut = True
  125 + #print "VB-R: Incrementou"
  126 + if(count == self.__countVerb):
  127 + #print "VB-R Adicionou " + token
  128 + lv.append([token,tag])
  129 + else:
  130 + lv.append([token,tag])
  131 + if (hasFut):
  132 + lv.append(["FUTURO", "T-VB"])
  133 + elif (hasPas):
  134 + lv.append(["PASSADO", "T-VB"])
  135 + it.reset()
  136 + return lv
  137 +
  138 +
  139 + def pluralAnalysis(self, word):
  140 +
  141 + if(word[-3:] == "OES" or word[-2:] == "AES" or word[-2:] == "AOS"):
  142 + return word[0:-3]+"AO"
  143 + elif(word[-3:] == "RES" or word[-2:] == "ZES" or word[-2:] == "NES"):
  144 + return word[0:-2]
  145 + elif(word[-3:] == "SES"):
  146 + #TODO: Algumas palavras possuem marcações gráficas na raiz singular. Ex: Gás – Gases
  147 + return word[0:-2]
  148 + elif(word[-2:] == "NS"):
  149 + return word[0:-2]+"M"
  150 + elif(word[-3:] == "EIS"):
  151 + return word[0:-3]+"IL"
  152 + elif(word[-2:] == "IS"):
  153 + if(word[-3] == "A" or word[-3] == "E" or word[-3] == "O" or word[-3] == "U"):
  154 + return word[0:-2]+"L"
  155 + else:
  156 + return word
  157 + elif(word[-1] == "S"):
  158 + #TODO: Palavras paroxítonas ou proparoxítonas terminadas em S. Ex: lápis, vírus, tagênis, ônibus, etc
  159 + return word[0:-1]
  160 + else:
  161 + return word
0 \ No newline at end of file 162 \ No newline at end of file
src/new/AplicaSinonimos.py 0 → 100644
@@ -0,0 +1,48 @@ @@ -0,0 +1,48 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva
  5 +#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  6 +
  7 +#LAViD - Laboratório de Aplicações de Vídeo Digital
  8 +
  9 +import os, csv, sys
  10 +from nltk.tree import *
  11 +from LeitorDicionarios import *
  12 +
  13 +class AplicaSinonimos(object):
  14 +
  15 + # Define e inicializa os atributos
  16 + def __init__(self):
  17 + self.__dicionarios = LeitorDicionarios()
  18 +
  19 + def sinonimosMorfologico(self, texto):
  20 + lista = texto
  21 + for i, elem in enumerate(lista):
  22 + token = self.verificaPalavra(elem[0])
  23 + listmp = list(elem)
  24 + listmp[0] = token
  25 + lista[i] = listmp
  26 + return lista
  27 +
  28 +
  29 + def dicionarioSinonimoFolhas(self, folhas):
  30 + dic = {}
  31 + for f in folhas:
  32 + token = self.verificaPalavra(f)
  33 + dic[f] = token
  34 + return dic
  35 +
  36 + def sinonimosSintatico(self, texto):
  37 + folhas = Tree.leaves(texto)
  38 + dic = self.dicionarioSinonimoFolhas(folhas)
  39 + stringTree = str(texto)
  40 + for t in folhas:
  41 + stringTree.replace(t, dic[t])
  42 + tree = Tree.fromstring(stringTree, brackets='()')
  43 + return tree
  44 +
  45 + def verificaPalavra(self, token):
  46 + if self.__dicionarios.hasSinonimo(token):
  47 + return self.__dicionarios.getSinonimo(token)
  48 + return token
0 \ No newline at end of file 49 \ No newline at end of file
src/new/Iterator.py 0 → 100644
@@ -0,0 +1,60 @@ @@ -0,0 +1,60 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva
  5 +#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  6 +
  7 +#LAViD - Laboratório de Aplicações de Vídeo Digital
  8 +
  9 +class Iterator(object):
  10 +
  11 + # inicializacao das variaveis
  12 + def __init__(self):
  13 + self.count = -1
  14 +
  15 + def load(self, lista):
  16 + self.__list = list(lista);
  17 + self.size = len(lista)
  18 +
  19 + def reset(self):
  20 + self.count = -1
  21 +
  22 + def getSize(self):
  23 + return self.size
  24 +
  25 + def getCount(self):
  26 + return self.count
  27 +
  28 + def getToken(self, i):
  29 + if(i == "+"):
  30 + return self.__list[self.count+1]
  31 +
  32 + elif(i == "-"):
  33 + return self.__list[self.count-1]
  34 +
  35 + else:
  36 + return self.__list[self.count]
  37 +
  38 + def getAtualW(self):
  39 + return self.getToken(0)[0].upper()
  40 +
  41 + def getAtualT(self):
  42 + return self.getToken(0)[1]
  43 +
  44 + def getProxW(self):
  45 + return self.getToken("+")[0].upper()
  46 +
  47 + def getProxT(self):
  48 + return self.getToken("+")[1]
  49 +
  50 + def getAntW(self):
  51 + return self.getToken("-")[0].upper()
  52 +
  53 + def getAntT(self):
  54 + return self.getToken("-")[1]
  55 +
  56 + def hasNext(self):
  57 + if(self.count < self.size-1):
  58 + self.count += 1
  59 + return True
  60 + return False
0 \ No newline at end of file 61 \ No newline at end of file
src/new/LeitorDicionarios.py 0 → 100644
@@ -0,0 +1,139 @@ @@ -0,0 +1,139 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva
  5 +#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  6 +
  7 +#LAViD - Laboratório de Aplicações de Vídeo Digital
  8 +
  9 +import os, csv, sys
  10 +
  11 +class LeitorDicionarios(object):
  12 + #_iInstance = None
  13 +
  14 + #class Singleton:
  15 + # def __init__(self):
  16 + # self.LeitorDicionarios = None
  17 +
  18 + #def __init__( self ):
  19 + # if LeitorDicionarios._iInstance is None:
  20 + # LeitorDicionarios._iInstance = LeitorDicionarios.Singleton()
  21 +
  22 + # self._EventHandler_instance = LeitorDicionarios._iInstance
  23 +
  24 + #def __getattr__(self, aAttr):
  25 + # return getattr(self._iInstance, aAttr)
  26 +
  27 + #def __setattr__(self, aAttr, aValue):
  28 + # return setattr(self._iInstance, aAttr, aValue)
  29 +
  30 + # Define e inicializa os atributos
  31 + def __init__(self):
  32 + self.__path = "/home/erickson/vlibras-translate/data/"
  33 + self.__dicInf = {}
  34 + self.__dicSin = {}
  35 + self.__dicWords = {}
  36 + self.__dic2Gen = {}
  37 + self.__dicTemVerbs = {}
  38 + self.__fileDic = ''
  39 + self.carregarVerbosInfinitivos()
  40 + self.carregarSinonimos()
  41 + self.carregarPalavrasIgnoradas()
  42 + self.carregarSubst2Generos()
  43 + self.carregarTemposVerbais()
  44 +
  45 + # Abre o self.__fileDic que contem os verbos no infinitivo e preenche o dicionario com os mesmos
  46 + def carregarVerbosInfinitivos(self):
  47 + try:
  48 + self.__fileDic = csv.reader(open(self.__path+"dicPortGlosa.csv"), delimiter=";")
  49 + except IOError, (errno, strerror):
  50 + print "I/O error(%s): %s" % (errno, strerror)
  51 + print "carregarVerbosInfinitivos"
  52 +
  53 + for row in self.__fileDic:
  54 + if row[1] != "":
  55 + try:
  56 + self.__dicInf[row[0].decode("utf-8")] = row[1].decode("utf-8")
  57 + except UnicodeDecodeError:
  58 + self.__dicInf[row[0].decode('iso8859-1').encode('utf-8')] = row[1].decode('iso8859-1').encode('utf-8')
  59 +
  60 + # Abre o self.__fileDic que contem os sinonimos e preenche o dicionario com os mesmos
  61 + def carregarSinonimos(self):
  62 + try:
  63 + self.__fileDic = csv.reader(open(self.__path+"portuguesGlosa.csv"), delimiter=";")
  64 + except IOError, (errno, strerror):
  65 + print "I/O error(%s): %s" % (errno, strerror)
  66 + print "carregarSinonimos"
  67 +
  68 + for row in self.__fileDic:
  69 + if row[1] != "":
  70 + self.__dicSin[row[0].decode("utf-8")] = row[1].decode("utf-8")
  71 +
  72 +
  73 + # Abre o self.__fileDic que contem os tempos verbais
  74 + def carregarTemposVerbais(self):
  75 + try:
  76 + self.__fileDic = csv.reader(open(self.__path+"temposVerbais.csv"), delimiter=";")
  77 + except IOError, (errno, strerror):
  78 + print "I/O error(%s): %s" % (errno, strerror)
  79 + print "carregarTemposVerbais"
  80 +
  81 + for row in self.__fileDic:
  82 + self.__dicTemVerbs[row[0].decode("utf-8")] = row[0].decode("utf-8")
  83 +
  84 + # Abre o self.__fileDic que contem os artigos e preposicoes de acordo com o modelo de idioma passado na chamada e preenche o dicionario com os mesmos
  85 + def carregarPalavrasIgnoradas(self):
  86 + try:
  87 + self.__fileDic = csv.reader(open(self.__path+"hWordsRemove.csv"), delimiter=";")
  88 + except IOError, (errno, strerror):
  89 + print "I/O error(%s): %s" % (errno, strerror)
  90 + print "carregarPalavrasIgnoradas"
  91 +
  92 + for row in self.__fileDic:
  93 + self.__dicWords[row[0].decode("utf-8")] = row[0].decode("utf-8")
  94 +
  95 + # Abre o self.__fileDic que contem os substantivos que sao comuns dos 2 generos e preenche o dicionario com os mesmos
  96 + def carregarSubst2Generos(self):
  97 + try:
  98 + self.__fileDic = csv.reader(open(self.__path+"subs2Generos.csv"), delimiter=";")
  99 + except IOError, (errno, strerror):
  100 + print "I/O error(%s): %s" % (errno, strerror)
  101 + print "carregarSubst2Generos"
  102 +
  103 + for row in self.__fileDic:
  104 + self.__dic2Gen[row[0].decode("utf-8")] = row[0].decode("utf-8")
  105 +
  106 + # Retorna o dicionario dos verbos no infinitivo
  107 + def getVerboInfinitivo(self, token):
  108 + return self.__dicInf[token]
  109 +
  110 + # Retorna o dicionario dos sinonimos
  111 + def getSinonimo(self, token):
  112 + return self.__dicSin[token]
  113 +
  114 + # Retorna o dicionario dos artigos e preposicoes a serem removidos pelo simplificador
  115 + def getPalavraIgnorada(self, token):
  116 + return self.__dicWords[token]
  117 +
  118 + # Retorna o dicionario dos substantivos a serem analisados pelo simplificador
  119 + def getSubst2Generos(self, token):
  120 + return self.__dic2Gen[token]
  121 +
  122 + # Retorna o dicionario dos tempos verbais
  123 + def getTempoVerbal(self, token):
  124 + return self.__dicTemVerbs[token]
  125 +
  126 + def hasVerboInfinitivo(self, token):
  127 + return self.__dicInf.has_key(token)
  128 +
  129 + def hasSinonimo(self, token):
  130 + return self.__dicSin.has_key(token)
  131 +
  132 + def hasPalavraIgnorada(self, token):
  133 + return self.__dicWords.has_key(token)
  134 +
  135 + def hasSubst2Genero(self, token):
  136 + return self.__dic2Gen.has_key(token)
  137 +
  138 + def hasTempoVerbal(self, token):
  139 + return self.__dicTemVerbs.has_key(token)
src/new/Tradutor.py 0 → 100644
@@ -0,0 +1,45 @@ @@ -0,0 +1,45 @@
  1 +#!/usr/bin/python
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#Autor: Erickson Silva
  5 +#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  6 +
  7 +#LAViD - Laboratório de Aplicações de Vídeo Digital
  8 +
  9 +import alexp
  10 +from AplicaSinonimos import *
  11 +from AplicaRegras import *
  12 +
  13 +sin = AplicaSinonimos()
  14 +reg = AplicaRegras()
  15 +
  16 +
  17 +def iniciarTraducao(texto):
  18 + textoDividido = texto.split(".")
  19 + for w in textoDividido:
  20 + if len(w) > 0:
  21 + gerarAnalise(w)
  22 +
  23 +def gerarAnalise(sentenca):
  24 + '''tokens = alexp.toqueniza(sentenca)
  25 + etiquetadas = alexp.etiquetaSentenca(tokens)
  26 + analiseMorf = analiseMorfologica(etiquetadas)
  27 + print analiseMorf'''
  28 +
  29 + analise = alexp.run(sentenca)
  30 +
  31 + if (isinstance(analise,type(None))):
  32 + analise = alexp.getAnaliseMorfologica()
  33 + print analiseMorfologica(analise)
  34 + else:
  35 + print analiseSintatica(analise)
  36 +
  37 +
  38 +def analiseMorfologica(sentenca):
  39 + proc = reg.simplificar(sentenca)
  40 + return sin.sinonimosMorfologico(proc)
  41 +
  42 +
  43 +def analiseSintatica(sentenca):
  44 + analise = sin.sinonimosSintatico(sentenca)
  45 + return analise
0 \ No newline at end of file 46 \ No newline at end of file
src/new/alexp.py 0 → 100644
@@ -0,0 +1,133 @@ @@ -0,0 +1,133 @@
  1 +#! /usr/bin/env python2.6
  2 +# -*- coding: utf-8 -*-
  3 +
  4 +#---------------------------------
  5 +
  6 +# Editado:
  7 +
  8 +#Autor: Erickson Silva
  9 +#Email: <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>
  10 +
  11 +#LAViD - Laboratório de Aplicações de Vídeo Digital
  12 +
  13 +#---------------------------------
  14 +
  15 +
  16 +# Donatus Brazilian Portuguese Parser
  17 +#
  18 +# Copyright (C) 2010-2013 Leonel F. de Alencar
  19 +#
  20 +# Author: Leonel F. de Alencar <leonel.de.alencar@ufc.br>
  21 +# Homepage: <http://www.leonel.profusehost.net/>
  22 +#
  23 +# Project's URL: <http://sourceforge.net/projects/donatus/>
  24 +# For license information, see LICENSE.TXT
  25 +#
  26 +# $Id: alexp.py $
  27 +
  28 +"""Este módulo contém funções que permitem utilizar o Aelius para etiquetar uma sentença, construindo entradas lexicais com base nas etiquetas atribuídas às palavras da sentença. Essas entradas lexicais são integradas em uma gramática CFG dada, que é transformada em um parser, utilizado para gerar uma árvore de estrutura sintagmática da sentença.
  29 +"""
  30 +import re, string,nltk,os
  31 +from Aelius.Extras import carrega
  32 +from Aelius import AnotaCorpus
  33 +
  34 +# definição de algumas variáveis globais para
  35 +# facilitar utilização das diferentes funções do módulo
  36 +
  37 +# sintaxe default em subpasta de nltk_data
  38 +DIR="/vlibras-translate/data/cfg.syn.nltk"
  39 +
  40 +# eventualmente será preciso incluir aqui outros sinais
  41 +# de pontuação, como o travessão
  42 +PUNCT=string.punctuation
  43 +
  44 +SENTENCA_ANOTADA=""
  45 +
  46 +
  47 +def toqueniza(s):
  48 + """Decodifica string utilizando utf-8, retornando uma lista de tokens em unicode.
  49 + """
  50 + decodificada=s.decode("utf-8")
  51 + return AnotaCorpus.TOK_PORT.tokenize(decodificada)
  52 +
  53 +def getAnaliseMorfologica():
  54 + return SENTENCA_ANOTADA
  55 +
  56 +def etiquetaSentenca(s):
  57 + """Aplica um dos etiquetadores do Aelius na etiquetagem da sentença dada como lista de tokens.
  58 + """
  59 + etiquetador = list((carrega("AeliusHunPos"),"nltk"))
  60 + anotada = AnotaCorpus.anota_sentencas([s],etiquetador,"hunpos")[0]
  61 + return anotada
  62 +
  63 +def geraEntradasLexicais(lista):
  64 + """Gera entradas lexicais no formato CFG do NLTK a partir de lista de pares constituídos de tokens e suas etiquetas.
  65 + """
  66 + entradas=[]
  67 + for e in lista:
  68 + # é necessário substituir símbolos como "-" e "+" do CHPTB
  69 + # que não são aceitos pelo NLTK como símbolos não terminais
  70 + c=re.sub(r"[-+]","_",e[1])
  71 + c=re.sub(r"\$","_S",c)
  72 + entradas.append("%s -> '%s'" % (c, e[0].lower()))
  73 + return entradas
  74 +
  75 +def corrigeAnotacao(lista):
  76 + """Esta função deverá corrigir alguns dos erros de anotação mais comuns do Aelius. No momento, apenas é corrigida VB-AN depois de TR.
  77 + """
  78 + i=1
  79 + while i < len(lista):
  80 + if lista[i][1] == "VB-AN" and lista[i-1][1].startswith("TR"):
  81 + lista[i]=(lista[i][0],"VB-PP")
  82 + i+=1
  83 +
  84 +# a função abaixo parece muito restritiva; talvez não seja necessário
  85 +# que o arquivo esteja no diretório nltk_data
  86 +def encontraArquivo(caminho=DIR):
  87 + """Encontra arquivo na pasta vlibras-translate.
  88 + """
  89 + home = os.path.expanduser("~")
  90 + path = os.path.realpath(home+caminho)
  91 + return path
  92 +
  93 +def extraiSintaxe(caminho=DIR):
  94 + """Extrai gramática armazenada em arquivo cujo caminho é definido relativamente ao diretório nltk_data.
  95 + """
  96 + arquivo=encontraArquivo(caminho)
  97 + if arquivo:
  98 + f=open(arquivo,"rU")
  99 + sintaxe=f.read()
  100 + f.close()
  101 + return sintaxe
  102 + else:
  103 + print "Arquivo %s não encontrado em nenhum dos diretórios de dados do NLTK:\n%s" % (caminho,"\n".join(nltk.data.path))
  104 +
  105 +
  106 +def analisaSentenca(sentenca):
  107 + """Retorna lista de árvores de estrutura sintagmática para a sentença dada sob a forma de uma lista de tokens, com base na gramática CFG cujo caminho é especificado como segundo argumento da função. Esse caminho é relativo à pasta nltk_data da instalação local do NLTK. A partir da etiquetagem morfossintática da sentença são geradas entradas lexicais que passam a integrar a gramática CFG. O caminho da gramática e o parser gerado são armazenados como tupla na variável ANALISADORES.
  108 + """
  109 + parser=constroiAnalisador(sentenca)
  110 + codificada=[w.encode("utf-8") for w in sentenca]
  111 + trees=parser.parse_one(codificada)
  112 + return trees
  113 +
  114 +def constroiAnalisador(s):
  115 + """Constrói analisador a partir de uma única sentença não anotada, dada como lista de tokens, e uma lista de regras sintáticas no formato CFG, armazenadas em arquivo. Esta função tem um bug, causado pela maneira como o Aelius etiqueta sentenças usando o módulo ProcessaNomesProprios: quando a sentença se inicia por paravra com inicial minúscula, essa palavra não é incorporada ao léxico, mas a versão com inicial maiúscula.
  116 + """
  117 + global SENTENCA_ANOTADA
  118 + SENTENCA_ANOTADA=etiquetaSentenca(s)
  119 + corrigeAnotacao(SENTENCA_ANOTADA)
  120 + entradas=geraEntradasLexicais(SENTENCA_ANOTADA)
  121 + lexico="\n".join(entradas)
  122 + gramatica="%s\n%s" % (extraiSintaxe(DIR).strip(),lexico)
  123 + cfg=nltk.CFG.fromstring(gramatica)
  124 + return nltk.ChartParser(cfg)
  125 +
  126 +def exibeArvores(arvores):
  127 + """Função 'wrapper' para a função de exibição de árvores do NLTK"""
  128 + nltk.draw.draw_trees(*arvores)
  129 +
  130 +def run(sentenca):
  131 + tokens=toqueniza(sentenca)
  132 + trees=analisaSentenca(tokens)
  133 + return trees
0 \ No newline at end of file 134 \ No newline at end of file
src/old version/AplicadorRegras.py
@@ -1,60 +0,0 @@ @@ -1,60 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
5 -  
6 -import xml.etree.ElementTree as ET  
7 -import os  
8 -  
9 -class AplicadorRegras(object):  
10 -  
11 - # inicializacao das variaves  
12 - def __init__(self):  
13 - self.__tree = ET.parse('vlibras_user/vlibras-core/data/regras.xml')  
14 - self.__root = self.__tree.getroot()  
15 - self.__tAux = []  
16 - self.__dAux = {}  
17 -  
18 - # aplica as regras  
19 - def aplicarRegras(self, ts):  
20 - self.__n = len(ts) # quantidade de tokens  
21 - for i in range(0,self.__n):  
22 - self.__tAux.append(self.__n)  
23 - self.__name = self.getNameRule(ts) # todos os etiquetadores numa so string (ver linha 35)  
24 - for morpho in self.__root:  
25 - for rule in morpho.findall('rule'): # procura a tag rule  
26 - if rule.get('name') == self.__name: # procura o atributo name na tag rule (ver linha 17)  
27 - if rule.find('active').text == "true": # verifica se a regra esta ativa  
28 - self.__c = 0  
29 - for classe in rule.iter('class'): # for nas tags class  
30 - self.__dAux[self.__c] = int(classe.find('newpos').text) # preenche dicionario com a ordem atual e futura das palavras  
31 - self.__c += 1  
32 - self.__c = 0  
33 - for w,t in ts:  
34 - i = self.__dAux.get(self.__c) # pega o indice de onde ficara a palavra  
35 - self.__tAux[i] = ([w,t]) # preenche a lista com a palavra+etiqueta na posicao correta (segundo o arquivo regras.xml)  
36 - self.__c += 1  
37 - return self.__tAux # retorna nova lista (ordenada)  
38 - return ts # retorna a lista sem alteracoes (nao existe regra)  
39 -  
40 - def getNameRule(self, ts):  
41 - self.__name = ""  
42 - for w,t in ts:  
43 - if t[:2] != "VB":  
44 - self.__name += t  
45 - else:  
46 - self.__name += t[:2]  
47 - return self.__name  
48 -  
49 -  
50 -  
51 -  
52 -  
53 -  
54 -  
55 -  
56 -  
57 -  
58 -  
59 -  
60 -  
src/old version/Classificador.py
@@ -1,44 +0,0 @@ @@ -1,44 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
5 -  
6 -from Aelius import AnotaCorpus, Toqueniza, Extras  
7 -  
8 -class Classificador(object):  
9 -  
10 - # inicializacao das variaveis  
11 - def __init__(self):  
12 - self.__h = Extras.carrega("AeliusHunPos") # carrega o modelo de idioma (passado por parametro ao instanciar)  
13 -  
14 - def anotaSentencas(self, str):  
15 - self.__t = ""  
16 - self.__tokens = ""  
17 - #try:  
18 - # tokenizae  
19 - self.__tokens = Toqueniza.TOK_PORT.tokenize(str)  
20 -  
21 - # realiza a classificacao morfologica  
22 - self.__t = AnotaCorpus.anota_sentencas([self.__tokens],self.__h,'hunpos')  
23 -  
24 - return self.listClean(self.__t)  
25 - #except:  
26 - # print "Erro ao efetuar a classificação morfologica."  
27 -  
28 -  
29 - def listClean(self, l):  
30 - lClean = []  
31 - for w,t in l[0]:  
32 - lClean.append([w,t])  
33 - return lClean  
34 -  
35 - # faz a impressao (usado apenas pra testes)  
36 - def imprimeSentencas(self):  
37 - for w,t in self.t[0]:  
38 - print "%s_%s " % (w,t),  
39 -  
40 -  
41 -  
42 -  
43 -  
44 -  
src/old version/Iterator.py
@@ -1,59 +0,0 @@ @@ -1,59 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
5 -  
6 -from StringAux import *  
7 -  
8 -class Iterator(object):  
9 -  
10 - # inicializacao das variaveis  
11 - def __init__(self):  
12 - self.count = -1  
13 -  
14 - def load(self, lista):  
15 - self.__list = list(lista);  
16 - self.size = len(lista)  
17 -  
18 - def reset(self):  
19 - self.count = -1  
20 -  
21 - def getSize(self):  
22 - return self.size  
23 -  
24 - def getCount(self):  
25 - return self.count  
26 -  
27 - def getToken(self, i):  
28 - if(i == "+"):  
29 - return self.__list[self.count+1]  
30 -  
31 - elif(i == "-"):  
32 - return self.__list[self.count-1]  
33 -  
34 - else:  
35 - return self.__list[self.count]  
36 -  
37 - def getAtualW(self):  
38 - return remover_acentos(self.getToken(0)[0].upper().encode('utf-8'))  
39 -  
40 - def getAtualT(self):  
41 - return self.getToken(0)[1].upper().encode('utf-8')  
42 -  
43 - def getProxW(self):  
44 - return remover_acentos(self.getToken("+")[0].upper().encode('utf-8'))  
45 -  
46 - def getProxT(self):  
47 - return self.getToken("+")[1].upper().encode('utf-8')  
48 -  
49 - def getAntW(self):  
50 - return remover_acentos(self.getToken("-")[0].upper().encode('utf-8'))  
51 -  
52 - def getAntT(self):  
53 - return self.getToken("-")[1].upper().encode('utf-8')  
54 -  
55 - def hasNext(self):  
56 - if(self.count < self.size-1):  
57 - self.count += 1  
58 - return True  
59 - return False  
60 \ No newline at end of file 0 \ No newline at end of file
src/old version/ModuleTranslate.py
@@ -1,14 +0,0 @@ @@ -1,14 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -from Tradutor import *  
5 -  
6 -tradutor = Tradutor()  
7 -  
8 -def iniciar(x):  
9 - try:  
10 - text = x.decode("utf-8")  
11 - except:  
12 - text = x.decode("iso-8859-1")  
13 -  
14 - return tradutor.traduzir(text)  
src/old version/Output.py
@@ -1,24 +0,0 @@ @@ -1,24 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
5 -  
6 -import sys  
7 -from Iterator import *  
8 -from StringAux import *  
9 -  
10 -class Output(object):  
11 -  
12 - # inicializa a variavel com o valor passado por paramentro ao instanciar  
13 - def __init__(self):  
14 - self.it = Iterator()  
15 -  
16 - # executa a saida  
17 - def executeOut(self, ts):  
18 - self.__glosa = []  
19 - self.it.load(ts)  
20 - while(self.it.hasNext()):  
21 - self.__glosa.append(self.it.getAtualW())  
22 - self.it.reset()  
23 - return ' '.join(self.__glosa)  
24 -  
src/old version/Simplificador.py
@@ -1,164 +0,0 @@ @@ -1,164 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
5 -  
6 -from WorkCSV import *  
7 -from Iterator import *  
8 -from StringAux import *  
9 -  
10 -class Simplificador(object):  
11 -  
12 - # inicializa todos as variaveis  
13 - def __init__(self):  
14 - self.it = Iterator()  
15 - self.__csv = WorkCSV()  
16 - self.__dicInf = {}  
17 - self.__dicSin = {}  
18 - self.__dicWords = {}  
19 - self.__dic2Gen = {}  
20 - self.__dicTemVerbs = {}  
21 - self.executeWorkCSV()  
22 -  
23 - # retira artigos e preposicoes; passa verbos para infinitivo e verificar se há sinonimos  
24 - def simplificar(self, texto):  
25 - self.__ts = []  
26 - self.it.load(texto)  
27 - self.__verb = False  
28 - self.__adv = False;  
29 - self.__countVerb = 0  
30 - self.__countAdv = 0  
31 - countWords = 0  
32 - while(self.it.hasNext()):  
33 - w = self.auxConvert(self.it.getAtualW())  
34 - t = self.it.getAtualT()  
35 - self.__b = False  
36 - if self.__dicWords.has_key(t) == False: # verifica se nao eh artigo/preposicao  
37 - wu = w.upper() # deixa o token maiusculo  
38 - #if t[:2] == "VB":  
39 - if t[-2:] == "-P":  
40 - wu = self.pluralAnalysis(w)  
41 - if t == "VB-P" or t == "VB-D" or t == "VB-R":  
42 - self.__verb = True  
43 - self.__countVerb += 1  
44 - if t[:3] == "ADV":  
45 - self.__adv = True  
46 - self.__countAdv += 1  
47 - if self.__dicInf.has_key(wu): # verifica se ha um verbo infinitivo desse token  
48 - sAux = self.__dicInf[wu] # se sim, adiciona numa string aux  
49 - if self.__dicSin.has_key(sAux): # verifica se ha um sinonimo para esse verbo infinitivo  
50 - self.__ts.append([self.__dicSin[sAux],t]) # se sim, entao adiciona na lista  
51 - self.__b = True  
52 - else:  
53 - self.__ts.append([sAux,t]) # caso contrario, adiciona so o verbo infinitivo msm  
54 - self.__b = True  
55 - if self.__b == False and self.__dicSin.has_key(wu): # verifica se nao foi encontrado verbo infinitivo e se ha sinonimo  
56 - self.__ts.append([self.__dicSin[wu],t]) # adiciona na o sinonimo lista  
57 - self.__b = True  
58 -  
59 - if self.__dic2Gen.has_key(wu):  
60 - del self.__ts[-1]  
61 - lenTicket = len(self.it.getAntT())  
62 - if ((self.__dicWords.has_key(self.it.getAntT())) and (self.it.getAntT()[lenTicket-1:] == "F") or (self.it.getAntT()[lenTicket-3:] == "F-P")):  
63 - self.__ts.append(["MULHER " + wu,t])  
64 - else:  
65 - self.__ts.append(["HOMEM " + wu,t])  
66 - self.__b = True  
67 - if self.__b == False: # verifica se nao encontrou nem verbo infinito ou sinonimo  
68 - self.__ts.append([wu,t])  
69 - countWords += 1  
70 - self.it.reset()  
71 - if self.__verb == True:  
72 - return self.verbalAnalysis(self.__ts)  
73 - return self.__ts  
74 -  
75 - # cria e recupera todos os dicionarios (verbos inf., sinonimos e artigos/preposicoes)  
76 - def executeWorkCSV(self):  
77 - self.__dicInf = self.__csv.getDicInf()  
78 - self.__dicSin = self.__csv.getDicSin()  
79 - self.__dicWords = self.__csv.getDicWords()  
80 - self.__dic2Gen = self.__csv.getDic2Gen()  
81 - self.__dicTemVerbs = self.__csv.getDicTemVerbs()  
82 -  
83 - # converte romano para numero  
84 - def auxConvert(self, t):  
85 - try:  
86 - return roman_to_int(t)  
87 - except:  
88 - return t  
89 -  
90 -  
91 - def verbalAnalysis(self, lista):  
92 - lv = []  
93 - self.it.load(lista)  
94 - hasFut = False  
95 - hasPas = False  
96 - count = 0  
97 - while(self.it.hasNext()):  
98 - w = self.it.getAtualW().upper()  
99 - t = self.it.getAtualT()  
100 -  
101 - if(t[:3] == "ADV"):  
102 - if (self.__dicTemVerbs.has_key(w)):  
103 - self.it.reset()  
104 - #print "ADV: retornou lista original"  
105 - return lista  
106 -  
107 - if(t == "VB-P"):  
108 - if (self.__countVerb > 1):  
109 - count += 1  
110 - #print "VB-P: Incrementou"  
111 - if(count == self.__countVerb):  
112 - #print "VB-P Adicionou " + w  
113 - lv.append([w,t])  
114 - else:  
115 - #print "VB-P: retornou lista original"  
116 - self.it.reset()  
117 - return lista  
118 - elif(t == "VB-D"):  
119 - count += 1  
120 - hasPas = True  
121 - #print "VB-D: Incrementou"  
122 - if(count == self.__countVerb):  
123 - #print "VB-D Adicionou " + w  
124 - lv.append([w,t])  
125 - elif(t == "VB-R"):  
126 - count += 1  
127 - hasFut = True  
128 - #print "VB-R: Incrementou"  
129 - if(count == self.__countVerb):  
130 - #print "VB-R Adicionou " + w  
131 - lv.append([w,t])  
132 - else:  
133 - lv.append([w,t])  
134 - if (hasFut):  
135 - lv.append(["FUTURO", "TVB"])  
136 - elif (hasPas):  
137 - lv.append(["PASSADO", "TVB"])  
138 - self.it.reset()  
139 - return lv  
140 -  
141 -  
142 - def pluralAnalysis(self, word):  
143 -  
144 - if(word[-3:] == "OES" or word[-2:] == "AES" or word[-2:] == "AOS"):  
145 - return word[0:-3]+"AO"  
146 - elif(word[-3:] == "RES" or word[-2:] == "ZES" or word[-2:] == "NES"):  
147 - return word[0:-2]  
148 - elif(word[-3:] == "SES"):  
149 - #TODO: Algumas palavras possuem marcações gráficas na raiz singular. Ex: Gás – Gases  
150 - return word[0:-2]  
151 - elif(word[-2:] == "NS"):  
152 - return word[0:-2]+"M"  
153 - elif(word[-3:] == "EIS"):  
154 - return word[0:-3]+"IL"  
155 - elif(word[-2:] == "IS"):  
156 - if(word[-3] == "A" or word[-3] == "E" or word[-3] == "O" or word[-3] == "U"):  
157 - return word[0:-2]+"L"  
158 - else:  
159 - return word  
160 - elif(word[-1] == "S"):  
161 - #TODO: Palavras paroxítonas ou proparoxítonas terminadas em S. Ex: lápis, vírus, tênis, ônibus, etc  
162 - return word[0:-1]  
163 - else:  
164 - return word  
165 \ No newline at end of file 0 \ No newline at end of file
src/old version/StringAux.py
@@ -1,83 +0,0 @@ @@ -1,83 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -from unicodedata import normalize  
5 -  
6 -ext = {1:"um", 2:"dois", 3:"três", 4:"quatro", 5:"cinco", 6:"seis", 7:"sete", 8:"oito", 9:"nove", 0:"zero"}  
7 -  
8 -def extenso(n):  
9 - strn = str(n)  
10 - sizen = len(strn)  
11 - tokens = []  
12 - for i in range (0, sizen):  
13 - x = int(strn[i])  
14 - tokens.append(ext[x])  
15 - return ' '.join(tokens)  
16 -  
17 -"""  
18 -def extenso(n):  
19 - strn = str(n)  
20 - sizen = len(strn)  
21 - tokens = []  
22 - for i in range (0, sizen):  
23 - tokens.append(strn[i])  
24 - return ' '.join(tokens)  
25 -"""  
26 -  
27 -def remover_acentos(txt):  
28 -  
29 - """ Devolve cópia de uma str substituindo os caracteres  
30 - acentuados pelos seus equivalentes não acentuados.  
31 -  
32 - ATENÇÃO: carateres gráficos não ASCII e não alfa-numéricos,  
33 - tais como bullets, travessões, aspas assimétricas, etc.  
34 - são simplesmente removidos!  
35 -  
36 - >>> remover_acentos('[ACENTUAÇÃO] ç: áàãâä! éèêë? íì&#297;îï, óòõôö; úù&#361;ûü.')  
37 - '[ACENTUACAO] c: aaaaa! eeee? iiiii, ooooo; uuuuu.'  
38 -  
39 - """  
40 - try:  
41 - return normalize('NFKD', txt.decode('utf-8')).encode('ASCII','ignore')  
42 - except:  
43 - return normalize('NFKD', txt.decode('iso-8859-1')).encode('ASCII','ignore')  
44 -  
45 -  
46 -def roman_to_int(input):  
47 - if not isinstance(input, type("")):  
48 - raise TypeError, "expected string, got %s" % type(input)  
49 - input = input.upper( )  
50 - nums = {'M':1000,  
51 - 'D':500,  
52 - 'C':100,  
53 - 'L':50,  
54 - 'X':10,  
55 - 'V':5,  
56 - 'I':1}  
57 - sum = 0  
58 - for i in range(len(input)):  
59 - try:  
60 - value = nums[input[i]]  
61 - if i+1 < len(input) and nums[input[i+1]] > value:  
62 - sum -= value  
63 - else: sum += value  
64 - except KeyError:  
65 - raise ValueError, 'input is not a valid Roman numeral: %s' % input  
66 -  
67 - if int_to_roman(sum) == input: return sum  
68 - else: raise ValueError, 'input is not a valid Roman numeral: %s' % input  
69 -  
70 -def int_to_roman(input):  
71 - if not isinstance(input, type(1)):  
72 - raise TypeError, "expected integer, got %s" % type(input)  
73 - if not 0 < input < 4000:  
74 - raise ValueError, "Argument must be between 1 and 3999"  
75 - ints = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)  
76 - nums = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')  
77 - result = []  
78 -  
79 - for i in range(len(ints)):  
80 - count = int(input / ints[i])  
81 - result.append(nums[i] * count)  
82 - input -= ints[i] * count  
83 - return ''.join(result)  
84 \ No newline at end of file 0 \ No newline at end of file
src/old version/Tradutor.py
@@ -1,38 +0,0 @@ @@ -1,38 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
5 -  
6 -from Classificador import *  
7 -from Simplificador import *  
8 -from AplicadorRegras import *  
9 -from Output import *  
10 -from StringAux import *  
11 -  
12 -  
13 -class Tradutor(object):  
14 -  
15 - def __init__(self):  
16 - #instanciando os objetos  
17 - self.__classificador = Classificador()  
18 - self.__simplificador = Simplificador()  
19 - self.__regras = AplicadorRegras()  
20 - self.__out = Output()  
21 -  
22 -  
23 - def traduzir(self, txt):  
24 - self.__tr = None  
25 -  
26 - #faz a tokenizacao e a classificacao  
27 - self.__t = self.__classificador.anotaSentencas(txt)  
28 -  
29 - #retira artigos e preposicoes  
30 - self.__ts = self.__simplificador.simplificar(self.__t)  
31 - self.__t = None  
32 -  
33 - #aplica as regras  
34 - self.__tr = self.__regras.aplicarRegras(self.__ts)  
35 - self.__ts = None  
36 -  
37 - #executa a saida  
38 - return self.__out.executeOut(self.__tr).encode("utf-8")  
src/old version/WorkCSV.py
@@ -1,125 +0,0 @@ @@ -1,125 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -#Autor: Erickson Silva <erickson.silva@lavid.ufpb.br> <ericksonsilva@live.com>  
5 -  
6 -import os, csv, sys  
7 -  
8 -class WorkCSV(object):  
9 - _iInstance = None  
10 -  
11 - class Singleton:  
12 - def __init__(self):  
13 - self.LeitorDicionarios = None  
14 -  
15 - def __init__( self ):  
16 - if LeitorDicionarios._iInstance is None:  
17 - LeitorDicionarios._iInstance = LeitorDicionarios.Singleton()  
18 -  
19 - self._EventHandler_instance = LeitorDicionarios._iInstance  
20 -  
21 - def __getattr__(self, aAttr):  
22 - return getattr(self._iInstance, aAttr)  
23 -  
24 - def __setattr__(self, aAttr, aValue):  
25 - return setattr(self._iInstance, aAttr, aValue)  
26 -  
27 - # Define e inicializa os atributos  
28 - def __init__(self):  
29 - self.__path = "vlibras_user/vlibras-core/data/"  
30 - self.__fileInf = ''  
31 - self.__dicInf = {}  
32 - self.__fileSin = ''  
33 - self.__dicSin = {}  
34 - self.__fileWords = ''  
35 - self.__dicWords = {}  
36 - self.__file2Gen = ''  
37 - self.__dic2Gen = {}  
38 - self.__fileTemVerbs = ''  
39 - self.__dicTemVerbs = {}  
40 - self.createDicInf()  
41 - self.createDicSin()  
42 - self.createDicWords()  
43 - self.createDic2Gen()  
44 - self.createDicTemVerbs()  
45 -  
46 - # Abre o arquivo que contem os verbos no infinitivo e preenche o dicionario com os mesmos  
47 - def createDicInf(self):  
48 - try:  
49 - self.__fileInf = csv.reader(open(self.__path+"dicPortGlosa.csv"), delimiter=";")  
50 - except IOError, (errno, strerror):  
51 - print "I/O error(%s): %s" % (errno, strerror)  
52 - print "createDicInf"  
53 -  
54 - for row in self.__fileInf:  
55 - if row[1] != "":  
56 - try:  
57 - self.__dicInf[row[0].decode("utf-8")] = row[1].decode("utf-8")  
58 - except UnicodeDecodeError:  
59 - self.__dicInf[row[0].decode('iso8859-1').encode('utf-8')] = row[1].decode('iso8859-1').encode('utf-8')  
60 -  
61 - # Abre o arquivo que contem os sinonimos e preenche o dicionario com os mesmos  
62 - def createDicSin(self):  
63 - try:  
64 - self.__fileSin = csv.reader(open(self.__path+"portuguesGlosa.csv"), delimiter=";")  
65 - except IOError, (errno, strerror):  
66 - print "I/O error(%s): %s" % (errno, strerror)  
67 - print "createDicSin"  
68 -  
69 - for row in self.__fileSin:  
70 - if row[1] != "":  
71 - self.__dicSin[row[0].decode("utf-8")] = row[1].decode("utf-8")  
72 -  
73 -  
74 - # Abre o arquivo que contem os tempos verbais  
75 - def createDicTemVerbs(self):  
76 - try:  
77 - self.__fileTemVerbs = csv.reader(open(self.__path+"temposVerbais.csv"), delimiter=";")  
78 - except IOError, (errno, strerror):  
79 - print "I/O error(%s): %s" % (errno, strerror)  
80 - print "createDicTemVerbs"  
81 -  
82 - for row in self.__fileTemVerbs:  
83 - self.__dicTemVerbs[row[0].decode("utf-8")] = row[0].decode("utf-8")  
84 -  
85 - # Abre o arquivo que contem os artigos e preposicoes de acordo com o modelo de idioma passado na chamada e preenche o dicionario com os mesmos  
86 - def createDicWords(self):  
87 - try:  
88 - self.__fileWords = csv.reader(open(self.__path+"hWordsRemove.csv"), delimiter=";")  
89 - except IOError, (errno, strerror):  
90 - print "I/O error(%s): %s" % (errno, strerror)  
91 - print "createDicWords"  
92 -  
93 - for row in self.__fileWords:  
94 - self.__dicWords[row[0].decode("utf-8")] = row[0].decode("utf-8")  
95 -  
96 - # Abre o arquivo que contem os substantivos que sao comuns dos 2 generos e preenche o dicionario com os mesmos  
97 - def createDic2Gen(self):  
98 - try:  
99 - self.__file2Gen = csv.reader(open(self.__path+"subs2Generos.csv"), delimiter=";")  
100 - except IOError, (errno, strerror):  
101 - print "I/O error(%s): %s" % (errno, strerror)  
102 - print "createDic2Gen"  
103 -  
104 - for row in self.__file2Gen:  
105 - self.__dic2Gen[row[0].decode("utf-8")] = row[0].decode("utf-8")  
106 -  
107 - # Retorna o dicionario dos verbos no infinitivo  
108 - def getDicInf(self):  
109 - return self.__dicInf  
110 -  
111 - # Retorna o dicionario dos sinonimos  
112 - def getDicSin(self):  
113 - return self.__dicSin  
114 -  
115 - # Retorna o dicionario dos artigos e preposicoes a serem removidos pelo simplificador  
116 - def getDicWords(self):  
117 - return self.__dicWords  
118 -  
119 - # Retorna o dicionario dos substantivos a serem analisados pelo simplificador  
120 - def getDic2Gen(self):  
121 - return self.__dic2Gen  
122 -  
123 - # Retorna o dicionario dos tempos verbais  
124 - def getDicTemVerbs(self):  
125 - return self.__dicTemVerbs  
126 \ No newline at end of file 0 \ No newline at end of file
translate.py
@@ -1,14 +0,0 @@ @@ -1,14 +0,0 @@
1 -#!/usr/bin/python  
2 -# -*- coding: utf-8 -*-  
3 -  
4 -from Tradutor import *  
5 -  
6 -tradutor = Tradutor()  
7 -  
8 -def iniciar(x):  
9 - try:  
10 - text = x.decode("utf-8")  
11 - except:  
12 - text = x.decode("iso-8859-1")  
13 -  
14 - return tradutor.traduzir(text)