Spaces:
Sleeping
Sleeping
Download app.py from Sarra22/phi2-python-bugfixer-api: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/Sarra22/phi2-python-bugfixer-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/Sarra22/phi2-python-bugfixer-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Sarra22/phi2-python-bugfixer-api/resolve/main/app.py
12.3 kB
| """ | |
| 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) | |
| 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" | |
| } | |
| 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) | |
| } | |
| 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) |