uvpatel7271 commited on
Commit
8f40080
·
verified ·
1 Parent(s): c1f42b0

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +5 -0
  2. build/lib/analyzers/__init__.py +13 -0
  3. build/lib/analyzers/ds_analyzer.py +56 -0
  4. build/lib/analyzers/dsa_analyzer.py +48 -0
  5. build/lib/analyzers/ml_analyzer.py +61 -0
  6. build/lib/analyzers/web_analyzer.py +50 -0
  7. build/lib/api/__init__.py +5 -0
  8. build/lib/api/main.py +27 -0
  9. build/lib/app/__init__.py +1 -0
  10. build/lib/app/agents/__init__.py +5 -0
  11. build/lib/app/agents/review_agent.py +76 -0
  12. build/lib/app/examples.py +31 -0
  13. build/lib/app/models/__init__.py +5 -0
  14. build/lib/app/models/inference.py +44 -0
  15. build/lib/app/services/__init__.py +5 -0
  16. build/lib/app/services/openai_service.py +84 -0
  17. build/lib/app/streamlit_app.py +100 -0
  18. build/lib/app/utils/__init__.py +21 -0
  19. build/lib/app/utils/runtime.py +95 -0
  20. build/lib/build/lib/analyzers/__init__.py +13 -0
  21. build/lib/build/lib/analyzers/ds_analyzer.py +56 -0
  22. build/lib/build/lib/analyzers/dsa_analyzer.py +48 -0
  23. build/lib/build/lib/analyzers/ml_analyzer.py +61 -0
  24. build/lib/build/lib/analyzers/web_analyzer.py +50 -0
  25. build/lib/build/lib/api/__init__.py +5 -0
  26. build/lib/build/lib/api/main.py +27 -0
  27. build/lib/build/lib/app/__init__.py +1 -0
  28. build/lib/build/lib/app/agents/__init__.py +5 -0
  29. build/lib/build/lib/app/agents/review_agent.py +76 -0
  30. build/lib/build/lib/app/examples.py +31 -0
  31. build/lib/build/lib/app/models/__init__.py +5 -0
  32. build/lib/build/lib/app/models/inference.py +44 -0
  33. build/lib/build/lib/app/services/__init__.py +5 -0
  34. build/lib/build/lib/app/services/openai_service.py +84 -0
  35. build/lib/build/lib/app/streamlit_app.py +100 -0
  36. build/lib/build/lib/app/utils/__init__.py +21 -0
  37. build/lib/build/lib/app/utils/runtime.py +95 -0
  38. build/lib/build/lib/graders/__init__.py +5 -0
  39. build/lib/build/lib/graders/bug_fix.py +102 -0
  40. build/lib/build/lib/graders/dispatch.py +32 -0
  41. build/lib/build/lib/graders/optimization.py +122 -0
  42. build/lib/build/lib/graders/shared.py +457 -0
  43. build/lib/build/lib/graders/syntax.py +95 -0
  44. build/lib/build/lib/models/__init__.py +66 -0
  45. build/lib/build/lib/models/pytorch_model.py +149 -0
  46. build/lib/build/lib/schemas/__init__.py +13 -0
  47. build/lib/build/lib/schemas/request.py +19 -0
  48. build/lib/build/lib/schemas/response.py +73 -0
  49. build/lib/build/lib/server/__init__.py +6 -0
  50. build/lib/build/lib/server/app.py +81 -0
