first commit

This commit is contained in:
2026-03-19 22:54:29 +03:30
parent 1a178f39b7
commit 035bc6f74d
91 changed files with 3821 additions and 130 deletions
+49 -32
View File
@@ -1,10 +1,10 @@
"""
پایپ‌لاین ورودی RAG: خواندن، چانک، embed و ذخیره در vector store
پایپ‌لاین ورودی RAG: خواندن، چانک، embed و ذخیره در vector store — با پشتیبانی از چند پایگاه دانش
سه منبع:
۱. لحن (tone) — sensor_uuid=__global__
۲. پایگاه دانش (knowledge base) — sensor_uuid=__global__
۳. دیتای خاک هر کاربر از DB (sensor_data + soil_data) — sensor_uuid=uuid
منابع:
۱. لحن هر پایگاه دانش (tone) — sensor_uuid=__global__, kb_name=chat|irrigation|fertilization
۲. پایگاه‌های دانش سه‌گانه — sensor_uuid=__global__, kb_name=chat|irrigation|fertilization
۳. دیتای خاک + هواشناسی هر کاربر از DB — sensor_uuid=uuid, kb_name=__all__
"""
import uuid
from pathlib import Path
@@ -12,14 +12,15 @@ from pathlib import Path
from .chunker import chunk_text, chunk_texts
from .config import load_rag_config, RAGConfig
from .embedding import embed_texts
from .user_data import load_user_sources
from .user_data import load_user_sources, build_user_weather_text
from .vector_store import QdrantVectorStore
# پسوندهای قابل خواندن
TEXT_EXTENSIONS = {".txt", ".md", ".rst", ".json"}
SENSOR_UUID_GLOBAL = "__global__"
KB_NAME_ALL = "__all__"
def _resolve_path(base: Path, p: str) -> Path:
"""تبدیل مسیر نسبی به مطلق نسبت به base پروژه."""
@@ -57,49 +58,64 @@ def _load_files_from_dir(dir_path: Path, prefix: str = "kb") -> list[tuple[str,
return out
def load_sources(config: RAGConfig | None = None) -> list[tuple[str, str, str]]:
def load_sources(
config: RAGConfig | None = None,
kb_name: str | None = None,
) -> list[tuple[str, str, str, str]]:
"""
بارگذاری سه منبع: لحن، پایگاه دانش، دیتای کاربر از DB.
بارگذاری منابع: لحن‌ها، پایگاه‌های دانش سه‌گانه، دیتای کاربران.
اگر kb_name مشخص شود، فقط آن پایگاه دانش لود می‌شود.
Returns:
[(source_id, content, sensor_uuid), ...]
sensor_uuid: __global__ برای tone/kb، uuid سنسور برای user
[(source_id, content, sensor_uuid, kb_name), ...]
"""
cfg = config or load_rag_config()
base = Path(__file__).resolve().parent.parent
sources: list[tuple[str, str, str]] = []
sources: list[tuple[str, str, str, str]] = []
# ۱. لحن
tone_path = _resolve_path(base, cfg.tone_file)
content = _load_file(tone_path)
if content:
sources.append(("tone", content, SENSOR_UUID_GLOBAL))
kbs_to_load = cfg.knowledge_bases.items()
if kb_name:
kbs_to_load = [(k, v) for k, v in kbs_to_load if k == kb_name]
# ۲. پایگاه دانش
kb_path = _resolve_path(base, cfg.knowledge_base_path)
for sid, c in _load_files_from_dir(kb_path, prefix="kb"):
sources.append((sid, c, SENSOR_UUID_GLOBAL))
if kb_path.is_file():
content = _load_file(kb_path)
for kbn, kb_cfg in kbs_to_load:
tone_path = _resolve_path(base, kb_cfg.tone_file)
content = _load_file(tone_path)
if content:
sources.append((f"kb:{kb_path.name}", content, SENSOR_UUID_GLOBAL))
sources.append((f"tone:{kbn}", content, SENSOR_UUID_GLOBAL, kbn))
kb_path = _resolve_path(base, kb_cfg.path)
for sid, c in _load_files_from_dir(kb_path, prefix=f"kb:{kbn}"):
sources.append((sid, c, SENSOR_UUID_GLOBAL, kbn))
if kb_path.is_file():
content = _load_file(kb_path)
if content:
sources.append((f"kb:{kbn}:{kb_path.name}", content, SENSOR_UUID_GLOBAL, kbn))
# ۳. دیتای کاربران از sensor_data + soil_data
for sid, content in load_user_sources():
sensor_uuid = sid.replace("user:", "")
sources.append((sid, content, sensor_uuid))
if sid.startswith("user:"):
sensor_uuid = sid.replace("user:", "")
elif sid.startswith("weather:"):
sensor_uuid = sid.replace("weather:", "")
else:
sensor_uuid = sid
sources.append((sid, content, sensor_uuid, KB_NAME_ALL))
return sources
def ingest(recreate: bool = False, config: RAGConfig | None = None) -> dict:
def ingest(
recreate: bool = False,
config: RAGConfig | None = None,
kb_name: str | None = None,
) -> dict:
"""
ورودی کامل: منابع را می‌خواند، چانک می‌کند، embed می‌کند و به vector store می‌فرستد.
دیتای هر کاربر (sensor_uuid) جدا embed و با metadata ذخیره می‌شود.
ورودی کامل: منابع را می‌خواند، چانک، embed و به vector store می‌فرستد.
kb_name اختیاری: اگر مشخص شود فقط آن پایگاه دانش ingest می‌شود.
Args:
recreate: اگر True باشد، collection را از نو می‌سازد
config: تنظیمات RAG
kb_name: نام پایگاه دانش (chat/irrigation/fertilization) — اختیاری
Returns:
آمار ورودی (تعداد چانک، منبع‌ها، خطاها)
@@ -109,7 +125,7 @@ def ingest(recreate: bool = False, config: RAGConfig | None = None) -> dict:
if recreate:
store.ensure_collection(recreate=True)
sources = load_sources(config=cfg)
sources = load_sources(config=cfg, kb_name=kb_name)
if not sources:
return {"chunks_added": 0, "sources": [], "error": "هیچ منبعی یافت نشد"}
@@ -117,7 +133,7 @@ def ingest(recreate: bool = False, config: RAGConfig | None = None) -> dict:
all_metas: list[dict] = []
all_ids: list[str] = []
for source_id, content, sensor_uuid in sources:
for source_id, content, sensor_uuid, src_kb in sources:
chunks = chunk_text(content, config=cfg)
for i, ch in enumerate(chunks):
uid = str(uuid.uuid4())
@@ -127,6 +143,7 @@ def ingest(recreate: bool = False, config: RAGConfig | None = None) -> dict:
"source": source_id,
"chunk_index": i,
"sensor_uuid": sensor_uuid,
"kb_name": src_kb,
})
if not all_chunks: