1+ /* global Summarizer */
12import DOMPurify from 'dompurify' ;
23import { marked } from 'marked' ;
34
@@ -58,18 +59,31 @@ async function onContentChange(newContent) {
5859
5960async function generateSummary ( text ) {
6061 try {
61- const session = await createSummarizer (
62- {
63- type : summaryTypeSelect . value ,
64- format : summaryFormatSelect . value ,
65- length : length . value
66- } ,
67- ( message , progress ) => {
68- console . log ( `${ message } (${ progress . loaded } /${ progress . total } )` ) ;
69- }
70- ) ;
71- const summary = await session . summarize ( text ) ;
72- session . destroy ( ) ;
62+ const options = {
63+ sharedContext : 'this is a website' ,
64+ type : summaryTypeSelect . value ,
65+ format : summaryFormatSelect . value ,
66+ length : length . value
67+ } ;
68+
69+ const availability = await Summarizer . availability ( ) ;
70+ let summarizer ;
71+ if ( availability === 'unavailable' ) {
72+ return 'Summarizer API is not available' ;
73+ }
74+ if ( availability === 'available' ) {
75+ // The Summarizer API can be used immediately .
76+ summarizer = await Summarizer . create ( options ) ;
77+ } else {
78+ // The Summarizer API can be used after the model is downloaded.
79+ summarizer = await Summarizer . create ( options ) ;
80+ summarizer . addEventListener ( 'downloadprogress' , ( e ) => {
81+ console . log ( `Downloaded ${ e . loaded * 100 } %` ) ;
82+ } ) ;
83+ await summarizer . ready ;
84+ }
85+ const summary = await summarizer . summarize ( text ) ;
86+ summarizer . destroy ( ) ;
7387 return summary ;
7488 } catch ( e ) {
7589 console . log ( 'Summary generation failed' ) ;
@@ -78,27 +92,6 @@ async function generateSummary(text) {
7892 }
7993}
8094
81- async function createSummarizer ( config , downloadProgressCallback ) {
82- if ( ! window . Summarizer ) {
83- throw new Error ( 'AI Summarization is not supported in this browser' ) ;
84- }
85- const available = await window . Summarizer . availability ( ) ;
86- if ( available === 'unavailable' ) {
87- throw new Error ( 'AI Summarization is not supported' ) ;
88- }
89- const summarizationSession = await window . Summarizer . create (
90- config ,
91- downloadProgressCallback
92- ) ;
93- if ( available === 'downloadable' ) {
94- summarizationSession . addEventListener (
95- 'downloadprogress' ,
96- downloadProgressCallback
97- ) ;
98- }
99- return summarizationSession ;
100- }
101-
10295async function showSummary ( text ) {
10396 summaryElement . innerHTML = DOMPurify . sanitize ( marked . parse ( text ) ) ;
10497}
0 commit comments