Spaces:
Sleeping
Sleeping
fix: remove ssr_mode (not supported in gradio 4.44.1)
Browse files
app.py
CHANGED
|
@@ -1,125 +1,270 @@
|
|
| 1 |
-
import os, re, json, shutil, subprocess, glob, traceback
|
| 2 |
from pathlib import Path
|
| 3 |
import gradio as gr
|
| 4 |
from huggingface_hub import hf_hub_download, HfApi
|
| 5 |
-
from llama_cpp import Llama
|
| 6 |
import git as gitlib
|
| 7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
WORKSPACE = Path("/workspace")
|
| 9 |
-
WORKSPACE.mkdir(exist_ok=True)
|
| 10 |
|
|
|
|
| 11 |
MODEL_REPO = "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF"
|
| 12 |
MODEL_FILE = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
|
|
|
| 21 |
path = (WORKSPACE / p).resolve()
|
| 22 |
if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
|
| 23 |
raise ValueError("Path escapes workspace")
|
| 24 |
return path
|
| 25 |
|
| 26 |
-
|
| 27 |
-
def
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
return f"replaced {txt.count(find)} occurrence(s) in {path}"
|
| 35 |
-
|
|
|
|
|
|
|
| 36 |
p = _safe(path)
|
| 37 |
-
if p.is_dir():
|
| 38 |
-
|
|
|
|
|
|
|
| 39 |
return f"deleted {path}"
|
| 40 |
-
|
|
|
|
|
|
|
| 41 |
base = _safe(root)
|
| 42 |
-
hits = [str(Path(x).relative_to(WORKSPACE))
|
|
|
|
| 43 |
return json.dumps(hits[:200])
|
| 44 |
-
|
| 45 |
-
|
|
|
|
|
|
|
| 46 |
target = _safe(name)
|
| 47 |
-
if target.exists():
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
if token:
|
| 54 |
url = r.remotes.origin.url.replace("https://", f"https://x-access-token:{token}@")
|
| 55 |
r.remotes.origin.set_url(url)
|
| 56 |
-
r.remotes.origin.push()
|
|
|
|
|
|
|
|
|
|
| 57 |
def _run(cmd, cwd):
|
| 58 |
-
proc = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True,
|
|
|
|
| 59 |
return f"[exit {proc.returncode}]\n{proc.stdout[-4000:]}\n{proc.stderr[-2000:]}"
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
| 62 |
if wrapper.exists():
|
| 63 |
-
os.chmod(wrapper, 0o755)
|
|
|
|
| 64 |
return _run(f"gradle {task} --no-daemon", cwd)
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
| 67 |
apks = glob.glob(f"{_safe(repo)}/**/*.apk", recursive=True)
|
| 68 |
return log + "\nAPKs:\n" + "\n".join(apks)
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
return f"uploaded {p.name} -> {repo_id}"
|
| 74 |
|
| 75 |
-
TOOLS = {"read_file":read_file,"write_file":write_file,"edit_file":edit_file,
|
| 76 |
-
"delete_file":delete_file,"search_files":search_files,"git_clone":git_clone,
|
| 77 |
-
"git_pull":git_pull,"git_push":git_push,"gradle_build":gradle_build,
|
| 78 |
-
"build_apk":build_apk,"upload_artifact":upload_artifact}
|
| 79 |
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
TOOL_RE = re.compile(r"```tool\s*(\{.*?\})\s*```", re.S)
|
| 85 |
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
transcript = ""
|
| 93 |
-
for _ in range(
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
| 96 |
transcript += reply + "\n"
|
| 97 |
m = TOOL_RE.search(reply)
|
| 98 |
if not m:
|
| 99 |
-
return transcript
|
| 100 |
try:
|
| 101 |
call = json.loads(m.group(1))
|
| 102 |
-
|
|
|
|
| 103 |
except Exception as e:
|
| 104 |
-
result = f"ERROR: {e}\n{traceback.format_exc()[-
|
| 105 |
-
msgs.append({"role":"assistant","content":reply})
|
| 106 |
-
msgs.append({"role":"user","content":f"tool_result:\n{result}"})
|
| 107 |
transcript += f"\n[tool result]\n{result}\n"
|
| 108 |
-
return transcript
|
| 109 |
|
|
|
|
|
|
|
| 110 |
with gr.Blocks(title="Android Build Agent") as demo:
|
| 111 |
-
gr.Markdown("## Android Build Agent (Qwen2.5-Coder + Gradle + SDK)")
|
| 112 |
-
|
| 113 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 114 |
clear = gr.Button("Clear")
|
| 115 |
-
state = gr.State([])
|
| 116 |
|
| 117 |
-
def respond(
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
|
| 122 |
-
|
| 123 |
-
clear.click(lambda: (
|
| 124 |
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, re, json, shutil, subprocess, glob, traceback, threading
|
| 2 |
from pathlib import Path
|
| 3 |
import gradio as gr
|
| 4 |
from huggingface_hub import hf_hub_download, HfApi
|
|
|
|
| 5 |
import git as gitlib
|
| 6 |
|
| 7 |
+
# llama_cpp is imported lazily inside the loader so a slow/failed model
|
| 8 |
+
# download never blocks the web server from binding to the port (which is
|
| 9 |
+
# what previously caused the Space to crash with RUNTIME_ERROR before the
|
| 10 |
+
# UI was ever served).
|
| 11 |
+
Llama = None
|
| 12 |
+
|
| 13 |
WORKSPACE = Path("/workspace")
|
| 14 |
+
WORKSPACE.mkdir(parents=True, exist_ok=True)
|
| 15 |
|
| 16 |
+
# ---------- Model load (CPU friendly, lazy + thread-safe) ----------
|
| 17 |
MODEL_REPO = "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF"
|
| 18 |
MODEL_FILE = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
|
| 19 |
|
| 20 |
+
_llm = None
|
| 21 |
+
_llm_lock = threading.Lock()
|
| 22 |
+
_llm_error = None
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def get_llm():
|
| 26 |
+
"""Load the model on first use. Returns the Llama instance or raises."""
|
| 27 |
+
global _llm, _llm_error, Llama
|
| 28 |
+
if _llm is not None:
|
| 29 |
+
return _llm
|
| 30 |
+
with _llm_lock:
|
| 31 |
+
if _llm is not None:
|
| 32 |
+
return _llm
|
| 33 |
+
try:
|
| 34 |
+
if Llama is None:
|
| 35 |
+
from llama_cpp import Llama as _LlamaCls
|
| 36 |
+
Llama = _LlamaCls
|
| 37 |
+
print("⏬ Downloading model ...", flush=True)
|
| 38 |
+
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 39 |
+
print("✅ Loading llama.cpp ...", flush=True)
|
| 40 |
+
_llm = Llama(
|
| 41 |
+
model_path=model_path,
|
| 42 |
+
n_ctx=4096,
|
| 43 |
+
n_threads=int(os.getenv("LLAMA_THREADS", "2")),
|
| 44 |
+
n_batch=256,
|
| 45 |
+
verbose=False,
|
| 46 |
+
)
|
| 47 |
+
_llm_error = None
|
| 48 |
+
print("✅ Model ready.", flush=True)
|
| 49 |
+
return _llm
|
| 50 |
+
except Exception as e: # noqa
|
| 51 |
+
_llm_error = f"{e}\n{traceback.format_exc()[-800:]}"
|
| 52 |
+
print("❌ Model load failed:\n" + _llm_error, flush=True)
|
| 53 |
+
raise
|
| 54 |
+
|
| 55 |
|
| 56 |
+
# ---------- Tools ----------
|
| 57 |
+
def _safe(p: str) -> Path:
|
| 58 |
path = (WORKSPACE / p).resolve()
|
| 59 |
if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
|
| 60 |
raise ValueError("Path escapes workspace")
|
| 61 |
return path
|
| 62 |
|
| 63 |
+
|
| 64 |
+
def read_file(path: str) -> str:
|
| 65 |
+
return _safe(path).read_text(encoding="utf-8", errors="replace")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def write_file(path: str, content: str) -> str:
|
| 69 |
+
p = _safe(path)
|
| 70 |
+
p.parent.mkdir(parents=True, exist_ok=True)
|
| 71 |
+
p.write_text(content, encoding="utf-8")
|
| 72 |
+
return f"wrote {len(content)} bytes -> {path}"
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def edit_file(path: str, find: str, replace: str) -> str:
|
| 76 |
+
p = _safe(path)
|
| 77 |
+
txt = p.read_text(encoding="utf-8")
|
| 78 |
+
if find not in txt:
|
| 79 |
+
return "pattern not found"
|
| 80 |
+
new = txt.replace(find, replace)
|
| 81 |
+
p.write_text(new, encoding="utf-8")
|
| 82 |
return f"replaced {txt.count(find)} occurrence(s) in {path}"
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def delete_file(path: str) -> str:
|
| 86 |
p = _safe(path)
|
| 87 |
+
if p.is_dir():
|
| 88 |
+
shutil.rmtree(p)
|
| 89 |
+
else:
|
| 90 |
+
p.unlink()
|
| 91 |
return f"deleted {path}"
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def search_files(pattern: str, root: str = ".") -> str:
|
| 95 |
base = _safe(root)
|
| 96 |
+
hits = [str(Path(x).relative_to(WORKSPACE))
|
| 97 |
+
for x in glob.glob(f"{base}/**/{pattern}", recursive=True)]
|
| 98 |
return json.dumps(hits[:200])
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def git_clone(url: str, dest: str = "") -> str:
|
| 102 |
+
name = dest or url.rstrip("/").split("/")[-1].replace(".git", "")
|
| 103 |
target = _safe(name)
|
| 104 |
+
if target.exists():
|
| 105 |
+
return f"{name} already exists"
|
| 106 |
+
gitlib.Repo.clone_from(url, target)
|
| 107 |
+
return f"cloned -> {name}"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def git_pull(repo: str) -> str:
|
| 111 |
+
r = gitlib.Repo(_safe(repo))
|
| 112 |
+
r.remotes.origin.pull()
|
| 113 |
+
return "pulled"
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def git_push(repo: str, message: str = "update", token: str = "") -> str:
|
| 117 |
+
r = gitlib.Repo(_safe(repo))
|
| 118 |
+
r.git.add(A=True)
|
| 119 |
+
r.index.commit(message)
|
| 120 |
if token:
|
| 121 |
url = r.remotes.origin.url.replace("https://", f"https://x-access-token:{token}@")
|
| 122 |
r.remotes.origin.set_url(url)
|
| 123 |
+
r.remotes.origin.push()
|
| 124 |
+
return "pushed"
|
| 125 |
+
|
| 126 |
+
|
| 127 |
def _run(cmd, cwd):
|
| 128 |
+
proc = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True,
|
| 129 |
+
text=True, timeout=1800)
|
| 130 |
return f"[exit {proc.returncode}]\n{proc.stdout[-4000:]}\n{proc.stderr[-2000:]}"
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def gradle_build(repo: str, task: str = "assembleDebug") -> str:
|
| 134 |
+
cwd = _safe(repo)
|
| 135 |
+
wrapper = cwd / "gradlew"
|
| 136 |
if wrapper.exists():
|
| 137 |
+
os.chmod(wrapper, 0o755)
|
| 138 |
+
return _run(f"./gradlew {task} --no-daemon", cwd)
|
| 139 |
return _run(f"gradle {task} --no-daemon", cwd)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def build_apk(repo: str, variant: str = "debug") -> str:
|
| 143 |
+
task = f"assemble{variant.capitalize()}"
|
| 144 |
+
log = gradle_build(repo, task)
|
| 145 |
apks = glob.glob(f"{_safe(repo)}/**/*.apk", recursive=True)
|
| 146 |
return log + "\nAPKs:\n" + "\n".join(apks)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def upload_artifact(path: str, repo_id: str, token: str, path_in_repo: str = "") -> str:
|
| 150 |
+
api = HfApi(token=token)
|
| 151 |
+
p = _safe(path)
|
| 152 |
+
api.upload_file(
|
| 153 |
+
path_or_fileobj=str(p),
|
| 154 |
+
path_in_repo=path_in_repo or p.name,
|
| 155 |
+
repo_id=repo_id,
|
| 156 |
+
repo_type="model",
|
| 157 |
+
)
|
| 158 |
return f"uploaded {p.name} -> {repo_id}"
|
| 159 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
TOOLS = {
|
| 162 |
+
"read_file": read_file, "write_file": write_file, "edit_file": edit_file,
|
| 163 |
+
"delete_file": delete_file, "search_files": search_files,
|
| 164 |
+
"git_clone": git_clone, "git_pull": git_pull, "git_push": git_push,
|
| 165 |
+
"gradle_build": gradle_build, "build_apk": build_apk,
|
| 166 |
+
"upload_artifact": upload_artifact,
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
TOOL_SPEC = """
|
| 170 |
+
Available tools (call by emitting a single JSON block: ```tool
|
| 171 |
+
{"name":"...","args":{...}}
|
| 172 |
+
```):
|
| 173 |
+
- read_file(path)
|
| 174 |
+
- write_file(path, content)
|
| 175 |
+
- edit_file(path, find, replace)
|
| 176 |
+
- delete_file(path)
|
| 177 |
+
- search_files(pattern, root=".")
|
| 178 |
+
- git_clone(url, dest="")
|
| 179 |
+
- git_pull(repo)
|
| 180 |
+
- git_push(repo, message="update", token="")
|
| 181 |
+
- gradle_build(repo, task="assembleDebug")
|
| 182 |
+
- build_apk(repo, variant="debug")
|
| 183 |
+
- upload_artifact(path, repo_id, token, path_in_repo="")
|
| 184 |
+
After tool result, continue. End with plain answer when done.
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
SYSTEM = ("You are an Android build agent. Use tools to clone, edit, build APKs, "
|
| 188 |
+
"and upload artifacts. " + TOOL_SPEC)
|
| 189 |
+
|
| 190 |
TOOL_RE = re.compile(r"```tool\s*(\{.*?\})\s*```", re.S)
|
| 191 |
|
| 192 |
+
|
| 193 |
+
def run_agent(user_msg, history, max_steps=6):
|
| 194 |
+
"""history is a list of OpenAI-style {role, content} dicts (type='messages')."""
|
| 195 |
+
msgs = [{"role": "system", "content": SYSTEM}]
|
| 196 |
+
for item in history or []:
|
| 197 |
+
if isinstance(item, dict) and item.get("role") in ("user", "assistant"):
|
| 198 |
+
content = item.get("content")
|
| 199 |
+
if content:
|
| 200 |
+
msgs.append({"role": item["role"], "content": str(content)})
|
| 201 |
+
msgs.append({"role": "user", "content": user_msg})
|
| 202 |
+
|
| 203 |
+
try:
|
| 204 |
+
llm = get_llm()
|
| 205 |
+
except Exception:
|
| 206 |
+
return ("⚠️ Model is not available yet. It may still be downloading on first "
|
| 207 |
+
"boot, or the download failed.\n\n"
|
| 208 |
+
f"Details:\n{_llm_error or 'unknown error'}")
|
| 209 |
+
|
| 210 |
transcript = ""
|
| 211 |
+
for _ in range(max_steps):
|
| 212 |
+
try:
|
| 213 |
+
out = llm.create_chat_completion(messages=msgs, temperature=0.2, max_tokens=800)
|
| 214 |
+
reply = out["choices"][0]["message"]["content"]
|
| 215 |
+
except Exception as e:
|
| 216 |
+
return transcript + f"\n⚠️ Inference error: {e}"
|
| 217 |
transcript += reply + "\n"
|
| 218 |
m = TOOL_RE.search(reply)
|
| 219 |
if not m:
|
| 220 |
+
return transcript
|
| 221 |
try:
|
| 222 |
call = json.loads(m.group(1))
|
| 223 |
+
fn = TOOLS[call["name"]]
|
| 224 |
+
result = fn(**call.get("args", {}))
|
| 225 |
except Exception as e:
|
| 226 |
+
result = f"ERROR: {e}\n{traceback.format_exc()[-500:]}"
|
| 227 |
+
msgs.append({"role": "assistant", "content": reply})
|
| 228 |
+
msgs.append({"role": "user", "content": f"tool_result:\n{result}"})
|
| 229 |
transcript += f"\n[tool result]\n{result}\n"
|
| 230 |
+
return transcript
|
| 231 |
|
| 232 |
+
|
| 233 |
+
# ---------- UI ----------
|
| 234 |
with gr.Blocks(title="Android Build Agent") as demo:
|
| 235 |
+
gr.Markdown("## 🤖 Android Build Agent (Qwen2.5-Coder + Gradle + SDK)")
|
| 236 |
+
|
| 237 |
+
# type="messages" avoids the deprecated tuple format that triggered the
|
| 238 |
+
# "unhashable type: 'dict'" template crash in earlier builds.
|
| 239 |
+
chat = gr.Chatbot(height=500, type="messages", show_copy_button=True)
|
| 240 |
+
box = gr.Textbox(
|
| 241 |
+
placeholder="e.g. clone https://github.com/.../MyApp and build debug APK",
|
| 242 |
+
show_label=False,
|
| 243 |
+
)
|
| 244 |
clear = gr.Button("Clear")
|
|
|
|
| 245 |
|
| 246 |
+
def respond(msg, history):
|
| 247 |
+
history = history or []
|
| 248 |
+
if not msg or not msg.strip():
|
| 249 |
+
return "", history
|
| 250 |
+
ans = run_agent(msg, history)
|
| 251 |
+
history = history + [
|
| 252 |
+
{"role": "user", "content": msg},
|
| 253 |
+
{"role": "assistant", "content": ans},
|
| 254 |
+
]
|
| 255 |
+
return "", history
|
| 256 |
|
| 257 |
+
box.submit(respond, [box, chat], [box, chat])
|
| 258 |
+
clear.click(lambda: ("", []), None, [box, chat])
|
| 259 |
|
| 260 |
+
# ---------- Launch (HF Docker Space correct config) ----------
|
| 261 |
+
# - server_name 0.0.0.0 + the port HF injects via $PORT (fallback 7860)
|
| 262 |
+
# - NO share=True (Docker Spaces are reachable through the HF proxy)
|
| 263 |
+
# - type="messages" Chatbot avoids the Jinja "unhashable dict" crash
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
port = int(os.getenv("PORT", "7860"))
|
| 266 |
+
demo.queue(max_size=20).launch(
|
| 267 |
+
server_name="0.0.0.0",
|
| 268 |
+
server_port=port,
|
| 269 |
+
show_error=True,
|
| 270 |
+
)
|