├── .env.example ├── .github ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── dependabot.yml └── workflows │ ├── auto-assign.yaml │ ├── doc-gen.yml │ └── greeting.yaml ├── .gitignore ├── .pre-commit-config.yaml ├── .readthedocs.yml ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Kolkata_Murder_case_2024-08-21.json ├── LICENSE ├── README.md ├── __init__.py ├── docs ├── Makefile ├── conf.py ├── index.rst ├── make.bat ├── modules.rst ├── src.dashboard.rst ├── src.ingestion.rst ├── src.preprocessing.rst ├── src.rst ├── src.sentiment_analysis.rst └── src.utils.rst ├── requirements.txt ├── src ├── __init__.py ├── dashboard │ ├── __init__.py │ ├── app.py │ └── requirements.txt ├── ingestion │ ├── __init__.py │ ├── fetch_articles.py │ ├── newsapi.py │ └── prawapi.py ├── pipeline.py ├── preprocessing │ ├── __init__.py │ ├── keyword_extraction.py │ └── summarization.py ├── sentiment_analysis │ ├── __init__.py │ ├── classify.py │ ├── sentiment_model.py │ └── wordcloud.py ├── styles.css └── utils │ ├── __init__.py │ ├── dbconnector.py │ └── logger.py └── wordcloud.png /.env.example: -------------------------------------------------------------------------------- 1 | REDDIT_USERNAME='run' 2 | REDDIT_PASSWORD='rup' 3 | REDDIT_CLIENTID='rcid' 4 | REDDIT_SECRETKEY='PTabcdefgdvuwsaJyWWWWxal99AbBbc' 5 | REDDIT_APPNAME='MyApp' 6 | GEMINI_API_KEY='api-key-here' 7 | NEWS_API_KEY='thats-my-api-key' 8 | MONGO_USERNAME='username' 9 | MONGO_PASSWORD='mongodb-password' 10 | DB_NAME='db_name' -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "pip" # See documentation for possible values 4 | directory: "/" # Location of package manifests 5 | schedule: 6 | interval: "weekly" 7 | -------------------------------------------------------------------------------- /.github/workflows/auto-assign.yaml: -------------------------------------------------------------------------------- 1 | name: Auto Assign 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | 7 | jobs: 8 | run: 9 | runs-on: ubuntu-latest 10 | 11 | permissions: 12 | issues: write 13 | pull-requests: write 14 | actions: read 15 | 16 | steps: 17 | - name: 'Auto-assign issue creator' 18 | uses: pozil/auto-assign-issue@v1 19 | with: 20 | repo-token: ${{ secrets.GITHUB_TOKEN }} 21 | assignees: ${{ github.event.issue.user.login }} # Assign the issue creator 22 | numOfAssignee: 1 23 | -------------------------------------------------------------------------------- /.github/workflows/doc-gen.yml: -------------------------------------------------------------------------------- 1 | name: Deploy Sphinx documentation to Pages 2 | 3 | on: 4 | # Triggers deployment on push to the master branch 5 | push: 6 | branches: [main, fix/sphinx-docs-pipeline] 7 | 8 | jobs: 9 | pages: 10 | runs-on: ubuntu-20.04 11 | environment: 12 | name: github-pages 13 | url: ${{ steps.deployment.outputs.page_url }} 14 | permissions: 15 | pages: write 16 | id-token: write 17 | 18 | steps: 19 | # Step 1: Checkout the repository 20 | - name: Checkout 21 | uses: actions/checkout@v4 22 | 23 | # Step 2: Set up Sphinx and deploy to GitHub Pages using the sphinx-notes/pages action 24 | - id: deployment 25 | uses: sphinx-notes/pages@v3 26 | with: 27 | # Path to your documentation (change to your docs folder) 28 | docs-folder: docs/ 29 | # Python dependencies to install, including any needed for building the documentation 30 | extra-requirements: requirements.txt 31 | requirements_path: requirements.txt 32 | # Optional: include this if using a custom Sphinx config 33 | sphinx-builder: html 34 | -------------------------------------------------------------------------------- /.github/workflows/greeting.yaml: -------------------------------------------------------------------------------- 1 | name: Advanced Greetings 2 | 3 | 4 | on: 5 | pull_request_target: 6 | types: [opened] 7 | issues: 8 | types: [opened] 9 | 10 | 11 | jobs: 12 | greeting: 13 | runs-on: ubuntu-latest 14 | permissions: 15 | issues: write 16 | pull-requests: write 17 | steps: 18 | - name: Check if First-Time Contributor 19 | id: first-time 20 | uses: actions/first-interaction@v1 21 | with: 22 | repo-token: ${{ secrets.GITHUB_TOKEN }} 23 | issue-message: '' 24 | pr-message: '' 25 | 26 | 27 | - name: Set Greeting Message 28 | id: set-message 29 | run: | 30 | if [[ "${{ github.event_name }}" == "issues" ]]; then 31 | if [[ "${{ steps.first-time.outputs.first-time-contributor }}" == "true" ]]; then 32 | echo "message=👋 Welcome, first-time contributor! Thanks for raising an issue. Our team will review it shortly. Stay tuned! 🚀" >> $GITHUB_OUTPUT 33 | else 34 | echo "message=🔄 Thanks for your continued contribution! We appreciate your help in improving the project. Our team will look into the issue soon!" >> $GITHUB_OUTPUT 35 | fi 36 | elif [[ "${{ github.event_name }}" == "pull_request_target" ]]; then 37 | if [[ "${{ steps.first-time.outputs.first-time-contributor }}" == "true" ]]; then 38 | echo "message=🎉 Welcome to your first pull request! We appreciate your contribution and will review it soon. Let's make this project even better together! 🌟" >> $GITHUB_OUTPUT 39 | else 40 | echo "message=👏 Great to see you again! Thanks for another awesome PR. We will review it as soon as possible. You're helping us improve with every contribution!" >> $GITHUB_OUTPUT 41 | fi 42 | fi 43 | - name: Post Greeting 44 | uses: actions/github-script@v6 45 | with: 46 | github-token: ${{ secrets.GITHUB_TOKEN }} 47 | script: | 48 | const message = "${{ steps.set-message.outputs.message }}"; 49 | if (context.eventName === 'issues') { 50 | github.rest.issues.createComment({ 51 | issue_number: context.issue.number, 52 | owner: context.repo.owner, 53 | repo: context.repo.repo, 54 | body: message 55 | }); 56 | } else if (context.eventName === 'pull_request_target') { 57 | github.rest.pulls.createReview({ 58 | pull_number: context.issue.number, 59 | owner: context.repo.owner, 60 | repo: context.repo.repo, 61 | body: message, 62 | event: 'COMMENT' 63 | }); 64 | } 65 | 66 | - name: Post Maintainer Welcome (Optional) 67 | if: github.actor == 'MaintainerUsername' 68 | run: | 69 | echo "message=🙌 Welcome back, maintainer! Thanks for reviewing and supporting this project!" >> $GITHUB_OUTPUT 70 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Sphinx 55 | _build/ 56 | _static/ 57 | _templates/ 58 | .vscode/ 59 | 60 | # Translations 61 | *.mo 62 | *.pot 63 | 64 | # Django stuff: 65 | *.log 66 | log.* 67 | app.* 68 | mygif.gif 69 | local_settings.py 70 | db.sqlite3 71 | db.sqlite3-journal 72 | 73 | # Flask stuff: 74 | instance/ 75 | .webassets-cache 76 | 77 | # Scrapy stuff: 78 | .scrapy 79 | 80 | # Sphinx documentation 81 | docs/_build/ 82 | 83 | # PyBuilder 84 | .pybuilder/ 85 | target/ 86 | 87 | # Jupyter Notebook 88 | .ipynb_checkpoints 89 | 90 | # IPython 91 | profile_default/ 92 | ipython_config.py 93 | 94 | # pyenv 95 | # For a library or package, you might want to ignore these files since the code is 96 | # intended to run in multiple environments; otherwise, check them in: 97 | # .python-version 98 | 99 | # pipenv 100 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 101 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 102 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 103 | # install all needed dependencies. 104 | #Pipfile.lock 105 | 106 | # poetry 107 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 108 | # This is especially recommended for binary packages to ensure reproducibility, and is more 109 | # commonly ignored for libraries. 110 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 111 | #poetry.lock 112 | 113 | # pdm 114 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 115 | #pdm.lock 116 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 117 | # in version control. 118 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 119 | .pdm.toml 120 | .pdm-python 121 | .pdm-build/ 122 | 123 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 124 | __pypackages__/ 125 | 126 | # Celery stuff 127 | celerybeat-schedule 128 | celerybeat.pid 129 | 130 | # SageMath parsed files 131 | *.sage.py 132 | 133 | # Environments 134 | .env 135 | .venv 136 | env/ 137 | venv/ 138 | ENV/ 139 | env.bak/ 140 | venv.bak/ 141 | 142 | # Spyder project settings 143 | .spyderproject 144 | .spyproject 145 | 146 | # Rope project settings 147 | .ropeproject 148 | 149 | # mkdocs documentation 150 | /site 151 | 152 | # mypy 153 | .mypy_cache/ 154 | .dmypy.json 155 | dmypy.json 156 | 157 | # Pyre type checker 158 | .pyre/ 159 | 160 | # pytype static type analyzer 161 | .pytype/ 162 | 163 | # Cython debug symbols 164 | cython_debug/ 165 | 166 | # PyCharm 167 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 168 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 169 | # and can be added to the global gitignore or merged into this file. For a more nuclear 170 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 171 | #.idea/ 172 | app.log.5 173 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/psf/black 3 | rev: 24.8.0 # Use the latest stable version of Black 4 | hooks: 5 | - id: black 6 | 7 | - repo: https://github.com/pycqa/isort 8 | rev: 5.13.2 9 | hooks: 10 | - id: isort 11 | 12 | - repo: https://github.com/hhatto/autopep8 13 | rev: v2.3.1 # Use the latest stable version of autopep8 14 | hooks: 15 | - id: autopep8 16 | -------------------------------------------------------------------------------- /.readthedocs.yml: -------------------------------------------------------------------------------- 1 | # .readthedocs.yaml 2 | 3 | # Required 4 | version: 2 5 | 6 | # Set the version of Python and other tools you might need 7 | build: 8 | os: ubuntu-22.04 9 | tools: 10 | python: "3.12" 11 | 12 | # Build documentation in the docs/ directory with Sphinx 13 | sphinx: 14 | configuration: docs/conf.py 15 | 16 | # Optionally declare the Python requirements required to build your docs 17 | python: 18 | install: 19 | - requirements: requirements.txt -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our 6 | community a harassment-free experience for everyone, regardless of age, body 7 | size, visible or invisible disability, ethnicity, sex characteristics, gender 8 | identity and expression, level of experience, education, socio-economic status, 9 | nationality, personal appearance, race, religion, or sexual identity 10 | and orientation. 11 | 12 | We pledge to act and interact in ways that contribute to an open, welcoming, 13 | diverse, inclusive, and healthy community. 14 | 15 | ## Our Standards 16 | 17 | Examples of behavior that contributes to a positive environment for our 18 | community include: 19 | 20 | * Demonstrating empathy and kindness toward other people 21 | * Being respectful of differing opinions, viewpoints, and experiences 22 | * Giving and gracefully accepting constructive feedback 23 | * Accepting responsibility and apologizing to those affected by our mistakes, 24 | and learning from the experience 25 | * Focusing on what is best not just for us as individuals, but for the 26 | overall community 27 | 28 | Examples of unacceptable behavior include: 29 | 30 | * The use of sexualized language or imagery, and sexual attention or 31 | advances of any kind 32 | * Trolling, insulting or derogatory comments, and personal or political attacks 33 | * Public or private harassment 34 | * Publishing others' private information, such as a physical or email 35 | address, without their explicit permission 36 | * Other conduct which could reasonably be considered inappropriate in a 37 | professional setting 38 | 39 | ## Enforcement Responsibilities 40 | 41 | Community leaders are responsible for clarifying and enforcing our standards of 42 | acceptable behavior and will take appropriate and fair corrective action in 43 | response to any behavior that they deem inappropriate, threatening, offensive, 44 | or harmful. 45 | 46 | Community leaders have the right and responsibility to remove, edit, or reject 47 | comments, commits, code, wiki edits, issues, and other contributions that are 48 | not aligned to this Code of Conduct, and will communicate reasons for moderation 49 | decisions when appropriate. 50 | 51 | ## Scope 52 | 53 | This Code of Conduct applies within all community spaces, and also applies when 54 | an individual is officially representing the community in public spaces. 55 | Examples of representing our community include using an official e-mail address, 56 | posting via an official social media account, or acting as an appointed 57 | representative at an online or offline event. 58 | 59 | ## Enforcement 60 | 61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 62 | reported to the community leaders responsible for enforcement at 63 | . 64 | All complaints will be reviewed and investigated promptly and fairly. 65 | 66 | All community leaders are obligated to respect the privacy and security of the 67 | reporter of any incident. 68 | 69 | ## Enforcement Guidelines 70 | 71 | Community leaders will follow these Community Impact Guidelines in determining 72 | the consequences for any action they deem in violation of this Code of Conduct: 73 | 74 | ### 1. Correction 75 | 76 | **Community Impact**: Use of inappropriate language or other behavior deemed 77 | unprofessional or unwelcome in the community. 78 | 79 | **Consequence**: A private, written warning from community leaders, providing 80 | clarity around the nature of the violation and an explanation of why the 81 | behavior was inappropriate. A public apology may be requested. 82 | 83 | ### 2. Warning 84 | 85 | **Community Impact**: A violation through a single incident or series 86 | of actions. 87 | 88 | **Consequence**: A warning with consequences for continued behavior. No 89 | interaction with the people involved, including unsolicited interaction with 90 | those enforcing the Code of Conduct, for a specified period of time. This 91 | includes avoiding interactions in community spaces as well as external channels 92 | like social media. Violating these terms may lead to a temporary or 93 | permanent ban. 94 | 95 | ### 3. Temporary Ban 96 | 97 | **Community Impact**: A serious violation of community standards, including 98 | sustained inappropriate behavior. 99 | 100 | **Consequence**: A temporary ban from any sort of interaction or public 101 | communication with the community for a specified period of time. No public or 102 | private interaction with the people involved, including unsolicited interaction 103 | with those enforcing the Code of Conduct, is allowed during this period. 104 | Violating these terms may lead to a permanent ban. 105 | 106 | ### 4. Permanent Ban 107 | 108 | **Community Impact**: Demonstrating a pattern of violation of community 109 | standards, including sustained inappropriate behavior, harassment of an 110 | individual, or aggression toward or disparagement of classes of individuals. 111 | 112 | **Consequence**: A permanent ban from any sort of public interaction within 113 | the community. 114 | 115 | ## Attribution 116 | 117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], 118 | version 2.0, available at 119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 120 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing Guidelines 2 | 3 | We welcome contributions to this project! To ensure a smooth collaboration, please follow these guidelines. 4 | 5 | ## How to Contribute 6 | 7 | ### 1. Fork the Repository 8 | - Click on the "Fork" button at the top right corner of this page. 9 | - Clone your forked repository to your local machine: 10 | ```bash 11 | git clone https://github.com/your-username/repo-name.git 12 | ``` 13 | 14 | ### 2. Create a Branch 15 | - Create a new branch for your feature or bug fix: 16 | ```bash 17 | git checkout -b your-branch-name 18 | ``` 19 | 20 | ### 3. Make Your Changes 21 | - Make the necessary changes in your local branch. 22 | - Ensure that your code adheres to the project's coding standards. 23 | 24 | ### 4. Test Your Changes 25 | - Run tests to confirm that your changes work as expected. 26 | - If applicable, add new tests for any new features. 27 | 28 | ### 5. Commit Your Changes 29 | - Commit your changes with a descriptive message: 30 | ```bash 31 | git commit -m "Brief description of your changes" 32 | ``` 33 | 34 | ### 6. Push to Your Fork 35 | - Push your changes back to your forked repository: 36 | ```bash 37 | git push origin your-branch-name 38 | ``` 39 | 40 | ### 7. Create a Pull Request 41 | - Navigate to the original repository where you want to contribute. 42 | - Click on the "New Pull Request" button. 43 | - Select your branch from the drop-down menu and create the pull request. 44 | 45 | ## Code of Conduct 46 | Please adhere to our [Code of Conduct](https://github.com/Devasy23/NewsAI/tree/main?tab=coc-ov-file) while contributing. 47 | 48 | ## Issues 49 | If you find a bug or have a feature request, please open an issue in the repository. Be sure to include relevant details and steps to reproduce the issue. 50 | 51 | ## Documentation 52 | If you are making changes to the documentation, please ensure it is clear and up-to-date. 53 | 54 | ## Thank You! 55 | Thank you for your interest in contributing to this project! Your help is greatly appreciated. 56 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | NewsAI Logo 3 |

