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
6 changes: 3 additions & 3 deletions archi.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,13 +74,13 @@ POST /api/classify_st_url
-> return JSON
```

`classify_repo()` initially selects scores greater than or equal to `0.3`. The Flask route then applies a second filter and returns only scores strictly greater than `0.4`, so a score of exactly `0.4` is not returned. The function's `top_k` limit is 10.
`classify_repo()` selects scores greater than or equal to `0.3`. The Flask route preserves those already-filtered predictions instead of applying a second, incompatible cutoff. The function's `top_k` limit is 10.

### Aurora path

The Aurora route sends the user's project description to `https://aurora-sdg.labs.vu.nl/classifier/classify/elsevier-sdg-multi`. It does not fetch the repository or call the local LUKE classifier. The response is normalized, scores above `0.1` are retained in `aurora_api.py`, and the Flask route applies its own strict `> 0.4` output filter.

Both routes perform a recommendation assessment after classification. Its result is attached only if no prediction remains after the route's `> 0.4` filter, but the assessment function itself is called whether or not predictions remain. Depending on text length and keywords, that assessment can do additional MPNet work even when the recommendation field is ultimately `null`.
Both routes perform a recommendation assessment after classification. Its result is attached only if no prediction remains after the route's model-specific filtering, but the assessment function itself is called whether or not predictions remain. Depending on text length and keywords, that assessment can do additional MPNet work even when the recommendation field is ultimately `null`.

## Repository and README path

Expand Down Expand Up @@ -172,7 +172,7 @@ It cleans both arguments and checks their combined text in this order:

Important input detail: the combined description plus summary is used for the word count and keyword checks, but the similarity calculation embeds only `user_description`. In the ST route, the second argument is the generated summary (or repository description fallback); in the Aurora route, the current Aurora response normally has no `project_description`, so the helper usually receives an empty second string.

The recommendation calculation runs after the route's primary classification. If the route returns one or more predictions above `0.4`, its recommendation result is discarded from the response. The recommendation check can nevertheless add time in that case if the text passes its length and keyword gates.
The recommendation calculation runs after the route's primary classification. If the route returns one or more predictions that survive its model-specific cutoff, its recommendation result is discarded from the response. The recommendation check can nevertheless add time in that case if the text passes its length and keyword gates.

## Model lifecycle and efficiency

Expand Down
19 changes: 9 additions & 10 deletions backend/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,10 @@
app = Flask(__name__)
CORS(app)

# Route-level output cutoff. The ST scorer's 0.3 threshold is an earlier
# candidate filter inside embedding_url.py, not the API response cutoff.
SDG_PREDICTION_CUTOFF = 0.4
# Aurora returns unfiltered scores, so its route applies this output cutoff.
# The ST URL classifier applies its own calibrated >= 0.3 cutoff before it
# returns from embedding_url.py and must not be filtered a second time here.
AURORA_PREDICTION_CUTOFF = 0.4


def _recommendation_payload(recommendation):
Expand All @@ -46,11 +47,11 @@ def _recommendation_payload(recommendation):
return payload


def _filter_predictions(predictions):
def _filter_aurora_predictions(predictions):
return [
prediction
for prediction in predictions
if prediction.get("prediction", 0) > SDG_PREDICTION_CUTOFF
if prediction.get("prediction", 0) > AURORA_PREDICTION_CUTOFF
]


Expand Down Expand Up @@ -161,7 +162,7 @@ def classify_aurora():
if isinstance(sdg_preds, dict)
else sdg_preds
)
filtered = _filter_predictions(preds)
filtered = _filter_aurora_predictions(preds)

response = {
"projectName": aurora_result.get("project_name"),
Expand Down Expand Up @@ -264,13 +265,11 @@ def classify_st_url():
{"sdg": name, "prediction": score}
for name, score in st_url_result.get("sdg_predictions", {}).items()
]
filtered = _filter_predictions(preds)

