Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,3 +118,23 @@ By designing software with sustainability as a guiding principle, developers can
DevSphere invites developers from diverse backgrounds and regions to join the initiative and actively participate in the shared mission of fostering sustainable software development. Together, the community can create a significant and positive impact on the environment, advocate for a more sustainable future within the software industry, and inspire others to embrace similar practices.

Let us unite our skills and expertise to develop software for a greener tomorrow. 🌿vvvvvvvvvvvvvvvvvvvv

## 🌿 myHerb Sustainability Shift Guidance (Prototype)

To help founders move from sustainability ambition to measurable action, DevSphere now includes a lightweight prototype in `apps/myherb_shift_advisor.py`.

### What it does
- Scores six core sustainability pillars (energy, water, waste, packaging, supply chain, community).
- Produces a weighted sustainability maturity score.
- Classifies organizations into a maturity tier (`Starter`, `Emerging`, `Progressing`, `Leader`).
- Suggests top 3 priority areas for the next sustainability shift sprint.

### Quick run
```bash
python apps/myherb_shift_advisor.py
```

### Run tests
```bash
cd apps && python -m unittest test_myherb_shift_advisor.py
```
132 changes: 132 additions & 0 deletions apps/myherb_shift_advisor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
"""myHerb Sustainability Shift Guidance Prototype.

A lightweight CLI-friendly module that helps organizations assess their
sustainability maturity and receive prioritized next steps.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, List


PILLARS = (
"energy",
"water",
"waste",
"packaging",
"supply_chain",
"community",
)


@dataclass(frozen=True)
class PillarAssessment:
"""A maturity score for a sustainability pillar (0-100)."""

name: str
score: int

def __post_init__(self) -> None:
if self.name not in PILLARS:
raise ValueError(f"Unknown pillar: {self.name}")
if not 0 <= self.score <= 100:
raise ValueError("Score must be in the range 0..100")


@dataclass
class ShiftReport:
weighted_score: float
tier: str
priorities: List[str]


def _default_weights() -> Dict[str, float]:
return {
"energy": 0.20,
"water": 0.15,
"waste": 0.20,
"packaging": 0.15,
"supply_chain": 0.20,
"community": 0.10,
}


def _tier_from_score(score: float) -> str:
if score >= 80:
return "Leader"
if score >= 60:
return "Progressing"
if score >= 40:
return "Emerging"
return "Starter"


def generate_shift_report(
assessments: List[PillarAssessment],
weights: Dict[str, float] | None = None,
) -> ShiftReport:
"""Generate a weighted sustainability shift report.

Args:
assessments: List of pillar scores.
weights: Optional custom weighting by pillar.

Returns:
ShiftReport with aggregate score, maturity tier, and top priorities.
"""

if len(assessments) != len(PILLARS):
raise ValueError("All pillars must be assessed exactly once")

seen = {assessment.name for assessment in assessments}
if seen != set(PILLARS):
raise ValueError("Assessments must include each pillar exactly once")

resolved_weights = weights or _default_weights()
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat empty custom weights as invalid input

Using weights or _default_weights() makes an empty dict ({}) fall back to defaults instead of failing validation, so callers with misloaded/empty config silently get a report computed with unintended weights. In this case the "Weights must include all pillars" guard is never reached, which hides input errors and can produce incorrect guidance without any exception.

Useful? React with 👍 / 👎.

if set(resolved_weights) != set(PILLARS):
raise ValueError("Weights must include all pillars")

total_weight = sum(resolved_weights.values())
if abs(total_weight - 1.0) > 1e-9:
raise ValueError("Weights must sum to 1.0")
Comment on lines +90 to +92
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Enforce valid weight ranges before scoring

The current validation only checks that weights sum to 1.0, so invalid distributions like a negative weight offset by a >1 weight (or NaN values) can pass and yield nonsensical aggregate scores and tiers. This affects any caller providing custom weights, and it can silently corrupt the report output; each weight should be validated as finite and within an expected range (typically 0..1).

Useful? React with 👍 / 👎.


score_map = {assessment.name: assessment.score for assessment in assessments}
weighted_score = sum(score_map[p] * resolved_weights[p] for p in PILLARS)
tier = _tier_from_score(weighted_score)

underperforming = sorted(PILLARS, key=lambda p: score_map[p])[:3]
priorities = [
f"Increase {pillar.replace('_', ' ')} initiatives (current score: {score_map[pillar]})"
for pillar in underperforming
]

return ShiftReport(
weighted_score=round(weighted_score, 2),
tier=tier,
priorities=priorities,
)


def demo() -> ShiftReport:
"""Return a sample report for showcasing the application idea."""

sample = [
PillarAssessment("energy", 55),
PillarAssessment("water", 62),
PillarAssessment("waste", 48),
PillarAssessment("packaging", 45),
PillarAssessment("supply_chain", 52),
PillarAssessment("community", 70),
]
return generate_shift_report(sample)


if __name__ == "__main__":
report = demo()
print("myHerb Sustainability Shift Guidance")
print(f"Weighted Score: {report.weighted_score}")
print(f"Tier: {report.tier}")
print("Top priorities:")
for item in report.priorities:
print(f"- {item}")
48 changes: 48 additions & 0 deletions apps/test_myherb_shift_advisor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import unittest

from myherb_shift_advisor import PillarAssessment, generate_shift_report


class ShiftAdvisorTests(unittest.TestCase):
def test_report_generation(self):
assessments = [
PillarAssessment("energy", 80),
PillarAssessment("water", 70),
PillarAssessment("waste", 60),
PillarAssessment("packaging", 65),
PillarAssessment("supply_chain", 75),
PillarAssessment("community", 85),
]

report = generate_shift_report(assessments)

self.assertEqual(report.tier, "Progressing")
self.assertAlmostEqual(report.weighted_score, 71.75)
self.assertEqual(len(report.priorities), 3)

def test_invalid_weight_sum(self):
assessments = [
PillarAssessment("energy", 80),
PillarAssessment("water", 70),
PillarAssessment("waste", 60),
PillarAssessment("packaging", 65),
PillarAssessment("supply_chain", 75),
PillarAssessment("community", 85),
]

with self.assertRaises(ValueError):
generate_shift_report(
assessments,
{
"energy": 0.1,
"water": 0.1,
"waste": 0.1,
"packaging": 0.1,
"supply_chain": 0.1,
"community": 0.1,
},
)


if __name__ == "__main__":
unittest.main()