hakua-memory 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hakua_memory/__init__.py +21 -0
- hakua_memory/composite.py +257 -0
- hakua_memory/config.py +168 -0
- hakua_memory/ebbinghaus/__init__.py +862 -0
- hakua_memory/ebbinghaus/experience.py +1488 -0
- hakua_memory/ebbinghaus/migrations.py +362 -0
- hakua_memory/ebbinghaus/models.py +85 -0
- hakua_memory/ebbinghaus/policies.py +529 -0
- hakua_memory/ebbinghaus/semantic_graph_bridge.py +764 -0
- hakua_memory/ebbinghaus/store.py +2736 -0
- hakua_memory/obsidian/__init__.py +32 -0
- hakua_memory/obsidian/templates.py +212 -0
- hakua_memory/rag/__init__.py +36 -0
- hakua_memory/rag/chunking.py +150 -0
- hakua_memory/rag/contradiction.py +228 -0
- hakua_memory/rag/ingestion.py +260 -0
- hakua_memory/rag/meeting.py +150 -0
- hakua_memory/rag/models.py +156 -0
- hakua_memory/rag/retrieval.py +235 -0
- hakua_memory/rag/schema.py +159 -0
- hakua_memory/rag/store.py +539 -0
- hakua_memory/semantic_graph/__init__.py +23 -0
- hakua_memory/semantic_graph/cli.py +161 -0
- hakua_memory/semantic_graph/cognitive.py +174 -0
- hakua_memory/semantic_graph/config.py +273 -0
- hakua_memory/semantic_graph/embedding/__init__.py +45 -0
- hakua_memory/semantic_graph/embedding/base.py +57 -0
- hakua_memory/semantic_graph/embedding/fake.py +78 -0
- hakua_memory/semantic_graph/embedding/llama_cpp.py +221 -0
- hakua_memory/semantic_graph/embedding/serializer.py +65 -0
- hakua_memory/semantic_graph/embedding/vectors.py +144 -0
- hakua_memory/semantic_graph/exporter.py +132 -0
- hakua_memory/semantic_graph/fusion.py +85 -0
- hakua_memory/semantic_graph/graph.py +480 -0
- hakua_memory/semantic_graph/inference.py +103 -0
- hakua_memory/semantic_graph/models.py +156 -0
- hakua_memory/semantic_graph/retrieval.py +235 -0
- hakua_memory/semantic_graph/runtime.py +1185 -0
- hakua_memory/semantic_graph/sanitize.py +164 -0
- hakua_memory/semantic_graph/schemas.py +462 -0
- hakua_memory/semantic_graph/store.py +1533 -0
- hakua_memory-0.2.0.dist-info/METADATA +238 -0
- hakua_memory-0.2.0.dist-info/RECORD +46 -0
- hakua_memory-0.2.0.dist-info/WHEEL +5 -0
- hakua_memory-0.2.0.dist-info/licenses/LICENSE +201 -0
- hakua_memory-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Obsidian Wiki bridge for hakua-memory."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from hakua_memory.ebbinghaus.store import _normalize_text
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _safe_slug(text: str, max_len: int = 64) -> str:
|
|
11
|
+
text = _normalize_text(text)
|
|
12
|
+
text = text.replace(" ", "-")
|
|
13
|
+
text = "".join(ch for ch in text if ch.isalnum() or ch in "-_.")
|
|
14
|
+
return text[:max_len] or "note"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def write_diary(wiki_root: Path, title: str, body: str) -> Path:
|
|
18
|
+
wiki_root.mkdir(parents=True, exist_ok=True)
|
|
19
|
+
diary = wiki_root / "diary"
|
|
20
|
+
diary.mkdir(exist_ok=True)
|
|
21
|
+
path = diary / f"{_safe_slug(title)}.md"
|
|
22
|
+
path.write_text(f"# {title}\n\n{body}\n", encoding="utf-8")
|
|
23
|
+
return path
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def write_dream(wiki_root: Path, body: str) -> Path:
|
|
27
|
+
wiki_root.mkdir(parents=True, exist_ok=True)
|
|
28
|
+
dreams = wiki_root / "dreams"
|
|
29
|
+
dreams.mkdir(exist_ok=True)
|
|
30
|
+
path = dreams / "latest.md"
|
|
31
|
+
path.write_text(f"# Dream\n\n{body}\n", encoding="utf-8")
|
|
32
|
+
return path
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"""Obsidian template management and export."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
from typing import Any, Optional
|
|
7
|
+
|
|
8
|
+
from hakua_memory.config import ObsidianConfig
|
|
9
|
+
|
|
10
|
+
# ── Default Templates ────────────────────────────────────────────────
|
|
11
|
+
|
|
12
|
+
DEFAULT_DIARY_TEMPLATE = """# {{title}}
|
|
13
|
+
|
|
14
|
+
> Date: {{date}}
|
|
15
|
+
> Type: Diary
|
|
16
|
+
|
|
17
|
+
{{content}}
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
*Generated by hakua-memory*
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
DEFAULT_DREAM_TEMPLATE = """# {{title}}
|
|
24
|
+
|
|
25
|
+
> Date: {{date}}
|
|
26
|
+
> Type: Dream
|
|
27
|
+
> Source: Ebbinghaus sleep cycle
|
|
28
|
+
|
|
29
|
+
{{content}}
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
*Generated by hakua-memory*
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
DEFAULT_SLEEP_LOG_TEMPLATE = """# 睡眠ログ {{month}}
|
|
36
|
+
|
|
37
|
+
## 概要
|
|
38
|
+
- レビュー対象: {{review_count}}件の記憶
|
|
39
|
+
- 再練習対象: {{rehearsal_count}}件
|
|
40
|
+
- 忘却対象: {{forget_count}}件
|
|
41
|
+
- 記憶圧縮率: {{compression_rate:.1%}}
|
|
42
|
+
|
|
43
|
+
## 再練習された記憶
|
|
44
|
+
{{rehearsal_list}}
|
|
45
|
+
|
|
46
|
+
## 忘却された記憶
|
|
47
|
+
{{forgotten_list}}
|
|
48
|
+
|
|
49
|
+
## 洞察
|
|
50
|
+
{{insights}}
|
|
51
|
+
|
|
52
|
+
## Ebbinghaus 忘却曲線
|
|
53
|
+
{{forgetting_curve}}
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
*Generated by hakua-memory*
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
DEFAULT_GRAPH_TEMPLATE = """# セマンティックグラフ {{month}}
|
|
60
|
+
|
|
61
|
+
## ノード統計
|
|
62
|
+
- 総ノード数: {{node_count}}
|
|
63
|
+
- アクティブ: {{active_count}}
|
|
64
|
+
- 候補: {{candidate_count}}
|
|
65
|
+
- 却下: {{rejected_count}}
|
|
66
|
+
|
|
67
|
+
## 主要ノード
|
|
68
|
+
{{top_nodes}}
|
|
69
|
+
|
|
70
|
+
## グラフ可視化
|
|
71
|
+
{{mermaid_graph}}
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
*Generated by hakua-memory*
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ObsidianTemplateRenderer:
|
|
79
|
+
"""Renders Obsidian-compatible markdown from templates."""
|
|
80
|
+
|
|
81
|
+
def __init__(self, config: Optional[ObsidianConfig] = None) -> None:
|
|
82
|
+
self.config = config or ObsidianConfig()
|
|
83
|
+
self.templates = {
|
|
84
|
+
"diary": self.config.diary_template or DEFAULT_DIARY_TEMPLATE,
|
|
85
|
+
"dream": self.config.dream_template or DEFAULT_DREAM_TEMPLATE,
|
|
86
|
+
"sleep_log": self.config.sleep_log_template or DEFAULT_SLEEP_LOG_TEMPLATE,
|
|
87
|
+
"graph": DEFAULT_GRAPH_TEMPLATE,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
def render(self, template_name: str, **kwargs: Any) -> str:
|
|
91
|
+
"""Render a template with given context."""
|
|
92
|
+
template = self.templates.get(template_name, "")
|
|
93
|
+
if not template:
|
|
94
|
+
return ""
|
|
95
|
+
|
|
96
|
+
# Add default context
|
|
97
|
+
context = {
|
|
98
|
+
"date": datetime.now(timezone.utc).strftime("%Y-%m-%d"),
|
|
99
|
+
"month": datetime.now(timezone.utc).strftime("%Y-%m"),
|
|
100
|
+
}
|
|
101
|
+
context.update(kwargs)
|
|
102
|
+
|
|
103
|
+
# Simple template substitution
|
|
104
|
+
result = template
|
|
105
|
+
for key, value in context.items():
|
|
106
|
+
placeholder = "{{" + key + "}}"
|
|
107
|
+
result = result.replace(placeholder, str(value))
|
|
108
|
+
|
|
109
|
+
return result
|
|
110
|
+
|
|
111
|
+
def render_sleep_log(
|
|
112
|
+
self,
|
|
113
|
+
review_count: int,
|
|
114
|
+
rehearsal_count: int,
|
|
115
|
+
forget_count: int,
|
|
116
|
+
rehearsal_list: list[str],
|
|
117
|
+
forgotten_list: list[str],
|
|
118
|
+
insights: list[str],
|
|
119
|
+
forgetting_curve: str = "",
|
|
120
|
+
) -> str:
|
|
121
|
+
"""Render sleep log template."""
|
|
122
|
+
compression_rate = (
|
|
123
|
+
(review_count - forget_count) / review_count if review_count > 0 else 1.0
|
|
124
|
+
)
|
|
125
|
+
return self.render(
|
|
126
|
+
"sleep_log",
|
|
127
|
+
review_count=review_count,
|
|
128
|
+
rehearsal_count=rehearsal_count,
|
|
129
|
+
forget_count=forget_count,
|
|
130
|
+
compression_rate=compression_rate,
|
|
131
|
+
rehearsal_list="\n".join(f"- {r}" for r in rehearsal_list) or "(なし)",
|
|
132
|
+
forgotten_list="\n".join(f"- {f}" for f in forgotten_list) or "(なし)",
|
|
133
|
+
insights="\n".join(f"- {i}" for i in insights) or "(なし)",
|
|
134
|
+
forgetting_curve=forgetting_curve or "(プロットなし)",
|
|
135
|
+
)
|
|
136
|
+
|
|
137
|
+
def render_graph_summary(
|
|
138
|
+
self,
|
|
139
|
+
node_count: int,
|
|
140
|
+
active_count: int,
|
|
141
|
+
candidate_count: int,
|
|
142
|
+
rejected_count: int,
|
|
143
|
+
top_nodes: list[dict[str, Any]],
|
|
144
|
+
mermaid_graph: str = "",
|
|
145
|
+
) -> str:
|
|
146
|
+
"""Render graph summary template."""
|
|
147
|
+
top_nodes_str = "\n".join(
|
|
148
|
+
f"- [{n.get('status', 'unknown')}] {n.get('label', n.get('node_id', 'unknown'))}"
|
|
149
|
+
for n in top_nodes[:10]
|
|
150
|
+
)
|
|
151
|
+
return self.render(
|
|
152
|
+
"graph",
|
|
153
|
+
node_count=node_count,
|
|
154
|
+
active_count=active_count,
|
|
155
|
+
candidate_count=candidate_count,
|
|
156
|
+
rejected_count=rejected_count,
|
|
157
|
+
top_nodes=top_nodes_str or "(ノードなし)",
|
|
158
|
+
mermaid_graph=mermaid_graph or "(グラフなし)",
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def generate_mermaid_graph(nodes: list[dict[str, Any]], edges: list[dict[str, Any]]) -> str:
|
|
163
|
+
"""Generate Mermaid graph syntax from nodes and edges."""
|
|
164
|
+
lines = ["graph TD", " %% Generated by hakua-memory"]
|
|
165
|
+
|
|
166
|
+
# Add nodes with styles
|
|
167
|
+
for node in nodes[:20]: # Limit to 20 nodes for readability
|
|
168
|
+
node_id = node.get("node_id", "unknown").replace("-", "_")
|
|
169
|
+
label = node.get("label", node_id)[:20]
|
|
170
|
+
status = node.get("status", "unknown")
|
|
171
|
+
|
|
172
|
+
# Style based on status
|
|
173
|
+
if status == "accepted":
|
|
174
|
+
lines.append(f' {node_id}["{label}"]:::accepted')
|
|
175
|
+
elif status == "asserted":
|
|
176
|
+
lines.append(f' {node_id}["{label}"]:::asserted')
|
|
177
|
+
elif status == "candidate":
|
|
178
|
+
lines.append(f' {node_id}["{label}"]:::candidate')
|
|
179
|
+
else:
|
|
180
|
+
lines.append(f' {node_id}["{label}"]')
|
|
181
|
+
|
|
182
|
+
# Add class definitions
|
|
183
|
+
lines.append(" classDef accepted fill:#9f9,stroke:#333,stroke-width:2px")
|
|
184
|
+
lines.append(" classDef asserted fill:#9cf,stroke:#333,stroke-width:2px")
|
|
185
|
+
lines.append(" classDef candidate fill:#fcc,stroke:#333,stroke-width:1px")
|
|
186
|
+
|
|
187
|
+
# Add edges
|
|
188
|
+
for edge in edges[:15]: # Limit to 15 edges
|
|
189
|
+
source = edge.get("source", "").replace("-", "_")
|
|
190
|
+
target = edge.get("target", "").replace("-", "_")
|
|
191
|
+
rel = edge.get("relationship", "relates_to")[:15]
|
|
192
|
+
if source and target:
|
|
193
|
+
lines.append(f" {source} -->|{rel}| {target}")
|
|
194
|
+
|
|
195
|
+
return "\n".join(lines)
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def generate_forgetting_curve_mermaid(
|
|
199
|
+
intervals: list[int],
|
|
200
|
+
retention_rates: list[float],
|
|
201
|
+
) -> str:
|
|
202
|
+
"""Generate Mermaid XY chart for forgetting curve."""
|
|
203
|
+
lines = [
|
|
204
|
+
"xychart-beta",
|
|
205
|
+
" title Ebbinghaus Forgetting Curve",
|
|
206
|
+
" x-axis [hours] " + ", ".join(str(i) for i in intervals),
|
|
207
|
+
" y-axisRetention Rate",
|
|
208
|
+
]
|
|
209
|
+
# Add data
|
|
210
|
+
data = ", ".join(f"{r:.2f}" for r in retention_rates)
|
|
211
|
+
lines.append(f" line [{data}]")
|
|
212
|
+
return "\n".join(lines)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""RAG module: document ingestion, retrieval, meeting extraction, contradictions."""
|
|
2
|
+
|
|
3
|
+
from .chunking import chunk_pages, chunk_slides, chunk_text
|
|
4
|
+
from .contradiction import Contradiction, detect_contradictions
|
|
5
|
+
from .ingestion import (
|
|
6
|
+
ingest_document,
|
|
7
|
+
ingest_markdown_string,
|
|
8
|
+
ingest_text_string,
|
|
9
|
+
)
|
|
10
|
+
from .meeting import extract_meeting_items
|
|
11
|
+
from .models import AclEntry, Chunk, Citation, Document, MeetingItem
|
|
12
|
+
from .retrieval import RagResult, render_citation_context, search_chunks
|
|
13
|
+
from .schema import ALL_DDL
|
|
14
|
+
from .store import DocumentStore
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"DocumentStore",
|
|
18
|
+
"Document",
|
|
19
|
+
"Chunk",
|
|
20
|
+
"Citation",
|
|
21
|
+
"MeetingItem",
|
|
22
|
+
"AclEntry",
|
|
23
|
+
"RagResult",
|
|
24
|
+
"Contradiction",
|
|
25
|
+
"ingest_document",
|
|
26
|
+
"ingest_markdown_string",
|
|
27
|
+
"ingest_text_string",
|
|
28
|
+
"chunk_text",
|
|
29
|
+
"chunk_pages",
|
|
30
|
+
"chunk_slides",
|
|
31
|
+
"search_chunks",
|
|
32
|
+
"render_citation_context",
|
|
33
|
+
"extract_meeting_items",
|
|
34
|
+
"detect_contradictions",
|
|
35
|
+
"ALL_DDL",
|
|
36
|
+
]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Document chunking with page/slide/section awareness."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import re
|
|
7
|
+
import uuid
|
|
8
|
+
from typing import Sequence
|
|
9
|
+
|
|
10
|
+
from .models import Chunk
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _sha256(text: str) -> str:
|
|
14
|
+
return hashlib.sha256(text.encode("utf-8")).hexdigest()
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _now_iso() -> str:
|
|
18
|
+
from datetime import datetime, timezone
|
|
19
|
+
return datetime.now(timezone.utc).isoformat()
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _estimate_tokens(text: str) -> int:
|
|
23
|
+
"""Rough token estimate: CJK chars count individually, words by whitespace."""
|
|
24
|
+
cjk = len(re.findall(r"[一-鿿-ヿ가-]", text))
|
|
25
|
+
non_cjk = re.sub(r"[一-鿿-ヿ가-]", "", text)
|
|
26
|
+
words = len(non_cjk.split())
|
|
27
|
+
return cjk + words
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def chunk_text(
|
|
31
|
+
text: str,
|
|
32
|
+
document_id: str,
|
|
33
|
+
*,
|
|
34
|
+
chunk_size: int = 512,
|
|
35
|
+
chunk_overlap: int = 64,
|
|
36
|
+
page_number: int | None = None,
|
|
37
|
+
slide_number: int | None = None,
|
|
38
|
+
section: str = "",
|
|
39
|
+
separator: str = "\n\n",
|
|
40
|
+
) -> list[Chunk]:
|
|
41
|
+
"""Split text into overlapping chunks with provenance."""
|
|
42
|
+
if not text.strip():
|
|
43
|
+
return []
|
|
44
|
+
paragraphs = [p.strip() for p in text.split(separator) if p.strip()]
|
|
45
|
+
if not paragraphs:
|
|
46
|
+
paragraphs = [text.strip()]
|
|
47
|
+
|
|
48
|
+
chunks: list[Chunk] = []
|
|
49
|
+
current: list[str] = []
|
|
50
|
+
current_len = 0
|
|
51
|
+
char_offset = 0
|
|
52
|
+
idx = 0
|
|
53
|
+
|
|
54
|
+
for para in paragraphs:
|
|
55
|
+
para_len = _estimate_tokens(para)
|
|
56
|
+
if current_len + para_len > chunk_size and current:
|
|
57
|
+
content = "\n\n".join(current)
|
|
58
|
+
chunks.append(
|
|
59
|
+
Chunk(
|
|
60
|
+
chunk_id=f"chunk-{uuid.uuid4().hex[:12]}",
|
|
61
|
+
document_id=document_id,
|
|
62
|
+
chunk_index=idx,
|
|
63
|
+
content=content,
|
|
64
|
+
content_hash=_sha256(content),
|
|
65
|
+
page_number=page_number,
|
|
66
|
+
slide_number=slide_number,
|
|
67
|
+
section=section,
|
|
68
|
+
start_char=char_offset,
|
|
69
|
+
end_char=char_offset + len(content),
|
|
70
|
+
token_count=_estimate_tokens(content),
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
idx += 1
|
|
74
|
+
char_offset += len(content) + len(separator)
|
|
75
|
+
# overlap: keep last chunk's tail
|
|
76
|
+
if chunk_overlap > 0 and chunks:
|
|
77
|
+
tail = chunks[-1].content[-chunk_overlap * 4:]
|
|
78
|
+
current = [tail, para]
|
|
79
|
+
current_len = _estimate_tokens(tail) + para_len
|
|
80
|
+
else:
|
|
81
|
+
current = [para]
|
|
82
|
+
current_len = para_len
|
|
83
|
+
else:
|
|
84
|
+
current.append(para)
|
|
85
|
+
current_len += para_len
|
|
86
|
+
|
|
87
|
+
if current:
|
|
88
|
+
content = "\n\n".join(current)
|
|
89
|
+
chunks.append(
|
|
90
|
+
Chunk(
|
|
91
|
+
chunk_id=f"chunk-{uuid.uuid4().hex[:12]}",
|
|
92
|
+
document_id=document_id,
|
|
93
|
+
chunk_index=idx,
|
|
94
|
+
content=content,
|
|
95
|
+
content_hash=_sha256(content),
|
|
96
|
+
page_number=page_number,
|
|
97
|
+
slide_number=slide_number,
|
|
98
|
+
section=section,
|
|
99
|
+
start_char=char_offset,
|
|
100
|
+
end_char=char_offset + len(content),
|
|
101
|
+
token_count=_estimate_tokens(content),
|
|
102
|
+
)
|
|
103
|
+
)
|
|
104
|
+
return chunks
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def chunk_pages(
|
|
108
|
+
pages: Sequence[str],
|
|
109
|
+
document_id: str,
|
|
110
|
+
*,
|
|
111
|
+
chunk_size: int = 512,
|
|
112
|
+
chunk_overlap: int = 64,
|
|
113
|
+
section: str = "",
|
|
114
|
+
) -> list[Chunk]:
|
|
115
|
+
"""Chunk a sequence of pages, preserving page provenance."""
|
|
116
|
+
all_chunks: list[Chunk] = []
|
|
117
|
+
for page_num, page_text in enumerate(pages, start=1):
|
|
118
|
+
page_chunks = chunk_text(
|
|
119
|
+
page_text,
|
|
120
|
+
document_id,
|
|
121
|
+
chunk_size=chunk_size,
|
|
122
|
+
chunk_overlap=chunk_overlap,
|
|
123
|
+
page_number=page_num,
|
|
124
|
+
section=section,
|
|
125
|
+
)
|
|
126
|
+
all_chunks.extend(page_chunks)
|
|
127
|
+
return all_chunks
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def chunk_slides(
|
|
131
|
+
slides: Sequence[str],
|
|
132
|
+
document_id: str,
|
|
133
|
+
*,
|
|
134
|
+
chunk_size: int = 512,
|
|
135
|
+
chunk_overlap: int = 64,
|
|
136
|
+
section: str = "",
|
|
137
|
+
) -> list[Chunk]:
|
|
138
|
+
"""Chunk a sequence of slides, preserving slide provenance."""
|
|
139
|
+
all_chunks: list[Chunk] = []
|
|
140
|
+
for slide_num, slide_text in enumerate(slides, start=1):
|
|
141
|
+
slide_chunks = chunk_text(
|
|
142
|
+
slide_text,
|
|
143
|
+
document_id,
|
|
144
|
+
chunk_size=chunk_size,
|
|
145
|
+
chunk_overlap=chunk_overlap,
|
|
146
|
+
slide_number=slide_num,
|
|
147
|
+
section=section,
|
|
148
|
+
)
|
|
149
|
+
all_chunks.extend(slide_chunks)
|
|
150
|
+
return all_chunks
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"""Contradiction detection between documents."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
from .models import Chunk
|
|
10
|
+
from .store import DocumentStore
|
|
11
|
+
|
|
12
|
+
# Contradiction signal patterns (Japanese + English)
|
|
13
|
+
NEGATION_PATTERNS = [
|
|
14
|
+
r"(?:ない|ません|ではない|できない|禁止|不可|しない)",
|
|
15
|
+
r"(?:not|no|never|cannot|must not|prohibited|forbidden)",
|
|
16
|
+
]
|
|
17
|
+
|
|
18
|
+
CONTRAST_PATTERNS = [
|
|
19
|
+
r"(?:しかし|だが|一方|逆に|反対|ただし|ところが)",
|
|
20
|
+
r"(?:however|but|on the other hand|conversely|instead|nevertheless|although)",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
DATE_NUM_PATTERNS = [
|
|
24
|
+
r"(\d{4}[-/年]\d{1,2}[-/月]\d{1,2})",
|
|
25
|
+
r"(\d+(?:\.\d+)?)\s*(%|percent|円|ドル|USD|JPY|人|件|個)",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Contradiction:
|
|
31
|
+
"""A detected contradiction between two chunks."""
|
|
32
|
+
|
|
33
|
+
contradiction_id: str
|
|
34
|
+
chunk_a_id: str
|
|
35
|
+
chunk_b_id: str
|
|
36
|
+
document_a_id: str
|
|
37
|
+
document_b_id: str
|
|
38
|
+
document_a_title: str
|
|
39
|
+
document_b_title: str
|
|
40
|
+
contradiction_type: str # negation, date_mismatch, number_mismatch, direct_contrast
|
|
41
|
+
description: str
|
|
42
|
+
quote_a: str = ""
|
|
43
|
+
quote_b: str = ""
|
|
44
|
+
confidence: float = 0.5
|
|
45
|
+
page_a: int | None = None
|
|
46
|
+
page_b: int | None = None
|
|
47
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def detect_contradictions(
|
|
51
|
+
store: DocumentStore,
|
|
52
|
+
*,
|
|
53
|
+
document_ids: list[str] | None = None,
|
|
54
|
+
min_confidence: float = 0.6,
|
|
55
|
+
) -> list[Contradiction]:
|
|
56
|
+
"""Detect contradictions between documents or within a single document.
|
|
57
|
+
|
|
58
|
+
Uses a heuristic approach based on:
|
|
59
|
+
- Negation signals on similar topics
|
|
60
|
+
- Date mismatches for the same event/milestone
|
|
61
|
+
- Number mismatches for the same metric
|
|
62
|
+
- Direct contrast markers (しかし, however)
|
|
63
|
+
|
|
64
|
+
This is intentionally conservative: false positives are preferable to
|
|
65
|
+
missing real contradictions in a RAG system.
|
|
66
|
+
|
|
67
|
+
Args:
|
|
68
|
+
store: DocumentStore with ingested chunks.
|
|
69
|
+
document_ids: If provided, only check these documents.
|
|
70
|
+
min_confidence: Minimum confidence threshold.
|
|
71
|
+
|
|
72
|
+
Returns:
|
|
73
|
+
List of detected contradictions.
|
|
74
|
+
"""
|
|
75
|
+
# Get all chunks for the specified documents
|
|
76
|
+
docs: dict[str, Any] = {}
|
|
77
|
+
|
|
78
|
+
if document_ids:
|
|
79
|
+
for doc_id in document_ids:
|
|
80
|
+
doc = store.get_document(doc_id)
|
|
81
|
+
if doc:
|
|
82
|
+
docs[doc_id] = doc
|
|
83
|
+
else:
|
|
84
|
+
# Get all documents
|
|
85
|
+
all_docs = store.list_documents(limit=1000)
|
|
86
|
+
for doc in all_docs:
|
|
87
|
+
docs[doc.document_id] = doc
|
|
88
|
+
|
|
89
|
+
# Collect chunks per document
|
|
90
|
+
doc_chunks: dict[str, list[Chunk]] = {}
|
|
91
|
+
for doc_id in docs:
|
|
92
|
+
doc_chunks[doc_id] = _get_chunks_for_document(store, doc_id)
|
|
93
|
+
|
|
94
|
+
contradictions: list[Contradiction] = []
|
|
95
|
+
doc_list = list(docs.keys())
|
|
96
|
+
|
|
97
|
+
# Compare chunks
|
|
98
|
+
for i, doc_a in enumerate(doc_list):
|
|
99
|
+
for doc_b in doc_list[i:]:
|
|
100
|
+
chunks_a = doc_chunks.get(doc_a, [])
|
|
101
|
+
chunks_b = doc_chunks.get(doc_b, [])
|
|
102
|
+
for chunk_a in chunks_a:
|
|
103
|
+
for chunk_b in chunks_b:
|
|
104
|
+
if chunk_a.chunk_id == chunk_b.chunk_id:
|
|
105
|
+
continue
|
|
106
|
+
contradiction = _compare_chunks(
|
|
107
|
+
chunk_a, chunk_b, docs[doc_a], docs[doc_b]
|
|
108
|
+
)
|
|
109
|
+
if contradiction and contradiction.confidence >= min_confidence:
|
|
110
|
+
contradictions.append(contradiction)
|
|
111
|
+
|
|
112
|
+
return contradictions
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _compare_chunks(
|
|
116
|
+
chunk_a: Chunk,
|
|
117
|
+
chunk_b: Chunk,
|
|
118
|
+
doc_a: Any,
|
|
119
|
+
doc_b: Any,
|
|
120
|
+
) -> Contradiction | None:
|
|
121
|
+
"""Compare two chunks for contradictions."""
|
|
122
|
+
# Check for direct contrast markers
|
|
123
|
+
has_contrast_a = any(re.search(p, chunk_a.content) for p in CONTRAST_PATTERNS)
|
|
124
|
+
|
|
125
|
+
# Check for negation
|
|
126
|
+
has_negation_a = any(re.search(p, chunk_a.content) for p in NEGATION_PATTERNS)
|
|
127
|
+
has_negation_b = any(re.search(p, chunk_b.content) for p in NEGATION_PATTERNS)
|
|
128
|
+
|
|
129
|
+
# If one has negation and the other doesn't, and they share similar terms
|
|
130
|
+
if has_negation_a != has_negation_b:
|
|
131
|
+
similarity = _chunk_similarity(chunk_a.content, chunk_b.content)
|
|
132
|
+
if similarity > 0.3:
|
|
133
|
+
return Contradiction(
|
|
134
|
+
contradiction_id=f"c-{chunk_a.chunk_id[:6]}-{chunk_b.chunk_id[:6]}",
|
|
135
|
+
chunk_a_id=chunk_a.chunk_id,
|
|
136
|
+
chunk_b_id=chunk_b.chunk_id,
|
|
137
|
+
document_a_id=doc_a.document_id,
|
|
138
|
+
document_b_id=doc_b.document_id,
|
|
139
|
+
document_a_title=doc_a.title,
|
|
140
|
+
document_b_title=doc_b.title,
|
|
141
|
+
contradiction_type="negation",
|
|
142
|
+
description=f"Possible negation contradiction between '{doc_a.title}' and '{doc_b.title}'",
|
|
143
|
+
quote_a=chunk_a.content[:200],
|
|
144
|
+
quote_b=chunk_b.content[:200],
|
|
145
|
+
confidence=0.6 + similarity * 0.3,
|
|
146
|
+
page_a=chunk_a.page_number,
|
|
147
|
+
page_b=chunk_b.page_number,
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
# Check for date/number mismatches on similar topics
|
|
151
|
+
dates_a = set(re.findall(DATE_NUM_PATTERNS[0], chunk_a.content))
|
|
152
|
+
dates_b = set(re.findall(DATE_NUM_PATTERNS[0], chunk_b.content))
|
|
153
|
+
if dates_a and dates_b and dates_a != dates_b:
|
|
154
|
+
similarity = _chunk_similarity(chunk_a.content, chunk_b.content)
|
|
155
|
+
if similarity > 0.4:
|
|
156
|
+
return Contradiction(
|
|
157
|
+
contradiction_id=f"d-{chunk_a.chunk_id[:6]}-{chunk_b.chunk_id[:6]}",
|
|
158
|
+
chunk_a_id=chunk_a.chunk_id,
|
|
159
|
+
chunk_b_id=chunk_b.chunk_id,
|
|
160
|
+
document_a_id=doc_a.document_id,
|
|
161
|
+
document_b_id=doc_b.document_id,
|
|
162
|
+
document_a_title=doc_a.title,
|
|
163
|
+
document_b_title=doc_b.title,
|
|
164
|
+
contradiction_type="date_mismatch",
|
|
165
|
+
description=f"Date mismatch: {dates_a} vs {dates_b}",
|
|
166
|
+
quote_a=chunk_a.content[:200],
|
|
167
|
+
quote_b=chunk_b.content[:200],
|
|
168
|
+
confidence=0.7,
|
|
169
|
+
page_a=chunk_a.page_number,
|
|
170
|
+
page_b=chunk_b.page_number,
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
# Check for direct contrast
|
|
174
|
+
if has_contrast_a or has_negation_a != has_negation_b:
|
|
175
|
+
similarity = _chunk_similarity(chunk_a.content, chunk_b.content)
|
|
176
|
+
if similarity > 0.5:
|
|
177
|
+
return Contradiction(
|
|
178
|
+
contradiction_id=f"dc-{chunk_a.chunk_id[:6]}-{chunk_b.chunk_id[:6]}",
|
|
179
|
+
chunk_a_id=chunk_a.chunk_id,
|
|
180
|
+
chunk_b_id=chunk_b.chunk_id,
|
|
181
|
+
document_a_id=doc_a.document_id,
|
|
182
|
+
document_b_id=doc_b.document_id,
|
|
183
|
+
document_a_title=doc_a.title,
|
|
184
|
+
document_b_title=doc_b.title,
|
|
185
|
+
contradiction_type="direct_contrast",
|
|
186
|
+
description="Direct contrast detected between chunks",
|
|
187
|
+
quote_a=chunk_a.content[:200],
|
|
188
|
+
quote_b=chunk_b.content[:200],
|
|
189
|
+
confidence=0.65,
|
|
190
|
+
page_a=chunk_a.page_number,
|
|
191
|
+
page_b=chunk_b.page_number,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def _chunk_similarity(text_a: str, text_b: str) -> float:
|
|
198
|
+
"""Simple Jaccard similarity of token sets."""
|
|
199
|
+
tokens_a = set(_tokenize(text_a))
|
|
200
|
+
tokens_b = set(_tokenize(text_b))
|
|
201
|
+
if not tokens_a or not tokens_b:
|
|
202
|
+
return 0.0
|
|
203
|
+
intersection = tokens_a & tokens_b
|
|
204
|
+
union = tokens_a | tokens_b
|
|
205
|
+
return len(intersection) / len(union)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _tokenize(text: str) -> list[str]:
|
|
209
|
+
"""Simple tokenization: split on whitespace and extract CJK chars."""
|
|
210
|
+
tokens = text.split()
|
|
211
|
+
cjk = re.findall(r"[一-鿿-ヿ가-]", text)
|
|
212
|
+
return tokens + cjk
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _get_chunks_for_document(store: DocumentStore, document_id: str) -> list[Chunk]:
|
|
216
|
+
"""Get all chunks for a document."""
|
|
217
|
+
# Use the existing search method with a broad query or add a direct query
|
|
218
|
+
with store._conn() as conn:
|
|
219
|
+
conn.row_factory = sqlite3.Row
|
|
220
|
+
rows = conn.execute(
|
|
221
|
+
"SELECT * FROM chunks WHERE document_id = ? ORDER BY chunk_index",
|
|
222
|
+
(document_id,),
|
|
223
|
+
).fetchall()
|
|
224
|
+
from .store import _row_to_chunk
|
|
225
|
+
return [_row_to_chunk(row) for row in rows]
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
import sqlite3 # noqa: E402
|