🚀 NewsAI: Where AI Meets Breaking News! 🌟

4 |

Buckle up, news junkies! We're about to take you on a wild ride through the information superhighway! 🎢

5 | 6 | ![GitHub stars](https://img.shields.io/github/stars/Multiverse-of-Projects/NewsAI?style=social) 7 | ![GitHub forks](https://img.shields.io/github/forks/Multiverse-of-Projects/NewsAI?style=social) 8 | ![GitHub watchers](https://img.shields.io/github/watchers/Multiverse-of-Projects/NewsAI?style=social) 9 | ![GitHub contributors](https://img.shields.io/github/contributors/Multiverse-of-Projects/NewsAI) 10 | ![GitHub last commit](https://img.shields.io/github/last-commit/Multiverse-of-Projects/NewsAI) 11 | [![Documentation Status](https://readthedocs.org/projects/newsai/badge/?version=latest)](https://newsai.readthedocs.io/en/latest/?badge=latest) 12 |
13 | 14 | ## 🎭 What's All the Fuss About? 15 | 16 | Imagine if CNN, Reddit, and a fortune-teller had a baby, and that baby was raised by AI. That's NewsAI! We're not just aggregating news; we're revolutionizing how you experience information: 17 | 18 | - 🔮 **Gemini-Powered Insights**: Google's Gemini AI is our crystal ball! 19 | - 🧠 **BERT-Based Sentiment Analysis**: We don't just read news; we feel it in our circuits! 20 | - 🚀 **FastAPI Backend**: So fast, it breaks the space-time continuum! 21 | - 🖥️ **Streamlit Dashboard**: Where data visualization meets modern art! 22 | - 🍃 **MongoDB**: Because our data is too cool for tables! 23 | 24 | ## 🎬 See It or Don't Believe It! 25 | 26 | Deployment link : https://news-ai-dashboard.streamlit.app/ 27 |
28 | 29 | Demo Video 30 | 31 |
32 | Warning: This video may cause uncontrollable desire to code! 🤓 33 |
34 | 35 | ## 🚀 Quick Start: 0 to Hero in 3... 2... 1... 36 | 37 | ```bash 38 | # Clone this bad boy 39 | git clone https://github.com/Multiverse-of-Projects/NewsAI.git 40 | 41 | # Enter the matrix 42 | cd NewsAI 43 | 44 | # Install magical dependencies 45 | pip install -r requirements.txt 46 | 47 | # Add neccessary creds in .env file 48 | create an .env file with api keys and all 49 | 50 | # Add python path and run streamlit from src/dashboard/ 51 | streamlit run app.py 52 | 53 | # If you want to run only the pipeline.py 54 | python -m src.pipeline 55 | 56 | # If you want to Unleash your creativity 57 | git checkout -b feature/skynet-integration 58 | 59 | # Start coding like you're trying to prevent Y2K! 60 | # for reference my python version == 3.12.7 61 | ``` 62 | 63 | ## 🌈 Contribution: Join Our Avengers of Code! 64 | 65 | 1. 🍴 Fork (the repo, not your dinner) 66 | 2. 🌿 Branch (create one, don't climb one) 67 | 3. 💡 Commit (changes, not crimes) 68 | 4. 🚀 Push (to the repo, not your luck) 69 | 5. 🎉 PR (Pull Request, not Public Relations) 70 | 71 | ## 🏆 Wall of Fame: Our Code Wizards 72 | 73 |
74 | 75 | 76 | 77 |
78 | 79 |
80 | These legends write code that makes Shakespeare look like a casual blogger! 81 |
82 | 83 | ## 📚 Documentation: The Sacred Texts 84 | 85 | Our docs are so good, they're basically the eighth wonder of the world. Check them out on [Read the Docs](https://newsai.readthedocs.io/)! 86 | 87 | ## 🎨 Our Tech Palette: Tools of Mass Construction 88 | 89 | - 🧠 **Gemini AI**: For insights sharper than a samurai's sword 90 | - 🤖 **BERT**: Sentiment analysis that can read between the lines (and emojis) 91 | - 🚀 **FastAPI**: Because life's too short for slow APIs 92 | - 🖥️ **Streamlit**: Making dashboards sexier than a sports car 93 | - 🍃 **MongoDB**: NoSQL? More like YesQL to all our data needs! 94 | 95 | ## 📬 Reach Out and Touch Code 96 | 97 | - 📧 Email: patel.devasy.23@gmail.com (We read faster than we code!) 98 | 99 | - 💬 Discord: [Join our server](https://discord.gg/kV4ANf6x) (Where we debate tabs vs. spaces) 100 | 101 | ## 📜 License to Thrill 102 | 103 | This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details. It's basically a license to code with reckless abandon! 104 | 105 | --- 106 | 107 |
108 | 109 |
110 | May your code be bug-free and your coffee be strong! 🚀☕ 111 |
112 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/__init__.py -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = . 9 | BUILDDIR = _build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | 3 | import os 4 | import sys 5 | 6 | sys.path.insert(0, os.path.abspath("..")) 7 | 8 | 9 | # 10 | # For the full list of built-in configuration values, see the documentation: 11 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 12 | 13 | # -- Project information ----------------------------------------------------- 14 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information 15 | 16 | project = "NewsAI" 17 | copyright = "2024, Devasy Patel, Hemang Joshi, Vraj Patel" 18 | author = "Devasy Patel, Hemang Joshi, Vraj Patel" 19 | release = "1.0.0" 20 | 21 | # -- General configuration --------------------------------------------------- 22 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration 23 | 24 | extensions = [ 25 | "sphinx.ext.autodoc", 26 | "sphinx.ext.viewcode", 27 | "sphinx.ext.napoleon", 28 | "myst_parser", # Add this line 29 | ] 30 | # Include markdown support 31 | myst_enable_extensions = [ 32 | "colon_fence", 33 | "html_image", 34 | ] 35 | source_suffix = { 36 | ".rst": "restructuredtext", 37 | ".md": "markdown", # Add this line to recognize markdown files 38 | } 39 | # Add any paths that contain templates here, relative to this directory. 40 | templates_path = ["_templates"] 41 | 42 | # List of patterns, relative to source directory, that match files and 43 | # directories to ignore when looking for source files. 44 | # This pattern also affects html_static_path and html_extra_path. 45 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"] 46 | 47 | # -- Options for HTML output ------------------------------------------------- 48 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output 49 | 50 | html_theme = "sphinx_rtd_theme" 51 | html_static_path = ["_static"] 52 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. News documentation master file, created by 2 | sphinx-quickstart on Thu Sep 12 17:47:15 2024. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | News AI documentation 7 | ===================== 8 | 9 | .. toctree:: 10 | :maxdepth: 2 11 | :caption: Contents: 12 | 13 | .. include:: src.pipeline.rst 14 | .. include:: src.ingestion.rst 15 | .. include:: src.preprocessing.rst 16 | .. include:: src.sentiment_analysis.rst 17 | .. include:: src.rst 18 | .. include:: modules.rst 19 | .. include:: src.dashboard.rst 20 | .. include:: src.utils.rst 21 | 22 | Project Overview 23 | ================ 24 | 25 | .. include:: ../README.md 26 | .. include:: README.md :parser: myst_parser.sphinx_ 27 | Demo Video 28 | ========== 29 | 30 | .. raw:: html 31 | 32 | 36 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | pushd %~dp0 4 | 5 | REM Command file for Sphinx documentation 6 | 7 | if "%SPHINXBUILD%" == "" ( 8 | set SPHINXBUILD=sphinx-build 9 | ) 10 | set SOURCEDIR=. 11 | set BUILDDIR=_build 12 | 13 | %SPHINXBUILD% >NUL 2>NUL 14 | if errorlevel 9009 ( 15 | echo. 16 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx 17 | echo.installed, then set the SPHINXBUILD environment variable to point 18 | echo.to the full path of the 'sphinx-build' executable. Alternatively you 19 | echo.may add the Sphinx directory to PATH. 20 | echo. 21 | echo.If you don't have Sphinx installed, grab it from 22 | echo.https://www.sphinx-doc.org/ 23 | exit /b 1 24 | ) 25 | 26 | if "%1" == "" goto help 27 | 28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 29 | goto end 30 | 31 | :help 32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O% 33 | 34 | :end 35 | popd 36 | -------------------------------------------------------------------------------- /docs/modules.rst: -------------------------------------------------------------------------------- 1 | src 2 | === 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | src 8 | -------------------------------------------------------------------------------- /docs/src.dashboard.rst: -------------------------------------------------------------------------------- 1 | src.dashboard package 2 | ===================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | src.dashboard.app module 8 | ------------------------ 9 | 10 | .. automodule:: src.dashboard.app 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | Module contents 16 | --------------- 17 | 18 | .. automodule:: src.dashboard 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | -------------------------------------------------------------------------------- /docs/src.ingestion.rst: -------------------------------------------------------------------------------- 1 | src.ingestion package 2 | ===================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | src.ingestion.fetch\_articles module 8 | ------------------------------------ 9 | 10 | .. automodule:: src.ingestion.fetch_articles 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | src.ingestion.newsapi module 16 | ---------------------------- 17 | 18 | .. automodule:: src.ingestion.newsapi 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | src.ingestion.prawapi module 24 | ---------------------------- 25 | 26 | .. automodule:: src.ingestion.prawapi 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | Module contents 32 | --------------- 33 | 34 | .. automodule:: src.ingestion 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | -------------------------------------------------------------------------------- /docs/src.preprocessing.rst: -------------------------------------------------------------------------------- 1 | src.preprocessing package 2 | ========================= 3 | 4 | Submodules 5 | ---------- 6 | 7 | src.preprocessing.keyword\_extraction module 8 | -------------------------------------------- 9 | 10 | .. automodule:: src.preprocessing.keyword_extraction 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | src.preprocessing.summarization module 16 | -------------------------------------- 17 | 18 | .. automodule:: src.preprocessing.summarization 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | Module contents 24 | --------------- 25 | 26 | .. automodule:: src.preprocessing 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | -------------------------------------------------------------------------------- /docs/src.rst: -------------------------------------------------------------------------------- 1 | src package 2 | =========== 3 | 4 | Subpackages 5 | ----------- 6 | 7 | .. toctree:: 8 | :maxdepth: 4 9 | 10 | src.dashboard 11 | src.ingestion 12 | src.preprocessing 13 | src.sentiment_analysis 14 | src.utils 15 | 16 | Submodules 17 | ---------- 18 | 19 | src.pipeline module 20 | ------------------- 21 | 22 | .. automodule:: src.pipeline 23 | :members: 24 | :undoc-members: 25 | :show-inheritance: 26 | 27 | Module contents 28 | --------------- 29 | 30 | .. automodule:: src 31 | :members: 32 | :undoc-members: 33 | :show-inheritance: 34 | -------------------------------------------------------------------------------- /docs/src.sentiment_analysis.rst: -------------------------------------------------------------------------------- 1 | src.sentiment\_analysis package 2 | =============================== 3 | 4 | Submodules 5 | ---------- 6 | 7 | src.sentiment\_analysis.classify module 8 | --------------------------------------- 9 | 10 | .. automodule:: src.sentiment_analysis.classify 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | src.sentiment\_analysis.sentiment\_model module 16 | ----------------------------------------------- 17 | 18 | .. automodule:: src.sentiment_analysis.sentiment_model 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | src.sentiment\_analysis.wordcloud module 24 | ---------------------------------------- 25 | 26 | .. automodule:: src.sentiment_analysis.wordcloud 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | 31 | Module contents 32 | --------------- 33 | 34 | .. automodule:: src.sentiment_analysis 35 | :members: 36 | :undoc-members: 37 | :show-inheritance: 38 | -------------------------------------------------------------------------------- /docs/src.utils.rst: -------------------------------------------------------------------------------- 1 | src.utils package 2 | ================= 3 | 4 | Submodules 5 | ---------- 6 | 7 | src.utils.dbconnector module 8 | ---------------------------- 9 | 10 | .. automodule:: src.utils.dbconnector 11 | :members: 12 | :undoc-members: 13 | :show-inheritance: 14 | 15 | src.utils.logger module 16 | ----------------------- 17 | 18 | .. automodule:: src.utils.logger 19 | :members: 20 | :undoc-members: 21 | :show-inheritance: 22 | 23 | Module contents 24 | --------------- 25 | 26 | .. automodule:: src.utils 27 | :members: 28 | :undoc-members: 29 | :show-inheritance: 30 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohappyeyeballs==2.4.0 2 | aiohttp==3.10.5 3 | aiosignal==1.3.1 4 | alabaster==0.7.16 5 | altair==5.4.1 6 | annotated-types==0.7.0 7 | attrs==24.2.0 8 | autopep8==2.3.1 9 | babel==2.16.0 10 | beautifulsoup4==4.12.3 11 | black==24.8.0 12 | blinker==1.8.2 13 | cachetools==5.5.0 14 | certifi==2024.7.4 15 | cfgv==3.4.0 16 | charset-normalizer==3.3.2 17 | click==8.1.7 18 | colorama==0.4.6 19 | colorlog==6.8.2 20 | contourpy==1.3.0 21 | cycler==0.12.1 22 | distlib==0.3.8 23 | dnspython==2.6.1 24 | docutils==0.20.1 25 | filelock==3.15.4 26 | fonttools==4.54.1 27 | frozenlist==1.4.1 28 | fsspec==2024.6.1 29 | gitdb==4.0.11 30 | GitPython==3.1.43 31 | google-ai-generativelanguage==0.6.10 32 | google-api-core==2.19.2 33 | google-api-python-client==2.149.0 34 | google-auth==2.34.0 35 | google-auth-httplib2==0.2.0 36 | google-generativeai>=0.7.2 37 | googleapis-common-protos==1.65.0 38 | grpcio==1.66.1 39 | grpcio-status==1.62.3 40 | httplib2==0.22.0 41 | huggingface-hub==0.24.6 42 | identify==2.6.0 43 | idna==3.8 44 | imagesize==1.4.1 45 | isort==5.13.2 46 | Jinja2==3.1.4 47 | joblib==1.4.2 48 | jsonschema==4.23.0 49 | jsonschema-specifications==2023.12.1 50 | keybert==0.8.5 51 | kiwisolver==1.4.5 52 | markdown-it-py==3.0.0 53 | MarkupSafe==2.1.5 54 | matplotlib==3.9.2 55 | mdit-py-plugins==0.4.2 56 | mdurl==0.1.2 57 | mpmath==1.3.0 58 | multidict==6.0.5 59 | mypy-extensions==1.0.0 60 | myst-parser==4.0.0 61 | narwhals==1.6.0 62 | networkx==3.3 63 | nltk==3.9.1 64 | nodeenv==1.9.1 65 | numpy==2.1.0 66 | packaging==24.1 67 | pandas==2.2.2 68 | pathspec==0.12.1 69 | pillow==10.4.0 70 | platformdirs==4.2.2 71 | plotly==5.24.0 72 | praw==7.7.1 73 | prawcore==2.4.0 74 | pre-commit==3.8.0 75 | prettytable==3.11.0 76 | proto-plus==1.24.0 77 | protobuf==4.25.4 78 | pyarrow==17.0.0 79 | pyasn1==0.6.0 80 | pyasn1_modules==0.4.0 81 | pycodestyle==2.12.1 82 | pydantic==2.8.2 83 | pydantic_core==2.20.1 84 | pydeck==0.9.1 85 | pyecharts==2.0.6 86 | Pygments==2.18.0 87 | pymongo==4.8.0 88 | pyparsing==3.1.4 89 | python-dateutil==2.9.0.post0 90 | python-dotenv==1.0.1 91 | pytz==2024.1 92 | PyYAML==6.0.2 93 | referencing==0.35.1 94 | regex==2024.7.24 95 | requests==2.32.3 96 | rich==13.8.0 97 | rpds-py==0.20.0 98 | rsa==4.9 99 | safetensors==0.4.4 100 | scikit-learn==1.5.2 101 | scipy==1.14.1 102 | seaborn==0.13.2 103 | sentence-transformers==3.0.1 104 | setuptools==74.0.0 105 | simplejson==3.19.3 106 | six==1.16.0 107 | smmap==5.0.1 108 | snowballstemmer==2.2.0 109 | soupsieve==2.6 110 | Sphinx==7.4.7 111 | sphinx-rtd-theme==2.0.0 112 | sphinxcontrib-applehelp==2.0.0 113 | sphinxcontrib-devhelp==2.0.0 114 | sphinxcontrib-htmlhelp==2.1.0 115 | sphinxcontrib-jquery==4.1 116 | sphinxcontrib-jsmath==1.0.1 117 | sphinxcontrib-qthelp==2.0.0 118 | sphinxcontrib-serializinghtml==2.0.0 119 | streamlit>=1.38.0 120 | streamlit-echarts==0.4.0 121 | sympy==1.13.1 122 | tenacity==9.0.0 123 | threadpoolctl==3.5.0 124 | tokenizers==0.19.1 125 | toml==0.10.2 126 | torch==2.5.0 127 | tornado==6.4.1 128 | tqdm==4.66.5 129 | transformers==4.44.2 130 | typing_extensions==4.12.2 131 | tzdata==2024.1 132 | update-checker==0.18.0 133 | uritemplate==4.1.1 134 | urllib3==2.2.2 135 | virtualenv==20.26.3 136 | watchdog==4.0.2 137 | wcwidth==0.2.13 138 | websocket-client==1.8.0 139 | wordcloud==1.9.3 140 | yarl==1.9.7 141 | -------------------------------------------------------------------------------- /src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/src/__init__.py -------------------------------------------------------------------------------- /src/dashboard/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/src/dashboard/__init__.py -------------------------------------------------------------------------------- /src/dashboard/app.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import time 4 | from datetime import datetime 5 | from io import BytesIO 6 | from typing import List 7 | 8 | import matplotlib.dates as mdates 9 | import matplotlib.pyplot as plt 10 | import numpy as np 11 | import pandas as pd 12 | import plotly.colors as pc 13 | import plotly.express as px 14 | import requests 15 | import seaborn as sns 16 | import streamlit as st 17 | from PIL import Image 18 | from streamlit_echarts import st_echarts 19 | 20 | from src.pipeline import process_articles 21 | from src.sentiment_analysis.wordcloud import generate_wordcloud 22 | from src.utils.dbconnector import (append_to_document, 23 | fetch_and_combine_articles, find_documents, 24 | find_one_document) 25 | from src.utils.logger import setup_logger 26 | 27 | logger = setup_logger() 28 | 29 | 30 | def download_images(image_urls, save_dir="downloaded_images"): 31 | # if not os.path.exists(save_dir): 32 | # os.makedirs(save_dir) 33 | """ 34 | Downloads a list of images from the given URLs and returns a list of PIL Image objects. 35 | 36 | Args: 37 | image_urls (List[str]): List of URLs of the images to download. 38 | save_dir (str, optional): Directory to save the downloaded images. Defaults to "downloaded_images". 39 | 40 | Returns: 41 | List[PIL.Image.Image]: List of PIL Image objects downloaded from the URLs. 42 | """ 43 | image_files = [] 44 | for _, url in enumerate(image_urls): 45 | try: 46 | response = requests.get(url) 47 | img = Image.open(BytesIO(response.content)) 48 | # img_path = os.path.join(save_dir, f'image_{idx}.png') 49 | # img.save(img_path) 50 | image_files.append(img) 51 | except Exception as e: 52 | print(f"Failed to download {url}: {e}") 53 | 54 | return image_files 55 | 56 | 57 | def create_and_show_gif(image_files): 58 | """ 59 | Creates a GIF from a list of PIL Image objects and displays it in Streamlit. 60 | 61 | Args: 62 | image_files (List[PIL.Image.Image]): List of PIL Image objects to create the GIF from. 63 | 64 | Returns: 65 | None 66 | """ 67 | if not all(isinstance(img, Image.Image) for img in image_files): 68 | raise ValueError("All items in image_files must be PIL.Image objects.") 69 | images = [img.convert("RGBA") for img in image_files] 70 | frames = [] 71 | for image in images: 72 | frames.append(image) 73 | frames[0].save( 74 | "mygif.gif", save_all=True, append_images=frames[1:], duration=300, loop=0 75 | ) 76 | st.image("mygif.gif", use_column_width=True) 77 | 78 | 79 | # sys.path.append(os.path.abspath(os.path.join(os.path.dirname(_file_), "..", ".."))) 80 | def extract_and_flatten_keywords(data) -> List[str]: 81 | """ 82 | Extracts and flattens a list of lists of keywords from a dataset. 83 | 84 | Args: 85 | data (pd.DataFrame): Pandas DataFrame containing a column named 'keywords' with a list of lists of keywords. 86 | 87 | Returns: 88 | List[str]: A flattened list of all keywords. 89 | """ 90 | all_keywords = [] 91 | all_keywords = data["keywords"].tolist() 92 | logger.info(all_keywords) 93 | all_keywords = [ 94 | item 95 | for sublist in all_keywords 96 | for item in sublist 97 | if isinstance(sublist, list) 98 | ] 99 | return all_keywords 100 | 101 | 102 | def load_css(file_name): 103 | """ 104 | Loads a CSS file and injects it into the Streamlit app. 105 | 106 | Args: 107 | file_name (str): Path to the CSS file to load. 108 | 109 | Returns: 110 | None 111 | """ 112 | with open(file_name) as f: 113 | st.markdown(f"", unsafe_allow_html=True) 114 | 115 | 116 | # Function to simulate data processing (replace with actual processing functions) 117 | 118 | 119 | # Function to create a word cloud 120 | 121 | 122 | # Function to create a spiderweb chart 123 | def generate_spiderweb(data): 124 | """ 125 | Generates a spiderweb chart using Streamlit's ECharts component. 126 | 127 | Args: 128 | data (dict): Dictionary where the keys are the topic names and the values are the topic weights. 129 | 130 | Returns: 131 | None 132 | """ 133 | options = { 134 | "title": {"text": "Spiderweb Chart Example"}, 135 | "radar": {"indicator": [{"name": key, "max": 100} for key in data.keys()]}, 136 | "series": [ 137 | { 138 | "name": "Topics", 139 | "type": "radar", 140 | "data": [{"value": list(data.values()), "name": "Topic Distribution"}], 141 | } 142 | ], 143 | } 144 | st_echarts(options=options) 145 | 146 | 147 | # Load external CSS 148 | # load_css("styles.css") 149 | # Layout Configuration 150 | # st.set_page_config(layout="wide") 151 | 152 | # Title and User Input 153 | st.title("News AI Dashboard") 154 | st.subheader("Enter your query to generate insights:") 155 | query = st.text_input("Query", "Enter a keyword or phrase") 156 | fetch_till = st.slider("Fetch articles till", 5, 100, 10) 157 | 158 | # Wait animation after submitting query 159 | if st.button("Submit"): 160 | with st.spinner("Processing data, please wait..."): 161 | prev = find_one_document("News_Articles_Ids", {"query": query}) 162 | # st.write(prev) 163 | if prev: 164 | data = prev["ids"] 165 | else: 166 | data = process_articles(query, limit=fetch_till) 167 | # st.write(data) 168 | df = fetch_and_combine_articles("News_Articles", data) 169 | st.success("Data processed successfully!") 170 | # st.write(df) 171 | # Column Layout 172 | col1, col2, col3 = st.columns(3) 173 | 174 | with col1: 175 | st.subheader("Keyword Extraction - Word Cloud") 176 | flattened_keywords = extract_and_flatten_keywords(df) 177 | wordcloud = generate_wordcloud(flattened_keywords, "Sentiments") 178 | plt.figure(figsize=(10, 5)) 179 | plt.imshow(wordcloud, interpolation="bilinear") 180 | plt.axis("off") 181 | st.pyplot(plt) 182 | # Pie Chart with topic-wise distribution 183 | with col2: 184 | # st.subheader("Sentiment Distribution") 185 | sentiment_counts = df["sentiment"].value_counts() 186 | fig = px.pie( 187 | values=sentiment_counts.values, 188 | names=sentiment_counts.index, 189 | title="Sentiment Distribution", 190 | hole=0.5, 191 | ) 192 | st.plotly_chart(fig) 193 | 194 | # Line chart for time-wise distribution 195 | st.subheader("Time-wise Sentiment Distribution") 196 | # Normalize the sentiment values to lowercase 197 | df["sentiment"] = df["sentiment"].str.lower() 198 | df["publishedat"] = pd.to_datetime(df["publishedat"]) 199 | 200 | # Extract dates and aggregate sentiment counts 201 | time_data = df.pivot_table( 202 | index=df["publishedat"].dt.date, 203 | columns="sentiment", 204 | aggfunc="size", 205 | fill_value=0, 206 | ) 207 | 208 | # Ensure all sentiments (positive, negative, neutral) are included 209 | for sentiment in ["positive", "negative", "neutral"]: 210 | if sentiment not in time_data.columns: 211 | time_data[sentiment] = 0 212 | 213 | # Reset the index to turn dates into a column 214 | time_data = time_data.reset_index() 215 | 216 | # Create the line plot 217 | fig = px.line( 218 | time_data, 219 | x="publishedat", 220 | y=["positive", "negative", "neutral"], 221 | title="Time-wise Sentiment Distribution", 222 | labels={"value": "Count", "variable": "Sentiment"}, 223 | ) 224 | 225 | # Customize line colors for each sentiment 226 | fig.update_traces(line=dict(color="green"), selector=dict(name="positive")) 227 | fig.update_traces(line=dict(color="red"), selector=dict(name="negative")) 228 | fig.update_traces(line=dict(color="blue"), selector=dict(name="neutral")) 229 | 230 | # Display the plot 231 | st.plotly_chart(fig) 232 | 233 | with col3: 234 | source_distribution = df["source"].value_counts() 235 | 236 | # Plot the pie chart 237 | fig = px.pie( 238 | names=source_distribution.index, 239 | values=source_distribution.values, 240 | title="Distribution of Articles by Source", 241 | color_discrete_sequence=pc.qualitative.Prism, 242 | ) 243 | st.plotly_chart(fig) 244 | 245 | df["publishedat"] = pd.to_datetime(df["publishedat"]) 246 | 247 | # Extract date only (without time) for grouping 248 | df["date"] = df["publishedat"].dt.date 249 | 250 | # Pivot the DataFrame to create a matrix for the heatmap 251 | # Count sentiment occurrences for each source per day 252 | heatmap_data = df.pivot_table( 253 | index="date", 254 | columns="source", 255 | values="sentiment", 256 | aggfunc="count", 257 | fill_value=0, 258 | ) 259 | 260 | # Plot the heatmap 261 | fig = px.imshow( 262 | heatmap_data, 263 | color_continuous_scale="YlGnBu", 264 | title="Sentiment Distribution Across Sources Over Time", 265 | ) 266 | fig.update_layout(xaxis_title="Source", 267 | yaxis_title="Date", xaxis_nticks=10) 268 | fig.update_xaxes(tickangle=-45) 269 | 270 | st.plotly_chart(fig) 271 | 272 | downloaded_images = download_images(df["urltoimage"].values) 273 | 274 | create_and_show_gif(downloaded_images) 275 | 276 | # Display summaries with highlighted keywords in an expander 277 | # Display summaries with highlighted keywords in an expander 278 | def highlight_keywords(text, keywords): 279 | for keyword in keywords: 280 | text = text.replace( 281 | keyword, 282 | f"{keyword}", 283 | ) 284 | return text 285 | 286 | with st.expander("View All Summaries with Highlighted Keywords"): 287 | st.subheader("Summaries") 288 | for index, row in df.iterrows(): 289 | summary = row["summary"] 290 | keywords = row["keywords"] 291 | highlighted_summary = highlight_keywords(summary, keywords) 292 | st.markdown(highlighted_summary, unsafe_allow_html=True) 293 | 294 | with st.expander("View Public Reddit Data"): 295 | # Reddit Word Cloud 296 | try: 297 | st.subheader("Reddit Keyword Extraction - Word Cloud") 298 | reddit_wordcloud = generate_wordcloud(data["reddit_keywords"]) 299 | plt.figure(figsize=(10, 5)) 300 | plt.imshow(reddit_wordcloud, interpolation="bilinear") 301 | plt.axis("off") 302 | st.pyplot(plt) 303 | 304 | # Reddit Sentiment Analysis 305 | st.subheader("Reddit Sentiment Distribution") 306 | reddit_sentiment_counts = pd.Series( 307 | data["reddit_sentiments"] 308 | ).value_counts() 309 | fig = px.pie( 310 | values=reddit_sentiment_counts.values, 311 | names=reddit_sentiment_counts.index, 312 | title="Reddit Sentiment Distribution", 313 | ) 314 | st.plotly_chart(fig) 315 | 316 | # Hot Discussion Points from Reddit 317 | st.subheader("Hot Discussion Points from Reddit") 318 | st.write( 319 | "Placeholder for Reddit hot discussion points (to be populated with real data)." 320 | ) 321 | 322 | except Exception as e: 323 | st.error(f"Error: {e}") 324 | -------------------------------------------------------------------------------- /src/dashboard/requirements.txt: -------------------------------------------------------------------------------- 1 | altair==5.4.1 2 | attrs==24.2.0 3 | autopep8==2.3.1 4 | beautifulsoup4==4.12.3 5 | black==24.8.0 6 | blinker==1.8.2 7 | cachetools==5.5.0 8 | certifi==2024.7.4 9 | cfgv==3.4.0 10 | charset-normalizer==3.3.2 11 | click==8.1.7 12 | colorama==0.4.6 13 | colorlog==6.8.2 14 | contourpy==1.3.0 15 | cycler==0.12.1 16 | distlib==0.3.8 17 | dnspython==2.6.1 18 | filelock==3.15.4 19 | fonttools==4.53.1 20 | fsspec==2024.6.1 21 | gitdb==4.0.11 22 | GitPython==3.1.43 23 | huggingface-hub==0.24.6 24 | identify==2.6.0 25 | idna==3.8 26 | isort==5.13.2 27 | Jinja2==3.1.4 28 | joblib==1.4.2 29 | jsonschema==4.23.0 30 | jsonschema-specifications==2023.12.1 31 | keybert==0.8.5 32 | kiwisolver==1.4.5 33 | markdown-it-py==3.0.0 34 | MarkupSafe==2.1.5 35 | matplotlib==3.9.2 36 | mdurl==0.1.2 37 | mpmath==1.3.0 38 | mypy-extensions==1.0.0 39 | narwhals==1.6.0 40 | networkx==3.3 41 | nltk==3.9.1 42 | nodeenv==1.9.1 43 | numpy==2.1.0 44 | nvidia-cublas-cu12==12.1.3.1 45 | nvidia-cuda-cupti-cu12==12.1.105 46 | nvidia-cuda-nvrtc-cu12==12.1.105 47 | nvidia-cuda-runtime-cu12==12.1.105 48 | nvidia-cudnn-cu12==9.1.0.70 49 | nvidia-cufft-cu12==11.0.2.54 50 | nvidia-curand-cu12==10.3.2.106 51 | nvidia-cusolver-cu12==11.4.5.107 52 | nvidia-cusparse-cu12==12.1.0.106 53 | nvidia-nccl-cu12==2.20.5 54 | nvidia-nvjitlink-cu12==12.6.68 55 | nvidia-nvtx-cu12==12.1.105 56 | packaging==24.1 57 | pandas==2.2.2 58 | pathspec==0.12.1 59 | pillow==10.4.0 60 | platformdirs==4.2.2 61 | plotly==5.24.0 62 | pre-commit==3.8.0 63 | prettytable==3.11.0 64 | protobuf==5.28.0 65 | pyarrow==17.0.0 66 | pycodestyle==2.12.1 67 | pydeck==0.9.1 68 | pyecharts==2.0.6 69 | Pygments==2.18.0 70 | pymongo==4.8.0 71 | pyparsing==3.1.4 72 | python-dateutil==2.9.0.post0 73 | python-dotenv==1.0.1 74 | pytz==2024.1 75 | PyYAML==6.0.2 76 | referencing==0.35.1 77 | regex==2024.7.24 78 | requests==2.32.3 79 | rich==13.8.0 80 | rpds-py==0.20.0 81 | safetensors==0.4.4 82 | scikit-learn==1.5.1 83 | scipy==1.14.1 84 | sentence-transformers==3.0.1 85 | setuptools==74.0.0 86 | simplejson==3.19.3 87 | six==1.16.0 88 | smmap==5.0.1 89 | soupsieve==2.6 90 | streamlit==1.38.0 91 | streamlit-echarts==0.4.0 92 | sympy==1.13.2 93 | tenacity==8.5.0 94 | threadpoolctl==3.5.0 95 | tokenizers==0.19.1 96 | toml==0.10.2 97 | torch==2.4.0 98 | tornado==6.4.1 99 | tqdm==4.66.5 100 | transformers==4.44.2 101 | triton==3.0.0 102 | typing_extensions==4.12.2 103 | tzdata==2024.1 104 | urllib3==2.2.2 105 | uv==0.3.5 106 | virtualenv==20.26.3 107 | watchdog==4.0.2 108 | wcwidth==0.2.13 109 | wordcloud==1.9.3 110 | -------------------------------------------------------------------------------- /src/ingestion/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/src/ingestion/__init__.py -------------------------------------------------------------------------------- /src/ingestion/fetch_articles.py: -------------------------------------------------------------------------------- 1 | """ 2 | This script asynchronously fetches and stores content of news articles 3 | by scraping provided URLs and checking if the content is already present in the database. 4 | """ 5 | import asyncio 6 | import json 7 | import os 8 | import sys 9 | from typing import Dict, List 10 | from urllib.parse import urlparse 11 | 12 | import aiohttp 13 | import requests 14 | from bs4 import BeautifulSoup 15 | 16 | from src.utils.dbconnector import (append_to_document, content_manager, 17 | find_documents) 18 | from src.utils.logger import setup_logger 19 | 20 | sys.path.append(os.path.abspath(os.path.join( 21 | os.path.dirname(__file__), "..", ".."))) 22 | 23 | sys.path.append(os.path.abspath(os.path.join( 24 | os.path.dirname(__file__), "..", ".."))) 25 | 26 | logger = setup_logger() 27 | 28 | 29 | async def fetch_article_content(article_ids, session): 30 | """ 31 | Fetches the content of a list of articles asynchronously, by checking if content already exists in the database, and if not, extracting the content from the given URLs. 32 | 33 | Args: 34 | article_ids (List[str]): List of IDs of the articles to fetch content for. 35 | session (aiohttp.ClientSession): The aiohttp session to use for the request. 36 | 37 | Returns: 38 | List[Dict[str, str]]: List of dictionaries, each containing the ID and content of a fetched article. 39 | """ 40 | try: 41 | # if not docs: 42 | # raise ValueError( 43 | # f"No documents found for article IDs: {article_ids}") 44 | docs = find_documents("News_Articles", {"id": {"$in": article_ids}}) 45 | except Exception as e: 46 | logger.error(f"Failed to find documents: {e}") 47 | raise 48 | 49 | urls_to_fetch = [] 50 | 51 | # Check if content already exists for each article 52 | for doc in docs: 53 | id = doc["id"] 54 | url = doc["url"] 55 | 56 | # Use the content manager to check if content already exists 57 | field_status = content_manager(id, ["content"]) 58 | 59 | if not field_status["content"]: 60 | urls_to_fetch.append({"id": id, "url": url}) 61 | logger.info(f"Fetching content for article {id}") 62 | else: 63 | logger.info( 64 | f"Content already exists for article {id}. Skipping fetch.") 65 | 66 | article_contents = [] 67 | 68 | # Define an asynchronous function to fetch content 69 | async def fetch_content(id, url): 70 | """ 71 | Fetches the content of a single article asynchronously. 72 | 73 | Args: 74 | id (str): The ID of the article to fetch content for. 75 | url (str): The URL of the article to fetch content from. 76 | 77 | Returns: 78 | None 79 | """ 80 | try: 81 | async with session.get(url) as response: 82 | response.raise_for_status() 83 | soup = BeautifulSoup(await response.text(), "html.parser") 84 | 85 | # Extract the article content based on common HTML structure 86 | article_content = "" 87 | 88 | # Many articles have a

tag structure for paragraphs 89 | paragraphs = soup.find_all("p") 90 | if paragraphs: 91 | for p in paragraphs: 92 | article_content += p.get_text() + "\n" 93 | else: 94 | # Fallback if no

tags found, try another structure, e.g.,

95 | divs = soup.find_all("div") 96 | for div in divs: 97 | article_content += div.get_text() + "\n" 98 | 99 | # Clean up the content 100 | article_content = article_content.strip() 101 | 102 | article_obj = {"id": id, "content": article_content} 103 | article_contents.append(article_obj) 104 | 105 | # Save content to MongoDB 106 | append_to_document("News_Articles", {"id": id}, article_obj) 107 | logger.info(f"Content fetched and saved for article {id}") 108 | except Exception as e: 109 | logger.error(f"Failed to fetch the article {id}: {e}") 110 | 111 | # Run the fetch operations in parallel using aiohttp 112 | tasks = [fetch_content(obj["id"], obj["url"]) for obj in urls_to_fetch] 113 | await asyncio.gather(*tasks) 114 | 115 | logger.info(f"Total articles content fetched: {len(article_contents)}") 116 | return article_contents 117 | 118 | 119 | async def test_fetch_article_content(article_ids: List[str]) -> List[Dict[str, str]]: 120 | """ 121 | Tests the fetch_article_content function by fetching content for a list of article IDs. 122 | 123 | Args: 124 | article_ids (List[str]): A list of article IDs to fetch content for. 125 | 126 | Returns: 127 | List[Dict[str, str]]: A list of dictionaries where each dictionary contains the ID and content of a fetched article. 128 | """ 129 | async with aiohttp.ClientSession() as session: 130 | contents = await fetch_article_content(article_ids, session) 131 | logger.info(contents) # Print the fetched content for verification 132 | 133 | 134 | if __name__ == "__main__": 135 | url = "https://www.rt.com/india/602908-reclaiming-night-protests-over-rape/" 136 | article_ids = [ 137 | "b01d85d7-d538-47cc-a7c4-31c13e7f6b4e", 138 | "15133cc7-1522-41f9-8db4-70568e837968", 139 | ] 140 | asyncio.run(test_fetch_article_content()) 141 | -------------------------------------------------------------------------------- /src/ingestion/newsapi.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import uuid 4 | from datetime import datetime 5 | 6 | import requests 7 | from dotenv import load_dotenv 8 | 9 | from src.utils.dbconnector import find_one_document, insert_document 10 | from src.utils.logger import setup_logger 11 | 12 | # Load API key from .env file 13 | load_dotenv() 14 | API_KEY = os.getenv("NEWS_API_KEY") 15 | 16 | # Configure logger 17 | logger = setup_logger() 18 | 19 | 20 | def fetch_news(query, from_date: datetime, sort_by, limit, to_json): 21 | """ 22 | Fetches news articles from NewsAPI for the given query, from date and sort_by. 23 | 24 | Args: 25 | query (str): The query to search for in the NewsAPI. 26 | from_date (datetime.datetime): The date from which to fetch the articles. 27 | sort_by (str): The field to sort the results by. 28 | limit (int): The number of articles to fetch. 29 | to_json (bool): Whether to store the results in a JSON file. 30 | 31 | Returns: 32 | List[str]: The IDs of the articles that were fetched and stored in MongoDB. 33 | """ 34 | url = f"https://newsapi.org/v2/everything?q={query}&from={from_date}&sortBy={sort_by}&apiKey={API_KEY}" 35 | try: 36 | logger.debug("Requesting data from NewsAPI") 37 | previous = find_one_document("News_Articles_Ids", {"query": query}) 38 | if previous: 39 | logger.info(f"Previous data found for {query} from {from_date}") 40 | return previous["ids"] 41 | response = requests.get(url) 42 | response.raise_for_status() # Raise an error for bad status codes 43 | data = response.json() 44 | 45 | if data.get("status") == "ok": 46 | logger.info(f"Total results: {data.get('totalResults')}") 47 | if to_json: 48 | try: 49 | # store the data in json 50 | # ----- 51 | filename = f"{query.replace(' ', '_')}_{from_date}.json" 52 | with open(filename, "w", encoding="utf-8") as f: 53 | json.dump(data, f, ensure_ascii=False, indent=4) 54 | logger.info(f"Results stored in {filename}") 55 | # ----- 56 | except Exception as e: 57 | logger.error( 58 | f"Error occurred while storing results: {str(e)}") 59 | else: 60 | articles_db = [] 61 | article_ids = [] 62 | for article in data.get("articles", [])[:limit]: 63 | logger.debug( 64 | f"Adding ids to articles and saving them to MongoDB") 65 | id = str(uuid.uuid4()) 66 | article_ids.append(id) 67 | article_obj = { 68 | "id": id, 69 | "title": article.get("title"), 70 | "description": article.get("description"), 71 | "url": article.get("url"), 72 | "urltoimage": article.get("urlToImage"), 73 | "publishedat": article.get("publishedAt"), 74 | "source": article.get("source").get("name"), 75 | } 76 | insert_document("News_Articles", article_obj) 77 | 78 | logger.info(f"Total articles saved: {len(articles_db)}") 79 | logger.debug(f"Article IDs: {article_ids}") 80 | insert_document( 81 | "News_Articles_Ids", {"query": query, "ids": article_ids} 82 | ) 83 | return article_ids 84 | else: 85 | logger.error(f"Error in response: {data}") 86 | except requests.exceptions.RequestException as e: 87 | logger.error(f"HTTP Request failed: {type(e).__name__} - {str(e)}") 88 | 89 | 90 | if __name__ == "__main__": 91 | # if __name__ == "__main__" and __package__ is None: 92 | __package__ = "src.ingestion" 93 | fetch_news( 94 | query="Kolkata Murder case", 95 | from_date="2024-08-21", 96 | sort_by="popularity", 97 | to_json=True, 98 | ) 99 | -------------------------------------------------------------------------------- /src/ingestion/prawapi.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import sys 4 | from datetime import datetime 5 | 6 | import praw 7 | from dotenv import load_dotenv 8 | 9 | from src.utils.logger import setup_logger 10 | 11 | sys.path.append(os.path.abspath(os.path.join( 12 | os.path.dirname(__file__), "..", ".."))) 13 | 14 | # Import setup_logger from utils 15 | 16 | load_dotenv() 17 | 18 | reddit = praw.Reddit( 19 | client_id=os.getenv("REDDIT_CLIENTID"), 20 | client_secret=os.getenv("REDDIT_SECRETKEY"), 21 | user_agent="{0} by u/{1}".format( 22 | os.getenv("REDDIT_APPNAME"), os.getenv("REDDIT_USERNAME") 23 | ), 24 | username=os.getenv("REDDIT_USERNAME"), 25 | password=os.getenv("REDDIT_PASSWORD"), 26 | ) 27 | 28 | logger = setup_logger() 29 | 30 | # constants 31 | COMMENT_COUNT = 10 32 | TIME_SLOT = "all" # Time filter can be 'all', 'day', 'week', 'month', 'year' 33 | 34 | 35 | def clean_content(content: str) -> str: 36 | # Replace carriage returns and newlines with spaces 37 | """ 38 | Clean a string by replacing carriage returns and newlines with spaces and then removing excessive spaces. 39 | 40 | Args: 41 | content (str): The string to clean. 42 | 43 | Returns: 44 | str: The cleaned string. 45 | """ 46 | if not isinstance(content, str): 47 | raise ValueError("Input must be a string.") 48 | cleaned_content = content.replace("\r", " ").replace("\n", " ") 49 | # Remove excessive spaces (multiple spaces turned into a single space) 50 | cleaned_content = " ".join(cleaned_content.split()) 51 | return cleaned_content 52 | 53 | 54 | def fetch_reddit_posts_by_keyword(keyword, limit=10, to_json=True): 55 | """ 56 | Fetches Reddit posts containing the given keyword. 57 | 58 | Args: 59 | keyword (str): The keyword to search for in Reddit posts. 60 | limit (int, optional): The number of posts to fetch. Defaults to 10. 61 | to_json (bool, optional): Whether to store the results in a JSON file. Defaults to True. 62 | 63 | Returns: 64 | List[Dict]: A list of dictionaries containing the post data. 65 | """ 66 | try: 67 | # Search for posts containing the keyword 68 | search_results = reddit.subreddit("all").search( 69 | query=keyword, 70 | sort="relevance", # Sort results by relevance 71 | time_filter=TIME_SLOT, 72 | limit=limit, 73 | ) 74 | 75 | posts = [] 76 | for post in search_results: 77 | if not post or post.stickied: # Skip if post is None or stickied 78 | continue 79 | 80 | post_data = { 81 | "title": post.title, 82 | "id": post.id, 83 | "content": clean_content(post.selftext), 84 | "url": post.url, 85 | "created_utc": datetime.utcfromtimestamp(post.created_utc).isoformat(), 86 | "top_comments": [], 87 | } 88 | 89 | # Fetch and process top comments 90 | try: 91 | comments = post.comments.list() # Get all comments 92 | sorted_comments = sorted( 93 | comments, 94 | key=lambda c: c.score if hasattr(c, "score") else 0, 95 | reverse=True, 96 | ) 97 | top_comments = sorted_comments[:COMMENT_COUNT] 98 | 99 | post_data["top_comments"] = [ 100 | { 101 | "comment_id": comment.id, 102 | "comment_content": clean_content(comment.body), 103 | "comment_score": comment.score, 104 | "comment_created_utc": datetime.utcfromtimestamp( 105 | comment.created_utc 106 | ).isoformat(), 107 | } 108 | for comment in top_comments 109 | if hasattr(comment, "body") 110 | ] 111 | except Exception as e: 112 | logger.error( 113 | f"Error fetching comments for post ID {post.id}: {str(e)}") 114 | 115 | posts.append(post_data) 116 | logger.debug(f"Post Title: {post.title}") 117 | logger.debug(f"Post URL: {post.url}") 118 | logger.debug( 119 | f"Post Content: {post.selftext[:100]}" 120 | ) # Print a snippet of content 121 | 122 | if to_json: 123 | try: 124 | filename = f"{keyword}_posts_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.json" 125 | with open(filename, "w", encoding="utf-8") as f: 126 | json.dump(posts, f, ensure_ascii=False, indent=4) 127 | logger.info(f"Results stored in {filename}") 128 | except Exception as e: 129 | logger.error(f"Error occurred while storing results: {str(e)}") 130 | else: 131 | logger.info( 132 | f"Fetched {len(posts)} posts containing the keyword '{keyword}'" 133 | ) 134 | 135 | except Exception as e: 136 | logger.error(f"Error fetching posts: {type(e).__name__} - {str(e)}") 137 | 138 | 139 | if __name__ == "__main__": 140 | # Example usage: searching for posts about "python" 141 | fetch_reddit_posts_by_keyword(keyword="python", limit=10) 142 | -------------------------------------------------------------------------------- /src/pipeline.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import json 3 | from concurrent.futures import ThreadPoolExecutor 4 | 5 | from aiohttp import ClientSession 6 | from tenacity import retry, stop_after_attempt, wait_fixed 7 | 8 | from src.ingestion.fetch_articles import fetch_article_content 9 | from src.ingestion.newsapi import fetch_news 10 | from src.preprocessing.keyword_extraction import (bert_keyword_extraction, 11 | extract_keywords) 12 | from src.preprocessing.summarization import summarize_texts 13 | from src.sentiment_analysis.classify import (analyze_sentiments, 14 | classify_sentiments) 15 | from src.sentiment_analysis.wordcloud import generate_wordcloud 16 | from src.utils.dbconnector import append_to_document, content_manager 17 | from src.utils.logger import setup_logger 18 | 19 | # Setup logger 20 | logger = setup_logger() 21 | 22 | 23 | async def summarize_texts_async(article_id): 24 | """ 25 | Asynchronous wrapper for summarize_texts. 26 | 27 | Args: 28 | article_id (str): ID of the article to summarize. 29 | 30 | Returns: 31 | str: Summarized text. 32 | """ 33 | loop = asyncio.get_event_loop() 34 | return await loop.run_in_executor(None, summarize_texts, [article_id]) 35 | 36 | 37 | async def extract_keywords_async(article_id): 38 | """ 39 | Asynchronous wrapper for extract_keywords. 40 | 41 | Args: 42 | article_id (str): ID of the article to extract keywords from. 43 | 44 | Returns: 45 | List[str]: List of extracted keywords. 46 | """ 47 | loop = asyncio.get_event_loop() 48 | return await loop.run_in_executor(None, extract_keywords, [article_id]) 49 | 50 | 51 | async def analyze_sentiments_async(article_id): 52 | """ 53 | Asynchronous wrapper for analyze_sentiments. 54 | 55 | Args: 56 | article_id (str): ID of the article to analyze. 57 | 58 | Returns: 59 | List[Dict[str, float]]: List of sentiment analysis results for each text. 60 | """ 61 | loop = asyncio.get_event_loop() 62 | return await loop.run_in_executor(None, analyze_sentiments, [article_id]) 63 | 64 | 65 | async def process_single_article_async(article_id, session): 66 | # Check the presence of content, summary, keywords, and sentiment in the DB 67 | """ 68 | Process a single article asynchronously, by fetching content, summarizing, extracting keywords and analyzing sentiment. 69 | 70 | Args: 71 | article_id (str): ID of the article to process. 72 | session (aiohttp.ClientSession): The aiohttp session to use for the request. 73 | 74 | Returns: 75 | str: The ID of the article that was processed. 76 | """ 77 | field_status = content_manager( 78 | article_id, ["content", "summary", "keywords", "sentiment"] 79 | ) 80 | 81 | # Fetch content only if not already present 82 | if not field_status["content"]: 83 | content = await fetch_article_content([article_id], session) 84 | # Save content to MongoDB 85 | # append_to_document("News_Articles", {"id": article_id}, {"content": content}) 86 | else: 87 | logger.info( 88 | f"Content already exists for article {article_id}. Skipping fetch.") 89 | 90 | # Summarize only if summary is not already present 91 | if not field_status["summary"]: 92 | if not field_status["content"]: 93 | content = await fetch_article_content([article_id], session) 94 | summary = await summarize_texts_async(article_id) 95 | # Save summary to MongoDB 96 | # append_to_document("News_Articles", {"id": article_id}, {"summary": summary}) 97 | else: 98 | logger.info( 99 | f"Summary already exists for article {article_id}. Skipping summarization." 100 | ) 101 | 102 | # Extract keywords only if not already present 103 | if not field_status["keywords"]: 104 | keywords = await extract_keywords_async(article_id) 105 | # Save keywords to MongoDB 106 | # append_to_document("News_Articles", {"id": article_id}, {"keywords": keywords}) 107 | else: 108 | logger.info( 109 | f"Keywords already exist for article {article_id}. Skipping extraction." 110 | ) 111 | 112 | # Analyze sentiment only if not already present 113 | if not field_status["sentiment"]: 114 | sentiment = await analyze_sentiments_async(article_id) 115 | # Save sentiment to MongoDB 116 | # append_to_document("News_Articles", {"id": article_id}, {"sentiment": sentiment}) 117 | else: 118 | logger.info( 119 | f"Sentiment already exists for article {article_id}. Skipping sentiment analysis." 120 | ) 121 | 122 | return article_id 123 | 124 | 125 | async def process_articles_async(query, limit=10): 126 | """ 127 | Process a list of articles asynchronously, by fetching content, summarizing, extracting keywords and analyzing sentiment. 128 | 129 | Args: 130 | query (str): The query to search for in the NewsAPI. 131 | limit (int, optional): The number of articles to fetch. Defaults to 10. 132 | 133 | Returns: 134 | List[str]: The IDs of the articles that were processed. 135 | """ 136 | logger.info("Starting the processing of articles.") 137 | article_ids = fetch_news( 138 | query=query, 139 | from_date="2024-08-16", 140 | sort_by="popularity", 141 | limit=limit, 142 | to_json=False, 143 | ) 144 | if not isinstance(article_ids, list): 145 | raise ValueError("article_ids should be a list") 146 | 147 | async with ClientSession() as session: 148 | tasks = [ 149 | process_single_article_async(article_id, session) 150 | for article_id in article_ids 151 | ] 152 | await asyncio.gather(*tasks) 153 | 154 | logger.info("Processing completed.") 155 | return article_ids 156 | 157 | 158 | def process_articles(query, limit=10): 159 | """ 160 | Process a list of articles by fetching content, summarizing, extracting keywords and analyzing sentiment. 161 | 162 | Args: 163 | query (str): The query to search for in the NewsAPI. 164 | limit (int, optional): The number of articles to fetch. Defaults to 10. 165 | 166 | Returns: 167 | List[str]: The IDs of the articles that were processed. 168 | """ 169 | logger.info("Starting the processing of articles.") 170 | article_ids = asyncio.run(process_articles_async(query, limit)) 171 | return article_ids 172 | # Fetch articles from NewsAPI 173 | article_ids = fetch_news( 174 | query=query, 175 | from_date="2024-08-04", 176 | sort_by="popularity", 177 | limit=limit, 178 | to_json=False, 179 | ) 180 | if not isinstance(article_ids, list): 181 | raise ValueError("article_ids should be a list") 182 | 183 | # Get contents for each article 184 | article_contents = fetch_article_content(article_ids) 185 | 186 | # contents_file = f"{query.replace(' ', '_')}_contents2.json" 187 | # with open(contents_file, "w", encoding="utf-8") as f: 188 | # json.dump(article_contents, f, ensure_ascii=False, indent=4) 189 | 190 | # Summarize the articles 191 | logger.info("Summarizing articles.") 192 | article_summaries = summarize_texts(article_ids) 193 | 194 | # summaries_file = f"{query.replace(' ', '_')}_summaries2.json" 195 | # with open(summaries_file, "w", encoding="utf-8") as f: 196 | # json.dump(article_summaries, f, ensure_ascii=False, indent=4) 197 | 198 | # Extract keywords from summaries 199 | logger.info("Extracting keywords from summaries.") 200 | article_keywords = extract_keywords(article_ids, top_n=10) 201 | 202 | # keywords_file = f"{query.replace(' ', '_')}_keywords2.json" 203 | # with open(keywords_file, "w", encoding="utf-8") as f: 204 | # json.dump(article_keywords, f, ensure_ascii=False, indent=4) 205 | 206 | # Analyze sentiments of summaries 207 | logger.info("Analyzing sentiments of summaries.") 208 | article_sentiments = analyze_sentiments(article_ids) 209 | 210 | 211 | if __name__ == "__main__": 212 | logger.info("Starting the processing of articles.") 213 | 214 | article_ids = process_articles("Adani Hindenburg Report", limit=10) 215 | logger.info(f"Article IDs: {article_ids}") 216 | 217 | # news_data = fetch_news( 218 | # query="Kolkata Murder Case", from_date="2024-08-01", sort_by="popularity", to_json=False 219 | # ) 220 | # urls = [article.get("url") for article in news_data.get("articles", [])] 221 | 222 | # # Process articles 223 | # keywords, sentiments, wordcloud = process_articles(urls) 224 | # logger.info(f"Keywords: {keywords}") 225 | # logger.info(f"Sentiments: {sentiments}") 226 | # wordcloud.to_image().save("wordcloud.png") 227 | # logger.info("Processing of articles completed successfully.") 228 | -------------------------------------------------------------------------------- /src/preprocessing/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/src/preprocessing/__init__.py -------------------------------------------------------------------------------- /src/preprocessing/keyword_extraction.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from typing import List 3 | 4 | import nltk 5 | from keybert import KeyBERT 6 | from nltk.corpus import stopwords 7 | from nltk.tokenize import word_tokenize 8 | 9 | from src.utils.dbconnector import append_to_document, find_documents 10 | from src.utils.logger import setup_logger 11 | 12 | nltk.download("punkt") 13 | nltk.download("stopwords") 14 | 15 | # Setup logger 16 | logger = setup_logger() 17 | 18 | 19 | # Not in use 20 | def preprocess_text(text): 21 | """ 22 | Preprocesses a given text by tokenizing it and removing stopwords. 23 | 24 | Args: 25 | text (str): The text to preprocess. 26 | 27 | Returns: 28 | List[str]: A list of words without stopwords. 29 | """ 30 | 31 | logger.info("Preprocessing text for tokenization and stopword removal.") 32 | stop_words = set(stopwords.words("english")) 33 | try: 34 | words = word_tokenize(text) 35 | except Exception as e: 36 | logger.error("Error during tokenization: %s", e) 37 | return [] 38 | filtered_words = [ 39 | word for word in words if word.isalnum() and word.lower() not in stop_words 40 | ] 41 | logger.info("Text preprocessed successfully.") 42 | return filtered_words 43 | 44 | 45 | # Not in use 46 | def bert_keyword_extraction(texts: List[str], top_n: int = 10) -> List[str]: 47 | """ 48 | Extracts keywords from a list of texts using KeyBERT. 49 | 50 | Args: 51 | texts (List[str]): List of texts to extract keywords from. 52 | top_n (int): Number of top keywords to extract per text. 53 | 54 | Returns: 55 | List[str]: List of unique extracted keywords. 56 | """ 57 | logger.info("Starting keyword extraction using KeyBERT.") 58 | model = KeyBERT("all-MiniLM-L6-v2") 59 | 60 | all_keywords = [] 61 | for text in texts: 62 | keywords = model.extract_keywords( 63 | text, keyphrase_ngram_range=(1, 2), top_n=top_n 64 | ) 65 | all_keywords.extend([kw[0] for kw in keywords]) 66 | 67 | logger.info("KeyBERT keyword extraction completed successfully.") 68 | return list(set(all_keywords)) # Return unique keywords 69 | 70 | 71 | def extract_keywords(article_ids, top_n: int = 10): 72 | """ 73 | Extracts keywords from a list of texts using KeyBERT. 74 | 75 | Args: 76 | texts (List[str]): List of texts to extract keywords from. 77 | top_n (int): Number of top keywords to extract per text. 78 | 79 | Returns: 80 | It returns something else not a list of list of str. 81 | List[List[str]]: List of keyword lists for each text. 82 | """ 83 | article_summaries = [] 84 | documents = find_documents("News_Articles", {"id": {"$in": article_ids}}) 85 | for doc in documents: 86 | article_summaries.append({"id": doc["id"], "summary": doc["summary"]}) 87 | 88 | logger.info("Initializing KeyBERT model for keyword extraction.") 89 | model = KeyBERT("all-MiniLM-L6-v2") 90 | 91 | article_keywords = [] 92 | logger.info(f"Extracting keywords from {len(article_summaries)} texts.") 93 | for idx, obj in enumerate(article_summaries): 94 | logger.debug( 95 | f"Extracting keywords from text {idx+1}/{len(article_summaries)}.") 96 | try: 97 | keywords = model.extract_keywords( 98 | obj.get("summary"), 99 | keyphrase_ngram_range=(1, 2), 100 | stop_words="english", 101 | top_n=top_n, 102 | ) 103 | extracted_keywords = [kw[0] for kw in keywords] 104 | keyword_obj = {"id": obj.get("id"), "keywords": extracted_keywords} 105 | 106 | article_keywords.append(keyword_obj) 107 | append_to_document("News_Articles", { 108 | "id": obj.get("id")}, keyword_obj) 109 | logger.debug(f"Keywords for text {idx+1}: {extracted_keywords}") 110 | except Exception as e: 111 | logger.error(f"Error extracting keywords from text {idx+1}: {e}") 112 | article_keywords.append([]) 113 | logger.info("Keyword extraction completed.") 114 | 115 | # -------- 116 | # MongoDB code to store article keywords 117 | # -------- 118 | 119 | return article_keywords 120 | 121 | 122 | # def aggregate_keywords(texts, top_n=10): 123 | # logger.info("Aggregating keywords across all articles.") 124 | # keywords = extract_keywords(texts, top_n) 125 | # logger.info(f"Top {top_n} aggregated keywords: {keywords}") 126 | # return keywords 127 | -------------------------------------------------------------------------------- /src/preprocessing/summarization.py: -------------------------------------------------------------------------------- 1 | import os 2 | from typing import List 3 | 4 | import google.generativeai as genai 5 | from dotenv import load_dotenv 6 | from google.generativeai.types import HarmBlockThreshold, HarmCategory 7 | 8 | from src.utils.dbconnector import append_to_document, find_documents 9 | from src.utils.logger import setup_logger 10 | 11 | load_dotenv() 12 | 13 | genai.configure(api_key=os.environ["GEMINI_API_KEY"]) 14 | 15 | 16 | # Setup logger 17 | logger = setup_logger() 18 | 19 | 20 | def summarize_texts( 21 | articles_id: List[str], max_length: int = 200, min_length: int = 20 22 | ): 23 | """ 24 | Summarizes a list of texts using a pre-trained Transformer model. 25 | 26 | Args: 27 | texts (List[str]): List of texts to summarize. 28 | max_length (int): Maximum length of the summary. 29 | min_length (int): Minimum length of the summary. 30 | 31 | Returns: 32 | List[str]: List of summarized texts. 33 | """ 34 | texts = [] 35 | logger.info("Initializing summarization pipeline.") 36 | articles = find_documents("News_Articles", {"id": {"$in": articles_id}}) 37 | for article in articles: 38 | texts.append( 39 | {"id": article["id"], "content": article.get("content", "")}) 40 | article_summaries = [] 41 | 42 | logger.info(f"Starting summarization of {len(texts)} texts.") 43 | for idx, obj in enumerate(texts): 44 | logger.debug(f"Summarizing text {idx+1}/{len(texts)}.") 45 | try: 46 | model = genai.GenerativeModel("gemini-1.5-flash") 47 | prompt = f""" 48 | Summarize the provided news document while preserving the most important keywords and maintaining the original sentiment or tone. Ensure that the summary is concise, accurately reflects the key points, and retains the emotional impact or intent of the original content. 49 | 50 | News Article: 51 | {obj.get("content")} 52 | """ 53 | response = model.generate_content( 54 | prompt, 55 | safety_settings={ 56 | HarmCategory.HARM_CATEGORY_HATE_SPEECH: HarmBlockThreshold.BLOCK_NONE, 57 | HarmCategory.HARM_CATEGORY_HARASSMENT: HarmBlockThreshold.BLOCK_NONE, 58 | HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT: HarmBlockThreshold.BLOCK_NONE, 59 | HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT: HarmBlockThreshold.BLOCK_NONE, 60 | }, 61 | ) 62 | logger.debug(f"DEBUG SUmmary{response.text}") 63 | article_summaries.append( 64 | {"id": obj.get("id"), "summary": response.text}) 65 | append_to_document( 66 | "News_Articles", {"id": obj.get("id")}, { 67 | "summary": response.text} 68 | ) 69 | logger.debug(f"Summary {idx+1}: {response.text}") 70 | 71 | except Exception as e: 72 | logger.error(f"Error summarizing text {idx+1}: {e}") 73 | article_summaries.append("") 74 | append_to_document("News_Articles", { 75 | "id": obj.get("id")}, {"summary": ""}) 76 | 77 | logger.info("Summarization completed.") 78 | return article_summaries 79 | 80 | 81 | if __name__ == "__main__": 82 | # Test summarization 83 | texts = [ 84 | { 85 | "id": "1", 86 | "content": "Early on Friday morning, a 31-year-old female trainee doctor retired to sleep in a seminar hall after a gruelling day at one of India’s oldest hospitals.\nIt was the last time she was seen alive.\nThe next morning, her colleagues discovered her half-naked body on the podium, bearing extensive injuries. Police later arrested a hospital volunteer worker in connection with what they say is a case of rape and murder at Kolkata’s 138-year-old RG Kar Medical College.\nTens of thousands of women in Kolkata and across West Bengal state are expected to participate in a 'Reclaim the Night' march at midnight on Wednesday, demanding the \"independence to live in freedom and without fear\". The march takes place just before India's Independence Day on Thursday. Outraged doctors have struck work both in the city and across India, demanding a strict federal law to protect them.\nThe tragic incident has again cast a spotlight on the violence against doctors and nurses in the country. Reports of doctors, regardless of gender, being assaulted by patients and their relatives have gained widespread attention. Women - who make up nearly 30% of India’s doctors and 80% of the nursing staff - are more vulnerable than their male colleagues. \nThe crime in the Kolkata hospital last week exposed the alarming security risks faced by the medical staff in many of India's state-run health facilities.\nAt RG Kar Hospital, which sees over 3,500 patients daily, the overworked trainee doctors - some working up to 36 hours straight - had no designated rest rooms, forcing them to seek rest in a third-floor seminar room. \nReports indicate that the arrested suspect, a volunteer worker with a troubled past, had unrestricted access to the ward and was captured on CCTV. Police allege that no background checks were conducted on the volunteer.\n\"The hospital has always been our first home; we only go home to rest. We never imagined it could be this unsafe. Now, after this incident, we're terrified,\" says Madhuparna Nandi, a junior doctor at Kolkata’s 76-year-old National Medical College.\nDr Nandi’s own journey highlights how female doctors in India's government hospitals have become resigned to working in conditions that compromise their security. \nAt her hospital, where she is a resident in gynaecology and obstetrics, there are no designated rest rooms and separate toilets for female doctors.\n“I use the patients’ or the nurses' toilets if they allow me. When I work late, I sometimes sleep in an empty patient bed in the ward or in a cramped waiting room with a bed and basin,” Dr Nandi told me.\nShe says she feels insecure even in the room where she rests after 24-hour shifts that start with outpatient duty and continue through ward rounds and maternity rooms.\nOne night in 2021, during the peak of the Covid pandemic, some men barged into her room and woke her by touching her, demanding, “Get up, get up. See our patient.”\n“I was completely shaken by the incident. But we never imagined it would come to a point where a doctor could be raped and murdered in the hospital,” Dr Nandi says.\nWhat happened on Friday was not an isolated incident. The most shocking case remains that of Aruna Shanbaug, a nurse at a prominent Mumbai hospital, who was left in a persistent vegetative state after being raped and strangled by a ward attendant in 1973. She died in 2015, after 42 years of severe brain damage and paralysis. More recently, in Kerala, Vandana Das, a 23-year-old medical intern, was fatally stabbed with surgical scissors by a drunken patient last year.\nIn overcrowded government hospitals with unrestricted access, doctors often face mob fury from patients' relatives after a death or over demands for immediate treatment. Kamna Kakkar, an anaesthetist, remembers a harrowing incident during a night shift in an intensive care unit (ICU) during the pandemic in 2021 at her hospital in Haryana in northern India.\n“I was the lone doctor in the ICU when three men, flaunting a politician’s name, forced their way in, demanding a much in-demand controlled drug. I gave in to protect myself, knowing the safety of my patients was at stake,\" Dr Kakkar told me.\nNamrata Mitra, a Kolkata-based pathologist who studied at the RG Kar Medical College, says her doctor father would often accompany her to work because she felt unsafe.\n“During my on-call duty, I took my father with me. Everyone laughed, but I had to sleep in a room tucked away in a long, dark corridor with a locked iron gate that only the nurse could open if a patient arrived,” Dr Mitra wrote in a Facebook post over the weekend.\n“I’m not ashamed to admit I was scared. What if someone from the ward - an attendant, or even a patient - tried something? I took advantage of the fact that my father was a doctor, but not everyone has that privilege.”\nWhen she was working in a public health centre in a district in West Bengal, Dr Mitra spent nights in a dilapidated one-storey building that served as the doctor’s hostel.\n“From dusk, a group of boys would gather around the house, making lewd comments as we went in and out for emergencies. They would ask us to check their blood pressure as an excuse to touch us and they would peek through the broken bathroom windows,” she wrote.\nYears later, during an emergency shift at a government hospital, “a group of drunk men passed by me, creating a ruckus, and one of them even groped me”, Dr Mitra said. “When I tried to complain, I found the police officers dozing off with their guns in hand.”\nThings have worsened over the years, says Saraswati Datta Bodhak, a pharmacologist at a government hospital in West Bengal's Bankura district. \"Both my daughters are young doctors and they tell me that hospital campuses in the state are overrun by anti-social elements, drunks and touts,\" she says. Dr Bodhak recalls seeing a man with a gun roaming around a top government hospital in Kolkata during a visit.\nIndia lacks a stringent federal law to protect healthcare workers. Although 25 states have some laws to prevent violence against them, convictions are “almost non-existent”, RV Asokan, president of the Indian Medical Association (IMA), an organisation of doctors, told me. A 2015 survey by IMA found that 75% of doctors in India have faced some form of violence at work. “Security in hospitals is almost absent,” he says. “One reason is that nobody thinks of hospitals as conflict zones.”\nSome states like Haryana have deployed private bouncers to strengthen security at government hospitals. In 2022, the federal government asked the states to deploy trained security forces for sensitive hospitals, install CCTV cameras, set up quick reaction teams, restrict entry to \"undesirable individuals\" and file complaints against offenders. Nothing much has happened, clearly. \nEven the protesting doctors don't seem to be very hopeful. “Nothing will change... The expectation will be that doctors should work round the clock and endure abuse as a norm,” says Dr Mitra. It is a disheartening thought.\nWith his song Big Dawgs, Hanumankind has fast become a name to reckon with in the global hip-hop scene.\nEighty years on, three survivors recall the catastrophe which killed at least three million people.\nThe building is to become an Ibis hotel, but one floor is now being used by the Indian Consulate.\nThe venture will form India's biggest entertainment player, competing with Sony, Netflix, and Amazon.\nSeveral rivers and reservoirs are overflowing as water levels have crossed the danger mark.\nCopyright 2024 BBC. All rights reserved.  The BBC is not responsible for the content of external sites. Read about our approach to external linking.", 87 | }, 88 | { 89 | "id": "2", 90 | "content": 'The rape and murder of a trainee doctor in India’s Kolkata city earlier this month has sparked massive outrage in the country, with tens of thousands of people protesting on the streets, demanding justice. BBC Hindi spoke to the doctor’s parents who remember their daughter as a clever, young woman who wanted to lead a good life and take care of her family.\nAll names and details of the family have been removed as Indian laws prohibit identifying a rape victim or her family.\n"Please make sure dad takes his medicines on time. Don\'t worry about me."\nThis was the last thing the 31-year-old doctor said to her mother, hours before she was brutally assaulted in a hospital where she worked. \n“The next day, we tried reaching her but the phone kept ringing," the mother told the BBC at their family home in a narrow alley, a few kilometres from Kolkata.\nThe same morning, the doctor’s partially-clothed body was discovered in the seminar hall, bearing extensive injuries. A hospital volunteer worker has been arrested in connection with the crime.\nThe incident has sparked massive outrage across the country, with protests in several major cities. At the weekend, doctors across hospitals in India observed a nation-wide strike called by the Indian Medical Association (IMA), with only emergency services available at major hospitals.\nThe family say they feel hollowed out by their loss.\n“At the age of 62, all my dreams have been shattered," her father told the BBC. \nSince their daughter\'s horrific murder, their house, located in a respectable neighbourhood, has become the focus of intense media scrutiny. \nBehind a police barricade stand dozens of journalists and camera crew, hoping to capture the parents in case they step out.\nA group of 10 to 15 police officers perpetually stand guard to ensure the cameras do not take photos of the victim\'s house.\nThe crime took place on the night of 9 August, when the woman, who was a junior doctor at the city\'s RG Kar Medical College, had gone to a seminar room to rest after a gruelling 36-hour shift. \nHer parents remembered how the young doctor, their only child, was a passionate student who worked extremely hard to become a doctor. \n“We come from a lower middle-class background and built everything on our own. When she was little, we struggled financially," said the father, who is a tailor.\nThe living room where he sat was cluttered with tools from his profession - a sewing machine, spools of thread and a heavy iron. There were scraps of fabrics scattered on the floor. \nThere were times when the family did not have money to even buy pomegranates, their daughter\'s favourite fruit, he continued. \n"But she could never bring herself to ask for anything for herself."\n“People would say, ‘You can’t make your daughter a doctor\'. But my daughter proved everyone wrong and got admission in a government-run medical college," he added, breaking down. A relative tried to console him.\nThe mother recalled how her daughter would write in her diary every night before going to bed.\n“She wrote that she wanted to win a gold medal for her medical degree. She wanted to lead a good life and take care of us too,” she said softly.\nAnd she did. \nThe father, who is a high blood-pressure patient, said their daughter always made sure he took his medicines on time. \n“Once I ran out of medicine and thought I’d just buy it the next day. But she found out, and even though it was around 10 or 11pm at night, she said no-one will eat until the medicine is here,” he said.\n“That’s how she was - she never let me worry about anything."\nHer mother listened intently, her hands repeatedly touching a gold bangle on her wrist - a bangle she had bought with her daughter.\nThe parents said their daughter’s marriage had almost been finalised. "But she would tell us not to worry and say she would continue to take care of all our expenses even after marriage," the father said. \nAs he spoke those words, the mother began to weep, her soft sobs echoing in the background.\nOccasionally, her eyes would wander to the staircase, leading up to their daughter\'s room.\nThe door has remained shut since 10 August and the parents have not set foot there since the news of her death.\nThey say they still can\'t believe that something "so barbaric" could happen to their daughter at her workplace. \n"The hospital should be a safe place," the father said. \nViolence against women is a major issue in India - an average of 90 rapes a day were reported in 2022, according to government data.\nThe parents said their daughter’s death had brought back memories of a 2012 case when a 22-year-old physiotherapy intern was gang-raped on a moving bus in capital Delhi. Her injuries were fatal.\nFollowing the assault - which made global headlines and led to weeks of protests - India tightened laws against sexual violence.\nBut reported cases of sexual assault have gone up and access to justice still remains a challenge for women.\nLast week, thousands participated in a Reclaim the Night march held in Kolkata to demand safety for women across the country.\nThe doctor’s case has also put a spotlight on challenges faced by healthcare workers, who have demanded a thorough and impartial investigation into the murder and a federal law to protect them - especially women - at work.\nFederal Health Minister JP Nadda has assured doctors that he will bring in strict measures to ensure better safety in their professional environments.\nBut for the parents of the doctor, it\'s too little too late.\n“We want the harshest punishment for the culprit," the father said.\n“Our state, our country and the whole world is asking for justice for our daughter."\nWith his song Big Dawgs, Hanumankind has fast become a name to reckon with in the global hip-hop scene.\nEighty years on, three survivors recall the catastrophe which killed at least three million people.\nThe building is to become an Ibis hotel, but one floor is now being used by the Indian Consulate.\nAmi and Stuart Geddes son Clark was delivered at 24 weeks due to complications and lived for just 12 days.\nThe venture will form India\'s biggest entertainment player, competing with Sony, Netflix, and Amazon.\nCopyright 2024 BBC. All rights reserved.  The BBC is not responsible for the content of external sites. Read about our approach to external linking.', 91 | }, 92 | ] 93 | print("Here") 94 | summaries = summarize_texts(texts) 95 | print("Now here") 96 | print(summaries) 97 | -------------------------------------------------------------------------------- /src/sentiment_analysis/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/src/sentiment_analysis/__init__.py -------------------------------------------------------------------------------- /src/sentiment_analysis/classify.py: -------------------------------------------------------------------------------- 1 | from typing import Dict, List, Tuple 2 | 3 | from src.sentiment_analysis.sentiment_model import analyze_sentiments 4 | from src.utils.logger import setup_logger 5 | 6 | # Setup logger 7 | logger = setup_logger() 8 | 9 | 10 | def classify_sentiments(texts: List[str]) -> Dict[str, List[Tuple[str, float]]]: 11 | """ 12 | Classify the sentiment of multiple texts. 13 | 14 | Args: 15 | texts (List[str]): List of text to classify sentiment for. 16 | 17 | Returns: 18 | Dict[str, List[Tuple[str, float]]]: Dictionary with three keys: 'positive', 'negative', 'neutral'. 19 | Each key maps to a list of tuples, where the first element of the tuple is the text and the second 20 | element is the sentiment score. 21 | """ 22 | if not texts: 23 | raise ValueError("Input texts should not be empty.") 24 | logger.info("Classifying sentiments of multiple articles.") 25 | results = {"positive": [], "negative": [], "neutral": []} 26 | for text in texts: 27 | sentiment = analyze_sentiment(text) 28 | label = sentiment[0]["label"] 29 | score = sentiment[0]["score"] 30 | 31 | if label == "POSITIVE": 32 | results["positive"].append((text, score)) 33 | elif label == "NEGATIVE": 34 | results["negative"].append((text, score)) 35 | else: 36 | results["neutral"].append((text, score)) 37 | 38 | logger.info("Sentiment classification completed.") 39 | return results 40 | -------------------------------------------------------------------------------- /src/sentiment_analysis/sentiment_model.py: -------------------------------------------------------------------------------- 1 | from typing import Dict, List 2 | 3 | from transformers import pipeline 4 | 5 | from src.utils.dbconnector import append_to_document, find_documents 6 | from src.utils.logger import setup_logger 7 | 8 | # Setup logger 9 | logger = setup_logger() 10 | 11 | 12 | def analyze_sentiments(article_ids: List[str]) -> List[Dict[str, float]]: 13 | """ 14 | Analyze the sentiment of a list of article IDs. 15 | 16 | Args: 17 | article_ids (List[str]): List of article IDs to analyze. 18 | 19 | Returns: 20 | List[Dict[str, float]]: List of sentiment analysis results for each text. 21 | """ 22 | article_obj = [] # This object should have id, title and description 23 | documents = find_documents("News_Articles", {"id": {"$in": article_ids}}) 24 | for doc in documents: 25 | article_obj.append( 26 | { 27 | "id": doc["id"], 28 | "title": doc["title"], 29 | "description": doc.get("content", ""), 30 | } 31 | ) 32 | 33 | logger.info("Initializing sentiment analysis pipeline.") 34 | sentiment_analyzer = pipeline( 35 | "sentiment-analysis", model="cardiffnlp/twitter-roberta-base-sentiment-latest" 36 | ) 37 | 38 | article_sentiments = [] 39 | logger.info(f"Analyzing sentiments for {len(article_obj)} texts.") 40 | for idx, obj in enumerate(article_obj): 41 | logger.debug( 42 | f"Analyzing sentiment for text {idx+1}/{len(article_obj)}.") 43 | try: 44 | analysis = sentiment_analyzer(obj.get("description")[:511]) 45 | print("Analysis", analysis) 46 | sentiment_obj = { 47 | "id": obj.get("id"), 48 | "sentiment": analysis[0]["label"], 49 | "sentiment_score": analysis[0]["score"], 50 | } 51 | article_sentiments.append(sentiment_obj) 52 | append_to_document("News_Articles", { 53 | "id": obj.get("id")}, sentiment_obj) 54 | logger.debug(f"Sentiment for text {idx+1}: {sentiment_obj}") 55 | 56 | except Exception as e: 57 | logger.error(f"Error analyzing sentiment for text {idx+1}: {e}") 58 | article_sentiments.append({"label": "UNKNOWN", "score": 0.0}) 59 | append_to_document( 60 | "News_Articles", 61 | {"id": obj.get("id")}, 62 | {"sentiment": "UNKNOWN", "sentiment_score": 0.0}, 63 | ) 64 | 65 | logger.info("Sentiment analysis completed.") 66 | return article_sentiments 67 | 68 | 69 | if __name__ == "__main__": 70 | # Test the function 71 | text = "A female trainee doctor was found dead in a seminar hall at a Kolkata hospital, sparking outrage and protests demanding safety for medical professionals. The incident, believed to be rape and murder, highlights the alarming security risks faced by doctors and nurses, particularly women, in India's government hospitals. Lack of designated rest rooms, unrestricted access to wards, and a lack of background checks for volunteers contribute to the vulnerability. Despite calls for stricter federal laws and increased security measures, many doctors remain pessimistic, feeling resigned to working in unsafe conditions. The article highlights the pervasive issue of violence against healthcare workers in India, with doctors often facing threats and assaults from patients, their relatives, and even hospital staff." 72 | analyze_sentiments([{"id": 1, "summary": text}]) 73 | -------------------------------------------------------------------------------- /src/sentiment_analysis/wordcloud.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | 3 | import matplotlib.pyplot as plt 4 | from wordcloud import WordCloud 5 | 6 | from src.utils.logger import setup_logger 7 | 8 | # Setup logger 9 | logger = setup_logger() 10 | 11 | 12 | def generate_wordcloud(keywords: List[str], sentiment_label: str) -> WordCloud: 13 | """ 14 | Generates a word cloud for the given list of keywords and sentiment label. 15 | 16 | Args: 17 | keywords (List[str]): List of keywords to include in the word cloud. 18 | sentiment_label (str): Sentiment label to generate the word cloud for. 19 | 20 | Returns: 21 | WordCloud: The generated word cloud. 22 | """ 23 | logger.info(f"Generating word cloud for {sentiment_label} sentiment.") 24 | text = " ".join(keywords) 25 | wordcloud = WordCloud( 26 | width=800, height=400, background_color="white", colormap="viridis" 27 | ).generate(text) 28 | return wordcloud 29 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/src/styles.css -------------------------------------------------------------------------------- /src/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/src/utils/__init__.py -------------------------------------------------------------------------------- /src/utils/dbconnector.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import pandas as pd 4 | from bson import ObjectId 5 | from dotenv import load_dotenv 6 | from pymongo import MongoClient 7 | 8 | from src.utils.logger import setup_logger 9 | 10 | logger = setup_logger() 11 | 12 | # Load environment variables 13 | load_dotenv() 14 | 15 | 16 | def get_mongo_client(): 17 | """ 18 | Connects to MongoDB and returns the database object. 19 | 20 | Uses environment variables for connection: 21 | MONGO_USERNAME: username for MongoDB authentication 22 | MONGO_PASSWORD: password for MongoDB authentication 23 | MONGO_DB_NAME: name of the database to connect to 24 | 25 | Returns: 26 | pymongo.database.Database: the connected database object 27 | 28 | Raises: 29 | Exception: if connection fails 30 | """ 31 | try: 32 | mongo_uri = f"mongodb+srv://{os.getenv('MONGO_USERNAME')}:{os.getenv('MONGO_PASSWORD')}@devasy23.a8hxla5.mongodb.net/?retryWrites=true&w=majority&appName=Devasy23" 33 | db_name = os.getenv("DB_NAME") 34 | client = MongoClient( 35 | mongo_uri, socketTimeoutMS=60000, connectTimeoutMS=60000) 36 | db = client[db_name] 37 | logger.info("Successfully connected to MongoDB.") 38 | return db 39 | except Exception as e: 40 | logger.error(f"Failed to connect to MongoDB: {e}") 41 | raise 42 | 43 | 44 | def content_manager(article_id, required_fields): 45 | """ 46 | Checks if the specified fields are present in the database for the given article_id. 47 | 48 | Args: 49 | article_id (str): The ID of the article to check. 50 | required_fields (list): A list of fields to check for presence (e.g., ["content", "summary", "keywords", "sentiment"]). 51 | 52 | Returns: 53 | dict: A dictionary with the status of each field (True if present, False if not). 54 | """ 55 | # Connect to the MongoDB 56 | db = get_mongo_client() 57 | collection = db["News_Articles"] 58 | 59 | # Query the document by article_id 60 | article = collection.find_one({"id": article_id}) 61 | 62 | # Check for the required fields 63 | field_status = { 64 | field: field in article and bool(article[field]) for field in required_fields 65 | } 66 | 67 | return field_status 68 | 69 | 70 | def insert_document(collection_name, document): 71 | """ 72 | Inserts a document into the given collection. 73 | 74 | Args: 75 | collection_name (str): The name of the collection. 76 | document (dict): The document to be inserted. 77 | 78 | Returns: 79 | str: The ID of the inserted document. 80 | 81 | Raises: 82 | Exception: If there is an error inserting the document. 83 | """ 84 | db = get_mongo_client() 85 | collection = db[collection_name] 86 | try: 87 | result = collection.insert_one(document) 88 | logger.info(f"Document inserted with ID: {result.inserted_id}") 89 | return result.inserted_id 90 | except Exception as e: 91 | logger.error(f"Failed to insert document: {e}") 92 | raise 93 | 94 | 95 | def find_one_document(collection_name, query): 96 | """ 97 | Finds a single document in the given MongoDB collection using the given query. 98 | 99 | Args: 100 | collection_name (str): The name of the collection. 101 | query (dict): The query to select documents. 102 | 103 | Returns: 104 | dict: The selected document. 105 | 106 | Raises: 107 | Exception: If there is an error finding the document. 108 | """ 109 | db = get_mongo_client() 110 | collection = db[collection_name] 111 | try: 112 | result = collection.find_one(query) 113 | return result 114 | except Exception as e: 115 | logger.error(f"Failed to find document: {e}") 116 | raise 117 | 118 | 119 | def append_to_document(collection_name, query, update_data): 120 | """ 121 | Appends new data to an existing document in the MongoDB collection. 122 | 123 | Args: 124 | collection_name (str): The name of the MongoDB collection. 125 | query (dict): The query to select the document to update. 126 | update_data (dict): The new data to be appended to the document. 127 | 128 | Returns: 129 | int: The number of documents updated. 130 | """ 131 | db = get_mongo_client() 132 | collection = db[collection_name] 133 | try: 134 | result = collection.update_one(query, {"$set": update_data}) 135 | if result.modified_count > 0: 136 | logger.info(f"Document updated successfully.") 137 | else: 138 | logger.warning( 139 | f"No document matched the query. No update performed.") 140 | return result.modified_count 141 | except Exception as e: 142 | logger.error(f"Failed to update document: {e}") 143 | raise 144 | 145 | 146 | def find_documents(collection_name, query): 147 | """ 148 | Finds documents in the given MongoDB collection using the given query. 149 | 150 | Args: 151 | collection_name (str): The name of the MongoDB collection. 152 | query (dict): The query to select documents. 153 | 154 | Returns: 155 | list: A list of documents found by the query. 156 | 157 | Raises: 158 | Exception: If there is an error finding documents. 159 | """ 160 | db = get_mongo_client() 161 | collection = db[collection_name] 162 | try: 163 | documents = collection.find(query) 164 | return documents 165 | except Exception as e: 166 | logger.error(f"Failed to find documents: {e}") 167 | raise 168 | 169 | 170 | def fetch_and_combine_articles(collection_name, article_ids): 171 | """ 172 | Fetches documents from the given MongoDB collection using the given IDs and combines them into a Pandas DataFrame. 173 | 174 | Args: 175 | collection_name (str): The name of the MongoDB collection. 176 | article_ids (List[str]): List of IDs of the articles to fetch and combine. 177 | 178 | Returns: 179 | pd.DataFrame: A Pandas DataFrame containing the combined documents. 180 | 181 | Raises: 182 | Exception: If there is an error fetching and combining the documents. 183 | """ 184 | db = get_mongo_client() 185 | collection = db[collection_name] 186 | 187 | # Debug log to check what is being passed to the function 188 | logger.debug(f"Received article_ids: {article_ids}") 189 | 190 | try: 191 | # Ensure article_ids is a list and not None 192 | 193 | # Query MongoDB to find documents by their IDs 194 | query = {"id": {"$in": article_ids}} 195 | documents = collection.find(query) 196 | logger.info(f"Fetched {documents} documents for the given IDs.") 197 | 198 | # Prepare a list of documents 199 | docs = [] 200 | for doc in documents: 201 | doc["_id"] = str( 202 | doc["_id"] 203 | ) # Convert ObjectId to string for easier handling 204 | docs.append(doc) 205 | 206 | # Convert the list of documents to a DataFrame 207 | df = pd.DataFrame(docs) 208 | print(df.drop(columns=["_id", "id"], inplace=True)) 209 | if df.empty: 210 | logger.warning("No documents found for the provided article IDs.") 211 | else: 212 | logger.info("Successfully converted documents to DataFrame.") 213 | logger.debug(df.columns) 214 | 215 | return df 216 | 217 | except Exception as e: 218 | logger.error(f"Failed to fetch and combine articles: {e}") 219 | raise 220 | -------------------------------------------------------------------------------- /src/utils/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from logging.handlers import RotatingFileHandler 3 | 4 | import colorlog 5 | 6 | 7 | def setup_logger(log_file="app.log"): 8 | """ 9 | Sets up a logger with a console handler and a rotating file handler. 10 | 11 | The console handler has color coding for different log levels, while the 12 | file handler does not. The file handler will rotate the log file every 13 | 5MB, keeping up to 5 backups. 14 | 15 | Parameters: 16 | log_file (str): The name of the log file to write to. Defaults to 17 | "app.log". 18 | 19 | Returns: 20 | logger (logging.Logger): The configured logger. 21 | """ 22 | logger = logging.getLogger("news_api_logger") 23 | 24 | # Check if the logger already has handlers to avoid duplicate logs 25 | if not logger.hasHandlers(): 26 | logger.setLevel(logging.DEBUG) 27 | 28 | # Create console handler with color coding 29 | handler = colorlog.StreamHandler() 30 | handler.setLevel(logging.DEBUG) 31 | 32 | formatter = colorlog.ColoredFormatter( 33 | "%(log_color)s%(levelname)s%(reset)s: [%(asctime)s] %(filename)s:%(funcName)s:%(lineno)d - %(message)s", 34 | datefmt="%Y-%m-%d %H:%M:%S", 35 | log_colors={ 36 | "DEBUG": "cyan", 37 | "INFO": "green", 38 | "WARNING": "yellow", 39 | "ERROR": "red", 40 | "CRITICAL": "red,bg_white", 41 | }, 42 | ) 43 | handler.setFormatter(formatter) 44 | 45 | # Create rotating file handler 46 | file_handler = RotatingFileHandler( 47 | log_file, maxBytes=5000000, backupCount=5) 48 | file_handler.setFormatter( 49 | logging.Formatter( 50 | "%(levelname)s: [%(asctime)s] %(filename)s:%(funcName)s:%(lineno)d - %(message)s", 51 | datefmt="%Y-%m-%d %H:%M:%S", 52 | ) 53 | ) 54 | 55 | # Add handlers to the logger 56 | logger.addHandler(handler) 57 | logger.addHandler(file_handler) 58 | 59 | return logger 60 | -------------------------------------------------------------------------------- /wordcloud.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Multiverse-of-Projects/NewsAI/920b6861970f9a6fbee7f9e90599ee88f1af21bd/wordcloud.png --------------------------------------------------------------------------------