From ed94cc8fb516455dbeea223d0fab25e4fb1c1d78 Mon Sep 17 00:00:00 2001 From: Sophie Zhang Date: Mon, 27 Feb 2023 16:56:02 -0500 Subject: feat: added summarization functionality to WebBox and cleaned up code --- src/client/apis/gpt/Summarization.ts | 20 +++- src/client/views/MainView.tsx | 1 + src/client/views/nodes/PDFBox.tsx | 1 + src/client/views/nodes/WebBox.tsx | 6 ++ .../views/nodes/formattedText/FormattedTextBox.tsx | 1 - src/client/views/pdf/AnchorMenu.tsx | 39 ++++--- src/client/views/pdf/GPTPopup.scss | 91 ++++++++++++++-- src/client/views/pdf/GPTPopup.tsx | 115 +++++++++++++++++++-- src/client/views/pdf/PDFViewer.tsx | 19 ++-- 9 files changed, 243 insertions(+), 50 deletions(-) (limited to 'src') diff --git a/src/client/apis/gpt/Summarization.ts b/src/client/apis/gpt/Summarization.ts index 931e0e48f..c0dcc0267 100644 --- a/src/client/apis/gpt/Summarization.ts +++ b/src/client/apis/gpt/Summarization.ts @@ -1,22 +1,32 @@ import { Configuration, OpenAIApi } from 'openai'; +/** + * Summarizes the inputted text with OpenAI. + * + * @param text Text to summarize + * @returns Summary of text + */ const gptSummarize = async (text: string) => { text += '.'; + const model = 'text-curie-001'; // Most advanced: text-davinci-003 + const maxTokens = 200; + const temp = 0.8; + try { const configuration = new Configuration({ apiKey: process.env.OPENAI_KEY, }); const openai = new OpenAIApi(configuration); const response = await openai.createCompletion({ - model: 'text-curie-001', - max_tokens: 256, - temperature: 0.7, - prompt: `Summarize this text in one sentence: ${text}`, + model: model, + max_tokens: maxTokens, + temperature: temp, + prompt: `Summarize this text: ${text}`, }); return response.data.choices[0].text; } catch (err) { console.log(err); - return ''; + return 'Error connecting with API.'; } }; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index da64e7c12..d7603cf5a 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -245,6 +245,7 @@ export class MainView extends React.Component { library.add( ...[ + fa.faExclamationCircle, fa.faEdit, fa.faTrash, fa.faTrashAlt, diff --git a/src/client/views/nodes/PDFBox.tsx b/src/client/views/nodes/PDFBox.tsx index b88ac113e..40c04c08f 100644 --- a/src/client/views/nodes/PDFBox.tsx +++ b/src/client/views/nodes/PDFBox.tsx @@ -485,6 +485,7 @@ export class PDFBox extends ViewBoxAnnotatableComponent this.createTextAnnotation(sel, !sel.isCollapsed ? sel.getRangeAt(0) : undefined); AnchorMenu.Instance.jumpTo(e.clientX * scale + mainContBounds.translateX, e.clientY * scale + mainContBounds.translateY - NumCast(this.layoutDoc._scrollTop) * scale); + // Changing which document to add the annotation to (the currently selected WebBox) + GPTPopup.Instance.setSidebarId(`${this.props.fieldKey}-${this._urlHash}-sidebar`); + GPTPopup.Instance.addDoc = this.sidebarAddDocument; } } }; @@ -780,6 +785,7 @@ export class WebBox extends ViewBoxAnnotatableComponent { + console.log(annotationKey); (doc instanceof Doc ? [doc] : doc).forEach(doc => (doc.webUrl = this._url)); return this.addDocument(doc, annotationKey); }; diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx index 683ccb9c4..b9327db0d 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx +++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx @@ -888,7 +888,6 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent { if (this._editorView && this._recording) { this.stopDictation(true); diff --git a/src/client/views/pdf/AnchorMenu.tsx b/src/client/views/pdf/AnchorMenu.tsx index 6bcfbe4c2..8f9261614 100644 --- a/src/client/views/pdf/AnchorMenu.tsx +++ b/src/client/views/pdf/AnchorMenu.tsx @@ -45,7 +45,7 @@ export class AnchorMenu extends AntimodeMenu { @observable public Highlighting: boolean = false; @observable public Status: 'marquee' | 'annotation' | '' = ''; - // GPT additions (flow 2) + // GPT additions @observable private summarizedText: string = ''; @observable private loadingSummary: boolean = false; @observable private showGPTPopup: boolean = false; @@ -63,7 +63,7 @@ export class AnchorMenu extends AntimodeMenu { }; private selectedText: string = ''; - setSelectedText = (txt: string) => { + public setSelectedText = (txt: string) => { this.selectedText = txt; }; @@ -71,9 +71,6 @@ export class AnchorMenu extends AntimodeMenu { public OnCrop: (e: PointerEvent) => void = unimplementedFunction; public OnClick: (e: PointerEvent) => void = unimplementedFunction; - public OnSummary: (e: PointerEvent) => Promise = () => { - return new Promise(() => {}); - }; public OnAudio: (e: PointerEvent) => void = unimplementedFunction; public StartDrag: (e: PointerEvent, ele: HTMLElement) => void = unimplementedFunction; public StartCropDrag: (e: PointerEvent, ele: HTMLElement) => void = unimplementedFunction; @@ -123,14 +120,27 @@ export class AnchorMenu extends AntimodeMenu { ); } - getGPTSummary = (e: React.PointerEvent) => { - setupMoveUpEvents(this, e, returnFalse, returnFalse, e => this.OnSummary?.(e)); + /** + * Returns a mock summary simulating an API call. + * @returns A Promise that resolves into a string + */ + mockSummarize = async (): Promise => { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve('Mock summary. This is a summary of the highlighted text.'); + }, 1000); + }); }; + /** + * Invokes the API with the selected text and stores it in the summarized text. + * @param e pointer down event + */ invokeGPT = async (e: React.PointerEvent) => { this.setGPTPopupVis(true); this.setLoading(true); const res = await gptSummarize(this.selectedText); + // const res = await this.mockSummarize(); if (res) { this.setSummarizedText(res); } else { @@ -243,12 +253,15 @@ export class AnchorMenu extends AntimodeMenu { - Summarize with AI}> - - - + {/* GPT Summarize icon only shows up when text is highlighted, not on marquee selection*/} + {AnchorMenu.Instance.StartCropDrag === unimplementedFunction && ( + Summarize with AI}> + + + )} + {AnchorMenu.Instance.OnAudio === unimplementedFunction ? null : ( Click to Record Annotation}> + + + ) : ( +
+ + + +
+ )} + + )} + {this.summaryDone && ( +
+ + AI generated responses can contain inaccurate or misleading content.{' '} + + Learn More + +
)} ); diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index 324f31f23..408ba07d1 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -25,6 +25,7 @@ import { Annotation } from './Annotation'; import './PDFViewer.scss'; import React = require('react'); import { gptSummarize } from '../../apis/gpt/Summarization'; +import { GPTPopup } from './GPTPopup'; const PDFJSViewer = require('pdfjs-dist/web/pdf_viewer'); const pdfjsLib = require('pdfjs-dist'); const _global = (window /* browser */ || global) /* node */ as any; @@ -41,6 +42,7 @@ interface IViewerProps extends FieldViewProps { fieldKey: string; pdf: Pdfjs.PDFDocumentProxy; url: string; + sidebarAddDoc: (doc: Doc | Doc[], sidebarKey?: string | undefined) => boolean; loaded?: (nw: number, nh: number, np: number) => void; setPdfViewer: (view: PDFViewer) => void; anchorMenuClick?: () => undefined | ((anchor: Doc, summarize?: boolean) => void); @@ -83,19 +85,6 @@ export class PDFViewer extends React.Component { return AnchorMenu.Instance?.GetAnchor; } - // Fields for using GPT to summarize selected text - private _summaryText: string = ''; - setSummaryText = async () => { - try { - const summary = await gptSummarize(this.selectionText()); - this._summaryText = `Summary: ${summary}`; - } catch (err) { - console.log(err); - this._summaryText = 'Failed to fetch summary.'; - } - }; - summaryText = () => this._summaryText; - selectionText = () => this._selectionText; selectionContent = () => this._selectionContent; @@ -435,6 +424,10 @@ export class PDFViewer extends React.Component { this.createTextAnnotation(sel, sel.getRangeAt(0)); AnchorMenu.Instance.jumpTo(e.clientX, e.clientY); } + + // Changing which document to add the annotation to (the currently selected PDF) + GPTPopup.Instance.setSidebarId('data-sidebar'); + GPTPopup.Instance.addDoc = this.props.sidebarAddDoc; }; @action -- cgit v1.2.3-70-g09d2 From 08e15b05cd014f99726826c9db407e738040cdbb Mon Sep 17 00:00:00 2001 From: Sophie Zhang Date: Mon, 27 Feb 2023 17:16:07 -0500 Subject: feat: deleted unnecessary props from MarqueeAnnotator --- src/client/apis/gpt/Summarization.ts | 2 +- src/client/views/MarqueeAnnotator.tsx | 6 ------ src/client/views/pdf/PDFViewer.tsx | 2 -- 3 files changed, 1 insertion(+), 9 deletions(-) (limited to 'src') diff --git a/src/client/apis/gpt/Summarization.ts b/src/client/apis/gpt/Summarization.ts index c0dcc0267..ba98ad591 100644 --- a/src/client/apis/gpt/Summarization.ts +++ b/src/client/apis/gpt/Summarization.ts @@ -10,7 +10,7 @@ const gptSummarize = async (text: string) => { text += '.'; const model = 'text-curie-001'; // Most advanced: text-davinci-003 const maxTokens = 200; - const temp = 0.8; + const temp = 0.5; try { const configuration = new Configuration({ diff --git a/src/client/views/MarqueeAnnotator.tsx b/src/client/views/MarqueeAnnotator.tsx index 9e9f24393..8757ac7bf 100644 --- a/src/client/views/MarqueeAnnotator.tsx +++ b/src/client/views/MarqueeAnnotator.tsx @@ -28,8 +28,6 @@ export interface MarqueeAnnotatorProps { docView: DocumentView; savedAnnotations: () => ObservableMap; selectionText: () => string; - summaryText: () => string; - setSummaryText: () => Promise; annotationLayer: HTMLDivElement; addDocument: (doc: Doc) => boolean; getPageFromScroll?: (top: number) => number; @@ -52,10 +50,6 @@ export class MarqueeAnnotator extends React.Component { AnchorMenu.Instance.OnCrop = (e: PointerEvent) => this.props.anchorMenuCrop?.(this.highlight('', true), true); AnchorMenu.Instance.OnClick = (e: PointerEvent) => this.props.anchorMenuClick?.()?.(this.highlight(this.props.highlightDragSrcColor ?? 'rgba(173, 216, 230, 0.75)', true)); - AnchorMenu.Instance.OnSummary = async (e: PointerEvent) => { - await this.props.setSummaryText(); - this.props.anchorMenuClick?.()?.(this.highlight('', true, undefined, undefined, true)); - }; AnchorMenu.Instance.OnAudio = unimplementedFunction; AnchorMenu.Instance.Highlight = this.highlight; AnchorMenu.Instance.GetAnchor = (savedAnnotations?: ObservableMap, addAsAnnotation?: boolean) => this.highlight('rgba(173, 216, 230, 0.75)', true, savedAnnotations, true); diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index 408ba07d1..6e268c561 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -607,8 +607,6 @@ export class PDFViewer extends React.Component { finishMarquee={this.finishMarquee} savedAnnotations={this.savedAnnotations} selectionText={this.selectionText} - setSummaryText={this.setSummaryText} - summaryText={this.summaryText} annotationLayer={this._annotationLayer.current} mainCont={this._mainCont.current} anchorMenuCrop={this._textSelecting ? undefined : this.crop} -- cgit v1.2.3-70-g09d2 From f189ce6f25b91fcd402b7e81ba8ed378e39e6142 Mon Sep 17 00:00:00 2001 From: Sophie Zhang Date: Wed, 1 Mar 2023 23:33:01 -0500 Subject: Added text completion --- src/client/apis/gpt/Summarization.ts | 45 ++++--- .../nodes/formattedText/FormattedTextBox.scss | 4 + .../views/nodes/formattedText/FormattedTextBox.tsx | 129 ++++++++++++++++----- src/client/views/pdf/AnchorMenu.tsx | 26 ++++- src/client/views/pdf/PDFViewer.tsx | 1 - 5 files changed, 154 insertions(+), 51 deletions(-) (limited to 'src') diff --git a/src/client/apis/gpt/Summarization.ts b/src/client/apis/gpt/Summarization.ts index ba98ad591..b65736237 100644 --- a/src/client/apis/gpt/Summarization.ts +++ b/src/client/apis/gpt/Summarization.ts @@ -1,27 +1,41 @@ import { Configuration, OpenAIApi } from 'openai'; +enum GPTCallType { + SUMMARY = 'summary', + COMPLETION = 'completion', +} + +type GPTCallOpts = { + model: string; + maxTokens: number; + temp: number; + prompt: string; +}; + +const callTypeMap: { [type: string]: GPTCallOpts } = { + summary: { model: 'text-davinci-003', maxTokens: 100, temp: 0.5, prompt: 'Summarize this text: ' }, + completion: { model: 'text-davinci-003', maxTokens: 100, temp: 0.5, prompt: '' }, +}; + /** - * Summarizes the inputted text with OpenAI. - * - * @param text Text to summarize - * @returns Summary of text + * Calls the OpenAI API. + * + * @param inputText Text to process + * @returns AI Output */ -const gptSummarize = async (text: string) => { - text += '.'; - const model = 'text-curie-001'; // Most advanced: text-davinci-003 - const maxTokens = 200; - const temp = 0.5; - +const gptAPICall = async (inputText: string, callType: GPTCallType) => { + if (callType === GPTCallType.SUMMARY) inputText += '.'; + const opts: GPTCallOpts = callTypeMap[callType]; try { const configuration = new Configuration({ apiKey: process.env.OPENAI_KEY, }); const openai = new OpenAIApi(configuration); const response = await openai.createCompletion({ - model: model, - max_tokens: maxTokens, - temperature: temp, - prompt: `Summarize this text: ${text}`, + model: opts.model, + max_tokens: opts.maxTokens, + temperature: opts.temp, + prompt: `${opts.prompt}${inputText}`, }); return response.data.choices[0].text; } catch (err) { @@ -30,4 +44,5 @@ const gptSummarize = async (text: string) => { } }; -export { gptSummarize }; + +export { gptAPICall, GPTCallType}; diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.scss b/src/client/views/nodes/formattedText/FormattedTextBox.scss index cbe0a465d..fd7fbb333 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.scss +++ b/src/client/views/nodes/formattedText/FormattedTextBox.scss @@ -149,6 +149,10 @@ audiotag:hover { } } +.gpt-typing-wrapper { + padding: 10px; +} + // .menuicon { // display: inline-block; // border-right: 1px solid rgba(0, 0, 0, 0.2); diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx index b9327db0d..35c845deb 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx +++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx @@ -64,12 +64,21 @@ import { SummaryView } from './SummaryView'; import applyDevTools = require('prosemirror-dev-tools'); import React = require('react'); import { Configuration, OpenAIApi } from 'openai'; +import { gptAPICall, GPTCallType } from '../../../apis/gpt/Summarization'; +import ReactLoading from 'react-loading'; +import Typist from 'react-typist'; const translateGoogleApi = require('translate-google-api'); export const GoogleRef = 'googleDocId'; type PullHandler = (exportState: Opt, dataDoc: Doc) => void; +enum GPTStatus { + LOADING, + TYPING, + NONE, +} + @observer export class FormattedTextBox extends ViewBoxAnnotatableComponent() { public static LayoutString(fieldStr: string) { @@ -172,6 +181,19 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent { + this.gptStatus = status; + }; + public static PasteOnLoad: ClipboardEvent | undefined; public static SelectOnLoad = ''; public static DontSelectInitialText = false; // whether initial text should be selected or not @@ -840,14 +862,48 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent this.generateImage(), icon: 'star' }); + optionItems.push({ description: `Ask GPT-3`, event: () => this.askGPT(), icon: 'lightbulb' }); optionItems.push({ description: !this.Document._singleLine ? 'Make Single Line' : 'Make Multi Line', event: () => (this.layoutDoc._singleLine = !this.layoutDoc._singleLine), icon: 'expand-arrows-alt' }); optionItems.push({ description: `${this.Document._autoHeight ? 'Lock' : 'Auto'} Height`, event: () => (this.layoutDoc._autoHeight = !this.layoutDoc._autoHeight), icon: 'plus' }); !options && cm.addItem({ description: 'Options...', subitems: optionItems, icon: 'eye' }); this._downX = this._downY = Number.NaN; }; + mockGPT = async (): Promise => { + return new Promise((resolve, reject) => { + setTimeout(() => { + resolve('Mock GPT Call.'); + }, 2000); + }); + }; + + askGPT = action(async () => { + try { + this.gptPrompt = (this.dataDoc.text as RichTextField)?.Text; + this.setGPTStatus(GPTStatus.LOADING); + let res = await gptAPICall((this.dataDoc.text as RichTextField)?.Text, GPTCallType.COMPLETION); + // let res = await this.mockGPT(); + if (res) { + this.gptRes = res; + this.setGPTStatus(GPTStatus.TYPING); + } else { + this.setGPTStatus(GPTStatus.NONE); + } + } catch (err) { + console.log(err); + this.dataDoc.text = (this.dataDoc.text as RichTextField)?.Text + 'Something went wrong'; + this.setGPTStatus(GPTStatus.NONE); + } + }); + + setGPTText = action(() => { + this.dataDoc.text = (this.dataDoc.text as RichTextField)?.Text + this.gptRes; + this.gptRes = ''; + this.setGPTStatus(GPTStatus.NONE); + }); + generateImage = async () => { - console.log("Generate image from text: ", (this.dataDoc.text as RichTextField)?.Text); + console.log('Generate image from text: ', (this.dataDoc.text as RichTextField)?.Text); try { const configuration = new Configuration({ apiKey: process.env.OPENAI_KEY, @@ -856,17 +912,17 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent { if (this._editorView && this._recording) { @@ -1942,29 +1997,45 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent -
+ {this.gptStatus === GPTStatus.NONE || this.gptStatus === GPTStatus.LOADING ? (
-
+ onScroll={this.onScroll} + onDrop={this.ondrop}> +
+
+ ) : ( +
+
{this.gptPrompt}
+
+ { + this.setGPTText(); + }}> +
{this.gptRes}
+
+
+ )} {this.noSidebar || this.props.dontSelectOnLoad || !this.SidebarShown || this.sidebarWidthPercent === '0%' ? null : this.sidebarCollection} {this.noSidebar || this.Document._noSidebar || this.props.dontSelectOnLoad || this.Document._singleLine ? null : this.sidebarHandle} {this.audioHandle} diff --git a/src/client/views/pdf/AnchorMenu.tsx b/src/client/views/pdf/AnchorMenu.tsx index 8f9261614..04904b3b1 100644 --- a/src/client/views/pdf/AnchorMenu.tsx +++ b/src/client/views/pdf/AnchorMenu.tsx @@ -10,7 +10,7 @@ import { SelectionManager } from '../../util/SelectionManager'; import { AntimodeMenu, AntimodeMenuProps } from '../AntimodeMenu'; import { LinkPopup } from '../linking/LinkPopup'; import { ButtonDropdown } from '../nodes/formattedText/RichTextMenu'; -import { gptSummarize } from '../../apis/gpt/Summarization'; +import { gptAPICall, GPTCallType } from '../../apis/gpt/Summarization'; import { GPTPopup } from './GPTPopup'; import './AnchorMenu.scss'; @@ -136,16 +136,17 @@ export class AnchorMenu extends AntimodeMenu { * Invokes the API with the selected text and stores it in the summarized text. * @param e pointer down event */ - invokeGPT = async (e: React.PointerEvent) => { + gptSummarize = async (e: React.PointerEvent) => { this.setGPTPopupVis(true); this.setLoading(true); - const res = await gptSummarize(this.selectedText); + const res = await gptAPICall(this.selectedText, GPTCallType.SUMMARY); // const res = await this.mockSummarize(); if (res) { this.setSummarizedText(res); } else { this.setSummarizedText('Something went wrong.'); } + this.setLoading(false); }; @@ -243,6 +244,19 @@ export class AnchorMenu extends AntimodeMenu { this.highlightColor = Utils.colorString(col); }; + /** + * Returns whether the selected text can be summarized. The goal is to have + * all selected text available to summarize but its only supported for pdf and web ATM. + * @returns Whether the GPT icon for summarization should appear + */ + canSummarize = (): boolean => { + const docs = SelectionManager.Docs(); + if (docs.length > 0) { + return docs[0].type === 'pdf' || docs[0].type === 'web'; + } + return false; + }; + render() { const buttons = this.Status === 'marquee' ? ( @@ -254,14 +268,14 @@ export class AnchorMenu extends AntimodeMenu { {/* GPT Summarize icon only shows up when text is highlighted, not on marquee selection*/} - {AnchorMenu.Instance.StartCropDrag === unimplementedFunction && ( + {AnchorMenu.Instance.StartCropDrag === unimplementedFunction && this.canSummarize() && ( Summarize with AI
}> -
)} - + {AnchorMenu.Instance.OnAudio === unimplementedFunction ? null : ( Click to Record Annotation}>