response = {
"projectName": projectName,
"projectUrl": projectUrl,
"predictions": filtered,
"recommendation": _recommendation_payload(rec) if not filtered else None,
"predictions": preds,
"recommendation": _recommendation_payload(rec) if not preds else None,
"readme_assessment": {
**_recommendation_payload(readme_assessment),
"relevant": readme_assessment["relevant"],
Expand Down
61 changes: 35 additions & 26 deletions backend/tests/test_recommendation_pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import app as flask_app
import sdg_constants
from app import SDG_PREDICTION_CUTOFF, _filter_predictions
from app import AURORA_PREDICTION_CUTOFF, _filter_aurora_predictions
from services import recommendation_pipeline as pipeline


Expand Down Expand Up @@ -50,9 +50,9 @@ def _impact_description():
)


def test_route_cutoff_is_shared_and_strict():
assert SDG_PREDICTION_CUTOFF == 0.4
assert _filter_predictions([
def test_aurora_route_cutoff_is_strict():
assert AURORA_PREDICTION_CUTOFF == 0.4
assert _filter_aurora_predictions([
{"sdg": "SDG 1", "prediction": 0.3},
{"sdg": "SDG 2", "prediction": 0.4},
{"sdg": "SDG 3", "prediction": 0.4001},
Expand Down Expand Up @@ -119,41 +119,50 @@ def test_low_similarity_quality_is_clamped_to_unit_interval(monkeypatch):
assert 0.0 <= result["text_quality"] <= 1.0


def test_st_route_returns_separate_readme_assessment(monkeypatch):
seen = []
def test_st_route_preserves_p5_predictions_accepted_by_classifier(monkeypatch):
sdg_4 = sdg_constants.SDG_NAMES[3]
sdg_9 = sdg_constants.SDG_NAMES[8]
monkeypatch.setattr(
flask_app,
"classify_url",
lambda **_kwargs: {
"summary": "classifier summary",
"readme_excerpt": "cleaned README excerpt",
"meta": {"description": "repository description"},
"sdg_predictions": {},
"summary": "p5.js supports creative coding education for students.",
"readme_excerpt": "p5.js supports creative coding education for students.",
"meta": {"description": "Creative coding education"},
# Scores observed from the p5.js ST ensemble. embedding_url.py has
# already accepted these with its calibrated >= 0.3 cutoff.
"sdg_predictions": {
sdg_4: 0.351,
sdg_9: 0.307,
},
},
)

def assess(description, readme):
seen.append((description, readme))
return {
"relevant": description == "cleaned README excerpt",
"reason": "no_sdg_signals",
"text_quality": 0.2,
monkeypatch.setattr(
flask_app,
"assess_relevance",
lambda *_args: {
"relevant": True,
"reason": "signals_present_but_low_similarity",
"text_quality": 0.9,
"suggestions": [],
}
"nearest_sdg": sdg_4,
"nearest_similarity": 0.22,
},
)

monkeypatch.setattr(flask_app, "assess_relevance", assess)
response = flask_app.app.test_client().post(
"/api/classify_st_url",
json={
"projectName": "project",
"projectUrl": "https://github.com/example/project",
"projectDescription": "user description",
"projectName": "p5.js",
"projectUrl": "https://github.com/processing/p5.js/",
"projectDescription": "Creative coding education for students and teachers.",
},
)

assert response.status_code == 200
assert seen == [
("user description", "classifier summary"),
("cleaned README excerpt", ""),
payload = response.get_json()
assert payload["predictions"] == [
{"sdg": sdg_4, "prediction": 0.351},
{"sdg": sdg_9, "prediction": 0.307},
]
assert response.get_json()["readme_assessment"]["relevant"] is True
assert payload["recommendation"] is None
12 changes: 7 additions & 5 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
# Testing Guide

This document inventories the testing this project needs: what exists today, what's missing, and the specific test cases each module should have. It's meant to guide contributors picking up `test/` issues, not to describe an aspirational end state — the backend now has a real `pytest` suite covering two modules (see table below), but most of the checklist is still unimplemented, and the frontend has no test runner at all.
This document inventories the testing this project needs: what exists today, what's missing, and the specific test cases each module should have. The backend has a `pytest` suite, and the frontend uses Vitest with React Testing Library for its classification flow.

## Current **state**

| Area | Test runner | Status |
|------|-------------|--------|
| Backend (`backend/`) | `pytest` (installed, in `requirements.txt`) | Two modules have real automated coverage: [`test_repo_fetcher.py`](../backend/tests/test_repo_fetcher.py) (72 tests) and [`test_embedding_url.py`](../backend/tests/test_embedding_url.py) (24 tests) — **all 96 passing**. `test_dpga_real_positives.py` and `test_gitlab_provider.py` remain manual, live-network scripts (excluded from collection via `conftest.py`'s `collect_ignore`) — useful as smoke tests, not part of the automated suite. `aurora_api.py`, `summariser.py`, `sdg_constants.py`, and `app.py` (§3–§6 below) still have no tests at all. |
| Backend (`backend/`) | `pytest` (installed, in `requirements.txt`) | The deterministic classification contract is covered in `test_recommendation_pipeline.py`. Other modules also have tests, but the broader suite currently contains unrelated `repo_fetcher` failures and is not the CI gate for this flow. The live-network scripts remain excluded from collection. |
| SDG inference (`backend/services/inference.py`, `sdg_model.py`) | covered indirectly | No direct tests — loading real weights makes naive unit testing hard (see [§7](#7-sdg-inference)). `zero_shot_scores` is tested on both branches (in-process and `MODEL_SERVICE_URL` over HTTP), and the load path is pinned by a mocked import trace. |
| Frontend (`frontend/`) | none | No Jest/Vitest/React Testing Library installed. `npm run lint` is the only check that runs today. |
| Frontend (`frontend/`) | Vitest + React Testing Library | `test/classification-flow.test.tsx` submits the form through a mocked API boundary and validates accepted prediction rendering. |

Run the backend suite with `cd backend && pytest tests/` (the two manual scripts are auto-excluded). Setting up a frontend runner (`Jest` + `React Testing Library`) is still a prerequisite for most of the work in §7–§8 and is good first-issue material.
Run the classification contract suite with `cd backend && pytest tests/test_recommendation_pipeline.py`, and run the frontend flow with `cd frontend && npm test`. The broader backend suite currently has unrelated `repo_fetcher` failures and should not be described as green until those tests are reconciled with repository validation behavior.



Expand Down Expand Up @@ -82,6 +82,7 @@ Integration-style tests using Flask's test client (no live server needed):

- `POST /api/classify_aurora`: missing `projectDescription` → `400`; happy path filters predictions to `> 0.4`; an exception from `aurora_classify` → `500` with the documented error shape.
- `POST /api/classify_st_url`: missing `projectDescription` → `400`; missing `projectUrl` → `200` with empty `predictions` and an explanatory `message`; each of `InvalidURLError`/`UnsupportedHostError`/`ValueError` → `400`, `RepositoryNotFoundError` → `404`, `RateLimitError` → `429`, `FetchError`/`requests.exceptions.HTTPError` → `502`, anything else → `500`. This status-code mapping is exactly the kind of thing that silently breaks during a refactor if it isn't pinned down by a test.
- The ST route contract test also pins the p5.js regression: classifier-approved SDG 4 (`0.351`) and SDG 9 (`0.307`) scores must reach `predictions` without being subjected to Aurora's stricter cutoff.
- No `/api/classify_st_description` route exists, and no frontend code calls it anymore (see [gap above](#known-gap-this-inventory-surfaced-resolved)) — nothing to test here unless the route is intentionally reintroduced later.
- CORS headers are present on responses.

Expand All @@ -95,7 +96,7 @@ Recommended approach:

## 8. Frontend

Requires installing Jest or Vitest + React Testing Library first.
Vitest and React Testing Library are configured in `frontend/vitest.config.ts`.

**Pure logic (no rendering required):**
- `lib/utils.ts` — `cn()` class merging/deduplication.
Expand All @@ -105,6 +106,7 @@ Requires installing Jest or Vitest + React Testing Library first.
- `services/api.ts` — `classifyByModel` switch: each model type routes to the correct client method; an unknown type falls back to Aurora.

**Component tests:**
- `test/classification-flow.test.tsx` — covered: form submission, API handoff, and accepted prediction rendering.
- `mainScreen.tsx` — every form-validation message branch ("Please fill in...", "valid repository URL").
- `results.tsx` — tab switching (`handleTabChange`) and its error path, `handleDownload`'s JSON/blob generation.
- `editModal.tsx` — add/remove SDG flow end to end.
Expand Down
Loading