Download main.py from elijah12e3rfr/law_processed: direct link, hf CLI and curl.
- Browser
- Download file 4.9 kB
-
https://huggingface.co/elijah12e3rfr/law_processed/resolve/main/main.py
- Command line
-
hf download hf://elijah12e3rfr/law_processed/main.py
-
curl -L -o main.py https://huggingface.co/elijah12e3rfr/law_processed/resolve/main/main.py
4.9 kB
| #!/usr/bin/env python3 | |
| import sys | |
| import os | |
| import json | |
| import pickle | |
| import numpy as np | |
| import faiss | |
| import requests | |
| from pathlib import Path | |
| from typing import List, Dict | |
| # โโ Load .env before anything else so os.getenv() works โโโโโโโโโโโโโโโโโโโโโโโโ | |
| from dotenv import load_dotenv | |
| BASE_DIR = Path(__file__).parent.resolve() | |
| load_dotenv(BASE_DIR / ".env") | |
| # โโ CONFIG โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| INDEX_DIR = BASE_DIR / "law_index_ollama" | |
| INDEX_PATH = INDEX_DIR / "faiss_ollama.index" | |
| META_PATH = INDEX_DIR / "metadata_ollama.pkl" | |
| OLLAMA_BASE_URL = "http://localhost:11434" | |
| EMBED_MODEL = "mxbai-embed-large" | |
| # โโ OpenAI settings (new SDK) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| import openai | |
| openai.api_key = os.getenv("OPENAI_API_KEY") | |
| MODEL = "gpt-4o-mini" | |
| # โโ Helper: get one Ollama embedding โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| def get_ollama_embedding(text: str) -> np.ndarray: | |
| resp = requests.post( | |
| f"{OLLAMA_BASE_URL}/api/embeddings", | |
| json={"model": EMBED_MODEL, "prompt": text}, | |
| timeout=30 | |
| ) | |
| resp.raise_for_status() | |
| emb = np.array(resp.json()["embedding"], dtype=np.float32) | |
| return emb / np.linalg.norm(emb) | |
| # โโ Lazyโload FAISS + records โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| _index: faiss.IndexFlatIP = None | |
| _records: List[Dict] = None | |
| def _load_index_and_records(): | |
| global _index, _records | |
| if _index is None or _records is None: | |
| if not INDEX_PATH.exists() or not META_PATH.exists(): | |
| raise FileNotFoundError( | |
| f"Index or metadata missing in {INDEX_DIR}. Run your indexing script first." | |
| ) | |
| _index = faiss.read_index(str(INDEX_PATH)) | |
| with open(META_PATH, "rb") as f: | |
| _records = pickle.load(f) | |
| return _index, _records | |
| # โโ Moduleโlevel retrieval function โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| def semantic_search(query: str, top_k: int = 5) -> List[Dict]: | |
| idx, recs = _load_index_and_records() | |
| q_emb = get_ollama_embedding(query) | |
| D, I = idx.search(q_emb.reshape(1, -1), top_k) | |
| out = [] | |
| for score, i in zip(D[0], I[0]): | |
| meta = recs[i]["meta"] | |
| citation = f"{meta['law_name']}{meta['article_title']}" | |
| out.append({ | |
| "score": float(score), | |
| "citation": citation, | |
| "text": recs[i]["text"] | |
| }) | |
| return out | |
| # โโ OpenAI summary function โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| def generate_summary(query: str) -> str: | |
| hits = semantic_search(query, top_k=5) | |
| if not hits: | |
| return "โ ๏ธ ๆฑๆญ๏ผๆชๆพๅฐ็ธ้ๆณๆขๆ้ใ" | |
| context = "\n\n".join( | |
| f"[{i+1}] {h['citation']}\nโฆ{h['text'][:200]}โฆ" | |
| for i, h in enumerate(hits) | |
| ) | |
| messages = [ | |
| { | |
| "role": "system", | |
| "content": ( | |
| "ไฝ ๆฏไธไฝ็ฒพ้ๅฐ็ฃๆณๅพ็ AI ๅฉๆใ" | |
| "่ซๆ นๆๆไปฅไธๆไพ็ๆณๆขๆ้๏ผ" | |
| "็จๅๆฎตๆนๅผใไพๅนด้ฝกๅ้่ชชๆใๆชๆๅนดไบบ็ฏ็ฝช็่็ฝฐๆนๅผใใ" | |
| "ๅจๆ่ฆไธญ๏ผๅผ็จ่ฆ็จใๆณๆขๅ็จฑ๏ผ็ฌฌXๆขใ็ๆ ผๅผใ" | |
| ) | |
| }, | |
| { | |
| "role": "user", | |
| "content": ( | |
| f"ๅ้ก๏ผ{query}\n\n" | |
| f"ๆณๆขๆ้๏ผ\n{context}\n\n" | |
| "่ซๆด็ๅบๆชๆๅนดไบบ็ฏ็ฝช็่็ฝฐๆถๆง๏ผ" | |
| "ไธฆไปฅๅนด้ฝกๅ้ๅๆฎต่ชชๆ๏ผ้้ปๆจๅบๅๆขๆ็ใ็ฌฌXๆขใใ" | |
| ) | |
| } | |
| ] | |
| resp = openai.chat.completions.create( | |
| model=MODEL, | |
| messages=messages, | |
| temperature=0.2, | |
| max_tokens=500 | |
| ) | |
| return resp.choices[0].message.content.strip() | |
| # โโ CLI entrypoint โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| if __name__ == "__main__": | |
| q = sys.argv[1] if len(sys.argv) > 1 else "ๆชๆๅนดไบบ็ฏ็ฝช็่็ฝฐๆนๅผ" | |
| print("๐ ๆชข็ดข่ๆ่ฆไธญโฆ\n") | |
| print(generate_summary(q)) | |