Spaces:
Sleeping
Sleeping
File size: 14,132 Bytes
b56a66f 994ab92 b56a66f 9b316e7 b56a66f 0719b05 6725fae b56a66f 994ab92 b56a66f 6725fae b56a66f 1a7ffc2 6725fae 48a1565 6725fae b56a66f 6725fae 0933659 6725fae 0933659 6725fae 0933659 6725fae 0933659 b56a66f 6725fae 0933659 6725fae ef1b65e b56a66f 0933659 6725fae b56a66f 6725fae b56a66f 0933659 48a1565 b56a66f 9b316e7 b56a66f 0cb027a 256d72e 0aa4931 0cb027a b56a66f 11047e7 9b316e7 11047e7 b56a66f 0933659 256d72e 0d101df b56a66f 0efc7c3 b56a66f 6725fae 631ed42 a8110f6 0d101df b56a66f 0efc7c3 b56a66f 0efc7c3 b56a66f 6725fae 1a7ffc2 0d101df 1a7ffc2 b56a66f 6725fae 0efc7c3 1a7ffc2 0933659 0cb027a b0b1b30 0cb027a b56a66f 0cb027a b56a66f 1a7ffc2 0efc7c3 b56a66f 3884d28 9b316e7 b56a66f e04680b 9b316e7 0d101df b0b1b30 9b316e7 ad817dd 3884d28 ad817dd 8f7d9f3 ad817dd 9b316e7 b0b1b30 994ab92 3884d28 994ab92 3884d28 b0b1b30 3884d28 994ab92 3884d28 b0b1b30 994ab92 b30308e 3884d28 994ab92 e04680b 994ab92 3884d28 994ab92 ec69b2c 994ab92 b0b1b30 994ab92 b0b1b30 3884d28 994ab92 3884d28 994ab92 b0b1b30 994ab92 b0b1b30 994ab92 3884d28 994ab92 3884d28 994ab92 3884d28 994ab92 3884d28 994ab92 b0b1b30 994ab92 b30308e b0b1b30 7377087 b0b1b30 0d101df 9b316e7 994ab92 9b316e7 3884d28 9b316e7 0d101df b56a66f b0b1b30 9b316e7 1a7ffc2 994ab92 b56a66f 0933659 6725fae 0d101df 994ab92 6725fae b56a66f 6725fae 48a1565 6725fae b56a66f 9b316e7 0933659 6725fae 0933659 9b316e7 b56a66f 6725fae 9b316e7 b56a66f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 | """
HuggingFace Space - Python Bug Fixer API
FAST API backend for fine-tuned Phi-2
FIXED VERSION: Better parsing of model output format
"""
import ast
import re
from contextlib import nullcontext
from typing import Optional, List, Dict
import torch
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field, ConfigDict
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import PeftModel
import uvicorn
app = FastAPI(
title="Python Bug Fixer API",
description="AI-powered Python bug detection and fixing",
version="2.3.0" # Updated version
)
# Enable CORS for VS Code extension
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Global variables for models
base_model = None
finetuned_model = None
tokenizer = None
device = None
try:
device = "cuda" if torch.cuda.is_available() else "cpu"
print(f"Using device: {device}")
# tokenizer
print("Load tokenizer")
tokenizer = AutoTokenizer.from_pretrained(
"microsoft/phi-2",
trust_remote_code=True
)
tokenizer.pad_token = tokenizer.eos_token
print("Tokenizer loaded!")
# load one base model (will be shared)
print("Loading Phi-2 base model (fp16)")
base_model = AutoModelForCausalLM.from_pretrained(
"microsoft/phi-2",
trust_remote_code=True,
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
device_map="auto" if device == "cuda" else None,
)
base_model.eval()
print("Base model loaded!")
# load PEFT adapter on top of base model
print("Load fine-tuned PEFT adapter")
finetuned_model = PeftModel.from_pretrained(
base_model,
"ashkanhsn/phi2-python-bugfixer"
)
finetuned_model.eval()
print("Fine-tuned model ready!")
print("Both models are ready!")
except Exception as e:
print(f"Error loading models: {e}")
import traceback
traceback.print_exc()
raise
class CodeRequest(BaseModel):
model_config = ConfigDict(populate_by_name=True)
code: str
task: str = 'fix'
temperature: Optional[float] = None
# Accept both snake_case and camelCase from clients
use_base_model: bool = Field(False, alias='useBaseModel')
class CodeResponse(BaseModel):
text: str
detectedBugs: list[str]
fixedCode: Optional[str] = None
explanation: Optional[str] = None
whyFix: Optional[str] = None
tests: Optional[str] = None
error: Optional[str] = None
def generate_response(code: str, task: str, use_base_model: bool = False, temperature_override: Optional[float] = None) -> str:
# Build prompt based on task
if task == "fix":
prompt = f"""### instruction:
Fix the following buggy Python code:
{code}
### output:
"""
temp = temperature_override if temperature_override is not None else 0.2
max_tokens = 300
do_sample = temp > 0.0
elif task == "analyze":
prompt = f"""### instruction:
Fix this buggy Python code.
{code}
Provide:
1. Bug explanation
2. Fixed code
3. Why the fix works
### output:
"""
temp = temperature_override if temperature_override is not None else 0.7
max_tokens = 1024
do_sample = True
elif task == "chat":
prompt = f"""### instruction:
{code}
### output:
"""
temp = temperature_override if temperature_override is not None else 0.2
max_tokens = 200
do_sample = True
else:
return generate_response(code, "fix", use_base_model, temperature_override)
# use ONE model object (PEFT) and toggle adapter off for base inference
model_name = 'BASE' if use_base_model else 'FINE-TUNED'
print(f'Using {model_name} model')
inputs = tokenizer(prompt, return_tensors='pt')
inputs = {k: v.to(finetuned_model.device) for k, v in inputs.items()}
# generate response
ctx = finetuned_model.disable_adapter() if use_base_model else nullcontext()
with torch.no_grad():
with ctx:
if do_sample:
outputs = finetuned_model.generate(
**inputs,
max_new_tokens=max_tokens,
temperature=temp,
do_sample=True,
top_p=0.95,
pad_token_id=tokenizer.eos_token_id,
eos_token_id=tokenizer.eos_token_id
)
else:
outputs = finetuned_model.generate(
**inputs,
max_new_tokens=max_tokens,
do_sample=False,
pad_token_id=tokenizer.eos_token_id,
eos_token_id=tokenizer.eos_token_id
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
if "### output:" in response:
response = response.split("### output:")[-1].strip()
return response
# Regex pattern used in "fix" task to split code from tests
TOPLEVEL_TEST_RE = re.compile(r"(?m)^(assert\s+|print\()")
def longest_valid_python_prefix(code: str) -> str:
"""Keep the longest prefix that parses as Python (prevents explanation text leaking into code)."""
lines = code.splitlines()
best = ""
buf = []
for line in lines:
buf.append(line)
candidate = "\n".join(buf).strip() + "\n"
try:
ast.parse(candidate)
best = "\n".join(buf)
except SyntaxError:
pass
return best.strip() if best.strip() else code.strip()
def parse_response(text: str, task: str) -> CodeResponse:
"""Parse model response based on actual output format"""
raw = text.strip()
if task == "fix":
# extract only the function/class definition
code_part = TOPLEVEL_TEST_RE.split(raw, maxsplit=1)[0].strip()
fixed_code = longest_valid_python_prefix(code_part)
# Remove trailing comments and empty lines
lines = fixed_code.split('\n')
while lines:
last_line = lines[-1].strip()
if not last_line or last_line.startswith('#'):
lines.pop()
else:
break
fixed_code = '\n'.join(lines)
return CodeResponse(text=raw, detectedBugs=[], fixedCode=fixed_code)
if task == "analyze":
lines = raw.split('\n')
# fixed code
fixed_code = None
code_lines = []
fixed_code_match = re.search(
r'###?\s*fixed\s+code.*?:?\s*\n+```(?:python)?\s*\n(.*?)\n```',
raw,
re.IGNORECASE | re.DOTALL
)
if fixed_code_match:
fixed_code = fixed_code_match.group(1).strip()
# Fallback: extract function/class definition from raw text
if not fixed_code:
in_function = False
for line in lines:
if line.startswith('def ') or line.startswith('class '):
in_function = True
code_lines.append(line)
elif in_function and (line.startswith(' ') or line.startswith('\t') or
line.strip().startswith('"""') or line.strip().startswith("'''")):
code_lines.append(line)
elif in_function and line.strip() and not line.startswith(' '):
break
elif in_function:
code_lines.append(line)
fixed_code = '\n'.join(code_lines).strip() if code_lines else None
# extract explanation
explanation = None
# "# Explanation:" comment section
# captures everything from "# Explanation:" until "# Test" or end
comment_explanation_match = re.search(
r'#\s*Explanation[^:\n]*:?\s*\n((?:#[^\n]*\n?)+)',
raw,
re.IGNORECASE
)
if comment_explanation_match:
explanation_text = comment_explanation_match.group(1)
# remove # prefixes and join lines
cleaned_lines = []
for line in explanation_text.split('\n'):
# remove leading # and whitespace
clean = line.strip().lstrip('#').strip()
# stop if we hit test-related content
if clean.lower().startswith('test'):
break
if clean:
cleaned_lines.append(clean)
explanation = ' '.join(cleaned_lines) if cleaned_lines else None
# Try markdown style ### Explanation:
if not explanation:
markdown_explanation_match = re.search(
r'###?\s*(?:bug\s+)?explanation[^\n]*:?\s*\n+(.*?)(?=\n###?\s*(?:test|why|fixed)|#\s*Test|$)',
raw,
re.IGNORECASE | re.DOTALL
)
if markdown_explanation_match:
explanation = markdown_explanation_match.group(1).strip()
# Clean up any # prefixes
cleaned_lines = []
for line in explanation.split('\n'):
clean = line.strip().lstrip('#').strip()
if clean:
cleaned_lines.append(clean)
explanation = ' '.join(cleaned_lines) if cleaned_lines else None
# extract test assertion
test_lines = []
test_start_match = re.search(
r'(?:#\s*Test(?:s|ing)?[^\n]*|###?\s*Test(?:s|ing)?[^\n]*)\n',
raw,
re.IGNORECASE
)
if test_start_match:
test_section = raw[test_start_match.end():]
# extract all assert statements
for line in test_section.split('\n'):
stripped = line.strip()
if stripped.startswith('assert '):
# remove inline comments for cleaner output
clean_assert = re.sub(r'\s*#.*$', '', stripped)
test_lines.append(clean_assert)
# Fallback: just find all assert statements in the raw text
if not test_lines:
for line in lines:
stripped = line.strip()
if stripped.startswith('assert '):
clean_assert = re.sub(r'\s*#.*$', '', stripped)
test_lines.append(clean_assert)
tests = '\n'.join(test_lines) if test_lines else None
# extract "WHY THE FIX WORKS" (mainly for base model)
whyFix = None
# Comment style: # Why the fix works:
why_comment_match = re.search(
r'#\s*Why\s+(?:the\s+)?fix\s+works:?\s*\n((?:#[^\n]*\n?)+)',
raw,
re.IGNORECASE
)
if why_comment_match:
why_text = why_comment_match.group(1)
cleaned_lines = []
for line in why_text.split('\n'):
clean = line.strip().lstrip('#').strip()
if clean.lower().startswith('test'):
break
if clean:
cleaned_lines.append(clean)
whyFix = ' '.join(cleaned_lines) if cleaned_lines else None
# Markdown style: ### Why the fix works:
if not whyFix:
why_markdown_match = re.search(
r'###?\s*why\s+(?:the\s+)?fix\s+works[^\n]*:?\s*\n+(.*?)(?=\n###?\s*test|#\s*Test|Testing|$)',
raw,
re.IGNORECASE | re.DOTALL
)
if why_markdown_match:
whyFix = why_markdown_match.group(1).strip()
# Clean up
cleaned_lines = []
for line in whyFix.split('\n'):
clean = line.strip().lstrip('#').strip()
if clean:
cleaned_lines.append(clean)
whyFix = ' '.join(cleaned_lines) if cleaned_lines else None
#bug summary
detected = []
if explanation:
# Take first sentence for the summary
sentences = explanation.split('.')
for s in sentences:
s = s.strip()
if len(s) > 20:
detected = [s + "."]
break
if not detected:
detected = ["Potential bug detected - see explanation for details"]
return CodeResponse(
text=raw,
detectedBugs=detected,
fixedCode=fixed_code,
explanation=explanation,
whyFix=whyFix,
tests=tests,
)
# For chat or unknown tasks
return CodeResponse(text=raw, detectedBugs=[], fixedCode=None)
@app.get("/")
def read_root():
return {
"name": "Python Bug Fixer API",
"status": "running",
"models": {
"base": "microsoft/phi-2",
"finetuned": "ashkanhsn/phi2-python-bugfixer (PEFT adapter)"
},
"version": "2.3.0",
"info": "Shared base model approach - efficient memory usage"
}
@app.get("/health")
def health_check():
return {
"status": "healthy",
"base_model_loaded": base_model is not None,
"finetuned_model_loaded": finetuned_model is not None,
"device": str(device)
}
@app.post("/analyze", response_model=CodeResponse)
async def analyze_code(request: CodeRequest):
try:
print(f"Request: task={request.task}, use_base_model={request.use_base_model}")
response_text = generate_response(
request.code,
request.task,
request.use_base_model,
request.temperature
)
return parse_response(response_text, request.task)
except Exception as e:
print(f"Error: {str(e)}")
raise HTTPException(status_code=500, detail=f"Error processing request: {str(e)}")
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=7860) |