-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexternalServiceClient.py
More file actions
455 lines (394 loc) · 17 KB
/
Copy pathexternalServiceClient.py
File metadata and controls
455 lines (394 loc) · 17 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
import requests
import sys
import os
import hashlib
from datetime import datetime
EXTERNAL_SERVICE_URL = "http://localhost:8180/ExternalService/"
userID = ""
userEmail = ""
username = ""
userToken = ""
convName = ""
convID = ""
convNextURL = ""
convEndURL = ""
convMessages = None
def main():
print('\nBienvenido al cliente del servicio REST externo de LlamaChat.')
while True:
print('Estado: \033[91mno autenticado\033[0m.')
print('Opciones disponibles:')
print('1. Registrarse')
print('2. Iniciar sesión')
print('3. Salir')
choice = input("\nElige una opción: ")
if choice == '1':
register()
elif choice == '2':
login()
elif choice == '3':
print("\033[91mSaliendo...\033[0m")
sys.exit()
else:
print("Opción \033[91mno válida\033[0m. Inténtalo de nuevo.\n")
if userID != "":
break
clearScreen()
print("\033[92mHas iniciado sesión correctamente. Bienvenido\033[0m")
while True:
print("Estado: \033[92mautenticado\033[0m.")
print("Opciones disponibles:")
print("1. Crear una conversación")
print("2. Ver la lista de conversaciones")
print("3. Ver mis datos y estadísticas")
print("4. Eliminar mi usuario")
print("5. Salir")
choice = input("\nElige una opción: ")
if choice == "1":
createConv()
elif choice == "2":
checkConvList()
elif choice == "3":
checkUserData()
elif choice == "4":
deleteUser()
elif choice == '5':
print("\033[91mSaliendo...\033[0m")
sys.exit()
else:
print("Opción \033[91mno válida\033[0m. Inténtalo de nuevo.\n")
def register():
global userID
global username
global userEmail
global userToken
print("\nOpción elegida: \033[92mregistro\033[0m.")
email = input("Correo electrónico: ")
name = input("Nombre de usuario: ")
password = input("Contraseña: ")
json = {"email": email, "name": name, "password": password}
response = requests.post(EXTERNAL_SERVICE_URL + "u/register", json=json)
if response.status_code == 200:
responseJSON = response.json()
userID = responseJSON['id']
username = responseJSON['name']
userEmail = responseJSON['email']
userToken = responseJSON['token']
else:
print(f"\033[91mHa ocurrido un error al hacer el registro. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
def login():
global userID
global username
global userEmail
global userToken
print("\nOpción elegida: \033[92miniciar sesión\033[0m.")
email = input("Correo electrónico: ")
password = input("Contraseña: ")
json = {"email": email, "password": password}
response = requests.post(EXTERNAL_SERVICE_URL + "checkLogin", json=json)
if response.status_code == 200:
responseJSON = response.json()
userID = responseJSON['id']
username = responseJSON['name']
userEmail = responseJSON['email']
userToken = responseJSON['token']
else:
print(f"\033[91mHa ocurrido un error al iniciar sesión. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
def createConv():
global convName
global convID
global convNextURL
global convEndURL
global convMessages
print("\nOpción elegida: \033[92mcrear una conversación\033[0m.")
convName = input("Nombre de la conversación: ")
url = EXTERNAL_SERVICE_URL + f"u/{userID}/dialogue"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
requestJSON = {"convName": convName}
response = requests.post(url, json=requestJSON, headers=headers)
if response.status_code == 201:
responseJSON = response.json()
convName = responseJSON.get('name')
convID = responseJSON.get('ID')
convNextURL = responseJSON.get('nextURL')
convEndURL = responseJSON.get('endURL')
convMessages = None
print("\033[92mConversación creada correctamente.\033[0m")
sendPrompts()
else:
print(f"\033[91mHa ocurrido un error al crear la conversación. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
def checkConvList():
print("\nOpción elegida: \033[92mver la lista de conversaciones\033[0m.")
url = EXTERNAL_SERVICE_URL + f"u/{userID}/dialogue"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
allConvs = response.json().get('allConvs', [])
if allConvs:
print("Conversaciones disponibles: ")
convStatus = {1: '\033[92mabierta\033[0m', 2: '\033[93mocupada\033[0m', 3: '\033[91mcerrada\033[0m'}
for index, conv in enumerate(allConvs, 1):
name = conv.get('name')
status = conv.get('status')
statusDescription = convStatus.get(status, '\033[90mdesconocido\033[0m')
print(f"{index}. {name} - Estado: {statusDescription}")
print("\nOpciones disponibles:")
print("1. Entrar a una conversación")
print("2. Eliminar todas las conversaciones")
print("3. Volver al menú principal")
choice = input("\nElige una opción: ")
if choice == "1":
conv_choice = int(input("Elige el número de la conversación a la que deseas entrar: "))
if 1 <= conv_choice <= len(allConvs):
enterConversation(allConvs[conv_choice - 1]['id'])
else:
print("\033[91mNúmero de conversación no válido. Volviendo al menú principal...\033[0m\n")
elif choice == "2":
print("\nOpción elegida: \033[92meliminar todas las conversaciones\033[0m.")
print("¿Estás seguro de que quieres eliminar todas las conversaciones? \033[91mEsta acción es irreversible.\033[0m")
print("1. Sí")
print("2. No")
choiceDelAllConvs = input("\nOpción elegida: ")
if choiceDelAllConvs == "1":
print("\033[91mEliminando todas las conversaciones...\033[0m")
url = EXTERNAL_SERVICE_URL + f"u/{userID}/delAllConvs"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
response = requests.delete(url, headers=headers)
if response.status_code == 200:
print("\033[92mSe han eliminado todas las conversaciones.\033[0m\n")
return
else:
print(f"\033[91mHa ocurrido un error al eliminar todas las conversaciones. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
elif choiceDelAllConvs == "2":
print("\033[92mVolviendo al menú principal...\033[0m\n")
return
else:
print("Opción \033[91mno válida\033[0m. Volverás al menú principal\n")
return
elif choice == "3":
print("\033[92mVolviendo al menú principal...\033[0m\n")
return
else:
print("Opción \033[91mno válida\033[0m. Se volverá al menú principal.\n")
else:
print("\033[91mNo hay conversaciones disponibles.\033[0m\n")
else:
print(f"\033[91mHa ocurrido un error al obtener todas las conversaciones. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
def enterConversation(enterConvID):
global convID
global convName
global convNextURL
global convEndURL
global convMessages
url = EXTERNAL_SERVICE_URL + f"u/{userID}/dialogue/{enterConvID}"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
responseJSON = response.json()
convID = responseJSON.get('convID')
convName = responseJSON.get('convName')
convNextURL = responseJSON.get('nextURL')
convEndURL = responseJSON.get('endURL')
convMessages = responseJSON.get('dialogues')
convStatus = responseJSON.get('status')
if convStatus == 3:
conversationLog()
else:
sendPrompts()
else:
print(f"\033[91mHa ocurrido un error al obtener los datos de la conversación. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
def conversationLog():
global convName
global convID
global convMessages
print(f"\n\033[92mConversación actual: \033[35m{convName}\033[0m")
if convMessages is not None:
for dialogue in convMessages:
print("\033[92mPregunta: \033[35m" + dialogue['prompt'])
print("\033[92mRespuesta: \033[35m" + dialogue['answer'] + "\n")
print("\n\033[0mOpciones disponibles:")
print("1. Eliminar la conversación")
print("2. Volver al menú principal")
choice = input("\nElige una opción: ")
if choice == "1":
print("\nOpción elegida: \033[92meliminar la conversación\033[0m.")
print("¿Estás seguro de que quieres eliminar la conversación? \033[91mEsta acción es irreversible.\033[0m")
print("1. Sí")
print("2. No")
choiceDelConv = input("\nOpción elegida: ")
if choiceDelConv == "1":
print("\033[91mEliminando la conversación...\033[0m")
url = EXTERNAL_SERVICE_URL + f"u/{userID}/dialogue/{convID}/del"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
response = requests.delete(url, headers=headers)
if response.status_code == 200:
print("\033[92mSe ha eliminado la conversación.\033[0m\n")
return
else:
print(f"\033[91mHa ocurrido un error al eliminar la conversación. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
elif choiceDelConv == "2":
print("\033[92mVolviendo al menú principal...\033[0m\n")
return
else:
print("Opción \033[91mno válida\033[0m. Volverás al menú principal\n")
return
elif choice == "2":
print("\033[92mVolviendo al menú principal...\033[0m\n")
return
else:
print("Opción \033[91mno válida\033[0m. Volverás al menú principal\n")
return
def sendPrompts():
global convName
global convID
global convNextURL
global convEndURL
global convMessages
print(f"\n\033[92mConversación actual: \033[35m{convName}\033[0m")
if convMessages is not None:
for dialogue in convMessages:
print("\033[92mPregunta: \033[35m" + dialogue['prompt'])
print("\033[92mRespuesta: \033[35m" + dialogue['answer'] + "\n")
while True:
print("\033[92mLeyenda:\n- \033[35m\"q\"\033[92m: salir de la conversación\n- \033[35m\"end\"\033[92m: terminar la conversación\033[0m\n")
prompt = input("Introduce el prompt a enviar: ")
print(f"\033[92mPrompt detectado: \033[35m{prompt}\033[0m")
if prompt == "end":
print("\033[91mTerminando la conversación...\033[0m")
url = f"http://localhost:8180/ExternalService{convEndURL}"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
response = requests.post(url, headers=headers)
if response.status_code == 200:
convID = ""
convName = ""
convNextURL = ""
convEndURL = ""
convMessages = None
print("\033[92mSe ha finalizado correctamente la conversación.\033[0m\n")
break
else:
print(f"\033[91mHa ocurrido un error al finalizar la conversación. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
elif prompt == "q":
print("\033[92mVolviendo al menú principal...\033[0m\n")
return
else:
print("\033[92mEnviando prompt...\033[0m")
timestamp = datetime.now()
timestamp = datetime.timestamp(timestamp)
timestamp = round(timestamp * 1000)
requestJSON = {'userID': userID, 'convID': convID, 'prompt': prompt, 'timestamp': timestamp}
url = f"http://localhost:8180/ExternalService{convNextURL}"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
response = requests.post(url, json=requestJSON, headers=headers)
if response.status_code == 200:
answerJSON = response.json()
lastAnswer = answerJSON['dialogues'][-1]['answer']
print(f"\033[92mRespuesta: \033[35m{lastAnswer}\033[0m\n")
elif response.status_code == 204:
print(f"\033[91mError: esta conversación aún no está lista para mandar más mensajes\033[0m\n")
else:
print(f"\033[91mHa ocurrido un error al enviar el prompt. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
def checkUserData():
print("\nOpción elegida: \033[92mver mis datos y estadísticas\033[0m.")
url = EXTERNAL_SERVICE_URL + f"u/{userID}/stats"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
statsJSON = response.json()
createdConvs = statsJSON.get('createdConvs', 0)
promptCalls = statsJSON.get('promptCalls', 0)
else:
print(f"\033[91mHa ocurrido un error al obtener tus estadísticas. Código: {response.status_code}\033[0m")
createdConvs = 0
promptCalls = 0
print(f"Email actual: {userEmail}")
print(f"Nombre de usuario: {username}")
print(f"Conversaciones creadas: {createdConvs}")
print(f"Llamadas al prompt: {promptCalls}\n")
def deleteUser():
print("\nOpción elegida: \033[92meliminar mi usuario\033[0m.")
print("¿Estás seguro de que quieres eliminar tu usuario? \033[91mEsta acción es irreversible.\033[0m")
print("1. Sí")
print("2. No")
choice = input("\nOpción elegida: ")
if choice == "1":
print("\033[91mEliminando usuario...\033[0m")
url = EXTERNAL_SERVICE_URL + f"u/deleteUser/{userID}"
currentDate = datetime.now().strftime("%Y-%m-%d")
authToken = genAuthToken(url, currentDate, userToken)
headers = {
"User": userID,
"Date": currentDate,
"Auth-Token": authToken
}
response = requests.delete(url, headers=headers)
if response.status_code == 200:
print("Usuario \033[92meliminado\033[0m. Gracias por usar este servicio.")
print("\033[91mSaliendo...\033[0m")
sys.exit()
else:
print(f"\033[91mHa ocurrido un error al eliminar el usuario. Código: {response.status_code}. Por favor, inténtalo de nuevo\033[0m\n")
elif choice == "2":
return
else:
print("Opción \033[91mno válida\033[0m. Volverás al menú principal\n")
return
def genAuthToken(url, date, userToken):
decodedStr = f"{url}{date}{userToken}"
md5String = hashlib.md5(decodedStr.encode())
return md5String.hexdigest()
def clearScreen():
if os.name == 'nt':
os.system('cls')
else:
os.system('clear')
if __name__ == "__main__":
main()