TagSpaces is an offline, open source, document manager with tagging support
Tag files with tags from the tag library (#2235)
Stanimir8382e8e95a49
diff --git a/package-lock.json b/package-lock.jsonindex 5e018be03..f677ce31c 100644--- a/package-lock.json+++ b/package-lock.json@@ -202,7 +202,7 @@"yarn": "please-use-npm"},"optionalDependencies": {- "@tagspacespro/tagspacespro": "5.0.108"+ "@tagspacespro/tagspacespro": "5.0.110"}},"node_modules/@adobe/css-tools": {@@ -15883,9 +15883,9 @@}},"node_modules/@tagspacespro/tagspacespro": {- "version": "5.0.108",- "resolved": "https://npm.pkg.github.com/download/@tagspacespro/tagspacespro/5.0.108/e3e6c01bb629ad0e5a9caba5cce1a281b97c9e25",- "integrity": "sha512-KdBu+Bdww0tSOL5V90ZMxXgxKZ5ly/o37d17teHZft3I+hlR11pQvPRINS8wGSGk/Ck4VZBRgetyYAfXFz0PUg==",+ "version": "5.0.110",+ "resolved": "https://npm.pkg.github.com/download/@tagspacespro/tagspacespro/5.0.110/1d011518ff1ae811c8805da5f2ab0c565192fc22",+ "integrity": "sha512-RpopO6tRujlmTkXEUFiLvcixTnwU1KB1MO59kr9TChtmuuTXsrHIujDlKZaCTSCLHnVtC0aXPGDIYURBFUE+QQ==","license": "Proprietary","optional": true},diff --git a/package.json b/package.jsonindex e121c5e81..aeb4a0b45 100644--- a/package.json+++ b/package.json@@ -243,7 +243,7 @@"zod-to-json-schema": "^3.24.1"},"optionalDependencies": {- "@tagspacespro/tagspacespro": "5.0.108"+ "@tagspacespro/tagspacespro": "5.0.110"},"devDependencies": {"@electron/notarize": "^2.3.2",diff --git a/src/renderer/components/AiPropertiesTab.tsx b/src/renderer/components/AiPropertiesTab.tsxindex f4b34e20c..7e05dc10f 100644--- a/src/renderer/components/AiPropertiesTab.tsx+++ b/src/renderer/components/AiPropertiesTab.tsx@@ -40,13 +40,8 @@ function AiPropertiesTab(props: Props) {return (<Box position="relative" display="inline-flex"><AiGenDescButton />- <span style={{ marginLeft: AppConfig.defaultSpaceBetweenButtons }}>- <AiGenTagsButton />- </span>{openedEntry.meta.description && (- <span style={{ marginLeft: AppConfig.defaultSpaceBetweenButtons }}>- <AiGenTagsButton fromDescription={true} />- </span>+ <AiGenTagsButton fromDescription={true} />)}</Box>);diff --git a/src/renderer/components/EditDescriptionButtons.tsx b/src/renderer/components/EditDescriptionButtons.tsxindex 13fe41b75..93ac7eba8 100644--- a/src/renderer/components/EditDescriptionButtons.tsx+++ b/src/renderer/components/EditDescriptionButtons.tsx@@ -6,7 +6,7 @@ import AiGenTagsButton from '-/components/chat/AiGenTagsButton';import { useFilePropertiesContext } from '-/hooks/useFilePropertiesContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { Pro } from '-/pro';-import { ButtonGroup } from '@mui/material';+import { Box, ButtonGroup } from '@mui/material';import React from 'react';import { useTranslation } from 'react-i18next';@@ -101,32 +101,23 @@ const EditDescriptionButtons: React.FC = () => {<ProTooltiptooltip={'Add AI generated description based on the file content'}>- <AiGenDescButton- disabled={!Pro}- style={{- borderTopRightRadius: openedEntry.meta.description- ? 0- : AppConfig.defaultCSSRadius,- borderBottomRightRadius: openedEntry.meta.description- ? 0- : AppConfig.defaultCSSRadius,- }}- />+ <AiGenDescButton disabled={!Pro} variant="outlined" /></ProTooltip>{openedEntry.meta.description && (- <ProTooltip- tooltip={'Add AI generated tags based on the description'}- >- <AiGenTagsButton- disabled={!Pro}- style={{- borderTopLeftRadius: 0,- borderBottomLeftRadius: 0,- }}- fromDescription={true}- variant="outlined"- />- </ProTooltip>+ <>+ <Box+ style={{ marginLeft: AppConfig.defaultSpaceBetweenButtons }}+ ></Box>+ <ProTooltip+ tooltip={'Add AI generated tags based on the description'}+ >+ <AiGenTagsButton+ disabled={!Pro}+ fromDescription={true}+ variant="outlined"+ />+ </ProTooltip>+ </>)}</ButtonGroup></div>diff --git a/src/renderer/components/EntryContainer.tsx b/src/renderer/components/EntryContainer.tsxindex 1bba1f0ea..f14531bba 100644--- a/src/renderer/components/EntryContainer.tsx+++ b/src/renderer/components/EntryContainer.tsx@@ -502,16 +502,16 @@ function EntryContainer() {};const savingFile = (force = false) => {- if (- fileViewer &&- fileViewer.current &&- fileViewer.current.contentWindow &&- // @ts-ignore- fileViewer.current.contentWindow.getContent- ) {- // @ts-ignore- const fileContent = fileViewer.current.contentWindow.getContent();- try {+ try {+ if (+ fileViewer &&+ fileViewer.current &&+ fileViewer.current.contentWindow &&+ // @ts-ignore+ fileViewer.current.contentWindow.getContent+ ) {+ // @ts-ignore+ const fileContent = fileViewer.current.contentWindow.getContent();//check if file is changedif (fileChanged || force) {isSavingInProgress.current = true;@@ -528,10 +528,10 @@ function EntryContainer() {isSavingInProgress.current = false;});}- } catch (e) {- isSavingInProgress.current = false;- console.debug('function getContent not exist for video file:', e);}+ } catch (e) {+ isSavingInProgress.current = false;+ console.debug('function getContent not exist for file:', e);}};diff --git a/src/renderer/components/chat/AiGenDescButton.tsx b/src/renderer/components/chat/AiGenDescButton.tsxindex 84550077c..3f10eab05 100644--- a/src/renderer/components/chat/AiGenDescButton.tsx+++ b/src/renderer/components/chat/AiGenDescButton.tsx@@ -16,25 +16,22 @@**/-import AppConfig from '-/AppConfig';import TsButton, { TSButtonProps } from '-/components/TsButton';+import { useAiGenerationDialogContext } from '-/components/dialogs/hooks/useAiGenerationDialogContext';import { TabNames } from '-/hooks/EntryPropsTabsContextProvider';import { useChatContext } from '-/hooks/useChatContext';import { useFilePropertiesContext } from '-/hooks/useFilePropertiesContext';+import { useIOActionsContext } from '-/hooks/useIOActionsContext';import { useNotificationContext } from '-/hooks/useNotificationContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';-import { formatDateTime } from '@tagspaces/tagspaces-common/misc';-import { extractFileExtension } from '@tagspaces/tagspaces-common/paths';+import { AppDispatch } from '-/reducers/app';+import { actions as SettingsActions } from '-/reducers/settings';+import { TS } from '-/tagspaces.namespace';+import { ButtonGroup } from '@mui/material';import { useState } from 'react';import { useTranslation } from 'react-i18next';+import { useDispatch } from 'react-redux';import { AIIcon } from '../CommonIcons';-import {- actions as SettingsActions,- getDefaultAIProvider,-} from '-/reducers/settings';-import { AppDispatch } from '-/reducers/app';-import { useDispatch, useSelector } from 'react-redux';-import { AIProvider } from '-/components/chat/ChatTypes';type Props = TSButtonProps & {};@@ -42,80 +39,87 @@ function AiGenDescButton(props: Props) {const { t } = useTranslation();const { style, disabled } = props;const dispatch: AppDispatch = useDispatch();- const defaultAiProvider: AIProvider = useSelector(getDefaultAIProvider);+ //const defaultAiProvider: AIProvider = useSelector(getDefaultAIProvider);const { openedEntry } = useOpenedEntryContext();- const { generate, getEntryModel } = useChatContext();+ const { setDescriptionChange } = useIOActionsContext();+ const { descriptionGenerate } = useChatContext();const { setDescription, saveDescription } = useFilePropertiesContext();const { showNotification } = useNotificationContext();+ const { openAiGenerationDialog } = useAiGenerationDialogContext();const [isLoading, setIsLoading] = useState<boolean>(false);- const openedEntryModel = getEntryModel(openedEntry.name, defaultAiProvider);- if (- !openedEntry ||- !openedEntryModel ||- ![- ...AppConfig.aiSupportedFiletypes.text,- ...AppConfig.aiSupportedFiletypes.image,- ].includes(openedEntry.extension)- ) {+ //const openedEntryModel = getEntryModel(openedEntry?.name, defaultAiProvider);+ if (!openedEntry) {+ //|| !openedEntryModel) {return null;}- const ext = extractFileExtension(openedEntry.name).toLowerCase();-- function handleGenerationResults(response) {+ function handleGenerationResults(entries: TS.FileSystemEntry[]) {//console.log('newOllamaMessage response:' + response);- setIsLoading(false);- if (response) {- dispatch(SettingsActions.setEntryContainerTab(TabNames.descriptionTab));- response =- response +- '\\\n *Generated with AI on ' +- formatDateTime(new Date(), true) +- '* \n';- if (openedEntry.meta.description) {- setDescription(openedEntry.meta.description + '\n *** \n' + response);- } else {- setDescription(response);- }- saveDescription();- //openEntry(openedEntry.path).then(() => {- showNotification(- 'Description for ' + openedEntry.name + ' generated by an AI.',- );+ if (entries) {+ setIsLoading(false);+ const promises = entries.map((entry) => {+ if (entry) {+ if (entry.uuid === openedEntry.uuid) {+ dispatch(+ SettingsActions.setEntryContainerTab(TabNames.descriptionTab),+ );+ setDescription(entry.meta.description);+ return saveDescription();+ } else {+ return setDescriptionChange(entry, entry.meta.description);+ }+ }+ return false;+ });+ Promise.all(promises).then((results) => {+ if (results && results.every((result) => result)) {+ showNotification(+ 'Description for ' + openedEntry.name + ' generated by an AI.',+ );+ }+ });}}return (- <TsButton- loading={isLoading}- disabled={isLoading || disabled}- tooltip="Uses currently configured AI model to generate description for this file"- startIcon={<AIIcon />}- data-tid="generateDescriptionAITID"- style={style}- onClick={() => {- setIsLoading(true);- if (AppConfig.aiSupportedFiletypes.image.includes(ext)) {- generate(- 'image',- 'description',- openedEntryModel.name,- openedEntry,- ).then((results) => handleGenerationResults(results));- } else if (AppConfig.aiSupportedFiletypes.text.includes(ext)) {- generate(- ext === 'pdf' ? 'image' : 'text',- 'summary',- openedEntryModel.name,- openedEntry,- ).then((results) => handleGenerationResults(results));- }- }}- >- {t('core:generateDescription')}- </TsButton>+ <ButtonGroup>+ <TsButton+ loading={isLoading}+ disabled={isLoading || disabled}+ // tooltip="Uses currently configured AI model to generate description for this file"+ // startIcon={<AIIcon />}+ data-tid="generateDescriptionAITID"+ style={{+ borderTopRightRadius: 0,+ borderBottomRightRadius: 0,+ paddingLeft: 28,+ }}+ onClick={() => {+ setIsLoading(true);+ descriptionGenerate([openedEntry]).then((entries) => {+ handleGenerationResults(entries);+ });+ }}+ >+ {t('core:generateDescription')}+ </TsButton>+ <TsButton+ // tooltip={t('core:openGenSettings')}+ aria-label={t('core:openGenSettings')}+ data-tid="fileContainerPrevFile"+ onClick={() => {+ openAiGenerationDialog('summary');+ }}+ style={{+ borderTopLeftRadius: 0,+ borderBottomLeftRadius: 0,+ }}+ >+ <AIIcon fontSize="small" />+ </TsButton>+ </ButtonGroup>);}diff --git a/src/renderer/components/chat/AiGenTagsButton.tsx b/src/renderer/components/chat/AiGenTagsButton.tsxindex a7fcb2598..b99102422 100644--- a/src/renderer/components/chat/AiGenTagsButton.tsx+++ b/src/renderer/components/chat/AiGenTagsButton.tsx@@ -19,27 +19,18 @@import AppConfig from '-/AppConfig';import TsButton, { TSButtonProps } from '-/components/TsButton';import { AIProvider } from '-/components/chat/ChatTypes';-import { TabNames } from '-/hooks/EntryPropsTabsContextProvider';+import { useAiGenerationDialogContext } from '-/components/dialogs/hooks/useAiGenerationDialogContext';import { useChatContext } from '-/hooks/useChatContext';-import {- actions as SettingsActions,- getTagColor,- getTagTextColor,-} from '-/reducers/settings';-import { useNotificationContext } from '-/hooks/useNotificationContext';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';-import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';import { getDefaultAIProvider } from '-/reducers/settings';import { TS } from '-/tagspaces.namespace';+import { ButtonGroup } from '@mui/material';import { ButtonPropsVariantOverrides } from '@mui/material/Button';import { OverridableStringUnion } from '@mui/types';-import { extractFileExtension } from '@tagspaces/tagspaces-common/paths';import { useState } from 'react';import { useTranslation } from 'react-i18next';-import { useDispatch, useSelector } from 'react-redux';+import { useSelector } from 'react-redux';import { AIIcon } from '../CommonIcons';-import { AppDispatch } from '-/reducers/app';-import { getTagColors } from '-/services/taglibrary-utils';type Props = TSButtonProps & {variant?: OverridableStringUnion<@@ -53,23 +44,13 @@ type Props = TSButtonProps & {};function AiGenTagsButton(props: Props) {- const {- fromDescription,- variant,- style,- disabled,- entries,- generationCompleted,- } = props;+ const { fromDescription, variant, disabled, entries, generationCompleted } =+ props;const { t } = useTranslation();- const dispatch: AppDispatch = useDispatch();const { openedEntry } = useOpenedEntryContext();+ const { tagsGenerate } = useChatContext();+ const { openAiGenerationDialog } = useAiGenerationDialogContext();const defaultAiProvider: AIProvider = useSelector(getDefaultAIProvider);- const defaultBackgroundColor = useSelector(getTagColor);- const defaultTextColor = useSelector(getTagTextColor);- const { generate, newChatMessage, getEntryModel } = useChatContext();- const { addTagsToFsEntry } = useTaggingActionsContext();- const { showNotification } = useNotificationContext();const [isLoading, setIsLoading] = useState<boolean>(false);@@ -90,94 +71,52 @@ function AiGenTagsButton(props: Props) {}const handleGeneration = () => {- const promises = generateEntries.map((entry) => {- const entryModel = getEntryModel(entry.name, defaultAiProvider);- const ext = extractFileExtension(entry.name).toLowerCase();- setIsLoading(true);- if (fromDescription && entry.meta.description) {- return newChatMessage(- entry.meta.description,- false,- 'user',- 'tags',- defaultAiProvider.defaultTextModel,- false,- [],- false,- ).then((results) => handleGenerationResults(entry, results));- } else if (AppConfig.aiSupportedFiletypes.image.includes(ext)) {- return generate('image', 'tags', entryModel.name, entry).then(- (results) => handleGenerationResults(entry, results),- );- } else if (AppConfig.aiSupportedFiletypes.text.includes(ext)) {- return generate('text', 'tags', entryModel.name, entry).then(- (results) => handleGenerationResults(entry, results),- );- }- return Promise.resolve(false);- });- Promise.all(promises).then(() => {- showNotification('Tags generated by an AI.');+ setIsLoading(true);+ tagsGenerate(generateEntries, fromDescription).then(() => {+ setIsLoading(false);if (generationCompleted) {generationCompleted();}});};- function handleGenerationResults(entry, response): Promise<boolean> {- console.log('newOllamaMessage response:' + response);- setIsLoading(false);- if (response) {- try {- const tags: TS.Tag[] = response.map((tag) => {- const tagTitle = tag.toLowerCase().split(' ')[0];- return {- title: tagTitle,- ...getTagColors(tagTitle, defaultTextColor, defaultBackgroundColor),- };- });- const uniqueTags = tags.filter(- (tag, index, self) =>- index === self.findIndex((o) => o.title === tag.title),- );- /* const regex = /\{([^}]+)\}/g;- const tags: TS.Tag[] = [...response.matchAll(regex)].map((match) => {- const tagTitle = match[1].trim().replace(/^,|,$/g, '').toLowerCase();- return {- title: tagTitle,- ...getTagColors(tagTitle, defaultTextColor, defaultBackgroundColor),- };- });*/- return addTagsToFsEntry(entry, uniqueTags).then(() => {- dispatch(- SettingsActions.setEntryContainerTab(TabNames.propertiesTab),- );- return true;- });- // showNotification('Tags for ' + entry.name + ' generated by an AI.');- } catch (e) {- console.error('parse response ' + response, e);- }- }- return Promise.resolve(false);- }-return (- <TsButton- loading={isLoading}- disabled={isLoading || disabled}- tooltip="Uses currently configured AI model to generate tags for this file"- startIcon={<AIIcon />}- style={style}- data-tid="generateTagsAITID"- onClick={handleGeneration}- variant={variant}- >- {t(- 'core:' +- (fromDescription ? 'generateTagsFromDescription' : 'generateTags'),- )}- </TsButton>+ <ButtonGroup>+ <TsButton+ loading={isLoading}+ disabled={isLoading || disabled}+ // tooltip="Uses currently configured AI model to generate tags for this file"+ // startIcon={<AIIcon />}+ data-tid="generateTagsAITID"+ onClick={handleGeneration}+ variant={variant}+ style={{+ borderTopRightRadius: 0,+ borderBottomRightRadius: 0,+ paddingLeft: 28,+ }}+ >+ {t(+ 'core:' ++ (fromDescription ? 'generateTagsFromDescription' : 'generateTags'),+ )}+ </TsButton>+ <TsButton+ // tooltip={t('core:openGenSettings')}+ aria-label={t('core:openGenSettings')}+ data-tid="fileContainerPrevFile"+ onClick={() => {+ openAiGenerationDialog('tags');+ }}+ style={{+ borderTopLeftRadius: 0,+ borderBottomLeftRadius: 0,+ }}+ variant={variant}+ >+ <AIIcon fontSize="small" />+ </TsButton>+ </ButtonGroup>);}diff --git a/src/renderer/components/chat/OllamaClient.ts b/src/renderer/components/chat/OllamaClient.tsindex c9fc9eb6a..b421953ba 100644--- a/src/renderer/components/chat/OllamaClient.ts+++ b/src/renderer/components/chat/OllamaClient.ts@@ -86,13 +86,20 @@ export async function newOllamaMessage(}}return undefined; // Return undefined for the streaming case if there's no final message content+ })+ .catch((e) => {+ console.error('newOllamaMessage error', e);});} else {// Handle the case where `stream` is false or undefined- const response: ChatResponse = await ollama.chat(- msg as ChatRequest & { stream?: false },- );- return response.message.content;+ try {+ const response: ChatResponse = await ollama.chat(+ msg as ChatRequest & { stream?: false },+ );+ return response.message.content;+ } catch (e) {+ console.error('newOllamaMessage error', e);+ }}}return undefined;diff --git a/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx b/src/renderer/components/dialogs/AddRemoveTagsDialog.tsxindex 7955e9f56..323e47def 100644--- a/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx+++ b/src/renderer/components/dialogs/AddRemoveTagsDialog.tsx@@ -39,11 +39,9 @@ import {extractDirectoryName,extractFileName,} from '@tagspaces/tagspaces-common/paths';-import React, { useReducer, useRef, useState } from 'react';+import { useReducer, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import TagsSelect from '../TagsSelect';-import AiGenTagsButton from '-/components/chat/AiGenTagsButton';-import { Pro } from '-/pro';interface Props {open: boolean;@@ -204,12 +202,12 @@ function AddRemoveTagsDialog(props: Props) {>{t('core:cancel')}</TsButton>- <AiGenTagsButton+ {/* <AiGenTagsButtondisabled={!Pro}entries={selected}variant="outlined"generationCompleted={() => onCloseDialog()}- />+ /> */}<TsButtondata-tid="cleanTagsMultipleEntries"disabled={selected.length < 1}diff --git a/src/renderer/components/dialogs/hooks/AiGenerationDialogContextProvider.tsx b/src/renderer/components/dialogs/hooks/AiGenerationDialogContextProvider.tsxnew file mode 100644index 000000000..0d4e8f905--- /dev/null+++ b/src/renderer/components/dialogs/hooks/AiGenerationDialogContextProvider.tsx@@ -0,0 +1,87 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2024-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import ConfirmDialog from '-/components/dialogs/ConfirmDialog';+import { Pro } from '-/pro';+import React, { createContext, useMemo, useReducer, useRef } from 'react';+import { useTranslation } from 'react-i18next';++type AiGenerationDialogContextData = {+ openAiGenerationDialog: (optionSelected?: generateOptionType) => void;+ closeAiGenerationDialog: () => void;+};++export const AiGenerationDialogContext =+ createContext<AiGenerationDialogContextData>({+ openAiGenerationDialog: undefined,+ closeAiGenerationDialog: undefined,+ });++export type AiGenerationDialogContextProviderProps = {+ children: React.ReactNode;+};++export type generateOptionType = 'tags' | 'summary' | 'analyseImages';++export const AiGenerationDialogContextProvider = ({+ children,+}: AiGenerationDialogContextProviderProps) => {+ const { t } = useTranslation();+ const open = useRef<boolean>(false);+ const option = useRef<generateOptionType>(undefined);+ const AiGenerationDialog = Pro && Pro.UI ? Pro.UI.AiGenerationDialog : false;+ const [ignored, forceUpdate] = useReducer((x) => x + 1, 0, undefined);++ function openDialog(optionSelected: generateOptionType = undefined) {+ open.current = true;+ option.current = optionSelected;+ forceUpdate();+ }++ function closeDialog() {+ open.current = false;+ forceUpdate();+ }++ const context = useMemo(() => {+ return {+ openAiGenerationDialog: openDialog,+ closeAiGenerationDialog: closeDialog,+ };+ }, []);++ return (+ <AiGenerationDialogContext.Provider value={context}>+ {AiGenerationDialog ? (+ <AiGenerationDialog+ open={open.current}+ onClose={closeDialog}+ option={option.current}+ />+ ) : (+ <ConfirmDialog+ open={true}+ onClose={() => {}}+ title={t('core:thisFunctionalityIsAvailableInPro')}+ confirmCallback={() => {}}+ />+ )}+ {children}+ </AiGenerationDialogContext.Provider>+ );+};diff --git a/src/renderer/components/dialogs/hooks/useAiGenerationDialogContext.tsx b/src/renderer/components/dialogs/hooks/useAiGenerationDialogContext.tsxnew file mode 100644index 000000000..fe6241dee--- /dev/null+++ b/src/renderer/components/dialogs/hooks/useAiGenerationDialogContext.tsx@@ -0,0 +1,6 @@+import { useContext } from 'react';++import { AiGenerationDialogContext } from '-/components/dialogs/hooks/AiGenerationDialogContextProvider';++export const useAiGenerationDialogContext = () =>+ useContext(AiGenerationDialogContext);diff --git a/src/renderer/containers/DialogsRoot.tsx b/src/renderer/containers/DialogsRoot.tsxindex e79066f44..ad0ad1c49 100644--- a/src/renderer/containers/DialogsRoot.tsx+++ b/src/renderer/containers/DialogsRoot.tsx@@ -39,6 +39,7 @@ import {DownloadUrlContextProvider,DownloadUrlDialogContext,} from '-/components/dialogs/hooks/DownloadUrlDialogContextProvider';+import { AiGenerationDialogContextProvider } from '-/components/dialogs/hooks/AiGenerationDialogContextProvider';export type DialogsRootProps = {children: React.ReactNode;@@ -58,21 +59,23 @@ function DialogsRoot({ children }: DialogsRootProps) {<LicenseDialogContextProvider><ThirdPartyLibsDialogContextProvider><AboutDialogContextProvider>- <OnboardingDialogContextProvider>- <KeyboardDialogContextProvider>- <LinkDialogContextProvider>- <ProTeaserDialogContextProvider>- <SettingsDialogContextProvider>- <ResolveConflictContextProvider>- <DownloadUrlContextProvider>- {children}- </DownloadUrlContextProvider>- </ResolveConflictContextProvider>- </SettingsDialogContextProvider>- </ProTeaserDialogContextProvider>- </LinkDialogContextProvider>- </KeyboardDialogContextProvider>- </OnboardingDialogContextProvider>+ <AiGenerationDialogContextProvider>+ <OnboardingDialogContextProvider>+ <KeyboardDialogContextProvider>+ <LinkDialogContextProvider>+ <ProTeaserDialogContextProvider>+ <SettingsDialogContextProvider>+ <ResolveConflictContextProvider>+ <DownloadUrlContextProvider>+ {children}+ </DownloadUrlContextProvider>+ </ResolveConflictContextProvider>+ </SettingsDialogContextProvider>+ </ProTeaserDialogContextProvider>+ </LinkDialogContextProvider>+ </KeyboardDialogContextProvider>+ </OnboardingDialogContextProvider>+ </AiGenerationDialogContextProvider></AboutDialogContextProvider></ThirdPartyLibsDialogContextProvider></LicenseDialogContextProvider>diff --git a/src/renderer/containers/TsAuth.tsx b/src/renderer/containers/TsAuth.tsxindex e5ab679ec..c74b766c0 100644--- a/src/renderer/containers/TsAuth.tsx+++ b/src/renderer/containers/TsAuth.tsx@@ -61,7 +61,7 @@ const TsAuth: React.FC<any> = (props) => {<AmplifyTotpSetupheaderText="TagSpaces Time-Based One-Time Password Login"slot="totp-setup"- issuer={t('core:name') + ' ' + window.location.hostname}+ issuer={t('core:appName') + ' ' + window.location.hostname}// user={props.user}/><AmplifySignUpdiff --git a/src/renderer/hooks/ChatProvider.tsx b/src/renderer/hooks/ChatProvider.tsxindex dee4a6e38..5caf200ae 100644--- a/src/renderer/hooks/ChatProvider.tsx+++ b/src/renderer/hooks/ChatProvider.tsx@@ -35,8 +35,11 @@ import { useSelectedEntriesContext } from '-/hooks/useSelectedEntriesContext';import { Pro } from '-/pro';import { actions as AppActions, AppDispatch } from '-/reducers/app';import {+ actions as SettingsActions,getDefaultAIProvider,getEntryContainerTab,+ getTagColor,+ getTagTextColor,} from '-/reducers/settings';import { extractPDFcontent } from '-/services/thumbsgenerator';import { toBase64Image } from '-/services/utils-io';@@ -57,10 +60,10 @@ import React, {useMemo,useReducer,useRef,- useState,} from 'react';import { useTranslation } from 'react-i18next';import { useDispatch, useSelector } from 'react-redux';+import { formatDateTime } from '@tagspaces/tagspaces-common/misc';import { useIOActionsContext } from '-/hooks/useIOActionsContext';import { TabNames } from '-/hooks/EntryPropsTabsContextProvider';import {@@ -71,7 +74,14 @@ import {} from '-/components/chat/OllamaClient';import { Ollama, ChatRequest, ModelResponse } from 'ollama';import { zodToJsonSchema } from 'zod-to-json-schema';-import { z } from 'zod';+import { getTagColors, getTagLibrary } from '-/services/taglibrary-utils';+import { useTaggingActionsContext } from '-/hooks/useTaggingActionsContext';+import {+ getZodDescription,+ getZodTags,+ StructuredDataProps,+} from '-/services/zodObjects';+import { generateOptionType } from '-/components/dialogs/hooks/AiGenerationDialogContextProvider';/*export type TimelineItem = {request: string;@@ -86,7 +96,7 @@ type ChatData = {//openedEntryModel: ModelResponse;chatHistoryItems: ChatItem[];isTyping: boolean;- refreshOllamaModels: (modelName?: string) => void;+ refreshOllamaModels: (modelName?: string) => Promise<boolean>;setModel: (model: ModelResponse | string) => Promise<boolean>;setImages: (imagesPaths: string[]) => void;removeImage: (uuid: string) => void;@@ -122,6 +132,16 @@ type ChatData = {checkProviderAlive: (providerUrl: string) => Promise<boolean>;getOllamaClient: (ollamaApiUrl: string) => Promise<Ollama>;getEntryModel: (entryName: string, aiProvider: AIProvider) => ModelResponse;+ tagsGenerate: (+ generateEntries: TS.FileSystemEntry[],+ fromDescription?: boolean,+ ) => Promise<boolean>;+ descriptionGenerate: (+ generateEntries: TS.FileSystemEntry[],+ ) => Promise<TS.FileSystemEntry[]>;+ generationSettings: GenerationSettings;+ setGenerationSettings: (genSettings: any) => void;+ resetGenerationSettings: (option: generateOptionType) => void;};export const ChatContext = createContext<ChatData>({@@ -151,16 +171,32 @@ export const ChatContext = createContext<ChatData>({checkProviderAlive: undefined,getOllamaClient: undefined,getEntryModel: undefined,+ tagsGenerate: undefined,+ descriptionGenerate: undefined,+ generationSettings: undefined,+ setGenerationSettings: undefined,+ resetGenerationSettings: undefined,});export type ChatContextProviderProps = {children: React.ReactNode;};+export type GenerationSettings = {+ option: generateOptionType;+ maxTags: number;+ maxChars: number;+ tagsFromLibrary: boolean;+ tagGroupsIds: string[];+ fromDescription: boolean;+ structuredDataProps: StructuredDataProps;+};+export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {const { t } = useTranslation();const { showNotification } = useNotificationContext();const { deleteDirectory } = useIOActionsContext();+ const { addTagsToFsEntry } = useTaggingActionsContext();const { openFileUploadDialog } = useFileUploadDialogContext();const { selectedEntries } = useSelectedEntriesContext();const { currentLocation } = useCurrentLocationContext();@@ -169,7 +205,12 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {const models = useRef<ModelResponse[]>([]);const defaultAiProvider: AIProvider = useSelector(getDefaultAIProvider);const selectedTabName = useSelector(getEntryContainerTab);+ const defaultBackgroundColor = useSelector(getTagColor);+ const defaultTextColor = useSelector(getTagTextColor);const currentModel = useRef<ModelResponse>(undefined);+ const generationSettings = useRef<GenerationSettings>(+ getGenerationSettings(),+ );/*const openedEntryModel = useRef<ModelResponse>(getOpenedEntryModel(openedEntry?.name, defaultAiProvider),);*/@@ -183,6 +224,8 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {Pro && Pro.UI ? Pro.UI.DEFAULT_SYSTEM_PROMPT : false;const SUMMARIZE_PROMPT = Pro && Pro.UI ? Pro.UI.SUMMARIZE_PROMPT : false;const IMAGE_DESCRIPTION = Pro && Pro.UI ? Pro.UI.IMAGE_DESCRIPTION : false;+ const IMAGE_DESCRIPTION_STRUCTURED =+ Pro && Pro.UI ? Pro.UI.IMAGE_DESCRIPTION_STRUCTURED : false;const TEXT_DESCRIPTION = Pro && Pro.UI ? Pro.UI.TEXT_DESCRIPTION : false;const GENERATE_TAGS = Pro && Pro.UI ? Pro.UI.GENERATE_TAGS : false;const GENERATE_IMAGE_TAGS =@@ -239,6 +282,23 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {}}, [openedEntry]);+ function getGenerationSettings(+ option: generateOptionType = 'tags',+ ): GenerationSettings {+ const item = localStorage.getItem(Pro.keys.generationSettingsKey);+ const storedObj = item ? JSON.parse(item) : {};+ return {+ option: option,+ structuredDataProps: { name: true, summary: true },+ maxTags: 4,+ maxChars: undefined,+ tagsFromLibrary: false,+ fromDescription: false,+ tagGroupsIds: [],+ ...storedObj,+ };+ }+async function getOllamaClient(ollamaApiUrl: string) {if (ollamaApiUrl) {try {@@ -348,9 +408,19 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {);}- function refreshOllamaModels(modelName = undefined) {+ /**+ * return true if model is loaded successful false otherwise+ */+ function checkOllamaModels(): Promise<boolean> {+ if (!models.current || models.current.length === 0) {+ return refreshOllamaModels();+ }+ return Promise.resolve(true);+ }++ function refreshOllamaModels(modelName = undefined): Promise<boolean> {if (defaultAiProvider) {- getOllamaModels(ollamaClient.current)+ return getOllamaModels(ollamaClient.current).then((m) => {if (m) {models.current = m;@@ -372,8 +442,10 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {if (success) {forceUpdate();}+ return success;});}+ return Promise.resolve(false);}function setModel(m: ModelResponse | string): Promise<boolean> {@@ -548,8 +620,7 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {onProgressHandler,).then((response) => {console.log('pullOllamaModel response:' + response);- refreshOllamaModels(newModelName);- return true;+ return refreshOllamaModels(newModelName);});/*return window.electronIO.ipcRenderer.invoke('pullOllamaModel', defaultAiProvider.url, {@@ -703,12 +774,28 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {} else {prompt = prompt.replace('{file_path}', '');}+ if (generationSettings.current.maxChars) {+ prompt = prompt.replace(+ '{max_chars}',+ 'max ' + generationSettings.current.maxChars + ' characters',+ );+ } else {+ prompt = prompt.replace('{max_chars}', '');+ }return prompt;}} else if (mode === 'description') {if (msg) {- return TEXT_DESCRIPTION.replace('{input_text}', msg);- } else if (IMAGE_DESCRIPTION) {+ return TEXT_DESCRIPTION.replace('{input_text}', msg).replace(+ '{max_chars}',+ generationSettings.current.maxChars+ ? 'max ' + generationSettings.current.maxChars + ' characters'+ : '',+ );+ } else {+ if (generationSettings.current.option === 'analyseImages') {+ return IMAGE_DESCRIPTION_STRUCTURED;+ }return IMAGE_DESCRIPTION.replace('{file_name}',openedEntry ? openedEntry.name : '',@@ -749,47 +836,23 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {};}, []);- const Tags = z.object({- topics: z.array(z.string()).max(4), // todo define generated tags maxLength in settings- });- const Description = z.object({- name: z.string(),- summary: z.string(),- });- const ObjectSchema = z.object({- name: z.string().describe('The name of the object'),- confidence: z- .number()- .min(0)- .max(1)- .describe('The confidence score of the object detection'),- attributes: z- .record(z.any())- .optional()- .describe('Additional attributes of the object'),- //attributes: z.string(),- });- const ImageDescription = z.object({- name: z.string().describe('The name of the Image'),- summary: z.string().describe('A concise summary of the image'),- objects: z- .array(ObjectSchema)- .describe('An array of objects detected in the image'),- scene: z.string().describe('The scene of the image'),- colors: z- .array(z.string())- .describe('An array of colors detected in the image'),- time_of_day: z- .enum(['Morning', 'Afternoon', 'Evening', 'Night', 'Unknown'])- .describe('The time of day the image was taken'),- setting: z- .enum(['Indoor', 'Outdoor', 'Unknown'])- .describe('The setting of the image'),- text_content: z- .string()- .optional()- .describe('Any text detected in the image'),- });+ function getTagsFromLibrary(): string[] {+ const tagsFromLibrary: string[] = [];+ if (+ generationSettings.current.tagsFromLibrary &&+ generationSettings.current.tagGroupsIds.length > 0+ ) {+ const tagLibrary: TS.TagGroup[] = getTagLibrary();+ generationSettings.current.tagGroupsIds.forEach((tagGroupId) => {+ const tagGroup = tagLibrary.find((tg) => tg.uuid === tagGroupId);+ if (tagGroup) {+ tagsFromLibrary.push(...tagGroup.children.map((tag) => tag.title));+ }+ });+ }+ return tagsFromLibrary;+ }+/*** @param msg If the messages array is empty, the model will be loaded into memory.* @param unload If the messages array is empty and the keep_alive parameter is set to 0, a model will be unloaded from memory.@@ -838,16 +901,37 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {}let format = undefined;if (mode === 'tags') {+ const tagsFromLibrary = getTagsFromLibrary();+ if (tagsFromLibrary.length > 0) {+ format = {+ format: zodToJsonSchema(+ getZodTags(generationSettings.current.maxTags, tagsFromLibrary),+ ),+ };+ }if (imgArray.length > 0) {- format = { format: zodToJsonSchema(ImageDescription) };+ format = {+ format: zodToJsonSchema(+ getZodDescription(generationSettings.current.structuredDataProps),+ ),+ };} else {- format = { format: zodToJsonSchema(Tags) };+ format = {+ format: zodToJsonSchema(+ getZodTags(generationSettings.current.maxTags, tagsFromLibrary),+ ),+ };}} else if (mode === 'description' || mode === 'summary') {- if (imgArray.length > 0) {- format = { format: zodToJsonSchema(ImageDescription) };- } else {- format = { format: zodToJsonSchema(Description) };+ if (+ imgArray.length > 0 &&+ generationSettings.current.option === 'analyseImages'+ ) {+ format = {+ format: zodToJsonSchema(+ getZodDescription(generationSettings.current.structuredDataProps),+ ),+ };}}const request: ChatRequest = {@@ -862,62 +946,113 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {request,chatMessageHandler,).then((apiResponse) => {+ console.log('apiResponse:' + apiResponse);+ if (apiResponse === undefined) {+ showNotification('Error check if Ollama service is alive');+ return undefined;+ }isTyping.current = false;if (msg && includeHistory) {saveHistoryItems();}if (mode === 'tags') {if (imgArray.length > 0) {- const response = ImageDescription.parse(JSON.parse(apiResponse));- const tags = response.objects.map((obj) => obj.name);+ const response = JSON.parse(apiResponse); // ImageDescription.parse(JSON.parse(apiResponse));+ const tags = response.objects+ ? response.objects.map((obj) => obj.name)+ : [];if (response.time_of_day && response.time_of_day !== 'Unknown') {tags.push(response.time_of_day);}if (response.setting && response.setting !== 'Unknown') {tags.push(response.setting);}+ if (response.topics) {+ tags.push(response.topics);+ }return [...tags, ...response.colors];} else {- const response = Tags.parse(JSON.parse(apiResponse));- return response.topics;+ let tags: string[] = [];+ try {+ const response = JSON.parse(apiResponse);+ tags = response.topics;+ } catch (e) {+ console.log('JSON.parse error for:' + apiResponse, e);+ if (apiResponse) {+ tags = apiResponse.split(' ');+ }+ //const zodTags = getZodTags(generationSettings.current.maxTags);+ //response = zodTags.parse(JSON.parse(apiResponse));+ }++ return tags.slice(0, generationSettings.current.maxTags);}} else if (mode === 'description' || mode === 'summary') {- if (imgArray.length > 0) {- const response = ImageDescription.parse(JSON.parse(apiResponse));- const objArray = response.objects.map(- (obj) =>- '\n\n > ##### Name: \n\n' +- obj.name +- '\n\n > ##### Attributes: \n\n' +- obj.attributes,- );- return (- '### Name: \n\n' +- response.name +- '\n\n ### Objects: \n\n' +- objArray.join('\n\n') +- '\n\n ### Scene: \n\n' +- response.scene +- '\n\n ### Colors:\n\n' +- response.colors +- '\n\n ### Summary:\n\n' +- response.summary +- '\n\n ### Day Time:\n\n' +- response.time_of_day +- '\n\n ### Setting:\n\n' +- response.setting +- (response.text_content- ? '\n\n ### Content:\n\n' + response.text_content- : '')- );- } else {- const response = Description.parse(JSON.parse(apiResponse));- return (- '### Name: \n\n' +- response.name +- '\n\n ### Summary:\n\n' ++ if (format) {+ const response = JSON.parse(apiResponse);+ const arrReturn = [];+ if (+ generationSettings.current.structuredDataProps.name &&+ response.name+ ) {+ arrReturn.push('**Name:** ' + response.name);+ }+ if (+ generationSettings.current.structuredDataProps.objects &&+ response.objects+ ) {+ arrReturn.push(+ response.objects.map(+ (obj) =>+ (obj.name ? '\n\n> > **Object Name:** ' + obj.name : '') ++ (obj.attributes+ ? '\n\n> > **Attributes:** ' ++ JSON.stringify(obj.attributes, null, 4).replace(+ /[{}\[\]]/g,+ '',+ )+ : ''),+ ),+ );+ }++ if (+ generationSettings.current.structuredDataProps.scene &&+ response.scene+ ) {+ arrReturn.push('**Scene:** ' + response.scene);+ }+ if (+ generationSettings.current.structuredDataProps.colors &&+ response.colors+ ) {+ arrReturn.push('**Colors:** ' + response.colors);+ }+ if (+ generationSettings.current.structuredDataProps.summary &&response.summary- );+ ) {+ arrReturn.push('**Summary:** ' + response.summary);+ }+ if (+ generationSettings.current.structuredDataProps.time_of_day &&+ response.time_of_day+ ) {+ arrReturn.push('**Day Time:** ' + response.time_of_day);+ }+ if (+ generationSettings.current.structuredDataProps.settings &&+ response.setting+ ) {+ arrReturn.push('**Setting:** ' + response.setting);+ }+ if (+ response.text_content &&+ generationSettings.current.structuredDataProps.text_content+ ) {+ arrReturn.push('**Content:** ' + response.text_content);+ }+ return arrReturn.join('\n\n') + '\n\n';}}return stream ? true : apiResponse;@@ -1000,6 +1135,195 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {return Promise.resolve(undefined);}+ function descriptionGenerate(+ generateEntries: TS.FileSystemEntry[],+ ): Promise<TS.FileSystemEntry[]> {+ return checkOllamaModels().then((success) => {+ if (success) {+ const promises = generateEntries.map((entry) => {+ const entryModel: ModelResponse = getEntryModel(+ entry.name,+ defaultAiProvider,+ );+ if (entryModel) {+ const ext = extractFileExtension(entry.name).toLowerCase();+ if (AppConfig.aiSupportedFiletypes.image.includes(ext)) {+ return generate(+ 'image',+ 'description',+ entryModel.name,+ entry,+ ).then((results) => handleGenDescResults(entry, results));+ } else if (AppConfig.aiSupportedFiletypes.text.includes(ext)) {+ return generate(+ 'text',+ 'description',+ entryModel.name,+ entry,+ ).then((results) => handleGenDescResults(entry, results));+ }+ } else {+ showNotification(+ 'Error No Model selected or there is a problem with Ollama service conection', //or Description generation not supported for:' + entry.name,+ );+ return Promise.resolve(undefined);+ }+ return Promise.resolve(entry);+ });+ return Promise.all(promises);+ } else {+ showNotification(+ 'Ollama Models not loaded. Check if Ollama service is alive.',+ );+ return undefined;+ }+ });+ }++ function handleGenDescResults(entry, response): TS.FileSystemEntry {+ if (response) {+ const generatedDesc =+ response ++ '\\\n *Generated with AI on ' ++ formatDateTime(new Date(), true) ++ '* \n';+ //dispatch(SettingsActions.setEntryContainerTab(TabNames.descriptionTab));+ entry.meta.description = entry.meta?.description+ ? entry.meta.description + '\n---\n' + generatedDesc+ : generatedDesc;++ return entry;+ }+ return undefined;+ }++ function tagsGenerate(+ generateEntries: TS.FileSystemEntry[],+ fromDescription: boolean = false,+ ): Promise<boolean> {+ return checkOllamaModels().then((success) => {+ if (success) {+ const promises = generateEntries.map((entry) => {+ const entryModel: ModelResponse = getEntryModel(+ entry.name,+ defaultAiProvider,+ );+ if (entryModel) {+ const ext = extractFileExtension(entry.name).toLowerCase();+ if (+ (fromDescription || generationSettings.current.fromDescription) &&+ entry.meta.description+ ) {+ return newChatMessage(+ entry.meta.description,+ false,+ 'user',+ 'tags',+ defaultAiProvider.defaultTextModel,+ false,+ [],+ false,+ ).then((results) => handleGenTagsResults(entry, results));+ } else if (AppConfig.aiSupportedFiletypes.image.includes(ext)) {+ return generate('image', 'tags', entryModel.name, entry).then(+ (results) => handleGenTagsResults(entry, results),+ );+ } else if (AppConfig.aiSupportedFiletypes.text.includes(ext)) {+ return generate('text', 'tags', entryModel.name, entry).then(+ (results) => handleGenTagsResults(entry, results),+ );+ }+ } else {+ showNotification('Tags generation not supported for:' + entry.name);+ }++ return Promise.resolve(false);+ });+ return Promise.all(promises).then((results) => {+ if (results && results.every((result) => result)) {+ showNotification('Tags generated by an AI.');+ return true;+ } else {+ return false;+ }+ });+ } else {+ showNotification(+ 'Ollama Models not loaded. Check if Ollama service is alive.',+ );+ return false;+ }+ });+ }++ function handleGenTagsResults(entry, response): Promise<boolean> {+ //console.log('newOllamaMessage response:' + response);+ if (response && response.length > 0) {+ try {+ const tags: TS.Tag[] = response.map((tag) => {+ if (tag) {+ const tagTitle = tag+ .replace(/[-/=[\]{}!@#$%^&*(),.?":{}|<>]/g, ' ')+ .toLowerCase()+ .split(' ')+ .filter((str) => str.trim() !== '')+ .slice(0, 3)+ .join('-');+ if (tagTitle) {+ return {+ title: tagTitle,+ ...getTagColors(+ tagTitle,+ defaultTextColor,+ defaultBackgroundColor,+ ),+ };+ }+ }+ return undefined;+ });+ const uniqueTags = tags.filter(+ (tag, index, self) =>+ tag && // Exclude undefined or null tags+ index === self.findIndex((t) => t?.title === tag.title),+ );+ /* const regex = /\{([^}]+)\}/g;+ const tags: TS.Tag[] = [...response.matchAll(regex)].map((match) => {+ const tagTitle = match[1].trim().replace(/^,|,$/g, '').toLowerCase();+ return {+ title: tagTitle,+ ...getTagColors(tagTitle, defaultTextColor, defaultBackgroundColor),+ };+ });*/+ return addTagsToFsEntry(entry, uniqueTags).then(() => {+ dispatch(+ SettingsActions.setEntryContainerTab(TabNames.propertiesTab),+ );+ return true;+ });+ // showNotification('Tags for ' + entry.name + ' generated by an AI.');+ } catch (e) {+ console.error('newOllamaMessage response ' + response, e);+ }+ } else {+ console.error('no response ' + response);+ }+ return Promise.resolve(false);+ }++ function setGenerationSettings(genSettings: any) {+ generationSettings.current = {+ ...generationSettings.current,+ ...genSettings,+ };+ forceUpdate();+ }++ function resetGenerationSettings(option: generateOptionType) {+ generationSettings.current = getGenerationSettings(option);+ forceUpdate();+ }+const context = useMemo(() => {return {isTyping: isTyping.current,@@ -1008,6 +1332,7 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {currentModel: currentModel.current,//openedEntryModel: openedEntryModel.current,chatHistoryItems: chatHistoryItems.current,+ generationSettings: generationSettings.current,refreshOllamaModels,getHistoryFilePath,setModel,@@ -1028,6 +1353,10 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {checkProviderAlive,getOllamaClient,getEntryModel,+ tagsGenerate,+ descriptionGenerate,+ setGenerationSettings,+ resetGenerationSettings,};}, [defaultAiProvider,@@ -1035,8 +1364,8 @@ export const ChatContextProvider = ({ children }: ChatContextProviderProps) => {models.current,images.current,currentModel.current,- //openedEntryModel.current,chatHistoryItems.current,+ generationSettings.current,openedEntry,selectedEntries,]);diff --git a/src/renderer/hooks/FilePropertiesContextProvider.tsx b/src/renderer/hooks/FilePropertiesContextProvider.tsxindex da02fb71e..41ffd1646 100644--- a/src/renderer/hooks/FilePropertiesContextProvider.tsx+++ b/src/renderer/hooks/FilePropertiesContextProvider.tsx@@ -44,7 +44,7 @@ type FilePropertiesContextData = {setEditDescriptionMode: (editMode: boolean) => void;setSaveDescriptionConfirmOpened: (open: boolean) => void;setDescription: (description: string) => void;- saveDescription: () => void;+ saveDescription: () => Promise<boolean>;};export const FilePropertiesContext = createContext<FilePropertiesContextData>({@@ -101,7 +101,7 @@ export const FilePropertiesContextProvider = ({}}, [openedEntry]);- const saveDescription = () => {+ function saveDescription(): Promise<boolean> {if (lastOpenedFile.current !== undefined) {const location = findLocation(lastOpenedFile.current.locationID);if (!location || location.isReadOnly) {@@ -116,17 +116,19 @@ export const FilePropertiesContextProvider = ({isDescriptionChanged.current = false;isEditMode.current = false;forceUpdate();- setDescriptionChange(+ return setDescriptionChange(lastOpenedFile.current,lastOpenedFile.current.meta?.description,).then(() => {if (lastOpenedFile.current.path !== openedEntry.path) {lastOpenedFile.current = { ...openedEntry };}+ return true;// description.current = openedEntry.meta?.description;});}- };+ return Promise.resolve(false);+ }function setDescription(d: string) {lastOpenedFile.current = {diff --git a/src/renderer/hooks/TaggingActionsContextProvider.tsx b/src/renderer/hooks/TaggingActionsContextProvider.tsxindex 5c4eb117f..2265eea5a 100644--- a/src/renderer/hooks/TaggingActionsContextProvider.tsx+++ b/src/renderer/hooks/TaggingActionsContextProvider.tsx@@ -167,8 +167,7 @@ export const TaggingActionsContextProvider = ({const { t } = useTranslation();const { findLocation, currentLocation, persistTagsInSidecarFile } =useCurrentLocationContext();- const { tagGroups, reflectTagLibraryChanged, broadcast } =- useEditedTagLibraryContext();+ const { tagGroups, reflectTagLibraryChanged } = useEditedTagLibraryContext();const {createLocationTagGroup,editLocationTagGroup,diff --git a/src/renderer/locales/en/core.json b/src/renderer/locales/en/core.jsonindex 8a4eba77d..e1887aa0f 100644--- a/src/renderer/locales/en/core.json+++ b/src/renderer/locales/en/core.json@@ -147,7 +147,7 @@"colorChangesToAllTags": "Apply color changes to all tags of the group","delete": "Delete","enableGlobalKeyboardShortcuts": "Enable global keyboard shortcuts",- "name": "TagSpaces",+ "appName": "TagSpaces","fileOperations": "File Operations","addRemoveTags": "Add / Remove Tags","openFile": "Open File",@@ -917,5 +917,29 @@"confirmHistoryDeletion": "Do you want to delete the AI-chat history?","doubleClickToOpen": "Double-click to open","tip": "Tip",+ "generateSummary": "Generate Summary",+ "analyseImages": "Extended analyses for images",+ "fromTagLibrary": "from Tag Library",+ "fromTagLibraryHelp": "use predefined tags from Tag Library only",+ "aiOperationTitle": "AI Operations",+ "aiGeneration": "AI Generation",+ "name": "Name",+ "summary": "Summary",+ "objects": "Objects",+ "scene": "Scene",+ "colors": "Colors",+ "time_of_day": "Time Of Day",+ "setting": "Settings",+ "text_content": "Text content in image",+ "maxTags": "Max Tags",+ "maxTagsHelp": "Max Tags to generate",+ "fromDescription": "From Description",+ "fromDescriptionHelp": "Generate Tags From Description",+ "limitSummary": "Limit Summary",+ "limitSummaryHelp": "Used for short or long summary",+ "maxChars": "Max characters for Summary",+ "maxCharsHelp": "Limit the characters of the generated summary",+ "aiGenSelectedEntries": "AI generation settings",+ "saveSettings": "Save Settings","-": "-"}diff --git a/src/renderer/perspectives/grid/components/MainToolbar.tsx b/src/renderer/perspectives/grid/components/MainToolbar.tsxindex 3bcc17e8f..74fa79504 100644--- a/src/renderer/perspectives/grid/components/MainToolbar.tsx+++ b/src/renderer/perspectives/grid/components/MainToolbar.tsx@@ -18,10 +18,9 @@import React from 'react';import { alpha, useTheme } from '@mui/material/styles';-import { useDispatch, useSelector } from 'react-redux';+import { useSelector } from 'react-redux';import { saveAs } from 'file-saver';-import { Toolbar, Box, Divider, Badge } from '@mui/material/';-import Tooltip from '-/components/Tooltip';+import { Toolbar, Box, Divider } from '@mui/material/';import TsIconButton from '-/components/TsIconButton';import SortingIcon from '@mui/icons-material/SwapVerticalCircle';import ShareIcon from '@mui/icons-material/Share';@@ -33,20 +32,18 @@ import {DownloadIcon,TagIcon,DeleteIcon,-} from '-/components/CommonIcons';-import CopyIcon from '@mui/icons-material/FileCopy';-import ExportIcon from '@mui/icons-material/AssignmentReturn';-import {ParentFolderIcon,FolderPropertiesIcon,PerspectiveSettingsIcon,+ AIIcon,} from '-/components/CommonIcons';+import CopyIcon from '@mui/icons-material/FileCopy';+import ExportIcon from '@mui/icons-material/AssignmentReturn';import AppConfig from '-/AppConfig';import { Pro } from '-/pro';import { ProTooltip } from '-/components/HelperComponents';import ZoomComponent from '-/components/ZoomComponent';import { getKeyBindingObject } from '-/reducers/settings';-import { actions as AppActions, AppDispatch } from '-/reducers/app';import { useTranslation } from 'react-i18next';import { useOpenedEntryContext } from '-/hooks/useOpenedEntryContext';import { useDirectoryContentContext } from '-/hooks/useDirectoryContentContext';@@ -56,6 +53,7 @@ import { usePerspectiveSettingsContext } from '-/hooks/usePerspectiveSettingsConimport { useDeleteMultipleEntriesDialogContext } from '-/components/dialogs/hooks/useDeleteMultipleEntriesDialogContext';import { useSortedDirContext } from '-/perspectives/grid/hooks/useSortedDirContext';import { TabNames } from '-/hooks/EntryPropsTabsContextProvider';+import { useAiGenerationDialogContext } from '-/components/dialogs/hooks/useAiGenerationDialogContext';interface Props {prefixDataTID?: string;@@ -80,8 +78,8 @@ function MainToolbar(props: Props) {openShareFilesDialog,} = props;- const { haveLocalSetting, setSettings, saveSettings } =- usePerspectiveSettingsContext();+ const { haveLocalSetting } = usePerspectiveSettingsContext();+ const { openAiGenerationDialog } = useAiGenerationDialogContext();const { nativeDragModeEnabled, setNativeDragModeEnabled } =useSortedDirContext();@@ -92,7 +90,6 @@ function MainToolbar(props: Props) {useDirectoryContentContext();const { selectedEntries } = useSelectedEntriesContext();const keyBindings = useSelector(getKeyBindingObject);- //const dispatch: AppDispatch = useDispatch();const { currentLocation, readOnlyMode } = useCurrentLocationContext();const { openDeleteMultipleEntriesDialog } =useDeleteMultipleEntriesDialogContext();@@ -188,6 +185,16 @@ function MainToolbar(props: Props) {<TagIcon /></TsIconButton>)}+ {!readOnlyMode && (+ <TsIconButton+ tooltip={t('core:aiGenSelectedEntries')}+ aria-label={t('core:aiGenSelectedEntries')}+ data-tid={prefixDataTID + 'PerspectiveAiGenTID'}+ onClick={() => openAiGenerationDialog()}+ >+ <AIIcon />+ </TsIconButton>+ )}{!readOnlyMode && (<TsIconButtontooltip={t('core:copyMoveSelectedEntries')}diff --git a/src/renderer/services/zodObjects.ts b/src/renderer/services/zodObjects.tsnew file mode 100644index 000000000..feb33d2ee--- /dev/null+++ b/src/renderer/services/zodObjects.ts@@ -0,0 +1,104 @@+/**+ * TagSpaces - universal file and folder organizer+ * Copyright (C) 2025-present TagSpaces GmbH+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License (version 3) as+ * published by the Free Software Foundation.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ */++import { z } from 'zod';+export type StructuredDataProps = {+ name?: boolean;+ summary?: boolean;+ objects?: boolean;+ scene?: boolean;+ colors?: boolean;+ time_of_day?: boolean;+ settings?: boolean;+ text_content?: boolean;+ topics?: boolean;+};++export const getZodTags = (max = 4, tagsArray: string[] = []) => {+ if (tagsArray.length > 0) {+ const [firstTag, ...restTags] = tagsArray;+ return z.object({+ topics: z+ .array(z.enum([firstTag, ...restTags]))+ .min(1)+ .max(max)+ .describe('The predefined topics'),+ });+ }+ return z.object({+ topics: z+ .array(z.string())+ .min(1)+ .max(max)+ .describe('The predefined topics'),+ });+};+/*export const Description = z.object({+ name: z.string(),+ summary: z.string(),+});*/+const ObjectSchema = z.object({+ name: z.string().describe('The name of the object'),+ confidence: z+ .number()+ .min(0)+ .max(1)+ .describe('The confidence score of the object detection'),+ attributes: z+ .record(z.any())+ .optional()+ .describe('Additional attributes of the object'),+ //attributes: z.string(),+});+export const imageDescriptionObj = {+ name: z.string().describe('The name of the Image'),+ summary: z.string().describe('A concise summary of the image'),+ objects: z+ .array(ObjectSchema)+ .describe('An array of objects detected in the image'),+ scene: z.string().describe('The scene of the image'),+ colors: z+ .array(z.string())+ .describe('An array of colors detected in the image'),+ time_of_day: z+ .enum(['Morning', 'Afternoon', 'Evening', 'Night', 'Unknown'])+ .describe('The time of day the image was taken'),+ setting: z+ .enum(['Indoor', 'Outdoor', 'Unknown'])+ .describe('The setting of the image'),+ text_content: z+ .string()+ .optional()+ .describe('Any text detected in the image'),+};++export const getZodDescription = (options: StructuredDataProps) =>+ z.object({+ ...(options.name && { name: imageDescriptionObj.name }),+ ...(options.summary && { summary: imageDescriptionObj.summary }),+ ...(options.objects && { objects: imageDescriptionObj.objects }),+ ...(options.scene && { scene: imageDescriptionObj.scene }),+ ...(options.colors && { colors: imageDescriptionObj.colors }),+ ...(options.time_of_day && {+ time_of_day: imageDescriptionObj.time_of_day,+ }),+ ...(options.settings && { setting: imageDescriptionObj.setting }),+ ...(options.text_content && {+ text_content: imageDescriptionObj.text_content,+ }),+ });