def Increase_brightness(): try: currrent_brightness = sbc.get_brightness() increased_brightness = currrent_brightness + 10 sbc.set_brightness(increased_brightness) except Exception as e: speak("sir brightness is full")
def brightness(query): res = [int(i) for i in query.split() if i.isdigit()] if len(res) == 0: speak("No digit specified") else: lev = res[0] current_brightness = sbc.get_brightness() new_lev = lev if ( "increment" in query or "add" in query or "increase" in query or "up" in query or "high" in query ): new_lev = min(current_brightness + lev, 100) sbc.set_brightness(new_lev) elif ( "decrement" in query or "subtract" in query or "decrease" in query or "low" in query or "down" in query ): print(lev) new_lev = max(current_brightness - lev, 0) sbc.set_brightness(new_lev) else: if new_lev > 100: new_lev = 100 elif new_lev < 0: new_lev = 0 sbc.set_brightness(new_lev) speak("Brightness is changed to" + str(new_lev))
def Decrease_brightness(): try: currrent_brightness = sbc.get_brightness() decreased_brightness = currrent_brightness - 10 sbc.set_brightness(decreased_brightness) except Exception as e: speak("sir brightness is low")
def slider(): master = Tk() master.title('Screen_Brightness_Control') w = Scale(master, from_=0, to=100, tickinterval=5, length=600, orient=HORIZONTAL, command=set_brightness) w.set(sbc.get_brightness()) w.pack() mainloop()
# importing the module import screen_brightness_control as sbc # get current brightness value current_brightness = sbc.get_brightness() print(current_brightness) # get the brightness of the primary display primary_brightness = sbc.get_brightness(display=0) print(primary_brightness)
##################################### wCam, hCam = 640, 480 ##################################### cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) cap.set(3, wCam) cap.set(4, hCam) pTime = 0 cTime = 0 detector = htm.handDetector(detectionConfidence = 0.7) briBar = 400 #briPer = 0 brightness = sbc.get_brightness() Area = 0 while(True): #Capture frame by frame success, img = cap.read() img = detector.findHands(img, draw = False) lmList, bbox = detector.findPosition(img, draw = True) if len(lmList) != 0: #Filter Based on size Area = (bbox[2] - bbox[0])*(bbox[3] - bbox[1])//100 #print(Area) if 250 < Area < 950:
def __init__(self, videoSource): self.backSub = cv2.createBackgroundSubtractorMOG2() self.initialBrightness = sbc.get_brightness() self.isDetecting = False self.status = 0 if videoSource == "debug": self.videoSource = -1 else: self.videoSource = int(videoSource[-1]) self.cap = cv2.VideoCapture(self.videoSource, cv2.CAP_DSHOW) if self.cap.isOpened() == False: print('Error while trying to open camera.') self.ret, self.frame1 = self.cap.read() self.ret, self.frame2 = self.cap.read() self.width = self.cap.get(cv2.CAP_PROP_FRAME_WIDTH) self.height = self.cap.get(cv2.CAP_PROP_FRAME_HEIGHT) self.motionDetected = [] self.isMoving = False self.config = ConfigParser() self.config.read('config.ini') self.inputs = ConfigParser() self.inputs.read('current_inputs.ini') self.defaultExercisesDict = dict(self.config.items('default')) self.customizedExerciseDict = dict(self.config.items('customized')) self.extremityTriggersDict = dict(self.config.items('extremity')) # self.timerFlag=0 # self.t0=0 # self.t1=1 currentDefaultInputsDict = dict(self.inputs.items('default')) currentCustomizedInputsDict = dict(self.inputs.items('customized')) extremityTriggerInputsDict = dict(self.inputs.items('extremity')) for key in currentDefaultInputsDict: if (int(currentDefaultInputsDict.get(key))) == 0: self.defaultExercisesDict.pop(key, None) for key in currentCustomizedInputsDict: if (int(currentCustomizedInputsDict.get(key))) == 0: self.customizedExerciseDict.pop(key, None) for key in extremityTriggerInputsDict: if (int(extremityTriggerInputsDict.get(key))) == 0: self.extremityTriggersDict.pop(key, None) self.currentDetectors = {} for key in self.defaultExercisesDict: eventType = self.defaultExercisesDict.get(key).split('+')[0] if len(self.defaultExercisesDict.get(key).split('+')) == 2: eventContent = self.defaultExercisesDict.get(key).split('+')[1] else: eventContent = None detector = default_exercise_detection.DefaultExerciseDetection(key) self.currentDetectors[detector] = (eventType, eventContent) for key in self.customizedExerciseDict: eventType = self.customizedExerciseDict.get(key).split('+')[0] if len(self.customizedExerciseDict.get(key).split('+')) == 2: eventContent = self.customizedExerciseDict.get(key).split( '+')[1] else: eventContent = None detector = customized_exercise_detection.CustomizedExerciseDetection( key) self.currentDetectors[detector] = (eventType, eventContent) for key in self.extremityTriggersDict: pos = self.extremityTriggersDict.get(key).split('+')[0] eventType = self.extremityTriggersDict.get(key).split('+')[1] if len(self.extremityTriggersDict.get(key).split('+')) == 3: eventContent = self.extremityTriggersDict.get(key).split( '+')[2] else: eventContent = None detector = extremity_trigger.ExtremityTrigger(key, pos) self.currentDetectors[detector] = (pos, eventType, eventContent) self.exercisesRecords = dict(self.defaultExercisesDict, **self.customizedExerciseDict) for key in self.exercisesRecords: self.exercisesRecords[key] = 0 self.extremityRecords = self.extremityTriggersDict for key in self.extremityTriggersDict: self.extremityRecords[key] = ( self.extremityTriggersDict.get(key).split('+')[0], 0) self.records = (self.exercisesRecords, self.extremityRecords) self.check_status()
def main(): global username global city global voice music = None music_list = [] if username == "": Speak("Hello. I'm your virtual assistant. What's your name?") username = input( "Hello I'm your virtual assistant What's your name?\n") data = json.load(open('Data\\user.json', )) data["username"] = username with open("Data\\user.json", "w") as f: f.write(json.dumps(data)) if city == "": while True: Speak("Please enter your city") city = input("Please Enter Your City :\n") geolocator = Nominatim(user_agent='myapplication') location = geolocator.geocode(city) if location != None: break data = json.load(open('Data\\user.json', )) data["city"] = city with open("Data\\user.json", "w") as f: f.write(json.dumps(data)) if not path.exists('Utils\\ffmpeg.exe'): print( "Please Make Sure To Download The Utils (FFMPEG.exe was not found)" ) Speak( "Please Make Sure To Download The Utils (F F M P E G dot exe was not found)" ) sleep(10) return False Speak(f"Good {welcome_mesage()} {username}") Speak( f"it is {int(strftime('%I'))} {int(strftime('%M'))} {strftime('%p')}") while True: try: calc = False with sr.Microphone() as source2: print("Adjusting Audio") r.adjust_for_ambient_noise(source2, duration=0.2) print("Listening") audio2 = r.listen(source2) print("Processing The Data ") MyText = r.recognize_google(audio2) MyText = MyText.lower() print("You said :" + MyText) # Replace numbers for Calculator MyText = replace_theTexting_by_num(MyText) for i in MyText: if i in numbers: calc = True if calc == True: MyText = replace_expresions(MyText) # Say Hello if "hello" in MyText: Speak("Hello to you too!") if "+" in MyText or "-" in MyText or "*" in MyText or "/" in MyText or "sqrt" in MyText: try: result = eval(MyText) Speak(f"The answer is {result}") print(f"The answer is {result}") except: Speak("What was That ?") elif "weather" in MyText: Speak("Checking Weather") Speak( f"The weather in {city} is {weather_message()[0]} degrees , and {weather_message()[1]}" ) elif "date" in MyText and not "update" in MyText: Speak("Today is " + str(strftime('%A')) + str(int(strftime('%d'))) + str(strftime('%B')) + str(strftime('%Y'))) elif "azan" in MyText or "pray" in MyText: Speak(get_prayer(city)) elif "time" in MyText: Speak( f"it is {int(strftime('%I'))} {int(strftime('%M'))} {strftime('%p')}" ) elif "change" in MyText and "name" in MyText: Speak("What's your name?") username = input("What's your name?\n") data = json.load(open('Data\\user.json', )) data["username"] = username with open("Data\\user.json", "w") as f: f.write(json.dumps(data)) elif "change" in MyText and "city" in MyText: while True: Speak("Please enter your new city") city = input("Please Enter Your New City :\n") geolocator = Nominatim(user_agent='myapplication') location = geolocator.geocode(city) if location != None: break data = json.load(open('Data\\user.json', )) data["city"] = city with open("Data\\user.json", "w") as f: f.write(json.dumps(data)) # Voice Changing elif "change" in MyText and "voice" in MyText: for a in range(len(v)): engine.setProperty('voice', (v[a])) Speak(f"For this voice press {a}") while True: c = input("Please Choose (0, 1) :") if c in ("0", "1"): c = int(c) break data = json.load(open('Data\\user.json', )) data["voice"] = c with open("Data\\user.json", "w") as f: f.write(json.dumps(data)) voices = engine.getProperty('voices') engine.setProperty('voice', v[int(c)]) # Notes elif "note" in MyText: if "take" in MyText: with open("Data\\notes.txt", "a") as f: Speak("Please Type Your Notes") notes = input("Please Type Your Notes :\n") f.write(notes + "\n") elif "delete" in MyText or "remove" in MyText: Speak("Your Notes Will Be Deleted. Are You Sure") notes = input("Are you sure (Y/N):\n") if notes.lower() == "y": with open("Data\\notes.txt", "w") as f: f.write("") else: with open("Data\\notes.txt", "r") as f: Speak(f.read()) # Open Programmes elif "open" in MyText: MyText = MyText.replace("open ", "") x = openApp(MyText) if not x: Speak("Here's some results from the internet") else: Speak(f"opening {str(MyText)}") # Google Search elif "google" in MyText: search = MyText.replace("google ", "") wb.open_new_tab( f'https://www.google.com/search?q={search}') elif "what is" in MyText or "what's" in MyText: search = MyText.replace("what is ", "") try: print(wikipedia.summary(search)) Speak("According to wikipedia " + str(wikipedia.summary(search, sentences=4))) except: search = MyText.replace("what is ", "") wb.open_new_tab( f'https://www.google.com/search?q={search}') elif "who is" in MyText: search = MyText.replace("who is ", "") try: print(wikipedia.summary(search)) Speak("According to wikipedia " + str(wikipedia.summary(search, sentences=4))) except: search = MyText.replace("who is ", "") wb.open_new_tab( f'https://www.google.com/search?q={search}') # Download From Youtube elif "download" in MyText: if 'music' in MyText: url = speakInput( "Please write down the name of the song you want to download :" ) youtube_downloader.youtube_download(url, "music") elif "youtube" in MyText: url = speakInput( "Please type the name of the video you want to download :" ) youtube_downloader.youtube_download(url, "youtube") elif "convert" in MyText: fileConverter.convertFile() # Music Player elif "music" in MyText: if "play" in MyText: artist = MyText.replace("play music ", "") if artist == "play music": artist = get_word("artist") Speak(f"Playing {artist} Music") music, music_list = music_player(artist, music) elif "pause" in MyText or "stop" in MyText or "continue" in MyText: pause_music(music) elif "next" in MyText: if music == None: artist = get_word("artist") + " music" music, music_list = music_player(artist, music) else: Speak("Playing next music") music = next_music(music, music_list) # Brightness Control elif "brightness" in MyText: old = sbc.get_brightness() if "increase" in MyText or "raise" in MyText: sbc.set_brightness(old + 25) speakPrint(f"increasing brightness") elif "max" in MyText: sbc.set_brightness(100) speakPrint(f"maximum brightness") elif "decrease" in MyText or "lower" in MyText: speakPrint(f"decreasing brightness") sbc.set_brightness(old - 25) elif "min" in MyText: speakPrint(f"Mnimun brightness") sbc.set_brightness(0) else: speakPrint(f"Current brightness is {old}") elif "close" in MyText: MyText = MyText.replace("close ", "") Speak(f"Closing {MyText}") x = closeApp(MyText) if not x: speakPrint( f"Nothing found, Please Make Sure That the name is the same in The Task Manager" ) else: speakPrint(f"{x} Closed") elif "check" in MyText and "update" in MyText: if CheckUpdate(version): speakPrint("Update Available") wb.open_new_tab( 'https://thevirtualassistant.netlify.app/') else: speakPrint("You Are Running The Latest Version") elif "help" in MyText: Speak("Check out our website") wb.open_new_tab('https://thevirtualassistant.netlify.app/') # Shutdown elif "shutdown" in MyText or "shut down" in MyText: if "after" in MyText: time = ((get_hours(MyText) * 3600 + get_minutes(MyText) * 60)) os.system(f"Shutdown -s -t {time}") else: for i in range(11, 0, -1): print(f"Shutting down in {i}") sleep(1) os.system("shutdown -s") # restart elif "restart" in MyText: if "after" in MyText: time = ((get_hours(MyText) * 3600 + get_minutes(MyText) * 60)) os.system(f"Shutdown -r -t {time}") else: for i in range(11, 0, -1): print(f"Restarting in {i}") sleep(1) os.system("shutdown -r") elif "bye" in MyText or "quit" in MyText or "leave" in MyText or "stop" in MyText or "adios" in MyText: Speak("it was an honor serving here ") quit() except sr.RequestError as e: speakPrint("Could not request results; {0}".format(e)) except sr.UnknownValueError: speakPrint("unknown error occured") word = get_word("stand_by") sleep(1) Speak(word) stand_by() Speak(get_word("after_stand_by"))
def set_brightness(case, value): try: value = int(value) except TypeError or ValueError: pass case = 3 if case == 0: # Set absolute brightness sbc.set_brightness(value) elif case == 1: # Set relative brightness (1&2) sbc.set_brightness(f'+{str(value)}') elif case == 2: sbc.set_brightness(f'-{str(value)}') elif case == 3: engine.say("Sorry, I had trouble setting your brightness. Try again.") if case != 3: brightness = sbc.get_brightness(display=1) engine.say(f"Your new brightness level is {brightness}") # get_brightness() # set_brightness(0, 20) # Multiple screens # def get_allbrightness(): # all_screens_brightness = sbc.get_brightness() # print(all_screens_brightness) # get_brightness() # def set_all(level): # screen_count = len(sbc.get_brightness())
def get_brightness(): primary_display_brightness = sbc.get_brightness(display=1) engine.say(f"Your brightness level is {primary_display_brightness}")
def runCasey(self): wishMe() while True: self.query = self.takeCommand() if 'wikipedia' in self.query: speak('Searching in Wikipedia...') print('Searching in Wikipedia...') self.query = self.query.replace("wikipedia", "") results = wikipedia.summary(self.query, sentences=2) speak("According to Wikipedia") print("According to Wikipedia") speak(results) print(results) elif 'play song' in self.query or 'song' in self.query: speak("Which song I should play") song = self.takeCommand() song_result = "playing ", song speak(song_result) print(song_result) pywhatkit.playonyt(song) elif 'screenshot' in self.query: image = pyautogui.screenshot() digits = [i for i in range(0, 10)] imageName = "" for i in range(6): index = math.floor(random.random() * 10) imageName += str(digits[index]) image.save("C:\\Users\\vijin\\Pictures\\Screenshots\\" + imageName + ".png") os.startfile("C:\\Users\\vijin\\Pictures\\Screenshots\\" + imageName + ".png") elif 'open youtube' in self.query: webbrowser.open("youtube.com") elif 'open google' in self.query: webbrowser.open("google.com") elif 'open stackoverflow' in self.query: webbrowser.open("stackoverflow.com") elif 'open facebook' in self.query: webbrowser.open("facebook.com") elif 'open instagram' in self.query: webbrowser.open("instagram.com") elif 'open wikipedia' in self.query: webbrowser.open("wikipedia.com") elif 'increase volume' in self.query: pyautogui.press("volumeup") speak("Volume increased") print("Volume increased") elif 'decrease volume' in self.query: pyautogui.press("volumedown") speak("Volume decreased") print("Volume decreased") elif 'close chrome' in self.query: os.system("taskkill /f /im " + "chrome.exe") speak("Closed Chrome Browser") print("Closed Chrome") elif 'take photo' in self.query or 'photo' in self.query: cam = cv2.VideoCapture(0) cv2.namedWindow("test") speak( "Press Space Bar to click photo and Escape button for closing the window" ) img_counter = 0 while True: ret, frame = cam.read() if not ret: print("failed to grab frame") break cv2.imshow("test", frame) k = cv2.waitKey(1) if k % 256 == 27: speak("Closing Camera") print("Escape hit, closing...") break elif k % 256 == 32: img_name = "opencv_frame_{}.png".format(img_counter) cv2.imwrite(img_name, frame) speak("Taking Photo") print("Taking photo") print("{} written!".format(img_name)) speak("Took Photo") print("Took Photo") img_counter += 1 cam.release() cv2.destroyAllWindows() elif 'record video' in self.query or 'video' in self.query: speak( "The video will be recorded automatically, press the q button in keyboard to stop recording" ) cap = cv2.VideoCapture(0) out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*"MJPG"), 30, (640, 480)) while (cap.isOpened()): ret, frame = cap.read() if ret: out.write(frame) cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break else: break cap.release() out.release() cv2.destroyAllWindows() elif 'mute' in self.query: pyautogui.press("volumemute") elif 'time' in self.query: strTime = datetime.datetime.now().strftime("%H:%M:%S") speak(f"Sir, the time is {strTime}") print(strTime) elif 'date' in self.query: strDate = str(datetime.date.today()) todayDate = "Today's date is ", strDate speak(todayDate) print(todayDate) elif 'open visual studio' in self.query: speak("Opening VS Code") print("Opening VS code") codePath = "C:\\Users\\vijin\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe" os.startfile(codePath) elif 'open word' in self.query: speak("Opening Microsoft Word") print("Opening Microsoft Word") wordPath = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Office\\Microsoft Office Word 2007" os.startfile(wordPath) elif 'open excel' in self.query: speak("Opening Microsoft Excel") print("Opening Microsoft Excel") excelPath = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\Microsoft Office\\Microsoft Office Excel 2007" os.startfile(excelPath) elif 'open media player' in self.query: speak("Opening VLC Media Player") print("Opening VLC Media Player") vlcPath = "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\VideoLAN\\VLC media player" os.startfile(vlcPath) elif 'email' in self.query: contacts = { "vijin": "*****@*****.**", "joker": "*****@*****.**" } print("To whom should I send the email") speak("To whom should I send the email") to = self.takeCommand() to = to.replace(" ", "") print(to) x = 0 for key, value in contacts.items(): if key == to: to = value print("What Message should I send") speak("What message should I send") message = self.takeCommand() sendEmail(to, message) x = x + 1 if x > 0: print("Email send successfully") else: print("Couldn't find the contact") elif 'increase brightness' in self.query: current_brightness = sbc.get_brightness() if current_brightness > 90: speak( "Brightness is at it's highest level. Can't increase brightness" ) print( "Brightness is at it's highest level. Can't increase brightness" ) else: new_brightness = current_brightness + 10 print(new_brightness) sbc.set_brightness(new_brightness) updated_brightness = "Brightness increased to ", new_brightness print(updated_brightness) speak(updated_brightness) elif 'decrease brightness' in self.query: current_brightness = sbc.get_brightness() if current_brightness < 10: speak( "Brightness is at its lowest level. Can't decrease brightness" ) print( "Brightness is at its lowest level. Can't decrease brightness" ) else: new_brightness = current_brightness - 10 print(new_brightness) sbc.set_brightness(new_brightness) updated_brightness = "Brightness decreased to ", new_brightness print(updated_brightness) speak(updated_brightness) elif 'shut down' in self.query: speak("shutting down") print("Shutting down") os.system('shutdown -s -t 0') elif 'sleep' in self.query: speak("Hibernating system") print("Hibernating system") os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0") elif 'weather' in self.query or 'temperature' in self.query: speak("which city's temperature do you want to look") city = self.takeCommand() q = "Temperature of ", city res = wfapp.query(q) print(next(res.results).text) speak(next(res.results).text) elif 'mathematics' in self.query or 'calculation' in self.query: speak("Tell me the problem") question = self.takeCommand() res = wfapp.query(question) print(next(res.results).text) speak(next(res.results).text) elif 'translate' in self.query: languages = { "hindi": "hi", "english": "en", "malayalam": "ml", "tamil": "ta" } dest_lang = "" x = 0 try: speak("In which language do you want me to translate") lang = self.takeCommand() for key, value in languages.items(): if key == lang: x = x + 1 dest_lang = value break if x > 0: speak("What do you want me to translate") text = self.takeCommand() translator = googletrans.Translator() result = translator.translate(text, dest_lang) print(result.text) translated_audio = gtts.gTTS(result.text, lang=dest_lang) translated_audio.save('audio.mp3') playsound.playsound('audio.mp3') else: speak("Couldn't find language") except Exception: speak("Couldn't translate") elif 'internet speed' in self.query: import speedtest st = speedtest.Speedtest() dl = st.download() up = st.upload() dl_speed = "download speed=", dl, " bits per second" up_speed = "upload speed=", up, " bits per second" print(dl_speed) print(up_speed) speak(dl_speed) speak(up_speed) elif 'joke' in self.query: import pyjokes jokes = pyjokes.get_jokes(language="en", category="all") r1 = random.randint(0, 100) joke = jokes[r1] speak(joke) print(joke, sep="\n") elif 'send message' in self.query: account_sid = 'your sid' auth_token = 'your auth_token' client = Client(account_sid, auth_token) speak("What do you want me to send?") print("What do you want me to send?") body = self.takeCommand() message = client.messages \ .create( body = body, from_='from number', to ='to number' ) print(message.sid) speak("Message sent") print("Message sent") elif 'news' in self.query or 'headlines' in self.query: news_url = "https://news.google.com/news/rss" Client = urlopen(news_url) xml_page = Client.read() Client.close() soup_page = soup(xml_page, "xml") news_list = soup_page.findAll("item") for i in range(1, 10): print(news_list[i].title.text) speak(news_list[i].title.text) print(news_list[i].pubDate.text)
import serial from serial.tools import list_ports slider_trinkey_port = None ports = list_ports.comports(include_links=False) for p in ports: if p.pid is not None: print("Port:", p.device, "-", hex(p.pid), end="\t") if p.pid == 0x8102: slider_trinkey_port = p print("Found Slider Trinkey!") trinkey = serial.Serial(p.device) break else: print("Did not find Slider Trinkey port :(") sys.exit() curr_brightness = sbc.get_brightness() while True: x = trinkey.readline().decode('utf-8') if not x.startswith("Slider: "): continue val = int(float(x.split(": ")[1])) if val != curr_brightness: print("Setting brightness to:", val) sbc.set_brightness(val) curr_brightness = sbc.get_brightness()
def Status(self): current_brightness_level = sbc.get_brightness() return current_brightness_level
args = parser.parse_args() kw = {} if args.display != None: if type(args.display) not in (str, int): raise TypeError('display arg must be str or int') if type(args.display) is str and args.display.isdigit(): args.display = int(args.display) kw['display'] = args.display if args.verbose: kw['verbose_error'] = True if args.method != None: kw['method'] = args.method if args.get: values = SBC.get_brightness(**kw) try: monitors = SBC.list_monitors(**kw) except: monitors = None if monitors == None: print(values) else: values = [values] if type(values) is int else values if args.display == None or type(values) == list: for i in range(len(monitors)): try: print( f'{monitors[i]}: {values[i]}{"%" if values[i]!=None else ""}' ) except IndexError:
continue # ignore empty lines if (line.find("command: landscape") != -1): if not landscape: try: monitor.set_landscape() landscape = True except Exception: pass if (line.find("command: portrait") != -1): if landscape: try: monitor.set_portrait_flipped() landscape = False except Exception: pass if (line.find("brightness: ") != -1): cbr = -1 try: cbr = sbc.get_brightness(display=0) except Exception: pass nbr = int(line.replace("brightness: ", "")) if (nbr != cbr): try: sbc.set_brightness(nbr, display=0) except Exception: pass
def Mouse_Key_down(KeyID): KeyAction = [0, 0, 0, 0] if KeyID == knob1: # 旋钮1旋转 KeyAction = copy.copy(Kb1) elif KeyID == knob1rp: KeyAction = copy.copy(Kb1rp) elif KeyID == knob2: KeyAction = copy.copy(Kb2) elif KeyID == knob2rp: KeyAction = copy.copy(Kb2rp) keyboard.press(KeyAction[0]) pyautogui.scroll(-100) keyboard.release(KeyAction[0]) Light_set = screen_brightness_control.get_brightness() # 获取全局亮度 # 调整屏幕亮度 def ScreenChange(percent): print(percent) screen_brightness_control.fade_brightness(percent, interval=0.01) # 设置亮度 # 亮度调整函数 def LightConfig(light_num): # 限幅函数 if light_num < 0: light_num = 0 elif light_num > 100: light_num = 100 # 亮度调整函数
import argparse import screen_brightness_control as SBC if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-s', '--set', type=int, help='set the brightness to this value') parser.add_argument('-g', '--get', action='store_true', help='get the current screen brightness') parser.add_argument('-f', '--fade', type=int, help='fade the brightness to this value') args = parser.parse_args() if args.get: print(SBC.get_brightness()) elif args.set != None: SBC.set_brightness(args.set) elif args.fade != None: SBC.fade_brightness(args.fade) else: print("No valid arguments")
# importing the module import screen_brightness_control as sbc # get current brightnessvalue print(sbc.get_brightness()) #set brightness to 50% sbc.set_brightness(90) print(sbc.get_brightness())
# Ctypes elif 'change my background' in query or 'change background' in query: ctypes.windll.user32.SystemParametersInfoW(20, 0, "E:\\munal\\munal.JPG", 0) speak("Background changed succesfully") elif 'lock window' in query or 'lock my window' in query or 'lock my laptop' in query or 'lock my computer' in query: speak("locking the device") ctypes.windll.user32.LockWorkStation() # END Ctypes # Brightness Control elif "brightness" in query: old = sbc.get_brightness() if "increase" in query or "raise" in query: sbc.set_brightness(old + 25) speak(f"increasing brightness") elif "max" in query: sbc.set_brightness(100) speak(f"maximum brightness") elif "decrease" in query or "lower" in query: speak(f"decreasing brightness") sbc.set_brightness(old - 25) elif "min" in query: speak(f"Mnimun brightness") sbc.set_brightness(0) else: speak(f"Current brightness is {old}")
if ret_val is None: raise Exception print(f'{name}{arrow} {ret_val}%') except Exception as e: if args.verbose: print(f'{name}{arrow} Failed: {e}') else: print(f'{name}{arrow} Failed') except Exception: kw = { 'display': args.display, 'method': args.method, 'verbose_error': args.verbose } if args.get: print(SBC.get_brightness(**kw)) else: print(SBC.set_brightness(args.set, **kw)) elif args.fade is not None: try: monitors = list(get_monitors(args)) for monitor in monitors: monitor.initial_brightness = monitor.get_brightness() monitor.fade_thread = monitor.fade_brightness( args.fade, blocking=False, start=monitor.initial_brightness) while True: done = [] for monitor in monitors:
def _widgets(self): self.brightness = IntVar() self.slider = Scale(self.app, length=300,from_=0, to=100,orient=HORIZONTAL, takefocus=1, highlightthickness=1) self.slider.set(sbc.get_brightness()) self.button = Button(self.app, text='Set', command=self._set_value) pass
speak("Opening the battery report file") run("start battery-report.html") else: speak("Generating Battery report") run("powercfg /batteryreport") run("start battery-report.html") elif output == 'helping': print( "Do read the readme file from the repository to get the help" ) speak( "I am dev console , Which has the functionality to execute system commands in kind of human language. Currently I can execute only few tasks ,but with the help of contributors ,I will be able to execute more soon! Execute any system command or type hello here to get DEV in action!" ) elif output == 'bright': current_brightness = sbc.get_brightness() if 40 < current_brightness[0] <= 60: speak("Curent brightness is okay! Want to alter it?") elif current_brightness[0] >= 80: speak("Brightness is too much! Want to alter it?") elif current_brightness[0] <= 30: speak("Brightness is too low! Want to alter it?") decision = input("Alter Brightness[y/n]:") if (decision == 'y'): battery_percentage = input( "Enter the brightness percentage. It will increased or decreased according to percenatge:" ) if battery_percentage.endswith("%"): battery_percentage = battery_percentage.replace( "%", " ") sbc.set_brightness(int(battery_percentage))
def changeBrightness(value): try: bc.fade_brightness(value, bc.get_brightness()) except bc.ScreenBrightnessError as error: print(error)