Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

add deduplication with obsidian

Louis Beaumont5891e99ec43f
diff --git a/pipes/obsidian/package.json b/pipes/obsidian/package.json
index e29b33d5b..407e88bc1 100644
--- a/pipes/obsidian/package.json
+++ b/pipes/obsidian/package.json
@@ -1,6 +1,6 @@
{
"name": "obsidian",
- "version": "0.1.26",
+ "version": "0.1.27",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
diff --git a/pipes/obsidian/src/app/api/log/route.ts b/pipes/obsidian/src/app/api/log/route.ts
index 73a124535..b458c895b 100644
--- a/pipes/obsidian/src/app/api/log/route.ts
+++ b/pipes/obsidian/src/app/api/log/route.ts
@@ -1,6 +1,6 @@
import { NextResponse } from "next/server";
import { z } from "zod";
-import { generateObject } from "ai";
+import { embed, generateObject } from "ai";
import { ollama } from "ollama-ai-provider";
import { ContentItem } from "@screenpipe/js";
import { pipe } from "@screenpipe/js";
@@ -94,7 +94,6 @@ async function generateWorkLog(
schema: workLog,
});
- console.log("response:", response.object);
const formatDate = (date: Date) => {
return date.toLocaleString("en-US", {
year: "numeric",
@@ -186,16 +185,86 @@ function getObsidianUrl(vaultName: string, filename: string): string {
)}&file=${encodeURIComponent(filename)}`;
}
+async function deduplicateScreenData(
+ screenData: ContentItem[]
+): Promise<ContentItem[]> {
+ if (!screenData.length) return screenData;
+
+ try {
+ const provider = ollama.embedding("nomic-embed-text");
+ const embeddings: number[][] = [];
+ const uniqueData: ContentItem[] = [];
+ let duplicatesRemoved = 0;
+
+ for (const item of screenData) {
+ const textToEmbed =
+ "content" in item
+ ? typeof item.content === "string"
+ ? item.content
+ : "text" in item.content
+ ? item.content.text
+ : JSON.stringify(item.content)
+ : "";
+
+ if (!textToEmbed.trim()) {
+ uniqueData.push(item);
+ continue;
+ }
+
+ try {
+ const { embedding } = await embed({
+ model: provider,
+ value: textToEmbed,
+ });
+
+ let isDuplicate = false;
+ for (let i = 0; i < embeddings.length; i++) {
+ const similarity = cosineSimilarity(embedding, embeddings[i]);
+ if (similarity > 0.95) {
+ isDuplicate = true;
+ duplicatesRemoved++;
+ break;
+ }
+ }
+
+ if (!isDuplicate) {
+ embeddings.push(embedding);
+ uniqueData.push(item);
+ }
+ } catch (error) {
+ console.warn("embedding failed for item, keeping it:", error);
+ uniqueData.push(item);
+ }
+ }
+
+ console.log(
+ `deduplication: removed ${duplicatesRemoved} duplicates from ${screenData.length} items`
+ );
+ return uniqueData;
+ } catch (error) {
+ console.warn("deduplication failed, using original data:", error);
+ return screenData;
+ }
+}
+
+function cosineSimilarity(a: number[], b: number[]): number {
+ const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);
+ const normA = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0));
+ const normB = Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));
+ return dotProduct / (normA * normB);
+}
+
export async function GET() {
try {
const settings = await pipe.settings.getAll();
- console.log("settings:", settings);
const interval =
settings.customSettings?.obsidian?.logTimeWindow || 3600000;
const obsidianPath = settings.customSettings?.obsidian?.vaultPath;
const customPrompt = settings.customSettings?.obsidian?.prompt;
const pageSize = settings.customSettings?.obsidian?.logPageSize || 100;
const model = settings.customSettings?.obsidian?.logModel;
+ const deduplicationEnabled =
+ settings.customSettings?.obsidian?.deduplicationEnabled;
if (!obsidianPath) {
return NextResponse.json(
@@ -207,7 +276,7 @@ export async function GET() {
const now = new Date();
const oneHourAgo = new Date(now.getTime() - interval);
- const screenData = await pipe.queryScreenpipe({
+ let screenData = await pipe.queryScreenpipe({
startTime: oneHourAgo.toISOString(),
endTime: now.toISOString(),
limit: pageSize,
@@ -218,6 +287,18 @@ export async function GET() {
return NextResponse.json({ message: "no activity detected" });
}
+ // Only deduplicate if enabled in settings
+ if (deduplicationEnabled) {
+ try {
+ screenData.data = await deduplicateScreenData(screenData.data);
+ } catch (error) {
+ console.warn(
+ "deduplication failed, continuing with original data:",
+ error
+ );
+ }
+ }
+
const logEntry = await generateWorkLog(
screenData.data,
model,
diff --git a/pipes/obsidian/src/components/obsidian-settings.tsx b/pipes/obsidian/src/components/obsidian-settings.tsx
index 17c464e47..96de8513d 100644
--- a/pipes/obsidian/src/components/obsidian-settings.tsx
+++ b/pipes/obsidian/src/components/obsidian-settings.tsx
@@ -29,6 +29,8 @@ import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import { CodeBlock } from "./ui/codeblock";
import { VideoComponent } from "./video";
+import { Switch } from "@/components/ui/switch";
+
export function ObsidianSettings() {
const { settings, updateSettings, loading } = usePipeSettings();
const [lastLog, setLastLog] = useState<any>(null);
@@ -50,6 +52,9 @@ export function ObsidianSettings() {
isChecking: false,
});
const [suggestedPaths, setSuggestedPaths] = useState<string[]>([]);
+ const [deduplicationEnabled, setDeduplicationEnabled] =
+ useState<boolean>(false);
+ const [checkingModel, setCheckingModel] = useState<boolean>(false);
useEffect(() => {
if (settings) {
@@ -201,7 +206,6 @@ export function ObsidianSettings() {
try {
const res = await fetch("/api/intelligence");
const data = await res.json();
- console.log("data", data);
setIntelligence(data.intelligence);
if (!data.summary.logsAnalyzed) {
@@ -377,6 +381,117 @@ export function ObsidianSettings() {
}
}, [settings?.vaultPath, validatePath]);
+ const setupDeduplication = async () => {
+ setCheckingModel(true);
+ try {
+ // Direct request to Ollama API
+ const checkRes = await fetch("http://localhost:11434/api/tags");
+ const models = await checkRes.json();
+
+ const hasEmbeddingModel = models.models?.some(
+ (m: { name: string }) => m.name === "nomic-embed-text"
+ );
+
+ if (!hasEmbeddingModel) {
+ // Show loading toast
+ const loadingToast = toast({
+ title: "pulling embedding model...",
+ description: (
+ <div>
+ <p>downloading nomic-embed-text model</p>
+ <p>this may take a few minutes</p>
+ <Loader2 className="h-4 w-4 animate-spin" />
+ </div>
+ ),
+ });
+
+ // Direct pull request to Ollama
+ const pullRes = await fetch("http://localhost:11434/api/pull", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ name: "nomic-embed-text" }),
+ });
+
+ if (!pullRes.ok) {
+ throw new Error("failed to pull model");
+ }
+
+ // Handle streaming response
+ const reader = pullRes.body?.getReader();
+ const decoder = new TextDecoder();
+
+ if (!reader) {
+ throw new Error("no response body");
+ }
+
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ const lines = chunk.split("\n").filter((line) => line.trim());
+
+ for (const line of lines) {
+ const response = JSON.parse(line);
+ console.log("progress:", response);
+
+ // Update toast with progress if available
+ if (response.total && response.completed) {
+ const progress = Math.round(
+ (response.completed / response.total) * 100
+ );
+ loadingToast.update({
+ id: loadingToast.id,
+ title: "pulling embedding model...",
+ description: (
+ <div>
+ <p>downloading nomic-embed-text model: {progress}%</p>
+ <p>{response.status}</p>
+ <Loader2 className="h-4 w-4 animate-spin" />
+ </div>
+ ),
+ });
+ }
+ }
+ }
+
+ loadingToast.update({
+ id: loadingToast.id,
+ title: "model ready",
+ description: "embedding model has been downloaded",
+ });
+ }
+
+ setDeduplicationEnabled(true);
+ await updateSettings({
+ ...settings!,
+ deduplicationEnabled: true,
+ });
+
+ toast({
+ title: "deduplication enabled",
+ description: "content will be deduplicated before processing",
+ });
+ } catch (error) {
+ console.error("error setting up deduplication:", error);
+ toast({
+ variant: "destructive",
+ title: "error",
+ description: "failed to setup deduplication",
+ });
+ setDeduplicationEnabled(false);
+ } finally {
+ setCheckingModel(false);
+ }
+ };
+
+ // Add this useEffect to initialize the state from settings
+ useEffect(() => {
+ if (settings) {
+ setDeduplicationEnabled(settings.deduplicationEnabled || false);
+ }
+ }, [settings]);
+
if (loading) {
return (
<div className="w-full max-w-4xl mx-auto space-y-8">
@@ -510,6 +625,49 @@ export function ObsidianSettings() {
<CardTitle>short-term activity logs</CardTitle>
</CardHeader>
<CardContent className="space-y-6">
+ <div className="space-y-2">
+ <Label
+ htmlFor="deduplication"
+ className="flex items-center gap-2"
+ >
+ <LineChart className="h-4 w-4" />
+ content deduplication
+ </Label>
+ <div className="flex items-center space-x-2">
+ <Switch
+ id="deduplication"
+ checked={deduplicationEnabled}
+ disabled={checkingModel || !pathValidation.isValid}
+ onCheckedChange={async (checked) => {
+ if (checked) {
+ await setupDeduplication();
+ } else {
+ setDeduplicationEnabled(false);
+ await updateSettings({
+ ...settings!,
+ deduplicationEnabled: false,
+ });
+ }
+ }}
+ />
+ <Label htmlFor="deduplication" className="text-sm">
+ {checkingModel ? (
+ <span className="flex items-center gap-2">
+ <Loader2 className="h-4 w-4 animate-spin" />
+ downloading model...
+ </span>
+ ) : (
+ "deduplicate similar content before processing"
+ )}
+ </Label>
+ </div>
+ <p className="text-xs text-muted-foreground">
+ uses embeddings to remove duplicate content, it will
+ download the <code>nomic-embed-text</code> model if it is
+ not already downloaded
+ </p>
+ </div>
+
<div className="space-y-2">
<Label
htmlFor="logTimeWindow"
diff --git a/pipes/obsidian/src/lib/types.ts b/pipes/obsidian/src/lib/types.ts
index ef675082a..bc41e7f19 100644
--- a/pipes/obsidian/src/lib/types.ts
+++ b/pipes/obsidian/src/lib/types.ts
@@ -33,5 +33,6 @@ export interface Settings {
logModel: string;
analysisModel: string;
analysisTimeWindow: number;
+ deduplicationEnabled: boolean;
screenpipeAppSettings: ScreenpipeAppSettings;
}
diff --git a/pipes/rewind/package.json b/pipes/rewind/package.json
index 577e60887..e9f7fa519 100644
--- a/pipes/rewind/package.json
+++ b/pipes/rewind/package.json
@@ -1,6 +1,6 @@
{
"name": "rewind",
- "version": "0.1.8",
+ "version": "0.1.9",
"private": true,
"scripts": {
"dev": "next dev --turbopack",
diff --git a/screenpipe-js/cli/dist/index.js b/screenpipe-js/cli/dist/index.js
index 87cc39d52..873f60486 100755
--- a/screenpipe-js/cli/dist/index.js
+++ b/screenpipe-js/cli/dist/index.js
@@ -62426,7 +62426,7 @@ async function downloadAndExtractSubdir(subdir, destPath) {
}
var createPipeCommand = new Command().name("create").description("create a new pipe").action(async () => {
console.log(source_default.bold(`
-welcome to screenpipe! \uD83D\uDE80
+welcome to screenpipe!
`));
logger.log(`let's create a new screenpipe pipe.
`);
@@ -62478,7 +62478,7 @@ welcome to screenpipe! \uD83D\uDE80
...PIPE_ADDITIONS.devDependencies
};
await import_fs_extra.default.writeJson(pkgPath, pkg, { spaces: 2 });
- loadingSpinner.succeed(source_default.green(`> pipe created successfully! \uD83C\uDF89`));
+ loadingSpinner.succeed(source_default.green(`> pipe created successfully!`));
console.log(`
to get started:`);
console.log(source_default.cyan(`cd ${directory}`));
diff --git a/screenpipe-js/cli/package.json b/screenpipe-js/cli/package.json
index ff6086726..751de0351 100644
--- a/screenpipe-js/cli/package.json
+++ b/screenpipe-js/cli/package.json
@@ -1,6 +1,6 @@
{
"name": "@screenpipe/dev",
- "version": "1.1.12",
+ "version": "1.1.13",
"description": "screenpipe development CLI",
"type": "module",
"main": "dist/index.js",
diff --git a/screenpipe-js/cli/src/commands/pipe/create.ts b/screenpipe-js/cli/src/commands/pipe/create.ts
index a4a8e9c65..b0002e2e9 100755
--- a/screenpipe-js/cli/src/commands/pipe/create.ts
+++ b/screenpipe-js/cli/src/commands/pipe/create.ts
@@ -33,7 +33,7 @@ export const createPipeCommand = new Command()
.name("create")
.description("create a new pipe")
.action(async () => {
- console.log(chalk.bold("\nwelcome to screenpipe! 🚀\n"));
+ console.log(chalk.bold("\nwelcome to screenpipe!\n"));
logger.log("let's create a new screenpipe pipe.\n");
logger.log(
"pipes are plugins that interact with captured screen and audio data."
@@ -92,7 +92,7 @@ export const createPipeCommand = new Command()
await fs.writeJson(pkgPath, pkg, { spaces: 2 });
- loadingSpinner.succeed(chalk.green(`> pipe created successfully! 🎉`));
+ loadingSpinner.succeed(chalk.green(`> pipe created successfully!`));
console.log("\nto get started:");
console.log(chalk.cyan(`cd ${directory}`));