File size: 4,843 Bytes
264b8a6 d9ee5f7 264b8a6 d9ee5f7 264b8a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | from __future__ import annotations
import json
import os
import subprocess
import tarfile
import time
import urllib.request
import zipfile
from fastapi import Request
from fastapi.responses import StreamingResponse
from gradio import Server
import httpx
app = Server()
try:
import spaces
HAS_SPACES = True
except ImportError:
HAS_SPACES = False
@spaces.GPU if HAS_SPACES else lambda f: f
def whygpu():
pass
def build_latest_llama_server():
binary_path = os.path.abspath("llama.cpp/build/bin/llama-server")
if os.path.exists(binary_path):
return binary_path
print("Building latest llama.cpp from master source...")
if not os.path.exists("llama.cpp"):
subprocess.run(["git", "clone", "https://github.com/unslothai/llama.cpp.git"], check=True)
else:
subprocess.run(["git", "pull"], cwd="llama.cpp", check=True)
subprocess.run(["git", "fetch", "origin", "pull/144/head:mtp"], cwd="llama.cpp", check=True)
subprocess.run(["git", "checkout", "mtp"], cwd="llama.cpp", check=True)
env = os.environ.copy()
if "/usr/local/cuda/bin" not in env.get("PATH", ""):
env["PATH"] = f"/usr/local/cuda/bin:{env.get('PATH', '')}"
cmake_cmd = [
"cmake",
"-B",
"build",
"-DCMAKE_BUILD_TYPE=Release",
"-DGGML_NATIVE=ON",
"-DGGML_OPENMP=ON",
"-DGGML_AVX512=ON",
]
subprocess.run(cmake_cmd, cwd="llama.cpp", env=env, check=True)
subprocess.run(
["cmake", "--build", "build", "--config", "Release", "-j", str(os.cpu_count() or 4), "--target", "llama-server"],
cwd="llama.cpp",
env=env,
check=True
)
if not os.path.exists(binary_path):
raise RuntimeError("Failed to build llama-server binary!")
return binary_path
def apathy_exe():
model_path = hf_hub_download(
repo_id="Qwen/Qwen3.8-Flash-Next",
filename="q.gguf",
)
def start_llama_server():
binary_path = build_latest_llama_server()
from huggingface_hub import hf_hub_download
model_path = None
for i in range(1,34):
mp = hf_hub_download(
repo_id="AtomicChat/Qwen3.8-Flash-Next-GGUF",
filename="Qwen3.8-Flash-Next-AD-4.27bpw-Q4_K_M-M64/Qwen3.8-Flash-Next-AD-4.27bpw-Q4_K_M-M64-{}-of-00033.gguf".format(str(i).zfill(5))
)
if not model_path:
model_path = mp
mmproj_path = hf_hub_download(
repo_id="AtomicChat/Qwen3.8-Flash-Next-GGUF",
filename="mmproj-Qwen3.8-Flash-Next-F16.gguf",
)
binary_dir = os.path.dirname(os.path.abspath(binary_path))
env = os.environ.copy()
env["LD_LIBRARY_PATH"] = f"{binary_dir}:{env.get('LD_LIBRARY_PATH', '')}"
cmd = [
binary_path,
"-m", model_path,
"-mm", mmproj_path,
#"-md", draft_path,
"--port", "8000",
"--host", "127.0.0.1",
"-t", "16",
"-tb", "16",
"-fa", "on",
"--parallel", "1",
"--load-mode", "dio",
"--cache-type-k", "q4_0",
"--cache-type-v", "q4_0",
"--jinja",
"--temp", "1.0",
"--top-p", "0.95",
"--top-k", "20",
"--min-p", "0.0",
"--presence-penalty", "0.0",
"--repeat-penalty", "1.0",
]
process = subprocess.Popen(cmd, env=env)
time.sleep(5)
return process
@app.middleware("http")
async def proxy_middleware(request: Request, call_next):
path = request.url.path
if path.startswith("/gradio_api"):
return await call_next(request)
url = f"http://127.0.0.1:8000{path}"
headers = {
k: v for k, v in request.headers.items()
if k.lower() not in ("host", "content-length", "accept-encoding")
}
body = await request.body()
client = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=120.0))
req = client.build_request(
method=request.method,
url=url,
headers=headers,
params=request.query_params,
content=body,
)
try:
response = await client.send(req, stream=True)
except Exception as e:
await client.aclose()
return StreamingResponse(iter([f"Proxy Error: {e}".encode()]), status_code=502)
async def stream_and_close():
try:
async for chunk in response.aiter_raw():
yield chunk
finally:
await response.aclose()
await client.aclose()
res_headers = {
k: v for k, v in response.headers.items()
if k.lower() not in ("content-length", "transfer-encoding", "connection")
}
return StreamingResponse(
stream_and_close(),
status_code=response.status_code,
headers=res_headers
)
if __name__ == "__main__":
start_llama_server()
app.launch(show_error=True) |