[
  {
    "path": ".github/ISSUE_TEMPLATE/PROJECT_SUGGESTION_TEMPLATE.md",
    "content": "---\nname: Project Suggestion\nabout: Propose an idea for a new project\ntitle: \"\"\nlabels: \"Project Suggestion\"\nassignees: \"\"\n---\n\n### Project Suggestion Title\n_A concise title for your project suggestion._\n\n### Description\n_Provide a detailed description of the project idea or feature you would like to propose._\n\n### Benefits\n_Explain how this project or feature would benefit the community or improve the existing repository._\n\n### Implementation Ideas\n_Offer any initial thoughts on how the project could be implemented, including potential technologies or approaches._\n\n### Additional Context\n_Include any other relevant information, links, or references that might help._\n\n### Suggested Contributors\n_If you have specific contributors in mind who might be interested in this project, please list them here._\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: \"Bug Report\"\nabout: \"Report a bug or issue.\"\ntitle: \"Bug Report Title\"\nlabels: [\"bug\", \"help wanted\"]\n---\n\n## Description\nPlease describe the bug you encountered, including steps to reproduce it.\n\n## Steps to Reproduce\n1. Step 1\n2. Step 2\n3. Step 3 ...\n\n## Expected Behavior\nWhat did you expect to happen?\n\n## Actual Behavior\nWhat actually happened?\n\n## Additional Context\nAdd any other context about the problem, screenshots, or logs that might be helpful.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "blank_issues_enabled: false \ncontact: false \n\ntemplates:\n  - name: \"Project Suggestion\"\n    description: \"Propose an idea for a new project.\"\n    title: \"Project Suggestion Title\"\n    labels: [\"Project Suggestion\"]\n  \n  - name: \"Bug Report\"\n    description: \"Report a bug or issue.\"\n    title: \"Bug Report Title\"\n    labels: [\"bug\", \"help wanted\"]\n  \n  - name: \"Feature Request\"\n    description: \"Request a new feature or enhancement.\"\n    title: \"Feature Request Title\"\n    labels: [\"feature\", \"enhancement\"]\n\n  - name: \"Other\"\n    description: \"Use this template for any other issues or inquiries.\"\n    title: \"Other Issue Title\"\n    labels: [\"question\", \"others\"]\n\nchoose_template:\n  title: \"Choose an Issue Template\"\n  description: \"Please select one of the templates below to create your issue.\"\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.md",
    "content": "---\nname: \"Feature Request\"\nabout: \"Request a new feature or enhancement.\"\ntitle: \"Feature Request Title\"\nlabels: [\"feature\", \"enhancement\"]\n---\n\n## Feature Description\nPlease describe the feature you would like to request.\n\n## Use Cases\nHow will this feature be used? Please provide examples.\n\n## Additional Context\nAdd any other context about the feature request, including design ideas or potential impacts.\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/other_issue.md",
    "content": "---\nname: \"Other\"\nabout: \"Use this template for any other issues or inquiries.\"\ntitle: \"Other Issue Title\"\nlabels: [\"question\", \"other\"]\n---\n\n## Description\nPlease provide a detailed description of your inquiry or issue.\n\n## Context\nAdd any relevant context or background information that may help in addressing your request.\n\n## Additional Information\nIf applicable, include any additional information, screenshots, or references.\n"
  },
  {
    "path": ".github/PROJECT_SUGGESTION_TEMPLATE.md",
    "content": "### Project Suggestion Title\n_A concise title for your project suggestion._\n\n### Description\n_Provide a detailed description of the project idea or feature you would like to propose._\n\n### Benefits\n_Explain how this project or feature would benefit the community or improve the existing repository._\n\n### Implementation Ideas\n_Offer any initial thoughts on how the project could be implemented, including potential technologies or approaches._\n\n### Additional Context\n_Include any other relevant information, links, or references that might help._\n\n### Suggested Contributors\n_If you have specific contributors in mind who might be interested in this project, please list them here._\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "### Developer Checklist\n- [ ] Adhered to the guidelines outlined in the README & Contributing file.\n- [ ] Maintained the correct directory structure (e.g., ProjectName/...yourfiles).\n- [ ] Please ensure to include a README file for enhanced project clarity.\n- [ ] Starred ⭐ the repository (optional).\n\n### Summary\n###### _Please provide a brief summary here._\n\n### Screenshot\n###### _Attach any relevant screenshots or GIFs here._\n\n### Live Project Link\n###### _Include a link to the live project here._\n"
  },
  {
    "path": ".github/workflows/generate-project-list.yml",
    "content": "name: Generate Project List\n\non:\n  push:\n    branches:\n      - main\n\njobs:\n  generate-list:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@v3\n        with:\n          token: ${{ secrets.ACTION_TOKEN }}\n          persist-credentials: true\n\n      - name: Fetch latest changes\n        run: git fetch origin\n\n      - name: Merge changes\n        run: |\n          git merge origin/main || echo \"No new changes to merge or merge conflict\"\n\n      - name: Generate project list\n        run: |\n          exclude_dirs=(.github)\n          exclude_files=(\"LICENSE\" \"README.md\" \"CONTRIBUTING.md\" \"Example README.md\" \"CODE_OF_CONDUCT.md\" \"PROJECTS.md\")\n\n          projects=()\n          for dir in */; do\n            if [[ ! \" ${exclude_dirs[@]} \" =~ \" ${dir%/} \" ]]; then\n              projects+=(\"$dir\")\n            fi\n          done\n\n          echo \"# Project List\" > PROJECTS.md\n          echo \"\" >> PROJECTS.md\n\n          for project in \"${projects[@]}\"; do\n            project_name=${project%/}\n            safe_project_name=${project_name// /%20}\n            echo \"* [$project_name](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/$safe_project_name)\" >> PROJECTS.md\n          done\n\n          for file in \"${exclude_files[@]}\"; do\n            sed -i \"/$file/d\" PROJECTS.md\n          done\n\n          # Debug output to check the content of PROJECTS.md\n          cat PROJECTS.md\n\n      - name: Commit project list\n        run: |\n          git config --global user.email \"github-actions[bot]@users.noreply.github.com\"\n          git config --global user.name \"github-actions[bot]\"\n          git add PROJECTS.md\n          if ! git diff --cached --exit-code; then\n            git commit -m \"Update project list\"\n            git push --force-with-lease\n          else\n            echo \"No changes to commit.\"\n          fi\n        env:\n          GITHUB_TOKEN: ${{ secrets.ACTION_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/welcome.yml",
    "content": "name: Welcome Comments\n\npermissions:\n  actions: write\n  attestations: write\n  checks: write\n  contents: write\n  deployments: write\n  id-token: write\n  issues: write\n  discussions: write\n  packages: write\n  pages: write\n  pull-requests: write\n  repository-projects: write\n  security-events: write\n  statuses: write\n\non:\n  issues:\n    types: [opened, closed]\n  pull_request_target:\n    types: [opened, closed]\n\njobs:\n  welcomer:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Auto Welcome on Issues or PRs\n        uses: actions/github-script@v6\n        with:\n          github-token: ${{ secrets.GITHUB_TOKEN }}\n          script: |\n            const author = context.payload.sender.login;\n            const commentBody = (message) => `👋 @${author} 👋\\n\\n${message}`;\n\n            if (context.eventName === 'issues') {\n              const issue = context.payload.issue;\n\n              if (context.payload.action === 'opened') {\n                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.`;\n                github.rest.issues.createComment({\n                  issue_number: issue.number,\n                  owner: context.repo.owner,\n                  repo: context.repo.repo,\n                  body: commentBody(message),\n                });\n              } else if (context.payload.action === 'closed') {\n                const message = `Thanks for closing the issue! We appreciate your updates.`;\n                github.rest.issues.createComment({\n                  issue_number: issue.number,\n                  owner: context.repo.owner,\n                  repo: context.repo.repo,\n                  body: commentBody(message),\n                });\n              }\n            } else if (context.eventName === 'pull_request_target') {\n              const pr = context.payload.pull_request;\n\n              if (context.payload.action === 'opened') {\n                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.`;\n                github.rest.issues.createComment({\n                  issue_number: pr.number,\n                  owner: context.repo.owner,\n                  repo: context.repo.repo,\n                  body: commentBody(message),\n                });\n              } else if (context.payload.action === 'closed') {\n            \t\tconst message = pr.merged \n                  ? `🎉 You've just merged your pull request! We're excited to have you in our community. Keep up the fantastic contributions to the project!`\n                  : `Thanks for closing the pull request! Your contributions are valuable to us.`;\n                \n                github.rest.issues.createComment({\n                  issue_number: pr.number,\n                  owner: context.repo.owner,\n                  repo: context.repo.repo,\n                  body: commentBody(message),\n                });\n              }\n            }\n"
  },
  {
    "path": "Age Calculator/calculate.py",
    "content": "import time\nfrom calendar import isleap\n\ndef judge_leap_year(year):\n    if isleap(year):\n        return True\n    else:\n        return False\n\ndef month_days(month, leap_year):\n    if month in [1, 3, 5, 7, 8, 10, 12]:\n        return 31\n    elif month in [4, 6, 9, 11]:\n        return 30\n    elif month == 2 and leap_year:\n        return 29\n    elif month == 2 and (not leap_year):\n        return 28\n\n\nname = input(\"Please enter your name: \")\nage = input(\"Please enter your age: \")\nlocaltime = time.localtime(time.time())\n\nyear = int(age)\nmonth = year * 12 + localtime.tm_mon\nday = 0\n\nbegin_year = int(localtime.tm_year) - year\nend_year = begin_year + year\n\nfor y in range(begin_year, end_year):\n    if (judge_leap_year(y)):\n        day = day + 366\n    else:\n        day = day + 365\n\nleap_year = judge_leap_year(localtime.tm_year)\nfor m in range(1, localtime.tm_mon):\n    day = day + month_days(m, leap_year)\n\nday = day + localtime.tm_mday\nprint(\"\\n\\t%s's age is %d years or \" % (name, year), end=\"\")\nprint(\"%d months or %d days\" % (month, day))\n"
  },
  {
    "path": "Age Calculator/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Alarm Bot/main.py",
    "content": "from tkinter import *\nimport datetime\nimport time\nimport winsound\nfrom threading import *\n\nroot = Tk()\nroot.geometry(\"400x200\")\n\ndef Threading():\n\tt1=Thread(target=alarm)\n\tt1.start()\n\ndef alarm():\n\twhile True:\n\t\tset_alarm_time = f\"{hour.get()}:{minute.get()}:{second.get()}\"\n\t\ttime.sleep(1)\n\t\tcurrent_time = datetime.datetime.now().strftime(\"%H:%M:%S\")\n\t\tprint(current_time,set_alarm_time)\n\n\t\tif current_time == set_alarm_time:\n\t\t\tprint(\"Time to Wake up\")\n\t\t\twinsound.PlaySound(\"sound.wav\",winsound.SND_ASYNC)\n\nLabel(root,text=\"Alarm Clock\",font=(\"Helvetica 20 bold\"),fg=\"red\").pack(pady=10)\nLabel(root,text=\"Set Time\",font=(\"Helvetica 15 bold\")).pack()\n\nframe = Frame(root)\nframe.pack()\n\nhour = StringVar(root)\nhours = ('00', '01', '02', '03', '04', '05', '06', '07',\n\t\t'08', '09', '10', '11', '12', '13', '14', '15',\n\t\t'16', '17', '18', '19', '20', '21', '22', '23', '24'\n\t\t)\nhour.set(hours[0])\n\nhrs = OptionMenu(frame, hour, *hours)\nhrs.pack(side=LEFT)\n\nminute = StringVar(root)\nminutes = ('00', '01', '02', '03', '04', '05', '06', '07',\n\t\t'08', '09', '10', '11', '12', '13', '14', '15',\n\t\t'16', '17', '18', '19', '20', '21', '22', '23',\n\t\t'24', '25', '26', '27', '28', '29', '30', '31',\n\t\t'32', '33', '34', '35', '36', '37', '38', '39',\n\t\t'40', '41', '42', '43', '44', '45', '46', '47',\n\t\t'48', '49', '50', '51', '52', '53', '54', '55',\n\t\t'56', '57', '58', '59', '60')\nminute.set(minutes[0])\n\nmins = OptionMenu(frame, minute, *minutes)\nmins.pack(side=LEFT)\n\nsecond = StringVar(root)\nseconds = ('00', '01', '02', '03', '04', '05', '06', '07',\n\t\t'08', '09', '10', '11', '12', '13', '14', '15',\n\t\t'16', '17', '18', '19', '20', '21', '22', '23',\n\t\t'24', '25', '26', '27', '28', '29', '30', '31',\n\t\t'32', '33', '34', '35', '36', '37', '38', '39',\n\t\t'40', '41', '42', '43', '44', '45', '46', '47',\n\t\t'48', '49', '50', '51', '52', '53', '54', '55',\n\t\t'56', '57', '58', '59', '60')\nsecond.set(seconds[0])\n\nsecs = OptionMenu(frame, second, *seconds)\nsecs.pack(side=LEFT)\n\nButton(root,text=\"Set Alarm\",font=(\"Helvetica 15\"),command=Threading).pack(pady=20)\nroot.mainloop()\n"
  },
  {
    "path": "Alarm Bot/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Ascii Art Generator/generate.py",
    "content": "import cv2\nimport numpy as np\nimport sys\n\nsymbols_list = [\"#\", \"-\", \"*\", \".\", \"+\", \"o\"]\nthreshold_list = [0, 50, 100, 150, 200]\n\ndef print_out_ascii(array):\n    for row in array:\n        for e in row:\n            print(symbols_list[int(e) % len(symbols_list)], end=\"\")\n        print()\n\n\ndef img_to_ascii(image):\n    height, width = image.shape\n    new_width = int(width / 20) \n    new_height = int(height / 40)\n\n    resized_image = cv2.resize(image, (new_width, new_height),)\n\n    thresh_image = np.zeros(resized_image.shape)\n\n    for i, threshold in enumerate(threshold_list):\n        thresh_image[resized_image > threshold] = i\n    return thresh_image\n\n\nif __name__ == \"__main__\":\n\n    if len(sys.argv) < 2:\n        print(\"Image Path not specified : Using sample_image.png\\n\")\n        image_path = \"sample_image.png\"\n\n    if len(sys.argv) == 2:\n        print(\"Using {} as Image Path\\n\".format(sys.argv[1]))\n        image_path = sys.argv[1]\n\n    image = cv2.imread(image_path, 0)\n    ascii_art = img_to_ascii(image)\n    print_out_ascii(ascii_art)\n    "
  },
  {
    "path": "Ascii Art Generator/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Audio Book Generator/main.py",
    "content": "from gtts import gTTS\nimport PyPDF2\n\npdf_File = open('name.pdf', 'rb') \n\npdf_Reader = PyPDF2.PdfFileReader(pdf_File)\ncount = pdf_Reader.numPages\ntextList = []\n\nfor i in range(count):\n   try:\n    page = pdf_Reader.getPage(i)    \n    textList.append(page.extractText())\n   except:\n       pass\n\ntextString = \" \".join(textList)\nprint(textString)\nlanguage = 'en'\n\nmyAudio = gTTS(text=textString, lang=language, slow=False)\nmyAudio.save(\"Audio.mp3\")\n"
  },
  {
    "path": "Audio Book Generator/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Code of Conduct\n*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.*\n\n*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.*\n\n## Our Standards\n- Examples of behavior that contributes to creating a positive environment include:\n    - Be respectful of others and their opinions\n    - Refrain from using discriminatory language or behavior\n    - Avoid engaging in personal attacks or harassment\n    - Help create a safe and positive environment for everyone\n    - Follow the project's guidelines and procedures\n\n- Examples of unacceptable behavior by participants include:\n    - Harassment or discrimination of any kind\n    - Threats, bullying, or violence\n    - Sharing of private information without consent\n    - Plagiarism or infringement of intellectual property rights\n    - Any other behavior that is deemed unacceptable by the project maintainers\n\n## Our Responsibilities\n- 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.\n- 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.\n\n## Consequences\n- If you engage in behavior that violates this Code of Conduct, you may be asked to stop, or other appropriate action may be taken. \n- If any unacceptable behavior will be determined by the project maintainers, and may include:\n  - Warning\n  - Removal from the project or community\n  - Reporting to appropriate authorities\n\n## Reporting\n- 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.\n\n## Attribution\n- 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)\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing Guidelines \n*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.*\n\n## How to Contribute\n*Here are some ways you can contribute:*\n- [Report an issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/creating-an-issue)\n- [Suggest a feature](CONTRIBUTING.md)\n- Improve the documentation\n- [Contribute code](CODE_OF_CONDUCT.md)\n\n## Reporting Issues\n*When reporting an issue, please include the following:*\n- A clear and descriptive title\n- A detailed description of the issue, including steps to reproduce the problem\n- Screenshots or other relevant media\n- The version of the project and dependencies you are using\n- The operating system and version you are using\n\n## Suggest a feature\n*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.*\n\n## Improve the documentation\n*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.*\n\n## Contribute code Guidelines\n*If you're interested in contributing code to the project, please follow these guidelines:*\n\n- Fork the repository. This creates a copy of the code that you can work on without affecting the original project.\n- Create a new branch. Use a descriptive name that reflects the changes you plan to make.\n- Make your changes. Keep your code clean, well-organized, and easy to read. Follow the project's existing coding style as closely as possible.\n- Test your changes. Make sure your changes don't break existing functionality and that they work as expected.\n- 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.\n- Add documentation. Add documentation to the README.md file and to the code files.\n\n## Pull Request Guidelines\n- Fork the repository and create a new branch for your changes.\n- Follow the existing code style and conventions.\n- Include tests for any new code.\n- Make sure all tests pass before submitting the pull request.\n- Do not include changes to the README or other documentation in the same pull request as code changes.\n\n## Code of Conduct\n*Please note that this project is released with a Code of Conduct. By participating in this project you agree to abide by its terms.*\n\n## License\nThis project is licensed under the terms of the MIT license.\n\n## Thank you!\nThank you for your interest in contributing to this project! We appreciate your help and look forward to working with you.\n"
  },
  {
    "path": "CountDown Timer/main.py",
    "content": "from tkinter import *\nimport tkinter as tk\n\nclass Application(Frame):\n    def __init__(self,master):\n        super(Application,self).__init__(master)\n        self.pack()\n        self.createWidgets()\n        \n        self.master.geometry(\"300x200\")\n        self._alarm_id = None\n        self._paused = False\n        self._starttime = 0\n    \n    # def startTimer(self):\n\n    def createWidgets(self):\n\n        self.someFrame = Frame(self)\n        self.time_var = StringVar()\n        self.input_time = tk.Entry(self, width=25, font=('Calibri',12), textvariable = self.time_var)\n        # Adding placeholder\n        self.input_time.insert(0, \"Enter Time in seconds\")\n        self.input_time.pack(padx=10,pady=(30,10))\n        #using bind method\n        self.input_time.bind(\"<Button-1>\", self.enter)\n        \n        self.startButton = Button(self.someFrame, text=\"Start\", font=('Helvetica',12), bg='green', fg='white', command=self.startTime)\n        self.startButton.pack(side=LEFT, padx=5)\n\n        self.pauseButton = Button(self.someFrame, text=\"Pause\", font=('Helvetica',12), bg='azure', command=self.pauseTime)\n        self.pauseButton.pack(side=LEFT, padx=5)\n\n        self.resetButton = Button(self.someFrame, text=\"Reset\", font=('Helvetica',12), bg='azure', command=self.resetTime)\n        self.resetButton.pack(side=LEFT, padx=5)\n\n        self.closeButton = Button(self.someFrame, text=\"Close\", font=('Helvetica',12), bg='red',fg='white', command=self.closeApp)\n        self.closeButton.pack(side=LEFT, padx=5)\n        self.someFrame.pack(side=TOP)\n\n        self.labelvariable = StringVar()\n        self.labelvariable.set(\"\")\n\n        self.thelabel = Label(self,textvariable = self.labelvariable,font=('Helvetica',50))\n        self.thelabel.pack(side=TOP)\n\n    # Removes placeholder text in the Entry widget\n    def enter(self,*args):\n        self.input_time.delete(0, 'end')\n        \n    # Resume function\n    def startTime(self):\n        self.get_time = self.time_var.get()\n        try:\n            self.time_in_int = int(self.get_time)\n        except:\n            self.time_in_int = 0\n        self._starttime = self.time_in_int\n        self._paused = False\n        if self._alarm_id is None:\n            self.countdown(self._starttime)\n\n    # Pause function\n    def pauseTime(self):\n        if self._alarm_id is not None:\n            self._paused = True\n\n    # Reset function\n    def resetTime(self):\n        if self._alarm_id is not None:\n            self.master.after_cancel(self._alarm_id)\n            self._alarm_id = None\n            self._paused = False\n            self.countdown(0)\n            self._paused = True\n    \n    def closeApp(self):\n        self.master.destroy()\n\n    def countdown(self, timeInSeconds, start=True):\n        if timeInSeconds == 0:\n            self._starttime=0\n            self.labelvariable.set(\"0\")\n            return\n        if start:\n            self._starttime = timeInSeconds\n        if self._paused:\n            self._alarm_id = self.master.after(1000, self.countdown, timeInSeconds, False)\n        else:\n            app.labelvariable.set(timeInSeconds)\n            self._alarm_id = self.master.after(1000, self.countdown, timeInSeconds-1, False)\n\n\nif __name__ == '__main__':\n    root = Tk()\n    root.title(\"Countdown Timer\")\n    app = Application(root)\n    root.mainloop()\n \n"
  },
  {
    "path": "CountDown Timer/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Currency Converter/main.py",
    "content": "import requests\n\nclass Currency_convertor:\n\trates = {}\n\tdef __init__(self, url):\n\t\tdata = requests.get(url).json()\n\t\tself.rates = data[\"rates\"]\n\n\tdef convert(self, from_currency, to_currency, amount):\n\t\tinitial_amount = amount\n\t\tif from_currency != 'EUR' :\n\t\t\tamount = amount / self.rates[from_currency]\n\n\t\tamount = round(amount * self.rates[to_currency], 2)\n\t\tprint('{} {} = {} {}'.format(initial_amount, from_currency, amount, to_currency))\n\nif __name__ == \"__main__\":\n\turl = str.__add__('http://data.fixer.io/api/latest?access_key=', YOUR_ACCESS_KEY)\n\tc = Currency_convertor(url)\n\tamount = int(input(\"Amount: \"))\n\tfrom_country = input(\"From Country: \")\n\tto_country = input(\"TO Country: \")\n\n\tc.convert(from_country, to_country, amount)\n"
  },
  {
    "path": "Currency Converter/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Custom GPT/README.md",
    "content": "# Conversational Retrieval with LangChain and OpenAI\r\n\r\nThis 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.\r\n\r\n## Features\r\n\r\n- Load documents from a specified directory.\r\n- Create and persist a vector store index for efficient querying.\r\n- Engage in conversational interactions, maintaining chat history.\r\n- Easily exit the program.\r\n\r\n## Requirements\r\n\r\n- Python 3.7+\r\n- Required packages:\r\n  - `openai`\r\n  - `langchain`\r\n  - `chromadb`\r\n\r\nYou can install the required packages using pip:\r\n\r\n```bash\r\npip install openai langchain chromadb\r\n```\r\n## Setup\r\n1. Clone the Repository:\r\n    ```bash\r\n    git clone https://github.com/king04aman/custom-gpt.git\r\n    cd your_repository\r\n    ```\r\n2. Set the OpenAI API Key:\r\nReplace `your_api_key_here` in the script with your actual OpenAI API key. You can also set the environment variable directly in your terminal:\r\n    ```bash\r\n    export OPENAI_API_KEY=\"your_api_key_here\"\r\n    ```\r\n3. Prepare Your Data:\r\nPlace your documents in a folder named `data/`. The script will load all documents from this directory.\r\n\r\n## Usage\r\nRun the script from the command line:\r\n```bash\r\npython main.py\r\n```\r\n### Command Line Arguments\r\nYou can provide an initial query as a command line argument:\r\n```bash\r\npython main.py \"Your initial query here\"\r\n```\r\n### Interactive Mode\r\nIf 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.\r\n\r\n### Persistence\r\n- Set the `PERSIST` variable to `True` in the script to enable saving the vector store index to disk for reuse in future sessions.\r\n- The index will be saved in a directory named `persist/`.\r\n\r\n## Example\r\n```bash\r\nPrompt (type 'quit' to exit): What is the significance of data persistence?\r\nResponse: [Your response here based on the documents]\r\n```\r\n\r\n## License\r\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\r\n\r\n## Contributing\r\nFeel free to submit issues or pull requests. Contributions are welcome!\r\n"
  },
  {
    "path": "Custom GPT/data/data.txt",
    "content": ""
  },
  {
    "path": "Custom GPT/example-env",
    "content": "OPENAI_API_KEY = \"your_api_key\""
  },
  {
    "path": "Custom GPT/main.py",
    "content": "import os\r\nimport openai\r\nimport sys\r\nfrom langchain.chains import ConversationalRetrievalChain\r\nfrom langchain.chat_models import ChatOpenAI\r\nfrom langchain.document_loaders import DirectoryLoader\r\nfrom langchain.embeddings import OpenAIEmbeddings\r\nfrom langchain.indexes import VectorstoreIndexCreator\r\nfrom langchain.indexes.vectorstore import VectorStoreIndexWrapper\r\nfrom langchain.vectorstores import Chroma\r\n\r\n\r\nos.environ[\"OPENAI_API_KEY\"] = \"your_api_key_here\"\r\nPERSIST = False\r\n\r\nquery = sys.argv[1] if len(sys.argv) > 1 else None\r\n\r\nif PERSIST and os.path.exists(\"persist\"):\r\n    print(\"Reusing index...\\n\")\r\n    vectorstore = Chroma(persist_directory=\"persist\", embedding_function=OpenAIEmbeddings())\r\n    index = VectorStoreIndexWrapper(vectorstore=vectorstore)\r\nelse:\r\n    loader = DirectoryLoader(\"data/\")\r\n    index = VectorstoreIndexCreator(vectorstore_kwargs={\"persist_directory\": \"persist\"}).from_loaders([loader]) if PERSIST else VectorstoreIndexCreator().from_loaders([loader])\r\n\r\nchain = ConversationalRetrievalChain.from_llm(\r\n    llm=ChatOpenAI(model=\"gpt-3.5-turbo\"),\r\n    retriever=index.vectorstore.as_retriever(search_kwargs={\"k\": 1}),\r\n)\r\n\r\nchat_history = []\r\n\r\nwhile True:\r\n    if not query:\r\n        query = input(\"Prompt (type 'quit' to exit): \")\r\n    if query.lower() in ['quit', 'q', 'exit']:\r\n        print(\"Exiting the program...\")\r\n        sys.exit()\r\n    \r\n    result = chain({\"question\": query, \"chat_history\": chat_history})\r\n    \r\n    print(\"Response:\", result['answer'])\r\n\r\n    chat_history.append((query, result['answer']))\r\n    query = None \r\n"
  },
  {
    "path": "Customizable_Workout_Playlist_Generator/README_SONG.md",
    "content": "# Customizable Workout Playlist Generator\n\nThis 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.\n\n## Features\n\n- Generate playlists for various workout types (e.g., HIIT, yoga, cardio)\n- Customize playlist duration\n- Filter songs by genre and BPM range\n- Integration with Spotify, Apple Music, and YouTube Music (API keys required)\n- Save and load playlists in JSON format\n\n## Requirements\n\n- Python 3.6+\n- Required Python packages (see `requirements.txt`)\n\n## Installation\n\n1. Clone this repository:\n   ```\n   git clone https://github.com/Ashutoshdas-dev/All-In-One-Python-Projects.git\n   cd Customizable_Workout_Playlist_Generator\n   ```\n\n2. Install the required packages:\n   ```\n   pip install -r requirements.txt\n   ```\n\n3. Set up API credentials for the music services you want to use (Spotify, Apple Music, or YouTube Music).\n\n## Usage\n\n1. Run the main script:\n   ```\n   python playlist.py\n   ```\n\n2. Follow the prompts to:\n   - Choose a music source (local database, Spotify, Apple Music, or YouTube Music)\n   - Enter workout type, duration, preferred genres, and BPM range\n   - Generate and view the playlist\n   - Save the playlist to a JSON file (optional)\n\n3. Repeat the process to generate multiple playlists or exit the program.\n\n## API Integration\n\nTo use the music streaming service integrations, you'll need to set up API credentials:\n\n- Spotify: Set up a Spotify Developer account and create an app to get your client ID and client secret.\n- Apple Music: Obtain an Apple Developer account and set up MusicKit.\n- YouTube Music: No authentication is required for basic usage.\n\nUpdate the respective client classes in `playlist.py` with your API credentials.\n"
  },
  {
    "path": "Customizable_Workout_Playlist_Generator/hiit_playlist.json",
    "content": "[\n  {\n    \"title\": \"Lose Yourself\",\n    \"artist\": \"Eminem\",\n    \"duration\": 326,\n    \"bpm\": 171,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"Till I Collapse\",\n    \"artist\": \"Eminem\",\n    \"duration\": 297,\n    \"bpm\": 171,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"God's Plan\",\n    \"artist\": \"Drake\",\n    \"duration\": 198,\n    \"bpm\": 154,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"Blinding Lights\",\n    \"artist\": \"The Weeknd\",\n    \"duration\": 200,\n    \"bpm\": 171,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Sicko Mode\",\n    \"artist\": \"Travis Scott\",\n    \"duration\": 312,\n    \"bpm\": 155,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"In the End\",\n    \"artist\": \"Linkin Park\",\n    \"duration\": 217,\n    \"bpm\": 105,\n    \"genre\": \"rock\"\n  },\n  {\n    \"title\": \"HUMBLE.\",\n    \"artist\": \"Kendrick Lamar\",\n    \"duration\": 177,\n    \"bpm\": 150,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"Shape of You\",\n    \"artist\": \"Ed Sheeran\",\n    \"duration\": 233,\n    \"bpm\": 96,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Rockstar\",\n    \"artist\": \"Post Malone\",\n    \"duration\": 218,\n    \"bpm\": 80,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"Senorita\",\n    \"artist\": \"Shawn Mendes\",\n    \"duration\": 190,\n    \"bpm\": 117,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Bad Guy\",\n    \"artist\": \"Billie Eilish\",\n    \"duration\": 194,\n    \"bpm\": 135,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Believer\",\n    \"artist\": \"Imagine Dragons\",\n    \"duration\": 204,\n    \"bpm\": 125,\n    \"genre\": \"rock\"\n  },\n  {\n    \"title\": \"Old Town Road\",\n    \"artist\": \"Lil Nas X\",\n    \"duration\": 157,\n    \"bpm\": 136,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"7 Rings\",\n    \"artist\": \"Ariana Grande\",\n    \"duration\": 178,\n    \"bpm\": 70,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Sunflower\",\n    \"artist\": \"Post Malone\",\n    \"duration\": 158,\n    \"bpm\": 90,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"No Tears Left to Cry\",\n    \"artist\": \"Ariana Grande\",\n    \"duration\": 206,\n    \"bpm\": 122,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Lucid Dreams\",\n    \"artist\": \"Juice WRLD\",\n    \"duration\": 239,\n    \"bpm\": 84,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"Memories\",\n    \"artist\": \"Maroon 5\",\n    \"duration\": 189,\n    \"bpm\": 91,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Savage Love\",\n    \"artist\": \"Jawsh 685 & Jason Derulo\",\n    \"duration\": 171,\n    \"bpm\": 96,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Levitating\",\n    \"artist\": \"Dua Lipa\",\n    \"duration\": 203,\n    \"bpm\": 103,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"One Dance\",\n    \"artist\": \"Drake\",\n    \"duration\": 173,\n    \"bpm\": 104,\n    \"genre\": \"afrobeats\"\n  },\n  {\n    \"title\": \"Stressed Out\",\n    \"artist\": \"Twenty One Pilots\",\n    \"duration\": 185,\n    \"bpm\": 85,\n    \"genre\": \"alternative\"\n  },\n  {\n    \"title\": \"Radioactive\",\n    \"artist\": \"Imagine Dragons\",\n    \"duration\": 186,\n    \"bpm\": 136,\n    \"genre\": \"rock\"\n  },\n  {\n    \"title\": \"Rolling in the Deep\",\n    \"artist\": \"Adele\",\n    \"duration\": 228,\n    \"bpm\": 105,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Closer\",\n    \"artist\": \"The Chainsmokers\",\n    \"duration\": 244,\n    \"bpm\": 95,\n    \"genre\": \"electronic\"\n  },\n  {\n    \"title\": \"Shake It Off\",\n    \"artist\": \"Taylor Swift\",\n    \"duration\": 219,\n    \"bpm\": 160,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Uptown Funk\",\n    \"artist\": \"Mark Ronson ft. Bruno Mars\",\n    \"duration\": 269,\n    \"bpm\": 115,\n    \"genre\": \"funk\"\n  },\n  {\n    \"title\": \"Sorry\",\n    \"artist\": \"Justin Bieber\",\n    \"duration\": 200,\n    \"bpm\": 100,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"The Middle\",\n    \"artist\": \"Zedd, Maren Morris\",\n    \"duration\": 184,\n    \"bpm\": 99,\n    \"genre\": \"electronic\"\n  },\n  {\n    \"title\": \"Shallow\",\n    \"artist\": \"Lady Gaga & Bradley Cooper\",\n    \"duration\": 215,\n    \"bpm\": 96,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Despacito\",\n    \"artist\": \"Luis Fonsi ft. Daddy Yankee\",\n    \"duration\": 229,\n    \"bpm\": 89,\n    \"genre\": \"reggaeton\"\n  },\n  {\n    \"title\": \"Attention\",\n    \"artist\": \"Charlie Puth\",\n    \"duration\": 211,\n    \"bpm\": 100,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Stay\",\n    \"artist\": \"The Kid LAROI & Justin Bieber\",\n    \"duration\": 141,\n    \"bpm\": 170,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Circles\",\n    \"artist\": \"Post Malone\",\n    \"duration\": 215,\n    \"bpm\": 120,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Call Out My Name\",\n    \"artist\": \"The Weeknd\",\n    \"duration\": 234,\n    \"bpm\": 135,\n    \"genre\": \"R&B\"\n  },\n  {\n    \"title\": \"Heat Waves\",\n    \"artist\": \"Glass Animals\",\n    \"duration\": 239,\n    \"bpm\": 81,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Good 4 U\",\n    \"artist\": \"Olivia Rodrigo\",\n    \"duration\": 178,\n    \"bpm\": 170,\n    \"genre\": \"pop-punk\"\n  },\n  {\n    \"title\": \"Montero (Call Me By Your Name)\",\n    \"artist\": \"Lil Nas X\",\n    \"duration\": 137,\n    \"bpm\": 89,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"Industry Baby\",\n    \"artist\": \"Lil Nas X ft. Jack Harlow\",\n    \"duration\": 212,\n    \"bpm\": 150,\n    \"genre\": \"hip-hop\"\n  },\n  {\n    \"title\": \"Dynamite\",\n    \"artist\": \"BTS\",\n    \"duration\": 199,\n    \"bpm\": 114,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Peaches\",\n    \"artist\": \"Justin Bieber ft. Daniel Caesar\",\n    \"duration\": 198,\n    \"bpm\": 90,\n    \"genre\": \"R&B\"\n  },\n  {\n    \"title\": \"Positions\",\n    \"artist\": \"Ariana Grande\",\n    \"duration\": 172,\n    \"bpm\": 100,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Watermelon Sugar\",\n    \"artist\": \"Harry Styles\",\n    \"duration\": 174,\n    \"bpm\": 96,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Say So\",\n    \"artist\": \"Doja Cat\",\n    \"duration\": 237,\n    \"bpm\": 111,\n    \"genre\": \"pop\"\n  },\n  {\n    \"title\": \"Mood\",\n    \"artist\": \"24kGoldn ft. Iann Dior\",\n    \"duration\": 140,\n    \"bpm\": 91,\n    \"genre\": \"hip-hop\"\n  }\n]\n"
  },
  {
    "path": "Customizable_Workout_Playlist_Generator/playlist.py",
    "content": "import json\nfrom datetime import timedelta\nimport random\nfrom typing import List, Dict, Optional\nimport os\n\n# Add these imports for API integration (you'll need to install these libraries)\nimport spotipy\nfrom spotipy.oauth2 import SpotifyOAuth\nimport requests\nfrom ytmusicapi import YTMusic\n\nclass Song:\n    def __init__(self, title: str, artist: str, duration: int, bpm: int, genre: str):\n        self.title = title\n        self.artist = artist\n        self.duration = duration  # in seconds\n        self.bpm = bpm\n        self.genre = genre\n\n    def __str__(self):\n        return f\"{self.title} - {self.artist} ({self.duration//60}:{self.duration%60:02d})\"\n\nclass WorkoutPlaylist:\n    def __init__(self):\n        self.songs: List[Song] = []\n        self.api_client = None  # Initialize api_client to None\n        self.load_song_database()\n\n    def load_song_database(self):\n        if self.api_client:\n            # TODO: Implement fetching songs from the chosen API\n            pass\n        else:\n            # Use the existing sample database\n            self.song_database = [\n                Song(\"Eye of the Tiger\", \"Survivor\", 240, 109, \"rock\"),\n                Song(\"Stronger\", \"Kanye West\", 312, 104, \"hip-hop\"),\n                Song(\"Thunderstruck\", \"AC/DC\", 292, 133, \"rock\"),\n                Song(\"Till I Collapse\", \"Eminem\", 297, 171, \"hip-hop\"),\n                Song(\"Shake It Off\", \"Taylor Swift\", 219, 160, \"pop\"),\n                Song(\"Lose Yourself\", \"Eminem\", 326, 171, \"hip-hop\"),\n                Song(\"Sweet Dreams\", \"Eurythmics\", 216, 125, \"pop\"),\n                Song(\"Don't Stop Believin'\", \"Journey\", 250, 119, \"rock\"),\n                Song(\"Pump It\", \"Black Eyed Peas\", 213, 154, \"pop\"),\n                Song(\"Run the World\", \"Beyoncé\", 236, 127, \"pop\"),\n            ]\n\n    def set_api_client(self, service: str):\n        if service == 'spotify':\n            self.api_client = SpotifyClient()\n        elif service == 'apple_music':\n            self.api_client = AppleMusicClient()\n        elif service == 'youtube_music':\n            self.api_client = YouTubeMusicClient()\n\n    def generate_playlist(\n        self,\n        workout_type: str,\n        duration_minutes: int,\n        preferred_genres: List[str] = None,\n        min_bpm: Optional[int] = None,\n        max_bpm: Optional[int] = None\n    ) -> List[Song]:\n        \"\"\"\n        Generate a workout playlist based on user preferences\n        \"\"\"\n        # Define BPM ranges for different workout types if not specified\n        workout_bpm_ranges = {\n            \"warmup\": (90, 120),\n            \"cardio\": (120, 140),\n            \"hiit\": (140, 180),\n            \"strength\": (110, 130),\n            \"cooldown\": (80, 110),\n            \"yoga\": (70, 100)\n        }\n\n        if min_bpm is None or max_bpm is None:\n            min_bpm, max_bpm = workout_bpm_ranges.get(workout_type.lower(), (100, 140))\n\n        # Filter songs based on criteria\n        suitable_songs = [\n            song for song in self.song_database\n            if min_bpm <= song.bpm <= max_bpm\n            and (preferred_genres is None or song.genre in preferred_genres)\n        ]\n\n        if not suitable_songs:\n            # If no songs match the criteria, gradually expand the BPM range\n            bpm_range_expansion = 10\n            while not suitable_songs and (min_bpm > 60 or max_bpm < 180):\n                min_bpm = max(60, min_bpm - bpm_range_expansion)\n                max_bpm = min(180, max_bpm + bpm_range_expansion)\n                suitable_songs = [\n                    song for song in self.song_database\n                    if min_bpm <= song.bpm <= max_bpm\n                    and (preferred_genres is None or song.genre in preferred_genres)\n                ]\n            \n            if not suitable_songs:\n                # If still no songs, ignore BPM and only consider genre\n                suitable_songs = [\n                    song for song in self.song_database\n                    if preferred_genres is None or song.genre in preferred_genres\n                ]\n                \n            if not suitable_songs:\n                # If still no songs, use all available songs\n                suitable_songs = self.song_database\n\n        # Create playlist\n        playlist = []\n        total_duration = 0\n        target_duration = duration_minutes * 60\n\n        while total_duration < target_duration and suitable_songs:\n            # Choose a random song that fits within remaining time\n            remaining_time = target_duration - total_duration\n            possible_songs = [s for s in suitable_songs if s.duration <= remaining_time]\n            \n            if not possible_songs:\n                # If no songs fit, choose the shortest available song\n                possible_songs = sorted(suitable_songs, key=lambda s: s.duration)\n                if possible_songs:\n                    selected_song = possible_songs[0]\n                else:\n                    break\n            else:\n                selected_song = random.choice(possible_songs)\n\n            playlist.append(selected_song)\n            total_duration += selected_song.duration\n            suitable_songs.remove(selected_song)\n\n        return playlist\n\n    def save_playlist(self, playlist: List[Song], filename: str):\n        \"\"\"Save playlist to a JSON file\"\"\"\n        playlist_data = [{\n            \"title\": song.title,\n            \"artist\": song.artist,\n            \"duration\": song.duration,\n            \"bpm\": song.bpm,\n            \"genre\": song.genre\n        } for song in playlist]\n\n        with open(filename, 'w') as f:\n            json.dump(playlist_data, f, indent=2)\n\n    def load_playlist(self, filename: str) -> List[Song]:\n        \"\"\"Load playlist from a JSON file\"\"\"\n        with open(filename, 'r') as f:\n            playlist_data = json.load(f)\n            \n        return [Song(**song_data) for song_data in playlist_data]\n\n    def share_playlist(self, playlist: List[Song], platform: str):\n        \"\"\"\n        TODO: Implement playlist sharing functionality\n        This method will allow users to share their playlists on various platforms\n        \"\"\"\n        pass  # Placeholder for future implementation\n\nclass SpotifyClient:\n    def __init__(self):\n        self.sp = spotipy.Spotify(auth_manager=SpotifyOAuth(scope=\"playlist-modify-private\"))\n\n    def search_songs(self, query: str, limit: int = 10) -> List[Song]:\n        results = self.sp.search(q=query, limit=limit, type='track')\n        songs = []\n        for track in results['tracks']['items']:\n            song = Song(\n                title=track['name'],\n                artist=track['artists'][0]['name'],\n                duration=track['duration_ms'] // 1000,\n                bpm=0,  # Spotify API doesn't provide BPM directly\n                genre=\"\"  # Spotify API doesn't provide genre directly\n            )\n            songs.append(song)\n        return songs\n\nclass AppleMusicClient:\n    def __init__(self):\n        # TODO: Implement Apple Music API client\n        # You'll need to set up Apple Music API credentials\n        pass\n\n    def search_songs(self, query: str, limit: int = 10) -> List[Song]:\n        # TODO: Implement song search using Apple Music API\n        # This is a placeholder implementation\n        return []\n\nclass YouTubeMusicClient:\n    def __init__(self):\n        self.ytmusic = YTMusic()\n\n    def search_songs(self, query: str, limit: int = 10) -> List[Song]:\n        results = self.ytmusic.search(query, filter=\"songs\", limit=limit)\n        songs = []\n        for track in results:\n            song = Song(\n                title=track['title'],\n                artist=track['artists'][0]['name'],\n                duration=int(track['duration_seconds']),\n                bpm=0,  # YouTube Music API doesn't provide BPM\n                genre=\"\"  # YouTube Music API doesn't provide genre directly\n            )\n            songs.append(song)\n        return songs\n\ndef format_playlist(playlist: List[Song]) -> str:\n    \"\"\"Format playlist for display\"\"\"\n    total_duration = sum(song.duration for song in playlist)\n    formatted = f\"Workout Playlist (Total Duration: {total_duration//60}:{total_duration%60:02d})\\n\"\n    formatted += \"-\" * 50 + \"\\n\"\n    \n    for i, song in enumerate(playlist, 1):\n        formatted += f\"{i}. {song}\\n\"\n    \n    return formatted\n\ndef get_user_input():\n    workout_type = input(\"Enter workout type (e.g., hiit, yoga, cardio): \").lower()\n    duration_minutes = int(input(\"Enter workout duration in minutes: \"))\n    genres = input(\"Enter preferred genres (comma-separated, or press Enter for all): \")\n    preferred_genres = [g.strip() for g in genres.split(\",\")] if genres else None\n    min_bpm = input(\"Enter minimum BPM (or press Enter for default): \")\n    max_bpm = input(\"Enter maximum BPM (or press Enter for default): \")\n    \n    min_bpm = int(min_bpm) if min_bpm else None\n    max_bpm = int(max_bpm) if max_bpm else None\n    \n    return workout_type, duration_minutes, preferred_genres, min_bpm, max_bpm\n\ndef choose_music_service():\n    print(\"Choose a music source:\")\n    print(\"1. Local database (demo)\")\n    print(\"2. Spotify\")\n    print(\"3. Apple Music\")\n    print(\"4. YouTube Music\")\n    \n    choice = input(\"Enter the number of your choice: \")\n    \n    if choice == '1':\n        return None\n    elif choice == '2':\n        return 'spotify'\n    elif choice == '3':\n        return 'apple_music'\n    elif choice == '4':\n        return 'youtube_music'\n    else:\n        print(\"Invalid choice. Using local database.\")\n        return None\n\ndef main():\n    generator = WorkoutPlaylist()\n    \n    # Ask for music source choice every time the script runs\n    service = choose_music_service()\n    if service:\n        generator.set_api_client(service)\n    \n    while True:\n        try:\n            workout_type, duration_minutes, preferred_genres, min_bpm, max_bpm = get_user_input()\n            \n            playlist = generator.generate_playlist(\n                workout_type=workout_type,\n                duration_minutes=duration_minutes,\n                preferred_genres=preferred_genres,\n                min_bpm=min_bpm,\n                max_bpm=max_bpm\n            )\n            \n            print(f\"\\n{workout_type.capitalize()} Workout Playlist:\")\n            print(format_playlist(playlist))\n            \n            save_option = input(\"Do you want to save this playlist? (y/n): \").lower()\n            if save_option == 'y':\n                filename = input(\"Enter filename to save (e.g., my_playlist.json): \")\n                generator.save_playlist(playlist, filename)\n                print(f\"Playlist saved to {filename}\")\n            \n            another = input(\"Generate another playlist? (y/n): \").lower()\n            if another != 'y':\n                break\n        \n        except ValueError as e:\n            print(f\"Error: {e}\")\n        except FileNotFoundError as e:\n            print(f\"Error: {e}\")\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "Customizable_Workout_Playlist_Generator/requirements.txt",
    "content": "spotipy==2.19.0\nrequests==2.26.0\nytmusicapi==0.22.0\n"
  },
  {
    "path": "Digital Clock/main.py",
    "content": "from time import strftime\nfrom tkinter import Label, Tk\n\nwindow = Tk()\nwindow.title(\"Digital Clock\")\nwindow.geometry(\"300x100\")\nwindow.configure(bg=\"green\")\nwindow.resizable(False, False) \n\nclock_label = Label(\n    window, bg=\"black\", fg=\"green\", font=(\"Arial\", 30, \"bold\"), relief=\"flat\"\n)\nclock_label.place(x=50, y=50)\n\n\ndef update_label():\n    current_time = strftime(\"%H: %M: %S\\n %d-%m-%Y \")\n    clock_label.configure(text=current_time)\n    clock_label.after(80, update_label)\n    clock_label.pack(anchor=\"center\")\n\nupdate_label()\nwindow.mainloop()"
  },
  {
    "path": "Digital Clock/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Example README.md",
    "content": "# Script Name\nShort description of package/script\n- If package, list of functionalities/scripts it can perform\n- If standalone script, short description of script explaining what it achieves\n\n# Description\n- If code is not explainable using comments, use this sections to explain your script\n\n# Prerequisites\n- List out the libraries imported in the script\n\n# Installing instructions\n- Explain how to setup and run your package/script in user's local machine.\n\n# Screenshot\n- Display images/gifs/videos of output/result of your script so that users can visualize it.\n\n# Author\nName(s) of author(s).\n"
  },
  {
    "path": "Expense Splitter/README.md",
    "content": "# Expense Splitter\n\nA simple Python script to split expenses among a group of people.\n\n## Features\n\n- Calculates the share per person based on the total amount and number of people.\n- User-friendly prompts and case-insensitive confirmation.\n\n## Usage\n\n1. Clone the repository.\n2. Navigate to the project directory.\n3. Run the script:\n   ```bash\n   python main.py\n"
  },
  {
    "path": "Expense Splitter/main.py",
    "content": "def calculate_split(total_amount: float, number_of_people: int, currency: str) -> None:\n    if number_of_people < 1:\n        raise ValueError('Number of people should be at least one.')\n\n    # Calculate the share per person\n    share_per_person: float = total_amount / number_of_people\n\n    # Print the results\n    print(f'Total expenses: {currency}{total_amount:,.2f}')\n    print(f'Number of people: {number_of_people}')\n    print(f'Each person should pay: {currency}{share_per_person:,.2f}')\n\n\ndef main() -> None:\n    try:\n        # Input for total amount\n        total_amount: float = float(input('Enter the total amount of the expense: '))\n        \n        # Input for number of people\n        number_of_people: int = int(input('Enter the number of people sharing the expense: '))\n        \n        # Call the function to calculate the split with currency set to rupees\n        calculate_split(total_amount, number_of_people, currency=\"₹\")\n        \n    except ValueError as e:\n        print(f'Error: {e}')\n\n\n# Run the main function\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "Expense Splitter/runtme.txt",
    "content": "Python 3.12.3"
  },
  {
    "path": "Extractive Text Summarization/readme.md",
    "content": "\n# 📝 Advanced Extractive Text Summarization Model\n\nWelcome 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.\n\n## 🚀 Project Overview\n\nThis model leverages NLP to:\n- **Extract key sentences** from a body of text.\n- **Score sentences** based on their importance using features like **TF-IDF**, sentence length, position, and presence of named entities.\n- **Cluster related sentences** via **K-means** to highlight critical points from various thematic groups.\n\n### Why It Matters\nIn 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.\n\n---\n\n## 📊 Features\n\n1. **Preprocessing**  \n   - Cleans and prepares text data for effective summarization.\n   \n2. **Scoring & Ranking**  \n   - Scores sentences based on TF-IDF, sentence structure, and key entities.\n   \n3. **Clustering & Key Point Extraction**  \n   - Uses K-means clustering to group sentences by topic and select key sentences for each group.\n   \n4. **Summary Generation**  \n   - Combines top-ranked sentences from each cluster to create a coherent, impactful summary.\n\n---\n\n## 🔧 How It Works\n\n1. **Data Preprocessing:** Initial cleaning (e.g., removing stop words, punctuation).\n2. **Sentence Scoring:** Uses TF-IDF, sentence structure, and named entity recognition to evaluate sentence importance.\n3. **K-means Clustering:** Groups related sentences to capture diverse perspectives within the text.\n4. **Summarization:** Extracts top sentences across clusters to create a balanced summary.\n\n---\n\n## 🛠️ Installation\n\n1. **Clone the Repository:**\n   ```bash\n   git clone https://github.com/one-alive/extractive_text_summarization.git\n   cd extractive_text_summarization\n   ```\n\n2. **Install Dependencies:**\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n---\n\n## ▶️ Usage\n\n1. **Run the Model on a Sample Text:**\n   ```bash\n   python summarize.py\n   ```\n\n2. **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.\n\n---\n\n## ⚙️ Next Steps\n\n- **Parameter Tuning:** Experiment with different clustering techniques and scoring weights.\n- **Expand Dataset Compatibility:** Optimize for specific types of documents like research papers or news articles.\n- **Add Fine-Tuning:** Integrate more NLP models to improve summarization accuracy.\n\n---\n\n## 🤝 Contributing\n\nContributions are welcome! If you have ideas or suggestions, please create a pull request or open an issue.\n\n---\n\n## 📬 Contact\n\nIf you have questions or want to explore collaboration opportunities, feel free to reach out!\n\n---"
  },
  {
    "path": "Extractive Text Summarization/requirements.txt",
    "content": "nltk==3.9.1\nnumpy==2.1.3\nscikit_learn==1.5.2\nspacy==3.8.2\n"
  },
  {
    "path": "Extractive Text Summarization/summary.py",
    "content": "import os\nimport re\nimport heapq\nimport numpy as np\nfrom collections import defaultdict\nfrom typing import List, Dict, Tuple, Union\nfrom nltk.tokenize import sent_tokenize\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.cluster import KMeans\nimport spacy\nfrom nltk.stem import PorterStemmer\n\n\nclass TextSummarization:\n    def __init__(self):\n        try:\n            self.nlp = spacy.load('en_core_web_sm')\n        except OSError:\n            print(\"Downloading spaCy model...\")\n            os.system(\"python -m spacy download en_core_web_sm\")\n            self.nlp = spacy.load('en_core_web_sm')\n\n        self.tfidf_vectorizer = TfidfVectorizer(stop_words='english')\n        self.stemmer = PorterStemmer()\n\n    def clean_text(self, text: str) -> Tuple[str, str]:\n        \"\"\"Clean and preprocess the text, returning both original and stemmed versions.\"\"\"\n        text = re.sub(r'[^\\w\\s.,!?]', '', text)  # Keep sentence structure\n        cleaned_text = ' '.join(text.split())  # Remove extra whitespace\n        stemmed_text = self.stem_text(cleaned_text)\n        return cleaned_text, stemmed_text\n\n    def stem_text(self, text: str) -> str:\n        \"\"\"Stem the words in the text.\"\"\"\n        words = text.split()\n        stemmed_words = [self.stemmer.stem(word) for word in words]\n        return ' '.join(stemmed_words)\n\n    def score_sentences(self, original_sentences: List[str], stemmed_sentences: List[str]) -> Dict[str, float]:\n        \"\"\"Score sentences based on TF-IDF and structural features.\"\"\"\n        tfidf_matrix = self.tfidf_vectorizer.fit_transform(stemmed_sentences)\n        sentence_scores = defaultdict(float)\n\n        for i, original_sentence in enumerate(original_sentences):\n            score = sum(tfidf_matrix[i, j] for j in tfidf_matrix[i].indices)\n            sent_doc = self.nlp(original_sentence)\n\n            # Apply length and positional weighting\n            length_factor = min(\n                1.0, len(sent_doc) / 20.0) if len(sent_doc) < 20 else 20.0 / len(sent_doc)\n            score *= length_factor\n\n            # Position bonuses\n            if i < len(original_sentence) * 0.2:\n                score *= 1.2\n            elif i > len(original_sentence) * 0.8:\n                score *= 1.1\n\n            # Bonuses for named entities and important dependencies\n            if sent_doc.ents:\n                score *= 1.2\n            if any(token.dep_ in ['nsubj', 'dobj'] for token in sent_doc):\n                score *= 1.1\n\n            sentence_scores[original_sentence] = score\n\n        return sentence_scores\n\n    def extract_key_points(self, original_sentences: List[str], stemmed_sentences: List[str], num_clusters: int = 5) -> List[str]:\n        \"\"\"Extract key points using K-means clustering.\"\"\"\n        num_clusters = min(num_clusters, len(original_sentences))\n        if num_clusters < 1:\n            return []\n\n        tfidf_matrix = self.tfidf_vectorizer.fit_transform(stemmed_sentences)\n        kmeans = KMeans(n_clusters=num_clusters, random_state=42)\n        kmeans.fit(tfidf_matrix)\n\n        labeled_sentences = [(orig, stem, label, idx) for idx, (orig, stem, label) in enumerate(\n            zip(original_sentences, stemmed_sentences, kmeans.labels_))]\n        key_points = []\n\n        for cluster in range(num_clusters):\n            cluster_sentences = [\n                item for item in labeled_sentences if item[2] == cluster]\n            if cluster_sentences:\n                cluster_center = kmeans.cluster_centers_[cluster]\n                distances = [np.linalg.norm(tfidf_matrix[item[3]].toarray(\n                ) - cluster_center) for item in cluster_sentences]\n                closest_sentence = cluster_sentences[np.argmin(\n                    distances)][0]  # Use original sentence\n\n                sent_doc = self.nlp(closest_sentence)\n                if len(sent_doc) >= 5:\n                    point = re.sub(r'\\s+', ' ', closest_sentence.strip('., '))\n                    if len(point.split()) >= 5:\n                        # Store with original index\n                        key_points.append((point, cluster_sentences[0][3]))\n\n        # Sort key points based on their original position in the text\n        key_points.sort(key=lambda x: x[1])\n        return [point for point, _ in key_points]\n\n    def summarize(self, text: str, num_sentences: int = 5) -> Dict[str, Union[str, List[str]]]:\n        \"\"\"Generate a comprehensive summary of the text.\"\"\"\n        cleaned_text, stemmed_text = self.clean_text(text)\n        original_sentences = sent_tokenize(cleaned_text)\n        stemmed_sentences = sent_tokenize(stemmed_text)\n        num_sentences = min(num_sentences, len(\n            original_sentences)) if original_sentences else 0\n\n        sentence_scores = self.score_sentences(\n            original_sentences, stemmed_sentences)\n        summary_sentences = heapq.nlargest(\n            num_sentences, sentence_scores.items(), key=lambda x: x[1])\n        summary_sentences.sort(key=lambda x: original_sentences.index(x[0]))\n\n        summary = ' '.join([sentence for sentence, _ in summary_sentences])\n        key_points = self.extract_key_points(\n            original_sentences, stemmed_sentences, num_clusters=min(5, len(original_sentences)))\n\n        return {\n            'summary': summary,\n            'key_points': key_points,\n        }\n\n\ndef main(text):\n    # Create summarizer instance\n    summarizer = TextSummarization()\n\n    # Generate summary\n    summary = summarizer.summarize(text)\n\n    print(\"Summary : \")\n    print(summary['summary'])\n    \n    \n    print(\"------\\n\")\n    \n    print(\"Key Points : \")\n    for i,j in enumerate(summary[\"key_points\"]):\n        print(f\"{i+1}. {j}\")\n        \n    print(\"------\")\n    \n\n\nif __name__ == \"__main__\":\n    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.\n\nFor 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.\n\nNowadays, 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.\"\"\")\n"
  },
  {
    "path": "Facebook Video Downloader/main.py",
    "content": "import os, re, requests, wget\n\nroot = os.path.dirname(os.path.abspath(__file__))\npath = os.path.join(root, \"Downloads\")\nif not os.path.exists(path):\n    os.mkdir(path)\n\nlink = input(\"Enter video link: \")\ntry:\n    r = requests.get(link)\n    if r.status_code == requests.codes.ok:\n        try:\n            sd_url = re.search('sd_src:\"(.+?)\"', r.text)[1]\n            url = (\n                re.search('hd_src:\"(.+?)\"', r.text)[1] if \"hd_src\" in r.text else sd_url\n            )\n            print(\"Downloading... Please wait...\")\n            wget.download(url, path)\n        except Exception as e:\n            print(e)\n    else:\n        print(\"Invalid Link!\")\n\nexcept Exception as e:\n    print(e)\n"
  },
  {
    "path": "Facebook Video Downloader/requirements.txt",
    "content": "requests==2.26.0\nwget==3.2"
  },
  {
    "path": "Facebook Video Downloader/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Gauss Elimination with Partial Pivoting/README.md",
    "content": "# Implementation of Gauss Elimination with Partial Pivoting\nThis 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.\n\n# Screenshot\nThose are some examples:\n\n![Example 1](gauss_example1.jpg)\n![Example 2](gauss_example2.jpg)\n\n# Author\n[GiovannaRMendes](https://github.com/GiovannaRMendes)"
  },
  {
    "path": "Gauss Elimination with Partial Pivoting/main.py",
    "content": "def gauss_partial(matrix: list, index_column: int):\n    index_max_val = index_column\n\n    for i in range(index_column, len(matrix)):\n        if matrix[index_column][index_column] < abs(matrix[i][index_column]):\n            index_max_val = i\n\n    if index_column != index_max_val:\n        matrix[index_column], matrix[index_max_val] = matrix[index_max_val], matrix[index_column]\n            \n\ndef verify_triangular(matrix: list) -> bool:\n\n    for i in range(len(matrix)):\n        for j in range(i, len(matrix)):\n\n            if (j == i and matrix[j][i] == 0) or (j != i and matrix[j][i] != 0):\n                return False\n        \n    return True\n\n\ndef gauss(matrix: list, index: int) -> list:\n    \n    for j in range(index+1, len(matrix)):\n        coefficient = round(matrix[j][index] / matrix[index][index], 2)\n        matrix[j][index] = 0\n\n        for k in range(index+1, len(matrix)+1):\n            matrix[j][k] = round(matrix[j][k] - coefficient * matrix[index][k], 5)\n\n    return matrix\n\n\ndef resolve_linear_system(matrix: list) -> list:\n    sum = 0\n    n = len(matrix)\n    results = [1] * n\n\n    for i in range(n-1, -1, -1):\n\n        for j in range(n-1, i, -1):\n            sum = sum + matrix[i][j]*results[j]\n\n        results[i] = round((matrix[i][n] - sum)/matrix[i][i], 2)\n        sum = 0\n\n    return results\n\n\ndef resolve_matrix(matrix: list):\n\n    for i in range(len(matrix)):\n        gauss_partial(matrix, i)\n        matrix = gauss(matrix, i)\n\n    print('\\nThe matrix after Gauss:')\n\n    for line in matrix:\n        print(\"[\", end='')\n        print(*(f'{val}' for val in line), end='')\n        print(\"]\")\n        \n    if verify_triangular(matrix):\n\n        print(\"\\nThe result of Gauss Elimination with Partial Pivoting:\")\n        for i, x in enumerate(resolve_linear_system(matrix)):\n            print(f'x_{i} = {x}')\n\n    else:\n        print(\"It's impossible to resolve, because it's not a triangular matrix\")\n        return 0\n        \n\ndef take_matrix() -> list:\n\n    line = 0\n    matrix = []\n    max_length = 0\n\n    number_lines = int(input(\"Please, insert the length of the your matrix: \"))\n    print(\"Please, insert only the numbers of the your augmented matrix (separete with espace):\")\n\n    for i in range(number_lines):\n        \n        try:\n            line = list(input().split())\n            line = list(int(val) for val in line)\n    \n            if max_length < len(line):\n                max_length = len(line)\n\n            matrix.append(line)\n        \n        except:\n            print(\"This matrix don't exist!!!\")\n            return 1\n        \n    if len(matrix) == max_length - 1:\n        return matrix\n    \n    return 0\n\n\nif __name__ == '__main__':\n\n    matrix = take_matrix()\n\n    if matrix == 0:\n        print(\"It's impossible to resolve\")\n\n    else:\n        print('The matrix:')\n\n        for line in matrix:\n            print(\"[\", end='')\n            print(*(f'{val}' for val in line), end='')\n            print(\"]\")\n\n        resolve_matrix(matrix)"
  },
  {
    "path": "Gauss Elimination with Partial Pivoting/runtime.txt",
    "content": "python-3.12.6"
  },
  {
    "path": "Geographic Distance/README.md",
    "content": "# Geographic Distance and Travel Time Calculator\n\nThis 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.\n\n## Features\n\n-   Input coordinates for two locations (latitude and longitude) interactively.\n-   Calculate the distance between the two coordinates in kilometers.\n-   Estimate the travel time based on a given average speed (in km/h).\n\n## Prerequisites\n\n-   Python 3.x installed on your system.\n\n## Setup\n\n1. Clone the repository\n\n    ```bash\n    git clone https://github.com/king04aman/All-In-One-Python-Projects.git\n    cd All-In-One-Python-Projects/Geographic Distance\n    ```\n\n2. Create and activate a virtual environment\n\n-   For macOS/Linux:\n\n    ```bash\n    python3 -m venv venv\n    source venv/bin/activate\n    ```\n\n-   For Windows:\n\n    ```bash\n    python -m venv venv\n    venv\\Scripts\\activate\n    ```\n\n3. Install the required dependencies\n\n    The required packages are listed in requirements.txt. Install them using the following command:\n\n    ```bash\n    pip install -r requirements.txt\n    ```\n\n    Note: The main dependency is geopy for calculating distances based on geodesic coordinates.\n\n## Usage\n\n1. Run the script:\n\n    ```bash\n    python geographic_distance.py\n    ```\n\n2. Enter the coordinates (latitude and longitude) of the two locations when prompted.\n3. Enter the average speed in km/h to calculate the travel time.\n\n    Example input:\n\n    ```\n    Enter the latitude and longitude of the first location (lat1, lon1) Example: 40.7128, -74.006: 52.5200, 13.4050\n    Enter the latitude and longitude of the second location (lat2, lon2) Example: 37.7749, -122.4194: 48.8566, 2.3522\n    Enter the average speed in km/h Example: 60: 80\n    ```\n\n    Example output:\n\n    ```\n    Distance between the two coordinates: 878.84 kilometers\n    Estimated travel time: 10.99 hours\n    ```\n\n## Requirements\n\nHere’s a list of Python dependencies in requirements.txt:\n\n```\ngeopy==2.2.0\npytest==8.3.3\n```\n"
  },
  {
    "path": "Geographic Distance/geographic_distance.py",
    "content": "from geopy.distance import geodesic\n\n\ndef calculate_distance_and_time(coord1, coord2, avg_speed):\n    \"\"\"\n    Calculate the distance between two coordinates and estimate travel time.\n    :param coord1: Tuple containing the latitude and longitude of the first location (lat1, lon1)\n    :param coord2: Tuple containing the latitude and longitude of the second location (lat2, lon2)\n    :param avg_speed: Average speed in km/h for estimating travel time\n    :return: Distance in kilometers and estimated travel time in hours\n    \"\"\"\n\n    # Calculate geodesic distance\n    distance = geodesic(coord1, coord2).kilometers\n    # Estimate travel time (distance / speed)\n    travel_time = distance / avg_speed\n\n    return distance, travel_time\n\n\ndef main():\n    # Coordinates (latitude, longitude)\n    try:\n        coord1 = tuple(map(float, input('Enter the latitude and longitude of the first location (lat1, lon1) Example: 40.7128, -74.006: ').split(',')))\n        coord2 = tuple(map(float, input('Enter the latitude and longitude of the second location (lat2, lon2) Example: 37.7749, -122.4194: ').split(',')))\n    except ValueError as e:\n        raise ValueError(\"Coordinates must be in the format 'lat, lon'\") from e\n\n    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])):\n        raise ValueError('Invalid coordinates')\n\n    # Speed in km/h (e.g., driving speed)\n    try:\n        avg_speed = float(input('Enter the average speed in km/h Example: 60: '))\n    except ValueError as e:\n        raise ValueError('Average speed must be a number') from e\n\n    if avg_speed <= 0:\n        raise ValueError('Average speed must be greater than 0.')\n\n    # Calculate the distance and travel time\n    distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed)\n\n    print(f'Distance between the two coordinates: {distance:.2f} kilometers')\n    print(f'Estimated travel time: {travel_time:.2f} hours')\n\n\nif __name__ == '__main__':\n    main()\n"
  },
  {
    "path": "Geographic Distance/requirements.txt",
    "content": "geopy==2.4.1\npytest==8.3.3\n"
  },
  {
    "path": "Geographic Distance/runtime.txt",
    "content": "python-3.12.7"
  },
  {
    "path": "Geographic Distance/test_geographic_distance.py",
    "content": "from unittest.mock import patch\n\nimport pytest\nfrom geographic_distance import calculate_distance_and_time, main\n\n\ndef test_calculate_distance_and_time():\n    # Test with valid coordinates and speed\n    coord1 = (40.7128, -74.006)\n    coord2 = (37.7749, -122.4194)\n    avg_speed = 60\n    distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed)\n    assert distance > 0\n    assert travel_time > 0\n\n\ndef test_calculate_distance_and_time_invalid_speed():\n    # Test with invalid speed (zero)\n    coord1 = (40.7128, -74.006)\n    coord2 = (37.7749, -122.4194)\n    avg_speed = 0\n    with pytest.raises(ValueError):\n        calculate_distance_and_time(coord1, coord2, avg_speed)\n\n\ndef test_calculate_distance_and_time_same_coordinates():\n    # Test with same coordinates\n    coord1 = (40.7128, -74.006)\n    coord2 = (40.7128, -74.006)\n    avg_speed = 60\n    distance, travel_time = calculate_distance_and_time(coord1, coord2, avg_speed)\n    assert distance == 0\n    assert travel_time == 0\n\n\n@pytest.fixture\ndef mock_input():\n    with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', '60']):\n        yield\n\n\ndef test_main(mock_input, capsys):\n    main()\n    captured = capsys.readouterr()\n    assert 'Distance between the two coordinates:' in captured.out\n    assert 'Estimated travel time:' in captured.out\n\n\ndef test_main_invalid_coordinates(mock_input, capsys):\n    with patch('builtins.input', side_effect=['abc, def', '37.7749, -122.4194', '60']):\n        with pytest.raises(ValueError):\n            main()\n\n\ndef test_main_invalid_speed(mock_input, capsys):\n    with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', 'abc']):\n        with pytest.raises(ValueError):\n            main()\n\n\ndef test_main_zero_speed(mock_input, capsys):\n    with patch('builtins.input', side_effect=['40.7128, -74.006', '37.7749, -122.4194', '0']):\n        with pytest.raises(ValueError):\n            main()\n\n\ndef test_main_same_coordinates(mock_input, capsys):\n    with patch('builtins.input', side_effect=['40.7128, -74.006', '40.7128, -74.006', '60']):\n        main()\n        captured = capsys.readouterr()\n        assert 'Distance between the two coordinates: 0.00 kilometers' in captured.out\n        assert 'Estimated travel time: 0.00 hours' in captured.out\n"
  },
  {
    "path": "Gesture-Based-Game-Controller/main.py",
    "content": "import cv2\nimport mediapipe as mp\nimport numpy as np\nimport time\n\n# Initialize MediaPipe hands module\nmp_hands = mp.solutions.hands\nhands = mp_hands.Hands()\nmp_drawing = mp.solutions.drawing_utils\n\n# Gesture mappings\nGESTURES = {\n    \"forward\": \"Move Forward\",\n    \"backward\": \"Move Backward\",\n    \"left\": \"Move Left\",\n    \"right\": \"Move Right\",\n    \"up\": \"Jump\"\n}\n\n# Define a function to calculate the direction based on landmarks\ndef detect_direction(landmarks):\n    # Get coordinates of wrist and index finger tip\n    wrist = landmarks[0]               # Wrist coordinates\n    index_finger_tip = landmarks[8]    # Index finger tip\n\n    # Calculate relative positions of index finger to wrist\n    x_diff = index_finger_tip.x - wrist.x  # Difference in X-axis\n    y_diff = index_finger_tip.y - wrist.y  # Difference in Y-axis\n\n    # Use thresholds to determine the direction\n    if abs(x_diff) > abs(y_diff):  # Horizontal movement dominates\n        if x_diff > 0.1:  # Index finger is to the right of the wrist\n            return \"right\"\n        elif x_diff < -0.1:  # Index finger is to the left of the wrist\n            return \"left\"\n    else:  # Vertical movement dominates\n        if y_diff > 0.1:  # Fingers are below wrist\n            return \"backward\"\n        elif y_diff < -0.1:  # Fingers are above wrist\n            return \"up\"\n    \n    # If no significant difference in X or Y, assume pointing forward\n    return \"forward\"\n\n# Video capture for hand gesture recognition\ncap = cv2.VideoCapture(0)\nprev_time = 0  # To implement delay between gesture changes\ndelay_interval = 1.0  # 1 second delay between actions\n\nwhile True:\n    ret, frame = cap.read()\n    if not ret:\n        break\n    \n    # Flip the frame horizontally for natural movement\n    frame = cv2.flip(frame, 1)\n    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n    \n    # Detect hands\n    results = hands.process(frame_rgb)\n    \n    landmark_list = []\n    \n    # If hand landmarks are detected\n    if results.multi_hand_landmarks:\n        for hand_landmarks in results.multi_hand_landmarks:\n            mp_drawing.draw_landmarks(frame, hand_landmarks, mp_hands.HAND_CONNECTIONS)\n            \n            # Collect hand landmark data\n            for lm in hand_landmarks.landmark:\n                landmark_list.append(lm)\n\n        # Detect direction based on the landmarks\n        direction = detect_direction(landmark_list)\n\n        # Check for time delay between actions\n        current_time = time.time()\n        if current_time - prev_time > delay_interval:\n            print(GESTURES[direction])  # Output corresponding action\n            prev_time = current_time\n    \n    # Display the frame with landmarks\n    cv2.imshow('Hand Gesture Recognition', frame)\n    \n    # Quit if 'q' is pressed\n    if cv2.waitKey(1) & 0xFF == ord('q'):\n        break\n\ncap.release()\ncv2.destroyAllWindows()\n"
  },
  {
    "path": "Gesture-Based-Game-Controller/readme.md",
    "content": "# Hand Gesture Control Using Computer Vision\n\nThis 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.\n\nThe project uses **OpenCV** and **MediaPipe** for hand landmark detection and gesture recognition.\n\n## Features\n\n- Detects hand gestures in real-time.\n- Maps gestures to game controls:\n  - **Move Forward**: Fingers pointing towards the screen.\n  - **Move Left**: Fingers pointing left.\n  - **Move Right**: Fingers pointing right.\n  - **Move Backward**: Fingers pointing downward.\n  - **Jump**: Fingers pointing upward.\n- Implements a delay between actions to prevent rapid switching of game controls.\n\n## Requirements\n\n- Python 3.7 or higher\n- OpenCV\n- MediaPipe\n- NumPy\n\n\n"
  },
  {
    "path": "Gesture-Based-Game-Controller/requirements.txt",
    "content": "opencv-python==4.8.0.74\nmediapipe==0.10.0\nnumpy==1.24.2\n"
  },
  {
    "path": "Gesture-Based-Game-Controller/runtime.txt",
    "content": "python-3.12.7"
  },
  {
    "path": "Handwritten-Assignments/main.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Aman Kumar\n# Version: 1.0.0\n\nimport pywhatkit as pw\n\ntext_to_convert = \"\"\"\nLorem 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.\n\"\"\"\n\npw.text_to_handwriting(text_to_convert, 'demo.png',[0,0,135])\nprint(\"Converted !!\")\n"
  },
  {
    "path": "Handwritten-Assignments/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Headlight Detection/headlightDetection.py",
    "content": "from shutil import which\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport cv2, time\n\ndef wait(t):\n    time.sleep()\n\n#List includes path for images representing differenct scenarios\nmlist = ['bus_coming.hpg','going.jpg','both.jpg']\n\n#codition: no vehicle\ndef scenario(condition):\n    image = cv2.imread(condition)\n    gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n    cv2.imwrite('gray_image.png',gray_image)\n    cv2.imshow('color_image',image)\n    blur_image = cv2.blur(gray_image,(15,15))\n    cv2.imwrite('blur_image.png',blur_image)\n    ret , thresh = cv2.threshold(blur_image,150,255,0)\n    contour_image , contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n    cv2.drwaContours(blur_image,contours,-1,(0,255,0),3)\n    cv2.imshow('blur_image.png',blur_image)\n    moments = [cv2.moments(cnt) for cnt in contours]\n    y_centroids = [int(round(m['m01']/m['m00'])) for m in moments]\n    x = len(y_centroids)\n    i=0\n    while i<x:\n        y_centroids[i] = y_centroids[i]//10"
  },
  {
    "path": "Headlight Detection/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Helmet Detection/main.py",
    "content": "from http.client import _DataType\nimport cv2, random, os, time, imutils\nimport numpy as np\nfrom tensorflow.keras.models import load_model\n\n\nos.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'\nnet = cv2.dnn.readNet(\"yolov3-custom_7000.weights\",\"yolov3-custom.cfg\")\nnet.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA)\nnet.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)\nmodel = load_model('helmet-nonhelmet_cnn.h5')\nprint('model loaded!!!')\ncap = cv2.VideoCapture('testing videos/test2.mp4')\nCOLORS = [(0,255,0,),(0,0,255)]\n\ndef helmet_or_nonhelmet(helmet_roi):\n    try:\n        helmet_roi = cv2.resize(helmet_roi,(224,224))\n        helmet_roi = np.array(helmet_roi,dtype='float32')\n        helmet_roi = helmet_roi.reshape(1,224,224,3)\n        helmet_roi = helmet_roi/255.0\n        return int(model.predict(helmet_roi)[0][0])\n    except:\n        pass\n\nlayer_names = net.getLayerNames()\noutput_layers = [layer_names[i[0] -1] for i in net.getUnconnectedOutLayers()]\n\nret = True\n\nwhile ret:\n    ret, img = cap.read()\n    img = imutlis.resize(img,height=5500)\n"
  },
  {
    "path": "Helmet Detection/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Image Compression/main.py",
    "content": "import cv2\n\nimg = cv2.imread('input.jpg')\nprint(img.shape)\n\nk = 5\nwidth = int((img.shape[1])/k)\nheight = int((img.shape[0])/k)\n\nscaled = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)\nprint(scaled.shape)\n\ncv2.imshow(\"Output\", scaled)\ncv2.waitKey(500)\ncv2.destroyAllWindows()\n\ncv2.imwrite('resized_image.jpg', scaled)\n"
  },
  {
    "path": "Image Compression/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "ImageSize Reducer/reduce.py",
    "content": "import cv2\n\nimg = cv2.imread('test.jpg')\nprint(img.shape)\n\nk = 5\nwidth = int((img.shape[1])/k)\nheight = int((img.shape[0])/k)\n\nscaled = cv2.resize(img, (width, height), interpolation=cv2.INTER_AREA)\nprint(scaled.shape)\n\ncv2.imshow(\"Output_Image\", scaled)\ncv2.waitKey(500)\ncv2.destroyAllWindows()\n\ncv2.imwrite('resized_image.jpg', scaled)\n"
  },
  {
    "path": "ImageSize Reducer/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Img-Steganograpy/main.py",
    "content": "from stegano import lsbset\nfrom stegano.lsbset import generators\n\n# Hide the message in the image\nflag=\"This is sample text msg!\"\nlets=lsbset.hide(\"./test.png\",flag,generators.eratosthenes())\nlets.save(\"steg.png\")\n\n# Show the message from the image\nf=open(\"steg.png\",\"rb\")\nlsbset.reveal(f,generators.eratosthenes())\n"
  },
  {
    "path": "Img-Steganograpy/runtime.txt",
    "content": "python-3.10.7\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2023 by Aman Kumar\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."
  },
  {
    "path": "Learn-FastAPI/FastAPI-CURD.py",
    "content": "from fastapi import FastAPI, HTTPException\r\nfrom pydantic import BaseModel\r\nfrom typing import List, Optional\r\nfrom uuid import UUID, uuid4\r\n\r\napp = FastAPI()\r\n\r\n# Define a Pydantic model for Task\r\nclass Task(BaseModel):\r\n    id: Optional[UUID] = None\r\n    title: str\r\n    description: Optional[str] = None\r\n    completed: bool = False\r\n\r\n# Initialize an empty list to store tasks\r\ntasks = []\r\n\r\n# Create a new task\r\n@app.post(\"/tasks/\", response_model=Task)\r\ndef create_task(task: Task):\r\n    task.id = uuid4()  # Assign a UUID to the task\r\n    tasks.append(task)  # Add the task to the tasks list\r\n    return task\r\n\r\n# Retrieve all tasks\r\n@app.get(\"/tasks/\", response_model=List[Task])\r\ndef read_tasks():\r\n    return tasks\r\n\r\n# Retrieve a specific task by ID\r\n@app.get(\"/tasks/{task_id}\", response_model=Task)\r\ndef read_task(task_id: UUID):\r\n    for task in tasks:\r\n        if task.id == task_id:\r\n            return task\r\n    \r\n    # Raise HTTPException if task not found\r\n    raise HTTPException(status_code=404, detail=\"Task not found\")\r\n\r\n# Update a specific task by ID\r\n@app.put(\"/tasks/{task_id}\", response_model=Task)\r\ndef update_task(task_id: UUID, task_update: Task):\r\n    for idx, task in enumerate(tasks):\r\n        if task.id == task_id:\r\n            updated_task = task.copy(update=task_update.dict(exclude_unset=True))\r\n            tasks[idx] = updated_task\r\n            return updated_task\r\n    \r\n    # Raise HTTPException if task not found\r\n    raise HTTPException(status_code=404, detail=\"Task not found\")\r\n\r\n# Delete a specific task by ID\r\n@app.delete(\"/tasks/{task_id}\", response_model=Task)\r\ndef delete_task(task_id: UUID):\r\n    for idx, task in enumerate(tasks):\r\n        if task.id == task_id:\r\n            return tasks.pop(idx)\r\n    \r\n    # Raise HTTPException if task not found\r\n    raise HTTPException(status_code=404, detail=\"Task not found\")\r\n\r\n# Run the FastAPI app\r\nif __name__ == \"__main__\":\r\n    import uvicorn\r\n\r\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\r\n"
  },
  {
    "path": "Learn-FastAPI/FastAPI-Tutorial.py",
    "content": "from fastapi import Depends, FastAPI, HTTPException, status\r\nfrom fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm\r\nfrom pydantic import BaseModel\r\nfrom datetime import datetime, timedelta\r\nfrom jose import JWTError, jwt\r\nfrom passlib.context import CryptContext\r\n\r\n# Constants\r\nSECRET_KEY = \"\"\r\nALGORITHM = \"HS256\"\r\nACCESS_TOKEN_EXPIRE_MINUTES = 30\r\n\r\n# Database simulation\r\ndb = {\r\n    \"aman\": {\r\n        \"username\": \"king04aman\",\r\n        \"full_name\": \"Aman Kumar\",\r\n        \"email\": \"aman@gmail.com\",\r\n        \"hashed_password\": \"$2b$12$HxWHkvMuL7WrZad6lcCfluNFj1/Zp63lvP5aUrKlSTYtoFzPXHOtu\",\r\n        \"disabled\": False\r\n    }\r\n}\r\n\r\n# Pydantic models\r\nclass Token(BaseModel):\r\n    access_token: str\r\n    token_type: str\r\n\r\nclass TokenData(BaseModel):\r\n    username: str or None = None\r\n\r\nclass User(BaseModel):\r\n    username: str\r\n    email: str or None = None\r\n    full_name: str or None = None\r\n    disabled: bool or None = None\r\n\r\nclass UserInDB(User):\r\n    hashed_password: str\r\n\r\n# Password hashing context\r\npwd_context = CryptContext(schemes=[\"bcrypt\"], deprecated=\"auto\")\r\n# OAuth2 password bearer\r\noauth2_scheme = OAuth2PasswordBearer(tokenUrl=\"token\")\r\n\r\n# FastAPI instance\r\napp = FastAPI()\r\n\r\n# Password helper functions\r\ndef verify_password(plain_password, hashed_password):\r\n    return pwd_context.verify(plain_password, hashed_password)\r\n\r\ndef get_password_hash(password):\r\n    return pwd_context.hash(password)\r\n\r\n# User authentication functions\r\ndef get_user(db, username: str):\r\n    if username in db:\r\n        user_data = db[username]\r\n        return UserInDB(**user_data)\r\n\r\ndef authenticate_user(db, username: str, password: str):\r\n    user = get_user(db, username)\r\n    if not user:\r\n        return False\r\n    if not verify_password(password, user.hashed_password):\r\n        return False\r\n    return user\r\n\r\n# Token creation function\r\ndef create_access_token(data: dict, expires_delta: timedelta or None = None):\r\n    to_encode = data.copy()\r\n    if expires_delta:\r\n        expire = datetime.utcnow() + expires_delta\r\n    else:\r\n        expire = datetime.utcnow() + timedelta(minutes=15)\r\n    to_encode.update({\"exp\": expire})\r\n    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)\r\n    return encoded_jwt\r\n\r\n# Dependency to get current user\r\nasync def get_current_user(token: str = Depends(oauth2_scheme)):\r\n    credential_exception = HTTPException(\r\n        status_code=status.HTTP_401_UNAUTHORIZED,\r\n        detail=\"Could not validate credentials\",\r\n        headers={\"WWW-Authenticate\": \"Bearer\"}\r\n    )\r\n    try:\r\n        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])\r\n        username: str = payload.get(\"sub\")\r\n        if username is None:\r\n            raise credential_exception\r\n        token_data = TokenData(username=username)\r\n    except JWTError:\r\n        raise credential_exception\r\n\r\n    user = get_user(db, username=token_data.username)\r\n    if user is None:\r\n        raise credential_exception\r\n\r\n    return user\r\n\r\n# Dependency to get current active user\r\nasync def get_current_active_user(current_user: UserInDB = Depends(get_current_user)):\r\n    if current_user.disabled:\r\n        raise HTTPException(status_code=400, detail=\"Inactive user\")\r\n    return current_user\r\n\r\n# Route to get access token\r\n@app.post(\"/token\", response_model=Token)\r\nasync def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):\r\n    user = authenticate_user(db, form_data.username, form_data.password)\r\n    if not user:\r\n        raise HTTPException(\r\n            status_code=status.HTTP_401_UNAUTHORIZED,\r\n            detail=\"Incorrect username or password\",\r\n            headers={\"WWW-Authenticate\": \"Bearer\"}\r\n        )\r\n    access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)\r\n    access_token = create_access_token(\r\n        data={\"sub\": user.username},\r\n        expires_delta=access_token_expires\r\n    )\r\n    return {\"access_token\": access_token, \"token_type\": \"bearer\"}\r\n\r\n# Route to get current user\r\n@app.get(\"/users/me/\", response_model=User)\r\nasync def read_users_me(current_user: User = Depends(get_current_active_user)):\r\n    return current_user\r\n\r\n# Route to get current user's items\r\n@app.get(\"/users/me/items\")\r\nasync def read_own_items(current_user: User = Depends(get_current_active_user)):\r\n    return [{\"item_id\": 1, \"owner\": current_user}]\r\n"
  },
  {
    "path": "Learn-FastAPI/README.md",
    "content": "# FastAPI CRUD and Authentication Example\r\n\r\nThis directory contains two FastAPI applications: one for basic CRUD operations (task management) and another for user authentication using JWT (JSON Web Tokens).\r\n\r\n## Overview\r\n\r\n1. **Task Management API (`fastapi-curd.py`)**:\r\n   - Implements basic CRUD operations for managing tasks.\r\n   - Tasks have attributes like `id`, `title`, `description`, and `completed`.\r\n\r\n2. **User Authentication API (`fastapi-tutorial.py`)**:\r\n   - Implements user registration, login, and token-based authentication.\r\n   - Uses JWT for secure access and stores user information in a simulated database.\r\n\r\n## Installation\r\n\r\nTo run the applications, ensure you have Python and FastAPI installed. You can install FastAPI and Uvicorn using pip:\r\n\r\n```bash\r\npip install fastapi uvicorn python-jose passlib[bcrypt]\r\n```\r\n\r\n## Running the Applications\r\n\r\nYou can run each application separately.\r\n\r\n### Task Management API\r\n\r\nTo run the task management API:\r\n\r\n```bash\r\npython fastapi-curd.py\r\n```\r\n\r\nThe API will be available at `http://localhost:8000/tasks/`.\r\n\r\n### User Authentication API\r\n\r\nTo run the user authentication API:\r\n\r\n```bash\r\npython fastapi-tutorial.py\r\n```\r\n\r\nThe API will be available at `http://localhost:8000/token` for login and `http://localhost:8000/users/me/` for user information.\r\n\r\n## API Endpoints\r\n\r\n### Task Management API Endpoints\r\n\r\n- **Create Task**: `POST /tasks/`\r\n- **Retrieve All Tasks**: `GET /tasks/`\r\n- **Retrieve Specific Task**: `GET /tasks/{task_id}`\r\n- **Update Task**: `PUT /tasks/{task_id}`\r\n- **Delete Task**: `DELETE /tasks/{task_id}`\r\n\r\n### User Authentication API Endpoints\r\n\r\n- **Token Generation**: `POST /token`\r\n- **Get Current User**: `GET /users/me/`\r\n- **Get Current User's Items**: `GET /users/me/items`\r\n\r\n## Author\r\n- [king04aman](https://github.com/king04aman)\r\n"
  },
  {
    "path": "Mental Health chatbot/Mental_health_bot.py",
    "content": "import pandas as pd\nimport numpy as np\nimport json\nimport nltk\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\nfrom tensorflow.keras.optimizers import Adam\nimport os\n\n# Download necessary NLTK data\nnltk.download('punkt')\nnltk.download('wordnet')\n\n# Initialize lemmatizer\nlemmatizer = WordNetLemmatizer()\n\n# Load datasets\ntry:\n    print(\"Files in current directory:\", os.listdir())\n    csv_files = [f for f in os.listdir() if f.endswith('.csv') and 'Combined' in f and 'Data' in f]\n    if csv_files:\n        df = pd.read_csv(csv_files[0])\n        print(f\"Loaded file: {csv_files[0]}\")\n        print(\"DataFrame columns:\", df.columns.tolist())\n        print(\"DataFrame shape:\", df.shape)\n        print(df.head())\n    else:\n        raise FileNotFoundError(\"No matching CSV file found\")\nexcept FileNotFoundError as e:\n    print(f\"Error: {str(e)}\")\n    print(\"Ensure 'Combined_Data.csv' is in the same directory.\")\n    print(\"Current working directory:\", os.getcwd())\n    exit(1)\n\n# Load intents.json\ntry:\n    with open('intents.json', 'r') as f:\n        intents = json.load(f)\nexcept FileNotFoundError as e:\n    print(f\"Error: {str(e)}. Ensure 'intents.json' is available.\")\n    exit(1)\n\n# Preprocess text data\ndef preprocess_text(text):\n    tokens = nltk.word_tokenize(str(text).lower())\n    return ' '.join([lemmatizer.lemmatize(token) for token in tokens])\n\n# Determine the correct column name for text data\ntext_column = 'statement' if 'statement' in df.columns else df.columns[0]\n\ndf['processed_text'] = df[text_column].apply(preprocess_text)\n\n# Create TF-IDF vectorizer\nvectorizer = TfidfVectorizer()\ntfidf_matrix = vectorizer.fit_transform(df['processed_text'])\n\n# Prepare data for model training\nX, y = [], []\n\nfor intent in intents['intents']:\n    for pattern in intent['patterns']:\n        X.append(preprocess_text(pattern))\n        y.append(intent['tag'])\n\nX = vectorizer.transform(X).toarray()\ny = pd.get_dummies(y).values\n\n# Ensure X and y have the same shape\nassert X.shape[0] == y.shape[0], f\"Shape mismatch: X={X.shape}, y={y.shape}\"\n\n# Build the model\nmodel = Sequential([\n    Dense(128, input_shape=(X.shape[1],), activation='relu'),\n    Dropout(0.5),\n    Dense(64, activation='relu'),\n    Dropout(0.5),\n    Dense(y.shape[1], activation='softmax')\n])\n\nmodel.compile(optimizer=Adam(learning_rate=0.01), loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model with error handling\ntry:\n    model.fit(X, y, epochs=200, batch_size=32, verbose=1)\nexcept Exception as e:\n    print(f\"Error during model training: {str(e)}\")\n    print(f\"X shape: {X.shape}, y shape: {y.shape}\")\n    raise\n\n# Chatbot function\ndef chatbot_response(user_input):\n    processed_input = preprocess_text(user_input)\n    input_vector = vectorizer.transform([processed_input]).toarray()\n\n    # Find similar responses from the dataset\n    similarities = cosine_similarity(input_vector, tfidf_matrix)\n    most_similar_idx = similarities.argmax()\n    response = df.iloc[most_similar_idx][text_column]\n\n    # Classify intent\n    intent_probs = model.predict(input_vector)[0]\n    intent_idx = intent_probs.argmax()\n    intent_tag = list(pd.get_dummies([i['tag'] for i in intents['intents']]).columns)[intent_idx]\n\n    # Get response from intents\n    for intent in intents['intents']:\n        if intent['tag'] == intent_tag:\n            intent_response = np.random.choice(intent['responses'])\n            break\n\n    return f\"Dataset Response: {response}\\n\\nIntent Response: {intent_response}\"\n\n# Main chat loop\nprint(\"Mental Health Chatbot: Hello! I'm here to provide support and resources for mental health. How can I help you today?\")\nwhile True:\n    user_input = input(\"You: \")\n    if user_input.lower() in ['quit', 'exit', 'bye']:\n        print(\"Mental Health Chatbot: Take care! Remember, it's okay to seek help when you need it.\")\n        break\n    response = chatbot_response(user_input)\n    print(\"Mental Health Chatbot:\", response)\n\n"
  },
  {
    "path": "Mental Health chatbot/README_BOT.md",
    "content": "# Mental Health Chatbot\n\nThis project implements a chatbot designed to provide support and information related to mental health. It uses natural language processing and machine learning techniques to understand user input and generate appropriate responses.\n\n## Features\n\n- Sentiment analysis of user input\n- Personalized responses based on user's emotional state\n- Information provision on various mental health topics\n- Supportive and empathetic conversation\n\n## Installation\n\n1. Clone this repository:\n   ```\n   git clone https://github.com/Ashutoshdas-dev/All-In-One-Python-Projects\n   cd All-In-One-Python-Projects/Mental Health Chatbot\n   ```\n\n2. Set up a virtual environment:\n   ```\n   python -m venv venv\n   ```\n\n3. Activate the virtual environment:\n   - On Windows:\n     ```\n     venv\\Scripts\\activate\n     ```\n   - On macOS and Linux:\n     ```\n     source venv/bin/activate\n     ```\n\n4. Install the required dependencies:\n   ```\n   pip install -r requirements.txt\n   ```\n\n## Usage\n\n1. Ensure your virtual environment is activated (see step 3 in Installation).\n\n2. Run the main script:\n   ```\n   python mental_health_chatbot.py\n   ```\n\n3. Follow the prompts to interact with the chatbot.\n\n4. Type 'quit' or 'exit' to end the conversation.\n\n5. When you're done, deactivate the virtual environment:\n   ```\n   deactivate\n   ```\n\n## Datasets\n\nThis project utilizes the following datasets for training and improving the chatbot's responses:\n\n1. [Sentiment Analysis for Mental Health](https://www.kaggle.com/datasets/suchintikasarkar/sentiment-analysis-for-mental-health)\n   - Description: This dataset contains text data labeled with sentiment for mental health-related content.\n   - Use: Helps in training the sentiment analysis component of the chatbot.\n\n2. [Mental Health Conversational Data](https://www.kaggle.com/datasets/elvis23/mental-health-conversational-data)\n   - Description: This dataset includes conversations related to mental health topics.\n   - Use: Aids in training the chatbot to generate more natural and context-appropriate responses.\n\n\n"
  },
  {
    "path": "Mental Health chatbot/requirements.txt",
    "content": "pandas\nnumpy\nnltk\nscikit-learn\ntensorflow\n"
  },
  {
    "path": "Merge PDFs/merge.py",
    "content": "from PyPDF2 import PdfFileMerger\n\n\ndef by_appending():\n    merger = PdfFileMerger()\n    f1 = open(\"testPDF1.pdf\", \"rb\")\n    merger.append(f1)\n    merger.append(\"testPDF12.pdf\")\n\n    merger.write(\"mergedPDF.pdf\")\n\ndef by_inserting():\n    merger = PdfFileMerger()\n    merger.append(\"testPDF1.pdf\")\n    merger.merge(0, \"testPDF2.pdf\")\n    merger.write(\"mergedPDF.pdf\")\n\n\nif __name__ == \"__main__\":\n    by_appending()\n    by_inserting()\n"
  },
  {
    "path": "Merge PDFs/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "MobileNumber Tracker/track.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Aman Kumar\n# Version: 1.0.0 \n\nimport phonenumbers\nfrom phonenumbers import timezone, carrier, geocoder\n\nnumber = input(\"Enter number to track (with +91): \")\nphone = phonenumbers.parse(number)\ntime = timezone.time_zones_for_number(phone)\ncarr = carrier.name_for_number(phone, 'en')\nreg = geocoder.description_for_number(phone, 'en')\n\nprint(\"STD Code: \", phone.country_code)\nprint(\"Number: \", phone.national_number)\nprint(\"Region: \", time)\nprint(\"Carrier: \", carr)\nprint(\"Country: \", reg)\n"
  },
  {
    "path": "Mood Based Music Recommender/Emosic-Spoti.py",
    "content": "import spotipy\nfrom spotipy.oauth2 import SpotifyClientCredentials\nimport random\n\n# Authentication - Replace with your credentials\nCLIENT_ID = 'your_spotify_client_id'\nCLIENT_SECRET = 'your_spotify_client_secret'\n\n# Connect to Spotify API\nauth_manager = SpotifyClientCredentials(client_id=CLIENT_ID, client_secret=CLIENT_SECRET)\nsp = spotipy.Spotify(auth_manager=auth_manager)\n\n# Dictionary to map emotions to musical characteristics\nemotion_to_genre = {\n    'happy': ['pop', 'dance', 'indie'],\n    'sad': ['acoustic', 'blues', 'piano'],\n    'angry': ['metal', 'rock', 'punk'],\n    'relaxed': ['ambient', 'chill', 'classical'],\n    'energetic': ['electronic', 'hip-hop', 'funk'],\n    'anxious': ['ambient', 'classical', 'jazz'],\n    'cheerful': ['pop', 'indie', 'reggae'],\n    'stressed': ['jazz', 'chill', 'lo-fi'],\n    'dreamy': ['dream-pop', 'ambient', 'shoegaze'],\n    'excited': ['dance', 'electronic', 'pop'],\n    'bored': ['alternative', 'indie', 'chill'],\n    'nostalgic': ['classic rock', 'folk', 'retro'],\n    'hopeful': ['pop', 'inspirational', 'uplifting'],\n    'content': ['soft rock', 'acoustic', 'country'],\n    'romantic': ['pop', 'r&b', 'soul'],\n}\n\n# Function to recommend tracks based on emotion\ndef recommend_tracks(emotion):\n    genres = emotion_to_genre.get(emotion.lower(), ['pop'])  # Default to 'pop' if emotion is not found\n    selected_genre = random.choice(genres)\n\n    # Fetch recommendations from Spotify\n    results = sp.recommendations(seed_genres=[selected_genre], limit=10)  # Increase limit for more results\n    tracks = results['tracks']\n    \n    playlist = []\n    for track in tracks:\n        track_info = {\n            'name': track['name'],\n            'artist': track['artists'][0]['name'],\n            'url': track['external_urls']['spotify']\n        }\n        playlist.append(track_info)\n    \n    return playlist, genres\n\n# Function to get maximum length of strings in a list of dictionaries\ndef get_max_lengths(playlist):\n    max_name_length = max(len(song['name']) for song in playlist) if playlist else 0\n    max_artist_length = max(len(song['artist']) for song in playlist) if playlist else 0\n    max_url_length = max(len(song['url']) for song in playlist) if playlist else 0\n    return max_name_length, max_artist_length, max_url_length\n\n# Main loop for user input\nwhile True:\n    emotion = input(\"\\nEnter your emotion (happy, sad, angry, relaxed, energetic, anxious, cheerful, stressed, dreamy, excited, bored, nostalgic, hopeful, content, romantic) or type 'exit' to quit: \").strip().lower()\n    \n    if emotion == 'exit':\n        print(\"Goodbye my Love!!!\")\n        break\n\n    # Get playlist based on the emotion\n    playlist, genres = recommend_tracks(emotion)\n\n    # Get maximum lengths for formatting\n    max_name_length, max_artist_length, max_url_length = get_max_lengths(playlist)\n\n    # Set a minimum width for columns to ensure proper alignment\n    min_name_length = max(20, max_name_length)\n    min_artist_length = max(15, max_artist_length)\n    min_url_length = 35  # Fixed width for URL\n\n    # Display the recommended playlist\n    if emotion not in emotion_to_genre:\n        print(\"The emotion you entered is NOT in the list, so we will show you pop music instead.\")\n    \n    print(f\"Here are some songs for your '{emotion}' mood:\" if emotion in emotion_to_genre else \"Here are some pop songs for you:\")\n    print(f\"STT | Song Name{' ' * (min_name_length - 9)} | Artist{' ' * (min_artist_length - 6)} | URL\")\n    print(\"-\" * (11 + max_name_length + max_artist_length + max_url_length))\n    \n    for idx, song in enumerate(playlist, 1):\n        print(f\"{idx:<3} | {song['name']:<{min_name_length}} | {song['artist']:<{min_artist_length}} | {song['url']}\")\n"
  },
  {
    "path": "Mood Based Music Recommender/README.md",
    "content": "# Music Recommendation Based on Emotion\n\nA Python script that recommends music playlists based on user-inputted emotions using the Spotify API. The script fetches songs that match the user's mood and provides a playlist with links to each song.\n\n## Features\n\n- Recommend songs based on various emotions.\n- Integrates with Spotify's Web API to fetch song recommendations.\n\n## Setup\n\n### 1. Set Up Spotify API\n\nTo use this script, you will need to create a Spotify Developer account and register an app to obtain your Client ID and Client Secret. Follow the instructions [here](https://developer.spotify.com/documentation/general/guides/authorization/app-settings/) to get your credentials.\n\nHere is an example:\n\n![alt text](image.png)\n\n### 2. Install Required Libraries\n\nMake sure you have the following Python libraries installed:\n\n    ```bash\n    pip install spotipy\n    pip install requests\n    ```\n\n\n### 3. Run the Script\n\n**Notes:**\n- Replace **your_spotify_client_id** and **your_spotify_client_secret** in the script with your actual Spotify API credentials.\n- You can extend the emotion_to_genre dictionary with more emotions and genres.\n- You can modify the limit=10 in the Spotify recommendations query to change the number of recommended songs.\n\nTo run the script, use the following command:\n\n    ```bash\n    python Emosic-Spoti.py\n    ```\n\n**Usage**\n\nAfter running the script, enter an emotion from the list below to get a music playlist:\n\n- happy\n- sad\n- angry\n- relaxed\n- energetic\n- anxious\n- cheerful\n- stressed\n- dreamy\n- excited\n- bored\n- nostalgic\n- hopeful\n- content\n- romantic\n\n  Type 'exit' to quit the program.\n\nIf the Emotion you enter is NOT in the list, so we will show **pop** music instead.\n\n**How It Works**\n\n- **Authentication**: The script uses the SpotifyClientCredentials class to handle authentication with the Spotify API.\n- **Emotion-to-Genre Mapping**: The script maps emotions to corresponding music genres using a predefined dictionary.\n- **Track Recommendations**: The script queries the Spotify API to fetch song recommendations based on the selected genre.\n- **User Input**: The user inputs their emotion, and the script fetches and displays a playlist of matching songs."
  },
  {
    "path": "Mood Based Music Recommender/requirement.txt",
    "content": "requests==2.32.3\nspotipy==2.24.0\n"
  },
  {
    "path": "Movie Scraper/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Movie Scraper/scrape.py",
    "content": "from bs4 import BeautifulSoup\nimport requests\nfrom fake_useragent import UserAgent\n\ndef requestUrl_and_bs4(url:str):\n    # All request and parser goes through here\n    agents = UserAgent().random\n    user_agent={\"User-Agent\": agents}\n\n    # Fixed the requests (changed status code from 403 to 200) \n    html = requests.get(url, headers=user_agent)\n    soup = BeautifulSoup(html.text, 'html.parser')\n\n    return soup\n\n\ndef getMovieDetails(movieName:str):\n    url = 'https://www.imdb.com'\n    query = '/search/title?title='\n    movieDetails = {}\n    movienamequery = query+'+'.join(movieName.strip().split(' '))\n    website_url = url+movienamequery+'&title_type=feature'\n\n    bs = requestUrl_and_bs4(website_url)\n\n    result = bs.find('a', {'class': 'ipc-title-link-wrapper'})\n    if result is None:\n        return None\n\n    movielink = url+result.attrs['href']\n\n    bs = requestUrl_and_bs4(movielink)\n\n    # Fix the movie name\n    movieDetails['name'] = bs.find('h1', {'data-testid': 'hero__pageTitle'}).text\n\n    # Fix year, runtime\n    box_one = bs.find('div', {'class': 'sc-b7c53eda-0 dUpRPQ'}).ul\n    box = box_one.find_all('li')\n    try:\n        movieDetails['year'] = box[0].text\n    except AttributeError:\n        movieDetails['year'] = 'Not available'\n\n    # Fix genres\n    box_two = bs.find('div', {'data-testid': \"genres\"})\n    movieDetails['genres'] = [\n       i.text for i in box_two.select('div.ipc-chip-list__scroller>a>span')]\n    \n    # Fix ratings\n    try:\n        movieDetails['rating'] = f\"{bs.find(\n            'div', {'data-testid': 'hero-rating-bar__aggregate-rating__score'}).span.text}/10 ({bs.find('div', {'class': 'sc-bde20123-3 gPVQxL'}).text})\"\n        movieDetails['runtime'] = box[2].text.strip()\n    except AttributeError:\n        movieDetails['rating'] = 'Not yet rated'\n        movieDetails['runtime'] = 'Not available'\n\n    # To get movie release date\n    movie_release_dates_url= f\"{url}{box[0].a.attrs['href']}\" \n    soup = requestUrl_and_bs4(movie_release_dates_url)\n\n    movieDetails['release_date'] = soup.select_one('#rel_1 > div > ul > li > span.ipc-metadata-list-item__list-content-item').text\n\n    creditSummary = bs.select('div.ipc-metadata-list-item__content-container > ul')\n\n    movieDetails['directors'] = [i.text for i in creditSummary[0].select('li>a')]\n    \n    try:\n        movieDetails['cast'] = [i.text for i in creditSummary[2].select('li>a')]\n        movieDetails['writers'] = [i.text for i in creditSummary[1].select('li>a')]\n\n    except IndexError:\n        movieDetails['cast']=movieDetails['writers']\n        movieDetails['writers']='Not found'\n\n    movieDetails['plot'] = bs.find('span', {'data-testid': 'plot-l'}).text.strip()\n   \n    return movieDetails\n\ndef main():\n    movieName = input('Enter the movie name : \\n')\n    movieDetails = getMovieDetails(movieName)\n    if movieDetails is None:\n        print('No movie found with given name!!!!!')\n        quit()\n    print('\\n{movie} ({year})'.format(\n        movie=movieDetails['name'], year=movieDetails['year']))\n    print('Rating:', movieDetails['rating'])\n    print('Runtime:', movieDetails['runtime'])\n    print('Release Date:', movieDetails['release_date'])\n    print('Genres:', ', '.join(movieDetails['genres']))\n    print('Director:', ', '.join(movieDetails['directors']))\n    print('Writer:', ', '.join(movieDetails['writers']))\n    print('Cast:', ', '.join(movieDetails['cast']))\n    print('Plot Summary:\\n', movieDetails['plot'])\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "My-Personal-Journal/README.md",
    "content": "# Personal Journal\n\nA 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.\n\n## Features\n\n- **Add New Entries**: Users can add journal entries with mood, content, and tags.\n- **Search Entries**: Search through entries using keywords or specific dates.\n- **Tag Management**: Create and view tags associated with each entry, and filter entries by tags.\n- **User-Friendly Interface**: A clean and professional UI for easy navigation and use.\n\n## Technologies Used\n\n- Python\n- Flask\n- SQLite\n- HTML/CSS\n\n## Installation\n\n1. **Clone the Repository**:\n   ```bash\n   git clone <repository-url>\n   cd your_project\n\n2. **Install Required Packages: Make sure you have Python installed (preferably Python 3). Install the required packages using pip**:\n    ```bash\n    pip install -r requirements.txt\n\n3. **Run the Application: Start the Flask application**:\n    ```bash\n    python app.py\n\n4. **Access the App: Open your web browser and navigate to http://127.0.0.1:8080 to access the application.**\n"
  },
  {
    "path": "My-Personal-Journal/app.py",
    "content": "from flask import Flask, render_template, request, redirect, url_for\nfrom journal_app import add_entry, search_entries\nfrom datetime import datetime\nimport sqlite3\n\napp = Flask(__name__)\n\n# Route to show the home page\n@app.route('/')\ndef index():\n    return render_template('index.html')\n\n# Route to add a new journal entry\n@app.route('/add', methods=['GET', 'POST'])\ndef add():\n    if request.method == 'POST':\n        mood = request.form['mood']\n        content = request.form['content']\n        tags = request.form['tags']\n        add_entry(\"user_1\", mood, content, tags)\n        return redirect(url_for('index'))\n    return render_template('add.html')\n\n# Route to search journal entries\n\n\n@app.route('/search', methods=['GET', 'POST'])\ndef search():\n    if request.method == 'POST':\n        search_input = request.form['search_term']\n\n        # Try to parse the input as a date\n        try:\n            search_date = datetime.strptime(search_input, '%Y-%m-%d').date()\n            results = search_entries(\"user_1\", date=search_date)\n        except ValueError:\n            # If parsing fails, treat it as a search term\n            results = search_entries(\"user_1\", search_term=search_input)\n\n        return render_template('search_results.html', results=results)\n\n    return render_template('search.html')\n\n\n# Route to list all unique tags\n@app.route('/tags')\ndef list_tags():\n    conn = sqlite3.connect('journal.db')\n    cursor = conn.cursor()\n\n    # Fetch unique tags from all entries\n    cursor.execute(\"SELECT DISTINCT tags FROM journal_entries\")\n    tags_data = cursor.fetchall()\n    conn.close()\n\n    # Flatten the tags and remove duplicates\n    tags = set()\n    for row in tags_data:\n        if row[0]:\n            tags.update(tag.strip() for tag in row[0].split(','))\n\n    return render_template('tags.html', tags=sorted(tags))\n\n# Route to show journal entries by tag\n@app.route('/tags/<tag>')\ndef entries_by_tag(tag):\n    conn = sqlite3.connect('journal.db')\n    cursor = conn.cursor()\n\n    # Search for entries that contain the selected tag\n    cursor.execute(\"SELECT * FROM journal_entries WHERE tags LIKE ?\", ('%' + tag + '%',))\n    results = cursor.fetchall()\n    conn.close()\n\n    return render_template('search_results.html', results=results)\n\nif __name__ == '__main__':\n    app.run(debug=True, port=8080)\n"
  },
  {
    "path": "My-Personal-Journal/database.py",
    "content": "from sqlalchemy.orm import sessionmaker\nfrom models import JournalEntry, Base\nfrom sqlalchemy import create_engine\n\nengine = create_engine('sqlite:///journal.db')\nBase.metadata.create_all(engine)\nSession = sessionmaker(bind=engine)\nsession = Session()\n\ndef add_entry(user_id, mood, content, tags):\n    entry = JournalEntry(user_id=user_id, mood=mood, content=content, tags=tags)\n    session.add(entry)\n    session.commit()\n\ndef search_entries(user_id, search_term=None, date=None):\n    query = session.query(JournalEntry).filter(JournalEntry.user_id == user_id)\n    if search_term:\n        query = query.filter(JournalEntry.content.contains(search_term))\n    if date:\n        query = query.filter(JournalEntry.date == date)\n    return query.all()\n"
  },
  {
    "path": "My-Personal-Journal/journal_app.py",
    "content": "import sqlite3\nfrom datetime import datetime\n\nDB_NAME = \"journal.db\"\n\ndef connect_db():\n    return sqlite3.connect(DB_NAME)\n\ndef create_table():\n    with connect_db() as conn:\n        cursor = conn.cursor()\n        cursor.execute('''\n            CREATE TABLE IF NOT EXISTS journal_entries (\n                id INTEGER PRIMARY KEY AUTOINCREMENT,\n                user_id TEXT,\n                date TEXT,\n                mood TEXT,\n                content TEXT,\n                tags TEXT\n            )\n        ''')\n        conn.commit()\n\ndef add_entry(user_id, mood, content, tags):\n    with connect_db() as conn:\n        cursor = conn.cursor()\n        cursor.execute('''\n            INSERT INTO journal_entries (user_id, date, mood, content, tags)\n            VALUES (?, ?, ?, ?, ?)\n        ''', (user_id, datetime.now().strftime('%Y-%m-%d %H:%M:%S'), mood, content, tags))\n        conn.commit()\n\ndef search_entries(user_id, search_term=None, date=None):\n    with connect_db() as conn:\n        cursor = conn.cursor()\n\n        if search_term:\n            query = '''\n                SELECT * FROM journal_entries \n                WHERE user_id = ? AND (content LIKE ? OR tags LIKE ?)\n            '''\n            cursor.execute(query, (user_id, f'%{search_term}%', f'%{search_term}%'))\n        elif date:\n            query = '''\n                SELECT * FROM journal_entries \n                WHERE user_id = ? AND date(date) = ?\n            '''\n            cursor.execute(query, (user_id, date.strftime('%Y-%m-%d')))\n        else:\n            return []\n\n        return cursor.fetchall()\n\n# Create the journal table at the start\ncreate_table()\n"
  },
  {
    "path": "My-Personal-Journal/requirements.txt",
    "content": "flask\nsqlalchemy\n# sqlite3\nbcrypt\npandas\nmatplotlib\n# tkinter\nflask"
  },
  {
    "path": "My-Personal-Journal/static/style.css",
    "content": "/* General Styles */\nbody {\n    font-family: 'Arial', sans-serif;\n    margin: 0;\n    padding: 0;\n    background-color: #f4f4f9;\n    color: #333;\n}\n\nh1, h2, h3, h4, h5, h6 {\n    color: #2c3e50;\n    text-align: center;\n}\n\n/* Header */\nheader {\n    background: #2980b9;\n    color: white;\n    padding: 20px 0;\n}\n\n/* Main Content */\n.container {\n    max-width: 1100px;\n    margin: 20px auto;\n    padding: 20px;\n    background: white;\n    border-radius: 8px;\n    box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);\n    text-align: center; /* Center text within the container */\n}\n\n/* Button Styles */\n.button-container {\n    display: flex;\n    justify-content: center; /* Center the buttons */\n    flex-direction: column; /* Stack buttons vertically */\n    gap: 20px; /* Space between buttons */\n    margin-top: 30px; /* Add margin to the top */\n}\n\n.button {\n    display: inline-block;\n    padding: 15px 30px;\n    background-color: #2980b9;\n    color: white;\n    border-radius: 4px;\n    text-decoration: none;\n    font-size: 1.2rem;\n    transition: background-color 0.3s ease;\n}\n\n.button:hover {\n    background-color: #3498db;\n}\n\n/* Footer */\nfooter {\n    text-align: center;\n    margin-top: 20px;\n    padding: 20px;\n    background-color: #2980b9;\n    color: white;\n}\n\np {\n    line-height: 1.6;\n    font-size: 1rem;\n}\n\na {\n    color: #3498db;\n    text-decoration: none;\n}\n\na:hover {\n    text-decoration: underline;\n}\n\n/* Header */\nheader {\n    background: #2980b9;\n    color: white;\n    padding: 20px 0;\n    text-align: center;\n}\n\n/* Main Content */\n.container {\n    max-width: 1100px;\n    margin: 20px auto;\n    padding: 20px;\n    background: white;\n    border-radius: 8px;\n    box-shadow: 0px 0px 15px rgba(0, 0, 0, 0.1);\n}\n\nh1 {\n    font-size: 2rem;\n    margin-bottom: 20px;\n}\n\n/* Form Styles */\n.form-group {\n    margin-bottom: 20px; /* Space between form groups */\n    text-align: left; /* Align labels and inputs to the left */\n}\n\nlabel {\n    display: block; /* Ensure labels are on separate lines */\n    margin-bottom: 5px; /* Space between label and input */\n}\n\n/* Form Styles */\nform {\n    display: flex;\n    flex-direction: column;\n    gap: 10px;\n}\n\nform input[type=\"text\"],\nform textarea {\n    padding: 10px;\n    font-size: 1rem;\n    border: 1px solid #ddd;\n    border-radius: 4px;\n}\n\nform textarea {\n    resize: vertical;\n}\n\nform input[type=\"submit\"] {\n    background-color: #2980b9;\n    color: white;\n    border: none;\n    padding: 10px;\n    display:flex;\n    font-size: 1rem;\n    cursor: pointer;\n    border-radius: 4px;\n}\n\nform input[type=\"submit\"]:hover {\n    background-color: #3498db;\n}\n\n/* Tag List */\nul {\n    list-style: none;\n    padding: 0;\n    display: flex;\n    justify-content: center; /* Centers the tags horizontally */\n    flex-wrap: wrap; /* Allows the tags to wrap if they exceed the width */\n    gap: 10px;\n}\n\nul li {\n    display: inline-block;\n    margin-right: 10px;\n}\n\nul li a {\n    display: inline-block;\n    padding: 10px 20px;\n    background-color: #2980b9;\n    color: white;\n    border-radius: 4px;\n    transition: background-color 0.3s ease;\n}\n\nul li a:hover {\n    background-color: #3498db;\n}\n\n/* Search Results */\n.search-results {\n    margin-top: 20px;\n}\n\n.search-results p {\n    padding: 10px;\n    background: #ecf0f1;\n    border-left: 5px solid #2980b9;\n    margin-bottom: 10px;\n}\n\nhr {\n    border: 0;\n    height: 1px;\n    background: #ddd;\n    margin: 20px 0;\n}\n\n/* Footer */\nfooter {\n    text-align: center;\n    margin-top: 20px;\n    padding: 20px;\n    background-color: #2980b9;\n    color: white;\n}\n\ninput[type=\"text\"],\ntextarea,\nselect {\n    width: 100%; /* Take full width of the container */\n    padding: 10px; /* Add padding for comfort */\n    border: 1px solid #ccc; /* Border style */\n    border-radius: 4px; /* Rounded corners */\n    box-sizing: border-box; /* Include padding in width */\n}\n\ntextarea {\n    height: 100px; /* Set a height for the textarea */\n}\n/* Search Results Styles */\n.results {\n    margin-top: 30px; /* Space above search results */\n    text-align: left; /* Align results to the left */\n}\n\n.results ul {\n    list-style-type: none; /* Remove default list styles */\n    padding: 0; /* Remove padding */\n}\n\n.results li {\n    background-color: #f4f4f9; /* Light background for entries */\n    border: 1px solid #ccc; /* Border for each entry */\n    border-radius: 4px; /* Rounded corners */\n    padding: 10px; /* Padding for comfort */\n    margin-bottom: 15px; /* Space between entries */\n}"
  },
  {
    "path": "My-Personal-Journal/templates/add.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Add New Entry</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='style.css') }}\">\n</head>\n<body>\n    <header>\n        <h1>Add New Journal Entry</h1>\n    </header>\n    <div class=\"container\">\n        <form action=\"/add\" method=\"post\">\n            <div class=\"form-group\">\n                <label for=\"title\">Title:</label>\n                <input type=\"text\" id=\"title\" name=\"title\" required>\n            </div>\n            <div class=\"form-group\">\n                <label for=\"content\">Content:</label>\n                <textarea id=\"content\" name=\"content\" required></textarea>\n            </div>\n            <div class=\"form-group\">\n                <label for=\"mood\">Mood:</label>\n                <select id=\"mood\" name=\"mood\" required>\n                    <option value=\"\">Select Mood</option>\n                    <option value=\"happy\">Happy</option>\n                    <option value=\"sad\">Sad</option>\n                    <option value=\"neutral\">Neutral</option>\n                    <option value=\"excited\">Excited</option>\n                    <option value=\"angry\">Angry</option>\n                </select>\n            </div>\n            <div class=\"form-group\">\n                <label for=\"tags\">Tags:</label>\n                <input type=\"text\" id=\"tags\" name=\"tags\" placeholder=\"Comma-separated tags\">\n            </div>\n            <button type=\"submit\" class=\"button\">Save Entry</button>\n        </form>\n    </div>\n    <footer>\n        <p>&copy; 2024 Personal Journal</p>\n    </footer>\n</body>\n</html>\n"
  },
  {
    "path": "My-Personal-Journal/templates/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n    <meta charset=\"UTF-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n    <title>Personal Journal</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='style.css') }}\">\n</head>\n<body>\n    <header>\n        <h1 style=\"color:white;\">Welcome to Your Personal Journal</h1>\n    </header>\n    <div class=\"container\">\n        <div class=\"button-container\">\n            <a class=\"button\" href=\"/add\">Add New Entry</a>\n            <a class=\"button\" href=\"/search\">Search Entries</a>\n            <a class=\"button\" href=\"/tags\">View All Tags</a>\n        </div>\n    </div>\n    <footer>\n        <p>&copy; 2024 Personal Journal</p>\n    </footer>\n</body>\n</html>\n"
  },
  {
    "path": "My-Personal-Journal/templates/search.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Search Journal Entries</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='style.css') }}\">\n\n</head>\n<body>\n    <div class=\"container\">\n        <h1>Search Journal Entries</h1>\n        <form method=\"POST\">\n            Search by keyword or date (YYYY-MM-DD): <input type=\"text\" name=\"search_term\"><br>\n            <input type=\"submit\" value=\"Search\">\n        </form>\n</body>\n</html>\n"
  },
  {
    "path": "My-Personal-Journal/templates/search_results.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Search Results</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='style.css') }}\">\n\n</head>\n<body>\n    <h1>Journal Entries</h1>\n   \n    <div class=\"container\">\n         {% for result in results %}\n        <p>Date: {{ result[2] }}, Mood: {{ result[3] }}, Tags: {{ result[5] }}</p>\n            <p>{{ result[4] }}</p>\n            <hr>\n        {% else %}\n            <p>No entries found.</p>\n        {% endfor %}\n    </div>\n        \n</body>\n</html>\n"
  },
  {
    "path": "My-Personal-Journal/templates/tags.html",
    "content": "<!DOCTYPE html>\n<html>\n<head>\n    <title>Tags</title>\n    <link rel=\"stylesheet\" type=\"text/css\" href=\"{{ url_for('static', filename='style.css') }}\">\n\n</head>\n<body>\n    <h1>Tags</h1>\n    <ul>\n        {% for tag in tags %}\n            <li><a href=\"/tags/{{ tag }}\">{{ tag }}</a></li>\n        {% else %}\n            <li>No tags found.</li>\n        {% endfor %}\n    </ul>\n</body>\n</html>\n"
  },
  {
    "path": "My-Personal-Journal/ui.py",
    "content": "# from main import add_entry, search_entries\n# import datetime\n\n# def display_menu():\n#     print(\"\\n=== My Personal Journal ===\")\n#     print(\"1. Create New Journal Entry\")\n#     print(\"2. Search Journal Entries\")\n#     print(\"3. Exit\")\n\n# def get_mood():\n#     mood = None\n#     while mood not in [\"happy\", \"sad\", \"neutral\"]:\n#         mood = input(\"How are you feeling today? (happy, sad, neutral): \").lower()\n#     return mood\n\n# def get_tags():\n#     tags = input(\"Add tags (comma-separated, e.g., work, personal): \")\n#     return tags\n\n# def create_new_entry(user_id):\n#     mood = get_mood()\n#     content = input(\"Write your journal entry: \")\n#     tags = get_tags()\n#     add_entry(user_id, mood, content, tags)\n#     print(\"Your entry has been saved!\")\n\n# def search_journal_entries(user_id):\n#     print(\"\\nSearch Entries\")\n#     print(\"1. Search by keyword\")\n#     print(\"2. Search by date\")\n#     choice = input(\"Choose a search option: \")\n\n#     if choice == '1':\n#         search_term = input(\"Enter a keyword to search for: \")\n#         results = search_entries(user_id, search_term=search_term)\n#     elif choice == '2':\n#         date_str = input(\"Enter a date (YYYY-MM-DD) to search: \")\n#         try:\n#             date = datetime.datetime.strptime(date_str, '%Y-%m-%d')\n#         except ValueError:\n#             print(\"Invalid date format. Please use YYYY-MM-DD.\")\n#             return\n#         results = search_entries(user_id, date=date)\n#     else:\n#         print(\"Invalid option.\")\n#         return\n\n#     if results:\n#         for entry in results:\n#             print(f\"\\nDate: {entry[2]}\")\n#             print(f\"Mood: {entry[3]}\")\n#             print(f\"Tags: {entry[5]}\")\n#             print(f\"Entry: {entry[4]}\")\n#             print(\"-\" * 40)\n#     else:\n#         print(\"No entries found for your search criteria.\")\n\n# def main_ui():\n#     user_id = input(\"Enter your user ID to start: \")\n\n#     while True:\n#         display_menu()\n#         choice = input(\"Select an option (1-3): \")\n\n#         if choice == '1':\n#             create_new_entry(user_id)\n#         elif choice == '2':\n#             search_journal_entries(user_id)\n#         elif choice == '3':\n#             print(\"Goodbye!\")\n#             break\n#         else:\n#             print(\"Invalid choice. Please try again.\")\n\n# if __name__ == \"__main__\":\n#     main_ui()\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom journal_app import add_entry, search_entries\nfrom datetime import datetime\n\nclass JournalApp(tk.Tk):\n    def __init__(self):\n        super().__init__()\n\n        self.title(\"Personal Journal\")\n        self.geometry(\"400x400\")\n\n        self.label = tk.Label(self, text=\"Personal Journal\", font=(\"Helvetica\", 16))\n        self.label.pack(pady=10)\n\n        self.add_button = tk.Button(self, text=\"Add New Entry\", command=self.add_entry)\n        self.add_button.pack(pady=5)\n\n        self.search_button = tk.Button(self, text=\"Search Entries\", command=self.search_entries)\n        self.search_button.pack(pady=5)\n\n    def add_entry(self):\n        self.new_window = tk.Toplevel(self)\n        self.new_window.title(\"Add New Entry\")\n\n        mood_label = tk.Label(self.new_window, text=\"Mood (happy, sad, neutral):\")\n        mood_label.pack(pady=5)\n        self.mood_entry = tk.Entry(self.new_window)\n        self.mood_entry.pack(pady=5)\n\n        content_label = tk.Label(self.new_window, text=\"Write your journal entry:\")\n        content_label.pack(pady=5)\n        self.content_entry = tk.Text(self.new_window, height=5, width=30)\n        self.content_entry.pack(pady=5)\n\n        tags_label = tk.Label(self.new_window, text=\"Tags (comma-separated):\")\n        tags_label.pack(pady=5)\n        self.tags_entry = tk.Entry(self.new_window)\n        self.tags_entry.pack(pady=5)\n\n        submit_button = tk.Button(self.new_window, text=\"Submit\", command=self.save_entry)\n        submit_button.pack(pady=10)\n\n    def save_entry(self):\n        mood = self.mood_entry.get()\n        content = self.content_entry.get(\"1.0\", tk.END)\n        tags = self.tags_entry.get()\n\n        if mood and content:\n            add_entry(\"user_1\", mood, content, tags)\n            messagebox.showinfo(\"Success\", \"Journal entry saved!\")\n            self.new_window.destroy()\n        else:\n            messagebox.showwarning(\"Input Error\", \"Please fill in all fields.\")\n\n    def search_entries(self):\n        self.search_window = tk.Toplevel(self)\n        self.search_window.title(\"Search Entries\")\n\n        search_label = tk.Label(self.search_window, text=\"Search by keyword or date (YYYY-MM-DD):\")\n        search_label.pack(pady=5)\n        self.search_entry = tk.Entry(self.search_window)\n        self.search_entry.pack(pady=5)\n\n        search_button = tk.Button(self.search_window, text=\"Search\", command=self.perform_search)\n        search_button.pack(pady=10)\n\n    def perform_search(self):\n        search_term = self.search_entry.get()\n        results = search_entries(\"user_1\", search_term=search_term)\n\n        if results:\n            result_window = tk.Toplevel(self)\n            result_window.title(\"Search Results\")\n\n            for result in results:\n                result_label = tk.Label(result_window, text=f\"Date: {result[2]}, Mood: {result[3]}, Tags: {result[5]}\")\n                result_label.pack()\n                content_label = tk.Label(result_window, text=f\"Entry: {result[4]}\")\n                content_label.pack(pady=5)\n        else:\n            messagebox.showinfo(\"No Results\", \"No journal entries found.\")\n\nif __name__ == \"__main__\":\n    app = JournalApp()\n    app.mainloop()\n"
  },
  {
    "path": "Notepad/main.py",
    "content": "from tkinter import *\nfrom tkinter import filedialog, messagebox\n\nroot = Tk()\nroot.geometry(\"700x500\")\nroot.title(\"Aman's Notepad\")\n\ndef save_file():\n    open_file = filedialog.asksaveasfile(mode='w', defaultextension=\".txt\")\n    if open_file is None:\n        return\n    text = str(entry.get(1.0, END))\n    open_file.write(text)\n    open_file.close()\n\ndef clear():\n    messagebox.showinfo(\"Cleared\", \"Cleared all contents !\")\n    entry.delete(1.0, END)\n\ndef open_file():\n    file = filedialog.askopenfile(mode='r', filetype=[('text files', '*.txt')])\n    if file is not None:\n        content = file.read()\n    entry.insert(INSERT, content)\n\nb1 = Button(root, text=\"Save\", command=save_file)\nb1.place(x=10, y=10)\n\nb2 = Button(root, text=\"Clear\", command=clear)\nb2.place(x=70, y=10)\n\nb3 = Button(root, text=\"Open\", command=open_file)\nb3.place(x=120, y=10)\n\nentry = Text(root, height=60, width=70, wrap=WORD, bg=\"black\", fg=\"green\", selectbackground=\"red\",\n             font=\"Courier 15\", insertbackground=\"violet\")\nentry.place(x=10, y=50)\n\nroot.mainloop()\n"
  },
  {
    "path": "OCR Image-to-Text Conversion/README.md",
    "content": "## Introduction\n\nImage 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.\n\n## Requirements\n\n- Python 3.x\n- Libraries:\n  - `pytesseract`\n  - `PIL` (Pillow)\n\nYou can install the required libraries by running:\n\n```bash\n    pip install pytesseract Pillow\n```\n\n## Installation Instructions for All Operating Systems\n\n### Windows\n\n1. **Install Python**:\n\n   - Download and install Python from the [official website](https://www.python.org/downloads/).\n   - During installation, make sure to check the box that says \"Add Python to PATH\".\n\n2. **Install Tesseract OCR**:\n\n   - Download the Tesseract installer from the [Tesseract GitHub releases page](https://github.com/tesseract-ocr/tesseract/releases).\n   - Run the installer and note the installation path (usually `C:\\Program Files\\Tesseract-OCR`).\n\n3. **Set Tesseract Path**:\n\n   - Add the Tesseract installation path to your system environment variables.\n     - Right-click on \"This PC\" or \"My Computer\" > Properties > Advanced system settings > Environment Variables.\n     - Under \"System variables\", find the `Path` variable and click Edit. Add the Tesseract path.\n\n4. **Install Required Libraries**:\n   - Open Command Prompt and run:\n     ```bash\n     pip install pytesseract Pillow\n     ```\n\n### macOS\n\n1. **Install Homebrew** (if not already installed):\n\n   - Open Terminal and run:\n     ```bash\n     /bin/bash -c \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)\"\n     ```\n\n2. **Install Python**:\n\n   - Use Homebrew to install Python:\n     ```bash\n     brew install python\n     ```\n\n3. **Install Tesseract OCR**:\n\n   - Install Tesseract using Homebrew:\n     ```bash\n     brew install tesseract\n     ```\n\n4. **Install Required Libraries**:\n   - In Terminal, run:\n     ```bash\n     pip install pytesseract Pillow\n     ```\n\n### Linux (Ubuntu/Debian)\n\n1. **Install Python** (if not already installed):\n\n   - Open Terminal and run:\n     ```bash\n     sudo apt update\n     sudo apt install python3 python3-pip\n     ```\n\n2. **Install Tesseract OCR**:\n\n   - Install Tesseract using:\n     ```bash\n     sudo apt install tesseract-ocr\n     ```\n\n3. **Install Required Libraries**:\n   - In Terminal, run:\n     ```bash\n     pip3 install pytesseract Pillow\n     ```\n\n## Usage Instructions\n\nAfter completing the installation, follow the usage instructions below to run the application.\n\n1. Open Command Prompt.\n2. Navigate to the directory where the script is located using the `cd` command:\n   ```bash\n    cd path\\to\\your\\script\n   ```\n3. Run the Python script\n   ```bash\n    python image_text_extractor.py - mine is main.py\n   ```"
  },
  {
    "path": "OCR Image-to-Text Conversion/main.py",
    "content": "import pytesseract\nfrom PIL import Image\nimport os\n\ndef extract_text_from_image(image_path):\n    \"\"\"Extracts text from an image file using Tesseract OCR.\"\"\"\n    try:\n        # Open the image file\n        with Image.open(image_path) as img:\n            # Use pytesseract to do OCR on the image\n            extracted_text = pytesseract.image_to_string(img)\n            return extracted_text\n    except Exception as e:\n        print(f\"Error processing the image: {e}\")\n        return None\n\ndef main():\n\n    image_path = input(\"Enter the path to the image file: \")\n\n    if not os.path.isfile(image_path):\n        print(\"File does not exist. Please check the path and try again.\")\n        return\n    text = extract_text_from_image(image_path)\n\n    if text:\n        print(\"Extracted Text:\")\n        print(text)\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "OCR Image-to-Text Conversion/requirements.txt",
    "content": "pillow==11.0.0\npytesseract==0.3.13"
  },
  {
    "path": "PROJECTS.md",
    "content": "# Project List\n\n* [Age Calculator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Age%20Calculator)\n* [Alarm Bot](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Alarm%20Bot)\n* [Ascii Art Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Ascii%20Art%20Generator)\n* [Audio Book Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Audio%20Book%20Generator)\n* [CountDown Timer](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/CountDown%20Timer)\n* [Currency Converter](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Currency%20Converter)\n* [Custom GPT](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Custom%20GPT)\n* [Customizable_Workout_Playlist_Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Customizable_Workout_Playlist_Generator)\n* [Digital Clock](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Digital%20Clock)\n* [Expense Splitter](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Expense%20Splitter)\n* [Extractive Text Summarization](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Extractive%20Text%20Summarization)\n* [Facebook Video Downloader](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Facebook%20Video%20Downloader)\n* [Geographic Distance](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Geographic%20Distance)\n* [Gesture-Based-Game-Controller](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Gesture-Based-Game-Controller)\n* [Handwritten-Assignments](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Handwritten-Assignments)\n* [Headlight Detection](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Headlight%20Detection)\n* [Helmet Detection](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Helmet%20Detection)\n* [Image Compression](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Image%20Compression)\n* [ImageSize Reducer](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/ImageSize%20Reducer)\n* [Img-Steganograpy](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Img-Steganograpy)\n* [Learn-FastAPI](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Learn-FastAPI)\n* [Mental Health chatbot](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Mental%20Health%20chatbot)\n* [Merge PDFs](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Merge%20PDFs)\n* [MobileNumber Tracker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/MobileNumber%20Tracker)\n* [Mood Based Music Recommender](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Mood%20Based%20Music%20Recommender)\n* [Movie Scraper](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Movie%20Scraper)\n* [My-Personal-Journal](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/My-Personal-Journal)\n* [Notepad](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Notepad)\n* [OCR Image-to-Text Conversion](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/OCR%20Image-to-Text%20Conversion)\n* [Password Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Password%20Generator)\n* [Plagiarism-Checker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Plagiarism-Checker)\n* [Pomodoro Timer](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Pomodoro%20Timer)\n* [QR Code Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/QR%20Code%20Generator)\n* [Random Movie Selector](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Random%20Movie%20Selector)\n* [Random Quotes Generator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Random%20Quotes%20Generator)\n* [Real-Time Cryptocurrency Price Tracker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Real-Time%20Cryptocurrency%20Price%20Tracker)\n* [Recipe Finder with Meal Planner](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Recipe%20Finder%20with%20Meal%20Planner)\n* [Resume Builder](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Resume%20Builder)\n* [Simple Assistant](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Simple%20Assistant)\n* [Snake-Game](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Snake-Game)\n* [Speech To Text](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Speech%20To%20Text)\n* [Spell Checker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Spell%20Checker)\n* [Telegram Bot](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Telegram%20Bot)\n* [Text Summarizer](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Text%20Summarizer)\n* [Text To Speech](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Text%20To%20Speech)\n* [Text to Morse Code](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Text%20to%20Morse%20Code)\n* [Text_Adventure_Game](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Text_Adventure_Game)\n* [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))\n* [To Do List](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/To%20Do%20List)\n* [Translator](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Translator)\n* [URL Sortener](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/URL%20Sortener)\n* [Validate-Email](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Validate-Email)\n* [Video Processor](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Video%20Processor)\n* [Video To Audio](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Video%20To%20Audio)\n* [Weather Alert](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Weather%20Alert)\n* [Word_frequency_counter](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Word_frequency_counter)\n* [Youtube Video Downloader](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/Youtube%20Video%20Downloader)\n* [personal-finance-tracker](https://github.com/king04aman/All-In-One-Python-Projects/tree/main/personal-finance-tracker)\n"
  },
  {
    "path": "Password Generator/main.py",
    "content": "from tkinter import *\nfrom random import choice\nimport string\n\nclass App:\n    def __init__(self):\n        self.window = Tk()\n        self.window.title('password_generator')\n        self.window.iconbitmap('logo.ico')\n        self.window.iconphoto(False, PhotoImage(file='logo.png'))\n        self.window.geometry('500x255')\n        self.window.config(bg='gray')\n\n        self.label()\n        self.entry()\n        self.button()\n\n    def label(self):\n        label_title = Label(self.window, text='Welcome to password generator', font=('Courrier', 20), bg='gray', fg='black')\n        label_title.pack()\n\n    def entry(self):\n        self.password_entry = Entry(self.window, font=('Courrier', 25), bg='white', fg='black', width=30, relief='solid')\n        self.password_entry.pack(pady=50)\n\n    def button(self):\n        password_generator = Button(self.window, text=\"Generate_password\",  font=('Courrier', 12), bg='white', fg='black', width=25, command=self.generate_password)\n        password_generator.pack()\n\n    def generate_password(self):\n        characters = string.ascii_letters + string.punctuation + string.digits\n        password = \"\"\n        for x in range(28):\n            password+=choice(characters)\n        self.password_entry.delete(0, END)\n        self.password_entry.insert(0, password)\n        \napp = App()\napp.window.mainloop()\n"
  },
  {
    "path": "Password Generator/requirements.txt",
    "content": "tk==0.1.0\n"
  },
  {
    "path": "Plagiarism-Checker/main.py",
    "content": "import os\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\nstudent_files = [doc for doc in os.listdir() if doc.endswith('.txt')]\nstudent_notes = [open(_file, encoding='utf-8').read()\n                 for _file in student_files]\n\n\ndef vectorize(Text): return TfidfVectorizer().fit_transform(Text).toarray()\ndef similarity(doc1, doc2): return cosine_similarity([doc1, doc2])\n\n\nvectors = vectorize(student_notes)\ns_vectors = list(zip(student_files, vectors))\nplagiarism_results = set()\n\n\ndef check_plagiarism():\n    global s_vectors\n    for student_a, text_vector_a in s_vectors:\n        new_vectors = s_vectors.copy()\n        current_index = new_vectors.index((student_a, text_vector_a))\n        del new_vectors[current_index]\n        for student_b, text_vector_b in new_vectors:\n            sim_score = similarity(text_vector_a, text_vector_b)[0][1]\n            student_pair = sorted((student_a, student_b))\n            score = (student_pair[0], student_pair[1], sim_score)\n            plagiarism_results.add(score)\n    return plagiarism_results\n\n\nfor data in check_plagiarism():\n    print(data)\n    "
  },
  {
    "path": "Plagiarism-Checker/requirements.txt",
    "content": "scikit_learn==0.24.2"
  },
  {
    "path": "Plagiarism-Checker/test1.txt",
    "content": "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."
  },
  {
    "path": "Plagiarism-Checker/test2.txt",
    "content": "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)."
  },
  {
    "path": "Pomodoro Timer/README.md",
    "content": "# Pomodoro Timer\n\nA simple, customizable command line pomodoro timer built in Python.\n\n## Features\n\n- Customizable work, short and long breaks intervals: Define your own durations for each cycle.\n- Pause whenever you want: Pause the timer when you want to take a break.\n- Cycles: Run Multiple cycles of work and break intervals\n- Console output: Show work and break intervals in the console.\n\n## How it works\n\nThe Pomodoro Timer follow these steps:\n1. Set your work and break intervals.\n2. Take a short break every work interval.\n3. After a set number of cycles, take a long break.\n\n## Usage\n\n1. Clone this repository to your machine.\n2. Run the Python script from the command line.\n   '''python pomodoro_timer.py'''\n\n## Author\n\n[MeuHubPython](https://github.com/MeuHubPython)\n\n"
  },
  {
    "path": "Pomodoro Timer/main.py",
    "content": "import time\n\n\ndef countdown(minutes, label):\n    total_seconds = minutes * 60\n    while total_seconds:\n        mins, secs = divmod(total_seconds, 60)\n        timer = f\"{mins:02d}:{secs:02d}\"\n        print(f\"{label} Timer: {timer}\", end=\"\\r\")\n        time.sleep(1)\n        total_seconds -= 1\n    print(f\"\\n{label} finished!\")\n\n\ndef handle_pause_stop():\n    while True:\n        user_input = input(\n            \"\\nPress 'p' to pause, 's' to stop, or 'Enter' to continue: \"\n        ).lower()\n        if user_input == \"p\":\n            print(\"Timer paused. Press 'Enter' to resume.\")\n            input()\n        elif user_input == \"s\":\n            print(\"Timer stopped.\")\n            return True  # Return True to signal that the timer should stop\n        else:\n            return False  # Return False to continue with the timer\n\n\ndef pomodoro_timer(work_min, short_break_min, long_break_min, cycles):\n    for i in range(cycles):\n        print(f\"\\nCycle {i+1} of {cycles}\")\n        countdown(work_min, \"Work\")\n        if i < cycles - 1:\n            print(\"\\nStarting short break...\")\n            if handle_pause_stop():\n                return\n            countdown(short_break_min, \"Short Break\")\n        else:\n            print(\"\\nStarting long break...\")\n            if handle_pause_stop():\n                return\n            countdown(long_break_min, \"Long Break\")\n            if not repeat_or_end():\n                return\n\n\ndef repeat_or_end():\n    user_input = input(\n        \"\\nCycle finished. Would you like to repeat the cycle? (y/n): \"\n    ).lower()\n    return user_input == \"y\"\n\n\ndef get_valid_input(prompt):\n    while True:\n        try:\n            value = int(input(prompt))\n            if value <= 0:\n                raise ValueError\n            return value\n        except ValueError:\n            print(\"Invalid input. Please enter a positive integer.\")\n\n\nif __name__ == \"__main__\":\n    work_minutes = get_valid_input(\"Enter work interval in minutes: \")\n    short_break_minutes = get_valid_input(\"Enter short break interval in minutes: \")\n    long_break_minutes = get_valid_input(\"Enter long break interval in minutes: \")\n    cycles = get_valid_input(\"Enter the number of cycles: \")\n\n    pomodoro_timer(work_minutes, short_break_minutes, long_break_minutes, cycles)\n"
  },
  {
    "path": "Pomodoro Timer/runtime.txt",
    "content": "Python 3.10.12\n"
  },
  {
    "path": "QR Code Generator/advanceQrGenerator.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Aman Kumar\n# Version: 1.0.0 \n\nimport qrcode\nfrom PIL import Image\n\nqr = qrcode.QRCode(version=1, error_correction=qrcode.ERROR_CORRECT_H, box_size=10, border=4)\n\nqr.add_data(\"https://github.com/king04aman/all-in-one-python-projects\")\nqr.make(fit=True)\nimg = qr.make_image(fill_color='blue', back_color='white')\nimg.save('./advanceQR.png')"
  },
  {
    "path": "QR Code Generator/basicQrGenerator.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Aman Kumar\n# Version: 1.0.0 \n\nimport qrcode as qr\n\nqrImg = qr.make(\"https://github.com/king04aman/All-In-One-Python-Projects/\")\nqrImg.save('demo.png')\n"
  },
  {
    "path": "QR Code Generator/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "README.md",
    "content": "<h1 align=\"center\"> All-In-One-Python-Projects </h1>\n\n<!-- banner -->\n![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)\n\n<!-- project badges -->\n[![BuiltByDev](https://forthebadge.com/images/badges/built-by-developers.svg)](https://github.com/king04aman)\n[![BuiltWithLov](https://forthebadge.com/images/badges/built-with-love.svg)](https://github.com/king04aman)\n[![MadeWithPy](https://forthebadge.com/images/badges/made-with-python.svg)](https://github.com/king04aman)\n<br/>\n![Issues](https://img.shields.io/github/issues/king04aman/All-In-One-Python-Projects.svg)\n![Contributors](https://img.shields.io/github/contributors/king04aman/All-In-One-Python-Projects.svg)\n![SizeInBytes](https://img.shields.io/github/repo-size/king04aman/All-In-One-Python-Projects.svg)\n![TopLanguage](https://img.shields.io/github/languages/top/king04aman/All-In-One-Python-Projects.svg)\n![PullRequests](https://img.shields.io/github/issues-pr/king04aman/All-In-One-Python-Projects.svg)\n\n\n<h2 align=\"center\"> Description </h2>\n\n_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._\n\n<hr>\n\n## Getting Started\nThese instructions will get you a copy of the project up and running on your local machine for development and testing purposes.\n\n## Prerequisites\n- Python 3.x\n\n## Installing\n1. Clone the repository to your local machine\n    ```bash\n    git clone https://github.com/king04aman/All-In-One-Python-Projects.git\n    ```\n2. Change directory into the cloned repository\n    ```bash\n    cd All-In-One-Python-Projects/<Project_name>\n    ``` \n3. Install the required libraries\n    ```bash\n    pip install -r requirements.txt\n    ```\n4. Run the program using\n    ```bash\n    python3 <script_name>.py\n    ```\n\n<hr>\n\n<h2 align='center'> Contribution Guide</h2>\n\n- Have a look at [Contributing Guidelines](CONTRIBUTING.md).\n- Take a look at the existing issues or create your own issues.\n- Avoid making pull request unless you are assigned with the issue.\n- Select the project on which you want to work or you can add your own project.\n- Create an issue with description on which project you want to work and wait for approval.\n- While making pull request add issue number with `#` (for example `#04`)\n- After approval fork this repository, add your changes then make pull request with issue number and wait for review.\n- Star this repository. 🌟\n\n\n<h2 align=center> Awesome Contributors 🤩 </h2>\n\nThanks go to these **Wonderful Contributors** ✨✨:\n\n<table>\n\t<tr>\n\t\t<td>\n\t\t\t<a href=\"https://github.com/king04aman/All-In-One-Python-Projects/graphs/contributors\">\n\t    \t<img src=\"https://contrib.rocks/image?repo=king04aman/All-In-One-Python-Projects\" />\n\t    </a>\n\t\t</td>\n\t</tr>\n</table>\n\n<hr>\n\n<h2 align='center'>Project Maintainer </h2>\n\n<table>\n\t<tr>\n        <td align=\"center\">\n            <a href=\"https://github.com/king04aman\">\n            <img src=\"https://images.weserv.nl/?url=https://avatars.githubusercontent.com/u/62813940?v=4&h=250&w=250&fit=cover&mask=circle&maxage=7d\" width=100px height=100px />\n            </a></br> \n            <h4 style=\"color:#ff8c00;font-weight: bolder; font-size: 15px\">Aman Kumar</h4>\n        </td>\n    </tr>\n</table>\n\n## License\n*This project is licensed under the MIT License - see the [LICENSE.md](LICENSE) file for details.*\n\n\n<hr>\n<h3 align='center'>🎉 😃 Happy Hacking 😃 🎉 </h3>\n"
  },
  {
    "path": "Random Movie Selector/main.py",
    "content": "from imdb import IMDb\nimport random\n\n\nclass ChooseMovie(object):\n    def __init__(self):\n        self.cursor = IMDb()\n        self.top250 = self.cursor.get_top250_movies()\n\n    def __repr__(self):\n        num = int(random.randint(0, 249))\n        return str(f\"\\n\\n\\t{num}: {self.top250[num]}\\n\\n\")\n\n\nif __name__ == '__main__':\n    print(ChooseMovie())"
  },
  {
    "path": "Random Movie Selector/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Random Quotes Generator/quotes.py",
    "content": "from bs4 import BeautifulSoup\nimport requests\nimport csv\n\nurl='http://quotes.toscrape.com'\n\nhtml=requests.get(url)\nbs=BeautifulSoup(html.text,'html.parser')\n\ntry:\n    csv_file=open('quote_list.csv','w')\n    fieldnames=['quote','author','tags']\n    dictwriter=csv.DictWriter(csv_file,fieldnames=fieldnames)\n\n    dictwriter.writeheader()\n\n    while True:\n        for quote in bs.findAll('div',{'class':'quote'}):\n            text=quote.find('span',{'class':'text'}).text\n            author=quote.find('small',{'class':'author'}).text\n            tags=[]\n            for tag in quote.findAll('a',{'class':'tag'}):\n                tags.append(tag.text)\n            dictwriter.writerow({'quote':text,'author':author,'tags':tags})\n        \n        next=bs.find('li',{'class':'next'})\n        if not next: \n            break\n\n        html=requests.get(url+next.a.attrs['href'])\n        bs=BeautifulSoup(html.text,'html.parser')\nexcept:\n    print('Unknown Error!!!')\nfinally:\n    csv_file.close()\n"
  },
  {
    "path": "Random Quotes Generator/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Real-Time Cryptocurrency Price Tracker/Readme.md",
    "content": "# Cryptocurrency Price Tracker with CoinGecko API\n\n## Project Overview\n\nThe **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.\n\n## Features\n\n- **Real-Time Price Retrieval**: Input the name of a cryptocurrency (eg. bitcoin) to retrieve its current price in USD\n- **24-Hour Price Change**: Displays the 24-hour percentage change in price for the selected cryptocurrency\n- **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\n- **Data Visualization**: Uses matplotlib to generate a line chart displaying the historical price data\n\n\n## Technologies Used\n\n- **Python**: The core programming language used to build the script\n- **CoinGecko API**: A free API used to fetch cryptocurrency prices, percentage changes, and historical data\n- **Requests**: A Python library for making HTTP requests to the CoinGecko API\n- **Matplotlib**: A Python library used to visualize historical cryptocurrency price data in a line chart format\n- **Datetime**: Python datetime module is used to convert and handle timestamps when retrieving historical price data\n\n## Prerequisites\n\nBefore running the application, ensure you have the following:\n\n- [Python 3.x](https://www.python.org/downloads/) installed on your system\n- `requests` and `matplotlib` libraries are installed. Refer to `requirements.txt` for a specific version\n  \n"
  },
  {
    "path": "Real-Time Cryptocurrency Price Tracker/main.py",
    "content": "import requests\nimport matplotlib.pyplot as plt\nimport datetime\n\nCOINGECKO_API_URL = \"https://api.coingecko.com/api/v3\"\n\n\ndef get_crypto_price(crypto_symbol):\n    headers = {\"accept\": \"application/json\"}\n    response = requests.get(f\"{COINGECKO_API_URL}/simple/price\", params={\n        'ids': crypto_symbol,\n        'vs_currencies': 'usd',\n        'include_24hr_change': 'true'\n    }, headers=headers)\n\n    if response.status_code == 200:\n        data = response.json()\n        if crypto_symbol in data:\n            price = data[crypto_symbol]['usd']\n            change_percentage = data[crypto_symbol]['usd_24h_change']\n            return price, change_percentage\n        else:\n            raise ValueError(f\"Cryptocurrency '{crypto_symbol}' not found.\")\n    else:\n        raise Exception(f\"Failed to fetch data: {response.status_code} - {response.reason}\")\n\n\ndef get_historical_data(crypto_symbol, days):\n    response = requests.get(f\"{COINGECKO_API_URL}/coins/{crypto_symbol}/market_chart\", params={\n        'vs_currency': 'usd',\n        'days': days\n    })\n\n    if response.status_code == 200:\n        data = response.json()\n        if 'prices' in data:\n            return data['prices']  # Returns price data over the days\n        else:\n            raise ValueError(f\"No historical data available for '{crypto_symbol}'.\")\n    else:\n        raise Exception(f\"Failed to fetch historical data: {response.status_code} - {response.reason}\")\n\n\ndef plot_historical_data(historical_data, crypto_symbol):\n    dates = [datetime.datetime.fromtimestamp(item[0] / 1000) for item in historical_data]\n    prices = [item[1] for item in historical_data]\n\n    plt.figure(figsize=(10, 6))\n    plt.plot(dates, prices, marker='o', linestyle='-', color='b')\n    plt.title(f'Historical Price Data for {crypto_symbol.capitalize()}')\n    plt.xlabel('Date')\n    plt.ylabel('Price (USD)')\n    plt.xticks(rotation=45)\n    plt.grid(True)\n    plt.tight_layout()\n    plt.show()\n\n\ndef main():\n    crypto = input(\"Enter cryptocurrency symbol (eg. bitcoin, ethereum): \").lower()\n\n    try:\n        # Get real-time price and 24-hour change\n        price, change = get_crypto_price(crypto)\n        print(f\"Current price of {crypto}: ${price}\")\n        print(f\"24-hour change: {change:.2f}%\")\n    except ValueError as e:\n        print(f\"Error: {e}\")\n        return\n    except Exception as e:\n        print(f\"Error fetching price data: {e}\")\n        return\n\n    # Validate and get historical data\n    while True:\n        try:\n            days = int(input(\"Enter the number of days for historical data (eg. 1, 7, 30): \"))\n            if days <= 0:\n                raise ValueError(\"The number of days must be a positive integer.\")\n            break\n        except ValueError as e:\n            print(f\"Invalid input: {e}. Please enter a valid number.\")\n\n    try:\n        historical_data = get_historical_data(crypto, days)\n        print(\"Historical data retrieved successfully.\")\n        plot_historical_data(historical_data, crypto)\n    except ValueError as e:\n        print(f\"Error: {e}\")\n    except Exception as e:\n        print(f\"Error fetching historical data: {e}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "Real-Time Cryptocurrency Price Tracker/requirements.txt",
    "content": "requests==2.32.3\nmatplotlib==3.9.2"
  },
  {
    "path": "Real-Time Cryptocurrency Price Tracker/runtime.txt",
    "content": "python-3.9.20"
  },
  {
    "path": "Recipe Finder with Meal Planner/Readme.md",
    "content": "# Meal Planner with Spoonacular API\n\n## Project Overview\n\nThe **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.\n\n## Features\n\n- **Search Recipes by Ingredients**: Input the ingredients you have, and the app will find up to 10 recipes that include those ingredients.\n- **View Recipe Details**: Get detailed information about the selected recipes, including preparation time and servings.\n- **Plan Meals for the Week**: Generate a random meal plan for up to 7 days based on the available recipes.\n- **Interactive User Interface**: Provides a simple, interactive command-line interface for easy input and output.\n\n## Technologies Used\n\n- **Python**: Core programming language used to build the app.\n- **Spoonacular API**: API used for fetching recipes and detailed information about them.\n- **Requests**: Python library for making HTTP requests to the Spoonacular API.\n\n## Prerequisites\n\nBefore running the application, ensure you have the following:\n\n- [Python 3.x](https://www.python.org/downloads/) installed on your system.\n- `requests` library installed. You can install it using:\n  \n"
  },
  {
    "path": "Recipe Finder with Meal Planner/main.py",
    "content": "import requests\nimport random\n\n# Replace 'your_api_key_here' with your actual Spoonacular API key\nAPI_KEY = \"74de4b7826b74b70b4d3a0fe3191239a\"\nBASE_URL = \"https://api.spoonacular.com/recipes\"\n\ndef find_recipes(ingredients):\n    \"\"\"Search for recipes based on ingredients using the Spoonacular API.\"\"\"\n    url = f\"{BASE_URL}/findByIngredients\"\n    params = {\n        'ingredients': ','.join(ingredients),\n        'number': 10,  # Get up to 10 recipes\n        'apiKey': API_KEY\n    }\n    response = requests.get(url, params=params)\n    \n    if response.status_code == 200:\n        recipes = response.json()\n        return [(recipe['title'], recipe['id']) for recipe in recipes]\n    else:\n        print(f\"Error: {response.status_code}\")\n        return []\n\ndef get_recipe_details(recipe_id):\n    \"\"\"Get details of a specific recipe by its ID.\"\"\"\n    url = f\"{BASE_URL}/{recipe_id}/information\"\n    params = {'apiKey': API_KEY}\n    response = requests.get(url, params=params)\n\n    if response.status_code == 200:\n        return response.json()\n    else:\n        print(f\"Error: {response.status_code}\")\n        return None\n\ndef plan_meals(ingredients):\n    \"\"\"Plan meals for the week based on available ingredients.\"\"\"\n    recipes = find_recipes(ingredients)\n    \n    if not recipes:\n        return \"No recipes found with the given ingredients.\"\n\n    meals = random.sample(recipes, min(7, len(recipes)))\n    return meals\n\ndef user_interface():\n    print(\"Welcome to the Meal Planner!\")\n    print(\"Enter the ingredients you have, separated by commas:\")\n    \n    ingredients = input().split(\",\")\n    ingredients = [ingredient.strip().lower() for ingredient in ingredients]\n\n    print(\"\\nSearching for recipes based on your ingredients...\\n\")\n    recipes = find_recipes(ingredients)\n\n    if recipes:\n        print(f\"Found the following recipes with your ingredients:\")\n        for i, (title, _) in enumerate(recipes):\n            print(f\"{i + 1}. {title}\")\n    else:\n        print(\"No recipes found with the given ingredients.\")\n\n    print(\"\\nDo you want to plan meals for the week with these ingredients? (yes/no)\")\n    if input().strip().lower() == \"yes\":\n        meals = plan_meals(ingredients)\n        print(\"\\nHere is your meal plan for the week:\")\n        for i, (title, recipe_id) in enumerate(meals, 1):\n            print(f\"Day {i}: {title}\")\n            recipe_details = get_recipe_details(recipe_id)\n            if recipe_details:\n                print(f\"  - Ready in: {recipe_details['readyInMinutes']} minutes\")\n                print(f\"  - Servings: {recipe_details['servings']}\")\n    else:\n        print(\"No meal plan generated.\")\n\nif __name__ == \"__main__\":\n    user_interface()\n"
  },
  {
    "path": "Recipe Finder with Meal Planner/runtime.txt",
    "content": "python-3.9.18\n"
  },
  {
    "path": "Resume Builder/README.md",
    "content": "# Interactive Resume Builder\n\nThis 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.\n\n## Features\n\n- Interactive CLI for entering resume data (contact info, work experience, education, etc.).\n- Ability to add, update, and modify multiple resume sections.\n- Automatically generates a well-formatted PDF resume.\n- Includes functionality to add detailed descriptions for work experience and projects.\n- Supports multiple certifications and achievements.\n- Simple and intuitive navigation using `prompt_toolkit` for menu interactions.\n\n## Prerequisites\n\n- Python 3.x must be installed on your system.\n\n## Setup Instructions\n\n1. **Clone the repository**:\n    ```bash\n    git clone https://github.com/username/your-repo.git\n    cd your-repo\n    ```\n\n2. **Create and activate a virtual environment**:\n\n    For macOS/Linux:\n    ```bash\n    python3 -m venv venv\n    source venv/bin/activate\n    ```\n\n    For Windows:\n    ```bash\n    python -m venv venv\n    venv\\Scripts\\activate\n    ```\n\n3. **Install the necessary dependencies**:\n    ```bash\n    pip install -r requirements.txt\n    ```\n\n4. **Run the application**:\n    ```bash\n    python resume_builder.py\n    ```\n\n## Usage\n\n- **Interactive Menu**: The program presents a menu to select which section of the resume you want to edit or add.\n- **PDF Generation**: Once all sections are filled, you can generate a PDF with all the input data.\n- **Options**:\n    - Add or edit Contact Information, Work Experience, Education, Skills, Projects, Certifications, and Achievements.\n    - Generate the PDF after completing the resume input.\n\n## Dependencies\n\n- `geopy`: For any geographic distance calculation (if needed for future features).\n- `prompt_toolkit`: A library for building beautiful command-line applications.\n- `fpdf`: A library for generating PDF documents from the entered resume data.\n\n## License\n\nThis project is licensed under the MIT License.\n"
  },
  {
    "path": "Resume Builder/requirements.txt",
    "content": "geopy==2.2.0\nprompt_toolkit==3.0.8\nfpdf==1.7.2\n"
  },
  {
    "path": "Resume Builder/resume_builder.py",
    "content": "from prompt_toolkit import prompt\nfrom prompt_toolkit.shortcuts import button_dialog\nfrom fpdf import FPDF\nimport os\n\n# To clear the terminal after selecting a section\ndef clear_screen():\n    os.system('cls' if os.name == 'nt' else 'clear')\n\n# Resume data storage\nresume_data = {\n    \"contact_info\": {},\n    \"experience\": [],\n    \"education\": [],\n    \"skills\": [],\n    \"projects\": [],\n    \"certifications\": [],\n    \"achievements\": []\n}\n\n# Function to navigate back to the main menu\ndef back_to_menu():\n    print(\"\\nReturning to main menu...\")\n\n# Add contact information\ndef add_contact_info():\n    clear_screen()\n    print(\"Enter Contact Information\")\n    resume_data[\"contact_info\"][\"name\"] = prompt(\"Name: \")\n    resume_data[\"contact_info\"][\"email\"] = prompt(\"Email: \")\n    resume_data[\"contact_info\"][\"phone\"] = prompt(\"Phone: \")\n    resume_data[\"contact_info\"][\"address\"] = prompt(\"Address: \")\n    resume_data[\"contact_info\"][\"linkedin\"] = prompt(\"LinkedIn URL: \")\n    resume_data[\"contact_info\"][\"github\"] = prompt(\"GitHub URL: \")\n    back_to_menu()\n\n# Add work experience\ndef add_experience():\n    while True:\n        clear_screen()\n        print(\"Enter Work Experience\")\n        experience = {\n            \"title\": prompt(\"Job Title: \"),\n            \"company\": prompt(\"Company: \"),\n            \"start_date\": prompt(\"Start Date (e.g., June 2024): \"),\n            \"end_date\": prompt(\"End Date (or type 'Present' if still working): \"),\n            \"details\": prompt(\"Details (comma-separated): \").split(',')\n        }\n        resume_data[\"experience\"].append(experience)\n\n        # Ask user if they want to add more experience entries\n        more = prompt(\"Do you want to add more work experience? (yes/no): \").strip().lower()\n        if more == \"no\":\n            break\n    back_to_menu()\n\n# Add education details\ndef add_education():\n    while True:\n        clear_screen()\n        print(\"Enter Education Information\")\n        education = {\n            \"degree\": prompt(\"Degree (e.g., B.Tech in CSE): \"),\n            \"institution\": prompt(\"Institution: \"),\n            \"start_year\": prompt(\"Start Year: \"),\n            \"end_year\": prompt(\"End Year: \")\n        }\n        resume_data[\"education\"].append(education)\n\n        # Ask user if they want to add more education entries\n        more = prompt(\"Do you want to add more education? (yes/no): \").strip().lower()\n        if more == \"no\":\n            break\n    back_to_menu()\n\n# Add skills\ndef add_skills():\n    clear_screen()\n    print(\"Enter Skills (comma-separated): \")\n    resume_data[\"skills\"] = prompt(\"Skills: \").split(',')\n    back_to_menu()\n\n# Add projects\ndef add_projects():\n    while True:\n        clear_screen()\n        print(\"Enter Projects Information\")\n        project = {\n            \"name\": prompt(\"Project Name: \"),\n            \"description\": prompt(\"Description: \"),\n            \"technologies\": prompt(\"Technologies Used: \")\n        }\n        resume_data[\"projects\"].append(project)\n\n        # Ask if they want to add more projects\n        more = prompt(\"Do you want to add more projects? (yes/no): \").strip().lower()\n        if more == \"no\":\n            break\n    back_to_menu()\n\n# Add certifications\ndef add_certifications():\n    while True:\n        clear_screen()\n        print(\"Enter Certifications\")\n        certification = {\n            \"name\": prompt(\"Certification Name: \"),\n            \"provider\": prompt(\"Provider: \"),\n            \"year\": prompt(\"Year: \")\n        }\n        resume_data[\"certifications\"].append(certification)\n\n        more = prompt(\"Do you want to add more certifications? (yes/no): \").strip().lower()\n        if more == \"no\":\n            break\n    back_to_menu()\n\n# Add achievements\ndef add_achievements():\n    while True:\n        clear_screen()\n        print(\"Enter Achievements\")\n        achievement = prompt(\"Achievement: \")\n        resume_data[\"achievements\"].append(achievement)\n\n        more = prompt(\"Do you want to add more achievements? (yes/no): \").strip().lower()\n        if more == \"no\":\n            break\n    back_to_menu()\n\n# PDF Generation class\nclass ResumePDF(FPDF):\n    def header(self):\n        self.set_font('Arial', 'B', 14)\n        self.cell(0, 10, resume_data[\"contact_info\"][\"name\"], 0, 1, 'C')\n        self.set_font('Arial', 'I', 12)\n        self.cell(0, 10, resume_data[\"contact_info\"][\"email\"], 0, 1, 'C')\n        self.cell(0, 10, resume_data[\"contact_info\"][\"phone\"], 0, 1, 'C')\n        self.cell(0, 10, resume_data[\"contact_info\"][\"address\"], 0, 1, 'C')\n\n    def add_section(self, title, content):\n        self.set_font('Arial', 'B', 12)\n        self.cell(0, 10, title, 0, 1)\n        self.set_font('Arial', '', 11)\n        for line in content:\n            self.cell(0, 10, line, 0, 1)\n\n# PDF Generation\ndef generate_pdf():\n    pdf = ResumePDF()\n    pdf.add_page()\n\n    # Contact Information\n    contact = resume_data[\"contact_info\"]\n    pdf.set_font('Arial', 'B', 12)\n    pdf.cell(0, 10, f\"{contact['name']} - {contact['email']}\", 0, 1)\n    pdf.cell(0, 10, f\"Phone: {contact['phone']} - Address: {contact['address']}\", 0, 1)\n    pdf.cell(0, 10, f\"LinkedIn: {contact.get('linkedin', 'N/A')} - GitHub: {contact.get('github', 'N/A')}\", 0, 1)\n\n    # Work Experience\n    pdf.set_font('Arial', 'B', 12)\n    pdf.cell(0, 10, \"Experience\", 0, 1)\n    pdf.set_font('Arial', '', 11)\n    for exp in resume_data[\"experience\"]:\n        details = ', '.join(exp[\"details\"])\n        pdf.cell(0, 10, f\"{exp['title']} at {exp['company']} ({exp['start_date']} - {exp['end_date']})\", 0, 1)\n        pdf.multi_cell(0, 10, f\"Responsibilities: {details}\")\n\n    # Education\n    pdf.set_font('Arial', 'B', 12)\n    pdf.cell(0, 10, \"Education\", 0, 1)\n    pdf.set_font('Arial', '', 11)\n    for edu in resume_data[\"education\"]:\n        pdf.cell(0, 10, f\"{edu['degree']} from {edu['institution']} ({edu['start_year']} - {edu['end_year']})\", 0, 1)\n\n    # Skills\n    pdf.set_font('Arial', 'B', 12)\n    pdf.cell(0, 10, \"Skills\", 0, 1)\n    pdf.multi_cell(0, 10, ', '.join(resume_data[\"skills\"]))\n\n    # Projects\n    pdf.set_font('Arial', 'B', 12)\n    pdf.cell(0, 10, \"Projects\", 0, 1)\n    pdf.set_font('Arial', '', 11)\n    for proj in resume_data[\"projects\"]:\n        pdf.cell(0, 10, proj[\"name\"], 0, 1)\n        pdf.multi_cell(0, 10, proj[\"description\"])\n        pdf.cell(0, 10, f\"Technologies Used: {proj['technologies']}\", 0, 1)\n\n    # Certifications\n    pdf.set_font('Arial', 'B', 12)\n    pdf.cell(0, 10, \"Certifications\", 0, 1)\n    pdf.set_font('Arial', '', 11)\n    for cert in resume_data[\"certifications\"]:\n        pdf.cell(0, 10, f\"{cert['name']} by {cert['provider']} ({cert['year']})\", 0, 1)\n\n    # Achievements\n    pdf.set_font('Arial', 'B', 12)\n    pdf.cell(0, 10, \"Achievements\", 0, 1)\n    pdf.set_font('Arial', '', 11)\n    for ach in resume_data[\"achievements\"]:\n        pdf.cell(0, 10, ach, 0, 1)\n\n    # Save PDF\n    pdf_output_path = \"generated_resume.pdf\"\n    pdf.output(pdf_output_path)\n\n    # Auto-open PDF after generation\n    os.system(f\"start {pdf_output_path}\" if os.name == \"nt\" else f\"open {pdf_output_path}\")\n    print(f\"Resume generated: {pdf_output_path}\")\n\n# Main Menu using button_dialog from prompt_toolkit\ndef interactive_menu():\n    while True:\n        clear_screen()\n        choice = button_dialog(\n            title=\"Interactive Resume Builder\",\n            text=\"Please choose a section to modify:\",\n            buttons=[\n                (\"Contact Info\", 1),\n                (\"Work Experience\", 2),\n                (\"Education\", 3),\n                (\"Skills\", 4),\n                (\"Projects\", 5),\n                (\"Certifications\", 6),\n                (\"Achievements\", 7),\n                (\"Generate PDF\", 8),\n                (\"Exit\", 9)\n            ]\n        ).run()\n\n        if choice == 1:\n            add_contact_info()\n        elif choice == 2:\n            add_experience()\n        elif choice == 3:\n            add_education()\n        elif choice == 4:\n            add_skills()\n        elif choice == 5:\n            add_projects()\n        elif choice == 6:\n            add_certifications()\n        elif choice == 7:\n            add_achievements()\n        elif choice == 8:\n            generate_pdf()\n        elif choice == 9:\n            break\n\n# Start the program\nif __name__ == \"__main__\":\n    interactive_menu()\n"
  },
  {
    "path": "Simple Assistant/assistant.py",
    "content": "import pyttsx3,datetime,os,random,requests\nimport wikipedia,webbrowser,sys,pywhatkit\nimport speech_recognition as sr \n\n\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty(\"voices\")\nengine.setProperty('voice',voices[1].id)\n\n\n# To convdert text into voice\ndef speak(audio):\n    engine.say(audio)\n    print(audio)\n    engine.runAndWait()\n\n# To convert voice into text\ndef takecommand():\n    r = sr.Recognizer()\n    with sr.Microphone() as source:\n        print(\"Listening...\")\n        r.pause_threshold = 1\n        audio = r.listen(source,timeout=2,phrase_time_limit=5)\n        \n    try:\n        print(\"Recognizing...\")\n        query = r.recognize_google(audio,language='en-in')\n    except Exception:\n        speak(\"Can you please say that again ... \")\n        return 'none'\n    return query\n\n# To wish\ndef wish():\n    hour = int(datetime.datetime.now().hour)\n    if hour >=0 and hour<=12:\n        speak(\"Good morning Sir\")\n    elif hour>12 and hour<16:\n        speak(\"Good afternoon Sir\")\n    elif hour>16 and hour<22:\n        speak(\"Good evening Sir\")\n    speak(\"I am jarvis, Please tell me how can i help you !\")\n\n\nif __name__ == \"__main__\":\n    wish()\n    if 1:\n        query = takecommand().lower()\n\n        if 'open notepad' in query:\n            npath = 'C:\\\\Windows\\\\System32\\\\notepad.exe'\n            os.startfile(npath)\n            speak(\"Please wait ! While I am opening notepad for you!\")\n\n        elif \"open cmd\" in query:\n            os.system('start cmd')\n            speak(\"Opening Command Promte\")\n\n        elif \"play music\" in query:\n            music_dir = 'D:\\\\Songs'\n            songs = os.listdir(music_dir)\n            rd = random.choice(songs)\n            os.startfile(os.path.join(music_dir,rd))\n            speak(\"Playing Music\")\n\n        elif \"ip address\" in query:\n            ip = requests.get(\"https://api.ipify.org\").text\n            speak(f\"Your Ip address is {ip}\")\n\n        elif 'wikipedia' in query:\n            speak(\"Searching in wikipedia\")\n            query = query.replace(\"wikipedia\",\"\")\n            results = wikipedia.summary(query,sentences=5)\n            speak(f\"according to wikipedia {results}\")\n        \n        elif \"open youtube\" in query:\n            webbrowser.open('www.youtube.com/')\n\n        elif \"open instagram\" in query:\n            webbrowser.open('www.instagram.com/')\n\n        elif \"open facebook\" in query:\n            webbrowser.open('www.facebook.com/')\n\n        elif \"open twitter\" in query:\n            webbrowser.open('www.twitter.com/')\n\n        elif \"open google\" in query:\n            speak('Sir what should i search on google ! ')\n            varg = takecommand().lower()\n            webbrowser.open(varg)\n\n        # elif 'send message' in query:\n        #     pywhatkit.sendwhatmsg(\"+919988776655\",'Hello I am Jarvis ! How are you Sir ?',18,33,10,True)\n\n        # elif 'play song on youtube' in query:\n        #     speak(\"Which song would you like to play on youtube ? \")\n        #     song = takecommand().lower()\n        #     pywhatkit.playonyt(song)\n\n        # elif 'play video' in query:\n        #     speak(\"Which video would you like to play on youtube ? \")\n        #     vsong = takecommand().lower()\n        #     pywhatkit.playonyt(vsong)\n\n\n        elif 'nothing' in query or 'abort' in query or 'stop' in query:\n            speak('okay')\n            speak('Bye Sir, have a good day.')\n            sys.exit()\n           \n        elif 'hello' in query:\n            speak('Hello Sir')\n\n        elif 'bye' in query:\n            speak('Bye Sir, have a good day.')\n            sys.exit()\n\n        \n        elif \"what\\'s up\" in query or 'how are you' in query:\n            stMsgs = ['Just doing my thing!', 'I am fine!', 'Nice!', 'I am nice and full of energy']\n            speak(random.choice(stMsgs))\n\n"
  },
  {
    "path": "Simple Assistant/raj_mistry01/Readme.md",
    "content": "# Jarvis - A Personal Voice Assistant 🗣️💻\n\nThis **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.\n\n## 🚀 Features\n\n1. **Voice & Text Interaction**  \n   - Provides **voice recognition** using Google Speech Recognition API.\n   - Users can **switch to text mode** if speech recognition fails.\n   \n2. **Application Management**  \n   - Open or close **Notepad** and **Command Prompt**.\n   - Manage system **battery levels** with alerts and suggestions.\n\n3. **Information Retrieval**  \n   - Get **Wikipedia summaries** for any topic.\n   - **Weather forecasts** by city or location-based.\n   - Check your **IP address** using an online API.\n\n4. **Entertainment & Media**  \n   - Search for **movie details** via IMDb, including cast, plot, and ratings.\n   - Open **YouTube** and automate subscriptions.\n\n5. **System Control**  \n   - Adjust **volume controls**: Increase, decrease, or mute.\n   - Minimize or maximize windows using **keyboard automation**.\n   - Track **internet speed** with Speedtest integration.\n\n6. **Utility Features**  \n   - Control **Webcam** access and capture videos.\n   - Perform calculations using **Wolfram Alpha**.\n   - Automatically **open websites** using Chrome.\n   - Monitor **system processes** and terminate them on command.\n\n---\n\n## 🔧 Setup Instructions\n\n1. **Clone the Repository**\n   ```bash\n   git clone https://github.com/yourusername/jarvis-assistant.git\n   cd jarvis-assistant\n   ```\n\n2. **Install Dependencies**  \n   Install all necessary Python packages using:\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n3. **Add Paths for Applications**\n   Set the paths for:\n   - **Chrome browser**: `\"C:/Program Files/Google/Chrome/Application/chrome.exe\"`\n   - **Notepad**: `\"C:/Windows/System32/notepad.exe\"`\n   - **Visual Studio Code** (optional): Adjust the path as per your installation.\n\n4. **Get API Keys**\n   - **OpenWeather API**: [Sign up here](https://openweathermap.org/) and replace `apiKey` in the code.\n   - **Wolfram Alpha API**: Get an API key [here](https://products.wolframalpha.com/api/).\n\n---\n\n## 🧑‍💻 Usage Instructions\n\n1. **Launch the Assistant**  \n   Run the script:\n   ```bash\n   python jarvis.py\n   ```\n\n2. **Speak Commands**:\n   - \"Open Notepad\" – Launches Notepad.\n   - \"What is the weather report?\" – Gives the weather of your current location.\n   - \"Search for Titanic on Wikipedia\" – Provides a brief Wikipedia summary.\n   - \"Close Command Prompt\" – Terminates the Command Prompt if running.\n   - \"What's my IP address?\" – Provides your public IP address.\n\n3. **Text Mode**  \n   If the voice input isn't recognized, type your queries when prompted.\n\n4. **Pause or Stop Listening**:\n   - Say **\"Stop listening\"**: Pauses the assistant.\n   - Resume by pressing **Ctrl + Alt + K**.\n   - Say **\"No query, thanks\"** to exit the assistant.\n\n---\n\n## 🌦️ Example Queries\n\n- **\"How are you, Jarvis?\"**  \n  → Jarvis responds and continues the conversation.\n\n- **\"Open Command Prompt\"**  \n  → Opens the Command Prompt window.\n\n- **\"Mute the volume\"**  \n  → Mutes system volume.\n\n---\n\n## 🎯 Known Issues and Limitations\n\n- Some queries require accurate phrasing.\n- Voice recognition may fail in noisy environments.\n- Web automation depends on having Chrome installed.\n- Weather reports return temperature in **Kelvin** by default (can be adjusted).\n\n---\n\n## 💡 Future Improvements\n\n- Add **Gmail** integration to send emails.\n- Support for **natural conversations** with chat history.\n- **Alarm feature** implementation.\n\n---\n\n## 🤖 Contribution\n\nFeel free to submit pull requests or report bugs/issues. Contributions are welcome to make this assistant smarter and more responsive!\n\n---\n\n\n## 🛠️ Prerequisites\n\n- **Python 3.7+**\n- Required Packages (install via `pip`):\n  ```bash\n  pip install -r requirements.txt\n\n---\n## 🛠️ Api Credits\n\n    Wolfram Api\n    OpenWheather Api\n\n\n- **Python 3.7+**\n- Required Packages (install via `pip`):\n  ```bash\n  pip install -r requirements.txt\n\nEnjoy using **Jarvis Personal Assistant**! 😊\n"
  },
  {
    "path": "Simple Assistant/raj_mistry01/main.py",
    "content": "import pyttsx3\nimport wmi\nimport speech_recognition as sr\nimport datetime\nimport wolframalpha\nimport subprocess as sp\nimport time\nimport pyautogui \nimport webbrowser as web\nimport random\nimport imdb\nimport psutil\nimport requests\nimport wikipedia\nimport pywhatkit\nimport smtplib\nimport sys\nimport keyboard\nimport speedtest\nimport cv2\nimport os\nimport numpy as np\nengine = pyttsx3.init('sapi5')\nvoices = engine.getProperty(\"voices\")\nengine.setProperty('voices',voices[0].id)\nrunnigprocesslist = []\nf = wmi.WMI()\nflag = 0 \ndef speak(audio) :\n    print(\"Jarvis : \",end=\"\")\n    engine.say(audio)\n    print(audio)\n    engine.runAndWait()\ndef takecommand() :\n    r = sr.Recognizer()\n    with sr.Microphone() as source :\n        print(\"Listening ...\")\n        r.adjust_for_ambient_noise(source)\n        r.pause_threshold =1 \n        audio = r.listen(source,phrase_time_limit=5)\n    try :\n        print(\"Recongnizing ..\")\n        text = r.recognize_google(audio,language = \"en-in\")\n        print(\"User said : \"+text)\n    except Exception as e :\n        print(\"Say that again : \")\n        return \"none\"\n    return text\ndef startlistening():\n    print(\"Started Listening : \")\n\ndef pauseListening() :\n    print(\"Paused Listening :\")\n\ndef weatherforecast(city) :\n    apiKey = \"apiKey\"\n    res = requests.get(f\"openWeatherApiEndpoint\").json()\n    weather_ = res[\"weather\"][0][\"main\"]\n    temp = res[\"main\"][\"temp\"]\n    feels_like = res[\"main\"][\"feels_like\"]\n    return weather_,temp,feels_like\n\ndef wish() :\n    hour = int(datetime.datetime.now().hour)\n    if hour >= 0 and hour <= 12 :\n        speak(\"Good morning :\")\n    elif hour > 12 and hour <= 18 :\n        speak(\"Good afternoon :\")\n    else :\n        speak(\"Good evening : \")\n    speak(\"I am jarvis ,sir  how can I assist you?\")\n# def sendEmail(to,content) :\n#     server = smtplib.SMTP(\"smtp.gmail.com\",587)\n#     server.ehlo()\n#     server.starttls()\n#     server.login(\"emailId\",\"yourpswd\")\n#     server.sendmail(\"emailId\",\"toemail\")\n#     server.close()\nif __name__ == \"__main__\" :\n    wish()\n    def main() :\n        global runnigprocesslist\n        tries = 0\n        query = \"\"\n        flag_ = 0\n        flagForText = 0\n        while True:\n            if tries < 3 :\n                if flag_ == 0 : \n                    query = takecommand().lower()\n                    tries += 1\n                else :\n                    if flagForText == 1: \n                        query  = input(\"(Prees V + Enter to turn voice chat again)Enter your query in text : \")\n                        if query == \"V\" :\n                            flag_  = 0\n                            flagForText = 0\n                            pass\n                        else :\n                            pass\n                    else : \n                        flag_ = 0\n                        pass\n                if \"stop listening\" in query :\n                    pauseListening()\n                    speak(\"Press ctrl+alt+k to continue listening.\")\n                    break\n                elif \"open notepad\" in query :\n                    tries = 0\n                    path = \"\" # path to notepad\n                    speak(\"Opening NOtepad sir.\")\n                    os.startfile(path)\n                elif \"close notepad\" in query :\n                    tries = 0\n                    for process in f.Win32_Process() :\n                        runnigprocesslist.append(process.Name)\n                    if \"Notepad.exe\" in runnigprocesslist :\n                        speak(\"Closing the notepad.\")\n                        os.system(\"taskkill /f /im notepad.exe\")\n                        flag = 1 \n                        runnigprocesslist = []\n                    else :\n                        speak(\"Notepad is not opened.\")\n                elif \"stop listening\" in query :\n                    tries = 0\n                    speak(\"Press ctrl+alt+p to pause the listening\")\n                elif \"how are you jarvis\" in query :\n                    tries = 0\n                    speak(\"I am fine sir , What about you ?? Sir.\")\n                    query = takecommand().lower()\n                    if \"not feeling good\" or \"sad\" or \"bad day\" in query :\n                        speak(\"What happend sir ,Please Tell me , May I help you ?\")\n                        query =  takecommand().lower()\n                        if \"disease\" in query :\n                            query = query.replace(query,\"drreddys.com\",1)\n                            path = \"\" # path to chrome\n                            web.register(\"chrome\",None,web.BackgroundBrowser(path))\n                            web.get(\"chrome\").open_new(query)\n                        else :\n                            pass\n                    elif \"good\" or \"feeling happy\" in query :\n                        speak(\"Ok sir , It seems to be nice to hear.\")\n                elif \"open command prompt\" in query :\n                    tries = 0\n                    speak(\"Opening the command propmpt.\")\n                    os.system(\"start cmd\")\n                elif \"close command prompt\" in query :\n                    tries = 0 \n                    for process in f.Win32_Process() :\n                        runnigprocesslist.append(process.Name)\n                    if \"cmd.exe\" in runnigprocesslist :\n                        speak(\"Closing the command propmt.\")\n                        os.system(\"taskkill /f /im cmd.exe\")\n                        flag = 1 \n                        runnigprocesslist = []\n                    else :\n                        speak(\"CMD is not opened.\")\n                    pass\n                elif \"clear the chat\" in query :\n                    tries = 0\n                    os.system(\"cls\")\n                elif \"are you forget to wish me\" in query or \"Wish me again\" in query :\n                    tries = 0\n                    wish()\n                elif \"open Webcamera\" in query :\n                    tries = 0\n                    cap = cv2.VideoCapture(0)\n                    while True :\n                        ret , img = cap.read()\n                        cv2.imshow(\"webcam\",img)\n                        k = cv2.waitKey(50)\n                        if k == 27 :\n                            break\n                    cap.release()\n                    cv2.destroyAllWindows()\n                elif \"open camera\" in query :\n                    tries = 0\n                    speak(\"Opening Camera sir\")\n                    sp.run(\"start microsoft.windows.camera:\",shell= True)\n                elif \"close camera\" in query :\n                    tries = 0\n                    for process in f.Win32_Process() :\n                        runnigprocesslist.append(process.Name)\n                    if \"WindowsCamera.exe\" in runnigprocesslist :\n                        speak(\"Closing the camera.\")\n                        flag = 1 \n                        os.system(\"taskkill /f /im WindowsCamera.exe\")\n                        runnigprocesslist = []\n                    else :\n                        speak(\"Camera is not opened.\")\n                elif \"calculate\" in query :\n                    # api = \"apiKey\"\n                    client = wolframalpha.Client(api)\n                    query = takecommand().lower()\n                    ind  = query.split().index(\"calculate\")\n                    text = query.split()[ind+1:]\n                    result = client.query(\" \".join(text))\n                    try :\n                        ans = next(result.results).text\n                        speak(\"The answer is \" + ans)\n                    except StopIteration :\n                        speak(\"I could not find it , Please say it again.\")\n                elif \"ip address\" in query :\n                    tries = 0\n                    ip = requests.get(\"apiKeyOfipyfyConfig\").json()\n                    speak(\"Your Ip address is : \" + ip[\"ip\"])\n                elif \"wikipedia\" in query :\n                    tries = 0\n                    speak(\"Searching in the wikipedia\")\n                    query = query.replace(\"wikipedia\",\"\")\n                    results = wikipedia.summary(query,sentences=2)\n                    speak(\"According to wikipedia \")\n                    speak(results)\n                    print(results)\n                elif \"open visual code\" in query :\n                    tries = 0\n                    path = \"\" # path to Vscode.exe\n                    os.startfile(path)\n                elif \"weather report\" in query :\n                    tries = 0\n                    ipAdd = requests.get(\"apiKeyOfipyfyConfig\").json()\n                    ipnum = ipAdd[\"ip\"]\n                    city = requests.get(f\"apiKeyOfipyfyConfigEndpoint\").text\n                    weather , temp , feels_like = weatherforecast(city)\n                    speak(f\"The weather report talks about {weather}.\")\n                    speak(f\"The temparature is {temp} kelvin.\")\n                    speak(f\"It feels like {feels_like} kelvin.\")\n                elif \"weather of my city\" in query :\n                    tries = 0\n                    speak(\"Sir tell me your city name : \")\n                    city  =  input(\"Enter the name of your city : \")\n                    speak(f\"Getting the weather of {city} : \")\n                    weather , temp , feels_like = weatherforecast(city)\n                    speak(f\"The weather report talks about {weather}.\")\n                    speak(f\"The temparature is {temp} kelvin.\")\n                    speak(f\"It feels like {feels_like} kelvin.\")\n                elif \".com\" in query:\n                    tries = 0\n                    path = \"\" # path to chrome\n                    web.register(\"chrome\",None,web.BackgroundBrowser(path))\n                    web.get(\"chrome\").open_new(query)\n                elif \"movie\" in query :\n                    movieDb = imdb.IMDb()\n                    speak(\"Input the name of movie in text\")\n                    movieName = input(\"Enter the name : \")\n                    movies = movieDb.search_movie(movieName)\n                    speak(\"Searching for... \" + movieName)\n                    speak(\"I found these\")\n                    for movie in movies :\n                        title = movie[\"title\"]\n                        year = movie[\"year\"]\n                        info = movie.getID()\n                        movieInfo = movieDb.get_movie(info)\n                        rating = movieInfo[\"rating\"]\n                        cast = movieInfo[\"cast\"]\n                        actor = cast[0:5]\n                        plot = movieInfo.get('plot outline','plot summary not available')\n                        speak(f\"{title} movie in {year} has an imdb rating of {rating}.\")\n                        speak(f\"It has a cast of {actor} . The plot of the movie is {plot}. \")\n                # elif \"send message\" in query:\n                #     tries = 0\n                #     pywhatkit.sendwhatmsg(\"tosendPhoneNum\",\"Hi raj\",2,25)\n                # elif \"email\" in query :\n                #     tries = 0\n                #     try :\n                #         speak(\"What should i say\")\n                #         content = takecommand().lower()\n                #         to = \"toEmailId\"\n                #         sendEmail(to,content)\n                #     except Exception as e :\n                #         print(e)\n                elif \"how much battery is left\" in query or \"power is left\" in query or \"battery\" in query : \n                    tries = 0\n                    battery = psutil.sensors_battery()\n                    percentage = battery.percent\n                    speak(f\"Sir your computer system has left {percentage}% battery power.\")\n                    if percentage <= 15 : \n                        speak(\"Sir you should plug in charger.\")\n                    elif percentage >=15 and percentage <= 35 :\n                        speak(\"Sir it is enough power to run on , but it is advisable to turn on battery saver made.\")\n                        speak(\"Sir Would you like to turn on battery saver mode?\")\n                        query = takecommand().lower()\n                        if \"yes\" in query : \n                            pyautogui.press(\"win+A\")\n                        else : \n                            pass\n                    elif percentage >= 35 and percentage <= 60 :\n                        speak(\"Sir you should we have enough battery power.\") \n                elif \"turn on chat mode\" in query or \"chat mode\" in query or \"chat\" in query:\n                    tries = 0\n                    flag_ = 1\n                    flagForText = 1\n                elif \"subscribe the coder\" in query or \"subscribe\" in query:\n                    tries = 0\n                    speak(\"Whoever using this my created basic voice assistant jarvis , I am thankful , Subscribe to my channel\")\n                    speak(\"Firstly go to Youtube\")\n                    path = \"pathtoChrome``\" # path to chrome\n                    web.register(\"chrome\",None,web.BackgroundBrowser(path))\n                    web.get(\"chrome\").open_new(\"https://www.youtube.com/\")\n                    speak(\"Click on the search bar\")\n                    pyautogui.moveTo(517,78,1)\n                    pyautogui.click(x=517,y=78,clicks=1,interval=0,button='left')\n                    speak(\"raj_mistry01 is username.\")\n                    pyautogui.typewrite(\"https://www.youtube.com/@raj_mistry01\",0.1)\n                    time.sleep(1)\n                    speak(\"Press Enter\")\n                    pyautogui.press(\"enter\")\n                    speak(\"Here you will subscribe the channel.\")\n                    pyautogui.moveTo(718,602,1)\n                    speak(\"Click here to subcribe\")\n                    pyautogui.click(x=718,y=602,clicks=1,interval=0,button='left')\n                    speak(\"Thank you for the subscribing Me🙏\")\n                elif \"volume up\" in query : \n                    tries = 0\n                    pyautogui.press(\"volumeup\")\n                elif \"volume down\" in query : \n                    tries = 0\n                    pyautogui.press(\"volumedown\")\n                elif \"mute the volume\" in query : \n                    tries = 0\n                    pyautogui.press(\"volumemute\")\n                elif \"turn on the volume\" in query :\n                    tries = 0\n                    pyautogui.press(\"volumemute\")\n                elif \"minimise the window\" in query: \n                    tries = 0\n                    pyautogui.moveTo(1774,32,2)\n                    pyautogui.click(1774,32)\n                elif \"maximize the window\" in query  :\n                    tries = 0\n                    pyautogui.moveTo(763,1054,2)\n                    pyautogui.click(763,1054)\n                elif \"internet speed\" in query : \n                    tries = 0 \n                    st = speedtest.Speedtest()\n                    download = st.download()\n                    up = st.upload()\n                    speak(f\"Sir we have {download} bits downloading speed per second and {up} bits downloading speed per second.\")\n                elif \"no query thanks\" in query :\n                    tries = 0\n                    speak(\"Thanks for using me sir , have a good day.\")\n                    sys.exit()\n                elif \"alarm\" in query or \"set alarm\" in query :\n                    pass\n                speak(\"Sir do you have any other work : \")\n            else :\n                speak(\"Sir I am unable to recognize the speech.\")\n                speak(\"Sir it is better to write query in text.\")\n                query = input(\"Enter the query : \")\n                query = query.lower()\n                tries = 0\n                flag_ = 1 \n                flagForText = 0 \nmain()"
  },
  {
    "path": "Simple Assistant/raj_mistry01/requirements.txt",
    "content": "pyttsx3\nwmi\nSpeechRecognition\nwolframalpha\nnumpy\npyautogui\nrequests\nwikipedia-api\npywhatkit\nsmtplib3\npsutil\nkeyboard\nspeedtest-cli\nopencv-python\nimdbpy"
  },
  {
    "path": "Simple Assistant/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Snake-Game/README.md",
    "content": "# Snake Game 🐍\n\nA 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.\n\n## Features\n- Interactive gameplay.\n- Score tracking.\n- Simple and user-friendly interface.\n\n## Installation\n1. Clone this repository:\n   ```bash\n   git clone <your-repository-url>\n2. Navigate the project folder\n   ```bash\n   cd snake-game\n3. Run the game\n   ```bash\n   python snake_game.py\n   \n# How to Play\n1. Use Arrow Keys to control the direction of the snake:\n   1. Up: Move up.\n   2. Down: Move down.\n   3. Left: Move left.\n   4. Right: Move right.\n2. Collect food to increase your score.\n3. Avoid colliding with:\n   1. Walls\n   2. The snake’s body.\n4. Goal: Achieve the highest score possible!\n\n# Technologies Used\nPython\n\n"
  },
  {
    "path": "Snake-Game/Snake.py",
    "content": "from turtle import Turtle, Screen\nSTARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]\nMOVE_DISTANCE = 20\nUP = 90\nDOWN = 270\nRIGHT = 0\nLEFT = 180\n\n\nclass Snake:\n    def __init__(self):\n        self.segments = []\n        self.x = 0\n        self.create_snake()\n        self.head = self.segments[0]\n\n    def create_snake(self):\n        for position in STARTING_POSITIONS:\n            self.add_segment(position)\n    def add_segment(self, position):\n        new_segment = Turtle(\"square\")\n        new_segment.color(\"white\")\n        new_segment.penup()\n        new_segment.goto(position)\n        self.segments.append(new_segment)\n    def reset(self):\n         for seg in self.segments:\n            seg.goto(1000, 1000)\n         self.segments.clear()\n         self.create_snake()\n         self.head = self.segments[0]\n    def extend(self):\n        self.add_segment(self.segments[-1].position())\n    def move(self):\n\n        for seg_num in range(len(self.segments)-1, 0,-1):\n            new_x = self.segments[seg_num-1].xcor()\n            new_y = self.segments[seg_num - 1].ycor()\n            self.segments[seg_num].goto(new_x, new_y)\n\n        self.head.forward(MOVE_DISTANCE)\n\n    def up(self):\n        if self.head.heading() != DOWN:\n            self.head.setheading(UP)\n\n    def down(self):\n        if self.head.heading() != UP:\n            self.head.setheading(DOWN)\n\n    def left(self):\n        if self.head.heading() != RIGHT:\n            self.head.setheading(LEFT)\n\n    def right(self):\n        if self.head.heading() != LEFT:\n            self.head.setheading(RIGHT)\n\n\n\n"
  },
  {
    "path": "Snake-Game/data.py",
    "content": "from scoreboard import Score\nscore = Score()\nHighScore = score.high_score"
  },
  {
    "path": "Snake-Game/data.txt",
    "content": "5"
  },
  {
    "path": "Snake-Game/food.py",
    "content": "from turtle import Turtle\nimport random\n\n\nclass Food(Turtle):\n\n    def __init__(self):\n        super().__init__()\n        self.shape(\"circle\")\n        self.penup()\n        self.shapesize(stretch_wid=0.5, stretch_len=0.5)\n        self.color(\"blue\")\n        self.speed(\"fastest\")\n        self.refresh()\n\n    def refresh(self):\n        random_x = random.randrange(-270,270)\n        random_y = random.randrange(-270, 270)\n        self.goto(random_x, random_y)\n"
  },
  {
    "path": "Snake-Game/main.py",
    "content": "from turtle import Turtle, Screen\nimport time\nfrom food import Food\nfrom Snake import Snake\nfrom scoreboard import Score\nscreen = Screen()\nscreen.setup(width=600, height=600)\nscreen.title(\"My Snake Game\")\nscreen.bgcolor(\"black\")\nscreen.tracer(0)\nsnake = Snake()\nfood = Food()\nscore = Score()\nscreen.listen()\nscreen.onkey(snake.up, \"Up\")\nscreen.onkey(snake.down, \"Down\")\nscreen.onkey(snake.right, \"Right\")\nscreen.onkey(snake.left, \"Left\")\n\nis_game_on = True\nwhile is_game_on:\n    screen.update()\n    time.sleep(0.1)\n    snake.move()\n    # collision with food\n    if snake.head.distance(food) < 15:\n        food.refresh()\n        snake.extend()\n        score.increase_score()\n    # collision with wall\n    if snake.head.xcor() < -280 or snake.head.xcor() > 280 or snake.head.ycor() < -280 or snake.head.ycor() > 280:\n        score.reset()\n        data = str(score.high_score)\n        with open(\"data.txt\", mode=\"w\") as file:\n            file.write(data)\n        snake.reset()\n    # collision with wall\n    for segment in snake.segments[1:]:\n        if snake.head.distance(segment) < 10:\n            score.reset()\n            data = str(score.high_score)\n            with open(\"data.txt\", mode=\"w\") as file:\n                file.write(data)\n            snake.reset()\n\n\n\n\n\n\n\n\nscreen.exitonclick()\n"
  },
  {
    "path": "Snake-Game/scoreboard.py",
    "content": "from turtle import Turtle\n\nclass Score(Turtle):\n\n\n        def __init__(self):\n            self.score = 0\n            with open(\"data.txt\") as file:\n                self.HighScore = int(file.read())\n            self.high_score = self.HighScore\n            super().__init__()\n            self.color(\"white\")\n            self.penup()\n            self.goto(0, 265)\n            self.hideturtle()\n            self.update_score()\n        def update_score(self):\n            self.clear()\n            self.write(f\"Score: {self.score} High Score:{self.high_score}\", align='center', font=('Arial', 24, 'normal'))\n        def reset(self):\n            if self.score > self.high_score:\n                self.high_score = self.score\n            self.score = 0\n            self.update_score()\n        def increase_score(self):\n            self.score += 1\n            self.update_score()\n\n    # def game_over(self):\n    #     self.goto(0, 0)\n    #     self.write(\"GAME OVER\", align='center', font=('Arial', 24, 'normal'))"
  },
  {
    "path": "Speech To Text/main.py",
    "content": "import speech_recognition\n\ndef record_voice():\n\tmicrophone = speech_recognition.Recognizer()\t\n\n\twith speech_recognition.Microphone() as live_phone:\n\t\tmicrophone.adjust_for_ambient_noise(live_phone)\n\t\tprint(\"I'm trying to hear you: \")\n\t\taudio = microphone.listen(live_phone)\n\t\ttry:\n\t\t\tphrase = microphone.recognize_google(audio, language='en')\n\t\t\treturn phrase\n\t\texcept speech_recognition.UnkownValueError:\n\t\t\treturn \"I didn't understand what you said\"\n\nif __name__ == '__main__':\n\tphrase = record_voice()\n\n\twith open('you_said_this.txt','w') as file:\n\t\tfile.write(phrase) \n\n\tprint('The last sentence you spoke was saved in you_said_this.txt') \n"
  },
  {
    "path": "Speech To Text/requirements.txt",
    "content": "PyAudio==0.2.11\nSpeechRecognition==3.8.1"
  },
  {
    "path": "Speech To Text/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Spell Checker/main.py",
    "content": "from textblob import TextBlob\n\nt = 1\nwhile t:\n    a = input(\"Enter the word to be checked:- \")\n    print(\"Original text: \"+str(a))\n\n    b = TextBlob(a)\n    print(\"Corrected text: \"+str(b.correct()))\n    t = int(input(\"Try Again? 1 : 0 \"))"
  },
  {
    "path": "Spell Checker/requirements.txt",
    "content": "textblob==0.17.1"
  },
  {
    "path": "Spell Checker/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Telegram Bot/main.py",
    "content": "# Importing modules\nimport os, requests\nfrom apscheduler.schedulers.background import BackgroundScheduler\nimport telebot\n\n# Golbal Variables\nCITY_NAME = \"Delhi,IN\"\n# Get Telegram Bot Token From Here: https://telegram.me/BotFather\nBOT_TOKEN = os.environ['BOT_TOKEN']\n# Get Your API Key From Here: https://openweathermap.org/api\nWEATHER_API_KEY = os.environ['WEATHER_API_KEY']\n\nscheduler = BackgroundScheduler()\n\n# Initialize bot object\nbot = telebot.TeleBot(BOT_TOKEN)\n\n\n# get weather data\ndef getWeather():\n    url = f\"https://api.openweathermap.org/data/2.5/weather?q={CITY_NAME}&appid={WEATHER_API_KEY}\"\n    response = requests.get(url)\n    weather_data = response.json()\n\n    weather_text = \"\"\n\n    if weather_data['cod'] == 200:\n        weather_text += f\"City : {weather_data['name']},  {weather_data['sys']['country']}\\n\"\n        weather_text += f\"Coordinate : {weather_data['coord']['lon']} °N, {weather_data['coord']['lat']} °E\\n\"\n        weather_text += f\"Weather : {weather_data['weather'][0]['main']}\\n\"\n        weather_text += f\"Temperature : {weather_data['main']['temp']} °F\\n\"\n        weather_text += f\"Pressure : {weather_data['main']['pressure']} hPa\\n\"\n        weather_text += f\"Humidity : {weather_data['main']['humidity']} %\\n\"\n        weather_text += f\"Min-Temp : {weather_data['main']['temp_min']} °F\\n\"\n        weather_text += f\"Max-Temp : {weather_data['main']['temp_max']} °F\\n\"\n        weather_text += f\"Wind Speed : {weather_data['wind']['speed']} m/s\\n\"\n        weather_text += f\"Wind Direction : {weather_data['wind']['deg']}°\\n\"\n        weather_text += f\"Visibility : {weather_data['visibility']} m\\n\"\n    else:\n        weather_text += f\"Error:  {weather_data['message']} \"\n\n    return weather_text\n\n\n# send weather data\ndef sendWeather(message):\n    weather_text = getWeather()\n    bot.send_message(\n        message,\n        text=\"The current weather details in Delhi is: \\n\\n\" + weather_text)\n\n\n# Start Weather updates\n@bot.message_handler(commands=['start'])\ndef start(message):\n    bot.reply_to(message, \"Weather updates started successfully.\")\n    scheduler.add_job(sendWeather(message.chat.id), 'interval', hours=1)\n    scheduler.start()\n\n\n# Stop weather updates\n@bot.message_handler(commands=['stop'])\ndef stop(message):\n    scheduler.remove_all_jobs()\n    bot.send_message(message.chat.id, text=\"Weather updates stopped successfully.\")\n\n\n# Test command\n@bot.message_handler(commands=['test'])\ndef send_welcome(message):\n    bot.reply_to(message, \"Hello, I am ready to serve you.\")\n\n\n# Set the listener\nbot.set_update_listener(start)\nbot.set_update_listener(stop)\n# Run the bot\nbot.infinity_polling()\n"
  },
  {
    "path": "Telegram Bot/requirements.txt",
    "content": "pyTelegramBotAPI==4.9.0\nAPScheduler==3.9.1\n"
  },
  {
    "path": "Telegram Bot/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Text Summarizer/README.md",
    "content": "# TextRank-based Text Summarization\n\nThis 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.\n\n## Table of Contents\n\n1. [Features](#features)\n2. [Installation](#installation)\n3. [Usage](#usage)\n4. [How It Works](#how-it-works)\n5. [Project Structure](#project-structure)\n6. [Dependencies](#dependencies)\n7. [License](#license)\n\n---\n\n## Features\n\n- Preprocesses text to clean and remove stopwords.\n- Utilizes **GloVe word embeddings** for sentence vectorization.\n- Applies the **TextRank algorithm** to rank and select important sentences.\n- Automatically downloads GloVe embeddings if not present locally.\n- Outputs a summary of the most relevant sentences from the input text.\n\n## Installation\n\n1. Clone the repository:\n   ```bash\n   git clone https://github.com/king04aman/All-In-One-Python-Projects.git\n   ```\n2. Install the required Python libraries:\n\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n3. Download necessary NLTK data for tokenization and stopword removal:\n   ```python\n   import nltk\n   nltk.download('punkt')\n   nltk.download('stopwords')\n   ```\n\n## Usage\n\n1. Prepare your CSV file with a column `article_text` containing the text articles you want to summarize.\n\n2. Run the script with your desired input:\n   ```bash\n   python text_summarizer.py\n   ```\n\n### Example:\n\n- Ensure the input CSV file is in the directory:\n\n  ```bash\n  Text Summarizer/sample.csv\n  ```\n\n- The script will output the summary of the most important sentences from the input text.\n\n### Command-line Parameters\n\nYou can modify the following paths and settings inside the script:\n\n- `input_csv`: Path to your input CSV file.\n- `glove_dir`: Directory for storing GloVe embeddings.\n- `glove_file`: Path to the GloVe embeddings file.\n- `top_n_sentences`: The number of sentences you want in the summary (default is 10).\n\n## How It Works\n\n### 1. Text Preprocessing\n\n- Sentences are tokenized, and each sentence is cleaned by:\n  - Removing punctuation, numbers, and special characters.\n  - Converting text to lowercase.\n  - Removing stopwords using the NLTK library.\n\n### 2. Sentence Vectorization\n\n- 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.\n- If the embeddings are not present, the script automatically downloads them.\n\n### 3. Building Similarity Matrix\n\n- A similarity matrix is built by calculating the **cosine similarity** between sentence vectors. This matrix forms the basis for ranking sentences.\n\n### 4. Sentence Ranking\n\n- 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.\n\n### 5. Output Summary\n\n- Based on the rankings, the top `n` sentences are selected as the summary. These sentences are printed as the output of the script.\n\n## Project Structure\n\n```\n.\n├── Text Summarizer/\n│   ├── sample.csv                # Example CSV input file with articles\n│   ├── text_summarizer.py  # Main script for summarization\n│   ├── glove/                    # Directory for storing GloVe embeddings\n│   └── text_summarizer.log # Log file\n```\n\n## Dependencies\n\n- **Python 3.x**\n- **Libraries**:\n  - `numpy`\n  - `pandas`\n  - `nltk`\n  - `sklearn`\n  - `networkx`\n  - `requests`\n  - `tqdm`\n\nAll dependencies can be installed via:\n\n```bash\npip install -r requirements.txt\n```\n\n### GloVe Embeddings\n\n- The script uses **GloVe embeddings** from Stanford NLP to generate sentence vectors.\n  - By default, the **100-dimensional GloVe vectors** (`glove.6B.100d.txt`) are used.\n  - Download link: [GloVe 6B embeddings](http://nlp.uoregon.edu/download/embeddings/glove.6B.100d.txt)\n\n## Short Summary\n\nTextRank Text Summarization\n\nThis script implements a TextRank-based approach for text summarization.\nThe input is a CSV file containing text articles, and the output is a summary\nof the text.\n\nSteps:\n\n1. Preprocesses the text by removing punctuation, numbers, special characters, and stopwords.\n2. Generates sentence vectors using GloVe word embeddings.\n3. Builds a similarity matrix using cosine similarity between sentence vectors.\n4. Applies the PageRank algorithm to rank sentences.\n5. Outputs a summary of the most important sentences.\n\nDependencies:\n\n- numpy\n- pandas\n- nltk\n- sklearn\n- networkx\n- GloVe word embeddings (automatically downloaded if not present)\n\nAuthor: [Himanshu Mahajan](https://github.com/himanshumahajan138)\n\nDate: 19-10-2024\n\n\n## License\n\nThis project is licensed under the MIT License.\n\n---\n"
  },
  {
    "path": "Text Summarizer/requirements.txt",
    "content": "networkx==3.3\nnltk==3.9.1\nnumpy==2.1.2\npandas==2.2.3\nRequests==2.32.3\nscikit_learn==1.5.2\ntqdm==4.66.5\n"
  },
  {
    "path": "Text Summarizer/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Text Summarizer/sample.csv",
    "content": "article_id,article_text,source\n1,\"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/\n2,\"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/\n3,\"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\n4,\"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/\n5,\"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\n6,\"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\n7,\"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/\n8,\"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\n"
  },
  {
    "path": "Text Summarizer/text_summarizer.py",
    "content": "\"\"\"\nTextRank Text Summarization\n\nThis script implements a TextRank-based approach for text summarization.\nThe input is a CSV file containing text articles, and the output is a summary\nof the text.\n\nSteps:\n1. Preprocesses the text by removing punctuation, numbers, special characters, and stopwords.\n2. Generates sentence vectors using GloVe word embeddings.\n3. Builds a similarity matrix using cosine similarity between sentence vectors.\n4. Applies the PageRank algorithm to rank sentences.\n5. Outputs a summary of the most important sentences.\n\nDependencies:\n- numpy\n- pandas\n- nltk\n- sklearn\n- networkx\n- GloVe word embeddings (automatically downloaded if not present)\n\nAuthor: Himanshu Mahajan (GitHub: himanshumahajan138)\nDate: 19-10-2024\n\"\"\"\n\nimport os\nimport requests\nfrom tqdm import tqdm\nimport numpy as np\nimport pandas as pd\nimport nltk\nfrom nltk.tokenize import sent_tokenize\nfrom nltk.corpus import stopwords\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport networkx as nx\nimport logging\n\n# Configure logging\nlogging.basicConfig(\n    level=logging.INFO,\n    format=\"%(asctime)s - %(levelname)s - %(message)s\",\n    handlers=[\n        logging.FileHandler(\"Text Summarizer/text_summarizer.log\"),\n        logging.StreamHandler(),\n    ],\n)\n\n# Download necessary NLTK data (if not already available)\nnltk.download(\"punkt\")  # Sentence tokenizer\nnltk.download(\"stopwords\")  # Stopwords list\n\n\n# Function to preprocess and clean sentences\ndef preprocess_sentences(sentences):\n    \"\"\"\n    Cleans and preprocesses sentences by removing non-alphabetic characters,\n    converting to lowercase, and removing stopwords.\n\n    Args:\n        sentences (list): List of sentences.\n\n    Returns:\n        list: Cleaned and preprocessed sentences.\n    \"\"\"\n    logging.info(\"Preprocessing sentences...\")\n    # Remove punctuation, numbers, and special characters\n    clean_sentences = pd.Series(sentences).str.replace(\"[^a-zA-Z]\", \" \", regex=True)\n\n    # Convert to lowercase\n    clean_sentences = [s.lower() for s in clean_sentences]\n\n    # Remove stopwords\n    stop_words = stopwords.words(\"english\")\n    clean_sentences = [\n        \" \".join([word for word in sentence.split() if word not in stop_words])\n        for sentence in clean_sentences\n    ]\n\n    logging.info(\"Preprocessing completed.\")\n    return clean_sentences\n\n\n# Function to generate sentence vectors using GloVe embeddings\ndef generate_sentence_vectors(sentences, word_embeddings, embedding_dim=100):\n    \"\"\"\n    Converts sentences into vectors by averaging the GloVe word embeddings of each word in the sentence.\n\n    Args:\n        sentences (list): List of sentences.\n        word_embeddings (dict): GloVe word embeddings.\n        embedding_dim (int): Dimensionality of GloVe vectors.\n\n    Returns:\n        list: List of sentence vectors.\n    \"\"\"\n    logging.info(\"Generating sentence vectors...\")\n    sentence_vectors = []\n    for sentence in sentences:\n        if len(sentence) != 0:\n            words = sentence.split()\n            sentence_vector = sum(\n                [\n                    word_embeddings.get(word, np.zeros((embedding_dim,)))\n                    for word in words\n                ]\n            ) / (len(words) + 0.001)\n        else:\n            sentence_vector = np.zeros((embedding_dim,))\n        sentence_vectors.append(sentence_vector)\n\n    logging.info(\"Sentence vectors generated.\")\n    return sentence_vectors\n\n\n# Function to build similarity matrix\ndef build_similarity_matrix(sentence_vectors):\n    \"\"\"\n    Builds a similarity matrix using cosine similarity between sentence vectors.\n\n    Args:\n        sentence_vectors (list): List of sentence vectors.\n\n    Returns:\n        np.ndarray: Similarity matrix.\n    \"\"\"\n    logging.info(\"Building similarity matrix...\")\n    sim_mat = np.zeros([len(sentence_vectors), len(sentence_vectors)])\n\n    for i in range(len(sentence_vectors)):\n        for j in range(len(sentence_vectors)):\n            if i != j:\n                sim_mat[i][j] = cosine_similarity(\n                    sentence_vectors[i].reshape(1, -1),\n                    sentence_vectors[j].reshape(1, -1),\n                )[0, 0]\n\n    logging.info(\"Similarity matrix built.\")\n    return sim_mat\n\n\n# Function to rank sentences using TextRank algorithm\ndef rank_sentences(similarity_matrix, sentences, top_n=10):\n    \"\"\"\n    Ranks sentences based on the PageRank algorithm applied to the similarity matrix.\n\n    Args:\n        similarity_matrix (np.ndarray): Similarity matrix.\n        sentences (list): List of original sentences.\n        top_n (int): Number of top-ranked sentences to return.\n\n    Returns:\n        list: Top-ranked sentences.\n    \"\"\"\n    logging.info(f\"Ranking top {top_n} sentences...\")\n    nx_graph = nx.from_numpy_array(similarity_matrix)\n    scores = nx.pagerank(nx_graph)\n\n    ranked_sentences = sorted(\n        ((scores[i], sentence) for i, sentence in enumerate(sentences)), reverse=True\n    )\n\n    logging.info(\"Sentences ranked.\")\n    return [ranked_sentences[i][1] for i in range(top_n)]\n\n\n# Function to download and extract GloVe embeddings\ndef download_glove(glove_url, glove_file, glove_dir):\n    \"\"\"\n    Downloads and extracts GloVe embeddings if not already present.\n\n    Args:\n        glove_url (str): URL to the GloVe embeddings zip file.\n        glove_zip (str): Path to the GloVe zip file.\n        glove_dir (str): Directory where the GloVe files will be extracted.\n    \"\"\"\n    if not os.path.exists(glove_file):\n        os.makedirs(glove_dir, exist_ok=True)\n        logging.info(\"GloVe embeddings not found, downloading...\")\n\n        # Stream the request to handle large files\n        with requests.get(glove_url, stream=True) as response:\n            response.raise_for_status()\n            total_size = int(response.headers.get(\"content-length\", 0))\n            block_size = 1024  # 1 Kibibyte\n\n            # Use tqdm to show progress bar\n            with tqdm(\n                total=total_size, unit=\"B\", unit_scale=True, desc=glove_file\n            ) as progress_bar:\n                with open(glove_file, \"wb\") as file:\n                    for data in response.iter_content(block_size):\n                        file.write(data)\n                        progress_bar.update(len(data))\n\n        logging.info(\"Download complete. Extracting files...\")\n\n    else:\n        logging.info(\"GloVe embeddings already present.\")\n\n\n# Main function to summarize text using TextRank\ndef summarize_text(input_csv, glove_file, top_n=10):\n    \"\"\"\n    Summarizes the text from a CSV file using the TextRank algorithm.\n\n    Args:\n        input_csv (str): Path to the input CSV file.\n        glove_file (str): Path to the GloVe embeddings file.\n        top_n (int): Number of sentences to include in the summary.\n\n    Returns:\n        list: Summary sentences.\n    \"\"\"\n    logging.info(f\"Starting text summarization for {input_csv}...\")\n\n    # Read the CSV file\n    df = pd.read_csv(input_csv)\n\n    # Tokenize articles into sentences\n    logging.info(\"Tokenizing articles into sentences...\")\n    sentences = [sent_tokenize(article) for article in df[\"article_text\"]]\n    sentences = [\n        sentence for sublist in sentences for sentence in sublist\n    ]  # Flatten the list\n\n    # Preprocess sentences\n    clean_sentences = preprocess_sentences(sentences)\n\n    # Load GloVe embeddings\n    logging.info(\"Loading GloVe embeddings...\")\n    word_embeddings = {}\n    with open(glove_file, \"r\", encoding=\"utf-8\") as f:\n        for line in f:\n            values = line.split()\n            word = values[0]\n            coefs = np.asarray(values[1:], dtype=\"float32\")\n            word_embeddings[word] = coefs\n\n    # Generate sentence vectors\n    sentence_vectors = generate_sentence_vectors(clean_sentences, word_embeddings)\n\n    # Build similarity matrix\n    sim_mat = build_similarity_matrix(sentence_vectors)\n\n    # Rank sentences\n    summary = rank_sentences(sim_mat, sentences, top_n=top_n)\n\n    logging.info(f\"Text summarization completed for {input_csv}.\")\n    return summary\n\n\nif __name__ == \"__main__\":\n    # Define paths and parameters\n    input_csv = os.getcwd() + \"/Text Summarizer/sample.csv\"  # Path to input CSV file\n    glove_dir = \"Text Summarizer/glove\"  # Directory where GloVe files will be stored\n\n    glove_file = os.path.join(\n        os.getcwd(), glove_dir, \"glove.6B.100d.txt\"\n    )  # Path to GloVe embeddings file\n\n    glove_url = \"http://nlp.uoregon.edu/download/embeddings/glove.6B.100d.txt\"  # URL for GloVe embeddings\n\n    top_n_sentences = 10  # Number of sentences in the summary\n\n    # Download and extract GloVe embeddings\n    download_glove(glove_url, glove_file, glove_dir)\n\n    # Generate summary\n    summary = summarize_text(input_csv, glove_file, top_n_sentences)\n\n    # Print summary\n    print(\"Summary:\")\n    for sentence in summary:\n        print(sentence + \"\\n\")\n"
  },
  {
    "path": "Text To Speech/README.md",
    "content": "# Script Name\n**Text to Speech Converter using gTTS**\n\n- 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).\n- It allows for customization of language, speech speed, accents, and other pre-processing and tokenizing options.\n- Features:\n  - Support for multiple languages using IETF language tags.\n  - Localized accents via different Google Translate top-level domains (`tld`).\n  - Option to slow down speech for easier comprehension.\n  - Custom text pre-processing and tokenization options.\n  - Timeout control for network requests.\n  - Automatic playing of the audio file after saving (optional).\n\n# Description\nThis 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.\n\n### Key Features:\n- **Multilingual Support**: Specify different languages using IETF language tags (`en`, `es`, etc.).\n- **Accents**: Use top-level domains (`tld`), such as `com`, `co.uk`, etc., to localize the accent.\n- **Custom Speed**: Option to slow down the speech for better understanding.\n- **Pre-Processing**: Built-in support for text pre-processing (e.g., removing punctuation).\n- **Timeout**: Set timeout limits for the API request.\n\n# Prerequisites\nThe following libraries are required to run the script:\n```bash\npip install gtts\n```\n\nAdditionally, the script uses built-in libraries like `os`.\n\n# Installing Instructions\n1. **Clone the Repository**:\n   Clone this repository to your local machine using:\n   ```bash\n   git clone <repository-url>\n   ```\n\n2. **Install Dependencies**:\n   Navigate to the project directory and install the required packages:\n   ```bash\n   pip install -r requirements.txt\n   ```\n\n3. **Run the Script**:\n   After cloning and installing dependencies, you can run the script directly:\n   ```bash\n   python text_to_speech.py\n   ```\n\n4. **Customize the Script**:\n   You can modify the input text, language, speed, and other options directly in the script:\n   ```python\n   text_to_speech(\"Hello, welcome to the gTTS Python tutorial.\", lang='en', slow=False)\n   ```\n\n# Output\n### Example output:\nAfter running the script with the text `\"Hello, welcome to the gTTS Python tutorial.\"`, the output file `output.mp3` is generated.\n\n\n# Author\n**[Himanshu Mahajan](https://github.com/himanshumahajan138)**\n"
  },
  {
    "path": "Text To Speech/requirements.txt",
    "content": "gTTS==2.5.2\n"
  },
  {
    "path": "Text To Speech/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Text To Speech/text_to_speech.py",
    "content": "from gtts import gTTS\nimport os\n\n\ndef text_to_speech(\n    text,\n    lang=\"en\",\n    tld=\"com\",\n    slow=False,\n    lang_check=True,\n    pre_processor_funcs=None,\n    tokenizer_func=None,\n    timeout=None,\n    output_file=\"output.mp3\",\n):\n    \"\"\"\n    Convert the provided text to speech and save it as an audio file.\n\n    Args:\n        text (string): The text to be read.\n        lang (string, optional): The language (IETF language tag) to read the text in. Default is 'en'.\n        tld (string, optional): Top-level domain for Google Translate host (e.g., 'com', 'co.uk').\n                                This affects accent localization. Default is 'com'.\n        slow (bool, optional): If True, reads the text more slowly. Default is False.\n        lang_check (bool, optional): If True, enforces valid language, raising a ValueError if unsupported. Default is True.\n        pre_processor_funcs (list, optional): List of pre-processing functions to modify the text before tokenizing.\n                                                Defaults to a list of built-in pre-processors.\n        tokenizer_func (callable, optional): Function to tokenize the text. Defaults to a built-in tokenizer.\n        timeout (float or tuple, optional): Seconds to wait for server response. Can be a float or a (connect, read) tuple.\n                                            Default is None (wait indefinitely).\n        output_file (string): Path for the output audio file (default: 'output.mp3').\n\n    Raises:\n        AssertionError: When text is None or empty.\n        ValueError: When lang_check is True and lang is unsupported.\n    \"\"\"\n\n    # Use default pre-processor functions if not provided\n    if pre_processor_funcs is None:\n        pre_processor_funcs = [\n            # Example built-in functions from gTTS:\n            # Converts tone marks, abbreviations, and deals with word substitutions\n            lambda text: text.replace(\n                \".\", \"\"\n            ),  # You can define more or use built-ins from gTTS\n        ]\n\n    # Use default tokenizer if not provided\n    if tokenizer_func is None:\n        tokenizer_func = lambda text: text.split()  # Basic tokenizer example\n\n    try:\n        # Create the gTTS object with the provided arguments\n        tts = gTTS(\n            text=text,\n            lang=lang,\n            tld=tld,\n            slow=slow,\n            lang_check=lang_check,\n            pre_processor_funcs=pre_processor_funcs,\n            tokenizer_func=tokenizer_func,\n            timeout=timeout,\n        )\n\n        # Save the audio file\n        tts.save(\"Text To Speech/\"+output_file)\n        print(f\"Audio saved at Text To Speech/{output_file}\")\n\n        # Optionally, play the audio file (Windows or Linux/MacOS)\n        # if os.name == \"nt\":  # Windows\n        #     os.system(f\"start {output_file}\")\n        # else:  # macOS/Linux\n        #     os.system(f\"xdg-open {output_file}\")\n\n    except AssertionError as ae:\n        print(f\"Assertion Error: {ae}\")\n    except ValueError as ve:\n        print(f\"Value Error: {ve}\")\n    except RuntimeError as re:\n        print(f\"Runtime Error: {re}\")\n\n\nif __name__ == \"__main__\":\n    # Example usage of the text_to_speech function with various arguments\n\n    # Basic example (English, default options)\n    text = \"Hello, welcome to the gTTS Python tutorial.\"\n    text_to_speech(text)\n\n    # # Custom example (Spanish, slow speech, and custom file name)\n    # text_to_speech(\n    #     \"Hola, bienvenido al tutorial de gTTS.\",\n    #     lang=\"es\",\n    #     slow=True,\n    #     output_file=\"spanish_slow.mp3\",\n    # )\n\n    # # Custom example with localized accent (UK English)\n    # text_to_speech(\n    #     \"Hello! How are you today?\",\n    #     lang=\"en\",\n    #     tld=\"co.uk\",\n    #     output_file=\"british_accent.mp3\",\n    # )\n\n    # # You can pass custom pre-processor functions to modify the text before it’s tokenized.\n    # text_to_speech(\n    #     \"Dr. Smith is a great person.\",\n    #     pre_processor_funcs=[lambda x: x.replace(\".\", \"\")],\n    #     output_file=\"custom_pre-processor.mp3\",\n    # )\n\n    # # You can set a timeout to limit how long the request to Google Translate waits.\n    # text_to_speech(\n    #     \"This will timeout after 5 seconds.\",\n    #     output_file=\"timeout.mp3\",\n    #     timeout=5.0\n    # )\n"
  },
  {
    "path": "Text to Morse Code/main.py",
    "content": "symbols = {\n    \"a\": \".-\",\n    \"b\": \"-...\",\n    \"c\": \"-.-.\",\n    \"d\": \"-..\",\n    \"e\": \".\",\n    \"f\": \"..-.\",\n    \"g\": \".-\",\n    \"h\": \"....\",\n    \"i\": \"..\",\n    \"j\": \".---\",\n    \"k\": \"-.-\",\n    \"l\": \".-..\",\n    \"m\": \"--\",\n    \"n\": \"-.\",\n    \"o\": \"---\",\n    \"p\": \".--.\",\n    \"q\": \"--.-\",\n    \"r\": \".-.\",\n    \"s\": \"...\",\n    \"t\": \"-\",\n    \"u\": \"..-\",\n    \"v\": \"...-\",\n    \"w\": \".--\",\n    \"x\": \"-..-\",\n    \"y\": \"-.--\",\n    \"z\": \"--..\",\n}\n\nask = input(\"Enter a word: \")\nlength = len(ask)\noutput = \"\"\n\nfor i in range(length):\n    if ask[i] in symbols.keys():\n        output = output + \" \" + symbols.get(ask[i])\n\nprint(output)   \n"
  },
  {
    "path": "Text to Morse Code/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Text_Adventure_Game/readme.md",
    "content": "# Text-Based Adventure Game\n\nWelcome 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.\n\n## Features\n\n- **Two distinct types of doors**: Players can choose between doors, which may lead to hidden items such as swords or shields.\n- **Combat System**: Engage in battle with different opponents:\n  - **Goblin**: A weak opponent that requires strategy.\n  - **Dragon**: A formidable final boss with special attacks.\n- **Inventory Management**: Pick up and use items like swords and shields to aid in combat.\n- **Game Save & Load**: Your progress is automatically saved, so you can load it later and continue from where you left off.\n\n## Gameplay\n\n- Players start the game by entering their name.\n- You are presented with two doors to choose from, each leading to different experiences.\n- Items like swords and shields can be found to help you in combat.\n- Random encounters with goblins and dragons will test your decision-making skills.\n- The game automatically saves your progress, allowing you to resume your adventure later.\n\n## How to Play\n\n1. **Choose a door**: When prompted, choose either the left or right door. Each door may contain hidden treasures like a sword or shield.\n2. **Make choices**: Decide whether to pick up items or face challenges.\n3. **Combat**: Engage in combat with either a goblin or dragon. Use your sword and shield to protect yourself or defeat enemies.\n4. **Save your progress**: The game will automatically save after each major action.\n5. **Reload your game**: If you exit the game, you can load it from the last saved point when you return.\n\n## Setup and Installation\n\n1. Ensure you have Python 3 installed on your machine.\n2. Clone this repository to your local machine.\n3. Navigate to the project directory.\n4. Run the text_adventure_game.py file.\n\n\n## Code Overview\n\nThe game is built using Python, and its logic is divided into several components:\n\n- **Opponent Class**: The base class for both weak and strong opponents. Handles basic attack logic.\n- **WeakOpponent Class**: A class for weaker opponents like the goblin. Overrides the attack method to reflect weaker attacks.\n- **FinalBoss Class**: A subclass of Opponent designed for more challenging enemies like the dragon, with special powers.\n- **Combat and Exploration**: Players can choose doors, explore rooms, collect items, and engage in combat.\n- **Saving and Loading**: The game state is saved to a file (`game_save.txt`), and players can load this file to continue their progress.\n\n## Error Handling\n\nThe game is designed with basic error handling using `try-except` blocks:\n- If there are issues with file saving or loading, an error message is displayed.\n- Combat logic is wrapped in error handling to prevent crashes due to unexpected input.\n\nEnjoy your adventure!\n"
  },
  {
    "path": "Text_Adventure_Game/text_adventure_game.py",
    "content": "import random\nimport os  # Used to check if the file exists\n\n# Opponent base class\nclass Opponent:\n    def __init__(self, name, health, attack_strength):\n        self.name = name\n        self.health = health\n        self.attack_strength = attack_strength\n\n    def attack(self):\n        \"\"\"General attack logic for opponents.\"\"\"\n        return random.randint(1, self.attack_strength)\n\n# WeakOpponent class inheriting from Opponent\nclass WeakOpponent(Opponent):\n    def __init__(self, name, health, attack_strength):\n        super().__init__(name, health, attack_strength)\n\n    def attack(self):\n        \"\"\"Overriding attack for weak opponents.\"\"\"\n        print(f\"{self.name} attacks weakly!\")\n        return random.randint(1, self.attack_strength // 2)  # Weak attack is halved\n\n# FinalBoss class inheriting from Opponent\nclass FinalBoss(Opponent):\n    def __init__(self, name, health, attack_strength, special_power):\n        super().__init__(name, health, attack_strength)\n        self.special_power = special_power  # New attribute for FinalBoss\n\n    def attack(self):\n        \"\"\"Overriding attack for final bosses with special power.\"\"\"\n        if random.random() > 0.7:  # 30% chance of using special power\n            print(f\"{self.name} uses {self.special_power}!\")\n            return random.randint(self.attack_strength, self.attack_strength * 2)\n        else:\n            print(f\"{self.name} attacks normally.\")\n            return super().attack()\n\n# Additional methods for game logic\n\ndef save_game(player_name, inventory, doors_chosen):\n    \"\"\"Saves the current game state to a file.\"\"\"\n    try:\n        with open('game_save.txt', 'w') as file:\n            file.write(f\"{player_name}\\n\")\n            file.write(\",\".join(inventory) + \"\\n\")\n            file.write(f\"{doors_chosen['left']},{doors_chosen['right']}\\n\")\n    except Exception as e:\n        print(f\"Error saving game: {e}\")\n\ndef load_game():\n    \"\"\"Loads the game state from a file if it exists.\"\"\"\n    if not os.path.exists('game_save.txt'):\n        return None, [], {\"left\": False, \"right\": False}\n\n    try:\n        with open('game_save.txt', 'r') as file:\n            file_content = file.readlines()\n\n        player_name = file_content[0].strip()\n        inventory = file_content[1].strip().split(\",\") if file_content[1].strip() else []\n        doors_status = file_content[2].strip().split(\",\")\n        doors_chosen = {\"left\": doors_status[0] == \"True\", \"right\": doors_status[1] == \"True\"}\n\n        return player_name, inventory, doors_chosen\n    except Exception as e:\n        print(f\"Error loading game: {e}\")\n        return None, [], {\"left\": False, \"right\": False}\n\ndef choose_door(doors_chosen, inventory):\n    \"\"\"Handles the player's choice of doors and updates the game state accordingly.\"\"\"\n    available_doors = []\n    if not doors_chosen[\"left\"]:\n        available_doors.append(\"left\")\n    if not doors_chosen[\"right\"]:\n        available_doors.append(\"right\")\n    \n    print(f'{\"You return to the two doors.\":^30}')\n    if available_doors:\n        print(f'{\"Available doors are: \" + \", \".join(available_doors):^30}')\n    \n    choice = \"\"\n    while choice not in available_doors:\n        choice = input(f'{\"Which door do you want to choose? (left/right): \":^30}').lower()\n\n    try:\n        if choice == \"left\" and not doors_chosen[\"left\"]:\n            print(f'{\"You are in a room with no doors. It is empty.\":^30}')\n            if input(f'{\"Do you want to look around? (yes/no): \":^30}').lower() == \"yes\":\n                print(f'{\"You see a sword on the ground.\":^30}')\n                if input(f'{\"Do you want to take the sword? (yes/no): \":^30}').lower() == \"yes\":\n                    inventory.append(\"sword\")\n                    print(f'{\"You took the sword!\":^30}')\n                else:\n                    print(f'{\"You left the sword.\":^30}')\n            doors_chosen[\"left\"] = True\n\n        elif choice == \"right\" and not doors_chosen[\"right\"]:\n            print(f'{\"You enter a room and find a shield!\":^30}')\n            if input(f'{\"Do you want to take the shield? (yes/no): \":^30}').lower() == \"yes\":\n                inventory.append(\"shield\")\n                print(f'{\"You took the shield!\":^30}')\n            else:\n                print(f'{\"You left the shield.\":^30}')\n            doors_chosen[\"right\"] = True\n    except Exception as e:\n        print(f\"Error during door selection: {e}\")\n    \n    save_game(player_name, inventory, doors_chosen)\n    return doors_chosen, inventory\n\ndef combat(choice, inventory):\n    \"\"\"Handles combat encounters using the new Opponent system.\"\"\"\n    try:\n        if choice == \"dragon\":\n            dragon = FinalBoss(\"Dragon\", health=100, attack_strength=20, special_power=\"Fire Breath\")\n            print(f'{\"You encounter a fearsome dragon!\":^30}')\n            if input(f'{\"Do you want to fight the dragon? (yes/no): \":^30}').lower() == \"yes\":\n                if \"sword\" in inventory:\n                    print(f'{\"Rolling the dice to see the outcome...\":^30}')\n                    player_attack = random.randint(1, 10)  # Simulating player's attack\n                    dragon_attack = dragon.attack()\n\n                    if player_attack >= dragon_attack:\n                        print(f'{\"You defeated the dragon with your sword!\":^30}')\n                    else:\n                        if \"shield\" in inventory:\n                            print(f'{\"The dragon overpowered you, but your shield saved you!\":^30}')\n                            inventory.remove(\"shield\")\n                        else:\n                            print(f'{\"The dragon overpowered you and you lost the game!\":^30}')\n                            inventory.clear()\n                else:\n                    print(f'{\"You were eaten by the dragon because you had no sword!\":^30}')\n                    inventory.clear()\n\n        elif choice == \"goblin\":\n            goblin = WeakOpponent(\"Goblin\", health=50, attack_strength=5)\n            print(f'{\"You encounter a sneaky goblin!\":^30}')\n            if input(f'{\"Do you want to fight the goblin? (yes/no): \":^30}').lower() == \"yes\":\n                if \"sword\" in inventory:\n                    print(f'{\"Rolling the dice to see the outcome...\":^30}')\n                    player_attack = random.randint(1, 10)  # Simulating player's attack\n                    goblin_attack = goblin.attack()\n\n                    if player_attack >= goblin_attack:\n                        print(f'{\"You defeated the goblin with your sword!\":^30}')\n                    else:\n                        if \"shield\" in inventory:\n                            print(f'{\"The goblin tricked you, but your shield protected you!\":^30}')\n                            inventory.remove(\"shield\")\n                        else:\n                            print(f'{\"The goblin tricked you and you lost the game!\":^30}')\n                            inventory.clear()\n                elif \"shield\" in inventory:\n                    print(f'{\"The goblin attacked, but your shield saved you!\":^30}')\n                    inventory.remove(\"shield\")\n                else:\n                    print(f'{\"The goblin defeated you because you had no sword or shield!\":^30}')\n                    inventory.clear()\n    except Exception as e:\n        print(f\"Error during combat: {e}\")\n    \n    return inventory\n\ndef play_game():\n    \"\"\"Main function that runs the game logic.\"\"\"\n    player_name, inventory, doors_chosen = load_game()\n\n    if not player_name:\n        player_name = input(\"Enter your name: \")\n\n    print(f'{\"Welcome to the Adventure Game, \" + player_name + \"!\":^30}')\n    \n    # Let player choose a door\n    doors_chosen, inventory = choose_door(doors_chosen, inventory)\n\n    # Encounter either a goblin or a dragon randomly\n    encounter = random.choice([\"goblin\", \"dragon\"])\n    inventory = combat(encounter, inventory)\n\nif __name__ == \"__main__\":\n    play_game()\n"
  },
  {
    "path": "Tic-Tac-Toc using AI (min-max)/README.md",
    "content": "# Tic-Tac-Toe Game with AI\n\nThis 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.\n\n### Key Features:\n- **Two Players**: Play against an AI or another human player.\n- **Minimax Algorithm**: The AI makes optimal moves based on the Minimax strategy.\n- **Graphical User Interface**: A simple and intuitive GUI using Pygame.\n- **Reset Option**: Restart the game easily at any time.\n\n# Prerequisites\nThe following libraries are required to run the script:\n```bash\npip install pygame numpy\n```\n\n# Installing Instructions\n1. **Clone the Repository**:\n   Clone this repository to your local machine using:\n   ```bash\n   git clone <repository-url>\n   ```\n\n2. **Install Dependencies**:\n   Navigate to the project directory and install the required packages:\n   ```bash\n   pip install pygame numpy\n   ```\n\n3. **Run the Script**:\n   After cloning and installing dependencies, you can run the script directly:\n   ```bash\n   python tic_tac_toe.py\n   ```\n\n4. **Customize the Script**:\n   You can modify game settings, such as board size and player options, directly in the script.\n\n# Gameplay Instructions\n- **Player vs AI:**: Click on the grid to make your move. The AI will respond automatically.\n- **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.\n- **Restart Game**: Press the R key to restart the game at any time.\n\n# Usage\n**Player vs AI**: Click on the grid to make your move. The AI will respond automatically.\n\n**Restart Game**: Press the R key to restart the game at any time.\n\n# Example\nAfter 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.\n![Game Screen](screenshots/screenshot1.png)\n![Winning State](screenshots/screenshot2.png)\n\n\n# Author\n**[Naumantamboli](https://github.com/Naumantamboli)**\n"
  },
  {
    "path": "Tic-Tac-Toc using AI (min-max)/requirements.txt",
    "content": "pygame==2.1.3\nnumpy==1.23.5\n"
  },
  {
    "path": "Tic-Tac-Toc using AI (min-max)/tic_tac_toc.py",
    "content": "import pygame\nimport sys\nimport numpy as np\n\npygame.init()\n\nWIDTH, HEIGHT = 600, 600\nLINE_WIDTH = 15\nBOARD_ROWS = 3\nBOARD_COLS = 3\nSQUARE_SIZE = WIDTH // BOARD_COLS\nCIRCLE_RADIUS = SQUARE_SIZE // 3\nCIRCLE_WIDTH = 15\nCROSS_WIDTH = 25\nSPACE = SQUARE_SIZE // 4\n\nBG_COLOR = (28, 170, 156)\nLINE_COLOR = (23, 145, 135)\nCIRCLE_COLOR = (239, 231, 200)\nCROSS_COLOR = (66, 66, 66)\nTEXT_COLOR = (255, 255, 255)\n\nscreen = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption('Tic Tac Toe')\nscreen.fill(BG_COLOR)\n\nfont = pygame.font.Font(None, 40)  # Font for displaying messages\nboard = np.zeros((BOARD_ROWS, BOARD_COLS))\n\ndifficulty = \"medium\"  # AI difficulty level (\"easy\", \"medium\", \"hard\")\n\ndef draw_lines():\n    for row in range(1, BOARD_ROWS):\n        pygame.draw.line(screen, LINE_COLOR, (0, row * SQUARE_SIZE), (WIDTH, row * SQUARE_SIZE), LINE_WIDTH)\n    for col in range(1, BOARD_COLS):\n        pygame.draw.line(screen, LINE_COLOR, (col * SQUARE_SIZE, 0), (col * SQUARE_SIZE, HEIGHT), LINE_WIDTH)\n\n# Draw figures (O and X)\ndef draw_figures():\n    for row in range(BOARD_ROWS):\n        for col in range(BOARD_COLS):\n            if board[row][col] == 1:\n                pygame.draw.circle(screen, CIRCLE_COLOR,\n                                   (int(col * SQUARE_SIZE + SQUARE_SIZE // 2), int(row * SQUARE_SIZE + SQUARE_SIZE // 2)),\n                                   CIRCLE_RADIUS, CIRCLE_WIDTH)\n            elif board[row][col] == 2:\n                pygame.draw.line(screen, CROSS_COLOR,\n                                 (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE),\n                                 (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SPACE), CROSS_WIDTH)\n                pygame.draw.line(screen, CROSS_COLOR,\n                                 (col * SQUARE_SIZE + SPACE, row * SQUARE_SIZE + SPACE),\n                                 (col * SQUARE_SIZE + SQUARE_SIZE - SPACE, row * SQUARE_SIZE + SQUARE_SIZE - SPACE),\n                                 CROSS_WIDTH)\n\ndef mark_square(row, col, player):\n    board[row][col] = player\n\ndef available_square(row, col):\n    return board[row][col] == 0\n\ndef is_board_full():\n    return np.all(board != 0)\n\ndef check_win(player):\n    for row in range(BOARD_ROWS):\n        if np.all(board[row, :] == player):\n            return True\n    for col in range(BOARD_COLS):\n        if np.all(board[:, col] == player):\n            return True\n    if board[0, 0] == player and board[1, 1] == player and board[2, 2] == player:\n        return True\n    if board[0, 2] == player and board[1, 1] == player and board[2, 0] == player:\n        return True\n    return False\n\ndef display_message(message):\n    text = font.render(message, True, TEXT_COLOR)\n    text_rect = text.get_rect(center=(WIDTH // 2, HEIGHT // 2))\n    screen.blit(text, text_rect)\n    pygame.display.update()\n    pygame.time.wait(2000)  # Wait for 2 seconds to display the message\n\n# Minimax algorithm with difficulty levels\ndef minimax(board, depth, is_maximizing):\n    if check_win(2):  # AI win\n        return 1\n    elif check_win(1):  # Player win\n        return -1\n    elif is_board_full():\n        return 0\n\n    if is_maximizing:\n        best_score = -np.inf\n        for row in range(BOARD_ROWS):\n            for col in range(BOARD_COLS):\n                if available_square(row, col):\n                    board[row][col] = 2\n                    score = minimax(board, depth + 1, False)\n                    board[row][col] = 0\n                    best_score = max(score, best_score)\n        return best_score\n    else:\n        best_score = np.inf\n        for row in range(BOARD_ROWS):\n            for col in range(BOARD_COLS):\n                if available_square(row, col):\n                    board[row][col] = 1\n                    score = minimax(board, depth + 1, True)\n                    board[row][col] = 0\n                    best_score = min(score, best_score)\n        return best_score\n\n# AI Move based on difficulty level\ndef ai_move():\n    best_score = -np.inf\n    move = None\n    for row in range(BOARD_ROWS):\n        for col in range(BOARD_COLS):\n            if available_square(row, col):\n                board[row][col] = 2\n                score = minimax(board, 0, False)\n                board[row][col] = 0\n                if score > best_score:\n                    best_score = score\n                    move = (row, col)\n    \n    if move:\n        mark_square(move[0], move[1], 2)\n\n# Easy AI move: choose a random available square\ndef easy_ai_move():\n    available_moves = [(row, col) for row in range(BOARD_ROWS) for col in range(BOARD_COLS) if available_square(row, col)]\n    if available_moves:\n        move = available_moves[np.random.randint(len(available_moves))]\n        mark_square(move[0], move[1], 2)\n\ndef restart():\n    screen.fill(BG_COLOR)\n    draw_lines()\n    global board\n    board = np.zeros((BOARD_ROWS, BOARD_COLS))\n\nplayer = 1  # Player 1 is human\ngame_over = False\n\ndraw_lines()\n\nwhile True:\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT:\n            pygame.quit()\n            sys.exit()\n\n        if event.type == pygame.MOUSEBUTTONDOWN and not game_over:\n            mouseX = event.pos[0]  # X coordinate\n            mouseY = event.pos[1]  # Y coordinate\n\n            clicked_row = mouseY // SQUARE_SIZE\n            clicked_col = mouseX // SQUARE_SIZE\n\n            if available_square(clicked_row, clicked_col):\n                mark_square(clicked_row, clicked_col, player)\n                if check_win(player):\n                    display_message(\"Player Wins!\")\n                    game_over = True\n                player = 2\n\n        if player == 2 and not game_over:\n            if difficulty == \"easy\":\n                easy_ai_move()\n            else:\n                ai_move()\n                \n            if check_win(2):\n                display_message(\"AI Wins!\")\n                game_over = True\n            player = 1\n\n        if event.type == pygame.KEYDOWN:\n            if event.key == pygame.K_r:\n                restart()\n                game_over = False\n                player = 1\n\n        if game_over and is_board_full():\n            display_message(\"It's a Draw!\")\n            game_over = True\n\n    draw_figures()\n    pygame.display.update()\n"
  },
  {
    "path": "To Do List/README.md",
    "content": "# To-Do List App\n\nThis is a simple To-Do List app built with Python using `tkinter` for the user interface and `sqlite3` for data storage.\n\n## Features\n\n- Add tasks\n- View tasks\n- Delete tasks\n- Save tasks to database\n\n## Requirements\n\n- Python 3.8.10\n- `tkinter`\n- `sqlite3`\n\n## Installation\n\n1. Clone the repository:\n   ```bash\n   git clone <repository-url>\n"
  },
  {
    "path": "To Do List/RithwikBejadi/To Do App/README.md",
    "content": "**#To-Do List Application**\nA 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.\n\n**Features**\n\nAdd Tasks: Add tasks with a description, category, due date, and priority level (High, Medium, Low).\n\nView Tasks: View all tasks, or filter tasks to see only completed or pending ones.\n\nSearch Tasks: Quickly search tasks by their name or category using the search bar.\n\nToggle Theme: Switch between dark and light themes to match your preference.\n\nMark Tasks as Complete: Mark tasks as completed to keep track of what’s done.\n\nPersistent Storage: All tasks are saved in an SQLite database, ensuring data is saved even after closing the app.\n\n\n**Prerequisites**\n\nPython 3.6+\nTkinter (Usually included with Python)\nSQLite (Included in Python’s standard library)\ntkcalendar: Install using pip install tkcalendar\n\n**Usage Instructions**\n\n1. Add a Task\nEnter a task description in the Task field.\nSpecify the Category for better organization.\nSelect a Due Date from the date picker.\nChoose a Priority from the drop-down menu (High, Medium, Low).\nClick Add Task to save it.\n\n2. View All Tasks\nClick on View All Tasks in the sidebar to display a list of all tasks.\nTasks are displayed with their description, category, due date, and priority level.\n\n3. View Completed Tasks\nClick View Completed Tasks in the sidebar to see tasks that have been marked as complete.\n\n4. View Pending Tasks\nClick View Pending Tasks in the sidebar to view tasks that are yet to be completed.\n\n5. Search Tasks\nUse the Search bar in the sidebar to find tasks by their description or category.\nThe list of tasks will update as you type, showing only those that match the search term.\n\n6. Mark Tasks as Complete\nSelect a task from the list and click Mark as Complete (add this button in your application).\nCompleted tasks will no longer appear in the pending tasks view.\n\n7. Toggle Dark/Light Theme\nClick Toggle Theme in the sidebar to switch between dark and light modes.\nThis changes the background color, text color, and button styles for a better visual experience.\n\n8. Close the Application\nClose the application by clicking the window close button (X) or selecting Exit.\nThe application safely saves your tasks and closes the database connection.\n\n\n**Database Structure**\nThe application uses an SQLite database with the following table structure:\n\nTable Name: tasks\n\nColumn Name\tType\tDescription\n\nid\t       INTEGER\tPrimary key, unique task ID\ntask\t    TEXT\tDescription of the task\ncategory\tTEXT\tCategory of the task (e.g., Work, Home)\ndue_date\tTEXT\tDue date of the task\npriority\tTEXT\tPriority level (High, Medium, Low)\ncompleted\tINTEGER\tStatus (0 = Pending, 1 = Completed)\n\n**License**\nThis project is licensed under the MIT License. See the LICENSE file for details.\n\n**Acknowledgments**\nThanks to the Python community for their extensive libraries and documentation.\nSpecial thanks to the creators of tkcalendar for providing a simple date picker widget for Tkinter.\n"
  },
  {
    "path": "To Do List/RithwikBejadi/To Do App/To_Do_AppTkInter.py",
    "content": "import tkinter as tk\nfrom tkinter import messagebox, ttk\nfrom tkcalendar import DateEntry\nimport sqlite3\n\nclass TodoApp:\n    def __init__(self, root):\n        self.root = root\n        self.root.title(\"To-Do List App\")\n        self.root.geometry(\"900x600\")\n\n        # Initialize attributes\n        self.is_dark_theme = True  # Start with dark theme\n\n        # Create main frame and sidebar frame\n        self.main_frame = tk.Frame(self.root, bg=\"#2E2E2E\")\n        self.main_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)\n\n        self.sidebar_frame = tk.Frame(self.root, width=200, bg=\"#3A3A3A\")\n        self.sidebar_frame.pack(side=tk.LEFT, fill=tk.Y)\n\n        self.create_widgets()\n        self.create_database()\n        self.apply_theme()  # Apply theme after frames are created\n        self.create_sidebar()\n        self.load_tasks()\n\n        # Bind the window close event to close the database connection\n        self.root.protocol(\"WM_DELETE_WINDOW\", self.close_app)\n\n    def create_sidebar(self):\n        \"\"\"Create the sidebar with navigation options.\"\"\"\n        tk.Label(self.sidebar_frame, text=\"Menu\", font=(\"Helvetica\", 16), bg=\"#3A3A3A\", fg=\"#FFFFFF\").pack(pady=10)\n\n        # Create the \"View All Tasks\" button\n        self.view_all_button = tk.Button(\n            self.sidebar_frame, \n            text=\"View All Tasks\", \n            command=self.load_tasks, \n            bg=\"#5A5A5A\", \n            fg=\"#FFFFFF\", \n            relief=\"flat\"\n        )\n        self.view_all_button.pack(pady=5, padx=10, fill=tk.X)\n\n        # Create other buttons like \"View Completed Tasks\", \"View Pending Tasks\", etc.\n        self.view_completed_button = tk.Button(\n            self.sidebar_frame, \n            text=\"View Completed Tasks\", \n            command=self.load_completed_tasks, \n            bg=\"#5A5A5A\", \n            fg=\"#FFFFFF\", \n            relief=\"flat\"\n        )\n        self.view_completed_button.pack(pady=5, padx=10, fill=tk.X)\n\n        self.view_pending_button = tk.Button(\n            self.sidebar_frame, \n            text=\"View Pending Tasks\", \n            command=self.load_pending_tasks, \n            bg=\"#5A5A5A\", \n            fg=\"#FFFFFF\", \n            relief=\"flat\"\n        )\n        self.view_pending_button.pack(pady=5, padx=10, fill=tk.X)\n\n        # Search entry and label\n        tk.Label(self.sidebar_frame, text=\"Search:\", bg=\"#3A3A3A\", fg=\"#FFFFFF\").pack(pady=5)\n        self.search_entry = tk.Entry(self.sidebar_frame, bg=\"#4B4B4B\", fg=\"#FFFFFF\", relief=\"flat\")\n        self.search_entry.pack(pady=5, padx=10, fill=tk.X)\n        self.search_entry.bind('<KeyRelease>', self.search_tasks)\n\n        # Toggle theme button\n        self.theme_button = tk.Button(\n            self.sidebar_frame, \n            text=\"Toggle Theme\", \n            command=self.toggle_theme, \n            bg=\"#5A5A5A\", \n            fg=\"#FFFFFF\", \n            relief=\"flat\"\n        )\n        self.theme_button.pack(pady=5, padx=10, fill=tk.X)\n\n    def apply_theme(self):\n        \"\"\"Apply the current theme to the application.\"\"\"\n        if self.is_dark_theme:\n            bg_color = \"#2E2E2E\"\n            fg_color = \"#FFFFFF\"\n            button_bg = \"#5A5A5A\"\n            entry_bg = \"#4B4B4B\"\n        else:\n            bg_color = \"#F0F0F0\"\n            fg_color = \"#000000\"\n            button_bg = \"#D0D0D0\"\n            entry_bg = \"#FFFFFF\"\n        \n        self.root.configure(bg=bg_color)\n        self.main_frame.configure(bg=bg_color)\n        self.sidebar_frame.configure(bg=\"#3A3A3A\" if self.is_dark_theme else \"#F0F0F0\")\n\n        # Update the colors of sidebar elements\n        for widget in self.sidebar_frame.winfo_children():\n            if isinstance(widget, tk.Button):\n                widget.configure(bg=button_bg, fg=fg_color)\n            elif isinstance(widget, tk.Entry):\n                widget.configure(bg=entry_bg, fg=fg_color)\n\n    def toggle_theme(self):\n        \"\"\"Toggle between light and dark themes.\"\"\"\n        self.is_dark_theme = not self.is_dark_theme\n        self.apply_theme()\n\n    def create_database(self):\n        \"\"\"Create the tasks table if it doesn't exist.\"\"\"\n        self.conn = sqlite3.connect(\"tasks.db\")\n        # Create the table if it doesn't exist yet\n        with self.conn:\n            self.conn.execute(\"\"\"\n                CREATE TABLE IF NOT EXISTS tasks (\n                    id INTEGER PRIMARY KEY,\n                    task TEXT NOT NULL,\n                    category TEXT,\n                    due_date TEXT,\n                    priority TEXT,\n                    completed INTEGER DEFAULT 0\n                )\n            \"\"\")\n\n    def create_widgets(self):\n        \"\"\"Create the main content area widgets.\"\"\"\n        frame = tk.Frame(self.main_frame, bg=\"#2E2E2E\" if self.is_dark_theme else \"#FFFFFF\", padx=10, pady=10)\n        frame.pack(pady=20, padx=20, fill=tk.BOTH, expand=True)\n\n        # Task entry\n        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)\n        self.task_entry = tk.Entry(frame, width=50, bg=\"#4B4B4B\", fg=\"#FFFFFF\", relief=\"flat\")\n        self.task_entry.grid(row=0, column=1, sticky=\"ew\", padx=5, pady=5)\n\n        # Category entry\n        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)\n        self.category_entry = tk.Entry(frame, width=50, bg=\"#4B4B4B\", fg=\"#FFFFFF\", relief=\"flat\")\n        self.category_entry.grid(row=1, column=1, sticky=\"ew\", padx=5, pady=5)\n\n        # Due date entry\n        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)\n        self.due_date_entry = DateEntry(frame, width=20, date_pattern='yyyy-mm-dd', background='#4B4B4B', foreground='white', relief=\"flat\")\n        self.due_date_entry.grid(row=2, column=1, sticky=\"w\", padx=5, pady=5)\n\n        # Priority menu\n        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)\n        self.priority_var = tk.StringVar(value=\"Medium\")\n        self.priority_menu = ttk.Combobox(frame, textvariable=self.priority_var, values=[\"High\", \"Medium\", \"Low\"], state=\"readonly\")\n        self.priority_menu.grid(row=3, column=1, sticky=\"w\", padx=5, pady=5)\n\n        # Add task button\n        self.add_task_button = tk.Button(frame, text=\"Add Task\", command=self.add_task, bg=\"#5A5A5A\", fg=\"#FFFFFF\", relief=\"flat\")\n        self.add_task_button.grid(row=4, column=1, sticky=\"e\", pady=10)\n\n        # Listbox for tasks\n        self.task_listbox = tk.Listbox(self.main_frame, font=(\"Helvetica\", 10), bg=\"#2E2E2E\", fg=\"#FFFFFF\", height=15, relief=\"flat\")\n        self.task_listbox.pack(pady=10, padx=20, fill=tk.BOTH, expand=True)\n\n    def load_tasks(self):\n        \"\"\"Load all pending tasks from the database.\"\"\"\n        self.task_listbox.delete(0, tk.END)\n        cursor = self.conn.cursor()\n        # Retrieve tasks that are not yet completed (completed=0)\n        cursor.execute(\"SELECT * FROM tasks WHERE completed=0\")\n        for row in cursor.fetchall():\n            # Format the task details for display in the listbox\n            self.task_listbox.insert(tk.END, f\"{row[1]} | {row[2]} | Due: {row[3]} | Priority: {row[4]}\")\n\n    def load_completed_tasks(self):\n        \"\"\"Load completed tasks from the database.\"\"\"\n        self.task_listbox.delete(0, tk.END)\n        cursor = self.conn.cursor()\n        # Retrieve tasks that are marked as completed (completed=1)\n        cursor.execute(\"SELECT * FROM tasks WHERE completed=1\")\n        for row in cursor.fetchall():\n            self.task_listbox.insert(tk.END, f\"{row[1]} | {row[2]} | Due: {row[3]} | Priority: {row[4]}\")\n\n    def load_pending_tasks(self):\n        \"\"\"Load pending tasks.\"\"\"\n        # Reuse the load_tasks method since it already loads pending tasks\n        self.load_tasks()\n\n    def add_task(self):\n        \"\"\"Add a new task to the database.\"\"\"\n        task = self.task_entry.get()\n        category = self.category_entry.get()\n        due_date = self.due_date_entry.get()\n        priority = self.priority_var.get()\n\n        # Validate that required fields are filled\n        if task and category and due_date:\n            with self.conn:\n                # Insert a new task into the database\n                self.conn.execute(\"INSERT INTO tasks (task, category, due_date, priority) VALUES (?, ?, ?, ?)\", \n                                  (task, category, due_date, priority))\n            # Refresh the task list to show the new entry\n            self.load_tasks()\n            # Clear the input fields after adding the task\n            self.task_entry.delete(0, tk.END)\n            self.category_entry.delete(0, tk.END)\n        else:\n            messagebox.showwarning(\"Input Error\", \"Please fill all fields.\")\n\n    def search_tasks(self, event):\n        \"\"\"Search tasks based on input in the search bar.\"\"\"\n        query = self.search_entry.get().lower()\n        self.task_listbox.delete(0, tk.END)\n        cursor = self.conn.cursor()\n        # Retrieve all tasks and filter by the search query\n        cursor.execute(\"SELECT * FROM tasks WHERE completed=0\")\n        for row in cursor.fetchall():\n            task_str = f\"{row[1]} | {row[2]} | Due: {row[3]} | Priority: {row[4]}\"\n            # Display only tasks that match the search query\n            if query in task_str.lower():\n                self.task_listbox.insert(tk.END, task_str)\n\n    def close_app(self):\n        \"\"\"Close the database connection and exit the application.\"\"\"\n        if self.conn:\n            self.conn.close()\n        self.root.destroy()\n\nif __name__ == \"__main__\":\n    root = tk.Tk()\n    app = TodoApp(root)\n    root.mainloop()\n"
  },
  {
    "path": "To Do List/RithwikBejadi/To Do App/requirements.txt",
    "content": "tkinter==8.6\nsqlite3==3.45.3\n"
  },
  {
    "path": "To Do List/RithwikBejadi/To Do App/runtime.txt",
    "content": "Python 3.12.4"
  },
  {
    "path": "To Do List/main.py",
    "content": "from tkinter import *\nimport sqlite3\n\nroot = Tk()\nroot.title(\"To-Do List App\")\nroot.geometry(\"400x400\")\n\nconn = sqlite3.connect('todolist.db')\nc = conn.cursor()\n\n# Create table\nc.execute('''CREATE TABLE IF NOT EXISTS tasks\n             (id INTEGER PRIMARY KEY, task TEXT NOT NULL)''')\n\ndef add_task():\n    task = task_entry.get()\n    if task:\n        c.execute(\"INSERT INTO tasks (task) VALUES (?)\", (task,))\n        conn.commit()\n        task_entry.delete(0, END)\n        populate_tasks()\n\ndef delete_task():\n    task_id = task_list.get(ACTIVE).split('.')[0]\n    c.execute(\"DELETE FROM tasks WHERE id=?\", (task_id,))\n    conn.commit()\n    populate_tasks()\n\ndef populate_tasks():\n    task_list.delete(0, END)\n    c.execute(\"SELECT * FROM tasks\")\n    tasks = c.fetchall()\n    for task in tasks:\n        task_list.insert(END, f\"{task[0]}. {task[1]}\")\n\n# Task entry\ntask_entry = Entry(root, width=50)\ntask_entry.pack(pady=10)\n\n# Add task button\nadd_task_button = Button(root, text=\"Add Task\", command=add_task)\nadd_task_button.pack(pady=5)\n\n# Task list\ntask_list = Listbox(root, width=50, height=15)\ntask_list.pack(pady=10)\n\n# Delete task button\ndelete_task_button = Button(root, text=\"Delete Task\", command=delete_task)\ndelete_task_button.pack(pady=5)\n\n# Populate tasks on startup\npopulate_tasks()\n\n# Run the main loop\nroot.mainloop()\n\nconn.close()\n"
  },
  {
    "path": "To Do List/requirement.txt",
    "content": "tk\nsqlite3\n"
  },
  {
    "path": "To Do List/runtime.txt",
    "content": "python-3.8.10\n"
  },
  {
    "path": "Translator/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Translator/translate.py",
    "content": "from tabulate import tabulate\nfrom googletrans import Translator\n\nclass TranslateClass(object):\n    def __init__(self, word, lang):\n        self.word = word\n        self.lang = lang\n        self.Trans = Translator(service_urls=[\"translate.google.com\"])\n\n    def __repr__(self):\n        translated = self.Trans.translate(self.word, dest=self.lang).text\n        data = [\n            ['Language:', \"Sentence\"],\n            ['English', self.word],\n            ['Hindi', str(translated)]]\n        table = str(tabulate(data, headers=\"firstrow\", tablefmt=\"grid\"))\n        return table\n\n\nif __name__ == '__main__':\n    translate = input('Enter Sentence: ')\n    language = 'hi'\n    print(TranslateClass(translate, language))"
  },
  {
    "path": "URL Sortener/main.py",
    "content": "import pyshorteners\n\n\ndef shorten_url(url):\n    return pyshorteners.Shortener().tinyurl.short(url)\n\n\nurl = input(\"Please enter URL: \")\nprint(\"URL after Shortening : \", shorten_url(url))\n"
  },
  {
    "path": "URL Sortener/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Validate-Email/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Validate-Email/validate.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Author: Aman Kumar\n# Version: 1.0.0 \n\nimport re\n\nemail_conditions = '^[a-z0-9]+[\\._]?[a-z0-9]+[@]\\w+[.]\\w{2,3}$'\nuser_email = input(\"Enter your email: \")\n\nisValid = re.search(email_conditions, user_email)\n\nif(isValid):\n    print(\"Valid Email\")\nelse:\n    print(\"Invalid Email\")\n"
  },
  {
    "path": "Video Processor/README.md",
    "content": "# Video Processing Tool\r\n\r\nIn 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.\r\n\r\n## Features\r\n\r\n- Extracts clips of a specified duration from the input video.\r\n- Applies image processing effects including brightness, contrast, saturation adjustments, and blurring.\r\n- Generates simple subtitle files for each clip.\r\n\r\n## Requirements\r\n\r\nTo run this script, you'll need the following Python packages:\r\n\r\n- `opencv-python`\r\n- `pysrt`\r\n\r\nYou can install these using pip:\r\n\r\n```bash\r\npip install opencv-python pysrt\r\n```\r\n\r\n## Usage\r\n\r\n1. **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.\r\n   \r\n2. **Clip Duration**: The default duration for each extracted clip is set to 10 seconds. You can modify this value in the script as needed.\r\n\r\n3. **Run the Script**: Execute the script using Python:\r\n\r\n   ```bash\r\n   python video_processor.py\r\n   ```\r\n\r\n4. **Output**: \r\n   - The processed clips will be saved as `clip0_out.mp4`, `clip1_out.mp4`, etc.\r\n   - Corresponding subtitle files will be saved as `clip0_subtitle.srt`, `clip1_subtitle.srt`, etc.\r\n\r\n## Code Explanation\r\n\r\n- **Video Capture**: The script uses OpenCV to read frames from the video.\r\n- **Image Processing**: Each frame within the clip duration is processed using filters and effects:\r\n  - **Brightness and Contrast**: Adjusts the brightness and contrast of the frame.\r\n  - **Saturation**: Modifies the saturation of the frame.\r\n  - **Blurring**: Applies Gaussian blur and combines with a weighted blend for a smoother look.\r\n  \r\n- **Subtitle Generation**: For each clip, a simple subtitle text (\"This is a sample subtitle\") is generated and saved in a `.srt` file format.\r\n\r\n## Limitations\r\n\r\n- The script assumes the video file can be read directly via OpenCV, which may not be applicable for all YouTube links without prior downloading.\r\n- Subtitle text is static; you may want to customize it based on the content of each clip.\r\n\r\n"
  },
  {
    "path": "Video Processor/requirements.txt",
    "content": "opencv-python==4.8.0.76\r\npysrt==1.1.2\r\n"
  },
  {
    "path": "Video Processor/video_processor.py",
    "content": "import cv2\r\nimport pysrt\r\n\r\n# Load the input video\r\ninput_file = input(\"Enter the YouTube video link: \")\r\ncap = cv2.VideoCapture(input_file)\r\n\r\n# Set the start and end times for each short video clip\r\nclip_duration = 10.0\r\nclip_start_time = 0.0\r\nclip_end_time = clip_start_time + clip_duration\r\n\r\n# Set up OpenCV for video processing\r\nkernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))\r\nbrightness = 30\r\ncontrast = 1.5\r\nsaturation = 1.5\r\n\r\n# Process each short video clip\r\ni = 0\r\nwhile cap.isOpened():\r\n    # Read the next frame from the input video\r\n    ret, frame = cap.read()\r\n    if not ret:\r\n        break\r\n    \r\n    # Get the current time in seconds\r\n    current_time = cap.get(cv2.CAP_PROP_POS_MSEC) / 1000.0\r\n    \r\n    # If the current time is within the current clip, process the frame\r\n    if current_time >= clip_start_time and current_time <= clip_end_time:\r\n        # Apply the filters and effects\r\n        frame = cv2.filter2D(frame, -1, kernel)\r\n        frame = cv2.convertScaleAbs(frame, alpha=contrast, beta=brightness)\r\n        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\r\n        h, s, v = cv2.split(frame)\r\n        s = cv2.convertScaleAbs(s, alpha=saturation, beta=0)\r\n        frame = cv2.merge((h, s, v))\r\n        frame = cv2.cvtColor(frame, cv2.COLOR_HSV2BGR)\r\n        frame = cv2.GaussianBlur(frame, (5,5), 0)\r\n        frame = cv2.addWeighted(frame, 1.5, cv2.blur(frame, (10,10)), -0.5, 0)\r\n        \r\n        # Write the modified frame to a new video file\r\n        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))))\r\n        out.write(frame)\r\n        out.release()\r\n        \r\n        # Generate subtitles for the clip\r\n        subtitle_text = \"This is a sample subtitle\"\r\n        subtitle_duration = clip_duration\r\n        subtitle_file = pysrt.SubRipFile()\r\n        subtitle = pysrt.SubRipItem(index=1, start=0, end=subtitle_duration, text=subtitle_text)\r\n        subtitle_file.append(subtitle)\r\n        subtitle_file.save('clip' + str(i) + '_subtitle.srt')\r\n        \r\n        # Move to the next clip\r\n        i += 1\r\n        clip_start_time += clip_duration\r\n        clip_end_time += clip_duration\r\n    \r\n    # If the current time is past the end of the current clip, move to the next clip\r\n    elif current_time > clip_end_time:\r\n        clip_start_time += clip_duration\r\n        clip_end_time += clip_duration\r\n\r\n# Release the resources\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n"
  },
  {
    "path": "Video To Audio/main.py",
    "content": "import moviepy\nfrom tkinter.filedialog import *\n\naskForVideo = askopenfilename()\nvideo = moviepy.editor.VideoFileClip(askForVideo)\n\naudio = video.audio\naudio.write_audiofile(\"demo.mp3\")\n\nprint(\"Conversion Completed !!\")\n"
  },
  {
    "path": "Video To Audio/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Weather Alert/README.md",
    "content": "# Weather Alert Script 🌦️\n\nA 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! 🚀\n\n## Features\n\n- **Fetch Weather Data**: Retrieves up-to-date weather information for any city using the OpenWeatherMap API.\n- **Custom Alerts**: Set your own temperature and wind speed thresholds. If the weather conditions exceed these, the script will alert you!\n- **Hourly Updates**: The script automatically checks the weather every hour, so you’re always in the loop.\n\n## Getting Started\n\n### Prerequisites\n\n- Python 3.x\n- `requests` and `python-dotenv` libraries\n\nInstall the required libraries using:\n\n```bash\npip install requests python-dotenv\n```\n\n## Setup\n\n- Clone or download this repository.\n- Get an API key from OpenWeatherMap. (It’s free!)\n- Create a .env file in the root directory and add your API key like shown in `.env.example`\n- Run the script\n\n```\npython weather_alert.py\n```\n\n## Troubleshooting\n\n- 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.\n- Error fetching data: This could happen if the API key is incorrect or if the city name is misspelled. Verify both and try again.\n"
  },
  {
    "path": "Weather Alert/main.py",
    "content": "import requests\nimport json\nimport time\nimport os\nfrom dotenv import load_dotenv\n\n# Load environment variables from .env file\nload_dotenv()\n\n# Load API key from environment variable (security fix)\nAPI_KEY = os.getenv('OPEN_WEATHER_MAP_API_KEY')\n\nif not API_KEY:\n    raise ValueError(\"Missing environment variable 'OPEN_WEATHER_MAP_API_KEY'\")\n\nUNIT = 'metric'\nBASE_URL = 'https://api.openweathermap.org/data/2.5/find'\n\n\ndef fetch_weather(city):\n    \"\"\"Fetches weather data for a given city.\n\n    Args:\n        city (str): Name of the city.\n\n    Returns:\n        dict: Weather data if successful, None otherwise.\n    \"\"\"\n\n    url = f\"{BASE_URL}?q={city}&appid={API_KEY}&units={UNIT}\"\n    response = requests.get(url)\n\n    if response.status_code == 200:\n        return response.json()\n    else:\n        print(f\"Error fetching data: {response.status_code}\")\n        return None\n\n\ndef check_alerts(data, temp_threshold, wind_speed_threshold):\n    \"\"\"Checks for temperature and wind speed alerts in weather data.\n\n    Args:\n        data (dict): Weather data.\n        temp_threshold (float): Temperature threshold in °C.\n        wind_speed_threshold (float): Wind speed threshold in m/s.\n\n    Prints alerts if any, otherwise prints a message indicating normal weather conditions.\n    \"\"\"\n\n    if not data or 'list' not in data or not data['list']:\n        print(\"No data available to check alerts.\")\n        return\n\n    weather_info = data['list'][0]\n    temp = weather_info['main']['temp']\n    wind_speed = weather_info['wind']['speed']\n\n    alerts = []\n    if temp > temp_threshold:\n        alerts.append(f\"Temperature alert! Current temperature: {temp}°C\")\n    if wind_speed > wind_speed_threshold:\n        alerts.append(f\"Wind speed alert! Current wind speed: {wind_speed} m/s\")\n\n    if alerts:\n        print(\"\\n\".join(alerts))\n    else:\n        print(\"No alerts. Weather conditions are normal.\")\n\n\ndef main():\n    \"\"\"Prompts user for city name, temperature and wind speed thresholds,\n    and continuously checks for alerts.\n    \"\"\"\n\n    city = input(\"Enter city name: \")\n    temp_threshold = float(input(\"Enter temperature threshold (°C): \"))\n    wind_speed_threshold = float(input(\"Enter wind speed threshold (m/s): \"))\n\n    while True:\n        weather_data = fetch_weather(city)\n        check_alerts(weather_data, temp_threshold, wind_speed_threshold)\n        print(\"Waiting for the next check...\")\n        time.sleep(3600)  # check every hour\n\n\nif __name__ == \"__main__\":\n    main()"
  },
  {
    "path": "Weather Alert/requirement.txt",
    "content": "requests\npython-dotenv"
  },
  {
    "path": "Weather Alert/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Word_frequency_counter/README.md",
    "content": "# Word Frequency Counter\n\nA 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.\n\n---\n\n- **Input :** Path of the text file to be processed\n- **Output :** List of top 10 words according to their frequency, along with their frequency of occurence.\n\n---\n\n## Features :\n\n- User friendly interface\n- Output is in tabular format\n- Case insensitive processing of words\n- Get the Top 10 words in the text file which occur most frequntly, along with their counts\n\n---\n\n## Usage :\n\n1. Clone the repository\n2. Navigate to the project folder\n3. Run the command :\n\n```python\npython3 main.py\n```"
  },
  {
    "path": "Word_frequency_counter/main.py",
    "content": "import regex as re\nfrom collections import Counter\n\ndef find_words_frequency(file_path):\n    '''\n    This script takes the path of the text file to be processed as input\n    and prints the top ten words and also prints their counts in the given text file.\n    '''\n    with open(file_path, 'r', encoding='utf-8') as file:\n        text = file.read().lower()\n\n    # Use `regex`'s findall function\n    all_words = re.findall(r'\\b\\p{L}+\\b', text)\n    word_frequency = Counter(all_words)\n    most_common_words = word_frequency.most_common(10)\n\n    # Print in tabular format\n    print(f\"{'Word':<15} {'Count':<5}\")\n    print(\"-\" * 20)\n    for word, count in most_common_words:\n        print(f\"{word:<15} {count:<5}\")\n\ndef main():\n    file_path = input(\"Enter the path of file : \")\n    find_words_frequency(file_path)\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "Word_frequency_counter/requirments.txt",
    "content": "regex=2.5.147\n"
  },
  {
    "path": "Word_frequency_counter/runtime.txt",
    "content": "python-3.10.7"
  },
  {
    "path": "Youtube Video Downloader/Readme.md",
    "content": " # YouTube Video Downloader with yt-dlp Integration\n\n## Project Overview\n\nThis 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.\n\n## Features\n\n- **Download YouTube Videos**: Download videos in various resolutions (360p, 720p, 1080p, etc.).\n- **Audio Extraction**: Extract and download only the audio from a YouTube video.\n- **Multiple Formats**: Support for multiple video formats like MP4, WebM, and audio formats like MP3, M4A.\n- **Batch Downloading**: Download multiple videos at once by providing a list of URLs.\n- **Simple Command-Line Interface**: Easy-to-use command-line input for seamless user experience.\n\n## Technologies Used\n\n- **Python**: The core programming language.\n- **yt-dlp**: The powerful Python package used for downloading videos and audio from YouTube and other platforms.\n\n## Installation\n\nTo get started with this project, follow these steps:\n\n1. **Clone the Repository**:\n   ```bash\n   git clone https://github.com/yourusername/YouTube-Video-Downloader.git\n"
  },
  {
    "path": "Youtube Video Downloader/main.py",
    "content": "import yt_dlp\n\ndef download_video(url, resolution='highest'):\n    try:\n        # Set yt-dlp options for video download\n        ydl_opts = {\n            'format': f'bestvideo[height<={resolution}]+bestaudio/best[height<={resolution}]' if resolution != 'highest' else 'best',\n            'outtmpl': '%(title)s.%(ext)s',  # Output file name template\n        }\n\n        # Download video with yt-dlp\n        with yt_dlp.YoutubeDL(ydl_opts) as ydl:\n            ydl.download([url])\n        print(\"Download completed!\")\n    except Exception as e:\n        print(f\"Error: {e}\")\n\nif __name__ == \"__main__\":\n    video_url = input(\"Enter YouTube URL: \")\n    video_resolution = input(\"Enter resolution (e.g., 720p or leave blank for highest): \").strip()\n\n    # Download the video with specified resolution\n    download_video(video_url, video_resolution or 'highest')\n"
  },
  {
    "path": "Youtube Video Downloader/requirements.txt",
    "content": "yt-dlp\n    "
  },
  {
    "path": "Youtube Video Downloader/runtime.txt",
    "content": "python-3.10.12\n"
  },
  {
    "path": "personal-finance-tracker/README.md",
    "content": "Personal Finance Tracker\n\nProject Overview:\nThe 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.\n\nFeatures:\nAdd Income: Record income entries with descriptions and amounts.\nAdd Expense: Record expenses, categorize them, and add descriptions.\nView Summary: View a summary of total income, expenses, and balance.\nSet Savings Goals: Define and track savings goals.\nVisualize Spending: Generate various charts (bar chart, pie chart, line chart, etc.) to better understand your spending habits.\n\nTechnologies Used:\nPython: Core programming language.\nSQLite3: Local database for storing transaction records.\nMatplotlib: Python library for generating visualizations.\n\n\nTo run the program:\n1] Clone the repository\n2] Navigate to Personal Finance Tracker folder\n3] Run the main.py file\n\nWhen you run the application, a menu will appear with the following options:\n\nAdd Income: Enter the amount and description of your income.\nAdd Expense: Enter the amount, category, and description of the expense.\nView Summary: See your total income, expenses, and remaining balance.\nSet Savings Goal: Set a savings goal to track progress.\nVisualize Spending: Choose from various charts to visualize your spending patterns."
  },
  {
    "path": "personal-finance-tracker/database.py",
    "content": "import sqlite3\n\nDB_FILE = \"data/finance.db\"\n\ndef get_connection():\n    conn = sqlite3.connect(DB_FILE)\n    return conn\n\ndef initialize_database():\n    conn = get_connection()\n    cursor = conn.cursor()\n\n    # Create income and expense table\n    cursor.execute('''\n        CREATE TABLE IF NOT EXISTS transactions (\n            id INTEGER PRIMARY KEY AUTOINCREMENT,\n            type TEXT NOT NULL,\n            category TEXT NOT NULL,\n            amount REAL NOT NULL,\n            date TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n        )\n    ''')\n\n    # Create table for savings goal\n    cursor.execute('''\n        CREATE TABLE IF NOT EXISTS savings_goal (\n            id INTEGER PRIMARY KEY,\n            goal_amount REAL NOT NULL\n        )\n    ''')\n\n    conn.commit()\n    conn.close()\n"
  },
  {
    "path": "personal-finance-tracker/main.py",
    "content": "import tracker\nimport savings\nimport visualization\nimport database\n\ndef main_menu():\n    while True:\n        print(\"\\n--- Personal Finance Tracker ---\")\n        print(\"1. Add Income\")\n        print(\"2. Add Expense\")\n        print(\"3. View Summary\")\n        print(\"4. Set Savings Goal\")\n        print(\"5. Visualize Spending\")\n        print(\"6. Exit\")\n        \n        choice = input(\"Choose an option: \")\n\n        if choice == \"1\":\n            tracker.add_income()\n        elif choice == \"2\":\n            tracker.add_expense()\n        elif choice == \"3\":\n            tracker.view_summary()\n        elif choice == \"4\":\n            savings.set_goal()\n        elif choice == \"5\":\n            visualization.visualize_data()\n        elif choice == \"6\":\n            print(\"Exiting...\")\n            break\n        else:\n            print(\"Invalid option. Please try again.\")\n\nif __name__ == \"__main__\":\n    database.initialize_database() \n    main_menu()\n"
  },
  {
    "path": "personal-finance-tracker/savings.py",
    "content": "from database import get_connection\n\ndef set_goal():\n    goal_amount = float(input(\"Enter your savings goal: \"))\n    \n    conn = get_connection()\n    cursor = conn.cursor()\n    \n    cursor.execute(\"INSERT OR REPLACE INTO savings_goal (id, goal_amount) VALUES (1, ?)\", (goal_amount,))\n    conn.commit()\n    conn.close()\n    \n    print(f\"Savings goal of {goal_amount} set successfully!\")\n\ndef track_savings_progress(balance):\n    conn = get_connection()\n    cursor = conn.cursor()\n    \n    cursor.execute(\"SELECT goal_amount FROM savings_goal WHERE id = 1\")\n    goal_row = cursor.fetchone()\n    conn.close()\n    \n    if goal_row:\n        goal_amount = goal_row[0]\n        remaining = goal_amount - balance\n        if remaining > 0:\n            print(f\"You need to save {remaining} more to reach your goal.\")\n        else:\n            print(f\"Congratulations! You've reached your savings goal.\")\n    else:\n        print(\"No savings goal set.\")\n"
  },
  {
    "path": "personal-finance-tracker/tracker.py",
    "content": "import sqlite3\nfrom database import get_connection\n\ndef add_income():\n    category = input(\"Enter income source (e.g., Salary, Freelance): \")\n    amount = float(input(\"Enter amount: \"))\n    \n    conn = get_connection()\n    cursor = conn.cursor()\n    \n    cursor.execute(\"INSERT INTO transactions (type, category, amount) VALUES (?, ?, ?)\", \n                   (\"Income\", category, amount))\n    conn.commit()\n    conn.close()\n    \n    print(\"Income added successfully!\")\n\ndef add_expense():\n    category = input(\"Enter expense category (e.g., Rent, Groceries): \")\n    amount = float(input(\"Enter amount: \"))\n    \n    conn = get_connection()\n    cursor = conn.cursor()\n    \n    cursor.execute(\"INSERT INTO transactions (type, category, amount) VALUES (?, ?, ?)\", \n                   (\"Expense\", category, amount))\n    conn.commit()\n    conn.close()\n    \n    print(\"Expense added successfully!\")\n\ndef view_summary():\n    conn = get_connection()\n    cursor = conn.cursor()\n    \n    cursor.execute(\"SELECT SUM(amount) FROM transactions WHERE type = 'Income'\")\n    total_income = cursor.fetchone()[0] or 0.0\n    \n    cursor.execute(\"SELECT SUM(amount) FROM transactions WHERE type = 'Expense'\")\n    total_expenses = cursor.fetchone()[0] or 0.0\n    \n    balance = total_income - total_expenses\n    \n    conn.close()\n    \n    print(f\"\\nTotal Income: {total_income}\")\n    print(f\"Total Expenses: {total_expenses}\")\n    print(f\"Balance: {balance}\")\n"
  },
  {
    "path": "personal-finance-tracker/visualization.py",
    "content": "import matplotlib.pyplot as plt\nfrom database import get_connection\n\ndef bar_chart_expense():\n    conn = get_connection()\n    cursor = conn.cursor()\n    \n    cursor.execute(\"SELECT category, SUM(amount) FROM transactions WHERE type = 'Expense' GROUP BY category\")\n    rows = cursor.fetchall()\n    conn.close()\n    \n    if rows:\n        categories = [row[0] for row in rows]\n        amounts = [row[1] for row in rows]\n        \n        plt.bar(categories, amounts)\n        plt.xlabel('Category')\n        plt.ylabel('Amount')\n        plt.title('Spending by Category')\n        plt.xticks(rotation=45)\n        plt.tight_layout()\n        plt.show()\n    else:\n        print(\"No expenses recorded yet.\")\n\ndef pie_chart_expense():\n    conn = get_connection()\n    cursor = conn.cursor()\n    \n    cursor.execute(\"SELECT category, SUM(amount) FROM transactions WHERE type = 'Expense' GROUP BY category\")\n    rows = cursor.fetchall()\n    conn.close()\n    \n    if rows:\n        categories = [row[0] for row in rows]\n        amounts = [row[1] for row in rows]\n        \n        plt.pie(amounts, labels=categories, autopct='%1.1f%%', startangle=90)\n        plt.title('Spending by Category')\n        plt.tight_layout()\n        plt.show()\n    else:\n        print(\"No expenses recorded yet.\")\n\ndef line_chart_expense_over_time():\n    conn = get_connection()\n    cursor = conn.cursor()\n    \n    cursor.execute(\"SELECT date, SUM(amount) FROM transactions WHERE type = 'Expense' GROUP BY date\")\n    rows = cursor.fetchall()\n    conn.close()\n    \n    if rows:\n        dates = [row[0] for row in rows]\n        amounts = [row[1] for row in rows]\n        \n        plt.plot(dates, amounts, marker='o')\n        plt.xlabel('Date')\n        plt.ylabel('Amount')\n        plt.title('Expenses Over Time')\n        plt.xticks(rotation=45)\n        plt.tight_layout()\n        plt.show()\n    else:\n        print(\"No expenses recorded yet.\")\n\ndef stacked_bar_chart_income_expense():\n    conn = get_connection()\n    cursor = conn.cursor()\n\n    cursor.execute(\"SELECT date, SUM(amount) FROM transactions WHERE type = 'Income' GROUP BY date\")\n    income_rows = cursor.fetchall()\n\n    cursor.execute(\"SELECT date, SUM(amount) FROM transactions WHERE type = 'Expense' GROUP BY date\")\n    expense_rows = cursor.fetchall()\n    \n    conn.close()\n\n    if income_rows and expense_rows:\n        income_dates = [row[0] for row in income_rows]\n        income_amounts = [row[1] for row in income_rows]\n        expense_dates = [row[0] for row in expense_rows]\n        expense_amounts = [row[1] for row in expense_rows]\n\n        plt.bar(income_dates, income_amounts, label='Income')\n        plt.bar(expense_dates, expense_amounts, bottom=income_amounts, label='Expense')\n\n        plt.xlabel('Date')\n        plt.ylabel('Amount')\n        plt.title('Income vs Expenses Over Time')\n        plt.xticks(rotation=45)\n        plt.legend()\n        plt.tight_layout()\n        plt.show()\n    else:\n        print(\"Not enough data to generate this chart.\")\n\ndef histogram_expense_distribution():\n    conn = get_connection()\n    cursor = conn.cursor()\n\n    cursor.execute(\"SELECT amount FROM transactions WHERE type = 'Expense'\")\n    rows = cursor.fetchall()\n    conn.close()\n\n    if rows:\n        amounts = [row[0] for row in rows]\n\n        plt.hist(amounts, bins=10)\n        plt.xlabel('Expense Amount')\n        plt.ylabel('Frequency')\n        plt.title('Expense Distribution')\n        plt.tight_layout()\n        plt.show()\n    else:\n        print(\"No expenses recorded yet.\")\n\ndef visualize_data():\n    print(\"\\n--- Visualization Menu ---\")\n    print(\"1. Bar Chart (Spending by Category)\")\n    print(\"2. Pie Chart (Spending by Category)\")\n    print(\"3. Line Chart (Expenses Over Time)\")\n    print(\"4. Stacked Bar Chart (Income vs Expenses)\")\n    print(\"5. Histogram (Expense Distribution)\")\n    \n    choice = input(\"Select a visualization option (1-5): \")\n\n    if choice == \"1\":\n        bar_chart_expense()\n    elif choice == \"2\":\n        pie_chart_expense()\n    elif choice == \"3\":\n        line_chart_expense_over_time()\n    elif choice == \"4\":\n        stacked_bar_chart_income_expense()\n    elif choice == \"5\":\n        histogram_expense_distribution()\n    else:\n        print(\"Invalid choice. Please select a valid option.\")\n"
  }
]