Spaces:
Build error
Build error
Download app.py from Replicable/PurpleRain-1: direct link, hf CLI and curl.
- Browser
- Download file 1.45 kB
-
https://huggingface.co/spaces/Replicable/PurpleRain-1/resolve/main/app.py
- Command line
-
hf download hf://spaces/Replicable/PurpleRain-1/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Replicable/PurpleRain-1/resolve/main/app.py
1.45 kB
| import os | |
| import torch | |
| import gradio as gr | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| # Load API token from environment variable (set in Hugging Face Spaces settings) | |
| ACCESS_TOKEN = os.getenv("HUGGINGFACE_TOKEN") | |
| # Ensure token is provided | |
| if ACCESS_TOKEN is None: | |
| raise ValueError("❌ ERROR: Missing HUGGINGFACE_TOKEN! Set it in Hugging Face Spaces settings.") | |
| # Model and tokenizer names | |
| MODEL_NAME = "google/gemma-2b" | |
| # Load tokenizer and model securely using the token | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, token=ACCESS_TOKEN) | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_NAME, | |
| token=ACCESS_TOKEN, | |
| torch_dtype=torch.float16, # Use float16 to optimize memory | |
| device_map="auto" # Automatically use GPU if available | |
| ) | |
| # Define the chat function | |
| def chat_with_gemma(prompt): | |
| inputs = tokenizer(prompt, return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu") | |
| output = model.generate(**inputs, max_new_tokens=200) | |
| response = tokenizer.decode(output[0], skip_special_tokens=True) | |
| return response | |
| # Create the Gradio interface | |
| iface = gr.Interface( | |
| fn=chat_with_gemma, | |
| inputs=gr.Textbox(lines=5, placeholder="Enter your prompt..."), | |
| outputs="text", | |
| title="Gemma-2B Chatbot", | |
| description="A chatbot powered by Google's Gemma-2B model, running on Hugging Face Spaces." | |
| ) | |
| # Launch the app | |
| if __name__ == "__main__": | |
| iface.launch() | |