slenk commited on
Commit
24210de
·
verified ·
1 Parent(s): 0a1f3da

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +48 -26
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
- model, tokenizer = load_model()
185
-
186
- user_content = source_code
187
- if use_rag:
188
- context = retrieve_context(source_code)
189
- if context:
190
- user_content = context + source_code
191
-
192
- messages = [
193
- {"role": "system", "content": SYSTEM_MESSAGE},
194
- {"role": "user", "content": user_content},
195
- ]
196
-
197
- input_text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
198
- inputs = tokenizer(input_text, return_tensors="pt").to(model.device)
199
- input_len = inputs["input_ids"].shape[-1]
200
-
201
- outputs = model.generate(
202
- **inputs,
203
- max_new_tokens=max_tokens,
204
- temperature=temperature,
205
- top_p=top_p,
206
- do_sample=True,
207
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
 
209
- generated = outputs[0][input_len:]
210
- return tokenizer.decode(generated, skip_special_tokens=True)
 
 
 
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 ---