Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,289 +1,298 @@
|
|
| 1 |
-
#
|
| 2 |
-
import os
|
| 3 |
-
import io
|
| 4 |
-
import json
|
| 5 |
-
import time
|
| 6 |
-
import tempfile
|
| 7 |
-
import requests
|
| 8 |
-
import gradio as gr
|
| 9 |
-
from typing import Tuple, Optional
|
| 10 |
-
|
| 11 |
-
#
|
| 12 |
-
HF_INFERENCE_URL = "https://api-inference.huggingface.co/models"
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
#
|
| 17 |
-
|
| 18 |
-
"
|
| 19 |
-
"
|
| 20 |
-
"
|
| 21 |
-
"
|
| 22 |
-
"
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
"
|
| 28 |
-
"
|
| 29 |
-
"
|
| 30 |
-
"
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
"
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
"
|
| 39 |
-
|
| 40 |
-
"
|
| 41 |
-
|
| 42 |
-
"
|
| 43 |
-
|
| 44 |
-
"
|
| 45 |
-
|
| 46 |
-
"
|
| 47 |
-
|
| 48 |
-
"
|
| 49 |
-
|
| 50 |
-
"
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
}
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
"
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
"
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
"
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
instruction = f"# Instruction: {task} for language {language}\n# Begin\n{prompt}\n# End\n"
|
| 153 |
-
gen = call_hf_inference(hf_model, hf_token, instruction, max_new_tokens=max_new_tokens, temperature=temperature, top_k=(None if top_k==0 else top_k))
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
return gen, None
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
code
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
(
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
gr.Markdown("
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
gr.
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
#
|
| 264 |
-
def
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
#
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# codegen_gradio_fixed.py
|
| 2 |
+
import os
|
| 3 |
+
import io
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
import tempfile
|
| 7 |
+
import requests
|
| 8 |
+
import gradio as gr
|
| 9 |
+
from typing import Tuple, Optional
|
| 10 |
+
|
| 11 |
+
# ------------------ Configuration ------------------
|
| 12 |
+
HF_INFERENCE_URL = "https://api-inference.huggingface.co/models"
|
| 13 |
+
DEFAULT_HF_MODEL = "bigcode/starcoder"
|
| 14 |
+
LANG_EXT = {
|
| 15 |
+
"Python": ".py", "JavaScript": ".js", "TypeScript": ".ts", "Go": ".go",
|
| 16 |
+
"Java": ".java", "C": ".c", "C++": ".cpp", "C#": ".cs", "Rust": ".rs",
|
| 17 |
+
"Kotlin": ".kt", "Swift": ".swift", "Ruby": ".rb", "PHP": ".php",
|
| 18 |
+
"Shell": ".sh", "PowerShell": ".ps1", "HTML": ".html", "CSS": ".css",
|
| 19 |
+
"SQL": ".sql", "R": ".r", "MATLAB": ".m", "Scala": ".scala",
|
| 20 |
+
"Haskell": ".hs", "Lua": ".lua", "Perl": ".pl", "Dart": ".dart",
|
| 21 |
+
"Elixir": ".ex", "Julia": ".jl", "Objective-C": ".m", "Assembly": ".s",
|
| 22 |
+
"Dockerfile": "Dockerfile", "JSON": ".json", "YAML": ".yml", "XML": ".xml"
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
# Dangerous keywords simple blacklist
|
| 26 |
+
DANGEROUS_KEYWORDS = [
|
| 27 |
+
"rm -rf", "mkfs", "dd if=", "fork bomb", "shutdown", "reboot", "poweroff",
|
| 28 |
+
"create user", "adduser", "useradd", "passwd", "ssh -i", "cryptominer", "virus",
|
| 29 |
+
"malware", "ransomware", "keylogger", "inject", "exploit", "reverse shell",
|
| 30 |
+
"nc -e", "wget http", "curl http", "chmod 777 /", "sudo rm -rf /", ">: /dev/sda"
|
| 31 |
+
]
|
| 32 |
+
|
| 33 |
+
# Task templates
|
| 34 |
+
TASK_TEMPLATES = {
|
| 35 |
+
"Generate code from description":
|
| 36 |
+
"Implement the following functionality in {lang}:\n\n{content}\n\n"
|
| 37 |
+
"Please provide only the code (no surrounding explanation).",
|
| 38 |
+
"Translate code to another language":
|
| 39 |
+
"Translate the following code from {src_lang} to {lang}. Keep behavior identical and include necessary imports.\n\n```{src_lang}\n{content}\n```",
|
| 40 |
+
"Explain code":
|
| 41 |
+
"Explain the following {lang} code. Provide a concise explanation, complexity notes, and potential pitfalls.\n\n```{lang}\n{content}\n```",
|
| 42 |
+
"Refactor code (readability/performance)":
|
| 43 |
+
"Refactor the following {lang} code for readability and performance. Keep behavior identical. Provide a 1-2 line summary of changes, then the refactored code only.\n\n```{lang}\n{content}\n```",
|
| 44 |
+
"Add unit tests":
|
| 45 |
+
"Write unit tests for the following {lang} code using a common testing framework (e.g., pytest for Python, jest for JS). Provide only the test code.\n\n```{lang}\n{content}\n```",
|
| 46 |
+
"Document & comment code":
|
| 47 |
+
"Add clear inline comments and a top-level docstring describing purpose, inputs, outputs, and side effects for this {lang} code. Provide the commented code only.\n\n```{lang}\n{content}\n```",
|
| 48 |
+
"Optimize for performance":
|
| 49 |
+
"Optimize the following {lang} code for performance while preserving behavior. Explain the optimization in 2-3 lines, then provide the optimized code only.\n\n```{lang}\n{content}\n```",
|
| 50 |
+
"Add type hints / static types":
|
| 51 |
+
"Add type annotations or static types to the following {lang} code where appropriate. Ensure the code remains valid.\n\n```{lang}\n{content}\n```",
|
| 52 |
+
"Create CLI tool":
|
| 53 |
+
"Create a command-line interface tool in {lang} that implements: {content}. Provide a complete script with argument parsing and a usage example."
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
# Model recommendations (HF model_name: (short description, compatibility notes))
|
| 57 |
+
MODEL_RECOMMENDATIONS = {
|
| 58 |
+
"bigcode/starcoder": (
|
| 59 |
+
"StarCoder: Open-source model specialized for code generation and multi-language support.",
|
| 60 |
+
"Good for Python, JS, TypeScript and general-purpose code generation. May return large outputs."
|
| 61 |
+
),
|
| 62 |
+
"bigcode/starcoder-base": (
|
| 63 |
+
"StarCoder-base: Lighter StarCoder variant with faster response but slightly lower fidelity.",
|
| 64 |
+
"Better for quick prototyping or smaller deployments."
|
| 65 |
+
),
|
| 66 |
+
"bigcode/codegen-2B-multi": (
|
| 67 |
+
"CodeGen 2B (multi): Code generation model trained on multi-language corpora.",
|
| 68 |
+
"Good for many languages; 2B size balances performance and resource usage."
|
| 69 |
+
),
|
| 70 |
+
"facebook/incoder-1B": (
|
| 71 |
+
"InCoder 1B: Autoregressive code model that supports code infilling and generation.",
|
| 72 |
+
"Smaller model appropriate for lower-resource environments; may require prompt engineering for best results."
|
| 73 |
+
),
|
| 74 |
+
"codellama/CodeLlama-7b-Instruct": (
|
| 75 |
+
"CodeLlama 7B Instruct: Instruction-tuned CodeLlama model for code generation and explanation.",
|
| 76 |
+
"High-quality outputs but large (7B); requires sufficient memory or HF Inference API."
|
| 77 |
+
),
|
| 78 |
+
"Salesforce/codegen-6B-mono": (
|
| 79 |
+
"CodeGen 6B Mono: Strong code generation model focused on mono-language generation.",
|
| 80 |
+
"Powerful but large; use HF Inference or a GPU-equipped local environment."
|
| 81 |
+
),
|
| 82 |
+
"bigcode/starcoder-large": (
|
| 83 |
+
"StarCoder-large: Larger StarCoder variant for higher fidelity.",
|
| 84 |
+
"Best-quality among StarCoder variants but resource heavy."
|
| 85 |
+
)
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
# ------------------ Helpers ------------------
|
| 89 |
+
def ext_for_language(lang: str) -> str:
|
| 90 |
+
return LANG_EXT.get(lang, ".txt")
|
| 91 |
+
|
| 92 |
+
def detect_dangerous(text: str) -> Optional[str]:
|
| 93 |
+
if not text:
|
| 94 |
+
return None
|
| 95 |
+
lower = text.lower()
|
| 96 |
+
for k in DANGEROUS_KEYWORDS:
|
| 97 |
+
if k in lower:
|
| 98 |
+
return k
|
| 99 |
+
return None
|
| 100 |
+
|
| 101 |
+
def build_prompt(task: str, lang: str, content: str, src_lang: Optional[str] = None) -> str:
|
| 102 |
+
tmpl = TASK_TEMPLATES.get(task, "{content}")
|
| 103 |
+
return tmpl.format(lang=lang, content=content, src_lang=src_lang or "")
|
| 104 |
+
|
| 105 |
+
def save_code_to_tempfile(code: str, filename_hint: str = "generated_code", ext: str = ".txt") -> str:
|
| 106 |
+
fd, path = tempfile.mkstemp(prefix=filename_hint + "_", suffix=ext)
|
| 107 |
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
| 108 |
+
f.write(code)
|
| 109 |
+
return path
|
| 110 |
+
|
| 111 |
+
# ------------------ HF Inference call ------------------
|
| 112 |
+
def call_hf_inference(model: str, hf_token: str, prompt: str, max_new_tokens: int = 512, temperature: float = 0.2, top_k: Optional[int] = None) -> str:
|
| 113 |
+
if not hf_token or not hf_token.strip():
|
| 114 |
+
return "[Error] No Hugging Face token provided."
|
| 115 |
+
|
| 116 |
+
url = f"{HF_INFERENCE_URL}/{model}"
|
| 117 |
+
headers = {"Authorization": f"Bearer {hf_token}", "Content-Type": "application/json"}
|
| 118 |
+
payload = {"inputs": prompt, "parameters": {"max_new_tokens": max_new_tokens, "temperature": temperature}}
|
| 119 |
+
if top_k and top_k > 0:
|
| 120 |
+
payload["parameters"]["top_k"] = top_k
|
| 121 |
+
try:
|
| 122 |
+
r = requests.post(url, headers=headers, json=payload, timeout=120)
|
| 123 |
+
r.raise_for_status()
|
| 124 |
+
data = r.json()
|
| 125 |
+
# common shapes: list with dicts or dict with generated_text
|
| 126 |
+
if isinstance(data, list) and len(data) > 0:
|
| 127 |
+
first = data[0]
|
| 128 |
+
if isinstance(first, dict) and "generated_text" in first:
|
| 129 |
+
return first["generated_text"]
|
| 130 |
+
return str(first)
|
| 131 |
+
if isinstance(data, dict):
|
| 132 |
+
if "generated_text" in data:
|
| 133 |
+
return data["generated_text"]
|
| 134 |
+
if "error" in data:
|
| 135 |
+
return "[HF Error] " + str(data["error"])
|
| 136 |
+
return json.dumps(data)
|
| 137 |
+
return str(data)
|
| 138 |
+
except requests.exceptions.HTTPError as e:
|
| 139 |
+
return f"[HF HTTP Error] {e} - {r.text if 'r' in locals() else ''}"
|
| 140 |
+
except Exception as e:
|
| 141 |
+
return f"[HF Error] {e}"
|
| 142 |
+
|
| 143 |
+
# ------------------ Generation pipeline ------------------
|
| 144 |
+
def generate_code_task(task: str, hf_token: str, hf_model: str, language: str, src_language: str, description: str,
|
| 145 |
+
temperature: float, max_new_tokens: int, top_k: int) -> Tuple[str, Optional[str]]:
|
| 146 |
+
# security
|
| 147 |
+
danger = detect_dangerous(description)
|
| 148 |
+
if danger:
|
| 149 |
+
return f"[Refused] Request contains potentially dangerous keyword: '{danger}'.", None
|
| 150 |
+
|
| 151 |
+
prompt = build_prompt(task, language, description, src_lang=src_language)
|
| 152 |
+
instruction = f"# Instruction: {task} for language {language}\n# Begin\n{prompt}\n# End\n"
|
| 153 |
+
gen = call_hf_inference(hf_model, hf_token, instruction, max_new_tokens=max_new_tokens, temperature=temperature, top_k=(None if top_k == 0 else top_k))
|
| 154 |
+
|
| 155 |
+
if isinstance(gen, str) and gen.startswith("[HF"):
|
| 156 |
+
# error from HF
|
| 157 |
+
return gen, None
|
| 158 |
+
|
| 159 |
+
code = gen.strip()
|
| 160 |
+
# extract code fence content if present
|
| 161 |
+
if "```" in code:
|
| 162 |
+
parts = code.split("```")
|
| 163 |
+
# parts may be: before, ```lang\ncode\n```, ...
|
| 164 |
+
# find the first non-empty code-like chunk
|
| 165 |
+
candidate = None
|
| 166 |
+
for i in range(1, len(parts), 2):
|
| 167 |
+
chunk = parts[i].strip()
|
| 168 |
+
if len(chunk) > 0:
|
| 169 |
+
# if chunk starts with language id like "python\n", remove the first line
|
| 170 |
+
lines = chunk.splitlines()
|
| 171 |
+
if len(lines) > 1 and len(lines[0]) <= 20 and not lines[0].strip().startswith(("#", "//")) and not "(" in lines[0]:
|
| 172 |
+
# treat as lang tag
|
| 173 |
+
candidate = "\n".join(lines[1:]).strip()
|
| 174 |
+
else:
|
| 175 |
+
candidate = chunk
|
| 176 |
+
break
|
| 177 |
+
if candidate:
|
| 178 |
+
code = candidate
|
| 179 |
+
|
| 180 |
+
# try to strip instruction echoes
|
| 181 |
+
if instruction.strip() and code.startswith(instruction.strip()):
|
| 182 |
+
code = code[len(instruction.strip()):].strip()
|
| 183 |
+
|
| 184 |
+
# fallback: ensure code not empty
|
| 185 |
+
if not code:
|
| 186 |
+
code = gen
|
| 187 |
+
|
| 188 |
+
ext = ext_for_language(language)
|
| 189 |
+
fname = f"code_{language.lower().replace(' ', '_')}{ext}"
|
| 190 |
+
path = save_code_to_tempfile(code, filename_hint="generated_code", ext=ext)
|
| 191 |
+
return code, path
|
| 192 |
+
|
| 193 |
+
# ------------------ UI wiring ------------------
|
| 194 |
+
EXAMPLES = [
|
| 195 |
+
("Generate code from description", "bigcode/starcoder", "Python", "", "A function that returns the nth Fibonacci number using dynamic programming (iterative).", 0.2, 256, 0),
|
| 196 |
+
("Translate code to another language", "bigcode/starcoder", "JavaScript", "Python", "def greet(name):\n return f\"Hello, {name}!\"", 0.2, 256, 0),
|
| 197 |
+
("Add unit tests", "bigcode/starcoder", "Python", "", "def add(a, b):\n return a + b", 0.2, 256, 0),
|
| 198 |
+
("Explain code", "bigcode/starcoder", "Go", "", 'package main\n\nimport "fmt"\n\nfunc main() {\n fmt.Println("Hello world")\n}', 0.2, 256, 0),
|
| 199 |
+
]
|
| 200 |
+
|
| 201 |
+
def load_example_to_inputs(example):
|
| 202 |
+
# returns values matching the UI inputs order we will set
|
| 203 |
+
(task_v, hf_mod, lang, src_lang, desc, temperature, max_new_tokens, top_k) = example
|
| 204 |
+
return hf_mod, task_v, lang, src_lang, desc, temperature, max_new_tokens, top_k
|
| 205 |
+
|
| 206 |
+
def do_generate(task, hf_token, hf_model, language, src_language, description, temperature, max_new_tokens, top_k):
|
| 207 |
+
if not hf_token or not hf_token.strip():
|
| 208 |
+
return "[Error] Please paste your Hugging Face API token.", None
|
| 209 |
+
if not hf_model or not hf_model.strip():
|
| 210 |
+
return "[Error] Please enter a Hugging Face model name.", None
|
| 211 |
+
if not description or not description.strip():
|
| 212 |
+
return "[Error] Please provide a description or code to operate on.", None
|
| 213 |
+
code, path = generate_code_task(task, hf_token, hf_model, language, src_language, description, temperature, int(max_new_tokens), int(top_k))
|
| 214 |
+
return code, path
|
| 215 |
+
|
| 216 |
+
def save_generated_as_file(code_text, language_val):
|
| 217 |
+
if not code_text or code_text.strip() == "":
|
| 218 |
+
return None
|
| 219 |
+
ext = ext_for_language(language_val)
|
| 220 |
+
return save_code_to_tempfile(code_text, filename_hint="generated_code", ext=ext)
|
| 221 |
+
|
| 222 |
+
# ------------------ Build Gradio UI ------------------
|
| 223 |
+
def build_ui():
|
| 224 |
+
with gr.Blocks(title="Polyglot Code Generator (Hugging Face Inference)") as demo:
|
| 225 |
+
gr.Markdown("# 🚀 Polyglot Code Generator\nGenerate, translate, explain, refactor and test code in many languages using Hugging Face models.\n\nPaste your Hugging Face Inference API token below (Settings → Access Tokens on Hugging Face).")
|
| 226 |
+
|
| 227 |
+
with gr.Row():
|
| 228 |
+
with gr.Column(scale=3):
|
| 229 |
+
hf_token = gr.Textbox(label="Hugging Face API Token (paste here)", type="password", placeholder="hf_xxx...")
|
| 230 |
+
# Model recommendation dropdown
|
| 231 |
+
model_choices = list(MODEL_RECOMMENDATIONS.keys())
|
| 232 |
+
hf_model = gr.Dropdown(label="Model (recommended)", choices=model_choices, value=DEFAULT_HF_MODEL)
|
| 233 |
+
model_info = gr.Markdown(value=f"**Model info:** {MODEL_RECOMMENDATIONS.get(DEFAULT_HF_MODEL)[0]} \n_{MODEL_RECOMMENDATIONS.get(DEFAULT_HF_MODEL)[1]}_")
|
| 234 |
+
|
| 235 |
+
task = gr.Dropdown(label="Task", choices=list(TASK_TEMPLATES.keys()), value="Generate code from description")
|
| 236 |
+
language = gr.Dropdown(label="Target language", choices=list(LANG_EXT.keys()), value="Python")
|
| 237 |
+
src_language = gr.Textbox(label="Source language (for translation)", placeholder="e.g. Python", value="")
|
| 238 |
+
description = gr.Textbox(label="Description / Input code", lines=8, placeholder="Describe the feature or paste the code to transform...")
|
| 239 |
+
temp = gr.Slider(label="temperature", minimum=0.0, maximum=1.0, value=0.2, step=0.05)
|
| 240 |
+
max_tokens = gr.Slider(label="max_new_tokens", minimum=16, maximum=2048, value=512, step=16)
|
| 241 |
+
top_k = gr.Slider(label="top_k (0 = default)", minimum=0, maximum=100, value=0, step=1)
|
| 242 |
+
|
| 243 |
+
gen_btn = gr.Button("Generate Code")
|
| 244 |
+
with gr.Accordion("Examples", open=False):
|
| 245 |
+
example_buttons = []
|
| 246 |
+
for i, ex in enumerate(EXAMPLES):
|
| 247 |
+
b = gr.Button(f"Load example: {ex[0]} → {ex[2]}")
|
| 248 |
+
example_buttons.append((b, ex))
|
| 249 |
+
|
| 250 |
+
with gr.Column(scale=2):
|
| 251 |
+
gr.Markdown("### Output")
|
| 252 |
+
code_out = gr.Code(value="", language="python", label="Generated Code / Explanation")
|
| 253 |
+
download_file = gr.File(label="Download generated file")
|
| 254 |
+
|
| 255 |
+
with gr.Row():
|
| 256 |
+
save_btn = gr.Button("Save as file (prepare download)")
|
| 257 |
+
explain_btn = gr.Button("Explain selected code (quick action)")
|
| 258 |
+
|
| 259 |
+
gr.Markdown("### Quick tips")
|
| 260 |
+
gr.Markdown("- If the model echoes the prompt or includes explanation, the app will try to extract the first code block.\n- For best results use a code-capable HF model like `bigcode/starcoder` or `codellama/CodeLlama-7b-Instruct` via the Inference API.")
|
| 261 |
+
|
| 262 |
+
# Events
|
| 263 |
+
# Update model info when hf_model changes
|
| 264 |
+
def update_model_info(model_name):
|
| 265 |
+
info = MODEL_RECOMMENDATIONS.get(model_name)
|
| 266 |
+
if info:
|
| 267 |
+
return f"**Model info:** {info[0]} \n_{info[1]}_"
|
| 268 |
+
else:
|
| 269 |
+
return "**Model info:** Unknown model. Compatibility depends on the model. Use a code-capable model."
|
| 270 |
+
|
| 271 |
+
hf_model.change(fn=update_model_info, inputs=[hf_model], outputs=[model_info])
|
| 272 |
+
|
| 273 |
+
# Example buttons wiring
|
| 274 |
+
for btn, ex in example_buttons:
|
| 275 |
+
btn.click(fn=load_example_to_inputs, inputs=None, outputs=[hf_model, task, language, src_language, description, temp, max_tokens, top_k], _js=None, _preprocess=False, _postprocess=False, args=[ex])
|
| 276 |
+
|
| 277 |
+
# Generate
|
| 278 |
+
gen_btn.click(fn=do_generate, inputs=[task, hf_token, hf_model, language, src_language, description, temp, max_tokens, top_k], outputs=[code_out, download_file])
|
| 279 |
+
|
| 280 |
+
# Save button
|
| 281 |
+
save_btn.click(fn=save_generated_as_file, inputs=[code_out, language], outputs=[download_file])
|
| 282 |
+
|
| 283 |
+
# Quick explain
|
| 284 |
+
def quick_explain(hf_token_val, hf_model_val, code_text, language_val, temp_val, max_tokens_val):
|
| 285 |
+
if not code_text or code_text.strip() == "":
|
| 286 |
+
return "[Error] No code to explain."
|
| 287 |
+
prompt = build_prompt("Explain code", language_val, code_text)
|
| 288 |
+
return call_hf_inference(hf_model_val, hf_token_val, f"# Instruction: Explain code\n{prompt}\n", max_new_tokens=int(max_tokens_val), temperature=float(temp_val))
|
| 289 |
+
|
| 290 |
+
explain_btn.click(fn=quick_explain, inputs=[hf_token, hf_model, code_out, language, temp, max_tokens], outputs=[code_out])
|
| 291 |
+
|
| 292 |
+
gr.Markdown("---\n**Safety note**: This app performs basic keyword checks to refuse obviously destructive requests. Always review generated code before running it in production.")
|
| 293 |
+
|
| 294 |
+
return demo
|
| 295 |
+
|
| 296 |
+
if __name__ == "__main__":
|
| 297 |
+
demo = build_ui()
|
| 298 |
+
demo.launch(server_name="0.0.0.0", share=False)
|