Download app.py from arnoxide/boxcode-model: direct link, hf CLI and curl.
- Browser
- Download file 2.16 kB
-
https://huggingface.co/arnoxide/boxcode-model/resolve/main/app.py
- Command line
-
hf download hf://arnoxide/boxcode-model/app.py
-
curl -L -o app.py https://huggingface.co/arnoxide/boxcode-model/resolve/main/app.py
2.16 kB
| 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. | |