vinith17 commited on
Commit
4ad1b43
·
1 Parent(s): aea1555

fix: consolidate app.py as FastAPI entry point for HF Space deployment

Browse files

- Replaced old Flask code with simple FastAPI import from main.py
- Ensures HF Space uses working bug detection system (main.py)
- Fixes deployment mismatch between localhost and HF Spaces
- app.py now acts as universal entry point for all deployment targets

Files changed (1) hide show
  1. app.py +7 -297
app.py CHANGED
@@ -1,303 +1,13 @@
1
- import json
2
- import logging
3
- import os
4
- import re
5
- import time
6
- import threading
7
 
8
- from flask import Flask, jsonify, render_template, request
9
- from flask_limiter import Limiter
10
- from flask_limiter.util import get_remote_address
11
 
12
- from config import (
13
- ALLOWED_EXTENSIONS,
14
- MAX_CONTENT_LENGTH_MB,
15
- RATE_LIMIT_AUTO_RUN,
16
- RATE_LIMIT_DEFAULT,
17
- RATE_LIMIT_REVIEW,
18
- RUNS_DIR,
19
- )
20
- from environment import CodeReviewEnv
21
- from agent import review, call_llm
22
- from grader import grade
23
- from training_loop import run_training
24
 
25
- logger = logging.getLogger(__name__)
26
-
27
- app = Flask(__name__)
28
- app.config['MAX_CONTENT_LENGTH'] = MAX_CONTENT_LENGTH_MB * 1024 * 1024
29
-
30
- limiter = Limiter(
31
- get_remote_address,
32
- app=app,
33
- default_limits=[RATE_LIMIT_DEFAULT],
34
- headers_enabled=True, # Adds Retry-After + X-RateLimit-* headers
35
- )
36
-
37
- # Ensure runs directory exists
38
- os.makedirs(RUNS_DIR, exist_ok=True)
39
- HISTORY_FILE = os.path.join(RUNS_DIR, "history.json")
40
-
41
- def allowed_file(filename):
42
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
43
-
44
- # --- Global State ---
45
- STATE = {
46
- "total_reward": 0,
47
- "episode_count": 0,
48
- "current_episode_id": None,
49
- "history": [],
50
- "is_running": False
51
- }
52
-
53
- # Initialize environment
54
- env = CodeReviewEnv("episodes.json", "answers.json")
55
-
56
- # Helper to save history to file
57
- def save_history_file():
58
- stats = {
59
- "total_reward": STATE["total_reward"],
60
- "episodes_run": STATE["episode_count"],
61
- "accuracy": calculate_accuracy(),
62
- "best_score": calculate_best_score()
63
- }
64
- data = {
65
- "overall_stats": stats,
66
- "history": STATE["history"]
67
- }
68
- with open(HISTORY_FILE, "w") as f:
69
- json.dump(data, f, indent=4)
70
-
71
- def calculate_accuracy():
72
- if STATE["episode_count"] == 0: return 0
73
- correct = sum(1 for h in STATE["history"] if h["correct"])
74
- return correct / STATE["episode_count"]
75
-
76
- def calculate_best_score():
77
- if not STATE["history"]: return 0
78
- return max(h["reward"] for h in STATE["history"])
79
-
80
- def find_bug_lines(code, ai_action):
81
- lines = code.splitlines()
82
- highlighted = []
83
- line_hint = ai_action.get("line_hint", "").lower()
84
- category = ai_action.get("category", "ok")
85
-
86
- if ai_action.get("type") != "flag":
87
- return []
88
-
89
- for i, line in enumerate(lines):
90
- line_lower = line.lower().strip()
91
- should_highlight = False
92
-
93
- # Security patterns
94
- if category == "security":
95
- if any(p in line_lower for p in [
96
- "f\"select", "f'select", "query =", "execute(",
97
- "password =", "hashed = password", "= password",
98
- "api_key =", "secret =", "token ="
99
- ]):
100
- should_highlight = True
101
-
102
- # Logic patterns
103
- if category == "logic":
104
- if any(p in line_lower for p in [
105
- "range(len(", "> amount", "< amount",
106
- ">= amount", "if accounts", "return"
107
- ]):
108
- should_highlight = True
109
-
110
- # Match line hint keywords
111
- if line_hint:
112
- hint_words = [w for w in line_hint.split() if len(w) > 3]
113
- if any(word in line_lower for word in hint_words):
114
- should_highlight = True
115
-
116
- if should_highlight:
117
- highlighted.append({
118
- "line_number": i + 1,
119
- "content": line,
120
- "severity": ai_action.get("severity", 3)
121
- })
122
-
123
- return highlighted[:3] # max 3 highlighted lines
124
-
125
- def get_fix_suggestion(code, ai_action):
126
- if ai_action.get("type") != "flag": return None
127
-
128
- comment = ai_action.get('comment', '')
129
- category = ai_action.get('category', '')
130
-
131
- fix_prompt = f"""
132
- You are a senior engineer. A code reviewer found this issue:
133
-
134
- Bug type: {category}
135
- Issue: {comment}
136
- Location: {ai_action.get('line_hint', '')}
137
-
138
- Here is the original buggy code:
139
- {code}
140
-
141
- Provide a fixed version of the code.
142
- Respond with ONLY a JSON object:
143
- {{
144
- "fixed_code": "the complete fixed code here",
145
- "changes": ["list", "of", "what", "changed"],
146
- "explanation": "one sentence explaining the fix"
147
- }}
148
- No markdown, no backticks, just the JSON object.
149
- """
150
-
151
- raw = call_llm(fix_prompt)
152
- if raw:
153
- try:
154
- match = re.search(r'(\{.*\})', raw, re.DOTALL)
155
- if match:
156
- return json.loads(match.group(1))
157
- except:
158
- pass
159
-
160
- # Fallback logic
161
- if category == "security" and "sql" in comment.lower():
162
- return {
163
- "fixed_code": code.replace(
164
- "f\"SELECT * FROM users WHERE username='{username}'\"",
165
- "\"SELECT * FROM users WHERE username=?\""
166
- ),
167
- "changes": ["Replaced f-string with parameterized query",
168
- "Added ? placeholder instead of variable interpolation"],
169
- "explanation": "Parameterized queries prevent SQL injection by separating code from data."
170
- }
171
-
172
- if category == "security" and "password" in comment.lower():
173
- return {
174
- "fixed_code": code.replace(
175
- "hashed = password",
176
- "import hashlib\n hashed = hashlib.sha256(password.encode()).hexdigest()"
177
- ),
178
- "changes": ["Added hashlib import",
179
- "Applied SHA-256 hashing before storing password"],
180
- "explanation": "Always hash passwords with a cryptographic function before storage."
181
- }
182
-
183
- if category == "logic" and "range(len(" in code:
184
- return {
185
- "fixed_code": code.replace("range(len(numbers) - 1)",
186
- "range(len(numbers))"),
187
- "changes": ["Fixed loop range to include last element"],
188
- "explanation": "range(len(x)) iterates all items; range(len(x)-1) skips the last one."
189
- }
190
-
191
- return None
192
-
193
- # --- Routes ---
194
-
195
- @app.route("/")
196
- def index():
197
- return render_template("index.html")
198
-
199
- @app.route("/api/next-episode", methods=["GET"])
200
- def next_episode():
201
- # Reset env to get a new snippet
202
- obs = env.reset()
203
- STATE["current_episode_id"] = obs["episode_id"]
204
- return jsonify({
205
- "episode_id": obs["episode_id"],
206
- "snippet_id": obs["snippet_id"],
207
- "code": obs["code"],
208
- "episode_count": STATE["episode_count"]
209
- })
210
-
211
- @app.route("/api/review", methods=["POST"])
212
- @limiter.limit(RATE_LIMIT_REVIEW)
213
- def perform_review():
214
- data = request.json
215
- code = data.get("code")
216
- episode_id = data.get("episode_id")
217
- snippet_id = data.get("snippet_id")
218
-
219
- # 1. Get AI Review
220
- ai_action = review(code)
221
-
222
- # 2. Get Ground Truth
223
- ground_truth = env._get_answer(episode_id)
224
-
225
- # 3. Grade the review
226
- res = grade(ai_action, ground_truth)
227
- reward = res.reward
228
-
229
- # 4. Update state
230
- STATE["total_reward"] += reward
231
- STATE["episode_count"] += 1
232
-
233
- record = {
234
- "episode_id": episode_id,
235
- "snippet_id": snippet_id,
236
- "ai_said": f"{ai_action.get('type')} / {ai_action.get('category')}",
237
- "reward": reward,
238
- "correct": res.correct,
239
- "breakdown": res.breakdown,
240
- "bug_type": res.bug_type
241
- }
242
- STATE["history"].append(record)
243
- save_history_file()
244
-
245
- return jsonify({
246
- "ai_action": ai_action,
247
- "reward": reward,
248
- "correct": res.correct,
249
- "breakdown": res.breakdown,
250
- "total_reward": STATE["total_reward"],
251
- "episode_count": STATE["episode_count"],
252
- "highlighted_lines": find_bug_lines(code, ai_action),
253
- "fix": get_fix_suggestion(code, ai_action)
254
- })
255
-
256
- @app.route("/api/history", methods=["GET"])
257
- def get_history():
258
- # If history is empty in state, try reading from file
259
- if not STATE["history"] and os.path.exists(HISTORY_FILE):
260
- try:
261
- with open(HISTORY_FILE) as f:
262
- data = json.load(f)
263
- STATE["history"] = data["history"]
264
- STATE["total_reward"] = data["overall_stats"]["total_reward"]
265
- STATE["episode_count"] = data["overall_stats"]["episodes_run"]
266
- except Exception as exc:
267
- logger.warning("Could not read history file: %s", exc)
268
-
269
- return jsonify({
270
- "history": STATE["history"],
271
- "total_reward": STATE["total_reward"],
272
- "episodes_run": STATE["episode_count"],
273
- "accuracy": calculate_accuracy(),
274
- "best_score": calculate_best_score()
275
- })
276
-
277
- @app.route("/api/train", methods=["POST"])
278
- @limiter.limit(RATE_LIMIT_AUTO_RUN)
279
- def train():
280
- episodes = request.json.get("episodes", 10)
281
-
282
- # run synchronously to match frontend assumptions
283
- try:
284
- output_data = run_training(num_episodes=episodes, verbose=False, resume=True)
285
- stats = output_data["overall_stats"]
286
- return jsonify(stats)
287
- except Exception as e:
288
- return jsonify({"error": str(e)}), 500
289
-
290
- @app.route("/api/health", methods=["GET"])
291
- def health():
292
- return jsonify({
293
- "status": "healthy",
294
- "has_anthropic": bool(os.environ.get("ANTHROPIC_API_KEY")),
295
- "has_openai": bool(os.environ.get("OPENAI_API_KEY"))
296
- })
297
-
298
- @app.route("/api/upload", methods=["POST"])
299
- @limiter.limit(RATE_LIMIT_REVIEW)
300
- def upload_file():
301
  if 'file' not in request.files:
302
  return jsonify({"error": "No file provided"}), 400
303
  file = request.files['file']
 
1
+ """
2
+ FastAPI entry point for Hugging Face Spaces and production deployment.
3
+ This file simply imports the main FastAPI application to ensure
4
+ consistent behavior across localhost and HF Spaces deployments.
5
+ """
 
6
 
7
+ from main import app
 
 
8
 
9
+ __all__ = ["app"]
 
 
 
 
 
 
 
 
 
 
 
10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  if 'file' not in request.files:
12
  return jsonify({"error": "No file provided"}), 400
13
  file = request.files['file']