Spaces:
Sleeping
Sleeping
Download app.py from boosterleap/FreeChatbot: direct link, hf CLI and curl.
- Browser
- Download file 3.63 kB
-
https://huggingface.co/spaces/boosterleap/FreeChatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/boosterleap/FreeChatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/boosterleap/FreeChatbot/resolve/main/app.py
3.63 kB
| import os | |
| import gradio as gr | |
| import torch | |
| from dotenv import load_dotenv | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| load_dotenv() | |
| MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-1.5B-Instruct") | |
| SYSTEM_PROMPT = ( | |
| "You are a concise, helpful assistant focused on data science and machine learning." | |
| ) | |
| MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "512")) | |
| TEMPERATURE = float(os.getenv("TEMPERATURE", "0.7")) | |
| print(f"Loading model: {MODEL_NAME} (first run downloads weights from Hugging Face Hub)...") | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| dtype = torch.float16 if device == "cuda" else torch.float32 | |
| tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME) | |
| if tokenizer.pad_token is None: | |
| tokenizer.pad_token = tokenizer.eos_token | |
| model = AutoModelForCausalLM.from_pretrained( | |
| MODEL_NAME, | |
| dtype=dtype, | |
| device_map="auto" if device == "cuda" else None, | |
| ) | |
| if device == "cpu": | |
| model = model.to(device) | |
| model.eval() | |
| print(f"Model ready on {device}.") | |
| def _history_to_messages(history): | |
| """Convert Gradio chat history to OpenAI-style message dicts.""" | |
| messages = [] | |
| if not history: | |
| return messages | |
| for item in history: | |
| if isinstance(item, dict): | |
| role = item.get("role") | |
| content = item.get("content") | |
| if role and content: | |
| messages.append({"role": role, "content": str(content).strip()}) | |
| elif isinstance(item, (list, tuple)) and len(item) == 2: | |
| user_msg, assistant_msg = item | |
| if user_msg and str(user_msg).strip(): | |
| messages.append({"role": "user", "content": str(user_msg).strip()}) | |
| if assistant_msg and str(assistant_msg).strip(): | |
| messages.append({"role": "assistant", "content": str(assistant_msg).strip()}) | |
| return messages | |
| def _generate(messages): | |
| prompt = tokenizer.apply_chat_template( | |
| messages, | |
| tokenize=False, | |
| add_generation_prompt=True, | |
| ) | |
| inputs = tokenizer(prompt, return_tensors="pt").to(model.device) | |
| gen_kwargs = { | |
| "max_new_tokens": MAX_NEW_TOKENS, | |
| "pad_token_id": tokenizer.eos_token_id, | |
| } | |
| if TEMPERATURE > 0: | |
| gen_kwargs.update(do_sample=True, temperature=TEMPERATURE) | |
| else: | |
| gen_kwargs.update(do_sample=False) | |
| with torch.no_grad(): | |
| outputs = model.generate(**inputs, **gen_kwargs) | |
| new_tokens = outputs[0][inputs["input_ids"].shape[1] :] | |
| return tokenizer.decode(new_tokens, skip_special_tokens=True).strip() | |
| def chat_fn(message, history): | |
| if not message or not message.strip(): | |
| return "" | |
| try: | |
| messages = [{"role": "system", "content": SYSTEM_PROMPT}] | |
| messages.extend(_history_to_messages(history)) | |
| messages.append({"role": "user", "content": str(message).strip()}) | |
| return _generate(messages) | |
| except torch.cuda.OutOfMemoryError: | |
| return ( | |
| "Error: GPU out of memory. Try a smaller model, e.g. " | |
| "MODEL_NAME=TinyLlama/TinyLlama-1.1B-Chat-v1.0" | |
| ) | |
| except Exception as e: | |
| return f"Error: {e}" | |
| demo = gr.ChatInterface( | |
| fn=chat_fn, | |
| title="Data Science AI Assistant (Free LLM)", | |
| description=( | |
| f"Local chatbot powered by **{MODEL_NAME}** — no API key required. " | |
| "Ask questions about data science, machine learning, and related topics." | |
| ), | |
| ) | |
| host = os.getenv("HOST") | |
| port = int(os.getenv("PORT", 7860)) | |
| if __name__ == "__main__": | |
| if host: | |
| demo.launch(server_name=host, server_port=port) | |
| else: | |
| demo.launch(server_port=port) | |