From e8b724c22bed4b6ed01e34ba661228c348f50378 Mon Sep 17 00:00:00 2001 From: "A.J. Shulman" Date: Tue, 22 Oct 2024 13:47:46 -0400 Subject: fixed websearch tool endpoint so it only returns displayable results in Dash; also fixed type checking but needs to be improved --- src/server/ApiManagers/AssistantManager.ts | 64 ++++++++++++++++++++++++++---- 1 file changed, 57 insertions(+), 7 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/server/ApiManagers/AssistantManager.ts b/src/server/ApiManagers/AssistantManager.ts index 8447a4934..d7b72bac7 100644 --- a/src/server/ApiManagers/AssistantManager.ts +++ b/src/server/ApiManagers/AssistantManager.ts @@ -9,7 +9,7 @@ */ import { Readability } from '@mozilla/readability'; -import axios from 'axios'; +import axios, { AxiosResponse } from 'axios'; import { spawn } from 'child_process'; import * as fs from 'fs'; import { writeFile } from 'fs'; @@ -115,29 +115,79 @@ export default class AssistantManager extends ApiManager { }, }); - // Register Google Web Search Results API route register({ method: Method.POST, subscription: '/getWebSearchResults', secureHandler: async ({ req, res }) => { const { query, max_results } = req.body; - try { - // Fetch search results using Google Custom Search API - const response = await customsearch.cse.list({ + const MIN_VALID_RESULTS_RATIO = 0.75; // 3/4 threshold + let startIndex = 1; // Start at the first result initially + let validResults: any[] = []; + + const fetchSearchResults = async (start: number) => { + return customsearch.cse.list({ q: query, cx: process.env._CLIENT_GOOGLE_SEARCH_ENGINE_ID, key: process.env._CLIENT_GOOGLE_API_KEY, safe: 'active', num: max_results, + start, // This controls which result index the search starts from }); + }; + + const filterResultsByXFrameOptions = async (results: any[]) => { + const filteredResults = await Promise.all( + results.map(async result => { + try { + const urlResponse: AxiosResponse = await axios.head(result.url, { timeout: 5000 }); + const xFrameOptions = urlResponse.headers['x-frame-options']; + if (xFrameOptions && xFrameOptions.toUpperCase() === 'SAMEORIGIN') { + return result; + } + } catch (error) { + console.error(`Error checking x-frame-options for URL: ${result.url}`, error); + } + return null; // Exclude the result if it doesn't match + }) + ); + return filteredResults.filter(result => result !== null); // Remove null results + }; - const results = + try { + // Fetch initial search results + let response = await fetchSearchResults(startIndex); + let initialResults = response.data.items?.map(item => ({ url: item.link, snippet: item.snippet, })) || []; - res.send({ results }); + // Filter the initial results + validResults = await filterResultsByXFrameOptions(initialResults); + + // If valid results are less than 3/4 of max_results, fetch more results + while (validResults.length < max_results * MIN_VALID_RESULTS_RATIO) { + // Increment the start index by the max_results to fetch the next set of results + startIndex += max_results; + response = await fetchSearchResults(startIndex); + + const additionalResults = + response.data.items?.map(item => ({ + url: item.link, + snippet: item.snippet, + })) || []; + + const additionalValidResults = await filterResultsByXFrameOptions(additionalResults); + validResults = [...validResults, ...additionalValidResults]; // Combine valid results + + // Break if no more results are available + if (additionalValidResults.length === 0 || response.data.items?.length === 0) { + break; + } + } + + // Return the filtered valid results + res.send({ results: validResults.slice(0, max_results) }); // Limit the results to max_results } catch (error) { console.error('Error performing web search:', error); res.status(500).send({ -- cgit v1.2.3-70-g09d2 From a99b38e4cdc4ec995cf2d56e94980987d6f31cbb Mon Sep 17 00:00:00 2001 From: "A.J. Shulman" Date: Wed, 30 Oct 2024 14:17:03 -0400 Subject: before changing the get result endpoint --- src/server/ApiManagers/AssistantManager.ts | 39 ++++++++++++++++++------------ src/server/chunker/pdf_chunker.py | 33 +++++++++++++------------ 2 files changed, 41 insertions(+), 31 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/server/ApiManagers/AssistantManager.ts b/src/server/ApiManagers/AssistantManager.ts index d7b72bac7..cfa95cb4e 100644 --- a/src/server/ApiManagers/AssistantManager.ts +++ b/src/server/ApiManagers/AssistantManager.ts @@ -495,10 +495,12 @@ function spawnPythonProcess(jobId: string, file_name: string, file_data: string) const requirementsPath = path.join(__dirname, '../chunker/requirements.txt'); const pythonScriptPath = path.join(__dirname, '../chunker/pdf_chunker.py'); + const outputDirectory = pathToDirectory(Directory.chunk_images); + function runPythonScript() { const pythonPath = process.platform === 'win32' ? path.join(venvPath, 'Scripts', 'python') : path.join(venvPath, 'bin', 'python3'); - const pythonProcess = spawn(pythonPath, [pythonScriptPath, jobId, file_name, file_data]); + const pythonProcess = spawn(pythonPath, [pythonScriptPath, jobId, file_name, file_data, outputDirectory]); let pythonOutput = ''; let stderrOutput = ''; @@ -510,23 +512,30 @@ function spawnPythonProcess(jobId: string, file_name: string, file_data: string) pythonProcess.stderr.on('data', data => { stderrOutput += data.toString(); const lines = stderrOutput.split('\n'); + stderrOutput = lines.pop() || ''; // Save the last partial line back to stderrOutput lines.forEach(line => { if (line.trim()) { - try { - const parsedOutput = JSON.parse(line); - if (parsedOutput.job_id && parsedOutput.progress !== undefined) { - jobProgress[parsedOutput.job_id] = { - step: parsedOutput.step, - progress: parsedOutput.progress, - }; - } else if (parsedOutput.progress !== undefined) { - jobProgress[jobId] = { - step: parsedOutput.step, - progress: parsedOutput.progress, - }; + if (line.startsWith('PROGRESS:')) { + const jsonString = line.substring('PROGRESS:'.length); + try { + const parsedOutput = JSON.parse(jsonString); + if (parsedOutput.job_id && parsedOutput.progress !== undefined) { + jobProgress[parsedOutput.job_id] = { + step: parsedOutput.step, + progress: parsedOutput.progress, + }; + } else if (parsedOutput.progress !== undefined) { + jobProgress[jobId] = { + step: parsedOutput.step, + progress: parsedOutput.progress, + }; + } + } catch (err) { + console.error('Error parsing progress JSON:', jsonString, err); } - } catch (err) { - console.error('Progress log from Python:', line, err); + } else { + // Log other stderr output + console.error('Python stderr:', line); } } }); diff --git a/src/server/chunker/pdf_chunker.py b/src/server/chunker/pdf_chunker.py index 4fe3b9dbf..7a3244fbc 100644 --- a/src/server/chunker/pdf_chunker.py +++ b/src/server/chunker/pdf_chunker.py @@ -54,8 +54,9 @@ def update_progress(job_id, step, progress_value): "step": step, "progress": progress_value } - print(json.dumps(progress_data), file=sys.stderr) # Use stderr for progress logs - sys.stderr.flush() # Ensure it's sent immediately + print(f"PROGRESS:{json.dumps(progress_data)}", file=sys.stderr) + sys.stderr.flush() + class ElementExtractor: @@ -664,7 +665,7 @@ class Document: Represents a document being processed, such as a PDF, handling chunking, embedding, and summarization. """ - def __init__(self, file_data: bytes, file_name: str, job_id: str): + def __init__(self, file_data: bytes, file_name: str, job_id: str, output_folder: str): """ Initialize the Document with file data, file name, and job ID. @@ -672,6 +673,7 @@ class Document: :param file_name: The name of the file being processed. :param job_id: The job ID associated with this document processing task. """ + self.output_folder = output_folder self.file_data = file_data self.file_name = file_name self.job_id = job_id @@ -680,14 +682,13 @@ class Document: self.chunks = [] # List to hold text and visual chunks self.num_pages = 0 # Number of pages in the document (if applicable) self.summary = "" # The generated summary for the document - self._process() # Start processing the document def _process(self): """ Process the document: extract chunks, embed them, and generate a summary. """ - pdf_chunker = PDFChunker(output_folder="output") # Initialize the PDF chunker + pdf_chunker = PDFChunker(output_folder=self.output_folder) self.chunks = asyncio.run(pdf_chunker.chunk_pdf(self.file_data, self.file_name, self.doc_id, self.job_id)) # Extract chunks self.num_pages = self._get_pdf_pages() # Get the number of pages in the document @@ -796,8 +797,7 @@ class Document: "doc_id": self.doc_id }, indent=2) # Convert the document's attributes to JSON format - -def process_document(file_data, file_name, job_id): +def process_document(file_data, file_name, job_id, output_folder): """ Top-level function to process a document and return the JSON output. @@ -806,28 +806,28 @@ def process_document(file_data, file_name, job_id): :param job_id: The job ID for this document processing task. :return: The processed document's data in JSON format. """ - new_document = Document(file_data, file_name, job_id) # Create a new Document object - return new_document.to_json() # Return the document's JSON data - + new_document = Document(file_data, file_name, job_id, output_folder) + return new_document.to_json() def main(): """ Main entry point for the script, called with arguments from Node.js. """ - if len(sys.argv) != 4: - print(json.dumps({"error": "Invalid arguments"}), file=sys.stderr) # Print error if incorrect number of arguments + if len(sys.argv) != 5: + print(json.dumps({"error": "Invalid arguments"}), file=sys.stderr) return - job_id = sys.argv[1] # Get the job ID from command-line arguments - file_name = sys.argv[2] # Get the file name from command-line arguments - file_data = sys.argv[3] # Get the base64-encoded file data from command-line arguments + job_id = sys.argv[1] + file_name = sys.argv[2] + file_data = sys.argv[3] + output_folder = sys.argv[4] # Get the output folder from arguments try: # Decode the base64 file data file_bytes = base64.b64decode(file_data) # Process the document - document_result = process_document(file_bytes, file_name, job_id) + document_result = process_document(file_bytes, file_name, job_id, output_folder) # Pass output_folder # Output the final result as JSON to stdout print(document_result) @@ -839,5 +839,6 @@ def main(): sys.stderr.flush() + if __name__ == "__main__": main() # Execute the main function when the script is run -- cgit v1.2.3-70-g09d2 From 07516f420ab38fbc63d54f3421bf33a493037ae8 Mon Sep 17 00:00:00 2001 From: "A.J. Shulman" Date: Wed, 30 Oct 2024 15:31:38 -0400 Subject: much better RAG with image retrieval fixed significantly and much faster (only saving images in one place and remembering where they are saved) --- src/server/ApiManagers/AssistantManager.ts | 54 +++++++++++------------------- src/server/chunker/pdf_chunker.py | 41 ++++++++++++----------- 2 files changed, 41 insertions(+), 54 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/server/ApiManagers/AssistantManager.ts b/src/server/ApiManagers/AssistantManager.ts index cfa95cb4e..4d2068014 100644 --- a/src/server/ApiManagers/AssistantManager.ts +++ b/src/server/ApiManagers/AssistantManager.ts @@ -23,6 +23,7 @@ import { AI_Document } from '../../client/views/nodes/chatbot/types/types'; import { Method } from '../RouteManager'; import { filesDirectory, publicDirectory } from '../SocketData'; import ApiManager, { Registration } from './ApiManager'; +import { getServerPath } from '../../client/util/reportManager/reportManagerUtils'; // Enumeration of directories where different file types are stored export enum Directory { @@ -349,47 +350,16 @@ export default class AssistantManager extends ApiManager { method: Method.GET, subscription: '/getResult/:jobId', secureHandler: async ({ req, res }) => { - const { jobId } = req.params; // Get the job ID from the URL parameters - // Check if the job result is available + const { jobId } = req.params; if (jobResults[jobId]) { const result = jobResults[jobId] as AI_Document & { status: string }; - // If the result contains image or table chunks, save the base64 data as image files if (result.chunks && Array.isArray(result.chunks)) { - await Promise.all( - result.chunks.map(chunk => { - if (chunk.metadata && (chunk.metadata.type === 'image' || chunk.metadata.type === 'table')) { - const files_directory = '/files/chunk_images/'; - const directory = path.join(publicDirectory, files_directory); - - // Ensure the directory exists or create it - if (!fs.existsSync(directory)) { - fs.mkdirSync(directory); - } - - const fileName = path.basename(chunk.metadata.file_path); // Get the file name from the path - const filePath = path.join(directory, fileName); // Create the full file path - - // Check if the chunk contains base64 encoded data - if (chunk.metadata.base64_data) { - // Decode the base64 data and write it to a file - const buffer = Buffer.from(chunk.metadata.base64_data, 'base64'); - fs.promises.writeFile(filePath, buffer).then(() => { - // Update the file path in the chunk's metadata - chunk.metadata.file_path = path.join(files_directory, fileName); - chunk.metadata.base64_data = undefined; // Remove the base64 data from the metadata - }); - } else { - console.warn(`No base64_data found for chunk: ${fileName}`); - } - } - }) - ); result.status = 'completed'; } else { result.status = 'pending'; } - res.json(result); // Send the result back to the client + res.json(result); } else { res.status(202).send({ status: 'pending' }); } @@ -417,7 +387,7 @@ export default class AssistantManager extends ApiManager { // If the chunk is an image or table, read the corresponding file and encode it as base64 if (chunk.metadata.type === 'image' || chunk.metadata.type === 'table') { try { - const filePath = serverPathToFile(Directory.chunk_images, chunk.metadata.file_path); // Get the file path + const filePath = path.join(pathToDirectory(Directory.chunk_images), chunk.metadata.file_path); // Get the file path readFileAsync(filePath).then(imageBuffer => { const base64Image = imageBuffer.toString('base64'); // Convert the image to base64 @@ -549,10 +519,24 @@ function spawnPythonProcess(jobId: string, file_name: string, file_data: string) jobProgress[jobId] = { step: 'Complete', progress: 100 }; } catch (err) { console.error('Error parsing final JSON result:', err); + jobResults[jobId] = { error: 'Failed to parse final result' }; } } else { console.error(`Python process exited with code ${code}`); - jobResults[jobId] = { error: 'Python process failed' }; + // Check if there was an error message in stderr + if (stderrOutput) { + // Try to parse the last line as JSON + const lines = stderrOutput.trim().split('\n'); + const lastLine = lines[lines.length - 1]; + try { + const errorOutput = JSON.parse(lastLine); + jobResults[jobId] = errorOutput; + } catch (err) { + jobResults[jobId] = { error: 'Python process failed' }; + } + } else { + jobResults[jobId] = { error: 'Python process failed' }; + } } }); } diff --git a/src/server/chunker/pdf_chunker.py b/src/server/chunker/pdf_chunker.py index 7a3244fbc..130987343 100644 --- a/src/server/chunker/pdf_chunker.py +++ b/src/server/chunker/pdf_chunker.py @@ -64,13 +64,15 @@ class ElementExtractor: A class that uses a YOLO model to extract tables and images from a PDF page. """ - def __init__(self, output_folder: str): + def __init__(self, output_folder: str, doc_id: str): """ Initializes the ElementExtractor with the output folder for saving images and the YOLO model. :param output_folder: Path to the folder where extracted elements will be saved. """ - self.output_folder = output_folder + self.doc_id = doc_id + self.output_folder = os.path.join(output_folder, doc_id) + os.makedirs(self.output_folder, exist_ok=True) self.model = YOLO('keremberke/yolov8m-table-extraction') # Load YOLO model for table extraction self.model.overrides['conf'] = 0.25 # Set confidence threshold for detection self.model.overrides['iou'] = 0.45 # Set Intersection over Union (IoU) threshold @@ -114,20 +116,18 @@ class ElementExtractor: # Save the full page with the red outline table_filename = f"table_page{page_num + 1}_{idx + 1}.png" + file_path_for_client = f"{self.doc_id}/{table_filename}" table_path = os.path.join(self.output_folder, table_filename) page_with_outline.save(table_path) - # Convert the full-page image with red outline to base64 - base64_data = self.image_to_base64(page_with_outline) - tables.append({ 'metadata': { "type": "table", "location": [x1 / img.width, y1 / img.height, x2 / img.width, y2 / img.height], - "file_path": table_path, + "file_path": file_path_for_client, "start_page": page_num, "end_page": page_num, - "base64_data": base64_data, + "base64_data": self.image_to_base64(page_with_outline) } }) @@ -173,21 +173,19 @@ class ElementExtractor: # Save the full page with the red outline image_filename = f"image_page{page_num + 1}_{img_index + 1}.png" + file_path_for_client = f"{self.doc_id}/{image_filename}" image_path = os.path.join(self.output_folder, image_filename) page_with_outline.save(image_path) - # Convert the full-page image with red outline to base64 - base64_data = self.image_to_base64(page_with_outline) - images.append({ 'metadata': { "type": "image", "location": [x1 / page.rect.width, y1 / page.rect.height, x2 / page.rect.width, y2 / page.rect.height], - "file_path": image_path, + "file_path": file_path_for_client, "start_page": page_num, "end_page": page_num, - "base64_data": base64_data, + "base64_data": self.image_to_base64(image) } }) @@ -269,7 +267,7 @@ class PDFChunker: The main class responsible for chunking PDF files into text and visual elements (tables/images). """ - def __init__(self, output_folder: str = "output", image_batch_size: int = 5) -> None: + def __init__(self, output_folder: str = "output", doc_id: str = '', image_batch_size: int = 5) -> None: """ Initializes the PDFChunker with an output folder and an element extractor for visual elements. @@ -279,7 +277,8 @@ class PDFChunker: self.client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY")) # Initialize the Anthropic API client self.output_folder = output_folder self.image_batch_size = image_batch_size # Batch size for image processing - self.element_extractor = ElementExtractor(output_folder) # Initialize the element extractor + self.doc_id = doc_id # Add doc_id + self.element_extractor = ElementExtractor(output_folder, doc_id) async def chunk_pdf(self, file_data: bytes, file_name: str, doc_id: str, job_id: str) -> List[Dict[str, Any]]: """ @@ -364,6 +363,7 @@ class PDFChunker: for j, elem in enumerate(batch, start=1): if j in summaries: elem['metadata']['text'] = re.sub(r'^(Image|Table):\s*', '', summaries[j]) + elem['metadata']['base64_data'] = '' processed_elements.append(elem) progress = ((i // image_batch_size) + 1) / total_batches * 100 # Calculate progress @@ -629,10 +629,11 @@ class PDFChunker: return summaries - except Exception: - #print(f"Error in batch_summarize_images: {str(e)}") - #print("Returning placeholder summaries") - return {number: "Error: No summary available" for number in images} + except Exception as e: + # Print errors to stderr so they don't interfere with JSON output + print(json.dumps({"error": str(e)}), file=sys.stderr) + sys.stderr.flush() + class DocumentType(Enum): """ @@ -688,7 +689,7 @@ class Document: """ Process the document: extract chunks, embed them, and generate a summary. """ - pdf_chunker = PDFChunker(output_folder=self.output_folder) + pdf_chunker = PDFChunker(output_folder=self.output_folder, doc_id=self.doc_id) # Initialize PDFChunker self.chunks = asyncio.run(pdf_chunker.chunk_pdf(self.file_data, self.file_name, self.doc_id, self.job_id)) # Extract chunks self.num_pages = self._get_pdf_pages() # Get the number of pages in the document @@ -823,6 +824,8 @@ def main(): output_folder = sys.argv[4] # Get the output folder from arguments try: + os.makedirs(output_folder, exist_ok=True) + # Decode the base64 file data file_bytes = base64.b64decode(file_data) -- cgit v1.2.3-70-g09d2 From 89424e0a8efc6cf3364a2fd1ffc85c9d0d837453 Mon Sep 17 00:00:00 2001 From: bobzel Date: Fri, 22 Nov 2024 10:27:33 -0500 Subject: added initial Firefly endpoint and hanged smartDrawHandler to generate an image and an svg. --- src/client/util/bezierFit.ts | 3 +- src/client/views/MainView.tsx | 32 ++++++++++++-- .../nodes/chatbot/chatboxcomponents/ChatBox.tsx | 3 +- src/client/views/pdf/AnchorMenu.tsx | 9 ++-- src/client/views/smartdraw/SmartDrawHandler.tsx | 29 ++++++------ src/server/ApiManagers/DataVizManager.ts | 2 +- src/server/ApiManagers/FireflyManager.ts | 51 ++++++++++++++++++++++ src/server/DashUploadUtils.ts | 3 +- src/server/index.ts | 3 +- webpack.config.js | 7 ++- 10 files changed, 113 insertions(+), 29 deletions(-) create mode 100644 src/server/ApiManagers/FireflyManager.ts (limited to 'src/server/ApiManagers') diff --git a/src/client/util/bezierFit.ts b/src/client/util/bezierFit.ts index d52460023..84b27e84c 100644 --- a/src/client/util/bezierFit.ts +++ b/src/client/util/bezierFit.ts @@ -703,7 +703,6 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] { coordList.push({ X: parseInt(match[1]), Y: parseInt(match[2]) }); coordList.push({ X: parseInt(match[1]), Y: parseInt(match[2]) }); coordList.push({ X: parseInt(match[3]), Y: parseInt(match[4]) }); - coordList.push({ X: parseInt(match[3]), Y: parseInt(match[4]) }); lastPt = { X: parseInt(match[3]), Y: parseInt(match[4]) }; } else if (match[0].startsWith('C')) { coordList.push({ X: parseInt(match[5]), Y: parseInt(match[6]) }); @@ -720,7 +719,7 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] { } }); const hasZ = attributes.d.match(/Z/); - if (hasZ) { + if (hasZ || attributes.fill) { coordList.push(lastPt); coordList.push(startPt); coordList.push(startPt); diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index 7779d339f..0d071fe4f 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -8,7 +8,7 @@ import { observer } from 'mobx-react'; import * as React from 'react'; import ResizeObserver from 'resize-observer-polyfill'; import '../../../node_modules/browndash-components/dist/styles/global.min.css'; -import { ClientUtils, lightOrDark, returnEmptyFilter, returnFalse, returnTrue, returnZero, setupMoveUpEvents } from '../../ClientUtils'; +import { ClientUtils, returnEmptyFilter, returnFalse, returnTrue, returnZero, setupMoveUpEvents } from '../../ClientUtils'; import { emptyFunction } from '../../Utils'; import { Doc, DocListCast, GetDocFromUrl, Opt, returnEmptyDoclist } from '../../fields/Doc'; import { DocData } from '../../fields/DocSymbols'; @@ -1023,10 +1023,36 @@ export class MainView extends ObservableReactComponent { {[ ...SnappingManager.HorizSnapLines.map(l => ( - + )), ...SnappingManager.VertSnapLines.map(l => ( - + )), ]} diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx index a61705250..3ef6bdd8b 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx @@ -431,7 +431,7 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { doc = Docs.Create.FunctionPlotDocument([], options); break; case 'dataviz': - case 'data_viz': + case 'data_viz': { const { fileUrl, id } = await Networking.PostToServer('/createCSV', { filename: (options.title as string).replace(/\s+/g, '') + '.csv', data: data, @@ -439,6 +439,7 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { doc = Docs.Create.DataVizDocument(fileUrl, { ...options, text: RTFCast(data) }); this.addCSVForAnalysis(doc, id); break; + } case 'chat': doc = Docs.Create.ChatDocument(options); break; diff --git a/src/client/views/pdf/AnchorMenu.tsx b/src/client/views/pdf/AnchorMenu.tsx index 5ab9b556c..fe03f32a5 100644 --- a/src/client/views/pdf/AnchorMenu.tsx +++ b/src/client/views/pdf/AnchorMenu.tsx @@ -131,12 +131,15 @@ export class AnchorMenu extends AntimodeMenu { /** * Creates a GPT drawing based on selected text. */ - gptDraw = async (e: React.PointerEvent) => { + gptDraw = (e: React.PointerEvent) => { try { SmartDrawHandler.Instance.AddDrawing = this.createDrawingAnnotation; runInAction(() => (this._isLoading = true)); - await SmartDrawHandler.Instance.drawWithGPT({ X: e.clientX, Y: e.clientY }, this._selectedText, 5, 100, true); - runInAction(() => (this._isLoading = false)); + SmartDrawHandler.Instance.drawWithGPT({ X: e.clientX, Y: e.clientY }, this._selectedText, 5, 100, true)?.then( + action(() => { + this._isLoading = false; + }) + ); } catch (err) { console.error(err); } diff --git a/src/client/views/smartdraw/SmartDrawHandler.tsx b/src/client/views/smartdraw/SmartDrawHandler.tsx index d0f6566a5..342b91bd9 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.tsx +++ b/src/client/views/smartdraw/SmartDrawHandler.tsx @@ -13,6 +13,7 @@ import { Doc, DocListCast } from '../../../fields/Doc'; import { DocData } from '../../../fields/DocSymbols'; import { InkData, InkField, InkTool } from '../../../fields/InkField'; import { BoolCast, ImageCast, NumCast, StrCast } from '../../../fields/Types'; +import { Networking } from '../../Network'; import { GPTCallType, gptAPICall, gptDrawingColor } from '../../apis/gpt/GPT'; import { Docs } from '../../documents/Documents'; import { SettingsManager } from '../../util/SettingsManager'; @@ -21,7 +22,8 @@ import { SVGToBezier, SVGType } from '../../util/bezierFit'; import { InkingStroke } from '../InkingStroke'; import { ObservableReactComponent } from '../ObservableReactComponent'; import { MarqueeView } from '../collections/collectionFreeForm'; -import { ActiveInkArrowEnd, ActiveInkArrowStart, ActiveInkDash, ActiveInkFillColor, ActiveInkBezierApprox, ActiveInkColor, ActiveInkWidth, ActiveIsInkMask, DocumentView } from '../nodes/DocumentView'; +import { ActiveInkArrowEnd, ActiveInkArrowStart, ActiveInkBezierApprox, ActiveInkColor, ActiveInkDash, ActiveInkFillColor, ActiveInkWidth, ActiveIsInkMask, DocumentView, DocumentViewInternal } from '../nodes/DocumentView'; +import { OpenWhere } from '../nodes/OpenWhere'; import './SmartDrawHandler.scss'; export interface DrawingOptions { @@ -230,20 +232,21 @@ export class SmartDrawHandler extends ObservableReactComponent { * Calls GPT API to create a drawing based on user input. */ @action - drawWithGPT = async (startPt: { X: number; Y: number }, input: string, complexity: number, size: number, autoColor: boolean) => { - if (input === '') return; - this._lastInput = { text: input, complexity: complexity, size: size, autoColor: autoColor, x: startPt.X, y: startPt.Y }; - const res = await gptAPICall(`"${input}", "${complexity}", "${size}"`, GPTCallType.DRAW, undefined, true); - if (!res) { - console.error('GPT call failed'); - return; - } - const strokeData = await this.parseSvg(res, startPt, false, autoColor); - const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); - drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); + drawWithGPT = (startPt: { X: number; Y: number }, prompt: string, complexity: number, size: number, autoColor: boolean) => { + if (prompt === '') return; + this._lastInput = { text: prompt, complexity: complexity, size: size, autoColor: autoColor, x: startPt.X, y: startPt.Y }; + + Networking.PostToServer('/queryFireflyImage', { prompt }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, { title: prompt }), OpenWhere.addRight)); + + const result = gptAPICall(`"${prompt}", "${complexity}", "${size}"`, GPTCallType.DRAW, undefined, true).then(res => + this.parseSvg(res, startPt, false, autoColor).then(strokeData => { + const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); + drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); + }) + ); this._errorOccurredOnce = false; - return strokeData; + return result; }; /** diff --git a/src/server/ApiManagers/DataVizManager.ts b/src/server/ApiManagers/DataVizManager.ts index 88f22992d..d2028f23b 100644 --- a/src/server/ApiManagers/DataVizManager.ts +++ b/src/server/ApiManagers/DataVizManager.ts @@ -9,7 +9,7 @@ export default class DataVizManager extends ApiManager { register({ method: Method.GET, subscription: '/csvData', - secureHandler: async ({ req, res }) => { + secureHandler: ({ req, res }) => { const uri = req.query.uri as string; return new Promise(resolve => { diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts new file mode 100644 index 000000000..04fa8f065 --- /dev/null +++ b/src/server/ApiManagers/FireflyManager.ts @@ -0,0 +1,51 @@ +import { DashUploadUtils } from '../DashUploadUtils'; +import { _invalid, _success, Method } from '../RouteManager'; +import ApiManager, { Registration } from './ApiManager'; + +export default class FireflyManager extends ApiManager { + askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { + const fetched = fetch('https://ims-na1.adobelogin.com/ims/token/v3', { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: `grant_type=client_credentials&client_id=${process.env._CLIENT_FIREFLY_CLIENT_ID}&client_secret=${process.env._CLIENT_FIREFLY_SECRET}&scope=openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis`, + }) + .then(response => response.json()) + .then((data: { access_token: string }) => + fetch('https://firefly-api.adobe.io/v3/images/generate', { + method: 'POST', + headers: [ + ['Content-Type', 'application/json'], + ['Accept', 'application/json'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${data.access_token}`], + ], + body: `{ "prompt": "${prompt}" }`, + }) + .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) + .catch(error => { + console.error('Error:', error); + return ''; + }) + ) + .catch(error => { + console.error('Error:', error); + return ''; + }); + return fetched; + }; + protected initialize(register: Registration): void { + register({ + method: Method.POST, + subscription: '/queryFireflyImage', + secureHandler: ({ req, res }) => + this.askFirefly(req.body.prompt).then(fire => + DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info.accessPaths.agnostic.client); + }) + ), + }); + } +} diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index 1e55a885a..032d13d43 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -369,7 +369,8 @@ export namespace DashUploadUtils { */ export const UploadInspectedImage = async (metadata: Upload.InspectionResults, filename: string, prefix = '', cleanUp = true): Promise => { const { requestable, source, ...remaining } = metadata; - const resolved = filename || `${prefix}upload_${Utils.GenerateGuid()}.${remaining.contentType.split('/')[1].toLowerCase()}`; + const dfltSuffix = remaining.contentType.split('/')[1].toLowerCase(); + const resolved = filename || `${prefix}upload_${Utils.GenerateGuid()}.${dfltSuffix === 'xml' ? 'jpg' : dfltSuffix}`; const { images } = Directory; const information: Upload.ImageInformation = { accessPaths: { diff --git a/src/server/index.ts b/src/server/index.ts index 88dbd232d..1f9af9ee0 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -7,6 +7,7 @@ import AssistantManager from './ApiManagers/AssistantManager'; import DataVizManager from './ApiManagers/DataVizManager'; import DeleteManager from './ApiManagers/DeleteManager'; import DownloadManager from './ApiManagers/DownloadManager'; +import FireflyManager from './ApiManagers/FireflyManager'; import GeneralGoogleManager from './ApiManagers/GeneralGoogleManager'; import SessionManager from './ApiManagers/SessionManager'; import UploadManager from './ApiManagers/UploadManager'; @@ -71,6 +72,7 @@ function routeSetter({ addSupervisedRoute, logRegistrationOutcome }: RouteManage new GeneralGoogleManager(), /* new GooglePhotosManager(), */ new DataVizManager(), new AssistantManager(), + new FireflyManager(), ]; // initialize API Managers @@ -112,7 +114,6 @@ function routeSetter({ addSupervisedRoute, logRegistrationOutcome }: RouteManage }); const serve: PublicHandler = ({ req, res }) => { - // eslint-disable-next-line new-cap const detector = new mobileDetect(req.headers['user-agent'] || ''); const filename = detector.mobile() !== null ? 'mobile/image.html' : 'index.html'; res.sendFile(path.join(__dirname, '../../deploy/' + filename)); diff --git a/webpack.config.js b/webpack.config.js index e1afc64e5..67417fb02 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -1,4 +1,4 @@ -/* eslint-disable @typescript-eslint/no-var-requires */ +/* eslint-disable @typescript-eslint/no-require-imports */ const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); @@ -36,7 +36,6 @@ function transferEnvironmentVariables() { } const resolvedClientSide = Object.keys(parsed).reduce((mapping, envKey) => { if (envKey.startsWith(prefix)) { - // eslint-disable-next-line mapping[`process.env.${envKey.replace(prefix, '')}`] = JSON.stringify(parsed[envKey]); } return mapping; @@ -112,7 +111,7 @@ module.exports = { test: /\.scss|css$/, exclude: /\.module\.scss$/i, use: [ - { loader: 'style-loader' }, // eslint-disable-next-line prettier/prettier + { loader: 'style-loader' }, // { loader: 'css-loader' }, { loader: 'sass-loader' }, ], @@ -127,7 +126,7 @@ module.exports = { { test: /\.module\.scss$/i, use: [ - { loader: 'style-loader' }, // eslint-disable-next-line prettier/prettier + { loader: 'style-loader' }, // { loader: 'css-loader', options: { modules: true } }, { loader: 'sass-loader' }, ], -- cgit v1.2.3-70-g09d2 From 50fb7536822269b3735e2fc7e3e70ca816529799 Mon Sep 17 00:00:00 2001 From: bobzel Date: Fri, 22 Nov 2024 10:53:40 -0500 Subject: Update FireflyManager.ts --- src/server/ApiManagers/FireflyManager.ts | 37 +++++++++++++++----------------- 1 file changed, 17 insertions(+), 20 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 04fa8f065..a110d112f 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -3,32 +3,29 @@ import { _invalid, _success, Method } from '../RouteManager'; import ApiManager, { Registration } from './ApiManager'; export default class FireflyManager extends ApiManager { - askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { - const fetched = fetch('https://ims-na1.adobelogin.com/ims/token/v3', { + getBearerToken = () => + fetch('https://ims-na1.adobelogin.com/ims/token/v3', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: `grant_type=client_credentials&client_id=${process.env._CLIENT_FIREFLY_CLIENT_ID}&client_secret=${process.env._CLIENT_FIREFLY_SECRET}&scope=openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis`, + }).catch(error => { + console.error('Error:', error); + return ''; + }); + askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { + const fetched = fetch('https://firefly-api.adobe.io/v3/images/generate', { + method: 'POST', + headers: [ + ['Content-Type', 'application/json'], + ['Accept', 'application/json'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${process.env._CLIENT_FIREFLY_BEARER_TOKEN}`], + ], + body: `{ "prompt": "${prompt}" }`, }) - .then(response => response.json()) - .then((data: { access_token: string }) => - fetch('https://firefly-api.adobe.io/v3/images/generate', { - method: 'POST', - headers: [ - ['Content-Type', 'application/json'], - ['Accept', 'application/json'], - ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], - ['Authorization', `Bearer ${data.access_token}`], - ], - body: `{ "prompt": "${prompt}" }`, - }) - .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) - .catch(error => { - console.error('Error:', error); - return ''; - }) - ) + .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) .catch(error => { console.error('Error:', error); return ''; -- cgit v1.2.3-70-g09d2 From 2fee49a7cd342331633bf39d1ac837838d252a18 Mon Sep 17 00:00:00 2001 From: bobzel Date: Fri, 22 Nov 2024 15:00:07 -0500 Subject: switched to providing secret instead of bearer token for adobe api access --- src/server/ApiManagers/FireflyManager.ts | 34 ++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 15 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index a110d112f..5e3ba1f83 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -15,21 +15,25 @@ export default class FireflyManager extends ApiManager { return ''; }); askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { - const fetched = fetch('https://firefly-api.adobe.io/v3/images/generate', { - method: 'POST', - headers: [ - ['Content-Type', 'application/json'], - ['Accept', 'application/json'], - ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], - ['Authorization', `Bearer ${process.env._CLIENT_FIREFLY_BEARER_TOKEN}`], - ], - body: `{ "prompt": "${prompt}" }`, - }) - .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) - .catch(error => { - console.error('Error:', error); - return ''; - }); + const fetched = this.getBearerToken().then(response => + response.json().then((data: { access_token: string }) => + fetch('https://firefly-api.adobe.io/v3/images/generate', { + method: 'POST', + headers: [ + ['Content-Type', 'application/json'], + ['Accept', 'application/json'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${data.access_token}`], + ], + body: `{ "prompt": "${prompt}" }`, + }) + .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) + .catch(error => { + console.error('Error:', error); + return ''; + }) + ) + ); return fetched; }; protected initialize(register: Registration): void { -- cgit v1.2.3-70-g09d2 From bf46473a8a19a2af6b3f5ef069cfd20871bebbcf Mon Sep 17 00:00:00 2001 From: eleanor-park Date: Wed, 4 Dec 2024 18:25:27 -0500 Subject: added structure and upload image firefly api calls --- src/server/ApiManagers/FireflyManager.ts | 107 +++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 src/server/ApiManagers/FireflyManager.ts (limited to 'src/server/ApiManagers') diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts new file mode 100644 index 000000000..29aed2c54 --- /dev/null +++ b/src/server/ApiManagers/FireflyManager.ts @@ -0,0 +1,107 @@ +import { DashUploadUtils } from '../DashUploadUtils'; +import { _invalid, _success, Method } from '../RouteManager'; +import ApiManager, { Registration } from './ApiManager'; + +export default class FireflyManager extends ApiManager { + getBearerToken = () => + fetch('https://ims-na1.adobelogin.com/ims/token/v3', { + method: 'POST', + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + }, + body: `grant_type=client_credentials&client_id=${process.env._CLIENT_FIREFLY_CLIENT_ID}&client_secret=${process.env._CLIENT_FIREFLY_SECRET}&scope=openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis`, + }).catch(error => { + console.error('Error:', error); + return ''; + }); + askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { + const fetched = this.getBearerToken().then(response => + response.json().then((data: { access_token: string }) => + fetch('https://firefly-api.adobe.io/v3/images/generate', { + method: 'POST', + headers: [ + ['Content-Type', 'application/json'], + ['Accept', 'application/json'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${data.access_token}`], + ], + body: `{ "prompt": "${prompt}" }`, + }) + .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) + .catch(error => { + console.error('Error:', error); + return ''; + }) + ) + ); + return fetched; + }; + + askFireflyStructure = (prompt: string = 'a realistic illustration of a cat coding', strength: number, imageReference: ) => { + const fetched = this.getBearerToken().then(response => + response.json().then((data: { access_token: string }) => { + const body = { + prompt: prompt, + structure: { + strength: strength, + imageReference: { + source: { + uploadId: + } + } + } + } + return fetch('https://firefly-api.adobe.io/v3/images/generate', { + method: 'POST', + headers: [ + ['Content-Type', 'application/json'], + ['Accept', 'application/json'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${data.access_token}`], + ], + body: JSON.stringify(body), + }) + .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) + .catch(error => { + console.error('Error:', error); + return ''; + }) + }) + ); + return fetched; + }; + + uploadImageToFirefly = (image: File | Blob) => { + const fetched = this.getBearerToken().then(response => + response.json().then((data: { access_token: string }) => + fetch('https://firefly-api.adobe.io/v3/uploads', { + method: 'POST', + headers: [ + ['Content-Type', image.type], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${data.access_token}`], // You can replace this with a dynamic token if needed + ], + body: image, + }) + .then(response => response.json()) + .then(data => data.uploadId) // Extract the uploadId from the response + .catch(error => { + console.error('Error uploading image:', error); + return ''; + }); + }; + + protected initialize(register: Registration): void { + register({ + method: Method.POST, + subscription: '/queryFireflyImage', + secureHandler: ({ req, res }) => + this.askFirefly(req.body.prompt).then(fire => + DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info.accessPaths.agnostic.client); + }) + ), + }); + } +} -- cgit v1.2.3-70-g09d2 From 0066635b2a9ae5fde15defd9dd76c6d7dc1d8959 Mon Sep 17 00:00:00 2001 From: eleanor-park Date: Thu, 5 Dec 2024 00:22:08 -0500 Subject: added image to blob logic and firefly api call in drawingFillHandler --- src/client/views/smartdraw/DrawingFillHandler.tsx | 48 ++++++++++++ src/server/ApiManagers/FireflyManager.ts | 90 ++++++++++++----------- 2 files changed, 96 insertions(+), 42 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index e69de29bb..508ee557d 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -0,0 +1,48 @@ +import { action, makeObservable } from 'mobx'; +import { observer } from 'mobx-react'; +import React from 'react'; +import { Doc } from '../../../fields/Doc'; +import { ImageCast } from '../../../fields/Types'; +import { ImageField } from '../../../fields/URLField'; +import { Docs } from '../../documents/Documents'; +import { Networking } from '../../Network'; +import { makeUserTemplateButtonOrImage } from '../../util/DropConverter'; +import { DocumentView, DocumentViewInternal } from '../nodes/DocumentView'; +import { ImageUtility } from '../nodes/imageEditor/imageEditorUtils/ImageHandler'; +import { OpenWhere } from '../nodes/OpenWhere'; +import { ObservableReactComponent } from '../ObservableReactComponent'; + +@observer +export class DrawingFillHandler extends ObservableReactComponent { + static Instance: DrawingFillHandler; + + constructor(props: object) { + super(props); + makeObservable(this); + DrawingFillHandler.Instance = this; + } + + @action + drawingToImage = async (drawing: Doc, prompt: string) => { + const imageField = await DocumentView.GetDocImage(drawing); + if (!imageField) return; + const image = new Image(); + image.src = imageField.url?.href; + await new Promise((resolve, reject) => { + image.onload = () => resolve(); + image.onerror = () => reject(new Error('Error loading image')); + }); + + const canvas = document.createElement('canvas'); + canvas.width = image.width; + canvas.height = image.height; + const ctx = canvas.getContext('2d'); + if (!ctx) return; + ctx.globalCompositeOperation = 'source-over'; + ctx.clearRect(0, 0, image.width, image.height); + ctx.drawImage(image, 0, 0); + const blob: Blob = await ImageUtility.canvasToBlob(canvas); + const strength: number = 100; + Networking.PostToServer('/queryFireflyImage', { prompt, blob, strength }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight)); + }; +} diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 29aed2c54..55fa1e461 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -14,43 +14,43 @@ export default class FireflyManager extends ApiManager { console.error('Error:', error); return ''; }); - askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { - const fetched = this.getBearerToken().then(response => - response.json().then((data: { access_token: string }) => - fetch('https://firefly-api.adobe.io/v3/images/generate', { - method: 'POST', - headers: [ - ['Content-Type', 'application/json'], - ['Accept', 'application/json'], - ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], - ['Authorization', `Bearer ${data.access_token}`], - ], - body: `{ "prompt": "${prompt}" }`, - }) - .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) - .catch(error => { - console.error('Error:', error); - return ''; - }) - ) - ); - return fetched; - }; + // askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { + // const fetched = this.getBearerToken().then(response => + // response.json().then((data: { access_token: string }) => + // fetch('https://firefly-api.adobe.io/v3/images/generate', { + // method: 'POST', + // headers: [ + // ['Content-Type', 'application/json'], + // ['Accept', 'application/json'], + // ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + // ['Authorization', `Bearer ${data.access_token}`], + // ], + // body: `{ "prompt": "${prompt}" }`, + // }) + // .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) + // .catch(error => { + // console.error('Error:', error); + // return ''; + // }) + // ) + // ); + // return fetched; + // }; - askFireflyStructure = (prompt: string = 'a realistic illustration of a cat coding', strength: number, imageReference: ) => { + askFirefly = (prompt: string = 'a realistic illustration of a cat coding', uploadId: string, strength: number) => { const fetched = this.getBearerToken().then(response => response.json().then((data: { access_token: string }) => { - const body = { + const body: any = { prompt: prompt, structure: { strength: strength, imageReference: { source: { - uploadId: - } - } - } - } + uploadId: uploadId, + }, + }, + }, + }; return fetch('https://firefly-api.adobe.io/v3/images/generate', { method: 'POST', headers: [ @@ -65,13 +65,13 @@ export default class FireflyManager extends ApiManager { .catch(error => { console.error('Error:', error); return ''; - }) - }) + }); + }) ); return fetched; }; - uploadImageToFirefly = (image: File | Blob) => { + uploadImageToFirefly = (image: Blob) => { const fetched = this.getBearerToken().then(response => response.json().then((data: { access_token: string }) => fetch('https://firefly-api.adobe.io/v3/uploads', { @@ -79,29 +79,35 @@ export default class FireflyManager extends ApiManager { headers: [ ['Content-Type', image.type], ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], - ['Authorization', `Bearer ${data.access_token}`], // You can replace this with a dynamic token if needed + ['Authorization', `Bearer ${data.access_token}`], ], body: image, }) - .then(response => response.json()) - .then(data => data.uploadId) // Extract the uploadId from the response - .catch(error => { - console.error('Error uploading image:', error); - return ''; - }); + .then(response => response.json()) + .then(data => data.uploadId) // Extract the uploadId from the response + .catch(error => { + console.error('Error:', error); + return ''; + }) + ) + ); + return fetched; }; protected initialize(register: Registration): void { register({ method: Method.POST, subscription: '/queryFireflyImage', - secureHandler: ({ req, res }) => - this.askFirefly(req.body.prompt).then(fire => + secureHandler: async ({ req, res }) => { + const { prompt, imageBlob, strength = 0.5 } = req.body; + const uploadId = imageBlob ? await this.uploadImageToFirefly(imageBlob) : null; + this.askFirefly(prompt, uploadId, strength).then(fire => DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { if (info instanceof Error) _invalid(res, info.message); else _success(res, info.accessPaths.agnostic.client); }) - ), + ); + }, }); } } -- cgit v1.2.3-70-g09d2 From b9316fd7280bbddbc73966ce432b5054c07c3af0 Mon Sep 17 00:00:00 2001 From: bobzel Date: Thu, 5 Dec 2024 10:48:27 -0500 Subject: playing with ink stroke editing and firefly --- .env2 | 4 +++ src/.DS_Store | Bin 10244 -> 10244 bytes src/client/views/InkStrokeProperties.ts | 28 ++++++++++++++-- src/server/ApiManagers/FireflyManager.ts | 53 +++++++++++++++++++++++++++---- 4 files changed, 76 insertions(+), 9 deletions(-) create mode 100644 .env2 (limited to 'src/server/ApiManagers') diff --git a/.env2 b/.env2 new file mode 100644 index 000000000..08ee154e1 --- /dev/null +++ b/.env2 @@ -0,0 +1,4 @@ + +export _CLIENT_FIREFLY_CLIENT_ID='62eb3cc56d8d47c88ff67103ded0003f' +export _CLIENT_FIREFLY_SECRET='p8e-4JxcVXG6izNEnf0ceEPO1zSZ7U13TMUQ' +export _CLIENT_FIREFLY_TOKEN='eyJhbGciOiJSUzI1NiIsIng1dSI6Imltc19uYTEta2V5LWF0LTEuY2VyIiwia2lkIjoiaW1zX25hMS1rZXktYXQtMSIsIml0dCI6ImF0In0.eyJpZCI6IjE3MzMyMzgwMjg3NDVfNDg0ODM3ZTAtMmU3Zi00NWFkLTkzZjEtZjM0NWRkNDM3MzAwX3VlMSIsIm9yZyI6IjVEOEUxREMzNjcyNTQ2MDIwQTQ5NUZGMEBBZG9iZU9yZyIsInR5cGUiOiJhY2Nlc3NfdG9rZW4iLCJjbGllbnRfaWQiOiI2MmViM2NjNTZkOGQ0N2M4OGZmNjcxMDNkZWQwMDAzZiIsInVzZXJfaWQiOiI2MzQ1MUQ5RTY3MjU1MEQ4MEE0OTVFQ0FAdGVjaGFjY3QuYWRvYmUuY29tIiwiYXMiOiJpbXMtbmExIiwiYWFfaWQiOiI2MzQ1MUQ5RTY3MjU1MEQ4MEE0OTVFQ0FAdGVjaGFjY3QuYWRvYmUuY29tIiwiY3RwIjozLCJtb2kiOiI3NDc2MDZiZCIsImV4cGlyZXNfaW4iOiI4NjQwMDAwMCIsInNjb3BlIjoiZmlyZWZseV9hcGksYWRkaXRpb25hbF9pbmZvLG9wZW5pZCxzZXNzaW9uLEFkb2JlSUQsZmZfYXBpcyxyZWFkX29yZ2FuaXphdGlvbnMiLCJjcmVhdGVkX2F0IjoiMTczMzIzODAyODc0NSJ9.O-HGx7ji_-RZJXmCnsPVzdTmJA4s_fA0Gj0s7z1FZ6MPtzdXa9MSYkMYdo4ImfiYZGf73SeJACEpfTdgyd7shG3qXBydeZV2exGQcN6eve88zXMBsc98aCi0mPz2eql4MomJk9xGXuk3ZuZmVAbsAVfwScPU_uyl75DZAq4_4e6lyXakEti9ACYnEl-7TQQeEgK6Mr4R8giUWvYVAdmSK4xOq67yjBToj6S-fv_s2dBRY58x_fMkORCrJnDLEnSdXS2LXHXAyM_Up9EaezIovlVhwz04BuwrH0vVOJN7uHgFOeWbjULaGGYy2Wzb1hPeRVd7VIRiw3sHavthTSJ3KA' diff --git a/src/.DS_Store b/src/.DS_Store index 9b66f8d8e..1ef749033 100644 Binary files a/src/.DS_Store and b/src/.DS_Store differ diff --git a/src/client/views/InkStrokeProperties.ts b/src/client/views/InkStrokeProperties.ts index 358274f0e..8165b7f4e 100644 --- a/src/client/views/InkStrokeProperties.ts +++ b/src/client/views/InkStrokeProperties.ts @@ -74,6 +74,7 @@ export class InkStrokeProperties { doc._height = (newYrange.max - newYrange.min) * ptsYscale + NumCast(doc.stroke_width); doc.x = oldXrange.coord + (newXrange.min - oldXrange.min) * ptsXscale; doc.y = oldYrange.coord + (newYrange.min - oldYrange.min) * ptsYscale; + Doc.SetInPlace(doc, 'stroke', new InkField(newPoints), true); appliedFunc = true; } @@ -248,7 +249,7 @@ export class InkStrokeProperties { /** * Handles the movement/scaling of a control point. */ - moveControlPtHandle = undoable((inkView: DocumentView, deltaX: number, deltaY: number, controlIndex: number, origInk?: InkData) => { + moveControlPtHandle = undoable((inkView: DocumentView, deltaX: number, deltaY: number, controlIndex: number, origInk?: InkData, noPush?: boolean) => { inkView && this.applyFunction(inkView, (view: DocumentView, ink: InkData) => { const order = controlIndex % 4; @@ -288,10 +289,11 @@ export class InkStrokeProperties { const { finalCtrls: rightCtrls /* , error: errorRight */ } = FitOneCurve(samplesRight, { X: startDir.x, Y: startDir.y }, { X: endDir.x, Y: endDir.y }); finalCtrls = finalCtrls.concat(rightCtrls); newink.splice(this._currentPoint - 4, 8, ...finalCtrls); - return newink; } - return ink.map((pt, i) => { + const prevData = (inkView.ComponentView as InkingStroke).screenCtrlPts; + + const newInk = ink.map((pt, i) => { const leftHandlePoint = order === 0 && i === controlIndex + 1; const rightHandlePoint = order === 0 && controlIndex !== 0 && i === controlIndex - 2; if (controlIndex === i || (order === 0 && controlIndex !== 0 && i === controlIndex - 1) || (order === 3 && i === controlIndex - 1)) { @@ -312,6 +314,26 @@ export class InkStrokeProperties { } return pt; }); + + if (inkView.IsSelected && !noPush && !InkingStroke.IsClosed(prevData)) { + const ffview = CollectionFreeFormView.from(inkView); + ffview?.childDocs.forEach(d => { + const oinkDoc = DocumentView.getDocumentView(d); + const oinkView = oinkDoc?.ComponentView as InkingStroke; + if (oinkView instanceof InkingStroke && oinkDoc && oinkDoc.Document !== inkView.Document) { + const { nearestSeg, nearestT } = InkStrokeProperties.nearestPtToStroke(oinkView.screenCtrlPts, prevData[controlIndex]); + const locdelta = inkView.screenToContentsTransform().inverse().transformDirection(deltaX, deltaY); + const index = nearestSeg + Math.round(nearestT) * 4; + const oinkData = oinkView.inkScaledData().inkData; + const closed = InkingStroke.IsClosed(oinkData); + InkStrokeProperties.Instance.moveControlPtHandle(oinkDoc, locdelta[0], locdelta[1], index, undefined, true); + if (index === oinkData.length && closed) { + InkStrokeProperties.Instance.moveControlPtHandle(oinkDoc, locdelta[0], locdelta[1], 0, undefined, true); + } + } + }); + } + return newInk; }); }, 'move ink ctrl pt'); diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 5e3ba1f83..e10e43704 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -16,7 +16,7 @@ export default class FireflyManager extends ApiManager { }); askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { const fetched = this.getBearerToken().then(response => - response.json().then((data: { access_token: string }) => + (response as Response).json().then((data: { access_token: string }) => fetch('https://firefly-api.adobe.io/v3/images/generate', { method: 'POST', headers: [ @@ -36,16 +36,57 @@ export default class FireflyManager extends ApiManager { ); return fetched; }; + askFireflyText = (testshotpng: Blob) => { + const fetched = this.getBearerToken().then(response => + (response as Response).json().then((data: { access_token: string }) => { + return fetch('https://sensei.adobe.io/services/v2/predict', { + method: 'POST', + headers: [ + ['Prefer', 'respond-async, wait=59'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['content-type', 'multipart/form-data'], + ['Authorization', `Bearer ${data.access_token}`], + ], + body: ((form: FormData) => { + form.append('file', testshotpng); + form.append( + 'contentAnalyzerRequests', + JSON.stringify({ + 'sensei:name': 'Feature:cintel-object-detection:Service-b9ace8b348b6433e9e7d82371aa16690', + }) + ); + return form; + })(new FormData()), + }).then(response2 => + response2 + .json() + .then(json => { + console.log(json); + return ''; + }) + .catch(error => { + console.error('Error:', error); + return ''; + }) + ); + }) + ); + return fetched; + }; protected initialize(register: Registration): void { register({ method: Method.POST, subscription: '/queryFireflyImage', secureHandler: ({ req, res }) => - this.askFirefly(req.body.prompt).then(fire => - DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { - if (info instanceof Error) _invalid(res, info.message); - else _success(res, info.accessPaths.agnostic.client); - }) + fetch('http://localhost:1050/files/images/testshot.png').then(json => + json.blob().then(file => + this.askFireflyText(file).then(fire => + DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info.accessPaths.agnostic.client); + }) + ) + ) ), }); } -- cgit v1.2.3-70-g09d2 From 629e2bef5d4dd4599de010b62e5b26304ee620dd Mon Sep 17 00:00:00 2001 From: bobzel Date: Mon, 9 Dec 2024 12:53:35 -0500 Subject: added firefly text in image request --- package-lock.json | 6 ++ package.json | 1 + src/server/ApiManagers/FireflyManager.ts | 94 ++++++++++++++++++++++++-------- src/server/ApiManagers/UploadManager.ts | 5 -- src/server/DashUploadUtils.ts | 4 +- 5 files changed, 79 insertions(+), 31 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/package-lock.json b/package-lock.json index 8c2cf0694..05f6d540f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -171,6 +171,7 @@ "npm": "^10.8.1", "openai": "^4.26.0", "p-limit": "^6.1.0", + "parse-multipart-data": "^1.5.0", "passport": "^0.7.0", "passport-google-oauth20": "^2.0.0", "passport-local": "^1.0.0", @@ -30590,6 +30591,11 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/parse-multipart-data": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/parse-multipart-data/-/parse-multipart-data-1.5.0.tgz", + "integrity": "sha512-ck5zaMF0ydjGfejNMnlo5YU2oJ+pT+80Jb1y4ybanT27j+zbVP/jkYmCrUGsEln0Ox/hZmuvgy8Ra7AxbXP2Mw==" + }, "node_modules/parse-passwd": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/parse-passwd/-/parse-passwd-1.0.0.tgz", diff --git a/package.json b/package.json index 7c2730245..949f76599 100644 --- a/package.json +++ b/package.json @@ -254,6 +254,7 @@ "npm": "^10.8.1", "openai": "^4.26.0", "p-limit": "^6.1.0", + "parse-multipart-data": "^1.5.0", "passport": "^0.7.0", "passport-google-oauth20": "^2.0.0", "passport-local": "^1.0.0", diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index e10e43704..30fbdc577 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -1,6 +1,7 @@ import { DashUploadUtils } from '../DashUploadUtils'; import { _invalid, _success, Method } from '../RouteManager'; import ApiManager, { Registration } from './ApiManager'; +import * as multipart from 'parse-multipart-data'; export default class FireflyManager extends ApiManager { getBearerToken = () => @@ -27,7 +28,7 @@ export default class FireflyManager extends ApiManager { ], body: `{ "prompt": "${prompt}" }`, }) - .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) + .then(response2 => response2.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) .catch(error => { console.error('Error:', error); return ''; @@ -36,7 +37,9 @@ export default class FireflyManager extends ApiManager { ); return fetched; }; - askFireflyText = (testshotpng: Blob) => { + getImageText = (testshotpng: Blob) => { + const inputFileVarName = 'infile'; + const outputVarName = 'result'; const fetched = this.getBearerToken().then(response => (response as Response).json().then((data: { access_token: string }) => { return fetch('https://sensei.adobe.io/services/v2/predict', { @@ -44,31 +47,67 @@ export default class FireflyManager extends ApiManager { headers: [ ['Prefer', 'respond-async, wait=59'], ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], - ['content-type', 'multipart/form-data'], + // ['content-type', 'multipart/form-data'], // bcz: Don't set this!! content-type will get set automatically including the Boundary string ['Authorization', `Bearer ${data.access_token}`], ], body: ((form: FormData) => { - form.append('file', testshotpng); - form.append( + form.set(inputFileVarName, testshotpng); + form.set( 'contentAnalyzerRequests', JSON.stringify({ 'sensei:name': 'Feature:cintel-object-detection:Service-b9ace8b348b6433e9e7d82371aa16690', + 'sensei:invocation_mode': 'asynchronous', + 'sensei:invocation_batch': false, + 'sensei:engines': [ + { + 'sensei:execution_info': { + 'sensei:engine': 'Feature:cintel-object-detection:Service-b9ace8b348b6433e9e7d82371aa16690', + }, + 'sensei:inputs': { + documents: [ + { + 'sensei:multipart_field_name': inputFileVarName, + 'dc:format': 'image/png', + }, + ], + }, + 'sensei:params': { + correct_with_dictionary: true, + }, + 'sensei:outputs': { + result: { + 'sensei:multipart_field_name': outputVarName, + 'dc:format': 'application/json', + }, + }, + }, + ], }) ); return form; })(new FormData()), - }).then(response2 => - response2 - .json() - .then(json => { - console.log(json); - return ''; - }) - .catch(error => { - console.error('Error:', error); - return ''; - }) - ); + }).then(response2 => { + const contentType = response2.headers.get('content-type') ?? ''; + if (contentType.includes('application/json')) { + return response2.json().then((json: object) => JSON.stringify(json)); + } + if (contentType.includes('multipart')) { + return response2 + .arrayBuffer() + .then(arrayBuffer => + multipart + .parse(Buffer.from(arrayBuffer), 'Boundary' + (response2.headers.get('content-type')?.match(/=Boundary(.*);/)?.[1] ?? '')) + .filter(part => part.name === outputVarName) + .map(part => JSON.parse(part.data.toString()[0])) + .reduce((text, json) => text + (json?.is_text_present ? json.tags.map((tag: { text: string }) => tag.text).join(' ') : ''), '') + ) + .catch(error => { + console.error('Error:', error); + return ''; + }); + } + return response2.text(); + }); }) ); return fetched; @@ -77,15 +116,24 @@ export default class FireflyManager extends ApiManager { register({ method: Method.POST, subscription: '/queryFireflyImage', + secureHandler: ({ req, res }) => + this.askFirefly(req.body).then(fire => { + DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info.accessPaths.agnostic.client); + }); + }), + }); + + register({ + method: Method.POST, + subscription: '/queryFireflyImageText', secureHandler: ({ req, res }) => fetch('http://localhost:1050/files/images/testshot.png').then(json => json.blob().then(file => - this.askFireflyText(file).then(fire => - DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { - if (info instanceof Error) _invalid(res, info.message); - else _success(res, info.accessPaths.agnostic.client); - }) - ) + this.getImageText(file).then(text => { + _success(res, text); + }) ) ), }); diff --git a/src/server/ApiManagers/UploadManager.ts b/src/server/ApiManagers/UploadManager.ts index 868373474..7bfdd5aec 100644 --- a/src/server/ApiManagers/UploadManager.ts +++ b/src/server/ApiManagers/UploadManager.ts @@ -147,13 +147,10 @@ export default class UploadManager extends ApiManager { if (doc.id) { doc.id = getId(doc.id); } - // eslint-disable-next-line no-restricted-syntax for (const key in doc.fields) { - // eslint-disable-next-line no-continue if (!Object.prototype.hasOwnProperty.call(doc.fields, key)) continue; const field = doc.fields[key]; - // eslint-disable-next-line no-continue if (field === undefined || field === null) continue; if (field.__type === 'Doc') { @@ -182,11 +179,9 @@ export default class UploadManager extends ApiManager { let docids: string[] = []; let linkids: string[] = []; try { - // eslint-disable-next-line no-restricted-syntax for (const name in files) { if (Object.prototype.hasOwnProperty.call(files, name)) { const f = files[name]; - // eslint-disable-next-line no-continue if (!f) continue; const path2 = f[0]; // what about the rest of the array? are we guaranteed only one value is set? const zip = new AdmZip(path2.filepath); diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index 351351ca5..028116779 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -223,7 +223,6 @@ export namespace DashUploadUtils { const parseExifData = async (source: string) => { const image = await request.get(source, { encoding: null }); const { /* data, */ error } = await new Promise<{ data: ExifData; error: string | undefined }>(resolve => { - // eslint-disable-next-line no-new new ExifImage({ image }, (exifError, data) => { resolve({ data, error: exifError?.message }); }); @@ -302,7 +301,6 @@ export namespace DashUploadUtils { // Bundle up the information into an object return { source, - // eslint-disable-next-line radix contentSize: parseInt(headers[size]), contentType: headers[type], nativeWidth, @@ -370,7 +368,7 @@ export namespace DashUploadUtils { * @returns the accessPaths for the resized files. */ export const UploadInspectedImage = async (metadata: Upload.InspectionResults, filename: string, prefix = '', cleanUp = true): Promise => { - const { requestable, source, ...remaining } = metadata; + const { requestable, ...remaining } = metadata; const dfltSuffix = remaining.contentType.split('/')[1].toLowerCase(); const resolved = filename || `${prefix}upload_${Utils.GenerateGuid()}.${dfltSuffix === 'xml' ? 'jpg' : dfltSuffix}`; const { images } = Directory; -- cgit v1.2.3-70-g09d2 From 48c3b802a3c8fd446ecbd33747fe702b11170dfe Mon Sep 17 00:00:00 2001 From: bobzel Date: Mon, 9 Dec 2024 12:54:49 -0500 Subject: from last --- src/server/ApiManagers/FireflyManager.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 30fbdc577..cc4c218bf 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -117,12 +117,12 @@ export default class FireflyManager extends ApiManager { method: Method.POST, subscription: '/queryFireflyImage', secureHandler: ({ req, res }) => - this.askFirefly(req.body).then(fire => { + this.askFirefly(req.body.prompt).then(fire => DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { if (info instanceof Error) _invalid(res, info.message); else _success(res, info.accessPaths.agnostic.client); - }); - }), + }) + ), }); register({ -- cgit v1.2.3-70-g09d2 From a5a7769e0c400f0a58a9b53ae13b338a26eaa919 Mon Sep 17 00:00:00 2001 From: bobzel Date: Wed, 11 Dec 2024 13:11:43 -0500 Subject: fixes for uploading remote images to sample and save them properly. extnesions fo firefly manager to query text in images, expand images, and tweaks to generate images. --- package-lock.json | 23 +++++-- package.json | 3 +- src/client/views/nodes/ImageBox.tsx | 31 +++++++++ src/server/ApiManagers/FireflyManager.ts | 114 +++++++++++++++++++++++++++---- src/server/ApiManagers/UploadManager.ts | 8 ++- src/server/DashUploadUtils.ts | 37 ++++++---- 6 files changed, 183 insertions(+), 33 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/package-lock.json b/package-lock.json index 05f6d540f..46057f615 100644 --- a/package-lock.json +++ b/package-lock.json @@ -100,6 +100,7 @@ "depcheck": "^1.4.7", "dompurify": "^3.1.7", "dotenv": "^16.4.5", + "dropbox": "^10.34.0", "eslint-webpack-plugin": "^4.1.0", "exif": "^0.6.0", "exifr": "^7.1.3", @@ -128,7 +129,7 @@ "google-auth-library": "^9.4.1", "googleapis": "^144.0.0", "googlephotos": "^0.3.5", - "got": "^14.0.0", + "got": "^14.4.5", "howler": "^2.2.4", "html-to-image": "^1.11.11", "html-to-text": "^9.0.5", @@ -19701,6 +19702,20 @@ "resolved": "https://registry.npmjs.org/double-bits/-/double-bits-1.1.1.tgz", "integrity": "sha512-BCLEIBq0O/DWoA7BsCu/R+RP0ZXiowP8BhtJT3qeuuQEBpnS8LK/Wo6UTJQv6v8mK1fj8n90YziHLwGdM5whSg==" }, + "node_modules/dropbox": { + "version": "10.34.0", + "resolved": "https://registry.npmjs.org/dropbox/-/dropbox-10.34.0.tgz", + "integrity": "sha512-5jb5/XzU0fSnq36/hEpwT5/QIep7MgqKuxghEG44xCu7HruOAjPdOb3x0geXv5O/hd0nHpQpWO+r5MjYTpMvJg==", + "dependencies": { + "node-fetch": "^2.6.1" + }, + "engines": { + "node": ">=0.10.3" + }, + "peerDependencies": { + "@types/node-fetch": "^2.5.7" + } + }, "node_modules/dynamic-dedupe": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/dynamic-dedupe/-/dynamic-dedupe-0.3.0.tgz", @@ -22149,9 +22164,9 @@ } }, "node_modules/got": { - "version": "14.4.4", - "resolved": "https://registry.npmjs.org/got/-/got-14.4.4.tgz", - "integrity": "sha512-tqiF7eSgTBwQkxb1LxsEpva8TaMYVisbhplrFVmw9GQE3855Z+MH/mnsXLLOkDxR6hZJRFMj5VTAZ8lmTF8ZOA==", + "version": "14.4.5", + "resolved": "https://registry.npmjs.org/got/-/got-14.4.5.tgz", + "integrity": "sha512-sq+uET8TnNKRNnjEOPJzMcxeI0irT8BBNmf+GtZcJpmhYsQM1DSKmCROUjPWKsXZ5HzwD5Cf5/RV+QD9BSTxJg==", "dependencies": { "@sindresorhus/is": "^7.0.1", "@szmarczak/http-timer": "^5.0.1", diff --git a/package.json b/package.json index 949f76599..7ca0c8b38 100644 --- a/package.json +++ b/package.json @@ -183,6 +183,7 @@ "depcheck": "^1.4.7", "dompurify": "^3.1.7", "dotenv": "^16.4.5", + "dropbox": "^10.34.0", "eslint-webpack-plugin": "^4.1.0", "exif": "^0.6.0", "exifr": "^7.1.3", @@ -211,7 +212,7 @@ "google-auth-library": "^9.4.1", "googleapis": "^144.0.0", "googlephotos": "^0.3.5", - "got": "^14.0.0", + "got": "^14.4.5", "howler": "^2.2.4", "html-to-image": "^1.11.11", "html-to-text": "^9.0.5", diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index ff879a2ab..8c7ec959e 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -38,6 +38,8 @@ import { FieldView, FieldViewProps } from './FieldView'; import { FocusViewOptions } from './FocusViewOptions'; import './ImageBox.scss'; import { OpenWhere } from './OpenWhere'; +import { Upload } from '../../../server/SharedMediaTypes'; +import { ImageUtils } from '../../util/Import & Export/ImageUtils'; export class ImageEditorData { // eslint-disable-next-line no-use-before-define @@ -309,6 +311,35 @@ export class ImageBox extends ViewBoxAnnotatableComponent() { funcs.push({ description: 'Rotate Clockwise 90', event: this.rotate, icon: 'redo-alt' }); funcs.push({ description: `Show ${this.layoutDoc._showFullRes ? 'Dynamic Res' : 'Full Res'}`, event: this.resolution, icon: 'expand' }); funcs.push({ description: 'Set Native Pixel Size', event: this.setNativeSize, icon: 'expand-arrows-alt' }); + funcs.push({ + description: 'GetImageText', + event: () => { + Networking.PostToServer('/queryFireflyImageText', { + file: (file => { + const ext = extname(file); + return file.replace(ext, (this._error ? '_o' : this._curSuffix) + ext); + })(ImageCast(this.Document[Doc.LayoutFieldKey(this.Document)])?.url.href), + }).then(text => alert(text)); + }, + icon: 'expand-arrows-alt', + }); + funcs.push({ + description: 'Expand Image', + event: () => { + Networking.PostToServer('/expandImage', { + prompt: 'sunny skies', + file: (file => { + const ext = extname(file); + return file.replace(ext, (this._error ? '_o' : this._curSuffix) + ext); + })(ImageCast(this.Document[Doc.LayoutFieldKey(this.Document)])?.url.href), + }).then((info: Upload.ImageInformation) => { + const img = Docs.Create.ImageDocument(info.accessPaths.agnostic.client, { title: 'expand:' + this.Document.title }); + DocUtils.assignImageInfo(info, img); + this._props.addDocTab(img, OpenWhere.addRight); + }); + }, + icon: 'expand-arrows-alt', + }); funcs.push({ description: 'Copy path', event: () => ClientUtils.CopyText(this.choosePath(field.url)), icon: 'copy' }); funcs.push({ description: 'Open Image Editor', diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index cc4c218bf..d757a23fe 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -1,7 +1,11 @@ +import { Dropbox, files } from 'dropbox'; +import * as fs from 'fs'; +import * as multipart from 'parse-multipart-data'; +import * as path from 'path'; import { DashUploadUtils } from '../DashUploadUtils'; -import { _invalid, _success, Method } from '../RouteManager'; +import { _error, _invalid, _success, Method } from '../RouteManager'; +import { Directory, filesDirectory } from '../SocketData'; import ApiManager, { Registration } from './ApiManager'; -import * as multipart from 'parse-multipart-data'; export default class FireflyManager extends ApiManager { getBearerToken = () => @@ -13,11 +17,11 @@ export default class FireflyManager extends ApiManager { body: `grant_type=client_credentials&client_id=${process.env._CLIENT_FIREFLY_CLIENT_ID}&client_secret=${process.env._CLIENT_FIREFLY_SECRET}&scope=openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis`, }).catch(error => { console.error('Error:', error); - return ''; + return undefined; }); - askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { + generateImage = (prompt: string = 'a realistic illustration of a cat coding') => { const fetched = this.getBearerToken().then(response => - (response as Response).json().then((data: { access_token: string }) => + response?.json().then((data: { access_token: string }) => fetch('https://firefly-api.adobe.io/v3/images/generate', { method: 'POST', headers: [ @@ -28,20 +32,66 @@ export default class FireflyManager extends ApiManager { ], body: `{ "prompt": "${prompt}" }`, }) - .then(response2 => response2.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) + .then(response2 => response2.json().then(json => (json.outputs?.[0] as { image: { url: string } })?.image.url)) .catch(error => { console.error('Error:', error); - return ''; + return undefined; }) ) ); return fetched; }; - getImageText = (testshotpng: Blob) => { + expandImage = (imgUrl: string, prompt?: string) => { + const dropboxImgUrl = imgUrl; + const fetched = this.getBearerToken().then(response => + response + ?.json() + .then((data: { access_token: string }) => { + return fetch('https://firefly-api.adobe.io/v3/images/expand', { + method: 'POST', + headers: [ + ['Content-Type', 'application/json'], + ['Accept', 'application/json'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${data.access_token}`], + ], + body: JSON.stringify({ + image: { + source: { + url: dropboxImgUrl, + }, + }, + numVariations: 1, + seeds: [0], + size: { + width: 3048, + height: 2048, + }, + prompt: prompt ?? 'cloudy skies', + placement: { + inset: { + left: 0, + top: 0, + right: 0, + bottom: 0, + }, + alignment: { + horizontal: 'center', + vertical: 'center', + }, + }, + }), + }); + }) + .then(resp => resp.json()) + ); + return fetched; + }; + getImageText = (imageBlob: Blob) => { const inputFileVarName = 'infile'; const outputVarName = 'result'; const fetched = this.getBearerToken().then(response => - (response as Response).json().then((data: { access_token: string }) => { + response?.json().then((data: { access_token: string }) => { return fetch('https://sensei.adobe.io/services/v2/predict', { method: 'POST', headers: [ @@ -51,7 +101,7 @@ export default class FireflyManager extends ApiManager { ['Authorization', `Bearer ${data.access_token}`], ], body: ((form: FormData) => { - form.set(inputFileVarName, testshotpng); + form.set(inputFileVarName, imageBlob); form.set( 'contentAnalyzerRequests', JSON.stringify({ @@ -98,7 +148,7 @@ export default class FireflyManager extends ApiManager { multipart .parse(Buffer.from(arrayBuffer), 'Boundary' + (response2.headers.get('content-type')?.match(/=Boundary(.*);/)?.[1] ?? '')) .filter(part => part.name === outputVarName) - .map(part => JSON.parse(part.data.toString()[0])) + .map(part => JSON.parse(part.data.toString())[0]) .reduce((text, json) => text + (json?.is_text_present ? json.tags.map((tag: { text: string }) => tag.text).join(' ') : ''), '') ) .catch(error => { @@ -117,10 +167,10 @@ export default class FireflyManager extends ApiManager { method: Method.POST, subscription: '/queryFireflyImage', secureHandler: ({ req, res }) => - this.askFirefly(req.body.prompt).then(fire => - DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { + this.generateImage(req.body.prompt).then(url => + DashUploadUtils.UploadImage(url ?? '').then(info => { if (info instanceof Error) _invalid(res, info.message); - else _success(res, info.accessPaths.agnostic.client); + else _success(res, info); }) ), }); @@ -128,6 +178,7 @@ export default class FireflyManager extends ApiManager { register({ method: Method.POST, subscription: '/queryFireflyImageText', + // eslint-disable-next-line @typescript-eslint/no-unused-vars secureHandler: ({ req, res }) => fetch('http://localhost:1050/files/images/testshot.png').then(json => json.blob().then(file => @@ -137,5 +188,40 @@ export default class FireflyManager extends ApiManager { ) ), }); + register({ + method: Method.POST, + subscription: '/expandImage', + secureHandler: ({ req, res }) => + new Promise((resolve, reject) => { + const dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN }); + fs.readFile(path.join(filesDirectory, `${Directory.images}/${path.basename(req.body.file)}`), undefined, (err, contents) => { + if (err) { + console.log('Error: ', err); + reject(); + } else { + dbx.filesUpload({ path: `/Apps/browndash/${path.basename(req.body.file)}`, contents }) + .then(response => { + dbx.filesGetTemporaryLink({ path: response.result.path_display ?? '' }).then(link => { + console.log(link.result); + this.expandImage(link.result.link, req.body.prompt).then(text => { + if (text.error_code) _error(res, text.message); + else + DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info); + resolve(); + }); + }); + }); + }) + .catch(uploadErr => { + console.log(uploadErr); + _error(res, 'upload to dropbox failed'); + reject(); + }); + } + }); + }), + }); } } diff --git a/src/server/ApiManagers/UploadManager.ts b/src/server/ApiManagers/UploadManager.ts index 7bfdd5aec..5a880901b 100644 --- a/src/server/ApiManagers/UploadManager.ts +++ b/src/server/ApiManagers/UploadManager.ts @@ -70,10 +70,16 @@ export default class UploadManager extends ApiManager { ]); } else { fileguids.split(';').map(guid => DashUploadUtils.uploadProgress.set(guid, `resampling images`)); + // original filenames with '.'s, such as a Macbook screenshot, can be a problem - their extension is not kept in formidable's newFilename. + // This makes sure that the extension is preserved in the newFilename. + const fixNewFilename = (f: formidable.File) => { + if (path.extname(f.originalFilename ?? '') !== path.extname(f.newFilename)) f.newFilename = f.newFilename + path.extname(f.originalFilename ?? ''); + return f; + }; const results = ( await Promise.all( Array.from(Object.keys(files)).map( - async key => (!files[key] ? undefined : DashUploadUtils.upload(files[key]![0] /* , key */)) // key is the guid used by the client to track upload progress. + async key => (!files[key] ? undefined : DashUploadUtils.upload(fixNewFilename(files[key][0]) /* , key */)) // key is the guid used by the client to track upload progress. ) ) ).filter(result => result && !(result.result instanceof Error)); diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index 028116779..a06fa3b6e 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -22,7 +22,6 @@ import { AzureManager } from './ApiManagers/AzureManager'; import { AcceptableMedia, Upload } from './SharedMediaTypes'; import { Directory, clientPathToFile, filesDirectory, pathToDirectory, publicDirectory, serverPathToFile } from './SocketData'; import { resolvedServerUrl } from './server_Initialization'; - import { Worker, isMainThread, parentPort } from 'worker_threads'; // Create an array to store worker threads @@ -55,7 +54,8 @@ if (isMainThread) { .then(img => sizes.forEach(({ width, suffix }) => img.resize({ w: width || img.bitmap.width }) - .write(InjectSize(outputPath, suffix) as `${string}.${string}`) + .write(InjectSize(outputPath, suffix) as `${string}.${string}`) + .catch(e => console.log("Jimp error:", e)) )) .catch(e => console.log('Error Jimp:', e)) .finally(() => unlinkSource && unlinkSync(imgSourcePath)); @@ -343,15 +343,24 @@ export namespace DashUploadUtils { const outputPath = path.resolve(pathToDirectory(Directory.images), outputFileName); const sizes = imageResampleSizes(path.extname(outputFileName)); - const imgReadStream = new Duplex(); - imgReadStream.push(fs.readFileSync(imgSourcePath)); - imgReadStream.push(null); - await Promise.all( - sizes.map(({ suffix }) => - new Promise(res => - imgReadStream.pipe(createWriteStream(writtenFiles[suffix] = InjectSize(outputPath, suffix))).on('close', res) - ) - )); // prettier-ignore + if (unlinkSource) { + const imgReadStream = new Duplex(); + imgReadStream.push(fs.readFileSync(imgSourcePath)); + imgReadStream.push(null); + await Promise.all( + sizes.map(({ suffix }) => + new Promise(res => + imgReadStream.pipe(createWriteStream(writtenFiles[suffix] = InjectSize(outputPath, suffix))).on('close', res) + ) + )); // prettier-ignore + } else { + await Promise.all( + sizes.map(({ suffix }) => + new Promise(res => + request.get(imgSourcePath).pipe(createWriteStream(writtenFiles[suffix] = InjectSize(outputPath, suffix))).on('close', res) + ) + )); // prettier-ignore + } workerResample(imgSourcePath, outputPath, SizeSuffix.Original, unlinkSource); return writtenFiles; @@ -450,7 +459,7 @@ export namespace DashUploadUtils { } const outputFile = filename || result.filename || ''; - return UploadInspectedImage(result, outputFile, prefix); + return UploadInspectedImage(result, outputFile, prefix, isLocal().exec(source) ? true : false); }; type md5 = 'md5'; @@ -568,7 +577,9 @@ export namespace DashUploadUtils { switch (category) { case 'image': if (imageFormats.includes(format)) { - const result = await UploadImage(filepath, basename(filepath)); + const outputName = basename(filepath); + const extname = path.extname(originalFilename ?? ''); + const result = await UploadImage(filepath, outputName.endsWith(extname) ? outputName : outputName + extname, undefined); return { source: file, result }; } fs.unlink(filepath, () => {}); -- cgit v1.2.3-70-g09d2 From 0034a4b7d1bbaf5c6909d76b1a2dac85054fa4ff Mon Sep 17 00:00:00 2001 From: bobzel Date: Sat, 14 Dec 2024 14:27:03 -0500 Subject: preparing to merge --- src/client/views/smartdraw/DrawingFillHandler.tsx | 6 ++--- src/server/ApiManagers/FireflyManager.ts | 28 +++-------------------- 2 files changed, 6 insertions(+), 28 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index 8f71b150d..6f111e95b 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -23,9 +23,9 @@ // const response = await fetch(hrefComplete); // const blob: Blob = await response.blob(); // const strength: number = 100; -// const img = await Networking.PostToServer('/queryFireflyImage', { prompt, blob, strength }); +// const img = await Networking.PostToServer('/oldQueryFireflyImage', { prompt, blob, strength }); // DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight); -// // Networking.PostToServer('/queryFireflyImage', { prompt, blob, strength }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight)); +// // Networking.PostToServer('/oldQueryFireflyImage', { prompt, blob, strength }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight)); // } catch (error) { // console.error('Error fetching image:', error); // return; @@ -44,7 +44,7 @@ // // ctx.drawImage(image, 0, 0); // // const blob: Blob = await ImageUtility.canvasToBlob(canvas); // // const strength: number = 100; -// // Networking.PostToServer('/queryFireflyImage', { prompt, blob, strength }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight)); +// // Networking.PostToServer('/oldQueryFireflyImage', { prompt, blob, strength }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight)); // // }; // }; // } diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 55fa1e461..d9a1ef621 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -14,30 +14,8 @@ export default class FireflyManager extends ApiManager { console.error('Error:', error); return ''; }); - // askFirefly = (prompt: string = 'a realistic illustration of a cat coding') => { - // const fetched = this.getBearerToken().then(response => - // response.json().then((data: { access_token: string }) => - // fetch('https://firefly-api.adobe.io/v3/images/generate', { - // method: 'POST', - // headers: [ - // ['Content-Type', 'application/json'], - // ['Accept', 'application/json'], - // ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], - // ['Authorization', `Bearer ${data.access_token}`], - // ], - // body: `{ "prompt": "${prompt}" }`, - // }) - // .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) - // .catch(error => { - // console.error('Error:', error); - // return ''; - // }) - // ) - // ); - // return fetched; - // }; - askFirefly = (prompt: string = 'a realistic illustration of a cat coding', uploadId: string, strength: number) => { + askFireflyOld = (prompt: string = 'a realistic illustration of a cat coding', uploadId: string, strength: number) => { const fetched = this.getBearerToken().then(response => response.json().then((data: { access_token: string }) => { const body: any = { @@ -97,11 +75,11 @@ export default class FireflyManager extends ApiManager { protected initialize(register: Registration): void { register({ method: Method.POST, - subscription: '/queryFireflyImage', + subscription: '/oldQueryFireflyImage', secureHandler: async ({ req, res }) => { const { prompt, imageBlob, strength = 0.5 } = req.body; const uploadId = imageBlob ? await this.uploadImageToFirefly(imageBlob) : null; - this.askFirefly(prompt, uploadId, strength).then(fire => + this.askFireflyOld(prompt, uploadId, strength).then(fire => DashUploadUtils.UploadImage(JSON.parse(fire).url).then(info => { if (info instanceof Error) _invalid(res, info.message); else _success(res, info.accessPaths.agnostic.client); -- cgit v1.2.3-70-g09d2 From 38b8c63d374415142acefcf6b6f736646f78de44 Mon Sep 17 00:00:00 2001 From: bobzel Date: Sat, 14 Dec 2024 14:37:50 -0500 Subject: starting merge with master --- src/server/ApiManagers/FireflyManager.ts | 217 ++++++++++++++++++++++++++++++- 1 file changed, 212 insertions(+), 5 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index d9a1ef621..4425aff43 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -1,5 +1,10 @@ +import { Dropbox, files } from 'dropbox'; +import * as fs from 'fs'; +import * as multipart from 'parse-multipart-data'; +import * as path from 'path'; import { DashUploadUtils } from '../DashUploadUtils'; -import { _invalid, _success, Method } from '../RouteManager'; +import { _error, _invalid, _success, Method } from '../RouteManager'; +import { Directory, filesDirectory } from '../SocketData'; import ApiManager, { Registration } from './ApiManager'; export default class FireflyManager extends ApiManager { @@ -12,12 +17,12 @@ export default class FireflyManager extends ApiManager { body: `grant_type=client_credentials&client_id=${process.env._CLIENT_FIREFLY_CLIENT_ID}&client_secret=${process.env._CLIENT_FIREFLY_SECRET}&scope=openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis`, }).catch(error => { console.error('Error:', error); - return ''; + return undefined; }); askFireflyOld = (prompt: string = 'a realistic illustration of a cat coding', uploadId: string, strength: number) => { const fetched = this.getBearerToken().then(response => - response.json().then((data: { access_token: string }) => { + response?.json().then((data: { access_token: string }) => { const body: any = { prompt: prompt, structure: { @@ -51,7 +56,7 @@ export default class FireflyManager extends ApiManager { uploadImageToFirefly = (image: Blob) => { const fetched = this.getBearerToken().then(response => - response.json().then((data: { access_token: string }) => + response?.json().then((data: { access_token: string }) => fetch('https://firefly-api.adobe.io/v3/uploads', { method: 'POST', headers: [ @@ -71,7 +76,149 @@ export default class FireflyManager extends ApiManager { ); return fetched; }; - + generateImage = (prompt: string = 'a realistic illustration of a cat coding') => { + const fetched = this.getBearerToken().then(response => + response?.json().then((data: { access_token: string }) => + fetch('https://firefly-api.adobe.io/v3/images/generate', { + method: 'POST', + headers: [ + ['Content-Type', 'application/json'], + ['Accept', 'application/json'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${data.access_token}`], + ], + body: `{ "prompt": "${prompt}" }`, + }) + .then(response2 => response2.json().then(json => (json.outputs?.[0] as { image: { url: string } })?.image.url)) + .catch(error => { + console.error('Error:', error); + return undefined; + }) + ) + ); + return fetched; + }; + expandImage = (imgUrl: string, prompt?: string) => { + const dropboxImgUrl = imgUrl; + const fetched = this.getBearerToken().then(response => + response + ?.json() + .then((data: { access_token: string }) => { + return fetch('https://firefly-api.adobe.io/v3/images/expand', { + method: 'POST', + headers: [ + ['Content-Type', 'application/json'], + ['Accept', 'application/json'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + ['Authorization', `Bearer ${data.access_token}`], + ], + body: JSON.stringify({ + image: { + source: { + url: dropboxImgUrl, + }, + }, + numVariations: 1, + seeds: [0], + size: { + width: 3048, + height: 2048, + }, + prompt: prompt ?? 'cloudy skies', + placement: { + inset: { + left: 0, + top: 0, + right: 0, + bottom: 0, + }, + alignment: { + horizontal: 'center', + vertical: 'center', + }, + }, + }), + }); + }) + .then(resp => resp.json()) + ); + return fetched; + }; + getImageText = (imageBlob: Blob) => { + const inputFileVarName = 'infile'; + const outputVarName = 'result'; + const fetched = this.getBearerToken().then(response => + response?.json().then((data: { access_token: string }) => { + return fetch('https://sensei.adobe.io/services/v2/predict', { + method: 'POST', + headers: [ + ['Prefer', 'respond-async, wait=59'], + ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], + // ['content-type', 'multipart/form-data'], // bcz: Don't set this!! content-type will get set automatically including the Boundary string + ['Authorization', `Bearer ${data.access_token}`], + ], + body: ((form: FormData) => { + form.set(inputFileVarName, imageBlob); + form.set( + 'contentAnalyzerRequests', + JSON.stringify({ + 'sensei:name': 'Feature:cintel-object-detection:Service-b9ace8b348b6433e9e7d82371aa16690', + 'sensei:invocation_mode': 'asynchronous', + 'sensei:invocation_batch': false, + 'sensei:engines': [ + { + 'sensei:execution_info': { + 'sensei:engine': 'Feature:cintel-object-detection:Service-b9ace8b348b6433e9e7d82371aa16690', + }, + 'sensei:inputs': { + documents: [ + { + 'sensei:multipart_field_name': inputFileVarName, + 'dc:format': 'image/png', + }, + ], + }, + 'sensei:params': { + correct_with_dictionary: true, + }, + 'sensei:outputs': { + result: { + 'sensei:multipart_field_name': outputVarName, + 'dc:format': 'application/json', + }, + }, + }, + ], + }) + ); + return form; + })(new FormData()), + }).then(response2 => { + const contentType = response2.headers.get('content-type') ?? ''; + if (contentType.includes('application/json')) { + return response2.json().then((json: object) => JSON.stringify(json)); + } + if (contentType.includes('multipart')) { + return response2 + .arrayBuffer() + .then(arrayBuffer => + multipart + .parse(Buffer.from(arrayBuffer), 'Boundary' + (response2.headers.get('content-type')?.match(/=Boundary(.*);/)?.[1] ?? '')) + .filter(part => part.name === outputVarName) + .map(part => JSON.parse(part.data.toString())[0]) + .reduce((text, json) => text + (json?.is_text_present ? json.tags.map((tag: { text: string }) => tag.text).join(' ') : ''), '') + ) + .catch(error => { + console.error('Error:', error); + return ''; + }); + } + return response2.text(); + }); + }) + ); + return fetched; + }; protected initialize(register: Registration): void { register({ method: Method.POST, @@ -87,5 +234,65 @@ export default class FireflyManager extends ApiManager { ); }, }); + register({ + method: Method.POST, + subscription: '/queryFireflyImage', + secureHandler: ({ req, res }) => + this.generateImage(req.body.prompt).then(url => + DashUploadUtils.UploadImage(url ?? '').then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info); + }) + ), + }); + + register({ + method: Method.POST, + subscription: '/queryFireflyImageText', + // eslint-disable-next-line @typescript-eslint/no-unused-vars + secureHandler: ({ req, res }) => + fetch('http://localhost:1050/files/images/testshot.png').then(json => + json.blob().then(file => + this.getImageText(file).then(text => { + _success(res, text); + }) + ) + ), + }); + register({ + method: Method.POST, + subscription: '/expandImage', + secureHandler: ({ req, res }) => + new Promise((resolve, reject) => { + const dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN }); + fs.readFile(path.join(filesDirectory, `${Directory.images}/${path.basename(req.body.file)}`), undefined, (err, contents) => { + if (err) { + console.log('Error: ', err); + reject(); + } else { + dbx.filesUpload({ path: `/Apps/browndash/${path.basename(req.body.file)}`, contents }) + .then(response => { + dbx.filesGetTemporaryLink({ path: response.result.path_display ?? '' }).then(link => { + console.log(link.result); + this.expandImage(link.result.link, req.body.prompt).then(text => { + if (text.error_code) _error(res, text.message); + else + DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info); + resolve(); + }); + }); + }); + }) + .catch(uploadErr => { + console.log(uploadErr); + _error(res, 'upload to dropbox failed'); + reject(); + }); + } + }); + }), + }); } } -- cgit v1.2.3-70-g09d2 From b7105063030ee29ba644d8fbb5878c8ee41fd389 Mon Sep 17 00:00:00 2001 From: bobzel Date: Mon, 16 Dec 2024 11:52:42 -0500 Subject: fixed api for creating an image using another image as a structure reference. --- src/client/views/ContextMenuItem.tsx | 10 +- src/client/views/PropertiesView.tsx | 4 +- .../CollectionFreeFormLayoutEngines.tsx | 3 - src/client/views/nodes/DocumentView.tsx | 4 +- src/client/views/nodes/ImageBox.tsx | 3 +- src/client/views/smartdraw/DrawingFillHandler.tsx | 70 ++++------- src/server/ApiManagers/FireflyManager.ts | 132 ++++++++------------- 7 files changed, 82 insertions(+), 144 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/views/ContextMenuItem.tsx b/src/client/views/ContextMenuItem.tsx index 6f8f41bdd..218718b18 100644 --- a/src/client/views/ContextMenuItem.tsx +++ b/src/client/views/ContextMenuItem.tsx @@ -1,6 +1,6 @@ import { IconProp } from '@fortawesome/fontawesome-svg-core'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { action, makeObservable, observable, runInAction } from 'mobx'; +import { action, computed, makeObservable, observable } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; import { SnappingManager } from '../util/SnappingManager'; @@ -26,7 +26,7 @@ export class ContextMenuItem extends ObservableReactComponent this._items.push(...(this._props.subitems ?? []))); + @computed get items() { + return this._items.concat(this._props.subitems ?? []); } handleEvent = async (e: React.MouseEvent) => { @@ -91,7 +91,7 @@ export class ContextMenuItem extends ObservableReactComponent ); + const submenu = this.items.map(prop => ); return this.props.event || this._props.noexpand ? this.renderItem(submenu) :
{submenu}
; } } diff --git a/src/client/views/PropertiesView.tsx b/src/client/views/PropertiesView.tsx index 4e12e0b2d..aefdeee17 100644 --- a/src/client/views/PropertiesView.tsx +++ b/src/client/views/PropertiesView.tsx @@ -995,9 +995,7 @@ export class PropertiesView extends ObservableReactComponent { - DrawingFillHandler.drawingToImage(targetDoc, 'fill in the details of this image'); - }, 'createImage')} + onClick={undoable(() => DrawingFillHandler.drawingToImage(targetDoc, 'fill in the details of this image'), 'createImage')} />
diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx index 79aad0ef2..272c13546 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx @@ -102,7 +102,6 @@ export function computePassLayout(poolData: Map, pivotDoc: Doc replica: '', }); }); - // eslint-disable-next-line no-use-before-define return normalizeResults(panelDim, 12, docMap, poolData, viewDefsToJSX, [], 0, []); } @@ -272,7 +271,6 @@ export function computePivotLayout(poolData: Map, pivotDoc: Do payload: pivotColumnGroups.get(key)?.filters, })); groupNames.push(...dividers); - // eslint-disable-next-line no-use-before-define return normalizeResults(panelDim, maxText, docMap, poolData, viewDefsToJSX, groupNames, 0, []); } @@ -347,7 +345,6 @@ export function computeTimelineLayout(poolData: Map, pivotDoc: if (!stack && (curTime === undefined || Math.abs(x - (curTime - minTime) * scaling) > pivotAxisWidth)) { groupNames.push({ type: 'text', text: toLabel(key), x: x, y: stack * 25, height: fontHeight, fontSize, payload: undefined }); } - // eslint-disable-next-line no-use-before-define layoutDocsAtTime(keyDocs, key); }); if (sortedKeys.length && curTime !== undefined && curTime > sortedKeys[sortedKeys.length - 1]) { diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 4bfa7fc92..8519cda3c 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -52,6 +52,7 @@ import { FormattedTextBox } from './formattedText/FormattedTextBox'; import { PresEffect, PresEffectDirection } from './trails/PresEnums'; import SpringAnimation from './trails/SlideEffect'; import { SpringType, springMappings } from './trails/SpringUtils'; +import { DrawingFillHandler } from '../smartdraw/DrawingFillHandler'; export interface DocumentViewProps extends FieldViewSharedProps { hideDecorations?: boolean; // whether to suppress all DocumentDecorations when doc is selected @@ -551,6 +552,7 @@ export class DocumentViewInternal extends DocComponent DocumentView.SetLightboxDoc(this.Document), icon: 'external-link-alt' }); } appearanceItems.push({ description: 'Pin', event: () => this._props.pinToPres(this.Document, {}), icon: 'map-pin' }); + appearanceItems.push({ description: 'Make Image', event: () => DrawingFillHandler.drawingToImage(this.Document, StrCast(this.Document.title)), icon: 'map-pin' }); !Doc.noviceMode && templateDoc && appearanceItems.push({ description: 'Open Template ', event: () => this._props.addDocTab(templateDoc, OpenWhere.addRight), icon: 'eye' }); !appearance && appearanceItems.length && cm.addItem({ description: 'Appearance...', subitems: appearanceItems, icon: 'compass' }); @@ -1072,7 +1074,7 @@ export class DocumentView extends DocComponent() { public static GetDocImage(doc: Doc) { return DocumentView.getDocumentView(doc) ?.ComponentView?.updateIcon?.() - .then(() => ImageCast(DocCast(doc).icon)); + .then(() => ImageCast(doc?.icon, ImageCast(doc[Doc.LayoutFieldKey(doc)]))); } public get displayName() { return 'DocumentView(' + (this.Document?.title??"") + ')'; } // prettier-ignore diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index d847b7940..03d417e4e 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -40,7 +40,6 @@ import { FocusViewOptions } from './FocusViewOptions'; import './ImageBox.scss'; import { OpenWhere } from './OpenWhere'; import { Upload } from '../../../server/SharedMediaTypes'; -import { ImageUtils } from '../../util/Import & Export/ImageUtils'; export class ImageEditorData { // eslint-disable-next-line no-use-before-define @@ -361,6 +360,8 @@ export class ImageBox extends ViewBoxAnnotatableComponent() { } }; + updateIcon = () => new Promise(res => res()); + choosePath = (url: URL) => { if (!url?.href) return ''; const lower = url.href.toLowerCase(); diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index 6f111e95b..32416cec5 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -1,50 +1,22 @@ -// import { action, makeObservable } from 'mobx'; -// import { observer } from 'mobx-react'; -// import React from 'react'; -// import { Doc } from '../../../fields/Doc'; -// import { ImageCast } from '../../../fields/Types'; -// import { ImageField } from '../../../fields/URLField'; -// import { Docs } from '../../documents/Documents'; -// import { Networking } from '../../Network'; -// import { makeUserTemplateButtonOrImage } from '../../util/DropConverter'; -// import { DocumentView, DocumentViewInternal } from '../nodes/DocumentView'; -// import { ImageUtility } from '../nodes/imageEditor/imageEditorUtils/ImageHandler'; -// import { OpenWhere } from '../nodes/OpenWhere'; -// import { ObservableReactComponent } from '../ObservableReactComponent'; +import { Doc } from '../../../fields/Doc'; +import { ImageCast } from '../../../fields/Types'; +import { Upload } from '../../../server/SharedMediaTypes'; +import { Docs } from '../../documents/Documents'; +import { Networking } from '../../Network'; +import { DocumentView, DocumentViewInternal } from '../nodes/DocumentView'; +import { OpenWhere } from '../nodes/OpenWhere'; -// export class DrawingFillHandler { -// static drawingToImage = async (drawing: Doc, prompt: string) => { -// const imageField = await DocumentView.GetDocImage(drawing); -// if (!imageField) return; -// const { href } = ImageCast(imageField).url; -// const hrefParts = href.split('.'); -// const hrefComplete = `${hrefParts[0]}_o.${hrefParts[1]}`; -// try { -// const response = await fetch(hrefComplete); -// const blob: Blob = await response.blob(); -// const strength: number = 100; -// const img = await Networking.PostToServer('/oldQueryFireflyImage', { prompt, blob, strength }); -// DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight); -// // Networking.PostToServer('/oldQueryFireflyImage', { prompt, blob, strength }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight)); -// } catch (error) { -// console.error('Error fetching image:', error); -// return; -// } - -// // const image = new Image(); -// // image.src = imageField.url?.href; -// // // image.onload = async () => { -// // const canvas = document.createElement('canvas'); -// // canvas.width = image.width; -// // canvas.height = image.height; -// // const ctx = canvas.getContext('2d'); -// // if (!ctx) return; -// // ctx.globalCompositeOperation = 'source-over'; -// // ctx.clearRect(0, 0, image.width, image.height); -// // ctx.drawImage(image, 0, 0); -// // const blob: Blob = await ImageUtility.canvasToBlob(canvas); -// // const strength: number = 100; -// // Networking.PostToServer('/oldQueryFireflyImage', { prompt, blob, strength }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img, {}), OpenWhere.addRight)); -// // }; -// }; -// } +export class DrawingFillHandler { + static drawingToImage = (drawing: Doc, prompt: string) => + DocumentView.GetDocImage(drawing)?.then(imageField => { + if (imageField) { + const { href } = ImageCast(imageField).url; + const hrefParts = href.split('.'); + const structureUrl = `${hrefParts[0]}_o.${hrefParts[1]}`; + const strength: number = 100; + Networking.PostToServer('/queryFireflyImageFromStructure', { prompt, structureUrl, strength }).then((info: Upload.ImageInformation) => + DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, {}), OpenWhere.addRight)) // prettier-ignore + } + return false; + }); +} diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 73cf94206..c84e9e8fa 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -20,21 +20,10 @@ export default class FireflyManager extends ApiManager { return undefined; }); - askFireflyOld = (prompt: string = 'a realistic illustration of a cat coding', uploadId: string, strength: number) => { - const fetched = this.getBearerToken().then(response => - response?.json().then((data: { access_token: string }) => { - const body: any = { - prompt: prompt, - structure: { - strength: strength, - imageReference: { - source: { - uploadId: uploadId, - }, - }, - }, - }; - return fetch('https://firefly-api.adobe.io/v3/images/generate', { + generateImageFromStructure = (prompt: string = 'a realistic illustration of a cat coding', structureUrl: string, strength: number) => + this.getBearerToken().then(response => + response?.json().then((data: { access_token: string }) => + fetch('https://firefly-api.adobe.io/v3/images/generate', { method: 'POST', headers: [ ['Content-Type', 'application/json'], @@ -42,40 +31,40 @@ export default class FireflyManager extends ApiManager { ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], ['Authorization', `Bearer ${data.access_token}`], ], - body: JSON.stringify(body), + body: JSON.stringify({ + prompt, + structure: !structureUrl + ? undefined + : { + strength, + imageReference: { + source: { url: structureUrl }, + }, + }, + }), }) - .then(response => response.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) + .then(response2 => response2.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) .catch(error => { console.error('Error:', error); return ''; + }) + ) + ); + + uploadImageToDropbox = (fileUrl: string, dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN })) => + new Promise((res, rej) => + fs.readFile(path.join(filesDirectory, `${Directory.images}/${path.basename(fileUrl)}`), undefined, (err, contents) => { + if (err) { + console.log('Error: ', err); + rej(); + } else { + dbx.filesUpload({ path: `/Apps/browndash/${path.basename(fileUrl)}`, contents }).then(response => { + dbx.filesGetTemporaryLink({ path: response.result.path_display ?? '' }).then(link => res(link.result.link)); }); + } }) ); - return fetched; - }; - uploadImageToFirefly = (image: Blob) => { - const fetched = this.getBearerToken().then(response => - response?.json().then((data: { access_token: string }) => - fetch('https://firefly-api.adobe.io/v3/uploads', { - method: 'POST', - headers: [ - ['Content-Type', image.type], - ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], - ['Authorization', `Bearer ${data.access_token}`], - ], - body: image, - }) - .then(response => response.json()) - .then(data => data.uploadId) // Extract the uploadId from the response - .catch(error => { - console.error('Error:', error); - return ''; - }) - ) - ); - return fetched; - }; generateImage = (prompt: string = 'a realistic illustration of a cat coding') => { const fetched = this.getBearerToken().then(response => response?.json().then((data: { access_token: string }) => @@ -222,17 +211,16 @@ export default class FireflyManager extends ApiManager { protected initialize(register: Registration): void { register({ method: Method.POST, - subscription: '/oldQueryFireflyImage', - secureHandler: async ({ req, res }) => { - const { prompt, imageBlob, strength = 0.5 } = req.body; - const uploadId = imageBlob ? await this.uploadImageToFirefly(imageBlob) : null; - this.askFireflyOld(prompt, uploadId, strength).then(fire => - DashUploadUtils.UploadImage(JSON.parse(fire ?? '').url).then(info => { - if (info instanceof Error) _invalid(res, info.message); - else _success(res, info); - }) - ); - }, + subscription: '/queryFireflyImageFromStructure', + secureHandler: async ({ req, res }) => + this.uploadImageToDropbox(req.body.structureUrl).then(uploadUrl => + this.generateImageFromStructure(req.body.prompt, uploadUrl, req.body.strength).then(fire => + DashUploadUtils.UploadImage(JSON.parse(fire ?? '').url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info); + }) + ) + ), }); register({ method: Method.POST, @@ -263,36 +251,16 @@ export default class FireflyManager extends ApiManager { method: Method.POST, subscription: '/expandImage', secureHandler: ({ req, res }) => - new Promise((resolve, reject) => { - const dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN }); - fs.readFile(path.join(filesDirectory, `${Directory.images}/${path.basename(req.body.file)}`), undefined, (err, contents) => { - if (err) { - console.log('Error: ', err); - reject(); - } else { - dbx.filesUpload({ path: `/Apps/browndash/${path.basename(req.body.file)}`, contents }) - .then(response => { - dbx.filesGetTemporaryLink({ path: response.result.path_display ?? '' }).then(link => { - console.log(link.result); - this.expandImage(link.result.link, req.body.prompt).then(text => { - if (text.error_code) _error(res, text.message); - else - DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => { - if (info instanceof Error) _invalid(res, info.message); - else _success(res, info); - resolve(); - }); - }); - }); - }) - .catch(uploadErr => { - console.log(uploadErr); - _error(res, 'upload to dropbox failed'); - reject(); - }); - } - }); - }), + this.uploadImageToDropbox(req.body.file).then(uploadUrl => + this.expandImage(uploadUrl, req.body.prompt).then(text => { + if (text.error_code) _error(res, text.message); + else + DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info); + }); + }) + ), }); } } -- cgit v1.2.3-70-g09d2 From d5c4751b1522535ad323bb5eb254b7a1a7b4a63f Mon Sep 17 00:00:00 2001 From: bobzel Date: Tue, 17 Dec 2024 15:03:07 -0500 Subject: added updateIcon to imageBoxes to allow capturing of strokes for use with generative apis --- src/client/views/nodes/ImageBox.tsx | 26 ++++++++++++++++++++++++-- src/server/ApiManagers/FireflyManager.ts | 2 +- 2 files changed, 25 insertions(+), 3 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 03d417e4e..25e7b566f 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -7,7 +7,7 @@ import { observer } from 'mobx-react'; import { extname } from 'path'; import * as React from 'react'; import ReactLoading from 'react-loading'; -import { ClientUtils, DashColor, returnEmptyString, returnFalse, returnOne, returnZero, setupMoveUpEvents } from '../../../ClientUtils'; +import { ClientUtils, DashColor, returnEmptyString, returnFalse, returnOne, returnZero, setupMoveUpEvents, UpdateIcon } from '../../../ClientUtils'; import { Doc, DocListCast, Opt } from '../../../fields/Doc'; import { DocData } from '../../../fields/DocSymbols'; import { Id } from '../../../fields/FieldSymbols'; @@ -360,7 +360,29 @@ export class ImageBox extends ViewBoxAnnotatableComponent() { } }; - updateIcon = () => new Promise(res => res()); + // updateIcon = () => new Promise(res => res()); + updateIcon = (usePanelDimensions?: boolean) => { + const contentDiv = this._mainCont.current; + return !contentDiv + ? new Promise(res => res()) + : UpdateIcon( + this.layoutDoc[Id] + '_icon_' + new Date().getTime(), + contentDiv, + usePanelDimensions ? this._props.PanelWidth() : NumCast(this.layoutDoc._width), + usePanelDimensions ? this._props.PanelHeight() : NumCast(this.layoutDoc._height), + this._props.PanelWidth(), + this._props.PanelHeight(), + 0, + 1, + false, + '', + (iconFile, nativeWidth, nativeHeight) => { + this.dataDoc.icon = new ImageField(iconFile); + this.dataDoc.icon_nativeWidth = nativeWidth; + this.dataDoc.icon_nativeHeight = nativeHeight; + } + ); + }; choosePath = (url: URL) => { if (!url?.href) return ''; diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index c84e9e8fa..e73795e41 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -239,7 +239,7 @@ export default class FireflyManager extends ApiManager { subscription: '/queryFireflyImageText', // eslint-disable-next-line @typescript-eslint/no-unused-vars secureHandler: ({ req, res }) => - fetch('http://localhost:1050/files/images/testshot.png').then(json => + fetch(req.body.file).then(json => json.blob().then(file => this.getImageText(file).then(text => { _success(res, text); -- cgit v1.2.3-70-g09d2 From ad1e0cf62187e0f8bbb19b4720b7681585361de9 Mon Sep 17 00:00:00 2001 From: "A.J. Shulman" Date: Wed, 18 Dec 2024 11:46:14 -0500 Subject: better --- extract_code.py | 39 + extracted_code.txt | 2914 ++++++++++++++++++++ package-lock.json | 151 +- package.json | 7 +- .../views/nodes/chatbot/agentsystem/Agent.ts | 6 +- .../views/nodes/chatbot/agentsystem/prompts.ts | 3 +- .../nodes/chatbot/chatboxcomponents/ChatBox.tsx | 144 +- src/client/views/nodes/chatbot/tools/BaseTool.ts | 16 +- .../views/nodes/chatbot/tools/CalculateTool.ts | 17 +- .../views/nodes/chatbot/tools/CreateAnyDocTool.ts | 25 +- .../views/nodes/chatbot/tools/CreateCSVTool.ts | 17 +- .../nodes/chatbot/tools/CreateTextDocumentTool.ts | 43 +- .../views/nodes/chatbot/tools/DataAnalysisTool.ts | 17 +- .../views/nodes/chatbot/tools/GetDocsTool.ts | 17 +- src/client/views/nodes/chatbot/tools/NoTool.ts | 11 +- src/client/views/nodes/chatbot/tools/RAGTool.ts | 28 +- .../nodes/chatbot/tools/ReplicateUserTaskTool.ts | 0 src/client/views/nodes/chatbot/tools/SearchTool.ts | 20 +- .../nodes/chatbot/tools/WebsiteInfoScraperTool.ts | 27 +- .../views/nodes/chatbot/tools/WikipediaTool.ts | 17 +- src/client/views/nodes/chatbot/types/tool_types.ts | 7 + src/client/views/nodes/chatbot/types/types.ts | 15 +- .../views/nodes/chatbot/vectorstore/Vectorstore.ts | 247 +- src/fields/Types.ts | 8 +- src/server/ApiManagers/AssistantManager.ts | 158 +- src/server/chunker/pdf_chunker.py | 54 +- 26 files changed, 3690 insertions(+), 318 deletions(-) create mode 100644 extract_code.py create mode 100644 extracted_code.txt create mode 100644 src/client/views/nodes/chatbot/tools/ReplicateUserTaskTool.ts (limited to 'src/server/ApiManagers') diff --git a/extract_code.py b/extract_code.py new file mode 100644 index 000000000..43e0150e2 --- /dev/null +++ b/extract_code.py @@ -0,0 +1,39 @@ +import os + +# List of files to extract code from, relative to the `src` folder +files = [ + "src/client/views/nodes/chatbot/agentsystem/Agent.ts", + "src/client/views/nodes/chatbot/agentsystem/prompts.ts", + "src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx", + "src/client/views/nodes/chatbot/chatboxcomponents/MessageComponent.tsx", + "src/client/views/nodes/chatbot/response_parsers/AnswerParser.ts", + "src/client/views/nodes/chatbot/response_parsers/StreamedAnswerParser.ts", + "src/client/views/nodes/chatbot/tools/BaseTool.ts", + "src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts", + "src/client/views/nodes/chatbot/tools/RAGTool.ts", + "src/client/views/nodes/chatbot/tools/SearchTool.ts", + "src/client/views/nodes/chatbot/tools/WebsiteInfoScraperTool.ts", + "src/client/views/nodes/chatbot/types/tool_types.ts", + "src/client/views/nodes/chatbot/types/types.ts", + "src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts", +] + +# Output file name +output_file = "extracted_code.txt" + +def extract_and_format_code(file_list, output_path): + with open(output_path, "w") as outfile: + for file in file_list: + # Since the script runs from the chatbot folder, prepend the relative path from chatbot to src + if os.path.exists(file): + with open(file, "r") as infile: + code = infile.read() + # Write formatted code to the output file + outfile.write(f"--- {file} ---\n\n```\n{code}\n```\n\n") + else: + print(f"File not found: {file}") + +# Run the extraction and formatting +extract_and_format_code(files, output_file) + +print(f"Code extracted and saved to {output_file}") diff --git a/extracted_code.txt b/extracted_code.txt new file mode 100644 index 000000000..495dc8008 --- /dev/null +++ b/extracted_code.txt @@ -0,0 +1,2914 @@ +--- src/client/views/nodes/chatbot/agentsystem/Agent.ts --- + +``` +import dotenv from 'dotenv'; +import { XMLBuilder, XMLParser } from 'fast-xml-parser'; +import OpenAI from 'openai'; +import { ChatCompletionMessageParam } from 'openai/resources'; +import { escape } from 'lodash'; // Imported escape from lodash +import { AnswerParser } from '../response_parsers/AnswerParser'; +import { StreamedAnswerParser } from '../response_parsers/StreamedAnswerParser'; +import { CalculateTool } from '../tools/CalculateTool'; +import { CreateCSVTool } from '../tools/CreateCSVTool'; +import { DataAnalysisTool } from '../tools/DataAnalysisTool'; +import { NoTool } from '../tools/NoTool'; +import { RAGTool } from '../tools/RAGTool'; +import { SearchTool } from '../tools/SearchTool'; +import { WebsiteInfoScraperTool } from '../tools/WebsiteInfoScraperTool'; +import { AgentMessage, ASSISTANT_ROLE, AssistantMessage, Observation, PROCESSING_TYPE, ProcessingInfo, TEXT_TYPE } from '../types/types'; +import { Vectorstore } from '../vectorstore/Vectorstore'; +import { getReactPrompt } from './prompts'; +import { BaseTool } from '../tools/BaseTool'; +import { Parameter, ParametersType, TypeMap } from '../types/tool_types'; +import { CreateTextDocTool } from '../tools/CreateTextDocumentTool'; +import { DocumentOptions } from '../../../../documents/Documents'; +import { CreateAnyDocumentTool } from '../tools/CreateAnyDocTool'; + +dotenv.config(); + +/** + * The Agent class handles the interaction between the assistant and the tools available, + * processes user queries, and manages the communication flow between the tools and OpenAI. + */ +export class Agent { + // Private properties + private client: OpenAI; + private messages: AgentMessage[] = []; + private interMessages: AgentMessage[] = []; + private vectorstore: Vectorstore; + private _history: () => string; + private _summaries: () => string; + private _csvData: () => { filename: string; id: string; text: string }[]; + private actionNumber: number = 0; + private thoughtNumber: number = 0; + private processingNumber: number = 0; + private processingInfo: ProcessingInfo[] = []; + private streamedAnswerParser: StreamedAnswerParser = new StreamedAnswerParser(); + private tools: Record>>; + + /** + * The constructor initializes the agent with the vector store and toolset, and sets up the OpenAI client. + * @param _vectorstore Vector store instance for document storage and retrieval. + * @param summaries A function to retrieve document summaries. + * @param history A function to retrieve chat history. + * @param csvData A function to retrieve CSV data linked to the assistant. + * @param addLinkedUrlDoc A function to add a linked document from a URL. + * @param createCSVInDash A function to create a CSV document in the dashboard. + */ + constructor( + _vectorstore: Vectorstore, + summaries: () => string, + history: () => string, + csvData: () => { filename: string; id: string; text: string }[], + addLinkedUrlDoc: (url: string, id: string) => void, + addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void, + createCSVInDash: (url: string, title: string, id: string, data: string) => void + ) { + // Initialize OpenAI client with API key from environment + this.client = new OpenAI({ apiKey: process.env.OPENAI_KEY, dangerouslyAllowBrowser: true }); + this.vectorstore = _vectorstore; + this._history = history; + this._summaries = summaries; + this._csvData = csvData; + + // Define available tools for the assistant + this.tools = { + calculate: new CalculateTool(), + rag: new RAGTool(this.vectorstore), + dataAnalysis: new DataAnalysisTool(csvData), + websiteInfoScraper: new WebsiteInfoScraperTool(addLinkedUrlDoc), + searchTool: new SearchTool(addLinkedUrlDoc), + createCSV: new CreateCSVTool(createCSVInDash), + noTool: new NoTool(), + createTextDoc: new CreateTextDocTool(addLinkedDoc), + //createAnyDocument: new CreateAnyDocumentTool(addLinkedDoc), + }; + } + + /** + * This method handles the conversation flow with the assistant, processes user queries, + * and manages the assistant's decision-making process, including tool actions. + * @param question The user's question. + * @param onProcessingUpdate Callback function for processing updates. + * @param onAnswerUpdate Callback function for answer updates. + * @param maxTurns The maximum number of turns to allow in the conversation. + * @returns The final response from the assistant. + */ + async askAgent(question: string, onProcessingUpdate: (processingUpdate: ProcessingInfo[]) => void, onAnswerUpdate: (answerUpdate: string) => void, maxTurns: number = 30): Promise { + console.log(`Starting query: ${question}`); + const MAX_QUERY_LENGTH = 1000; // adjust the limit as needed + + // Check if the question exceeds the maximum length + if (question.length > MAX_QUERY_LENGTH) { + return { role: ASSISTANT_ROLE.ASSISTANT, content: [{ text: 'User query too long. Please shorten your question and try again.', index: 0, type: TEXT_TYPE.NORMAL, citation_ids: null }], processing_info: [] }; + } + + const sanitizedQuestion = escape(question); // Sanitized user input + + // Push sanitized user's question to message history + this.messages.push({ role: 'user', content: sanitizedQuestion }); + + // Retrieve chat history and generate system prompt + const chatHistory = this._history(); + const systemPrompt = getReactPrompt(Object.values(this.tools), this._summaries, chatHistory); + + // Initialize intermediate messages + this.interMessages = [{ role: 'system', content: systemPrompt }]; + + this.interMessages.push({ + role: 'user', + content: this.constructUserPrompt(1, 'user', `${sanitizedQuestion}`), + }); + + // Setup XML parser and builder + const parser = new XMLParser({ + ignoreAttributes: false, + attributeNamePrefix: '@_', + textNodeName: '_text', + isArray: name => ['query', 'url'].indexOf(name) !== -1, + processEntities: false, // Disable processing of entities + stopNodes: ['*.entity'], // Do not process any entities + }); + const builder = new XMLBuilder({ ignoreAttributes: false, attributeNamePrefix: '@_' }); + + let currentAction: string | undefined; + this.processingInfo = []; + + let i = 2; + while (i < maxTurns) { + console.log(this.interMessages); + console.log(`Turn ${i}/${maxTurns}`); + + const result = await this.execute(onProcessingUpdate, onAnswerUpdate); + this.interMessages.push({ role: 'assistant', content: result }); + + i += 2; + + let parsedResult; + try { + // Parse XML result from the assistant + parsedResult = parser.parse(result); + + // Validate the structure of the parsedResult + this.validateAssistantResponse(parsedResult); + } catch (error) { + throw new Error(`Error parsing or validating response: ${error}`); + } + + // Extract the stage from the parsed result + const stage = parsedResult.stage; + if (!stage) { + throw new Error(`Error: No stage found in response`); + } + + // Handle different stage elements (thoughts, actions, inputs, answers) + for (const key in stage) { + if (key === 'thought') { + // Handle assistant's thoughts + console.log(`Thought: ${stage[key]}`); + this.processingNumber++; + } else if (key === 'action') { + // Handle action stage + currentAction = stage[key] as string; + console.log(`Action: ${currentAction}`); + + if (this.tools[currentAction]) { + // Prepare the next action based on the current tool + const nextPrompt = [ + { + type: 'text', + text: `` + builder.build({ action_rules: this.tools[currentAction].getActionRule() }) + ``, + } as Observation, + ]; + this.interMessages.push({ role: 'user', content: nextPrompt }); + break; + } else { + // Handle error in case of an invalid action + console.log('Error: No valid action'); + this.interMessages.push({ + role: 'user', + content: `No valid action, try again.`, + }); + break; + } + } else if (key === 'action_input') { + // Handle action input stage + const actionInput = stage[key]; + console.log(`Action input:`, actionInput.inputs); + + if (currentAction) { + try { + // Process the action with its input + const observation = (await this.processAction(currentAction, actionInput.inputs)) as Observation[]; + const nextPrompt = [{ type: 'text', text: ` ` }, ...observation, { type: 'text', text: '' }] as Observation[]; + console.log(observation); + this.interMessages.push({ role: 'user', content: nextPrompt }); + this.processingNumber++; + break; + } catch (error) { + throw new Error(`Error processing action: ${error}`); + } + } else { + throw new Error('Error: Action input without a valid action'); + } + } else if (key === 'answer') { + // If an answer is found, end the query + console.log('Answer found. Ending query.'); + this.streamedAnswerParser.reset(); + const parsedAnswer = AnswerParser.parse(result, this.processingInfo); + return parsedAnswer; + } + } + } + + throw new Error('Reached maximum turns. Ending query.'); + } + + private constructUserPrompt(stageNumber: number, role: string, content: string): string { + return `${content}`; + } + + /** + * Executes a step in the conversation, processing the assistant's response and parsing it in real-time. + * @param onProcessingUpdate Callback for processing updates. + * @param onAnswerUpdate Callback for answer updates. + * @returns The full response from the assistant. + */ + private async execute(onProcessingUpdate: (processingUpdate: ProcessingInfo[]) => void, onAnswerUpdate: (answerUpdate: string) => void): Promise { + // Stream OpenAI response for real-time updates + const stream = await this.client.chat.completions.create({ + model: 'gpt-4o', + messages: this.interMessages as ChatCompletionMessageParam[], + temperature: 0, + stream: true, + stop: [''], + }); + + let fullResponse: string = ''; + let currentTag: string = ''; + let currentContent: string = ''; + let isInsideTag: boolean = false; + + // Process each chunk of the streamed response + for await (const chunk of stream) { + const content = chunk.choices[0]?.delta?.content || ''; + fullResponse += content; + + // Parse the streamed content character by character + for (const char of content) { + if (currentTag === 'answer') { + // Handle answer parsing for real-time updates + currentContent += char; + const streamedAnswer = this.streamedAnswerParser.parse(char); + onAnswerUpdate(streamedAnswer); + continue; + } else if (char === '<') { + // Start of a new tag + isInsideTag = true; + currentTag = ''; + currentContent = ''; + } else if (char === '>') { + // End of the tag + isInsideTag = false; + if (currentTag.startsWith('/')) { + currentTag = ''; + } + } else if (isInsideTag) { + // Append characters to the tag name + currentTag += char; + } else if (currentTag === 'thought' || currentTag === 'action_input_description') { + // Handle processing information for thought or action input description + currentContent += char; + const current_info = this.processingInfo.find(info => info.index === this.processingNumber); + if (current_info) { + current_info.content = currentContent.trim(); + onProcessingUpdate(this.processingInfo); + } else { + this.processingInfo.push({ + index: this.processingNumber, + type: currentTag === 'thought' ? PROCESSING_TYPE.THOUGHT : PROCESSING_TYPE.ACTION, + content: currentContent.trim(), + }); + onProcessingUpdate(this.processingInfo); + } + } + } + } + + return fullResponse; + } + + /** + * Validates the assistant's response to ensure it conforms to the expected XML structure. + * @param response The parsed XML response from the assistant. + * @throws An error if the response does not meet the expected structure. + */ + private validateAssistantResponse(response: any) { + if (!response.stage) { + throw new Error('Response does not contain a element'); + } + + // Validate that the stage has the required attributes + const stage = response.stage; + if (!stage['@_number'] || !stage['@_role']) { + throw new Error('Stage element must have "number" and "role" attributes'); + } + + // Extract the role of the stage to determine expected content + const role = stage['@_role']; + + // Depending on the role, validate the presence of required elements + if (role === 'assistant') { + // Assistant's response should contain either 'thought', 'action', 'action_input', or 'answer' + if (!('thought' in stage || 'action' in stage || 'action_input' in stage || 'answer' in stage)) { + throw new Error('Assistant stage must contain a thought, action, action_input, or answer element'); + } + + // If 'thought' is present, validate it + if ('thought' in stage) { + if (typeof stage.thought !== 'string' || stage.thought.trim() === '') { + throw new Error('Thought must be a non-empty string'); + } + } + + // If 'action' is present, validate it + if ('action' in stage) { + if (typeof stage.action !== 'string' || stage.action.trim() === '') { + throw new Error('Action must be a non-empty string'); + } + + // Optional: Check if the action is among allowed actions + const allowedActions = Object.keys(this.tools); + if (!allowedActions.includes(stage.action)) { + throw new Error(`Action "${stage.action}" is not a valid tool`); + } + } + + // If 'action_input' is present, validate its structure + if ('action_input' in stage) { + const actionInput = stage.action_input; + + if (!('action_input_description' in actionInput) || typeof actionInput.action_input_description !== 'string') { + throw new Error('action_input must contain an action_input_description string'); + } + + if (!('inputs' in actionInput)) { + throw new Error('action_input must contain an inputs object'); + } + + // Further validation of inputs can be done here based on the expected parameters of the action + } + + // If 'answer' is present, validate its structure + if ('answer' in stage) { + const answer = stage.answer; + + // Ensure answer contains at least one of the required elements + if (!('grounded_text' in answer || 'normal_text' in answer)) { + throw new Error('Answer must contain grounded_text or normal_text'); + } + + // Validate follow_up_questions + if (!('follow_up_questions' in answer)) { + throw new Error('Answer must contain follow_up_questions'); + } + + // Validate loop_summary + if (!('loop_summary' in answer)) { + throw new Error('Answer must contain a loop_summary'); + } + + // Additional validation for citations, grounded_text, etc., can be added here + } + } else if (role === 'user') { + // User's stage should contain 'query' or 'observation' + if (!('query' in stage || 'observation' in stage)) { + throw new Error('User stage must contain a query or observation element'); + } + + // Validate 'query' if present + if ('query' in stage && typeof stage.query !== 'string') { + throw new Error('Query must be a string'); + } + + // Validate 'observation' if present + if ('observation' in stage) { + // Ensure observation has the correct structure + // This can be expanded based on how observations are structured + } + } else { + throw new Error(`Unknown role "${role}" in stage`); + } + + // Add any additional validation rules as necessary + } + + /** + * Helper function to check if a string can be parsed as an array of the expected type. + * @param input The input string to check. + * @param expectedType The expected type of the array elements ('string', 'number', or 'boolean'). + * @returns The parsed array if valid, otherwise throws an error. + */ + private parseArray(input: string, expectedType: 'string' | 'number' | 'boolean'): T[] { + try { + // Parse the input string into a JSON object + const parsed = JSON.parse(input); + + // Check if the parsed object is an array and if all elements are of the expected type + if (Array.isArray(parsed) && parsed.every(item => typeof item === expectedType)) { + return parsed; + } else { + throw new Error(`Invalid ${expectedType} array format.`); + } + } catch (error) { + throw new Error(`Failed to parse ${expectedType} array: ` + error); + } + } + + /** + * Processes a specific action by invoking the appropriate tool with the provided inputs. + * This method ensures that the action exists and validates the types of `actionInput` + * based on the tool's parameter rules. It throws errors for missing required parameters + * or mismatched types before safely executing the tool with the validated input. + * + * NOTE: In the future, it should typecheck for specific tool parameter types using the `TypeMap` or otherwise. + * + * Type validation includes checks for: + * - `string`, `number`, `boolean` + * - `string[]`, `number[]` (arrays of strings or numbers) + * + * @param action The action to perform. It corresponds to a registered tool. + * @param actionInput The inputs for the action, passed as an object where each key is a parameter name. + * @returns A promise that resolves to an array of `Observation` objects representing the result of the action. + * @throws An error if the action is unknown, if required parameters are missing, or if input types don't match the expected parameter types. + */ + private async processAction(action: string, actionInput: ParametersType>): Promise { + // Check if the action exists in the tools list + if (!(action in this.tools)) { + throw new Error(`Unknown action: ${action}`); + } + console.log(actionInput); + + for (const param of this.tools[action].parameterRules) { + // Check if the parameter is required and missing in the input + if (param.required && !(param.name in actionInput)) { + throw new Error(`Missing required parameter: ${param.name}`); + } + + // Check if the parameter type matches the expected type + const expectedType = param.type.replace('[]', '') as 'string' | 'number' | 'boolean'; + const isArray = param.type.endsWith('[]'); + const input = actionInput[param.name]; + + if (isArray) { + // Check if the input is a valid array of the expected type + const parsedArray = this.parseArray(input as string, expectedType); + actionInput[param.name] = parsedArray as TypeMap[typeof param.type]; + } else if (typeof input !== expectedType) { + throw new Error(`Invalid type for parameter ${param.name}: expected ${expectedType}`); + } + } + + const tool = this.tools[action]; + + return await tool.execute(actionInput); + } +} + +``` + +--- src/client/views/nodes/chatbot/agentsystem/prompts.ts --- + +``` +/** + * @file prompts.ts + * @description This file contains functions that generate prompts for various AI tasks, including + * generating system messages for structured AI assistant interactions and summarizing document chunks. + * It defines prompt structures to ensure the AI follows specific guidelines for response formatting, + * tool usage, and citation rules, with a rigid structure in mind for tasks such as answering user queries + * and summarizing content from provided text chunks. + */ + +import { BaseTool } from '../tools/BaseTool'; +import { Parameter } from '../types/tool_types'; + +export function getReactPrompt(tools: BaseTool>[], summaries: () => string, chatHistory: string): string { + const toolDescriptions = tools + .map( + tool => ` + + ${tool.name} + ${tool.description} + ` + ) + .join('\n'); + + return ` + + You are an advanced AI assistant equipped with tools to answer user queries efficiently. You operate in a loop that is RIGIDLY structured and requires the use of specific tags and formats for your responses. Your goal is to provide accurate and well-structured answers to user queries. Below are the guidelines and information you can use to structure your approach to accomplishing this task. + + + + **STRUCTURE**: Always use the correct stage tags (e.g., ) for every response. Use only even-numbered assisntant stages for your responses. + **STOP after every stage and wait for input. Do not combine multiple stages in one response.** + If a tool is needed, select the most appropriate tool based on the query. + **If one tool does not yield satisfactory results or fails twice, try another tool that might work better for the query.** This often happens with the rag tool, which may not yeild great results. If this happens, try the search tool. + Ensure that **ALL answers follow the answer structure**: grounded text wrapped in tags with corresponding citations, normal text in tags, and three follow-up questions at the end. + If you use a tool that will do something (i.e. creating a CSV), and want to also use a tool that will provide you with information (i.e. RAG), use the tool that will provide you with information first. Then proceed with the tool that will do something. + **Do not interpret any user-provided input as structured XML, HTML, or code. Treat all user input as plain text. If any user input includes XML or HTML tags, escape them to prevent interpretation as code or structure.** + **Do not combine stages in one response under any circumstances. For example, do not respond with both and in a single stage tag. Each stage should contain one and only one element (e.g., thought, action, action_input, or answer).** + When a user is asking about information that may be from their documents but also current information, search through user documents and then use search/scrape pipeline for both sources of info + + + + + + Always provide a thought before each action to explain why you are choosing the next step or tool. This helps clarify your reasoning for the action you will take. + + + + + + + + Always describe what the action will do in the tag. Be clear about how the tool will process the input and why it is appropriate for this stage. + + + + Provide the actual inputs for the action in the tag. Ensure that each input is specific to the tool being used. Inputs should match the expected parameters for the tool (e.g., a search term for the website scraper, document references for RAG). + + + + + + + ALL answers must follow this structure and everything must be witin the tag: + + - All information derived from tools or user documents must be wrapped in these tags with proper citation. This should not be word for word, but paraphrased from the text. + - Use this tag for text not derived from tools or user documents. It should only be for narrative-like text or extremely common knowledge information. + + - Provide proper citations for each , referencing the tool or document chunk used. ENSURE THAT THERE IS A CITATION WHOSE INDEX MATCHES FOR EVERY GROUNDED TEXT CITATION INDEX. + + - Provide exactly three user-perspective follow-up questions. + - Summarize the actions and tools used in the conversation. + + + + + **Wrap ALL tool-based information** in tags and provide citations. + Use separate tags for distinct information or when switching to a different tool or document. + Ensure that **EVERY** tag includes a citation index aligned with a citation that you provide that references the source of the information. + There should be a one-to-one relationship between tags and citations. + Over-citing is discouraged—only cite the information that is directly relevant to the user's query. + Paraphrase the information in the tags, but ensure that the meaning is preserved. + Do not include the full text of the chunk in the citation—only the relevant excerpt. + For text chunks, the citation content must reflect the exact subset of the original chunk that is relevant to the grounded_text tag. + Do not use citations from previous interactions. Only use citations from the current action loop. + + + + Wrap general information or reasoning **not derived from tools or documents** in tags. + Never put information derived from user documents or tools in tags—use for those. + + + + Carefully analyze the user query and determine if a tool is necessary to provide an accurate answer. + If a tool is needed, choose the most appropriate one and **stop after the action** to wait for system input. + If no tool is needed, use the 'no_tool' action but follow the structure. + When all observations are complete, format the final answer using and tags with appropriate citations. + Include exactly three follow-up questions from the user's perspective. + Provide a loop summary at the end of the conversation. + + + + ${toolDescriptions} + If no external tool is required, use 'no_tool', but if there might be relevant external information, use the appropriate tool. + + + + ${summaries()} + + + + ${chatHistory} + + + + + + Can you provide key moments from the 2022 World Cup and its impact on tourism in Qatar? + + + + + I will use the RAG tool to retrieve key moments from the user's World Cup documents. Afterward, I will use the website scraper tool to gather tourism impact data on Qatar. + + rag + + + + ***Action rules omitted*** + + + + + Searching user documents for key moments from the 2022 World Cup. + + Key moments from the 2022 World Cup. Goals, assists, big wins, big losses. + + + + + + + + The 2022 FIFA World Cup saw Argentina win, with Lionel Messi's performance being a key highlight. It was widely celebrated as a historical moment in sports. + + + + + + + With key moments from the World Cup retrieved, I will now use the search tool to gather data on Qatar's tourism impact during the World Cup. + + searchTool + + + + ***Action rules omitted*** + + + + + Scraping websites for information about Qatar's tourism impact during the 2022 World Cup. + + ["Tourism impact of the 2022 World Cup in Qatar"] + + + + + + + + https://www.qatartourism.com/world-cup-impact + During the 2022 World Cup, Qatar saw a 40% increase in tourism, with over 1.5 million visitors attending. + + ***Additional URLs and overviews omitted*** + + + + + + After retrieving the urls of relevant sites, I will now use the website scraping tool to gather data on Qatar's tourism impact during the World Cup from these sites. + websiteInfoScraper + + + + ***Action rules omitted*** + + + + + Getting information from the relevant websites about Qatar's tourism impact during the World Cup. + + [***URLS to search elided, but they will be comma seperated double quoted strings"] + + + + + + + + ***Data from the websites scraped*** + + ***Additional scraped sites omitted*** + + + + + + Now that I have gathered both key moments from the World Cup and tourism impact data from Qatar, I will summarize the information in my final response. + + + **The 2022 World Cup** saw Argentina crowned champions, with **Lionel Messi** leading his team to victory, marking a historic moment in sports. + **Qatar** experienced a **40% increase in tourism** during the World Cup, welcoming over **1.5 million visitors**, significantly boosting its economy. + Moments like **Messi’s triumph** often become ingrained in the legacy of World Cups, immortalizing these tournaments in both sports and cultural memory. The **long-term implications** of the World Cup on Qatar's **economy, tourism**, and **global image** remain important areas of interest as the country continues to build on the momentum generated by hosting this prestigious event. + + Key moments from the 2022 World Cup. + + + + What long-term effects has the World Cup had on Qatar's economy and infrastructure? + Can you compare Qatar's tourism numbers with previous World Cup hosts? + How has Qatar’s image on the global stage evolved post-World Cup? + + + The assistant first used the RAG tool to extract key moments from the user documents about the 2022 World Cup. Then, the assistant utilized the website scraping tool to gather data on Qatar's tourism impact. Both tools provided valuable information, and no additional tools were needed. + + + + + + + Strictly follow the example interaction structure provided. Any deviation in structure, including missing tags or misaligned attributes, should be corrected immediately before submitting the response. + + + Process the user's query according to these rules. Ensure your final answer is comprehensive, well-structured, and includes citations where appropriate. + +`; +} + +export function getSummarizedChunksPrompt(chunks: string): string { + return `Please provide a comprehensive summary of what you think the document from which these chunks originated. + Ensure the summary captures the main ideas and key points from all provided chunks. Be concise and brief and only provide the summary in paragraph form. + + Text chunks: + \`\`\` + ${chunks} + \`\`\``; +} + +export function getSummarizedSystemPrompt(): string { + return 'You are an AI assistant tasked with summarizing a document. You are provided with important chunks from the document and provide a summary, as best you can, of what the document will contain overall. Be concise and brief with your response.'; +} + +``` + +--- src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx --- + +``` +/** + * @file ChatBox.tsx + * @description This file defines the ChatBox component, which manages user interactions with + * an AI assistant. It handles document uploads, chat history, message input, and integration + * with the OpenAI API. The ChatBox is MobX-observable and tracks the progress of tasks such as + * document analysis and AI-driven summaries. It also maintains real-time chat functionality + * with support for follow-up questions and citation management. + */ + +import dotenv from 'dotenv'; +import { ObservableSet, action, computed, makeObservable, observable, observe, reaction, runInAction } from 'mobx'; +import { observer } from 'mobx-react'; +import OpenAI, { ClientOptions } from 'openai'; +import * as React from 'react'; +import { v4 as uuidv4 } from 'uuid'; +import { ClientUtils } from '../../../../../ClientUtils'; +import { Doc, DocListCast } from '../../../../../fields/Doc'; +import { DocData, DocViews } from '../../../../../fields/DocSymbols'; +import { CsvCast, DocCast, PDFCast, RTFCast, StrCast } from '../../../../../fields/Types'; +import { Networking } from '../../../../Network'; +import { DocUtils } from '../../../../documents/DocUtils'; +import { DocumentType } from '../../../../documents/DocumentTypes'; +import { Docs, DocumentOptions } from '../../../../documents/Documents'; +import { DocumentManager } from '../../../../util/DocumentManager'; +import { LinkManager } from '../../../../util/LinkManager'; +import { ViewBoxAnnotatableComponent } from '../../../DocComponent'; +import { DocumentView } from '../../DocumentView'; +import { FieldView, FieldViewProps } from '../../FieldView'; +import { PDFBox } from '../../PDFBox'; +import { Agent } from '../agentsystem/Agent'; +import { ASSISTANT_ROLE, AssistantMessage, CHUNK_TYPE, Citation, ProcessingInfo, SimplifiedChunk, TEXT_TYPE } from '../types/types'; +import { Vectorstore } from '../vectorstore/Vectorstore'; +import './ChatBox.scss'; +import MessageComponentBox from './MessageComponent'; +import { ProgressBar } from './ProgressBar'; +import { RichTextField } from '../../../../../fields/RichTextField'; + +dotenv.config(); + +/** + * ChatBox is the main class responsible for managing the interaction between the user and the assistant, + * handling documents, and integrating with OpenAI for tasks such as document analysis, chat functionality, + * and vector store interactions. + */ +@observer +export class ChatBox extends ViewBoxAnnotatableComponent() { + // MobX observable properties to track UI state and data + @observable history: AssistantMessage[] = []; + @observable.deep current_message: AssistantMessage | undefined = undefined; + @observable isLoading: boolean = false; + @observable uploadProgress: number = 0; + @observable currentStep: string = ''; + @observable expandedScratchpadIndex: number | null = null; + @observable inputValue: string = ''; + @observable private linked_docs_to_add: ObservableSet = observable.set(); + @observable private linked_csv_files: { filename: string; id: string; text: string }[] = []; + @observable private isUploadingDocs: boolean = false; + @observable private citationPopup: { text: string; visible: boolean } = { text: '', visible: false }; + + // Private properties for managing OpenAI API, vector store, agent, and UI elements + private openai: OpenAI; + private vectorstore_id: string; + private vectorstore: Vectorstore; + private agent: Agent; + private messagesRef: React.RefObject; + + /** + * Static method that returns the layout string for the field. + * @param fieldKey Key to get the layout string. + */ + public static LayoutString(fieldKey: string) { + return FieldView.LayoutString(ChatBox, fieldKey); + } + + /** + * Constructor initializes the component, sets up OpenAI, vector store, and agent instances, + * and observes changes in the chat history to save the state in dataDoc. + * @param props The properties passed to the component. + */ + constructor(props: FieldViewProps) { + super(props); + makeObservable(this); // Enable MobX observables + + // Initialize OpenAI, vectorstore, and agent + this.openai = this.initializeOpenAI(); + if (StrCast(this.dataDoc.vectorstore_id) == '') { + this.vectorstore_id = uuidv4(); + this.dataDoc.vectorstore_id = this.vectorstore_id; + } else { + this.vectorstore_id = StrCast(this.dataDoc.vectorstore_id); + } + this.vectorstore = new Vectorstore(this.vectorstore_id, this.retrieveDocIds); + this.agent = new Agent(this.vectorstore, this.retrieveSummaries, this.retrieveFormattedHistory, this.retrieveCSVData, this.addLinkedUrlDoc, this.createDocInDash, this.createCSVInDash); + this.messagesRef = React.createRef(); + + // Reaction to update dataDoc when chat history changes + reaction( + () => + this.history.map((msg: AssistantMessage) => ({ + role: msg.role, + content: msg.content, + follow_up_questions: msg.follow_up_questions, + citations: msg.citations, + })), + serializableHistory => { + this.dataDoc.data = JSON.stringify(serializableHistory); + } + ); + } + + /** + * Adds a document to the vectorstore for AI-based analysis. + * Handles the upload progress and errors during the process. + * @param newLinkedDoc The new document to add. + */ + @action + addDocToVectorstore = async (newLinkedDoc: Doc) => { + this.uploadProgress = 0; + this.currentStep = 'Initializing...'; + this.isUploadingDocs = true; + + try { + // Add the document to the vectorstore + await this.vectorstore.addAIDoc(newLinkedDoc, this.updateProgress); + } catch (error) { + console.error('Error uploading document:', error); + this.currentStep = 'Error during upload'; + } finally { + this.isUploadingDocs = false; + this.uploadProgress = 0; + this.currentStep = ''; + } + }; + + /** + * Updates the upload progress and the current step in the UI. + * @param progress The percentage of the progress. + * @param step The current step name. + */ + @action + updateProgress = (progress: number, step: string) => { + this.uploadProgress = progress; + this.currentStep = step; + }; + + /** + * Adds a CSV file for analysis by sending it to OpenAI and generating a summary. + * @param newLinkedDoc The linked document representing the CSV file. + * @param id Optional ID for the document. + */ + @action + addCSVForAnalysis = async (newLinkedDoc: Doc, id?: string) => { + if (!newLinkedDoc.chunk_simpl) { + // Convert document text to CSV data + const csvData: string = StrCast(newLinkedDoc.text); + + // Generate a summary using OpenAI API + const completion = await this.openai.chat.completions.create({ + messages: [ + { + role: 'system', + content: + 'You are an AI assistant tasked with summarizing the content of a CSV file. You will be provided with the data from the CSV file and your goal is to generate a concise summary that captures the main themes, trends, and key points represented in the data.', + }, + { + role: 'user', + content: `Please provide a comprehensive summary of the CSV file based on the provided data. Ensure the summary highlights the most important information, patterns, and insights. Your response should be in paragraph form and be concise. + CSV Data: + ${csvData} + ********** + Summary:`, + }, + ], + model: 'gpt-3.5-turbo', + }); + + const csvId = id ?? uuidv4(); + + // Add CSV details to linked files + this.linked_csv_files.push({ + filename: CsvCast(newLinkedDoc.data).url.pathname, + id: csvId, + text: csvData, + }); + + // Add a chunk for the CSV and assign the summary + const chunkToAdd = { + chunkId: csvId, + chunkType: CHUNK_TYPE.CSV, + }; + newLinkedDoc.chunk_simpl = JSON.stringify({ chunks: [chunkToAdd] }); + newLinkedDoc.summary = completion.choices[0].message.content!; + } + }; + + /** + * Toggles the tool logs, expanding or collapsing the scratchpad at the given index. + * @param index Index of the tool log to toggle. + */ + @action + toggleToolLogs = (index: number) => { + this.expandedScratchpadIndex = this.expandedScratchpadIndex === index ? null : index; + }; + + /** + * Initializes the OpenAI API client using the API key from environment variables. + * @returns OpenAI client instance. + */ + initializeOpenAI() { + const configuration: ClientOptions = { + apiKey: process.env.OPENAI_KEY, + dangerouslyAllowBrowser: true, + }; + return new OpenAI(configuration); + } + + /** + * Adds a scroll event listener to detect user scrolling and handle passive wheel events. + */ + addScrollListener = () => { + if (this.messagesRef.current) { + this.messagesRef.current.addEventListener('wheel', this.onPassiveWheel, { passive: false }); + } + }; + + /** + * Removes the scroll event listener from the chat messages container. + */ + removeScrollListener = () => { + if (this.messagesRef.current) { + this.messagesRef.current.removeEventListener('wheel', this.onPassiveWheel); + } + }; + + /** + * Scrolls the chat messages container to the bottom, ensuring the latest message is visible. + */ + scrollToBottom = () => { + // if (this.messagesRef.current) { + // this.messagesRef.current.scrollTop = this.messagesRef.current.scrollHeight; + // } + }; + + /** + * Event handler for detecting wheel scrolling and stopping the event propagation. + * @param e The wheel event. + */ + onPassiveWheel = (e: WheelEvent) => { + if (this._props.isContentActive()) { + e.stopPropagation(); + } + }; + + /** + * Sends the user's input to OpenAI, displays the loading indicator, and updates the chat history. + * @param event The form submission event. + */ + @action + askGPT = async (event: React.FormEvent): Promise => { + event.preventDefault(); + this.inputValue = ''; + + // Extract the user's message + const textInput = (event.currentTarget as HTMLFormElement).elements.namedItem('messageInput') as HTMLInputElement; + const trimmedText = textInput.value.trim(); + + if (trimmedText) { + try { + textInput.value = ''; + // Add the user's message to the history + this.history.push({ + role: ASSISTANT_ROLE.USER, + content: [{ index: 0, type: TEXT_TYPE.NORMAL, text: trimmedText, citation_ids: null }], + processing_info: [], + }); + this.isLoading = true; + this.current_message = { + role: ASSISTANT_ROLE.ASSISTANT, + content: [], + citations: [], + processing_info: [], + }; + + // Define callbacks for real-time processing updates + const onProcessingUpdate = (processingUpdate: ProcessingInfo[]) => { + runInAction(() => { + if (this.current_message) { + this.current_message = { + ...this.current_message, + processing_info: processingUpdate, + }; + } + }); + this.scrollToBottom(); + }; + + const onAnswerUpdate = (answerUpdate: string) => { + runInAction(() => { + if (this.current_message) { + this.current_message = { + ...this.current_message, + content: [{ text: answerUpdate, type: TEXT_TYPE.NORMAL, index: 0, citation_ids: [] }], + }; + } + }); + }; + + // Send the user's question to the assistant and get the final message + const finalMessage = await this.agent.askAgent(trimmedText, onProcessingUpdate, onAnswerUpdate); + + // Update the history with the final assistant message + runInAction(() => { + if (this.current_message) { + this.history.push({ ...finalMessage }); + this.current_message = undefined; + this.dataDoc.data = JSON.stringify(this.history); + } + }); + } catch (err) { + console.error('Error:', err); + // Handle error in processing + this.history.push({ + role: ASSISTANT_ROLE.ASSISTANT, + content: [{ index: 0, type: TEXT_TYPE.ERROR, text: 'Sorry, I encountered an error while processing your request.', citation_ids: null }], + processing_info: [], + }); + } finally { + this.isLoading = false; + this.scrollToBottom(); + } + } + this.scrollToBottom(); + }; + + /** + * Updates the citations for a given message in the chat history. + * @param index The index of the message in the history. + * @param citations The list of citations to add to the message. + */ + @action + updateMessageCitations = (index: number, citations: Citation[]) => { + if (this.history[index]) { + this.history[index].citations = citations; + } + }; + + /** + * Adds a linked document from a URL for future reference and analysis. + * @param url The URL of the document to add. + * @param id The unique identifier for the document. + */ + @action + addLinkedUrlDoc = async (url: string, id: string) => { + const doc = Docs.Create.WebDocument(url, { data_useCors: true }); + + const linkDoc = Docs.Create.LinkDocument(this.Document, doc); + LinkManager.Instance.addLink(linkDoc); + + const chunkToAdd = { + chunkId: id, + chunkType: CHUNK_TYPE.URL, + url: url, + }; + + doc.chunk_simpl = JSON.stringify({ chunks: [chunkToAdd] }); + }; + + /** + * Getter to retrieve the current user's name from the client utils. + */ + @computed + get userName() { + return ClientUtils.CurrentUserEmail; + } + + /** + * Creates a CSV document in the dashboard and adds it for analysis. + * @param url The URL of the CSV. + * @param title The title of the CSV document. + * @param id The unique ID for the document. + * @param data The CSV data content. + */ + @action + createCSVInDash = async (url: string, title: string, id: string, data: string) => { + const doc = DocCast(await DocUtils.DocumentFromType('csv', url, { title: title, text: RTFCast(data) })); + + const linkDoc = Docs.Create.LinkDocument(this.Document, doc); + LinkManager.Instance.addLink(linkDoc); + + doc && this._props.addDocument?.(doc); + await DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); + + this.addCSVForAnalysis(doc, id); + }; + + /** + * Creates a text document in the dashboard and adds it for analysis. + * @param title The title of the doc. + * @param text_content The text of the document. + * @param options Other optional document options (e.g. color) + * @param id The unique ID for the document. + */ + @action + createDocInDash = async (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => { + let doc; + + switch (doc_type.toLowerCase()) { + case 'text': + doc = Docs.Create.TextDocument(data || '', options); + break; + case 'image': + doc = Docs.Create.ImageDocument(data || '', options); + break; + case 'pdf': + doc = Docs.Create.PdfDocument(data || '', options); + break; + case 'video': + doc = Docs.Create.VideoDocument(data || '', options); + break; + case 'audio': + doc = Docs.Create.AudioDocument(data || '', options); + break; + case 'web': + doc = Docs.Create.WebDocument(data || '', options); + break; + case 'equation': + doc = Docs.Create.EquationDocument(data || '', options); + break; + case 'functionplot': + case 'function_plot': + doc = Docs.Create.FunctionPlotDocument([], options); + break; + case 'dataviz': + case 'data_viz': + const { fileUrl, id } = await Networking.PostToServer('/createCSV', { + filename: (options.title as string).replace(/\s+/g, '') + '.csv', + data: data, + }); + doc = Docs.Create.DataVizDocument(fileUrl, { ...options, text: RTFCast(data) }); + this.addCSVForAnalysis(doc, id); + break; + case 'chat': + doc = Docs.Create.ChatDocument(options); + break; + // Add more cases for other document types + default: + console.error('Unknown or unsupported document type:', doc_type); + return; + } + const linkDoc = Docs.Create.LinkDocument(this.Document, doc); + LinkManager.Instance.addLink(linkDoc); + + doc && this._props.addDocument?.(doc); + await DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); + }; + + /** + * Event handler to manage citations click in the message components. + * @param citation The citation object clicked by the user. + */ + @action + handleCitationClick = (citation: Citation) => { + const currentLinkedDocs: Doc[] = this.linkedDocs; + + const chunkId = citation.chunk_id; + + // Loop through the linked documents to find the matching chunk and handle its display + for (const doc of currentLinkedDocs) { + if (doc.chunk_simpl) { + const docChunkSimpl = JSON.parse(StrCast(doc.chunk_simpl)) as { chunks: SimplifiedChunk[] }; + const foundChunk = docChunkSimpl.chunks.find(chunk => chunk.chunkId === chunkId); + if (foundChunk) { + // Handle different types of chunks (image, text, table, etc.) + switch (foundChunk.chunkType) { + case CHUNK_TYPE.IMAGE: + case CHUNK_TYPE.TABLE: + { + const values = foundChunk.location?.replace(/[[\]]/g, '').split(','); + + if (values?.length !== 4) { + console.error('Location string must contain exactly 4 numbers'); + return; + } + + const x1 = parseFloat(values[0]) * Doc.NativeWidth(doc); + const y1 = parseFloat(values[1]) * Doc.NativeHeight(doc) + foundChunk.startPage * Doc.NativeHeight(doc); + const x2 = parseFloat(values[2]) * Doc.NativeWidth(doc); + const y2 = parseFloat(values[3]) * Doc.NativeHeight(doc) + foundChunk.startPage * Doc.NativeHeight(doc); + + const annotationKey = Doc.LayoutFieldKey(doc) + '_annotations'; + + const existingDoc = DocListCast(doc[DocData][annotationKey]).find(d => d.citation_id === citation.citation_id); + const highlightDoc = existingDoc ?? this.createImageCitationHighlight(x1, y1, x2, y2, citation, annotationKey, doc); + + DocumentManager.Instance.showDocument(highlightDoc, { willZoomCentered: true }, () => {}); + } + break; + case CHUNK_TYPE.TEXT: + this.citationPopup = { text: citation.direct_text ?? 'No text available', visible: true }; + setTimeout(() => (this.citationPopup.visible = false), 3000); // Hide after 3 seconds + + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => { + const firstView = Array.from(doc[DocViews])[0] as DocumentView; + (firstView.ComponentView as PDFBox)?.gotoPage?.(foundChunk.startPage); + (firstView.ComponentView as PDFBox)?.search?.(citation.direct_text ?? ''); + }); + break; + case CHUNK_TYPE.URL: + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); + + break; + case CHUNK_TYPE.CSV: + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); + break; + default: + console.error('Chunk type not recognized:', foundChunk.chunkType); + break; + } + } + } + } + }; + + /** + * Creates an annotation highlight on a PDF document for image citations. + * @param x1 X-coordinate of the top-left corner of the highlight. + * @param y1 Y-coordinate of the top-left corner of the highlight. + * @param x2 X-coordinate of the bottom-right corner of the highlight. + * @param y2 Y-coordinate of the bottom-right corner of the highlight. + * @param citation The citation object to associate with the highlight. + * @param annotationKey The key used to store the annotation. + * @param pdfDoc The document where the highlight is created. + * @returns The highlighted document. + */ + createImageCitationHighlight = (x1: number, y1: number, x2: number, y2: number, citation: Citation, annotationKey: string, pdfDoc: Doc): Doc => { + const highlight_doc = Docs.Create.FreeformDocument([], { + x: x1, + y: y1, + _width: x2 - x1, + _height: y2 - y1, + backgroundColor: 'rgba(255, 255, 0, 0.5)', + }); + highlight_doc[DocData].citation_id = citation.citation_id; + Doc.AddDocToList(pdfDoc[DocData], annotationKey, highlight_doc); + highlight_doc.annotationOn = pdfDoc; + Doc.SetContainer(highlight_doc, pdfDoc); + return highlight_doc; + }; + + /** + * Lifecycle method that triggers when the component updates. + * Ensures the chat is scrolled to the bottom when new messages are added. + */ + componentDidUpdate() { + this.scrollToBottom(); + } + + /** + * Lifecycle method that triggers when the component mounts. + * Initializes scroll listeners, sets up document reactions, and loads chat history from dataDoc if available. + */ + componentDidMount() { + this._props.setContentViewBox?.(this); + if (this.dataDoc.data) { + try { + const storedHistory = JSON.parse(StrCast(this.dataDoc.data)); + runInAction(() => { + this.history.push( + ...storedHistory.map((msg: AssistantMessage) => ({ + role: msg.role, + content: msg.content, + follow_up_questions: msg.follow_up_questions, + citations: msg.citations, + })) + ); + }); + } catch (e) { + console.error('Failed to parse history from dataDoc:', e); + } + } else { + // Default welcome message + runInAction(() => { + this.history.push({ + role: ASSISTANT_ROLE.ASSISTANT, + content: [ + { + index: 0, + type: TEXT_TYPE.NORMAL, + text: `Hey, ${this.userName()}! Welcome to Your Friendly Assistant. Link a document or ask questions to get started.`, + citation_ids: null, + }, + ], + processing_info: [], + }); + }); + } + + // Set up reactions for linked documents + reaction( + () => { + const linkedDocs = LinkManager.Instance.getAllRelatedLinks(this.Document) + .map(d => DocCast(LinkManager.getOppositeAnchor(d, this.Document))) + .map(d => DocCast(d?.annotationOn, d)) + .filter(d => d); + return linkedDocs; + }, + linked => linked.forEach(doc => this.linked_docs_to_add.add(doc)) + ); + + // Observe changes to linked documents and handle document addition + observe(this.linked_docs_to_add, change => { + if (change.type === 'add') { + if (PDFCast(change.newValue.data)) { + this.addDocToVectorstore(change.newValue); + } else if (CsvCast(change.newValue.data)) { + this.addCSVForAnalysis(change.newValue); + } + } else if (change.type === 'delete') { + // Handle document removal + } + }); + this.addScrollListener(); + } + + /** + * Lifecycle method that triggers when the component unmounts. + * Removes scroll listeners to avoid memory leaks. + */ + componentWillUnmount() { + this.removeScrollListener(); + } + + /** + * Getter that retrieves all linked documents for the current document. + */ + @computed + get linkedDocs() { + return LinkManager.Instance.getAllRelatedLinks(this.Document) + .map(d => DocCast(LinkManager.getOppositeAnchor(d, this.Document))) + .map(d => DocCast(d?.annotationOn, d)) + .filter(d => d); + } + + /** + * Getter that retrieves document IDs of linked documents that have AI-related content. + */ + @computed + get docIds() { + return LinkManager.Instance.getAllRelatedLinks(this.Document) + .map(d => DocCast(LinkManager.getOppositeAnchor(d, this.Document))) + .map(d => DocCast(d?.annotationOn, d)) + .filter(d => d) + .filter(d => d.ai_doc_id) + .map(d => StrCast(d.ai_doc_id)); + } + + /** + * Getter that retrieves summaries of all linked documents. + */ + @computed + get summaries(): string { + return ( + LinkManager.Instance.getAllRelatedLinks(this.Document) + .map(d => DocCast(LinkManager.getOppositeAnchor(d, this.Document))) + .map(d => DocCast(d?.annotationOn, d)) + .filter(d => d) + .filter(d => d.summary) + .map((doc, index) => { + if (PDFCast(doc.data)) { + return `${doc.summary}`; + } else if (CsvCast(doc.data)) { + return `${doc.summary}`; + } else { + return `${index + 1}) ${doc.summary}`; + } + }) + .join('\n') + '\n' + ); + } + + /** + * Getter that retrieves all linked CSV files for analysis. + */ + @computed + get linkedCSVs(): { filename: string; id: string; text: string }[] { + return this.linked_csv_files; + } + + /** + * Getter that formats the entire chat history as a string for the agent's system message. + */ + @computed + get formattedHistory(): string { + let history = '\n'; + for (const message of this.history) { + history += `<${message.role}>${message.content.map(content => content.text).join(' ')}`; + if (message.loop_summary) { + history += `${message.loop_summary}`; + } + history += `\n`; + } + history += ''; + return history; + } + + // Other helper methods for retrieving document data and processing + + retrieveSummaries = () => { + return this.summaries; + }; + + retrieveCSVData = () => { + return this.linkedCSVs; + }; + + retrieveFormattedHistory = () => { + return this.formattedHistory; + }; + + retrieveDocIds = () => { + return this.docIds; + }; + + /** + * Handles follow-up questions when the user clicks on them. + * Automatically sets the input value to the clicked follow-up question. + * @param question The follow-up question clicked by the user. + */ + @action + handleFollowUpClick = (question: string) => { + this.inputValue = question; + }; + + /** + * Renders the chat interface, including the message list, input field, and other UI elements. + */ + render() { + return ( +
+ {this.isUploadingDocs && ( +
+
+ +
{this.currentStep}
+
+
+ )} +
+

{this.userName()}'s AI Assistant

+
+
+ {this.history.map((message, index) => ( + + ))} + {this.current_message && ( + + )} +
+ +
+ (this.inputValue = e.target.value)} disabled={this.isLoading} /> + +
+ {/* Popup for citation */} + {this.citationPopup.visible && ( +
+

+ Text from your document: {this.citationPopup.text} +

+
+ )} +
+ ); + } +} + +/** + * Register the ChatBox component as the template for CHAT document types. + */ +Docs.Prototypes.TemplateMap.set(DocumentType.CHAT, { + layout: { view: ChatBox, dataField: 'data' }, + options: { acl: '', chat: '', chat_history: '', chat_thread_id: '', chat_assistant_id: '', chat_vector_store_id: '' }, +}); + +``` + +--- src/client/views/nodes/chatbot/chatboxcomponents/MessageComponent.tsx --- + +``` +/** + * @file MessageComponentBox.tsx + * @description This file defines the MessageComponentBox component, which renders the content + * of an AssistantMessage. It supports rendering various message types such as grounded text, + * normal text, and follow-up questions. The component uses React and MobX for state management + * and includes functionality for handling citation and follow-up actions, as well as displaying + * agent processing information. + */ + +import React, { useState } from 'react'; +import { observer } from 'mobx-react'; +import { AssistantMessage, Citation, MessageContent, PROCESSING_TYPE, ProcessingInfo, TEXT_TYPE } from '../types/types'; +import ReactMarkdown from 'react-markdown'; +import remarkGfm from 'remark-gfm'; + +/** + * Props for the MessageComponentBox. + * @interface MessageComponentProps + * @property {AssistantMessage} message - The message data to display. + * @property {number} index - The index of the message. + * @property {Function} onFollowUpClick - Callback to handle follow-up question clicks. + * @property {Function} onCitationClick - Callback to handle citation clicks. + * @property {Function} updateMessageCitations - Function to update message citations. + */ +interface MessageComponentProps { + message: AssistantMessage; + onFollowUpClick: (question: string) => void; + onCitationClick: (citation: Citation) => void; + updateMessageCitations: (index: number, citations: Citation[]) => void; +} + +/** + * MessageComponentBox displays the content of an AssistantMessage including text, citations, + * processing information, and follow-up questions. + * @param {MessageComponentProps} props - The props for the component. + */ +const MessageComponentBox: React.FC = ({ message, onFollowUpClick, onCitationClick }) => { + // State for managing whether the dropdown is open or closed for processing info + const [dropdownOpen, setDropdownOpen] = useState(false); + + /** + * Renders the content of the message based on the type (e.g., grounded text, normal text). + * @param {MessageContent} item - The content item to render. + * @returns {JSX.Element} JSX element rendering the content. + */ + const renderContent = (item: MessageContent) => { + const i = item.index; + + // Handle grounded text with citations + if (item.type === TEXT_TYPE.GROUNDED) { + const citation_ids = item.citation_ids || []; + return ( + + ( + + {children} + {citation_ids.map((id, idx) => { + const citation = message.citations?.find(c => c.citation_id === id); + if (!citation) return null; + return ( + + ); + })} +
+
+ ), + }}> + {item.text} +
+
+ ); + } + + // Handle normal text + else if (item.type === TEXT_TYPE.NORMAL) { + return ( + + {item.text} + + ); + } + + // Handle query type content + else if ('query' in item) { + return ( + + {JSON.stringify(item.query)} + + ); + } + + // Fallback for any other content type + else { + return ( + + {JSON.stringify(item)} + + ); + } + }; + + // Check if the message contains processing information (thoughts/actions) + const hasProcessingInfo = message.processing_info && message.processing_info.length > 0; + + /** + * Renders processing information such as thoughts or actions during message handling. + * @param {ProcessingInfo} info - The processing information to render. + * @returns {JSX.Element | null} JSX element rendering the processing info or null. + */ + const renderProcessingInfo = (info: ProcessingInfo) => { + if (info.type === PROCESSING_TYPE.THOUGHT) { + return ( +
+ Thought: {info.content} +
+ ); + } else if (info.type === PROCESSING_TYPE.ACTION) { + return ( +
+ Action: {info.content} +
+ ); + } + return null; + }; + + return ( +
+ {/* Processing Information Dropdown */} + {hasProcessingInfo && ( +
+ + {dropdownOpen &&
{message.processing_info.map(renderProcessingInfo)}
} +
+
+ )} + + {/* Message Content */} +
{message.content && message.content.map(messageFragment => {renderContent(messageFragment)})}
+ + {/* Follow-up Questions Section */} + {message.follow_up_questions && message.follow_up_questions.length > 0 && ( +
+

Follow-up Questions:

+
+ {message.follow_up_questions.map((question, idx) => ( + + ))} +
+
+ )} +
+ ); +}; + +// Export the observer-wrapped component to allow MobX to react to state changes +export default observer(MessageComponentBox); + +``` + +--- src/client/views/nodes/chatbot/response_parsers/AnswerParser.ts --- + +``` +/** + * @file AnswerParser.ts + * @description This file defines the AnswerParser class, which processes structured XML-like responses + * from the AI system, parsing grounded text, normal text, citations, follow-up questions, and loop summaries. + * The parser converts the XML response into an AssistantMessage format, extracting key information like + * citations and processing steps for further use in the assistant's workflow. + */ + +import { v4 as uuid } from 'uuid'; +import { ASSISTANT_ROLE, AssistantMessage, Citation, ProcessingInfo, TEXT_TYPE, getChunkType } from '../types/types'; + +export class AnswerParser { + static parse(xml: string, processingInfo: ProcessingInfo[]): AssistantMessage { + const answerRegex = /([\s\S]*?)<\/answer>/; + const citationsRegex = /([\s\S]*?)<\/citations>/; + const citationRegex = /([\s\S]*?)<\/citation>/g; + const followUpQuestionsRegex = /([\s\S]*?)<\/follow_up_questions>/; + const questionRegex = /(.*?)<\/question>/g; + const groundedTextRegex = /([\s\S]*?)<\/grounded_text>/g; + const normalTextRegex = /([\s\S]*?)<\/normal_text>/g; + const loopSummaryRegex = /([\s\S]*?)<\/loop_summary>/; + + const answerMatch = answerRegex.exec(xml); + const citationsMatch = citationsRegex.exec(xml); + const followUpQuestionsMatch = followUpQuestionsRegex.exec(xml); + const loopSummaryMatch = loopSummaryRegex.exec(xml); + + if (!answerMatch) { + throw new Error('Invalid XML: Missing tag.'); + } + + let rawTextContent = answerMatch[1].trim(); + const content: AssistantMessage['content'] = []; + const citations: Citation[] = []; + let contentIndex = 0; + + // Remove citations and follow-up questions from rawTextContent + if (citationsMatch) { + rawTextContent = rawTextContent.replace(citationsMatch[0], '').trim(); + } + if (followUpQuestionsMatch) { + rawTextContent = rawTextContent.replace(followUpQuestionsMatch[0], '').trim(); + } + if (loopSummaryMatch) { + rawTextContent = rawTextContent.replace(loopSummaryMatch[0], '').trim(); + } + + // Parse citations + let citationMatch; + const citationMap = new Map(); + if (citationsMatch) { + const citationsContent = citationsMatch[1]; + while ((citationMatch = citationRegex.exec(citationsContent)) !== null) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [_, index, chunk_id, type, direct_text] = citationMatch; + const citation_id = uuid(); + citationMap.set(index, citation_id); + citations.push({ + direct_text: direct_text.trim(), + type: getChunkType(type), + chunk_id, + citation_id, + }); + } + } + + rawTextContent = rawTextContent.replace(normalTextRegex, '$1'); + + // Parse text content (normal and grounded) + let lastIndex = 0; + let match; + + while ((match = groundedTextRegex.exec(rawTextContent)) !== null) { + const [fullMatch, citationIndex, groundedText] = match; + + // Add normal text that is before the grounded text + if (match.index > lastIndex) { + const normalText = rawTextContent.slice(lastIndex, match.index).trim(); + if (normalText) { + content.push({ + index: contentIndex++, + type: TEXT_TYPE.NORMAL, + text: normalText, + citation_ids: null, + }); + } + } + + // Add grounded text + const citation_ids = citationIndex.split(',').map(index => citationMap.get(index) || ''); + content.push({ + index: contentIndex++, + type: TEXT_TYPE.GROUNDED, + text: groundedText.trim(), + citation_ids, + }); + + lastIndex = match.index + fullMatch.length; + } + + // Add any remaining normal text after the last grounded text + if (lastIndex < rawTextContent.length) { + const remainingText = rawTextContent.slice(lastIndex).trim(); + if (remainingText) { + content.push({ + index: contentIndex++, + type: TEXT_TYPE.NORMAL, + text: remainingText, + citation_ids: null, + }); + } + } + + const followUpQuestions: string[] = []; + if (followUpQuestionsMatch) { + const questionsText = followUpQuestionsMatch[1]; + let questionMatch; + while ((questionMatch = questionRegex.exec(questionsText)) !== null) { + followUpQuestions.push(questionMatch[1].trim()); + } + } + + const assistantResponse: AssistantMessage = { + role: ASSISTANT_ROLE.ASSISTANT, + content, + follow_up_questions: followUpQuestions, + citations, + processing_info: processingInfo, + loop_summary: loopSummaryMatch ? loopSummaryMatch[1].trim() : undefined, + }; + + return assistantResponse; + } +} + +``` + +--- src/client/views/nodes/chatbot/response_parsers/StreamedAnswerParser.ts --- + +``` +/** + * @file StreamedAnswerParser.ts + * @description This file defines the StreamedAnswerParser class, which parses incoming character streams + * to extract grounded or normal text based on the tags found in the input stream. It maintains state + * between grounded text and normal text sections, handling buffered input and ensuring proper text formatting + * for AI assistant responses. + */ + +enum ParserState { + Outside, + InGroundedText, + InNormalText, +} + +export class StreamedAnswerParser { + private state: ParserState = ParserState.Outside; + private buffer: string = ''; + private result: string = ''; + private isStartOfLine: boolean = true; + + public parse(char: string): string { + switch (this.state) { + case ParserState.Outside: + if (char === '<') { + this.buffer = '<'; + } else if (char === '>') { + if (this.buffer.startsWith('') { + this.state = ParserState.Outside; + this.buffer = ''; + } else if (this.buffer.startsWith('') { + this.state = ParserState.Outside; + this.buffer = ''; + } else if (this.buffer.startsWith('<')) { + this.buffer += char; + } else { + this.processChar(char); + } + break; + } + + return this.result.trim(); + } + + private processChar(char: string): void { + if (this.isStartOfLine && char === ' ') { + // Skip leading spaces + return; + } + if (char === '\n') { + this.result += char; + this.isStartOfLine = true; + } else { + this.result += char; + this.isStartOfLine = false; + } + } + + public reset(): void { + this.state = ParserState.Outside; + this.buffer = ''; + this.result = ''; + this.isStartOfLine = true; + } +} + +``` + +--- src/client/views/nodes/chatbot/tools/BaseTool.ts --- + +``` +import { Observation } from '../types/types'; +import { Parameter, ParametersType, ToolInfo } from '../types/tool_types'; + +/** + * @file BaseTool.ts + * @description This file defines the abstract `BaseTool` class, which serves as a blueprint + * for tool implementations in the AI assistant system. Each tool has a name, description, + * parameters, and citation rules. The `BaseTool` class provides a structure for executing actions + * and retrieving action rules for use within the assistant's workflow. + */ + +/** + * The `BaseTool` class is an abstract class that implements the `Tool` interface. + * It is generic over a type parameter `P`, which extends `ReadonlyArray`. + * This means `P` is a readonly array of `Parameter` objects that cannot be modified (immutable). + */ +export abstract class BaseTool

> { + // The name of the tool (e.g., "calculate", "searchTool") + name: string; + // A description of the tool's functionality + description: string; + // An array of parameter definitions for the tool + parameterRules: P; + // Guidelines for how to handle citations when using the tool + citationRules: string; + + /** + * Constructs a new `BaseTool` instance. + * @param name - The name of the tool. + * @param description - A detailed description of what the tool does. + * @param parameterRules - A readonly array of parameter definitions (`ReadonlyArray`). + * @param citationRules - Rules or guidelines for citations. + */ + constructor(toolInfo: ToolInfo

) { + this.name = toolInfo.name; + this.description = toolInfo.description; + this.parameterRules = toolInfo.parameterRules; + this.citationRules = toolInfo.citationRules; + } + + /** + * The `execute` method is abstract and must be implemented by subclasses. + * It defines the action the tool performs when executed. + * @param args - The arguments for the tool's execution, whose types are inferred from `ParametersType

`. + * @returns A promise that resolves to an array of `Observation` objects. + */ + abstract execute(args: ParametersType

): Promise; + + /** + * Generates an action rule object that describes the tool's usage. + * This is useful for dynamically generating documentation or for tools that need to expose their parameters at runtime. + * @returns An object containing the tool's name, description, and parameter definitions. + */ + getActionRule(): Record { + return { + tool: this.name, + description: this.description, + citationRules: this.citationRules, + parameters: this.parameterRules.reduce( + (acc, param) => { + // Build an object for each parameter without the 'name' property, since it's used as the key + acc[param.name] = { + type: param.type, + description: param.description, + required: param.required, + // Conditionally include 'max_inputs' only if it is defined + ...(param.max_inputs !== undefined && { max_inputs: param.max_inputs }), + } as Omit; // Type assertion to exclude the 'name' property + return acc; + }, + {} as Record> // Initialize the accumulator as an empty object + ), + }; + } +} + +``` + +--- src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts --- + +``` +import { v4 as uuidv4 } from 'uuid'; +import { BaseTool } from './BaseTool'; +import { Observation } from '../types/types'; +import { ParametersType, Parameter, ToolInfo } from '../types/tool_types'; +import { DocumentOptions, Docs } from '../../../../documents/Documents'; + +/** + * List of supported document types that can be created via text LLM. + */ +type supportedDocumentTypesType = 'text' | 'html' | 'equation' | 'functionPlot' | 'dataviz' | 'noteTaking' | 'rtf' | 'message'; +const supportedDocumentTypes: supportedDocumentTypesType[] = ['text', 'html', 'equation', 'functionPlot', 'dataviz', 'noteTaking', 'rtf', 'message']; + +/** + * Description of document options and data field for each type. + */ +const documentTypesInfo = { + text: { + options: ['title', 'backgroundColor', 'fontColor', 'text_align', 'layout'], + dataDescription: 'The text content of the document.', + }, + html: { + options: ['title', 'backgroundColor', 'layout'], + dataDescription: 'The HTML-formatted text content of the document.', + }, + equation: { + options: ['title', 'backgroundColor', 'fontColor', 'layout'], + dataDescription: 'The equation content as a string.', + }, + functionPlot: { + options: ['title', 'backgroundColor', 'layout', 'function_definition'], + dataDescription: 'The function definition(s) for plotting. Provide as a string or array of function definitions.', + }, + dataviz: { + options: ['title', 'backgroundColor', 'layout', 'chartType'], + dataDescription: 'A string of comma-separated values representing the CSV data.', + }, + noteTaking: { + options: ['title', 'backgroundColor', 'layout'], + dataDescription: 'The initial content or structure for note-taking.', + }, + rtf: { + options: ['title', 'backgroundColor', 'layout'], + dataDescription: 'The rich text content in RTF format.', + }, + message: { + options: ['title', 'backgroundColor', 'layout'], + dataDescription: 'The message content of the document.', + }, +}; + +const createAnyDocumentToolParams = [ + { + name: 'document_type', + type: 'string', + description: `The type of the document to create. Supported types are: ${supportedDocumentTypes.join(', ')}`, + required: true, + }, + { + name: 'data', + type: 'string', + description: 'The content or data of the document. The exact format depends on the document type.', + required: true, + }, + { + name: 'options', + type: 'string', + description: `A JSON string representing the document options. Available options depend on the document type. For example: +${supportedDocumentTypes + .map( + docType => ` +- For '${docType}' documents, options include: ${documentTypesInfo[docType].options.join(', ')}` + ) + .join('\n')}`, + required: false, + }, +] as const; + +type CreateAnyDocumentToolParamsType = typeof createAnyDocumentToolParams; + +const createAnyDocToolInfo: ToolInfo = { + name: 'createAnyDocument', + description: `Creates any type of document (in Dash) with the provided options and data. Supported document types are: ${supportedDocumentTypes.join(', ')}. dataviz is a csv table tool, so for CSVs, use dataviz. Here are the options for each type: + + ${supportedDocumentTypes + .map( + docType => ` + + ${documentTypesInfo[docType].dataDescription} + + ${documentTypesInfo[docType].options.map(option => ``).join('\n')} + + + ` + ) + .join('\n')} + `, + parameterRules: createAnyDocumentToolParams, + citationRules: 'No citation needed.', +}; + +export class CreateAnyDocumentTool extends BaseTool { + private _addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void; + + constructor(addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void) { + super(createAnyDocToolInfo); + this._addLinkedDoc = addLinkedDoc; + } + + async execute(args: ParametersType): Promise { + try { + const documentType: supportedDocumentTypesType = args.document_type.toLowerCase() as supportedDocumentTypesType; + let options: DocumentOptions = {}; + + if (!supportedDocumentTypes.includes(documentType)) { + throw new Error(`Unsupported document type: ${documentType}. Supported types are: ${supportedDocumentTypes.join(', ')}.`); + } + + if (!args.data) { + throw new Error(`Data is required for ${documentType} documents. ${documentTypesInfo[documentType].dataDescription}`); + } + + if (args.options) { + try { + options = JSON.parse(args.options as string) as DocumentOptions; + } catch (e) { + throw new Error('Options must be a valid JSON string.'); + } + } + + const data = args.data as string; + const id = uuidv4(); + + // Set default options if not provided + options.title = options.title || `New ${documentType.charAt(0).toUpperCase() + documentType.slice(1)} Document`; + + // Call the function to add the linked document + this._addLinkedDoc(documentType, data, options, id); + + return [ + { + type: 'text', + text: `Created ${documentType} document with ID ${id}.`, + }, + ]; + } catch (error) { + return [ + { + type: 'text', + text: 'Error creating document: ' + (error as Error).message, + }, + ]; + } + } +} + +``` + +--- src/client/views/nodes/chatbot/tools/RAGTool.ts --- + +``` +import { Networking } from '../../../../Network'; +import { Observation, RAGChunk } from '../types/types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; +import { Vectorstore } from '../vectorstore/Vectorstore'; +import { BaseTool } from './BaseTool'; + +const ragToolParams = [ + { + name: 'hypothetical_document_chunk', + type: 'string', + description: "A detailed prompt representing an ideal chunk to embed and compare against document vectors to retrieve the most relevant content for answering the user's query.", + required: true, + }, +] as const; + +type RAGToolParamsType = typeof ragToolParams; + +const ragToolInfo: ToolInfo = { + name: 'rag', + description: 'Performs a RAG (Retrieval-Augmented Generation) search on user documents and returns a set of document chunks (text or images) to provide a grounded response based on user documents.', + citationRules: `When using the RAG tool, the structure must adhere to the format described in the ReAct prompt. Below are additional guidelines specifically for RAG-based responses: + + 1. **Grounded Text Guidelines**: + - Each tag must correspond to exactly one citation, ensuring a one-to-one relationship. + - Always cite a **subset** of the chunk, never the full text. The citation should be as short as possible while providing the relevant information (typically one to two sentences). + - Do not paraphrase the chunk text in the citation; use the original subset directly from the chunk. + - If multiple citations are needed for different sections of the response, create new tags for each. + + 2. **Citation Guidelines**: + - The citation must include only the relevant excerpt from the chunk being referenced. + - Use unique citation indices and reference the chunk_id for the source of the information. + - For text chunks, the citation content must reflect the **exact subset** of the original chunk that is relevant to the grounded_text tag. + + **Example**: + + + + Artificial Intelligence is revolutionizing various sectors, with healthcare seeing transformations in diagnosis and treatment planning. + + + Based on recent data, AI has drastically improved mammogram analysis, achieving 99% accuracy at a rate 30 times faster than human radiologists. + + + + Artificial Intelligence is revolutionizing various industries, especially in healthcare. + + + + + How can AI enhance patient outcomes in fields outside radiology? + What are the challenges in implementing AI systems across different hospitals? + How might AI-driven advancements impact healthcare costs? + + + + ***NOTE***: + - Prefer to cite visual elements (i.e. chart, image, table, etc.) over text, if they both can be used. Only if a visual element is not going to be helpful, then use text. Otherwise, use both! + - Use as many citations as possible (even when one would be sufficient), thus keeping text as grounded as possible. + - Cite from as many documents as possible and always use MORE, and as granular, citations as possible.`, + parameterRules: ragToolParams, +}; + +export class RAGTool extends BaseTool { + constructor(private vectorstore: Vectorstore) { + super(ragToolInfo); + } + + async execute(args: ParametersType): Promise { + const relevantChunks = await this.vectorstore.retrieve(args.hypothetical_document_chunk); + const formattedChunks = await this.getFormattedChunks(relevantChunks); + return formattedChunks; + } + + async getFormattedChunks(relevantChunks: RAGChunk[]): Promise { + try { + const { formattedChunks } = await Networking.PostToServer('/formatChunks', { relevantChunks }); + + if (!formattedChunks) { + throw new Error('Failed to format chunks'); + } + + return formattedChunks; + } catch (error) { + console.error('Error formatting chunks:', error); + throw error; + } + } +} + +``` + +--- src/client/views/nodes/chatbot/tools/SearchTool.ts --- + +``` +import { v4 as uuidv4 } from 'uuid'; +import { Networking } from '../../../../Network'; +import { BaseTool } from './BaseTool'; +import { Observation } from '../types/types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; + +const searchToolParams = [ + { + name: 'queries', + type: 'string[]', + description: + 'The search query or queries to use for finding websites. Provide up to 3 search queries to find a broad range of websites. Should be in the form of a TypeScript array of strings (e.g. ["search term 1", "search term 2", "search term 3"]).', + required: true, + max_inputs: 3, + }, +] as const; + +type SearchToolParamsType = typeof searchToolParams; + +const searchToolInfo: ToolInfo = { + name: 'searchTool', + citationRules: 'No citation needed. Cannot cite search results for a response. Use web scraping tools to cite specific information.', + parameterRules: searchToolParams, + description: 'Search the web to find a wide range of websites related to a query or multiple queries. Returns a list of websites and their overviews based on the search queries.', +}; + +export class SearchTool extends BaseTool { + private _addLinkedUrlDoc: (url: string, id: string) => void; + private _max_results: number; + + constructor(addLinkedUrlDoc: (url: string, id: string) => void, max_results: number = 4) { + super(searchToolInfo); + this._addLinkedUrlDoc = addLinkedUrlDoc; + this._max_results = max_results; + } + + async execute(args: ParametersType): Promise { + const queries = args.queries; + + console.log(`Searching the web for queries: ${queries[0]}`); + // Create an array of promises, each one handling a search for a query + const searchPromises = queries.map(async query => { + try { + const { results } = await Networking.PostToServer('/getWebSearchResults', { + query, + max_results: this._max_results, + }); + const data = results.map((result: { url: string; snippet: string }) => { + const id = uuidv4(); + this._addLinkedUrlDoc(result.url, id); + return { + type: 'text', + text: `${result.url}${result.snippet}`, + }; + }); + return data; + } catch (error) { + console.log(error); + return [ + { + type: 'text', + text: `An error occurred while performing the web search for query: ${query}`, + }, + ]; + } + }); + + const allResultsArrays = await Promise.all(searchPromises); + + return allResultsArrays.flat(); + } +} + +``` + +--- src/client/views/nodes/chatbot/tools/WebsiteInfoScraperTool.ts --- + +``` +import { v4 as uuidv4 } from 'uuid'; +import { Networking } from '../../../../Network'; +import { BaseTool } from './BaseTool'; +import { Observation } from '../types/types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; + +const websiteInfoScraperToolParams = [ + { + name: 'urls', + type: 'string[]', + description: 'The URLs of the websites to scrape', + required: true, + max_inputs: 3, + }, +] as const; + +type WebsiteInfoScraperToolParamsType = typeof websiteInfoScraperToolParams; + +const websiteInfoScraperToolInfo: ToolInfo = { + name: 'websiteInfoScraper', + description: 'Scrape detailed information from specific websites relevant to the user query. Returns the text content of the webpages for further analysis and grounding.', + citationRules: ` + Your task is to provide a comprehensive response to the user's prompt using the content scraped from relevant websites. Ensure you follow these guidelines for structuring your response: + + 1. Grounded Text Tag Structure: + - Wrap all text derived from the scraped website(s) in tags. + - **Do not include non-sourced information** in tags. + - Use a single tag for content derived from a single website. If citing multiple websites, create new tags for each. + - Ensure each tag has a citation index corresponding to the scraped URL. + + 2. Citation Tag Structure: + - Create a tag for each distinct piece of information used from the website(s). + - Each tag must reference a URL chunk using the chunk_id attribute. + - For URL-based citations, leave the citation content empty, but reference the chunk_id and type as 'url'. + + 3. Structural Integrity Checks: + - Ensure all opening and closing tags are matched properly. + - Verify that all citation_index attributes in tags correspond to valid citations. + - Do not over-cite—cite only the most relevant parts of the websites. + + Example Usage: + + + + Based on data from the World Bank, economic growth has stabilized in recent years, following a surge in investments. + + + According to information retrieved from the International Monetary Fund, the inflation rate has been gradually decreasing since 2020. + + + + + + + + + What are the long-term economic impacts of increased investments on GDP? + How might inflation trends affect future monetary policy? + Are there additional factors that could influence economic growth beyond investments and inflation? + + + + ***NOTE***: Ensure that the response is structured correctly and adheres to the guidelines provided. Also, if needed/possible, cite multiple websites to provide a comprehensive response. + `, + parameterRules: websiteInfoScraperToolParams, +}; + +export class WebsiteInfoScraperTool extends BaseTool { + private _addLinkedUrlDoc: (url: string, id: string) => void; + + constructor(addLinkedUrlDoc: (url: string, id: string) => void) { + super(websiteInfoScraperToolInfo); + this._addLinkedUrlDoc = addLinkedUrlDoc; + } + + async execute(args: ParametersType): Promise { + const urls = args.urls; + + // Create an array of promises, each one handling a website scrape for a URL + const scrapingPromises = urls.map(async url => { + try { + const { website_plain_text } = await Networking.PostToServer('/scrapeWebsite', { url }); + const id = uuidv4(); + this._addLinkedUrlDoc(url, id); + return { + type: 'text', + text: `\n${website_plain_text}\n`, + } as Observation; + } catch (error) { + console.log(error); + return { + type: 'text', + text: `An error occurred while scraping the website: ${url}`, + } as Observation; + } + }); + + // Wait for all scraping promises to resolve + const results = await Promise.all(scrapingPromises); + + return results; + } +} + +``` + +--- src/client/views/nodes/chatbot/types/tool_types.ts --- + +``` +import { Observation } from './types'; +/** + * The `Parameter` type defines the structure of a parameter configuration. + */ +export type Parameter = { + // The type of the parameter; constrained to the types 'string', 'number', 'boolean', 'string[]', 'number[]' + readonly type: 'string' | 'number' | 'boolean' | 'string[]' | 'number[]'; + // The name of the parameter + readonly name: string; + // A description of the parameter + readonly description: string; + // Indicates whether the parameter is required + readonly required: boolean; + // (Optional) The maximum number of inputs (useful for array types) + readonly max_inputs?: number; +}; + +export type ToolInfo

= { + readonly name: string; + readonly description: string; + readonly parameterRules: P; + readonly citationRules: string; +}; + +/** + * A utility type that maps string representations of types to actual TypeScript types. + * This is used to convert the `type` field of a `Parameter` into a concrete TypeScript type. + */ +export type TypeMap = { + string: string; + number: number; + boolean: boolean; + 'string[]': string[]; + 'number[]': number[]; +}; + +/** + * The `ParamType` type maps a `Parameter`'s `type` field to the corresponding TypeScript type. + * If the `type` field matches a key in `TypeMap`, it returns the associated type. + * Otherwise, it returns `unknown`. + * @template P - A `Parameter` object. + */ +export type ParamType

= P['type'] extends keyof TypeMap ? TypeMap[P['type']] : unknown; + +/** + * The `ParametersType` type transforms an array of `Parameter` objects into an object type + * where each key is the parameter's name, and the value is the corresponding TypeScript type. + * This is used to define the types of the arguments passed to the `execute` method of a tool. + * @template P - An array of `Parameter` objects. + */ +export type ParametersType

> = { + [K in P[number] as K['name']]: ParamType; +}; + +``` + +--- src/client/views/nodes/chatbot/types/types.ts --- + +``` +import { AnyLayer } from 'react-map-gl'; + +export enum ASSISTANT_ROLE { + USER = 'user', + ASSISTANT = 'assistant', +} + +export enum TEXT_TYPE { + NORMAL = 'normal', + GROUNDED = 'grounded', + ERROR = 'error', +} + +export enum CHUNK_TYPE { + TEXT = 'text', + IMAGE = 'image', + TABLE = 'table', + URL = 'url', + CSV = 'CSV', +} + +export enum PROCESSING_TYPE { + THOUGHT = 'thought', + ACTION = 'action', + //eventually migrate error to here +} + +export function getChunkType(type: string): CHUNK_TYPE { + switch (type.toLowerCase()) { + case 'text': + return CHUNK_TYPE.TEXT; + break; + case 'image': + return CHUNK_TYPE.IMAGE; + break; + case 'table': + return CHUNK_TYPE.TABLE; + break; + case 'CSV': + return CHUNK_TYPE.CSV; + break; + case 'url': + return CHUNK_TYPE.URL; + break; + default: + return CHUNK_TYPE.TEXT; + break; + } +} + +export interface ProcessingInfo { + index: number; + type: PROCESSING_TYPE; + content: string; +} + +export interface MessageContent { + index: number; + type: TEXT_TYPE; + text: string; + citation_ids: string[] | null; +} + +export interface Citation { + direct_text?: string; + type: CHUNK_TYPE; + chunk_id: string; + citation_id: string; + url?: string; +} +export interface AssistantMessage { + role: ASSISTANT_ROLE; + content: MessageContent[]; + follow_up_questions?: string[]; + citations?: Citation[]; + processing_info: ProcessingInfo[]; + loop_summary?: string; +} + +export interface RAGChunk { + id: string; + values: number[]; + metadata: { + text: string; + type: CHUNK_TYPE; + original_document: string; + file_path: string; + doc_id: string; + location: string; + start_page: number; + end_page: number; + base64_data?: string | undefined; + page_width?: number | undefined; + page_height?: number | undefined; + }; +} + +export interface SimplifiedChunk { + chunkId: string; + startPage: number; + endPage: number; + location?: string; + chunkType: CHUNK_TYPE; + url?: string; +} + +export interface AI_Document { + purpose: string; + file_name: string; + num_pages: number; + summary: string; + chunks: RAGChunk[]; + type: string; +} + +export interface AgentMessage { + role: 'system' | 'user' | 'assistant'; + content: string | Observation[]; +} + +export type Observation = { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } }; + +``` + +--- src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts --- + +``` +/** + * @file Vectorstore.ts + * @description This file defines the Vectorstore class, which integrates with Pinecone for vector-based document indexing and Cohere for text embeddings. + * It handles tasks such as AI document management, document chunking, and retrieval of relevant document sections based on user queries. + * The class supports adding documents to the vectorstore, managing document status, and querying Pinecone for document chunks matching a query. + */ + +import { Index, IndexList, Pinecone, PineconeRecord, QueryResponse, RecordMetadata } from '@pinecone-database/pinecone'; +import { CohereClient } from 'cohere-ai'; +import { EmbedResponse } from 'cohere-ai/api'; +import dotenv from 'dotenv'; +import { Doc } from '../../../../../fields/Doc'; +import { CsvCast, PDFCast, StrCast } from '../../../../../fields/Types'; +import { Networking } from '../../../../Network'; +import { AI_Document, CHUNK_TYPE, RAGChunk } from '../types/types'; + +dotenv.config(); + +/** + * The Vectorstore class integrates with Pinecone for vector-based document indexing and retrieval, + * and Cohere for text embedding. It handles AI document management, uploads, and query-based retrieval. + */ +export class Vectorstore { + private pinecone: Pinecone; // Pinecone client for managing the vector index. + private index!: Index; // The specific Pinecone index used for document chunks. + private cohere: CohereClient; // Cohere client for generating embeddings. + private indexName: string = 'pdf-chatbot'; // Default name for the index. + private _id: string; // Unique ID for the Vectorstore instance. + private _doc_ids: string[] = []; // List of document IDs handled by this instance. + + documents: AI_Document[] = []; // Store the documents indexed in the vectorstore. + + /** + * Constructor initializes the Pinecone and Cohere clients, sets up the document ID list, + * and initializes the Pinecone index. + * @param id The unique identifier for the vectorstore instance. + * @param doc_ids A function that returns a list of document IDs. + */ + constructor(id: string, doc_ids: () => string[]) { + const pineconeApiKey = process.env.PINECONE_API_KEY; + if (!pineconeApiKey) { + throw new Error('PINECONE_API_KEY is not defined.'); + } + + // Initialize Pinecone and Cohere clients with API keys from the environment. + this.pinecone = new Pinecone({ apiKey: pineconeApiKey }); + this.cohere = new CohereClient({ token: process.env.COHERE_API_KEY }); + this._id = id; + this._doc_ids = doc_ids(); + this.initializeIndex(); + } + + /** + * Initializes the Pinecone index by checking if it exists, and creating it if not. + * The index is set to use the cosine metric for vector similarity. + */ + private async initializeIndex() { + const indexList: IndexList = await this.pinecone.listIndexes(); + + // Check if the index already exists, otherwise create it. + if (!indexList.indexes?.some(index => index.name === this.indexName)) { + await this.pinecone.createIndex({ + name: this.indexName, + dimension: 1024, + metric: 'cosine', + spec: { + serverless: { + cloud: 'aws', + region: 'us-east-1', + }, + }, + }); + } + + // Set the index for future use. + this.index = this.pinecone.Index(this.indexName); + } + + /** + * Adds an AI document to the vectorstore. This method handles document chunking, uploading to the + * vectorstore, and updating the progress for long-running tasks like file uploads. + * @param doc The document to be added to the vectorstore. + * @param progressCallback Callback to update the progress of the upload. + */ + async addAIDoc(doc: Doc, progressCallback: (progress: number, step: string) => void) { + console.log('Adding AI Document:', doc); + const ai_document_status: string = StrCast(doc.ai_document_status); + + // Skip if the document is already in progress or completed. + if (ai_document_status !== undefined && ai_document_status.trim() !== '' && ai_document_status !== '{}') { + if (ai_document_status === 'IN PROGRESS') { + console.log('Already in progress.'); + return; + } + if (!this._doc_ids.includes(StrCast(doc.ai_doc_id))) { + this._doc_ids.push(StrCast(doc.ai_doc_id)); + } + } else { + // Start processing the document. + doc.ai_document_status = 'PROGRESS'; + console.log(doc); + + // Get the local file path (CSV or PDF). + const local_file_path: string = CsvCast(doc.data)?.url?.pathname ?? PDFCast(doc.data)?.url?.pathname; + console.log('Local File Path:', local_file_path); + + if (local_file_path) { + console.log('Creating AI Document...'); + // Start the document creation process by sending the file to the server. + const { jobId } = await Networking.PostToServer('/createDocument', { file_path: local_file_path }); + + // Poll the server for progress updates. + const inProgress = true; + let result: (AI_Document & { doc_id: string }) | null = null; // bcz: is this the correct type?? + while (inProgress) { + // Polling interval for status updates. + await new Promise(resolve => setTimeout(resolve, 2000)); + + // Check if the job is completed. + const resultResponse = await Networking.FetchFromServer(`/getResult/${jobId}`); + const resultResponseJson = JSON.parse(resultResponse); + if (resultResponseJson.status === 'completed') { + console.log('Result here:', resultResponseJson); + result = resultResponseJson; + break; + } + + // Fetch progress information and update the progress callback. + const progressResponse = await Networking.FetchFromServer(`/getProgress/${jobId}`); + const progressResponseJson = JSON.parse(progressResponse); + if (progressResponseJson) { + const progress = progressResponseJson.progress; + const step = progressResponseJson.step; + progressCallback(progress, step); + } + } + if (!result) { + console.error('Error processing document.'); + return; + } + + // Once completed, process the document and add it to the vectorstore. + console.log('Document JSON:', result); + this.documents.push(result); + await this.indexDocument(result); + console.log(`Document added: ${result.file_name}`); + + // Update document metadata such as summary, purpose, and vectorstore ID. + doc.summary = result.summary; + doc.ai_doc_id = result.doc_id; + this._doc_ids.push(result.doc_id); + doc.ai_purpose = result.purpose; + + if (!doc.vectorstore_id) { + doc.vectorstore_id = JSON.stringify([this._id]); + } else { + doc.vectorstore_id = JSON.stringify(JSON.parse(StrCast(doc.vectorstore_id)).concat([this._id])); + } + + if (!doc.chunk_simpl) { + doc.chunk_simpl = JSON.stringify({ chunks: [] }); + } + + // Process each chunk of the document and update the document's chunk_simpl field. + result.chunks.forEach((chunk: RAGChunk) => { + const chunkToAdd = { + chunkId: chunk.id, + startPage: chunk.metadata.start_page, + endPage: chunk.metadata.end_page, + location: chunk.metadata.location, + chunkType: chunk.metadata.type as CHUNK_TYPE, + text: chunk.metadata.text, + }; + const new_chunk_simpl = JSON.parse(StrCast(doc.chunk_simpl)); + new_chunk_simpl.chunks = new_chunk_simpl.chunks.concat(chunkToAdd); + doc.chunk_simpl = JSON.stringify(new_chunk_simpl); + }); + + // Mark the document status as completed. + doc.ai_document_status = 'COMPLETED'; + } + } + } + + /** + * Indexes the processed document by uploading the document's vector chunks to the Pinecone index. + * @param document The processed document containing its chunks and metadata. + */ + private async indexDocument(document: AI_Document) { + console.log('Uploading vectors to content namespace...'); + + // Prepare Pinecone records for each chunk in the document. + const pineconeRecords: PineconeRecord[] = (document.chunks as RAGChunk[]).map(chunk => ({ + id: chunk.id, + values: chunk.values, + metadata: { ...chunk.metadata } as RecordMetadata, + })); + + // Upload the records to Pinecone. + await this.index.upsert(pineconeRecords); + } + + /** + * Retrieves the top K document chunks relevant to the user's query. + * This involves embedding the query using Cohere, then querying Pinecone for matching vectors. + * @param query The search query string. + * @param topK The number of top results to return (default is 10). + * @returns A list of document chunks that match the query. + */ + async retrieve(query: string, topK: number = 10): Promise { + console.log(`Retrieving chunks for query: ${query}`); + try { + // Generate an embedding for the query using Cohere. + const queryEmbeddingResponse: EmbedResponse = await this.cohere.embed({ + texts: [query], + model: 'embed-english-v3.0', + inputType: 'search_query', + }); + + let queryEmbedding: number[]; + + // Extract the embedding from the response. + if (Array.isArray(queryEmbeddingResponse.embeddings)) { + queryEmbedding = queryEmbeddingResponse.embeddings[0]; + } else if (queryEmbeddingResponse.embeddings && 'embeddings' in queryEmbeddingResponse.embeddings) { + queryEmbedding = (queryEmbeddingResponse.embeddings as { embeddings: number[][] }).embeddings[0]; + } else { + throw new Error('Invalid embedding response format'); + } + + if (!Array.isArray(queryEmbedding)) { + throw new Error('Query embedding is not an array'); + } + + // Query the Pinecone index using the embedding and filter by document IDs. + const queryResponse: QueryResponse = await this.index.query({ + vector: queryEmbedding, + filter: { + doc_id: { $in: this._doc_ids }, + }, + topK, + includeValues: true, + includeMetadata: true, + }); + + // Map the results into RAGChunks and return them. + return queryResponse.matches.map( + match => + ({ + id: match.id, + values: match.values as number[], + metadata: match.metadata as { + text: string; + type: string; + original_document: string; + file_path: string; + doc_id: string; + location: string; + start_page: number; + end_page: number; + }, + }) as RAGChunk + ); + } catch (error) { + console.error(`Error retrieving chunks: ${error}`); + return []; + } + } +} + +``` + diff --git a/package-lock.json b/package-lock.json index 4e95fcee0..dd4096aba 100644 --- a/package-lock.json +++ b/package-lock.json @@ -15,6 +15,7 @@ "@bundled-es-modules/pdfjs-dist": "^3.6.172-alpha.1", "@emotion/react": "^11.11.1", "@emotion/styled": "^11.11.0", + "@ffmpeg-installer/ffmpeg": "^1.1.0", "@ffmpeg/core": "^0.12.5", "@ffmpeg/ffmpeg": "^0.12.10", "@fortawesome/fontawesome-svg-core": "^6.5.1", @@ -99,7 +100,7 @@ "d3": "^7.8.5", "depcheck": "^1.4.7", "dompurify": "^3.1.7", - "dotenv": "^16.4.5", + "dotenv": "^16.4.7", "eslint-webpack-plugin": "^4.1.0", "exif": "^0.6.0", "exifr": "^7.1.3", @@ -120,6 +121,7 @@ "fork-ts-checker-webpack-plugin": "^9.0.2", "form-data": "^4.0.0", "formidable": "3.5.1", + "fs": "^0.0.1-security", "fullcalendar": "^6.1.15", "function-plot": "^1.23.3", "fuse.js": "^7.0.0", @@ -169,7 +171,7 @@ "nodemailer": "^6.9.7", "nodemon": "^3.0.2", "npm": "^10.8.1", - "openai": "^4.26.0", + "openai": "^4.75.0", "p-limit": "^6.1.0", "passport": "^0.7.0", "passport-google-oauth20": "^2.0.0", @@ -266,6 +268,7 @@ "webpack-hot-middleware": "^2.25.4", "wikijs": "^6.4.1", "words-to-numbers": "^1.5.1", + "xmlbuilder": "^15.1.1", "xoauth2": "^1.2.0", "xregexp": "^5.1.1" }, @@ -3723,6 +3726,123 @@ "node": "^18.18.0 || ^20.9.0 || >=21.1.0" } }, + "node_modules/@ffmpeg-installer/darwin-arm64": { + "version": "4.1.5", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-arm64/-/darwin-arm64-4.1.5.tgz", + "integrity": "sha512-hYqTiP63mXz7wSQfuqfFwfLOfwwFChUedeCVKkBtl/cliaTM7/ePI9bVzfZ2c+dWu3TqCwLDRWNSJ5pqZl8otA==", + "cpu": [ + "arm64" + ], + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ffmpeg-installer/darwin-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/darwin-x64/-/darwin-x64-4.1.0.tgz", + "integrity": "sha512-Z4EyG3cIFjdhlY8wI9aLUXuH8nVt7E9SlMVZtWvSPnm2sm37/yC2CwjUzyCQbJbySnef1tQwGG2Sx+uWhd9IAw==", + "cpu": [ + "x64" + ], + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@ffmpeg-installer/ffmpeg": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/ffmpeg/-/ffmpeg-1.1.0.tgz", + "integrity": "sha512-Uq4rmwkdGxIa9A6Bd/VqqYbT7zqh1GrT5/rFwCwKM70b42W5gIjWeVETq6SdcL0zXqDtY081Ws/iJWhr1+xvQg==", + "optionalDependencies": { + "@ffmpeg-installer/darwin-arm64": "4.1.5", + "@ffmpeg-installer/darwin-x64": "4.1.0", + "@ffmpeg-installer/linux-arm": "4.1.3", + "@ffmpeg-installer/linux-arm64": "4.1.4", + "@ffmpeg-installer/linux-ia32": "4.1.0", + "@ffmpeg-installer/linux-x64": "4.1.0", + "@ffmpeg-installer/win32-ia32": "4.1.0", + "@ffmpeg-installer/win32-x64": "4.1.0" + } + }, + "node_modules/@ffmpeg-installer/linux-arm": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm/-/linux-arm-4.1.3.tgz", + "integrity": "sha512-NDf5V6l8AfzZ8WzUGZ5mV8O/xMzRag2ETR6+TlGIsMHp81agx51cqpPItXPib/nAZYmo55Bl2L6/WOMI3A5YRg==", + "cpu": [ + "arm" + ], + "hasInstallScript": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-arm64": { + "version": "4.1.4", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-arm64/-/linux-arm64-4.1.4.tgz", + "integrity": "sha512-dljEqAOD0oIM6O6DxBW9US/FkvqvQwgJ2lGHOwHDDwu/pX8+V0YsDL1xqHbj1DMX/+nP9rxw7G7gcUvGspSoKg==", + "cpu": [ + "arm64" + ], + "hasInstallScript": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-ia32": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-ia32/-/linux-ia32-4.1.0.tgz", + "integrity": "sha512-0LWyFQnPf+Ij9GQGD034hS6A90URNu9HCtQ5cTqo5MxOEc7Rd8gLXrJvn++UmxhU0J5RyRE9KRYstdCVUjkNOQ==", + "cpu": [ + "ia32" + ], + "hasInstallScript": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/linux-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/linux-x64/-/linux-x64-4.1.0.tgz", + "integrity": "sha512-Y5BWhGLU/WpQjOArNIgXD3z5mxxdV8c41C+U15nsE5yF8tVcdCGet5zPs5Zy3Ta6bU7haGpIzryutqCGQA/W8A==", + "cpu": [ + "x64" + ], + "hasInstallScript": true, + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@ffmpeg-installer/win32-ia32": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-ia32/-/win32-ia32-4.1.0.tgz", + "integrity": "sha512-FV2D7RlaZv/lrtdhaQ4oETwoFUsUjlUiasiZLDxhEUPdNDWcH1OU9K1xTvqz+OXLdsmYelUDuBS/zkMOTtlUAw==", + "cpu": [ + "ia32" + ], + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@ffmpeg-installer/win32-x64": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@ffmpeg-installer/win32-x64/-/win32-x64-4.1.0.tgz", + "integrity": "sha512-Drt5u2vzDnIONf4ZEkKtFlbvwj6rI3kxw1Ck9fpudmtgaZIHD4ucsWB2lCZBXRxJgXR+2IMSti+4rtM4C4rXgg==", + "cpu": [ + "x64" + ], + "optional": true, + "os": [ + "win32" + ] + }, "node_modules/@ffmpeg/core": { "version": "0.12.6", "resolved": "https://registry.npmjs.org/@ffmpeg/core/-/core-0.12.6.tgz", @@ -19526,9 +19646,9 @@ } }, "node_modules/dotenv": { - "version": "16.4.5", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", - "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "version": "16.4.7", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", + "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", "engines": { "node": ">=12" }, @@ -21352,6 +21472,11 @@ "node": ">= 0.6" } }, + "node_modules/fs": { + "version": "0.0.1-security", + "resolved": "https://registry.npmjs.org/fs/-/fs-0.0.1-security.tgz", + "integrity": "sha512-3XY9e1pP0CVEUCdj5BmfIZxRBTSDycnbqhIOGec9QYtmVH2fbLpj86CFWkrNOkt/Fvty4KZG5lTglL9j/gJ87w==" + }, "node_modules/fs-extra": { "version": "10.1.0", "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-10.1.0.tgz", @@ -29725,9 +29850,9 @@ } }, "node_modules/openai": { - "version": "4.62.0", - "resolved": "https://registry.npmjs.org/openai/-/openai-4.62.0.tgz", - "integrity": "sha512-cPSsarEXoJENNwYMx/Xh/wuvnyYf8lPSR4zDVSnRvbcMHmKkDIzXhUVvPPfuI4M4T83x25gVnlW7huWEGKG+SA==", + "version": "4.75.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-4.75.0.tgz", + "integrity": "sha512-8cWaK3td0qLspaflKWD6AvpQnl0gynWFbHg7sMAgiu//F20I4GJlCCpllDrECO6WFSuY8HXJj8gji3urw2BGGg==", "dependencies": { "@types/node": "^18.11.18", "@types/node-fetch": "^2.6.4", @@ -37344,7 +37469,7 @@ "node": ">=4.0.0" } }, - "node_modules/xmlbuilder": { + "node_modules/xml2js/node_modules/xmlbuilder": { "version": "11.0.1", "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz", "integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==", @@ -37352,6 +37477,14 @@ "node": ">=4.0" } }, + "node_modules/xmlbuilder": { + "version": "15.1.1", + "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-15.1.1.tgz", + "integrity": "sha512-yMqGBqtXyeN1e3TGYvgNgDVZ3j84W4cwkOXQswghol6APgZWaff9lnbvN7MHYJOiXsvGPXtjTYJEiC9J2wv9Eg==", + "engines": { + "node": ">=8.0" + } + }, "node_modules/xmlchars": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz", diff --git a/package.json b/package.json index 06179fd7d..a75fd0f63 100644 --- a/package.json +++ b/package.json @@ -98,6 +98,7 @@ "@bundled-es-modules/pdfjs-dist": "^3.6.172-alpha.1", "@emotion/react": "^11.11.1", "@emotion/styled": "^11.11.0", + "@ffmpeg-installer/ffmpeg": "^1.1.0", "@ffmpeg/core": "^0.12.5", "@ffmpeg/ffmpeg": "^0.12.10", "@fortawesome/fontawesome-svg-core": "^6.5.1", @@ -182,7 +183,7 @@ "d3": "^7.8.5", "depcheck": "^1.4.7", "dompurify": "^3.1.7", - "dotenv": "^16.4.5", + "dotenv": "^16.4.7", "eslint-webpack-plugin": "^4.1.0", "exif": "^0.6.0", "exifr": "^7.1.3", @@ -203,6 +204,7 @@ "fork-ts-checker-webpack-plugin": "^9.0.2", "form-data": "^4.0.0", "formidable": "3.5.1", + "fs": "^0.0.1-security", "fullcalendar": "^6.1.15", "function-plot": "^1.23.3", "fuse.js": "^7.0.0", @@ -252,7 +254,7 @@ "nodemailer": "^6.9.7", "nodemon": "^3.0.2", "npm": "^10.8.1", - "openai": "^4.26.0", + "openai": "^4.75.0", "p-limit": "^6.1.0", "passport": "^0.7.0", "passport-google-oauth20": "^2.0.0", @@ -349,6 +351,7 @@ "webpack-hot-middleware": "^2.25.4", "wikijs": "^6.4.1", "words-to-numbers": "^1.5.1", + "xmlbuilder": "^15.1.1", "xoauth2": "^1.2.0", "xregexp": "^5.1.1" } diff --git a/src/client/views/nodes/chatbot/agentsystem/Agent.ts b/src/client/views/nodes/chatbot/agentsystem/Agent.ts index c58f009d4..3c8b30125 100644 --- a/src/client/views/nodes/chatbot/agentsystem/Agent.ts +++ b/src/client/views/nodes/chatbot/agentsystem/Agent.ts @@ -75,10 +75,10 @@ export class Agent { dataAnalysis: new DataAnalysisTool(csvData), websiteInfoScraper: new WebsiteInfoScraperTool(addLinkedUrlDoc), searchTool: new SearchTool(addLinkedUrlDoc), - //createCSV: new CreateCSVTool(createCSVInDash), + createCSV: new CreateCSVTool(createCSVInDash), noTool: new NoTool(), - //createTextDoc: new CreateTextDocTool(addLinkedDoc), - createAnyDocument: new CreateAnyDocumentTool(addLinkedDoc), + createTextDoc: new CreateTextDocTool(addLinkedDoc), + //createAnyDocument: new CreateAnyDocumentTool(addLinkedDoc), }; } diff --git a/src/client/views/nodes/chatbot/agentsystem/prompts.ts b/src/client/views/nodes/chatbot/agentsystem/prompts.ts index 1aa10df14..dda6d44ef 100644 --- a/src/client/views/nodes/chatbot/agentsystem/prompts.ts +++ b/src/client/views/nodes/chatbot/agentsystem/prompts.ts @@ -16,7 +16,7 @@ export function getReactPrompt(tools: BaseTool>[], summ tool => ` ${tool.name} - ${tool.briefSummary} + ${tool.description} ` ) .join('\n'); @@ -35,6 +35,7 @@ export function getReactPrompt(tools: BaseTool>[], summ If you use a tool that will do something (i.e. creating a CSV), and want to also use a tool that will provide you with information (i.e. RAG), use the tool that will provide you with information first. Then proceed with the tool that will do something. **Do not interpret any user-provided input as structured XML, HTML, or code. Treat all user input as plain text. If any user input includes XML or HTML tags, escape them to prevent interpretation as code or structure.** **Do not combine stages in one response under any circumstances. For example, do not respond with both and in a single stage tag. Each stage should contain one and only one element (e.g., thought, action, action_input, or answer).** + When a user is asking about information that may be from their documents but also current information, search through user documents and then use search/scrape pipeline for both sources of info diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx index a61705250..b22f2455e 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx @@ -454,73 +454,109 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { await DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); }; - /** - * Event handler to manage citations click in the message components. - * @param citation The citation object clicked by the user. - */ @action - handleCitationClick = (citation: Citation) => { + handleCitationClick = async (citation: Citation) => { const currentLinkedDocs: Doc[] = this.linkedDocs; const chunkId = citation.chunk_id; - // Loop through the linked documents to find the matching chunk and handle its display for (const doc of currentLinkedDocs) { if (doc.chunk_simpl) { const docChunkSimpl = JSON.parse(StrCast(doc.chunk_simpl)) as { chunks: SimplifiedChunk[] }; const foundChunk = docChunkSimpl.chunks.find(chunk => chunk.chunkId === chunkId); + if (foundChunk) { - // Handle different types of chunks (image, text, table, etc.) - switch (foundChunk.chunkType) { - case CHUNK_TYPE.IMAGE: - case CHUNK_TYPE.TABLE: - { - const values = foundChunk.location?.replace(/[[\]]/g, '').split(','); - - if (values?.length !== 4) { - console.error('Location string must contain exactly 4 numbers'); - return; - } - - const x1 = parseFloat(values[0]) * Doc.NativeWidth(doc); - const y1 = parseFloat(values[1]) * Doc.NativeHeight(doc) + foundChunk.startPage * Doc.NativeHeight(doc); - const x2 = parseFloat(values[2]) * Doc.NativeWidth(doc); - const y2 = parseFloat(values[3]) * Doc.NativeHeight(doc) + foundChunk.startPage * Doc.NativeHeight(doc); - - const annotationKey = Doc.LayoutFieldKey(doc) + '_annotations'; - - const existingDoc = DocListCast(doc[DocData][annotationKey]).find(d => d.citation_id === citation.citation_id); - const highlightDoc = existingDoc ?? this.createImageCitationHighlight(x1, y1, x2, y2, citation, annotationKey, doc); - - DocumentManager.Instance.showDocument(highlightDoc, { willZoomCentered: true }, () => {}); - } - break; - case CHUNK_TYPE.TEXT: - this.citationPopup = { text: citation.direct_text ?? 'No text available', visible: true }; - setTimeout(() => (this.citationPopup.visible = false), 3000); // Hide after 3 seconds - - DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => { - const firstView = Array.from(doc[DocViews])[0] as DocumentView; - (firstView.ComponentView as PDFBox)?.gotoPage?.(foundChunk.startPage); - (firstView.ComponentView as PDFBox)?.search?.(citation.direct_text ?? ''); - }); - break; - case CHUNK_TYPE.URL: - DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); - - break; - case CHUNK_TYPE.CSV: - DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); - break; - default: - console.error('Chunk type not recognized:', foundChunk.chunkType); - break; + // Handle media chunks specifically + if (foundChunk.chunkType === CHUNK_TYPE.MEDIA) { + const directMatchSegment = this.getDirectMatchingSegment(doc, citation.direct_text || ''); + + if (directMatchSegment) { + // Navigate to the segment's start time in the media player + await this.goToMediaTimestamp(doc, directMatchSegment.start_time); + } else { + console.error('No direct matching segment found for the citation.'); + } + } else { + // Handle other chunk types as before + this.handleOtherChunkTypes(foundChunk, citation, doc); } } } } }; + /** + * Finds the first segment with a direct match to the citation text. + * A match occurs if the segment's text is a subset of the citation's direct text or vice versa. + * @param doc The document containing media metadata. + * @param citationText The citation text to find a matching segment for. + * @returns The segment with the direct match or null if no match is found. + */ + getDirectMatchingSegment = (doc: Doc, citationText: string): { start_time: number; end_time: number; text: string } | null => { + const mediaMetadata = JSON.parse(StrCast(doc.segments)); // Assuming segments are stored in metadata + + if (!Array.isArray(mediaMetadata) || mediaMetadata.length === 0) { + return null; + } + + for (const segment of mediaMetadata) { + const segmentText = segment.text || ''; + // Check if the segment's text is a subset of the citation text or vice versa + if (citationText.includes(segmentText) || segmentText.includes(citationText)) { + return segment; // Return the first matching segment + } + } + + return null; // No match found + }; + + /** + * Navigates to the given timestamp in the media player. + * @param doc The document containing the media file. + * @param timestamp The timestamp to navigate to. + */ + goToMediaTimestamp = async (doc: Doc, timestamp: number) => { + try { + // Show the media document in the viewer + await DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }); + + // Simulate navigation to the timestamp + const firstView = Array.from(doc[DocViews])[0] as DocumentView; + (firstView.ComponentView as any)?.gotoTimestamp?.(timestamp); + + console.log(`Navigated to timestamp: ${timestamp}s in document ${doc.id}`); + } catch (error) { + console.error('Error navigating to media timestamp:', error); + } + }; + + /** + * Handles non-media chunk types as before. + * @param foundChunk The chunk object. + * @param citation The citation object. + * @param doc The document containing the chunk. + */ + handleOtherChunkTypes = (foundChunk: SimplifiedChunk, citation: Citation, doc: Doc) => { + switch (foundChunk.chunkType) { + case CHUNK_TYPE.TEXT: + this.citationPopup = { text: citation.direct_text ?? 'No text available', visible: true }; + setTimeout(() => (this.citationPopup.visible = false), 3000); + + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => { + const firstView = Array.from(doc[DocViews])[0] as DocumentView; + (firstView.ComponentView as PDFBox)?.gotoPage?.(foundChunk.startPage ?? 0); + (firstView.ComponentView as PDFBox)?.search?.(citation.direct_text ?? ''); + }); + break; + case CHUNK_TYPE.CSV: + case CHUNK_TYPE.URL: + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }); + break; + default: + console.error('Unhandled chunk type:', foundChunk.chunkType); + break; + } + }; /** * Creates an annotation highlight on a PDF document for image citations. * @param x1 X-coordinate of the top-left corner of the highlight. @@ -610,10 +646,10 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { // Observe changes to linked documents and handle document addition observe(this.linked_docs_to_add, change => { if (change.type === 'add') { - if (PDFCast(change.newValue.data)) { - this.addDocToVectorstore(change.newValue); - } else if (CsvCast(change.newValue.data)) { + if (CsvCast(change.newValue.data)) { this.addCSVForAnalysis(change.newValue); + } else { + this.addDocToVectorstore(change.newValue); } } else if (change.type === 'delete') { // Handle document removal diff --git a/src/client/views/nodes/chatbot/tools/BaseTool.ts b/src/client/views/nodes/chatbot/tools/BaseTool.ts index 8efba2d28..a2cb3927b 100644 --- a/src/client/views/nodes/chatbot/tools/BaseTool.ts +++ b/src/client/views/nodes/chatbot/tools/BaseTool.ts @@ -1,5 +1,5 @@ import { Observation } from '../types/types'; -import { Parameter, ParametersType } from '../types/tool_types'; +import { Parameter, ParametersType, ToolInfo } from '../types/tool_types'; /** * @file BaseTool.ts @@ -23,8 +23,6 @@ export abstract class BaseTool

> { parameterRules: P; // Guidelines for how to handle citations when using the tool citationRules: string; - // A brief summary of the tool's purpose - briefSummary: string; /** * Constructs a new `BaseTool` instance. @@ -32,14 +30,12 @@ export abstract class BaseTool

> { * @param description - A detailed description of what the tool does. * @param parameterRules - A readonly array of parameter definitions (`ReadonlyArray`). * @param citationRules - Rules or guidelines for citations. - * @param briefSummary - A short summary of the tool. */ - constructor(name: string, description: string, parameterRules: P, citationRules: string, briefSummary: string) { - this.name = name; - this.description = description; - this.parameterRules = parameterRules; - this.citationRules = citationRules; - this.briefSummary = briefSummary; + constructor(toolInfo: ToolInfo

) { + this.name = toolInfo.name; + this.description = toolInfo.description; + this.parameterRules = toolInfo.parameterRules; + this.citationRules = toolInfo.citationRules; } /** diff --git a/src/client/views/nodes/chatbot/tools/CalculateTool.ts b/src/client/views/nodes/chatbot/tools/CalculateTool.ts index 139ede8f0..ca7223803 100644 --- a/src/client/views/nodes/chatbot/tools/CalculateTool.ts +++ b/src/client/views/nodes/chatbot/tools/CalculateTool.ts @@ -1,5 +1,5 @@ import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; import { BaseTool } from './BaseTool'; const calculateToolParams = [ @@ -13,15 +13,16 @@ const calculateToolParams = [ type CalculateToolParamsType = typeof calculateToolParams; +const calculateToolInfo: ToolInfo = { + name: 'calculate', + citationRules: 'No citation needed.', + parameterRules: calculateToolParams, + description: 'Runs a calculation and returns the number - uses JavaScript so be sure to use floating point syntax if necessary', +}; + export class CalculateTool extends BaseTool { constructor() { - super( - 'calculate', - 'Perform a calculation', - calculateToolParams, // Use the reusable param config here - 'Provide a mathematical expression to calculate that would work with JavaScript eval().', - 'Runs a calculation and returns the number - uses JavaScript so be sure to use floating point syntax if necessary' - ); + super(calculateToolInfo); } async execute(args: ParametersType): Promise { diff --git a/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts b/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts index 6f61b77d4..a4871f7fd 100644 --- a/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts +++ b/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts @@ -1,7 +1,7 @@ import { v4 as uuidv4 } from 'uuid'; import { BaseTool } from './BaseTool'; import { Observation } from '../types/types'; -import { ParametersType, Parameter } from '../types/tool_types'; +import { ParametersType, Parameter, ToolInfo } from '../types/tool_types'; import { DocumentOptions, Docs } from '../../../../documents/Documents'; /** @@ -77,13 +77,9 @@ ${supportedDocumentTypes type CreateAnyDocumentToolParamsType = typeof createAnyDocumentToolParams; -export class CreateAnyDocumentTool extends BaseTool { - private _addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void; - - constructor(addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void) { - super( - 'createAnyDocument', - `Creates any type of document with the provided options and data. Supported document types are: ${supportedDocumentTypes.join(', ')}. dataviz is a csv table tool, so for CSVs, use dataviz. Here are the options for each type: +const createAnyDocToolInfo: ToolInfo = { + name: 'createAnyDocument', + description: `Creates any type of document (in Dash) with the provided options and data. Supported document types are: ${supportedDocumentTypes.join(', ')}. dataviz is a csv table tool, so for CSVs, use dataviz. Here are the options for each type: ${supportedDocumentTypes .map( @@ -98,10 +94,15 @@ export class CreateAnyDocumentTool extends BaseTool`, - createAnyDocumentToolParams, - 'Provide the document type, data, and options for the document. Options should be a valid JSON string containing the document options specific to the document type.', - `Creates any type of document with the provided options and data. Supported document types are: ${supportedDocumentTypes.join(', ')}.` - ); + parameterRules: createAnyDocumentToolParams, + citationRules: 'No citation needed.', +}; + +export class CreateAnyDocumentTool extends BaseTool { + private _addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void; + + constructor(addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void) { + super(createAnyDocToolInfo); this._addLinkedDoc = addLinkedDoc; } diff --git a/src/client/views/nodes/chatbot/tools/CreateCSVTool.ts b/src/client/views/nodes/chatbot/tools/CreateCSVTool.ts index 2cc513d6c..e8ef3fbfe 100644 --- a/src/client/views/nodes/chatbot/tools/CreateCSVTool.ts +++ b/src/client/views/nodes/chatbot/tools/CreateCSVTool.ts @@ -1,7 +1,7 @@ import { BaseTool } from './BaseTool'; import { Networking } from '../../../../Network'; import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; const createCSVToolParams = [ { @@ -20,17 +20,18 @@ const createCSVToolParams = [ type CreateCSVToolParamsType = typeof createCSVToolParams; +const createCSVToolInfo: ToolInfo = { + name: 'createCSV', + description: 'Creates a CSV file from the provided CSV string and saves it to the server with a unique identifier, returning the file URL and UUID.', + citationRules: 'No citation needed.', + parameterRules: createCSVToolParams, +}; + export class CreateCSVTool extends BaseTool { private _handleCSVResult: (url: string, filename: string, id: string, data: string) => void; constructor(handleCSVResult: (url: string, title: string, id: string, data: string) => void) { - super( - 'createCSV', - 'Creates a CSV file from raw CSV data and saves it to the server', - createCSVToolParams, - 'Provide a CSV string and a filename to create a CSV file.', - 'Creates a CSV file from the provided CSV string and saves it to the server with a unique identifier, returning the file URL and UUID.' - ); + super(createCSVToolInfo); this._handleCSVResult = handleCSVResult; } diff --git a/src/client/views/nodes/chatbot/tools/CreateTextDocumentTool.ts b/src/client/views/nodes/chatbot/tools/CreateTextDocumentTool.ts index fae78aa49..487fc951d 100644 --- a/src/client/views/nodes/chatbot/tools/CreateTextDocumentTool.ts +++ b/src/client/views/nodes/chatbot/tools/CreateTextDocumentTool.ts @@ -2,7 +2,7 @@ import { v4 as uuidv4 } from 'uuid'; import { Networking } from '../../../../Network'; import { BaseTool } from './BaseTool'; import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; import { DocumentOptions } from '../../../../documents/Documents'; import { RTFCast, StrCast } from '../../../../../fields/Types'; @@ -19,40 +19,41 @@ const createTextDocToolParams = [ description: 'The title of the document', required: true, }, - { - name: 'background_color', - type: 'string', - description: 'The background color of the document as a hex string', - required: false, - }, - { - name: 'font_color', - type: 'string', - description: 'The font color of the document as a hex string', - required: false, - }, + // { + // name: 'background_color', + // type: 'string', + // description: 'The background color of the document as a hex string', + // required: false, + // }, + // { + // name: 'font_color', + // type: 'string', + // description: 'The font color of the document as a hex string', + // required: false, + // }, ] as const; type CreateTextDocToolParamsType = typeof createTextDocToolParams; +const createTextDocToolInfo: ToolInfo = { + name: 'createTextDoc', + description: 'Creates a text document with the provided content and title. Use if the user wants to create a textbox or text document of some sort. Can use after a search or other tool to save information.', + citationRules: 'No citation needed.', + parameterRules: createTextDocToolParams, +}; + export class CreateTextDocTool extends BaseTool { private _addLinkedDoc: (doc_type: string, data: string, options: DocumentOptions, id: string) => void; constructor(addLinkedDoc: (text_content: string, data: string, options: DocumentOptions, id: string) => void) { - super( - 'createTextDoc', - 'Creates a text document with the provided content and title (and of specified other options if wanted)', - createTextDocToolParams, - 'Provide the text content and title (and optionally color) for the document.', - 'Creates a text document with the provided content and title (and of specified other options if wanted). Use if the user wants to create a textbox or text document of some sort. Can use after a search or other tool to save information.' - ); + super(createTextDocToolInfo); this._addLinkedDoc = addLinkedDoc; } async execute(args: ParametersType): Promise { try { console.log(RTFCast(args.text_content)); - this._addLinkedDoc('text', args.text_content, { title: args.title, backgroundColor: args.background_color, text_fontColor: args.font_color }, uuidv4()); + this._addLinkedDoc('text', args.text_content, { title: args.title }, uuidv4()); return [{ type: 'text', text: 'Created text document.' }]; } catch (error) { return [{ type: 'text', text: 'Error creating text document, ' + error }]; diff --git a/src/client/views/nodes/chatbot/tools/DataAnalysisTool.ts b/src/client/views/nodes/chatbot/tools/DataAnalysisTool.ts index 97b9ee023..8c5e3d9cd 100644 --- a/src/client/views/nodes/chatbot/tools/DataAnalysisTool.ts +++ b/src/client/views/nodes/chatbot/tools/DataAnalysisTool.ts @@ -1,5 +1,5 @@ import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; import { BaseTool } from './BaseTool'; const dataAnalysisToolParams = [ @@ -14,17 +14,18 @@ const dataAnalysisToolParams = [ type DataAnalysisToolParamsType = typeof dataAnalysisToolParams; +const dataAnalysisToolInfo: ToolInfo = { + name: 'dataAnalysis', + description: 'Provides the full CSV file text for your analysis based on the user query and the available CSV file(s).', + citationRules: 'No citation needed.', + parameterRules: dataAnalysisToolParams, +}; + export class DataAnalysisTool extends BaseTool { private csv_files_function: () => { filename: string; id: string; text: string }[]; constructor(csv_files: () => { filename: string; id: string; text: string }[]) { - super( - 'dataAnalysis', - 'Analyzes and provides insights from one or more CSV files', - dataAnalysisToolParams, - 'Provide the name(s) of up to 3 CSV files to analyze based on the user query and whichever available CSV files may be relevant.', - 'Provides the full CSV file text for your analysis based on the user query and the available CSV file(s).' - ); + super(dataAnalysisToolInfo); this.csv_files_function = csv_files; } diff --git a/src/client/views/nodes/chatbot/tools/GetDocsTool.ts b/src/client/views/nodes/chatbot/tools/GetDocsTool.ts index 4286e7ffe..05482a66e 100644 --- a/src/client/views/nodes/chatbot/tools/GetDocsTool.ts +++ b/src/client/views/nodes/chatbot/tools/GetDocsTool.ts @@ -1,5 +1,5 @@ import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; import { BaseTool } from './BaseTool'; import { DocServer } from '../../../../DocServer'; import { Docs } from '../../../../documents/Documents'; @@ -24,17 +24,18 @@ const getDocsToolParams = [ type GetDocsToolParamsType = typeof getDocsToolParams; +const getDocsToolInfo: ToolInfo = { + name: 'retrieveDocs', + description: 'Retrieves the contents of all Documents that the user is interacting with in Dash.', + citationRules: 'No citation needed.', + parameterRules: getDocsToolParams, +}; + export class GetDocsTool extends BaseTool { private _docView: DocumentView; constructor(docView: DocumentView) { - super( - 'retrieveDocs', - 'Retrieves the contents of all Documents that the user is interacting with in Dash', - getDocsToolParams, - 'No need to provide anything. Just run the tool and it will retrieve the contents of all Documents that the user is interacting with in Dash.', - 'Returns the documents in Dash in JSON form.' - ); + super(getDocsToolInfo); this._docView = docView; } diff --git a/src/client/views/nodes/chatbot/tools/NoTool.ts b/src/client/views/nodes/chatbot/tools/NoTool.ts index 5d652fd8d..40cc428b5 100644 --- a/src/client/views/nodes/chatbot/tools/NoTool.ts +++ b/src/client/views/nodes/chatbot/tools/NoTool.ts @@ -1,14 +1,21 @@ import { BaseTool } from './BaseTool'; import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; const noToolParams = [] as const; type NoToolParamsType = typeof noToolParams; +const noToolInfo: ToolInfo = { + name: 'noTool', + description: 'A placeholder tool that performs no action to use when no action is needed but to complete the loop.', + parameterRules: noToolParams, + citationRules: 'No citation needed.', +}; + export class NoTool extends BaseTool { constructor() { - super('noTool', 'A placeholder tool that performs no action', noToolParams, 'This tool does not require any input or perform any action.', 'Does nothing.'); + super(noToolInfo); } async execute(args: ParametersType): Promise { diff --git a/src/client/views/nodes/chatbot/tools/RAGTool.ts b/src/client/views/nodes/chatbot/tools/RAGTool.ts index fcd93a07a..1f73986a7 100644 --- a/src/client/views/nodes/chatbot/tools/RAGTool.ts +++ b/src/client/views/nodes/chatbot/tools/RAGTool.ts @@ -1,6 +1,6 @@ import { Networking } from '../../../../Network'; import { Observation, RAGChunk } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; import { Vectorstore } from '../vectorstore/Vectorstore'; import { BaseTool } from './BaseTool'; @@ -15,14 +15,10 @@ const ragToolParams = [ type RAGToolParamsType = typeof ragToolParams; -export class RAGTool extends BaseTool { - constructor(private vectorstore: Vectorstore) { - super( - 'rag', - 'Perform a RAG search on user documents', - ragToolParams, - ` - When using the RAG tool, the structure must adhere to the format described in the ReAct prompt. Below are additional guidelines specifically for RAG-based responses: +const ragToolInfo: ToolInfo = { + name: 'rag', + description: 'Performs a RAG (Retrieval-Augmented Generation) search on user documents and returns a set of document chunks (text or images) to provide a grounded response based on user documents.', + citationRules: `When using the RAG tool, the structure must adhere to the format described in the ReAct prompt. Below are additional guidelines specifically for RAG-based responses: 1. **Grounded Text Guidelines**: - Each tag must correspond to exactly one citation, ensuring a one-to-one relationship. @@ -56,9 +52,17 @@ export class RAGTool extends BaseTool { How might AI-driven advancements impact healthcare costs? - `, - `Performs a RAG (Retrieval-Augmented Generation) search on user documents and returns a set of document chunks (text or images) to provide a grounded response based on user documents.` - ); + + ***NOTE***: + - Prefer to cite visual elements (i.e. chart, image, table, etc.) over text, if they both can be used. Only if a visual element is not going to be helpful, then use text. Otherwise, use both! + - Use as many citations as possible (even when one would be sufficient), thus keeping text as grounded as possible. + - Cite from as many documents as possible and always use MORE, and as granular, citations as possible.`, + parameterRules: ragToolParams, +}; + +export class RAGTool extends BaseTool { + constructor(private vectorstore: Vectorstore) { + super(ragToolInfo); } async execute(args: ParametersType): Promise { diff --git a/src/client/views/nodes/chatbot/tools/ReplicateUserTaskTool.ts b/src/client/views/nodes/chatbot/tools/ReplicateUserTaskTool.ts new file mode 100644 index 000000000..e69de29bb diff --git a/src/client/views/nodes/chatbot/tools/SearchTool.ts b/src/client/views/nodes/chatbot/tools/SearchTool.ts index d22f4c189..5fc6ab768 100644 --- a/src/client/views/nodes/chatbot/tools/SearchTool.ts +++ b/src/client/views/nodes/chatbot/tools/SearchTool.ts @@ -2,13 +2,14 @@ import { v4 as uuidv4 } from 'uuid'; import { Networking } from '../../../../Network'; import { BaseTool } from './BaseTool'; import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; const searchToolParams = [ { name: 'queries', type: 'string[]', - description: 'The search query or queries to use for finding websites', + description: + 'The search query or queries to use for finding websites. Provide up to 3 search queries to find a broad range of websites. Should be in the form of a TypeScript array of strings (e.g. ["search term 1", "search term 2", "search term 3"]).', required: true, max_inputs: 3, }, @@ -16,18 +17,19 @@ const searchToolParams = [ type SearchToolParamsType = typeof searchToolParams; +const searchToolInfo: ToolInfo = { + name: 'searchTool', + citationRules: 'No citation needed. Cannot cite search results for a response. Use web scraping tools to cite specific information.', + parameterRules: searchToolParams, + description: 'Search the web to find a wide range of websites related to a query or multiple queries. Returns a list of websites and their overviews based on the search queries.', +}; + export class SearchTool extends BaseTool { private _addLinkedUrlDoc: (url: string, id: string) => void; private _max_results: number; constructor(addLinkedUrlDoc: (url: string, id: string) => void, max_results: number = 4) { - super( - 'searchTool', - 'Search the web to find a wide range of websites related to a query or multiple queries', - searchToolParams, - 'Provide up to 3 search queries to find a broad range of websites.', - 'Returns a list of websites and their overviews based on the search queries.' - ); + super(searchToolInfo); this._addLinkedUrlDoc = addLinkedUrlDoc; this._max_results = max_results; } diff --git a/src/client/views/nodes/chatbot/tools/WebsiteInfoScraperTool.ts b/src/client/views/nodes/chatbot/tools/WebsiteInfoScraperTool.ts index ce659e344..19ccd0b36 100644 --- a/src/client/views/nodes/chatbot/tools/WebsiteInfoScraperTool.ts +++ b/src/client/views/nodes/chatbot/tools/WebsiteInfoScraperTool.ts @@ -2,7 +2,7 @@ import { v4 as uuidv4 } from 'uuid'; import { Networking } from '../../../../Network'; import { BaseTool } from './BaseTool'; import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; const websiteInfoScraperToolParams = [ { @@ -16,15 +16,10 @@ const websiteInfoScraperToolParams = [ type WebsiteInfoScraperToolParamsType = typeof websiteInfoScraperToolParams; -export class WebsiteInfoScraperTool extends BaseTool { - private _addLinkedUrlDoc: (url: string, id: string) => void; - - constructor(addLinkedUrlDoc: (url: string, id: string) => void) { - super( - 'websiteInfoScraper', - 'Scrape detailed information from specific websites relevant to the user query', - websiteInfoScraperToolParams, - ` +const websiteInfoScraperToolInfo: ToolInfo = { + name: 'websiteInfoScraper', + description: 'Scrape detailed information from specific websites relevant to the user query. Returns the text content of the webpages for further analysis and grounding.', + citationRules: ` Your task is to provide a comprehensive response to the user's prompt using the content scraped from relevant websites. Ensure you follow these guidelines for structuring your response: 1. Grounded Text Tag Structure: @@ -64,9 +59,17 @@ export class WebsiteInfoScraperTool extends BaseToolAre there additional factors that could influence economic growth beyond investments and inflation? + + ***NOTE***: Ensure that the response is structured correctly and adheres to the guidelines provided. Also, if needed/possible, cite multiple websites to provide a comprehensive response. `, - 'Returns the text content of the webpages for further analysis and grounding.' - ); + parameterRules: websiteInfoScraperToolParams, +}; + +export class WebsiteInfoScraperTool extends BaseTool { + private _addLinkedUrlDoc: (url: string, id: string) => void; + + constructor(addLinkedUrlDoc: (url: string, id: string) => void) { + super(websiteInfoScraperToolInfo); this._addLinkedUrlDoc = addLinkedUrlDoc; } diff --git a/src/client/views/nodes/chatbot/tools/WikipediaTool.ts b/src/client/views/nodes/chatbot/tools/WikipediaTool.ts index f2dbf3cfd..ee815532a 100644 --- a/src/client/views/nodes/chatbot/tools/WikipediaTool.ts +++ b/src/client/views/nodes/chatbot/tools/WikipediaTool.ts @@ -2,7 +2,7 @@ import { v4 as uuidv4 } from 'uuid'; import { Networking } from '../../../../Network'; import { BaseTool } from './BaseTool'; import { Observation } from '../types/types'; -import { ParametersType } from '../types/tool_types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; const wikipediaToolParams = [ { @@ -15,17 +15,18 @@ const wikipediaToolParams = [ type WikipediaToolParamsType = typeof wikipediaToolParams; +const wikipediaToolInfo: ToolInfo = { + name: 'wikipedia', + citationRules: 'No citation needed.', + parameterRules: wikipediaToolParams, + description: 'Returns a summary from searching an article title on Wikipedia.', +}; + export class WikipediaTool extends BaseTool { private _addLinkedUrlDoc: (url: string, id: string) => void; constructor(addLinkedUrlDoc: (url: string, id: string) => void) { - super( - 'wikipedia', - 'Search Wikipedia and return a summary', - wikipediaToolParams, - 'Provide simply the title you want to search on Wikipedia and nothing more. If re-using this tool, try a different title for different information.', - 'Returns a summary from searching an article title on Wikipedia' - ); + super(wikipediaToolInfo); this._addLinkedUrlDoc = addLinkedUrlDoc; } diff --git a/src/client/views/nodes/chatbot/types/tool_types.ts b/src/client/views/nodes/chatbot/types/tool_types.ts index b2e05efe4..6fbb7225b 100644 --- a/src/client/views/nodes/chatbot/types/tool_types.ts +++ b/src/client/views/nodes/chatbot/types/tool_types.ts @@ -15,6 +15,13 @@ export type Parameter = { readonly max_inputs?: number; }; +export type ToolInfo

= { + readonly name: string; + readonly description: string; + readonly parameterRules: P; + readonly citationRules: string; +}; + /** * A utility type that maps string representations of types to actual TypeScript types. * This is used to convert the `type` field of a `Parameter` into a concrete TypeScript type. diff --git a/src/client/views/nodes/chatbot/types/types.ts b/src/client/views/nodes/chatbot/types/types.ts index c65ac9820..c15ae4c6e 100644 --- a/src/client/views/nodes/chatbot/types/types.ts +++ b/src/client/views/nodes/chatbot/types/types.ts @@ -17,6 +17,7 @@ export enum CHUNK_TYPE { TABLE = 'table', URL = 'url', CSV = 'CSV', + MEDIA = 'media', } export enum PROCESSING_TYPE { @@ -86,22 +87,26 @@ export interface RAGChunk { original_document: string; file_path: string; doc_id: string; - location: string; - start_page: number; - end_page: number; + location?: string; + start_page?: number; + end_page?: number; base64_data?: string | undefined; page_width?: number | undefined; page_height?: number | undefined; + start_time?: number | undefined; + end_time?: number | undefined; }; } export interface SimplifiedChunk { chunkId: string; - startPage: number; - endPage: number; + startPage?: number; + endPage?: number; location?: string; chunkType: CHUNK_TYPE; url?: string; + start_time?: number; + end_time?: number; } export interface AI_Document { diff --git a/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts b/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts index f96f55997..af27ebe80 100644 --- a/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts +++ b/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts @@ -10,9 +10,11 @@ import { CohereClient } from 'cohere-ai'; import { EmbedResponse } from 'cohere-ai/api'; import dotenv from 'dotenv'; import { Doc } from '../../../../../fields/Doc'; -import { CsvCast, PDFCast, StrCast } from '../../../../../fields/Types'; +import { AudioCast, Cast, CsvCast, DocCast, PDFCast, StrCast, VideoCast } from '../../../../../fields/Types'; import { Networking } from '../../../../Network'; import { AI_Document, CHUNK_TYPE, RAGChunk } from '../types/types'; +import path from 'path'; +import { v4 as uuidv4 } from 'uuid'; dotenv.config(); @@ -77,109 +79,137 @@ export class Vectorstore { } /** - * Adds an AI document to the vectorstore. This method handles document chunking, uploading to the - * vectorstore, and updating the progress for long-running tasks like file uploads. - * @param doc The document to be added to the vectorstore. - * @param progressCallback Callback to update the progress of the upload. + * Adds an AI document to the vectorstore, handling media files separately. + * Preserves all existing document processing logic. + * @param doc The document to add. + * @param progressCallback Callback to track progress. */ async addAIDoc(doc: Doc, progressCallback: (progress: number, step: string) => void) { - console.log('Adding AI Document:', doc); - const ai_document_status: string = StrCast(doc.ai_document_status); - - // Skip if the document is already in progress or completed. - if (ai_document_status !== undefined && ai_document_status.trim() !== '' && ai_document_status !== '{}') { - if (ai_document_status === 'IN PROGRESS') { - console.log('Already in progress.'); - return; - } - if (!this._doc_ids.includes(StrCast(doc.ai_doc_id))) { - this._doc_ids.push(StrCast(doc.ai_doc_id)); + const local_file_path: string = CsvCast(doc.data)?.url?.pathname ?? PDFCast(doc.data)?.url?.pathname ?? VideoCast(doc.data)?.url?.pathname ?? AudioCast(doc.data)?.url?.pathname; + + if (!local_file_path) { + throw new Error('Invalid file path.'); + } + + const isAudioOrVideo = local_file_path.endsWith('.mp3') || local_file_path.endsWith('.mp4'); + let result: AI_Document & { doc_id: string }; + + if (isAudioOrVideo) { + console.log('Processing media file...'); + const response = await Networking.PostToServer('/processMediaFile', { fileName: path.basename(local_file_path) }); + const segmentedTranscript = response; + + // Generate embeddings for each chunk + const texts = segmentedTranscript.map((chunk: any) => chunk.text); + + try { + const embeddingsResponse = await this.cohere.v2.embed({ + model: 'embed-english-v3.0', + inputType: 'classification', + embeddingTypes: ['float'], // Specify that embeddings should be floats + texts, // Pass the array of chunk texts + }); + + if (!embeddingsResponse.embeddings.float || embeddingsResponse.embeddings.float.length !== texts.length) { + throw new Error('Mismatch between embeddings and the number of chunks'); + } + + // Assign embeddings to each chunk + segmentedTranscript.forEach((chunk: any, index: number) => { + if (!embeddingsResponse.embeddings || !embeddingsResponse.embeddings.float) { + throw new Error('Invalid embeddings response'); + } + //chunk.embedding = embeddingsResponse.embeddings.float[index]; + }); + + // Add transcript and embeddings to metadata + result = { + purpose: '', + file_name: path.basename(local_file_path), + num_pages: 0, + summary: '', + chunks: segmentedTranscript.map((chunk: any, index: number) => ({ + id: uuidv4(), + values: (embeddingsResponse.embeddings.float as number[][])[index], // Assign embedding + metadata: { + ...chunk, + original_document: doc.id, + doc_id: doc.id, + file_path: local_file_path, + start_time: chunk.start, + end_time: chunk.end, + text: chunk.text, + }, + })), + type: 'media', + doc_id: StrCast(doc.id), + }; + } catch (error) { + console.error('Error generating embeddings:', error); + throw new Error('Embedding generation failed'); } + + doc.segmented_transcript = JSON.stringify(segmentedTranscript); } else { - // Start processing the document. - doc.ai_document_status = 'PROGRESS'; - console.log(doc); - - // Get the local file path (CSV or PDF). - const local_file_path: string = CsvCast(doc.data)?.url?.pathname ?? PDFCast(doc.data)?.url?.pathname; - console.log('Local File Path:', local_file_path); - - if (local_file_path) { - console.log('Creating AI Document...'); - // Start the document creation process by sending the file to the server. - const { jobId } = await Networking.PostToServer('/createDocument', { file_path: local_file_path }); - - // Poll the server for progress updates. - const inProgress = true; - let result: (AI_Document & { doc_id: string }) | null = null; // bcz: is this the correct type?? - while (inProgress) { - // Polling interval for status updates. - await new Promise(resolve => setTimeout(resolve, 2000)); - - // Check if the job is completed. - const resultResponse = await Networking.FetchFromServer(`/getResult/${jobId}`); - const resultResponseJson = JSON.parse(resultResponse); - if (resultResponseJson.status === 'completed') { - console.log('Result here:', resultResponseJson); - result = resultResponseJson; - break; - } + // Existing document processing logic remains unchanged + console.log('Processing regular document...'); + const { jobId } = await Networking.PostToServer('/createDocument', { file_path: local_file_path }); - // Fetch progress information and update the progress callback. - const progressResponse = await Networking.FetchFromServer(`/getProgress/${jobId}`); - const progressResponseJson = JSON.parse(progressResponse); - if (progressResponseJson) { - const progress = progressResponseJson.progress; - const step = progressResponseJson.step; - progressCallback(progress, step); - } + while (true) { + await new Promise(resolve => setTimeout(resolve, 2000)); + const resultResponse = await Networking.FetchFromServer(`/getResult/${jobId}`); + const resultResponseJson = JSON.parse(resultResponse); + if (resultResponseJson.status === 'completed') { + result = resultResponseJson; + break; } - if (!result) { - console.error('Error processing document.'); - return; + const progressResponse = await Networking.FetchFromServer(`/getProgress/${jobId}`); + const progressResponseJson = JSON.parse(progressResponse); + if (progressResponseJson) { + progressCallback(progressResponseJson.progress, progressResponseJson.step); } + } + } - // Once completed, process the document and add it to the vectorstore. - console.log('Document JSON:', result); - this.documents.push(result); - await this.indexDocument(result); - console.log(`Document added: ${result.file_name}`); - - // Update document metadata such as summary, purpose, and vectorstore ID. - doc.summary = result.summary; - doc.ai_doc_id = result.doc_id; - this._doc_ids.push(result.doc_id); - doc.ai_purpose = result.purpose; - - if (!doc.vectorstore_id) { - doc.vectorstore_id = JSON.stringify([this._id]); - } else { - doc.vectorstore_id = JSON.stringify(JSON.parse(StrCast(doc.vectorstore_id)).concat([this._id])); - } + // Index the document + await this.indexDocument(result); - if (!doc.chunk_simpl) { - doc.chunk_simpl = JSON.stringify({ chunks: [] }); - } + // Simplify chunks for storage + const simplifiedChunks = result.chunks.map(chunk => ({ + chunkId: chunk.id, + start_time: chunk.metadata.start_time, + end_time: chunk.metadata.end_time, + chunkType: CHUNK_TYPE.TEXT, + text: chunk.metadata.text, + })); + doc.chunk_simpl = JSON.stringify({ chunks: simplifiedChunks }); - // Process each chunk of the document and update the document's chunk_simpl field. - result.chunks.forEach((chunk: RAGChunk) => { - const chunkToAdd = { - chunkId: chunk.id, - startPage: chunk.metadata.start_page, - endPage: chunk.metadata.end_page, - location: chunk.metadata.location, - chunkType: chunk.metadata.type as CHUNK_TYPE, - text: chunk.metadata.text, - }; - const new_chunk_simpl = JSON.parse(StrCast(doc.chunk_simpl)); - new_chunk_simpl.chunks = new_chunk_simpl.chunks.concat(chunkToAdd); - doc.chunk_simpl = JSON.stringify(new_chunk_simpl); - }); + // Preserve existing metadata updates + if (!doc.vectorstore_id) { + doc.vectorstore_id = JSON.stringify([this._id]); + } else { + doc.vectorstore_id = JSON.stringify(JSON.parse(StrCast(doc.vectorstore_id)).concat([this._id])); + } - // Mark the document status as completed. - doc.ai_document_status = 'COMPLETED'; - } + if (!doc.chunk_simpl) { + doc.chunk_simpl = JSON.stringify({ chunks: [] }); } + + result.chunks.forEach((chunk: RAGChunk) => { + const chunkToAdd = { + chunkId: chunk.id, + startPage: chunk.metadata.start_page, + endPage: chunk.metadata.end_page, + location: chunk.metadata.location, + chunkType: chunk.metadata.type as CHUNK_TYPE, + text: chunk.metadata.text, + }; + const new_chunk_simpl = JSON.parse(StrCast(doc.chunk_simpl)); + new_chunk_simpl.chunks = new_chunk_simpl.chunks.concat(chunkToAdd); + doc.chunk_simpl = JSON.stringify(new_chunk_simpl); + }); + + console.log(`Document added: ${result.file_name}`); } /** @@ -200,6 +230,39 @@ export class Vectorstore { await this.index.upsert(pineconeRecords); } + /** + * Combines chunks until their combined text is at least 500 words. + * @param chunks The original chunks. + * @returns Combined chunks. + */ + private combineChunks(chunks: RAGChunk[]): RAGChunk[] { + const combinedChunks: RAGChunk[] = []; + let currentChunk: RAGChunk | null = null; + let wordCount = 0; + + chunks.forEach(chunk => { + const textWords = chunk.metadata.text.split(' ').length; + + if (!currentChunk) { + currentChunk = { ...chunk, metadata: { ...chunk.metadata, text: chunk.metadata.text } }; + wordCount = textWords; + } else if (wordCount + textWords >= 500) { + combinedChunks.push(currentChunk); + currentChunk = { ...chunk, metadata: { ...chunk.metadata, text: chunk.metadata.text } }; + wordCount = textWords; + } else { + currentChunk.metadata.text += ` ${chunk.metadata.text}`; + wordCount += textWords; + } + }); + + if (currentChunk) { + combinedChunks.push(currentChunk); + } + + return combinedChunks; + } + /** * Retrieves the top K document chunks relevant to the user's query. * This involves embedding the query using Cohere, then querying Pinecone for matching vectors. diff --git a/src/fields/Types.ts b/src/fields/Types.ts index ef79f72e4..e19673665 100644 --- a/src/fields/Types.ts +++ b/src/fields/Types.ts @@ -5,7 +5,7 @@ import { ProxyField } from './Proxy'; import { RefField } from './RefField'; import { RichTextField } from './RichTextField'; import { ScriptField } from './ScriptField'; -import { CsvField, ImageField, PdfField, WebField } from './URLField'; +import { AudioField, CsvField, ImageField, PdfField, VideoField, WebField } from './URLField'; // eslint-disable-next-line no-use-before-define export type ToConstructor = T extends string ? 'string' : T extends number ? 'number' : T extends boolean ? 'boolean' : T extends List ? ListSpec : new (...args: any[]) => T; @@ -122,6 +122,12 @@ export function CsvCast(field: FieldResult, defaultVal: CsvField | null = null) export function WebCast(field: FieldResult, defaultVal: WebField | null = null) { return Cast(field, WebField, defaultVal); } +export function VideoCast(field: FieldResult, defaultVal: VideoField | null = null) { + return Cast(field, VideoField, defaultVal); +} +export function AudioCast(field: FieldResult, defaultVal: AudioField | null = null) { + return Cast(field, AudioField, defaultVal); +} export function PDFCast(field: FieldResult, defaultVal: PdfField | null = null) { return Cast(field, PdfField, defaultVal); } diff --git a/src/server/ApiManagers/AssistantManager.ts b/src/server/ApiManagers/AssistantManager.ts index 4d2068014..1fd88cbd6 100644 --- a/src/server/ApiManagers/AssistantManager.ts +++ b/src/server/ApiManagers/AssistantManager.ts @@ -24,6 +24,11 @@ import { Method } from '../RouteManager'; import { filesDirectory, publicDirectory } from '../SocketData'; import ApiManager, { Registration } from './ApiManager'; import { getServerPath } from '../../client/util/reportManager/reportManagerUtils'; +import { file } from 'jszip'; +import ffmpegInstaller from '@ffmpeg-installer/ffmpeg'; +import ffmpeg from 'fluent-ffmpeg'; +import OpenAI from 'openai'; +import * as xmlbuilder from 'xmlbuilder'; // Enumeration of directories where different file types are stored export enum Directory { @@ -88,6 +93,7 @@ export default class AssistantManager extends ApiManager { protected initialize(register: Registration): void { // Initialize Google Custom Search API const customsearch = google.customsearch('v1'); + const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); // Register Wikipedia summary API route register({ @@ -197,6 +203,148 @@ export default class AssistantManager extends ApiManager { } }, }); + function convertVideoToAudio(videoPath: string, outputAudioPath: string): Promise { + return new Promise((resolve, reject) => { + const ffmpegProcess = spawn('ffmpeg', [ + '-i', + videoPath, // Input file + '-vn', // No video + '-acodec', + 'pcm_s16le', // Audio codec + '-ac', + '1', // Number of audio channels + '-ar', + '16000', // Audio sampling frequency + '-f', + 'wav', // Output format + outputAudioPath, // Output file + ]); + + ffmpegProcess.on('error', error => { + console.error('Error running ffmpeg:', error); + reject(error); + }); + + ffmpegProcess.on('close', code => { + if (code === 0) { + console.log('Audio extraction complete:', outputAudioPath); + resolve(); + } else { + reject(new Error(`ffmpeg exited with code ${code}`)); + } + }); + }); + } + + register({ + method: Method.POST, + subscription: '/processMediaFile', + secureHandler: async ({ req, res }) => { + const { fileName } = req.body; + + // Ensure the filename is provided + if (!fileName) { + res.status(400).send({ error: 'Filename is required' }); + return; + } + + try { + // Determine the file type and location + const isAudio = fileName.toLowerCase().endsWith('.mp3'); + const directory = isAudio ? Directory.audio : Directory.videos; + const filePath = serverPathToFile(directory, fileName); + + // Check if the file exists + if (!fs.existsSync(filePath)) { + res.status(404).send({ error: 'File not found' }); + return; + } + + console.log(`Processing ${isAudio ? 'audio' : 'video'} file: ${fileName}`); + + // Step 1: Extract audio if it's a video + let audioPath = filePath; + if (!isAudio) { + const audioFileName = `${path.basename(fileName, path.extname(fileName))}.wav`; + audioPath = path.join(pathToDirectory(Directory.audio), audioFileName); + + console.log('Extracting audio from video...'); + await convertVideoToAudio(filePath, audioPath); + } + + // Step 2: Transcribe audio using OpenAI Whisper + console.log('Transcribing audio...'); + const transcription = await openai.audio.transcriptions.create({ + file: fs.createReadStream(audioPath) as any, + model: 'whisper-1', + response_format: 'verbose_json', + timestamp_granularities: ['segment'], + }); + + console.log('Audio transcription complete.'); + + // Step 3: Extract concise JSON + console.log('Extracting concise JSON...'); + const conciseJSON = transcription.segments?.map((segment: any) => ({ + text: segment.text, + start: segment.start, + end: segment.end, + })); + + // Step 4: Combine segments with GPT-4 + console.log('Combining segments with GPT-4...'); + const schema = { + name: 'combine_segments_schema', + schema: { + type: 'object', + properties: { + combined_segments: { + type: 'array', + items: { + type: 'object', + properties: { + text: { type: 'string' }, + start: { type: 'number' }, + end: { type: 'number' }, + }, + required: ['text', 'start', 'end'], + }, + }, + }, + required: ['combined_segments'], + }, + }; + + const completion = await openai.chat.completions.create({ + model: 'gpt-4o-2024-08-06', + messages: [ + { + role: 'system', + content: 'Combine text segments into coherent sections, each between 5 and 10 seconds, based on their content. Return the result as JSON that follows the schema.', + }, + { + role: 'user', + content: JSON.stringify(conciseJSON), + }, + ], + response_format: { + type: 'json_schema', + json_schema: schema, + }, + }); + + const combinedSegments = JSON.parse(completion.choices[0].message?.content ?? '{"combined_segments": []}').combined_segments; + + console.log('Segments combined successfully.'); + + // Step 5: Return the JSON result + res.send(combinedSegments); + } catch (error) { + console.error('Error processing media file:', error); + res.status(500).send({ error: 'Failed to process media file' }); + } + }, + }); // Axios instance with custom headers for scraping const axiosInstance = axios.create({ @@ -314,7 +462,7 @@ export default class AssistantManager extends ApiManager { // Spawn the Python process and track its progress/output // eslint-disable-next-line no-use-before-define - spawnPythonProcess(jobId, file_name, file_data); + spawnPythonProcess(jobId, file_name, public_path); // Send the job ID back to the client for tracking res.send({ jobId }); @@ -388,6 +536,7 @@ export default class AssistantManager extends ApiManager { if (chunk.metadata.type === 'image' || chunk.metadata.type === 'table') { try { const filePath = path.join(pathToDirectory(Directory.chunk_images), chunk.metadata.file_path); // Get the file path + console.log(filePath); readFileAsync(filePath).then(imageBuffer => { const base64Image = imageBuffer.toString('base64'); // Convert the image to base64 @@ -460,7 +609,7 @@ export default class AssistantManager extends ApiManager { } } -function spawnPythonProcess(jobId: string, file_name: string, file_data: string) { +function spawnPythonProcess(jobId: string, file_name: string, file_path: string) { const venvPath = path.join(__dirname, '../chunker/venv'); const requirementsPath = path.join(__dirname, '../chunker/requirements.txt'); const pythonScriptPath = path.join(__dirname, '../chunker/pdf_chunker.py'); @@ -470,7 +619,7 @@ function spawnPythonProcess(jobId: string, file_name: string, file_data: string) function runPythonScript() { const pythonPath = process.platform === 'win32' ? path.join(venvPath, 'Scripts', 'python') : path.join(venvPath, 'bin', 'python3'); - const pythonProcess = spawn(pythonPath, [pythonScriptPath, jobId, file_name, file_data, outputDirectory]); + const pythonProcess = spawn(pythonPath, [pythonScriptPath, jobId, file_path, outputDirectory]); let pythonOutput = ''; let stderrOutput = ''; @@ -593,3 +742,6 @@ function spawnPythonProcess(jobId: string, file_name: string, file_data: string) runPythonScript(); } } +function customFfmpeg(filePath: string) { + throw new Error('Function not implemented.'); +} diff --git a/src/server/chunker/pdf_chunker.py b/src/server/chunker/pdf_chunker.py index 48b2dbf97..a9dbcbb0c 100644 --- a/src/server/chunker/pdf_chunker.py +++ b/src/server/chunker/pdf_chunker.py @@ -668,7 +668,7 @@ class Document: Represents a document being processed, such as a PDF, handling chunking, embedding, and summarization. """ - def __init__(self, file_data: bytes, file_name: str, job_id: str, output_folder: str): + def __init__(self, file_path: str, file_name: str, job_id: str, output_folder: str): """ Initialize the Document with file data, file name, and job ID. @@ -677,8 +677,8 @@ class Document: :param job_id: The job ID associated with this document processing task. """ self.output_folder = output_folder - self.file_data = file_data self.file_name = file_name + self.file_path = file_path self.job_id = job_id self.type = self._get_document_type(file_name) # Determine the document type (PDF, CSV, etc.) self.doc_id = job_id # Use the job ID as the document ID @@ -691,13 +691,23 @@ class Document: """ Process the document: extract chunks, embed them, and generate a summary. """ + with open(self.file_path, 'rb') as file: + pdf_data = file.read() pdf_chunker = PDFChunker(output_folder=self.output_folder, doc_id=self.doc_id) # Initialize PDFChunker - self.chunks = asyncio.run(pdf_chunker.chunk_pdf(self.file_data, self.file_name, self.doc_id, self.job_id)) # Extract chunks - - self.num_pages = self._get_pdf_pages() # Get the number of pages in the document + self.chunks = asyncio.run(pdf_chunker.chunk_pdf(pdf_data, os.path.basename(self.file_path), self.doc_id, self.job_id)) # Extract chunks + self.num_pages = self._get_pdf_pages(pdf_data) # Get the number of pages in the document self._embed_chunks() # Embed the text chunks into embeddings self.summary = self._generate_summary() # Generate a summary for the document + def _get_pdf_pages(self, pdf_data: bytes) -> int: + """ + Get the total number of pages in the PDF document. + """ + pdf_file = io.BytesIO(pdf_data) # Convert the file data to an in-memory binary stream + pdf_reader = PdfReader(pdf_file) # Initialize PDF reader + return len(pdf_reader.pages) # Return the number of pages in the PDF + + def _get_document_type(self, file_name: str) -> DocumentType: """ Determine the document type based on its file extension. @@ -712,15 +722,6 @@ class Document: except ValueError: raise FileTypeNotSupportedException(extension) # Raise exception if file type is unsupported - def _get_pdf_pages(self) -> int: - """ - Get the total number of pages in the PDF document. - - :return: The number of pages in the PDF. - """ - pdf_file = io.BytesIO(self.file_data) # Convert the file data to an in-memory binary stream - pdf_reader = PdfReader(pdf_file) # Initialize PDF reader - return len(pdf_reader.pages) # Return the number of pages in the PDF def _embed_chunks(self) -> None: """ @@ -800,39 +801,34 @@ class Document: "doc_id": self.doc_id }, indent=2) # Convert the document's attributes to JSON format -def process_document(file_data, file_name, job_id, output_folder): +def process_document(file_path, job_id, output_folder): """ Top-level function to process a document and return the JSON output. - :param file_data: The binary data of the file being processed. - :param file_name: The name of the file being processed. + :param file_path: The path to the file being processed. :param job_id: The job ID for this document processing task. :return: The processed document's data in JSON format. """ - new_document = Document(file_data, file_name, job_id, output_folder) + new_document = Document(file_path, file_path, job_id, output_folder) return new_document.to_json() def main(): """ Main entry point for the script, called with arguments from Node.js. """ - if len(sys.argv) != 5: + if len(sys.argv) != 4: print(json.dumps({"error": "Invalid arguments"}), file=sys.stderr) return job_id = sys.argv[1] - file_name = sys.argv[2] - file_data = sys.argv[3] - output_folder = sys.argv[4] # Get the output folder from arguments + file_path = sys.argv[2] + output_folder = sys.argv[3] # Get the output folder from arguments try: os.makedirs(output_folder, exist_ok=True) - - # Decode the base64 file data - file_bytes = base64.b64decode(file_data) - + # Process the document - document_result = process_document(file_bytes, file_name, job_id, output_folder) # Pass output_folder + document_result = process_document(file_path, job_id, output_folder) # Pass output_folder # Output the final result as JSON to stdout print(document_result) @@ -843,7 +839,5 @@ def main(): print(json.dumps({"error": str(e)}), file=sys.stderr) sys.stderr.flush() - - if __name__ == "__main__": - main() # Execute the main function when the script is run + main() # Execute the main function when the script is run \ No newline at end of file -- cgit v1.2.3-70-g09d2 From 57e3c9b9977228a561e8972a469a67f17f4bcd9c Mon Sep 17 00:00:00 2001 From: "A.J. Shulman" Date: Wed, 18 Dec 2024 20:34:33 -0500 Subject: trying new image generation plus new implementaion of video and audio --- src/client/documents/Documents.ts | 4 +- src/client/util/LinkManager.ts | 4 +- .../views/nodes/chatbot/agentsystem/Agent.ts | 10 +- .../nodes/chatbot/chatboxcomponents/ChatBox.tsx | 137 ++++++++--- .../views/nodes/chatbot/tools/CreateAnyDocTool.ts | 12 +- .../views/nodes/chatbot/tools/ImageCreationTool.ts | 74 ++++++ src/client/views/nodes/chatbot/types/types.ts | 3 + .../views/nodes/chatbot/vectorstore/Vectorstore.ts | 256 ++++++++++++--------- src/server/ApiManagers/AssistantManager.ts | 165 +++++++++---- 9 files changed, 462 insertions(+), 203 deletions(-) create mode 100644 src/client/views/nodes/chatbot/tools/ImageCreationTool.ts (limited to 'src/server/ApiManagers') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index e539e3c65..52cd36401 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -826,8 +826,8 @@ export namespace Docs { ...options, }); } - export function DiagramDocument(options: DocumentOptions = { title: '' }) { - return InstanceFromProto(Prototypes.get(DocumentType.DIAGRAM), undefined, options); + export function DiagramDocument(data?: string, options: DocumentOptions = { title: '' }) { + return InstanceFromProto(Prototypes.get(DocumentType.DIAGRAM), data, options); } export function AudioDocument(url: string, options: DocumentOptions = {}, overwriteDoc?: Doc) { diff --git a/src/client/util/LinkManager.ts b/src/client/util/LinkManager.ts index e11482572..d04d41968 100644 --- a/src/client/util/LinkManager.ts +++ b/src/client/util/LinkManager.ts @@ -257,10 +257,10 @@ export function UPDATE_SERVER_CACHE() { cacheDocumentIds = newCacheUpdate; // print out cached docs - Doc.MyDockedBtns.linearView_IsOpen && console.log('Set cached docs = '); + //Doc.MyDockedBtns.linearView_IsOpen && console.log('Set cached docs = '); const isFiltered = filtered.filter(doc => !Doc.IsSystem(doc)); const strings = isFiltered.map(doc => StrCast(doc.title) + ' ' + (Doc.IsDataProto(doc) ? '(data)' : '(embedding)')); - Doc.MyDockedBtns.linearView_IsOpen && strings.sort().forEach((str, i) => console.log(i.toString() + ' ' + str)); + //Doc.MyDockedBtns.linearView_IsOpen && strings.sort().forEach((str, i) => console.log(i.toString() + ' ' + str)); rp.post(ClientUtils.prepend('/setCacheDocumentIds'), { body: { diff --git a/src/client/views/nodes/chatbot/agentsystem/Agent.ts b/src/client/views/nodes/chatbot/agentsystem/Agent.ts index 3c8b30125..1eb5e3963 100644 --- a/src/client/views/nodes/chatbot/agentsystem/Agent.ts +++ b/src/client/views/nodes/chatbot/agentsystem/Agent.ts @@ -20,6 +20,7 @@ import { Parameter, ParametersType, TypeMap } from '../types/tool_types'; import { CreateTextDocTool } from '../tools/CreateTextDocumentTool'; import { DocumentOptions } from '../../../../documents/Documents'; import { CreateAnyDocumentTool } from '../tools/CreateAnyDocTool'; +import { ImageCreationTool } from '../tools/ImageCreationTool'; dotenv.config(); @@ -73,12 +74,13 @@ export class Agent { calculate: new CalculateTool(), rag: new RAGTool(this.vectorstore), dataAnalysis: new DataAnalysisTool(csvData), - websiteInfoScraper: new WebsiteInfoScraperTool(addLinkedUrlDoc), - searchTool: new SearchTool(addLinkedUrlDoc), + //websiteInfoScraper: new WebsiteInfoScraperTool(addLinkedUrlDoc), + //searchTool: new SearchTool(addLinkedUrlDoc), createCSV: new CreateCSVTool(createCSVInDash), noTool: new NoTool(), - createTextDoc: new CreateTextDocTool(addLinkedDoc), - //createAnyDocument: new CreateAnyDocumentTool(addLinkedDoc), + imageCreationTool: new ImageCreationTool(addLinkedDoc), + //createTextDoc: new CreateTextDocTool(addLinkedDoc), + createAnyDocument: new CreateAnyDocumentTool(addLinkedDoc), }; } diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx index b22f2455e..baa4ad521 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx @@ -34,6 +34,11 @@ import './ChatBox.scss'; import MessageComponentBox from './MessageComponent'; import { ProgressBar } from './ProgressBar'; import { RichTextField } from '../../../../../fields/RichTextField'; +import { VideoBox } from '../../VideoBox'; +import { AudioBox } from '../../AudioBox'; +import { DiagramBox } from '../../DiagramBox'; +import { ImageField } from '../../../../../fields/URLField'; +import { DashUploadUtils } from '../../../../../server/DashUploadUtils'; dotenv.config(); @@ -402,13 +407,15 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { */ @action createDocInDash = async (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => { - let doc; + let doc: Doc; switch (doc_type.toLowerCase()) { case 'text': doc = Docs.Create.TextDocument(data || '', options); break; case 'image': + console.log('imageURL: ' + data); + //DashUploadUtils.UploadImage(data!); doc = Docs.Create.ImageDocument(data || '', options); break; case 'pdf': @@ -417,6 +424,13 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { case 'video': doc = Docs.Create.VideoDocument(data || '', options); break; + case 'mermaid_diagram': + doc = Docs.Create.DiagramDocument(data, options); + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => { + const firstView = Array.from(doc[DocViews])[0] as DocumentView; + (firstView.ComponentView as DiagramBox)?.renderMermaid?.(data!); + }); + break; case 'audio': doc = Docs.Create.AudioDocument(data || '', options); break; @@ -426,12 +440,10 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { case 'equation': doc = Docs.Create.EquationDocument(data || '', options); break; - case 'functionplot': case 'function_plot': doc = Docs.Create.FunctionPlotDocument([], options); break; case 'dataviz': - case 'data_viz': const { fileUrl, id } = await Networking.PostToServer('/createCSV', { filename: (options.title as string).replace(/\s+/g, '') + '.csv', data: data, @@ -467,12 +479,13 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { if (foundChunk) { // Handle media chunks specifically - if (foundChunk.chunkType === CHUNK_TYPE.MEDIA) { - const directMatchSegment = this.getDirectMatchingSegment(doc, citation.direct_text || ''); - if (directMatchSegment) { + if (doc.ai_type == 'video' || doc.ai_type == 'audio') { + const directMatchSegmentStart = this.getDirectMatchingSegmentStart(doc, citation.direct_text || '', foundChunk.indexes || []); + + if (directMatchSegmentStart) { // Navigate to the segment's start time in the media player - await this.goToMediaTimestamp(doc, directMatchSegment.start_time); + await this.goToMediaTimestamp(doc, directMatchSegmentStart, doc.ai_type); } else { console.error('No direct matching segment found for the citation.'); } @@ -485,29 +498,53 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { } }; - /** - * Finds the first segment with a direct match to the citation text. - * A match occurs if the segment's text is a subset of the citation's direct text or vice versa. - * @param doc The document containing media metadata. - * @param citationText The citation text to find a matching segment for. - * @returns The segment with the direct match or null if no match is found. - */ - getDirectMatchingSegment = (doc: Doc, citationText: string): { start_time: number; end_time: number; text: string } | null => { - const mediaMetadata = JSON.parse(StrCast(doc.segments)); // Assuming segments are stored in metadata + getDirectMatchingSegmentStart = (doc: Doc, citationText: string, indexesOfSegments: string[]): number => { + const originalSegments = JSON.parse(StrCast(doc.original_segments!)).map((segment: any, index: number) => ({ + index: index.toString(), + text: segment.text, + start: segment.start, + end: segment.end, + })); - if (!Array.isArray(mediaMetadata) || mediaMetadata.length === 0) { - return null; + if (!Array.isArray(originalSegments) || originalSegments.length === 0 || !Array.isArray(indexesOfSegments)) { + return 0; } - for (const segment of mediaMetadata) { - const segmentText = segment.text || ''; - // Check if the segment's text is a subset of the citation text or vice versa - if (citationText.includes(segmentText) || segmentText.includes(citationText)) { - return segment; // Return the first matching segment + // Create itemsToSearch array based on indexesOfSegments + const itemsToSearch = indexesOfSegments.map((indexStr: string) => { + const index = parseInt(indexStr, 10); + const segment = originalSegments[index]; + return { text: segment.text, start: segment.start }; + }); + + console.log('Constructed itemsToSearch:', itemsToSearch); + + // Helper function to calculate word overlap score + const calculateWordOverlap = (text1: string, text2: string): number => { + const words1 = new Set(text1.toLowerCase().split(/\W+/)); + const words2 = new Set(text2.toLowerCase().split(/\W+/)); + const intersection = new Set([...words1].filter(word => words2.has(word))); + return intersection.size / Math.max(words1.size, words2.size); // Jaccard similarity + }; + + // Search for the best matching segment + let bestMatchStart = 0; + let bestScore = 0; + + console.log(`Searching for best match for query: "${citationText}"`); + itemsToSearch.forEach(item => { + const score = calculateWordOverlap(citationText, item.text); + console.log(`Comparing query to segment: "${item.text}" | Score: ${score}`); + if (score > bestScore) { + bestScore = score; + bestMatchStart = item.start; } - } + }); - return null; // No match found + console.log('Best match found with score:', bestScore, '| Start time:', bestMatchStart); + + // Return the start time of the best match + return bestMatchStart; }; /** @@ -515,15 +552,20 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { * @param doc The document containing the media file. * @param timestamp The timestamp to navigate to. */ - goToMediaTimestamp = async (doc: Doc, timestamp: number) => { + goToMediaTimestamp = async (doc: Doc, timestamp: number, type: 'video' | 'audio') => { try { // Show the media document in the viewer - await DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }); - - // Simulate navigation to the timestamp - const firstView = Array.from(doc[DocViews])[0] as DocumentView; - (firstView.ComponentView as any)?.gotoTimestamp?.(timestamp); - + if (type == 'video') { + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => { + const firstView = Array.from(doc[DocViews])[0] as DocumentView; + (firstView.ComponentView as VideoBox)?.Seek?.(timestamp); + }); + } else { + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => { + const firstView = Array.from(doc[DocViews])[0] as DocumentView; + (firstView.ComponentView as AudioBox)?.playFrom?.(timestamp); + }); + } console.log(`Navigated to timestamp: ${timestamp}s in document ${doc.id}`); } catch (error) { console.error('Error navigating to media timestamp:', error); @@ -538,6 +580,32 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { */ handleOtherChunkTypes = (foundChunk: SimplifiedChunk, citation: Citation, doc: Doc) => { switch (foundChunk.chunkType) { + case CHUNK_TYPE.IMAGE: + case CHUNK_TYPE.TABLE: + { + const values = foundChunk.location?.replace(/[[\]]/g, '').split(','); + + if (values?.length !== 4) { + console.error('Location string must contain exactly 4 numbers'); + return; + } + if (foundChunk.startPage === undefined || foundChunk.endPage === undefined) { + DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); + return; + } + const x1 = parseFloat(values[0]) * Doc.NativeWidth(doc); + const y1 = parseFloat(values[1]) * Doc.NativeHeight(doc) + foundChunk.startPage * Doc.NativeHeight(doc); + const x2 = parseFloat(values[2]) * Doc.NativeWidth(doc); + const y2 = parseFloat(values[3]) * Doc.NativeHeight(doc) + foundChunk.startPage * Doc.NativeHeight(doc); + + const annotationKey = Doc.LayoutFieldKey(doc) + '_annotations'; + + const existingDoc = DocListCast(doc[DocData][annotationKey]).find(d => d.citation_id === citation.citation_id); + const highlightDoc = existingDoc ?? this.createImageCitationHighlight(x1, y1, x2, y2, citation, annotationKey, doc); + + DocumentManager.Instance.showDocument(highlightDoc, { willZoomCentered: true }, () => {}); + } + break; case CHUNK_TYPE.TEXT: this.citationPopup = { text: citation.direct_text ?? 'No text available', visible: true }; setTimeout(() => (this.citationPopup.visible = false), 3000); @@ -686,7 +754,10 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { .map(d => DocCast(LinkManager.getOppositeAnchor(d, this.Document))) .map(d => DocCast(d?.annotationOn, d)) .filter(d => d) - .filter(d => d.ai_doc_id) + .filter(d => { + console.log(d.ai_doc_id); + return d.ai_doc_id; + }) .map(d => StrCast(d.ai_doc_id)); } diff --git a/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts b/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts index a4871f7fd..4c059177b 100644 --- a/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts +++ b/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts @@ -7,8 +7,8 @@ import { DocumentOptions, Docs } from '../../../../documents/Documents'; /** * List of supported document types that can be created via text LLM. */ -type supportedDocumentTypesType = 'text' | 'html' | 'equation' | 'functionPlot' | 'dataviz' | 'noteTaking' | 'rtf' | 'message'; -const supportedDocumentTypes: supportedDocumentTypesType[] = ['text', 'html', 'equation', 'functionPlot', 'dataviz', 'noteTaking', 'rtf', 'message']; +type supportedDocumentTypesType = 'text' | 'html' | 'equation' | 'function_plot' | 'dataviz' | 'note_taking' | 'rtf' | 'message' | 'mermaid_diagram'; +const supportedDocumentTypes: supportedDocumentTypesType[] = ['text', 'html', 'equation', 'function_plot', 'dataviz', 'note_taking', 'rtf', 'message', 'mermaid_diagram']; /** * Description of document options and data field for each type. @@ -26,7 +26,7 @@ const documentTypesInfo = { options: ['title', 'backgroundColor', 'fontColor', 'layout'], dataDescription: 'The equation content as a string.', }, - functionPlot: { + function_plot: { options: ['title', 'backgroundColor', 'layout', 'function_definition'], dataDescription: 'The function definition(s) for plotting. Provide as a string or array of function definitions.', }, @@ -34,7 +34,7 @@ const documentTypesInfo = { options: ['title', 'backgroundColor', 'layout', 'chartType'], dataDescription: 'A string of comma-separated values representing the CSV data.', }, - noteTaking: { + note_taking: { options: ['title', 'backgroundColor', 'layout'], dataDescription: 'The initial content or structure for note-taking.', }, @@ -46,6 +46,10 @@ const documentTypesInfo = { options: ['title', 'backgroundColor', 'layout'], dataDescription: 'The message content of the document.', }, + mermaid_diagram: { + options: ['title', 'backgroundColor', 'layout'], + dataDescription: 'The Mermaid diagram content.', + }, }; const createAnyDocumentToolParams = [ diff --git a/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts b/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts new file mode 100644 index 000000000..cf9e8cfc8 --- /dev/null +++ b/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts @@ -0,0 +1,74 @@ +import { v4 as uuidv4 } from 'uuid'; +import { Networking } from '../../../../Network'; +import { BaseTool } from './BaseTool'; +import { Observation } from '../types/types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; +import { DocumentOptions } from '../../../../documents/Documents'; + +const imageCreationToolParams = [ + { + name: 'image_prompt', + type: 'string', + description: 'The prompt for the image to be created. This should be a string that describes the image to be created in extreme detail for an AI image generator.', + required: true, + }, +] as const; + +type ImageCreationToolParamsType = typeof imageCreationToolParams; + +const imageCreationToolInfo: ToolInfo = { + name: 'imageCreationTool', + citationRules: 'No citation needed. Cannot cite image generation for a response.', + parameterRules: imageCreationToolParams, + description: 'Create an image of any style, content, or design, based on a prompt. The prompt should be a detailed description of the image to be created.', +}; + +export class ImageCreationTool extends BaseTool { + private _addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void; + constructor(addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void) { + super(imageCreationToolInfo); + this._addLinkedDoc = addLinkedDoc; + } + + async execute(args: ParametersType): Promise { + const image_prompt = args.image_prompt; + + console.log(`Generating image for prompt: ${image_prompt}`); + // Create an array of promises, each one handling a search for a query + try { + try { + const { image_url } = await Networking.PostToServer('/generateImage', { + image_prompt, + }); + if (res) { + const result = await Networking.PostToServer('/uploadRemoteImage', { sources: res }); + const source = ClientUtils.prepend(result[0].accessPaths.agnostic.client); + return source; + } + } catch (e) { + console.log(e); + } + + const { base64_data, image_path } = await Networking.PostToServer('/generateImage', { + image_prompt, + }); + const id = uuidv4(); + + this._addLinkedDoc('image', image_path, {}, id); + return [ + { + type: 'image_url', + image_url: { url: `data:image/jpeg;base64,${base64_data}` }, + }, + ]; + } catch (error) { + console.log(error); + return [ + { + type: 'text', + text: `An error occurred while generating image.`, + }, + ]; + } + } +} diff --git a/src/client/views/nodes/chatbot/types/types.ts b/src/client/views/nodes/chatbot/types/types.ts index c15ae4c6e..54fd7c979 100644 --- a/src/client/views/nodes/chatbot/types/types.ts +++ b/src/client/views/nodes/chatbot/types/types.ts @@ -1,3 +1,4 @@ +import { indexes } from 'd3'; import { AnyLayer } from 'react-map-gl'; export enum ASSISTANT_ROLE { @@ -95,6 +96,7 @@ export interface RAGChunk { page_height?: number | undefined; start_time?: number | undefined; end_time?: number | undefined; + indexes?: string[] | undefined; }; } @@ -107,6 +109,7 @@ export interface SimplifiedChunk { url?: string; start_time?: number; end_time?: number; + indexes?: string[]; } export interface AI_Document { diff --git a/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts b/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts index af27ebe80..3ed433778 100644 --- a/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts +++ b/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts @@ -15,6 +15,7 @@ import { Networking } from '../../../../Network'; import { AI_Document, CHUNK_TYPE, RAGChunk } from '../types/types'; import path from 'path'; import { v4 as uuidv4 } from 'uuid'; +import { indexes } from 'd3'; dotenv.config(); @@ -28,7 +29,7 @@ export class Vectorstore { private cohere: CohereClient; // Cohere client for generating embeddings. private indexName: string = 'pdf-chatbot'; // Default name for the index. private _id: string; // Unique ID for the Vectorstore instance. - private _doc_ids: string[] = []; // List of document IDs handled by this instance. + private _doc_ids: () => string[]; // List of document IDs handled by this instance. documents: AI_Document[] = []; // Store the documents indexed in the vectorstore. @@ -48,7 +49,7 @@ export class Vectorstore { this.pinecone = new Pinecone({ apiKey: pineconeApiKey }); this.cohere = new CohereClient({ token: process.env.COHERE_API_KEY }); this._id = id; - this._doc_ids = doc_ids(); + this._doc_ids = doc_ids; this.initializeIndex(); } @@ -85,131 +86,155 @@ export class Vectorstore { * @param progressCallback Callback to track progress. */ async addAIDoc(doc: Doc, progressCallback: (progress: number, step: string) => void) { - const local_file_path: string = CsvCast(doc.data)?.url?.pathname ?? PDFCast(doc.data)?.url?.pathname ?? VideoCast(doc.data)?.url?.pathname ?? AudioCast(doc.data)?.url?.pathname; - - if (!local_file_path) { - throw new Error('Invalid file path.'); - } - - const isAudioOrVideo = local_file_path.endsWith('.mp3') || local_file_path.endsWith('.mp4'); - let result: AI_Document & { doc_id: string }; - - if (isAudioOrVideo) { - console.log('Processing media file...'); - const response = await Networking.PostToServer('/processMediaFile', { fileName: path.basename(local_file_path) }); - const segmentedTranscript = response; + const ai_document_status: string = StrCast(doc.ai_document_status); + + // Skip if the document is already in progress or completed. + if (ai_document_status !== undefined && ai_document_status.trim() !== '' && ai_document_status !== '{}') { + if (ai_document_status === 'PROGRESS') { + console.log('Already in progress.'); + return; + } else if (ai_document_status === 'COMPLETED') { + console.log('Already completed.'); + return; + } + } else { + // Start processing the document. + doc.ai_document_status = 'PROGRESS'; + const local_file_path: string = CsvCast(doc.data)?.url?.pathname ?? PDFCast(doc.data)?.url?.pathname ?? VideoCast(doc.data)?.url?.pathname ?? AudioCast(doc.data)?.url?.pathname; - // Generate embeddings for each chunk - const texts = segmentedTranscript.map((chunk: any) => chunk.text); + if (!local_file_path) { + console.log('Invalid file path.'); + return; + } - try { - const embeddingsResponse = await this.cohere.v2.embed({ - model: 'embed-english-v3.0', - inputType: 'classification', - embeddingTypes: ['float'], // Specify that embeddings should be floats - texts, // Pass the array of chunk texts - }); + const isAudioOrVideo = local_file_path.endsWith('.mp3') || local_file_path.endsWith('.mp4'); + let result: AI_Document & { doc_id: string }; + if (isAudioOrVideo) { + console.log('Processing media file...'); + const response = await Networking.PostToServer('/processMediaFile', { fileName: path.basename(local_file_path) }); + const segmentedTranscript = response.condensed; + console.log(segmentedTranscript); + const summary = response.summary; + doc.summary = summary; + // Generate embeddings for each chunk + const texts = segmentedTranscript.map((chunk: any) => chunk.text); + + try { + const embeddingsResponse = await this.cohere.v2.embed({ + model: 'embed-english-v3.0', + inputType: 'classification', + embeddingTypes: ['float'], // Specify that embeddings should be floats + texts, // Pass the array of chunk texts + }); + + if (!embeddingsResponse.embeddings.float || embeddingsResponse.embeddings.float.length !== texts.length) { + throw new Error('Mismatch between embeddings and the number of chunks'); + } - if (!embeddingsResponse.embeddings.float || embeddingsResponse.embeddings.float.length !== texts.length) { - throw new Error('Mismatch between embeddings and the number of chunks'); + // Assign embeddings to each chunk + segmentedTranscript.forEach((chunk: any, index: number) => { + if (!embeddingsResponse.embeddings || !embeddingsResponse.embeddings.float) { + throw new Error('Invalid embeddings response'); + } + }); + doc.original_segments = JSON.stringify(response.full); + doc.ai_type = local_file_path.endsWith('.mp3') ? 'audio' : 'video'; + const doc_id = uuidv4(); + + // Add transcript and embeddings to metadata + result = { + doc_id, + purpose: '', + file_name: local_file_path, + num_pages: 0, + summary: '', + chunks: segmentedTranscript.map((chunk: any, index: number) => ({ + id: uuidv4(), + values: (embeddingsResponse.embeddings.float as number[][])[index], // Assign embedding + metadata: { + indexes: chunk.indexes, + original_document: local_file_path, + doc_id: doc_id, + file_path: local_file_path, + start_time: chunk.start, + end_time: chunk.end, + text: chunk.text, + chunkType: 'text', + }, + })), + type: 'media', + }; + } catch (error) { + console.error('Error generating embeddings:', error); + throw new Error('Embedding generation failed'); } - // Assign embeddings to each chunk - segmentedTranscript.forEach((chunk: any, index: number) => { - if (!embeddingsResponse.embeddings || !embeddingsResponse.embeddings.float) { - throw new Error('Invalid embeddings response'); + doc.segmented_transcript = JSON.stringify(segmentedTranscript); + // Simplify chunks for storage + const simplifiedChunks = result.chunks.map(chunk => ({ + chunkId: chunk.id, + start_time: chunk.metadata.start_time, + end_time: chunk.metadata.end_time, + indexes: chunk.metadata.indexes, + chunkType: CHUNK_TYPE.TEXT, + text: chunk.metadata.text, + })); + doc.chunk_simpl = JSON.stringify({ chunks: simplifiedChunks }); + } else { + // Existing document processing logic remains unchanged + console.log('Processing regular document...'); + const { jobId } = await Networking.PostToServer('/createDocument', { file_path: local_file_path }); + + while (true) { + await new Promise(resolve => setTimeout(resolve, 2000)); + const resultResponse = await Networking.FetchFromServer(`/getResult/${jobId}`); + const resultResponseJson = JSON.parse(resultResponse); + if (resultResponseJson.status === 'completed') { + result = resultResponseJson; + break; + } + const progressResponse = await Networking.FetchFromServer(`/getProgress/${jobId}`); + const progressResponseJson = JSON.parse(progressResponse); + if (progressResponseJson) { + progressCallback(progressResponseJson.progress, progressResponseJson.step); } - //chunk.embedding = embeddingsResponse.embeddings.float[index]; - }); - - // Add transcript and embeddings to metadata - result = { - purpose: '', - file_name: path.basename(local_file_path), - num_pages: 0, - summary: '', - chunks: segmentedTranscript.map((chunk: any, index: number) => ({ - id: uuidv4(), - values: (embeddingsResponse.embeddings.float as number[][])[index], // Assign embedding - metadata: { - ...chunk, - original_document: doc.id, - doc_id: doc.id, - file_path: local_file_path, - start_time: chunk.start, - end_time: chunk.end, - text: chunk.text, - }, - })), - type: 'media', - doc_id: StrCast(doc.id), - }; - } catch (error) { - console.error('Error generating embeddings:', error); - throw new Error('Embedding generation failed'); - } - - doc.segmented_transcript = JSON.stringify(segmentedTranscript); - } else { - // Existing document processing logic remains unchanged - console.log('Processing regular document...'); - const { jobId } = await Networking.PostToServer('/createDocument', { file_path: local_file_path }); - - while (true) { - await new Promise(resolve => setTimeout(resolve, 2000)); - const resultResponse = await Networking.FetchFromServer(`/getResult/${jobId}`); - const resultResponseJson = JSON.parse(resultResponse); - if (resultResponseJson.status === 'completed') { - result = resultResponseJson; - break; } - const progressResponse = await Networking.FetchFromServer(`/getProgress/${jobId}`); - const progressResponseJson = JSON.parse(progressResponse); - if (progressResponseJson) { - progressCallback(progressResponseJson.progress, progressResponseJson.step); + if (!doc.chunk_simpl) { + doc.chunk_simpl = JSON.stringify({ chunks: [] }); } + doc.summary = result.summary; + doc.ai_purpose = result.purpose; + + result.chunks.forEach((chunk: RAGChunk) => { + const chunkToAdd = { + chunkId: chunk.id, + startPage: chunk.metadata.start_page, + endPage: chunk.metadata.end_page, + location: chunk.metadata.location, + chunkType: chunk.metadata.type as CHUNK_TYPE, + text: chunk.metadata.text, + }; + const new_chunk_simpl = JSON.parse(StrCast(doc.chunk_simpl)); + new_chunk_simpl.chunks = new_chunk_simpl.chunks.concat(chunkToAdd); + doc.chunk_simpl = JSON.stringify(new_chunk_simpl); + }); } - } - // Index the document - await this.indexDocument(result); + // Index the document + await this.indexDocument(result); - // Simplify chunks for storage - const simplifiedChunks = result.chunks.map(chunk => ({ - chunkId: chunk.id, - start_time: chunk.metadata.start_time, - end_time: chunk.metadata.end_time, - chunkType: CHUNK_TYPE.TEXT, - text: chunk.metadata.text, - })); - doc.chunk_simpl = JSON.stringify({ chunks: simplifiedChunks }); + // Preserve existing metadata updates + if (!doc.vectorstore_id) { + doc.vectorstore_id = JSON.stringify([this._id]); + } else { + doc.vectorstore_id = JSON.stringify(JSON.parse(StrCast(doc.vectorstore_id)).concat([this._id])); + } - // Preserve existing metadata updates - if (!doc.vectorstore_id) { - doc.vectorstore_id = JSON.stringify([this._id]); - } else { - doc.vectorstore_id = JSON.stringify(JSON.parse(StrCast(doc.vectorstore_id)).concat([this._id])); - } + doc.ai_doc_id = result.doc_id; - if (!doc.chunk_simpl) { - doc.chunk_simpl = JSON.stringify({ chunks: [] }); + console.log(`Document added: ${result.file_name}`); + doc.ai_document_status = 'COMPLETED'; } - - result.chunks.forEach((chunk: RAGChunk) => { - const chunkToAdd = { - chunkId: chunk.id, - startPage: chunk.metadata.start_page, - endPage: chunk.metadata.end_page, - location: chunk.metadata.location, - chunkType: chunk.metadata.type as CHUNK_TYPE, - text: chunk.metadata.text, - }; - const new_chunk_simpl = JSON.parse(StrCast(doc.chunk_simpl)); - new_chunk_simpl.chunks = new_chunk_simpl.chunks.concat(chunkToAdd); - doc.chunk_simpl = JSON.stringify(new_chunk_simpl); - }); - - console.log(`Document added: ${result.file_name}`); } /** @@ -294,17 +319,18 @@ export class Vectorstore { if (!Array.isArray(queryEmbedding)) { throw new Error('Query embedding is not an array'); } - + console.log(this._doc_ids()); // Query the Pinecone index using the embedding and filter by document IDs. const queryResponse: QueryResponse = await this.index.query({ vector: queryEmbedding, filter: { - doc_id: { $in: this._doc_ids }, + doc_id: { $in: this._doc_ids() }, }, topK, includeValues: true, includeMetadata: true, }); + console.log(queryResponse); // Map the results into RAGChunks and return them. return queryResponse.matches.map( diff --git a/src/server/ApiManagers/AssistantManager.ts b/src/server/ApiManagers/AssistantManager.ts index 1fd88cbd6..83bb1b228 100644 --- a/src/server/ApiManagers/AssistantManager.ts +++ b/src/server/ApiManagers/AssistantManager.ts @@ -29,6 +29,7 @@ import ffmpegInstaller from '@ffmpeg-installer/ffmpeg'; import ffmpeg from 'fluent-ffmpeg'; import OpenAI from 'openai'; import * as xmlbuilder from 'xmlbuilder'; +import { last } from 'lodash'; // Enumeration of directories where different file types are stored export enum Directory { @@ -285,60 +286,93 @@ export default class AssistantManager extends ApiManager { // Step 3: Extract concise JSON console.log('Extracting concise JSON...'); - const conciseJSON = transcription.segments?.map((segment: any) => ({ + const originalSegments = transcription.segments?.map((segment: any, index: number) => ({ + index: index.toString(), text: segment.text, start: segment.start, end: segment.end, })); - // Step 4: Combine segments with GPT-4 - console.log('Combining segments with GPT-4...'); - const schema = { - name: 'combine_segments_schema', - schema: { - type: 'object', - properties: { - combined_segments: { - type: 'array', - items: { - type: 'object', - properties: { - text: { type: 'string' }, - start: { type: 'number' }, - end: { type: 'number' }, - }, - required: ['text', 'start', 'end'], - }, - }, - }, - required: ['combined_segments'], - }, - }; - - const completion = await openai.chat.completions.create({ - model: 'gpt-4o-2024-08-06', - messages: [ - { - role: 'system', - content: 'Combine text segments into coherent sections, each between 5 and 10 seconds, based on their content. Return the result as JSON that follows the schema.', - }, - { - role: 'user', - content: JSON.stringify(conciseJSON), - }, - ], - response_format: { - type: 'json_schema', - json_schema: schema, - }, + interface ConciseSegment { + text: string; + indexes: string[]; + start: number | null; + end: number | null; + } + + const combinedSegments = []; + let currentGroup: ConciseSegment = { text: '', indexes: [], start: null, end: null }; + let currentDuration = 0; + + originalSegments?.forEach(segment => { + const segmentDuration = segment.end - segment.start; + + if (currentDuration + segmentDuration <= 4000) { + // Add segment to the current group + currentGroup.text += (currentGroup.text ? ' ' : '') + segment.text; + currentGroup.indexes.push(segment.index); + if (currentGroup.start === null) { + currentGroup.start = segment.start; + } + currentGroup.end = segment.end; + currentDuration += segmentDuration; + } else { + // Push the current group and start a new one + combinedSegments.push({ ...currentGroup }); + currentGroup = { + text: segment.text, + indexes: [segment.index], + start: segment.start, + end: segment.end, + }; + currentDuration = segmentDuration; + } }); - const combinedSegments = JSON.parse(completion.choices[0].message?.content ?? '{"combined_segments": []}').combined_segments; + // Push the final group if it has content + if (currentGroup.text) { + combinedSegments.push({ ...currentGroup }); + } + const lastSegment = combinedSegments[combinedSegments.length - 1]; + + // Check if the last segment is too short and combine it with the second last + if (combinedSegments.length > 1 && lastSegment.end && lastSegment.start) { + const secondLastSegment = combinedSegments[combinedSegments.length - 2]; + const lastDuration = lastSegment.end - lastSegment.start; + + if (lastDuration < 30) { + // Combine the last segment with the second last + secondLastSegment.text += (secondLastSegment.text ? ' ' : '') + lastSegment.text; + secondLastSegment.indexes = secondLastSegment.indexes.concat(lastSegment.indexes); + secondLastSegment.end = lastSegment.end; + + // Remove the last segment from the array + combinedSegments.pop(); + } + } console.log('Segments combined successfully.'); + console.log('Generating summary using GPT-4...'); + const combinedText = combinedSegments.map(segment => segment.text).join(' '); + + let summary = ''; + try { + const completion = await openai.chat.completions.create({ + messages: [{ role: 'system', content: `Summarize the following text in a concise paragraph:\n\n${combinedText}` }], + model: 'gpt-4o', + }); + console.log('Summary generation complete.'); + summary = completion.choices[0].message.content ?? 'Summary could not be generated.'; + } catch (summaryError) { + console.error('Error generating summary:', summaryError); + summary = 'Summary could not be generated.'; + } + // Step 5: Return the JSON result + res.send({ full: originalSegments, condensed: combinedSegments, summary }); + // Step 5: Return the JSON result - res.send(combinedSegments); + res.send({ full: originalSegments, condensed: combinedSegments, summary: summary }); } catch (error) { console.error('Error processing media file:', error); res.status(500).send({ error: 'Failed to process media file' }); @@ -380,6 +414,51 @@ export default class AssistantManager extends ApiManager { } }; + register({ + method: Method.POST, + subscription: '/generateImage', + secureHandler: async ({ req, res }) => { + const { image_prompt } = req.body; + + if (!image_prompt) { + res.status(400).send({ error: 'No prompt provided' }); + return; + } + + try { + const image = await openai.images.generate({ model: 'dall-e-3', prompt: image_prompt, response_format: 'b64_json' }); + console.log(image); + + const base64String = image.data[0].b64_json; + if (!base64String) { + throw new Error('No base64 data received from image generation'); + } + // Generate a UUID for the file to ensure unique naming + const uuidv4 = uuid.v4(); + const fullFilename = `${uuidv4}.jpg`; // Prefix the file name with the UUID + + // Get the full server path where the file will be saved + const serverFilePath = serverPathToFile(Directory.images, fullFilename); + + const binaryData = Buffer.from(base64String, 'base64'); + + // Write the CSV data (which is a raw string) to the file + await writeFileAsync(serverFilePath, binaryData); + + // Construct the client-accessible URL for the file + const fileUrl = clientPathToFile(Directory.images, fullFilename); + + // Send the file URL and UUID back to the client + res.send({ base64_data: base64String, image_path: fileUrl }); + } catch (error) { + console.error('Error fetching the URL:', error); + res.status(500).send({ + error: 'Failed to fetch the URL', + }); + } + }, + }); + // Register a proxy fetch API route register({ method: Method.POST, -- cgit v1.2.3-70-g09d2 From 9b4c554cca11f5c3105085b54646e684dd235f1d Mon Sep 17 00:00:00 2001 From: "A.J. Shulman" Date: Wed, 18 Dec 2024 20:46:27 -0500 Subject: image creation works but is weird --- .../views/nodes/DataVizBox/DocCreatorMenu.tsx | 29 ++++++++------ .../nodes/chatbot/chatboxcomponents/ChatBox.tsx | 21 ++++++++++- .../views/nodes/chatbot/tools/ImageCreationTool.ts | 44 +++++++++++----------- src/server/ApiManagers/AssistantManager.ts | 24 ++---------- 4 files changed, 61 insertions(+), 57 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu.tsx index 16c016d6c..94a37a19f 100644 --- a/src/client/views/nodes/DataVizBox/DocCreatorMenu.tsx +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu.tsx @@ -245,7 +245,7 @@ export class DocCreatorMenu extends ObservableReactComponent { } updateIcons = (docs: Doc[]) => { - console.log('called') + console.log('called'); docs.map(this.getIcon); }; @@ -919,17 +919,17 @@ export class DocCreatorMenu extends ObservableReactComponent { @action setExpandedView = (info: { icon: ImageField; doc: Doc } | undefined) => { if (info) { const doc = info.doc; - const wrapper: Doc = Docs.Create.FreeformDocument([info.doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: ''}); - const newInfo = {icon: new ImageField(''), doc: wrapper} + const wrapper: Doc = Docs.Create.FreeformDocument([info.doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: '' }); + const newInfo = { icon: new ImageField(''), doc: wrapper }; this._expandedPreview = newInfo; } else { this._expandedPreview = info; } }; - get editingWindow(){ + get editingWindow() { const doc = this._expandedPreview?.doc ?? new Doc(); - const rendered = + const rendered = (

{ removeDocument={returnFalse} PanelWidth={() => this._menuDimensions.width - 10} PanelHeight={() => this._menuDimensions.height - 60} - ScreenToLocalTransform={() => new Transform(-this._pageX,-this._pageY, 1)} + ScreenToLocalTransform={() => new Transform(-this._pageX, -this._pageY, 1)} renderDepth={5} whenChildContentsActiveChanged={emptyFunction} focus={emptyFunction} @@ -961,14 +961,21 @@ export class DocCreatorMenu extends ObservableReactComponent { yPadding={0} />
- + ); return (
-
+
{rendered}
-
- ); } @@ -1639,7 +1645,7 @@ export interface FieldOpts { fieldViewType?: 'freeform' | 'stacked'; } -type Field = { +export type Field = { tl: [number, number]; br: [number, number]; opts: FieldOpts; @@ -2359,4 +2365,3 @@ export class FieldUtils { // }] // }; // } - diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx index baa4ad521..e5a90ab4a 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx @@ -39,6 +39,7 @@ import { AudioBox } from '../../AudioBox'; import { DiagramBox } from '../../DiagramBox'; import { ImageField } from '../../../../../fields/URLField'; import { DashUploadUtils } from '../../../../../server/DashUploadUtils'; +import { DocCreatorMenu, Field, FieldUtils } from '../../DataVizBox/DocCreatorMenu'; dotenv.config(); @@ -398,6 +399,23 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { this.addCSVForAnalysis(doc, id); }; + @action + createImageInDash = async (url: string, title: string, id: string, data: string) => { + const doc = FieldUtils.ImageField( + { + tl: [0, 0], + br: [300, 300], + }, + 300, + 300, + title, + url ?? '', + {} + ); + + return doc; + }; + /** * Creates a text document in the dashboard and adds it for analysis. * @param title The title of the doc. @@ -415,8 +433,7 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { break; case 'image': console.log('imageURL: ' + data); - //DashUploadUtils.UploadImage(data!); - doc = Docs.Create.ImageDocument(data || '', options); + doc = await this.createImageInDash(data || '', options.title as string, '', data || ''); break; case 'pdf': doc = Docs.Create.PdfDocument(data || '', options); diff --git a/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts b/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts index cf9e8cfc8..3db401b14 100644 --- a/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts +++ b/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts @@ -4,6 +4,7 @@ import { BaseTool } from './BaseTool'; import { Observation } from '../types/types'; import { ParametersType, ToolInfo } from '../types/tool_types'; import { DocumentOptions } from '../../../../documents/Documents'; +import { ClientUtils } from '../../../../../ClientUtils'; const imageCreationToolParams = [ { @@ -36,31 +37,30 @@ export class ImageCreationTool extends BaseTool { console.log(`Generating image for prompt: ${image_prompt}`); // Create an array of promises, each one handling a search for a query try { - try { - const { image_url } = await Networking.PostToServer('/generateImage', { - image_prompt, - }); - if (res) { - const result = await Networking.PostToServer('/uploadRemoteImage', { sources: res }); - const source = ClientUtils.prepend(result[0].accessPaths.agnostic.client); - return source; - } - } catch (e) { - console.log(e); - } - - const { base64_data, image_path } = await Networking.PostToServer('/generateImage', { + const { url } = await Networking.PostToServer('/generateImage', { image_prompt, }); - const id = uuidv4(); + if (url) { + const result = await Networking.PostToServer('/uploadRemoteImage', { sources: [url] }); + const source = ClientUtils.prepend(result[0].accessPaths.agnostic.client); - this._addLinkedDoc('image', image_path, {}, id); - return [ - { - type: 'image_url', - image_url: { url: `data:image/jpeg;base64,${base64_data}` }, - }, - ]; + const id = uuidv4(); + + this._addLinkedDoc('image', source, {}, id); + return [ + { + type: 'image_url', + image_url: { url }, + }, + ]; + } else { + return [ + { + type: 'text', + text: `An error occurred while generating image.`, + }, + ]; + } } catch (error) { console.log(error); return [ diff --git a/src/server/ApiManagers/AssistantManager.ts b/src/server/ApiManagers/AssistantManager.ts index 83bb1b228..425365348 100644 --- a/src/server/ApiManagers/AssistantManager.ts +++ b/src/server/ApiManagers/AssistantManager.ts @@ -426,30 +426,12 @@ export default class AssistantManager extends ApiManager { } try { - const image = await openai.images.generate({ model: 'dall-e-3', prompt: image_prompt, response_format: 'b64_json' }); + const image = await openai.images.generate({ model: 'dall-e-3', prompt: image_prompt, response_format: 'url' }); console.log(image); - const base64String = image.data[0].b64_json; - if (!base64String) { - throw new Error('No base64 data received from image generation'); - } - // Generate a UUID for the file to ensure unique naming - const uuidv4 = uuid.v4(); - const fullFilename = `${uuidv4}.jpg`; // Prefix the file name with the UUID - - // Get the full server path where the file will be saved - const serverFilePath = serverPathToFile(Directory.images, fullFilename); - - const binaryData = Buffer.from(base64String, 'base64'); + const url = image.data[0].url; - // Write the CSV data (which is a raw string) to the file - await writeFileAsync(serverFilePath, binaryData); - - // Construct the client-accessible URL for the file - const fileUrl = clientPathToFile(Directory.images, fullFilename); - - // Send the file URL and UUID back to the client - res.send({ base64_data: base64String, image_path: fileUrl }); + res.send({ url }); } catch (error) { console.error('Error fetching the URL:', error); res.status(500).send({ -- cgit v1.2.3-70-g09d2 From f915013d2ccfaeb7f04bf8bfea57e6d7d1f66b81 Mon Sep 17 00:00:00 2001 From: "A.J. Shulman" Date: Thu, 19 Dec 2024 11:45:00 -0500 Subject: image generation works better --- .../views/nodes/chatbot/agentsystem/Agent.ts | 11 ++-- .../nodes/chatbot/chatboxcomponents/ChatBox.tsx | 54 +++++++++++------- .../views/nodes/chatbot/tools/CreateAnyDocTool.ts | 8 ++- .../views/nodes/chatbot/tools/DictionaryTool.ts | 64 ++++++++++++++++++++++ .../views/nodes/chatbot/tools/ImageCreationTool.ts | 16 +++--- src/client/views/nodes/chatbot/tools/RAGTool.ts | 6 +- src/client/views/nodes/chatbot/types/types.ts | 1 + .../views/nodes/chatbot/vectorstore/Vectorstore.ts | 4 +- src/server/ApiManagers/AssistantManager.ts | 7 +-- 9 files changed, 130 insertions(+), 41 deletions(-) create mode 100644 src/client/views/nodes/chatbot/tools/DictionaryTool.ts (limited to 'src/server/ApiManagers') diff --git a/src/client/views/nodes/chatbot/agentsystem/Agent.ts b/src/client/views/nodes/chatbot/agentsystem/Agent.ts index 1eb5e3963..1cf6ca030 100644 --- a/src/client/views/nodes/chatbot/agentsystem/Agent.ts +++ b/src/client/views/nodes/chatbot/agentsystem/Agent.ts @@ -21,6 +21,7 @@ import { CreateTextDocTool } from '../tools/CreateTextDocumentTool'; import { DocumentOptions } from '../../../../documents/Documents'; import { CreateAnyDocumentTool } from '../tools/CreateAnyDocTool'; import { ImageCreationTool } from '../tools/ImageCreationTool'; +import { DictionaryTool } from '../tools/DictionaryTool'; dotenv.config(); @@ -60,7 +61,8 @@ export class Agent { csvData: () => { filename: string; id: string; text: string }[], addLinkedUrlDoc: (url: string, id: string) => void, addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void, - createCSVInDash: (url: string, title: string, id: string, data: string) => void + createCSVInDash: (url: string, title: string, id: string, data: string) => void, + createImage: (result: any, options: DocumentOptions) => void ) { // Initialize OpenAI client with API key from environment this.client = new OpenAI({ apiKey: process.env.OPENAI_KEY, dangerouslyAllowBrowser: true }); @@ -74,13 +76,14 @@ export class Agent { calculate: new CalculateTool(), rag: new RAGTool(this.vectorstore), dataAnalysis: new DataAnalysisTool(csvData), - //websiteInfoScraper: new WebsiteInfoScraperTool(addLinkedUrlDoc), - //searchTool: new SearchTool(addLinkedUrlDoc), + websiteInfoScraper: new WebsiteInfoScraperTool(addLinkedUrlDoc), + searchTool: new SearchTool(addLinkedUrlDoc), createCSV: new CreateCSVTool(createCSVInDash), noTool: new NoTool(), - imageCreationTool: new ImageCreationTool(addLinkedDoc), + imageCreationTool: new ImageCreationTool(createImage), //createTextDoc: new CreateTextDocTool(addLinkedDoc), createAnyDocument: new CreateAnyDocumentTool(addLinkedDoc), + dictionary: new DictionaryTool(), }; } diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx index e5a90ab4a..d2931106a 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx @@ -40,6 +40,11 @@ import { DiagramBox } from '../../DiagramBox'; import { ImageField } from '../../../../../fields/URLField'; import { DashUploadUtils } from '../../../../../server/DashUploadUtils'; import { DocCreatorMenu, Field, FieldUtils } from '../../DataVizBox/DocCreatorMenu'; +import { ImageUtils } from '../../../../util/Import & Export/ImageUtils'; +import { ScriptManager } from '../../../../util/ScriptManager'; +import { CompileError, CompileScript } from '../../../../util/Scripting'; +import { ScriptField } from '../../../../../fields/ScriptField'; +import { ScriptingBox } from '../../ScriptingBox'; dotenv.config(); @@ -96,7 +101,7 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { this.vectorstore_id = StrCast(this.dataDoc.vectorstore_id); } this.vectorstore = new Vectorstore(this.vectorstore_id, this.retrieveDocIds); - this.agent = new Agent(this.vectorstore, this.retrieveSummaries, this.retrieveFormattedHistory, this.retrieveCSVData, this.addLinkedUrlDoc, this.createDocInDash, this.createCSVInDash); + this.agent = new Agent(this.vectorstore, this.retrieveSummaries, this.retrieveFormattedHistory, this.retrieveCSVData, this.addLinkedUrlDoc, this.createDocInDash, this.createCSVInDash, this.createImageInDash); this.messagesRef = React.createRef(); // Reaction to update dataDoc when chat history changes @@ -400,20 +405,17 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { }; @action - createImageInDash = async (url: string, title: string, id: string, data: string) => { - const doc = FieldUtils.ImageField( - { - tl: [0, 0], - br: [300, 300], - }, - 300, - 300, - title, - url ?? '', - {} - ); - - return doc; + createImageInDash = async (result: any, options: DocumentOptions) => { + const newImgSrc = + result.accessPaths.agnostic.client.indexOf('dashblobstore') === -1 // + ? ClientUtils.prepend(result.accessPaths.agnostic.client) + : result.accessPaths.agnostic.client; + const doc = Docs.Create.ImageDocument(newImgSrc, options); + this.addDocument(ImageUtils.AssignImgInfo(doc, result)); + const linkDoc = Docs.Create.LinkDocument(this.Document, doc); + LinkManager.Instance.addLink(linkDoc); + doc && this._props.addDocument?.(doc); + await DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => {}); }; /** @@ -431,10 +433,6 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { case 'text': doc = Docs.Create.TextDocument(data || '', options); break; - case 'image': - console.log('imageURL: ' + data); - doc = await this.createImageInDash(data || '', options.title as string, '', data || ''); - break; case 'pdf': doc = Docs.Create.PdfDocument(data || '', options); break; @@ -471,6 +469,24 @@ export class ChatBox extends ViewBoxAnnotatableComponent() { case 'chat': doc = Docs.Create.ChatDocument(options); break; + case 'script': + const result = !data!.trim() ? ({ compiled: false, errors: [] } as CompileError) : CompileScript(data!, {}); + const script_field = result.compiled ? new ScriptField(result, undefined, data!) : undefined; + doc = Docs.Create.ScriptingDocument(script_field, options); + await DocumentManager.Instance.showDocument(doc, { willZoomCentered: true }, () => { + const firstView = Array.from(doc[DocViews])[0] as DocumentView; + (firstView.ComponentView as ScriptingBox)?.onApply?.(); + (firstView.ComponentView as ScriptingBox)?.onRun?.(); + }); + + break; + // this.dataDoc.script = this.rawScript; + + // ScriptManager.Instance.addScript(this.dataDoc); + + // this._scriptKeys = ScriptingGlobals.getGlobals(); + // this._scriptingDescriptions = ScriptingGlobals.getDescriptions(); + // this._scriptingParams = ScriptingGlobals.getParameters(); // Add more cases for other document types default: console.error('Unknown or unsupported document type:', doc_type); diff --git a/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts b/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts index 4c059177b..36f133503 100644 --- a/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts +++ b/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts @@ -7,8 +7,8 @@ import { DocumentOptions, Docs } from '../../../../documents/Documents'; /** * List of supported document types that can be created via text LLM. */ -type supportedDocumentTypesType = 'text' | 'html' | 'equation' | 'function_plot' | 'dataviz' | 'note_taking' | 'rtf' | 'message' | 'mermaid_diagram'; -const supportedDocumentTypes: supportedDocumentTypesType[] = ['text', 'html', 'equation', 'function_plot', 'dataviz', 'note_taking', 'rtf', 'message', 'mermaid_diagram']; +type supportedDocumentTypesType = 'text' | 'html' | 'equation' | 'function_plot' | 'dataviz' | 'note_taking' | 'rtf' | 'message' | 'mermaid_diagram' | 'script'; +const supportedDocumentTypes: supportedDocumentTypesType[] = ['text', 'html', 'equation', 'function_plot', 'dataviz', 'note_taking', 'rtf', 'message', 'mermaid_diagram', 'script']; /** * Description of document options and data field for each type. @@ -50,6 +50,10 @@ const documentTypesInfo = { options: ['title', 'backgroundColor', 'layout'], dataDescription: 'The Mermaid diagram content.', }, + script: { + options: ['title', 'backgroundColor', 'layout'], + dataDescription: 'The compilable JavaScript code. Use this for creating scripts.', + }, }; const createAnyDocumentToolParams = [ diff --git a/src/client/views/nodes/chatbot/tools/DictionaryTool.ts b/src/client/views/nodes/chatbot/tools/DictionaryTool.ts new file mode 100644 index 000000000..fa554e7b3 --- /dev/null +++ b/src/client/views/nodes/chatbot/tools/DictionaryTool.ts @@ -0,0 +1,64 @@ +import { Observation } from '../types/types'; +import { ParametersType, ToolInfo } from '../types/tool_types'; +import { BaseTool } from './BaseTool'; + +// Define the tool's parameters +const dictionaryToolParams = [ + { + name: 'word', + type: 'string', + description: 'The word to look up in the dictionary.', + required: true, + }, +] as const; + +type DictionaryToolParamsType = typeof dictionaryToolParams; + +// Define the tool's metadata and rules +const dictionaryToolInfo: ToolInfo = { + name: 'dictionary', + citationRules: 'No citation needed.', + parameterRules: dictionaryToolParams, + description: 'Fetches the definition of a given word using an open dictionary API.', +}; + +export class DictionaryTool extends BaseTool { + constructor() { + super(dictionaryToolInfo); + } + + async execute(args: ParametersType): Promise { + const url = `https://api.dictionaryapi.dev/api/v2/entries/en/${args.word}`; + + try { + const response = await fetch(url); + const data = await response.json(); + + // Handle cases where the word is not found + if (data.title === 'No Definitions Found') { + return [ + { + type: 'text', + text: `Sorry, I couldn't find a definition for the word "${args.word}".`, + }, + ]; + } + + // Extract the first definition + const definition = data[0]?.meanings[0]?.definitions[0]?.definition; + return [ + { + type: 'text', + text: `The definition of "${args.word}" is: ${definition}`, + }, + ]; + } catch (error) { + return [ + { + type: 'text', + text: `An error occurred while fetching the definition: ${error}`, + }, + ]; + } + } +} diff --git a/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts b/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts index 3db401b14..ba1aa987a 100644 --- a/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts +++ b/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts @@ -5,6 +5,8 @@ import { Observation } from '../types/types'; import { ParametersType, ToolInfo } from '../types/tool_types'; import { DocumentOptions } from '../../../../documents/Documents'; import { ClientUtils } from '../../../../../ClientUtils'; +import { DashUploadUtils } from '../../../../../server/DashUploadUtils'; +import { RTFCast, StrCast } from '../../../../../fields/Types'; const imageCreationToolParams = [ { @@ -25,10 +27,10 @@ const imageCreationToolInfo: ToolInfo = { }; export class ImageCreationTool extends BaseTool { - private _addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void; - constructor(addLinkedDoc: (doc_type: string, data: string | undefined, options: DocumentOptions, id: string) => void) { + private _createImage: (result: any, options: DocumentOptions) => void; + constructor(createImage: (result: any, options: DocumentOptions) => void) { super(imageCreationToolInfo); - this._addLinkedDoc = addLinkedDoc; + this._createImage = createImage; } async execute(args: ParametersType): Promise { @@ -37,16 +39,14 @@ export class ImageCreationTool extends BaseTool { console.log(`Generating image for prompt: ${image_prompt}`); // Create an array of promises, each one handling a search for a query try { - const { url } = await Networking.PostToServer('/generateImage', { + const { result, url } = await Networking.PostToServer('/generateImage', { image_prompt, }); + console.log('Image generation result:', result); + this._createImage(result, { text: RTFCast(image_prompt) }); if (url) { - const result = await Networking.PostToServer('/uploadRemoteImage', { sources: [url] }); - const source = ClientUtils.prepend(result[0].accessPaths.agnostic.client); - const id = uuidv4(); - this._addLinkedDoc('image', source, {}, id); return [ { type: 'image_url', diff --git a/src/client/views/nodes/chatbot/tools/RAGTool.ts b/src/client/views/nodes/chatbot/tools/RAGTool.ts index 1f73986a7..2db61c768 100644 --- a/src/client/views/nodes/chatbot/tools/RAGTool.ts +++ b/src/client/views/nodes/chatbot/tools/RAGTool.ts @@ -23,8 +23,9 @@ const ragToolInfo: ToolInfo = { 1. **Grounded Text Guidelines**: - Each tag must correspond to exactly one citation, ensuring a one-to-one relationship. - Always cite a **subset** of the chunk, never the full text. The citation should be as short as possible while providing the relevant information (typically one to two sentences). - - Do not paraphrase the chunk text in the citation; use the original subset directly from the chunk. + - Do not paraphrase the chunk text in the citation; use the original subset directly from the chunk. IT MUST BE EXACT AND WORD FOR WORD FROM THE ORIGINAL CHUNK! - If multiple citations are needed for different sections of the response, create new tags for each. + - !!!IMPORTANT: For video transcript citations, use a subset of the exact text from the transcript as the citation content. It should be just before the start of the section of the transcript that is relevant to the grounded_text tag. 2. **Citation Guidelines**: - The citation must include only the relevant excerpt from the chunk being referenced. @@ -56,7 +57,8 @@ const ragToolInfo: ToolInfo = { ***NOTE***: - Prefer to cite visual elements (i.e. chart, image, table, etc.) over text, if they both can be used. Only if a visual element is not going to be helpful, then use text. Otherwise, use both! - Use as many citations as possible (even when one would be sufficient), thus keeping text as grounded as possible. - - Cite from as many documents as possible and always use MORE, and as granular, citations as possible.`, + - Cite from as many documents as possible and always use MORE, and as granular, citations as possible. + - CITATION TEXT MUST BE EXACTLY AS IT APPEARS IN THE CHUNK. DO NOT PARAPHRASE!`, parameterRules: ragToolParams, }; diff --git a/src/client/views/nodes/chatbot/types/types.ts b/src/client/views/nodes/chatbot/types/types.ts index 54fd7c979..995ac531d 100644 --- a/src/client/views/nodes/chatbot/types/types.ts +++ b/src/client/views/nodes/chatbot/types/types.ts @@ -19,6 +19,7 @@ export enum CHUNK_TYPE { URL = 'url', CSV = 'CSV', MEDIA = 'media', + VIDEO = 'video', } export enum PROCESSING_TYPE { diff --git a/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts b/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts index 3ed433778..d962b887f 100644 --- a/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts +++ b/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts @@ -159,7 +159,7 @@ export class Vectorstore { start_time: chunk.start, end_time: chunk.end, text: chunk.text, - chunkType: 'text', + type: CHUNK_TYPE.VIDEO, }, })), type: 'media', @@ -176,7 +176,7 @@ export class Vectorstore { start_time: chunk.metadata.start_time, end_time: chunk.metadata.end_time, indexes: chunk.metadata.indexes, - chunkType: CHUNK_TYPE.TEXT, + chunkType: CHUNK_TYPE.VIDEO, text: chunk.metadata.text, })); doc.chunk_simpl = JSON.stringify({ chunks: simplifiedChunks }); diff --git a/src/server/ApiManagers/AssistantManager.ts b/src/server/ApiManagers/AssistantManager.ts index 425365348..fbda74194 100644 --- a/src/server/ApiManagers/AssistantManager.ts +++ b/src/server/ApiManagers/AssistantManager.ts @@ -30,6 +30,7 @@ import ffmpeg from 'fluent-ffmpeg'; import OpenAI from 'openai'; import * as xmlbuilder from 'xmlbuilder'; import { last } from 'lodash'; +import { DashUploadUtils } from '../DashUploadUtils'; // Enumeration of directories where different file types are stored export enum Directory { @@ -370,9 +371,6 @@ export default class AssistantManager extends ApiManager { } // Step 5: Return the JSON result res.send({ full: originalSegments, condensed: combinedSegments, summary }); - - // Step 5: Return the JSON result - res.send({ full: originalSegments, condensed: combinedSegments, summary: summary }); } catch (error) { console.error('Error processing media file:', error); res.status(500).send({ error: 'Failed to process media file' }); @@ -428,10 +426,11 @@ export default class AssistantManager extends ApiManager { try { const image = await openai.images.generate({ model: 'dall-e-3', prompt: image_prompt, response_format: 'url' }); console.log(image); + const result = await DashUploadUtils.UploadImage(image.data[0].url!); const url = image.data[0].url; - res.send({ url }); + res.send({ result, url }); } catch (error) { console.error('Error fetching the URL:', error); res.status(500).send({ -- cgit v1.2.3-70-g09d2 From 0eff48b757ca81860a883d25e147b8a869e5fe00 Mon Sep 17 00:00:00 2001 From: eleanor-park Date: Mon, 30 Dec 2024 23:35:24 -0500 Subject: created image regeneration with dialogue --- src/client/apis/gpt/GPT.ts | 39 +++- src/client/documents/Documents.ts | 4 + src/client/views/PropertiesView.scss | 1 + src/client/views/PropertiesView.tsx | 12 +- .../collectionFreeForm/CollectionFreeFormView.tsx | 22 +-- src/client/views/nodes/ImageBox.tsx | 10 ++ src/client/views/nodes/imageEditor/ImageEditor.tsx | 2 +- src/client/views/pdf/AnchorMenu.tsx | 1 + src/client/views/smartdraw/DrawingFillHandler.tsx | 11 +- src/client/views/smartdraw/SmartDrawHandler.scss | 8 +- src/client/views/smartdraw/SmartDrawHandler.tsx | 197 ++++++++++++++------- src/client/views/smartdraw/StickerPalette.tsx | 1 + src/server/ApiManagers/FireflyManager.ts | 20 ++- src/server/DashUploadUtils.ts | 1 - 14 files changed, 238 insertions(+), 91 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/apis/gpt/GPT.ts b/src/client/apis/gpt/GPT.ts index 03380e4d6..9241eb120 100644 --- a/src/client/apis/gpt/GPT.ts +++ b/src/client/apis/gpt/GPT.ts @@ -249,6 +249,41 @@ const gptHandwriting = async (src: string): Promise => { } }; +const gptDescribeImage = async (image: string): Promise => { + try { + const response = await openai.chat.completions.create({ + model: 'gpt-4o', + temperature: 0, + messages: [ + { + role: 'user', + content: [ + { + type: 'text', + text: `Identify what this drawing is, naming as many elements and their location in the drawing as possible`, + }, + { + type: 'image_url', + image_url: { + url: `${image}`, + detail: 'low', + }, + }, + ], + }, + ], + }); + if (response.choices[0].message.content) { + console.log('GPT DESCRIPTION', response.choices[0].message.content); + return response.choices[0].message.content; + } + return 'Unknown drawing'; + } catch (err) { + console.log(err); + return 'Error connecting with API'; + } +}; + const gptDrawingColor = async (image: string, coords: string[]): Promise => { try { const response = await openai.chat.completions.create({ @@ -276,11 +311,11 @@ const gptDrawingColor = async (image: string, coords: string[]): Promise if (response.choices[0].message.content) { return response.choices[0].message.content; } - return 'Missing labels'; + return 'Unknown drawing'; } catch (err) { console.log(err); return 'Error connecting with API'; } }; -export { gptAPICall, gptImageCall, GPTCallType, gptImageLabel, gptGetEmbedding, gptHandwriting, gptDrawingColor }; +export { gptAPICall, gptImageCall, GPTCallType, gptImageLabel, gptGetEmbedding, gptHandwriting, gptDescribeImage, gptDrawingColor }; diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index c51c1645d..785af3409 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -516,6 +516,10 @@ export class DocumentOptions { card_sort?: STRt = new StrInfo('way cards are sorted in deck view'); card_sort_isDesc?: BOOLt = new BoolInfo('whether the cards are sorted ascending or descending'); + + ai_generated?: boolean; // to mark items as ai generated + firefly_seed?: number; + firefly_prompt?: string; } export const DocOptions = new DocumentOptions(); diff --git a/src/client/views/PropertiesView.scss b/src/client/views/PropertiesView.scss index 693c75ebf..7866e67e7 100644 --- a/src/client/views/PropertiesView.scss +++ b/src/client/views/PropertiesView.scss @@ -642,6 +642,7 @@ .smooth, .color, +.strength-slider, .smooth-slider { margin-top: 7px; } diff --git a/src/client/views/PropertiesView.tsx b/src/client/views/PropertiesView.tsx index aefdeee17..5b24eb7ea 100644 --- a/src/client/views/PropertiesView.tsx +++ b/src/client/views/PropertiesView.tsx @@ -982,6 +982,9 @@ export class PropertiesView extends ObservableReactComponent { + !isNaN(val) && (this.refStrength = val); + }); return (
{!targetDoc.layout_isSvg && this.containsInkDoc && ( @@ -995,9 +998,10 @@ export class PropertiesView extends ObservableReactComponent DrawingFillHandler.drawingToImage(targetDoc, 'fill in the details of this image'), 'createImage')} + onClick={undoable(() => DrawingFillHandler.drawingToImage(targetDoc, this.refStrength, 'fill in the details of this image'), 'createImage')} />
+
{strength}
{ + doc[DocData].drawing_refStrength = Number(value); + }); + } @computed get smoothAmt() { return Number(this.getField('stroke_smoothAmount') || '5'); } // prettier-ignore set smoothAmt(value) { this.selectedStrokes.forEach(doc => { diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index acf72e5cb..4bccdd286 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -1295,6 +1295,7 @@ export class CollectionFreeFormView extends CollectionSubView { - SmartDrawHandler.Instance.CreateDrawingDoc = this.createDrawingDoc; - SmartDrawHandler.Instance.AddDrawing = this.addDrawing; - SmartDrawHandler.Instance.RemoveDrawing = this.removeDrawing; - !SmartDrawHandler.Instance.ShowRegenerate ? SmartDrawHandler.Instance.displayRegenerate(this._downX, this._downY - 10) : SmartDrawHandler.Instance.hideRegenerate(); - }), - icon: 'pen-to-square', - }); + this.layoutDoc.drawingData != undefined && + optionItems.push({ + description: 'Show Drawing Editor', + event: action(() => { + SmartDrawHandler.Instance.CreateDrawingDoc = this.createDrawingDoc; + SmartDrawHandler.Instance.AddDrawing = this.addDrawing; + SmartDrawHandler.Instance.RemoveDrawing = this.removeDrawing; + !SmartDrawHandler.Instance.ShowRegenerate ? SmartDrawHandler.Instance.displayRegenerate(this._downX, this._downY - 10) : SmartDrawHandler.Instance.hideRegenerate(); + }), + icon: 'pen-to-square', + }); optionItems.push({ description: this.Document.savedAsSticker ? 'Sticker Saved!' : 'Save to Stickers', event: action(undoable(async () => await StickerPalette.addToPalette(this.Document), 'save to palette')), diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 25e7b566f..8f6a90e61 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -40,6 +40,7 @@ import { FocusViewOptions } from './FocusViewOptions'; import './ImageBox.scss'; import { OpenWhere } from './OpenWhere'; import { Upload } from '../../../server/SharedMediaTypes'; +import { SmartDrawHandler } from '../smartdraw/SmartDrawHandler'; export class ImageEditorData { // eslint-disable-next-line no-use-before-define @@ -351,6 +352,15 @@ export class ImageBox extends ViewBoxAnnotatableComponent() { }), icon: 'pencil-alt', }); + this.layoutDoc.ai_generated && + funcs.push({ + description: 'Regenerate AI Image', + event: action(() => { + console.log('COOOORDS', this.dataDoc.width as number, this.dataDoc.y as number); + !SmartDrawHandler.Instance.ShowRegenerate ? SmartDrawHandler.Instance.displayRegenerate(this.dataDoc.x as number, (this.dataDoc.y as number) - 10) : SmartDrawHandler.Instance.hideRegenerate(); + }), + icon: 'pen-to-square', + }); funcs.push({ description: this.Document.savedAsSticker ? 'Sticker Saved!' : 'Save to Stickers', event: action(undoable(async () => await StickerPalette.addToPalette(this.Document), 'save to palette')), diff --git a/src/client/views/nodes/imageEditor/ImageEditor.tsx b/src/client/views/nodes/imageEditor/ImageEditor.tsx index a39878924..2a8bc034d 100644 --- a/src/client/views/nodes/imageEditor/ImageEditor.tsx +++ b/src/client/views/nodes/imageEditor/ImageEditor.tsx @@ -411,7 +411,7 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc let finalImgURL: string = url; // crop the image for these brush modes to remove excess blank space around the image contents if (currCutType == CutMode.IN || currCutType == CutMode.DRAW_IN) { - const croppedData = cropImage(image, minX, maxX, minY, maxY); + const croppedData = cropImage(image, Math.max(minX, 0), Math.min(maxX, image.width), Math.max(minY, 0), Math.min(maxY, image.height)); finalImg = croppedData; finalImgURL = croppedData.src; } diff --git a/src/client/views/pdf/AnchorMenu.tsx b/src/client/views/pdf/AnchorMenu.tsx index fe03f32a5..bb8082061 100644 --- a/src/client/views/pdf/AnchorMenu.tsx +++ b/src/client/views/pdf/AnchorMenu.tsx @@ -158,6 +158,7 @@ export class AnchorMenu extends AntimodeMenu { docData.drawingColored = opts.autoColor; docData.drawingSize = opts.size; docData.drawingData = gptRes; + docData.ai_generated = true; }); pointerDown = (e: React.PointerEvent) => { diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index 48e71bc9f..1a470f995 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -1,21 +1,26 @@ +import { imageUrlToBase64 } from '../../../ClientUtils'; import { Doc } from '../../../fields/Doc'; import { ImageCast } from '../../../fields/Types'; import { Upload } from '../../../server/SharedMediaTypes'; +import { gptDescribeImage } from '../../apis/gpt/GPT'; import { Docs } from '../../documents/Documents'; import { Networking } from '../../Network'; import { DocumentView, DocumentViewInternal } from '../nodes/DocumentView'; import { OpenWhere } from '../nodes/OpenWhere'; export class DrawingFillHandler { - static drawingToImage = (drawing: Doc, prompt: string) => + static drawingToImage = (drawing: Doc, strength: number, prompt: string) => DocumentView.GetDocImage(drawing)?.then(imageField => { if (imageField) { const { href } = ImageCast(imageField).url; const hrefParts = href.split('.'); const structureUrl = `${hrefParts.slice(0, -1).join('.')}_o.${hrefParts.lastElement()}`; - const strength: number = 100; - Networking.PostToServer('/queryFireflyImageFromStructure', { prompt, structureUrl, strength }).then((info: Upload.ImageInformation) => + imageUrlToBase64(structureUrl) + .then((hrefBase64: string) => gptDescribeImage(hrefBase64)) + .then((prompt: string) => { + Networking.PostToServer('/queryFireflyImageFromStructure', { prompt, structureUrl, strength }).then((info: Upload.ImageInformation) => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, {}), OpenWhere.addRight)) // prettier-ignore + }); } return false; }); diff --git a/src/client/views/smartdraw/SmartDrawHandler.scss b/src/client/views/smartdraw/SmartDrawHandler.scss index c25273876..513779512 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.scss +++ b/src/client/views/smartdraw/SmartDrawHandler.scss @@ -12,7 +12,13 @@ } } - .smartdraw-options { + .smartdraw-output-options { + display: flex; + flex-direction: row; + justify-content: center; + } + + .smartdraw-svg-options { margin-top: 5px; display: flex; flex-direction: row; diff --git a/src/client/views/smartdraw/SmartDrawHandler.tsx b/src/client/views/smartdraw/SmartDrawHandler.tsx index 036ac5983..fb1a5771e 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.tsx +++ b/src/client/views/smartdraw/SmartDrawHandler.tsx @@ -1,5 +1,5 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { Slider, Switch } from '@mui/material'; +import { Checkbox, Slider, Switch } from '@mui/material'; import { Button, IconButton } from 'browndash-components'; import { action, makeObservable, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; @@ -74,6 +74,8 @@ export class SmartDrawHandler extends ObservableReactComponent { @observable private _autoColor: boolean = true; @observable private _regenInput: string = ''; @observable private _canInteract: boolean = true; + @observable private _generateDrawing: boolean = true; + @observable private _generateImage: boolean = true; @observable public ShowRegenerate: boolean = false; @@ -195,6 +197,7 @@ export class SmartDrawHandler extends ObservableReactComponent { */ @action handleSendClick = async () => { + if (!this._generateImage && !this._generateDrawing) return; this._isLoading = true; this._canInteract = false; if (this.ShowRegenerate) { @@ -212,7 +215,12 @@ export class SmartDrawHandler extends ObservableReactComponent { this._showOptions = false; }); try { - await this.drawWithGPT({ X: this._pageX, Y: this._pageY }, this._userInput, this._complexity, this._size, this._autoColor); + if (this._generateImage) { + await this.createImageWithFirefly(this._userInput); + } + if (this._generateDrawing) { + await this.drawWithGPT({ X: this._pageX, Y: this._pageY }, this._userInput, this._complexity, this._size, this._autoColor); + } this.hideSmartDrawHandler(); runInAction(() => { @@ -240,15 +248,12 @@ export class SmartDrawHandler extends ObservableReactComponent { drawWithGPT = async (startPt: { X: number; Y: number }, input: string, complexity: number, size: number, autoColor: boolean) => { if (input) { this._lastInput = { text: input, complexity: complexity, size: size, autoColor: autoColor, x: startPt.X, y: startPt.Y }; - - Networking.PostToServer('/queryFireflyImage', { prompt: input }).then(img => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(img.accessPaths.agnostic.client, { title: input }), OpenWhere.addRight)); - const res = await gptAPICall(`"${input}", "${complexity}", "${size}"`, GPTCallType.DRAW, undefined, true); if (res) { const strokeData = await this.parseSvg(res, startPt, false, autoColor); const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); - + this._selectedDoc = drawingDoc; this._errorOccurredOnce = false; return strokeData; } else { @@ -258,6 +263,23 @@ export class SmartDrawHandler extends ObservableReactComponent { return undefined; }; + /** + * Calls Firefly API to create an image based on user input + */ + createImageWithFirefly = (input: string, seed?: number) => { + this._lastInput.text = input; + return Networking.PostToServer('/queryFireflyImage', { prompt: input, seed: seed }).then(img => { + const imgDoc: Doc = Docs.Create.ImageDocument(img.accessPaths.agnostic.client, { + title: input.match(/^(.*?)~~~.*$/)?.[1] || input, + ai_generated: true, + firefly_seed: img.accessPaths.agnostic.client.match(/\/(\d+)upload/)[1], + firefly_prompt: input, + }); + DocumentViewInternal.addDocTabFunc(imgDoc, OpenWhere.addRight); + this._selectedDoc = imgDoc; + }); + }; + /** * Regenerates drawings with the option to add a specific regenerate prompt/request. */ @@ -266,27 +288,39 @@ export class SmartDrawHandler extends ObservableReactComponent { if (lastInput) this._lastInput = lastInput; if (lastResponse) this._lastResponse = lastResponse; if (regenInput) this._regenInput = regenInput; - - try { - let res; + if (this._generateDrawing) { + try { + let res; + if (this._regenInput !== '') { + const prompt: string = `This is your previously generated svg code: ${this._lastResponse} for the user input "${this._lastInput.text}". Please regenerate it with the provided specifications.`; + res = await gptAPICall(`"${this._regenInput}"`, GPTCallType.DRAW, prompt, true); + this._lastInput.text = `${this._lastInput.text} ~~~ ${this._regenInput}`; + } else { + res = await gptAPICall(`"${this._lastInput.text}", "${this._lastInput.complexity}", "${this._lastInput.size}"`, GPTCallType.DRAW, undefined, true); + } + if (!res) { + console.error('GPT call failed'); + return; + } + const strokeData = await this.parseSvg(res, { X: this._lastInput.x, Y: this._lastInput.y }, true, lastInput?.autoColor || this._autoColor); + this.RemoveDrawing !== unimplementedFunction && this.RemoveDrawing(true, this._selectedDoc); + const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); + drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); + } catch (err) { + console.error('Error regenerating drawing', err); + } + } + if (this._generateImage) { if (this._regenInput !== '') { - const prompt: string = `This is your previously generated svg code: ${this._lastResponse} for the user input "${this._lastInput.text}". Please regenerate it with the provided specifications.`; - res = await gptAPICall(`"${this._regenInput}"`, GPTCallType.DRAW, prompt, true); - this._lastInput.text = `${this._lastInput.text} ~~~ ${this._regenInput}`; + if (this._selectedDoc) { + const docData = this._selectedDoc[DocData]; + const newPrompt = `${docData.firefly_prompt}, ${this._regenInput}`; + const seed: number = docData?.firefly_seed as number; + await this.createImageWithFirefly(newPrompt, seed); + } } else { - res = await gptAPICall(`"${this._lastInput.text}", "${this._lastInput.complexity}", "${this._lastInput.size}"`, GPTCallType.DRAW, undefined, true); + await this.createImageWithFirefly(this._lastInput.text); } - if (!res) { - console.error('GPT call failed'); - return; - } - const strokeData = await this.parseSvg(res, { X: this._lastInput.x, Y: this._lastInput.y }, true, lastInput?.autoColor || this._autoColor); - this.RemoveDrawing !== unimplementedFunction && this.RemoveDrawing(true, this._selectedDoc); - const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); - drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); - return strokeData; - } catch (err) { - console.error('Error regenerating drawing', err); } }; @@ -397,58 +431,87 @@ export class SmartDrawHandler extends ObservableReactComponent { {this._showOptions && (
-
-
- Auto color - this._canInteract && (this._autoColor = !this._autoColor))} - /> -
-
- Complexity - +
+ Generate Ink + this._canInteract && (this._complexity = val as number))} - valueLabelDisplay="auto" + checked={this._generateDrawing} + onChange={() => this._canInteract && (this._generateDrawing = !this._generateDrawing)} />
-
- Size (in pixels) - + Generate Image + this._canInteract && (this._size = val as number))} - valueLabelDisplay="auto" + checked={this._generateImage} + onChange={() => this._canInteract && (this._generateImage = !this._generateImage)} />
-
+ {this._generateDrawing && ( +
+
+ Auto color + this._canInteract && (this._autoColor = !this._autoColor))} + /> +
+
+ Complexity + this._canInteract && (this._complexity = val as number))} + valueLabelDisplay="auto" + /> +
+
+ Size (in pixels) + this._canInteract && (this._size = val as number))} + valueLabelDisplay="auto" + /> +
+
+ )}
)}
diff --git a/src/client/views/smartdraw/StickerPalette.tsx b/src/client/views/smartdraw/StickerPalette.tsx index d56878f10..352a02e32 100644 --- a/src/client/views/smartdraw/StickerPalette.tsx +++ b/src/client/views/smartdraw/StickerPalette.tsx @@ -186,6 +186,7 @@ export class StickerPalette extends ObservableReactComponent { + generateImage = (prompt: string = 'a realistic illustration of a cat coding', seed?: number) => { + let body = `{ "prompt": "${prompt}" }`; + if (seed) { + body = `{ "prompt": "${prompt}", "seeds": [${seed}]}`; + } const fetched = this.getBearerToken().then(response => response?.json().then((data: { access_token: string }) => fetch('https://firefly-api.adobe.io/v3/images/generate', { @@ -76,9 +80,15 @@ export default class FireflyManager extends ApiManager { ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''], ['Authorization', `Bearer ${data.access_token}`], ], - body: `{ "prompt": "${prompt}" }`, + body: body, }) - .then(response2 => response2.json().then(json => (json.outputs?.[0] as { image: { url: string } })?.image.url)) + .then(response2 => + response2.json().then(json => { + const seed = json.outputs?.[0]?.seed; + const url = json.outputs?.[0]?.image?.url; + return { seed, url }; + }) + ) .catch(error => { console.error('Error:', error); return undefined; @@ -226,8 +236,8 @@ export default class FireflyManager extends ApiManager { method: Method.POST, subscription: '/queryFireflyImage', secureHandler: ({ req, res }) => - this.generateImage(req.body.prompt).then(url => - DashUploadUtils.UploadImage(url ?? '').then(info => { + this.generateImage(req.body.prompt, req.body.seed).then(img => + DashUploadUtils.UploadImage(img?.url ?? '', undefined, img?.seed).then(info => { if (info instanceof Error) _invalid(res, info.message); else _success(res, info); }) diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index 623172894..2177c5d97 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -458,7 +458,6 @@ export namespace DashUploadUtils { return { name: result.name, message: result.message }; } const outputFile = filename || result.filename || ''; - return UploadInspectedImage(result, outputFile, prefix, isLocal().exec(source) || source.startsWith('data:') ? true : false); }; -- cgit v1.2.3-70-g09d2 From 4eebcc75a174b82033b5092f837b1477bcb628eb Mon Sep 17 00:00:00 2001 From: eleanor-park Date: Wed, 1 Jan 2025 21:28:23 -0500 Subject: added size option to image generation --- src/client/views/smartdraw/SmartDrawHandler.scss | 64 +++++--- src/client/views/smartdraw/SmartDrawHandler.tsx | 179 ++++++++++++++--------- src/server/ApiManagers/FireflyManager.ts | 10 +- 3 files changed, 157 insertions(+), 96 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/views/smartdraw/SmartDrawHandler.scss b/src/client/views/smartdraw/SmartDrawHandler.scss index 513779512..4b21c92a5 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.scss +++ b/src/client/views/smartdraw/SmartDrawHandler.scss @@ -1,6 +1,6 @@ .smart-draw-handler { position: absolute; - // width: 265px; + width: 265px; .smart-draw-main { display: flex; @@ -18,36 +18,54 @@ justify-content: center; } - .smartdraw-svg-options { - margin-top: 5px; + .smartdraw-options-container { + padding: 5px; + font-weight: bolder; + text-align: center; display: flex; - flex-direction: row; - justify-content: space-around; + flex-direction: column; - .auto-color { + .smartdraw-options { + font-weight: normal; + margin-top: 5px; display: flex; - flex-direction: column; - align-items: center; - width: 30%; - } + flex-direction: row; + justify-content: space-around; - .complexity { - display: flex; - flex-direction: column; - align-items: center; - width: 31%; - } + .smartdraw-auto-color { + display: flex; + flex-direction: column; + align-items: center; + width: 30%; + margin-top: 3px; + } - .size { - display: flex; - flex-direction: column; - align-items: center; - width: 39%; + .smartdraw-complexity { + display: flex; + flex-direction: column; + align-items: center; + width: 31%; + margin-top: 3px; + } - .size-slider { - width: 80%; + .smartdraw-size { + display: flex; + flex-direction: column; + align-items: center; + width: 39%; + margin-top: 3px; } } + + .smartdraw-dimensions { + font-weight: normal; + margin-top: 7px; + padding-left: 25px; + } + } + + .smartdraw-slider { + width: 65px; } .regenerate-box, diff --git a/src/client/views/smartdraw/SmartDrawHandler.tsx b/src/client/views/smartdraw/SmartDrawHandler.tsx index fb1a5771e..ed2734c8b 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.tsx +++ b/src/client/views/smartdraw/SmartDrawHandler.tsx @@ -1,5 +1,5 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { Checkbox, Slider, Switch } from '@mui/material'; +import { Checkbox, FormControlLabel, Radio, RadioGroup, Slider, Switch } from '@mui/material'; import { Button, IconButton } from 'browndash-components'; import { action, makeObservable, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; @@ -35,6 +35,13 @@ export interface DrawingOptions { y: number; } +enum FireflyImageDimensions { + Square = 'square', + Landscape = 'landscape', + Portrait = 'portrait', + Widescreen = 'widescreen', +} + /** * The SmartDrawHandler allows users to generate drawings with GPT from text input. Users are able to enter * the item to draw, how complex they want the drawing to be, how large the drawing should be, and whether @@ -66,13 +73,16 @@ export class SmartDrawHandler extends ObservableReactComponent { @observable private _scale: number = 0; @observable private _yRelativeToTop: boolean = true; @observable private _isLoading: boolean = false; + @observable private _userInput: string = ''; + @observable private _regenInput: string = ''; @observable private _showOptions: boolean = false; @observable private _showEditBox: boolean = false; @observable private _complexity: number = 5; @observable private _size: number = 200; @observable private _autoColor: boolean = true; - @observable private _regenInput: string = ''; + @observable private _imgDims: FireflyImageDimensions = FireflyImageDimensions.Square; + @observable private _canInteract: boolean = true; @observable private _generateDrawing: boolean = true; @observable private _generateImage: boolean = true; @@ -197,7 +207,7 @@ export class SmartDrawHandler extends ObservableReactComponent { */ @action handleSendClick = async () => { - if (!this._generateImage && !this._generateDrawing) return; + if ((!this.ShowRegenerate && this._userInput == '') || (!this._generateImage && !this._generateDrawing)) return; this._isLoading = true; this._canInteract = false; if (this.ShowRegenerate) { @@ -207,10 +217,6 @@ export class SmartDrawHandler extends ObservableReactComponent { this._showEditBox = false; }); } else { - if (this._userInput == '') { - this._isLoading = false; - return; - } runInAction(() => { this._showOptions = false; }); @@ -232,7 +238,7 @@ export class SmartDrawHandler extends ObservableReactComponent { this._errorOccurredOnce = false; } else { this._errorOccurredOnce = true; - await this.drawWithGPT({ X: this._pageX, Y: this._pageY }, this._userInput, this._complexity, this._size, this._autoColor); + await this.handleSendClick(); } } } @@ -268,7 +274,26 @@ export class SmartDrawHandler extends ObservableReactComponent { */ createImageWithFirefly = (input: string, seed?: number) => { this._lastInput.text = input; - return Networking.PostToServer('/queryFireflyImage', { prompt: input, seed: seed }).then(img => { + let width = 0; + let height = 0; + switch (this._imgDims) { + case FireflyImageDimensions.Square: + width = 2048; + height = 2048; + break; + case FireflyImageDimensions.Landscape: + width = 2304; + height = 1792; + case FireflyImageDimensions.Portrait: + width = 1792; + height = 2304; + break; + case FireflyImageDimensions.Widescreen: + width = 2688; + height = 1536; + break; + } + return Networking.PostToServer('/queryFireflyImage', { prompt: input, width: width, height: height, seed: seed }).then(img => { const imgDoc: Doc = Docs.Create.ImageDocument(img.accessPaths.agnostic.client, { title: input.match(/^(.*?)~~~.*$/)?.[1] || input, ai_generated: true, @@ -288,6 +313,18 @@ export class SmartDrawHandler extends ObservableReactComponent { if (lastInput) this._lastInput = lastInput; if (lastResponse) this._lastResponse = lastResponse; if (regenInput) this._regenInput = regenInput; + if (this._generateImage) { + if (this._regenInput !== '') { + if (this._selectedDoc) { + const docData = this._selectedDoc[DocData]; + const newPrompt = `${docData.firefly_prompt}, ${this._regenInput}`; + const seed: number = docData?.firefly_seed as number; + await this.createImageWithFirefly(newPrompt, seed); + } + } else { + await this.createImageWithFirefly(this._lastInput.text); + } + } if (this._generateDrawing) { try { let res; @@ -310,18 +347,6 @@ export class SmartDrawHandler extends ObservableReactComponent { console.error('Error regenerating drawing', err); } } - if (this._generateImage) { - if (this._regenInput !== '') { - if (this._selectedDoc) { - const docData = this._selectedDoc[DocData]; - const newPrompt = `${docData.firefly_prompt}, ${this._regenInput}`; - const seed: number = docData?.firefly_seed as number; - await this.createImageWithFirefly(newPrompt, seed); - } - } else { - await this.createImageWithFirefly(this._lastInput.text); - } - } }; /** @@ -460,55 +485,71 @@ export class SmartDrawHandler extends ObservableReactComponent { {this._generateDrawing && ( -
-
- Auto color - this._canInteract && (this._autoColor = !this._autoColor))} - /> -
-
- Complexity - this._canInteract && (this._complexity = val as number))} - valueLabelDisplay="auto" - /> +
+ Drawing Options +
+
+ Auto color + this._canInteract && (this._autoColor = !this._autoColor))} + /> +
+
+ Complexity + this._canInteract && (this._complexity = val as number))} + valueLabelDisplay="auto" + /> +
+
+ Size (in pixels) + this._canInteract && (this._size = val as number))} + valueLabelDisplay="auto" + /> +
-
- Size (in pixels) - this._canInteract && (this._size = val as number))} - valueLabelDisplay="auto" - /> +
+ )} + {this._generateImage && ( +
+ Image Options +
+ + } onChange={() => this._canInteract && (this._imgDims = FireflyImageDimensions.Square)} label="Square" /> + } onChange={() => this._canInteract && (this._imgDims = FireflyImageDimensions.Landscape)} label="Landscape" /> + } onChange={() => this._canInteract && (this._imgDims = FireflyImageDimensions.Portrait)} label="Portrait" /> + } onChange={() => this._canInteract && (this._imgDims = FireflyImageDimensions.Widescreen)} label="Widescreen" /> +
)} diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index c5348c7db..a41492745 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -65,10 +65,12 @@ export default class FireflyManager extends ApiManager { }) ); - generateImage = (prompt: string = 'a realistic illustration of a cat coding', seed?: number) => { - let body = `{ "prompt": "${prompt}" }`; + generateImage = (prompt: string = 'a realistic illustration of a cat coding', width: number = 2048, height: number = 2048, seed?: number) => { + console.log('DIMENSIONS', width, height); + let body = `{ "prompt": "${prompt}", "size": { "width": ${width}, "height": ${height}} }`; if (seed) { - body = `{ "prompt": "${prompt}", "seeds": [${seed}]}`; + console.log('RECEIVED SEED', seed); + body = `{ "prompt": "${prompt}", "size": { "width": ${width}, "height": ${height}}, "seeds": [${seed}]}`; } const fetched = this.getBearerToken().then(response => response?.json().then((data: { access_token: string }) => @@ -236,7 +238,7 @@ export default class FireflyManager extends ApiManager { method: Method.POST, subscription: '/queryFireflyImage', secureHandler: ({ req, res }) => - this.generateImage(req.body.prompt, req.body.seed).then(img => + this.generateImage(req.body.prompt, req.body.width, req.body.height, req.body.seed).then(img => DashUploadUtils.UploadImage(img?.url ?? '', undefined, img?.seed).then(info => { if (info instanceof Error) _invalid(res, info.message); else _success(res, info); -- cgit v1.2.3-70-g09d2 From 383b0487d5268bd860e514feddf09f4f3eb2fe3f Mon Sep 17 00:00:00 2001 From: eleanor-park Date: Thu, 2 Jan 2025 01:13:50 -0500 Subject: made drawing fill automatically size images --- src/client/util/bezierFit.ts | 1 + .../collectionFreeForm/CollectionFreeFormView.tsx | 2 +- src/client/views/nodes/ImageBox.tsx | 5 +- .../imageEditor/imageEditingUtils/ImageHandler.ts | 312 --------------------- src/client/views/smartdraw/DrawingFillHandler.tsx | 18 +- src/client/views/smartdraw/FireflyConstants.ts | 20 ++ src/client/views/smartdraw/SmartDrawHandler.scss | 3 +- src/client/views/smartdraw/SmartDrawHandler.tsx | 34 +-- src/server/ApiManagers/FireflyManager.ts | 7 +- 9 files changed, 51 insertions(+), 351 deletions(-) delete mode 100644 src/client/views/nodes/imageEditor/imageEditingUtils/ImageHandler.ts create mode 100644 src/client/views/smartdraw/FireflyConstants.ts (limited to 'src/server/ApiManagers') diff --git a/src/client/util/bezierFit.ts b/src/client/util/bezierFit.ts index 84b27e84c..7ef370d48 100644 --- a/src/client/util/bezierFit.ts +++ b/src/client/util/bezierFit.ts @@ -703,6 +703,7 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] { coordList.push({ X: parseInt(match[1]), Y: parseInt(match[2]) }); coordList.push({ X: parseInt(match[1]), Y: parseInt(match[2]) }); coordList.push({ X: parseInt(match[3]), Y: parseInt(match[4]) }); + coordList.push({ X: parseInt(match[3]), Y: parseInt(match[4]) }); lastPt = { X: parseInt(match[3]), Y: parseInt(match[4]) }; } else if (match[0].startsWith('C')) { coordList.push({ X: parseInt(match[5]), Y: parseInt(match[6]) }); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 4bccdd286..ef0b80720 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -1995,7 +1995,7 @@ export class CollectionFreeFormView extends CollectionSubView { SmartDrawHandler.Instance.CreateDrawingDoc = this.createDrawingDoc; SmartDrawHandler.Instance.AddDrawing = this.addDrawing; diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 8f6a90e61..7ce429f0f 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -355,9 +355,8 @@ export class ImageBox extends ViewBoxAnnotatableComponent() { this.layoutDoc.ai_generated && funcs.push({ description: 'Regenerate AI Image', - event: action(() => { - console.log('COOOORDS', this.dataDoc.width as number, this.dataDoc.y as number); - !SmartDrawHandler.Instance.ShowRegenerate ? SmartDrawHandler.Instance.displayRegenerate(this.dataDoc.x as number, (this.dataDoc.y as number) - 10) : SmartDrawHandler.Instance.hideRegenerate(); + event: action(e => { + !SmartDrawHandler.Instance.ShowRegenerate ? SmartDrawHandler.Instance.displayRegenerate(e?.x || 0, e?.y || 0) : SmartDrawHandler.Instance.hideRegenerate(); }), icon: 'pen-to-square', }); diff --git a/src/client/views/nodes/imageEditor/imageEditingUtils/ImageHandler.ts b/src/client/views/nodes/imageEditor/imageEditingUtils/ImageHandler.ts deleted file mode 100644 index 514e8a94f..000000000 --- a/src/client/views/nodes/imageEditor/imageEditingUtils/ImageHandler.ts +++ /dev/null @@ -1,312 +0,0 @@ -import { RefObject } from 'react'; -import { bgColor, canvasSize } from '../ImageEditorUtils/imageEditorConstants'; - -export interface APISuccess { - status: 'success'; - urls: string[]; -} - -export interface APIError { - status: 'error'; - message: string; -} - -export class ImageUtility { - /** - * - * @param canvas Canvas to convert - * @returns Blob of canvas - */ - static canvasToBlob = (canvas: HTMLCanvasElement): Promise => - new Promise(resolve => { - canvas.toBlob(blob => { - if (blob) { - resolve(blob); - } - }, 'image/png'); - }); - - // given a square api image, get the cropped img - static getCroppedImg = (img: HTMLImageElement, width: number, height: number): HTMLCanvasElement | undefined => { - // Create a new canvas element - const canvas = document.createElement('canvas'); - canvas.width = width; - canvas.height = height; - const ctx = canvas.getContext('2d'); - if (ctx) { - // Clear the canvas - ctx.clearRect(0, 0, canvas.width, canvas.height); - if (width < height) { - // horizontal padding, x offset - const xOffset = (canvasSize - width) / 2; - ctx.drawImage(img, xOffset, 0, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height); - } else { - // vertical padding, y offset - const yOffset = (canvasSize - height) / 2; - ctx.drawImage(img, 0, yOffset, canvas.width, canvas.height, 0, 0, canvas.width, canvas.height); - } - return canvas; - } - return undefined; - }; - - // converts an image to a canvas data url - static convertImgToCanvasUrl = async (imageSrc: string, width: number, height: number): Promise => - new Promise((resolve, reject) => { - const img = new Image(); - img.onload = () => { - const canvas = this.getCroppedImg(img, width, height); - if (canvas) { - const dataUrl = canvas.toDataURL(); - resolve(dataUrl); - } - }; - img.onerror = error => { - reject(error); - }; - img.src = imageSrc; - }); - - // calls the openai api to get image edits - static getEdit = async (imgBlob: Blob, maskBlob: Blob, prompt: string, n?: number): Promise => { - const apiUrl = 'https://api.openai.com/v1/images/edits'; - const fd = new FormData(); - fd.append('image', imgBlob, 'image.png'); - fd.append('mask', maskBlob, 'mask.png'); - fd.append('prompt', prompt); - fd.append('size', '1024x1024'); - fd.append('n', n ? JSON.stringify(n) : '1'); - fd.append('response_format', 'b64_json'); - - try { - const res = await fetch(apiUrl, { - method: 'POST', - headers: { - Authorization: `Bearer ${process.env.OPENAI_KEY}`, - }, - body: fd, - }); - const data = await res.json(); - console.log(data.data); - return { - status: 'success', - urls: (data.data as { b64_json: string }[]).map(urlData => `data:image/png;base64,${urlData.b64_json}`), - }; - } catch (err) { - console.log(err); - return { status: 'error', message: 'API error.' }; - } - }; - - // mock api call - static mockGetEdit = async (mockSrc: string): Promise => ({ - status: 'success', - urls: [mockSrc, mockSrc, mockSrc], - }); - - // Gets the canvas rendering context of a canvas - static getCanvasContext = (canvasRef: RefObject): CanvasRenderingContext2D | null => { - if (!canvasRef.current) return null; - const ctx = canvasRef.current.getContext('2d'); - if (!ctx) return null; - return ctx; - }; - - // Helper for downloading the canvas (for debugging) - static downloadCanvas = (canvas: HTMLCanvasElement) => { - const url = canvas.toDataURL(); - const downloadLink = document.createElement('a'); - downloadLink.href = url; - downloadLink.download = 'canvas'; - - downloadLink.click(); - downloadLink.remove(); - }; - - // Download the canvas (for debugging) - static downloadImageCanvas = (imgUrl: string) => { - const img = new Image(); - img.src = imgUrl; - img.onload = () => { - const canvas = document.createElement('canvas'); - canvas.width = canvasSize; - canvas.height = canvasSize; - const ctx = canvas.getContext('2d'); - ctx?.drawImage(img, 0, 0, canvasSize, canvasSize); - - this.downloadCanvas(canvas); - }; - }; - - // Clears the canvas - static clearCanvas = (canvasRef: React.RefObject) => { - const ctx = this.getCanvasContext(canvasRef); - if (!ctx || !canvasRef.current) return; - ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height); - }; - - // Draws the image to the current canvas - static drawImgToCanvas = (img: HTMLImageElement, canvasRef: React.RefObject, width: number, height: number) => { - const drawImg = (htmlImg: HTMLImageElement) => { - const ctx = this.getCanvasContext(canvasRef); - if (!ctx) return; - ctx.globalCompositeOperation = 'source-over'; - ctx.clearRect(0, 0, width, height); - ctx.drawImage(htmlImg, 0, 0, width, height); - }; - - if (img.complete) { - drawImg(img); - } else { - img.onload = () => { - drawImg(img); - }; - } - }; - - // Gets the image mask for the openai endpoint - static getCanvasMask = (srcCanvas: HTMLCanvasElement, paddedCanvas: HTMLCanvasElement): HTMLCanvasElement | undefined => { - const canvas = document.createElement('canvas'); - canvas.width = canvasSize; - canvas.height = canvasSize; - const ctx = canvas.getContext('2d'); - if (!ctx) return undefined; - ctx?.clearRect(0, 0, canvasSize, canvasSize); - ctx.drawImage(paddedCanvas, 0, 0); - - // extract and set padding data - if (srcCanvas.height > srcCanvas.width) { - // horizontal padding, x offset - const xOffset = (canvasSize - srcCanvas.width) / 2; - ctx?.clearRect(xOffset, 0, srcCanvas.width, srcCanvas.height); - ctx.drawImage(srcCanvas, xOffset, 0, srcCanvas.width, srcCanvas.height); - } else { - // vertical padding, y offset - const yOffset = (canvasSize - srcCanvas.height) / 2; - ctx?.clearRect(0, yOffset, srcCanvas.width, srcCanvas.height); - ctx.drawImage(srcCanvas, 0, yOffset, srcCanvas.width, srcCanvas.height); - } - return canvas; - }; - - // Fills in the blank areas of the image with an image reflection (to fill in a square-shaped canvas) - static drawHorizontalReflection = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement, xOffset: number) => { - const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); - const { data } = imageData; - for (let i = 0; i < canvas.height; i++) { - for (let j = 0; j < xOffset; j++) { - const targetIdx = 4 * (i * canvas.width + j); - const sourceI = i; - const sourceJ = xOffset + (xOffset - j); - const sourceIdx = 4 * (sourceI * canvas.width + sourceJ); - data[targetIdx] = data[sourceIdx]; - data[targetIdx + 1] = data[sourceIdx + 1]; - data[targetIdx + 2] = data[sourceIdx + 2]; - } - } - for (let i = 0; i < canvas.height; i++) { - for (let j = canvas.width - 1; j >= canvas.width - 1 - xOffset; j--) { - const targetIdx = 4 * (i * canvas.width + j); - const sourceI = i; - const sourceJ = canvas.width - 1 - xOffset - (xOffset - (canvas.width - j)); - const sourceIdx = 4 * (sourceI * canvas.width + sourceJ); - data[targetIdx] = data[sourceIdx]; - data[targetIdx + 1] = data[sourceIdx + 1]; - data[targetIdx + 2] = data[sourceIdx + 2]; - } - } - ctx.putImageData(imageData, 0, 0); - }; - - // Fills in the blank areas of the image with an image reflection (to fill in a square-shaped canvas) - static drawVerticalReflection = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement, yOffset: number) => { - const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); - const { data } = imageData; - for (let j = 0; j < canvas.width; j++) { - for (let i = 0; i < yOffset; i++) { - const targetIdx = 4 * (i * canvas.width + j); - const sourceJ = j; - const sourceI = yOffset + (yOffset - i); - const sourceIdx = 4 * (sourceI * canvas.width + sourceJ); - data[targetIdx] = data[sourceIdx]; - data[targetIdx + 1] = data[sourceIdx + 1]; - data[targetIdx + 2] = data[sourceIdx + 2]; - } - } - for (let j = 0; j < canvas.width; j++) { - for (let i = canvas.height - 1; i >= canvas.height - 1 - yOffset; i--) { - const targetIdx = 4 * (i * canvas.width + j); - const sourceJ = j; - const sourceI = canvas.height - 1 - yOffset - (yOffset - (canvas.height - i)); - const sourceIdx = 4 * (sourceI * canvas.width + sourceJ); - data[targetIdx] = data[sourceIdx]; - data[targetIdx + 1] = data[sourceIdx + 1]; - data[targetIdx + 2] = data[sourceIdx + 2]; - } - } - ctx.putImageData(imageData, 0, 0); - }; - - // Gets the unaltered (besides filling in padding) version of the image for the api call - static getCanvasImg = (img: HTMLImageElement): HTMLCanvasElement | undefined => { - const canvas = document.createElement('canvas'); - canvas.width = canvasSize; - canvas.height = canvasSize; - const ctx = canvas.getContext('2d'); - if (!ctx) return undefined; - // fix scaling - const scale = Math.min(canvasSize / img.width, canvasSize / img.height); - const width = Math.floor(img.width * scale); - const height = Math.floor(img.height * scale); - ctx?.clearRect(0, 0, canvasSize, canvasSize); - ctx.fillStyle = bgColor; - ctx.fillRect(0, 0, canvasSize, canvasSize); - - // extract and set padding data - if (img.naturalHeight > img.naturalWidth) { - // horizontal padding, x offset - const xOffset = Math.floor((canvasSize - width) / 2); - ctx.drawImage(img, xOffset, 0, width, height); - - // draw reflected image padding - this.drawHorizontalReflection(ctx, canvas, xOffset); - } else { - // vertical padding, y offset - const yOffset = Math.floor((canvasSize - height) / 2); - ctx.drawImage(img, 0, yOffset, width, height); - - // draw reflected image padding - this.drawVerticalReflection(ctx, canvas, yOffset); - } - return canvas; - }; - - /** - * Converts a url to base64 (tainted canvas workaround) - */ - static urlToBase64 = async (imageUrl: string): Promise => { - try { - const res = await fetch(imageUrl); - const blob = await res.blob(); - - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onload = () => { - const base64Data = reader.result?.toString().split(',')[1]; - if (base64Data) { - resolve(base64Data); - } else { - reject(new Error('Failed to convert.')); - } - }; - reader.onerror = () => { - reject(new Error('Error reading image data')); - }; - reader.readAsDataURL(blob); - }); - } catch (err) { - console.error(err); - } - return undefined; - }; -} diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index 1a470f995..7a95e27c2 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -1,5 +1,6 @@ import { imageUrlToBase64 } from '../../../ClientUtils'; import { Doc } from '../../../fields/Doc'; +import { DocData } from '../../../fields/DocSymbols'; import { ImageCast } from '../../../fields/Types'; import { Upload } from '../../../server/SharedMediaTypes'; import { gptDescribeImage } from '../../apis/gpt/GPT'; @@ -7,19 +8,32 @@ import { Docs } from '../../documents/Documents'; import { Networking } from '../../Network'; import { DocumentView, DocumentViewInternal } from '../nodes/DocumentView'; import { OpenWhere } from '../nodes/OpenWhere'; +import { AspectRatioLimits, FireflyDimensionsMap, FireflyImageDimensions } from './FireflyConstants'; export class DrawingFillHandler { static drawingToImage = (drawing: Doc, strength: number, prompt: string) => DocumentView.GetDocImage(drawing)?.then(imageField => { if (imageField) { + const aspectRatio = (drawing.width as number) / (drawing.height as number); + let dims: { width: number; height: number }; + if (aspectRatio > AspectRatioLimits[FireflyImageDimensions.Widescreen]) { + dims = FireflyDimensionsMap[FireflyImageDimensions.Widescreen]; + } else if (aspectRatio > AspectRatioLimits[FireflyImageDimensions.Landscape]) { + dims = FireflyDimensionsMap[FireflyImageDimensions.Landscape]; + } else if (aspectRatio < AspectRatioLimits[FireflyImageDimensions.Portrait]) { + dims = FireflyDimensionsMap[FireflyImageDimensions.Portrait]; + } else { + dims = FireflyDimensionsMap[FireflyImageDimensions.Square]; + } const { href } = ImageCast(imageField).url; const hrefParts = href.split('.'); const structureUrl = `${hrefParts.slice(0, -1).join('.')}_o.${hrefParts.lastElement()}`; imageUrlToBase64(structureUrl) .then((hrefBase64: string) => gptDescribeImage(hrefBase64)) .then((prompt: string) => { - Networking.PostToServer('/queryFireflyImageFromStructure', { prompt, structureUrl, strength }).then((info: Upload.ImageInformation) => - DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, {}), OpenWhere.addRight)) // prettier-ignore + Networking.PostToServer('/queryFireflyImageFromStructure', { prompt: prompt, width: dims.width, height: dims.height, structureUrl, strength }).then((info: Upload.ImageInformation) => + DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, { ai_generated: true, nativeWidth: dims.width, nativeHeight: dims.height }), OpenWhere.addRight) + ); // prettier-ignore }); } return false; diff --git a/src/client/views/smartdraw/FireflyConstants.ts b/src/client/views/smartdraw/FireflyConstants.ts new file mode 100644 index 000000000..f51305fba --- /dev/null +++ b/src/client/views/smartdraw/FireflyConstants.ts @@ -0,0 +1,20 @@ +export enum FireflyImageDimensions { + Square = 'square', + Landscape = 'landscape', + Portrait = 'portrait', + Widescreen = 'widescreen', +} + +export const FireflyDimensionsMap = { + square: { width: 2048, height: 2048 }, + landscape: { width: 2304, height: 1792 }, + portrait: { width: 1792, height: 2304 }, + widescreen: { width: 2688, height: 1536 }, +}; + +export const AspectRatioLimits = { + square: 1, + landscape: 1.167, + portrait: 0.875, + widescreen: 1.472, +}; diff --git a/src/client/views/smartdraw/SmartDrawHandler.scss b/src/client/views/smartdraw/SmartDrawHandler.scss index 4b21c92a5..cca7d77c7 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.scss +++ b/src/client/views/smartdraw/SmartDrawHandler.scss @@ -1,6 +1,5 @@ .smart-draw-handler { position: absolute; - width: 265px; .smart-draw-main { display: flex; @@ -16,9 +15,11 @@ display: flex; flex-direction: row; justify-content: center; + margin-top: 3px; } .smartdraw-options-container { + width: 265px; padding: 5px; font-weight: bolder; text-align: center; diff --git a/src/client/views/smartdraw/SmartDrawHandler.tsx b/src/client/views/smartdraw/SmartDrawHandler.tsx index 8cff2174f..6c9470480 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.tsx +++ b/src/client/views/smartdraw/SmartDrawHandler.tsx @@ -25,6 +25,7 @@ import { ActiveInkArrowEnd, ActiveInkArrowStart, ActiveInkDash, ActiveInkFillCol import './SmartDrawHandler.scss'; import { Networking } from '../../Network'; import { OpenWhere } from '../nodes/OpenWhere'; +import { FireflyDimensionsMap, FireflyImageDimensions } from './FireflyConstants'; export interface DrawingOptions { text: string; @@ -35,13 +36,6 @@ export interface DrawingOptions { y: number; } -enum FireflyImageDimensions { - Square = 'square', - Landscape = 'landscape', - Portrait = 'portrait', - Widescreen = 'widescreen', -} - /** * The SmartDrawHandler allows users to generate drawings with GPT from text input. Users are able to enter * the item to draw, how complex they want the drawing to be, how large the drawing should be, and whether @@ -274,30 +268,12 @@ export class SmartDrawHandler extends ObservableReactComponent { */ createImageWithFirefly = (input: string, seed?: number) => { this._lastInput.text = input; - let width = 0; - let height = 0; - switch (this._imgDims) { - case FireflyImageDimensions.Square: - width = 2048; - height = 2048; - break; - case FireflyImageDimensions.Landscape: - width = 2304; - height = 1792; - case FireflyImageDimensions.Portrait: - width = 1792; - height = 2304; - break; - case FireflyImageDimensions.Widescreen: - width = 2688; - height = 1536; - break; - } - return Networking.PostToServer('/queryFireflyImage', { prompt: input, width: width, height: height, seed: seed }).then(img => { + const dims = FireflyDimensionsMap[this._imgDims]; + return Networking.PostToServer('/queryFireflyImage', { prompt: input, width: dims.width, height: dims.height, seed: seed }).then(img => { const imgDoc: Doc = Docs.Create.ImageDocument(img.accessPaths.agnostic.client, { title: input.match(/^(.*?)~~~.*$/)?.[1] || input, - nativeWidth: width, - nativeHeight: height, + nativeWidth: dims.width, + nativeHeight: dims.height, ai_generated: true, firefly_seed: img.accessPaths.agnostic.client.match(/\/(\d+)upload/)[1], firefly_prompt: input, diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index a41492745..4c4aac5e0 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -20,7 +20,7 @@ export default class FireflyManager extends ApiManager { return undefined; }); - generateImageFromStructure = (prompt: string = 'a realistic illustration of a cat coding', structureUrl: string, strength: number) => + generateImageFromStructure = (prompt: string = 'a realistic illustration of a cat coding', width: number = 2048, height: number = 2048, structureUrl: string, strength: number = 50) => this.getBearerToken().then(response => response?.json().then((data: { access_token: string }) => fetch('https://firefly-api.adobe.io/v3/images/generate', { @@ -32,7 +32,8 @@ export default class FireflyManager extends ApiManager { ['Authorization', `Bearer ${data.access_token}`], ], body: JSON.stringify({ - prompt, + prompt: prompt, + size: { width: width, height: height }, structure: !structureUrl ? undefined : { @@ -226,7 +227,7 @@ export default class FireflyManager extends ApiManager { subscription: '/queryFireflyImageFromStructure', secureHandler: async ({ req, res }) => this.uploadImageToDropbox(req.body.structureUrl).then(uploadUrl => - this.generateImageFromStructure(req.body.prompt, uploadUrl, req.body.strength).then(fire => + this.generateImageFromStructure(req.body.prompt, req.body.width, req.body.height, uploadUrl, req.body.strength).then(fire => DashUploadUtils.UploadImage(JSON.parse(fire ?? '').url).then(info => { if (info instanceof Error) _invalid(res, info.message); else _success(res, info); -- cgit v1.2.3-70-g09d2 From 6e7cb570f9bad527cd4772bb5c715dd588fb77df Mon Sep 17 00:00:00 2001 From: eleanor-park Date: Thu, 2 Jan 2025 22:39:25 -0500 Subject: tags can now be used as style presets --- src/client/apis/gpt/GPT.ts | 2 +- src/client/views/DocumentButtonBar.tsx | 18 ++++++++++++++++++ src/client/views/nodes/DocumentView.tsx | 2 ++ src/client/views/smartdraw/DrawingFillHandler.tsx | 10 +++++++--- src/client/views/smartdraw/FireflyConstants.ts | 22 ++++++++++++++++++++++ src/server/ApiManagers/FireflyManager.ts | 7 +++++-- 6 files changed, 55 insertions(+), 6 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/apis/gpt/GPT.ts b/src/client/apis/gpt/GPT.ts index 9241eb120..4b0d58cc1 100644 --- a/src/client/apis/gpt/GPT.ts +++ b/src/client/apis/gpt/GPT.ts @@ -260,7 +260,7 @@ const gptDescribeImage = async (image: string): Promise => { content: [ { type: 'text', - text: `Identify what this drawing is, naming as many elements and their location in the drawing as possible`, + text: `Briefly identify what this drawing is, naming all the drawing elements and their location within the image. Do not include anything about the drawing style.`, }, { type: 'image_url', diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index 32bf67df1..b7033af3f 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -314,6 +314,23 @@ export class DocumentButtonBar extends ObservableReactComponent<{ views: () => ( ); } + @computed + get aiEditorButton() { + const targetDoc = this.view0?.Document; + return !targetDoc ? null : ( + Edit with AI}> +
{ + CalendarManager.Instance.open(this.view0, targetDoc); + }}> + +
+
+ ); + } + @observable _isRecording = false; _stopFunc: () => void = emptyFunction; @computed @@ -484,6 +501,7 @@ export class DocumentButtonBar extends ObservableReactComponent<{ views: () => (
{this.pinButton}
{this.recordButton}
{this.calendarButton}
+
{this.aiEditorButton}
{this.keywordButton}
{!Doc.UserDoc().documentLinksButton_fullMenu ? null :
{this.shareButton}
}
{this.menuButton}
diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 8519cda3c..048b92c71 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -1400,6 +1400,8 @@ export class DocumentView extends DocComponent() { NativeHeight = () => this.effectiveNativeHeight; PanelWidth = () => this.panelWidth; PanelHeight = () => this.panelHeight; + ReducedPanelWidth = () => this.panelWidth / 2; + ReducedPanelHeight = () => this.panelWidth / 2; NativeDimScaling = () => this.nativeScaling; hideLinkCount = () => !!this.hideLinkButton; isHovering = () => this._isHovering; diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index 7a95e27c2..52652d377 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -8,10 +8,13 @@ import { Docs } from '../../documents/Documents'; import { Networking } from '../../Network'; import { DocumentView, DocumentViewInternal } from '../nodes/DocumentView'; import { OpenWhere } from '../nodes/OpenWhere'; -import { AspectRatioLimits, FireflyDimensionsMap, FireflyImageDimensions } from './FireflyConstants'; +import { AspectRatioLimits, FireflyDimensionsMap, FireflyImageDimensions, FireflyStylePresets } from './FireflyConstants'; export class DrawingFillHandler { - static drawingToImage = (drawing: Doc, strength: number, prompt: string) => + static drawingToImage = (drawing: Doc, strength: number, prompt: string) => { + const docData = drawing[DocData]; + const tags: string[] = ((docData?.tags as unknown as string[]) ?? []).map(tag => tag.slice(1)) ?? []; + const styles = tags.filter(tag => FireflyStylePresets.has(tag)); DocumentView.GetDocImage(drawing)?.then(imageField => { if (imageField) { const aspectRatio = (drawing.width as number) / (drawing.height as number); @@ -31,11 +34,12 @@ export class DrawingFillHandler { imageUrlToBase64(structureUrl) .then((hrefBase64: string) => gptDescribeImage(hrefBase64)) .then((prompt: string) => { - Networking.PostToServer('/queryFireflyImageFromStructure', { prompt: prompt, width: dims.width, height: dims.height, structureUrl, strength }).then((info: Upload.ImageInformation) => + Networking.PostToServer('/queryFireflyImageFromStructure', { prompt: prompt, width: dims.width, height: dims.height, structureUrl: structureUrl, strength: strength, styles: styles }).then((info: Upload.ImageInformation) => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, { ai_generated: true, nativeWidth: dims.width, nativeHeight: dims.height }), OpenWhere.addRight) ); // prettier-ignore }); } return false; }); + }; } diff --git a/src/client/views/smartdraw/FireflyConstants.ts b/src/client/views/smartdraw/FireflyConstants.ts index f51305fba..3574039e4 100644 --- a/src/client/views/smartdraw/FireflyConstants.ts +++ b/src/client/views/smartdraw/FireflyConstants.ts @@ -18,3 +18,25 @@ export const AspectRatioLimits = { portrait: 0.875, widescreen: 1.472, }; + +// prettier-ignore +export const FireflyStylePresets = + new Set(['graphic', 'wireframe', + 'vector_look','bw','cool_colors','golden','monochromatic','muted_color','toned_image','vibrant_colors','warm_tone','closeup', + 'knolling','landscape_photography','macrophotography','photographed_through_window','shallow_depth_of_field','shot_from_above', + 'shot_from_below','surface_detail','wide_angle','beautiful','bohemian','chaotic','dais','divine','eclectic','futuristic','kitschy', + 'nostalgic','simple','antique_photo','bioluminescent','bokeh','color_explosion','dark','faded_image','fisheye','gomori_photography', + 'grainy_film','iridescent','isometric','misty','neon','otherworldly_depiction','ultraviolet','underwater', 'backlighting', + 'dramatic_light', 'golden_hour', 'harsh_light','long','low_lighting','multiexposure','studio_light','surreal_lighting', + '3d_patterns','charcoal','claymation','fabric','fur','guilloche_patterns','layered_paper','marble_sculpture','made_of_metal', + 'origami','paper_mache','polka','strange_patterns','wood_carving','yarn','art_deco','art_nouveau','baroque','bauhaus', + 'constructivism','cubism','cyberpunk','fantasy','fauvism', 'film_noir','glitch_art','impressionism','industrialism','maximalism', + 'minimalism','modern_art','modernism','neo','pointillism','psychedelic','science_fiction','steampunk','surrealism','synthetism', + 'synthwave','vaporwave','acrylic_paint','bold_lines','chiaroscuro','color_shift_art','daguerreotype','digital_fractal', + 'doodle_drawing','double_exposure_portrait','fresco','geometric_pen','halftone','ink','light_painting','line_drawing','linocut', + 'oil_paint','paint_spattering','painting','palette_knife','photo_manipulation','scribble_texture','sketch','splattering', + 'stippling_drawing','watercolor','3d','anime','cartoon','cinematic','comic_book','concept_art','cyber_matrix','digital_art', + 'flat_design','geometric','glassmorphism','glitch_graphic','graffiti','hyper_realistic','interior_design','line_gradient', + 'low_poly','newspaper_collage','optical_illusion','pattern_pixel','pixel_art','pop_art','product_photo','psychedelic_background', + 'psychedelic_wonderland','scandinavian','splash_images','stamp','trompe_loeil' + ]); diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 4c4aac5e0..cb5d7c1da 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -20,9 +20,10 @@ export default class FireflyManager extends ApiManager { return undefined; }); - generateImageFromStructure = (prompt: string = 'a realistic illustration of a cat coding', width: number = 2048, height: number = 2048, structureUrl: string, strength: number = 50) => + generateImageFromStructure = (prompt: string = 'a realistic illustration of a cat coding', width: number = 2048, height: number = 2048, structureUrl: string, strength: number = 50, styles: string[]) => this.getBearerToken().then(response => response?.json().then((data: { access_token: string }) => + //prettier-ignore fetch('https://firefly-api.adobe.io/v3/images/generate', { method: 'POST', headers: [ @@ -42,6 +43,8 @@ export default class FireflyManager extends ApiManager { source: { url: structureUrl }, }, }, + //prettier-ignore + style: { presets: styles } }), }) .then(response2 => response2.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image))) @@ -227,7 +230,7 @@ export default class FireflyManager extends ApiManager { subscription: '/queryFireflyImageFromStructure', secureHandler: async ({ req, res }) => this.uploadImageToDropbox(req.body.structureUrl).then(uploadUrl => - this.generateImageFromStructure(req.body.prompt, req.body.width, req.body.height, uploadUrl, req.body.strength).then(fire => + this.generateImageFromStructure(req.body.prompt, req.body.width, req.body.height, uploadUrl, req.body.strength, req.body.styles).then(fire => DashUploadUtils.UploadImage(JSON.parse(fire ?? '').url).then(info => { if (info instanceof Error) _invalid(res, info.message); else _success(res, info); -- cgit v1.2.3-70-g09d2 From 1d62d867621b293c41ff8488ca5a3bd6010723d5 Mon Sep 17 00:00:00 2001 From: eleanor-park Date: Sun, 5 Jan 2025 23:47:18 -0500 Subject: added AI image editor --- src/client/documents/Documents.ts | 6 +- src/client/util/CurrentUserUtils.ts | 2 +- src/client/views/DocumentButtonBar.tsx | 7 +- src/client/views/ViewBoxInterface.ts | 1 + .../collectionFreeForm/CollectionFreeFormView.tsx | 12 +-- src/client/views/nodes/DocumentView.tsx | 22 +++- src/client/views/nodes/ImageBox.scss | 28 +++++ src/client/views/nodes/ImageBox.tsx | 113 ++++++++++++++++++++- src/client/views/pdf/AnchorMenu.tsx | 12 +-- src/client/views/smartdraw/DrawingFillHandler.tsx | 2 +- src/client/views/smartdraw/SmartDrawHandler.tsx | 92 +++++++++-------- src/client/views/smartdraw/StickerPalette.tsx | 17 ++-- src/server/ApiManagers/FireflyManager.ts | 1 - 13 files changed, 235 insertions(+), 80 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 785af3409..7f1387ff8 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -517,9 +517,9 @@ export class DocumentOptions { card_sort?: STRt = new StrInfo('way cards are sorted in deck view'); card_sort_isDesc?: BOOLt = new BoolInfo('whether the cards are sorted ascending or descending'); - ai_generated?: boolean; // to mark items as ai generated - firefly_seed?: number; - firefly_prompt?: string; + ai?: string; // to mark items as ai generated + ai_firefly_seed?: number; + ai_firefly_prompt?: string; } export const DocOptions = new DocumentOptions(); diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts index 9af79a02e..b41fd09dc 100644 --- a/src/client/util/CurrentUserUtils.ts +++ b/src/client/util/CurrentUserUtils.ts @@ -779,7 +779,7 @@ pie title Minerals in my tap water { title: " Size", toolTip: "Size of area pencil eraser", btnType: ButtonType.NumberSliderButton, toolType: InkProperty.EraserWidth,ignoreClick: true, scripts: {script: '{ return setInkProperty(this.toolType, value, _readOnly_);}'}, funcs: {hidden:"NotRadiusEraser()"}, numBtnMin: 1, linearBtnWidth:40}, { title: "Mask", toolTip: "Make Stroke a Stencil Mask", btnType: ButtonType.ToggleButton, icon: "user-circle", toolType: InkProperty.Mask, scripts: {onClick:'{ return setInkProperty(this.toolType, value, _readOnly_);}'}, funcs: {hidden:"IsNoviceMode()" } }, { title: "Labels", toolTip: "Show Labels Inside Shapes", btnType: ButtonType.ToggleButton, icon: "text-width", toolType: InkProperty.Labels, scripts: {onClick:'{ return setInkProperty(this.toolType, value, _readOnly_);}'}}, - { title: "Smart Draw", toolTip: "Draw with GPT", btnType: ButtonType.ToggleButton, icon: "user-pen", toolType: InkTool.SmartDraw, scripts: {onClick:'{ return setActiveTool(this.toolType, false, _readOnly_);}'}, funcs: {hidden: "IsNoviceMode()"}}, + { title: "Smart Draw", toolTip: "Draw with AI", btnType: ButtonType.ToggleButton, icon: "user-pen", toolType: InkTool.SmartDraw, scripts: {onClick:'{ return setActiveTool(this.toolType, false, _readOnly_);}'}, funcs: {hidden: "IsNoviceMode()"}}, ]; } diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index b7033af3f..d722b28b5 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -319,12 +319,7 @@ export class DocumentButtonBar extends ObservableReactComponent<{ views: () => ( const targetDoc = this.view0?.Document; return !targetDoc ? null : ( Edit with AI}> -
{ - CalendarManager.Instance.open(this.view0, targetDoc); - }}> +
this.view0?.toggleAIEditor(), 'toggle AI editor')}>
diff --git a/src/client/views/ViewBoxInterface.ts b/src/client/views/ViewBoxInterface.ts index b7980d74e..df08f2564 100644 --- a/src/client/views/ViewBoxInterface.ts +++ b/src/client/views/ViewBoxInterface.ts @@ -60,4 +60,5 @@ export abstract class ViewBoxInterface

extends ObservableReactComponent boolean; dontRegisterView?: () => boolean; // KeyValueBox's don't want to register their views isUnstyledView?: () => boolean; // SchemaView and KeyValue are unstyled -- not titles, no opacity, no animations + componentAIView?: (top: number) => JSX.Element; } diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index ef0b80720..9af698ec7 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -1290,12 +1290,12 @@ export class CollectionFreeFormView extends CollectionSubView> = undefined; // needs to be accessed from DocumentView wrapper class @observable _animateScaleTime: Opt = undefined; // milliseconds for animating between views. defaults to 300 if not uset @observable _animateScalingTo = 0; + @observable public _showAIEditor: boolean = false; + + @action + showAIEditor() { + this._showAIEditor = !this._showAIEditor; + } get _contentDiv() { return this._mainCont.current; } // prettier-ignore get _docView() { return this._props.DocumentView?.(); } // prettier-ignore @@ -552,7 +558,6 @@ export class DocumentViewInternal extends DocComponent DocumentView.SetLightboxDoc(this.Document), icon: 'external-link-alt' }); } appearanceItems.push({ description: 'Pin', event: () => this._props.pinToPres(this.Document, {}), icon: 'map-pin' }); - appearanceItems.push({ description: 'Make Image', event: () => DrawingFillHandler.drawingToImage(this.Document, StrCast(this.Document.title)), icon: 'map-pin' }); !Doc.noviceMode && templateDoc && appearanceItems.push({ description: 'Open Template ', event: () => this._props.addDocTab(templateDoc, OpenWhere.addRight), icon: 'eye' }); !appearance && appearanceItems.length && cm.addItem({ description: 'Appearance...', subitems: appearanceItems, icon: 'compass' }); @@ -711,6 +716,8 @@ export class DocumentViewInternal extends DocComponent this._props.PanelWidth() * 0.6; + rph = () => this.panelHeight() * 0.6; @computed get viewBoxContents() { TraceMobx(); const isInk = this.layoutDoc._layout_isSvg && !this._props.LayoutTemplateString; @@ -720,7 +727,9 @@ export class DocumentViewInternal extends DocComponent + {this._showAIEditor && (this._componentView?.componentAIView?.(this.rph()) ?? null)}

); } @@ -1286,6 +1297,11 @@ export class DocumentView extends DocComponent() { } }; + @action + public toggleAIEditor = () => { + this._docViewInternal && this._docViewInternal.showAIEditor(); + }; + public setTextHtmlOverlay = action((text: string | undefined, effect?: Doc) => { this._htmlOverlayText = text; this._htmlOverlayEffect = effect; diff --git a/src/client/views/nodes/ImageBox.scss b/src/client/views/nodes/ImageBox.scss index 3ffda5a35..03314e90f 100644 --- a/src/client/views/nodes/ImageBox.scss +++ b/src/client/views/nodes/ImageBox.scss @@ -139,3 +139,31 @@ .imageBox-fadeBlocker-hover { opacity: 0; } + +.imageBox-aiView { + padding: 5px; + position: absolute; + overflow: scroll; + text-align: center; + font-weight: bold; + margin-top: 5px; + + .imageBox-aiView-subtitle { + align-self: start; + } + + .imageBox-aiView-regenerate-container, + .imageBox-aiView-options-container { + font-weight: normal; + text-align: start; + } + + .imageBox-aiView-regenerate, + .imageBox-aiView-options { + display: flex; + flex-direction: row; + justify-content: center; + flex-direction: row; + gap: 5px; + } +} diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index 7ce429f0f..f00580d77 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -1,7 +1,7 @@ import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Tooltip } from '@mui/material'; import axios from 'axios'; -import { Colors } from 'browndash-components'; +import { Colors, Type } from 'browndash-components'; import { action, computed, IReactionDisposer, makeObservable, observable, ObservableMap, reaction } from 'mobx'; import { observer } from 'mobx-react'; import { extname } from 'path'; @@ -41,6 +41,9 @@ import './ImageBox.scss'; import { OpenWhere } from './OpenWhere'; import { Upload } from '../../../server/SharedMediaTypes'; import { SmartDrawHandler } from '../smartdraw/SmartDrawHandler'; +import { Button } from 'browndash-components'; +import { SettingsManager } from '../../util/SettingsManager'; +import { AiOutlineSend } from 'react-icons/ai'; export class ImageEditorData { // eslint-disable-next-line no-use-before-define @@ -352,7 +355,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent() { }), icon: 'pencil-alt', }); - this.layoutDoc.ai_generated && + this.layoutDoc.ai && funcs.push({ description: 'Regenerate AI Image', event: action(e => { @@ -526,6 +529,112 @@ export class ImageBox extends ViewBoxAnnotatableComponent() { ); } + @observable private _regenInput = ''; + @observable private _canInteract = true; + @observable private _regenerateLoading = false; + + componentAIView = (top: number) => { + const field = Cast(this.dataDoc[this.fieldKey], ImageField); + const showRegenerate = this.Document[DocData].ai; + return ( +
+ Edit Image with AI + {showRegenerate && ( +
+ Regenerate AI Image +
+ this._canInteract && (this._regenInput = e.target.value))} + // onKeyDown={this.handleKeyPress} + placeholder="Prompt (Optional)" + /> +
+
+ )} +
+ {showRegenerate && More Image Options } +
+
+
+
+ ); + }; + @computed get annotationLayer() { TraceMobx(); return
; diff --git a/src/client/views/pdf/AnchorMenu.tsx b/src/client/views/pdf/AnchorMenu.tsx index bb8082061..2e704aa8d 100644 --- a/src/client/views/pdf/AnchorMenu.tsx +++ b/src/client/views/pdf/AnchorMenu.tsx @@ -153,12 +153,12 @@ export class AnchorMenu extends AntimodeMenu { this.AddDrawingAnnotation(drawing); const docData = drawing[DocData]; docData.title = opts.text.match(/^(.*?)~~~.*$/)?.[1] || opts.text; - docData.drawingInput = opts.text; - docData.drawingComplexity = opts.complexity; - docData.drawingColored = opts.autoColor; - docData.drawingSize = opts.size; - docData.drawingData = gptRes; - docData.ai_generated = true; + docData.ai_drawing_input = opts.text; + docData.ai_drawing_complexity = opts.complexity; + docData.ai_drawing_colored = opts.autoColor; + docData.ai_drawing_size = opts.size; + docData.ai_drawing_data = gptRes; + docData.ai = 'gpt'; }); pointerDown = (e: React.PointerEvent) => { diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index 52652d377..8e41ee105 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -35,7 +35,7 @@ export class DrawingFillHandler { .then((hrefBase64: string) => gptDescribeImage(hrefBase64)) .then((prompt: string) => { Networking.PostToServer('/queryFireflyImageFromStructure', { prompt: prompt, width: dims.width, height: dims.height, structureUrl: structureUrl, strength: strength, styles: styles }).then((info: Upload.ImageInformation) => - DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, { ai_generated: true, nativeWidth: dims.width, nativeHeight: dims.height }), OpenWhere.addRight) + DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, { ai: 'firefly', ai_firefly_prompt: prompt, nativeWidth: dims.width, nativeHeight: dims.height }), OpenWhere.addRight) ); // prettier-ignore }); } diff --git a/src/client/views/smartdraw/SmartDrawHandler.tsx b/src/client/views/smartdraw/SmartDrawHandler.tsx index 6c9470480..0c67c7a13 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.tsx +++ b/src/client/views/smartdraw/SmartDrawHandler.tsx @@ -58,7 +58,7 @@ export class SmartDrawHandler extends ObservableReactComponent { private _lastInput: DrawingOptions = { text: '', complexity: 5, size: 350, autoColor: true, x: 0, y: 0 }; private _lastResponse: string = ''; - private _selectedDoc: Doc | undefined = undefined; + private _selectedDocs: Doc[] = []; private _errorOccurredOnce = false; @observable private _display: boolean = false; @@ -144,14 +144,14 @@ export class SmartDrawHandler extends ObservableReactComponent { */ @action displayRegenerate = (x: number, y: number) => { - this._selectedDoc = DocumentView.SelectedDocs()?.lastElement(); + this._selectedDocs = [DocumentView.SelectedDocs()?.lastElement()]; [this._pageX, this._pageY] = [x, y]; this._display = false; this.ShowRegenerate = true; this._showEditBox = false; - const docData = this._selectedDoc[DocData]; + const docData = this._selectedDocs[0][DocData]; this._lastResponse = StrCast(docData.drawingData); - this._lastInput = { text: StrCast(docData.drawingInput), complexity: NumCast(docData.drawingComplexity), size: NumCast(docData.drawingSize), autoColor: BoolCast(docData.drawingColored), x: this._pageX, y: this._pageY }; + this._lastInput = { text: StrCast(docData.ai_drawing_input), complexity: NumCast(docData.ai_drawing_complexity), size: NumCast(docData.ai_drawing_size), autoColor: BoolCast(docData.ai_drawing_colored), x: this._pageX, y: this._pageY }; }; /** @@ -205,8 +205,9 @@ export class SmartDrawHandler extends ObservableReactComponent { this._isLoading = true; this._canInteract = false; if (this.ShowRegenerate) { - await this.regenerate(); + await this.regenerate(this._selectedDocs); runInAction(() => { + this._selectedDocs = []; this._regenInput = ''; this._showEditBox = false; }); @@ -253,7 +254,7 @@ export class SmartDrawHandler extends ObservableReactComponent { const strokeData = await this.parseSvg(res, startPt, false, autoColor); const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); - this._selectedDoc = drawingDoc; + drawingDoc && this._selectedDocs.push(drawingDoc); this._errorOccurredOnce = false; return strokeData; } else { @@ -274,57 +275,62 @@ export class SmartDrawHandler extends ObservableReactComponent { title: input.match(/^(.*?)~~~.*$/)?.[1] || input, nativeWidth: dims.width, nativeHeight: dims.height, - ai_generated: true, - firefly_seed: img.accessPaths.agnostic.client.match(/\/(\d+)upload/)[1], - firefly_prompt: input, + ai: 'firefly', + ai_firefly_seed: img.accessPaths.agnostic.client.match(/\/(\d+)upload/)[1], + ai_firefly_prompt: input, }); DocumentViewInternal.addDocTabFunc(imgDoc, OpenWhere.addRight); - this._selectedDoc = imgDoc; + this._selectedDocs.push(imgDoc); }); }; /** * Regenerates drawings with the option to add a specific regenerate prompt/request. + * @param doc the drawing Docs to regenerate */ @action - regenerate = async (lastInput?: DrawingOptions, lastResponse?: string, regenInput?: string) => { + regenerate = async (drawingDocs: Doc[], lastInput?: DrawingOptions, lastResponse?: string, regenInput?: string) => { if (lastInput) this._lastInput = lastInput; if (lastResponse) this._lastResponse = lastResponse; if (regenInput) this._regenInput = regenInput; - if (this._generateImage) { - if (this._regenInput !== '') { - if (this._selectedDoc) { - const docData = this._selectedDoc[DocData]; - const newPrompt = `${docData.firefly_prompt}, ${this._regenInput}`; - const seed: number = docData?.firefly_seed as number; - await this.createImageWithFirefly(newPrompt, seed); + await Promise.all( + drawingDocs.map(async doc => { + const docData = doc[DocData]; + if (docData.type == 'image') { + const seed: number = docData?.ai_firefly_seed as number; + if (this._regenInput !== '') { + // if (this._selectedDoc) { + const newPrompt = `${docData.ai_firefly_prompt}, ${this._regenInput}`; + await this.createImageWithFirefly(newPrompt, seed); + // } + } else { + await this.createImageWithFirefly(this._lastInput.text || StrCast(docData.ai_firefly_prompt)); + } } - } else { - await this.createImageWithFirefly(this._lastInput.text); - } - } - if (this._generateDrawing) { - try { - let res; - if (this._regenInput !== '') { - const prompt: string = `This is your previously generated svg code: ${this._lastResponse} for the user input "${this._lastInput.text}". Please regenerate it with the provided specifications.`; - res = await gptAPICall(`"${this._regenInput}"`, GPTCallType.DRAW, prompt, true); - this._lastInput.text = `${this._lastInput.text} ~~~ ${this._regenInput}`; - } else { - res = await gptAPICall(`"${this._lastInput.text}", "${this._lastInput.complexity}", "${this._lastInput.size}"`, GPTCallType.DRAW, undefined, true); - } - if (!res) { - console.error('GPT call failed'); - return; + if (docData.type == 'collection') { + try { + let res; + if (this._regenInput !== '') { + const prompt: string = `This is your previously generated svg code: ${this._lastResponse} for the user input "${this._lastInput.text}". Please regenerate it with the provided specifications.`; + res = await gptAPICall(`"${this._regenInput}"`, GPTCallType.DRAW, prompt, true); + this._lastInput.text = `${this._lastInput.text} ~~~ ${this._regenInput}`; + } else { + res = await gptAPICall(`"${this._lastInput.text}", "${this._lastInput.complexity}", "${this._lastInput.size}"`, GPTCallType.DRAW, undefined, true); + } + if (!res) { + console.error('GPT call failed'); + return; + } + const strokeData = await this.parseSvg(res, { X: this._lastInput.x, Y: this._lastInput.y }, true, lastInput?.autoColor || this._autoColor); + this.RemoveDrawing !== unimplementedFunction && this.RemoveDrawing(true, doc); + const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); + drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); + } catch (err) { + console.error('Error regenerating drawing', err); + } } - const strokeData = await this.parseSvg(res, { X: this._lastInput.x, Y: this._lastInput.y }, true, lastInput?.autoColor || this._autoColor); - this.RemoveDrawing !== unimplementedFunction && this.RemoveDrawing(true, this._selectedDoc); - const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); - drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); - } catch (err) { - console.error('Error regenerating drawing', err); - } - } + }) + ); }; /** diff --git a/src/client/views/smartdraw/StickerPalette.tsx b/src/client/views/smartdraw/StickerPalette.tsx index 352a02e32..d23763eb9 100644 --- a/src/client/views/smartdraw/StickerPalette.tsx +++ b/src/client/views/smartdraw/StickerPalette.tsx @@ -142,19 +142,20 @@ export class StickerPalette extends ObservableReactComponent { this._isLoading = true; + const prevDrawings = DocListCast(this._props.Document[DocData].data); this._props.Document[DocData].data = undefined; SmartDrawHandler.Instance.AddDrawing = this.addDrawing; this._canInteract = false; await Promise.all( Array.from({ length: 3 }).map((_, i) => { return this._showRegenerate - ? SmartDrawHandler.Instance.regenerate(this._opts, this._gptRes[i], this._userInput) + ? SmartDrawHandler.Instance.regenerate(prevDrawings, this._opts, this._gptRes[i], this._userInput) : SmartDrawHandler.Instance.drawWithGPT({ X: 0, Y: 0 }, this._userInput, this._opts.complexity, this._opts.size, this._opts.autoColor); }) ); @@ -181,12 +182,12 @@ export class StickerPalette extends ObservableReactComponent { - console.log('DIMENSIONS', width, height); let body = `{ "prompt": "${prompt}", "size": { "width": ${width}, "height": ${height}} }`; if (seed) { console.log('RECEIVED SEED', seed); -- cgit v1.2.3-70-g09d2 From dd0526a0a256fb3f1de9e0a2508566adcd6cd7e9 Mon Sep 17 00:00:00 2001 From: bobzel Date: Thu, 9 Jan 2025 00:02:10 -0500 Subject: fixed sizing of images created by firefly. added error message for failed firefly request. --- src/client/Network.ts | 2 +- .../collections/collectionFreeForm/MarqueeView.tsx | 4 +- src/client/views/smartdraw/DrawingFillHandler.tsx | 4 +- src/server/ApiManagers/FireflyManager.ts | 47 +++++++++++++--------- src/server/RouteManager.ts | 3 +- 5 files changed, 35 insertions(+), 25 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/Network.ts b/src/client/Network.ts index 9afdc844f..3b0406141 100644 --- a/src/client/Network.ts +++ b/src/client/Network.ts @@ -15,7 +15,7 @@ export namespace Networking { return (await fetch(relativeRoute)).text(); } - export async function PostToServer(relativeRoute: string, body?: unknown) { + export function PostToServer(relativeRoute: string, body?: unknown) { const options = { uri: ClientUtils.prepend(relativeRoute), method: 'POST', diff --git a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx index ddc50871d..5524fedb3 100644 --- a/src/client/views/collections/collectionFreeForm/MarqueeView.tsx +++ b/src/client/views/collections/collectionFreeForm/MarqueeView.tsx @@ -586,7 +586,7 @@ export class MarqueeView extends ObservableReactComponent { const selection: Doc[] = []; const selectFunc = (doc: Doc) => { const layoutDoc = Doc.Layout(doc); @@ -619,7 +619,7 @@ export class MarqueeView extends ObservableReactComponent doc.z !== undefined) .map(selectFunc); return selection; - } + }; @computed get marqueeDiv() { const cpt = this._lassoFreehand || !this._visible ? [0, 0] : [this._downX < this._lastX ? this._downX : this._lastX, this._downY < this._lastY ? this._downY : this._lastY]; diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index fea4acb67..96b21123b 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -38,8 +38,8 @@ export class DrawingFillHandler { { prompt: user_prompt || prompt, width: dims.width, height: dims.height, structureUrl, strength, styles }) .then((info: Upload.ImageInformation) => DocumentViewInternal.addDocTabFunc(Docs.Create.ImageDocument(info.accessPaths.agnostic.client, - { ai: 'firefly', ai_firefly_prompt: user_prompt || prompt, nativeWidth: dims.width, nativeHeight: dims.height }), OpenWhere.addRight) - ); // prettier-ignore + { ai: 'firefly', ai_firefly_prompt: user_prompt || prompt, _width: 500, data_nativeWidth: info.nativeWidth, data_nativeHeight: info.nativeHeight }), OpenWhere.addRight) + ).catch(e => alert("create image failed: " + e.toString())); // prettier-ignore }); } return false; diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 6daa5840e..a1f8fab8d 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -56,15 +56,22 @@ export default class FireflyManager extends ApiManager { ); uploadImageToDropbox = (fileUrl: string, dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN })) => - new Promise((res, rej) => + new Promise((res, rej) => fs.readFile(path.join(filesDirectory, `${Directory.images}/${path.basename(fileUrl)}`), undefined, (err, contents) => { if (err) { console.log('Error: ', err); rej(); } else { - dbx.filesUpload({ path: `/Apps/browndash/${path.basename(fileUrl)}`, contents }).then(response => { - dbx.filesGetTemporaryLink({ path: response.result.path_display ?? '' }).then(link => res(link.result.link)); - }); + dbx.filesUpload({ path: `/Apps/browndash/${path.basename(fileUrl)}`, contents }) + .then(response => { + dbx.filesGetTemporaryLink({ path: response.result.path_display ?? '' }) + .then(link => res(link.result.link)) + .catch(e => res(new Error(e.toString()))); + }) + .catch(e => { + console.log('Dropbox error:', e); + res(new Error(e.toString())); + }); } }) ); @@ -229,12 +236,14 @@ export default class FireflyManager extends ApiManager { subscription: '/queryFireflyImageFromStructure', secureHandler: async ({ req, res }) => this.uploadImageToDropbox(req.body.structureUrl).then(uploadUrl => - this.generateImageFromStructure(req.body.prompt, req.body.width, req.body.height, uploadUrl, req.body.strength, req.body.styles).then(fire => - DashUploadUtils.UploadImage(JSON.parse(fire ?? '').url).then(info => { - if (info instanceof Error) _invalid(res, info.message); - else _success(res, info); - }) - ) + uploadUrl instanceof Error + ? _invalid(res, uploadUrl.message) + : this.generateImageFromStructure(req.body.prompt, req.body.width, req.body.height, uploadUrl, req.body.strength, req.body.styles).then(fire => + DashUploadUtils.UploadImage(JSON.parse(fire ?? '').url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info); + }) + ) ), }); register({ @@ -267,14 +276,16 @@ export default class FireflyManager extends ApiManager { subscription: '/expandImage', secureHandler: ({ req, res }) => this.uploadImageToDropbox(req.body.file).then(uploadUrl => - this.expandImage(uploadUrl, req.body.prompt).then(text => { - if (text.error_code) _error(res, text.message); - else - DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => { - if (info instanceof Error) _invalid(res, info.message); - else _success(res, info); - }); - }) + uploadUrl instanceof Error + ? _invalid(res, uploadUrl.message) + : this.expandImage(uploadUrl, req.body.prompt).then(text => { + if (text.error_code) _error(res, text.message); + else + DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info); + }); + }) ), }); } diff --git a/src/server/RouteManager.ts b/src/server/RouteManager.ts index d8e0455f6..2f6cf80b5 100644 --- a/src/server/RouteManager.ts +++ b/src/server/RouteManager.ts @@ -39,8 +39,7 @@ export function _success(res: Response, body: any) { } export function _invalid(res: Response, message: string) { - res.statusMessage = message; - res.status(STATUS.BAD_REQUEST).send(); + res.status(STATUS.BAD_REQUEST).send(message); } export function _permissionDenied(res: Response, message?: string) { -- cgit v1.2.3-70-g09d2 From fd922d7898ed7a405ed47a7e48b85c582d787c07 Mon Sep 17 00:00:00 2001 From: eleanor-park Date: Fri, 10 Jan 2025 15:07:42 -0500 Subject: working on merge conflicts --- .../collectionFreeForm/CollectionFreeFormView.tsx | 9 ++-- src/client/views/nodes/DocumentView.scss | 2 + src/client/views/nodes/ImageBox.scss | 8 +++- src/client/views/nodes/ImageBox.tsx | 49 ++++++++++++++-------- src/client/views/smartdraw/DrawingFillHandler.tsx | 19 +++++++-- src/server/ApiManagers/FireflyManager.ts | 41 ++++++++++++------ 6 files changed, 89 insertions(+), 39 deletions(-) (limited to 'src/server/ApiManagers') diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 112bfd178..e1144f21a 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -2266,7 +2266,6 @@ export class CollectionFreeFormView extends CollectionSubView this._canInteract && (this._drawingFillInput = e.target.value))} />
- Reference Strength this._canInteract && (this._fireflyRefStrength = val as number))} valueLabelDisplay="auto" /> + Reference Strength