Repository: king04aman/All-In-One-Python-Projects Branch: main Commit: 5675c6daa7f7 Files: 227 Total size: 284.9 KB Directory structure: gitextract_lpystzk0/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── PROJECT_SUGGESTION_TEMPLATE.md │ │ ├── bug_report.md │ │ ├── config.yml │ │ ├── feature_request.md │ │ └── other_issue.md │ ├── PROJECT_SUGGESTION_TEMPLATE.md │ ├── pull_request_template.md │ └── workflows/ │ ├── generate-project-list.yml │ └── welcome.yml ├── Age Calculator/ │ ├── calculate.py │ └── runtime.txt ├── Alarm Bot/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Ascii Art Generator/ │ ├── generate.py │ ├── requirements.txt │ └── runtime.txt ├── Audio Book Generator/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── CountDown Timer/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Currency Converter/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Custom GPT/ │ ├── README.md │ ├── data/ │ │ └── data.txt │ ├── example-env │ └── main.py ├── Customizable_Workout_Playlist_Generator/ │ ├── README_SONG.md │ ├── hiit_playlist.json │ ├── playlist.py │ └── requirements.txt ├── Digital Clock/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Example README.md ├── Expense Splitter/ │ ├── README.md │ ├── main.py │ └── runtme.txt ├── Extractive Text Summarization/ │ ├── readme.md │ ├── requirements.txt │ └── summary.py ├── Facebook Video Downloader/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Gauss Elimination with Partial Pivoting/ │ ├── README.md │ ├── main.py │ └── runtime.txt ├── Geographic Distance/ │ ├── README.md │ ├── geographic_distance.py │ ├── requirements.txt │ ├── runtime.txt │ └── test_geographic_distance.py ├── Gesture-Based-Game-Controller/ │ ├── main.py │ ├── readme.md │ ├── requirements.txt │ └── runtime.txt ├── Handwritten-Assignments/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Headlight Detection/ │ ├── headlightDetection.py │ ├── requirements.txt │ └── runtime.txt ├── Helmet Detection/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Image Compression/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── ImageSize Reducer/ │ ├── reduce.py │ ├── requirements.txt │ └── runtime.txt ├── Img-Steganograpy/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── LICENSE ├── Learn-FastAPI/ │ ├── FastAPI-CURD.py │ ├── FastAPI-Tutorial.py │ └── README.md ├── Mental Health chatbot/ │ ├── Mental_health_bot.py │ ├── README_BOT.md │ └── requirements.txt ├── Merge PDFs/ │ ├── merge.py │ ├── requirements.txt │ └── runtime.txt ├── MobileNumber Tracker/ │ ├── requirements.txt │ ├── runtime.txt │ └── track.py ├── Mood Based Music Recommender/ │ ├── Emosic-Spoti.py │ ├── README.md │ └── requirement.txt ├── Movie Scraper/ │ ├── requirements.txt │ ├── runtime.txt │ └── scrape.py ├── My-Personal-Journal/ │ ├── README.md │ ├── app.py │ ├── database.py │ ├── journal_app.py │ ├── requirements.txt │ ├── static/ │ │ └── style.css │ ├── templates/ │ │ ├── add.html │ │ ├── index.html │ │ ├── search.html │ │ ├── search_results.html │ │ └── tags.html │ └── ui.py ├── Notepad/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── OCR Image-to-Text Conversion/ │ ├── README.md │ ├── main.py │ └── requirements.txt ├── PROJECTS.md ├── Password Generator/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Plagiarism-Checker/ │ ├── main.py │ ├── requirements.txt │ ├── runtime.txt │ ├── test1.txt │ └── test2.txt ├── Pomodoro Timer/ │ ├── README.md │ ├── main.py │ └── runtime.txt ├── QR Code Generator/ │ ├── advanceQrGenerator.py │ ├── basicQrGenerator.py │ ├── requirements.txt │ └── runtime.txt ├── README.md ├── Random Movie Selector/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Random Quotes Generator/ │ ├── quotes.py │ ├── requirements.txt │ └── runtime.txt ├── Real-Time Cryptocurrency Price Tracker/ │ ├── Readme.md │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Recipe Finder with Meal Planner/ │ ├── Readme.md │ ├── main.py │ └── runtime.txt ├── Resume Builder/ │ ├── README.md │ ├── requirements.txt │ └── resume_builder.py ├── Simple Assistant/ │ ├── assistant.py │ ├── raj_mistry01/ │ │ ├── Readme.md │ │ ├── main.py │ │ └── requirements.txt │ ├── requirements.txt │ └── runtime.txt ├── Snake-Game/ │ ├── README.md │ ├── Snake.py │ ├── data.py │ ├── data.txt │ ├── food.py │ ├── main.py │ └── scoreboard.py ├── Speech To Text/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Spell Checker/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Telegram Bot/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Text Summarizer/ │ ├── README.md │ ├── requirements.txt │ ├── runtime.txt │ ├── sample.csv │ └── text_summarizer.py ├── Text To Speech/ │ ├── README.md │ ├── requirements.txt │ ├── runtime.txt │ └── text_to_speech.py ├── Text to Morse Code/ │ ├── main.py │ └── runtime.txt ├── Text_Adventure_Game/ │ ├── readme.md │ └── text_adventure_game.py ├── Tic-Tac-Toc using AI (min-max)/ │ ├── README.md │ ├── requirements.txt │ └── tic_tac_toc.py ├── To Do List/ │ ├── README.md │ ├── RithwikBejadi/ │ │ └── To Do App/ │ │ ├── README.md │ │ ├── To_Do_AppTkInter.py │ │ ├── requirements.txt │ │ └── runtime.txt │ ├── main.py │ ├── requirement.txt │ └── runtime.txt ├── Translator/ │ ├── requirements.txt │ ├── runtime.txt │ └── translate.py ├── URL Sortener/ │ ├── main.py │ ├── requirements.txt │ └── runtime.txt ├── Validate-Email/ │ ├── runtime.txt │ └── validate.py ├── Video Processor/ │ ├── README.md │ ├── requirements.txt │ └── video_processor.py ├── Video To Audio/ │ ├── main.py │ ├── requirement.txt │ └── runtime.txt ├── Weather Alert/ │ ├── README.md │ ├── main.py │ ├── requirement.txt │ └── runtime.txt ├── Word_frequency_counter/ │ ├── README.md │ ├── main.py │ ├── requirments.txt │ └── runtime.txt ├── Youtube Video Downloader/ │ ├── Readme.md │ ├── main.py │ ├── requirements.txt │ └── runtime.txt └── personal-finance-tracker/ ├── README.md ├── database.py ├── main.py ├── savings.py ├── tracker.py └── visualization.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/PROJECT_SUGGESTION_TEMPLATE.md ================================================ --- name: Project Suggestion about: Propose an idea for a new project title: "" labels: "Project Suggestion" assignees: "" --- ### Project Suggestion Title _A concise title for your project suggestion._ ### Description _Provide a detailed description of the project idea or feature you would like to propose._ ### Benefits _Explain how this project or feature would benefit the community or improve the existing repository._ ### Implementation Ideas _Offer any initial thoughts on how the project could be implemented, including potential technologies or approaches._ ### Additional Context _Include any other relevant information, links, or references that might help._ ### Suggested Contributors _If you have specific contributors in mind who might be interested in this project, please list them here._ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: "Bug Report" about: "Report a bug or issue." title: "Bug Report Title" labels: ["bug", "help wanted"] --- ## Description Please describe the bug you encountered, including steps to reproduce it. ## Steps to Reproduce 1. Step 1 2. Step 2 3. Step 3 ... ## Expected Behavior What did you expect to happen? ## Actual Behavior What actually happened? ## Additional Context Add any other context about the problem, screenshots, or logs that might be helpful. ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact: false templates: - name: "Project Suggestion" description: "Propose an idea for a new project." title: "Project Suggestion Title" labels: ["Project Suggestion"] - name: "Bug Report" description: "Report a bug or issue." title: "Bug Report Title" labels: ["bug", "help wanted"] - name: "Feature Request" description: "Request a new feature or enhancement." title: "Feature Request Title" labels: ["feature", "enhancement"] - name: "Other" description: "Use this template for any other issues or inquiries." title: "Other Issue Title" labels: ["question", "others"] choose_template: title: "Choose an Issue Template" description: "Please select one of the templates below to create your issue." ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: "Feature Request" about: "Request a new feature or enhancement." title: "Feature Request Title" labels: ["feature", "enhancement"] --- ## Feature Description Please describe the feature you would like to request. ## Use Cases How will this feature be used? Please provide examples. ## Additional Context Add any other context about the feature request, including design ideas or potential impacts. ================================================ FILE: .github/ISSUE_TEMPLATE/other_issue.md ================================================ --- name: "Other" about: "Use this template for any other issues or inquiries." title: "Other Issue Title" labels: ["question", "other"] --- ## Description Please provide a detailed description of your inquiry or issue. ## Context Add any relevant context or background information that may help in addressing your request. ## Additional Information If applicable, include any additional information, screenshots, or references. ================================================ FILE: .github/PROJECT_SUGGESTION_TEMPLATE.md ================================================ ### Project Suggestion Title _A concise title for your project suggestion._ ### Description _Provide a detailed description of the project idea or feature you would like to propose._ ### Benefits _Explain how this project or feature would benefit the community or improve the existing repository._ ### Implementation Ideas _Offer any initial thoughts on how the project could be implemented, including potential technologies or approaches._ ### Additional Context _Include any other relevant information, links, or references that might help._ ### Suggested Contributors _If you have specific contributors in mind who might be interested in this project, please list them here._ ================================================ FILE: .github/pull_request_template.md ================================================ ### Developer Checklist - [ ] Adhered to the guidelines outlined in the README & Contributing file. - [ ] Maintained the correct directory structure (e.g., ProjectName/...yourfiles). - [ ] Please ensure to include a README file for enhanced project clarity. - [ ] Starred ⭐ the repository (optional). ### Summary ###### _Please provide a brief summary here._ ### Screenshot ###### _Attach any relevant screenshots or GIFs here._ ### Live Project Link ###### _Include a link to the live project here._ ================================================ FILE: .github/workflows/generate-project-list.yml ================================================ name: Generate Project List on: push: branches: - main jobs: generate-list: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 with: token: ${{ secrets.ACTION_TOKEN }} persist-credentials: true - name: Fetch latest changes run: git fetch origin - name: Merge changes run: | git merge origin/main || echo "No new changes to merge or merge conflict" - name: Generate project list run: | exclude_dirs=(.github) exclude_files=("LICENSE" "README.md" "CONTRIBUTING.md" "Example README.md" "CODE_OF_CONDUCT.md" "PROJECTS.md") projects=() for dir in */; do if [[ ! " ${exclude_dirs[@]} " =~ " ${dir%/} " ]]; then projects+=("$dir") fi done echo "# Project List" > PROJECTS.md echo "" >> PROJECTS.md for project in "${projects[@]}"; do project_name=${project%/} safe_project_name=${project_name// /%20} echo "* [$project_name](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/$safe_project_name)" >> PROJECTS.md done for file in "${exclude_files[@]}"; do sed -i "/$file/d" PROJECTS.md done # Debug output to check the content of PROJECTS.md cat PROJECTS.md - name: Commit project list run: | git config --global user.email "github-actions[bot]@users.noreply.github.com" git config --global user.name "github-actions[bot]" git add PROJECTS.md if ! git diff --cached --exit-code; then git commit -m "Update project list" git push --force-with-lease else echo "No changes to commit." fi env: GITHUB_TOKEN: ${{ secrets.ACTION_TOKEN }} ================================================ FILE: .github/workflows/welcome.yml ================================================ name: Welcome Comments permissions: actions: write attestations: write checks: write contents: write deployments: write id-token: write issues: write discussions: write packages: write pages: write pull-requests: write repository-projects: write security-events: write statuses: write on: issues: types: [opened, closed] pull_request_target: types: [opened, closed] jobs: welcomer: runs-on: ubuntu-latest steps: - name: Auto Welcome on Issues or PRs uses: actions/github-script@v6 with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | const author = context.payload.sender.login; const commentBody = (message) => `👋 @${author} 👋\n\n${message}`; if (context.eventName === 'issues') { const issue = context.payload.issue; if (context.payload.action === 'opened') { const message = `We're thrilled to see you opening an issue! Your input is valuable to us. Don’t forget to fill out our issue template for the best experience. We will look into it soon.`; github.rest.issues.createComment({ issue_number: issue.number, owner: context.repo.owner, repo: context.repo.repo, body: commentBody(message), }); } else if (context.payload.action === 'closed') { const message = `Thanks for closing the issue! We appreciate your updates.`; github.rest.issues.createComment({ issue_number: issue.number, owner: context.repo.owner, repo: context.repo.repo, body: commentBody(message), }); } } else if (context.eventName === 'pull_request_target') { const pr = context.payload.pull_request; if (context.payload.action === 'opened') { const message = `We're delighted to have your pull request! Please take a moment to check our contributing guidelines and ensure you've filled out the PR template for a smooth process. We will review it soon.`; github.rest.issues.createComment({ issue_number: pr.number, owner: context.repo.owner, repo: context.repo.repo, body: commentBody(message), }); } else if (context.payload.action === 'closed') { const message = pr.merged ? `🎉 You've just merged your pull request! We're excited to have you in our community. Keep up the fantastic contributions to the project!` : `Thanks for closing the pull request! Your contributions are valuable to us.`; github.rest.issues.createComment({ issue_number: pr.number, owner: context.repo.owner, repo: context.repo.repo, body: commentBody(message), }); } } ================================================ FILE: Age Calculator/calculate.py ================================================ import time from calendar import isleap def judge_leap_year(year): if isleap(year): return True else: return False def month_days(month, leap_year): if month in [1, 3, 5, 7, 8, 10, 12]: return 31 elif month in [4, 6, 9, 11]: return 30 elif month == 2 and leap_year: return 29 elif month == 2 and (not leap_year): return 28 name = input("Please enter your name: ") age = input("Please enter your age: ") localtime = time.localtime(time.time()) year = int(age) month = year * 12 + localtime.tm_mon day = 0 begin_year = int(localtime.tm_year) - year end_year = begin_year + year for y in range(begin_year, end_year): if (judge_leap_year(y)): day = day + 366 else: day = day + 365 leap_year = judge_leap_year(localtime.tm_year) for m in range(1, localtime.tm_mon): day = day + month_days(m, leap_year) day = day + localtime.tm_mday print("\n\t%s's age is %d years or " % (name, year), end="") print("%d months or %d days" % (month, day)) ================================================ FILE: Age Calculator/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Alarm Bot/main.py ================================================ from tkinter import * import datetime import time import winsound from threading import * root = Tk() root.geometry("400x200") def Threading(): t1=Thread(target=alarm) t1.start() def alarm(): while True: set_alarm_time = f"{hour.get()}:{minute.get()}:{second.get()}" time.sleep(1) current_time = datetime.datetime.now().strftime("%H:%M:%S") print(current_time,set_alarm_time) if current_time == set_alarm_time: print("Time to Wake up") winsound.PlaySound("sound.wav",winsound.SND_ASYNC) Label(root,text="Alarm Clock",font=("Helvetica 20 bold"),fg="red").pack(pady=10) Label(root,text="Set Time",font=("Helvetica 15 bold")).pack() frame = Frame(root) frame.pack() hour = StringVar(root) hours = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24' ) hour.set(hours[0]) hrs = OptionMenu(frame, hour, *hours) hrs.pack(side=LEFT) minute = StringVar(root) minutes = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60') minute.set(minutes[0]) mins = OptionMenu(frame, minute, *minutes) mins.pack(side=LEFT) second = StringVar(root) seconds = ('00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60') second.set(seconds[0]) secs = OptionMenu(frame, second, *seconds) secs.pack(side=LEFT) Button(root,text="Set Alarm",font=("Helvetica 15"),command=Threading).pack(pady=20) root.mainloop() ================================================ FILE: Alarm Bot/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Ascii Art Generator/generate.py ================================================ import cv2 import numpy as np import sys symbols_list = ["#", "-", "*", ".", "+", "o"] threshold_list = [0, 50, 100, 150, 200] def print_out_ascii(array): for row in array: for e in row: print(symbols_list[int(e) % len(symbols_list)], end="") print() def img_to_ascii(image): height, width = image.shape new_width = int(width / 20) new_height = int(height / 40) resized_image = cv2.resize(image, (new_width, new_height),) thresh_image = np.zeros(resized_image.shape) for i, threshold in enumerate(threshold_list): thresh_image[resized_image > threshold] = i return thresh_image if __name__ == "__main__": if len(sys.argv) < 2: print("Image Path not specified : Using sample_image.png\n") image_path = "sample_image.png" if len(sys.argv) == 2: print("Using {} as Image Path\n".format(sys.argv[1])) image_path = sys.argv[1] image = cv2.imread(image_path, 0) ascii_art = img_to_ascii(image) print_out_ascii(ascii_art) ================================================ FILE: Ascii Art Generator/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Audio Book Generator/main.py ================================================ from gtts import gTTS import PyPDF2 pdf_File = open('name.pdf', 'rb') pdf_Reader = PyPDF2.PdfFileReader(pdf_File) count = pdf_Reader.numPages textList = [] for i in range(count): try: page = pdf_Reader.getPage(i) textList.append(page.extractText()) except: pass textString = " ".join(textList) print(textString) language = 'en' myAudio = gTTS(text=textString, lang=language, slow=False) myAudio.save("Audio.mp3") ================================================ FILE: Audio Book Generator/runtime.txt ================================================ python-3.10.7 ================================================ FILE: CODE_OF_CONDUCT.md ================================================ # Code of Conduct *As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.* *We are committed to creating a welcoming and inclusive environment for all people, regardless of their background or identity. We expect all members of our community, including contributors, users, and maintainers, to abide by this Code of Conduct.* ## Our Standards - Examples of behavior that contributes to creating a positive environment include: - Be respectful of others and their opinions - Refrain from using discriminatory language or behavior - Avoid engaging in personal attacks or harassment - Help create a safe and positive environment for everyone - Follow the project's guidelines and procedures - Examples of unacceptable behavior by participants include: - Harassment or discrimination of any kind - Threats, bullying, or violence - Sharing of private information without consent - Plagiarism or infringement of intellectual property rights - Any other behavior that is deemed unacceptable by the project maintainers ## Our Responsibilities - Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. - Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Consequences - If you engage in behavior that violates this Code of Conduct, you may be asked to stop, or other appropriate action may be taken. - If any unacceptable behavior will be determined by the project maintainers, and may include: - Warning - Removal from the project or community - Reporting to appropriate authorities ## Reporting - If you witness or experience conduct that violates this Code of Conduct, please contact us immediately on [Linkedin](https://linkedin.com/in/king04aman/). We will take all reports seriously and will work to resolve the issue as quickly as possible. ## Attribution - This Code of Conduct is adapted from the Contributor Covenant, version 1.4, available at [https://www.contributor-covenant.org/version/1/4/code-of-conduct.html](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html) ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing Guidelines *Thank you for your interest in contributing to this Python project! We welcome and appreciate contributions of all kinds, from bug reports and feature requests to documentation and code improvements.* ## How to Contribute *Here are some ways you can contribute:* - [Report an issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/creating-an-issue) - [Suggest a feature](CONTRIBUTING.md) - Improve the documentation - [Contribute code](CODE_OF_CONDUCT.md) ## Reporting Issues *When reporting an issue, please include the following:* - A clear and descriptive title - A detailed description of the issue, including steps to reproduce the problem - Screenshots or other relevant media - The version of the project and dependencies you are using - The operating system and version you are using ## Suggest a feature *To suggest a new feature, please open an issue on GitHub and provide a detailed description of what you would like to see added, and why it would be useful.* ## Improve the documentation *We welcome improvements to the documentation, whether they're typo fixes, explanations of complex concepts, or examples of how to use the software. To make changes to the documentation, please fork the repository, make your changes, and submit a pull request.* ## Contribute code Guidelines *If you're interested in contributing code to the project, please follow these guidelines:* - Fork the repository. This creates a copy of the code that you can work on without affecting the original project. - Create a new branch. Use a descriptive name that reflects the changes you plan to make. - Make your changes. Keep your code clean, well-organized, and easy to read. Follow the project's existing coding style as closely as possible. - Test your changes. Make sure your changes don't break existing functionality and that they work as expected. - Submit a pull request. Once you've made your changes and tested them, submit a pull request. Please provide a clear and concise description of your changes and why they're needed. - Add documentation. Add documentation to the README.md file and to the code files. ## Pull Request Guidelines - Fork the repository and create a new branch for your changes. - Follow the existing code style and conventions. - Include tests for any new code. - Make sure all tests pass before submitting the pull request. - Do not include changes to the README or other documentation in the same pull request as code changes. ## Code of Conduct *Please note that this project is released with a Code of Conduct. By participating in this project you agree to abide by its terms.* ## License This project is licensed under the terms of the MIT license. ## Thank you! Thank you for your interest in contributing to this project! We appreciate your help and look forward to working with you. ================================================ FILE: CountDown Timer/main.py ================================================ from tkinter import * import tkinter as tk class Application(Frame): def __init__(self,master): super(Application,self).__init__(master) self.pack() self.createWidgets() self.master.geometry("300x200") self._alarm_id = None self._paused = False self._starttime = 0 # def startTimer(self): def createWidgets(self): self.someFrame = Frame(self) self.time_var = StringVar() self.input_time = tk.Entry(self, width=25, font=('Calibri',12), textvariable = self.time_var) # Adding placeholder self.input_time.insert(0, "Enter Time in seconds") self.input_time.pack(padx=10,pady=(30,10)) #using bind method self.input_time.bind("", self.enter) self.startButton = Button(self.someFrame, text="Start", font=('Helvetica',12), bg='green', fg='white', command=self.startTime) self.startButton.pack(side=LEFT, padx=5) self.pauseButton = Button(self.someFrame, text="Pause", font=('Helvetica',12), bg='azure', command=self.pauseTime) self.pauseButton.pack(side=LEFT, padx=5) self.resetButton = Button(self.someFrame, text="Reset", font=('Helvetica',12), bg='azure', command=self.resetTime) self.resetButton.pack(side=LEFT, padx=5) self.closeButton = Button(self.someFrame, text="Close", font=('Helvetica',12), bg='red',fg='white', command=self.closeApp) self.closeButton.pack(side=LEFT, padx=5) self.someFrame.pack(side=TOP) self.labelvariable = StringVar() self.labelvariable.set("") self.thelabel = Label(self,textvariable = self.labelvariable,font=('Helvetica',50)) self.thelabel.pack(side=TOP) # Removes placeholder text in the Entry widget def enter(self,*args): self.input_time.delete(0, 'end') # Resume function def startTime(self): self.get_time = self.time_var.get() try: self.time_in_int = int(self.get_time) except: self.time_in_int = 0 self._starttime = self.time_in_int self._paused = False if self._alarm_id is None: self.countdown(self._starttime) # Pause function def pauseTime(self): if self._alarm_id is not None: self._paused = True # Reset function def resetTime(self): if self._alarm_id is not None: self.master.after_cancel(self._alarm_id) self._alarm_id = None self._paused = False self.countdown(0) self._paused = True def closeApp(self): self.master.destroy() def countdown(self, timeInSeconds, start=True): if timeInSeconds == 0: self._starttime=0 self.labelvariable.set("0") return if start: self._starttime = timeInSeconds if self._paused: self._alarm_id = self.master.after(1000, self.countdown, timeInSeconds, False) else: app.labelvariable.set(timeInSeconds) self._alarm_id = self.master.after(1000, self.countdown, timeInSeconds-1, False) if __name__ == '__main__': root = Tk() root.title("Countdown Timer") app = Application(root) root.mainloop() ================================================ FILE: CountDown Timer/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Currency Converter/main.py ================================================ import requests class Currency_convertor: rates = {} def __init__(self, url): data = requests.get(url).json() self.rates = data["rates"] def convert(self, from_currency, to_currency, amount): initial_amount = amount if from_currency != 'EUR' : amount = amount / self.rates[from_currency] amount = round(amount * self.rates[to_currency], 2) print('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency)) if __name__ == "__main__": url = str.__add__('http://data.fixer.io/api/latest?access_key=', YOUR_ACCESS_KEY) c = Currency_convertor(url) amount = int(input("Amount: ")) from_country = input("From Country: ") to_country = input("TO Country: ") c.convert(from_country, to_country, amount) ================================================ FILE: Currency Converter/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Custom GPT/README.md ================================================ # Conversational Retrieval with LangChain and OpenAI This directory contains a Python script that implements a conversational retrieval system using LangChain and OpenAI's API. The script allows users to query a collection of documents and receive responses based on the retrieved information. ## Features - Load documents from a specified directory. - Create and persist a vector store index for efficient querying. - Engage in conversational interactions, maintaining chat history. - Easily exit the program. ## Requirements - Python 3.7+ - Required packages: - `openai` - `langchain` - `chromadb` You can install the required packages using pip: ```bash pip install openai langchain chromadb ``` ## Setup 1. Clone the Repository: ```bash git clone https://github.com/king04aman/custom-gpt.git cd your_repository ``` 2. Set the OpenAI API Key: Replace `your_api_key_here` in the script with your actual OpenAI API key. You can also set the environment variable directly in your terminal: ```bash export OPENAI_API_KEY="your_api_key_here" ``` 3. Prepare Your Data: Place your documents in a folder named `data/`. The script will load all documents from this directory. ## Usage Run the script from the command line: ```bash python main.py ``` ### Command Line Arguments You can provide an initial query as a command line argument: ```bash python main.py "Your initial query here" ``` ### Interactive Mode If no initial query is provided, the script will prompt you to enter queries interactively. Type your question and press Enter to get a response. Type `quit`, `q`, or exit to `exit` the program. ### Persistence - Set the `PERSIST` variable to `True` in the script to enable saving the vector store index to disk for reuse in future sessions. - The index will be saved in a directory named `persist/`. ## Example ```bash Prompt (type 'quit' to exit): What is the significance of data persistence? Response: [Your response here based on the documents] ``` ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. ## Contributing Feel free to submit issues or pull requests. Contributions are welcome! ================================================ FILE: Custom GPT/data/data.txt ================================================ ================================================ FILE: Custom GPT/example-env ================================================ OPENAI_API_KEY = "your_api_key" ================================================ FILE: Custom GPT/main.py ================================================ import os import openai import sys from langchain.chains import ConversationalRetrievalChain from langchain.chat_models import ChatOpenAI from langchain.document_loaders import DirectoryLoader from langchain.embeddings import OpenAIEmbeddings from langchain.indexes import VectorstoreIndexCreator from langchain.indexes.vectorstore import VectorStoreIndexWrapper from langchain.vectorstores import Chroma os.environ["OPENAI_API_KEY"] = "your_api_key_here" PERSIST = False query = sys.argv[1] if len(sys.argv) > 1 else None if PERSIST and os.path.exists("persist"): print("Reusing index...\n") vectorstore = Chroma(persist_directory="persist", embedding_function=OpenAIEmbeddings()) index = VectorStoreIndexWrapper(vectorstore=vectorstore) else: loader = DirectoryLoader("data/") index = VectorstoreIndexCreator(vectorstore_kwargs={"persist_directory": "persist"}).from_loaders([loader]) if PERSIST else VectorstoreIndexCreator().from_loaders([loader]) chain = ConversationalRetrievalChain.from_llm( llm=ChatOpenAI(model="gpt-3.5-turbo"), retriever=index.vectorstore.as_retriever(search_kwargs={"k": 1}), ) chat_history = [] while True: if not query: query = input("Prompt (type 'quit' to exit): ") if query.lower() in ['quit', 'q', 'exit']: print("Exiting the program...") sys.exit() result = chain({"question": query, "chat_history": chat_history}) print("Response:", result['answer']) chat_history.append((query, result['answer'])) query = None ================================================ FILE: Customizable_Workout_Playlist_Generator/README_SONG.md ================================================ # Customizable Workout Playlist Generator This Python application generates customized workout playlists based on user preferences, including workout type, duration, preferred genres, and BPM range. It can use a local song database or integrate with popular music streaming services like Spotify, Apple Music, and YouTube Music. ## Features - Generate playlists for various workout types (e.g., HIIT, yoga, cardio) - Customize playlist duration - Filter songs by genre and BPM range - Integration with Spotify, Apple Music, and YouTube Music (API keys required) - Save and load playlists in JSON format ## Requirements - Python 3.6+ - Required Python packages (see `requirements.txt`) ## Installation 1. Clone this repository: ``` git clone https://github.com/Ashutoshdas-dev/All-In-One-Python-Projects.git cd Customizable_Workout_Playlist_Generator ``` 2. Install the required packages: ``` pip install -r requirements.txt ``` 3. Set up API credentials for the music services you want to use (Spotify, Apple Music, or YouTube Music). ## Usage 1. Run the main script: ``` python playlist.py ``` 2. Follow the prompts to: - Choose a music source (local database, Spotify, Apple Music, or YouTube Music) - Enter workout type, duration, preferred genres, and BPM range - Generate and view the playlist - Save the playlist to a JSON file (optional) 3. Repeat the process to generate multiple playlists or exit the program. ## API Integration To use the music streaming service integrations, you'll need to set up API credentials: - Spotify: Set up a Spotify Developer account and create an app to get your client ID and client secret. - Apple Music: Obtain an Apple Developer account and set up MusicKit. - YouTube Music: No authentication is required for basic usage. Update the respective client classes in `playlist.py` with your API credentials. ================================================ FILE: Customizable_Workout_Playlist_Generator/hiit_playlist.json ================================================ [ { "title": "Lose Yourself", "artist": "Eminem", "duration": 326, "bpm": 171, "genre": "hip-hop" }, { "title": "Till I Collapse", "artist": "Eminem", "duration": 297, "bpm": 171, "genre": "hip-hop" }, { "title": "God's Plan", "artist": "Drake", "duration": 198, "bpm": 154, "genre": "hip-hop" }, { "title": "Blinding Lights", "artist": "The Weeknd", "duration": 200, "bpm": 171, "genre": "pop" }, { "title": "Sicko Mode", "artist": "Travis Scott", "duration": 312, "bpm": 155, "genre": "hip-hop" }, { "title": "In the End", "artist": "Linkin Park", "duration": 217, "bpm": 105, "genre": "rock" }, { "title": "HUMBLE.", "artist": "Kendrick Lamar", "duration": 177, "bpm": 150, "genre": "hip-hop" }, { "title": "Shape of You", "artist": "Ed Sheeran", "duration": 233, "bpm": 96, "genre": "pop" }, { "title": "Rockstar", "artist": "Post Malone", "duration": 218, "bpm": 80, "genre": "hip-hop" }, { "title": "Senorita", "artist": "Shawn Mendes", "duration": 190, "bpm": 117, "genre": "pop" }, { "title": "Bad Guy", "artist": "Billie Eilish", "duration": 194, "bpm": 135, "genre": "pop" }, { "title": "Believer", "artist": "Imagine Dragons", "duration": 204, "bpm": 125, "genre": "rock" }, { "title": "Old Town Road", "artist": "Lil Nas X", "duration": 157, "bpm": 136, "genre": "hip-hop" }, { "title": "7 Rings", "artist": "Ariana Grande", "duration": 178, "bpm": 70, "genre": "pop" }, { "title": "Sunflower", "artist": "Post Malone", "duration": 158, "bpm": 90, "genre": "hip-hop" }, { "title": "No Tears Left to Cry", "artist": "Ariana Grande", "duration": 206, "bpm": 122, "genre": "pop" }, { "title": "Lucid Dreams", "artist": "Juice WRLD", "duration": 239, "bpm": 84, "genre": "hip-hop" }, { "title": "Memories", "artist": "Maroon 5", "duration": 189, "bpm": 91, "genre": "pop" }, { "title": "Savage Love", "artist": "Jawsh 685 & Jason Derulo", "duration": 171, "bpm": 96, "genre": "pop" }, { "title": "Levitating", "artist": "Dua Lipa", "duration": 203, "bpm": 103, "genre": "pop" }, { "title": "One Dance", "artist": "Drake", "duration": 173, "bpm": 104, "genre": "afrobeats" }, { "title": "Stressed Out", "artist": "Twenty One Pilots", "duration": 185, "bpm": 85, "genre": "alternative" }, { "title": "Radioactive", "artist": "Imagine Dragons", "duration": 186, "bpm": 136, "genre": "rock" }, { "title": "Rolling in the Deep", "artist": "Adele", "duration": 228, "bpm": 105, "genre": "pop" }, { "title": "Closer", "artist": "The Chainsmokers", "duration": 244, "bpm": 95, "genre": "electronic" }, { "title": "Shake It Off", "artist": "Taylor Swift", "duration": 219, "bpm": 160, "genre": "pop" }, { "title": "Uptown Funk", "artist": "Mark Ronson ft. Bruno Mars", "duration": 269, "bpm": 115, "genre": "funk" }, { "title": "Sorry", "artist": "Justin Bieber", "duration": 200, "bpm": 100, "genre": "pop" }, { "title": "The Middle", "artist": "Zedd, Maren Morris", "duration": 184, "bpm": 99, "genre": "electronic" }, { "title": "Shallow", "artist": "Lady Gaga & Bradley Cooper", "duration": 215, "bpm": 96, "genre": "pop" }, { "title": "Despacito", "artist": "Luis Fonsi ft. Daddy Yankee", "duration": 229, "bpm": 89, "genre": "reggaeton" }, { "title": "Attention", "artist": "Charlie Puth", "duration": 211, "bpm": 100, "genre": "pop" }, { "title": "Stay", "artist": "The Kid LAROI & Justin Bieber", "duration": 141, "bpm": 170, "genre": "pop" }, { "title": "Circles", "artist": "Post Malone", "duration": 215, "bpm": 120, "genre": "pop" }, { "title": "Call Out My Name", "artist": "The Weeknd", "duration": 234, "bpm": 135, "genre": "R&B" }, { "title": "Heat Waves", "artist": "Glass Animals", "duration": 239, "bpm": 81, "genre": "pop" }, { "title": "Good 4 U", "artist": "Olivia Rodrigo", "duration": 178, "bpm": 170, "genre": "pop-punk" }, { "title": "Montero (Call Me By Your Name)", "artist": "Lil Nas X", "duration": 137, "bpm": 89, "genre": "hip-hop" }, { "title": "Industry Baby", "artist": "Lil Nas X ft. Jack Harlow", "duration": 212, "bpm": 150, "genre": "hip-hop" }, { "title": "Dynamite", "artist": "BTS", "duration": 199, "bpm": 114, "genre": "pop" }, { "title": "Peaches", "artist": "Justin Bieber ft. Daniel Caesar", "duration": 198, "bpm": 90, "genre": "R&B" }, { "title": "Positions", "artist": "Ariana Grande", "duration": 172, "bpm": 100, "genre": "pop" }, { "title": "Watermelon Sugar", "artist": "Harry Styles", "duration": 174, "bpm": 96, "genre": "pop" }, { "title": "Say So", "artist": "Doja Cat", "duration": 237, "bpm": 111, "genre": "pop" }, { "title": "Mood", "artist": "24kGoldn ft. Iann Dior", "duration": 140, "bpm": 91, "genre": "hip-hop" } ] ================================================ FILE: Customizable_Workout_Playlist_Generator/playlist.py ================================================ import json from datetime import timedelta import random from typing import List, Dict, Optional import os # Add these imports for API integration (you'll need to install these libraries) import spotipy from spotipy.oauth2 import SpotifyOAuth import requests from ytmusicapi import YTMusic class Song: def __init__(self, title: str, artist: str, duration: int, bpm: int, genre: str): self.title = title self.artist = artist self.duration = duration # in seconds self.bpm = bpm self.genre = genre def __str__(self): return f"{self.title} - {self.artist} ({self.duration//60}:{self.duration%60:02d})" class WorkoutPlaylist: def __init__(self): self.songs: List[Song] = [] self.api_client = None # Initialize api_client to None self.load_song_database() def load_song_database(self): if self.api_client: # TODO: Implement fetching songs from the chosen API pass else: # Use the existing sample database self.song_database = [ Song("Eye of the Tiger", "Survivor", 240, 109, "rock"), Song("Stronger", "Kanye West", 312, 104, "hip-hop"), Song("Thunderstruck", "AC/DC", 292, 133, "rock"), Song("Till I Collapse", "Eminem", 297, 171, "hip-hop"), Song("Shake It Off", "Taylor Swift", 219, 160, "pop"), Song("Lose Yourself", "Eminem", 326, 171, "hip-hop"), Song("Sweet Dreams", "Eurythmics", 216, 125, "pop"), Song("Don't Stop Believin'", "Journey", 250, 119, "rock"), Song("Pump It", "Black Eyed Peas", 213, 154, "pop"), Song("Run the World", "Beyoncé", 236, 127, "pop"), ] def set_api_client(self, service: str): if service == 'spotify': self.api_client = SpotifyClient() elif service == 'apple_music': self.api_client = AppleMusicClient() elif service == 'youtube_music': self.api_client = YouTubeMusicClient() def generate_playlist( self, workout_type: str, duration_minutes: int, preferred_genres: List[str] = None, min_bpm: Optional[int] = None, max_bpm: Optional[int] = None ) -> List[Song]: """ Generate a workout playlist based on user preferences """ # Define BPM ranges for different workout types if not specified workout_bpm_ranges = { "warmup": (90, 120), "cardio": (120, 140), "hiit": (140, 180), "strength": (110, 130), "cooldown": (80, 110), "yoga": (70, 100) } if min_bpm is None or max_bpm is None: min_bpm, max_bpm = workout_bpm_ranges.get(workout_type.lower(), (100, 140)) # Filter songs based on criteria suitable_songs = [ song for song in self.song_database if min_bpm <= song.bpm <= max_bpm and (preferred_genres is None or song.genre in preferred_genres) ] if not suitable_songs: # If no songs match the criteria, gradually expand the BPM range bpm_range_expansion = 10 while not suitable_songs and (min_bpm > 60 or max_bpm < 180): min_bpm = max(60, min_bpm - bpm_range_expansion) max_bpm = min(180, max_bpm + bpm_range_expansion) suitable_songs = [ song for song in self.song_database if min_bpm <= song.bpm <= max_bpm and (preferred_genres is None or song.genre in preferred_genres) ] if not suitable_songs: # If still no songs, ignore BPM and only consider genre suitable_songs = [ song for song in self.song_database if preferred_genres is None or song.genre in preferred_genres ] if not suitable_songs: # If still no songs, use all available songs suitable_songs = self.song_database # Create playlist playlist = [] total_duration = 0 target_duration = duration_minutes * 60 while total_duration < target_duration and suitable_songs: # Choose a random song that fits within remaining time remaining_time = target_duration - total_duration possible_songs = [s for s in suitable_songs if s.duration <= remaining_time] if not possible_songs: # If no songs fit, choose the shortest available song possible_songs = sorted(suitable_songs, key=lambda s: s.duration) if possible_songs: selected_song = possible_songs[0] else: break else: selected_song = random.choice(possible_songs) playlist.append(selected_song) total_duration += selected_song.duration suitable_songs.remove(selected_song) return playlist def save_playlist(self, playlist: List[Song], filename: str): """Save playlist to a JSON file""" playlist_data = [{ "title": song.title, "artist": song.artist, "duration": song.duration, "bpm": song.bpm, "genre": song.genre } for song in playlist] with open(filename, 'w') as f: json.dump(playlist_data, f, indent=2) def load_playlist(self, filename: str) -> List[Song]: """Load playlist from a JSON file""" with open(filename, 'r') as f: playlist_data = json.load(f) return [Song(**song_data) for song_data in playlist_data] def share_playlist(self, playlist: List[Song], platform: str): """ TODO: Implement playlist sharing functionality This method will allow users to share their playlists on various platforms """ pass # Placeholder for future implementation class SpotifyClient: def __init__(self): self.sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope="playlist-modify-private")) def search_songs(self, query: str, limit: int = 10) -> List[Song]: results = self.sp.search(q=query, limit=limit, type='track') songs = [] for track in results['tracks']['items']: song = Song( title=track['name'], artist=track['artists'][0]['name'], duration=track['duration_ms'] // 1000, bpm=0, # Spotify API doesn't provide BPM directly genre="" # Spotify API doesn't provide genre directly ) songs.append(song) return songs class AppleMusicClient: def __init__(self): # TODO: Implement Apple Music API client # You'll need to set up Apple Music API credentials pass def search_songs(self, query: str, limit: int = 10) -> List[Song]: # TODO: Implement song search using Apple Music API # This is a placeholder implementation return [] class YouTubeMusicClient: def __init__(self): self.ytmusic = YTMusic() def search_songs(self, query: str, limit: int = 10) -> List[Song]: results = self.ytmusic.search(query, filter="songs", limit=limit) songs = [] for track in results: song = Song( title=track['title'], artist=track['artists'][0]['name'], duration=int(track['duration_seconds']), bpm=0, # YouTube Music API doesn't provide BPM genre="" # YouTube Music API doesn't provide genre directly ) songs.append(song) return songs def format_playlist(playlist: List[Song]) -> str: """Format playlist for display""" total_duration = sum(song.duration for song in playlist) formatted = f"Workout Playlist (Total Duration: {total_duration//60}:{total_duration%60:02d})\n" formatted += "-" * 50 + "\n" for i, song in enumerate(playlist, 1): formatted += f"{i}. {song}\n" return formatted def get_user_input(): workout_type = input("Enter workout type (e.g., hiit, yoga, cardio): ").lower() duration_minutes = int(input("Enter workout duration in minutes: ")) genres = input("Enter preferred genres (comma-separated, or press Enter for all): ") preferred_genres = [g.strip() for g in genres.split(",")] if genres else None min_bpm = input("Enter minimum BPM (or press Enter for default): ") max_bpm = input("Enter maximum BPM (or press Enter for default): ") min_bpm = int(min_bpm) if min_bpm else None max_bpm = int(max_bpm) if max_bpm else None return workout_type, duration_minutes, preferred_genres, min_bpm, max_bpm def choose_music_service(): print("Choose a music source:") print("1. Local database (demo)") print("2. Spotify") print("3. Apple Music") print("4. YouTube Music") choice = input("Enter the number of your choice: ") if choice == '1': return None elif choice == '2': return 'spotify' elif choice == '3': return 'apple_music' elif choice == '4': return 'youtube_music' else: print("Invalid choice. Using local database.") return None def main(): generator = WorkoutPlaylist() # Ask for music source choice every time the script runs service = choose_music_service() if service: generator.set_api_client(service) while True: try: workout_type, duration_minutes, preferred_genres, min_bpm, max_bpm = get_user_input() playlist = generator.generate_playlist( workout_type=workout_type, duration_minutes=duration_minutes, preferred_genres=preferred_genres, min_bpm=min_bpm, max_bpm=max_bpm ) print(f"\n{workout_type.capitalize()} Workout Playlist:") print(format_playlist(playlist)) save_option = input("Do you want to save this playlist? (y/n): ").lower() if save_option == 'y': filename = input("Enter filename to save (e.g., my_playlist.json): ") generator.save_playlist(playlist, filename) print(f"Playlist saved to {filename}") another = input("Generate another playlist? (y/n): ").lower() if another != 'y': break except ValueError as e: print(f"Error: {e}") except FileNotFoundError as e: print(f"Error: {e}") if __name__ == "__main__": main() ================================================ FILE: Customizable_Workout_Playlist_Generator/requirements.txt ================================================ spotipy==2.19.0 requests==2.26.0 ytmusicapi==0.22.0 ================================================ FILE: Digital Clock/main.py ================================================ from time import strftime from tkinter import Label, Tk window = Tk() window.title("Digital Clock") window.geometry("300x100") window.configure(bg="green") window.resizable(False, False) clock_label = Label( window, bg="black", fg="green", font=("Arial", 30, "bold"), relief="flat" ) clock_label.place(x=50, y=50) def update_label(): current_time = strftime("%H: %M: %S\n %d-%m-%Y ") clock_label.configure(text=current_time) clock_label.after(80, update_label) clock_label.pack(anchor="center") update_label() window.mainloop() ================================================ FILE: Digital Clock/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Example README.md ================================================ # Script Name Short description of package/script - If package, list of functionalities/scripts it can perform - If standalone script, short description of script explaining what it achieves # Description - If code is not explainable using comments, use this sections to explain your script # Prerequisites - List out the libraries imported in the script # Installing instructions - Explain how to setup and run your package/script in user's local machine. # Screenshot - Display images/gifs/videos of output/result of your script so that users can visualize it. # Author Name(s) of author(s). ================================================ FILE: Expense Splitter/README.md ================================================ # Expense Splitter A simple Python script to split expenses among a group of people. ## Features - Calculates the share per person based on the total amount and number of people. - User-friendly prompts and case-insensitive confirmation. ## Usage 1. Clone the repository. 2. Navigate to the project directory. 3. Run the script: ```bash python main.py ================================================ FILE: Expense Splitter/main.py ================================================ def calculate_split(total_amount: float, number_of_people: int, currency: str) -> None: if number_of_people < 1: raise ValueError('Number of people should be at least one.') # Calculate the share per person share_per_person: float = total_amount / number_of_people # Print the results print(f'Total expenses: {currency}{total_amount:,.2f}') print(f'Number of people: {number_of_people}') print(f'Each person should pay: {currency}{share_per_person:,.2f}') def main() -> None: try: # Input for total amount total_amount: float = float(input('Enter the total amount of the expense: ')) # Input for number of people number_of_people: int = int(input('Enter the number of people sharing the expense: ')) # Call the function to calculate the split with currency set to rupees calculate_split(total_amount, number_of_people, currency="₹") except ValueError as e: print(f'Error: {e}') # Run the main function if __name__ == "__main__": main() ================================================ FILE: Expense Splitter/runtme.txt ================================================ Python 3.12.3 ================================================ FILE: Extractive Text Summarization/readme.md ================================================ # 📝 Advanced Extractive Text Summarization Model Welcome to the **Advanced Extractive Text Summarization Model**! This project uses **Natural Language Processing (NLP)** techniques to automatically distill essential points from lengthy content, making it an invaluable tool for handling reports, research papers, news articles, and more. ## 🚀 Project Overview This model leverages NLP to: - **Extract key sentences** from a body of text. - **Score sentences** based on their importance using features like **TF-IDF**, sentence length, position, and presence of named entities. - **Cluster related sentences** via **K-means** to highlight critical points from various thematic groups. ### Why It Matters In today’s information-dense world, quickly understanding critical points from long documents is essential. This model saves time and boosts productivity by providing concise summaries while preserving core insights. --- ## 📊 Features 1. **Preprocessing** - Cleans and prepares text data for effective summarization. 2. **Scoring & Ranking** - Scores sentences based on TF-IDF, sentence structure, and key entities. 3. **Clustering & Key Point Extraction** - Uses K-means clustering to group sentences by topic and select key sentences for each group. 4. **Summary Generation** - Combines top-ranked sentences from each cluster to create a coherent, impactful summary. --- ## 🔧 How It Works 1. **Data Preprocessing:** Initial cleaning (e.g., removing stop words, punctuation). 2. **Sentence Scoring:** Uses TF-IDF, sentence structure, and named entity recognition to evaluate sentence importance. 3. **K-means Clustering:** Groups related sentences to capture diverse perspectives within the text. 4. **Summarization:** Extracts top sentences across clusters to create a balanced summary. --- ## 🛠️ Installation 1. **Clone the Repository:** ```bash git clone https://github.com/one-alive/extractive_text_summarization.git cd extractive_text_summarization ``` 2. **Install Dependencies:** ```bash pip install -r requirements.txt ``` --- ## ▶️ Usage 1. **Run the Model on a Sample Text:** ```bash python summarize.py ``` 2. **Adjust Parameters:** You can tune parameters such as the number of clusters, sentence selection criteria, and summary length for better results based on the text type. --- ## ⚙️ Next Steps - **Parameter Tuning:** Experiment with different clustering techniques and scoring weights. - **Expand Dataset Compatibility:** Optimize for specific types of documents like research papers or news articles. - **Add Fine-Tuning:** Integrate more NLP models to improve summarization accuracy. --- ## 🤝 Contributing Contributions are welcome! If you have ideas or suggestions, please create a pull request or open an issue. --- ## 📬 Contact If you have questions or want to explore collaboration opportunities, feel free to reach out! --- ================================================ FILE: Extractive Text Summarization/requirements.txt ================================================ nltk==3.9.1 numpy==2.1.3 scikit_learn==1.5.2 spacy==3.8.2 ================================================ FILE: Extractive Text Summarization/summary.py ================================================ import os import re import heapq import numpy as np from collections import defaultdict from typing import List, Dict, Tuple, Union from nltk.tokenize import sent_tokenize from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans import spacy from nltk.stem import PorterStemmer class TextSummarization: def __init__(self): try: self.nlp = spacy.load('en_core_web_sm') except OSError: print("Downloading spaCy model...") os.system("python -m spacy download en_core_web_sm") self.nlp = spacy.load('en_core_web_sm') self.tfidf_vectorizer = TfidfVectorizer(stop_words='english') self.stemmer = PorterStemmer() def clean_text(self, text: str) -> Tuple[str, str]: """Clean and preprocess the text, returning both original and stemmed versions.""" text = re.sub(r'[^\w\s.,!?]', '', text) # Keep sentence structure cleaned_text = ' '.join(text.split()) # Remove extra whitespace stemmed_text = self.stem_text(cleaned_text) return cleaned_text, stemmed_text def stem_text(self, text: str) -> str: """Stem the words in the text.""" words = text.split() stemmed_words = [self.stemmer.stem(word) for word in words] return ' '.join(stemmed_words) def score_sentences(self, original_sentences: List[str], stemmed_sentences: List[str]) -> Dict[str, float]: """Score sentences based on TF-IDF and structural features.""" tfidf_matrix = self.tfidf_vectorizer.fit_transform(stemmed_sentences) sentence_scores = defaultdict(float) for i, original_sentence in enumerate(original_sentences): score = sum(tfidf_matrix[i, j] for j in tfidf_matrix[i].indices) sent_doc = self.nlp(original_sentence) # Apply length and positional weighting length_factor = min( 1.0, len(sent_doc) / 20.0) if len(sent_doc) < 20 else 20.0 / len(sent_doc) score *= length_factor # Position bonuses if i < len(original_sentence) * 0.2: score *= 1.2 elif i > len(original_sentence) * 0.8: score *= 1.1 # Bonuses for named entities and important dependencies if sent_doc.ents: score *= 1.2 if any(token.dep_ in ['nsubj', 'dobj'] for token in sent_doc): score *= 1.1 sentence_scores[original_sentence] = score return sentence_scores def extract_key_points(self, original_sentences: List[str], stemmed_sentences: List[str], num_clusters: int = 5) -> List[str]: """Extract key points using K-means clustering.""" num_clusters = min(num_clusters, len(original_sentences)) if num_clusters < 1: return [] tfidf_matrix = self.tfidf_vectorizer.fit_transform(stemmed_sentences) kmeans = KMeans(n_clusters=num_clusters, random_state=42) kmeans.fit(tfidf_matrix) labeled_sentences = [(orig, stem, label, idx) for idx, (orig, stem, label) in enumerate( zip(original_sentences, stemmed_sentences, kmeans.labels_))] key_points = [] for cluster in range(num_clusters): cluster_sentences = [ item for item in labeled_sentences if item[2] == cluster] if cluster_sentences: cluster_center = kmeans.cluster_centers_[cluster] distances = [np.linalg.norm(tfidf_matrix[item[3]].toarray( ) - cluster_center) for item in cluster_sentences] closest_sentence = cluster_sentences[np.argmin( distances)][0] # Use original sentence sent_doc = self.nlp(closest_sentence) if len(sent_doc) >= 5: point = re.sub(r'\s+', ' ', closest_sentence.strip('., ')) if len(point.split()) >= 5: # Store with original index key_points.append((point, cluster_sentences[0][3])) # Sort key points based on their original position in the text key_points.sort(key=lambda x: x[1]) return [point for point, _ in key_points] def summarize(self, text: str, num_sentences: int = 5) -> Dict[str, Union[str, List[str]]]: """Generate a comprehensive summary of the text.""" cleaned_text, stemmed_text = self.clean_text(text) original_sentences = sent_tokenize(cleaned_text) stemmed_sentences = sent_tokenize(stemmed_text) num_sentences = min(num_sentences, len( original_sentences)) if original_sentences else 0 sentence_scores = self.score_sentences( original_sentences, stemmed_sentences) summary_sentences = heapq.nlargest( num_sentences, sentence_scores.items(), key=lambda x: x[1]) summary_sentences.sort(key=lambda x: original_sentences.index(x[0])) summary = ' '.join([sentence for sentence, _ in summary_sentences]) key_points = self.extract_key_points( original_sentences, stemmed_sentences, num_clusters=min(5, len(original_sentences))) return { 'summary': summary, 'key_points': key_points, } def main(text): # Create summarizer instance summarizer = TextSummarization() # Generate summary summary = summarizer.summarize(text) print("Summary : ") print(summary['summary']) print("------\n") print("Key Points : ") for i,j in enumerate(summary["key_points"]): print(f"{i+1}. {j}") print("------") if __name__ == "__main__": main("""NLP is a subfield of computer science and artificial intelligence concerned with interactions between computers and human (natural) languages. It is used to apply machine learning algorithms to text and speech. For example, we can use NLP to create systems like speech recognition, document summarization, machine translation, spam detection, named entity recognition, question answering, autocomplete, predictive typing and so on. Nowadays, most of us have smartphones that have speech recognition. These smartphones use NLP to understand what is said. Also, many people use laptops which operating system has a built-in speech recognition.""") ================================================ FILE: Facebook Video Downloader/main.py ================================================ import os, re, requests, wget root = os.path.dirname(os.path.abspath(__file__)) path = os.path.join(root, "Downloads") if not os.path.exists(path): os.mkdir(path) link = input("Enter video link: ") try: r = requests.get(link) if r.status_code == requests.codes.ok: try: sd_url = re.search('sd_src:"(.+?)"', r.text)[1] url = ( re.search('hd_src:"(.+?)"', r.text)[1] if "hd_src" in r.text else sd_url ) print("Downloading... Please wait...") wget.download(url, path) except Exception as e: print(e) else: print("Invalid Link!") except Exception as e: print(e) ================================================ FILE: Facebook Video Downloader/requirements.txt ================================================ requests==2.26.0 wget==3.2 ================================================ FILE: Facebook Video Downloader/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Gauss Elimination with Partial Pivoting/README.md ================================================ # Implementation of Gauss Elimination with Partial Pivoting This implementaion is a Gauss Elimination with Partial Pivoting in Python. You can insert a number of lines of your augmented matrix and then, the numbers that compose it. # Screenshot Those are some examples: ![Example 1](gauss_example1.jpg) ![Example 2](gauss_example2.jpg) # Author [GiovannaRMendes](https://github.com/GiovannaRMendes) ================================================ FILE: Gauss Elimination with Partial Pivoting/main.py ================================================ def gauss_partial(matrix: list, index_column: int): index_max_val = index_column for i in range(index_column, len(matrix)): if matrix[index_column][index_column] < abs(matrix[i][index_column]): index_max_val = i if index_column != index_max_val: matrix[index_column], matrix[index_max_val] = matrix[index_max_val], matrix[index_column] def verify_triangular(matrix: list) -> bool: for i in range(len(matrix)): for j in range(i, len(matrix)): if (j == i and matrix[j][i] == 0) or (j != i and matrix[j][i] != 0): return False return True def gauss(matrix: list, index: int) -> list: for j in range(index+1, len(matrix)): coefficient = round(matrix[j][index] / matrix[index][index], 2) matrix[j][index] = 0 for k in range(index+1, len(matrix)+1): matrix[j][k] = round(matrix[j][k] - coefficient * matrix[index][k], 5) return matrix def resolve_linear_system(matrix: list) -> list: sum = 0 n = len(matrix) results = [1] * n for i in range(n-1, -1, -1): for j in range(n-1, i, -1): sum = sum + matrix[i][j]*results[j] results[i] = round((matrix[i][n] - sum)/matrix[i][i], 2) sum = 0 return results def resolve_matrix(matrix: list): for i in range(len(matrix)): gauss_partial(matrix, i) matrix = gauss(matrix, i) print('\nThe matrix after Gauss:') for line in matrix: print("[", end='') print(*(f'{val}' for val in line), end='') print("]") if verify_triangular(matrix): print("\nThe result of Gauss Elimination with Partial Pivoting:") for i, x in enumerate(resolve_linear_system(matrix)): print(f'x_{i} = {x}') else: print("It's impossible to resolve, because it's not a triangular matrix") return 0 def take_matrix() -> list: line = 0 matrix = [] max_length = 0 number_lines = int(input("Please, insert the length of the your matrix: ")) print("Please, insert only the numbers of the your augmented matrix (separete with espace):") for i in range(number_lines): try: line = list(input().split()) line = list(int(val) for val in line) if max_length < len(line): max_length = len(line) matrix.append(line) except: print("This matrix don't exist!!!") return 1 if len(matrix) == max_length - 1: return matrix return 0 if __name__ == '__main__': matrix = take_matrix() if matrix == 0: print("It's impossible to resolve") else: print('The matrix:') for line in matrix: print("[", end='') print(*(f'{val}' for val in line), end='') print("]") resolve_matrix(matrix) ================================================ FILE: Gauss Elimination with Partial Pivoting/runtime.txt ================================================ python-3.12.6 ================================================ FILE: Geographic Distance/README.md ================================================ # Geographic Distance and Travel Time Calculator This Python script calculates the geodesic distance between two geographic coordinates and estimates travel time based on a given average speed. It uses the geopy library to compute distances. ## Features - Input coordinates for two locations (latitude and longitude) interactively. - Calculate the distance between the two coordinates in kilometers. - Estimate the travel time based on a given average speed (in km/h). ## Prerequisites - Python 3.x installed on your system. ## Setup 1. Clone the repository ```bash git clone https://github.com/king04aman/All-In-One-Python-Projects.git cd All-In-One-Python-Projects/Geographic Distance ``` 2. Create and activate a virtual environment - For macOS/Linux: ```bash python3 -m venv venv source venv/bin/activate ``` - For Windows: ```bash python -m venv venv venv\Scripts\activate ``` 3. Install the required dependencies The required packages are listed in requirements.txt. Install them using the following command: ```bash pip install -r requirements.txt ``` Note: The main dependency is geopy for calculating distances based on geodesic coordinates. ## Usage 1. Run the script: ```bash python geographic_distance.py ``` 2. Enter the coordinates (latitude and longitude) of the two locations when prompted. 3. Enter the average speed in km/h to calculate the travel time. Example input: ``` Enter the latitude and longitude of the first location (lat1, lon1) Example: 40.7128, -74.006: 52.5200, 13.4050 Enter the latitude and longitude of the second location (lat2, lon2) Example: 37.7749, -122.4194: 48.8566, 2.3522 Enter the average speed in km/h Example: 60: 80 ``` Example output: ``` Distance between the two coordinates: 878.84 kilometers Estimated travel time: 10.99 hours ``` ## Requirements Here’s a list of Python dependencies in requirements.txt: ``` geopy==2.2.0 pytest==8.3.3 ``` ================================================ FILE: Geographic Distance/geographic_distance.py ================================================ from geopy.distance import geodesic def calculate_distance_and_time(coord1, coord2, avg_speed): """ Calculate the distance between two coordinates and estimate travel time. :param coord1: Tuple containing the latitude and longitude of the first location (lat1, lon1) :param coord2: Tuple containing the latitude and longitude of the second location (lat2, lon2) :param avg_speed: Average speed in km/h for estimating travel time :return: Distance in kilometers and estimated travel time in hours """ # Calculate geodesic distance distance = geodesic(coord1, coord2).kilometers # Estimate travel time (distance / speed) travel_time = distance / avg_speed return distance, travel_time def main(): # Coordinates (latitude, longitude) try: coord1 = tuple(map(float, input('Enter the latitude and longitude of the first location (lat1, lon1) Example: 40.7128, -74.006: ').split(','))) coord2 = tuple(map(float, input('Enter the latitude and longitude of the second location (lat2, lon2) Example: 37.7749, -122.4194: ').split(','))) except ValueError as e: raise ValueError("Coordinates must be in the format 'lat, lon'") from e if not all(-90 <= x <= 90 for x in (coord1[0], coord2[0])) or not all(-180 <= x <= 180 for x in (coord1[1], coord2[1])): raise ValueError('Invalid coordinates') # Speed in km/h (e.g., driving speed) try: avg_speed = float(input('Enter the average speed in km/h Example: 60: ')) except ValueError as e: raise ValueError('Average speed must be a number') from e if avg_speed <= 0: raise ValueError('Average speed must be greater than 0.') # Calculate the distance and travel time distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed) print(f'Distance between the two coordinates: {distance:.2f} kilometers') print(f'Estimated travel time: {travel_time:.2f} hours') if __name__ == '__main__': main() ================================================ FILE: Geographic Distance/requirements.txt ================================================ geopy==2.4.1 pytest==8.3.3 ================================================ FILE: Geographic Distance/runtime.txt ================================================ python-3.12.7 ================================================ FILE: Geographic Distance/test_geographic_distance.py ================================================ from unittest.mock import patch import pytest from geographic_distance import calculate_distance_and_time, main def test_calculate_distance_and_time(): # Test with valid coordinates and speed coord1 = (40.7128, -74.006) coord2 = (37.7749, -122.4194) avg_speed = 60 distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed) assert distance > 0 assert travel_time > 0 def test_calculate_distance_and_time_invalid_speed(): # Test with invalid speed (zero) coord1 = (40.7128, -74.006) coord2 = (37.7749, -122.4194) avg_speed = 0 with pytest.raises(ValueError): calculate_distance_and_time(coord1, coord2, avg_speed) def test_calculate_distance_and_time_same_coordinates(): # Test with same coordinates coord1 = (40.7128, -74.006) coord2 = (40.7128, -74.006) avg_speed = 60 distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed) assert distance == 0 assert travel_time == 0 @pytest.fixture def mock_input(): with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', '60']): yield def test_main(mock_input, capsys): main() captured = capsys.readouterr() assert 'Distance between the two coordinates:' in captured.out assert 'Estimated travel time:' in captured.out def test_main_invalid_coordinates(mock_input, capsys): with patch('builtins.input', side_effect=['abc, def', '37.7749, -122.4194', '60']): with pytest.raises(ValueError): main() def test_main_invalid_speed(mock_input, capsys): with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', 'abc']): with pytest.raises(ValueError): main() def test_main_zero_speed(mock_input, capsys): with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', '0']): with pytest.raises(ValueError): main() def test_main_same_coordinates(mock_input, capsys): with patch('builtins.input', side_effect=['40.7128, -74.006', '40.7128, -74.006', '60']): main() captured = capsys.readouterr() assert 'Distance between the two coordinates: 0.00 kilometers' in captured.out assert 'Estimated travel time: 0.00 hours' in captured.out ================================================ FILE: Gesture-Based-Game-Controller/main.py ================================================ import cv2 import mediapipe as mp import numpy as np import time # Initialize MediaPipe hands module mp_hands = mp.solutions.hands hands = mp_hands.Hands() mp_drawing = mp.solutions.drawing_utils # Gesture mappings GESTURES = { "forward": "Move Forward", "backward": "Move Backward", "left": "Move Left", "right": "Move Right", "up": "Jump" } # Define a function to calculate the direction based on landmarks def detect_direction(landmarks): # Get coordinates of wrist and index finger tip wrist = landmarks[0] # Wrist coordinates index_finger_tip = landmarks[8] # Index finger tip # Calculate relative positions of index finger to wrist x_diff = index_finger_tip.x - wrist.x # Difference in X-axis y_diff = index_finger_tip.y - wrist.y # Difference in Y-axis # Use thresholds to determine the direction if abs(x_diff) > abs(y_diff): # Horizontal movement dominates if x_diff > 0.1: # Index finger is to the right of the wrist return "right" elif x_diff < -0.1: # Index finger is to the left of the wrist return "left" else: # Vertical movement dominates if y_diff > 0.1: # Fingers are below wrist return "backward" elif y_diff < -0.1: # Fingers are above wrist return "up" # If no significant difference in X or Y, assume pointing forward return "forward" # Video capture for hand gesture recognition cap = cv2.VideoCapture(0) prev_time = 0 # To implement delay between gesture changes delay_interval = 1.0 # 1 second delay between actions while True: ret, frame = cap.read() if not ret: break # Flip the frame horizontally for natural movement frame = cv2.flip(frame, 1) frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # Detect hands results = hands.process(frame_rgb) landmark_list = [] # If hand landmarks are detected if results.multi_hand_landmarks: for hand_landmarks in results.multi_hand_landmarks: mp_drawing.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS) # Collect hand landmark data for lm in hand_landmarks.landmark: landmark_list.append(lm) # Detect direction based on the landmarks direction = detect_direction(landmark_list) # Check for time delay between actions current_time = time.time() if current_time - prev_time > delay_interval: print(GESTURES[direction]) # Output corresponding action prev_time = current_time # Display the frame with landmarks cv2.imshow('Hand Gesture Recognition', frame) # Quit if 'q' is pressed if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() ================================================ FILE: Gesture-Based-Game-Controller/readme.md ================================================ # Hand Gesture Control Using Computer Vision This project uses computer vision and machine learning to detect hand gestures and map them to simple game controls like moving forward, left, right, jumping, and moving backward. The project uses **OpenCV** and **MediaPipe** for hand landmark detection and gesture recognition. ## Features - Detects hand gestures in real-time. - Maps gestures to game controls: - **Move Forward**: Fingers pointing towards the screen. - **Move Left**: Fingers pointing left. - **Move Right**: Fingers pointing right. - **Move Backward**: Fingers pointing downward. - **Jump**: Fingers pointing upward. - Implements a delay between actions to prevent rapid switching of game controls. ## Requirements - Python 3.7 or higher - OpenCV - MediaPipe - NumPy ================================================ FILE: Gesture-Based-Game-Controller/requirements.txt ================================================ opencv-python==4.8.0.74 mediapipe==0.10.0 numpy==1.24.2 ================================================ FILE: Gesture-Based-Game-Controller/runtime.txt ================================================ python-3.12.7 ================================================ FILE: Handwritten-Assignments/main.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Aman Kumar # Version: 1.0.0 import pywhatkit as pw text_to_convert = """ Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Scelerisque varius morbi enim nunc faucibus. Porta nibh venenatis cras sed felis eget velit. Sem viverra aliquet eget sit amet tellus. Volutpat lacus laoreet non curabitur gravida arcu ac tortor. Scelerisque felis imperdiet proin fermentum leo vel orci porta non. Est ullamcorper eget nulla facilisi etiam dignissim diam quis enim. Vitae turpis massa sed elementum tempus egestas sed. Egestas integer eget aliquet nibh praesent. Risus sed vulputate odio ut enim blandit volutpat maecenas. Vitae congue eu consequat ac felis. Aliquet eget sit amet tellus cras. Vel fringilla est ullamcorper eget nulla facilisi. Tristique senectus et netus et malesuada fames ac. Nullam eget felis eget nunc. Tincidunt praesent semper feugiat nibh sed pulvinar proin gravida hendrerit. Enim eu turpis egestas pretium aenean pharetra magna. """ pw.text_to_handwriting(text_to_convert, 'demo.png',[0,0,135]) print("Converted !!") ================================================ FILE: Handwritten-Assignments/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Headlight Detection/headlightDetection.py ================================================ from shutil import which import numpy as np from matplotlib import pyplot as plt import cv2, time def wait(t): time.sleep() #List includes path for images representing differenct scenarios mlist = ['bus_coming.hpg','going.jpg','both.jpg'] #codition: no vehicle def scenario(condition): image = cv2.imread(condition) gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) cv2.imwrite('gray_image.png',gray_image) cv2.imshow('color_image',image) blur_image = cv2.blur(gray_image,(15,15)) cv2.imwrite('blur_image.png',blur_image) ret , thresh = cv2.threshold(blur_image,150,255,0) contour_image , contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) cv2.drwaContours(blur_image,contours,-1,(0,255,0),3) cv2.imshow('blur_image.png',blur_image) moments = [cv2.moments(cnt) for cnt in contours] y_centroids = [int(round(m['m01']/m['m00'])) for m in moments] x = len(y_centroids) i=0 while ia>span')] # Fix ratings try: movieDetails['rating'] = f"{bs.find( 'div', {'data-testid': 'hero-rating-bar__aggregate-rating__score'}).span.text}/10 ({bs.find('div', {'class': 'sc-bde20123-3 gPVQxL'}).text})" movieDetails['runtime'] = box[2].text.strip() except AttributeError: movieDetails['rating'] = 'Not yet rated' movieDetails['runtime'] = 'Not available' # To get movie release date movie_release_dates_url= f"{url}{box[0].a.attrs['href']}" soup = requestUrl_and_bs4(movie_release_dates_url) movieDetails['release_date'] = soup.select_one('#rel_1 > div > ul > li > span.ipc-metadata-list-item__list-content-item').text creditSummary = bs.select('div.ipc-metadata-list-item__content-container > ul') movieDetails['directors'] = [i.text for i in creditSummary[0].select('li>a')] try: movieDetails['cast'] = [i.text for i in creditSummary[2].select('li>a')] movieDetails['writers'] = [i.text for i in creditSummary[1].select('li>a')] except IndexError: movieDetails['cast']=movieDetails['writers'] movieDetails['writers']='Not found' movieDetails['plot'] = bs.find('span', {'data-testid': 'plot-l'}).text.strip() return movieDetails def main(): movieName = input('Enter the movie name : \n') movieDetails = getMovieDetails(movieName) if movieDetails is None: print('No movie found with given name!!!!!') quit() print('\n{movie} ({year})'.format( movie=movieDetails['name'], year=movieDetails['year'])) print('Rating:', movieDetails['rating']) print('Runtime:', movieDetails['runtime']) print('Release Date:', movieDetails['release_date']) print('Genres:', ', '.join(movieDetails['genres'])) print('Director:', ', '.join(movieDetails['directors'])) print('Writer:', ', '.join(movieDetails['writers'])) print('Cast:', ', '.join(movieDetails['cast'])) print('Plot Summary:\n', movieDetails['plot']) if __name__ == "__main__": main() ================================================ FILE: My-Personal-Journal/README.md ================================================ # Personal Journal A simple web-based application for maintaining a personal journal. Users can create entries, tag them, and search through past entries by date or keywords. The application is built using Flask and SQLite for a lightweight and efficient experience. ## Features - **Add New Entries**: Users can add journal entries with mood, content, and tags. - **Search Entries**: Search through entries using keywords or specific dates. - **Tag Management**: Create and view tags associated with each entry, and filter entries by tags. - **User-Friendly Interface**: A clean and professional UI for easy navigation and use. ## Technologies Used - Python - Flask - SQLite - HTML/CSS ## Installation 1. **Clone the Repository**: ```bash git clone cd your_project 2. **Install Required Packages: Make sure you have Python installed (preferably Python 3). Install the required packages using pip**: ```bash pip install -r requirements.txt 3. **Run the Application: Start the Flask application**: ```bash python app.py 4. **Access the App: Open your web browser and navigate to http://127.0.0.1:8080 to access the application.** ================================================ FILE: My-Personal-Journal/app.py ================================================ from flask import Flask, render_template, request, redirect, url_for from journal_app import add_entry, search_entries from datetime import datetime import sqlite3 app = Flask(__name__) # Route to show the home page @app.route('/') def index(): return render_template('index.html') # Route to add a new journal entry @app.route('/add', methods=['GET', 'POST']) def add(): if request.method == 'POST': mood = request.form['mood'] content = request.form['content'] tags = request.form['tags'] add_entry("user_1", mood, content, tags) return redirect(url_for('index')) return render_template('add.html') # Route to search journal entries @app.route('/search', methods=['GET', 'POST']) def search(): if request.method == 'POST': search_input = request.form['search_term'] # Try to parse the input as a date try: search_date = datetime.strptime(search_input, '%Y-%m-%d').date() results = search_entries("user_1", date=search_date) except ValueError: # If parsing fails, treat it as a search term results = search_entries("user_1", search_term=search_input) return render_template('search_results.html', results=results) return render_template('search.html') # Route to list all unique tags @app.route('/tags') def list_tags(): conn = sqlite3.connect('journal.db') cursor = conn.cursor() # Fetch unique tags from all entries cursor.execute("SELECT DISTINCT tags FROM journal_entries") tags_data = cursor.fetchall() conn.close() # Flatten the tags and remove duplicates tags = set() for row in tags_data: if row[0]: tags.update(tag.strip() for tag in row[0].split(',')) return render_template('tags.html', tags=sorted(tags)) # Route to show journal entries by tag @app.route('/tags/') def entries_by_tag(tag): conn = sqlite3.connect('journal.db') cursor = conn.cursor() # Search for entries that contain the selected tag cursor.execute("SELECT * FROM journal_entries WHERE tags LIKE ?", ('%' + tag + '%',)) results = cursor.fetchall() conn.close() return render_template('search_results.html', results=results) if __name__ == '__main__': app.run(debug=True, port=8080) ================================================ FILE: My-Personal-Journal/database.py ================================================ from sqlalchemy.orm import sessionmaker from models import JournalEntry, Base from sqlalchemy import create_engine engine = create_engine('sqlite:///journal.db') Base.metadata.create_all(engine) Session = sessionmaker(bind=engine) session = Session() def add_entry(user_id, mood, content, tags): entry = JournalEntry(user_id=user_id, mood=mood, content=content, tags=tags) session.add(entry) session.commit() def search_entries(user_id, search_term=None, date=None): query = session.query(JournalEntry).filter(JournalEntry.user_id == user_id) if search_term: query = query.filter(JournalEntry.content.contains(search_term)) if date: query = query.filter(JournalEntry.date == date) return query.all() ================================================ FILE: My-Personal-Journal/journal_app.py ================================================ import sqlite3 from datetime import datetime DB_NAME = "journal.db" def connect_db(): return sqlite3.connect(DB_NAME) def create_table(): with connect_db() as conn: cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS journal_entries ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id TEXT, date TEXT, mood TEXT, content TEXT, tags TEXT ) ''') conn.commit() def add_entry(user_id, mood, content, tags): with connect_db() as conn: cursor = conn.cursor() cursor.execute(''' INSERT INTO journal_entries (user_id, date, mood, content, tags) VALUES (?, ?, ?, ?, ?) ''', (user_id, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), mood, content, tags)) conn.commit() def search_entries(user_id, search_term=None, date=None): with connect_db() as conn: cursor = conn.cursor() if search_term: query = ''' SELECT * FROM journal_entries WHERE user_id = ? AND (content LIKE ? OR tags LIKE ?) ''' cursor.execute(query, (user_id, f'%{search_term}%', f'%{search_term}%')) elif date: query = ''' SELECT * FROM journal_entries WHERE user_id = ? AND date(date) = ? ''' cursor.execute(query, (user_id, date.strftime('%Y-%m-%d'))) else: return [] return cursor.fetchall() # Create the journal table at the start create_table() ================================================ FILE: My-Personal-Journal/requirements.txt ================================================ flask sqlalchemy # sqlite3 bcrypt pandas matplotlib # tkinter flask ================================================ FILE: My-Personal-Journal/static/style.css ================================================ /* General Styles */ body { font-family: 'Arial', sans-serif; margin: 0; padding: 0; background-color: #f4f4f9; color: #333; } h1, h2, h3, h4, h5, h6 { color: #2c3e50; text-align: center; } /* Header */ header { background: #2980b9; color: white; padding: 20px 0; } /* Main Content */ .container { max-width: 1100px; margin: 20px auto; padding: 20px; background: white; border-radius: 8px; box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1); text-align: center; /* Center text within the container */ } /* Button Styles */ .button-container { display: flex; justify-content: center; /* Center the buttons */ flex-direction: column; /* Stack buttons vertically */ gap: 20px; /* Space between buttons */ margin-top: 30px; /* Add margin to the top */ } .button { display: inline-block; padding: 15px 30px; background-color: #2980b9; color: white; border-radius: 4px; text-decoration: none; font-size: 1.2rem; transition: background-color 0.3s ease; } .button:hover { background-color: #3498db; } /* Footer */ footer { text-align: center; margin-top: 20px; padding: 20px; background-color: #2980b9; color: white; } p { line-height: 1.6; font-size: 1rem; } a { color: #3498db; text-decoration: none; } a:hover { text-decoration: underline; } /* Header */ header { background: #2980b9; color: white; padding: 20px 0; text-align: center; } /* Main Content */ .container { max-width: 1100px; margin: 20px auto; padding: 20px; background: white; border-radius: 8px; box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1); } h1 { font-size: 2rem; margin-bottom: 20px; } /* Form Styles */ .form-group { margin-bottom: 20px; /* Space between form groups */ text-align: left; /* Align labels and inputs to the left */ } label { display: block; /* Ensure labels are on separate lines */ margin-bottom: 5px; /* Space between label and input */ } /* Form Styles */ form { display: flex; flex-direction: column; gap: 10px; } form input[type="text"], form textarea { padding: 10px; font-size: 1rem; border: 1px solid #ddd; border-radius: 4px; } form textarea { resize: vertical; } form input[type="submit"] { background-color: #2980b9; color: white; border: none; padding: 10px; display:flex; font-size: 1rem; cursor: pointer; border-radius: 4px; } form input[type="submit"]:hover { background-color: #3498db; } /* Tag List */ ul { list-style: none; padding: 0; display: flex; justify-content: center; /* Centers the tags horizontally */ flex-wrap: wrap; /* Allows the tags to wrap if they exceed the width */ gap: 10px; } ul li { display: inline-block; margin-right: 10px; } ul li a { display: inline-block; padding: 10px 20px; background-color: #2980b9; color: white; border-radius: 4px; transition: background-color 0.3s ease; } ul li a:hover { background-color: #3498db; } /* Search Results */ .search-results { margin-top: 20px; } .search-results p { padding: 10px; background: #ecf0f1; border-left: 5px solid #2980b9; margin-bottom: 10px; } hr { border: 0; height: 1px; background: #ddd; margin: 20px 0; } /* Footer */ footer { text-align: center; margin-top: 20px; padding: 20px; background-color: #2980b9; color: white; } input[type="text"], textarea, select { width: 100%; /* Take full width of the container */ padding: 10px; /* Add padding for comfort */ border: 1px solid #ccc; /* Border style */ border-radius: 4px; /* Rounded corners */ box-sizing: border-box; /* Include padding in width */ } textarea { height: 100px; /* Set a height for the textarea */ } /* Search Results Styles */ .results { margin-top: 30px; /* Space above search results */ text-align: left; /* Align results to the left */ } .results ul { list-style-type: none; /* Remove default list styles */ padding: 0; /* Remove padding */ } .results li { background-color: #f4f4f9; /* Light background for entries */ border: 1px solid #ccc; /* Border for each entry */ border-radius: 4px; /* Rounded corners */ padding: 10px; /* Padding for comfort */ margin-bottom: 15px; /* Space between entries */ } ================================================ FILE: My-Personal-Journal/templates/add.html ================================================ Add New Entry

