# 🌱 EcoTrace

> **Measure your code's carbon footprint. Write cleaner code. Protect the planet.**

EcoTrace is a lightweight yet powerful Python library that analyzes the CPU and GPU load of your functions and calculates how much CO₂ they emit.

![EcoTrace Demo](demo.gif)

[![PyPI version](https://badge.fury.io/py/ecotrace.svg)](https://badge.fury.io/py/ecotrace)
[![Python 3.7+](https://img.shields.io/badge/python-3.7+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
[![Downloads](https://pepy.tech/badge/ecotrace)](https://pepy.tech/project/ecotrace)
[![Downloads/Month](https://pepy.tech/badge/ecotrace/month)](https://pepy.tech/project/ecotrace)
[![GitHub stars](https://img.shields.io/github/stars/Zwony/ecotrace?style=social)](https://github.com/Zwony/ecotrace/stargazers)

---

## 🚀 Installation

```bash
pip install ecotrace
```

---

## ⚡ Quick Start

```python
from ecotrace import EcoTrace

eco = EcoTrace(region_code="US")

@eco.track
def process_data():
    return sum(i * i for i in range(10**6))

process_data()
# [EcoTrace] Function   : process_data
# [EcoTrace] Duration   : 0.0452 sec
# [EcoTrace] Avg CPU    : 23.4%
# [EcoTrace] CO2 Emitted: 0.00001823 gCO2
```

---

## 🧩 Features

### ✅ CPU Tracking — `@eco.track`

Track any function with a single decorator:

```python
@eco.track
def train_model():
    # model training...
    pass
```

Async functions are supported out of the box:

```python
@eco.track
async def fetch_data():
    await asyncio.sleep(1)
    # API call...
```

### ✅ GPU Tracking — `@eco.track_gpu`

Supports NVIDIA, AMD, and Intel GPUs. Select a specific GPU with `gpu_index`:

```python
# Default — first GPU
eco = EcoTrace(region_code="US")

# Select a specific GPU
eco = EcoTrace(region_code="US", gpu_index=1)

@eco.track_gpu
def gpu_compute():
    # GPU-intensive work...
    pass
```

### ✅ Async Measurement — `eco.measure_async()`

For more accurate, continuous sampling of async functions:

```python
async def my_async_task():
    await asyncio.sleep(1)
    return "Done"

result = await eco.measure_async(my_async_task)
print(f"CO2: {result['carbon']}g, Result: {result['result']}")
```

### ✅ Comparison Analysis — `eco.compare()`

Compare two implementations side-by-side:

```python
def fast_version():
    return sum(i for i in range(10**5))

def slow_version():
    return sum(i for i in range(10**6))

result = eco.compare(fast_version, slow_version)
```

### ✅ PDF Report with Charts — `eco.generate_pdf_report()`

Export all measurements as a detailed PDF report including CPU usage charts:

```python
# Pass cpu_samples from measure_async to include the chart
eco.generate_pdf_report("report.pdf", comparison=result, cpu_samples=result.get('cpu_samples'))
```

Report includes:
- System info (CPU, GPU, TDP, region)
- Full function measurement history
- **NEW: CPU Usage Over Time charts**
- Comparison analysis table
- Total cumulative CO₂ emissions

### ✅ Carbon Limit Warning

Get a warning when you exceed a defined threshold:

```python
eco = EcoTrace(region_code="US", carbon_limit=0.001)
# ⚠️ WARNING: Carbon limit exceeded! (0.00124 > 0.001 gCO2)
```

---

## 🌍 Supported Regions

EcoTrace supports **36 regions** with real-world carbon intensity data.

| Code | Country        | Carbon Intensity |
|------|----------------|-----------------|
| TR   | Turkey         | 475 gCO₂/kWh    |
| DE   | Germany        | 385 gCO₂/kWh    |
| FR   | France         | 55 gCO₂/kWh     |
| US   | United States  | 367 gCO₂/kWh    |
| GB   | United Kingdom | 253 gCO₂/kWh    |
| IN   | India          | 708 gCO₂/kWh    |
| CN   | China          | 555 gCO₂/kWh    |
| AU   | Australia      | 490 gCO₂/kWh    |
| CA   | Canada         | 130 gCO₂/kWh    |
| BR   | Brazil         | 74 gCO₂/kWh     |
| JP   | Japan          | 463 gCO₂/kWh    |
| KR   | South Korea    | 415 gCO₂/kWh    |
| NL   | Netherlands    | 290 gCO₂/kWh    |
| SE   | Sweden         | 13 gCO₂/kWh     |
| NO   | Norway         | 26 gCO₂/kWh     |
| PL   | Poland         | 635 gCO₂/kWh    |
| IT   | Italy          | 233 gCO₂/kWh    |
| ES   | Spain          | 187 gCO₂/kWh    |
| PT   | Portugal       | 176 gCO₂/kWh    |
| BE   | Belgium        | 167 gCO₂/kWh    |
| CH   | Switzerland    | 25 gCO₂/kWh     |
| AT   | Austria        | 158 gCO₂/kWh    |
| FI   | Finland        | 65 gCO₂/kWh     |
| DK   | Denmark        | 166 gCO₂/kWh    |
| CZ   | Czech Republic | 412 gCO₂/kWh    |
| HU   | Hungary        | 223 gCO₂/kWh    |
| RO   | Romania        | 293 gCO₂/kWh    |
| ZA   | South Africa   | 928 gCO₂/kWh    |
| MX   | Mexico         | 527 gCO₂/kWh    |
| AR   | Argentina      | 314 gCO₂/kWh    |
| ID   | Indonesia      | 761 gCO₂/kWh    |
| MY   | Malaysia       | 585 gCO₂/kWh    |
| TH   | Thailand       | 513 gCO₂/kWh    |
| PH   | Philippines    | 558 gCO₂/kWh    |
| SG   | Singapore      | 408 gCO₂/kWh    |
| NZ   | New Zealand    | 120 gCO₂/kWh    |
| EG   | Egypt          | 448 gCO₂/kWh    |
| NG   | Nigeria        | 385 gCO₂/kWh    |

> Don't see your region? [Open a feature request](https://github.com/Zwony/ecotrace/issues/new?template=feature_request.md) and we'll add it!

---

## 🖥️ Supported CPUs

EcoTrace automatically detects TDP values using the [Boavizta](https://github.com/Boavizta/cpu-spec) database with 1800+ CPUs:

- Intel Core i3 / i5 / i7 / i9 (all generations)
- AMD Ryzen 3 / 5 / 7 / 9
- Apple M1 / M2 / M3
- AMD Threadripper, EPYC
- Intel Xeon

---

## 📦 Dependencies

```
psutil
py-cpuinfo
fpdf
matplotlib
nvidia-ml-py
wmi; sys_platform == 'win32'
```

---

## 📊 Sample PDF Output

```
EcoTrace Analysis Report
─────────────────────────────────────
CPU      : Intel Core i7-13700H
TDP      : 45.0W
Region   : US (367 gCO₂/kWh)
─────────────────────────────────────
Function       Duration(s)  CPU%   Carbon(gCO2)
process_data   0.0452       23.4   0.00001823
fetch_data     1.0021       2.1    0.00037486
─────────────────────────────────────
TOTAL CUMULATIVE EMISSIONS: 0.00039309 gCO2
```

---

## 🤝 Contributing

Pull requests and issues are welcome!

---

## 💬 Community & Support

Join the EcoTrace community to contribute, ask questions, and connect with other developers.

[![Join Discord](https://img.shields.io/discord/1483105790993633411?label=Join%20Discord&logo=discord&style=for-the-badge)](https://discord.gg/hs58XXb3Uq)

- 🐛 Report bugs
- 💡 Suggest new features
- 💻 Share your hardware TDP data to grow the database
- 🛠️ Get installation and usage support

## 👤 Author

**Emre Özkal** — [emreozkal03@gmail.com](mailto:emreozkal03@gmail.com)

---

## 📄 License

MIT License — use it however you like.