Nafiul Huda commited on
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151import osimport jsonimport gradio as grimport spacesfrom fastapi import Request, Responsefrom fastapi.responses import JSONResponse, StreamingResponsefrom huggingface_hub import hf_hub_downloadfrom llama_cpp import Llama# 1. DUMMY GPU FUNCTION: Satisfies the Hugging Face ZeroGPU checks@spaces.GPU(duration=5)def dummy_gpu():print("ZeroGPU validation satisfied.")return 1dummy_gpu()# 2. DOWNLOAD LFM 2.5 8B A1B GGUF MODELprint("Downloading LFM2.5-8B-A1B-GGUF model...")model_path = hf_hub_download(repo_id="Abiray/MiniCPM5-1B-GGUF",filename="minicpm5-1b-Q6_K.gguf")# 3. LOAD MODEL DIRECTLY IN PYTHON (CPU ONLY)print("Loading model into memory via llama-cpp-python...")llm = Llama(model_path=model_path,n_ctx=8192,n_threads=8,verbose=False)print("Model loaded successfully!")# 4. BUILD GRADIO UIdef chat_with_llama(message, history):messages = [{"role": "system", "content": "You are a helpful AI assistant."}]for user_msg, assistant_msg in history:messages.append({"role": "user", "content": user_msg})messages.append({"role": "assistant", "content": assistant_msg})messages.append({"role": "user", "content": message})stream = llm.create_chat_completion(messages=messages,stream=True,temperature=0.7,max_tokens=1024)partial_response = ""for chunk in stream:if "choices" in chunk and len(chunk["choices"]) > 0:delta = chunk["choices"][0].get("delta", {})if "content" in delta:partial_response += delta["content"]yield partial_responsewith gr.Blocks() as demo:gr.Markdown("# 🚀 LiquidAI LFM2.5-8B (CPU & API Enabled)")gr.Markdown("""Running **LFM2.5-8B-A1B** natively via `llama-cpp-python` entirely on CPU! ZeroGPU is bypassed safely.### 🔌 Developer API Available!This Space also silently hosts a real API endpoint on the exact same port.**Endpoint:** `POST /v1/chat/completions` (Supports Streaming & Non-Streaming OpenAI formats)""")gr.ChatInterface(fn=chat_with_llama,examples=["Who are you?", "Write a python script to reverse a string.", "Explain quantum computing."],)# 5. ROBUST MONKEY-PATCH FOR FASTAPI ROUTESimport fastapi# Store original FastAPI init methodoriginal_fastapi_init = fastapi.FastAPI.__init__def custom_fastapi_init(self, *args, **kwargs):# Initialize the standard FastAPI applicationoriginal_fastapi_init(self, *args, **kwargs)# Check if this is the app instance Gradio is constructingif kwargs.get("title") == "Gradio" or "gradio" in str(args):print("Successfully targeted Gradio's internal FastAPI server! Injecting routes...")# CORS Preflight (OPTIONS) handler@self.options("/v1/chat/completions")async def chat_api_options():return Response(status_code=200,headers={"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "POST, OPTIONS","Access-Control-Allow-Headers": "Content-Type, Authorization",})# Custom OpenAI-compatible route with explicit CORS headers@self.post("/v1/chat/completions")async def chat_api(request: Request):try:body = await request.json()messages = body.get("messages", [])stream = body.get("stream", False)temperature = body.get("temperature", 0.7)max_tokens = body.get("max_tokens", 1024)headers = {"Access-Control-Allow-Origin": "*","Access-Control-Allow-Methods": "POST, OPTIONS","Access-Control-Allow-Headers": "Content-Type, Authorization",}if stream:def stream_generator():for chunk in llm.create_chat_completion(messages=messages,stream=True,temperature=temperature,max_tokens=max_tokens):yield f"data: {json.dumps(chunk)}\n\n"yield "data: [DONE]\n\n"return StreamingResponse(stream_generator(),media_type="text/event-stream",headers=headers)else:response = llm.create_chat_completion(messages=messages,stream=False,temperature=temperature,max_tokens=max_tokens)return JSONResponse(content=response, headers=headers)except Exception as e:return JSONResponse(status_code=500,content={"error": str(e)},headers={"Access-Control-Allow-Origin": "*"})# Apply patch directly to the FastAPI library before Gradio can call itfastapi.FastAPI.__init__ = custom_fastapi_init# 6. LAUNCH GRADIOif __name__ == "__main__":demo.launch(server_name="0.0.0.0", server_port=7860)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211import os, io, json, time, zipfile, subprocess, urllib.requestfrom pathlib import Pathimport gradio as grimport spacesimport httpxfrom huggingface_hub import hf_hub_download# ===== 0. CONFIG (override in Space Settings → Variables and secrets) =====LLAMA_TAG = os.environ.get("LLAMA_TAG", "") # pin e.g. "b8407"; "" = latestMODEL_REPO = os.environ.get("MODEL_REPO", "Abiray/MiniCPM5-1B-GGUF")MODEL_FILE = os.environ.get("MODEL_FILE", "minicpm5-1b-Q6_K.gguf")CTX_SIZE = int(os.environ.get("CTX_SIZE", "8192"))PARALLEL = int(os.environ.get("PARALLEL", "2"))LLAMA_PORT = int(os.environ.get("LLAMA_PORT", "8080")) # internal onlyAPI_KEY = os.environ.get("LLAMA_API_KEY", "") # SET THIS as a Space secret!SYSTEM_PROMPT = os.environ.get("SYSTEM_PROMPT", "You are a helpful AI assistant.")# ===== 1. HOLD THE ZEROGPU HARDWARE (~5s of quota, once, at boot) =====@spaces.GPU(duration=5)def _hold_zerogpu():print("[zerogpu] host claimed; GPU slice released, CPU+RAM stay ours.")return True_hold_zerogpu()# ===== 2. READ THE "DYNAMIC" CPU/RAM WE ACTUALLY GOT (cgroup truth) =====def effective_cpus() -> int:try:quota, period = Path("/sys/fs/cgroup/cpu.max").read_text().split()[:2]if quota != "max":return max(1, int(quota) // int(period))except Exception:passtry:return len(os.sched_getaffinity(0))except Exception:return os.cpu_count() or 2def memory_limit_gb():try:v = Path("/sys/fs/cgroup/memory.max").read_text().strip()if v != "max":return round(int(v) / 1e9, 1)except Exception:passreturn NoneCORES = effective_cpus()print(f"[resources] effective cores: {CORES} | RAM limit: {memory_limit_gb() or '?'} GB")# ===== 3. FETCH PREBUILT llama.cpp (seconds, zero compilation) =====FALLBACK_TAG = "b8407"def resolve_tag() -> str:if LLAMA_TAG:return LLAMA_TAGtry:req = urllib.request.Request("https://api.github.com/repos/ggml-org/llama.cpp/releases/latest",headers={"User-Agent": "hf-space"})with urllib.request.urlopen(req, timeout=10) as r:return json.load(r)["tag_name"]except Exception as e:print(f"[llama.cpp] latest-tag lookup failed ({e}); pinned fallback {FALLBACK_TAG}")return FALLBACK_TAGdef ensure_llama_server() -> Path:tag = resolve_tag()root = Path.home() / ".cache" / "llamacpp" / tagserver = root / "build" / "bin" / "llama-server"if not server.exists():url = (f"https://github.com/ggml-org/llama.cpp/releases/download/"f"{tag}/llama-{tag}-bin-ubuntu-x64.zip")print(f"[llama.cpp] downloading {url}")req = urllib.request.Request(url, headers={"User-Agent": "hf-space"})with urllib.request.urlopen(req, timeout=180) as r:blob = r.read()root.mkdir(parents=True, exist_ok=True)with zipfile.ZipFile(io.BytesIO(blob)) as z:z.extractall(root)for f in (root / "build" / "bin").iterdir():f.chmod(0o755)return server# ===== 4. MODEL =====print(f"[model] downloading {MODEL_REPO}/{MODEL_FILE}")model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)# ===== 5. LAUNCH llama-server, SIZED TO THE DETECTED HARDWARE =====server_bin = ensure_llama_server()UPSTREAM = f"http://127.0.0.1:{LLAMA_PORT}"env = os.environ.copy()env["LD_LIBRARY_PATH"] = f"{server_bin.parent}:{env.get('LD_LIBRARY_PATH', '')}"env.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")cmd = [str(server_bin), "-m", model_path,"--host", "127.0.0.1", "--port", str(LLAMA_PORT),"-t", str(CORES), "-tb", str(CORES), # every core the cgroup gives us"-c", str(CTX_SIZE),"-np", str(PARALLEL), # real concurrent slots, no global lock"-fa", # flash attention → much smaller KV cache"--cache-reuse", "256", # KV reuse across chat turns]if API_KEY:cmd += ["--api-key", API_KEY]proc = subprocess.Popen(cmd, env=env)def wait_ready(timeout=600):t0 = time.time()while time.time() - t0 < timeout:if proc.poll() is not None:raise RuntimeError(f"llama-server died early (code {proc.returncode})")try:if httpx.get(f"{UPSTREAM}/health", timeout=2).status_code == 200:print("[llama.cpp] server ready")returnexcept Exception:passtime.sleep(1)raise TimeoutError("llama-server not ready in time")wait_ready()# ===== 6. GRADIO UI (same backend as the API) =====from openai import OpenAIoai = OpenAI(base_url=f"{UPSTREAM}/v1", api_key=API_KEY or "not-needed")def _normalize(history):msgs = [{"role": "system", "content": SYSTEM_PROMPT}]for item in history:if isinstance(item, dict):msgs.append({"role": item["role"], "content": item["content"]})else:user, bot = itemmsgs.append({"role": "user", "content": user})if bot:msgs.append({"role": "assistant", "content": bot})return msgsdef chat(message, history):stream = oai.chat.completions.create(model="local",messages=_normalize(history) + [{"role": "user", "content": message}],stream=True, temperature=0.7, max_tokens=1024,)out = ""for chunk in stream:delta = chunk.choices[0].delta.contentif delta:out += deltayield outwith gr.Blocks() as demo:gr.Markdown(f"# ⚡ llama.cpp on ZeroGPU's free CPU\n"f"`{MODEL_REPO}` · {CORES} threads · ctx {CTX_SIZE} · {PARALLEL} parallel slots\n\n"f"**External API:** `POST /v1/chat/completions` on this Space's `*.hf.space` URL.")gr.ChatInterface(fn=chat, examples=["Who are you?","Write a python script to reverse a string.", "Explain quantum computing."])demo = demo.queue()# ===== 7. PUBLIC /v1 PROXY — the supported way, no monkey-patch =====from fastapi import FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import Response, StreamingResponseapp = FastAPI(title="llama-cpp-proxy")app.add_middleware(CORSMiddleware, allow_origins=["*"],allow_methods=["*"], allow_headers=["*"])_http = httpx.AsyncClient(timeout=httpx.Timeout(None))@app.api_route("/v1/{path:path}", methods=["GET", "POST"])async def v1_proxy(path: str, request: Request):body = await request.body()headers = {k: request.headers[k] for k in ("authorization", "content-type")if k in request.headers}wants_stream = Falseif body:try:wants_stream = bool(json.loads(body).get("stream"))except Exception:passurl = f"{UPSTREAM}/v1/{path}"if request.method == "POST" and wants_stream:req = _http.build_request("POST", url, content=body, headers=headers)resp = await _http.send(req, stream=True)async def gen():try:async for chunk in resp.aiter_raw():yield chunkfinally:await resp.aclose()return StreamingResponse(gen(), status_code=resp.status_code,media_type="text/event-stream")resp = await _http.request(request.method, url, content=body or None, headers=headers)return Response(content=resp.content, status_code=resp.status_code,media_type=resp.headers.get("content-type", "application/json"))app = gr.mount_gradio_app(app, demo, path="/") # mounted LAST so /v1/* winsif __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))
app.py+198-138