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

feat: speaker identification UI / API

Ezra Ellette1146c2b10d0b
diff --git a/screenpipe-app-tauri/app/identify-speakers/page.tsx b/screenpipe-app-tauri/app/identify-speakers/page.tsx
new file mode 100644
index 000000000..de5488fd7
--- /dev/null
+++ b/screenpipe-app-tauri/app/identify-speakers/page.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import IdentifySpeakers from "@/components/identify-speakers";
+import { useState } from "react";
+
+export default function IdentifySpeakersPage() {
+ const [_, setShowIdentifySpeakers] = useState(true);
+ return (
+ <IdentifySpeakers
+ showIdentifySpeakers={true}
+ setShowIdentifySpeakers={setShowIdentifySpeakers}
+ />
+ );
+}
diff --git a/screenpipe-app-tauri/app/meetings/page.tsx b/screenpipe-app-tauri/app/meetings/page.tsx
new file mode 100644
index 000000000..5396cc0df
--- /dev/null
+++ b/screenpipe-app-tauri/app/meetings/page.tsx
@@ -0,0 +1,14 @@
+"use client";
+
+import MeetingHistory from "@/components/meeting-history";
+import { useState } from "react";
+
+export default function MeetingsPage() {
+ const [showMeetingHistory, setShowMeetingHistory] = useState(true);
+ return (
+ <MeetingHistory
+ showMeetingHistory={true}
+ setShowMeetingHistory={setShowMeetingHistory}
+ />
+ );
+}
diff --git a/screenpipe-app-tauri/bun.lockb b/screenpipe-app-tauri/bun.lockb
index 3bd3e9ce9..cd6892df9 100755
Binary files a/screenpipe-app-tauri/bun.lockb and b/screenpipe-app-tauri/bun.lockb differ
diff --git a/screenpipe-app-tauri/components/auth.tsx b/screenpipe-app-tauri/components/auth.tsx
index 18b464ac2..4e6443b7a 100644
--- a/screenpipe-app-tauri/components/auth.tsx
+++ b/screenpipe-app-tauri/components/auth.tsx
@@ -6,7 +6,6 @@ import { useEffect, useState } from "react";
import { useUser } from "@/lib/hooks/use-user";
import { Avatar, AvatarFallback } from "./ui/avatar";
import posthog from "posthog-js";
-import { DropdownMenuItem } from "./ui/dropdown-menu";
import { LogIn } from "lucide-react";
export function AuthButton() {
@@ -33,10 +32,10 @@ export function AuthButton() {
{user?.email}
</span>
) : (
- <DropdownMenuItem className="cursor-pointer" onClick={handleSignIn}>
+ <div className="p-2 m-0" onClick={handleSignIn}>
<LogIn className="mr-2 h-4 w-4" />
<span>sign in</span>
- </DropdownMenuItem>
+ </div>
)}
</div>
);
diff --git a/screenpipe-app-tauri/components/header.tsx b/screenpipe-app-tauri/components/header.tsx
index 2a04ec4b8..97309a6fd 100644
--- a/screenpipe-app-tauri/components/header.tsx
+++ b/screenpipe-app-tauri/components/header.tsx
@@ -1,12 +1,9 @@
"use client";
-import Image from "next/image";
import { Button } from "@/components/ui/button";
import { Settings } from "@/components/settings";
-import { PrettyLink } from "@/components/pretty-link";
import HealthStatus from "@/components/screenpipe-status";
import React from "react";
-import MeetingHistory from "@/components/meeting-history";
import {
DropdownMenu,
DropdownMenuContent,
@@ -19,13 +16,13 @@ import {
import {
MessageSquare,
Heart,
- Menu,
Bell,
Play,
Folder,
Search,
Book,
User,
+ Fingerprint,
} from "lucide-react";
import { open } from "@tauri-apps/plugin-shell";
import {
@@ -33,8 +30,7 @@ import {
InboxMessages,
Message,
} from "@/components/inbox-messages";
-import { useState, useRef, useEffect } from "react";
-import Onboarding from "@/components/onboarding";
+import { useState, useEffect } from "react";
import { useOnboarding } from "@/lib/hooks/use-onboarding";
import { listen } from "@tauri-apps/api/event";
import localforage from "localforage";
@@ -51,12 +47,12 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
import { Calendar } from "lucide-react";
-import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { useUser } from "@/lib/hooks/use-user";
import { AuthButton } from "./auth";
export default function Header() {
const [showInbox, setShowInbox] = useState(false);
+ const [showSettings, setShowSettings] = useState(false);
const [messages, setMessages] = useState<Message[]>([]);
const { health } = useHealthCheck();
const { settings } = useSettings();
@@ -137,6 +133,14 @@ export default function Header() {
await invoke("show_search");
};
+ const handleShowMeetingHistory = async () => {
+ await invoke("show_meetings");
+ };
+
+ const handleShowIdentifySpeakers = async () => {
+ await invoke("show_identify_speakers");
+ };
+
return (
<div>
{isLoading ? (
@@ -150,6 +154,43 @@ export default function Header() {
</div>
<div className="flex space-x-4 absolute top-4 right-4">
<HealthStatus className="mt-3 cursor-pointer" />
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <div>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="cursor-pointer"
+ onClick={handleShowTimeline}
+ disabled={
+ !settings.enableFrameCache ||
+ !health ||
+ health.status === "error"
+ }
+ >
+ <Clock className="mr-2 h-4 w-4" />
+ timeline
+ </Button>
+ </div>
+ </TooltipTrigger>
+ {!settings.enableFrameCache && (
+ <TooltipContent>
+ <p>enable timeline in settings first</p>
+ </TooltipContent>
+ )}
+ </Tooltip>
+ </TooltipProvider>
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={handleShowMeetingHistory}
+ className="cursor-pointer"
+ >
+ <Calendar className="mr-2 h-4 w-4" />
+ <span>meetings</span>
+ </Button>
+ <Settings />
<Button
variant="ghost"
size="icon"
@@ -174,9 +215,20 @@ export default function Header() {
<DropdownMenuLabel>account</DropdownMenuLabel>
<DropdownMenuSeparator />
<DropdownMenuGroup>
- <AuthButton />
+ <DropdownMenuItem className="cursor-pointer p-0">
+ <AuthButton />
+ </DropdownMenuItem>
<DropdownMenuSeparator />
- <Settings />
+ <DropdownMenuItem
+ className="cursor-pointer p-0"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setShowSettings(true);
+ }}
+ >
+ <Settings />
+ </DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuGroup>
@@ -200,8 +252,20 @@ export default function Header() {
<Clock className="mr-2 h-4 w-4" />
<span>timeline</span>
</DropdownMenuItem>
- <DropdownMenuItem className="cursor-pointer p-0">
- <MeetingHistory />
+ <DropdownMenuItem
+ className="cursor-pointer"
+ onClick={handleShowMeetingHistory}
+ disabled={!health || health.status === "error"}
+ >
+ <Calendar className="mr-2 h-4 w-4" />
+ <span>meetings</span>
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className="cursor-pointer"
+ onClick={handleShowIdentifySpeakers}
+ >
+ <Fingerprint className="mr-2 h-4 w-4" />
+ <span>identify speakers</span>
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
diff --git a/screenpipe-app-tauri/components/identify-speakers.tsx b/screenpipe-app-tauri/components/identify-speakers.tsx
new file mode 100644
index 000000000..72bde93fb
--- /dev/null
+++ b/screenpipe-app-tauri/components/identify-speakers.tsx
@@ -0,0 +1,1340 @@
+"use client";
+
+import { useState, useEffect } from "react";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { useSettings } from "@/lib/hooks/use-settings";
+import { useToast } from "./ui/use-toast";
+import {
+ X,
+ Fingerprint,
+ Check,
+ ChevronRight,
+ Save,
+ Ghost,
+ Trash,
+} from "lucide-react";
+import { usePostHog } from "posthog-js/react";
+import { Badge } from "./ui/badge";
+import { Input } from "./ui/input";
+import { cn, getFileSize, keysToCamelCase } from "@/lib/utils";
+import { VideoComponent } from "./video";
+import { AudioSample, MeetingSegment, Speaker } from "@/lib/types";
+import { isSea } from "node:sea";
+import { motion } from "framer-motion";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "./ui/card";
+
+interface UnnamedSpeaker {
+ id: number;
+ name: string;
+ metadata: string;
+}
+
+export default function IdentifySpeakers({
+ showIdentifySpeakers,
+ setShowIdentifySpeakers,
+ segments,
+ className,
+}: {
+ showIdentifySpeakers: boolean;
+ setShowIdentifySpeakers: (show: boolean) => void;
+ segments?: MeetingSegment[];
+ className?: string;
+}) {
+ const posthog = usePostHog();
+ const { settings } = useSettings();
+ const [unnamedSpeakers, setUnnamedSpeakers] = useState<Speaker[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const { toast } = useToast();
+ const [showError, setShowError] = useState(false);
+ const [currentSpeakerIndex, setCurrentSpeakerIndex] = useState(0);
+ const [showHallucinationConfirm, setShowHallucinationConfirm] =
+ useState(false);
+ const [showNameUpdateConfirm, setShowNameUpdateConfirm] = useState(false);
+ const [speakerSearchTerm, setSpeakerSearchTerm] = useState<string>("");
+ const [speakers, setSpeakers] = useState<Speaker[]>([]);
+ const [isSearching, setIsSearching] = useState(false);
+ const [showMergeConfirm, setShowMergeConfirm] = useState(false);
+ const [selectedExistingSpeaker, setSelectedExistingSpeaker] =
+ useState<Speaker | null>(null);
+ const [segmentSpeakerIds, setSegmentSpeakerIds] = useState<number[]>([]);
+ const [similarSpeakers, setSimilarSpeakers] = useState<Speaker[]>([]);
+ const [isFetchingSimilarSpeakers, setIsFetchingSimilarSpeakers] =
+ useState(false);
+ const [speakerIdentified, setSpeakerIdentified] = useState(false);
+ const [similarSpeakerIndex, setSimilarSpeakerIndex] = useState(0);
+ const [showRemoveSpeakerConfirm, setShowRemoveSpeakerConfirm] =
+ useState(false);
+ const [showSpeakerNames, setShowSpeakerNames] = useState(false);
+ const [mounted, setMounted] = useState(false);
+ useEffect(() => {
+ setMounted(true);
+ }, []);
+ useEffect(() => {
+ if (!isSearching && speakers.length > 0) {
+ setShowSpeakerNames(true);
+ }
+ }, [isSearching, speakers]);
+
+ useEffect(() => {
+ if (speakerSearchTerm) {
+ fetchSpeakers(speakerSearchTerm);
+ }
+ }, [speakerSearchTerm]);
+
+ useEffect(() => {
+ if (unnamedSpeakers.length > 0) {
+ fetchSimilarSpeakers(unnamedSpeakers[currentSpeakerIndex].id);
+ }
+ }, [currentSpeakerIndex]);
+
+ useEffect(() => {
+ speakerIdentified &&
+ setSimilarSpeakers(similarSpeakers.filter((s) => !s.name));
+ }, [speakerIdentified]);
+
+ useEffect(() => {
+ if (posthog) {
+ posthog.identify(settings.userId);
+ posthog.people.set({
+ userId: settings.userId,
+ });
+ }
+ }, [posthog, settings.userId]);
+
+ useEffect(() => {
+ if (segments) {
+ setSegmentSpeakerIds(segments.map((segment) => segment.speaker.id));
+ }
+ }, [segments]);
+
+ useEffect(() => {
+ if (showIdentifySpeakers) {
+ loadUnnamedSpeakers();
+ posthog?.capture("identify_speakers_opened", {
+ userId: settings.userId,
+ source: segments ? "meeting_history" : "menu",
+ });
+ } else {
+ posthog?.capture("identify_speakers_closed", {
+ userId: settings.userId,
+ source: segments ? "meeting_history" : "menu",
+ });
+ setSpeakerIdentified(false);
+ setSelectedExistingSpeaker(null);
+ setSpeakerSearchTerm("");
+ setSpeakers([]);
+ setSimilarSpeakers([]);
+ setCurrentSpeakerIndex(0);
+ }
+ /* eslint-disable-next-line react-hooks/exhaustive-deps */
+ }, [showIdentifySpeakers, settings.userId, posthog]);
+
+ useEffect(() => {
+ setShowError(!!error);
+ }, [error]);
+
+ useEffect(() => {
+ if (showError) {
+ setTimeout(() => {
+ setShowError(false);
+ }, 5000);
+ }
+ }, [showError]);
+
+ async function loadUnnamedSpeakers() {
+ setLoading(true);
+ try {
+ await fetchUnnamedSpeakers();
+ } catch (err) {
+ setError("failed to load unnamed speakers");
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ async function fetchSpeakers(searchTerm: string) {
+ setIsSearching(true);
+
+ try {
+ const response = await fetch(
+ `http://localhost:3030/speakers/search?name=${searchTerm}`
+ );
+ if (!response.ok) {
+ throw new Error("failed to fetch speakers");
+ }
+ const result = await response.json();
+ setSpeakers(result);
+ } catch (error) {
+ console.error("error fetching speakers:", error);
+ setError("failed to fetch speakers");
+ } finally {
+ setIsSearching(false);
+ }
+ }
+
+ async function fetchSimilarSpeakers(speakerId: number) {
+ setIsFetchingSimilarSpeakers(true);
+
+ console.log("fetching similar speakers for", speakerId);
+ try {
+ const response = await fetch(
+ `http://localhost:3030/speakers/similar?speaker_id=${speakerId}&limit=5`
+ );
+ if (!response.ok) {
+ throw new Error("failed to fetch similar speakers");
+ }
+ const result = await response.json();
+
+ const updatedUnnamedSpeakers = result.map((speaker: UnnamedSpeaker) => ({
+ ...speaker,
+ metadata: speaker.metadata ? JSON.parse(speaker.metadata) : undefined,
+ }));
+ const camelCaseResult: Speaker[] = updatedUnnamedSpeakers.map(
+ keysToCamelCase<Speaker>
+ );
+
+ let similarSpeakersResult: Speaker[] = [];
+ for (const speaker of camelCaseResult) {
+ let longestAudioSample = speaker.metadata?.audioSamples[0];
+ let longestAudioPathSize = -Infinity;
+ for (const sample of speaker.metadata?.audioSamples || []) {
+ const size = await getFileSize(sample.path);
+ if (size > longestAudioPathSize) {
+ longestAudioSample = sample;
+ longestAudioPathSize = size;
+ }
+ }
+ similarSpeakersResult.push({
+ ...speaker,
+ metadata: {
+ audioSamples: [
+ {
+ path: longestAudioSample?.path || "",
+ transcript: longestAudioSample?.transcript || "",
+ },
+ ],
+ },
+ });
+ }
+
+ setSimilarSpeakers(similarSpeakersResult);
+ } catch (error) {
+ console.error("error fetching similar speakers:", error);
+ setError("failed to fetch similar speakers");
+ } finally {
+ setIsFetchingSimilarSpeakers(false);
+ }
+ }
+
+ async function fetchUnnamedSpeakers() {
+ setLoading(true);
+ try {
+ // Always fetch from the last 7x24 hours
+
+ const response = await fetch(
+ `http://localhost:3030/speakers/unnamed?limit=1&offset=0${
+ segmentSpeakerIds.length > 0
+ ? `&speaker_ids=${segmentSpeakerIds.join(",")}`
+ : ""
+ }`
+ );
+ if (!response.ok) {
+ throw new Error("failed to fetch unnamed speakers");
+ }
+ const result = await response.json();
+ const updatedUnnamedSpeakers = result.map((speaker: UnnamedSpeaker) => ({
+ ...speaker,
+ metadata: speaker.metadata ? JSON.parse(speaker.metadata) : undefined,
+ }));
+ const camelCaseResult = updatedUnnamedSpeakers.map(
+ keysToCamelCase<Speaker>
+ );
+
+ const results: Speaker[] = await camelCaseResult.map(
+ async (speaker: Speaker) => {
+ const durations: Map<string, number> = new Map();
+ for (const sample of speaker.metadata?.audioSamples || []) {
+ const size = await getFileSize(sample.path);
+ durations.set(sample.path, size);
+ }
+
+ return {
+ ...speaker,
+ metadata: {
+ ...speaker.metadata,
+ audioSamples: speaker.metadata?.audioSamples.sort(
+ (a: AudioSample, b: AudioSample) =>
+ (durations.get(b.path) || 0) - (durations.get(a.path) || 0)
+ ),
+ },
+ };
+ }
+ );
+
+ let sortedResults = await Promise.all(results);
+ console.log("results", sortedResults);
+
+ setUnnamedSpeakers(sortedResults);
+ } catch (err) {
+ setError(
+ "some trouble fetching new meetings. please check health status."
+ );
+ console.error("fetch error:", err);
+ } finally {
+ setLoading(false);
+ }
+ }
+
+ const handleRefresh = async () => {
+ setSpeakers([]);
+ try {
+ await fetchUnnamedSpeakers();
+ toast({
+ title: "speakers refreshed",
+ description: "your speaker identification has been updated.",
+ });
+ } catch (error) {
+ console.error("error refreshing meetings:", error);
+ toast({
+ title: "refresh failed",
+ description:
+ "failed to refresh speaker identification. please try again.",
+ variant: "destructive",
+ });
+ } finally {
+ setSpeakerSearchTerm("");
+ setSpeakerIdentified(false);
+ setSelectedExistingSpeaker(null);
+ }
+ };
+
+ const handleUpdateSpeakerName = async (newName: string) => {
+ // use the endpoint /speakers/update to update the name
+ try {
+ await fetch(`http://localhost:3030/speakers/update`, {
+ method: "POST",
+ body: JSON.stringify({
+ id: unnamedSpeakers[currentSpeakerIndex].id,
+ name: newName,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ setSpeakerIdentified(true);
+ } catch (error) {
+ console.error("error updating speaker name:", error);
+ toast({
+ title: "error",
+ description: "failed to update speaker name. please try again.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleRemoveSpeaker = async () => {
+ try {
+ await fetch(`http://localhost:3030/speakers/delete`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ id: unnamedSpeakers[currentSpeakerIndex].id,
+ }),
+ });
+
+ handleRefresh();
+ } catch (error) {
+ console.error("error removing speaker:", error);
+ toast({
+ title: "error",
+ description: "failed to remove speaker. please try again.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ const handleMergeSpeakers = async () => {
+ if (selectedExistingSpeaker) {
+ try {
+ // Add API call to merge speakers
+ await fetch(`http://localhost:3030/speakers/merge`, {
+ method: "POST",
+ body: JSON.stringify({
+ speaker_to_merge_id: unnamedSpeakers[currentSpeakerIndex].id,
+ speaker_to_keep_id: selectedExistingSpeaker.id,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+
+ toast({
+ title: "speakers merged",
+ description: "the speakers have been successfully merged",
+ });
+
+ if (selectedExistingSpeaker.name) {
+ setSpeakerIdentified(true);
+ setSpeakerSearchTerm(selectedExistingSpeaker.name);
+ }
+
+ setSimilarSpeakers(similarSpeakers.filter((s) => !s.name));
+
+ setUnnamedSpeakers(
+ unnamedSpeakers.map((s) => ({
+ ...s,
+ id:
+ s.id === unnamedSpeakers[currentSpeakerIndex].id
+ ? selectedExistingSpeaker.id
+ : s.id,
+ }))
+ );
+ } catch (error) {
+ console.error("error merging speakers:", error);
+ toast({
+ title: "error",
+ description: "failed to merge speakers. please try again.",
+ variant: "destructive",
+ });
+ }
+ }
+ setShowMergeConfirm(false);
+ };
+
+ const handleMarkSpeakerAsHallucination = async () => {
+ // use the endpoint /speakers/hallucination to mark the speaker as hallucination
+ try {
+ await fetch(`http://localhost:3030/speakers/hallucination`, {
+ method: "POST",
+ body: JSON.stringify({
+ speaker_id: unnamedSpeakers[currentSpeakerIndex].id,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
+ } catch (error) {
+ console.error("error ignoring speaker:", error);
+ toast({
+ title: "error",
+ description: "failed to ignore speaker. please try again.",
+ variant: "destructive",
+ });
+ }
+ };
+
+ // 4. Return null on first render to avoid hydration mismatch
+ if (!mounted) {
+ return null;
+ }
+
+ return segments ? (
+ <Dialog open={showIdentifySpeakers} onOpenChange={setShowIdentifySpeakers}>
+ <DialogTrigger asChild>
+ <Button
+ onClick={() => setShowIdentifySpeakers(true)}
+ size="sm"
+ className="text-xs bg-black text-white hover:bg-gray-800"
+ >
+ <Fingerprint className="mr-2 h-4 w-4" />
+ identify speakers
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="max-w-[90vw] w-full max-h-[90vh] h-full">
+ <DialogHeader className="py-4">
+ <DialogTitle className="flex items-center justify-between">
+ <div className="flex items-center">
+ identify speakers based on recent audio clips
+ <Badge variant="secondary" className="ml-2">
+ experimental
+ </Badge>
+ </div>
+ </DialogTitle>
+ </DialogHeader>
+ <div className="flex-grow overflow-auto min-h-[600px] flex flex-col">
+ {loading ? (
+ <div className="space-y-6 min-h-[600px]">
+ {[1, 2, 3].map((i) => (
+ <div key={i} className="p-4 border rounded animate-pulse">
+ <div className="h-6 bg-gray-200 rounded w-3/4 mb-4"></div>
+ <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
+ <div className="h-4 bg-gray-200 rounded w-1/4 mb-4"></div>
+ <div className="h-20 bg-gray-200 rounded mb-2"></div>
+ <div className="h-4 bg-gray-200 rounded w-1/3"></div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="min-h-[600px] flex flex-col">
+ {showError && error && (
+ <div
+ className="bg-gray-100 border-l-4 border-black text-gray-700 p-4 mb-4 flex justify-between items-center"
+ role="alert"
+ >
+ <div>
+ <p className="font-bold">warning</p>
+ <p>{error}</p>
+ </div>
+ <button
+ onClick={() => setShowError(false)}
+ className="text-gray-700 hover:text-black"
+ >
+ <X size={18} />
+ </button>
+ </div>
+ )}
+ {unnamedSpeakers.length === 0 && !loading && !error && (
+ <p className="text-center">no unnamed speakers found.</p>
+ )}
+
+ {unnamedSpeakers.length > 0 && (
+ <div className="mx-4">
+ <div className="p-4 border rounded h-full">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center space-x-2">
+ <span className="font-medium">identify speaker</span>
+ </div>
+ </div>
+ <form
+ className="space-y-4"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setShowNameUpdateConfirm(true);
+ await fetchSpeakers(speakerSearchTerm);
+ }}
+ >
+ <div className="flex items-center space-x-2">
+ <div className="relative flex-1 max-w-xs">
+ <Input
+ onFocus={() => {
+ setShowSpeakerNames(true);
+ }}
+ onBlur={(e) => {
+ // Add a small delay to allow the click event to fire first
+ setTimeout(() => {
+ setShowSpeakerNames(false);
+ }, 200);
+ }}
+ value={speakerSearchTerm}
+ name="speakerName"
+ onChange={(e) => {
+ const newValue = e.target.value;
+ setSpeakerSearchTerm(newValue);
+ // Only filter existing speakers if we have any
+ if (speakers.length > 0) {
+ setSpeakers(
+ speakers.filter((speaker) =>
+ speaker.name
+ .toLowerCase()
+ .includes(newValue.toLowerCase())
+ )
+ );
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === " " && !segments) {
+ setSpeakerSearchTerm(speakerSearchTerm + " ");
+ }
+ }}
+ placeholder="Enter speaker name"
+ className="w-full"
+ />
+ {speakerSearchTerm && (
+ <div className="absolute z-10 w-full mt-1 bg-white border rounded-md shadow-lg max-h-48 overflow-y-auto">
+ {isSearching ? (
+ <div className="flex justify-center items-center p-4">
+ <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
+ </div>
+ ) : (
+ showSpeakerNames && (
+ <ul className="py-1">
+ {speakers.map((speaker) => (
+ <li
+ key={speaker.id}
+ className="px-3 py-2 hover:bg-gray-100 cursor-pointer truncate"
+ onClick={(e) => {
+ setSpeakerSearchTerm(speaker.name);
+ setSelectedExistingSpeaker(speaker);
+ setShowMergeConfirm(true);
+ setShowSpeakerNames(false);
+ }}
+ >
+ {speaker.name}
+ </li>
+ ))}
+ </ul>
+ )
+ )}
+ </div>
+ )}
+ </div>
+ <Button
+ type="submit"
+ disabled={!speakerSearchTerm || speakerIdentified}
+ size="sm"
+ onClick={(e) => {
+ e.preventDefault();
+ setShowNameUpdateConfirm(true);
+ }}
+ >
+ <Save className="mr-2" />
+ update name
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={speakerIdentified}
+ onClick={async (e) => {
+ e.preventDefault();
+ setShowHallucinationConfirm(true);
+ }}
+ >
+ <Ghost className="mr-2" />
+ nobody is speaking
+ </Button>
+ <Button
+ type="button"
+ disabled={speakerIdentified}
+ variant="secondary"
+ onClick={async (e) => {
+ e.preventDefault();
+ setShowRemoveSpeakerConfirm(true);
+ }}
+ >
+ <Trash className="mr-2" />
+ remove speaker
+ </Button>
+ </div>
+ </form>
+
+ <div className="mt-4">
+ <p className="text-sm text-gray-500 mb-2">
+ audio samples:
+ </p>
+ <div className="grid grid-cols-3 gap-2">
+ {unnamedSpeakers[
+ currentSpeakerIndex
+ ].metadata?.audioSamples
+ .slice(0, 3)
+ .map((sample, index) => (
+ <VideoComponent
+ key={index}
+ filePath={sample.path}
+ customDescription={`transcript: ${sample.transcript}`}
+ />
+ ))}
+ </div>
+ </div>
+ {speakerIdentified && (
+ <div className="mt-4 flex justify-end">
+ <Button
+ onClick={() => {
+ handleRefresh();
+ }}
+ >
+ next speaker
+ <ChevronRight className="ml-2" />
+ </Button>
+ </div>
+ )}
+ <div className="mt-8">
+ {similarSpeakers.length > 0 && (
+ <p className="text-sm text-gray-500 mb-4">
+ is this the same speaker?
+ </p>
+ )}
+ {isFetchingSimilarSpeakers ? (
+ <div className="flex justify-center items-center p-4">
+ <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
+ </div>
+ ) : (
+ <div>
+ {similarSpeakers.map((speaker, index) => {
+ if (similarSpeakerIndex !== index) {
+ return null;
+ }
+ return (
+ <div
+ className="flex space-x-2 items-center"
+ key={speaker.id}
+ >
+ <span>{speaker.name || ""}</span>
+ {speaker.metadata?.audioSamples.map(
+ (sample) => (
+ <VideoComponent
+ key={sample.path}
+ filePath={sample.path}
+ customDescription={`transcript: ${sample.transcript}`}
+ className="max-w-[300px]"
+ />
+ )
+ )}
+ <Button
+ size="default"
+ variant="default"
+ onClick={() => {
+ setSelectedExistingSpeaker(speaker);
+ setShowMergeConfirm(true);
+ }}
+ >
+ <Check className="mr-2" />
+ same speaker
+ </Button>
+ <Button
+ size="default"
+ variant="outline"
+ onClick={() => {
+ const newSpeakers = similarSpeakers.filter(
+ (s) => s.id !== speaker.id
+ );
+ setSimilarSpeakers(newSpeakers);
+ setSimilarSpeakerIndex(
+ Math.max(
+ 0,
+ Math.min(
+ similarSpeakerIndex,
+ newSpeakers.length - 1
+ )
+ )
+ );
+ }}
+ >
+ <X className="mr-2" />
+ different speaker
+ </Button>
+ <Button
+ size="default"
+ className={
+ similarSpeakers.length === 1 ? "hidden" : ""
+ }
+ variant="secondary"
+ onClick={() => {
+ setSimilarSpeakerIndex(
+ (index + 1) % similarSpeakers.length
+ );
+ }}
+ >
+ skip
+ <ChevronRight className="ml-2" />
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </DialogContent>
+ <Dialog
+ open={showHallucinationConfirm}
+ onOpenChange={setShowHallucinationConfirm}
+ >
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>confirm</DialogTitle>
+ <DialogDescription>
+ are you sure you nobody is speaking? this action cannot be undone.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex justify-end space-x-2">
+ <Button
+ variant="outline"
+ onClick={() => setShowHallucinationConfirm(false)}
+ >
+ cancel
+ </Button>
+ <Button
+ variant="default"
+ onClick={async () => {
+ await handleMarkSpeakerAsHallucination();
+ setShowHallucinationConfirm(false);
+ toast({
+ title: "speaker ignored",
+ description:
+ "This speaker will be ignored in future processing",
+ });
+ setSpeakerIdentified(true);
+ }}
+ >
+ confirm
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog
+ open={showNameUpdateConfirm}
+ onOpenChange={setShowNameUpdateConfirm}
+ >
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>confirm name update</DialogTitle>
+ <DialogDescription>
+ are you sure you want to update this speaker&apos;s name to &quot;
+ {speakerSearchTerm}
+ &quot;?
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex justify-end space-x-2">
+ <Button
+ variant="ghost"
+ onClick={() => setShowNameUpdateConfirm(false)}
+ >
+ cancel
+ </Button>
+ <Button
+ onClick={async () => {
+ await handleUpdateSpeakerName(speakerSearchTerm);
+ setShowNameUpdateConfirm(false);
+ toast({
+ title: "speaker renamed",
+ description: "the speaker name has been updated",
+ });
+ }}
+ >
+ confirm
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog open={showMergeConfirm} onOpenChange={setShowMergeConfirm}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>merge speakers</DialogTitle>
+ {selectedExistingSpeaker?.name ? (
+ <DialogDescription>
+ do you want to merge this speaker with existing speaker
+ {` "${selectedExistingSpeaker?.name}"`}? this will combine their
+ audio samples and future recordings.
+ </DialogDescription>
+ ) : (
+ <DialogDescription>
+ do you want to merge this speaker? this will combine their audio
+ samples and future recordings.
+ </DialogDescription>
+ )}
+ </DialogHeader>
+ <div className="flex justify-end space-x-2">
+ <Button variant="ghost" onClick={() => setShowMergeConfirm(false)}>
+ cancel
+ </Button>
+ {selectedExistingSpeaker?.name && (
+ <Button
+ variant="outline"
+ onClick={() => {
+ setShowMergeConfirm(false);
+ // Still update the name without merging
+ handleUpdateSpeakerName(selectedExistingSpeaker?.name || "");
+ toast({
+ title: "speaker renamed",
+ description:
+ "the speaker name has been updated without merging",
+ });
+ }}
+ >
+ just update name
+ </Button>
+ )}
+
+ <Button onClick={handleMergeSpeakers}>merge speakers</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog
+ open={showRemoveSpeakerConfirm}
+ onOpenChange={setShowRemoveSpeakerConfirm}
+ >
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>confirm remove speaker</DialogTitle>
+ <DialogDescription>
+ are you sure you want to remove this speaker? this action cannot
+ be undone.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex justify-end space-x-2">
+ <Button
+ variant="outline"
+ onClick={() => setShowRemoveSpeakerConfirm(false)}
+ >
+ cancel
+ </Button>
+ <Button
+ onClick={async () => {
+ await handleRemoveSpeaker();
+ setShowRemoveSpeakerConfirm(false);
+ toast({
+ title: "speaker removed",
+ description: "the speaker has been removed",
+ });
+ }}
+ >
+ confirm
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </Dialog>
+ ) : (
+ <Card>
+ <CardHeader>
+ <CardTitle>identify speakers</CardTitle>
+ <CardDescription>
+ identify speakers based on recent audio clips
+ <Badge variant="secondary" className="ml-2">
+ experimental
+ </Badge>
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="max-w-[90vw] w-full max-h-[90vh] h-full">
+ <div className="flex-grow overflow-auto min-h-[600px] flex flex-col">
+ {loading ? (
+ <div className="space-y-6 min-h-[600px]">
+ {[1, 2, 3].map((i) => (
+ <div key={i} className="p-4 border rounded animate-pulse">
+ <div className="h-6 bg-gray-200 rounded w-3/4 mb-4"></div>
+ <div className="h-4 bg-gray-200 rounded w-1/2 mb-2"></div>
+ <div className="h-4 bg-gray-200 rounded w-1/4 mb-4"></div>
+ <div className="h-20 bg-gray-200 rounded mb-2"></div>
+ <div className="h-4 bg-gray-200 rounded w-1/3"></div>
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="min-h-[600px] flex flex-col">
+ {showError && error && (
+ <div
+ className="bg-gray-100 border-l-4 border-black text-gray-700 p-4 mb-4 flex justify-between items-center"
+ role="alert"
+ >
+ <div>
+ <p className="font-bold">warning</p>
+ <p>{error}</p>
+ </div>
+ <button
+ onClick={() => setShowError(false)}
+ className="text-gray-700 hover:text-black"
+ >
+ <X size={18} />
+ </button>
+ </div>
+ )}
+ {unnamedSpeakers.length === 0 && !loading && !error && (
+ <p className="text-center">no unnamed speakers found.</p>
+ )}
+
+ {unnamedSpeakers.length > 0 && (
+ <div className="mx-4">
+ <div className="p-4 border rounded h-full">
+ <div className="flex items-center justify-between mb-4">
+ <div className="flex items-center space-x-2">
+ <span className="font-medium">identify speaker</span>
+ </div>
+ </div>
+ <form
+ className="space-y-4"
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setShowNameUpdateConfirm(true);
+ await fetchSpeakers(speakerSearchTerm);
+ }}
+ >
+ <div className="flex items-center space-x-2">
+ <div className="relative flex-1 max-w-xs">
+ <Input
+ onFocus={() => {
+ setShowSpeakerNames(true);
+ }}
+ onBlur={(e) => {
+ // Add a small delay to allow the click event to fire first
+ setTimeout(() => {
+ setShowSpeakerNames(false);
+ }, 200);
+ }}
+ value={speakerSearchTerm}
+ name="speakerName"
+ onChange={(e) => {
+ const newValue = e.target.value;
+ setSpeakerSearchTerm(newValue);
+ // Only filter existing speakers if we have any
+ if (speakers.length > 0) {
+ setSpeakers(
+ speakers.filter((speaker) =>
+ speaker.name
+ .toLowerCase()
+ .includes(newValue.toLowerCase())
+ )
+ );
+ }
+ }}
+ onKeyDown={(e) => {
+ if (e.key === " " && !segments) {
+ setSpeakerSearchTerm(speakerSearchTerm + " ");
+ }
+ }}
+ placeholder="Enter speaker name"
+ className="w-full"
+ />
+ {speakerSearchTerm && (
+ <div className="absolute z-10 w-full mt-1 bg-white border rounded-md shadow-lg max-h-48 overflow-y-auto">
+ {isSearching ? (
+ <div className="flex justify-center items-center p-4">
+ <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
+ </div>
+ ) : (
+ showSpeakerNames && (
+ <ul className="py-1">
+ {speakers.map((speaker) => (
+ <li
+ key={speaker.id}
+ className="px-3 py-2 hover:bg-gray-100 cursor-pointer truncate"
+ onClick={(e) => {
+ setSpeakerSearchTerm(speaker.name);
+ setSelectedExistingSpeaker(speaker);
+ setShowMergeConfirm(true);
+ setShowSpeakerNames(false);
+ }}
+ >
+ {speaker.name}
+ </li>
+ ))}
+ </ul>
+ )
+ )}
+ </div>
+ )}
+ </div>
+ <Button
+ type="submit"
+ disabled={!speakerSearchTerm || speakerIdentified}
+ size="sm"
+ onClick={(e) => {
+ e.preventDefault();
+ setShowNameUpdateConfirm(true);
+ }}
+ >
+ <Save className="mr-2" />
+ update name
+ </Button>
+ <Button
+ type="button"
+ variant="outline"
+ disabled={speakerIdentified}
+ onClick={async (e) => {
+ e.preventDefault();
+ setShowHallucinationConfirm(true);
+ }}
+ >
+ <Ghost className="mr-2" />
+ nobody is speaking
+ </Button>
+ <Button
+ type="button"
+ disabled={speakerIdentified}
+ variant="secondary"
+ onClick={async (e) => {
+ e.preventDefault();
+ setShowRemoveSpeakerConfirm(true);
+ }}
+ >
+ <Trash className="mr-2" />
+ remove speaker
+ </Button>
+ </div>
+ </form>
+
+ <div className="mt-4">
+ <p className="text-sm text-gray-500 mb-2">
+ audio samples:
+ </p>
+ <div className="grid grid-cols-3 gap-2">
+ {unnamedSpeakers[
+ currentSpeakerIndex
+ ].metadata?.audioSamples
+ .slice(0, 3)
+ .map((sample, index) => (
+ <VideoComponent
+ key={index}
+ filePath={sample.path}
+ customDescription={`transcript: ${sample.transcript}`}
+ />
+ ))}
+ </div>
+ </div>
+ {speakerIdentified && (
+ <div className="mt-4 flex justify-end">
+ <Button
+ onClick={() => {
+ handleRefresh();
+ }}
+ >
+ next speaker
+ <ChevronRight className="ml-2" />
+ </Button>
+ </div>
+ )}
+ <div className="mt-8">
+ {similarSpeakers.length > 0 && (
+ <p className="text-sm text-gray-500 mb-4">
+ is this the same speaker?
+ </p>
+ )}
+ {isFetchingSimilarSpeakers ? (
+ <div className="flex justify-center items-center p-4">
+ <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-gray-900"></div>
+ </div>
+ ) : (
+ <div>
+ {similarSpeakers.map((speaker, index) => {
+ if (similarSpeakerIndex !== index) {
+ return null;
+ }
+ return (
+ <div
+ className="flex space-x-2 items-center"
+ key={speaker.id}
+ >
+ <span>{speaker.name || ""}</span>
+ {speaker.metadata?.audioSamples.map(
+ (sample) => (
+ <VideoComponent
+ key={sample.path}
+ filePath={sample.path}
+ customDescription={`transcript: ${sample.transcript}`}
+ className="max-w-[300px]"
+ />
+ )
+ )}
+ <Button
+ size="default"
+ variant="default"
+ onClick={() => {
+ setSelectedExistingSpeaker(speaker);
+ setShowMergeConfirm(true);
+ }}
+ >
+ <Check className="mr-2" />
+ same speaker
+ </Button>
+ <Button
+ size="default"
+ variant="outline"
+ onClick={() => {
+ const newSpeakers = similarSpeakers.filter(
+ (s) => s.id !== speaker.id
+ );
+ setSimilarSpeakers(newSpeakers);
+ setSimilarSpeakerIndex(
+ Math.max(
+ 0,
+ Math.min(
+ similarSpeakerIndex,
+ newSpeakers.length - 1
+ )
+ )
+ );
+ }}
+ >
+ <X className="mr-2" />
+ different speaker
+ </Button>
+ <Button
+ size="default"
+ className={
+ similarSpeakers.length === 1 ? "hidden" : ""
+ }
+ variant="secondary"
+ onClick={() => {
+ setSimilarSpeakerIndex(
+ (index + 1) % similarSpeakers.length
+ );
+ }}
+ >
+ skip
+ <ChevronRight className="ml-2" />
+ </Button>
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </CardContent>
+ <Dialog
+ open={showHallucinationConfirm}
+ onOpenChange={setShowHallucinationConfirm}
+ >
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>confirm</DialogTitle>
+ <DialogDescription>
+ are you sure you nobody is speaking? this action cannot be undone.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex justify-end space-x-2">
+ <Button
+ variant="outline"
+ onClick={() => setShowHallucinationConfirm(false)}
+ >
+ cancel
+ </Button>
+ <Button
+ variant="default"
+ onClick={async () => {
+ await handleMarkSpeakerAsHallucination();
+ setShowHallucinationConfirm(false);
+ toast({
+ title: "speaker ignored",
+ description:
+ "This speaker will be ignored in future processing",
+ });
+ setSpeakerIdentified(true);
+ }}
+ >
+ confirm
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog
+ open={showNameUpdateConfirm}
+ onOpenChange={setShowNameUpdateConfirm}
+ >
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>confirm name update</DialogTitle>
+ <DialogDescription>
+ are you sure you want to update this speaker&apos;s name to &quot;
+ {speakerSearchTerm}
+ &quot;?
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex justify-end space-x-2">
+ <Button
+ variant="ghost"
+ onClick={() => setShowNameUpdateConfirm(false)}
+ >
+ cancel
+ </Button>
+ <Button
+ onClick={async () => {
+ await handleUpdateSpeakerName(speakerSearchTerm);
+ setShowNameUpdateConfirm(false);
+ toast({
+ title: "speaker renamed",
+ description: "the speaker name has been updated",
+ });
+ }}
+ >
+ confirm
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog open={showMergeConfirm} onOpenChange={setShowMergeConfirm}>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>merge speakers</DialogTitle>
+ {selectedExistingSpeaker?.name ? (
+ <DialogDescription>
+ do you want to merge this speaker with existing speaker
+ {` "${selectedExistingSpeaker?.name}"`}? this will combine their
+ audio samples and future recordings.
+ </DialogDescription>
+ ) : (
+ <DialogDescription>
+ do you want to merge this speaker? this will combine their audio
+ samples and future recordings.
+ </DialogDescription>
+ )}
+ </DialogHeader>
+ <div className="flex justify-end space-x-2">
+ <Button variant="ghost" onClick={() => setShowMergeConfirm(false)}>
+ cancel
+ </Button>
+ {selectedExistingSpeaker?.name && (
+ <Button
+ variant="outline"
+ onClick={() => {
+ setShowMergeConfirm(false);
+ // Still update the name without merging
+ handleUpdateSpeakerName(selectedExistingSpeaker?.name || "");
+ toast({
+ title: "speaker renamed",
+ description:
+ "the speaker name has been updated without merging",
+ });
+ }}
+ >
+ just update name
+ </Button>
+ )}
+
+ <Button onClick={handleMergeSpeakers}>merge speakers</Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ <Dialog
+ open={showRemoveSpeakerConfirm}
+ onOpenChange={setShowRemoveSpeakerConfirm}
+ >
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader>
+ <DialogTitle>confirm remove speaker</DialogTitle>
+ <DialogDescription>
+ are you sure you want to remove this speaker? this action cannot
+ be undone.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="flex justify-end space-x-2">
+ <Button
+ variant="outline"
+ onClick={() => setShowRemoveSpeakerConfirm(false)}
+ >
+ cancel
+ </Button>
+ <Button
+ onClick={async () => {
+ await handleRemoveSpeaker();
+ setShowRemoveSpeakerConfirm(false);
+ toast({
+ title: "speaker removed",
+ description: "the speaker has been removed",
+ });
+ }}
+ >
+ confirm
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </Card>
+ );
+}
diff --git a/screenpipe-app-tauri/components/meeting-history.tsx b/screenpipe-app-tauri/components/meeting-history.tsx
index b9063e2cc..ee8cdf1dc 100644
--- a/screenpipe-app-tauri/components/meeting-history.tsx
+++ b/screenpipe-app-tauri/components/meeting-history.tsx
@@ -1,3 +1,5 @@
+"use client";
+
import React, { useState, useEffect, useCallback, useMemo } from "react";
import { Button } from "@/components/ui/button";
import {
@@ -36,7 +38,7 @@ import {
} from "@/components/ui/tooltip";
import { Input } from "./ui/input";
import { Textarea } from "./ui/textarea";
-import { keysToCamelCase } from "@/lib/utils";
+import { cn, keysToCamelCase } from "@/lib/utils";
import { HelpCircle } from "lucide-react";
import {
Card,
@@ -49,6 +51,7 @@ import { ValueOf } from "next/dist/shared/lib/constants";
import { Checkbox } from "./ui/checkbox";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { DropdownMenuItem } from "./ui/dropdown-menu";
+import IdentifySpeakers from "./identify-speakers";
function formatDate(date: string): string {
const dateObj = new Date(date);
@@ -92,6 +95,7 @@ interface MeetingSegment {
transcription: string;
deviceName: string;
deviceType: string;
+ speaker: Speaker;
}
interface Meeting {
@@ -108,6 +112,11 @@ interface Meeting {
segments: MeetingSegment[];
}
+interface Speaker {
+ id: number;
+ name: string;
+}
+
interface AudioContent {
chunkId: number;
transcription: string;
@@ -117,6 +126,7 @@ interface AudioContent {
tags: string[];
deviceName: string;
deviceType: string;
+ speaker: Speaker;
}
interface AudioTranscription {
@@ -124,13 +134,20 @@ interface AudioTranscription {
content: AudioContent;
}
-export default function MeetingHistory({ className }: { className?: string }) {
+export default function MeetingHistory({
+ showMeetingHistory,
+ setShowMeetingHistory,
+ className,
+}: {
+ showMeetingHistory: boolean;
+ setShowMeetingHistory: (show: boolean) => void;
+ className?: string;
+}) {
const posthog = usePostHog();
const { settings } = useSettings();
const [meetings, setMeetings] = useState<Meeting[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
- const [isOpen, setIsOpen] = useState(false);
const [isSummarizing, setIsSummarizing] = useState(false);
const [isIdentifying, setIsIdentifying] = useState(false);
const { toast } = useToast();
@@ -144,6 +161,17 @@ export default function MeetingHistory({ className }: { className?: string }) {
const [customIdentifyPrompt, setCustomIdentifyPrompt] = useState<string>(
"please identify the participants in this meeting transcript. provide a comma-separated list of one or two word names or roles or characteristics. if it's not possible to identify, respond with n/a."
);
+ const [openIdentifyDialogs, setOpenIdentifyDialogs] = useState<{
+ [key: number]: boolean;
+ }>({});
+
+ // Add this function to handle individual dialog states
+ const handleIdentifyDialog = (meetingGroup: number, isOpen: boolean) => {
+ setOpenIdentifyDialogs((prev) => ({
+ ...prev,
+ [meetingGroup]: isOpen,
+ }));
+ };
const { health } = useHealthCheck();
useEffect(() => {
@@ -153,21 +181,21 @@ export default function MeetingHistory({ className }: { className?: string }) {
}, [posthog, settings.userId]);
useEffect(() => {
- if (isOpen) {
+ if (showMeetingHistory) {
loadMeetings();
posthog?.capture("meeting_history_opened", {
userId: settings.userId,
});
}
- }, [isOpen]);
+ }, [showMeetingHistory]);
useEffect(() => {
setShowError(!!error);
}, [error]);
useEffect(() => {
- console.log("Dialog state changed:", isOpen);
- }, [isOpen]);
+ console.log("Dialog state changed:", showMeetingHistory);
+ }, [showMeetingHistory]);
async function loadMeetings() {
setLoading(true);
@@ -365,70 +393,6 @@ export default function MeetingHistory({ className }: { className?: string }) {
}
}
- async function identifyParticipants(meeting: Meeting) {
- setIsIdentifying(true);
- posthog?.capture("participant_identification_started", {
- userId: settings.userId,
- meetingId: meeting.meetingGroup,
- });
- try {
- const openai = new OpenAI({
- apiKey: settings.openaiApiKey,
- baseURL: settings.aiUrl,
- dangerouslyAllowBrowser: true,
- });
-
- const model = settings.aiModel;
-
- const messages = [
- {
- role: "system" as const,
- content: `you are an assistant that identifies participants in meeting transcripts. your goal is to provide a list of one or two or more word names or roles or characteristics.
-
- for example your rsponse could be:
- Bob Smith (marketing), John Doe (sales), Jane Smith (ceo)
- `,
- },
- {
- role: "user" as const,
- content: `${customIdentifyPrompt}\n\ntranscript with device types:\n\n${meeting.fullTranscription}`,
- },
- ];
-
- const response = await openai.chat.completions.create({
- model: model,
- messages: messages,
- });
-
- const participants =
- response.choices[0]?.message?.content || "no participants identified.";
-
- // Update the meeting with the identified participants
- const updatedMeeting = { ...meeting, participants };
- const updatedMeetings = meetings.map((m) =>
- m.meetingGroup === meeting.meetingGroup ? updatedMeeting : m
- );
- setMeetings(updatedMeetings);
- await setItem("meetings", updatedMeetings);
-
- toast({
- title: "participants identified",
- description:
- "the meeting participants have been identified successfully.",
- });
- } catch (error) {
- console.error("error identifying participants:", error);
- toast({
- title: "error",
- description:
- "failed to identify meeting participants. please try again.",
- variant: "destructive",
- });
- } finally {
- setIsIdentifying(false);
- }
- }
-
function formatTimestamp(timestamp: string): string {
const date = new Date(timestamp);
return new Intl.DateTimeFormat("en-US", {
@@ -462,6 +426,16 @@ export default function MeetingHistory({ className }: { className?: string }) {
? new Date(transcriptions[index - 1].content.timestamp)
: null;
+ // Get speaker name based on speaker info or device type
+ const speakerName =
+ trans.content.speaker?.name && trans.content.speaker.name.length > 0
+ ? trans.content.speaker.name
+ : trans.content.deviceType?.toLowerCase() === "input"
+ ? "you"
+ : trans.content.deviceType?.toLowerCase() === "output"
+ ? "others"
+ : "unknown";
+
if (
!currentMeeting ||
(prevTime &&
@@ -475,13 +449,9 @@ export default function MeetingHistory({ className }: { className?: string }) {
meetingGroup: meetingGroup,
meetingStart: trans.content.timestamp,
meetingEnd: trans.content.timestamp,
- fullTranscription: `${formatTimestamp(trans.content.timestamp)} [${
- trans.content.deviceType?.toLowerCase() === "input"
- ? "you"
- : trans.content.deviceType?.toLowerCase() === "output"
- ? "others"
- : "unknown"
- }] ${trans.content.transcription}\n`,
+ fullTranscription: `${formatTimestamp(
+ trans.content.timestamp
+ )} [${speakerName}] ${trans.content.transcription}\n`,
name: null,
participants: null,
summary: null,
@@ -492,25 +462,29 @@ export default function MeetingHistory({ className }: { className?: string }) {
transcription: trans.content.transcription,
deviceName: trans.content.deviceName,
deviceType: trans.content.deviceType,
+ speaker: trans.content.speaker || {
+ id: -1,
+ name: speakerName,
+ },
},
],
deviceNames: new Set([trans.content.deviceName]),
};
} else if (currentMeeting) {
currentMeeting.meetingEnd = trans.content.timestamp;
- currentMeeting.fullTranscription += `${trans.content.timestamp} [${
- trans.content.deviceType?.toLowerCase() === "input"
- ? "you"
- : trans.content.deviceType?.toLowerCase() === "output"
- ? "others"
- : "unknown"
- }] ${trans.content.transcription}\n`;
+ currentMeeting.fullTranscription += `${formatTimestamp(
+ trans.content.timestamp
+ )} [${speakerName}] ${trans.content.transcription}\n`;
currentMeeting.selectedDevices.add(trans.content.deviceName);
currentMeeting.segments.push({
timestamp: trans.content.timestamp,
transcription: trans.content.transcription,
deviceName: trans.content.deviceName,
deviceType: trans.content.deviceType,
+ speaker: trans.content.speaker || {
+ id: -1,
+ name: speakerName,
+ },
});
currentMeeting.deviceNames.add(trans.content.deviceName);
}
@@ -661,29 +635,15 @@ export default function MeetingHistory({ className }: { className?: string }) {
);
return (
- <Dialog open={isOpen} onOpenChange={setIsOpen}>
- <DialogTrigger asChild>
- <DropdownMenuItem
- className="cursor-pointer"
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setIsOpen(true);
- }}
- disabled={!health || health.status === "error"}
- >
- <Calendar className="mr-2 h-4 w-4" />
- <span>meetings</span>
- </DropdownMenuItem>
- </DialogTrigger>
- <DialogContent
- className="max-w-[90vw] w-full max-h-[90vh] h-full"
+ <Card>
+ <CardContent
+ className="h-full"
onClick={(e) => {
e.stopPropagation();
}}
>
- <DialogHeader className="py-4">
- <DialogTitle className="flex items-center justify-between">
+ <CardHeader className="py-4">
+ <CardTitle className="flex items-center justify-between">
<div className="flex items-center">
meeting and conversation history
<Badge variant="secondary" className="ml-2">
@@ -744,9 +704,9 @@ export default function MeetingHistory({ className }: { className?: string }) {
</Tooltip>
</TooltipProvider>
</div>
- </DialogTitle>
- </DialogHeader>
- <DialogDescription className="mb-4">
+ </CardTitle>
+ </CardHeader>
+ <CardDescription className="mb-4">
<span className="block text-sm text-gray-600">
this page provides transcriptions and summaries of your daily
meetings. it uses your ai settings to generate summaries. note:
@@ -757,7 +717,7 @@ export default function MeetingHistory({ className }: { className?: string }) {
<span className="block text-sm text-gray-600 mt-2">
<strong>make sure to setup your ai settings</strong>
</span>
- </DialogDescription>
+ </CardDescription>
<div className="flex-grow overflow-auto">
{loading ? (
<div className="space-y-6">
@@ -854,56 +814,40 @@ export default function MeetingHistory({ className }: { className?: string }) {
</div>
</CardHeader>
<CardContent>
- <div className="mb-4">
- <div className="flex flex-col space-y-2">
- <div className="flex items-center justify-end mb-1">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <HelpCircle className="h-5 w-5 cursor-help text-gray-500" />
- </TooltipTrigger>
- <TooltipContent side="top" align="end">
- <p className="max-w-xs">
- best practice for identification is to say
- &quot;person talking about x, y, z, is
- john ...&quot; this helps the ai to link
- topics to specific individuals, improving
- accuracy in participant identification.
- </p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <Textarea
- rows={2}
- value={customIdentifyPrompt}
- onChange={(e) =>
- setCustomIdentifyPrompt(e.target.value)
- }
- placeholder="custom identify prompt (optional)"
- className="resize-none border rounded text-sm w-full"
- />
- <div className="flex items-center justify-between">
- <p>
- participants:{" "}
- {meeting.participants || "not identified"}
- </p>
- <Button
- onClick={() => identifyParticipants(meeting)}
- disabled={isIdentifying}
- size="sm"
- className="text-xs bg-black text-white hover:bg-gray-800"
- >
- {isIdentifying ? (
- <Users className="h-4 w-4 mr-2 animate-pulse" />
- ) : (
- <Users className="h-4 w-4 mr-2" />
- )}
- {isIdentifying ? "identifying..." : "identify"}
- </Button>
+ {!meeting.segments.every((s) => s.speaker.name) && (
+ <div className="mb-4">
+ <div className="flex flex-col space-y-2">
+ <div className="flex items-center justify-end mb-1">
+ <TooltipProvider>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <HelpCircle className="h-5 w-5 cursor-help text-gray-500" />
+ </TooltipTrigger>
+ <TooltipContent side="top" align="end">
+ <p className="max-w-xs">
+ identify speakers in your meetings
+ </p>
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ <div className="flex items-center justify-end">
+ <IdentifySpeakers
+ showIdentifySpeakers={
+ openIdentifyDialogs[meeting.meetingGroup]
+ }
+ setShowIdentifySpeakers={(isOpen) =>
+ handleIdentifyDialog(
+ meeting.meetingGroup,
+ isOpen
+ )
+ }
+ segments={meeting.segments}
+ />
+ </div>
</div>
</div>
- </div>
+ )}
<div className="mb-4 relative">
<h4 className="font-semibold mb-2">transcription:</h4>
<Button
@@ -915,7 +859,10 @@ export default function MeetingHistory({ className }: { className?: string }) {
)
.map((s) => {
return `${formatTimestamp(s.timestamp)} [${
- s.deviceType?.toLowerCase() === "input"
+ s.speaker
+ ? s.speaker.name
+ : s.deviceType?.toLowerCase() ===
+ "input"
? "you"
: "others"
}] ${s.transcription}`;
@@ -944,7 +891,10 @@ export default function MeetingHistory({ className }: { className?: string }) {
<React.Fragment key={i}>
<span className="font-bold">
{`${formatTimestamp(s.timestamp)} [${
- s.deviceType?.toLowerCase() === "input"
+ s.speaker
+ ? s.speaker.name
+ : s.deviceType?.toLowerCase() ===
+ "input"
? "you"
: "others"
}]`}
@@ -1021,7 +971,7 @@ export default function MeetingHistory({ className }: { className?: string }) {
</>
)}
</div>
- </DialogContent>
- </Dialog>
+ </CardContent>
+ </Card>
);
}
diff --git a/screenpipe-app-tauri/components/search-chat.tsx b/screenpipe-app-tauri/components/search-chat.tsx
index 0a6b11d21..205fbb313 100644
--- a/screenpipe-app-tauri/components/search-chat.tsx
+++ b/screenpipe-app-tauri/components/search-chat.tsx
@@ -34,6 +34,8 @@ import {
Clock,
Check,
Plus,
+ SpeechIcon,
+ ChevronsUpDown,
} from "lucide-react";
import { useToast } from "./ui/use-toast";
import posthog from "posthog-js";
@@ -71,12 +73,22 @@ import { Checkbox } from "@/components/ui/checkbox";
import { IconCode } from "@/components/ui/icons";
import { CodeBlock } from "./ui/codeblock";
import { SqlAutocompleteInput } from "./sql-autocomplete-input";
-import { encode, removeDuplicateSelections } from "@/lib/utils";
+import { cn, encode, removeDuplicateSelections } from "@/lib/utils";
import { ExampleSearch, ExampleSearchCards } from "./example-search-cards";
import { useDebounce } from "@/lib/hooks/use-debounce";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
import { SearchHistory } from "@/lib/types/history";
import { platform } from "@tauri-apps/plugin-os";
+import {
+ CommandInput,
+ CommandList,
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ Command,
+} from "./ui/command";
+import { Speaker } from "@/lib/types";
+import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";
interface SearchChatProps {
currentSearchId: string | null;
@@ -224,7 +236,11 @@ export function SearchChat({
const [isAiLoading, setIsAiLoading] = useState(false);
const [minLength, setMinLength] = useState(50);
const [maxLength, setMaxLength] = useState(10000);
-
+ const [speakers, setSpeakers] = useState<Speaker[]>([]);
+ const [selectedSpeakers, setSelectedSpeakers] = useState<{
+ [key: number]: Speaker;
+ }>({});
+ const [openSpeakers, setOpenSpeakers] = useState(false);
// Chat state
const [chatMessages, setChatMessages] = useState<Array<Message>>([]);
@@ -276,10 +292,47 @@ export function SearchChat({
const [currentPlatform, setCurrentPlatform] = useState<string | null>(null);
+ const [speakerSearchQuery, setSpeakerSearchQuery] = useState("");
+
useEffect(() => {
setCurrentPlatform(platform());
}, []);
+ const handleSpeakerChange = (speaker: Speaker) => {
+ setSelectedSpeakers((prev) => {
+ const newSpeakers = { ...prev, [speaker.id]: speaker };
+
+ if (prev[speaker.id]) {
+ delete newSpeakers[speaker.id];
+ }
+
+ return newSpeakers;
+ });
+ };
+
+ useEffect(() => {
+ if (isQueryParamsDialogOpen && !speakers.length) {
+ loadSpeakers();
+ }
+ }, [isQueryParamsDialogOpen]);
+
+ useEffect(() => {
+ loadSpeakers();
+ }, [speakerSearchQuery]);
+
+ const loadSpeakers = async () => {
+ try {
+ const getSpeakers = await fetch(
+ `http://localhost:3030/speakers/search?name=${speakerSearchQuery}`
+ );
+ const speakers = await getSpeakers.json();
+ setSpeakers(speakers);
+ } catch (error) {
+ console.error("Error loading speakers:", error);
+ setSpeakers([]);
+ }
+ };
+
// Update content type when checkboxes change
const handleContentTypeChange = (type: "ocr" | "audio" | "ui") => {
const newTypes = { ...selectedTypes, [type]: !selectedTypes[type] };
@@ -669,6 +722,10 @@ export function SearchChat({
end_time: endDate.toISOString(),
min_length: overrides.minLength || minLength,
max_length: maxLength,
+ speaker_ids:
+ Object.keys(selectedSpeakers).length > 0
+ ? Object.keys(selectedSpeakers).length
+ : undefined,
});
try {
@@ -685,6 +742,10 @@ export function SearchChat({
include_frames: includeFrames,
min_length: overrides.minLength || minLength,
max_length: maxLength,
+ speaker_ids:
+ Object.keys(selectedSpeakers).length > 0
+ ? Object.keys(selectedSpeakers).join(",")
+ : undefined,
};
const response = await queryScreenpipe(searchParams);
@@ -955,6 +1016,11 @@ export function SearchChat({
{new Date(item.content.timestamp).toLocaleString()}{" "}
{/* Display local time */}
</p>
+ {item.type === "Audio" && item.content.speaker?.name && (
+ <p className="text-xs text-gray-400">
+ {item.content.speaker.name}
+ </p>
+ )}
{item.type === "OCR" && item.content.app_name && (
<div className="flex items-center gap-1">
<span className="text-xs text-muted-foreground">app:</span>
@@ -1461,6 +1527,71 @@ export function SearchChat({
</Tooltip>
</TooltipProvider>
</div>
+ <div className="flex items-center justify-center space-x-2">
+ <Label htmlFor="speakers" className="flex items-center space-x-2">
+ <SpeechIcon className="h-4 w-4" />
+ <span>speakers</span>
+ </Label>
+ <Popover open={openSpeakers} onOpenChange={setOpenSpeakers}>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ role="combobox"
+ aria-expanded={openSpeakers}
+ className="w-full justify-between"
+ >
+ {Object.values(selectedSpeakers).length > 0
+ ? `${Object.values(selectedSpeakers)
+ .map((s) => s.name)
+ .join(", ")}`
+ : "select speakers"}
+ <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-full p-0">
+ <Command>
+ <CommandInput
+ placeholder="search speakers..."
+ value={speakerSearchQuery}
+ onValueChange={setSpeakerSearchQuery}
+ />
+ <CommandList>
+ <CommandEmpty>no speakers found.</CommandEmpty>
+ <CommandGroup>
+ {speakers.map((speaker: Speaker) => (
+ <CommandItem
+ key={speaker.id}
+ value={speaker.name}
+ onSelect={() => handleSpeakerChange(speaker)}
+ >
+ <div className="flex items-center">
+ <Check
+ className={cn(
+ "mr-2 h-4 w-4",
+ selectedSpeakers[speaker.id]
+ ? "opacity-100"
+ : "opacity-0"
+ )}
+ />
+ <span
+ style={{
+ userSelect: "none",
+ WebkitUserSelect: "none",
+ MozUserSelect: "none",
+ msUserSelect: "none",
+ }}
+ >
+ {speaker.name}
+ </span>
+ </div>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ </div>
<DialogFooter>
<Button onClick={() => setIsQueryParamsDialogOpen(false)}>
done
diff --git a/screenpipe-app-tauri/components/settings.tsx b/screenpipe-app-tauri/components/settings.tsx
index 701bb62b0..34a9dcd2c 100644
--- a/screenpipe-app-tauri/components/settings.tsx
+++ b/screenpipe-app-tauri/components/settings.tsx
@@ -33,7 +33,7 @@ import {
import { Textarea } from "./ui/textarea";
import { Slider } from "@/components/ui/slider"; // Add this import
import { Badge } from "@/components/ui/badge"; // Add this import
-import { parseKeyboardShortcut } from "@/lib/utils"; // Add this import
+import { cn, parseKeyboardShortcut } from "@/lib/utils"; // Add this import
import {
Eye,
@@ -64,7 +64,6 @@ import {
} from "@/components/ui/select";
import { useInterval } from "@/lib/hooks/use-interval";
import { useHealthCheck } from "@/lib/hooks/use-health-check";
-import { DropdownMenuItem } from "./ui/dropdown-menu";
export function Settings({ className }: { className?: string }) {
const {
@@ -528,15 +527,18 @@ export function Settings({ className }: { className?: string }) {
}}
>
<DialogTrigger asChild>
- <DropdownMenuItem
- className="cursor-pointer"
+ <div
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className
+ )}
onSelect={(e) => e.preventDefault()}
>
<div className="flex items-center">
<Settings2 className="mr-2 h-4 w-4" />
<span>settings</span>
</div>
- </DropdownMenuItem>
+ </div>
</DialogTrigger>
<DialogContent className="max-w-[80vw] w-full max-h-[80vh] h-full overflow-y-auto">
diff --git a/screenpipe-app-tauri/components/video.tsx b/screenpipe-app-tauri/components/video.tsx
index 748595dc6..3fcd9af80 100644
--- a/screenpipe-app-tauri/components/video.tsx
+++ b/screenpipe-app-tauri/components/video.tsx
@@ -1,11 +1,16 @@
import { memo, useCallback, useEffect, useState } from "react";
import { readFile, open } from "@tauri-apps/plugin-fs";
import { platform } from "@tauri-apps/plugin-os";
+import { cn } from "@/lib/utils";
export const VideoComponent = memo(function VideoComponent({
filePath,
+ customDescription,
+ className,
}: {
filePath: string;
+ customDescription?: string;
+ className?: string;
}) {
const [mediaSrc, setMediaSrc] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
@@ -24,7 +29,9 @@ export const VideoComponent = memo(function VideoComponent({
const renderFileLink = () => (
// TODO button open link
- <p className="mt-2 text-center text-xs text-gray-500">{filePath}</p>
+ <p className={"mt-2 text-center text-xs text-gray-500"}>
+ {customDescription || filePath}
+ </p>
);
const getMimeType = (path: string): string => {
@@ -91,14 +98,19 @@ export const VideoComponent = memo(function VideoComponent({
if (!mediaSrc) {
return (
- <div className="w-full h-48 bg-gray-200 animate-pulse rounded-md flex items-center justify-center">
+ <div
+ className={cn(
+ "w-full h-48 bg-gray-200 animate-pulse rounded-md flex items-center justify-center",
+ className
+ )}
+ >
<span className="text-gray-500">Loading media...</span>
</div>
);
}
return (
- <div className="w-full max-w-2xl text-center">
+ <div className={cn("w-full max-w-2xl text-center", className)}>
{isAudio ? (
<div className="bg-gray-100 p-4 rounded-md">
<audio controls className="w-full">
diff --git a/screenpipe-app-tauri/lib/screenpipe.ts b/screenpipe-app-tauri/lib/screenpipe.ts
index 2850ef0b8..731a5f7bf 100644
--- a/screenpipe-app-tauri/lib/screenpipe.ts
+++ b/screenpipe-app-tauri/lib/screenpipe.ts
@@ -1,5 +1,6 @@
import { z } from "zod";
import { encode } from "./utils";
+import { Speaker } from "./types";
// Define types based on the server's schema
export type OCRContent = {
@@ -23,6 +24,7 @@ export type AudioContent = {
tags: string[];
device_name: string;
device_type: string;
+ speaker: Speaker;
};
export type FTSContent = {
@@ -135,6 +137,10 @@ export const screenpipeQuery = z.object({
.number()
.default(10000)
.describe("Maximum length of the text to include in the response"),
+ speaker_ids: z
+ .string()
+ .describe("Comma separated list of speaker ids to filter by")
+ .optional(),
});
export const screenpipeMultiQuery = z.object({
@@ -173,7 +179,8 @@ export async function queryScreenpipe(
if (params.app_name) queryParams.append("app_name", params.app_name);
if (params.window_name)
queryParams.append("window_name", params.window_name);
-
+ if (params.speaker_ids)
+ queryParams.append("speaker_ids", params.speaker_ids);
const url = `http://localhost:3030/search?${queryParams.toString()}`;
console.log("calling screenpipe", url);
diff --git a/screenpipe-app-tauri/lib/types/index.ts b/screenpipe-app-tauri/lib/types/index.ts
new file mode 100644
index 000000000..bc0f308e3
--- /dev/null
+++ b/screenpipe-app-tauri/lib/types/index.ts
@@ -0,0 +1,3 @@
+export * from "./meeting";
+export * from "./speaker";
+export * from "./history";
diff --git a/screenpipe-app-tauri/lib/types/meeting.ts b/screenpipe-app-tauri/lib/types/meeting.ts
new file mode 100644
index 000000000..13dc14aca
--- /dev/null
+++ b/screenpipe-app-tauri/lib/types/meeting.ts
@@ -0,0 +1,9 @@
+import { Speaker } from "./speaker";
+
+export interface MeetingSegment {
+ timestamp: string;
+ transcription: string;
+ deviceName: string;
+ deviceType: string;
+ speaker: Speaker;
+}
diff --git a/screenpipe-app-tauri/lib/types/speaker.ts b/screenpipe-app-tauri/lib/types/speaker.ts
new file mode 100644
index 000000000..7b5222c04
--- /dev/null
+++ b/screenpipe-app-tauri/lib/types/speaker.ts
@@ -0,0 +1,12 @@
+export type AudioSample = {
+ path: string;
+ transcript: string;
+};
+
+export interface Speaker {
+ id: number;
+ name: string;
+ metadata?: {
+ audioSamples: AudioSample[];
+ };
+}
diff --git a/screenpipe-app-tauri/lib/utils.ts b/screenpipe-app-tauri/lib/utils.ts
index c9a17efa1..7c08df633 100644
--- a/screenpipe-app-tauri/lib/utils.ts
+++ b/screenpipe-app-tauri/lib/utils.ts
@@ -1,8 +1,10 @@
+import { stat } from "@tauri-apps/plugin-fs";
import { platform } from "@tauri-apps/plugin-os";
import { type ClassValue, clsx } from "clsx";
import { twMerge } from "tailwind-merge";
import { ContentItem } from "./screenpipe";
import levenshtein from "js-levenshtein";
+import { Duration } from "date-fns";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
@@ -139,3 +141,9 @@ export function stringToColor(str: string): string {
}
return color;
}
+
+export async function getFileSize(filePath: string): Promise<number> {
+ const { size } = await stat(filePath);
+
+ return size;
+}
diff --git a/screenpipe-app-tauri/src-tauri/Cargo.lock b/screenpipe-app-tauri/src-tauri/Cargo.lock
index 5c9ca8189..660e11a04 100755
--- a/screenpipe-app-tauri/src-tauri/Cargo.lock
+++ b/screenpipe-app-tauri/src-tauri/Cargo.lock
@@ -1390,7 +1390,7 @@ version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330c60081dcc4c72131f8eb70510f1ac07223e5d4163db481a04a0befcffa412"
dependencies = [
- "libloading 0.8.6",
+ "libloading 0.7.4",
]
[[package]]
@@ -5428,7 +5428,7 @@ dependencies = [
"tauri-runtime",
"tauri-runtime-wry",
"tauri-utils",
- "thiserror 2.0.4",
+ "thiserror 2.0.5",
"tokio",
"tray-icon",
"url",
@@ -5481,7 +5481,7 @@ dependencies = [
"sha2",
"syn 2.0.90",
"tauri-utils",
- "thiserror 2.0.4",
+ "thiserror 2.0.5",
"time",
"url",
"uuid",
@@ -5762,7 +5762,7 @@ dependencies = [
"serde",
"serde_json",
"tauri-utils",
- "thiserror 2.0.4",
+ "thiserror 2.0.5",
"url",
"windows 0.58.0",
]
@@ -5822,7 +5822,7 @@ dependencies = [
"serde_json",
"serde_with",
"swift-rs",
- "thiserror 2.0.4",
+ "thiserror 2.0.5",
"toml 0.8.2",
"url",
"urlpattern",
@@ -5891,11 +5891,11 @@ dependencies = [
[[package]]
name = "thiserror"
-version = "2.0.4"
+version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2f49a1853cf82743e3b7950f77e0f4d622ca36cf4317cba00c767838bac8d490"
+checksum = "643caef17e3128658ff44d85923ef2d28af81bb71e0d67bbfe1d76f19a73e053"
dependencies = [
- "thiserror-impl 2.0.4",
+ "thiserror-impl 2.0.5",
]
[[package]]
@@ -5911,9 +5911,9 @@ dependencies = [
[[package]]
name = "thiserror-impl"
-version = "2.0.4"
+version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8381894bb3efe0c4acac3ded651301ceee58a15d47c2e34885ed1908ad667061"
+checksum = "995d0bbc9995d1f19d28b7215a9352b0fc3cd3a2d2ec95c2cadc485cdedbcdde"
dependencies = [
"proc-macro2",
"quote",
diff --git a/screenpipe-app-tauri/src-tauri/capabilities/main.json b/screenpipe-app-tauri/src-tauri/capabilities/main.json
index e9449ea1f..ef6841232 100644
--- a/screenpipe-app-tauri/src-tauri/capabilities/main.json
+++ b/screenpipe-app-tauri/src-tauri/capabilities/main.json
@@ -2,11 +2,7 @@
"identifier": "migrated",
"description": "permissions that were migrated from v1",
"local": true,
- "windows": [
- "main",
- "timeline",
- "search"
- ],
+ "windows": ["main", "timeline", "search", "meetings", "identify-speakers"],
"permissions": [
"core:event:allow-listen",
"core:event:default",
@@ -135,11 +131,7 @@
{
"name": "screenpipe",
"cmd": "screenpipe",
- "args": [
- "pipe",
- "purge",
- "-y"
- ],
+ "args": ["pipe", "purge", "-y"],
"sidecar": true
}
]
@@ -150,9 +142,7 @@
{
"name": "screenpipe",
"cmd": "screenpipe",
- "args": [
- "setup"
- ],
+ "args": ["setup"],
"sidecar": true
}
]
@@ -163,9 +153,7 @@
{
"name": "screenpipe",
"cmd": "screenpipe",
- "args": [
- "migrate"
- ],
+ "args": ["migrate"],
"sidecar": true
}
]
@@ -176,9 +164,7 @@
{
"name": "ollama",
"cmd": "ollama",
- "args": [
- "serve"
- ],
+ "args": ["serve"],
"sidecar": true
}
]
@@ -217,12 +203,7 @@
{
"name": "screenpipe-pipe-list",
"cmd": "screenpipe",
- "args": [
- "pipe",
- "list",
- "--output",
- "json"
- ],
+ "args": ["pipe", "list", "--output", "json"],
"sidecar": true
}
]
@@ -338,4 +319,4 @@
]
}
]
-}
\ No newline at end of file
+}
diff --git a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
index 39b08ecf1..486808a66 100644
--- a/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
+++ b/screenpipe-app-tauri/src-tauri/gen/schemas/capabilities.json
@@ -1 +1 @@
-{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main","timeline","search"],"permissions":["core:event:allow-listen","core:event:default","core:app:allow-version","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","store:default","store:allow-create-store","store:allow-get","store:allow-set","store:allow-save","store:allow-load","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","fs:allow-remove","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","purge","-y"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["setup"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["migrate"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["serve"],"cmd":"ollama","name":"ollama","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["run",{"validator":"\\S*"}],"cmd":"ollama","name":"ollama-run","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","store:default",{"identifier":"shell:allow-execute","allow":[{"args":["pipe","list","--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-list","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","download",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-download","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","enable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-enable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","disable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-disable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","update",{"validator":"\\S+"},{"validator":"\\{.*\\}"}],"cmd":"screenpipe","name":"screenpipe-pipe-update","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","delete",{"validator":"\\S+"},"--yes"],"cmd":"screenpipe","name":"screenpipe-pipe-delete","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","info",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-info","sidecar":true}]}]}}
\ No newline at end of file
+{"migrated":{"identifier":"migrated","description":"permissions that were migrated from v1","local":true,"windows":["main","timeline","search","meetings","identify-speakers"],"permissions":["core:event:allow-listen","core:event:default","core:app:allow-version","process:allow-restart","process:allow-exit","notification:default","core:resources:default","core:menu:default","core:tray:default","shell:default","store:default","store:allow-create-store","store:allow-get","store:allow-set","store:allow-save","store:allow-load","shell:allow-open","fs:allow-watch","fs:allow-open","fs:default","fs:allow-read-file","fs:allow-read-dir","fs:allow-read","fs:allow-write-file","fs:read-dirs","fs:allow-copy-file","fs:allow-exists","fs:allow-read-text-file","fs:allow-create","fs:allow-mkdir","fs:allow-remove","global-shortcut:allow-is-registered","global-shortcut:allow-register","global-shortcut:allow-unregister","global-shortcut:allow-unregister-all","global-shortcut:default",{"identifier":"fs:scope","allow":[{"path":"$XDG_DATA_HOME","requireLiteralLeadingDot":false},{"path":"$XDG_DATA_HOME/**","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/*","requireLiteralLeadingDot":false},{"path":"$LOCALAPPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/*","requireLiteralLeadingDot":false},{"path":"$APPLOCALDATA/**","requireLiteralLeadingDot":false},{"path":"$APPDATA/*","requireLiteralLeadingDot":false},{"path":"$APPDATA/**","requireLiteralLeadingDot":false},{"path":"$APPCONFIG/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/*","requireLiteralLeadingDot":false},{"path":"$RESOURCE/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$HOME/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/*","requireLiteralLeadingDot":false},{"path":"$APP/*","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/data/**","requireLiteralLeadingDot":false},{"path":"$HOME/.screenpipe/pipes/**","requireLiteralLeadingDot":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["-c",{"validator":"\\S+"}],"cmd":"sh","name":"exec-sh","sidecar":false}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","purge","-y"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["setup"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["migrate"],"cmd":"screenpipe","name":"screenpipe","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["serve"],"cmd":"ollama","name":"ollama","sidecar":true}]},{"identifier":"shell:allow-spawn","allow":[{"args":["run",{"validator":"\\S*"}],"cmd":"ollama","name":"ollama-run","sidecar":true}]},"cli:default","shell:default","shell:allow-spawn","dialog:default","updater:default","os:default","os:allow-arch","os:allow-hostname","os:allow-os-type","core:path:default","process:default","store:default",{"identifier":"shell:allow-execute","allow":[{"args":["pipe","list","--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-list","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","download",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-download","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","enable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-enable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","disable",{"validator":"\\S+"}],"cmd":"screenpipe","name":"screenpipe-pipe-disable","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","update",{"validator":"\\S+"},{"validator":"\\{.*\\}"}],"cmd":"screenpipe","name":"screenpipe-pipe-update","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","delete",{"validator":"\\S+"},"--yes"],"cmd":"screenpipe","name":"screenpipe-pipe-delete","sidecar":true}]},{"identifier":"shell:allow-execute","allow":[{"args":["pipe","info",{"validator":"\\S+"},"--output","json"],"cmd":"screenpipe","name":"screenpipe-pipe-info","sidecar":true}]}]}}
\ No newline at end of file
diff --git a/screenpipe-app-tauri/src-tauri/src/commands.rs b/screenpipe-app-tauri/src-tauri/src/commands.rs
index 8fd53fd0f..6c178b4e9 100644
--- a/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -135,6 +135,61 @@ pub fn show_timeline(app_handle: tauri::AppHandle<tauri::Wry>) {
.unwrap();
}
}
+#[tauri::command]
+pub fn show_meetings(app_handle: tauri::AppHandle<tauri::Wry>) {
+ if let Some(window) = app_handle.get_webview_window("meetings") {
+ #[cfg(target_os = "macos")]
+ let _ = app_handle.set_activation_policy(tauri::ActivationPolicy::Accessory);
+
+ // let _ = window.set_visible_on_all_workspaces(true);
+ // let _ = window.set_always_on_top(true);
+ let _ = window.set_decorations(true);
+ let _ = window.show();
+ let _ = window.set_focus();
+ } else {
+ let _window = tauri::WebviewWindowBuilder::new(
+ &app_handle,
+ "meetings",
+ tauri::WebviewUrl::App("meetings.html".into()),
+ )
+ .title("meetings")
+ .decorations(true)
+ .transparent(true)
+ // .always_on_top(true)
+ // .visible_on_all_workspaces(true) // Added this
+ .center()
+ .build()
+ .unwrap();
+ }
+}
+
+#[tauri::command]
+pub fn show_identify_speakers(app_handle: tauri::AppHandle<tauri::Wry>) {
+ if let Some(window) = app_handle.get_webview_window("identify-speakers") {
+ #[cfg(target_os = "macos")]
+ let _ = app_handle.set_activation_policy(tauri::ActivationPolicy::Accessory);
+
+ // let _ = window.set_visible_on_all_workspaces(true);
+ // let _ = window.set_always_on_top(true);
+ let _ = window.set_decorations(true);
+ let _ = window.show();
+ let _ = window.set_focus();
+ } else {
+ let _window = tauri::WebviewWindowBuilder::new(
+ &app_handle,
+ "identify-speakers",
+ tauri::WebviewUrl::App("identify-speakers.html".into()),
+ )
+ .title("identify-speakers")
+ .decorations(true)
+ .transparent(true)
+ // .always_on_top(true)
+ // .visible_on_all_workspaces(true) // Added this
+ .center()
+ .build()
+ .unwrap();
+ }
+}
const DEFAULT_SHORTCUT: &str = "Super+Alt+S";
diff --git a/screenpipe-app-tauri/src-tauri/src/main.rs b/screenpipe-app-tauri/src-tauri/src/main.rs
index dafd53b83..d173d7796 100755
--- a/screenpipe-app-tauri/src-tauri/src/main.rs
+++ b/screenpipe-app-tauri/src-tauri/src/main.rs
@@ -166,6 +166,8 @@ async fn main() {
icons::get_app_icon,
commands::open_auth_window,
commands::show_search,
+ commands::show_meetings,
+ commands::show_identify_speakers,
])
.setup(|app| {
// Logging setup
diff --git a/screenpipe-app-tauri/src-tauri/tauri.conf.json b/screenpipe-app-tauri/src-tauri/tauri.conf.json
index 38e384d9b..7e57dc240 100644
--- a/screenpipe-app-tauri/src-tauri/tauri.conf.json
+++ b/screenpipe-app-tauri/src-tauri/tauri.conf.json
@@ -11,12 +11,7 @@
"active": true,
"category": "DeveloperTool",
"copyright": "",
- "targets": [
- "app",
- "dmg",
- "appimage",
- "nsis"
- ],
+ "targets": ["app", "dmg", "appimage", "nsis"],
"externalBin": [],
"icon": [
"icons/32x32.png",
@@ -31,34 +26,16 @@
"icons/screenpipe-logo-tray-black.png"
],
"longDescription": "",
- "resources": [
- "assets/*"
- ],
+ "resources": ["assets/*"],
"shortDescription": "",
"fileAssociations": [
{
"description": "Video files",
- "ext": [
- "mp4",
- "mkv",
- "avi",
- "mov",
- "wmv",
- "webm"
- ]
+ "ext": ["mp4", "mkv", "avi", "mov", "wmv", "webm"]
},
{
"description": "Audio files",
- "ext": [
- "mp3",
- "wav",
- "aac",
- "flac",
- "oga",
- "ogg",
- "opic",
- "opus"
- ]
+ "ext": ["mp3", "wav", "aac", "flac", "oga", "ogg", "opic", "opus"]
}
]
},
@@ -113,17 +90,38 @@
"visible": false,
"decorations": true,
"transparent": true
+ },
+ {
+ "title": "meetings",
+ "url": "/meetings",
+ "label": "meetings",
+ "width": 1200,
+ "height": 1000,
+ "minWidth": 1000,
+ "minHeight": 600,
+ "visible": false,
+ "decorations": true,
+ "transparent": true
+ },
+ {
+ "title": "identify speakers",
+ "url": "/identify-speakers",
+ "label": "identify-speakers",
+ "visible": false,
+ "width": 1200,
+ "height": 850,
+ "minWidth": 1200,
+ "minHeight": 850,
+ "resizable": true
}
],
"security": {
"assetProtocol": {
"enable": true,
- "scope": [
- "$APPDATA/**"
- ]
+ "scope": ["$APPDATA/**"]
},
"csp": null
},
"macOSPrivateApi": true
}
-}
\ No newline at end of file
+}
diff --git a/screenpipe-app-tauri/src-tauri/ui_monitor-aarch64-apple-darwin b/screenpipe-app-tauri/src-tauri/ui_monitor-aarch64-apple-darwin
index b8610eb78..8c8ef0920 100755
Binary files a/screenpipe-app-tauri/src-tauri/ui_monitor-aarch64-apple-darwin and b/screenpipe-app-tauri/src-tauri/ui_monitor-aarch64-apple-darwin differ
diff --git a/screenpipe-app-tauri/src-tauri/ui_monitor-x86_64-apple-darwin b/screenpipe-app-tauri/src-tauri/ui_monitor-x86_64-apple-darwin
index b8597c2ba..1ee1fa0af 100755
Binary files a/screenpipe-app-tauri/src-tauri/ui_monitor-x86_64-apple-darwin and b/screenpipe-app-tauri/src-tauri/ui_monitor-x86_64-apple-darwin differ
diff --git a/screenpipe-server/benches/db_benchmarks.rs b/screenpipe-server/benches/db_benchmarks.rs
index 6fd02d359..f0348c068 100644
--- a/screenpipe-server/benches/db_benchmarks.rs
+++ b/screenpipe-server/benches/db_benchmarks.rs
@@ -82,6 +82,7 @@ fn bench_search(c: &mut Criterion) {
None,
None,
None,
+ None,
)
.await
.unwrap()
diff --git a/screenpipe-server/src/core.rs b/screenpipe-server/src/core.rs
index 7806c8e41..4df980c54 100644
--- a/screenpipe-server/src/core.rs
+++ b/screenpipe-server/src/core.rs
@@ -494,3 +494,22 @@ async fn get_or_create_speaker_from_embedding(
Ok(speaker)
}
}
+
+pub async fn merge_speakers(
+ db: &DatabaseManager,
+ speaker_to_keep_id: i64,
+ speaker_to_merge_id: i64,
+) -> Result<Speaker, anyhow::Error> {
+ // make sure both speakers exist
+ let _ = db.get_speaker_by_id(speaker_to_keep_id).await?;
+ let _ = db.get_speaker_by_id(speaker_to_merge_id).await?;
+
+ // call merge method from db
+ match db
+ .merge_speakers(speaker_to_keep_id, speaker_to_merge_id)
+ .await
+ {
+ Ok(speaker) => Ok(speaker),
+ Err(e) => Err(anyhow::anyhow!("Failed to merge speakers: {}", e)),
+ }
+}
diff --git a/screenpipe-server/src/db.rs b/screenpipe-server/src/db.rs
index a728dd03a..0e88c34d0 100644
--- a/screenpipe-server/src/db.rs
+++ b/screenpipe-server/src/db.rs
@@ -21,12 +21,14 @@ use tokio::time::{timeout, Duration as TokioDuration};
use zerocopy::AsBytes;
use crate::db_types::{
- AudioEntry, AudioResult, AudioResultRaw, FrameData, OCREntry, OCRResult, OCRResultRaw, Speaker,
- TagContentType,
+ AudioChunk, AudioEntry, AudioResult, AudioResultRaw, FrameData, OCREntry, OCRResult,
+ OCRResultRaw, Speaker, TagContentType,
};
use crate::db_types::{ContentType, UiContent};
use crate::db_types::{SearchResult, TimeSeriesChunk};
+use futures::future::try_join_all;
+
pub struct DatabaseManager {
pub pool: SqlitePool,
}
@@ -150,13 +152,14 @@ impl DatabaseManager {
let mut tx = self.pool.begin().await?;
// Insert the full transcription
- let affected =
- sqlx::query("UPDATE audio_transcriptions SET transcription = ?1 WHERE id = ?2")
- .bind(transcription)
- .bind(audio_chunk_id)
- .execute(&mut *tx)
- .await?
- .rows_affected();
+ let affected = sqlx::query(
+ "UPDATE audio_transcriptions SET transcription = ?1 WHERE audio_chunk_id = ?2",
+ )
+ .bind(transcription)
+ .bind(audio_chunk_id)
+ .execute(&mut *tx)
+ .await?
+ .rows_affected();
// Commit the transaction for the full transcription
tx.commit().await?;
@@ -216,7 +219,7 @@ impl DatabaseManager {
&self,
embedding: &[f32],
) -> Result<Option<Speaker>, SqlxError> {
- let speaker_threshold = 0.6;
+ let speaker_threshold = 0.5;
let bytes: &[u8] = embedding.as_bytes();
// Using subquery with LIMIT 1 instead of JOIN
@@ -443,6 +446,7 @@ impl DatabaseManager {
window_name: Option<&str>,
min_length: Option<usize>,
max_length: Option<usize>,
+ speaker_ids: Option<Vec<i64>>,
) -> Result<Vec<SearchResult>, sqlx::Error> {
let mut results = Vec::new();
@@ -464,7 +468,14 @@ impl DatabaseManager {
max_length,
),
self.search_audio(
- query, limit, offset, start_time, end_time, min_length, max_length
+ query,
+ limit,
+ offset,
+ start_time,
+ end_time,
+ min_length,
+ max_length,
+ speaker_ids
),
self.search_ui_monitoring(
query,
@@ -530,7 +541,14 @@ impl DatabaseManager {
if app_name.is_none() && window_name.is_none() {
let audio_results = self
.search_audio(
- query, limit, offset, start_time, end_time, min_length, max_length,
+ query,
+ limit,
+ offset,
+ start_time,
+ end_time,
+ min_length,
+ max_length,
+ speaker_ids,
)
.await?;
results.extend(audio_results.into_iter().map(SearchResult::Audio));
@@ -560,6 +578,7 @@ impl DatabaseManager {
end_time,
min_length,
max_length,
+ speaker_ids,
)
.await?;
let ui_results = self
@@ -616,6 +635,7 @@ impl DatabaseManager {
end_time,
min_length,
max_length,
+ speaker_ids,
)
.await?;
let ocr_results = self
@@ -761,7 +781,15 @@ impl DatabaseManager {
end_time: Option<DateTime<Utc>>,
min_length: Option<usize>,
max_length: Option<usize>,
+ speaker_ids: Option<Vec<i64>>,
) -> Result<Vec<AudioResult>, sqlx::Error> {
+ let mut json_array: String = "[]".to_string();
+ if let Some(ids) = speaker_ids {
+ if !ids.is_empty() {
+ json_array = serde_json::to_string(&ids).unwrap_or_default();
+ }
+ }
+
let base_sql = if query.is_empty() {
"audio_transcriptions"
} else {
@@ -785,9 +813,11 @@ impl DatabaseManager {
audio_transcriptions.transcription_engine,
GROUP_CONCAT(tags.name, ',') as tags,
audio_transcriptions.device as device_name,
- audio_transcriptions.is_input_device
+ audio_transcriptions.is_input_device,
+ audio_transcriptions.speaker_id
FROM {}
JOIN audio_chunks ON audio_transcriptions.audio_chunk_id = audio_chunks.id
+ LEFT JOIN speakers on audio_transcriptions.speaker_id = speakers.id
LEFT JOIN audio_tags ON audio_chunks.id = audio_tags.audio_chunk_id
LEFT JOIN tags ON audio_tags.tag_id = tags.id
{}
@@ -795,9 +825,11 @@ impl DatabaseManager {
AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)
AND (?4 IS NULL OR LENGTH(audio_transcriptions.transcription) >= ?4)
AND (?5 IS NULL OR LENGTH(audio_transcriptions.transcription) <= ?5)
+ AND speakers.hallucination = 0
+ AND (json_array_length(?6) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?6)))
GROUP BY audio_transcriptions.audio_chunk_id, audio_transcriptions.offset_index
ORDER BY audio_transcriptions.timestamp DESC
- LIMIT ?6 OFFSET ?7
+ LIMIT ?7 OFFSET ?8
"#,
base_sql, where_clause
);
@@ -808,14 +840,22 @@ impl DatabaseManager {
.bind(end_time)
.bind(min_length.map(|l| l as i64))
.bind(max_length.map(|l| l as i64))
+ .bind(json_array)
.bind(limit)
.bind(offset)
.fetch_all(&self.pool)
.await?;
- Ok(raw_results
- .into_iter()
- .map(|raw| AudioResult {
+ let futures = raw_results.into_iter().map(|raw| async move {
+ let speaker = match raw.speaker_id {
+ Some(id) => match self.get_speaker_by_id(id).await {
+ Ok(speaker) => Some(speaker),
+ Err(_) => None,
+ },
+ None => None,
+ };
+
+ Ok::<AudioResult, sqlx::Error>(AudioResult {
audio_chunk_id: raw.audio_chunk_id,
transcription: raw.transcription,
timestamp: raw.timestamp,
@@ -832,8 +872,11 @@ impl DatabaseManager {
} else {
DeviceType::Output
},
+ speaker,
})
- .collect())
+ });
+
+ Ok(try_join_all(futures).await?.into_iter().collect())
}
pub async fn get_frame(&self, frame_id: i64) -> Result<Option<(String, i64)>, sqlx::Error> {
@@ -855,6 +898,7 @@ impl DatabaseManager {
.await
}
+ #[allow(clippy::too_many_arguments)]
pub async fn count_search_results(
&self,
query: &str,
@@ -865,7 +909,15 @@ impl DatabaseManager {
window_name: Option<&str>,
min_length: Option<usize>,
max_length: Option<usize>,
+ speaker_ids: Option<Vec<i64>>,
) -> Result<usize, sqlx::Error> {
+ let mut json_array: String = "[]".to_string();
+ if let Some(ids) = speaker_ids {
+ if !ids.is_empty() {
+ json_array = serde_json::to_string(&ids).unwrap_or_default();
+ }
+ }
+
let sql = match content_type {
ContentType::OCR => {
format!(
@@ -892,7 +944,7 @@ impl DatabaseManager {
ContentType::Audio => {
format!(
r#"
- SELECT COUNT(DISTINCT audio_transcriptions.id)
+ SELECT COUNT(DISTINCT audio_transcriptions.audio_chunk_id)
FROM audio_transcriptions_fts
JOIN audio_transcriptions ON audio_transcriptions_fts.audio_chunk_id = audio_transcriptions.audio_chunk_id
WHERE {}
@@ -900,6 +952,7 @@ impl DatabaseManager {
AND (?3 IS NULL OR audio_transcriptions.timestamp <= ?3)
AND (?6 IS NULL OR LENGTH(audio_transcriptions.transcription) >= ?6)
AND (?7 IS NULL OR LENGTH(audio_transcriptions.transcription) <= ?7)
+ AND (json_array_length(?8) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?8)))
"#,
if query.is_empty() {
"1=1"
@@ -955,6 +1008,7 @@ impl DatabaseManager {
AND (?6 IS NULL OR LENGTH(audio_transcriptions.transcription) >= ?6)
AND (?7 IS NULL OR LENGTH(audio_transcriptions.transcription) <= ?7)
AND audio_transcriptions.transcription != ''
+ AND (json_array_length(?8) = 0 OR audio_transcriptions.speaker_id IN (SELECT value FROM json_each(?8)))
UNION ALL
@@ -982,7 +1036,7 @@ impl DatabaseManager {
if query.is_empty() {
"audio_transcriptions"
} else {
- "audio_transcriptions_fts JOIN audio_transcriptions ON audio_transcriptions_fts.audio_chunk_id = audio_transcriptions.audio_chunk_id"
+ "audio_transcriptions_fts JOIN audio_transcriptions ON audio_transcriptions_fts.rowid = audio_transcriptions.id"
},
if query.is_empty() {
"1=1"
@@ -1012,6 +1066,7 @@ impl DatabaseManager {
.bind(window_name)
.bind(min_length.map(|len| len as i64))
.bind(max_length.map(|len| len as i64))
+ .bind(json_array)
.fetch_one(&self.pool)
.await?;
@@ -1468,4 +1523,257 @@ impl DatabaseManager {
Ok(tags.into_iter().map(|t| t.0).collect())
}
+
+ pub async fn get_audio_chunks_for_speaker(
+ &self,
+ speaker_id: i64,
+ ) -> Result<Vec<AudioChunk>, sqlx::Error> {
+ sqlx::query_as::<_, AudioChunk>(
+ "SELECT * FROM audio_chunks WHERE id IN (SELECT audio_chunk_id FROM audio_transcriptions WHERE speaker_id = ?)",
+ )
+ .bind(speaker_id)
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ // get unnamed speakers
+ pub async fn get_unnamed_speakers(
+ &self,
+ limit: u32,
+ offset: u32,
+ speaker_ids: Option<Vec<i64>>,
+ ) -> Result<Vec<Speaker>, sqlx::Error> {
+ let base_query = r#"
+ WITH RecentAudioPaths AS (
+ SELECT DISTINCT
+ s.id as speaker_id,
+ ac.file_path,
+ at.transcription
+ FROM speakers s
+ JOIN audio_transcriptions at ON s.id = at.speaker_id
+ JOIN audio_chunks ac ON at.audio_chunk_id = ac.id
+ WHERE (s.name = '' OR s.name IS NULL)
+ AND s.hallucination = 0
+ "#;
+
+ let speaker_filter = match &speaker_ids {
+ Some(ids) if !ids.is_empty() => {
+ let placeholders = vec!["?"; ids.len()].join(",");
+ format!("AND s.id IN ({})", placeholders)
+ }
+ _ => String::new(),
+ };
+
+ let query = format!(
+ r#"{}
+ {}
+ AND at.timestamp IN (
+ SELECT timestamp
+ FROM audio_transcriptions at2
+ WHERE at2.speaker_id = s.id
+ ORDER BY timestamp DESC
+ LIMIT 3
+ )
+ )
+ SELECT
+ s.id,
+ s.name,
+ CASE
+ WHEN s.metadata = '' OR s.metadata IS NULL OR json_valid(s.metadata) = 0
+ THEN json_object('audio_samples', json_group_array(
+ DISTINCT json_object(
+ 'path', rap.file_path,
+ 'transcript', rap.transcription
+ )
+ ))
+ ELSE json_patch(
+ json(s.metadata),
+ json_object('audio_samples', json_group_array(
+ DISTINCT json_object(
+ 'path', rap.file_path,
+ 'transcript', rap.transcription
+ )
+ ))
+ )
+ END as metadata,
+ COUNT(at.id) as transcription_count
+ FROM speakers s
+ JOIN RecentAudioPaths rap ON s.id = rap.speaker_id
+ JOIN audio_transcriptions at ON s.id = at.speaker_id
+ GROUP BY s.id
+ ORDER BY transcription_count DESC
+ LIMIT ? OFFSET ?
+ "#,
+ base_query, speaker_filter
+ );
+
+ let mut db_query = sqlx::query_as::<sqlx::Sqlite, Speaker>(&query);
+
+ // Add speaker_id bindings if present
+ if let Some(ids) = speaker_ids {
+ for id in ids {
+ db_query = db_query.bind(id);
+ }
+ }
+
+ // Add limit and offset last
+ db_query = db_query.bind(limit).bind(offset);
+
+ let res = db_query.fetch_all(&self.pool).await?;
+ Ok(res)
+ }
+
+ pub async fn merge_speakers(
+ &self,
+ speaker_to_keep_id: i64,
+ speaker_to_merge_id: i64,
+ ) -> Result<Speaker, sqlx::Error> {
+ let mut tx = self.pool.begin().await?;
+
+ // for each audio transcription of the speaker to merge, update the speaker_id to the speaker to keep
+ sqlx::query("UPDATE audio_transcriptions SET speaker_id = ? WHERE speaker_id = ?")
+ .bind(speaker_to_keep_id)
+ .bind(speaker_to_merge_id)
+ .execute(&mut *tx)
+ .await?;
+
+ // update speaker_embeddings
+ sqlx::query("UPDATE speaker_embeddings SET speaker_id = ? WHERE speaker_id = ?")
+ .bind(speaker_to_keep_id)
+ .bind(speaker_to_merge_id)
+ .execute(&mut *tx)
+ .await?;
+
+ // delete the speaker to merge
+ sqlx::query("DELETE FROM speakers WHERE id = ?")
+ .bind(speaker_to_merge_id)
+ .execute(&mut *tx)
+ .await?;
+
+ tx.commit().await?;
+
+ self.get_speaker_by_id(speaker_to_keep_id).await
+ }
+
+ pub async fn search_speakers(&self, name_prefix: &str) -> Result<Vec<Speaker>, sqlx::Error> {
+ sqlx::query_as::<_, Speaker>(
+ "SELECT * FROM speakers WHERE name LIKE ? || '%' AND hallucination = 0",
+ )
+ .bind(name_prefix)
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ pub async fn delete_speaker(&self, id: i64) -> Result<(), sqlx::Error> {
+ let mut tx = self.pool.begin().await?;
+
+ // Array of (query, operation description) tuples
+ let operations = [
+ (
+ "DELETE FROM audio_transcriptions WHERE speaker_id = ?",
+ "audio transcriptions",
+ ),
+ (
+ "DELETE FROM audio_chunks WHERE id IN (SELECT audio_chunk_id FROM audio_transcriptions WHERE speaker_id = ?)",
+ "audio chunks",
+ ),
+ (
+ "DELETE FROM speaker_embeddings WHERE speaker_id = ?",
+ "speaker embeddings",
+ ),
+ (
+ "DELETE FROM speakers WHERE id = ?",
+ "speaker",
+ ),
+ ];
+
+ // Execute each deletion operation
+ for (query, operation) in operations {
+ if let Err(e) = sqlx::query(query).bind(id).execute(&mut *tx).await {
+ error!("Failed to delete {} for speaker {}: {}", operation, id, e);
+ tx.rollback().await?;
+ return Err(e);
+ }
+ debug!("Successfully deleted {} for speaker {}", operation, id);
+ }
+
+ tx.commit().await.map_err(|e| {
+ error!("Failed to commit speaker deletion transaction: {}", e);
+ e
+ })?;
+
+ debug!("Successfully committed speaker deletion transaction");
+ Ok(())
+ }
+
+ pub async fn get_similar_speakers(
+ &self,
+ speaker_id: i64,
+ limit: u32,
+ ) -> Result<Vec<Speaker>, sqlx::Error> {
+ let threshold = 0.8;
+
+ sqlx::query_as::<sqlx::Sqlite, Speaker>(
+ r#"
+ WITH RecentAudioPaths AS (
+ SELECT DISTINCT
+ s.id as speaker_id,
+ ac.file_path,
+ at.transcription
+ FROM speakers s
+ JOIN audio_transcriptions at ON s.id = at.speaker_id
+ JOIN audio_chunks ac ON at.audio_chunk_id = ac.id
+ AND s.hallucination = 0
+ AND at.timestamp IN (
+ SELECT timestamp
+ FROM audio_transcriptions at2
+ WHERE at2.speaker_id = s.id
+ ORDER BY timestamp DESC
+ LIMIT 3
+ )
+ ),
+ speaker_embedding AS (
+ SELECT embedding FROM speaker_embeddings WHERE speaker_id = ?1
+ )
+ SELECT
+ s.id,
+ s.name,
+ CASE
+ WHEN s.metadata = '' OR s.metadata IS NULL OR json_valid(s.metadata) = 0
+ THEN json_object('audio_samples', json_group_array(DISTINCT json_object(
+ 'path', rap.file_path,
+ 'transcript', rap.transcription
+ )))
+ ELSE json_patch(
+ json(s.metadata),
+ json_object('audio_samples', json_group_array(DISTINCT json_object(
+ 'path', rap.file_path,
+ 'transcript', rap.transcription
+ )))
+ )
+ END as metadata
+ FROM speaker_embeddings se
+ JOIN speakers s ON se.speaker_id = s.id
+ JOIN RecentAudioPaths rap ON s.id = rap.speaker_id
+ WHERE vec_distance_cosine(se.embedding, (SELECT embedding FROM speaker_embedding)) < ?2
+ AND se.speaker_id != ?1
+ GROUP BY s.id
+ ORDER BY vec_distance_cosine(se.embedding, (SELECT embedding FROM speaker_embedding))
+ LIMIT ?3"#,
+ )
+ .bind(speaker_id)
+ .bind(threshold)
+ .bind(limit)
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ pub async fn mark_speaker_as_hallucination(&self, id: i64) -> Result<(), sqlx::Error> {
+ sqlx::query("UPDATE speakers SET hallucination = TRUE WHERE id = ?")
+ .bind(id)
+ .execute(&self.pool)
+ .await?;
+
+ Ok(())
+ }
}
diff --git a/screenpipe-server/src/db_types.rs b/screenpipe-server/src/db_types.rs
index 5650c0f25..5459ce4c4 100644
--- a/screenpipe-server/src/db_types.rs
+++ b/screenpipe-server/src/db_types.rs
@@ -81,9 +81,10 @@ pub struct AudioResultRaw {
pub tags: Option<String>,
pub device_name: String,
pub is_input_device: bool,
+ pub speaker_id: Option<i64>,
}
-#[derive(Debug, Serialize, Deserialize, FromRow)]
+#[derive(Debug, Serialize, Deserialize, FromRow, Clone)]
pub struct Speaker {
pub id: i64,
pub name: String,
@@ -101,6 +102,7 @@ pub struct AudioResult {
pub tags: Vec<String>,
pub device_name: String,
pub device_type: DeviceType,
+ pub speaker: Option<Speaker>,
}
#[derive(Debug, Deserialize, PartialEq)]
@@ -171,4 +173,11 @@ impl ToString for ContentSource {
ContentSource::Audio => "audio".to_string(),
}
}
-}
\ No newline at end of file
+}
+
+#[derive(Debug, FromRow)]
+pub struct AudioChunk {
+ pub id: i64,
+ pub file_path: String,
+ pub timestamp: DateTime<Utc>,
+}
diff --git a/screenpipe-server/src/migrations/20241207202831_add_speaker_id_to_fts.sql b/screenpipe-server/src/migrations/20241207202831_add_speaker_id_to_fts.sql
new file mode 100644
index 000000000..895e28e0f
--- /dev/null
+++ b/screenpipe-server/src/migrations/20241207202831_add_speaker_id_to_fts.sql
@@ -0,0 +1,38 @@
+PRAGMA foreign_keys = OFF;
+
+-- Drop existing triggers and FTS tables
+DROP TRIGGER IF EXISTS audio_transcriptions_ai;
+DROP TABLE IF EXISTS audio_transcriptions_fts;
+
+CREATE VIRTUAL TABLE IF NOT EXISTS audio_transcriptions_fts USING fts5(
+ transcription,
+ device,
+ audio_chunk_id UNINDEXED,
+ speaker_id,
+ tokenize='unicode61'
+);
+
+INSERT OR IGNORE INTO audio_transcriptions_fts(audio_chunk_id, transcription, device, speaker_id)
+SELECT
+ audio_chunk_id,
+ COALESCE(transcription, '') as transcription,
+ COALESCE(device, '') as device,
+ speaker_id
+FROM audio_transcriptions
+WHERE transcription IS NOT NULL
+ AND transcription != ''
+ AND audio_chunk_id IS NOT NULL;
+
+CREATE TRIGGER IF NOT EXISTS audio_transcriptions_ai AFTER INSERT ON audio_transcriptions
+WHEN NEW.transcription IS NOT NULL AND NEW.transcription != '' AND NEW.audio_chunk_id IS NOT NULL
+BEGIN
+ INSERT OR IGNORE INTO audio_transcriptions_fts(audio_chunk_id, transcription, device, speaker_id)
+ VALUES (
+ NEW.audio_chunk_id,
+ NEW.transcription,
+ COALESCE(NEW.device, ''),
+ NEW.speaker_id
+ );
+END;
+
+PRAGMA foreign_keys = ON;
\ No newline at end of file
diff --git a/screenpipe-server/src/server.rs b/screenpipe-server/src/server.rs
index a007da719..16ba715f0 100644
--- a/screenpipe-server/src/server.rs
+++ b/screenpipe-server/src/server.rs
@@ -13,7 +13,7 @@ use futures::{
use image::ImageFormat::{self};
use crate::{
- db_types::{ContentType, SearchResult, TagContentType},
+ db_types::{ContentType, SearchResult, Speaker, TagContentType},
pipe_manager::PipeManager,
video::{finish_ffmpeg_process, start_ffmpeg_process, write_frame_to_ffmpeg, MAX_FPS},
video_cache::{FrameCache, TimeSeriesFrame},
@@ -30,7 +30,7 @@ use screenpipe_audio::{
};
use screenpipe_vision::monitor::list_monitors;
use screenpipe_vision::OcrEngine;
-use serde::{Deserialize, Serialize};
+use serde::{Deserialize, Deserializer, Serialize};
use serde_json::{json, Value};
use std::{
collections::HashMap,
@@ -54,6 +54,8 @@ use enigo::{Enigo, Key, Settings};
use screenpipe_audio::LAST_AUDIO_CAPTURE;
+use std::str::FromStr;
+
pub struct AppState {
pub db: Arc<DatabaseManager>,
pub vision_control: Arc<AtomicBool>,
@@ -90,6 +92,11 @@ pub(crate) struct SearchQuery {
min_length: Option<usize>,
#[serde(default)]
max_length: Option<usize>,
+ #[serde(
+ deserialize_with = "from_comma_separated_array",
+ default = "default_speaker_ids"
+ )]
+ speaker_ids: Option<Vec<i64>>,
}
#[derive(Deserialize)]
@@ -124,6 +131,28 @@ pub struct PaginationInfo {
pub total: i64,
}
+#[derive(Serialize, Deserialize, Debug)]
+pub struct UpdateSpeakerRequest {
+ pub id: i64,
+ pub name: Option<String>,
+ pub metadata: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct SearchSpeakersRequest {
+ pub name: Option<String>,
+}
+
+#[derive(Serialize, Deserialize, Debug)]
+pub struct DeleteSpeakerRequest {
+ pub id: i64,
+}
+
+#[derive(Deserialize)]
+struct MarkAsHallucinationRequest {
+ speaker_id: i64,
+}
+
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "type", content = "content")]
pub enum ContentItem {
@@ -155,6 +184,7 @@ pub struct AudioContent {
pub tags: Vec<String>,
pub device_name: String,
pub device_type: DeviceType,
+ pub speaker: Option<Speaker>,
}
#[derive(Serialize, Deserialize, Debug)]
@@ -231,7 +261,7 @@ pub(crate) async fn search(
(StatusCode, JsonResponse<serde_json::Value>),
> {
info!(
- "received search request: query='{}', content_type={:?}, limit={}, offset={}, start_time={:?}, end_time={:?}, app_name={:?}, window_name={:?}, min_length={:?}, max_length={:?}",
+ "received search request: query='{}', content_type={:?}, limit={}, offset={}, start_time={:?}, end_time={:?}, app_name={:?}, window_name={:?}, min_length={:?}, max_length={:?}, speaker_ids={:?}",
query.q.as_deref().unwrap_or(""),
query.content_type,
query.pagination.limit,
@@ -241,7 +271,8 @@ pub(crate) async fn search(
query.app_name,
query.window_name,
query.min_length,
- query.max_length
+ query.max_length,
+ query.speaker_ids
);
let query_str = query.q.as_deref().unwrap_or("");
@@ -260,6 +291,7 @@ pub(crate) async fn search(
query.window_name.as_deref(),
query.min_length,
query.max_length,
+ query.speaker_ids.clone(),
),
state.db.count_search_results(
query_str,
@@ -270,6 +302,7 @@ pub(crate) async fn search(
query.window_name.as_deref(),
query.min_length,
query.max_length,
+ query.speaker_ids.clone(),
),
)
.await
@@ -304,6 +337,7 @@ pub(crate) async fn search(
tags: audio.tags.clone(),
device_name: audio.device_name.clone(),
device_type: audio.device_type.clone(),
+ speaker: audio.speaker.clone(),
}),
SearchResult::UI(ui) => ContentItem::UI(UiContent {
id: ui.id,
@@ -1294,6 +1328,212 @@ impl From<TimeSeriesFrame> for StreamTimeSeriesResponse {
}
}
+#[derive(Deserialize, Debug)]
+pub struct GetUnnamedSpeakersRequest {
+ limit: u32,
+ offset: u32,
+ // comma separated list of speaker ids to include
+ #[serde(
+ deserialize_with = "from_comma_separated_array",
+ default = "default_speaker_ids"
+ )]
+ speaker_ids: Option<Vec<i64>>,
+}
+
+fn default_speaker_ids() -> Option<Vec<i64>> {
+ None
+}
+
+#[derive(Deserialize, Debug)]
+pub struct GetSimilarSpeakersRequest {
+ speaker_id: i64,
+ limit: u32,
+}
+
+fn from_comma_separated_array<'de, D>(deserializer: D) -> Result<Option<Vec<i64>>, D::Error>
+where
+ D: Deserializer<'de>,
+{
+ let s = Option::<String>::deserialize(deserializer).unwrap_or(None);
+ let s = match s {
+ None => return Ok(None),
+ Some(s) => s,
+ };
+ s.split(',')
+ .map(|i| i64::from_str(i).map_err(serde::de::Error::custom))
+ .collect::<Result<Vec<_>, _>>()
+ .map(Some)
+}
+
+async fn get_unnamed_speakers_handler(
+ State(state): State<Arc<AppState>>,
+ Query(request): Query<GetUnnamedSpeakersRequest>,
+) -> Result<JsonResponse<Vec<Speaker>>, (StatusCode, JsonResponse<Value>)> {
+ let speakers = state
+ .db
+ .get_unnamed_speakers(request.limit, request.offset, request.speaker_ids)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ )
+ })?;
+
+ // convert metadata to json
+ let speakers = speakers
+ .into_iter()
+ .map(|speaker| {
+ let mut metadata: Value = serde_json::from_str(&speaker.metadata).unwrap();
+ if let Some(audio_samples) = metadata.get("audio_samples").and_then(|v| v.as_array()) {
+ metadata["audio_samples"] = serde_json::to_value(audio_samples).unwrap();
+ }
+ Speaker {
+ metadata: metadata.to_string(),
+ ..speaker
+ }
+ })
+ .collect();
+
+ Ok(JsonResponse(speakers))
+}
+
+async fn update_speaker_handler(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<UpdateSpeakerRequest>,
+) -> Result<JsonResponse<Speaker>, (StatusCode, JsonResponse<Value>)> {
+ let speaker_id = payload.id;
+
+ if let Some(name) = payload.name {
+ if let Err(e) = state.db.update_speaker_name(speaker_id, &name).await {
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ ));
+ }
+ }
+
+ if let Some(metadata) = payload.metadata {
+ if let Err(e) = state
+ .db
+ .update_speaker_metadata(speaker_id, &metadata)
+ .await
+ {
+ return Err((
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ ));
+ }
+ }
+
+ Ok(JsonResponse(
+ state.db.get_speaker_by_id(speaker_id).await.unwrap(),
+ ))
+}
+
+async fn search_speakers_handler(
+ State(state): State<Arc<AppState>>,
+ Query(request): Query<SearchSpeakersRequest>,
+) -> Result<JsonResponse<Vec<Speaker>>, (StatusCode, JsonResponse<Value>)> {
+ let search_prefix = request.name.unwrap_or_default();
+ Ok(JsonResponse(
+ state.db.search_speakers(&search_prefix).await.unwrap(),
+ ))
+}
+
+async fn delete_speaker_handler(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<DeleteSpeakerRequest>,
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
+ // get audio_chunks for this speaker
+ let audio_chunks = state
+ .db
+ .get_audio_chunks_for_speaker(payload.id)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ )
+ })?;
+
+ state.db.delete_speaker(payload.id).await.map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ )
+ })?;
+
+ // delete all audio chunks from the file system
+ for audio_chunk in audio_chunks {
+ std::fs::remove_file(audio_chunk.file_path).map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ )
+ })?;
+ }
+
+ Ok(JsonResponse(json!({"success": true})))
+}
+
+async fn mark_as_hallucination_handler(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<MarkAsHallucinationRequest>,
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
+ let speaker_id = payload.speaker_id;
+
+ state
+ .db
+ .mark_speaker_as_hallucination(speaker_id)
+ .await
+ .unwrap();
+
+ Ok(JsonResponse(json!({"success": true})))
+}
+
+async fn merge_speakers_handler(
+ State(state): State<Arc<AppState>>,
+ Json(payload): Json<MergeSpeakersRequest>,
+) -> Result<JsonResponse<Value>, (StatusCode, JsonResponse<Value>)> {
+ let speaker_to_keep_id = payload.speaker_to_keep_id;
+ let speaker_to_merge_id = payload.speaker_to_merge_id;
+
+ state
+ .db
+ .merge_speakers(speaker_to_keep_id, speaker_to_merge_id)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string(), "speaker_to_keep_id": speaker_to_keep_id, "speaker_to_merge_id": speaker_to_merge_id})),
+ )
+ })?;
+
+ Ok(JsonResponse(json!({"success": true})))
+}
+
+async fn get_similar_speakers_handler(
+ State(state): State<Arc<AppState>>,
+ Query(request): Query<GetSimilarSpeakersRequest>,
+) -> Result<JsonResponse<Vec<Speaker>>, (StatusCode, JsonResponse<Value>)> {
+ let speaker_id = request.speaker_id;
+ let limit = request.limit;
+
+ let similar_speakers = state
+ .db
+ .get_similar_speakers(speaker_id, limit)
+ .await
+ .map_err(|e| {
+ (
+ StatusCode::INTERNAL_SERVER_ERROR,
+ JsonResponse(json!({"error": e.to_string()})),
+ )
+ })?;
+
+ Ok(JsonResponse(similar_speakers))
+}
+
pub fn create_router() -> Router<Arc<AppState>> {
let cors = CorsLayer::new()
.allow_origin(Any)
@@ -1323,6 +1563,16 @@ pub fn create_router() -> Router<Arc<AppState>> {
.route("/raw_sql", post(execute_raw_sql))
.route("/add", post(add_to_database))
.route("/stream/frames", get(stream_frames_handler))
+ .route("/speakers/unnamed", get(get_unnamed_speakers_handler))
+ .route("/speakers/update", post(update_speaker_handler))
+ .route("/speakers/search", get(search_speakers_handler))
+ .route("/speakers/delete", post(delete_speaker_handler))
+ .route(
+ "/speakers/hallucination",
+ post(mark_as_hallucination_handler),
+ )
+ .route("/speakers/merge", post(merge_speakers_handler))
+ .route("/speakers/similar", get(get_similar_speakers_handler))
.route("/experimental/frames/merge", post(merge_frames_handler))
.layer(cors);
@@ -1452,6 +1702,12 @@ pub struct DeletePipeRequest {
pipe_id: String,
}
+#[derive(Deserialize, Debug)]
+struct MergeSpeakersRequest {
+ speaker_to_keep_id: i64,
+ speaker_to_merge_id: i64,
+}
+
/*
Curl commands for reference:
diff --git a/screenpipe-server/tests/db.rs b/screenpipe-server/tests/db.rs
index e5af27331..5a643eb5d 100644
--- a/screenpipe-server/tests/db.rs
+++ b/screenpipe-server/tests/db.rs
@@ -13,8 +13,6 @@ mod tests {
async fn setup_test_db() -> DatabaseManager {
let db = DatabaseManager::new("sqlite::memory:").await.unwrap();
-
-
db
}
@@ -50,6 +48,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -89,6 +88,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -106,6 +106,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -152,6 +153,7 @@ mod tests {
Some("window"),
None,
None,
+ None,
)
.await
.unwrap();
@@ -169,6 +171,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -228,6 +231,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -245,6 +249,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -345,14 +350,14 @@ mod tests {
// After inserting both audio transcriptions, let's check all audio entries
let all_audio = db
- .search_audio("", 100, 0, None, None, None, None)
+ .search_audio("", 100, 0, None, None, None, None, None)
.await
.unwrap();
println!("All audio entries: {:?}", all_audio);
// Then try specific search
let audio_results = db
- .search_audio("2", 100, 0, None, None, None, None)
+ .search_audio("2", 100, 0, None, None, None, None, None)
.await
.unwrap();
println!("Audio results for '2': {:?}", audio_results);
@@ -372,6 +377,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -391,6 +397,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -414,6 +421,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -432,6 +440,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -495,8 +504,10 @@ mod tests {
.await
.unwrap();
+ let audio_chunk_id2 = db.insert_audio_chunk("test_audio2.mp4").await.unwrap();
+
db.insert_audio_transcription(
- audio_chunk_id,
+ audio_chunk_id2,
"Hello from audio 2",
1,
"",
@@ -521,6 +532,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -543,6 +555,7 @@ mod tests {
None,
None,
None,
+ None,
)
.await
.unwrap();
@@ -616,4 +629,246 @@ mod tests {
println!("Speaker: {:?}", speaker);
assert_eq!(speaker.name, "test name");
}
+
+ #[tokio::test]
+ async fn test_get_unnamed_speakers() {
+ let db = setup_test_db().await;
+
+ // insert n audio chunks for each speaker
+ for n in 0..3 {
+ let speaker = db.insert_speaker(&vec![n as f32; 512]).await.unwrap();
+ for i in 0..=n {
+ let audio_chunk_id = db
+ .insert_audio_chunk(&format!("audio{}{}", n, i))
+ .await
+ .unwrap();
+ db.insert_audio_transcription(
+ audio_chunk_id,
+ "test transcription",
+ 0,
+ "",
+ &AudioDevice::new("test".to_string(), DeviceType::Output),
+ Some(speaker.id),
+ )
+ .await
+ .unwrap();
+ }
+ }
+
+ // insert a speaker with a name
+ let speaker = db.insert_speaker(&vec![0.1; 512]).await.unwrap();
+ db.update_speaker_name(speaker.id, "test name")
+ .await
+ .unwrap();
+
+ // Get unnamed speakers
+ let unnamed_speakers = db.get_unnamed_speakers(10, 0, None).await.unwrap();
+
+ assert_eq!(unnamed_speakers.len(), 3, "Should find 3 unnamed speakers");
+
+ let speaker_3 = &unnamed_speakers[0];
+ assert_eq!(speaker_3.id, 3);
+ assert!(speaker_3.name.is_empty());
+
+ // speaker 2 should be next
+ let speaker_2 = &unnamed_speakers[1];
+ assert_eq!(speaker_2.id, 2);
+ assert!(speaker_2.name.is_empty());
+
+ // speaker 1 should be last
+ let speaker_1 = &unnamed_speakers[2];
+ assert_eq!(speaker_1.id, 1);
+ assert!(speaker_1.name.is_empty());
+
+ let metadata: serde_json::Value =
+ serde_json::from_str(&speaker_3.metadata).expect("Metadata should be valid JSON");
+
+ let audio_samples = metadata["audio_samples"]
+ .as_array()
+ .expect("Audio Samples should be an array");
+
+ println!("Audio samples: {:?}", audio_samples);
+
+ assert_eq!(audio_samples.len(), 3);
+ }
+
+ #[tokio::test]
+ async fn test_get_unnamed_speakers_with_speaker_ids() {
+ let db = setup_test_db().await;
+
+ // insert n audio chunks for each speaker
+ for n in 0..3 {
+ let speaker = db.insert_speaker(&vec![n as f32; 512]).await.unwrap();
+ for i in 0..=n {
+ let audio_chunk_id = db
+ .insert_audio_chunk(&format!("audio{}{}", n, i))
+ .await
+ .unwrap();
+ db.insert_audio_transcription(
+ audio_chunk_id,
+ "test transcription",
+ 0,
+ "",
+ &AudioDevice::new("test".to_string(), DeviceType::Output),
+ Some(speaker.id),
+ )
+ .await
+ .unwrap();
+ }
+ }
+
+ // insert a speaker with a name
+ let speaker = db.insert_speaker(&vec![0.1; 512]).await.unwrap();
+ db.update_speaker_name(speaker.id, "test name")
+ .await
+ .unwrap();
+
+ // Get unnamed speakers
+ let unnamed_speakers = db
+ .get_unnamed_speakers(10, 0, Some(vec![speaker.id, 1, 2, 3]))
+ .await
+ .unwrap();
+
+ assert_eq!(unnamed_speakers.len(), 3, "Should find 3 unnamed speakers");
+ // ensure the order is correct
+ assert_eq!(unnamed_speakers[0].id, 3);
+ assert_eq!(unnamed_speakers[1].id, 2);
+ assert_eq!(unnamed_speakers[2].id, 1);
+ }
+
+ #[tokio::test]
+ async fn test_merge_speakers() {
+ let db = setup_test_db().await;
+
+ let speaker_1 = db.insert_speaker(&vec![0.1; 512]).await.unwrap();
+ db.update_speaker_name(speaker_1.id, "speaker 1")
+ .await
+ .unwrap();
+ let speaker_2 = db.insert_speaker(&vec![0.2; 512]).await.unwrap();
+ db.update_speaker_name(speaker_2.id, "speaker 2")
+ .await
+ .unwrap();
+
+ // for each speaker, insert 2 audio chunks
+ for speaker in [speaker_1.clone(), speaker_2.clone()] {
+ for i in 0..2 {
+ let audio_chunk_id = db
+ .insert_audio_chunk(&format!("audio{}{}", speaker.id, i))
+ .await
+ .unwrap();
+
+ // insert audio transcription
+ db.insert_audio_transcription(
+ audio_chunk_id,
+ "test transcription",
+ 0,
+ "",
+ &AudioDevice::new("test".to_string(), DeviceType::Output),
+ Some(speaker.id),
+ )
+ .await
+ .unwrap();
+ }
+ }
+
+ db.merge_speakers(speaker_1.id, speaker_2.id).await.unwrap();
+
+ let speakers = db.search_speakers("").await.unwrap();
+ assert_eq!(speakers.len(), 1);
+ assert_eq!(speakers[0].name, "speaker 1");
+ }
+
+ #[tokio::test]
+ async fn test_search_speakers() {
+ let db = setup_test_db().await;
+
+ let speaker = db.insert_speaker(&vec![0.1; 512]).await.unwrap();
+ db.update_speaker_name(speaker.id, "test name")
+ .await
+ .unwrap();
+
+ let speakers = db.search_speakers("test").await.unwrap();
+ assert_eq!(speakers.len(), 1);
+ assert_eq!(speakers[0].name, "test name");
+ }
+
+ #[tokio::test]
+ async fn test_delete_speaker() {
+ let db = setup_test_db().await;
+
+ let speaker = db.insert_speaker(&vec![0.1; 512]).await.unwrap();
+
+ let audio_chunk_id = db.insert_audio_chunk("test_audio.mp4").await.unwrap();
+ db.insert_audio_transcription(
+ audio_chunk_id,
+ "test transcription",
+ 0,
+ "",
+ &AudioDevice::new("test".to_string(), DeviceType::Output),
+ Some(speaker.id),
+ )
+ .await
+ .unwrap();
+
+ db.delete_speaker(speaker.id).await.unwrap();
+
+ let speakers = db.search_speakers("").await.unwrap();
+ assert_eq!(speakers.len(), 0);
+
+ // make sure audio_chunks are deleted
+ let audio_chunks = db.get_audio_chunks_for_speaker(speaker.id).await.unwrap();
+ assert_eq!(audio_chunks.len(), 0);
+ }
+
+ #[tokio::test]
+ async fn test_mark_speaker_as_hallucination() {
+ let db = setup_test_db().await;
+
+ let speaker = db.insert_speaker(&vec![0.1; 512]).await.unwrap();
+ db.mark_speaker_as_hallucination(speaker.id).await.unwrap();
+
+ let speakers = db.search_speakers("").await.unwrap();
+ assert_eq!(speakers.len(), 0);
+ }
+
+ #[tokio::test]
+ async fn test_get_similar_speakers() {
+ let db = setup_test_db().await;
+
+ // Create first speaker with audio data
+ let speaker = db.insert_speaker(&vec![0.1; 512]).await.unwrap();
+ db.update_speaker_name(speaker.id, "test name")
+ .await
+ .unwrap();
+ let audio_chunk_id = db.insert_audio_chunk("test_audio1.mp4").await.unwrap();
+ db.insert_audio_transcription(
+ audio_chunk_id,
+ "test transcription",
+ 0,
+ "",
+ &AudioDevice::new("test".to_string(), DeviceType::Output),
+ Some(speaker.id),
+ )
+ .await
+ .unwrap();
+
+ // Create second speaker with audio data
+ let speaker2 = db.insert_speaker(&vec![0.2; 512]).await.unwrap();
+ db.update_speaker_name(speaker2.id, "name").await.unwrap();
+ let audio_chunk_id2 = db.insert_audio_chunk("test_audio2.mp4").await.unwrap();
+ db.insert_audio_transcription(
+ audio_chunk_id2,
+ "test transcription",
+ 0,
+ "",
+ &AudioDevice::new("test".to_string(), DeviceType::Output),
+ Some(speaker2.id),
+ )
+ .await
+ .unwrap();
+
+ let similar_speakers = db.get_similar_speakers(speaker.id, 10).await.unwrap();
+ assert_eq!(similar_speakers.len(), 1);
+ assert_eq!(similar_speakers[0].id, speaker2.id);
+ }
}
diff --git a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin
index 200bb7f8b..27dc6d78e 100755
Binary files a/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin and b/screenpipe-vision/bin/ui_monitor-aarch64-apple-darwin differ