Download chat.py from elijah12e3rfr/law_processed: direct link, hf CLI and curl.
- Browser
- Download file 1.66 kB
-
https://huggingface.co/elijah12e3rfr/law_processed/resolve/main/chat.py
- Command line
-
hf download hf://elijah12e3rfr/law_processed/chat.py
-
curl -L -o chat.py https://huggingface.co/elijah12e3rfr/law_processed/resolve/main/chat.py
1.66 kB
| #!/usr/bin/env python3 | |
| from pathlib import Path | |
| import pickle | |
| import faiss | |
| import numpy as np | |
| import requests | |
| # — copy these from your embed_law.py — | |
| OLLAMA_URL = "http://localhost:11434" # or use os.getenv if you prefer | |
| EMBED_MODEL = "mxbai-embed-large" # same as before | |
| INDEX_DIR = Path("law_index_ollama") | |
| INDEX_PATH = INDEX_DIR / "faiss_ollama.index" | |
| META_PATH = INDEX_DIR / "metadata_ollama.pkl" | |
| def get_ollama_embedding(text: str) -> np.ndarray: | |
| resp = requests.post( | |
| f"{OLLAMA_URL}/api/embeddings", | |
| json={"model": EMBED_MODEL, "prompt": text}, | |
| timeout=30 | |
| ); resp.raise_for_status() | |
| vec = np.array(resp.json()["embedding"], dtype=np.float32) | |
| return vec / np.linalg.norm(vec, ord=2) | |
| def load_index(): | |
| idx = faiss.read_index(str(INDEX_PATH)) | |
| records = pickle.load(open(META_PATH, "rb")) | |
| return idx, records | |
| def search_laws(query: str, idx, records, top_k: int = 5): | |
| q_emb = get_ollama_embedding(query) | |
| scores, ids = idx.search(q_emb.reshape(1, -1), top_k) | |
| out = [] | |
| for s, i in zip(scores[0], ids[0]): | |
| rec = records[i] | |
| out.append((s, rec["law_name"], rec["article_title"], rec["text"])) | |
| return out | |
| if __name__ == "__main__": | |
| idx, records = load_index() | |
| tests = [ | |
| "國父陵園管理委員會組織條例 第1條", | |
| "公司法 第23條 董事職責", | |
| "民法 繼承 程序 時效" | |
| ] | |
| for q in tests: | |
| print(f"\n=== Query: {q} ===") | |
| for score, law, art, text in search_laws(q, idx, records, top_k=3): | |
| print(f"{score:.4f} | {law} | {art}\n {text[:80]}…") | |