Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,44 +1,175 @@
|
|
| 1 |
-
|
| 2 |
-
from
|
| 3 |
-
import torch
|
| 4 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
|
|
|
|
| 7 |
|
| 8 |
-
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
)
|
| 15 |
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
return_tensors="pt",
|
| 24 |
-
add_generation_prompt=True
|
| 25 |
-
).to(model.device)
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
|
| 40 |
|
| 41 |
-
demo.launch(
|
| 42 |
-
server_name="0.0.0.0",
|
| 43 |
-
server_port=7860
|
| 44 |
-
)
|
|
|
|
| 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 load (CPU friendly) ----------
|
| 12 |
+
MODEL_REPO = "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF"
|
| 13 |
+
MODEL_FILE = "qwen2.5-coder-1.5b-instruct-q4_k_m.gguf"
|
| 14 |
|
| 15 |
+
print("⏬ Downloading model ...")
|
| 16 |
+
model_path = hf_hub_download(repo_id=MODEL_REPO, filename=MODEL_FILE)
|
| 17 |
+
print("✅ Loading llama.cpp ...")
|
| 18 |
+
llm = Llama(
|
| 19 |
+
model_path=model_path,
|
| 20 |
+
n_ctx=4096,
|
| 21 |
+
n_threads=int(os.getenv("LLAMA_THREADS", "2")),
|
| 22 |
+
n_batch=256,
|
| 23 |
+
verbose=False,
|
| 24 |
)
|
| 25 |
|
| 26 |
+
# ---------- Tools ----------
|
| 27 |
+
def _safe(p: str) -> Path:
|
| 28 |
+
path = (WORKSPACE / p).resolve()
|
| 29 |
+
if WORKSPACE.resolve() not in path.parents and path != WORKSPACE.resolve():
|
| 30 |
+
raise ValueError("Path escapes workspace")
|
| 31 |
+
return path
|
| 32 |
|
| 33 |
+
def read_file(path: str) -> str:
|
| 34 |
+
return _safe(path).read_text(encoding="utf-8", errors="replace")
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
+
def write_file(path: str, content: str) -> str:
|
| 37 |
+
p = _safe(path); p.parent.mkdir(parents=True, exist_ok=True)
|
| 38 |
+
p.write_text(content, encoding="utf-8")
|
| 39 |
+
return f"wrote {len(content)} bytes -> {path}"
|
| 40 |
+
|
| 41 |
+
def edit_file(path: str, find: str, replace: str) -> str:
|
| 42 |
+
p = _safe(path); txt = p.read_text(encoding="utf-8")
|
| 43 |
+
if find not in txt: return "pattern not found"
|
| 44 |
+
new = txt.replace(find, replace)
|
| 45 |
+
p.write_text(new, encoding="utf-8")
|
| 46 |
+
return f"replaced {txt.count(find)} occurrence(s) in {path}"
|
| 47 |
+
|
| 48 |
+
def delete_file(path: str) -> str:
|
| 49 |
+
p = _safe(path)
|
| 50 |
+
if p.is_dir(): shutil.rmtree(p)
|
| 51 |
+
else: p.unlink()
|
| 52 |
+
return f"deleted {path}"
|
| 53 |
+
|
| 54 |
+
def search_files(pattern: str, root: str = ".") -> str:
|
| 55 |
+
base = _safe(root)
|
| 56 |
+
hits = [str(Path(x).relative_to(WORKSPACE)) for x in glob.glob(f"{base}/**/{pattern}", recursive=True)]
|
| 57 |
+
return json.dumps(hits[:200])
|
| 58 |
+
|
| 59 |
+
def git_clone(url: str, dest: str = "") -> str:
|
| 60 |
+
name = dest or url.rstrip("/").split("/")[-1].replace(".git", "")
|
| 61 |
+
target = _safe(name)
|
| 62 |
+
if target.exists(): return f"{name} already exists"
|
| 63 |
+
gitlib.Repo.clone_from(url, target)
|
| 64 |
+
return f"cloned -> {name}"
|
| 65 |
+
|
| 66 |
+
def git_pull(repo: str) -> str:
|
| 67 |
+
r = gitlib.Repo(_safe(repo)); r.remotes.origin.pull()
|
| 68 |
+
return "pulled"
|
| 69 |
+
|
| 70 |
+
def git_push(repo: str, message: str = "update", token: str = "") -> str:
|
| 71 |
+
r = gitlib.Repo(_safe(repo))
|
| 72 |
+
r.git.add(A=True); r.index.commit(message)
|
| 73 |
+
if token:
|
| 74 |
+
url = r.remotes.origin.url.replace("https://", f"https://x-access-token:{token}@")
|
| 75 |
+
r.remotes.origin.set_url(url)
|
| 76 |
+
r.remotes.origin.push()
|
| 77 |
+
return "pushed"
|
| 78 |
+
|
| 79 |
+
def _run(cmd, cwd):
|
| 80 |
+
proc = subprocess.run(cmd, cwd=cwd, shell=True, capture_output=True, text=True, timeout=1800)
|
| 81 |
+
return f"[exit {proc.returncode}]\n{proc.stdout[-4000:]}\n{proc.stderr[-2000:]}"
|
| 82 |
+
|
| 83 |
+
def gradle_build(repo: str, task: str = "assembleDebug") -> str:
|
| 84 |
+
cwd = _safe(repo)
|
| 85 |
+
wrapper = cwd / "gradlew"
|
| 86 |
+
if wrapper.exists():
|
| 87 |
+
os.chmod(wrapper, 0o755)
|
| 88 |
+
return _run(f"./gradlew {task} --no-daemon", cwd)
|
| 89 |
+
return _run(f"gradle {task} --no-daemon", cwd)
|
| 90 |
|
| 91 |
+
def build_apk(repo: str, variant: str = "debug") -> str:
|
| 92 |
+
task = f"assemble{variant.capitalize()}"
|
| 93 |
+
log = gradle_build(repo, task)
|
| 94 |
+
apks = glob.glob(f"{_safe(repo)}/**/*.apk", recursive=True)
|
| 95 |
+
return log + "\nAPKs:\n" + "\n".join(apks)
|
| 96 |
+
|
| 97 |
+
def upload_artifact(path: str, repo_id: str, token: str, path_in_repo: str = "") -> str:
|
| 98 |
+
api = HfApi(token=token)
|
| 99 |
+
p = _safe(path)
|
| 100 |
+
api.upload_file(
|
| 101 |
+
path_or_fileobj=str(p),
|
| 102 |
+
path_in_repo=path_in_repo or p.name,
|
| 103 |
+
repo_id=repo_id,
|
| 104 |
+
repo_type="model",
|
| 105 |
)
|
| 106 |
+
return f"uploaded {p.name} -> {repo_id}"
|
| 107 |
+
|
| 108 |
+
TOOLS = {
|
| 109 |
+
"read_file": read_file, "write_file": write_file, "edit_file": edit_file,
|
| 110 |
+
"delete_file": delete_file, "search_files": search_files,
|
| 111 |
+
"git_clone": git_clone, "git_pull": git_pull, "git_push": git_push,
|
| 112 |
+
"gradle_build": gradle_build, "build_apk": build_apk,
|
| 113 |
+
"upload_artifact": upload_artifact,
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
TOOL_SPEC = """
|
| 117 |
+
Available tools (call by emitting a single JSON block: ```tool\n{"name":"...","args":{...}}\n```):
|
| 118 |
+
- read_file(path)
|
| 119 |
+
- write_file(path, content)
|
| 120 |
+
- edit_file(path, find, replace)
|
| 121 |
+
- delete_file(path)
|
| 122 |
+
- search_files(pattern, root=".")
|
| 123 |
+
- git_clone(url, dest="")
|
| 124 |
+
- git_pull(repo)
|
| 125 |
+
- git_push(repo, message="update", token="")
|
| 126 |
+
- gradle_build(repo, task="assembleDebug")
|
| 127 |
+
- build_apk(repo, variant="debug")
|
| 128 |
+
- upload_artifact(path, repo_id, token, path_in_repo="")
|
| 129 |
+
After tool result, continue. End with plain answer when done.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
SYSTEM = "You are an Android build agent. Use tools to clone, edit, build APKs, and upload artifacts. " + TOOL_SPEC
|
| 133 |
+
|
| 134 |
+
TOOL_RE = re.compile(r"```tool\s*(\{.*?\})\s*```", re.S)
|
| 135 |
+
|
| 136 |
+
def run_agent(user_msg, history, max_steps=6):
|
| 137 |
+
msgs = [{"role": "system", "content": SYSTEM}]
|
| 138 |
+
for u, a in history:
|
| 139 |
+
msgs.append({"role": "user", "content": u})
|
| 140 |
+
msgs.append({"role": "assistant", "content": a})
|
| 141 |
+
msgs.append({"role": "user", "content": user_msg})
|
| 142 |
+
|
| 143 |
+
transcript = ""
|
| 144 |
+
for _ in range(max_steps):
|
| 145 |
+
out = llm.create_chat_completion(messages=msgs, temperature=0.2, max_tokens=800)
|
| 146 |
+
reply = out["choices"][0]["message"]["content"]
|
| 147 |
+
transcript += reply + "\n"
|
| 148 |
+
m = TOOL_RE.search(reply)
|
| 149 |
+
if not m:
|
| 150 |
+
return transcript
|
| 151 |
+
try:
|
| 152 |
+
call = json.loads(m.group(1))
|
| 153 |
+
fn = TOOLS[call["name"]]
|
| 154 |
+
result = fn(**call.get("args", {}))
|
| 155 |
+
except Exception as e:
|
| 156 |
+
result = f"ERROR: {e}\n{traceback.format_exc()[-500:]}"
|
| 157 |
+
msgs.append({"role": "assistant", "content": reply})
|
| 158 |
+
msgs.append({"role": "user", "content": f"tool_result:\n{result}"})
|
| 159 |
+
transcript += f"\n[tool result]\n{result}\n"
|
| 160 |
+
return transcript
|
| 161 |
+
|
| 162 |
+
with gr.Blocks(title="Android Build Agent") as demo:
|
| 163 |
+
gr.Markdown("## 🤖 Android Build Agent (Qwen2.5-Coder + Gradle + SDK)")
|
| 164 |
+
chat = gr.Chatbot(height=500)
|
| 165 |
+
box = gr.Textbox(placeholder="e.g. clone https://github.com/.../MyApp and build debug APK")
|
| 166 |
+
state = gr.State([])
|
| 167 |
|
| 168 |
+
def respond(msg, hist):
|
| 169 |
+
ans = run_agent(msg, hist)
|
| 170 |
+
hist = hist + [(msg, ans)]
|
| 171 |
+
return "", hist, hist
|
| 172 |
|
| 173 |
+
box.submit(respond, [box, state], [box, chat, state])
|
| 174 |
|
| 175 |
+
demo.queue().launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
|
|
|
|
|