-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvhil_OO.py
More file actions
2361 lines (2048 loc) · 101 KB
/
vhil_OO.py
File metadata and controls
2361 lines (2048 loc) · 101 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
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 pyautogui
import pygetwindow
import time
import pywinctl as pwc
from PIL import ImageGrab
import re
import os
from together import Together
from meta_ai_api import MetaAI
import sys
import sounddevice as sd
# from TTS.api import TTS
import time
import whisper
import subprocess
import threading
import sounddevice as sd
import wave
import numpy as np
from pynput.keyboard import Key, Controller
import concurrent.futures
import requests
import abc
import logging
import functools
import csv
import sqlite3
from datetime import date
def assert_type(obj, expected_type):
assert isinstance(obj, expected_type), f"Expected {expected_type}, but got {type(obj)}"
# ---------- KEYBOARD UTILS ---------
def input_keys(keys,duration=0.000001, delay=0.1):
print("** Exec Input keys: " + keys.lower())
pynput_keyboard = Controller()
numb_inputs = 0
for letter in keys.lower():
# pyautogui.press(letter.lower())
# time.sleep(1)
pynput_keyboard.type(letter,duration=0,delay=delay)
numb_inputs = numb_inputs + 1
# time.sleep(1.5)
time.sleep(0.4)
if numb_inputs == 2:
break
def refresh_page():
# pyautogui.hotkey('command', 'r')
print("\n**REFRESHING PAGE")
pyautogui.press('esc')
pynput_keyboard = Controller()
with pynput_keyboard.pressed(Key.cmd):
pynput_keyboard.press('r')
pynput_keyboard.release('r')
time.sleep(4.4)
pyautogui.press('esc')
def scroll_full_page_down():
VoiceAssistant.voice("I'm scrolling")
input_keys("dd")
def scroll_half_page_down():
VoiceAssistant.voice("I'm scrolling")
input_keys("d")
def scroll_to_top_of_page():
time.sleep(0.5)
VoiceAssistant.voice("I'm scrolling")
input_keys("gg")
def clear_prefilled_txt_box():
pyautogui.press('esc') # use input keys instead when refactoring
input_keys("gi")
time.sleep(0.3)
pyautogui.hotkey('command', 'a')
# Delete selected text
time.sleep(0.3)
pyautogui.press('delete')
# exit out of the input txtbox
pyautogui.press('esc') # use input keys instead when refactoring
def fill_in_txtbox(input_text,duration=0.02,delay=0.02, clear_txtbox_first=True):
# focus on txtbox
pyautogui.press('esc') # use input keys instead when refactoring
time.sleep(0.2)
input_keys("gi")
time.sleep(0.3)
pynput_keyboard = Controller()
# type actual text, need to do in this way cuz pyautogui is dumb sometimes and pynput cannot type "." for some reason
for char in input_text:
# if char == ".":
# All non-letter characters (including punctuation, digits and whitespace) will be typed using pyautogui.
if not char.isalpha():
pyautogui.typewrite(char)
else:
pynput_keyboard.type(char,duration,delay)
# exit out of the input txtbox
pyautogui.press('esc') # use input keys instead when refactoring
# sentences = new_msg.split(".")
# for i, sentence in enumerate(sentences):
# # for char in sentence:
# # pynput_keyboard.press(char).release()
# pynput_keyboard.type(sentence,0.03,0.03)
# if i < len(sentences) - 1: # Don't press '.' after last sentence
# pyautogui.typewrite(".")
# pynput_keyboard.type(input,0.03,0.03)
# ---------- WINDOW UTILS ---------
def get_matching_windows(window_name,only_one_matching_window=False):
while True:#attempts < max_attempts:
windows = pwc.getWindowsWithTitle(
title=window_name,
condition=pwc.Re.CONTAINS,
flags=pwc.Re.IGNORECASE
)
print(windows)
if windows is not None:
break
if(only_one_matching_window and len(windows) > 1):
raise Exception("FOUND MORE THAN ONE MATCHING WINDOW, please be more specific")
return windows
# PURE FUNC
def activate_window(window_name):
print(f"** Activating {window_name} Window")
# pyautogui.sleep(1) # Wait 1000ms
# max_attempts = 30000
# attempts = 0
# windows=None
# # while True:#attempts < max_attempts:
# windows = pwc.getWindowsWithTitle(
# title=window_name,
# condition=pwc.Re.CONTAINS,
# flags=pwc.Re.IGNORECASE
# )
# print(windows)
# if windows is not None:
# break
# if(len(windows) > 1):
# raise Exception("FOUND MORE THAN ONE MATCHING WINDOW, please be more specific")
windows = get_matching_windows(window_name, only_one_matching_window=True)
if windows:
windows[0].activate()
print(f"{window_name} window activated")
pyautogui.sleep(0.1) # Wait 100ms
pyautogui.click(
windows[0].left + 80,
windows[0].top + 40
)
print("Clicked on " + window_name + " window")
return windows # ret matching windows
else:
print(f"Failed to activate. Can't find {window_name} window.")
#print(f"No {window_name} window found")
class ScreenshotManager:
def __init__(self, entire_window=False, custom_use_defaults=False, screenshot_filename="screenshot.png", window_name="LinkedIn"):
self.entire_window = entire_window
self.custom_use_defaults = custom_use_defaults
self.x1, self.y1 = 1527,200 #231 #457, 237
self.x2, self.y2 = 2508,1100 # 1421, 827
self.width, self.height = self.x2 - self.x1, self.y2 - self.y1
self.screenshot_filename = screenshot_filename
self.window_name = window_name
self._windows = activate_window(self.window_name)
self.running = True
self.coords_lock = threading.Lock()
# self.root= tk.Tk()
@property
def windows(self):
return self._windows
def config_ss_params(self):
# if self.entire_window:
# # windows = activate_window(self.window_name)
# # self.windows = windows
# # self.x1, self.y1 = self.windows[0].left, self.windows[0].top
# # self.x2, self.y2 = self.windows[0].right, self.windows[0].bottom
# # self.width, self.height = self.windows[0].width, self.windows[0].height
# self.update_window_coords()
# self.start_coord_updates()
# elif not self.custom_use_defaults:
# manually obtain coords
if not self.custom_use_defaults and not self.entire_window:
print("** Configuring Screenshot params...")
for i in range(5, 0, -1):
print(i)
time.sleep(1)
self.x1, self.y1 = pyautogui.position()
print(f"1st Mouse position: ({self.x1}, {self.y1})")
for i in range(5, 0, -1):
print(i)
time.sleep(1)
self.x2, self.y2 = pyautogui.position()
print(f"2nd Mouse position: ({self.x2}, {self.y2})")
self.width, self.height = self.x2 - self.x1, self.y2 - self.y1
image = pyautogui.screenshot(region=(self.x1, self.y1, self.width, self.height))
image.save(self.screenshot_filename)
print("Took test screenshot with new params @ screenshot.png")
elif self.entire_window:
print("Using entire window for screenshots")
else:
print("Using custom default coordinates for screenshots")
return
def update_window_coords(self):
try:
with self.coords_lock:
if self.windows is not None:
new_x1, new_y1 = self.windows[0].left, self.windows[0].top
new_x2, new_y2 = self.windows[0].right, self.windows[0].bottom
# new_width, new_height = self.windows[0].width, self.windows[0].height
new_width = self.windows[0].right - self.windows[0].left
new_height = self.windows[0].bottom - self.windows[0].top
print("SELF.WINDOWS:",self.windows)
print("new_x1:", new_x1)
print("new_y1:", new_y1)
print("new_x2:", new_x2)
print("new_y2:", new_y2)
print("new_width:", new_width)
print("new_height:", new_height)
if(new_x1 == new_y1 == new_x2 == new_y2 == 0):
print("\nUH-OH...0 Coords found \n")
return
return
if (new_x1, new_y1, new_x2, new_y2, new_width, new_height) != (self.x1, self.y1, self.x2, self.y2, self.width, self.height):
self.x1, self.y1 = new_x1, new_y1
self.x2, self.y2 = new_x2, new_y2
self.width, self.height = new_width, new_height
print("Updated window coordinates")
except Exception as e:
print(f"An error occurred in updating window coords: {str(e)}")
# self.root.after(500, self.update_window_coords)
def start_coord_updates(self):
threading.Thread(target=self.run_updates).start()
def run_updates(self):
while self.running:
self.update_window_coords()
time.sleep(1) # 200ms
def stop_updates(self):
self.running = False
def take_ss(self):
with self.coords_lock:
# print("in TAKE SS func")
# image = pyautogui.screenshot(region=(self.x1, self.y1, self.width, self.height))
if self.entire_window:
while True:
self.x1, self.y1 = self.windows[0].left, self.windows[0].top
self.width, self.height = self.windows[0].width, self.windows[0].height
if self.width > 0 and self.height > 0:
break
print(f"Current Screenshot Coordinates (will retry): {self.x1, self.y1, self.width, self.height}")
time.sleep(2)
self._windows = get_matching_windows(self.window_name, only_one_matching_window=True)
print(f"Screenshot Coordinates: {self.x1, self.y1, self.width, self.height}")
image = ImageGrab.grab(bbox=(self.x1, self.y1, self.x1 + self.width, self.y1 + self.height))
image.save(self.screenshot_filename)
# print("hit keys & took ss")
return self.upload_ss()
def upload_ss(self):
with open(self.screenshot_filename, 'rb') as f:
data = f.read()
response = requests.put('http://bashupload.com/screenshot.png', data=data, timeout=4)
# print("printing response")
# print(response.content)
# time.sleep(0.5)
return self.extract_link(response)
def extract_link(self, response):
match = re.search(r'wget\s+(http[s]?://\S+)', response.text)
if match:
matched_link = match.group(1)
# print(matched_link)
return matched_link
else:
print("No link found")
return None
class MicInputRecorder:
def __init__(self, whisper_model_name='tiny',duration=3, sample_rate=44100, channels=1, input_audio_file_name="responding_to_vision.wav"):
"""
Initialize MicInputRecorder.
Args:
whisper_model_name (str): Whisper model name. Defaults to 'tiny'.
duration (int): Recording duration in seconds. Defaults to 3.
"""
self.whisper_model_name = whisper_model_name
self.model = whisper.load_model(whisper_model_name)
self.duration = duration
self.sample_rate = sample_rate # Hz
self.channels = channels # channel=1 is Mono
self.input_audio_file_name = input_audio_file_name
def record_audio(self):
"""
Record audio from microphone.
Returns:
np.ndarray: Recorded audio.
"""
with VoiceAssistant.voice_lock:
print("Recording...")
audio = sd.rec(int(self.duration * self.sample_rate),
samplerate=self.sample_rate,
channels=self.channels)
sd.wait() # Wait for recording to finish
print("Recording finished.")
return audio
def save_audio_to_wav(self, audio):
"""
Save recorded audio to WAV file.
Args:
audio (np.ndarray): Recorded audio.
"""
# Ensure highest value is in 16-bit range
audio *= 32767 / np.max(np.abs(audio))
audio = audio.astype(np.int16)
wave_file = wave.open(self.input_audio_file_name, "wb")
wave_file.setnchannels(self.channels)
wave_file.setsampwidth(2) # 16-bit audio
wave_file.setframerate(self.sample_rate)
wave_file.writeframes(audio.tobytes())
wave_file.close()
def transcribe_audio(self):
"""
Transcribe recorded audio using Whisper.
Returns:
str: Transcribed text.
"""
result = self.model.transcribe(self.input_audio_file_name)
print("Transcription from mic: ")
print(result["text"])
print("Transcription done.")
return result["text"]
def get_mic_input(self):
"""
Record and transcribe microphone input.
Returns:
str: Transcribed text.
"""
audio = self.record_audio()
self.save_audio_to_wav(audio)
return self.transcribe_audio()
class VoiceAssistant:
voice_lock = threading.Lock()
enabled = True
@classmethod
def enable_voice(cls):
cls.enabled = True
@classmethod
def disable_voice(cls):
cls.enabled = False
@staticmethod
# block is useless cuz we now have locks
def voice(input, block=False):
"""
Play a VoiceAssistant.voice message.
Args:
input (str): The text to be spoken.
block (bool, optional): Whether to block until the VoiceAssistant.voice message is finished. Defaults to False.
"""
if VoiceAssistant.enabled:
thread = threading.Thread(target=VoiceAssistant._voice_thread, args=(input, block))
thread.start()
# if block:
# thread.join() # Wait for the thread to finish
@staticmethod
def _voice_thread(input, block=False):
VoiceAssistant.voice_lock.acquire()
try:
subprocess.call(["say", input])
finally:
VoiceAssistant.voice_lock.release()
# ---------- LLM UTILS ---------
class LLMManager(abc.ABC):
def __init__(self, new_llm_every_req=True):
self._total_numb_requests_served = 0
self._lock = threading.Lock()
# self.MAX_REQS_B4_TIMEOUT = 50
self.new_llm_every_req = new_llm_every_req
self._internalLLM = None if new_llm_every_req else self._init_internal_llm()
@property
def internalLLM(self):
"""
Gets the internal LLM instance.
"""
return self._internalLLM
@internalLLM.setter
def internalLLM(self, value):
"""
Sets the internal LLM instance.
"""
self._internalLLM = value
@abc.abstractmethod
def _init_internal_llm(self):
pass
@abc.abstractmethod
def prompt_llm(self,prompt_str):
pass
def _increment_total_numb_requests_served(self):
with self._lock:
self._total_numb_requests_served += 1
@property
def total_numb_requests_served(self):
with self._lock:
return self._total_numb_requests_served
@total_numb_requests_served.setter
def total_numb_requests_served(self, value):
"""
Sets the internal LLM instance.
"""
self._total_numb_requests_served = value
class MetaManager(LLMManager):
"""
A manager class for handling MetaAI() requests.
"""
MAX_REQS_B4_TIMEOUT = 40 #acc is 50
def __init__(self, new_llm_every_req=True):
"""
Initializes the MetaManager instance.
Args:
new_llm_every_req (bool): Whether to create a new LLM for every request. Defaults to True.
"""
super().__init__(new_llm_every_req)
#prime the metaAI
thread = threading.Thread(target=self.prime_MetaAI)
thread.start()
# self.internal_meta = MetaAI()
# self._internalLLM = None if new_llm_every_req else MetaAI()
def _init_internal_llm(self):
m = MetaAI()
return m
def prime_MetaAI(self):
if self.internalLLM is not None:
res = self.internalLLM.prompt("Hi")
def prompt_llm(self, prompt_str):
"""
Prompts the LLM with the given prompt string.
Args:
prompt_str (str): The prompt string to use.
Returns:
dict: The response from the LLM.
"""
res = None
self._increment_total_numb_requests_served()
if(self.internalLLM is None):
# create new meta object for every req
main_meta = MetaAI()
res = main_meta.prompt(prompt_str)
#return main_meta.prompt(prompt_str)
else:
# use same meta object as long as possible
mai = self.internalLLM
# assert_type(mai, MetaAI)
res = mai.prompt(prompt_str)
self._update_internalLLM() # update internal metaAI if necessary
return res
def _update_internalLLM(self):
if(self.total_numb_requests_served % MetaManager.MAX_REQS_B4_TIMEOUT == 0):
# Get new MetaAI() for internal meta to avoid time out
self.internalLLM = MetaAI()
# prime it so its now slow on the first req
thread = threading.Thread(target=self.prime_MetaAI)
thread.start()
class TogetherManager(LLMManager):
MAX_RETRIES = 3
"""
A manager class for handling Together API requests.
"""
def __init__(self, ssManager, new_llm_every_req=True,
TOGETHER_model_str="meta-llama/Llama-Vision-Free",
max_tokens= 512,
temperature=0.5,#0.1, #0.7,
top_p=0.4, #0.8, #0.7,
top_k=50): #30#50):
"""
Initializes the TogetherManager instance.
Args:
new_llm_every_req (bool): Whether to create a new LLM for every request. Defaults to True.
"""
super().__init__(new_llm_every_req)
# self.TOGETHER_model_str and self.internalLLM maybe the EXACT SAME FOR THIS CLASS
self._TOGETHER_model_str = TOGETHER_model_str
self._ss = ssManager
self.max_tokens=max_tokens
self.temperature=temperature
self.top_p=top_p
self.top_k=top_k
# self.internal_meta = MetaAI()
# self._internalLLM = None if new_llm_every_req else MetaAI()
def enable_90B(self):
self.TOGETHER_model_str = "meta-llama/Llama-3.2-90B-Vision-Instruct-Turbo"
def disable_90B(self):
self.TOGETHER_model_str = "meta-llama/Llama-Vision-Free"
def _init_internal_llm(self):
t = Together()
return t
@property
def TOGETHER_model_str(self):
"""
Gets the internal LLM instance.
"""
return self._TOGETHER_model_str
@TOGETHER_model_str.setter
def TOGETHER_model_str(self, value):
"""
Gets the internal LLM instance.
"""
self._TOGETHER_model_str = value
@property
def ss(self):
"""
Gets the internal LLM instance.
"""
return self._ss
# return response of LLAMA vision
def meta_vision_wrapper(self, query, ss_link):
client = self.internalLLM if self.internalLLM else Together() # use same LLM, else use new LLM each requests
response = client.chat.completions.create(
model=self.TOGETHER_model_str,
messages=[
# {
# "role": "user",
# "content": [
# {
# "type": "text",
# "text": "what is this "
# },
# {
# "type": "image_url",
# "image_url": {
# "url": "https://www.islandeguide.com/custom/domain_1/image_files/2_photo_11878.jpg" #s3://together-ai-uploaded-user-images-prod/c8606f29-76d7-4b52-a736-5e000b38b8ef.jpg"
# }
# }
# ]
# },
# {
# "role": "assistant",
# "content": "This is a QR code for WiFi."
# }
# ],
# {
# "role": "user",
# "content": [
# {"type": "text",
# "text": "take ur time and solve this math problem correctly. Dont get distracted and only output the final correct answer." }, #"What sort of animal is in this picture? What is its usual diet? What area is the animal native to? And isn’t there some AI model that’s related to the image?"},
# {
# "type": "image_url",
# "image_url": {
# "url": "https://drive.usercontent.google.com/u/0/uc?id=1nscxcJhIeyPfTds7uNNF4dSvhZLZwu6W&export=download"#"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/LLama.jpg/444px-LLama.jpg?20050123205659",
# },
# },
# ],
# }
{
"role": "user",
"content": [
{"type": "text",
"text": query }, #"What sort of animal is in this picture? What is its usual diet? What area is the animal native to? And isn’t there some AI model that’s related to the image?"},
{
"type": "image_url",
"image_url": {
"url": ss_link #"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/LLama.jpg/444px-LLama.jpg?20050123205659",
},
},
],
}
# ,{
# "role": "user",
# "content": [
# {"type": "text",
# "text": "Nice. now only tell me the final answer value (only the number)." }
# ]
# }
],
max_tokens = self.max_tokens,
temperature = self.temperature,
top_p = self.top_p,
top_k = self.top_k,
# max_tokens= 512,#50,#512,#50,#512,
# temperature=0.1,#0.3,#0.7,
# top_p= 0.8,#0.5,#0.90,#0.7,
# top_k=30,#10,#50,
repetition_penalty=1,
stop=["<|eot_id|>","<|eom_id|>"],
# truncate=130560,
stream=False
)
# print(response.choices[0].message.content)
return response.choices[0].message.content
def ask_vision_meta(self,q):
VoiceAssistant.voice("I'm reading")
retries = 0
vision_res = None
while retries < TogetherManager.MAX_RETRIES:
try:
link_to_ss = self.ss.take_ss()
time.sleep(0.5)
vision_res = self.meta_vision_wrapper(q, link_to_ss)
break # Exit the loop if successful
except Exception as e:
retries += 1
print(f"Attempt {retries} failed: {e}")
if retries == TogetherManager.MAX_RETRIES:
print("Max retries exceeded. Giving up.")
return None
return vision_res
def prompt_llm(self, prompt_str):
"""
Prompts the LLM with the given prompt string.
Args:
prompt_str (str): The prompt string to use.
Returns:
dict: The response from the LLM.
"""
res = self.ask_vision_meta(prompt_str)
self._increment_total_numb_requests_served()
print("total reqs served: " + str(self.total_numb_requests_served))
return res
# if(self.internalLLM is None):
# # create new meta object for every req
# main_meta = MetaAI()
# return main_meta.prompt(prompt_str)
# else:
# # use same meta object as long as possible
# res = self.internalLLM.prompt(prompt_str)
# self._update_internalLLM() # update internal metaAI if necessary
# return re
# ---------- Logging & State Tracker ---------
class StateMeta(type):
current_file_name = os.path.basename(__file__) # name of the Python file that is currently being executed.
logging_filename = current_file_name.split('.')[0] + ".log"#"vision_hil_log_file.log"
state_filename = current_file_name.split('.')[0] + "_state.txt"
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
console_handler.setFormatter(formatter)
file_handler = logging.FileHandler(logging_filename, mode='w')
file_handler.setLevel(logging.INFO)
logger.addHandler(console_handler)
logger.addHandler(file_handler)
enabled = True # New toggle variable
def state_decorator(func):
@functools.wraps(func)
# IMPORTANT: "self" refers to the caller function!!!!
def wrapper(self, *args, **kwargs):
if StateMeta.enabled: # Check the toggle
# Log the function name and arguments
args_repr = [repr(a) for a in args]
kwargs_repr = [f"{k}={v!r}" for k, v in kwargs.items()]
signature = ", ".join(args_repr + kwargs_repr)
StateMeta.logger.info(f"Calling {func.__name__}({signature})")
# Write the current state to the state file
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Calling {func.__name__}", file=file)
# Write the current state to the state file
# llm = getattr(self, 'llm', None)
# if llm:
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Calling {func.__name__}, {llm.total_numb_requests_served}, 0", file=file)
# else:
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Calling {func.__name__}", file=file)
# vm = getattr(self, 'vm', None)
# # vm = getattr(self, 'vm', None)
# # if hasattr(self, 'vm') and self.vm is not None:
# # print(f"DEBUGGGGG: {self.vm.total_numb_requests_served}")
# # else:
# # print("DEBUGGGGG: self.vm is None or does not exist")
# if vm:
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Calling {func.__name__}, {self.llm.total_numb_requests_served}, {self.vm.total_numb_requests_served}", file=file)
# else:
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Calling {func.__name__}", file=file)
# if not any(value is None for value in self.__dict__.values()):
# if hasattr(self, 'vm') and hasattr(self, 'llm') and hasattr(self, 'total_connections_made'):
# remember "self" is the caller func
# only have to check if this attribute is set because llm and vm are in the parent class
# print(self)
# inits dont hve any attributes yet
with open(StateMeta.state_filename, 'w') as file:
if func.__name__ == "__init__" or not hasattr(self, 'vm'):
print(f"Calling {func.__name__}", file=file)
elif hasattr(self, 'total_connections_made'):
print(f"Calling {func.__name__}, {self.llm.total_numb_requests_served},{self.vm.total_numb_requests_served},{self.total_connections_made}", file=file)
else:
print(f"Calling {func.__name__}, {self.llm.total_numb_requests_served},{self.vm.total_numb_requests_served}", file=file)
# print(f"Calling {func.__name__}", file=file)
# Call the function
result = func(self, *args, **kwargs)
if StateMeta.enabled: # Check the toggle
# Log the function completion
StateMeta.logger.info(f"Completed {func.__name__}({signature})")
# # Write the completed state to the state file
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Completed {func.__name__}", file=file)
# if hasattr(self, 'vm') and self.vm is not None:
# print(f"DEBUGGGGG: {self.vm.total_numb_requests_served}")
# else:
# print("DEBUGGGGG: self.vm is None or does not exist")
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Completed {func.__name__}, {self.llm.total_numb_requests_served}, {self.vm.total_numb_requests_served}", file=file)
# if hasattr(self, 'vm') and hasattr(self, 'llm') and hasattr(self, 'total_connections_made'):
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Completed {func.__name__}, {self.llm.total_numb_requests_served},{self.vm.total_numb_requests_served},{self.total_connections_made}", file=file)
# else:
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Completed {func.__name__}", file=file)
# if hasattr(self, 'total_connections_made'):
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Completed {func.__name__}, {self.llm.total_numb_requests_served},{self.vm.total_numb_requests_served},{self.total_connections_made}", file=file)
# else:
# with open(StateMeta.state_filename, 'w') as file:
# print(f"Completed {func.__name__}, {self.llm.total_numb_requests_served},{self.vm.total_numb_requests_served}", file=file)
return result
return wrapper
def __new__(cls, name, bases, dct):
for key, value in dct.items():
if callable(value):
dct[key] = cls.state_decorator(value)
return super().__new__(cls, name, bases, dct)
@classmethod
def enable_logging(cls):
cls.enabled = True
@classmethod
def disable_logging(cls):
cls.enabled = False
# ---------- Automator Objects ---------
# NVM... they are now instance variables
# purposely just class variables for now so that I don't have code duplication for now
# but changing these class variables affects ALL instances of the class -> not good for if different subclassses want diff configs of this parent class (in which case I have to change these to instance variables)
class Automator_LLMs(metaclass=StateMeta):
# llm = None
# vm = None
def __init__(self, llm, vm, enable_voice=True):
self.llm = llm
self.vm = vm
self.enable_voice = enable_voice
def voice(self, input):
if self.enable_voice and sys.platform == 'darwin':
VoiceAssistant.voice(input)
else:
print(f" ** voice not available yet for this system: {sys.platform}")
def ask_vision_meta(self, input):
answer = self.vm.prompt_llm(input)
return answer
class ButtonClicker(Automator_LLMs):
def __init__(self, llm, vm, descp, max_retries=2, pre_click_action=None, alt_click_action=None,safety_check=False, redun=2):
self.descp = descp
super().__init__(llm,vm)
self.max_retries = max_retries
self.pre_click_action = pre_click_action if pre_click_action else None
self.alt_click_action = alt_click_action if alt_click_action else None
self.safety_check = safety_check
self.redundancy = redun
self.boost_90B = False
if self.boost_90B:
self.vm.enable_90B()
# Deleting (Calling destructor)
def __del__(self):
if self.boost_90B:
self.vm.disable_90B()
def find_and_click(self):
"""
Finds and clicks the button described by self.descp.
"""
print(f"** INSIDE find_and_click_general func for {self.descp}")
# if self.pre_click_action:
# self.pre_click_action()
time.sleep(0.5)
# retry = 0
# while retry < self.max_retries:
# self._attempt_click(retry)
# retry += 1
# if self.post_click_action:
# return self.post_click_action(res)
try:
self._attempt_click()
except Exception as e:
print(f"Raised Exception: {e}")
raise Exception(f"Failed to click on {self.descp}")
return 1 # bad
def _attempt_click(self):
"""
Attempts to click the button.
"""
status = f"Let's click on {self.descp}"
print(status)
self.voice(status)
retry = 0
while retry < self.max_retries:
if self.pre_click_action:
self.pre_click_action()
if self.safety_check:
check_for_button = f'''Given the image, can you identify {self.descp}? Only output YES or NO'''
vision_res = None
vision_res2 = None
with concurrent.futures.ThreadPoolExecutor() as executor:
future1 = executor.submit(self.ask_vision_meta, check_for_button)
if self.redundancy is not None:
future2 = executor.submit(self.ask_vision_meta, check_for_button)
vision_res = future1.result()
vision_res2 = future2.result()
print(vision_res)
print(vision_res2)
# vision_res = self.ask_vision_meta(check_for_button)
# print(vision_res)
if self.redundancy is not None:
if "yes" not in vision_res.lower() or "yes" not in vision_res2.lower():
status = f"CAN'T FIND {self.descp}! Retrying..."
print(status)
self.voice(status)
retry += 1
continue
else:
if "yes" not in vision_res.lower():
status = f"CAN'T FIND {self.descp}! Retrying..."
print(status)
self.voice(status)
retry += 1
continue
self._click_button()
return 0 # good
# double check
if self.redundancy:
vision_res2 = self.ask_vision_meta(check_for_button)
print(vision_res2)
if "yes" not in vision_res.lower() and "yes" not in vision_res2.lower():
status = f"CAN'T FIND {self.descp}! Retrying..."
print(status)
self.voice(status)
retry += 1
continue
else:
self._click_button()
return 0 # good
else:
if "yes" not in vision_res.lower():
status = f"CAN'T FIND {self.descp}! Retrying..."
print(status)
self.voice(status)
retry += 1
continue
else:
self._click_button()
return 0 # good
# OLD CODE
# check_for_button = f'''Given the image, can you identify {self.descp}? Only output YES or NO'''
# vision_res = self.ask_vision_meta(check_for_button)
# print(vision_res)
# if "yes" not in vision_res.lower():
# status = f"CAN'T FIND {self.descp}! Retrying..."
# print(status)
# self.voice(status)
# retry += 1
# continue
# else:
# self._click_button()
# return 0 # good
# # if self.alt_click_action():
# # self.alt_click_action()
# else:
raise Exception(f"Attempt click for {self.descp} failed")
def _click_button(self):
"""
Clicks the button.
"""
input_keys("f")
followup = f'''Next to each selectable feature in this image of webpage, there is a 1 or 2 lettered encoding in a yellow box next to the LEFT or slightly UPPER LEFT side of the feature.
Which lettered encoding is associated with {self.descp}? Start your answer with "The letter encoding is"'''
#followup = f'''Next to each selectable feature in this image of webpage, there is a 1 or 2 lettered encoding in a yellow box directly adjacent to the left of the feature. Which lettered encoding is associated with {self.descp}? Be brief and start your answer with "The letter encoding is "'''
# followup= f'''Analyze the provided webpage image and identify the 1 or 2-letter encoding in the yellow box adjacent to {self.descp}. Respond with: "The letter encoding is [insert encoding]"'''
followup= f'''Analyze the provided webpage image and identify the best 1-letter or 2-letter encoding in the yellow box adjacent left of the feature. Which lettered encoding is associated with {self.descp}? Respond with: "The letter encoding is "'''
# followup= f'''Analyze the webpage image and identify the single best 1-2 letter encoding in the yellow box adjacent to {self.descp}. Respond with: "The best letter encoding is [insert encoding]"'''
vision_res = self.ask_vision_meta(followup)
print(vision_res)
# res = meta.prompt(f"Given this input, only just output the one or two letter encoding: {vision_res}")
res = self.llm.prompt_llm(f"Given this input, only just output the 1 or 2-letter encoding: {vision_res}")
print(res["message"])
input_keys(res["message"])
status = f"Clicked on {self.descp}"
print(status)
self.voice(status)
class ConnectionExecutor(Automator_LLMs):
def __init__(self, llm, vm, big_blob_info,max_retries=3,autosend=False,autoskip_connection=False):
self.big_blob_info = big_blob_info
super().__init__(llm,vm)
self.local_meta = MetaAI()
self.max_retries = max_retries
self.autoskip_connection = autoskip_connection
self.autosend=autosend
self.hyperpersonalized_message = None
def execute_connection(self):
"""
Executes the connection process.
"""