├── .github ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── main.yml │ └── main_pyjango.yml ├── .gitignore ├── Data_Analytics ├── Pandas Profiling ├── Titanic__Survivors_dataset │ ├── Titanic__Survivors_dataset .ipynb │ └── train.csv └── Weather History │ ├── README.md │ ├── performing_analysis_of_meteorological_data.ipynb │ └── weatherHistory.csv ├── LICENSE ├── Machine Learning ├── Face Detection │ ├── fac_dec.py │ └── haarcascade_frontalface_default.xml ├── IRIS_classification │ ├── iris.csv │ └── iris_classifier.py ├── Pytorch_series │ ├── CNN_network.py │ ├── Custom_dataset_images │ │ ├── custom_dataset_images.py │ │ ├── face_landmarks.csv │ │ └── faces │ │ │ ├── 0805personali01.jpg │ │ │ ├── 1084239450_e76e00b7e7.jpg │ │ │ ├── 10comm-decarlo.jpg │ │ │ ├── 110276240_bec305da91.jpg │ │ │ ├── 1198_0_861.jpg │ │ │ ├── 137341995_e7c48e9a75.jpg │ │ │ ├── 1383023626_8a49e4879a.jpg │ │ │ ├── 144044282_87cf3ff76e.jpg │ │ │ ├── 152601997_ec6429a43c.jpg │ │ │ ├── 1549040388_b99e9fa295.jpg │ │ │ ├── 1878519279_f905d4f34e.jpg │ │ │ ├── 2046713398_91aaa6fe1c.jpg │ │ │ ├── 2173711035_dbd53b4f9f.jpg │ │ │ ├── 2210514040_6b03ff2629.jpg │ │ │ ├── 2322901504_08122b01ba.jpg │ │ │ ├── 2327253037_66a61ea6fe.jpg │ │ │ ├── 2328398005_d328a70b4c.jpg │ │ │ ├── 2370961440_6bc8ce346c.jpg │ │ │ ├── 2382SJ8.jpg │ │ │ ├── 252418361_440b75751b.jpg │ │ │ ├── 262007783_943bbcf613.jpg │ │ │ ├── 2633371780_45b740b670.jpg │ │ │ ├── 2647088981_60e9fe40cd.jpg │ │ │ ├── 2711409561_a0786a3d3d.jpg │ │ │ ├── 2722779845_7fcb64a096.jpg │ │ │ ├── 2795838930_0cc5aa5f41.jpg │ │ │ ├── 2902323565_100017b63c.jpg │ │ │ ├── 2902760364_89c50bde40.jpg │ │ │ ├── 2956581526_cd803f2daa.jpg │ │ │ ├── 297448785_b2dda4b2c0.jpg │ │ │ ├── 299733036_fff5ea6f8e.jpg │ │ │ ├── 303808204_1f744bc407.jpg │ │ │ ├── 3074791551_baee7fa0c1.jpg │ │ │ ├── 3152653555_68322314f3.jpg │ │ │ ├── 3264867945_fe18d442c1.jpg │ │ │ ├── 3273658251_b95f65c244.jpg │ │ │ ├── 3298715079_5af7c78fcb.jpg │ │ │ ├── 3325611505_ddc7beffa1.jpg │ │ │ ├── 3362762930_24f76cb89c.jpg │ │ │ ├── 343583208_e986824d77.jpg │ │ │ ├── 3461016494_56cce9c984.jpg │ │ │ ├── 348272697_832ce65324.jpg │ │ │ ├── 3534188114_2108895291.jpg │ │ │ ├── 3534189272_8ef88ba368.jpg │ │ │ ├── 3555944509_7b477069c6.jpg │ │ │ ├── 3574737496_6ee8207045.jpg │ │ │ ├── 362167809_d5a5dcbfdb.jpg │ │ │ ├── 363149951_8be04dc6c0.jpg │ │ │ ├── 3638950581_3387685d3a.jpg │ │ │ ├── 3646828311_bfeb429ef7.jpg │ │ │ ├── 3689162471_5f9ffb5aa0.jpg │ │ │ ├── 3718903026_c1bf5dfcf8.jpg │ │ │ ├── 3790616528_297c0ac935.jpg │ │ │ ├── 3855944735_e252959937.jpg │ │ │ ├── 3856149136_d4595ffdd4.jpg │ │ │ ├── 3872768751_e60d7fdbd5.jpg │ │ │ ├── 529447797_0f9d2fb756.jpg │ │ │ ├── 57635685_d41c98f8ca.jpg │ │ │ ├── 809285949_6889026b53.jpg │ │ │ ├── 92053278_be61a225d2.jpg │ │ │ ├── 96063776_bdb3617b64.jpg │ │ │ ├── 97308305_4b737d0873.jpg │ │ │ ├── britney-bald.jpg │ │ │ ├── create_landmark_dataset.py │ │ │ ├── deeny.peggy.jpg │ │ │ ├── matt-mathes.jpg │ │ │ ├── person-7.jpg │ │ │ ├── person.jpg │ │ │ ├── person_TjahjonoDGondhowiardjo.jpg │ │ │ └── personalpic.jpg │ ├── Instance_Segmentation │ │ ├── Instance_Segmentation.ipynb │ │ └── README.md │ ├── README.md │ ├── RNN_network.py │ ├── bidirectinal_lstm.py │ ├── data_augmentation.py │ ├── handling_imbalanced_dataset.py │ ├── load_save_model.py │ ├── sample_neural_network.py │ ├── tensorr_basics.py │ └── transfer_learning.py └── smile detection │ ├── detection.py │ ├── haarcascade_frontalface_default.xml │ └── smile.xml ├── Projects ├── 2 player tic tac toe game.py ├── Audiobook Voice-Over.py ├── Billing System │ ├── Bill.PNG │ └── Billing_System.py ├── Blackjack game.py ├── Chess │ ├── game.py │ ├── network.py │ ├── run.py │ └── server.py ├── DSA Practice Bot on Telegram │ ├── constants.py │ ├── main.py │ └── responses.py ├── Face Recognition ├── Face_Recognisation.py ├── Hangman │ ├── hangman.py │ ├── hangman_art.py │ └── hangman_words.py ├── ImageCompression.py ├── Job_Scraping.py ├── Language Translator │ ├── images │ │ └── trans.png │ ├── readme.md │ ├── requirements.txt │ └── translator.py ├── Music Player │ ├── music-player.py │ ├── music_player.png │ └── songs │ │ ├── Dhadak (Title Track).mp3 │ │ └── O Saathi.mp3 ├── Pong ├── Pong.py ├── Quiz game │ ├── questions.py │ └── quiz.py ├── Random_Option_Chooser.py ├── RiddleMe! ├── Rock Paper Scissor Game │ ├── README.md │ ├── main.py │ └── rock_paper_scissor_game.py ├── Roshambo.py ├── Roulette-Game.py ├── SnakeGame │ ├── img │ │ ├── apple.jpg │ │ └── ghost.png │ └── main.py ├── Space Shooter Game │ ├── .idea │ │ ├── .gitignore │ │ ├── inspectionProfiles │ │ │ ├── Project_Default.xml │ │ │ └── profiles_settings.xml │ │ ├── misc.xml │ │ ├── modules.xml │ │ └── pythonProject15.iml │ ├── SHPinscher-Regular.otf │ ├── background.png │ ├── bullet.png │ ├── enemy laser.png │ ├── enemy spaceship.png │ ├── main.py │ ├── missile spaceship.png │ ├── missile.png │ └── spaceship.png ├── Stack using Class.py ├── Task_Reminder │ ├── Instructions.md │ ├── ReminderDiary.xlsx │ ├── img │ │ ├── Task_Reminder.ico │ │ ├── Task_Reminder.png │ │ └── Task_Reminder.psd │ ├── main.py │ └── requirements.txt ├── Tic-Tac-Toe.py ├── URLShortener.py ├── Youtube - AudioVideo Downloader │ ├── app.png │ ├── application.pyw │ ├── icons │ │ ├── back.png │ │ ├── search.png │ │ └── youtube.png │ └── readme.md ├── YoutubeDownloader.py ├── YoutubeVideoDownloader.png ├── acro-chat.py ├── alpha.py ├── alphaAi.PNG ├── calc.py ├── choice_game.py ├── currencyconvertor.py ├── days-alives.py ├── days_alive.py ├── dice_roll.py ├── game.py ├── guess_num.py ├── image_to_ascii.py ├── leap_year.py ├── madlibs.py ├── password_generator_1.py ├── phone_nums.py ├── qr_generator.py ├── queue-demo.py ├── queue_1.py ├── rps.py ├── snake_game.py ├── stopwatch.py ├── tkinter_Calc.py ├── tkinter_Digital_Clock.py ├── tkinter_calc.PNG ├── tkinter_digital_clock.PNG ├── twitter-sentiment-analysis │ ├── Twitter_Data.csv │ └── twitter-sentiment-analysis.ipynb └── username_generator.py └── README.md /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 9 | 10 | ## What does this PR do? 11 | 12 | (Provide a description of what this PR does.) 13 | 14 | 15 | ## Related PRs and Issues is any 16 | 17 | (If this PR is related to any other PR or resolves any issue or related to any issue link all related PR and issues here.) 18 | 19 | 20 | 23 | 24 | ### Have you read the Contributing Guidelines? 25 | 26 | - [ ] yes 27 | - [ ] no 28 | 29 | ### Is the code your own? 30 | 31 | - [ ] yes 32 | - [ ] no 33 | 34 | 35 | ### Is your code in proper folder and proper subfolder? 36 | 37 | - [ ] yes 38 | - [ ] no 39 | 40 | ### Have you made or updated corresponding README.md file in the folder? 41 | 42 | - [ ] yes 43 | - [ ] no 44 | 45 | ### Is the code beautified? 46 | 47 | - [ ] yes 48 | - [ ] no 49 | 50 | ### Is the code clear to understand woth proper variable naming and comments? 51 | 52 | - [ ] yes 53 | - [ ] no 54 | 55 | ### Is the problem/project already present and you have implemented it using a new technique? 56 | 57 | - [ ] yes, i have used a new technique and added corresponding documentation 58 | - [ ] no, it is new 59 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | 2 | name: Formatting python code 3 | on: 4 | push: 5 | paths: 6 | - '**.py' 7 | workflow_dispatch: 8 | inputs: 9 | logLevel: 10 | description: 'Log level' 11 | required: true 12 | default: 'warning' 13 | tags: 14 | description: 'Test scenario tags' 15 | jobs: 16 | autoyapf: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@master 20 | with: 21 | ref: ${{ github.head_ref }} 22 | - name: autoyapf 23 | id: autoyapf 24 | uses: mritunjaysharma394/autoyapf@v2 25 | with: 26 | args: --style pep8 --recursive --in-place . 27 | - name: Check for modified files 28 | id: git-check 29 | run: echo ::set-output name=modified::$(if git diff-index --quiet HEAD --; then echo "false"; else echo "true"; fi) 30 | - name: Push changes 31 | if: steps.git-check.outputs.modified == 'true' 32 | run: | 33 | git config --global user.name 'Aatmaj-Zephyr' 34 | git config --global user.email 'Aatmaj-Zephyr@users.noreply.github.com' 35 | git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }} 36 | git commit -am "Automated autoyapf fixes" 37 | git push 38 | -------------------------------------------------------------------------------- /.github/workflows/main_pyjango.yml: -------------------------------------------------------------------------------- 1 | # Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy 2 | # More GitHub Actions for Azure: https://github.com/Azure/actions 3 | # More info on Python, GitHub Actions, and Azure App Service: https://aka.ms/python-webapps-actions 4 | 5 | name: Build and deploy Python app to Azure Web App - pyjango 6 | 7 | on: 8 | push: 9 | branches: 10 | - main 11 | workflow_dispatch: 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | 20 | - name: Set up Python version 21 | uses: actions/setup-python@v1 22 | with: 23 | python-version: '3.9' 24 | 25 | - name: Create and start virtual environment 26 | run: | 27 | python -m venv venv 28 | source venv/bin/activate 29 | 30 | - name: Install dependencies 31 | run: pip install -r requirements.txt 32 | 33 | # Optional: Add step to run tests here (PyTest, Django test suites, etc.) 34 | 35 | - name: Upload artifact for deployment jobs 36 | uses: actions/upload-artifact@v2 37 | with: 38 | name: python-app 39 | path: | 40 | . 41 | !venv/ 42 | 43 | deploy: 44 | runs-on: ubuntu-latest 45 | needs: build 46 | environment: 47 | name: 'Production' 48 | url: ${{ steps.deploy-to-webapp.outputs.webapp-url }} 49 | 50 | steps: 51 | - name: Download artifact from build job 52 | uses: actions/download-artifact@v2 53 | with: 54 | name: python-app 55 | path: . 56 | 57 | - name: 'Deploy to Azure Web App' 58 | uses: azure/webapps-deploy@v2 59 | id: deploy-to-webapp 60 | with: 61 | app-name: 'pyjango' 62 | slot-name: 'Production' 63 | publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_78CCF423DA314A77AE77A63C7C486B49 }} 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /Data_Analytics/Pandas Profiling: -------------------------------------------------------------------------------- 1 | !pip install pandas_profiling==2.9.0 2 | from pandas_profiling import ProfileReport 3 | import pandas as pd 4 | import seaborn as sns 5 | df = sns.load_dataset('iris') 6 | prof = ProfileReport(df) 7 | prof.to_widget() 8 | -------------------------------------------------------------------------------- /Data_Analytics/Weather History/README.md: -------------------------------------------------------------------------------- 1 | # Performing Analysis of Meteorological Data 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Prajakta Sathe 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Machine Learning/Face Detection/fac_dec.py: -------------------------------------------------------------------------------- 1 | # This script will detect faces via your webcam. 2 | # Tested with OpenCV3 3 | 4 | import cv2 5 | 6 | cap = cv2.VideoCapture(0) 7 | 8 | # Create the haar cascade 9 | faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 10 | 11 | while(True): 12 | # Capture frame-by-frame 13 | ret, frame = cap.read() 14 | 15 | # Our operations on the frame come here 16 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 17 | 18 | # Detect faces in the image 19 | faces = faceCascade.detectMultiScale( 20 | gray, 21 | scaleFactor=1.1, 22 | minNeighbors=5, 23 | minSize=(30, 30) 24 | #flags = cv2.CV_HAAR_SCALE_IMAGE 25 | ) 26 | 27 | print("Found {0} faces!".format(len(faces))) 28 | 29 | # Draw a rectangle around the faces 30 | for (x, y, w, h) in faces: 31 | cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) 32 | 33 | 34 | # Display the resulting frame 35 | cv2.imshow('frame', frame) 36 | if cv2.waitKey(1) & 0xFF == ord('q'): 37 | break 38 | 39 | # When everything done, release the capture 40 | cap.release() 41 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /Machine Learning/IRIS_classification/iris.csv: -------------------------------------------------------------------------------- 1 | sepal_length,sepal_width,petal_length,petal_width,species 2 | 5.1,3.5,1.4,0.2,setosa 3 | 4.9,3.0,1.4,0.2,setosa 4 | 4.7,3.2,1.3,0.2,setosa 5 | 4.6,3.1,1.5,0.2,setosa 6 | 5.0,3.6,1.4,0.2,setosa 7 | 5.4,3.9,1.7,0.4,setosa 8 | 4.6,3.4,1.4,0.3,setosa 9 | 5.0,3.4,1.5,0.2,setosa 10 | 4.4,2.9,1.4,0.2,setosa 11 | 4.9,3.1,1.5,0.1,setosa 12 | 5.4,3.7,1.5,0.2,setosa 13 | 4.8,3.4,1.6,0.2,setosa 14 | 4.8,3.0,1.4,0.1,setosa 15 | 4.3,3.0,1.1,0.1,setosa 16 | 5.8,4.0,1.2,0.2,setosa 17 | 5.7,4.4,1.5,0.4,setosa 18 | 5.4,3.9,1.3,0.4,setosa 19 | 5.1,3.5,1.4,0.3,setosa 20 | 5.7,3.8,1.7,0.3,setosa 21 | 5.1,3.8,1.5,0.3,setosa 22 | 5.4,3.4,1.7,0.2,setosa 23 | 5.1,3.7,1.5,0.4,setosa 24 | 4.6,3.6,1.0,0.2,setosa 25 | 5.1,3.3,1.7,0.5,setosa 26 | 4.8,3.4,1.9,0.2,setosa 27 | 5.0,3.0,1.6,0.2,setosa 28 | 5.0,3.4,1.6,0.4,setosa 29 | 5.2,3.5,1.5,0.2,setosa 30 | 5.2,3.4,1.4,0.2,setosa 31 | 4.7,3.2,1.6,0.2,setosa 32 | 4.8,3.1,1.6,0.2,setosa 33 | 5.4,3.4,1.5,0.4,setosa 34 | 5.2,4.1,1.5,0.1,setosa 35 | 5.5,4.2,1.4,0.2,setosa 36 | 4.9,3.1,1.5,0.2,setosa 37 | 5.0,3.2,1.2,0.2,setosa 38 | 5.5,3.5,1.3,0.2,setosa 39 | 4.9,3.6,1.4,0.1,setosa 40 | 4.4,3.0,1.3,0.2,setosa 41 | 5.1,3.4,1.5,0.2,setosa 42 | 5.0,3.5,1.3,0.3,setosa 43 | 4.5,2.3,1.3,0.3,setosa 44 | 4.4,3.2,1.3,0.2,setosa 45 | 5.0,3.5,1.6,0.6,setosa 46 | 5.1,3.8,1.9,0.4,setosa 47 | 4.8,3.0,1.4,0.3,setosa 48 | 5.1,3.8,1.6,0.2,setosa 49 | 4.6,3.2,1.4,0.2,setosa 50 | 5.3,3.7,1.5,0.2,setosa 51 | 5.0,3.3,1.4,0.2,setosa 52 | 7.0,3.2,4.7,1.4,versicolor 53 | 6.4,3.2,4.5,1.5,versicolor 54 | 6.9,3.1,4.9,1.5,versicolor 55 | 5.5,2.3,4.0,1.3,versicolor 56 | 6.5,2.8,4.6,1.5,versicolor 57 | 5.7,2.8,4.5,1.3,versicolor 58 | 6.3,3.3,4.7,1.6,versicolor 59 | 4.9,2.4,3.3,1.0,versicolor 60 | 6.6,2.9,4.6,1.3,versicolor 61 | 5.2,2.7,3.9,1.4,versicolor 62 | 5.0,2.0,3.5,1.0,versicolor 63 | 5.9,3.0,4.2,1.5,versicolor 64 | 6.0,2.2,4.0,1.0,versicolor 65 | 6.1,2.9,4.7,1.4,versicolor 66 | 5.6,2.9,3.6,1.3,versicolor 67 | 6.7,3.1,4.4,1.4,versicolor 68 | 5.6,3.0,4.5,1.5,versicolor 69 | 5.8,2.7,4.1,1.0,versicolor 70 | 6.2,2.2,4.5,1.5,versicolor 71 | 5.6,2.5,3.9,1.1,versicolor 72 | 5.9,3.2,4.8,1.8,versicolor 73 | 6.1,2.8,4.0,1.3,versicolor 74 | 6.3,2.5,4.9,1.5,versicolor 75 | 6.1,2.8,4.7,1.2,versicolor 76 | 6.4,2.9,4.3,1.3,versicolor 77 | 6.6,3.0,4.4,1.4,versicolor 78 | 6.8,2.8,4.8,1.4,versicolor 79 | 6.7,3.0,5.0,1.7,versicolor 80 | 6.0,2.9,4.5,1.5,versicolor 81 | 5.7,2.6,3.5,1.0,versicolor 82 | 5.5,2.4,3.8,1.1,versicolor 83 | 5.5,2.4,3.7,1.0,versicolor 84 | 5.8,2.7,3.9,1.2,versicolor 85 | 6.0,2.7,5.1,1.6,versicolor 86 | 5.4,3.0,4.5,1.5,versicolor 87 | 6.0,3.4,4.5,1.6,versicolor 88 | 6.7,3.1,4.7,1.5,versicolor 89 | 6.3,2.3,4.4,1.3,versicolor 90 | 5.6,3.0,4.1,1.3,versicolor 91 | 5.5,2.5,4.0,1.3,versicolor 92 | 5.5,2.6,4.4,1.2,versicolor 93 | 6.1,3.0,4.6,1.4,versicolor 94 | 5.8,2.6,4.0,1.2,versicolor 95 | 5.0,2.3,3.3,1.0,versicolor 96 | 5.6,2.7,4.2,1.3,versicolor 97 | 5.7,3.0,4.2,1.2,versicolor 98 | 5.7,2.9,4.2,1.3,versicolor 99 | 6.2,2.9,4.3,1.3,versicolor 100 | 5.1,2.5,3.0,1.1,versicolor 101 | 5.7,2.8,4.1,1.3,versicolor 102 | 6.3,3.3,6.0,2.5,virginica 103 | 5.8,2.7,5.1,1.9,virginica 104 | 7.1,3.0,5.9,2.1,virginica 105 | 6.3,2.9,5.6,1.8,virginica 106 | 6.5,3.0,5.8,2.2,virginica 107 | 7.6,3.0,6.6,2.1,virginica 108 | 4.9,2.5,4.5,1.7,virginica 109 | 7.3,2.9,6.3,1.8,virginica 110 | 6.7,2.5,5.8,1.8,virginica 111 | 7.2,3.6,6.1,2.5,virginica 112 | 6.5,3.2,5.1,2.0,virginica 113 | 6.4,2.7,5.3,1.9,virginica 114 | 6.8,3.0,5.5,2.1,virginica 115 | 5.7,2.5,5.0,2.0,virginica 116 | 5.8,2.8,5.1,2.4,virginica 117 | 6.4,3.2,5.3,2.3,virginica 118 | 6.5,3.0,5.5,1.8,virginica 119 | 7.7,3.8,6.7,2.2,virginica 120 | 7.7,2.6,6.9,2.3,virginica 121 | 6.0,2.2,5.0,1.5,virginica 122 | 6.9,3.2,5.7,2.3,virginica 123 | 5.6,2.8,4.9,2.0,virginica 124 | 7.7,2.8,6.7,2.0,virginica 125 | 6.3,2.7,4.9,1.8,virginica 126 | 6.7,3.3,5.7,2.1,virginica 127 | 7.2,3.2,6.0,1.8,virginica 128 | 6.2,2.8,4.8,1.8,virginica 129 | 6.1,3.0,4.9,1.8,virginica 130 | 6.4,2.8,5.6,2.1,virginica 131 | 7.2,3.0,5.8,1.6,virginica 132 | 7.4,2.8,6.1,1.9,virginica 133 | 7.9,3.8,6.4,2.0,virginica 134 | 6.4,2.8,5.6,2.2,virginica 135 | 6.3,2.8,5.1,1.5,virginica 136 | 6.1,2.6,5.6,1.4,virginica 137 | 7.7,3.0,6.1,2.3,virginica 138 | 6.3,3.4,5.6,2.4,virginica 139 | 6.4,3.1,5.5,1.8,virginica 140 | 6.0,3.0,4.8,1.8,virginica 141 | 6.9,3.1,5.4,2.1,virginica 142 | 6.7,3.1,5.6,2.4,virginica 143 | 6.9,3.1,5.1,2.3,virginica 144 | 5.8,2.7,5.1,1.9,virginica 145 | 6.8,3.2,5.9,2.3,virginica 146 | 6.7,3.3,5.7,2.5,virginica 147 | 6.7,3.0,5.2,2.3,virginica 148 | 6.3,2.5,5.0,1.9,virginica 149 | 6.5,3.0,5.2,2.0,virginica 150 | 6.2,3.4,5.4,2.3,virginica 151 | 5.9,3.0,5.1,1.8,virginica 152 | -------------------------------------------------------------------------------- /Machine Learning/IRIS_classification/iris_classifier.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import pandas as pd 3 | from sklearn.model_selection import train_test_split 4 | from sklearn.neighbors import KNeighborsClassifier 5 | from sklearn.datasets import load_iris 6 | 7 | 8 | #classifier code 9 | 10 | #loading the data 11 | iris_data=load_iris() 12 | #iris_data=pd.read_csv("iris.csv") 13 | 14 | #Splitting the data into features and label 15 | x=iris_data["data"] 16 | y=iris_data["target"] 17 | 18 | #Splitting data into tarining and test data 19 | x_train, x_test, y_train, y_test=train_test_split(x,y,random_state=0, test_size=0.3) 20 | 21 | kclassifier=KNeighborsClassifier(n_neighbors=2) 22 | 23 | #fitting training data into KNN classifier 24 | kclassifier.fit(x_train, y_train) 25 | 26 | xn=np.array([[7,3,4,1.5]]) 27 | 28 | xpred=kclassifier.predict(xn) 29 | 30 | print(iris_data["target_names"][xpred]) 31 | 32 | #The classifier can be changed into a pickle file fr use in other files 33 | #import pickle 34 | #pickle.dump(kclassifier, open("knclassifier.pkl", "wb")) 35 | #model=pickle.load(open("knclassifier.pkl", "rb")) 36 | #xn=np.array([[5,1,4,2]]) -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/CNN_network.py: -------------------------------------------------------------------------------- 1 | ###################### Imports ############################# 2 | 3 | import torch 4 | import torch.nn.functional as F 5 | import torchvision.datasets as datasets 6 | import torchvision.transforms as transforms 7 | from torch import optim 8 | from torch import nn 9 | from torch.utils.data import DataLoader 10 | from tqdm import tqdm 11 | import matplotlib.pyplot as plt 12 | 13 | ##################### Building the Network ################ 14 | 15 | class CNN(nn.Module): 16 | def __init__(self,in_channels=1, num_classes=10): 17 | super(CNN,self).__init__() 18 | self.conv1 = nn.Conv2d(in_channels = in_channels,out_channels = 8,kernel_size=(3, 3),stride=(1, 1),padding=(1, 1),) 19 | self.pool = nn.MaxPool2d((2,2), (2,2)) 20 | self.conv2 = nn.Conv2d(in_channels=8, 21 | out_channels=16, 22 | kernel_size=(3, 3), 23 | stride=(1, 1), 24 | padding=(1, 1), 25 | ) 26 | self.dropout1 = nn.Dropout(0.3) 27 | self.dropout2 = nn.Dropout(0.3) 28 | 29 | self.fc1 = nn.Linear(784, 64) 30 | self.fc2 = nn.Linear(64, 32) 31 | self.fc3 = nn.Linear(32, num_classes) 32 | 33 | def forward(self, x): 34 | x = self.pool(F.relu(self.conv1(x))) 35 | x = self.dropout1(x) 36 | x = self.pool(F.relu(self.conv2(x))) 37 | x = torch.flatten(x, 1) 38 | x = self.dropout1(x) 39 | x = F.relu(self.fc1(x)) 40 | x = self.dropout1(x) 41 | x = F.relu(self.fc2(x)) 42 | x = self.fc3(x) 43 | return x 44 | 45 | 46 | # Set device 47 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 48 | 49 | # Hyperparameters 50 | in_channels = 1 51 | num_classes = 10 52 | learning_rate = 0.001 53 | batch_size = 32 54 | num_epochs = 5 55 | 56 | # Load Data 57 | train_dataset = datasets.MNIST(root="dataset/", train=True, transform=transforms.ToTensor(), download=True) 58 | test_dataset = datasets.MNIST(root="dataset/", train=False, transform=transforms.ToTensor(), download=True) 59 | train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) 60 | test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) 61 | 62 | # Initialize network 63 | model = CNN(in_channels=in_channels, num_classes=num_classes).to(device) 64 | 65 | # Loss and optimizer 66 | criterion = nn.CrossEntropyLoss() 67 | optimizer = optim.RMSprop(model.parameters(),lr = learning_rate) 68 | 69 | 70 | ######################### Train Network ######################## 71 | 72 | for epoch in range(num_epochs): 73 | for batch_idx, (data, targets) in enumerate(tqdm(train_loader)): 74 | # Get data to cuda if possible 75 | data = data.to(device=device) 76 | targets = targets.to(device=device) 77 | 78 | # forward 79 | scores = model(data) 80 | loss = criterion(scores, targets) 81 | 82 | # backward 83 | optimizer.zero_grad() 84 | loss.backward() 85 | 86 | # gradient descent or adam step 87 | optimizer.step() 88 | 89 | # Check accuracy on training & test to see how good our model 90 | def check_accuracy(loader, model): 91 | num_correct = 0 92 | num_samples = 0 93 | model.eval() 94 | 95 | with torch.no_grad(): 96 | for x, y in loader: 97 | x = x.to(device=device) 98 | y = y.to(device=device) 99 | 100 | scores = model(x) 101 | _, predictions = scores.max(1) 102 | num_correct += (predictions == y).sum() 103 | num_samples += predictions.size(0) 104 | 105 | 106 | model.train() 107 | return num_correct/num_samples 108 | 109 | print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}") 110 | print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}") 111 | 112 | 113 | ## Saving the model 114 | 115 | PATH = './cifar_net.pth' 116 | torch.save(model.state_dict(), PATH) 117 | 118 | ###################### Testing the Model ######################### 119 | 120 | examples = enumerate(test_loader) 121 | batch_idx, (example_data, example_targets) = next(examples) 122 | 123 | fig = plt.figure() 124 | for i in range(6): 125 | plt.subplot(2,3,i+1) 126 | plt.tight_layout() 127 | plt.imshow(example_data[i][0], cmap='gray', interpolation='none') 128 | plt.title("Ground Truth: {}".format(example_targets[i])) 129 | plt.xticks([]) 130 | plt.yticks([]) 131 | 132 | fig.show() 133 | 134 | classes = ('0', '1', '2', '3', 135 | '4', '5', '6', '7', '8', '9') 136 | 137 | net = CNN() 138 | net.load_state_dict(torch.load(PATH)) 139 | 140 | ############# Predict accuracy per class ################ 141 | 142 | correct_pred = {classname: 0 for classname in classes} 143 | total_pred = {classname: 0 for classname in classes} 144 | 145 | # again no gradients needed 146 | with torch.no_grad(): 147 | for data in test_loader: 148 | images, labels = data 149 | outputs = net(images) 150 | _, predictions = torch.max(outputs, 1) 151 | # collect the correct predictions for each class 152 | for label, prediction in zip(labels, predictions): 153 | if label == prediction: 154 | correct_pred[classes[label]] += 1 155 | total_pred[classes[label]] += 1 156 | 157 | 158 | # print accuracy for each class 159 | for classname, correct_count in correct_pred.items(): 160 | accuracy = 100 * float(correct_count) / total_pred[classname] 161 | print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %') -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/custom_dataset_images.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch.utils.data import Dataset # Gives easier dataset managment by creating mini batches etc. 3 | from skimage import io 4 | import os 5 | import numpy as np 6 | import pandas as pd 7 | import matplotlib.pyplot as plt 8 | 9 | ## Viewing the landamarks on the images 10 | 11 | landmarks_frame = pd.read_csv('./face_landmarks.csv') 12 | 13 | n = 65 14 | img_name = landmarks_frame.iloc[n, 0] 15 | landmarks = landmarks_frame.iloc[n, 1:] 16 | landmarks = np.asarray(landmarks) 17 | landmarks = landmarks.astype('float').reshape(-1, 2) 18 | 19 | print('Image name: {}'.format(img_name)) 20 | print('Landmarks shape: {}'.format(landmarks.shape)) 21 | print('First 4 Landmarks: {}'.format(landmarks[:4])) 22 | 23 | 24 | def show_landmarks(image, landmarks): 25 | """Show image with landmarks""" 26 | plt.imshow(image) 27 | plt.scatter(landmarks[:, 0], landmarks[:, 1], s=10, marker='.', c='r') 28 | plt.pause(0.001) # pause a bit so that plots are updated 29 | 30 | plt.figure() 31 | show_landmarks(io.imread(os.path.join('./faces', img_name)), 32 | landmarks) 33 | plt.show() 34 | 35 | 36 | ## Creating the dataset 37 | ''' 38 | torch.utils.data.Dataset is an abstract class representing a dataset. Your custom dataset should inherit Dataset and override the following methods: 39 | 40 | __len__ so that len(dataset) returns the size of the dataset. 41 | __getitem__ to support the indexing such that dataset[i] can be used to get iiith sample. 42 | 43 | ''' 44 | 45 | class FaceLandmarksDataset(Dataset): 46 | """Face Landmarks dataset.""" 47 | 48 | def __init__(self, csv_file, root_dir, transform=None): 49 | """ 50 | Args: 51 | csv_file (string): Path to the csv file with annotations. 52 | root_dir (string): Directory with all the images. 53 | transform (callable, optional): Optional transform to be applied 54 | on a sample. 55 | """ 56 | self.landmarks_frame = pd.read_csv(csv_file) 57 | self.root_dir = root_dir 58 | self.transform = transform 59 | 60 | def __len__(self): 61 | return len(self.landmarks_frame) 62 | 63 | def __getitem__(self, idx): 64 | if torch.is_tensor(idx): 65 | idx = idx.tolist() 66 | 67 | img_name = os.path.join(self.root_dir, 68 | self.landmarks_frame.iloc[idx, 0]) 69 | image = io.imread(img_name) 70 | landmarks = self.landmarks_frame.iloc[idx, 1:] 71 | landmarks = np.array([landmarks]) 72 | landmarks = landmarks.astype('float').reshape(-1, 2) 73 | sample = {'image': image, 'landmarks': landmarks} 74 | 75 | if self.transform: 76 | sample = self.transform(sample) 77 | 78 | return sample 79 | 80 | face_dataset = FaceLandmarksDataset(csv_file='./face_landmarks.csv', 81 | root_dir='./faces') 82 | 83 | fig = plt.figure() 84 | 85 | for i in range(len(face_dataset)): 86 | sample = face_dataset[i] 87 | 88 | print(i, sample['image'].shape, sample['landmarks'].shape) 89 | 90 | ax = plt.subplot(1, 4, i + 1) 91 | plt.tight_layout() 92 | ax.set_title('Sample #{}'.format(i)) 93 | ax.axis('off') 94 | show_landmarks(**sample) 95 | 96 | if i == 3: 97 | plt.show() 98 | break -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/0805personali01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/0805personali01.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/1084239450_e76e00b7e7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/1084239450_e76e00b7e7.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/10comm-decarlo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/10comm-decarlo.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/110276240_bec305da91.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/110276240_bec305da91.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/1198_0_861.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/1198_0_861.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/137341995_e7c48e9a75.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/137341995_e7c48e9a75.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/1383023626_8a49e4879a.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/1383023626_8a49e4879a.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/144044282_87cf3ff76e.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/144044282_87cf3ff76e.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/152601997_ec6429a43c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/152601997_ec6429a43c.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/1549040388_b99e9fa295.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/1549040388_b99e9fa295.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/1878519279_f905d4f34e.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/1878519279_f905d4f34e.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2046713398_91aaa6fe1c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2046713398_91aaa6fe1c.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2173711035_dbd53b4f9f.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2173711035_dbd53b4f9f.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2210514040_6b03ff2629.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2210514040_6b03ff2629.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2322901504_08122b01ba.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2322901504_08122b01ba.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2327253037_66a61ea6fe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2327253037_66a61ea6fe.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2328398005_d328a70b4c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2328398005_d328a70b4c.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2370961440_6bc8ce346c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2370961440_6bc8ce346c.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2382SJ8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2382SJ8.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/252418361_440b75751b.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/252418361_440b75751b.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/262007783_943bbcf613.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/262007783_943bbcf613.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2633371780_45b740b670.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2633371780_45b740b670.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2647088981_60e9fe40cd.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2647088981_60e9fe40cd.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2711409561_a0786a3d3d.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2711409561_a0786a3d3d.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2722779845_7fcb64a096.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2722779845_7fcb64a096.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2795838930_0cc5aa5f41.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2795838930_0cc5aa5f41.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2902323565_100017b63c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2902323565_100017b63c.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2902760364_89c50bde40.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2902760364_89c50bde40.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/2956581526_cd803f2daa.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/2956581526_cd803f2daa.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/297448785_b2dda4b2c0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/297448785_b2dda4b2c0.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/299733036_fff5ea6f8e.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/299733036_fff5ea6f8e.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/303808204_1f744bc407.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/303808204_1f744bc407.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3074791551_baee7fa0c1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3074791551_baee7fa0c1.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3152653555_68322314f3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3152653555_68322314f3.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3264867945_fe18d442c1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3264867945_fe18d442c1.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3273658251_b95f65c244.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3273658251_b95f65c244.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3298715079_5af7c78fcb.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3298715079_5af7c78fcb.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3325611505_ddc7beffa1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3325611505_ddc7beffa1.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3362762930_24f76cb89c.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3362762930_24f76cb89c.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/343583208_e986824d77.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/343583208_e986824d77.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3461016494_56cce9c984.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3461016494_56cce9c984.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/348272697_832ce65324.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/348272697_832ce65324.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3534188114_2108895291.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3534188114_2108895291.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3534189272_8ef88ba368.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3534189272_8ef88ba368.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3555944509_7b477069c6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3555944509_7b477069c6.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3574737496_6ee8207045.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3574737496_6ee8207045.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/362167809_d5a5dcbfdb.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/362167809_d5a5dcbfdb.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/363149951_8be04dc6c0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/363149951_8be04dc6c0.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3638950581_3387685d3a.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3638950581_3387685d3a.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3646828311_bfeb429ef7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3646828311_bfeb429ef7.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3689162471_5f9ffb5aa0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3689162471_5f9ffb5aa0.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3718903026_c1bf5dfcf8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3718903026_c1bf5dfcf8.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3790616528_297c0ac935.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3790616528_297c0ac935.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3855944735_e252959937.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3855944735_e252959937.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3856149136_d4595ffdd4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3856149136_d4595ffdd4.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/3872768751_e60d7fdbd5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/3872768751_e60d7fdbd5.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/529447797_0f9d2fb756.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/529447797_0f9d2fb756.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/57635685_d41c98f8ca.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/57635685_d41c98f8ca.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/809285949_6889026b53.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/809285949_6889026b53.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/92053278_be61a225d2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/92053278_be61a225d2.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/96063776_bdb3617b64.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/96063776_bdb3617b64.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/97308305_4b737d0873.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/97308305_4b737d0873.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/britney-bald.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/britney-bald.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/create_landmark_dataset.py: -------------------------------------------------------------------------------- 1 | """Create a sample face landmarks dataset. 2 | 3 | Adapted from dlib/python_examples/face_landmark_detection.py 4 | See this file for more explanation. 5 | 6 | Download a trained facial shape predictor from: 7 | http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2 8 | """ 9 | import dlib 10 | import glob 11 | import csv 12 | from skimage import io 13 | 14 | detector = dlib.get_frontal_face_detector() 15 | predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') 16 | num_landmarks = 68 17 | 18 | with open('face_landmarks.csv', 'w', newline='') as csvfile: 19 | csv_writer = csv.writer(csvfile) 20 | 21 | header = ['image_name'] 22 | for i in range(num_landmarks): 23 | header += ['part_{}_x'.format(i), 'part_{}_y'.format(i)] 24 | 25 | csv_writer.writerow(header) 26 | 27 | for f in glob.glob('*.jpg'): 28 | img = io.imread(f) 29 | dets = detector(img, 1) # face detection 30 | 31 | # ignore all the files with no or more than one faces detected. 32 | if len(dets) == 1: 33 | row = [f] 34 | 35 | d = dets[0] 36 | # Get the landmarks/parts for the face in box d. 37 | shape = predictor(img, d) 38 | for i in range(num_landmarks): 39 | part_i_x = shape.part(i).x 40 | part_i_y = shape.part(i).y 41 | row += [part_i_x, part_i_y] 42 | 43 | csv_writer.writerow(row) 44 | -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/deeny.peggy.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/deeny.peggy.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/matt-mathes.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/matt-mathes.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/person-7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/person-7.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/person.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/person.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/person_TjahjonoDGondhowiardjo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/person_TjahjonoDGondhowiardjo.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Custom_dataset_images/faces/personalpic.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Machine Learning/Pytorch_series/Custom_dataset_images/faces/personalpic.jpg -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/Instance_Segmentation/README.md: -------------------------------------------------------------------------------- 1 | # Mask R-CNN Implementation with PyTorch 2 | 3 | The dataset for this task can directly be downloaded by running the code cell and unzipping it. 4 | 5 | All the details related to performing the task have been explained in this [medium blog post](https://medium.com/@mohit_gaikwad/mask-r-cnn-implementation-with-pytorch-4aeb210ee9b7). 6 | Mask R-CNN research [paper review post](https://medium.com/@mohit_gaikwad/review-mask-r-cnn-f395b46499fb). 7 | 8 | Apart from the code in the post, changes that can be made are: 9 | 1. Using a different Optimizer. 10 | 2. Using a different predictor head. 11 | 3. Using different data augmentation techniques. 12 | 4. Trying out different hyperparameters. 13 | 5. Training for more number of epochs. 14 | 15 | Please fork this repo and figure out what more updates could be done to the code for achieveing better mAP. 16 | -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/README.md: -------------------------------------------------------------------------------- 1 | # PyTorch Implementation 2 | 3 | This repo contains: 4 | 5 | >> implementing CNN, RNN, LSTM, GRU from scratch with Pytorch. 6 | 7 | >> Creating Dataset to train a Model. 8 | 9 | >> Data Augmentation Techniques. 10 | 11 | >> Trainig a INstance Segmentation Network by Fine-Tuning Mask-RCNN. 12 | 13 | Future addition: 14 | >> Object Detection using YOLOv4. 15 | 16 | >> Object Classification. 17 | 18 | >> Other PyTorch basic concepts. 19 | 20 | In case any doubt related to concept, try directly refering to PyTorch's original Documentation. 21 | -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/RNN_network.py: -------------------------------------------------------------------------------- 1 | # Imports 2 | 3 | import torch 4 | import torchvision # torch package for vision related things 5 | import torch.nn.functional as F # Parameterless functions, like (some) activation functions 6 | import torchvision.datasets as datasets # Standard datasets 7 | import torchvision.transforms as transforms # Transformations we can perform on our dataset for augmentation 8 | from torch import optim # For optimizers like SGD, Adam, etc. 9 | from torch import nn # All neural network modules 10 | from torch.utils.data import DataLoader # Gives easier dataset managment by creating mini batches etc. 11 | from tqdm import tqdm # For a nice progress bar! 12 | 13 | # Set device 14 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 15 | 16 | # Hyperparameters 17 | input_size = 28 18 | hidden_size = 256 19 | num_layers = 2 20 | num_classes = 10 21 | sequence_length = 28 22 | learning_rate = 0.005 23 | batch_size = 64 24 | num_epochs = 3 25 | 26 | # Recurrent neural network (many-to-one) 27 | class RNN(nn.Module): 28 | def __init__(self, input_size, hidden_size, num_layers, num_classes): 29 | super(RNN, self).__init__() 30 | self.hidden_size = hidden_size 31 | self.num_layers = num_layers 32 | self.rnn = nn.RNN(input_size, hidden_size, num_layers, batch_first=True) 33 | self.fc = nn.Linear(hidden_size * sequence_length, num_classes) 34 | 35 | def forward(self, x): 36 | # Set initial hidden and cell states 37 | h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) 38 | 39 | # Forward propagate LSTM 40 | out, _ = self.rnn(x, h0) 41 | out = out.reshape(out.shape[0], -1) 42 | 43 | # Decode the hidden state of the last time step 44 | out = self.fc(out) 45 | return out 46 | 47 | # Recurrent neural network with GRU (many-to-one) 48 | class RNN_GRU(nn.Module): 49 | def __init__(self, input_size, hidden_size, num_layers, num_classes): 50 | super(RNN_GRU, self).__init__() 51 | self.hidden_size = hidden_size 52 | self.num_layers = num_layers 53 | self.gru = nn.GRU(input_size, hidden_size, num_layers, batch_first=True) 54 | self.fc = nn.Linear(hidden_size * sequence_length, num_classes) 55 | 56 | def forward(self, x): 57 | # Set initial hidden and cell states 58 | h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) 59 | 60 | # Forward propagate LSTM 61 | out, _ = self.gru(x, h0) 62 | out = out.reshape(out.shape[0], -1) 63 | 64 | # Decode the hidden state of the last time step 65 | out = self.fc(out) 66 | return out 67 | 68 | # Recurrent neural network with LSTM (many-to-one) 69 | class RNN_LSTM(nn.Module): 70 | def __init__(self, input_size, hidden_size, num_layers, num_classes): 71 | super(RNN_LSTM, self).__init__() 72 | self.hidden_size = hidden_size 73 | self.num_layers = num_layers 74 | self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) 75 | self.fc = nn.Linear(hidden_size * sequence_length, num_classes) 76 | 77 | def forward(self, x): 78 | # Set initial hidden and cell states 79 | h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) 80 | c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(device) 81 | 82 | # Forward propagate LSTM 83 | out, _ = self.lstm( 84 | x, (h0, c0) 85 | ) # out: tensor of shape (batch_size, seq_length, hidden_size) 86 | out = out.reshape(out.shape[0], -1) 87 | 88 | # Decode the hidden state of the last time step 89 | out = self.fc(out) 90 | return out 91 | 92 | # Load Data 93 | train_dataset = datasets.MNIST(root="dataset/", train=True, transform=transforms.ToTensor(), download=True) 94 | test_dataset = datasets.MNIST(root="dataset/", train=False, transform=transforms.ToTensor(), download=True) 95 | train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) 96 | test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) 97 | 98 | # Initialize network (try out just using simple RNN, or GRU, and then compare with LSTM) 99 | model = RNN(input_size, hidden_size, num_layers, num_classes).to(device) 100 | 101 | # Loss and optimizer 102 | criterion = nn.CrossEntropyLoss() 103 | optimizer = optim.Adam(model.parameters(), lr=learning_rate) 104 | 105 | # Train Network 106 | for epoch in range(num_epochs): 107 | for batch_idx, (data, targets) in enumerate(tqdm(train_loader)): 108 | # Get data to cuda if possible 109 | data = data.to(device=device).squeeze(1) 110 | targets = targets.to(device=device) 111 | 112 | # forward 113 | scores = model(data) 114 | loss = criterion(scores, targets) 115 | 116 | # backward 117 | optimizer.zero_grad() 118 | loss.backward() 119 | 120 | # gradient descent update step/adam step 121 | optimizer.step() 122 | 123 | # Check accuracy on training & test to see how good our model 124 | def check_accuracy(loader, model): 125 | num_correct = 0 126 | num_samples = 0 127 | 128 | # Set model to eval 129 | model.eval() 130 | 131 | with torch.no_grad(): 132 | for x, y in loader: 133 | x = x.to(device=device).squeeze(1) 134 | y = y.to(device=device) 135 | 136 | scores = model(x) 137 | _, predictions = scores.max(1) 138 | num_correct += (predictions == y).sum() 139 | num_samples += predictions.size(0) 140 | 141 | # Toggle model back to train 142 | model.train() 143 | return num_correct / num_samples 144 | 145 | print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:2f}") 146 | print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}") -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/bidirectinal_lstm.py: -------------------------------------------------------------------------------- 1 | # Imports 2 | import torch 3 | import torchvision # torch package for vision related things 4 | import torch.nn.functional as F # Parameterless functions, like (some) activation functions 5 | import torchvision.datasets as datasets # Standard datasets 6 | import torchvision.transforms as transforms # Transformations we can perform on our dataset for augmentation 7 | from torch import optim # For optimizers like SGD, Adam, etc. 8 | from torch import nn # All neural network modules 9 | from torch.utils.data import DataLoader # Gives easier dataset managment by creating mini batches etc. 10 | from tqdm import tqdm # For a nice progress bar! 11 | 12 | # Set device 13 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 14 | 15 | # Hyperparameters 16 | input_size = 28 17 | hidden_size = 256 18 | num_layers = 2 19 | num_classes = 10 20 | sequence_length = 28 21 | learning_rate = 0.005 22 | batch_size = 64 23 | num_epochs = 3 24 | 25 | # Create a bidirectional LSTM 26 | class BRNN(nn.Module): 27 | def __init__(self, input_size, hidden_size, num_layers, num_classes): 28 | super(BRNN, self).__init__() 29 | self.hidden_size = hidden_size 30 | self.num_layers = num_layers 31 | self.lstm = nn.LSTM( 32 | input_size, hidden_size, num_layers, batch_first=True, bidirectional=True 33 | ) 34 | self.fc = nn.Linear(hidden_size * 2, num_classes) 35 | 36 | def forward(self, x): 37 | h0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(device) 38 | c0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size).to(device) 39 | 40 | out, _ = self.lstm(x, (h0, c0)) 41 | out = self.fc(out[:, -1, :]) 42 | 43 | return out 44 | 45 | 46 | # Load Data 47 | train_dataset = datasets.MNIST(root="dataset/", train=True, transform=transforms.ToTensor(), download=True) 48 | test_dataset = datasets.MNIST(root="dataset/", train=False, transform=transforms.ToTensor(), download=True) 49 | train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) 50 | test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) 51 | 52 | # Initialize network (try out just using simple RNN, or GRU, and then compare with LSTM) 53 | model = BRNN(input_size, hidden_size, num_layers, num_classes).to(device) 54 | 55 | # Loss and optimizer 56 | criterion = nn.CrossEntropyLoss() 57 | optimizer = optim.Adam(model.parameters(), lr=learning_rate) 58 | 59 | # Train Network 60 | for epoch in range(num_epochs): 61 | for batch_idx, (data, targets) in enumerate(tqdm(train_loader)): 62 | # Get data to cuda if possible 63 | data = data.to(device=device).squeeze(1) 64 | targets = targets.to(device=device) 65 | 66 | # forward 67 | scores = model(data) 68 | loss = criterion(scores, targets) 69 | 70 | # backward 71 | optimizer.zero_grad() 72 | loss.backward() 73 | 74 | # gradient descent update step/adam step 75 | optimizer.step() 76 | 77 | # Check accuracy on training & test to see how good our model 78 | def check_accuracy(loader, model): 79 | num_correct = 0 80 | num_samples = 0 81 | 82 | # Set model to eval 83 | model.eval() 84 | 85 | with torch.no_grad(): 86 | for x, y in loader: 87 | x = x.to(device=device).squeeze(1) 88 | y = y.to(device=device) 89 | 90 | scores = model(x) 91 | _, predictions = scores.max(1) 92 | num_correct += (predictions == y).sum() 93 | num_samples += predictions.size(0) 94 | 95 | # Toggle model back to train 96 | model.train() 97 | return num_correct / num_samples 98 | 99 | print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:2f}") 100 | print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}") -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/data_augmentation.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Refer to the original blog for more info: https://pytorch.org/vision/stable/transforms.html 3 | 4 | ''' 5 | 6 | ## Imports 7 | import torch 8 | import torchvision # torch package for vision related things 9 | import torch.nn.functional as F # Parameterless functions, like (some) activation functions 10 | import torchvision.datasets as datasets # Standard datasets 11 | import torchvision.transforms as transforms # Transformations we can perform on our dataset for augmentation 12 | from torch import optim # For optimizers like SGD, Adam, etc. 13 | from torch import nn # All neural network modules 14 | from torch.utils.data import DataLoader # Gives easier dataset managment by creating mini batches etc. 15 | from tqdm import tqdm # For nice progress bar! 16 | 17 | # Set device 18 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 19 | 20 | # Hyperparameters 21 | in_channels = 3 22 | num_classes = 10 23 | learning_rate = 0.001 24 | batch_size = 64 25 | num_epochs = 5 26 | load_model = True 27 | 28 | # Applied transformation 29 | my_transforms = transforms.Compose( 30 | [ # Compose makes it possible to have many transforms 31 | transforms.Resize((224,224)), # Resizes (32,32) to (36,36) 32 | transforms.RandomCrop((132, 132)), # Takes a random (32,32) crop 33 | transforms.ColorJitter(brightness=0.5), # Change brightness of image 34 | transforms.RandomRotation( 35 | degrees=45 36 | ), # Perhaps a random rotation from -45 to 45 degrees 37 | transforms.RandomHorizontalFlip( 38 | p=0.5 39 | ), # Flips the image horizontally with probability 0.5 40 | transforms.RandomVerticalFlip( 41 | p=0.05 42 | ), # Flips image vertically with probability 0.05 43 | transforms.RandomGrayscale(p=0.2), # Converts to grayscale with probability 0.2 44 | transforms.ToTensor(), # Finally converts PIL image to tensor so we can train w. pytorch 45 | transforms.Normalize( 46 | mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5] 47 | ), # Note: these values aren't optimal 48 | ] 49 | ) 50 | 51 | # Load Data 52 | train_dataset = datasets.CIFAR10( 53 | root="dataset/", train=True, transform=my_transforms, download=True 54 | ) 55 | test_dataset = datasets.CIFAR10(root="dataset/", train=False, transform=my_transforms, download=True) 56 | 57 | train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) 58 | test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) 59 | 60 | ''' 61 | class CNN(nn.Module): 62 | def __init__(self,in_channels=1, num_classes=10): 63 | super(CNN,self).__init__() 64 | self.conv1 = nn.Conv2d(in_channels = in_channels,out_channels = 8,kernel_size=(3, 3),stride=(1, 1),padding=(1, 1),) 65 | self.pool = nn.MaxPool2d((2,2), (2,2)) 66 | self.conv2 = nn.Conv2d(in_channels=8, 67 | out_channels=16, 68 | kernel_size=(3, 3), 69 | stride=(1, 1), 70 | padding=(1, 1), 71 | ) 72 | self.dropout1 = nn.Dropout(0.3) 73 | self.dropout2 = nn.Dropout(0.3) 74 | 75 | self.fc1 = nn.Linear(1024, 512) 76 | self.fc2 = nn.Linear(512, 64) 77 | self.fc3 = nn.Linear(64, num_classes) 78 | 79 | def forward(self, x): 80 | x = self.pool(F.relu(self.conv1(x))) 81 | x = self.dropout1(x) 82 | x = self.pool(F.relu(self.conv2(x))) 83 | x = torch.flatten(x, 1) 84 | x = self.dropout1(x) 85 | x = F.relu(self.fc1(x)) 86 | x = self.dropout1(x) 87 | x = F.relu(self.fc2(x)) 88 | x = self.fc3(x) 89 | return x 90 | ''' 91 | 92 | ''' 93 | # Initialize network 94 | model = CNN(in_channels=in_channels, num_classes=num_classes).to(device) 95 | ''' 96 | 97 | # Simple Identity class that let's input pass without changes 98 | class Identity(nn.Module): 99 | def __init__(self): 100 | super(Identity, self).__init__() 101 | 102 | def forward(self, x): 103 | return x 104 | 105 | # Load pretrain model & modify it 106 | model = torchvision.models.vgg19(pretrained=True) 107 | 108 | # If you want to do finetuning then set requires_grad = False 109 | # Remove these two lines if you want to train entire model, 110 | # and only want to load the pretrain weights. 111 | for param in model.parameters(): 112 | param.requires_grad = False 113 | 114 | model.avgpool = Identity() 115 | model.classifier = nn.Sequential( 116 | nn.Linear(512, 100), nn.ReLU(), nn.Dropout(),nn.Linear(100, num_classes) 117 | ) 118 | model.to(device) 119 | 120 | # Loss and optimizer 121 | criterion = nn.CrossEntropyLoss() 122 | optimizer = optim.Adam(model.parameters(),lr = learning_rate) 123 | 124 | # Train Network 125 | for epoch in range(num_epochs): 126 | losses = [] 127 | # if epoch % 3 == 0: 128 | # checkpoint = {"state_dict": model.state_dict(), "optimizer": optimizer.state_dict()} 129 | # # Try save checkpoint 130 | # save_checkpoint(checkpoint) 131 | 132 | for batch_idx, (data, targets) in enumerate(tqdm(train_loader)): 133 | # Get data to cuda if possible 134 | data = data.to(device=device) 135 | targets = targets.to(device=device) 136 | 137 | # forward 138 | scores = model(data) 139 | loss = criterion(scores, targets) 140 | 141 | # backward 142 | optimizer.zero_grad() 143 | loss.backward() 144 | losses.append(loss.item()) 145 | # gradient descent or adam step 146 | optimizer.step() 147 | 148 | print(f"Cost at epoch {epoch} is {sum(losses)/len(losses):.5f}") 149 | 150 | # Check accuracy on training & test to see how good our model 151 | def check_accuracy(loader, model): 152 | num_correct = 0 153 | num_samples = 0 154 | model.eval() 155 | 156 | with torch.no_grad(): 157 | for x, y in loader: 158 | x = x.to(device=device) 159 | y = y.to(device=device) 160 | 161 | scores = model(x) 162 | _, predictions = scores.max(1) 163 | num_correct += (predictions == y).sum() 164 | num_samples += predictions.size(0) 165 | 166 | print( 167 | f"Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}" 168 | ) 169 | model.train() 170 | 171 | check_accuracy(test_loader, model) -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/handling_imbalanced_dataset.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Dataset: https://www.kaggle.com/datasets/77934f795ab14e30431ba210ec52d6ebb8b271da3a8e2d524012fdd5bec276ca 3 | 4 | Refer this blog for more detialed knowledge abot handling imbalanced dataset: https://towardsdatascience.com/address-class-imbalance-easily-with-pytorch-e2d4fa208627 5 | ''' 6 | import torch 7 | import torchvision.datasets as datasets 8 | import os 9 | from torch.utils.data import WeightedRandomSampler, DataLoader 10 | import torchvision.transforms as transforms 11 | import torch.nn as nn 12 | 13 | # Methods for dealing with imbalanced datasets: 14 | # 1. Oversampling 15 | # 2. Class weighting 16 | 17 | def get_loader(root_dir, batch_size): 18 | my_transforms = transforms.Compose( 19 | [ 20 | transforms.Resize((224, 224)), 21 | transforms.ToTensor(), 22 | ] 23 | ) 24 | 25 | dataset = datasets.ImageFolder(root=root_dir, transform=my_transforms) 26 | class_weights = [] 27 | for root, subdir, files in os.walk(root_dir): 28 | if len(files) > 0: 29 | class_weights.append(1/len(files)) 30 | 31 | sample_weights = [0] * len(dataset) 32 | 33 | for idx, (data, label) in enumerate(dataset): 34 | class_weight = class_weights[label] 35 | sample_weights[idx] = class_weight 36 | 37 | sampler = WeightedRandomSampler(sample_weights, num_samples= 38 | len(sample_weights), replacement=True) 39 | 40 | loader = DataLoader(dataset, batch_size=batch_size, sampler=sampler) 41 | return loader 42 | 43 | 44 | def main(): 45 | loader = get_loader(root_dir="dataset", batch_size=8) 46 | 47 | num_retrievers = 0 48 | num_elkhounds = 0 49 | for epoch in range(10): 50 | for data, labels in loader: 51 | num_retrievers += torch.sum(labels==0) 52 | num_elkhounds += torch.sum(labels==1) 53 | 54 | print(num_retrievers) 55 | print(num_elkhounds) 56 | 57 | if __name__ == "__main__": 58 | main() 59 | -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/load_save_model.py: -------------------------------------------------------------------------------- 1 | ###################### Imports ############################# 2 | 3 | import torch 4 | import torch.nn.functional as F 5 | import torchvision.datasets as datasets 6 | import torchvision.transforms as transforms 7 | from torch import optim 8 | from torch import nn 9 | from torch.utils.data import DataLoader 10 | from tqdm import tqdm 11 | import matplotlib.pyplot as plt 12 | 13 | ##################### Building the Network ################ 14 | 15 | class CNN(nn.Module): 16 | def __init__(self,in_channels=1, num_classes=10): 17 | super(CNN,self).__init__() 18 | self.conv1 = nn.Conv2d(in_channels = in_channels,out_channels = 8,kernel_size=(3, 3),stride=(1, 1),padding=(1, 1),) 19 | self.pool = nn.MaxPool2d((2,2), (2,2)) 20 | self.conv2 = nn.Conv2d(in_channels=8, 21 | out_channels=16, 22 | kernel_size=(3, 3), 23 | stride=(1, 1), 24 | padding=(1, 1), 25 | ) 26 | self.dropout1 = nn.Dropout(0.3) 27 | self.dropout2 = nn.Dropout(0.3) 28 | 29 | self.fc1 = nn.Linear(784, 64) 30 | self.fc2 = nn.Linear(64, 32) 31 | self.fc3 = nn.Linear(32, num_classes) 32 | 33 | def forward(self, x): 34 | x = self.pool(F.relu(self.conv1(x))) 35 | x = self.dropout1(x) 36 | x = self.pool(F.relu(self.conv2(x))) 37 | x = torch.flatten(x, 1) 38 | x = self.dropout1(x) 39 | x = F.relu(self.fc1(x)) 40 | x = self.dropout1(x) 41 | x = F.relu(self.fc2(x)) 42 | x = self.fc3(x) 43 | return x 44 | 45 | def save_checkpoint(state, filename="my_checkpoint.pth.tar"): 46 | print("=> Saving checkpoint") 47 | torch.save(state, filename) 48 | 49 | 50 | def load_checkpoint(checkpoint, model, optimizer): 51 | print("=> Loading checkpoint") 52 | model.load_state_dict(checkpoint["state_dict"]) 53 | optimizer.load_state_dict(checkpoint["optimizer"]) 54 | 55 | # Set device 56 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 57 | 58 | # Hyperparameters 59 | in_channels = 1 60 | num_classes = 10 61 | learning_rate = 0.001 62 | batch_size = 32 63 | num_epochs = 5 64 | load_model = True 65 | 66 | # Load Data 67 | train_dataset = datasets.MNIST(root="dataset/", train=True, transform=transforms.ToTensor(), download=True) 68 | test_dataset = datasets.MNIST(root="dataset/", train=False, transform=transforms.ToTensor(), download=True) 69 | train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) 70 | test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) 71 | 72 | # Initialize network 73 | model = CNN(in_channels=in_channels, num_classes=num_classes).to(device) 74 | 75 | # Loss and optimizer 76 | criterion = nn.CrossEntropyLoss() 77 | optimizer = optim.RMSprop(model.parameters(),lr = learning_rate) 78 | 79 | ######################### Train Network ######################## 80 | 81 | if load_model: 82 | load_checkpoint(torch.load("my_checkpoint.pth.tar"), model, optimizer) 83 | 84 | for epoch in range(num_epochs): 85 | 86 | if epoch % 3 == 0: 87 | checkpoint = {"state_dict": model.state_dict(), "optimizer": optimizer.state_dict()} 88 | # Try save checkpoint 89 | save_checkpoint(checkpoint) 90 | 91 | for batch_idx, (data, targets) in enumerate(tqdm(train_loader)): 92 | # Get data to cuda if possible 93 | data = data.to(device=device) 94 | targets = targets.to(device=device) 95 | 96 | # forward 97 | scores = model(data) 98 | loss = criterion(scores, targets) 99 | 100 | # backward 101 | optimizer.zero_grad() 102 | loss.backward() 103 | 104 | # gradient descent or adam step 105 | optimizer.step() 106 | 107 | # Check accuracy on training & test to see how good our model 108 | def check_accuracy(loader, model): 109 | num_correct = 0 110 | num_samples = 0 111 | model.eval() 112 | 113 | with torch.no_grad(): 114 | for x, y in loader: 115 | x = x.to(device=device) 116 | y = y.to(device=device) 117 | 118 | scores = model(x) 119 | _, predictions = scores.max(1) 120 | num_correct += (predictions == y).sum() 121 | num_samples += predictions.size(0) 122 | 123 | 124 | model.train() 125 | return num_correct/num_samples 126 | 127 | print(f"Accuracy on training set: {check_accuracy(train_loader, model)*100:.2f}") 128 | print(f"Accuracy on test set: {check_accuracy(test_loader, model)*100:.2f}") 129 | 130 | 131 | ## Saving the model 132 | 133 | PATH = './cifar_net.pth' 134 | torch.save(model.state_dict(), PATH) 135 | 136 | ###################### Testing the Model ######################### 137 | 138 | examples = enumerate(test_loader) 139 | batch_idx, (example_data, example_targets) = next(examples) 140 | 141 | fig = plt.figure() 142 | for i in range(6): 143 | plt.subplot(2,3,i+1) 144 | plt.tight_layout() 145 | plt.imshow(example_data[i][0], cmap='gray', interpolation='none') 146 | plt.title("Ground Truth: {}".format(example_targets[i])) 147 | plt.xticks([]) 148 | plt.yticks([]) 149 | 150 | fig.show() 151 | 152 | classes = ('0', '1', '2', '3', 153 | '4', '5', '6', '7', '8', '9') 154 | 155 | net = CNN() 156 | net.load_state_dict(torch.load(PATH)) 157 | 158 | ############# Predict accuracy per class ################ 159 | 160 | correct_pred = {classname: 0 for classname in classes} 161 | total_pred = {classname: 0 for classname in classes} 162 | 163 | # again no gradients needed 164 | with torch.no_grad(): 165 | for data in test_loader: 166 | images, labels = data 167 | outputs = net(images) 168 | _, predictions = torch.max(outputs, 1) 169 | # collect the correct predictions for each class 170 | for label, prediction in zip(labels, predictions): 171 | if label == prediction: 172 | correct_pred[classes[label]] += 1 173 | total_pred[classes[label]] += 1 174 | 175 | 176 | # print accuracy for each class 177 | for classname, correct_count in correct_pred.items(): 178 | accuracy = 100 * float(correct_count) / total_pred[classname] 179 | print(f'Accuracy for class: {classname:5s} is {accuracy:.1f} %') -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/sample_neural_network.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torch.optim as optim 4 | import torch.nn.functional as F 5 | from torch.utils.data import DataLoader 6 | import torchvision.datasets as dataset 7 | import torchvision.transforms as transforms 8 | from tqdm import tqdm 9 | from yaml import load 10 | 11 | # Create a fully connected Network 12 | class NN(nn.Module): 13 | def __init__(self,input_size,no_of_classes): 14 | super(NN,self).__init__() 15 | 16 | ''' 17 | Add some more layers to imporve the performance of the model 18 | ''' 19 | self.flatten = nn.Flatten() 20 | self.linear_relu_stack = nn.Sequential( 21 | nn.Linear(input_size, 512), 22 | nn.ReLU(), 23 | nn.Linear(512, 512), 24 | nn.ReLU(), 25 | nn.Linear(512, no_of_classes), 26 | ) 27 | 28 | def forward(self, x): 29 | x = self.flatten(x) 30 | logits = self.linear_relu_stack(x) 31 | return logits 32 | 33 | # Setting up the device 34 | device =torch.device('cuda'if torch.cuda.is_available () else 'cpu') 35 | 36 | # Hyper Parameters 37 | input_size = 784 ## Input size of the image 38 | num_classes = 10 39 | learning_rate = 0.0001 40 | batch_size = 64 41 | num_epochs = 5 42 | 43 | # Load dataset 44 | train_dataset = dataset.MNIST(root='dataset/',train=True,transform=transforms.ToTensor(),download=True) 45 | test_dataset = dataset.MNIST(root='dataset/',train=False,transform=transforms.ToTensor(),download=True) 46 | train_loader = DataLoader(dataset=train_dataset,batch_size=batch_size,shuffle=True) 47 | test_loader = DataLoader(dataset=test_dataset,batch_size=batch_size,shuffle=True) 48 | 49 | # Initialize the network 50 | model = NN(input_size=input_size,no_of_classes = num_classes) 51 | 52 | # Loss Function and Optimizer 53 | loss_fcn = nn.CrossEntropyLoss() 54 | optimizer = optim.RMSprop(model.parameters(),lr = learning_rate) 55 | 56 | # Train the Netork 57 | for epoch in range(num_epochs): 58 | for batch_idx,(data,targets) in enumerate (tqdm(train_loader)): 59 | # Get data to cuda if possible 60 | data = data.to(device = device) 61 | ''' 62 | shape = 64,1,28,28 -- Batch size,No of channels,width,height 63 | ''' 64 | targets = targets.to(device = device) 65 | 66 | # Reshape the Tensor 67 | data = data.reshape(data.shape[0],-1) 68 | ''' 69 | shape = 64,784 -- Batch size,No of channels x width x height 70 | ''' 71 | 72 | # Forward Pass 73 | score = model(data) 74 | loss = loss_fcn(score,targets) 75 | 76 | # Backpass 77 | optimizer.zero_grad() 78 | loss.backward() 79 | 80 | optimizer.step() 81 | 82 | def check_acc(loader,model): 83 | 84 | num_correct = 0 85 | num_samples = 0 86 | model.eval() 87 | 88 | with torch.no_grad(): 89 | for x,y in loader: 90 | x = x.to(device = device) 91 | y = y.to(device = device) 92 | x = x.reshape(x.shape[0],-1) 93 | 94 | scores = model(x) 95 | _,predictions = scores.max(1) 96 | num_correct += (predictions == y).sum() 97 | num_samples += predictions.size(0) 98 | 99 | 100 | model.train() 101 | return num_correct / num_samples 102 | 103 | print(f"Accuracy on training set: {check_acc(train_loader, model)*100:.2f}") 104 | print(f"Accuracy on test set: {check_acc(test_loader, model)*100:.2f}") -------------------------------------------------------------------------------- /Machine Learning/Pytorch_series/transfer_learning.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torchvision # torch package for vision related things 3 | import torch.nn.functional as F # Parameterless functions, like (some) activation functions 4 | import torchvision.datasets as datasets # Standard datasets 5 | import torchvision.transforms as transforms # Transformations we can perform on our dataset for augmentation 6 | from torch import optim # For optimizers like SGD, Adam, etc. 7 | from torch import nn # All neural network modules 8 | from torch.utils.data import DataLoader # Gives easier dataset managment by creating mini batches etc. 9 | from tqdm import tqdm # For nice progress bar! 10 | 11 | # Set device 12 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 13 | 14 | # Hyperparameters 15 | in_channels = 3 16 | num_classes = 10 17 | learning_rate = 0.001 18 | batch_size = 1024 19 | num_epochs = 5 20 | load_model = True 21 | 22 | # Load Data 23 | train_dataset = datasets.CIFAR10( 24 | root="dataset/", train=True, transform=transforms.ToTensor(), download=True 25 | ) 26 | test_dataset = datasets.CIFAR10(root="dataset/", train=False, transform=transforms.ToTensor(), download=True) 27 | 28 | train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True) 29 | test_loader = DataLoader(dataset=test_dataset, batch_size=batch_size, shuffle=True) 30 | 31 | ''' 32 | class CNN(nn.Module): 33 | def __init__(self,in_channels=1, num_classes=10): 34 | super(CNN,self).__init__() 35 | self.conv1 = nn.Conv2d(in_channels = in_channels,out_channels = 8,kernel_size=(3, 3),stride=(1, 1),padding=(1, 1),) 36 | self.pool = nn.MaxPool2d((2,2), (2,2)) 37 | self.conv2 = nn.Conv2d(in_channels=8, 38 | out_channels=16, 39 | kernel_size=(3, 3), 40 | stride=(1, 1), 41 | padding=(1, 1), 42 | ) 43 | self.dropout1 = nn.Dropout(0.3) 44 | self.dropout2 = nn.Dropout(0.3) 45 | 46 | self.fc1 = nn.Linear(1024, 512) 47 | self.fc2 = nn.Linear(512, 64) 48 | self.fc3 = nn.Linear(64, num_classes) 49 | 50 | def forward(self, x): 51 | x = self.pool(F.relu(self.conv1(x))) 52 | x = self.dropout1(x) 53 | x = self.pool(F.relu(self.conv2(x))) 54 | x = torch.flatten(x, 1) 55 | x = self.dropout1(x) 56 | x = F.relu(self.fc1(x)) 57 | x = self.dropout1(x) 58 | x = F.relu(self.fc2(x)) 59 | x = self.fc3(x) 60 | return x 61 | ''' 62 | 63 | ''' 64 | # Initialize network 65 | model = CNN(in_channels=in_channels, num_classes=num_classes).to(device) 66 | ''' 67 | 68 | # Simple Identity class that let's input pass without changes 69 | class Identity(nn.Module): 70 | def __init__(self): 71 | super(Identity, self).__init__() 72 | 73 | def forward(self, x): 74 | return x 75 | 76 | # Load pretrain model & modify it 77 | model = torchvision.models.vgg19(pretrained=True) 78 | 79 | # If you want to do finetuning then set requires_grad = False 80 | # Remove these two lines if you want to train entire model, 81 | # and only want to load the pretrain weights. 82 | for param in model.parameters(): 83 | param.requires_grad = False 84 | 85 | model.avgpool = Identity() 86 | model.classifier = nn.Sequential( 87 | nn.Linear(512, 100), nn.ReLU(), nn.Dropout(),nn.Linear(100, num_classes) 88 | ) 89 | model.to(device) 90 | 91 | # Loss and optimizer 92 | criterion = nn.CrossEntropyLoss() 93 | optimizer = optim.Adam(model.parameters(),lr = learning_rate) 94 | 95 | # Train Network 96 | for epoch in range(num_epochs): 97 | losses = [] 98 | # if epoch % 3 == 0: 99 | # checkpoint = {"state_dict": model.state_dict(), "optimizer": optimizer.state_dict()} 100 | # # Try save checkpoint 101 | # save_checkpoint(checkpoint) 102 | 103 | for batch_idx, (data, targets) in enumerate(tqdm(train_loader)): 104 | # Get data to cuda if possible 105 | data = data.to(device=device) 106 | targets = targets.to(device=device) 107 | 108 | # forward 109 | scores = model(data) 110 | loss = criterion(scores, targets) 111 | 112 | # backward 113 | optimizer.zero_grad() 114 | loss.backward() 115 | losses.append(loss.item()) 116 | # gradient descent or adam step 117 | optimizer.step() 118 | 119 | print(f"Cost at epoch {epoch} is {sum(losses)/len(losses):.5f}") 120 | 121 | # Check accuracy on training & test to see how good our model 122 | def check_accuracy(loader, model): 123 | num_correct = 0 124 | num_samples = 0 125 | model.eval() 126 | 127 | with torch.no_grad(): 128 | for x, y in loader: 129 | x = x.to(device=device) 130 | y = y.to(device=device) 131 | 132 | scores = model(x) 133 | _, predictions = scores.max(1) 134 | num_correct += (predictions == y).sum() 135 | num_samples += predictions.size(0) 136 | 137 | print( 138 | f"Got {num_correct} / {num_samples} with accuracy {float(num_correct)/float(num_samples)*100:.2f}" 139 | ) 140 | model.train() 141 | 142 | check_accuracy(train_loader, model) 143 | 144 | 145 | ''' 146 | A self created CNN model as mentioned above when trained on CIFAR10 dataset gives an accuracy of ~ 46%, 147 | whereas, when vgg19 is fine-tuned the accuracy improves upto 60%when trained fpr 5 epochs. 148 | 149 | ''' -------------------------------------------------------------------------------- /Machine Learning/smile detection/detection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import random 4 | 5 | 6 | face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') 7 | smile_cascade=cv2.CascadeClassifier('smile.xml') 8 | 9 | cap=cv2.VideoCapture(0) 10 | 11 | run=True 12 | while run: 13 | ret, img =cap.read() 14 | gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 15 | faces=face_cascade.detectMultiScale(gray, 1.1, 5) 16 | 17 | for (x,y,w,h) in faces: 18 | cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2) 19 | roi_gray=gray[y:y+h, x:x+w] 20 | roi_color=img[y:y+h, x:x+w] 21 | smiles=smile_cascade.detectMultiScale(roi_gray, 1.05, 5) 22 | for (sx,sy,sw,sh) in smiles: 23 | cv2.rectangle(roi_color, (sx,sy), (sx+sw,sy+sh), (255,255,0), 2) 24 | if cv2.waitKey(1) & 0xff==ord('s'): 25 | cv2.imwrite(f"{str(random.randint(10000))}.png", img) 26 | break 27 | 28 | cv2.imshow('img_smile', img) 29 | 30 | 31 | if cv2.waitKey(2) & 0xff==ord('q'): 32 | break 33 | 34 | 35 | cap.release() 36 | cv2.destroyAllWindows() 37 | -------------------------------------------------------------------------------- /Projects/Audiobook Voice-Over.py: -------------------------------------------------------------------------------- 1 | #Importing the libraries 2 | import cv2 3 | import pytesseract 4 | from PIL import Image 5 | from gtts import gTTS 6 | from playsound import playsound 7 | # Specifying the path 8 | pytesseract.pytesseract.tesseract_cmd = r'C:/Program Files/Tesseract-OCR/tesseract.exe' 9 | 10 | # Reading the image 11 | image = cv2.imread('1.png') 12 | 13 | # Extraction of text from image 14 | text = pytesseract.image_to_string(image) 15 | 16 | # Printing the text 17 | print(text) 18 | # Create the voice_text variable to store the data. 19 | 20 | voice_text = "" 21 | 22 | # Pre-processing the data 23 | 24 | for i in text.split(): 25 | voice_text += i + ' ' 26 | 27 | voice_text = voice_text[:-1] 28 | voice_text 29 | 30 | tts = gTTS(voice_text) 31 | tts.save("test.mp3") 32 | playsound("test.mp3") -------------------------------------------------------------------------------- /Projects/Billing System/Bill.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Billing System/Bill.PNG -------------------------------------------------------------------------------- /Projects/Blackjack game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | logo = """ 4 | .------. _ _ _ _ _ 5 | |A_ _ |. | | | | | | (_) | | 6 | |( \/ ).-----. | |__ | | __ _ ___| | ___ __ _ ___| | __ 7 | | \ /|K /\ | | '_ \| |/ _` |/ __| |/ / |/ _` |/ __| |/ / 8 | | \/ | / \ | | |_) | | (_| | (__| <| | (_| | (__| < 9 | `-----| \ / | |_.__/|_|\__,_|\___|_|\_\ |\__,_|\___|_|\_\\ 10 | | \/ K| _/ | 11 | `------' |__/ 12 | """ 13 | 14 | 15 | def deal_card(): 16 | cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10] 17 | card = random.choice(cards) 18 | return card 19 | 20 | 21 | def calculate_score(cards): 22 | if sum(cards) == 21 and len(cards) == 2: 23 | return 0 24 | 25 | if 11 in cards and sum(cards) > 21: 26 | cards.remove(11) 27 | cards.append(1) 28 | return sum(cards) 29 | 30 | 31 | def compare(user_score, computer_score): 32 | if user_score > 21 and computer_score > 21: 33 | return "You went over. You lose 😤" 34 | 35 | if user_score == computer_score: 36 | return "Draw 🙃" 37 | elif computer_score == 0: 38 | return "Lose, opponent has Blackjack 😱" 39 | elif user_score == 0: 40 | return "Win with a Blackjack 😎" 41 | elif user_score > 21: 42 | return "You went over. You lose 😭" 43 | elif computer_score > 21: 44 | return "Opponent went over. You win 😁" 45 | elif user_score > computer_score: 46 | return "You win 😃" 47 | else: 48 | return "You lose 😤" 49 | 50 | 51 | def play_game(): 52 | 53 | print(logo) 54 | 55 | user_cards = [] 56 | computer_cards = [] 57 | is_game_over = False 58 | 59 | for _ in range(2): 60 | user_cards.append(deal_card()) 61 | computer_cards.append(deal_card()) 62 | 63 | while not is_game_over: 64 | user_score = calculate_score(user_cards) 65 | computer_score = calculate_score(computer_cards) 66 | print(f" Your cards: {user_cards}, current score: {user_score}") 67 | print(f" Computer's first card: {computer_cards[0]}") 68 | 69 | if user_score == 0 or computer_score == 0 or user_score > 21: 70 | is_game_over = True 71 | else: 72 | user_should_deal = input( 73 | "Type 'y' to get another card, type 'n' to pass: ") 74 | if user_should_deal == "y": 75 | user_cards.append(deal_card()) 76 | else: 77 | is_game_over = True 78 | 79 | while computer_score != 0 and computer_score < 17: 80 | computer_cards.append(deal_card()) 81 | computer_score = calculate_score(computer_cards) 82 | 83 | print(f" Your final hand: {user_cards}, final score: {user_score}") 84 | print( 85 | f" Computer's final hand: {computer_cards}, final score: {computer_score}" 86 | ) 87 | print(compare(user_score, computer_score)) 88 | 89 | 90 | while input( 91 | "Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y": 92 | play_game() 93 | -------------------------------------------------------------------------------- /Projects/Chess/game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | from network import Network 3 | 4 | 5 | class Player(): 6 | width = height = 50 7 | 8 | def __init__(self, startx, starty, color=(255,0,0)): 9 | self.x = startx 10 | self.y = starty 11 | self.velocity = 2 12 | self.color = color 13 | 14 | def draw(self, g): 15 | pygame.draw.rect(g, self.color ,(self.x, self.y, self.width, self.height), 0) 16 | 17 | def move(self, dirn): 18 | """ 19 | :param dirn: 0 - 3 (right, left, up, down) 20 | :return: None 21 | """ 22 | 23 | if dirn == 0: 24 | self.x += self.velocity 25 | elif dirn == 1: 26 | self.x -= self.velocity 27 | elif dirn == 2: 28 | self.y -= self.velocity 29 | else: 30 | self.y += self.velocity 31 | 32 | 33 | class Game: 34 | 35 | def __init__(self, w, h): 36 | self.net = Network() 37 | self.width = w 38 | self.height = h 39 | self.player = Player(50, 50) 40 | self.player2 = Player(100,100) 41 | self.canvas = Canvas(self.width, self.height, "Testing...") 42 | 43 | def run(self): 44 | clock = pygame.time.Clock() 45 | run = True 46 | while run: 47 | clock.tick(60) 48 | 49 | for event in pygame.event.get(): 50 | if event.type == pygame.QUIT: 51 | run = False 52 | 53 | if event.type == pygame.K_ESCAPE: 54 | run = False 55 | 56 | keys = pygame.key.get_pressed() 57 | 58 | if keys[pygame.K_RIGHT]: 59 | if self.player.x <= self.width - self.player.velocity: 60 | self.player.move(0) 61 | 62 | if keys[pygame.K_LEFT]: 63 | if self.player.x >= self.player.velocity: 64 | self.player.move(1) 65 | 66 | if keys[pygame.K_UP]: 67 | if self.player.y >= self.player.velocity: 68 | self.player.move(2) 69 | 70 | if keys[pygame.K_DOWN]: 71 | if self.player.y <= self.height - self.player.velocity: 72 | self.player.move(3) 73 | 74 | # Send Network Stuff 75 | self.player2.x, self.player2.y = self.parse_data(self.send_data()) 76 | 77 | # Update Canvas 78 | self.canvas.draw_background() 79 | self.player.draw(self.canvas.get_canvas()) 80 | self.player2.draw(self.canvas.get_canvas()) 81 | self.canvas.update() 82 | 83 | pygame.quit() 84 | 85 | def send_data(self): 86 | """ 87 | Send position to server 88 | :return: None 89 | """ 90 | data = str(self.net.id) + ":" + str(self.player.x) + "," + str(self.player.y) 91 | reply = self.net.send(data) 92 | return reply 93 | 94 | @staticmethod 95 | def parse_data(data): 96 | try: 97 | d = data.split(":")[1].split(",") 98 | return int(d[0]), int(d[1]) 99 | except: 100 | return 0,0 101 | 102 | 103 | class Canvas: 104 | 105 | def __init__(self, w, h, name="None"): 106 | self.width = w 107 | self.height = h 108 | self.screen = pygame.display.set_mode((w,h)) 109 | pygame.display.set_caption(name) 110 | 111 | @staticmethod 112 | def update(): 113 | pygame.display.update() 114 | 115 | def draw_text(self, text, size, x, y): 116 | pygame.font.init() 117 | font = pygame.font.SysFont("comicsans", size) 118 | render = font.render(text, 1, (0,0,0)) 119 | 120 | self.screen.draw(render, (x,y)) 121 | 122 | def get_canvas(self): 123 | return self.screen 124 | 125 | def draw_background(self): 126 | self.screen.fill((255,255,255)) 127 | -------------------------------------------------------------------------------- /Projects/Chess/network.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | 4 | class Network: 5 | 6 | def __init__(self): 7 | self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | self.host = "127.0.0.1" 9 | self.port = 5555 10 | self.addr = (self.host, self.port) 11 | self.id = self.connect() 12 | 13 | def connect(self): 14 | self.client.connect(self.addr) 15 | return self.client.recv(2048).decode() 16 | 17 | def send(self, data): 18 | """ 19 | :param data: str 20 | :return: str 21 | """ 22 | try: 23 | self.client.send(str.encode(data)) 24 | reply = self.client.recv(2048).decode() 25 | return reply 26 | except socket.error as e: 27 | return str(e) 28 | -------------------------------------------------------------------------------- /Projects/Chess/run.py: -------------------------------------------------------------------------------- 1 | import Projects.game as game 2 | 3 | if __name__ == "__main__": 4 | g = game.Game(500,500) 5 | g.run() 6 | -------------------------------------------------------------------------------- /Projects/Chess/server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from _thread import * 3 | import sys 4 | 5 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 6 | 7 | server = 'localhost' 8 | port = 5555 9 | 10 | server_ip = socket.gethostbyname(server) 11 | 12 | try: 13 | s.bind((server, port)) 14 | 15 | except socket.error as e: 16 | print(str(e)) 17 | 18 | s.listen(2) 19 | print("Waiting for a connection") 20 | 21 | currentId = "0" 22 | pos = ["0:50,50", "1:100,100"] 23 | def threaded_client(conn): 24 | global currentId, pos 25 | conn.send(str.encode(currentId)) 26 | currentId = "1" 27 | reply = '' 28 | while True: 29 | try: 30 | data = conn.recv(2048) 31 | reply = data.decode('utf-8') 32 | if not data: 33 | conn.send(str.encode("Goodbye")) 34 | break 35 | else: 36 | print("Recieved: " + reply) 37 | arr = reply.split(":") 38 | id = int(arr[0]) 39 | pos[id] = reply 40 | 41 | if id == 0: nid = 1 42 | if id == 1: nid = 0 43 | 44 | reply = pos[nid][:] 45 | print("Sending: " + reply) 46 | 47 | conn.sendall(str.encode(reply)) 48 | except: 49 | break 50 | 51 | print("Connection Closed") 52 | conn.close() 53 | 54 | while True: 55 | conn, addr = s.accept() 56 | print("Connected to: ", addr) 57 | 58 | start_new_thread(threaded_client, (conn,)) -------------------------------------------------------------------------------- /Projects/DSA Practice Bot on Telegram/constants.py: -------------------------------------------------------------------------------- 1 | API_KEY='1796716216:AAEa1RtednckbK1577c--cJHfPpJQiV411s' -------------------------------------------------------------------------------- /Projects/DSA Practice Bot on Telegram/main.py: -------------------------------------------------------------------------------- 1 | import constants as keys 2 | from telegram.ext import * 3 | import responses as R 4 | 5 | print("Bot started....") 6 | 7 | def start_command(update,context): 8 | update.message.reply_text('Hello! Select a DSA topic to study or practice!') 9 | 10 | 11 | def help_command(update,context): 12 | update.message.reply_text('If you want to know about something, type in the topic. Otherwise feel free to have a chat :)') 13 | 14 | def handle_message(update,context): 15 | text=str(update.message.text).lower() 16 | response=R.sampleresponses(text) 17 | update.message.reply_text(response) 18 | 19 | def error(update,context): 20 | print(f"Update {update} caused error {context.error}") 21 | 22 | def main(): 23 | updater=Updater(keys.API_KEY, use_context=True) 24 | dp=updater.dispatcher 25 | dp.add_handler(CommandHandler("start", start_command)) 26 | dp.add_handler(CommandHandler("help", help_command)) 27 | dp.add_handler(MessageHandler(Filters.text, handle_message)) 28 | dp.add_error_handler(error) 29 | 30 | updater.start_polling() 31 | updater.idle() 32 | 33 | main() 34 | 35 | 36 | -------------------------------------------------------------------------------- /Projects/DSA Practice Bot on Telegram/responses.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | import urllib 3 | 4 | def sampleresponses(input_text): 5 | user_message=str(input_text).lower() 6 | #about="tell me something about" 7 | #length=len(about) 8 | message1="Resource to study" 9 | message2="Resource to Practice" 10 | webUrl='' 11 | webUrl2='' 12 | flag_var=-1 13 | if user_message in ("hello","hi","sup"): 14 | return "Hey! How's it going?" 15 | if user_message in ("who are you", "who are you?", "whats your name", "what is your name?","What's your name","What's your name?"): 16 | return "My name is Data Structures and Algorithms Practice Bot" 17 | if user_message in ("time","time?","what's the time","what is the time?"): 18 | now=datetime.now() 19 | date_time=now.strftime("%d/%m/%y, %H:%M:%S") 20 | return str(date_time) 21 | if user_message in("dynamic programming","dp"): 22 | webUrl='https://www.youtube.com/watch?v=oBt53YbR9Kk' 23 | webUrl2='https://www.hackerearth.com/practice/algorithms/dynamic-programming/introduction-to-dynamic-programming-1/practice-problems/' 24 | flag_var=1 25 | if user_message in ('greedy algorithms','greedy'): 26 | webUrl='https://www.youtube.com/playlist?list=PLqM7alHXFySESatj68JKWHRVhoJ1BxtLW' 27 | webUrl2='https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/' 28 | flag_var=1 29 | if 'array' in user_message: 30 | webUrl='https://www.youtube.com/playlist?list=PLBlnK6fEyqRjoG6aJ4FvFU1tlXbjLBiOP' 31 | webUrl2='https://leetcode.com/tag/array/' 32 | flag_var=1 33 | if 'linked list' in user_message: 34 | webUrl='https://www.geeksforgeeks.org/data-structures/linked-list/' 35 | webUrl2='https://leetcode.com/tag/linked-list/' 36 | flag_var=1 37 | if 'sort' in user_message: 38 | webUrl='https://www.youtube.com/playlist?list=PL2_aWCzGMAwKedT2KfDMB9YA5DgASZb3U' 39 | webUrl2='https://leetcode.com/tag/sort/' 40 | flag_var=1 41 | if 'search' in user_message: 42 | webUrl='https://www.youtube.com/watch?v=13ocRMSJy5M' 43 | webUrl2='https://leetcode.com/tag/binary-search/' 44 | flag_var=1 45 | if 'number theory' in user_message: 46 | webUrl='https://www.youtube.com/watch?v=19SW3P_PRHQ' 47 | webUrl2='https://codeforces.com/blog/entry/49494' 48 | flag_var=1 49 | if 'bitmasking' in user_message: 50 | webUrl='https://www.youtube.com/watch?v=wEZfc6cPC4w' 51 | webUrl2='https://leetcode.com/tag/bit-manipulation/' 52 | flag_var=1 53 | if 'backtracking' in user_message or 'recursion' in user_message: 54 | webUrl='https://www.youtube.com/playlist?list=PL-Jc9J83PIiFxaBahjslhBD1LiJAV7nKs' 55 | webUrl2='https://leetcode.com/tag/backtracking/' 56 | flag_var=1 57 | if 'stack' in user_message: 58 | webUrl='https://www.youtube.com/playlist?list=PL_z_8CaSLPWdeOezg68SKkeLN4-T_jNHd' 59 | webUrl2='https://leetcode.com/tag/stack/' 60 | flag_var=1 61 | if 'queue' in user_message: 62 | webUrl='https://www.youtube.com/watch?v=zp6pBNbUB2U' 63 | webUrl2='https://leetcode.com/tag/queue/' 64 | flag_var=1 65 | if 'tree' in user_message: 66 | webUrl='https://www.youtube.com/watch?v=I_JuQ5ayPmc' 67 | webUrl2='https://leetcode.com/tag/tree/' 68 | flag_var=1 69 | if 'heap' in user_message: 70 | webUrl='https://www.youtube.com/playlist?list=PL_z_8CaSLPWdtY9W22VjnPxG30CXNZpI9' 71 | webUrl2='https://leetcode.com/tag/heap/' 72 | flag_var=1 73 | if 'hash' in user_message: 74 | webUrl='https://www.youtube.com/playlist?list=PLqM7alHXFySGwXaessYMemAnITqlZdZVE' 75 | webUrl2='https://leetcode.com/tag/hash-table/' 76 | flag_var=1 77 | if 'trie' in user_message: 78 | webUrl='https://www.youtube.com/watch?v=AXjmTQ8LEoI' 79 | webUrl2='https://leetcode.com/tag/trie/' 80 | flag_var=1 81 | if 'graph' in user_message: 82 | webUrl='https://www.youtube.com/playlist?list=PLl4Y2XuUavmtTOvFcW3HfI1oQ3hsgkB3a' 83 | webUrl2='https://leetcode.com/tag/graph/' 84 | flag_var=1 85 | if 'string' in user_message: 86 | webUrl='https://www.youtube.com/playlist?list=PLqjW-ORyj-hLKFq_ESmFpXDnaLKaTCMio' 87 | webUrl2='https://leetcode.com/tag/string/' 88 | flag_var=1 89 | if flag_var==1: 90 | return message1+'\n'+webUrl+'\n'+message2+'\n'+webUrl2 91 | else: 92 | return "I do not understand you" -------------------------------------------------------------------------------- /Projects/Face Recognition: -------------------------------------------------------------------------------- 1 | import cv2 2 | import dlib 3 | 4 | cap = cv2.VideoCapture(0) 5 | detector = dlib.get_frontal_face_detector() 6 | 7 | while True: 8 | ret, frame = cap.read() 9 | frame = cv2.flip(frame,1) 10 | gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 11 | faces = detector(gray) 12 | 13 | i=0 14 | 15 | for face in faces: 16 | x, y = face.left(), face.top() 17 | x1, y1 = face.right(), face.bottom() 18 | cv2.rectangle(frame,(x,y),(x1,y1),(0,255,0),2) 19 | i=i+1 20 | cv2.putText(frame,'face num'+str(i),(x-10,y-10),cv2.FONT_HERSHEY_SIMPLEX,0.7,(0,0,255),2) 21 | print(face,i) 22 | cv2.imshow('frame',frame) 23 | if cv2.waitKey(1) & 0xFF == ord('q'): 24 | break 25 | cap.release() 26 | cv2.destroyAllWindows() 27 | -------------------------------------------------------------------------------- /Projects/Face_Recognisation.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | 4 | face_Reg = cv2.CascadeClassifier('haarcascade_frontalface_default') 5 | cap = cv2.VideoCapture(0) 6 | cap.set(3, 640) # set Width 7 | cap.set(4, 480) # set Height 8 | while True: 9 | ret, vid = cap.read() 10 | faces = face_Reg.detectMultiScale(vid, 11 | scaleFactor=1.2, 12 | minNeighbors=5, 13 | minSize=(20, 20), 14 | flags=cv2.cv.CV_HAAR_SCALE_IMAGE) 15 | for (x, y, w, h) in faces: 16 | cv2.rectangle(vid, (x, y), (x + w, y + h), (0, 255, 0), 2) 17 | cv2.imshow('frame', vid) 18 | k = cv2.waitKey(30) & 0xff 19 | if k == 27: # press 'ESC' to quit 20 | break 21 | cap.release() 22 | cv2.destroyAllWindows() 23 | -------------------------------------------------------------------------------- /Projects/Hangman/hangman.py: -------------------------------------------------------------------------------- 1 | # We will be playing HANGMAN game here..... 2 | 3 | import random 4 | import hangman_art 5 | from hangman_words import word_list 6 | import os 7 | 8 | chosen_word = random.choice(word_list) 9 | game_continue = True 10 | misses = [] 11 | chances = 6 12 | s2 = [] 13 | for i in range(len(chosen_word)): 14 | s2.append("_") 15 | 16 | print(hangman_art.logo) 17 | print(" ".join(s2)) 18 | 19 | while(game_continue): 20 | i=0 21 | guess_input = input("\nGuess: ").lower() 22 | guess = False 23 | 24 | os.system('clear') 25 | 26 | if guess_input in s2 or guess_input in misses: 27 | print(f"You have already guessed '{guess_input}'\n") 28 | 29 | else: 30 | for i in range(0,len(chosen_word)): 31 | if guess_input == chosen_word[i]: 32 | guess = True 33 | s2[i] = chosen_word[i] 34 | 35 | if guess == False: #what happens when wrong choice is made 36 | print("You made a wrong guess.\n") 37 | chances -= 1 38 | misses.append(f"{guess_input}") 39 | else: 40 | print("Right guess.\n") 41 | 42 | print(f'{" ".join(s2)}') #print the current updated string 43 | print("\nMisses: "+" ".join(misses)) 44 | print(hangman_art.stages[chances]) 45 | 46 | any_left = False 47 | 48 | if "_" in s2: 49 | any_left = True 50 | 51 | if any_left == False: 52 | print(hangman_art.you_won) 53 | game_continue = False 54 | 55 | if chances == 0: 56 | game_continue = False 57 | if any_left: 58 | print(hangman_art.game_over) 59 | print(f"Right answer was '{chosen_word}'") 60 | 61 | -------------------------------------------------------------------------------- /Projects/Hangman/hangman_art.py: -------------------------------------------------------------------------------- 1 | stages = [''' 2 | +---+ 3 | | | 4 | O | 5 | /|\ | 6 | / \ | 7 | | 8 | ========= 9 | ''', ''' 10 | +---+ 11 | | | 12 | O | 13 | /|\ | 14 | / | 15 | | 16 | ========= 17 | ''', ''' 18 | +---+ 19 | | | 20 | O | 21 | /|\ | 22 | | 23 | | 24 | ========= 25 | ''', ''' 26 | +---+ 27 | | | 28 | O | 29 | /| | 30 | | 31 | | 32 | =========''', ''' 33 | +---+ 34 | | | 35 | O | 36 | | | 37 | | 38 | | 39 | ========= 40 | ''', ''' 41 | +---+ 42 | | | 43 | O | 44 | | 45 | | 46 | | 47 | ========= 48 | ''', ''' 49 | +---+ 50 | | | 51 | | 52 | | 53 | | 54 | | 55 | ========= 56 | '''] 57 | 58 | logo = ''' 59 | _ 60 | | | 61 | | |__ __ _ _ __ __ _ _ __ ___ __ _ _ __ 62 | | '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ 63 | | | | | (_| | | | | (_| | | | | | | (_| | | | | 64 | |_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_| 65 | __/ | 66 | |___/ 67 | ''' 68 | 69 | game_over = ''' 70 | ._._. ________ ________ ._._. 71 | | | |/ _____/_____ _____ ____ \_____ \___ __ ___________ | | | 72 | | | / \ ___\__ \ / \_/ __ \ / | \ \/ // __ \_ __ \ | | | 73 | \|\\\ \_\ \/ __ \| Y Y \ ___/ / | \ /\ ___/| | \/ \|\| 74 | ____\______ (____ /__|_| /\___ > \_______ /\_/ \___ >__| ____ 75 | \/\/ \/ \/ \/ \/ \/ \/ \/\/ 76 | 77 | ''' 78 | 79 | you_won = ''' 80 | ._._._____.___. __ __ ._._. 81 | | | |\__ | | ____ __ __ / \ / \____ ____ | | | 82 | | | | / | |/ _ \| | \ \ \/\/ / _ \ / \ | | | 83 | \|\| \____ ( <_> ) | / \ ( <_> ) | \ \|\| 84 | ____ / ______|\____/|____/ \__/\ / \____/|___| / ____ 85 | \/\/ \/ \/ \/ \/\/ 86 | 87 | ''' -------------------------------------------------------------------------------- /Projects/Hangman/hangman_words.py: -------------------------------------------------------------------------------- 1 | word_list = [ 2 | 'abruptly', 3 | 'absurd', 4 | 'abyss', 5 | 'affix', 6 | 'askew', 7 | 'avenue', 8 | 'awkward', 9 | 'axiom', 10 | 'azure', 11 | 'bagpipes', 12 | 'bandwagon', 13 | 'banjo', 14 | 'bayou', 15 | 'beekeeper', 16 | 'bikini', 17 | 'blitz', 18 | 'blizzard', 19 | 'boggle', 20 | 'bookworm', 21 | 'boxcar', 22 | 'boxful', 23 | 'buckaroo', 24 | 'buffalo', 25 | 'buffoon', 26 | 'buxom', 27 | 'buzzard', 28 | 'buzzing', 29 | 'buzzwords', 30 | 'caliph', 31 | 'cobweb', 32 | 'cockiness', 33 | 'croquet', 34 | 'crypt', 35 | 'curacao', 36 | 'cycle', 37 | 'daiquiri', 38 | 'dirndl', 39 | 'disavow', 40 | 'dizzying', 41 | 'duplex', 42 | 'dwarves', 43 | 'embezzle', 44 | 'equip', 45 | 'espionage', 46 | 'euouae', 47 | 'exodus', 48 | 'faking', 49 | 'fishhook', 50 | 'fixable', 51 | 'fjord', 52 | 'flapjack', 53 | 'flopping', 54 | 'fluffiness', 55 | 'flyby', 56 | 'foxglove', 57 | 'frazzled', 58 | 'frizzled', 59 | 'fuchsia', 60 | 'funny', 61 | 'gabby', 62 | 'galaxy', 63 | 'galvanize', 64 | 'gazebo', 65 | 'giaour', 66 | 'gizmo', 67 | 'glowworm', 68 | 'glyph', 69 | 'gnarly', 70 | 'gnostic', 71 | 'gossip', 72 | 'grogginess', 73 | 'haiku', 74 | 'haphazard', 75 | 'hyphen', 76 | 'iatrogenic', 77 | 'icebox', 78 | 'injury', 79 | 'ivory', 80 | 'ivy', 81 | 'jackpot', 82 | 'jaundice', 83 | 'jawbreaker', 84 | 'jaywalk', 85 | 'jazziest', 86 | 'jazzy', 87 | 'jelly', 88 | 'jigsaw', 89 | 'jinx', 90 | 'jiujitsu', 91 | 'jockey', 92 | 'jogging', 93 | 'joking', 94 | 'jovial', 95 | 'joyful', 96 | 'juicy', 97 | 'jukebox', 98 | 'jumbo', 99 | 'kayak', 100 | 'kazoo', 101 | 'keyhole', 102 | 'khaki', 103 | 'kilobyte', 104 | 'kiosk', 105 | 'kitsch', 106 | 'kiwifruit', 107 | 'klutz', 108 | 'knapsack', 109 | 'larynx', 110 | 'lengths', 111 | 'lucky', 112 | 'luxury', 113 | 'lymph', 114 | 'marquis', 115 | 'matrix', 116 | 'megahertz', 117 | 'microwave', 118 | 'mnemonic', 119 | 'mystify', 120 | 'naphtha', 121 | 'nightclub', 122 | 'nowadays', 123 | 'numbskull', 124 | 'nymph', 125 | 'onyx', 126 | 'ovary', 127 | 'oxidize', 128 | 'oxygen', 129 | 'pajama', 130 | 'peekaboo', 131 | 'phlegm', 132 | 'pixel', 133 | 'pizazz', 134 | 'pneumonia', 135 | 'polka', 136 | 'pshaw', 137 | 'psyche', 138 | 'puppy', 139 | 'puzzling', 140 | 'quartz', 141 | 'queue', 142 | 'quips', 143 | 'quixotic', 144 | 'quiz', 145 | 'quizzes', 146 | 'quorum', 147 | 'razzmatazz', 148 | 'rhubarb', 149 | 'rhythm', 150 | 'rickshaw', 151 | 'schnapps', 152 | 'scratch', 153 | 'shiv', 154 | 'snazzy', 155 | 'sphinx', 156 | 'spritz', 157 | 'squawk', 158 | 'staff', 159 | 'strength', 160 | 'strengths', 161 | 'stretch', 162 | 'stronghold', 163 | 'stymied', 164 | 'subway', 165 | 'swivel', 166 | 'syndrome', 167 | 'thriftless', 168 | 'thumbscrew', 169 | 'topaz', 170 | 'transcript', 171 | 'transgress', 172 | 'transplant', 173 | 'triphthong', 174 | 'twelfth', 175 | 'twelfths', 176 | 'unknown', 177 | 'unworthy', 178 | 'unzip', 179 | 'uptown', 180 | 'vaporize', 181 | 'vixen', 182 | 'vodka', 183 | 'voodoo', 184 | 'vortex', 185 | 'voyeurism', 186 | 'walkway', 187 | 'waltz', 188 | 'wave', 189 | 'wavy', 190 | 'waxy', 191 | 'wellspring', 192 | 'wheezy', 193 | 'whiskey', 194 | 'whizzing', 195 | 'whomever', 196 | 'wimpy', 197 | 'witchcraft', 198 | 'wizard', 199 | 'woozy', 200 | 'wristwatch', 201 | 'wyvern', 202 | 'xylophone', 203 | 'yachtsman', 204 | 'yippee', 205 | 'yoked', 206 | 'youthful', 207 | 'yummy', 208 | 'zephyr', 209 | 'zigzag', 210 | 'zigzagging', 211 | 'zilch', 212 | 'zipper', 213 | 'zodiac', 214 | 'zombie', 215 | ] -------------------------------------------------------------------------------- /Projects/ImageCompression.py: -------------------------------------------------------------------------------- 1 | # pip install Pillow 2 | 3 | import os 4 | import sys 5 | from PIL import Image 6 | 7 | def compressImage(file): 8 | 9 | filepath = os.path.join(os.getcwd(), file) 10 | 11 | picture = Image.open(filepath) 12 | 13 | picture.save("Compressed_"+file, 14 | "JPEG", 15 | optimize = True, 16 | quality = 10) 17 | return 18 | 19 | if __name__ == "__main__": 20 | 21 | cwd = os.getcwd() 22 | 23 | formats = ('.jpg', '.jpeg') 24 | 25 | for file in os.listdir(cwd): 26 | if os.path.splitext(file)[1].lower() in formats: 27 | print('compressing', file) 28 | compressImage(file) 29 | 30 | print("Done") 31 | 32 | -------------------------------------------------------------------------------- /Projects/Job_Scraping.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import pandas as pd 3 | from bs4 import BeautifulSoup 4 | from tkinter import * 5 | from tkinter import messagebox 6 | 7 | res = [] 8 | 9 | 10 | def getdata(url): 11 | r = requests.get(url) 12 | return r.text 13 | 14 | 15 | def getinfo(): 16 | result = '' 17 | htmldata = getdata("https://www.sarkariresult.com/latestjob.php") 18 | soup = BeautifulSoup(htmldata, 'html.parser') 19 | 20 | for li in soup.find_all("div", id="post"): 21 | result += (li.get_text()) 22 | res.set(result) 23 | 24 | 25 | # object of tkinter 26 | # and background set for light grey 27 | master = Tk() 28 | master.configure(bg='light grey') 29 | 30 | # Variable Classes in tkinter 31 | res = StringVar() 32 | 33 | # Creating label for each information 34 | # name using widget Label 35 | Label(master, text="List of the Jobs :", bg="light grey", 36 | font="100").grid(row=0, sticky=W) 37 | 38 | # Creating lebel for class variable 39 | # name using widget Entry 40 | Label(master, text="", textvariable=res, bg="light grey").grid(row=3, 41 | column=1, 42 | sticky=W) 43 | 44 | # creating a button using the widget 45 | # Button that will call the submit function 46 | b = Button(master, text="Get latest job", command=getinfo) 47 | b.grid(row=0, column=2, columnspan=2, rowspan=2, padx=5, pady=5) 48 | 49 | mainloop() 50 | -------------------------------------------------------------------------------- /Projects/Language Translator/images/trans.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Language Translator/images/trans.png -------------------------------------------------------------------------------- /Projects/Language Translator/readme.md: -------------------------------------------------------------------------------- 1 | # Language Translator 2 | ![made-with-python](https://img.shields.io/badge/Made%20with-Python-blue.svg) 3 | ![streamlit](https://img.shields.io/badge/Streamlit-FF4B4B?&logo=streamlit&logoColor=white) 4 | ![terminal](https://img.shields.io/badge/Windows%20Terminal-4D4D4D?&logo=Windows%20terminal&logoColor=white) 5 | ![vscode](https://img.shields.io/badge/Visual_Studio_Code-0078D4?&logo=visual%20studio%20code&logoColor=white) 6 | 7 | Language Translator is used to detect and translate between languages created using gTTS (google text to speech), googletrans, and streamlit python packages. 8 | 9 | ## Installation 10 | Open command prompt and create new environment 11 | ``` 12 | conda create -n your_env_name python = (any_version_number) 13 | ``` 14 | Then Activate the newly created environment 15 | ``` 16 | conda activate your_env_name 17 | ``` 18 | Clone the repository using `git` 19 | ``` 20 | git clone https://github.com/PrajaktaSathe/Python.git 21 | ``` 22 | Change to the cloned directory 23 | ``` 24 | cd "Python\Projects\Language Translator" 25 | ``` 26 | Then install all requirement packages for the app 27 | ``` 28 | pip install -r requirements.txt 29 | ``` 30 | Then, Run the `translator.py` script 31 | ``` 32 | streamlit run translator.py 33 | ``` 34 | ## 📷 Screenshots 35 | ![output_image](images/trans.png) 36 | -------------------------------------------------------------------------------- /Projects/Language Translator/requirements.txt: -------------------------------------------------------------------------------- 1 | streamlit==1.10.0 2 | googletrans==3.1.0a0 3 | gTTS==2.2.3 4 | -------------------------------------------------------------------------------- /Projects/Language Translator/translator.py: -------------------------------------------------------------------------------- 1 | import streamlit as st # building web apps in python 2 | from PIL import Image # for opening image files 3 | from datetime import date # provides date & time functions 4 | from gtts import gTTS, lang # for text speech 5 | from googletrans import Translator # provides translation functions 6 | 7 | # setting app's title, icon & layout 8 | st.set_page_config(page_title="Simply! Translate", page_icon="🎯") 9 | 10 | 11 | def get_key(val): 12 | """function to find the key of the given value in the dict object 13 | 14 | Args: 15 | val (str): value to find key 16 | 17 | Returns: 18 | key(str): key for the given value 19 | """ 20 | for key, value in lang.tts_langs().items(): 21 | if val == value: 22 | return key 23 | 24 | 25 | def main(): 26 | # instance of Translator() 27 | trans = Translator() 28 | 29 | # gets gtts supported languages as dict 30 | langs = lang.tts_langs() 31 | 32 | # display current date & header 33 | st.header("Translate your thoughts.") 34 | st.write(f"Date : {date.today()}") 35 | 36 | input_text = st.text_input("Enter whatever") # gets text to translate 37 | lang_choice = st.selectbox( 38 | "Language to translate: ", list(langs.values()) 39 | ) # shows the supported languages list as selectbox options 40 | 41 | if st.button("Translate"): 42 | if input_text == "": 43 | # if the user input is empty 44 | st.write("Please Enter text to translate") 45 | 46 | else: 47 | detect_expander = st.expander("Detected Language") 48 | with detect_expander: 49 | detect = trans.detect([input_text])[ 50 | 0 51 | ] # detect the user given text language 52 | detect_text = f"Detected Language : {langs[detect.lang]}" 53 | st.success(detect_text) # displays the detected language 54 | 55 | # convert the detected text to audio file 56 | detect_audio = gTTS(text=input_text, lang=detect.lang, slow=False) 57 | detect_audio.save("user_detect.mp3") 58 | audio_file = open("user_detect.mp3", "rb") 59 | audio_bytes = audio_file.read() 60 | st.audio(audio_bytes, format="audio/ogg", start_time=0) 61 | 62 | trans_expander = st.expander("Translated Text") 63 | with trans_expander: 64 | translation = trans.translate( 65 | input_text, dest=get_key(lang_choice) 66 | ) # translates user given text to target language 67 | translation_text = f"Translated Text : {translation.text}" 68 | st.success(translation_text) # displays the translated text 69 | 70 | # convert the translated text to audio file 71 | translated_audio = gTTS( 72 | text=translation.text, lang=get_key(lang_choice), slow=False 73 | ) 74 | translated_audio.save("user_trans.mp3") 75 | audio_file = open("user_trans.mp3", "rb") 76 | audio_bytes = audio_file.read() 77 | st.audio(audio_bytes, format="audio/ogg", start_time=0) 78 | 79 | # download button to download translated audio file 80 | with open("user_trans.mp3", "rb") as file: 81 | st.download_button( 82 | label="Download", 83 | data=file, 84 | file_name="trans.mp3", 85 | mime="audio/ogg", 86 | ) 87 | 88 | 89 | if __name__ == "__main__": 90 | main() # calls the main() first 91 | -------------------------------------------------------------------------------- /Projects/Music Player/music-player.py: -------------------------------------------------------------------------------- 1 | # Importing Required Modules & libraries 2 | from tkinter import * 3 | import pygame 4 | import os 5 | 6 | 7 | # Defining MusicPlayer Class 8 | 9 | 10 | class MusicPlayer: 11 | # Defining Constructor 12 | def __init__(self, root): 13 | self.root = root 14 | # Title of the window 15 | self.root.title("Music Player") 16 | # Window Geometry 17 | self.root.geometry("2000x300+300+300") 18 | # Initiating Pygame 19 | pygame.init() 20 | # Initiating Pygame Mixer 21 | pygame.mixer.init() 22 | # Declaring track Variable 23 | self.track = StringVar() 24 | # Declaring Status Variable 25 | self.status = StringVar() 26 | 27 | # Creating Track Frame for Song label & status label 28 | trackframe = LabelFrame(self.root, text="Song Track", font=("times new roman", 15, "bold"), bg="grey", 29 | fg="white", bd=5, relief=GROOVE) 30 | trackframe.place(x=0, y=0, width=600, height=100) 31 | # Inserting Song Track Label 32 | songtrack = Label(trackframe, textvariable=self.track, width=20, font=("times new roman", 24, "bold"), 33 | bg="grey", fg="gold").grid(row=0, column=0, padx=10, pady=5) 34 | # Inserting Status Label 35 | trackstatus = Label(trackframe, textvariable=self.status, font=("times new roman", 24, "bold"), bg="grey", 36 | fg="gold").grid(row=0, column=1, padx=10, pady=5) 37 | 38 | # Creating Button Frame 39 | buttonframe = LabelFrame(self.root, text="Control Panel", font=("times new roman", 15, "bold"), bg="grey", 40 | fg="white", bd=5, relief=GROOVE) 41 | buttonframe.place(x=0, y=100, width=600, height=100) 42 | # Inserting Play Button 43 | playbtn = Button(buttonframe, text="PLAY", command=self.playsong, width=6, height=1, 44 | font=("times new roman", 17, "bold"), fg="navyblue", bg="gold").grid(row=0, column=0, padx=10, 45 | pady=5) 46 | # Inserting Pause Button 47 | playbtn = Button(buttonframe, text="PAUSE", command=self.pausesong, width=8, height=1, 48 | font=("times new roman", 17, "bold"), fg="navyblue", bg="gold").grid(row=0, column=1, padx=10, 49 | pady=5) 50 | # Inserting Unpause Button 51 | playbtn = Button(buttonframe, text="UNPAUSE", command=self.unpausesong, width=10, height=1, 52 | font=("times new roman", 17, "bold"), fg="navyblue", bg="gold").grid(row=0, column=2, padx=10, 53 | pady=5) 54 | # Inserting Stop Button 55 | playbtn = Button(buttonframe, text="STOP", command=self.stopsong, width=6, height=1, 56 | font=("times new roman", 17, "bold"), fg="navyblue", bg="gold").grid(row=0, column=3, padx=10, 57 | pady=5) 58 | 59 | # Creating Playlist Frame 60 | songsframe = LabelFrame(self.root, text="Songs Playlist", font=("times new roman", 16, "bold"), bg="grey", 61 | fg="white", bd=5, relief=GROOVE) 62 | songsframe.place(x=600, y=0, width=400, height=200) 63 | # Inserting scrollbar 64 | scrol_y = Scrollbar(songsframe, orient=VERTICAL) 65 | # Inserting Playlist listbox 66 | self.playlist = Listbox(songsframe, yscrollcommand=scrol_y.set, selectbackground="gold", selectmode=SINGLE, 67 | font=("times new roman", 12, "bold"), bg="black", fg="navyblue", bd=5, relief=GROOVE) 68 | # Applying Scrollbar to listbox 69 | scrol_y.pack(side=RIGHT, fill=Y) 70 | scrol_y.config(command=self.playlist.yview) 71 | self.playlist.pack(fill=BOTH) 72 | # Changing Directory for fetching Songs 73 | os.chdir("songs") 74 | # Fetching Songs 75 | songtracks = os.listdir() 76 | # Inserting Songs into Playlist 77 | for track in songtracks: 78 | self.playlist.insert(END, track) 79 | 80 | # Defining Play Song Function 81 | def playsong(self): 82 | # Displaying Selected Song title 83 | self.track.set(self.playlist.get(ACTIVE)) 84 | # Displaying Status 85 | self.status.set("-Playing") 86 | # Loading Selected Song 87 | pygame.mixer.music.load(self.playlist.get(ACTIVE)) 88 | # Playing Selected Song 89 | pygame.mixer.music.play() 90 | 91 | def stopsong(self): 92 | # Displaying Status 93 | self.status.set("-Stopped") 94 | # Stopped Song 95 | pygame.mixer.music.stop() 96 | 97 | def pausesong(self): 98 | # Displaying Status 99 | self.status.set("-Paused") 100 | # Paused Song 101 | pygame.mixer.music.pause() 102 | 103 | def unpausesong(self): 104 | # Displaying Status 105 | self.status.set("-Playing") 106 | # Playing back Song 107 | pygame.mixer.music.unpause() 108 | 109 | 110 | # Creating TK Container 111 | root = Tk() 112 | # Passing Root to MusicPlayer Class 113 | MusicPlayer(root) 114 | # Root Window Looping 115 | root.mainloop() 116 | -------------------------------------------------------------------------------- /Projects/Music Player/music_player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Music Player/music_player.png -------------------------------------------------------------------------------- /Projects/Music Player/songs/Dhadak (Title Track).mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Music Player/songs/Dhadak (Title Track).mp3 -------------------------------------------------------------------------------- /Projects/Music Player/songs/O Saathi.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Music Player/songs/O Saathi.mp3 -------------------------------------------------------------------------------- /Projects/Pong: -------------------------------------------------------------------------------- 1 | import turtle as Turtle 2 | 3 | 4 | Player1_Score = 0 5 | Player2_Score = 0 6 | 7 | 8 | window = Turtle.Screen() 9 | window.title("Ponggo Game!") 10 | window.bgcolor("green") 11 | window.setup(width=800,height=600) 12 | window.tracer(0) 13 | 14 | 15 | 16 | #creating left paddle 17 | leftblock=Turtle.Turtle() 18 | leftblock.speed(0) 19 | leftblock.shape("square") 20 | leftblock.color("white") 21 | leftblock.shapesize(stretch_wid=5,stretch_len=1) 22 | leftblock.penup() 23 | leftblock.goto(-350,0) 24 | 25 | #creating right paddle 26 | rightblock=Turtle.Turtle() 27 | rightblock.speed(0) 28 | rightblock.shape("square") 29 | rightblock.color("white") 30 | rightblock.shapesize(stretch_wid=5,stretch_len=1) 31 | rightblock.penup() 32 | rightblock.goto(+350,0) 33 | 34 | #creating the ball 35 | 36 | ball = Turtle.Turtle() 37 | ball.speed(0) 38 | ball.shape("circle") 39 | ball.color("red") 40 | ball.penup() 41 | ball.goto(5,5) 42 | ballxdirection=0.2 43 | ballydirection=0.2 44 | 45 | #creating pen for score 46 | 47 | pen =Turtle.Turtle() 48 | pen.speed(0) 49 | pen.color("white") 50 | pen.penup() 51 | pen.hideturtle() 52 | pen.goto(0,260) 53 | pen.write("score",align="center",font=('Arial',24,'normal')) 54 | 55 | #moving leftblock 56 | 57 | def leftblockup(): 58 | y = leftblock.ycor() 59 | y = y +90 60 | leftblock.sety(y) 61 | if y == 360: 62 | y = y -90 63 | leftblock.sety(y) 64 | 65 | def leftblockdown(): 66 | y = leftblock.ycor() 67 | y = y - 90 68 | leftblock.sety(y) 69 | if y == -360: 70 | y = y+90 71 | leftblock.sety(y) 72 | 73 | 74 | 75 | #moving rightblock 76 | 77 | def rightblockup(): 78 | y = rightblock.ycor() 79 | y = y +90 80 | rightblock.sety(y) 81 | if y == 360: 82 | y = y -90 83 | rightblock.sety(y) 84 | 85 | def rightblockdown(): 86 | y = rightblock.ycor() 87 | y = y - 90 88 | rightblock.sety(y) 89 | if y == -360: 90 | y = y+90 91 | rightblock.sety(y) 92 | 93 | def Victorypage_player1(): 94 | Turtle.textinput("Congratulations !", "Player 1 You Won! Did you Enjoy the game?") 95 | Turtle.resetscreen 96 | 97 | def Victorypage_player2(): 98 | Turtle.textinput("Congratulations !", "Player 2 You Won! Did you Enjoy the game?") 99 | Turtle.resetscreen 100 | 101 | #assigns keys to play 102 | 103 | window.listen() 104 | window.onkeypress(leftblockup,'w') 105 | window.onkeypress(leftblockdown,'s') 106 | window.onkeypress(rightblockup,'Up') 107 | window.onkeypress(rightblockdown,'Down') 108 | 109 | while True: 110 | window.update() 111 | 112 | #moving motion 113 | ball.setx(ball.xcor()+ballxdirection) 114 | ball.sety(ball.ycor()+ballydirection) 115 | 116 | #settingup border 117 | if ball.ycor()>290: 118 | ball.sety(290) 119 | ballydirection=ballydirection*-1 120 | if ball.ycor()<-290: 121 | ball.sety(-290) 122 | ballydirection=ballydirection*-1 123 | 124 | #if the ball passes the block (>390 or <-390) 125 | if ball.xcor()>390: 126 | ball.goto(0,0) 127 | ballxdirection=ballxdirection 128 | Player1_Score+=1 129 | pen.clear() 130 | pen.write("Player 1: {} Player2: {}".format(Player1_Score,Player2_Score),align='center',font=('Arial',24,'normal')) 131 | 132 | if ball.xcor()<-390: 133 | ball.goto(0,0) 134 | ballxdirection=ballxdirection 135 | Player2_Score+=1 136 | pen.clear() 137 | pen.write("Player 1: {} Player2: {}".format(Player1_Score,Player2_Score),align='center',font=('Arial',24,'normal')) 138 | 139 | #Handling Collisions 140 | 141 | if (ball.xcor()>340)and(ball.xcor()<350)and(ball.ycor()rightblock.ycor()-40): 142 | ball.setx(340) 143 | ballxdirection=ballxdirection*-1 144 | 145 | if (ball.xcor()<-340)and(ball.xcor()>-350)and(ball.ycor()leftblock.ycor()-40): 146 | ball.setx(-340) 147 | ballxdirection=ballxdirection*-1 148 | 149 | if Player1_Score == 10: 150 | Victorypage_player1() 151 | break 152 | 153 | if Player2_Score == 10: 154 | Victorypage_player2() 155 | break 156 | -------------------------------------------------------------------------------- /Projects/Pong.py: -------------------------------------------------------------------------------- 1 | import turtle 2 | 3 | wn = turtle.Screen() 4 | wn.title("Pong by Shivam") 5 | wn.bgcolor("black") 6 | wn.setup(width=800, height=500) 7 | wn.tracer(0) 8 | 9 | # Score 10 | score_a = 0 11 | score_b = 0 12 | 13 | # Paddle A 14 | paddle_a = turtle.Turtle() # This makes an object in paddle_a. 15 | paddle_a.speed(0) 16 | paddle_a.shape("square") 17 | paddle_a.shapesize(stretch_wid=6, stretch_len=1) 18 | paddle_a.color("blue") 19 | paddle_a.penup() 20 | paddle_a.goto(-350, 0) 21 | 22 | # Paddle B 23 | paddle_b = turtle.Turtle() 24 | paddle_b.speed(0) 25 | paddle_b.shape("square") 26 | paddle_b.shapesize(stretch_wid=6, stretch_len=1) 27 | paddle_b.color("red") 28 | paddle_b.penup() 29 | paddle_b.goto(350, 0) 30 | 31 | # Ball 32 | ball = turtle.Turtle() 33 | ball.speed(0) 34 | ball.shape("circle") 35 | ball.color("yellow") 36 | ball.penup() 37 | ball.goto(0, 0) 38 | ball.dx = 0.34 # dx means delta/change X-cordinate. 39 | ball.dy = 0.34 40 | 41 | # Pen 42 | pen = turtle.Turtle() 43 | pen.speed(0) 44 | pen.color("white") 45 | pen.penup() 46 | pen.hideturtle() 47 | pen.goto(0, 210) 48 | pen.write("Player A: 0 Player B: 0", align="center", font=("Courier", 15, "bold")) 49 | 50 | # Function 51 | def paddle_a_up(): 52 | if paddle_a.ycor() > 160: exit() 53 | y = paddle_a.ycor() # This gives the Y-cordinate of paddle_a object to y. 54 | y += 20 # This increase the value of paddle_a's Y-cordinate. 55 | paddle_a.sety(y) # sety() is puting the new updated value of Y-cordinate to y. 56 | 57 | def paddle_a_down(): 58 | if paddle_a.ycor() < -160: 59 | exit() 60 | y = paddle_a.ycor() 61 | y -= 20 62 | paddle_a.sety(y) 63 | 64 | def paddle_b_up(): 65 | if paddle_b.ycor() > 160: 66 | exit() 67 | y = paddle_b.ycor() 68 | y += 20 69 | paddle_b.sety(y) 70 | 71 | def paddle_b_down(): 72 | if paddle_b.ycor() < -160: 73 | exit() 74 | y = paddle_b.ycor() 75 | y -= 20 76 | paddle_b.sety(y) 77 | 78 | # Keyboard binding 79 | wn.listen() # Here our window(wn) wait to listen the keypress. 80 | wn.onkeypress(paddle_a_up, "w") # If the key is w then because of onkeypress() it run paddle_a_up function. 81 | wn.onkeypress(paddle_a_down, "s") 82 | wn.onkeypress(paddle_b_up, "Up") # Up is for up arrow key. 83 | wn.onkeypress(paddle_b_down, "Down") # Down is for down arrow key. 84 | 85 | # Main game loop 86 | while True: 87 | wn.update() 88 | 89 | # Move the Ball 90 | ball.setx(ball.xcor() + ball.dx) 91 | ball.sety(ball.ycor() + ball.dy) 92 | 93 | # Border Checking 94 | """ 95 | As line-6 total height=500 and the ball is at the center of the screen so Y-cordinate is set to +250 at top 96 | and -250 at down as the ball size is 20px so from (0,0) it is +10 and -10 and that's how it's go. 97 | """ 98 | if ball.ycor() > 240: 99 | ball.sety(240) 100 | ball.dy *= -1 101 | 102 | if ball.ycor() < -240: 103 | ball.sety(-240) 104 | ball.dy *= -1 105 | 106 | """ 107 | As line-6 total width=800 and the ball is at the center of the screen so Y-cordinate is set to +400 at top 108 | and -400 at down as the ball size is 20px so from (0,0) it is +10 and -10 and that's how it's go. 109 | """ 110 | if ball.xcor() > 390: 111 | ball.goto(0, 0) 112 | ball.dx *= -1 113 | score_a += 1 114 | pen.clear() 115 | if score_a > score_b: 116 | pen.color("blue") 117 | pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center", font=("Courier", 15, "bold")) 118 | 119 | if ball.xcor() < -390: 120 | ball.goto(0, 0) 121 | ball.dx *= -1 122 | score_b += 1 123 | pen.clear() 124 | if score_b > score_a: 125 | pen.color("red") 126 | pen.write("Player A: {} Player B: {}".format(score_a, score_b), align="center", font=("Courier", 15, "bold")) 127 | 128 | 129 | if (ball.xcor() > 340 and ball.xcor() < 350) and (ball.ycor() < (paddle_b.ycor()+60) and ball.ycor() > (paddle_b.ycor()-60)): 130 | ball.setx(340) 131 | ball.dx *= -1 132 | 133 | if (ball.xcor() < -340 and ball.xcor() > -350) and (ball.ycor() < (paddle_a.ycor()+60) and ball.ycor() > (paddle_a.ycor()-60)): 134 | ball.setx(-340) 135 | ball.dx *= -1 136 | -------------------------------------------------------------------------------- /Projects/Quiz game/questions.py: -------------------------------------------------------------------------------- 1 | quiz = { 2 | 1 : { 3 | "question" : "What is the first name of Iron Man?", 4 | "answer" : "Tony" 5 | }, 6 | 2 : { 7 | "question" : "Who is called the god of lightning in Avengers?", 8 | "answer" : "Thor" 9 | }, 10 | 3 : { 11 | "question" : "Who carries a shield of American flag theme in Avengers?", 12 | "answer" : "Captain America" 13 | }, 14 | 4 : { 15 | "question" : "Which avenger is green in color?", 16 | "answer" : "Hulk" 17 | }, 18 | 5 : { 19 | "question" : "Which avenger can change it's size?", 20 | "answer" : "AntMan" 21 | }, 22 | 6 : { 23 | "question" : "Which Avenger is red in color and has mind stone?", 24 | "answer" : "Vision" 25 | } 26 | } -------------------------------------------------------------------------------- /Projects/Quiz game/quiz.py: -------------------------------------------------------------------------------- 1 | from questions import quiz 2 | 3 | 4 | def check_ans(question, ans, attempts, score): 5 | if quiz[question]['answer'].lower() == ans.lower(): 6 | print(f"Correct Answer! \nYour score is {score + 1}!") 7 | return True 8 | else: 9 | print(f"Wrong Answer :( \nYou have {attempts - 1} left! \nTry again...") 10 | return False 11 | 12 | 13 | def print_dictionary(): 14 | for question_id, ques_answer in quiz.items(): 15 | for key in ques_answer: 16 | print(key + ':', ques_answer[key]) 17 | 18 | 19 | def intro_message(): 20 | print("Welcome to this fun food quiz! \nAre you ready to test your knowledge about food?") 21 | print("There are a total of 20 questions, you can skip a question anytime by typing 'skip'") 22 | input("Press any key to start the fun ;) ") 23 | return True 24 | 25 | 26 | # python project.py 27 | intro = intro_message() 28 | while True: 29 | score = 0 30 | for question in quiz: 31 | attempts = 3 32 | while attempts > 0: 33 | print(quiz[question]['question']) 34 | answer = input("Enter Answer (To move to the next question, type 'skip') : ") 35 | if answer == "skip": 36 | break 37 | check = check_ans(question, answer, attempts, score) 38 | if check: 39 | score += 1 40 | break 41 | attempts -= 1 42 | 43 | break 44 | 45 | print(f"Your final score is {score}!\n\n") 46 | print("Want to know the correct answers? Please see them below! ;)\n") 47 | print_dictionary() 48 | print("Thanks for playing! 💜") -------------------------------------------------------------------------------- /Projects/Random_Option_Chooser.py: -------------------------------------------------------------------------------- 1 | #Python Code Random Option Chooser 2 | 3 | #imported random module 4 | import random 5 | 6 | print("Hello...! This is random option chooser program. ") 7 | 8 | #define a empty list to store options 9 | options = [] 10 | 11 | #variable for run the infinite while loop 12 | inf = 0 13 | 14 | #start the while loop 15 | while inf == 0: 16 | print("\nChoose a number to continue.") 17 | print( 18 | " \t01) Add the options. \n \t02) Choose a random option. \n \t03) How to use. \n \t04) About the program. \n \t05) Exit" 19 | ) 20 | a = input("Your option : ") 21 | 22 | #if cond. to store options in the list 23 | if a == "1": 24 | del options[:] 25 | c = int(input("\nEnter the number of options : ")) 26 | 27 | if c == 0: 28 | print( 29 | "\nNumber of options cannot be zero. Please enter more than one option." 30 | ) 31 | continue 32 | elif c == 1: 33 | print( 34 | "\nYou have enter number of options as one. Please enter more than one option for better performance." 35 | ) 36 | continue 37 | else: 38 | for d in range(c): 39 | options.append( 40 | input("\nEnter the " + str(d + 1) + " option : ")) 41 | 42 | #if cond. to choose a random option from the list. Items in the list should be more than two. 43 | if a == "2": 44 | e = options[random.randint(0, c - 1)] 45 | print("\nRandomly chose option for you is : " + e) 46 | continue 47 | 48 | #How to use print line 49 | if a == "3": 50 | print( 51 | "\nFirst enter number one in the terminal and add your options to the program.\nThen to get a random option, enter number two in the terminal.\nIf you want to edit the options, you can enter number two again and add the options.\nEnter number four to know about the program.\nTo exit from the program enter number five." 52 | ) 53 | continue 54 | 55 | #About the program print line 56 | if a == "4": 57 | print( 58 | "\nYou can a choose a random option with this program.\nFor a example if you want to choose a random name from a list of name, you can enter those names first and then get a random name without an infleunce from anyone and anything." 59 | ) 60 | continue 61 | 62 | #exit from the infinite while loop 63 | if a == "5": 64 | print("\nThank you for using this program. Good Bye !") 65 | inf = 1 66 | 67 | quit() 68 | -------------------------------------------------------------------------------- /Projects/RiddleMe!: -------------------------------------------------------------------------------- 1 | q=["I’m tall when I’m young, and I’m short when I’m old. What am I?","What goes up but never comes down?","I shave every day, but my beard stays the same. What am I?","I have branches, but no fruit, trunk or leaves. What am I?","The more of this there is, the less you see. What is it?","What has many keys but can’t open a single lock?","What invention lets you look right through a wall?","It belongs to you, but other people use it more than you do. What is it?","I am an odd number. Take away a letter and I become even. What number am I?","What five-letter word becomes shorter when you add two letters to it?"] 2 | a=['candle','age','barber','bank','darkness','piano','window','name','seven','short'] 3 | print(f'HANGMAN\nRules:\nThere are {len(q)} questions.\nYou will be given 3 chances to answer a question.\nSuccessfully answering a question will award you 1 point.\nEnjoy!') 4 | chance=1 5 | score=0 6 | for i in range (len(q)): 7 | print('>',q[i]) 8 | while chance<=3: 9 | guess=(input('Guess: ')) 10 | chance+=1 11 | if guess==a[i]: 12 | print('That is correct. Proceeding to next question...') 13 | score+=1 14 | chance=1 15 | break 16 | else: 17 | print('Wrong. Try Again!') 18 | else: 19 | print('Correct Answer:',a[i]) 20 | print('Proceeding to next question...') 21 | chance=1 22 | print(f'Final score is {score}/{len(q)}\nThank you!') 23 | input('Press enter to exit') 24 | -------------------------------------------------------------------------------- /Projects/Rock Paper Scissor Game/README.md: -------------------------------------------------------------------------------- 1 | # Rock Paper Scissor Game🔥 2 | 3 | - In the rock, paper and scissors game our goal is to create a command-line game where a user has the option to choose between rock, paper and scissors and if the user wins the score is added, and at the end when the user finishes the game, the score is shown to the user. 4 | 5 | ## 📌Rock, Paper and Scissors Game with Python 6 | 7 | - To create the Rock, Paper and Scissors game with Python, we need to take the user’s choice and then we need to compare it with the computer choice which is taken using the random module in Python from a list of choices, and if the user wins then the score will increase by 1: 8 | 9 | ### Code: 10 | 11 | import random 12 | 13 | choices = ["Rock", "Paper", "Scissor"] 14 | 15 | player = False 16 | cpu_score = 0 17 | player_score = 0 18 | 19 | while True: 20 | player = input("Enter your choice ").capitalize() 21 | 22 | computer = random.choice(choices) 23 | 24 | if computer == player: 25 | print("Its tie now...") 26 | 27 | elif player == "Rock": 28 | if computer == "Paper": 29 | print("You lose...", computer, "covers", player) 30 | cpu_score += 1 31 | 32 | else: 33 | print("You won...", player, "smashes", computer) 34 | player_score += 1 35 | 36 | elif player == "Paper": 37 | if computer == "Rock": 38 | print("You won...", player, "covers", computer) 39 | player_score += 1 40 | 41 | else: 42 | print("You lose...", computer, "cut", player) 43 | cpu_score += 1 44 | 45 | elif player == "Scissor": 46 | if computer == "Paper": 47 | print("You won...", player, "cut", computer) 48 | player_score += 1 49 | 50 | else: 51 | print("You lose...", computer, "smashes", player) 52 | cpu_score += 1 53 | 54 | elif player == "End": 55 | print("The final scores are ") 56 | print(f"CPU Score {cpu_score}") 57 | print(f"Player Score {player_score}") 58 | break 59 | 60 | 61 | ### Output: 62 | 63 | Enter your choice rock 64 | Its tie now... 65 | Enter your choice paper 66 | You won... Paper covers Rock 67 | Enter your choice scissors 68 | You lose... Rock smashes Scissors 69 | Enter your choice end 70 | The final scores are 71 | CPU Score 1 72 | Player Score 1 73 | 74 | ## 📌Summary 75 | 76 | - Creating these types of games will help a beginner to think logically. You can even use this idea to make your own game. In the end, creating these types of programs will help you create your algorithms, which is a very important skill for coding interviews and competitive programming. 77 | -------------------------------------------------------------------------------- /Projects/Rock Paper Scissor Game/main.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | randNo = random.randint(1,3) 4 | if randNo == 1: 5 | computer_choose = "r" # if randNo is equal to 1 then it will store 'r' as computer choice 6 | if randNo == 2: 7 | computer_choose = "p" # if randNo is equal to 2 then it will store 'p' as computer choice 8 | if randNo == 3: 9 | computer_choose = "s" # if randNo is equal to 3 then it will store 's' as computer choice 10 | 11 | # Defining gameWin function for performing major task for this game. 12 | 13 | def gameWin(computer_choose, user_input): 14 | if computer_choose == user_input: 15 | return None 16 | elif computer_choose == "r": 17 | if user_input == "p": 18 | return True 19 | elif user_input == "s": 20 | return False 21 | 22 | elif computer_choose == "p": 23 | if user_input == "r": 24 | return False 25 | elif user_input == "s": 26 | return True 27 | 28 | elif computer_choose == "s": 29 | if user_input == "r": 30 | return True 31 | elif user_input == "p": 32 | return False 33 | 34 | print("Computer Choosed already from Rock('r') or Paper('p') or Scissor('s')") 35 | 36 | print("Now your turn to choose") 37 | 38 | user_input = input("Choose from Rock('r') or Paper('p') or Scissor('s') ") #taking input from the user 39 | 40 | # It shows the user what computer choose from rock, paper or scissor. 41 | print("Computer choosed " + computer_choose) 42 | 43 | # It shows the user what he/she choose from rock, paper or scissor. 44 | print("You Choosed " + user_input) 45 | 46 | 47 | # This block of if-else statement will find out conditon of gameWin function 48 | 49 | if gameWin(computer_choose, user_input) == None: 50 | print("It tie now") 51 | 52 | elif gameWin(computer_choose, user_input): 53 | print("Congratulations You Won!!!") 54 | 55 | else: 56 | print("You Lose!") 57 | -------------------------------------------------------------------------------- /Projects/Rock Paper Scissor Game/rock_paper_scissor_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | choices = ["Rock", "Paper", "Scissor"] 4 | 5 | player = False 6 | cpu_score = 0 7 | player_score = 0 8 | 9 | while True: 10 | player = input("Enter your choice ").capitalize() 11 | 12 | computer = random.choice(choices) 13 | 14 | if computer == player: 15 | print("Its tie now...") 16 | 17 | elif player == "Rock": 18 | if computer == "Paper": 19 | print("You lose...", computer, "covers", player) 20 | cpu_score += 1 21 | 22 | else: 23 | print("You won...", player, "smashes", computer) 24 | player_score += 1 25 | 26 | elif player == "Paper": 27 | if computer == "Rock": 28 | print("You won...", player, "covers", computer) 29 | player_score += 1 30 | 31 | else: 32 | print("You lose...", computer, "cut", player) 33 | cpu_score += 1 34 | 35 | elif player == "Scissor": 36 | if computer == "Paper": 37 | print("You won...", player, "cut", computer) 38 | player_score += 1 39 | 40 | else: 41 | print("You lose...", computer, "smashes", player) 42 | cpu_score += 1 43 | 44 | elif player == "End": 45 | print("The final scores are ") 46 | print(f"CPU Score {cpu_score}") 47 | print(f"Player Score {player_score}") 48 | break -------------------------------------------------------------------------------- /Projects/Roshambo.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | ## The actions possible in the game 4 | actions = ["rock", "paper", "scissors"] 5 | ## User makes a selection 6 | while (1): 7 | print("Welcome to the game") 8 | user_choice = input( 9 | "Make your choice (rock ,paper, scissors) or type 'Q' to exit the game : \n" 10 | ) 11 | computer_choice = random.choice(actions) 12 | if user_choice == computer_choice: 13 | print("It is a tie!!!") 14 | elif user_choice == 'rock': 15 | if computer_choice == 'paper': 16 | print( 17 | f"Computer chose : {computer_choice}. You lose !!! Better luck next time" 18 | ) 19 | else: 20 | print(f"Computer chose : {computer_choice}. You Win !!!") 21 | elif user_choice == 'scissor': 22 | if computer_choice == "rock": 23 | print( 24 | f"Computer chose : {computer_choice}. You lose !!! Better luck next time" 25 | ) 26 | else: 27 | print(f"Computer chose : {computer_choice}. You Win !!!") 28 | elif user_choice == 'paper': 29 | if computer_choice == 'scissors': 30 | print( 31 | f"Computer chose : {computer_choice}. You lose !!! Better luck next time" 32 | ) 33 | else: 34 | print(f"Computer chose : {computer_choice}. You win !!!") 35 | elif user_choice == 'Q': 36 | break 37 | else: 38 | print("Please make a correct choice: (rock, paper, scissors) or 'Q' ") 39 | -------------------------------------------------------------------------------- /Projects/Roulette-Game.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | 3 | totalAmount = 1000 #total amount invested 4 | 5 | while totalAmount > 0: 6 | print("Welcome !!!\nYou have", totalAmount, 7 | "€. Good Luck !!\n_________________________________") 8 | selectedNumber = int(input("\nOn which number do you want to bet ?")) 9 | 10 | x = 0 11 | x = selectNumber 12 | if x < 0 or x > 49: 13 | print("You have to bet a number between 0 and 49") 14 | 15 | bettingAmount = int(input("How much do you want to bet on this number?")) 16 | numberOutput = randint( 17 | 0, 49) # line to use to generate a random number between 0 and 49 18 | print("\nThe number output is", numberOutput) 19 | 20 | if numberOutput == selectedNumber: 21 | print("You Win!!!\n_________________________________") 22 | 23 | else: 24 | print("Sorry but you lost, try again !") 25 | totalAmount -= bettingAmount 26 | print("\nYou now have", totalAmount, 27 | "€ left\n_________________________________") 28 | 29 | if totalAmount == 0: 30 | print( 31 | "Sorry but you don't have enough money to continue !\nThe game is now ending !" 32 | ) 33 | -------------------------------------------------------------------------------- /Projects/SnakeGame/img/apple.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/SnakeGame/img/apple.jpg -------------------------------------------------------------------------------- /Projects/SnakeGame/img/ghost.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/SnakeGame/img/ghost.png -------------------------------------------------------------------------------- /Projects/Space Shooter Game/.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | -------------------------------------------------------------------------------- /Projects/Space Shooter Game/.idea/inspectionProfiles/Project_Default.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /Projects/Space Shooter Game/.idea/inspectionProfiles/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 6 | -------------------------------------------------------------------------------- /Projects/Space Shooter Game/.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /Projects/Space Shooter Game/.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /Projects/Space Shooter Game/.idea/pythonProject15.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /Projects/Space Shooter Game/SHPinscher-Regular.otf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Space Shooter Game/SHPinscher-Regular.otf -------------------------------------------------------------------------------- /Projects/Space Shooter Game/background.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Space Shooter Game/background.png -------------------------------------------------------------------------------- /Projects/Space Shooter Game/bullet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Space Shooter Game/bullet.png -------------------------------------------------------------------------------- /Projects/Space Shooter Game/enemy laser.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Space Shooter Game/enemy laser.png -------------------------------------------------------------------------------- /Projects/Space Shooter Game/enemy spaceship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Space Shooter Game/enemy spaceship.png -------------------------------------------------------------------------------- /Projects/Space Shooter Game/missile spaceship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Space Shooter Game/missile spaceship.png -------------------------------------------------------------------------------- /Projects/Space Shooter Game/missile.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Space Shooter Game/missile.png -------------------------------------------------------------------------------- /Projects/Space Shooter Game/spaceship.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Space Shooter Game/spaceship.png -------------------------------------------------------------------------------- /Projects/Stack using Class.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | data = [] 3 | top = len(data) - 1 4 | size = 10 5 | 6 | def push(self, element): 7 | if (self.top == self.size - 1): 8 | print("Stack is full! OVERFLOW!") 9 | else: 10 | self.top += 1 11 | self.data.append(element) 12 | print(self.data[self.top], "has entered the stack\n") 13 | 14 | def pop(self): 15 | if (self.top == -1): 16 | print("Stack is Empty! UNDERFLOW!") 17 | else: 18 | print(self.data[self.top], " has been popped\n") 19 | del self.data[self.top] 20 | self.top -= 1 21 | 22 | def peek(self): 23 | print("Location of Top is : ", self.top + 1) 24 | for i in range(self.top + 1): 25 | print(self.data[i]) 26 | 27 | 28 | s = Stack() 29 | while (1): 30 | print("Enter:\n 1:Push\n 2:Pop\n 3:Display Stack\n 4:Exit") 31 | i = int(input("Enter your choice : ")) 32 | if (i == 1): 33 | element = int(input("Enter element to push : ")) 34 | s.push(element) 35 | elif (i == 2): 36 | s.pop() 37 | elif (i == 3): 38 | s.show() 39 | else: 40 | break 41 | -------------------------------------------------------------------------------- /Projects/Task_Reminder/Instructions.md: -------------------------------------------------------------------------------- 1 | ## Basic Task Reminder 2 | 3 | This small project is a basic task reminder program built in python for windows machine. 4 | 5 | It has a voice output and notification system. 6 | 7 | All you have to do is fill your schedule in the given excel file with proper time format. 8 | 9 | The notification system will notify you at the time that you have specified in the excel file with its description. 10 | -------------------------------------------------------------------------------- /Projects/Task_Reminder/ReminderDiary.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Task_Reminder/ReminderDiary.xlsx -------------------------------------------------------------------------------- /Projects/Task_Reminder/img/Task_Reminder.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Task_Reminder/img/Task_Reminder.ico -------------------------------------------------------------------------------- /Projects/Task_Reminder/img/Task_Reminder.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Task_Reminder/img/Task_Reminder.png -------------------------------------------------------------------------------- /Projects/Task_Reminder/img/Task_Reminder.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Task_Reminder/img/Task_Reminder.psd -------------------------------------------------------------------------------- /Projects/Task_Reminder/main.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | from openpyxl import load_workbook 3 | import time 4 | from datetime import datetime 5 | from plyer import notification 6 | import pyttsx3 7 | 8 | 9 | engine = pyttsx3.init('sapi5')# Initialize engine for the voices 10 | voices = engine.getProperty('voices') 11 | engine.setProperty('voice', voices[0].id)# Set voice for the reminder 12 | 13 | 14 | def clean_time(t,m): 15 | ''' 16 | This function will clean the time and convert it to 24 hours time. 17 | ''' 18 | temp = int(t.split(':')[0]) 19 | if m=='pm' and temp!=12: 20 | temp+=12 21 | return str(temp)+':'+str(t.split(':')[1])+':00' 22 | else: 23 | return t+':00' 24 | 25 | 26 | def check_valid_time(tm): 27 | ''' 28 | This function is used to check whether the entered time is valid or not. 29 | ''' 30 | if int(tm.split(':')[0]) >=24: 31 | return False 32 | else: 33 | return True 34 | 35 | 36 | def speak(audio): 37 | ''' 38 | This function will be used to give output in form of voice. 39 | ''' 40 | engine.say(audio) 41 | engine.runAndWait() 42 | 43 | 44 | if __name__ == "__main__": 45 | diary = load_workbook('ReminderDiary.xlsx')['Sheet1'].values # Loading workbook. 46 | next(diary) # Incrementing the excel sheet inorder to avoid header frame. 47 | df = pd.DataFrame(data=diary,columns=('time','am/pm','task','status')) # creating dataframe from excel. 48 | del diary # deleting the workbook variable which is now of no longer use. 49 | for index, row in df.iterrows(): # Iterating the diary, checking the schedule 50 | if row['time'] == None: 51 | break 52 | try: 53 | a_time = clean_time(row['time'].strftime('%H:%M:%S'),row['am/pm']) # Converting to 24 hour time. 54 | if not(check_valid_time(a_time)): 55 | continue 56 | current_time = datetime.now().strftime('%H:%M:%S') # getting current time. 57 | tdelta = datetime.strptime(a_time, '%H:%M:%S') - datetime.strptime(current_time, '%H:%M:%S') # Calculating the time left for the next reminder. 58 | del current_time 59 | tdelta = str(tdelta).split(':') 60 | secs = int(int(tdelta[0])*3600+int(tdelta[1])*60+int(tdelta[2])) # Converting the remaining time into seconds. 61 | del tdelta,a_time 62 | time.sleep(secs) # Sending program to sleep mode until next event occurs. 63 | notification.notify( 64 | title=row['task'], 65 | app_icon="D:\Github Projects\Basic-Python-Projects\Task_Reminder\img\Task_Reminder.ico", 66 | message='Hey ayush its time to complete your following task... '+row['task'], 67 | timeout=3, 68 | ) # sending notification in windows. 69 | time.sleep(1) 70 | speak('Hey ayush its time to complete your task named '+row['task']) # Notifying in a voice form. 71 | 72 | except Exception as e: 73 | print('There is some error in your scheduling') 74 | print(e) 75 | print('Its end of your schedule. Have a great day ahead') # indicating end of schedule. -------------------------------------------------------------------------------- /Projects/Task_Reminder/requirements.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Task_Reminder/requirements.txt -------------------------------------------------------------------------------- /Projects/Tic-Tac-Toe.py: -------------------------------------------------------------------------------- 1 | board=['0','1','2','3','4','5','6','7','8'] 2 | empty = [0,1,2,3,4,5,6,7,8] 3 | 4 | def display_board(): 5 | print(' | | ') 6 | print(board[0]+' | '+board[1]+' | '+board[2]) 7 | print(' | | ') 8 | print('---------') 9 | print(' | | ') 10 | print(board[3]+' | '+board[4]+' | '+board[5]) 11 | print(' | | ') 12 | print('---------') 13 | print(' | | ') 14 | print(board[6]+' | '+board[7]+' | '+board[8]) 15 | print(' | | ') 16 | 17 | def player_input(player): 18 | player_symbol = ['X','O'] 19 | correct_input = True 20 | 21 | position = int(input('player {playerNo} chance! Choose field to fill {symbol} '.format(playerNo = player +1, symbol = player_symbol[player]))) 22 | 23 | if board[position] == 'X' or board[position] == 'O': 24 | correct_input = False 25 | 26 | if not correct_input: 27 | print("Position already equipped") 28 | player_input(player) 29 | else: 30 | empty.remove(position) 31 | board[position] = player_symbol[player] 32 | return 1 33 | 34 | def check_win(): 35 | player_symbol = ['X','O'] 36 | winning_positions =[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]] 37 | 38 | for check in winning_positions: 39 | first_symbol = board[check[0]] 40 | if first_symbol != ' ': 41 | won = True 42 | for point in check: 43 | if board[point] != first_symbol: 44 | won = False 45 | break 46 | if won: 47 | if first_symbol == player_symbol[0]: 48 | print('player 1 won') 49 | else: 50 | print('player 2 won') 51 | break 52 | else: 53 | won = False 54 | 55 | if won: 56 | return 0 57 | else: 58 | return 1 59 | def play(): 60 | player = 0 61 | while empty and check_win(): 62 | display_board() 63 | player_input(player) 64 | player = int(not player) 65 | if not empty: 66 | print("NO WINNER!") 67 | 68 | if __name__ == '__main__': 69 | play() 70 | -------------------------------------------------------------------------------- /Projects/URLShortener.py: -------------------------------------------------------------------------------- 1 | import pyperclip 2 | # if you don't have pyperclip imported, you can do so by using the command - pip install pyperclip 3 | import pyshorteners 4 | # if you don't have pyshortener imported, you can do so by using the command - pip install pyshortener 5 | from tkinter import * 6 | # importing tkinter 7 | 8 | root = Tk() 9 | root.geometry("400x200") 10 | root.title("URL Shortener") 11 | root.configure(bg="#49A") 12 | url = StringVar() 13 | url_address = StringVar() 14 | 15 | 16 | def urlshortner(): 17 | urladdress = url.get() 18 | url_short = pyshorteners.Shortener().tinyurl.short(urladdress) 19 | url_address.set(url_short) 20 | 21 | 22 | def copyurl(): 23 | url_short = url_address.get() 24 | pyperclip.copy(url_short) 25 | 26 | 27 | Label(root, text="My URL Shortener", font="poppins").pack(pady=10) 28 | Entry(root, textvariable=url).pack(pady=5) 29 | Button(root, text="Generate Short URl", command=urlshortner).pack(pady=7) 30 | Entry(root, textvariable=url_address).pack(pady=5) 31 | Button(root, text="Copy URL", command=copyurl).pack(pady=5) 32 | 33 | root.mainloop() 34 | -------------------------------------------------------------------------------- /Projects/Youtube - AudioVideo Downloader/app.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Youtube - AudioVideo Downloader/app.png -------------------------------------------------------------------------------- /Projects/Youtube - AudioVideo Downloader/icons/back.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Youtube - AudioVideo Downloader/icons/back.png -------------------------------------------------------------------------------- /Projects/Youtube - AudioVideo Downloader/icons/search.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Youtube - AudioVideo Downloader/icons/search.png -------------------------------------------------------------------------------- /Projects/Youtube - AudioVideo Downloader/icons/youtube.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/Youtube - AudioVideo Downloader/icons/youtube.png -------------------------------------------------------------------------------- /Projects/Youtube - AudioVideo Downloader/readme.md: -------------------------------------------------------------------------------- 1 | # SaveFromYT 2 | 3 | [![forthebadge](https://forthebadge.com/images/badges/built-with-love.svg)](https://forthebadge.com) 4 | [![forthebadge](https://forthebadge.com/images/badges/built-with-swag.svg)](https://forthebadge.com) 5 | [![forthebadge](https://forthebadge.com/images/badges/made-with-python.svg)](https://forthebadge.com) 6 | 7 | SaveFromYT is a simple python tkinter based application to download mp4 videos and mp3 audio from a youtube video url 8 | 9 | ![Alt text](app.png?raw=true "SaveFromYT") 10 | 11 | The application requires an active internet connection for downloading mp4/mp3. 12 | 13 | ## How to Download 14 | 15 | Download this project from here [Download SaveFromYT](https://downgit.github.io/#/home?url=https:%2F%2Fgithub.com%2FpyGuru123%2FTkinter-Applications%2Ftree%2Fmaster%2FYoutube%20-%20AudioVideo%20Downloader) 16 | 17 | ## Requirements 18 | 19 | Use the package manager [pip](https://pip.pypa.io/en/stable/) to install following packages :- 20 | * pafy 21 | * youtube-dl 22 | 23 | ```bash 24 | pip install pafy 25 | pip install youtube-dl 26 | ``` 27 | 28 | pafy uses youtube-dl as backend, so remember to install both packages 29 | 30 | #### API Note 31 | 32 | Pafy comes with default api key, but if you get API limit exceede error, get yourself an youtube v3 api key from [google console](https://developers.google.com/youtube/v3/getting-started) and paste in the script beginning 33 | 34 | ```bash 35 | pafy.set_api_key(key) 36 | ``` 37 | 38 | ## Usage 39 | 40 | Double click the application.pyw to open the GUI application, then paste the youtube video url which you want download and click enter, the followup screen will come up with video metadata and download buttons for downloading files. You can choose video quality from the option box before downloding. 41 | 42 | 43 | ## Contributing 44 | 45 | Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. 46 | 47 | Please make sure to update tests as appropriate. -------------------------------------------------------------------------------- /Projects/YoutubeDownloader.py: -------------------------------------------------------------------------------- 1 | #Make sure you have installed pytube3 on your system. If not follow these steps:- 2 | #Open windows terminal and type (First install PIP) 3 | #pip install pytubeX 4 | 5 | from pytube import YouTube 6 | 7 | n = int(input("Enter the number of youtube videos to download: ")) 8 | links = [] 9 | print("\nEnter all the links one per line:") 10 | 11 | for i in range(0, n): 12 | temp = input() 13 | links.append(temp) 14 | 15 | for i in range(0, n): 16 | link = links[i] 17 | yt = YouTube(link) 18 | print("\nDetails for Video", i + 1, "\n") 19 | print("Title of video: ", yt.title) 20 | print("Number of views: ", yt.views) 21 | print("Length of video: ", yt.length, "seconds") 22 | stream = str(yt.streams.filter(progressive=True)) 23 | stream = stream[1:] 24 | stream = stream[:-1] 25 | streamlist = stream.split(", ") 26 | print("\nAll available options for downloads:\n") 27 | for i in range(0, len(streamlist)): 28 | st = streamlist[i].split(" ") 29 | print(i + 1, ") ", st[1], " and ", st[3], sep='') 30 | tag = int( 31 | input("\nEnter the itag of your preferred stream to download: ")) 32 | ys = yt.streams.get_by_itag(tag) 33 | print("\nDownloading...") 34 | ys.download() 35 | print("\nDownload completed!!") 36 | print() 37 | -------------------------------------------------------------------------------- /Projects/YoutubeVideoDownloader.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/YoutubeVideoDownloader.png -------------------------------------------------------------------------------- /Projects/acro-chat.py: -------------------------------------------------------------------------------- 1 | # MODULES 2 | import pyttsx3 3 | import datetime 4 | import requests 5 | import speech_recognition as sr 6 | from requests import get 7 | 8 | engine = pyttsx3.init('sapi5') 9 | voices = engine.getProperty('voices') 10 | #print(voices[0].id) 11 | #print(voices[1].id) 12 | #print(voices[2].id) 13 | #print(voices[3].id) 14 | #print(voices[4].id) 15 | #print(voices[5].id) 16 | #print(voices[6].id) 17 | #print(voices) 18 | engine.setProperty('voice', voices[1].id) 19 | 20 | 21 | def speak(audio): 22 | engine.say(audio) 23 | engine.runAndWait() 24 | 25 | 26 | # WISH ME 27 | def wishMe(): 28 | hour = int(datetime.datetime.now().hour) 29 | if hour >= 0 and hour < 12: 30 | speak("Good Morning Sir!") 31 | 32 | elif hour >= 12 and hour < 18: 33 | speak("Good Afternoon Sir!") 34 | 35 | else: 36 | speak("Good Evening Sir!") 37 | 38 | speak("Acro Here,How may i help you?") 39 | 40 | 41 | def takeCommand(): 42 | #It takes microphone input from the user and returns string output 43 | 44 | r = sr.Recognizer() 45 | with sr.Microphone() as source: 46 | print("Listening...") 47 | r.pause_threshold = 1 48 | audio = r.listen(source) 49 | 50 | try: 51 | print("Recognizing...") 52 | query = r.recognize_google(audio, language='en-in') 53 | print(f"User said: {query}\n") 54 | 55 | except Exception as e: 56 | # print(e) 57 | print("Say that again please...") 58 | return "None" 59 | return query 60 | 61 | 62 | wishMe() 63 | 64 | 65 | def run_alpha(): 66 | inpu = takeCommand() 67 | print(inpu) 68 | url = "http://api.brainshop.ai/get?bid=157984&key=3S0hhLXZ5GS2KYs4&uid=[uid]&msg=[{}]".format( 69 | inpu) 70 | response = requests.get(url).json()['cnt'] 71 | print(response) 72 | speak(response) 73 | 74 | 75 | while True: 76 | run_alpha() 77 | -------------------------------------------------------------------------------- /Projects/alpha.py: -------------------------------------------------------------------------------- 1 | # MODULES 2 | import pyttsx3 3 | import datetime 4 | import speech_recognition as sr 5 | import webbrowser 6 | import os 7 | import random 8 | from requests import get 9 | import pyjokes 10 | 11 | engine = pyttsx3.init('sapi5') 12 | voices = engine.getProperty('voices') 13 | # print(voices[0].id) 14 | engine.setProperty('voice', voices[0].id) 15 | 16 | 17 | def speak(audio): 18 | engine.say(audio) 19 | engine.runAndWait() 20 | 21 | 22 | # WISH ME 23 | def wishMe(): 24 | hour = int(datetime.datetime.now().hour) 25 | if hour >= 0 and hour < 12: 26 | speak("Good Morning Sir!") 27 | 28 | elif hour >= 12 and hour < 18: 29 | speak("Good Afternoon Sir!") 30 | 31 | else: 32 | speak("Good Evening Sir!") 33 | 34 | speak("ALPHA Here,How may i help you?") 35 | 36 | 37 | def takeCommand(): 38 | #It takes microphone input from the user and returns string output 39 | 40 | r = sr.Recognizer() 41 | with sr.Microphone() as source: 42 | print("Listening...") 43 | r.pause_threshold = 1 44 | audio = r.listen(source) 45 | 46 | try: 47 | print("Recognizing...") 48 | query = r.recognize_google(audio, language='en-in') 49 | print(f"User said: {query}\n") 50 | 51 | except Exception as e: 52 | # print(e) 53 | print("Say that again please...") 54 | return "None" 55 | return query 56 | 57 | 58 | def run_alpha(): 59 | wishMe() 60 | query = takeCommand() 61 | print(query) 62 | 63 | # SEARCH SOMETHING ON GOOGLE 64 | if 'search on google' in query: 65 | speak("What would you like to search on google?") 66 | cm = takeCommand().lower() 67 | webbrowser.open(f"{cm}") 68 | 69 | # WHATS THE TIME 70 | elif 'the time' in query: 71 | strTime = datetime.datetime.now().strftime("%H:%M:%S") 72 | speak(f"The Time is {strTime}") 73 | 74 | # SIMPLE TALKS 75 | elif "what\'s up" in query or 'how are you' in query: 76 | stMsgs = [ 77 | 'Just doing my thing!', 'I am fine!', 'Nice!', 78 | 'I am nice and full of energy', 'i am okey ! How are you' 79 | ] 80 | ans_q = random.choice(stMsgs) 81 | speak(ans_q) 82 | ans_take_from_user_how_are_you = takeCommand() 83 | if 'fine' in ans_take_from_user_how_are_you or 'happy' in ans_take_from_user_how_are_you or 'okey' in ans_take_from_user_how_are_you: 84 | speak('okey..') 85 | elif 'not' in ans_take_from_user_how_are_you or 'sad' in ans_take_from_user_how_are_you or 'upset' in ans_take_from_user_how_are_you: 86 | speak('oh sorry..') 87 | elif 'make you' in query or 'created you' in query or 'develop you' in query: 88 | ans_m = " For your information Sachin Lohar AKA ALPHA Created me ! I give Lot of Thannks to Him " 89 | print(ans_m) 90 | speak(ans_m) 91 | elif "who are you" in query or "about you" in query or "your details" in query: 92 | about = "I am ALPHA an A I based computer program but i can help you lot like a your close friend ! i promise you ! Simple try me to give simple command ! like playing music or video from your directory i also play video and song from web or online ! i can also entain you i so think you Understand me ! ok Lets Start " 93 | print(about) 94 | speak(about) 95 | elif "hello" in query or "hello ALPHA" in query: 96 | hel = "Hello Sir ! How May i Help you.." 97 | print(hel) 98 | speak(hel) 99 | elif "your name" in query or "sweat name" in query: 100 | na_me = "Thanks for Asking my name my self ! ALPHA" 101 | print(na_me) 102 | speak(na_me) 103 | elif "you feeling" in query: 104 | print("feeling Very sweet after meeting with you") 105 | speak("feeling Very sweet after meeting with you") 106 | #IP ADDRESS 107 | elif "ip address" in query: 108 | ip = get('https://api.ipify.org').text 109 | speak(f"Your IP address is {ip}") 110 | # JOKE 111 | elif "Tell me a joke" in query: 112 | joke = pyjokes.get_joke() 113 | speak(joke) 114 | 115 | # SHUTDOWN 116 | elif "shut down the system" in query: 117 | os.system("shutdown /s /t 5") 118 | # RESTART 119 | elif "restart the system" in query: 120 | os.system("shutdown /r /t 5") 121 | 122 | 123 | # SLEEP 124 | elif "sleep the system" in query: 125 | os.system("rundll32.exe powrprof.dll,SetSuspendState 0,1,0") 126 | 127 | while True: 128 | run_alpha() 129 | -------------------------------------------------------------------------------- /Projects/alphaAi.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/alphaAi.PNG -------------------------------------------------------------------------------- /Projects/calc.py: -------------------------------------------------------------------------------- 1 | # calculator function - which when called will function as a calculator 2 | def calculator(): 3 | print( 4 | "Options:\n\t[1] Add \n\t[2] Subtract \n\t[3] Multiply \n\t[4] Divide \n\t[5] Power \n\t[6] Square root" 5 | ) 6 | ch = int(input("\t--> ")) # take option input from user 7 | 8 | #addition 9 | if ch == 1: 10 | num1 = float(input("1st number --> ")) 11 | num2 = float(input("2nd number --> ")) 12 | print(f"{num1} + {num2} = {num1 + num2}") 13 | #subtraction 14 | elif ch == 2: 15 | num1 = float(input("1st number --> ")) 16 | num2 = float(input("2nd number --> ")) 17 | print(f"{num1} - {num2} = {num1 - num2}") 18 | #multiplication 19 | elif ch == 3: 20 | num1 = float(input("1st number --> ")) 21 | num2 = float(input("2nd number --> ")) 22 | print(f"{num1} x {num2} = {num1 * num2}") 23 | #division 24 | elif ch == 4: 25 | num1 = float(input("Dividend --> ")) 26 | num2 = float(input("Divisor --> ")) 27 | # try-except which checks if divisor is zero (which isn't allowed) 28 | try: 29 | print(f"{num1} ÷ {num2} = {num1 / num2}") 30 | except ZeroDivisionError: 31 | print(f"{num1} ÷ {num2} = Error: Division by 0!") 32 | #power 33 | elif ch == 5: 34 | num = float(input("Number --> ")) 35 | power = float(input("Power --> ")) 36 | print(f"{num} ^ {power} = {num ** power}") 37 | #root 38 | elif ch == 6: 39 | num = float(input("Number --> ")) 40 | print(f"√{num} = {num**(1/2)}") 41 | else: 42 | print("Invalid input!!") 43 | 44 | 45 | #==================== 46 | # MAIN PROGRAM 47 | print("<-- Basic Calculator -->") 48 | print("Does what it says on the tin!") 49 | print("-" * 30) #decoration 50 | 51 | run = 'Y' 52 | while run == 'Y': 53 | calculator() 54 | 55 | print("-" * 30) 56 | 57 | print("Would you like calculate more?\n\t[Y] Yes\n\t[N] No") 58 | run = input("\t--> ").upper() 59 | while run not in ['Y', 'YES', 'N', 'NO']: 60 | run = input("\t--> ").upper() 61 | 62 | print("-" * 30) 63 | -------------------------------------------------------------------------------- /Projects/choice_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | print("Welcome to the choice game!") 3 | name = input("Enter your name: ").lower() 4 | age = int(input("Enter your age: ")) 5 | win_lose = ["win", "lose"] 6 | 7 | if age >= 16: 8 | print("You are allowed to play!") 9 | wants_to_play = input("Do you want to play? (yes/no) ").lower() 10 | if wants_to_play == "yes": 11 | print("Let's play!!") 12 | letter_choice = input("Choose a letter (a/b): ") 13 | if letter_choice == "a": 14 | win_or_lose = random.choice(win_lose) 15 | if win_or_lose == "win": 16 | left_or_right = input("Good! Choose left or right(left/right): ").lower() 17 | if left_or_right == "left": 18 | win_or_lose_1 = random.choice(win_lose) 19 | if win_or_lose_1 == "win": 20 | print("Congratulations!! You win!!!") 21 | else: 22 | print("Sorry! You lose!") 23 | else: 24 | print("Sorry! You lose!") 25 | else: 26 | win_or_lose = random.choice(win_lose) 27 | if win_or_lose == "win": 28 | up_or_down = input("Good! Choose up/down(up/down): ").lower() 29 | if up_or_down == "up": 30 | win_or_lose_1 = random.choice(win_lose) 31 | if win_or_lose_1 == "win": 32 | print("Congratulations!! You win!!!") 33 | else: 34 | print("Sorry! You lose!") 35 | else: 36 | print("Sorry! You lose!") 37 | else: 38 | print("Goodbye!") 39 | else: 40 | print("Sorry, you aren't allowed to play!") 41 | 42 | 43 | ''' 44 | 45 | if age >= 16: 46 | print("You are allowed to play!") 47 | wants_to_play = input("Do you want to play? (yes/no) ").lower() 48 | if wants_to_play == "yes": 49 | print("Let's play!!") 50 | letter_choice = input("Choose a letter (a/b): ") 51 | if letter_choice == "a": 52 | up_or_down = input("Good choice! Do you want to go up or down?(up/down): ").lower() 53 | if up_or_down == "up": 54 | print("Congratulations! You Win!") 55 | else: 56 | print("Snap! You lost!") 57 | else: 58 | left_or_right = input("Well chosen! Do you want to go left/right?(left/right) ").lower() 59 | if left_or_right == "right": 60 | print("Congratulations! You win!") 61 | else: 62 | print("Snap! You lost!") 63 | else: 64 | print("Goodbye!") 65 | else: 66 | print("Sorry, you aren't allowed to play!") 67 | 68 | ''' 69 | -------------------------------------------------------------------------------- /Projects/currencyconvertor.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from tkinter import * 3 | import tkinter as tk 4 | from tkinter import ttk 5 | 6 | 7 | class RealTimeCurrencyConverter(): 8 | 9 | def __init__(self, url): 10 | self.data = requests.get(url).json() 11 | self.currencies = self.data['rates'] 12 | 13 | def convert(self, from_currency, to_currency, amount): 14 | initial_amount = amount 15 | if from_currency != 'USD': 16 | amount = amount / self.currencies[from_currency] 17 | 18 | # limiting the precision to 4 decimal places 19 | amount = round(amount * self.currencies[to_currency], 4) 20 | return amount 21 | 22 | 23 | class App(tk.Tk): 24 | 25 | def __init__(self, converter): 26 | tk.Tk.__init__(self) 27 | self.title = 'Currency Converter' 28 | self.currency_converter = converter 29 | 30 | #self.configure(background = 'blue') 31 | self.geometry("600x250") 32 | 33 | # Label 34 | self.intro_label = Label( 35 | self, 36 | text='Welcome to Real Time Currency Convertor', 37 | fg='white', 38 | bg='navyblue', 39 | relief=tk.RAISED, 40 | borderwidth=3) 41 | self.intro_label.config(font=('Courier', 15, 'bold')) 42 | 43 | self.date_label = Label( 44 | self, 45 | text= 46 | f"1 Indian Rupee equals = {self.currency_converter.convert('INR','USD',1)} USD \n Date : {self.currency_converter.data['date']}", 47 | relief=tk.GROOVE, 48 | borderwidth=5) 49 | 50 | self.intro_label.place(x=120, y=0) 51 | self.date_label.place(x=160, y=50) 52 | 53 | # Entry box 54 | valid = (self.register(self.restrictNumberOnly), '%d', '%P') 55 | self.amount_field = Entry(self, 56 | bd=3, 57 | relief=tk.RIDGE, 58 | justify=tk.CENTER, 59 | validate='key', 60 | validatecommand=valid) 61 | 62 | self.converted_amount_field_label = Label(self, 63 | text='', 64 | fg='black', 65 | bg='white', 66 | relief=tk.RIDGE, 67 | justify=tk.CENTER, 68 | width=20, 69 | borderwidth=3) 70 | 71 | # dropdown 72 | self.from_currency_variable = StringVar(self) 73 | self.from_currency_variable.set("INR") # default value 74 | self.to_currency_variable = StringVar(self) 75 | self.to_currency_variable.set("USD") # default value 76 | 77 | font = ("Courier", 12, "bold") 78 | self.option_add('*TCombobox*Listbox.font', font) 79 | self.from_currency_dropdown = ttk.Combobox( 80 | self, 81 | textvariable=self.from_currency_variable, 82 | values=list(self.currency_converter.currencies.keys()), 83 | font=font, 84 | state='readonly', 85 | width=12, 86 | justify=tk.CENTER) 87 | self.to_currency_dropdown = ttk.Combobox( 88 | self, 89 | textvariable=self.to_currency_variable, 90 | values=list(self.currency_converter.currencies.keys()), 91 | font=font, 92 | state='readonly', 93 | width=12, 94 | justify=tk.CENTER) 95 | 96 | # placing 97 | self.from_currency_dropdown.place(x=40, y=120) 98 | self.amount_field.place(x=36, y=150) 99 | self.to_currency_dropdown.place(x=346, y=120) 100 | #self.converted_amount_field.place(x = 346, y = 150) 101 | self.converted_amount_field_label.place(x=346, y=150) 102 | 103 | # Convert button 104 | self.convert_button = Button(self, 105 | text="Convert", 106 | fg="black", 107 | bg="blue", 108 | command=self.perform) 109 | self.convert_button.config(font=('Courier', 15, 'bold')) 110 | self.convert_button.place(x=240, y=190) 111 | 112 | def perform(self): 113 | amount = float(self.amount_field.get()) 114 | from_curr = self.from_currency_variable.get() 115 | to_curr = self.to_currency_variable.get() 116 | 117 | converted_amount = self.currency_converter.convert( 118 | from_curr, to_curr, amount) 119 | converted_amount = round(converted_amount, 2) 120 | 121 | self.converted_amount_field_label.config(text=str(converted_amount)) 122 | 123 | def restrictNumberOnly(self, action, string): 124 | regex = re.compile(r"[0-9,]*?(\.)?[0-9,]*$") 125 | result = regex.match(string) 126 | return (string == "" 127 | or (string.count('.') <= 1 and result is not None)) 128 | 129 | 130 | if __name__ == '__main__': 131 | url = ' add your api url from here https://www.exchangerate-api.com/' 132 | converter = RealTimeCurrencyConverter(url) 133 | 134 | App(converter) 135 | mainloop() 136 | -------------------------------------------------------------------------------- /Projects/days-alives.py: -------------------------------------------------------------------------------- 1 | # This program calculates the number of days an individual has been alive for 2 | 3 | import datetime 4 | 5 | a = int(input("What year were you born ? ")) 6 | b = int( 7 | input( 8 | "What month were you born(Number format where January is 1 and December is 12) ? " 9 | )) 10 | c = int(input("What day of the month were you born in ? ")) 11 | birthday = datetime.date(a, b, c) 12 | today = datetime.date.today() 13 | days_alive = today - birthday 14 | print(" You have been alive for " + str(days_alive)) 15 | -------------------------------------------------------------------------------- /Projects/days_alive.py: -------------------------------------------------------------------------------- 1 | # This program calculates the number of days an individual has been alive for 2 | 3 | import datetime 4 | 5 | a = int(input("What year were you born ? ")) 6 | b = int( 7 | input( 8 | "What month were you born(Number format where January is 1 and December is 12) ? " 9 | )) 10 | c = int(input("What day of the month were you born in ? ")) 11 | birthday = datetime.date(a, b, c) 12 | today = datetime.date.today() 13 | days_alive = today - birthday 14 | print(" You have been alive for " + str(days_alive)) 15 | -------------------------------------------------------------------------------- /Projects/dice_roll.py: -------------------------------------------------------------------------------- 1 | # import random module - 2 | import random 3 | 4 | # make a list of numbers on the die - 5 | dice_numbers = [1, 2, 3, 4, 5, 6] 6 | 7 | # initialize user_input to 1 8 | user_input = 1 9 | 10 | # continue to "roll" die until user wants to stop - 11 | while(user_input == 1): 12 | print(random.choice(dice_numbers)) # print a random number from the list dice_numbers 13 | user_input = int(input("Enter 1 to continue, 0 to stop: ")) # take user input i.e. whether he wants to continue or stop 14 | -------------------------------------------------------------------------------- /Projects/game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def guess(x): 5 | random_number = random.randint(1, x) 6 | guess = 0 7 | while guess != random_number: 8 | guess = int(input(f"Enter your number between 1 and {x}\n")) 9 | if guess > x: 10 | print("Please,enter the number within the limits") 11 | if guess < random_number: 12 | print("Sorry, try again. Too low") 13 | elif guess < random_number: 14 | print("Sorry, try again. Too high") 15 | print(f'Congrats, you guessed it right. The number is {random_number}') 16 | 17 | 18 | guess(10) 19 | -------------------------------------------------------------------------------- /Projects/guess_num.py: -------------------------------------------------------------------------------- 1 | # Guessing game - 2 | 3 | # importing random module - 4 | import random 5 | 6 | print("Welcome to the guess-the-number game!!") 7 | print("You have 10 chances to begin with!") 8 | 9 | 10 | # function which implements the game - 11 | def guess_num(): 12 | # random number from 1 to 100 is stored - 13 | random_num = random.randint(1, 100) 14 | # choices variable is set to 10 - 15 | chances = 10 16 | # guess variable is set to 0 - 17 | guess = 0 18 | while guess != random_num or chances == 0: 19 | guess = int(input("Guess a number between 1 and 100: ")) 20 | if guess > random_num: 21 | print("Nope! Guessed number is too high!") 22 | chances -= 1 23 | print("You have " + str(chances) + " chance(s) left!") 24 | elif guess < random_num: 25 | print("Nope! Guessed number is too low!") 26 | chances -= 1 27 | print("You have " + str(chances) + " chance(s) left!") 28 | else: 29 | print("Yay!! You guessed the number correctly!!") 30 | 31 | 32 | guess_num() 33 | -------------------------------------------------------------------------------- /Projects/image_to_ascii.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from PIL import Image 3 | 4 | i_path = sys.argv[1] 5 | img = Image.open(i_path) 6 | width, height = img.size 7 | aspect_ratio = height / width 8 | nwidth = 120 9 | nheight = aspect_ratio * nwidth * 0.55 10 | img = img.resize((nwidth, int(nheight))) 11 | # converts image to greyscale 12 | img = img.convert('L') 13 | pixels = img.getdata() 14 | # replace pixels according to how dark they are 15 | chars = ["B", "S", "#", "&", "@", "$", "%", "*", "!", ":", "."] 16 | npixels = [chars[pixel // 25] for pixel in pixels] 17 | npixels = ''.join(npixels) 18 | npixels_count = len(npixels) 19 | ascii_image = [ 20 | npixels[index:index + nwidth] for index in range(0, npixels_count, nwidth) 21 | ] 22 | ascii_image = "\n".join(ascii_image) 23 | print(ascii_image) 24 | with open("ascii_image.txt", "w") as f: 25 | f.write(ascii_image) 26 | -------------------------------------------------------------------------------- /Projects/leap_year.py: -------------------------------------------------------------------------------- 1 | def leap_check(year) -> str: 2 | """ Check if a year is a leap year """ 3 | if ((year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0)): 4 | return f"{year} is a leap year!" 5 | else: 6 | return f"{year} is not a leap year!" 7 | #==================== 8 | # MAIN PROGRAM 9 | print("<-- Leap Year Checker -->") 10 | print("This program will check if a year you input is a leap year") 11 | print("\n") 12 | 13 | run = 'Y' 14 | while run == 'Y': #runs once before user intervention 15 | try: 16 | input_year = int(input("Enter a year\n\t--> ")) 17 | except ValueError: 18 | input_year = int(input("Must be an integer!\n\t--> ")) 19 | print(leap_check(input_year)) 20 | 21 | print("-" * 30) #decoration 22 | 23 | print("Would you like to check another year?\n\t[Y] Yes\n\t[N] No") 24 | run = input("\t--> ").upper() 25 | while run not in ['Y','Yes','N','No']: #input validation 26 | run = input("\t--> ").upper() 27 | 28 | print("-" * 30)l 29 | -------------------------------------------------------------------------------- /Projects/madlibs.py: -------------------------------------------------------------------------------- 1 | # program to generate a madlibs game - 2 | # function which returns noun - 3 | def ret_noun(): 4 | noun = input("Enter noun: ") 5 | return noun 6 | 7 | # function which returns verb - 8 | def ret_verb(): 9 | verb = input("Enter verb: ") 10 | return verb 11 | 12 | # function which returns adjective - 13 | def ret_adj(): 14 | adj = input("Enter adjective: ") 15 | return adj 16 | 17 | name = ret_noun() 18 | verb = ret_verb() 19 | grade = ret_noun() 20 | name1 = ret_noun() 21 | food = ret_noun() 22 | adj = ret_adj() 23 | game = ret_noun() 24 | ani = ret_noun() 25 | 26 | # to print the madlibs using words from user input - 27 | print(f"Hi! My name is {name}! I am in grade {grade}. My teacher's name is {name1}. My favorite thing to do in school is {verb}. I like to eat {food}. I like to help my mom who is very {adj}. I also like to play {game}.I have a pet {ani}, which I love very much!") -------------------------------------------------------------------------------- /Projects/password_generator_1.py: -------------------------------------------------------------------------------- 1 | import random 2 | import string 3 | 4 | word_list = [] 5 | letters_l = [ 6 | 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 7 | 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' 8 | ] 9 | letters_u = [ 10 | 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 11 | 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' 12 | ] 13 | numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9'] 14 | special_signs = ['-', '_', '#', '$', '&', '*', '@'] 15 | animals = ["ponies", "elephants", "unicorns", "tiger", "lion", "dog", "cat"] 16 | 17 | letter_1 = random.choice(letters_l) 18 | num = random.choice(numbers) 19 | sign = random.choice(special_signs) 20 | ani = random.choice(animals) 21 | letter_2 = random.choice(letters_u) 22 | 23 | password = letter_1 + num + sign + ani.capitalize() + letter_2 24 | print(password) 25 | -------------------------------------------------------------------------------- /Projects/phone_nums.py: -------------------------------------------------------------------------------- 1 | # create an empty dictionary - 2 | phone_nums_dict = {} 3 | 4 | 5 | # function to add/update number to the list(dictionary) - 6 | def add_num(name, num): 7 | name.capitalize() 8 | # if statement checks if the number entered is numeric and 10 digits long - 9 | if (num.isnumeric() and num.__len__() == 10): 10 | phone_nums_dict.update({name: num}) 11 | print("Entry added to contact list!") 12 | else: 13 | print("You have entered the number incorrectly!") 14 | 15 | 16 | # function to search for a number using a specific name - 17 | def search(name): 18 | if (name in phone_nums_dict): 19 | print(phone_nums_dict[name]) 20 | else: 21 | print("Name and number not found!") 22 | 23 | 24 | # function to display the dictionary - 25 | def display_list(): 26 | print(phone_nums_dict) 27 | 28 | 29 | choice = 1 30 | while (choice == 1): 31 | user_input_choice = int( 32 | input( 33 | "Enter 1 to add/update number, 2 to search for a number, 3 to display list: " 34 | )) 35 | if (user_input_choice == 1): 36 | user_input_name = input("Enter name: ").capitalize() 37 | user_input_num = input("Enter number: ") 38 | add_num(user_input_name, user_input_num) 39 | elif (user_input_choice == 2): 40 | user_input_name = input("Enter name to search: ").capitalize() 41 | search(user_input_name) 42 | elif (user_input_choice == 3): 43 | display_list() 44 | else: 45 | print("Invalid input!") 46 | choice = int(input("Do you want to continue? (1: continue/0: stop): ")) 47 | -------------------------------------------------------------------------------- /Projects/qr_generator.py: -------------------------------------------------------------------------------- 1 | #importing module which needs to be installed,it does not come pre installed with python 2 | import pyqrcode 3 | 4 | # get user input to create a QR Code. 5 | data = input("Enter the text or link to generate QR code: ") 6 | 7 | # creating QR Code 8 | qr = pyqrcode.create(data) 9 | 10 | # qr code is not diectly visible,exporting it into a file,keeping scale parameter 8 11 | qr.svg('qr_code.svg', scale=8) 12 | -------------------------------------------------------------------------------- /Projects/queue-demo.py: -------------------------------------------------------------------------------- 1 | # Program to implement queue data structure in python - 2 | class queue: 3 | # Constructor to initialize a queue 4 | def __init__(self): 5 | self.items = [] 6 | 7 | # Function to enqueue elements - 8 | def enqueue(self, item): 9 | self.items.insert(item) 10 | 11 | # Function to dequeue elements - 12 | def dequeue(self): 13 | return self.items.pop() 14 | 15 | 16 | # Function to enqueue element 17 | def enqueue(my_queue): 18 | item = int(input("Enter element to enqueue: ")) 19 | my_queue.append(item) 20 | 21 | 22 | # Function to dequeue element 23 | def dequeue(my_queue): 24 | print("Dequeued element: " + str(my_queue[0])) 25 | my_queue.pop(0) 26 | 27 | 28 | # Function to display elements in a queue 29 | def display(my_queue): 30 | print(my_queue) 31 | 32 | 33 | switcher = {1: enqueue, 2: dequeue, 3: display} 34 | 35 | 36 | # Function for performing operations on queue 37 | def queue(my_queue): 38 | argument = eval( 39 | input( 40 | "Enter 1 to enqueue, 2 to dequeue, 3 to display queue, 4 to exit: " 41 | )) 42 | op = switcher.get(argument) 43 | 44 | while (argument != 4): 45 | op(my_queue) 46 | argument = eval( 47 | input( 48 | "Enter 1 to enqueue, 2 to dequeue, 3 to display queue, 4 to exit: " 49 | )) 50 | op = switcher.get(argument) 51 | 52 | 53 | # Create empty queue 54 | my_queue = [] 55 | # Perform operations on queue 56 | queue(my_queue) 57 | -------------------------------------------------------------------------------- /Projects/queue_1.py: -------------------------------------------------------------------------------- 1 | # Initialize an empty list - 2 | my_queue = [] 3 | 4 | # Function to enqueue element 5 | def enqueue(my_queue): 6 | item = int(input("Enter element to enqueue: ")) 7 | my_queue.append(item) 8 | 9 | # Function to dequeue element 10 | def dequeue(my_queue): 11 | print("Dequeued element: " + str(my_queue[0])) 12 | my_queue.pop(0) 13 | 14 | # Function to display elements in a queue 15 | def display(my_queue): 16 | print(my_queue) 17 | 18 | 19 | switcher = { 20 | 1: enqueue, 21 | 2: dequeue, 22 | 3: display 23 | } 24 | 25 | # Function for performing operations on queue 26 | def queue(my_queue): 27 | argument = eval(input("Enter 1 to enqueue, 2 to dequeue, 3 to display queue, 4 to exit: ")) 28 | op = switcher.get(argument) 29 | 30 | while (argument != 4): 31 | op(my_queue) 32 | argument = eval(input("Enter 1 to enqueue, 2 to dequeue, 3 to display queue, 4 to exit: ")) 33 | op = switcher.get(argument) 34 | 35 | # Create empty queue 36 | my_queue = [] 37 | # Perform operations on queue 38 | queue(my_queue) -------------------------------------------------------------------------------- /Projects/rps.py: -------------------------------------------------------------------------------- 1 | from os import system 2 | import random 3 | 4 | def play(): 5 | system('cls'); 6 | alpha = 0 7 | player = 0 8 | d = 0 9 | while(d == 0): 10 | player = int(input("\n1. ROCK \n2. PAPER \n3. SCISSORS \n4. End Game \nEnter Your Choice: \n")) 11 | if(player == 1 or player == 2 or player == 3 or player == 4): 12 | alpha = random.randint(1,3) 13 | if(alpha == 1 and player == 1): 14 | print("\nALPHA: Rock\nYou: Rock\nTIE\n") 15 | elif(alpha == 2 and player == 2): 16 | print("\nALPHA: Paper\nYou: Paper\nTIE\n") 17 | elif(alpha == 3 and player == 3): 18 | print("\nALPHA: Scissors\nYou: Scissors\nTIE\n") 19 | elif(alpha == 2 and player == 1): 20 | print("\nALPHA: Paper\nYou: Rock\nALPHA WON!!\n") 21 | elif(alpha == 3 and player == 2): 22 | print("\nALPHA: Scissors\nYou: Paper\nALPHA WON!!\n") 23 | elif(alpha == 1 and player == 3): 24 | print("\nALPHA: Rock\nYou: Scissors\nALPHA WON!!\n") 25 | elif(alpha == 2 and player == 3): 26 | print("\nALPHA: Paper\nYou: Scissors\nYOU WON!!\n") 27 | elif(alpha == 3 and player == 1): 28 | print("\nALPHA: Scissors\nYou: Rock\nYOU WON!!\n") 29 | elif(alpha == 1 and player == 2): 30 | print("\nALPHA: Rock\nYou: Paper\nYOU WON!!\n") 31 | elif(player == 4): 32 | d = 1 33 | self_exit() 34 | else: 35 | print("\nInvalid Input!!\n") 36 | 37 | def how(): 38 | system('cls') 39 | print("\n\nHow to Play\n\nWhen its time to play, you and ALPHA will each form one of the three objects either rock, paper or scissors. You will then name a winner based on which object you both played.\nFor instance, rock crushes scissors but is covered by paper, paper covers rock but is cut by scissors, and scissors is crushed by rock but cuts paper. The player who picks the stronger of the two objects is the winner.\n") 40 | enter = int(input("\nPress any number to go Back: \n")) 41 | main() 42 | 43 | def about(): 44 | system('cls') 45 | print("\n\nAbout\n\nRock, Paper, Scissors (aka \"Ro-Sham-Bo\"; janken; \"Bato, Bato, Pick\"; and \"Scissors, Paper, Stone\") is a simple hand game with many names and variations. It is played around the world and is commonly used as a way of coming to decisions. In some cases is even played for sport.\nThis is a Basic Rock, Paper and Scissors Game Program in Python.\nGame Developed by sachinl0har.\n\n@copyrights All Rights Reserved\n") 46 | enter = int(input("\nPress any number to go Back: \n")) 47 | main() 48 | 49 | def self_exit(): 50 | system('cls') 51 | print("\n\nThanks For Playing\n\n") 52 | exit() 53 | 54 | def main(): 55 | system('cls'); 56 | x = int(input("1. Play Game \n2. How to play? \n3. About \n4. Exit \nEnter your choice: \n")) 57 | switcher = { 58 | 1: play, 59 | 2: how, 60 | 3: about, 61 | 4: self_exit 62 | } 63 | return switcher.get(x)() 64 | 65 | main() 66 | -------------------------------------------------------------------------------- /Projects/snake_game.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import random 3 | # initializing pygame 4 | pygame.init() 5 | 6 | # Colors 7 | white = (255, 255, 255) # rgb format 8 | red = (255, 0, 0) 9 | black = (0, 0, 0) 10 | 11 | # Creating window 12 | screen_width = 900 13 | screen_height = 600 14 | gameWindow = pygame.display.set_mode((screen_width, screen_height)) 15 | 16 | # Game Title 17 | pygame.display.set_caption("Coders Home") 18 | pygame.display.update() 19 | clock = pygame.time.Clock() 20 | font = pygame.font.SysFont(None, 55) 21 | 22 | def text_screen(text, color, x, y): 23 | screen_text = font.render(text, True, color) 24 | gameWindow.blit(screen_text, [x,y]) 25 | 26 | 27 | def plot_snake(gameWindow, color, snk_list, snake_size): 28 | for x,y in snk_list: 29 | pygame.draw.rect(gameWindow, color, [x, y, snake_size, snake_size]) 30 | 31 | # Game Loop 32 | def gameloop(): 33 | exit_game = False 34 | game_over = False 35 | snake_x = 45 36 | snake_y = 55 37 | velocity_x = 0 38 | velocity_y = 0 39 | snk_list = [] 40 | snk_length = 1 41 | 42 | food_x = random.randint(20, screen_width-20) 43 | food_y = random.randint(60, screen_height -20) 44 | score = 0 45 | init_velocity = 4 46 | snake_size = 30 47 | fps = 60 # fps = frames per second 48 | while not exit_game: 49 | if game_over: 50 | gameWindow.fill(white) 51 | text_screen("Game Over! Press Enter To Continue", red, 100, 250) 52 | 53 | for event in pygame.event.get(): 54 | if event.type == pygame.QUIT: 55 | exit_game = True 56 | 57 | if event.type == pygame.KEYDOWN: 58 | if event.key == pygame.K_RETURN: 59 | gameloop() 60 | 61 | else: 62 | 63 | for event in pygame.event.get(): 64 | if event.type == pygame.QUIT: 65 | exit_game = True 66 | 67 | if event.type == pygame.KEYDOWN: 68 | if event.key == pygame.K_RIGHT: 69 | velocity_x = init_velocity 70 | velocity_y = 0 71 | 72 | if event.key == pygame.K_LEFT: 73 | velocity_x = - init_velocity 74 | velocity_y = 0 75 | 76 | if event.key == pygame.K_UP: 77 | velocity_y = - init_velocity 78 | velocity_x = 0 79 | 80 | if event.key == pygame.K_DOWN: 81 | velocity_y = init_velocity 82 | velocity_x = 0 83 | 84 | snake_x = snake_x + velocity_x 85 | snake_y = snake_y + velocity_y 86 | 87 | if abs(snake_x - food_x)<10 and abs(snake_y - food_y)<10: 88 | score +=1S 89 | food_x = random.randint(20, screen_width - 30) 90 | food_y = random.randint(60, screen_height - 30) 91 | snk_length +=5 92 | 93 | gameWindow.fill(white) 94 | text_screen("Score: " + str(score * 10), red, 5, 5) 95 | pygame.draw.rect(gameWindow, red, [food_x, food_y, snake_size, snake_size]) 96 | pygame.draw.line(gameWindow, red, (0,40), (900,40),5) 97 | 98 | head = [] 99 | head.append(snake_x) 100 | head.append(snake_y) 101 | snk_list.append(head) 102 | 103 | if len(snk_list)>snk_length: 104 | del snk_list[0] 105 | 106 | if head in snk_list[:-1]: 107 | game_over = True 108 | 109 | if snake_x<0 or snake_x>screen_width-20 or snake_y<50 or snake_y>screen_height-20: 110 | game_over = True 111 | plot_snake(gameWindow, black, snk_list, snake_size) 112 | pygame.display.update() 113 | clock.tick(fps) 114 | pygame.quit() 115 | quit() 116 | gameloop() -------------------------------------------------------------------------------- /Projects/stopwatch.py: -------------------------------------------------------------------------------- 1 | # stopwatch.py - A stopwatch that tracks the amount of time between hits of the "Enter" key, 2 | # with each key hit starting a new “lap” on the timer and prints the lap number, total time, and lap time. 3 | # multithreading is used to display a timer whilst the stopwatch is working. 4 | 5 | import time 6 | import datetime 7 | import threading 8 | 9 | # Instructions 10 | print(" Stopwatch ".center(30, "*")) 11 | print("Hit \"Enter\" to begin the program.") 12 | input() 13 | print("Program is already running.") 14 | print("Hit \"Enter\" again to create laps.") 15 | print("Press 'Ctrl' + 'C' to end the program.") 16 | 17 | 18 | # Count up timer function. 19 | def countUp(): 20 | """A count up timer which would be displayed while the stopwatch is ongoing.""" 21 | second = 1 22 | 23 | try: 24 | while True: 25 | time.sleep(1) 26 | print(datetime.timedelta(seconds=second), end="\r") 27 | second += 1 28 | except KeyboardInterrupt: 29 | pass 30 | 31 | 32 | # Stopwatch function. 33 | def stopwatch(): 34 | """Displays laps when the user presses the 'Enter' button.""" 35 | 36 | startTime = time.time() 37 | lastTime = startTime 38 | lapNum = 1 39 | 40 | try: 41 | while True: 42 | input() 43 | lapTime = round(time.time() - lastTime, 2) 44 | totalTime = round(time.time() - startTime, 2) 45 | print('Lap #%s: %s (%s)' % (lapNum, totalTime, lapTime)) 46 | print() 47 | lapNum += 1 48 | lastTime = time.time() # reset the last lap time 49 | except EOFError: 50 | print("\nDone.") 51 | 52 | 53 | # Calling the functions. 54 | threadObj = threading.Thread(target=stopwatch) # Creating a multithreading object whose target is stopWatch(). 55 | threadObj.start() # Start the stopWatch() function. 56 | countUp() 57 | -------------------------------------------------------------------------------- /Projects/tkinter_Calc.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import math 3 | 4 | wind = Tk() 5 | wind.geometry("270x430") 6 | # wind.resizable(0,0) 7 | wind.title("Basic Calculator") 8 | 9 | text = Entry(wind, font=("arial", 16)) 10 | text.pack(fill=X, padx=5, pady=5, ipady=5) 11 | 12 | 13 | def addToText(n): 14 | text.insert(END, n) 15 | 16 | 17 | def calculate(): 18 | result = eval(text.get()) 19 | text.delete(0, END) 20 | text.insert(0, result) 21 | 22 | 23 | def button_clear(): 24 | text.delete(0, END) 25 | 26 | 27 | frame = Frame(wind) 28 | frame.pack(side=TOP, anchor=NW) 29 | 30 | rightFrame = Frame(frame) 31 | rightFrame.pack(side=RIGHT) 32 | 33 | frame1 = Frame(frame) 34 | frame1.pack() 35 | 36 | #btn 1 to 3 37 | btn1 = Button(frame1, 38 | text="1", 39 | fg='black', 40 | bg='#696969', 41 | width=9, 42 | height=4, 43 | command=lambda: addToText("1")) 44 | btn1.pack(side=LEFT) 45 | btn2 = Button(frame1, 46 | text="2", 47 | fg='black', 48 | bg='#696969', 49 | width=9, 50 | height=4, 51 | command=lambda: addToText("2")) 52 | btn2.pack(side=LEFT) 53 | btn3 = Button(frame1, 54 | text="3", 55 | fg='black', 56 | bg='#696969', 57 | width=9, 58 | height=4, 59 | command=lambda: addToText("3")) 60 | btn3.pack(side=LEFT) 61 | 62 | frame2 = Frame(frame) 63 | frame2.pack() 64 | 65 | #btn 4 to 6 66 | btn4 = Button(frame2, 67 | text="4", 68 | fg='black', 69 | bg='#696969', 70 | width=9, 71 | height=4, 72 | command=lambda: addToText("4")) 73 | btn4.pack(side=LEFT) 74 | btn5 = Button(frame2, 75 | text="5", 76 | fg='black', 77 | bg='#696969', 78 | width=9, 79 | height=4, 80 | command=lambda: addToText("5")) 81 | btn5.pack(side=LEFT) 82 | btn6 = Button(frame2, 83 | text="6", 84 | fg='black', 85 | bg='#696969', 86 | width=9, 87 | height=4, 88 | command=lambda: addToText("6")) 89 | btn6.pack(side=LEFT) 90 | 91 | frame3 = Frame(frame) 92 | frame3.pack() 93 | 94 | #btn 7 to 9 95 | btn7 = Button(frame3, 96 | text="7", 97 | fg='black', 98 | bg='#696969', 99 | width=9, 100 | height=4, 101 | command=lambda: addToText("7")) 102 | btn7.pack(side=LEFT) 103 | btn8 = Button(frame3, 104 | text="8", 105 | fg='black', 106 | bg='#696969', 107 | width=9, 108 | height=4, 109 | command=lambda: addToText("8")) 110 | btn8.pack(side=LEFT) 111 | btn9 = Button(frame3, 112 | text="9", 113 | fg='black', 114 | bg='#696969', 115 | width=9, 116 | height=4, 117 | command=lambda: addToText("9")) 118 | btn9.pack(side=LEFT) 119 | 120 | frame4 = Frame(frame) 121 | frame4.pack() 122 | 123 | #btn . 0 = 124 | btnpoint = Button(frame4, 125 | text=".", 126 | fg='black', 127 | bg='#696969', 128 | width=9, 129 | height=4, 130 | command=lambda: addToText(".")) 131 | btnpoint.pack(side=LEFT) 132 | btnzero = Button(frame4, 133 | text="0", 134 | fg='black', 135 | bg='#696969', 136 | width=9, 137 | height=4, 138 | command=lambda: addToText("0")) 139 | btnzero.pack(side=LEFT) 140 | btneq = Button(frame4, 141 | text="=", 142 | fg='black', 143 | bg='#696969', 144 | width=9, 145 | height=4, 146 | command=lambda: calculate()) 147 | btneq.pack(side=LEFT) 148 | 149 | #operators 150 | btndiv = Button(rightFrame, 151 | text="/", 152 | fg='black', 153 | bg='#696969', 154 | width=6, 155 | height=4, 156 | command=lambda: addToText("/")) 157 | btndiv.pack() 158 | btnmul = Button(rightFrame, 159 | text="x", 160 | fg='black', 161 | bg='#696969', 162 | width=6, 163 | height=4, 164 | command=lambda: addToText("*")) 165 | btnmul.pack() 166 | btndif = Button(rightFrame, 167 | text="-", 168 | fg='black', 169 | bg='#696969', 170 | width=6, 171 | height=4, 172 | command=lambda: addToText("-")) 173 | btndif.pack() 174 | btnplus = Button(rightFrame, 175 | text="+", 176 | fg='black', 177 | bg='#696969', 178 | width=6, 179 | height=4, 180 | command=lambda: addToText("+")) 181 | btnplus.pack() 182 | btnplus = Button(rightFrame, 183 | text="%", 184 | fg='black', 185 | bg='#696969', 186 | width=6, 187 | height=4, 188 | command=lambda: addToText("%")) 189 | btnplus.pack() 190 | 191 | frame5 = Frame(frame) 192 | frame5.pack() 193 | 194 | btnclear = Button(frame5, 195 | text="C", 196 | fg='black', 197 | bg='#696969', 198 | width=30, 199 | height=4, 200 | command=lambda: button_clear()) 201 | btnclear.pack() 202 | 203 | wind.mainloop() 204 | -------------------------------------------------------------------------------- /Projects/tkinter_Digital_Clock.py: -------------------------------------------------------------------------------- 1 | import time 2 | from tkinter import * 3 | 4 | root = Tk() 5 | root.geometry('450x100') 6 | root.title('DIGITAL CLOCK') 7 | 8 | 9 | def clocktime(time1=''): 10 | time2 = time.strftime('%H:%M:%S') 11 | if time2 != time1: 12 | time1 = time2 13 | clock.config(text=time2) 14 | 15 | clock.after(1000, clocktime) 16 | 17 | 18 | clock = Label(root, 19 | font='verdana 55 bold', 20 | background='black', 21 | foreground='green') 22 | clock.pack(fill='both', expand=1) 23 | clocktime() 24 | root.mainloop() 25 | -------------------------------------------------------------------------------- /Projects/tkinter_calc.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/tkinter_calc.PNG -------------------------------------------------------------------------------- /Projects/tkinter_digital_clock.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/PrajaktaSathe/Python/58e46fa0c307c63c131b61fbea04f9069fed6804/Projects/tkinter_digital_clock.PNG -------------------------------------------------------------------------------- /Projects/username_generator.py: -------------------------------------------------------------------------------- 1 | ch = int( 2 | input( 3 | "Do you want to generate a username with your name (1) or username without your name (2): " 4 | )) 5 | vowels = ['a', 'e', 'i', 'o', 'u'] 6 | if ch == 1: 7 | name = input("Enter name/nickname: ").lower() 8 | lastn = input("Enter last name: ").lower() 9 | bday = input("Enter birth-date (only day): ") 10 | pwd = "" 11 | for l in name: 12 | # if l in vowels: 13 | # l = l.capitalize() 14 | pwd += l 15 | pwd = pwd + "_" 16 | for l in lastn: 17 | # if l in vowels: 18 | # l = l.capitalize() 19 | pwd += l 20 | pwd = pwd + "_" + bday 21 | print(pwd) 22 | elif ch == 2: 23 | fav_adj = input("Enter adjective: ").lower() 24 | fav_animal = input( 25 | "Enter your favourite animal/cartoon/character: ").lower() 26 | fav_num = input("Enter your favourite number: ") 27 | pwd = fav_adj + "_" + fav_animal + "_" + fav_num 28 | print(pwd) 29 | else: 30 | print("Invalid input!") 31 | --------------------------------------------------------------------------------