Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import torch
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 7 |
+
|
| 8 |
+
load_dotenv()
|
| 9 |
+
|
| 10 |
+
MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-1.5B-Instruct")
|
| 11 |
+
SYSTEM_PROMPT = (
|
| 12 |
+
"You are a concise, helpful assistant focused on data science and machine learning."
|
| 13 |
+
)
|
| 14 |
+
MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "512"))
|
| 15 |
+
TEMPERATURE = float(os.getenv("TEMPERATURE", "0.7"))
|
| 16 |
+
|
| 17 |
+
print(f"Loading model: {MODEL_NAME} (first run downloads weights from Hugging Face Hub)...")
|
| 18 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 19 |
+
dtype = torch.float16 if device == "cuda" else torch.float32
|
| 20 |
+
|
| 21 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
|
| 22 |
+
if tokenizer.pad_token is None:
|
| 23 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 24 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 25 |
+
MODEL_NAME,
|
| 26 |
+
dtype=dtype,
|
| 27 |
+
device_map="auto" if device == "cuda" else None,
|
| 28 |
+
)
|
| 29 |
+
if device == "cpu":
|
| 30 |
+
model = model.to(device)
|
| 31 |
+
model.eval()
|
| 32 |
+
print(f"Model ready on {device}.")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _history_to_messages(history):
|
| 36 |
+
"""Convert Gradio chat history to OpenAI-style message dicts."""
|
| 37 |
+
messages = []
|
| 38 |
+
if not history:
|
| 39 |
+
return messages
|
| 40 |
+
|
| 41 |
+
for item in history:
|
| 42 |
+
if isinstance(item, dict):
|
| 43 |
+
role = item.get("role")
|
| 44 |
+
content = item.get("content")
|
| 45 |
+
if role and content:
|
| 46 |
+
messages.append({"role": role, "content": str(content).strip()})
|
| 47 |
+
elif isinstance(item, (list, tuple)) and len(item) == 2:
|
| 48 |
+
user_msg, assistant_msg = item
|
| 49 |
+
if user_msg and str(user_msg).strip():
|
| 50 |
+
messages.append({"role": "user", "content": str(user_msg).strip()})
|
| 51 |
+
if assistant_msg and str(assistant_msg).strip():
|
| 52 |
+
messages.append({"role": "assistant", "content": str(assistant_msg).strip()})
|
| 53 |
+
return messages
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _generate(messages):
|
| 57 |
+
prompt = tokenizer.apply_chat_template(
|
| 58 |
+
messages,
|
| 59 |
+
tokenize=False,
|
| 60 |
+
add_generation_prompt=True,
|
| 61 |
+
)
|
| 62 |
+
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
| 63 |
+
|
| 64 |
+
gen_kwargs = {
|
| 65 |
+
"max_new_tokens": MAX_NEW_TOKENS,
|
| 66 |
+
"pad_token_id": tokenizer.eos_token_id,
|
| 67 |
+
}
|
| 68 |
+
if TEMPERATURE > 0:
|
| 69 |
+
gen_kwargs.update(do_sample=True, temperature=TEMPERATURE)
|
| 70 |
+
else:
|
| 71 |
+
gen_kwargs.update(do_sample=False)
|
| 72 |
+
|
| 73 |
+
with torch.no_grad():
|
| 74 |
+
outputs = model.generate(**inputs, **gen_kwargs)
|
| 75 |
+
|
| 76 |
+
new_tokens = outputs[0][inputs["input_ids"].shape[1] :]
|
| 77 |
+
return tokenizer.decode(new_tokens, skip_special_tokens=True).strip()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def chat_fn(message, history):
|
| 81 |
+
if not message or not message.strip():
|
| 82 |
+
return ""
|
| 83 |
+
|
| 84 |
+
try:
|
| 85 |
+
messages = [{"role": "system", "content": SYSTEM_PROMPT}]
|
| 86 |
+
messages.extend(_history_to_messages(history))
|
| 87 |
+
messages.append({"role": "user", "content": str(message).strip()})
|
| 88 |
+
return _generate(messages)
|
| 89 |
+
|
| 90 |
+
except torch.cuda.OutOfMemoryError:
|
| 91 |
+
return (
|
| 92 |
+
"Error: GPU out of memory. Try a smaller model, e.g. "
|
| 93 |
+
"MODEL_NAME=TinyLlama/TinyLlama-1.1B-Chat-v1.0"
|
| 94 |
+
)
|
| 95 |
+
except Exception as e:
|
| 96 |
+
return f"Error: {e}"
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
demo = gr.ChatInterface(
|
| 100 |
+
fn=chat_fn,
|
| 101 |
+
title="Data Science AI Assistant (Free LLM)",
|
| 102 |
+
description=(
|
| 103 |
+
f"Local chatbot powered by **{MODEL_NAME}** — no API key required. "
|
| 104 |
+
"Ask questions about data science, machine learning, and related topics."
|
| 105 |
+
),
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
host = os.getenv("HOST")
|
| 109 |
+
port = int(os.getenv("PORT", 7860))
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
if host:
|
| 113 |
+
demo.launch(server_name=host, server_port=port)
|
| 114 |
+
else:
|
| 115 |
+
demo.launch(server_port=port)
|