Spaces:
Runtime error
Runtime error
Download app.py from Campcraft-ai/Field-guide: direct link, hf CLI and curl.
- Browser
- Download file 6.4 kB
-
https://huggingface.co/spaces/Campcraft-ai/Field-guide/resolve/main/app.py
- Command line
-
hf download hf://spaces/Campcraft-ai/Field-guide/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Campcraft-ai/Field-guide/resolve/main/app.py
6.4 kB
| import os, re, json, time, pathlib, math | |
| import gradio as gr | |
| import numpy as np | |
| TOP_K = int(os.getenv("TOP_K", "4")) | |
| MODEL_ID = os.getenv("MODEL_ID", "TinyLlama/TinyLlama-1.1B-Chat-v1.0") | |
| USE_TGI_URL = os.getenv("USE_TGI_URL") # if set, call TGI /v1/chat/completions | |
| SYSTEM_PROMPT = ( | |
| "You are the Campfire guide. Be concise. Prefer numbered steps for procedures. " | |
| "Safety first. If unsure or outside scope, say so. Cite the provided snippets like [S1], [S2]." | |
| ) | |
| # --- Retrieval helpers --- | |
| from sentence_transformers import SentenceTransformer | |
| from rank_bm25 import BM25Okapi | |
| EMB_MODEL_ID = os.getenv("EMB_MODEL_ID", "sentence-transformers/all-MiniLM-L6-v2") | |
| emb_model = SentenceTransformer(EMB_MODEL_ID) | |
| def read_chunks(base="field_guide"): | |
| chunks, metas = [], [] | |
| base = pathlib.Path(base) | |
| for md in sorted(base.rglob("*.md")): | |
| text = md.read_text(encoding="utf-8", errors="ignore") | |
| # naive chunking into ~600-char pieces on paragraph boundaries | |
| paras = [p.strip() for p in text.split("\n\n") if p.strip()] | |
| buf = "" | |
| for p in paras: | |
| if len(buf) + len(p) < 600: | |
| buf = (buf + "\n\n" + p).strip() | |
| else: | |
| if buf: | |
| chunks.append(buf); metas.append({"path": str(md), "title": md.stem}) | |
| buf = p | |
| if buf: | |
| chunks.append(buf); metas.append({"path": str(md), "title": md.stem}) | |
| return chunks, metas | |
| CHUNKS, METAS = read_chunks() | |
| BM25 = BM25Okapi([c.split() for c in CHUNKS]) | |
| EMB = emb_model.encode(CHUNKS, normalize_embeddings=True) | |
| def retrieve(query, top_k=TOP_K): | |
| q_emb = emb_model.encode([query], normalize_embeddings=True)[0] | |
| # semantic | |
| sims = EMB @ q_emb | |
| top_sem_idx = np.argsort(-sims)[:top_k*2] | |
| # lexical | |
| bm25_scores = BM25.get_scores(query.split()) | |
| top_lex_idx = np.argsort(-bm25_scores)[:top_k*2] | |
| # merge | |
| cand = set(top_sem_idx.tolist() + top_lex_idx.tolist()) | |
| scored = sorted([(i, (sims[i] + bm25_scores[i]/10.0)) for i in cand], key=lambda x: -x[1]) | |
| picks = [i for i,_ in scored[:top_k]] | |
| snippets = [] | |
| for rank, i in enumerate(picks, 1): | |
| meta = METAS[i] | |
| snippets.append((f"S{rank}", CHUNKS[i], meta)) | |
| return snippets | |
| def build_context(snippets): | |
| lines = [] | |
| for tag, text, meta in snippets: | |
| title = meta.get("title", "note") | |
| lines.append(f"[{tag}] {title}: {text}") | |
| return "\n\n".join(lines) | |
| # --- Generation backends --- | |
| def chat_local(model_id, messages, max_new_tokens=256, temperature=0.3, top_p=0.9): | |
| from transformers import AutoTokenizer, AutoModelForCausalLM, TextStreamer | |
| import torch | |
| tok = AutoTokenizer.from_pretrained(model_id, use_fast=True) | |
| # device_map auto so it uses GPU if available | |
| model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto") | |
| # simple chat template if available | |
| if hasattr(tok, "apply_chat_template"): | |
| prompt = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) | |
| else: | |
| # fallback: concatenate | |
| prompt = "" | |
| for m in messages: | |
| role = m.get("role","user") | |
| content = m.get("content","") | |
| prompt += f"{role.upper()}: {content}\n" | |
| prompt += "ASSISTANT:" | |
| inputs = tok([prompt], return_tensors="pt").to(model.device) | |
| gen = model.generate( | |
| **inputs, | |
| max_new_tokens=max_new_tokens, | |
| do_sample=temperature > 0, | |
| temperature=temperature, | |
| top_p=top_p, | |
| repetition_penalty=1.1, | |
| pad_token_id=tok.eos_token_id, | |
| ) | |
| out = tok.decode(gen[0], skip_special_tokens=True) | |
| # naive split to get assistant part | |
| if "ASSISTANT:" in out: | |
| out = out.split("ASSISTANT:")[-1].strip() | |
| else: | |
| # try to remove the prompt prefix | |
| out = out[len(prompt):].strip() | |
| return out | |
| def chat_tgi(url, messages, max_new_tokens=256, temperature=0.3, top_p=0.9, stream=False): | |
| import requests | |
| payload = { | |
| "model": "dummy", | |
| "messages": messages, | |
| "max_tokens": max_new_tokens, | |
| "temperature": temperature, | |
| "top_p": top_p, | |
| "stream": stream, | |
| } | |
| r = requests.post(url.rstrip("/") + "/v1/chat/completions", json=payload, timeout=120) | |
| r.raise_for_status() | |
| data = r.json() | |
| return data["choices"][0]["message"]["content"] | |
| def answer(query, mode, max_new_tokens, temperature, top_p): | |
| t0 = time.time() | |
| snippets = retrieve(query, top_k=TOP_K) | |
| context = build_context(snippets) | |
| sys_preface = SYSTEM_PROMPT + (" Always use a numbered list." if mode == "Step-by-step" else "") | |
| ctx_header = f"Use ONLY these notes to answer. If not in notes, say you don't know and propose a safe fallback.\n\n{context}\n\n" | |
| messages = [ | |
| {"role": "system", "content": sys_preface}, | |
| {"role": "user", "content": ctx_header + "\nQuestion: " + query}, | |
| ] | |
| if USE_TGI_URL: | |
| out = chat_tgi(USE_TGI_URL, messages, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p) | |
| else: | |
| out = chat_local(MODEL_ID, messages, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p) | |
| dt = time.time() - t0 | |
| sources = "\n".join([f"[{tag}] {meta.get('title')} — {meta.get('path')}" for tag, _, meta in snippets]) | |
| return out, sources, f"{dt:.1f}s" | |
| with gr.Blocks(title="Campfire — Micro-LLM + Local RAG") as demo: | |
| gr.Markdown("""# Campfire — Micro-LLM + Local RAG | |
| Type a question. The model answers **only** from the local field guide below and cites snippets. | |
| """) | |
| with gr.Row(): | |
| inp = gr.Textbox(label="Question", placeholder="How do I treat mild hypothermia?") | |
| with gr.Row(): | |
| mode = gr.Radio(["Concise", "Step-by-step"], value="Concise", label="Style") | |
| max_new = gr.Slider(32, 512, 256, step=32, label="Max new tokens") | |
| temp = gr.Slider(0.0, 1.0, 0.3, step=0.05, label="Temperature") | |
| topp = gr.Slider(0.1, 1.0, 0.9, step=0.05, label="Top-p") | |
| btn = gr.Button("Answer") | |
| out = gr.Markdown(label="Answer") | |
| src = gr.Markdown(label="Sources") | |
| lat = gr.Label(label="Latency") | |
| btn.click(answer, inputs=[inp, mode, max_new, temp, topp], outputs=[out, src, lat]) | |
| if __name__ == "__main__": | |
| demo.launch() | |