Spaces:
Runtime error
Runtime error
Download build_vectorstore.py from htchu/WeatherLRDDemo: direct link, hf CLI and curl.
- Browser
- Download file 5.96 kB
-
https://huggingface.co/spaces/htchu/WeatherLRDDemo/resolve/main/build_vectorstore.py
- Command line
-
hf download hf://spaces/htchu/WeatherLRDDemo/build_vectorstore.py
-
curl -L -o build_vectorstore.py https://huggingface.co/spaces/htchu/WeatherLRDDemo/resolve/main/build_vectorstore.py
5.96 kB
| """ | |
| 建立向量資料庫 | |
| 將爬取的法規文本切分並建立 FAISS 向量索引 | |
| """ | |
| import json | |
| import os | |
| import re | |
| import pickle | |
| from pathlib import Path | |
| import numpy as np | |
| import requests | |
| def load_laws(json_path="data/moenv_laws.json"): | |
| """載入爬取的法規 JSON""" | |
| with open(json_path, "r", encoding="utf-8") as f: | |
| return json.load(f) | |
| def chunk_text(text, chunk_size=500, overlap=100): | |
| """將文本切分為固定大小的段落,帶重疊""" | |
| if not text or len(text.strip()) == 0: | |
| return [] | |
| chunks = [] | |
| start = 0 | |
| while start < len(text): | |
| end = start + chunk_size | |
| chunk = text[start:end] | |
| if chunk.strip(): | |
| chunks.append(chunk.strip()) | |
| start += chunk_size - overlap | |
| return chunks | |
| def chunk_by_articles(content, title="", category=""): | |
| """按條文切分法規內容""" | |
| prefix = "" | |
| if title: | |
| prefix += f"法規名稱:{title}\n" | |
| if category: | |
| prefix += f"分類:{category}\n" | |
| # 嘗試按「第 X 條」切分 | |
| articles = re.split(r"(?=第\s*\d+(?:-\d+)?\s*條)", content) | |
| chunks = [] | |
| for article in articles: | |
| article = article.strip() | |
| if not article: | |
| continue | |
| full_text = prefix + article if prefix else article | |
| # 如果單一條文太長,再做二次切分 | |
| if len(full_text) > 800: | |
| sub_chunks = chunk_text(full_text, chunk_size=500, overlap=100) | |
| chunks.extend(sub_chunks) | |
| else: | |
| chunks.append(full_text) | |
| # 如果沒有條文格式,就用固定大小切分 | |
| if not chunks: | |
| full_text = prefix + content if prefix else content | |
| chunks = chunk_text(full_text, chunk_size=500, overlap=100) | |
| return chunks | |
| def get_embeddings_twcc(texts, api_url, api_key, model="ffm-embedding"): | |
| """使用 TWCC oneAI AFS 取得 embedding""" | |
| headers = { | |
| "Content-Type": "application/json", | |
| "X-API-KEY": api_key, | |
| } | |
| url = f"{api_url}/embeddings" | |
| all_embeddings = [] | |
| # 分批處理,每次最多 8 筆 | |
| batch_size = 8 | |
| for i in range(0, len(texts), batch_size): | |
| batch = texts[i : i + batch_size] | |
| payload = {"model": model, "inputs": batch} | |
| resp = requests.post(url, json=payload, headers=headers, timeout=60) | |
| resp.raise_for_status() | |
| data = resp.json() | |
| for item in data.get("data", []): | |
| all_embeddings.append(item["embedding"]) | |
| if i % 50 == 0 and i > 0: | |
| print(f" 已處理 {i}/{len(texts)} 筆 embeddings") | |
| return np.array(all_embeddings, dtype=np.float32) | |
| def get_embeddings_local(texts): | |
| """使用 sentence-transformers 本地模型取得 embedding(備用方案)""" | |
| from sentence_transformers import SentenceTransformer | |
| model = SentenceTransformer("paraphrase-multilingual-MiniLM-L12-v2") | |
| embeddings = model.encode(texts, show_progress_bar=True, batch_size=32) | |
| return np.array(embeddings, dtype=np.float32) | |
| def build_faiss_index(embeddings): | |
| """建立 FAISS 索引""" | |
| import faiss | |
| dim = embeddings.shape[1] | |
| index = faiss.IndexFlatIP(dim) # 內積相似度(需先正規化) | |
| # L2 正規化 | |
| faiss.normalize_L2(embeddings) | |
| index.add(embeddings) | |
| return index | |
| def main(): | |
| import argparse | |
| parser = argparse.ArgumentParser(description="建立法規向量資料庫") | |
| parser.add_argument( | |
| "--embedding", | |
| choices=["twcc", "local"], | |
| default="local", | |
| help="Embedding 方式:twcc (使用 TWCC API) 或 local (本地模型)", | |
| ) | |
| parser.add_argument("--twcc-api-url", default="", help="TWCC AFS API URL") | |
| parser.add_argument("--twcc-api-key", default="", help="TWCC AFS API Key") | |
| parser.add_argument( | |
| "--input", default="data/moenv_laws.json", help="法規 JSON 檔案路徑" | |
| ) | |
| parser.add_argument("--output-dir", default="vectorstore", help="輸出目錄") | |
| args = parser.parse_args() | |
| # 載入法規 | |
| print("載入法規資料...") | |
| laws = load_laws(args.input) | |
| print(f"共載入 {len(laws)} 筆法規") | |
| # 切分文本 | |
| print("切分文本...") | |
| all_chunks = [] | |
| all_metadata = [] | |
| for law in laws: | |
| chunks = chunk_by_articles( | |
| law.get("content", ""), | |
| title=law.get("title", ""), | |
| category=law.get("category_name", ""), | |
| ) | |
| for chunk in chunks: | |
| all_chunks.append(chunk) | |
| all_metadata.append( | |
| { | |
| "law_id": law.get("id", ""), | |
| "title": law.get("title", ""), | |
| "category": law.get("category_name", ""), | |
| "publish_date": law.get("publish_date", ""), | |
| } | |
| ) | |
| print(f"共切分為 {len(all_chunks)} 個文本段落") | |
| # 產生 embeddings | |
| print("產生 embeddings...") | |
| if args.embedding == "twcc": | |
| if not args.twcc_api_url or not args.twcc_api_key: | |
| raise ValueError("使用 TWCC embedding 需提供 --twcc-api-url 和 --twcc-api-key") | |
| embeddings = get_embeddings_twcc( | |
| all_chunks, args.twcc_api_url, args.twcc_api_key | |
| ) | |
| else: | |
| embeddings = get_embeddings_local(all_chunks) | |
| print(f"Embedding 維度: {embeddings.shape}") | |
| # 建立 FAISS 索引 | |
| print("建立 FAISS 索引...") | |
| index = build_faiss_index(embeddings) | |
| # 儲存 | |
| output_dir = Path(args.output_dir) | |
| output_dir.mkdir(exist_ok=True) | |
| import faiss | |
| faiss.write_index(index, str(output_dir / "laws.index")) | |
| with open(output_dir / "chunks.pkl", "wb") as f: | |
| pickle.dump({"chunks": all_chunks, "metadata": all_metadata}, f) | |
| print(f"向量資料庫已儲存至 {output_dir}/") | |
| print(f" - laws.index ({index.ntotal} 向量)") | |
| print(f" - chunks.pkl ({len(all_chunks)} 段落)") | |
| if __name__ == "__main__": | |
| main() | |