Corin1998 commited on
Commit
1fd8f5d
·
verified ·
1 Parent(s): b57346f

Create ingest.py

Browse files
Files changed (1) hide show
  1. rag/ingest.py +92 -0
rag/ingest.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from typing import Dict, List, Any
3
+ import os, json, glob, re
4
+ from .util_text import clean_text
5
+
6
+ _TXT_EXT = {".txt", ".md", ".markdown"}
7
+ _JSON_EXT = {".json", ".jsonl"}
8
+
9
+ def _read_text(path: str) -> str:
10
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
11
+ return f.read()
12
+
13
+ def _title_from_text(t: str) -> str:
14
+ for line in t.splitlines():
15
+ s = clean_text(line)
16
+ if s:
17
+ return s[:80]
18
+ return "Untitled"
19
+
20
+ def _meta_from_text(t: str) -> dict:
21
+ meta = {}
22
+ # "lat: 35.6", "lon: 139.7" 的な記述を素朴に拾う
23
+ mlat = re.search(r"\blat(?:itude)?\s*[:=]\s*([-+]?\d+(?:\.\d+)?)", t, re.I)
24
+ mlon = re.search(r"\blon(?:gitude)?\s*[:=]\s*([-+]?\d+(?:\.\d+)?)", t, re.I)
25
+ if mlat and mlon:
26
+ meta["lat"] = float(mlat.group(1))
27
+ meta["lon"] = float(mlon.group(1))
28
+ # タグ行: "tags: a,b,c"
29
+ mtag = re.search(r"\btags?\s*[:=]\s*([^\n]+)", t, re.I)
30
+ if mtag:
31
+ tags = [s.strip() for s in mtag.group(1).split(",") if s.strip()]
32
+ meta["tags"] = tags
33
+ return meta
34
+
35
+ def _doc_from_json(obj: dict) -> dict:
36
+ text = clean_text(str(obj.get("text") or obj.get("body") or ""))
37
+ title = obj.get("title") or _title_from_text(text)
38
+ meta = obj.get("meta") or {}
39
+ for k in ("lat", "lon", "tags", "url", "city", "type"):
40
+ if k in obj and k not in meta:
41
+ meta[k] = obj[k]
42
+ meta.setdefault("title", title)
43
+ return {"id": str(obj.get("id") or title), "text": text, "meta": meta}
44
+
45
+ def build_corpus(dir_map: Dict[str, str]) -> List[dict]:
46
+ """
47
+ dir_map 例: {"blogs": "data/blogs", "reviews": "data/reviews", "events": "data/events"}
48
+ 各ディレクトリ配下の .txt/.md/.json/.jsonl を収集して Doc 配列を返す。
49
+ Doc = {"id","text","meta{title,lat,lon,tags,...}"}
50
+ """
51
+ docs: List[dict] = []
52
+ for _, d in (dir_map or {}).items():
53
+ if not d or not os.path.isdir(d):
54
+ continue
55
+ paths = []
56
+ for ext in list(_TXT_EXT | _JSON_EXT):
57
+ paths += glob.glob(os.path.join(d, f"**/*{ext}"), recursive=True)
58
+
59
+ for p in paths:
60
+ _, ext = os.path.splitext(p)
61
+ try:
62
+ if ext.lower() in _TXT_EXT:
63
+ t = clean_text(_read_text(p))
64
+ if not t:
65
+ continue
66
+ m = _meta_from_text(t)
67
+ title = _title_from_text(t)
68
+ m.setdefault("title", title)
69
+ docs.append({"id": p, "text": t, "meta": m})
70
+ else: # JSON / JSONL
71
+ raw = _read_text(p)
72
+ if ext.lower() == ".jsonl":
73
+ for line in raw.splitlines():
74
+ line = line.strip()
75
+ if not line:
76
+ continue
77
+ try:
78
+ obj = json.loads(line)
79
+ docs.append(_doc_from_json(obj))
80
+ except Exception:
81
+ continue
82
+ else:
83
+ obj = json.loads(raw)
84
+ if isinstance(obj, list):
85
+ for o in obj:
86
+ if isinstance(o, dict):
87
+ docs.append(_doc_from_json(o))
88
+ elif isinstance(obj, dict):
89
+ docs.append(_doc_from_json(obj))
90
+ except Exception:
91
+ continue
92
+ return docs