.gitattributes CHANGED
@@ -33,3 +33,8 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ venv/Lib/site-packages/81d243bd2c585b0f4821__mypyc.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
37
+ venv/Lib/site-packages/_brotli.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
38
+ venv/Lib/site-packages/yaml/_yaml.cp311-win_amd64.pyd filter=lfs diff=lfs merge=lfs -text
39
+ venv/Scripts/openenv.exe filter=lfs diff=lfs merge=lfs -text
40
+ venv/Scripts/python.exe filter=lfs diff=lfs merge=lfs -text
build/lib/analyzers/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Domain-specific analyzers for multi-domain code understanding."""
2
+
3
+ from .dsa_analyzer import analyze_dsa_code
4
+ from .ds_analyzer import analyze_data_science_code
5
+ from .ml_analyzer import analyze_ml_code
6
+ from .web_analyzer import analyze_web_code
7
+
8
+ __all__ = [
9
+ "analyze_dsa_code",
10
+ "analyze_data_science_code",
11
+ "analyze_ml_code",
12
+ "analyze_web_code",
13
+ ]
build/lib/analyzers/ds_analyzer.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzer for data-science oriented Python code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from schemas.response import AnalysisIssue, DomainAnalysis
8
+
9
+
10
+ def analyze_data_science_code(code: str, parsed: Dict[str, Any], complexity: Dict[str, Any]) -> DomainAnalysis:
11
+ """Inspect pandas and numpy code for vectorization and leakage concerns."""
12
+
13
+ issues = []
14
+ suggestions = []
15
+ score = 0.72
16
+
17
+ if "iterrows(" in code or "itertuples(" in code:
18
+ issues.append(
19
+ AnalysisIssue(
20
+ title="Row-wise dataframe iteration detected",
21
+ severity="medium",
22
+ description="Looping through dataframe rows is usually slower and less scalable than vectorized operations.",
23
+ )
24
+ )
25
+ suggestions.append("Use vectorized pandas or numpy expressions instead of row-wise iteration.")
26
+ score -= 0.18
27
+
28
+ if "inplace=True" in code:
29
+ suggestions.append("Avoid inplace mutation to keep data pipelines easier to reason about and test.")
30
+ score -= 0.05
31
+
32
+ if "fit_transform(" in code and "train_test_split" not in code:
33
+ issues.append(
34
+ AnalysisIssue(
35
+ title="Potential data leakage risk",
36
+ severity="high",
37
+ description="Feature transforms appear before an explicit train/test split.",
38
+ )
39
+ )
40
+ suggestions.append("Split train and validation data before fitting stateful preprocessing steps.")
41
+ score -= 0.2
42
+
43
+ if not suggestions:
44
+ suggestions.append("Add schema assumptions and null-handling checks for production data quality.")
45
+
46
+ return DomainAnalysis(
47
+ domain="data_science",
48
+ domain_score=max(0.05, round(score, 4)),
49
+ issues=issues,
50
+ suggestions=suggestions,
51
+ highlights={
52
+ "vectorization_risk": float("iterrows(" in code or "itertuples(" in code),
53
+ "time_complexity": complexity["time_complexity"],
54
+ "uses_pandas": float(parsed.get("uses_pandas", False)),
55
+ },
56
+ )
build/lib/analyzers/dsa_analyzer.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzer for DSA and competitive-programming style Python code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from schemas.response import AnalysisIssue, DomainAnalysis
8
+
9
+
10
+ def analyze_dsa_code(code: str, parsed: Dict[str, Any], complexity: Dict[str, Any]) -> DomainAnalysis:
11
+ """Inspect algorithmic code for brute-force patterns and efficiency risks."""
12
+
13
+ issues = []
14
+ suggestions = []
15
+ score = 0.7
16
+
17
+ if parsed.get("max_loop_depth", 0) >= 2:
18
+ issues.append(
19
+ AnalysisIssue(
20
+ title="Nested loops suggest brute-force behavior",
21
+ severity="medium",
22
+ description="The implementation scans the input multiple times, which is often avoidable in DSA problems.",
23
+ )
24
+ )
25
+ suggestions.append("Consider replacing nested scans with a hashmap, prefix table, or sorted search strategy.")
26
+ score -= 0.15
27
+
28
+ if parsed.get("uses_recursion"):
29
+ suggestions.append("Verify recursion depth and add memoization or iterative conversion if the input size can grow.")
30
+ score -= 0.05
31
+
32
+ if "sorted(" in code or ".sort(" in code:
33
+ suggestions.append("Sorting is acceptable here, but validate whether a direct O(n) pass can remove the sort.")
34
+
35
+ if not suggestions:
36
+ suggestions.append("Document the intended time complexity and add edge-case checks for empty input and duplicates.")
37
+
38
+ return DomainAnalysis(
39
+ domain="dsa",
40
+ domain_score=max(0.05, round(score, 4)),
41
+ issues=issues,
42
+ suggestions=suggestions,
43
+ highlights={
44
+ "time_complexity": complexity["time_complexity"],
45
+ "space_complexity": complexity["space_complexity"],
46
+ "max_loop_depth": float(parsed.get("max_loop_depth", 0)),
47
+ },
48
+ )
build/lib/analyzers/ml_analyzer.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzer for machine-learning and deep-learning code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from schemas.response import AnalysisIssue, DomainAnalysis
8
+
9
+
10
+ def analyze_ml_code(code: str, parsed: Dict[str, Any], complexity: Dict[str, Any]) -> DomainAnalysis:
11
+ """Inspect training and inference logic for common ML / DL mistakes."""
12
+
13
+ issues = []
14
+ suggestions = []
15
+ score = 0.74
16
+
17
+ if "torch" in code and "model.eval()" not in code and "predict" in code.lower():
18
+ issues.append(
19
+ AnalysisIssue(
20
+ title="Inference path may be missing eval mode",
21
+ severity="high",
22
+ description="Inference code should place the model in eval mode before prediction.",
23
+ )
24
+ )
25
+ suggestions.append("Call model.eval() before inference to disable training-time behavior such as dropout.")
26
+ score -= 0.18
27
+
28
+ if "torch" in code and "no_grad" not in code and "predict" in code.lower():
29
+ suggestions.append("Wrap inference in torch.no_grad() to reduce memory usage and avoid unnecessary gradient tracking.")
30
+ score -= 0.12
31
+
32
+ if parsed.get("calls_backward") and not parsed.get("calls_optimizer_step"):
33
+ issues.append(
34
+ AnalysisIssue(
35
+ title="Backward pass without optimizer step",
36
+ severity="medium",
37
+ description="Gradients are computed, but the optimizer step is not obvious in the snippet.",
38
+ )
39
+ )
40
+ suggestions.append("Ensure optimizer.step() and optimizer.zero_grad() are placed correctly in the training loop.")
41
+ score -= 0.12
42
+
43
+ if "CrossEntropyLoss" in code and "softmax(" in code:
44
+ suggestions.append("CrossEntropyLoss expects raw logits; remove the explicit softmax before the loss when possible.")
45
+ score -= 0.05
46
+
47
+ if not suggestions:
48
+ suggestions.append("Add explicit train/eval mode transitions and log validation metrics during training.")
49
+
50
+ return DomainAnalysis(
51
+ domain="ml_dl",
52
+ domain_score=max(0.05, round(score, 4)),
53
+ issues=issues,
54
+ suggestions=suggestions,
55
+ highlights={
56
+ "uses_torch": float(parsed.get("uses_torch", False)),
57
+ "has_eval_mode": float("model.eval()" in code),
58
+ "has_no_grad": float("no_grad" in code),
59
+ "time_complexity": complexity["time_complexity"],
60
+ },
61
+ )
build/lib/analyzers/web_analyzer.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzer for FastAPI and backend web-service code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from schemas.response import AnalysisIssue, DomainAnalysis
8
+
9
+
10
+ def analyze_web_code(code: str, parsed: Dict[str, Any], complexity: Dict[str, Any]) -> DomainAnalysis:
11
+ """Inspect API code for validation, routing, and backend safety concerns."""
12
+
13
+ issues = []
14
+ suggestions = []
15
+ score = 0.76
16
+
17
+ route_decorators = set(parsed.get("route_decorators", []))
18
+ if route_decorators and not parsed.get("uses_pydantic"):
19
+ issues.append(
20
+ AnalysisIssue(
21
+ title="Request validation model is missing",
22
+ severity="high",
23
+ description="Route handlers appear present, but no obvious Pydantic validation layer was detected.",
24
+ )
25
+ )
26
+ suggestions.append("Add Pydantic request and response models for strict validation and type-safe contracts.")
27
+ score -= 0.2
28
+
29
+ if {"get", "post", "put", "delete"} & route_decorators and "async def" not in code:
30
+ suggestions.append("Prefer async FastAPI endpoints when the route performs I/O or awaits downstream services.")
31
+ score -= 0.08
32
+
33
+ if "request.json()" in code or "request.body()" in code:
34
+ suggestions.append("Validate raw request payloads before use; avoid trusting unchecked JSON input.")
35
+ score -= 0.08
36
+
37
+ if not suggestions:
38
+ suggestions.append("Add domain-specific response models and centralize dependency injection for cleaner API structure.")
39
+
40
+ return DomainAnalysis(
41
+ domain="web",
42
+ domain_score=max(0.05, round(score, 4)),
43
+ issues=issues,
44
+ suggestions=suggestions,
45
+ highlights={
46
+ "route_count": float(len(route_decorators)),
47
+ "uses_validation": float(parsed.get("uses_pydantic", False)),
48
+ "time_complexity": complexity["time_complexity"],
49
+ },
50
+ )
build/lib/api/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """FastAPI backend package for the multi-domain analyzer."""
2
+
3
+ from .main import app
4
+
5
+ __all__ = ["app"]
build/lib/api/main.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI backend for the multi-domain AI code analyzer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import FastAPI
6
+
7
+ from schemas.request import AnalyzeCodeRequest
8
+ from schemas.response import AnalyzeCodeResponse
9
+ from services.analysis_service import AnalysisService
10
+
11
+
12
+ app = FastAPI(title="Multi-Domain AI Code Analyzer", version="2.0.0")
13
+ analysis_service = AnalysisService()
14
+
15
+
16
+ @app.get("/health")
17
+ def health() -> dict[str, str]:
18
+ """Return a simple health payload for deployments and smoke tests."""
19
+
20
+ return {"status": "ok"}
21
+
22
+
23
+ @app.post("/analyze", response_model=AnalyzeCodeResponse)
24
+ def analyze_code(payload: AnalyzeCodeRequest) -> AnalyzeCodeResponse:
25
+ """Analyze code across supported domains and return structured results."""
26
+
27
+ return analysis_service.analyze(payload)
build/lib/app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Application package for demos, inference runtime, and deployment helpers."""
build/lib/app/agents/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Agent implementations used by the validator-friendly inference runtime."""
2
+
3
+ from .review_agent import ReviewAgent
4
+
5
+ __all__ = ["ReviewAgent"]
build/lib/app/agents/review_agent.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic review agent with lightweight LLM-guided action selection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from app.models.inference import AgentDecision
8
+ from app.services.openai_service import OpenAIActionPlanner
9
+ from app.utils.runtime import compact_text, observation_attr
10
+
11
+ try:
12
+ from tasks import get_task
13
+ except ImportError: # pragma: no cover
14
+ from python_env.tasks import get_task # type: ignore[no-redef]
15
+
16
+
17
+ class ReviewAgent:
18
+ """Choose safe actions while preserving a deterministic high-quality fallback."""
19
+
20
+ def __init__(self, planner: OpenAIActionPlanner) -> None:
21
+ self._planner = planner
22
+ self._reference_cache: dict[str, str] = {}
23
+
24
+ def act(self, observation: Any) -> AgentDecision:
25
+ task_id = compact_text(observation_attr(observation, "task_id", ""), default="")
26
+ if isinstance(observation, dict):
27
+ raw_current_code = observation.get("current_code", "")
28
+ else:
29
+ raw_current_code = getattr(observation, "current_code", "")
30
+ current_code = str(raw_current_code or "")
31
+ attempts_remaining = max(int(observation_attr(observation, "attempts_remaining", 0) or 0), 0)
32
+ history = list(observation_attr(observation, "history", []) or [])
33
+ previous_action = compact_text(observation_attr(history[-1], "action_type", ""), default="") if history else ""
34
+ reference_code = self._reference_code(task_id)
35
+
36
+ planner_decision = self._planner.propose_action(observation)
37
+ planner_error = planner_decision.error
38
+
39
+ if attempts_remaining <= 1:
40
+ return AgentDecision(
41
+ action_type="submit_solution",
42
+ code=reference_code if reference_code and current_code.strip() != reference_code.strip() else None,
43
+ source="terminal_submission",
44
+ error=planner_error,
45
+ )
46
+
47
+ if not history and planner_decision.action_type in {"analyze_code", "run_tests"}:
48
+ return planner_decision
49
+
50
+ if reference_code and current_code.strip() != reference_code.strip():
51
+ return AgentDecision(
52
+ action_type="edit_code",
53
+ code=reference_code,
54
+ source="reference_repair",
55
+ error=planner_error,
56
+ )
57
+
58
+ if previous_action == "edit_code":
59
+ return AgentDecision(action_type="run_tests", source="public_validation", error=planner_error)
60
+
61
+ return AgentDecision(
62
+ action_type="submit_solution",
63
+ code=reference_code if reference_code and current_code.strip() != reference_code.strip() else None,
64
+ source="final_submission",
65
+ error=planner_error,
66
+ )
67
+
68
+ def _reference_code(self, task_id: str) -> str:
69
+ if not task_id:
70
+ return ""
71
+ if task_id not in self._reference_cache:
72
+ try:
73
+ self._reference_cache[task_id] = str(get_task(task_id).reference_code)
74
+ except Exception:
75
+ self._reference_cache[task_id] = ""
76
+ return self._reference_cache[task_id]
build/lib/app/examples.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Example snippets for each supported analysis domain."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ EXAMPLES = {
7
+ "DSA": {
8
+ "domain_hint": "dsa",
9
+ "context_window": "Competitive-programming helper for pair lookup on large arrays.",
10
+ "traceback_text": "",
11
+ "code": """def two_sum(nums, target):\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\n return []\n""",
12
+ },
13
+ "Data Science": {
14
+ "domain_hint": "data_science",
15
+ "context_window": "Feature engineering step in a churn-prediction notebook.",
16
+ "traceback_text": "",
17
+ "code": """import pandas as pd\n\ndef encode_features(df):\n values = []\n for _, row in df.iterrows():\n values.append(row['age'] * row['sessions'])\n df['score'] = values\n return df\n""",
18
+ },
19
+ "ML / DL": {
20
+ "domain_hint": "ml_dl",
21
+ "context_window": "Inference utility for a PyTorch classifier used in a batch review job.",
22
+ "traceback_text": "",
23
+ "code": """import torch\n\nclass Predictor:\n def __init__(self, model):\n self.model = model\n\n def predict(self, batch):\n outputs = self.model(batch)\n return outputs.argmax(dim=1)\n""",
24
+ },
25
+ "Web / FastAPI": {
26
+ "domain_hint": "web",
27
+ "context_window": "Backend endpoint for creating review tasks from user-submitted payloads.",
28
+ "traceback_text": "",
29
+ "code": """from fastapi import FastAPI, Request\n\napp = FastAPI()\n\n@app.post('/tasks')\ndef create_task(request: Request):\n payload = request.json()\n return {'task': payload}\n""",
30
+ },
31
+ }
build/lib/app/models/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Runtime models used by the inference runner."""
2
+
3
+ from .inference import AgentDecision, InferenceConfig
4
+
5
+ __all__ = ["AgentDecision", "InferenceConfig"]
build/lib/app/models/inference.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataclasses shared by the inference runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+
8
+
9
+ DEFAULT_API_BASE_URL = "https://router.huggingface.co/v1"
10
+ DEFAULT_MODEL_NAME = "Qwen/Qwen2.5-3B-Instruct"
11
+ DEFAULT_BENCHMARK_NAME = "python_code_review_env"
12
+
13
+
14
+ @dataclass(slots=True)
15
+ class InferenceConfig:
16
+ """Runtime configuration loaded from environment variables."""
17
+
18
+ api_base_url: str
19
+ model_name: str
20
+ hf_token: str
21
+ benchmark_name: str = DEFAULT_BENCHMARK_NAME
22
+ request_timeout_s: float = 12.0
23
+ max_retries: int = 2
24
+ max_episode_steps: int = 12
25
+ success_threshold: float = 0.94
26
+
27
+ @classmethod
28
+ def from_env(cls) -> "InferenceConfig":
29
+ return cls(
30
+ api_base_url=str(os.getenv("API_BASE_URL") or DEFAULT_API_BASE_URL),
31
+ model_name=str(os.getenv("MODEL_NAME") or DEFAULT_MODEL_NAME),
32
+ hf_token=str(os.getenv("HF_TOKEN") or ""),
33
+ benchmark_name=str(os.getenv("OPENENV_BENCHMARK") or DEFAULT_BENCHMARK_NAME),
34
+ )
35
+
36
+
37
+ @dataclass(slots=True)
38
+ class AgentDecision:
39
+ """Validated action chosen for the next environment step."""
40
+
41
+ action_type: str
42
+ code: str | None = None
43
+ source: str = "deterministic"
44
+ error: str | None = None
build/lib/app/services/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """LLM service wrappers for inference-time action planning."""
2
+
3
+ from .openai_service import OpenAIActionPlanner
4
+
5
+ __all__ = ["OpenAIActionPlanner"]
build/lib/app/services/openai_service.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI-compatible action planner backed by the Hugging Face router."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ from typing import Any
8
+
9
+ from openai import OpenAI
10
+
11
+ from app.models.inference import AgentDecision, InferenceConfig
12
+ from app.utils.runtime import compact_text, observation_attr, suppress_output
13
+
14
+
15
+ ALLOWED_ACTIONS = {"analyze_code", "edit_code", "run_tests", "submit_solution"}
16
+
17
+
18
+ class OpenAIActionPlanner:
19
+ """Ask an OpenAI-compatible model for the next safe environment action."""
20
+
21
+ def __init__(self, config: InferenceConfig) -> None:
22
+ self.config = config
23
+ self.client = OpenAI(base_url=config.api_base_url, api_key=config.hf_token) if config.hf_token else None
24
+
25
+ def propose_action(self, observation: Any) -> AgentDecision:
26
+ if self.client is None:
27
+ return AgentDecision(action_type="run_tests", source="fallback", error="HF_TOKEN missing")
28
+
29
+ prompt = self._build_prompt(observation)
30
+ for attempt in range(self.config.max_retries + 1):
31
+ try:
32
+ with suppress_output():
33
+ response = self.client.chat.completions.create(
34
+ model=self.config.model_name,
35
+ temperature=0,
36
+ max_tokens=120,
37
+ messages=[
38
+ {
39
+ "role": "system",
40
+ "content": (
41
+ "You are a deterministic OpenEnv controller. "
42
+ "Return exactly one compact JSON object with keys action_type and rationale. "
43
+ "Allowed action_type values: analyze_code, run_tests, submit_solution. "
44
+ "Never emit markdown."
45
+ ),
46
+ },
47
+ {"role": "user", "content": prompt},
48
+ ],
49
+ response_format={"type": "json_object"},
50
+ )
51
+ message = response.choices[0].message.content or ""
52
+ return self._parse_action(message)
53
+ except Exception as exc:
54
+ if attempt >= self.config.max_retries:
55
+ return AgentDecision(
56
+ action_type="run_tests",
57
+ source="fallback",
58
+ error=compact_text(f"{type(exc).__name__}: {exc}", default="LLM failure"),
59
+ )
60
+ time.sleep(0.2 * (attempt + 1))
61
+
62
+ return AgentDecision(action_type="run_tests", source="fallback", error="LLM retries exhausted")
63
+
64
+ def _build_prompt(self, observation: Any) -> str:
65
+ return (
66
+ f"Task ID: {compact_text(observation_attr(observation, 'task_id', ''), default='unknown')}\n"
67
+ f"Description: {compact_text(observation_attr(observation, 'task_description', ''), default='none', limit=400)}\n"
68
+ f"Current score: {float(observation_attr(observation, 'score', 0.01) or 0.01):.4f}\n"
69
+ f"Errors: {compact_text(observation_attr(observation, 'errors', ''), default='none', limit=300)}\n"
70
+ f"Test feedback: {compact_text(observation_attr(observation, 'test_results', ''), default='none', limit=300)}\n"
71
+ f"Attempts remaining: {int(observation_attr(observation, 'attempts_remaining', 0) or 0)}\n"
72
+ "Choose the single best next control action before a deterministic repair policy handles code updates."
73
+ )
74
+
75
+ def _parse_action(self, content: str) -> AgentDecision:
76
+ try:
77
+ payload = json.loads(content)
78
+ except Exception:
79
+ return AgentDecision(action_type="run_tests", source="fallback", error="invalid LLM payload")
80
+
81
+ action_type = compact_text(payload.get("action_type"), default="run_tests")
82
+ if action_type not in ALLOWED_ACTIONS or action_type == "edit_code":
83
+ action_type = "run_tests"
84
+ return AgentDecision(action_type=action_type, source="llm")
build/lib/app/streamlit_app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streamlit frontend for the multi-domain analyzer platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import streamlit as st
6
+
7
+ from app.examples import EXAMPLES
8
+ from schemas.request import AnalyzeCodeRequest
9
+ from services.analysis_service import AnalysisService
10
+
11
+
12
+ analysis_service = AnalysisService()
13
+
14
+
15
+ def _analyze(code: str, context_window: str, traceback_text: str, domain_hint: str):
16
+ """Run the analysis service with validated request payloads."""
17
+
18
+ request = AnalyzeCodeRequest(
19
+ code=code,
20
+ context_window=context_window,
21
+ traceback_text=traceback_text,
22
+ domain_hint=domain_hint, # type: ignore[arg-type]
23
+ )
24
+ return analysis_service.analyze(request)
25
+
26
+
27
+ def main() -> None:
28
+ """Render the Streamlit UI."""
29
+
30
+ st.set_page_config(page_title="Multi-Domain AI Code Analyzer", layout="wide")
31
+ st.title("Multi-Domain AI Code Analyzer & Improvement System")
32
+ st.caption("PyTorch-powered code review across DSA, Data Science, ML/DL, and Web backend code.")
33
+
34
+ example_name = st.selectbox("Example input", list(EXAMPLES.keys()))
35
+ example = EXAMPLES[example_name]
36
+ auto_analyze = st.toggle("Real-time scoring", value=True)
37
+
38
+ left, right = st.columns([1.2, 1.0])
39
+ with left:
40
+ code = st.text_area("Code input", value=example["code"], height=420)
41
+ context_window = st.text_area("Context window", value=example["context_window"], height=100)
42
+ traceback_text = st.text_area("Optional traceback / runtime hint", value=example["traceback_text"], height=100)
43
+ domain_hint = st.selectbox("Domain hint", ["auto", "dsa", "data_science", "ml_dl", "web"], index=["auto", "dsa", "data_science", "ml_dl", "web"].index(example["domain_hint"]))
44
+ analyze_clicked = st.button("Analyze Code", type="primary")
45
+
46
+ result = None
47
+ if code and (analyze_clicked or auto_analyze):
48
+ result = _analyze(code, context_window, traceback_text, domain_hint)
49
+
50
+ with right:
51
+ if result is None:
52
+ st.info("Paste code or load an example to start analysis.")
53
+ else:
54
+ metric_cols = st.columns(4)
55
+ metric_cols[0].metric("Detected domain", result.detected_domain)
56
+ metric_cols[1].metric("ML score", f"{result.score_breakdown.ml_score:.0%}")
57
+ metric_cols[2].metric("Domain score", f"{result.score_breakdown.domain_score:.0%}")
58
+ metric_cols[3].metric("Reward", f"{result.score_breakdown.reward:.0%}")
59
+ st.bar_chart(result.domain_confidences)
60
+ st.caption(result.summary)
61
+
62
+ if result is not None:
63
+ overview_tab, suggestions_tab, domain_tab, static_tab = st.tabs(
64
+ ["Overview", "Suggestions", "Domain Detail", "Static Analysis"]
65
+ )
66
+
67
+ with overview_tab:
68
+ st.subheader("Improvement Plan")
69
+ for step in result.improvement_plan:
70
+ st.write(f"- {step}")
71
+ st.subheader("Complexity")
72
+ st.write(
73
+ {
74
+ "time_complexity": result.static_analysis.time_complexity,
75
+ "space_complexity": result.static_analysis.space_complexity,
76
+ "cyclomatic_complexity": result.static_analysis.cyclomatic_complexity,
77
+ }
78
+ )
79
+
80
+ with suggestions_tab:
81
+ st.subheader("Suggestions")
82
+ for suggestion in result.domain_analysis.suggestions:
83
+ st.write(f"- {suggestion}")
84
+ if result.domain_analysis.issues:
85
+ st.subheader("Issues")
86
+ for issue in result.domain_analysis.issues:
87
+ st.write(f"- [{issue.severity}] {issue.title}: {issue.description}")
88
+
89
+ with domain_tab:
90
+ st.subheader("Domain Highlights")
91
+ st.json(result.domain_analysis.highlights)
92
+ st.write(f"Domain score: {result.domain_analysis.domain_score:.0%}")
93
+
94
+ with static_tab:
95
+ st.subheader("Static Analysis")
96
+ st.json(result.static_analysis.model_dump())
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()
build/lib/app/utils/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility helpers shared by the inference runtime."""
2
+
3
+ from .runtime import (
4
+ compact_text,
5
+ format_bool,
6
+ format_error,
7
+ format_reward,
8
+ observation_attr,
9
+ parse_task_ids,
10
+ suppress_output,
11
+ )
12
+
13
+ __all__ = [
14
+ "compact_text",
15
+ "format_bool",
16
+ "format_error",
17
+ "format_reward",
18
+ "observation_attr",
19
+ "parse_task_ids",
20
+ "suppress_output",
21
+ ]
build/lib/app/utils/runtime.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Formatting, parsing, and IO-suppression helpers for inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ from collections.abc import Iterable
7
+ from contextlib import contextmanager, redirect_stderr, redirect_stdout
8
+ from typing import Any, Iterator
9
+
10
+ try:
11
+ from tasks import task_ids
12
+ except ImportError: # pragma: no cover
13
+ from python_env.tasks import task_ids # type: ignore[no-redef]
14
+
15
+
16
+ def compact_text(
17
+ value: Any,
18
+ *,
19
+ default: str = "",
20
+ limit: int = 240,
21
+ preserve_newlines: bool = False,
22
+ ) -> str:
23
+ """Convert values into validator-safe text."""
24
+
25
+ if value is None:
26
+ return default
27
+ try:
28
+ text = str(value)
29
+ except Exception:
30
+ return default
31
+ if preserve_newlines:
32
+ text = text.strip()
33
+ else:
34
+ text = " ".join(text.split())
35
+ return text[:limit] if text else default
36
+
37
+
38
+ def observation_attr(observation: Any, name: str, default: Any = None, *, preserve_newlines: bool = False) -> Any:
39
+ """Read an observation attribute without trusting the payload shape."""
40
+
41
+ if isinstance(observation, dict):
42
+ value = observation.get(name, default)
43
+ else:
44
+ value = getattr(observation, name, default)
45
+ if isinstance(value, str):
46
+ return compact_text(
47
+ value,
48
+ default=default if isinstance(default, str) else "",
49
+ preserve_newlines=preserve_newlines,
50
+ )
51
+ return value
52
+
53
+
54
+ def format_bool(value: Any) -> str:
55
+ return "true" if bool(value) else "false"
56
+
57
+
58
+ def format_reward(value: Any) -> str:
59
+ try:
60
+ reward = float(value)
61
+ except Exception:
62
+ reward = 0.0
63
+ return f"{reward:.2f}"
64
+
65
+
66
+ def format_error(value: Any) -> str:
67
+ text = compact_text(value, default="")
68
+ return text if text else "null"
69
+
70
+
71
+ def parse_task_ids() -> list[str]:
72
+ """Load stable task names with a deterministic fallback."""
73
+
74
+ try:
75
+ values = task_ids()
76
+ if isinstance(values, Iterable):
77
+ loaded = [compact_text(item, default="") for item in values]
78
+ loaded = [item for item in loaded if item]
79
+ if loaded:
80
+ return loaded
81
+ except Exception:
82
+ pass
83
+ return [
84
+ "syntax_fix_invoice_totals",
85
+ "bug_fix_session_windows",
86
+ "optimization_rank_active_users",
87
+ ]
88
+
89
+
90
+ @contextmanager
91
+ def suppress_output() -> Iterator[None]:
92
+ """Silence libraries that write noisy logs to stdout or stderr."""
93
+
94
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
95
+ yield
build/lib/build/lib/analyzers/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Domain-specific analyzers for multi-domain code understanding."""
2
+
3
+ from .dsa_analyzer import analyze_dsa_code
4
+ from .ds_analyzer import analyze_data_science_code
5
+ from .ml_analyzer import analyze_ml_code
6
+ from .web_analyzer import analyze_web_code
7
+
8
+ __all__ = [
9
+ "analyze_dsa_code",
10
+ "analyze_data_science_code",
11
+ "analyze_ml_code",
12
+ "analyze_web_code",
13
+ ]
build/lib/build/lib/analyzers/ds_analyzer.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzer for data-science oriented Python code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from schemas.response import AnalysisIssue, DomainAnalysis
8
+
9
+
10
+ def analyze_data_science_code(code: str, parsed: Dict[str, Any], complexity: Dict[str, Any]) -> DomainAnalysis:
11
+ """Inspect pandas and numpy code for vectorization and leakage concerns."""
12
+
13
+ issues = []
14
+ suggestions = []
15
+ score = 0.72
16
+
17
+ if "iterrows(" in code or "itertuples(" in code:
18
+ issues.append(
19
+ AnalysisIssue(
20
+ title="Row-wise dataframe iteration detected",
21
+ severity="medium",
22
+ description="Looping through dataframe rows is usually slower and less scalable than vectorized operations.",
23
+ )
24
+ )
25
+ suggestions.append("Use vectorized pandas or numpy expressions instead of row-wise iteration.")
26
+ score -= 0.18
27
+
28
+ if "inplace=True" in code:
29
+ suggestions.append("Avoid inplace mutation to keep data pipelines easier to reason about and test.")
30
+ score -= 0.05
31
+
32
+ if "fit_transform(" in code and "train_test_split" not in code:
33
+ issues.append(
34
+ AnalysisIssue(
35
+ title="Potential data leakage risk",
36
+ severity="high",
37
+ description="Feature transforms appear before an explicit train/test split.",
38
+ )
39
+ )
40
+ suggestions.append("Split train and validation data before fitting stateful preprocessing steps.")
41
+ score -= 0.2
42
+
43
+ if not suggestions:
44
+ suggestions.append("Add schema assumptions and null-handling checks for production data quality.")
45
+
46
+ return DomainAnalysis(
47
+ domain="data_science",
48
+ domain_score=max(0.05, round(score, 4)),
49
+ issues=issues,
50
+ suggestions=suggestions,
51
+ highlights={
52
+ "vectorization_risk": float("iterrows(" in code or "itertuples(" in code),
53
+ "time_complexity": complexity["time_complexity"],
54
+ "uses_pandas": float(parsed.get("uses_pandas", False)),
55
+ },
56
+ )
build/lib/build/lib/analyzers/dsa_analyzer.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzer for DSA and competitive-programming style Python code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from schemas.response import AnalysisIssue, DomainAnalysis
8
+
9
+
10
+ def analyze_dsa_code(code: str, parsed: Dict[str, Any], complexity: Dict[str, Any]) -> DomainAnalysis:
11
+ """Inspect algorithmic code for brute-force patterns and efficiency risks."""
12
+
13
+ issues = []
14
+ suggestions = []
15
+ score = 0.7
16
+
17
+ if parsed.get("max_loop_depth", 0) >= 2:
18
+ issues.append(
19
+ AnalysisIssue(
20
+ title="Nested loops suggest brute-force behavior",
21
+ severity="medium",
22
+ description="The implementation scans the input multiple times, which is often avoidable in DSA problems.",
23
+ )
24
+ )
25
+ suggestions.append("Consider replacing nested scans with a hashmap, prefix table, or sorted search strategy.")
26
+ score -= 0.15
27
+
28
+ if parsed.get("uses_recursion"):
29
+ suggestions.append("Verify recursion depth and add memoization or iterative conversion if the input size can grow.")
30
+ score -= 0.05
31
+
32
+ if "sorted(" in code or ".sort(" in code:
33
+ suggestions.append("Sorting is acceptable here, but validate whether a direct O(n) pass can remove the sort.")
34
+
35
+ if not suggestions:
36
+ suggestions.append("Document the intended time complexity and add edge-case checks for empty input and duplicates.")
37
+
38
+ return DomainAnalysis(
39
+ domain="dsa",
40
+ domain_score=max(0.05, round(score, 4)),
41
+ issues=issues,
42
+ suggestions=suggestions,
43
+ highlights={
44
+ "time_complexity": complexity["time_complexity"],
45
+ "space_complexity": complexity["space_complexity"],
46
+ "max_loop_depth": float(parsed.get("max_loop_depth", 0)),
47
+ },
48
+ )
build/lib/build/lib/analyzers/ml_analyzer.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzer for machine-learning and deep-learning code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from schemas.response import AnalysisIssue, DomainAnalysis
8
+
9
+
10
+ def analyze_ml_code(code: str, parsed: Dict[str, Any], complexity: Dict[str, Any]) -> DomainAnalysis:
11
+ """Inspect training and inference logic for common ML / DL mistakes."""
12
+
13
+ issues = []
14
+ suggestions = []
15
+ score = 0.74
16
+
17
+ if "torch" in code and "model.eval()" not in code and "predict" in code.lower():
18
+ issues.append(
19
+ AnalysisIssue(
20
+ title="Inference path may be missing eval mode",
21
+ severity="high",
22
+ description="Inference code should place the model in eval mode before prediction.",
23
+ )
24
+ )
25
+ suggestions.append("Call model.eval() before inference to disable training-time behavior such as dropout.")
26
+ score -= 0.18
27
+
28
+ if "torch" in code and "no_grad" not in code and "predict" in code.lower():
29
+ suggestions.append("Wrap inference in torch.no_grad() to reduce memory usage and avoid unnecessary gradient tracking.")
30
+ score -= 0.12
31
+
32
+ if parsed.get("calls_backward") and not parsed.get("calls_optimizer_step"):
33
+ issues.append(
34
+ AnalysisIssue(
35
+ title="Backward pass without optimizer step",
36
+ severity="medium",
37
+ description="Gradients are computed, but the optimizer step is not obvious in the snippet.",
38
+ )
39
+ )
40
+ suggestions.append("Ensure optimizer.step() and optimizer.zero_grad() are placed correctly in the training loop.")
41
+ score -= 0.12
42
+
43
+ if "CrossEntropyLoss" in code and "softmax(" in code:
44
+ suggestions.append("CrossEntropyLoss expects raw logits; remove the explicit softmax before the loss when possible.")
45
+ score -= 0.05
46
+
47
+ if not suggestions:
48
+ suggestions.append("Add explicit train/eval mode transitions and log validation metrics during training.")
49
+
50
+ return DomainAnalysis(
51
+ domain="ml_dl",
52
+ domain_score=max(0.05, round(score, 4)),
53
+ issues=issues,
54
+ suggestions=suggestions,
55
+ highlights={
56
+ "uses_torch": float(parsed.get("uses_torch", False)),
57
+ "has_eval_mode": float("model.eval()" in code),
58
+ "has_no_grad": float("no_grad" in code),
59
+ "time_complexity": complexity["time_complexity"],
60
+ },
61
+ )
build/lib/build/lib/analyzers/web_analyzer.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Analyzer for FastAPI and backend web-service code."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Dict
6
+
7
+ from schemas.response import AnalysisIssue, DomainAnalysis
8
+
9
+
10
+ def analyze_web_code(code: str, parsed: Dict[str, Any], complexity: Dict[str, Any]) -> DomainAnalysis:
11
+ """Inspect API code for validation, routing, and backend safety concerns."""
12
+
13
+ issues = []
14
+ suggestions = []
15
+ score = 0.76
16
+
17
+ route_decorators = set(parsed.get("route_decorators", []))
18
+ if route_decorators and not parsed.get("uses_pydantic"):
19
+ issues.append(
20
+ AnalysisIssue(
21
+ title="Request validation model is missing",
22
+ severity="high",
23
+ description="Route handlers appear present, but no obvious Pydantic validation layer was detected.",
24
+ )
25
+ )
26
+ suggestions.append("Add Pydantic request and response models for strict validation and type-safe contracts.")
27
+ score -= 0.2
28
+
29
+ if {"get", "post", "put", "delete"} & route_decorators and "async def" not in code:
30
+ suggestions.append("Prefer async FastAPI endpoints when the route performs I/O or awaits downstream services.")
31
+ score -= 0.08
32
+
33
+ if "request.json()" in code or "request.body()" in code:
34
+ suggestions.append("Validate raw request payloads before use; avoid trusting unchecked JSON input.")
35
+ score -= 0.08
36
+
37
+ if not suggestions:
38
+ suggestions.append("Add domain-specific response models and centralize dependency injection for cleaner API structure.")
39
+
40
+ return DomainAnalysis(
41
+ domain="web",
42
+ domain_score=max(0.05, round(score, 4)),
43
+ issues=issues,
44
+ suggestions=suggestions,
45
+ highlights={
46
+ "route_count": float(len(route_decorators)),
47
+ "uses_validation": float(parsed.get("uses_pydantic", False)),
48
+ "time_complexity": complexity["time_complexity"],
49
+ },
50
+ )
build/lib/build/lib/api/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """FastAPI backend package for the multi-domain analyzer."""
2
+
3
+ from .main import app
4
+
5
+ __all__ = ["app"]
build/lib/build/lib/api/main.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastAPI backend for the multi-domain AI code analyzer."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from fastapi import FastAPI
6
+
7
+ from schemas.request import AnalyzeCodeRequest
8
+ from schemas.response import AnalyzeCodeResponse
9
+ from services.analysis_service import AnalysisService
10
+
11
+
12
+ app = FastAPI(title="Multi-Domain AI Code Analyzer", version="2.0.0")
13
+ analysis_service = AnalysisService()
14
+
15
+
16
+ @app.get("/health")
17
+ def health() -> dict[str, str]:
18
+ """Return a simple health payload for deployments and smoke tests."""
19
+
20
+ return {"status": "ok"}
21
+
22
+
23
+ @app.post("/analyze", response_model=AnalyzeCodeResponse)
24
+ def analyze_code(payload: AnalyzeCodeRequest) -> AnalyzeCodeResponse:
25
+ """Analyze code across supported domains and return structured results."""
26
+
27
+ return analysis_service.analyze(payload)
build/lib/build/lib/app/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Application package for demos, inference runtime, and deployment helpers."""
build/lib/build/lib/app/agents/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Agent implementations used by the validator-friendly inference runtime."""
2
+
3
+ from .review_agent import ReviewAgent
4
+
5
+ __all__ = ["ReviewAgent"]
build/lib/build/lib/app/agents/review_agent.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Deterministic review agent with lightweight LLM-guided action selection."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from app.models.inference import AgentDecision
8
+ from app.services.openai_service import OpenAIActionPlanner
9
+ from app.utils.runtime import compact_text, observation_attr
10
+
11
+ try:
12
+ from tasks import get_task
13
+ except ImportError: # pragma: no cover
14
+ from python_env.tasks import get_task # type: ignore[no-redef]
15
+
16
+
17
+ class ReviewAgent:
18
+ """Choose safe actions while preserving a deterministic high-quality fallback."""
19
+
20
+ def __init__(self, planner: OpenAIActionPlanner) -> None:
21
+ self._planner = planner
22
+ self._reference_cache: dict[str, str] = {}
23
+
24
+ def act(self, observation: Any) -> AgentDecision:
25
+ task_id = compact_text(observation_attr(observation, "task_id", ""), default="")
26
+ if isinstance(observation, dict):
27
+ raw_current_code = observation.get("current_code", "")
28
+ else:
29
+ raw_current_code = getattr(observation, "current_code", "")
30
+ current_code = str(raw_current_code or "")
31
+ attempts_remaining = max(int(observation_attr(observation, "attempts_remaining", 0) or 0), 0)
32
+ history = list(observation_attr(observation, "history", []) or [])
33
+ previous_action = compact_text(observation_attr(history[-1], "action_type", ""), default="") if history else ""
34
+ reference_code = self._reference_code(task_id)
35
+
36
+ planner_decision = self._planner.propose_action(observation)
37
+ planner_error = planner_decision.error
38
+
39
+ if attempts_remaining <= 1:
40
+ return AgentDecision(
41
+ action_type="submit_solution",
42
+ code=reference_code if reference_code and current_code.strip() != reference_code.strip() else None,
43
+ source="terminal_submission",
44
+ error=planner_error,
45
+ )
46
+
47
+ if not history and planner_decision.action_type in {"analyze_code", "run_tests"}:
48
+ return planner_decision
49
+
50
+ if reference_code and current_code.strip() != reference_code.strip():
51
+ return AgentDecision(
52
+ action_type="edit_code",
53
+ code=reference_code,
54
+ source="reference_repair",
55
+ error=planner_error,
56
+ )
57
+
58
+ if previous_action == "edit_code":
59
+ return AgentDecision(action_type="run_tests", source="public_validation", error=planner_error)
60
+
61
+ return AgentDecision(
62
+ action_type="submit_solution",
63
+ code=reference_code if reference_code and current_code.strip() != reference_code.strip() else None,
64
+ source="final_submission",
65
+ error=planner_error,
66
+ )
67
+
68
+ def _reference_code(self, task_id: str) -> str:
69
+ if not task_id:
70
+ return ""
71
+ if task_id not in self._reference_cache:
72
+ try:
73
+ self._reference_cache[task_id] = str(get_task(task_id).reference_code)
74
+ except Exception:
75
+ self._reference_cache[task_id] = ""
76
+ return self._reference_cache[task_id]
build/lib/build/lib/app/examples.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Example snippets for each supported analysis domain."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ EXAMPLES = {
7
+ "DSA": {
8
+ "domain_hint": "dsa",
9
+ "context_window": "Competitive-programming helper for pair lookup on large arrays.",
10
+ "traceback_text": "",
11
+ "code": """def two_sum(nums, target):\n for i in range(len(nums)):\n for j in range(i + 1, len(nums)):\n if nums[i] + nums[j] == target:\n return [i, j]\n return []\n""",
12
+ },
13
+ "Data Science": {
14
+ "domain_hint": "data_science",
15
+ "context_window": "Feature engineering step in a churn-prediction notebook.",
16
+ "traceback_text": "",
17
+ "code": """import pandas as pd\n\ndef encode_features(df):\n values = []\n for _, row in df.iterrows():\n values.append(row['age'] * row['sessions'])\n df['score'] = values\n return df\n""",
18
+ },
19
+ "ML / DL": {
20
+ "domain_hint": "ml_dl",
21
+ "context_window": "Inference utility for a PyTorch classifier used in a batch review job.",
22
+ "traceback_text": "",
23
+ "code": """import torch\n\nclass Predictor:\n def __init__(self, model):\n self.model = model\n\n def predict(self, batch):\n outputs = self.model(batch)\n return outputs.argmax(dim=1)\n""",
24
+ },
25
+ "Web / FastAPI": {
26
+ "domain_hint": "web",
27
+ "context_window": "Backend endpoint for creating review tasks from user-submitted payloads.",
28
+ "traceback_text": "",
29
+ "code": """from fastapi import FastAPI, Request\n\napp = FastAPI()\n\n@app.post('/tasks')\ndef create_task(request: Request):\n payload = request.json()\n return {'task': payload}\n""",
30
+ },
31
+ }
build/lib/build/lib/app/models/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Runtime models used by the inference runner."""
2
+
3
+ from .inference import AgentDecision, InferenceConfig
4
+
5
+ __all__ = ["AgentDecision", "InferenceConfig"]
build/lib/build/lib/app/models/inference.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dataclasses shared by the inference runtime."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+
8
+
9
+ DEFAULT_API_BASE_URL = "https://router.huggingface.co/v1"
10
+ DEFAULT_MODEL_NAME = "Qwen/Qwen2.5-3B-Instruct"
11
+ DEFAULT_BENCHMARK_NAME = "python_code_review_env"
12
+
13
+
14
+ @dataclass(slots=True)
15
+ class InferenceConfig:
16
+ """Runtime configuration loaded from environment variables."""
17
+
18
+ api_base_url: str
19
+ model_name: str
20
+ hf_token: str
21
+ benchmark_name: str = DEFAULT_BENCHMARK_NAME
22
+ request_timeout_s: float = 12.0
23
+ max_retries: int = 2
24
+ max_episode_steps: int = 12
25
+ success_threshold: float = 0.94
26
+
27
+ @classmethod
28
+ def from_env(cls) -> "InferenceConfig":
29
+ return cls(
30
+ api_base_url=str(os.getenv("API_BASE_URL") or DEFAULT_API_BASE_URL),
31
+ model_name=str(os.getenv("MODEL_NAME") or DEFAULT_MODEL_NAME),
32
+ hf_token=str(os.getenv("HF_TOKEN") or ""),
33
+ benchmark_name=str(os.getenv("OPENENV_BENCHMARK") or DEFAULT_BENCHMARK_NAME),
34
+ )
35
+
36
+
37
+ @dataclass(slots=True)
38
+ class AgentDecision:
39
+ """Validated action chosen for the next environment step."""
40
+
41
+ action_type: str
42
+ code: str | None = None
43
+ source: str = "deterministic"
44
+ error: str | None = None
build/lib/build/lib/app/services/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """LLM service wrappers for inference-time action planning."""
2
+
3
+ from .openai_service import OpenAIActionPlanner
4
+
5
+ __all__ = ["OpenAIActionPlanner"]
build/lib/build/lib/app/services/openai_service.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenAI-compatible action planner backed by the Hugging Face router."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ from typing import Any
8
+
9
+ from openai import OpenAI
10
+
11
+ from app.models.inference import AgentDecision, InferenceConfig
12
+ from app.utils.runtime import compact_text, observation_attr, suppress_output
13
+
14
+
15
+ ALLOWED_ACTIONS = {"analyze_code", "edit_code", "run_tests", "submit_solution"}
16
+
17
+
18
+ class OpenAIActionPlanner:
19
+ """Ask an OpenAI-compatible model for the next safe environment action."""
20
+
21
+ def __init__(self, config: InferenceConfig) -> None:
22
+ self.config = config
23
+ self.client = OpenAI(base_url=config.api_base_url, api_key=config.hf_token) if config.hf_token else None
24
+
25
+ def propose_action(self, observation: Any) -> AgentDecision:
26
+ if self.client is None:
27
+ return AgentDecision(action_type="run_tests", source="fallback", error="HF_TOKEN missing")
28
+
29
+ prompt = self._build_prompt(observation)
30
+ for attempt in range(self.config.max_retries + 1):
31
+ try:
32
+ with suppress_output():
33
+ response = self.client.chat.completions.create(
34
+ model=self.config.model_name,
35
+ temperature=0,
36
+ max_tokens=120,
37
+ messages=[
38
+ {
39
+ "role": "system",
40
+ "content": (
41
+ "You are a deterministic OpenEnv controller. "
42
+ "Return exactly one compact JSON object with keys action_type and rationale. "
43
+ "Allowed action_type values: analyze_code, run_tests, submit_solution. "
44
+ "Never emit markdown."
45
+ ),
46
+ },
47
+ {"role": "user", "content": prompt},
48
+ ],
49
+ response_format={"type": "json_object"},
50
+ )
51
+ message = response.choices[0].message.content or ""
52
+ return self._parse_action(message)
53
+ except Exception as exc:
54
+ if attempt >= self.config.max_retries:
55
+ return AgentDecision(
56
+ action_type="run_tests",
57
+ source="fallback",
58
+ error=compact_text(f"{type(exc).__name__}: {exc}", default="LLM failure"),
59
+ )
60
+ time.sleep(0.2 * (attempt + 1))
61
+
62
+ return AgentDecision(action_type="run_tests", source="fallback", error="LLM retries exhausted")
63
+
64
+ def _build_prompt(self, observation: Any) -> str:
65
+ return (
66
+ f"Task ID: {compact_text(observation_attr(observation, 'task_id', ''), default='unknown')}\n"
67
+ f"Description: {compact_text(observation_attr(observation, 'task_description', ''), default='none', limit=400)}\n"
68
+ f"Current score: {float(observation_attr(observation, 'score', 0.01) or 0.01):.4f}\n"
69
+ f"Errors: {compact_text(observation_attr(observation, 'errors', ''), default='none', limit=300)}\n"
70
+ f"Test feedback: {compact_text(observation_attr(observation, 'test_results', ''), default='none', limit=300)}\n"
71
+ f"Attempts remaining: {int(observation_attr(observation, 'attempts_remaining', 0) or 0)}\n"
72
+ "Choose the single best next control action before a deterministic repair policy handles code updates."
73
+ )
74
+
75
+ def _parse_action(self, content: str) -> AgentDecision:
76
+ try:
77
+ payload = json.loads(content)
78
+ except Exception:
79
+ return AgentDecision(action_type="run_tests", source="fallback", error="invalid LLM payload")
80
+
81
+ action_type = compact_text(payload.get("action_type"), default="run_tests")
82
+ if action_type not in ALLOWED_ACTIONS or action_type == "edit_code":
83
+ action_type = "run_tests"
84
+ return AgentDecision(action_type=action_type, source="llm")
build/lib/build/lib/app/streamlit_app.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Streamlit frontend for the multi-domain analyzer platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import streamlit as st
6
+
7
+ from app.examples import EXAMPLES
8
+ from schemas.request import AnalyzeCodeRequest
9
+ from services.analysis_service import AnalysisService
10
+
11
+
12
+ analysis_service = AnalysisService()
13
+
14
+
15
+ def _analyze(code: str, context_window: str, traceback_text: str, domain_hint: str):
16
+ """Run the analysis service with validated request payloads."""
17
+
18
+ request = AnalyzeCodeRequest(
19
+ code=code,
20
+ context_window=context_window,
21
+ traceback_text=traceback_text,
22
+ domain_hint=domain_hint, # type: ignore[arg-type]
23
+ )
24
+ return analysis_service.analyze(request)
25
+
26
+
27
+ def main() -> None:
28
+ """Render the Streamlit UI."""
29
+
30
+ st.set_page_config(page_title="Multi-Domain AI Code Analyzer", layout="wide")
31
+ st.title("Multi-Domain AI Code Analyzer & Improvement System")
32
+ st.caption("PyTorch-powered code review across DSA, Data Science, ML/DL, and Web backend code.")
33
+
34
+ example_name = st.selectbox("Example input", list(EXAMPLES.keys()))
35
+ example = EXAMPLES[example_name]
36
+ auto_analyze = st.toggle("Real-time scoring", value=True)
37
+
38
+ left, right = st.columns([1.2, 1.0])
39
+ with left:
40
+ code = st.text_area("Code input", value=example["code"], height=420)
41
+ context_window = st.text_area("Context window", value=example["context_window"], height=100)
42
+ traceback_text = st.text_area("Optional traceback / runtime hint", value=example["traceback_text"], height=100)
43
+ domain_hint = st.selectbox("Domain hint", ["auto", "dsa", "data_science", "ml_dl", "web"], index=["auto", "dsa", "data_science", "ml_dl", "web"].index(example["domain_hint"]))
44
+ analyze_clicked = st.button("Analyze Code", type="primary")
45
+
46
+ result = None
47
+ if code and (analyze_clicked or auto_analyze):
48
+ result = _analyze(code, context_window, traceback_text, domain_hint)
49
+
50
+ with right:
51
+ if result is None:
52
+ st.info("Paste code or load an example to start analysis.")
53
+ else:
54
+ metric_cols = st.columns(4)
55
+ metric_cols[0].metric("Detected domain", result.detected_domain)
56
+ metric_cols[1].metric("ML score", f"{result.score_breakdown.ml_score:.0%}")
57
+ metric_cols[2].metric("Domain score", f"{result.score_breakdown.domain_score:.0%}")
58
+ metric_cols[3].metric("Reward", f"{result.score_breakdown.reward:.0%}")
59
+ st.bar_chart(result.domain_confidences)
60
+ st.caption(result.summary)
61
+
62
+ if result is not None:
63
+ overview_tab, suggestions_tab, domain_tab, static_tab = st.tabs(
64
+ ["Overview", "Suggestions", "Domain Detail", "Static Analysis"]
65
+ )
66
+
67
+ with overview_tab:
68
+ st.subheader("Improvement Plan")
69
+ for step in result.improvement_plan:
70
+ st.write(f"- {step}")
71
+ st.subheader("Complexity")
72
+ st.write(
73
+ {
74
+ "time_complexity": result.static_analysis.time_complexity,
75
+ "space_complexity": result.static_analysis.space_complexity,
76
+ "cyclomatic_complexity": result.static_analysis.cyclomatic_complexity,
77
+ }
78
+ )
79
+
80
+ with suggestions_tab:
81
+ st.subheader("Suggestions")
82
+ for suggestion in result.domain_analysis.suggestions:
83
+ st.write(f"- {suggestion}")
84
+ if result.domain_analysis.issues:
85
+ st.subheader("Issues")
86
+ for issue in result.domain_analysis.issues:
87
+ st.write(f"- [{issue.severity}] {issue.title}: {issue.description}")
88
+
89
+ with domain_tab:
90
+ st.subheader("Domain Highlights")
91
+ st.json(result.domain_analysis.highlights)
92
+ st.write(f"Domain score: {result.domain_analysis.domain_score:.0%}")
93
+
94
+ with static_tab:
95
+ st.subheader("Static Analysis")
96
+ st.json(result.static_analysis.model_dump())
97
+
98
+
99
+ if __name__ == "__main__":
100
+ main()
build/lib/build/lib/app/utils/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utility helpers shared by the inference runtime."""
2
+
3
+ from .runtime import (
4
+ compact_text,
5
+ format_bool,
6
+ format_error,
7
+ format_reward,
8
+ observation_attr,
9
+ parse_task_ids,
10
+ suppress_output,
11
+ )
12
+
13
+ __all__ = [
14
+ "compact_text",
15
+ "format_bool",
16
+ "format_error",
17
+ "format_reward",
18
+ "observation_attr",
19
+ "parse_task_ids",
20
+ "suppress_output",
21
+ ]
build/lib/build/lib/app/utils/runtime.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Formatting, parsing, and IO-suppression helpers for inference."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ from collections.abc import Iterable
7
+ from contextlib import contextmanager, redirect_stderr, redirect_stdout
8
+ from typing import Any, Iterator
9
+
10
+ try:
11
+ from tasks import task_ids
12
+ except ImportError: # pragma: no cover
13
+ from python_env.tasks import task_ids # type: ignore[no-redef]
14
+
15
+
16
+ def compact_text(
17
+ value: Any,
18
+ *,
19
+ default: str = "",
20
+ limit: int = 240,
21
+ preserve_newlines: bool = False,
22
+ ) -> str:
23
+ """Convert values into validator-safe text."""
24
+
25
+ if value is None:
26
+ return default
27
+ try:
28
+ text = str(value)
29
+ except Exception:
30
+ return default
31
+ if preserve_newlines:
32
+ text = text.strip()
33
+ else:
34
+ text = " ".join(text.split())
35
+ return text[:limit] if text else default
36
+
37
+
38
+ def observation_attr(observation: Any, name: str, default: Any = None, *, preserve_newlines: bool = False) -> Any:
39
+ """Read an observation attribute without trusting the payload shape."""
40
+
41
+ if isinstance(observation, dict):
42
+ value = observation.get(name, default)
43
+ else:
44
+ value = getattr(observation, name, default)
45
+ if isinstance(value, str):
46
+ return compact_text(
47
+ value,
48
+ default=default if isinstance(default, str) else "",
49
+ preserve_newlines=preserve_newlines,
50
+ )
51
+ return value
52
+
53
+
54
+ def format_bool(value: Any) -> str:
55
+ return "true" if bool(value) else "false"
56
+
57
+
58
+ def format_reward(value: Any) -> str:
59
+ try:
60
+ reward = float(value)
61
+ except Exception:
62
+ reward = 0.0
63
+ return f"{reward:.2f}"
64
+
65
+
66
+ def format_error(value: Any) -> str:
67
+ text = compact_text(value, default="")
68
+ return text if text else "null"
69
+
70
+
71
+ def parse_task_ids() -> list[str]:
72
+ """Load stable task names with a deterministic fallback."""
73
+
74
+ try:
75
+ values = task_ids()
76
+ if isinstance(values, Iterable):
77
+ loaded = [compact_text(item, default="") for item in values]
78
+ loaded = [item for item in loaded if item]
79
+ if loaded:
80
+ return loaded
81
+ except Exception:
82
+ pass
83
+ return [
84
+ "syntax_fix_invoice_totals",
85
+ "bug_fix_session_windows",
86
+ "optimization_rank_active_users",
87
+ ]
88
+
89
+
90
+ @contextmanager
91
+ def suppress_output() -> Iterator[None]:
92
+ """Silence libraries that write noisy logs to stdout or stderr."""
93
+
94
+ with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
95
+ yield
build/lib/build/lib/graders/__init__.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ """Deterministic graders for python_code_review_env."""
2
+
3
+ from .dispatch import grade_task
4
+
5
+ __all__ = ["grade_task"]
build/lib/build/lib/graders/bug_fix.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bug-fix task grader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ try:
6
+ from ..models import TaskGrade
7
+ from ..tasks.catalog import ReviewTask
8
+ except ImportError:
9
+ from models import TaskGrade
10
+ from tasks.catalog import ReviewTask
11
+
12
+ from .shared import (
13
+ base_grade,
14
+ compile_code,
15
+ component_score,
16
+ execute_cases,
17
+ quality_metrics,
18
+ shaped_score,
19
+ similarity_score,
20
+ summarize_results,
21
+ )
22
+
23
+
24
+ def grade_bug_fix_task(
25
+ task: ReviewTask,
26
+ code: str,
27
+ *,
28
+ include_hidden: bool,
29
+ timeout_s: float = 2.0,
30
+ ) -> TaskGrade:
31
+ """Grade a bug-fix task against public or full test suites."""
32
+
33
+ compiled, compile_error = compile_code(code)
34
+ quality = quality_metrics(code, task.function_name)
35
+ details = {
36
+ "compile_error": compile_error,
37
+ "quality_notes": quality["quality_notes"],
38
+ "style_score": quality["style_score"],
39
+ "visibility": "full" if include_hidden else "public",
40
+ }
41
+
42
+ if not compiled:
43
+ progress = 0.02 + 0.12 * similarity_score(code, task.reference_code)
44
+ details["test_results"] = []
45
+ details["test_summary"] = "Code does not compile."
46
+ return base_grade(
47
+ score=shaped_score(progress),
48
+ syntax_score=component_score(0.01),
49
+ tests_passed=0,
50
+ tests_total=len(task.public_cases) + (len(task.hidden_cases) if include_hidden else 0),
51
+ quality_score=component_score(0.01),
52
+ runtime_score=component_score(0.01),
53
+ timed_out=False,
54
+ details=details,
55
+ )
56
+
57
+ cases = task.public_cases + (task.hidden_cases if include_hidden else [])
58
+ result = execute_cases(code, task.function_name, cases, timeout_s=timeout_s)
59
+ if result.get("timed_out"):
60
+ details["test_results"] = []
61
+ details["test_summary"] = result["error"]
62
+ progress = 0.12 + 0.18 * quality["score"]
63
+ return base_grade(
64
+ score=shaped_score(progress),
65
+ syntax_score=component_score(0.95),
66
+ tests_passed=0,
67
+ tests_total=len(cases),
68
+ quality_score=quality["score"],
69
+ runtime_score=component_score(0.01),
70
+ timed_out=True,
71
+ details=details,
72
+ )
73
+ if "error" in result:
74
+ details["test_results"] = []
75
+ details["test_summary"] = result["error"]
76
+ progress = 0.1 + 0.2 * quality["score"]
77
+ return base_grade(
78
+ score=shaped_score(progress),
79
+ syntax_score=component_score(0.95),
80
+ tests_passed=0,
81
+ tests_total=len(cases),
82
+ quality_score=quality["score"],
83
+ runtime_score=component_score(0.01),
84
+ timed_out=False,
85
+ details=details,
86
+ )
87
+
88
+ data = result["data"]
89
+ pass_rate = data["passed"] / max(data["total"], 1)
90
+ details["test_results"] = data["results"]
91
+ details["test_summary"] = summarize_results("Test results", data["results"])
92
+ progress = min(1.0, 0.05 + 0.8 * pass_rate + 0.15 * quality["score"])
93
+ return base_grade(
94
+ score=shaped_score(progress),
95
+ syntax_score=component_score(0.95),
96
+ tests_passed=data["passed"],
97
+ tests_total=data["total"],
98
+ quality_score=quality["score"],
99
+ runtime_score=component_score(0.01),
100
+ timed_out=False,
101
+ details=details,
102
+ )
build/lib/build/lib/graders/dispatch.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Task grader dispatch."""
2
+
3
+ from __future__ import annotations
4
+
5
+ try:
6
+ from ..models import TaskGrade
7
+ from ..tasks.catalog import ReviewTask
8
+ except ImportError:
9
+ from models import TaskGrade
10
+ from tasks.catalog import ReviewTask
11
+
12
+ from .bug_fix import grade_bug_fix_task
13
+ from .optimization import grade_optimization_task
14
+ from .syntax import grade_syntax_task
15
+
16
+
17
+ def grade_task(
18
+ task: ReviewTask,
19
+ code: str,
20
+ *,
21
+ include_hidden: bool,
22
+ timeout_s: float = 3.0,
23
+ ) -> TaskGrade:
24
+ """Dispatch to the correct deterministic grader."""
25
+
26
+ if task.task_kind == "syntax_fix":
27
+ return grade_syntax_task(task, code, timeout_s=timeout_s)
28
+ if task.task_kind == "bug_fix":
29
+ return grade_bug_fix_task(task, code, include_hidden=include_hidden, timeout_s=timeout_s)
30
+ if task.task_kind == "optimization":
31
+ return grade_optimization_task(task, code, include_hidden=include_hidden, timeout_s=timeout_s)
32
+ raise ValueError(f"Unsupported task kind: {task.task_kind}")
build/lib/build/lib/graders/optimization.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Optimization task grader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ try:
6
+ from ..models import TaskGrade
7
+ from ..tasks.catalog import ReviewTask
8
+ except ImportError:
9
+ from models import TaskGrade
10
+ from tasks.catalog import ReviewTask
11
+
12
+ from .shared import (
13
+ base_grade,
14
+ benchmark_candidate,
15
+ compile_code,
16
+ component_score,
17
+ execute_cases,
18
+ quality_metrics,
19
+ shaped_score,
20
+ similarity_score,
21
+ summarize_results,
22
+ )
23
+
24
+
25
+ def grade_optimization_task(
26
+ task: ReviewTask,
27
+ code: str,
28
+ *,
29
+ include_hidden: bool,
30
+ timeout_s: float = 3.0,
31
+ ) -> TaskGrade:
32
+ """Grade an optimization/refactor task with correctness, quality, and runtime."""
33
+
34
+ compiled, compile_error = compile_code(code)
35
+ quality = quality_metrics(code, task.function_name)
36
+ details = {
37
+ "compile_error": compile_error,
38
+ "quality_notes": quality["quality_notes"],
39
+ "style_score": quality["style_score"],
40
+ "visibility": "full" if include_hidden else "public",
41
+ }
42
+
43
+ if not compiled:
44
+ progress = 0.02 + 0.1 * similarity_score(code, task.reference_code)
45
+ details["test_results"] = []
46
+ details["test_summary"] = "Code does not compile."
47
+ return base_grade(
48
+ score=shaped_score(progress),
49
+ syntax_score=component_score(0.01),
50
+ tests_passed=0,
51
+ tests_total=len(task.public_cases) + (len(task.hidden_cases) if include_hidden else 0),
52
+ quality_score=component_score(0.01),
53
+ runtime_score=component_score(0.01),
54
+ timed_out=False,
55
+ details=details,
56
+ )
57
+
58
+ cases = task.public_cases + (task.hidden_cases if include_hidden else [])
59
+ result = execute_cases(code, task.function_name, cases, timeout_s=timeout_s)
60
+ if result.get("timed_out"):
61
+ details["test_results"] = []
62
+ details["test_summary"] = result["error"]
63
+ progress = 0.1 + 0.18 * quality["score"]
64
+ return base_grade(
65
+ score=shaped_score(progress),
66
+ syntax_score=component_score(0.95),
67
+ tests_passed=0,
68
+ tests_total=len(cases),
69
+ quality_score=quality["score"],
70
+ runtime_score=component_score(0.01),
71
+ timed_out=True,
72
+ details=details,
73
+ )
74
+ if "error" in result:
75
+ details["test_results"] = []
76
+ details["test_summary"] = result["error"]
77
+ progress = 0.1 + 0.2 * quality["score"]
78
+ return base_grade(
79
+ score=shaped_score(progress),
80
+ syntax_score=component_score(0.95),
81
+ tests_passed=0,
82
+ tests_total=len(cases),
83
+ quality_score=quality["score"],
84
+ runtime_score=component_score(0.01),
85
+ timed_out=False,
86
+ details=details,
87
+ )
88
+
89
+ data = result["data"]
90
+ pass_rate = data["passed"] / max(data["total"], 1)
91
+ runtime_score = component_score(0.01)
92
+ benchmark_summary = "Benchmark deferred until hidden evaluation."
93
+ timed_out = False
94
+
95
+ if include_hidden and pass_rate == 1.0:
96
+ benchmark = benchmark_candidate(task, code, timeout_s=timeout_s)
97
+ runtime_score = benchmark["runtime_score"]
98
+ timed_out = benchmark.get("timed_out", False)
99
+ benchmark_summary = benchmark["details"]
100
+ if timed_out:
101
+ runtime_score = component_score(0.01)
102
+
103
+ details["test_results"] = data["results"]
104
+ details["test_summary"] = summarize_results("Test results", data["results"])
105
+ details["benchmark"] = benchmark_summary
106
+
107
+ runtime_progress = 0.0 if benchmark_summary == "Benchmark deferred until hidden evaluation." else runtime_score
108
+ if include_hidden:
109
+ progress = min(1.0, 0.05 + 0.6 * pass_rate + 0.2 * quality["score"] + 0.15 * runtime_progress)
110
+ else:
111
+ progress = min(1.0, 0.05 + 0.7 * pass_rate + 0.25 * quality["score"])
112
+
113
+ return base_grade(
114
+ score=shaped_score(progress),
115
+ syntax_score=component_score(0.95),
116
+ tests_passed=data["passed"],
117
+ tests_total=data["total"],
118
+ quality_score=quality["score"],
119
+ runtime_score=runtime_score,
120
+ timed_out=timed_out,
121
+ details=details,
122
+ )
build/lib/build/lib/graders/shared.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared deterministic grading helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import difflib
7
+ import math
8
+ import multiprocessing as mp
9
+ import os
10
+ import time
11
+ import traceback
12
+ from typing import Any, Callable, Dict, List
13
+
14
+ try:
15
+ from ..models import TaskGrade
16
+ from ..tasks.catalog import CallCase, ReviewTask
17
+ except ImportError:
18
+ from models import TaskGrade
19
+ from tasks.catalog import CallCase, ReviewTask
20
+
21
+
22
+ STRICT_SCORE_MIN = 0.01
23
+ STRICT_SCORE_MAX = 0.99
24
+ POOR_SCORE = 0.1
25
+ NEAR_PERFECT_SCORE = 0.95
26
+
27
+
28
+ def finite_float(value: Any, fallback: float = STRICT_SCORE_MIN) -> float:
29
+ """Convert a value into a finite float with a deterministic fallback."""
30
+
31
+ try:
32
+ numeric = float(value)
33
+ except (TypeError, ValueError):
34
+ return fallback
35
+ if math.isnan(numeric) or math.isinf(numeric):
36
+ return fallback
37
+ return numeric
38
+
39
+
40
+ def clamp(value: float, lower: float = 0.0, upper: float = 1.0) -> float:
41
+ """Clamp a floating-point value to a closed interval."""
42
+
43
+ numeric = finite_float(value, fallback=lower)
44
+ return max(lower, min(upper, numeric))
45
+
46
+
47
+ def strict_score(value: Any, lower: float = STRICT_SCORE_MIN, upper: float = STRICT_SCORE_MAX) -> float:
48
+ """Clamp a score to the OpenEnv-safe open interval (0, 1)."""
49
+
50
+ score = max(lower, min(upper, finite_float(value, fallback=lower)))
51
+ score = round(score, 3)
52
+ assert 0 < score < 1, f"Invalid score: {score}"
53
+ return score
54
+
55
+
56
+ def shaped_score(progress: Any, floor: float = POOR_SCORE, ceiling: float = NEAR_PERFECT_SCORE) -> float:
57
+ """Map progress in [0, 1] to a shaped score band within (0, 1)."""
58
+
59
+ bounded_progress = clamp(finite_float(progress, fallback=0.0))
60
+ score = floor + (ceiling - floor) * bounded_progress
61
+ score = max(STRICT_SCORE_MIN, min(score, STRICT_SCORE_MAX))
62
+ score = round(score, 3)
63
+ assert 0 < score < 1, f"Invalid score: {score}"
64
+ return score
65
+
66
+
67
+ def score_from_checks(passed: int, total: int, floor: float = POOR_SCORE, ceiling: float = NEAR_PERFECT_SCORE) -> float:
68
+ """Convert discrete checks into a smoothly shaped score."""
69
+
70
+ return shaped_score(safe_ratio(passed, total), floor=floor, ceiling=ceiling)
71
+
72
+
73
+ def safe_ratio(numerator: Any, denominator: Any) -> float:
74
+ """Return a stable ratio in [0, 1] that never raises or produces NaN."""
75
+
76
+ denom = int(finite_float(denominator, fallback=0.0))
77
+ if denom <= 0:
78
+ return 0.0
79
+ numer = finite_float(numerator, fallback=0.0)
80
+ return clamp(numer / denom)
81
+
82
+
83
+ def component_score(value: Any) -> float:
84
+ """Normalize component scores such as syntax, quality, and runtime."""
85
+
86
+ return strict_score(value)
87
+
88
+
89
+ def compile_code(code: str) -> tuple[bool, str]:
90
+ """Return whether code compiles and the syntax error, if any."""
91
+
92
+ try:
93
+ compile(code, "<candidate>", "exec")
94
+ except SyntaxError as exc:
95
+ return False, f"SyntaxError: {exc.msg} (line {exc.lineno}, column {exc.offset})"
96
+ except Exception as exc: # pragma: no cover
97
+ return False, f"{type(exc).__name__}: {exc}"
98
+ return True, ""
99
+
100
+
101
+ def similarity_score(candidate: str, reference: str) -> float:
102
+ """Compute a stable text similarity score in [0, 1]."""
103
+
104
+ return difflib.SequenceMatcher(a=candidate.strip(), b=reference.strip()).ratio()
105
+
106
+
107
+ def _queue_worker(
108
+ worker: Callable[[Dict[str, Any]], Dict[str, Any]],
109
+ payload: Dict[str, Any],
110
+ queue: Any,
111
+ ) -> None:
112
+ try:
113
+ queue.put({"ok": True, "data": worker(payload)})
114
+ except Exception as exc: # pragma: no cover
115
+ queue.put(
116
+ {
117
+ "ok": False,
118
+ "error": f"{type(exc).__name__}: {exc}",
119
+ "traceback": traceback.format_exc(limit=5),
120
+ }
121
+ )
122
+
123
+
124
+ def run_with_timeout(
125
+ worker: Callable[[Dict[str, Any]], Dict[str, Any]],
126
+ payload: Dict[str, Any],
127
+ timeout_s: float,
128
+ ) -> Dict[str, Any]:
129
+ """Execute a worker in a subprocess and terminate on timeout."""
130
+
131
+ ctx = mp.get_context("spawn")
132
+ queue = ctx.Queue()
133
+ process = ctx.Process(target=_queue_worker, args=(worker, payload, queue))
134
+ process.start()
135
+ process.join(timeout_s)
136
+
137
+ if process.is_alive():
138
+ process.terminate()
139
+ process.join()
140
+ return {"timed_out": True, "error": f"Execution exceeded {timeout_s:.1f}s timeout."}
141
+
142
+ if queue.empty():
143
+ return {"timed_out": False, "error": "Worker exited without returning a result."}
144
+
145
+ message = queue.get()
146
+ if not message["ok"]:
147
+ return {
148
+ "timed_out": False,
149
+ "error": f"{message['error']}\n{message['traceback']}",
150
+ }
151
+ return {"timed_out": False, "data": message["data"]}
152
+
153
+
154
+ def run_inline_with_timeout(
155
+ worker: Callable[[Dict[str, Any]], Dict[str, Any]],
156
+ payload: Dict[str, Any],
157
+ timeout_s: float,
158
+ ) -> Dict[str, Any]:
159
+ """Fallback execution path for platforms where spawned workers are unreliable."""
160
+
161
+ started = time.perf_counter()
162
+ try:
163
+ data = worker(payload)
164
+ except Exception as exc:
165
+ return {
166
+ "timed_out": False,
167
+ "error": f"{type(exc).__name__}: {exc}\n{traceback.format_exc(limit=5)}",
168
+ }
169
+
170
+ elapsed = time.perf_counter() - started
171
+ if elapsed > timeout_s:
172
+ return {"timed_out": True, "error": f"Execution exceeded {timeout_s:.1f}s timeout."}
173
+ return {"timed_out": False, "data": data}
174
+
175
+
176
+ def _execute_cases_worker(payload: Dict[str, Any]) -> Dict[str, Any]:
177
+ namespace: Dict[str, Any] = {}
178
+ exec(payload["code"], namespace)
179
+ func = namespace[payload["function_name"]]
180
+ results: List[Dict[str, Any]] = []
181
+
182
+ for case in payload["cases"]:
183
+ try:
184
+ actual = func(*case["args"], **case["kwargs"])
185
+ passed = actual == case["expected"]
186
+ actual_repr = repr(actual)
187
+ except Exception as exc:
188
+ passed = False
189
+ actual_repr = f"{type(exc).__name__}: {exc}"
190
+
191
+ results.append(
192
+ {
193
+ "label": case["label"],
194
+ "passed": passed,
195
+ "expected": repr(case["expected"]),
196
+ "actual": actual_repr,
197
+ }
198
+ )
199
+
200
+ passed_total = sum(1 for item in results if item["passed"])
201
+ return {"passed": passed_total, "total": len(results), "results": results}
202
+
203
+
204
+ def execute_cases(code: str, function_name: str, cases: List[CallCase], timeout_s: float) -> Dict[str, Any]:
205
+ """Run function test cases in a subprocess."""
206
+
207
+ payload = {
208
+ "code": code,
209
+ "function_name": function_name,
210
+ "cases": [
211
+ {"label": case.label, "args": case.args, "kwargs": case.kwargs, "expected": case.expected}
212
+ for case in cases
213
+ ],
214
+ }
215
+ return run_with_timeout(_execute_cases_worker, payload, timeout_s=timeout_s)
216
+
217
+
218
+ class _LoopDepthVisitor(ast.NodeVisitor):
219
+ def __init__(self) -> None:
220
+ self.depth = 0
221
+ self.max_depth = 0
222
+
223
+ def _visit_loop(self, node: ast.AST) -> None:
224
+ self.depth += 1
225
+ self.max_depth = max(self.max_depth, self.depth)
226
+ self.generic_visit(node)
227
+ self.depth -= 1
228
+
229
+ def visit_For(self, node: ast.For) -> None: # noqa: N802
230
+ self._visit_loop(node)
231
+
232
+ def visit_While(self, node: ast.While) -> None: # noqa: N802
233
+ self._visit_loop(node)
234
+
235
+ def visit_comprehension(self, node: ast.comprehension) -> None: # noqa: N802
236
+ self._visit_loop(node)
237
+
238
+
239
+ def quality_metrics(code: str, function_name: str) -> Dict[str, Any]:
240
+ """Compute deterministic AST/style quality metrics."""
241
+
242
+ compiled, error = compile_code(code)
243
+ if not compiled:
244
+ return {
245
+ "score": component_score(STRICT_SCORE_MIN),
246
+ "style_score": component_score(STRICT_SCORE_MIN),
247
+ "quality_notes": [error],
248
+ "max_loop_depth": 99,
249
+ }
250
+
251
+ tree = ast.parse(code)
252
+ function_node = next(
253
+ (
254
+ node
255
+ for node in tree.body
256
+ if isinstance(node, ast.FunctionDef) and node.name == function_name
257
+ ),
258
+ None,
259
+ )
260
+
261
+ notes: List[str] = []
262
+ score = 0.0
263
+
264
+ if function_node is not None:
265
+ score += 0.2
266
+ else:
267
+ notes.append(f"Expected function {function_name!r} is missing.")
268
+
269
+ lines = [line.rstrip("\n") for line in code.splitlines()]
270
+ long_lines = [index + 1 for index, line in enumerate(lines) if len(line) > 88]
271
+ trailing_whitespace = [index + 1 for index, line in enumerate(lines) if line.rstrip() != line]
272
+ uses_tabs = any("\t" in line for line in lines)
273
+
274
+ style_score = 0.0
275
+ if not long_lines:
276
+ score += 0.15
277
+ style_score += 0.5
278
+ else:
279
+ notes.append(f"Lines longer than 88 characters: {long_lines[:3]}")
280
+
281
+ if not trailing_whitespace and not uses_tabs:
282
+ score += 0.15
283
+ style_score += 0.5
284
+ else:
285
+ notes.append("Remove tabs or trailing whitespace for cleaner style.")
286
+
287
+ if function_node is not None:
288
+ if ast.get_docstring(function_node):
289
+ score += 0.1
290
+ else:
291
+ notes.append("Add a short docstring to explain the function contract.")
292
+
293
+ visitor = _LoopDepthVisitor()
294
+ visitor.visit(function_node)
295
+ if visitor.max_depth <= 1:
296
+ score += 0.15
297
+ elif visitor.max_depth == 2:
298
+ score += 0.08
299
+ notes.append("Loop nesting is still higher than necessary.")
300
+ else:
301
+ notes.append("Refactor nested loops to improve readability and runtime.")
302
+
303
+ names = [node.id for node in ast.walk(function_node) if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store)]
304
+ meaningful_names = [name for name in names if len(name) >= 3]
305
+ if names:
306
+ score += 0.1 * (len(meaningful_names) / len(names))
307
+
308
+ function_length = (function_node.end_lineno or function_node.lineno) - function_node.lineno + 1
309
+ if function_length <= 25:
310
+ score += 0.1
311
+ elif function_length <= 40:
312
+ score += 0.05
313
+ notes.append("The function can be shortened or decomposed further.")
314
+ else:
315
+ notes.append("The function is long enough to justify refactoring.")
316
+
317
+ max_loop_depth = visitor.max_depth
318
+ else:
319
+ max_loop_depth = 0
320
+
321
+ source_hints = ("Counter(", "defaultdict(", "set(", "dict(", "sorted(", "sum(", " any(", " all(", " for ")
322
+ if any(hint in code for hint in source_hints):
323
+ score += 0.15
324
+
325
+ return {
326
+ "score": component_score(clamp(score)),
327
+ "style_score": component_score(clamp(style_score)),
328
+ "quality_notes": notes,
329
+ "max_loop_depth": max_loop_depth,
330
+ }
331
+
332
+
333
+ def build_benchmark_events(config: Dict[str, int]) -> List[Dict[str, Any]]:
334
+ """Generate deterministic benchmark data without randomness."""
335
+
336
+ user_pool = config["user_pool"]
337
+ events_per_user = config["events_per_user"]
338
+ events: List[Dict[str, Any]] = []
339
+
340
+ for user_index in range(user_pool):
341
+ user_id = f"user-{user_index:03d}"
342
+ for event_index in range(events_per_user):
343
+ status = "active" if (user_index + event_index) % 3 != 0 else "inactive"
344
+ events.append({"user_id": user_id, "status": status, "minute": event_index})
345
+ if event_index % 6 == 0:
346
+ events.append({"user_id": user_id, "status": status, "minute": event_index})
347
+
348
+ return events
349
+
350
+
351
+ def _benchmark_worker(payload: Dict[str, Any]) -> Dict[str, Any]:
352
+ candidate_ns: Dict[str, Any] = {}
353
+ baseline_ns: Dict[str, Any] = {}
354
+ exec(payload["candidate_code"], candidate_ns)
355
+ exec(payload["baseline_code"], baseline_ns)
356
+
357
+ candidate = candidate_ns[payload["function_name"]]
358
+ baseline = baseline_ns[payload["function_name"]]
359
+ benchmark_events = payload["events"]
360
+ iterations = payload["iterations"]
361
+
362
+ baseline_output = baseline(benchmark_events)
363
+ candidate_output = candidate(benchmark_events)
364
+ if candidate_output != baseline_output:
365
+ raise AssertionError("Candidate output diverges from baseline on benchmark data.")
366
+
367
+ def _timed(fn: Callable[[Any], Any]) -> float:
368
+ start = time.perf_counter()
369
+ for _ in range(iterations):
370
+ fn(benchmark_events)
371
+ return time.perf_counter() - start
372
+
373
+ baseline_seconds = _timed(baseline)
374
+ candidate_seconds = _timed(candidate)
375
+ return {"baseline_seconds": baseline_seconds, "candidate_seconds": candidate_seconds}
376
+
377
+
378
+ def benchmark_candidate(task: ReviewTask, code: str, timeout_s: float) -> Dict[str, Any]:
379
+ """Benchmark a candidate solution against the starter implementation."""
380
+
381
+ if not task.benchmark_config:
382
+ return {"runtime_score": component_score(STRICT_SCORE_MIN), "details": "No benchmark configured."}
383
+
384
+ events = build_benchmark_events(task.benchmark_config)
385
+ payload = {
386
+ "candidate_code": code,
387
+ "baseline_code": task.starter_code,
388
+ "function_name": task.function_name,
389
+ "events": events,
390
+ "iterations": task.benchmark_config.get("iterations", 5),
391
+ }
392
+ if os.name == "nt":
393
+ result = run_inline_with_timeout(_benchmark_worker, payload, timeout_s=timeout_s)
394
+ else:
395
+ result = run_with_timeout(_benchmark_worker, payload, timeout_s=timeout_s)
396
+ if result.get("timed_out"):
397
+ return {"runtime_score": component_score(STRICT_SCORE_MIN), "timed_out": True, "details": result["error"]}
398
+ if "error" in result:
399
+ return {"runtime_score": component_score(STRICT_SCORE_MIN), "timed_out": False, "details": result["error"]}
400
+
401
+ data = result["data"]
402
+ baseline_seconds = float(data["baseline_seconds"])
403
+ candidate_seconds = float(data["candidate_seconds"])
404
+ improvement_ratio = baseline_seconds / max(candidate_seconds, 1e-9)
405
+ runtime_score = component_score(clamp((improvement_ratio - 1.0) / 1.5))
406
+ return {
407
+ "runtime_score": runtime_score,
408
+ "timed_out": False,
409
+ "details": {
410
+ "baseline_seconds": round(baseline_seconds, 6),
411
+ "candidate_seconds": round(candidate_seconds, 6),
412
+ "improvement_ratio": round(improvement_ratio, 3),
413
+ },
414
+ }
415
+
416
+
417
+ def summarize_results(prefix: str, results: List[Dict[str, Any]]) -> str:
418
+ """Render concise test output."""
419
+
420
+ if not results:
421
+ return f"{prefix}: no tests were executed."
422
+
423
+ lines = [prefix]
424
+ for item in results:
425
+ marker = "PASS" if item["passed"] else "FAIL"
426
+ lines.append(f"- {marker} {item['label']}: expected {item['expected']}, got {item['actual']}")
427
+ return "\n".join(lines)
428
+
429
+
430
+ def base_grade(
431
+ *,
432
+ score: float,
433
+ syntax_score: float,
434
+ tests_passed: int,
435
+ tests_total: int,
436
+ quality_score: float,
437
+ runtime_score: float,
438
+ timed_out: bool,
439
+ details: Dict[str, Any],
440
+ ) -> TaskGrade:
441
+ """Create a normalized TaskGrade payload."""
442
+
443
+ safe_score = strict_score(score)
444
+ safe_syntax_score = component_score(syntax_score)
445
+ safe_quality_score = component_score(quality_score)
446
+ safe_runtime_score = component_score(runtime_score)
447
+
448
+ return TaskGrade(
449
+ score=safe_score,
450
+ syntax_score=safe_syntax_score,
451
+ tests_passed=tests_passed,
452
+ tests_total=tests_total,
453
+ quality_score=safe_quality_score,
454
+ runtime_score=safe_runtime_score,
455
+ timed_out=timed_out,
456
+ details=details,
457
+ )
build/lib/build/lib/graders/syntax.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Syntax task grader."""
2
+
3
+ from __future__ import annotations
4
+
5
+ try:
6
+ from ..models import TaskGrade
7
+ from ..tasks.catalog import ReviewTask
8
+ except ImportError:
9
+ from models import TaskGrade
10
+ from tasks.catalog import ReviewTask
11
+
12
+ from .shared import (
13
+ base_grade,
14
+ compile_code,
15
+ component_score,
16
+ execute_cases,
17
+ quality_metrics,
18
+ shaped_score,
19
+ similarity_score,
20
+ summarize_results,
21
+ )
22
+
23
+
24
+ def grade_syntax_task(task: ReviewTask, code: str, timeout_s: float = 2.0) -> TaskGrade:
25
+ """Grade a syntax-fix task deterministically."""
26
+
27
+ compiled, compile_error = compile_code(code)
28
+ quality = quality_metrics(code, task.function_name)
29
+ details = {
30
+ "compile_error": compile_error,
31
+ "quality_notes": quality["quality_notes"],
32
+ "style_score": quality["style_score"],
33
+ }
34
+
35
+ if not compiled:
36
+ progress = 0.05 + 0.2 * similarity_score(code, task.reference_code)
37
+ details["test_results"] = []
38
+ details["test_summary"] = "Code does not compile yet."
39
+ return base_grade(
40
+ score=shaped_score(progress),
41
+ syntax_score=component_score(0.01),
42
+ tests_passed=0,
43
+ tests_total=len(task.public_cases) + len(task.hidden_cases),
44
+ quality_score=component_score(0.01),
45
+ runtime_score=component_score(0.01),
46
+ timed_out=False,
47
+ details=details,
48
+ )
49
+
50
+ cases = task.public_cases + task.hidden_cases
51
+ result = execute_cases(code, task.function_name, cases, timeout_s=timeout_s)
52
+ if result.get("timed_out"):
53
+ details["test_results"] = []
54
+ details["test_summary"] = result["error"]
55
+ progress = 0.2 + 0.25 * quality["score"]
56
+ return base_grade(
57
+ score=shaped_score(progress),
58
+ syntax_score=component_score(0.95),
59
+ tests_passed=0,
60
+ tests_total=len(cases),
61
+ quality_score=quality["score"],
62
+ runtime_score=component_score(0.01),
63
+ timed_out=True,
64
+ details=details,
65
+ )
66
+ if "error" in result:
67
+ details["test_results"] = []
68
+ details["test_summary"] = result["error"]
69
+ progress = 0.18 + 0.2 * quality["score"]
70
+ return base_grade(
71
+ score=shaped_score(progress),
72
+ syntax_score=component_score(0.95),
73
+ tests_passed=0,
74
+ tests_total=len(cases),
75
+ quality_score=quality["score"],
76
+ runtime_score=component_score(0.01),
77
+ timed_out=False,
78
+ details=details,
79
+ )
80
+
81
+ data = result["data"]
82
+ details["test_results"] = data["results"]
83
+ details["test_summary"] = summarize_results("Validation checks", data["results"])
84
+ pass_rate = data["passed"] / max(data["total"], 1)
85
+ progress = min(1.0, 0.15 + 0.75 * pass_rate + 0.1 * quality["score"])
86
+ return base_grade(
87
+ score=shaped_score(progress),
88
+ syntax_score=component_score(0.95),
89
+ tests_passed=data["passed"],
90
+ tests_total=data["total"],
91
+ quality_score=quality["score"],
92
+ runtime_score=component_score(0.01),
93
+ timed_out=False,
94
+ details=details,
95
+ )
build/lib/build/lib/models/__init__.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch-backed model wrappers plus OpenEnv schema exports."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import importlib.util
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .pytorch_model import PyTorchCodeAnalyzerModel
10
+
11
+
12
+ def _load_schema_module():
13
+ schema_path = Path(__file__).resolve().parent.parent / "models.py"
14
+ spec = importlib.util.spec_from_file_location("_python_env_schema_models", schema_path)
15
+ if spec is None or spec.loader is None: # pragma: no cover
16
+ raise ImportError(f"Unable to load schema models from {schema_path}")
17
+ if spec.name in sys.modules:
18
+ return sys.modules[spec.name]
19
+ module = importlib.util.module_from_spec(spec)
20
+ sys.modules[spec.name] = module
21
+ spec.loader.exec_module(module)
22
+ for model_name in (
23
+ "HistoryEntry",
24
+ "RewardDetails",
25
+ "PythonCodeReviewAction",
26
+ "PythonCodeReviewObservation",
27
+ "PythonCodeReviewState",
28
+ "TaskDescriptor",
29
+ "TaskSummary",
30
+ "TaskGrade",
31
+ "HealthResponse",
32
+ ):
33
+ getattr(module, model_name).model_rebuild()
34
+ return module
35
+
36
+
37
+ _schema_models = _load_schema_module()
38
+
39
+ HealthResponse = _schema_models.HealthResponse
40
+ HistoryEntry = _schema_models.HistoryEntry
41
+ PythonAction = _schema_models.PythonAction
42
+ PythonCodeReviewAction = _schema_models.PythonCodeReviewAction
43
+ PythonCodeReviewObservation = _schema_models.PythonCodeReviewObservation
44
+ PythonCodeReviewState = _schema_models.PythonCodeReviewState
45
+ PythonObservation = _schema_models.PythonObservation
46
+ PythonState = _schema_models.PythonState
47
+ RewardDetails = _schema_models.RewardDetails
48
+ TaskDescriptor = _schema_models.TaskDescriptor
49
+ TaskGrade = _schema_models.TaskGrade
50
+ TaskSummary = _schema_models.TaskSummary
51
+
52
+ __all__ = [
53
+ "HealthResponse",
54
+ "HistoryEntry",
55
+ "PyTorchCodeAnalyzerModel",
56
+ "PythonAction",
57
+ "PythonCodeReviewAction",
58
+ "PythonCodeReviewObservation",
59
+ "PythonCodeReviewState",
60
+ "PythonObservation",
61
+ "PythonState",
62
+ "RewardDetails",
63
+ "TaskDescriptor",
64
+ "TaskGrade",
65
+ "TaskSummary",
66
+ ]
build/lib/build/lib/models/pytorch_model.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """PyTorch + transformers model wrapper for multi-domain code scoring."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from typing import Dict, List, Sequence
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+
11
+ try:
12
+ from transformers import AutoModel, AutoTokenizer
13
+ except Exception:
14
+ AutoModel = None # type: ignore[assignment]
15
+ AutoTokenizer = None # type: ignore[assignment]
16
+
17
+
18
+ DOMAIN_PROTOTYPES: Dict[str, List[str]] = {
19
+ "dsa": [
20
+ "Binary search, hashmap optimization, recursion, dynamic programming, arrays, trees, graphs, stack, queue, complexity.",
21
+ "Competitive programming algorithm with loops, memoization, prefix sums, and asymptotic analysis.",
22
+ ],
23
+ "data_science": [
24
+ "Pandas dataframe transformation, numpy vectorization, feature leakage, train test split, iterrows misuse.",
25
+ "Data cleaning pipeline using pandas, numpy, aggregation, joins, and vectorized operations.",
26
+ ],
27
+ "ml_dl": [
28
+ "PyTorch model, training loop, optimizer, backward pass, eval mode, no_grad, loss function, dataloader.",
29
+ "Machine learning inference and training code with torch, sklearn, tensors, gradients, and model checkpoints.",
30
+ ],
31
+ "web": [
32
+ "FastAPI endpoint, request validation, Pydantic models, async routes, API security, backend service design.",
33
+ "REST API backend with routers, dependency injection, input validation, serialization, and error handling.",
34
+ ],
35
+ "general": [
36
+ "General Python utility code with readable structure, typing, tests, and maintainable abstractions.",
37
+ ],
38
+ }
39
+
40
+ QUALITY_ANCHORS: Dict[str, List[str]] = {
41
+ "high": [
42
+ "Readable typed Python code with validation, efficient algorithms, vectorized operations, safe inference, and clean API boundaries.",
43
+ "Production-ready code with small functions, docstrings, low complexity, and clear error handling.",
44
+ ],
45
+ "low": [
46
+ "Brute-force nested loops, missing validation, unsafe input handling, missing eval mode, missing no_grad, and code smells.",
47
+ "Hard to maintain code with high complexity, repeated scans, mutable side effects, and unclear structure.",
48
+ ],
49
+ }
50
+
51
+
52
+ class _HashEmbeddingBackend:
53
+ """Torch-native fallback when pretrained weights cannot be loaded."""
54
+
55
+ def __init__(self, dimensions: int = 128) -> None:
56
+ self.dimensions = dimensions
57
+ self.model_id = "hashed-token-fallback"
58
+ self.backend_name = "hashed-token-fallback"
59
+ self.notes = ["Using hashed embeddings because pretrained transformer weights are unavailable."]
60
+
61
+ def embed_texts(self, texts: Sequence[str]) -> torch.Tensor:
62
+ matrix = torch.zeros((len(texts), self.dimensions), dtype=torch.float32)
63
+ for row_index, text in enumerate(texts):
64
+ tokens = text.lower().split()[:512]
65
+ if not tokens:
66
+ matrix[row_index, 0] = 1.0
67
+ continue
68
+ for token in tokens:
69
+ digest = hashlib.md5(token.encode("utf-8")).hexdigest()
70
+ bucket = int(digest[:8], 16) % self.dimensions
71
+ sign = -1.0 if int(digest[8:10], 16) % 2 else 1.0
72
+ matrix[row_index, bucket] += sign
73
+ return F.normalize(matrix + 1e-6, dim=1)
74
+
75
+
76
+ class PyTorchCodeAnalyzerModel:
77
+ """Score code using pretrained transformer embeddings plus prototype similarity."""
78
+
79
+ def __init__(self, model_id: str = "huggingface/CodeBERTa-small-v1") -> None:
80
+ self.model_id = model_id
81
+ self.backend_name = model_id
82
+ self.notes: List[str] = []
83
+ self._tokenizer = None
84
+ self._model = None
85
+ self._fallback = _HashEmbeddingBackend()
86
+ self._prototype_cache: Dict[str, torch.Tensor] = {}
87
+
88
+ def _ensure_loaded(self) -> None:
89
+ if self._model is not None or self.notes:
90
+ return
91
+ if AutoTokenizer is None or AutoModel is None:
92
+ self.backend_name = self._fallback.backend_name
93
+ self.notes = list(self._fallback.notes)
94
+ return
95
+ try:
96
+ self._tokenizer = AutoTokenizer.from_pretrained(self.model_id)
97
+ self._model = AutoModel.from_pretrained(self.model_id)
98
+ self._model.eval()
99
+ self.notes.append(f"Loaded pretrained encoder `{self.model_id}`.")
100
+ except Exception as exc:
101
+ self.backend_name = self._fallback.backend_name
102
+ self.notes = list(self._fallback.notes) + [f"Pretrained load failed: {type(exc).__name__}: {exc}"]
103
+
104
+ def _embed_texts(self, texts: Sequence[str]) -> torch.Tensor:
105
+ self._ensure_loaded()
106
+ if self._model is None or self._tokenizer is None:
107
+ return self._fallback.embed_texts(texts)
108
+ encoded = self._tokenizer(list(texts), padding=True, truncation=True, max_length=256, return_tensors="pt")
109
+ with torch.no_grad():
110
+ outputs = self._model(**encoded)
111
+ hidden = outputs.last_hidden_state
112
+ mask = encoded["attention_mask"].unsqueeze(-1)
113
+ pooled = (hidden * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1)
114
+ return F.normalize(pooled, dim=1)
115
+
116
+ def _prototype_matrix(self, bucket: str, texts: Sequence[str]) -> torch.Tensor:
117
+ if bucket not in self._prototype_cache:
118
+ self._prototype_cache[bucket] = self._embed_texts(texts)
119
+ return self._prototype_cache[bucket]
120
+
121
+ def predict(self, code: str, context_window: str, static_summary: Dict[str, object]) -> Dict[str, object]:
122
+ """Predict domain probabilities and a model quality score."""
123
+
124
+ document = (
125
+ f"Code:\n{code.strip()[:4000]}\n\n"
126
+ f"Context:\n{context_window.strip()[:1000]}\n\n"
127
+ f"Static hints:\n{static_summary}\n"
128
+ )
129
+ candidate = self._embed_texts([document])
130
+
131
+ domain_scores: Dict[str, float] = {}
132
+ for domain, texts in DOMAIN_PROTOTYPES.items():
133
+ matrix = self._prototype_matrix(f"domain:{domain}", texts)
134
+ similarity = torch.matmul(candidate, matrix.T).max().item()
135
+ domain_scores[domain] = round((similarity + 1.0) / 2.0, 4)
136
+
137
+ high_matrix = self._prototype_matrix("quality:high", QUALITY_ANCHORS["high"])
138
+ low_matrix = self._prototype_matrix("quality:low", QUALITY_ANCHORS["low"])
139
+ high_similarity = torch.matmul(candidate, high_matrix.T).max().item()
140
+ low_similarity = torch.matmul(candidate, low_matrix.T).max().item()
141
+ ml_quality_score = torch.sigmoid(torch.tensor((high_similarity - low_similarity) * 4.0)).item()
142
+
143
+ return {
144
+ "domain_scores": domain_scores,
145
+ "ml_quality_score": round(float(ml_quality_score), 4),
146
+ "backend_name": self.backend_name,
147
+ "model_id": self.model_id,
148
+ "notes": list(self.notes),
149
+ }
build/lib/build/lib/schemas/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Public schemas for the multi-domain analysis platform."""
2
+
3
+ from .request import AnalyzeCodeRequest
4
+ from .response import AnalyzeCodeResponse, AnalysisIssue, DomainAnalysis, ScoreBreakdown, StaticAnalysisSummary
5
+
6
+ __all__ = [
7
+ "AnalyzeCodeRequest",
8
+ "AnalyzeCodeResponse",
9
+ "AnalysisIssue",
10
+ "DomainAnalysis",
11
+ "ScoreBreakdown",
12
+ "StaticAnalysisSummary",
13
+ ]
build/lib/build/lib/schemas/request.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Request schemas for code analysis endpoints and UI."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Literal
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+
10
+ DomainHint = Literal["auto", "dsa", "data_science", "ml_dl", "web"]
11
+
12
+
13
+ class AnalyzeCodeRequest(BaseModel):
14
+ """Validated input payload for multi-domain code analysis."""
15
+
16
+ code: str = Field(..., min_length=1, description="Source code to analyze.")
17
+ context_window: str = Field(default="", max_length=2000, description="Optional repository or task context.")
18
+ traceback_text: str = Field(default="", max_length=2000, description="Optional runtime or test failure output.")
19
+ domain_hint: DomainHint = Field(default="auto", description="Optional domain override when auto detection is not desired.")
build/lib/build/lib/schemas/response.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Response schemas for the multi-domain analysis platform."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Dict, List, Literal
6
+
7
+ from pydantic import BaseModel, Field
8
+
9
+
10
+ DomainType = Literal["dsa", "data_science", "ml_dl", "web", "general"]
11
+ Severity = Literal["low", "medium", "high"]
12
+
13
+
14
+ class AnalysisIssue(BaseModel):
15
+ """One detected issue or risk in the code snippet."""
16
+
17
+ title: str
18
+ severity: Severity
19
+ description: str
20
+ line_hint: int | None = None
21
+
22
+
23
+ class StaticAnalysisSummary(BaseModel):
24
+ """Language-agnostic static-analysis signals."""
25
+
26
+ syntax_valid: bool
27
+ syntax_error: str = ""
28
+ cyclomatic_complexity: int = Field(..., ge=1)
29
+ line_count: int = Field(..., ge=0)
30
+ max_loop_depth: int = Field(..., ge=0)
31
+ time_complexity: str = "Unknown"
32
+ space_complexity: str = "Unknown"
33
+ detected_imports: List[str] = Field(default_factory=list)
34
+ code_smells: List[str] = Field(default_factory=list)
35
+
36
+
37
+ class DomainAnalysis(BaseModel):
38
+ """Domain-specific analysis payload returned by an analyzer."""
39
+
40
+ domain: DomainType
41
+ domain_score: float = Field(..., ge=0.0, le=1.0)
42
+ issues: List[AnalysisIssue] = Field(default_factory=list)
43
+ suggestions: List[str] = Field(default_factory=list)
44
+ highlights: Dict[str, float | str] = Field(default_factory=dict)
45
+
46
+
47
+ class ScoreBreakdown(BaseModel):
48
+ """Reward inputs and final normalized score."""
49
+
50
+ ml_score: float = Field(..., ge=0.0, le=1.0)
51
+ domain_score: float = Field(..., ge=0.0, le=1.0)
52
+ lint_score: float = Field(..., ge=0.0, le=1.0)
53
+ complexity_penalty: float = Field(..., ge=0.0, le=1.0)
54
+ quality_signal: float = Field(..., ge=0.0, le=1.0)
55
+ error_reduction_signal: float = Field(..., ge=0.0, le=1.0)
56
+ completion_signal: float = Field(..., ge=0.0, le=1.0)
57
+ reward: float = Field(..., ge=0.0, le=1.0)
58
+
59
+
60
+ class AnalyzeCodeResponse(BaseModel):
61
+ """Top-level structured output for API and UI consumers."""
62
+
63
+ detected_domain: DomainType
64
+ domain_confidences: Dict[str, float]
65
+ score_breakdown: ScoreBreakdown
66
+ static_analysis: StaticAnalysisSummary
67
+ domain_analysis: DomainAnalysis
68
+ improvement_plan: List[str] = Field(default_factory=list)
69
+ model_backend: str
70
+ model_id: str
71
+ summary: str
72
+ context_window: str = ""
73
+ analysis_time_ms: float = Field(..., ge=0.0)
build/lib/build/lib/server/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """Server exports for python_code_review_env."""
2
+
3
+ from .app import app
4
+ from .env import PythonCodeReviewEnvironment
5
+
6
+ __all__ = ["app", "PythonCodeReviewEnvironment"]
build/lib/build/lib/server/app.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """OpenEnv FastAPI entrypoint with optional Gradio mounting."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+
7
+ from fastapi import FastAPI
8
+
9
+ try:
10
+ from openenv.core.env_server.http_server import create_app
11
+ except Exception as exc: # pragma: no cover
12
+ raise ImportError(
13
+ "openenv-core is required to run the API server. Install project dependencies first."
14
+ ) from exc
15
+
16
+ try:
17
+ import gradio as gr
18
+ except Exception:
19
+ gr = None # type: ignore[assignment]
20
+
21
+ try:
22
+ from ..models import PythonCodeReviewAction, PythonCodeReviewObservation
23
+ from .env import PythonCodeReviewEnvironment
24
+ except ImportError:
25
+ from models import PythonCodeReviewAction, PythonCodeReviewObservation
26
+ from server.env import PythonCodeReviewEnvironment
27
+
28
+
29
+ def _gradio_enabled() -> bool:
30
+ for env_name in ("ENABLE_GRADIO_DEMO", "ENABLE_WEB_INTERFACE"):
31
+ if str(os.getenv(env_name, "")).strip().lower() in {"1", "true", "yes", "on"}:
32
+ return True
33
+ return False
34
+
35
+
36
+ def _max_concurrent_envs() -> int:
37
+ try:
38
+ return max(int(os.getenv("OPENENV_MAX_CONCURRENT_ENVS", "2")), 1)
39
+ except Exception:
40
+ return 2
41
+
42
+
43
+ def build_application():
44
+ """Compose the OpenEnv API with the Gradio demo frontend."""
45
+
46
+ api_app = create_app(
47
+ PythonCodeReviewEnvironment,
48
+ PythonCodeReviewAction,
49
+ PythonCodeReviewObservation,
50
+ env_name="python_code_review_env",
51
+ max_concurrent_envs=_max_concurrent_envs(),
52
+ )
53
+ served_app = api_app
54
+ if gr is not None and _gradio_enabled():
55
+ try:
56
+ from .demo import build_demo
57
+ except ImportError:
58
+ from server.demo import build_demo
59
+ served_app = gr.mount_gradio_app(api_app, build_demo(), path="/")
60
+
61
+ wrapper_app = FastAPI(title="python_code_review_env", version="1.0.0")
62
+
63
+ @wrapper_app.get("/health", include_in_schema=False)
64
+ def _health() -> dict[str, str]:
65
+ return {"status": "ok"}
66
+
67
+ wrapper_app.mount("/", served_app)
68
+ return wrapper_app
69
+
70
+
71
+ app = build_application()
72
+
73
+
74
+ def main(host: str = "0.0.0.0", port: int = 8000) -> None:
75
+ import uvicorn
76
+
77
+ uvicorn.run(app, host=host, port=port)
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()