Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,155 +1,149 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Code Collab AI Backend β Fast code generation API
|
| 3 |
-
Uses Qwen 2.5 Coder 0.5B GGUF for low-latency HTML/CSS/JS generation.
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
import
|
| 8 |
-
import
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
from fastapi
|
| 13 |
-
from
|
| 14 |
-
from
|
| 15 |
-
from llama_cpp import Llama
|
| 16 |
-
|
| 17 |
-
# βββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 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 |
-
lang =
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
@app.
|
| 120 |
-
def
|
| 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 |
-
html=parsed["html"],
|
| 151 |
-
css=parsed["css"],
|
| 152 |
-
js=parsed["js"],
|
| 153 |
-
raw=raw_text,
|
| 154 |
-
time_ms=elapsed_ms,
|
| 155 |
-
)
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Code Collab AI Backend β Fast code generation API
|
| 3 |
+
Uses Qwen 2.5 Coder 0.5B GGUF for low-latency HTML/CSS/JS generation.
|
| 4 |
+
Model is loaded once at startup and stays in memory forever.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import re
|
| 9 |
+
import time
|
| 10 |
+
from contextlib import asynccontextmanager
|
| 11 |
+
|
| 12 |
+
from fastapi import FastAPI, HTTPException
|
| 13 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
+
from pydantic import BaseModel
|
| 15 |
+
from llama_cpp import Llama
|
| 16 |
+
|
| 17 |
+
# βββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 18 |
+
MODEL_PATH = os.path.join(os.path.dirname(__file__), "qwen2.5-coder-0.5b-instruct-q4_k_m.gguf")
|
| 19 |
+
N_CTX = 1536 # Smaller context = faster (free tier)
|
| 20 |
+
N_THREADS = 2 # HF free tier has 2 vCPU
|
| 21 |
+
MAX_TOKENS = 512 # Keep output short for speed
|
| 22 |
+
TEMPERATURE = 0.5 # Lower = faster + more deterministic
|
| 23 |
+
|
| 24 |
+
# βββ System prompt (optimized for structured output) βββββββββββββββββββ
|
| 25 |
+
SYSTEM_PROMPT = """You are a web code generator. Given a user request, output ONLY three fenced code blocks:
|
| 26 |
+
|
| 27 |
+
```html
|
| 28 |
+
(body content only, no html/head/body tags)
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
```css
|
| 32 |
+
(complete styles)
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
```js
|
| 36 |
+
(complete JavaScript)
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Rules:
|
| 40 |
+
- No explanations, no markdown text outside code blocks
|
| 41 |
+
- If a section is not needed, output an empty code block for it
|
| 42 |
+
- Write clean, modern code"""
|
| 43 |
+
|
| 44 |
+
# βββ Global model reference (loaded once, stays forever) ββββββββββββββ
|
| 45 |
+
llm = None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@asynccontextmanager
|
| 49 |
+
async def lifespan(app: FastAPI):
|
| 50 |
+
"""Load model once at startup. It stays in memory for the entire lifetime."""
|
| 51 |
+
global llm
|
| 52 |
+
print(f"π Loading model from {MODEL_PATH}...")
|
| 53 |
+
llm = Llama(
|
| 54 |
+
model_path=MODEL_PATH,
|
| 55 |
+
n_ctx=N_CTX,
|
| 56 |
+
n_threads=N_THREADS,
|
| 57 |
+
n_gpu_layers=0, # CPU only (free HF Spaces)
|
| 58 |
+
verbose=False,
|
| 59 |
+
)
|
| 60 |
+
print("π Model loaded and ready! It will stay in memory forever.")
|
| 61 |
+
yield
|
| 62 |
+
# Model stays loaded β never unloaded
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# βββ FastAPI App βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 66 |
+
app = FastAPI(title="Code Collab AI", lifespan=lifespan)
|
| 67 |
+
|
| 68 |
+
app.add_middleware(
|
| 69 |
+
CORSMiddleware,
|
| 70 |
+
allow_origins=["*"],
|
| 71 |
+
allow_methods=["*"],
|
| 72 |
+
allow_headers=["*"],
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class GenerateRequest(BaseModel):
|
| 77 |
+
prompt: str
|
| 78 |
+
max_tokens: int = MAX_TOKENS
|
| 79 |
+
temperature: float = TEMPERATURE
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class GenerateResponse(BaseModel):
|
| 83 |
+
html: str
|
| 84 |
+
css: str
|
| 85 |
+
js: str
|
| 86 |
+
raw: str
|
| 87 |
+
time_ms: int
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def parse_code_blocks(text: str) -> dict:
|
| 91 |
+
"""Extract HTML, CSS, JS from fenced code blocks."""
|
| 92 |
+
result = {"html": "", "css": "", "js": ""}
|
| 93 |
+
|
| 94 |
+
for match in re.finditer(r"```(\w+)\s*\n([\s\S]*?)```", text):
|
| 95 |
+
lang = match.group(1).lower()
|
| 96 |
+
code = match.group(2).strip()
|
| 97 |
+
|
| 98 |
+
if lang in ("html", "xml"):
|
| 99 |
+
result["html"] = code
|
| 100 |
+
elif lang == "css":
|
| 101 |
+
result["css"] = code
|
| 102 |
+
elif lang in ("js", "javascript"):
|
| 103 |
+
result["js"] = code
|
| 104 |
+
|
| 105 |
+
# Fallback: if no blocks found, treat as HTML
|
| 106 |
+
if not any(result.values()):
|
| 107 |
+
result["html"] = text.strip()
|
| 108 |
+
|
| 109 |
+
return result
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# βββ API Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 113 |
+
|
| 114 |
+
@app.get("/")
|
| 115 |
+
def health():
|
| 116 |
+
return {"status": "ok", "model": "Qwen2.5-Coder-0.5B-Instruct-GGUF", "loaded": llm is not None}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@app.post("/generate", response_model=GenerateResponse)
|
| 120 |
+
def generate(req: GenerateRequest):
|
| 121 |
+
if llm is None:
|
| 122 |
+
raise HTTPException(503, "Model not loaded yet")
|
| 123 |
+
|
| 124 |
+
if not req.prompt.strip():
|
| 125 |
+
raise HTTPException(400, "Prompt cannot be empty")
|
| 126 |
+
|
| 127 |
+
start = time.time()
|
| 128 |
+
|
| 129 |
+
output = llm.create_chat_completion(
|
| 130 |
+
messages=[
|
| 131 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 132 |
+
{"role": "user", "content": req.prompt},
|
| 133 |
+
],
|
| 134 |
+
max_tokens=req.max_tokens,
|
| 135 |
+
temperature=req.temperature,
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
raw_text = output["choices"][0]["message"]["content"]
|
| 139 |
+
elapsed_ms = int((time.time() - start) * 1000)
|
| 140 |
+
|
| 141 |
+
parsed = parse_code_blocks(raw_text)
|
| 142 |
+
|
| 143 |
+
return GenerateResponse(
|
| 144 |
+
html=parsed["html"],
|
| 145 |
+
css=parsed["css"],
|
| 146 |
+
js=parsed["js"],
|
| 147 |
+
raw=raw_text,
|
| 148 |
+
time_ms=elapsed_ms,
|
| 149 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|