Spaces:
Sleeping
Sleeping
Create app py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183from __future__ import annotationsimport jsonimport osimport subprocessimport tarfileimport timeimport urllib.requestimport zipfile
from fastapi import Requestfrom fastapi.responses import StreamingResponsefrom gradio import Serverimport httpx
app = Server()
try: import spaces HAS_SPACES = Trueexcept ImportError: HAS_SPACES = False
@spaces.GPU if HAS_SPACES else lambda f: fdef 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/ggml-org/llama.cpp.git"], check=True) else: subprocess.run(["git", "pull"], 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-27B", filename="q.gguf", )
def start_llama_server(): binary_path = build_latest_llama_server()
from huggingface_hub import hf_hub_download
model_path = hf_hub_download( repo_id="unsloth/Qwen3.8-Flash-Next-GGUF", filename="UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00001-of-00004.gguf", )
model_path2 = hf_hub_download( repo_id="unsloth/Qwen3.8-Flash-Next-GGUF", filename="UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00002-of-00004.gguf", )
model_path3 = hf_hub_download( repo_id="unsloth/Qwen3.8-Flash-Next-GGUF", filename="UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00003-of-00004.gguf", ) model_path4 = hf_hub_download( repo_id="unsloth/Qwen3.8-Flash-Next-GGUF", filename="UD-Q4_K_XL/Qwen3.8-Flash-Next-UD-Q4_K_XL-00004-of-00004.gguf", )
#draft_path = hf_hub_download( # repo_id="unsloth/Qwen3.8-27B-GGUF", # filename="MTP/mtp-Qwen3.8-27B-Q4_0.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, "-md", draft_path, "--port", "8000", "--host", "127.0.0.1", "-t", "16", "-tb", "16", "-fa", "on", "--parallel", "1", "--spec-type", "draft-mtp", "--spec-draft-n-max", "4", "--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)app pyAdded+183