DhyandevP commited on
Commit
a8e68ee
·
1 Parent(s): bebe643

style: polish code and documentation with natural human developer style

Browse files
Files changed (2) hide show
  1. README.md +24 -36
  2. main.py +38 -40
README.md CHANGED
@@ -8,48 +8,36 @@ pinned: false
8
  license: mit
9
  ---
10
 
11
- # Code Evaluator
12
 
13
- A minimal, high-speed code evaluation service for Hugging Face Spaces. It validates code submissions (pasted text, single files, or `.zip` archives) against specified question objectives using any major AI provider, returning a code score (0–100) and a concise, natural, human-written feedback paragraph.
14
 
15
- ## Supported Providers & Auto-Detection
 
16
 
17
- The application automatically identifies your provider by its API key format or environment variable:
 
 
 
 
18
 
19
- | Provider | Key Format / Secret | Auto-Configured Endpoint | Default Model |
20
- |---|---|---|---|
21
- | **Google Gemini** | `AIza...` or `GEMINI_API_KEY` | `https://generativelanguage.googleapis.com/v1beta/openai/` | `gemini-2.0-flash` |
22
- | **OpenAI** | `sk-...` or `OPENAI_API_KEY` | `https://api.openai.com/v1` | `gpt-4o-mini` |
23
- | **Groq** | `gsk_...` or `GROQ_API_KEY` | `https://api.groq.com/openai/v1` | `llama-3.3-70b-versatile` |
24
- | **OpenRouter** | `sk-or-...` or `OPENROUTER_API_KEY` | `https://openrouter.ai/api/v1` | `meta-llama/llama-3.3-70b-instruct` |
25
- | **Any Custom API** | Any key + custom `Base URL` | DeepSeek, Mistral, Ollama, Together, etc. | Custom |
26
 
27
- ## Hugging Face Spaces Configuration
 
 
 
 
28
 
29
- Add any of the following in your Space Settings (**Settings** → **Variables and secrets**):
30
 
31
- - `OPENAI_API_KEY` (or `GEMINI_API_KEY` / `GROQ_API_KEY`)
32
- - *(Optional)* `OPENAI_BASE_URL` (if targeting a custom gateway or local model)
33
- - *(Optional)* `OPENAI_MODEL` (if overriding the default model)
34
 
35
- *Note: You can also specify or override the API key, Base URL, and Model directly in the web UI.*
36
-
37
- ## API Usage
38
-
39
- ### `POST /evaluate`
40
- Accepts `multipart/form-data`:
41
- - `question` (string, required): The problem statement, question, or rubric.
42
- - `code` (string, optional): Raw source code string.
43
- - `file` (file, optional): Single source code file or a `.zip` project archive.
44
- - `api_key` (string, optional): Override API key.
45
- - `base_url` (string, optional): Override base URL.
46
- - `model` (string, optional): Override model ID.
47
-
48
- **Response**:
49
- ```json
50
- {
51
- "score": 90,
52
- "feedback": "Your solution handles the core logic cleanly and the two-pointer approach keeps time complexity to O(n). However, it trips up on boundary cases with empty inputs. Handling that will make this rock solid.",
53
- "model": "gemini-2.0-flash"
54
- }
55
  ```
 
 
 
8
  license: mit
9
  ---
10
 
11
+ # Code Evaluator ⚡
12
 
13
+ A clean, fast tool to automatically grade code submissions against problem descriptions or interview questions. Runs on Hugging Face Spaces and works out of the box with Google Gemini, OpenAI, Groq, or local models.
14
 
15
+ ## Why this exists
16
+ Most automated grading tools are either bloated with complex database queues or spit out robotic, unhelpful essay reviews. This app keeps it simple: upload or paste the code, get an honest score (0–100) and a single, well-written paragraph explaining what worked and what broke.
17
 
