Spaces:
Paused
Paused
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -181,33 +181,55 @@ def generate_spec(
|
|
| 181 |
if not source_code.strip():
|
| 182 |
return "*Please paste some Python source code.*"
|
| 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 |
# --- Gradio UI ---
|
|
|
|
| 181 |
if not source_code.strip():
|
| 182 |
return "*Please paste some Python source code.*"
|
| 183 |
|
| 184 |
+
try:
|
| 185 |
+
model, tokenizer = load_model()
|
| 186 |
+
|
| 187 |
+
user_content = source_code
|
| 188 |
+
if use_rag:
|
| 189 |
+
context = retrieve_context(source_code)
|
| 190 |
+
if context:
|
| 191 |
+
user_content = context + source_code
|
| 192 |
+
|
| 193 |
+
messages = [
|
| 194 |
+
{"role": "system", "content": SYSTEM_MESSAGE},
|
| 195 |
+
{"role": "user", "content": user_content},
|
| 196 |
+
]
|
| 197 |
+
|
| 198 |
+
input_text = tokenizer.apply_chat_template(
|
| 199 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 200 |
+
)
|
| 201 |
+
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
|
| 202 |
+
input_len = inputs["input_ids"].shape[-1]
|
| 203 |
+
|
| 204 |
+
# Check if input is too long -- truncate RAG context if needed
|
| 205 |
+
if input_len > 3500 and use_rag:
|
| 206 |
+
# Retry without RAG context
|
| 207 |
+
messages = [
|
| 208 |
+
{"role": "system", "content": SYSTEM_MESSAGE},
|
| 209 |
+
{"role": "user", "content": source_code},
|
| 210 |
+
]
|
| 211 |
+
input_text = tokenizer.apply_chat_template(
|
| 212 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 213 |
+
)
|
| 214 |
+
inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
|
| 215 |
+
input_len = inputs["input_ids"].shape[-1]
|
| 216 |
+
|
| 217 |
+
outputs = model.generate(
|
| 218 |
+
**inputs,
|
| 219 |
+
max_new_tokens=max_tokens,
|
| 220 |
+
temperature=temperature,
|
| 221 |
+
top_p=top_p,
|
| 222 |
+
do_sample=True,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
generated = outputs[0][input_len:]
|
| 226 |
+
return tokenizer.decode(generated, skip_special_tokens=True)
|
| 227 |
|
| 228 |
+
except Exception as e:
|
| 229 |
+
return (
|
| 230 |
+
f"**Error generating specification:**\n\n```\n{e}\n```\n\n"
|
| 231 |
+
"Try with a shorter input or disable RAG."
|
| 232 |
+
)
|
| 233 |
|
| 234 |
|
| 235 |
# --- Gradio UI ---
|