Add New Journal Entry

© 2024 Personal Journal

================================================ FILE: My-Personal-Journal/templates/index.html ================================================ Personal Journal

Welcome to Your Personal Journal

© 2024 Personal Journal

================================================ FILE: My-Personal-Journal/templates/search.html ================================================ Search Journal Entries

Search Journal Entries

Search by keyword or date (YYYY-MM-DD):
================================================ FILE: My-Personal-Journal/templates/search_results.html ================================================ Search Results

Journal Entries

{% for result in results %}

Date: {{ result[2] }}, Mood: {{ result[3] }}, Tags: {{ result[5] }}

{{ result[4] }}


{% else %}

No entries found.

{% endfor %}
================================================ FILE: My-Personal-Journal/templates/tags.html ================================================ Tags

Tags

    {% for tag in tags %}
  • {{ tag }}
  • {% else %}
  • No tags found.
  • {% endfor %}
================================================ FILE: My-Personal-Journal/ui.py ================================================ # from main import add_entry, search_entries # import datetime # def display_menu(): # print("\n=== My Personal Journal ===") # print("1. Create New Journal Entry") # print("2. Search Journal Entries") # print("3. Exit") # def get_mood(): # mood = None # while mood not in ["happy", "sad", "neutral"]: # mood = input("How are you feeling today? (happy, sad, neutral): ").lower() # return mood # def get_tags(): # tags = input("Add tags (comma-separated, e.g., work, personal): ") # return tags # def create_new_entry(user_id): # mood = get_mood() # content = input("Write your journal entry: ") # tags = get_tags() # add_entry(user_id, mood, content, tags) # print("Your entry has been saved!") # def search_journal_entries(user_id): # print("\nSearch Entries") # print("1. Search by keyword") # print("2. Search by date") # choice = input("Choose a search option: ") # if choice == '1': # search_term = input("Enter a keyword to search for: ") # results = search_entries(user_id, search_term=search_term) # elif choice == '2': # date_str = input("Enter a date (YYYY-MM-DD) to search: ") # try: # date = datetime.datetime.strptime(date_str, '%Y-%m-%d') # except ValueError: # print("Invalid date format. Please use YYYY-MM-DD.") # return # results = search_entries(user_id, date=date) # else: # print("Invalid option.") # return # if results: # for entry in results: # print(f"\nDate: {entry[2]}") # print(f"Mood: {entry[3]}") # print(f"Tags: {entry[5]}") # print(f"Entry: {entry[4]}") # print("-" * 40) # else: # print("No entries found for your search criteria.") # def main_ui(): # user_id = input("Enter your user ID to start: ") # while True: # display_menu() # choice = input("Select an option (1-3): ") # if choice == '1': # create_new_entry(user_id) # elif choice == '2': # search_journal_entries(user_id) # elif choice == '3': # print("Goodbye!") # break # else: # print("Invalid choice. Please try again.") # if __name__ == "__main__": # main_ui() import tkinter as tk from tkinter import messagebox from journal_app import add_entry, search_entries from datetime import datetime class JournalApp(tk.Tk): def __init__(self): super().__init__() self.title("Personal Journal") self.geometry("400x400") self.label = tk.Label(self, text="Personal Journal", font=("Helvetica", 16)) self.label.pack(pady=10) self.add_button = tk.Button(self, text="Add New Entry", command=self.add_entry) self.add_button.pack(pady=5) self.search_button = tk.Button(self, text="Search Entries", command=self.search_entries) self.search_button.pack(pady=5) def add_entry(self): self.new_window = tk.Toplevel(self) self.new_window.title("Add New Entry") mood_label = tk.Label(self.new_window, text="Mood (happy, sad, neutral):") mood_label.pack(pady=5) self.mood_entry = tk.Entry(self.new_window) self.mood_entry.pack(pady=5) content_label = tk.Label(self.new_window, text="Write your journal entry:") content_label.pack(pady=5) self.content_entry = tk.Text(self.new_window, height=5, width=30) self.content_entry.pack(pady=5) tags_label = tk.Label(self.new_window, text="Tags (comma-separated):") tags_label.pack(pady=5) self.tags_entry = tk.Entry(self.new_window) self.tags_entry.pack(pady=5) submit_button = tk.Button(self.new_window, text="Submit", command=self.save_entry) submit_button.pack(pady=10) def save_entry(self): mood = self.mood_entry.get() content = self.content_entry.get("1.0", tk.END) tags = self.tags_entry.get() if mood and content: add_entry("user_1", mood, content, tags) messagebox.showinfo("Success", "Journal entry saved!") self.new_window.destroy() else: messagebox.showwarning("Input Error", "Please fill in all fields.") def search_entries(self): self.search_window = tk.Toplevel(self) self.search_window.title("Search Entries") search_label = tk.Label(self.search_window, text="Search by keyword or date (YYYY-MM-DD):") search_label.pack(pady=5) self.search_entry = tk.Entry(self.search_window) self.search_entry.pack(pady=5) search_button = tk.Button(self.search_window, text="Search", command=self.perform_search) search_button.pack(pady=10) def perform_search(self): search_term = self.search_entry.get() results = search_entries("user_1", search_term=search_term) if results: result_window = tk.Toplevel(self) result_window.title("Search Results") for result in results: result_label = tk.Label(result_window, text=f"Date: {result[2]}, Mood: {result[3]}, Tags: {result[5]}") result_label.pack() content_label = tk.Label(result_window, text=f"Entry: {result[4]}") content_label.pack(pady=5) else: messagebox.showinfo("No Results", "No journal entries found.") if __name__ == "__main__": app = JournalApp() app.mainloop() ================================================ FILE: Notepad/main.py ================================================ from tkinter import * from tkinter import filedialog, messagebox root = Tk() root.geometry("700x500") root.title("Aman's Notepad") def save_file(): open_file = filedialog.asksaveasfile(mode='w', defaultextension=".txt") if open_file is None: return text = str(entry.get(1.0, END)) open_file.write(text) open_file.close() def clear(): messagebox.showinfo("Cleared", "Cleared all contents !") entry.delete(1.0, END) def open_file(): file = filedialog.askopenfile(mode='r', filetype=[('text files', '*.txt')]) if file is not None: content = file.read() entry.insert(INSERT, content) b1 = Button(root, text="Save", command=save_file) b1.place(x=10, y=10) b2 = Button(root, text="Clear", command=clear) b2.place(x=70, y=10) b3 = Button(root, text="Open", command=open_file) b3.place(x=120, y=10) entry = Text(root, height=60, width=70, wrap=WORD, bg="black", fg="green", selectbackground="red", font="Courier 15", insertbackground="violet") entry.place(x=10, y=50) root.mainloop() ================================================ FILE: OCR Image-to-Text Conversion/README.md ================================================ ## Introduction Image Text Extractor is a Python application that utilizes Tesseract OCR to extract text from images. This application allows users to input the path to an image file and receive the extracted text in return. ## Requirements - Python 3.x - Libraries: - `pytesseract` - `PIL` (Pillow) You can install the required libraries by running: ```bash pip install pytesseract Pillow ``` ## Installation Instructions for All Operating Systems ### Windows 1. **Install Python**: - Download and install Python from the [official website](https://www.python.org/downloads/). - During installation, make sure to check the box that says "Add Python to PATH". 2. **Install Tesseract OCR**: - Download the Tesseract installer from the [Tesseract GitHub releases page](https://github.com/tesseract-ocr/tesseract/releases). - Run the installer and note the installation path (usually `C:\Program Files\Tesseract-OCR`). 3. **Set Tesseract Path**: - Add the Tesseract installation path to your system environment variables. - Right-click on "This PC" or "My Computer" > Properties > Advanced system settings > Environment Variables. - Under "System variables", find the `Path` variable and click Edit. Add the Tesseract path. 4. **Install Required Libraries**: - Open Command Prompt and run: ```bash pip install pytesseract Pillow ``` ### macOS 1. **Install Homebrew** (if not already installed): - Open Terminal and run: ```bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` 2. **Install Python**: - Use Homebrew to install Python: ```bash brew install python ``` 3. **Install Tesseract OCR**: - Install Tesseract using Homebrew: ```bash brew install tesseract ``` 4. **Install Required Libraries**: - In Terminal, run: ```bash pip install pytesseract Pillow ``` ### Linux (Ubuntu/Debian) 1. **Install Python** (if not already installed): - Open Terminal and run: ```bash sudo apt update sudo apt install python3 python3-pip ``` 2. **Install Tesseract OCR**: - Install Tesseract using: ```bash sudo apt install tesseract-ocr ``` 3. **Install Required Libraries**: - In Terminal, run: ```bash pip3 install pytesseract Pillow ``` ## Usage Instructions After completing the installation, follow the usage instructions below to run the application. 1. Open Command Prompt. 2. Navigate to the directory where the script is located using the `cd` command: ```bash cd path\to\your\script ``` 3. Run the Python script ```bash python image_text_extractor.py - mine is main.py ``` ================================================ FILE: OCR Image-to-Text Conversion/main.py ================================================ import pytesseract from PIL import Image import os def extract_text_from_image(image_path): """Extracts text from an image file using Tesseract OCR.""" try: # Open the image file with Image.open(image_path) as img: # Use pytesseract to do OCR on the image extracted_text = pytesseract.image_to_string(img) return extracted_text except Exception as e: print(f"Error processing the image: {e}") return None def main(): image_path = input("Enter the path to the image file: ") if not os.path.isfile(image_path): print("File does not exist. Please check the path and try again.") return text = extract_text_from_image(image_path) if text: print("Extracted Text:") print(text) if __name__ == "__main__": main() ================================================ FILE: OCR Image-to-Text Conversion/requirements.txt ================================================ pillow==11.0.0 pytesseract==0.3.13 ================================================ FILE: PROJECTS.md ================================================ # Project List * [Age Calculator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Age%20Calculator) * [Alarm Bot](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Alarm%20Bot) * [Ascii Art Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Ascii%20Art%20Generator) * [Audio Book Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Audio%20Book%20Generator) * [CountDown Timer](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/CountDown%20Timer) * [Currency Converter](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Currency%20Converter) * [Custom GPT](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Custom%20GPT) * [Customizable_Workout_Playlist_Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Customizable_Workout_Playlist_Generator) * [Digital Clock](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Digital%20Clock) * [Expense Splitter](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Expense%20Splitter) * [Extractive Text Summarization](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Extractive%20Text%20Summarization) * [Facebook Video Downloader](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Facebook%20Video%20Downloader) * [Geographic Distance](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Geographic%20Distance) * [Gesture-Based-Game-Controller](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Gesture-Based-Game-Controller) * [Handwritten-Assignments](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Handwritten-Assignments) * [Headlight Detection](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Headlight%20Detection) * [Helmet Detection](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Helmet%20Detection) * [Image Compression](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Image%20Compression) * [ImageSize Reducer](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/ImageSize%20Reducer) * [Img-Steganograpy](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Img-Steganograpy) * [Learn-FastAPI](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Learn-FastAPI) * [Mental Health chatbot](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Mental%20Health%20chatbot) * [Merge PDFs](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Merge%20PDFs) * [MobileNumber Tracker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/MobileNumber%20Tracker) * [Mood Based Music Recommender](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Mood%20Based%20Music%20Recommender) * [Movie Scraper](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Movie%20Scraper) * [My-Personal-Journal](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/My-Personal-Journal) * [Notepad](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Notepad) * [OCR Image-to-Text Conversion](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/OCR%20Image-to-Text%20Conversion) * [Password Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Password%20Generator) * [Plagiarism-Checker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Plagiarism-Checker) * [Pomodoro Timer](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Pomodoro%20Timer) * [QR Code Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/QR%20Code%20Generator) * [Random Movie Selector](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Random%20Movie%20Selector) * [Random Quotes Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Random%20Quotes%20Generator) * [Real-Time Cryptocurrency Price Tracker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Real-Time%20Cryptocurrency%20Price%20Tracker) * [Recipe Finder with Meal Planner](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Recipe%20Finder%20with%20Meal%20Planner) * [Resume Builder](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Resume%20Builder) * [Simple Assistant](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Simple%20Assistant) * [Snake-Game](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Snake-Game) * [Speech To Text](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Speech%20To%20Text) * [Spell Checker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Spell%20Checker) * [Telegram Bot](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Telegram%20Bot) * [Text Summarizer](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Text%20Summarizer) * [Text To Speech](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Text%20To%20Speech) * [Text to Morse Code](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Text%20to%20Morse%20Code) * [Text_Adventure_Game](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Text_Adventure_Game) * [Tic-Tac-Toc using AI (min-max)](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Tic-Tac-Toc%20using%20AI%20(min-max)) * [To Do List](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/To%20Do%20List) * [Translator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Translator) * [URL Sortener](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/URL%20Sortener) * [Validate-Email](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Validate-Email) * [Video Processor](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Video%20Processor) * [Video To Audio](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Video%20To%20Audio) * [Weather Alert](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Weather%20Alert) * [Word_frequency_counter](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Word_frequency_counter) * [Youtube Video Downloader](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Youtube%20Video%20Downloader) * [personal-finance-tracker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/personal-finance-tracker) ================================================ FILE: Password Generator/main.py ================================================ from tkinter import * from random import choice import string class App: def __init__(self): self.window = Tk() self.window.title('password_generator') self.window.iconbitmap('logo.ico') self.window.iconphoto(False, PhotoImage(file='logo.png')) self.window.geometry('500x255') self.window.config(bg='gray') self.label() self.entry() self.button() def label(self): label_title = Label(self.window, text='Welcome to password generator', font=('Courrier', 20), bg='gray', fg='black') label_title.pack() def entry(self): self.password_entry = Entry(self.window, font=('Courrier', 25), bg='white', fg='black', width=30, relief='solid') self.password_entry.pack(pady=50) def button(self): password_generator = Button(self.window, text="Generate_password", font=('Courrier', 12), bg='white', fg='black', width=25, command=self.generate_password) password_generator.pack() def generate_password(self): characters = string.ascii_letters + string.punctuation + string.digits password = "" for x in range(28): password+=choice(characters) self.password_entry.delete(0, END) self.password_entry.insert(0, password) app = App() app.window.mainloop() ================================================ FILE: Password Generator/requirements.txt ================================================ tk==0.1.0 ================================================ FILE: Plagiarism-Checker/main.py ================================================ import os from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity student_files = [doc for doc in os.listdir() if doc.endswith('.txt')] student_notes = [open(_file, encoding='utf-8').read() for _file in student_files] def vectorize(Text): return TfidfVectorizer().fit_transform(Text).toarray() def similarity(doc1, doc2): return cosine_similarity([doc1, doc2]) vectors = vectorize(student_notes) s_vectors = list(zip(student_files, vectors)) plagiarism_results = set() def check_plagiarism(): global s_vectors for student_a, text_vector_a in s_vectors: new_vectors = s_vectors.copy() current_index = new_vectors.index((student_a, text_vector_a)) del new_vectors[current_index] for student_b, text_vector_b in new_vectors: sim_score = similarity(text_vector_a, text_vector_b)[0][1] student_pair = sorted((student_a, student_b)) score = (student_pair[0], student_pair[1], sim_score) plagiarism_results.add(score) return plagiarism_results for data in check_plagiarism(): print(data) ================================================ FILE: Plagiarism-Checker/requirements.txt ================================================ scikit_learn==0.24.2 ================================================ FILE: Plagiarism-Checker/test1.txt ================================================ Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. ================================================ FILE: Plagiarism-Checker/test2.txt ================================================ It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). ================================================ FILE: Pomodoro Timer/README.md ================================================ # Pomodoro Timer A simple, customizable command line pomodoro timer built in Python. ## Features - Customizable work, short and long breaks intervals: Define your own durations for each cycle. - Pause whenever you want: Pause the timer when you want to take a break. - Cycles: Run Multiple cycles of work and break intervals - Console output: Show work and break intervals in the console. ## How it works The Pomodoro Timer follow these steps: 1. Set your work and break intervals. 2. Take a short break every work interval. 3. After a set number of cycles, take a long break. ## Usage 1. Clone this repository to your machine. 2. Run the Python script from the command line. '''python pomodoro_timer.py''' ## Author [MeuHubPython](https://github.com/MeuHubPython) ================================================ FILE: Pomodoro Timer/main.py ================================================ import time def countdown(minutes, label): total_seconds = minutes * 60 while total_seconds: mins, secs = divmod(total_seconds, 60) timer = f"{mins:02d}:{secs:02d}" print(f"{label} Timer: {timer}", end="\r") time.sleep(1) total_seconds -= 1 print(f"\n{label} finished!") def handle_pause_stop(): while True: user_input = input( "\nPress 'p' to pause, 's' to stop, or 'Enter' to continue: " ).lower() if user_input == "p": print("Timer paused. Press 'Enter' to resume.") input() elif user_input == "s": print("Timer stopped.") return True # Return True to signal that the timer should stop else: return False # Return False to continue with the timer def pomodoro_timer(work_min, short_break_min, long_break_min, cycles): for i in range(cycles): print(f"\nCycle {i+1} of {cycles}") countdown(work_min, "Work") if i < cycles - 1: print("\nStarting short break...") if handle_pause_stop(): return countdown(short_break_min, "Short Break") else: print("\nStarting long break...") if handle_pause_stop(): return countdown(long_break_min, "Long Break") if not repeat_or_end(): return def repeat_or_end(): user_input = input( "\nCycle finished. Would you like to repeat the cycle? (y/n): " ).lower() return user_input == "y" def get_valid_input(prompt): while True: try: value = int(input(prompt)) if value <= 0: raise ValueError return value except ValueError: print("Invalid input. Please enter a positive integer.") if __name__ == "__main__": work_minutes = get_valid_input("Enter work interval in minutes: ") short_break_minutes = get_valid_input("Enter short break interval in minutes: ") long_break_minutes = get_valid_input("Enter long break interval in minutes: ") cycles = get_valid_input("Enter the number of cycles: ") pomodoro_timer(work_minutes, short_break_minutes, long_break_minutes, cycles) ================================================ FILE: Pomodoro Timer/runtime.txt ================================================ Python 3.10.12 ================================================ FILE: QR Code Generator/advanceQrGenerator.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Aman Kumar # Version: 1.0.0 import qrcode from PIL import Image qr = qrcode.QRCode(version=1, error_correction=qrcode.ERROR_CORRECT_H, box_size=10, border=4) qr.add_data("https://github.com/king04aman/all-in-one-python-projects") qr.make(fit=True) img = qr.make_image(fill_color='blue', back_color='white') img.save('./advanceQR.png') ================================================ FILE: QR Code Generator/basicQrGenerator.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Aman Kumar # Version: 1.0.0 import qrcode as qr qrImg = qr.make("https://github.com/king04aman/All-In-One-Python-Projects/") qrImg.save('demo.png') ================================================ FILE: QR Code Generator/runtime.txt ================================================ python-3.10.7 ================================================ FILE: README.md ================================================

