-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselenium_chat.py
1676 lines (1259 loc) · 61.5 KB
/
selenium_chat.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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import html
import os
import random
import re
import time
import json
# import win32com.client as comclt
import pyautogui
import pyperclip
from selenium import webdriver
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium_stealth import stealth
from webdriver_manager.chrome import ChromeDriverManager
from compare_translations import unpickle_paragraphs, pickle_paragraphs
from lib import my_text
from lib import time_it
from lib import my_prompts_th_perplexity
from lib import my_prompts_ch_perplexity
def init_session():
global driver, actions, attach_to_chrome_remote_debug, el, conf, answer_conent_mem, window_tab_titles, prompt, paragraphs
conf = {}
conf['project'] = 'prj_lp_fug_01'
el = {'chatGPT': {}, 'perplexity': {}, 'aiStudio': {}}
el['chatGPT']['code_blocks_class'] = '.p-4' # code element
el['chatGPT']['send_button_class'] = 'button[data-testid="send-button"]' # send button
el['chatGPT']['answers_class'] = 'div[data-message-author-role="assistant"]' # each anser window
el['chatGPT']['question_class'] = 'div[data-message-author-role="user"]' # each anser window
el['chatGPT']['prompt_textarea_id'] = 'prompt-textarea'
el = {'chatGPT': {}, 'perplexity': {}, 'aiStudio': {}}
el['aiStudio']['code_blocks_class'] = '.p-4' # code element
el['aiStudio']['send_button_class'] = 'button[data-testid="send-button"]' # send button
el['aiStudio']['answers_class'] = 'div.editor div.ql-editor' # each anser window
el['aiStudio']['stop_button'] = 'button.run-button.stoppable'
el['aiStudio']['run_button'] = 'button.run-button'
el['aiStudio']['question_class'] = 'div[data-message-author-role="user"]' # each anser window
el['aiStudio']['prompt_textarea'] = 'div.editor div'
# element changes when screenorientation changes to horizontal, just need to reassign the element with .find_element
# el['chatGPT']['continue_button_class'] = 'polygon[points="11 19 2 12 11 5 11 19"]'
el['chatGPT']['continue_button_class'] = '.-rotate-180'
# len(driver.find_elements(By.CSS_SELECTOR, 'div[data-message-author-role="assistant"]'))*2
# == len(driver.find_elements(By.CSS_SELECTOR, '.w-full .text-gray-400.visible')) => chatgpt answer complete
el['chatGPT']['completed_converstion_parts_marker'] = '.w-full .text-gray-400.visible'
el['perplexity']['code_blocks_class'] = 'div.codeWrapper code' # code element
el['perplexity']['send_button_class'] = '.grow button svg[data-icon="arrow-right"]' # send button
el['perplexity']['send_followup_button_class'] = '.grow button svg[data-icon="arrow-up"]' # send button
el['perplexity']['answers_class'] = 'div.min-w-0.break-words div div' # each anser window
el['perplexity']['question_class'] = 'div[data-message-author-role="user"]' # each anser window
el['perplexity']['prompt_textarea'] = 'textarea.col-end-4'
# if the botton has the class 'text-textOff' = pro disabled, 'text-super' = pro enabled
el['perplexity']['pro_toggle'] = 'button[data-testid="copilot-toggle"]'
el['perplexity']['pro_toggle_inactive'] = 'button.text-textOff[data-testid="copilot-toggle"]'
el['perplexity']['server_error_text'] = 'Sorry! There was a server error'
el['perplexity']['send_output_lang_class'] = 'textarea[placeholder="Programming language"]'
el['perplexity']['answer_stop_button'] = 'svg[data-icon="circle-stop"]'
el['perplexity']['attach_class'] = 'svg[data-icon="circle-plus"]'
el['perplexity']['skip_followup_button_class'] = 'svg[data-icon="forward"]'
el['perplexity']['check_claude_opus'] = "//div[text()='Claude 3 Opus']"
el['perplexity']['check_chatGPT'] = "//div[text()='GPT-4 Turbo']"
el['perplexity']['check_chatGPTo'] = "//div[text()='GPT-4 Omni']"
el['perplexity']['check_model'] = ".tracking-wide']"
prompt = {}
conf['google_account'] = 'wdcmm' #default google account to use - changes the url of saved prompt
continue_prompt = 'continue to translate following the specified rules from above, start 1 item previous before you stoped.'
continue_prompt = 'translate all <item> from attribute id=0 to id=90, and do not output attribute gr or tk of <item>. '
window_tab_titles = {}
user_data_dir = '~/.config/chrome-remote'
# Setup Chrome options to use the user data directory
chrome_options = webdriver.ChromeOptions()
chrome_options.binary_location = "/opt/chrome-linux64/chrome"
chrome_driver_path = '/usr/local/bin/chromedriver'
if attach_to_chrome_remote_debug:
# this one line connect it to chrome remote debugg.. with the debugger account
# start chrome with debugg mode first:
# cd "C:\Program Files\Google\Chrome\Application\"
# .\chrome.exe --remote-debugging-port=9222 --user-data-dir="C:/ChromeDevSession"
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")
else:
# this will start a new chrome instance, but with the default chrome user account
chrome_options.add_argument(f'user-data-dir={user_data_dir}')
# Setup ChromeDriver
s = Service(executable_path=chrome_driver_path)
# Initialize the Chrome driver with the options
driver = webdriver.Chrome(service=s, options=chrome_options)
# Apply stealth
stealth(driver,
languages=["en-US", "en"],
vendor="Google Inc.",
platform="Win32",
webgl_vendor="Intel Inc.",
renderer="Intel Iris OpenGL Engine",
fix_hairline=True,
)
if attach_to_chrome_remote_debug:
# Get the title of the current page
title = driver.title
print(f'current tab title: {driver.title}')
else:
# Open the new webpage
driver.get('https://chat.openai.com') # Replace with the URL of the webpage you want to access
# Create an ActionChains object
actions = ActionChains(driver)
def click_skip_follow_up_question(ai='perplexity', wait_for_element_loaded=0):
# # enter follow up input..
# retLangE = driver.find_element(By.CSS_SELECTOR, el['perplexity']['send_output_lang_class'])
# actions.move_to_element(retLangE).perform()
#
# send_text_slowly(retLangE, "xml", speed=0.001)
# time.sleep(0.5)
# send_text_slowly(retLangE, "\n", speed=0.01)
try:
# if skip button available, click it
if wait_for_element_loaded > 0:
wait_for_element_class(el['perplexity']['skip_followup_button_class'])
skipE = driver.find_element(By.CSS_SELECTOR, el['perplexity']['skip_followup_button_class'])
time.sleep(0.2)
actions.move_to_element(skipE).perform()
time.sleep(0.2)
skipE.click()
time.sleep(0.2)
return True
except Exception as e:
return False
def wait_untill_no_element_with_innertext(text):
present = True
i = 0
while present:
try:
elFrom = driver.find_element(By.XPATH, f"//div[text()='{text}']")
except Exception as e:
return True
i += 1
if i > 120:
print('waited too long for upload to finish (timeout 120s)')
return False
time.sleep(1)
return True
def wait_for_element_id(element_id, max_seconds_to_wait=10):
try:
# Wait up to 10 seconds for the element to be present in the DOM
element = WebDriverWait(driver, max_seconds_to_wait).until(
EC.presence_of_element_located((By.ID, element_id))
)
print(f"Element with ID '{element_id}' is present.")
except TimeoutException:
print(f"Timed out ({max_seconds_to_wait}s) waiting for element with ID '{element_id}' to load.")
def wait_for_element_class(element_class, max_wait=10):
try:
# Wait up to 10 seconds for the element to be present in the DOM
element = WebDriverWait(driver, max_wait).until(
EC.presence_of_element_located((By.CSS_SELECTOR, element_class))
)
print(f"Element with ID '{element_class}' is present.")
except TimeoutException:
print(f"Timed out ({max_wait}s) waiting for element with CLASS '{element_class}' to load.")
def get_model_name():
global el
try:
div_element = driver.find_element(By.XPATH, el['perplexity']['check_claude_opus'])
return 'claude_opus'
except:
pass
try:
div_element = driver.find_element(By.XPATH, el['perplexity']['check_chatGPTo'])
return 'chatGPTo'
except:
pass
try:
div_element = driver.find_element(By.XPATH, el['perplexity']['check_chatGPT'])
return 'chatGPT'
except:
pass
return 'unknown'
def get_last_element(element_class, xpath=False):
if xpath:
elements = driver.find_elements(By.XPATH, element_class)
else:
elements = driver.find_elements(By.CSS_SELECTOR, element_class)
# Select the last element from the list
if elements: # Check if the list is not empty
last_element = elements[-1]
# Now, you can interact with the last_element, e.g., clicking it
# last_element.click()
else:
print(f"No elements with class '{element_class}' found.")
return False
return last_element
def wait_untill_element_unchanged(element_class, seconds=5, last_element=True):
# Specify the locator for the element you want to monitor
try:
# Initially wait for the element to be present
element = get_last_element(element_class)
unchanged_for = 0
start_time = time.time()
previous_text = element.text
# Loop until the element's text doesn't change for 5 seconds
while unchanged_for < seconds:
time.sleep(0.5) # Check every 0.5 seconds to reduce load
try:
# Re-find the element to get the current state
element = get_last_element(element_class)
current_text = element.text
if current_text == previous_text:
# Calculate how long the text has been unchanged
unchanged_for = time.time() - start_time
else:
# Reset timer if the text has changed
previous_text = current_text
start_time = time.time()
unchanged_for = 0
except:
# Handle cases where the element might not be found anymore
print("Element no longer found.")
break
except Exception as e:
print(f"An error occurred: {str(e)}")
finally:
pass
def send_text_slowly(element, text, speed=0.001):
for char in text:
element.send_keys(char)
pause = random.uniform(speed, speed * 10) # Generate a random pause between 0.1 and 0.3 seconds
time.sleep(pause) # Pause for the generated duration
def get_current_tab_id():
current_window = driver.current_window_handle
windows = driver.window_handles
current_index = windows.index(current_window)
return current_index
def goto_tab(tab='first'):
""" the numberings is from newest to oldest (index 0 is the tab created last)
valid: last, first, next, prev/previous, int (=tab nr), cycle (to see the order)
"""
global driver
# valid: cycle, last, first, next, prev/previous or an int
current_window = driver.current_window_handle
windows = driver.window_handles
current_index = windows.index(current_window)
if tab.isdigit():
next_index = int(tab) # Use modulo to loop back to the first tab if at the end
elif tab == 'first':
next_index = len(windows) - 1 # Use modulo to loop back to the first tab if at the end
elif tab == 'last':
next_index = 0 # Use modulo to loop back to the first tab if at the end
elif tab == 'next':
next_index = (current_index - 1) % len(windows) # Use modulo to loop back to the first tab if at the end
elif tab == 'prev' or tab == 'previous':
next_index = (current_index - 1) % len(windows) # Use modulo to loop back to the first tab if at the end
elif tab == 'cycle':
next_index = current_index
for i in range(20):
next_index = (next_index + 1) % len(windows)
driver.switch_to.window(windows[next_index])
if next_index == 0:
print('first tab - short pause')
time.sleep(2)
time.sleep(1)
else:
return False # Use modulo to loop back to the first tab if at the end
driver.switch_to.window(windows[next_index])
return True
def new_tab(url='https://chat.openai.com'):
global driver
# https://www.selenium.dev/documentation/webdriver/interactions/windows/
# driver.execute_script(f"window.open('{url}', '_blank');")
# goto_tab('last')
driver.switch_to.new_window('tab')
# loads a url and waits until loaded
driver.get(url)
time.sleep(2)
def is_perplexity_pro_enabled(alert=False):
try:
proE = driver.find_element(By.CSS_SELECTOR, el['perplexity']['pro_toggle_inactive'])
# if element found => pro not enabled
if alert:
pyautogui.alert('pro not enabled!!')
return False
except Exception as e:
# pro is enabled
return True
def is_server_error(retries=0, reload=True, pause_between_retries=60, alert=False):
for i in range(retries+1):
try:
errE = driver.find_element(By.XPATH, f"//h1[contains(text(), '{el['perplexity']['server_error_text']}')]")
# if element found => server error page detected
if alert:
pyautogui.alert('Server Error!!')
if reload:
tab_close_if_url_starts_with(url_start='https://www.perplexity.ai/')
new_tab('https://www.perplexity.ai/')
# Switch to the new window, which brings it into focus
window_handle = driver.current_window_handle
driver.switch_to.window(window_handle)
time.sleep(pause_between_retries)
except Exception as e:
# no error detected, just return
return False
return True
def is_the_answer_finished(platform='perplexity'):
if platform == 'aiStudio':
try:
stop_button = driver.find_element(By.CSS_SELECTOR, el['aiStudio']['stop_button'])
return False
except Exception as e:
print('no Stop button found -> finished ' + get_identifier())
return True
if platform == 'chatGPT':
# len(driver.find_elements(By.CSS_SELECTOR, 'div[data-message-author-role="assistant"]'))*2
# == len(driver.find_elements(By.CSS_SELECTOR, '.w-full .text-gray-400.visible')) => chatgpt answer complete
try:
answers_chatGPT = len(driver.find_elements(By.CSS_SELECTOR, el['chatGPT']['answers_class']))
answer_edit_icons = len(
driver.find_elements(By.CSS_SELECTOR, el['chatGPT']['completed_converstion_parts_marker']))
if answers_chatGPT * 2 == answer_edit_icons:
return True
except Exception as e:
print('no marker found to check if chatGPT is done answering')
return False
if platform == 'perplexity':
# len(driver.find_elements(By.CSS_SELECTOR, 'div[data-message-author-role="assistant"]'))*2
# == len(driver.find_elements(By.CSS_SELECTOR, '.w-full .text-gray-400.visible')) => chatgpt answer complete
try:
stop_button = driver.find_element(By.CSS_SELECTOR, el['perplexity']['answer_stop_button'])
return False
except Exception as e:
print('no Stop button found -> finished ' + get_identifier())
return True
return False
def set_title(title):
driver.execute_script(f"document.title = '{title}'")
def test_basic_elements():
global el, driver
# set title of active window
driver.execute_script("document.title = 'selenium zombie 1'")
# get_last_element(element_class) # last answer
# driver.find_element(By.CSS_SELECTOR, element_class)
# driver.find_element(By.ID, element_class)
wait_for_element_id('prompt-textarea', 30)
try:
promptE = driver.find_element(By.ID, el['chatGPT']['prompt_textarea_id'])
except NoSuchElementException as e:
print('no prompt input field found!')
sendE = driver.find_element(By.CSS_SELECTOR, el['chatGPT']['send_button_class'])
# move to prompt field
actions.move_to_element(promptE).perform()
promptE.click()
# enter some question
pr = 'hi there'
promptE.send_keys(pr)
# send the prompt
actions.move_to_element(sendE).perform()
sendE.click()
# get the last answer element
answerE = get_last_element(el['chatGPT']['answers_class'])
answerE.text
# find the last code element inside the answerE element
codeE = answerE.find_element(By.XPATH, ".//code[last()]")
# send some java script
# driver.execute_script("window.location.href = 'https://chat.openai.com';")
# driver.execute_script("alert('spookey');")
# wait untill the last element on the webpage of this class doesnt change any more
# eg the AI is done with answering
wait_untill_element_unchanged(el['chatGPT']['answers_class'], 5, last_element=True)
def click_on_contiune_prompt():
global el
try:
# check if contiune is available
continueEl = driver.find_element(By.CSS_SELECTOR, el['chatGPT']['continue_button_class'])
current_window = driver.current_window_handle
windows = driver.window_handles
current_index = windows.index(current_window)
# move to button
actions.move_to_element(continueEl).perform()
print(f'continued with window "{driver.title}" id_{current_index}')
# click
continueEl.click()
return True
except NoSuchElementException as e:
print('no continue input field found.')
except Exception as e:
print('not found, but different error')
return False
def click_send_prompt(platform='perplexity', wait_for_element_loaded=0):
""" wait_for_element_loaded = seconds to wait for element to be available before giving up (0=dont wait)"""
global el
# get send prompt button element
if platform == 'chatGPT':
if wait_for_element_loaded > 0:
wait_for_element_class(el['chatGPT']['send_button_class'], wait_for_element_loaded)
try:
sendE = driver.find_element(By.CSS_SELECTOR, el['chatGPT']['send_button_class'])
except Exception as e:
print('no send button found..')
return False
if platform == 'aiStudio':
if is_the_answer_finished(platform):
try:
sendE = driver.find_element(By.CSS_SELECTOR, el['aiStudio']['run_button'])
except Exception as e:
print(' no run/stop button found.')
if platform == 'perplexity':
wait_untill_no_element_with_innertext("Uploading...")
# perplexity has 2 butoons
if wait_for_element_loaded > 0:
wait_for_element_class(el['perplexity']['send_button_class'], wait_for_element_loaded)
try:
sendE = driver.find_element(By.CSS_SELECTOR, el['perplexity']['send_button_class'])
except Exception as e:
try:
# if it is not the first question of the prompt, the send button is not arrow-left, but arrow-up
sendE = driver.find_element(By.CSS_SELECTOR, el['perplexity']['send_followup_button_class'])
except Exception as e:
print('no send prompt button found')
return False
try:
time.sleep(0.3)
actions.move_to_element(sendE).perform()
time.sleep(0.2)
sendE.click()
time.sleep(0.3)
except Exception as e:
print('couldnt click send on tab ' + get_identifier())
def past_prompt(text, platform='perplexity', click_send=False, speed=0.0001, use_paste=True, project=''):
global driver, el
prompt, pa = text
# test for el['perplexity']['answers_class']
if platform == 'chatGPT':
wait_for_element_id(el['chatGPT']['prompt_textarea_id'], 30)
if platform == 'perplexity':
wait_for_element_class(el['perplexity']['prompt_textarea'], 30)
if platform == 'aiStudio':
wait_for_element_class(el['aiStudio']['prompt_textarea'], 30)
# get text input element
try:
if platform == 'chatGPT':
promptE = driver.find_element(By.ID, el['chatGPT']['prompt_textarea_id'])
if platform == 'perplexity':
promptE = driver.find_element(By.CSS_SELECTOR, el['perplexity']['prompt_textarea'])
if platform == 'aiStudio':
promptE = driver.find_element(By.CSS_SELECTOR, el['aiStudio']['prompt_textarea'])
except NoSuchElementException as e:
print('no prompt input field found! ' + get_identifier())
# move to prompt field
actions.move_to_element(promptE).perform()
promptE.click()
# best option is to use paste to enter the prompt (quick)
if use_paste:
time.sleep(0.1)
# send_text_slowly(promptE, ' ', speed=speed)
# time.sleep(0.1)
# put text in clipboard
pyperclip.copy(prompt)
# past clipboard to element
promptE.send_keys(Keys.CONTROL + 'v')
time.sleep(2.5)
if platform == 'aiStudio':
answer_marker = '\n\n-----Ai answer text:-----'
# copy xml to prompt
pyperclip.copy(pa + answer_marker)
# past clipboard to element
time.sleep(1)
promptE.send_keys(Keys.CONTROL + 'v')
time.sleep(2.1)
# promptE.send_keys(Keys.CONTROL + Keys.ENTER)
# click_send = False # shortcut to send -> easy
# time.sleep(20) # maybe 10 works as well, easily too much
if platform == 'chatGPT':
# copy xml to prompt
pyperclip.copy(pa)
# past clipboard to element
promptE.send_keys(Keys.CONTROL + 'v')
if platform == 'perplexity':
use_attachent = False
if use_attachent: # attach file for text to translate
# attach file
attach_file(pa, project, ai='perplexity')
# wait until upload finished (if attaching file) before continuing
wait_untill_no_element_with_innertext("Uploading...")
else: # simple past for text to translate
# copy xml to prompt
#actions.move_to_element(promptE).perform()
#promptE.click()
pyperclip.copy(pa)
time.sleep(1)
# past clipboard to element
promptE.send_keys(Keys.CONTROL + 'v')
# in case of the "are you human" question
else:
send_text_slowly(promptE, prompt + pa, speed=speed)
time.sleep(3)
# send the prompt
if click_send:
# Scroll to the bottom of the page
tab_scroll_to_bottom(platform=platform)
click_send_prompt(platform, wait_for_element_loaded=15)
time.sleep(2)
# Scroll to the bottom of the page
tab_scroll_to_bottom(platform)
if platform == 'aiStudio':
# check if error (too many requests?), wait a bit and click send again
try:
for ii in range(20):
if not check_if_element_contains_pattern(promptE, pattern='⚠ Error'):
break
time.sleep(6*60)
click_send_prompt(platform, wait_for_element_loaded=15)
except Exception as e:
print(" couldnt click..")
# perplexity wants to help with the output.. tell it xml
if platform == 'perplexity':
try:
click_send_prompt(platform, wait_for_element_loaded=0)
time.sleep(5)
# Scroll to the bottom of the page
tab_scroll_to_bottom()
time.sleep(2) # Wait for the page to load after scrolling (adjust as needed)
# skip follow up input, because it sometimes asks for 2 things..
click_skip_follow_up_question(platform, wait_for_element_loaded=15)
time.sleep(2)
# Scroll to the bottom of the page
tab_scroll_to_bottom()
# try a second time, sometimes doesnt work
click_skip_follow_up_question()
# retLangE.element.send_keys(Keys.ENTER)
except Exception as e:
print('couldnt choose the output lang in tab ' + get_identifier())
return True
def attach_file(text, project_name, ai='perplexity'):
# put text in clipboard
attachE = driver.find_element(By.CSS_SELECTOR, el['perplexity']['attach_class'])
# attachE.SendKeys("C:\\Some_Folder\\MyFile.txt");
attachE.click()
with open(f"{project_name}/paste_tmp.txt", 'w', encoding='utf-8') as file:
file.write(text)
abs_script_path = script_directory = os.path.dirname(os.path.abspath(__file__))
# sleep = 1
# version 1 (win10):
# windowsShell = comclt.Dispatch("WScript.Shell")
# time.sleep(sleep)
# windowsShell.SendKeys(f'{abs_script_path}\\{project_name}')
# time.sleep(sleep)
# windowsShell.SendKeys("{ENTER}") # can do "{TAB}" as well..
# time.sleep(sleep)
# windowsShell.SendKeys(f'paste_tmp.txt')
# time.sleep(sleep)
# windowsShell.SendKeys("{ENTER}") # can do "{TAB}" as well..
# time.sleep(sleep)
# version 2 (pip install pyautogui):
# import pyautogui
#
# # Optional: Wait for a few seconds to switch to the window where you want to send the keystrokes
# time.sleep(5)
try:
time.sleep(3)
# # Find the window with the title 'open'
# windows = pyautogui.getWindowsWithTitle('Open')
#
# if len(windows) > 0:
# # If the window is found, activate it to bring it to the foreground
# windows[0].activate()
# else:
# print("No window with the title 'open' found.")
click_on_open_dialog()
is_window_focused('Open', force=True)
time.sleep(0.5)
# go to project path
pyautogui.typewrite(f'{abs_script_path}\\{project_name}')
time.sleep(1)
# Sending the Enter key
pyautogui.press('enter')
time.sleep(1)
# open tmp file (upload)
pyautogui.typewrite(f'paste_tmp.txt')
time.sleep(1)
# Sending the Enter key
pyautogui.press('enter')
time.sleep(1)
except Exception as e:
print('Attaching file failed')
def click_on_open_dialog():
try:
# Find the window with the title 'open'
windows = pyautogui.getWindowsWithTitle('open')
if len(windows) > 0:
# If the window is found, get its coordinates and size
window = windows[0]
x, y, width, height = window.left, window.top, window.width, window.height
# Calculate the center point of the window
center_x = x + width // 2
center_y = y + height // 2
click_y = y + 10
# Move the mouse to the center of the window
pyautogui.moveTo(center_x, click_y)
# Perform a mouse click at the center of the window
pyautogui.click()
else:
print("No window with the title 'open' found.")
except Exception as e:
print('window open not found..')
def is_window_focused(window_title, force=False):
""" if force == True the window must be in the forground, or execution will be blocked"""
while True:
try:
# Get the currently active window
active_window = pyautogui.getActiveWindow()
# Check if the active window's title matches the desired window title
if force:
if active_window.title == window_title:
return True
else:
# if force is set True and the window title does not match the desired one
# display warning and than try again.
pyautogui.alert('File choosing dialog not in Focus! \n\n'
'click ok and than click somewere in the file chooser dialog. \n\n'
'(script will continue 5s after the dialog is confirmed)')
time.sleep(5)
else:
return active_window.title == window_title
except Exception as e:
print(f"An error occurred: {e}")
return False
def batch_populate(platform='perplexity', project='prj_lp_fug_01', prompt_name='chatGPT_02',nr_of_tabs=1, start_block=0,
block_range=[], nr_of_groups=1, max_tokens=4000, process_only_untranslated_paragraphs=False):
global paragraphs, prompts, conf
try:
# if a range is given, open as many tabs as there are elements
if len(block_range) > 0:
nr_of_tabs = len(block_range)
except Exception as e:
block_range = []
window_tab_titles = {}
groups = my_text.group_paragraphs_by_tokens(paragraphs, max_tokens=max_tokens, prompt_name=prompt_name,
process_only_unfinished=process_only_untranslated_paragraphs)
group_id_start = start_block
groups_to_send_per_tab = nr_of_groups # each with 3200 tokens (if thai, english about 900)
block_range_done = []
for tab_id in range(nr_of_tabs):
# new_tab('https://twitter.com/')
if platform == 'chatGPT':
new_tab('https://chat.openai.com/')
if platform == 'perplexity':
new_tab('https://www.perplexity.ai/')
if platform == 'aiStudio':
# only 50 querys per account / day -- needs to change chrome account in chrome too
if conf['google_account'] == 'rrrr':
new_tab('https://aistudio.google.com/app/prompts/1dGv6MBszg5FOzqORhBNcvFew-4KH6HR4') # rrrrr account
elif conf['google_account'] == 'kusala':
new_tab('https://aistudio.google.com/app/prompts/1NPusGemK_weAi0OcJTywnY-fH8nzyKP3') # b.kusala account
else:
new_tab('https://aistudio.google.com/app/prompts/1aIq5b6sauz4Zr1wn8Qai4esCB7XBX7kn') # wat doi account already saved prompt, with safety blocker disabled
wait_for_element_class(el['aiStudio']['prompt_textarea'], max_wait=20)
# Switch to the new window, which brings it into focus
window_handle = driver.current_window_handle
driver.switch_to.window(window_handle)
if platform == 'perplexity':
# check if pro version enabled (otherwise the ai's are only very weak)
# is_perplexity_pro_enabled(alert=True)
is_server_error(retries=4, pause_between_retries=5*60)
pa = ''
pa_ids = []
tc = 0
group_counter = 0
tab_id = get_current_tab_id()
t = {}
t['group_start'] = ''
t['group_end'] = ''
# case: block range give
if len(block_range) > 0:
for group_id, paragraph_ids in enumerate(groups):
# if max groups to send to one tab is reached -> dont add any more paragraphs
if group_id not in block_range:
continue
# check if the block was already processed
if group_id in block_range_done:
continue
# if max groups to send to one tab is reached -> dont add any more paragraphs
if group_counter >= groups_to_send_per_tab:
continue
if group_id in block_range:
pa_ids += paragraph_ids
group_counter += 1
if t['group_start'] == '':
t['group_start'] = group_id
t['group_end'] = group_id
block_range_done.append(group_id)
# if there are no more paragraphs to process
if len(pa_ids) == 0:
return 'no more paragraphs'
title = f"p{pa_ids[0] + 2:0>4}-{pa_ids[-1] + 2:0>4}__g{t['group_start']:0>3}" # -{t['group_end']:0>3}
else:
# case: no block range is given, but start paragraph
for group_id, paragraph_ids in enumerate(groups):
# start to add paragraphs when not yet pasted
if group_id_start > group_id:
continue
# if max groups to send to one tab is reached -> dont add any more paragraphs
if group_counter >= groups_to_send_per_tab:
continue
group_counter += 1
pa_ids += paragraph_ids
# if there are no more paragraphs to process
if len(pa_ids) == 0:
return 'no more paragraphs'
title = f'p{groups[group_id_start][0] + 2:0>4}-{groups[group_id_start - 1 + groups_to_send_per_tab][-1] + 2:0>4}__g{group_id_start:0>3}' # -{group_id_start - 1 + groups_to_send_per_tab:0>3}
# set identifier, to keep track of which tab is for what
set_identifier(title)
json_data = {}
for paragraph_id in pa_ids:
item = paragraphs[paragraph_id]['original']['text']
item = re.sub(r'\n', ' ', item)
tc += my_text.token_count(item)
# pa += f' <item id="{paragraph_id + 2}" gr="{group_id}" tk="{tc}">{item}</item>\n'
if conf['encode_as'] == 'xml':
pa += f' <item id="{paragraph_id + 2}">{item}</item>\n'
if conf['encode_as'] == 'json':
json_data[paragraph_id + 2] = item
if conf['encode_as'] == 'json':
pa = json.dumps(json_data, sort_keys=False, indent=4, ensure_ascii=False)
group_id_start = group_id_start + groups_to_send_per_tab
if platform == 'perplexity':
# check if pro version enabled (otherwise the ai's are only very weak)
is_perplexity_pro_enabled(alert=True)
# is_server_error(retries=4, pause_between_retries=5*60)
# change from internet search to normal query
perplexity_set_focus('Writing')
pr = prompts[prompt_name]['prompt']
past_prompt([pr, pa], platform=platform, click_send=True, speed=0.0001, use_paste=True,
project=project) # speed 0.001 is pretty tame..
return True
# to keep track of the tabs through various cases: reload (hash), changes through the pages itself (div)
# and easily find the corresponding tab (title)
def set_identifier(hash):
set_identifier_hash(hash)
set_identifier_div(hash)
set_title(hash)
# retrieve identifier, whichever is still available
def get_identifier():
try:
div = get_identifier_div()
if div != '':
set_identifier_hash(div)
set_title(div)
return div
hash = get_identifier_hash()
hash = hash[1:] # is returned with '#' as first char
if hash != '':
set_identifier_div(hash)
set_title(hash)
return hash
except Exception as e:
ta = get_current_tab_id()
print(' problem retrieving or setting identifier in tab ' + str(ta))
return ''
def set_identifier_hash(hash):
try:
# JavaScript code to append a hash to the current URL without reloading the page
script = f"window.location.hash = '{hash}';"
# Execute the script using Selenium's execute_script method
driver.execute_script(script)
except Exception as e:
print('hash not set')
return False