Spaces:
Runtime error

willingc's picture
Upload app.py with huggingface_hub
0ec78a9 verified
Raw History Blame Contribute Delete
5.66 kB
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
# Model configuration
MODEL_ID = "satyrn-ai/Qwen3.8-27B-py3.15"
# Load model and tokenizer
print(f"Loading model: {MODEL_ID}")
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
torch_dtype=torch.bfloat16,
device_map="auto"
)
print("Model loaded successfully!")
# Example prompts
EXAMPLES = [
["Write a Python function to calculate the Fibonacci sequence using dynamic programming"],
["Create a class for managing a binary search tree with insert and search methods"],
["Write a decorator that measures the execution time of a function"],
["Implement a function to parse JSON data and handle errors gracefully"],
["Create a context manager for reading and writing files safely"],
]
def generate_code(
prompt: str,
temperature: float = 0.7,
max_new_tokens: int = 512,
top_p: float = 0.9,
repetition_penalty: float = 1.1
):
"""Generate Python code based on the input prompt."""
if not prompt.strip():
return "Please enter a prompt to generate code."
# Format the prompt for code generation
formatted_prompt = f"""You are a helpful Python coding assistant. Generate clean, well-documented Python code.
User request: {prompt}
Python code:
```python"""
# Tokenize input
inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device)
# Generate
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
temperature=temperature,
top_p=top_p,
repetition_penalty=repetition_penalty,
do_sample=temperature > 0,
pad_token_id=tokenizer.eos_token_id,
)
# Decode output
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Extract the generated code (after the prompt)
if "```python" in generated_text:
code_start = generated_text.find("```python") + len("```python")
# Find the end of code block if it exists
code_end = generated_text.find("```", code_start)
if code_end != -1:
generated_code = generated_text[code_start:code_end].strip()
else:
generated_code = generated_text[code_start:].strip()
else:
# Fallback: return everything after the formatted prompt
generated_code = generated_text[len(formatted_prompt):].strip()
return f"```python\n{generated_code}\n```"
# Create Gradio interface
with gr.Blocks(theme=gr.themes.Soft()) as demo:
gr.Markdown(
"""
# 🐍 Qwen3.8-27B Python Code Generator
Generate Python code using the **satyrn-ai/Qwen3.8-27B-py3.15** model.
This model is specialized for Python 3.15 code generation tasks.
Enter your request in natural language and the model will generate corresponding Python code.
"""
)
with gr.Row():
with gr.Column(scale=1):
prompt_input = gr.Textbox(
label="Code Request",
placeholder="Describe what Python code you want to generate...",
lines=4
)
with gr.Accordion("Advanced Settings", open=False):
temperature = gr.Slider(
minimum=0.1,
maximum=2.0,
value=0.7,
step=0.1,
label="Temperature",
info="Higher values make output more creative but less focused"
)
max_tokens = gr.Slider(
minimum=128,
maximum=2048,
value=512,
step=128,
label="Max New Tokens",
info="Maximum length of generated code"
)
top_p = gr.Slider(
minimum=0.1,
maximum=1.0,
value=0.9,
step=0.05,
label="Top P",
info="Nucleus sampling parameter"
)
repetition_penalty = gr.Slider(
minimum=1.0,
maximum=2.0,
value=1.1,
step=0.1,
label="Repetition Penalty",
info="Penalize repeated tokens"
)
generate_btn = gr.Button("Generate Code", variant="primary", size="lg")
with gr.Column(scale=1):
output = gr.Markdown(label="Generated Code")
gr.Examples(
examples=EXAMPLES,
inputs=[prompt_input],
outputs=output,
fn=generate_code,
cache_examples=False,
)
gr.Markdown(
"""
---
### About
**Model**: [satyrn-ai/Qwen3.8-27B-py3.15](https://huggingface.co/satyrn-ai/Qwen3.8-27B-py3.15)
A 28B parameter vision-language model fine-tuned for Python code generation using the Satyrn Models Unsloth training pipeline.
For more information, visit the [GitHub repository](https://github.com/satyrn-ai/satyrn-models).
"""
)
# Set up the generation event
generate_btn.click(
fn=generate_code,
inputs=[prompt_input, temperature, max_tokens, top_p, repetition_penalty],
outputs=output
)
prompt_input.submit(
fn=generate_code,
inputs=[prompt_input, temperature, max_tokens, top_p, repetition_penalty],
outputs=output
)
if __name__ == "__main__":
demo.launch()