Nafiul Huda commited on
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,151 +1,211 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import
|
|
|
|
| 3 |
import gradio as gr
|
| 4 |
import spaces
|
| 5 |
-
|
| 6 |
-
from fastapi.responses import JSONResponse, StreamingResponse
|
| 7 |
from huggingface_hub import hf_hub_download
|
| 8 |
-
from llama_cpp import Llama
|
| 9 |
|
| 10 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
@spaces.GPU(duration=5)
|
| 12 |
-
def
|
| 13 |
-
print("
|
| 14 |
-
return
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
# 2.
|
| 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 |
-
partial_response = ""
|
| 52 |
for chunk in stream:
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
yield partial_response
|
| 58 |
|
| 59 |
with gr.Blocks() as demo:
|
| 60 |
-
gr.Markdown(
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
### 🔌 Developer API Available!
|
| 65 |
-
This Space also silently hosts a real API endpoint on the exact same port.
|
| 66 |
-
**Endpoint:** `POST /v1/chat/completions` (Supports Streaming & Non-Streaming OpenAI formats)
|
| 67 |
-
""")
|
| 68 |
-
|
| 69 |
-
gr.ChatInterface(
|
| 70 |
-
fn=chat_with_llama,
|
| 71 |
-
examples=["Who are you?", "Write a python script to reverse a string.", "Explain quantum computing."],
|
| 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 |
-
|
| 101 |
-
@self.post("/v1/chat/completions")
|
| 102 |
-
async def chat_api(request: Request):
|
| 103 |
try:
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
"
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
def stream_generator():
|
| 118 |
-
for chunk in llm.create_chat_completion(
|
| 119 |
-
messages=messages,
|
| 120 |
-
stream=True,
|
| 121 |
-
temperature=temperature,
|
| 122 |
-
max_tokens=max_tokens
|
| 123 |
-
):
|
| 124 |
-
yield f"data: {json.dumps(chunk)}\n\n"
|
| 125 |
-
yield "data: [DONE]\n\n"
|
| 126 |
-
return StreamingResponse(
|
| 127 |
-
stream_generator(),
|
| 128 |
-
media_type="text/event-stream",
|
| 129 |
-
headers=headers
|
| 130 |
-
)
|
| 131 |
-
else:
|
| 132 |
-
response = llm.create_chat_completion(
|
| 133 |
-
messages=messages,
|
| 134 |
-
stream=False,
|
| 135 |
-
temperature=temperature,
|
| 136 |
-
max_tokens=max_tokens
|
| 137 |
-
)
|
| 138 |
-
return JSONResponse(content=response, headers=headers)
|
| 139 |
-
except Exception as e:
|
| 140 |
-
return JSONResponse(
|
| 141 |
-
status_code=500,
|
| 142 |
-
content={"error": str(e)},
|
| 143 |
-
headers={"Access-Control-Allow-Origin": "*"}
|
| 144 |
-
)
|
| 145 |
-
|
| 146 |
-
# Apply patch directly to the FastAPI library before Gradio can call it
|
| 147 |
-
fastapi.FastAPI.__init__ = custom_fastapi_init
|
| 148 |
-
|
| 149 |
-
# 6. LAUNCH GRADIO
|
| 150 |
if __name__ == "__main__":
|
| 151 |
-
|
|
|
|
|
|
| 1 |
+
import os, io, json, time, zipfile, subprocess, urllib.request
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
|
| 4 |
import gradio as gr
|
| 5 |
import spaces
|
| 6 |
+
import httpx
|
|
|
|
| 7 |
from huggingface_hub import hf_hub_download
|
|
|
|
| 8 |
|
| 9 |
+
# ===== 0. CONFIG (override in Space Settings → Variables and secrets) =====
|
| 10 |
+
LLAMA_TAG = os.environ.get("LLAMA_TAG", "") # pin e.g. "b8407"; "" = latest
|
| 11 |
+
MODEL_REPO = os.environ.get("MODEL_REPO", "Abiray/MiniCPM5-1B-GGUF")
|
| 12 |
+
MODEL_FILE = os.environ.get("MODEL_FILE", "minicpm5-1b-Q6_K.gguf")
|
| 13 |
+
CTX_SIZE = int(os.environ.get("CTX_SIZE", "8192"))
|
| 14 |
+
PARALLEL = int(os.environ.get("PARALLEL", "2"))
|
| 15 |
+
LLAMA_PORT = int(os.environ.get("LLAMA_PORT", "8080")) # internal only
|
| 16 |
+
API_KEY = os.environ.get("LLAMA_API_KEY", "") # SET THIS as a Space secret!
|
| 17 |
+
SYSTEM_PROMPT = os.environ.get("SYSTEM_PROMPT", "You are a helpful AI assistant.")
|
| 18 |
+
|
| 19 |
+
# ===== 1. HOLD THE ZEROGPU HARDWARE (~5s of quota, once, at boot) =====
|
| 20 |
@spaces.GPU(duration=5)
|
| 21 |
+
def _hold_zerogpu():
|
| 22 |
+
print("[zerogpu] host claimed; GPU slice released, CPU+RAM stay ours.")
|
| 23 |
+
return True
|
| 24 |
+
|
| 25 |
+
_hold_zerogpu()
|
| 26 |
+
|
| 27 |
+
# ===== 2. READ THE "DYNAMIC" CPU/RAM WE ACTUALLY GOT (cgroup truth) =====
|
| 28 |
+
def effective_cpus() -> int:
|
| 29 |
+
try:
|
| 30 |
+
quota, period = Path("/sys/fs/cgroup/cpu.max").read_text().split()[:2]
|
| 31 |
+
if quota != "max":
|
| 32 |
+
return max(1, int(quota) // int(period))
|
| 33 |
+
except Exception:
|
| 34 |
+
pass
|
| 35 |
+
try:
|
| 36 |
+
return len(os.sched_getaffinity(0))
|
| 37 |
+
except Exception:
|
| 38 |
+
return os.cpu_count() or 2
|
| 39 |
+
|
| 40 |
+
def memory_limit_gb():
|
| 41 |
+
try:
|
| 42 |
+
v = Path("/sys/fs/cgroup/memory.max").read_text().strip()
|
| 43 |
+
if v != "max":
|
| 44 |
+
return round(int(v) / 1e9, 1)
|
| 45 |
+
except Exception:
|
| 46 |
+
pass
|
| 47 |
+
return None
|
| 48 |
+
|
| 49 |
+
CORES = effective_cpus()
|
| 50 |
+
print(f"[resources] effective cores: {CORES} | RAM limit: {memory_limit_gb() or '?'} GB")
|
| 51 |
+
|
| 52 |
+
# ===== 3. FETCH PREBUILT llama.cpp (seconds, zero compilation) =====
|
| 53 |
+
FALLBACK_TAG = "b8407"
|
| 54 |
+
|
| 55 |
+
def resolve_tag() -> str:
|
| 56 |
+
if LLAMA_TAG:
|
| 57 |
+
return LLAMA_TAG
|
| 58 |
+
try:
|
| 59 |
+
req = urllib.request.Request(
|
| 60 |
+
"https://api.github.com/repos/ggml-org/llama.cpp/releases/latest",
|
| 61 |
+
headers={"User-Agent": "hf-space"})
|
| 62 |
+
with urllib.request.urlopen(req, timeout=10) as r:
|
| 63 |
+
return json.load(r)["tag_name"]
|
| 64 |
+
except Exception as e:
|
| 65 |
+
print(f"[llama.cpp] latest-tag lookup failed ({e}); pinned fallback {FALLBACK_TAG}")
|
| 66 |
+
return FALLBACK_TAG
|
| 67 |
+
|
| 68 |
+
def ensure_llama_server() -> Path:
|
| 69 |
+
tag = resolve_tag()
|
| 70 |
+
root = Path.home() / ".cache" / "llamacpp" / tag
|
| 71 |
+
server = root / "build" / "bin" / "llama-server"
|
| 72 |
+
if not server.exists():
|
| 73 |
+
url = (f"https://github.com/ggml-org/llama.cpp/releases/download/"
|
| 74 |
+
f"{tag}/llama-{tag}-bin-ubuntu-x64.zip")
|
| 75 |
+
print(f"[llama.cpp] downloading {url}")
|
| 76 |
+
req = urllib.request.Request(url, headers={"User-Agent": "hf-space"})
|
| 77 |
+
with urllib.request.urlopen(req, timeout=180) as r:
|
| 78 |
+
blob = r.read()
|
| 79 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 80 |
+
with zipfile.ZipFile(io.BytesIO(blob)) as z:
|
| 81 |
+
z.extractall(root)
|
| 82 |
+
for f in (root / "build" / "bin").iterdir():
|
| 83 |
+
f.chmod(0o755)
|
| 84 |
+
return server
|
| 85 |
+
|
| 86 |
+
# ===== 4. MODEL =====
|
| 87 |
+
print(f"[model] downloading {MODEL_REPO}/{MODEL_FILE}")
|
| 88 |
+
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 89 |
+
|
| 90 |
+
# ===== 5. LAUNCH llama-server, SIZED TO THE DETECTED HARDWARE =====
|
| 91 |
+
server_bin = ensure_llama_server()
|
| 92 |
+
UPSTREAM = f"http://127.0.0.1:{LLAMA_PORT}"
|
| 93 |
+
|
| 94 |
+
env = os.environ.copy()
|
| 95 |
+
env["LD_LIBRARY_PATH"] = f"{server_bin.parent}:{env.get('LD_LIBRARY_PATH', '')}"
|
| 96 |
+
env.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
|
| 97 |
+
|
| 98 |
+
cmd = [
|
| 99 |
+
str(server_bin), "-m", model_path,
|
| 100 |
+
"--host", "127.0.0.1", "--port", str(LLAMA_PORT),
|
| 101 |
+
"-t", str(CORES), "-tb", str(CORES), # every core the cgroup gives us
|
| 102 |
+
"-c", str(CTX_SIZE),
|
| 103 |
+
"-np", str(PARALLEL), # real concurrent slots, no global lock
|
| 104 |
+
"-fa", # flash attention → much smaller KV cache
|
| 105 |
+
"--cache-reuse", "256", # KV reuse across chat turns
|
| 106 |
+
]
|
| 107 |
+
if API_KEY:
|
| 108 |
+
cmd += ["--api-key", API_KEY]
|
| 109 |
+
|
| 110 |
+
proc = subprocess.Popen(cmd, env=env)
|
| 111 |
+
|
| 112 |
+
def wait_ready(timeout=600):
|
| 113 |
+
t0 = time.time()
|
| 114 |
+
while time.time() - t0 < timeout:
|
| 115 |
+
if proc.poll() is not None:
|
| 116 |
+
raise RuntimeError(f"llama-server died early (code {proc.returncode})")
|
| 117 |
+
try:
|
| 118 |
+
if httpx.get(f"{UPSTREAM}/health", timeout=2).status_code == 200:
|
| 119 |
+
print("[llama.cpp] server ready")
|
| 120 |
+
return
|
| 121 |
+
except Exception:
|
| 122 |
+
pass
|
| 123 |
+
time.sleep(1)
|
| 124 |
+
raise TimeoutError("llama-server not ready in time")
|
| 125 |
+
|
| 126 |
+
wait_ready()
|
| 127 |
+
|
| 128 |
+
# ===== 6. GRADIO UI (same backend as the API) =====
|
| 129 |
+
from openai import OpenAI
|
| 130 |
+
oai = OpenAI(base_url=f"{UPSTREAM}/v1", api_key=API_KEY or "not-needed")
|
| 131 |
+
|
| 132 |
+
def _normalize(history):
|
| 133 |
+
msgs = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 134 |
+
for item in history:
|
| 135 |
+
if isinstance(item, dict):
|
| 136 |
+
msgs.append({"role": item["role"], "content": item["content"]})
|
| 137 |
+
else:
|
| 138 |
+
user, bot = item
|
| 139 |
+
msgs.append({"role": "user", "content": user})
|
| 140 |
+
if bot:
|
| 141 |
+
msgs.append({"role": "assistant", "content": bot})
|
| 142 |
+
return msgs
|
| 143 |
+
|
| 144 |
+
def chat(message, history):
|
| 145 |
+
stream = oai.chat.completions.create(
|
| 146 |
+
model="local",
|
| 147 |
+
messages=_normalize(history) + [{"role": "user", "content": message}],
|
| 148 |
+
stream=True, temperature=0.7, max_tokens=1024,
|
| 149 |
)
|
| 150 |
+
out = ""
|
|
|
|
| 151 |
for chunk in stream:
|
| 152 |
+
delta = chunk.choices[0].delta.content
|
| 153 |
+
if delta:
|
| 154 |
+
out += delta
|
| 155 |
+
yield out
|
|
|
|
| 156 |
|
| 157 |
with gr.Blocks() as demo:
|
| 158 |
+
gr.Markdown(
|
| 159 |
+
f"# ⚡ llama.cpp on ZeroGPU's free CPU\n"
|
| 160 |
+
f"`{MODEL_REPO}` · {CORES} threads · ctx {CTX_SIZE} · {PARALLEL} parallel slots\n\n"
|
| 161 |
+
f"**External API:** `POST /v1/chat/completions` on this Space's `*.hf.space` URL."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
)
|
| 163 |
+
gr.ChatInterface(fn=chat, examples=["Who are you?",
|
| 164 |
+
"Write a python script to reverse a string.", "Explain quantum computing."])
|
| 165 |
+
|
| 166 |
+
demo = demo.queue()
|
| 167 |
|
| 168 |
+
# ===== 7. PUBLIC /v1 PROXY — the supported way, no monkey-patch =====
|
| 169 |
+
from fastapi import FastAPI, Request
|
| 170 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 171 |
+
from fastapi.responses import Response, StreamingResponse
|
| 172 |
+
|
| 173 |
+
app = FastAPI(title="llama-cpp-proxy")
|
| 174 |
+
app.add_middleware(CORSMiddleware, allow_origins=["*"],
|
| 175 |
+
allow_methods=["*"], allow_headers=["*"])
|
| 176 |
+
_http = httpx.AsyncClient(timeout=httpx.Timeout(None))
|
| 177 |
+
|
| 178 |
+
@app.api_route("/v1/{path:path}", methods=["GET", "POST"])
|
| 179 |
+
async def v1_proxy(path: str, request: Request):
|
| 180 |
+
body = await request.body()
|
| 181 |
+
headers = {k: request.headers[k] for k in ("authorization", "content-type")
|
| 182 |
+
if k in request.headers}
|
| 183 |
+
wants_stream = False
|
| 184 |
+
if body:
|
| 185 |
+
try:
|
| 186 |
+
wants_stream = bool(json.loads(body).get("stream"))
|
| 187 |
+
except Exception:
|
| 188 |
+
pass
|
| 189 |
+
|
| 190 |
+
url = f"{UPSTREAM}/v1/{path}"
|
| 191 |
+
if request.method == "POST" and wants_stream:
|
| 192 |
+
req = _http.build_request("POST", url, content=body, headers=headers)
|
| 193 |
+
resp = await _http.send(req, stream=True)
|
| 194 |
+
async def gen():
|
|
|
|
|
|
|
| 195 |
try:
|
| 196 |
+
async for chunk in resp.aiter_raw():
|
| 197 |
+
yield chunk
|
| 198 |
+
finally:
|
| 199 |
+
await resp.aclose()
|
| 200 |
+
return StreamingResponse(gen(), status_code=resp.status_code,
|
| 201 |
+
media_type="text/event-stream")
|
| 202 |
+
|
| 203 |
+
resp = await _http.request(request.method, url, content=body or None, headers=headers)
|
| 204 |
+
return Response(content=resp.content, status_code=resp.status_code,
|
| 205 |
+
media_type=resp.headers.get("content-type", "application/json"))
|
| 206 |
+
|
| 207 |
+
app = gr.mount_gradio_app(app, demo, path="/") # mounted LAST so /v1/* wins
|
| 208 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
if __name__ == "__main__":
|
| 210 |
+
import uvicorn
|
| 211 |
+
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "7860")))
|