Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,411 +1,143 @@
|
|
| 1 |
-
"""
|
| 2 |
-
GenBuddy β Intelligent App Builder (Hugging Face Gradio Space)
|
| 3 |
-
|
| 4 |
-
Features:
|
| 5 |
-
- Name & gender customization + memory
|
| 6 |
-
- Detects framework from natural language or explicit pick
|
| 7 |
-
- Generates Full (runnable) or Lightweight project scaffolds for:
|
| 8 |
-
React, Node/Express, Flask, Django, .NET (C#)
|
| 9 |
-
- Accepts uploaded files to include in project
|
| 10 |
-
- Basic code analysis and diagnostics
|
| 11 |
-
- Packages project as downloadable zip
|
| 12 |
-
- Keeps templates for repeated tasks (auto-apply on repeat)
|
| 13 |
-
"""
|
| 14 |
-
|
| 15 |
import gradio as gr
|
| 16 |
import os
|
| 17 |
-
import
|
|
|
|
| 18 |
import json
|
| 19 |
-
import
|
| 20 |
-
import zipfile
|
| 21 |
import tempfile
|
| 22 |
from datetime import datetime
|
| 23 |
-
from
|
| 24 |
-
|
| 25 |
-
# -------------- Persistence (simple JSON memory) --------------
|
| 26 |
-
MEMORY_FN = "genbuddy_memory.json"
|
| 27 |
-
if os.path.exists(MEMORY_FN):
|
| 28 |
-
try:
|
| 29 |
-
with open(MEMORY_FN, "r", encoding="utf-8") as f:
|
| 30 |
-
MEMORY = json.load(f)
|
| 31 |
-
except Exception:
|
| 32 |
-
MEMORY = {}
|
| 33 |
-
else:
|
| 34 |
-
MEMORY = {}
|
| 35 |
-
|
| 36 |
-
def save_memory():
|
| 37 |
-
with open(MEMORY_FN, "w", encoding="utf-8") as f:
|
| 38 |
-
json.dump(MEMORY, f, indent=2)
|
| 39 |
-
|
| 40 |
-
def ensure_user(user_id="default"):
|
| 41 |
-
if user_id not in MEMORY:
|
| 42 |
-
MEMORY[user_id] = {
|
| 43 |
-
"name": "GenBuddy",
|
| 44 |
-
"gender": "female",
|
| 45 |
-
"preferences": {"tone": "friendly", "verbosity": "medium"},
|
| 46 |
-
"templates": {},
|
| 47 |
-
"history": []
|
| 48 |
-
}
|
| 49 |
-
save_memory()
|
| 50 |
-
|
| 51 |
-
# -------------- Utilities --------------
|
| 52 |
-
def nowtag():
|
| 53 |
-
return datetime.now().strftime("%Y%m%d%H%M%S")
|
| 54 |
-
|
| 55 |
-
def zip_folder(src_dir, out_path):
|
| 56 |
-
with zipfile.ZipFile(out_path, "w", zipfile.ZIP_DEFLATED) as zf:
|
| 57 |
-
for root, _, files in os.walk(src_dir):
|
| 58 |
-
for f in files:
|
| 59 |
-
full = os.path.join(root, f)
|
| 60 |
-
arc = os.path.relpath(full, src_dir)
|
| 61 |
-
zf.write(full, arc)
|
| 62 |
-
return out_path
|
| 63 |
-
|
| 64 |
-
def write_file(path, content, mode="w"):
|
| 65 |
-
os.makedirs(os.path.dirname(path), exist_ok=True)
|
| 66 |
-
with open(path, mode, encoding="utf-8") as f:
|
| 67 |
-
f.write(content)
|
| 68 |
-
|
| 69 |
-
def detect_framework_from_text(text):
|
| 70 |
-
t = text.lower()
|
| 71 |
-
mapping = {
|
| 72 |
-
"react": ["react", "create react", "vite react", "next.js", "next js"],
|
| 73 |
-
"node": ["node", "express", "expressjs"],
|
| 74 |
-
"flask": ["flask", "python flask"],
|
| 75 |
-
"django": ["django", "python django"],
|
| 76 |
-
"dotnet": ["dotnet", ".net", "c#", "csharp", "asp.net"],
|
| 77 |
-
"react_native": ["react native", "react-native"],
|
| 78 |
-
"flutter": ["flutter"]
|
| 79 |
-
}
|
| 80 |
-
for key, keywords in mapping.items():
|
| 81 |
-
for k in keywords:
|
| 82 |
-
if k in t:
|
| 83 |
-
return key
|
| 84 |
-
return None
|
| 85 |
-
|
| 86 |
-
def detect_language_from_filename(filename):
|
| 87 |
-
ext = Path(filename).suffix.lower()
|
| 88 |
-
return {
|
| 89 |
-
".py": "python",
|
| 90 |
-
".js": "javascript",
|
| 91 |
-
".ts": "typescript",
|
| 92 |
-
".cs": "csharp",
|
| 93 |
-
".java": "java",
|
| 94 |
-
".html": "html",
|
| 95 |
-
".css": "css",
|
| 96 |
-
".json": "json"
|
| 97 |
-
}.get(ext, "unknown")
|
| 98 |
-
|
| 99 |
-
def analyze_uploaded_file_bytes(name, bts):
|
| 100 |
-
try:
|
| 101 |
-
txt = bts.decode("utf-8", errors="ignore")
|
| 102 |
-
except:
|
| 103 |
-
return {"name": name, "error": "Could not decode file"}
|
| 104 |
-
lines = txt.splitlines()
|
| 105 |
-
stats = {"name": name, "lines": len(lines), "empty": sum(1 for l in lines if not l.strip())}
|
| 106 |
-
stats["language"] = detect_language_from_filename(name)
|
| 107 |
-
# simple heuristics:
|
| 108 |
-
stats["functions"] = sum(1 for l in lines if re.search(r"\bdef\b|\bfunction\b|\bclass\b", l))
|
| 109 |
-
stats["has_imports"] = bool(re.search(r"\bimport\b|\brequire\b|\busing\b", txt))
|
| 110 |
-
return stats
|
| 111 |
-
|
| 112 |
-
# -------------- Project Generators --------------
|
| 113 |
-
def gen_react_full(target_dir, app_name="genbuddy-app"):
|
| 114 |
-
# package.json
|
| 115 |
-
package = {
|
| 116 |
-
"name": app_name,
|
| 117 |
-
"version": "0.1.0",
|
| 118 |
-
"private": True,
|
| 119 |
-
"scripts": {
|
| 120 |
-
"start": "vite",
|
| 121 |
-
"build": "vite build",
|
| 122 |
-
"dev": "vite"
|
| 123 |
-
},
|
| 124 |
-
"dependencies": {
|
| 125 |
-
"react": "^18.2.0",
|
| 126 |
-
"react-dom": "^18.2.0"
|
| 127 |
-
},
|
| 128 |
-
"devDependencies": {
|
| 129 |
-
"vite": "^5.0.0"
|
| 130 |
-
}
|
| 131 |
-
}
|
| 132 |
-
write_file(os.path.join(target_dir, "package.json"), json.dumps(package, indent=2))
|
| 133 |
-
write_file(os.path.join(target_dir, "index.html"),
|
| 134 |
-
"<!doctype html><html><head><meta charset='utf-8'><title>GenBuddy React</title></head><body><div id='root'></div><script type='module' src='/src/main.jsx'></script></body></html>")
|
| 135 |
-
write_file(os.path.join(target_dir, "src", "main.jsx"),
|
| 136 |
-
"import React from 'react';\nimport { createRoot } from 'react-dom/client';\nimport App from './App';\ncreateRoot(document.getElementById('root')).render(<App/>);")
|
| 137 |
-
write_file(os.path.join(target_dir, "src", "App.jsx"),
|
| 138 |
-
"export default function App(){return (<div style={{fontFamily:'system-ui',padding:24}}> <h1>GenBuddy React App</h1><p>Welcome β scaffold generated by GenBuddy.</p></div>)}")
|
| 139 |
-
write_file(os.path.join(target_dir, "README.md"),
|
| 140 |
-
"This is a Vite + React scaffold generated by GenBuddy. Install with `npm install` and run `npm run dev`.")
|
| 141 |
-
|
| 142 |
-
def gen_react_light(target_dir, app_name="genbuddy-app"):
|
| 143 |
-
# Single HTML with CDN React (lightweight)
|
| 144 |
-
html = """<!doctype html>
|
| 145 |
-
<html>
|
| 146 |
-
<head><meta charset="utf-8"><title>GenBuddy React (Light)</title></head>
|
| 147 |
-
<body>
|
| 148 |
-
<div id="root"></div>
|
| 149 |
-
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
|
| 150 |
-
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
|
| 151 |
-
<script>
|
| 152 |
-
const e = React.createElement;
|
| 153 |
-
function App(){ return e('div', {style:{fontFamily:'system-ui', padding:20}}, e('h1', null, 'GenBuddy Light React'), e('p', null, 'This is a lightweight scaffold using CDN React.'))}
|
| 154 |
-
ReactDOM.createRoot(document.getElementById('root')).render(e(App));
|
| 155 |
-
</script>
|
| 156 |
-
</body>
|
| 157 |
-
</html>"""
|
| 158 |
-
write_file(os.path.join(target_dir, "index.html"), html)
|
| 159 |
-
|
| 160 |
-
def gen_node_express_full(target_dir, app_name="genbuddy-node"):
|
| 161 |
-
package = {
|
| 162 |
-
"name": app_name,
|
| 163 |
-
"version": "0.1.0",
|
| 164 |
-
"scripts": {"start": "node server.js"},
|
| 165 |
-
"dependencies": {"express": "^4.18.2"}
|
| 166 |
-
}
|
| 167 |
-
write_file(os.path.join(target_dir, "package.json"), json.dumps(package, indent=2))
|
| 168 |
-
write_file(os.path.join(target_dir, "server.js"),
|
| 169 |
-
"const express = require('express');\nconst app = express();\napp.use(express.json());\napp.get('/', (req, res)=> res.send('<h1>GenBuddy Node App</h1>'));\napp.listen(3000, ()=> console.log('Server listening on :3000'))")
|
| 170 |
-
write_file(os.path.join(target_dir, "README.md"), "Install with npm install; run with npm start")
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
write_file(os.path.join(target_dir, "README.md"), "Light Node HTTP server; run with `node server.js`")
|
| 176 |
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
def gen_flask_light(target_dir):
|
| 184 |
-
gen_flask_full(target_dir) # Flask is already lightweight; keep same but note minimal
|
| 185 |
-
|
| 186 |
-
def gen_django_full(target_dir, project_name="genbuddy_site"):
|
| 187 |
-
# Create minimal manage.py and project settings (not executing django-admin here)
|
| 188 |
-
write_file(os.path.join(target_dir, "README.md"),
|
| 189 |
-
"Django scaffold. For full project, run `django-admin startproject {}` locally and merge files.".format(project_name))
|
| 190 |
-
write_file(os.path.join(target_dir, "notes.txt"),
|
| 191 |
-
"Django full scaffolding needs django-admin; GenBuddy provides a starter README to guide you.")
|
| 192 |
-
|
| 193 |
-
def gen_dotnet_full(target_dir):
|
| 194 |
-
# Provide .csproj and Program.cs minimal for dotnet 6/7
|
| 195 |
-
write_file(os.path.join(target_dir, "Program.cs"),
|
| 196 |
-
"using System;\nConsole.WriteLine(\"GenBuddy .NET scaffold β create a proper project using `dotnet new web` locally.\");")
|
| 197 |
-
write_file(os.path.join(target_dir, "README.md"),
|
| 198 |
-
"Dotnet scaffold: run `dotnet new web -o .` locally to initialize a runnable project.")
|
| 199 |
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
f"<!doctype html><html><head><meta charset='utf-8'><title>GenBuddy App</title></head><body><h1>Generated App</h1><p>{command}</p></body></html>")
|
| 204 |
-
write_file(os.path.join(target_dir, "styles.css"), "body{font-family:system-ui;padding:20px;}")
|
| 205 |
|
| 206 |
-
|
| 207 |
-
def build_project_from_spec(spec, mode="light", include_files=None, project_name=None):
|
| 208 |
"""
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
include_files: list of dicts: {"name":..., "content_bytes":...}
|
| 212 |
-
project_name: optional string
|
| 213 |
-
returns zip_path
|
| 214 |
"""
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
os.makedirs(os.path.dirname(dest), exist_ok=True)
|
| 226 |
-
with open(dest, "wb") as fh:
|
| 227 |
-
fh.write(f["content_bytes"])
|
| 228 |
-
|
| 229 |
-
framework = spec.get("framework")
|
| 230 |
-
command = spec.get("command", "")
|
| 231 |
-
|
| 232 |
-
# Dispatch generators
|
| 233 |
-
if framework == "react":
|
| 234 |
-
if mode == "full":
|
| 235 |
-
gen_react_full(target_dir, app_name=project_name)
|
| 236 |
-
else:
|
| 237 |
-
gen_react_light(target_dir, app_name=project_name)
|
| 238 |
-
elif framework == "node":
|
| 239 |
-
if mode == "full":
|
| 240 |
-
gen_node_express_full(target_dir, app_name=project_name)
|
| 241 |
else:
|
| 242 |
-
|
| 243 |
-
elif framework == "flask":
|
| 244 |
-
gen_flask_full(target_dir) if mode == "full" else gen_flask_light(target_dir)
|
| 245 |
-
elif framework == "django":
|
| 246 |
-
gen_django_full(target_dir, project_name=project_name)
|
| 247 |
-
elif framework == "dotnet":
|
| 248 |
-
gen_dotnet_full(target_dir)
|
| 249 |
-
else:
|
| 250 |
-
# try to guess from command text
|
| 251 |
-
guessed = detect_framework_from_text(command)
|
| 252 |
-
if guessed:
|
| 253 |
-
return build_project_from_spec({"framework": guessed, "command": command}, mode=mode, include_files=include_files, project_name=project_name)
|
| 254 |
-
# fallback generic web scaffold
|
| 255 |
-
gen_generic_web(target_dir, command)
|
| 256 |
-
|
| 257 |
-
# write a manifest
|
| 258 |
-
manifest = {
|
| 259 |
-
"generated_at": datetime.utcnow().isoformat(),
|
| 260 |
-
"framework": framework or "generic",
|
| 261 |
-
"mode": mode,
|
| 262 |
-
"command": command,
|
| 263 |
-
"project_name": project_name
|
| 264 |
-
}
|
| 265 |
-
write_file(os.path.join(target_dir, "genbuddy_manifest.json"), json.dumps(manifest, indent=2))
|
| 266 |
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
|
|
|
|
|
|
| 270 |
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
|
|
|
|
|
|
| 274 |
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
# set name/gender when provided
|
| 279 |
-
if name:
|
| 280 |
-
MEMORY[user_id]["name"] = name
|
| 281 |
-
if gender:
|
| 282 |
-
MEMORY[user_id]["gender"] = gender
|
| 283 |
-
save_memory()
|
| 284 |
|
| 285 |
-
# Save to history
|
| 286 |
-
MEMORY[user_id].setdefault("history", []).append({"ts": datetime.utcnow().isoformat(), "input": command_text})
|
| 287 |
-
save_memory()
|
| 288 |
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
include_files.append({"name": f.name, "content_bytes": f.read()})
|
| 296 |
-
else:
|
| 297 |
-
f = uploaded
|
| 298 |
-
include_files.append({"name": f.name, "content_bytes": f.read()})
|
| 299 |
|
| 300 |
-
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
spec = {"framework": framework, "command": command_text}
|
| 306 |
|
| 307 |
-
|
| 308 |
-
|
|
|
|
| 309 |
|
| 310 |
-
# store templates for repeated tasks
|
| 311 |
-
templates = MEMORY[user_id].setdefault("templates", {})
|
| 312 |
-
# If command repeats -> store as template
|
| 313 |
-
if command_text.strip():
|
| 314 |
-
templates_key = re.sub(r"\\s+", "_", command_text.strip())[:50]
|
| 315 |
-
templates[templates_key] = {"spec": spec, "mode": mode_key, "timestamp": datetime.utcnow().isoformat()}
|
| 316 |
-
MEMORY[user_id]["templates"] = templates
|
| 317 |
-
save_memory()
|
| 318 |
|
| 319 |
-
|
| 320 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 321 |
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
return status_msg + "\\n\\nUploaded files analysis:\\n" + analysis_summary, zip_path
|
| 326 |
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
"name": "GenBuddy",
|
| 332 |
-
"gender": "female",
|
| 333 |
-
"preferences": {"tone": "friendly", "verbosity": "medium"},
|
| 334 |
-
"templates": {},
|
| 335 |
-
"history": []
|
| 336 |
-
}
|
| 337 |
-
save_memory()
|
| 338 |
-
return "Memory reset for user: " + user_id
|
| 339 |
|
| 340 |
-
with gr.Blocks(css="style.css", title="GenBuddy β Intelligent App Builder" :
|
| 341 |
-
gr.HTML("<div class='app-accent'></div>")
|
| 342 |
-
gr.Markdown("<h1 class='title'>πΈ GenBuddy β Intelligent App Builder</h1>")
|
| 343 |
|
| 344 |
-
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
name = gr.Textbox(label="Buddy display name (optional)", placeholder="e.g., Aurora")
|
| 348 |
-
gender = gr.Dropdown(label="Buddy gender", choices=["female", "male", "non-binary"], value="female")
|
| 349 |
-
set_btn = gr.Button("Set Name & Gender")
|
| 350 |
-
status = gr.Textbox(label="Status", interactive=False)
|
| 351 |
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
framework_choice = gr.Dropdown(label="Explicit framework (optional) β leave blank to auto-detect",
|
| 355 |
-
choices=["", "react", "node", "flask", "django", "dotnet"], value="")
|
| 356 |
-
mode_choice = gr.Radio(label="Mode", choices=["Light (fast)", "Full (runnable)"], value="Full (runnable)")
|
| 357 |
-
upload_files = gr.File(label="Upload files to include (optional)", file_count="multiple")
|
| 358 |
-
run_btn = gr.Button("Build App π")
|
| 359 |
-
output_text = gr.Textbox(label="Output", lines=6, interactive=False)
|
| 360 |
-
download_file = gr.File(label="Download Project ZIP", interactive=False)
|
| 361 |
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
|
|
|
|
|
|
|
|
|
|
| 367 |
|
| 368 |
-
|
| 369 |
-
gr.Markdown("### Quick actions & tips")
|
| 370 |
-
gr.Markdown("- Try: `Create login system with email + OTP`")
|
| 371 |
-
gr.Markdown("- Try: `Make a React dashboard that calls an external API`")
|
| 372 |
-
gr.Markdown("- Upload sample files to include them in the generated project")
|
| 373 |
-
gr.Markdown("**Mode**: Full = includes package files (you must run install locally); Light = CDN/minimal stubs.")
|
| 374 |
-
gr.Markdown("**Safety**: GenBuddy will NOT execute user code in the Space environment β it only generates and packages.")
|
| 375 |
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
|
|
|
| 383 |
|
| 384 |
-
|
| 385 |
-
uid = uid or "default"
|
| 386 |
-
ensure_user(uid)
|
| 387 |
-
# map readable mode to internal
|
| 388 |
-
mode_label = "Full (runnable)" if "Full" in mode_sel else "Light (fast)"
|
| 389 |
-
out_msg, zip_path = handle_user_interaction(uid, nm, g, mode_sel, framework_sel or None, cmd_text or "", uploaded)
|
| 390 |
-
# Gradio can return path to file for download
|
| 391 |
-
return out_msg, zip_path
|
| 392 |
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
return "\\n".join(lines) if lines else "No templates saved yet."
|
| 401 |
|
| 402 |
-
|
| 403 |
-
uid = uid or "default"
|
| 404 |
-
return reset_memory(uid), ""
|
| 405 |
|
| 406 |
-
|
| 407 |
-
|
| 408 |
-
refresh_templates.click(refresh_templates_fn, inputs=[user_id], outputs=[templates_box])
|
| 409 |
-
reset_btn.click(reset_fn, inputs=[user_id], outputs=[status, templates_box])
|
| 410 |
|
| 411 |
-
launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
+
import time
|
| 4 |
+
import traceback
|
| 5 |
import json
|
| 6 |
+
import re
|
|
|
|
| 7 |
import tempfile
|
| 8 |
from datetime import datetime
|
| 9 |
+
from io import BytesIO
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
# ============================================================
|
| 12 |
+
# GENBUDDY β INTELLIGENT APP BUILDER
|
| 13 |
+
# ============================================================
|
|
|
|
| 14 |
|
| 15 |
+
APP_TITLE = "GenBuddy β Intelligent App Builder"
|
| 16 |
+
APP_DESCRIPTION = """
|
| 17 |
+
An evolving AI developer that automates app creation, debugging, and optimization.
|
| 18 |
+
Built for intelligent, autonomous workflow completion with minimal user input.
|
| 19 |
+
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
+
# ============================================================
|
| 22 |
+
# CORE BEHAVIOR LOGIC
|
| 23 |
+
# ============================================================
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
def analyze_code(code_text):
|
|
|
|
| 26 |
"""
|
| 27 |
+
Analyzes user-submitted code, detects the language, checks for errors,
|
| 28 |
+
and returns optimization or bug-fix suggestions.
|
|
|
|
|
|
|
|
|
|
| 29 |
"""
|
| 30 |
+
try:
|
| 31 |
+
# Detect language (simplified pattern matching)
|
| 32 |
+
if "def " in code_text:
|
| 33 |
+
lang = "Python"
|
| 34 |
+
elif "function " in code_text or "const " in code_text:
|
| 35 |
+
lang = "JavaScript"
|
| 36 |
+
elif "#include" in code_text:
|
| 37 |
+
lang = "C/C++"
|
| 38 |
+
elif "public class" in code_text:
|
| 39 |
+
lang = "C# / Java"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
else:
|
| 41 |
+
lang = "Unknown"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
issues = []
|
| 44 |
+
if "print(" not in code_text and lang == "Python":
|
| 45 |
+
issues.append("No output function found (add print or return statements).")
|
| 46 |
+
if "TODO" in code_text:
|
| 47 |
+
issues.append("Contains TODO comments β incomplete logic.")
|
| 48 |
|
| 49 |
+
summary = f"Language Detected: **{lang}**\n"
|
| 50 |
+
if issues:
|
| 51 |
+
summary += "\nβ οΈ Issues Found:\n" + "\n".join(f"- {i}" for i in issues)
|
| 52 |
+
else:
|
| 53 |
+
summary += "\nβ
No major issues found."
|
| 54 |
|
| 55 |
+
return summary
|
| 56 |
+
except Exception as e:
|
| 57 |
+
return f"β Error analyzing code:\n{traceback.format_exc()}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
+
def improve_code(code_text):
|
| 61 |
+
"""
|
| 62 |
+
Performs simple auto-improvements (e.g., adds docstrings, fixes minor syntax).
|
| 63 |
+
"""
|
| 64 |
+
try:
|
| 65 |
+
improved = code_text.strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
+
# Auto-add docstring if missing
|
| 68 |
+
if "def " in improved and '"""' not in improved:
|
| 69 |
+
improved = re.sub(
|
| 70 |
+
r"(def\s+\w+\(.*\):)",
|
| 71 |
+
r'\1\n """Auto-generated by GenBuddy: function purpose unclear."""',
|
| 72 |
+
improved,
|
| 73 |
+
)
|
| 74 |
|
| 75 |
+
# Remove trailing whitespace and normalize indentation
|
| 76 |
+
improved = "\n".join(line.rstrip() for line in improved.splitlines())
|
|
|
|
| 77 |
|
| 78 |
+
return improved
|
| 79 |
+
except Exception:
|
| 80 |
+
return f"β Error improving code:\n{traceback.format_exc()}"
|
| 81 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
def build_app(name, code_text):
|
| 84 |
+
"""
|
| 85 |
+
Simulates app creation β saves code, generates structure, and returns build info.
|
| 86 |
+
"""
|
| 87 |
+
try:
|
| 88 |
+
build_dir = os.path.join(tempfile.gettempdir(), name.replace(" ", "_"))
|
| 89 |
+
os.makedirs(build_dir, exist_ok=True)
|
| 90 |
|
| 91 |
+
file_path = os.path.join(build_dir, "app.py")
|
| 92 |
+
with open(file_path, "w", encoding="utf-8") as f:
|
| 93 |
+
f.write(code_text)
|
|
|
|
| 94 |
|
| 95 |
+
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 96 |
+
return f"π App '{name}' built successfully at {build_dir}\nπ {timestamp}"
|
| 97 |
+
except Exception:
|
| 98 |
+
return f"β Build failed:\n{traceback.format_exc()}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
+
# ============================================================
|
| 102 |
+
# GRADIO UI
|
| 103 |
+
# ============================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
with gr.Blocks(css="style.css", title=APP_TITLE) as demo:
|
| 106 |
+
gr.Markdown(f"# π§ {APP_TITLE}\n{APP_DESCRIPTION}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
with gr.Tab("π¬ Chat & Analyze"):
|
| 109 |
+
code_input = gr.Textbox(
|
| 110 |
+
label="Paste your code or repo snippet here",
|
| 111 |
+
placeholder="Enter Python, JS, or other code...",
|
| 112 |
+
lines=10,
|
| 113 |
+
)
|
| 114 |
+
analyze_btn = gr.Button("π Analyze Code")
|
| 115 |
+
analyze_output = gr.Markdown()
|
| 116 |
|
| 117 |
+
analyze_btn.click(fn=analyze_code, inputs=code_input, outputs=analyze_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
|
| 119 |
+
with gr.Tab("βοΈ Improve Code"):
|
| 120 |
+
improve_input = gr.Textbox(
|
| 121 |
+
label="Code to Improve",
|
| 122 |
+
placeholder="Paste your raw code here",
|
| 123 |
+
lines=10,
|
| 124 |
+
)
|
| 125 |
+
improve_btn = gr.Button("π Auto-Improve")
|
| 126 |
+
improve_output = gr.Code(label="Improved Code", language="python")
|
| 127 |
|
| 128 |
+
improve_btn.click(fn=improve_code, inputs=improve_input, outputs=improve_output)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
|
| 130 |
+
with gr.Tab("ποΈ Build App"):
|
| 131 |
+
app_name = gr.Textbox(label="App Name", placeholder="MyTestApp")
|
| 132 |
+
code_content = gr.Textbox(
|
| 133 |
+
label="App Code", placeholder="Paste or generate code to package...", lines=10
|
| 134 |
+
)
|
| 135 |
+
build_btn = gr.Button("π οΈ Build App")
|
| 136 |
+
build_output = gr.Markdown()
|
|
|
|
| 137 |
|
| 138 |
+
build_btn.click(fn=build_app, inputs=[app_name, code_content], outputs=build_output)
|
|
|
|
|
|
|
| 139 |
|
| 140 |
+
gr.Markdown("---")
|
| 141 |
+
gr.Markdown("πΎ **GenBuddy** Β© 2025 β Autonomous AI App Builder.")
|
|
|
|
|
|
|
| 142 |
|
| 143 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|