-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainCLVA.py
More file actions
272 lines (232 loc) · 7.92 KB
/
mainCLVA.py
File metadata and controls
272 lines (232 loc) · 7.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
# *- coding: utf-8 -*
# @author: Dante Fernando Bazaldua Huerta
# Manage all connections
import pyrebase
import requests # Hacer query a CLVA-i
import time
import keys as security
import urllib
# Inicializar firebase
firebase = pyrebase.initialize_app(security.config)
# ------------------------ FIREBASE -------------------------
auth = firebase.auth() # Objecto de autenticación
# Iniciar sesion en firebase
user = auth.sign_in_with_email_and_password(
security.email,
security.passwd
)
storage = firebase.storage() # Referencia al storage
db = firebase.database() # Referencia a la base de datos
# Clase para cada uno de los n objetos que pudieran
# suceder al leer el archivo de audio
class LvaProcess(object):
link = ""
response = ""
response_text = ""
status = ""
uid = ""
URL_inside = ""
def __init__(self, link, uid):
self.link = link
self.uid = uid
self.response = ""
self.response_text = ""
self.status = ""
# self._processFile()
# Codifica la URL
def encodeURL(self, urlin):
txt = ""
tmp = ''
for c in urlin:
if c is '?':
tmp = '%3F'
elif c is '=':
tmp = '%3D'
elif c is '&':
tmp = '%26'
elif c is '/':
tmp = '%2F'
elif c is ':':
tmp = '%3A'
elif c is '%':
tmp = '%25'
else:
tmp = c
txt = txt + tmp
# End for loop
return txt
# Proceso que ejecuta conexión con el storage
def _processFile(self):
URL = '/cloud/' + self.uid + '/' + self.link
try:
# Ejecutar solicitud
audio = storage.child(URL).get_url(user['idToken'])
# print user['idToken']
print "URL de descarga: -> %s" %(audio)
# Codificar la URL
e = audio
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cache-Control': 'no-cache',
'N-MS-AUTHCB': security.N_MS_AUTHCB
}
service = security.ra7
url_encoded = urllib.quote(e, safe='')
# print "URL_encoded de descarga: -> %s" %(url_encoded)
# Truncate the string
# info = (e[75:150] + '...') if len(e) > 200 else e
# print info
line_req = service + url_encoded
# Ejecuta la consulta
req = requests.get(line_req, headers=headers)
self.response = req.json()
self.status = req.status_code
self.response_text = req.text
rsp = (
"\t\t"
+ self.uid +
" -> "
+ self.link +
" [ "
+ self.response_text +
" ]"
)
return rsp
# print "\t\t %s -> %s [OK]" %(str(self.uid), str(self.link))
# TODO: Guardar la respuesta en el archivo de texto
except Exception as e:
print "Problema en LvaProcess %s" % (str(e))
class Transaction(object):
uid = ""
# Constructor:
# Id de la transaccion
def __init__(self, uid):
self.uid = uid
pass
# Actualiza la rama con el resultado y la fecha
def updateBranch(self, information):
try:
# Obtener el tiempo actual en el que se realiza la transaccion
timex = time.localtime(time.time())
transaction = db.child("Transfer/" + self.uid).get()
th = transaction.val()
# Cambiar los datos en la rama
th["resultado"] = information
th["date_final"] = time.strftime('%Y/%m/%d - %H:%M:%S %Z', timex)
th["codec"] = "ra7"
th["processed"] = True
# print users
db.child("Transfer").child(self.uid).set(th)
except Exception as e:
# TODO: mejorar el caching pues pudieron pasar muchas cosas como:
# - No se encontró la rama ( fue eliminada por alguna razón )
# - No se pudo obtener de manera correcta el resultado o fecha
print e
DB_PATH_POSITION = 'Encuestas'
DB_PATH_TRANSFER = 'Transfer'
def getPositionKey(key):
try:
element = db.child(DB_PATH_TRANSFER).child(key).get()
tran = element.val()
if 'key_encuesta' not in tran:
return None
except Exception as e:
print str(e)
return None
return tran['key_encuesta']
def getPositionInfo(key_encuesta):
try:
element = db.child(DB_PATH_POSITION).child(key_encuesta).get()
tran = element.val()
if 'cuestionario' not in tran:
return None
except Exception as e:
print str(e)
return None
return tran['cuestionario']
def convertPosIntoPathList(questionary):
count = 0
paths = []
try:
for element in questionary:
for key in element:
if (key == "tipo") and (element[key] == "pregunta"):
paths.append(str(count) + ".wav")
count = count + 1
if count == 0:
return 0
except Exception as e:
print str(e)
return paths
# Adding new recipe: no processing.
class AudioFile(object):
"""
Clase que obtiene todo el archivo de audio
y garantiza un UID para la transacción
"""
audioFile = None
# Rutas relativas para cada audio:
paths = []
uid = ""
# Constructor, asigna un uid para concretar la transaccion
def __init__(self, uid):
self.paths = []
self.uid = uid
# Obtener el archivo de procesamiento automaticamente
key_encuesta = getPositionKey(uid)
if key_encuesta is not None:
quest = getPositionInfo(key_encuesta)
if quest is not None:
self.paths = convertPosIntoPathList(quest)
# self.getProcessingFile() --> Latest process to get the audio files.
# Obtener el archivo con los audios
def getProcessingFile(self):
try:
poi = '/cloud/'+self.uid+'/processing.txt'
self.audioFile = storage.child(poi).get_url(user['idToken'])
# print "URL de descarga: -> %s" %(self.audioFile)
if self.audioFile is not '':
# Aquí se recibe el link del archivo que contiene
# ubicación de los audios
# Procesamiento del URL para obtener los audios
self.process_file(self.audioFile)
except Exception as e:
log = "URL ERROR - " + str(e)
print log
# Modulo de proceso del archivo de texto
def process_file(self, URL):
try:
# Ejecutar solicitud
req = requests.get(URL)
self.readlineByLine(req.text)
# TODO: Mejorar el registro de actividades pues pudieron
# haber sucedido las siguientes:
# - El archivo no está bien escrito
# - El achivo no contenía los correctos archivos
except Exception as e:
print str(e)
# Lee linea por linea el texto completo
def readlineByLine(self, raw):
i = 0
sep = raw.split('\n')
tot = len(sep)
try:
for line in sep:
if i > 4:
realAudio = self.parseLine(line)
new = realAudio.split('\r')
# print "L[%d] - %s" %( i, new )
self.paths.append(str(new[0]))
if i == (tot - 2):
break
i = i + 1
except Exception as e:
print "No se ha leído", e
# No Exception
# Separa la linea y devuelve donde se encuentra cada archivo
def parseLine(self, lineCode):
# print lineCode
separated = lineCode.split('||')
last = separated[4].split('\\')
return last[4]