File size: 3,882 Bytes
c959d59 b332e70 f514b2d 2cb47b8 b332e70 | 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 | import os, json, numpy as np, torch, spaces, gradio as gr
from huggingface_hub import hf_hub_download
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer, AutoModelForCausalLM
TOKEN, MODEL, INDEX = os.environ["HF_TOKEN"], "escc/eco-8b", "escc/eco-index"
# Exactly as in training (including the missing space after "it."): changing it changes behaviour.
SYSTEM = ("You are Eco, an environmental advocate built on Qwen3-8B. You speak with deep respect for life, nature and doing what is right: every living thing is worthy of care. "
"Be warm, thoughtful and sincere, never preachy or solemn. Answer the question first. Answer ONLY from the provided context, never naming or citing it."
"If the sources don't cover the question, say so plainly.")
chunks = json.load(open(hf_hub_download(INDEX, "chunks.json", repo_type="dataset", token=TOKEN)))
E = np.load(hf_hub_download(INDEX, "E.npy", repo_type="dataset", token=TOKEN))
emb = SentenceTransformer("BAAI/bge-small-en-v1.5", device="cpu")
tok = AutoTokenizer.from_pretrained(MODEL, token=TOKEN)
model = AutoModelForCausalLM.from_pretrained(MODEL, token=TOKEN, torch_dtype=torch.bfloat16).to("cuda")
def ctx(q, k=4):
s = E @ emb.encode(q, normalize_embeddings=True)
return "Context:\n\n" + "\n\n".join(chunks[i][1] for i in sorted(np.argpartition(-s, k)[:k], key=lambda i: -s[i]))
def chat(msgs, n=400):
p = tok.apply_chat_template(msgs, add_generation_prompt=True, enable_thinking=False, tokenize=False)
ids = tok(p, return_tensors="pt").input_ids.to("cuda")
return tok.decode(model.generate(ids, max_new_tokens=n, do_sample=False)[0, ids.shape[1]:], skip_special_tokens=True).strip()
text = lambda c: c if isinstance(c, str) else " ".join(x.get("text", "") for x in c if isinstance(x, dict))
@spaces.GPU(duration=45)
def respond(q, history):
hist = [{"role": h["role"], "content": text(h["content"])} for h in history]
sq = chat(hist + [{"role": "user", "content": "Rewrite as a standalone search query: " + q}], 40) if hist else q
return chat([{"role": "system", "content": SYSTEM}] + hist + [{"role": "user", "content": ctx(sq) + "\n\nQuestion: " + q}])
css = ".gradio-container { --font: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; }"
keys = ["body_background_fill", "body_text_color", "body_text_color_subdued", "background_fill_primary", "background_fill_secondary",
"block_background_fill", "input_background_fill", "border_color_primary", "block_border_color", "input_border_color",
"input_border_color_focus", "border_color_accent_subdued", "color_accent_soft", "link_text_color", "block_label_text_color",
"button_primary_background_fill", "button_secondary_background_fill", "button_primary_background_fill_hover",
"button_secondary_background_fill_hover", "button_primary_text_color", "button_secondary_text_color"]
# light: the site's white / light-blue / black embeds; dark: black with white text and blue accents
light = ["#ffffff", "#000000", "#5b7fa6", "#ffffff", "#f6f9fc", "#ffffff", "#ffffff", "#c9dcee", "#c9dcee", "#c9dcee",
"#0466C8", "#c9dcee", "#eaf4fd", "#0466C8", "#0466C8", "#0466C8", "#0466C8", "#2f9ce8", "#2f9ce8", "#ffffff", "#ffffff"]
dark = ["#000000", "#ffffff", "#8fb8e0", "#000000", "#0a1420", "#000000", "#0a1420", "#1f3b5c", "#1f3b5c", "#1f3b5c",
"#5aa4e8", "#1f3b5c", "#0b2a4a", "#5aa4e8", "#5aa4e8", "#0466C8", "#0466C8", "#2f9ce8", "#2f9ce8", "#ffffff", "#ffffff"]
theme = gr.themes.Base().set(**dict(zip(keys, light)), **{k + "_dark": v for k, v in zip(keys, dark)}, color_accent="#0466C8",
block_radius="8px", input_radius="6px", button_large_radius="6px", button_small_radius="6px")
gr.ChatInterface(respond, title="Eco", description="Questions about nature, climate and the environment.").launch(theme=theme, css=css)
|