Spaces:
Sleeping
Sleeping
File size: 3,629 Bytes
41ce36f | 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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | 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)
|