noteweaver 0.1.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.
noteweaver/__init__.py ADDED
@@ -0,0 +1,45 @@
1
+ """Shared contracts, note management, generation, and verified project persistence."""
2
+
3
+ from ._version import __version__
4
+
5
+ from .models import (
6
+ SCHEMA_VERSION,
7
+ ContractError,
8
+ DocumentInfo,
9
+ ExportResult,
10
+ GeneratedNote,
11
+ NotePageLocation,
12
+ NoteRequest,
13
+ NoteSection,
14
+ OriginalPageLocation,
15
+ PageContent,
16
+ ProjectState,
17
+ document_id_for_file,
18
+ validate_export,
19
+ validate_generation,
20
+ validate_page,
21
+ validate_request,
22
+ verify_source,
23
+ )
24
+ from .project import (
25
+ add_manual_note, approve_note, create_project, delete_note, list_notes, update_note,
26
+ )
27
+ from .persistence import load_project, save_project
28
+ from .generation import NoteGenerator, default_generator
29
+ from .workflow import generate_note
30
+ from .exporters import PyMuPDFPDFExporter
31
+ from .providers import GenerationError, FakeNoteProvider, NoteProvider, OpenAICompatibleProvider, GroqProvider
32
+
33
+ __all__ = [
34
+ "__version__",
35
+ "PyMuPDFPDFExporter", "SCHEMA_VERSION", "ContractError", "DocumentInfo", "ExportResult",
36
+ "GeneratedNote", "NotePageLocation", "NoteRequest", "NoteSection",
37
+ "OriginalPageLocation", "PageContent", "ProjectState", "document_id_for_file",
38
+ "validate_export", "validate_generation", "validate_page", "validate_request",
39
+ "verify_source",
40
+ "add_manual_note", "approve_note", "create_project", "delete_note", "list_notes",
41
+ "update_note",
42
+ "load_project", "save_project",
43
+ "NoteGenerator", "default_generator", "generate_note", "GroqProvider",
44
+ "GenerationError", "FakeNoteProvider", "NoteProvider", "OpenAICompatibleProvider",
45
+ ]
noteweaver/_version.py ADDED
@@ -0,0 +1,3 @@
1
+ """Single source for package and HTTP client versions."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,200 @@
1
+ """Approved-note PDF export using the team's shared data contracts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import os
7
+ from pathlib import Path
8
+ import tempfile
9
+ from typing import Iterator
10
+
11
+ from .models import (
12
+ ContractError, ExportResult, GeneratedNote, NotePageLocation,
13
+ OriginalPageLocation, ProjectState, validate_export, verify_source,
14
+ )
15
+
16
+
17
+ class PyMuPDFPDFExporter:
18
+ """Render plain-text English/Chinese notes to a new, verified study PDF.
19
+
20
+ Install the ``export`` extra. Existing destinations are never overwritten.
21
+ Missing font glyphs are errors rather than silent substitutions.
22
+ """
23
+
24
+ def __init__(self) -> None:
25
+ try:
26
+ import pymupdf
27
+ except ImportError as exc:
28
+ raise ImportError(
29
+ 'PDF export requires PyMuPDF; install this checkout with '
30
+ 'python -m pip install -e ".[export]"'
31
+ ) from exc
32
+ self._pdf = pymupdf
33
+ # MuPDF's bundled Droid Sans Fallback covers Latin and CJK characters.
34
+ # The font is embedded in output; no system font or network lookup occurs.
35
+ self._font = pymupdf.Font("cjk")
36
+
37
+ @staticmethod
38
+ def _check_destination(source: Path, output: Path) -> None:
39
+ if source.resolve() == output.resolve() or (
40
+ output.exists() and os.path.samefile(source, output)
41
+ ):
42
+ raise ValueError("Output must not identify the source PDF, including aliases")
43
+ if output.exists() or output.is_symlink():
44
+ raise FileExistsError(f"Output already exists: {output}")
45
+
46
+ def export(self, source: Path, project: ProjectState, output: Path) -> ExportResult:
47
+ """Export approved notes in project order and return validated page maps.
48
+
49
+ Source bytes are verified before reading and before publication. Build
50
+ privately beside the destination and publish without replacing a file.
51
+ """
52
+ if not isinstance(project, ProjectState):
53
+ raise TypeError("project must be a shared ProjectState")
54
+ source, output = Path(source).absolute(), Path(output).absolute()
55
+ self._check_destination(source, output)
56
+ verify_source(project, source)
57
+ source_bytes = source.read_bytes()
58
+ if "sha256:" + hashlib.sha256(source_bytes).hexdigest() != project.document.document_id:
59
+ raise ContractError("Source document changed while reading")
60
+
61
+ temporary: Path | None = None
62
+ try:
63
+ with self._pdf.open(stream=source_bytes, filetype="pdf") as doc:
64
+ if doc.needs_pass:
65
+ raise ValueError("Password-protected PDFs are not supported for export")
66
+ if len(doc) != project.document.page_count:
67
+ raise ContractError("Source PDF page count does not match project metadata")
68
+ # Edit a memory copy of the entire document, preserving original
69
+ # pages, annotations and links rather than copying isolated pages.
70
+ old_toc = doc.get_toc(simple=False)
71
+ old_links = [page.get_links() for page in doc]
72
+ original_locations = []
73
+ note_locations = []
74
+ notes_by_page: dict[int, list[GeneratedNote]] = {}
75
+ for note in project.notes:
76
+ if note.status == "approved":
77
+ notes_by_page.setdefault(note.original_page, []).append(note)
78
+ cursor = 0
79
+ for original_page in range(1, project.document.page_count + 1):
80
+ original_locations.append(OriginalPageLocation(original_page, cursor + 1))
81
+ cursor += 1
82
+ for ordinal, note in enumerate(notes_by_page.get(original_page, []), 1):
83
+ pages = self._render_note(doc, note, cursor, ordinal)
84
+ note_locations.append(NotePageLocation(note.note_id, pages))
85
+ cursor += len(pages)
86
+ result = ExportResult(
87
+ document_id=project.document.document_id,
88
+ output_path=str(output), output_page_count=len(doc),
89
+ original_to_output_pages=tuple(original_locations),
90
+ note_to_output_pages=tuple(note_locations),
91
+ )
92
+ validate_export(project, result)
93
+ self._navigation(doc, old_toc, old_links, result, notes_by_page)
94
+ with tempfile.NamedTemporaryFile(
95
+ dir=output.parent, prefix=".noteweaver-", suffix=".pdf", delete=False,
96
+ ) as handle:
97
+ temporary = Path(handle.name)
98
+ doc.save(temporary, garbage=3, deflate=True)
99
+ with self._pdf.open(temporary) as saved:
100
+ if len(saved) != result.output_page_count:
101
+ raise ContractError("Saved PDF page count differs from export map")
102
+ verify_source(project, source)
103
+ self._check_destination(source, output)
104
+ # Atomic no-clobber publication on the destination filesystem.
105
+ os.link(temporary, output)
106
+ return result
107
+ finally:
108
+ if temporary is not None:
109
+ temporary.unlink(missing_ok=True)
110
+
111
+ def _lines(self, text: str, size: float, width: float) -> Iterator[str]:
112
+ """Wrap by measured glyph advances, always consuming source characters."""
113
+ text = text.replace("\r\n", "\n").replace("\r", "\n").expandtabs(4)
114
+ for char in set(text) - {"\n"}:
115
+ if not self._font.has_glyph(ord(char)):
116
+ raise ValueError(f"Export font cannot render U+{ord(char):04X}; edit the text first")
117
+ for paragraph in text.split("\n"):
118
+ if not paragraph:
119
+ yield ""
120
+ continue
121
+ advances = self._font.char_lengths(paragraph, fontsize=size)
122
+ start = 0
123
+ while start < len(paragraph):
124
+ end, used, last_space = start, 0.0, -1
125
+ while end < len(paragraph) and used + advances[end] <= width:
126
+ used += advances[end]
127
+ if paragraph[end] == " ":
128
+ last_space = end
129
+ end += 1
130
+ if end == start:
131
+ raise ValueError("A text glyph is wider than the available note area")
132
+ if end < len(paragraph) and last_space > start:
133
+ end = last_space + 1
134
+ yield paragraph[start:end]
135
+ start = end
136
+
137
+ def _render_note(self, doc, note: GeneratedNote, index: int, ordinal: int) -> tuple[int, ...]:
138
+ width, height, margin = 595, 842, 54
139
+ body_top, body_bottom = 100, height - 64
140
+ pages: list[int] = []
141
+ page = None
142
+ y = body_top
143
+
144
+ def draw(text: str, x: float, baseline: float, size: float, color) -> None:
145
+ writer = self._pdf.TextWriter(page.rect)
146
+ writer.append((x, baseline), text, font=self._font, fontsize=size)
147
+ writer.write_text(page, color=color)
148
+
149
+ def new_page() -> None:
150
+ nonlocal page, y
151
+ page = doc.new_page(pno=index + len(pages), width=width, height=height)
152
+ pages.append(index + len(pages) + 1)
153
+ draw(f"Original page {note.original_page} | Supplementary note {ordinal}",
154
+ margin, 48, 10, (0.25, 0.3, 0.4))
155
+ page.draw_line((margin, 65), (width - margin, 65), color=(0.75, 0.78, 0.82))
156
+ draw(f"Note page {len(pages)} | Output page {pages[-1]}",
157
+ margin, height - 30, 9, (0.35, 0.4, 0.45))
158
+ y = body_top
159
+
160
+ def block(text: str, size: float, color=(0.12, 0.15, 0.2)) -> None:
161
+ nonlocal y
162
+ leading = max(size * 1.5, size * (self._font.ascender - self._font.descender) + 2)
163
+ for line in self._lines(text, size, width - 2 * margin):
164
+ if page is None or y - self._font.descender * size > body_bottom:
165
+ new_page()
166
+ if line:
167
+ draw(line, margin, y, size, color)
168
+ y += leading
169
+ y += 7
170
+
171
+ block(note.title, 17, (0.1, 0.18, 0.32))
172
+ if note.source_pages:
173
+ block("Source pages: " + ", ".join(map(str, note.source_pages)) +
174
+ " (source claims, not fact checking)", 9)
175
+ for section in note.sections:
176
+ origin = {"lecture": "Lecture-based claim", "ai": "AI-added material", "user": "User-written"}[section.origin]
177
+ block(f"{section.kind.replace('_', ' ').title()} | {origin}", 10, (0.22, 0.35, 0.5))
178
+ block(section.content, 11)
179
+ return tuple(pages)
180
+
181
+ def _navigation(self, doc, old_toc, old_links, result, notes_by_page) -> None:
182
+ locations = {item.original_page: item.output_page for item in result.original_to_output_pages}
183
+ note_pages = {item.note_id: item.output_pages for item in result.note_to_output_pages}
184
+ for original, links in enumerate(old_links, 1):
185
+ page = doc[locations[original] - 1]
186
+ for link in links:
187
+ if link.get("kind") == self._pdf.LINK_GOTO and link.get("page", -1) >= 0:
188
+ link["page"] = locations[link["page"] + 1] - 1
189
+ page.update_link(link)
190
+ for item in old_toc:
191
+ destination = item[3]
192
+ if destination.get("kind") == self._pdf.LINK_GOTO and destination.get("page", -1) >= 0:
193
+ destination["page"] = locations[destination["page"] + 1] - 1
194
+ item[2] = destination["page"] + 1
195
+ toc = old_toc + [[1, "NoteWeaver study navigation", 1]]
196
+ for original, output in locations.items():
197
+ toc.append([2, f"Original page {original}", output])
198
+ for ordinal, note in enumerate(notes_by_page.get(original, []), 1):
199
+ toc.append([3, f"Note {ordinal}: {note.title}", note_pages[note.note_id][0]])
200
+ doc.set_toc(toc)
@@ -0,0 +1,84 @@
1
+ """NoteGenerator: turn lecture context + student question into a draft note.
2
+
3
+ This module implements the shared NoteGenerator protocol. It never reads or
4
+ writes PDFs; it only validates the supplied context against the request and
5
+ delegates content production to a replaceable NoteProvider.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from noteweaver.models import (
11
+ ContractError,
12
+ DocumentInfo,
13
+ GeneratedNote,
14
+ NoteRequest,
15
+ PageContent,
16
+ validate_generation,
17
+ validate_page,
18
+ validate_request,
19
+ )
20
+ from noteweaver.providers.base import GenerationError, NoteProvider
21
+ from noteweaver.providers.fake import FakeNoteProvider
22
+
23
+
24
+ class NoteGenerator:
25
+ """Concrete NoteGenerator that wraps a NoteProvider.
26
+
27
+ By default uses FakeNoteProvider (offline, deterministic). Pass any object
28
+ satisfying the NoteProvider protocol to switch to a live service.
29
+ """
30
+
31
+ def __init__(self, provider: NoteProvider | None = None) -> None:
32
+ self._provider: NoteProvider = provider if provider is not None else FakeNoteProvider()
33
+
34
+ def generate(
35
+ self,
36
+ document: DocumentInfo,
37
+ request: NoteRequest,
38
+ context: tuple[PageContent, ...],
39
+ ) -> GeneratedNote:
40
+ """Produce a draft GeneratedNote and run validate_generation.
41
+
42
+ Raises:
43
+ ContractError: context does not match request, pages not ok, or the
44
+ resulting note violates shared contracts.
45
+ GenerationError: the underlying provider failed (network, auth,
46
+ malformed reply, forced failure, etc.).
47
+ """
48
+ # Validate the full input boundary before a provider can send any text.
49
+ if type(document) is not DocumentInfo or type(request) is not NoteRequest:
50
+ raise ContractError("document and request must use the shared model types")
51
+ validate_request(document, request)
52
+ if type(context) is not tuple or any(type(page) is not PageContent for page in context):
53
+ raise ContractError("context must be a tuple of PageContent")
54
+ for page in context:
55
+ validate_page(document, page)
56
+ if page.extraction_status != "ok":
57
+ raise ContractError("generation needs successfully extracted text")
58
+ page_numbers = tuple(page.original_page for page in context)
59
+ if len(set(page_numbers)) != len(page_numbers):
60
+ raise ContractError("context must not contain duplicate pages")
61
+ if set(page_numbers) != set(request.context_pages):
62
+ raise ContractError("actual context must match request.context_pages exactly")
63
+
64
+ try:
65
+ note = self._provider.generate(document, request, context)
66
+ except GenerationError:
67
+ raise
68
+ except Exception as exc: # noqa: BLE001 — isolate unexpected provider bugs
69
+ raise GenerationError(f"provider failed unexpectedly: {type(exc).__name__}") from None
70
+
71
+ # Enforce draft status and full shared validation before returning.
72
+ if type(note) is not GeneratedNote:
73
+ raise GenerationError("provider must return a GeneratedNote")
74
+ if note.status != "draft":
75
+ # Providers should already return draft; defend the contract.
76
+ raise ContractError("new generated notes must be drafts")
77
+
78
+ validate_generation(document, request, context, note)
79
+ return note
80
+
81
+
82
+ def default_generator() -> NoteGenerator:
83
+ """Convenience factory that returns an offline FakeNoteProvider generator."""
84
+ return NoteGenerator(FakeNoteProvider())
@@ -0,0 +1,34 @@
1
+ """Module boundary signatures only; members implement these protocols."""
2
+
3
+ from pathlib import Path
4
+ from typing import Protocol
5
+
6
+ from .models import DocumentInfo, ExportResult, GeneratedNote, NoteRequest, PageContent, ProjectState
7
+
8
+
9
+ class PDFReader(Protocol):
10
+ def inspect(self, source: Path) -> DocumentInfo:
11
+ """Member 1: read page count and hash the source bytes."""
12
+ ...
13
+
14
+ def read_page(self, source: Path, original_page: int) -> PageContent:
15
+ """Member 1: original_page is 1-based; preview_path is optional."""
16
+ ...
17
+
18
+
19
+ class NoteGenerator(Protocol):
20
+ def generate(self, document: DocumentInfo, request: NoteRequest,
21
+ context: tuple[PageContent, ...]) -> GeneratedNote:
22
+ """Member 2: return a draft; run validate_generation before returning."""
23
+ ...
24
+
25
+
26
+ class PDFExporter(Protocol):
27
+ def export(self, source: Path, project: ProjectState, output: Path) -> ExportResult:
28
+ """Member 3: verify source; new output path; approved notes only.
29
+
30
+ Reject an output that resolves to the input source (including aliases).
31
+ Validate placement with validate_export after rendering. This protocol
32
+ itself does not inspect files, render pages, or enforce these operations.
33
+ """
34
+ ...