-
Notifications
You must be signed in to change notification settings - Fork 0
/
gptscrap.py
617 lines (385 loc) 路 24.1 KB
/
gptscrap.py
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
# Clase y m茅todos usados para hacer scraping en https://chat.openai.com/
# Imports.
# - Selenium.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
# To undetected.
import undetected_chromedriver as uc
# Others.
import time
import random
import datetime
import sqlite3
from html import unescape
# Librer铆as para la API.
from flask import Flask, request, jsonify, send_file
from markupsafe import escape
from werkzeug.utils import secure_filename
# Importamos nuestra clase para cargar las configuraciones y dem谩s.
from load import Load
# Cargamos las configuraciones.
load = Load()
lConfig = load.configurations()
# Instanciando la app de Flask.
app = Flask(__name__)
app.config.from_mapping(
SECRET_KEY = load.secretKey,
)
class ChatGPT:
def __init__(self, google_email: str, google_password: str, gpt_premium = False, debug = False, time_to_wait = 5):
"""
# Usa chatGPT sin limitaciones. Es necesario loguear con google.
DONT USE YOUR PERSONAL ACCOUNT, PLEASE! 馃
# Args:
- google_email (str): Your google email.
- google_password (str): Your google password.
- gpt_premium (bool): If you have GPT+ buying.
- debug (bool): Debug mode?
- time_to_wait (float): The time you will wait between pages to click on the buttons. We should ideally make sure that the page is fully loaded, and this can vary by computer, so no one knows your computer better than you.
# Returns:
- None: none.
"""
# Personal Configs
self.google_email = google_email
self.google_password = google_password
self.gpt_premium = gpt_premium
self.debug = debug
self.time_to_wait = time_to_wait
self.is_busy = False
self.responses = []
self.cola = [] # Cola de mensajes.
print(f'[{datetime.datetime.now().time()}] Trying logging with:\n\n\tEmail: {self.google_email}\n\n\tPassword: ************\n\n\tPremium: {"Yes" if self.gpt_premium == True else "No"}\n\n')
# Selenium Confgis
self.url = 'https://chat.openai.com/'
self.options = Options() # Instanciamos las configuraciones de Selenium.
self.options.headless = self.debug # Sin ventana?
self.driver = uc.Chrome(options = self.options) # El navegador que se usar谩. Se inicia.
self.driver.get(self.url) # Petici贸n a la url de ChatGPT.
self.driver.maximize_window()
# | -------------------------- |
# Conexi贸n a la base de datos donde estar谩 el hisyorial.
conn = sqlite3.connect('history.db')
cursor = conn.cursor()
try:
cursor.execute("""
CREATE TABLE history (
from, message, time
)
""")
except:
pass
# Click en el bot贸n de login desde la p谩gina principal de OPENIA (es la p谩gina que aparece directamente al poner chat.openai.com). Esto lo hacemos porque cada que se da al bot贸n genera un ID identificador. De lo contrario ser铆a imposible iniciar sesi贸n (Web de OA).
to_login_button = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-primary'))) # Obtenemos el bot贸n.
to_login_button.click()
# Click en logueo de Google (Web de OA).
to_login_with_google = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'c1df4626c'))) # Obtenemos el bot贸n.
to_login_with_google.click()
# Boton para pasar a poner la password (Web de Google).
next_google_button = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'VfPpkd-LgbsSe-OWXEXe-k8QpJ'))) # Obtenemos el bot贸n.
print(f'[{datetime.datetime.now().time()}] In google login... Writing the email.')
# Tomamos el input del correo (Web de Google).
email_google_input = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'whsOnd'))) # Obtenemos el bot贸n.
email_google_input.send_keys(self.google_email)
# Siguiente p谩gina: password.
next_google_button.click()
time.sleep(5)
# intentamos valdiar si est谩 bien la contrase帽a. Si falla es porque estpa bien la password.
try:
result = self.driver.find_elements(By.CLASS_NAME, 'Jj6Lae')[0].text.lower()
if ('email' in result or 'cuenta' in result or 'account' in result): # Validamos si introdujo bien la contrase帽a.
print(result)
self.driver.close()
print(f'[{datetime.datetime.now().time()}] There has been an error with the credentials. Try to check the credentials.')
exit()
except:
pass
print(f'[{datetime.datetime.now().time()}] In google login... Writing the password.')
# Ponemos la password.
password_google_input = WebDriverWait(self.driver, 7).until(EC.element_to_be_clickable((By.CLASS_NAME, 'whsOnd'))) # Obtenemos el bot贸n.
password_google_input.send_keys(self.google_password)
next_google_button = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'VfPpkd-LgbsSe-OWXEXe-k8QpJ'))) # Obtenemos el bot贸n.
# Click en siguiente. (termina?)
next_google_button.click()
time.sleep(5)
# intentamos valdiar si est谩 bien la contrase帽a. Si falla es porque estpa bien la password.
try:
result = self.driver.find_elements(By.CLASS_NAME, 'OyEIQ')[0].find_elements(By.XPATH, '//div/span')[2]
if ('password' in result.text or 'contrase帽a' in result.text): # Validamos si introdujo bien la contrase帽a.
print(f'[{datetime.datetime.now().time()}] There has been an error with the credentials. Try to check the credentials.')
self.driver.close()
exit()
except:
print(f'[{datetime.datetime.now().time()}] Logged!')
# Ac谩 nos redirige a la web de ChatGPT
# Click en el bot贸n de next si est谩 disponible. Al parecer en las nuevas cuentas de OA pone un anuncio con info de la propia empresa. Lo que validaremos es si esta existe! (Web de OA).
time.sleep(2)
try:
to_next_button = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-neutral'))) # Obtenemos el bot贸n.
if (to_next_button != None):
to_next_button.click()
time.sleep(1)
# Saltamos ahora la siguente ventana de anuncio.
to_next_button = self.driver.find_elements(By.CLASS_NAME, 'btn-neutral')[1]
to_next_button.click()
time.sleep(1)
# Damos ahora en "Done"!
to_dones_button = self.driver.find_elements(By.CLASS_NAME, 'btn-primary')[1]
to_dones_button.click()
except:
pass
print(f'[{datetime.datetime.now().time()}] Ready To Talk, guys c:')
time.sleep(3)
# Instanciamos el input para el texto y el bot贸n de env铆o.
self.input = self.driver.find_element(By.ID, 'prompt-textarea')
self.send_button = self.driver.find_elements(By.CLASS_NAME, 'rounded-md')[-1]
# Running API
print(f'[{datetime.datetime.now().time()}] Running API...')
@app.route("/API/Talk/", methods = ["POST"])
def talk():
# Validamos si nos est谩n pasando una clave de acceso.
if 'AuthKey' in request.form:
AuthKey = request.form['AuthKey'] # Clave de acceso pasada.
auth = False
# Valdidamos la clave.
for username in load.authUsers:
if AuthKey == load.authUsers[username]:
auth = True
break
else:
auth = False
return "You are not authorized to use the API. Contact your system administrator or try again."
# Si est谩 autorizado. Pasamos a la siguiente fase: Recibir el audio.
if (auth):
if 'message' in request.form:
message = request.form['message']
res = self.talk_in_actual_room(message) # Hacemos la petici贸n de generar una respuesta.
return res
else:
message = 'De donde proviene la frase "pan con jam贸n"? Mis compa帽eros dijeron que era del filosofo griego Alquimedes.'
else:
return "You are not authorized on the API side. Contact the developer to get access to the API."
else:
return "It appears that you are not passing an authorization key. Make sure you are passing the 'AuthKey' parameter."
@app.route("/API/Report", methods = ['POST'])
def report():
# Validamos si nos est谩n pasando una clave de acceso.
if 'AuthKey' in request.form:
AuthKey = request.form['AuthKey'] # Clave de acceso pasada.
auth = False
# Valdidamos la clave.
for username in load.authUsers:
if AuthKey == load.authUsers[username]:
auth = True
break
else:
auth = False
return "You are not authorized to use the API. Contact your system administrator or try again."
# Si est谩 autorizado. Pasamos a la siguiente fase: Recibir el audio.
if (auth):
screenshot = self.api_report()
screenshot_route = screenshot['screenshot_url']
return send_file(screenshot_route, mimetype='image/jpg')
else:
return "You are not authorized on the API side. Contact the developer to get access to the API."
else:
return "It appears that you are not passing an authorization key. Make sure you are passing the 'AuthKey' parameter."
@app.route("/API/Restart", methods = ['POST'])
def restart():
# Validamos si nos est谩n pasando una clave de acceso.
if 'AuthKey' in request.form:
AuthKey = request.form['AuthKey'] # Clave de acceso pasada.
auth = False
# Valdidamos la clave.
for username in load.authUsers:
if AuthKey == load.authUsers[username]:
auth = True
break
else:
auth = False
return "You are not authorized to use the API. Contact your system administrator or try again."
# Si est谩 autorizado. Pasamos a la siguiente fase: Recibir el audio.
if (auth):
print('Restarting inference API...')
print(f'[{datetime.datetime.now().time()}] Trying logging with:\n\n\tEmail: {self.google_email}\n\n\tPassword: ************\n\n\tPremium: {"Yes" if self.gpt_premium == True else "No"}\n\n')
try:
# Selenium Confgis
self.url = 'https://chat.openai.com/'
self.options = Options() # Instanciamos las configuraciones de Selenium.
self.options.headless = self.debug # Sin ventana?
self.driver = uc.Chrome(options = self.options) # El navegador que se usar谩. Se inicia.
self.driver.get(self.url) # Petici贸n a la url de ChatGPT.
self.driver.maximize_window()
# | -------------------------- |
# Conexi贸n a la base de datos donde estar谩 el hisyorial.
conn = sqlite3.connect('history.db')
cursor = conn.cursor()
try:
cursor.execute("""
CREATE TABLE history (
from, message, time
)
""")
except:
pass
# Click en el bot贸n de login desde la p谩gina principal de OPENIA (es la p谩gina que aparece directamente al poner chat.openai.com). Esto lo hacemos porque cada que se da al bot贸n genera un ID identificador. De lo contrario ser铆a imposible iniciar sesi贸n (Web de OA).
to_login_button = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-primary'))) # Obtenemos el bot贸n.
to_login_button.click()
# Click en logueo de Google (Web de OA).
to_login_with_google = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'c1df4626c'))) # Obtenemos el bot贸n.
to_login_with_google.click()
# Boton para pasar a poner la password (Web de Google).
next_google_button = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'VfPpkd-LgbsSe-OWXEXe-k8QpJ'))) # Obtenemos el bot贸n.
print(f'[{datetime.datetime.now().time()}] In google login... Writing the email.')
# Tomamos el input del correo (Web de Google).
email_google_input = WebDriverWait(self.driver, 5).until(EC.element_to_be_clickable((By.CLASS_NAME, 'whsOnd'))) # Obtenemos el bot贸n.
email_google_input.send_keys(self.google_email)
# Siguiente p谩gina: password.
next_google_button.click()
time.sleep(5)
# intentamos valdiar si est谩 bien la contrase帽a. Si falla es porque estpa bien la password.
try:
result = self.driver.find_elements(By.CLASS_NAME, 'Jj6Lae')[0].text.lower()
if ('email' in result or 'cuenta' in result or 'account' in result): # Validamos si introdujo bien la contrase帽a.
print(result)
self.driver.close()
print(f'[{datetime.datetime.now().time()}] There has been an error with the credentials. Try to check the credentials.')
exit()
except:
pass
print(f'[{datetime.datetime.now().time()}] In google login... Writing the password.')
# Ponemos la password.
password_google_input = WebDriverWait(self.driver, 7).until(EC.element_to_be_clickable((By.CLASS_NAME, 'whsOnd'))) # Obtenemos el bot贸n.
password_google_input.send_keys(self.google_password)
next_google_button = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'VfPpkd-LgbsSe-OWXEXe-k8QpJ'))) # Obtenemos el bot贸n.
# Click en siguiente. (termina?)
next_google_button.click()
time.sleep(5)
# intentamos valdiar si est谩 bien la contrase帽a. Si falla es porque estpa bien la password.
try:
result = self.driver.find_elements(By.CLASS_NAME, 'OyEIQ')[0].find_elements(By.XPATH, '//div/span')[2]
if ('password' in result.text or 'contrase帽a' in result.text): # Validamos si introdujo bien la contrase帽a.
print(f'[{datetime.datetime.now().time()}] There has been an error with the credentials. Try to check the credentials.')
self.driver.close()
exit()
except:
print(f'[{datetime.datetime.now().time()}] Logged!')
# Ac谩 nos redirige a la web de ChatGPT
# Click en el bot贸n de next si est谩 disponible. Al parecer en las nuevas cuentas de OA pone un anuncio con info de la propia empresa. Lo que validaremos es si esta existe! (Web de OA).
time.sleep(2)
try:
to_next_button = WebDriverWait(self.driver, self.time_to_wait).until(EC.element_to_be_clickable((By.CLASS_NAME, 'btn-neutral'))) # Obtenemos el bot贸n.
if (to_next_button != None):
to_next_button.click()
time.sleep(1)
# Saltamos ahora la siguente ventana de anuncio.
to_next_button = self.driver.find_elements(By.CLASS_NAME, 'btn-neutral')[1]
to_next_button.click()
time.sleep(1)
# Damos ahora en "Done"!
to_dones_button = self.driver.find_elements(By.CLASS_NAME, 'btn-primary')[1]
to_dones_button.click()
except:
pass
print(f'[{datetime.datetime.now().time()}] Ready To Talk, guys c:')
time.sleep(3)
# Instanciamos el input para el texto y el bot贸n de env铆o.
self.input = self.driver.find_element(By.ID, 'prompt-textarea')
self.send_button = self.driver.find_elements(By.CLASS_NAME, 'rounded-md')[-1]
print('The inference source was restarted.')
return 'The inference source was restarted.'
except:
print('An error while we are restarting...')
return 'An error while we are restarting...'
else:
return "You are not authorized on the API side. Contact the developer to get access to the API."
else:
return "It appears that you are not passing an authorization key. Make sure you are passing the 'AuthKey' parameter."
print(f'[{datetime.datetime.now().time()}] API Runned.')
# Configuraci贸n b谩sica de la app. Esto es bueno tenerlo claro para el desplegue.
app.run(port = load.port, debug = load.debug)
# Env铆a un mensaje a ChatGPT.
def talk_in_actual_room(self, message, behaviour = 'Recuerda comportarte como si fueses un bot de discord que busca ayudar a los usuarios y te llamas RetroAssistant, aqu铆 mi texto: '):
"""
# Talk in the actual room with ChatGPT.
# Args:
- message (str): The message to ChatGPT-
# Returns:
- Dict with response.
"""
while True:
if self.is_busy != False:
# Conexi贸n a la base de datos donde estar谩 el hisyorial.
conn = sqlite3.connect('history.db')
cursor = conn.cursor()
self.is_busy = True
# Bot presset. His behaviour.
message = behaviour + message
self.input.send_keys(message) # Escribimos el mensaje en el input.
# Env铆amos el mensaje.
self.send_button = self.driver.find_elements(By.CLASS_NAME, 'rounded-md')[-1] # Lo volvemos a instanciar porque al parecer causa errores.
self.send_button.click()
cursor.execute(f"""
INSERT INTO history VALUES('@Uwu', '{message}', '{datetime.datetime.now().time()}')
""")
conn.commit()
while True:
# btn[1]
# flex
# Regenerate response button (or generating...)
time.sleep(2)
try:
generating_button = self.driver.find_elements(By.CLASS_NAME, 'btn')[1]
generating_button = generating_button.find_element(By.CLASS_NAME, 'flex')
if generating_button.text == 'Stop generating':
print(f'[{datetime.datetime.now().time()}] Generating response...')
elif generating_button.text == 'Regenerate response':
print(f'[{datetime.datetime.now().time()}] We recive a response!')
break
else:
print('Algo ha ocurrido :/')
except:
time.sleep(3) # Si falla, quiere decir que da la opci贸n de seguir generando, quiz谩s esto nos interese despu茅s.
generating_button = self.driver.find_elements(By.CLASS_NAME, 'btn')[1]
generating_button = generating_button.find_element(By.CLASS_NAME, 'flex')
if generating_button.text == 'Stop generating':
print(f'[{datetime.datetime.now().time()}] Generating response...')
elif generating_button.text == 'Regenerate response':
print(f'[{datetime.datetime.now().time()}] We recive a response!')
break
else:
print('Algo ha ocurrido :/')
response = self.driver.find_elements(By.CLASS_NAME, 'markdown') # Obtenemos el 煤ltimo mensaje.
if isinstance(response, list):
self.responses.append(unescape(response[-1].text))
else:
self.responses.append(unescape(response.text))
print(self.responses[-1])
cursor.execute(f"""
INSERT INTO history VALUES ('GPT', '{self.responses[-1]}', '{datetime.datetime.now().time()}')
""")
conn.commit()
print(f'[{datetime.datetime.now().time()}] Message "{message}" sended!')
self.api_report()
self.is_busy = False
return jsonify({'response_message': self.responses[-1], 'actual_time': f'[{datetime.datetime.now().time()}]'}), 200, {'Content-Type': 'application/json; charset=utf-8'}
else:
time.sleep(2)
# Obt茅n un reporte de la API.
def api_report(self):
"""
# Get a report about the API.
# Args:
- Nothing.
# Returns:
- Dict with response.
"""
# Tomamos una captura.
screenshot_route = f'./reports/[GTPWrap] {random.randint(0, 200)} - {random.randint(0, 10)}.png'
self.driver.save_screenshot(screenshot_route)
print(f'API is Busy: {self.is_busy}\nScreenshot: TODO, GENERATE A LINK WITH FLASK')
return {'is_busy': self.is_busy, 'screenshot_url': screenshot_route}
#! TESTS.
ChatGPT(load.credentials['google_email'], load.credentials['google_password'], False)