File size: 12,268 Bytes
b56a66f
 
 
 
 
9b316e7
 
 
 
 
 
b56a66f
 
0719b05
6725fae
b56a66f
 
 
 
 
 
 
9b316e7
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
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
 
9b316e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7377087
 
 
 
 
 
 
 
 
 
 
 
 
 
b56a66f
 
6725fae
9b316e7
 
0d101df
b0b1b30
 
9b316e7
 
 
 
b0b1b30
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7377087
 
 
 
b0b1b30
 
7377087
b0b1b30
0d101df
9b316e7
 
 
 
b0b1b30
9b316e7
0d101df
b56a66f
b0b1b30
9b316e7
1a7ffc2
b56a66f
 
 
 
 
0933659
 
6725fae
0d101df
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
"""
HuggingFace Space - Python Bug Fixer API
FAST API backend for fine-tuned Phi-2
"""

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.2.0"
)

# 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

STOP_HEADING_RE = re.compile(
    r"""(?im)^\s*(?:###\s*(?:explanation|why.*works|testing|tests?)\s*:?
            |#\s*Explanation(?:\s+of\s+the\s+fix)?\s*:?
            |Explanation\s+of\s+the\s+fix\s*:?
            )\s*$""",
    re.VERBOSE,
)
TOPLEVEL_TEST_RE = re.compile(r"(?m)^(assert\s+|print\()")
TEST_START_RE = re.compile(r"(?m)^(assert\s+|print\()")
FENCED_CODE_RE = re.compile(r"```(?:python)?\s*\n([\s\S]*?)\n```", re.IGNORECASE)

def extract_first_fenced_code(text: str) -> Optional[str]:
    m = FENCED_CODE_RE.search(text)
    return m.group(1).strip() if m else None

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 extract_section(text: str, heading_patterns: List[str]) -> Optional[str]:
    """extract section content following a heading, stopping at next heading or top-level tests"""
    for hp in heading_patterns:
        m = re.search(hp, text, flags=re.IGNORECASE | re.MULTILINE)
        if not m:
            continue
        start = m.end()
        tail = text[start:]

        # stop at next heading or tests
        stop_m = re.search(r"(?im)^\s*###\s*[A-Za-z].*?:?\s*$|(?m)^(assert\s+|print\()", tail)
        chunk = tail[: stop_m.start()] if stop_m else tail
        chunk = chunk.strip()
        if len(chunk) >= 5:
            return chunk
    return None

def extract_tests(text: str) -> Optional[str]:
    # prefer explicit "Tests" section
    t = extract_section(text, [
        r"(?im)^\s*###\s*Tests?\s*:?\s*$",
        r"(?im)^\s*###\s*Testing\s*:?\s*$",
        r"(?im)^\s*#\s*Tests?\s*:?\s*$",
        r"(?im)^\s*#\s*Testing\s*:?\s*$",
    ])
    if t:
        # keep only assert/print lines if the section contains mixed content
        lines = [ln.rstrip() for ln in t.splitlines() if ln.strip()]
        # If there are asserts, show from first assert onward
        for i, ln in enumerate(lines):
            if ln.lstrip().startswith("assert"):
                return "\n".join(lines[i:]).strip()
        return "\n".join(lines).strip()

    # Fallback: from first top-level assert to end
    m = re.search(r"(?m)^assert\s+.*$", text)
    if m:
        return text[m.start():].strip()
    return None

def guess_bug_summaries(explanation: Optional[str]) -> List[str]:
    # if not explanation:
    #     return ["Code analyzed and fixed - check explanation for details"]
    # # Take first 1-2 decent sentences
    # cleaned = " ".join([ln.strip().lstrip("#").strip() for ln in explanation.splitlines() if ln.strip()])
    # sentences = re.split(r"[.!?]\s+", cleaned)
    # out = []
    # for s in sentences:
    #     s = s.strip()
    #     if len(s) >= 18:
    #         out.append(s + ".")
    #     if len(out) == 2:
    #         break
    # return out if out else ["Code analyzed and fixed - check explanation for details"]
    return []

def parse_response(text: str, task: str) -> CodeResponse:
    """parse model response"""
    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)
        return CodeResponse(text=raw, detectedBugs=[], fixedCode=fixed_code)

    if task == "analyze":
        lines = raw.split('\n')
        
        # extract the fixed code (function/class definition only)
        code_lines = []
        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()
        
        # extract explanatory comments (lines starting with #)
        explanation_lines = []
        for line in lines:
            stripped = line.strip()
            # Get comment lines that are NOT part of the function definition
            if stripped.startswith('#') and line not in code_lines:
                explanation_lines.append(stripped.lstrip('#').strip())
        
        explanation = '\n'.join(explanation_lines).strip() if explanation_lines else None
        
        # extract test assertions
        test_lines = []
        for line in lines:
            stripped = line.strip()
            if stripped.startswith('assert '):
                test_lines.append(stripped)
        
        tests = '\n'.join(test_lines).strip() if test_lines else None
        
        # create bug summary from explanation
        detected = []
        if explanation:
            cleaned = explanation.replace("Explanation:", "").replace("\n", " ").strip()
            sentences = cleaned.split('.')
            if sentences and len(sentences[0].strip()) > 20:
                detected = [sentences[0].strip() + "."]
        
        if not detected:
            detected = ["Potential bug detected - see explanation for details"]
        
        return CodeResponse(
            text=raw,
            detectedBugs=detected,
            fixedCode=fixed_code,
            explanation=explanation,
            whyFix=None,  # Your model doesn't separate this
            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.1.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)