18
+ ## Features
19
+ - **No Background Queues**: Evaluates synchronously in 2–5 seconds. No stuck jobs or database files.
20
+ - **Multi-Provider Support**: Auto-detects Google Gemini (`AIza...`), Groq (`gsk_...`), OpenRouter, and OpenAI.
21
+ - **Flexible Inputs**: Paste a snippet directly, upload a single file, or drop an entire `.zip` project.
22
+ - **Human-Style Reviews**: Written like feedback from a senior engineer reviewing your pull request.
23
 
24
+ ## How to Deploy on Hugging Face
 
 
 
 
 
 
25
 
26
+ 1. Fork or push this repo to your Space (`sdk: docker`).
27
+ 2. Go to **Settings** → **Variables and secrets**.
28
+ 3. Add a secret with your API key:
29
+ - `OPENAI_API_KEY` (OpenAI, Groq, etc.) or `GEMINI_API_KEY` (Google AI Studio).
30
+ 4. *(Optional)* Add a variable `OPENAI_MODEL` if you want to lock in a specific model (e.g. `gemini-2.0-flash` or `gpt-4o-mini`).
31
 
32
+ You can also change providers and models directly in the web UI at any time.
33
 
34
+ ## Local Setup
 
 
35
 
36
+ ```bash
37
+ git clone https://github.com/dhyandevp/Code-Evaluator.git
38
+ cd Code-Evaluator
39
+ pip install -r requirements.txt
40
+ uvicorn main:app --port 7860 --reload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  ```
42
+
43
+ Then open `http://localhost:7860`.
main.py CHANGED
@@ -1,8 +1,9 @@
 
1
  import json
2
  import logging
3
  import os
4
  import zipfile
5
- import io
6
  from fastapi import FastAPI, File, Form, HTTPException, UploadFile
7
  from fastapi.middleware.cors import CORSMiddleware
8
  from fastapi.responses import FileResponse, JSONResponse
@@ -11,7 +12,7 @@ from openai import AsyncOpenAI
11
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
12
  logger = logging.getLogger("evaluator")
13
 
14
- app = FastAPI(title="Code Evaluator", version="5.0.0")
15
 
