eco-code-analyzer


Nameeco-code-analyzer JSON
Version 0.3.3 PyPI version JSON
download
home_pagehttps://github.com/vinerya/eco-code-analyzer
SummaryA Python library that analyzes code for ecological impact and provides optimization suggestions
upload_time2024-09-17 16:08:11
maintainerNone
docs_urlNone
authorMoudather Chelbi
requires_python>=3.7
licenseNone
keywords code analysis environmental impact energy efficiency eco-friendly coding
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
# 🌍 **Eco-Code Analyzer** ![Eco-Friendly Badge](https://img.shields.io/badge/Eco-Friendly-green) ![Python](https://img.shields.io/badge/Python-3.x-blue)

Eco-Code Analyzer is a Python library that analyzes code for its ecological impact, providing developers with insights and recommendations to write more environmentally friendly and efficient code. By optimizing code for energy efficiency and resource usage, we can collectively reduce the carbon footprint of our software.

---

## 🛠️ **Installation**

Install Eco-Code Analyzer via pip:

```bash
pip install eco-code-analyzer
```

For development:

```bash
pip install eco-code-analyzer[dev]
```

---

## ✨ **Features**

- ♻️ Analyzes Python code for ecological impact
- 📊 Provides an overall eco-score and a detailed breakdown
- 💡 Offers improvement suggestions with examples and environmental impact estimates
- 🔍 Analyzes entire projects or individual files
- 🌱 Estimates potential energy savings and CO2 reduction
- 🌍 Calculates project carbon footprint
- ⏳ Analyzes Git history to track eco-score over time
- 📈 Generates visualizations of eco-score trends
- ⚙️ Supports custom configuration and rules
- 🌳 Allows users to contribute to tree planting based on analysis results

---

## 🚀 **Usage**

### As a Library

```python
from eco_code_analyzer import analyze_code, get_eco_score, get_improvement_suggestions, estimate_energy_savings

code = """ 
def example_function():
    result = []
    for i in range(100):
        result.append(i * 2)
    return result
"""

analysis_result = analyze_code(code)
eco_score = get_eco_score(analysis_result)
suggestions = get_improvement_suggestions(analysis_result)
energy_savings = estimate_energy_savings({'overall_score': eco_score})

print(f"Eco-Score: {eco_score}")
print("Improvement Suggestions:")
for suggestion in suggestions:
    print(f"- {suggestion['category']}: {suggestion['suggestion']}")
    print(f"  Impact: {suggestion['impact']}")
    print(f"  Example: {suggestion['example']}")
    print(f"  Environmental Impact: {suggestion['environmental_impact']}")

print("
Estimated Environmental Impact if Optimized:")
print(f"Potential Energy Savings: {energy_savings['energy_kwh_per_year']:.2f} kWh/year")
print(f"Potential CO2 Reduction: {energy_savings['co2_kg_per_year']:.2f} kg CO2/year")
print(f"Equivalent to planting: {energy_savings['trees_equivalent']:.2f} trees")
```

### As a Command-Line Tool

Analyze a single file:

```bash
eco-code-analyzer path/to/your/python_file.py
```

Analyze a project directory:

```bash
eco-code-analyzer path/to/your/project/directory -v
```

Generate a detailed report:

```bash
eco-code-analyzer path/to/your/project/directory -o report.json
```

Analyze Git history and visualize eco-score trend:

```bash
eco-code-analyzer path/to/your/project/directory -g -n 10 --visualize
```

Use a custom configuration:

```bash
eco-code-analyzer path/to/your/project/directory -c config.json
```

Contribute to tree planting based on analysis results:

```bash
eco-code-analyzer path/to/your/project/directory --contribute
```

---

## 🌿 **Environmental Impact and Tree Planting**

The Eco-Code Analyzer helps developers understand the environmental impact of their code by:

1. Estimating energy consumption and CO2 emissions for different code constructs
2. Providing an overall eco-score that reflects the code's environmental friendliness
3. Offering specific suggestions to improve code efficiency and reduce energy consumption
4. Calculating potential energy savings and CO2 reduction if the code is optimized
5. Tracking the project's eco-score over time to encourage continuous improvement
6. Estimating the equivalent number of trees that need to be planted to offset the code's environmental impact

By using the Eco-Code Analyzer, developers can:

- Reduce the energy consumption of their applications
- Lower the carbon footprint of their software
- Improve code performance and efficiency
- Raise awareness about the environmental impact of code
- Actively contribute to reforestation efforts based on their code's impact

The new tree planting feature allows users to take immediate action to offset their code's environmental impact. When using the `--contribute` flag, the tool will:

