File size: 2,162 Bytes
169f50e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
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

from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import gradio as gr # Example using Gradio for a simple web interface

# Define the model path (relative to the Space root)
model_path = "." # Model and tokenizer files are expected in the root

# Load the model and tokenizer
try:
    tokenizer = AutoTokenizer.from_pretrained(model_path)
    model = AutoModelForCausalLM.from_pretrained(model_path)
    print("Model and tokenizer loaded successfully.")
except Exception as e:
    print(f"Error loading model or tokenizer: {e}")
    # Exit or handle error appropriately in a real app
    exit()


def generate_code(prompt, max_length=100):
    """Generates code based on a given prompt."""
    try:
        input_ids = tokenizer(prompt, return_tensors="pt").input_ids
        # Ensure input_ids are on the same device as the model if using GPU
        if torch.cuda.is_available():
            model.to('cuda')
            input_ids = input_ids.to('cuda')

        # Generate text
        output_ids = model.generate(input_ids, max_length=max_length, num_return_sequences=1, no_repeat_ngram_size=2)

        # Decode the output
        # Decode only the newly generated part
        generated_text = tokenizer.decode(output_ids[0][len(input_ids[0]):], skip_special_tokens=True)
        return prompt + generated_text # Return prompt + generated part

    except Exception as e:
        return f"Error generating code: {e}"

# Create a simple Gradio interface
iface = gr.Interface(
    fn=generate_code,
    inputs=gr.Textbox(lines=2, label="Enter code prompt"),
    outputs=gr.Textbox(label="Generated code"),
    title="Code Generation Model",
    description="Generate code snippets based on your input prompt."
)

if __name__ == "__main__":
    # To run this locally for testing, you would typically use iface.launch()
    # For Hugging Face Spaces, the app is automatically run based on the file name (app.py)
    # and the presence of a Gradio or Streamlit interface.
    # We'll keep the launch call here for local testing purposes if needed.
    # iface.launch()
    pass # In a real Space, this part is handled by the platform.