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
18 changes: 10 additions & 8 deletions explain_my_code/api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,17 +129,19 @@ def explain_all_levels(payload: ExplainRequest) -> Any:
"""All three levels in one call.

The parse and analysis passes are the expensive part and are level-independent, so
the client can switch levels instantly instead of paying a round trip per level.
they run once and only the narration is repeated per level. The client can switch
levels instantly instead of paying a round trip per level.
"""
first = explain(
payload.code,
language=payload.language,
level=Level.ELI5,
filename=payload.filename,
enrich=False,
)
out: dict[str, Any] = {}
for level in Level:
result = explain(
payload.code,
language=payload.language,
level=level,
filename=payload.filename,
enrich=False,
)
result = first if level is first.level else first.at_level(level)
out[level.value] = {
"summary": result.summary,
"lines": [line.to_dict() for line in result.lines],
Expand Down
34 changes: 34 additions & 0 deletions explain_my_code/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,40 @@ def to_dict(self, *, include_ir: bool = False) -> dict[str, Any]:
out["ir"] = self.analysis.root.to_dict()
return out

def at_level(self, level: Level | str) -> Explanation:
"""The same parse and analysis, narrated for another audience.

Parsing and analysis do not depend on the level, so this only re-runs the
narration, and node ids in the result match this explanation's `analysis`.
LLM enrichment is level-specific and is not carried over.
"""
level = Level(level)
started = time.perf_counter()
parsed = ParseResult(
self.analysis.root,
self.language,
self.source,
self.diagnostics,
self.analysis.parser,
self.analysis.degraded,
)
annotations = annotate(parsed, self.analysis, level)
summary = summarize(self.analysis, level)
lines = line_view(annotations, level)
elapsed = (time.perf_counter() - started) * 1000
return Explanation(
language=self.language,
level=level,
source=self.source,
summary=summary,
lines=lines,
annotations=annotations,
analysis=self.analysis,
diagnostics=self.diagnostics,
detection_confidence=self.detection_confidence,
timings_ms={"explain": elapsed, "total": elapsed},
)


class SourceTooLarge(ValueError):
pass
Expand Down
22 changes: 22 additions & 0 deletions tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,28 @@ def test_all_levels_returns_all_three():
assert body["eli5"]["summary"] != body["developer"]["summary"]


def test_all_levels_parses_once(monkeypatch):
from explain_my_code.adapters.base import get_adapter
from explain_my_code.ir import Language

adapter = get_adapter(Language.PYTHON)
calls = []
real_parse = adapter.parse
monkeypatch.setattr(adapter, "parse", lambda code: calls.append(code) or real_parse(code))
client.post("/v1/explain/all-levels", json={"code": PY, "language": "python"})
assert len(calls) == 1


def test_all_levels_node_ids_match_the_shared_analysis():
"""Every level's lines must point at the nodes `analysis` describes. Parsing once per
level gave each level its own ids, so only ELI5's matched."""
body = client.post("/v1/explain/all-levels", json={"code": PY}).json()
function_id = body["analysis"]["functions"][0]["nodeId"]
for level in ("eli5", "beginner", "developer"):
definition = next(line for line in body[level]["lines"] if line["line"] == 1)
assert definition["nodeId"] == function_id, level


def test_include_ir_is_opt_in():
without = client.post("/v1/explain", json={"code": PY}).json()
with_ir = client.post("/v1/explain", json={"code": PY, "includeIr": True}).json()
Expand Down
11 changes: 11 additions & 0 deletions tests/test_explain.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,17 @@ def test_all_three_levels_produce_different_prose():
assert texts[Level.ELI5] != texts[Level.BEGINNER] != texts[Level.DEVELOPER]


@pytest.mark.parametrize("level", list(Level), ids=lambda level: level.value)
def test_at_level_matches_a_fresh_explanation(level):
fresh = explain(SAMPLE, level=level)
reused = explain(SAMPLE, level=Level.ELI5).at_level(level)
assert reused.level is level
assert reused.summary == fresh.summary
assert [(line.line, line.text, line.kind) for line in reused.lines] == [
(line.line, line.text, line.kind) for line in fresh.lines
]


def test_eli5_avoids_jargon():
jargon = ("cyclomatic", "asymptotic", "invariant", "idempotent", "polymorphism")
result = explain(SAMPLE, level=Level.ELI5)
Expand Down
Loading