ice-shan commited on
Commit
6d7e24f
·
verified ·
1 Parent(s): 48d144a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +168 -0
app.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import json
3
+ import os
4
+ import subprocess
5
+ import tarfile
6
+ import time
7
+ import urllib.request
8
+ import zipfile
9
+
10
+ from fastapi import Request
11
+ from fastapi.responses import StreamingResponse
12
+ from gradio import Server
13
+ import httpx
14
+
15
+ app = Server()
16
+
17
+ try:
18
+ import spaces
19
+ HAS_SPACES = True
20
+ except ImportError:
21
+ HAS_SPACES = False
22
+
23
+ @spaces.GPU if HAS_SPACES else lambda f: f
24
+ def whygpu():
25
+ pass
26
+
27
+ def build_latest_llama_server():
28
+ binary_path = os.path.abspath("llama.cpp/build/bin/llama-server")
29
+ if os.path.exists(binary_path):
30
+ return binary_path
31
+
32
+ print("Building latest llama.cpp from master source...")
33
+
34
+ if not os.path.exists("llama.cpp"):
35
+ subprocess.run(["git", "clone", "https://github.com/ggml-org/llama.cpp.git"], check=True)
36
+ else:
37
+ subprocess.run(["git", "pull"], cwd="llama.cpp", check=True)
38
+
39
+ env = os.environ.copy()
40
+ if "/usr/local/cuda/bin" not in env.get("PATH", ""):
41
+ env["PATH"] = f"/usr/local/cuda/bin:{env.get('PATH', '')}"
42
+
43
+ cmake_cmd = [
44
+ "cmake",
45
+ "-B",
46
+ "build",
47
+ "-DCMAKE_BUILD_TYPE=Release",
48
+ "-DGGML_NATIVE=ON",
49
+ "-DGGML_OPENMP=ON",
50
+ "-DGGML_AVX512=ON",
51
+ ]
52
+
53
+ subprocess.run(cmake_cmd, cwd="llama.cpp", env=env, check=True)
54
+ subprocess.run(
55
+ ["cmake", "--build", "build", "--config", "Release", "-j", str(os.cpu_count() or 4), "--target", "llama-server"],
56
+ cwd="llama.cpp",
57
+ env=env,
58
+ check=True
59
+ )
60
+
61
+ if not os.path.exists(binary_path):
62
+ raise RuntimeError("Failed to build llama-server binary!")
63
+
64
+ return binary_path
65
+
66
+ def apathy_exe():
67
+ model_path = hf_hub_download(
68
+ repo_id="Qwen/Qwen3.8-27B",
69
+ filename="q.gguf",
70
+ )
71
+
72
+ def start_llama_server():
73
+ binary_path = build_latest_llama_server()
74
+
75
+ from huggingface_hub import hf_hub_download
76
+
77
+ model_path = hf_hub_download(
78
+ repo_id="unsloth/Qwen3.8-27B-GGUF",
79
+ filename="Qwen3.8-27B-UD-Q8_K_XL.gguf",
80
+ )
81
+
82
+ draft_path = hf_hub_download(
83
+ repo_id="unsloth/Qwen3.8-27B-GGUF",
84
+ filename="MTP/mtp-Qwen3.8-27B-Q4_0.gguf",
85
+ )
86
+
87
+ binary_dir = os.path.dirname(os.path.abspath(binary_path))
88
+ env = os.environ.copy()
89
+ env["LD_LIBRARY_PATH"] = f"{binary_dir}:{env.get('LD_LIBRARY_PATH', '')}"
90
+
91
+ cmd = [
92
+ binary_path,
93
+ "-m", model_path,
94
+ "-md", draft_path,
95
+ "--port", "8000",
96
+ "--host", "127.0.0.1",
97
+ "-t", "16",
98
+ "-tb", "16",
99
+ "-fa", "on",
100
+ "--parallel", "1",
101
+ "--spec-type", "draft-mtp",
102
+ "--spec-draft-n-max", "4",
103
+ "--cache-type-k", "q4_0",
104
+ "--cache-type-v", "q4_0",
105
+ "--jinja",
106
+ "--temp", "1.0",
107
+ "--top-p", "0.95",
108
+ "--top-k", "20",
109
+ "--min-p", "0.0",
110
+ "--presence-penalty", "0.0",
111
+ "--repeat-penalty", "1.0",
112
+ ]
113
+
114
+ process = subprocess.Popen(cmd, env=env)
115
+ time.sleep(5)
116
+ return process
117
+
118
+ @app.middleware("http")
119
+ async def proxy_middleware(request: Request, call_next):
120
+ path = request.url.path
121
+ if path.startswith("/gradio_api"):
122
+ return await call_next(request)
123
+
124
+ url = f"http://127.0.0.1:8000{path}"
125
+
126
+ headers = {
127
+ k: v for k, v in request.headers.items()
128
+ if k.lower() not in ("host", "content-length", "accept-encoding")
129
+ }
130
+ body = await request.body()
131
+
132
+ client = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=120.0))
133
+ req = client.build_request(
134
+ method=request.method,
135
+ url=url,
136
+ headers=headers,
137
+ params=request.query_params,
138
+ content=body,
139
+ )
140
+
141
+ try:
142
+ response = await client.send(req, stream=True)
143
+ except Exception as e:
144
+ await client.aclose()
145
+ return StreamingResponse(iter([f"Proxy Error: {e}".encode()]), status_code=502)
146
+
147
+ async def stream_and_close():
148
+ try:
149
+ async for chunk in response.aiter_raw():
150
+ yield chunk
151
+ finally:
152
+ await response.aclose()
153
+ await client.aclose()
154
+
155
+ res_headers = {
156
+ k: v for k, v in response.headers.items()
157
+ if k.lower() not in ("content-length", "transfer-encoding", "connection")
158
+ }
159
+
160
+ return StreamingResponse(
161
+ stream_and_close(),
162
+ status_code=response.status_code,
163
+ headers=res_headers
164
+ )
165
+
166
+ if __name__ == "__main__":
167
+ start_llama_server()
168
+ app.launch(show_error=True)