1. Calculate the number of trees equivalent to the potential CO2 reduction
2. Provide an estimated cost for planting these trees
3. Offer the user an option to contribute to a tree planting organization directly from the command line

Remember, every small optimization and contribution counts. By collectively improving our code's eco-friendliness and supporting reforestation efforts, we can make a significant impact on reducing the IT industry's carbon footprint and promoting a healthier planet.

---

## ⚙️ **Configuration**

You can customize the behavior of the Eco-Code Analyzer by providing a JSON configuration file. This includes the ability to adjust weights for different aspects of the analysis and configure the coefficients used in the calculations.

Here's an example configuration file:

```json
{
  "weights": {
    "energy_efficiency": 0.4,
    "resource_usage": 0.3,
    "code_optimizations": 0.2,
    "custom_rules": 0.1
  },
  "thresholds": {
    "eco_score": 0.7,
    "category_score": 0.6
  },
  "custom_rules": [
    {
      "name": "check_api_call_efficiency",
      "weight": 0.05
    }
  ],
  "coefficients": {
    "energy_consumption_per_cpu_cycle": 1e-9,
    "co2_emissions_per_kwh": 0.5,
    "base_energy_consumption_per_year": 100,
    "base_co2_emissions_per_year": 50,
    "trees_equivalent_factor": 2
  }
}
```

In this configuration:

- `weights`: Adjust the importance of different categories in the overall eco-score.
- `thresholds`: Set the levels at which warnings or suggestions are triggered.
- `custom_rules`: Add your own rules or adjust the weight of existing ones.
- `coefficients`: Configure the key assumptions used in environmental impact calculations:
  - `energy_consumption_per_cpu_cycle`: Energy consumed per CPU cycle (in joules)
  - `co2_emissions_per_kwh`: CO2 emitted per kWh of energy (varies by region)
  - `base_energy_consumption_per_year`: Assumed baseline energy consumption for a typical project (in kWh)
  - `base_co2_emissions_per_year`: Assumed baseline CO2 emissions for a typical project (in kg)
  - `trees_equivalent_factor`: Factor used to convert CO2 reduction to equivalent number of trees planted

By adjusting these coefficients, you can tailor the analysis to better match your specific environment or to reflect more recent data on energy consumption and emissions.

---

## 🤝 **Contributing**

Contributions are welcome! Please feel free to submit a Pull Request. Here are some ways you can contribute:

1. Add new rules for detecting eco-unfriendly code patterns
2. Improve the accuracy of energy consumption and CO2 emission estimates
3. Enhance the visualization capabilities
4. Add support for more programming languages
5. Improve documentation and provide usage examples
6. Refine the assumptions and coefficients used in the analysis
7. Expand the tree planting contribution feature with more options and partnerships

---

## 📄 **License**

This project is licensed under the MIT License.

---

## 🌱 **Let's Build a Greener Future, One Line of Code at a Time!**