All-In-One-Python-Projects

![All-In-One-Python-Projects](https://socialify.git.ci/king04aman/all-in-one-python-projects/image?description=1&font=Jost&language=1&logo=https%3A%2F%2Fimages.weserv.nl%2F%3Furl%3Dhttps%3A%2F%2Favatars.githubusercontent.com%2Fu%2F62813940%3Fv%3D4%26h%3D250%26w%3D250%26fit%3Dcover%26mask%3Dcircle%26maxage%3D7d&name=1&owner=1&pattern=Floating%20Cogs&theme=Dark) [![BuiltByDev](https://forthebadge.com/images/badges/built-by-developers.svg)](https://github.com/king04aman) [![BuiltWithLov](https://forthebadge.com/images/badges/built-with-love.svg)](https://github.com/king04aman) [![MadeWithPy](https://forthebadge.com/images/badges/made-with-python.svg)](https://github.com/king04aman)
![Issues](https://img.shields.io/github/issues/king04aman/All-In-One-Python-Projects.svg) ![Contributors](https://img.shields.io/github/contributors/king04aman/All-In-One-Python-Projects.svg) ![SizeInBytes](https://img.shields.io/github/repo-size/king04aman/All-In-One-Python-Projects.svg) ![TopLanguage](https://img.shields.io/github/languages/top/king04aman/All-In-One-Python-Projects.svg) ![PullRequests](https://img.shields.io/github/issues-pr/king04aman/All-In-One-Python-Projects.svg)

Description

_All-In-One-Python-Projects is a collection of all scripts starting from very basic to advance scripts. This is your personal zone where you may search or add any new scripts that can simplify your or other developer's life and give them something to do when they're bored. Start producing exciting scripts that benefit the community._
## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. ## Prerequisites - Python 3.x ## Installing 1. Clone the repository to your local machine ```bash git clone https://github.com/king04aman/All-In-One-Python-Projects.git ``` 2. Change directory into the cloned repository ```bash cd All-In-One-Python-Projects/ ``` 3. Install the required libraries ```bash pip install -r requirements.txt ``` 4. Run the program using ```bash python3 .py ```

Contribution Guide

- Have a look at [Contributing Guidelines](CONTRIBUTING.md). - Take a look at the existing issues or create your own issues. - Avoid making pull request unless you are assigned with the issue. - Select the project on which you want to work or you can add your own project. - Create an issue with description on which project you want to work and wait for approval. - While making pull request add issue number with `#` (for example `#04`) - After approval fork this repository, add your changes then make pull request with issue number and wait for review. - Star this repository. 🌟

Awesome Contributors 🤩

Thanks go to these **Wonderful Contributors** ✨✨:

Project Maintainer


Aman Kumar

## License *This project is licensed under the MIT License - see the [LICENSE.md](LICENSE) file for details.*

🎉 😃 Happy Hacking 😃 🎉

================================================ FILE: Random Movie Selector/main.py ================================================ from imdb import IMDb import random class ChooseMovie(object): def __init__(self): self.cursor = IMDb() self.top250 = self.cursor.get_top250_movies() def __repr__(self): num = int(random.randint(0, 249)) return str(f"\n\n\t{num}: {self.top250[num]}\n\n") if __name__ == '__main__': print(ChooseMovie()) ================================================ FILE: Random Movie Selector/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Random Quotes Generator/quotes.py ================================================ from bs4 import BeautifulSoup import requests import csv url='http://quotes.toscrape.com' html=requests.get(url) bs=BeautifulSoup(html.text,'html.parser') try: csv_file=open('quote_list.csv','w') fieldnames=['quote','author','tags'] dictwriter=csv.DictWriter(csv_file,fieldnames=fieldnames) dictwriter.writeheader() while True: for quote in bs.findAll('div',{'class':'quote'}): text=quote.find('span',{'class':'text'}).text author=quote.find('small',{'class':'author'}).text tags=[] for tag in quote.findAll('a',{'class':'tag'}): tags.append(tag.text) dictwriter.writerow({'quote':text,'author':author,'tags':tags}) next=bs.find('li',{'class':'next'}) if not next: break html=requests.get(url+next.a.attrs['href']) bs=BeautifulSoup(html.text,'html.parser') except: print('Unknown Error!!!') finally: csv_file.close() ================================================ FILE: Random Quotes Generator/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Real-Time Cryptocurrency Price Tracker/Readme.md ================================================ # Cryptocurrency Price Tracker with CoinGecko API ## Project Overview The **Real-Time Cryptocurrency Price Tracker** is a Python script that allows users to retrieve real-time cryptocurrency prices, percentage price changes, and historical price data using the CoinGecko public API. The script also offers a simple visualization of historical price trends. Refer to [CoinGecko API](https://docs.coingecko.com/v3.0.1/reference/introduction) and [CoinGecko Coins List](https://api.coingecko.com/api/v3/coins/list) for more information. ## Features - **Real-Time Price Retrieval**: Input the name of a cryptocurrency (eg. bitcoin) to retrieve its current price in USD - **24-Hour Price Change**: Displays the 24-hour percentage change in price for the selected cryptocurrency - **Historical Price Data**: Retrieve historical price data for a specified number of days (eg. 1 day, 7 days, or 30 days) and visualize it in a chart - **Data Visualization**: Uses matplotlib to generate a line chart displaying the historical price data ## Technologies Used - **Python**: The core programming language used to build the script - **CoinGecko API**: A free API used to fetch cryptocurrency prices, percentage changes, and historical data - **Requests**: A Python library for making HTTP requests to the CoinGecko API - **Matplotlib**: A Python library used to visualize historical cryptocurrency price data in a line chart format - **Datetime**: Python datetime module is used to convert and handle timestamps when retrieving historical price data ## Prerequisites Before running the application, ensure you have the following: - [Python 3.x](https://www.python.org/downloads/) installed on your system - `requests` and `matplotlib` libraries are installed. Refer to `requirements.txt` for a specific version ================================================ FILE: Real-Time Cryptocurrency Price Tracker/main.py ================================================ import requests import matplotlib.pyplot as plt import datetime COINGECKO_API_URL = "https://api.coingecko.com/api/v3" def get_crypto_price(crypto_symbol): headers = {"accept": "application/json"} response = requests.get(f"{COINGECKO_API_URL}/simple/price", params={ 'ids': crypto_symbol, 'vs_currencies': 'usd', 'include_24hr_change': 'true' }, headers=headers) if response.status_code == 200: data = response.json() if crypto_symbol in data: price = data[crypto_symbol]['usd'] change_percentage = data[crypto_symbol]['usd_24h_change'] return price, change_percentage else: raise ValueError(f"Cryptocurrency '{crypto_symbol}' not found.") else: raise Exception(f"Failed to fetch data: {response.status_code} - {response.reason}") def get_historical_data(crypto_symbol, days): response = requests.get(f"{COINGECKO_API_URL}/coins/{crypto_symbol}/market_chart", params={ 'vs_currency': 'usd', 'days': days }) if response.status_code == 200: data = response.json() if 'prices' in data: return data['prices'] # Returns price data over the days else: raise ValueError(f"No historical data available for '{crypto_symbol}'.") else: raise Exception(f"Failed to fetch historical data: {response.status_code} - {response.reason}") def plot_historical_data(historical_data, crypto_symbol): dates = [datetime.datetime.fromtimestamp(item[0] / 1000) for item in historical_data] prices = [item[1] for item in historical_data] plt.figure(figsize=(10, 6)) plt.plot(dates, prices, marker='o', linestyle='-', color='b') plt.title(f'Historical Price Data for {crypto_symbol.capitalize()}') plt.xlabel('Date') plt.ylabel('Price (USD)') plt.xticks(rotation=45) plt.grid(True) plt.tight_layout() plt.show() def main(): crypto = input("Enter cryptocurrency symbol (eg. bitcoin, ethereum): ").lower() try: # Get real-time price and 24-hour change price, change = get_crypto_price(crypto) print(f"Current price of {crypto}: ${price}") print(f"24-hour change: {change:.2f}%") except ValueError as e: print(f"Error: {e}") return except Exception as e: print(f"Error fetching price data: {e}") return # Validate and get historical data while True: try: days = int(input("Enter the number of days for historical data (eg. 1, 7, 30): ")) if days <= 0: raise ValueError("The number of days must be a positive integer.") break except ValueError as e: print(f"Invalid input: {e}. Please enter a valid number.") try: historical_data = get_historical_data(crypto, days) print("Historical data retrieved successfully.") plot_historical_data(historical_data, crypto) except ValueError as e: print(f"Error: {e}") except Exception as e: print(f"Error fetching historical data: {e}") if __name__ == "__main__": main() ================================================ FILE: Real-Time Cryptocurrency Price Tracker/requirements.txt ================================================ requests==2.32.3 matplotlib==3.9.2 ================================================ FILE: Real-Time Cryptocurrency Price Tracker/runtime.txt ================================================ python-3.9.20 ================================================ FILE: Recipe Finder with Meal Planner/Readme.md ================================================ # Meal Planner with Spoonacular API ## Project Overview The **Meal Planner** is a command-line application that helps users plan their meals based on available ingredients. By using the [Spoonacular API](https://spoonacular.com/food-api), users can search for recipes, view recipe details, and generate meal plans for the week. It also provides important details like cooking time and servings for each recipe. This tool makes meal planning efficient and fun while minimizing food waste. ## Features - **Search Recipes by Ingredients**: Input the ingredients you have, and the app will find up to 10 recipes that include those ingredients. - **View Recipe Details**: Get detailed information about the selected recipes, including preparation time and servings. - **Plan Meals for the Week**: Generate a random meal plan for up to 7 days based on the available recipes. - **Interactive User Interface**: Provides a simple, interactive command-line interface for easy input and output. ## Technologies Used - **Python**: Core programming language used to build the app. - **Spoonacular API**: API used for fetching recipes and detailed information about them. - **Requests**: Python library for making HTTP requests to the Spoonacular API. ## Prerequisites Before running the application, ensure you have the following: - [Python 3.x](https://www.python.org/downloads/) installed on your system. - `requests` library installed. You can install it using: ================================================ FILE: Recipe Finder with Meal Planner/main.py ================================================ import requests import random # Replace 'your_api_key_here' with your actual Spoonacular API key API_KEY = "74de4b7826b74b70b4d3a0fe3191239a" BASE_URL = "https://api.spoonacular.com/recipes" def find_recipes(ingredients): """Search for recipes based on ingredients using the Spoonacular API.""" url = f"{BASE_URL}/findByIngredients" params = { 'ingredients': ','.join(ingredients), 'number': 10, # Get up to 10 recipes 'apiKey': API_KEY } response = requests.get(url, params=params) if response.status_code == 200: recipes = response.json() return [(recipe['title'], recipe['id']) for recipe in recipes] else: print(f"Error: {response.status_code}") return [] def get_recipe_details(recipe_id): """Get details of a specific recipe by its ID.""" url = f"{BASE_URL}/{recipe_id}/information" params = {'apiKey': API_KEY} response = requests.get(url, params=params) if response.status_code == 200: return response.json() else: print(f"Error: {response.status_code}") return None def plan_meals(ingredients): """Plan meals for the week based on available ingredients.""" recipes = find_recipes(ingredients) if not recipes: return "No recipes found with the given ingredients." meals = random.sample(recipes, min(7, len(recipes))) return meals def user_interface(): print("Welcome to the Meal Planner!") print("Enter the ingredients you have, separated by commas:") ingredients = input().split(",") ingredients = [ingredient.strip().lower() for ingredient in ingredients] print("\nSearching for recipes based on your ingredients...\n") recipes = find_recipes(ingredients) if recipes: print(f"Found the following recipes with your ingredients:") for i, (title, _) in enumerate(recipes): print(f"{i + 1}. {title}") else: print("No recipes found with the given ingredients.") print("\nDo you want to plan meals for the week with these ingredients? (yes/no)") if input().strip().lower() == "yes": meals = plan_meals(ingredients) print("\nHere is your meal plan for the week:") for i, (title, recipe_id) in enumerate(meals, 1): print(f"Day {i}: {title}") recipe_details = get_recipe_details(recipe_id) if recipe_details: print(f" - Ready in: {recipe_details['readyInMinutes']} minutes") print(f" - Servings: {recipe_details['servings']}") else: print("No meal plan generated.") if __name__ == "__main__": user_interface() ================================================ FILE: Recipe Finder with Meal Planner/runtime.txt ================================================ python-3.9.18 ================================================ FILE: Resume Builder/README.md ================================================ # Interactive Resume Builder This Python project is a command-line interface (CLI) tool for building professional resumes. The tool allows users to interactively input various sections of their resume, such as contact information, work experience, education, skills, projects, certifications, and achievements. The resume is then formatted and exported as a PDF file. ## Features - Interactive CLI for entering resume data (contact info, work experience, education, etc.). - Ability to add, update, and modify multiple resume sections. - Automatically generates a well-formatted PDF resume. - Includes functionality to add detailed descriptions for work experience and projects. - Supports multiple certifications and achievements. - Simple and intuitive navigation using `prompt_toolkit` for menu interactions. ## Prerequisites - Python 3.x must be installed on your system. ## Setup Instructions 1. **Clone the repository**: ```bash git clone https://github.com/username/your-repo.git cd your-repo ``` 2. **Create and activate a virtual environment**: For macOS/Linux: ```bash python3 -m venv venv source venv/bin/activate ``` For Windows: ```bash python -m venv venv venv\Scripts\activate ``` 3. **Install the necessary dependencies**: ```bash pip install -r requirements.txt ``` 4. **Run the application**: ```bash python resume_builder.py ``` ## Usage - **Interactive Menu**: The program presents a menu to select which section of the resume you want to edit or add. - **PDF Generation**: Once all sections are filled, you can generate a PDF with all the input data. - **Options**: - Add or edit Contact Information, Work Experience, Education, Skills, Projects, Certifications, and Achievements. - Generate the PDF after completing the resume input. ## Dependencies - `geopy`: For any geographic distance calculation (if needed for future features). - `prompt_toolkit`: A library for building beautiful command-line applications. - `fpdf`: A library for generating PDF documents from the entered resume data. ## License This project is licensed under the MIT License. ================================================ FILE: Resume Builder/requirements.txt ================================================ geopy==2.2.0 prompt_toolkit==3.0.8 fpdf==1.7.2 ================================================ FILE: Resume Builder/resume_builder.py ================================================ from prompt_toolkit import prompt from prompt_toolkit.shortcuts import button_dialog from fpdf import FPDF import os # To clear the terminal after selecting a section def clear_screen(): os.system('cls' if os.name == 'nt' else 'clear') # Resume data storage resume_data = { "contact_info": {}, "experience": [], "education": [], "skills": [], "projects": [], "certifications": [], "achievements": [] } # Function to navigate back to the main menu def back_to_menu(): print("\nReturning to main menu...") # Add contact information def add_contact_info(): clear_screen() print("Enter Contact Information") resume_data["contact_info"]["name"] = prompt("Name: ") resume_data["contact_info"]["email"] = prompt("Email: ") resume_data["contact_info"]["phone"] = prompt("Phone: ") resume_data["contact_info"]["address"] = prompt("Address: ") resume_data["contact_info"]["linkedin"] = prompt("LinkedIn URL: ") resume_data["contact_info"]["github"] = prompt("GitHub URL: ") back_to_menu() # Add work experience def add_experience(): while True: clear_screen() print("Enter Work Experience") experience = { "title": prompt("Job Title: "), "company": prompt("Company: "), "start_date": prompt("Start Date (e.g., June 2024): "), "end_date": prompt("End Date (or type 'Present' if still working): "), "details": prompt("Details (comma-separated): ").split(',') } resume_data["experience"].append(experience) # Ask user if they want to add more experience entries more = prompt("Do you want to add more work experience? (yes/no): ").strip().lower() if more == "no": break back_to_menu() # Add education details def add_education(): while True: clear_screen() print("Enter Education Information") education = { "degree": prompt("Degree (e.g., B.Tech in CSE): "), "institution": prompt("Institution: "), "start_year": prompt("Start Year: "), "end_year": prompt("End Year: ") } resume_data["education"].append(education) # Ask user if they want to add more education entries more = prompt("Do you want to add more education? (yes/no): ").strip().lower() if more == "no": break back_to_menu() # Add skills def add_skills(): clear_screen() print("Enter Skills (comma-separated): ") resume_data["skills"] = prompt("Skills: ").split(',') back_to_menu() # Add projects def add_projects(): while True: clear_screen() print("Enter Projects Information") project = { "name": prompt("Project Name: "), "description": prompt("Description: "), "technologies": prompt("Technologies Used: ") } resume_data["projects"].append(project) # Ask if they want to add more projects more = prompt("Do you want to add more projects? (yes/no): ").strip().lower() if more == "no": break back_to_menu() # Add certifications def add_certifications(): while True: clear_screen() print("Enter Certifications") certification = { "name": prompt("Certification Name: "), "provider": prompt("Provider: "), "year": prompt("Year: ") } resume_data["certifications"].append(certification) more = prompt("Do you want to add more certifications? (yes/no): ").strip().lower() if more == "no": break back_to_menu() # Add achievements def add_achievements(): while True: clear_screen() print("Enter Achievements") achievement = prompt("Achievement: ") resume_data["achievements"].append(achievement) more = prompt("Do you want to add more achievements? (yes/no): ").strip().lower() if more == "no": break back_to_menu() # PDF Generation class class ResumePDF(FPDF): def header(self): self.set_font('Arial', 'B', 14) self.cell(0, 10, resume_data["contact_info"]["name"], 0, 1, 'C') self.set_font('Arial', 'I', 12) self.cell(0, 10, resume_data["contact_info"]["email"], 0, 1, 'C') self.cell(0, 10, resume_data["contact_info"]["phone"], 0, 1, 'C') self.cell(0, 10, resume_data["contact_info"]["address"], 0, 1, 'C') def add_section(self, title, content): self.set_font('Arial', 'B', 12) self.cell(0, 10, title, 0, 1) self.set_font('Arial', '', 11) for line in content: self.cell(0, 10, line, 0, 1) # PDF Generation def generate_pdf(): pdf = ResumePDF() pdf.add_page() # Contact Information contact = resume_data["contact_info"] pdf.set_font('Arial', 'B', 12) pdf.cell(0, 10, f"{contact['name']} - {contact['email']}", 0, 1) pdf.cell(0, 10, f"Phone: {contact['phone']} - Address: {contact['address']}", 0, 1) pdf.cell(0, 10, f"LinkedIn: {contact.get('linkedin', 'N/A')} - GitHub: {contact.get('github', 'N/A')}", 0, 1) # Work Experience pdf.set_font('Arial', 'B', 12) pdf.cell(0, 10, "Experience", 0, 1) pdf.set_font('Arial', '', 11) for exp in resume_data["experience"]: details = ', '.join(exp["details"]) pdf.cell(0, 10, f"{exp['title']} at {exp['company']} ({exp['start_date']} - {exp['end_date']})", 0, 1) pdf.multi_cell(0, 10, f"Responsibilities: {details}") # Education pdf.set_font('Arial', 'B', 12) pdf.cell(0, 10, "Education", 0, 1) pdf.set_font('Arial', '', 11) for edu in resume_data["education"]: pdf.cell(0, 10, f"{edu['degree']} from {edu['institution']} ({edu['start_year']} - {edu['end_year']})", 0, 1) # Skills pdf.set_font('Arial', 'B', 12) pdf.cell(0, 10, "Skills", 0, 1) pdf.multi_cell(0, 10, ', '.join(resume_data["skills"])) # Projects pdf.set_font('Arial', 'B', 12) pdf.cell(0, 10, "Projects", 0, 1) pdf.set_font('Arial', '', 11) for proj in resume_data["projects"]: pdf.cell(0, 10, proj["name"], 0, 1) pdf.multi_cell(0, 10, proj["description"]) pdf.cell(0, 10, f"Technologies Used: {proj['technologies']}", 0, 1) # Certifications pdf.set_font('Arial', 'B', 12) pdf.cell(0, 10, "Certifications", 0, 1) pdf.set_font('Arial', '', 11) for cert in resume_data["certifications"]: pdf.cell(0, 10, f"{cert['name']} by {cert['provider']} ({cert['year']})", 0, 1) # Achievements pdf.set_font('Arial', 'B', 12) pdf.cell(0, 10, "Achievements", 0, 1) pdf.set_font('Arial', '', 11) for ach in resume_data["achievements"]: pdf.cell(0, 10, ach, 0, 1) # Save PDF pdf_output_path = "generated_resume.pdf" pdf.output(pdf_output_path) # Auto-open PDF after generation os.system(f"start {pdf_output_path}" if os.name == "nt" else f"open {pdf_output_path}") print(f"Resume generated: {pdf_output_path}") # Main Menu using button_dialog from prompt_toolkit def interactive_menu(): while True: clear_screen() choice = button_dialog( title="Interactive Resume Builder", text="Please choose a section to modify:", buttons=[ ("Contact Info", 1), ("Work Experience", 2), ("Education", 3), ("Skills", 4), ("Projects", 5), ("Certifications", 6), ("Achievements", 7), ("Generate PDF", 8), ("Exit", 9) ] ).run() if choice == 1: add_contact_info() elif choice == 2: add_experience() elif choice == 3: add_education() elif choice == 4: add_skills() elif choice == 5: add_projects() elif choice == 6: add_certifications() elif choice == 7: add_achievements() elif choice == 8: generate_pdf() elif choice == 9: break # Start the program if __name__ == "__main__": interactive_menu() ================================================ FILE: Simple Assistant/assistant.py ================================================ import pyttsx3,datetime,os,random,requests import wikipedia,webbrowser,sys,pywhatkit import speech_recognition as sr engine = pyttsx3.init('sapi5') voices = engine.getProperty("voices") engine.setProperty('voice',voices[1].id) # To convdert text into voice def speak(audio): engine.say(audio) print(audio) engine.runAndWait() # To convert voice into text def takecommand(): r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source,timeout=2,phrase_time_limit=5) try: print("Recognizing...") query = r.recognize_google(audio,language='en-in') except Exception: speak("Can you please say that again ... ") return 'none' return query # To wish def wish(): hour = int(datetime.datetime.now().hour) if hour >=0 and hour<=12: speak("Good morning Sir") elif hour>12 and hour<16: speak("Good afternoon Sir") elif hour>16 and hour<22: speak("Good evening Sir") speak("I am jarvis, Please tell me how can i help you !") if __name__ == "__main__": wish() if 1: query = takecommand().lower() if 'open notepad' in query: npath = 'C:\\Windows\\System32\\notepad.exe' os.startfile(npath) speak("Please wait ! While I am opening notepad for you!") elif "open cmd" in query: os.system('start cmd') speak("Opening Command Promte") elif "play music" in query: music_dir = 'D:\\Songs' songs = os.listdir(music_dir) rd = random.choice(songs) os.startfile(os.path.join(music_dir,rd)) speak("Playing Music") elif "ip address" in query: ip = requests.get("https://api.ipify.org").text speak(f"Your Ip address is {ip}") elif 'wikipedia' in query: speak("Searching in wikipedia") query = query.replace("wikipedia","") results = wikipedia.summary(query,sentences=5) speak(f"according to wikipedia {results}") elif "open youtube" in query: webbrowser.open('www.youtube.com/') elif "open instagram" in query: webbrowser.open('www.instagram.com/') elif "open facebook" in query: webbrowser.open('www.facebook.com/') elif "open twitter" in query: webbrowser.open('www.twitter.com/') elif "open google" in query: speak('Sir what should i search on google ! ') varg = takecommand().lower() webbrowser.open(varg) # elif 'send message' in query: # pywhatkit.sendwhatmsg("+919988776655",'Hello I am Jarvis ! How are you Sir ?',18,33,10,True) # elif 'play song on youtube' in query: # speak("Which song would you like to play on youtube ? ") # song = takecommand().lower() # pywhatkit.playonyt(song) # elif 'play video' in query: # speak("Which video would you like to play on youtube ? ") # vsong = takecommand().lower() # pywhatkit.playonyt(vsong) elif 'nothing' in query or 'abort' in query or 'stop' in query: speak('okay') speak('Bye Sir, have a good day.') sys.exit() elif 'hello' in query: speak('Hello Sir') elif 'bye' in query: speak('Bye Sir, have a good day.') sys.exit() elif "what\'s up" in query or 'how are you' in query: stMsgs = ['Just doing my thing!', 'I am fine!', 'Nice!', 'I am nice and full of energy'] speak(random.choice(stMsgs)) ================================================ FILE: Simple Assistant/raj_mistry01/Readme.md ================================================ # Jarvis - A Personal Voice Assistant 🗣️💻 This **Jarvis Personal Assistant** is a Python-based virtual assistant that can execute commands, automate tasks, and provide information at your request. It can help you manage files, open applications, search Wikipedia, forecast weather, and much more—all through voice commands. ## 🚀 Features 1. **Voice & Text Interaction** - Provides **voice recognition** using Google Speech Recognition API. - Users can **switch to text mode** if speech recognition fails. 2. **Application Management** - Open or close **Notepad** and **Command Prompt**. - Manage system **battery levels** with alerts and suggestions. 3. **Information Retrieval** - Get **Wikipedia summaries** for any topic. - **Weather forecasts** by city or location-based. - Check your **IP address** using an online API. 4. **Entertainment & Media** - Search for **movie details** via IMDb, including cast, plot, and ratings. - Open **YouTube** and automate subscriptions. 5. **System Control** - Adjust **volume controls**: Increase, decrease, or mute. - Minimize or maximize windows using **keyboard automation**. - Track **internet speed** with Speedtest integration. 6. **Utility Features** - Control **Webcam** access and capture videos. - Perform calculations using **Wolfram Alpha**. - Automatically **open websites** using Chrome. - Monitor **system processes** and terminate them on command. --- ## 🔧 Setup Instructions 1. **Clone the Repository** ```bash git clone https://github.com/yourusername/jarvis-assistant.git cd jarvis-assistant ``` 2. **Install Dependencies** Install all necessary Python packages using: ```bash pip install -r requirements.txt ``` 3. **Add Paths for Applications** Set the paths for: - **Chrome browser**: `"C:/Program Files/Google/Chrome/Application/chrome.exe"` - **Notepad**: `"C:/Windows/System32/notepad.exe"` - **Visual Studio Code** (optional): Adjust the path as per your installation. 4. **Get API Keys** - **OpenWeather API**: [Sign up here](https://openweathermap.org/) and replace `apiKey` in the code. - **Wolfram Alpha API**: Get an API key [here](https://products.wolframalpha.com/api/). --- ## 🧑‍💻 Usage Instructions 1. **Launch the Assistant** Run the script: ```bash python jarvis.py ``` 2. **Speak Commands**: - "Open Notepad" – Launches Notepad. - "What is the weather report?" – Gives the weather of your current location. - "Search for Titanic on Wikipedia" – Provides a brief Wikipedia summary. - "Close Command Prompt" – Terminates the Command Prompt if running. - "What's my IP address?" – Provides your public IP address. 3. **Text Mode** If the voice input isn't recognized, type your queries when prompted. 4. **Pause or Stop Listening**: - Say **"Stop listening"**: Pauses the assistant. - Resume by pressing **Ctrl + Alt + K**. - Say **"No query, thanks"** to exit the assistant. --- ## 🌦️ Example Queries - **"How are you, Jarvis?"** → Jarvis responds and continues the conversation. - **"Open Command Prompt"** → Opens the Command Prompt window. - **"Mute the volume"** → Mutes system volume. --- ## 🎯 Known Issues and Limitations - Some queries require accurate phrasing. - Voice recognition may fail in noisy environments. - Web automation depends on having Chrome installed. - Weather reports return temperature in **Kelvin** by default (can be adjusted). --- ## 💡 Future Improvements - Add **Gmail** integration to send emails. - Support for **natural conversations** with chat history. - **Alarm feature** implementation. --- ## 🤖 Contribution Feel free to submit pull requests or report bugs/issues. Contributions are welcome to make this assistant smarter and more responsive! --- ## 🛠️ Prerequisites - **Python 3.7+** - Required Packages (install via `pip`): ```bash pip install -r requirements.txt --- ## 🛠️ Api Credits Wolfram Api OpenWheather Api - **Python 3.7+** - Required Packages (install via `pip`): ```bash pip install -r requirements.txt Enjoy using **Jarvis Personal Assistant**! 😊 ================================================ FILE: Simple Assistant/raj_mistry01/main.py ================================================ import pyttsx3 import wmi import speech_recognition as sr import datetime import wolframalpha import subprocess as sp import time import pyautogui import webbrowser as web import random import imdb import psutil import requests import wikipedia import pywhatkit import smtplib import sys import keyboard import speedtest import cv2 import os import numpy as np engine = pyttsx3.init('sapi5') voices = engine.getProperty("voices") engine.setProperty('voices',voices[0].id) runnigprocesslist = [] f = wmi.WMI() flag = 0 def speak(audio) : print("Jarvis : ",end="") engine.say(audio) print(audio) engine.runAndWait() def takecommand() : r = sr.Recognizer() with sr.Microphone() as source : print("Listening ...") r.adjust_for_ambient_noise(source) r.pause_threshold =1 audio = r.listen(source,phrase_time_limit=5) try : print("Recongnizing ..") text = r.recognize_google(audio,language = "en-in") print("User said : "+text) except Exception as e : print("Say that again : ") return "none" return text def startlistening(): print("Started Listening : ") def pauseListening() : print("Paused Listening :") def weatherforecast(city) : apiKey = "apiKey" res = requests.get(f"openWeatherApiEndpoint").json() weather_ = res["weather"][0]["main"] temp = res["main"]["temp"] feels_like = res["main"]["feels_like"] return weather_,temp,feels_like def wish() : hour = int(datetime.datetime.now().hour) if hour >= 0 and hour <= 12 : speak("Good morning :") elif hour > 12 and hour <= 18 : speak("Good afternoon :") else : speak("Good evening : ") speak("I am jarvis ,sir how can I assist you?") # def sendEmail(to,content) : # server = smtplib.SMTP("smtp.gmail.com",587) # server.ehlo() # server.starttls() # server.login("emailId","yourpswd") # server.sendmail("emailId","toemail") # server.close() if __name__ == "__main__" : wish() def main() : global runnigprocesslist tries = 0 query = "" flag_ = 0 flagForText = 0 while True: if tries < 3 : if flag_ == 0 : query = takecommand().lower() tries += 1 else : if flagForText == 1: query = input("(Prees V + Enter to turn voice chat again)Enter your query in text : ") if query == "V" : flag_ = 0 flagForText = 0 pass else : pass else : flag_ = 0 pass if "stop listening" in query : pauseListening() speak("Press ctrl+alt+k to continue listening.") break elif "open notepad" in query : tries = 0 path = "" # path to notepad speak("Opening NOtepad sir.") os.startfile(path) elif "close notepad" in query : tries = 0 for process in f.Win32_Process() : runnigprocesslist.append(process.Name) if "Notepad.exe" in runnigprocesslist : speak("Closing the notepad.") os.system("taskkill /f /im notepad.exe") flag = 1 runnigprocesslist = [] else : speak("Notepad is not opened.") elif "stop listening" in query : tries = 0 speak("Press ctrl+alt+p to pause the listening") elif "how are you jarvis" in query : tries = 0 speak("I am fine sir , What about you ?? Sir.") query = takecommand().lower() if "not feeling good" or "sad" or "bad day" in query : speak("What happend sir ,Please Tell me , May I help you ?") query = takecommand().lower() if "disease" in query : query = query.replace(query,"drreddys.com",1) path = "" # path to chrome web.register("chrome",None,web.BackgroundBrowser(path)) web.get("chrome").open_new(query) else : pass elif "good" or "feeling happy" in query : speak("Ok sir , It seems to be nice to hear.") elif "open command prompt" in query : tries = 0 speak("Opening the command propmpt.") os.system("start cmd") elif "close command prompt" in query : tries = 0 for process in f.Win32_Process() : runnigprocesslist.append(process.Name) if "cmd.exe" in runnigprocesslist : speak("Closing the command propmt.") os.system("taskkill /f /im cmd.exe") flag = 1 runnigprocesslist = [] else : speak("CMD is not opened.") pass elif "clear the chat" in query : tries = 0 os.system("cls") elif "are you forget to wish me" in query or "Wish me again" in query : tries = 0 wish() elif "open Webcamera" in query : tries = 0 cap = cv2.VideoCapture(0) while True : ret , img = cap.read() cv2.imshow("webcam",img) k = cv2.waitKey(50) if k == 27 : break cap.release() cv2.destroyAllWindows() elif "open camera" in query : tries = 0 speak("Opening Camera sir") sp.run("start microsoft.windows.camera:",shell= True) elif "close camera" in query : tries = 0 for process in f.Win32_Process() : runnigprocesslist.append(process.Name) if "WindowsCamera.exe" in runnigprocesslist : speak("Closing the camera.") flag = 1 os.system("taskkill /f /im WindowsCamera.exe") runnigprocesslist = [] else : speak("Camera is not opened.") elif "calculate" in query : # api = "apiKey" client = wolframalpha.Client(api) query = takecommand().lower() ind = query.split().index("calculate") text = query.split()[ind+1:] result = client.query(" ".join(text)) try : ans = next(result.results).text speak("The answer is " + ans) except StopIteration : speak("I could not find it , Please say it again.") elif "ip address" in query : tries = 0 ip = requests.get("apiKeyOfipyfyConfig").json() speak("Your Ip address is : " + ip["ip"]) elif "wikipedia" in query : tries = 0 speak("Searching in the wikipedia") query = query.replace("wikipedia","") results = wikipedia.summary(query,sentences=2) speak("According to wikipedia ") speak(results) print(results) elif "open visual code" in query : tries = 0 path = "" # path to Vscode.exe os.startfile(path) elif "weather report" in query : tries = 0 ipAdd = requests.get("apiKeyOfipyfyConfig").json() ipnum = ipAdd["ip"] city = requests.get(f"apiKeyOfipyfyConfigEndpoint").text weather , temp , feels_like = weatherforecast(city) speak(f"The weather report talks about {weather}.") speak(f"The temparature is {temp} kelvin.") speak(f"It feels like {feels_like} kelvin.") elif "weather of my city" in query : tries = 0 speak("Sir tell me your city name : ") city = input("Enter the name of your city : ") speak(f"Getting the weather of {city} : ") weather , temp , feels_like = weatherforecast(city) speak(f"The weather report talks about {weather}.") speak(f"The temparature is {temp} kelvin.") speak(f"It feels like {feels_like} kelvin.") elif ".com" in query: tries = 0 path = "" # path to chrome web.register("chrome",None,web.BackgroundBrowser(path)) web.get("chrome").open_new(query) elif "movie" in query : movieDb = imdb.IMDb() speak("Input the name of movie in text") movieName = input("Enter the name : ") movies = movieDb.search_movie(movieName) speak("Searching for... " + movieName) speak("I found these") for movie in movies : title = movie["title"] year = movie["year"] info = movie.getID() movieInfo = movieDb.get_movie(info) rating = movieInfo["rating"] cast = movieInfo["cast"] actor = cast[0:5] plot = movieInfo.get('plot outline','plot summary not available') speak(f"{title} movie in {year} has an imdb rating of {rating}.") speak(f"It has a cast of {actor} . The plot of the movie is {plot}. ") # elif "send message" in query: # tries = 0 # pywhatkit.sendwhatmsg("tosendPhoneNum","Hi raj",2,25) # elif "email" in query : # tries = 0 # try : # speak("What should i say") # content = takecommand().lower() # to = "toEmailId" # sendEmail(to,content) # except Exception as e : # print(e) elif "how much battery is left" in query or "power is left" in query or "battery" in query : tries = 0 battery = psutil.sensors_battery() percentage = battery.percent speak(f"Sir your computer system has left {percentage}% battery power.") if percentage <= 15 : speak("Sir you should plug in charger.") elif percentage >=15 and percentage <= 35 : speak("Sir it is enough power to run on , but it is advisable to turn on battery saver made.") speak("Sir Would you like to turn on battery saver mode?") query = takecommand().lower() if "yes" in query : pyautogui.press("win+A") else : pass elif percentage >= 35 and percentage <= 60 : speak("Sir you should we have enough battery power.") elif "turn on chat mode" in query or "chat mode" in query or "chat" in query: tries = 0 flag_ = 1 flagForText = 1 elif "subscribe the coder" in query or "subscribe" in query: tries = 0 speak("Whoever using this my created basic voice assistant jarvis , I am thankful , Subscribe to my channel") speak("Firstly go to Youtube") path = "pathtoChrome``" # path to chrome web.register("chrome",None,web.BackgroundBrowser(path)) web.get("chrome").open_new("https://www.youtube.com/") speak("Click on the search bar") pyautogui.moveTo(517,78,1) pyautogui.click(x=517,y=78,clicks=1,interval=0,button='left') speak("raj_mistry01 is username.") pyautogui.typewrite("https://www.youtube.com/@raj_mistry01",0.1) time.sleep(1) speak("Press Enter") pyautogui.press("enter") speak("Here you will subscribe the channel.") pyautogui.moveTo(718,602,1) speak("Click here to subcribe") pyautogui.click(x=718,y=602,clicks=1,interval=0,button='left') speak("Thank you for the subscribing Me🙏") elif "volume up" in query : tries = 0 pyautogui.press("volumeup") elif "volume down" in query : tries = 0 pyautogui.press("volumedown") elif "mute the volume" in query : tries = 0 pyautogui.press("volumemute") elif "turn on the volume" in query : tries = 0 pyautogui.press("volumemute") elif "minimise the window" in query: tries = 0 pyautogui.moveTo(1774,32,2) pyautogui.click(1774,32) elif "maximize the window" in query : tries = 0 pyautogui.moveTo(763,1054,2) pyautogui.click(763,1054) elif "internet speed" in query : tries = 0 st = speedtest.Speedtest() download = st.download() up = st.upload() speak(f"Sir we have {download} bits downloading speed per second and {up} bits downloading speed per second.") elif "no query thanks" in query : tries = 0 speak("Thanks for using me sir , have a good day.") sys.exit() elif "alarm" in query or "set alarm" in query : pass speak("Sir do you have any other work : ") else : speak("Sir I am unable to recognize the speech.") speak("Sir it is better to write query in text.") query = input("Enter the query : ") query = query.lower() tries = 0 flag_ = 1 flagForText = 0 main() ================================================ FILE: Simple Assistant/raj_mistry01/requirements.txt ================================================ pyttsx3 wmi SpeechRecognition wolframalpha numpy pyautogui requests wikipedia-api pywhatkit smtplib3 psutil keyboard speedtest-cli opencv-python imdbpy ================================================ FILE: Simple Assistant/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Snake-Game/README.md ================================================ # Snake Game 🐍 A classic Snake Game built using Python. Control the snake, collect food, and try to achieve the highest score without colliding with the walls or yourself. ## Features - Interactive gameplay. - Score tracking. - Simple and user-friendly interface. ## Installation 1. Clone this repository: ```bash git clone 2. Navigate the project folder ```bash cd snake-game 3. Run the game ```bash python snake_game.py # How to Play 1. Use Arrow Keys to control the direction of the snake: 1. Up: Move up. 2. Down: Move down. 3. Left: Move left. 4. Right: Move right. 2. Collect food to increase your score. 3. Avoid colliding with: 1. Walls 2. The snake’s body. 4. Goal: Achieve the highest score possible! # Technologies Used Python ================================================ FILE: Snake-Game/Snake.py ================================================ from turtle import Turtle, Screen STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)] MOVE_DISTANCE = 20 UP = 90 DOWN = 270 RIGHT = 0 LEFT = 180 class Snake: def __init__(self): self.segments = [] self.x = 0 self.create_snake() self.head = self.segments[0] def create_snake(self): for position in STARTING_POSITIONS: self.add_segment(position) def add_segment(self, position): new_segment = Turtle("square") new_segment.color("white") new_segment.penup() new_segment.goto(position) self.segments.append(new_segment) def reset(self): for seg in self.segments: seg.goto(1000, 1000) self.segments.clear() self.create_snake() self.head = self.segments[0] def extend(self): self.add_segment(self.segments[-1].position()) def move(self): for seg_num in range(len(self.segments)-1, 0,-1): new_x = self.segments[seg_num-1].xcor() new_y = self.segments[seg_num - 1].ycor() self.segments[seg_num].goto(new_x, new_y) self.head.forward(MOVE_DISTANCE) def up(self): if self.head.heading() != DOWN: self.head.setheading(UP) def down(self): if self.head.heading() != UP: self.head.setheading(DOWN) def left(self): if self.head.heading() != RIGHT: self.head.setheading(LEFT) def right(self): if self.head.heading() != LEFT: self.head.setheading(RIGHT) ================================================ FILE: Snake-Game/data.py ================================================ from scoreboard import Score score = Score() HighScore = score.high_score ================================================ FILE: Snake-Game/data.txt ================================================ 5 ================================================ FILE: Snake-Game/food.py ================================================ from turtle import Turtle import random class Food(Turtle): def __init__(self): super().__init__() self.shape("circle") self.penup() self.shapesize(stretch_wid=0.5, stretch_len=0.5) self.color("blue") self.speed("fastest") self.refresh() def refresh(self): random_x = random.randrange(-270,270) random_y = random.randrange(-270, 270) self.goto(random_x, random_y) ================================================ FILE: Snake-Game/main.py ================================================ from turtle import Turtle, Screen import time from food import Food from Snake import Snake from scoreboard import Score screen = Screen() screen.setup(width=600, height=600) screen.title("My Snake Game") screen.bgcolor("black") screen.tracer(0) snake = Snake() food = Food() score = Score() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.right, "Right") screen.onkey(snake.left, "Left") is_game_on = True while is_game_on: screen.update() time.sleep(0.1) snake.move() # collision with food if snake.head.distance(food) < 15: food.refresh() snake.extend() score.increase_score() # collision with wall if snake.head.xcor() < -280 or snake.head.xcor() > 280 or snake.head.ycor() < -280 or snake.head.ycor() > 280: score.reset() data = str(score.high_score) with open("data.txt", mode="w") as file: file.write(data) snake.reset() # collision with wall for segment in snake.segments[1:]: if snake.head.distance(segment) < 10: score.reset() data = str(score.high_score) with open("data.txt", mode="w") as file: file.write(data) snake.reset() screen.exitonclick() ================================================ FILE: Snake-Game/scoreboard.py ================================================ from turtle import Turtle class Score(Turtle): def __init__(self): self.score = 0 with open("data.txt") as file: self.HighScore = int(file.read()) self.high_score = self.HighScore super().__init__() self.color("white") self.penup() self.goto(0, 265) self.hideturtle() self.update_score() def update_score(self): self.clear() self.write(f"Score: {self.score} High Score:{self.high_score}", align='center', font=('Arial', 24, 'normal')) def reset(self): if self.score > self.high_score: self.high_score = self.score self.score = 0 self.update_score() def increase_score(self): self.score += 1 self.update_score() # def game_over(self): # self.goto(0, 0) # self.write("GAME OVER", align='center', font=('Arial', 24, 'normal')) ================================================ FILE: Speech To Text/main.py ================================================ import speech_recognition def record_voice(): microphone = speech_recognition.Recognizer() with speech_recognition.Microphone() as live_phone: microphone.adjust_for_ambient_noise(live_phone) print("I'm trying to hear you: ") audio = microphone.listen(live_phone) try: phrase = microphone.recognize_google(audio, language='en') return phrase except speech_recognition.UnkownValueError: return "I didn't understand what you said" if __name__ == '__main__': phrase = record_voice() with open('you_said_this.txt','w') as file: file.write(phrase) print('The last sentence you spoke was saved in you_said_this.txt') ================================================ FILE: Speech To Text/requirements.txt ================================================ PyAudio==0.2.11 SpeechRecognition==3.8.1 ================================================ FILE: Speech To Text/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Spell Checker/main.py ================================================ from textblob import TextBlob t = 1 while t: a = input("Enter the word to be checked:- ") print("Original text: "+str(a)) b = TextBlob(a) print("Corrected text: "+str(b.correct())) t = int(input("Try Again? 1 : 0 ")) ================================================ FILE: Spell Checker/requirements.txt ================================================ textblob==0.17.1 ================================================ FILE: Spell Checker/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Telegram Bot/main.py ================================================ # Importing modules import os, requests from apscheduler.schedulers.background import BackgroundScheduler import telebot # Golbal Variables CITY_NAME = "Delhi,IN" # Get Telegram Bot Token From Here: https://telegram.me/BotFather BOT_TOKEN = os.environ['BOT_TOKEN'] # Get Your API Key From Here: https://openweathermap.org/api WEATHER_API_KEY = os.environ['WEATHER_API_KEY'] scheduler = BackgroundScheduler() # Initialize bot object bot = telebot.TeleBot(BOT_TOKEN) # get weather data def getWeather(): url = f"https://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&appid={WEATHER_API_KEY}" response = requests.get(url) weather_data = response.json() weather_text = "" if weather_data['cod'] == 200: weather_text += f"City : {weather_data['name']}, {weather_data['sys']['country']}\n" weather_text += f"Coordinate : {weather_data['coord']['lon']} °N, {weather_data['coord']['lat']} °E\n" weather_text += f"Weather : {weather_data['weather'][0]['main']}\n" weather_text += f"Temperature : {weather_data['main']['temp']} °F\n" weather_text += f"Pressure : {weather_data['main']['pressure']} hPa\n" weather_text += f"Humidity : {weather_data['main']['humidity']} %\n" weather_text += f"Min-Temp : {weather_data['main']['temp_min']} °F\n" weather_text += f"Max-Temp : {weather_data['main']['temp_max']} °F\n" weather_text += f"Wind Speed : {weather_data['wind']['speed']} m/s\n" weather_text += f"Wind Direction : {weather_data['wind']['deg']}°\n" weather_text += f"Visibility : {weather_data['visibility']} m\n" else: weather_text += f"Error: {weather_data['message']} " return weather_text # send weather data def sendWeather(message): weather_text = getWeather() bot.send_message( message, text="The current weather details in Delhi is: \n\n" + weather_text) # Start Weather updates @bot.message_handler(commands=['start']) def start(message): bot.reply_to(message, "Weather updates started successfully.") scheduler.add_job(sendWeather(message.chat.id), 'interval', hours=1) scheduler.start() # Stop weather updates @bot.message_handler(commands=['stop']) def stop(message): scheduler.remove_all_jobs() bot.send_message(message.chat.id, text="Weather updates stopped successfully.") # Test command @bot.message_handler(commands=['test']) def send_welcome(message): bot.reply_to(message, "Hello, I am ready to serve you.") # Set the listener bot.set_update_listener(start) bot.set_update_listener(stop) # Run the bot bot.infinity_polling() ================================================ FILE: Telegram Bot/requirements.txt ================================================ pyTelegramBotAPI==4.9.0 APScheduler==3.9.1 ================================================ FILE: Telegram Bot/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Text Summarizer/README.md ================================================ # TextRank-based Text Summarization This project implements a **TextRank-based approach** to extract summaries from large textual data, such as articles. The summarization algorithm ranks sentences based on their relevance and importance, using concepts derived from the PageRank algorithm applied to text. ## Table of Contents 1. [Features](#features) 2. [Installation](#installation) 3. [Usage](#usage) 4. [How It Works](#how-it-works) 5. [Project Structure](#project-structure) 6. [Dependencies](#dependencies) 7. [License](#license) --- ## Features - Preprocesses text to clean and remove stopwords. - Utilizes **GloVe word embeddings** for sentence vectorization. - Applies the **TextRank algorithm** to rank and select important sentences. - Automatically downloads GloVe embeddings if not present locally. - Outputs a summary of the most relevant sentences from the input text. ## Installation 1. Clone the repository: ```bash git clone https://github.com/king04aman/All-In-One-Python-Projects.git ``` 2. Install the required Python libraries: ```bash pip install -r requirements.txt ``` 3. Download necessary NLTK data for tokenization and stopword removal: ```python import nltk nltk.download('punkt') nltk.download('stopwords') ``` ## Usage 1. Prepare your CSV file with a column `article_text` containing the text articles you want to summarize. 2. Run the script with your desired input: ```bash python text_summarizer.py ``` ### Example: - Ensure the input CSV file is in the directory: ```bash Text Summarizer/sample.csv ``` - The script will output the summary of the most important sentences from the input text. ### Command-line Parameters You can modify the following paths and settings inside the script: - `input_csv`: Path to your input CSV file. - `glove_dir`: Directory for storing GloVe embeddings. - `glove_file`: Path to the GloVe embeddings file. - `top_n_sentences`: The number of sentences you want in the summary (default is 10). ## How It Works ### 1. Text Preprocessing - Sentences are tokenized, and each sentence is cleaned by: - Removing punctuation, numbers, and special characters. - Converting text to lowercase. - Removing stopwords using the NLTK library. ### 2. Sentence Vectorization - The script uses **GloVe embeddings** to convert words in each sentence into a vector representation. Sentence vectors are the average of all word vectors in a sentence. - If the embeddings are not present, the script automatically downloads them. ### 3. Building Similarity Matrix - A similarity matrix is built by calculating the **cosine similarity** between sentence vectors. This matrix forms the basis for ranking sentences. ### 4. Sentence Ranking - The **PageRank algorithm** is applied to the similarity matrix. Sentences are ranked based on their scores, where higher-ranked sentences are deemed more important for summarization. ### 5. Output Summary - Based on the rankings, the top `n` sentences are selected as the summary. These sentences are printed as the output of the script. ## Project Structure ``` . ├── Text Summarizer/ │ ├── sample.csv # Example CSV input file with articles │ ├── text_summarizer.py # Main script for summarization │ ├── glove/ # Directory for storing GloVe embeddings │ └── text_summarizer.log # Log file ``` ## Dependencies - **Python 3.x** - **Libraries**: - `numpy` - `pandas` - `nltk` - `sklearn` - `networkx` - `requests` - `tqdm` All dependencies can be installed via: ```bash pip install -r requirements.txt ``` ### GloVe Embeddings - The script uses **GloVe embeddings** from Stanford NLP to generate sentence vectors. - By default, the **100-dimensional GloVe vectors** (`glove.6B.100d.txt`) are used. - Download link: [GloVe 6B embeddings](http://nlp.uoregon.edu/download/embeddings/glove.6B.100d.txt) ## Short Summary TextRank Text Summarization This script implements a TextRank-based approach for text summarization. The input is a CSV file containing text articles, and the output is a summary of the text. Steps: 1. Preprocesses the text by removing punctuation, numbers, special characters, and stopwords. 2. Generates sentence vectors using GloVe word embeddings. 3. Builds a similarity matrix using cosine similarity between sentence vectors. 4. Applies the PageRank algorithm to rank sentences. 5. Outputs a summary of the most important sentences. Dependencies: - numpy - pandas - nltk - sklearn - networkx - GloVe word embeddings (automatically downloaded if not present) Author: [Himanshu Mahajan](https://github.com/himanshumahajan138) Date: 19-10-2024 ## License This project is licensed under the MIT License. --- ================================================ FILE: Text Summarizer/requirements.txt ================================================ networkx==3.3 nltk==3.9.1 numpy==2.1.2 pandas==2.2.3 Requests==2.32.3 scikit_learn==1.5.2 tqdm==4.66.5 ================================================ FILE: Text Summarizer/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Text Summarizer/sample.csv ================================================ article_id,article_text,source 1,"Maria Sharapova has basically no friends as tennis players on the WTA Tour. The Russian player has no problems in openly speaking about it and in a recent interview she said: 'I don't really hide any feelings too much. I think everyone knows this is my job here. When I'm on the courts or when I'm on the court playing, I'm a competitor and I want to beat every single person whether they're in the locker room or across the net.So I'm not the one to strike up a conversation about the weather and know that in the next few minutes I have to go and try to win a tennis match. I'm a pretty competitive girl. I say my hellos, but I'm not sending any players flowers as well. Uhm, I'm not really friendly or close to many players. I have not a lot of friends away from the courts.' When she said she is not really close to a lot of players, is that something strategic that she is doing? Is it different on the men's tour than the women's tour? 'No, not at all. I think just because you're in the same sport doesn't mean that you have to be friends with everyone just because you're categorized, you're a tennis player, so you're going to get along with tennis players. I think every person has different interests. I have friends that have completely different jobs and interests, and I've met them in very different parts of my life. I think everyone just thinks because we're tennis players we should be the greatest of friends. But ultimately tennis is just a very small part of what we do. There are so many other things that we're interested in, that we do.'",https://www.tennisworldusa.org/tennis/news/Maria_Sharapova/62220/i-do-not-have-friends-in-tennis-says-maria-sharapova/ 2,"BASEL, Switzerland (AP), Roger Federer advanced to the 14th Swiss Indoors final of his career by beating seventh-seeded Daniil Medvedev 6-1, 6-4 on Saturday. Seeking a ninth title at his hometown event, and a 99th overall, Federer will play 93th-ranked Marius Copil on Sunday. Federer dominated the 20th-ranked Medvedev and had his first match-point chance to break serve again at 5-1. He then dropped his serve to love, and let another match point slip in Medvedev's next service game by netting a backhand. He clinched on his fourth chance when Medvedev netted from the baseline. Copil upset expectations of a Federer final against Alexander Zverev in a 6-3, 6-7 (6), 6-4 win over the fifth-ranked German in the earlier semifinal. The Romanian aims for a first title after arriving at Basel without a career win over a top-10 opponent. Copil has two after also beating No. 6 Marin Cilic in the second round. Copil fired 26 aces past Zverev and never dropped serve, clinching after 2 1/2 hours with a forehand volley winner to break Zverev for the second time in the semifinal. He came through two rounds of qualifying last weekend to reach the Basel main draw, including beating Zverev's older brother, Mischa. Federer had an easier time than in his only previous match against Medvedev, a three-setter at Shanghai two weeks ago.",http://www.tennis.com/pro-game/2018/10/copil-stuns-5th-ranked-zverev-to-reach-swiss-indoors-final/77721/ 3,"Roger Federer has revealed that organisers of the re-launched and condensed Davis Cup gave him three days to decide if he would commit to the controversial competition. Speaking at the Swiss Indoors tournament where he will play in Sundays final against Romanian qualifier Marius Copil, the world number three said that given the impossibly short time frame to make a decision, he opted out of any commitment. ""They only left me three days to decide"", Federer said. ""I didn't to have time to consult with all the people I had to consult. ""I could not make a decision in that time, so I told them to do what they wanted."" The 20-time Grand Slam champion has voiced doubts about the wisdom of the one-week format to be introduced by organisers Kosmos, who have promised the International Tennis Federation up to $3 billion in prize money over the next quarter-century. The competition is set to feature 18 countries in the November 18-24 finals in Madrid next year, and will replace the classic home-and-away ties played four times per year for decades. Kosmos is headed by Barcelona footballer Gerard Pique, who is hoping fellow Spaniard Rafael Nadal will play in the upcoming event. Novak Djokovic has said he will give precedence to the ATP's intended re-launch of the defunct World Team Cup in January 2020, at various Australian venues. Major players feel that a big event in late November combined with one in January before the Australian Open will mean too much tennis and too little rest. Federer said earlier this month in Shanghai in that his chances of playing the Davis Cup were all but non-existent. ""I highly doubt it, of course. We will see what happens,"" he said. ""I do not think this was designed for me, anyhow. This was designed for the future generation of players."" Argentina and Britain received wild cards to the new-look event, and will compete along with the four 2018 semi-finalists and the 12 teams who win qualifying rounds next February. ""I don't like being under that kind of pressure,"" Federer said of the deadline Kosmos handed him.",https://scroll.in/field/899938/tennis-roger-federer-ignored-deadline-set-by-new-davis-cup 4,"Kei Nishikori will try to end his long losing streak in ATP finals and Kevin Anderson will go for his second title of the year at the Erste Bank Open on Sunday. The fifth-seeded Nishikori reached his third final of 2018 after beating Mikhail Kukushkin of Kazakhstan 6-4, 6-3 in the semifinals. A winner of 11 ATP events, Nishikori hasn't triumphed since winning in Memphis in February 2016. He has lost eight straight finals since. The second-seeded Anderson defeated Fernando Verdasco 6-3, 3-6, 6-4. Anderson has a shot at a fifth career title and second of the year after winning in New York in February. Nishikori leads Anderson 4-2 on career matchups, but the South African won their only previous meeting this year. With a victory on Sunday, Anderson will qualify for the ATP Finals. Currently in ninth place, Nishikori with a win could move to within 125 points of the cut for the eight-man event in London next month. Nishikori held serve throughout against Kukushkin, who came through qualifying. He used his first break point to close out the first set before going up 3-0 in the second and wrapping up the win on his first match point. Against Verdasco, Anderson hit nine of his 19 aces in the opening set. The Spaniard broke Anderson twice in the second but didn't get another chance on the South African's serve in the final set.",http://www.tennis.com/pro-game/2018/10/nishikori-beats-kukushkin-in-vienna-for-3rd-final-of-season/77719/ 5,"Federer, 37, first broke through on tour over two decades ago and he has since gone on to enjoy a glittering career. The 20-time Grand Slam winner is chasing his 99th ATP title at the Swiss Indoors this week and he faces Jan-Lennard Struff in the second round on Thursday (6pm BST). Davenport enjoyed most of her success in the late 1990s and her third and final major tournament win came at the 2000 Australian Open. But she claims the mentality of professional tennis players slowly began to change after the new millennium. ""It seems pretty friendly right now,"" said Davenport. ""I think there is a really nice environment and a great atmosphere, especially between some of the veteran players helping some of the younger players out. ""It's a very pleasant atmosphere, I'd have to say, around the locker rooms. ""I felt like the best weeks that I had to get to know players when I was playing were the Fed Cup weeks or the Olympic weeks, not necessarily during the tournaments. ""And even though maybe we had smaller teams, I still think we kept to ourselves quite a bit. ""Not always, but I really feel like in the mid-2000 years there was a huge shift of the attitudes of the top players and being more friendly and being more giving, and a lot of that had to do with players like Roger coming up. ""I just felt like it really kind of changed where people were a little bit, definitely in the 90s, a lot more quiet, into themselves, and then it started to become better."" Meanwhile, Federer is hoping he can improve his service game as he hunts his ninth Swiss Indoors title this week. ""I didn't serve very well [against first-round opponent Filip Kranjovic,"" Federer said. ""I think I was misfiring the corners, I was not hitting the lines enough. ""Clearly you make your life more difficult, but still I was up 6-2, 3-1, break points, so things could have ended very quickly today, even though I didn't have the best serve percentage stats. ""But maybe that's exactly what caught up to me eventually. It's just getting used to it. This is where the first rounds can be tricky.""",https://www.express.co.uk/sport/tennis/1036101/Roger-Federer-Swiss-Indoors-Jan-Lennard-Struff-Lindsay-Davenport 6,"Nadal has not played tennis since he was forced to retire from the US Open semi-finals against Juan Martin Del Porto with a knee injury. The world No 1 has been forced to miss Spain's Davis Cup clash with France and the Asian hard court season. But with the ATP World Tour Finals due to begin next month, Nadal is ready to prove his fitness before the season-ending event at the 02 Arena. Nadal flew to Paris on Friday and footage from the Paris Masters official Twitter account shows the Spaniard smiling as he strides onto court for practice. The Paris Masters draw has been made and Nadal will start his campaign on Tuesday or Wednesday against either Fernando Verdasco or Jeremy Chardy. Nadal could then play defending champion Jack Sock in the third round before a potential quarter-final with either Borna Coric or Dominic Thiem. Nadal's appearance in Paris is a big boost to the tournament organisers who could see Roger Federer withdraw. Federer is in action at the Swiss Indoors in Basel and if he reaches the final, he could pull out of Paris in a bid to stay fresh for London. But as it stands, Federer is in the draw and is scheduled to face either former world No 3 Milos Raonic or Jo-Wilfried Tsonga in the second round. Federer's projected route to the Paris final could also lead to matches against Kevin Anderson and Novak Djokovic. Djokovic could play Marco Cecchinato in the second round. British No 1 Kyle Edmund is the 12th seed in Paris and will get underway in round two against either Karen Khachanov or Filip Krajinovic.",https://www.express.co.uk/sport/tennis/1037119/Rafael-Nadal-World-No-1-Paris-Masters-Federer-Djokovic 7,"Tennis giveth, and tennis taketh away. The end of the season is finally in sight, and with so many players defending,or losing,huge chunks of points in Singapore, Zhuhai and London, podcast co-hosts Nina Pantic and Irina Falconi discuss the art of defending points (02:14). It's no secret that Jack Sock has struggled on the singles court this year (his record is 7-19). He could lose 1,400 points in the next few weeks, but instead of focusing on the negative, it can all be about perspective (06:28). Let's also not forget his two Grand Slam doubles triumphs this season. Two players, Stefanos Tsitsipas and Kyle Edmund, won their first career ATP titles last week (13:26). It's a big deal because you never forget your first. Irina looks back at her WTA title win in Bogota in 2016, and tells an unforgettable story about her semifinal drama (14:04). In Singapore, one of the biggest storylines (aside from the matches, of course) has been the on-court coaching debate. Nina and Irina give their opinions on what coaching should look like in the future, on both tours (18:55).",http://www.tennis.com/pro-game/2018/10/tenniscom-podcast-irina-falconi-jack-sock-rafael-nadal-singapore/77698/ 8,"Federer won the Swiss Indoors last week by beating Romanian qualifier Marius Copil in the final. The 37-year-old claimed his 99th ATP title and is hunting the century in the French capital this week. Federer has been handed a difficult draw where could could come across Kevin Anderson, Novak Djokovic and Rafael Nadal in the latter rounds. But first the 20-time Grand Slam winner wants to train on the Paris Masters court this afternoon before deciding whether to appear for his opening match against either Milos Raonic or Jo-Wilfried Tsonga. ""On Monday, I am free and will look how I feel,"" Federer said after winning the Swiss Indoors. ""On Tuesday I will fly to Paris and train in the afternoon to be ready for my first match on Wednesday night. ""I felt good all week and better every day. ""We also had the impression that at this stage it might be better to play matches than to train. ""And as long as I fear no injury, I play."" Federer's success in Basel last week was the ninth time he has won his hometown tournament. And he was delighted to be watched on by all of his family and friends as he purchased 60 tickets for the final for those dearest to him. ""My children, my parents, my sister and my team are all there,"" Federer added. ""It is always very emotional for me to thank my team. And sometimes it tilts with the emotions, sometimes I just stumble. ""It means the world to me. It makes me incredibly happy to win my home tournament and make people happy here. ""I do not know if it's maybe my last title, so today I try a lot more to absorb that and enjoy the moments much more consciously. ""Maybe I should celebrate as if it were my last title. ""There are very touching moments: seeing the ball children, the standing ovations, all the familiar faces in the audience. Because it was not always easy in the last weeks.""",https://www.express.co.uk/sport/tennis/1038186/Roger-Federer-set-for-crunch-Paris-Masters-decision-today ================================================ FILE: Text Summarizer/text_summarizer.py ================================================ """ TextRank Text Summarization This script implements a TextRank-based approach for text summarization. The input is a CSV file containing text articles, and the output is a summary of the text. Steps: 1. Preprocesses the text by removing punctuation, numbers, special characters, and stopwords. 2. Generates sentence vectors using GloVe word embeddings. 3. Builds a similarity matrix using cosine similarity between sentence vectors. 4. Applies the PageRank algorithm to rank sentences. 5. Outputs a summary of the most important sentences. Dependencies: - numpy - pandas - nltk - sklearn - networkx - GloVe word embeddings (automatically downloaded if not present) Author: Himanshu Mahajan (GitHub: himanshumahajan138) Date: 19-10-2024 """ import os import requests from tqdm import tqdm import numpy as np import pandas as pd import nltk from nltk.tokenize import sent_tokenize from nltk.corpus import stopwords from sklearn.metrics.pairwise import cosine_similarity import networkx as nx import logging # Configure logging logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s", handlers=[ logging.FileHandler("Text Summarizer/text_summarizer.log"), logging.StreamHandler(), ], ) # Download necessary NLTK data (if not already available) nltk.download("punkt") # Sentence tokenizer nltk.download("stopwords") # Stopwords list # Function to preprocess and clean sentences def preprocess_sentences(sentences): """ Cleans and preprocesses sentences by removing non-alphabetic characters, converting to lowercase, and removing stopwords. Args: sentences (list): List of sentences. Returns: list: Cleaned and preprocessed sentences. """ logging.info("Preprocessing sentences...") # Remove punctuation, numbers, and special characters clean_sentences = pd.Series(sentences).str.replace("[^a-zA-Z]", " ", regex=True) # Convert to lowercase clean_sentences = [s.lower() for s in clean_sentences] # Remove stopwords stop_words = stopwords.words("english") clean_sentences = [ " ".join([word for word in sentence.split() if word not in stop_words]) for sentence in clean_sentences ] logging.info("Preprocessing completed.") return clean_sentences # Function to generate sentence vectors using GloVe embeddings def generate_sentence_vectors(sentences, word_embeddings, embedding_dim=100): """ Converts sentences into vectors by averaging the GloVe word embeddings of each word in the sentence. Args: sentences (list): List of sentences. word_embeddings (dict): GloVe word embeddings. embedding_dim (int): Dimensionality of GloVe vectors. Returns: list: List of sentence vectors. """ logging.info("Generating sentence vectors...") sentence_vectors = [] for sentence in sentences: if len(sentence) != 0: words = sentence.split() sentence_vector = sum( [ word_embeddings.get(word, np.zeros((embedding_dim,))) for word in words ] ) / (len(words) + 0.001) else: sentence_vector = np.zeros((embedding_dim,)) sentence_vectors.append(sentence_vector) logging.info("Sentence vectors generated.") return sentence_vectors # Function to build similarity matrix def build_similarity_matrix(sentence_vectors): """ Builds a similarity matrix using cosine similarity between sentence vectors. Args: sentence_vectors (list): List of sentence vectors. Returns: np.ndarray: Similarity matrix. """ logging.info("Building similarity matrix...") sim_mat = np.zeros([len(sentence_vectors), len(sentence_vectors)]) for i in range(len(sentence_vectors)): for j in range(len(sentence_vectors)): if i != j: sim_mat[i][j] = cosine_similarity( sentence_vectors[i].reshape(1, -1), sentence_vectors[j].reshape(1, -1), )[0, 0] logging.info("Similarity matrix built.") return sim_mat # Function to rank sentences using TextRank algorithm def rank_sentences(similarity_matrix, sentences, top_n=10): """ Ranks sentences based on the PageRank algorithm applied to the similarity matrix. Args: similarity_matrix (np.ndarray): Similarity matrix. sentences (list): List of original sentences. top_n (int): Number of top-ranked sentences to return. Returns: list: Top-ranked sentences. """ logging.info(f"Ranking top {top_n} sentences...") nx_graph = nx.from_numpy_array(similarity_matrix) scores = nx.pagerank(nx_graph) ranked_sentences = sorted( ((scores[i], sentence) for i, sentence in enumerate(sentences)), reverse=True ) logging.info("Sentences ranked.") return [ranked_sentences[i][1] for i in range(top_n)] # Function to download and extract GloVe embeddings def download_glove(glove_url, glove_file, glove_dir): """ Downloads and extracts GloVe embeddings if not already present. Args: glove_url (str): URL to the GloVe embeddings zip file. glove_zip (str): Path to the GloVe zip file. glove_dir (str): Directory where the GloVe files will be extracted. """ if not os.path.exists(glove_file): os.makedirs(glove_dir, exist_ok=True) logging.info("GloVe embeddings not found, downloading...") # Stream the request to handle large files with requests.get(glove_url, stream=True) as response: response.raise_for_status() total_size = int(response.headers.get("content-length", 0)) block_size = 1024 # 1 Kibibyte # Use tqdm to show progress bar with tqdm( total=total_size, unit="B", unit_scale=True, desc=glove_file ) as progress_bar: with open(glove_file, "wb") as file: for data in response.iter_content(block_size): file.write(data) progress_bar.update(len(data)) logging.info("Download complete. Extracting files...") else: logging.info("GloVe embeddings already present.") # Main function to summarize text using TextRank def summarize_text(input_csv, glove_file, top_n=10): """ Summarizes the text from a CSV file using the TextRank algorithm. Args: input_csv (str): Path to the input CSV file. glove_file (str): Path to the GloVe embeddings file. top_n (int): Number of sentences to include in the summary. Returns: list: Summary sentences. """ logging.info(f"Starting text summarization for {input_csv}...") # Read the CSV file df = pd.read_csv(input_csv) # Tokenize articles into sentences logging.info("Tokenizing articles into sentences...") sentences = [sent_tokenize(article) for article in df["article_text"]] sentences = [ sentence for sublist in sentences for sentence in sublist ] # Flatten the list # Preprocess sentences clean_sentences = preprocess_sentences(sentences) # Load GloVe embeddings logging.info("Loading GloVe embeddings...") word_embeddings = {} with open(glove_file, "r", encoding="utf-8") as f: for line in f: values = line.split() word = values[0] coefs = np.asarray(values[1:], dtype="float32") word_embeddings[word] = coefs # Generate sentence vectors sentence_vectors = generate_sentence_vectors(clean_sentences, word_embeddings) # Build similarity matrix sim_mat = build_similarity_matrix(sentence_vectors) # Rank sentences summary = rank_sentences(sim_mat, sentences, top_n=top_n) logging.info(f"Text summarization completed for {input_csv}.") return summary if __name__ == "__main__": # Define paths and parameters input_csv = os.getcwd() + "/Text Summarizer/sample.csv" # Path to input CSV file glove_dir = "Text Summarizer/glove" # Directory where GloVe files will be stored glove_file = os.path.join( os.getcwd(), glove_dir, "glove.6B.100d.txt" ) # Path to GloVe embeddings file glove_url = "http://nlp.uoregon.edu/download/embeddings/glove.6B.100d.txt" # URL for GloVe embeddings top_n_sentences = 10 # Number of sentences in the summary # Download and extract GloVe embeddings download_glove(glove_url, glove_file, glove_dir) # Generate summary summary = summarize_text(input_csv, glove_file, top_n_sentences) # Print summary print("Summary:") for sentence in summary: print(sentence + "\n") ================================================ FILE: Text To Speech/README.md ================================================ # Script Name **Text to Speech Converter using gTTS** - This script converts text into speech using Google’s Text-to-Speech (gTTS) API and saves the output as an audio file (e.g., `.mp3` format). - It allows for customization of language, speech speed, accents, and other pre-processing and tokenizing options. - Features: - Support for multiple languages using IETF language tags. - Localized accents via different Google Translate top-level domains (`tld`). - Option to slow down speech for easier comprehension. - Custom text pre-processing and tokenization options. - Timeout control for network requests. - Automatic playing of the audio file after saving (optional). # Description This script provides a convenient interface for converting text into speech using the `gTTS` library. The text can be read in multiple languages, at different speeds, and with various localized accents. The script also includes advanced options for pre-processing the input text and customizing how it's tokenized before being sent to the gTTS API. ### Key Features: - **Multilingual Support**: Specify different languages using IETF language tags (`en`, `es`, etc.). - **Accents**: Use top-level domains (`tld`), such as `com`, `co.uk`, etc., to localize the accent. - **Custom Speed**: Option to slow down the speech for better understanding. - **Pre-Processing**: Built-in support for text pre-processing (e.g., removing punctuation). - **Timeout**: Set timeout limits for the API request. # Prerequisites The following libraries are required to run the script: ```bash pip install gtts ``` Additionally, the script uses built-in libraries like `os`. # Installing Instructions 1. **Clone the Repository**: Clone this repository to your local machine using: ```bash git clone ``` 2. **Install Dependencies**: Navigate to the project directory and install the required packages: ```bash pip install -r requirements.txt ``` 3. **Run the Script**: After cloning and installing dependencies, you can run the script directly: ```bash python text_to_speech.py ``` 4. **Customize the Script**: You can modify the input text, language, speed, and other options directly in the script: ```python text_to_speech("Hello, welcome to the gTTS Python tutorial.", lang='en', slow=False) ``` # Output ### Example output: After running the script with the text `"Hello, welcome to the gTTS Python tutorial."`, the output file `output.mp3` is generated. # Author **[Himanshu Mahajan](https://github.com/himanshumahajan138)** ================================================ FILE: Text To Speech/requirements.txt ================================================ gTTS==2.5.2 ================================================ FILE: Text To Speech/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Text To Speech/text_to_speech.py ================================================ from gtts import gTTS import os def text_to_speech( text, lang="en", tld="com", slow=False, lang_check=True, pre_processor_funcs=None, tokenizer_func=None, timeout=None, output_file="output.mp3", ): """ Convert the provided text to speech and save it as an audio file. Args: text (string): The text to be read. lang (string, optional): The language (IETF language tag) to read the text in. Default is 'en'. tld (string, optional): Top-level domain for Google Translate host (e.g., 'com', 'co.uk'). This affects accent localization. Default is 'com'. slow (bool, optional): If True, reads the text more slowly. Default is False. lang_check (bool, optional): If True, enforces valid language, raising a ValueError if unsupported. Default is True. pre_processor_funcs (list, optional): List of pre-processing functions to modify the text before tokenizing. Defaults to a list of built-in pre-processors. tokenizer_func (callable, optional): Function to tokenize the text. Defaults to a built-in tokenizer. timeout (float or tuple, optional): Seconds to wait for server response. Can be a float or a (connect, read) tuple. Default is None (wait indefinitely). output_file (string): Path for the output audio file (default: 'output.mp3'). Raises: AssertionError: When text is None or empty. ValueError: When lang_check is True and lang is unsupported. """ # Use default pre-processor functions if not provided if pre_processor_funcs is None: pre_processor_funcs = [ # Example built-in functions from gTTS: # Converts tone marks, abbreviations, and deals with word substitutions lambda text: text.replace( ".", "" ), # You can define more or use built-ins from gTTS ] # Use default tokenizer if not provided if tokenizer_func is None: tokenizer_func = lambda text: text.split() # Basic tokenizer example try: # Create the gTTS object with the provided arguments tts = gTTS( text=text, lang=lang, tld=tld, slow=slow, lang_check=lang_check, pre_processor_funcs=pre_processor_funcs, tokenizer_func=tokenizer_func, timeout=timeout, ) # Save the audio file tts.save("Text To Speech/"+output_file) print(f"Audio saved at Text To Speech/{output_file}") # Optionally, play the audio file (Windows or Linux/MacOS) # if os.name == "nt": # Windows # os.system(f"start {output_file}") # else: # macOS/Linux # os.system(f"xdg-open {output_file}") except AssertionError as ae: print(f"Assertion Error: {ae}") except ValueError as ve: print(f"Value Error: {ve}") except RuntimeError as re: print(f"Runtime Error: {re}") if __name__ == "__main__": # Example usage of the text_to_speech function with various arguments # Basic example (English, default options) text = "Hello, welcome to the gTTS Python tutorial." text_to_speech(text) # # Custom example (Spanish, slow speech, and custom file name) # text_to_speech( # "Hola, bienvenido al tutorial de gTTS.", # lang="es", # slow=True, # output_file="spanish_slow.mp3", # ) # # Custom example with localized accent (UK English) # text_to_speech( # "Hello! How are you today?", # lang="en", # tld="co.uk", # output_file="british_accent.mp3", # ) # # You can pass custom pre-processor functions to modify the text before it’s tokenized. # text_to_speech( # "Dr. Smith is a great person.", # pre_processor_funcs=[lambda x: x.replace(".", "")], # output_file="custom_pre-processor.mp3", # ) # # You can set a timeout to limit how long the request to Google Translate waits. # text_to_speech( # "This will timeout after 5 seconds.", # output_file="timeout.mp3", # timeout=5.0 # ) ================================================ FILE: Text to Morse Code/main.py ================================================ symbols = { "a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": ".-", "h": "....", "i": "..", "j": ".---", "k": "-.-", "l": ".-..", "m": "--", "n": "-.", "o": "---", "p": ".--.", "q": "--.-", "r": ".-.", "s": "...", "t": "-", "u": "..-", "v": "...-", "w": ".--", "x": "-..-", "y": "-.--", "z": "--..", } ask = input("Enter a word: ") length = len(ask) output = "" for i in range(length): if ask[i] in symbols.keys(): output = output + " " + symbols.get(ask[i]) print(output) ================================================ FILE: Text to Morse Code/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Text_Adventure_Game/readme.md ================================================ # Text-Based Adventure Game Welcome to the **Text-Based Adventure Game**! This Python game is a simple interactive adventure where players explore rooms, collect items, and engage in combat with opponents like goblins and dragons. Each decision you make will affect your inventory and how you handle future challenges. ## Features - **Two distinct types of doors**: Players can choose between doors, which may lead to hidden items such as swords or shields. - **Combat System**: Engage in battle with different opponents: - **Goblin**: A weak opponent that requires strategy. - **Dragon**: A formidable final boss with special attacks. - **Inventory Management**: Pick up and use items like swords and shields to aid in combat. - **Game Save & Load**: Your progress is automatically saved, so you can load it later and continue from where you left off. ## Gameplay - Players start the game by entering their name. - You are presented with two doors to choose from, each leading to different experiences. - Items like swords and shields can be found to help you in combat. - Random encounters with goblins and dragons will test your decision-making skills. - The game automatically saves your progress, allowing you to resume your adventure later. ## How to Play 1. **Choose a door**: When prompted, choose either the left or right door. Each door may contain hidden treasures like a sword or shield. 2. **Make choices**: Decide whether to pick up items or face challenges. 3. **Combat**: Engage in combat with either a goblin or dragon. Use your sword and shield to protect yourself or defeat enemies. 4. **Save your progress**: The game will automatically save after each major action. 5. **Reload your game**: If you exit the game, you can load it from the last saved point when you return. ## Setup and Installation 1. Ensure you have Python 3 installed on your machine. 2. Clone this repository to your local machine. 3. Navigate to the project directory. 4. Run the text_adventure_game.py file. ## Code Overview The game is built using Python, and its logic is divided into several components: - **Opponent Class**: The base class for both weak and strong opponents. Handles basic attack logic. - **WeakOpponent Class**: A class for weaker opponents like the goblin. Overrides the attack method to reflect weaker attacks. - **FinalBoss Class**: A subclass of Opponent designed for more challenging enemies like the dragon, with special powers. - **Combat and Exploration**: Players can choose doors, explore rooms, collect items, and engage in combat. - **Saving and Loading**: The game state is saved to a file (`game_save.txt`), and players can load this file to continue their progress. ## Error Handling The game is designed with basic error handling using `try-except` blocks: - If there are issues with file saving or loading, an error message is displayed. - Combat logic is wrapped in error handling to prevent crashes due to unexpected input. Enjoy your adventure! ================================================ FILE: Text_Adventure_Game/text_adventure_game.py ================================================ import random import os # Used to check if the file exists # Opponent base class class Opponent: def __init__(self, name, health, attack_strength): self.name = name self.health = health self.attack_strength = attack_strength def attack(self): """General attack logic for opponents.""" return random.randint(1, self.attack_strength) # WeakOpponent class inheriting from Opponent class WeakOpponent(Opponent): def __init__(self, name, health, attack_strength): super().__init__(name, health, attack_strength) def attack(self): """Overriding attack for weak opponents.""" print(f"{self.name} attacks weakly!") return random.randint(1, self.attack_strength // 2) # Weak attack is halved # FinalBoss class inheriting from Opponent class FinalBoss(Opponent): def __init__(self, name, health, attack_strength, special_power): super().__init__(name, health, attack_strength) self.special_power = special_power # New attribute for FinalBoss def attack(self): """Overriding attack for final bosses with special power.""" if random.random() > 0.7: # 30% chance of using special power print(f"{self.name} uses {self.special_power}!") return random.randint(self.attack_strength, self.attack_strength * 2) else: print(f"{self.name} attacks normally.") return super().attack() # Additional methods for game logic def save_game(player_name, inventory, doors_chosen): """Saves the current game state to a file.""" try: with open('game_save.txt', 'w') as file: file.write(f"{player_name}\n") file.write(",".join(inventory) + "\n") file.write(f"{doors_chosen['left']},{doors_chosen['right']}\n") except Exception as e: print(f"Error saving game: {e}") def load_game(): """Loads the game state from a file if it exists.""" if not os.path.exists('game_save.txt'): return None, [], {"left": False, "right": False} try: with open('game_save.txt', 'r') as file: file_content = file.readlines() player_name = file_content[0].strip() inventory = file_content[1].strip().split(",") if file_content[1].strip() else [] doors_status = file_content[2].strip().split(",") doors_chosen = {"left": doors_status[0] == "True", "right": doors_status[1] == "True"} return player_name, inventory, doors_chosen except Exception as e: print(f"Error loading game: {e}") return None, [], {"left": False, "right": False} def choose_door(doors_chosen, inventory): """Handles the player's choice of doors and updates the game state accordingly.""" available_doors = [] if not doors_chosen["left"]: available_doors.append("left") if not doors_chosen["right"]: available_doors.append("right") print(f'{"You return to the two doors.":^30}') if available_doors: print(f'{"Available doors are: " + ", ".join(available_doors):^30}') choice = "" while choice not in available_doors: choice = input(f'{"Which door do you want to choose? (left/right): ":^30}').lower() try: if choice == "left" and not doors_chosen["left"]: print(f'{"You are in a room with no doors. It is empty.":^30}') if input(f'{"Do you want to look around? (yes/no): ":^30}').lower() == "yes": print(f'{"You see a sword on the ground.":^30}') if input(f'{"Do you want to take the sword? (yes/no): ":^30}').lower() == "yes": inventory.append("sword") print(f'{"You took the sword!":^30}') else: print(f'{"You left the sword.":^30}') doors_chosen["left"] = True elif choice == "right" and not doors_chosen["right"]: print(f'{"You enter a room and find a shield!":^30}') if input(f'{"Do you want to take the shield? (yes/no): ":^30}').lower() == "yes": inventory.append("shield") print(f'{"You took the shield!":^30}') else: print(f'{"You left the shield.":^30}') doors_chosen["right"] = True except Exception as e: print(f"Error during door selection: {e}") save_game(player_name, inventory, doors_chosen) return doors_chosen, inventory def combat(choice, inventory): """Handles combat encounters using the new Opponent system.""" try: if choice == "dragon": dragon = FinalBoss("Dragon", health=100, attack_strength=20, special_power="Fire Breath") print(f'{"You encounter a fearsome dragon!":^30}') if input(f'{"Do you want to fight the dragon? (yes/no): ":^30}').lower() == "yes": if "sword" in inventory: print(f'{"Rolling the dice to see the outcome...":^30}') player_attack = random.randint(1, 10) # Simulating player's attack dragon_attack = dragon.attack() if player_attack >= dragon_attack: print(f'{"You defeated the dragon with your sword!":^30}') else: if "shield" in inventory: print(f'{"The dragon overpowered you, but your shield saved you!":^30}') inventory.remove("shield") else: print(f'{"The dragon overpowered you and you lost the game!":^30}') inventory.clear() else: print(f'{"You were eaten by the dragon because you had no sword!":^30}') inventory.clear() elif choice == "goblin": goblin = WeakOpponent("Goblin", health=50, attack_strength=5) print(f'{"You encounter a sneaky goblin!":^30}') if input(f'{"Do you want to fight the goblin? (yes/no): ":^30}').lower() == "yes": if "sword" in inventory: print(f'{"Rolling the dice to see the outcome...":^30}') player_attack = random.randint(1, 10) # Simulating player's attack goblin_attack = goblin.attack() if player_attack >= goblin_attack: print(f'{"You defeated the goblin with your sword!":^30}') else: if "shield" in inventory: print(f'{"The goblin tricked you, but your shield protected you!":^30}') inventory.remove("shield") else: print(f'{"The goblin tricked you and you lost the game!":^30}') inventory.clear() elif "shield" in inventory: print(f'{"The goblin attacked, but your shield saved you!":^30}') inventory.remove("shield") else: print(f'{"The goblin defeated you because you had no sword or shield!":^30}') inventory.clear() except Exception as e: print(f"Error during combat: {e}") return inventory def play_game(): """Main function that runs the game logic.""" player_name, inventory, doors_chosen = load_game() if not player_name: player_name = input("Enter your name: ") print(f'{"Welcome to the Adventure Game, " + player_name + "!":^30}') # Let player choose a door doors_chosen, inventory = choose_door(doors_chosen, inventory) # Encounter either a goblin or a dragon randomly encounter = random.choice(["goblin", "dragon"]) inventory = combat(encounter, inventory) if __name__ == "__main__": play_game() ================================================ FILE: Tic-Tac-Toc using AI (min-max)/README.md ================================================ # Tic-Tac-Toe Game with AI This project is a Tic-Tac-Toe game implemented in Python using the Pygame library. The game presents a classic, engaging experience where players can compete against either an AI opponent or another human player. The AI leverages the Minimax algorithm, a decision-making algorithm used in game theory, to evaluate potential moves and choose the best possible action at each turn. This guarantees that the AI will always make optimal moves, creating a challenging and competitive environment for players of all skill levels. ### Key Features: - **Two Players**: Play against an AI or another human player. - **Minimax Algorithm**: The AI makes optimal moves based on the Minimax strategy. - **Graphical User Interface**: A simple and intuitive GUI using Pygame. - **Reset Option**: Restart the game easily at any time. # Prerequisites The following libraries are required to run the script: ```bash pip install pygame numpy ``` # Installing Instructions 1. **Clone the Repository**: Clone this repository to your local machine using: ```bash git clone ``` 2. **Install Dependencies**: Navigate to the project directory and install the required packages: ```bash pip install pygame numpy ``` 3. **Run the Script**: After cloning and installing dependencies, you can run the script directly: ```bash python tic_tac_toe.py ``` 4. **Customize the Script**: You can modify game settings, such as board size and player options, directly in the script. # Gameplay Instructions - **Player vs AI:**: Click on the grid to make your move. The AI will respond automatically. - **AI Difficulty Levels**: You can adjust the difficulty of the AI in the game settings to suit your skill level. Higher levels make the AI more challenging. - **Restart Game**: Press the R key to restart the game at any time. # Usage **Player vs AI**: Click on the grid to make your move. The AI will respond automatically. **Restart Game**: Press the R key to restart the game at any time. # Example After starting the game, you can play by clicking on the grid cells. The AI will make its move following your turn, and the game will continue until one player wins or the game ends in a draw. ![Game Screen](screenshots/screenshot1.png) ![Winning State](screenshots/screenshot2.png) # Author **[Naumantamboli](https://github.com/Naumantamboli)** ================================================ FILE: Tic-Tac-Toc using AI (min-max)/requirements.txt ================================================ pygame==2.1.3 numpy==1.23.5 ================================================ FILE: Tic-Tac-Toc using AI (min-max)/tic_tac_toc.py ================================================ import pygame import sys import numpy as np pygame.init() WIDTH, HEIGHT = 600, 600 LINE_WIDTH = 15 BOARD_ROWS = 3 BOARD_COLS = 3 SQUARE_SIZE = WIDTH // BOARD_COLS CIRCLE_RADIUS = SQUARE_SIZE // 3 CIRCLE_WIDTH = 15 CROSS_WIDTH = 25 SPACE = SQUARE_SIZE // 4 BG_COLOR = (28, 170, 156) LINE_COLOR = (23, 145, 135) CIRCLE_COLOR = (239, 231, 200) CROSS_COLOR = (66, 66, 66) TEXT_COLOR = (255, 255, 255) screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Tic Tac Toe') screen.fill(BG_COLOR) font = pygame.font.Font(None, 40) # Font for displaying messages board = np.zeros((BOARD_ROWS, BOARD_COLS)) difficulty = "medium" # AI difficulty level ("easy", "medium", "hard") def draw_lines(): for row in range(1, BOARD_ROWS): pygame.draw.line(screen, LINE_COLOR, (0, row * SQUARE_SIZE), (WIDTH, row * SQUARE_SIZE), LINE_WIDTH) for col in range(1, BOARD_COLS): pygame.draw.line(screen, LINE_COLOR, (col * SQUARE_SIZE, 0), (col * SQUARE_SIZE, HEIGHT), LINE_WIDTH) # Draw figures (O and X) def draw_figures(): for row in range(BOARD_ROWS): for col in range(BOARD_COLS): if board[row][col] == 1: pygame.draw.circle(screen, CIRCLE_COLOR, (int(col * SQUARE_SIZE + SQUARE_SIZE // 2), int(row * SQUARE_SIZE + SQUARE_SIZE // 2)), CIRCLE_RADIUS, CIRCLE_WIDTH) elif board[row][col] == 2: pygame.draw.line(screen, CROSS_COLOR, (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE), (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SPACE), CROSS_WIDTH) pygame.draw.line(screen, CROSS_COLOR, (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SPACE), (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE), CROSS_WIDTH) def mark_square(row, col, player): board[row][col] = player def available_square(row, col): return board[row][col] == 0 def is_board_full(): return np.all(board != 0) def check_win(player): for row in range(BOARD_ROWS): if np.all(board[row, :] == player): return True for col in range(BOARD_COLS): if np.all(board[:, col] == player): return True if board[0, 0] == player and board[1, 1] == player and board[2, 2] == player: return True if board[0, 2] == player and board[1, 1] == player and board[2, 0] == player: return True return False def display_message(message): text = font.render(message, True, TEXT_COLOR) text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2)) screen.blit(text, text_rect) pygame.display.update() pygame.time.wait(2000) # Wait for 2 seconds to display the message # Minimax algorithm with difficulty levels def minimax(board, depth, is_maximizing): if check_win(2): # AI win return 1 elif check_win(1): # Player win return -1 elif is_board_full(): return 0 if is_maximizing: best_score = -np.inf for row in range(BOARD_ROWS): for col in range(BOARD_COLS): if available_square(row, col): board[row][col] = 2 score = minimax(board, depth + 1, False) board[row][col] = 0 best_score = max(score, best_score) return best_score else: best_score = np.inf for row in range(BOARD_ROWS): for col in range(BOARD_COLS): if available_square(row, col): board[row][col] = 1 score = minimax(board, depth + 1, True) board[row][col] = 0 best_score = min(score, best_score) return best_score # AI Move based on difficulty level def ai_move(): best_score = -np.inf move = None for row in range(BOARD_ROWS): for col in range(BOARD_COLS): if available_square(row, col): board[row][col] = 2 score = minimax(board, 0, False) board[row][col] = 0 if score > best_score: best_score = score move = (row, col) if move: mark_square(move[0], move[1], 2) # Easy AI move: choose a random available square def easy_ai_move(): available_moves = [(row, col) for row in range(BOARD_ROWS) for col in range(BOARD_COLS) if available_square(row, col)] if available_moves: move = available_moves[np.random.randint(len(available_moves))] mark_square(move[0], move[1], 2) def restart(): screen.fill(BG_COLOR) draw_lines() global board board = np.zeros((BOARD_ROWS, BOARD_COLS)) player = 1 # Player 1 is human game_over = False draw_lines() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN and not game_over: mouseX = event.pos[0] # X coordinate mouseY = event.pos[1] # Y coordinate clicked_row = mouseY // SQUARE_SIZE clicked_col = mouseX // SQUARE_SIZE if available_square(clicked_row, clicked_col): mark_square(clicked_row, clicked_col, player) if check_win(player): display_message("Player Wins!") game_over = True player = 2 if player == 2 and not game_over: if difficulty == "easy": easy_ai_move() else: ai_move() if check_win(2): display_message("AI Wins!") game_over = True player = 1 if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: restart() game_over = False player = 1 if game_over and is_board_full(): display_message("It's a Draw!") game_over = True draw_figures() pygame.display.update() ================================================ FILE: To Do List/README.md ================================================ # To-Do List App This is a simple To-Do List app built with Python using `tkinter` for the user interface and `sqlite3` for data storage. ## Features - Add tasks - View tasks - Delete tasks - Save tasks to database ## Requirements - Python 3.8.10 - `tkinter` - `sqlite3` ## Installation 1. Clone the repository: ```bash git clone ================================================ FILE: To Do List/RithwikBejadi/To Do App/README.md ================================================ **#To-Do List Application** A simple and intuitive To-Do List application built with Python's Tkinter library for the GUI and SQLite for persistent task storage. This application helps you manage tasks with categories, due dates, and priority levels, allowing easy organization of daily activities. **Features** Add Tasks: Add tasks with a description, category, due date, and priority level (High, Medium, Low). View Tasks: View all tasks, or filter tasks to see only completed or pending ones. Search Tasks: Quickly search tasks by their name or category using the search bar. Toggle Theme: Switch between dark and light themes to match your preference. Mark Tasks as Complete: Mark tasks as completed to keep track of what’s done. Persistent Storage: All tasks are saved in an SQLite database, ensuring data is saved even after closing the app. **Prerequisites** Python 3.6+ Tkinter (Usually included with Python) SQLite (Included in Python’s standard library) tkcalendar: Install using pip install tkcalendar **Usage Instructions** 1. Add a Task Enter a task description in the Task field. Specify the Category for better organization. Select a Due Date from the date picker. Choose a Priority from the drop-down menu (High, Medium, Low). Click Add Task to save it. 2. View All Tasks Click on View All Tasks in the sidebar to display a list of all tasks. Tasks are displayed with their description, category, due date, and priority level. 3. View Completed Tasks Click View Completed Tasks in the sidebar to see tasks that have been marked as complete. 4. View Pending Tasks Click View Pending Tasks in the sidebar to view tasks that are yet to be completed. 5. Search Tasks Use the Search bar in the sidebar to find tasks by their description or category. The list of tasks will update as you type, showing only those that match the search term. 6. Mark Tasks as Complete Select a task from the list and click Mark as Complete (add this button in your application). Completed tasks will no longer appear in the pending tasks view. 7. Toggle Dark/Light Theme Click Toggle Theme in the sidebar to switch between dark and light modes. This changes the background color, text color, and button styles for a better visual experience. 8. Close the Application Close the application by clicking the window close button (X) or selecting Exit. The application safely saves your tasks and closes the database connection. **Database Structure** The application uses an SQLite database with the following table structure: Table Name: tasks Column Name Type Description id INTEGER Primary key, unique task ID task TEXT Description of the task category TEXT Category of the task (e.g., Work, Home) due_date TEXT Due date of the task priority TEXT Priority level (High, Medium, Low) completed INTEGER Status (0 = Pending, 1 = Completed) **License** This project is licensed under the MIT License. See the LICENSE file for details. **Acknowledgments** Thanks to the Python community for their extensive libraries and documentation. Special thanks to the creators of tkcalendar for providing a simple date picker widget for Tkinter. ================================================ FILE: To Do List/RithwikBejadi/To Do App/To_Do_AppTkInter.py ================================================ import tkinter as tk from tkinter import messagebox, ttk from tkcalendar import DateEntry import sqlite3 class TodoApp: def __init__(self, root): self.root = root self.root.title("To-Do List App") self.root.geometry("900x600") # Initialize attributes self.is_dark_theme = True # Start with dark theme # Create main frame and sidebar frame self.main_frame = tk.Frame(self.root, bg="#2E2E2E") self.main_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True) self.sidebar_frame = tk.Frame(self.root, width=200, bg="#3A3A3A") self.sidebar_frame.pack(side=tk.LEFT, fill=tk.Y) self.create_widgets() self.create_database() self.apply_theme() # Apply theme after frames are created self.create_sidebar() self.load_tasks() # Bind the window close event to close the database connection self.root.protocol("WM_DELETE_WINDOW", self.close_app) def create_sidebar(self): """Create the sidebar with navigation options.""" tk.Label(self.sidebar_frame, text="Menu", font=("Helvetica", 16), bg="#3A3A3A", fg="#FFFFFF").pack(pady=10) # Create the "View All Tasks" button self.view_all_button = tk.Button( self.sidebar_frame, text="View All Tasks", command=self.load_tasks, bg="#5A5A5A", fg="#FFFFFF", relief="flat" ) self.view_all_button.pack(pady=5, padx=10, fill=tk.X) # Create other buttons like "View Completed Tasks", "View Pending Tasks", etc. self.view_completed_button = tk.Button( self.sidebar_frame, text="View Completed Tasks", command=self.load_completed_tasks, bg="#5A5A5A", fg="#FFFFFF", relief="flat" ) self.view_completed_button.pack(pady=5, padx=10, fill=tk.X) self.view_pending_button = tk.Button( self.sidebar_frame, text="View Pending Tasks", command=self.load_pending_tasks, bg="#5A5A5A", fg="#FFFFFF", relief="flat" ) self.view_pending_button.pack(pady=5, padx=10, fill=tk.X) # Search entry and label tk.Label(self.sidebar_frame, text="Search:", bg="#3A3A3A", fg="#FFFFFF").pack(pady=5) self.search_entry = tk.Entry(self.sidebar_frame, bg="#4B4B4B", fg="#FFFFFF", relief="flat") self.search_entry.pack(pady=5, padx=10, fill=tk.X) self.search_entry.bind('', self.search_tasks) # Toggle theme button self.theme_button = tk.Button( self.sidebar_frame, text="Toggle Theme", command=self.toggle_theme, bg="#5A5A5A", fg="#FFFFFF", relief="flat" ) self.theme_button.pack(pady=5, padx=10, fill=tk.X) def apply_theme(self): """Apply the current theme to the application.""" if self.is_dark_theme: bg_color = "#2E2E2E" fg_color = "#FFFFFF" button_bg = "#5A5A5A" entry_bg = "#4B4B4B" else: bg_color = "#F0F0F0" fg_color = "#000000" button_bg = "#D0D0D0" entry_bg = "#FFFFFF" self.root.configure(bg=bg_color) self.main_frame.configure(bg=bg_color) self.sidebar_frame.configure(bg="#3A3A3A" if self.is_dark_theme else "#F0F0F0") # Update the colors of sidebar elements for widget in self.sidebar_frame.winfo_children(): if isinstance(widget, tk.Button): widget.configure(bg=button_bg, fg=fg_color) elif isinstance(widget, tk.Entry): widget.configure(bg=entry_bg, fg=fg_color) def toggle_theme(self): """Toggle between light and dark themes.""" self.is_dark_theme = not self.is_dark_theme self.apply_theme() def create_database(self): """Create the tasks table if it doesn't exist.""" self.conn = sqlite3.connect("tasks.db") # Create the table if it doesn't exist yet with self.conn: self.conn.execute(""" CREATE TABLE IF NOT EXISTS tasks ( id INTEGER PRIMARY KEY, task TEXT NOT NULL, category TEXT, due_date TEXT, priority TEXT, completed INTEGER DEFAULT 0 ) """) def create_widgets(self): """Create the main content area widgets.""" frame = tk.Frame(self.main_frame, bg="#2E2E2E" if self.is_dark_theme else "#FFFFFF", padx=10, pady=10) frame.pack(pady=20, padx=20, fill=tk.BOTH, expand=True) # Task entry tk.Label(frame, text="Task:", font=("Helvetica", 12), bg=frame["bg"], fg="#FFFFFF" if self.is_dark_theme else "#000000").grid(row=0, column=0, sticky="w", pady=5) self.task_entry = tk.Entry(frame, width=50, bg="#4B4B4B", fg="#FFFFFF", relief="flat") self.task_entry.grid(row=0, column=1, sticky="ew", padx=5, pady=5) # Category entry tk.Label(frame, text="Category:", font=("Helvetica", 12), bg=frame["bg"], fg="#FFFFFF" if self.is_dark_theme else "#000000").grid(row=1, column=0, sticky="w", pady=5) self.category_entry = tk.Entry(frame, width=50, bg="#4B4B4B", fg="#FFFFFF", relief="flat") self.category_entry.grid(row=1, column=1, sticky="ew", padx=5, pady=5) # Due date entry tk.Label(frame, text="Due Date:", font=("Helvetica", 12), bg=frame["bg"], fg="#FFFFFF" if self.is_dark_theme else "#000000").grid(row=2, column=0, sticky="w", pady=5) self.due_date_entry = DateEntry(frame, width=20, date_pattern='yyyy-mm-dd', background='#4B4B4B', foreground='white', relief="flat") self.due_date_entry.grid(row=2, column=1, sticky="w", padx=5, pady=5) # Priority menu tk.Label(frame, text="Priority:", font=("Helvetica", 12), bg=frame["bg"], fg="#FFFFFF" if self.is_dark_theme else "#000000").grid(row=3, column=0, sticky="w", pady=5) self.priority_var = tk.StringVar(value="Medium") self.priority_menu = ttk.Combobox(frame, textvariable=self.priority_var, values=["High", "Medium", "Low"], state="readonly") self.priority_menu.grid(row=3, column=1, sticky="w", padx=5, pady=5) # Add task button self.add_task_button = tk.Button(frame, text="Add Task", command=self.add_task, bg="#5A5A5A", fg="#FFFFFF", relief="flat") self.add_task_button.grid(row=4, column=1, sticky="e", pady=10) # Listbox for tasks self.task_listbox = tk.Listbox(self.main_frame, font=("Helvetica", 10), bg="#2E2E2E", fg="#FFFFFF", height=15, relief="flat") self.task_listbox.pack(pady=10, padx=20, fill=tk.BOTH, expand=True) def load_tasks(self): """Load all pending tasks from the database.""" self.task_listbox.delete(0, tk.END) cursor = self.conn.cursor() # Retrieve tasks that are not yet completed (completed=0) cursor.execute("SELECT * FROM tasks WHERE completed=0") for row in cursor.fetchall(): # Format the task details for display in the listbox self.task_listbox.insert(tk.END, f"{row[1]} | {row[2]} | Due: {row[3]} | Priority: {row[4]}") def load_completed_tasks(self): """Load completed tasks from the database.""" self.task_listbox.delete(0, tk.END) cursor = self.conn.cursor() # Retrieve tasks that are marked as completed (completed=1) cursor.execute("SELECT * FROM tasks WHERE completed=1") for row in cursor.fetchall(): self.task_listbox.insert(tk.END, f"{row[1]} | {row[2]} | Due: {row[3]} | Priority: {row[4]}") def load_pending_tasks(self): """Load pending tasks.""" # Reuse the load_tasks method since it already loads pending tasks self.load_tasks() def add_task(self): """Add a new task to the database.""" task = self.task_entry.get() category = self.category_entry.get() due_date = self.due_date_entry.get() priority = self.priority_var.get() # Validate that required fields are filled if task and category and due_date: with self.conn: # Insert a new task into the database self.conn.execute("INSERT INTO tasks (task, category, due_date, priority) VALUES (?, ?, ?, ?)", (task, category, due_date, priority)) # Refresh the task list to show the new entry self.load_tasks() # Clear the input fields after adding the task self.task_entry.delete(0, tk.END) self.category_entry.delete(0, tk.END) else: messagebox.showwarning("Input Error", "Please fill all fields.") def search_tasks(self, event): """Search tasks based on input in the search bar.""" query = self.search_entry.get().lower() self.task_listbox.delete(0, tk.END) cursor = self.conn.cursor() # Retrieve all tasks and filter by the search query cursor.execute("SELECT * FROM tasks WHERE completed=0") for row in cursor.fetchall(): task_str = f"{row[1]} | {row[2]} | Due: {row[3]} | Priority: {row[4]}" # Display only tasks that match the search query if query in task_str.lower(): self.task_listbox.insert(tk.END, task_str) def close_app(self): """Close the database connection and exit the application.""" if self.conn: self.conn.close() self.root.destroy() if __name__ == "__main__": root = tk.Tk() app = TodoApp(root) root.mainloop() ================================================ FILE: To Do List/RithwikBejadi/To Do App/requirements.txt ================================================ tkinter==8.6 sqlite3==3.45.3 ================================================ FILE: To Do List/RithwikBejadi/To Do App/runtime.txt ================================================ Python 3.12.4 ================================================ FILE: To Do List/main.py ================================================ from tkinter import * import sqlite3 root = Tk() root.title("To-Do List App") root.geometry("400x400") conn = sqlite3.connect('todolist.db') c = conn.cursor() # Create table c.execute('''CREATE TABLE IF NOT EXISTS tasks (id INTEGER PRIMARY KEY, task TEXT NOT NULL)''') def add_task(): task = task_entry.get() if task: c.execute("INSERT INTO tasks (task) VALUES (?)", (task,)) conn.commit() task_entry.delete(0, END) populate_tasks() def delete_task(): task_id = task_list.get(ACTIVE).split('.')[0] c.execute("DELETE FROM tasks WHERE id=?", (task_id,)) conn.commit() populate_tasks() def populate_tasks(): task_list.delete(0, END) c.execute("SELECT * FROM tasks") tasks = c.fetchall() for task in tasks: task_list.insert(END, f"{task[0]}. {task[1]}") # Task entry task_entry = Entry(root, width=50) task_entry.pack(pady=10) # Add task button add_task_button = Button(root, text="Add Task", command=add_task) add_task_button.pack(pady=5) # Task list task_list = Listbox(root, width=50, height=15) task_list.pack(pady=10) # Delete task button delete_task_button = Button(root, text="Delete Task", command=delete_task) delete_task_button.pack(pady=5) # Populate tasks on startup populate_tasks() # Run the main loop root.mainloop() conn.close() ================================================ FILE: To Do List/requirement.txt ================================================ tk sqlite3 ================================================ FILE: To Do List/runtime.txt ================================================ python-3.8.10 ================================================ FILE: Translator/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Translator/translate.py ================================================ from tabulate import tabulate from googletrans import Translator class TranslateClass(object): def __init__(self, word, lang): self.word = word self.lang = lang self.Trans = Translator(service_urls=["translate.google.com"]) def __repr__(self): translated = self.Trans.translate(self.word, dest=self.lang).text data = [ ['Language:', "Sentence"], ['English', self.word], ['Hindi', str(translated)]] table = str(tabulate(data, headers="firstrow", tablefmt="grid")) return table if __name__ == '__main__': translate = input('Enter Sentence: ') language = 'hi' print(TranslateClass(translate, language)) ================================================ FILE: URL Sortener/main.py ================================================ import pyshorteners def shorten_url(url): return pyshorteners.Shortener().tinyurl.short(url) url = input("Please enter URL: ") print("URL after Shortening : ", shorten_url(url)) ================================================ FILE: URL Sortener/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Validate-Email/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Validate-Email/validate.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Aman Kumar # Version: 1.0.0 import re email_conditions = '^[a-z0-9]+[\._]?[a-z0-9]+[@]\w+[.]\w{2,3}$' user_email = input("Enter your email: ") isValid = re.search(email_conditions, user_email) if(isValid): print("Valid Email") else: print("Invalid Email") ================================================ FILE: Video Processor/README.md ================================================ # Video Processing Tool In this Python tool processes a video file by extracting short clips, applying filters and effects, and generating subtitles for each clip. The processed clips are saved as new video files along with corresponding subtitle files. ## Features - Extracts clips of a specified duration from the input video. - Applies image processing effects including brightness, contrast, saturation adjustments, and blurring. - Generates simple subtitle files for each clip. ## Requirements To run this script, you'll need the following Python packages: - `opencv-python` - `pysrt` You can install these using pip: ```bash pip install opencv-python pysrt ``` ## Usage 1. **Input Video**: The script prompts you to enter the link to a YouTube video. Make sure to use a video URL that is accessible and can be downloaded. 2. **Clip Duration**: The default duration for each extracted clip is set to 10 seconds. You can modify this value in the script as needed. 3. **Run the Script**: Execute the script using Python: ```bash python video_processor.py ``` 4. **Output**: - The processed clips will be saved as `clip0_out.mp4`, `clip1_out.mp4`, etc. - Corresponding subtitle files will be saved as `clip0_subtitle.srt`, `clip1_subtitle.srt`, etc. ## Code Explanation - **Video Capture**: The script uses OpenCV to read frames from the video. - **Image Processing**: Each frame within the clip duration is processed using filters and effects: - **Brightness and Contrast**: Adjusts the brightness and contrast of the frame. - **Saturation**: Modifies the saturation of the frame. - **Blurring**: Applies Gaussian blur and combines with a weighted blend for a smoother look. - **Subtitle Generation**: For each clip, a simple subtitle text ("This is a sample subtitle") is generated and saved in a `.srt` file format. ## Limitations - The script assumes the video file can be read directly via OpenCV, which may not be applicable for all YouTube links without prior downloading. - Subtitle text is static; you may want to customize it based on the content of each clip. ================================================ FILE: Video Processor/requirements.txt ================================================ opencv-python==4.8.0.76 pysrt==1.1.2 ================================================ FILE: Video Processor/video_processor.py ================================================ import cv2 import pysrt # Load the input video input_file = input("Enter the YouTube video link: ") cap = cv2.VideoCapture(input_file) # Set the start and end times for each short video clip clip_duration = 10.0 clip_start_time = 0.0 clip_end_time = clip_start_time + clip_duration # Set up OpenCV for video processing kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3)) brightness = 30 contrast = 1.5 saturation = 1.5 # Process each short video clip i = 0 while cap.isOpened(): # Read the next frame from the input video ret, frame = cap.read() if not ret: break # Get the current time in seconds current_time = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0 # If the current time is within the current clip, process the frame if current_time >= clip_start_time and current_time <= clip_end_time: # Apply the filters and effects frame = cv2.filter2D(frame, -1, kernel) frame = cv2.convertScaleAbs(frame, alpha=contrast, beta=brightness) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) h, s, v = cv2.split(frame) s = cv2.convertScaleAbs(s, alpha=saturation, beta=0) frame = cv2.merge((h, s, v)) frame = cv2.cvtColor(frame, cv2.COLOR_HSV2BGR) frame = cv2.GaussianBlur(frame, (5,5), 0) frame = cv2.addWeighted(frame, 1.5, cv2.blur(frame, (10,10)), -0.5, 0) # Write the modified frame to a new video file out = cv2.VideoWriter('clip' + str(i) + '_out.mp4', cv2.VideoWriter_fourcc(*'mp4v'), cap.get(cv2.CAP_PROP_FPS), (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))) out.write(frame) out.release() # Generate subtitles for the clip subtitle_text = "This is a sample subtitle" subtitle_duration = clip_duration subtitle_file = pysrt.SubRipFile() subtitle = pysrt.SubRipItem(index=1, start=0, end=subtitle_duration, text=subtitle_text) subtitle_file.append(subtitle) subtitle_file.save('clip' + str(i) + '_subtitle.srt') # Move to the next clip i += 1 clip_start_time += clip_duration clip_end_time += clip_duration # If the current time is past the end of the current clip, move to the next clip elif current_time > clip_end_time: clip_start_time += clip_duration clip_end_time += clip_duration # Release the resources cap.release() cv2.destroyAllWindows() ================================================ FILE: Video To Audio/main.py ================================================ import moviepy from tkinter.filedialog import * askForVideo = askopenfilename() video = moviepy.editor.VideoFileClip(askForVideo) audio = video.audio audio.write_audiofile("demo.mp3") print("Conversion Completed !!") ================================================ FILE: Video To Audio/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Weather Alert/README.md ================================================ # Weather Alert Script 🌦️ A simple Python script that fetches weather data for your city and alerts you if the temperature or wind speed crosses your set thresholds. Perfect for staying on top of weather changes and preparing for unexpected conditions! 🚀 ## Features - **Fetch Weather Data**: Retrieves up-to-date weather information for any city using the OpenWeatherMap API. - **Custom Alerts**: Set your own temperature and wind speed thresholds. If the weather conditions exceed these, the script will alert you! - **Hourly Updates**: The script automatically checks the weather every hour, so you’re always in the loop. ## Getting Started ### Prerequisites - Python 3.x - `requests` and `python-dotenv` libraries Install the required libraries using: ```bash pip install requests python-dotenv ``` ## Setup - Clone or download this repository. - Get an API key from OpenWeatherMap. (It’s free!) - Create a .env file in the root directory and add your API key like shown in `.env.example` - Run the script ``` python weather_alert.py ``` ## Troubleshooting - Missing API Key Error: Double-check that your .env file contains the correct OPEN_WEATHER_MAP_API_KEY. Make sure there are no typos or extra spaces. - Error fetching data: This could happen if the API key is incorrect or if the city name is misspelled. Verify both and try again. ================================================ FILE: Weather Alert/main.py ================================================ import requests import json import time import os from dotenv import load_dotenv # Load environment variables from .env file load_dotenv() # Load API key from environment variable (security fix) API_KEY = os.getenv('OPEN_WEATHER_MAP_API_KEY') if not API_KEY: raise ValueError("Missing environment variable 'OPEN_WEATHER_MAP_API_KEY'") UNIT = 'metric' BASE_URL = 'https://api.openweathermap.org/data/2.5/find' def fetch_weather(city): """Fetches weather data for a given city. Args: city (str): Name of the city. Returns: dict: Weather data if successful, None otherwise. """ url = f"{BASE_URL}?q={city}&appid={API_KEY}&units={UNIT}" response = requests.get(url) if response.status_code == 200: return response.json() else: print(f"Error fetching data: {response.status_code}") return None def check_alerts(data, temp_threshold, wind_speed_threshold): """Checks for temperature and wind speed alerts in weather data. Args: data (dict): Weather data. temp_threshold (float): Temperature threshold in °C. wind_speed_threshold (float): Wind speed threshold in m/s. Prints alerts if any, otherwise prints a message indicating normal weather conditions. """ if not data or 'list' not in data or not data['list']: print("No data available to check alerts.") return weather_info = data['list'][0] temp = weather_info['main']['temp'] wind_speed = weather_info['wind']['speed'] alerts = [] if temp > temp_threshold: alerts.append(f"Temperature alert! Current temperature: {temp}°C") if wind_speed > wind_speed_threshold: alerts.append(f"Wind speed alert! Current wind speed: {wind_speed} m/s") if alerts: print("\n".join(alerts)) else: print("No alerts. Weather conditions are normal.") def main(): """Prompts user for city name, temperature and wind speed thresholds, and continuously checks for alerts. """ city = input("Enter city name: ") temp_threshold = float(input("Enter temperature threshold (°C): ")) wind_speed_threshold = float(input("Enter wind speed threshold (m/s): ")) while True: weather_data = fetch_weather(city) check_alerts(weather_data, temp_threshold, wind_speed_threshold) print("Waiting for the next check...") time.sleep(3600) # check every hour if __name__ == "__main__": main() ================================================ FILE: Weather Alert/requirement.txt ================================================ requests python-dotenv ================================================ FILE: Weather Alert/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Word_frequency_counter/README.md ================================================ # Word Frequency Counter A simple python script that counts the number of words in a given text document and prints the top 10 words according to their frequency, along with their frequency of occurence. --- - **Input :** Path of the text file to be processed - **Output :** List of top 10 words according to their frequency, along with their frequency of occurence. --- ## Features : - User friendly interface - Output is in tabular format - Case insensitive processing of words - Get the Top 10 words in the text file which occur most frequntly, along with their counts --- ## Usage : 1. Clone the repository 2. Navigate to the project folder 3. Run the command : ```python python3 main.py ``` ================================================ FILE: Word_frequency_counter/main.py ================================================ import regex as re from collections import Counter def find_words_frequency(file_path): ''' This script takes the path of the text file to be processed as input and prints the top ten words and also prints their counts in the given text file. ''' with open(file_path, 'r', encoding='utf-8') as file: text = file.read().lower() # Use `regex`'s findall function all_words = re.findall(r'\b\p{L}+\b', text) word_frequency = Counter(all_words) most_common_words = word_frequency.most_common(10) # Print in tabular format print(f"{'Word':<15} {'Count':<5}") print("-" * 20) for word, count in most_common_words: print(f"{word:<15} {count:<5}") def main(): file_path = input("Enter the path of file : ") find_words_frequency(file_path) if __name__ == "__main__": main() ================================================ FILE: Word_frequency_counter/requirments.txt ================================================ regex=2.5.147 ================================================ FILE: Word_frequency_counter/runtime.txt ================================================ python-3.10.7 ================================================ FILE: Youtube Video Downloader/Readme.md ================================================ # YouTube Video Downloader with yt-dlp Integration ## Project Overview This project is a command-line based YouTube Video Downloader that integrates with `yt-dlp` to allow users to download videos from YouTube. It enables downloading in various formats and resolutions, giving users flexibility in managing their video downloads. ## Features - **Download YouTube Videos**: Download videos in various resolutions (360p, 720p, 1080p, etc.). - **Audio Extraction**: Extract and download only the audio from a YouTube video. - **Multiple Formats**: Support for multiple video formats like MP4, WebM, and audio formats like MP3, M4A. - **Batch Downloading**: Download multiple videos at once by providing a list of URLs. - **Simple Command-Line Interface**: Easy-to-use command-line input for seamless user experience. ## Technologies Used - **Python**: The core programming language. - **yt-dlp**: The powerful Python package used for downloading videos and audio from YouTube and other platforms. ## Installation To get started with this project, follow these steps: 1. **Clone the Repository**: ```bash git clone https://github.com/yourusername/YouTube-Video-Downloader.git ================================================ FILE: Youtube Video Downloader/main.py ================================================ import yt_dlp def download_video(url, resolution='highest'): try: # Set yt-dlp options for video download ydl_opts = { 'format': f'bestvideo[height<={resolution}]+bestaudio/best[height<={resolution}]' if resolution != 'highest' else 'best', 'outtmpl': '%(title)s.%(ext)s', # Output file name template } # Download video with yt-dlp with yt_dlp.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) print("Download completed!") except Exception as e: print(f"Error: {e}") if __name__ == "__main__": video_url = input("Enter YouTube URL: ") video_resolution = input("Enter resolution (e.g., 720p or leave blank for highest): ").strip() # Download the video with specified resolution download_video(video_url, video_resolution or 'highest') ================================================ FILE: Youtube Video Downloader/requirements.txt ================================================ yt-dlp ================================================ FILE: Youtube Video Downloader/runtime.txt ================================================ python-3.10.12 ================================================ FILE: personal-finance-tracker/README.md ================================================ Personal Finance Tracker Project Overview: The Personal Finance Tracker is a simple command-line application that helps users track their income, expenses, and savings goals. It also provides visualizations of spending patterns to better understand financial habits. The project uses SQLite for data storage and Matplotlib for creating various financial charts. Features: Add Income: Record income entries with descriptions and amounts. Add Expense: Record expenses, categorize them, and add descriptions. View Summary: View a summary of total income, expenses, and balance. Set Savings Goals: Define and track savings goals. Visualize Spending: Generate various charts (bar chart, pie chart, line chart, etc.) to better understand your spending habits. Technologies Used: Python: Core programming language. SQLite3: Local database for storing transaction records. Matplotlib: Python library for generating visualizations. To run the program: 1] Clone the repository 2] Navigate to Personal Finance Tracker folder 3] Run the main.py file When you run the application, a menu will appear with the following options: Add Income: Enter the amount and description of your income. Add Expense: Enter the amount, category, and description of the expense. View Summary: See your total income, expenses, and remaining balance. Set Savings Goal: Set a savings goal to track progress. Visualize Spending: Choose from various charts to visualize your spending patterns. ================================================ FILE: personal-finance-tracker/database.py ================================================ import sqlite3 DB_FILE = "data/finance.db" def get_connection(): conn = sqlite3.connect(DB_FILE) return conn def initialize_database(): conn = get_connection() cursor = conn.cursor() # Create income and expense table cursor.execute(''' CREATE TABLE IF NOT EXISTS transactions ( id INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT NOT NULL, category TEXT NOT NULL, amount REAL NOT NULL, date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ''') # Create table for savings goal cursor.execute(''' CREATE TABLE IF NOT EXISTS savings_goal ( id INTEGER PRIMARY KEY, goal_amount REAL NOT NULL ) ''') conn.commit() conn.close() ================================================ FILE: personal-finance-tracker/main.py ================================================ import tracker import savings import visualization import database def main_menu(): while True: print("\n--- Personal Finance Tracker ---") print("1. Add Income") print("2. Add Expense") print("3. View Summary") print("4. Set Savings Goal") print("5. Visualize Spending") print("6. Exit") choice = input("Choose an option: ") if choice == "1": tracker.add_income() elif choice == "2": tracker.add_expense() elif choice == "3": tracker.view_summary() elif choice == "4": savings.set_goal() elif choice == "5": visualization.visualize_data() elif choice == "6": print("Exiting...") break else: print("Invalid option. Please try again.") if __name__ == "__main__": database.initialize_database() main_menu() ================================================ FILE: personal-finance-tracker/savings.py ================================================ from database import get_connection def set_goal(): goal_amount = float(input("Enter your savings goal: ")) conn = get_connection() cursor = conn.cursor() cursor.execute("INSERT OR REPLACE INTO savings_goal (id, goal_amount) VALUES (1, ?)", (goal_amount,)) conn.commit() conn.close() print(f"Savings goal of {goal_amount} set successfully!") def track_savings_progress(balance): conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT goal_amount FROM savings_goal WHERE id = 1") goal_row = cursor.fetchone() conn.close() if goal_row: goal_amount = goal_row[0] remaining = goal_amount - balance if remaining > 0: print(f"You need to save {remaining} more to reach your goal.") else: print(f"Congratulations! You've reached your savings goal.") else: print("No savings goal set.") ================================================ FILE: personal-finance-tracker/tracker.py ================================================ import sqlite3 from database import get_connection def add_income(): category = input("Enter income source (e.g., Salary, Freelance): ") amount = float(input("Enter amount: ")) conn = get_connection() cursor = conn.cursor() cursor.execute("INSERT INTO transactions (type, category, amount) VALUES (?, ?, ?)", ("Income", category, amount)) conn.commit() conn.close() print("Income added successfully!") def add_expense(): category = input("Enter expense category (e.g., Rent, Groceries): ") amount = float(input("Enter amount: ")) conn = get_connection() cursor = conn.cursor() cursor.execute("INSERT INTO transactions (type, category, amount) VALUES (?, ?, ?)", ("Expense", category, amount)) conn.commit() conn.close() print("Expense added successfully!") def view_summary(): conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT SUM(amount) FROM transactions WHERE type = 'Income'") total_income = cursor.fetchone()[0] or 0.0 cursor.execute("SELECT SUM(amount) FROM transactions WHERE type = 'Expense'") total_expenses = cursor.fetchone()[0] or 0.0 balance = total_income - total_expenses conn.close() print(f"\nTotal Income: {total_income}") print(f"Total Expenses: {total_expenses}") print(f"Balance: {balance}") ================================================ FILE: personal-finance-tracker/visualization.py ================================================ import matplotlib.pyplot as plt from database import get_connection def bar_chart_expense(): conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT category, SUM(amount) FROM transactions WHERE type = 'Expense' GROUP BY category") rows = cursor.fetchall() conn.close() if rows: categories = [row[0] for row in rows] amounts = [row[1] for row in rows] plt.bar(categories, amounts) plt.xlabel('Category') plt.ylabel('Amount') plt.title('Spending by Category') plt.xticks(rotation=45) plt.tight_layout() plt.show() else: print("No expenses recorded yet.") def pie_chart_expense(): conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT category, SUM(amount) FROM transactions WHERE type = 'Expense' GROUP BY category") rows = cursor.fetchall() conn.close() if rows: categories = [row[0] for row in rows] amounts = [row[1] for row in rows] plt.pie(amounts, labels=categories, autopct='%1.1f%%', startangle=90) plt.title('Spending by Category') plt.tight_layout() plt.show() else: print("No expenses recorded yet.") def line_chart_expense_over_time(): conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT date, SUM(amount) FROM transactions WHERE type = 'Expense' GROUP BY date") rows = cursor.fetchall() conn.close() if rows: dates = [row[0] for row in rows] amounts = [row[1] for row in rows] plt.plot(dates, amounts, marker='o') plt.xlabel('Date') plt.ylabel('Amount') plt.title('Expenses Over Time') plt.xticks(rotation=45) plt.tight_layout() plt.show() else: print("No expenses recorded yet.") def stacked_bar_chart_income_expense(): conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT date, SUM(amount) FROM transactions WHERE type = 'Income' GROUP BY date") income_rows = cursor.fetchall() cursor.execute("SELECT date, SUM(amount) FROM transactions WHERE type = 'Expense' GROUP BY date") expense_rows = cursor.fetchall() conn.close() if income_rows and expense_rows: income_dates = [row[0] for row in income_rows] income_amounts = [row[1] for row in income_rows] expense_dates = [row[0] for row in expense_rows] expense_amounts = [row[1] for row in expense_rows] plt.bar(income_dates, income_amounts, label='Income') plt.bar(expense_dates, expense_amounts, bottom=income_amounts, label='Expense') plt.xlabel('Date') plt.ylabel('Amount') plt.title('Income vs Expenses Over Time') plt.xticks(rotation=45) plt.legend() plt.tight_layout() plt.show() else: print("Not enough data to generate this chart.") def histogram_expense_distribution(): conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT amount FROM transactions WHERE type = 'Expense'") rows = cursor.fetchall() conn.close() if rows: amounts = [row[0] for row in rows] plt.hist(amounts, bins=10) plt.xlabel('Expense Amount') plt.ylabel('Frequency') plt.title('Expense Distribution') plt.tight_layout() plt.show() else: print("No expenses recorded yet.") def visualize_data(): print("\n--- Visualization Menu ---") print("1. Bar Chart (Spending by Category)") print("2. Pie Chart (Spending by Category)") print("3. Line Chart (Expenses Over Time)") print("4. Stacked Bar Chart (Income vs Expenses)") print("5. Histogram (Expense Distribution)") choice = input("Select a visualization option (1-5): ") if choice == "1": bar_chart_expense() elif choice == "2": pie_chart_expense() elif choice == "3": line_chart_expense_over_time() elif choice == "4": stacked_bar_chart_income_expense() elif choice == "5": histogram_expense_distribution() else: print("Invalid choice. Please select a valid option.")