From 86c10d4ff79a05fc2533123b10e1319baeb173a1 Mon Sep 17 00:00:00 2001 From: Fenris Lycaon Date: Sat, 8 Jul 2023 16:53:56 +0530 Subject: [PATCH] Fix Linting --- BSE_data/bombay.py | 17 +- .../detect_translate.py | 15 +- aes_py/aes_tool.py | 5 +- aes_py/main.py | 8 +- alarm_clock/AlarmClock.py | 9 +- algebra_solver_gui/algebra.py | 7 +- aqi_tracker/aqi-tracker.py | 79 +-- articles_to_pdf/articles_to_pdf.py | 82 ++- ascii_image/ascii_image.py | 21 +- attachment-downloader/app.py | 2 +- attendance_automator/main.py | 32 +- audio_book/PDF_TO_AUDIO.py | 18 +- audio_recoder/audio_recorder.py | 39 +- audio_remover/audio-remover.py | 33 +- audio_sticky_notes/main.py | 6 +- audio_sticky_notes/note.py | 17 +- auto_backup/main.py | 29 +- auto_calender/calendarauto.py | 101 +-- auto_calender/task.py | 2 +- auto_clicker/autoclicker.py | 2 +- auto_completer/auto-complete.py | 24 +- .../api_crypto_mail_alert.py | 23 +- auto_cursor_mover/auto_cursor_mover.py | 3 +- auto_news_reader/mySpeaker.py | 12 +- auto_news_reader/read_npr_news.py | 20 +- auto_pixelsort/autosort.py | 107 +-- auto_searcher/autosearcher.py | 32 +- auto_shutdown/auto_shutdown.py | 6 +- auto_typer/autotyper.py | 43 +- automated_calling/autocall.py | 34 +- barcode_scanner/barcode_scanner.py | 27 +- battery_notification/battery_notification.py | 13 +- birthday_wisher/birth_day_wish_telegram.py | 16 +- bmi_calculator/Calculator.py | 53 +- book_manager/Dialog.py | 52 +- book_manager/book.py | 18 +- book_manager/bookman.py | 105 +-- book_manager/data_model.py | 2 +- broken_linkfinder/broken_linkfinder.py | 23 +- browser_notification_sender/GUI_components.py | 19 +- bulk_renamer/bulk_renamer.py | 2 +- bulkemail_sender/main.py | 14 +- caeser_cipher/caeser_cipher.py | 15 +- calendar/AlCalendar.py | 73 +- captcha_solver/csolver.py | 5 +- .../cardekho_dynamic_data_scraping.py | 38 +- certificate_generator/app/__init__.py | 2 +- certificate_generator/app/routes.py | 25 +- certificate_generator/app/utils.py | 17 +- cfsol_submitter/headless.py | 37 +- cfsol_submitter/submit.py | 31 +- chat_bot/rule_based_chatbot.py | 76 +- codechef_scraper/codechef.py | 95 ++- codeforces_scraper/script.py | 5 +- .../AlColorImageGenerator.py | 134 ++-- colorimage_bw/colour_to_bw.py | 6 +- compare_img/compare_img.py | 1 + competitive_calendar/main.py | 11 +- competitive_calendar/utils.py | 25 +- .../connect_strongest_wifi.py | 16 +- copy_to_clipboard/copy_to_clipboard.py | 2 +- corona_tracker/global.py | 3 +- corona_tracker/italy.py | 5 +- corona_tracker_visualizer/corona_tracker.py | 306 ++++---- covid19_telegram_bot/covid19_telegram_bot.py | 7 +- cpu_tempreature/main.py | 82 ++- create_zip/zip.py | 24 +- credit_card_generator/cc_generate.py | 304 ++++---- credit_card_validator/cc_check.py | 207 +++--- crypto_converter/cryptoconvert.py | 88 ++- crypto_currency/main.py | 7 +- crypto_tracker/crypto.py | 12 +- csv_to_excel/main.py | 5 +- csv_to_json/main.py | 7 +- currency_converter/currency_converter.py | 6 +- datascience_books_scraper/scrape.py | 35 +- .../desktop_break_notifier.py | 29 +- dictionary_gui/dictionary.py | 33 +- digital_clock/clock.py | 17 +- directory_tree/tree.py | 35 +- discord_embedded_message/message.py | 1 + discord_github_bot/bot.py | 41 +- discount_alerter/amazon_price.py | 63 +- dns_verifier/dnslu.py | 26 +- doc_to_pdf/doc_to_pdf.py | 3 +- document_summarizer/AlDocSummarizer.py | 179 +++-- duplicate_files_remover/main.py | 46 +- duplicatefile_finder/file_dup.py | 25 +- email_feed/gmail_feed.py | 29 +- email_phone_extractor/extract-phone-email.py | 40 +- email_sender/__init__.py | 2 +- email_sender/email_sender.py | 95 +-- email_validator/config.py | 2 +- email_validator/main.py | 98 +-- emptyfolder_cleaner/EmptyFolderCleaner.py | 9 +- eterm/src/AutoCompleter.py | 4 +- eterm/src/credsChecker.py | 19 +- eterm/src/main.py | 229 +++--- excel_inspector/excel_inspector.py | 17 +- excel_to_csv/excel_to_csv.py | 7 +- excel_tools/excel-tools.py | 6 +- expense_manager/app.py | 176 +++-- expense_manager/db.py | 72 +- .../extract_text_from_pdf.py | 3 +- eye_blink_reminder/eye_blink_reminder.py | 12 +- eye_detection/eye_detector.py | 15 +- face_detection/main.py | 9 +- face_morpher/facemorphing.py | 33 +- face_recognition/face_recognition.py | 29 +- .../facebook_video_downloader.py | 12 +- facemask_detector/dataset.py | 6 +- facemask_detector/detect_face_mask.py | 7 +- facemask_detector/model.py | 13 +- facemask_detector/train.py | 24 +- fancy_text_generator/fancy_text_generate.py | 444 ++++++------ file_arranger/file_arranger.py | 81 ++- file_encrypter/file_decrypter.py | 4 +- file_encrypter/file_encrypter.py | 7 +- file_mover/filemover.py | 38 +- file_search/filesearch.py | 65 +- file_unlatcher/AlFileUnlatcher.py | 129 ++-- .../AlFileUnlatcher/AlFileSearcher.py | 8 +- flask_login_template/app.py | 20 +- flask_login_template/forms.py | 43 +- flask_login_template/setup/config.py | 11 +- flask_login_template/user.py | 65 +- flipkart_price_tracker/flipkart.py | 46 +- folders_arranger/folders_arranger.py | 30 +- fork_and_clone/Fnc.py | 35 +- gender_detector/detect_gender_webcam.py | 24 +- .../geocordinate-locator.py | 5 +- github_scraper/scrapper.py | 15 +- gmeet_zoom_joiner/gmeet_zoom_bot.py | 52 +- .../google_images_scraper.py | 8 +- google_meet_schedular/AutoMeet.py | 99 ++- hackernews_scrapper/hackernews_scrapper.py | 21 +- horoscope_destination/horoscope.py | 47 +- html_to_markdown/AlHtmlToMarkdown.py | 123 ++-- html_to_pdf/htmtopdf.py | 6 +- ig_dontfollowback/main.py | 23 +- image_annotater/imageannotater.py | 54 +- .../image_background_subtractor.py | 9 +- image_cartoonizer/imagecartoonizer.py | 6 +- image_collage/image_collage.py | 5 +- image_compressor/image_compressor.py | 5 +- image_cropper/image_cropper.py | 18 +- image_downloader/main.py | 5 +- image_encoder/decode_img.py | 6 +- image_encoder/encode_img.py | 14 +- image_resizer/image_resizer.py | 58 +- image_rounded_corner/rounded_corner.py | 8 +- image_separator/main.py | 39 +- .../Image_steganography_decode.py | 27 +- image_steganography/image_steganography.py | 23 +- image_to_pdf/main.py | 11 +- image_to_speech/image_to_speech.py | 9 +- images_to_video/img2vid.py | 12 +- imdb_episode_rename/rename.py | 110 +-- imdb_querier/imdb_movie_rating_querier.py | 8 +- .../insta_profile_pic_download.py | 4 +- instagram_follow_bot/instabot.py | 35 +- instagram_follow_bot/instabot2.py | 3 +- instagram_scraper/instagram_scraper.py | 38 +- interview_automater/app.py | 658 ++++++++++-------- ip_tracker/ipgeo.py | 19 +- iplscore_notifier/score.py | 46 +- jarvis_assistant/script.py | 43 +- jpg_to_png/jpg_to_png.py | 55 +- json_to_md/script.py | 86 ++- json_to_yaml/json2yaml.py | 1 + key_logger/keylogger.py | 9 +- language_translator/AlTranslator.py | 119 ++-- .../letter_image_generator.py | 36 +- markdown_editor/markdown_editor.py | 13 +- markdown_to_pdf/markdown_to_pdf.py | 10 +- markdown_viewer/markdown_viewer.py | 38 +- medium_to_pdf/main.py | 20 +- ml_solver/ML_solver_run.py | 52 +- ml_solver/__init__.py | 2 +- ml_solver/configs.py | 1 + ml_solver/data.py | 386 ++++------ ml_solver/hyperparams.py | 23 +- ml_solver/main.py | 6 +- ml_solver/preprocessing.py | 24 +- ml_solver/solver.py | 107 +-- ml_solver/utils.py | 4 +- .../morse-code-translator.py | 76 +- motivational_quoter/motivate.py | 23 +- movie_tv_ratings/movie_tv_ratings.py | 50 +- mp4_to_mp3_convertor/main.py | 103 +-- multimode-calculator/calculator.py | 393 ++++++++--- music_downloader/music-downloader.py | 10 +- music_player/player.py | 40 +- mysqldump_to_csv/mysql_dump_to_csv.py | 22 +- netflix_analyzer/netflix.py | 250 ++++--- news_scraper/news_scraper.py | 59 +- old_docker_images_auto_delete/main.py | 72 +- password_checker/password_strength_checker.py | 4 +- password_generator/password_generator.py | 30 +- password_manager/password_manager.py | 90 ++- pdf_editor/pdf_editor.py | 19 +- pdf_encryptor/pdf_encryptor.py | 39 +- pdf_merger/pdf_merger.py | 21 +- pdf_pages_remover/main.py | 8 +- pdf_to_audio/pdf_to_audio.py | 12 +- pdf_to_docx/pdf2docx.py | 43 +- pdf_to_image/main_code.py | 14 +- pdf_tools/pdf_tools.py | 26 +- pdf_watermarkadder/main.py | 12 +- png_to_jpg/main.py | 9 +- pnr_status_checker/pnr_status_checker.py | 44 +- polygon_detector/polygon_detect.py | 152 ++-- pomodoro_timer/pomodoro_timer.py | 93 +-- ppt2pdf/ppt2pdf_linux.py | 5 +- ppt2pdf/ppt2pdf_win.py | 12 +- ppt2video/convertor.py | 36 +- .../helper/pdf_operations.py | 32 +- prescription_generator/helper/speech.py | 30 +- prescription_generator/main.py | 9 +- price_tracker/priceTrackerScript.py | 40 +- price_tracker/send_email.py | 3 +- product_availability/product_availability.py | 20 +- product_availability/send_email.py | 2 +- profanity_filter/filter.py | 32 +- programming_quoter/programming_quoter.py | 67 +- pylinter/run-mccabe.py | 7 +- pylinter/run-pyflakes.py | 6 +- .../AlPythonPackageInstaller.py | 136 ++-- qrcode_generator/googleSourceCode_YT.py | 21 +- qrcode_generator/qr_generator.py | 112 +-- qrcode_scanner/scanner.py | 19 +- quick_painter/main.py | 15 +- random_email_generator/main.py | 26 +- random_wallpaper/random_wallpaper.py | 7 +- raspberry_pi_locator/main.py | 4 +- retweet_bot/keys.py | 8 +- retweet_bot/retweet_bot.py | 21 +- .../non_blocking_audio_recorder.py | 15 +- rpyaudio_recorder/recorder.py | 50 +- rubikscube_solver/colordetection.py | 34 +- rubikscube_solver/combiner.py | 6 +- rubikscube_solver/normalizer.py | 4 +- rubikscube_solver/solver.py | 66 +- rubikscube_solver/video.py | 349 ++++++---- scan_ports/scan_port.py | 5 +- screen_recorder/screen_recorder.py | 21 +- screen_shoter/screenshooter.py | 46 +- .../security_headers/security_headers.py | 24 +- security_headers/security_headers.py | 24 +- send_sms/sms.py | 32 +- .../simple-plagiarism-detector.py | 8 +- site_blocker/site_blocker.py | 4 +- .../slideshare_downloader.py | 7 +- sms_location/sms_loc.py | 28 +- song_scraper_GUI/findMyTune.py | 209 +++--- song_scraper_GUI/mp3Clan_top_web_scraper.py | 37 +- sort_vizualizer/main.py | 100 ++- speech_alarm/script.py | 21 +- speech_recognition_news/newsapi.py | 29 +- speedTest/SpeedTest.py | 12 +- speed_tester/speed_tester.py | 8 +- spell_corrector/spell_corrector.py | 18 +- sticky_notes/sticky_notes.py | 65 +- stocks_visualizer/visualise_prices.py | 10 +- stop_watch/Stopwatch.py | 34 +- straighten_image/straighten_image.py | 4 +- subtitle_creator/subtitle_creator.py | 21 +- subtitle_downloader/subtitle_downloader.py | 1 + sudoku_solver/solve_sudoku.py | 10 +- system_information/sys_info.py | 3 +- take_a_break/TakeABreak.py | 2 +- tar_py/tar_py.py | 18 +- telegram_backup/telebackup.py | 2 +- telegram_forward_bot/bot.py | 13 +- telegram_quotefancy/telegram_quotefancy.py | 3 +- temp_email/temp_email.py | 61 +- text_encryptor/aes_enc_dec.py | 33 +- text_from_image/main.py | 1 - text_summarize/text_summarize.py | 41 +- text_to_sound/text_to_sound.py | 5 +- time_zone_conversion/time_zone.py | 36 +- timezone_cli/tz_tool.py | 99 +-- tkinter_python_gui/USWeatherForecast.py | 82 ++- todo_list/app.py | 49 +- torrent_search/torrent_search.py | 295 ++++---- tweet_bot/config.py | 3 +- tweet_bot/favretweet.py | 4 +- tweet_bot/followfollowers.py | 9 +- tweet_bot/tweet-cli.py | 1 + tweet_scraper/tweet_scraper.py | 4 +- url_shortener/url.py | 5 +- video_cropper/video_cropper.py | 109 +-- video_desaturator/video_desaturator.py | 31 +- video_merger/video_merger.py | 8 +- video_player/videoplayer.py | 9 +- video_textadder/video-textadder.py | 56 +- video_to_audio/video-to-audio.py | 3 +- video_togif/video2gif.py | 3 +- video_watermark/main.py | 39 +- video_watermarker/water_marker.py | 14 +- virtual_keyboard/main.py | 351 ++++++---- voice_recorder/voice_recorder.py | 54 +- voice_shutdown/automate_shutdown.py | 11 +- voice_to_text/voice_to_text.py | 33 +- watermark_maker/main.py | 12 +- watermark_removal/watermark_removal.py | 5 +- weather_informer/weather.py | 48 +- webex_automation/Main.py | 56 +- website_blocker/website_blocker.py | 23 +- websiteurl_scraper/webUrlscraper.py | 25 +- whatsapp_automation/wa_scrapper.py | 5 +- whatsapp_bot/whatsapp.py | 11 +- wifi_passwords/wifi_passwords.py | 65 +- .../wikipedia_search_and_save.py | 20 +- word_cloud/word_cloud.py | 11 +- wordle_solver/wordle_solver.py | 66 +- xkcd_downloader/download_xkcd.py | 27 +- yaml_to_json/yaml_to_json.py | 11 +- youtube_args_search/youtube_search.py | 12 +- youtube_cli_search/script.py | 6 +- youtube_clipper/youtube_clip.py | 48 +- youtube_dl_gui/YoutubeDL.py | 18 +- youtube_downloader/ytdownloader.py | 27 +- youtube_to_mp3/youtube_to_mp3.py | 5 +- ytthumbnail_grabber/ytthumbnail_grabber.py | 10 +- zip_extractor/zip_extractor.py | 6 +- zip_password_cracker/zip_password_cracker.py | 14 +- .../zomato_scraper.py | 36 +- zoom_attendance_taker/attendanceTaker.py | 30 +- 329 files changed, 7809 insertions(+), 6028 deletions(-) diff --git a/BSE_data/bombay.py b/BSE_data/bombay.py index 675710953..1739c529a 100644 --- a/BSE_data/bombay.py +++ b/BSE_data/bombay.py @@ -7,7 +7,7 @@ for j in i: print(j, i[j]) -print('\n-------------------------\n') +print("\n-------------------------\n") tl = b.topLosers() print("\nTOP LOSERS - Now\n") @@ -16,9 +16,18 @@ print(f"{j}: {i[j]}") # indices catagory parameter -category = ["market_cap/broad", "sector_and_industry", "thematics", - "strategy", "sustainability", "volatility", "composite", - "government", "corporate", "money_market"] +category = [ + "market_cap/broad", + "sector_and_industry", + "thematics", + "strategy", + "sustainability", + "volatility", + "composite", + "government", + "corporate", + "money_market", +] for i in category: indices = b.getIndices(category=i) diff --git a/Detect_and_Translate_languages/detect_translate.py b/Detect_and_Translate_languages/detect_translate.py index 0d2aa9b96..713181de3 100644 --- a/Detect_and_Translate_languages/detect_translate.py +++ b/Detect_and_Translate_languages/detect_translate.py @@ -6,12 +6,12 @@ # Python program to detect and translate with the help of speech recognition +import pyttsx3 import speech_recognition as sr -from langdetect import detect from google_trans_new import google_translator -import pyttsx3 +from langdetect import detect -''' +""" Supported Languages: {'af': 'afrikaans', 'sq': 'albanian', 'am': 'amharic', 'ar': 'arabic', 'hy': 'armenian', 'az': 'azerbaijani', 'eu': 'basque', 'be': 'belarusian', @@ -41,7 +41,7 @@ 'cy': 'welsh', 'xh': 'xhosa', 'yi': 'yiddish', 'yo': 'yoruba', 'zu': 'zulu', 'fil': 'Filipino', 'he': 'Hebrew'} -''' +""" r = sr.Recognizer() translator = google_translator() @@ -61,18 +61,17 @@ def trans(x, d): print("Start speaking.....(To terminate the program say 'Stop!')") -while (1): +while 1: try: with sr.Microphone() as source2: r.adjust_for_ambient_noise(source2, duration=0.2) audio2 = r.listen(source2) MyText = r.recognize_google(audio2) MyText.lower() - if MyText == 'stop': + if MyText == "stop": break print("Did you say " + MyText) - d = input( - 'Enter the language you need the text to be translated into:') + d = input("Enter the language you need the text to be translated into:") translated = trans(MyText, d) print(translated) SpeakText(MyText) diff --git a/aes_py/aes_tool.py b/aes_py/aes_tool.py index 7be85b5f1..c6baf4f08 100644 --- a/aes_py/aes_tool.py +++ b/aes_py/aes_tool.py @@ -1,6 +1,7 @@ import base64 -from Crypto.Cipher import AES + from Crypto import Random +from Crypto.Cipher import AES from Crypto.Protocol.KDF import PBKDF2 BLOCK_SIZE = 16 @@ -13,7 +14,7 @@ def pad(s): def unpad(s): - return s[: -ord(s[len(s) - 1:])] + return s[: -ord(s[len(s) - 1 :])] def get_private_key(password): diff --git a/aes_py/main.py b/aes_py/main.py index fe70fe62c..e5882504f 100644 --- a/aes_py/main.py +++ b/aes_py/main.py @@ -1,10 +1,12 @@ import argparse from getpass import getpass -import aes_tool +import aes_tool -parser = argparse.ArgumentParser(description="Aes \ - encryption and decryption command") +parser = argparse.ArgumentParser( + description="Aes \ + encryption and decryption command" +) parser.add_argument("--text", help=argparse.SUPPRESS) parser.add_argument( diff --git a/alarm_clock/AlarmClock.py b/alarm_clock/AlarmClock.py index 8d06e03d2..b4bfd86b8 100644 --- a/alarm_clock/AlarmClock.py +++ b/alarm_clock/AlarmClock.py @@ -1,5 +1,6 @@ -import time import datetime +import time + import simpleaudio t = int() @@ -7,9 +8,9 @@ def snooze(t): global set_time - HH_MM = set_time.split(':') + HH_MM = set_time.split(":") HH_MM[1] = str(int(HH_MM[1]) + t) - set_time = ':'.join(HH_MM) + set_time = ":".join(HH_MM) set_time = input("please enter the time in HH:MM format to set an alarm : ") @@ -34,7 +35,7 @@ def alarm(set_time): while True: alarm(set_time) x = input("Press y if you want the alarm to snooze: ") - if x == 'y': + if x == "y": t = int(input("Snooze time: ")) snooze(t) print(f"The alarm will ring again in {t} min") diff --git a/algebra_solver_gui/algebra.py b/algebra_solver_gui/algebra.py index eb8e88772..d90e6b5cd 100644 --- a/algebra_solver_gui/algebra.py +++ b/algebra_solver_gui/algebra.py @@ -1,6 +1,6 @@ -from sympy.core.sympify import kernS import PySimpleGUIQt as sg import sympy as sy +from sympy.core.sympify import kernS class AlgebraSolver: @@ -27,8 +27,9 @@ def evaluate_linear(self, expression): return sy.solveset(sy.Eq(sy_exp, req)) def render(self): - window = sg.Window("Algebra Solver", resizable=True, - size=(800, 100)).Layout(self.layout) + window = sg.Window("Algebra Solver", resizable=True, size=(800, 100)).Layout( + self.layout + ) while True: event, values = window.Read() diff --git a/aqi_tracker/aqi-tracker.py b/aqi_tracker/aqi-tracker.py index cdb85a329..b6f12075d 100644 --- a/aqi_tracker/aqi-tracker.py +++ b/aqi_tracker/aqi-tracker.py @@ -1,76 +1,77 @@ -import requests -import sys import getopt +import sys +import requests -def main(argv): +def main(argv): def usage(): - print('usage: %s [-c city] [-a accesstoken] [-h help] ...') \ - % argv[0] + print("usage: %s [-c city] [-a accesstoken] [-h help] ...") % argv[0] return 100 try: - (opts, args) = getopt.getopt(argv[1:], 'c:a:h') + (opts, args) = getopt.getopt(argv[1:], "c:a:h") except getopt.GetoptError: return usage() def help(): - print("AQI Tracker -" - "\tLets the user know the real-time air quality values" - "\t\t(usage: %s [-c city] [-a accesstoken] [-h help])" - "\ncity:\t\tname of the cit" - "\naccesstoken:\tYou need to get access token by " - "registering on http://aqicn.org/data-platform/register/" - "\n\t\t*if no accesstoken provided then demo accesstoken will" - " be used \n\t\tand with demo access token only Shanghai's" - " air quality values can be retrieved.") - - city = 'shanghai' - accesstoken = 'demo' + print( + "AQI Tracker -" + "\tLets the user know the real-time air quality values" + "\t\t(usage: %s [-c city] [-a accesstoken] [-h help])" + "\ncity:\t\tname of the cit" + "\naccesstoken:\tYou need to get access token by " + "registering on http://aqicn.org/data-platform/register/" + "\n\t\t*if no accesstoken provided then demo accesstoken will" + " be used \n\t\tand with demo access token only Shanghai's" + " air quality values can be retrieved." + ) + + city = "shanghai" + accesstoken = "demo" for (k, v) in opts: - if k == '-c': + if k == "-c": city = v - elif k == '-a': + elif k == "-a": accesstoken = v - elif k == '-h': + elif k == "-h": return help() - url = 'http://api.waqi.info/feed/' + city + '/?token=' + accesstoken - print('URL: ', url) + url = "http://api.waqi.info/feed/" + city + "/?token=" + accesstoken + print("URL: ", url) - r = requests.get(url, auth=('user', 'pass')) + r = requests.get(url, auth=("user", "pass")) if r.status_code == 200: data = r.json() - value = data['data']['iaqi']['pm25']['v'] + value = data["data"]["iaqi"]["pm25"]["v"] toDisplay = str(value) if value > 0 and value < 50: - print('Air Quality Alert ->') - print('Current Value: Healthy - ' + toDisplay) + print("Air Quality Alert ->") + print("Current Value: Healthy - " + toDisplay) elif value > 50 and value < 100: - print('Air Quality Alert ->') - print('Current Value: Moderate - ' + toDisplay) + print("Air Quality Alert ->") + print("Current Value: Moderate - " + toDisplay) elif value > 100 and value < 150: - print('Air Quality Alert ->') - print('Current Value: Sensitive - ' + toDisplay) + print("Air Quality Alert ->") + print("Current Value: Sensitive - " + toDisplay) elif value > 150 and value < 200: - print('Air Quality Alert ->') - print('Current Value: UnHealhty - ' + toDisplay) + print("Air Quality Alert ->") + print("Current Value: UnHealhty - " + toDisplay) elif value > 200 and value < 250: - print('Air Quality Alert ->') - print('Current Value: UnHealthy - ' + toDisplay) + print("Air Quality Alert ->") + print("Current Value: UnHealthy - " + toDisplay) elif value > 250 and value > 300: - print('Air Quality Alert ->') - print('Current Value: Hazardous - ' + toDisplay) + print("Air Quality Alert ->") + print("Current Value: Hazardous - " + toDisplay) else: - print('Error: Unable to connect to server') + print("Error: Unable to connect to server") -if __name__ == '__main__': +if __name__ == "__main__": sys.exit(main(sys.argv)) diff --git a/articles_to_pdf/articles_to_pdf.py b/articles_to_pdf/articles_to_pdf.py index 1793fd017..dc64f8a92 100644 --- a/articles_to_pdf/articles_to_pdf.py +++ b/articles_to_pdf/articles_to_pdf.py @@ -1,9 +1,9 @@ -from selenium import webdriver -from selenium.webdriver.firefox.options import Options as Options_firefox -from selenium.webdriver.chrome.options import Options as Options_chrome - from pathlib import Path + import pdfkit +from selenium import webdriver +from selenium.webdriver.chrome.options import Options as Options_chrome +from selenium.webdriver.firefox.options import Options as Options_firefox def setup_driver(): @@ -14,9 +14,9 @@ def setup_driver(): find_chromedriver = Path("chromedriver") if find_geckodriver.exists(): - driver = 'geckodriver' - print('Using %s' % driver) - PATH_TO_DRIVER = './%s' % driver + driver = "geckodriver" + print("Using %s" % driver) + PATH_TO_DRIVER = "./%s" % driver firefox_options = Options_firefox() @@ -27,25 +27,33 @@ def setup_driver(): opt = webdriver.FirefoxProfile() opt.set_preference("network.cookie.cookieBehavior", 2) - browser = webdriver.Firefox(executable_path=PATH_TO_DRIVER, options=firefox_options, firefox_profile=opt) + browser = webdriver.Firefox( + executable_path=PATH_TO_DRIVER, options=firefox_options, firefox_profile=opt + ) elif find_chromedriver.exists(): - driver = 'chromedriver' - print('Using %s' % driver) - PATH_TO_DRIVER = './%s' % driver + driver = "chromedriver" + print("Using %s" % driver) + PATH_TO_DRIVER = "./%s" % driver chrome_options = Options_chrome() # run in headless mode - chrome_options.add_argument('--headless') + chrome_options.add_argument("--headless") # disable cookies to prevent popups - chrome_options.add_experimental_option('prefs', {'profile.default_content_setting_values.cookies': 2}) + chrome_options.add_experimental_option( + "prefs", {"profile.default_content_setting_values.cookies": 2} + ) - browser = webdriver.Chrome(executable_path=PATH_TO_DRIVER, options=chrome_options) + browser = webdriver.Chrome( + executable_path=PATH_TO_DRIVER, options=chrome_options + ) else: - print('ERROR: No valid driver found. Only geckodriver or chromedriver is supported!') + print( + "ERROR: No valid driver found. Only geckodriver or chromedriver is supported!" + ) exit() return browser @@ -55,7 +63,7 @@ def scrape_medium(browser, search_term, search_count): # perform search of keyword in medium - browser.get('https://medium.com/search?q=%s' % search_term) + browser.get("https://medium.com/search?q=%s" % search_term) browser.implicitly_wait(10) results = browser.find_elements_by_xpath('//a[contains(text(), "Read more")]') @@ -63,11 +71,11 @@ def scrape_medium(browser, search_term, search_count): all_articles = [] # get the links for all articles and store in list for each_article in results: - all_articles.append(each_article.get_attribute('href')) + all_articles.append(each_article.get_attribute("href")) # go to link of each article and export as PDF for counter, url in enumerate(all_articles, 1): - print('Exporting article %s/%s: %s' % ((counter), search_count, url)) + print("Exporting article %s/%s: %s" % ((counter), search_count, url)) browser.get(url) browser.implicitly_wait(10) @@ -79,16 +87,16 @@ def scrape_medium(browser, search_term, search_count): url_to_export = browser.current_url # pdf name will contain article title - pdf = 'Medium-%s.pdf' % article_title - pdf = pdf.replace(' ', '-') + pdf = "Medium-%s.pdf" % article_title + pdf = pdf.replace(" ", "-") # export pdf - quiet_mode = {'quiet': ''} + quiet_mode = {"quiet": ""} pdfkit.from_url(url_to_export, pdf, options=quiet_mode) # stop when we reach specified search count - if (counter == int(search_count)): - print('Complete. %s medium articles exported to PDF.' % search_count) + if counter == int(search_count): + print("Complete. %s medium articles exported to PDF." % search_count) browser.close() return @@ -96,23 +104,25 @@ def scrape_medium(browser, search_term, search_count): def process_option_1(): # get user settings - user_input = input('Enter search term followed by number of articles between 1 and 10 (e.g "learn python 5"): ') - user_input = user_input.split(' ') + user_input = input( + 'Enter search term followed by number of articles between 1 and 10 (e.g "learn python 5"): ' + ) + user_input = user_input.split(" ") # last entry should be a number try: search_count = int(user_input[-1]) except ValueError: - print('ERROR: Invalid input. The last entry must end with a number!') + print("ERROR: Invalid input. The last entry must end with a number!") return # remove number from list user_input.pop() # join strings to load the phrase to search - search_term = ' ' + search_term = " " for each_word in user_input: - search_term = search_term + each_word + ' ' + search_term = search_term + each_word + " " browser = setup_driver() scrape_medium(browser, search_term, search_count) @@ -124,9 +134,9 @@ def process_option_2(): # export a single article from the URL url = input("Paste URL to convert to PDF (must begin with 'https://'): ") - print('Converting to PDF...') - quiet_mode = {'quiet': ''} - pdfkit.from_url(url, 'converted.pdf', options=quiet_mode) + print("Converting to PDF...") + quiet_mode = {"quiet": ""} + pdfkit.from_url(url, "converted.pdf", options=quiet_mode) print('Complete. See "converted.pdf"') exit() @@ -135,15 +145,17 @@ def program_run(): while True: # get user option - option = input("Enter '1' to search medium or '2' to export a single medium article: ") + option = input( + "Enter '1' to search medium or '2' to export a single medium article: " + ) - if option == '1': + if option == "1": process_option_1() - elif option == '2': + elif option == "2": process_option_2() - elif option == 'x': + elif option == "x": exit() else: diff --git a/ascii_image/ascii_image.py b/ascii_image/ascii_image.py index 41e77b999..040c07813 100644 --- a/ascii_image/ascii_image.py +++ b/ascii_image/ascii_image.py @@ -1,15 +1,18 @@ -from PIL import Image -import numpy as np import argparse +import numpy as np +from PIL import Image + parser = argparse.ArgumentParser() -parser.add_argument('inputImage', help='Enter the path to image') -parser.add_argument('outputFile', help='Enter the path to output File') +parser.add_argument("inputImage", help="Enter the path to image") +parser.add_argument("outputFile", help="Enter the path to output File") +parser.add_argument( + "-w", "--width", help="Enter width of output image", type=int, default=75 +) parser.add_argument( - '-w', '--width', help='Enter width of output image', type=int, default=75) -parser.add_argument('-c', '--colorInvert', - help='Enter to invert color of image', action='store_true') + "-c", "--colorInvert", help="Enter to invert color of image", action="store_true" +) args = parser.parse_args() @@ -20,7 +23,7 @@ asci = r"@%#*+=-:. "[::1] if args.colorInvert: - asci = r"@%#*+=-:. "[:: - 1] + asci = r"@%#*+=-:. "[::-1] # input image img = Image.open(inputImagePath) @@ -33,7 +36,7 @@ def avg(imggg): - return (np.average(np.array(imggg))) + return np.average(np.array(imggg)) # opening file diff --git a/attachment-downloader/app.py b/attachment-downloader/app.py index 1f926ab79..ce946ea9c 100644 --- a/attachment-downloader/app.py +++ b/attachment-downloader/app.py @@ -1,5 +1,5 @@ -import imaplib import email +import imaplib import os USEREMAIL = "example@mail.com" diff --git a/attendance_automator/main.py b/attendance_automator/main.py index 79f664be3..f9962c003 100644 --- a/attendance_automator/main.py +++ b/attendance_automator/main.py @@ -1,10 +1,12 @@ +import os +from datetime import datetime + import cv2 import numpy as np + import face_recognition -import os -from datetime import datetime -path = 'images' +path = "images" images = [] personName = [] myList = os.listdir(path) @@ -12,7 +14,7 @@ print(myList) for cu_img in myList: - current_Img = cv2.imread(f'{path} / {cu_img}') + current_Img = cv2.imread(f"{path} / {cu_img}") images.append(current_Img) personName.append(os.path.splitext(cu_img)[0]) @@ -30,23 +32,23 @@ def faceEncodings(images): return encodeList -encodeListKnown = (faceEncodings(images)) +encodeListKnown = faceEncodings(images) print("All Encoding Complete!!!!!") def attendance(name): - with open('Attendance.csv', 'r+') as f: + with open("Attendance.csv", "r+") as f: myDataList = f.readlines() nameList = [] for line in myDataList: - entry = line.split(',') + entry = line.split(",") nameList.append(entry[0]) if name not in nameList: time_now = datetime.now() - tStr = time_now.strftime('%H:%M:%S') - dStr = time_now.strftime('%d/%m/%Y') - f.writelines(f'{name}, {tStr}, {dStr}') + tStr = time_now.strftime("%H:%M:%S") + dStr = time_now.strftime("%d/%m/%Y") + f.writelines(f"{name}, {tStr}, {dStr}") cap = cv2.VideoCapture(0) @@ -74,7 +76,15 @@ def attendance(name): y1, x2, y2, x1 = y1 * 4, x2 * 4, y2 * 4, x1 * 4 cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) cv2.rectangle(frame, (x1, y2 - 35), (x2, y2), (0, 255, 0), cv2.FILLED) - cv2.putText(frame, name, (x1 + 6, y2 - 6), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 0, 0), 1) + cv2.putText( + frame, + name, + (x1 + 6, y2 - 6), + cv2.FONT_HERSHEY_COMPLEX, + 1, + (255, 0, 0), + 1, + ) attendance(name) cv2.imshow("Camera", frame) diff --git a/audio_book/PDF_TO_AUDIO.py b/audio_book/PDF_TO_AUDIO.py index d5a9e1fc8..2fbda955e 100644 --- a/audio_book/PDF_TO_AUDIO.py +++ b/audio_book/PDF_TO_AUDIO.py @@ -1,22 +1,24 @@ -import pyttsx3 +from tkinter import Tk +from tkinter.filedialog import askopenfilename + import PyPDF2 +import pyttsx3 from gtts import gTTS -from tkinter.filedialog import askopenfilename -from tkinter import Tk + Tk().withdraw() filelocation = askopenfilename() # open the dialog GUI -book = open(filelocation, 'rb') +book = open(filelocation, "rb") pdfReader = PyPDF2.PdfFileReader(book) pages = pdfReader.numPages print("No. of pages: ", pages) speaker = pyttsx3.init() -whole_text = '' -choice = input('choice? ') +whole_text = "" +choice = input("choice? ") -if choice == '1': +if choice == "1": for num in range(0, pages): page = pdfReader.getPage(num) @@ -27,5 +29,5 @@ speaker.runAndWait() -final_file = gTTS(text=whole_text, lang='en') # store file in variable +final_file = gTTS(text=whole_text, lang="en") # store file in variable final_file.save("Output Audio.mp3") # Saving audio file diff --git a/audio_recoder/audio_recorder.py b/audio_recoder/audio_recorder.py index 5f3f46bf0..a3a3c0e6d 100644 --- a/audio_recoder/audio_recorder.py +++ b/audio_recoder/audio_recorder.py @@ -1,10 +1,11 @@ -import tkinter as tk import threading -import pyaudio +import tkinter as tk import wave +import pyaudio + -class App(): +class App: chunk = 1024 sample_format = pyaudio.paInt16 channels = 2 @@ -14,34 +15,38 @@ class App(): def __init__(self, master): self.isrecording = False - self.button1 = tk.Button(main, text='Start', width=6, - command=self.startrecording) - self.button2 = tk.Button(main, text='Stop', width=6, - command=self.stoprecording) + self.button1 = tk.Button( + main, text="Start", width=6, command=self.startrecording + ) + self.button2 = tk.Button(main, text="Stop", width=6, command=self.stoprecording) self.button1.pack() self.button2.pack() def startrecording(self): self.p = pyaudio.PyAudio() - self.stream = self.p.open(format=self.sample_format, - channels=self.channels, rate=self.fs, - frames_per_buffer=self.chunk, input=True) + self.stream = self.p.open( + format=self.sample_format, + channels=self.channels, + rate=self.fs, + frames_per_buffer=self.chunk, + input=True, + ) self.isrecording = True - self.button1['state'] = 'disable' - print('Recording') + self.button1["state"] = "disable" + print("Recording") t = threading.Thread(target=self.record) t.start() def stoprecording(self): self.isrecording = False - print('Recording Completed') - self.filename = input('Name the file?') + print("Recording Completed") + self.filename = input("Name the file?") self.filename = self.filename + ".wav" - wf = wave.open(self.filename, 'wb') + wf = wave.open(self.filename, "wb") wf.setnchannels(self.channels) wf.setsampwidth(self.p.get_sample_size(self.sample_format)) wf.setframerate(self.fs) - wf.writeframes(b''.join(self.frames)) + wf.writeframes(b"".join(self.frames)) wf.close() main.destroy() @@ -52,7 +57,7 @@ def record(self): main = tk.Tk() -main.title('Audio Recorder') +main.title("Audio Recorder") main.minsize(width=250, height=70) app = App(main) diff --git a/audio_remover/audio-remover.py b/audio_remover/audio-remover.py index 140fa63f9..be5d6259c 100644 --- a/audio_remover/audio-remover.py +++ b/audio_remover/audio-remover.py @@ -1,6 +1,7 @@ -from moviepy.editor import VideoFileClip -import os import argparse +import os + +from moviepy.editor import VideoFileClip # Define the base directory base_dir = os.path.dirname(os.path.abspath(__file__)) @@ -8,17 +9,16 @@ # Define CLI arguments parser = argparse.ArgumentParser() parser.add_argument( - '-f', + "-f", type=str, - help='The file path of target video. ' + help="The file path of target video. " + 'ex. /home/user/example.mp4.\nDefault value is "demo.mp4"', - default=base_dir + '/demo.mp4' + default=base_dir + "/demo.mp4", ) parser.add_argument( - '-n', + "-n", type=str, - help='The new file name.\n' - + 'Default value is {current file name}_noAudio.mp4', + help="The new file name.\n" + "Default value is {current file name}_noAudio.mp4", ) args = parser.parse_args() @@ -31,11 +31,14 @@ break except Exception: print( - 'Directory or file is not valid,' - + ' please enter a valid file directory ...') - audio_path = str(input('Enter the video path again (absolute path without space): ')) + "Directory or file is not valid," + + " please enter a valid file directory ..." + ) + audio_path = str( + input("Enter the video path again (absolute path without space): ") + ) -origin_file = (lambda x: x.split('/')[-1])(audio_path) +origin_file = (lambda x: x.split("/")[-1])(audio_path) if args.n: new_file = args.n @@ -44,9 +47,9 @@ def remove_audio(audio): - ''' + """ main function to remove audio from input video - ''' + """ video = VideoFileClip(audio) video = video.without_audio() video.write_videofile(os.path.join(base_dir, new_file)) @@ -56,5 +59,5 @@ def main(): remove_audio(audio_path) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/audio_sticky_notes/main.py b/audio_sticky_notes/main.py index b51fcbc97..3f090558f 100644 --- a/audio_sticky_notes/main.py +++ b/audio_sticky_notes/main.py @@ -1,5 +1,5 @@ -import tkinter import subprocess +import tkinter def makenew(): @@ -41,9 +41,9 @@ def reset(): while True: try: - makeNewBtn = tkinter.Button(manager, text='New+', command=makenew) + makeNewBtn = tkinter.Button(manager, text="New+", command=makenew) makeNewBtn.pack() - reset = tkinter.Button(manager, text='Reset-', command=reset) + reset = tkinter.Button(manager, text="Reset-", command=reset) reset.pack() tkinter.mainloop() except tkinter.TclError: diff --git a/audio_sticky_notes/note.py b/audio_sticky_notes/note.py index 20c79d4f0..0d75c001c 100644 --- a/audio_sticky_notes/note.py +++ b/audio_sticky_notes/note.py @@ -1,7 +1,8 @@ +import sys import tkinter + import sounddevice as sd import soundfile as sf -import sys def rec10s(): @@ -22,12 +23,14 @@ def rec(duration): recording = sd.rec(int(duration * fs), samplerate=fs, channels=2) sd.wait() - return sf.write("assets\\recordings\\AudioNote{}.flac".format(str(sys.argv[1])), recording, fs) + return sf.write( + "assets\\recordings\\AudioNote{}.flac".format(str(sys.argv[1])), recording, fs + ) def playback(): filename = "assets\\recordings\\AudioNote{}.flac".format(str(sys.argv[1])) - data, fs = sf.read(filename, dtype='float32') + data, fs = sf.read(filename, dtype="float32") sd.play(data, fs) sd.wait() @@ -35,7 +38,9 @@ def playback(): master = tkinter.Tk() master.title("Audio Note {}".format(str(sys.argv[1]))) -tkinter.Label(master, text=" Record for: (sec) ").grid(row=0, sticky=tkinter.W, rowspan=5, padx=15) +tkinter.Label(master, text=" Record for: (sec) ").grid( + row=0, sticky=tkinter.W, rowspan=5, padx=15 +) b = tkinter.Button(master, text="5", command=rec5s) b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=10, pady=10) @@ -46,7 +51,9 @@ def playback(): d = tkinter.Button(master, text="15", command=rec15s) d.grid(row=0, column=6, columnspan=2, rowspan=2, padx=10, pady=10) -tkinter.Label(master, text=" Playback: ").grid(row=5, sticky=tkinter.W, rowspan=5, padx=15) +tkinter.Label(master, text=" Playback: ").grid( + row=5, sticky=tkinter.W, rowspan=5, padx=15 +) e = tkinter.Button(master, text="Listen to the note", command=playback) e.grid(row=5, column=3, columnspan=5, padx=10, pady=10) diff --git a/auto_backup/main.py b/auto_backup/main.py index 29a11ac50..4aaefe1e3 100644 --- a/auto_backup/main.py +++ b/auto_backup/main.py @@ -1,9 +1,9 @@ +import zipfile from datetime import datetime from pathlib import Path -import zipfile -source_folder = './auto_backup/source/' # Source directory to be backed up -backup_folder = './auto_backup/backup' # Directory to save backups +source_folder = "./auto_backup/source/" # Source directory to be backed up +backup_folder = "./auto_backup/backup" # Directory to save backups backup_amount = 5 source_folder_path = Path(source_folder) @@ -13,35 +13,38 @@ backup_folder_path.mkdir(parents=True, exist_ok=True) -existing_backups = [x for x in backup_folder_path.iterdir( -) if x.is_file() and x.suffix == '.zip' and x.name.startswith('backup-')] +existing_backups = [ + x + for x in backup_folder_path.iterdir() + if x.is_file() and x.suffix == ".zip" and x.name.startswith("backup-") +] -sorted_backup = list( - sorted(existing_backups, key=lambda f: f.name)) +sorted_backup = list(sorted(existing_backups, key=lambda f: f.name)) while len(sorted_backup) >= backup_amount: backup_to_delete = sorted_backup.pop(0) backup_to_delete.unlink() -backup_file_name = f'backup_{datetime.now().strftime("%Y%m%d%H%M%S")}_{source_folder_path.name}.zip' +backup_file_name = ( + f'backup_{datetime.now().strftime("%Y%m%d%H%M%S")}_{source_folder_path.name}.zip' +) -zip_file = zipfile.ZipFile( - str(backup_folder_path / backup_file_name), mode='w') +zip_file = zipfile.ZipFile(str(backup_folder_path / backup_file_name), mode="w") if source_folder_path.is_file(): zip_file.write( source_folder_path.absolute(), arcname=source_folder_path.name, - compress_type=zipfile.ZIP_DEFLATED + compress_type=zipfile.ZIP_DEFLATED, ) elif source_folder_path.is_dir(): - for file in source_folder_path.glob('**/*'): + for file in source_folder_path.glob("**/*"): if file.is_file(): zip_file.write( file.absolute(), arcname=str(file.relative_to(source_folder_path)), - compress_type=zipfile.ZIP_DEFLATED + compress_type=zipfile.ZIP_DEFLATED, ) zip_file.close() diff --git a/auto_calender/calendarauto.py b/auto_calender/calendarauto.py index 267ba4fcc..a611d4f72 100644 --- a/auto_calender/calendarauto.py +++ b/auto_calender/calendarauto.py @@ -1,44 +1,45 @@ from __future__ import print_function -import pickle + import os.path -from googleapiclient.discovery import build -from google_auth_oauthlib.flow import InstalledAppFlow +import pickle +from datetime import datetime, timedelta + from google.auth.transport.requests import Request +from google_auth_oauthlib.flow import InstalledAppFlow +from googleapiclient.discovery import build from task import Task -from datetime import timedelta, datetime - categories = { # Lavender - '#a4bdfc': '', + "#a4bdfc": "", # Blueberry - '#5484ed': '', + "#5484ed": "", # Peacock - '#46d6db': 'Exercise', + "#46d6db": "Exercise", # Sage - '#7ae7bf': 'My Apps', + "#7ae7bf": "My Apps", # Basil - '#51b749': 'App', + "#51b749": "App", # Tangerine - '#ffb878': '', + "#ffb878": "", # Banana - '#fbd75b': '', + "#fbd75b": "", # Flamingo - '#ff887c': '', + "#ff887c": "", # Tomato - '#dc2127': 'YouTube', + "#dc2127": "YouTube", # Mandarine - '#fa573c': '', + "#fa573c": "", # Grape - '#dbadff': 'Work', + "#dbadff": "Work", # Graphite - '#e1e1e1': 'School' + "#e1e1e1": "School", } EVENTS_TO_LOOK_THROUGH = 60 # If modifying these scopes, delete the file token.pickle. -SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] +SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"] def main(): @@ -49,50 +50,60 @@ def main(): # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. - if os.path.exists('token.pickle'): - with open('token.pickle', 'rb') as token: + if os.path.exists("token.pickle"): + with open("token.pickle", "rb") as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) + flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES) creds = flow.run_local_server() # Save the credentials for the next run - with open('token.pickle', 'wb') as token: + with open("token.pickle", "wb") as token: pickle.dump(creds, token) - service = build('calendar', 'v3', credentials=creds) + service = build("calendar", "v3", credentials=creds) # Call the Calendar API start_day = datetime.utcnow() # 'Z' indicates UTC time - now = datetime.utcnow().isoformat() + 'Z' - last_monday = (datetime.utcnow() - timedelta(start_day.weekday())).isoformat() + 'Z' - - print('Getting the upcoming 10 events') - print('**************************************************************\n') - - events_result = service.events().list(calendarId='primary', timeMin=last_monday, timeMax=now, - maxResults=EVENTS_TO_LOOK_THROUGH, singleEvents=True, - orderBy='startTime').execute() - colors = service.colors().get(fields='event').execute() - defaultColor = (service.calendarList().get(calendarId="primary").execute())['backgroundColor'] - events = events_result.get('items', []) + now = datetime.utcnow().isoformat() + "Z" + last_monday = (datetime.utcnow() - timedelta(start_day.weekday())).isoformat() + "Z" + + print("Getting the upcoming 10 events") + print("**************************************************************\n") + + events_result = ( + service.events() + .list( + calendarId="primary", + timeMin=last_monday, + timeMax=now, + maxResults=EVENTS_TO_LOOK_THROUGH, + singleEvents=True, + orderBy="startTime", + ) + .execute() + ) + colors = service.colors().get(fields="event").execute() + defaultColor = (service.calendarList().get(calendarId="primary").execute())[ + "backgroundColor" + ] + events = events_result.get("items", []) tasks = [] if not events: - print('No upcoming events found.') + print("No upcoming events found.") for event in events: - start_string = event['start'].get('dateTime', event['start'].get('date')) - end_string = event['end'].get('dateTime', event['end'].get('date')) + start_string = event["start"].get("dateTime", event["start"].get("date")) + end_string = event["end"].get("dateTime", event["end"].get("date")) - name = event['summary'] + name = event["summary"] try: - color = colors['event'][event['colorId']]['background'] + color = colors["event"][event["colorId"]]["background"] except KeyError: color = defaultColor task = Task(name, parse_time(start_string), parse_time(end_string), color) @@ -109,7 +120,9 @@ def main(): text = "For " + category + " you have planned to spend:" number_of_spaces = 15 number_of_spaces -= len(category) - string_length = len(text) + number_of_spaces # will be adding 10 extra spaces + string_length = ( + len(text) + number_of_spaces + ) # will be adding 10 extra spaces string_revised = text.ljust(string_length) print("\n-----------------------------------------------------------------") print(string_revised + format_timedelta(total_time) + "hrs this week") @@ -130,8 +143,8 @@ def parse_time(timestamp): def format_timedelta(timedelta): # Takes a timedelta and returns a string hours = timedelta.total_seconds() / 3600 - return ("%.2f" % hours) + return "%.2f" % hours -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/auto_calender/task.py b/auto_calender/task.py index e5a550d82..1d6b639da 100644 --- a/auto_calender/task.py +++ b/auto_calender/task.py @@ -18,7 +18,7 @@ def make_int(self, time): arr = [] for line in time: if line.strip(): - try: # line contains eol character(s) + try: # line contains eol character(s) n = int(line) arr.append(n) except Exception: diff --git a/auto_clicker/autoclicker.py b/auto_clicker/autoclicker.py index f0091fe75..03d4afd46 100644 --- a/auto_clicker/autoclicker.py +++ b/auto_clicker/autoclicker.py @@ -4,7 +4,7 @@ # ======== Controls ======== start_or_pause_key = Key.f1 exit_key = Key.esc -delay = 1 # seconds +delay = 1 # seconds # ==== global variables ==== pause = True diff --git a/auto_completer/auto-complete.py b/auto_completer/auto-complete.py index 08d7d7a94..0bbb74df6 100644 --- a/auto_completer/auto-complete.py +++ b/auto_completer/auto-complete.py @@ -1,9 +1,9 @@ +import re + import torch import torch.nn as nn import torch.nn.functional as F -import re - device = torch.device("cpu") @@ -96,7 +96,7 @@ def generate_text_ngram(model, inputs, word_dict, n_words): # Making ngrams is also easy, you should be using (n-1) in slicing def make_n_grams(text, n): - return [(text[i: i + n], text[i + n]) for i in range(len(text) - n)] + return [(text[i : i + n], text[i + n]) for i in range(len(text) - n)] # Define hyperparameters N = 8 @@ -130,16 +130,22 @@ def make_n_grams(text, n): choice = int(input("Enter your choice (1-4): ")) - 1 input_text = d_sents[choice] else: - input_text = input("""Please enter an 8 word sentence - (Since loaded model uses 8-gram):""") + input_text = input( + """Please enter an 8 word sentence + (Since loaded model uses 8-gram):""" + ) n_seq = int(input("Enter number of more words to generate: ")) if len(input_text.split()) < 8: - raise ("""Please enter an 8 word sentence - to start with or choose from defaults!!!""") + raise ( + """Please enter an 8 word sentence + to start with or choose from defaults!!!""" + ) out = " ".join(generate_text_ngram(model, input_text, word_ixs, n_seq)[0]) - print(f"""\n\nThe Generated Text is: \n============================\n{out} - \n============================""") + print( + f"""\n\nThe Generated Text is: \n============================\n{out} + \n============================""" + ) diff --git a/auto_crypto_alert_mail/api_crypto_mail_alert.py b/auto_crypto_alert_mail/api_crypto_mail_alert.py index 5bbc3e0ee..202f975f1 100644 --- a/auto_crypto_alert_mail/api_crypto_mail_alert.py +++ b/auto_crypto_alert_mail/api_crypto_mail_alert.py @@ -2,16 +2,17 @@ # pip install secure-smtplib # pip install requests -import requests import smtplib -''' +import requests + +""" <===== IMPORTANT =====> 1. THIS WILL NOT WORK WHEN SENDING MAIL FROM GMAIL BECAUSE OF NEW GOOGLE SECURITY POLICIES. 2. BUT YOU CAN SEND MAIL FROM OUTLOOK OR ANY OTHER MAIL SERVICES WITHOUT ANY PROBLEM. 3. ONLY UPDATE 'from_email', 'from_email_password' & 'to_email'. 4. IF USING ANY OTHER MAIL SERVICE THEN CHANGE THE SERVER AND PORT TOO IN LINE 19 & 20. -''' +""" # Add your Email ID & it's Password by which you are sending the email alert from_email = "" @@ -29,9 +30,17 @@ def check_price(): cpolarity = int(input("Choose from 1 & 2: ")) trig_point = 1 if cpolarity == 1: - trig_point = float(input("Input the trigger price(dollar) above at which you want to recieve mail alert: ")) + trig_point = float( + input( + "Input the trigger price(dollar) above at which you want to recieve mail alert: " + ) + ) else: - trig_point = float(input("Input the trigger price(dollar) below at which you want to recieve mail alert: ")) + trig_point = float( + input( + "Input the trigger price(dollar) below at which you want to recieve mail alert: " + ) + ) def send_mail(): server = smtplib.SMTP(mail_server, mail_port) @@ -46,9 +55,9 @@ def send_mail(): else: body = f"{spot_name.upper()} Exchange is now below ${trig_point}: Current Exchange Rate: ${lprice}." - msg = f'''Subject: {subject}\n + msg = f"""Subject: {subject}\n To: {"".join(to_email)}\n - {body}''' + {body}""" server.sendmail(from_email, to_email, msg.encode("utf8")) diff --git a/auto_cursor_mover/auto_cursor_mover.py b/auto_cursor_mover/auto_cursor_mover.py index dce7b0bc7..b718acede 100644 --- a/auto_cursor_mover/auto_cursor_mover.py +++ b/auto_cursor_mover/auto_cursor_mover.py @@ -1,6 +1,7 @@ -import pyautogui import time +import pyautogui + while True: pyautogui.moveRel(0, 8) time.sleep(5) diff --git a/auto_news_reader/mySpeaker.py b/auto_news_reader/mySpeaker.py index 9beb08f0e..9cbe924f4 100644 --- a/auto_news_reader/mySpeaker.py +++ b/auto_news_reader/mySpeaker.py @@ -11,22 +11,24 @@ pass except RuntimeError: pass - voices = engine.getProperty('voices') - engine.setProperty('voice', voices[1].id) - engine.setProperty('rate', 150) - engine.setProperty('volume', 1.2) + voices = engine.getProperty("voices") + engine.setProperty("voice", voices[1].id) + engine.setProperty("rate", 150) + engine.setProperty("volume", 1.2) def print_say(txt): print(txt) engine.say(txt) engine.runAndWait() + + # If you are using Mac or Linux, use gtts for text to speech elif platform.system() == "Darwin" or platform.system() == "Linux": import os def print_say(texts): print(texts) - texts = texts.replace('"', '') + texts = texts.replace('"', "") texts = texts.replace("'", "") os.system(f'gtts-cli --nocheck "{texts}" | mpg123 -q -') # End of File diff --git a/auto_news_reader/read_npr_news.py b/auto_news_reader/read_npr_news.py index c34971b46..ee6215ac2 100644 --- a/auto_news_reader/read_npr_news.py +++ b/auto_news_reader/read_npr_news.py @@ -1,22 +1,24 @@ from io import BytesIO -import requests + import bs4 +import requests from pygame import mixer + +from auto_news_reader.mySpeaker import print_say # Import functions from the local package from auto_news_reader.voice_to_text import voice_to_text -from auto_news_reader.mySpeaker import print_say def news_brief(): # Locate the website for the NPR news brief - url = 'https://www.npr.org/podcasts/500005/npr-news-now' + url = "https://www.npr.org/podcasts/500005/npr-news-now" # Convert the source code to a soup string response = requests.get(url) - soup = bs4.BeautifulSoup(response.text, 'html.parser') + soup = bs4.BeautifulSoup(response.text, "html.parser") # Locate the tag that contains the mp3 files - casts = soup.findAll('a', {'class': 'audio-module-listen'}) + casts = soup.findAll("a", {"class": "audio-module-listen"}) # Obtain the web link for the mp3 file - cast = casts[0]['href'] + cast = casts[0]["href"] # Remove the unwanted components in the link mp3 = cast.find("?") mymp3 = cast[0:mp3] @@ -31,11 +33,11 @@ def news_brief(): while True: - print_say('Python is listening…') + print_say("Python is listening…") inp = voice_to_text().lower() - print_say(f'you just said: {inp}') + print_say(f"you just said: {inp}") if inp == "stop listening": - print_say('Goodbye!') + print_say("Goodbye!") break # If "news" in your voice command, play news brief elif "news" in inp: diff --git a/auto_pixelsort/autosort.py b/auto_pixelsort/autosort.py index f1bb58db6..be48bf95c 100644 --- a/auto_pixelsort/autosort.py +++ b/auto_pixelsort/autosort.py @@ -1,7 +1,8 @@ -import os -import sys import getopt +import os import random as r +import sys + from PIL import Image from pixelsort import pixelsort @@ -11,11 +12,11 @@ def randomize_params(): # --- DEFINE ALL PARAMETERS --- params = { - 1: 'interval_function', - 2: 'randomness', - 3: 'lower_threshold', - 4: 'upper_threshold', - 5: 'sorting_function', + 1: "interval_function", + 2: "randomness", + 3: "lower_threshold", + 4: "upper_threshold", + 5: "sorting_function", } # --- RANDOMIZE COUNT AND CHOICE OF PARAMS --- @@ -28,32 +29,32 @@ def randomize_params(): # --- SET DEFAULTS FOR PARAMS --- args = {} - args['angle'] = angle - args['interval_function'] = 'threshold' - args['lower_threshold'] = 0.5 - args['upper_threshold'] = 0.8 - args['randomness'] = 0.5 - args['sorting_function'] = 'lightness' + args["angle"] = angle + args["interval_function"] = "threshold" + args["lower_threshold"] = 0.5 + args["upper_threshold"] = 0.8 + args["randomness"] = 0.5 + args["sorting_function"] = "lightness" # --- UPDATE WITH RANDOMIZED VALUES --- for param in selected_params: - if param == 'interval_function': - interval_fns = ['random', 'threshold', 'waves'] - args['interval_function'] = r.choice(interval_fns) - elif param == 'randomness': - args['randomness'] = r.uniform(0.5, 1) - elif param == 'sorting_function': - sorting_fns = ['lightness', 'hue', 'saturation', 'intensity', 'minimum'] - args['sorting_function'] = r.choice(sorting_fns) - elif param == 'lower_threshold': - args['lower_threshold'] = r.uniform(0.5, 1) - elif param == 'upper_threshold': + if param == "interval_function": + interval_fns = ["random", "threshold", "waves"] + args["interval_function"] = r.choice(interval_fns) + elif param == "randomness": + args["randomness"] = r.uniform(0.5, 1) + elif param == "sorting_function": + sorting_fns = ["lightness", "hue", "saturation", "intensity", "minimum"] + args["sorting_function"] = r.choice(sorting_fns) + elif param == "lower_threshold": + args["lower_threshold"] = r.uniform(0.5, 1) + elif param == "upper_threshold": up_thresh = r.uniform(0.6, 1) - if up_thresh <= args['lower_threshold']: - up_thresh += r.uniform(0.1, 1 - args['lower_threshold']) - args['upper_threshold'] = up_thresh - elif args['upper_threshold'] - args['lower_threshold'] < 0.25: - args['lower_threshold'] -= 0.25 + if up_thresh <= args["lower_threshold"]: + up_thresh += r.uniform(0.1, 1 - args["lower_threshold"]) + args["upper_threshold"] = up_thresh + elif args["upper_threshold"] - args["lower_threshold"] < 0.25: + args["lower_threshold"] -= 0.25 return args @@ -61,12 +62,12 @@ def perform_sorting(args, img): # --- PERFORM PIXELSORT WITH RANDOMIZED PARAMS --- new_img = pixelsort( image=img, - angle=args['angle'], - interval_function=args['interval_function'], - lower_threshold=args['lower_threshold'], - upper_threshold=args['upper_threshold'], - randomness=args['randomness'], - sorting_function=args['sorting_function'] + angle=args["angle"], + interval_function=args["interval_function"], + lower_threshold=args["lower_threshold"], + upper_threshold=args["upper_threshold"], + randomness=args["randomness"], + sorting_function=args["sorting_function"], ) return new_img @@ -74,29 +75,29 @@ def perform_sorting(args, img): def Main(): # --- DEFINE ARGS AND SET DEFAULTS --- count = 0 - in_path = 'images/' - out_path = 'generated/' + in_path = "images/" + out_path = "generated/" argument_list = sys.argv[1:] - options = 'hi:n:' + options = "hi:n:" # --- DEFINE TERMINAL ARG OPERATIONS --- try: args, _ = getopt.getopt(argument_list, options) for current_argument, current_value in args: - if current_argument in ('-h'): - print('-' * 30) - print('-h : args description') - print('-i : pass location of input img-file') - print('-n : number of outputs required') - print('-' * 30) - if current_argument in ('-i'): - print('-' * 30) + if current_argument in ("-h"): + print("-" * 30) + print("-h : args description") + print("-i : pass location of input img-file") + print("-n : number of outputs required") + print("-" * 30) + if current_argument in ("-i"): + print("-" * 30) in_path += current_value - print(f'[+] Input-file: {in_path}') - if current_argument in ('-n'): + print(f"[+] Input-file: {in_path}") + if current_argument in ("-n"): count = int(current_value) - print(f'[+] Output-Count: {current_value}') - print('-' * 30) + print(f"[+] Output-Count: {current_value}") + print("-" * 30) except getopt.error as error: print(str(error)) @@ -113,18 +114,18 @@ def Main(): # --- PRINT RANDOMIZED CHOICES --- for arg in args.items(): - print(arg[0], ':', arg[1]) + print(arg[0], ":", arg[1]) # --- DEFINE LOCATIONS FOR LOAD AND SAVE --- in_file = in_path - out_file = out_path + f'result-0{index + 1}.png' + out_file = out_path + f"result-0{index + 1}.png" img = Image.open(in_file) # --- CALL SORT FUNCTION --- new_img = perform_sorting(args, img) # --- SAVE NEW FILE --- new_img.save(out_file) - print('-' * 30) + print("-" * 30) if __name__ == "__main__": diff --git a/auto_searcher/autosearcher.py b/auto_searcher/autosearcher.py index b0a593416..800bb9248 100644 --- a/auto_searcher/autosearcher.py +++ b/auto_searcher/autosearcher.py @@ -1,17 +1,17 @@ -from PIL import ImageGrab -import pytesseract import threading -import pynput.mouse as ms + import pynput.keyboard as kb -from pynput.keyboard import Key, Controller +import pynput.mouse as ms +import pytesseract +from PIL import ImageGrab +from pynput.keyboard import Controller, Key from selenium import webdriver keyboard = Controller() -pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' +pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" class Autosearch(threading.Thread): - def __init__(self, pImage, defined, pCords, clickCount, chromepath): super(Autosearch, self).__init__() @@ -22,7 +22,6 @@ def __init__(self, pImage, defined, pCords, clickCount, chromepath): self.chromepath = chromepath def area_select(self): - def on_click(x, y, button, pressed): if pressed: @@ -42,7 +41,6 @@ def on_click(x, y, button, pressed): listener.join() def keyPress(self): - def on_press(key): i = 10 print(i) @@ -59,29 +57,33 @@ def on_release(key): def capture(self): if self.defined: - self.pImage = ImageGrab.grab(bbox=(self.pCords[0], self.pCords[1], self.pCords[2], self.pCords[3])) + self.pImage = ImageGrab.grab( + bbox=(self.pCords[0], self.pCords[1], self.pCords[2], self.pCords[3]) + ) parastring = pytesseract.image_to_string(self.pImage) - parastring.replace('/n', '+') - parastring.replace(' ', '+') + parastring.replace("/n", "+") + parastring.replace(" ", "+") Autosearch.searches(self, parastring) else: - print('error') + print("error") def searches(self, parastring): options = webdriver.ChromeOptions() - options.add_experimental_option('excludeSwitches', ['enable-automation']) + options.add_experimental_option("excludeSwitches", ["enable-automation"]) browser = webdriver.Chrome(executable_path=self.chromepath, options=options) - url = browser.get("https://www.google.com/search?q=" + parastring + "&start=" + '0') + url = browser.get( + "https://www.google.com/search?q=" + parastring + "&start=" + "0" + ) browser.get(url) -if __name__ == '__main__': +if __name__ == "__main__": r = Autosearch(None, False, [0, 0, 0, 0], 0, "/Users/HP/Desktop/chromedriver") r.keyPress() diff --git a/auto_shutdown/auto_shutdown.py b/auto_shutdown/auto_shutdown.py index ad04fab33..e0a400fff 100644 --- a/auto_shutdown/auto_shutdown.py +++ b/auto_shutdown/auto_shutdown.py @@ -13,9 +13,9 @@ def shutdown(): sec = 60 -print('Computer Will Now Shutdown in ' + str(set_time) + ' Minutes') +print("Computer Will Now Shutdown in " + str(set_time) + " Minutes") time.sleep(set_time * sec) -print('\n') -print('Computer Will Now Shutdown!') +print("\n") +print("Computer Will Now Shutdown!") time.sleep(3) shutdown() diff --git a/auto_typer/autotyper.py b/auto_typer/autotyper.py index a83453d3d..822a9e7b8 100644 --- a/auto_typer/autotyper.py +++ b/auto_typer/autotyper.py @@ -1,13 +1,14 @@ -from PIL import ImageGrab -from pytesseract import pytesseract import time -import pynput.mouse as ms + import pynput.keyboard as kb -from pynput.keyboard import Key, Controller +import pynput.mouse as ms +from PIL import ImageGrab +from pynput.keyboard import Controller, Key +from pytesseract import pytesseract keyboard = Controller() -pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' +pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe" class AutoTyper: @@ -19,12 +20,12 @@ class AutoTyper: def area_select(): - print('Click twice to define TEXT window') + print("Click twice to define TEXT window") def on_click(x, y, button, pressed): if pressed: - print('({0}, {1})'.format(x, y)) + print("({0}, {1})".format(x, y)) if AutoTyper.clickCount == 0: AutoTyper.pCords[0] = x AutoTyper.pCords[1] = y @@ -32,7 +33,7 @@ def on_click(x, y, button, pressed): AutoTyper.pCords[2] = x AutoTyper.pCords[3] = y AutoTyper.defined = True - print('') + print("") AutoTyper.clickCount = 0 return False AutoTyper.clickCount += 1 @@ -42,7 +43,7 @@ def on_click(x, y, button, pressed): def keyPress(): - print('UP ARROW') + print("UP ARROW") def on_press(key): i = 10 @@ -51,7 +52,7 @@ def on_press(key): def on_release(key): if key == Key.up: - print('Pressed\n') + print("Pressed\n") AutoTyper.area_select() AutoTyper.capture() @@ -62,7 +63,7 @@ def on_release(key): def startTyping(delaytime: float): - print('DOWN ARROW') + print("DOWN ARROW") def on_press(key): i = 10 @@ -70,7 +71,7 @@ def on_press(key): def on_release(key): if key == Key.down: - print('Pressed\n') + print("Pressed\n") AutoTyper.output(delaytime) return False @@ -80,20 +81,24 @@ def on_release(key): def capture(): if AutoTyper.defined: - AutoTyper.pImage = ImageGrab.grab(bbox=(AutoTyper.pCords[0], - AutoTyper.pCords[1], - AutoTyper.pCords[2], - AutoTyper.pCords[3])) + AutoTyper.pImage = ImageGrab.grab( + bbox=( + AutoTyper.pCords[0], + AutoTyper.pCords[1], + AutoTyper.pCords[2], + AutoTyper.pCords[3], + ) + ) else: - print('please define an area to OCR before trying to print') + print("please define an area to OCR before trying to print") def output(delaytime: float): try: paraString = pytesseract.image_to_string(AutoTyper.pImage) except SystemError: - print('\n Error while processing your image, please retry.') + print("\n Error while processing your image, please retry.") return False length = len(paraString) @@ -110,5 +115,5 @@ def start(delaytime: float): AutoTyper.startTyping(delaytime) -if __name__ == '__main__': +if __name__ == "__main__": start(0.01) diff --git a/automated_calling/autocall.py b/automated_calling/autocall.py index a63caf464..411d3d505 100644 --- a/automated_calling/autocall.py +++ b/automated_calling/autocall.py @@ -5,12 +5,12 @@ print("\n" + " ***** WELCOME TO AUTOMATED PYTHON CALLING SCRIPT ***** ") print(" ***** PLEASE CREATE A TWILIO ACCOUNT BEFORE USING THE SCRIPT ***** ") print(" ***** TO CREATE TWILIO ACCOUNT GO TO WWW.TWILIO.COM ***** ") -print(" ***** TYPE 'YES/yes' IF YOU WANT TO PROCEED ***** " + '\n') +print(" ***** TYPE 'YES/yes' IF YOU WANT TO PROCEED ***** " + "\n") i = input() print("\n") -if (i == "YES" or i == "yes"): +if i == "YES" or i == "yes": account_sid = input(" ENTER YOUR TWILIO ACCOUNT-SID ") auth_token = input(" ENTER YOUR TWILIO AUTH-TOKEN ") @@ -20,28 +20,32 @@ print("**** press 2 for multiple phone numbers *****") i = int(input()) - if (i == 1): - print(" ***** PLEASE ENTER RECIEVER's NUMBER **note mention your country code followed by '+' *****") + if i == 1: + print( + " ***** PLEASE ENTER RECIEVER's NUMBER **note mention your country code followed by '+' *****" + ) number = int(input()) - print(" ***** PLEASE ENTER YOUR AUTOGENERATED NUMBER **note mention your country code followed by '+' *****") + print( + " ***** PLEASE ENTER YOUR AUTOGENERATED NUMBER **note mention your country code followed by '+' *****" + ) my_number = int(input()) call = client.calls.create( - url='http://demo.twilio.com/docs/voice.xml', - to=number, - from_=my_number + url="http://demo.twilio.com/docs/voice.xml", to=number, from_=my_number ) print(" call success ") - if (i == 2): - print(" ***** PLEASE ENTER RECIEVER's NUMBER SEPARTED BY SPACE AND FOLLOWED BY + COUNTRY-CODE") - number = list(int(i) for i in input().strip().split(' ')) - print(" ***** PLEASE ENTER YOUR AUTOGENERATED NUMBER AND FOLLOWED BY + COUNTRY-CODE") + if i == 2: + print( + " ***** PLEASE ENTER RECIEVER's NUMBER SEPARTED BY SPACE AND FOLLOWED BY + COUNTRY-CODE" + ) + number = list(int(i) for i in input().strip().split(" ")) + print( + " ***** PLEASE ENTER YOUR AUTOGENERATED NUMBER AND FOLLOWED BY + COUNTRY-CODE" + ) my_number = int(input()) for i in number: call = client.calls.create( - url='http://demo.twilio.com/docs/voice.xml', - to=i, - from_=my_number + url="http://demo.twilio.com/docs/voice.xml", to=i, from_=my_number ) print(" call success to the number " + str(i)) diff --git a/barcode_scanner/barcode_scanner.py b/barcode_scanner/barcode_scanner.py index 1c7da0b6f..705cf4035 100644 --- a/barcode_scanner/barcode_scanner.py +++ b/barcode_scanner/barcode_scanner.py @@ -1,32 +1,39 @@ #!/usr/bin/python -from pyzbar.pyzbar import decode from glob import glob + import cv2 +from pyzbar.pyzbar import decode def barcode(decoded, image): - imge = cv2.rectangle(image, (decoded.rect.left, decoded.rect.top), - (decoded.rect.left + decoded.rect.width, - decoded.rect.top + decoded.rect.height), - color=(0, 255, 0), thickness=5) + imge = cv2.rectangle( + image, + (decoded.rect.left, decoded.rect.top), + ( + decoded.rect.left + decoded.rect.width, + decoded.rect.top + decoded.rect.height, + ), + color=(0, 255, 0), + thickness=5, + ) return imge def scan(image): dcode = decode(image) for obj in dcode: - print('Given barcode:', obj) + print("Given barcode:", obj) image = barcode(obj, image) - print('Barcode Type:', obj.type) - print('Scanned Data:', obj.data) + print("Barcode Type:", obj.type) + print("Scanned Data:", obj.data) print() return image -dat = input('Enter the path of the barcode') +dat = input("Enter the path of the barcode") data = glob(dat) for code in data: img = cv2.imread(code) img = scan(img) - cv2.imshow('img', img) + cv2.imshow("img", img) cv2.waitKey(0) diff --git a/battery_notification/battery_notification.py b/battery_notification/battery_notification.py index 44cda7eca..c757afffd 100644 --- a/battery_notification/battery_notification.py +++ b/battery_notification/battery_notification.py @@ -1,23 +1,24 @@ import psutil from plyer import notification + # From psutil we import sensors battery class which gives us battery percentage -threshold = int(input('Enter the threshold: ')) +threshold = int(input("Enter the threshold: ")) battery = psutil.sensors_battery() percent = battery.percent -while (True): +while True: battery = psutil.sensors_battery() cur_per = battery.percent change = cur_per - percent diff = abs(change) - ''' We calculate the change in the battery - and show notification if battery level increases or decreases''' - if (diff >= threshold): + """ We calculate the change in the battery + and show notification if battery level increases or decreases""" + if diff >= threshold: notification.notify( title="Battery Percentage", message=str(cur_per) + "% Battery Remaining", - timeout=5 + timeout=5, ) percent = cur_per continue diff --git a/birthday_wisher/birth_day_wish_telegram.py b/birthday_wisher/birth_day_wish_telegram.py index 889f1d100..79394152d 100644 --- a/birthday_wisher/birth_day_wish_telegram.py +++ b/birthday_wisher/birth_day_wish_telegram.py @@ -6,22 +6,22 @@ from telethon.sync import TelegramClient from telethon.tl.types import InputPeerUser -api_id = '' -api_hash = '' -token = '' +api_id = "" +api_hash = "" +token = "" -phone = '' +phone = "" def send_message(msg): - client = TelegramClient('session', api_id, api_hash) + client = TelegramClient("session", api_id, api_hash) client.connect() if not client.is_user_authorized(): client.send_code_request(phone) - client.sign_in(phone, input('Enter the code: ')) + client.sign_in(phone, input("Enter the code: ")) try: - receiver = InputPeerUser('user_id', 'user_hash') - client.send_message(receiver, msg, parse_mode='html') + receiver = InputPeerUser("user_id", "user_hash") + client.send_message(receiver, msg, parse_mode="html") except Exception as e: print(e) client.disconnect() diff --git a/bmi_calculator/Calculator.py b/bmi_calculator/Calculator.py index 1f4d62cbe..ed4c6c35f 100644 --- a/bmi_calculator/Calculator.py +++ b/bmi_calculator/Calculator.py @@ -3,9 +3,9 @@ def reset_entry(): - age_tf.delete(0, 'end') - height_tf.delete(0, 'end') - weight_tf.delete(0, 'end') + age_tf.delete(0, "end") + height_tf.delete(0, "end") + weight_tf.delete(0, "end") def calculate_bmi(): @@ -18,50 +18,59 @@ def calculate_bmi(): def bmi_index(bmi): if bmi < 18.5: - messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Underweight') + messagebox.showinfo("bmi-pythonguides", f"BMI = {bmi} is Underweight") elif (bmi > 18.5) and (bmi < 24.9): - messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Normal') + messagebox.showinfo("bmi-pythonguides", f"BMI = {bmi} is Normal") elif (bmi > 24.9) and (bmi < 29.9): - messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Overweight') - elif (bmi > 29.9): - messagebox.showinfo('bmi-pythonguides', f'BMI = {bmi} is Obesity') + messagebox.showinfo("bmi-pythonguides", f"BMI = {bmi} is Overweight") + elif bmi > 29.9: + messagebox.showinfo("bmi-pythonguides", f"BMI = {bmi} is Obesity") else: - messagebox.showerror('bmi-pythonguides', 'something went wrong!') + messagebox.showerror("bmi-pythonguides", "something went wrong!") ws = tk.Tk() -ws.title('PythonGuides') -ws.geometry('400x300') -ws.config(bg='#686e70') +ws.title("PythonGuides") +ws.geometry("400x300") +ws.config(bg="#686e70") var = tk.IntVar() frame = tk.Frame(ws, padx=10, pady=10) frame.pack(expand=True) age_lb = tk.Label(frame, text="Enter Age (2 - 120)") age_lb.grid(row=1, column=1) -age_tf = tk.Entry(frame, ) +age_tf = tk.Entry( + frame, +) age_tf.grid(row=1, column=2, pady=5) -gen_lb = tk.Label(frame, text='Select Gender') +gen_lb = tk.Label(frame, text="Select Gender") gen_lb.grid(row=2, column=1) frame2 = tk.Frame(frame) frame2.grid(row=2, column=2, pady=5) -male_rb = tk.Radiobutton(frame2, text='Male', variable=var, value=1) +male_rb = tk.Radiobutton(frame2, text="Male", variable=var, value=1) male_rb.pack(side=tk.LEFT) -female_rb = tk.Radiobutton(frame2, text='Female', variable=var, value=2) +female_rb = tk.Radiobutton(frame2, text="Female", variable=var, value=2) female_rb.pack(side=tk.RIGHT) height_lb = tk.Label(frame, text="Enter Height (cm) ") height_lb.grid(row=3, column=1) -weight_lb = tk.Label(frame, text="Enter Weight (kg) ", ) +weight_lb = tk.Label( + frame, + text="Enter Weight (kg) ", +) weight_lb.grid(row=4, column=1) -height_tf = tk.Entry(frame,) +height_tf = tk.Entry( + frame, +) height_tf.grid(row=3, column=2, pady=5) -weight_tf = tk.Entry(frame,) +weight_tf = tk.Entry( + frame, +) weight_tf.grid(row=4, column=2, pady=5) frame3 = tk.Frame(frame) frame3.grid(row=5, columnspan=3, pady=10) -cal_btn = tk.Button(frame3, text='Calculate', command=calculate_bmi) +cal_btn = tk.Button(frame3, text="Calculate", command=calculate_bmi) cal_btn.pack(side=tk.LEFT) -reset_btn = tk.Button(frame3, text='Reset', command=reset_entry) +reset_btn = tk.Button(frame3, text="Reset", command=reset_entry) reset_btn.pack(side=tk.LEFT) -exit_btn = tk.Button(frame3, text='Exit', command=lambda: ws.destroy()) +exit_btn = tk.Button(frame3, text="Exit", command=lambda: ws.destroy()) exit_btn.pack(side=tk.RIGHT) ws.mainloop() diff --git a/book_manager/Dialog.py b/book_manager/Dialog.py index 2401e677b..9e7c59906 100644 --- a/book_manager/Dialog.py +++ b/book_manager/Dialog.py @@ -8,22 +8,23 @@ # run again. Do not edit this file unless you know what you are doing. -from PyQt5 import QtCore, QtGui, QtWidgets import os +from PyQt5 import QtCore, QtGui, QtWidgets + class Ui_Dialog(object): - def setupUi(self, Dialog, name='', path='', notes='', tags='', add=0): + def setupUi(self, Dialog, name="", path="", notes="", tags="", add=0): Dialog.setObjectName("Dialog") Dialog.resize(433, 310) self.dialog = Dialog self.add = add self.data = {} - self.data['delete'] = False - self.data['name'] = '' - self.data['path'] = '' - self.data['tags'] = '' - self.data['notes'] = '' + self.data["delete"] = False + self.data["name"] = "" + self.data["path"] = "" + self.data["tags"] = "" + self.data["notes"] = "" self.label = QtWidgets.QLabel(Dialog) self.label.setGeometry(QtCore.QRect(20, 30, 55, 16)) self.label.setObjectName("label") @@ -54,11 +55,13 @@ def setupUi(self, Dialog, name='', path='', notes='', tags='', add=0): self.textEdit.setText(notes) if add == 0: self.pushButton_delete = QtWidgets.QPushButton(Dialog) - self.pushButton_delete.setGeometry( - QtCore.QRect(20, 250, 93, 28)) + self.pushButton_delete.setGeometry(QtCore.QRect(20, 250, 93, 28)) icon = QtGui.QIcon() - icon.addPixmap(QtGui.QPixmap(".\\Icons/delete.webp"), - QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon.addPixmap( + QtGui.QPixmap(".\\Icons/delete.webp"), + QtGui.QIcon.Normal, + QtGui.QIcon.Off, + ) self.pushButton_delete.setIcon(icon) self.pushButton_delete.setObjectName("pushButton_delete") self.pushButton_delete.clicked.connect(self.delete_clicked) @@ -71,8 +74,9 @@ def setupUi(self, Dialog, name='', path='', notes='', tags='', add=0): self.pushButton_open.clicked.connect(self.open_clicked) self.pushButton_open.setText("") icon1 = QtGui.QIcon() - icon1.addPixmap(QtGui.QPixmap(".\\Icons/open.webp"), - QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon1.addPixmap( + QtGui.QPixmap(".\\Icons/open.webp"), QtGui.QIcon.Normal, QtGui.QIcon.Off + ) self.pushButton_open.setIcon(icon1) self.pushButton_open.setObjectName("pushButton_open") self.pushButton_cancel = QtWidgets.QPushButton(Dialog) @@ -95,7 +99,7 @@ def retranslateUi(self, Dialog): self.pushButton_cancel.setText(_translate("Dialog", "Cancel")) def delete_clicked(self): - self.data['delete'] = True + self.data["delete"] = True self.dialog.accept() def cancel_clicked(self): @@ -104,19 +108,18 @@ def cancel_clicked(self): def open_clicked(self): try: - item = self.lineEdit_2.text().split('/') - finalpath = '/'.join(item[:-1]) + item = self.lineEdit_2.text().split("/") + finalpath = "/".join(item[:-1]) if finalpath: os.startfile(finalpath) except Exception as e: print("Open Error Occurred", e) def ok_clicked(self): - self.data['name'] = self.lineEdit.text() - self.data['path'] = self.lineEdit_2.text() - self.data['tags'] = [i.strip() - for i in self.lineEdit_3.text().split(', ')] - self.data['notes'] = self.textEdit.toPlainText() + self.data["name"] = self.lineEdit.text() + self.data["path"] = self.lineEdit_2.text() + self.data["tags"] = [i.strip() for i in self.lineEdit_3.text().split(", ")] + self.data["notes"] = self.textEdit.toPlainText() self.dialog.accept() # pass @@ -126,13 +129,14 @@ def ok_clicked(self): # self.data['tags'] = self.lineEdit_3.text() # self.data['notes'] = self.textEdit.toPlainText() # self.dialog.accept() - # print(name) - # return name - # Dialog.done(name) + # print(name) + # return name + # Dialog.done(name) if __name__ == "__main__": import sys + app = QtWidgets.QApplication(sys.argv) Dialog = QtWidgets.QDialog() ui = Ui_Dialog() diff --git a/book_manager/book.py b/book_manager/book.py index c151998b9..de7f70358 100644 --- a/book_manager/book.py +++ b/book_manager/book.py @@ -1,4 +1,3 @@ - # conn = sqlite3.connect("books.db") # c = conn.cursor() @@ -16,20 +15,22 @@ def add_book(conn, book): c = conn.cursor() - c.execute("INSERT INTO books VALUES (?, ?, ?, ?)", - (book.name, book.path, book.notes, book.tags)) + c.execute( + "INSERT INTO books VALUES (?, ?, ?, ?)", + (book.name, book.path, book.notes, book.tags), + ) conn.commit() def delete_book(conn, path): c = conn.cursor() - c.execute("DELETE FROM books WHERE path = ? ", (path, )) + c.execute("DELETE FROM books WHERE path = ? ", (path,)) conn.commit() def edit_book(conn, prop, value, name): c = conn.cursor() - if prop in ['name', 'notes', 'tags', 'path']: + if prop in ["name", "notes", "tags", "path"]: c.execute(f"UPDATE books SET {prop} = ? WHERE path = ?", (value, name)) conn.commit() @@ -40,16 +41,17 @@ def show_books(conn): finresults = [] results = c.fetchall() for i in results: - finresults.append([i[0], i[1], i[2].split(', '), i[3]]) + finresults.append([i[0], i[1], i[2].split(", "), i[3]]) return finresults def search_book(conn, prop, value): c = conn.cursor() - if prop in ['name', 'notes', 'tags', 'path']: - c.execute(f"SELECT * FROM books where {prop} = ?", (value, )) + if prop in ["name", "notes", "tags", "path"]: + c.execute(f"SELECT * FROM books where {prop} = ?", (value,)) conn.commit() + # print("Welcome to BookMan") # while True: # print("1.Add New Book\n2.Edit a Book\n3.Display all books\n4.Delete a book\n5.Exit") diff --git a/book_manager/bookman.py b/book_manager/bookman.py index aa41d6869..3c10df769 100644 --- a/book_manager/bookman.py +++ b/book_manager/bookman.py @@ -8,11 +8,13 @@ # run again. Do not edit this file unless you know what you are doing. -from PyQt5 import QtCore, QtGui, QtWidgets import sqlite3 -from book import show_books, add_book, edit_book, delete_book -from Dialog import Ui_Dialog + +from book import add_book, delete_book, edit_book, show_books from data_model import Book +from Dialog import Ui_Dialog +from PyQt5 import QtCore, QtGui, QtWidgets + conn = sqlite3.connect("books.db") books = [] @@ -31,8 +33,9 @@ def setupUi(self, MainWindow): books = show_books(conn) for item in books: newitem = QtWidgets.QListWidgetItem( - f"Name: {item[0]}\nPath: {item[1]}\nTags: {', '.join(item[2])}\nNotes: {item[3]}\n") - font = QtGui.QFont('Times', 12) + f"Name: {item[0]}\nPath: {item[1]}\nTags: {', '.join(item[2])}\nNotes: {item[3]}\n" + ) + font = QtGui.QFont("Times", 12) font.setBold(True) font.setWeight(50) newitem.setFont(font) @@ -44,16 +47,13 @@ def setupUi(self, MainWindow): palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(85, 170, 0)) brush.setStyle(QtCore.Qt.SolidPattern) - palette.setBrush(QtGui.QPalette.Active, - QtGui.QPalette.BrightText, brush) + palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(85, 170, 0)) brush.setStyle(QtCore.Qt.SolidPattern) - palette.setBrush(QtGui.QPalette.Inactive, - QtGui.QPalette.BrightText, brush) + palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.BrightText, brush) brush = QtGui.QBrush(QtGui.QColor(85, 170, 0)) brush.setStyle(QtCore.Qt.SolidPattern) - palette.setBrush(QtGui.QPalette.Disabled, - QtGui.QPalette.BrightText, brush) + palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.BrightText, brush) self.label.setPalette(palette) self.label.setText("") self.label.setPixmap(QtGui.QPixmap("Icons/logo.png")) @@ -62,8 +62,9 @@ def setupUi(self, MainWindow): self.button_add = QtWidgets.QPushButton(self.centralwidget) self.button_add.setGeometry(QtCore.QRect(20, 80, 111, 41)) icon = QtGui.QIcon() - icon.addPixmap(QtGui.QPixmap("Icons/add.svg"), - QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon.addPixmap( + QtGui.QPixmap("Icons/add.svg"), QtGui.QIcon.Normal, QtGui.QIcon.Off + ) self.button_add.setIcon(icon) self.button_add.setObjectName("button_add") self.button_add.clicked.connect(self.add_books) @@ -74,8 +75,9 @@ def setupUi(self, MainWindow): self.button_search.setGeometry(QtCore.QRect(40, 180, 41, 31)) self.button_search.setText("") icon1 = QtGui.QIcon() - icon1.addPixmap(QtGui.QPixmap("Icons/search.webp"), - QtGui.QIcon.Normal, QtGui.QIcon.Off) + icon1.addPixmap( + QtGui.QPixmap("Icons/search.webp"), QtGui.QIcon.Normal, QtGui.QIcon.Off + ) self.button_search.setIcon(icon1) self.button_search.setObjectName("button_search") self.button_search.clicked.connect(self.search_books) @@ -137,8 +139,9 @@ def show_all(self): # print(books) for item in books: newitem = QtWidgets.QListWidgetItem( - f"Name: {item[0]}\nPath: {item[1]}\nTags: {', '.join(item[2])}\nNotes: {item[3]}\n") - font = QtGui.QFont('Times', 12) + f"Name: {item[0]}\nPath: {item[1]}\nTags: {', '.join(item[2])}\nNotes: {item[3]}\n" + ) + font = QtGui.QFont("Times", 12) font.setBold(True) font.setWeight(50) newitem.setFont(font) @@ -150,8 +153,12 @@ def search_books(self): global books results = [] searchtext = self.lineEdit.text() - field = [self.radioButton_1.isChecked(), self.radioButton_2.isChecked( - ), self.radioButton_3.isChecked(), self.radioButton_4.isChecked()] + field = [ + self.radioButton_1.isChecked(), + self.radioButton_2.isChecked(), + self.radioButton_3.isChecked(), + self.radioButton_4.isChecked(), + ] ind = field.index(True) for i in books: if searchtext in i[ind]: @@ -159,8 +166,9 @@ def search_books(self): self.list_1.clear() for item in results: newitem = QtWidgets.QListWidgetItem( - f"Name: {item[0]}\nPath: {item[1]}\nTags: {', '.join(item[2])}\nNotes: {item[3]}\n") - font = QtGui.QFont('Times', 12) + f"Name: {item[0]}\nPath: {item[1]}\nTags: {', '.join(item[2])}\nNotes: {item[3]}\n" + ) + font = QtGui.QFont("Times", 12) font.setBold(True) font.setWeight(50) newitem.setFont(font) @@ -169,26 +177,40 @@ def search_books(self): def add_books(self): global books res = self.open_dialog_box() - name = res[0].split('/')[-1] + name = res[0].split("/")[-1] Dialog2 = QtWidgets.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog2, path=res[0], name=name, add=1) Dialog2.show() s = Dialog2.exec_() if s == 1: - if ui.data['path'] not in [i[1] for i in books]: - books.append([ui.data['name'], ui.data['path'], - ui.data['tags'], ui.data['notes']]) + if ui.data["path"] not in [i[1] for i in books]: + books.append( + [ + ui.data["name"], + ui.data["path"], + ui.data["tags"], + ui.data["notes"], + ] + ) item = books[-1] newitem = QtWidgets.QListWidgetItem( - f"Name: {item[0]}\nPath: {item[1]}\nTags: {', '.join(item[2])}\nNotes: {item[3]}\n") - font = QtGui.QFont('Times', 12) + f"Name: {item[0]}\nPath: {item[1]}\nTags: {', '.join(item[2])}\nNotes: {item[3]}\n" + ) + font = QtGui.QFont("Times", 12) font.setBold(True) font.setWeight(50) newitem.setFont(font) self.list_1.addItem(newitem) - add_book(conn, Book(ui.data['name'], ui.data['path'], ', '.join( - item[2]), ui.data['notes'])) + add_book( + conn, + Book( + ui.data["name"], + ui.data["path"], + ", ".join(item[2]), + ui.data["notes"], + ), + ) def open_dialog_box(self): filename = QtWidgets.QFileDialog.getOpenFileName() @@ -197,20 +219,19 @@ def open_dialog_box(self): def open_properties(self, item): global books - lines = item.text().split('\n') + lines = item.text().split("\n") final = [] for index, i in enumerate(lines): lines[index] = i.strip() - val = ' '.join(lines[index].split(' ')[1:]) + val = " ".join(lines[index].split(" ")[1:]) final.append(val) Dialog2 = QtWidgets.QDialog() ui = Ui_Dialog() - ui.setupUi( - Dialog2, path=final[1], name=final[0], tags=final[2], notes=final[3]) + ui.setupUi(Dialog2, path=final[1], name=final[0], tags=final[2], notes=final[3]) Dialog2.show() s = Dialog2.exec_() if s == 1: - if ui.data['delete'] is True: + if ui.data["delete"] is True: for index, i in enumerate(books): if i[1] == final[1]: ind = index @@ -224,19 +245,19 @@ def open_properties(self, item): if i[1] == final[1]: ind = index break - books[index][0] = ui.data['name'] - books[index][1] = ui.data['path'] - books[index][2] = ui.data['tags'] - books[index][3] = ui.data['notes'] - edit_book(conn, 'name', books[index][0], books[index][1]) - edit_book(conn, 'tags', ', '.join( - books[index][2]), books[index][1]) - edit_book(conn, 'notes', books[index][3], books[index][1]) + books[index][0] = ui.data["name"] + books[index][1] = ui.data["path"] + books[index][2] = ui.data["tags"] + books[index][3] = ui.data["notes"] + edit_book(conn, "name", books[index][0], books[index][1]) + edit_book(conn, "tags", ", ".join(books[index][2]), books[index][1]) + edit_book(conn, "notes", books[index][3], books[index][1]) self.show_all() if __name__ == "__main__": import sys + app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() diff --git a/book_manager/data_model.py b/book_manager/data_model.py index 9dbeaee32..d77f098c1 100644 --- a/book_manager/data_model.py +++ b/book_manager/data_model.py @@ -1,5 +1,5 @@ class Book: - """ The Class for Book Record Details """ + """The Class for Book Record Details""" def __init__(self, name, path, tags, notes): self.name = name diff --git a/broken_linkfinder/broken_linkfinder.py b/broken_linkfinder/broken_linkfinder.py index 051f502e0..58daf7626 100644 --- a/broken_linkfinder/broken_linkfinder.py +++ b/broken_linkfinder/broken_linkfinder.py @@ -1,8 +1,8 @@ -import requests import sys +from urllib.parse import urljoin, urlparse + +import requests from bs4 import BeautifulSoup -from urllib.parse import urlparse -from urllib.parse import urljoin searched_links = [] broken_links = [] @@ -11,16 +11,25 @@ def getLinksFromHTML(html): def getLink(el): return el["href"] - return list(map(getLink, BeautifulSoup(html, features="html.parser").select("a[href]"))) + + return list( + map(getLink, BeautifulSoup(html, features="html.parser").select("a[href]")) + ) def find_broken_links(domainToSearch, URL, parentURL): - if (not (URL in searched_links)) and (not URL.startswith("mailto:")) and (not ("javascript:" in URL)) and \ - (not URL.endswith(".png")) and (not URL.endswith(".jpg")) and (not URL.endswith(".jpeg")): + if ( + (not (URL in searched_links)) + and (not URL.startswith("mailto:")) + and (not ("javascript:" in URL)) + and (not URL.endswith(".png")) + and (not URL.endswith(".jpg")) + and (not URL.endswith(".jpeg")) + ): try: requestObj = requests.get(URL) searched_links.append(URL) - if (requestObj.status_code == 404): + if requestObj.status_code == 404: broken_links.append("BROKEN: link " + URL + " from " + parentURL) print(broken_links[-1]) else: diff --git a/browser_notification_sender/GUI_components.py b/browser_notification_sender/GUI_components.py index 406104e5b..a1282983b 100644 --- a/browser_notification_sender/GUI_components.py +++ b/browser_notification_sender/GUI_components.py @@ -1,4 +1,5 @@ -from tkinter import messagebox, Tk, Label, Text, Button, END +from tkinter import END, Button, Label, Text, Tk, messagebox + import sender @@ -7,7 +8,7 @@ def run(): window.title("Send Something Cool!") - window.geometry('420x200') + window.geometry("420x200") lbl = Label(window) @@ -18,14 +19,20 @@ def run(): txt.grid(column=2, row=2) def clicked(): - message = (txt.get("1.0", END)) + message = txt.get("1.0", END) sender.send(message) txt.delete("1.0", END) - messagebox.showinfo("Information", - "Your message sent successfully to all linked Devices!") + messagebox.showinfo( + "Information", "Your message sent successfully to all linked Devices!" + ) - btn = Button(window, text="Send", command=clicked, bg="lightgreen", ) + btn = Button( + window, + text="Send", + command=clicked, + bg="lightgreen", + ) btn.grid(column=2, row=4, ipadx=30, ipady=5, pady=10) diff --git a/bulk_renamer/bulk_renamer.py b/bulk_renamer/bulk_renamer.py index 5dd537a07..1868412b9 100644 --- a/bulk_renamer/bulk_renamer.py +++ b/bulk_renamer/bulk_renamer.py @@ -8,7 +8,7 @@ def add_end_slash(path): def handle_ext(filename): - if (len(filename.split(".")) > 1): + if len(filename.split(".")) > 1: return filename.split(".")[-1] else: return "" diff --git a/bulkemail_sender/main.py b/bulkemail_sender/main.py index e37e52530..a5c330399 100644 --- a/bulkemail_sender/main.py +++ b/bulkemail_sender/main.py @@ -1,17 +1,17 @@ -import pandas as pb -import smtplib import getpass +import smtplib +import pandas as pb -e = pb.read_excel('list.xlsx') -emails = e['Emails'].values +e = pb.read_excel("list.xlsx") +emails = e["Emails"].values server = smtplib.SMTP("smtp.gmail.com", 587) server.starttls() emailid = input("Enter your email id here: ") -server.login(emailid, getpass.getpass(prompt='Password: ')) +server.login(emailid, getpass.getpass(prompt="Password: ")) msg = input("Enter the body message here: ") -subject = input('Enter the subject of the message here: ') -body = 'Subject: {}\n\n{}'.format(subject, msg) +subject = input("Enter the subject of the message here: ") +body = "Subject: {}\n\n{}".format(subject, msg) for email in emails: server.sendmail(emailid, email, body) server.quit() diff --git a/caeser_cipher/caeser_cipher.py b/caeser_cipher/caeser_cipher.py index 832ad2418..4f2034a72 100644 --- a/caeser_cipher/caeser_cipher.py +++ b/caeser_cipher/caeser_cipher.py @@ -1,7 +1,8 @@ from __future__ import print_function + +import argparse import os import string -import argparse try: maketrans = string.maketrans # python2 @@ -29,14 +30,12 @@ def caeser_cipher(string_: str, offset: int, decode: bool, file_: string): lower_offset_alphabet = ( string.ascii_lowercase[offset:] + string.ascii_lowercase[:offset] ) - lower_translation_table = maketrans( - string.ascii_lowercase, lower_offset_alphabet) + lower_translation_table = maketrans(string.ascii_lowercase, lower_offset_alphabet) upper_offset_alphabet = ( string.ascii_uppercase[offset:] + string.ascii_uppercase[:offset] ) - upper_translation_table = maketrans( - string.ascii_uppercase, upper_offset_alphabet) + upper_translation_table = maketrans(string.ascii_uppercase, upper_offset_alphabet) lower_converted = string_.translate(lower_translation_table) final_converted = lower_converted.translate(upper_translation_table) @@ -57,8 +56,7 @@ def check_offset_range(value: int) -> int: """ value = int(value) if value < -25 or value > 25: - raise argparse.ArgumentTypeError( - "{} is an invalid offset".format(value)) + raise argparse.ArgumentTypeError("{} is an invalid offset".format(value)) return value @@ -85,8 +83,7 @@ def check_offset_range(value: int) -> int: ) group = parser.add_mutually_exclusive_group(required=True) - group.add_argument("-f", "--file", dest="file", - help="file to encode", default=None) + group.add_argument("-f", "--file", dest="file", help="file to encode", default=None) group.add_argument( "-s", "--string", dest="string", help="string to encode", default=None ) diff --git a/calendar/AlCalendar.py b/calendar/AlCalendar.py index 756085f3c..e6fd38e5f 100644 --- a/calendar/AlCalendar.py +++ b/calendar/AlCalendar.py @@ -1,23 +1,23 @@ -from tkinter import font, Button, X -from tkinter import Tk, Frame, SUNKEN, Label -from tkcalendar import Calendar -from datetime import datetime -from PIL import ImageTk, Image -import os import calendar +import os +from datetime import datetime +from tkinter import SUNKEN, Button, Frame, Label, Tk, X, font + +from PIL import Image, ImageTk +from tkcalendar import Calendar cwd = os.path.dirname(os.path.realpath(__file__)) -class AlCalendar(): +class AlCalendar: def __init__(self): root = Tk(className=" ALCALENDAR ") root.geometry("400x250+1500+765") root.resizable(0, 0) - root.iconbitmap(os.path.join(cwd + '\\UI\\icons', 'alcalendar.ico')) + root.iconbitmap(os.path.join(cwd + "\\UI\\icons", "alcalendar.ico")) root.config(bg="#222222") root.overrideredirect(1) - color = '#222222' + color = "#222222" def callback(event): root.geometry("500x750+1410+300") @@ -33,28 +33,46 @@ def hideScreen(): root.overrideredirect(0) root.iconify() - textHighlightFont = font.Font(family='OnePlus Sans Display', size=12) - appHighlightFont = font.Font(family='OnePlus Sans Display', size=12, - weight='bold') + textHighlightFont = font.Font(family="OnePlus Sans Display", size=12) + appHighlightFont = font.Font( + family="OnePlus Sans Display", size=12, weight="bold" + ) - titleBar = Frame(root, bg='#141414', relief=SUNKEN, bd=0) - icon = Image.open(os.path.join(cwd + '\\UI\\icons', 'alcalendar.ico')) + titleBar = Frame(root, bg="#141414", relief=SUNKEN, bd=0) + icon = Image.open(os.path.join(cwd + "\\UI\\icons", "alcalendar.ico")) icon = icon.resize((30, 30), Image.ANTIALIAS) icon = ImageTk.PhotoImage(icon) iconLabel = Label(titleBar, image=icon) iconLabel.photo = icon - iconLabel.config(bg='#141414') + iconLabel.config(bg="#141414") iconLabel.grid(row=0, column=0, sticky="nsew") - titleLabel = Label(titleBar, text='ALCALENDAR', fg='#909090', - bg='#141414', font=appHighlightFont) + titleLabel = Label( + titleBar, + text="ALCALENDAR", + fg="#909090", + bg="#141414", + font=appHighlightFont, + ) titleLabel.grid(row=0, column=1, sticky="nsew") - closeButton = Button(titleBar, text="x", bg='#141414', fg="#909090", - borderwidth=0, command=root.destroy, - font=appHighlightFont) + closeButton = Button( + titleBar, + text="x", + bg="#141414", + fg="#909090", + borderwidth=0, + command=root.destroy, + font=appHighlightFont, + ) closeButton.grid(row=0, column=3, sticky="nsew") - minimizeButton = Button(titleBar, text="-", bg='#141414', fg="#909090", - borderwidth=0, command=hideScreen, - font=appHighlightFont) + minimizeButton = Button( + titleBar, + text="-", + bg="#141414", + fg="#909090", + borderwidth=0, + command=hideScreen, + font=appHighlightFont, + ) minimizeButton.grid(row=0, column=2, sticky="nsew") titleBar.grid_columnconfigure(0, weight=1) titleBar.grid_columnconfigure(1, weight=75) @@ -65,15 +83,16 @@ def hideScreen(): now = datetime.now() weekday = now.weekday() weekdayName = calendar.day_name[weekday] - today = datetime.strftime(now, '%B %d, %Y') - fullDate = weekdayName + ', ' + today + today = datetime.strftime(now, "%B %d, %Y") + fullDate = weekdayName + ", " + today date = Label(root, text=fullDate) date.pack() date.config(bg=color, fg="white", font=textHighlightFont) - cal = Calendar(root, selectmode='day', year=now.year, month=now.month, - day=now.day) + cal = Calendar( + root, selectmode="day", year=now.year, month=now.month, day=now.day + ) cal.pack(fill=X) titleBar.bind("", callback) diff --git a/captcha_solver/csolver.py b/captcha_solver/csolver.py index 6abcb1300..e419c786c 100644 --- a/captcha_solver/csolver.py +++ b/captcha_solver/csolver.py @@ -1,6 +1,7 @@ -import pytesseract -import sys import os +import sys + +import pytesseract from PIL import Image # Set Tesseract location diff --git a/cardekho_scraper/cardekho_dynamic_data_scraping.py b/cardekho_scraper/cardekho_dynamic_data_scraping.py index bd2a8e90d..c3da99434 100644 --- a/cardekho_scraper/cardekho_dynamic_data_scraping.py +++ b/cardekho_scraper/cardekho_dynamic_data_scraping.py @@ -1,27 +1,28 @@ -''' +""" Import the necessary libraries -''' -# !pip install selenium -from selenium import webdriver +""" import time + import pandas as pd from bs4 import BeautifulSoup as soup +# !pip install selenium +from selenium import webdriver -''' +""" Define the browser/driver and open the desired webpage -''' -driver = webdriver.Chrome( - 'D:\\Softwares\\chromedriver_win32\\chromedriver.exe' -) -driver.get('https://www.cardekho.com/filter/new-cars') -''' +""" +driver = webdriver.Chrome("D:\\Softwares\\chromedriver_win32\\chromedriver.exe") +driver.get("https://www.cardekho.com/filter/new-cars") +""" Keep scrolling automatically and extract the data from the webpage and store it -''' +""" for i in range(0, 20): driver.execute_script("window.scrollTo(0, document.body.scrollHeight)") time.sleep(1) - driver.execute_script("window.scrollTo(0, \ - (document.body.scrollHeight)*0.73)") + driver.execute_script( + "window.scrollTo(0, \ + (document.body.scrollHeight)*0.73)" + ) time.sleep(1) res = driver.execute_script("return document.documentElement.outerHTML") driver.quit() @@ -56,11 +57,6 @@ else: engines.append(" ") df = pd.DataFrame( - { - 'Car Name': cars, - 'Price': prices, - 'Engine': engines, - 'Mileage': mileages - } + {"Car Name": cars, "Price": prices, "Engine": engines, "Mileage": mileages} ) -df.to_csv('carScrap.csv', index=False, encoding='utf-8') +df.to_csv("carScrap.csv", index=False, encoding="utf-8") diff --git a/certificate_generator/app/__init__.py b/certificate_generator/app/__init__.py index bab1467c2..130ff4737 100644 --- a/certificate_generator/app/__init__.py +++ b/certificate_generator/app/__init__.py @@ -1,6 +1,6 @@ from flask import Flask app = Flask(__name__) -app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 +app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0 from app import routes # noqa: E402,F401 diff --git a/certificate_generator/app/routes.py b/certificate_generator/app/routes.py index 15e083d72..4458a3986 100644 --- a/certificate_generator/app/routes.py +++ b/certificate_generator/app/routes.py @@ -1,10 +1,10 @@ # External Imports import os -from flask import render_template, request, send_file # Internal Imports from app import app from app.utils import generate_certificate +from flask import render_template, request, send_file @app.after_request @@ -15,32 +15,30 @@ def add_header(r): r.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" r.headers["Pragma"] = "no-cache" r.headers["Expires"] = "0" - r.headers['Cache-Control'] = 'public, max-age=0' + r.headers["Cache-Control"] = "public, max-age=0" return r -@app.route('/', methods=['GET', 'POST']) +@app.route("/", methods=["GET", "POST"]) def home(): - '''home + """home Renders home page - ''' + """ return render_template("certificate.html") -@app.route('/render', methods=['POST']) +@app.route("/render", methods=["POST"]) def render_certificate(): """ Get's information from user and generates the certificate using generate_certificate function """ if request.method == "POST": - file_name = generate_certificate( - request.form['name'], - request.form['pr_num']) - return render_template('download.html', file_name=file_name) + file_name = generate_certificate(request.form["name"], request.form["pr_num"]) + return render_template("download.html", file_name=file_name) -@app.route('/download_certificate', methods=['GET']) +@app.route("/download_certificate", methods=["GET"]) def download(): """ Download the generated certificate @@ -48,5 +46,6 @@ def download(): if request.method == "GET": filename = request.args.get("filename") filepath = os.path.join("static/certificates/generated", filename) - return send_file(filepath, as_attachment=True, cache_timeout=0, - attachment_filename=filename) + return send_file( + filepath, as_attachment=True, cache_timeout=0, attachment_filename=filename + ) diff --git a/certificate_generator/app/utils.py b/certificate_generator/app/utils.py index 2de02e4bb..080275a57 100644 --- a/certificate_generator/app/utils.py +++ b/certificate_generator/app/utils.py @@ -1,25 +1,24 @@ # External Imports -from PIL import Image, ImageFont, ImageDraw import os # Internal Imports from app import app +from PIL import Image, ImageDraw, ImageFont def generate_certificate(name, pr_num): - '''generate_certificate Generates certificate using base template + """generate_certificate Generates certificate using base template Args: name (string): Name to be displayed on certificate pr_num (integer): PR number to be displayed on certificate - ''' + """ # Path to template certificate template_dir = os.path.join(app.root_path, "static/certificates/template") template_filename = "template.png" # Path to save the certificate - output_dir = os.path.join(app.root_path, "static", - "certificates/generated/") + output_dir = os.path.join(app.root_path, "static", "certificates/generated/") output_filename = f"{name}.png" # Load the template file @@ -33,10 +32,10 @@ def generate_certificate(name, pr_num): contribution in #{pr_num} at {contributed_at}. """ # Load fonts - name_font = ImageFont.truetype(os.path.join( - template_dir, "Sanchez-Regular.ttf"), 150) - msg_font = ImageFont.truetype(os.path.join( - template_dir, "Sanchez-Regular.ttf"), 70) + name_font = ImageFont.truetype( + os.path.join(template_dir, "Sanchez-Regular.ttf"), 150 + ) + msg_font = ImageFont.truetype(os.path.join(template_dir, "Sanchez-Regular.ttf"), 70) # Insert text (Name) draw.text((1000, 1390), name, (51, 213, 172), font=name_font) diff --git a/cfsol_submitter/headless.py b/cfsol_submitter/headless.py index fee7aa237..a452c7282 100644 --- a/cfsol_submitter/headless.py +++ b/cfsol_submitter/headless.py @@ -1,10 +1,11 @@ -from selenium import webdriver -from selenium.webdriver.common.keys import Keys # noqa: F401 -from selenium.webdriver.common.by import By # noqa: F401 -from selenium.webdriver.chrome.options import Options # noqa: F401 import os from time import sleep +from selenium import webdriver +from selenium.webdriver.chrome.options import Options # noqa: F401 +from selenium.webdriver.common.by import By # noqa: F401 +from selenium.webdriver.common.keys import Keys # noqa: F401 + # Enter your login Credentials within the "" username = "" @@ -21,7 +22,9 @@ options.add_argument("--headless") options.headless = True options.add_argument("--window-size=1920x1080") -options.add_argument(r"C:\Users\Divyansh Mishra\AppData\Local\Google\Chrome\User Data\Default") # noqa: E501 +options.add_argument( + r"C:\Users\Divyansh Mishra\AppData\Local\Google\Chrome\User Data\Default" +) # noqa: E501 # Locating the problem: Please enter the problem code. @@ -34,7 +37,7 @@ t = len(problem) for i in range(t): - if (not problem[i].isdigit()): + if not problem[i].isdigit(): break else: part1 = part1 + problem[i] @@ -42,10 +45,10 @@ for j in range(i, t): part2 = part2 + problem[j] -st = part1 + '/' + part2 +st = part1 + "/" + part2 -print('https://codeforces.com/problemset/problem/' + st) +print("https://codeforces.com/problemset/problem/" + st) # Locating path of problem @@ -53,21 +56,25 @@ path = os.getcwd() Path = input() -path = path + '/' + Path +path = path + "/" + Path print(path) -driver = webdriver.Chrome(r'C:\Python\Chromedriver\chromedriver.exe', options=options) # noqa: E501 -driver.get('https://codeforces.com/problemset/problem/' + st) +driver = webdriver.Chrome( + r"C:\Python\Chromedriver\chromedriver.exe", options=options +) # noqa: E501 +driver.get("https://codeforces.com/problemset/problem/" + st) driver.find_element_by_xpath("//*[@id='header']/div[2]/div[2]/a[1]").click() driver.find_element_by_id("handleOrEmail").send_keys(username) driver.find_element_by_id("password").send_keys(password) -driver.find_element_by_xpath("//*[@id='enterForm']/table/tbody/tr[4]/td/div[1]/input").click() # noqa: E501 +driver.find_element_by_xpath( + "//*[@id='enterForm']/table/tbody/tr[4]/td/div[1]/input" +).click() # noqa: E501 sleep(5) # Language selection -js = "var op = document.getElementsByTagName('option'); for(var i=0;i") diff --git a/color_image_generator/AlColorImageGenerator.py b/color_image_generator/AlColorImageGenerator.py index 88f38f29f..f96795102 100644 --- a/color_image_generator/AlColorImageGenerator.py +++ b/color_image_generator/AlColorImageGenerator.py @@ -1,9 +1,10 @@ -import numpy as np -import cv2 -from tkinter import Tk, END, SUNKEN, Label, Button, Frame -from tkinter import font, filedialog, X, Text, BOTH -from PIL import ImageTk, Image import os +from tkinter import (BOTH, END, SUNKEN, Button, Frame, Label, Text, Tk, X, + filedialog, font) + +import cv2 +import numpy as np +from PIL import Image, ImageTk cwd = os.path.dirname(os.path.realpath(__file__)) @@ -13,11 +14,10 @@ def __init__(self): root = Tk(className="ALCOLORIMAGENERATOR") root.geometry("400x150+1510+865") root.resizable(0, 0) - root.iconbitmap(os.path.join(cwd + '\\UI\\icons', - 'alcolorimagegenerator.ico')) + root.iconbitmap(os.path.join(cwd + "\\UI\\icons", "alcolorimagegenerator.ico")) root.config(bg="#000000") root.overrideredirect(1) - color = '#000000' + color = "#000000" def callback(event): root.geometry("400x130+1510+885") @@ -35,31 +35,32 @@ def hideScreen(): def openImage(): imageFileEntry.delete(1.0, END) - filename = filedialog.askopenfilename(filetypes=[('Image Files', - '*.jpg *.jpeg ' - '*.bmp *.png ' - '*.webp *.tiff')] - ) + filename = filedialog.askopenfilename( + filetypes=[ + ("Image Files", "*.jpg *.jpeg " "*.bmp *.png " "*.webp *.tiff") + ] + ) imageFileEntry.insert(1.0, filename) def convert(): - net = cv2.dnn.readNetFromCaffe(cwd + '\\AlColorImageGenerator\\mod' - 'el\\colorization_deploy_v2.prototx' - 't', cwd + '\\AlColorImageGenerator' - '\\model\\colorization_release_v2.' - 'caffemodel') - pts = np.load(cwd + '\\AlColorImageGenerator\\model\\pts_in_hull.' - 'npy') + net = cv2.dnn.readNetFromCaffe( + cwd + "\\AlColorImageGenerator\\mod" + "el\\colorization_deploy_v2.prototx" + "t", + cwd + "\\AlColorImageGenerator" + "\\model\\colorization_release_v2." + "caffemodel", + ) + pts = np.load(cwd + "\\AlColorImageGenerator\\model\\pts_in_hull." "npy") class8 = net.getLayerId("class8_ab") conv8 = net.getLayerId("conv8_313_rh") pts = pts.transpose().reshape(2, 313, 1, 1) net.getLayer(class8).blobs = [pts.astype("float32")] - net.getLayer(conv8).blobs = [np.full([1, 313], 2.606, dtype='float' - '32')] + net.getLayer(conv8).blobs = [np.full([1, 313], 2.606, dtype="float" "32")] img = imageFileEntry.get("1.0", END) - img = img.replace('/', '\\')[:-1] + img = img.replace("/", "\\")[:-1] nimg = os.path.basename(img) - cimg = 'color_' + nimg + cimg = "color_" + nimg image = cv2.imread(img) scaled = image.astype("float32") / 255.0 lab = cv2.cvtColor(scaled, cv2.COLOR_BGR2LAB) @@ -74,36 +75,54 @@ def convert(): colorized = cv2.cvtColor(colorized, cv2.COLOR_LAB2BGR) colorized = np.clip(colorized, 0, 1) colorized = (255 * colorized).astype("uint8") - cimg = os.path.join(cwd + '\\AlColorImageGenerator\\images\\color', - cimg) + cimg = os.path.join(cwd + "\\AlColorImageGenerator\\images\\color", cimg) cv2.imwrite(cimg, colorized) cv2.imshow("Original", image) cv2.imshow("Colorized", colorized) cv2.waitKey(0) - textHighlightFont = font.Font(family='OnePlus Sans Display', size=12) - appHighlightFont = font.Font(family='OnePlus Sans Display', size=12, - weight='bold') + textHighlightFont = font.Font(family="OnePlus Sans Display", size=12) + appHighlightFont = font.Font( + family="OnePlus Sans Display", size=12, weight="bold" + ) - titleBar = Frame(root, bg='#141414', relief=SUNKEN, bd=0) - icon = Image.open(os.path.join(cwd + '\\UI\\icons', - 'alcolorimagegenerator.ico')) + titleBar = Frame(root, bg="#141414", relief=SUNKEN, bd=0) + icon = Image.open( + os.path.join(cwd + "\\UI\\icons", "alcolorimagegenerator.ico") + ) icon = icon.resize((30, 30), Image.ANTIALIAS) icon = ImageTk.PhotoImage(icon) iconLabel = Label(titleBar, image=icon) iconLabel.photo = icon - iconLabel.config(bg='#141414') + iconLabel.config(bg="#141414") iconLabel.grid(row=0, column=0, sticky="nsew") - titleLabel = Label(titleBar, text='ALCOLORIMAGEGENERATOR', - fg='#909090', bg='#141414', font=appHighlightFont) + titleLabel = Label( + titleBar, + text="ALCOLORIMAGEGENERATOR", + fg="#909090", + bg="#141414", + font=appHighlightFont, + ) titleLabel.grid(row=0, column=1, sticky="nsew") - closeButton = Button(titleBar, text="x", bg='#141414', fg="#909090", - borderwidth=0, command=root.destroy, - font=appHighlightFont) + closeButton = Button( + titleBar, + text="x", + bg="#141414", + fg="#909090", + borderwidth=0, + command=root.destroy, + font=appHighlightFont, + ) closeButton.grid(row=0, column=3, sticky="nsew") - minimizeButton = Button(titleBar, text="-", bg='#141414', fg="#909090", - borderwidth=0, command=hideScreen, - font=appHighlightFont) + minimizeButton = Button( + titleBar, + text="-", + bg="#141414", + fg="#909090", + borderwidth=0, + command=hideScreen, + font=appHighlightFont, + ) minimizeButton.grid(row=0, column=2, sticky="nsew") titleBar.grid_columnconfigure(0, weight=1) titleBar.grid_columnconfigure(1, weight=20) @@ -111,18 +130,35 @@ def convert(): titleBar.grid_columnconfigure(3, weight=1) titleBar.pack(fill=X) - imageFile = Button(root, text="IMAGE TO BE COVERTED", borderwidth=0, - highlightthickness=3, command=openImage) + imageFile = Button( + root, + text="IMAGE TO BE COVERTED", + borderwidth=0, + highlightthickness=3, + command=openImage, + ) imageFile.pack(fill=X) imageFile.config(bg=color, fg="white", font=appHighlightFont) - imageFileEntry = Text(root, bg="white", fg=color, - highlightbackground=color, highlightcolor=color, - highlightthickness=3, bd=0, - font=textHighlightFont, height=1) + imageFileEntry = Text( + root, + bg="white", + fg=color, + highlightbackground=color, + highlightcolor=color, + highlightthickness=3, + bd=0, + font=textHighlightFont, + height=1, + ) imageFileEntry.pack(fill=BOTH, expand=True) - convert = Button(root, borderwidth=0, highlightthickness=5, - text="CONVERT IMAGE", command=convert) + convert = Button( + root, + borderwidth=0, + highlightthickness=5, + text="CONVERT IMAGE", + command=convert, + ) convert.config(bg=color, fg="white", font=appHighlightFont) convert.pack(fill=X) diff --git a/colorimage_bw/colour_to_bw.py b/colorimage_bw/colour_to_bw.py index fd744d262..4712da0f9 100644 --- a/colorimage_bw/colour_to_bw.py +++ b/colorimage_bw/colour_to_bw.py @@ -2,11 +2,11 @@ def colour_to_bw(original_image_path, output_path): - ''' + """ Function to convert colour image to black and white - ''' + """ original_image = cv2.imread(original_image_path) gray_img = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY) thresh = 128 img_bw = cv2.threshold(gray_img, thresh, 255, cv2.THRESH_BINARY)[1] - cv2.imwrite(output_path + 'final_image.png', img_bw) + cv2.imwrite(output_path + "final_image.png", img_bw) diff --git a/compare_img/compare_img.py b/compare_img/compare_img.py index d936142fd..db3060e8a 100644 --- a/compare_img/compare_img.py +++ b/compare_img/compare_img.py @@ -1,4 +1,5 @@ import sys + import cv2 import numpy as np from skimage import io diff --git a/competitive_calendar/main.py b/competitive_calendar/main.py index 8e61751cf..1d2fcf944 100644 --- a/competitive_calendar/main.py +++ b/competitive_calendar/main.py @@ -1,15 +1,12 @@ -from utils import printCalendar import argparse +from utils import printCalendar + parser = argparse.ArgumentParser( - description='Get a list of all competitive programming contests happening on various sites.' + description="Get a list of all competitive programming contests happening on various sites." ) -parser.add_argument( - '--today', - action='store_true', - help='Print only today\'s contests' -) +parser.add_argument("--today", action="store_true", help="Print only today's contests") args = vars(parser.parse_args()) today = args["today"] diff --git a/competitive_calendar/utils.py b/competitive_calendar/utils.py index 7f04bce5e..581db229f 100644 --- a/competitive_calendar/utils.py +++ b/competitive_calendar/utils.py @@ -1,13 +1,14 @@ from datetime import datetime, timedelta -from dateutil import tz + import requests +from dateutil import tz def get_datetime(utc_time): """ Convert date string to datetime object """ - utc = datetime.strptime(utc_time, '%Y-%m-%dT%H:%M:%S.%fZ') + utc = datetime.strptime(utc_time, "%Y-%m-%dT%H:%M:%S.%fZ") return utc @@ -21,7 +22,7 @@ def get_local_timestamp(utc, from_zone=None): to_zone = tz.tzlocal() # Auto-detect zone utc = utc.replace(tzinfo=from_zone) - local_time = utc.astimezone(to_zone) # Convert time zone + local_time = utc.astimezone(to_zone) # Convert time zone return local_time @@ -39,29 +40,27 @@ def getContests(today=False): Returns fetched contests in desired day-wise format """ TOMORROW = get_local_timestamp( - (datetime.today() + timedelta(days=1)) - .replace(hour=0, minute=0, second=0, microsecond=0), - from_zone=tz.tzlocal() + (datetime.today() + timedelta(days=1)).replace( + hour=0, minute=0, second=0, microsecond=0 + ), + from_zone=tz.tzlocal(), ) contests = fetchContests() calendar = {} for contest in contests: - local_start_time = get_local_timestamp( - get_datetime(contest["start_time"])) + local_start_time = get_local_timestamp(get_datetime(contest["start_time"])) local_end_time = get_local_timestamp(get_datetime(contest["end_time"])) - contest["start_time"] = local_start_time.strftime( - "%I:%M %p, %d %b '%y") - contest["end_time"] = local_end_time.strftime( - "%I:%M %p, %d %b '%y") + contest["start_time"] = local_start_time.strftime("%I:%M %p, %d %b '%y") + contest["end_time"] = local_end_time.strftime("%I:%M %p, %d %b '%y") if local_end_time <= TOMORROW: # If contest has already ended, skip continue elif local_start_time <= TOMORROW and local_end_time > TOMORROW: # If contest is open today key = "Today ({})".format(datetime.today().strftime("%d %b '%y")) - else: # Future contests + else: # Future contests if today: return calendar key = local_start_time.strftime("%d %B, %Y") diff --git a/connect_strongest_wifi/connect_strongest_wifi.py b/connect_strongest_wifi/connect_strongest_wifi.py index 2c4a724d1..edee403ad 100644 --- a/connect_strongest_wifi/connect_strongest_wifi.py +++ b/connect_strongest_wifi/connect_strongest_wifi.py @@ -1,9 +1,8 @@ -import subprocess import getpass +import subprocess import time -from pywifi import PyWiFi -from pywifi import const -from pywifi import Profile + +from pywifi import Profile, PyWiFi, const def connect_wifi(ssid, password): @@ -36,9 +35,10 @@ def get_available_wifi(): try: - cmd = ['netsh', 'wlan', 'show', 'network', 'mode=Bssid'] - wifidata = subprocess.check_output(cmd).decode( - 'ascii').replace("\r", "").split("\n\n") + cmd = ["netsh", "wlan", "show", "network", "mode=Bssid"] + wifidata = ( + subprocess.check_output(cmd).decode("ascii").replace("\r", "").split("\n\n") + ) except subprocess.CalledProcessError: print("\nWhoops! Your Wi-Fi seems to be powered off.") @@ -53,7 +53,7 @@ def get_available_wifi(): networks.append((ssid, signal)) networks = sorted(networks, reverse=True, key=lambda x: x[1]) - return (networks) + return networks def main(): diff --git a/copy_to_clipboard/copy_to_clipboard.py b/copy_to_clipboard/copy_to_clipboard.py index b365c94b8..1f7612763 100644 --- a/copy_to_clipboard/copy_to_clipboard.py +++ b/copy_to_clipboard/copy_to_clipboard.py @@ -1,7 +1,7 @@ import os -import sys import platform import subprocess +import sys # Seeing if the file exists if os.path.exists(sys.argv[1]): diff --git a/corona_tracker/global.py b/corona_tracker/global.py index a12c97ce3..6abd8beb6 100755 --- a/corona_tracker/global.py +++ b/corona_tracker/global.py @@ -6,8 +6,9 @@ @author: edoardottt """ -import requests import time + +import requests from bs4 import BeautifulSoup url = "https://worldometers.info/coronavirus/" diff --git a/corona_tracker/italy.py b/corona_tracker/italy.py index 0e6eb7fca..7b8a4cb25 100755 --- a/corona_tracker/italy.py +++ b/corona_tracker/italy.py @@ -7,11 +7,12 @@ https://edoardoottavianelli.it """ import csv -import requests -import socket import getopt +import socket import sys +import requests + CSV_URL = "https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/\ dpc-covid19-ita-andamento-nazionale.csv" data = [] diff --git a/corona_tracker_visualizer/corona_tracker.py b/corona_tracker_visualizer/corona_tracker.py index 8016eec17..deea280c2 100644 --- a/corona_tracker_visualizer/corona_tracker.py +++ b/corona_tracker_visualizer/corona_tracker.py @@ -1,19 +1,17 @@ import json -import requests -from pandas import DataFrame -from matplotlib import pyplot as plt -from matplotlib.backends.backend_tkagg import ( - FigureCanvasTkAgg, -) -from matplotlib.figure import Figure +import textwrap as tw import tkinter as tk from tkinter import messagebox + import numpy as np +import requests from bs4 import BeautifulSoup -import textwrap as tw +from matplotlib import pyplot as plt +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg +from matplotlib.figure import Figure +from pandas import DataFrame from selenium import webdriver - frame_stat = None frame_data = None button_show = None @@ -27,10 +25,10 @@ def call_browser(arg): """opening pages on browser using selenium""" browser = webdriver.Chrome(executable_path="./chromedriver.exe") - if arg == '1': + if arg == "1": browser.get("https://www.who.int/") - if arg == '2': + if arg == "2": browser.get("https://sandipandas898.wixsite.com/sandipandas") @@ -64,28 +62,19 @@ def get_chart(country): print("Reading done") try: - if country == '': + if country == "": return df = DataFrame(info[country]) - df.to_csv('corona_timeseries.csv') - plt.rcParams.update({'font.size': 8}) + df.to_csv("corona_timeseries.csv") + plt.rcParams.update({"font.size": 8}) figure = Figure(figsize=(5, 5), dpi=90) subplot = figure.add_subplot(111) - subplot.plot( - df['date'], df['confirmed'], - label='confirmed', color='blue' - ) - subplot.plot( - df['date'], df['deaths'], - label='deaths', color='red' - ) - subplot.plot( - df['date'], df['recovered'], - label='recovered', color='green' - ) - subplot.legend(loc='upper left') + subplot.plot(df["date"], df["confirmed"], label="confirmed", color="blue") + subplot.plot(df["date"], df["deaths"], label="deaths", color="red") + subplot.plot(df["date"], df["recovered"], label="recovered", color="green") + subplot.legend(loc="upper left") start, end = subplot.get_xlim() subplot.xaxis.set_ticks(np.arange(start, end, 45)) @@ -96,8 +85,7 @@ def get_chart(country): canvas = FigureCanvasTkAgg(figure, master=frame_stat) canvas.get_tk_widget().grid( - row=4, column=0, columnspan=3, - sticky="wen", padx=20, pady=5 + row=4, column=0, columnspan=3, sticky="wen", padx=20, pady=5 ) plt.show() @@ -114,10 +102,10 @@ def scrape_data(): response = requests.get("https://www.worldometers.info/coronavirus/") data = BeautifulSoup(response.content, "html.parser") - data_table = data.find('table', id="main_table_countries_today") + data_table = data.find("table", id="main_table_countries_today") # data_title = data_table.find('thead').text - data_info = data_table.find('tbody').find_all('tr') + data_info = data_table.find("tbody").find_all("tr") country = [] total_cases = [] @@ -129,7 +117,7 @@ def scrape_data(): continent = [] for i in range(len(data_info)): - country_data = data_info[i].find_all('td') + country_data = data_info[i].find_all("td") country.append(country_data[1].text) total_cases.append(country_data[2].text) new_cases.append(country_data[3].text) @@ -150,61 +138,75 @@ def scrape_data(): continent = continent[8:] return ( - totals, country, - total_cases, new_cases, - total_deaths, new_deaths, - total_recovered, active_cases, - continent + totals, + country, + total_cases, + new_cases, + total_deaths, + new_deaths, + total_recovered, + active_cases, + continent, ) def put_data_to_ui(): """put data on the interface to show""" - (totals, country, total_cases, new_cases, total_deaths, - new_deaths, total_recovered, active_cases, - continent) = scrape_data() + ( + totals, + country, + total_cases, + new_cases, + total_deaths, + new_deaths, + total_recovered, + active_cases, + continent, + ) = scrape_data() frame_total = tk.Frame(frame_data, bg="#6197ed") frame_total.grid(row=0, column=0, sticky="we", padx=3) main_title1 = tk.Label( - frame_total, font=( - "Times New Roman", 18, "bold" - ), bg="#6197ed", fg="#000000", - text="World Corona Dashboard" + frame_total, + font=("Times New Roman", 18, "bold"), + bg="#6197ed", + fg="#000000", + text="World Corona Dashboard", ) main_title1.grid(row=0, column=1, sticky="we", pady=10) main_title2 = tk.Label( - frame_total, font=( - "Times New Roman", 12, "italic" - ), bg="#6197ed", fg="#000000", - text="get real time update of COVID-19 cases" + frame_total, + font=("Times New Roman", 12, "italic"), + bg="#6197ed", + fg="#000000", + text="get real time update of COVID-19 cases", ) main_title2.grid(row=1, column=1, sticky="we") confirmed_label = tk.Label( - frame_total, font=( - "Times New Roman", 12, "bold" - ), bg="#5a54f7", fg="#000000", - text="Total Confirmed\n" + str(totals[0]) - ) - confirmed_label.grid( - row=2, column=0, sticky="we", ipadx=65, ipady=5, pady=12 + frame_total, + font=("Times New Roman", 12, "bold"), + bg="#5a54f7", + fg="#000000", + text="Total Confirmed\n" + str(totals[0]), ) + confirmed_label.grid(row=2, column=0, sticky="we", ipadx=65, ipady=5, pady=12) recovered_label = tk.Label( - frame_total, font=( - "Times New Roman", 12, "bold" - ), - bg="#73fa8e", fg="#000000", - text="Recovered\n" + str(totals[1]) + frame_total, + font=("Times New Roman", 12, "bold"), + bg="#73fa8e", + fg="#000000", + text="Recovered\n" + str(totals[1]), ) recovered_label.grid(row=2, column=1, sticky="we", ipadx=21, ipady=5) death_label = tk.Label( - frame_total, font=( - "Times New Roman", 12, "bold" - ), bg="#f25a49", fg="#000000", - text="Death\n" + str(totals[2]) + frame_total, + font=("Times New Roman", 12, "bold"), + bg="#f25a49", + fg="#000000", + text="Death\n" + str(totals[2]), ) death_label.grid(row=2, column=2, sticky="we", ipadx=100, ipady=5) @@ -212,45 +214,76 @@ def put_data_to_ui(): frame_title.grid(row=1, column=0, sticky="n", pady=3) title_label_c = tk.Label( - frame_title, borderwidth=2, relief="solid", bg="#ff8317", + frame_title, + borderwidth=2, + relief="solid", + bg="#ff8317", fg="#000000", - font=("Times New Roman", 12, "bold"), text="Counry" + font=("Times New Roman", 12, "bold"), + text="Counry", ) title_label_tc = tk.Label( - frame_title, borderwidth=2, relief="solid", bg="#ff8317", + frame_title, + borderwidth=2, + relief="solid", + bg="#ff8317", fg="#000000", - font=("Times New Roman", 12, "bold"), text="Total \nCases" + font=("Times New Roman", 12, "bold"), + text="Total \nCases", ) title_label_nc = tk.Label( - frame_title, borderwidth=2, relief="solid", bg="#ff8317", + frame_title, + borderwidth=2, + relief="solid", + bg="#ff8317", fg="#000000", - font=("Times New Roman", 12, "bold"), text="New \nCases" + font=("Times New Roman", 12, "bold"), + text="New \nCases", ) title_label_td = tk.Label( - frame_title, borderwidth=2, relief="solid", bg="#ff8317", + frame_title, + borderwidth=2, + relief="solid", + bg="#ff8317", fg="#000000", - font=("Times New Roman", 12, "bold"), text="Total \nDeaths" + font=("Times New Roman", 12, "bold"), + text="Total \nDeaths", ) title_label_nd = tk.Label( - frame_title, borderwidth=2, relief="solid", bg="#ff8317", + frame_title, + borderwidth=2, + relief="solid", + bg="#ff8317", fg="#000000", - font=("Times New Roman", 12, "bold"), text="New \nDeaths" + font=("Times New Roman", 12, "bold"), + text="New \nDeaths", ) title_label_tr = tk.Label( - frame_title, borderwidth=2, relief="solid", bg="#ff8317", + frame_title, + borderwidth=2, + relief="solid", + bg="#ff8317", fg="#000000", - font=("Times New Roman", 12, "bold"), text="Total \nRecovered" + font=("Times New Roman", 12, "bold"), + text="Total \nRecovered", ) title_label_ac = tk.Label( - frame_title, borderwidth=2, relief="solid", bg="#ff8317", + frame_title, + borderwidth=2, + relief="solid", + bg="#ff8317", fg="#000000", - font=("Times New Roman", 12, "bold"), text="Active \nCases" + font=("Times New Roman", 12, "bold"), + text="Active \nCases", ) title_label_con = tk.Label( - frame_title, borderwidth=2, relief="solid", - bg="#ff8317", fg="#000000", + frame_title, + borderwidth=2, + relief="solid", + bg="#ff8317", + fg="#000000", font=("Times New Roman", 12, "bold"), - text="Continent" + text="Continent", ) title_label_c.grid(row=0, column=0, padx=1, pady=1, ipadx=24, ipady=10) @@ -268,66 +301,63 @@ def put_data_to_ui(): scrollable_frame = tk.Frame(canvas, bg="#f5c167") - scrollbar = tk.Scrollbar( - frame_data, orient="vertical", command=canvas.yview - ) + scrollbar = tk.Scrollbar(frame_data, orient="vertical", command=canvas.yview) scrollbar.grid(row=2, column=1, sticky="e", ipady=200, ipadx=3) canvas.configure(yscrollcommand=scrollbar.set) canvas.create_window((0, 0), window=scrollable_frame) scrollable_frame.bind( - "", - lambda e: canvas.configure(scrollregion=canvas.bbox("all")) + "", lambda e: canvas.configure(scrollregion=canvas.bbox("all")) ) for i in range(len(country)): data_label1 = tk.Label( - scrollable_frame, fg="#000000", - bg="#f5c167", text=tw.fill(country[i], width=12) + scrollable_frame, + fg="#000000", + bg="#f5c167", + text=tw.fill(country[i], width=12), ) data_label1.grid(row=i, column=0, sticky="ew", padx=(5, 0)) data_label2 = tk.Label( - scrollable_frame, fg="#000000", - bg="#f5c167", text=total_cases[i] + scrollable_frame, fg="#000000", bg="#f5c167", text=total_cases[i] ) data_label2.grid(row=i, column=1, sticky="ew", padx=(17, 18)) data_label3 = tk.Label( - scrollable_frame, fg="#000000", - bg="#f5c167", text=new_cases[i] + scrollable_frame, fg="#000000", bg="#f5c167", text=new_cases[i] ) data_label3.grid(row=i, column=2, sticky="ew", padx=(15, 15)) data_label4 = tk.Label( - scrollable_frame, fg="#000000", - bg="#f5c167", text=total_deaths[i] + scrollable_frame, fg="#000000", bg="#f5c167", text=total_deaths[i] ) data_label4.grid(row=i, column=3, sticky="ew", padx=(24, 20)) data_label5 = tk.Label( - scrollable_frame, fg="#000000", - bg="#f5c167", text=new_deaths[i] + scrollable_frame, fg="#000000", bg="#f5c167", text=new_deaths[i] ) data_label5.grid(row=i, column=4, sticky="ew", padx=(18, 25)) data_label6 = tk.Label( - scrollable_frame, fg="#000000", - bg="#f5c167", text=total_recovered[i] + scrollable_frame, fg="#000000", bg="#f5c167", text=total_recovered[i] ) data_label6.grid(row=i, column=5, sticky="ew", padx=(20, 30)) data_label7 = tk.Label( - scrollable_frame, fg="#000000", - bg="#f5c167", text=active_cases[i] + scrollable_frame, fg="#000000", bg="#f5c167", text=active_cases[i] ) data_label7.grid(row=i, column=6, sticky="ew", padx=(10, 13)) data_label8 = tk.Label( - scrollable_frame, fg="#000000", - bg="#f5c167", font=("Helvetica", 9, "italic"), text=continent[i] + scrollable_frame, + fg="#000000", + bg="#f5c167", + font=("Helvetica", 9, "italic"), + text=continent[i], ) data_label8.grid(row=i, column=7, sticky="ew", padx=(0, 0)) refresh_btn = tk.Button( - frame_data, text="Update Data", - font=( - "Helvetica", 12, "bold" - ), fg="#000000", command=refresh + frame_data, + text="Update Data", + font=("Helvetica", 12, "bold"), + fg="#000000", + command=refresh, ) refresh_btn.grid(row=3, column=0, sticky="ew", padx=250) @@ -358,58 +388,56 @@ def main_ui(): frame_stat = tk.Frame(root, bg="#e3c1f7") frame_stat.grid( - row=0, column=1, sticky="ens", - ipady=screen_height, ipadx=screen_width + row=0, column=1, sticky="ens", ipady=screen_height, ipadx=screen_width ) visit_btn1 = tk.Button( - frame_stat, text="Visit developer's site", bg="#fcaccd", - font=("Helvetica", 11, "bold"), relief="flat", - fg="#000000", command=lambda: call_browser(2) + frame_stat, + text="Visit developer's site", + bg="#fcaccd", + font=("Helvetica", 11, "bold"), + relief="flat", + fg="#000000", + command=lambda: call_browser(2), ) visit_btn1.grid( - row=0, column=0, ipady=3, ipadx=5, pady=(60, 5), - padx=(20, 5), sticky="w" + row=0, column=0, ipady=3, ipadx=5, pady=(60, 5), padx=(20, 5), sticky="w" ) visit_btn2 = tk.Button( - frame_stat, text="Visit WHO's official site", bg="#fcaccd", - font=("Helvetica", 11, "bold"), fg="#000000", - relief="flat", command=lambda: call_browser(1) - ) - visit_btn2.grid( - row=0, column=1, ipady=3, ipadx=5, - pady=(60, 5), padx=5, sticky="w" + frame_stat, + text="Visit WHO's official site", + bg="#fcaccd", + font=("Helvetica", 11, "bold"), + fg="#000000", + relief="flat", + command=lambda: call_browser(1), ) + visit_btn2.grid(row=0, column=1, ipady=3, ipadx=5, pady=(60, 5), padx=5, sticky="w") show_label = tk.Label( - frame_stat, text="Enter Country name to show the growth Trend", - font=("Helvetica", 11, "italic"), bg="#e3c1f7", fg="#000000" - ) - show_label.grid( - row=2, column=0, padx=20, pady=(18, 5), - columnspan=5, sticky="w" + frame_stat, + text="Enter Country name to show the growth Trend", + font=("Helvetica", 11, "italic"), + bg="#e3c1f7", + fg="#000000", ) + show_label.grid(row=2, column=0, padx=20, pady=(18, 5), columnspan=5, sticky="w") name = tk.StringVar() entry = tk.Entry( - frame_stat, width=15, textvariable=name, - font=("Helvetica", 12, "bold") - ) - entry.grid( - column=0, row=3, padx=(20, 5), - pady=5, ipady=5, sticky="w" + frame_stat, width=15, textvariable=name, font=("Helvetica", 12, "bold") ) + entry.grid(column=0, row=3, padx=(20, 5), pady=5, ipady=5, sticky="w") button = tk.Button( - frame_stat, text="Show Trend", - font=("Helvetica", 11, "bold"), fg="#000000", - command=lambda: get_chart(name.get()) - ) - button.grid( - column=1, row=3, pady=5, ipadx=3, - ipady=2, sticky="w" + frame_stat, + text="Show Trend", + font=("Helvetica", 11, "bold"), + fg="#000000", + command=lambda: get_chart(name.get()), ) + button.grid(column=1, row=3, pady=5, ipadx=3, ipady=2, sticky="w") put_data_to_ui() diff --git a/covid19_telegram_bot/covid19_telegram_bot.py b/covid19_telegram_bot/covid19_telegram_bot.py index 7213794f9..3075ca854 100644 --- a/covid19_telegram_bot/covid19_telegram_bot.py +++ b/covid19_telegram_bot/covid19_telegram_bot.py @@ -13,9 +13,10 @@ def send_msg(text): token = "YOUR-TOKEN-HERE" chat_id = "GROUP-CHAT-ID-HERE" url_req = ( - 'https://api.telegram.org/' - 'bot' + token + '/sendMessage' + '?chat_id' - '=' + chat_id + "&text=" + text) + "https://api.telegram.org/" + "bot" + token + "/sendMessage" + "?chat_id" + "=" + chat_id + "&text=" + text + ) results = requests.get(url_req) print(results.json()) diff --git a/cpu_tempreature/main.py b/cpu_tempreature/main.py index dcf3a7569..782a682d0 100644 --- a/cpu_tempreature/main.py +++ b/cpu_tempreature/main.py @@ -1,6 +1,6 @@ +import getopt import os import sys -import getopt def rtcheck(seconds): @@ -14,8 +14,7 @@ def rtcheck(seconds): def usageinfo(check, run, exitmsg): print("Usage information:\n") print("-h / --help\t\tDisplay this usage info.") - print( - "-s / --seconds [seconds]\tRun cputemp for specified number of seconds") + print("-s / --seconds [seconds]\tRun cputemp for specified number of seconds") print("-C / --celsius\t\tDisplay temperature in Celsius") print("-F / --fahrenheit\t\tDisplay temperature in Fahrenheit") print("-K / --kelvin\t\tDisplay temperature in Kelvin") @@ -27,7 +26,9 @@ def usageinfo(check, run, exitmsg): def hwcheck(): - if os.path.exists("/sys/devices/LNXSYSTM:00/LNXTHERM:00/LNXTHERM:01/thermal_zone/temp"): + if os.path.exists( + "/sys/devices/LNXSYSTM:00/LNXTHERM:00/LNXTHERM:01/thermal_zone/temp" + ): return 4 elif os.path.exists("/sys/bus/acpi/devices/LNXTHERM:00/thermal_zone/temp"): @@ -61,20 +62,43 @@ def getDegree(): def getTemp(hardware): if hardware == 1: - temp = open("/proc/acpi/thermal_zone/THM0/temperature").read( - ).strip().lstrip('temperature :').rstrip(' C') + temp = ( + open("/proc/acpi/thermal_zone/THM0/temperature") + .read() + .strip() + .lstrip("temperature :") + .rstrip(" C") + ) elif hardware == 2: - temp = open("/proc/acpi/thermal_zone/THRM/temperature").read( - ).strip().lstrip('temperature :').rstrip(' C') + temp = ( + open("/proc/acpi/thermal_zone/THRM/temperature") + .read() + .strip() + .lstrip("temperature :") + .rstrip(" C") + ) elif hardware == 3: - temp = open("/proc/acpi/thermal_zone/THR1/temperature").read( - ).strip().lstrip('temperature :').rstrip(' C') + temp = ( + open("/proc/acpi/thermal_zone/THR1/temperature") + .read() + .strip() + .lstrip("temperature :") + .rstrip(" C") + ) elif hardware == 4: - temp = open( - "/sys/devices/LNXSYSTM:00/LNXTHERM:00/LNXTHERM:01/thermal_zone/temp").read().strip().rstrip('000') + temp = ( + open("/sys/devices/LNXSYSTM:00/LNXTHERM:00/LNXTHERM:01/thermal_zone/temp") + .read() + .strip() + .rstrip("000") + ) elif hardware == 5: - temp = open( - "/sys/bus/acpi/devices/LNXTHERM:00/thermal_zone/temp").read().strip().rstrip('000') + temp = ( + open("/sys/bus/acpi/devices/LNXTHERM:00/thermal_zone/temp") + .read() + .strip() + .rstrip("000") + ) temp = str(float(temp) / 10.0) else: return 0 @@ -82,12 +106,12 @@ def getTemp(hardware): def dispTemp(temp, degree, minutes, seconds): - print("\rCPU Temperature: ", temp, degree, end=' ') - print("(Time Running: ", minutes, ":", end=' ') + print("\rCPU Temperature: ", temp, degree, end=" ") + print("(Time Running: ", minutes, ":", end=" ") if seconds < 10: - print("0" + str(seconds), ")", end=' ') + print("0" + str(seconds), ")", end=" ") else: - print(seconds, ")", end=' ') + print(seconds, ")", end=" ") def convertDegree(degree, temp): @@ -117,8 +141,19 @@ def main(): ticker = 0 exitmsg = "" try: - opts, args = getopt.getopt(sys.argv[1:], "aCFKs:hV", [ - "average", "celsius", "kelvin", "fahrenheit", "seconds=", "help", "version"]) + opts, args = getopt.getopt( + sys.argv[1:], + "aCFKs:hV", + [ + "average", + "celsius", + "kelvin", + "fahrenheit", + "seconds=", + "help", + "version", + ], + ) except getopt.GetoptError: help = 1 check = 1 @@ -163,6 +198,7 @@ def main(): degree = getDegree() import datetime import time + prevtemp = 21 tmax = 0 tmin = 1000 @@ -206,12 +242,12 @@ def main(): tavg = tsum / ticker tavg = round(tavg, 1) if avg == 0: - print("\n\nHighest recorded temperature was", - tmax, "degrees", degree, ".") + print("\n\nHighest recorded temperature was", tmax, "degrees", degree, ".") print("Lowest recorded temperature was", tmin, "degrees", degree, ".") print("Average temperature was", tavg, "degrees", degree, ".\n") import os + if avg == 1: return 0 elif os.path.exists("/var/log/cputemp.log") and avg == 0: @@ -251,5 +287,5 @@ def main(): return 1 -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/create_zip/zip.py b/create_zip/zip.py index 62a9de1ef..96bcf1f4d 100644 --- a/create_zip/zip.py +++ b/create_zip/zip.py @@ -1,14 +1,15 @@ +import argparse import os import zipfile -import argparse def cli_parse(): - cli = argparse.ArgumentParser(prog='zip creator', - description='Basic automation script for \ - creating zip file from a folder') - cli.add_argument("folder", metavar='Folder', - type=str, help="Path to folder") + cli = argparse.ArgumentParser( + prog="zip creator", + description="Basic automation script for \ + creating zip file from a folder", + ) + cli.add_argument("folder", metavar="Folder", type=str, help="Path to folder") cli.add_argument("-o", "--output", type=str, help="Output file path") return cli.parse_args() @@ -23,19 +24,20 @@ def zipdir(path, ziph): for root, dirs, files in os.walk(path): print(root, dirs, files, path) for file in files: - ziph.write(os.path.join(root, file), - os.path.relpath(os.path.join(root, file), - os.path.join(path, '..'))) + ziph.write( + os.path.join(root, file), + os.path.relpath(os.path.join(root, file), os.path.join(path, "..")), + ) # print(output) if not output: output = os.path.basename(folder) -if not output.lower().endswith('.zip'): +if not output.lower().endswith(".zip"): output += ".zip" -zipf = zipfile.ZipFile(output, 'w', zipfile.ZIP_DEFLATED) +zipf = zipfile.ZipFile(output, "w", zipfile.ZIP_DEFLATED) zipdir(folder, zipf) zipf.close() diff --git a/credit_card_generator/cc_generate.py b/credit_card_generator/cc_generate.py index 800651bbe..2ffa05a2f 100644 --- a/credit_card_generator/cc_generate.py +++ b/credit_card_generator/cc_generate.py @@ -1,145 +1,179 @@ # flake8: noqa -import sys import random +import sys + def digits_of(number): - return [int(i) for i in str(number)] + return [int(i) for i in str(number)] + def checksum_luhn(card_number): - digits = digits_of(card_number) - odd_digits = digits[-1::-2] # From right - even_digits = digits[-2::-2] # From right - total = sum(odd_digits) - for digit in even_digits: - total += sum(digits_of(2 * digit)) - return total % 10 + digits = digits_of(card_number) + odd_digits = digits[-1::-2] # From right + even_digits = digits[-2::-2] # From right + total = sum(odd_digits) + for digit in even_digits: + total += sum(digits_of(2 * digit)) + return total % 10 + def is_valid(card_number): - return checksum_luhn(card_number) == 0 - -cc = ["Visa card" , "American Express card" , "Diners Club Carte Blanche" , "Mastercard card" , "Discover card" ] - -def fill_cc(ll , t_rn ): - for i in range(t_rn): - app = random.randrange(0, 10, 1) - ll.append(app) - # method to find check sum for random numbers - even = ll[-1::-2] # From right - odd = ll[-2::-2] # From right - # doubling the even nd adding unit and tens place - even2 = [] - for i in even: - even2.append(sum(digits_of(i * 2))) - even2 = sum(even2) - odd = sum(odd) - check_sum = odd + even2 - if (check_sum % 10 == 0): - ll.append(0) - else: - modl = check_sum % 10 - ll.append(10 - modl) - - # ll contains valid numbers now so printing it - res = str("".join(map(str, ll))) - res = '' - for i in ll: - res += str(i) - - if(is_valid(res)): - print(res) - else: - print("!ERRORRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR") - - -def print_cc ( ccn , cca ): - - while(cca != 0): - - ccs = [] - if (ccn==1): # we have two cases for visa - ccs.append(13) - ccs.append(16) - if ( ccn == 4 or ccn == 5 ): - ccs.append(16) - if(ccn == 2): - ccs.append(15) - if(ccn == 3): - ccs.append(14) - - ll = [] # it will store-up the cc numbers - fin_size = random.choice(ccs) # for visa we will choose 13 or 16 randomly - if(ccn==1): #VISA - ll.append(4) - t_rn = fin_size -2 - fill_cc(ll , t_rn) - cca-=1 - - elif (ccn == 2): # AMEX - ll.append(3) - second_dig = [4 , 7] - second_dig = random.choice(second_dig) - ll.append(second_dig) - t_rn = fin_size - 3 - fill_cc(ll, t_rn) - cca -= 1 - - elif (ccn == 3): # diner club carte blanche - ll.append(3) - ll.append(0) - third_dig = [0,1,2,3,4,5] - third_dig = random.choice(third_dig) - ll.append(third_dig) - t_rn = fin_size - 4 - fill_cc(ll, t_rn) - cca -= 1 - - elif (ccn == 4): # master - ll.append(5) - second_dig = [1,2,3,4,5] - second_dig = random.choice(second_dig) - ll.append(second_dig) - t_rn = fin_size - 3 - fill_cc(ll, t_rn) - cca -= 1 - - elif (ccn == 5): # discover - ll.append(6) - ll.append(0) - ll.append(1) - ll.append(1) - t_rn = fin_size - 5 - fill_cc(ll, t_rn) - cca -= 1 + return checksum_luhn(card_number) == 0 + + +cc = [ + "Visa card", + "American Express card", + "Diners Club Carte Blanche", + "Mastercard card", + "Discover card", +] + + +def fill_cc(ll, t_rn): + for i in range(t_rn): + app = random.randrange(0, 10, 1) + ll.append(app) + # method to find check sum for random numbers + even = ll[-1::-2] # From right + odd = ll[-2::-2] # From right + # doubling the even nd adding unit and tens place + even2 = [] + for i in even: + even2.append(sum(digits_of(i * 2))) + even2 = sum(even2) + odd = sum(odd) + check_sum = odd + even2 + if check_sum % 10 == 0: + ll.append(0) + else: + modl = check_sum % 10 + ll.append(10 - modl) + + # ll contains valid numbers now so printing it + res = str("".join(map(str, ll))) + res = "" + for i in ll: + res += str(i) + + if is_valid(res): + print(res) + else: + print( + "!ERRORRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR" + ) + + +def print_cc(ccn, cca): + + while cca != 0: + + ccs = [] + if ccn == 1: # we have two cases for visa + ccs.append(13) + ccs.append(16) + if ccn == 4 or ccn == 5: + ccs.append(16) + if ccn == 2: + ccs.append(15) + if ccn == 3: + ccs.append(14) + + ll = [] # it will store-up the cc numbers + fin_size = random.choice(ccs) # for visa we will choose 13 or 16 randomly + if ccn == 1: # VISA + ll.append(4) + t_rn = fin_size - 2 + fill_cc(ll, t_rn) + cca -= 1 + + elif ccn == 2: # AMEX + ll.append(3) + second_dig = [4, 7] + second_dig = random.choice(second_dig) + ll.append(second_dig) + t_rn = fin_size - 3 + fill_cc(ll, t_rn) + cca -= 1 + + elif ccn == 3: # diner club carte blanche + ll.append(3) + ll.append(0) + third_dig = [0, 1, 2, 3, 4, 5] + third_dig = random.choice(third_dig) + ll.append(third_dig) + t_rn = fin_size - 4 + fill_cc(ll, t_rn) + cca -= 1 + + elif ccn == 4: # master + ll.append(5) + second_dig = [1, 2, 3, 4, 5] + second_dig = random.choice(second_dig) + ll.append(second_dig) + t_rn = fin_size - 3 + fill_cc(ll, t_rn) + cca -= 1 + + elif ccn == 5: # discover + ll.append(6) + ll.append(0) + ll.append(1) + ll.append(1) + t_rn = fin_size - 5 + fill_cc(ll, t_rn) + cca -= 1 + def cc_generator(): - a=1 - print("Credit Card Generator") - print("Supported Credit Cards:\n************************") - for i in cc: - print( a, ">", i) - a+=1 - - ccn = int(input("Choose the credit card number from the above list: [NOTE: Press -1 if you to generate random cc]::")) - - if(ccn == -1): - print("Choose the total numbers of random credit cards you want to generate:" , end = '') - cca = int(input()) - print("*************************** List of randomly generated credit card numbers/name are shown below ******************************") - ccn_r = [1 , 2, 3, 4 , 5] - - for i in range(cca): - rnd = random.choice(ccn_r) - print(cc[rnd-1]) - print_cc(rnd, 1) - else: - - if not( 1 <= ccn <= 5 ): - print('wrong choice') - return - print("Choose the total numbers of credit cards you want to generate for " , cc[ccn-1] , ":" , sep = '' , end='') - cca = int(input()) - print("*************************** List of generated" , cc[ccn-1] ,"numbers are shown below ******************************") - print_cc(ccn , cca ) - -if __name__ == '__main__': - cc_generator() + a = 1 + print("Credit Card Generator") + print("Supported Credit Cards:\n************************") + for i in cc: + print(a, ">", i) + a += 1 + + ccn = int( + input( + "Choose the credit card number from the above list: [NOTE: Press -1 if you to generate random cc]::" + ) + ) + + if ccn == -1: + print( + "Choose the total numbers of random credit cards you want to generate:", + end="", + ) + cca = int(input()) + print( + "*************************** List of randomly generated credit card numbers/name are shown below ******************************" + ) + ccn_r = [1, 2, 3, 4, 5] + + for i in range(cca): + rnd = random.choice(ccn_r) + print(cc[rnd - 1]) + print_cc(rnd, 1) + else: + + if not (1 <= ccn <= 5): + print("wrong choice") + return + print( + "Choose the total numbers of credit cards you want to generate for ", + cc[ccn - 1], + ":", + sep="", + end="", + ) + cca = int(input()) + print( + "*************************** List of generated", + cc[ccn - 1], + "numbers are shown below ******************************", + ) + print_cc(ccn, cca) + + +if __name__ == "__main__": + cc_generator() diff --git a/credit_card_validator/cc_check.py b/credit_card_validator/cc_check.py index f2ab73ef6..467edadc9 100644 --- a/credit_card_validator/cc_check.py +++ b/credit_card_validator/cc_check.py @@ -1,94 +1,131 @@ # flake8: noqa import sys + + def digits_of(number): - return [int(i) for i in str(number)] + return [int(i) for i in str(number)] + def checksum_luhn(card_number): - digits = digits_of(card_number) - odd_digits = digits[-1::-2] # From right - even_digits = digits[-2::-2] # From right - total = sum(odd_digits) - for digit in even_digits: - total += sum(digits_of(2 * digit)) - return total % 10 + digits = digits_of(card_number) + odd_digits = digits[-1::-2] # From right + even_digits = digits[-2::-2] # From right + total = sum(odd_digits) + for digit in even_digits: + total += sum(digits_of(2 * digit)) + return total % 10 + def is_valid(card_number): - return checksum_luhn(card_number) == 0 - -cc = ["Visa card" , "American Express card" , "Diners Club Carte Blanche" , "Mastercard card" , "Discover card" ] -mii = [ 'ISO/TC 68 and other industry assignments' , -'Airlines' , -"Airlines, financial and other future industry assignments" , -"Travel and entertainment" , -"Banking and financial" , -"Banking and financial" , -"Merchandising and banking/financial" , -"Petroleum and other future industry assignments" , -"Healthcare, telecommunications and other future industry assignments", "For assignment by national standards bodies"] + return checksum_luhn(card_number) == 0 + + +cc = [ + "Visa card", + "American Express card", + "Diners Club Carte Blanche", + "Mastercard card", + "Discover card", +] +mii = [ + "ISO/TC 68 and other industry assignments", + "Airlines", + "Airlines, financial and other future industry assignments", + "Travel and entertainment", + "Banking and financial", + "Banking and financial", + "Merchandising and banking/financial", + "Petroleum and other future industry assignments", + "Healthcare, telecommunications and other future industry assignments", + "For assignment by national standards bodies", +] + def main(): - print("Credit Card Validator") - print("Supported Credit Cards:\n************************") - for i in cc: - print( ">",i) - choice = 'y' - while choice == 'y' or choice == 'Y': - try: - card_number = input("\nEnter the credit card number: ") - if is_valid(card_number) and 13 <= len(card_number) and len(card_number) <= 19: - print("\nThis is a valid credit card number.") - digi = digits_of(card_number) - lenn = len(digi) - if card_number[0:1] == "4" and ( lenn == 16 or lenn == 13 ): # visa case - print("Type:" , cc[0]) - print("Major Industry Identifier (MII):" , mii[digi[0]]) - if(lenn==13): - print("Account Number:", card_number[6:12]) - print("Checksum:", digi[12]) - else: # 16 case - print("Account Number:", card_number[6:15]) - print("Checksum:", digi[15]) - - elif card_number[0:2] == "34" or card_number[0:2] == "37" and lenn == 15 : # american express card - print("Type:" , cc[1]) - print("Major Industry Identifier (MII):", mii[digi[0]]) - print("Account Number:", card_number[4:11]) - print("Card Number within the account:", card_number[11:14]) - print("Checksum:", digi[14]) - - elif card_number[0:2] == "300" or card_number[0:2] == "301" or card_number[0:2] == "302" or card_number[0:2] == "303" or card_number[0:2] == "304" or card_number[0:2] == "305" and lenn ==14 : #Diner club carte blanche - print("Type:", cc[2]) - print("Major Industry Identifier (MII):", mii[digi[0]]) - print("Checksum:", digi[13]) - - elif card_number[0:2] == "51" or card_number[0:2] == "52" or card_number[0:2] == "53" or card_number[0:2] == "54" or card_number[0:2] == "55" and lenn == 16 : - print("Type:", cc[3]) - print("Major Industry Identifier (MII):", mii[digi[0]]) - print("Account Number:", card_number[6:15]) - print("Checksum:", digi[15]) - - elif card_number[0:4] == "6011" and lenn == 16 : - print("Type:", cc[4]) - print("Major Industry Identifier (MII):", mii[digi[0]]) - print("Account Number:", card_number[4:15]) - print("Checksum:", digi[15]) - - else: - print("Other informations are not displayed as it doesn't belong to list shown below, however cc is valid") - for i in cc: - print(">", i) - else: - print("\nInvalid!! Credit card number.") - - choice = input("\nWant to check again? (y/n): ") - - except ValueError: - print("\nErr! Credit card number should be numeric. Try again.") - except: - print("Unexpected error:", sys.exc_info()[0]) - raise - - - -if __name__ == '__main__': - main() + print("Credit Card Validator") + print("Supported Credit Cards:\n************************") + for i in cc: + print(">", i) + choice = "y" + while choice == "y" or choice == "Y": + try: + card_number = input("\nEnter the credit card number: ") + if ( + is_valid(card_number) + and 13 <= len(card_number) + and len(card_number) <= 19 + ): + print("\nThis is a valid credit card number.") + digi = digits_of(card_number) + lenn = len(digi) + if card_number[0:1] == "4" and (lenn == 16 or lenn == 13): # visa case + print("Type:", cc[0]) + print("Major Industry Identifier (MII):", mii[digi[0]]) + if lenn == 13: + print("Account Number:", card_number[6:12]) + print("Checksum:", digi[12]) + else: # 16 case + print("Account Number:", card_number[6:15]) + print("Checksum:", digi[15]) + + elif ( + card_number[0:2] == "34" or card_number[0:2] == "37" and lenn == 15 + ): # american express card + print("Type:", cc[1]) + print("Major Industry Identifier (MII):", mii[digi[0]]) + print("Account Number:", card_number[4:11]) + print("Card Number within the account:", card_number[11:14]) + print("Checksum:", digi[14]) + + elif ( + card_number[0:2] == "300" + or card_number[0:2] == "301" + or card_number[0:2] == "302" + or card_number[0:2] == "303" + or card_number[0:2] == "304" + or card_number[0:2] == "305" + and lenn == 14 + ): # Diner club carte blanche + print("Type:", cc[2]) + print("Major Industry Identifier (MII):", mii[digi[0]]) + print("Checksum:", digi[13]) + + elif ( + card_number[0:2] == "51" + or card_number[0:2] == "52" + or card_number[0:2] == "53" + or card_number[0:2] == "54" + or card_number[0:2] == "55" + and lenn == 16 + ): + print("Type:", cc[3]) + print("Major Industry Identifier (MII):", mii[digi[0]]) + print("Account Number:", card_number[6:15]) + print("Checksum:", digi[15]) + + elif card_number[0:4] == "6011" and lenn == 16: + print("Type:", cc[4]) + print("Major Industry Identifier (MII):", mii[digi[0]]) + print("Account Number:", card_number[4:15]) + print("Checksum:", digi[15]) + + else: + print( + "Other informations are not displayed as it doesn't belong to list shown below, however cc is valid" + ) + for i in cc: + print(">", i) + else: + print("\nInvalid!! Credit card number.") + + choice = input("\nWant to check again? (y/n): ") + + except ValueError: + print("\nErr! Credit card number should be numeric. Try again.") + except: + print("Unexpected error:", sys.exc_info()[0]) + raise + + +if __name__ == "__main__": + main() diff --git a/crypto_converter/cryptoconvert.py b/crypto_converter/cryptoconvert.py index fe1ddfd77..3f2f767ea 100644 --- a/crypto_converter/cryptoconvert.py +++ b/crypto_converter/cryptoconvert.py @@ -3,12 +3,13 @@ def exchange_rates(exchange_type): """This function gets exhange rates. -The coinbase API returns the JSON for an input cryptocurrency -with data or exhangerate of one coin to all known "normal" fiat -currencies like BTC(input) to INR, USD etc.""" + The coinbase API returns the JSON for an input cryptocurrency + with data or exhangerate of one coin to all known "normal" fiat + currencies like BTC(input) to INR, USD etc.""" exchange_type = exchange_type.upper() response_obj = requests.get( - f"https://api.coinbase.com/v2/exchange-rates?currency={exchange_type}") + f"https://api.coinbase.com/v2/exchange-rates?currency={exchange_type}" + ) try: exchange_dict = response_obj.json()["data"]["rates"] @@ -19,10 +20,10 @@ def exchange_rates(exchange_type): def convert_fiat_to_crypto(fvalue, ftype, ctype): """This function converts Fiat Money to Cryptocurrency amount. -Returns 1 if the input is found not valid, converted currency value -if the input is found valid, else returns "None". -"fvalue" corresponds to Fiat Money value, "ftype" to Fiat Money type and -"ctype" to Cryptocurrency type --> all given by the user.""" + Returns 1 if the input is found not valid, converted currency value + if the input is found valid, else returns "None". + "fvalue" corresponds to Fiat Money value, "ftype" to Fiat Money type and + "ctype" to Cryptocurrency type --> all given by the user.""" flag, statement = validity_of_currencytype(ctype, ftype) if flag == 1: print(statement) @@ -42,10 +43,10 @@ def convert_fiat_to_crypto(fvalue, ftype, ctype): def convert_crypto_to_fiat(cvalue, ctype, ftype): """This function converts Cryptocurrency amount to Fiat Money. -Returns 1 if the input is found not valid, converted currency value -if the input is found valid, else returns "None". -"cvalue" corresponds to Cryptocurrency value, "ctype" to Cryptocurrency type -and "ftype" to Fiat Money type --> all given by the user.""" + Returns 1 if the input is found not valid, converted currency value + if the input is found valid, else returns "None". + "cvalue" corresponds to Cryptocurrency value, "ctype" to Cryptocurrency type + and "ftype" to Fiat Money type --> all given by the user.""" flag, statement = validity_of_currencytype(ctype, ftype) if flag == 1: print(statement) @@ -65,12 +66,28 @@ def convert_crypto_to_fiat(cvalue, ctype, ftype): def validity_of_currencytype(ctype, ftype): """This function checks if the user input of Cryptocurrency type -or Fiat Money type are truly the latter. -Returns 1 if found an error in the input, else returns 0.""" - available_cryptocurrencies = ['ADA', 'BTC', 'BSV', 'ETH', - 'ETC', 'BCH', 'LINK', 'LTC', - 'DOGE', 'ZEC', 'SHIB', 'ZRX', 'MKR', - 'MATIC', 'USDC', 'XRP', 'DOT', 'XLM'] + or Fiat Money type are truly the latter. + Returns 1 if found an error in the input, else returns 0.""" + available_cryptocurrencies = [ + "ADA", + "BTC", + "BSV", + "ETH", + "ETC", + "BCH", + "LINK", + "LTC", + "DOGE", + "ZEC", + "SHIB", + "ZRX", + "MKR", + "MATIC", + "USDC", + "XRP", + "DOT", + "XLM", + ] if ctype not in available_cryptocurrencies: return 1, f"\n{ctype} is not a Cryptocurrency. Try Again!\n" elif ftype in available_cryptocurrencies: @@ -81,7 +98,7 @@ def validity_of_currencytype(ctype, ftype): def main(): """This function loops through the input given by the user, -until given a bad input or "Q/q". """ + until given a bad input or "Q/q".""" while True: user_inp = input("\n\tEnter Your Choice Here : ") @@ -89,11 +106,12 @@ def main(): crypto_type = input("\nEnter the Cryptocurrency Type : ") fiat_type = input("Enter the Fiat Money Type : ") try: - crypto_value = float( - input("\nEnter the Cryptocurrency Value : ")) + crypto_value = float(input("\nEnter the Cryptocurrency Value : ")) except Exception: - print('''Bad Input! - Please Enter \"y\" if you wish to continue, else \"n\".''') + print( + """Bad Input! + Please Enter \"y\" if you wish to continue, else \"n\".""" + ) choice = input() if choice == "y": continue @@ -103,14 +121,17 @@ def main(): print("Bad Input Again!") return result = convert_crypto_to_fiat( - crypto_value, crypto_type.upper(), fiat_type.upper()) + crypto_value, crypto_type.upper(), fiat_type.upper() + ) if result is None: return elif result == 1: continue - print(f"""\n{'-'*42} + print( + f"""\n{'-'*42} {crypto_value} {crypto_type.upper()} in {fiat_type.upper()} is --> {result} -{'-'*42}""") +{'-'*42}""" + ) elif user_inp == "2": fiat_type = input("\nEnter the Fiat Money Type : ") @@ -118,8 +139,10 @@ def main(): try: fiat_value = float(input("\nEnter the Fiat Money Value : ")) except Exception: - print('''You did not enter a number! - Please Enter \"y\" if you wish to continue, else \"n\".''') + print( + """You did not enter a number! + Please Enter \"y\" if you wish to continue, else \"n\".""" + ) choice = input() if choice == "y": continue @@ -129,14 +152,17 @@ def main(): print("Bad Input Again!") return result = convert_fiat_to_crypto( - fiat_value, fiat_type.upper(), crypto_type.upper()) + fiat_value, fiat_type.upper(), crypto_type.upper() + ) if result is None: return elif result == 1: continue - print(f"""\n{'-'*42} + print( + f"""\n{'-'*42} {fiat_value} {fiat_type.upper()} in {crypto_type.upper()} is --> {result} -{'-'*42}""") +{'-'*42}""" + ) elif user_inp == "Q" or user_inp == "q": return diff --git a/crypto_currency/main.py b/crypto_currency/main.py index ec8a5fc3f..e19f62370 100644 --- a/crypto_currency/main.py +++ b/crypto_currency/main.py @@ -1,11 +1,12 @@ # import required libraries +import csv +import time +from tkinter import filedialog + import requests from bs4 import BeautifulSoup, NavigableString from scrapy import Selector -import time -import csv from selenium import webdriver -from tkinter import filedialog print("For executing this program, you need a webdriver for your browser.....") print( diff --git a/crypto_tracker/crypto.py b/crypto_tracker/crypto.py index bdbd0d635..187ebb5f3 100644 --- a/crypto_tracker/crypto.py +++ b/crypto_tracker/crypto.py @@ -1,6 +1,7 @@ -import requests import sys +import requests + def get_prices(): @@ -9,12 +10,11 @@ def get_prices(): coins = sys.argv[1:] else: # Default coins - coins = ["BTC", "ETH", "XRP", "LTC", "BCH", - "ADA", "DOT", "LINK", "BNB", "XLM"] + coins = ["BTC", "ETH", "XRP", "LTC", "BCH", "ADA", "DOT", "LINK", "BNB", "XLM"] crypto_data = requests.get( "https://min-api.cryptocompare.com/" - "data/pricemultifull?fsyms={}&tsyms=USD" - .format(",".join(coins))).json()["RAW"] + "data/pricemultifull?fsyms={}&tsyms=USD".format(",".join(coins)) + ).json()["RAW"] data = {} for i in crypto_data: @@ -22,7 +22,7 @@ def get_prices(): "coin": i, "price": crypto_data[i]["USD"]["PRICE"], "change_day": crypto_data[i]["USD"]["CHANGEPCT24HOUR"], - "change_hour": crypto_data[i]["USD"]["CHANGEPCTHOUR"] + "change_hour": crypto_data[i]["USD"]["CHANGEPCTHOUR"], } return data diff --git a/csv_to_excel/main.py b/csv_to_excel/main.py index 698030121..442462489 100644 --- a/csv_to_excel/main.py +++ b/csv_to_excel/main.py @@ -1,6 +1,7 @@ -import pandas as pd -import sys import os +import sys + +import pandas as pd args = sys.argv[1:] # get command line *args assert args, "No file/dir was provided" # raise error is no arg is passed diff --git a/csv_to_json/main.py b/csv_to_json/main.py index e619b84f7..c90aa4fcf 100644 --- a/csv_to_json/main.py +++ b/csv_to_json/main.py @@ -1,6 +1,7 @@ -import pandas as pd -import sys import os +import sys + +import pandas as pd args = sys.argv[1:] # get command line *args assert args, "No file was provided; Provide a CSV filename" @@ -11,5 +12,5 @@ if not isdir: assert args[-1].endswith(".csv"), "Input file is not CSV" data = pd.read_csv(args[-1]) # load CSV data as Pd object - data.to_json(args[-1][:-4] + ".json", orient='records') + data.to_json(args[-1][:-4] + ".json", orient="records") del data diff --git a/currency_converter/currency_converter.py b/currency_converter/currency_converter.py index 5aca03068..2c7f0dc61 100644 --- a/currency_converter/currency_converter.py +++ b/currency_converter/currency_converter.py @@ -15,18 +15,18 @@ def __init__(self, url): # Conversion def convert(self, from_country, to_country, amount): initial = amount - if from_country != 'EUR': + if from_country != "EUR": amount = amount / self.rates[from_country] # Precision to 2 decimal places amount = round(amount * self.rate[to_country], 2) - print(f'{initial} {from_country} = {amount} {to_country}') + print(f"{initial} {from_country} = {amount} {to_country}") # Driver Code if __name__ == "__main__": # Replace API_KEY with your own API key from fixer.io - url = 'http://data.fixer.io/api/latest?access_key=API_KEY' + url = "http://data.fixer.io/api/latest?access_key=API_KEY" cc = Currency_Converter(url) from_country = input("From: ") to_country = input("To: ") diff --git a/datascience_books_scraper/scrape.py b/datascience_books_scraper/scrape.py index dd41a01be..9a4a993a9 100644 --- a/datascience_books_scraper/scrape.py +++ b/datascience_books_scraper/scrape.py @@ -1,45 +1,44 @@ +import csv + import requests from bs4 import BeautifulSoup -import csv + Book_name = [] Year = [] Publisher = [] Author = [] for j in range(1, 11): - source = requests.get( - f'https://1lib.in/s/data%20science?page={j}').text - soup = BeautifulSoup(source, 'lxml') - books = soup.find_all('table', attrs={'style': 'width:100%;height:100%;'}) + source = requests.get(f"https://1lib.in/s/data%20science?page={j}").text + soup = BeautifulSoup(source, "lxml") + books = soup.find_all("table", attrs={"style": "width:100%;height:100%;"}) for i in books: # book name try: - Book_name.append(i.find('h3').text.strip()) + Book_name.append(i.find("h3").text.strip()) except Exception: - Book_name.append('nan') + Book_name.append("nan") # year try: - Year.append( - i.find('div', class_='property_year').text.strip()[6:10]) + Year.append(i.find("div", class_="property_year").text.strip()[6:10]) except Exception: - Year.append('nan') + Year.append("nan") # publisher try: - Publisher.append( - i.find('div', attrs={'title': 'Publisher'}).text.strip()) + Publisher.append(i.find("div", attrs={"title": "Publisher"}).text.strip()) except Exception: - Publisher.append('nan') + Publisher.append("nan") # Author try: - Author.append(i.find('div', class_='authors').text.strip()) + Author.append(i.find("div", class_="authors").text.strip()) except Exception: - Author.append('nan') + Author.append("nan") -file_name = '500Datasciencebooks.csv' +file_name = "500Datasciencebooks.csv" -with open(file_name, 'w') as file: +with open(file_name, "w") as file: writer = csv.writer(file) - writer.writerow(['Sr.No', 'Book name', 'Publisher', 'Author', 'Year']) + writer.writerow(["Sr.No", "Book name", "Publisher", "Author", "Year"]) for i in range(1, len(Book_name)): writer.writerow([i, Book_name[i], Publisher[i], Author[i], Year[i]]) diff --git a/desktop_break_notifier/desktop_break_notifier.py b/desktop_break_notifier/desktop_break_notifier.py index f6fd5a75b..9b458a562 100644 --- a/desktop_break_notifier/desktop_break_notifier.py +++ b/desktop_break_notifier/desktop_break_notifier.py @@ -1,12 +1,13 @@ -from plyer import notification -from time import sleep import argparse +from time import sleep + +from plyer import notification # the main function def main(args: argparse.Namespace) -> None: # creating a title - title = 'Time for a break!' + title = "Time for a break!" # fetching the message message = args.message @@ -17,7 +18,7 @@ def main(args: argparse.Namespace) -> None: # if delay is less than 60 then set the delay to 60 and inform the user if delay < 1: delay = 1 - print('Warning: Set delay = 1 minute(s) as passed delay < 1 minute(s)') + print("Warning: Set delay = 1 minute(s) as passed delay < 1 minute(s)") # loop to show the messages as long as the user doesn't explicitly stop the script while True: @@ -31,26 +32,28 @@ def main(args: argparse.Namespace) -> None: ) -if __name__ == '__main__': +if __name__ == "__main__": # instantiating argparse parser = argparse.ArgumentParser() # adding argument for delay seconds parser.add_argument( - '-d', '--delay', - metavar='', - help='Specify delay time in minutes. [DEFAULT=20]', + "-d", + "--delay", + metavar="", + help="Specify delay time in minutes. [DEFAULT=20]", type=int, - default=20 + default=20, ) # adding argument for custom message parser.add_argument( - '-m', '--message', - metavar='', - help='Specify a message for the notification', + "-m", + "--message", + metavar="", + help="Specify a message for the notification", type=str, - default='You have been working continuously. Consider taking a break.' + default="You have been working continuously. Consider taking a break.", ) # parsing the args diff --git a/dictionary_gui/dictionary.py b/dictionary_gui/dictionary.py index 7027b2527..28a5de54d 100644 --- a/dictionary_gui/dictionary.py +++ b/dictionary_gui/dictionary.py @@ -1,5 +1,6 @@ from tkinter import * # noqa from tkinter import messagebox + from PyDictionary import PyDictionary # Creating Tkinter Scaffold @@ -13,24 +14,27 @@ def getMeaning(): response = dictionary.meaning(word.get()) - if (response): - if ('Noun' in response): - meaning = response['Noun'][0] - elif ('Verb' in response): - meaning = response['Verb'][0] - elif ('Adjective' in response): - meaning = response['Adjective'][0] + if response: + if "Noun" in response: + meaning = response["Noun"][0] + elif "Verb" in response: + meaning = response["Verb"][0] + elif "Adjective" in response: + meaning = response["Adjective"][0] else: meaning = "Invalid word" else: messagebox.showinfo( - "Error", "Please add a Noun, Pronoun, verb or a valid word.") + "Error", "Please add a Noun, Pronoun, verb or a valid word." + ) # Show meaning in frame meaning_label.config(text=meaning) # Heading Label -heading_label = Label(root, text="DICTIONARY", font=("Helvetica 35 bold"), foreground='Blue') # noqa +heading_label = Label( + root, text="DICTIONARY", font=("Helvetica 35 bold"), foreground="Blue" +) # noqa heading_label.config(anchor=CENTER) # noqa heading_label.pack(pady=10) @@ -41,7 +45,16 @@ def getMeaning(): word.pack(padx=10) frame.pack() -search_button = Button(root, text="Search Word", font=("Helvetica 15 bold"), relief=RIDGE, borderwidth=3, cursor="hand2", foreground='Green', command=getMeaning) # noqa +search_button = Button( + root, + text="Search Word", + font=("Helvetica 15 bold"), + relief=RIDGE, + borderwidth=3, + cursor="hand2", + foreground="Green", + command=getMeaning, +) # noqa search_button.config(anchor=CENTER) # noqa search_button.pack(pady=10) diff --git a/digital_clock/clock.py b/digital_clock/clock.py index e9d573495..dcb4ad094 100644 --- a/digital_clock/clock.py +++ b/digital_clock/clock.py @@ -2,18 +2,25 @@ from time import strftime top = tkinter.Tk() -top.title('Clock') +top.title("Clock") top.resizable(0, 0) def time(): - string = strftime('%H:%M:%S %p') + string = strftime("%H:%M:%S %p") clockTime.config(text=string) clockTime.after(1000, time) -clockTime = tkinter.Label(top, font=( - 'courier new', 40,), background='black', foreground='white') -clockTime.pack(anchor='center') +clockTime = tkinter.Label( + top, + font=( + "courier new", + 40, + ), + background="black", + foreground="white", +) +clockTime.pack(anchor="center") time() top.mainloop() diff --git a/directory_tree/tree.py b/directory_tree/tree.py index 817c5d2fa..acfbc03a7 100644 --- a/directory_tree/tree.py +++ b/directory_tree/tree.py @@ -1,5 +1,5 @@ -import os import argparse +import os # function to generate a pattern @@ -11,13 +11,13 @@ def get_pattern(level: int) -> str: separators_length = spaces // 2 # generating the pattern - pattern = '' + pattern = "" for i in range(separators_length): - pattern += ' |' + pattern += " |" # adding the finishing - pattern += '__' + pattern += "__" return pattern @@ -29,13 +29,13 @@ def print_structure(path: str, level: int) -> None: print(path) else: # if it is not the root directory # if dir name is something like dir/indir/then make it indir/ - if '/' in path: + if "/" in path: # the header information should start with level - 1 print(f'{get_pattern(level - 1)}{path.split("/")[-1]}/') else: # if dir name is dir then show the user dir/ # so that it is clear that it is a directory - print(f'{get_pattern(level)}{path}/') + print(f"{get_pattern(level)}{path}/") # list the contents of the dir contents = os.listdir(path) @@ -48,7 +48,7 @@ def print_structure(path: str, level: int) -> None: # checking if the content is the file if os.path.isfile(full_path): # if it is then print the file name - print(f'{get_pattern(level)}{content}') + print(f"{get_pattern(level)}{content}") else: # if it is a dir instead # add spacing vertically b/w different folders if requested if args.spacing: @@ -68,30 +68,33 @@ def main(args: argparse.Namespace) -> None: # if the passed directory name is invalid then inform the user and exit if not os.path.isdir(dir_path): - print('ERROR: can not find the path specified!') + print("ERROR: can not find the path specified!") exit(0) # printing the structure for the given path and the level print_structure(dir_path, 0) -if __name__ == '__main__': +if __name__ == "__main__": # creating the argparse object parser = argparse.ArgumentParser() # creating an argument for the directory parser.add_argument( - '-d', '--directory', - metavar='', - help='path to the directory. [DEFAULT=\'.\']', - type=str, default='./' + "-d", + "--directory", + metavar="", + help="path to the directory. [DEFAULT='.']", + type=str, + default="./", ) # adding argument for vertical spacing b/w folders parser.add_argument( - '-s', '--spacing', - action='store_true', - help='Add spacing b/w folders output vertically' + "-s", + "--spacing", + action="store_true", + help="Add spacing b/w folders output vertically", ) # parsing the arguments diff --git a/discord_embedded_message/message.py b/discord_embedded_message/message.py index 907a543b4..bb73c4c6e 100644 --- a/discord_embedded_message/message.py +++ b/discord_embedded_message/message.py @@ -1,5 +1,6 @@ import datetime import json + import requests diff --git a/discord_github_bot/bot.py b/discord_github_bot/bot.py index b9e022e2e..6e1e80b8e 100644 --- a/discord_github_bot/bot.py +++ b/discord_github_bot/bot.py @@ -1,12 +1,13 @@ -from discord.ext.commands import Bot -from discord.utils import get as discord_get -from discord.ext.tasks import loop -import discord -import requests import json # config import config +import discord +import requests +from discord.ext.commands import Bot +from discord.ext.tasks import loop +from discord.utils import get as discord_get + github_session = requests.Session() github_session.auth = (config.GITHUB_USERNAME, config.GITHUB_TOKEN) # This keeps the already sent notification ids @@ -18,7 +19,7 @@ # Gets Notifications from Github def get_github_notifications(): - url = f'https://api.github.com/repos/{config.GITHUB_REPO}/notifications' + url = f"https://api.github.com/repos/{config.GITHUB_REPO}/notifications" r = github_session.get(url) return r.text @@ -33,19 +34,21 @@ async def send_notification(context): ) if channel is None: # else use the context - print(f'[Notifications] Cannot find channel {config.DISCORD_CHANNEL}\n') + print(f"[Notifications] Cannot find channel {config.DISCORD_CHANNEL}\n") channel = context try: notifications = get_github_notifications() notifications = json.loads(notifications) except Exception as err: - print(f'Exception Occured. {str(err)}') + print(f"Exception Occured. {str(err)}") notifications = None if notifications is None: if context.message: await context.message.reply else: - await context.guild.send("There was some error in getting notifications....\nTry Later.") + await context.guild.send( + "There was some error in getting notifications....\nTry Later." + ) return # Loop through notifications and check if already sent for notifi in notifications: @@ -57,13 +60,18 @@ async def send_notification(context): print(f'[Notification] Updated At: {notifi["updated_at"]}') print(f'[Notification] URL: {notifi["subject"]["url"]}') # Get URL to the notification subject - direct_url = str(notifi["subject"]["url"]).replace("api.github", "github").replace("/repos/", "/") + direct_url = ( + str(notifi["subject"]["url"]) + .replace("api.github", "github") + .replace("/repos/", "/") + ) # Make a new message and send it embededMessage = discord.Embed( title=f'{notifi["id"]} - {notifi["subject"]["title"]}', url=direct_url, description=f'Reason: {notifi["reason"]}\nUpdated At: {notifi["updated_at"]}\nURL: {direct_url}', - color=discord.Color.blue()) + color=discord.Color.blue(), + ) # Add the notification ID to list of already sent, so it does'nt repeat already_sent.insert(0, notifi["id"]) await channel.send(embed=embededMessage) @@ -73,17 +81,16 @@ async def send_notification(context): # Discord Bot Connected @client.event async def on_ready(): - print(f'{client.user} has connected!') + print(f"{client.user} has connected!") await client.change_presence( activity=discord.Activity( - type=discord.ActivityType.listening, - name='Type !help to get help' + type=discord.ActivityType.listening, name="Type !help to get help" ) ) # Runs on !update command -@client.command(name='update') +@client.command(name="update") async def update(context): print("[Command] Updating Notifications.....") await context.message.reply( @@ -93,7 +100,7 @@ async def update(context): # Runs on !start command -@client.command(name='start') +@client.command(name="start") async def start_notifications(context): print("Starting Notifications Bot....") notify.start(context) @@ -101,7 +108,7 @@ async def start_notifications(context): # Runs on !stop command -@client.command(name='stop') +@client.command(name="stop") async def stop_notifications(context): print("[Command] Notifications Bot Has Stopped....") notify.cancel() diff --git a/discount_alerter/amazon_price.py b/discount_alerter/amazon_price.py index 6e6ef490f..501be72e2 100644 --- a/discount_alerter/amazon_price.py +++ b/discount_alerter/amazon_price.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 -import requests +import time from os import getenv + import bs4 +import requests from twilio.rest import Client -import time """ Scrapper: get_price() digs amazon URL and exracts the ProductID of it. @@ -23,30 +24,33 @@ def get_price(URL): ProductID = URL.split("/product/", 1)[1].split("/")[0] headers = { - 'authority': 'www.camelcamelcamel.com', - 'pragma': 'no-cache', - 'cache-control': 'no-cache', - 'dnt': '1', - 'upgrade-insecure-requests': '1', - 'user-agent': '''Mozilla/5.0 (X11; Chrome x86_64 8172.45.0) AppleWebKit/537.36 - (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36''', - 'accept': '''text/html,application/xhtml+xml,application/xml;q=0.9,image/ - webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9''', - 'sec-fetch-site': 'none', - 'sec-fetch-mode': 'navigate', - 'sec-fetch-dest': 'document', - 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', + "authority": "www.camelcamelcamel.com", + "pragma": "no-cache", + "cache-control": "no-cache", + "dnt": "1", + "upgrade-insecure-requests": "1", + "user-agent": """Mozilla/5.0 (X11; Chrome x86_64 8172.45.0) AppleWebKit/537.36 + (KHTML, like Gecko) Chrome/51.0.2704.64 Safari/537.36""", + "accept": """text/html,application/xhtml+xml,application/xml;q=0.9,image/ + webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9""", + "sec-fetch-site": "none", + "sec-fetch-mode": "navigate", + "sec-fetch-dest": "document", + "accept-language": "en-GB,en-US;q=0.9,en;q=0.8", } - htmldata = requests.get("https://" + country_prefix + "camelcamelcamel.com/product/" + ProductID, headers=headers) - soup = bs4.BeautifulSoup(htmldata.text, 'html.parser') - current = ".".join(soup.find("span", {'class': 'green'}).text[:-1].split(",")) - ''' + htmldata = requests.get( + "https://" + country_prefix + "camelcamelcamel.com/product/" + ProductID, + headers=headers, + ) + soup = bs4.BeautifulSoup(htmldata.text, "html.parser") + current = ".".join(soup.find("span", {"class": "green"}).text[:-1].split(",")) + """ This could be handy for futur advance comparison or maybe auto order. # highest = ".".join(soup.find("tr", {'class': 'highest_price'}).text.strip().split("\n")[1][:-1].split(",")) # lowest = ".".join(soup.find("tr", {'class': 'lowest_price'}).text.strip().split("\n")[1][:-1].split(",")) - ''' - return (float(current)) + """ + return float(current) """ @@ -56,18 +60,17 @@ def get_price(URL): def check_price(URL, desired_price): if isinstance(desired_price) is False: - raise TypeError('Desired Price should be Int or Double decimal') + raise TypeError("Desired Price should be Int or Double decimal") else: - current_price = (get_price(getenv("URL"))) - if (desired_price < current_price): + current_price = get_price(getenv("URL")) + if desired_price < current_price: # TODO: Sends email pass - if (desired_price >= current_price): - Client(getenv( - 'ACCOUNT_SID'), getenv('AUTH_TOKEN')).messages.create( - body='Current price for {} is {}.'.format(getenv("URL"), current_price), - from_='+twilio_number', - to='+user_phone_number' + if desired_price >= current_price: + Client(getenv("ACCOUNT_SID"), getenv("AUTH_TOKEN")).messages.create( + body="Current price for {} is {}.".format(getenv("URL"), current_price), + from_="+twilio_number", + to="+user_phone_number", ) diff --git a/dns_verifier/dnslu.py b/dns_verifier/dnslu.py index bfff4c65c..739d6d42a 100644 --- a/dns_verifier/dnslu.py +++ b/dns_verifier/dnslu.py @@ -20,33 +20,35 @@ def dac(dns_val=None) -> OrderedDict: if dns_val is None: raise ValueError("Sorry, DNS is needed") if isinstance(dns_val, str) is False: - raise TypeError("Sorry, \'DNS\' must be type \'str\'") + raise TypeError("Sorry, 'DNS' must be type 'str'") try: - output = dns.resolver.resolve(dns_val, 'A') + output = dns.resolver.resolve(dns_val, "A") ip_values = [ipval.to_text() for ipval in output] except dns.resolver.NXDOMAIN: avail = True - return OrderedDict([ - ("DNS", dns_val), - ("IP", ip_values), - ("AVAIL", avail), - ]) + return OrderedDict( + [ + ("DNS", dns_val), + ("IP", ip_values), + ("AVAIL", avail), + ] + ) -if __name__ == '__main__': +if __name__ == "__main__": dns_val = None option = None if len(sys.argv) > 1: - if '--dns' in sys.argv: - d_index = sys.argv.index('--dns') + if "--dns" in sys.argv: + d_index = sys.argv.index("--dns") if d_index == sys.argv.index(sys.argv[-1:][0]): print("Sorry, DNS was not specified") sys.exit(1) - dns_val = sys.argv[sys.argv.index('--dns') + 1] + dns_val = sys.argv[sys.argv.index("--dns") + 1] else: - print("help:\nuse \'--dns\' for DNS specification") + print("help:\nuse '--dns' for DNS specification") sys.exit(1) try: response = dac(dns_val=dns_val) diff --git a/doc_to_pdf/doc_to_pdf.py b/doc_to_pdf/doc_to_pdf.py index d7e535c88..b6de052b2 100644 --- a/doc_to_pdf/doc_to_pdf.py +++ b/doc_to_pdf/doc_to_pdf.py @@ -1,9 +1,10 @@ import comtypes.client + wdFormatPDF = 17 def doc_to_pdf(input_file_path, output_file_path): - word = comtypes.client.CreateObject('Word.Application') + word = comtypes.client.CreateObject("Word.Application") doc = word.Documents.Open(input_file_path) doc.SaveAs(output_file_path, FileFormat=wdFormatPDF) doc.Close() diff --git a/document_summarizer/AlDocSummarizer.py b/document_summarizer/AlDocSummarizer.py index dcd22915c..a9627b106 100644 --- a/document_summarizer/AlDocSummarizer.py +++ b/document_summarizer/AlDocSummarizer.py @@ -1,28 +1,28 @@ -import PyPDF2 import heapq -from docx import Document -import re import os -from tkinter import Tk, END, Frame, SUNKEN, BOTH -from tkinter import font, X, Label, Button, Text, Entry -from PIL import ImageTk, Image +import re +from tkinter import (BOTH, END, SUNKEN, Button, Entry, Frame, Label, Text, Tk, + X, font) + import nltk +import PyPDF2 +from docx import Document +from PIL import Image, ImageTk -nltk.download('punkt') -nltk.download('stopwords') +nltk.download("punkt") +nltk.download("stopwords") cwd = os.path.dirname(os.path.realpath(__file__)) -class AlDocSummarizer(): +class AlDocSummarizer: def __init__(self): root = Tk(className=" ALDOCSUMMARIZER ") root.geometry("550x250+1350+765") root.resizable(0, 0) - root.iconbitmap(os.path.join(cwd + '\\UI\\icons', - 'aldocsummarizer.ico')) + root.iconbitmap(os.path.join(cwd + "\\UI\\icons", "aldocsummarizer.ico")) root.config(bg="#0098c0") root.overrideredirect(1) - color = '#0098c0' + color = "#0098c0" def callback(event): root.geometry("400x175+1500+840") @@ -40,13 +40,13 @@ def hideScreen(): def summarize(): filename = fileText.get() - filepath = os.path.join(cwd + '\\AlDocSummarizer', filename) + filepath = os.path.join(cwd + "\\AlDocSummarizer", filename) if os.path.exists(filepath): - articleText = '' + articleText = "" extension = os.path.splitext(filepath)[1] try: if extension.lower() == ".pdf": - pdfFileObj = open(filepath, 'rb') + pdfFileObj = open(filepath, "rb") pdfReader = PyPDF2.PdfFileReader(pdfFileObj) for i in range(pdfReader.numPages): pageObj = pdfReader.getPage(i) @@ -57,14 +57,12 @@ def summarize(): for paragraph in document.paragraphs: articleText += paragraph.text - articleText = re.sub(r'\[[0-9]*\]', ' ', articleText) - articleText = re.sub(r'\s+', ' ', articleText) - formattedArticleText = re.sub('[^a-zA-Z]', ' ', - articleText) - formattedArticleText = re.sub(r'\s+', ' ', - formattedArticleText) + articleText = re.sub(r"\[[0-9]*\]", " ", articleText) + articleText = re.sub(r"\s+", " ", articleText) + formattedArticleText = re.sub("[^a-zA-Z]", " ", articleText) + formattedArticleText = re.sub(r"\s+", " ", formattedArticleText) sentenceList = nltk.sent_tokenize(articleText) - stopwords = nltk.corpus.stopwords.words('english') + stopwords = nltk.corpus.stopwords.words("english") wordFreq = {} for word in nltk.word_tokenize(formattedArticleText): if word not in stopwords: @@ -81,60 +79,83 @@ def summarize(): for sent in sentenceList: for word in nltk.word_tokenize(sent.lower()): if word in wordFreq.keys(): - if len(sent.split(' ')) < 30: + if len(sent.split(" ")) < 30: if sent not in sentenceScores.keys(): sentenceScores[sent] = wordFreq[word] else: sentenceScores[sent] += wordFreq[word] - summarySentences = heapq.nlargest(int(lines.get()), - sentenceScores, - key=sentenceScores.get) - summaryFileName = filename.replace(extension, '') - extension = extension.replace('.', '') - summaryFileName = f'{summaryFileName}_{extension}_' - summaryFileName += 'summarized.txt' - summaryFilePath = os.path.join(cwd + '\\AlDocSummarizer\\' - 'Summarize', - summaryFileName) + summarySentences = heapq.nlargest( + int(lines.get()), sentenceScores, key=sentenceScores.get + ) + summaryFileName = filename.replace(extension, "") + extension = extension.replace(".", "") + summaryFileName = f"{summaryFileName}_{extension}_" + summaryFileName += "summarized.txt" + summaryFilePath = os.path.join( + cwd + "\\AlDocSummarizer\\" "Summarize", summaryFileName + ) summaryFile = open(summaryFilePath, "w") summaryFile.writelines(summarySentences) summaryFile.close() text.delete(1.0, END) - text.insert(1.0, summaryFileName + ' has been saved ' - 'successfully in Summarize folder') + text.insert( + 1.0, + summaryFileName + " has been saved " + "successfully in Summarize folder", + ) except Exception as e: text.delete(1.0, END) print(str(e)) - text.insert(1.0, 'Invalid document, please provide .pdf or' - ' .docx extension files') + text.insert( + 1.0, + "Invalid document, please provide .pdf or" + " .docx extension files", + ) else: text.delete(1.0, END) - text.insert(1.0, 'Invalid file path') + text.insert(1.0, "Invalid file path") - textHighlightFont = font.Font(family='OnePlus Sans Display', size=12) - appHighlightFont = font.Font(family='OnePlus Sans Display', size=12, - weight='bold') + textHighlightFont = font.Font(family="OnePlus Sans Display", size=12) + appHighlightFont = font.Font( + family="OnePlus Sans Display", size=12, weight="bold" + ) - titleBar = Frame(root, bg='#141414', relief=SUNKEN, bd=0) - icon = Image.open(os.path.join(cwd + '\\UI\\icons', - 'aldocsummarizer.ico')) + titleBar = Frame(root, bg="#141414", relief=SUNKEN, bd=0) + icon = Image.open(os.path.join(cwd + "\\UI\\icons", "aldocsummarizer.ico")) icon = icon.resize((30, 30), Image.ANTIALIAS) icon = ImageTk.PhotoImage(icon) iconLabel = Label(titleBar, image=icon) iconLabel.photo = icon - iconLabel.config(bg='#141414') + iconLabel.config(bg="#141414") iconLabel.grid(row=0, column=0, sticky="nsew") - titleLabel = Label(titleBar, text='ALDOCSUMMARIZER', fg='#909090', - bg='#141414', font=appHighlightFont) + titleLabel = Label( + titleBar, + text="ALDOCSUMMARIZER", + fg="#909090", + bg="#141414", + font=appHighlightFont, + ) titleLabel.grid(row=0, column=1, sticky="nsew") - closeButton = Button(titleBar, text="x", bg='#141414', fg="#909090", - borderwidth=0, command=root.destroy, - font=appHighlightFont) + closeButton = Button( + titleBar, + text="x", + bg="#141414", + fg="#909090", + borderwidth=0, + command=root.destroy, + font=appHighlightFont, + ) closeButton.grid(row=0, column=3, sticky="nsew") - minimizeButton = Button(titleBar, text="-", bg='#141414', fg="#909090", - borderwidth=0, command=hideScreen, - font=appHighlightFont) + minimizeButton = Button( + titleBar, + text="-", + bg="#141414", + fg="#909090", + borderwidth=0, + command=hideScreen, + font=appHighlightFont, + ) minimizeButton.grid(row=0, column=2, sticky="nsew") titleBar.grid_columnconfigure(0, weight=1) titleBar.grid_columnconfigure(1, weight=30) @@ -145,28 +166,54 @@ def summarize(): fileText = Label(root, text="DOCUMENT TO BE SUMMARIZED") fileText.pack() fileText.config(bg=color, fg="white", font=appHighlightFont) - fileText = Entry(root, bg="white", fg=color, highlightbackground=color, - highlightcolor=color, highlightthickness=3, bd=0, - font=textHighlightFont) + fileText = Entry( + root, + bg="white", + fg=color, + highlightbackground=color, + highlightcolor=color, + highlightthickness=3, + bd=0, + font=textHighlightFont, + ) fileText.pack(fill=X) - lines = Label(root, text="NUMBER OF LINES IN WHICH DOCUMENT HAS TO" - " SUMMARIZED") + lines = Label( + root, text="NUMBER OF LINES IN WHICH DOCUMENT HAS TO" " SUMMARIZED" + ) lines.pack() lines.config(bg=color, fg="white", font=appHighlightFont) - lines = Entry(root, bg="white", fg=color, highlightbackground=color, - highlightcolor=color, highlightthickness=3, bd=0, - font=textHighlightFont) + lines = Entry( + root, + bg="white", + fg=color, + highlightbackground=color, + highlightcolor=color, + highlightthickness=3, + bd=0, + font=textHighlightFont, + ) lines.pack(fill=X) - docSummary = Button(root, borderwidth=0, highlightthickness=3, - text="SUMMARIZE", command=summarize) + docSummary = Button( + root, + borderwidth=0, + highlightthickness=3, + text="SUMMARIZE", + command=summarize, + ) docSummary.config(bg=color, fg="white", font=appHighlightFont) docSummary.pack(fill=X) - text = Text(root, font="sans-serif", relief=SUNKEN, - highlightbackground=color, highlightcolor=color, - highlightthickness=5, bd=0) + text = Text( + root, + font="sans-serif", + relief=SUNKEN, + highlightbackground=color, + highlightcolor=color, + highlightthickness=5, + bd=0, + ) text.config(bg="white", fg=color, height=2, font=textHighlightFont) text.pack(fill=BOTH, expand=True) diff --git a/duplicate_files_remover/main.py b/duplicate_files_remover/main.py index 18e5c5a7e..89a5f70e2 100644 --- a/duplicate_files_remover/main.py +++ b/duplicate_files_remover/main.py @@ -1,6 +1,7 @@ +import hashlib import os import sys -import hashlib + import pandas as pd @@ -8,7 +9,7 @@ def file_list(folder): path = os.path.abspath(folder) files = [entry.path for entry in os.scandir(path) if entry.is_file()] - print(f'[+] Found {len(files)} files in {folder}. ') + print(f"[+] Found {len(files)} files in {folder}. ") return files @@ -17,7 +18,7 @@ def file_list(folder): def get_hash(filename): block_size = 65536 - with open(filename, 'rb') as f: + with open(filename, "rb") as f: m = hashlib.sha256() block = f.read(block_size) while len(block) > 0: @@ -27,6 +28,7 @@ def get_hash(filename): return digest + # create hashtable @@ -41,7 +43,7 @@ def hashtable(files): try: hash_identifier.extend([get_hash(f)]) except OSError: - hash_identifier.extend(['Hash could not be generated.']) + hash_identifier.extend(["Hash could not be generated."]) return hash_identifier @@ -51,10 +53,10 @@ def hashtable(files): def create_hashtable(folder): files = file_list(folder) - df = pd.DataFrame(columns=['file', 'hash']) - df['file'] = files - df['hash'] = hashtable(files) - print('[+] Generated all hashes.') + df = pd.DataFrame(columns=["file", "hash"]) + df["file"] = files + df["hash"] = hashtable(files) + print("[+] Generated all hashes.") return df @@ -62,12 +64,10 @@ def create_hashtable(folder): # get duplicates def list_duplicates(folder): duplicates_files = create_hashtable(folder) - duplicates_files = duplicates_files[duplicates_files['hash'].duplicated( - keep=False)] - duplicates_files.sort_values(by='hash', inplace=True) - duplicates_files = duplicates_files.drop_duplicates( - subset='hash', keep='first') - print(f'[+] Found {len(duplicates_files)} duplicates.\n') + duplicates_files = duplicates_files[duplicates_files["hash"].duplicated(keep=False)] + duplicates_files.sort_values(by="hash", inplace=True) + duplicates_files = duplicates_files.drop_duplicates(subset="hash", keep="first") + print(f"[+] Found {len(duplicates_files)} duplicates.\n") print(duplicates_files) return duplicates_files @@ -75,21 +75,21 @@ def list_duplicates(folder): # list_duplicates('C:/Users/ramij/Desktop/secret') -if __name__ == '__main__': - folder = str(input('Folder full path (eg: C:/Users/bob/Desktop): ')) +if __name__ == "__main__": + folder = str(input("Folder full path (eg: C:/Users/bob/Desktop): ")) if not os.path.exists(folder): - print('Folder does not exist.') + print("Folder does not exist.") sys.exit(1) else: pass duplicates = list_duplicates(folder) - delete = input('\n[!] Do you want to delete the duplicates (y/n):') - print('\n') - if delete.lower() == 'y': - duplicates = duplicates['file'].tolist() + delete = input("\n[!] Do you want to delete the duplicates (y/n):") + print("\n") + if delete.lower() == "y": + duplicates = duplicates["file"].tolist() for f in duplicates: os.remove(f) - print(f'Deleted {f}') + print(f"Deleted {f}") else: - print('[X] Exiting...') + print("[X] Exiting...") diff --git a/duplicatefile_finder/file_dup.py b/duplicatefile_finder/file_dup.py index 262ffa521..4bb45af14 100644 --- a/duplicatefile_finder/file_dup.py +++ b/duplicatefile_finder/file_dup.py @@ -1,17 +1,18 @@ -import os import hashlib +import os # prints duplicate files from the list def show_dup_files(dup_list): if len(dup_files) == 0: - print('no duplicate files found') - return # noqa - print('Duplicate files in the inputted directory : ') + print("no duplicate files found") + return # noqa + print("Duplicate files in the inputted directory : ") for file_name in dup_list: print(file_name) + # prints out everything inside a given folder @@ -26,7 +27,7 @@ def show_all_files(dest_fold): def get_digest(file_path): h = hashlib.sha256() - with open(file_path, 'rb') as file: + with open(file_path, "rb") as file: while True: # Reading is buffered, so we can read smaller chunks. chunk = file.read(h.block_size) @@ -48,7 +49,7 @@ def get_file_hashes(file_size, size_dic, root_fold): if __name__ == "__main__": try: - dest_folder = input('input the absolute path of a folder : ') + dest_folder = input("input the absolute path of a folder : ") track_file_size = dict() dup_files = list() files_list = os.listdir(dest_folder) @@ -61,11 +62,13 @@ def get_file_hashes(file_size, size_dic, root_fold): # searching in the dictionary if file_size in track_file_size.values(): - '''if it exists it may be a potential dup file - to confirm it we will hash content of both and comapare'''# noqa + """if it exists it may be a potential dup file + to confirm it we will hash content of both and comapare""" # noqa # now there can be more than one files with same size so have - files_hashed_list = get_file_hashes(file_size, track_file_size, dest_folder)# noqa + files_hashed_list = get_file_hashes( + file_size, track_file_size, dest_folder + ) # noqa file_hash_2 = get_digest(os.path.join(dest_folder, file_name)) @@ -74,7 +77,7 @@ def get_file_hashes(file_size, size_dic, root_fold): else: track_file_size[file_name] = file_size - # show_all_files(dest_folder) + # show_all_files(dest_folder) show_dup_files(dup_files) except Exception as err: - print(err) # noqa \ No newline at end of file + print(err) # noqa diff --git a/email_feed/gmail_feed.py b/email_feed/gmail_feed.py index e0b25fceb..999017baf 100644 --- a/email_feed/gmail_feed.py +++ b/email_feed/gmail_feed.py @@ -1,29 +1,34 @@ -import xmltodict import re + import requests +import xmltodict username = "xxx" password = "xxx" -URL = 'https://%s:%s@mail.google.com/mail/u/0/feed/atom/all' % (username, password) +URL = "https://%s:%s@mail.google.com/mail/u/0/feed/atom/all" % (username, password) r = requests.get(URL) if r.status_code == 401: - print("login [%s] or password [%s] is incorrect\n%s" % (username, password, 'Error')) + print( + "login [%s] or password [%s] is incorrect\n%s" % (username, password, "Error") + ) elif r.status_code != 200: print("Requests error [%s] - %s" % (r.status_code, URL)) elif r.status_code == 200: contents = r.text a = xmltodict.parse(contents) - for k in range(len(a['feed']['entry'])): - text = a['feed']['entry'][k]['summary'] - key_words1 = re.findall('unsusbscribe', text) - key_words2 = re.findall('Stop these mails', text) + for k in range(len(a["feed"]["entry"])): + text = a["feed"]["entry"][k]["summary"] + key_words1 = re.findall("unsusbscribe", text) + key_words2 = re.findall("Stop these mails", text) keys = key_words1 + key_words2 - urls = re.findall(r'''(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-&?=%.]+''', text) + urls = re.findall( + r"""(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-&?=%.]+""", text + ) if len(keys) > 0 and len(urls) > 0: - print(a['feed']['entry'][k]['title']) - print(a['feed']['entry'][k]['summary'][0:50]) - print(a['feed']['entry'][k]['author']['email']) + print(a["feed"]["entry"][k]["title"]) + print(a["feed"]["entry"][k]["summary"][0:50]) + print(a["feed"]["entry"][k]["author"]["email"]) print(urls) - print('----------') + print("----------") diff --git a/email_phone_extractor/extract-phone-email.py b/email_phone_extractor/extract-phone-email.py index 7c901227f..0d24304bd 100644 --- a/email_phone_extractor/extract-phone-email.py +++ b/email_phone_extractor/extract-phone-email.py @@ -1,21 +1,25 @@ +import csv import os +import re import sys -import csv + import pyperclip -import re # Create phone regex. phoneRegex = re.compile( - r'''(\(?([\d]{3})\)?[\.|\s|\-]*([\d]{3})[\.|\s|\-]*([\d]{4}))''', - re.VERBOSE) + r"""(\(?([\d]{3})\)?[\.|\s|\-]*([\d]{3})[\.|\s|\-]*([\d]{4}))""", re.VERBOSE +) # Create email regex. -emailRegex = re.compile(r'''( +emailRegex = re.compile( + r"""( [a-zA-Z0-9._%+-] + #username @ # @symbole [a-zA-Z0-9.-] + # domain (\.[a-zA-Z]{2,4}) # dot-something - )''', re.VERBOSE) + )""", + re.VERBOSE, +) text = "" @@ -37,31 +41,33 @@ phoneMatches = [] emailMatches = [] for groups in phoneRegex.findall(text): - phoneNum = '-'.join([groups[1], groups[2], groups[3]]) + phoneNum = "-".join([groups[1], groups[2], groups[3]]) phoneMatches.append(phoneNum) for groups in emailRegex.findall(text): emailMatches.append(groups[0]) -if (len(phoneMatches) > 0 or len(emailMatches)): - matches = '\n'.join(phoneMatches) + '\n' + '\n'.join(emailMatches) +if len(phoneMatches) > 0 or len(emailMatches): + matches = "\n".join(phoneMatches) + "\n" + "\n".join(emailMatches) pyperclip.copy(matches) - print('Copied to clipboard!') + print("Copied to clipboard!") s = pyperclip.paste() - print("Phone Numbers - \n\t" - + '\n\t'.join(phoneMatches) - + "\nEmails - \n\t" - + '\n\t'.join(emailMatches)) + print( + "Phone Numbers - \n\t" + + "\n\t".join(phoneMatches) + + "\nEmails - \n\t" + + "\n\t".join(emailMatches) + ) - with open('phones.csv', 'w') as f: + with open("phones.csv", "w") as f: # using csv.writer method from CSV package write = csv.writer(f) write.writerows([phoneMatches]) print("Phone numbers saved to phones.csv") - with open('emails.csv', 'w') as f: + with open("emails.csv", "w") as f: # using csv.writer method from CSV package write = csv.writer(f) write.writerows([emailMatches]) print("Phone numbers saved to emails.csv") else: - print('No phone numbers or email addresses found.') + print("No phone numbers or email addresses found.") diff --git a/email_sender/__init__.py b/email_sender/__init__.py index 49d5ebd4c..67a43f6d0 100644 --- a/email_sender/__init__.py +++ b/email_sender/__init__.py @@ -1,2 +1,2 @@ __author__ = "Sam Culley" -__version__ = '0.1' +__version__ = "0.1" diff --git a/email_sender/email_sender.py b/email_sender/email_sender.py index 8d93a0ae1..652d0dda9 100644 --- a/email_sender/email_sender.py +++ b/email_sender/email_sender.py @@ -1,13 +1,12 @@ -import smtplib import argparse import logging +import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class EmailSender(object): - def __init__(self, host="localhost", port=25, username=None, - password=None): + def __init__(self, host="localhost", port=25, username=None, password=None): self.host = host self.port = port # we can have no username/password but no host or port @@ -15,9 +14,9 @@ def __init__(self, host="localhost", port=25, username=None, self.password = password or None # setup logging logging.basicConfig( - format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', - level=logging.INFO) - self.logger = logging.getLogger('EmailSender') + format="%(asctime)s:%(levelname)s:%(name)s:%(message)s", level=logging.INFO + ) + self.logger = logging.getLogger("EmailSender") def email_message_input(self): """initialises a keyboard based prompt to users of the command line @@ -27,8 +26,7 @@ def email_message_input(self): :return: object contain the email message provided by the user """ try: - self.logger.info("Enter/Paste your email. Ctrl-D or Ctrl-Z " - "to save it") + self.logger.info("Enter/Paste your email. Ctrl-D or Ctrl-Z " "to save it") contents = [] while True: try: @@ -37,7 +35,7 @@ def email_message_input(self): break contents.append(line) - return '\n'.join(contents) + return "\n".join(contents) except Exception as e: self.logger.error(f"Unable to process email message input: {e}") raise Exception("Unable to process email message input") @@ -55,18 +53,27 @@ def prepare_email(self, subject, from_email, to_email, body): """ try: msg = MIMEMultipart() - msg['Subject'] = subject - msg['From'] = from_email - msg['To'] = to_email - msg.attach(MIMEText(body, 'plain')) + msg["Subject"] = subject + msg["From"] = from_email + msg["To"] = to_email + msg.attach(MIMEText(body, "plain")) return msg.as_string() except Exception as error: self.logger.error(f"Unable to prepare email message: {error}") raise Exception("Unable to prepare email message") - def send_email(self, subject, from_email, to_email, msg, - host=None, port=None, username=None, password=None): + def send_email( + self, + subject, + from_email, + to_email, + msg, + host=None, + port=None, + username=None, + password=None, + ): """Sends an email, has the options for host, port, user/pass so you can choose where to send an email. @@ -102,8 +109,7 @@ def send_email(self, subject, from_email, to_email, msg, return smtp.sendmail(from_email, to_email, email) except ConnectionRefusedError: self.logger.error(f"Error to connect to smtp://{host}:{port}") - raise Exception(f"Error to connect to smtp host: " - f"smtp://{host}:{port}") + raise Exception(f"Error to connect to smtp host: " f"smtp://{host}:{port}") except Exception as error: self.logger.error(f"Unable to send email message: {error}") raise Exception("Unable to send email message") @@ -111,45 +117,54 @@ def send_email(self, subject, from_email, to_email, msg, if __name__ == "__main__": args = argparse.ArgumentParser(description="EmailSender") - args.add_argument('--subject', help="Subject to use in the Email message", - required=True) - args.add_argument('--from_email', help="Email address to use as the from" - " address.", required=True) - args.add_argument('--to_email', help="Email address to used to send emails" - " too.", required=True) - args.add_argument('--msg', help="Email message", default=None) - args.add_argument('--host', help="SMTP Host", default="localhost") - args.add_argument('--port', help="SMTP Port", default=25, type=int) - args.add_argument('--username', help="SMTP username", default=None) - args.add_argument('--password', help="SMTP password", default=None) + args.add_argument( + "--subject", help="Subject to use in the Email message", required=True + ) + args.add_argument( + "--from_email", + help="Email address to use as the from" " address.", + required=True, + ) + args.add_argument( + "--to_email", help="Email address to used to send emails" " too.", required=True + ) + args.add_argument("--msg", help="Email message", default=None) + args.add_argument("--host", help="SMTP Host", default="localhost") + args.add_argument("--port", help="SMTP Port", default=25, type=int) + args.add_argument("--username", help="SMTP username", default=None) + args.add_argument("--password", help="SMTP password", default=None) args = args.parse_args() try: # create the EmailSender class object, using the command line options # as params - email_sender = EmailSender(host=args.host, - port=args.port, - username=args.username, - password=args.password) + email_sender = EmailSender( + host=args.host, + port=args.port, + username=args.username, + password=args.password, + ) # set the message to the message provided in the command line options # if specified, otherwise ask for input if args.msg: msg = args.msg else: - email_sender.logger.info("Email message not provided, please " - "input now!") + email_sender.logger.info("Email message not provided, please " "input now!") msg = email_sender.email_message_input() # send the email - email_sender.send_email(subject=args.subject, - from_email=args.from_email, - to_email=args.to_email, - msg=msg) + email_sender.send_email( + subject=args.subject, + from_email=args.from_email, + to_email=args.to_email, + msg=msg, + ) email_sender.logger.info("Email message successfully delivered") except Exception as e: email_sender = EmailSender() - email_sender.logger.error(f"Unable to execute the EmailSender " - f"commandline script: {e}") + email_sender.logger.error( + f"Unable to execute the EmailSender " f"commandline script: {e}" + ) diff --git a/email_validator/config.py b/email_validator/config.py index 2bcd9f265..8200a1c30 100644 --- a/email_validator/config.py +++ b/email_validator/config.py @@ -1 +1 @@ -api_key = "API_KEY" # Paste your API-Key here +api_key = "API_KEY" # Paste your API-Key here diff --git a/email_validator/main.py b/email_validator/main.py index ab4306e82..083902bee 100644 --- a/email_validator/main.py +++ b/email_validator/main.py @@ -1,10 +1,10 @@ import config -# The quickemailverification module allows -# us to verify email addresses in bulk. -import quickemailverification # The openpyxl module allows your Python programs # to read and modify Excel spreadsheet files. import openpyxl +# The quickemailverification module allows +# us to verify email addresses in bulk. +import quickemailverification from openpyxl.styles import Font @@ -13,41 +13,42 @@ def write_header_row(): sheet = wb.active # Change the sheet name of the workbook sheet.title = "Email Validator" - sheet.column_dimensions['A'].width = 30 - sheet.column_dimensions['C'].width = 20 - sheet.column_dimensions['D'].width = 17 - sheet.column_dimensions['E'].width = 17 - sheet.column_dimensions['H'].width = 25 - sheet.column_dimensions['I'].width = 14 - sheet.column_dimensions['J'].width = 40 - sheet.column_dimensions['K'].width = 20 - sheet.column_dimensions['L'].width = 20 - sheet.column_dimensions['M'].width = 30 - sheet.column_dimensions['N'].width = 10 - sheet.column_dimensions['O'].width = 20 + sheet.column_dimensions["A"].width = 30 + sheet.column_dimensions["C"].width = 20 + sheet.column_dimensions["D"].width = 17 + sheet.column_dimensions["E"].width = 17 + sheet.column_dimensions["H"].width = 25 + sheet.column_dimensions["I"].width = 14 + sheet.column_dimensions["J"].width = 40 + sheet.column_dimensions["K"].width = 20 + sheet.column_dimensions["L"].width = 20 + sheet.column_dimensions["M"].width = 30 + sheet.column_dimensions["N"].width = 10 + sheet.column_dimensions["O"].width = 20 header_row_font = Font(size=14, bold=True) labels = { - 'A': "Email", - 'B': "Result", - 'C': "Reason", - 'D': "Disposable", - 'E': "Accept All", - 'F': "Role", - 'G': "Free", - 'H': "User", - 'I': "Domain", - 'J': "MX Record", - 'K': "MX Domain", - 'L': "Safe to Send", - 'M': "Did You Mean?", - 'N': "Success", - 'O': "Message"} + "A": "Email", + "B": "Result", + "C": "Reason", + "D": "Disposable", + "E": "Accept All", + "F": "Role", + "G": "Free", + "H": "User", + "I": "Domain", + "J": "MX Record", + "K": "MX Domain", + "L": "Safe to Send", + "M": "Did You Mean?", + "N": "Success", + "O": "Message", + } for column in labels: label = labels[column] - sheet[f'{column}1'].font = header_row_font - sheet[f'{column}1'] = label - wb.save('result.xlsx') + sheet[f"{column}1"].font = header_row_font + sheet[f"{column}1"] = label + wb.save("result.xlsx") def add_data_in_column(response): @@ -55,21 +56,22 @@ def add_data_in_column(response): data_font = Font(size=12) columns = { - "email": 'A', - "result": 'B', - "reason": 'C', - "disposable": 'D', - "accept_all": 'E', - "role": 'F', - "free": 'G', - "user": 'H', - "domain": 'I', - "mx_record": 'J', - "mx_domain": 'K', + "email": "A", + "result": "B", + "reason": "C", + "disposable": "D", + "accept_all": "E", + "role": "F", + "free": "G", + "user": "H", + "domain": "I", + "mx_record": "J", + "mx_domain": "K", "safe_to_send": "L", "did_you_mean": "M", - "success": 'N', - "message": 'O'} + "success": "N", + "message": "O", + } # Each time this function is called, the result # corresponding to that email would be printed on a new row. @@ -81,7 +83,7 @@ def add_data_in_column(response): column = columns[label] sheet[f"{column}{max_filled_row}"].font = data_font sheet[f"{column}{max_filled_row}"] = data - wb.save('result.xlsx') + wb.save("result.xlsx") if __name__ == "__main__": @@ -97,7 +99,7 @@ def add_data_in_column(response): emails = f.read().split("\n") for email in emails: response = quickemailverification.verify(email) - if response.body['success'] == 'false': + if response.body["success"] == "false": print("API Key is invalid. Follow the instructions ", end="") print("in README.md to get an API key.") break diff --git a/emptyfolder_cleaner/EmptyFolderCleaner.py b/emptyfolder_cleaner/EmptyFolderCleaner.py index f161ac33e..62d6fa5dd 100644 --- a/emptyfolder_cleaner/EmptyFolderCleaner.py +++ b/emptyfolder_cleaner/EmptyFolderCleaner.py @@ -8,8 +8,11 @@ def get_subdirectories(path): :param path: the path to check :return: a list with the direct subdirectories names """ - return [os.path.join(path, o) for o in os.listdir(path) - if os.path.isdir(os.path.join(path, o))] + return [ + os.path.join(path, o) + for o in os.listdir(path) + if os.path.isdir(os.path.join(path, o)) + ] def clean_empty_folders(path, removeRoot=True, verbose=False): @@ -40,7 +43,7 @@ def clean_empty_folders(path, removeRoot=True, verbose=False): return False -if __name__ == '__main__': +if __name__ == "__main__": selected_path = input("Write the desired path: ") remove_root = None while remove_root is None: diff --git a/eterm/src/AutoCompleter.py b/eterm/src/AutoCompleter.py index 8ec3c035b..3c199d81d 100644 --- a/eterm/src/AutoCompleter.py +++ b/eterm/src/AutoCompleter.py @@ -1,5 +1,4 @@ class MyCompleter: - def __init__(self, options): self.options = sorted(options) self.matches = None @@ -7,8 +6,7 @@ def __init__(self, options): def complete(self, text, state): if state == 0: if text: - self.matches = [s for s in self.options - if text in s] + self.matches = [s for s in self.options if text in s] else: self.matches = self.options[:] diff --git a/eterm/src/credsChecker.py b/eterm/src/credsChecker.py index 6f3a9ccc2..559206e8e 100644 --- a/eterm/src/credsChecker.py +++ b/eterm/src/credsChecker.py @@ -1,17 +1,20 @@ import sys from smtplib import SMTP_SSL, SMTPAuthenticationError + from colorama import Fore def check(email, password): - with SMTP_SSL('smtp.gmail.com', 465) as session: + with SMTP_SSL("smtp.gmail.com", 465) as session: try: session.login(email, password) except SMTPAuthenticationError: - print("Allow less secure apps is in the OFF " - "state by going to " - "https://myaccount.google.com/lesssecureapps . " - "Turn it on and try again. " - "make sure the Sender" - " email & password are correct.") - sys.exit(f'{Fore.RED}[-] Wrong credentials{Fore.RESET}') + print( + "Allow less secure apps is in the OFF " + "state by going to " + "https://myaccount.google.com/lesssecureapps . " + "Turn it on and try again. " + "make sure the Sender" + " email & password are correct." + ) + sys.exit(f"{Fore.RED}[-] Wrong credentials{Fore.RESET}") diff --git a/eterm/src/main.py b/eterm/src/main.py index 727a6e335..227cb46b5 100755 --- a/eterm/src/main.py +++ b/eterm/src/main.py @@ -1,8 +1,10 @@ #!/usr/bin/python3 import argparse +import email import getpass import hashlib +import imaplib import json import os import readline @@ -13,24 +15,23 @@ from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText -import imaplib -import email -from colorama import Fore, init # File imports import AutoCompleter import credsChecker +from colorama import Fore, init class EmailSender: def __init__(self): init(autoreset=True) - self.parser = argparse.ArgumentParser(description="Send Emails" - " through your terminal.", - epilog="For more info check " - "my github page " - "https://github.com/" - "mrHola21/Eterm/") + self.parser = argparse.ArgumentParser( + description="Send Emails" " through your terminal.", + epilog="For more info check " + "my github page " + "https://github.com/" + "mrHola21/Eterm/", + ) self.get_arguments() @@ -52,35 +53,65 @@ def __init__(self): self.check_credentials() def get_arguments(self): - self.parser.add_argument('from_', metavar="sender's email address", ) - self.parser.add_argument('--to', '-t', metavar="Receivers" - " email", help="receiver's " - "email address") - self.parser.add_argument('--subject', '-s', action="store_tr" - "ue", help="Add Subject to your Email.") - self.parser.add_argument('--body', '-b', action="store_" - "true", help="Add the body to your Email") - self.parser.add_argument('--file', '-f', metavar="File", type=str, - nargs='+', help="Add Files to" - " your emails") - self.parser.add_argument('--listall', '-L', action="store_" - "true", help='show all emails') - self.parser.add_argument('--list', '-l', metavar="number of" - " emails to show", action="store", type=int) - self.parser.add_argument('--verbose', '-v', action="store" - "_true", help="Get Expanded Emails") - self.parser.add_argument('--search', help="Search for" - " a specific email") - self.parser.add_argument('--server', '-S', metavar="server" - " name", type=str, help="Change " - "The SMTP server.Default is 'smtp.gmail.com'") - self.parser.add_argument('--imapserver', '-i', metavar="imap" - " server", type=str, help="Change" - " The Imap Server.Default" - " is 'imap.gmail.com'") - self.parser.add_argument('--port', '-p', metavar="port" - " number", type=int, help="Change The" - " SMTP server's port.Default is 587") + self.parser.add_argument( + "from_", + metavar="sender's email address", + ) + self.parser.add_argument( + "--to", + "-t", + metavar="Receivers" " email", + help="receiver's " "email address", + ) + self.parser.add_argument( + "--subject", "-s", action="store_tr" "ue", help="Add Subject to your Email." + ) + self.parser.add_argument( + "--body", "-b", action="store_" "true", help="Add the body to your Email" + ) + self.parser.add_argument( + "--file", + "-f", + metavar="File", + type=str, + nargs="+", + help="Add Files to" " your emails", + ) + self.parser.add_argument( + "--listall", "-L", action="store_" "true", help="show all emails" + ) + self.parser.add_argument( + "--list", + "-l", + metavar="number of" " emails to show", + action="store", + type=int, + ) + self.parser.add_argument( + "--verbose", "-v", action="store" "_true", help="Get Expanded Emails" + ) + self.parser.add_argument("--search", help="Search for" " a specific email") + self.parser.add_argument( + "--server", + "-S", + metavar="server" " name", + type=str, + help="Change " "The SMTP server.Default is 'smtp.gmail.com'", + ) + self.parser.add_argument( + "--imapserver", + "-i", + metavar="imap" " server", + type=str, + help="Change" " The Imap Server.Default" " is 'imap.gmail.com'", + ) + self.parser.add_argument( + "--port", + "-p", + metavar="port" " number", + type=int, + help="Change The" " SMTP server's port.Default is 587", + ) def route(self): if self.args.list is not None or self.args.listall or self.args.search: @@ -91,49 +122,57 @@ def route(self): def new_email(self): password = bytes( getpass.getpass( - 'First Time Entering ' - 'The Password For ' - f'{Fore.BLUE}{self.args.from_} {Fore.RESET}:'), 'utf8') - credsChecker.check(self.args.from_, password.decode('utf-8')) + "First Time Entering " + "The Password For " + f"{Fore.BLUE}{self.args.from_} {Fore.RESET}:" + ), + "utf8", + ) + credsChecker.check(self.args.from_, password.decode("utf-8")) hashed_pass = hashlib.sha512(password) x = hashed_pass.hexdigest() - json_format = {'gmail': self.args.from_, - 'password': x} - with open('pass.json', 'w+') as f: + json_format = {"gmail": self.args.from_, "password": x} + with open("pass.json", "w+") as f: json.dump(json_format, f) print(f"{Fore.CYAN}[+]Saved the Email and Password") print("Sending Email Now") self.check_credentials() def check_credentials(self): - if os.stat('pass.json').st_size != 0: - with open('pass.json', 'r') as password_file: + if os.stat("pass.json").st_size != 0: + with open("pass.json", "r") as password_file: json_data = json.load(password_file) - self.password = bytes(getpass.getpass(f'Enter Password for ' - f'{Fore.BLUE}' - f' {self.args.from_}' - f'{Fore.RESET}:'), - 'utf-8') + self.password = bytes( + getpass.getpass( + f"Enter Password for " + f"{Fore.BLUE}" + f" {self.args.from_}" + f"{Fore.RESET}:" + ), + "utf-8", + ) hashed = hashlib.sha512(self.password).hexdigest() - if json_data['gmail'] == self.args.from_: - if str(json_data['password']) == str(hashed): + if json_data["gmail"] == self.args.from_: + if str(json_data["password"]) == str(hashed): self.route() else: - print(f'{Fore.RED}Wrong Password!{Fore.RESET}') + print(f"{Fore.RED}Wrong Password!{Fore.RESET}") for i in range(1, 4): self.password = bytes( getpass.getpass( - f'{Fore.RED}{i}{Fore.RESET}' - f' Wrong Password Enter Again for ' - f'{Fore.BLUE}' - f'{self.args.from_}{Fore.RESET}:'), - 'utf8') + f"{Fore.RED}{i}{Fore.RESET}" + f" Wrong Password Enter Again for " + f"{Fore.BLUE}" + f"{self.args.from_}{Fore.RESET}:" + ), + "utf8", + ) hashed = hashlib.sha512(self.password).hexdigest() - if json_data['password'] == str(hashed): + if json_data["password"] == str(hashed): self.send_email_file() else: pass - sys.exit(f'{Fore.RED}Wrong Password') + sys.exit(f"{Fore.RED}Wrong Password") else: self.new_email() else: @@ -142,21 +181,31 @@ def check_credentials(self): def get_subject(self): try: subject_completer = AutoCompleter.MyCompleter( - [greeting.strip() for greeting in - open('Autocompletions/greeting.txt', 'r').readlines()]) + [ + greeting.strip() + for greeting in open( + "Autocompletions/greeting.txt", "r" + ).readlines() + ] + ) readline.set_completer(subject_completer.complete) - readline.parse_and_bind('tab: complete') - return input(f'{Fore.BLUE}Subject>' - f'{Fore.RESET}') if self.args.subject else None + readline.parse_and_bind("tab: complete") + return ( + input(f"{Fore.BLUE}Subject>" f"{Fore.RESET}") + if self.args.subject + else None + ) except KeyboardInterrupt: - sys.exit('\n' + "Exiting ! Did Not Send The Email.") + sys.exit("\n" + "Exiting ! Did Not Send The Email.") def get_body(self): if self.args.body: try: - print(f'{Fore.LIGHTBLACK_EX}Hint:{Fore.RESET} ' - f'Press {Fore.BLUE}Ctrl+C{Fore.RESET} to ' - 'end the message!') + print( + f"{Fore.LIGHTBLACK_EX}Hint:{Fore.RESET} " + f"Press {Fore.BLUE}Ctrl+C{Fore.RESET} to " + "end the message!" + ) while True: line = input(f"{Fore.CYAN}Body>") if line: @@ -166,7 +215,7 @@ def get_body(self): self.body_content_list.append("\n") else: break - self.body_content = '\n'.join(self.body_content_list) + self.body_content = "\n".join(self.body_content_list) except KeyboardInterrupt: print(f"\n\n{Fore.LIGHTGREEN_EX}Body done!") return self.body_content @@ -177,20 +226,22 @@ def get_recipients(self): def send_email_file(self): self.get_recipients() - self.msg['subject'] = self.get_subject() - self.msg['from'] = self.from_email - self.msg['to'] = self.to_email - text = MIMEText(self.getbody() if self.args.body else "", 'plain') + self.msg["subject"] = self.get_subject() + self.msg["from"] = self.from_email + self.msg["to"] = self.to_email + text = MIMEText(self.getbody() if self.args.body else "", "plain") self.msg.attach(text) if self.args.file: for file in self.args.file: - with open(file, 'r') as f: - payload = MIMEBase('application', 'octet-stream') + with open(file, "r") as f: + payload = MIMEBase("application", "octet-stream") payload.set_payload(f.read()) encoders.encode_base64(payload) - payload.add_header('Content-Disposition', 'attachment', - filename=self.args.file - [self.args.file.index(file)]) + payload.add_header( + "Content-Disposition", + "attachment", + filename=self.args.file[self.args.file.index(file)], + ) self.msg.attach(payload) try: if self.args.server is not None: @@ -207,10 +258,11 @@ def send_email_file(self): "Allow less secure apps is in the OFF state by going to " "https://myaccount.google.com/lesssecureapps . " "Turn it on and try again. " - "make sure the Sender email & password are correct.") + "make sure the Sender email & password are correct." + ) except socket.gaierror: sys.exit(f"{Fore.RED}Check your internet & firewall settings.") - os.system('clear' if os.name == 'posix' else 'cls') + os.system("clear" if os.name == "posix" else "cls") print(f"{Fore.GREEN} Email Send ") sys.exit(0) @@ -221,8 +273,9 @@ def read_email(self): try: mail = imaplib.IMAP4_SSL(self.imap_server) except socket.gaierror: - sys.exit(f"`{Fore.RED}{self.imap_server}{Fore.RESET}`" - " Service Not recogonised") + sys.exit( + f"`{Fore.RED}{self.imap_server}{Fore.RESET}`" " Service Not recogonised" + ) self.get_recipients() mail.login(self.from_email, str(self.password.decode())) @@ -237,7 +290,7 @@ def read_email(self): print("Total Emails:", len(selected_mails[0].split())) if not self.args.listall: - num_of_emails = selected_mails[0].split()[::-1][0:self.args.list] + num_of_emails = selected_mails[0].split()[::-1][0 : self.args.list] else: num_of_emails = selected_mails[0].split()[::-1] @@ -265,7 +318,7 @@ def concise(): print("Fetching...") for num in num_of_emails: - _, data = mail.fetch(num, '(RFC822)') + _, data = mail.fetch(num, "(RFC822)") _, bytes_data = data[0] email_message = email.message_from_bytes(bytes_data) @@ -276,5 +329,5 @@ def concise(): concise() -if __name__ == '__main__': +if __name__ == "__main__": send = EmailSender() diff --git a/excel_inspector/excel_inspector.py b/excel_inspector/excel_inspector.py index ab7080723..f9d638a93 100644 --- a/excel_inspector/excel_inspector.py +++ b/excel_inspector/excel_inspector.py @@ -1,17 +1,18 @@ # Parse spreadsheets and its sheets =========================================== -import pandas as pd import os +import pandas as pd + # add your folder path -sheets_folder = r'' +sheets_folder = r"" for path, subdirs, files in os.walk(sheets_folder): for filename in files: - print('\n [] File:', filename, '===============') - if filename.endswith('.xlsx'): - excel = pd.ExcelFile(path + '\\' + filename) - print('Number of sheets:', len(excel.sheet_names)) - print('Sheet names:', excel.sheet_names) + print("\n [] File:", filename, "===============") + if filename.endswith(".xlsx"): + excel = pd.ExcelFile(path + "\\" + filename) + print("Number of sheets:", len(excel.sheet_names)) + print("Sheet names:", excel.sheet_names) for sheet in excel.sheet_names: df = excel.parse(sheet) - print('Sheet:', sheet, ' with the columns:', list(df.columns)) + print("Sheet:", sheet, " with the columns:", list(df.columns)) diff --git a/excel_to_csv/excel_to_csv.py b/excel_to_csv/excel_to_csv.py index dd22afd00..e19161699 100644 --- a/excel_to_csv/excel_to_csv.py +++ b/excel_to_csv/excel_to_csv.py @@ -1,10 +1,11 @@ -import openpyxl import csv +import openpyxl + print("Enter Path of your Excel file") xls_file = input() -csv_file = 'mycsvfile.csv' -mode = 'w' +csv_file = "mycsvfile.csv" +mode = "w" wb = openpyxl.load_workbook(xls_file) sh = wb.active diff --git a/excel_tools/excel-tools.py b/excel_tools/excel-tools.py index d35ab9670..52b9db453 100644 --- a/excel_tools/excel-tools.py +++ b/excel_tools/excel-tools.py @@ -5,6 +5,7 @@ # download and install openpyxl import openpyxl + print("enter the name of the excel file") path = input() wb_obj = openpyxl.load_workbook(path) @@ -33,6 +34,7 @@ print("enter your workbook name eg name.xlsx") s = input() from openpyxl import Workbook + wbk = Workbook() wbk.save(filename=s) sheet = wbk.active @@ -72,14 +74,14 @@ print("if you want to create a bar chart type CHART") if input() == "CHART": from openpyxl.chart import BarChart3D, Reference + print("how many columns do you want") lel = int(input()) print("enter", lel, " values") for i in range(lel): b = int(input()) sheet.append([b]) - values = Reference(sheet, min_col=1, min_row=1, - max_col=1, max_row=lel) + values = Reference(sheet, min_col=1, min_row=1, max_col=1, max_row=lel) chart = BarChart3D() chart.add_data(values) print("enter chart title") diff --git a/expense_manager/app.py b/expense_manager/app.py index 486006912..6348ce538 100644 --- a/expense_manager/app.py +++ b/expense_manager/app.py @@ -1,6 +1,7 @@ -import db import tkinter as tk -from tkinter.ttk import Button, Frame, Entry, Label +from tkinter.ttk import Button, Entry, Frame, Label + +import db LARGE_FONT = ("Verdana", 32) @@ -51,7 +52,9 @@ def main_window(self): button2 = Button(self.frame, text="Household expenses", command=self.household) button2.pack() - button3 = Button(self.frame, text="Entertainment expenses", command=self.entertainment) + button3 = Button( + self.frame, text="Entertainment expenses", command=self.entertainment + ) button3.pack() button4 = Button(self.frame, text="Other expenses", command=self.other) @@ -63,7 +66,7 @@ def main_window(self): # INSERT VALUES def groceries(self): top = tk.Toplevel(self.frame) - top.title('Groceries expenses') + top.title("Groceries expenses") Label(top, text="Name of good").grid(row=1, column=0, sticky=tk.W, pady=2) Label(top, text="Price").grid(row=2, column=0, sticky=tk.W, pady=2) Label(top, text="Date of purchase").grid(row=3, column=0, sticky=tk.W, pady=2) @@ -80,20 +83,44 @@ def groceries(self): # BUTTONS - B1 = Button(top, text="Insert Values", command=lambda: (self.insert(db.insert_groceries, e1, e2, e3), - self.added(top))) + B1 = Button( + top, + text="Insert Values", + command=lambda: ( + self.insert(db.insert_groceries, e1, e2, e3), + self.added(top), + ), + ) B1.grid(row=1, column=2) - B2 = Button(top, text="Select All", command=lambda: (text.delete(1.0, tk.END), - text.insert(tk.END, self.display_all(db.select_all_groceries())))) + B2 = Button( + top, + text="Select All", + command=lambda: ( + text.delete(1.0, tk.END), + text.insert(tk.END, self.display_all(db.select_all_groceries())), + ), + ) B2.grid(row=2, column=2) - B3 = Button(top, text="Find value", command=lambda: (text.delete(1.0, tk.END), - text.insert(tk.END, self.find_expense(db.select_grocery, e1, e2)))) + B3 = Button( + top, + text="Find value", + command=lambda: ( + text.delete(1.0, tk.END), + text.insert(tk.END, self.find_expense(db.select_grocery, e1, e2)), + ), + ) B3.grid(row=2, column=3) - B3 = Button(top, text="Delete expense", command=lambda: (self.delete_expense(db.delete_grocery, e1, e2), - self.delete(top))) + B3 = Button( + top, + text="Delete expense", + command=lambda: ( + self.delete_expense(db.delete_grocery, e1, e2), + self.delete(top), + ), + ) B3.grid(row=4, column=2) B5 = Button(top, text="Exit", command=exit) @@ -101,7 +128,7 @@ def groceries(self): def household(self): top = tk.Toplevel(self.frame) - top.title('Household expenses') + top.title("Household expenses") Label(top, text="Name of good").grid(row=1, column=0, sticky=tk.W, pady=2) Label(top, text="Price").grid(row=2, column=0, sticky=tk.W, pady=2) Label(top, text="Date of purchase").grid(row=3, column=0, sticky=tk.W, pady=2) @@ -118,20 +145,44 @@ def household(self): # BUTTONS### - B1 = Button(top, text="Insert Values", - command=lambda: (self.insert(db.insert_household, e1, e2, e3), self.added(top))) + B1 = Button( + top, + text="Insert Values", + command=lambda: ( + self.insert(db.insert_household, e1, e2, e3), + self.added(top), + ), + ) B1.grid(row=1, column=2) - B2 = Button(top, text="Select All", command=lambda: (text.delete(1.0, tk.END), - text.insert(tk.END, self.display_all(db.select_all_household())))) + B2 = Button( + top, + text="Select All", + command=lambda: ( + text.delete(1.0, tk.END), + text.insert(tk.END, self.display_all(db.select_all_household())), + ), + ) B2.grid(row=2, column=2) - B3 = Button(top, text="Find value", command=lambda: (text.delete(1.0, tk.END), - text.insert(tk.END, self.find_expense(db.select_household, e1, e2)))) + B3 = Button( + top, + text="Find value", + command=lambda: ( + text.delete(1.0, tk.END), + text.insert(tk.END, self.find_expense(db.select_household, e1, e2)), + ), + ) B3.grid(row=2, column=3) - B3 = Button(top, text="Delete expense", - command=lambda: (self.delete_expense(db.delete_household, e1, e2), self.delete(top))) + B3 = Button( + top, + text="Delete expense", + command=lambda: ( + self.delete_expense(db.delete_household, e1, e2), + self.delete(top), + ), + ) B3.grid(row=4, column=2) B5 = Button(top, text="Exit", command=exit) @@ -139,7 +190,7 @@ def household(self): def entertainment(self): top = tk.Toplevel(self.frame) - top.title('Entertainment expenses') + top.title("Entertainment expenses") Label(top, text="Name of good").grid(row=1, column=0, sticky=tk.W, pady=2) Label(top, text="Price").grid(row=2, column=0, sticky=tk.W, pady=2) Label(top, text="Date of purchase").grid(row=3, column=0, sticky=tk.W, pady=2) @@ -156,20 +207,44 @@ def entertainment(self): # BUTTONS - B1 = Button(top, text="Insert Values", - command=lambda: (self.insert(db.insert_entertrainment, e1, e2, e3), self.added(top))) + B1 = Button( + top, + text="Insert Values", + command=lambda: ( + self.insert(db.insert_entertrainment, e1, e2, e3), + self.added(top), + ), + ) B1.grid(row=1, column=2) - B2 = Button(top, text="Select All", command=lambda: (text.delete(1.0, tk.END), - text.insert(tk.END, self.display_all(db.select_all_entertrainment())))) + B2 = Button( + top, + text="Select All", + command=lambda: ( + text.delete(1.0, tk.END), + text.insert(tk.END, self.display_all(db.select_all_entertrainment())), + ), + ) B2.grid(row=2, column=2) - B3 = Button(top, text="Find value", command=lambda: (text.delete(1.0, tk.END), - text.insert(tk.END, self.find_expense(db.select_entertainment, e1, e2)))) + B3 = Button( + top, + text="Find value", + command=lambda: ( + text.delete(1.0, tk.END), + text.insert(tk.END, self.find_expense(db.select_entertainment, e1, e2)), + ), + ) B3.grid(row=2, column=3) - B3 = Button(top, text="Delete expense", - command=lambda: (self.delete_expense(db.delete_entertainment, e1, e2), self.delete(top))) + B3 = Button( + top, + text="Delete expense", + command=lambda: ( + self.delete_expense(db.delete_entertainment, e1, e2), + self.delete(top), + ), + ) B3.grid(row=4, column=2) B5 = Button(top, text="Exit", command=exit) @@ -177,7 +252,7 @@ def entertainment(self): def other(self): top = tk.Toplevel(self.frame) - top.title('Entertainment expenses') + top.title("Entertainment expenses") Label(top, text="Name of good").grid(row=1, column=0, sticky=tk.W, pady=2) Label(top, text="Price").grid(row=2, column=0, sticky=tk.W, pady=2) Label(top, text="Date of purchase").grid(row=3, column=0, sticky=tk.W, pady=2) @@ -194,20 +269,41 @@ def other(self): # BUTTONS### - B1 = Button(top, text="Insert Values", - command=lambda: (self.insert(db.insert_other, e1, e2, e3), self.added(top))) + B1 = Button( + top, + text="Insert Values", + command=lambda: (self.insert(db.insert_other, e1, e2, e3), self.added(top)), + ) B1.grid(row=1, column=2) - B2 = Button(top, text="Select All", command=lambda: ( - text.delete(1.0, tk.END), text.insert(tk.END, self.display_all(db.select_all_other())))) + B2 = Button( + top, + text="Select All", + command=lambda: ( + text.delete(1.0, tk.END), + text.insert(tk.END, self.display_all(db.select_all_other())), + ), + ) B2.grid(row=2, column=2) - B3 = Button(top, text="Find value", command=lambda: ( - text.delete(1.0, tk.END), text.insert(tk.END, self.find_expense(db.select_other, e1, e2)))) + B3 = Button( + top, + text="Find value", + command=lambda: ( + text.delete(1.0, tk.END), + text.insert(tk.END, self.find_expense(db.select_other, e1, e2)), + ), + ) B3.grid(row=2, column=3) - B3 = Button(top, text="Delete expense", - command=lambda: (self.delete_expense(db.delete_other, e1, e2), self.delete(top))) + B3 = Button( + top, + text="Delete expense", + command=lambda: ( + self.delete_expense(db.delete_other, e1, e2), + self.delete(top), + ), + ) B3.grid(row=4, column=2) B5 = Button(top, text="Exit", command=exit) @@ -217,7 +313,7 @@ def other(self): def main(): # db.create_tables(connection) root = tk.Tk() - root.geometry('600x500') + root.geometry("600x500") root.title("Expense Manager") ExpenseManager(root) root.mainloop() diff --git a/expense_manager/db.py b/expense_manager/db.py index 825342249..0c1c98358 100644 --- a/expense_manager/db.py +++ b/expense_manager/db.py @@ -1,5 +1,6 @@ -import sqlite3 import datetime +import sqlite3 + now = datetime.datetime.utcnow() CREATE_GROCERIES = "CREATE TABLE IF NOT EXISTS groceries (id INTEGER PRIMARY KEY,good TEXT, price INTEGER, date DATE);" @@ -33,15 +34,16 @@ def create_tables(): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: return conn.execute(CREATE_OTHER) + # INSERT VALUES def insert_groceries(good, price, date): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(INSERT_GROCERIES, (good, price, date)) @@ -49,7 +51,7 @@ def insert_groceries(good, price, date): def insert_household(good, price, date): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(INSERT_HOUSEHOLD, (good, price, date)) @@ -58,7 +60,7 @@ def insert_household(good, price, date): def insert_entertrainment(good, price, date): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(INSERT_ENTERTAINMENT, (good, price, date)) @@ -67,133 +69,135 @@ def insert_entertrainment(good, price, date): def insert_other(good, price, date): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(INSERT_OTHER, (good, price, date)) conn.commit() c.close() + # SELECT_ALL def select_all_groceries(): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(SELECT_ALL1) # have to store data into a list of Tuple list = c.fetchall() c.close() - output = '' + output = "" for x in list: - output = output + str(x[1]) + ' ' + str(x[2]) + ' ' + ' ' + str(x[3]) + '\n' + output = output + str(x[1]) + " " + str(x[2]) + " " + " " + str(x[3]) + "\n" return output def select_all_household(): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(SELECT_ALL2) # have to store data into a list of Tuple list = c.fetchall() c.close() - output = '' + output = "" for x in list: - output = output + str(x[1]) + ' ' + str(x[2]) + ' ' + ' ' + str(x[3]) + '\n' + output = output + str(x[1]) + " " + str(x[2]) + " " + " " + str(x[3]) + "\n" return output def select_all_entertrainment(): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(SELECT_ALL3) # have to store data into a list of Tuple list = c.fetchall() c.close() - output = '' + output = "" for x in list: - output = output + str(x[1]) + ' ' + str(x[2]) + ' ' + ' ' + str(x[3]) + '\n' + output = output + str(x[1]) + " " + str(x[2]) + " " + " " + str(x[3]) + "\n" return output def select_all_other(): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(SELECT_ALL4) # have to store data into a list of Tuple list = c.fetchall() c.close() - output = '' + output = "" for x in list: - output = output + str(x[1]) + ' ' + str(x[2]) + ' ' + ' ' + str(x[3]) + '\n' + output = output + str(x[1]) + " " + str(x[2]) + " " + " " + str(x[3]) + "\n" return output + # SELECT SPECIFIC def select_grocery(good, price): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(SELECT_GROCERIES, (good, price)) # have to store data into a list of Tuple list = c.fetchall() c.close() - output = '' + output = "" for x in list: - output = output + str(x[1]) + ' ' + str(x[2]) + ' ' + ' ' + str(x[3]) + '\n' + output = output + str(x[1]) + " " + str(x[2]) + " " + " " + str(x[3]) + "\n" return output def select_household(good, price): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(SELECT_HOUSEHOLD, (good, price)) # have to store data into a list of Tuple list = c.fetchall() c.close() - output = '' + output = "" for x in list: - output = output + str(x[1]) + ' ' + str(x[2]) + ' ' + ' ' + str(x[3]) + '\n' + output = output + str(x[1]) + " " + str(x[2]) + " " + " " + str(x[3]) + "\n" return output def select_entertainment(good, price): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(SELECT_ENTERTAINMENT, (good, price)) # have to store data into a list of Tuple list = c.fetchall() c.close() - output = '' + output = "" for x in list: - output = output + str(x[1]) + ' ' + str(x[2]) + ' ' + ' ' + str(x[3]) + '\n' + output = output + str(x[1]) + " " + str(x[2]) + " " + " " + str(x[3]) + "\n" return output def select_other(good, price): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(SELECT_OTHER, (good, price)) # have to store data into a list of Tuple list = c.fetchall() c.close() - output = '' + output = "" for x in list: - output = output + str(x[1]) + ' ' + str(x[2]) + ' ' + ' ' + str(x[3]) + '\n' + output = output + str(x[1]) + " " + str(x[2]) + " " + " " + str(x[3]) + "\n" return output # DELETE VALUE def delete_grocery(good, price): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(DELETE_GROCERIES, (good, price)) @@ -202,7 +206,7 @@ def delete_grocery(good, price): def delete_household(good, price): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(DELETE_HOUSEHOLD, (good, price)) @@ -211,7 +215,7 @@ def delete_household(good, price): def delete_entertainment(good, price): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(DELETE_ENTERTAINMENT, (good, price)) @@ -220,7 +224,7 @@ def delete_entertainment(good, price): def delete_other(good, price): - conn = sqlite3.connect('data.db') + conn = sqlite3.connect("data.db") with conn: c = conn.cursor() c.execute(DELETE_OTHER, (good, price)) diff --git a/extract_text_from_pdf/extract_text_from_pdf.py b/extract_text_from_pdf/extract_text_from_pdf.py index 8cb13d086..23620ffc3 100644 --- a/extract_text_from_pdf/extract_text_from_pdf.py +++ b/extract_text_from_pdf/extract_text_from_pdf.py @@ -1,8 +1,9 @@ # import module PyPDF2 import PyPDF2 + # put 'example.pdf' in working directory # and open it in read binary mode -pdfFileObj = open('example.pdf', 'rb') +pdfFileObj = open("example.pdf", "rb") # call and store PdfFileReader # object in pdfReader pdfReader = PyPDF2.PdfFileReader(pdfFileObj) diff --git a/eye_blink_reminder/eye_blink_reminder.py b/eye_blink_reminder/eye_blink_reminder.py index 69cd3332d..9bdb8884c 100644 --- a/eye_blink_reminder/eye_blink_reminder.py +++ b/eye_blink_reminder/eye_blink_reminder.py @@ -1,19 +1,19 @@ +import multiprocessing import os -import playsound from time import sleep -import multiprocessing + +import playsound def remind(): while True: sleep(20 * 60) os.popen('osascript -e "set Volume 6"') - p = multiprocessing.Process( - target=playsound.playsound, args=("danger.mp3",)) + p = multiprocessing.Process(target=playsound.playsound, args=("danger.mp3",)) p.start() - inp = input('Dismiss? y|n') + inp = input("Dismiss? y|n") - if inp == 'y': + if inp == "y": print("yes") p.terminate() continue diff --git a/eye_detection/eye_detector.py b/eye_detection/eye_detector.py index 9af7fe35a..f71ae238d 100644 --- a/eye_detection/eye_detector.py +++ b/eye_detection/eye_detector.py @@ -1,8 +1,9 @@ import cv2 + face_cascade = cv2.CascadeClassifier( - cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') -eye_cascade = cv2.CascadeClassifier( - cv2.data.haarcascades + 'haarcascade_eye.xml') + cv2.data.haarcascades + "haarcascade_frontalface_default.xml" +) +eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_eye.xml") cap = cv2.VideoCapture(0) while 1: ret, img = cap.read() @@ -10,13 +11,13 @@ faces = face_cascade.detectMultiScale(gray, 1.3, 5) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) - roi_gray = gray[y:y + h, x:x + w] - roi_color = img[y:y + h, x:x + w] + roi_gray = gray[y : y + h, x : x + w] + roi_color = img[y : y + h, x : x + w] eyes = eye_cascade.detectMultiScale(roi_gray) for (ex, ey, ew, eh) in eyes: cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2) - cv2.imshow('Web Cam Input', img) - k = cv2.waitKey(30) & 0xff + cv2.imshow("Web Cam Input", img) + k = cv2.waitKey(30) & 0xFF if k == 27: break cap.release() diff --git a/face_detection/main.py b/face_detection/main.py index e8415a1f0..5df88cf2b 100644 --- a/face_detection/main.py +++ b/face_detection/main.py @@ -11,10 +11,7 @@ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( - gray, - scaleFactor=1.1, - minNeighbors=5, - minSize=(30, 30) + gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30) ) # Draw a rectangle around the faces @@ -22,9 +19,9 @@ cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) # Display the resulting frame - cv2.imshow('Video', frame) + cv2.imshow("Video", frame) - if cv2.waitKey(1) & 0xFF == ord('q'): + if cv2.waitKey(1) & 0xFF == ord("q"): break # When everything is done, release the capture diff --git a/face_morpher/facemorphing.py b/face_morpher/facemorphing.py index de4382927..01b902ecd 100644 --- a/face_morpher/facemorphing.py +++ b/face_morpher/facemorphing.py @@ -1,5 +1,6 @@ -import numpy as np import cv2 +import numpy as np + # import sys # Read points from text file @@ -15,6 +16,7 @@ def readPoints(path): return points + # Apply affine transform calculated using srcTri and dstTri to src and # output an image of size. @@ -23,9 +25,14 @@ def applyAffineTransform(src, srcTri, dstTri, size): # Given a pair of triangles, find the affine transform. warpMat = cv2.getAffineTransform(np.float32(srcTri), np.float32(dstTri)) # Apply the Affine Transform just found to the src image - dst = cv2.warpAffine(src, warpMat, (size[0], size[1]), None, - flags=cv2.INTER_LINEAR, - borderMode=cv2.BORDER_REFLECT_101) + dst = cv2.warpAffine( + src, + warpMat, + (size[0], size[1]), + None, + flags=cv2.INTER_LINEAR, + borderMode=cv2.BORDER_REFLECT_101, + ) return dst @@ -44,11 +51,11 @@ def morphTriangle(img1, img2, img, t1, t2, t, alpha): tRect.append(((t[i][0] - r[0]), (t[i][1] - r[1]))) t1Rect.append(((t1[i][0] - r1[0]), (t1[i][1] - r1[1]))) t2Rect.append(((t2[i][0] - r2[0]), (t2[i][1] - r2[1]))) - mask = np . zeros((r[3], r[2], 3), dtype=np . float32) + mask = np.zeros((r[3], r[2], 3), dtype=np.float32) cv2.fillConvexPoly(mask, np.int32(tRect), (1.0, 1.0, 1.0), 16, 0) # Apply warpImage to small rectangular patches - img1Rect = img1[r1[1]:r1[1] + r1[3], r1[0]:r1[0] + r1[2]] - img2Rect = img2[r2[1]:r2[1] + r2[3], r2[0]:r2[0] + r2[2]] + img1Rect = img1[r1[1] : r1[1] + r1[3], r1[0] : r1[0] + r1[2]] + img2Rect = img2[r2[1] : r2[1] + r2[3], r2[0] : r2[0] + r2[2]] size = (r[2], r[3]) warpImage1 = applyAffineTransform(img1Rect, t1Rect, tRect, size) warpImage2 = applyAffineTransform(img2Rect, t2Rect, tRect, size) @@ -57,11 +64,11 @@ def morphTriangle(img1, img2, img, t1, t2, t, alpha): imgRect = (1.0 - alpha) * warpImage1 + alpha * warpImage2 # Copy triangular region of the rectangular patch to the output image - img[r[1]: r[1] + r[3], r[0]: r[0] + r[2]] - img[r[1]: r[1] + r[3], r[0]: r[0] + r[2]] * (1 - mask) + imgRect * mask + img[r[1] : r[1] + r[3], r[0] : r[0] + r[2]] + img[r[1] : r[1] + r[3], r[0] : r[0] + r[2]] * (1 - mask) + imgRect * mask -if __name__ == '__main__': +if __name__ == "__main__": filename1 = r"C:\Users\Anustup\Desktop\Facemorph\hilary_clinton.jpg" filename2 = r"C:\Users\Anustup\Desktop\Facemorph\ted_cruz.jpg" alpha = 0.5 @@ -72,8 +79,8 @@ def morphTriangle(img1, img2, img, t1, t2, t, alpha): img1 = np.float32(img1) img2 = np.float32(img2) # Read array of corresponding points - points1 = readPoints(filename1 + '.txt') - points2 = readPoints(filename2 + '.txt') + points1 = readPoints(filename1 + ".txt") + points2 = readPoints(filename2 + ".txt") points = [] # Compute weighted average point coordinates for i in range(0, len(points1)): @@ -81,7 +88,7 @@ def morphTriangle(img1, img2, img, t1, t2, t, alpha): y = (1 - alpha) * points1[i][1] + alpha * points2[i][1] points.append((x, y)) # Allocate space for final output - imgMorph = np . zeros(img1 . shape, dtype=img1 . dtype) + imgMorph = np.zeros(img1.shape, dtype=img1.dtype) with open(r"C:\Users\Anustup\Desktop\Facemorph\tri.txt") as file: for line in file: x, y, z = line.split() diff --git a/face_recognition/face_recognition.py b/face_recognition/face_recognition.py index 08c9d8ee2..ae0cb9ddf 100644 --- a/face_recognition/face_recognition.py +++ b/face_recognition/face_recognition.py @@ -1,10 +1,12 @@ -import face_recognition as fr import os +import time + import cv2 import numpy as np -import time from VideoCapture import Device +import face_recognition as fr + def get_encoded_faces(): @@ -34,7 +36,7 @@ def classify_face(im): faces_encoded = list(faces.values()) known_face_names = list(faces.keys()) cam = Device() - cam.saveSnapshot('~/faces/image.jpg') + cam.saveSnapshot("~/faces/image.jpg") time.sleep(5) img = cv2.imread(im, 1) # img = cv2.resize(img, (0, 0), fx=0.5, fy=0.5) @@ -59,19 +61,26 @@ def classify_face(im): for (top, right, bottom, left), name in zip(face_locations, face_names): # Draw a box around the face - cv2.rectangle(img, (left - 20, top - 20), - (right + 20, bottom + 20), (255, 0, 0), 2) + cv2.rectangle( + img, (left - 20, top - 20), (right + 20, bottom + 20), (255, 0, 0), 2 + ) # Draw a label with a name below the face - cv2.rectangle(img, (left - 20, bottom - 15), - (right + 20, bottom + 20), (255, 0, 0), cv2.FILLED) + cv2.rectangle( + img, + (left - 20, bottom - 15), + (right + 20, bottom + 20), + (255, 0, 0), + cv2.FILLED, + ) font = cv2.FONT_HERSHEY_DUPLEX - cv2.putText(img, name, (left - 20, bottom + 15), - font, 1.0, (255, 255, 255), 2) + cv2.putText( + img, name, (left - 20, bottom + 15), font, 1.0, (255, 255, 255), 2 + ) # Display the resulting image img1 = cv2.resize(img, (960, 540)) - cv2.imshow('Result', img1) + cv2.imshow("Result", img1) cv2.waitKey(0) return face_names diff --git a/facebook_video_downloader/facebook_video_downloader.py b/facebook_video_downloader/facebook_video_downloader.py index 3df59b51e..4c766a6a6 100644 --- a/facebook_video_downloader/facebook_video_downloader.py +++ b/facebook_video_downloader/facebook_video_downloader.py @@ -1,22 +1,24 @@ import os import re + import requests import wget root = os.path.dirname(os.path.abspath(__file__)) -path = os.path.join(root, 'downloads') +path = os.path.join(root, "downloads") if not os.path.exists(path): os.mkdir(path) -link = input('Enter the link of the video: ') +link = input("Enter the link of the video: ") try: r = requests.get(link) if r.status_code == requests.codes.ok: try: sd_url = re.search('sd_src:"(.+?)"', r.text)[1] - url = re.search('hd_src:"(.+?)"', - r.text)[1] if 'hd_src' in r.text else sd_url - print('Downloading...') + url = ( + re.search('hd_src:"(.+?)"', r.text)[1] if "hd_src" in r.text else sd_url + ) + print("Downloading...") wget.download(url, path) except Exception as e: print(e) diff --git a/facemask_detector/dataset.py b/facemask_detector/dataset.py index 4f6bc77d8..7adf7363c 100644 --- a/facemask_detector/dataset.py +++ b/facemask_detector/dataset.py @@ -3,11 +3,11 @@ # IMPORTS # ====================================================================== -import torch - import os -from PIL import Image + +import torch from bs4 import BeautifulSoup +from PIL import Image ###################################################################### # Data source - https://www.kaggle.com/andrewmvd/face-mask-detection diff --git a/facemask_detector/detect_face_mask.py b/facemask_detector/detect_face_mask.py index a9173b748..9c3c62c05 100644 --- a/facemask_detector/detect_face_mask.py +++ b/facemask_detector/detect_face_mask.py @@ -3,14 +3,13 @@ # IMPORTS # ====================================================================== -import torch -from torchvision import transforms - import os import sys -from PIL import Image +import torch from model import FaceMaskDetector +from PIL import Image +from torchvision import transforms from train import plot_result # ===================================================================== diff --git a/facemask_detector/model.py b/facemask_detector/model.py index b7d7a1d03..36130bc8f 100644 --- a/facemask_detector/model.py +++ b/facemask_detector/model.py @@ -3,12 +3,11 @@ # IMPORTS # ====================================================================== +import pkbar import torch import torchvision from torchvision.models.detection.faster_rcnn import FastRCNNPredictor -import pkbar - # ===================================================================== # PyTorch class for the model # ====================================================================== @@ -25,10 +24,7 @@ def build_model(self, n_classes): pretrained=self.pretrained ) in_features = model.roi_heads.box_predictor.cls_score.in_features - model.roi_heads.box_predictor = FastRCNNPredictor( - in_features, - n_classes + 1 - ) + model.roi_heads.box_predictor = FastRCNNPredictor(in_features, n_classes + 1) self.model = model @@ -58,10 +54,7 @@ def train(self, n_epochs, learning_rate): for i, (images, annotations) in enumerate(self.data_loader): images = list(image.to(self.device) for image in images) annotations = [ - { - k: v.to(self.device) - for k, v in t.items() - } for t in annotations + {k: v.to(self.device) for k, v in t.items()} for t in annotations ] losses = self.model([images[0]], [annotations[0]]) diff --git a/facemask_detector/train.py b/facemask_detector/train.py index 610f95c9e..7c55e05fd 100644 --- a/facemask_detector/train.py +++ b/facemask_detector/train.py @@ -3,18 +3,15 @@ # IMPORTS # ====================================================================== -import torch -from torchvision import transforms - import os +import warnings +import matplotlib.patches as patches +import matplotlib.pyplot as plt +import torch from dataset import FaceMaskDataset from model import FaceMaskDetector - -import matplotlib.pyplot as plt -import matplotlib.patches as patches - -import warnings +from torchvision import transforms warnings.filterwarnings("ignore") @@ -85,11 +82,7 @@ def collate_fn(batch): # ====================================================================== # Training the Faster-RCNN model # ====================================================================== - model = FaceMaskDetector( - data_loader=data_loader, - device=device, - pretrained=True - ) + model = FaceMaskDetector(data_loader=data_loader, device=device, pretrained=True) model.build_model(n_classes=3) @@ -116,10 +109,7 @@ def collate_fn(batch): if i > iters - 1: break imgs = list(img.to(device) for img in imgs) - annotations = [ - {k: v.to(device) for k, v in t.items()} - for t in annotations - ] + annotations = [{k: v.to(device) for k, v in t.items()} for t in annotations] pred = model.predict(imgs) diff --git a/fancy_text_generator/fancy_text_generate.py b/fancy_text_generator/fancy_text_generate.py index 2216643e3..c0994f535 100644 --- a/fancy_text_generator/fancy_text_generate.py +++ b/fancy_text_generator/fancy_text_generate.py @@ -1,254 +1,250 @@ # flake8: noqa import re + class fancy(object): def bold(text): fancy_bold = { - 'a': '\uD835\uDD86'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'b': '\uD835\uDD87'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'c': '\uD835\uDD88'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'd': '\uD835\uDD89'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'e': '\uD835\uDD8A'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'f': '\uD835\uDD8B'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'g': '\uD835\uDD8C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'h': '\uD835\uDD8D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'i': '\uD835\uDD8E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'j': '\uD835\uDD8F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'k': '\uD835\uDD90'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'l': '\uD835\uDD91'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'm': '\uD835\uDD92'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'n': '\uD835\uDD93'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'o': '\uD835\uDD94'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'p': '\uD835\uDD95'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'q': '\uD835\uDD96'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'r': '\uD835\uDD97'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 's': '\uD835\uDD98'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 't': '\uD835\uDD99'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'u': '\uD835\uDD9A'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'v': '\uD835\uDD9B'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'w': '\uD835\uDD9C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'x': '\uD835\uDD9D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'y': '\uD835\uDD9E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'z': '\uD835\uDD9F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'A': '\uD835\uDD6C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'B': '\uD835\uDD6D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'C': '\uD835\uDD6E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'D': '\uD835\uDD6F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'E': '\uD835\uDD70'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'F': '\uD835\uDD71'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'G': '\uD835\uDD72'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'H': '\uD835\uDD73'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'I': '\uD835\uDD74'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'J': '\uD835\uDD75'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'K': '\uD835\uDD76'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'L': '\uD835\uDD77'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'M': '\uD835\uDD78'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'N': '\uD835\uDD79'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'O': '\uD835\uDD7A'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'P': '\uD835\uDD7B'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Q': '\uD835\uDD7C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'R': '\uD835\uDD7D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'S': '\uD835\uDD7E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'T': '\uD835\uDD7F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'U': '\uD835\uDD80'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'V': '\uD835\uDD81'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'W': '\uD835\uDD82'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'X': '\uD835\uDD83'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Y': '\uD835\uDD84'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Z': '\uD835\uDD85'.encode('utf-16', 'surrogatepass').decode('utf-16') + "a": "\uD835\uDD86".encode("utf-16", "surrogatepass").decode("utf-16"), + "b": "\uD835\uDD87".encode("utf-16", "surrogatepass").decode("utf-16"), + "c": "\uD835\uDD88".encode("utf-16", "surrogatepass").decode("utf-16"), + "d": "\uD835\uDD89".encode("utf-16", "surrogatepass").decode("utf-16"), + "e": "\uD835\uDD8A".encode("utf-16", "surrogatepass").decode("utf-16"), + "f": "\uD835\uDD8B".encode("utf-16", "surrogatepass").decode("utf-16"), + "g": "\uD835\uDD8C".encode("utf-16", "surrogatepass").decode("utf-16"), + "h": "\uD835\uDD8D".encode("utf-16", "surrogatepass").decode("utf-16"), + "i": "\uD835\uDD8E".encode("utf-16", "surrogatepass").decode("utf-16"), + "j": "\uD835\uDD8F".encode("utf-16", "surrogatepass").decode("utf-16"), + "k": "\uD835\uDD90".encode("utf-16", "surrogatepass").decode("utf-16"), + "l": "\uD835\uDD91".encode("utf-16", "surrogatepass").decode("utf-16"), + "m": "\uD835\uDD92".encode("utf-16", "surrogatepass").decode("utf-16"), + "n": "\uD835\uDD93".encode("utf-16", "surrogatepass").decode("utf-16"), + "o": "\uD835\uDD94".encode("utf-16", "surrogatepass").decode("utf-16"), + "p": "\uD835\uDD95".encode("utf-16", "surrogatepass").decode("utf-16"), + "q": "\uD835\uDD96".encode("utf-16", "surrogatepass").decode("utf-16"), + "r": "\uD835\uDD97".encode("utf-16", "surrogatepass").decode("utf-16"), + "s": "\uD835\uDD98".encode("utf-16", "surrogatepass").decode("utf-16"), + "t": "\uD835\uDD99".encode("utf-16", "surrogatepass").decode("utf-16"), + "u": "\uD835\uDD9A".encode("utf-16", "surrogatepass").decode("utf-16"), + "v": "\uD835\uDD9B".encode("utf-16", "surrogatepass").decode("utf-16"), + "w": "\uD835\uDD9C".encode("utf-16", "surrogatepass").decode("utf-16"), + "x": "\uD835\uDD9D".encode("utf-16", "surrogatepass").decode("utf-16"), + "y": "\uD835\uDD9E".encode("utf-16", "surrogatepass").decode("utf-16"), + "z": "\uD835\uDD9F".encode("utf-16", "surrogatepass").decode("utf-16"), + "A": "\uD835\uDD6C".encode("utf-16", "surrogatepass").decode("utf-16"), + "B": "\uD835\uDD6D".encode("utf-16", "surrogatepass").decode("utf-16"), + "C": "\uD835\uDD6E".encode("utf-16", "surrogatepass").decode("utf-16"), + "D": "\uD835\uDD6F".encode("utf-16", "surrogatepass").decode("utf-16"), + "E": "\uD835\uDD70".encode("utf-16", "surrogatepass").decode("utf-16"), + "F": "\uD835\uDD71".encode("utf-16", "surrogatepass").decode("utf-16"), + "G": "\uD835\uDD72".encode("utf-16", "surrogatepass").decode("utf-16"), + "H": "\uD835\uDD73".encode("utf-16", "surrogatepass").decode("utf-16"), + "I": "\uD835\uDD74".encode("utf-16", "surrogatepass").decode("utf-16"), + "J": "\uD835\uDD75".encode("utf-16", "surrogatepass").decode("utf-16"), + "K": "\uD835\uDD76".encode("utf-16", "surrogatepass").decode("utf-16"), + "L": "\uD835\uDD77".encode("utf-16", "surrogatepass").decode("utf-16"), + "M": "\uD835\uDD78".encode("utf-16", "surrogatepass").decode("utf-16"), + "N": "\uD835\uDD79".encode("utf-16", "surrogatepass").decode("utf-16"), + "O": "\uD835\uDD7A".encode("utf-16", "surrogatepass").decode("utf-16"), + "P": "\uD835\uDD7B".encode("utf-16", "surrogatepass").decode("utf-16"), + "Q": "\uD835\uDD7C".encode("utf-16", "surrogatepass").decode("utf-16"), + "R": "\uD835\uDD7D".encode("utf-16", "surrogatepass").decode("utf-16"), + "S": "\uD835\uDD7E".encode("utf-16", "surrogatepass").decode("utf-16"), + "T": "\uD835\uDD7F".encode("utf-16", "surrogatepass").decode("utf-16"), + "U": "\uD835\uDD80".encode("utf-16", "surrogatepass").decode("utf-16"), + "V": "\uD835\uDD81".encode("utf-16", "surrogatepass").decode("utf-16"), + "W": "\uD835\uDD82".encode("utf-16", "surrogatepass").decode("utf-16"), + "X": "\uD835\uDD83".encode("utf-16", "surrogatepass").decode("utf-16"), + "Y": "\uD835\uDD84".encode("utf-16", "surrogatepass").decode("utf-16"), + "Z": "\uD835\uDD85".encode("utf-16", "surrogatepass").decode("utf-16"), } - pattern = re.compile(r'(' + '|'.join(fancy_bold.keys()) + r')') + pattern = re.compile(r"(" + "|".join(fancy_bold.keys()) + r")") result = pattern.sub(lambda x: fancy_bold[x.group()], text) - return (result) - + return result def light(text): fancy_light = { - 'a': '\uD835\uDD1E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'b': '\uD835\uDD1F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'c': '\uD835\uDD20'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'd': '\uD835\uDD21'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'e': '\uD835\uDD22'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'f': '\uD835\uDD23'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'g': '\uD835\uDD24'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'h': '\uD835\uDD25'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'i': '\uD835\uDD26'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'j': '\uD835\uDD27'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'k': '\uD835\uDD28'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'l': '\uD835\uDD29'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'm': '\uD835\uDD2A'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'n': '\uD835\uDD2B'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'o': '\uD835\uDD2C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'p': '\uD835\uDD2D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'q': '\uD835\uDD2E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'r': '\uD835\uDD2F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 's': '\uD835\uDD30'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 't': '\uD835\uDD31'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'u': '\uD835\uDD32'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'v': '\uD835\uDD33'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'w': '\uD835\uDD34'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'x': '\uD835\uDD35'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'y': '\uD835\uDD36'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'z': '\uD835\uDD37'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'A': '\uD835\uDD04'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'B': '\uD835\uDD05'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'C': '\u212D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'D': '\uD835\uDD07'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'E': '\uD835\uDD08'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'F': '\uD835\uDD09'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'G': '\uD835\uDD0A'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'H': '\u210C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'I': '\u2111'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'J': '\uD835\uDD0D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'K': '\uD835\uDD0E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'L': '\uD835\uDD0F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'M': '\uD835\uDD10'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'N': '\uD835\uDD11'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'O': '\uD835\uDD12'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'P': '\uD835\uDD13'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Q': '\uD835\uDD14'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'R': '\u211C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'S': '\uD835\uDD16'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'T': '\uD835\uDD17'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'U': '\uD835\uDD18'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'V': '\uD835\uDD19'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'W': '\uD835\uDD1A'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'X': '\uD835\uDD1B'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Y': '\uD835\uDD1C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Z': '\u2128'.encode('utf-16', 'surrogatepass').decode('utf-16'), + "a": "\uD835\uDD1E".encode("utf-16", "surrogatepass").decode("utf-16"), + "b": "\uD835\uDD1F".encode("utf-16", "surrogatepass").decode("utf-16"), + "c": "\uD835\uDD20".encode("utf-16", "surrogatepass").decode("utf-16"), + "d": "\uD835\uDD21".encode("utf-16", "surrogatepass").decode("utf-16"), + "e": "\uD835\uDD22".encode("utf-16", "surrogatepass").decode("utf-16"), + "f": "\uD835\uDD23".encode("utf-16", "surrogatepass").decode("utf-16"), + "g": "\uD835\uDD24".encode("utf-16", "surrogatepass").decode("utf-16"), + "h": "\uD835\uDD25".encode("utf-16", "surrogatepass").decode("utf-16"), + "i": "\uD835\uDD26".encode("utf-16", "surrogatepass").decode("utf-16"), + "j": "\uD835\uDD27".encode("utf-16", "surrogatepass").decode("utf-16"), + "k": "\uD835\uDD28".encode("utf-16", "surrogatepass").decode("utf-16"), + "l": "\uD835\uDD29".encode("utf-16", "surrogatepass").decode("utf-16"), + "m": "\uD835\uDD2A".encode("utf-16", "surrogatepass").decode("utf-16"), + "n": "\uD835\uDD2B".encode("utf-16", "surrogatepass").decode("utf-16"), + "o": "\uD835\uDD2C".encode("utf-16", "surrogatepass").decode("utf-16"), + "p": "\uD835\uDD2D".encode("utf-16", "surrogatepass").decode("utf-16"), + "q": "\uD835\uDD2E".encode("utf-16", "surrogatepass").decode("utf-16"), + "r": "\uD835\uDD2F".encode("utf-16", "surrogatepass").decode("utf-16"), + "s": "\uD835\uDD30".encode("utf-16", "surrogatepass").decode("utf-16"), + "t": "\uD835\uDD31".encode("utf-16", "surrogatepass").decode("utf-16"), + "u": "\uD835\uDD32".encode("utf-16", "surrogatepass").decode("utf-16"), + "v": "\uD835\uDD33".encode("utf-16", "surrogatepass").decode("utf-16"), + "w": "\uD835\uDD34".encode("utf-16", "surrogatepass").decode("utf-16"), + "x": "\uD835\uDD35".encode("utf-16", "surrogatepass").decode("utf-16"), + "y": "\uD835\uDD36".encode("utf-16", "surrogatepass").decode("utf-16"), + "z": "\uD835\uDD37".encode("utf-16", "surrogatepass").decode("utf-16"), + "A": "\uD835\uDD04".encode("utf-16", "surrogatepass").decode("utf-16"), + "B": "\uD835\uDD05".encode("utf-16", "surrogatepass").decode("utf-16"), + "C": "\u212D".encode("utf-16", "surrogatepass").decode("utf-16"), + "D": "\uD835\uDD07".encode("utf-16", "surrogatepass").decode("utf-16"), + "E": "\uD835\uDD08".encode("utf-16", "surrogatepass").decode("utf-16"), + "F": "\uD835\uDD09".encode("utf-16", "surrogatepass").decode("utf-16"), + "G": "\uD835\uDD0A".encode("utf-16", "surrogatepass").decode("utf-16"), + "H": "\u210C".encode("utf-16", "surrogatepass").decode("utf-16"), + "I": "\u2111".encode("utf-16", "surrogatepass").decode("utf-16"), + "J": "\uD835\uDD0D".encode("utf-16", "surrogatepass").decode("utf-16"), + "K": "\uD835\uDD0E".encode("utf-16", "surrogatepass").decode("utf-16"), + "L": "\uD835\uDD0F".encode("utf-16", "surrogatepass").decode("utf-16"), + "M": "\uD835\uDD10".encode("utf-16", "surrogatepass").decode("utf-16"), + "N": "\uD835\uDD11".encode("utf-16", "surrogatepass").decode("utf-16"), + "O": "\uD835\uDD12".encode("utf-16", "surrogatepass").decode("utf-16"), + "P": "\uD835\uDD13".encode("utf-16", "surrogatepass").decode("utf-16"), + "Q": "\uD835\uDD14".encode("utf-16", "surrogatepass").decode("utf-16"), + "R": "\u211C".encode("utf-16", "surrogatepass").decode("utf-16"), + "S": "\uD835\uDD16".encode("utf-16", "surrogatepass").decode("utf-16"), + "T": "\uD835\uDD17".encode("utf-16", "surrogatepass").decode("utf-16"), + "U": "\uD835\uDD18".encode("utf-16", "surrogatepass").decode("utf-16"), + "V": "\uD835\uDD19".encode("utf-16", "surrogatepass").decode("utf-16"), + "W": "\uD835\uDD1A".encode("utf-16", "surrogatepass").decode("utf-16"), + "X": "\uD835\uDD1B".encode("utf-16", "surrogatepass").decode("utf-16"), + "Y": "\uD835\uDD1C".encode("utf-16", "surrogatepass").decode("utf-16"), + "Z": "\u2128".encode("utf-16", "surrogatepass").decode("utf-16"), } - pattern = re.compile(r'(' + '|'.join(fancy_light.keys()) + r')') + pattern = re.compile(r"(" + "|".join(fancy_light.keys()) + r")") result = pattern.sub(lambda x: fancy_light[x.group()], text) - return (result) - + return result def box(text): fancy_box = { - 'a': '\uD83C\uDD70'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'b': '\uD83C\uDD71'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'c': '\uD83C\uDD72'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'd': '\uD83C\uDD73'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'e': '\uD83C\uDD74'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'f': '\uD83C\uDD75'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'g': '\uD83C\uDD76'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'h': '\uD83C\uDD77'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'i': '\uD83C\uDD78'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'j': '\uD83C\uDD79'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'k': '\uD83C\uDD7A'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'l': '\uD83C\uDD7B'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'm': '\uD83C\uDD7C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'n': '\uD83C\uDD7D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'o': '\uD83C\uDD7E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'p': '\uD83C\uDD7F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'q': '\uD83C\uDD80'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'r': '\uD83C\uDD81'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 's': '\uD83C\uDD82'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 't': '\uD83C\uDD83'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'u': '\uD83C\uDD84'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'v': '\uD83C\uDD85'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'w': '\uD83C\uDD86'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'x': '\uD83C\uDD87'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'y': '\uD83C\uDD88'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'z': '\uD83C\uDD89'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'A': '\uD83C\uDD70'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'B': '\uD83C\uDD71'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'C': '\uD83C\uDD72'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'D': '\uD83C\uDD73'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'E': '\uD83C\uDD74'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'F': '\uD83C\uDD75'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'G': '\uD83C\uDD76'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'H': '\uD83C\uDD77'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'I': '\uD83C\uDD78'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'J': '\uD83C\uDD79'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'K': '\uD83C\uDD7A'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'L': '\uD83C\uDD7B'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'M': '\uD83C\uDD7C'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'N': '\uD83C\uDD7D'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'O': '\uD83C\uDD7E'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'P': '\uD83C\uDD7F'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Q': '\uD83C\uDD80'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'R': '\uD83C\uDD81'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'S': '\uD83C\uDD82'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'T': '\uD83C\uDD83'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'U': '\uD83C\uDD84'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'V': '\uD83C\uDD85'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'W': '\uD83C\uDD86'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'X': '\uD83C\uDD87'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Y': '\uD83C\uDD88'.encode('utf-16', 'surrogatepass').decode('utf-16'), - 'Z': '\uD83C\uDD89'.encode('utf-16', 'surrogatepass').decode('utf-16') + "a": "\uD83C\uDD70".encode("utf-16", "surrogatepass").decode("utf-16"), + "b": "\uD83C\uDD71".encode("utf-16", "surrogatepass").decode("utf-16"), + "c": "\uD83C\uDD72".encode("utf-16", "surrogatepass").decode("utf-16"), + "d": "\uD83C\uDD73".encode("utf-16", "surrogatepass").decode("utf-16"), + "e": "\uD83C\uDD74".encode("utf-16", "surrogatepass").decode("utf-16"), + "f": "\uD83C\uDD75".encode("utf-16", "surrogatepass").decode("utf-16"), + "g": "\uD83C\uDD76".encode("utf-16", "surrogatepass").decode("utf-16"), + "h": "\uD83C\uDD77".encode("utf-16", "surrogatepass").decode("utf-16"), + "i": "\uD83C\uDD78".encode("utf-16", "surrogatepass").decode("utf-16"), + "j": "\uD83C\uDD79".encode("utf-16", "surrogatepass").decode("utf-16"), + "k": "\uD83C\uDD7A".encode("utf-16", "surrogatepass").decode("utf-16"), + "l": "\uD83C\uDD7B".encode("utf-16", "surrogatepass").decode("utf-16"), + "m": "\uD83C\uDD7C".encode("utf-16", "surrogatepass").decode("utf-16"), + "n": "\uD83C\uDD7D".encode("utf-16", "surrogatepass").decode("utf-16"), + "o": "\uD83C\uDD7E".encode("utf-16", "surrogatepass").decode("utf-16"), + "p": "\uD83C\uDD7F".encode("utf-16", "surrogatepass").decode("utf-16"), + "q": "\uD83C\uDD80".encode("utf-16", "surrogatepass").decode("utf-16"), + "r": "\uD83C\uDD81".encode("utf-16", "surrogatepass").decode("utf-16"), + "s": "\uD83C\uDD82".encode("utf-16", "surrogatepass").decode("utf-16"), + "t": "\uD83C\uDD83".encode("utf-16", "surrogatepass").decode("utf-16"), + "u": "\uD83C\uDD84".encode("utf-16", "surrogatepass").decode("utf-16"), + "v": "\uD83C\uDD85".encode("utf-16", "surrogatepass").decode("utf-16"), + "w": "\uD83C\uDD86".encode("utf-16", "surrogatepass").decode("utf-16"), + "x": "\uD83C\uDD87".encode("utf-16", "surrogatepass").decode("utf-16"), + "y": "\uD83C\uDD88".encode("utf-16", "surrogatepass").decode("utf-16"), + "z": "\uD83C\uDD89".encode("utf-16", "surrogatepass").decode("utf-16"), + "A": "\uD83C\uDD70".encode("utf-16", "surrogatepass").decode("utf-16"), + "B": "\uD83C\uDD71".encode("utf-16", "surrogatepass").decode("utf-16"), + "C": "\uD83C\uDD72".encode("utf-16", "surrogatepass").decode("utf-16"), + "D": "\uD83C\uDD73".encode("utf-16", "surrogatepass").decode("utf-16"), + "E": "\uD83C\uDD74".encode("utf-16", "surrogatepass").decode("utf-16"), + "F": "\uD83C\uDD75".encode("utf-16", "surrogatepass").decode("utf-16"), + "G": "\uD83C\uDD76".encode("utf-16", "surrogatepass").decode("utf-16"), + "H": "\uD83C\uDD77".encode("utf-16", "surrogatepass").decode("utf-16"), + "I": "\uD83C\uDD78".encode("utf-16", "surrogatepass").decode("utf-16"), + "J": "\uD83C\uDD79".encode("utf-16", "surrogatepass").decode("utf-16"), + "K": "\uD83C\uDD7A".encode("utf-16", "surrogatepass").decode("utf-16"), + "L": "\uD83C\uDD7B".encode("utf-16", "surrogatepass").decode("utf-16"), + "M": "\uD83C\uDD7C".encode("utf-16", "surrogatepass").decode("utf-16"), + "N": "\uD83C\uDD7D".encode("utf-16", "surrogatepass").decode("utf-16"), + "O": "\uD83C\uDD7E".encode("utf-16", "surrogatepass").decode("utf-16"), + "P": "\uD83C\uDD7F".encode("utf-16", "surrogatepass").decode("utf-16"), + "Q": "\uD83C\uDD80".encode("utf-16", "surrogatepass").decode("utf-16"), + "R": "\uD83C\uDD81".encode("utf-16", "surrogatepass").decode("utf-16"), + "S": "\uD83C\uDD82".encode("utf-16", "surrogatepass").decode("utf-16"), + "T": "\uD83C\uDD83".encode("utf-16", "surrogatepass").decode("utf-16"), + "U": "\uD83C\uDD84".encode("utf-16", "surrogatepass").decode("utf-16"), + "V": "\uD83C\uDD85".encode("utf-16", "surrogatepass").decode("utf-16"), + "W": "\uD83C\uDD86".encode("utf-16", "surrogatepass").decode("utf-16"), + "X": "\uD83C\uDD87".encode("utf-16", "surrogatepass").decode("utf-16"), + "Y": "\uD83C\uDD88".encode("utf-16", "surrogatepass").decode("utf-16"), + "Z": "\uD83C\uDD89".encode("utf-16", "surrogatepass").decode("utf-16"), } - pattern = re.compile(r'(' + '|'.join(fancy_box.keys()) + r')') + pattern = re.compile(r"(" + "|".join(fancy_box.keys()) + r")") result = pattern.sub(lambda x: fancy_box[x.group()], text) return result - def sorcerer(text): fancy_sorcerer = { - 'a': '\u01DF', - 'b': '\u026E', - 'c': '\u0188', - 'd': '\u0256', - 'e': '\u025B', - 'f': '\u0284', - 'g': '\u0262', - 'h': '\u0266', - 'i': '\u0268', - 'j': '\u029D', - 'k': '\u04C4', - 'l': '\u029F', - 'm': '\u028D', - 'n': '\u057C', - 'o': '\u0585', - 'p': '\u0584', - 'q': '\u0566', - 'r': '\u0280', - 's': '\u0586', - 't': '\u0236', - 'u': '\u028A', - 'v': '\u028B', - 'w': '\u0561', - 'x': '\u04FC', - 'y': '\u028F', - 'z': '\u0290', - 'A': '\u01DF', - 'B': '\u026E', - 'C': '\u0188', - 'D': '\u0256', - 'E': '\u025B', - 'F': '\u0284', - 'G': '\u0262', - 'H': '\u0266', - 'I': '\u0268', - 'J': '\u029D', - 'K': '\u04C4', - 'L': '\u029F', - 'M': '\u028D', - 'N': '\u057C', - 'O': '\u0585', - 'P': '\u0584', - 'Q': '\u0566', - 'R': '\u0280', - 'S': '\u0586', - 'T': '\u0236', - 'U': '\u028A', - 'V': '\u028B', - 'W': '\u0561', - 'X': '\u04FC', - 'Y': '\u028F', - 'Z': '\u0290' - + "a": "\u01DF", + "b": "\u026E", + "c": "\u0188", + "d": "\u0256", + "e": "\u025B", + "f": "\u0284", + "g": "\u0262", + "h": "\u0266", + "i": "\u0268", + "j": "\u029D", + "k": "\u04C4", + "l": "\u029F", + "m": "\u028D", + "n": "\u057C", + "o": "\u0585", + "p": "\u0584", + "q": "\u0566", + "r": "\u0280", + "s": "\u0586", + "t": "\u0236", + "u": "\u028A", + "v": "\u028B", + "w": "\u0561", + "x": "\u04FC", + "y": "\u028F", + "z": "\u0290", + "A": "\u01DF", + "B": "\u026E", + "C": "\u0188", + "D": "\u0256", + "E": "\u025B", + "F": "\u0284", + "G": "\u0262", + "H": "\u0266", + "I": "\u0268", + "J": "\u029D", + "K": "\u04C4", + "L": "\u029F", + "M": "\u028D", + "N": "\u057C", + "O": "\u0585", + "P": "\u0584", + "Q": "\u0566", + "R": "\u0280", + "S": "\u0586", + "T": "\u0236", + "U": "\u028A", + "V": "\u028B", + "W": "\u0561", + "X": "\u04FC", + "Y": "\u028F", + "Z": "\u0290", } - pattern = re.compile(r'(' + '|'.join(fancy_sorcerer.keys()) + r')') + pattern = re.compile(r"(" + "|".join(fancy_sorcerer.keys()) + r")") result = pattern.sub(lambda x: fancy_sorcerer[x.group()], text) - return (result) + return result -ch = 'y' -while(ch=='y' or ch=='Y'): - text = input('Enter the text you want to make fancy:') +ch = "y" +while ch == "y" or ch == "Y": + text = input("Enter the text you want to make fancy:") print(fancy.box(text)) print(fancy.sorcerer(text)) print(fancy.light(text)) print(fancy.bold(text)) - ch = input('Want to enter more press y/Y:') - + ch = input("Want to enter more press y/Y:") diff --git a/file_arranger/file_arranger.py b/file_arranger/file_arranger.py index 71784caad..31b141eb9 100644 --- a/file_arranger/file_arranger.py +++ b/file_arranger/file_arranger.py @@ -16,7 +16,7 @@ def organize_junk(): file_path.rename(directory_path.joinpath(file_path)) else: - directory_path = Path('Others') + directory_path = Path("Others") directory_path.mkdir(exist_ok=True) file_path.rename(directory_path.joinpath(file_path)) @@ -28,28 +28,71 @@ def organize_junk(): DIRECTORIES = { - "Webpages": [".html5", ".html", ".htm", ".xhtml", ".aspx", ".php"], - - "Images": [".jpg", ".jpeg", ".png", ".tiff", ".gif", ".bmp", ".bpg", ".svg", - ".heif", ".psd"], - - "Videos": [".avi", ".mp4", ".flv", ".mkv", ".wmv", ".mov", ".webm", ".vob", - ".3gp", ".mpeg", ".mpg", ".qt"], - - "Docs": [".pdf", ".doc", ".docx", ".xls", ".xlsx", ".ppt", ".pptx", ".epub", - ".opus", ".txt", ".in", ".out", ".xml"], - + "Images": [ + ".jpg", + ".jpeg", + ".png", + ".tiff", + ".gif", + ".bmp", + ".bpg", + ".svg", + ".heif", + ".psd", + ], + "Videos": [ + ".avi", + ".mp4", + ".flv", + ".mkv", + ".wmv", + ".mov", + ".webm", + ".vob", + ".3gp", + ".mpeg", + ".mpg", + ".qt", + ], + "Docs": [ + ".pdf", + ".doc", + ".docx", + ".xls", + ".xlsx", + ".ppt", + ".pptx", + ".epub", + ".opus", + ".txt", + ".in", + ".out", + ".xml", + ], "Archive": [".rar", ".zip", ".7z"], - - "Audio": [".mp3", ".aac", ".ogg", ".m4a", ".wav", ".aa", ".dvf", ".m4b", - ".m4p", ".msv", ".oga", ".raw", ".vox"] - + "Audio": [ + ".mp3", + ".aac", + ".ogg", + ".m4a", + ".wav", + ".aa", + ".dvf", + ".m4b", + ".m4p", + ".msv", + ".oga", + ".raw", + ".vox", + ], } -FILE_FORMATS = {file_format: directory - for directory, file_formats in DIRECTORIES.items() - for file_format in file_formats} +FILE_FORMATS = { + file_format: directory + for directory, file_formats in DIRECTORIES.items() + for file_format in file_formats +} if __name__ == "__main__": diff --git a/file_encrypter/file_decrypter.py b/file_encrypter/file_decrypter.py index 2a9aa57e1..f3b455d71 100644 --- a/file_encrypter/file_decrypter.py +++ b/file_encrypter/file_decrypter.py @@ -1,5 +1,7 @@ -import pyAesCrypt import sys + +import pyAesCrypt + bufferSize = 64 * 1024 password = input("password for decrypting : ") opname = sys.argv[1].replace(".aes", "") diff --git a/file_encrypter/file_encrypter.py b/file_encrypter/file_encrypter.py index 3c7764aad..56a9cbbbd 100644 --- a/file_encrypter/file_encrypter.py +++ b/file_encrypter/file_encrypter.py @@ -1,6 +1,7 @@ -import pyAesCrypt -import sys import re +import sys + +import pyAesCrypt bufferSize = 64 * 1024 @@ -9,7 +10,7 @@ def check_password(password): """ function to check the strength of password """ - regex = re.compile('[@_!#$%^&*()<>?/\\|}{~:]') + regex = re.compile("[@_!#$%^&*()<>?/\\|}{~:]") t1 = len(password) >= 8 t2 = not (regex.search(password) is None) diff --git a/file_mover/filemover.py b/file_mover/filemover.py index 93e555ad3..64161fd78 100644 --- a/file_mover/filemover.py +++ b/file_mover/filemover.py @@ -3,36 +3,42 @@ import time # 1st part asks the user what folder they want to pull files/data from -print('You are about to move files from one directory to another.') -dirA = input('What directory would you like to move? (please enter full path):') +print("You are about to move files from one directory to another.") +dirA = input("What directory would you like to move? (please enter full path):") dirA_exist = os.path.exists(dirA) # checks if the folder exist or not while os.path.exists(dirA) is not True: - dirA = input(f'{dirA} directory does not exist, please try again (please enter full path):') + dirA = input( + f"{dirA} directory does not exist, please try again (please enter full path):" + ) else: # 2nd part is to ask the user where they want to move the contents of a folder to - dirB = input(f'Where would you like to transfer the contents of {dirA}? (please enter full path):') + dirB = input( + f"Where would you like to transfer the contents of {dirA}? (please enter full path):" + ) # check's if the destination folder exist or not while os.path.exists(dirB) is not True: # asks the user if they would like to create the directory - Q1 = input(f'{dirB} does not exist, would you like to create it (Y/N)?') + Q1 = input(f"{dirB} does not exist, would you like to create it (Y/N)?") # if they say yes, it is create - if Q1 == 'Y': - print(f'Creating {dirB}') + if Q1 == "Y": + print(f"Creating {dirB}") os.mkdir(dirB) - print(f'{dirB} created') + print(f"{dirB} created") # if they say no, they are asked again where to transfer the files - elif Q1 == 'N': - dirB = input(f'Where would you like to transfer the contents of {dirA}? (please enter full path):') + elif Q1 == "N": + dirB = input( + f"Where would you like to transfer the contents of {dirA}? (please enter full path):" + ) # if Y or N is not entered, user is asked to try again else: - print('That is not a valid entry, please try again') + print("That is not a valid entry, please try again") # sets up a endless while loop to continuously move files from one to the other until the code is exited running = True @@ -41,16 +47,16 @@ dir_contents = os.scandir(dirA) for content in dir_contents: - content_to_move = dirA + '\\' + content.name + content_to_move = dirA + "\\" + content.name # skips any folders found if os.path.isdir(content_to_move): - print(f'{content_to_move} is a folder and not a file, skipping') + print(f"{content_to_move} is a folder and not a file, skipping") continue # moves file one at a time else: - shutil.move(dirA + '\\' + content.name, dirB) - print(f'File {content.name} has been moved') + shutil.move(dirA + "\\" + content.name, dirB) + print(f"File {content.name} has been moved") # sleeps for 30 seconds till it checks again - print('sleeping for 30 seconds') + print("sleeping for 30 seconds") time.sleep(30) diff --git a/file_search/filesearch.py b/file_search/filesearch.py index bd874d56a..29229392d 100644 --- a/file_search/filesearch.py +++ b/file_search/filesearch.py @@ -1,13 +1,14 @@ -import os -import datetime import argparse +import datetime +import os + from progress.bar import Bar class FileSearch: def __init__(self): self.file_count = 0 - self.progress_bar = Bar('Searching', suffix='%(eta)ds') + self.progress_bar = Bar("Searching", suffix="%(eta)ds") def get_file_count(self, path, is_folder): @@ -24,12 +25,7 @@ def get_file_count(self, path, is_folder): self.file_count += len(files) def __perform_search( - self, - search_term, - start_dir, - is_folder, - disable_case, - show_bar + self, search_term, start_dir, is_folder, disable_case, show_bar ): results = [] for root, dirs, files in os.walk(start_dir): @@ -57,12 +53,7 @@ def __perform_search( return results def search( - self, - search_term, - start_dir, - is_folder=False, - disable_case=False, - show_bar=True + self, search_term, start_dir, is_folder=False, disable_case=False, show_bar=True ): self.file_count = 0 self.get_file_count(start_dir, is_folder) @@ -73,70 +64,58 @@ def search( start_time = datetime.datetime.now() result = self.__perform_search( - search_term, - start_dir, - is_folder, - disable_case, - show_bar + search_term, start_dir, is_folder, disable_case, show_bar ) end_time = datetime.datetime.now() if not is_folder: print( - f"\n\n[INFO] Searched {self.file_count:,} files in {(end_time-start_time).total_seconds()} seconds") + f"\n\n[INFO] Searched {self.file_count:,} files in {(end_time-start_time).total_seconds()} seconds" + ) else: print( - f"\n\n[INFO] Searched {self.file_count:,} folders in {(end_time-start_time).total_seconds()} seconds") + f"\n\n[INFO] Searched {self.file_count:,} folders in {(end_time-start_time).total_seconds()} seconds" + ) return result if __name__ == "__main__": - parser = argparse.ArgumentParser( - description="Search files within your computer") + parser = argparse.ArgumentParser(description="Search files within your computer") parser.add_argument( - "search-term", - metavar="term", - type=str, - help="Filename/Word to search for" + "search-term", metavar="term", type=str, help="Filename/Word to search for" ) parser.add_argument( - "start-dir", - metavar="dir", - type=str, - help="Directory where you want to search" + "start-dir", metavar="dir", type=str, help="Directory where you want to search" ) parser.add_argument( "-dc", "--disable-case", action="store_true", - help="Perform case insensitive search" + help="Perform case insensitive search", ) parser.add_argument( "-f", "--folder", action="store_true", - help="Search only folders (default: searches files)" + help="Search only folders (default: searches files)", ) parser.add_argument( - "-nb", - "--no-bar", - action="store_false", - help="Not show progress bar" + "-nb", "--no-bar", action="store_false", help="Not show progress bar" ) args = parser.parse_args().__dict__ searcher = FileSearch() results = searcher.search( - args['search-term'], - args['start-dir'], - args['folder'], - args['disable_case'], - args['no_bar'] + args["search-term"], + args["start-dir"], + args["folder"], + args["disable_case"], + args["no_bar"], ) print("[INFO] Results: \n") diff --git a/file_unlatcher/AlFileUnlatcher.py b/file_unlatcher/AlFileUnlatcher.py index 2a90d7029..e768caa42 100644 --- a/file_unlatcher/AlFileUnlatcher.py +++ b/file_unlatcher/AlFileUnlatcher.py @@ -1,22 +1,22 @@ -import subprocess import os -from tkinter import Tk, Label, END, Frame, SUNKEN -from tkinter import font, Button, X, Entry, Text, BOTH -from PIL import ImageTk, Image +import subprocess +from tkinter import (BOTH, END, SUNKEN, Button, Entry, Frame, Label, Text, Tk, + X, font) + +from PIL import Image, ImageTk cwd = os.path.dirname(os.path.realpath(__file__)) -class AlFileUnlatcher(): +class AlFileUnlatcher: def __init__(self): root = Tk(className=" ALFILEUNLATCHER ") root.geometry("400x175+1500+840") root.resizable(0, 0) - root.iconbitmap(os.path.join(cwd + '\\UI\\icons', - 'alfileunlatcher.ico')) + root.iconbitmap(os.path.join(cwd + "\\UI\\icons", "alfileunlatcher.ico")) root.config(bg="#ffe69b") root.overrideredirect(1) - color = '#ffe69b' + color = "#ffe69b" def callback(event): root.geometry("400x175+1500+840") @@ -34,8 +34,7 @@ def hideScreen(): def find(): inputFile = fileText.get() - fileName = os.path.join(cwd + '/AlFileUnlatcher', - 'files_database.lst') + fileName = os.path.join(cwd + "/AlFileUnlatcher", "files_database.lst") if os.path.exists(fileName): pass else: @@ -47,7 +46,7 @@ def find(): dFile = open(fileName, "r") files = dFile.readlines() for file in files: - file = file.replace('\n', '') + file = file.replace("\n", "") if os.path.basename(file) == inputFile: if os.path.isfile(file): filesList.append(file) @@ -59,23 +58,25 @@ def find(): lines = filesList + otherList nFile = open(fileName, "w+") for line in lines: - line += '\n' + line += "\n" nFile.write(line) nFile.close() lfl = len(filesList) lnfl = len(notFoundList) if (lfl == 0) or (lnfl != 0 and lfl == 0) or (lnfl != 0): - check = subprocess.check_output(f'python {cwd}/AlFileUnlatcher' - '/AlFileSearcher.py "' + '' - '' + inputFile + '"') - check = check.decode("utf-8").replace('\r\n', ',:;') - output = check.split(',:;')[:-1] - allFiles = [i + '\n' for i in output] - dFile = open(fileName, 'a') + check = subprocess.check_output( + f"python {cwd}/AlFileUnlatcher" + '/AlFileSearcher.py "' + "" + "" + inputFile + '"' + ) + check = check.decode("utf-8").replace("\r\n", ",:;") + output = check.split(",:;")[:-1] + allFiles = [i + "\n" for i in output] + dFile = open(fileName, "a") dFile.writelines(allFiles) dFile.close() uniqlines = set(open(fileName).readlines()) - bar = open(fileName, 'w+').writelines(set(uniqlines)) + bar = open(fileName, "w+").writelines(set(uniqlines)) if bar: bar.close() for file in output: @@ -84,43 +85,61 @@ def find(): filesList.append(file) if len(filesList) == 0: text.delete(1.0, END) - text.insert(1.0, 'Invalid input file') + text.insert(1.0, "Invalid input file") else: for file in filesList: directory = os.path.dirname(file) filename = os.path.basename(file) try: text.delete(1.0, END) - text.insert(1.0, 'Opening ' + inputFile) + text.insert(1.0, "Opening " + inputFile) os.startfile(os.path.join(directory, filename)) except Exception as e: print(str(e)) - text.insert(1.0, 'Set a default application to open' - ' the input file') + text.insert( + 1.0, "Set a default application to open" " the input file" + ) - textHighlightFont = font.Font(family='OnePlus Sans Display', size=12) - appHighlightFont = font.Font(family='OnePlus Sans Display', size=12, - weight='bold') + textHighlightFont = font.Font(family="OnePlus Sans Display", size=12) + appHighlightFont = font.Font( + family="OnePlus Sans Display", size=12, weight="bold" + ) - titleBar = Frame(root, bg='#141414', relief=SUNKEN, bd=0) - icon = Image.open(os.path.join(cwd + '\\UI\\icons', - 'alfileunlatcher.ico')) + titleBar = Frame(root, bg="#141414", relief=SUNKEN, bd=0) + icon = Image.open(os.path.join(cwd + "\\UI\\icons", "alfileunlatcher.ico")) icon = icon.resize((30, 30), Image.ANTIALIAS) icon = ImageTk.PhotoImage(icon) iconLabel = Label(titleBar, image=icon) iconLabel.photo = icon - iconLabel.config(bg='#141414') + iconLabel.config(bg="#141414") iconLabel.grid(row=0, column=0, sticky="nsew") - titleLabel = Label(titleBar, text='ALFILEUNLATCHER', fg='#909090', - bg='#141414', font=appHighlightFont) + titleLabel = Label( + titleBar, + text="ALFILEUNLATCHER", + fg="#909090", + bg="#141414", + font=appHighlightFont, + ) titleLabel.grid(row=0, column=1, sticky="nsew") - closeButton = Button(titleBar, text="x", bg='#141414', fg="#909090", - borderwidth=0, command=root.destroy, - font=appHighlightFont) + closeButton = Button( + titleBar, + text="x", + bg="#141414", + fg="#909090", + borderwidth=0, + command=root.destroy, + font=appHighlightFont, + ) closeButton.grid(row=0, column=3, sticky="nsew") - minimizeButton = Button(titleBar, text="-", bg='#141414', fg="#909090", - borderwidth=0, command=hideScreen, - font=appHighlightFont) + minimizeButton = Button( + titleBar, + text="-", + bg="#141414", + fg="#909090", + borderwidth=0, + command=hideScreen, + font=appHighlightFont, + ) minimizeButton.grid(row=0, column=2, sticky="nsew") titleBar.grid_columnconfigure(0, weight=1) titleBar.grid_columnconfigure(1, weight=30) @@ -131,20 +150,34 @@ def find(): fileText = Label(root, text="FILE TO BE SEARCHED AND OPENED") fileText.pack() fileText.config(bg=color, fg="#0078d7", font=appHighlightFont) - fileText = Entry(root, bg="#0078d7", fg='white', - highlightbackground=color, highlightcolor=color, - highlightthickness=3, bd=0, font=textHighlightFont) + fileText = Entry( + root, + bg="#0078d7", + fg="white", + highlightbackground=color, + highlightcolor=color, + highlightthickness=3, + bd=0, + font=textHighlightFont, + ) fileText.pack(fill=X) - find = Button(root, borderwidth=0, highlightthickness=3, - text="OPEN FILE", command=find) + find = Button( + root, borderwidth=0, highlightthickness=3, text="OPEN FILE", command=find + ) find.config(bg=color, fg="#0078d7", font=appHighlightFont) find.pack(fill=X) - text = Text(root, font="sans-serif", relief=SUNKEN, - highlightbackground=color, highlightcolor=color, - highlightthickness=5, bd=0) - text.config(bg="#0078d7", fg='white', height=2, font=textHighlightFont) + text = Text( + root, + font="sans-serif", + relief=SUNKEN, + highlightbackground=color, + highlightcolor=color, + highlightthickness=5, + bd=0, + ) + text.config(bg="#0078d7", fg="white", height=2, font=textHighlightFont) text.pack(fill=BOTH, expand=True) titleBar.bind("", callback) diff --git a/file_unlatcher/AlFileUnlatcher/AlFileSearcher.py b/file_unlatcher/AlFileUnlatcher/AlFileSearcher.py index fe6635b52..61439fd44 100644 --- a/file_unlatcher/AlFileUnlatcher/AlFileSearcher.py +++ b/file_unlatcher/AlFileUnlatcher/AlFileSearcher.py @@ -1,11 +1,11 @@ import os import re -import win32api import sys +import win32api -class AlFileSearcher(): +class AlFileSearcher: def __init__(self, fileName): super().__init__() self.findFileInAllDrives(fileName) @@ -19,9 +19,9 @@ def findFile(self, rootFolder, rex): def findFileInAllDrives(self, fileName): rex = re.compile(fileName) - for drive in win32api.GetLogicalDriveStrings().split('\000')[:-1]: + for drive in win32api.GetLogicalDriveStrings().split("\000")[:-1]: self.findFile(drive, rex) -if __name__ == '__main__': +if __name__ == "__main__": AlFileSearcher(sys.argv[1]) diff --git a/flask_login_template/app.py b/flask_login_template/app.py index 7ba85c295..c6a50286e 100644 --- a/flask_login_template/app.py +++ b/flask_login_template/app.py @@ -1,36 +1,38 @@ -from flask import Flask, render_template, flash, redirect, session from functools import wraps + import setup.config as config +from flask import Flask, flash, redirect, render_template, session from user import User -app = Flask(__name__, template_folder="templates", static_folder='static') +app = Flask(__name__, template_folder="templates", static_folder="static") def login_required(f): @wraps(f) def wrap(*args, **kwargs): - if 'logged_in' in session: + if "logged_in" in session: return f(*args, **kwargs) else: - flash('Unauthorized. Please login.', 'danger') - return redirect('/') + flash("Unauthorized. Please login.", "danger") + return redirect("/") + return wrap -@app.route('/', methods=['POST', 'GET']) +@app.route("/", methods=["POST", "GET"]) def register(): return User().register() -@app.route('/logout') +@app.route("/logout") def logout(): return User().logout() -@app.route('/dashboard') +@app.route("/dashboard") @login_required def dashboard(): - return render_template('dashboard.html') + return render_template("dashboard.html") if __name__ == "__main__": diff --git a/flask_login_template/forms.py b/flask_login_template/forms.py index 22fe99cb9..2fcc35cb1 100644 --- a/flask_login_template/forms.py +++ b/flask_login_template/forms.py @@ -1,30 +1,33 @@ -from wtforms import Form, StringField, PasswordField, validators, SubmitField +from wtforms import Form, PasswordField, StringField, SubmitField, validators class registerForm(Form): name = StringField( - '', + "", [validators.DataRequired(), validators.Length(min=1, max=50)], - render_kw={"placeholder": "Name"}) + render_kw={"placeholder": "Name"}, + ) username = StringField( - '', - [validators.Length(min=4, max=25)], - render_kw={"placeholder": "Username"}) + "", [validators.Length(min=4, max=25)], render_kw={"placeholder": "Username"} + ) email = StringField( - '', - [validators.Length(min=6, max=150)], - render_kw={"placeholder": "Email"}) - password = PasswordField('', [ - validators.DataRequired(), - validators.EqualTo('confirm', message="Passwords do not match!") - ], render_kw={"placeholder": "Password"}) - confirm = PasswordField('', render_kw={"placeholder": "Confirm Password"}) - submit1 = SubmitField('Register') + "", [validators.Length(min=6, max=150)], render_kw={"placeholder": "Email"} + ) + password = PasswordField( + "", + [ + validators.DataRequired(), + validators.EqualTo("confirm", message="Passwords do not match!"), + ], + render_kw={"placeholder": "Password"}, + ) + confirm = PasswordField("", render_kw={"placeholder": "Confirm Password"}) + submit1 = SubmitField("Register") class loginForm(Form): - username = StringField('', render_kw={"placeholder": "Username"}) - password = PasswordField('', [ - validators.DataRequired() - ], render_kw={"placeholder": "Password"}) - submit2 = SubmitField('Login') + username = StringField("", render_kw={"placeholder": "Username"}) + password = PasswordField( + "", [validators.DataRequired()], render_kw={"placeholder": "Password"} + ) + submit2 = SubmitField("Login") diff --git a/flask_login_template/setup/config.py b/flask_login_template/setup/config.py index 6c340b8a8..842fe4bf9 100644 --- a/flask_login_template/setup/config.py +++ b/flask_login_template/setup/config.py @@ -1,9 +1,10 @@ -from dotenv import load_dotenv -import pymongo import os +import pymongo +from dotenv import load_dotenv + load_dotenv() -template = os.environ['TEMPLATE'] -secret_key = os.environ['SECRET_KEY'] -client = pymongo.MongoClient(os.environ['MONGO_CONNECTION_STRING']) +template = os.environ["TEMPLATE"] +secret_key = os.environ["SECRET_KEY"] +client = pymongo.MongoClient(os.environ["MONGO_CONNECTION_STRING"]) db = client.registration diff --git a/flask_login_template/user.py b/flask_login_template/user.py index 5776ecbfb..a3fd90e92 100644 --- a/flask_login_template/user.py +++ b/flask_login_template/user.py @@ -1,15 +1,16 @@ -from flask import render_template, flash, redirect, session, request -from forms import registerForm, loginForm -from passlib.hash import sha256_crypt -import setup.config as config import uuid +import setup.config as config +from flask import flash, redirect, render_template, request, session +from forms import loginForm, registerForm +from passlib.hash import sha256_crypt + class User: def start_session(self, user): - del user['password'] - session['logged_in'] = True - session['user'] = user + del user["password"] + session["logged_in"] = True + session["user"] = user def register(self): reg_form = registerForm(request.form) @@ -21,60 +22,58 @@ def register(self): "name": reg_form.name.data, "email": reg_form.email.data, "username": reg_form.username.data, - "password": reg_form.password.data} - user['password'] = sha256_crypt.encrypt(user['password']) - if config.db.users.find_one({"email": user['email']}): + "password": reg_form.password.data, + } + user["password"] = sha256_crypt.encrypt(user["password"]) + if config.db.users.find_one({"email": user["email"]}): error = "Email already exists!" return render_template( config.template, error=error, reg_form=reg_form, - login_form=login_form) + login_form=login_form, + ) if config.db.users.insert_one(user): self.start_session(user) - flash('You are now registered and can log in!', 'success') + flash("You are now registered and can log in!", "success") return render_template( - config.template, - reg_form=reg_form, - login_form=login_form) + config.template, reg_form=reg_form, login_form=login_form + ) elif login_form.submit2.data and login_form.validate(): - user = config.db.users.find_one( - {"username": login_form.username.data}) + user = config.db.users.find_one({"username": login_form.username.data}) if user: - if sha256_crypt.verify( - login_form.password.data, user['password']): + if sha256_crypt.verify(login_form.password.data, user["password"]): self.start_session(user) - return render_template('dashboard.html') + return render_template("dashboard.html") else: - error = 'Incorrect login details!' + error = "Incorrect login details!" return render_template( config.template, error=error, reg_form=reg_form, - login_form=login_form) + login_form=login_form, + ) else: - error = 'Username not found!' + error = "Username not found!" return render_template( config.template, error=error, reg_form=reg_form, - login_form=login_form) - error = 'Check the registered details!' + login_form=login_form, + ) + error = "Check the registered details!" return render_template( - config.template, - error=error, - reg_form=reg_form, - login_form=login_form) + config.template, error=error, reg_form=reg_form, login_form=login_form + ) else: try: return render_template( - config.template, - reg_form=reg_form, - login_form=login_form) + config.template, reg_form=reg_form, login_form=login_form + ) except Exception: return "Given template does not exists." def logout(self): session.clear() flash("You are now logged out!", "success") - return redirect('/') + return redirect("/") diff --git a/flipkart_price_tracker/flipkart.py b/flipkart_price_tracker/flipkart.py index 8460945ac..04a936c18 100644 --- a/flipkart_price_tracker/flipkart.py +++ b/flipkart_price_tracker/flipkart.py @@ -1,55 +1,57 @@ -import requests -from bs4 import BeautifulSoup as bs import smtplib import time -headers = {'User-Agent': 'Mozilla/5.0 Chrome/86.0.4240.75'} + +import requests +from bs4 import BeautifulSoup as bs + +headers = {"User-Agent": "Mozilla/5.0 Chrome/86.0.4240.75"} def sendMail(title): - '''Send Email''' - server = smtplib.SMTP('smtp.gmail.com', 587) + """Send Email""" + server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.ehlo() server.login(MY_EMAIL, MY_APP_PASSWORD) - subject = 'Change in price detected for ' + title + subject = "Change in price detected for " + title print(subject) - body = 'Click the link to go to the product page \n' + PRODUCT_URL + body = "Click the link to go to the product page \n" + PRODUCT_URL msg = f"Subject: {subject}\n\n{body}" print(msg) server.sendmail(MY_EMAIL, RECEIVER_EMAIL, msg) - print('Email Sent') + print("Email Sent") server.quit() def priceCheck(): - '''Price checking function''' + """Price checking function""" page = requests.get(PRODUCT_URL, headers=headers) - soup = bs(page.content, 'html.parser') + soup = bs(page.content, "html.parser") # title from 'B_NuCI' class - title = soup.find("span", {"class": "B_NuCI"}).get_text()[0:8] + '..' + title = soup.find("span", {"class": "B_NuCI"}).get_text()[0:8] + ".." print(title) # price from '_30jeq3 _16Jk6d' class, raw_price = soup.find("div", {"class": "_30jeq3 _16Jk6d"}) # removing unnecessary characters from the price. - price = float(raw_price.get_text()[1:].replace(',', '')) + price = float(raw_price.get_text()[1:].replace(",", "")) print(price) print(THRESHHOLD) # If the price falls below threshold, send an email - if (price < THRESHHOLD): + if price < THRESHHOLD: sendMail(title) -PRODUCT_URL = input('Enter the product url:') -THRESHHOLD = float(input('Enter the desired price:')) -MY_EMAIL = input('Enter the email address that will be used to send alerts:') -MY_APP_PASSWORD = input('Enter password:') -RECEIVER_EMAIL = input('Enter the receiver email:') -CHECK_AGAIN = int(input('Enter the time between checks in minutes:')) +PRODUCT_URL = input("Enter the product url:") +THRESHHOLD = float(input("Enter the desired price:")) +MY_EMAIL = input("Enter the email address that will be used to send alerts:") +MY_APP_PASSWORD = input("Enter password:") +RECEIVER_EMAIL = input("Enter the receiver email:") +CHECK_AGAIN = int(input("Enter the time between checks in minutes:")) -if (PRODUCT_URL == '' or MY_APP_PASSWORD == '' or MY_EMAIL == '' or RECEIVER_EMAIL == ''): - print('VALUES MISSING! TRY AGAIN') +if PRODUCT_URL == "" or MY_APP_PASSWORD == "" or MY_EMAIL == "" or RECEIVER_EMAIL == "": + print("VALUES MISSING! TRY AGAIN") exit() -while (True): +while True: priceCheck() time.sleep(CHECK_AGAIN * 60) diff --git a/folders_arranger/folders_arranger.py b/folders_arranger/folders_arranger.py index f729fe054..260f5d049 100644 --- a/folders_arranger/folders_arranger.py +++ b/folders_arranger/folders_arranger.py @@ -1,23 +1,23 @@ -import shutil import os +import shutil import string class ArrangeScripts: def __init__(self, path_to_folder): - self.folders = ['a_e', 'f_j', 'k_o', 'p_t', 'u_z'] + self.folders = ["a_e", "f_j", "k_o", "p_t", "u_z"] self.folder_mapping = {} for alphabet in list(string.ascii_lowercase): - if alphabet in list('abcde'): - self.folder_mapping[alphabet] = 'a_e' - elif alphabet in list('fghij'): - self.folder_mapping[alphabet] = 'f_j' - elif alphabet in list('klmno'): - self.folder_mapping[alphabet] = 'k_o' - elif alphabet in list('pqrst'): - self.folder_mapping[alphabet] = 'p_t' - elif alphabet in list('uvwxyz'): - self.folder_mapping[alphabet] = 'u_z' + if alphabet in list("abcde"): + self.folder_mapping[alphabet] = "a_e" + elif alphabet in list("fghij"): + self.folder_mapping[alphabet] = "f_j" + elif alphabet in list("klmno"): + self.folder_mapping[alphabet] = "k_o" + elif alphabet in list("pqrst"): + self.folder_mapping[alphabet] = "p_t" + elif alphabet in list("uvwxyz"): + self.folder_mapping[alphabet] = "u_z" self.path_to_folder = path_to_folder @@ -36,13 +36,15 @@ def organize_folder(self): source_path = os.path.join(self.path_to_folder, a_folder) first_char = a_folder.lower()[0] - destination_path = os.path.join(self.path_to_folder, self.folder_mapping[first_char]) + destination_path = os.path.join( + self.path_to_folder, self.folder_mapping[first_char] + ) shutil.move(source_path, destination_path, copy_function=shutil.copytree) def process_folders(): # get folder path - user_input = input('Enter path to folder which needs to be organized: ') + user_input = input("Enter path to folder which needs to be organized: ") arrange = ArrangeScripts(user_input) arrange.organize_folder() diff --git a/fork_and_clone/Fnc.py b/fork_and_clone/Fnc.py index 106cfd31a..74fc5a262 100644 --- a/fork_and_clone/Fnc.py +++ b/fork_and_clone/Fnc.py @@ -1,5 +1,6 @@ import subprocess import sys + from github import Github @@ -8,17 +9,17 @@ def fork(): print("To quit at any point click ctrl-c") accOrOrg = input( "Fork to your profile or an organization" - "(type org for organization, acc for profile): ") - while (accOrOrg != "acc" and accOrOrg != "org"): + "(type org for organization, acc for profile): " + ) + while accOrOrg != "acc" and accOrOrg != "org": accOrOrg = input("invalid answer: acc or org: ") username = input("Your github username: ") password = input("Your github password: ") try: g = Github(username, password) user = g.get_user() - repo = input( - "Name of repo you want to fork (in the form owner/repo): ") - if (accOrOrg == "acc"): + repo = input("Name of repo you want to fork (in the form owner/repo): ") + if accOrOrg == "acc": user.create_fork(g.get_repo(repo)) else: org = input("name of your organization: ") @@ -33,25 +34,33 @@ def fork(): def clone(repo): - location = input( - "Path for cloning repo into" - "(default is current directory): ") + location = input("Path for cloning repo into" "(default is current directory): ") try: if len(location.strip()) != 0: arr = repo.split("/") subprocess.run( - "git clone https://github.com/" + repo + ".git " + location - + "\\" + arr[0] + "\\" + arr[1], shell=True, check=True) + "git clone https://github.com/" + + repo + + ".git " + + location + + "\\" + + arr[0] + + "\\" + + arr[1], + shell=True, + check=True, + ) else: subprocess.run( - "git clone https://github.com/" + repo + ".git", - shell=True, check=True) + "git clone https://github.com/" + repo + ".git", shell=True, check=True + ) except Exception as e: print("ERROR: " + str(e)) fnc = input( "To start from the forking type fork, to start from" - "cloning type clone, to exit press ctrl-c: ").lower() + "cloning type clone, to exit press ctrl-c: " + ).lower() if fnc == "fork": fork() elif fnc == "clone": diff --git a/gender_detector/detect_gender_webcam.py b/gender_detector/detect_gender_webcam.py index 10ba7d7ae..302d8f611 100644 --- a/gender_detector/detect_gender_webcam.py +++ b/gender_detector/detect_gender_webcam.py @@ -1,14 +1,20 @@ -from keras.preprocessing.image import img_to_array -from keras.models import load_model import os -from keras.utils import get_file -import numpy as np + import cv2 import cvlib as cv +import numpy as np +from keras.models import load_model +from keras.preprocessing.image import img_to_array +from keras.utils import get_file # load model dwnld_link = "https://github.com/arunponnusamy/cvlib/releases/download/v0.2.0/gender_detection.model" -model_path = get_file("gender_detection.model", dwnld_link, cache_subdir="pre-trained", cache_dir=os.getcwd()) +model_path = get_file( + "gender_detection.model", + dwnld_link, + cache_subdir="pre-trained", + cache_dir=os.getcwd(), +) model = load_model(model_path) # open_webcam @@ -18,7 +24,7 @@ print("Could not open webcam") exit() -classes = ['man' , 'woman'] +classes = ["man", "woman"] # loop through frames while webcam.isOpened(): @@ -66,11 +72,13 @@ label = "{}: {:.2f}%".format(label, conf[idx] * 100) Y = startY - 10 if startY - 10 > 10 else startY + 10 # write label and confidence above face rectangle - cv2.putText(frame, label, (startX, Y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2) + cv2.putText( + frame, label, (startX, Y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0), 2 + ) # display output cv2.imshow("gender detection", frame) # press "Q" to stop - if cv2.waitKey(1) & 0xFF == ord('q'): + if cv2.waitKey(1) & 0xFF == ord("q"): break # release resources webcam.release() diff --git a/geocordinate_locating_tool/geocordinate-locator.py b/geocordinate_locating_tool/geocordinate-locator.py index 19a725628..60dc496a6 100644 --- a/geocordinate_locating_tool/geocordinate-locator.py +++ b/geocordinate_locating_tool/geocordinate-locator.py @@ -1,6 +1,7 @@ -from tkinter import Label, StringVar, Button, END, Entry, Tk -from geopy.geocoders import ArcGIS +from tkinter import END, Button, Entry, Label, StringVar, Tk + import clipboard +from geopy.geocoders import ArcGIS def f(): diff --git a/github_scraper/scrapper.py b/github_scraper/scrapper.py index 11405714f..2cfc3b0fe 100644 --- a/github_scraper/scrapper.py +++ b/github_scraper/scrapper.py @@ -1,9 +1,12 @@ -import requests import argparse -parser = argparse.ArgumentParser(description='Fetch information about Github user.') -parser.add_argument('user', type=str, nargs=1, help='User that you want to look up into.') -parser.add_argument('--json', action='store_true', help='Output data in json format') +import requests + +parser = argparse.ArgumentParser(description="Fetch information about Github user.") +parser.add_argument( + "user", type=str, nargs=1, help="User that you want to look up into." +) +parser.add_argument("--json", action="store_true", help="Output data in json format") args = vars(parser.parse_args()) user = args["user"][0] @@ -11,11 +14,11 @@ API_URL = "https://api.github.com" -req = requests.get(f'{API_URL}/users/{user}') +req = requests.get(f"{API_URL}/users/{user}") data = req.json() if is_json: print(data) else: for key, value in data.items(): - print(f'{key}: {value}') + print(f"{key}: {value}") diff --git a/gmeet_zoom_joiner/gmeet_zoom_bot.py b/gmeet_zoom_joiner/gmeet_zoom_bot.py index f81e7036c..2f86d0c6c 100644 --- a/gmeet_zoom_joiner/gmeet_zoom_bot.py +++ b/gmeet_zoom_joiner/gmeet_zoom_bot.py @@ -1,9 +1,9 @@ import time import webbrowser -import schedule + import pyautogui import pyperclip - +import schedule url1 = "PASTE gmeet link/zoom link/zoom meeting id" url2 = "PASTE gmeet link/zoom link/zoom meeting id" @@ -14,17 +14,17 @@ def gMeet(url): time.sleep(3) print("Joining Class") time.sleep(2) - pyautogui.hotkey('command', 'd') + pyautogui.hotkey("command", "d") print("Turned off camera") - pyautogui.hotkey('command', 'e') + pyautogui.hotkey("command", "e") print("Turned off mic") time.sleep(3) for i in range(4): - pyautogui.press('tab') + pyautogui.press("tab") time.sleep(3) - pyautogui.press('enter') + pyautogui.press("enter") def zMeet(url): @@ -33,47 +33,49 @@ def zMeet(url): time.sleep(0.2) - pyautogui.press('esc', interval=0.1) + pyautogui.press("esc", interval=0.1) time.sleep(0.3) # open shart - pyautogui.press('win', interval=0.5) + pyautogui.press("win", interval=0.5) # type zoom - pyautogui.write('zoom') + pyautogui.write("zoom") time.sleep(2) # press enter - pyautogui.press('enter', interval=0.5) + pyautogui.press("enter", interval=0.5) time.sleep(8) # Click zoom button - x, y = pyautogui.locateCenterOnScreen('zoom_btn.png') + x, y = pyautogui.locateCenterOnScreen("zoom_btn.png") pyautogui.click(x, y) - pyautogui.press('enter', interval=0.5) + pyautogui.press("enter", interval=0.5) # paste link - pyautogui.hotkey('ctrl', 'v') + pyautogui.hotkey("ctrl", "v") # use tabs to move to next section - pyautogui.press('tab', interval=0.5) - pyautogui.press('tab', interval=0.5) - pyautogui.press('tab', interval=0.5) - pyautogui.press('enter', interval=0.5) # mute mic + pyautogui.press("tab", interval=0.5) + pyautogui.press("tab", interval=0.5) + pyautogui.press("tab", interval=0.5) + pyautogui.press("enter", interval=0.5) # mute mic - pyautogui.press('tab', interval=0.5) - pyautogui.press('enter', interval=0.5) # turn off camera + pyautogui.press("tab", interval=0.5) + pyautogui.press("enter", interval=0.5) # turn off camera - pyautogui.press('tab', interval=0.5) - pyautogui.press('enter', interval=3) # join zoom link + pyautogui.press("tab", interval=0.5) + pyautogui.press("enter", interval=3) # join zoom link if __name__ == "__main__": - schedule.every().day.at("16:00").do(gMeet(url1) if ( - url1.startswith("https://meet")) else zMeet(url1)) - schedule.every().day.at("06:00").do(gMeet(url2) if ( - url2.startswith("https://meet")) else zMeet(url2)) + schedule.every().day.at("16:00").do( + gMeet(url1) if (url1.startswith("https://meet")) else zMeet(url1) + ) + schedule.every().day.at("06:00").do( + gMeet(url2) if (url2.startswith("https://meet")) else zMeet(url2) + ) while True: schedule.run_pending() # check if we need to run anything diff --git a/google_images_scraper/google_images_scraper.py b/google_images_scraper/google_images_scraper.py index 66f38097d..4c2a966b9 100644 --- a/google_images_scraper/google_images_scraper.py +++ b/google_images_scraper/google_images_scraper.py @@ -1,11 +1,11 @@ -from selenium import webdriver -from bs4 import BeautifulSoup -import urllib.request -import time import argparse import os +import time +import urllib.request import geckodriver_autoinstaller +from bs4 import BeautifulSoup +from selenium import webdriver def driver_download(): diff --git a/google_meet_schedular/AutoMeet.py b/google_meet_schedular/AutoMeet.py index aba1f4a62..bd3d2718c 100644 --- a/google_meet_schedular/AutoMeet.py +++ b/google_meet_schedular/AutoMeet.py @@ -1,42 +1,51 @@ -from selenium import webdriver -import time import re +import time + # from pynput.keyboard import Controller from notify_run import Notify +from selenium import webdriver -class AutoMeet(): +class AutoMeet: usernameStr = None passwordStr = None url_meet = None options = None browser = None - def __init__(self, username_string, password_string, url_of_meet,): + def __init__( + self, + username_string, + password_string, + url_of_meet, + ): self.usernameStr = username_string self.passwordStr = password_string self.url_meet = url_of_meet self.options = webdriver.ChromeOptions() self.options.add_argument("--disable-infobars") self.options.add_argument("--window-size=800,600") - self.options.add_experimental_option("prefs", { - "profile.default_content_setting_values.media_stream_camera": 2, - "profile.default_content_setting_values.media_stream_mic": 2, - # "profile.default_content_setting_values.geolocation": 2, - "profile.default_content_setting_values.notifications": 2 - }) + self.options.add_experimental_option( + "prefs", + { + "profile.default_content_setting_values.media_stream_camera": 2, + "profile.default_content_setting_values.media_stream_mic": 2, + # "profile.default_content_setting_values.geolocation": 2, + "profile.default_content_setting_values.notifications": 2, + }, + ) self.browser = webdriver.Chrome(chrome_options=self.options) # ---------------Wrapper for Gmail ID And Non Gmail ID----------------- def automeetG(self): - self.browser.get(('https://stackoverflow.com/')) + self.browser.get(("https://stackoverflow.com/")) # self.browser.find_element_by_xpath("/html/body/header/div/ol[2]/li[2]/a[2]").click() self.waiting_N_click("/html/body/header/div/ol[2]/li[2]/a[2]") # self.browser.find_element_by_xpath("//*[@id=\"openid-buttons\"]/button[1]").click() - self.waiting_N_click("//*[@id=\"openid-buttons\"]/button[1]") - username = self.browser.find_element_by_id('identifierId') + self.waiting_N_click('//*[@id="openid-buttons"]/button[1]') + username = self.browser.find_element_by_id("identifierId") username.send_keys(self.usernameStr) - nextButton = self.browser.find_element_by_id('identifierNext') + nextButton = self.browser.find_element_by_id("identifierNext") nextButton.click() time.sleep(15) # 5 # keyboard = Controller() @@ -44,53 +53,73 @@ def automeetG(self): password = self.browser.find_element_by_xpath("//input[@class='whsOnd zHQkBf']") password.send_keys(self.passwordStr) # keyboard.type(passwordStr) - signInButton = self.browser.find_element_by_id('passwordNext') + signInButton = self.browser.find_element_by_id("passwordNext") signInButton.click() time.sleep(5) # 3 self.browser.get(self.url_meet) time.sleep(10) # 6 - element = self.browser.find_element_by_class_name('Ce1Y1c') + element = self.browser.find_element_by_class_name("Ce1Y1c") self.browser.execute_script("arguments[0].click();", element) try: - self.browser.find_element_by_xpath('//*[@id="yDmH0d"]/div[3]/div/div[2]/div[3]/div').click() + self.browser.find_element_by_xpath( + '//*[@id="yDmH0d"]/div[3]/div/div[2]/div[3]/div' + ).click() try: - self.browser.find_element_by_xpath("//span[@class='NPEfkd RveJvd snByac' and contains(text(), \ - 'Ask to join')]").click() + self.browser.find_element_by_xpath( + "//span[@class='NPEfkd RveJvd snByac' and contains(text(), \ + 'Ask to join')]" + ).click() except BaseException: - self.browser.find_element_by_xpath("//span[@class='NPEfkd RveJvd snByac' and contains(text(), \ - 'Join now')]").click() + self.browser.find_element_by_xpath( + "//span[@class='NPEfkd RveJvd snByac' and contains(text(), \ + 'Join now')]" + ).click() except BaseException: try: - self.browser.find_element_by_xpath("//span[@class='NPEfkd RveJvd snByac' and contains(text(), \ - 'Ask to join')]").click() + self.browser.find_element_by_xpath( + "//span[@class='NPEfkd RveJvd snByac' and contains(text(), \ + 'Ask to join')]" + ).click() except BaseException: - self.browser.find_element_by_xpath("//span[@class='NPEfkd RveJvd snByac' and contains(text(), \ - 'Join now')]").click() + self.browser.find_element_by_xpath( + "//span[@class='NPEfkd RveJvd snByac' and contains(text(), \ + 'Join now')]" + ).click() # time.sleep(15) # Wasnt here # self.browser.find_element_by_xpath("//*[@id=\"ow3\"]/div[1]/div/div[4]/div[3]/div[6]/div[3]/div/div[2]/div[3]/span/span").click() - self.waiting_N_click("//*[@id=\"ow3\"]/div[1]/div/div[4]/div[3]/div[6]/div[3]/div/div[2]/div[3]/span/span") + self.waiting_N_click( + '//*[@id="ow3"]/div[1]/div/div[4]/div[3]/div[6]/div[3]/div/div[2]/div[3]/span/span' + ) currentStudents = 0 greatestStudents = 0 text_temp = "" final_text = "" while True: time.sleep(25) # reduce it later - text = self.browser.find_element_by_xpath("/html/body/div[1]/c-wiz/div[1]/div/div[4]/div[3]/div[3]/ \ - div/div[2]/div[2]/div[2]/span[2]/div/div[1]").text - people = self.browser.find_element_by_xpath("/html/body/div[1]/c-wiz/div[1]/div/div[4]/div[3]/div[3]/ \ - div/div[2]/div[2]/div[1]/div[1]").text + text = self.browser.find_element_by_xpath( + "/html/body/div[1]/c-wiz/div[1]/div/div[4]/div[3]/div[3]/ \ + div/div[2]/div[2]/div[2]/span[2]/div/div[1]" + ).text + people = self.browser.find_element_by_xpath( + "/html/body/div[1]/c-wiz/div[1]/div/div[4]/div[3]/div[3]/ \ + div/div[2]/div[2]/div[1]/div[1]" + ).text # print(people) # print(text) final_text = text.replace(text_temp, "") # print(final_text) text_temp = text - link = re.findall(r"(http|ftp|https)://([\w-]+(?:(?:.[\w-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?", - final_text) - if ("http" in final_text): + link = re.findall( + r"(http|ftp|https)://([\w-]+(?:(?:.[\w-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?", + final_text, + ) + if "http" in final_text: notify = Notify() - notify.send(link[0][0] + "://" + link[0][1], link[0][0] + "://" + link[0][1]) + notify.send( + link[0][0] + "://" + link[0][1], link[0][0] + "://" + link[0][1] + ) print(link[0][0] + "://" + link[0][1]) - people_int = re.findall(r'[0-9]+', people) + people_int = re.findall(r"[0-9]+", people) # print(people_int[0]) currentStudents = int(people_int[0]) if currentStudents > greatestStudents: diff --git a/hackernews_scrapper/hackernews_scrapper.py b/hackernews_scrapper/hackernews_scrapper.py index fd548631f..446eb9f62 100644 --- a/hackernews_scrapper/hackernews_scrapper.py +++ b/hackernews_scrapper/hackernews_scrapper.py @@ -1,6 +1,7 @@ -import requests import csv import sys + +import requests from bs4 import BeautifulSoup as bs @@ -10,9 +11,12 @@ def main(): # Number of articles requested by the user try: - number_of_articles = int(input( - '''Enter the number of articles you want from the hackernews website. -(1-30) : ''')) + number_of_articles = int( + input( + """Enter the number of articles you want from the hackernews website. +(1-30) : """ + ) + ) except ValueError: print("\nYou did not enter a number. Try again.\n") sys.exit(1) @@ -24,10 +28,10 @@ def main(): response = requests.get(baseurl) # soup object for easy scrapping - soup = bs(response.content, 'html.parser') + soup = bs(response.content, "html.parser") # Finding all the a tags with the class storylink - latest = soup.find_all('a', attrs={'class': 'storylink'}) + latest = soup.find_all("a", attrs={"class": "storylink"}) # list to track the links of the articles links = [] @@ -38,13 +42,12 @@ def main(): # Fetching the links and names from the soup object # storing them in respective lists for article in latest: - links.append(article['href']) + links.append(article["href"]) titles.append(article.text) result = [] - for title, link in zip(titles[:number_of_articles], - links[:number_of_articles]): + for title, link in zip(titles[:number_of_articles], links[:number_of_articles]): d = {} d["News Title"] = title d["Link to the News"] = link diff --git a/horoscope_destination/horoscope.py b/horoscope_destination/horoscope.py index 394b6eb75..f8570cee8 100644 --- a/horoscope_destination/horoscope.py +++ b/horoscope_destination/horoscope.py @@ -9,19 +9,20 @@ def get_info(sign, day): parameters = {"sign": sign, "day": day} - headers = {'x-rapidapi-host': "sameer-kumar-aztro-v1.p.rapidapi.com", - 'x-rapidapi-key': - "9b63804a3cmsh368b3af884ede93p1e0b5djsn7ebb3eb30986"} + headers = { + "x-rapidapi-host": "sameer-kumar-aztro-v1.p.rapidapi.com", + "x-rapidapi-key": "9b63804a3cmsh368b3af884ede93p1e0b5djsn7ebb3eb30986", + } robj = requests.post(base_url, headers=headers, params=parameters) return_object = robj.json() if robj.status_code == 200: - res = f'''We see that you are {sign.capitalize()}. Your horoscope for the date + res = f"""We see that you are {sign.capitalize()}. Your horoscope for the date {return_object['current_date']} says that : '{return_object["description"]}'\n You are compatible with {return_object["compatibility"]}. Your lucky color, number and time are {return_object["color"]}, {return_object["lucky_number"]} and {return_object["lucky_time"]} respectively.\n - You are expected to be in '{return_object["mood"]}' mood.''' + You are expected to be in '{return_object["mood"]}' mood.""" return res else: @@ -34,10 +35,10 @@ def bad_input(container, code): print("\nThis is NOT a valid entry.") yn = input("Are you requesting to QUIT? (press y / n) : ") - if yn == 'y': + if yn == "y": print("\nThankyou for holding up!\n") return 1 - elif yn == 'n': + elif yn == "n": print("\nPlease enter a valid number.\n") return 0 else: @@ -51,7 +52,7 @@ def main(): an invalid entry by the user. It then invokes the get_info() function to collect the required result and print it.""" - info_zodiac = ''' + info_zodiac = """ Hello and Welcome to your Horoscope Destination!\n\n Select your Zodiac Sign from the list below. Press the code along the Sign to proceed.\n @@ -67,20 +68,30 @@ def main(): 10. Capricorn 11. Aquarius 12. Pisces - Press any other character to QUIT.\n''' + Press any other character to QUIT.\n""" - info_day = ''' + info_day = """ Which day's horoscope are you looking for?\n 1. Yesterday 2. Today 3. Tomorrow - Press any other character to QUIT.\n''' - - zodiac = {'1': 'aries', '2': 'taurus', '3': 'gemini', - '4': 'cancer', '5': 'leo', '6': 'virgo', '7': 'libra', - '8': 'scorpio', '9': 'sagittarius', '10': 'capricorn', - '11': 'aquarius', '12': 'pisces'} - day = {'1': "yesterday", '2': "today", '3': "tomorrow"} + Press any other character to QUIT.\n""" + + zodiac = { + "1": "aries", + "2": "taurus", + "3": "gemini", + "4": "cancer", + "5": "leo", + "6": "virgo", + "7": "libra", + "8": "scorpio", + "9": "sagittarius", + "10": "capricorn", + "11": "aquarius", + "12": "pisces", + } + day = {"1": "yesterday", "2": "today", "3": "tomorrow"} zodiac_code, day_code = 0, 0 @@ -111,6 +122,6 @@ def main(): print(f'\n\nWe have an astro prediction for you!\n\n" {result} "\n') -if __name__ == '__main__': +if __name__ == "__main__": """The main driver code.""" main() diff --git a/html_to_markdown/AlHtmlToMarkdown.py b/html_to_markdown/AlHtmlToMarkdown.py index 41d2f5c00..2e35002c7 100644 --- a/html_to_markdown/AlHtmlToMarkdown.py +++ b/html_to_markdown/AlHtmlToMarkdown.py @@ -1,23 +1,22 @@ -import markdownify import os -from tkinter import Tk, END, Frame, SUNKEN, Label -from tkinter import font, Button, X, Entry, Text, BOTH -from PIL import ImageTk, Image +from tkinter import (BOTH, END, SUNKEN, Button, Entry, Frame, Label, Text, Tk, + X, font) -cwd = os.path.dirname(os.path.realpath(__file__)) +import markdownify +from PIL import Image, ImageTk +cwd = os.path.dirname(os.path.realpath(__file__)) -class AlHtmlToMarkdown(): +class AlHtmlToMarkdown: def __init__(self): root = Tk(className=" ALHTMLTOMARKDOWN ") root.geometry("400x175+1500+840") root.resizable(0, 0) - root.iconbitmap(os.path.join(cwd + '\\UI\\icons', - 'alhtmltomarkdown.ico')) + root.iconbitmap(os.path.join(cwd + "\\UI\\icons", "alhtmltomarkdown.ico")) root.config(bg="#6a199b") root.overrideredirect(1) - color = '#6a199b' + color = "#6a199b" def callback(event): root.geometry("400x175+1500+840") @@ -35,7 +34,7 @@ def hideScreen(): def markdown(): filename = fileText.get() - filepath = os.path.join(cwd + '\\AlHtmlToMarkdown', filename) + filepath = os.path.join(cwd + "\\AlHtmlToMarkdown", filename) if os.path.exists(filepath): extension = os.path.splitext(filepath)[1] try: @@ -43,50 +42,70 @@ def markdown(): htmlFile = open(filepath, "r") html = htmlFile.read() htmlFile.close() - markDown = markdownify.markdownify(html, - heading_style="ATX") - markdownFileName = filename.replace(extension, '.md') - markdownFilePath = os.path.join(cwd + '\\AlHtmlToMarkd' - 'own\\Markdown', - markdownFileName) + markDown = markdownify.markdownify(html, heading_style="ATX") + markdownFileName = filename.replace(extension, ".md") + markdownFilePath = os.path.join( + cwd + "\\AlHtmlToMarkd" "own\\Markdown", markdownFileName + ) markdownFile = open(markdownFilePath, "w") markdownFile.writelines(markDown) markdownFile.close() text.delete(1.0, END) - text.insert(1.0, markdownFileName + ' has been saved ' - 'successfully in Markdown folder') + text.insert( + 1.0, + markdownFileName + " has been saved " + "successfully in Markdown folder", + ) except Exception as e: text.delete(1.0, END) print(str(e)) - text.insert(1.0, 'Invalid document, please provide .html ' - 'extension files') + text.insert( + 1.0, "Invalid document, please provide .html " "extension files" + ) else: text.delete(1.0, END) - text.insert(1.0, 'Invalid file path') + text.insert(1.0, "Invalid file path") - textHighlightFont = font.Font(family='OnePlus Sans Display', size=12) - appHighlightFont = font.Font(family='OnePlus Sans Display', size=12, - weight='bold') + textHighlightFont = font.Font(family="OnePlus Sans Display", size=12) + appHighlightFont = font.Font( + family="OnePlus Sans Display", size=12, weight="bold" + ) - titleBar = Frame(root, bg='#141414', relief=SUNKEN, bd=0) - icon = Image.open(os.path.join(cwd + '\\UI\\icons', - 'alhtmltomarkdown.ico')) + titleBar = Frame(root, bg="#141414", relief=SUNKEN, bd=0) + icon = Image.open(os.path.join(cwd + "\\UI\\icons", "alhtmltomarkdown.ico")) icon = icon.resize((30, 30), Image.ANTIALIAS) icon = ImageTk.PhotoImage(icon) iconLabel = Label(titleBar, image=icon) iconLabel.photo = icon - iconLabel.config(bg='#141414') + iconLabel.config(bg="#141414") iconLabel.grid(row=0, column=0, sticky="nsew") - titleLabel = Label(titleBar, text='ALHTMLTOMARKDOWN', fg='#909090', - bg='#141414', font=appHighlightFont) + titleLabel = Label( + titleBar, + text="ALHTMLTOMARKDOWN", + fg="#909090", + bg="#141414", + font=appHighlightFont, + ) titleLabel.grid(row=0, column=1, sticky="nsew") - closeButton = Button(titleBar, text="x", bg='#141414', fg="#909090", - borderwidth=0, command=root.destroy, - font=appHighlightFont) + closeButton = Button( + titleBar, + text="x", + bg="#141414", + fg="#909090", + borderwidth=0, + command=root.destroy, + font=appHighlightFont, + ) closeButton.grid(row=0, column=3, sticky="nsew") - minimizeButton = Button(titleBar, text="-", bg='#141414', fg="#909090", - borderwidth=0, command=hideScreen, - font=appHighlightFont) + minimizeButton = Button( + titleBar, + text="-", + bg="#141414", + fg="#909090", + borderwidth=0, + command=hideScreen, + font=appHighlightFont, + ) minimizeButton.grid(row=0, column=2, sticky="nsew") titleBar.grid_columnconfigure(0, weight=1) titleBar.grid_columnconfigure(1, weight=30) @@ -97,20 +116,34 @@ def markdown(): fileText = Label(root, text="HTML FILE") fileText.pack() fileText.config(bg=color, fg="white", font=appHighlightFont) - fileText = Entry(root, bg="white", fg='#7a1da3', - highlightbackground=color, highlightcolor=color, - highlightthickness=3, bd=0, font=textHighlightFont) + fileText = Entry( + root, + bg="white", + fg="#7a1da3", + highlightbackground=color, + highlightcolor=color, + highlightthickness=3, + bd=0, + font=textHighlightFont, + ) fileText.pack(fill=X) - convertToMarkdown = Button(root, borderwidth=0, highlightthickness=3, - text="MARKDOWN", command=markdown) + convertToMarkdown = Button( + root, borderwidth=0, highlightthickness=3, text="MARKDOWN", command=markdown + ) convertToMarkdown.config(bg=color, fg="white", font=appHighlightFont) convertToMarkdown.pack(fill=X) - text = Text(root, font="sans-serif", relief=SUNKEN, - highlightbackground=color, highlightcolor=color, - highlightthickness=5, bd=0) - text.config(bg="white", fg='#7a1da3', height=2, font=textHighlightFont) + text = Text( + root, + font="sans-serif", + relief=SUNKEN, + highlightbackground=color, + highlightcolor=color, + highlightthickness=5, + bd=0, + ) + text.config(bg="white", fg="#7a1da3", height=2, font=textHighlightFont) text.pack(fill=BOTH, expand=True) titleBar.bind("", callback) diff --git a/html_to_pdf/htmtopdf.py b/html_to_pdf/htmtopdf.py index c42b66e6d..63acd8305 100644 --- a/html_to_pdf/htmtopdf.py +++ b/html_to_pdf/htmtopdf.py @@ -1,5 +1,5 @@ import pdfkit -fr_url = input('Enter the url the html of which will be converted to pdf : ') -to_pdf = input('Enter the output of the file without pdf extension :') -pdfkit.from_url(fr_url, to_pdf + '.pdf') +fr_url = input("Enter the url the html of which will be converted to pdf : ") +to_pdf = input("Enter the output of the file without pdf extension :") +pdfkit.from_url(fr_url, to_pdf + ".pdf") diff --git a/ig_dontfollowback/main.py b/ig_dontfollowback/main.py index 8bdf94c39..0d26e35f7 100644 --- a/ig_dontfollowback/main.py +++ b/ig_dontfollowback/main.py @@ -1,18 +1,29 @@ # Made by Maxim Iliouchenko (https://github.com/maxily1) # Importing Libraries -import instaloader import argparse +import instaloader + # Get instance L = instaloader.Instaloader() # Creating an argument parser -parser = argparse.ArgumentParser(description='Process log-in data') +parser = argparse.ArgumentParser(description="Process log-in data") # Adding arguments -parser.add_argument('-u', type=str, required=True, help="Enter a username which will be used in the app.") -parser.add_argument('-p', type=str, required=True, help="Enter a password which will be used in the app.") +parser.add_argument( + "-u", + type=str, + required=True, + help="Enter a username which will be used in the app.", +) +parser.add_argument( + "-p", + type=str, + required=True, + help="Enter a password which will be used in the app.", +) # Parsing the args args = parser.parse_args() @@ -47,7 +58,9 @@ print(not_following_back) -choice = input("Would you like to save the people who don't follow you as a file? (y/n): ") +choice = input( + "Would you like to save the people who don't follow you as a file? (y/n): " +) if choice == "y": f = open("dont_follow_back.txt", "w") for person in not_following_back: diff --git a/image_annotater/imageannotater.py b/image_annotater/imageannotater.py index 4b3f5d687..a4fc017d3 100644 --- a/image_annotater/imageannotater.py +++ b/image_annotater/imageannotater.py @@ -1,10 +1,12 @@ +import sys + import cv2 import numpy as np import pandas as pd -import sys + # Define the file name of the image INPUT_IMAGE = sys.argv[1] -IMAGE_NAME = INPUT_IMAGE[:INPUT_IMAGE.index(".")] +IMAGE_NAME = INPUT_IMAGE[: INPUT_IMAGE.index(".")] OUTPUT_IMAGE = IMAGE_NAME + "_annotated.jpg" output_csv_file = sys.argv[2] # Load the image and store into a variable @@ -15,12 +17,20 @@ y_vals = [] annotation_vals = [] # Dictionary containing some colors -colors = {'blue': (255, 0, 0), 'green': (0, 255, 0), 'red': (0, 0, 255), - 'yellow': (0, 255, 255), 'magenta': (255, 0, 255), - 'cyan': (255, 255, 0), 'white': (255, 255, 255), 'black': (0, 0, 0), - 'gray': (125, 125, 125), - 'rand': np.random.randint(0, high=256, size=(3,)).tolist(), - 'dark_gray': (50, 50, 50), 'light_gray': (220, 220, 220)} +colors = { + "blue": (255, 0, 0), + "green": (0, 255, 0), + "red": (0, 0, 255), + "yellow": (0, 255, 255), + "magenta": (255, 0, 255), + "cyan": (255, 255, 0), + "white": (255, 255, 255), + "black": (0, 0, 0), + "gray": (125, 125, 125), + "rand": np.random.randint(0, high=256, size=(3,)).tolist(), + "dark_gray": (50, 50, 50), + "light_gray": (220, 220, 220), +} def draw_circle(event, x, y, flags, param): @@ -33,7 +43,7 @@ def draw_circle(event, x, y, flags, param): if event == cv2.EVENT_LBUTTONDBLCLK: # Draw the dot - cv2.circle(image, (x, y), 5, colors['magenta'], -1) + cv2.circle(image, (x, y), 5, colors["magenta"], -1) # Annotate the image txt = input("Describe this pixel using one word (e.g. dog) and press ENTER: ") @@ -44,21 +54,27 @@ def draw_circle(event, x, y, flags, param): annotation_vals.append(txt) # Print the coordinates and the annotation to the console - print("x = " + str(x) + " y = " + str(y) - + " Annotation = " + txt + "\n") + print("x = " + str(x) + " y = " + str(y) + " Annotation = " + txt + "\n") # Set the position of the text part of the annotation text_x_pos = None text_y_pos = y - if x < (width / 2) : + if x < (width / 2): text_x_pos = int(x + (width * 0.075)) else: text_x_pos = int(x - (width * 0.075)) # Write text on the image - cv2.putText(image, txt, (text_x_pos, text_y_pos), - cv2.FONT_HERSHEY_SIMPLEX, 1, colors['magenta'], 2) + cv2.putText( + image, + txt, + (text_x_pos, text_y_pos), + cv2.FONT_HERSHEY_SIMPLEX, + 1, + colors["magenta"], + 2, + ) cv2.imwrite(OUTPUT_IMAGE, image) @@ -70,21 +86,21 @@ def draw_circle(event, x, y, flags, param): print("Double click anywhere inside the image to annotate that point...\n") # We create a named window where the mouse callback will be established -cv2.namedWindow('Image mouse') +cv2.namedWindow("Image mouse") # We set the mouse callback function to 'draw_circle': -cv2.setMouseCallback('Image mouse', draw_circle) +cv2.setMouseCallback("Image mouse", draw_circle) while True: # Show image 'Image mouse': - cv2.imshow('Image mouse', image) + cv2.imshow("Image mouse", image) # Continue until 'q' is pressed: - if cv2.waitKey(20) & 0xFF == ord('q'): + if cv2.waitKey(20) & 0xFF == ord("q"): break # Create a dictionary using lists -data = {'X': x_vals, 'Y': y_vals, 'Annotation': annotation_vals} +data = {"X": x_vals, "Y": y_vals, "Annotation": annotation_vals} # Create the Pandas DataFrame df = pd.DataFrame(data) diff --git a/image_background_subtractor/image_background_subtractor.py b/image_background_subtractor/image_background_subtractor.py index 556d09216..eb259d5ca 100644 --- a/image_background_subtractor/image_background_subtractor.py +++ b/image_background_subtractor/image_background_subtractor.py @@ -1,12 +1,15 @@ import cv2 import mediapipe as mp import numpy as np + mp_drawing = mp.solutions.drawing_utils mp_selfie_segmentation = mp.solutions.selfie_segmentation # You can use multiple Images for removal at a go by just specifying the name of the images in the list. -IMAGE_FILES = ['location_to_image/image.jpg'] +IMAGE_FILES = ["location_to_image/image.jpg"] BG_COLOR = (192, 192, 192) # gray, you can set to any -with mp_selfie_segmentation.SelfieSegmentation(model_selection=0) as selfie_segmentation: +with mp_selfie_segmentation.SelfieSegmentation( + model_selection=0 +) as selfie_segmentation: for idx, file in enumerate(IMAGE_FILES): image = cv2.imread(file) image_height, image_width, _ = image.shape @@ -15,4 +18,4 @@ bg_image = np.zeros(image.shape, dtype=np.uint8) bg_image[:] = BG_COLOR output_image = np.where(condition, image, bg_image) - cv2.imwrite('location_to_store_result/result' + str(idx) + '.png', output_image) + cv2.imwrite("location_to_store_result/result" + str(idx) + ".png", output_image) diff --git a/image_cartoonizer/imagecartoonizer.py b/image_cartoonizer/imagecartoonizer.py index 5c2fe960d..b74554d98 100644 --- a/image_cartoonizer/imagecartoonizer.py +++ b/image_cartoonizer/imagecartoonizer.py @@ -1,4 +1,5 @@ import cv2 + # import numpy as np img = cv2.imread(r"input image.jpg") @@ -6,8 +7,9 @@ # 1) Edges gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 5) -edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, - cv2.THRESH_BINARY, 9, 9) +edges = cv2.adaptiveThreshold( + gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 9 +) # 2) Color color = cv2.bilateralFilter(img, 9, 300, 300) diff --git a/image_collage/image_collage.py b/image_collage/image_collage.py index b83fdad65..e6f90283c 100644 --- a/image_collage/image_collage.py +++ b/image_collage/image_collage.py @@ -1,7 +1,8 @@ -import requests -from PIL import Image from io import BytesIO + import numpy as np +import requests +from PIL import Image lst = [] for i in range(0, 4): diff --git a/image_compressor/image_compressor.py b/image_compressor/image_compressor.py index f9c43ed60..15f587223 100644 --- a/image_compressor/image_compressor.py +++ b/image_compressor/image_compressor.py @@ -1,7 +1,8 @@ -from PIL import Image from os.path import getsize from tkinter.filedialog import askopenfilename, asksaveasfilename +from PIL import Image + def compress(): file_path = askopenfilename(title="select image ") @@ -19,5 +20,5 @@ def compress(): print(f"New size of image is : {getsize(save_path)} Bytes") -if __name__ == '__main__': +if __name__ == "__main__": compress() diff --git a/image_cropper/image_cropper.py b/image_cropper/image_cropper.py index 0f2b442bd..2b6edd189 100644 --- a/image_cropper/image_cropper.py +++ b/image_cropper/image_cropper.py @@ -4,32 +4,34 @@ def crop(): # Taking the image path as an input - file_path = str(input('Enter the image path (absolute path): ')) + file_path = str(input("Enter the image path (absolute path): ")) # Opening image with an RGB mode, works only with jpeg/jpg formats img = Image.open(file_path, mode="r") # Calculating size of the original image in pixels for reference width, height = img.size - print('the old width is: ' + str(width) + ' and the old height is: ' + str(height)) + print("the old width is: " + str(width) + " and the old height is: " + str(height)) # Taking left, top, right, bottom points for the cropped image as input # Image pixels coorginate grid: X increases from left to right, Y increases from top to bottom - left = int(input('Enter the new left point: ')) - top = int(input('Enter the new top point: ')) - right = int(input('Enter the new right point: ')) - bottom = int(input('Enter the new bottom point: ')) + left = int(input("Enter the new left point: ")) + top = int(input("Enter the new top point: ")) + right = int(input("Enter the new right point: ")) + bottom = int(input("Enter the new bottom point: ")) # Crop the image with specified points cropped_img = img.crop((left, top, right, bottom)) # Save the cropped image as a separate image named "cropped_img.jpg" under a specified directory - cropped_image_path = str(input('Enter the path to save the cropped image (absolute path): ')) + cropped_image_path = str( + input("Enter the path to save the cropped image (absolute path): ") + ) cropped_img.save(f"{cropped_image_path}/cropped_img.jpg") # Show the image in the image viewer cropped_img.show() -if __name__ == '__main__': +if __name__ == "__main__": crop() diff --git a/image_downloader/main.py b/image_downloader/main.py index 6fb0cb9b0..68257803a 100644 --- a/image_downloader/main.py +++ b/image_downloader/main.py @@ -1,7 +1,8 @@ +import os +from io import BytesIO + import requests from PIL import Image -from io import BytesIO -import os download_path = os.path.dirname(os.path.abspath(__file__)) count = 1 diff --git a/image_encoder/decode_img.py b/image_encoder/decode_img.py index d2bc22356..a6f308e4b 100644 --- a/image_encoder/decode_img.py +++ b/image_encoder/decode_img.py @@ -5,11 +5,11 @@ def decode(): f = open("base64_image.txt", "r") base64_img = f.read() f.close() - base64_img_bytes = base64_img.encode('utf-8') - with open('decoded_image.png', 'wb') as file_to_save: + base64_img_bytes = base64_img.encode("utf-8") + with open("decoded_image.png", "wb") as file_to_save: decoded_image_data = base64.decodebytes(base64_img_bytes) file_to_save.write(decoded_image_data) -if __name__ == '__main__': +if __name__ == "__main__": decode() diff --git a/image_encoder/encode_img.py b/image_encoder/encode_img.py index b8c2ec5c0..00f11e56b 100644 --- a/image_encoder/encode_img.py +++ b/image_encoder/encode_img.py @@ -1,21 +1,21 @@ -import os import base64 +import os def encoder(): - img_file = os.listdir('encode_image/') - print('file to be encode: ', img_file) + img_file = os.listdir("encode_image/") + print("file to be encode: ", img_file) for image in img_file: - with open("encode_image/" + image, 'rb') as binary_file: + with open("encode_image/" + image, "rb") as binary_file: binary_file_data = binary_file.read() base64_encoded_data = base64.b64encode(binary_file_data) - base64_message = base64_encoded_data.decode('utf-8') + base64_message = base64_encoded_data.decode("utf-8") print(base64_message) - f = open('encoded.txt', 'w') + f = open("encoded.txt", "w") f.write("data:image/png;base64," + base64_message) f.close() -if __name__ == '__main__': +if __name__ == "__main__": encoder() diff --git a/image_resizer/image_resizer.py b/image_resizer/image_resizer.py index ca1e91f69..45a9730ea 100644 --- a/image_resizer/image_resizer.py +++ b/image_resizer/image_resizer.py @@ -1,32 +1,33 @@ -import cv2 -import os import argparse +import os + +import cv2 parser = argparse.ArgumentParser() parser.add_argument( - '-f', + "-f", type=str, - help='The file path of target image. ' + help="The file path of target image. " + 'ex. /home/user/example.jpeg.\nDefault value is "demo.jpeg"', - default=os.path.dirname(__file__) + '/demo.jpeg' + default=os.path.dirname(__file__) + "/demo.jpeg", ) parser.add_argument( - '-rw', + "-rw", type=int, help='The new width to be resize.\nDefault value is "640"', - default=640 + default=640, ) parser.add_argument( - '-rh', + "-rh", type=int, help='The new height to be resize.\nDefault value is "480"', - default=480 + default=480, ) parser.add_argument( - '-n', + "-n", type=str, - help='The file name.\n' - + 'Default value is current {current file name}_{rw}x{rh}.jpeg', + help="The file name.\n" + + "Default value is current {current file name}_{rw}x{rh}.jpeg", ) args = parser.parse_args() @@ -37,8 +38,8 @@ if args.n: new_file = args.n else: - new_file = (lambda x: x.split('/')[-1].split('.')[0])(args.f) - new_file += f'_{args.rw}x{args.rh}.jpeg' + new_file = (lambda x: x.split("/")[-1].split(".")[0])(args.f) + new_file += f"_{args.rw}x{args.rh}.jpeg" # If path is invalid, ask user to input image path again # and output current image ratio @@ -46,15 +47,16 @@ img = cv2.imread(img_path) if img is None: print( - 'Directory or file is not valid,' - + ' please enter a valid file directory ...') - img_path = str(input('Enter the image path again (absolute path): ')) + "Directory or file is not valid," + + " please enter a valid file directory ..." + ) + img_path = str(input("Enter the image path again (absolute path): ")) else: break original_width = img.shape[0] original_height = img.shape[1] -print(f'Current image ratio is {original_width} x {original_height}') +print(f"Current image ratio is {original_width} x {original_height}") # If stdin rw & rh value larger than original img size # ask user to input again. @@ -62,26 +64,26 @@ try: if resized_width > original_width: raise RuntimeError( - 'Resized width must be no larger than original width' - + f' (< {original_width})' + "Resized width must be no larger than original width" + + f" (< {original_width})" ) if resized_height > original_height: raise RuntimeError( - 'Resized height must be no larger than original height' - + f' (< {original_height})' + "Resized height must be no larger than original height" + + f" (< {original_height})" ) break except RuntimeError as err: print(err) - resized_width = int(input('Enter the new width: ')) - resized_height = int(input('Enter the new height: ')) + resized_width = int(input("Enter the new width: ")) + resized_height = int(input("Enter the new height: ")) # Export new resized image onto the same dir as image_resizer.py new_img = cv2.resize(img, (resized_width, resized_height)) -cv2.imwrite(f'{os.path.dirname(__file__)}/{new_file}', new_img) +cv2.imwrite(f"{os.path.dirname(__file__)}/{new_file}", new_img) -comment = f'Resized image ({resized_width} x {resized_height})' -comment += ' is now stored on the directory below:' -comment += f'\n{os.path.dirname(__file__)}/{new_file}' +comment = f"Resized image ({resized_width} x {resized_height})" +comment += " is now stored on the directory below:" +comment += f"\n{os.path.dirname(__file__)}/{new_file}" print(comment) diff --git a/image_rounded_corner/rounded_corner.py b/image_rounded_corner/rounded_corner.py index 7d56b5fad..85e65c796 100644 --- a/image_rounded_corner/rounded_corner.py +++ b/image_rounded_corner/rounded_corner.py @@ -2,10 +2,10 @@ def add_corners(im, rad): - circle = Image.new('L', (rad * 2, rad * 2), 0) + circle = Image.new("L", (rad * 2, rad * 2), 0) draw = ImageDraw.Draw(circle) draw.ellipse((0, 0, rad * 2, rad * 2), fill=255) - alpha = Image.new('L', im.size, 255) + alpha = Image.new("L", im.size, 255) w, h = im.size alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0)) alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad)) @@ -15,6 +15,6 @@ def add_corners(im, rad): return im -im = Image.open('Location_to_image/image.png') +im = Image.open("Location_to_image/image.png") im = add_corners(im, 100) -im.save('Location_to_store/img_rounded.png') +im.save("Location_to_store/img_rounded.png") diff --git a/image_separator/main.py b/image_separator/main.py index 2e56b4cd5..3cd39923e 100644 --- a/image_separator/main.py +++ b/image_separator/main.py @@ -2,21 +2,21 @@ import os import cv2 - -from keras.applications.vgg16 import VGG16, preprocess_input - import numpy as np - +from keras.applications.vgg16 import VGG16, preprocess_input from sklearn.cluster import KMeans - from tensorflow.keras.models import Model - -parser = argparse.ArgumentParser(description='Summarize the given text') -parser.add_argument('-p', '--path', help="Path to the directory", type=str) -parser.add_argument('-c', '--cluster', help="Number of cluster", type=int) -parser.add_argument('-o', '--output', help="output location (default: OUTPUT)", - type=str, default="./OUTPUT/") +parser = argparse.ArgumentParser(description="Summarize the given text") +parser.add_argument("-p", "--path", help="Path to the directory", type=str) +parser.add_argument("-c", "--cluster", help="Number of cluster", type=int) +parser.add_argument( + "-o", + "--output", + help="output location (default: OUTPUT)", + type=str, + default="./OUTPUT/", +) args = parser.parse_args() if not (args.path): @@ -30,9 +30,8 @@ def get_model(): - base_model = VGG16(weights='imagenet', include_top=True) - model = Model(inputs=base_model.input, - outputs=base_model.layers[-2].output) + base_model = VGG16(weights="imagenet", include_top=True) + model = Model(inputs=base_model.input, outputs=base_model.layers[-2].output) return model @@ -62,7 +61,7 @@ def feature_vectors(imgs_dict, model): def clustering(img_feature_vector): images = list(img_feature_vector.values()) - kmeans = KMeans(n_clusters=CLUSTER, init='k-means++') + kmeans = KMeans(n_clusters=CLUSTER, init="k-means++") kmeans.fit(images) y_kmeans = kmeans.predict(images) file_names = list(imgs_dict.keys()) @@ -73,17 +72,17 @@ def separate(y_kmeans, file_names): n_clusters = CLUSTER cluster_path = OUTPUT path_to_files = PATH_TO_FILES - if (not os.path.exists(cluster_path)): + if not os.path.exists(cluster_path): os.mkdir(cluster_path) for c in range(0, n_clusters): - if not os.path.exists(cluster_path + 'cluster_' + str(c)): - os.mkdir(cluster_path + 'cluster_' + str(c)) + if not os.path.exists(cluster_path + "cluster_" + str(c)): + os.mkdir(cluster_path + "cluster_" + str(c)) for fn, cluster in zip(file_names, y_kmeans): image = cv2.imread(os.path.join(path_to_files, fn)) - cv2.imwrite(cluster_path + 'cluster_' + str(cluster) + '/' + fn, image) + cv2.imwrite(cluster_path + "cluster_" + str(cluster) + "/" + fn, image) -if __name__ == '__main__': +if __name__ == "__main__": imgs_dict = get_files(path_to_files=PATH_TO_FILES, size=(224, 224)) model = get_model() diff --git a/image_steganography/Image_steganography_decode.py b/image_steganography/Image_steganography_decode.py index b2604c392..d4260b4e0 100644 --- a/image_steganography/Image_steganography_decode.py +++ b/image_steganography/Image_steganography_decode.py @@ -1,8 +1,9 @@ +import codecs +import math + import cv2 import numpy as np from Crypto.Cipher import AES -import math -import codecs def decrypt(mess, key): @@ -22,11 +23,11 @@ def correlation(M1, M2): lo = li + ls - 1 wo = wi + ws - 1 g = np.zeros([li + ls * 2 - 2, wi + ws * 2 - 2]) - g[ls - 1:li + ls - 1, ws - 1:wi + ws - 1] = M1 + g[ls - 1 : li + ls - 1, ws - 1 : wi + ws - 1] = M1 out = np.zeros([lo, wo]) for x in range(lo): for y in range(wo): - C = np.multiply(g[x:x + ls, y:y + ws], M2) + C = np.multiply(g[x : x + ls, y : y + ws], M2) out[x, y] = np.sum(C) return out @@ -39,9 +40,13 @@ def gaussian_filter(dim): m = int((dim / 2) + 1) for i in range(int((dim / 2) + 1)): for j in range(int((dim / 2) + 1)): - fil[i, j] = np.exp(- ((((m - i - 1)**2) + ((m - j - 1)**2)) / (2 * sigma ** 2))) + fil[i, j] = np.exp( + -((((m - i - 1) ** 2) + ((m - j - 1) ** 2)) / (2 * sigma**2)) + ) fil[i, j] = fil[i, j] / (2 * np.pi * sigma**2) - fil[i, k - j - 1] = fil[k - i - 1, j] = fil[k - i - 1, k - j - 1] = fil[i, j] + fil[i, k - j - 1] = fil[k - i - 1, j] = fil[k - i - 1, k - j - 1] = fil[ + i, j + ] s = np.sum(fil) fil = fil / s return fil @@ -81,7 +86,7 @@ def image_steg_decode(orimg, gr, key): f = np.append(f, num) ascii_string = "" for i in range(int(n / 8)): - b = ' '.join(str(int(e)) for e in f[i * 8:(i * 8) + 8]) + b = " ".join(str(int(e)) for e in f[i * 8 : (i * 8) + 8]) b = b.replace(" ", "") an_integer = int(b, 2) ascii_character = chr(an_integer) @@ -96,17 +101,17 @@ def image_steg_decode(orimg, gr, key): n = n + 1 ascii_string = "" for i in range(int((le + 80) / 8)): - b = ' '.join(str(int(e)) for e in f[i * 8:(i * 8) + 8]) + b = " ".join(str(int(e)) for e in f[i * 8 : (i * 8) + 8]) b = b.replace(" ", "") an_integer = int(b, 2) ascii_character = chr(an_integer) ascii_string += ascii_character ascii_string = ascii_string[12:-1] - ascii_string = bytes(ascii_string, 'utf-8') - ed, _ = codecs.escape_decode(ascii_string, 'hex') + ascii_string = bytes(ascii_string, "utf-8") + ed, _ = codecs.escape_decode(ascii_string, "hex") print(ed) ans = decrypt(ed, key) - return (ans) + return ans image = cv2.imread("original image") diff --git a/image_steganography/image_steganography.py b/image_steganography/image_steganography.py index cfd2ac689..b0d6ee73d 100644 --- a/image_steganography/image_steganography.py +++ b/image_steganography/image_steganography.py @@ -1,9 +1,10 @@ +import math + import cv2 import numpy as np from Crypto.Cipher import AES -import math -image = cv2.imread('file location') +image = cv2.imread("file location") def encrypt(mess, key): @@ -26,11 +27,11 @@ def correlation(M1, M2): lo = li + ls - 1 wo = wi + ws - 1 g = np.zeros([li + ls * 2 - 2, wi + ws * 2 - 2]) - g[ls - 1:li + ls - 1, ws - 1:wi + ws - 1] = M1 + g[ls - 1 : li + ls - 1, ws - 1 : wi + ws - 1] = M1 out = np.zeros([lo, wo]) for x in range(lo): for y in range(wo): - C = np.multiply(g[x:x + ls, y:y + ws], M2) + C = np.multiply(g[x : x + ls, y : y + ws], M2) out[x, y] = np.sum(C) return out @@ -43,9 +44,13 @@ def gaussian_filter(dim): m = int((dim / 2) + 1) for i in range(int((dim / 2) + 1)): for j in range(int((dim / 2) + 1)): - fil[i, j] = np.exp(-((((m - i - 1)**2) + ((m - j - 1)**2)) / (2 * sigma**2))) + fil[i, j] = np.exp( + -((((m - i - 1) ** 2) + ((m - j - 1) ** 2)) / (2 * sigma**2)) + ) fil[i, j] = fil[i, j] / (2 * np.pi * sigma**2) - fil[i, k - j - 1] = fil[k - i - 1, j] = fil[k - i - 1, k - j - 1] = fil[i, j] + fil[i, k - j - 1] = fil[k - i - 1, j] = fil[k - i - 1, k - j - 1] = fil[ + i, j + ] s = np.sum(fil) fil = fil / s return fil @@ -78,12 +83,12 @@ def image_steg(img, mess, key): l1 = l1 + "/" arr = " ".join(f"{ord(x):08b}" for x in l1) for j in arr: - if j != ' ': + if j != " ": le = np.append(le, int(j)) for i in le: x, y = f_points[n] pix_val = img_gray[x, y] - if (pix_val % 2 == i): + if pix_val % 2 == i: img_gray[x, y] = img_gray[x, y] else: img_gray[x, y] = img_gray[x, y] - 1 @@ -92,7 +97,7 @@ def image_steg(img, mess, key): for i in f: x, y = f_points[n] pix_val = img_gray[x, y] - if (pix_val % 2 == i): + if pix_val % 2 == i: img_gray[x, y] = img_gray[x, y] else: img_gray[x, y] = img_gray[x, y] - 1 diff --git a/image_to_pdf/main.py b/image_to_pdf/main.py index 6042d10d8..ba7e811b9 100644 --- a/image_to_pdf/main.py +++ b/image_to_pdf/main.py @@ -1,16 +1,17 @@ import os + from fpdf import FPDF def converter(): - img_files = os.listdir('images/') - print('files to be converted: ', img_files) + img_files = os.listdir("images/") + print("files to be converted: ", img_files) pdf = FPDF() for image in img_files: pdf.add_page() - pdf.image('images/' + image) - pdf.output('converted.pdf', 'F') + pdf.image("images/" + image) + pdf.output("converted.pdf", "F") -if __name__ == '__main__': +if __name__ == "__main__": converter() diff --git a/image_to_speech/image_to_speech.py b/image_to_speech/image_to_speech.py index 45c0edbcb..f6007b305 100644 --- a/image_to_speech/image_to_speech.py +++ b/image_to_speech/image_to_speech.py @@ -1,10 +1,11 @@ import pytesseract -from PIL import Image import pyttsx3 -img = Image.open('Location_to_Image/text_image.png') -pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe' +from PIL import Image + +img = Image.open("Location_to_Image/text_image.png") +pytesseract.pytesseract.tesseract_cmd = "C:/Program Files/Tesseract-OCR/tesseract.exe" result = pytesseract.image_to_string(img) -with open('text.txt', mode='w') as file: +with open("text.txt", mode="w") as file: file.write(result) print(result) engine = pyttsx3.init() diff --git a/images_to_video/img2vid.py b/images_to_video/img2vid.py index 5d561416e..d747682dd 100644 --- a/images_to_video/img2vid.py +++ b/images_to_video/img2vid.py @@ -1,11 +1,13 @@ -import cv2 +import argparse +import cv2 from imutils import paths -import argparse ap = argparse.ArgumentParser() ap.add_argument("-p", "--path", required=True, help="path to input directory") -ap.add_argument("-o", "--output_video", type=str, required=True, help="output video name") +ap.add_argument( + "-o", "--output_video", type=str, required=True, help="output video name" +) args = vars(ap.parse_args()) out = None @@ -23,7 +25,9 @@ img_array.append(img) if out is None: - out = cv2.VideoWriter(args["output_video"], cv2.VideoWriter_fourcc(*'DIVX'), 1, (w, h), True) + out = cv2.VideoWriter( + args["output_video"], cv2.VideoWriter_fourcc(*"DIVX"), 1, (w, h), True + ) for i in range(len(img_array)): out.write(img_array[i]) diff --git a/imdb_episode_rename/rename.py b/imdb_episode_rename/rename.py index 5c0114d3d..a0ff30fd1 100644 --- a/imdb_episode_rename/rename.py +++ b/imdb_episode_rename/rename.py @@ -1,38 +1,46 @@ +import argparse import os + import imdb -import argparse from termcolor import colored -arg_parser = argparse.ArgumentParser( - usage='python rename.py [-h] [options]') +arg_parser = argparse.ArgumentParser(usage="python rename.py [-h] [options]") arg_parser.add_argument( - '-c', - '--code', + "-c", + "--code", type=str, - help='IMDb CODE for the Series', + help="IMDb CODE for the Series", required=False, - metavar='') + metavar="", +) arg_parser.add_argument( - '-e', - '--episode', + "-e", + "--episode", type=str, - help='Rename EPISODES of the series in the specified Directory', + help="Rename EPISODES of the series in the specified Directory", default=False, - metavar='') + metavar="", +) -arg_parser.add_argument('-s', '--subtitle', type=str, - help='Rename SUBTITLES of the Series in the Directory', - default=False, metavar='') +arg_parser.add_argument( + "-s", + "--subtitle", + type=str, + help="Rename SUBTITLES of the Series in the Directory", + default=False, + metavar="", +) arg_parser.add_argument( - '-t', - '--tag', + "-t", + "--tag", type=str, - help='Rename VIDEO TAGS for MKV Videos', + help="Rename VIDEO TAGS for MKV Videos", required=False, - metavar='') + metavar="", +) args = arg_parser.parse_args() @@ -48,28 +56,24 @@ def get_episodes(imdb_code): print("SERIES: {}".format(colored(series, "magenta"))) ia.update(series, "episodes") - episodes = series.data['episodes'] + episodes = series.data["episodes"] episode_list = [] for season in episodes.keys(): for episode in episodes[season]: - title = episodes[season][episode]['title'] + title = episodes[season][episode]["title"] if season < 10: if episode < 10: - ep_name = "{} S0{}E0{} - {}".format(series, - season, episode, title) + ep_name = "{} S0{}E0{} - {}".format(series, season, episode, title) else: - ep_name = "{} S0{}E{} - {}".format(series, - season, episode, title) + ep_name = "{} S0{}E{} - {}".format(series, season, episode, title) else: if episode < 10: - ep_name = "{} S{}E0{} - {}".format(series, - season, episode, title) + ep_name = "{} S{}E0{} - {}".format(series, season, episode, title) else: - ep_name = "{} S{}E{} - {}".format(series, - season, episode, title) + ep_name = "{} S{}E{} - {}".format(series, season, episode, title) for i in ep_name: if i in not_allowed: @@ -95,15 +99,17 @@ def rename_episode(directory, episode_list): ep_name += ext filename = os.path.join(directory, og_name) newfilename = os.path.join(directory, ep_name) - print("Renaming {} to {}".format( - colored(filename, 'yellow'), - colored(newfilename, 'green'))) + print( + "Renaming {} to {}".format( + colored(filename, "yellow"), colored(newfilename, "green") + ) + ) os.rename(filename, newfilename) print( - colored( - "RENAMING", "red"), colored( - "EPISODES", "cyan"), colored( - "FINISHED!\n", "red")) + colored("RENAMING", "red"), + colored("EPISODES", "cyan"), + colored("FINISHED!\n", "red"), + ) def rename_subtitle(directory, episode_list): @@ -120,15 +126,15 @@ def rename_subtitle(directory, episode_list): newfilename = os.path.join(directory, ep_name) print( "Renaming {} to {}".format( - colored( - filename, 'yellow'), colored( - newfilename, 'green'))) + colored(filename, "yellow"), colored(newfilename, "green") + ) + ) os.rename(filename, newfilename) print( - colored( - "RENAMING", "red"), colored( - "SUBTITLES", "cyan"), colored( - "FINISHED!\n", "red")) + colored("RENAMING", "red"), + colored("SUBTITLES", "cyan"), + colored("FINISHED!\n", "red"), + ) def edit_tag(directory): @@ -136,20 +142,22 @@ def edit_tag(directory): if ".mkv" in file: title = file.replace(".mkv", "") command = r'mkvpropedit "{}\{}" --set "title={}"'.format( - directory, file, title) + directory, file, title + ) os.system(command) if ".mp4" in file: title = file.replace(".mp4", "") command = r'mkvpropedit "{}\{}" --set "title={}"'.format( - directory, file, title) + directory, file, title + ) os.system(command) print( - colored( - "RENAMING", "red"), colored( - "VIDEO TAGS", "cyan"), colored( - "FINISHED!\n", "red")) + colored("RENAMING", "red"), + colored("VIDEO TAGS", "cyan"), + colored("FINISHED!\n", "red"), + ) if __name__ == "__main__": @@ -158,13 +166,13 @@ def edit_tag(directory): episodes = get_episodes(args.code) if args.episode: - args.episode = r'{}'.format(args.episode) + args.episode = r"{}".format(args.episode) rename_episode(args.episode, episodes) if args.subtitle: - args.subtitle = r'{}'.format(args.subtitle) + args.subtitle = r"{}".format(args.subtitle) rename_subtitle(args.subtitle, episodes) if args.tag: - args.tag = r'{}'.format(args.tag) + args.tag = r"{}".format(args.tag) edit_tag(args.tag) diff --git a/imdb_querier/imdb_movie_rating_querier.py b/imdb_querier/imdb_movie_rating_querier.py index b1d8d92ea..b546770f5 100644 --- a/imdb_querier/imdb_movie_rating_querier.py +++ b/imdb_querier/imdb_movie_rating_querier.py @@ -1,4 +1,5 @@ import sys + import imdb imdb_object = imdb.IMDb() @@ -7,14 +8,17 @@ print("Please provide movie name in proper format!!!") sys.exit() -movie_name = sys.argv[1].replace('_', ' ') +movie_name = sys.argv[1].replace("_", " ") try: search_result = imdb_object.search_movie(movie_name, 1) movie_data = search_result[0].__dict__ vote_details = imdb_object.get_movie_vote_details(movie_data["movieID"]) movie_rating_stats = vote_details["data"]["demographics"]["imdb users"] - print("Rating: %s, based on %s votes" % (movie_rating_stats["rating"], movie_rating_stats["votes"])) + print( + "Rating: %s, based on %s votes" + % (movie_rating_stats["rating"], movie_rating_stats["votes"]) + ) except KeyError: print("Movie ratings data is not available") diff --git a/instadp_downloader/insta_profile_pic_download.py b/instadp_downloader/insta_profile_pic_download.py index 36c0100b3..0de8d4011 100644 --- a/instadp_downloader/insta_profile_pic_download.py +++ b/instadp_downloader/insta_profile_pic_download.py @@ -18,10 +18,10 @@ # finding the image in the url # using html parser u = s.find("meta", property="og:image") -url = u.attrs['content'] +url = u.attrs["content"] # saving the image the folder # where this file is saved -with open(username + '.jpg', 'wb') as pic: +with open(username + ".jpg", "wb") as pic: binary = requests.get(url).content pic.write(binary) diff --git a/instagram_follow_bot/instabot.py b/instagram_follow_bot/instabot.py index c3958b308..0722f0712 100644 --- a/instagram_follow_bot/instabot.py +++ b/instagram_follow_bot/instabot.py @@ -1,14 +1,15 @@ +import csv +import time + from selenium import webdriver from selenium.webdriver.common.by import By -from selenium.webdriver.support.ui import WebDriverWait -from selenium.webdriver.support import expected_conditions as ec from selenium.webdriver.common.keys import Keys -import time -import csv +from selenium.webdriver.support import expected_conditions as ec +from selenium.webdriver.support.ui import WebDriverWait already_follow = [] -with open('follower.csv', 'r') as csv_file: +with open("follower.csv", "r") as csv_file: csv_reader = csv.reader(csv_file) for row in csv_reader: if len(row) != 0: @@ -27,15 +28,19 @@ def __init__(self, username, password): self.browser.maximize_window() def wait_for_object(self, type, string): - return WebDriverWait(self.browser, 3).until(ec.presence_of_element_located((type, string))) + return WebDriverWait(self.browser, 3).until( + ec.presence_of_element_located((type, string)) + ) def wait_for_objects(self, type, string): - return WebDriverWait(self.browser, 3).until(ec.presence_of_all_elements_located((type, string))) + return WebDriverWait(self.browser, 3).until( + ec.presence_of_all_elements_located((type, string)) + ) def login(self): self.browser.get("https://www.instagram.com") - inputs = self.wait_for_objects(By.CSS_SELECTOR, '._2hvTZ.pexuQ.zyHYP') + inputs = self.wait_for_objects(By.CSS_SELECTOR, "._2hvTZ.pexuQ.zyHYP") inputs[0].send_keys(self.username) inputs[1].send_keys(self.password) @@ -54,13 +59,14 @@ def follow_followers(self, root_name, number_follower): time.sleep(2) - followers = self.wait_for_objects(By.CSS_SELECTOR, '._81NM2') + followers = self.wait_for_objects(By.CSS_SELECTOR, "._81NM2") followers[1].click() for i in range(1, number_follower + 1): time.sleep(2) src1 = self.wait_for_object( - By.XPATH, f'/html/body/div[5]/div/div/div[2]/ul/div/li[{i}]') + By.XPATH, f"/html/body/div[5]/div/div/div[2]/ul/div/li[{i}]" + ) self.browser.execute_script("arguments[0].scrollIntoView();", src1) time.sleep(5) @@ -72,7 +78,7 @@ def follow_followers(self, root_name, number_follower): else: all_follower.append(follower_name) - with open('follower.csv', 'a') as csv_file: + with open("follower.csv", "a") as csv_file: csv_writer = csv.writer(csv_file) csv_writer.writerow(all_follower) @@ -82,13 +88,16 @@ def follow_followers(self, root_name, number_follower): time.sleep(5) subscribe_buttons = self.wait_for_objects( - By.XPATH, '//button[text()="Follow"]') + By.XPATH, '//button[text()="Follow"]' + ) subscribe_buttons[0].click() time.sleep(5) -bot = InstagramBot(username="enter-your-username-here", password="enter-your-password-here") +bot = InstagramBot( + username="enter-your-username-here", password="enter-your-password-here" +) bot.login() # bot.like_hashtag('lifestyle', 3) bot.follow_followers("therock", 3) diff --git a/instagram_follow_bot/instabot2.py b/instagram_follow_bot/instabot2.py index 772d05c76..1f8258a82 100644 --- a/instagram_follow_bot/instabot2.py +++ b/instagram_follow_bot/instabot2.py @@ -3,5 +3,4 @@ bot = InstaPy(username="enter-your-username-here", password="enter-your-password-here") bot.login() bot.set_skip_users(skip_private=False, skip_no_profile_pic=True) -bot.follow_user_followers('nitb.creators', amount=50, - randomize=False, sleep_delay=10) +bot.follow_user_followers("nitb.creators", amount=50, randomize=False, sleep_delay=10) diff --git a/instagram_scraper/instagram_scraper.py b/instagram_scraper/instagram_scraper.py index a0ed8a7d6..5b71bd57d 100644 --- a/instagram_scraper/instagram_scraper.py +++ b/instagram_scraper/instagram_scraper.py @@ -1,8 +1,9 @@ # import selenium, time, urllib.request -from selenium import webdriver import time import urllib.request +from selenium import webdriver + profileUrl = input("enter profile url to scrape: ") # open chrome and go to the set page driver = webdriver.Chrome() @@ -10,40 +11,47 @@ driver.get(profileUrl) # scroll to the bottom of the page -pageLength = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);" - "var pageLength=document.body.scrollHeight;return pageLength;") +pageLength = driver.execute_script( + "window.scrollTo(0, document.body.scrollHeight);" + "var pageLength=document.body.scrollHeight;return pageLength;" +) match = True while match: lastCount = pageLength - pageLength = driver.execute_script("window.scrollTo(0, document.body.scrollHeight);" - "var pageLength=document.body.scrollHeight;return pageLength;") + pageLength = driver.execute_script( + "window.scrollTo(0, document.body.scrollHeight);" + "var pageLength=document.body.scrollHeight;return pageLength;" + ) if lastCount == pageLength: match = False # find all links that match '/p' and append to list named userPosts userPosts = [] -links = driver.find_elements_by_tag_name('a') +links = driver.find_elements_by_tag_name("a") for link in links: - post = link.get_attribute('href') - if '/p/' in post: + post = link.get_attribute("href") + if "/p/" in post: userPosts.append(post) -download_url = '' +download_url = "" # extract shortcode and identify post type, then download them as jpg or mp4 depending on post type for post in userPosts: driver.get(post) shortcode = driver.current_url.split("/")[-2] postType = driver.find_element_by_xpath( - '//meta[@property="og:type"]').get_attribute('content') - if postType == 'video': + '//meta[@property="og:type"]' + ).get_attribute("content") + if postType == "video": download_url = driver.find_element_by_xpath( - "//meta[@property='og:video']").get_attribute('content') - urllib.request.urlretrieve(download_url, '{}.mp4'.format(shortcode)) + "//meta[@property='og:video']" + ).get_attribute("content") + urllib.request.urlretrieve(download_url, "{}.mp4".format(shortcode)) else: download_url = driver.find_element_by_xpath( - "//meta[@property='og:image']").get_attribute('content') - urllib.request.urlretrieve(download_url, '{}.jpg'.format(shortcode)) + "//meta[@property='og:image']" + ).get_attribute("content") + urllib.request.urlretrieve(download_url, "{}.jpg".format(shortcode)) time.sleep(5) # close connections and chrome once all posts are downloaded driver.close() diff --git a/interview_automater/app.py b/interview_automater/app.py index b8dcc5b53..28cc45919 100644 --- a/interview_automater/app.py +++ b/interview_automater/app.py @@ -1,13 +1,13 @@ # The code uses dash library in Python for rendering the web-app. # More information can be found at https://dash.plotly.com/ # Importing required libraries +import webbrowser + import dash -import dash_html_components as html import dash_core_components as dcc +import dash_html_components as html from dash.dependencies import Input, Output from dash.exceptions import PreventUpdate -import webbrowser - # Initialisation app = dash.Dash(__name__) @@ -21,119 +21,143 @@ # Setting layout app.layout = html.Div( - style={'textAlign': "center", "marginLeft": "50px", "marginRight": "50px"}, + style={"textAlign": "center", "marginLeft": "50px", "marginRight": "50px"}, children=[ html.H1( - style={'color': "#1876D2", 'fontWeight': "bolder", - "marginBottom": "50px", 'fontSize': "50px"}, - children='Test your personality 😁'), - html.H3('May I know your name?'), - dcc.Input(id='name', type='text', - style={"height": "30px", "borderRadius": "20px", - "textIndent": "10px", "fontSize": "20px"}), - html.Button('Submit', - style={'backgroundColor': "#1876D2", "border": "none", - "marginLeft": "10px", "outline": "none", - 'fontWeight': "bolder", "padding": "10px", - "borderRadius": "20px", 'color': "white"}, - id='submit', n_clicks=0), - html.Div(id='init'), - html.Div(id='q1'), - html.Div(id='q2'), - html.Div(id='q3'), - html.Div(id='q4'), - html.Div(id='q5'), - html.Div(id='q6'), - html.Div(id='q7'), - html.Div(id='q8'), - html.Div(id='q9'), - html.Div(id='q10'), - html.Div(id='result') - ] + style={ + "color": "#1876D2", + "fontWeight": "bolder", + "marginBottom": "50px", + "fontSize": "50px", + }, + children="Test your personality 😁", + ), + html.H3("May I know your name?"), + dcc.Input( + id="name", + type="text", + style={ + "height": "30px", + "borderRadius": "20px", + "textIndent": "10px", + "fontSize": "20px", + }, + ), + html.Button( + "Submit", + style={ + "backgroundColor": "#1876D2", + "border": "none", + "marginLeft": "10px", + "outline": "none", + "fontWeight": "bolder", + "padding": "10px", + "borderRadius": "20px", + "color": "white", + }, + id="submit", + n_clicks=0, + ), + html.Div(id="init"), + html.Div(id="q1"), + html.Div(id="q2"), + html.Div(id="q3"), + html.Div(id="q4"), + html.Div(id="q5"), + html.Div(id="q6"), + html.Div(id="q7"), + html.Div(id="q8"), + html.Div(id="q9"), + html.Div(id="q10"), + html.Div(id="result"), + ], ) # Using callbacks to handle questions and answers, # along with keeping a track of score @app.callback( - Output('init', 'children'), - [Input('name', 'value'), Input('submit', 'n_clicks')] + Output("init", "children"), [Input("name", "value"), Input("submit", "n_clicks")] ) def update_name(name, n_clicks): if n_clicks == 0: raise PreventUpdate else: - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''You like to spend + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""You like to spend your free time exploring something new or do you follow - same routine'''), - dcc.RadioItems( - id='a2', options=[{'label': 'New 💯', - 'value': 'new'}, - {'label': 'Same as always', - 'value': 'same'}], - value=None)] - - -@app.callback( - Output('q1', 'children'), - [Input('a1', 'value')] -) + same routine""", + ), + dcc.RadioItems( + id="a2", + options=[ + {"label": "New 💯", "value": "new"}, + {"label": "Same as always", "value": "same"}, + ], + value=None, + ), + ] + + +@app.callback(Output("q1", "children"), [Input("a1", "value")]) def q1(a1): global score if a1 is None: raise PreventUpdate else: - if a1 == 'yes': + if a1 == "yes": score = score + 1 - elif a1 == 'maybe': + elif a1 == "maybe": score = score + 0.5 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''You like to spend + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""You like to spend your free time exploring something new or do you follow - same routine'''), - dcc.RadioItems( - id='a2', options=[{'label': 'New 💯', - 'value': 'new'}, - {'label': 'Same as always', - 'value': 'same'}], - value=None)] - - -@app.callback( - Output('q2', 'children'), - [Input('a2', 'value')] -) + same routine""", + ), + dcc.RadioItems( + id="a2", + options=[ + {"label": "New 💯", "value": "new"}, + {"label": "Same as always", "value": "same"}, + ], + value=None, + ), + ] + + +@app.callback(Output("q2", "children"), [Input("a2", "value")]) def q2(a2): global score if a2 is None: raise PreventUpdate else: - if a2 == 'new': + if a2 == "new": score = score + 1 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children=''''How comfortable - are you while talking to new people?'''), - dcc.Slider( - id='a3', - min=0, - max=10, - marks={ - 0: 'Not at all', - 10: 'Absolutely comfortable' - }, - step=1, - value=None - )] - - -@app.callback( - Output('q3', 'children'), - [Input('a3', 'value')] -) + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""'How comfortable + are you while talking to new people?""", + ), + dcc.Slider( + id="a3", + min=0, + max=10, + marks={0: "Not at all", 10: "Absolutely comfortable"}, + step=1, + value=None, + ), + ] + + +@app.callback(Output("q3", "children"), [Input("a3", "value")]) def q3(a3): global score if a3 is None: @@ -159,203 +183,221 @@ def q3(a3): score = score + 0.9 elif a3 == 10: score = score + 1 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''What do you prefer- - hard work or smart work?'''), - dcc.RadioItems( - id='a4', - options=[{'label': 'Hard work', 'value': 'hard'}, - {'label': 'Smart work', 'value': 'smart'}, - {'label': 'It depends on the situation', - 'value': 'both'}], - value=None)] - - -@app.callback( - Output('q4', 'children'), - [Input('a4', 'value')] -) + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""What do you prefer- + hard work or smart work?""", + ), + dcc.RadioItems( + id="a4", + options=[ + {"label": "Hard work", "value": "hard"}, + {"label": "Smart work", "value": "smart"}, + {"label": "It depends on the situation", "value": "both"}, + ], + value=None, + ), + ] + + +@app.callback(Output("q4", "children"), [Input("a4", "value")]) def q4(a4): global score if a4 is None: raise PreventUpdate else: - if a4 == 'hard': + if a4 == "hard": score = score + 0.5 - elif a4 == 'smart': + elif a4 == "smart": score = score + 0.5 - elif a4 == 'both': + elif a4 == "both": score = score + 1 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''You and your peer + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""You and your peer are working together. He/she is stuck in a task. - Will you?'''), - dcc.RadioItems( - id='a5', - options=[{'label': 'Help them instantly', - 'value': 'fast'}, - {'label': '''Help after completing your current - work''', - 'value': 'curr'}, - {'label': '''Help after - completing all your work''', - 'value': 'no'}], - value=None)] + Will you?""", + ), + dcc.RadioItems( + id="a5", + options=[ + {"label": "Help them instantly", "value": "fast"}, + { + "label": """Help after completing your current + work""", + "value": "curr", + }, + { + "label": """Help after + completing all your work""", + "value": "no", + }, + ], + value=None, + ), + ] -@app.callback( - Output('q5', 'children'), - [Input('a5', 'value')] -) +@app.callback(Output("q5", "children"), [Input("a5", "value")]) def q5(a5): global score if a5 is None: raise PreventUpdate else: - if a5 == 'fast': + if a5 == "fast": score = score + 0.5 - elif a5 == 'curr': + elif a5 == "curr": score = score + 1 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''Which category do - you fit in?'''), - dcc.RadioItems( - id='a6', - options=[{'label': 'Extrovert', 'value': 'ex'}, - {'label': 'Introvert', 'value': 'in'}, - {'label': 'Ambivert', 'value': 'am'}], - value=None)] - - -@app.callback( - Output('q6', 'children'), - [Input('a6', 'value')] -) + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""Which category do + you fit in?""", + ), + dcc.RadioItems( + id="a6", + options=[ + {"label": "Extrovert", "value": "ex"}, + {"label": "Introvert", "value": "in"}, + {"label": "Ambivert", "value": "am"}, + ], + value=None, + ), + ] + + +@app.callback(Output("q6", "children"), [Input("a6", "value")]) def q6(a6): global score if a6 is None: raise PreventUpdate else: - if a6 == 'ex': + if a6 == "ex": score = score + 1 - elif a6 == 'am': + elif a6 == "am": score = score + 0.5 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''Are you willing to - work overtime if required?'''), - dcc.RadioItems( - id='a7', - options=[{'label': 'Yes I would be happy', - 'value': 'happy'}, - {'label': 'Yes, if I get paid accordingly', - 'value': 'pay'}, - {'label': 'No, I am not comfortable doing this', - 'value': 'no'}], - value=None)] - - -@app.callback( - Output('q7', 'children'), - [Input('a7', 'value')] -) + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""Are you willing to + work overtime if required?""", + ), + dcc.RadioItems( + id="a7", + options=[ + {"label": "Yes I would be happy", "value": "happy"}, + {"label": "Yes, if I get paid accordingly", "value": "pay"}, + {"label": "No, I am not comfortable doing this", "value": "no"}, + ], + value=None, + ), + ] + + +@app.callback(Output("q7", "children"), [Input("a7", "value")]) def q7(a7): global score if a7 is None: raise PreventUpdate else: - if a7 == 'happy': + if a7 == "happy": score = score + 1 - elif a7 == 'no': + elif a7 == "no": score = score + 0.5 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''How comfortable - will you be if we ask you to travel for work?'''), - dcc.RadioItems( - id='a8', - options=[{'label': 'No problem, I\'m ready', - 'value': 'ready'}, - {'label': 'Only if my safety is taken care of', - 'value': 'safe'}, - {'label': 'No, it is tiring for me', - 'value': 'no'}], - value=None)] - - -@app.callback( - Output('q8', 'children'), - [Input('a8', 'value')] -) + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""How comfortable + will you be if we ask you to travel for work?""", + ), + dcc.RadioItems( + id="a8", + options=[ + {"label": "No problem, I'm ready", "value": "ready"}, + {"label": "Only if my safety is taken care of", "value": "safe"}, + {"label": "No, it is tiring for me", "value": "no"}, + ], + value=None, + ), + ] + + +@app.callback(Output("q8", "children"), [Input("a8", "value")]) def q8(a8): global score if a8 is None: raise PreventUpdate else: - if a8 == 'ready': + if a8 == "ready": score = score + 1 - elif a8 == 'safe': + elif a8 == "safe": score = score + 1 - elif a8 == 'no': + elif a8 == "no": score = score + 0.5 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''What is the salary - range you expect as a fresher?'''), - dcc.RadioItems( - id='a9', - options=[{'label': '<= 4 lpa', - 'value': 'less'}, - {'label': '> 4 lpa till < 90 lpa', - 'value': 'more'}, - {'label': 'Best according to my talent', - 'value': 'mid'}], - value=None)] - - -@app.callback( - Output('q9', 'children'), - [Input('a9', 'value')] -) + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""What is the salary + range you expect as a fresher?""", + ), + dcc.RadioItems( + id="a9", + options=[ + {"label": "<= 4 lpa", "value": "less"}, + {"label": "> 4 lpa till < 90 lpa", "value": "more"}, + {"label": "Best according to my talent", "value": "mid"}, + ], + value=None, + ), + ] + + +@app.callback(Output("q9", "children"), [Input("a9", "value")]) def q9(a9): global score if a9 is None: raise PreventUpdate else: - if a9 == 'more': + if a9 == "more": score = score + 1 - elif a9 == 'mid': + elif a9 == "mid": score = score + 1 - elif a9 == 'less': + elif a9 == "less": score = score + 0.5 - return [html.Br(), - html.H3( - style={'color': "#1876D2"}, children='''How likely will + return [ + html.Br(), + html.H3( + style={"color": "#1876D2"}, + children="""How likely will you reveal the company policies to an outsider, either - knowingly or unknowingly?'''), - dcc.Slider( - id='a10', - min=1, - max=5, - marks={ - 1: 'Very unlikely', - 2: 'Somewhat unlikely', - 3: 'I don\'t know', - 4: 'somewhat likely', - 5: 'Very likely' - }, - step=1, - value=None - )] - - -@app.callback( - Output('q10', 'children'), - [Input('a10', 'value')] -) + knowingly or unknowingly?""", + ), + dcc.Slider( + id="a10", + min=1, + max=5, + marks={ + 1: "Very unlikely", + 2: "Somewhat unlikely", + 3: "I don't know", + 4: "somewhat likely", + 5: "Very likely", + }, + step=1, + value=None, + ), + ] + + +@app.callback(Output("q10", "children"), [Input("a10", "value")]) def q10(a10): global score if a10 is None: @@ -371,76 +413,118 @@ def q10(a10): score = score - 0.5 elif a10 == 5: score = score - 1 - return [html.Br(), html.H3('Any feedback you want to provide?'), - dcc.Input(id='res', type='text', - style={"height": "30px", "borderRadius": "20px", - "textIndent": "10px", "fontSize": "20px"}), - html.Button('Submit', id='feedback', n_clicks=0, - style={'backgroundColor': "#1876D2", - "border": "none", - "marginLeft": "10px", - "outline": "none", - 'fontWeight': "bolder", - "padding": "10px", - "borderRadius": "20px", - 'color': "white"}) - ] + return [ + html.Br(), + html.H3("Any feedback you want to provide?"), + dcc.Input( + id="res", + type="text", + style={ + "height": "30px", + "borderRadius": "20px", + "textIndent": "10px", + "fontSize": "20px", + }, + ), + html.Button( + "Submit", + id="feedback", + n_clicks=0, + style={ + "backgroundColor": "#1876D2", + "border": "none", + "marginLeft": "10px", + "outline": "none", + "fontWeight": "bolder", + "padding": "10px", + "borderRadius": "20px", + "color": "white", + }, + ), + ] # Displaying result according to score -@app.callback( - Output('result', 'children'), - [Input('feedback', 'n_clicks')] -) +@app.callback(Output("result", "children"), [Input("feedback", "n_clicks")]) def result(n_clicks): if n_clicks == 0: raise PreventUpdate else: if score == 0: - return [html.Br(), - html.H3("Score: " + str(score) + '''/10 --> I am sorry. - You are a poor fit.''', - style={"fontSize": "25px", "color": "#1876D2"}), - html.H3("😔"), - html.H3('Thanks for your time!')] + return [ + html.Br(), + html.H3( + "Score: " + + str(score) + + """/10 --> I am sorry. + You are a poor fit.""", + style={"fontSize": "25px", "color": "#1876D2"}, + ), + html.H3("😔"), + html.H3("Thanks for your time!"), + ] elif score < 5: - return [html.Br(), - html.H3("Score: " + str(score) + '''/10 --> You need to work - more upon your personality.''', - style={"fontSize": "25px", "color": "#1876D2"}), - html.H3("🙂"), - html.H3('Thanks for your time!')] + return [ + html.Br(), + html.H3( + "Score: " + + str(score) + + """/10 --> You need to work + more upon your personality.""", + style={"fontSize": "25px", "color": "#1876D2"}, + ), + html.H3("🙂"), + html.H3("Thanks for your time!"), + ] elif score == 5: - return [html.Br(), - html.H3("Score: " + str(score) + '''/10 --> You are average. - You can always improve.''', - style={"fontSize": "25px", "color": "#1876D2"}), - html.H3("😃"), - html.H3('Thanks for your time!')] + return [ + html.Br(), + html.H3( + "Score: " + + str(score) + + """/10 --> You are average. + You can always improve.""", + style={"fontSize": "25px", "color": "#1876D2"}, + ), + html.H3("😃"), + html.H3("Thanks for your time!"), + ] elif score > 5 and score < 8.5: - return [html.Br(), - html.H3("Score: " + str(score) + '''/10 --> You are a decent + return [ + html.Br(), + html.H3( + "Score: " + + str(score) + + """/10 --> You are a decent fit for the company. Remember, practise makes a - man perfect!''', - style={"fontSize": "25px", "color": "#1876D2"}), - html.H3("💯💯"), - html.H3('Thanks for your time!')] + man perfect!""", + style={"fontSize": "25px", "color": "#1876D2"}, + ), + html.H3("💯💯"), + html.H3("Thanks for your time!"), + ] elif score >= 8.5 and score <= 10: - return [html.Br(), - html.H3("Score: " + str(score) + '''/10 --> Excellent🎉 We + return [ + html.Br(), + html.H3( + "Score: " + + str(score) + + """/10 --> Excellent🎉 We are proud to have you in the workforce. - Congratulations!!''', - style={"fontSize": "25px", "color": "#1876D2"}), - html.H3("🔥🔥"), - html.H3('Thanks for your time!')] + Congratulations!!""", + style={"fontSize": "25px", "color": "#1876D2"}, + ), + html.H3("🔥🔥"), + html.H3("Thanks for your time!"), + ] def web(): - webbrowser.open_new('http://127.0.0.1:8050/') + webbrowser.open_new("http://127.0.0.1:8050/") # The main function -if __name__ == '__main__': +if __name__ == "__main__": web() - app.title = 'yourPersonality' + app.title = "yourPersonality" app.run_server() diff --git a/ip_tracker/ipgeo.py b/ip_tracker/ipgeo.py index 1c88b5749..68f6c7bc8 100644 --- a/ip_tracker/ipgeo.py +++ b/ip_tracker/ipgeo.py @@ -1,24 +1,28 @@ -import requests import sys +import requests + def main(): url = "http://ip-api.com/json/" if len(sys.argv) > 1: # getting address from command line. - address = ''.join(sys.argv[1:]) + address = "".join(sys.argv[1:]) url += address response = requests.request("GET", url) response = response.json() - if response['status'] == 'fail': - sys.exit(f''' + if response["status"] == "fail": + sys.exit( + f""" status : {response['status']} message : {response['message']} - ''') + """ + ) - print(f''' + print( + f""" Country : {response['country']} Country Code : {response['countryCode']} Region : {response['region']} @@ -30,7 +34,8 @@ def main(): Timezone : {response['timezone']} ISP : {response['isp']} Organization : {response['org']} - ''') + """ + ) if __name__ == "__main__": diff --git a/iplscore_notifier/score.py b/iplscore_notifier/score.py index 2be76bcff..6470922c9 100644 --- a/iplscore_notifier/score.py +++ b/iplscore_notifier/score.py @@ -13,16 +13,23 @@ def match_info(mid): c = Cricbuzz() minfo = c.matchinfo(mid) - print('------------------------------------------') + print("------------------------------------------") print(" Match No : " + minfo["mnum"]) - print(" Match Between : " + minfo["team1"]["name"] + " v/s " + minfo["team2"]["name"]) + print( + " Match Between : " + minfo["team1"]["name"] + " v/s " + minfo["team2"]["name"] + ) - if (minfo["toss"] == ""): + if minfo["toss"] == "": print(" Toss is yet to happen") else: print(" Toss : " + minfo["toss"]) - print(" Match Location : " + minfo["venue_name"] + " located at " + minfo["venue_location"]) + print( + " Match Location : " + + minfo["venue_name"] + + " located at " + + minfo["venue_location"] + ) print(" Match Status : " + minfo["status"]) @@ -36,18 +43,33 @@ def live_score(mid): else: print("-------------------------------------------") print("Innings No : " + lscore["batting"]["score"][0]["inning_num"]) - print(lscore["batting"]["team"] + " : " + lscore["batting"]["score"][0]["runs"] + "/" - + lscore["batting"]["score"][0]["wickets"] + " in " + lscore["batting"]["score"][0]["overs"] + " overs") - - message = (lscore["batting"]["team"] + " : " + lscore["batting"]["score"][0]["runs"] + "/" - + lscore["batting"]["score"][0]["wickets"] + " in " + lscore["batting"]["score"][0]["overs"] - + " overs") + print( + lscore["batting"]["team"] + + " : " + + lscore["batting"]["score"][0]["runs"] + + "/" + + lscore["batting"]["score"][0]["wickets"] + + " in " + + lscore["batting"]["score"][0]["overs"] + + " overs" + ) + + message = ( + lscore["batting"]["team"] + + " : " + + lscore["batting"]["score"][0]["runs"] + + "/" + + lscore["batting"]["score"][0]["wickets"] + + " in " + + lscore["batting"]["score"][0]["overs"] + + " overs" + ) n.show_toast("LIVE MATCH SCORE", message, duration=10) for i in matches: - if (i["srs"] == srs_to_watch): + if i["srs"] == srs_to_watch: match_id.append(i["id"]) print("Match Details Available : ") @@ -63,7 +85,7 @@ def live_score(mid): message = input("Do you want to refresh the score ? [Y/N]") if message == "Y": - print('------------------------------------------') + print("------------------------------------------") elif message == "N": break else: diff --git a/jarvis_assistant/script.py b/jarvis_assistant/script.py index abc214655..a6b25352b 100644 --- a/jarvis_assistant/script.py +++ b/jarvis_assistant/script.py @@ -1,14 +1,15 @@ -import pyttsx3 # pip install pyttsx3 -import speech_recognition as sr # pip install speechRecognition import datetime -import wikipedia # pip install wikipedia -import webbrowser import os import smtplib +import webbrowser + +import pyttsx3 # pip install pyttsx3 +import speech_recognition as sr # pip install speechRecognition +import wikipedia # pip install wikipedia -engine = pyttsx3.init('sapi5') -voices = engine.getProperty('voices') -engine.setProperty('voice', voices[0].id) +engine = pyttsx3.init("sapi5") +voices = engine.getProperty("voices") +engine.setProperty("voice", voices[0].id) def speak(audio): @@ -37,7 +38,7 @@ def takeCommand(): try: print("Recognizing...") - query = r.recognize_google(audio, language='en-in') + query = r.recognize_google(audio, language="en-in") print(f"User said: {query}\n") except Exception: print("Say that again please...") @@ -46,11 +47,11 @@ def takeCommand(): def sendEmail(to, content): - server = smtplib.SMTP('smtp.gmail.com', 587) + server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() - server.login('youremail@gmail.com', 'your-password') - server.sendmail('youremail@gmail.com', to, content) + server.login("youremail@gmail.com", "your-password") + server.sendmail("youremail@gmail.com", to, content) server.close() @@ -58,38 +59,38 @@ def sendEmail(to, content): wishMe() while True: query = takeCommand().lower() - if 'wikipedia' in query: - speak('Searching Wikipedia...') + if "wikipedia" in query: + speak("Searching Wikipedia...") query = query.replace("wikipedia", "") results = wikipedia.summary(query, sentences=2) speak("According to Wikipedia") print(results) speak(results) - elif 'open youtube' in query: + elif "open youtube" in query: webbrowser.open("youtube.com") - elif 'open google' in query: + elif "open google" in query: webbrowser.open("google.com") - elif 'open stackoverflow' in query: + elif "open stackoverflow" in query: webbrowser.open("stackoverflow.com") - elif 'play music' in query: - music_dir = 'D:\\Non Critical\\songs\\Favorite Songs2' + elif "play music" in query: + music_dir = "D:\\Non Critical\\songs\\Favorite Songs2" songs = os.listdir(music_dir) os.startfile(os.path.join(music_dir, songs[0])) - elif 'the time' in query: + elif "the time" in query: strTime = datetime.datetime.now().strftime("%H:%M:%S") speak(f"Sir, the time is {strTime}") - elif 'open code' in query: + elif "open code" in query: # change this path according to you codePath = "/path/to/vscode/executable" os.startfile(codePath) - elif 'email to anshul' in query: + elif "email to anshul" in query: try: speak("What should I say?") content = takeCommand() diff --git a/jpg_to_png/jpg_to_png.py b/jpg_to_png/jpg_to_png.py index 0af568023..1e47fb18b 100644 --- a/jpg_to_png/jpg_to_png.py +++ b/jpg_to_png/jpg_to_png.py @@ -10,65 +10,65 @@ import tkinter as tk from tkinter import filedialog as fd -from PIL import Image from tkinter import messagebox +from PIL import Image + root = tk.Tk() # title for the output window -root.title('JPG to PNG and ViceVersa') +root.title("JPG to PNG and ViceVersa") # function to convert file from jpg to png + def jpg_to_png(): global im1 import_filename = fd.askopenfilename() - if import_filename.endswith('.jpg'): + if import_filename.endswith(".jpg"): im1 = Image.open(import_filename) - export_filename = fd.asksaveasfilename(defaultextension='.png') + export_filename = fd.asksaveasfilename(defaultextension=".png") im1.save(export_filename) - messagebox.showinfo('Congratulations ', - 'Your image is converted to Png ') + messagebox.showinfo("Congratulations ", "Your image is converted to Png ") else: - Label_2 = tk.Label(root, text='Error!', width=20, fg='red', - font=('bold', 15)) + Label_2 = tk.Label(root, text="Error!", width=20, fg="red", font=("bold", 15)) Label_2.place(x=80, y=280) - messagebox.showerror('Fail!!', 'Something Went Wrong.') + messagebox.showerror("Fail!!", "Something Went Wrong.") # function to convert png file to jpg + def png_to_jpg(): global im1 import_filename = fd.askopenfilename() - if import_filename.endswith('.png'): + if import_filename.endswith(".png"): im1 = Image.open(import_filename) - export_filename = fd.asksaveasfilename(defaultextension='.jpg') + export_filename = fd.asksaveasfilename(defaultextension=".jpg") im1.save(export_filename) - messagebox.showinfo('Congratulations ', - 'Your Image is converted to jpg ') + messagebox.showinfo("Congratulations ", "Your Image is converted to jpg ") else: - Label_2 = tk.Label(root, text='Error!', width=20, fg='red', - font=('bold', 15)) + Label_2 = tk.Label(root, text="Error!", width=20, fg="red", font=("bold", 15)) Label_2.place(x=80, y=280) - messagebox.showerror('Fail!!', 'Something Went Wrong.') + messagebox.showerror("Fail!!", "Something Went Wrong.") # first button for output window btn1 = tk.Button( root, - text='Click for JPG to PNG Conversion', + text="Click for JPG to PNG Conversion", width=30, height=2, - bg='#22577A', - fg='white', - font=('arial', 12, 'bold'), - command=jpg_to_png) + bg="#22577A", + fg="white", + font=("arial", 12, "bold"), + command=jpg_to_png, +) # coordinates of first button on output window @@ -78,13 +78,14 @@ def png_to_jpg(): btn2 = tk.Button( root, - text='Click for PNG to JPG Coversion', + text="Click for PNG to JPG Coversion", width=30, height=2, - bg='#38A3A5', - fg='white', - font=('arial', 12, 'bold'), - command=png_to_jpg) + bg="#38A3A5", + fg="white", + font=("arial", 12, "bold"), + command=png_to_jpg, +) # coordinates of second button on the output window @@ -92,5 +93,5 @@ def png_to_jpg(): # size in pixels of output window which is 500x500 -root.geometry('500x500+400+200') +root.geometry("500x500+400+200") root.mainloop() diff --git a/json_to_md/script.py b/json_to_md/script.py index 10bdab520..4efe3a433 100644 --- a/json_to_md/script.py +++ b/json_to_md/script.py @@ -1,14 +1,14 @@ -import sys -import json import argparse +import json +import sys markdown = "" tab = " " -list_tag = '* ' -inline_code = '`' -code_block = '```' -subtitle = '## ' -htag = '#' +list_tag = "* " +inline_code = "`" +code_block = "```" +subtitle = "## " +htag = "#" if sys.version_info < (3, 0): @@ -17,7 +17,7 @@ def load_json(file): try: - with open(file, 'r') as f: + with open(file, "r") as f: data = f.read() return json.loads(data) except: # noqa @@ -33,10 +33,10 @@ def parse_json(json_block, depth, options): def parse_dict(d, depth, options): for k in d: - if k in options['ignore']: + if k in options["ignore"]: continue - if options['keep'] != '': - if k not in options['keep']: + if options["keep"] != "": + if k not in options["keep"]: continue if isinstance(d[k], (dict, list)): add_header(k, depth) @@ -55,21 +55,33 @@ def parse_list(l, depth, options): # noqa def build_header_chain(depth): - chain = list_tag * (bool(depth)) + htag * (depth + 1) + \ - ' value ' + (htag * (depth + 1) + '\n') + chain = ( + list_tag * (bool(depth)) + + htag * (depth + 1) + + " value " + + (htag * (depth + 1) + "\n") + ) return chain def build_value_chain(key, value, depth): - chain = tab * (bool(depth - 1)) + list_tag + \ - str(key) + ": " + inline_code + str(value) + inline_code + "\n" + chain = ( + tab * (bool(depth - 1)) + + list_tag + + str(key) + + ": " + + inline_code + + str(value) + + inline_code + + "\n" + ) return chain def add_header(value, depth): chain = build_header_chain(depth) global markdown - markdown += chain.replace('value', value.title()) + markdown += chain.replace("value", value.title()) def add_value(key, value, depth): @@ -79,7 +91,7 @@ def add_value(key, value, depth): def write_out(markdown, output_file): - with open(output_file, 'w+') as f: + with open(output_file, "w+") as f: f.write(markdown) @@ -88,48 +100,56 @@ def convert(input_file, output_file, options): depth = 0 parse_json(json_data, depth, options) global markdown - markdown = markdown.replace('#######', '######') + markdown = markdown.replace("#######", "######") write_out(markdown, output_file) def main(): - parser = argparse.ArgumentParser(description="Json to Markdown converter", - usage='%(prog)s -i $INPUTFILENAME [options]', # noqa - epilog="Ca va bien aller!") # noqa - parser.add_argument('-i', '--input', help='Input filename', required=True) - parser.add_argument('-o', '--output', help='Output filename') - parser.add_argument('-x', '--ignore', help='A list of keys to ignore in a json file') - parser.add_argument('-k', '--keep', help='A list of keys to convert exclusively in a json file') - parser.add_argument('-r', '--replace', help='A list of dict to replace keys values. Not implemented') + parser = argparse.ArgumentParser( + description="Json to Markdown converter", + usage="%(prog)s -i $INPUTFILENAME [options]", # noqa + epilog="Ca va bien aller!", + ) # noqa + parser.add_argument("-i", "--input", help="Input filename", required=True) + parser.add_argument("-o", "--output", help="Output filename") + parser.add_argument( + "-x", "--ignore", help="A list of keys to ignore in a json file" + ) + parser.add_argument( + "-k", "--keep", help="A list of keys to convert exclusively in a json file" + ) + parser.add_argument( + "-r", "--replace", help="A list of dict to replace keys values. Not implemented" + ) args = parser.parse_args() if args.input is None: - print('[Error] User must specify input') + print("[Error] User must specify input") exit else: input_file = args.input if args.output is None: - output_file = f'{args.input[:-4]}md' + output_file = f"{args.input[:-4]}md" else: output_file = args.output - print(f'[INFO] output: {output_file}') + print(f"[INFO] output: {output_file}") if args.ignore is not None: keys_to_ignore = load_json(args.ignore) print(keys_to_ignore) else: - keys_to_ignore = '' + keys_to_ignore = "" if args.keep is not None: keys_to_keep = load_json(args.keep) print(keys_to_keep) else: - keys_to_keep = '' + keys_to_keep = "" options = dict() - options['ignore'] = keys_to_ignore - options['keep'] = keys_to_keep + options["ignore"] = keys_to_ignore + options["keep"] = keys_to_keep print(options) convert(input_file, output_file, options) diff --git a/json_to_yaml/json2yaml.py b/json_to_yaml/json2yaml.py index 9323e69b1..d966311a2 100644 --- a/json_to_yaml/json2yaml.py +++ b/json_to_yaml/json2yaml.py @@ -1,6 +1,7 @@ import json import os import sys + import yaml # Checking there is a file name passed diff --git a/key_logger/keylogger.py b/key_logger/keylogger.py index 311a86536..27ddf0f1d 100644 --- a/key_logger/keylogger.py +++ b/key_logger/keylogger.py @@ -1,12 +1,15 @@ import logging + from pynput.keyboard import Listener def keylogger_py(): log_destination = "" - logging.basicConfig(filename=(log_destination + "logs.txt"), - level=logging.DEBUG, - format='%(asctime)s : %(message)s') + logging.basicConfig( + filename=(log_destination + "logs.txt"), + level=logging.DEBUG, + format="%(asctime)s : %(message)s", + ) def keypress(key): logging.info(str(key)) diff --git a/language_translator/AlTranslator.py b/language_translator/AlTranslator.py index 092a0b3ae..4cb9bea87 100644 --- a/language_translator/AlTranslator.py +++ b/language_translator/AlTranslator.py @@ -1,21 +1,20 @@ -from tkinter import Tk, Frame, SUNKEN, Label -from tkinter import ttk, Button, X, Text, WORD -from tkinter import font, END -from googletrans import Translator, LANGUAGES -from PIL import ImageTk, Image import os +from tkinter import (END, SUNKEN, WORD, Button, Frame, Label, Text, Tk, X, + font, ttk) -cwd = os.path.dirname(os.path.realpath(__file__)) +from googletrans import LANGUAGES, Translator +from PIL import Image, ImageTk +cwd = os.path.dirname(os.path.realpath(__file__)) -class AlTranslator(): +class AlTranslator: def __init__(self): root = Tk(className=" ALTRANSLATOR ") root.geometry("1080x400+820+615") root.resizable(0, 0) - root.iconbitmap(os.path.join(cwd + '\\UI\\icons', 'altranslator.ico')) - root.config(bg='#ffffff') + root.iconbitmap(os.path.join(cwd + "\\UI\\icons", "altranslator.ico")) + root.config(bg="#ffffff") root.overrideredirect(1) def callback(event): @@ -32,28 +31,45 @@ def hideScreen(): root.overrideredirect(0) root.iconify() - appHighlightFont = font.Font(family='OnePlus Sans Display', size=12, - weight='bold') + appHighlightFont = font.Font( + family="OnePlus Sans Display", size=12, weight="bold" + ) - titleBar = Frame(root, bg='#141414', relief=SUNKEN, bd=0) - icon = Image.open(os.path.join(cwd + '\\UI\\icons', - 'altranslator.ico')) + titleBar = Frame(root, bg="#141414", relief=SUNKEN, bd=0) + icon = Image.open(os.path.join(cwd + "\\UI\\icons", "altranslator.ico")) icon = icon.resize((30, 30), Image.ANTIALIAS) icon = ImageTk.PhotoImage(icon) iconLabel = Label(titleBar, image=icon) iconLabel.photo = icon - iconLabel.config(bg='#141414') + iconLabel.config(bg="#141414") iconLabel.grid(row=0, column=0, sticky="nsew") - titleLabel = Label(titleBar, text='ALTRANSLATOR', fg='#909090', - bg='#141414', font=appHighlightFont) + titleLabel = Label( + titleBar, + text="ALTRANSLATOR", + fg="#909090", + bg="#141414", + font=appHighlightFont, + ) titleLabel.grid(row=0, column=1, sticky="nsew") - closeButton = Button(titleBar, text="x", bg='#141414', fg="#909090", - borderwidth=0, command=root.destroy, - font=appHighlightFont) + closeButton = Button( + titleBar, + text="x", + bg="#141414", + fg="#909090", + borderwidth=0, + command=root.destroy, + font=appHighlightFont, + ) closeButton.grid(row=0, column=3, sticky="nsew") - minimizeButton = Button(titleBar, text="-", bg='#141414', fg="#909090", - borderwidth=0, command=hideScreen, - font=appHighlightFont) + minimizeButton = Button( + titleBar, + text="-", + bg="#141414", + fg="#909090", + borderwidth=0, + command=hideScreen, + font=appHighlightFont, + ) minimizeButton.grid(row=0, column=2, sticky="nsew") titleBar.grid_columnconfigure(0, weight=1) titleBar.grid_columnconfigure(1, weight=20) @@ -61,34 +77,59 @@ def hideScreen(): titleBar.grid_columnconfigure(3, weight=1) titleBar.pack(fill=X) - inputText = Text(root, font=appHighlightFont, height=11, - wrap=WORD, padx=5, pady=5, width=40, fg='#4877bc') + inputText = Text( + root, + font=appHighlightFont, + height=11, + wrap=WORD, + padx=5, + pady=5, + width=40, + fg="#4877bc", + ) inputText.place(x=20, y=100) - outputText = Text(root, font=appHighlightFont, height=11, wrap=WORD, - padx=5, pady=5, width=40, bg='#f8f9fb', fg='#4877bc') + outputText = Text( + root, + font=appHighlightFont, + height=11, + wrap=WORD, + padx=5, + pady=5, + width=40, + bg="#f8f9fb", + fg="#4877bc", + ) outputText.place(x=610, y=100) language = list(LANGUAGES.values()) - srcLang = ttk.Combobox(root, values=language, width=22, - font=appHighlightFont) + srcLang = ttk.Combobox(root, values=language, width=22, font=appHighlightFont) srcLang.place(x=20, y=60) - srcLang.set('Source language') - destLang = ttk.Combobox(root, values=language, width=22, - font=appHighlightFont) + srcLang.set("Source language") + destLang = ttk.Combobox(root, values=language, width=22, font=appHighlightFont) destLang.place(x=800, y=60) - destLang.set('Destination language') + destLang.set("Destination language") def gTranslate(): translator = Translator() - translated = translator.translate(text=inputText.get(1.0, END), - src=srcLang.get().capitalize(), - dest=destLang.get().capitalize()) + translated = translator.translate( + text=inputText.get(1.0, END), + src=srcLang.get().capitalize(), + dest=destLang.get().capitalize(), + ) outputText.delete(1.0, END) outputText.insert(END, translated.text) - trans_btn = Button(root, text='Translate', font=appHighlightFont, - pady=5, command=gTranslate, fg='#8e8d91', width=9, - bg='#ffffff', bd=0) + trans_btn = Button( + root, + text="Translate", + font=appHighlightFont, + pady=5, + command=gTranslate, + fg="#8e8d91", + width=9, + bg="#ffffff", + bd=0, + ) trans_btn.place(x=500, y=180) titleBar.bind("", callback) diff --git a/letter_image_generator/letter_image_generator.py b/letter_image_generator/letter_image_generator.py index f3963d6a2..ec324457b 100644 --- a/letter_image_generator/letter_image_generator.py +++ b/letter_image_generator/letter_image_generator.py @@ -1,24 +1,34 @@ -from PIL import Image, ImageDraw, ImageFont -from typing import Tuple import os import random +from typing import Tuple + +from PIL import Image, ImageDraw, ImageFont -def letter_image_generator(letter: str, width: int = 480, - height: int = 480) -> Image: +def letter_image_generator(letter: str, width: int = 480, height: int = 480) -> Image: def random_color_generator() -> Tuple: - return (random.randint(0, 255), - random.randint(0, 255), - random.randint(0, 255), ) + return ( + random.randint(0, 255), + random.randint(0, 255), + random.randint(0, 255), + ) - img = Image.new(mode="RGB", size=(width, height), - color=random_color_generator()) + img = Image.new(mode="RGB", size=(width, height), color=random_color_generator()) draw = ImageDraw.Draw(img) - font = ImageFont.truetype(os.path.join("fonts", "OpenSans-Bold.ttf"), - size=height // 2) + font = ImageFont.truetype( + os.path.join("fonts", "OpenSans-Bold.ttf"), size=height // 2 + ) w, h = draw.textsize(letter, font=font) - draw.text(((width - w) / 2, (height - h) / 4), letter, - (255, 255, 255,), font=font) + draw.text( + ((width - w) / 2, (height - h) / 4), + letter, + ( + 255, + 255, + 255, + ), + font=font, + ) return img diff --git a/markdown_editor/markdown_editor.py b/markdown_editor/markdown_editor.py index 0ef49792c..cd03a046f 100644 --- a/markdown_editor/markdown_editor.py +++ b/markdown_editor/markdown_editor.py @@ -1,8 +1,8 @@ #!/usr/bin/python # -*- coding: utf-8 -*- import tkinter as tk -from tkinter import Tk -from tkinter import font, filedialog, messagebox as mbox +from tkinter import Tk, filedialog, font +from tkinter import messagebox as mbox from click import FileError from markdown2 import Markdown @@ -19,8 +19,7 @@ def __init__(self, master=None): def onChange(self, event): self.inputeditor.edit_modified(0) md2html = Markdown() - self.outputbox.set_html(md2html.convert( - self.inputeditor.get("1.0", tk.END))) + self.outputbox.set_html(md2html.convert(self.inputeditor.get("1.0", tk.END))) def openfile(self): filename = filedialog.askopenfilename( @@ -36,7 +35,8 @@ def openfile(self): self.inputeditor.insert(tk.END, open(filename, "r").read()) except FileError: mbox.showerror( - "Error opening file", "{} \ + "Error opening file", + "{} \ cannot be opened !".format( filename ), @@ -73,8 +73,7 @@ def init_window(self): self.inputeditor.bind("<>", self.onChange) self.outputbox = HTMLLabel( - self, width="1", background="white", - html="

Markdown Editor

" + self, width="1", background="white", html="

Markdown Editor

" ) self.outputbox.pack(fill=tk.BOTH, expand=1, side=tk.RIGHT) diff --git a/markdown_to_pdf/markdown_to_pdf.py b/markdown_to_pdf/markdown_to_pdf.py index f36c86ad0..a870f098d 100644 --- a/markdown_to_pdf/markdown_to_pdf.py +++ b/markdown_to_pdf/markdown_to_pdf.py @@ -1,6 +1,7 @@ +import sys + import markdown import pdfkit -import sys args = sys.argv[1:] # get command line *args assert args, "No file/dir was provided" # raise error is no arg is passed @@ -16,9 +17,10 @@ # configuring pdfkit to point to our installation of wkhtmltopdf config = pdfkit.configuration( - wkhtmltopdf=r"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe") + wkhtmltopdf=r"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe" +) for html_text in enumerate(html_texts): print(html_text[0]) - filename = args[html_text[0]].split('.')[0] - pdfkit.from_string(html_text[1], f'{filename}.pdf', configuration=config) + filename = args[html_text[0]].split(".")[0] + pdfkit.from_string(html_text[1], f"{filename}.pdf", configuration=config) diff --git a/markdown_viewer/markdown_viewer.py b/markdown_viewer/markdown_viewer.py index 205bea073..7a4293afd 100644 --- a/markdown_viewer/markdown_viewer.py +++ b/markdown_viewer/markdown_viewer.py @@ -1,51 +1,51 @@ import tkinter as tk -from tkinter import Tk -from tkinter import font, filedialog, messagebox as mbox +from tkinter import Tk, filedialog, font +from tkinter import messagebox as mbox + from markdown2 import Markdown from tkhtmlview import HTMLLabel class Window(tk.Frame): - def __init__(self, master=None): tk.Frame.__init__(self, master) self.master = master - self.font = font.Font(family='Helvetica', size=14) + self.font = font.Font(family="Helvetica", size=14) self.init_window() def openfile(self): - filename = \ - filedialog.askopenfilename(filetypes=(('Markdown File', - '*.md , *.mdown'), - ('Text file', '*.txt'))) + filename = filedialog.askopenfilename( + filetypes=(("Markdown File", "*.md , *.mdown"), ("Text file", "*.txt")) + ) if filename: try: md2html = Markdown() - self.outputbox.set_html(md2html.convert(open(filename, - 'r').read())) + self.outputbox.set_html(md2html.convert(open(filename, "r").read())) except Exception: - mbox.showerror('Error opening file', - 'The selected file cannot be opened !') + mbox.showerror( + "Error opening file", "The selected file cannot be opened !" + ) def init_window(self): - self.master.title('Mardown Viewer') + self.master.title("Mardown Viewer") self.pack(fill=tk.BOTH, expand=1) self.mainmenu = tk.Menu(self) self.filemenu = tk.Menu(self.mainmenu) - self.filemenu.add_command(label='Open', command=self.openfile) + self.filemenu.add_command(label="Open", command=self.openfile) self.filemenu.add_separator() - self.filemenu.add_command(label='Exit', command=self.quit) - self.mainmenu.add_cascade(label='File', menu=self.filemenu) + self.filemenu.add_command(label="Exit", command=self.quit) + self.mainmenu.add_cascade(label="File", menu=self.filemenu) self.master.config(menu=self.mainmenu) - self.outputbox = HTMLLabel(self, width='1', background='white', - html='

Welcome

') + self.outputbox = HTMLLabel( + self, width="1", background="white", html="

Welcome

" + ) self.outputbox.pack(fill=tk.BOTH, expand=1, side=tk.RIGHT) self.outputbox.fit_height() root = Tk() -root.geometry('750x600') +root.geometry("750x600") app = Window(master=root) app.mainloop() diff --git a/medium_to_pdf/main.py b/medium_to_pdf/main.py index a1e8f2cc8..d86b112b8 100644 --- a/medium_to_pdf/main.py +++ b/medium_to_pdf/main.py @@ -1,12 +1,14 @@ #!/usr/bin/env python -import pdfkit import sys +import pdfkit + -class MediumToPdf(): +class MediumToPdf: """ This class contains method to convert a medium article into pdf file. """ + def __init__(self, url, output_file): """ url: The url of medium article. @@ -20,18 +22,18 @@ def convert_to_pdf(self, url, output_file): output_file: The name of the output file. """ options = { - 'page-size': 'A4', - 'margin-top': '0.75in', - 'margin-right': '0.75in', - 'margin-bottom': '0.75in', - 'margin-left': '0.75in', + "page-size": "A4", + "margin-top": "0.75in", + "margin-right": "0.75in", + "margin-bottom": "0.75in", + "margin-left": "0.75in", } pdfkit.from_url(url, output_file, options=options) if __name__ == "__main__": - url = sys.argv[sys.argv.index('--url') + 1] - output_file = sys.argv[sys.argv.index('--output') + 1] + url = sys.argv[sys.argv.index("--url") + 1] + output_file = sys.argv[sys.argv.index("--output") + 1] try: medium_to_pdf = MediumToPdf(url, output_file) except Exception as e: diff --git a/ml_solver/ML_solver_run.py b/ml_solver/ML_solver_run.py index 43f0842bb..5c81108b3 100644 --- a/ml_solver/ML_solver_run.py +++ b/ml_solver/ML_solver_run.py @@ -7,13 +7,14 @@ import subprocess import sys from pathlib import Path -import pandas as pd -from solver import solver, metrics_dict, models_dict +import pandas as pd from constants import Constants +from solver import metrics_dict, models_dict, solver logger = logging.getLogger(__name__) + class CLI: # Note these are the arguments list with there description that is used to interact with automation script @@ -217,9 +218,7 @@ def init(self, *args, **kwargs): ) d["model_type"] = model_type model_name = ( - input( - f"enter algorithm you want to use: [NeuralNetwork] " - ) + input(f"enter algorithm you want to use: [NeuralNetwork] ") or "NeuralNetwork" ) d["model_name"] = model_name @@ -253,9 +252,7 @@ def _accept_user_input( self.dict_args["data_path"] = data_path if yaml_needed: yaml_path = ( - input( - f"enter path to your yaml file: [{default_yaml_path}] " - ) + input(f"enter path to your yaml file: [{default_yaml_path}] ") or default_yaml_path ) self.dict_args["yaml_path"] = yaml_path @@ -378,9 +375,7 @@ def metrics(self): """ print(f"\nML_solver's supported metrics overview: \n") reg_metrics = [func.__name__ for func in metrics_dict.get("regression")] - clf_metrics = [ - func.__name__ for func in metrics_dict.get("classification") - ] + clf_metrics = [func.__name__ for func in metrics_dict.get("classification")] df_metrics = ( pd.DataFrame.from_dict( @@ -417,27 +412,19 @@ def experiment(self): f"Therefore, you will need to provide few information before proceeding.\n" ) train_data_path = ( - input( - f"enter path to your data: [{default_train_data_path}] " - ) + input(f"enter path to your data: [{default_train_data_path}] ") or default_train_data_path ) eval_data_path = ( - input( - f"enter path to your data: [{default_eval_data_path}] " - ) + input(f"enter path to your data: [{default_eval_data_path}] ") or default_eval_data_path ) test_data_path = ( - input( - f"enter path to your data: [{default_test_data_path}] " - ) + input(f"enter path to your data: [{default_test_data_path}] ") or default_test_data_path ) yaml_path = ( - input( - f"enter path to your yaml file: [{default_yaml_path}] " - ) + input(f"enter path to your yaml file: [{default_yaml_path}] ") or default_yaml_path ) @@ -471,8 +458,6 @@ def experiment(self): solver(**eval_args) solver(**pred_args) - - def _tableize(self, df): """ pretty-print a dataframe as table @@ -482,9 +467,7 @@ def _tableize(self, df): df_columns = df.columns.tolist() max_len_in_lst = lambda lst: len(sorted(lst, reverse=True, key=len)[0]) align_center = ( - lambda st, sz: "{0}{1}{0}".format( - " " * (1 + (sz - len(st)) // 2), st - )[:sz] + lambda st, sz: "{0}{1}{0}".format(" " * (1 + (sz - len(st)) // 2), st)[:sz] if len(st) < sz else st ) @@ -502,14 +485,11 @@ def _tableize(self, df): col: 2 + max(max_val_len_for_col.get(col, 0), max_col_len) for col in df_columns } - build_hline = lambda row: "+".join( - ["-" * col_sizes[col] for col in row] - ).join(["+", "+"]) + build_hline = lambda row: "+".join(["-" * col_sizes[col] for col in row]).join( + ["+", "+"] + ) build_data = lambda row, align: "|".join( - [ - align(str(val), col_sizes[df_columns[idx]]) - for idx, val in enumerate(row) - ] + [align(str(val), col_sizes[df_columns[idx]]) for idx, val in enumerate(row)] ).join(["|", "|"]) hline = build_hline(df_columns) out = [hline, build_data(df_columns, align_center), hline] @@ -518,7 +498,6 @@ def _tableize(self, df): out.append(hline) return "\n".join(out) - def info(self): print( f""" @@ -536,5 +515,6 @@ def info(self): def main(): CLI() + if __name__ == "__main__": main() diff --git a/ml_solver/__init__.py b/ml_solver/__init__.py index d8498f803..84cc8c373 100644 --- a/ml_solver/__init__.py +++ b/ml_solver/__init__.py @@ -4,7 +4,7 @@ except ImportError: # pragma: no cover from importlib_metadata import PackageNotFoundError, version -from .solver import solver, metrics_dict, models_dict +from .solver import metrics_dict, models_dict, solver try: __version__ = version(__name__) diff --git a/ml_solver/configs.py b/ml_solver/configs.py index 933612677..6f6765ee3 100644 --- a/ml_solver/configs.py +++ b/ml_solver/configs.py @@ -1,6 +1,7 @@ # flake8: noqa import os from pathlib import Path + from constants import Constants res_path = Path(os.getcwd()) / Constants.stats_dir diff --git a/ml_solver/data.py b/ml_solver/data.py index 0e0ed90d8..16927224a 100644 --- a/ml_solver/data.py +++ b/ml_solver/data.py @@ -1,488 +1,388 @@ # flake8: noqa -from sklearn.linear_model import (LinearRegression, - LogisticRegression, - Ridge, - RANSACRegressor, - RidgeClassifier, - RidgeClassifierCV, - RidgeCV, - BayesianRidge, - SGDRegressor, - GammaRegressor, - LogisticRegressionCV, - TheilSenRegressor, - PoissonRegressor, - TweedieRegressor, - ARDRegression, - SGDClassifier, - HuberRegressor, - Lasso, - LassoCV, - LassoLars, - LassoLarsCV, - PassiveAggressiveClassifier, - ElasticNet, - ElasticNetCV, - Perceptron) +import logging -from sklearn.ensemble import (RandomForestClassifier, - RandomForestRegressor, - ExtraTreesRegressor, - ExtraTreesClassifier, - AdaBoostClassifier, - AdaBoostRegressor, - BaggingClassifier, - BaggingRegressor, +from sklearn.calibration import CalibratedClassifierCV +from sklearn.cluster import (DBSCAN, OPTICS, AffinityPropagation, + AgglomerativeClustering, Birch, + FeatureAgglomeration, KMeans, MeanShift, + MiniBatchKMeans, SpectralBiclustering, + SpectralClustering, SpectralCoclustering) +from sklearn.ensemble import (AdaBoostClassifier, AdaBoostRegressor, + BaggingClassifier, BaggingRegressor, + ExtraTreesClassifier, ExtraTreesRegressor, GradientBoostingClassifier, GradientBoostingRegressor, - StackingClassifier, - StackingRegressor, - VotingClassifier, - VotingRegressor) - -from sklearn.naive_bayes import (BernoulliNB, - CategoricalNB, - ComplementNB, - GaussianNB, - MultinomialNB) - -from sklearn.cluster import (KMeans, - AffinityPropagation, - AgglomerativeClustering, - Birch, - DBSCAN, - FeatureAgglomeration, - MiniBatchKMeans, - MeanShift, - OPTICS, - SpectralBiclustering, - SpectralClustering, - SpectralCoclustering) - -from sklearn.calibration import CalibratedClassifierCV -from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor, ExtraTreeClassifier, ExtraTreeRegressor -from sklearn.svm import SVC, SVR, LinearSVC, LinearSVR, NuSVC, NuSVR -from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor -from sklearn.neural_network import MLPRegressor, MLPClassifier, BernoulliRBM -from sklearn.metrics import (mean_squared_error, - mean_absolute_error, - mean_squared_log_error, - median_absolute_error, - accuracy_score, - f1_score, - r2_score, - precision_score, + RandomForestClassifier, RandomForestRegressor, + StackingClassifier, StackingRegressor, + VotingClassifier, VotingRegressor) +from sklearn.linear_model import (ARDRegression, BayesianRidge, ElasticNet, + ElasticNetCV, GammaRegressor, HuberRegressor, + Lasso, LassoCV, LassoLars, LassoLarsCV, + LinearRegression, LogisticRegression, + LogisticRegressionCV, + PassiveAggressiveClassifier, Perceptron, + PoissonRegressor, RANSACRegressor, Ridge, + RidgeClassifier, RidgeClassifierCV, RidgeCV, + SGDClassifier, SGDRegressor, + TheilSenRegressor, TweedieRegressor) +from sklearn.metrics import (accuracy_score, f1_score, mean_absolute_error, + mean_squared_error, mean_squared_log_error, + median_absolute_error, precision_score, r2_score, recall_score) +from sklearn.naive_bayes import (BernoulliNB, CategoricalNB, ComplementNB, + GaussianNB, MultinomialNB) +from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor +from sklearn.neural_network import BernoulliRBM, MLPClassifier, MLPRegressor +from sklearn.svm import SVC, SVR, LinearSVC, LinearSVR, NuSVC, NuSVR +from sklearn.tree import (DecisionTreeClassifier, DecisionTreeRegressor, + ExtraTreeClassifier, ExtraTreeRegressor) from sklearn.utils.multiclass import type_of_target -import logging -logging.basicConfig(format='%(levelname)s - %(message)s', level=logging.INFO) +logging.basicConfig(format="%(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogger(__name__) models_dict = { - "regression": { - "LinearRegression": { "class": LinearRegression, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html", - }, - "SGDRegressor": { "class": SGDRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDRegressor.html?" - "highlight=sgd#sklearn.linear_model.SGDRegressor", - + "highlight=sgd#sklearn.linear_model.SGDRegressor", }, - "Lasso": { "class": Lasso, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Lasso.html?" - "highlight=lasso#sklearn.linear_model.Lasso", - "cv_class": LassoCV + "highlight=lasso#sklearn.linear_model.Lasso", + "cv_class": LassoCV, }, - "LassoLars": { "class": LassoLars, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LassoLars.html?" - "highlight=lasso#sklearn.linear_model.LassoLars", - "cv_class": LassoLarsCV + "highlight=lasso#sklearn.linear_model.LassoLars", + "cv_class": LassoLarsCV, }, - "BayesianRegression": { "class": BayesianRidge, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.BayesianRidge.html?" - "highlight=ridge#sklearn.linear_model.BayesianRidge" + "highlight=ridge#sklearn.linear_model.BayesianRidge", }, - "HuberRegression": { "class": HuberRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.HuberRegressor.html?" - "highlight=huber#sklearn.linear_model.HuberRegressor" + "highlight=huber#sklearn.linear_model.HuberRegressor", }, - "Ridge": { "class": Ridge, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Ridge.html" - "#sklearn.linear_model.Ridge", - "cv_class": RidgeCV + "#sklearn.linear_model.Ridge", + "cv_class": RidgeCV, }, - "PoissonRegression": { "class": PoissonRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.PoissonRegressor.html?" - "highlight=poisson#sklearn.linear_model.PoissonRegressor" + "highlight=poisson#sklearn.linear_model.PoissonRegressor", }, - "ARDRegression": { "class": ARDRegression, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ARDRegression.html?" - "highlight=ard#sklearn.linear_model.ARDRegression" + "highlight=ard#sklearn.linear_model.ARDRegression", }, - "TweedieRegression": { "class": TweedieRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TweedieRegressor.html?" - "highlight=tweedie#sklearn.linear_model.TweedieRegressor" + "highlight=tweedie#sklearn.linear_model.TweedieRegressor", }, - "TheilSenRegression": { "class": TheilSenRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.TheilSenRegressor.html?" - "highlight=theilsenregressor#sklearn.linear_model.TheilSenRegressor" + "highlight=theilsenregressor#sklearn.linear_model.TheilSenRegressor", }, - "GammaRegression": { "class": GammaRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.GammaRegressor.html?" - "highlight=gamma%20regressor#sklearn.linear_model.GammaRegressor" + "highlight=gamma%20regressor#sklearn.linear_model.GammaRegressor", }, - "RANSACRegression": { "class": RANSACRegressor, - "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RANSACRegressor.html" + "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RANSACRegressor.html", }, - "DecisionTree": { "class": DecisionTreeRegressor, "link": "https://scikit-learn.org/stable/modules/generatedsklearn.tree.DecisionTreeRegressor.html?" - "highlight=decision%20tree%20regressor#sklearn.tree.DecisionTreeRegressor" + "highlight=decision%20tree%20regressor#sklearn.tree.DecisionTreeRegressor", }, - "ExtraTree": { "class": ExtraTreeRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.tree.ExtraTreeRegressor.html" - "#sklearn.tree.ExtraTreeRegressor" + "#sklearn.tree.ExtraTreeRegressor", }, - "RandomForest": { "class": RandomForestRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestRegressor.html?" - "highlight=random%20forest#sklearn.ensemble.RandomForestRegressor"}, - + "highlight=random%20forest#sklearn.ensemble.RandomForestRegressor", + }, "ExtraTrees": { "class": ExtraTreesRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesRegressor.html?" - "highlight=extra%20trees#sklearn.ensemble.ExtraTreesRegressor"}, - + "highlight=extra%20trees#sklearn.ensemble.ExtraTreesRegressor", + }, "SVM": { "class": SVR, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVR.html?" - "highlight=svr#sklearn.svm.SVR"}, - + "highlight=svr#sklearn.svm.SVR", + }, "LinearSVM": { "class": LinearSVR, - "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVR.html#sklearn.svm.LinearSVR" + "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVR.html#sklearn.svm.LinearSVR", }, - "NuSVM": { "class": NuSVR, - "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.NuSVR.html#sklearn.svm.NuSVR" + "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.NuSVR.html#sklearn.svm.NuSVR", }, - "NearestNeighbor": { "class": KNeighborsRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsRegressor.html?" - "highlight=neighbor#sklearn.neighbors.KNeighborsRegressor"}, - + "highlight=neighbor#sklearn.neighbors.KNeighborsRegressor", + }, "NeuralNetwork": { "class": MLPRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPRegressor.html?" - "highlight=mlp#sklearn.neural_network.MLPRegressor" + "highlight=mlp#sklearn.neural_network.MLPRegressor", }, - "ElasticNet": { "class": ElasticNet, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.ElasticNet.html?" - "highlight=elasticnet#sklearn.linear_model.ElasticNet", - "cv_class": ElasticNetCV + "highlight=elasticnet#sklearn.linear_model.ElasticNet", + "cv_class": ElasticNetCV, }, - "BernoulliRBM": { "class": BernoulliRBM, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.BernoulliRBM.html#" - "sklearn.neural_network.BernoulliRBM" + "sklearn.neural_network.BernoulliRBM", }, - "BoltzmannMachine": { "class": BernoulliRBM, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.BernoulliRBM.html#" - "sklearn.neural_network.BernoulliRBM" + "sklearn.neural_network.BernoulliRBM", }, - "Adaboost": { "class": AdaBoostRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostRegressor.html#" - "sklearn.ensemble.AdaBoostRegressor" + "sklearn.ensemble.AdaBoostRegressor", }, - "Bagging": { "class": BaggingRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingRegressor.html" - "#sklearn.ensemble.BaggingRegressor" + "#sklearn.ensemble.BaggingRegressor", }, - "GradientBoosting": { "class": GradientBoostingRegressor, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingRegressor.html" - "#sklearn.ensemble.GradientBoostingRegressor" - } + "#sklearn.ensemble.GradientBoostingRegressor", + }, }, - "classification": { - "LogisticRegression": { - "class": LogisticRegression, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegression.html?" - "highlight=regression#sklearn.linear_model.LogisticRegression", - "cv_class": LogisticRegressionCV + "highlight=regression#sklearn.linear_model.LogisticRegression", + "cv_class": LogisticRegressionCV, }, - "SGDClassifier": { - "class": SGDClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html?" - "highlight=sgd#sklearn.linear_model.SGDClassifier", + "highlight=sgd#sklearn.linear_model.SGDClassifier", }, - "Ridge": { "class": RidgeClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.RidgeClassifier.html?" - "highlight=ridgeclassifier#sklearn.linear_model.RidgeClassifier", - "cv_class": RidgeClassifierCV + "highlight=ridgeclassifier#sklearn.linear_model.RidgeClassifier", + "cv_class": RidgeClassifierCV, }, - "DecisionTree": { "class": DecisionTreeClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html?" - "highlight=decision%20tree#sklearn.tree.DecisionTreeClassifier"}, - + "highlight=decision%20tree#sklearn.tree.DecisionTreeClassifier", + }, "ExtraTree": { "class": ExtraTreeClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.tree.ExtraTreeClassifier.html" - "#sklearn.tree.ExtraTreeClassifier" + "#sklearn.tree.ExtraTreeClassifier", }, - "RandomForest": { "class": RandomForestClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html?" - "highlight=random%20forest#sklearn.ensemble.RandomForestClassifier"}, - + "highlight=random%20forest#sklearn.ensemble.RandomForestClassifier", + }, "ExtraTrees": { "class": ExtraTreesClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.ExtraTreesClassifier.html?" - "highlight=extra%20trees#sklearn.ensemble.ExtraTreesClassifier"}, - + "highlight=extra%20trees#sklearn.ensemble.ExtraTreesClassifier", + }, "SVM": { "class": SVC, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.SVC.html?" - "highlight=svc#sklearn.svm.SVC"}, - + "highlight=svc#sklearn.svm.SVC", + }, "LinearSVM": { "class": LinearSVC, - "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC" + "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.LinearSVC.html#sklearn.svm.LinearSVC", }, - "NuSVM": { "class": NuSVC, - "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.NuSVC.html#sklearn.svm.NuSVC" + "link": "https://scikit-learn.org/stable/modules/generated/sklearn.svm.NuSVC.html#sklearn.svm.NuSVC", }, - - "NearestNeighbor": { "class": KNeighborsClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html?" - "highlight=neighbor#sklearn.neighbors.KNeighborsClassifier"}, - + "highlight=neighbor#sklearn.neighbors.KNeighborsClassifier", + }, "NeuralNetwork": { "class": MLPClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.MLPClassifier.html?" - "highlight=mlp#sklearn.neural_network.MLPClassifier" + "highlight=mlp#sklearn.neural_network.MLPClassifier", }, - "PassiveAgressiveClassifier": { "class": PassiveAggressiveClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.PassiveAggressiveClassifier.html?" - "highlight=passiveaggressiveclassifier#sklearn.linear_model.PassiveAggressiveClassifier" + "highlight=passiveaggressiveclassifier#sklearn.linear_model.PassiveAggressiveClassifier", }, - "Perceptron": { "class": Perceptron, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.Perceptron.html#" - "sklearn.linear_model.Perceptron" + "sklearn.linear_model.Perceptron", }, - "BernoulliRBM": { - "class": BernoulliRBM, - "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.BernoulliRBM.html#" - "sklearn.neural_network.BernoulliRBM" - }, - + "class": BernoulliRBM, + "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.BernoulliRBM.html#" + "sklearn.neural_network.BernoulliRBM", + }, "BoltzmannMachine": { "class": BernoulliRBM, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.neural_network.BernoulliRBM.html#" - "sklearn.neural_network.BernoulliRBM" + "sklearn.neural_network.BernoulliRBM", }, - "CalibratedClassifier": { "class": CalibratedClassifierCV, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.calibration.CalibratedClassifierCV.html#" - "sklearn.calibration.CalibratedClassifierCV" + "sklearn.calibration.CalibratedClassifierCV", }, - "Adaboost": { "class": AdaBoostClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.AdaBoostClassifier.html#" - "sklearn.ensemble.AdaBoostClassifier" + "sklearn.ensemble.AdaBoostClassifier", }, - "Bagging": { "class": BaggingClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.BaggingClassifier.html" - "#sklearn.ensemble.BaggingClassifier" + "#sklearn.ensemble.BaggingClassifier", }, - "GradientBoosting": { "class": GradientBoostingClassifier, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.GradientBoostingClassifier.html" - "#sklearn.ensemble.GradientBoostingClassifier" + "#sklearn.ensemble.GradientBoostingClassifier", }, - "BernoulliNaiveBayes": { "class": BernoulliNB, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.BernoulliNB.html" - "#sklearn.naive_bayes.BernoulliNB" + "#sklearn.naive_bayes.BernoulliNB", }, - "CategoricalNaiveBayes": { "class": CategoricalNB, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.CategoricalNB.html" - "#sklearn.naive_bayes.CategoricalNB" + "#sklearn.naive_bayes.CategoricalNB", }, - "ComplementNaiveBayes": { "class": ComplementNB, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.ComplementNB.html" - "#sklearn.naive_bayes.ComplementNB" + "#sklearn.naive_bayes.ComplementNB", }, - "GaussianNaiveBayes": { "class": GaussianNB, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.GaussianNB.html" - "#sklearn.naive_bayes.GaussianNB" + "#sklearn.naive_bayes.GaussianNB", }, - "MultinomialNaiveBayes": { "class": MultinomialNB, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.naive_bayes.MultinomialNB.html" - "#sklearn.naive_bayes.MultinomialNB" - } - - + "#sklearn.naive_bayes.MultinomialNB", + }, }, - "clustering": { "KMeans": { "class": KMeans, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html" - "#sklearn.cluster.KMeans" + "#sklearn.cluster.KMeans", }, - "AffinityPropagation": { "class": AffinityPropagation, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AffinityPropagation.html" - "#sklearn.cluster.AffinityPropagation" + "#sklearn.cluster.AffinityPropagation", }, - "Birch": { "class": Birch, - "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.Birch.html#sklearn.cluster.Birch" + "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.Birch.html#sklearn.cluster.Birch", }, - "AgglomerativeClustering": { "class": AgglomerativeClustering, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html#" - "sklearn.cluster.AgglomerativeClustering" + "sklearn.cluster.AgglomerativeClustering", }, - "FeatureAgglomeration": { "class": FeatureAgglomeration, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.FeatureAgglomeration.html#" - "sklearn.cluster.FeatureAgglomeration" + "sklearn.cluster.FeatureAgglomeration", }, "DBSCAN": { "class": DBSCAN, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.DBSCAN.html" - "#sklearn.cluster.DBSCAN" + "#sklearn.cluster.DBSCAN", }, "MiniBatchKMeans": { "class": MiniBatchKMeans, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.MiniBatchKMeans.html" - "#sklearn.cluster.MiniBatchKMeans" + "#sklearn.cluster.MiniBatchKMeans", }, - "SpectralBiclustering": { "class": SpectralBiclustering, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralBiclustering.html" - "#sklearn.cluster.SpectralBiclustering" + "#sklearn.cluster.SpectralBiclustering", }, - "SpectralCoclustering": { "class": SpectralCoclustering, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralCoclustering.html" - "#sklearn.cluster.SpectralCoclustering" + "#sklearn.cluster.SpectralCoclustering", }, - "SpectralClustering": { "class": SpectralClustering, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.SpectralClustering.html" - "#sklearn.cluster.SpectralClustering" + "#sklearn.cluster.SpectralClustering", }, - "MeanShift": { "class": MeanShift, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.MeanShift.html#" - "sklearn.cluster.MeanShift" + "sklearn.cluster.MeanShift", }, "OPTICS": { "class": OPTICS, "link": "https://scikit-learn.org/stable/modules/generated/sklearn.cluster.OPTICS.html" - "#sklearn.cluster.OPTICS" + "#sklearn.cluster.OPTICS", }, - - } - + }, } metrics_dict = { "regression": ( - mean_squared_error, mean_absolute_error, mean_squared_log_error, median_absolute_error, r2_score + mean_squared_error, + mean_absolute_error, + mean_squared_log_error, + median_absolute_error, + r2_score, ), - "classification": ( - accuracy_score, f1_score, precision_score, recall_score - ) + "classification": (accuracy_score, f1_score, precision_score, recall_score), } @@ -493,7 +393,9 @@ def evaluate_model(model, model_type, x_test, y_pred, y_true, get_score_only, ** if y_pred.ndim > 1: if y_true.shape[1] > 1 or y_pred.shape[1] > 1: - logger.info(f"Multitarget {model_type} Evaluation: calculating {model_type} score") + logger.info( + f"Multitarget {model_type} Evaluation: calculating {model_type} score" + ) return {f"{model_type} score": model.score(x_test, y_true)} if model_type not in metrics_dict.keys(): @@ -504,22 +406,26 @@ def evaluate_model(model, model_type, x_test, y_pred, y_true, get_score_only, ** for metric in metrics: logger.info(f"Calculating {metric.__name__} .....") logger.info(f"type of target: {type_of_target(y_true)}") - if type_of_target(y_true) in ('multiclass-multioutput', - 'multilabel-indicator', - 'multiclass') and metric.__name__ in ('precision_score', - 'accuracy_score', - 'recall_score', - 'f1_score'): - if metric.__name__ == 'accuracy_score': - eval_res[metric.__name__] = metric(y_pred=y_pred, - y_true=y_true) + if type_of_target(y_true) in ( + "multiclass-multioutput", + "multilabel-indicator", + "multiclass", + ) and metric.__name__ in ( + "precision_score", + "accuracy_score", + "recall_score", + "f1_score", + ): + if metric.__name__ == "accuracy_score": + eval_res[metric.__name__] = metric(y_pred=y_pred, y_true=y_true) else: - eval_res[metric.__name__] = metric(y_pred=y_pred, - y_true=y_true, - average='micro') + eval_res[metric.__name__] = metric( + y_pred=y_pred, y_true=y_true, average="micro" + ) else: - eval_res[metric.__name__] = metric(y_pred=y_pred, y_true=y_true, **kwargs) + eval_res[metric.__name__] = metric( + y_pred=y_pred, y_true=y_true, **kwargs + ) return eval_res - diff --git a/ml_solver/hyperparams.py b/ml_solver/hyperparams.py index 90023bed8..c620357dc 100644 --- a/ml_solver/hyperparams.py +++ b/ml_solver/hyperparams.py @@ -1,26 +1,17 @@ # flake8: noqa from sklearn.model_selection import GridSearchCV, RandomizedSearchCV -def hyperparameter_search(model, - method, - params, - x_train, - y_train, - **kwargs): + + +def hyperparameter_search(model, method, params, x_train, y_train, **kwargs): search = None - if method == 'grid_search': - search = GridSearchCV(model, - params, - **kwargs) + if method == "grid_search": + search = GridSearchCV(model, params, **kwargs) - elif method == 'random_search': - search = RandomizedSearchCV(model, - params, - **kwargs) + elif method == "random_search": + search = RandomizedSearchCV(model, params, **kwargs) else: raise Exception("hyperparameter method must be grid_search or random_search") search.fit(x_train, y_train) return search.best_estimator_, search.best_score_, search.best_params_ - - diff --git a/ml_solver/main.py b/ml_solver/main.py index 64c22a756..dd793e318 100644 --- a/ml_solver/main.py +++ b/ml_solver/main.py @@ -7,11 +7,11 @@ def print_hi(name): # Use a breakpoint in the code line below to debug your script. - print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint. + print(f"Hi, {name}") # Press Ctrl+F8 to toggle the breakpoint. # Press the green button in the gutter to run the script. -if __name__ == '__main__': - print_hi('PyCharm') +if __name__ == "__main__": + print_hi("PyCharm") # See PyCharm help at https://www.jetbrains.com/help/pycharm/ diff --git a/ml_solver/preprocessing.py b/ml_solver/preprocessing.py index 19f46f0c4..691034911 100644 --- a/ml_solver/preprocessing.py +++ b/ml_solver/preprocessing.py @@ -4,12 +4,8 @@ import numpy as np import pandas as pd from sklearn.impute import SimpleImputer -from sklearn.preprocessing import ( - LabelEncoder, - MinMaxScaler, - OneHotEncoder, - StandardScaler, -) +from sklearn.preprocessing import (LabelEncoder, MinMaxScaler, OneHotEncoder, + StandardScaler) logging.basicConfig(format="%(levelname)s - %(message)s", level=logging.INFO) logger = logging.getLogger(__name__) @@ -51,9 +47,7 @@ def update_dataset_props(dataset_props: dict, default_dataset_props: dict): if key1 in dataset_props.keys(): for key2 in default_dataset_props[key1].keys(): if key2 in dataset_props[key1].keys(): - default_dataset_props[key1][key2] = dataset_props[key1][ - key2 - ] + default_dataset_props[key1][key2] = dataset_props[key1][key2] return default_dataset_props @@ -76,9 +70,7 @@ def handle_missing_values(df, fill_value=np.nan, strategy="mean"): def encode(df, encoding_type="onehotencoding", column=None): if not encoding_type: - raise Exception( - f"encoding type should be -> oneHotEncoding or labelEncoding" - ) + raise Exception(f"encoding type should be -> oneHotEncoding or labelEncoding") if encoding_type == "onehotencoding": logger.info(f"performing a one hot encoding ...") @@ -95,9 +87,7 @@ def encode(df, encoding_type="onehotencoding", column=None): encoder.fit(df[column]) classes_map = { cls: int(lbl) - for (cls, lbl) in zip( - encoder.classes_, encoder.transform(encoder.classes_) - ) + for (cls, lbl) in zip(encoder.classes_, encoder.transform(encoder.classes_)) } logger.info(f"label encoding classes => {encoder.classes_}") logger.info(f"classes map => {classes_map}") @@ -105,9 +95,7 @@ def encode(df, encoding_type="onehotencoding", column=None): return df, classes_map else: - raise Exception( - f"encoding type should be -> oneHotEncoding or labelEncoding" - ) + raise Exception(f"encoding type should be -> oneHotEncoding or labelEncoding") def normalize(x, y=None, method="standard"): diff --git a/ml_solver/solver.py b/ml_solver/solver.py index 86acce6f2..494da734b 100644 --- a/ml_solver/solver.py +++ b/ml_solver/solver.py @@ -4,6 +4,7 @@ import logging import os import warnings + import joblib import numpy as np import pandas as pd @@ -12,20 +13,10 @@ from configs import configs from data import evaluate_model, metrics_dict, models_dict from hyperparams import hyperparameter_search - from preprocessing import ( - encode, - handle_missing_values, - normalize, - read_data_to_df, - update_dataset_props, - ) - from utils import ( - _reshape, - create_yaml, - extract_params, - read_json, - read_yaml, - ) + from preprocessing import (encode, handle_missing_values, normalize, + read_data_to_df, update_dataset_props) + from utils import (_reshape, create_yaml, extract_params, read_json, + read_yaml) except ImportError: from utils import ( read_yaml, @@ -68,12 +59,8 @@ class solver: description_file = configs.get( "description_file" ) # path to the description.json file - evaluation_file = configs.get( - "evaluation_file" - ) # path to the evaluation.json file - prediction_file = configs.get( - "prediction_file" - ) # path to the predictions.csv + evaluation_file = configs.get("evaluation_file") # path to the evaluation.json file + prediction_file = configs.get("prediction_file") # path to the predictions.csv default_dataset_props = configs.get( "dataset_props" ) # dataset props that can be changed from the yaml file @@ -86,9 +73,7 @@ class solver: def __init__(self, **cli_args): logger.info(f"Entered CLI args: {cli_args}") logger.info(f"Executing command: {cli_args.get('cmd')} ...") - self.data_path: str = str( - cli_args.get("data_path") - ) # path to the dataset + self.data_path: str = str(cli_args.get("data_path")) # path to the dataset logger.info(f"reading data from {self.data_path}") self.command = cli_args.get("cmd", None) @@ -146,14 +131,10 @@ def __init__(self, **cli_args): # if entered command is evaluate or predict, then the pre-fitted model needs to be loaded and used else: - self.model_path = cli_args.get( - "model_path", self.default_model_path - ) + self.model_path = cli_args.get("model_path", self.default_model_path) logger.info(f"path of the pre-fitted model => {self.model_path}") - self.prediction_file = cli_args.get( - "prediction_file", self.prediction_file - ) + self.prediction_file = cli_args.get("prediction_file", self.prediction_file) # set description.json if provided: self.description_file = cli_args.get( @@ -163,9 +144,7 @@ def __init__(self, **cli_args): # load description file to read stored training parameters with open(self.description_file) as f: dic = json.load(f) - self.target: list = dic.get( - "target" - ) # target to predict as a list + self.target: list = dic.get("target") # target to predict as a list self.model_type: str = dic.get( "type" ) # type of the model -> regression, classification or clustering @@ -192,9 +171,7 @@ def _create_model(self, **kwargs): model = algorithms.get( model_algorithm ) # extract model class depending on the algorithm - logger.info( - f"Solving a {model_type} problem using ===> {model_algorithm}" - ) + logger.info(f"Solving a {model_type} problem using ===> {model_algorithm}") if not model: raise Exception("Model not found in the algorithms list") else: @@ -217,13 +194,9 @@ def _create_model(self, **kwargs): ) else: model_class = model.get("class") - logger.info( - f"model arguments: \n" f"{self.model_props.get('arguments')}" - ) + logger.info(f"model arguments: \n" f"{self.model_props.get('arguments')}") model = ( - model_class(**kwargs) - if not model_args - else model_class(**model_args) + model_class(**kwargs) if not model_args else model_class(**model_args) ) return model, model_args @@ -248,13 +221,9 @@ def _save_model(self, model): ) except OSError: - logger.exception( - f"Creating the directory {self.results_path} failed " - ) + logger.exception(f"Creating the directory {self.results_path} failed ") else: - logger.info( - f"Successfully created the directory in {self.results_path} " - ) + logger.info(f"Successfully created the directory in {self.results_path} ") joblib.dump(model, open(self.default_model_path, "wb")) return True @@ -292,15 +261,11 @@ def _process_data(self, target="fit"): assert isinstance( self.target, list ), "provide target(s) as a list in the yaml file" - assert ( - len(self.target) > 0 - ), "please provide at least a target to predict" + assert len(self.target) > 0, "please provide at least a target to predict" try: read_data_options = self.dataset_props.get("read_data_options", {}) - dataset = read_data_to_df( - data_path=self.data_path, **read_data_options - ) + dataset = read_data_to_df(data_path=self.data_path, **read_data_options) logger.info(f"dataset shape: {dataset.shape}") attributes = list(dataset.columns) logger.info(f"dataset attributes: {attributes}") @@ -320,9 +285,7 @@ def _process_data(self, target="fit"): column=column, ) if classes_map: - self.dataset_props[ - "label_encoding_classes" - ] = classes_map + self.dataset_props["label_encoding_classes"] = classes_map logger.info( f"adding classes_map to dataset props: \n{classes_map}" ) @@ -350,9 +313,7 @@ def _process_data(self, target="fit"): return normalize(x, method=scaling_method) if any(col not in attributes for col in self.target): - raise Exception( - "chosen target(s) to predict must exist in the dataset" - ) + raise Exception("chosen target(s) to predict must exist in the dataset") y = pd.concat([dataset.pop(x) for x in self.target], axis=1) x = _reshape(dataset.to_numpy()) @@ -476,21 +437,15 @@ def fit(self, **kwargs): cv_results = cross_validate( estimator=self.model, X=x_train, y=y_train, **cv_params ) - hyperparams_props = self.model_props.get( - "hyperparameter_search", None - ) + hyperparams_props = self.model_props.get("hyperparameter_search", None) if hyperparams_props: # perform hyperparameter search method = hyperparams_props.get("method", None) grid_params = hyperparams_props.get("parameter_grid", None) hp_args = hyperparams_props.get("arguments", None) - logger.info( - f"Performing hyperparameter search using -> {method}" - ) - logger.info( - f"Grid parameters entered by the user: {grid_params}" - ) + logger.info(f"Performing hyperparameter search using -> {method}") + logger.info(f"Grid parameters entered by the user: {grid_params}") logger.info(f"Additional hyperparameter arguments: {hp_args}") best_estimator, best_params, best_score = hyperparameter_search( model=self.model, @@ -577,9 +532,7 @@ def fit(self, **kwargs): with open(self.description_file, "w", encoding="utf-8") as f: json.dump(fit_description, f, ensure_ascii=False, indent=4) except Exception as e: - logger.exception( - f"Error while storing the fit description file: {e}" - ) + logger.exception(f"Error while storing the fit description file: {e}") def evaluate(self, **kwargs): """ @@ -621,9 +574,7 @@ def _get_predictions(self, **kwargs): """ try: model = self._load_model(f=self.model_path) - x_val = ( - self._prepare_predict_data() - ) # the same is used for clustering + x_val = self._prepare_predict_data() # the same is used for clustering y_pred = model.predict(x_val) y_pred = _reshape(y_pred) logger.info( @@ -634,9 +585,7 @@ def _get_predictions(self, **kwargs): self.target = ["result"] df_pred = pd.DataFrame.from_dict( { - self.target[i]: y_pred[:, i] - if len(y_pred.shape) > 1 - else y_pred + self.target[i]: y_pred[:, i] if len(y_pred.shape) > 1 else y_pred for i in range(len(self.target)) } ) @@ -687,6 +636,4 @@ def create_init_mock_file( f"you just need to overwrite the values to meet your expectations" ) else: - logger.warning( - f"something went wrong while initializing a default file" - ) + logger.warning(f"something went wrong while initializing a default file") diff --git a/ml_solver/utils.py b/ml_solver/utils.py index a0a78c75a..f6ba5039b 100644 --- a/ml_solver/utils.py +++ b/ml_solver/utils.py @@ -73,9 +73,7 @@ def load_trained_model(f: str = ""): try: if not f: logger.info(f"result path: {configs.get('results_path')} ") - logger.info( - f"loading model form {configs.get('default_model_path')} " - ) + logger.info(f"loading model form {configs.get('default_model_path')} ") with open(configs.get("default_model_path"), "rb") as _model: model = joblib.load(_model) else: diff --git a/morse_code_translator/morse-code-translator.py b/morse_code_translator/morse-code-translator.py index a4d534e6f..34d2b44f8 100644 --- a/morse_code_translator/morse-code-translator.py +++ b/morse_code_translator/morse-code-translator.py @@ -1,42 +1,72 @@ import os # Plain text to morse code dictionary. -MORSE_CODE_DICT = {'A': '.-', 'B': '-...', - 'C': '-.-.', 'D': '-..', 'E': '.', - 'F': '..-.', 'G': '--.', 'H': '....', - 'I': '..', 'J': '.---', 'K': '-.-', - 'L': '.-..', 'M': '--', 'N': '-.', - 'O': '---', 'P': '.--.', 'Q': '--.-', - 'R': '.-.', 'S': '...', 'T': '-', - 'U': '..-', 'V': '...-', 'W': '.--', - 'X': '-..-', 'Y': '-.--', 'Z': '--..', - '1': '.----', '2': '..---', '3': '...--', - '4': '....-', '5': '.....', '6': '-....', - '7': '--...', '8': '---..', '9': '----.', - '0': '-----', ',': '--..--', '.': '.-.-.-', - '?': '..--..', '/': '-..-.', '-': '-....-', - '(': '-.--.', ')': '-.--.-', ' ': '/'} +MORSE_CODE_DICT = { + "A": ".-", + "B": "-...", + "C": "-.-.", + "D": "-..", + "E": ".", + "F": "..-.", + "G": "--.", + "H": "....", + "I": "..", + "J": ".---", + "K": "-.-", + "L": ".-..", + "M": "--", + "N": "-.", + "O": "---", + "P": ".--.", + "Q": "--.-", + "R": ".-.", + "S": "...", + "T": "-", + "U": "..-", + "V": "...-", + "W": ".--", + "X": "-..-", + "Y": "-.--", + "Z": "--..", + "1": ".----", + "2": "..---", + "3": "...--", + "4": "....-", + "5": ".....", + "6": "-....", + "7": "--...", + "8": "---..", + "9": "----.", + "0": "-----", + ",": "--..--", + ".": ".-.-.-", + "?": "..--..", + "/": "-..-.", + "-": "-....-", + "(": "-.--.", + ")": "-.--.-", + " ": "/", +} # Morse code to plain text dictionary. REV_MORSE_CODE_DICT = {v: k for k, v in MORSE_CODE_DICT.items()} def translate(text): - if not all(t == '.' or t == '-' or t == '/' or t.isspace() for t in text): + if not all(t == "." or t == "-" or t == "/" or t.isspace() for t in text): print() print("The morse code encryption of the text is :-") print() - return ' '.join([MORSE_CODE_DICT.get(t, '?') for t in text]) + return " ".join([MORSE_CODE_DICT.get(t, "?") for t in text]) else: print() print("The translated text is :-") print() - return ''.join([REV_MORSE_CODE_DICT.get(t, '?') - for t in text.split()]) + return "".join([REV_MORSE_CODE_DICT.get(t, "?") for t in text.split()]) if __name__ == "__main__": - os.system('cls') + os.system("cls") print("-" * 50) print("ENTER MORSE CODE SENTENCE TO DECODE AND NORMAL SENTENCE TO ENCODE") print("-" * 50) @@ -47,10 +77,8 @@ def translate(text): user_input = input("Enter a sentence: ") print(translate(user_input.upper())) print() - q = input( - "Do you want another translation ? (Y/Yes) or (N/No): " - ).lower() - if q == 'n' or q == 'no': + q = input("Do you want another translation ? (Y/Yes) or (N/No): ").lower() + if q == "n" or q == "no": quit = True # Script by Swaraj Baral (github.com/SwarajBaral) diff --git a/motivational_quoter/motivate.py b/motivational_quoter/motivate.py index 864567c51..5da3f07fe 100644 --- a/motivational_quoter/motivate.py +++ b/motivational_quoter/motivate.py @@ -1,27 +1,28 @@ +import json import os import sys -import json import time + import requests from win10toast import ToastNotifier def check_availability(): # check if the running device is windows - if os.name == 'nt': + if os.name == "nt": pass else: - print('This script only runs on windows.') + print("This script only runs on windows.") sys.exit(0) def get_quote(): # access api to get a quote - url = 'https://zenquotes.io/api/random' - req = requests.request('GET', url) + url = "https://zenquotes.io/api/random" + req = requests.request("GET", url) if req.status_code != 200: - print('Connot reach api.') + print("Connot reach api.") sys.exit(0) else: pass @@ -32,21 +33,21 @@ def get_quote(): def create_notifier(data): - quote = data[0]['q'] - author = data[0]['a'] + quote = data[0]["q"] + author = data[0]["a"] toast = ToastNotifier() toast.show_toast(f"By {author}", quote) def main_app(): - time_ = int(input('Repeat notification after (hours): ')) + time_ = int(input("Repeat notification after (hours): ")) while True: check_availability() data = get_quote() create_notifier(data) - print('Sent notification.') + print("Sent notification.") time.sleep(time_ * 3600) -if __name__ == '__main__': +if __name__ == "__main__": main_app() diff --git a/movie_tv_ratings/movie_tv_ratings.py b/movie_tv_ratings/movie_tv_ratings.py index 6f25b01e4..a56e3f8b2 100644 --- a/movie_tv_ratings/movie_tv_ratings.py +++ b/movie_tv_ratings/movie_tv_ratings.py @@ -1,31 +1,47 @@ -import requests import re + +import requests from bs4 import BeautifulSoup # Gets top 250 movies from IMDB def scrape_movies(): - response = requests.get('http://www.imdb.com/chart/top') - soup = BeautifulSoup(response.text, 'lxml') + response = requests.get("http://www.imdb.com/chart/top") + soup = BeautifulSoup(response.text, "lxml") - movies = soup.select('td.titleColumn') - ratings = [b.attrs.get('data-value') for b in soup.select('td.posterColumn span[name=ir]')] + movies = soup.select("td.titleColumn") + ratings = [ + b.attrs.get("data-value") for b in soup.select("td.posterColumn span[name=ir]") + ] for i in range(len(movies)): movie_string = movies[i].get_text() - movie = (' '.join(movie_string.split()).replace('.', '')) - movie_title = movie[len(str(i)) + 1:-7] - print(("| " + str(i + 1)) + (" | " + movie_title) + (" | Rating : " + "{:.1f}".format(float(ratings[i])))) + movie = " ".join(movie_string.split()).replace(".", "") + movie_title = movie[len(str(i)) + 1 : -7] + print( + ("| " + str(i + 1)) + + (" | " + movie_title) + + (" | Rating : " + "{:.1f}".format(float(ratings[i]))) + ) return # Gets top 250 TV shows from IMDB def scrape_tvshows(): page = requests.get("https://www.imdb.com/chart/toptv") - Results = re.findall(r'" alt="(.+?)".*?title="(.*?)".*?strong.*?"(.*?)"', page.text, re.DOTALL) + Results = re.findall( + r'" alt="(.+?)".*?title="(.*?)".*?strong.*?"(.*?)"', page.text, re.DOTALL + ) for i in range(len(Results)): - print("| " + str(i + 1) + " | " + Results[i][0] + " | Rating : " + Results[i][-1][:3]) + print( + "| " + + str(i + 1) + + " | " + + Results[i][0] + + " | Rating : " + + Results[i][-1][:3] + ) return @@ -37,16 +53,16 @@ def scrape_tvshows(): print("Type 'exit' to exit\n") val = input("Type here: ") -while (val): - if val == 'Movies': - globals()['scrape_movies']() +while val: + if val == "Movies": + globals()["scrape_movies"]() print("\n") val = input("Type 'Movies' or 'TV' or 'exit': ") - elif val == 'TV': - globals()['scrape_tvshows']() + elif val == "TV": + globals()["scrape_tvshows"]() print("\n") val = input("Type 'Movies' or 'TV' or 'exit': ") - elif val == 'exit': - val = '' + elif val == "exit": + val = "" else: val = input("Wrong Input. Try Again: ") diff --git a/mp4_to_mp3_convertor/main.py b/mp4_to_mp3_convertor/main.py index 114abf28b..935769049 100644 --- a/mp4_to_mp3_convertor/main.py +++ b/mp4_to_mp3_convertor/main.py @@ -1,24 +1,22 @@ # MP4 to MP3 Converter # imported necessary library -from tkinter import Tk, Button, Text, END +import os import tkinter as tk -from tkinter import filedialog import tkinter.messagebox as mbox -from PIL import Image, ImageTk +from tkinter import END, Button, Text, Tk, filedialog + import moviepy import moviepy.editor -import os +from PIL import Image, ImageTk # created a main window window = Tk() -window.title('MP4 to MP3 Converter') +window.title("MP4 to MP3 Converter") window.geometry("1000x700") # top label -start1 = tk.Label(text="MP4 to MP3 Converter", - font=("Arial", 50), - fg="magenta") +start1 = tk.Label(text="MP4 to MP3 Converter", font=("Arial", 50), fg="magenta") start1.place(x=130, y=10) # image on the main window @@ -34,14 +32,15 @@ def mp4_choose(): global filename, onlyfilename - filename = filedialog.askopenfilename(initialdir="/", - title="Choose MP4", - filetypes=(("Text files", "*.Mp4*"), - ("all files", "*.*"))) + filename = filedialog.askopenfilename( + initialdir="/", + title="Choose MP4", + filetypes=(("Text files", "*.Mp4*"), ("all files", "*.*")), + ) # Change label contents # label_file_explorer.configure(text="File : " + filename) onlyfilename = os.path.basename(filename) - fname.delete('1.0', END) + fname.delete("1.0", END) fname.insert(END, onlyfilename) @@ -50,25 +49,29 @@ def mp4_choose(): select1.place(x=50, y=500) # textarea for file name only -fname = Text(window, - height=1, - width=23, - font=("Arial", 25), - bg="light yellow", - fg="brown", - borderwidth=2, - relief="solid") +fname = Text( + window, + height=1, + width=23, + font=("Arial", 25), + bg="light yellow", + fg="brown", + borderwidth=2, + relief="solid", +) fname.place(x=360, y=505) # created a choose button , to choose the image from the local system -chooseb = Button(window, - text='SELECT', - command=mp4_choose, - font=("Arial", 17), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") +chooseb = Button( + window, + text="SELECT", + command=mp4_choose, + font=("Arial", 17), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", +) chooseb.place(x=800, y=500) @@ -80,24 +83,26 @@ def convert(): aud_fname = "" for i in onlyfilename: - if i == '.': + if i == ".": break else: aud_fname = aud_fname + i print(aud_fname) - audio.write_audiofile(f'{aud_fname}.mp3') - mbox.showinfo("Success", - "Video converted to Audio.\n\nAudio Saved Successfully") + audio.write_audiofile(f"{aud_fname}.mp3") + mbox.showinfo("Success", "Video converted to Audio.\n\nAudio Saved Successfully") # created a choose button , to choose the image from the local system -convertb = Button(window, - text='CONVERT MP4 To MP3', - command=convert, font=("Arial", 20), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") +convertb = Button( + window, + text="CONVERT MP4 To MP3", + command=convert, + font=("Arial", 20), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", +) convertb.place(x=150, y=600) @@ -108,14 +113,16 @@ def exit_win(): # creating an exit button -exitB = Button(window, - text='EXIT', - command=exit_win, - font=("Arial", 20), - bg="red", - fg="blue", - borderwidth=3, - relief="raised") +exitB = Button( + window, + text="EXIT", + command=exit_win, + font=("Arial", 20), + bg="red", + fg="blue", + borderwidth=3, + relief="raised", +) exitB.place(x=750, y=600) # this is done to show the exit dialog box when tried to exit from diff --git a/multimode-calculator/calculator.py b/multimode-calculator/calculator.py index 1a4cf5768..29688e9c2 100644 --- a/multimode-calculator/calculator.py +++ b/multimode-calculator/calculator.py @@ -1,6 +1,6 @@ +import math import tkinter as tk from tkinter import messagebox -import math e = None e2 = None @@ -251,10 +251,7 @@ def equal(): result = float(f_num) ** int(second_num) e.insert(0, result) e2.delete(0, len(e2.get())) - e2.insert( - 0, - str(f_num) + " ^ " + str(second_num) + " = " + str(result) - ) + e2.insert(0, str(f_num) + " ^ " + str(second_num) + " = " + str(result)) if sign == "exp": result = math.exp(num) @@ -284,10 +281,7 @@ def equal(): result = f_num % int(second_num) e.insert(0, result) e2.delete(0, len(e2.get())) - e2.insert( - 0, - str(f_num) + " % " + str(second_num) + " = " + str(result) - ) + e2.insert(0, str(f_num) + " % " + str(second_num) + " = " + str(result)) if sign == "sin_inv": result = math.degrees(math.asin(num)) @@ -343,116 +337,187 @@ def create_frame(mode): global e global e2 - e2 = tk.Entry( - frame, font=("Helvetica", 9), width=40, borderwidth=2 - ) + e2 = tk.Entry(frame, font=("Helvetica", 9), width=40, borderwidth=2) e2.grid(row=0, column=0, columnspan=3, padx=10, pady=10, ipady=3) - e = tk.Entry( - frame, font=("Helvetica", 9, "bold"), width=40, borderwidth=5 - ) + e = tk.Entry(frame, font=("Helvetica", 9, "bold"), width=40, borderwidth=5) e.grid(row=1, column=0, columnspan=3, padx=10, pady=10, ipady=8) e.focus() - if mode == 'n': + if mode == "n": button_1 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="1", padx=35, pady=5, command=lambda: show(1) + text="1", + padx=35, + pady=5, + command=lambda: show(1), ) button_2 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="2", padx=35, pady=5, command=lambda: show(2) + text="2", + padx=35, + pady=5, + command=lambda: show(2), ) button_3 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="3", padx=35, pady=5, command=lambda: show(3) + text="3", + padx=35, + pady=5, + command=lambda: show(3), ) button_4 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="4", padx=35, pady=5, command=lambda: show(4) + text="4", + padx=35, + pady=5, + command=lambda: show(4), ) button_5 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="5", padx=35, pady=5, command=lambda: show(5) + text="5", + padx=35, + pady=5, + command=lambda: show(5), ) button_6 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="6", padx=35, pady=5, command=lambda: show(6) + text="6", + padx=35, + pady=5, + command=lambda: show(6), ) button_7 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="7", padx=35, pady=5, command=lambda: show(7) + text="7", + padx=35, + pady=5, + command=lambda: show(7), ) button_8 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="8", padx=35, pady=5, command=lambda: show(8) + text="8", + padx=35, + pady=5, + command=lambda: show(8), ) button_9 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="9", padx=35, pady=5, command=lambda: show(9) + text="9", + padx=35, + pady=5, + command=lambda: show(9), ) button_0 = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="0", padx=35, pady=5, command=lambda: show(0) + text="0", + padx=35, + pady=5, + command=lambda: show(0), ) button_del = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="<--", padx=31, pady=5, command=delete + text="<--", + padx=31, + pady=5, + command=delete, ) button_add = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="+", padx=35, pady=5, command=addition + text="+", + padx=35, + pady=5, + command=addition, ) button_clear = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="Clear", padx=77, pady=5, command=clear + text="Clear", + padx=77, + pady=5, + command=clear, ) button_equal = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="=", padx=89, pady=5, command=equal + text="=", + padx=89, + pady=5, + command=equal, ) button_dot = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text=".", padx=37, pady=5, command=lambda: show(".") + text=".", + padx=37, + pady=5, + command=lambda: show("."), ) button_sqrt = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="sqrt", padx=27, pady=5, command=sqrt + text="sqrt", + padx=27, + pady=5, + command=sqrt, ) button_sub = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="-", padx=37, pady=5, command=subtraction + text="-", + padx=37, + pady=5, + command=subtraction, ) button_mul = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="*", padx=37, pady=5, command=multiplication + text="*", + padx=37, + pady=5, + command=multiplication, ) button_div = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="/", padx=37, pady=5, command=division + text="/", + padx=37, + pady=5, + command=division, ) button_1.grid(row=2, column=0, pady=5) @@ -483,182 +548,283 @@ def create_frame(mode): frame, background="light gray", font=("Helvetica", 9, "bold"), - text="1", padx=35, pady=5, command=lambda: show(1) + text="1", + padx=35, + pady=5, + command=lambda: show(1), ) button_2 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="2", padx=36, pady=5, command=lambda: show(2) + text="2", + padx=36, + pady=5, + command=lambda: show(2), ) button_3 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="3", padx=35, pady=5, command=lambda: show(3) + text="3", + padx=35, + pady=5, + command=lambda: show(3), ) button_4 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="4", padx=35, pady=5, command=lambda: show(4) + text="4", + padx=35, + pady=5, + command=lambda: show(4), ) button_5 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="5", padx=36, pady=5, command=lambda: show(5) + text="5", + padx=36, + pady=5, + command=lambda: show(5), ) button_6 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="6", padx=35, pady=5, command=lambda: show(6) + text="6", + padx=35, + pady=5, + command=lambda: show(6), ) button_7 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="7", padx=35, pady=5, command=lambda: show(7) + text="7", + padx=35, + pady=5, + command=lambda: show(7), ) button_8 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="8", padx=36, pady=5, command=lambda: show(8) + text="8", + padx=36, + pady=5, + command=lambda: show(8), ) button_9 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="9", padx=35, pady=5, command=lambda: show(9) + text="9", + padx=35, + pady=5, + command=lambda: show(9), ) button_0 = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="0", padx=35, pady=5, command=lambda: show(0) + text="0", + padx=35, + pady=5, + command=lambda: show(0), ) button_add = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="+", padx=35, pady=5, command=addition) + text="+", + padx=35, + pady=5, + command=addition, + ) button_clear = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="<--", padx=31, pady=5, command=delete) + text="<--", + padx=31, + pady=5, + command=delete, + ) button_dot = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text=".", padx=37, pady=5, command=lambda: show(".")) + text=".", + padx=37, + pady=5, + command=lambda: show("."), + ) button_equal = tk.Button( - frame, background="light gray", + frame, + background="light gray", font=("Helvetica", 9, "bold"), - text="=", padx=89, pady=5, command=equal) + text="=", + padx=89, + pady=5, + command=equal, + ) button_sin = tk.Button( frame, background="light gray", - padx=29, pady=5, - font=("Helvetica", 9, "bold"), text="sin", command=sin + padx=29, + pady=5, + font=("Helvetica", 9, "bold"), + text="sin", + command=sin, ) button_cos = tk.Button( frame, background="light gray", - padx=30, pady=5, - font=("Helvetica", 9, "bold"), text="cos", command=cos + padx=30, + pady=5, + font=("Helvetica", 9, "bold"), + text="cos", + command=cos, ) button_tan = tk.Button( frame, background="light gray", - padx=31, pady=5, - font=("Helvetica", 9, "bold"), text="tan", command=tan + padx=31, + pady=5, + font=("Helvetica", 9, "bold"), + text="tan", + command=tan, ) button_cot = tk.Button( frame, background="light gray", - padx=20, pady=5, - font=("Helvetica", 9, "bold"), text="sin^-1", command=sin_inv + padx=20, + pady=5, + font=("Helvetica", 9, "bold"), + text="sin^-1", + command=sin_inv, ) button_cosec = tk.Button( frame, background="light gray", - padx=21, pady=5, - font=("Helvetica", 9, "bold"), text="cos^-1", command=cos_inv + padx=21, + pady=5, + font=("Helvetica", 9, "bold"), + text="cos^-1", + command=cos_inv, ) button_sec = tk.Button( frame, background="light gray", - padx=22, pady=5, - font=("Helvetica", 9, "bold"), text="tan^-1", command=tan_inv + padx=22, + pady=5, + font=("Helvetica", 9, "bold"), + text="tan^-1", + command=tan_inv, ) button_fact = tk.Button( frame, background="light gray", - padx=35, pady=5, - font=("Helvetica", 9, "bold"), text="X!", command=fact + padx=35, + pady=5, + font=("Helvetica", 9, "bold"), + text="X!", + command=fact, ) button_sqrt = tk.Button( frame, background="light gray", - padx=26, pady=5, - font=("Helvetica", 9, "bold"), text="sqrt", command=sqrt + padx=26, + pady=5, + font=("Helvetica", 9, "bold"), + text="sqrt", + command=sqrt, ) button_exp = tk.Button( frame, background="light gray", - padx=30, pady=5, - font=("Helvetica", 9, "bold"), text="exp", command=exp + padx=30, + pady=5, + font=("Helvetica", 9, "bold"), + text="exp", + command=exp, ) button_cube = tk.Button( frame, background="light gray", - padx=27, pady=5, - font=("Helvetica", 9, "bold"), text="X^3", command=cube + padx=27, + pady=5, + font=("Helvetica", 9, "bold"), + text="X^3", + command=cube, ) button_n_pow = tk.Button( frame, background="light gray", - padx=30, pady=5, - font=("Helvetica", 9, "bold"), text="X^n", command=n_pow + padx=30, + pady=5, + font=("Helvetica", 9, "bold"), + text="X^n", + command=n_pow, ) button_inv = tk.Button( frame, background="light gray", - padx=27, pady=5, - font=("Helvetica", 9, "bold"), text="X^-1", command=inv + padx=27, + pady=5, + font=("Helvetica", 9, "bold"), + text="X^-1", + command=inv, ) button_rem = tk.Button( frame, background="light gray", - padx=26, pady=5, - font=("Helvetica", 9, "bold"), text="X%n", command=rem + padx=26, + pady=5, + font=("Helvetica", 9, "bold"), + text="X%n", + command=rem, ) button_e = tk.Button( frame, background="light gray", - padx=78, pady=5, - font=("Helvetica", 9, "bold"), text="Clear", command=clear + padx=78, + pady=5, + font=("Helvetica", 9, "bold"), + text="Clear", + command=clear, ) button_sub = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="-", padx=37, pady=5, command=subtraction + text="-", + padx=37, + pady=5, + command=subtraction, ) button_mul = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="*", padx=37, pady=5, command=multiplication + text="*", + padx=37, + pady=5, + command=multiplication, ) button_div = tk.Button( frame, background="light gray", font=("Helvetica", 9, "bold"), - text="/", padx=37, pady=5, command=division + text="/", + padx=37, + pady=5, + command=division, ) button_1.grid(row=7, column=0, pady=5) @@ -715,24 +881,25 @@ def create_frame(mode): background="light gray", variable=mode, font=("Helvetica", 9, "bold"), - text="Scientific", value="s" - ).grid( - row=0, column=0, padx=5, pady=5, ipadx=10 - ) + text="Scientific", + value="s", + ).grid(row=0, column=0, padx=5, pady=5, ipadx=10) tk.Radiobutton( root, background="light gray", variable=mode, font=("Helvetica", 9, "bold"), - text="Simple", value="n" - ).grid( - row=0, column=1, padx=5, pady=5, ipadx=10 - ) + text="Simple", + value="n", + ).grid(row=0, column=1, padx=5, pady=5, ipadx=10) choose_btn = tk.Button( - root, background="light gray", - width=10, font=("Helvetica", 9, "bold"), - text="Select", command=lambda: create_frame(mode.get()) + root, + background="light gray", + width=10, + font=("Helvetica", 9, "bold"), + text="Select", + command=lambda: create_frame(mode.get()), ) choose_btn.grid(row=0, column=2, padx=5, pady=5) root.mainloop() diff --git a/music_downloader/music-downloader.py b/music_downloader/music-downloader.py index f0f8669f4..32be488dc 100644 --- a/music_downloader/music-downloader.py +++ b/music_downloader/music-downloader.py @@ -1,17 +1,17 @@ from youtube_dl import YoutubeDL -audio_downloader = YoutubeDL({'format': 'bestaudio'}) +audio_downloader = YoutubeDL({"format": "bestaudio"}) while True: try: - print('Youtube Downloader'.center(40, '_')) - URL = input('Enter youtube url : ') + print("Youtube Downloader".center(40, "_")) + URL = input("Enter youtube url : ") audio_downloader.extract_info(URL) except Exception: - print("Couldn\'t download the audio") + print("Couldn't download the audio") finally: - option = int(input('\n1.download again \n2.Exit\n\nOption here :')) + option = int(input("\n1.download again \n2.Exit\n\nOption here :")) if option != 1: break diff --git a/music_player/player.py b/music_player/player.py index 57fee19d8..17f8875d9 100644 --- a/music_player/player.py +++ b/music_player/player.py @@ -1,7 +1,7 @@ import tkinter as tk -from tkinter import RIGHT, TOP, CENTER, X +from tkinter import CENTER, RIGHT, TOP, X, filedialog from tkinter.filedialog import Button, Tk -from tkinter import filedialog + import vlc # Define root @@ -17,7 +17,8 @@ def pick_music(): global music_path, label_text # Get chosen files path music_path = filedialog.askopenfilename( - filetypes=(("mp3 files", "*.mp3"), ("waw files", "*.waw"))) + filetypes=(("mp3 files", "*.mp3"), ("waw files", "*.waw")) + ) # Set music name label text label_text.set(music_path.split("/")[-1]) # Set button states to normal @@ -51,45 +52,30 @@ def pause_music(): # Pick music button pck_btn = Button( - root, - text="Pick Music", - font="Rockwell", - relief="flat", - command=pick_music) + root, text="Pick Music", font="Rockwell", relief="flat", command=pick_music +) pck_btn.pack(side=TOP) # Music name label -msc_nme_lbl = tk.Label( - root, - justify=CENTER, - textvariable=label_text) +msc_nme_lbl = tk.Label(root, justify=CENTER, textvariable=label_text) msc_nme_lbl.pack(side=TOP, fill=X, padx=10) # Stop music button stop_music_button = Button( - root, - text="Stop", - font="Rockwell", - relief="flat", - command=stop_music) + root, text="Stop", font="Rockwell", relief="flat", command=stop_music +) stop_music_button.pack(side=RIGHT) # Pause music button pause_music_button = Button( - root, - text="Pause", - font="Rockwell", - relief="flat", - command=pause_music) + root, text="Pause", font="Rockwell", relief="flat", command=pause_music +) pause_music_button.pack(side=RIGHT) # Play music button play_music_button = Button( - root, - text="Play", - font="Rockwell", - relief="flat", - command=play_music) + root, text="Play", font="Rockwell", relief="flat", command=play_music +) play_music_button.pack(side=RIGHT) # Set default button satates to disabled diff --git a/mysqldump_to_csv/mysql_dump_to_csv.py b/mysqldump_to_csv/mysql_dump_to_csv.py index 17ac8fe5e..c52aec518 100644 --- a/mysqldump_to_csv/mysql_dump_to_csv.py +++ b/mysqldump_to_csv/mysql_dump_to_csv.py @@ -1,29 +1,29 @@ import ast import csv import os -import sys import re +import sys # This will hold the table name as key, and columns as values. mainDict = {} def createStatement(line): - return line.startswith('CREATE TABLE') + return line.startswith("CREATE TABLE") # To detect fields, aka column names def fieldDef(line): - return line.strip().startswith('`') + return line.strip().startswith("`") def insertStatement(line): - return line.startswith('INSERT INTO') + return line.startswith("INSERT INTO") def getCleanedValue(line): value = None - result = re.search(r'\`([^\`]*)\`', line) + result = re.search(r"\`([^\`]*)\`", line) if result: value = result.groups()[0] print(value) @@ -31,9 +31,9 @@ def getCleanedValue(line): def getValueTuple(line): - values = line.partition(' VALUES ')[-1].strip().replace('NULL', "''") + values = line.partition(" VALUES ")[-1].strip().replace("NULL", "''") # To exclude the ; - if values[-1] == ';': + if values[-1] == ";": values = values[:-1] return ast.literal_eval(values) @@ -41,8 +41,8 @@ def getValueTuple(line): def writeFile(outputDirectory, tableName, schema, values): # File name that the current table will be assigned to - fileName = os.path.join(outputDirectory, '%s.csv' % (tableName,)) - with open(fileName, 'w') as writeFile: + fileName = os.path.join(outputDirectory, "%s.csv" % (tableName,)) + with open(fileName, "w") as writeFile: writer = csv.DictWriter(writeFile, fieldnames=schema) writer.writeheader() for value in values: @@ -52,7 +52,7 @@ def writeFile(outputDirectory, tableName, schema, values): def parseFile(fileName, outputDirectory): tableName = None - with open(fileName, 'r') as readFile: + with open(fileName, "r") as readFile: for line in readFile: if createStatement(line): tableName = getCleanedValue(line) @@ -67,5 +67,5 @@ def parseFile(fileName, outputDirectory): writeFile(outputDirectory, tableName, currentTable, values) -if __name__ == '__main__': +if __name__ == "__main__": parseFile(sys.argv[1], sys.argv[2]) diff --git a/netflix_analyzer/netflix.py b/netflix_analyzer/netflix.py index ee4888e80..ebe0e9ff0 100644 --- a/netflix_analyzer/netflix.py +++ b/netflix_analyzer/netflix.py @@ -1,162 +1,212 @@ -import pandas as pd import matplotlib.pyplot as plt +import pandas as pd import seaborn as sns def clean_data(user_name: str, data_frame: object) -> object: - ''' - user_name: user name whose data you want to visualize - data_frame: data in the form panda dataframe + """ + user_name: user name whose data you want to visualize + data_frame: data in the form panda dataframe - Extra columns are removed and the time is converted to proper format - and returns the cleaned data - ''' + Extra columns are removed and the time is converted to proper format + and returns the cleaned data + """ # Extracting data for the given profile name - data = data_frame[data_frame['Profile Name'] == user_name] + data = data_frame[data_frame["Profile Name"] == user_name] data.reset_index(inplace=True) # Droping extra columns that will not be used - columns_to_drop = ['Country', 'Bookmark', 'Latest Bookmark', 'index', 'Attributes'] + columns_to_drop = ["Country", "Bookmark", "Latest Bookmark", "index", "Attributes"] data = data.drop(columns=columns_to_drop) # Convert Start Time to datetime. Currently it is object - data = data.rename(columns={'Start Time': 'Date'}) - data['Date'] = pd.to_datetime(data['Date']) + data = data.rename(columns={"Start Time": "Date"}) + data["Date"] = pd.to_datetime(data["Date"]) - data['Year'] = data['Date'].dt.year - data['Month'] = data['Date'].dt.month - data['day_of_week'] = data['Date'].dt.dayofweek - data['day_name'] = data['Date'].dt.day_name() + data["Year"] = data["Date"].dt.year + data["Month"] = data["Date"].dt.month + data["day_of_week"] = data["Date"].dt.dayofweek + data["day_name"] = data["Date"].dt.day_name() # Type of video like TRAILER, PROMOTIONAL, etc. - data = data[data['Supplemental Video Type'].isna()] - data[['TV Show', 'Season', 'Episode']] = data['Title'].str.split(':', expand=True, n=2) - data['Content Type'] = data['Season'].apply(lambda x : 'Movie' if x is None else 'TV Show') - data = data.rename(columns={'Temp': 'Content Type'}) + data = data[data["Supplemental Video Type"].isna()] + data[["TV Show", "Season", "Episode"]] = data["Title"].str.split( + ":", expand=True, n=2 + ) + data["Content Type"] = data["Season"].apply( + lambda x: "Movie" if x is None else "TV Show" + ) + data = data.rename(columns={"Temp": "Content Type"}) # Droping Supplemental Videos - data = data.drop(columns='Supplemental Video Type') - data['date_of_month'] = data['Date'].dt.day - temporary_data = ['Profile Name', 'Date', 'date_of_month', 'day_of_week', 'day_name', 'Month', 'Year'] - temporary_data += ['Duration', 'Title', 'TV Show', 'Season', 'Episode', 'Content Type', 'Device Type'] + data = data.drop(columns="Supplemental Video Type") + data["date_of_month"] = data["Date"].dt.day + temporary_data = [ + "Profile Name", + "Date", + "date_of_month", + "day_of_week", + "day_name", + "Month", + "Year", + ] + temporary_data += [ + "Duration", + "Title", + "TV Show", + "Season", + "Episode", + "Content Type", + "Device Type", + ] data = data[temporary_data] # Extract timestamp as a seperate column - data['Start Time'] = data['Date'].apply(lambda x : str(x).split('+')[0].split(' ')[1]) - data['Date'] = pd.to_datetime(data['Date']) - data['Date'] = data['Date'].dt.date - data.set_index('Date', inplace=True) + data["Start Time"] = data["Date"].apply( + lambda x: str(x).split("+")[0].split(" ")[1] + ) + data["Date"] = pd.to_datetime(data["Date"]) + data["Date"] = data["Date"].dt.date + data.set_index("Date", inplace=True) # Convert duration HH:MM:SS to number of minutes - data['Duration'] = data['Duration'].str.split(':').apply(lambda x: int(x[0]) * 3600 + int(x[1]) * 60 + int(x[2])) + data["Duration"] = ( + data["Duration"] + .str.split(":") + .apply(lambda x: int(x[0]) * 3600 + int(x[1]) * 60 + int(x[2])) + ) return data def average_time_spent_per_day(data: object) -> None: - ''' - data: cleaned data - - Extracts the average time spent on each day - ''' - - avg_second_per_day = data.groupby('day_name')['Duration'].mean().sort_values() - day_of_week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] + """ + data: cleaned data + + Extracts the average time spent on each day + """ + + avg_second_per_day = data.groupby("day_name")["Duration"].mean().sort_values() + day_of_week = [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + ] sns.set_style("darkgrid") - font = {'family': 'serif', - 'color': '#004466', - 'weight': 'normal', - 'size': 18} + font = {"family": "serif", "color": "#004466", "weight": "normal", "size": 18} plt.figure(figsize=(20, 15)) - ax = sns.barplot(x=avg_second_per_day.index, y=avg_second_per_day.values, palette=("crest_r"), order=day_of_week) - ax.set_ylabel('Viewing Duration (in Seconds)', fontdict={'size': 14, 'family': 'serif'}) - ax.set_xlabel('Day of Week', fontdict={'size': 14, 'family': 'serif'}) - ax.set_title('Average Viewing Time per Day (in seconds)', fontdict=font) - ax.tick_params(axis='both', labelsize=13) + ax = sns.barplot( + x=avg_second_per_day.index, + y=avg_second_per_day.values, + palette=("crest_r"), + order=day_of_week, + ) + ax.set_ylabel( + "Viewing Duration (in Seconds)", fontdict={"size": 14, "family": "serif"} + ) + ax.set_xlabel("Day of Week", fontdict={"size": 14, "family": "serif"}) + ax.set_title("Average Viewing Time per Day (in seconds)", fontdict=font) + ax.tick_params(axis="both", labelsize=13) plt.show() def top_watched_TV_show(data: object) -> object: - ''' - data: cleaned data + """ + data: cleaned data - Extracts the TV Shows and calculate the total time spent on each TV Show - and returns the data of only tv_shows - ''' + Extracts the TV Shows and calculate the total time spent on each TV Show + and returns the data of only tv_shows + """ - tv_shows = data[data['Content Type'] == 'TV Show'] - tv_shows[tv_shows['Episode'].isna()] - tv_shows['Title'].nunique() - order_tv_shows = tv_shows.groupby('TV Show')['Duration'] - most_watched = order_tv_shows.mean().reset_index().sort_values(by='Duration', ascending=False) + tv_shows = data[data["Content Type"] == "TV Show"] + tv_shows[tv_shows["Episode"].isna()] + tv_shows["Title"].nunique() + order_tv_shows = tv_shows.groupby("TV Show")["Duration"] + most_watched = ( + order_tv_shows.mean().reset_index().sort_values(by="Duration", ascending=False) + ) - font = {'family': 'serif', - 'color': '#004466', - 'weight': 'normal', - 'size': 18} + font = {"family": "serif", "color": "#004466", "weight": "normal", "size": 18} plt.figure(figsize=(22, 12)) - ax = sns.barplot(y=most_watched['TV Show'][:10], x=most_watched['Duration'][:10], palette=("winter")) - ax.set_ylabel('TV Series', fontdict={'size': 14, 'family': 'serif'}) - ax.set_xlabel('Watch Time (in seconds)', fontdict={'size': 14, 'family': 'serif'}) - ax.set_title('Top 10 TV Shows by Average Duration (seconds)', fontdict=font) - ax.tick_params(axis='both', labelsize=13) + ax = sns.barplot( + y=most_watched["TV Show"][:10], + x=most_watched["Duration"][:10], + palette=("winter"), + ) + ax.set_ylabel("TV Series", fontdict={"size": 14, "family": "serif"}) + ax.set_xlabel("Watch Time (in seconds)", fontdict={"size": 14, "family": "serif"}) + ax.set_title("Top 10 TV Shows by Average Duration (seconds)", fontdict=font) + ax.tick_params(axis="both", labelsize=13) return tv_shows def binge_watch(tv_shows: object) -> None: - ''' - tv_shows: data of tv_shows - - Extract top binge watched TV Shows - ''' - - binge = tv_shows.groupby([tv_shows.index, 'TV Show']) - binge = binge['Episode'].count().reset_index().sort_values(by='Episode', ascending=False) - binge = binge[binge['Episode'] > 5] - top_10_binge = binge.groupby('TV Show')['Episode'].sum().reset_index().sort_values(by='Episode', ascending=False) - - font = {'family': 'serif', - 'color': '#004466', - 'weight': 'normal', - 'size': 18} + """ + tv_shows: data of tv_shows + + Extract top binge watched TV Shows + """ + + binge = tv_shows.groupby([tv_shows.index, "TV Show"]) + binge = ( + binge["Episode"] + .count() + .reset_index() + .sort_values(by="Episode", ascending=False) + ) + binge = binge[binge["Episode"] > 5] + top_10_binge = ( + binge.groupby("TV Show")["Episode"] + .sum() + .reset_index() + .sort_values(by="Episode", ascending=False) + ) + + font = {"family": "serif", "color": "#004466", "weight": "normal", "size": 18} plt.figure(figsize=(22, 12)) - ax = sns.barplot(y=top_10_binge['TV Show'][:10], x=top_10_binge['Episode'][:10], orient='h', ci='None') - ax.set_ylabel('TV Series', fontdict={'size': 14, 'family': 'serif'}) - ax.set_xlabel('Number of Episodes', fontdict={'size': 14, 'family': 'serif'}) - ax.set_title('Top 10 Binge Watching TV Series', fontdict=font) - ax.tick_params(axis='both', labelsize=13) + ax = sns.barplot( + y=top_10_binge["TV Show"][:10], + x=top_10_binge["Episode"][:10], + orient="h", + ci="None", + ) + ax.set_ylabel("TV Series", fontdict={"size": 14, "family": "serif"}) + ax.set_xlabel("Number of Episodes", fontdict={"size": 14, "family": "serif"}) + ax.set_title("Top 10 Binge Watching TV Series", fontdict=font) + ax.tick_params(axis="both", labelsize=13) def average_time_spent_per_month(data: object) -> None: - ''' - data: cleaned data + """ + data: cleaned data - Extact the average time spent per month - ''' + Extact the average time spent per month + """ - font = {'family': 'serif', - 'color': '#004466', - 'weight': 'normal', - 'size': 18} + font = {"family": "serif", "color": "#004466", "weight": "normal", "size": 18} # Each row is a data point in boxplot and plots the distribution (histogram) of Watch Time for each month plt.figure(figsize=(20, 10)) - ax = sns.boxplot(x=data['Month'], y=data['Duration']) - ax.set_ylabel('Watch Time (Seconds)', fontdict={'size': 14, 'family': 'serif'}) - ax.set_xlabel('Month', fontdict={'size': 14, 'family': 'serif'}) - ax.set_title('Distribution of Duration (Seconds) over the months', fontdict=font) - ax.tick_params(axis='both', labelsize=13) + ax = sns.boxplot(x=data["Month"], y=data["Duration"]) + ax.set_ylabel("Watch Time (Seconds)", fontdict={"size": 14, "family": "serif"}) + ax.set_xlabel("Month", fontdict={"size": 14, "family": "serif"}) + ax.set_title("Distribution of Duration (Seconds) over the months", fontdict=font) + ax.tick_params(axis="both", labelsize=13) plt.show() def main(): - user_name = '153' - data_frame = pd.read_csv('ViewingActivity.csv') + user_name = "153" + data_frame = pd.read_csv("ViewingActivity.csv") final_data = clean_data(user_name, data_frame) average_time_spent_per_day(final_data) @@ -165,5 +215,5 @@ def main(): average_time_spent_per_month(final_data) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/news_scraper/news_scraper.py b/news_scraper/news_scraper.py index 209d9a09b..aa4777ef5 100644 --- a/news_scraper/news_scraper.py +++ b/news_scraper/news_scraper.py @@ -1,40 +1,37 @@ +from datetime import date + +import pandas as pd import requests from bs4 import BeautifulSoup -from datetime import date from docx import Document -import pandas as pd today = date.today() page = requests.get("https://inshorts.com/en/read/") page.status_code # A status_code of 200 means that the page downloaded successfully. -soup = BeautifulSoup(page.content, 'html.parser') +soup = BeautifulSoup(page.content, "html.parser") -headlines_tags = soup.find_all('span', itemprop="headline") +headlines_tags = soup.find_all("span", itemprop="headline") headlines = [pt.get_text() for pt in headlines_tags] -author_tags = soup.find_all('span', class_="author") +author_tags = soup.find_all("span", class_="author") author = [pt.get_text() for pt in author_tags] author = author[::2] -date_tags = soup.find_all('span', class_="date") +date_tags = soup.find_all("span", class_="date") date = [pt.get_text() for pt in date_tags] -time_tags = soup.find_all('span', class_="time", itemprop="datePublished") +time_tags = soup.find_all("span", class_="time", itemprop="datePublished") time = [pt.get_text() for pt in time_tags] -body_tags = soup.find_all('div', itemprop="articleBody") +body_tags = soup.find_all("div", itemprop="articleBody") body = [pt.get_text() for pt in body_tags] final = [] for i in range(len(body)): - news = {'Title': None, - 'Author': None, - 'Date': None, - 'Time': None, - 'Details': None} - news['Title'] = headlines[i] - news['Author'] = author[i] - news['Date'] = date[i] - news['Time'] = time[i] - news['Details'] = body[i] + news = {"Title": None, "Author": None, "Date": None, "Time": None, "Details": None} + news["Title"] = headlines[i] + news["Author"] = author[i] + news["Date"] = date[i] + news["Time"] = time[i] + news["Details"] = body[i] final.append(news) final @@ -42,24 +39,20 @@ textfile.write("NEWS " + str(today) + "\n") for element in final: for key, value in element.items(): - textfile.write(f'{key}: {value}\n') - textfile.write('\n') + textfile.write(f"{key}: {value}\n") + textfile.write("\n") textfile.close() document = Document() -document.add_heading('NEWS ' + str(today), 0) +document.add_heading("NEWS " + str(today), 0) for element in final: - p = document.add_paragraph('') + p = document.add_paragraph("") for key, value in element.items(): - p.add_run(f'{key}: {value}\n') - p.add_run('\n') -document.save('D:/pythonProject2/news.docx') + p.add_run(f"{key}: {value}\n") + p.add_run("\n") +document.save("D:/pythonProject2/news.docx") -news_df = pd.DataFrame({ - "Title": headlines, - "Author": author, - "Date": date, - "Time": time, - "Details": body -}) -news_df.to_csv('news.csv') +news_df = pd.DataFrame( + {"Title": headlines, "Author": author, "Date": date, "Time": time, "Details": body} +) +news_df.to_csv("news.csv") diff --git a/old_docker_images_auto_delete/main.py b/old_docker_images_auto_delete/main.py index 5345214ca..52c86de6e 100644 --- a/old_docker_images_auto_delete/main.py +++ b/old_docker_images_auto_delete/main.py @@ -8,16 +8,17 @@ which would be never stopped. """ -import subprocess as sp -import re -import operator import itertools +import operator +import re +import subprocess as sp class DeleteImage: """ Deleting Old Docker Images """ + def __init__(self): self.img_list = [] self.hash_list = [] @@ -26,9 +27,14 @@ def get_all(self): """ Storing All the Docker Image Details Found on the System to a File """ - file = open("temp.txt", "r+", encoding='utf-8') + file = open("temp.txt", "r+", encoding="utf-8") file.truncate(0) - sp.run("sudo docker image list --format '{{.Repository}}~{{.Tag}}' >> temp.txt",shell=True , capture_output=True, check=True) # noqa + sp.run( + "sudo docker image list --format '{{.Repository}}~{{.Tag}}' >> temp.txt", + shell=True, + capture_output=True, + check=True, + ) # noqa file.close() def is_excluded(self, tag): @@ -46,17 +52,17 @@ def load_all(self): """ Loading data from the File to the Python program """ - file = open("temp.txt", "r", encoding='utf-8') + file = open("temp.txt", "r", encoding="utf-8") for line in file: line = line.rstrip("\n") - image = line.split('~') + image = line.split("~") if self.is_excluded(image[1]): regex = r"^(((\d+\.)?(\d+\.)?(\*|\d+)))(\-(dev|stage|prod))*$" match = re.search(regex, image[1]) - img_dict = {'Repository': image[0], 'Tag': match.group(2)} + img_dict = {"Repository": image[0], "Tag": match.group(2)} self.img_list.append(img_dict) file.close() @@ -64,9 +70,11 @@ def man_data(self): """ Manipulating Data to perform the reqd operation """ - key = operator.itemgetter('Repository') - b_key = [{'Repository': x, 'Tag': [d['Tag'] for d in y]} - for x, y in itertools.groupby(sorted(self.img_list, key=key), key=key)] # noqa + key = operator.itemgetter("Repository") + b_key = [ + {"Repository": x, "Tag": [d["Tag"] for d in y]} + for x, y in itertools.groupby(sorted(self.img_list, key=key), key=key) + ] # noqa self.img_list.clear() self.img_list = b_key.copy() @@ -77,26 +85,29 @@ def sort_tag(self): """ for img in self.img_list: - temp = img['Tag'].copy() + temp = img["Tag"].copy() - for new, i in enumerate(img['Tag']): - img['Tag'][new] = int(i.replace('.', '')) + for new, i in enumerate(img["Tag"]): + img["Tag"][new] = int(i.replace(".", "")) - max_len = len(str(max(abs(x) for x in img['Tag']))) - template_string = '{:<0' + str(max_len) + '}' + max_len = len(str(max(abs(x) for x in img["Tag"]))) + template_string = "{:<0" + str(max_len) + "}" final_list = [] - for new, i in enumerate(img['Tag']): + for new, i in enumerate(img["Tag"]): final_list.append(template_string.format(i)) - for i in range(0, len(img['Tag'])): - hash_map = {'TagsManipulated': final_list[i], 'TagsOriginal': temp[i]} # noqa + for i in range(0, len(img["Tag"])): + hash_map = { + "TagsManipulated": final_list[i], + "TagsOriginal": temp[i], + } # noqa self.hash_list.append(hash_map) final_list.sort() - img['Tag'].clear() - img['Tag'].extend(final_list[:-1]) + img["Tag"].clear() + img["Tag"].extend(final_list[:-1]) print(self.hash_list) print(self.img_list) @@ -106,11 +117,11 @@ def hash_function(self, tag): Hash Function for Error Detection """ for hash_map in self.hash_list: - if tag == hash_map['TagsManipulated']: - temp = hash_map['TagsOriginal'] + if tag == hash_map["TagsManipulated"]: + temp = hash_map["TagsOriginal"] break else: - temp = 'Error in Manipulation' + temp = "Error in Manipulation" return temp def remove_image(self): @@ -118,12 +129,17 @@ def remove_image(self): Running the Docker RMI Command to Delete the Older Versions """ for img in self.img_list: - if img['Tag']: - for tag in img['Tag']: + if img["Tag"]: + for tag in img["Tag"]: val = self.hash_function(tag) - image_url = img['Repository'] + ":" + val + image_url = img["Repository"] + ":" + val print("Deleting Image : " + image_url) - sp.run("sudo docker rmi " + image_url,shell=True,capture_output=True , check=True) # noqa + sp.run( + "sudo docker rmi " + image_url, + shell=True, + capture_output=True, + check=True, + ) # noqa # Main Function diff --git a/password_checker/password_strength_checker.py b/password_checker/password_strength_checker.py index 4b14ee83c..06c61c5cb 100644 --- a/password_checker/password_strength_checker.py +++ b/password_checker/password_strength_checker.py @@ -1,8 +1,8 @@ -import sys import re +import sys password = sys.argv[1] -regex = re.compile('[@_!#$%^&*()<>?/|}{~:]') +regex = re.compile("[@_!#$%^&*()<>?/|}{~:]") t1 = len(password) >= 8 t2 = not (regex.search(password) is None) diff --git a/password_generator/password_generator.py b/password_generator/password_generator.py index e590f9f08..9ed97fe4f 100644 --- a/password_generator/password_generator.py +++ b/password_generator/password_generator.py @@ -1,18 +1,18 @@ import argparse # to work with the arguments -import string import secrets +import string # function to generate the password def get_password(length: int) -> str: # creating data - symbols = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+'] + symbols = ["!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "-", "+"] numbers = [str(a) for a in range(10)] lowercase_characters = string.ascii_lowercase uppercase_characters = string.ascii_uppercase # variable to hold the password - password = '' + password = "" # adding one symbol password += secrets.choice(symbols) @@ -66,7 +66,8 @@ def shuffle(password: list): # swap elements at index x and index y password[x], password[y] = password[y], password[x] # return concatenated password - return ''.join(password) + return "".join(password) + # main method @@ -84,28 +85,29 @@ def main(args: argparse.Namespace) -> None: password = get_password(length) # printing the password to the user - print(f'PASSWORD: {password}') + print(f"PASSWORD: {password}") -if __name__ == '__main__': +if __name__ == "__main__": # creating the argparse object parser = argparse.ArgumentParser() # adding the length argument parser.add_argument( - '-l', '--length', - help='Length of the password. [MIN=6], [MAX=20], [DEFAULT = 6]', - metavar='', + "-l", + "--length", + help="Length of the password. [MIN=6], [MAX=20], [DEFAULT = 6]", + metavar="", default=6, - type=int + type=int, ) # adding the exclude duplicates argument parser.add_argument( - '-ed', - '--excludeduplicates', - action='store_true', - help='Exculdes duplicate characters from the password' + "-ed", + "--excludeduplicates", + action="store_true", + help="Exculdes duplicate characters from the password", ) # parsing the argument diff --git a/password_manager/password_manager.py b/password_manager/password_manager.py index 7e5feaf63..111f28e81 100755 --- a/password_manager/password_manager.py +++ b/password_manager/password_manager.py @@ -9,15 +9,16 @@ """ import argparse -import sys -import os -import sqlite3 import base64 +import os import signal +import sqlite3 +import sys from getpass import getpass + +from Crypto import Random from Crypto.Cipher import AES from Crypto.Hash import SHA256 -from Crypto import Random # The program data file. FILENAME = ".pass.db" @@ -41,7 +42,7 @@ def main(): print(f"[{RED_COLOR}-{NO_COLOR}] Error in database connection...") sys.exit(1) - if args.password == '' or args.password is None: + if args.password == "" or args.password is None: # User didn't enter the password (argument) if is_first: @@ -55,7 +56,7 @@ def main(): print(f"[{RED_COLOR}-{NO_COLOR}] Didn't match...") sys.exit(1) - if new(user_password, COOKIE, '-', 0) != 0: + if new(user_password, COOKIE, "-", 0) != 0: # ERROR (Cookie didn't set) print(f"[{RED_COLOR}-{NO_COLOR}] Error in saving...") os.remove(FILENAME) @@ -125,13 +126,11 @@ def check_password(user_password): with sqlite3.connect(FILENAME) as conn: cursor = conn.cursor() # Fetches the cookie (canary) value - row = cursor.execute( - "SELECT * FROM passwords WHERE id=0;" - ).fetchone() + row = cursor.execute("SELECT * FROM passwords WHERE id=0;").fetchone() - bin_user_password = str(user_password).encode('utf-8') + bin_user_password = str(user_password).encode("utf-8") - if decrypt(bin_user_password, row[1]).decode('utf-8') == COOKIE: + if decrypt(bin_user_password, row[1]).decode("utf-8") == COOKIE: # The password is correct # because it can decrypt the encrypted cookie value return 0 @@ -157,7 +156,7 @@ def prompt(user_password): print("\nBye...") sys.exit(0) - if cmd.lower() == 'new': + if cmd.lower() == "new": name = input("Where did you use this password for> ") password = input("Enter the new password to save> ") @@ -171,17 +170,15 @@ def prompt(user_password): else: # ERROR - print( - f"[{RED_COLOR}-{NO_COLOR}] Error while writing the password..." - ) + print(f"[{RED_COLOR}-{NO_COLOR}] Error while writing the password...") prompt(user_password) - elif cmd.lower() == 'delete': + elif cmd.lower() == "delete": id_num = input("Which id? > ") confirm = input("Are you sure [Y/n]> ") - if confirm.lower() == 'y': + if confirm.lower() == "y": if delete(id_num) == 0: # Row deleted @@ -192,7 +189,7 @@ def prompt(user_password): prompt(user_password) - elif cmd.lower() == 'show': + elif cmd.lower() == "show": result = select_data(user_password) @@ -204,7 +201,7 @@ def prompt(user_password): prompt(user_password) - elif cmd.lower() == 'exit': + elif cmd.lower() == "exit": print("Bye...") sys.exit(0) @@ -242,14 +239,14 @@ def new(user_password, name, password, id_num=-1): );""", [ encrypt( - str(user_password).encode('utf-8'), - str(name).encode('utf-8') + str(user_password).encode("utf-8"), + str(name).encode("utf-8"), ), encrypt( - str(user_password).encode('utf-8'), - str(password).encode('utf-8') - ) - ] + str(user_password).encode("utf-8"), + str(password).encode("utf-8"), + ), + ], ) else: @@ -262,14 +259,14 @@ def new(user_password, name, password, id_num=-1): [ id_num, encrypt( - str(user_password).encode('utf-8'), - str(name).encode('utf-8') + str(user_password).encode("utf-8"), + str(name).encode("utf-8"), ), encrypt( - str(user_password).encode('utf-8'), - str(password).encode('utf-8') - ) - ] + str(user_password).encode("utf-8"), + str(password).encode("utf-8"), + ), + ], ) return 0 @@ -289,8 +286,7 @@ def delete(id_num): with sqlite3.connect(FILENAME) as conn: cursor = conn.cursor() cursor.execute( - "DELETE FROM passwords WHERE id = ? AND name != ?;", - [id_num, COOKIE] + "DELETE FROM passwords WHERE id = ? AND name != ?;", [id_num, COOKIE] ) return 0 @@ -319,12 +315,12 @@ def select_data(user_password): result.append( ( id_num, - decrypt( - str(user_password).encode('utf-8'), name - ).decode('utf-8'), - decrypt( - str(user_password).encode('utf-8'), password - ).decode('utf-8') + decrypt(str(user_password).encode("utf-8"), name).decode( + "utf-8" + ), + decrypt(str(user_password).encode("utf-8"), password).decode( + "utf-8" + ), ) ) @@ -386,11 +382,11 @@ def decrypt(key, source, decode=True): key = SHA256.new(key).digest() # extract the IV from the beginning - IV = source[:AES.block_size] + IV = source[: AES.block_size] decryptor = AES.new(key, AES.MODE_CBC, IV) # decrypt - data = decryptor.decrypt(source[AES.block_size:]) + data = decryptor.decrypt(source[AES.block_size :]) # pick the padding value from the end; Python 2.x: ord(data[-1]) padding = data[-1] @@ -409,18 +405,18 @@ def exit_program(sig, frame): sys.exit(0) -if __name__ == '__main__': +if __name__ == "__main__": global args # The program arguments parser = argparse.ArgumentParser(description="Password Manager CLI") # -p | --password PASSWORD parser.add_argument( - '-p', - '--password', - metavar='password', + "-p", + "--password", + metavar="password", type=str, - default='', - help='the program password' + default="", + help="the program password", ) args = parser.parse_args() diff --git a/pdf_editor/pdf_editor.py b/pdf_editor/pdf_editor.py index 2cead0c35..635870dc6 100644 --- a/pdf_editor/pdf_editor.py +++ b/pdf_editor/pdf_editor.py @@ -1,20 +1,21 @@ +import os +import subprocess + from docx import Document from pdf2docx import parse -import subprocess -import os def pdf_to_word(pdf_file): # convert to dpcx - word_file = 'word.docx' + word_file = "word.docx" parse(pdf_file, word_file) def edit_word(find, replacement): # open docx file - word_file = Document('word.docx') + word_file = Document("word.docx") replace = {find: replacement} # scan file and replace text with new text @@ -24,13 +25,15 @@ def edit_word(find, replacement): line.text = line.text.replace(x, replace[x]) # exported edited docx - word_file.save('converted.docx') + word_file.save("converted.docx") def word_to_pdf(): # export edited docx to pdf - subprocess.run(["libreoffice", "--headless", "--convert-to", "pdf", 'converted.docx']) + subprocess.run( + ["libreoffice", "--headless", "--convert-to", "pdf", "converted.docx"] + ) # clean up files if os.path.exists("word.docx"): @@ -42,7 +45,9 @@ def word_to_pdf(): if __name__ == "__main__": # get user input: pdf to edit, text to find, replacement text - file, find, replacement = input("Your settings (format: file_name.pdf text_to_replace replacement_text): ").split() + file, find, replacement = input( + "Your settings (format: file_name.pdf text_to_replace replacement_text): " + ).split() pdf_to_word(file) edit_word(find, replacement) diff --git a/pdf_encryptor/pdf_encryptor.py b/pdf_encryptor/pdf_encryptor.py index c53dd6ec1..00b2f8c7a 100644 --- a/pdf_encryptor/pdf_encryptor.py +++ b/pdf_encryptor/pdf_encryptor.py @@ -1,20 +1,33 @@ import argparse import getpass -import pyAesCrypt import os import sys +import pyAesCrypt BUFFERSIZE = 64 * 1024 def parse_args(): - parser = argparse.ArgumentParser(description="Encrypt " - "and decrypt PDF files") - parser.add_argument('-e', '--encrypt', dest='encrypt', type=str, - nargs=1, metavar='filename', help='Encrypt') - parser.add_argument('-d', '--decrypt', dest='decrypt', type=str, - nargs=1, metavar='filename', help='Decrypt') + parser = argparse.ArgumentParser(description="Encrypt " "and decrypt PDF files") + parser.add_argument( + "-e", + "--encrypt", + dest="encrypt", + type=str, + nargs=1, + metavar="filename", + help="Encrypt", + ) + parser.add_argument( + "-d", + "--decrypt", + dest="decrypt", + type=str, + nargs=1, + metavar="filename", + help="Decrypt", + ) args = parser.parse_args() if len(sys.argv) == 1: @@ -52,19 +65,21 @@ def decrypt(filename, password): sys.exit() -if __name__ == '__main__': +if __name__ == "__main__": args = parse_args() if args.encrypt: encrypt_file = args.encrypt[0] file_exist(encrypt_file) - password = getpass.getpass("Please provide the password to " - "encrypt the file with: ") + password = getpass.getpass( + "Please provide the password to " "encrypt the file with: " + ) encrypt(encrypt_file, password) print("{} has been successfully encrypted.".format(encrypt_file)) else: decrypt_file = args.decrypt[0] file_exist(decrypt_file) - password = getpass.getpass("Please provide the password to " - "decrypt the file with: ") + password = getpass.getpass( + "Please provide the password to " "decrypt the file with: " + ) decrypt(decrypt_file, password) print("{} has been successfully decrypted.".format(decrypt_file)) diff --git a/pdf_merger/pdf_merger.py b/pdf_merger/pdf_merger.py index 9f16341fa..8ca40de2c 100644 --- a/pdf_merger/pdf_merger.py +++ b/pdf_merger/pdf_merger.py @@ -1,7 +1,9 @@ import os + from PyPDF2 import PdfFileMerger -print(""" +print( + """ __________________ ___ ___ | ___ \\ _ \\ ___| | \\/ | | |_/ / | | | |_ | . . | ___ _ __ __ _ ___ _ __ @@ -9,13 +11,20 @@ | | | |/ /| | | | | | __/ | | (_| | __/ | \\_| |___/ \\_| \\_| |_/\\___|_| \\__, |\\___|_| __/ | - |___/ """) + |___/ """ +) print("📚 Step 1: put the PDFs you want to merge in a folder!") -print("✏️ Step 2: name your files in the order you want to merge!\ - (like 'file1.pdf', 'file2.pdf'...)") +print( + "✏️ Step 2: name your files in the order you want to merge!\ + (like 'file1.pdf', 'file2.pdf'...)" +) -path = os.path.abspath(input("📬 Step 3: Type the path of the folder\ - containing the PDFs you want to merge (relative path): ")) +path = os.path.abspath( + input( + "📬 Step 3: Type the path of the folder\ + containing the PDFs you want to merge (relative path): " + ) +) os.chdir(path) output_file = input("💌 Step 4 (required): Name your output file: ") + ".pdf" diff --git a/pdf_pages_remover/main.py b/pdf_pages_remover/main.py index 79a83cf1d..a646492d6 100644 --- a/pdf_pages_remover/main.py +++ b/pdf_pages_remover/main.py @@ -1,4 +1,4 @@ -from PyPDF2 import PdfFileWriter, PdfFileReader +from PyPDF2 import PdfFileReader, PdfFileWriter print("What is the file that you would like to modify?\n[Provide file address]") file = str(input()) @@ -8,7 +8,9 @@ print("How many pages do you need to delete?") n = int(input()) -print("Enter the page numbers of the files you want to delete:\n[Enter page numbers followed by pressing 'Enter']") +print( + "Enter the page numbers of the files you want to delete:\n[Enter page numbers followed by pressing 'Enter']" +) for i in range(0, n): givenPage = int(input()) - 1 pagesToDelete.append(givenPage) @@ -21,7 +23,7 @@ p = inputFile.getPage(i) output.addPage(p) -with open('output.pdf', 'wb') as f: +with open("output.pdf", "wb") as f: output.write(f) print("Done!") diff --git a/pdf_to_audio/pdf_to_audio.py b/pdf_to_audio/pdf_to_audio.py index 44aaf4aa4..903578702 100644 --- a/pdf_to_audio/pdf_to_audio.py +++ b/pdf_to_audio/pdf_to_audio.py @@ -1,13 +1,15 @@ -import pyttsx3 -import PyPDF2 -from tkinter.filedialog import askopenfilename from tkinter import Tk +from tkinter.filedialog import askopenfilename + +import PyPDF2 +import pyttsx3 from gtts import gTTS + Tk().withdraw() filelocation = askopenfilename() # To select pdf files -pdf_file = open(filelocation, 'rb') +pdf_file = open(filelocation, "rb") pdfReader = PyPDF2.PdfFileReader(pdf_file) speak = pyttsx3.init() pages = pdfReader.numPages @@ -21,7 +23,7 @@ speak.say(text) complete_pdf += text speak.runAndWait() -final_file = gTTS(text=complete_pdf, lang='en') # store file in variable +final_file = gTTS(text=complete_pdf, lang="en") # store file in variable file_name = input("Name of the MP3 file: ") final_file.save(file_name + ".mp3") # Saving audio file print("Conversion is Complete") diff --git a/pdf_to_docx/pdf2docx.py b/pdf_to_docx/pdf2docx.py index 067159c12..15848d477 100644 --- a/pdf_to_docx/pdf2docx.py +++ b/pdf_to_docx/pdf2docx.py @@ -1,7 +1,8 @@ # Import Libraries -from pdf2docx import parse from typing import Tuple + import groupdocs_conversion_cloud +from pdf2docx import parse def convert_pdf2docx(input_file: str, pages: Tuple = None): @@ -14,21 +15,27 @@ def convert_pdf2docx(input_file: str, pages: Tuple = None): def cloud_convert(app_sid, app_key): - convert_api = groupdocs_conversion_cloud.ConvertApi.from_keys(app_sid, app_key) # Create instance of the API + convert_api = groupdocs_conversion_cloud.ConvertApi.from_keys( + app_sid, app_key + ) # Create instance of the API file_api = groupdocs_conversion_cloud.FileApi.from_keys(app_sid, app_key) try: # upload source file to storage - filename = input("Please enter the complete and correct file path of the required pdf: ") + filename = input( + "Please enter the complete and correct file path of the required pdf: " + ) remote_name = filename - output_name = remote_name.split('.')[0] + "docx" + output_name = remote_name.split(".")[0] + "docx" remote_name = filename - strformat = 'docx' + strformat = "docx" - request_upload = groupdocs_conversion_cloud.UploadFileRequest(remote_name, filename) + request_upload = groupdocs_conversion_cloud.UploadFileRequest( + remote_name, filename + ) file_api.upload_file(request_upload) -# Extract Text from PDF document + # Extract Text from PDF document settings = groupdocs_conversion_cloud.ConvertSettings() settings.file_path = remote_name settings.format = strformat @@ -38,18 +45,28 @@ def cloud_convert(app_sid, app_key): print("Document converted successfully: " + str(response)) except groupdocs_conversion_cloud.ApiException as e: - print("Exception when calling get_supported_conversion_types: {0}".format(e.message)) + print( + "Exception when calling get_supported_conversion_types: {0}".format( + e.message + ) + ) if __name__ == "__main__": - choice = input("Press 1 for basic file conversion, 2 for advanced file conversion(GroupDocs account required)") - while choice != '1' and choice != '2': + choice = input( + "Press 1 for basic file conversion, 2 for advanced file conversion(GroupDocs account required)" + ) + while choice != "1" and choice != "2": print("Please enter a valid choice!\n") - choice = input("Press 1 for basic file conversion, 2 for advanced file conversion(GroupDocs account required)") - if choice == '1': + choice = input( + "Press 1 for basic file conversion, 2 for advanced file conversion(GroupDocs account required)" + ) + if choice == "1": - pdf_path = input("Please enter the complete and correct file path of the required pdf: ") + pdf_path = input( + "Please enter the complete and correct file path of the required pdf: " + ) convert_pdf2docx(pdf_path) else: sid = input("Enter app SID: ") diff --git a/pdf_to_image/main_code.py b/pdf_to_image/main_code.py index fa763a1ab..d38f60442 100644 --- a/pdf_to_image/main_code.py +++ b/pdf_to_image/main_code.py @@ -1,10 +1,14 @@ import os import sys -from PyPDF2 import PdfFileMerger + from pdf2image import convert_from_path +from PyPDF2 import PdfFileMerger -sys.path.insert(1, '''B:/Production_Programs/Github/ - Automation-scripts/Pdf_to_image/sample_files''') +sys.path.insert( + 1, + """B:/Production_Programs/Github/ + Automation-scripts/Pdf_to_image/sample_files""", +) fileName = "myfile.pdf" if os.path.exists(fileName): @@ -14,7 +18,7 @@ x = [a for a in os.listdir() if a.endswith(".pdf")] merger = PdfFileMerger() for pdf in x: - merger.append(open(pdf, 'rb')) + merger.append(open(pdf, "rb")) with open(fileName, "wb") as fout: merger.write(fout) @@ -23,7 +27,7 @@ images = convert_from_path(fileName) for i, image in enumerate(images): - fname = 'image' + str(i) + '.png' + fname = "image" + str(i) + ".png" image.save(fname, "PNG") print("all file converted") diff --git a/pdf_tools/pdf_tools.py b/pdf_tools/pdf_tools.py index bed8ea20e..c0258445b 100644 --- a/pdf_tools/pdf_tools.py +++ b/pdf_tools/pdf_tools.py @@ -10,16 +10,24 @@ # IMPORTANT::keep your pdf file in the SAME file or add path/rename MANUALLY -from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger from pathlib import Path -print("this script can print, edit, modify, rotate and add passwords to PDF documents if used properly") -pdf_path = (Path.home() / "myfile.pdf") +from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter + +print( + "this script can print, edit, modify, rotate and add passwords to PDF documents if used properly" +) +pdf_path = Path.home() / "myfile.pdf" pdf = PdfFileReader(str(pdf_path)) print("to get info on your file type INFO") if input() == "INFO": - print("documeng title", pdf.documentInfo.title, "\n", "from page 0 to", int - (pdf.documentInfo.title) - 1) + print( + "documeng title", + pdf.documentInfo.title, + "\n", + "from page 0 to", + int(pdf.documentInfo.title) - 1, + ) print("number of pages:", pdf.getNumPages()) print("more details:", pdf.documentInfo) print("to extract pages type OUTPUT") @@ -28,7 +36,7 @@ if input() == "FULL": for page in pdf.pages: print("text will be saved in a txt file") - with open('fulltext.txt', 'w') as f: + with open("fulltext.txt", "w") as f: f.write(page.extractText()) if input() == "PAGE": print("which page do you want?") @@ -48,7 +56,7 @@ print("add more pages (YES/NO)") print("if you want to concatenate two PDF docs, type ADD") if input() == "ADD": - BASE_PATH = (Path.home()) + BASE_PATH = Path.home() print("name the two files eg file1.pdf, file2.pdf one by one") m = input() n = input() @@ -59,7 +67,9 @@ output_path = Path.home() / "concatenated.pdf" with output_path.open(mode="wb") as output_file: pdf_merger.write(output_file) -print("if you want to rotate all pages clockwise write CW or write ACW for anticlockwise") +print( + "if you want to rotate all pages clockwise write CW or write ACW for anticlockwise" +) if input() == "CW": pdf_reader = PdfFileReader(str(pdf_path)) pdf_writer = PdfFileWriter() diff --git a/pdf_watermarkadder/main.py b/pdf_watermarkadder/main.py index d6d9b0a28..17ae5cd94 100644 --- a/pdf_watermarkadder/main.py +++ b/pdf_watermarkadder/main.py @@ -1,9 +1,8 @@ -from reportlab.pdfgen import canvas -from reportlab.lib.units import inch +from PyPDF2 import PdfFileReader, PdfFileWriter from reportlab.lib import colors from reportlab.lib.pagesizes import A4 -from PyPDF2 import PdfFileReader, PdfFileWriter - +from reportlab.lib.units import inch +from reportlab.pdfgen import canvas print("Enter file names with its extenstion!") @@ -21,10 +20,9 @@ def makeWatermark(): def makepdf(): pdf_file = input("PDF file: ") - watermark = 'watermark.pdf' + watermark = "watermark.pdf" merged = "finalDraft.pdf" - with open(pdf_file, "rb") as input_file,\ - open(watermark, "rb") as watermark_file: + with open(pdf_file, "rb") as input_file, open(watermark, "rb") as watermark_file: input_pdf = PdfFileReader(input_file) watermark_pdf = PdfFileReader(watermark_file) watermark_page = watermark_pdf.getPage(0) diff --git a/png_to_jpg/main.py b/png_to_jpg/main.py index 1060f235a..b2183d556 100644 --- a/png_to_jpg/main.py +++ b/png_to_jpg/main.py @@ -1,13 +1,14 @@ -from PIL import Image import os +from PIL import Image + project_root_path = os.path.dirname(os.path.abspath(__file__)) # open image in png format -img_png = Image.open(project_root_path + '/input/mario.png') +img_png = Image.open(project_root_path + "/input/mario.png") # converting image to RGB -rgb_im = img_png.convert('RGB') +rgb_im = img_png.convert("RGB") # The image object is used to save the image in jpg format -rgb_im.save(project_root_path + '/output/mario.jpg') +rgb_im.save(project_root_path + "/output/mario.jpg") diff --git a/pnr_status_checker/pnr_status_checker.py b/pnr_status_checker/pnr_status_checker.py index fe1651a55..741b905a4 100644 --- a/pnr_status_checker/pnr_status_checker.py +++ b/pnr_status_checker/pnr_status_checker.py @@ -1,4 +1,5 @@ import requests + api_key = "" base_url = "https://api.railwayapi.com/v2/pnr-status/pnr/" pnr_number = str(input("enter the PNR number")) @@ -18,24 +19,41 @@ total_passengers = result["total_passengers"] passengers_list = result["passengers"] chart_prepared = result["chart_prepared"] - print(" train name : " + str(train_name) - + "\n train number : " + str(train_number) - + "\n from station : " + str(from_station) - + "\n to station : " + str(to_station) - + "\n boarding point : " + str(boarding_point) - + "\n reservation unto : " + str(reservation_unto) - + "\n pnr number : " + str(pnr_num) - + "\n date of journey : " + str(date_of_journey) - + "\n total no. of passengers: " + str(total_passengers) - + "\n chart prepared : " + str(chart_prepared)) + print( + " train name : " + + str(train_name) + + "\n train number : " + + str(train_number) + + "\n from station : " + + str(from_station) + + "\n to station : " + + str(to_station) + + "\n boarding point : " + + str(boarding_point) + + "\n reservation unto : " + + str(reservation_unto) + + "\n pnr number : " + + str(pnr_num) + + "\n date of journey : " + + str(date_of_journey) + + "\n total no. of passengers: " + + str(total_passengers) + + "\n chart prepared : " + + str(chart_prepared) + ) # for multiple passengers against same PNR for passenger in passengers_list: passenger_num = passenger["no"] current_status = passenger["current_status"] booking_status = passenger["booking_status"] # print following values - print(" passenger number : " + str(passenger_num) - + "\n current status : " + str(current_status) - + "\n booking_status : " + str(booking_status)) + print( + " passenger number : " + + str(passenger_num) + + "\n current status : " + + str(current_status) + + "\n booking_status : " + + str(booking_status) + ) else: print("Record Not Found") diff --git a/polygon_detector/polygon_detect.py b/polygon_detector/polygon_detect.py index 3764b8457..2b59e2a18 100644 --- a/polygon_detector/polygon_detect.py +++ b/polygon_detector/polygon_detect.py @@ -1,12 +1,12 @@ - # flake8: noqa -import cv2 -import numpy as np import os +import cv2 +import numpy as np shapes = {} + def scan_image(img_file_path): global shapes @@ -21,29 +21,29 @@ def scan_image(img_file_path): for i in range(1, len(co)): app = cv2.approxPolyDP(co[i], 0.01 * cv2.arcLength(co[i], True), True) M = cv2.moments(co[i]) - cX = int(M['m10'] / M['m00']) - cY = int(M['m01'] / M['m00']) + cX = int(M["m10"] / M["m00"]) + cY = int(M["m01"] / M["m00"]) Area = round(cv2.contourArea(co[i]), 1) colorarr = img[cY, cX] - fincol = 'NA' + fincol = "NA" B = colorarr[0] G = colorarr[1] R = colorarr[2] - if (R > G): - if (B > R): - fincol = 'blue' + if R > G: + if B > R: + fincol = "blue" else: - fincol = 'red' + fincol = "red" else: - if (B > G): - fincol = 'blue' + if B > G: + fincol = "blue" else: - fincol = 'green' - if (len(app) == 3): - shapes1['Triangle'] = [fincol, Area, cX, cY] - elif (len(app) == 4): + fincol = "green" + if len(app) == 3: + shapes1["Triangle"] = [fincol, Area, cX, cY] + elif len(app) == 4: ptsarr = app.ravel() x1 = ptsarr[0] @@ -55,13 +55,13 @@ def scan_image(img_file_path): x4 = ptsarr[6] y4 = ptsarr[7] - l1 = ((x2 - x1) ** 2 + (y2 - y1) ** 2) - l2 = ((x3 - x2) ** 2 + (y3 - y2) ** 2) - l3 = ((x4 - x3) ** 2 + (y4 - y3) ** 2) - l4 = ((x4 - x1) ** 2 + (y4 - y1) ** 2) + l1 = (x2 - x1) ** 2 + (y2 - y1) ** 2 + l2 = (x3 - x2) ** 2 + (y3 - y2) ** 2 + l3 = (x4 - x3) ** 2 + (y4 - y3) ** 2 + l4 = (x4 - x1) ** 2 + (y4 - y1) ** 2 - d1 = ((x3 - x1) ** 2 + (y3 - y1) ** 2) - d2 = ((x4 - x2) ** 2 + (y4 - y2) ** 2) + d1 = (x3 - x1) ** 2 + (y3 - y1) ** 2 + d2 = (x4 - x2) ** 2 + (y4 - y2) ** 2 ap1 = float(l1) / l2 ap2 = float(l2) / l3 @@ -70,50 +70,54 @@ def scan_image(img_file_path): f = 0 - if (abs(x2 - x1) < 3 and abs(x3 - x4) < 3): + if abs(x2 - x1) < 3 and abs(x3 - x4) < 3: f = 1 - if (abs(y2 - y1) < 3 and abs(y3 - y4) < 3): + if abs(y2 - y1) < 3 and abs(y3 - y4) < 3: f = 1 - if (abs(x1 - x4) < 3 and abs(x2 - x3) < 3): + if abs(x1 - x4) < 3 and abs(x2 - x3) < 3: f = 1 - if (abs(y1 - y4) < 3 and abs(y2 - y3) < 3): + if abs(y1 - y4) < 3 and abs(y2 - y3) < 3: f = 1 - if ((x2 - x1) != 0 and (x3 - x4) != 0): + if (x2 - x1) != 0 and (x3 - x4) != 0: sl1 = float(y2 - y1) / (x2 - x1) sl2 = float(y3 - y4) / (x3 - x4) - if (sl2 != 0): + if sl2 != 0: sl = abs(float(sl1) / sl2) - if (sl >= 0.9 and sl <= 1.1): + if sl >= 0.9 and sl <= 1.1: f = 1 - if ((x1 - x4) != 0 and (x2 - x3) != 0): + if (x1 - x4) != 0 and (x2 - x3) != 0: sl1 = float(y1 - y4) / (x1 - x4) sl2 = float(y2 - y3) / (x2 - x3) - if (sl2 != 0): + if sl2 != 0: sl = abs(float(sl1) / sl2) - if (sl >= 0.9 and sl <= 1.1): + if sl >= 0.9 and sl <= 1.1: f = 1 - - if ((ap1 >= 0.9 and ap1 <= 1.1) and (ap2 >= 0.9 and ap2 <= 1.1) and (ap3 >= 0.9 and ap3 <= 1.1) and ( - ap4 >= 0.9 and ap4 <= 1.1)): - if (float(d1) / d2 >= 0.9 and float(d1) / d2 <= 1.1): - shapes1['Square'] = [fincol, Area, cX, cY] + if ( + (ap1 >= 0.9 and ap1 <= 1.1) + and (ap2 >= 0.9 and ap2 <= 1.1) + and (ap3 >= 0.9 and ap3 <= 1.1) + and (ap4 >= 0.9 and ap4 <= 1.1) + ): + if float(d1) / d2 >= 0.9 and float(d1) / d2 <= 1.1: + shapes1["Square"] = [fincol, Area, cX, cY] else: - shapes1['Rhombus'] = [fincol, Area, cX, cY] - elif ((float(l1) / l3 >= 0.9 and float(l1) / l3 <= 1.1) and ( - float(l2) / l4 >= 0.9 and float(l2) / l4 <= 1.1)): - shapes1['Parallelogram'] = [fincol, Area, cX, cY] - elif (f): - shapes1['Trapezium'] = [fincol, Area, cX, cY] + shapes1["Rhombus"] = [fincol, Area, cX, cY] + elif (float(l1) / l3 >= 0.9 and float(l1) / l3 <= 1.1) and ( + float(l2) / l4 >= 0.9 and float(l2) / l4 <= 1.1 + ): + shapes1["Parallelogram"] = [fincol, Area, cX, cY] + elif f: + shapes1["Trapezium"] = [fincol, Area, cX, cY] else: - shapes1['Quadrilateral'] = [fincol, Area, cX, cY] - elif (len(app) == 5): - shapes1['Pentagon'] = [fincol, Area, cX, cY] - elif (len(app) == 6): - shapes1['Hexagon'] = [fincol, Area, cX, cY] + shapes1["Quadrilateral"] = [fincol, Area, cX, cY] + elif len(app) == 5: + shapes1["Pentagon"] = [fincol, Area, cX, cY] + elif len(app) == 6: + shapes1["Hexagon"] = [fincol, Area, cX, cY] else: - shapes1['Circle'] = [fincol, Area, cX, cY] + shapes1["Circle"] = [fincol, Area, cX, cY] shapes.clear() @@ -125,51 +129,47 @@ def scan_image(img_file_path): return shapes -if __name__ == '__main__': +if __name__ == "__main__": total_sam = 1 - while(total_sam != 0 ): + while total_sam != 0: curr_dir_path = os.getcwd() - print('Currently working in '+ curr_dir_path) - - img_dir_path = curr_dir_path + '/Samples/' + print("Currently working in " + curr_dir_path) + img_dir_path = curr_dir_path + "/Samples/" file_num = total_sam - total_sam-=1 - img_file_path = img_dir_path + 'Sample' + str(file_num) + '.png' + total_sam -= 1 + img_file_path = img_dir_path + "Sample" + str(file_num) + ".png" - if os.path.exists('Samples/Sample' + str(file_num) + '.png'): - print('\nFound Sample' + str(file_num) + '.png') + if os.path.exists("Samples/Sample" + str(file_num) + ".png"): + print("\nFound Sample" + str(file_num) + ".png") else: - print('\n[ERROR] Sample' + str(file_num) + '.png not found. Make sure "Samples" folder has the selected file.') + print( + "\n[ERROR] Sample" + + str(file_num) + + '.png not found. Make sure "Samples" folder has the selected file.' + ) exit() - - try: shapes = scan_image(img_file_path) - print('*******************************') - - print('Total Shapes Found =' , len(shapes)) - - for i , j in shapes.items(): - print ( 'Shape Name:' , i ) - print('Color:', j[0]) - print('Area:', j[1]) - print('Location cX, cY:', j[2] , j[3]) - print('Color:', j[3]) - print('*******************************') - + print("*******************************") + print("Total Shapes Found =", len(shapes)) + for i, j in shapes.items(): + print("Shape Name:", i) + print("Color:", j[0]) + print("Area:", j[1]) + print("Location cX, cY:", j[2], j[3]) + print("Color:", j[3]) + print("*******************************") except Exception: - print('\n[ERROR] scan_image function is throwing an error.') + print("\n[ERROR] scan_image function is throwing an error.") exit() - - diff --git a/pomodoro_timer/pomodoro_timer.py b/pomodoro_timer/pomodoro_timer.py index f06fdc931..21afe5801 100644 --- a/pomodoro_timer/pomodoro_timer.py +++ b/pomodoro_timer/pomodoro_timer.py @@ -1,20 +1,21 @@ import ctypes +import os +import threading import time from tkinter import Button, Entry, Frame, Label, Tk from tkinter.constants import BOTTOM, FLAT, LEFT from tkinter.font import BOLD -import threading -import os try: import winsound + ctypes.windll.shcore.SetProcessDpiAwareness(True) except Exception: pass root = Tk() root.config(bg="Salmon") -root.geometry('600x500') +root.geometry("600x500") root.title("Pomodoro Timer") root.resizable(0, 0) @@ -28,8 +29,7 @@ def user_start(): custom_work = int(user_input_work.get()) custom_break = int(user_input_break.get()) start_timer_params = (custom_work, custom_break) - return threading.Thread( - target=start_timer, args=[start_timer_params]).start() + return threading.Thread(target=start_timer, args=[start_timer_params]).start() def today(): @@ -76,7 +76,7 @@ def start_timer(options, cycle_limit=5): winsound.Beep(323, 250) winsound.Beep(583, 250) except Exception: - os.system('tput bel') + os.system("tput bel") while temp_break: title_label.config(text="You should be taking a break now.") @@ -89,7 +89,7 @@ def start_timer(options, cycle_limit=5): winsound.Beep(523, 250) winsound.Beep(783, 250) except Exception: - os.system('tput bel') + os.system("tput bel") cycles += 1 reset() @@ -97,38 +97,43 @@ def start_timer(options, cycle_limit=5): # Title -title_label = Label(root, text="Focus...", - font=("MV Boli", 20, BOLD), - bg="Salmon") +title_label = Label(root, text="Focus...", font=("MV Boli", 20, BOLD), bg="Salmon") title_label.pack() # Cycle Number -cycle_label = Label(root, font=("Consolas", 20, BOLD), - bg="Salmon") +cycle_label = Label(root, font=("Consolas", 20, BOLD), bg="Salmon") # Pomodoro Timer -timer_label = Label(root, text="Timer here", - bg="black", fg="green", font=("Consolas", 32), - width=10) +timer_label = Label( + root, text="Timer here", bg="black", fg="green", font=("Consolas", 32), width=10 +) timer_label.pack(pady=20) # Pomodoro Cycle Button Options button_frame = Frame(root, bg="salmon") button_frame.pack(pady=10) -pom_one = Button(button_frame, text="25/5 Cycle", font="Helvetica 12", - height=1, width=12, - command=lambda: threading.Thread( - target=start_timer, args=[POMO_OPTIONS[0]] - ).start() - ) +pom_one = Button( + button_frame, + text="25/5 Cycle", + font="Helvetica 12", + height=1, + width=12, + command=lambda: threading.Thread( + target=start_timer, args=[POMO_OPTIONS[0]] + ).start(), +) pom_one.grid(row=0, column=0, padx=5) -pom_two = Button(button_frame, text="20/10 Cycle", font="Helvetica 12", - height=1, width=12, - command=lambda: threading.Thread( - target=start_timer, args=[POMO_OPTIONS[1]] - ).start() - ) +pom_two = Button( + button_frame, + text="20/10 Cycle", + font="Helvetica 12", + height=1, + width=12, + command=lambda: threading.Thread( + target=start_timer, args=[POMO_OPTIONS[1]] + ).start(), +) pom_two.grid(row=0, column=1) # User input time options @@ -136,49 +141,49 @@ def start_timer(options, cycle_limit=5): input_frame.pack(pady=20) custom_label = Label( - input_frame, text="Enter Custom work/break", bg="salmon", font="Serif 10") + input_frame, text="Enter Custom work/break", bg="salmon", font="Serif 10" +) custom_label.grid(row=0, column=0, columnspan=2) -input_label_work = Label(input_frame, text="Work (in mins)", - bg="salmon", font="Serif 10") -input_label_break = Label(input_frame, text="Break (in mins)", - bg="salmon", font="Serif 10") +input_label_work = Label( + input_frame, text="Work (in mins)", bg="salmon", font="Serif 10" +) +input_label_break = Label( + input_frame, text="Break (in mins)", bg="salmon", font="Serif 10" +) input_label_work.grid(row=2, column=0) input_label_break.grid(row=2, column=1) -user_input_work = Entry(input_frame, font=( - "Sans Serif", 12), relief=FLAT, width=10) -user_input_break = Entry(input_frame, font=( - "Sans Serif", 12), relief=FLAT, width=10) +user_input_work = Entry(input_frame, font=("Sans Serif", 12), relief=FLAT, width=10) +user_input_break = Entry(input_frame, font=("Sans Serif", 12), relief=FLAT, width=10) user_input_work.grid(row=1, column=0) user_input_break.grid(row=1, column=1, padx=10) -user_input_start = Button(input_frame, text="Start", - font=("Sans Serif", 8), - relief=FLAT, command=user_start) +user_input_start = Button( + input_frame, text="Start", font=("Sans Serif", 8), relief=FLAT, command=user_start +) user_input_start.grid(row=1, column=2) # Date time label -date_label = Label(root, text="Datetime:", - font=("Consolas", 14), bg="salmon") +date_label = Label(root, text="Datetime:", font=("Consolas", 14), bg="salmon") date_label.pack(side=BOTTOM) # Instruction Label instruction_label = Label( root, - text=''' + text=""" • Select the predefined pomodoro options • Or enter your own work/break timings • Work until the work timer ends • Take a break until break timer ends • This will go on for 4 cycles in total - ''', + """, font="Serif 12 bold", justify=LEFT, - bg="salmon" + bg="salmon", ) instruction_label.pack() diff --git a/ppt2pdf/ppt2pdf_linux.py b/ppt2pdf/ppt2pdf_linux.py index 27b8dde41..f4e07b9ad 100644 --- a/ppt2pdf/ppt2pdf_linux.py +++ b/ppt2pdf/ppt2pdf_linux.py @@ -1,12 +1,13 @@ # import libraries import glob -import tqdm import os +import tqdm + PATH = "INPUT FOLDER" # extension et = "pptx" # or ppt files = [f for f in glob.glob(PATH + "/**/*.{}".format(et), recursive=True)] for f in tqdm.tqdm(files): - command = "unoconv -f pdf \"{}\"".format(f) + command = 'unoconv -f pdf "{}"'.format(f) os.system(command) diff --git a/ppt2pdf/ppt2pdf_win.py b/ppt2pdf/ppt2pdf_win.py index 5dcc43693..db9b66f67 100644 --- a/ppt2pdf/ppt2pdf_win.py +++ b/ppt2pdf/ppt2pdf_win.py @@ -1,14 +1,14 @@ # Note that comtypes is only available for Windows. -from comtypes.client import CreateObject, Constants +from comtypes.client import Constants, CreateObject # Function PPTtoPDF def PPTtoPDF(inputFileName, outputFileName, formatType=2): - powerpoint = CreateObject('Powerpoint.Application') + powerpoint = CreateObject("Powerpoint.Application") constants = Constants(powerpoint) powerpoint.Visible = 1 - if outputFileName[-3:] != 'pdf': + if outputFileName[-3:] != "pdf": outputFileName = outputFileName + ".pdf" deck = powerpoint.Presentations.Open(inputFileName) deck.SaveAs(outputFileName, constants.PpSaveAsPDF) @@ -18,11 +18,11 @@ def PPTtoPDF(inputFileName, outputFileName, formatType=2): # Function PPTtoPDFNote def PPTtoPDFNote(inputFileName, outputFileName, formatType=32): - powerpoint = CreateObject('Powerpoint.Application') + powerpoint = CreateObject("Powerpoint.Application") constants = Constants(powerpoint) powerpoint.Visible = 1 - if outputFileName[-3:] != 'pdf': + if outputFileName[-3:] != "pdf": outputFileName = outputFileName + ".pdf" deck = powerpoint.Presentations.Open(inputFileName) deck.ExportAsFixedFormat( @@ -32,7 +32,7 @@ def PPTtoPDFNote(inputFileName, outputFileName, formatType=32): False, # No frame constants.ppPrintHandoutHorizontalFirst, constants.ppPrintOutputNotesPages, - constants.ppPrintAll + constants.ppPrintAll, ) deck.Close() powerpoint.Quit() diff --git a/ppt2video/convertor.py b/ppt2video/convertor.py index 4069ce4aa..70d1ae97b 100644 --- a/ppt2video/convertor.py +++ b/ppt2video/convertor.py @@ -1,7 +1,8 @@ -import win32com.client import os import sys +import win32com.client + # PpSaveAsFileType enumeration (PowerPoint) ppSaveAsMP4 = 39 # PpSlideLayout enumeration (PowerPoint) @@ -10,8 +11,7 @@ msoShapeRectangle = 1 -def ppt2video(pptx, video, timing, duration, - resolution, frames, quality, dict): +def ppt2video(pptx, video, timing, duration, resolution, frames, quality, dict): # Check if system requirements are met. if sys.platform == "win32": @@ -44,11 +44,10 @@ def ppt2video(pptx, video, timing, duration, if slide.SlideIndex in list: # Create new slide with new text len_new_ppt = len(new_presentation.Slides) - new_slide = new_presentation.Slides.Add(len_new_ppt + 1, - ppLayoutText) + new_slide = new_presentation.Slides.Add(len_new_ppt + 1, ppLayoutText) new_slide.Shapes.addShape( - msoShapeRectangle, 150, 150, 250, 250). \ - TextFrame.TextRange.Text = dict.get(str(slide.SlideIndex)) + msoShapeRectangle, 150, 150, 250, 250 + ).TextFrame.TextRange.Text = dict.get(str(slide.SlideIndex)) # Copying slide from original presentation and adding it new one. slide.Copy() len_new_ppt = len(new_presentation.Slides) @@ -61,13 +60,14 @@ def ppt2video(pptx, video, timing, duration, # Presentation.CreateVideo method (PowerPoint) # https://docs.microsoft.com/en-us/office/vba/api/powerpoint.presentation.createvideo - new_presentation.CreateVideo(video_path, timing, duration, - resolution, frames, quality) + new_presentation.CreateVideo( + video_path, timing, duration, resolution, frames, quality + ) while True: try: # Update the video file, if already exists. os.rename(video_path, video_path) - print(f'The video from {pptx} has been created.') + print(f"The video from {pptx} has been created.") break except Exception: pass @@ -77,7 +77,7 @@ def ppt2video(pptx, video, timing, duration, pass -if __name__ == '__main__': +if __name__ == "__main__": # e.g.:test.pptx, file expected to be in the root folder file_name = "" # e.g.: test_video, will be created in the root folder @@ -98,7 +98,13 @@ def ppt2video(pptx, video, timing, duration, # to leave without additional input. input_dict = {} - ppt2video(f"./{file_name}", f"./{video_name}.mp4", - UseTimingsAndNarrations, - DefaultSlideDuration, VertResolution, - FramesPerSecond, Quality, input_dict) + ppt2video( + f"./{file_name}", + f"./{video_name}.mp4", + UseTimingsAndNarrations, + DefaultSlideDuration, + VertResolution, + FramesPerSecond, + Quality, + input_dict, + ) diff --git a/prescription_generator/helper/pdf_operations.py b/prescription_generator/helper/pdf_operations.py index a195cfae9..48ca19c10 100644 --- a/prescription_generator/helper/pdf_operations.py +++ b/prescription_generator/helper/pdf_operations.py @@ -6,11 +6,11 @@ def footer(self): # Position at 1.5 cm from bottom self.set_y(-15) # Arial italic 8 - self.set_font('Arial', 'I', 8) + self.set_font("Arial", "I", 8) # Text color in gray self.set_text_color(128) # Page number - self.cell(0, 10, 'Page ' + str(self.page_no()), 0, 0, 'C') + self.cell(0, 10, "Page " + str(self.page_no()), 0, 0, "C") def save_pdf(medicines): @@ -21,37 +21,27 @@ def save_pdf(medicines): # setting style and size of font for the pdf pdf.set_font("Arial", size=12) - pdf.cell( - 200, 10, - txt="Generated Prscription", - ln=1, align='C' - ) + pdf.cell(200, 10, txt="Generated Prscription", ln=1, align="C") for medic in medicines: - if ('Medicine Name' in medicines[medic]): + if "Medicine Name" in medicines[medic]: # create a cell + pdf.cell(200, 10, ln=1, align="C", txt=medic) pdf.cell( - 200, 10, - ln=1, align='C', - txt=medic - ) - pdf.cell( - 200, 10, + 200, + 10, ln=2, txt="Medicine Name: " + medicines[medic]["Medicine Name"], ) if "Instruction" in medicines[medic]: pdf.cell( - 200, 10, + 200, + 10, ln=2, - txt="Instructions: " + medicines[medic]["Instruction"] + txt="Instructions: " + medicines[medic]["Instruction"], ) else: - pdf.cell( - 200, 10, - ln=2, - txt="Instructions*: No Instructions given" - ) + pdf.cell(200, 10, ln=2, txt="Instructions*: No Instructions given") # save the pdf with name .pdf pdf.output("Prescription.pdf") diff --git a/prescription_generator/helper/speech.py b/prescription_generator/helper/speech.py index 4b3c6f528..8355afdd4 100644 --- a/prescription_generator/helper/speech.py +++ b/prescription_generator/helper/speech.py @@ -3,6 +3,7 @@ def speech_rec_for_linux(): import espeak + espeak.init() speaker = espeak.Espeak() # import pyttsx3 @@ -14,7 +15,7 @@ def speech_rec_for_linux(): medicines = {} with sr.Microphone() as source: - while (True): + while True: medicine_dict = {} count += 1 @@ -31,11 +32,8 @@ def speech_rec_for_linux(): print("Done") try: - text = r.recognize_google( - recorded_audio, - language="en-US" - ) - if 'exit' in str(text).lower(): + text = r.recognize_google(recorded_audio, language="en-US") + if "exit" in str(text).lower(): print("Thanks for using our service!") break @@ -55,10 +53,7 @@ def speech_rec_for_linux(): print("Done") try: - text = r.recognize_google( - recorded_audio, - language="en-US" - ) + text = r.recognize_google(recorded_audio, language="en-US") medicine_dict["Instruction"] = str(text) print("Decoded Text : {}".format(text)) @@ -72,6 +67,7 @@ def speech_rec_for_linux(): def speech_rec_for_windows(): import pyttsx3 + speaker = pyttsx3.init() # from win32com.client import Dispatch # speak = Dispatch("SAPI.SpVoice").Speak @@ -82,7 +78,7 @@ def speech_rec_for_windows(): medicines = {} with sr.Microphone() as source: - while (True): + while True: medicine_dict = {} count += 1 @@ -99,11 +95,8 @@ def speech_rec_for_windows(): print("Done") try: - text = r.recognize_google( - recorded_audio, - language="en-US" - ) - if 'exit' in str(text).lower(): + text = r.recognize_google(recorded_audio, language="en-US") + if "exit" in str(text).lower(): print("Thanks for using our service!") break @@ -124,10 +117,7 @@ def speech_rec_for_windows(): print("Done") try: - text = r.recognize_google( - recorded_audio, - language="en-US" - ) + text = r.recognize_google(recorded_audio, language="en-US") medicine_dict["Instruction"] = str(text) print("Decoded Text : {}".format(text)) diff --git a/prescription_generator/main.py b/prescription_generator/main.py index 42935d66d..ff59cf965 100644 --- a/prescription_generator/main.py +++ b/prescription_generator/main.py @@ -1,18 +1,19 @@ import sys + from helper.pdf_operations import save_pdf -from helper.speech import speech_rec_for_windows, speech_rec_for_linux +from helper.speech import speech_rec_for_linux, speech_rec_for_windows def start_app(): - if sys.platform.startswith('linux'): + if sys.platform.startswith("linux"): medicines = speech_rec_for_linux() - elif sys.platform.startswith('win32'): + elif sys.platform.startswith("win32"): medicines = speech_rec_for_windows() print(medicines) save_pdf(medicines) -if __name__ == '__main__': +if __name__ == "__main__": start_app() diff --git a/price_tracker/priceTrackerScript.py b/price_tracker/priceTrackerScript.py index 801b8903c..8039e8a16 100644 --- a/price_tracker/priceTrackerScript.py +++ b/price_tracker/priceTrackerScript.py @@ -1,28 +1,29 @@ +import time +import unicodedata + import requests from bs4 import BeautifulSoup -import unicodedata -import time from send_email import send_email - -HEADERS = ({'User-Agent': - """Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like +HEADERS = { + "User-Agent": """Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36""", - 'Accept-Language': 'en-US, en;q=0.5'}) + "Accept-Language": "en-US, en;q=0.5", +} def get_product_info(url): page = requests.get(url, headers=HEADERS) soup = BeautifulSoup(page.content, features="html.parser") try: - title = soup.find(id='productTitle').get_text().strip() + title = soup.find(id="productTitle").get_text().strip() price_str = soup.find(id="priceblock_ourprice").get_text() except Exception as e: print(e) return None, None, None try: - soup.select('#availability .a-color-success')[0].get_text().strip() + soup.select("#availability .a-color-success")[0].get_text().strip() available = True except Exception as e: print(e) @@ -30,7 +31,7 @@ def get_product_info(url): try: price = unicodedata.normalize("NFKD", price_str) - price = price.replace(',', '').replace('₹', '') + price = price.replace(",", "").replace("₹", "") price = float(price) except Exception as e: @@ -42,32 +43,33 @@ def get_product_info(url): def createTuple(urls, limits): if len(urls) != len(limits): - print("""url list and limit list are not equal - --Make Sure you add "," after each url and limit""") + print( + """url list and limit list are not equal + --Make Sure you add "," after each url and limit""" + ) return [] return [(urls[i], limits[i]) for i in range(0, len(urls))] -if __name__ == '__main__': +if __name__ == "__main__": urls = [ # Add URL of Amazon Website here as shown below "url1", - "url2" + "url2", ] limits = [ # Add crossponding limit to which you want to get email # like you want get email when price below 100 so put 100 in the limit "limit1", - "limit2" + "limit2", ] products = createTuple(urls, limits) while True: - if (len(products) == 0): + if len(products) == 0: break - print('Number of products left whose price is Not Dropped yet', - len(products)) - print('checking...') + print("Number of products left whose price is Not Dropped yet", len(products)) + print("checking...") time.sleep(10) products_below_limit = [] for product_url, limit in products: @@ -84,6 +86,6 @@ def createTuple(urls, limits): message += f"{url}\n\n" foundData.append((url, limit)) - if (send_email(message)): + if send_email(message): for found in foundData: products.remove(found) diff --git a/price_tracker/send_email.py b/price_tracker/send_email.py index 5b760cf44..b301f2da9 100644 --- a/price_tracker/send_email.py +++ b/price_tracker/send_email.py @@ -1,4 +1,3 @@ - import smtplib import ssl @@ -18,7 +17,7 @@ def send_email(message): try: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message) - print('email sent!') + print("email sent!") return True except Exception as e: print(e) diff --git a/product_availability/product_availability.py b/product_availability/product_availability.py index 66b5d48a3..2124ee9c1 100644 --- a/product_availability/product_availability.py +++ b/product_availability/product_availability.py @@ -1,24 +1,26 @@ +import time + import requests from bs4 import BeautifulSoup -import time from send_email import send_email -HEADERS = ({'User-Agent': - """Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36""", - 'Accept-Language': 'en-US, en;q=0.5'}) +HEADERS = { + "User-Agent": """Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36""", + "Accept-Language": "en-US, en;q=0.5", +} def product_info(url): page = requests.get(url, headers=HEADERS) soup = BeautifulSoup(page.content, features="html.parser") try: - title = soup.find(id='productTitle').get_text().strip() + title = soup.find(id="productTitle").get_text().strip() except Exception as e: print(e) return None, None try: - soup.select('#availability .a-color-success')[0].get_text().strip() + soup.select("#availability .a-color-success")[0].get_text().strip() available = True except Exception as e: print(e) @@ -27,11 +29,11 @@ def product_info(url): return title, available -if __name__ == '__main__': +if __name__ == "__main__": url = "" while True: - print('checking...') + print("checking...") time.sleep(1) title, available = product_info(url) print(title, available) @@ -40,7 +42,7 @@ def product_info(url): text += "Your tracked products are Available Now!\n\n" text += f"{title}\n" text += f"{url}\n\n" - if (send_email(text)): + if send_email(text): break else: print("Not Available") diff --git a/product_availability/send_email.py b/product_availability/send_email.py index 7cb541799..40d34482b 100644 --- a/product_availability/send_email.py +++ b/product_availability/send_email.py @@ -13,7 +13,7 @@ def send_email(message): try: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message) - print('sent!!!') + print("sent!!!") return True except Exception as e: print(e) diff --git a/profanity_filter/filter.py b/profanity_filter/filter.py index eb8e59287..c038e4a3e 100644 --- a/profanity_filter/filter.py +++ b/profanity_filter/filter.py @@ -1,11 +1,12 @@ -from better_profanity import profanity import argparse +from better_profanity import profanity + # the main function def main(args: argparse.Namespace) -> None: # this will store the passed content - content = '' + content = "" # if text is passed then read that if args.text is not None: @@ -17,7 +18,7 @@ def main(args: argparse.Namespace) -> None: content += data except FileNotFoundError: # if file not found # \033[91m specifies the red color - print('\033[91mERROR: file not found\033[0m') + print("\033[91mERROR: file not found\033[0m") exit(0) # exit the program # censor the content @@ -25,22 +26,22 @@ def main(args: argparse.Namespace) -> None: # writing censored data to a file if asked if args.output is not None: - with open(args.output, 'w') as f: + with open(args.output, "w") as f: f.write(censored) # informing the user - print(f'\033[92m[+] Censored data written to {args.output}\033[0m') + print(f"\033[92m[+] Censored data written to {args.output}\033[0m") # printing the content to the console print() - print('\033[1mCENSORED DATA\033[0m') + print("\033[1mCENSORED DATA\033[0m") print() print(censored) # if -f is passed then write the censored data back to the original file -if __name__ == '__main__': +if __name__ == "__main__": # argparse obj parser = argparse.ArgumentParser() @@ -50,27 +51,16 @@ def main(args: argparse.Namespace) -> None: # adding arguments to the group # argument for text input_grp.add_argument( - '-t', '--text', - type=str, - metavar='', - help='Specify the string to censor' + "-t", "--text", type=str, metavar="", help="Specify the string to censor" ) # argument for file input_grp.add_argument( - '-f', '--file', - type=str, - metavar='', - help='Specify the file to censor' + "-f", "--file", type=str, metavar="", help="Specify the file to censor" ) # argument for output file - parser.add_argument( - '-o', - '--output', - metavar='', - help='Specify an output file' - ) + parser.add_argument("-o", "--output", metavar="", help="Specify an output file") # parsing the args args = parser.parse_args() diff --git a/programming_quoter/programming_quoter.py b/programming_quoter/programming_quoter.py index c7d05c069..e5b17329c 100644 --- a/programming_quoter/programming_quoter.py +++ b/programming_quoter/programming_quoter.py @@ -1,45 +1,32 @@ -from win10toast import ToastNotifier import random -listOfQuotes = ['First, solve the problem. ' - 'Then, write the code', - 'Experience is the name everyone ' - 'gives to their mistakes', - 'In order to be irreplaceable, ' - 'one must always be different', - 'Java is to JavaScript ' - 'what car is to Carpet', - 'Knowledge is power', - 'Ruby is rubbish! PHP ' - 'is phpantastic!', - 'Code is like humor.' - ' When you have to explain it, it’s bad', - 'Fix the cause, ' - 'not the symptom', - 'Simplicity is the ' - 'soul of efficiency', - 'Before software can be ' - 'reusable it first has to be usable', - 'Make it work, make ' - 'it right, make it fast', - 'Truth can only be found ' - 'in one place: the code', - 'How you look at it is pretty ' - 'much how youll see it', - 'Perl – The only language that ' - 'looks the same before and after RSA encryption', - 'A conscious human is driven by ' - 'their conscience, not popular opinion', - 'The most important property of a ' - 'program is whether it accomplishes ' - 'the intention of its user', - 'Computers are useless. They ' - 'can only give you answers', - 'Hardware: The parts of a ' - 'computer system that can be kicked'] +from win10toast import ToastNotifier + +listOfQuotes = [ + "First, solve the problem. " "Then, write the code", + "Experience is the name everyone " "gives to their mistakes", + "In order to be irreplaceable, " "one must always be different", + "Java is to JavaScript " "what car is to Carpet", + "Knowledge is power", + "Ruby is rubbish! PHP " "is phpantastic!", + "Code is like humor." " When you have to explain it, it’s bad", + "Fix the cause, " "not the symptom", + "Simplicity is the " "soul of efficiency", + "Before software can be " "reusable it first has to be usable", + "Make it work, make " "it right, make it fast", + "Truth can only be found " "in one place: the code", + "How you look at it is pretty " "much how youll see it", + "Perl – The only language that " "looks the same before and after RSA encryption", + "A conscious human is driven by " "their conscience, not popular opinion", + "The most important property of a " + "program is whether it accomplishes " + "the intention of its user", + "Computers are useless. They " "can only give you answers", + "Hardware: The parts of a " "computer system that can be kicked", +] toaster = ToastNotifier() -toaster.show_toast("Programming Quote", random.choice(listOfQuotes), - icon_path=None, - duration=10) +toaster.show_toast( + "Programming Quote", random.choice(listOfQuotes), icon_path=None, duration=10 +) diff --git a/pylinter/run-mccabe.py b/pylinter/run-mccabe.py index 2c740e3fc..ad17d3f12 100644 --- a/pylinter/run-mccabe.py +++ b/pylinter/run-mccabe.py @@ -1,6 +1,8 @@ import ast import sys + import mccabe + from .utils import collect_sources @@ -12,8 +14,9 @@ def process(py_source, max_complexity): for graph in visitor.graphs.values(): if graph.complexity() > max_complexity: text = "{}:{}:{} {} {}" - return text.format(py_source, graph.lineno, graph.column, graph.entity, - graph.complexity()) + return text.format( + py_source, graph.lineno, graph.column, graph.entity, graph.complexity() + ) def main(): diff --git a/pylinter/run-pyflakes.py b/pylinter/run-pyflakes.py index 3c64f0567..c50b7f0aa 100644 --- a/pylinter/run-pyflakes.py +++ b/pylinter/run-pyflakes.py @@ -1,15 +1,15 @@ -import sys import subprocess +import sys from .utils import collect_sources def ignore(p): - """ Ignore hidden and test files """ + """Ignore hidden and test files""" parts = p.splitall() if any(x.startswith(".") for x in parts): return True - if 'test' in parts: + if "test" in parts: return True return False diff --git a/python_package_installer/AlPythonPackageInstaller.py b/python_package_installer/AlPythonPackageInstaller.py index 185b4a613..285bb29ae 100644 --- a/python_package_installer/AlPythonPackageInstaller.py +++ b/python_package_installer/AlPythonPackageInstaller.py @@ -1,24 +1,25 @@ +import os import subprocess -from tkinter import Tk, END, Frame, SUNKEN, Button, X, Text -from tkinter import font, Label, Entry, BOTH +from tkinter import (BOTH, END, SUNKEN, Button, Entry, Frame, Label, Text, Tk, + X, font) + import pyttsx3 -from PIL import ImageTk, Image -import os +from PIL import Image, ImageTk cwd = os.path.dirname(os.path.realpath(__file__)) -class AlPythonPackageInstaller(): - +class AlPythonPackageInstaller: def __init__(self): root = Tk(className=" ALPYTHONPACKAGEINSTALLER ") root.geometry("400x200+1500+815") root.resizable(0, 0) - root.iconbitmap(os.path.join(cwd + '\\UI\\icons', - 'alpythonpackageinstaller.ico')) + root.iconbitmap( + os.path.join(cwd + "\\UI\\icons", "alpythonpackageinstaller.ico") + ) root.config(bg="#0d4b98") root.overrideredirect(1) - color = '#0d4b98' + color = "#0d4b98" def callback(event): root.geometry("500x750+1410+300") @@ -35,60 +36,81 @@ def hideScreen(): root.iconify() def speak(audio): - engine = pyttsx3.init('sapi5') - voices = engine.getProperty('voices') - engine.setProperty('voice', voices[0].id) + engine = pyttsx3.init("sapi5") + voices = engine.getProperty("voices") + engine.setProperty("voice", voices[0].id) engine.say(audio) engine.runAndWait() def install(): text.delete(1.0, END) package = pythonPackage.get() - check = subprocess.getoutput('pip install ' + package) - if '==' in package: - package = package.split('==')[0] - alreadyInstalled = 'Requirement already satisfied: ' + package - nowInstalled = 'Successfully installed ' + package - errorInstalling = 'ERROR: Could not find a version that satisfies'\ - 'the requirement ' + package - someError = 'ERROR: ' - var = check.split('\n') + check = subprocess.getoutput("pip install " + package) + if "==" in package: + package = package.split("==")[0] + alreadyInstalled = "Requirement already satisfied: " + package + nowInstalled = "Successfully installed " + package + errorInstalling = ( + "ERROR: Could not find a version that satisfies" + "the requirement " + package + ) + someError = "ERROR: " + var = check.split("\n") if nowInstalled in var[-1]: text.insert(1.0, var[-1]) - speak('Successfully installed ' + package) + speak("Successfully installed " + package) elif len(var) >= 3 and nowInstalled in var[-3]: text.insert(1.0, var[-3]) - speak('Successfully installed ' + package) + speak("Successfully installed " + package) elif alreadyInstalled in var[0]: text.insert(1.0, var[0]) - speak(package + 'already installed') + speak(package + "already installed") elif errorInstalling in check or someError in check: text.insert(1.0, check) - speak('Error installing ' + package) + speak("Error installing " + package) - textHighlightFont = font.Font(family='OnePlus Sans Display', size=12) - appHighlightFont = font.Font(family='OnePlus Sans Display', size=12, - weight='bold') + textHighlightFont = font.Font(family="OnePlus Sans Display", size=12) + appHighlightFont = font.Font( + family="OnePlus Sans Display", size=12, weight="bold" + ) - titleBar = Frame(root, bg='#141414', relief=SUNKEN, bd=0) - icon = Image.open(os.path.join(cwd + '\\UI\\icons', - 'alpythonpackageinstaller.ico')) + titleBar = Frame(root, bg="#141414", relief=SUNKEN, bd=0) + icon = Image.open( + os.path.join(cwd + "\\UI\\icons", "alpythonpackageinstaller.ico") + ) icon = icon.resize((30, 30), Image.ANTIALIAS) icon = ImageTk.PhotoImage(icon) iconLabel = Label(titleBar, image=icon) iconLabel.photo = icon - iconLabel.config(bg='#141414') + iconLabel.config(bg="#141414") iconLabel.grid(row=0, column=0, sticky="nsew") - titleLabel = Label(titleBar, text='ALPYTHONPACKAGEINSTALLER', - fg='#909090', bg='#141414', font=appHighlightFont) + titleLabel = Label( + titleBar, + text="ALPYTHONPACKAGEINSTALLER", + fg="#909090", + bg="#141414", + font=appHighlightFont, + ) titleLabel.grid(row=0, column=1, sticky="nsew") - closeButton = Button(titleBar, text="x", bg='#141414', fg="#909090", - borderwidth=0, command=root.destroy, - font=appHighlightFont) + closeButton = Button( + titleBar, + text="x", + bg="#141414", + fg="#909090", + borderwidth=0, + command=root.destroy, + font=appHighlightFont, + ) closeButton.grid(row=0, column=3, sticky="nsew") - minimizeButton = Button(titleBar, text="-", bg='#141414', fg="#909090", - borderwidth=0, command=hideScreen, - font=appHighlightFont) + minimizeButton = Button( + titleBar, + text="-", + bg="#141414", + fg="#909090", + borderwidth=0, + command=hideScreen, + font=appHighlightFont, + ) minimizeButton.grid(row=0, column=2, sticky="nsew") titleBar.grid_columnconfigure(0, weight=1) titleBar.grid_columnconfigure(1, weight=75) @@ -99,22 +121,34 @@ def install(): pythonPackage = Label(root, text="PACKAGE NAME") pythonPackage.pack() pythonPackage.config(bg=color, fg="#fcf2f0", font=textHighlightFont) - pythonPackage = Entry(root, bg="#ffdf14", fg='#0e3b74', - highlightbackground=color, highlightcolor=color, - highlightthickness=3, bd=0, - font=appHighlightFont) + pythonPackage = Entry( + root, + bg="#ffdf14", + fg="#0e3b74", + highlightbackground=color, + highlightcolor=color, + highlightthickness=3, + bd=0, + font=appHighlightFont, + ) pythonPackage.pack(fill=X) - install = Button(root, borderwidth=0, highlightthickness=3, - text="INSTALL", command=install) + install = Button( + root, borderwidth=0, highlightthickness=3, text="INSTALL", command=install + ) install.config(bg=color, fg="#fcf2f0", font=textHighlightFont) install.pack(fill=X) - text = Text(root, font="sans-serif", relief=SUNKEN, - highlightbackground=color, highlightcolor=color, - highlightthickness=5, bd=0) - text.config(bg="#ffdf14", fg='#0e3b74', height=2, - font=appHighlightFont) + text = Text( + root, + font="sans-serif", + relief=SUNKEN, + highlightbackground=color, + highlightcolor=color, + highlightthickness=5, + bd=0, + ) + text.config(bg="#ffdf14", fg="#0e3b74", height=2, font=appHighlightFont) text.pack(fill=BOTH, expand=True) titleBar.bind("", callback) diff --git a/qrcode_generator/googleSourceCode_YT.py b/qrcode_generator/googleSourceCode_YT.py index 4d8a45f25..f4939c640 100644 --- a/qrcode_generator/googleSourceCode_YT.py +++ b/qrcode_generator/googleSourceCode_YT.py @@ -1,13 +1,14 @@ -import pickle +import datetime import os +import pickle + +from google.auth.transport.requests import Request from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build -from google.auth.transport.requests import Request -import datetime def Create_Service(client_secret_file, api_name, api_version, *scopes): - print(client_secret_file, api_name, api_version, scopes, sep='-') + print(client_secret_file, api_name, api_version, scopes, sep="-") CLIENT_SECRET_FILE = client_secret_file API_SERVICE_NAME = api_name API_VERSION = api_version @@ -16,11 +17,11 @@ def Create_Service(client_secret_file, api_name, api_version, *scopes): cred = None - pickle_file = f'token_{API_SERVICE_NAME}_{API_VERSION}.pickle' + pickle_file = f"token_{API_SERVICE_NAME}_{API_VERSION}.pickle" # print(pickle_file) if os.path.exists(pickle_file): - with open(pickle_file, 'rb') as token: + with open(pickle_file, "rb") as token: cred = pickle.load(token) if not cred or not cred.valid: @@ -30,19 +31,19 @@ def Create_Service(client_secret_file, api_name, api_version, *scopes): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRET_FILE, SCOPES) cred = flow.run_local_server() - with open(pickle_file, 'wb') as token: + with open(pickle_file, "wb") as token: pickle.dump(cred, token) try: service = build(API_SERVICE_NAME, API_VERSION, credentials=cred) - print(API_SERVICE_NAME, 'service created successfully') + print(API_SERVICE_NAME, "service created successfully") return service except Exception as e: - print('Unable to connect.') + print("Unable to connect.") print(e) return None def convert_to_RFC_datetime(year=1900, month=1, day=1, hour=0, minute=0): - dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + 'Z' + dt = datetime.datetime(year, month, day, hour, minute, 0).isoformat() + "Z" return dt diff --git a/qrcode_generator/qr_generator.py b/qrcode_generator/qr_generator.py index df819ec28..3e61a4ead 100644 --- a/qrcode_generator/qr_generator.py +++ b/qrcode_generator/qr_generator.py @@ -1,29 +1,29 @@ # from re import sub +import os +import time import tkinter -from tkinter import Tk, Label, StringVar, PhotoImage, HORIZONTAL # from tkinter.ttk import * import tkinter.ttk -from tkinter.ttk import Progressbar, Button -from tkinter import filedialog -import time +from tkinter import HORIZONTAL, Label, PhotoImage, StringVar, Tk, filedialog +from tkinter.ttk import Button, Progressbar + # from oauthlib.oauth2.rfc6749.clients.base import BODY import qrcode +from googleapiclient.http import MediaFileUpload # from qrcode.constants import ERROR_CORRECT_H from googleSourceCode_YT import Create_Service -from googleapiclient.http import MediaFileUpload -import os # Create variables to store information which are passed to function required to create Google Drive API instance -CLIENT_SECRET_FILE = 'OAuth_Client.json' -API_NAME = 'drive' -API_VERSION = 'v3' -SCOPES = ['https://www.googleapis.com/auth/drive'] +CLIENT_SECRET_FILE = "OAuth_Client.json" +API_NAME = "drive" +API_VERSION = "v3" +SCOPES = ["https://www.googleapis.com/auth/drive"] service = Create_Service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES) # initialize GUI and set window size root = Tk() -root.title('QR Code Generator!') +root.title("QR Code Generator!") root.geometry("600x400") root.configure(background="#F6E5FE") @@ -43,7 +43,9 @@ def clear(): # To retrieve text from entry widget, set to instance of StringVar class entered_text = StringVar() -text_intro = Label(main, text="Convert anything to a QR Code! Select what you want to convert:") +text_intro = Label( + main, text="Convert anything to a QR Code! Select what you want to convert:" +) text_intro.grid(row=0, column=0, columnspan=4, padx=10, pady=10) @@ -51,53 +53,52 @@ def clear(): def openFE(): global my_image root.filename = filedialog.askopenfilename( - initialdir='/home', + initialdir="/home", title="Select file", filetypes=( - ('PDF files', "*.pdf"), + ("PDF files", "*.pdf"), ("png files", "*.png"), - ("all files", "*.*") - ) + ("all files", "*.*"), + ), ) # Uploading file to drive head, tail = os.path.split(root.filename) file_names = [str(tail)] - mime_types = ['application/pdf', 'application/vnd.ms-powerpoint', 'image/png', 'image/jpeg', 'application/msword'] + mime_types = [ + "application/pdf", + "application/vnd.ms-powerpoint", + "image/png", + "image/jpeg", + "application/msword", + ] for file_name, mime_type in zip(file_names, mime_types): file_metadata = { - 'name': file_name, + "name": file_name, } - file_path = head + '/{0}' + file_path = head + "/{0}" media = MediaFileUpload(file_path.format(file_name), mimetype=mime_type) - extract_filedata = service.files().create( - body=file_metadata, - media_body=media, - fields='id' - ).execute() + extract_filedata = ( + service.files() + .create(body=file_metadata, media_body=media, fields="id") + .execute() + ) - file_id = extract_filedata.get('id') + file_id = extract_filedata.get("id") uploadFiles() - request_body = { - 'role': 'reader', - 'type': 'anyone' - } + request_body = {"role": "reader", "type": "anyone"} - service.permissions().create( - fileId=file_id, - body=request_body - ).execute() + service.permissions().create(fileId=file_id, body=request_body).execute() - response_share_link = service.files().get( - fileId=file_id, - fields='webViewLink' - ).execute() + response_share_link = ( + service.files().get(fileId=file_id, fields="webViewLink").execute() + ) - submit(response_share_link['webViewLink']) + submit(response_share_link["webViewLink"]) my_btn = Button(main, text="Files", command=openFE).grid(row=3, pady=10) @@ -109,7 +110,7 @@ def submit(anythingElse): version=1, error_correction=qrcode.constants.ERROR_CORRECT_H, box_size=6, - border=4 + border=4, ) qr.add_data(anythingElse) @@ -118,36 +119,49 @@ def submit(anythingElse): img.save("text_QR.png") photo = PhotoImage(file="text_QR.png") label = Label(main, image=photo) - label.photo = photo # referencing + label.photo = photo # referencing label.grid(row=6, column=1, columnspan=2, pady=10) # Creating Text entry fields def textbox(): - Label(main, text="Enter your text: ").grid(row=0, column=0, columnspan=4, padx=10, pady=10) - entryfield = tkinter.Entry(main, textvariable=entered_text, width=50, borderwidth=5, bg="#FEFFE2") + Label(main, text="Enter your text: ").grid( + row=0, column=0, columnspan=4, padx=10, pady=10 + ) + entryfield = tkinter.Entry( + main, textvariable=entered_text, width=50, borderwidth=5, bg="#FEFFE2" + ) entryfield.grid(row=4, column=1, pady=20) - Button(main, text="Submit", command=lambda: [submit(entered_text.get())]).grid(row=5, column=2, columnspan=4) + Button(main, text="Submit", command=lambda: [submit(entered_text.get())]).grid( + row=5, column=2, columnspan=4 + ) my_btn2 = Button(main, text="Text", command=lambda: [clear(), textbox()]) -my_btn2.grid(row=3, column=1,) +my_btn2.grid( + row=3, + column=1, +) # Progress bar for file upload def uploadFiles(): - progbar = Progressbar(main, orient=HORIZONTAL, length=200, mode='determinate') + progbar = Progressbar(main, orient=HORIZONTAL, length=200, mode="determinate") progbar.grid(row=5, columnspan=3, pady=10) for i in range(50): - if progbar['value'] == 66 or progbar['value'] == 90: + if progbar["value"] == 66 or progbar["value"] == 90: time.sleep(0.5) root.update_idletasks() - progbar['value'] += 2 + progbar["value"] += 2 time.sleep(0.02) progbar.destroy() - tkinter.Label(main, text='Upload Successful!', fg='green').grid(row=5, columnspan=3, pady=10) + tkinter.Label(main, text="Upload Successful!", fg="green").grid( + row=5, columnspan=3, pady=10 + ) -my_btn3 = Button(main, text="URL", command=lambda: [clear(), textbox()]).grid(row=3, column=2) +my_btn3 = Button(main, text="URL", command=lambda: [clear(), textbox()]).grid( + row=3, column=2 +) root.mainloop() diff --git a/qrcode_scanner/scanner.py b/qrcode_scanner/scanner.py index 30ef6633d..5ba181581 100644 --- a/qrcode_scanner/scanner.py +++ b/qrcode_scanner/scanner.py @@ -1,24 +1,21 @@ -from pyzbar.pyzbar import decode -from PIL import ImageTk -from tkinter import tk -import PIL.Image -from tkinter import filedialog import tkinter.font as tkFont +from tkinter import filedialog, tk + +import PIL.Image +from PIL import ImageTk +from pyzbar.pyzbar import decode root = tk.Tk() -root.title('QR CODE SCANNER') +root.title("QR CODE SCANNER") root.geometry("600x400") def open(): global my_image root.filename = filedialog.askopenfilename( - initialdir='/home', + initialdir="/home", title="Select file", - filetypes=( - ("png files", "*.png"), - ("all files", "*.*") - ) + filetypes=(("png files", "*.png"), ("all files", "*.*")), ) tk.Label(root, text=root.filename).pack() my_image = ImageTk.PhotoImage(PIL.Image.open(root.filename)) diff --git a/quick_painter/main.py b/quick_painter/main.py index d745a522b..779f8700d 100644 --- a/quick_painter/main.py +++ b/quick_painter/main.py @@ -1,6 +1,5 @@ -from tkinter import Tk, Button, Canvas -from tkinter import colorchooser -from tkinter import filedialog +from tkinter import Button, Canvas, Tk, colorchooser, filedialog + from PIL import Image, ImageDraw width = 1280 @@ -55,7 +54,9 @@ def ButtonClear(): def cursor(event): global cursor_ if cursor_ not in canvas.find_all(): - cursor_ = canvas.create_oval(event.x - 10, event.y - 10, event.x + 10, event.y + 10, width=0, fill='cyan') + cursor_ = canvas.create_oval( + event.x - 10, event.y - 10, event.x + 10, event.y + 10, width=0, fill="cyan" + ) canvas.coords(cursor_, event.x - 10, event.y - 10, event.x + 10, event.y + 10) canvas.update_idletasks() @@ -66,7 +67,9 @@ def paint(event): x1, y1 = (event.x - 10), (event.y - 10) x2, y2 = (event.x + 10), (event.y + 10) canvas.create_oval(x1, y1, x2, y2, width=0, fill=color) - draw.ellipse([(event.x - 10, event.y - 10), (event.x + 10, event.y + 10)], fill=color) + draw.ellipse( + [(event.x - 10, event.y - 10), (event.x + 10, event.y + 10)], fill=color + ) canvas.update_idletasks() @@ -75,7 +78,7 @@ def erase(event): item = canvas.find_closest(event.x, event.y) coords = canvas.coords(item) - if (abs(event.x - (coords[0] + 10)) < 35 and abs(event.y - (coords[1] + 10)) < 35): + if abs(event.x - (coords[0] + 10)) < 35 and abs(event.y - (coords[1] + 10)) < 35: canvas.delete(item) draw.ellipse([(coords[0], coords[1]), (coords[2], coords[3])], fill=background) diff --git a/random_email_generator/main.py b/random_email_generator/main.py index f6d073d03..39139e998 100644 --- a/random_email_generator/main.py +++ b/random_email_generator/main.py @@ -1,8 +1,9 @@ import random import string + import progressbar -''' Ask user for total number of emails required''' +""" Ask user for total number of emails required""" def getcount(): @@ -15,21 +16,30 @@ def getcount(): return getcount() -'''Below function creates a random length of email +"""Below function creates a random length of email between 1-20 characters length and adds domain and extension to give the resulting -email''' +email""" def make_email(): - extensions = ['com', 'net', 'org', 'gov'] - domains = ['gmail', 'yahoo', 'comcast', 'verizon', 'charter', - 'hotmail', 'outlook', 'frontier'] + extensions = ["com", "net", "org", "gov"] + domains = [ + "gmail", + "yahoo", + "comcast", + "verizon", + "charter", + "hotmail", + "outlook", + "frontier", + ] finalext = extensions[random.randint(0, len(extensions) - 1)] finaldom = domains[random.randint(0, len(domains) - 1)] accountlen = random.randint(1, 20) - finalacc = ''.join(random.choice(string.ascii_lowercase + string.digits) - for _ in range(accountlen)) + finalacc = "".join( + random.choice(string.ascii_lowercase + string.digits) for _ in range(accountlen) + ) finale = finalacc + "@" + finaldom + "." + finalext return finale diff --git a/random_wallpaper/random_wallpaper.py b/random_wallpaper/random_wallpaper.py index d5b788654..50577e90d 100644 --- a/random_wallpaper/random_wallpaper.py +++ b/random_wallpaper/random_wallpaper.py @@ -1,6 +1,6 @@ import ctypes -import random import os +import random PATH = "C:\\Users\\your\\path\\to\\wallpaper" SPI_SETDESKWALLPAPER = 20 # 0x0014 @@ -11,8 +11,5 @@ new_wallpaper = PATH + "\\" + pic ctypes.windll.user32.SystemParametersInfoW( - SPI_SETDESKWALLPAPER, - 0, - new_wallpaper, - SPIF_SENDCHANGE + SPI_SETDESKWALLPAPER, 0, new_wallpaper, SPIF_SENDCHANGE ) diff --git a/raspberry_pi_locator/main.py b/raspberry_pi_locator/main.py index cbccca542..ec923bc64 100644 --- a/raspberry_pi_locator/main.py +++ b/raspberry_pi_locator/main.py @@ -71,9 +71,7 @@ def scrape_chicago_electronics(): def scrape_okdo(): - urls = { - "2gb": "https://www.okdo.com/us/p/raspberry-pi-4-model-b-2gb-2/" - } + urls = {"2gb": "https://www.okdo.com/us/p/raspberry-pi-4-model-b-2gb-2/"} print("--- OKdo ---") for ram_size, url in urls.items(): response = requests.get(url) diff --git a/retweet_bot/keys.py b/retweet_bot/keys.py index 6c736e908..1ec0af7e8 100644 --- a/retweet_bot/keys.py +++ b/retweet_bot/keys.py @@ -1,6 +1,6 @@ # Twitter application consumer keys and access tokens. # Remember, keep this information private. -consumer_key = '' -consumer_secret = '' -access_token = '' -access_token_secret = '' +consumer_key = "" +consumer_secret = "" +access_token = "" +access_token_secret = "" diff --git a/retweet_bot/retweet_bot.py b/retweet_bot/retweet_bot.py index 90ad19f07..4c0d73998 100644 --- a/retweet_bot/retweet_bot.py +++ b/retweet_bot/retweet_bot.py @@ -1,10 +1,9 @@ -import tweepy from time import sleep + +import tweepy # Import your keys from keys.py present in the same folder -from keys import consumer_key -from keys import consumer_secret -from keys import access_token -from keys import access_token_secret +from keys import (access_token, access_token_secret, consumer_key, + consumer_secret) def retweet(hashtag, retweetNum): @@ -16,15 +15,15 @@ def retweet(hashtag, retweetNum): # Input number of retweets during main function call for tweet in tweepy.Cursor(api.search, q=hashtag).items(retweetNum): try: - print('\nTweet found by @' + tweet.user.screen_name) - print('Attempting to retweet') + print("\nTweet found by @" + tweet.user.screen_name) + print("Attempting to retweet") tweet.retweet() - print('Retweet published successfully.') + print("Retweet published successfully.") # Change time for sleep accordingly. sleep(10) # Reasons why your retweet failed except tweepy.TweepError as error: - print('\nError. Retweet not successful. Reason: ') + print("\nError. Retweet not successful. Reason: ") print(error.reason) except StopIteration: break @@ -33,12 +32,12 @@ def retweet(hashtag, retweetNum): def main(): print("Tell me a hashtag to retweet: ") hashtag = input() - hashtag = '#' + hashtag + hashtag = "#" + hashtag print("Tell me how many times do I retweet: ") retweetNum = int(input()) print("Retweet process started") retweet(hashtag, retweetNum) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/rpyaudio_recorder/non_blocking_audio_recorder.py b/rpyaudio_recorder/non_blocking_audio_recorder.py index 0cf11c0c6..ba92a9a61 100644 --- a/rpyaudio_recorder/non_blocking_audio_recorder.py +++ b/rpyaudio_recorder/non_blocking_audio_recorder.py @@ -1,11 +1,12 @@ -from recorder import Recorder # custom recorder script -from gpiozero import Button # for button interface -from datetime import datetime -import signal # Using this library to catch keyboard interrupts import os +import signal # Using this library to catch keyboard interrupts import sys +from datetime import datetime + +from gpiozero import Button # for button interface +from recorder import Recorder # custom recorder script -ROOT_PATH = os.path.realpath(os.path.join(__file__, '..')) +ROOT_PATH = os.path.realpath(os.path.join(__file__, "..")) def signal_handler(signal, frame): @@ -16,7 +17,7 @@ def signal_handler(signal, frame): signal.signal(signal.SIGINT, signal_handler) -class ButtonRecorder(): +class ButtonRecorder: def __init__(self): """ Initialize button and recorder @@ -72,7 +73,7 @@ def startRecording(self, name): print("In recordTag") self.button.when_released = self.released print("Saving with timestamp audio recording to loaction : {}".format(name)) - self.recfile = self.recorderHandler.open(name, 'wb') + self.recfile = self.recorderHandler.open(name, "wb") self.recfile.start_recording() print("Recording Started") diff --git a/rpyaudio_recorder/recorder.py b/rpyaudio_recorder/recorder.py index f1110caf5..5afdcb6f7 100644 --- a/rpyaudio_recorder/recorder.py +++ b/rpyaudio_recorder/recorder.py @@ -1,5 +1,5 @@ # -*- coding: utf-8 -*- -'''recorder.py +"""recorder.py Provides WAV recording functionality via two approaches: Blocking mode (record for a set duration): >>> rec = Recorder(channels=2) @@ -11,30 +11,31 @@ ... recfile2.start_recording() ... time.sleep(5.0) ... recfile2.stop_recording() -''' +""" -import pyaudio import wave +import pyaudio + class Recorder(object): - '''A recorder class for recording audio to a WAV file. + """A recorder class for recording audio to a WAV file. Records in mono by default. - ''' + """ def __init__(self, channels=1, rate=16000, frames_per_buffer=1024 * 4): self.channels = channels self.rate = rate self.frames_per_buffer = frames_per_buffer - def open(self, fname, mode='wb'): - return RecordingFile(fname, mode, self.channels, self.rate, - self.frames_per_buffer) + def open(self, fname, mode="wb"): + return RecordingFile( + fname, mode, self.channels, self.rate, self.frames_per_buffer + ) class RecordingFile(object): - def __init__(self, fname, mode, channels, - rate, frames_per_buffer): + def __init__(self, fname, mode, channels, rate, frames_per_buffer): self.fname = fname self.mode = mode self.channels = channels @@ -52,11 +53,13 @@ def __exit__(self, exception, value, traceback): def record(self, duration): # Use a stream with no callback function in blocking mode - self._stream = self._pa.open(format=pyaudio.paInt16, - channels=self.channels, - rate=self.rate, - input=True, - frames_per_buffer=self.frames_per_buffer) + self._stream = self._pa.open( + format=pyaudio.paInt16, + channels=self.channels, + rate=self.rate, + input=True, + frames_per_buffer=self.frames_per_buffer, + ) for _ in range(int(self.rate / self.frames_per_buffer * duration)): audio = self._stream.read(self.frames_per_buffer) self.wavefile.writeframes(audio) @@ -64,12 +67,14 @@ def record(self, duration): def start_recording(self): # Use a stream with a callback in non-blocking mode - self._stream = self._pa.open(format=pyaudio.paInt16, - channels=self.channels, - rate=self.rate, - input=True, - frames_per_buffer=self.frames_per_buffer, - stream_callback=self.get_callback()) + self._stream = self._pa.open( + format=pyaudio.paInt16, + channels=self.channels, + rate=self.rate, + input=True, + frames_per_buffer=self.frames_per_buffer, + stream_callback=self.get_callback(), + ) self._stream.start_stream() return self @@ -81,6 +86,7 @@ def get_callback(self): def callback(in_data, frame_count, time_info, status): self.wavefile.writeframes(in_data) return in_data, pyaudio.paContinue + return callback def close(self): @@ -88,7 +94,7 @@ def close(self): self._pa.terminate() self.wavefile.close() - def _prepare_file(self, fname, mode='wb'): + def _prepare_file(self, fname, mode="wb"): wavefile = wave.open(fname, mode) wavefile.setnchannels(self.channels) wavefile.setsampwidth(self._pa.get_sample_size(pyaudio.paInt16)) diff --git a/rubikscube_solver/colordetection.py b/rubikscube_solver/colordetection.py index 6eae7330f..44c4a21f9 100644 --- a/rubikscube_solver/colordetection.py +++ b/rubikscube_solver/colordetection.py @@ -17,19 +17,21 @@ def get_color_name(self, hsv, cal): """Get the name of the color based on the hue. :returns: string.""" (h, s, v) = hsv for color in cal: - if color == 'red' or color == 'orange': - if (h < cal[color][1][0] or h > cal[color][0][0])\ - and s in range(cal[color][1][1], cal[color][0][1])\ - and v in range( - cal[color][1][2], cal[color][0][2]): + if color == "red" or color == "orange": + if ( + (h < cal[color][1][0] or h > cal[color][0][0]) + and s in range(cal[color][1][1], cal[color][0][1]) + and v in range(cal[color][1][2], cal[color][0][2]) + ): return color - elif h in range(cal[color][1][0], cal[color][0][0])\ - and s in range(cal[color][1][1], cal[color][0][1])\ - and v in range( - cal[color][1][2], cal[color][0][2]): + elif ( + h in range(cal[color][1][0], cal[color][0][0]) + and s in range(cal[color][1][1], cal[color][0][1]) + and v in range(cal[color][1][2], cal[color][0][2]) + ): return color - return 'white' + return "white" def name_to_rgb(self, name): """Get the main RGB color for a name. @@ -38,12 +40,12 @@ def name_to_rgb(self, name): :returns: tuple. """ color = { - 'red': (0, 0, 255), - 'orange': (0, 165, 255), - 'blue': (255, 0, 0), - 'green': (0, 255, 0), - 'white': (255, 255, 255), - 'yellow': (0, 255, 255) + "red": (0, 0, 255), + "orange": (0, 165, 255), + "blue": (255, 0, 0), + "green": (0, 255, 0), + "white": (255, 255, 255), + "yellow": (0, 255, 255), } return color[name] diff --git a/rubikscube_solver/combiner.py b/rubikscube_solver/combiner.py index b8f3263ae..070f396e7 100644 --- a/rubikscube_solver/combiner.py +++ b/rubikscube_solver/combiner.py @@ -12,9 +12,9 @@ def sides(self, sides): :param sides: dictionary with all the sides :returns: string """ - combined = '' - for face in 'URFDLB': - combined += ''.join(sides[face]) + combined = "" + for face in "URFDLB": + combined += "".join(sides[face]) return combined diff --git a/rubikscube_solver/normalizer.py b/rubikscube_solver/normalizer.py index 6a9c1b4d7..3d4b6df21 100644 --- a/rubikscube_solver/normalizer.py +++ b/rubikscube_solver/normalizer.py @@ -19,11 +19,11 @@ def algorithm(self, alg, language): :param alg: The algorithm itself :returns: list """ - with open('solve-manual.json') as f: + with open("solve-manual.json") as f: manual = json.load(f) solution = [] - for notation in alg.split(' '): + for notation in alg.split(" "): solution.append(manual[language][notation]) return solution diff --git a/rubikscube_solver/solver.py b/rubikscube_solver/solver.py index e31a45268..f728167e9 100644 --- a/rubikscube_solver/solver.py +++ b/rubikscube_solver/solver.py @@ -5,10 +5,10 @@ from sys import exit as Die try: - import kociemba import argparse - import video as webcam + import kociemba + import video as webcam from combiner import combine from normalizer import normalize except ImportError as err: @@ -21,59 +21,65 @@ class Solver: def __init__(self, normalize, language): """Initialise variables.""" self.humanize = normalize - self.language = (language[0]) if isinstance( - language, list) else language + self.language = (language[0]) if isinstance(language, list) else language def run(self): """Start webcam from video script.""" state = webcam.scan() if not state: print( - '\033[0;33m[Solver SCAN ERROR] Ops,' - ' you did not scan in all 6 sides.') - print('Please try again.\033[0m') + "\033[0;33m[Solver SCAN ERROR] Ops," " you did not scan in all 6 sides." + ) + print("Please try again.\033[0m") Die(1) unsolvedState = combine.sides(state) try: algorithm = kociemba.solve(unsolvedState) - length = len(algorithm.split(' ')) + length = len(algorithm.split(" ")) except ValueError as err: print( - '\033[0;33m[Solver SOLVE ERROR] Ops, ' - 'you did not scan in all 6 sides correctly.') - print('Please try again.\033[0m') + "\033[0;33m[Solver SOLVE ERROR] Ops, " + "you did not scan in all 6 sides correctly." + ) + print("Please try again.\033[0m") print(err) Die(1) - print('-- SOLUTION --') - print('Starting position:\n front: green\n top: white\n') - print(algorithm, '({0} moves)'.format(length), '\n') + print("-- SOLUTION --") + print("Starting position:\n front: green\n top: white\n") + print(algorithm, "({0} moves)".format(length), "\n") # if self.humanize: manual = normalize.algorithm(algorithm, self.language) for index, text in enumerate(manual): - print('{}. {}'.format(index + 1, text)) + print("{}. {}".format(index + 1, text)) Die(0) -if __name__ == '__main__': +if __name__ == "__main__": # define argument parser. parser = argparse.ArgumentParser() - parser.add_argument('-n', '--normalize', default=False, - action='store_true', - help='Shows the solution normalized.' - ' For example "R2" would be: \ - "Turn the right side 180 degrees".') - parser.add_argument('-l', '--language', nargs=1, default='en', - help='You can pass in a single \ - argument which will be the language' - ' for the normalization output. \ - Default is "en".') + parser.add_argument( + "-n", + "--normalize", + default=False, + action="store_true", + help="Shows the solution normalized." + ' For example "R2" would be: \ + "Turn the right side 180 degrees".', + ) + parser.add_argument( + "-l", + "--language", + nargs=1, + default="en", + help="You can pass in a single \ + argument which will be the language" + ' for the normalization output. \ + Default is "en".', + ) args = parser.parse_args() # run Solver with its arguments. - Solver( - args.normalize, - args.language - ).run() + Solver(args.normalize, args.language).run() diff --git a/rubikscube_solver/video.py b/rubikscube_solver/video.py index 7c95c0a8f..bffcde8d7 100644 --- a/rubikscube_solver/video.py +++ b/rubikscube_solver/video.py @@ -36,48 +36,74 @@ These are the coordinates of each sticker for each set. Feel free to play with these values if you don't like the sticker placement. """ -detector_stickers = [[200, 120], [300, 120], [400, 120], - [200, 220], [300, 220], [400, 220], - [200, 320], [300, 320], [400, 320]] - -current_stickers = [[20, 20], [54, 20], [88, 20], - [20, 54], [54, 54], [88, 54], - [20, 88], [54, 88], [88, 88]] - -recorded_stickers = [[20, 130], [54, 130], [88, 130], - [20, 164], [54, 164], [88, 164], - [20, 198], [54, 198], [88, 198]] +detector_stickers = [ + [200, 120], + [300, 120], + [400, 120], + [200, 220], + [300, 220], + [400, 220], + [200, 320], + [300, 320], + [400, 320], +] + +current_stickers = [ + [20, 20], + [54, 20], + [88, 20], + [20, 54], + [54, 54], + [88, 54], + [20, 88], + [54, 88], + [88, 88], +] + +recorded_stickers = [ + [20, 130], + [54, 130], + [88, 130], + [20, 164], + [54, 164], + [88, 164], + [20, 198], + [54, 198], + [88, 198], +] def draw_detector_stickers(frame): """Draws the 9 static stickers in the frame.""" - for (x, y) in (detector_stickers): + for (x, y) in detector_stickers: cv2.rectangle(frame, (x, y), (x + 50, y + 50), (255, 255, 255), 1) def draw_current_stickers(frame, state): """Draws the 9 detected stickers in the frame.""" for index, (x, y) in enumerate(current_stickers): - cv2.rectangle(frame, (x, y), (x + 32, y + 32), - ColorDetector.name_to_rgb(state[index]), -1) + cv2.rectangle( + frame, (x, y), (x + 32, y + 32), ColorDetector.name_to_rgb(state[index]), -1 + ) def draw_recorded_stickers(frame, state): """Draws the 9 Recorded stickers in the frame.""" for index, (x, y) in enumerate(recorded_stickers): - cv2.rectangle(frame, (x, y), (x + 32, y + 32), - ColorDetector.name_to_rgb(state[index]), -1) + cv2.rectangle( + frame, (x, y), (x + 32, y + 32), ColorDetector.name_to_rgb(state[index]), -1 + ) def color_to_notation(color): """Help function for converting colors to notation used by solver.""" notation = { - 'green': 'F', - 'white': 'U', - 'blue': 'B', - 'red': 'R', - 'orange': 'L', - 'yellow': 'D' + "green": "F", + "white": "U", + "blue": "B", + "red": "R", + "orange": "L", + "yellow": "D", } return notation[color] @@ -104,54 +130,89 @@ def scan(): # collection of scanned sides sides = {} # default starting preview sticker colors - preview = ['white', 'white', 'white', - 'white', 'white', 'white', - 'white', 'white', 'white'] - state = [0, 0, 0, # current sticker colors - 0, 0, 0, - 0, 0, 0] + preview = [ + "white", + "white", + "white", + "white", + "white", + "white", + "white", + "white", + "white", + ] + state = [0, 0, 0, 0, 0, 0, 0, 0, 0] # current sticker colors defaultcal = { # default color calibration - 'white': [[179, 67, 255], [0, 0, 0]], - 'green': [[72, 255, 218], [47, 61, 21]], - 'red': [[179, 255, 240], [6, 0, 102]], - 'orange': [[179, 255, 255], [17, 147, 207]], - 'yellow': [[49, 242, 255], [18, 61, 211]], - 'blue': [[127, 255, 212], [82, 72, 51]] + "white": [[179, 67, 255], [0, 0, 0]], + "green": [[72, 255, 218], [47, 61, 21]], + "red": [[179, 255, 240], [6, 0, 102]], + "orange": [[179, 255, 255], [17, 147, 207]], + "yellow": [[49, 242, 255], [18, 61, 211]], + "blue": [[127, 255, 212], [82, 72, 51]], } colorcal = {} # color calibration dictionary - color = ['white', 'green', 'red', 'orange', - 'yellow', 'blue'] # list of valid colors - - cv2.namedWindow('default', 0) + color = [ + "white", + "green", + "red", + "orange", + "yellow", + "blue", + ] # list of valid colors + + cv2.namedWindow("default", 0) # create trackbars here - cv2.createTrackbar('H Upper', 'default', - defaultcal[color[len(colorcal)]][0][0], - 179, empty_callback) - cv2.createTrackbar('S Upper', 'default', - defaultcal[color[len(colorcal)]][0][1], 255, - empty_callback) - cv2.createTrackbar('V Upper', 'default', - defaultcal[color[len(colorcal)]][0][2], 255, - empty_callback) - cv2.createTrackbar('H Lower', 'default', - defaultcal[color[len(colorcal)]][1][0], 179, - empty_callback) - cv2.createTrackbar('S Lower', 'default', - defaultcal[color[len(colorcal)]][1][1], 255, - empty_callback) - cv2.createTrackbar('V Lower', 'default', - defaultcal[color[len(colorcal)]][1][2], 255, - empty_callback) + cv2.createTrackbar( + "H Upper", + "default", + defaultcal[color[len(colorcal)]][0][0], + 179, + empty_callback, + ) + cv2.createTrackbar( + "S Upper", + "default", + defaultcal[color[len(colorcal)]][0][1], + 255, + empty_callback, + ) + cv2.createTrackbar( + "V Upper", + "default", + defaultcal[color[len(colorcal)]][0][2], + 255, + empty_callback, + ) + cv2.createTrackbar( + "H Lower", + "default", + defaultcal[color[len(colorcal)]][1][0], + 179, + empty_callback, + ) + cv2.createTrackbar( + "S Lower", + "default", + defaultcal[color[len(colorcal)]][1][1], + 255, + empty_callback, + ) + cv2.createTrackbar( + "V Lower", + "default", + defaultcal[color[len(colorcal)]][1][2], + 255, + empty_callback, + ) # Remember that the range for S and V are not 0 to 179 colorcal = defaultcal # Creates a window named 'my_window_name' - cv2.createTrackbar('My track bar', 'my_window_name', - 125, 255, empty_callback) + cv2.createTrackbar("My track bar", "my_window_name", 125, 255, empty_callback) while cameratesting: # --------------- Used for Testing ------------------------ @@ -184,9 +245,9 @@ def scan(): # (xbot_right,ybot_right), (r,g,b), borderwidth) # Displays the frame on the window we made - value = cv2.getTrackbarPos('My track bar', 'my_window_name') + value = cv2.getTrackbarPos("My track bar", "my_window_name") print(value) - cv2.imshow('my_window_name', frame) + cv2.imshow("my_window_name", frame) # Sets the amount of time to display a frame in milliseconds key = cv2.waitKey(10) @@ -203,11 +264,12 @@ def scan(): for index, (x, y) in enumerate(detector_stickers): # extracts hsv values within sticker - roi = hsv[y:y + 32, x:x + 32] + roi = hsv[y : y + 32, x : x + 32] # filters the hsv values into one hsv avg_hsv = ColorDetector.median_hsv(roi) color_name = ColorDetector.get_color_name( - avg_hsv, colorcal) # extracts the color based on hsv + avg_hsv, colorcal + ) # extracts the color based on hsv state[index] = color_name # stores the color # update when space bar is pressed. @@ -228,39 +290,81 @@ def scan(): draw_current_stickers(frame, state) # append amount of scanned sides - text = 'scanned sides: {}/6'.format(len(sides)) - cv2.putText(frame, text, (20, 460), cv2.FONT_HERSHEY_TRIPLEX, - 0.5, (255, 255, 0), 1, cv2.LINE_AA) + text = "scanned sides: {}/6".format(len(sides)) + cv2.putText( + frame, + text, + (20, 460), + cv2.FONT_HERSHEY_TRIPLEX, + 0.5, + (255, 255, 0), + 1, + cv2.LINE_AA, + ) # indicate the scanning instruction - textInstruction = 'scan and rotate the cube with white on the top' \ - ' and green on the front (towards camera)' - textInstruction2 = 'the color of center brick is used as the side' \ - ' identifier (since the center brick does not ' \ - 'move) ' - textInstruction3 = 'you can scan as many times as you want' - textInstruction4 = 'the program will overwrite the old scan ' \ - 'when same side is detected,' \ - ' press esc key get the solution ' - cv2.putText(frame, textInstruction, (20, 600), - cv2.FONT_HERSHEY_TRIPLEX, 0.5, - (255, 255, 0), 1, cv2.LINE_AA) - cv2.putText(frame, textInstruction2, (20, 620), - cv2.FONT_HERSHEY_TRIPLEX, 0.5, - (255, 255, 0), 1, cv2.LINE_AA) - cv2.putText(frame, textInstruction3, (20, 640), - cv2.FONT_HERSHEY_TRIPLEX, 0.5, - (255, 255, 0), 1, cv2.LINE_AA) - cv2.putText(frame, textInstruction4, (20, 660), - cv2.FONT_HERSHEY_TRIPLEX, 0.5, - (255, 255, 0), 1, cv2.LINE_AA) + textInstruction = ( + "scan and rotate the cube with white on the top" + " and green on the front (towards camera)" + ) + textInstruction2 = ( + "the color of center brick is used as the side" + " identifier (since the center brick does not " + "move) " + ) + textInstruction3 = "you can scan as many times as you want" + textInstruction4 = ( + "the program will overwrite the old scan " + "when same side is detected," + " press esc key get the solution " + ) + cv2.putText( + frame, + textInstruction, + (20, 600), + cv2.FONT_HERSHEY_TRIPLEX, + 0.5, + (255, 255, 0), + 1, + cv2.LINE_AA, + ) + cv2.putText( + frame, + textInstruction2, + (20, 620), + cv2.FONT_HERSHEY_TRIPLEX, + 0.5, + (255, 255, 0), + 1, + cv2.LINE_AA, + ) + cv2.putText( + frame, + textInstruction3, + (20, 640), + cv2.FONT_HERSHEY_TRIPLEX, + 0.5, + (255, 255, 0), + 1, + cv2.LINE_AA, + ) + cv2.putText( + frame, + textInstruction4, + (20, 660), + cv2.FONT_HERSHEY_TRIPLEX, + 0.5, + (255, 255, 0), + 1, + cv2.LINE_AA, + ) # quit on escape. if key == 27: break # show result - cv2.imshow('default', frame) + cv2.imshow("default", frame) if key == 99: colorcal = {} @@ -268,26 +372,25 @@ def scan(): _, frame = cam.read() hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) - key = cv2.waitKey(10) & 0xff + key = cv2.waitKey(10) & 0xFF # hue upper lower - hu = cv2.getTrackbarPos('H Upper', 'default') - hl = cv2.getTrackbarPos('H Lower', 'default') + hu = cv2.getTrackbarPos("H Upper", "default") + hl = cv2.getTrackbarPos("H Lower", "default") # saturation upper lower - su = cv2.getTrackbarPos('S Upper', 'default') - sl = cv2.getTrackbarPos('S Lower', 'default') + su = cv2.getTrackbarPos("S Upper", "default") + sl = cv2.getTrackbarPos("S Lower", "default") # value upper lower - vu = cv2.getTrackbarPos('V Upper', 'default') - vl = cv2.getTrackbarPos('V Lower', 'default') - print('H upper', hu) - print('H Lower', hl) - print('S upper', su) - print('S Lower', sl) - print('V upper', vu) - print('V Lower', vl) - - if color[len(colorcal)] == 'red'\ - or color[len(colorcal)] == 'orange': + vu = cv2.getTrackbarPos("V Upper", "default") + vl = cv2.getTrackbarPos("V Lower", "default") + print("H upper", hu) + print("H Lower", hl) + print("S upper", su) + print("S Lower", sl) + print("V upper", vu) + print("V Lower", vl) + + if color[len(colorcal)] == "red" or color[len(colorcal)] == "orange": lower_hsv = np.array([0, sl, vl]) upper_hsv = np.array([hl, su, vu]) mask1 = cv2.inRange(hsv, lower_hsv, upper_hsv) @@ -311,29 +414,37 @@ def scan(): if len(colorcal) < 6: cv2.setTrackbarPos( - 'H Upper', 'default', - defaultcal[color[len(colorcal)]][0][0]) + "H Upper", "default", defaultcal[color[len(colorcal)]][0][0] + ) cv2.setTrackbarPos( - 'S Upper', 'default', - defaultcal[color[len(colorcal)]][0][1]) + "S Upper", "default", defaultcal[color[len(colorcal)]][0][1] + ) cv2.setTrackbarPos( - 'V Upper', 'default', - defaultcal[color[len(colorcal)]][0][2]) + "V Upper", "default", defaultcal[color[len(colorcal)]][0][2] + ) cv2.setTrackbarPos( - 'H Lower', 'default', - defaultcal[color[len(colorcal)]][1][0]) + "H Lower", "default", defaultcal[color[len(colorcal)]][1][0] + ) cv2.setTrackbarPos( - 'S Lower', 'default', - defaultcal[color[len(colorcal)]][1][1]) + "S Lower", "default", defaultcal[color[len(colorcal)]][1][1] + ) cv2.setTrackbarPos( - 'V Lower', 'default', - defaultcal[color[len(colorcal)]][1][2]) + "V Lower", "default", defaultcal[color[len(colorcal)]][1][2] + ) if len(colorcal) < 6: - text = 'calibrating {}'.format(color[len(colorcal)]) - cv2.putText(res, text, (20, 460), cv2.FONT_HERSHEY_TRIPLEX, - 0.5, (255, 255, 255), 1, cv2.LINE_AA) - cv2.imshow('default', res) + text = "calibrating {}".format(color[len(colorcal)]) + cv2.putText( + res, + text, + (20, 460), + cv2.FONT_HERSHEY_TRIPLEX, + 0.5, + (255, 255, 255), + 1, + cv2.LINE_AA, + ) + cv2.imshow("default", res) # quit on escape key if key == 27: break diff --git a/scan_ports/scan_port.py b/scan_ports/scan_port.py index 6208c9ae9..748b06083 100755 --- a/scan_ports/scan_port.py +++ b/scan_ports/scan_port.py @@ -1,8 +1,9 @@ -import pyfiglet -import sys import socket +import sys from datetime import datetime +import pyfiglet + ascii_banner = pyfiglet.figlet_format("PORT SCANNER") print(ascii_banner) diff --git a/screen_recorder/screen_recorder.py b/screen_recorder/screen_recorder.py index 5fe2b8145..af9392d0b 100644 --- a/screen_recorder/screen_recorder.py +++ b/screen_recorder/screen_recorder.py @@ -1,7 +1,8 @@ +import datetime as dt + +import cv2 import numpy as np import pyautogui -import cv2 -import datetime as dt print("Key Commands:") print("s - Start") @@ -11,14 +12,14 @@ # Create VideoWriter resolution = (1920, 1080) fps = 60 -codec = cv2.VideoWriter_fourcc(*'XVID') -filename = dt.datetime.now().strftime('%m-%d-%Y_%H-%M_recording.avi') +codec = cv2.VideoWriter_fourcc(*"XVID") +filename = dt.datetime.now().strftime("%m-%d-%Y_%H-%M_recording.avi") recording = cv2.VideoWriter(filename, codec, fps, resolution) # Create preview window -cv2.namedWindow('Preview', cv2.WINDOW_NORMAL) -cv2.resizeWindow('Preview', 480, 270) +cv2.namedWindow("Preview", cv2.WINDOW_NORMAL) +cv2.resizeWindow("Preview", 480, 270) start = False pause = False @@ -31,17 +32,17 @@ frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) recording.write(frame) - cv2.imshow('Preview', frame) + cv2.imshow("Preview", frame) key = cv2.waitKey(1) # Receive key commands - if key == ord('q'): + if key == ord("q"): print("Recording ended.") break - elif key == ord('s'): + elif key == ord("s"): if not start: print("Recording started. Press 'q' to end recording.") start = True - elif key == ord('w') and start: + elif key == ord("w") and start: pause = not pause if pause: print("Recording paused. Press 'w' to resume recording.") diff --git a/screen_shoter/screenshooter.py b/screen_shoter/screenshooter.py index e415abad5..e069debf6 100644 --- a/screen_shoter/screenshooter.py +++ b/screen_shoter/screenshooter.py @@ -1,9 +1,9 @@ import cv2 import numpy as np -import pynput.mouse as ms -import pynput.keyboard as kb -from pynput.keyboard import Key, Controller import pyautogui +import pynput.keyboard as kb +import pynput.mouse as ms +from pynput.keyboard import Controller, Key keyboard = Controller() @@ -18,22 +18,22 @@ class TwoClicksScreenShot: @staticmethod def area_select(): - print('Click twice to define Screenshot area') + print("Click twice to define Screenshot area") def on_click(x, y, button, pressed): if pressed: if TwoClicksScreenShot.clickCount == 0: - print('First point ({0}, {1})'.format(x, y)) + print("First point ({0}, {1})".format(x, y)) TwoClicksScreenShot.pCords[0] = x TwoClicksScreenShot.pCords[1] = y elif TwoClicksScreenShot.clickCount == 1: - print('Second point ({0}, {1})'.format(x, y)) + print("Second point ({0}, {1})".format(x, y)) TwoClicksScreenShot.pCords[2] = x - TwoClicksScreenShot.pCords[0] TwoClicksScreenShot.pCords[3] = y - TwoClicksScreenShot.pCords[1] TwoClicksScreenShot.defined = True - print('') + print("") TwoClicksScreenShot.clickCount = 0 return False TwoClicksScreenShot.clickCount += 1 @@ -44,16 +44,16 @@ def on_click(x, y, button, pressed): @staticmethod def keypress(): - print('Press UP key to define Screenshot Area') + print("Press UP key to define Screenshot Area") def on_release(key): if key == Key.up: - print('Pressed\n') + print("Pressed\n") TwoClicksScreenShot.area_select() if TwoClicksScreenShot.capture(): return False else: - print('Define points properly!! Press UP again to define') + print("Define points properly!! Press UP again to define") return True with kb.Listener(on_release=on_release) as listener: @@ -62,11 +62,11 @@ def on_release(key): @staticmethod def start_typing(): - print('Press DOWN key to capture') + print("Press DOWN key to capture") def on_release(key): if key == Key.down: - print('Pressed\n') + print("Pressed\n") TwoClicksScreenShot.output() return False @@ -79,16 +79,24 @@ def capture(): return False if TwoClicksScreenShot.defined: - TwoClicksScreenShot.screenShot = pyautogui.screenshot(region=(TwoClicksScreenShot.pCords[0], - TwoClicksScreenShot.pCords[1], - TwoClicksScreenShot.pCords[2], - TwoClicksScreenShot.pCords[3])) - TwoClicksScreenShot.screenShot = cv2.cvtColor(np.array(TwoClicksScreenShot.screenShot), cv2.COLOR_BGR2RGB) + TwoClicksScreenShot.screenShot = pyautogui.screenshot( + region=( + TwoClicksScreenShot.pCords[0], + TwoClicksScreenShot.pCords[1], + TwoClicksScreenShot.pCords[2], + TwoClicksScreenShot.pCords[3], + ) + ) + TwoClicksScreenShot.screenShot = cv2.cvtColor( + np.array(TwoClicksScreenShot.screenShot), cv2.COLOR_BGR2RGB + ) return True @staticmethod def output(): - cv2.imwrite(TwoClicksScreenShot.filename + ".png", TwoClicksScreenShot.screenShot) + cv2.imwrite( + TwoClicksScreenShot.filename + ".png", TwoClicksScreenShot.screenShot + ) print("Screenshot saved as " + TwoClicksScreenShot.filename + ".png") @@ -97,5 +105,5 @@ def start(): TwoClicksScreenShot.start_typing() -if __name__ == '__main__': +if __name__ == "__main__": start() diff --git a/security headers/security_headers/security_headers.py b/security headers/security_headers/security_headers.py index 769ae69a0..d6565a63c 100644 --- a/security headers/security_headers/security_headers.py +++ b/security headers/security_headers/security_headers.py @@ -1,4 +1,5 @@ from datetime import datetime + import requests from bs4 import BeautifulSoup @@ -17,8 +18,7 @@ # Making a GET request def find_headers(): for url in website_url: - r = requests.get(f'https://securityheaders.com/?q=' - f'{url}&followRedirects=on') + r = requests.get(f"https://securityheaders.com/?q=" f"{url}&followRedirects=on") Strict_Transport_Security_status = False X_Content_Type_Options_status = False @@ -28,13 +28,13 @@ def find_headers(): Permissions_Policy_status = False # Parsing the HTML - soup = BeautifulSoup(r.content, 'html.parser') + soup = BeautifulSoup(r.content, "html.parser") print(soup) score = soup.find("div", {"class": "score"}) # print(score) - text = soup.findAll("li", {'class': "headerItem pill pill-green"}) + text = soup.findAll("li", {"class": "headerItem pill pill-green"}) # print("headers present") for i in text: if i.text == "Strict-Transport-Security": @@ -50,11 +50,17 @@ def find_headers(): elif i.text == "Permissions-Policy": Permissions_Policy_status = True - data = [url, getdate, score, Strict_Transport_Security_status, - X_Content_Type_Options_status, - X_Frame_Options_status, - Content_Security_Policy_status, - Referrer_Policy_status, Permissions_Policy_status] + data = [ + url, + getdate, + score, + Strict_Transport_Security_status, + X_Content_Type_Options_status, + X_Frame_Options_status, + Content_Security_Policy_status, + Referrer_Policy_status, + Permissions_Policy_status, + ] print(data) diff --git a/security_headers/security_headers.py b/security_headers/security_headers.py index 769ae69a0..d6565a63c 100644 --- a/security_headers/security_headers.py +++ b/security_headers/security_headers.py @@ -1,4 +1,5 @@ from datetime import datetime + import requests from bs4 import BeautifulSoup @@ -17,8 +18,7 @@ # Making a GET request def find_headers(): for url in website_url: - r = requests.get(f'https://securityheaders.com/?q=' - f'{url}&followRedirects=on') + r = requests.get(f"https://securityheaders.com/?q=" f"{url}&followRedirects=on") Strict_Transport_Security_status = False X_Content_Type_Options_status = False @@ -28,13 +28,13 @@ def find_headers(): Permissions_Policy_status = False # Parsing the HTML - soup = BeautifulSoup(r.content, 'html.parser') + soup = BeautifulSoup(r.content, "html.parser") print(soup) score = soup.find("div", {"class": "score"}) # print(score) - text = soup.findAll("li", {'class': "headerItem pill pill-green"}) + text = soup.findAll("li", {"class": "headerItem pill pill-green"}) # print("headers present") for i in text: if i.text == "Strict-Transport-Security": @@ -50,11 +50,17 @@ def find_headers(): elif i.text == "Permissions-Policy": Permissions_Policy_status = True - data = [url, getdate, score, Strict_Transport_Security_status, - X_Content_Type_Options_status, - X_Frame_Options_status, - Content_Security_Policy_status, - Referrer_Policy_status, Permissions_Policy_status] + data = [ + url, + getdate, + score, + Strict_Transport_Security_status, + X_Content_Type_Options_status, + X_Frame_Options_status, + Content_Security_Policy_status, + Referrer_Policy_status, + Permissions_Policy_status, + ] print(data) diff --git a/send_sms/sms.py b/send_sms/sms.py index 5dcbbacb5..b152c55e4 100644 --- a/send_sms/sms.py +++ b/send_sms/sms.py @@ -1,36 +1,32 @@ from twilio.rest import Client -sid = 'ACCOUNT SID goes here' -auth_token = 'AUTH token here' +sid = "ACCOUNT SID goes here" +auth_token = "AUTH token here" -twilio_number = 'Your Twilio provided number here' +twilio_number = "Your Twilio provided number here" client = Client(sid, auth_token) -details = {'Message created': '', 'Date sent': '', 'Body': ''} +details = {"Message created": "", "Date sent": "", "Body": ""} def craft(msg, fromPhone, sendTo): - message = client.messages.create( - body=msg, - from_=fromPhone, - to=sendTo - ) + message = client.messages.create(body=msg, from_=fromPhone, to=sendTo) - details['Message created'] = str(message.date_created) - details['Date sent'] = str(message.date_sent) - details['Body'] = str(message.body) + details["Message created"] = str(message.date_created) + details["Date sent"] = str(message.date_sent) + details["Body"] = str(message.body) def main(msg: str): - return craft(msg, twilio_number, '+15555550100') + return craft(msg, twilio_number, "+15555550100") -if __name__ == '__main__': - main('Hello, user! Sent from Python!') - seeDetails = input('See details of this message? [y/n]: ') - if seeDetails.lower() == 'y': +if __name__ == "__main__": + main("Hello, user! Sent from Python!") + seeDetails = input("See details of this message? [y/n]: ") + if seeDetails.lower() == "y": for i in details: - print(f'{i} = {details[i]}') + print(f"{i} = {details[i]}") else: exit() diff --git a/simple_plagiarism_detector/simple-plagiarism-detector.py b/simple_plagiarism_detector/simple-plagiarism-detector.py index 66592af63..a68bc6d29 100644 --- a/simple_plagiarism_detector/simple-plagiarism-detector.py +++ b/simple_plagiarism_detector/simple-plagiarism-detector.py @@ -4,15 +4,15 @@ import math import re -from collections import Counter import sys +from collections import Counter WORD = re.compile(r"[A-Za-z0-9]") SPECIAL_CHARS = re.compile(r"[^A-Za-z0-9]") def get_cosine(vec1, vec2): - """ Function to compute Cosine Similarity between two word vectors""" + """Function to compute Cosine Similarity between two word vectors""" intersection = set(vec1.keys()) & set(vec2.keys()) numerator = sum([vec1[x] * vec2[x] for x in intersection]) @@ -43,8 +43,8 @@ def text_to_vector(text): if len(text1) == 0 and len(text2) == 0: print("given text files were empty, imputing '1' as place holder") - text1 = '' + '1' - text2 = '' + '1' + text1 = "" + "1" + text2 = "" + "1" vector1 = text_to_vector(text1) vector2 = text_to_vector(text2) diff --git a/site_blocker/site_blocker.py b/site_blocker/site_blocker.py index 6fe6338c5..dceee1879 100644 --- a/site_blocker/site_blocker.py +++ b/site_blocker/site_blocker.py @@ -2,14 +2,14 @@ def add_domain(): domain_name = input("Enter the domain of the website to block:") with open("c:/Windows/System32/drivers/etc/hosts", "a") as fileHandler: - fileHandler.write('127.0.0.1 {}'.format(domain_name) + '\n') + fileHandler.write("127.0.0.1 {}".format(domain_name) + "\n") # function for removing the domains from the host file def remove_all_domains(): all_domains_list = input("Enter the domains to remove separated by space:") all_domains = all_domains_list.split(" ") - with open("c:/Windows/System32/drivers/etc/hosts", 'r+') as f: + with open("c:/Windows/System32/drivers/etc/hosts", "r+") as f: file_contents = f.readlines() for each_domain in all_domains: for each_line in file_contents: diff --git a/slideshare_downloader/slideshare_downloader.py b/slideshare_downloader/slideshare_downloader.py index c5efd64d4..609670458 100644 --- a/slideshare_downloader/slideshare_downloader.py +++ b/slideshare_downloader/slideshare_downloader.py @@ -9,16 +9,17 @@ """ import io import os + import requests from bs4 import BeautifulSoup from pptx import Presentation -url = 'https://www.slideshare.net/Slideshare/get-started-with-slide-share' +url = "https://www.slideshare.net/Slideshare/get-started-with-slide-share" data = requests.get(url) -html = BeautifulSoup(data.text, 'html.parser') -links = html.select('img.slide_image') +html = BeautifulSoup(data.text, "html.parser") +links = html.select("img.slide_image") prs = Presentation() for link in links: image = link["data-full"] diff --git a/sms_location/sms_loc.py b/sms_location/sms_loc.py index 156afb459..07435ac9b 100644 --- a/sms_location/sms_loc.py +++ b/sms_location/sms_loc.py @@ -1,23 +1,23 @@ import requests + no = input("enter your no") -r = requests.get('https://get.geojs.io/') -ip_request = requests.get('https://get.geojs.io/v1/ip.json') -ipadd = ip_request.json()['ip'] -url = 'https://get.geojs.io/v1/ip/geo/' + ipadd + '.json' +r = requests.get("https://get.geojs.io/") +ip_request = requests.get("https://get.geojs.io/v1/ip.json") +ipadd = ip_request.json()["ip"] +url = "https://get.geojs.io/v1/ip/geo/" + ipadd + ".json" geo_request = requests.get(url) geo_data = geo_request.json() msg = f"latitude: {geo_data['latitude']} longitude : {geo_data['longitude']} city : {geo_data['city']}" url1 = "https://www.fast2sms.com/dev/bulk" -query = {"authorization" : "your api key ", - "sender_id" : "FSTSMS", - "message" : msg, - "language" : "english", - "route" : "p", - "numbers" : no - } - -headers = { - 'cache-control' : "no-cache" +query = { + "authorization": "your api key ", + "sender_id": "FSTSMS", + "message": msg, + "language": "english", + "route": "p", + "numbers": no, } + +headers = {"cache-control": "no-cache"} response = requests.request("GET", url1, headers=headers, params=query) print(response.text) diff --git a/song_scraper_GUI/findMyTune.py b/song_scraper_GUI/findMyTune.py index 9497cfb20..bdcc9aa9d 100644 --- a/song_scraper_GUI/findMyTune.py +++ b/song_scraper_GUI/findMyTune.py @@ -1,29 +1,28 @@ -from tkinter import Tk, Button, Toplevel, Label, Frame, PhotoImage, Entry -from tkinter import TOP, LEFT, RIGHT, NE, W, DISABLED, NORMAL, YES -from tkinter import CENTER, BOTH -from tkinter import ttk -import tkinter.messagebox import os -from mp3Clan_top_web_scraper import findMySong, downloadMySong +import tkinter.messagebox +from tkinter import (BOTH, CENTER, DISABLED, LEFT, NE, NORMAL, RIGHT, TOP, YES, + Button, Entry, Frame, Label, PhotoImage, Tk, Toplevel, W, + ttk) + +from mp3Clan_top_web_scraper import downloadMySong, findMySong class SongGUI: def __init__(self, root): self.root = root - self.root.title('Find my tune') + self.root.title("Find my tune") self.root.geometry() self.root.minsize(800, 800) self.searchname = tkinter.StringVar() # creating help button - help_button_img = PhotoImage(file='images/help_button.png') + help_button_img = PhotoImage(file="images/help_button.png") help_button_img = help_button_img.subsample(2) help_img_label = Label(image=help_button_img) help_img_label.image = help_button_img - self.help_button = Button(self.root, - image=help_button_img, - command=self.helpFrame, - border=0) + self.help_button = Button( + self.root, image=help_button_img, command=self.helpFrame, border=0 + ) self.help_button.pack(side=TOP, anchor=NE, padx=10, pady=10) # creating input frame @@ -31,40 +30,45 @@ def __init__(self, root): self.input_frame.pack() # creating heading - heading = Label(self.input_frame, text="Find My Tune", - font=("Helvetica", 30), fg="black") + heading = Label( + self.input_frame, text="Find My Tune", font=("Helvetica", 30), fg="black" + ) heading.pack(pady=20, side=TOP) # creating search bar - self.search_box_input = Entry(self.input_frame, font=( - "Helvetica", 20), textvariable=self.searchname) + self.search_box_input = Entry( + self.input_frame, font=("Helvetica", 20), textvariable=self.searchname + ) self.search_box_input.pack() # creating search button - search_button_img = PhotoImage(file='images/search_button.png') + search_button_img = PhotoImage(file="images/search_button.png") search_button_img = search_button_img.subsample(2) search_img_label = Label(image=search_button_img) search_img_label.image = search_button_img - self.search_button = Button(self.input_frame, image=search_button_img, - border=0, command=self.searchSong) + self.search_button = Button( + self.input_frame, image=search_button_img, border=0, command=self.searchSong + ) self.search_button.pack(pady=10, side=LEFT) # creating refresh button - refresh_button_img = PhotoImage(file='images/refresh_button.png') + refresh_button_img = PhotoImage(file="images/refresh_button.png") refresh_button_img = refresh_button_img.subsample(2) refresh_img_label = Label(image=refresh_button_img) refresh_img_label.image = refresh_button_img - self.refresh_button = Button(self.input_frame, - image=refresh_button_img, - fg='green', - command=self.refreshFrame, - border=0) + self.refresh_button = Button( + self.input_frame, + image=refresh_button_img, + fg="green", + command=self.refreshFrame, + border=0, + ) self.refresh_button.pack(pady=10, side=RIGHT) def helpFrame(self): - '''shows help Window in new frame''' + """shows help Window in new frame""" - self.help_button['state'] = DISABLED + self.help_button["state"] = DISABLED # Toplevel object which will be treated as a new window self.help_window = Toplevel(self.root) @@ -79,56 +83,72 @@ def helpFrame(self): # reading content from help_window.txt info_file = open("help_window.txt") - lines = info_file. readlines() + lines = info_file.readlines() - heading = Label(self.help_window, font=( - "Helvetica 20 underline"), text="HELP WINDOW") + heading = Label( + self.help_window, font=("Helvetica 20 underline"), text="HELP WINDOW" + ) heading.pack(side=TOP, padx=10, pady=10) # code, to show content in help_window - Label(self.help_window, wraplength=500, justify="left", font=("", 12), - text=lines[0]).pack(side=TOP, pady=10, padx=5) - Label(self.help_window, font=("Helvetica 16 underline bold"), - text="INSTRUCTIONS").pack(anchor=W, padx=10, pady=10) + Label( + self.help_window, + wraplength=500, + justify="left", + font=("", 12), + text=lines[0], + ).pack(side=TOP, pady=10, padx=5) + Label( + self.help_window, font=("Helvetica 16 underline bold"), text="INSTRUCTIONS" + ).pack(anchor=W, padx=10, pady=10) for i in range(1, 9): - Label(self.help_window, wraplength=500, - justify="left", font=("", 12), - text=str(i) + ". " + lines[i]).pack(anchor=W, pady=2, padx=10) - Label(self.help_window, font=("Helvetica 16 underline"), - text="NOTE").pack(anchor=W, padx=10, pady=10) + Label( + self.help_window, + wraplength=500, + justify="left", + font=("", 12), + text=str(i) + ". " + lines[i], + ).pack(anchor=W, pady=2, padx=10) + Label(self.help_window, font=("Helvetica 16 underline"), text="NOTE").pack( + anchor=W, padx=10, pady=10 + ) for i in range(8, 11): - Label(self.help_window, wraplength=500, - justify="left", font=("", 12), - text=str(i - 7) + ". " + lines[i]).pack(anchor=W, pady=2, padx=10) + Label( + self.help_window, + wraplength=500, + justify="left", + font=("", 12), + text=str(i - 7) + ". " + lines[i], + ).pack(anchor=W, pady=2, padx=10) self.help_window.protocol("WM_DELETE_WINDOW", self.close_window) def close_window(self): - '''function which closes the help_window''' + """function which closes the help_window""" self.help_window.destroy() - self.help_button['state'] = NORMAL + self.help_button["state"] = NORMAL def searchSong(self): - ''''function reads the search_input and searchs for the song''' + """'function reads the search_input and searchs for the song""" self.songname = self.searchname.get() - self.searchname.set('') + self.searchname.set("") # if the search box is not empty - if (self.songname): + if self.songname: self.songlist = findMySong(self.songname) - self.search_button['state'] = DISABLED - self.searchname.set('') + self.search_button["state"] = DISABLED + self.searchname.set("") self.result_frame = Frame(self.root) self.result_frame.pack() self.results = ttk.Treeview(self.result_frame) # if search is not empty - if (self.songlist): + if self.songlist: # creates four cols, 1 phantom columns - self.results['columns'] = ('S.NO', 'Name', 'Duration') + self.results["columns"] = ("S.NO", "Name", "Duration") style = ttk.Style() style.configure("Treeview", rowheight=18, columns=30000) @@ -136,8 +156,7 @@ def searchSong(self): self.results.column("#0", stretch=YES, width=0, minwidth=0) self.results.column("S.NO", stretch=YES, anchor=W, width=40) self.results.column("Name", anchor=W, stretch=YES, width=600) - self.results.column( - "Duration", stretch=YES, anchor=W, width=80) + self.results.column("Duration", stretch=YES, anchor=W, width=80) # Create Headings self.results.heading("S.NO", text="S.NO", anchor=W) @@ -146,73 +165,81 @@ def searchSong(self): self.results.pack(pady=10, expand=1, fill=BOTH) for i in range(len(self.songlist)): - self.results.insert(parent='', index='end', iid=i, text='', - values=(str(i + 1), - self.songlist[i]['title'], - self.songlist[i]['duration'])) + self.results.insert( + parent="", + index="end", + iid=i, + text="", + values=( + str(i + 1), + self.songlist[i]["title"], + self.songlist[i]["duration"], + ), + ) self.down_button = Button( - self.result_frame, text='DOWNLOAD', - fg='white', bg='green', - command=self.downloadSong) + self.result_frame, + text="DOWNLOAD", + fg="white", + bg="green", + command=self.downloadSong, + ) self.down_button.pack(padx=10, side=TOP) else: tkinter.messagebox.showerror( - 'No Song Foumd', - "Could'nt find your song, please try again") - self.search_button['state'] = NORMAL + "No Song Foumd", "Could'nt find your song, please try again" + ) + self.search_button["state"] = NORMAL else: - tkinter.messagebox.showerror( - 'Search box Empty', "Please enter song name") - self.search_button['state'] = NORMAL + tkinter.messagebox.showerror("Search box Empty", "Please enter song name") + self.search_button["state"] = NORMAL def downloadSong(self): - '''Function which download the song''' + """Function which download the song""" - self.down_button['state'] = DISABLED + self.down_button["state"] = DISABLED songNumber = self.results.focus() # if option is selected - if (songNumber): + if songNumber: songNumber = int(songNumber) - downloadMySong(self.songlist[songNumber]['download-link']) - filename = [f for f in os.listdir() if f.endswith('.mp3')] - if (filename): + downloadMySong(self.songlist[songNumber]["download-link"]) + filename = [f for f in os.listdir() if f.endswith(".mp3")] + if filename: # rename file and save in download folder - os.rename(filename[0], 'downloads/' + filename[0][:-14] + ".mp3") + os.rename(filename[0], "downloads/" + filename[0][:-14] + ".mp3") tkinter.messagebox.showinfo( - 'Song Downloaded Successfully', - "Your song is downloaded.") + "Song Downloaded Successfully", "Your song is downloaded." + ) else: tkinter.messagebox.showerror( - 'Song Not Downloaded', - "Could'nt download your song, please try again later.") - filename = [f for f in os.listdir( - ) if f.endswith('.crdownload')] - if (filename): + "Song Not Downloaded", + "Could'nt download your song, please try again later.", + ) + filename = [f for f in os.listdir() if f.endswith(".crdownload")] + if filename: for file in filename: os.remove(file) else: tkinter.messagebox.showerror( - 'Song Not Selected', - "Please choose one item from list, then press download button") - self.down_button['state'] = NORMAL + "Song Not Selected", + "Please choose one item from list, then press download button", + ) + self.down_button["state"] = NORMAL def refreshFrame(self): - '''clears the search window''' - self.search_button['state'] = NORMAL - self.searchname.set('') + """clears the search window""" + self.search_button["state"] = NORMAL + self.searchname.set("") try: - self.result_frame. pack_forget() + self.result_frame.pack_forget() except AttributeError: - tkinter.messagebox.showinfo( - 'Already Refreshed', - "window already refreshed") + tkinter.messagebox.showinfo("Already Refreshed", "window already refreshed") -if (__name__ == "__main__"): +if __name__ == "__main__": root = Tk() SongGUI(root) root.mainloop() diff --git a/song_scraper_GUI/mp3Clan_top_web_scraper.py b/song_scraper_GUI/mp3Clan_top_web_scraper.py index 6fb75e108..10dcc8545 100644 --- a/song_scraper_GUI/mp3Clan_top_web_scraper.py +++ b/song_scraper_GUI/mp3Clan_top_web_scraper.py @@ -1,14 +1,15 @@ +import time + from selenium import webdriver -from webdriver_manager.chrome import ChromeDriverManager from selenium.common.exceptions import NoSuchElementException, TimeoutException -import time from selenium.webdriver.chrome.options import Options +from webdriver_manager.chrome import ChromeDriverManager def findMySong(song_name): - ''' - function which accepts string and returns list of 10 available songs - ''' + """ + function which accepts string and returns list of 10 available songs + """ options = Options() options.headless = True @@ -25,23 +26,22 @@ def findMySong(song_name): time.sleep(10) try: - songs = driver.find_elements_by_class_name('mp3list-table') + songs = driver.find_elements_by_class_name("mp3list-table") song_list = [] cnt = 0 for song in songs: try: - if (cnt < 10): - details = song.find_element_by_class_name( - "mp3list-play").text + if cnt < 10: + details = song.find_element_by_class_name("mp3list-play").text details = details.split("\n") link_sel_obj = song.find_element_by_tag_name("a") link = link_sel_obj.get_attribute("href") link = link[:33] + "get" + link[37:] - if (len(details) > 2): + if len(details) > 2: vid_item = { - 'title': details[0], + "title": details[0], "duration": details[-1], - "download-link": link + "download-link": link, } song_list.append(vid_item) cnt += 1 @@ -53,20 +53,19 @@ def findMySong(song_name): except NoSuchElementException: print("big error") driver.close() - return (song_list) + return song_list def downloadMySong(url): - ''' - function which accepts url, - and download's and save song in current directory - ''' + """ + function which accepts url, + and download's and save song in current directory + """ try: options = Options() options.headless = True - driver = webdriver.Chrome( - ChromeDriverManager().install(), options=options) + driver = webdriver.Chrome(ChromeDriverManager().install(), options=options) driver.set_page_load_timeout(20) driver.get(url) diff --git a/sort_vizualizer/main.py b/sort_vizualizer/main.py index b1c74ffb2..c309f92ce 100644 --- a/sort_vizualizer/main.py +++ b/sort_vizualizer/main.py @@ -1,24 +1,23 @@ # quick sort visualizer # import tkinter as tk -from tkinter import Tk, Label, Button, Frame, Canvas, Entry, SW, W -from tkinter import messagebox import random -import time import sys +import time +from tkinter import SW, Button, Canvas, Entry, Frame, Label, Tk, W, messagebox sys.setrecursionlimit(10**6) # colours -DARK_GREY = '#73C6B6' -LIGHT_GREY = '#B2BABB' -WHITE = '#F0F3F4' -GREEN = '#82E0AA' -GREEN_2 = '#76D7C4' -BLUE = '#85C1E9' -PURPLE = '#BB8FCE' -RED = '#F5B7B1' -YELLOW = '#F7E806' +DARK_GREY = "#73C6B6" +LIGHT_GREY = "#B2BABB" +WHITE = "#F0F3F4" +GREEN = "#82E0AA" +GREEN_2 = "#76D7C4" +BLUE = "#85C1E9" +PURPLE = "#BB8FCE" +RED = "#F5B7B1" +YELLOW = "#F7E806" # array of elements / rectangle heights array = [] @@ -86,10 +85,19 @@ def quickSort(array, left, right, drawRect): pivot = partition(array, left, right, drawRect) quickSort(array, left, pivot, drawRect) quickSort(array, pivot + 1, right, drawRect) - drawRect(array, [BLUE if x >= left and x < pivot - else YELLOW if x == pivot - else PURPLE if x > pivot and x <= right - else RED for x in range(len(array))]) + drawRect( + array, + [ + BLUE + if x >= left and x < pivot + else YELLOW + if x == pivot + else PURPLE + if x > pivot and x <= right + else RED + for x in range(len(array)) + ], + ) time.sleep(0.5) drawRect(array, [GREEN for x in range(len(array))]) @@ -99,9 +107,9 @@ def quickSort(array, left, right, drawRect): def sort(): try: quickSort(array, 0, len(array) - 1, drawRect) - messagebox.showinfo('Succces', 'Array sorted!') + messagebox.showinfo("Succces", "Array sorted!") except Exception: - messagebox.showinfo('Error', 'Array could not be sorted') + messagebox.showinfo("Error", "Array could not be sorted") def exit_win(): @@ -113,7 +121,7 @@ def exit_win(): # main window root = Tk() -root.title('Quick Sort Visualizer') +root.title("Quick Sort Visualizer") # background color root.config(bg=LIGHT_GREY) # disabling resizing of window @@ -121,69 +129,43 @@ def exit_win(): # ---adding frames--- # top name frame -top = Frame(root, - width=1300, - height=200, - bg=GREEN_2, - bd=8, - relief="groove") +top = Frame(root, width=1300, height=200, bg=GREEN_2, bd=8, relief="groove") top.grid(row=0, column=0, padx=10, pady=5) # frame for canvas -canvas = Canvas(root, - width=1000, - height=380, - bg=WHITE) +canvas = Canvas(root, width=1000, height=380, bg=WHITE) canvas.grid(row=1, column=0, padx=10, pady=5) # frame for user entries -entries = Frame(root, - width=1300, - height=300, - bg=GREEN_2, - bd=8, - relief="groove") +entries = Frame(root, width=1300, height=300, bg=GREEN_2, bd=8, relief="groove") entries.grid(row=2, column=0, padx=10, pady=5) # ---adding widgets--- # top label -greeting = Label(top, - text="Quick Sort Visualizer", - width=62, - font=("Courier New", 20, "bold"), - background=GREEN_2) +greeting = Label( + top, + text="Quick Sort Visualizer", + width=62, + font=("Courier New", 20, "bold"), + background=GREEN_2, +) greeting.grid(row=0, column=1, pady=5) # user entries and buttons # row 0 -Size = Label(entries, - text="Size of array : ", - bg=LIGHT_GREY, - relief="groove") -Size.grid(row=0, - column=0, - padx=15, - pady=5, - sticky=W, - ipadx=20, - ipady=5) +Size = Label(entries, text="Size of array : ", bg=LIGHT_GREY, relief="groove") +Size.grid(row=0, column=0, padx=15, pady=5, sticky=W, ipadx=20, ipady=5) sizeEntry = Entry(entries, justify="center") sizeEntry.grid(row=0, column=1, padx=15, pady=5, sticky=W, ipady=5) -minn = Label(entries, - text="Minimum element : ", - bg=LIGHT_GREY, - relief="groove") +minn = Label(entries, text="Minimum element : ", bg=LIGHT_GREY, relief="groove") minn.grid(row=0, column=2, padx=15, pady=5, sticky=W, ipadx=20, ipady=5) minEntry = Entry(entries, justify="center") minEntry.grid(row=0, column=3, padx=15, pady=5, sticky=W, ipady=5) -maxx = Label(entries, - text="Maximum element : ", - bg=LIGHT_GREY, - relief="groove") +maxx = Label(entries, text="Maximum element : ", bg=LIGHT_GREY, relief="groove") maxx.grid(row=0, column=4, padx=15, pady=5, sticky=W, ipadx=20, ipady=5) maxEntry = Entry(entries, justify="center") maxEntry.grid(row=0, column=5, padx=15, pady=5, sticky=W, ipady=5) diff --git a/speech_alarm/script.py b/speech_alarm/script.py index dc7d4c4d1..441c85963 100644 --- a/speech_alarm/script.py +++ b/speech_alarm/script.py @@ -1,16 +1,16 @@ -import speech_recognition as sr -import winsound import datetime -import pyttsx3 +import winsound +import pyttsx3 +import speech_recognition as sr engine = pyttsx3.init() def speech(audio): - engine.setProperty('rate', 200) - voices = engine.getProperty('voices') - engine.setProperty('voice', voices[0].id) + engine.setProperty("rate", 200) + voices = engine.getProperty("voices") + engine.setProperty("voice", voices[0].id) engine.say(audio) engine.runAndWait() @@ -28,7 +28,7 @@ def takeCommand(): try: print("Recognizing...") print() - query = r.recognize_google(audio, language='en-in') + query = r.recognize_google(audio, language="en-in") print(f"you said: {query}\n") except Exception as e: @@ -52,9 +52,12 @@ def alarm(Timing): print(f"Done, alarm is set for {Timing}") while True: - if Horeal == datetime.datetime.now().hour and Mireal == datetime.datetime.now().minute: + if ( + Horeal == datetime.datetime.now().hour + and Mireal == datetime.datetime.now().minute + ): print("alarm is running please exit the program") - winsound.PlaySound('abc', winsound.SND_LOOP) + winsound.PlaySound("abc", winsound.SND_LOOP) elif Mireal < datetime.datetime.now().minute: break diff --git a/speech_recognition_news/newsapi.py b/speech_recognition_news/newsapi.py index e09789355..7a242fb6b 100644 --- a/speech_recognition_news/newsapi.py +++ b/speech_recognition_news/newsapi.py @@ -1,11 +1,11 @@ -import os -import requests import json -from dotenv import load_dotenv, find_dotenv -from newspaper import Article -from newspaper import Config +import os from datetime import datetime +import requests +from dotenv import find_dotenv, load_dotenv +from newspaper import Article, Config + news_information = dict() failed_port_connection = [] @@ -18,13 +18,11 @@ def get_top_news(news_information, todays_date): load_dotenv(find_dotenv(r"path to env variable")) news_api_key = os.getenv("news_api") params = ( - ('country', 'us'), - ('apiKey', f'{news_api_key}'), + ("country", "us"), + ("apiKey", f"{news_api_key}"), ) - response = requests.get( - """https://newsapi.org/v2/top-headlines""", - params=params) - news_articles = response.json()['articles'] + response = requests.get("""https://newsapi.org/v2/top-headlines""", params=params) + news_articles = response.json()["articles"] for i in news_articles: user_agent = """Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:78.0) @@ -32,13 +30,18 @@ def get_top_news(news_information, todays_date): config = Config() config.browser_user_agent = user_agent config.request_timeout = 10 - article = Article(i['url'], config=config) + article = Article(i["url"], config=config) print(i["url"]) article.download() article.parse() article.nlp() summary = article.summary # noqa - news_information[i["source"]["name"]] = {"title": i["title"], "summary": summary, "url": i["url"], "date": f"{todays_date}"} # noqa + news_information[i["source"]["name"]] = { + "title": i["title"], + "summary": summary, + "url": i["url"], + "date": f"{todays_date}", + } # noqa def json_file(news_information, todays_date): diff --git a/speedTest/SpeedTest.py b/speedTest/SpeedTest.py index 0f220a9bf..3553e8a8b 100644 --- a/speedTest/SpeedTest.py +++ b/speedTest/SpeedTest.py @@ -1,5 +1,5 @@ -from plyer import notification import speedtest +from plyer import notification st = speedtest.Speedtest(secure=True) @@ -9,13 +9,15 @@ download = st.download() / 1048576 upload = st.upload() / 1048576 ping = st.results.ping -country = st.results.server['country'] -city_of_country = st.results.server['name'] +country = st.results.server["country"] +city_of_country = st.results.server["name"] # printing the data print(f"Speedtest from a server located in {city_of_country}, {country}") -print(f"Download Speed: {download:.2f} Mbps, \nUpload Speed: {upload:.2f} Mbps,\nPing: {ping} ms") +print( + f"Download Speed: {download:.2f} Mbps, \nUpload Speed: {upload:.2f} Mbps,\nPing: {ping} ms" +) # displaying the notification @@ -23,5 +25,5 @@ title=f"Speedtest from a server located in {city_of_country}, {country}", message=f"Download Speed: {download:.2f} Mbps, \nUpload Speed: {upload:.2f} Mbps,\nPing: {ping} ms", # displaying time - timeout=5 + timeout=5, ) diff --git a/speed_tester/speed_tester.py b/speed_tester/speed_tester.py index 397b99583..c3eac38c7 100644 --- a/speed_tester/speed_tester.py +++ b/speed_tester/speed_tester.py @@ -1,7 +1,8 @@ -import speedtest -import subprocess import platform import re +import subprocess + +import speedtest def ping_google(): @@ -9,8 +10,7 @@ def ping_google(): system = platform.system().lower() option = "n" if system == "windows" else "c" res = subprocess.check_output( - f"ping -{option} 10 google.com", - shell=True, universal_newlines=True + f"ping -{option} 10 google.com", shell=True, universal_newlines=True ) if "unreachable" in res: return False diff --git a/spell_corrector/spell_corrector.py b/spell_corrector/spell_corrector.py index a27ae37a5..8f1c1a2f7 100644 --- a/spell_corrector/spell_corrector.py +++ b/spell_corrector/spell_corrector.py @@ -1,14 +1,14 @@ +from tkinter import Tk, filedialog + from textblob import TextBlob -from tkinter import Tk -from tkinter import filedialog gui = Tk() -gui.filename = filedialog.askopenfilename(initialdir="/", - title="Select file", - filetypes=(("txt files", - ".txt"), - ("all files", ".*"))) -f = open(gui.filename, 'r') +gui.filename = filedialog.askopenfilename( + initialdir="/", + title="Select file", + filetypes=(("txt files", ".txt"), ("all files", ".*")), +) +f = open(gui.filename, "r") s = [] for i in f: s.append(i) @@ -16,7 +16,7 @@ for i in range(len(s)): s[i] = TextBlob(s[i]) s[i] = s[i].correct() -f = open(gui.filename, 'w') +f = open(gui.filename, "w") for i in range(len(s)): s[i] = str(s[i]) f.write(s[i]) diff --git a/sticky_notes/sticky_notes.py b/sticky_notes/sticky_notes.py index e015ab62c..dbc2ef706 100644 --- a/sticky_notes/sticky_notes.py +++ b/sticky_notes/sticky_notes.py @@ -1,7 +1,7 @@ -from tkinter import Tk, Label, Frame, Entry, Button, Listbox, Scrollbar, TclError -from tkinter.font import Font -from tkinter import END, TOP, BOTTOM, ANCHOR, LEFT, BOTH, RIGHT, FLAT import ctypes +from tkinter import (ANCHOR, BOTH, BOTTOM, END, FLAT, LEFT, RIGHT, TOP, Button, + Entry, Frame, Label, Listbox, Scrollbar, TclError, Tk) +from tkinter.font import Font ctypes.windll.shcore.SetProcessDpiAwareness(True) @@ -9,9 +9,10 @@ def err(msg): - error.config(text=f"Error: {msg}", fg="red", font=('Sans Serif', 18)) + error.config(text=f"Error: {msg}", fg="red", font=("Sans Serif", 18)) error.pack(pady=20) + # Tkinter button functions @@ -21,8 +22,7 @@ def add_note(): else: error.pack_forget() start_msg.pack_forget() - notes_list.insert( - END, f"{notes_list.size() + 1}. " + notes_entry.get()) + notes_list.insert(END, f"{notes_list.size() + 1}. " + notes_entry.get()) notes_entry.delete(0, END) notes_list.see("end") @@ -68,9 +68,9 @@ def uncheck_note(): # Main window root = Tk() -root.title('Python Sticky notes') -root.geometry('600x600') -root.config(bg='#d3d3d3') +root.title("Python Sticky notes") +root.geometry("600x600") +root.config(bg="#d3d3d3") root.iconbitmap("./favicon.ico") root.resizable(False, False) @@ -85,21 +85,26 @@ def uncheck_note(): notes_frame.pack(pady=10) # Welcome Message -start_msg = Label(notes_frame, text="Enter a note to get started...", font=( - "Sans serif", 18), fg="darkgrey") +start_msg = Label( + notes_frame, + text="Enter a note to get started...", + font=("Sans serif", 18), + fg="darkgrey", +) start_msg.pack(side=TOP) # Main ListBox for notes -notes_list = Listbox(notes_frame, - font=my_font, - width=25, - height=5, - bd=0, - bg="SystemButtonFace", - selectbackground="grey", - activestyle="none", - highlightthickness=0 - ) +notes_list = Listbox( + notes_frame, + font=my_font, + width=25, + height=5, + bd=0, + bg="SystemButtonFace", + selectbackground="grey", + activestyle="none", + highlightthickness=0, +) notes_list.pack(side=LEFT, fill=BOTH) # Scrollbar for notes_frame @@ -120,12 +125,11 @@ def uncheck_note(): # Buttons add_button = Button(function_button_frame, text="Add note", command=add_note) -delete_button = Button(function_button_frame, - text="Delete note", command=delete_note) -checked_button = Button(function_button_frame, - text="Check item", command=check_note) -unchecked_button = Button(function_button_frame, - text="Uncheck item", command=uncheck_note) +delete_button = Button(function_button_frame, text="Delete note", command=delete_note) +checked_button = Button(function_button_frame, text="Check item", command=check_note) +unchecked_button = Button( + function_button_frame, text="Uncheck item", command=uncheck_note +) add_button.grid(row=0, column=0) delete_button.grid(row=0, column=1, padx=10) @@ -136,9 +140,10 @@ def uncheck_note(): error = Label(root) # Author Info -author = Label(root, text="© Swaraj Baral\nGithub: SwarajBaral", - bg="#d3d3d3", fg="grey") +author = Label( + root, text="© Swaraj Baral\nGithub: SwarajBaral", bg="#d3d3d3", fg="grey" +) author.pack(side=BOTTOM) -if __name__ == '__main__': +if __name__ == "__main__": root.mainloop() diff --git a/stocks_visualizer/visualise_prices.py b/stocks_visualizer/visualise_prices.py index 387249fcf..b3f60b966 100644 --- a/stocks_visualizer/visualise_prices.py +++ b/stocks_visualizer/visualise_prices.py @@ -1,8 +1,10 @@ -from nsetools import Nse -import requests -from datetime import datetime as dt, timedelta -import plotly.graph_objects as go +from datetime import datetime as dt +from datetime import timedelta + import pandas as pd +import plotly.graph_objects as go +import requests +from nsetools import Nse nse = Nse() headers = { diff --git a/stop_watch/Stopwatch.py b/stop_watch/Stopwatch.py index 69f72fb4b..fd8312c75 100644 --- a/stop_watch/Stopwatch.py +++ b/stop_watch/Stopwatch.py @@ -19,7 +19,7 @@ def count(): string = tt.strftime("%H:%M:%S") display = string - label['text'] = display # Or label.config(text=display) + label["text"] = display # Or label.config(text=display) # label.after(arg1, arg2) delays by # first argument given in milliseconds @@ -39,17 +39,17 @@ def Start(label): global running running = True counter_label(label) - start['state'] = 'disabled' - stop['state'] = 'normal' - reset['state'] = 'normal' + start["state"] = "disabled" + stop["state"] = "normal" + reset["state"] = "normal" # Stop function of the stopwatch def Stop(): global running - start['state'] = 'normal' - stop['state'] = 'disabled' - reset['state'] = 'normal' + start["state"] = "normal" + stop["state"] = "disabled" + reset["state"] = "normal" running = False @@ -60,12 +60,12 @@ def Reset(label): # If reset is pressed after pressing stop. if running is False: - reset['state'] = 'disabled' - label['text'] = 'Welcome!' + reset["state"] = "disabled" + label["text"] = "Welcome!" # If reset is pressed while the stopwatch is running. else: - label['text'] = 'Starting' + label["text"] = "Starting" root = Tkinter.Tk() @@ -73,15 +73,15 @@ def Reset(label): # Fixing the window size. root.minsize(width=250, height=70) -label = Tkinter.Label(root, text="Welcome!", fg="black", - font="Verdana 30 bold") +label = Tkinter.Label(root, text="Welcome!", fg="black", font="Verdana 30 bold") label.pack() f = Tkinter.Frame(root) -start = Tkinter.Button(f, text='Start', width=6, command=lambda: Start(label)) -stop = Tkinter.Button(f, text='Stop', width=6, state='disabled', command=Stop) -reset = Tkinter.Button(f, text='Reset', width=6, state='disabled', - command=lambda: Reset(label)) -f.pack(anchor='center', pady=5) +start = Tkinter.Button(f, text="Start", width=6, command=lambda: Start(label)) +stop = Tkinter.Button(f, text="Stop", width=6, state="disabled", command=Stop) +reset = Tkinter.Button( + f, text="Reset", width=6, state="disabled", command=lambda: Reset(label) +) +f.pack(anchor="center", pady=5) start.pack(side="left") stop.pack(side="left") reset.pack(side="left") diff --git a/straighten_image/straighten_image.py b/straighten_image/straighten_image.py index fa5c9a889..dbe2221a5 100644 --- a/straighten_image/straighten_image.py +++ b/straighten_image/straighten_image.py @@ -1,9 +1,9 @@ -import cv2 import math + +import cv2 import numpy as np from scipy import ndimage - path = "test.jpg" image = cv2.imread(path) image_edges = cv2.Canny(image, 100, 100, apertureSize=3) diff --git a/subtitle_creator/subtitle_creator.py b/subtitle_creator/subtitle_creator.py index b73fe565a..914b4a55e 100644 --- a/subtitle_creator/subtitle_creator.py +++ b/subtitle_creator/subtitle_creator.py @@ -1,9 +1,10 @@ -import moviepy.editor as mp -import speech_recognition as sr -import wave import contextlib -from moviepy.editor import VideoFileClip, TextClip, CompositeVideoClip import sys +import wave + +import moviepy.editor as mp +import speech_recognition as sr +from moviepy.editor import CompositeVideoClip, TextClip, VideoFileClip def get_audio(filename): @@ -12,7 +13,7 @@ def get_audio(filename): def get_file_length(audiofile): - with contextlib.closing(wave.open(audiofile, 'r')) as f: + with contextlib.closing(wave.open(audiofile, "r")) as f: frames = f.getnframes() rate = f.getframerate() duration = frames / float(rate) @@ -36,10 +37,12 @@ def get_text(audiofile="audio.wav"): def write_text(text_chunks, original_video, output, font_size=15): txt_clips = [] for i in range(len(text_chunks)): - txt_clips.append(TextClip(text_chunks[i], fontsize=font_size, color="yellow") - .set_position('bottom') - .set_duration(3) - .set_start(i * 3)) + txt_clips.append( + TextClip(text_chunks[i], fontsize=font_size, color="yellow") + .set_position("bottom") + .set_duration(3) + .set_start(i * 3) + ) clips = [original_video] clips.extend(txt_clips) result = CompositeVideoClip(clips) diff --git a/subtitle_downloader/subtitle_downloader.py b/subtitle_downloader/subtitle_downloader.py index 2334565aa..ed4b35bf7 100644 --- a/subtitle_downloader/subtitle_downloader.py +++ b/subtitle_downloader/subtitle_downloader.py @@ -1,5 +1,6 @@ # Importing necessary modules import sys + from youtube_transcript_api import YouTubeTranscriptApi if len(sys.argv) != 2: diff --git a/sudoku_solver/solve_sudoku.py b/sudoku_solver/solve_sudoku.py index 0a60c9e6b..61d9b7e17 100644 --- a/sudoku_solver/solve_sudoku.py +++ b/sudoku_solver/solve_sudoku.py @@ -1,6 +1,6 @@ def is_number_valid(row, col, num): # function to find if the number is valid or not in the respective space - global grid # making grid as global variable + global grid # making grid as global variable for i in range(0, 9): # for loop to find if the number is present in the row or not if grid[row][i] == num: @@ -17,11 +17,11 @@ def is_number_valid(row, col, num): for j in range(0, 3): if grid[row_subset + i][col_subset + j] == num: return False - return True # if not preent in the all the possibilities returns True + return True # if not preent in the all the possibilities returns True def print_board(): # function to print the puzzle after solving - global grid # global variables + global grid # global variables for i in range(len(grid)): # for loop to print the board if i % 3 == 0 and i != 0: print("- - - - - - - - - - - - - ") @@ -56,9 +56,11 @@ def solve_sudoku(): grid[row][col] = 0 return print("\nSoltion is:") - print_board() # calls the print_board function + print_board() # calls the print_board function # if user presses enter then function is called again input("Check for more solution?") + + # takes each line of the sudoku as input with spaces between two numbers diff --git a/system_information/sys_info.py b/system_information/sys_info.py index 97f6d8ec5..4754b3fe1 100644 --- a/system_information/sys_info.py +++ b/system_information/sys_info.py @@ -1,7 +1,8 @@ -import psutil import platform from datetime import datetime +import psutil + print("+----------------------+") print("| System Information |") print("+----------------------+") diff --git a/take_a_break/TakeABreak.py b/take_a_break/TakeABreak.py index c8d0bfe24..8d5e38568 100644 --- a/take_a_break/TakeABreak.py +++ b/take_a_break/TakeABreak.py @@ -1,5 +1,5 @@ -import webbrowser import time +import webbrowser total_breaks = int(3) break_count = int(0) diff --git a/tar_py/tar_py.py b/tar_py/tar_py.py index 600f2cf2c..797879f46 100644 --- a/tar_py/tar_py.py +++ b/tar_py/tar_py.py @@ -1,5 +1,5 @@ -import tarfile import os +import tarfile def list_tar(archive, verbosity): @@ -44,14 +44,14 @@ def create_tar(archive, folder_name, compression=None): def get_tar_mode(compression): """Determine tarfile open mode according to the given compression.""" - if compression == 'gzip': - return 'w:gz' - if compression == 'bzip2': - return 'w:bz2' - if compression == 'lzma': - return 'w:xz' + if compression == "gzip": + return "w:gz" + if compression == "bzip2": + return "w:bz2" + if compression == "lzma": + return "w:xz" if compression: - msg = 'pytarfile does not support %s for tar compression' + msg = "pytarfile does not support %s for tar compression" print(msg) # no compression - return 'w' + return "w" diff --git a/telegram_backup/telebackup.py b/telegram_backup/telebackup.py index 3500486e5..aae9ef717 100644 --- a/telegram_backup/telebackup.py +++ b/telegram_backup/telebackup.py @@ -8,4 +8,4 @@ with Client("my_account", api_id, api_hash) as app: for file in sys.argv[1:]: app.send_document("me", file) - print(f'[+] Successfully uploaded {file}.') + print(f"[+] Successfully uploaded {file}.") diff --git a/telegram_forward_bot/bot.py b/telegram_forward_bot/bot.py index 1461d9b18..32415cd54 100644 --- a/telegram_forward_bot/bot.py +++ b/telegram_forward_bot/bot.py @@ -1,20 +1,23 @@ from telethon import TelegramClient, events + # from telethon.tl.functions.messages import ForwardMessagesRequest api_id = 111111 # Replace 111111 with Your Telegram API ID -api_hash = 'Your Telegram Hash ID' -client = TelegramClient('anon', api_id, api_hash) +api_hash = "Your Telegram Hash ID" +client = TelegramClient("anon", api_id, api_hash) -@client.on(events. NewMessage(outgoing=False)) +@client.on(events.NewMessage(outgoing=False)) async def handler(event): chat_id = event.chat_id -# Let's print all the chat ids you are incoming messages from + # Let's print all the chat ids you are incoming messages from print(chat_id) if chat_id == 22222: # Replace 22222 with the Chat Id of the origin message Here msg = event.raw_text - await client. send_message(44444, msg) + await client.send_message(44444, msg) + + # Replace 44444 with the Chat Id of of the Chat Where To Send client.start() client.run_until_disconnected() diff --git a/telegram_quotefancy/telegram_quotefancy.py b/telegram_quotefancy/telegram_quotefancy.py index 1df66277d..96cf45a65 100644 --- a/telegram_quotefancy/telegram_quotefancy.py +++ b/telegram_quotefancy/telegram_quotefancy.py @@ -1,7 +1,8 @@ # ----- imports ----- import time -import schedule + import requests +import schedule from quotefancy import get_quote # Some Required Vars diff --git a/temp_email/temp_email.py b/temp_email/temp_email.py index 73bac0f66..108edbdc3 100644 --- a/temp_email/temp_email.py +++ b/temp_email/temp_email.py @@ -1,27 +1,30 @@ -from typing import Optional -import requests import time import uuid +from typing import Optional + +import requests class Maildrop(object): _apikey = "QM8VTHrLR2JloKTJMZ3N6Qa93FVsx8LapKCzEjui" _inbox = "https://api.maildrop.cc/v2/mailbox" - _search_fields = ("sender", "subject", "body",) + _search_fields = ( + "sender", + "subject", + "body", + ) def __init__( - self, - address: Optional[str] = None, - message_filter: Optional[str] = None + self, address: Optional[str] = None, message_filter: Optional[str] = None ) -> None: """Create an instance of the Maildrop.cc client. - :param address: Optional address to monitor on maildrop. - Can be a full email with or without domain. - Defaults to a random uuid. - Note the address if you plan to re-use it in the future. - :param message_filter: Optional text to search for in - sender, subject, and body fields. + :param address: Optional address to monitor on maildrop. + Can be a full email with or without domain. + Defaults to a random uuid. + Note the address if you plan to re-use it in the future. + :param message_filter: Optional text to search for in + sender, subject, and body fields. """ if address and "@" in address: # drop the domain from the email address @@ -37,10 +40,9 @@ def __init__( self._seen = set() self._emails = list() self._client = requests.Session() - self._client.headers.update({ - "Content-Type": "application/json", - "x-api-key": self._apikey - }) + self._client.headers.update( + {"Content-Type": "application/json", "x-api-key": self._apikey} + ) print(f"maildrop address set to {self._address}@maildrop.cc") @property @@ -56,9 +58,9 @@ def emails(self) -> list: def _get_body(self, email_id: str) -> str: """Retrieves the body of an email. - :param email_id: The unique identifier of the email to retrieve. - :returns: The body of the requested email. - :rtype: str + :param email_id: The unique identifier of the email to retrieve. + :returns: The body of the requested email. + :rtype: str """ resp = self._client.get(f"{self._inbox}/{self._address}/{email_id}") if not resp.ok: @@ -81,10 +83,12 @@ def get_emails(self) -> list: self._seen.add(email_id) email["body"] = self._get_body(email_id) if self._filter: - if any([ - self._filter in email.get(field, "") - for field in self._search_fields - ]): + if any( + [ + self._filter in email.get(field, "") + for field in self._search_fields + ] + ): new_emails.append(email) else: new_emails.append(email) @@ -94,9 +98,9 @@ def get_emails(self) -> list: def monitor_inbox(self, interval: int = 5) -> None: """Check for unseen emails at an interval until told to stop. - :param interval: Optional number of seconds to wait - before re-checking for unseen emails. - Defaults to 5 seconds. + :param interval: Optional number of seconds to wait + before re-checking for unseen emails. + Defaults to 5 seconds. """ print(f"checking inbox every {interval} seconds") print("to stop monitoring loop, press & hold ctrl+c") @@ -119,6 +123,7 @@ def monitor_inbox(self, interval: int = 5) -> None: if __name__ == "__main__": import argparse + parser = argparse.ArgumentParser() parser.add_argument( "-a", @@ -127,7 +132,7 @@ def monitor_inbox(self, interval: int = 5) -> None: "A specific maildrop.cc email address to monitor. " "If omitted, a randomly-generated UUID4 is used." ), - default=None + default=None, ) parser.add_argument( "-f", @@ -136,7 +141,7 @@ def monitor_inbox(self, interval: int = 5) -> None: "A string to search for in new emails. " "If omitted, all new emails are returned." ), - default=None + default=None, ) args = parser.parse_args() md = Maildrop(address=args.address, message_filter=args.filter) diff --git a/text_encryptor/aes_enc_dec.py b/text_encryptor/aes_enc_dec.py index 55ea86142..91b13519a 100644 --- a/text_encryptor/aes_enc_dec.py +++ b/text_encryptor/aes_enc_dec.py @@ -1,6 +1,7 @@ -import sys import base64 import math +import sys + try: from Crypto.Cipher import AES except ImportError: @@ -18,18 +19,20 @@ def GetKey(): global KEY tempKey = input("Enter password(min length: 8, max length: 32)") - while (len(tempKey.strip()) < 8 or len(tempKey.strip()) > 32 or ' ' in tempKey): - if (' ' in tempKey): + while len(tempKey.strip()) < 8 or len(tempKey.strip()) > 32 or " " in tempKey: + if " " in tempKey: print("White spaces are not allowed!") else: - print("Password must be at least 8 characters long and at max 32 characters long. Try Again!") - while (len(tempKey) % 8 != 0): + print( + "Password must be at least 8 characters long and at max 32 characters long. Try Again!" + ) + while len(tempKey) % 8 != 0: tempKey = tempKey + PADDING_CHARACTER KEY = tempKey def AES_Encryption(cleartext): - if (len(KEY) < 8 or len(KEY) % 8 != 0): + if len(KEY) < 8 or len(KEY) % 8 != 0: print("Password is corrupted. Exiting!") sys.exit() return @@ -38,31 +41,33 @@ def AES_Encryption(cleartext): nearest_multiple_of_16 = 16 * math.ceil(cleartext_length / 16) padded_cleartext = cleartext.rjust(nearest_multiple_of_16) raw_ciphertext = AES_Encryptor.encrypt(padded_cleartext) - return base64.b64encode(raw_ciphertext).decode('utf-8') + return base64.b64encode(raw_ciphertext).decode("utf-8") def AES_Decryption(ciphertext): - if (len(KEY) < 8 or len(KEY) % 8 != 0): + if len(KEY) < 8 or len(KEY) % 8 != 0: print("Password is corrupted. Exiting!") sys.exit() return AES_Decryptor = AES.new(KEY, AES.MODE_CBC, VECTOR_FOR_AES) raw_ciphertext = base64.b64decode(ciphertext) decrypted_message_with_padding = AES_Decryptor.decrypt(raw_ciphertext) - return decrypted_message_with_padding.decode('utf-8').strip() + return decrypted_message_with_padding.decode("utf-8").strip() if __name__ == "__main__": type = "S" - while (type not in "ed"): + while type not in "ed": type = input("Encrypt or Decrypt the text(e/d): ") type = type.strip().lower() - if (len(type) != 1): + if len(type) != 1: type = "S" GetKey() - if (type == "e"): - print("NOTE: If you forget this password, you will not be able'\ - ' to decrypt text correctly. So, DO NOT FORGET PASSWORD!!") + if type == "e": + print( + "NOTE: If you forget this password, you will not be able'\ + ' to decrypt text correctly. So, DO NOT FORGET PASSWORD!!" + ) message = input("Enter message in single line: ") ciphertext = AES_Encryption(message) print("Encrypted Message: %s" % ciphertext) diff --git a/text_from_image/main.py b/text_from_image/main.py index de51bd731..10f43ab0c 100644 --- a/text_from_image/main.py +++ b/text_from_image/main.py @@ -1,7 +1,6 @@ import cv2 import pytesseract - tesseract_path = r"D:\Saransh\Softwares\Tesseract-OCR\tesseract.exe" image_path = "test.png" file_path = "output.txt" diff --git a/text_summarize/text_summarize.py b/text_summarize/text_summarize.py index 70fb63c14..2ebca6883 100644 --- a/text_summarize/text_summarize.py +++ b/text_summarize/text_summarize.py @@ -1,4 +1,5 @@ import argparse + from summarizer import Summarizer @@ -10,31 +11,33 @@ def text_summarize(text, **kwargs): return model(text, **kwargs) -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description='Summarize the given text') - parser.add_argument('-t', '--text', help="Text to summarize", - type=str) - parser.add_argument('-f', '--file', help="Filename to read text from", - type=str) - parser.add_argument('-r', '--ratio', - help="Given the ratio of the summarized text " - "(default: 0.2)", - type=float, default=0.2) - parser.add_argument('-o', '--output', - help="Given the path to an output file. " - "Otherwise stdout will be used", - type=str, default=None) +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Summarize the given text") + parser.add_argument("-t", "--text", help="Text to summarize", type=str) + parser.add_argument("-f", "--file", help="Filename to read text from", type=str) + parser.add_argument( + "-r", + "--ratio", + help="Given the ratio of the summarized text " "(default: 0.2)", + type=float, + default=0.2, + ) + parser.add_argument( + "-o", + "--output", + help="Given the path to an output file. " "Otherwise stdout will be used", + type=str, + default=None, + ) args = parser.parse_args() if not (args.text or args.file): parser.error("Either --text or --file is required") if args.text and args.file: - parser.error("The arguments --text and --file are not " - "allowed together") + parser.error("The arguments --text and --file are not " "allowed together") if args.file: - with open(args.file, 'r') as infile: + with open(args.file, "r") as infile: text = infile.readlines() text = "\n".join(text) if args.text: @@ -42,7 +45,7 @@ def text_summarize(text, **kwargs): summary = text_summarize(text, ratio=args.ratio) if args.output: - with open(args.output, 'w') as outfile: + with open(args.output, "w") as outfile: outfile.write(summary) outfile.write("\n") else: diff --git a/text_to_sound/text_to_sound.py b/text_to_sound/text_to_sound.py index 32857ae1c..3400eb753 100644 --- a/text_to_sound/text_to_sound.py +++ b/text_to_sound/text_to_sound.py @@ -1,7 +1,8 @@ from gtts import gTTS from playsound import playsound -text_val = 'All the best for your exam.' -language = 'en' + +text_val = "All the best for your exam." +language = "en" obj = gTTS(text=text_val, lang=language, slow=False) obj.save("exam.mp3") playsound("exam.mp3") diff --git a/time_zone_conversion/time_zone.py b/time_zone_conversion/time_zone.py index 59af59d30..8d097640c 100644 --- a/time_zone_conversion/time_zone.py +++ b/time_zone_conversion/time_zone.py @@ -1,10 +1,12 @@ class InvalidHours(Exception): """Invalid""" + pass class InvalidMins(Exception): """Invalid""" + pass @@ -47,16 +49,16 @@ class InvalidMins(Exception): if hours1 > 12: hours1 = hours1 - 12 - if ampm == 'am': - ampm = 'pm' - elif ampm == 'pm': - ampm = 'am' + if ampm == "am": + ampm = "pm" + elif ampm == "pm": + ampm = "am" elif hours1 < 0: hours1 = hours1 + 12 - if ampm == 'am': - ampm = 'pm' - elif ampm == 'pm': - ampm = 'am' + if ampm == "am": + ampm = "pm" + elif ampm == "pm": + ampm = "am" if end_zone == "CST": hours1 = hours1 - 6 @@ -69,16 +71,16 @@ class InvalidMins(Exception): if hours1 > 12: hours1 = hours1 - 12 - if ampm == 'am': - ampm = 'pm' - elif ampm == 'pm': - ampm = 'am' + if ampm == "am": + ampm = "pm" + elif ampm == "pm": + ampm = "am" elif hours1 < 0: hours1 = hours1 + 12 - if ampm == 'am': - ampm = 'pm' - elif ampm == 'pm': - ampm = 'am' + if ampm == "am": + ampm = "pm" + elif ampm == "pm": + ampm = "am" # Result -print('Time: ' + str(hours1) + ":" + str(mins1) + ampm) +print("Time: " + str(hours1) + ":" + str(mins1) + ampm) diff --git a/timezone_cli/tz_tool.py b/timezone_cli/tz_tool.py index 1d522129d..ad5f1e71e 100644 --- a/timezone_cli/tz_tool.py +++ b/timezone_cli/tz_tool.py @@ -1,22 +1,23 @@ -import sys import getopt +import sys from datetime import datetime -from pytz import timezone + from dateutil.relativedelta import relativedelta +from pytz import timezone # --- INFO ON PARAMS --- def print_help(): - print('[+] use --cu and pass custom timezone to find time.') - print('[+] use --cm to get the time of common timezones around the world.') - print('[+] use --cmp and pass two \'-\' seperated timezones to compare.') - print('[+] use --help again if needed.') - print('\n' + '-' * 50 + '\n') + print("[+] use --cu and pass custom timezone to find time.") + print("[+] use --cm to get the time of common timezones around the world.") + print("[+] use --cmp and pass two '-' seperated timezones to compare.") + print("[+] use --help again if needed.") + print("\n" + "-" * 50 + "\n") # --- GET DATETIME OF PASSED TIMEZONE --- def get_datetime(time_zone): - utcnow = timezone('utc').localize(datetime.utcnow()) + utcnow = timezone("utc").localize(datetime.utcnow()) output_datetime = utcnow.astimezone(timezone(time_zone)).replace(tzinfo=None) return output_datetime @@ -24,80 +25,80 @@ def get_datetime(time_zone): # --- GET DATETIME OF CUSTOM TIMEZONE --- def get_custom_tz(time_zone): response = str(get_datetime(time_zone)) - print(f'%20s' % 'Timezone' + ' :' + ' ' * 2 + time_zone) # noqa - date, time = response.split(' ') - hours, minutes, seconds = time.split(':') - print('%20s' % 'Hours' + ' :' + ' ' * 2 + hours) - print('%20s' % 'Minutes' + ' :' + ' ' * 2 + minutes) - print('%20s' % 'Seconds' + ' :' + ' ' * 2 + seconds) - print('%20s' % 'Date' + ' :' + ' ' * 2 + date) - print('\n' + '-' * 50 + '\n') + print(f"%20s" % "Timezone" + " :" + " " * 2 + time_zone) # noqa + date, time = response.split(" ") + hours, minutes, seconds = time.split(":") + print("%20s" % "Hours" + " :" + " " * 2 + hours) + print("%20s" % "Minutes" + " :" + " " * 2 + minutes) + print("%20s" % "Seconds" + " :" + " " * 2 + seconds) + print("%20s" % "Date" + " :" + " " * 2 + date) + print("\n" + "-" * 50 + "\n") # --- GET DATETIMES OF COMMON TIMEZONES --- def get_common_tz(): common_tz_list = [ - 'America/Sao_Paulo', - 'America/New_York', - 'America/Mexico_City', - 'Asia/Kolkata', - 'Asia/Tokyo', - 'Europe/Paris', - 'Europe/Berlin', - 'Africa/Johannesburg', - 'Africa/Casablanca', - 'Australia/Melbourne', + "America/Sao_Paulo", + "America/New_York", + "America/Mexico_City", + "Asia/Kolkata", + "Asia/Tokyo", + "Europe/Paris", + "Europe/Berlin", + "Africa/Johannesburg", + "Africa/Casablanca", + "Australia/Melbourne", ] for item in common_tz_list: - print('%-20s' % item, end='') - print(':' + ' ' * 2 + str(get_datetime(item))) - print('\n' + '-' * 50 + '\n') + print("%-20s" % item, end="") + print(":" + " " * 2 + str(get_datetime(item))) + print("\n" + "-" * 50 + "\n") # --- COMPARE DIFFERENCES BTW TWO TIMEZONES --- def get_comparisons(tz_1, tz_2): offset = relativedelta(get_datetime(tz_1), get_datetime(tz_2)) - print('%25s' % 'Comparing :', tz_1) - print('%25s' % 'With :', tz_2) - print('') - print('%25s' % 'Hours :', offset.hours) - print('%25s' % 'Minutes :', offset.minutes) - print('%25s' % 'Seconds :', offset.seconds) - print('\n' + '-' * 50 + '\n') + print("%25s" % "Comparing :", tz_1) + print("%25s" % "With :", tz_2) + print("") + print("%25s" % "Hours :", offset.hours) + print("%25s" % "Minutes :", offset.minutes) + print("%25s" % "Seconds :", offset.seconds) + print("\n" + "-" * 50 + "\n") # --- MAIN FUNCTION --- def Main(): - print('\n' + '-' * 50 + '\n') - print(' ' * 16 + 'TIMEZONE TOOL') - print('\n' + '-' * 50 + '\n') + print("\n" + "-" * 50 + "\n") + print(" " * 16 + "TIMEZONE TOOL") + print("\n" + "-" * 50 + "\n") # --- SET DEFAULTS --- argument_list = sys.argv[1:] - options = '' - long_options = ['cu=', 'cm', 'cp=', 'help'] + options = "" + long_options = ["cu=", "cm", "cp=", "help"] # --- TRY-CATCH BLOCK FOR ARGS --- try: args, _ = getopt.getopt(argument_list, shortopts=options, longopts=long_options) for current_argument, current_value in args: - if current_argument in ('--help'): + if current_argument in ("--help"): print_help() - if current_argument in ('--cu'): + if current_argument in ("--cu"): get_custom_tz(current_value) - if current_argument in ('--cm'): + if current_argument in ("--cm"): get_common_tz() - if current_argument in ('--cp'): - timezones = current_value.split('-') + if current_argument in ("--cp"): + timezones = current_value.split("-") if len(timezones) == 2: get_comparisons(timezones[0], timezones[1]) else: - print(' ' * 5, '[+] Seperate the Timezones with \'-\'') - print('\n' + '-' * 50 + '\n') + print(" " * 5, "[+] Seperate the Timezones with '-'") + print("\n" + "-" * 50 + "\n") except getopt.error as error: print(str(error)) -if __name__ == '__main__': +if __name__ == "__main__": Main() diff --git a/tkinter_python_gui/USWeatherForecast.py b/tkinter_python_gui/USWeatherForecast.py index 62544f91d..6502ab71a 100644 --- a/tkinter_python_gui/USWeatherForecast.py +++ b/tkinter_python_gui/USWeatherForecast.py @@ -1,13 +1,15 @@ import tkinter as tk import tkinter.ttk as ttk + import requests # Free Open Weather API (https://rapidapi.com/community/api/open-weather-map/) url = "https://community-open-weather-map.p.rapidapi.com/forecast" -headers = {'x-rapidapi-host': "community-open-weather-map.p.rapidapi.com", - 'x-rapidapi-key': - "8e9e50a21bmshda23fe83770e19ep14a949jsn482dfa5dc300"} +headers = { + "x-rapidapi-host": "community-open-weather-map.p.rapidapi.com", + "x-rapidapi-key": "8e9e50a21bmshda23fe83770e19ep14a949jsn482dfa5dc300", +} # initialize tkinter GUI root = tk.Tk() @@ -18,9 +20,14 @@ # Initialize table for US city weather information def createTable(data, city): - weather_view['columns'] = ('city', 'temperature', - 'minTemp', 'maxTemp', - 'condition', 'description') + weather_view["columns"] = ( + "city", + "temperature", + "minTemp", + "maxTemp", + "condition", + "description", + ) weather_view.column("#0", width=0, stretch=tk.NO) weather_view.column("city", anchor=tk.CENTER, width=85) weather_view.column("temperature", anchor=tk.CENTER, width=95) @@ -31,8 +38,7 @@ def createTable(data, city): weather_view.heading("#0", text="", anchor=tk.CENTER) weather_view.heading("city", text="City Name", anchor=tk.CENTER) - weather_view.heading("temperature", text="Temperature (F)", - anchor=tk.CENTER) + weather_view.heading("temperature", text="Temperature (F)", anchor=tk.CENTER) weather_view.heading("minTemp", text="Min Temp", anchor=tk.CENTER) weather_view.heading("maxTemp", text="Max Temp", anchor=tk.CENTER) weather_view.heading("condition", text="Condition", anchor=tk.CENTER) @@ -43,21 +49,33 @@ def createTable(data, city): # Populate table with weather information for each new US city def NewEntry(data, city): try: - temp = str(round((((int(data['list'][1]['main']['temp']) - - 273.15) * 1.8) + 32), 2)) - temp_min = str(round((((int(data['list'][1]['main']['temp_min']) - - 273.15) * 1.8) + 32), 2)) - temp_max = str(round((((int(data['list'][1]['main']['temp_max']) - - 273.15) * 1.8) + 32), 2)) - weather = data['list'][2]['weather'][0]['main'] - weather_desc = data['list'][2]['weather'][0]['description'] - weather_view.insert(parent='', index='end', iid=None, text='', - values=(city, temp, temp_min, temp_max, - weather, weather_desc)) + temp = str( + round((((int(data["list"][1]["main"]["temp"]) - 273.15) * 1.8) + 32), 2) + ) + temp_min = str( + round((((int(data["list"][1]["main"]["temp_min"]) - 273.15) * 1.8) + 32), 2) + ) + temp_max = str( + round((((int(data["list"][1]["main"]["temp_max"]) - 273.15) * 1.8) + 32), 2) + ) + weather = data["list"][2]["weather"][0]["main"] + weather_desc = data["list"][2]["weather"][0]["description"] + weather_view.insert( + parent="", + index="end", + iid=None, + text="", + values=(city, temp, temp_min, temp_max, weather, weather_desc), + ) weather_view.grid(columnspan=3, row=3) except Exception: - weather_view.insert(parent='', index='end', iid=None, text='', - values=(city, None, None, None, None, None)) + weather_view.insert( + parent="", + index="end", + iid=None, + text="", + values=(city, None, None, None, None, None), + ) weather_view.grid(columnspan=3, row=3) @@ -69,7 +87,7 @@ def NewEntry(data, city): # Weather Tracker application - title label = tk.Label(root, text="US Weather Tracker") label.grid(columnspan=3, row=0, pady=30) -label.configure(font=("Courier", 25, "bold"), fg='#092653') +label.configure(font=("Courier", 25, "bold"), fg="#092653") # Weather Tracker application - title desc = tk.Label(root, text="Provide a US city name below...") @@ -97,8 +115,7 @@ def addWeather(): city = cityEntry.get() location = city + ",us" querystring = {"q": location} - response = requests.request("GET", url, headers=headers, - params=querystring) + response = requests.request("GET", url, headers=headers, params=querystring) createTable(response.json(), city) button_text.set("Add New City") newTable = False @@ -106,17 +123,20 @@ def addWeather(): city = cityEntry.get() location = city + ",us" querystring = {"q": location} - response = requests.request("GET", url, headers=headers, - params=querystring) + response = requests.request("GET", url, headers=headers, params=querystring) NewEntry(response.json(), city) # Button to add cities to weather forecast table -getCityWeather = tk.Button(root, textvariable=button_text, - command=addWeather, width=30, - font=("Courier", 15), - bg='#092653', - fg="white").grid(columnspan=3, row=4, pady=10) +getCityWeather = tk.Button( + root, + textvariable=button_text, + command=addWeather, + width=30, + font=("Courier", 15), + bg="#092653", + fg="white", +).grid(columnspan=3, row=4, pady=10) root.mainloop() diff --git a/todo_list/app.py b/todo_list/app.py index 490d3205f..75fe47856 100644 --- a/todo_list/app.py +++ b/todo_list/app.py @@ -1,11 +1,12 @@ -from flask import Flask, render_template, request, flash, redirect -from flask_sqlalchemy import SQLAlchemy from datetime import datetime +from flask import Flask, flash, redirect, render_template, request +from flask_sqlalchemy import SQLAlchemy + app = Flask(__name__) -app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' -app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False -app.secret_key = 'any random secret' +app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite://" +app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False +app.secret_key = "any random secret" db = SQLAlchemy(app) @@ -15,56 +16,56 @@ class TODO(db.Model): date_created = db.Column(db.DateTime, default=datetime.utcnow) def __repr__(self): - return '' % self.id + return "" % self.id -@app.route('/', methods=['POST', 'GET']) +@app.route("/", methods=["POST", "GET"]) def hello(): db.create_all() - if request.method == 'POST': - task = request.form['content'] + if request.method == "POST": + task = request.form["content"] new_task = TODO(content=task) try: db.session.add(new_task) db.session.commit() - flash('Successfully added!') - return redirect('/') + flash("Successfully added!") + return redirect("/") except Exception: - flash('An error occurred') - return redirect('/') + flash("An error occurred") + return redirect("/") else: tasks = TODO.query.order_by(TODO.date_created).all() return render_template("toDoListTemplate.html", tasks=tasks) -@app.route('/delete/') +@app.route("/delete/") def delete(id): task = TODO.query.get_or_404(id) try: db.session.delete(task) db.session.commit() - flash('Successfully deleted') - return redirect('/') + flash("Successfully deleted") + return redirect("/") except Exception: - flash('An error occurred') - return redirect('/') + flash("An error occurred") + return redirect("/") -@app.route('/modify/', methods=['POST', 'GET']) +@app.route("/modify/", methods=["POST", "GET"]) def modify(id): task = TODO.query.get_or_404(id) - if request.method == 'POST': - task.content = request.form['content'] + if request.method == "POST": + task.content = request.form["content"] try: db.session.commit() flash("Successfully updated") - return redirect('/') + return redirect("/") except Exception: flash("An error occurred") - return redirect('/') + return redirect("/") else: return render_template("toDoListTemplate.html", tasks=task) -if __name__ == '__main__': +if __name__ == "__main__": app.run() diff --git a/torrent_search/torrent_search.py b/torrent_search/torrent_search.py index 29e56eb58..db13a0a8c 100755 --- a/torrent_search/torrent_search.py +++ b/torrent_search/torrent_search.py @@ -1,65 +1,74 @@ #!/usr/bin/env python3 +import argparse import asyncio import json -import argparse -from aiohttp import ClientSession, ClientError -from aiohttp.http_exceptions import HttpProcessingError -from urllib.parse import quote from collections import defaultdict from re import sub +from urllib.parse import quote + +from aiohttp import ClientError, ClientSession +from aiohttp.http_exceptions import HttpProcessingError from bs4 import BeautifulSoup results = defaultdict(list) urlList = { - 'thepiratebay': 'https://thepiratebay10.org/search/{query}/{page}/99/0', - '1337x': 'https://1337x.to/search/{query}/{page}/', - 'torlock': 'https://www.torlock.com/all/torrents/{query}/{page}.html' + "thepiratebay": "https://thepiratebay10.org/search/{query}/{page}/99/0", + "1337x": "https://1337x.to/search/{query}/{page}/", + "torlock": "https://www.torlock.com/all/torrents/{query}/{page}.html", } category_list = { - 'anime': 'Anime', - 'applications': 'Applications', - 'documentaries': 'Documentaries', - 'games': 'Games', - 'movies': 'Movies', - 'music': 'Music', - 'other': 'Other', - 'television': 'Television', - 'xxx': 'XXX', - 'unknown': 'Unknown' + "anime": "Anime", + "applications": "Applications", + "documentaries": "Documentaries", + "games": "Games", + "movies": "Movies", + "music": "Music", + "other": "Other", + "television": "Television", + "xxx": "XXX", + "unknown": "Unknown", } def to_object( - title: str = '', - url: str = '', - magnet_link: str = '', + title: str = "", + url: str = "", + magnet_link: str = "", seeder: int = None, - leecher: int = None + leecher: int = None, ): return { - 'title': title, - 'url': url, - 'magett-link': magnet_link, - 'seeder': seeder, - 'leecher': leecher + "title": title, + "url": url, + "magett-link": magnet_link, + "seeder": seeder, + "leecher": leecher, } def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser( - description='Meta-Search-Script for torrents.' + parser = argparse.ArgumentParser(description="Meta-Search-Script for torrents.") + parser.add_argument("query", metavar="QUERY", type=str, help="the search term") + parser.add_argument( + "-s", + "--seeder-limit", + dest="seeder_limit", + type=int, + action="store", + default=0, + help="minimum number of seeders", + ) + parser.add_argument( + "-c", + "--categories", + dest="categories", + nargs="*", + default=[], + help="filter by categories", ) - parser.add_argument('query', metavar='QUERY', type=str, - help='the search term') - parser.add_argument('-s', '--seeder-limit', dest='seeder_limit', type=int, - action='store', default=0, - help='minimum number of seeders') - parser.add_argument('-c', '--categories', dest='categories', - nargs='*', default=[], - help='filter by categories') args = parser.parse_args() @@ -69,36 +78,30 @@ def parse_args() -> argparse.Namespace: return args -async def send_query( - url: str, - session: ClientSession, - headers: dict = None -) -> str: - response = await session.request(method='GET', url=url, headers=headers) +async def send_query(url: str, session: ClientSession, headers: dict = None) -> str: + response = await session.request(method="GET", url=url, headers=headers) response.raise_for_status() - return await response.text(errors='ignore') + return await response.text(errors="ignore") -async def parse_thepiratebay( - args: argparse.Namespace, - session: ClientSession -) -> None: +async def parse_thepiratebay(args: argparse.Namespace, session: ClientSession) -> None: page = 1 - while (True): + while True: try: - html = await send_query(urlList['thepiratebay'].format_map({ - 'query': quote(args.query), - 'page': page}), - session + html = await send_query( + urlList["thepiratebay"].format_map( + {"query": quote(args.query), "page": page} + ), + session, ) except (ClientError, HttpProcessingError): break - soup = BeautifulSoup(html, 'html.parser') + soup = BeautifulSoup(html, "html.parser") try: - rows = soup.find('div', id='main-content').find_all('tr')[1:-1] + rows = soup.find("div", id="main-content").find_all("tr")[1:-1] except AttributeError: break @@ -106,19 +109,14 @@ async def parse_thepiratebay( break for row in rows: - columns = row.find_all('td') - category = sub(r'\W+', ' ', columns[0].find('a').text).strip() - category = category_list.get( - category.lower(), - category_list.get('unknown') - ) + columns = row.find_all("td") + category = sub(r"\W+", " ", columns[0].find("a").text).strip() + category = category_list.get(category.lower(), category_list.get("unknown")) title = sub( - '[\n\t]+', - ' ', - columns[1].find('div', class_='detName').text + "[\n\t]+", " ", columns[1].find("div", class_="detName").text ).strip() - url = columns[1].find('a', href=True)['href'] - magnet_link = columns[1].find_all('a')[1]['href'] + url = columns[1].find("a", href=True)["href"] + magnet_link = columns[1].find_all("a")[1]["href"] seeder = int(columns[2].text.strip()) leecher = int(columns[3].text.strip()) @@ -129,62 +127,60 @@ async def parse_thepiratebay( if seeder < args.seeder_limit: continue - results[category].append(to_object( - title=title, - url=url, - magnet_link=magnet_link, - seeder=seeder, - leecher=leecher - )) + results[category].append( + to_object( + title=title, + url=url, + magnet_link=magnet_link, + seeder=seeder, + leecher=leecher, + ) + ) page += 1 -async def parse_1337x( - args: argparse.Namespace, - session: ClientSession -) -> None: +async def parse_1337x(args: argparse.Namespace, session: ClientSession) -> None: category_mappings = { - '6': category_list.get('television'), - '9': category_list.get('documentaries'), - '10': category_list.get('games'), - '18': category_list.get('applications'), - '19': category_list.get('applications'), - '22': category_list.get('music'), - '23': category_list.get('music'), - '28': category_list.get('anime'), - '36': category_list.get('other'), - '41': category_list.get('television'), - '42': category_list.get('movies'), - '48': category_list.get('xxx'), - '50': category_list.get('other'), - '51': category_list.get('xxx'), - '52': category_list.get('other'), - '53': category_list.get('music'), - '56': category_list.get('applications'), - '59': category_list.get('music'), - '71': category_list.get('television'), - '75': category_list.get('television'), - '78': category_list.get('anime'), - '80': category_list.get('anime'), + "6": category_list.get("television"), + "9": category_list.get("documentaries"), + "10": category_list.get("games"), + "18": category_list.get("applications"), + "19": category_list.get("applications"), + "22": category_list.get("music"), + "23": category_list.get("music"), + "28": category_list.get("anime"), + "36": category_list.get("other"), + "41": category_list.get("television"), + "42": category_list.get("movies"), + "48": category_list.get("xxx"), + "50": category_list.get("other"), + "51": category_list.get("xxx"), + "52": category_list.get("other"), + "53": category_list.get("music"), + "56": category_list.get("applications"), + "59": category_list.get("music"), + "71": category_list.get("television"), + "75": category_list.get("television"), + "78": category_list.get("anime"), + "80": category_list.get("anime"), } page = 1 - while (True): + while True: try: - html = await send_query(urlList['1337x'].format_map({ - 'query': quote(args.query), - 'page': page}), - session + html = await send_query( + urlList["1337x"].format_map({"query": quote(args.query), "page": page}), + session, ) except (ClientError, HttpProcessingError): break - soup = BeautifulSoup(html, 'html.parser') + soup = BeautifulSoup(html, "html.parser") try: - rows = soup.find('table', class_='table-list').find_all('tr')[1:] + rows = soup.find("table", class_="table-list").find_all("tr")[1:] except AttributeError: break @@ -192,14 +188,11 @@ async def parse_1337x( break for row in rows: - columns = row.find_all('td') - category = columns[0].find_all('a')[0]['href'].split('/')[2] - category = category_mappings.get( - category, - category_list.get('unknown') - ) - title = columns[0].find_all('a')[1].text.strip() - url = 'https://1337x.to' + columns[0].find_all('a')[1]['href'] + columns = row.find_all("td") + category = columns[0].find_all("a")[0]["href"].split("/")[2] + category = category_mappings.get(category, category_list.get("unknown")) + title = columns[0].find_all("a")[1].text.strip() + url = "https://1337x.to" + columns[0].find_all("a")[1]["href"] seeder = int(columns[1].text.strip()) leecher = int(columns[2].text.strip()) @@ -210,48 +203,46 @@ async def parse_1337x( if seeder < args.seeder_limit: continue - results[category].append(to_object( - title=title, - url=url, - seeder=seeder, - leecher=leecher - )) + results[category].append( + to_object(title=title, url=url, seeder=seeder, leecher=leecher) + ) page += 1 async def parse_torlock(args, session: ClientSession) -> None: category_mappings = { - 'tv0': category_list.get('other'), - 'tv1': category_list.get('movie'), - 'tv2': category_list.get('music'), - 'tv3': category_list.get('television'), - 'tv4': category_list.get('games'), - 'tv5': category_list.get('application'), - 'tv6': category_list.get('anime'), - 'tv7': category_list.get('xxx'), - 'tv8': category_list.get('other'), - 'tv9': category_list.get('other'), - 'tv10': category_list.get('television'), - 'tv12': category_list.get('other') + "tv0": category_list.get("other"), + "tv1": category_list.get("movie"), + "tv2": category_list.get("music"), + "tv3": category_list.get("television"), + "tv4": category_list.get("games"), + "tv5": category_list.get("application"), + "tv6": category_list.get("anime"), + "tv7": category_list.get("xxx"), + "tv8": category_list.get("other"), + "tv9": category_list.get("other"), + "tv10": category_list.get("television"), + "tv12": category_list.get("other"), } page = 1 - while (True): + while True: try: - html = await send_query(urlList['torlock'].format_map({ - 'query': quote(args.query), - 'page': page}), - session + html = await send_query( + urlList["torlock"].format_map( + {"query": quote(args.query), "page": page} + ), + session, ) except (ClientError, HttpProcessingError): break - soup = BeautifulSoup(html, 'html.parser') + soup = BeautifulSoup(html, "html.parser") try: - rows = soup.find_all('table')[4].find_all('tr')[1:] + rows = soup.find_all("table")[4].find_all("tr")[1:] except AttributeError: break @@ -259,14 +250,11 @@ async def parse_torlock(args, session: ClientSession) -> None: break for row in rows: - columns = row.find_all('td') - category = columns[0].find('span')['class'][0] - category = category_mappings.get( - category, - category_list.get('unknown') - ) - title = columns[0].find('a').text.strip() - url = 'https://torlock.to' + columns[0].find('a')['href'] + columns = row.find_all("td") + category = columns[0].find("span")["class"][0] + category = category_mappings.get(category, category_list.get("unknown")) + title = columns[0].find("a").text.strip() + url = "https://torlock.to" + columns[0].find("a")["href"] seeder = int(columns[3].text.strip()) leecher = int(columns[4].text.strip()) @@ -277,22 +265,15 @@ async def parse_torlock(args, session: ClientSession) -> None: if seeder < args.seeder_limit: continue - results[category].append(to_object( - title=title, - url=url, - seeder=seeder, - leecher=leecher - )) + results[category].append( + to_object(title=title, url=url, seeder=seeder, leecher=leecher) + ) page += 1 async def run(args): - task_list = [ - parse_thepiratebay, - parse_1337x, - parse_torlock - ] + task_list = [parse_thepiratebay, parse_1337x, parse_torlock] async with ClientSession() as session: for i in range(len(task_list)): diff --git a/tweet_bot/config.py b/tweet_bot/config.py index 4aecb3140..6f581cc90 100644 --- a/tweet_bot/config.py +++ b/tweet_bot/config.py @@ -1,8 +1,9 @@ #!/usr/bin/env python3 -import tweepy import logging import os +import tweepy + logger = logging.getLogger() diff --git a/tweet_bot/favretweet.py b/tweet_bot/favretweet.py index cf3d82d56..6979d401c 100644 --- a/tweet_bot/favretweet.py +++ b/tweet_bot/favretweet.py @@ -1,9 +1,9 @@ #!/usr/bin/env python3 -import tweepy import logging -from config import create_api +import tweepy +from config import create_api logging.basicConfig(level=logging.INFO) logger = logging.getLogger() diff --git a/tweet_bot/followfollowers.py b/tweet_bot/followfollowers.py index 5ac591bbc..77a1e13d5 100644 --- a/tweet_bot/followfollowers.py +++ b/tweet_bot/followfollowers.py @@ -1,18 +1,19 @@ #!/usr/bin/env python3 -import tweepy import logging -from config import create_api import time +import tweepy +from config import create_api + logging.basicConfig(level=logging.INFO) logger = logging.getLogger() -''' +""" A lot of Twitter API endpoints use pagination to return their results. Tweepy cursors take away part of the complexity of working with paginated results. The Cursor object is iterable and takes care of fetching the various result pages transparently. -''' +""" def follow_followers(api): diff --git a/tweet_bot/tweet-cli.py b/tweet_bot/tweet-cli.py index bcf79e1cb..e6a4b3e79 100644 --- a/tweet_bot/tweet-cli.py +++ b/tweet_bot/tweet-cli.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 from sys import argv + from config import create_api usage = """ diff --git a/tweet_scraper/tweet_scraper.py b/tweet_scraper/tweet_scraper.py index 7eab4b5c4..a5de0dd40 100644 --- a/tweet_scraper/tweet_scraper.py +++ b/tweet_scraper/tweet_scraper.py @@ -1,8 +1,8 @@ import os -import tweepy +import tweepy -username = "saranshchopra7" # edit the username here +username = "saranshchopra7" # edit the username here number_of_tweets = 100 # max can be 200 # API keys diff --git a/url_shortener/url.py b/url_shortener/url.py index b6b70b9ed..c28a09d56 100644 --- a/url_shortener/url.py +++ b/url_shortener/url.py @@ -1,8 +1,9 @@ # Title :- URL Shortener # The URL shortener is application which takes url input from user and shorts it -import pyshorteners import sys +import pyshorteners + # url converter function def make_short(url): @@ -16,5 +17,5 @@ def main(): print(cooked_url) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/video_cropper/video_cropper.py b/video_cropper/video_cropper.py index 462bc1c11..d56119fd7 100644 --- a/video_cropper/video_cropper.py +++ b/video_cropper/video_cropper.py @@ -1,51 +1,78 @@ -import ffmpeg import argparse -import sys import os +import sys + +import ffmpeg def to_int(a, rel_to): - ''' + """ Converts string to integer. If string contains "%" it converts it to a float and multiplies by rel_to EG: 50% -> 0.5*rel_to - ''' + """ if type(a) == int: return a else: - if '%' in a: - return int((int(a.replace('%', '')) / 100) * rel_to) + if "%" in a: + return int((int(a.replace("%", "")) / 100) * rel_to) else: return int(a) -if __name__ == '__main__': +if __name__ == "__main__": # set up the arguments to be parsed parser = argparse.ArgumentParser() - parser.add_argument('-i', '--input', type=str, help='the file to crop') - parser.add_argument('-c', '--crop', type=str, help='the amount to crop in the format "TOP,BOTTOM,LEFT,RIGHT"') - parser.add_argument('-t', '--top', type=str, help='the amount to crop off the top of the video') - parser.add_argument('-b', '--bottom', type=str, help='the amount to crop off the bottom of the video') - parser.add_argument('-l', '--left', type=str, help='the amount to crop off the left of the video') - parser.add_argument('-r', '--right', type=str, help='the amount to crop off the right of the video') - parser.add_argument('-o', '--output', type=str, help='the file to output to (cannot be the same as input file)') - parser.add_argument('-y', '--yes', action='store_true', help='skip the prompt to confirm overwriting a file') + parser.add_argument("-i", "--input", type=str, help="the file to crop") + parser.add_argument( + "-c", + "--crop", + type=str, + help='the amount to crop in the format "TOP,BOTTOM,LEFT,RIGHT"', + ) + parser.add_argument( + "-t", "--top", type=str, help="the amount to crop off the top of the video" + ) + parser.add_argument( + "-b", + "--bottom", + type=str, + help="the amount to crop off the bottom of the video", + ) + parser.add_argument( + "-l", "--left", type=str, help="the amount to crop off the left of the video" + ) + parser.add_argument( + "-r", "--right", type=str, help="the amount to crop off the right of the video" + ) + parser.add_argument( + "-o", + "--output", + type=str, + help="the file to output to (cannot be the same as input file)", + ) + parser.add_argument( + "-y", + "--yes", + action="store_true", + help="skip the prompt to confirm overwriting a file", + ) args = parser.parse_args() # check whether the user is using the --crop arg # or a combination of the --left, --right, --top, --bottom args if args.crop is not None: - args.crop = args.crop.split(',') + args.crop = args.crop.split(",") if len(args.crop) == 4: # check it is the right length crop = { - 'top': args.crop[0], - 'bottom': args.crop[1], - 'left': args.crop[2], - 'right': args.crop[3] + "top": args.crop[0], + "bottom": args.crop[1], + "left": args.crop[2], + "right": args.crop[3], } else: # if the length is not 4 then the format is not supported @@ -55,55 +82,55 @@ def to_int(a, rel_to): sys.exit(1) else: # parse all of the other possible crop kwargs - crop = {'top': 0, 'bottom': 0, 'left': 0, 'right': 0} + crop = {"top": 0, "bottom": 0, "left": 0, "right": 0} if args.top: - crop['top'] = args.top + crop["top"] = args.top if args.bottom: - crop['bottom'] = args.bottom + crop["bottom"] = args.bottom if args.left: - crop['left'] = args.left + crop["left"] = args.left if args.right: - crop['right'] = args.right + crop["right"] = args.right # if no values were supplied all crops will equal 0 if all(i == 0 for i in crop.values()): - sys.stderr.write('ERROR: no crop applied. All crops equal to 0') + sys.stderr.write("ERROR: no crop applied. All crops equal to 0") sys.exit(1) # validate that args.input is a file if args.input is None or not os.path.isfile(args.input): - sys.stderr.write('ERROR: input file does not exist') + sys.stderr.write("ERROR: input file does not exist") sys.exit(1) # find the video data for the input file # and find it's default video stream (the first one) metadata = ffmpeg.probe(args.input) vid_stream = None - for stream in metadata['streams']: - if stream['codec_type'] == 'video': + for stream in metadata["streams"]: + if stream["codec_type"] == "video": vid_stream = stream break # if no video stream has been found we cannot crop it if vid_stream is None: - sys.stderr.write('ERROR: could not find valid video stream in file') + sys.stderr.write("ERROR: could not find valid video stream in file") sys.exit(1) # convert all crop values to an integer - crop['top'] = to_int(crop['top'], vid_stream['height']) - crop['bottom'] = to_int(crop['bottom'], vid_stream['height']) - crop['left'] = to_int(crop['left'], vid_stream['width']) - crop['right'] = to_int(crop['right'], vid_stream['width']) + crop["top"] = to_int(crop["top"], vid_stream["height"]) + crop["bottom"] = to_int(crop["bottom"], vid_stream["height"]) + crop["left"] = to_int(crop["left"], vid_stream["width"]) + crop["right"] = to_int(crop["right"], vid_stream["width"]) # calculate the new width and height of the video - width = vid_stream['width'] - (crop['left'] + crop['right']) - height = vid_stream['height'] - (crop['top'] + crop['bottom']) + width = vid_stream["width"] - (crop["left"] + crop["right"]) + height = vid_stream["height"] - (crop["top"] + crop["bottom"]) if width <= 0: # the new width cannot be less than or equal to 0 - sys.stderr.write('ERROR: resulting width must be greater than 0') + sys.stderr.write("ERROR: resulting width must be greater than 0") sys.exit(1) if height <= 0: # the new height cannot be less than or equal to 0 - sys.stderr.write('ERROR: resulting height must be greater than 0') + sys.stderr.write("ERROR: resulting height must be greater than 0") sys.exit(1) # call ffmpeg with the required args @@ -112,9 +139,9 @@ def to_int(a, rel_to): args.input, width, height, - crop['left'], - crop['top'], + crop["left"], + crop["top"], "-y " if args.yes else "", - args.output + args.output, ) os.system(cmd) diff --git a/video_desaturator/video_desaturator.py b/video_desaturator/video_desaturator.py index 0e5970088..30c20d26b 100644 --- a/video_desaturator/video_desaturator.py +++ b/video_desaturator/video_desaturator.py @@ -1,29 +1,35 @@ import argparse -import sys import os +import sys - -if __name__ == '__main__': +if __name__ == "__main__": # set up the arguments to be parsed parser = argparse.ArgumentParser() - parser.add_argument('-l', '--level', type=int, help='the saturation percentage to use (default: 0, max: 300)') - parser.add_argument('-y', '--yes', action='store_true', help='skip the prompt to overwrite the file') - parser.add_argument('in_file', type=str, help='the file to desaturate') - parser.add_argument('out_file', type=str, help='the file to output to') + parser.add_argument( + "-l", + "--level", + type=int, + help="the saturation percentage to use (default: 0, max: 300)", + ) + parser.add_argument( + "-y", "--yes", action="store_true", help="skip the prompt to overwrite the file" + ) + parser.add_argument("in_file", type=str, help="the file to desaturate") + parser.add_argument("out_file", type=str, help="the file to output to") args = parser.parse_args() # check if the supplied file exists if not os.path.isfile(args.in_file): - sys.stderr.write('ERROR: input file does not exist') + sys.stderr.write("ERROR: input file does not exist") sys.exit(1) # check that the level given is within range level = 0 if args.level is not None: if args.level < 0 or args.level > 300: - sys.stderr.write('ERROR: saturation level must be between 0 and 300') + sys.stderr.write("ERROR: saturation level must be between 0 and 300") sys.exit(1) level = args.level @@ -33,10 +39,5 @@ # create the ffmpeg command and run it cmd = 'ffmpeg -hide_banner -loglevel error -i "{}" -c:a copy -vf "eq=saturation={}" {}{}' - cmd = cmd.format( - args.in_file, - level, - "-y " if args.yes else "", - args.out_file - ) + cmd = cmd.format(args.in_file, level, "-y " if args.yes else "", args.out_file) os.system(cmd) diff --git a/video_merger/video_merger.py b/video_merger/video_merger.py index fea6aff84..cdbad26eb 100644 --- a/video_merger/video_merger.py +++ b/video_merger/video_merger.py @@ -1,8 +1,8 @@ import sys -import ffmpeg +import ffmpeg -if __name__ == '__main__': +if __name__ == "__main__": print(sys.argv) print(len(sys.argv)) print(str(sys.argv[len(sys.argv) - 1])) @@ -10,4 +10,6 @@ for i in range(1, len(sys.argv) - 1): list.write("file {}\n".format(sys.argv[i])) list.close() - ffmpeg.input("list.txt", format='concat', safe=0).output(sys.argv[len(sys.argv) - 1], c='copy').run() + ffmpeg.input("list.txt", format="concat", safe=0).output( + sys.argv[len(sys.argv) - 1], c="copy" + ).run() diff --git a/video_player/videoplayer.py b/video_player/videoplayer.py index b35d17b8b..daa654a11 100644 --- a/video_player/videoplayer.py +++ b/video_player/videoplayer.py @@ -1,14 +1,15 @@ -import cv2 import sys +import cv2 + def play_video(cap): is_paused = False - while (cap.isOpened()): + while cap.isOpened(): if not is_paused: ret, frame = cap.read() if ret: - cv2.imshow('Frame', frame) + cv2.imshow("Frame", frame) key = cv2.waitKey(25) if key == 113: break @@ -33,5 +34,5 @@ def cap_check(path): return cap -if __name__ == '__main__': +if __name__ == "__main__": cleanup(play_video(cap_check(sys.argv[1]))) diff --git a/video_textadder/video-textadder.py b/video_textadder/video-textadder.py index 7675368aa..c123c278a 100644 --- a/video_textadder/video-textadder.py +++ b/video_textadder/video-textadder.py @@ -1,7 +1,8 @@ +import argparse +import os + from moviepy.editor import CompositeVideoClip, VideoFileClip from moviepy.video.VideoClip import TextClip -import os -import argparse # Define the base directory base_dir = os.path.dirname(os.path.abspath(__file__)) @@ -9,31 +10,25 @@ # Define CLI arguments parser = argparse.ArgumentParser() parser.add_argument( - '-f', + "-f", type=str, - help='The file path of target video. ' + help="The file path of target video. " + 'ex. /home/user/example.mp4.\nDefault value is "demo.mp4"', - default=base_dir + '/demo.mp4' + default=base_dir + "/demo.mp4", ) parser.add_argument( - '-t', + "-t", type=str, - help='The text you want to add to video top. ' - + 'ex. "Hellow Video"', - default='This is demo example' + help="The text you want to add to video top. " + 'ex. "Hellow Video"', + default="This is demo example", ) parser.add_argument( - '-s', - type=int, - help='The font size of video watermark. ' - + 'ex. 30', - default='30' + "-s", type=int, help="The font size of video watermark. " + "ex. 30", default="30" ) parser.add_argument( - '-n', + "-n", type=str, - help='The new file name.\n' - + 'Default value is {current file name}_title.mp4', + help="The new file name.\n" + "Default value is {current file name}_title.mp4", ) # Define Variable @@ -46,15 +41,18 @@ while True: try: video = VideoFileClip(video_path) - print('video resultion: ', video.size) + print("video resultion: ", video.size) break except Exception: print( - 'Directory or file is not valid,' - + ' please enter a valid file directory ...') - video_path = str(input('Enter the video path again (absolute path without space): ')) + "Directory or file is not valid," + + " please enter a valid file directory ..." + ) + video_path = str( + input("Enter the video path again (absolute path without space): ") + ) -origin_file = (lambda x: x.split('/')[-1])(video_path) +origin_file = (lambda x: x.split("/")[-1])(video_path) if args.n: new_file = args.n @@ -63,12 +61,14 @@ def add_text(content, font_size): - ''' + """ add text on the top of video stream - ''' - txt_clip = (TextClip(content, fontsize=font_size, color='white') - .set_position('top') - .set_duration(video.duration)) + """ + txt_clip = ( + TextClip(content, fontsize=font_size, color="white") + .set_position("top") + .set_duration(video.duration) + ) result = CompositeVideoClip([video, txt_clip]) result.write_videofile(new_file) @@ -77,5 +77,5 @@ def main(): add_text(video_watermark, font_size) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/video_to_audio/video-to-audio.py b/video_to_audio/video-to-audio.py index 8eafa9879..641fd046e 100644 --- a/video_to_audio/video-to-audio.py +++ b/video_to_audio/video-to-audio.py @@ -1,6 +1,7 @@ import moviepy.editor as mp + video = input("Please enter the path to video: ") video = mp.VideoFileClip(video) dst = input("Please enter the output directory: ") -dst = dst + '/converted.mp3' +dst = dst + "/converted.mp3" video.audio.write_audiofile(dst) diff --git a/video_togif/video2gif.py b/video_togif/video2gif.py index 40c3d8eab..ee5d104a8 100644 --- a/video_togif/video2gif.py +++ b/video_togif/video2gif.py @@ -14,6 +14,7 @@ class HighestQuality(ConversionQuality): """ Requires imageio module """ + def __init__(self): ConversionQuality.__init__(self, 1.0, 12, "imageio") @@ -37,7 +38,7 @@ def convert2gif(path, quality=MediumQuality(), out_filename=None): return out_filename -if __name__ == '__main__': +if __name__ == "__main__": file = input("Write the file name: ") result = convert2gif(file) print("Generated GIF at " + result) diff --git a/video_watermark/main.py b/video_watermark/main.py index df6bbc981..77ccba7b2 100644 --- a/video_watermark/main.py +++ b/video_watermark/main.py @@ -1,18 +1,19 @@ # Made by Maxim Iliouchenko (https://github.com/maxily1) # Importing Libraries -from moviepy.editor import * # noqa: F403, E261 import argparse +from moviepy.editor import * # noqa: F403, E261 + # Creating an argument parser -parser = argparse.ArgumentParser(description='Process video path and data') +parser = argparse.ArgumentParser(description="Process video path and data") # Adding arguments -parser.add_argument('-p', type=str, required=True, help="File Name") -parser.add_argument('-t', type=str, required=True, help="Watermark Text") -parser.add_argument('-f', type=str, required=True, help="Watermark Text Font") -parser.add_argument('-c', type=str, required=True, help="Watermark Text Color") -parser.add_argument('-s', type=int, required=True, help="Font size") +parser.add_argument("-p", type=str, required=True, help="File Name") +parser.add_argument("-t", type=str, required=True, help="Watermark Text") +parser.add_argument("-f", type=str, required=True, help="Watermark Text Font") +parser.add_argument("-c", type=str, required=True, help="Watermark Text Color") +parser.add_argument("-s", type=int, required=True, help="Font size") # Parsing Args args = parser.parse_args() @@ -25,20 +26,24 @@ font_size = args.s # Start of code -clip = VideoFileClip(file_name, audio=True) # noqa: F405, E261 +clip = VideoFileClip(file_name, audio=True) # noqa: F405, E261 w, h = clip.size # A clip with a text, and semi-opaque bg -text = TextClip( # noqa: F405, E261 - watermark_text, font=font_choice, # noqa: E126, E261 - color=color_choice, fontsize=font_size # noqa: E126, E261 - ) # noqa: E123, E261, E126 +text = TextClip( # noqa: F405, E261 + watermark_text, + font=font_choice, # noqa: E126, E261 + color=color_choice, + fontsize=font_size, # noqa: E126, E261 +) # noqa: E123, E261, E126 text_col = text.on_color( - size=(clip.w + text.w, text.h - 10), # noqa: E126, E261 - color=(0, 0, 0), pos=(6, 'center'), col_opacity=0.6 - ) # noqa: E123, E261 + size=(clip.w + text.w, text.h - 10), # noqa: E126, E261 + color=(0, 0, 0), + pos=(6, "center"), + col_opacity=0.6, +) # noqa: E123, E261 # Save the file -final_clip = CompositeVideoClip([clip, text_col]) # noqa: F405, E261 +final_clip = CompositeVideoClip([clip, text_col]) # noqa: F405, E261 final_clip.duration = clip.duration -final_clip.write_videofile("Output.mp4", fps=24, codec='libx264') +final_clip.write_videofile("Output.mp4", fps=24, codec="libx264") diff --git a/video_watermarker/water_marker.py b/video_watermarker/water_marker.py index ab9dc0b78..64298c70a 100644 --- a/video_watermarker/water_marker.py +++ b/video_watermarker/water_marker.py @@ -7,14 +7,16 @@ video = mp.VideoFileClip("input.mp4") # Declaring a couple different constraints for the watermarker -mark = (mp.ImageClip("mark.png") - .set_duration(video.duration) - .resize(height=100) - .margin(right=8, top=8, opacity=0) - .set_pos(("right", "bottom"))) +mark = ( + mp.ImageClip("mark.png") + .set_duration(video.duration) + .resize(height=100) + .margin(right=8, top=8, opacity=0) + .set_pos(("right", "bottom")) +) # Combining the watermark with the video final = mp.CompositeVideoClip([video, mark]) # Writes the edited video to a file -final.write_videofile("output.mp4", audio_codec='aac') +final.write_videofile("output.mp4", audio_codec="aac") diff --git a/virtual_keyboard/main.py b/virtual_keyboard/main.py index 3cc686efc..8dd11f4ad 100644 --- a/virtual_keyboard/main.py +++ b/virtual_keyboard/main.py @@ -1,92 +1,182 @@ -from tkinter import Tk, Button, END, Label, Canvas, Frame, PhotoImage, NW -from tkinter import messagebox -import tkinter.messagebox as mbox import tkinter as tk +import tkinter.messagebox as mbox +from tkinter import (END, NW, Button, Canvas, Frame, Label, PhotoImage, Tk, + messagebox) root = Tk() root.title("Virtual Keyboard") -root.geometry('1000x700') +root.geometry("1000x700") class Keypad(tk.Frame): cells = [ - ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], - ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', - 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'], - ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', - 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'], - ['!', '@', '#', '$', '%', '&', '*', '/', '\'', '.', ',', ';', ':', '?', - '<', '>', '😀', '😋', '😂', '🌞', '🌴', '🍕', '🏳', '♻', '✔', '👍'], + ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"], + [ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h", + "i", + "j", + "k", + "l", + "m", + "n", + "o", + "p", + "q", + "r", + "s", + "t", + "u", + "v", + "w", + "x", + "y", + "z", + ], + [ + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + "I", + "J", + "K", + "L", + "M", + "N", + "O", + "P", + "Q", + "R", + "S", + "T", + "U", + "V", + "W", + "X", + "Y", + "Z", + ], + [ + "!", + "@", + "#", + "$", + "%", + "&", + "*", + "/", + "'", + ".", + ",", + ";", + ":", + "?", + "<", + ">", + "😀", + "😋", + "😂", + "🌞", + "🌴", + "🍕", + "🏳", + "♻", + "✔", + "👍", + ], ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.target = None - self.memory = '' + self.memory = "" for y, row in enumerate(self.cells): for x, item in enumerate(row): - b = tk.Button(self, - text=item, - command=lambda text=item: self.append(text), - font=("Arial", 14), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") - b.grid(row=y, column=x, sticky='news') - - x = tk.Button(self, - text='Space', - command=self.space, - font=("Arial", 14), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") - x.grid(row=0, column=10, columnspan='4', sticky='news') - - x = tk.Button(self, - text='tab', - command=self.tab, - font=("Arial", 14), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") - x.grid(row=0, column=14, columnspan='3', sticky='news') - - x = tk.Button(self, - text='Backspace', - command=self.backspace, - font=("Arial", 14), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") - x.grid(row=0, column=17, columnspan='3', sticky='news') - - x = tk.Button(self, - text='Clear', - command=self.clear, - font=("Arial", 14), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") - x.grid(row=0, column=20, columnspan='3', sticky='news') - - x = tk.Button(self, - text='Hide', - command=self.hide, - font=("Arial", 14), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") - x.grid(row=0, column=23, columnspan='3', sticky='news') + b = tk.Button( + self, + text=item, + command=lambda text=item: self.append(text), + font=("Arial", 14), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", + ) + b.grid(row=y, column=x, sticky="news") + + x = tk.Button( + self, + text="Space", + command=self.space, + font=("Arial", 14), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", + ) + x.grid(row=0, column=10, columnspan="4", sticky="news") + + x = tk.Button( + self, + text="tab", + command=self.tab, + font=("Arial", 14), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", + ) + x.grid(row=0, column=14, columnspan="3", sticky="news") + + x = tk.Button( + self, + text="Backspace", + command=self.backspace, + font=("Arial", 14), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", + ) + x.grid(row=0, column=17, columnspan="3", sticky="news") + + x = tk.Button( + self, + text="Clear", + command=self.clear, + font=("Arial", 14), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", + ) + x.grid(row=0, column=20, columnspan="3", sticky="news") + + x = tk.Button( + self, + text="Hide", + command=self.hide, + font=("Arial", 14), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", + ) + x.grid(row=0, column=23, columnspan="3", sticky="news") def get(self): if self.target: @@ -94,11 +184,11 @@ def get(self): def append(self, text): if self.target: - self.target.insert('end', text) + self.target.insert("end", text) def clear(self): if self.target: - self.target.delete('1.0', 'end') + self.target.delete("1.0", "end") def backspace(self): if self.target: @@ -125,7 +215,7 @@ def copy(self): # TODO: copy to clipboad if self.target: self.memory = self.get() - self.label['text'] = 'memory: ' + self.memory + self.label["text"] = "memory: " + self.memory print(self.memory) def paste(self): @@ -136,19 +226,20 @@ def paste(self): def show(self, entry): self.target = entry - self.place(relx=0.5, rely=0.5, anchor='c') + self.place(relx=0.5, rely=0.5, anchor="c") def hide(self): self.target = None self.place_forget() + # ------------------------------------------------------- def print_output(): - mbox.showinfo("Text Entered", - "Text Entered :\n\n" + text_enter.get('1.0', END)) + mbox.showinfo("Text Entered", "Text Entered :\n\n" + text_enter.get("1.0", END)) + # firstclick1 = True # def on_text_enter_click(event): @@ -165,7 +256,7 @@ def des_f1(): f1 = Frame(root, height=700, width=1000) f1.propagate(0) -f1.pack(side='top') +f1.pack(side="top") # start1 = Label(f1, text='VIRTUAL', font=("Arial", 100), fg="magenta") # start1.place(x=250, y=100) @@ -178,64 +269,70 @@ def des_f1(): p1 = PhotoImage(file="Images/keyboard.png") c.create_image(200, 100, image=p1, anchor=NW) -start1 = Label(f1, - text='VIRTUAL KEYBOARD', - font=("Arial", 50), - fg="magenta", - underline=0) +start1 = Label( + f1, text="VIRTUAL KEYBOARD", font=("Arial", 50), fg="magenta", underline=0 +) start1.place(x=150, y=10) -startb = Button(f1, - text="START", - command=des_f1, - font=("Arial", 30), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") +startb = Button( + f1, + text="START", + command=des_f1, + font=("Arial", 30), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", +) startb.place(x=180, y=550) f2 = Frame(root, height=700, width=1000) f2.propagate(0) -f2.pack(side='top') +f2.pack(side="top") keypad = Keypad(root) -start2 = Label(f2, text='ENTER TEXT HERE...', font=("Arial", 40), fg="magenta") +start2 = Label(f2, text="ENTER TEXT HERE...", font=("Arial", 40), fg="magenta") start2.place(x=200, y=460) -text_enter = tk.Text(f2, - height=10, - width=80, - font=("Arial", 15), - bg="light yellow", - fg="brown", - borderwidth=3, - relief="solid") -text_enter.insert(END, 'Enter your text here from virtual keyboard...') +text_enter = tk.Text( + f2, + height=10, + width=80, + font=("Arial", 15), + bg="light yellow", + fg="brown", + borderwidth=3, + relief="solid", +) +text_enter.insert(END, "Enter your text here from virtual keyboard...") # default line in text area, can be cleared when touched # text_enter.bind('', on_text_enter_click) text_enter.place(x=50, y=10) -keyboardb = Button(f2, - text="KEYBOARD", - command=lambda: keypad.show(text_enter), - font=("Arial", 30), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") +keyboardb = Button( + f2, + text="KEYBOARD", + command=lambda: keypad.show(text_enter), + font=("Arial", 30), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", +) keyboardb.place(x=100, y=550) -printb = Button(f2, - text="PRINT", - command=print_output, - font=("Arial", 30), - bg="light green", - fg="blue", - borderwidth=3, - relief="raised") +printb = Button( + f2, + text="PRINT", + command=print_output, + font=("Arial", 30), + bg="light green", + fg="blue", + borderwidth=3, + relief="raised", +) printb.place(x=450, y=550) @@ -244,14 +341,16 @@ def exit_win(): root.destroy() -exitb = Button(root, - text="EXIT", - command=exit_win, - font=("Arial", 30), - bg="red", - fg="blue", - borderwidth=3, - relief="raised") +exitb = Button( + root, + text="EXIT", + command=exit_win, + font=("Arial", 30), + bg="red", + fg="blue", + borderwidth=3, + relief="raised", +) exitb.place(x=700, y=550) diff --git a/voice_recorder/voice_recorder.py b/voice_recorder/voice_recorder.py index 7a7e7e5cd..afb031a98 100644 --- a/voice_recorder/voice_recorder.py +++ b/voice_recorder/voice_recorder.py @@ -1,10 +1,11 @@ -import tkinter as tk import threading -import pyaudio +import tkinter as tk import wave +import pyaudio + -class App(): +class App: chunk = 1024 sample_format = pyaudio.paInt16 channels = 2 @@ -15,10 +16,18 @@ class App(): def __init__(self, master): self.isrecording = False - self.button1 = tk.Button(main, text='rec', command=self.startrecording).grid(row=1, column=0) - self.button2 = tk.Button(main, text='pause', command=self.pause).grid(row=1, column=1) - self.button3 = tk.Button(main, text='resume', command=self.resume).grid(row=1, column=2) - self.button4 = tk.Button(main, text='stop', command=self.stoprecording).grid(row=1, column=3) + self.button1 = tk.Button(main, text="rec", command=self.startrecording).grid( + row=1, column=0 + ) + self.button2 = tk.Button(main, text="pause", command=self.pause).grid( + row=1, column=1 + ) + self.button3 = tk.Button(main, text="resume", command=self.resume).grid( + row=1, column=2 + ) + self.button4 = tk.Button(main, text="stop", command=self.stoprecording).grid( + row=1, column=3 + ) def record(self): @@ -28,44 +37,49 @@ def record(self): def startrecording(self): - if (self.state == ""): + if self.state == "": self.p = pyaudio.PyAudio() - self.stream = self.p.open(format=self.sample_format, channels=self.channels, - rate=self.fs, frames_per_buffer=self.chunk, input=True) + self.stream = self.p.open( + format=self.sample_format, + channels=self.channels, + rate=self.fs, + frames_per_buffer=self.chunk, + input=True, + ) self.isrecording = True self.state = "R" - print('Recording') + print("Recording") t = threading.Thread(target=self.record) t.start() def stoprecording(self): - if (self.state == ""): + if self.state == "": print("Empty Recording Cannot be saved") else: main.destroy() self.isrecording = False self.state = "S" - print('recording complete') - self.filename = input('\nPlease Enter required Filename\n') + print("recording complete") + self.filename = input("\nPlease Enter required Filename\n") self.filename = self.filename + ".wav" - wf = wave.open(self.filename, 'wb') + wf = wave.open(self.filename, "wb") wf.setnchannels(self.channels) wf.setsampwidth(self.p.get_sample_size(self.sample_format)) wf.setframerate(self.fs) - wf.writeframes(b''.join(self.frames)) + wf.writeframes(b"".join(self.frames)) wf.close() def pause(self): - if (self.state == "R" or self.state == "Res"): + if self.state == "R" or self.state == "Res": self.isrecording = False print("Recording Paused") self.state = "P" def resume(self): - if (self.state == "P"): + if self.state == "P": self.isrecording = True self.state = "Res" print("Recording Resumed") @@ -74,7 +88,7 @@ def resume(self): main = tk.Tk() -main.title('recorder') -main.geometry('200x50') +main.title("recorder") +main.geometry("200x50") app = App(main) main.mainloop() diff --git a/voice_shutdown/automate_shutdown.py b/voice_shutdown/automate_shutdown.py index 7fcc7f276..8595af807 100644 --- a/voice_shutdown/automate_shutdown.py +++ b/voice_shutdown/automate_shutdown.py @@ -1,8 +1,9 @@ -from win32com.client import Dispatch -import speech_recognition as sr import os import time +import speech_recognition as sr +from win32com.client import Dispatch + def speak(audio): speak = Dispatch(("sapi.spvoice")) @@ -21,7 +22,7 @@ def TakeCommand(): audio = r.listen(source) try: print("Recognizing...") - Query = r.recognize_google(audio, language='en-in') + Query = r.recognize_google(audio, language="en-in") except Exception: speak("Say that again please") @@ -29,8 +30,8 @@ def TakeCommand(): return Query -while (True): - if __name__ == '__main__': +while True: + if __name__ == "__main__": Query = TakeCommand().lower() if "shut down" or "shutdown" in Query: diff --git a/voice_to_text/voice_to_text.py b/voice_to_text/voice_to_text.py index f5dc315bc..5c9d36adb 100644 --- a/voice_to_text/voice_to_text.py +++ b/voice_to_text/voice_to_text.py @@ -1,20 +1,25 @@ #!/usr/bin/env python3 -import speech_recognition as sr import argparse +import speech_recognition as sr -parser = argparse.ArgumentParser(description=("Performs" - "voice-to-text transcription on" - "audio files using" - "PocketSphinx.")) -parser.add_argument('-p', '--path', - type=str, required=True, help="Audio file path.") -parser.add_argument('-o', '--output', type=str, - required=False, help="Optional output to a file." - "By default, the recognized" - "text is printed out." - "(Choose a file name.)") +parser = argparse.ArgumentParser( + description=( + "Performs" "voice-to-text transcription on" "audio files using" "PocketSphinx." + ) +) +parser.add_argument("-p", "--path", type=str, required=True, help="Audio file path.") +parser.add_argument( + "-o", + "--output", + type=str, + required=False, + help="Optional output to a file." + "By default, the recognized" + "text is printed out." + "(Choose a file name.)", +) args = parser.parse_args() @@ -26,11 +31,11 @@ def main(): audio = r.record(infile) if args.output: output = args.output - with open(output, 'w') as outfile: + with open(output, "w") as outfile: print(r.recognize_sphinx(audio), file=outfile) else: print(r.recognize_sphinx(audio)) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/watermark_maker/main.py b/watermark_maker/main.py index d6d9b0a28..17ae5cd94 100644 --- a/watermark_maker/main.py +++ b/watermark_maker/main.py @@ -1,9 +1,8 @@ -from reportlab.pdfgen import canvas -from reportlab.lib.units import inch +from PyPDF2 import PdfFileReader, PdfFileWriter from reportlab.lib import colors from reportlab.lib.pagesizes import A4 -from PyPDF2 import PdfFileReader, PdfFileWriter - +from reportlab.lib.units import inch +from reportlab.pdfgen import canvas print("Enter file names with its extenstion!") @@ -21,10 +20,9 @@ def makeWatermark(): def makepdf(): pdf_file = input("PDF file: ") - watermark = 'watermark.pdf' + watermark = "watermark.pdf" merged = "finalDraft.pdf" - with open(pdf_file, "rb") as input_file,\ - open(watermark, "rb") as watermark_file: + with open(pdf_file, "rb") as input_file, open(watermark, "rb") as watermark_file: input_pdf = PdfFileReader(input_file) watermark_pdf = PdfFileReader(watermark_file) watermark_page = watermark_pdf.getPage(0) diff --git a/watermark_removal/watermark_removal.py b/watermark_removal/watermark_removal.py index b0be09a06..cfc48b09f 100644 --- a/watermark_removal/watermark_removal.py +++ b/watermark_removal/watermark_removal.py @@ -1,6 +1,7 @@ -import numpy as np import glob + import cv2 +import numpy as np from pdf2image import convert_from_path @@ -11,7 +12,7 @@ def pdf_to_jpg(path_to_folder, output_path): i = 0 for page in pages: - page.save(output_path + "/image%04i.jpg" % i, 'JPEG') + page.save(output_path + "/image%04i.jpg" % i, "JPEG") i += 1 diff --git a/weather_informer/weather.py b/weather_informer/weather.py index 5fb8f684e..17b909f5d 100644 --- a/weather_informer/weather.py +++ b/weather_informer/weather.py @@ -1,18 +1,18 @@ -import click import locale -import requests +import click +import requests # # # # # # # # # # # # # # # # # Constants # # # # # # # # # # # # # # # # # # -URL = 'https://wttr.in/{loc}?{fore}{metric}{col}AF&lang={lang}&format={format}' -ERR_MSG = 'Error: could not reach the service. Status code: {}.' -CONN_ERR = 'Error: connection not available.' -FORECAST_HELP = 'Shows also the forecasts for today and tomorrow.' -METRIC_HELP = 'Use the International System of Units.' -USCS_HELP = 'Use the United States Customary Units.' -LANG_HELP = 'Choose preferred language. ISO 639-1 code.' -COLORS_HELP = 'Keep or remove terminal sequences for colors. Default is keep.' -ONELINE_HELP = 'Shorter summary that fits in one line and uses emojis.' +URL = "https://wttr.in/{loc}?{fore}{metric}{col}AF&lang={lang}&format={format}" +ERR_MSG = "Error: could not reach the service. Status code: {}." +CONN_ERR = "Error: connection not available." +FORECAST_HELP = "Shows also the forecasts for today and tomorrow." +METRIC_HELP = "Use the International System of Units." +USCS_HELP = "Use the United States Customary Units." +LANG_HELP = "Choose preferred language. ISO 639-1 code." +COLORS_HELP = "Keep or remove terminal sequences for colors. Default is keep." +ONELINE_HELP = "Shorter summary that fits in one line and uses emojis." # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # @@ -23,25 +23,25 @@ def default_lang(): return locale.getdefaultlocale()[0][:2] -@click.command(context_settings=dict(help_option_names=['-h', '--help'])) -@click.argument('location', default='') -@click.option('-f', '--forecast', is_flag=True, help=FORECAST_HELP) -@click.option('-m', '--metric', 'metric', flag_value='m', help=METRIC_HELP) -@click.option('-u', '--uscs', 'metric', flag_value='u', help=USCS_HELP) -@click.option('-l', '--language', default=default_lang(), help=LANG_HELP) -@click.option('--colors/--no-colors', default='True', help=COLORS_HELP) -@click.option('-o', '--one-line', is_flag=True, help=ONELINE_HELP) +@click.command(context_settings=dict(help_option_names=["-h", "--help"])) +@click.argument("location", default="") +@click.option("-f", "--forecast", is_flag=True, help=FORECAST_HELP) +@click.option("-m", "--metric", "metric", flag_value="m", help=METRIC_HELP) +@click.option("-u", "--uscs", "metric", flag_value="u", help=USCS_HELP) +@click.option("-l", "--language", default=default_lang(), help=LANG_HELP) +@click.option("--colors/--no-colors", default="True", help=COLORS_HELP) +@click.option("-o", "--one-line", is_flag=True, help=ONELINE_HELP) def wttr(location, forecast, metric, language, colors, one_line): """ Cli built using wttr.in API """ url = URL.format( loc=location, - fore='2' if forecast else '0', - metric=metric if metric is not None else '', + fore="2" if forecast else "0", + metric=metric if metric is not None else "", lang=language, - col='' if colors else 'T', - format='4' if one_line else '' + col="" if colors else "T", + format="4" if one_line else "", ) try: response = requests.get(url) @@ -53,5 +53,5 @@ def wttr(location, forecast, metric, language, colors, one_line): print(CONN_ERR) -if __name__ == '__main__': +if __name__ == "__main__": wttr() diff --git a/webex_automation/Main.py b/webex_automation/Main.py index 38c4c3d35..dc0775501 100644 --- a/webex_automation/Main.py +++ b/webex_automation/Main.py @@ -1,14 +1,15 @@ -import pandas as pd -import webbrowser -import pyautogui -import time +import calendar # Reading the file import datetime -import calendar +import time +import webbrowser + +import pandas as pd +import pyautogui def findDay(tdate): - born = datetime.datetime.strptime(tdate, '%Y-%m-%d').weekday() + born = datetime.datetime.strptime(tdate, "%Y-%m-%d").weekday() return calendar.day_name[born] @@ -16,11 +17,11 @@ def findDay(tdate): # printing todays date -print('Current date: ', tdate) +print("Current date: ", tdate) d = findDay(str(tdate)) print(d) -df = pd.read_csv(str(d) + '.csv') +df = pd.read_csv(str(d) + ".csv") # Starting the session @@ -29,18 +30,18 @@ def sign_in(url): # url = 'https://meetingsapac15.webex.com/meet/ddpuri' try: - path = 'C://Program Files//Google//Chrome//Application//chrome.exe' - webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(path)) - webbrowser.get('chrome').open(url) + path = "C://Program Files//Google//Chrome//Application//chrome.exe" + webbrowser.register("chrome", None, webbrowser.BackgroundBrowser(path)) + webbrowser.get("chrome").open(url) except path.DoesNotExist: - path = 'C://Program Files(x86)//Google//Chrome//Application//chrome.exe' - webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(path)) - webbrowser.get('chrome').open(url) + path = "C://Program Files(x86)//Google//Chrome//Application//chrome.exe" + webbrowser.register("chrome", None, webbrowser.BackgroundBrowser(path)) + webbrowser.get("chrome").open(url) time.sleep(20) - print('we are here') - meeting_id_btn = 'NONE' - while meeting_id_btn == 'NONE': - meeting_id_btn = pyautogui.locateCenterOnScreen('1.png') + print("we are here") + meeting_id_btn = "NONE" + while meeting_id_btn == "NONE": + meeting_id_btn = pyautogui.locateCenterOnScreen("1.png") print(meeting_id_btn) pyautogui.moveTo(meeting_id_btn) pyautogui.click() @@ -49,8 +50,9 @@ def sign_in(url): def sign_out(): import wmi + ti = 0 - name = ['CiscoCollabHost.exe', 'webexmta.exe', 'atmgr.exe'] + name = ["CiscoCollabHost.exe", "webexmta.exe", "atmgr.exe"] f = wmi.WMI() for process in f.Win32_Process(): if process.name in name: @@ -58,24 +60,24 @@ def sign_out(): ti += 1 break if ti == 0: - print('Process not found!!!') + print("Process not found!!!") while True: # checking of the current time exists in the csv file - now = datetime.now().strftime('%H:%M') - if now in str(df['timings']): + now = datetime.now().strftime("%H:%M") + if now in str(df["timings"]): - row = df.loc[df['timings'] == now] + row = df.loc[df["timings"] == now] url = str(row.iloc[0, 1]) sign_in(url) - print('signed in') + print("signed in") - if now in str(df['end']): - row = df.loc[df['end'] == now] + if now in str(df["end"]): + row = df.loc[df["end"] == now] sign_out() - print('signed out') + print("signed out") diff --git a/website_blocker/website_blocker.py b/website_blocker/website_blocker.py index 65e508a8e..866d0d5a0 100644 --- a/website_blocker/website_blocker.py +++ b/website_blocker/website_blocker.py @@ -1,13 +1,14 @@ import ctypes -import sys -from sys import platform import os +import sys from os import system +from sys import platform + from elevate import elevate class Blocker: - hosts_path = '' + hosts_path = "" redirect = "127.0.0.1" website_list = [] os_number = 0 @@ -32,13 +33,13 @@ def blocker_menu(self): print("Type 'exit' to stop the blocker") user_input = input("Enter here: ") - if user_input == '+': + if user_input == "+": self.add_websites() print("Blocked Websites (^v^)") for website in self.website_list: print("# " + website) - elif user_input == 'exit': + elif user_input == "exit": print("Restoring Every change.....") self.restore_host_file() print("Thanks you using") @@ -47,7 +48,7 @@ def blocker_menu(self): print("Invalid Input Try Again") def restore_host_file(self): - with open(self.hosts_path, 'r+') as file: + with open(self.hosts_path, "r+") as file: content = file.readlines() file.seek(0) for line in content: @@ -65,16 +66,16 @@ def add_websites(self): print("Enter a website url to add like 'www.facebook.com or facebook.com'") user_input = input("Enter URL Here: ") self.website_list.append(user_input) - with open(self.hosts_path, 'r+') as file: + with open(self.hosts_path, "r+") as file: file.write(self.redirect + " " + user_input + "\n") file.close() def clear_console(self): if self.os_number == 2: - _ = system('cls') + _ = system("cls") else: - _ = system('clear') + _ = system("clear") def get_os(): @@ -92,7 +93,9 @@ def get_os(): def driver(): if get_os() == 2: if ctypes.windll.shell32.IsUserAnAdmin() == 0: - ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, __file__, None, 1) + ctypes.windll.shell32.ShellExecuteW( + None, "runas", sys.executable, __file__, None, 1 + ) else: if os.getuid() == 0: elevate(graphical=False) diff --git a/websiteurl_scraper/webUrlscraper.py b/websiteurl_scraper/webUrlscraper.py index 6c9ac1d19..5c1b2b15b 100644 --- a/websiteurl_scraper/webUrlscraper.py +++ b/websiteurl_scraper/webUrlscraper.py @@ -2,7 +2,8 @@ # ssl helps us to avoid cretificate verifation and so on import ssl -from urllib.request import urlopen, Request +from urllib.request import Request, urlopen + from bs4 import BeautifulSoup ctx = ssl.create_default_context() @@ -11,26 +12,26 @@ # getting in the website link Url = input("Enter your Urllink") -try : +try: # trying to access the page - page = Request(Url, headers={'User-Agent': 'Mozilla/5.0'}) + page = Request(Url, headers={"User-Agent": "Mozilla/5.0"}) page = urlopen(page, context=ctx).read() # Using beautifulsoup to read the contents of the page - soup = BeautifulSoup(page, 'html.parser') + soup = BeautifulSoup(page, "html.parser") # finding all the link headers - links = soup.findAll('a') - if (links is not None) : + links = soup.findAll("a") + if links is not None: finalLinks = [] # getting actual site links from the header a - for link in links : - if 'href' in str(link) : + for link in links: + if "href" in str(link): templist = str(link).split("href") - index1 = templist[-1].index("\"") - index2 = templist[-1][index1 + 1 :].index("\"") + index1 = templist[-1].index('"') + index2 = templist[-1][index1 + 1 :].index('"') finalLinks.append(templist[-1][index1 : index2 + 3]) print("Here are your final links") # printing the final completed list - for i in finalLinks : + for i in finalLinks: print(i) -except Exception as e : +except Exception as e: print(str(e)) diff --git a/whatsapp_automation/wa_scrapper.py b/whatsapp_automation/wa_scrapper.py index 9ee4650f1..296950168 100644 --- a/whatsapp_automation/wa_scrapper.py +++ b/whatsapp_automation/wa_scrapper.py @@ -1,9 +1,10 @@ +import time + from selenium import webdriver from selenium.webdriver.common.keys import Keys -import time name = ["Bot"] -driver = webdriver.Chrome(executable_path='chromedriver.exe') +driver = webdriver.Chrome(executable_path="chromedriver.exe") driver.get("https:// web.whatsapp.com/ ") bot = "Hi" time.sleep(8) diff --git a/whatsapp_bot/whatsapp.py b/whatsapp_bot/whatsapp.py index baffe4373..2f15e13a9 100644 --- a/whatsapp_bot/whatsapp.py +++ b/whatsapp_bot/whatsapp.py @@ -1,12 +1,13 @@ -import pywhatkit from datetime import datetime +import pywhatkit + now = datetime.now() chour = now.strftime("%H") -mobile = input('Enter Mobile No of Receiver : ') -message = input('Enter Message you wanna send : ') -hour = int(chour) + int(input('Enter hour : ')) -minute = int(input('Enter minute : ')) +mobile = input("Enter Mobile No of Receiver : ") +message = input("Enter Message you wanna send : ") +hour = int(chour) + int(input("Enter hour : ")) +minute = int(input("Enter minute : ")) pywhatkit.sendwhatmsg(mobile, message, hour, minute) diff --git a/wifi_passwords/wifi_passwords.py b/wifi_passwords/wifi_passwords.py index 2c14d6a18..ee2ab5f8f 100644 --- a/wifi_passwords/wifi_passwords.py +++ b/wifi_passwords/wifi_passwords.py @@ -1,91 +1,90 @@ -import subprocess -import platform import locale +import platform +import subprocess def exec_linux(): - cmd = 'ls /etc/NetworkManager/system-connections' + cmd = "ls /etc/NetworkManager/system-connections" wifi_ssids = subprocess.run(cmd, capture_output=True, shell=True) - list_ssids = wifi_ssids.stdout.decode().split('\n') + list_ssids = wifi_ssids.stdout.decode().split("\n") list_cmds = list() for i in list_ssids: - if i != '': + if i != "": list_cmds.append(f' "/etc/NetworkManager/system-connections/{i}"') - cat_cmds = 'sudo cat ' + ' '.join(list_cmds) + ' | grep psk=' + cat_cmds = "sudo cat " + " ".join(list_cmds) + " | grep psk=" print( - 'Requires sudo permission to read the wifi passwords, ' - + 'if you want you can see the command, [Y]', end=' ') - if input().lower() == 'y': - print(f'\n{cat_cmds}\n') + "Requires sudo permission to read the wifi passwords, " + + "if you want you can see the command, [Y]", + end=" ", + ) + if input().lower() == "y": + print(f"\n{cat_cmds}\n") passwords = subprocess.run(cat_cmds, capture_output=True, shell=True) - psks = passwords.stdout.decode().split('\n') + psks = passwords.stdout.decode().split("\n") if len(psks) != len(list_cmds): - print('\nInvalid password!\n') + print("\nInvalid password!\n") return 0 - print('\n List of Wifi SSIDs with passwords\n') + print("\n List of Wifi SSIDs with passwords\n") for i in zip(list_ssids, psks): - print(f'\t{i[0]} : {i[1][4:]}') + print(f"\t{i[0]} : {i[1][4:]}") def exec_windows(): default_lang = locale.getdefaultlocale()[0] KEYWORDS = { - "fr_FR": ['profil tous les utilisateurs', 'Contenu'], - "en_GB": ['all user profile', 'Key Content'], - "en_US": ['all user profile', 'Key Content'], - "en_IN": ['all user profile', 'Key Content'] + "fr_FR": ["profil tous les utilisateurs", "Contenu"], + "en_GB": ["all user profile", "Key Content"], + "en_US": ["all user profile", "Key Content"], + "en_IN": ["all user profile", "Key Content"], } wifi_ssids = subprocess.run( - 'netsh wlan show profile', - capture_output=True, - shell=True + "netsh wlan show profile", capture_output=True, shell=True ) list_ssids = [ - i.strip().lower() for i in wifi_ssids.stdout.decode("ISO-8859-1") - .split('\r\n') + i.strip().lower() for i in wifi_ssids.stdout.decode("ISO-8859-1").split("\r\n") ] cmds = list() for ssid in list_ssids: if ssid.startswith(KEYWORDS[default_lang][0]): - cmds.append(ssid.split(':')[1].strip()) + cmds.append(ssid.split(":")[1].strip()) output = list() for cmd in cmds: cat_cmd = f'netsh wlan show profile "{cmd}" key=clear' cat_cmd = subprocess.run(cat_cmd, capture_output=True, shell=True) - out = cat_cmd.stdout.decode("ISO-8859-1").split('\r\n') + out = cat_cmd.stdout.decode("ISO-8859-1").split("\r\n") for key in out: if key.strip().startswith(KEYWORDS[default_lang][1]): - temp_key = key.split(': ') + temp_key = key.split(": ") if len(temp_key) == 2: output.append((cmd, temp_key[1])) break else: - output.append((cmd, '')) + output.append((cmd, "")) break - print('\n List of Wifi SSIDs with passwords\n') + print("\n List of Wifi SSIDs with passwords\n") for i in output: - print(f'\t{i[0]} : {i[1]}') + print(f"\t{i[0]} : {i[1]}") -if __name__ == '__main__': +if __name__ == "__main__": current_platform = platform.system().lower() - if current_platform == 'linux': + if current_platform == "linux": exec_linux() - elif current_platform == 'windows': + elif current_platform == "windows": exec_windows() else: - print('Apologies, only supports Linux and Windows') + print("Apologies, only supports Linux and Windows") diff --git a/wikipedia_searchsave/wikipedia_search_and_save.py b/wikipedia_searchsave/wikipedia_search_and_save.py index c09cfdc16..b060520f3 100644 --- a/wikipedia_searchsave/wikipedia_search_and_save.py +++ b/wikipedia_searchsave/wikipedia_search_and_save.py @@ -1,4 +1,5 @@ import argparse + import wikipedia from fpdf import FPDF @@ -6,20 +7,20 @@ class PDF(FPDF): def chapter_title(self, label): # Arial 12 - self.set_font('Arial', '', 12) + self.set_font("Arial", "", 12) # Background color self.set_fill_color(200, 220, 255) # Title - self.cell(0, 6, '%s' % (label), 0, 1, 'L', 1) + self.cell(0, 6, "%s" % (label), 0, 1, "L", 1) # Line break self.ln(4) def chapter_body(self, file_name): # Read text file - with open(file_name, 'rb') as fh: - txt = fh.read().decode('latin-1') + with open(file_name, "rb") as fh: + txt = fh.read().decode("latin-1") # Times 12 - self.set_font('Times', '', 12) + self.set_font("Times", "", 12) # Output justified text self.multi_cell(0, 5, txt) # Line break @@ -35,7 +36,7 @@ def wikipedia_search(user_input): query = wikipedia.page(user_input) # Writing the search result in a temp file - file = open('temp.txt', 'w') + file = open("temp.txt", "w") # write() - it used to write direct text to the file file.write(query.summary) # closing the file @@ -46,9 +47,9 @@ def wikipedia_search(user_input): # declaring our file name pdf_file_name = user_input + ".pdf" # writing the content to a pdf file - pdf.print_chapter(query.original_title, 'temp.txt') + pdf.print_chapter(query.original_title, "temp.txt") # saving the file in our computer - pdf.output(pdf_file_name, 'F') + pdf.output(pdf_file_name, "F") # Clearing our temp file open("temp.txt", "w").close() @@ -58,8 +59,7 @@ def main(): # Initialize parser parser = argparse.ArgumentParser() # Adding optional argument - parser.add_argument("-s", "--search", - help="search your query") + parser.add_argument("-s", "--search", help="search your query") # parser.add_argument("-m", "--message", help="insert your message here") # Read arguments from command line diff --git a/word_cloud/word_cloud.py b/word_cloud/word_cloud.py index 635cc8b23..741164d2e 100644 --- a/word_cloud/word_cloud.py +++ b/word_cloud/word_cloud.py @@ -1,21 +1,22 @@ -from wordcloud import WordCloud, STOPWORDS import matplotlib.pyplot as plt +from wordcloud import STOPWORDS, WordCloud + stopwords = set(STOPWORDS) def wordcloud(path, title=None): - data = open(path, 'r').read().lower() + data = open(path, "r").read().lower() wordcloud = WordCloud( - background_color='white', + background_color="white", stopwords=stopwords, max_words=200, max_font_size=40, scale=3, - random_state=1 + random_state=1, ).generate(str(data)) fig = plt.figure(1, figsize=(12, 12)) - plt.axis('off') + plt.axis("off") if title: fig.suptitle(title, fontsize=20) fig.subplots_adjust(top=2.3) diff --git a/wordle_solver/wordle_solver.py b/wordle_solver/wordle_solver.py index 49b08175e..5a82a3019 100755 --- a/wordle_solver/wordle_solver.py +++ b/wordle_solver/wordle_solver.py @@ -1,13 +1,13 @@ # https://www.wordunscrambler.net/word-list/wordle-word-list # for the list of words +import time + +from pynput import keyboard from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.firefox.service import Service as FirefoxService from webdriver_manager.firefox import GeckoDriverManager -from pynput import keyboard -import time - # This class is used to store data about the wordle such as : # - the list of possible words @@ -16,12 +16,13 @@ # - the letters that are correct and their position in a list # - the word that is currently being tested + class Finder: def __init__(self): self.possible_words = get_list_of_words() self.present_letters = set([]) self.absent_letters = set([]) - self.word = [''] * 5 + self.word = [""] * 5 # Creators recommend “Slate” as starting word self.word_to_try = "slate" @@ -37,15 +38,10 @@ def on_release(key): # Get the status of the letters in the wordle def get_row_results(game_row): tiles = game_row.find_elements( - By.XPATH, ".//*[contains(@class, 'Tile-module_tile__')]") + By.XPATH, ".//*[contains(@class, 'Tile-module_tile__')]" + ) row_results = [] - res_to_int = { - "correct": 1, - "present": 0, - "absent": -1, - "empty": -2, - "tbd": -3 - } + res_to_int = {"correct": 1, "present": 0, "absent": -1, "empty": -2, "tbd": -3} for tile in tiles: row_results.append(res_to_int[tile.get_attribute("data-state")]) print(f"Row results : {row_results}") @@ -120,9 +116,11 @@ def solving_algorithm(res, finder): # We keep all the words that don't match # the pattern of the word entered finder.possible_words = list( - filter(lambda x_word: - not check_match(word[letter], x_word[letter]), - finder.possible_words)) + filter( + lambda x_word: not check_match(word[letter], x_word[letter]), + finder.possible_words, + ) + ) else: # Case when the status of the letter is "absent" print(f"Letter {word[letter]} is absent") @@ -132,9 +130,11 @@ def solving_algorithm(res, finder): # We keep all the words that don't match # the pattern of the word entered finder.possible_words = list( - filter(lambda x_word: - not check_match(word[letter], x_word[letter]), - finder.possible_words)) + filter( + lambda x_word: not check_match(word[letter], x_word[letter]), + finder.possible_words, + ) + ) print("\n") print("Updating list of possible words ...") @@ -142,20 +142,26 @@ def solving_algorithm(res, finder): # Update list of words for absent in finder.absent_letters: finder.possible_words = list( - filter(lambda x_word: - not check_letter_in_word(absent, x_word), - finder.possible_words)) + filter( + lambda x_word: not check_letter_in_word(absent, x_word), + finder.possible_words, + ) + ) for present in finder.present_letters: finder.possible_words = list( - filter(lambda x_word: - check_letter_in_word(present, x_word), - finder.possible_words)) + filter( + lambda x_word: check_letter_in_word(present, x_word), + finder.possible_words, + ) + ) for i in range(len(finder.word)): if finder.word[i] != "": finder.possible_words = list( - filter(lambda x_word: - check_match(x_word[i], finder.word[i]), - finder.possible_words)) + filter( + lambda x_word: check_match(x_word[i], finder.word[i]), + finder.possible_words, + ) + ) # Update the next word to try finder.word_to_try = finder.possible_words[0] @@ -170,8 +176,7 @@ def solving_algorithm(res, finder): def main(): # Start the browser - browser = webdriver.Firefox( - service=FirefoxService(GeckoDriverManager().install())) + browser = webdriver.Firefox(service=FirefoxService(GeckoDriverManager().install())) browser.get("https://www.nytimes.com/games/wordle/index.html") # Create the finder object (cf. class Finder) @@ -191,7 +196,8 @@ def main(): # Get the game rows game_rows = browser.find_elements( - By.XPATH, "//*[contains(@class, 'Row-module_row__')]") + By.XPATH, "//*[contains(@class, 'Row-module_row__')]" + ) # Enter words until the game is over or the wordle is solved for i in range(guesses_left, 0, -1): diff --git a/xkcd_downloader/download_xkcd.py b/xkcd_downloader/download_xkcd.py index 5923da1bc..c103ffa7f 100644 --- a/xkcd_downloader/download_xkcd.py +++ b/xkcd_downloader/download_xkcd.py @@ -1,33 +1,34 @@ #! python3 -import requests import os + import bs4 +import requests -url = input("The url of the XKCD comics") # starting url -os.makedirs('xkcd', exist_ok=True) # store comics in ./xkcd -while not url.endswith('#'): - print('Downloading page %s...' % url) +url = input("The url of the XKCD comics") # starting url +os.makedirs("xkcd", exist_ok=True) # store comics in ./xkcd +while not url.endswith("#"): + print("Downloading page %s..." % url) res = requests.get(url) res.raise_for_status() - soup = bs4.BeautifulSoup(res.text, 'html.parser') - comicElem = soup.select('#comic img') + soup = bs4.BeautifulSoup(res.text, "html.parser") + comicElem = soup.select("#comic img") if comicElem == []: - print('Could not find comic image.') + print("Could not find comic image.") else: - comicUrl = 'https:' + comicElem[0].get('src') + comicUrl = "https:" + comicElem[0].get("src") # Download the image. - print('Downloading image %s...' % (comicUrl)) + print("Downloading image %s..." % (comicUrl)) res = requests.get(comicUrl) res.raise_for_status() - imageFile = open(os.path.join('xkcd', os.path.basename(comicUrl)), 'wb') + imageFile = open(os.path.join("xkcd", os.path.basename(comicUrl)), "wb") for chunk in res.iter_content(100000): imageFile.write(chunk) imageFile.close() # Get the Prev button's url. prevLink = soup.select('a[rel="prev"]')[0] - url = 'https://xkcd.com' + prevLink.get('href') + url = "https://xkcd.com" + prevLink.get("href") -print('Done.') +print("Done.") diff --git a/yaml_to_json/yaml_to_json.py b/yaml_to_json/yaml_to_json.py index 7cdd0c68c..78f49df2f 100644 --- a/yaml_to_json/yaml_to_json.py +++ b/yaml_to_json/yaml_to_json.py @@ -1,7 +1,8 @@ -from ruyaml import YAML import argparse import json +from ruyaml import YAML + def get_yaml_data(yaml_name=None): if not yaml_name: @@ -29,10 +30,10 @@ def convert_to_json(yaml_data, json_name=None, intent=None): def main(): - parser = argparse.ArgumentParser(description='Convert YAML file to JSON') - parser.add_argument('--yaml', type=str, help='YAML filename') - parser.add_argument('--json', type=str, help='JSON filename') - parser.add_argument('--intent', type=int, help="intent value for JSON") + parser = argparse.ArgumentParser(description="Convert YAML file to JSON") + parser.add_argument("--yaml", type=str, help="YAML filename") + parser.add_argument("--json", type=str, help="JSON filename") + parser.add_argument("--intent", type=int, help="intent value for JSON") args = parser.parse_args() yaml_name = args.yaml diff --git a/youtube_args_search/youtube_search.py b/youtube_args_search/youtube_search.py index 9f0922e40..151c1acea 100644 --- a/youtube_args_search/youtube_search.py +++ b/youtube_args_search/youtube_search.py @@ -1,5 +1,7 @@ -from selenium import webdriver import argparse + +from selenium import webdriver + links = [] path_to_gekoDriver = "" # enter the path here @@ -7,10 +9,10 @@ parser = argparse.ArgumentParser() # adding arguments -parser.add_argument('query', help='Enter the query to search video on youtube') +parser.add_argument("query", help="Enter the query to search video on youtube") parser.add_argument( - '-n', '--number', help='Video number which is to be opened', - type=int, default=1) + "-n", "--number", help="Video number which is to be opened", type=int, default=1 +) args = parser.parse_args() @@ -24,7 +26,7 @@ try: # opens the nth video requested by the user - xxpath = (driver.find_elements_by_xpath('//*[@id="video-title"]')) + xxpath = driver.find_elements_by_xpath('//*[@id="video-title"]') xxpath[number - 1].click() except Exception as e: diff --git a/youtube_cli_search/script.py b/youtube_cli_search/script.py index a10df6509..6b8e2d7ab 100644 --- a/youtube_cli_search/script.py +++ b/youtube_cli_search/script.py @@ -1,5 +1,5 @@ -import urllib.request import re +import urllib.request # Prepare the request link search = input("Search For: ") @@ -23,8 +23,6 @@ videos_link.append(f"{standard_video_link}{videos_identifiers[i]}") -print(f"status: Success,\n" - f"result: {len(videos_link)},\n" - f"links:") +print(f"status: Success,\n" f"result: {len(videos_link)},\n" f"links:") for video in videos_link: print(video) diff --git a/youtube_clipper/youtube_clip.py b/youtube_clipper/youtube_clip.py index 51e65b3d7..605c8f89f 100644 --- a/youtube_clipper/youtube_clip.py +++ b/youtube_clipper/youtube_clip.py @@ -14,19 +14,23 @@ def time_manipulation(time): time = "00:" + time if len(time) == 7: time = "0" + time - h, m, s = time.split(':') + h, m, s = time.split(":") time = int(h) * 3600 + int(m) * 60 + int(s) return time youtube_link = input("Enter the Youtube video link: ") -start_time = input("Enter start time of the video clip in HH:MM:SS|H:MM:SS|MM:SS|M:SS|SS|S format: ") +start_time = input( + "Enter start time of the video clip in HH:MM:SS|H:MM:SS|MM:SS|M:SS|SS|S format: " +) start_time = time_manipulation(start_time) # start time in seconds -end_time = input("Enter end time of the video clip in HH:MM:SS|H:MM:SS|MM:SS|M:SS|SS|S format: ") +end_time = input( + "Enter end time of the video clip in HH:MM:SS|H:MM:SS|MM:SS|M:SS|SS|S format: " +) end_time = time_manipulation(end_time) # end time in seconds duration = end_time - start_time Output_file_name = input("Enter your output video name: ") -Output_file_name = Output_file_name + '.mp4' +Output_file_name = Output_file_name + ".mp4" # Error-1 if duration <= 0: @@ -34,8 +38,11 @@ def time_manipulation(time): quit() # calculating the length of youtube video in seconds -duration_of_video = subprocess.run(["youtube-dl", "--no-check-certificate", "--get-duration", youtube_link], - stdout=subprocess.PIPE, text=True) +duration_of_video = subprocess.run( + ["youtube-dl", "--no-check-certificate", "--get-duration", youtube_link], + stdout=subprocess.PIPE, + text=True, +) video_length = duration_of_video.stdout video_length = video_length[:-1] video_length = time_manipulation(video_length) # video length in seconds @@ -47,14 +54,31 @@ def time_manipulation(time): # removing the channel name from link if it is present for ch in youtube_link: - if ch == '&': - youtube_link = youtube_link[:youtube_link.index(ch)] + if ch == "&": + youtube_link = youtube_link[: youtube_link.index(ch)] # getting the download link of the youtube video -download_link = subprocess.run(["youtube-dl", "--no-check-certificate", "-f", "22", "--get-url", youtube_link], - stdout=subprocess.PIPE, text=True) +download_link = subprocess.run( + ["youtube-dl", "--no-check-certificate", "-f", "22", "--get-url", youtube_link], + stdout=subprocess.PIPE, + text=True, +) link = download_link.stdout # downloading the video from start_time to end_time -subprocess.run(["ffmpeg", "-ss", str(start_time), "-i", link, "-t", str(duration), "-c:v", "copy", "-c:a", - "copy", Output_file_name]) +subprocess.run( + [ + "ffmpeg", + "-ss", + str(start_time), + "-i", + link, + "-t", + str(duration), + "-c:v", + "copy", + "-c:a", + "copy", + Output_file_name, + ] +) diff --git a/youtube_dl_gui/YoutubeDL.py b/youtube_dl_gui/YoutubeDL.py index 60f2f2706..a851c1433 100644 --- a/youtube_dl_gui/YoutubeDL.py +++ b/youtube_dl_gui/YoutubeDL.py @@ -1,8 +1,9 @@ import os -from time import sleep import tkinter as tk -from PIL import Image, ImageTk from threading import Thread +from time import sleep + +from PIL import Image, ImageTk # initialize tkinter GUI root = tk.Tk() @@ -19,7 +20,7 @@ label.grid(columnspan=3, row=0, pady=30) label.configure(font=("Courier", 28, "bold")) -img = Image.open('images/youtube-logo.png') +img = Image.open("images/youtube-logo.png") img = ImageTk.PhotoImage(img) img_label = tk.Label(image=img) img_label.image = img @@ -84,9 +85,14 @@ def downloadVideo(): second().start() -getVideo = tk.Button(root, textvariable=downloadButton, - fg="red", command=downloadVideo, - font=("Courier", 15), height=2) +getVideo = tk.Button( + root, + textvariable=downloadButton, + fg="red", + command=downloadVideo, + font=("Courier", 15), + height=2, +) getVideo.grid(columnspan=3, row=6, pady=10) diff --git a/youtube_downloader/ytdownloader.py b/youtube_downloader/ytdownloader.py index 83b0fdbd3..74acb0b80 100644 --- a/youtube_downloader/ytdownloader.py +++ b/youtube_downloader/ytdownloader.py @@ -1,17 +1,24 @@ import argparse + from pytube import YouTube def cli_parse(): - cli = argparse.ArgumentParser(prog='ytdownloader', - description='Basic automation script for downloading YouTube hosted videos') - cli.add_argument("url", metavar='URL', type=str, help="Youtube video URL") + cli = argparse.ArgumentParser( + prog="ytdownloader", + description="Basic automation script for downloading YouTube hosted videos", + ) + cli.add_argument("url", metavar="URL", type=str, help="Youtube video URL") cli.add_argument("-p", "--path", type=str, help="Destination file path") - cli.add_argument("-c", "--captions", type=str, - help="Captions lang to download") + cli.add_argument("-c", "--captions", type=str, help="Captions lang to download") cli.add_argument("-r", "--res", type=str, help="Resolution to download") - cli.add_argument("-v", "--verbose", type=bool, default=False, - help="Show information about script processing") + cli.add_argument( + "-v", + "--verbose", + type=bool, + default=False, + help="Show information about script processing", + ) return cli.parse_args() @@ -24,7 +31,8 @@ def cli_parse(): if not stream: stream = video.streams.get_highest_resolution() print( - f"Sorry, '{args.res}' resolution is not available for this video.\nDownloading highest resolution...") + f"Sorry, '{args.res}' resolution is not available for this video.\nDownloading highest resolution..." + ) if not args.path: @@ -40,8 +48,7 @@ def cli_parse(): file.write(caps) file.close() except KeyError: - print( - f"Sorry, '{args.captions}' captions are not available for this video.") + print(f"Sorry, '{args.captions}' captions are not available for this video.") if args.verbose: print(f"Successfully downloaded video: {dest}") diff --git a/youtube_to_mp3/youtube_to_mp3.py b/youtube_to_mp3/youtube_to_mp3.py index 93a5cf07c..3c4ccada9 100644 --- a/youtube_to_mp3/youtube_to_mp3.py +++ b/youtube_to_mp3/youtube_to_mp3.py @@ -1,6 +1,7 @@ import os -from pytube import YouTube + import moviepy.editor as mp +from pytube import YouTube SAVE_PATH = r"C:\Users\Downloads" link = input("Paste the link") @@ -13,7 +14,7 @@ m = video.title print(m + "is downloaded in .mp4 audio format") -text_files = [f for f in os.listdir(SAVE_PATH) if f.endswith('.mp4')] +text_files = [f for f in os.listdir(SAVE_PATH) if f.endswith(".mp4")] print(text_files) s = input("Kindly paste the title you want in .mp3 from above list") diff --git a/ytthumbnail_grabber/ytthumbnail_grabber.py b/ytthumbnail_grabber/ytthumbnail_grabber.py index 77a747216..d21118c61 100644 --- a/ytthumbnail_grabber/ytthumbnail_grabber.py +++ b/ytthumbnail_grabber/ytthumbnail_grabber.py @@ -6,17 +6,15 @@ def parser(): parse = argparse.ArgumentParser( - prog='ytthumbnail_grabber', - description="Script for grabbing thumbnail from Youtube video" - ) - parse.add_argument( - "url", metavar='URL', type=str, help="Youtube video URL" + prog="ytthumbnail_grabber", + description="Script for grabbing thumbnail from Youtube video", ) + parse.add_argument("url", metavar="URL", type=str, help="Youtube video URL") parse.add_argument("-n", "--name", type=str, help="Select filename.") return parse.parse_args() -if __name__ == '__main__': +if __name__ == "__main__": name = "thumbnail.jpg" args = parser() if args.name: diff --git a/zip_extractor/zip_extractor.py b/zip_extractor/zip_extractor.py index fd0accad1..6f83b3024 100644 --- a/zip_extractor/zip_extractor.py +++ b/zip_extractor/zip_extractor.py @@ -1,6 +1,8 @@ +import time from zipfile import ZipFile + import easygui -import time + # import the required libraries print("Select the path of zip file...") # a function in easygui that opens @@ -12,7 +14,7 @@ # opening the zip file selected # in read mode -with ZipFile(path, 'r') as zip: +with ZipFile(path, "r") as zip: # prints the contents in the zip folder zip.printdir() print("Select the destination directory to extract!!") diff --git a/zip_password_cracker/zip_password_cracker.py b/zip_password_cracker/zip_password_cracker.py index d882e3221..3727cd760 100644 --- a/zip_password_cracker/zip_password_cracker.py +++ b/zip_password_cracker/zip_password_cracker.py @@ -6,7 +6,7 @@ def extract_zip(zip_file: ZipFile, password_file: Path): - with open(password_file, 'r') as passwords: + with open(password_file, "r") as passwords: for password in passwords.readlines(): try: zip_file.extractall(pwd=password.strip().encode()) @@ -18,12 +18,12 @@ def extract_zip(zip_file: ZipFile, password_file: Path): print("Password not found") -@click.command(context_settings={'help_option_names': ['-h', '--help']}) -@click.option('--zip', help='Set path to zip file') +@click.command(context_settings={"help_option_names": ["-h", "--help"]}) +@click.option("--zip", help="Set path to zip file") @click.option( - '--passwords', - default=Path().cwd() / 'passwords.txt', - help='Set path to file with passwords', + "--passwords", + default=Path().cwd() / "passwords.txt", + help="Set path to file with passwords", ) def main(zip, passwords): """Simple program that greets NAME for a total of COUNT times.""" @@ -31,5 +31,5 @@ def main(zip, passwords): extract_zip(zip_file, passwords) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/zomato_dinein_restaurant_scraper/zomato_scraper.py b/zomato_dinein_restaurant_scraper/zomato_scraper.py index 518b3e970..7fbb17302 100644 --- a/zomato_dinein_restaurant_scraper/zomato_scraper.py +++ b/zomato_dinein_restaurant_scraper/zomato_scraper.py @@ -1,16 +1,16 @@ # -- IMPORTING LIBRARIES -- -import pandas as pd -from selenium import webdriver -from bs4 import BeautifulSoup import time +import pandas as pd +from bs4 import BeautifulSoup +from selenium import webdriver # -- STARTING CHROME WITH WEBDRIVER -- browser = webdriver.Chrome() # -- OPENING URL IN BROWSER -- -url = 'https://www.zomato.com/indore/dine-out' +url = "https://www.zomato.com/indore/dine-out" browser.get(url) @@ -25,19 +25,33 @@ html = browser.page_source # -- CREATING BeautifulSoup OBJECT -- -soup = BeautifulSoup(html, 'html.parser') +soup = BeautifulSoup(html, "html.parser") # -- DEFINING FUNCTION FOR EXTRACTING RESATURANT DETAILS -- def zomato(soup): - name = [i.text.strip() for i in soup.find_all('h4', class_='sc-1hp8d8a-0 sc-dpiBDp iFpvOr')] - cuisine = [i.text.strip() for i in soup.find_all('p', class_='sc-1hez2tp-0 sc-hENMEE ffqcCI')] - area = [i.text.strip() for i in soup.find_all('p', class_='sc-1hez2tp-0 sc-dCaJBF jughZz')] - rate = [i.text.strip() for i in soup.find_all('p', class_='sc-1hez2tp-0 sc-hENMEE crfqyB')] - return pd.DataFrame({'Name': name, 'Cuisine': cuisine, 'Area': area, 'Rate for Two': rate}) + name = [ + i.text.strip() + for i in soup.find_all("h4", class_="sc-1hp8d8a-0 sc-dpiBDp iFpvOr") + ] + cuisine = [ + i.text.strip() + for i in soup.find_all("p", class_="sc-1hez2tp-0 sc-hENMEE ffqcCI") + ] + area = [ + i.text.strip() + for i in soup.find_all("p", class_="sc-1hez2tp-0 sc-dCaJBF jughZz") + ] + rate = [ + i.text.strip() + for i in soup.find_all("p", class_="sc-1hez2tp-0 sc-hENMEE crfqyB") + ] + return pd.DataFrame( + {"Name": name, "Cuisine": cuisine, "Area": area, "Rate for Two": rate} + ) # -- DISPLAYING AND EXPORTING RESULTS -- df = zomato(soup) print(df.head()) -df.to_csv('Zomato Restaurants.csv') +df.to_csv("Zomato Restaurants.csv") diff --git a/zoom_attendance_taker/attendanceTaker.py b/zoom_attendance_taker/attendanceTaker.py index 21f0d3fc4..26ebd443e 100644 --- a/zoom_attendance_taker/attendanceTaker.py +++ b/zoom_attendance_taker/attendanceTaker.py @@ -1,13 +1,14 @@ +from datetime import datetime + +import PySimpleGUI as sg from selenium import webdriver -from selenium.webdriver.support import ui +from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC -import PySimpleGUI as sg +from selenium.webdriver.support import ui from webdriver_manager.chrome import ChromeDriverManager from webdriver_manager.firefox import GeckoDriverManager from webdriver_manager.microsoft import EdgeChromiumDriverManager -from selenium.common.exceptions import NoSuchElementException -from datetime import datetime class Zoom: @@ -34,8 +35,7 @@ def join(self): self.wait = ui.WebDriverWait(self.driver, 30) self.zoom_join_meeting = self.driver.get("https://zoom.us/join") ui.WebDriverWait(self.driver, 100).until( - EC.presence_of_element_located((By.XPATH, - '//*[@id="join-confno"]')) + EC.presence_of_element_located((By.XPATH, '//*[@id="join-confno"]')) ) enter_pid = self.driver.find_element_by_xpath('//*[@id="join-confno"]') enter_pid.send_keys(self.meeting_personal_id) @@ -60,8 +60,7 @@ def join(self): ) join_from_browser.click() self.wait.until( - lambda field: - self.driver.find_element_by_xpath('//*[@id="inputname"]') + lambda field: self.driver.find_element_by_xpath('//*[@id="inputname"]') ) name_field = self.driver.find_element_by_xpath('//*[@id="inputname"]') name_field.send_keys(self.username) @@ -70,8 +69,7 @@ def join(self): ) join_button.click() passcode = ui.WebDriverWait(self.driver, 300).until( - EC.presence_of_element_located((By.XPATH, - '//*[@id="inputpasscode"]')) + EC.presence_of_element_located((By.XPATH, '//*[@id="inputpasscode"]')) ) passcode.send_keys(self.meeting_password) join_button = ui.WebDriverWait(self.driver, 300).until( @@ -91,7 +89,7 @@ def get_attendees_list(self): ( By.XPATH, '//*[@id="wc-container-left"]/div[3]/div/' - 'div[2]/div/div/div[1]/div', + "div[2]/div/div/div[1]/div", ) ) ) @@ -104,7 +102,7 @@ def get_attendees_list(self): while True: elem = self.driver.find_element_by_xpath( f'//*[@id="wc-container-left"]/div[3]/div/div[2]' - f'/div/div/div[1]/div[{i}]/div' + f"/div/div/div[1]/div[{i}]/div" ) i += 1 attendees.append(elem.text) @@ -112,7 +110,7 @@ def get_attendees_list(self): pass print(attendees) with open("attended.csv", "w+") as fp: - fp.write(datetime.now().isoformat(' ')) + fp.write(datetime.now().isoformat(" ")) fp.writelines(",".join(attendees)) @@ -121,8 +119,7 @@ def __init__(self): self.drivers = ["Chrome", "FireFox(Gecko)", "Edge"] self.layout = [ [sg.Text("Meeting ID: "), sg.Input(key="meetingID")], - [sg.Text("Meeting Password"), - sg.Input(password_char="*", key="password")], + [sg.Text("Meeting Password"), sg.Input(password_char="*", key="password")], [sg.Text("Name"), sg.Input(key="name")], [ sg.Listbox( @@ -150,8 +147,7 @@ def create(self): gui = GUI() values = gui.create() zoom_client = Zoom( - values["Driver"][0], values["meetingID"], - values["name"], values["password"] + values["Driver"][0], values["meetingID"], values["name"], values["password"] ) zoom_client.setup_driver() zoom_client.join()