Spaces:
Configuration error

File size: 3,774 Bytes
0863bb2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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

import streamlit as st
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch

# Define the path to the model (it's in the root of the Space)
model_path = "."
# Define the repository ID for display purposes
repo_id_display = "arnoxide/boxcode-model" # Display the model repo, not the app repo

# Load the model and tokenizer (cache them using Streamlit's caching)
@st.cache_resource # Use st.cache_resource for models and other resources
def load_model():
    """Loads the fine-tuned model and tokenizer."""
    try:
        tokenizer = AutoTokenizer.from_pretrained(model_path)
        model = AutoModelForCausalLM.from_pretrained(model_path)
        # Ensure model is on GPU if available
        if torch.cuda.is_available():
            model.to('cuda')
        return tokenizer, model
    except Exception as e:
        st.error(f"Error loading model or tokenizer: {e}")
        return None, None

tokenizer, model = load_model()

def generate_code(prompt, tokenizer, model, max_length=200):
    """Generates code based on a given prompt using the loaded model."""
    if tokenizer is None or model is None:
        return "Error: Model or tokenizer not loaded."

    try:
        input_ids = tokenizer(prompt, return_tensors="pt").input_ids

        # Ensure input_ids are on the same device as the model
        if torch.cuda.is_available():
            input_ids = input_ids.to('cuda')

        # Generate text
        # Use appropriate generation parameters (e.g., do_sample=True, top_k, top_p)
        # for more varied output if needed. Keep it simple for now.
        output_ids = model.generate(
            input_ids,
            max_length=max_length,
            num_return_sequences=1,
            no_repeat_ngram_size=2,
            pad_token_id=tokenizer.pad_token_id # Ensure pad token is handled
        )

        # Decode the output
        # Decode the entire output sequence, including the prompt
        generated_text_with_prompt = tokenizer.decode(output_ids[0], skip_special_tokens=True)

        # Optionally, extract only the generated part (after the prompt)
        # This is a simple approach, may need refinement based on model behavior
        if generated_text_with_prompt.startswith(prompt):
             generated_text = generated_text_with_prompt[len(prompt):].strip()
        else:
             generated_text = generated_text_with_prompt # Fallback if prompt is not at start


        return generated_text

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

# Streamlit Application Layout
st.title("Code Generation Model")
st.write(f"Powered by a fine-tuned model hosted on Hugging Face Hub ({repo_id_display})")

# Input area
prompt_text = st.text_area("Enter your code prompt here:", height=150, key="prompt_input")

# Generation button
if st.button("Generate Code"):
    if prompt_text:
        with st.spinner("Generating code..."):
            # Call the code generation function
            generated_code = generate_code(prompt_text, tokenizer, model)
            # Store the generated code in session state to persist it
            st.session_state['generated_code'] = generated_code
    else:
        st.warning("Please enter a prompt.")

# Output area
# Use st.session_state to retrieve and display the generated code after a rerun
if 'generated_code' in st.session_state and st.session_state['generated_code']:
    st.text_area("Generated Code:", value=st.session_state['generated_code'], height=300, key="generated_output")
    # Alternatively, for code highlighting:
    # st.code(st.session_state['generated_code'], language='python') # Specify language if known


st.write("---")
st.write("This is a simple Streamlit application for demonstrating code generation.")