Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110from fastapi import FastAPIfrom pydantic import BaseModelfrom typing import List, Literal
app = FastAPI(title="Python AI Stub")
class Cursor(BaseModel): l: int c: int
class Viewport(BaseModel): start: int end: int text: str
class Diagnostic(BaseModel): l: int sev: str msg: str
class Memory(BaseModel): short: List[str] = [] sess: List[str] = [] proj: List[str] = []
class Inp(BaseModel): intent: str file: str lang: str cursor: Cursor viewport: Viewport diag: List[Diagnostic] = [] term: str = "" mem: Memory = Memory()
class Need(BaseModel): function: bool = False xrefs: List[str] = [] page_ids: List[str] = []
class Out(BaseModel): mode: Literal["patch","full","ask"] patch: str = "" full_text: str = "" explanation: str = "" confidence: float = 0.9 need: Need = Need()
@app.post("/code_help", response_model=Out)def code_help(x: Inp): before = x.viewport.text if "print(reslt)" in before: after = before.replace("print(reslt)","print(result)",1) h_start = x.viewport.start h_count = x.viewport.end - x.viewport.start + 1 patch = f"--- a/{x.file}\n+++ b/{x.file}\n@@ -{h_start},{h_count} +{h_start},{h_count} @@\n-{before}\n+{after}\n" return Out(mode="patch", patch=patch, full_text="", explanation="Fixed misspelling: reslt -> result.", confidence=0.96) return Out(mode="ask", explanation="Need more context.", confidence=0.6)# app.py (Python_ai)import difflibimport jsonimport osfrom typing import Dict, Any
from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponsefrom fastapi.middleware.cors import CORSMiddleware
APP_NAME = "Python_ai"app = FastAPI(title=APP_NAME)
# Allow CORS just in case you call it directly from the Brain UIapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=[""], allow_headers=[""],)
def ok(payload: Dict[str, Any] | None = None) -> JSONResponse: return JSONResponse({"ok": True, **(payload or {})})
@app.get("/health")def health(): return ok()
def make_unified_diff(filename: str, old_text: str, new_text: str) -> str: # Ensure both end with newline so ranges are sane if not old_text.endswith("\n"): old_text += "\n" if not new_text.endswith("\n"): new_text += "\n" diff = difflib.unified_diff( old_text.splitlines(keepends=True), new_text.splitlines(keepends=True), fromfile=f"a/{filename}", tofile=f"b/{filename}", n=3, ) return "".join(diff)
def minimal_fix(view_text: str) -> tuple[str, str, str]: """ Very small heuristic fixer: - reslt -> result (common typo) - NameError 'bar' if foo returns bar but bar undefined -> return 'result' instead Only edits when the change is obvious; otherwise returns original text. """ old = view_text new = old
# Trivial typo fix if "reslt" in new: new = new.replace("reslt", "result")
# If there's a pattern like: # def foo():\n return bar\n\nresult = foo() # we can't know bar; safer to leave it alone here. # Keep this service minimal/fast.
return old, new, "Fixed trivial misspelling(s) where obvious."
@app.post("/code_help")async def code_help(req: Request): """ Accepts ANY JSON shape to avoid 422. We only read fields we need. Returns a PATCH-first JSON as your 'PythonFixer' contract expects. """ try: body = await req.json() except Exception: body = {}
# Extract with defaults (never 422) utterance = body.get("utterance", "") telemetry = body.get("telemetry", {}) or {} filename = telemetry.get("file", "main.py") viewport = telemetry.get("viewport", {}) or {} view_text = viewport.get("text", "")
# Minimal edit logic old_text, new_text, why = minimal_fix(view_text)
if new_text != old_text: patch = make_unified_diff(filename, old_text, new_text) resp = { "mode": "patch", "patch": patch, "full_text": "", "explanation": why, "confidence": 0.96, "need": {"function": False, "xrefs": [], "page_ids": []}, } else: # Nothing obvious to fix; ask for more context (keeps contract) resp = { "mode": "ask", "patch": "", "full_text": "", "explanation": "Need more context or a specific error message to propose a safe minimal patch.", "confidence": 0.55, "need": {"function": False, "xrefs": [], "page_ids": []}, }
# Always 200 with the contract object return JSONResponse(resp)
# HF entryif _name_ == "_main_": import uvicorn uvicorn.run("app:app", host="0.0.0.0", port=int(os.getenv("PORT", "7860")), reload=False)app.py+110-58