slidedesk 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.
- slidedesk/__init__.py +6 -0
- slidedesk/cli.py +46 -0
- slidedesk/convert.py +181 -0
- slidedesk/db.py +102 -0
- slidedesk/embeddings.py +112 -0
- slidedesk/image_embeddings.py +49 -0
- slidedesk/images.py +61 -0
- slidedesk/layout_strip.py +210 -0
- slidedesk/models.py +64 -0
- slidedesk/pptx_tools.py +159 -0
- slidedesk/project.py +548 -0
- slidedesk/scanner.py +275 -0
- slidedesk/server/__init__.py +0 -0
- slidedesk/server/app.py +363 -0
- slidedesk/server/static/css/style.css +384 -0
- slidedesk/server/static/js/app.js +1502 -0
- slidedesk/server/templates/index.html +102 -0
- slidedesk/text_generation.py +199 -0
- slidedesk-0.1.0.dist-info/METADATA +111 -0
- slidedesk-0.1.0.dist-info/RECORD +24 -0
- slidedesk-0.1.0.dist-info/WHEEL +5 -0
- slidedesk-0.1.0.dist-info/entry_points.txt +2 -0
- slidedesk-0.1.0.dist-info/licenses/LICENSE +28 -0
- slidedesk-0.1.0.dist-info/top_level.txt +1 -0
slidedesk/__init__.py
ADDED
slidedesk/cli.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Command-line entry point: `slidedesk <folder>`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import threading
|
|
5
|
+
import webbrowser
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
|
|
9
|
+
from .project import SlideProject
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@click.command()
|
|
13
|
+
@click.argument("folder", type=click.Path(file_okay=False, path_type=str))
|
|
14
|
+
@click.option("--host", default="127.0.0.1", show_default=True)
|
|
15
|
+
@click.option("--port", default=5000, show_default=True, type=int)
|
|
16
|
+
@click.option("--no-browser", is_flag=True, help="Don't open a browser window.")
|
|
17
|
+
@click.option("--no-scan", is_flag=True, help="Use indexed decks without scanning folders for changes or new decks.")
|
|
18
|
+
@click.option(
|
|
19
|
+
"--scan-interval",
|
|
20
|
+
default=5.0,
|
|
21
|
+
show_default=True,
|
|
22
|
+
type=float,
|
|
23
|
+
help="Seconds between background folder scans.",
|
|
24
|
+
)
|
|
25
|
+
def main(folder: str, host: str, port: int, no_browser: bool, scan_interval: float, no_scan: bool = False) -> None:
|
|
26
|
+
"""Open (or create) a project in FOLDER and start the GUI server."""
|
|
27
|
+
from .server.app import create_app
|
|
28
|
+
|
|
29
|
+
project = SlideProject(folder)
|
|
30
|
+
if not no_scan:
|
|
31
|
+
project.scan_in_background(interval=scan_interval)
|
|
32
|
+
|
|
33
|
+
app = create_app(project, scan_enabled=not no_scan)
|
|
34
|
+
|
|
35
|
+
if not no_browser:
|
|
36
|
+
url = f"http://{host}:{port}/"
|
|
37
|
+
threading.Timer(1.0, lambda: webbrowser.open(url)).start()
|
|
38
|
+
|
|
39
|
+
try:
|
|
40
|
+
app.run(host=host, port=port, threaded=True, use_reloader=False)
|
|
41
|
+
finally:
|
|
42
|
+
project.close()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
if __name__ == "__main__":
|
|
46
|
+
main()
|
slidedesk/convert.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Convert .pptx files to .pdf using Microsoft PowerPoint via COM automation.
|
|
2
|
+
|
|
3
|
+
Windows-only: requires Microsoft PowerPoint and pywin32 to be installed.
|
|
4
|
+
Rendering slide *images* from the resulting PDFs is done separately via
|
|
5
|
+
pdf2image/poppler (see images.py) and has no PowerPoint dependency.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import platform
|
|
10
|
+
import threading
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
_PP_SAVE_AS_PDF = 32 # PowerPoint's ppSaveAsPDF file-format constant
|
|
14
|
+
|
|
15
|
+
_local = threading.local()
|
|
16
|
+
_apps = []
|
|
17
|
+
_apps_lock = threading.Lock()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ConversionError(RuntimeError):
|
|
21
|
+
pass
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _retain_app(app) -> None:
|
|
25
|
+
with _apps_lock:
|
|
26
|
+
_apps.append(app)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def repair_pptx(source: Path, repaired: Path) -> None:
|
|
30
|
+
"""Open and resave an export using a dedicated PowerPoint instance."""
|
|
31
|
+
if platform.system() != "Windows":
|
|
32
|
+
raise ConversionError("Repairing PowerPoint exports requires Microsoft PowerPoint on Windows.")
|
|
33
|
+
try:
|
|
34
|
+
import pythoncom
|
|
35
|
+
import win32com.client
|
|
36
|
+
except ImportError as exc:
|
|
37
|
+
raise ConversionError("pywin32 is required to repair PowerPoint exports.") from exc
|
|
38
|
+
|
|
39
|
+
source = source.resolve()
|
|
40
|
+
repaired = repaired.resolve()
|
|
41
|
+
repaired.parent.mkdir(parents=True, exist_ok=True)
|
|
42
|
+
app = None
|
|
43
|
+
presentation = None
|
|
44
|
+
pythoncom.CoInitialize()
|
|
45
|
+
print(f"Repairing PowerPoint export: {source} -> {repaired}")
|
|
46
|
+
try:
|
|
47
|
+
try:
|
|
48
|
+
app = win32com.client.DispatchEx("PowerPoint.Application")
|
|
49
|
+
_retain_app(app)
|
|
50
|
+
app.DisplayAlerts = 2 # ppAlertsNone
|
|
51
|
+
presentation = app.Presentations.Open(
|
|
52
|
+
str(source), ReadOnly=False, Untitled=False, WithWindow=False
|
|
53
|
+
)
|
|
54
|
+
presentation.SaveAs(str(repaired), 24) # ppSaveAsOpenXMLPresentation
|
|
55
|
+
finally:
|
|
56
|
+
if presentation is not None:
|
|
57
|
+
presentation.Close()
|
|
58
|
+
except Exception as exc:
|
|
59
|
+
import warnings
|
|
60
|
+
warnings.warn(f"PowerPoint failed to repair {source.name}: {exc}")
|
|
61
|
+
pythoncom.CoUninitialize()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _get_powerpoint_app():
|
|
65
|
+
if platform.system() != "Windows":
|
|
66
|
+
raise ConversionError(
|
|
67
|
+
"Converting .pptx to .pdf requires Microsoft PowerPoint via COM "
|
|
68
|
+
"automation, which is only available on Windows."
|
|
69
|
+
)
|
|
70
|
+
try:
|
|
71
|
+
import pythoncom
|
|
72
|
+
import win32com.client
|
|
73
|
+
except ImportError as exc:
|
|
74
|
+
raise ConversionError(
|
|
75
|
+
"pywin32 is required for .pptx -> .pdf conversion. Install it with "
|
|
76
|
+
"'pip install pywin32'."
|
|
77
|
+
) from exc
|
|
78
|
+
|
|
79
|
+
app = getattr(_local, "app", None)
|
|
80
|
+
if app is not None:
|
|
81
|
+
return app
|
|
82
|
+
|
|
83
|
+
pythoncom.CoInitialize()
|
|
84
|
+
try:
|
|
85
|
+
app = win32com.client.DispatchEx("PowerPoint.Application")
|
|
86
|
+
except Exception as exc:
|
|
87
|
+
raise ConversionError(f"Could not start PowerPoint: {exc}") from exc
|
|
88
|
+
_retain_app(app)
|
|
89
|
+
_local.app = app
|
|
90
|
+
return app
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def convert_pptx_to_pdf(pptx_path: Path, out_pdf_path: Path, timeout: int = 180) -> None:
|
|
94
|
+
"""Convert `pptx_path` to a PDF at `out_pdf_path` using PowerPoint COM automation."""
|
|
95
|
+
app = _get_powerpoint_app()
|
|
96
|
+
pptx_path = pptx_path.resolve()
|
|
97
|
+
out_pdf_path = out_pdf_path.resolve()
|
|
98
|
+
out_pdf_path.parent.mkdir(parents=True, exist_ok=True)
|
|
99
|
+
|
|
100
|
+
presentation = None
|
|
101
|
+
try:
|
|
102
|
+
presentation = app.Presentations.Open(
|
|
103
|
+
str(pptx_path), ReadOnly=True, WithWindow=False
|
|
104
|
+
)
|
|
105
|
+
presentation.SaveAs(str(out_pdf_path), _PP_SAVE_AS_PDF)
|
|
106
|
+
except Exception as exc:
|
|
107
|
+
raise ConversionError(
|
|
108
|
+
f"PowerPoint failed to convert {pptx_path} to PDF: {exc}"
|
|
109
|
+
) from exc
|
|
110
|
+
finally:
|
|
111
|
+
if presentation is not None:
|
|
112
|
+
presentation.Close()
|
|
113
|
+
|
|
114
|
+
if not out_pdf_path.exists():
|
|
115
|
+
raise ConversionError(f"PowerPoint did not produce {out_pdf_path}")
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _copy_to_clipboard(pptx_path: Path, do_copy) -> None:
|
|
119
|
+
"""Open `pptx_path` in a windowless PowerPoint and run `do_copy(presentation)`,
|
|
120
|
+
which is expected to call `.Copy()` on some slide selection to populate the clipboard.
|
|
121
|
+
"""
|
|
122
|
+
if platform.system() != "Windows":
|
|
123
|
+
raise ConversionError("Copying slides to the clipboard requires Microsoft PowerPoint on Windows.")
|
|
124
|
+
try:
|
|
125
|
+
import pythoncom
|
|
126
|
+
import win32com.client
|
|
127
|
+
except ImportError as exc:
|
|
128
|
+
raise ConversionError("pywin32 is required to copy slides to the clipboard.") from exc
|
|
129
|
+
|
|
130
|
+
pptx_path = pptx_path.resolve()
|
|
131
|
+
presentation = None
|
|
132
|
+
pythoncom.CoInitialize()
|
|
133
|
+
try:
|
|
134
|
+
try:
|
|
135
|
+
app = win32com.client.DispatchEx("PowerPoint.Application")
|
|
136
|
+
_retain_app(app)
|
|
137
|
+
app.DisplayAlerts = 2 # ppAlertsNone
|
|
138
|
+
presentation = app.Presentations.Open(
|
|
139
|
+
str(pptx_path), ReadOnly=True, Untitled=False, WithWindow=False
|
|
140
|
+
)
|
|
141
|
+
do_copy(presentation)
|
|
142
|
+
finally:
|
|
143
|
+
if presentation is not None:
|
|
144
|
+
presentation.Close()
|
|
145
|
+
except ConversionError:
|
|
146
|
+
pythoncom.CoUninitialize()
|
|
147
|
+
raise
|
|
148
|
+
except Exception as exc:
|
|
149
|
+
pythoncom.CoUninitialize()
|
|
150
|
+
raise ConversionError(f"PowerPoint failed to copy slides from {pptx_path.name}: {exc}") from exc
|
|
151
|
+
pythoncom.CoUninitialize()
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def copy_slide_to_clipboard(pptx_path: Path, index_in_deck: int) -> None:
|
|
155
|
+
"""Copy one slide from `pptx_path` onto the OS clipboard via PowerPoint's
|
|
156
|
+
native `Slide.Copy()`, so it can be pasted directly into another open
|
|
157
|
+
PowerPoint presentation. Requires PowerPoint on Windows.
|
|
158
|
+
"""
|
|
159
|
+
def do_copy(presentation):
|
|
160
|
+
slide_number = index_in_deck + 1
|
|
161
|
+
if not (1 <= slide_number <= presentation.Slides.Count):
|
|
162
|
+
raise ConversionError(f"Slide index {index_in_deck} out of range for {pptx_path.name}")
|
|
163
|
+
presentation.Slides(slide_number).Copy()
|
|
164
|
+
|
|
165
|
+
_copy_to_clipboard(pptx_path, do_copy)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def copy_slides_to_clipboard(pptx_path: Path) -> None:
|
|
169
|
+
"""Copy every slide in `pptx_path` onto the OS clipboard as a single
|
|
170
|
+
multi-slide `SlideRange.Copy()`, so the whole set can be pasted together.
|
|
171
|
+
"""
|
|
172
|
+
def do_copy(presentation):
|
|
173
|
+
if presentation.Slides.Count == 0:
|
|
174
|
+
raise ConversionError("No slides to copy")
|
|
175
|
+
presentation.Slides.Range().Copy()
|
|
176
|
+
|
|
177
|
+
_copy_to_clipboard(pptx_path, do_copy)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def shutdown() -> None:
|
|
181
|
+
"""Compatibility hook; PowerPoint instances are intentionally left open."""
|
slidedesk/db.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
"""Low-level SQLite schema and connection helpers for a slidedesk project."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import sqlite3
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
SCHEMA_VERSION = 2
|
|
8
|
+
|
|
9
|
+
_SCHEMA = """
|
|
10
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
11
|
+
key TEXT PRIMARY KEY,
|
|
12
|
+
value TEXT
|
|
13
|
+
);
|
|
14
|
+
|
|
15
|
+
CREATE TABLE IF NOT EXISTS decks (
|
|
16
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
17
|
+
pptx_path TEXT UNIQUE NOT NULL,
|
|
18
|
+
pptx_mtime REAL NOT NULL,
|
|
19
|
+
pdf_path TEXT,
|
|
20
|
+
pdf_mtime REAL,
|
|
21
|
+
hidden_pdf_path TEXT,
|
|
22
|
+
hidden_pdf_mtime REAL,
|
|
23
|
+
last_scanned REAL
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
CREATE TABLE IF NOT EXISTS slides (
|
|
27
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
28
|
+
deck_id INTEGER NOT NULL REFERENCES decks(id) ON DELETE CASCADE,
|
|
29
|
+
index_in_deck INTEGER NOT NULL,
|
|
30
|
+
visible_pdf_page INTEGER,
|
|
31
|
+
hidden INTEGER NOT NULL DEFAULT 0,
|
|
32
|
+
text TEXT NOT NULL DEFAULT '',
|
|
33
|
+
UNIQUE(deck_id, index_in_deck)
|
|
34
|
+
);
|
|
35
|
+
|
|
36
|
+
CREATE INDEX IF NOT EXISTS idx_slides_deck ON slides(deck_id);
|
|
37
|
+
|
|
38
|
+
CREATE TABLE IF NOT EXISTS slide_embeddings (
|
|
39
|
+
slide_id INTEGER PRIMARY KEY REFERENCES slides(id) ON DELETE CASCADE,
|
|
40
|
+
model TEXT NOT NULL,
|
|
41
|
+
vector BLOB NOT NULL,
|
|
42
|
+
updated_at REAL NOT NULL
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
CREATE TABLE IF NOT EXISTS slide_image_embeddings (
|
|
46
|
+
slide_id INTEGER PRIMARY KEY REFERENCES slides(id) ON DELETE CASCADE,
|
|
47
|
+
model TEXT NOT NULL,
|
|
48
|
+
source_key TEXT NOT NULL,
|
|
49
|
+
vector BLOB NOT NULL,
|
|
50
|
+
updated_at REAL NOT NULL
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
CREATE TABLE IF NOT EXISTS slide_strip_image_embeddings (
|
|
54
|
+
slide_id INTEGER PRIMARY KEY REFERENCES slides(id) ON DELETE CASCADE,
|
|
55
|
+
model TEXT NOT NULL,
|
|
56
|
+
source_key TEXT NOT NULL,
|
|
57
|
+
vector BLOB NOT NULL,
|
|
58
|
+
updated_at REAL NOT NULL
|
|
59
|
+
);
|
|
60
|
+
|
|
61
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS slides_fts USING fts5(
|
|
62
|
+
text,
|
|
63
|
+
content='slides',
|
|
64
|
+
content_rowid='id'
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
CREATE TRIGGER IF NOT EXISTS slides_ai AFTER INSERT ON slides BEGIN
|
|
68
|
+
INSERT INTO slides_fts(rowid, text) VALUES (new.id, new.text);
|
|
69
|
+
END;
|
|
70
|
+
|
|
71
|
+
CREATE TRIGGER IF NOT EXISTS slides_ad AFTER DELETE ON slides BEGIN
|
|
72
|
+
INSERT INTO slides_fts(slides_fts, rowid, text) VALUES ('delete', old.id, old.text);
|
|
73
|
+
END;
|
|
74
|
+
|
|
75
|
+
CREATE TRIGGER IF NOT EXISTS slides_au AFTER UPDATE ON slides BEGIN
|
|
76
|
+
INSERT INTO slides_fts(slides_fts, rowid, text) VALUES ('delete', old.id, old.text);
|
|
77
|
+
INSERT INTO slides_fts(rowid, text) VALUES (new.id, new.text);
|
|
78
|
+
END;
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def connect(db_path: Path) -> sqlite3.Connection:
|
|
83
|
+
"""Open a connection to the project database, creating the schema if needed."""
|
|
84
|
+
conn = sqlite3.connect(str(db_path), check_same_thread=False)
|
|
85
|
+
conn.row_factory = sqlite3.Row
|
|
86
|
+
conn.execute("PRAGMA foreign_keys = ON")
|
|
87
|
+
conn.executescript(_SCHEMA)
|
|
88
|
+
deck_columns = {row["name"] for row in conn.execute("PRAGMA table_info(decks)")}
|
|
89
|
+
for column, kind in (("strip_pdf_path", "TEXT"), ("strip_pdf_mtime", "REAL")):
|
|
90
|
+
if column not in deck_columns:
|
|
91
|
+
conn.execute(f"ALTER TABLE decks ADD COLUMN {column} {kind}")
|
|
92
|
+
columns = {row["name"] for row in conn.execute("PRAGMA table_info(slides)")}
|
|
93
|
+
if "user_hidden" not in columns:
|
|
94
|
+
conn.execute("ALTER TABLE slides ADD COLUMN user_hidden INTEGER")
|
|
95
|
+
if "source_slide_id" not in columns:
|
|
96
|
+
conn.execute("ALTER TABLE slides ADD COLUMN source_slide_id INTEGER")
|
|
97
|
+
conn.execute(
|
|
98
|
+
"INSERT OR REPLACE INTO meta(key, value) VALUES ('schema_version', ?)",
|
|
99
|
+
(str(SCHEMA_VERSION),),
|
|
100
|
+
)
|
|
101
|
+
conn.commit()
|
|
102
|
+
return conn
|
slidedesk/embeddings.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Optional embedding-based semantic search via a local Hugging Face model.
|
|
2
|
+
|
|
3
|
+
Caches one embedding vector per slide (see `slide_embeddings` table in db.py) so
|
|
4
|
+
that only new/changed slide text needs to be sent to the embedding endpoint;
|
|
5
|
+
searching just embeds the query and compares it against the cached vectors.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import array
|
|
10
|
+
import math
|
|
11
|
+
import threading
|
|
12
|
+
from typing import List, Sequence
|
|
13
|
+
|
|
14
|
+
DEFAULT_MODEL = "intfloat/multilingual-e5-large-instruct"
|
|
15
|
+
|
|
16
|
+
_local_model_cache = {}
|
|
17
|
+
_local_model_lock = threading.Lock()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class EmbeddingError(RuntimeError):
|
|
21
|
+
"""Raised when an embedding could not be computed (missing deps/key, API error, ...)."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def is_available() -> bool:
|
|
25
|
+
"""Check whether the local embedding dependencies are installed."""
|
|
26
|
+
try:
|
|
27
|
+
import torch
|
|
28
|
+
import transformers
|
|
29
|
+
except ImportError:
|
|
30
|
+
return False
|
|
31
|
+
return True
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def get_device():
|
|
35
|
+
"""Pick the best available torch device (CUDA > MPS > CPU)."""
|
|
36
|
+
import torch
|
|
37
|
+
|
|
38
|
+
try:
|
|
39
|
+
cuda = getattr(torch, "cuda", None)
|
|
40
|
+
if cuda is not None and cuda.is_available():
|
|
41
|
+
return torch.device("cuda")
|
|
42
|
+
backends = getattr(torch, "backends", None)
|
|
43
|
+
mps = getattr(backends, "mps", None) if backends is not None else None
|
|
44
|
+
if mps is not None and mps.is_available():
|
|
45
|
+
return torch.device("mps")
|
|
46
|
+
return torch.device("cpu")
|
|
47
|
+
except AttributeError:
|
|
48
|
+
# torch module stubbed out (e.g. in tests) without a device API.
|
|
49
|
+
return "cpu"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def embed_local(text: str, embedding_model: str = DEFAULT_MODEL) -> List[float]:
|
|
53
|
+
"""Embed `text` using a locally downloaded Hugging Face E5 model."""
|
|
54
|
+
try:
|
|
55
|
+
import torch
|
|
56
|
+
from transformers import AutoModel, AutoTokenizer
|
|
57
|
+
except ImportError as exc:
|
|
58
|
+
raise EmbeddingError("The 'torch' and 'transformers' packages are required for embeddings") from exc
|
|
59
|
+
|
|
60
|
+
device = get_device()
|
|
61
|
+
with _local_model_lock:
|
|
62
|
+
cache_key = (embedding_model, str(device))
|
|
63
|
+
if cache_key not in _local_model_cache:
|
|
64
|
+
tokenizer = AutoTokenizer.from_pretrained(embedding_model)
|
|
65
|
+
# low_cpu_mem_usage would place weights on the "meta" device; disable it
|
|
66
|
+
# so the model is materialized directly and can be moved with .to(device).
|
|
67
|
+
model = AutoModel.from_pretrained(
|
|
68
|
+
embedding_model, dtype=torch.float32, low_cpu_mem_usage=False
|
|
69
|
+
)
|
|
70
|
+
# Keep all floating-point parameters and buffers consistent,
|
|
71
|
+
# including layers whose checkpoint dtype differs from the rest.
|
|
72
|
+
model.float()
|
|
73
|
+
model.to(device)
|
|
74
|
+
model.eval()
|
|
75
|
+
_local_model_cache[cache_key] = (tokenizer, model)
|
|
76
|
+
tokenizer, model = _local_model_cache[cache_key]
|
|
77
|
+
|
|
78
|
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, max_length=512)
|
|
79
|
+
inputs = {
|
|
80
|
+
key: value.to(device) if hasattr(value, "to") else value
|
|
81
|
+
for key, value in inputs.items()
|
|
82
|
+
}
|
|
83
|
+
with torch.inference_mode():
|
|
84
|
+
outputs = model(**inputs)
|
|
85
|
+
token_embeddings = outputs.last_hidden_state
|
|
86
|
+
attention_mask = inputs["attention_mask"].unsqueeze(-1).expand(token_embeddings.size()).float()
|
|
87
|
+
pooled = (token_embeddings * attention_mask).sum(dim=1) / attention_mask.sum(dim=1).clamp(min=1e-9)
|
|
88
|
+
normalized = torch.nn.functional.normalize(pooled, p=2, dim=1)
|
|
89
|
+
return normalized[0].cpu().tolist()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def pack_vector(vector: Sequence[float]) -> bytes:
|
|
93
|
+
"""Serialize an embedding vector to bytes for storage in the DB."""
|
|
94
|
+
return array.array("f", vector).tobytes()
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def unpack_vector(blob: bytes) -> array.array:
|
|
98
|
+
"""Deserialize an embedding vector previously stored with `pack_vector`."""
|
|
99
|
+
arr = array.array("f")
|
|
100
|
+
arr.frombytes(blob)
|
|
101
|
+
return arr
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def cosine_similarity(a: Sequence[float], b: Sequence[float]) -> float:
|
|
105
|
+
"""Compute the cosine similarity between two vectors."""
|
|
106
|
+
dot = sum(x * y for x, y in zip(a, b))
|
|
107
|
+
norm_a = math.sqrt(sum(x * x for x in a))
|
|
108
|
+
norm_b = math.sqrt(sum(y * y for y in b))
|
|
109
|
+
if norm_a == 0 or norm_b == 0:
|
|
110
|
+
return 0.0
|
|
111
|
+
return dot / (norm_a * norm_b)
|
|
112
|
+
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Lazy, process-local CLIP inference; persistent vectors live in the project DB."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import threading
|
|
5
|
+
from importlib.util import find_spec
|
|
6
|
+
|
|
7
|
+
from .embeddings import EmbeddingError, get_device
|
|
8
|
+
|
|
9
|
+
MODEL = "openai/clip-vit-base-patch32"
|
|
10
|
+
_lock = threading.Lock()
|
|
11
|
+
_models = {}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def is_available() -> bool:
|
|
15
|
+
"""Check dependencies without loading or downloading the model."""
|
|
16
|
+
return all(find_spec(name) is not None for name in ("torch", "transformers"))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def embed_image(image, model: str = MODEL):
|
|
20
|
+
"""Load CLIP once and embed an RGB slide without tracking gradients."""
|
|
21
|
+
with _lock:
|
|
22
|
+
try:
|
|
23
|
+
import torch
|
|
24
|
+
from transformers import CLIPModel, CLIPProcessor
|
|
25
|
+
|
|
26
|
+
device = get_device()
|
|
27
|
+
cache_key = (model, str(device))
|
|
28
|
+
if cache_key not in _models:
|
|
29
|
+
# low_cpu_mem_usage would place weights on the "meta" device; disable it
|
|
30
|
+
# so the model is materialized directly and can be moved with .to(device).
|
|
31
|
+
encoder = CLIPModel.from_pretrained(model, low_cpu_mem_usage=False)
|
|
32
|
+
encoder.eval()
|
|
33
|
+
encoder.to(device)
|
|
34
|
+
processor = CLIPProcessor.from_pretrained(model)
|
|
35
|
+
_models[cache_key] = encoder, processor
|
|
36
|
+
encoder, processor = _models[cache_key]
|
|
37
|
+
inputs = processor(images=image.convert("RGB"), return_tensors="pt")
|
|
38
|
+
inputs = {
|
|
39
|
+
key: value.to(device) if hasattr(value, "to") else value
|
|
40
|
+
for key, value in inputs.items()
|
|
41
|
+
}
|
|
42
|
+
with torch.no_grad():
|
|
43
|
+
features = encoder.get_image_features(**inputs)
|
|
44
|
+
# Transformers 5 returns a model output; 4 returns a tensor.
|
|
45
|
+
if hasattr(features, "pooler_output"):
|
|
46
|
+
features = features.pooler_output
|
|
47
|
+
return features.squeeze(0).cpu().tolist()
|
|
48
|
+
except Exception as exc:
|
|
49
|
+
raise EmbeddingError(f"CLIP image embedding failed: {exc}") from exc
|
slidedesk/images.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Render PNG images for individual slides from their PDF export, with caching."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
from functools import lru_cache
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Optional
|
|
8
|
+
|
|
9
|
+
from pdf2image import convert_from_bytes
|
|
10
|
+
from PIL import Image
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _cache_key(pdf_path: Path, page: int) -> str:
|
|
14
|
+
stat = pdf_path.stat()
|
|
15
|
+
raw = f"{pdf_path}|{stat.st_mtime_ns}|{stat.st_size}|{page}"
|
|
16
|
+
return hashlib.sha1(raw.encode("utf-8")).hexdigest()
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@lru_cache(maxsize=20)
|
|
20
|
+
def _read_pdf_bytes_cached(
|
|
21
|
+
pdf_path: Path
|
|
22
|
+
) -> bytes:
|
|
23
|
+
return pdf_path.read_bytes()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def read_pdf_bytes(pdf_path: Path) -> bytes:
|
|
27
|
+
"""Read a PDF from disk, caching up to 20 recent file versions."""
|
|
28
|
+
return _read_pdf_bytes_cached(pdf_path)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def render_page(
|
|
32
|
+
pdf_path: Path, page: int, cache_dir: Path, grayscale: bool = False
|
|
33
|
+
) -> Image.Image:
|
|
34
|
+
"""Return the given 1-based `page` of `pdf_path` as a PIL Image, using a
|
|
35
|
+
PNG cache on disk keyed by pdf path/mtime/page so repeat requests are cheap.
|
|
36
|
+
With `grayscale`, the cached PNG is converted to grayscale before saving.
|
|
37
|
+
"""
|
|
38
|
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
|
39
|
+
key = _cache_key(pdf_path, page)
|
|
40
|
+
cached = cache_dir / f"{key}.png"
|
|
41
|
+
if cached.exists():
|
|
42
|
+
return Image.open(cached)
|
|
43
|
+
|
|
44
|
+
pages = convert_from_bytes(
|
|
45
|
+
read_pdf_bytes(pdf_path), dpi=80, first_page=page, last_page=page
|
|
46
|
+
)
|
|
47
|
+
if not pages:
|
|
48
|
+
raise ValueError(f"Page {page} not found in {pdf_path}")
|
|
49
|
+
image = pages[0]
|
|
50
|
+
if grayscale:
|
|
51
|
+
image = image.convert("L").convert("RGB")
|
|
52
|
+
image.save(cached, format="PNG")
|
|
53
|
+
return image
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def cached_path(
|
|
57
|
+
pdf_path: Path, page: int, cache_dir: Path
|
|
58
|
+
) -> Optional[Path]:
|
|
59
|
+
key = _cache_key(pdf_path, page)
|
|
60
|
+
candidate = cache_dir / f"{key}.png"
|
|
61
|
+
return candidate if candidate.exists() else None
|