23v commited on
Commit
360dec1
·
verified ·
1 Parent(s): cb7c792

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -192
app.py DELETED
@@ -1,192 +0,0 @@
1
- from __future__ import annotations
2
- import json
3
- import os
4
- import socket
5
- import subprocess
6
- import tarfile
7
- import time
8
- import urllib.request
9
- import zipfile
10
-
11
- from fastapi import Request
12
- from fastapi.responses import StreamingResponse
13
- from gradio import Server
14
- import httpx
15
-
16
- app = Server()
17
-
18
- try:
19
- import spaces
20
- HAS_SPACES = True
21
- except ImportError:
22
- HAS_SPACES = False
23
-
24
- @spaces.GPU if HAS_SPACES else lambda f: f
25
- def whygpu():
26
- pass
27
-
28
- # Guard so llama-server (and therefore the model weights) can never be
29
- # loaded into memory more than once, even if start_llama_server() ends up
30
- # being called again (module re-import, a reload, a duplicate call, etc.).
31
- _llama_server_started = False
32
-
33
-
34
- def _is_llama_server_up(timeout: float = 1.0) -> bool:
35
- """Return True if something is already listening on the llama-server port."""
36
- try:
37
- with socket.create_connection(("127.0.0.1", 8000), timeout=timeout):
38
- return True
39
- except OSError:
40
- return False
41
-
42
-
43
- def build_latest_llama_server():
44
- binary_path = os.path.abspath("llama.cpp/build/bin/llama-server")
45
- if os.path.exists(binary_path):
46
- return binary_path
47
-
48
- print("Building latest llama.cpp from master source...")
49
-
50
- if not os.path.exists("llama.cpp"):
51
- subprocess.run(["git", "clone", "https://github.com/unslothai/llama.cpp.git"], check=True)
52
- else:
53
- subprocess.run(["git", "pull"], cwd="llama.cpp", check=True)
54
-
55
- subprocess.run(["git", "fetch", "origin", "pull/144/head:mtp"], cwd="llama.cpp", check=True)
56
- subprocess.run(["git", "checkout", "mtp"], cwd="llama.cpp", check=True)
57
-
58
- env = os.environ.copy()
59
- if "/usr/local/cuda/bin" not in env.get("PATH", ""):
60
- env["PATH"] = f"/usr/local/cuda/bin:{env.get('PATH', '')}"
61
-
62
- cmake_cmd = [
63
- "cmake",
64
- "-B",
65
- "build",
66
- "-DCMAKE_BUILD_TYPE=Release",
67
- "-DGGML_NATIVE=ON",
68
- "-DGGML_OPENMP=ON",
69
- "-DGGML_AVX512=ON",
70
- ]
71
-
72
- subprocess.run(cmake_cmd, cwd="llama.cpp", env=env, check=True)
73
- subprocess.run(
74
- ["cmake", "--build", "build", "--config", "Release", "-j", str(os.cpu_count() or 4), "--target", "llama-server"],
75
- cwd="llama.cpp",
76
- env=env,
77
- check=True
78
- )
79
-
80
- if not os.path.exists(binary_path):
81
- raise RuntimeError("Failed to build llama-server binary!")
82
-
83
- return binary_path
84
-
85
-
86
- def start_llama_server():
87
- global _llama_server_started
88
-
89
- # 1) Already started earlier in this same Python process -> do nothing.
90
- if _llama_server_started:
91
- print("start_llama_server() called again in this process - already running, skipping.")
92
- return None
93
-
94
- # 2) A llama-server (from an earlier run / another worker) is already
95
- # listening on the port -> don't spin up a second copy of the model.
96
- if _is_llama_server_up():
97
- print("Port 8000 is already serving llama-server - skipping duplicate startup.")
98
- _llama_server_started = True
99
- return None
100
-
101
- binary_path = build_latest_llama_server()
102
-
103
- from huggingface_hub import hf_hub_download
104
-
105
- model_path = hf_hub_download(
106
- repo_id="bartowski/moonshotai_Kimi-Linear-48B-A3B-Instruct-GGUF",
107
- filename="moonshotai_Kimi-Linear-48B-A3B-Instruct-Q4_K_M.gguf",
108
- )
109
-
110
- binary_dir = os.path.dirname(os.path.abspath(binary_path))
111
- env = os.environ.copy()
112
- env["LD_LIBRARY_PATH"] = f"{binary_dir}:{env.get('LD_LIBRARY_PATH', '')}"
113
-
114
- cmd = [
115
- binary_path,
116
- "-m", model_path,
117
- "--port", "8000",
118
- "--host", "127.0.0.1",
119
- "-t", "16",
120
- "-tb", "16",
121
- "-fa", "on",
122
- "--parallel", "1",
123
- "--load-mode", "dio",
124
- "--cache-type-k", "q4_0",
125
- "--cache-type-v", "q4_0",
126
- "--jinja",
127
- "--temp", "1.0",
128
- "--top-p", "0.95",
129
- "--top-k", "20",
130
- "--min-p", "0.0",
131
- "--presence-penalty", "0.0",
132
- "--repeat-penalty", "1.0",
133
- ]
134
-
135
- process = subprocess.Popen(cmd, env=env)
136
- _llama_server_started = True
137
- time.sleep(5)
138
- return process
139
-
140
-
141
- @app.middleware("http")
142
- async def proxy_middleware(request: Request, call_next):
143
- path = request.url.path
144
- if path.startswith("/gradio_api"):
145
- return await call_next(request)
146
-
147
- url = f"http://127.0.0.1:8000{path}"
148
-
149
- headers = {
150
- k: v for k, v in request.headers.items()
151
- if k.lower() not in ("host", "content-length", "accept-encoding")
152
- }
153
- body = await request.body()
154
-
155
- client = httpx.AsyncClient(timeout=httpx.Timeout(600.0, connect=120.0))
156
- req = client.build_request(
157
- method=request.method,
158
- url=url,
159
- headers=headers,
160
- params=request.query_params,
161
- content=body,
162
- )
163
-
164
- try:
165
- response = await client.send(req, stream=True)
166
- except Exception as e:
167
- await client.aclose()
168
- return StreamingResponse(iter([f"Proxy Error: {e}".encode()]), status_code=502)
169
-
170
- async def stream_and_close():
171
- try:
172
- async for chunk in response.aiter_raw():
173
- yield chunk
174
- finally:
175
- await response.aclose()
176
- await client.aclose()
177
-
178
- res_headers = {
179
- k: v for k, v in response.headers.items()
180
- if k.lower() not in ("content-length", "transfer-encoding", "connection")
181
- }
182
-
183
- return StreamingResponse(
184
- stream_and_close(),
185
- status_code=response.status_code,
186
- headers=res_headers
187
- )
188
-
189
-
190
- if __name__ == "__main__":
191
- start_llama_server()
192
- app.launch(show_error=True)