16
  app.add_middleware(
17
  CORSMiddleware,
@@ -20,9 +21,13 @@ app.add_middleware(
20
  allow_headers=["*"],
21
  )
22
 
23
- # ponytail: Auto-detects Google Gemini, Groq, OpenRouter from key prefixes; upgrade path: explicit provider registry if non-standard keys emerge.
 
 
 
 
24
  def resolve_provider(api_key: str = "", base_url: str = "", model: str = "") -> tuple[str, str, str]:
25
- """Auto-detect provider endpoints and default models from API key signatures."""
26
  key = (
27
  api_key.strip()
28
  or os.getenv("OPENAI_API_KEY")
@@ -35,50 +40,47 @@ def resolve_provider(api_key: str = "", base_url: str = "", model: str = "") ->
35
  url = base_url.strip() or os.getenv("OPENAI_BASE_URL", "").strip()
36
  mod = model.strip() or os.getenv("OPENAI_MODEL", "").strip()
37
 
38
- # Google Gemini (AIza...) -> official OpenAI-compatible gateway
39
  if key.startswith("AIza") or os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY"):
40
  url = url or "https://generativelanguage.googleapis.com/v1beta/openai/"
41
  mod = mod or "gemini-2.0-flash"
42
 
43
- # Groq (gsk_...)
44
  elif key.startswith("gsk_") or os.getenv("GROQ_API_KEY"):
45
  url = url or "https://api.groq.com/openai/v1"
46
  mod = mod or "llama-3.3-70b-versatile"
47
 
48
- # OpenRouter (sk-or-...)
49
  elif key.startswith("sk-or-") or os.getenv("OPENROUTER_API_KEY"):
50
  url = url or "https://openrouter.ai/api/v1"
51
  mod = mod or "meta-llama/llama-3.3-70b-instruct"
52
 
53
- # Default fallback: standard OpenAI
54
  url = url or "https://api.openai.com/v1"
55
  mod = mod or "gpt-4o-mini"
56
 
57
  return key, url, mod
58
 
59
- SYSTEM_PROMPT = """You are an experienced senior software engineer conducting a direct code review.
 
60
  Evaluate the code against the provided problem statement or question.
61
 
62
  Review guidelines:
63
- - Write exactly like a thoughtful human mentor or senior peer reviewing a pull request.
64
- - Address the author naturally (e.g., "Your solution handles...", "You implemented...").
65
- - Never use robotic AI clichés like "The submitted code demonstrates", "In conclusion", "Overall, the code...", or "It is worth mentioning".
66
- - Be concise, direct, and technically honest with zero fluff: highlight what works, call out specific bugs, unhandled edge cases, or complexity issues, and justify the score.
67
- - Keep your entire feedback to a single, well-written, correctly aligned paragraph.
68
 
69
- You must respond strictly with a valid JSON object:
70
  {
71
  "score": <integer from 0 to 100>,
72
- "feedback": "<Single natural, human-written paragraph giving constructive, direct feedback and score rationale.>"
73
  }"""
74
 
75
- SKIP_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", ".idea", ".vscode", "dist", "build"}
76
- BINARY_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".exe", ".bin", ".pyc", ".pdf", ".zip", ".tar", ".gz"}
77
 
78
-
79
- # ponytail: In-memory zip extraction with 10MB ceiling; upgrade path: stream to tempfile if archives exceed memory limits.
80
  def extract_code_from_upload(raw_bytes: bytes, filename: str) -> str:
81
- """Extract readable source code from uploaded raw file or zip archive."""
82
  if filename.lower().endswith(".zip"):
83
  try:
84
  with zipfile.ZipFile(io.BytesIO(raw_bytes)) as zf:
@@ -87,19 +89,19 @@ def extract_code_from_upload(raw_bytes: bytes, filename: str) -> str:
87
  if info.is_dir():
88
  continue
89
  parts = info.filename.replace("\\", "/").split("/")
90
- if any(part in SKIP_DIRS or part.startswith(".") for part in parts):
91
  continue
92
  ext = os.path.splitext(info.filename)[1].lower()
93
- if ext in BINARY_EXTS:
94
  continue
95
  content = zf.read(info)
96
- if b"\x00" in content[:1024]: # Skip binary
97
  continue
98
  text = content.decode("utf-8", errors="replace")
99
  snippets.append(f"--- File: {info.filename} ---\n{text}")
100
  return "\n\n".join(snippets)
101
  except zipfile.BadZipFile:
102
- raise HTTPException(status_code=400, detail="Invalid zip archive.")
103
  return raw_bytes.decode("utf-8", errors="replace")
104
 
105
 
@@ -115,17 +117,15 @@ def index():
115
  return JSONResponse({"status": "running", "service": "Code Evaluator"})
116
 
117
 
118
- # ponytail: Synchronous request-response evaluation without job queue; upgrade path: add background worker if LLM latency exceeds client timeout.
119
  @app.post("/evaluate")
120
  async def evaluate_code(
121
- question: str = Form(..., description="Question or task objective"),
122
- code: str = Form("", description="Raw source code text"),
123
- file: UploadFile | None = File(None, description="Optional single code file or .zip archive"),
124
- api_key: str = Form("", description="Optional OpenAI-compatible API key override"),
125
- base_url: str = Form("", description="Optional OpenAI-compatible base URL override"),
126
- model: str = Form("", description="Optional model ID override"),
127
  ) -> dict:
128
- # Resolve code submission
129
  code_text = code.strip()
130
  if file and file.filename:
131
  raw_bytes = await file.read()
@@ -133,18 +133,16 @@ async def evaluate_code(
133
  code_text = f"{code_text}\n\n{extracted}".strip() if code_text else extracted
134
 
135
  if not code_text:
136
- raise HTTPException(status_code=400, detail="No code submitted. Provide code text or upload a file/zip.")
137
 
138
- # Resolve AI client credentials (auto-detects Google, Groq, OpenRouter, OpenAI, etc.)
139
  active_key, active_base_url, active_model = resolve_provider(api_key, base_url, model)
140
  if not active_key:
141
  raise HTTPException(
142
  status_code=400,
143
- detail="API key missing. Set OPENAI_API_KEY, GEMINI_API_KEY, or GROQ_API_KEY in Hugging Face secrets, or supply it in the request.",
144
  )
145
 
146
  client = AsyncOpenAI(api_key=active_key, base_url=active_base_url)
147
-
148
  user_prompt = f"<QUESTION_OBJECTIVE>\n{question}\n</QUESTION_OBJECTIVE>\n\n<CODE_SUBMISSION>\n{code_text}\n</CODE_SUBMISSION>"
149
 
150
  try:
@@ -165,8 +163,8 @@ async def evaluate_code(
165
  "model": active_model,
166
  }
167
  except json.JSONDecodeError:
168
- logger.exception("Failed to parse LLM JSON response.")
169
- raise HTTPException(status_code=502, detail="Evaluation engine returned invalid JSON.")
170
  except Exception as exc:
171
- logger.exception("LLM evaluation error: %s", exc)
172
  raise HTTPException(status_code=500, detail=f"Evaluation failed: {str(exc)}")
 
1
+ import io
2
  import json
3
  import logging
4
  import os
5
  import zipfile
6
+
7
  from fastapi import FastAPI, File, Form, HTTPException, UploadFile
8
  from fastapi.middleware.cors import CORSMiddleware
9
  from fastapi.responses import FileResponse, JSONResponse
 
12
  logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s: %(message)s")
13
  logger = logging.getLogger("evaluator")
14
 
15
+ app = FastAPI(title="Code Evaluator")
16
 
17
  app.add_middleware(
18
  CORSMiddleware,
 
21
  allow_headers=["*"],
22
  )
23
 
24
+ # Directories and extensions we don't want to parse from zip files
25
+ IGNORE_DIRS = {".git", "node_modules", "__pycache__", ".venv", "venv", ".idea", ".vscode", "dist", "build"}
26
+ IGNORE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".exe", ".bin", ".pyc", ".pdf", ".zip", ".tar", ".gz"}
27
+
28
+
29
  def resolve_provider(api_key: str = "", base_url: str = "", model: str = "") -> tuple[str, str, str]:
30
+ """Figure out which provider the user wants based on key prefix or env vars."""
31
  key = (
32
  api_key.strip()
33
  or os.getenv("OPENAI_API_KEY")
 
40
  url = base_url.strip() or os.getenv("OPENAI_BASE_URL", "").strip()
41
  mod = model.strip() or os.getenv("OPENAI_MODEL", "").strip()
42
 
43
+ # Google Gemini keys start with 'AIza'
44
  if key.startswith("AIza") or os.getenv("GEMINI_API_KEY") or os.getenv("GOOGLE_API_KEY"):
45
  url = url or "https://generativelanguage.googleapis.com/v1beta/openai/"
46
  mod = mod or "gemini-2.0-flash"
47
 
48
+ # Groq keys start with 'gsk_'
49
  elif key.startswith("gsk_") or os.getenv("GROQ_API_KEY"):
50
  url = url or "https://api.groq.com/openai/v1"
51
  mod = mod or "llama-3.3-70b-versatile"
52
 
53
+ # OpenRouter keys start with 'sk-or-'
54
  elif key.startswith("sk-or-") or os.getenv("OPENROUTER_API_KEY"):
55
  url = url or "https://openrouter.ai/api/v1"
56
  mod = mod or "meta-llama/llama-3.3-70b-instruct"
57
 
58
+ # Default to standard OpenAI
59
  url = url or "https://api.openai.com/v1"
60
  mod = mod or "gpt-4o-mini"
61
 
62
  return key, url, mod
63
 
64
+
65
+ SYSTEM_PROMPT = """You are an experienced senior software engineer reviewing a developer's code submission.
66
  Evaluate the code against the provided problem statement or question.
67
 
68
  Review guidelines:
69
+ - Write in a natural, direct, constructive human voice (like a mentor reviewing a pull request).
70
+ - Address the author directly ("Your solution handles...", "You implemented...").
71
+ - Do NOT use generic AI filler like "The submitted code demonstrates", "In conclusion", or "Overall, the code...".
72
+ - Be specific and honest: highlight what works well, call out any bugs or missed edge cases, and explain why points were deducted.
73
+ - Keep your feedback strictly to a single, well-written, correctly aligned paragraph.
74
 
75
+ Respond with a JSON object:
76
  {
77
  "score": <integer from 0 to 100>,
78
+ "feedback": "<Single natural, human-written paragraph giving constructive feedback and score reasoning.>"
79
  }"""
80
 
 
 
81
 
 
 
82
  def extract_code_from_upload(raw_bytes: bytes, filename: str) -> str:
83
+ """Read uploaded text or unpack source files from a zip archive."""
84
  if filename.lower().endswith(".zip"):
85
  try:
86
  with zipfile.ZipFile(io.BytesIO(raw_bytes)) as zf:
 
89
  if info.is_dir():
90
  continue
91
  parts = info.filename.replace("\\", "/").split("/")
92
+ if any(part in IGNORE_DIRS or part.startswith(".") for part in parts):
93
  continue
94
  ext = os.path.splitext(info.filename)[1].lower()
95
+ if ext in IGNORE_EXTS:
96
  continue
97
  content = zf.read(info)
98
+ if b"\x00" in content[:1024]: # Skip binary files
99
  continue
100
  text = content.decode("utf-8", errors="replace")
101
  snippets.append(f"--- File: {info.filename} ---\n{text}")
102
  return "\n\n".join(snippets)
103
  except zipfile.BadZipFile:
104
+ raise HTTPException(status_code=400, detail="Invalid or corrupt zip archive.")
105
  return raw_bytes.decode("utf-8", errors="replace")
106
 
107
 
 
117
  return JSONResponse({"status": "running", "service": "Code Evaluator"})
118
 
119
 
 
120
  @app.post("/evaluate")
121
  async def evaluate_code(
122
+ question: str = Form(...),
123
+ code: str = Form(""),
124
+ file: UploadFile | None = File(None),
125
+ api_key: str = Form(""),
126
+ base_url: str = Form(""),
127
+ model: str = Form(""),
128
  ) -> dict:
 
129
  code_text = code.strip()
130
  if file and file.filename:
131
  raw_bytes = await file.read()
 
133
  code_text = f"{code_text}\n\n{extracted}".strip() if code_text else extracted
134
 
135
  if not code_text:
136
+ raise HTTPException(status_code=400, detail="Please provide code text or upload a file/zip.")
137
 
 
138
  active_key, active_base_url, active_model = resolve_provider(api_key, base_url, model)
139
  if not active_key:
140
  raise HTTPException(
141
  status_code=400,
142
+ detail="Missing API key. Set OPENAI_API_KEY, GEMINI_API_KEY, or GROQ_API_KEY in Hugging Face secrets, or enter one in the UI.",
143
  )
144
 
145
  client = AsyncOpenAI(api_key=active_key, base_url=active_base_url)
 
146
  user_prompt = f"<QUESTION_OBJECTIVE>\n{question}\n</QUESTION_OBJECTIVE>\n\n<CODE_SUBMISSION>\n{code_text}\n</CODE_SUBMISSION>"
147
 
148
  try:
 
163
  "model": active_model,
164
  }
165
  except json.JSONDecodeError:
166
+ logger.exception("Could not parse LLM JSON response.")
167
+ raise HTTPException(status_code=502, detail="LLM returned an invalid JSON response.")
168
  except Exception as exc:
169
+ logger.exception("Evaluation failed: %s", exc)
170
  raise HTTPException(status_code=500, detail=f"Evaluation failed: {str(exc)}")