By using the Eco-Code Analyzer, you're not just improving your code – you're contributing to a more sustainable future for software development and our planet. Together, we can make a significant impact on reducing the environmental footprint of the IT industry and supporting global reforestation efforts. Happy eco-coding!



            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/vinerya/eco-code-analyzer",
    "name": "eco-code-analyzer",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "code analysis, environmental impact, energy efficiency, eco-friendly coding",
    "author": "Moudather Chelbi",
    "author_email": "moudather.chelbi@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/62/5a/0e498857bdffb3724b0b7b81ce52c6dec4881d19927e9a4e88c0af954a1e/eco-code-analyzer-0.3.3.tar.gz",
    "platform": null,
    "description": "\n# \ud83c\udf0d **Eco-Code Analyzer** ![Eco-Friendly Badge](https://img.shields.io/badge/Eco-Friendly-green) ![Python](https://img.shields.io/badge/Python-3.x-blue)\n\nEco-Code Analyzer is a Python library that analyzes code for its ecological impact, providing developers with insights and recommendations to write more environmentally friendly and efficient code. By optimizing code for energy efficiency and resource usage, we can collectively reduce the carbon footprint of our software.\n\n---\n\n## \ud83d\udee0\ufe0f **Installation**\n\nInstall Eco-Code Analyzer via pip:\n\n```bash\npip install eco-code-analyzer\n```\n\nFor development:\n\n```bash\npip install eco-code-analyzer[dev]\n```\n\n---\n\n## \u2728 **Features**\n\n- \u267b\ufe0f Analyzes Python code for ecological impact\n- \ud83d\udcca Provides an overall eco-score and a detailed breakdown\n- \ud83d\udca1 Offers improvement suggestions with examples and environmental impact estimates\n- \ud83d\udd0d Analyzes entire projects or individual files\n- \ud83c\udf31 Estimates potential energy savings and CO2 reduction\n- \ud83c\udf0d Calculates project carbon footprint\n- \u23f3 Analyzes Git history to track eco-score over time\n- \ud83d\udcc8 Generates visualizations of eco-score trends\n- \u2699\ufe0f Supports custom configuration and rules\n- \ud83c\udf33 Allows users to contribute to tree planting based on analysis results\n\n---\n\n## \ud83d\ude80 **Usage**\n\n### As a Library\n\n```python\nfrom eco_code_analyzer import analyze_code, get_eco_score, get_improvement_suggestions, estimate_energy_savings\n\ncode = \"\"\" \ndef example_function():\n    result = []\n    for i in range(100):\n        result.append(i * 2)\n    return result\n\"\"\"\n\nanalysis_result = analyze_code(code)\neco_score = get_eco_score(analysis_result)\nsuggestions = get_improvement_suggestions(analysis_result)\nenergy_savings = estimate_energy_savings({'overall_score': eco_score})\n\nprint(f\"Eco-Score: {eco_score}\")\nprint(\"Improvement Suggestions:\")\nfor suggestion in suggestions:\n    print(f\"- {suggestion['category']}: {suggestion['suggestion']}\")\n    print(f\"  Impact: {suggestion['impact']}\")\n    print(f\"  Example: {suggestion['example']}\")\n    print(f\"  Environmental Impact: {suggestion['environmental_impact']}\")\n\nprint(\"\nEstimated Environmental Impact if Optimized:\")\nprint(f\"Potential Energy Savings: {energy_savings['energy_kwh_per_year']:.2f} kWh/year\")\nprint(f\"Potential CO2 Reduction: {energy_savings['co2_kg_per_year']:.2f} kg CO2/year\")\nprint(f\"Equivalent to planting: {energy_savings['trees_equivalent']:.2f} trees\")\n```\n\n### As a Command-Line Tool\n\nAnalyze a single file:\n\n```bash\neco-code-analyzer path/to/your/python_file.py\n```\n\nAnalyze a project directory:\n\n```bash\neco-code-analyzer path/to/your/project/directory -v\n```\n\nGenerate a detailed report:\n\n```bash\neco-code-analyzer path/to/your/project/directory -o report.json\n```\n\nAnalyze Git history and visualize eco-score trend:\n\n```bash\neco-code-analyzer path/to/your/project/directory -g -n 10 --visualize\n```\n\nUse a custom configuration:\n\n```bash\neco-code-analyzer path/to/your/project/directory -c config.json\n```\n\nContribute to tree planting based on analysis results:\n\n```bash\neco-code-analyzer path/to/your/project/directory --contribute\n```\n\n---\n\n## \ud83c\udf3f **Environmental Impact and Tree Planting**\n\nThe Eco-Code Analyzer helps developers understand the environmental impact of their code by:\n\n1. Estimating energy consumption and CO2 emissions for different code constructs\n2. Providing an overall eco-score that reflects the code's environmental friendliness\n3. Offering specific suggestions to improve code efficiency and reduce energy consumption\n4. Calculating potential energy savings and CO2 reduction if the code is optimized\n5. Tracking the project's eco-score over time to encourage continuous improvement\n6. Estimating the equivalent number of trees that need to be planted to offset the code's environmental impact\n\nBy using the Eco-Code Analyzer, developers can:\n\n- Reduce the energy consumption of their applications\n- Lower the carbon footprint of their software\n- Improve code performance and efficiency\n- Raise awareness about the environmental impact of code\n- Actively contribute to reforestation efforts based on their code's impact\n\nThe new tree planting feature allows users to take immediate action to offset their code's environmental impact. When using the `--contribute` flag, the tool will:\n\n1. Calculate the number of trees equivalent to the potential CO2 reduction\n2. Provide an estimated cost for planting these trees\n3. Offer the user an option to contribute to a tree planting organization directly from the command line\n\nRemember, every small optimization and contribution counts. By collectively improving our code's eco-friendliness and supporting reforestation efforts, we can make a significant impact on reducing the IT industry's carbon footprint and promoting a healthier planet.\n\n---\n\n## \u2699\ufe0f **Configuration**\n\nYou can customize the behavior of the Eco-Code Analyzer by providing a JSON configuration file. This includes the ability to adjust weights for different aspects of the analysis and configure the coefficients used in the calculations.\n\nHere's an example configuration file:\n\n```json\n{\n  \"weights\": {\n    \"energy_efficiency\": 0.4,\n    \"resource_usage\": 0.3,\n    \"code_optimizations\": 0.2,\n    \"custom_rules\": 0.1\n  },\n  \"thresholds\": {\n    \"eco_score\": 0.7,\n    \"category_score\": 0.6\n  },\n  \"custom_rules\": [\n    {\n      \"name\": \"check_api_call_efficiency\",\n      \"weight\": 0.05\n    }\n  ],\n  \"coefficients\": {\n    \"energy_consumption_per_cpu_cycle\": 1e-9,\n    \"co2_emissions_per_kwh\": 0.5,\n    \"base_energy_consumption_per_year\": 100,\n    \"base_co2_emissions_per_year\": 50,\n    \"trees_equivalent_factor\": 2\n  }\n}\n```\n\nIn this configuration:\n\n- `weights`: Adjust the importance of different categories in the overall eco-score.\n- `thresholds`: Set the levels at which warnings or suggestions are triggered.\n- `custom_rules`: Add your own rules or adjust the weight of existing ones.\n- `coefficients`: Configure the key assumptions used in environmental impact calculations:\n  - `energy_consumption_per_cpu_cycle`: Energy consumed per CPU cycle (in joules)\n  - `co2_emissions_per_kwh`: CO2 emitted per kWh of energy (varies by region)\n  - `base_energy_consumption_per_year`: Assumed baseline energy consumption for a typical project (in kWh)\n  - `base_co2_emissions_per_year`: Assumed baseline CO2 emissions for a typical project (in kg)\n  - `trees_equivalent_factor`: Factor used to convert CO2 reduction to equivalent number of trees planted\n\nBy adjusting these coefficients, you can tailor the analysis to better match your specific environment or to reflect more recent data on energy consumption and emissions.\n\n---\n\n## \ud83e\udd1d **Contributing**\n\nContributions are welcome! Please feel free to submit a Pull Request. Here are some ways you can contribute:\n\n1. Add new rules for detecting eco-unfriendly code patterns\n2. Improve the accuracy of energy consumption and CO2 emission estimates\n3. Enhance the visualization capabilities\n4. Add support for more programming languages\n5. Improve documentation and provide usage examples\n6. Refine the assumptions and coefficients used in the analysis\n7. Expand the tree planting contribution feature with more options and partnerships\n\n---\n\n## \ud83d\udcc4 **License**\n\nThis project is licensed under the MIT License.\n\n---\n\n## \ud83c\udf31 **Let's Build a Greener Future, One Line of Code at a Time!**\n\nBy using the Eco-Code Analyzer, you're not just improving your code \u2013 you're contributing to a more sustainable future for software development and our planet. Together, we can make a significant impact on reducing the environmental footprint of the IT industry and supporting global reforestation efforts. Happy eco-coding!\n\n\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A Python library that analyzes code for ecological impact and provides optimization suggestions",
    "version": "0.3.3",
    "project_urls": {
        "Homepage": "https://github.com/vinerya/eco-code-analyzer"
    },
    "split_keywords": [
        "code analysis",
        " environmental impact",
        " energy efficiency",
        " eco-friendly coding"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "7d0ba7c133e1ea85825f9bb32a7eccf3c3bb34edd55bc717bbddee4a6205ebda",
                "md5": "e90686fac209e24dc6c475e7553314f9",
                "sha256": "a24fc4c2efe580e2b12266882315060e93f126a3322d8dbf5f57cf9e21098e61"
            },
            "downloads": -1,
            "filename": "eco_code_analyzer-0.3.3-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "e90686fac209e24dc6c475e7553314f9",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 11889,
            "upload_time": "2024-09-17T16:08:10",
            "upload_time_iso_8601": "2024-09-17T16:08:10.190014Z",
            "url": "https://files.pythonhosted.org/packages/7d/0b/a7c133e1ea85825f9bb32a7eccf3c3bb34edd55bc717bbddee4a6205ebda/eco_code_analyzer-0.3.3-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "625a0e498857bdffb3724b0b7b81ce52c6dec4881d19927e9a4e88c0af954a1e",
                "md5": "93257aab99dfc67bb94134df24305e69",
                "sha256": "2219600f8e43cacf4fe0545e24df76fe7e4e854288d5e99083a4538f5ac6ae6d"
            },
            "downloads": -1,
            "filename": "eco-code-analyzer-0.3.3.tar.gz",
            "has_sig": false,
            "md5_digest": "93257aab99dfc67bb94134df24305e69",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 13460,
            "upload_time": "2024-09-17T16:08:11",
            "upload_time_iso_8601": "2024-09-17T16:08:11.485776Z",
            "url": "https://files.pythonhosted.org/packages/62/5a/0e498857bdffb3724b0b7b81ce52c6dec4881d19927e9a4e88c0af954a1e/eco-code-analyzer-0.3.3.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-17 16:08:11",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "vinerya",
    "github_project": "eco-code-analyzer",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "eco-code-analyzer"
}
        
Elapsed time: 0.40751s