Download app.py from ashkanhsn/phi2-python-bugfixer-api: direct link, hf CLI and curl.
- Browser
- Download file 14.2 kB
-
https://huggingface.co/spaces/ashkanhsn/phi2-python-bugfixer-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/ashkanhsn/phi2-python-bugfixer-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/ashkanhsn/phi2-python-bugfixer-api/resolve/main/app.py
14.2 kB
| """ | |
| 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 this 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} | |
| Respond with ### headers: Explanation, Fixed Code, Why the fix works. | |
| ### output: | |
| ### Fixed Code: | |
| ```python | |
| """ | |
| temp = temperature_override if temperature_override is not None else 0.6 | |
| 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) | |
| 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" | |
| } | |
| 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) |