Upload folder using huggingface_hub
Browse files- static/help0.html +23 -15
- static/javascript/rag_mgr.js +4 -0
- static/javascript/rag_rqs.js +1 -9
- static/javascript/rag_ui.js +3 -6
- static/js/ragrqs.min.js +13 -12
static/help0.html
CHANGED
@@ -48,16 +48,15 @@
|
|
48 |
<p class="center"> Comandi lato destro in basso: </p>
|
49 |
</div>
|
50 |
<div>
|
51 |
-
Documeti => RAG => Contesto => Query:
|
52 |
<p>
|
53 |
Input per la query da utilizzare per la elaborazione RAG.
|
|
|
54 |
Ogni documento in archivio è diviso in parti compatibili con l'ampiezza della finestra
|
55 |
di input sel Model utilizzato.
|
56 |
</p>
|
57 |
<p>
|
58 |
-
Per ogni parte esegue una query utilizzandola
|
59 |
-
per estrarre informazioni/concetti pertinenti alla stessa.
|
60 |
-
|
61 |
</p>
|
62 |
<p>
|
63 |
Il risultato di ogni query è archiviato nella memoria locale.
|
@@ -71,11 +70,10 @@
|
|
71 |
</p>
|
72 |
</div>
|
73 |
<div>
|
74 |
-
Contesto => Query:
|
75 |
<p>
|
76 |
Input per query che utilizzano il contesto creato con l'elaborazione RAG.
|
77 |
Inizia una conversazione.
|
78 |
-
Utilizzare il pulsante o premere RETURN.
|
79 |
</p>
|
80 |
<p>
|
81 |
La conversazioe ha senso relativamente all'elaborazione RAG se ogni query è una variazione / approfondimento della query iiziale.
|
@@ -87,6 +85,7 @@
|
|
87 |
Cancella la storia della conversazione attiva.
|
88 |
Non vengoo cancellati i dati dell'laborazione RAG
|
89 |
</p>
|
|
|
90 |
</div>
|
91 |
<!-- -->
|
92 |
<hr>
|
@@ -134,7 +133,7 @@
|
|
134 |
Con il clic del mouse sul nome di un documento si visualizza.
|
135 |
</p>
|
136 |
</div>
|
137 |
-
|
138 |
<div>
|
139 |
Numero query:
|
140 |
<p>
|
@@ -142,7 +141,7 @@
|
|
142 |
necessaire per analizzare tutti i documenti caricati.
|
143 |
</p>
|
144 |
</div>
|
145 |
-
|
146 |
|
147 |
<div>
|
148 |
Cancella Dati:
|
@@ -159,11 +158,11 @@
|
|
159 |
</p>
|
160 |
</div>
|
161 |
|
162 |
-
<!-- -->
|
163 |
|
164 |
<p class="center">Sequenza Comandi Interrogazione -Conversazione</p>
|
165 |
<div>
|
166 |
-
Archivia nella memoria locale
|
167 |
<p>
|
168 |
Utilizza i dati di esempio per le prme prove.
|
169 |
Utilizza upload file o upload dir per i documenti da leggere dal tuo computer.
|
@@ -180,22 +179,31 @@
|
|
180 |
Click sul bottone rosso in basso a destrai.DOcuento => RAG =>Contetso => QURY
|
181 |
<p>
|
182 |
Viene lanciata una sequenzaa di elaborazione per analizzare i documeti sulla base della query.
|
183 |
-
Se il log è attivo vedrai la sequnza di elaborazione.
|
184 |
-
|
|
|
|
|
|
|
|
|
185 |
Alla fine del proesso sarà visualizzata la risposta.
|
186 |
</p>
|
187 |
</div>
|
188 |
|
189 |
<div>
|
190 |
-
Click sul bottone verdo in basso a
|
191 |
<p>
|
192 |
Inizia una comnversazione utilizzando le informazion precedentemnete raccolte dai documeti-
|
193 |
-
Puoi inviare domande successive
|
|
|
194 |
È FONDAMENTALE che le query siano approfondimenti e/o chairimenti della query iniziale.
|
195 |
In caso conrtario non si sfrutta il Contesto creato dall'elaborazione precdente.
|
|
|
196 |
Quindi per una query completamnete nuova (sempre relativa ai documeti archviati) è necessario inizare una nuova elaborazione.
|
|
|
197 |
Il comando cancella, oltre a cancellare il campo di input canella anche la sequnza query-risposte della
|
198 |
-
conversazione.
|
|
|
|
|
199 |
</p>
|
200 |
</div>
|
201 |
|
|
|
48 |
<p class="center"> Comandi lato destro in basso: </p>
|
49 |
</div>
|
50 |
<div>
|
51 |
+
Documeti => RAG => Contesto => Query: (Pulsante Rosso)
|
52 |
<p>
|
53 |
Input per la query da utilizzare per la elaborazione RAG.
|
54 |
+
<br>
|
55 |
Ogni documento in archivio è diviso in parti compatibili con l'ampiezza della finestra
|
56 |
di input sel Model utilizzato.
|
57 |
</p>
|
58 |
<p>
|
59 |
+
Per ogni parte esegue una query utilizzandola per estrarre informazioni/concetti pertinenti alla stessa.
|
|
|
|
|
60 |
</p>
|
61 |
<p>
|
62 |
Il risultato di ogni query è archiviato nella memoria locale.
|
|
|
70 |
</p>
|
71 |
</div>
|
72 |
<div>
|
73 |
+
Contesto => Query: (Pulsante Verde / Invio)
|
74 |
<p>
|
75 |
Input per query che utilizzano il contesto creato con l'elaborazione RAG.
|
76 |
Inizia una conversazione.
|
|
|
77 |
</p>
|
78 |
<p>
|
79 |
La conversazioe ha senso relativamente all'elaborazione RAG se ogni query è una variazione / approfondimento della query iiziale.
|
|
|
85 |
Cancella la storia della conversazione attiva.
|
86 |
Non vengoo cancellati i dati dell'laborazione RAG
|
87 |
</p>
|
88 |
+
Per andare a capo: Maiusc. + Invio
|
89 |
</div>
|
90 |
<!-- -->
|
91 |
<hr>
|
|
|
133 |
Con il clic del mouse sul nome di un documento si visualizza.
|
134 |
</p>
|
135 |
</div>
|
136 |
+
|
137 |
<div>
|
138 |
Numero query:
|
139 |
<p>
|
|
|
141 |
necessaire per analizzare tutti i documenti caricati.
|
142 |
</p>
|
143 |
</div>
|
144 |
+
|
145 |
|
146 |
<div>
|
147 |
Cancella Dati:
|
|
|
158 |
</p>
|
159 |
</div>
|
160 |
|
161 |
+
<!-- -->
|
162 |
|
163 |
<p class="center">Sequenza Comandi Interrogazione -Conversazione</p>
|
164 |
<div>
|
165 |
+
Archivia nella memoria locale uno o più documenti:
|
166 |
<p>
|
167 |
Utilizza i dati di esempio per le prme prove.
|
168 |
Utilizza upload file o upload dir per i documenti da leggere dal tuo computer.
|
|
|
179 |
Click sul bottone rosso in basso a destrai.DOcuento => RAG =>Contetso => QURY
|
180 |
<p>
|
181 |
Viene lanciata una sequenzaa di elaborazione per analizzare i documeti sulla base della query.
|
182 |
+
Se il log è attivo vedrai la sequnza di elaborazione.
|
183 |
+
<br>
|
184 |
+
Il loro numero dipende dalle dimensioni dei documenti.
|
185 |
+
<br>
|
186 |
+
l menu puoi utilizzare il comando "Num Query" per vedere quante elaborazioni saranno fatte per ogi documento.
|
187 |
+
<br>
|
188 |
Alla fine del proesso sarà visualizzata la risposta.
|
189 |
</p>
|
190 |
</div>
|
191 |
|
192 |
<div>
|
193 |
+
Click sul bottone verdo in basso a destra (oppure Invio). Contesto => Query
|
194 |
<p>
|
195 |
Inizia una comnversazione utilizzando le informazion precedentemnete raccolte dai documeti-
|
196 |
+
Puoi inviare domande successive di approfondimento e chiarmento .
|
197 |
+
<br>
|
198 |
È FONDAMENTALE che le query siano approfondimenti e/o chairimenti della query iniziale.
|
199 |
In caso conrtario non si sfrutta il Contesto creato dall'elaborazione precdente.
|
200 |
+
<br>
|
201 |
Quindi per una query completamnete nuova (sempre relativa ai documeti archviati) è necessario inizare una nuova elaborazione.
|
202 |
+
<br>
|
203 |
Il comando cancella, oltre a cancellare il campo di input canella anche la sequnza query-risposte della
|
204 |
+
conversazione.
|
205 |
+
<br>
|
206 |
+
NON cancell i dati dell'elaborazione iniziale.
|
207 |
</p>
|
208 |
</div>
|
209 |
|
static/javascript/rag_mgr.js
CHANGED
@@ -102,6 +102,10 @@ const Rag = {
|
|
102 |
this.readRespsFromDb();
|
103 |
this.readFromDb();
|
104 |
},
|
|
|
|
|
|
|
|
|
105 |
saveToDb() {
|
106 |
const js = {
|
107 |
context: this.ragContext,
|
|
|
102 |
this.readRespsFromDb();
|
103 |
this.readFromDb();
|
104 |
},
|
105 |
+
returnOk() {
|
106 |
+
const ok = this.ragContext.length > 10;
|
107 |
+
return ok;
|
108 |
+
},
|
109 |
saveToDb() {
|
110 |
const js = {
|
111 |
context: this.ragContext,
|
static/javascript/rag_rqs.js
CHANGED
@@ -19,7 +19,7 @@
|
|
19 |
*/
|
20 |
|
21 |
"use strict";
|
22 |
-
const VERS = "0.1.
|
23 |
|
24 |
var xlog = console.log;
|
25 |
var xerror = console.error;
|
@@ -143,14 +143,6 @@ function elencoDati(e) {
|
|
143 |
wnds.wpre.show(msg);
|
144 |
}
|
145 |
|
146 |
-
//elenco documenti in memoria
|
147 |
-
// function elencoDocs(e) {
|
148 |
-
// DataMgr.readDbDocNames();
|
149 |
-
// const arr = DataMgr.doc_names;
|
150 |
-
// const s = arr.join("\n");
|
151 |
-
// wnds.wpre.show(s);
|
152 |
-
// }
|
153 |
-
|
154 |
//visualizza docuemnto
|
155 |
const showT = (n) => {
|
156 |
const arr = DataMgr.docs;
|
|
|
19 |
*/
|
20 |
|
21 |
"use strict";
|
22 |
+
const VERS = "0.1.48 (26-08-2024)";
|
23 |
|
24 |
var xlog = console.log;
|
25 |
var xerror = console.error;
|
|
|
143 |
wnds.wpre.show(msg);
|
144 |
}
|
145 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
146 |
//visualizza docuemnto
|
147 |
const showT = (n) => {
|
148 |
const arr = DataMgr.docs;
|
static/javascript/rag_ui.js
CHANGED
@@ -231,13 +231,14 @@ const TextInput = {
|
|
231 |
},
|
232 |
handleEnter(e) {
|
233 |
if (e.key === "Enter" && !e.shiftKey) {
|
|
|
234 |
e.preventDefault();
|
235 |
this.send2();
|
236 |
}
|
237 |
},
|
238 |
|
239 |
// legge i documenti dal DBlocale
|
240 |
-
//
|
241 |
// crea il contesto
|
242 |
async send() {
|
243 |
const q = this.inp.value;
|
@@ -295,10 +296,6 @@ const TextInput = {
|
|
295 |
hideSpinner();
|
296 |
},
|
297 |
clear() {
|
298 |
-
// let s = "messaggio di prova per vedere la massima larghezza";
|
299 |
-
// for (let i = 0; i < 40; i++) {
|
300 |
-
// UaLog.log(s);
|
301 |
-
// }
|
302 |
const ok = confirm("Confermi cancellazione conversazione? ");
|
303 |
if (!ok) return;
|
304 |
this.inp.value = "";
|
@@ -306,7 +303,7 @@ const TextInput = {
|
|
306 |
ThreadMgr.init();
|
307 |
},
|
308 |
};
|
309 |
-
|
310 |
const setOutText = (txt) => {
|
311 |
let out = document.getElementById("id-text-out");
|
312 |
const h = `<pre class="pre-text"></pre>`;
|
|
|
231 |
},
|
232 |
handleEnter(e) {
|
233 |
if (e.key === "Enter" && !e.shiftKey) {
|
234 |
+
if (!Rag.returnOk()) return;
|
235 |
e.preventDefault();
|
236 |
this.send2();
|
237 |
}
|
238 |
},
|
239 |
|
240 |
// legge i documenti dal DBlocale
|
241 |
+
// salva le risposte RAG
|
242 |
// crea il contesto
|
243 |
async send() {
|
244 |
const q = this.inp.value;
|
|
|
296 |
hideSpinner();
|
297 |
},
|
298 |
clear() {
|
|
|
|
|
|
|
|
|
299 |
const ok = confirm("Confermi cancellazione conversazione? ");
|
300 |
if (!ok) return;
|
301 |
this.inp.value = "";
|
|
|
303 |
ThreadMgr.init();
|
304 |
},
|
305 |
};
|
306 |
+
|
307 |
const setOutText = (txt) => {
|
308 |
let out = document.getElementById("id-text-out");
|
309 |
const h = `<pre class="pre-text"></pre>`;
|
static/js/ragrqs.min.js
CHANGED
@@ -33,15 +33,16 @@ function getErrorInfo(a){let b={};try{b=JSON.parse(a.message)}catch(c){a=`getErr
|
|
33 |
*/
|
34 |
const MAX_PROMPT_LENGTH=81920,PROMPT_DECR=2048,TIMEOUT=6E4;function wait(a){return new Promise(b=>setTimeout(b,1E3*a))}async function example(){console.log("Inizio attesa...");await wait(5);console.log("Fine attesa!")}example();
|
35 |
const truncInput=(a,b)=>a.substring(0,a.length-b),setMaxLen=a=>a.substring(0,MAX_PROMPT_LENGTH-1E3),getPartSize=(a,b,c)=>{c=MAX_PROMPT_LENGTH-c;a.length+b.length<c?c=a.length:(a=a.indexOf(".",c),a=(-1!=a?a:c)+1,a>c+100&&(a=c),c=a);return c},getPartDoc=(a,b)=>{const c=a.substring(0,b);a=a.substring(b).trim();return[c,a]},ragLog=(a,b,c,d)=>{const e=MAX_PROMPT_LENGTH;d=d.reduce((f,g)=>f+g.length,0);xlog(`${a} mx:${e} lft:${b} rgt:${c} arr:${d}`);a=formatRow([a,b,c,d],[8,-7,-7,-7]);UaLog.log(a)},Rag=
|
36 |
-
{ragContext:"",ragQuery:"",ragAnswer:"",answers:[],docContextLst:[],prompts:[],doc:"",doc_part:"",init(){this.readRespsFromDb();this.readFromDb()},saveToDb(){UaDb.saveJson(ID_RAG,{context:this.ragContext,ragquery:this.ragQuery,raganswer:this.ragAnswer});UaDb.saveArray(ID_THREAD,ThreadMgr.rows)},readFromDb(){const a=UaDb.readJson(ID_RAG);this.ragContext=a.context||"";this.ragQuery=a.ragquery||"";this.ragAnswer=a.raganswer||"";ThreadMgr.rows=UaDb.readArray(ID_THREAD)},
|
37 |
-
this.answers)},readRespsFromDb(){this.answers=UaDb.readArray(ID_RESPONSES)},async requestDocsRAG(a){DataMgr.deleteJsonDati();DataMgr.readDbDocNames();DataMgr.readDbDocs();this.ragQuery=a;this.saveToDb();var b=0;try{var c=1;for(let e=0;e<DataMgr.docs.length;e++){let f=DataMgr.docs[e];if(""==f.trim())continue;const g=DataMgr.doc_names[e],k=f.length;xlog(`${g} (${k}) `);UaLog.log(`${g} (${k}) `);++b;var d=1;let h=0,l="",t="",u="",m="",v=[];for(;;){let r=getPartSize(f,
|
38 |
-
[t,u]=getPartDoc(f,r);ragLog(`${c}) ${b},${d}`,t.length,u.length,this.answers);l=promptDoc(t,a,g);const p=getPayloadDoc(l);try{if(m=await HfRequest.post(p,TIMEOUT),!m)return""}catch(n){console.error("RR1)\n",n);const w=getErrorInfo(n);if(w.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Doc ${l.length}`);h+=PROMPT_DECR;continue}else if(w.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout Doc");wait(5);continue}else throw n;}d++;c++;f=u;m=cleanResponse(m);v.push(m);
|
39 |
-
v.length;let q=v.join("\n\n");for(d="";;){l=promptBuildContext(q,this.ragQuery);const r=getPayloadBuildContext(l);try{if(d=await HfRequest.post(r,TIMEOUT),!d)return""}catch(p){console.error("RR2)",p);const n=getErrorInfo(p);if(n.errorType===ERROR_TOKENS){UaLog.log(`Error tokens build Context ${l.length}`);q=truncInput(q,PROMPT_DECR);q=setMaxLen(q);continue}else if(n.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout build Context");wait(5);
|
40 |
-
d=`\n### DOCUMENTO: ${g}\n ${d}`;this.docContextLst.push(d)}}catch(e){throw console.error(e),e;}this.ragContext=this.docContextLst.join("\n\n");this.saveToDb();b="";c=this.ragContext;try{for(;;){let e=promptWithContext(c,a);const f=getPayloadWithContext(e);try{if(b=await HfRequest.post(f,TIMEOUT),!b)return""}catch(g){console.error("RR3)",g);const k=getErrorInfo(g);if(k.errorType===ERROR_TOKENS){UaLog.log(`Error tokens with Context ${e.length}`);
|
41 |
-
TIMEOUT_ERROR){UaLog.log("Error timeout with Context");wait(5);continue}else throw g;}break}this.ragAnswer=b=cleanResponse(b);this.saveRespToDb();ThreadMgr.init();this.saveToDb();UaLog.log(`Risposta (${this.ragAnswer.length})`)}catch(e){throw console.error(e),b=`${e}`,e;}finally{return b}},async requestContext(a){let b="";if(!this.ragContext&&!await confirm("Contesto vuoto. Vuoi continuare?"))return"";if(ThreadMgr.isFirst()){ThreadMgr.init();
|
42 |
-
for(;;){prompt=promptThread(c,d,a);const e=getPayloadThread(prompt);try{if(b=await HfRequest.post(e,TIMEOUT),!b)return""}catch(f){console.error("RR4)",f);const g=getErrorInfo(f);if(g.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Thread Init ${prompt.length}`);d=truncInput(d,PROMPT_DECR);c=setMaxLen(c);continue}else if(g.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout Thread Init");continue}else throw f;}break}b=cleanResponse(b);ThreadMgr.add(a,
|
43 |
-
b=`${d}`,d;}finally{return b}}else try{let d=this.ragContext,e=ThreadMgr.getThread();for(c="";;){c=promptThread(d,e,a);const f=getPayloadThread(c);try{if(b=await HfRequest.post(f,TIMEOUT),!b)return""}catch(g){console.error("RR5)",g);const k=getErrorInfo(g);if(k.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Thread ${c.length}`);e=truncInput(e,PROMPT_DECR);continue}else if(k.errorType===
|
44 |
-
b);b=ThreadMgr.getThread();UaLog.log(`Conversazione (${c.length})`)}catch(d){throw console.error(d),b=`${d}`,d;}finally{return b}}},LLM="## Assistant:",USER="## User:",ThreadMgr={rows:[],init(){this.rows=[];Rag.ragAnswer?this.add(Rag.ragQuery,Rag.ragAnswer):this.add("","")},add(a,b){this.rows.push([a,b]);UaDb.saveArray(ID_THREAD,ThreadMgr.rows)},getThread(){const a=[];for(const b of this.rows)a.push(`${USER}\n${b[0]}\n${LLM}\n${b[1]}\n`);
|
|
|
45 |
SYSTEM: Sei un assistente AI specializzato nell'analisi di documenti. Rispondi ESCLUSIVAMENTE in italiano. Non usare altre lingue in nessuna parte della risposta.
|
46 |
|
47 |
TASK: Analizza il documento ${c} ed estrai le informazioni rilevanti per rispondere alla domanda fornita.
|
@@ -175,7 +176,7 @@ RESPONSE:
|
|
175 |
`}function getPayloadDoc(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:1024,num_return_sequences:1,temperature:.2,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:4,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:90,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
176 |
function getPayloadBuildContext(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:6E3,num_return_sequences:1,temperature:.2,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:4,repetition_penalty:1.2,return_full_text:!1,details:!1,max_time:180,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
177 |
function getPayloadWithContext(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:2048,num_return_sequences:1,temperature:.3,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:5,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:120,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
178 |
-
function getPayloadThread(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:2048,num_return_sequences:1,temperature:.3,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:5,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:120,seed:42},options:{use_cache:!1,wait_for_model:!0}}};const VERS="0.1.
|
179 |
function openApp(){tm=umgm();wnds.init();Menu.init();TextInput.init();TextOutput.init();Rag.init();document.querySelector(".menu-btn").checked=!1;release()}function release(){document.querySelector(".release").innerHTML=VERS}const op0=async function(a){a=await requestGet("./help1.html");wnds.wdiv.show(a)};function showQuery(a){wnds.wpre.show(`\n${Rag.ragQuery}`)}function showRagResponse(a){wnds.wpre.show(`\n${Rag.ragAnswer}`)}function showThread(a){a=ThreadMgr.getThread();wnds.wpre.show(a)}
|
180 |
function elencoRisposte(a){a=[...Rag.answers];0==a.length&&(a=UaDb.readArray(ID_RESPONSES));0!=a.length&&(a=a.map((b,c)=>`\n[${c+1}]\n ${b.trim()}`).join("\n"),wnds.wpre.show(a))}function showContesto(a){wnds.wpre.show(`${Rag.ragContext}`)}function elencoDati(a){var b=UaDb.getAllIds();a=[];for(var c of b)b=UaDb.read(c).length,a.push(`${c} (${b})`);c=a.join("\n ");wnds.wpre.show(c)}const showT=a=>{wnds.wpre.show(DataMgr.docs[a])};
|
181 |
function elencoDocs(){DataMgr.readDbDocs();DataMgr.readDbDocNames();var a=DataMgr.doc_names,b=UaJtfh();let c=0;b.append("<ul>");for(const g of a){a=b;var d=a.append,e=g,f=c++;d.call(a,`
|
@@ -210,8 +211,8 @@ function loadTestoEsempio(a){DataMgr.loadDoc(`data/${a}`);wnds.wdiv.close()}asyn
|
|
210 |
closeAll(){UaWindowAdm.close("id_w0");UaWindowAdm.close("id_w1");UaWindowAdm.close("id_out")}},Menu={init(){const a=document.querySelector("#id-menu-btn");a.addEventListener("change",()=>{document.querySelector("body").classList.toggle("menu-open",a.checked)});const b=document.getElementById("id_log");UaLog.callHide=()=>{b.classList.contains("active")&&b.classList.remove("active")};UaLog.callShow=()=>{b.classList.contains("active")||b.classList.add("active")};UaLog.setXY(54,13).setZ(111).new();UaLog.log_show("")},
|
211 |
close(){const a=document.querySelector("#menu-toggle");document.querySelector("body").classList.remove("menu-open",a.checked);document.querySelector(".menu-btn").checked=!1},async help(){const a=await requestGet("./help0.html");wnds.wdiv.show(a)},upload(){RagUpload.open()},uploadDir(){RagUpload.openDir()},async load(){alert("load")},log(){UaLog.toggle()}},TextInput={wnd:null,init(){this.inp=document.querySelector(".text-input");document.addEventListener("keydown",a=>{document.activeElement!==this.inp&&
|
212 |
("F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 Control Alt Shift Meta CapsLock Escape PrintScreen ScrollLock Pause Insert Delete Home End PageUp PageDown ArrowLeft ArrowRight ArrowUp ArrowDown".split(" ").includes(a.key)||a.ctrlKey||a.metaKey||a.preventDefault())});document.querySelector(".clear-button").addEventListener("click",()=>{this.inp.value="";this.inp.focus()});this.inp.addEventListener("keydown",a=>this.handleEnter(a));document.querySelector(".send-input").addEventListener("click",()=>this.send());
|
213 |
-
document.querySelector(".send2-input").addEventListener("click",()=>this.send2());document.querySelector(".clear-input").addEventListener("click",()=>this.clear())},handleEnter(a){"Enter"
|
214 |
-
|
215 |
(this.inp.value="",setOutText(""),ThreadMgr.init())}},setOutText=a=>{var b=document.getElementById("id-text-out");b.innerHTML='<pre class="pre-text"></pre>';b=b.querySelector(".pre-text");b.textContent=a;b.scrollTop=b.scrollHeight};
|
216 |
TextOutput={init(){this.copyBtn=document.querySelector(".copy-output");this.copyBtn.addEventListener("click",()=>this.copy());document.querySelector(".clear-output").addEventListener("click",()=>this.clear());document.querySelector(".wnd-output").addEventListener("click",()=>this.openWnd())},openWnd(){const a=document.getElementById("id-text-out").textContent;wnds.wout.show(a)},async copy(){const a=document.getElementById("id-text-out").querySelector("pre");if(a){var b=a.textContent;a.classList.add("copied");
|
217 |
this.copyBtn.classList.add("copied");try{await navigator.clipboard.writeText(b)}catch(c){console.error("Errore ",c)}setTimeout(()=>{this.copyBtn.classList.remove("copied");a.classList.remove("copied")},5E3)}},clear(){document.getElementById("id-text-out").textContent=""}};const RagUpload={open(){const a=UaWindowAdm.create("id_upload");a.drag();a.setZ(12);a.vw_vh().setXY(16.5,10,-1);a.setHtml('\n <div class="window-text">\n <div class="btn-wrapper">\n <button class="btn-close" title="chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>\n </div> \n <div class="upload"> \n <h4>Upload file Text / PDF</h4> \n <form id="uploadForm">\n <input class="file" type="file" id="id_fileupload" > \n <button type="button" onclick="RagUpload.upload();">Upload and Convert</button>\n </form>\n <div id="result" class="result"></div>\n </div>\n </div>\n ');
|
|
|
33 |
*/
|
34 |
const MAX_PROMPT_LENGTH=81920,PROMPT_DECR=2048,TIMEOUT=6E4;function wait(a){return new Promise(b=>setTimeout(b,1E3*a))}async function example(){console.log("Inizio attesa...");await wait(5);console.log("Fine attesa!")}example();
|
35 |
const truncInput=(a,b)=>a.substring(0,a.length-b),setMaxLen=a=>a.substring(0,MAX_PROMPT_LENGTH-1E3),getPartSize=(a,b,c)=>{c=MAX_PROMPT_LENGTH-c;a.length+b.length<c?c=a.length:(a=a.indexOf(".",c),a=(-1!=a?a:c)+1,a>c+100&&(a=c),c=a);return c},getPartDoc=(a,b)=>{const c=a.substring(0,b);a=a.substring(b).trim();return[c,a]},ragLog=(a,b,c,d)=>{const e=MAX_PROMPT_LENGTH;d=d.reduce((f,g)=>f+g.length,0);xlog(`${a} mx:${e} lft:${b} rgt:${c} arr:${d}`);a=formatRow([a,b,c,d],[8,-7,-7,-7]);UaLog.log(a)},Rag=
|
36 |
+
{ragContext:"",ragQuery:"",ragAnswer:"",answers:[],docContextLst:[],prompts:[],doc:"",doc_part:"",init(){this.readRespsFromDb();this.readFromDb()},returnOk(){return 10<this.ragContext.length},saveToDb(){UaDb.saveJson(ID_RAG,{context:this.ragContext,ragquery:this.ragQuery,raganswer:this.ragAnswer});UaDb.saveArray(ID_THREAD,ThreadMgr.rows)},readFromDb(){const a=UaDb.readJson(ID_RAG);this.ragContext=a.context||"";this.ragQuery=a.ragquery||"";this.ragAnswer=a.raganswer||"";ThreadMgr.rows=UaDb.readArray(ID_THREAD)},
|
37 |
+
saveRespToDb(){UaDb.saveArray(ID_RESPONSES,this.answers)},readRespsFromDb(){this.answers=UaDb.readArray(ID_RESPONSES)},async requestDocsRAG(a){DataMgr.deleteJsonDati();DataMgr.readDbDocNames();DataMgr.readDbDocs();this.ragQuery=a;this.saveToDb();var b=0;try{var c=1;for(let e=0;e<DataMgr.docs.length;e++){let f=DataMgr.docs[e];if(""==f.trim())continue;const g=DataMgr.doc_names[e],k=f.length;xlog(`${g} (${k}) `);UaLog.log(`${g} (${k}) `);++b;var d=1;let h=0,l="",t="",u="",m="",v=[];for(;;){let r=getPartSize(f,
|
38 |
+
promptDoc("",a,""),h);if(10>r)break;[t,u]=getPartDoc(f,r);ragLog(`${c}) ${b},${d}`,t.length,u.length,this.answers);l=promptDoc(t,a,g);const p=getPayloadDoc(l);try{if(m=await HfRequest.post(p,TIMEOUT),!m)return""}catch(n){console.error("RR1)\n",n);const w=getErrorInfo(n);if(w.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Doc ${l.length}`);h+=PROMPT_DECR;continue}else if(w.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout Doc");wait(5);continue}else throw n;}d++;c++;f=u;m=cleanResponse(m);v.push(m);
|
39 |
+
this.answers.push(`DOCUMENTO : ${g}_${d}\n${m}`)}const x=v.length;let q=v.join("\n\n");for(d="";;){l=promptBuildContext(q,this.ragQuery);const r=getPayloadBuildContext(l);try{if(d=await HfRequest.post(r,TIMEOUT),!d)return""}catch(p){console.error("RR2)",p);const n=getErrorInfo(p);if(n.errorType===ERROR_TOKENS){UaLog.log(`Error tokens build Context ${l.length}`);q=truncInput(q,PROMPT_DECR);q=setMaxLen(q);continue}else if(n.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout build Context");wait(5);
|
40 |
+
continue}else throw p;}break}UaLog.log(`context ${x} => ${d.length}`);d=`\n### DOCUMENTO: ${g}\n ${d}`;this.docContextLst.push(d)}}catch(e){throw console.error(e),e;}this.ragContext=this.docContextLst.join("\n\n");this.saveToDb();b="";c=this.ragContext;try{for(;;){let e=promptWithContext(c,a);const f=getPayloadWithContext(e);try{if(b=await HfRequest.post(f,TIMEOUT),!b)return""}catch(g){console.error("RR3)",g);const k=getErrorInfo(g);if(k.errorType===ERROR_TOKENS){UaLog.log(`Error tokens with Context ${e.length}`);
|
41 |
+
c=truncInput(c,PROMPT_DECR);c=setMaxLen(c);continue}else if(k.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout with Context");wait(5);continue}else throw g;}break}this.ragAnswer=b=cleanResponse(b);this.saveRespToDb();ThreadMgr.init();this.saveToDb();UaLog.log(`Risposta (${this.ragAnswer.length})`)}catch(e){throw console.error(e),b=`${e}`,e;}finally{return b}},async requestContext(a){let b="";if(!this.ragContext&&!await confirm("Contesto vuoto. Vuoi continuare?"))return"";if(ThreadMgr.isFirst()){ThreadMgr.init();
|
42 |
+
try{var c=this.ragContext;let d=ThreadMgr.getThread();for(;;){prompt=promptThread(c,d,a);const e=getPayloadThread(prompt);try{if(b=await HfRequest.post(e,TIMEOUT),!b)return""}catch(f){console.error("RR4)",f);const g=getErrorInfo(f);if(g.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Thread Init ${prompt.length}`);d=truncInput(d,PROMPT_DECR);c=setMaxLen(c);continue}else if(g.errorType===TIMEOUT_ERROR){UaLog.log("Error timeout Thread Init");continue}else throw f;}break}b=cleanResponse(b);ThreadMgr.add(a,
|
43 |
+
b);b=ThreadMgr.getThread();UaLog.log(`Inizio Conversazione (${prompt.length})`)}catch(d){throw console.error(d),b=`${d}`,d;}finally{return b}}else try{let d=this.ragContext,e=ThreadMgr.getThread();for(c="";;){c=promptThread(d,e,a);const f=getPayloadThread(c);try{if(b=await HfRequest.post(f,TIMEOUT),!b)return""}catch(g){console.error("RR5)",g);const k=getErrorInfo(g);if(k.errorType===ERROR_TOKENS){UaLog.log(`Error tokens Thread ${c.length}`);e=truncInput(e,PROMPT_DECR);continue}else if(k.errorType===
|
44 |
+
TIMEOUT_ERROR){UaLog.log("Error timeout Thread");continue}else throw g;}break}b=cleanResponse(b);ThreadMgr.add(a,b);b=ThreadMgr.getThread();UaLog.log(`Conversazione (${c.length})`)}catch(d){throw console.error(d),b=`${d}`,d;}finally{return b}}},LLM="## Assistant:",USER="## User:",ThreadMgr={rows:[],init(){this.rows=[];Rag.ragAnswer?this.add(Rag.ragQuery,Rag.ragAnswer):this.add("","")},add(a,b){this.rows.push([a,b]);UaDb.saveArray(ID_THREAD,ThreadMgr.rows)},getThread(){const a=[];for(const b of this.rows)a.push(`${USER}\n${b[0]}\n${LLM}\n${b[1]}\n`);
|
45 |
+
return a.join("\n\n")},isFirst(){return 2>this.rows.length}};function promptDoc(a,b,c){return`
|
46 |
SYSTEM: Sei un assistente AI specializzato nell'analisi di documenti. Rispondi ESCLUSIVAMENTE in italiano. Non usare altre lingue in nessuna parte della risposta.
|
47 |
|
48 |
TASK: Analizza il documento ${c} ed estrai le informazioni rilevanti per rispondere alla domanda fornita.
|
|
|
176 |
`}function getPayloadDoc(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:1024,num_return_sequences:1,temperature:.2,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:4,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:90,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
177 |
function getPayloadBuildContext(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:6E3,num_return_sequences:1,temperature:.2,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:4,repetition_penalty:1.2,return_full_text:!1,details:!1,max_time:180,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
178 |
function getPayloadWithContext(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:2048,num_return_sequences:1,temperature:.3,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:5,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:120,seed:42},options:{use_cache:!1,wait_for_model:!0}}}
|
179 |
+
function getPayloadThread(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:2048,num_return_sequences:1,temperature:.3,top_p:.85,top_k:30,do_sample:!1,no_repeat_ngram_size:4,num_beams:5,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:120,seed:42},options:{use_cache:!1,wait_for_model:!0}}};const VERS="0.1.48 (26-08-2024)";var xlog=console.log,xerror=console.error;const cancelRequest=()=>{confirm("Confermi Cancellazione Richeista ?")&&(HfRequest.cancelRequest(),hideSpinner())},showSpinner=()=>{const a=document.getElementById("spinner");a.classList.add("show-spinner");a.addEventListener("click",cancelRequest)},hideSpinner=()=>{const a=document.getElementById("spinner");a.classList.remove("show-spinner");a.removeEventListener("click",cancelRequest)};var tm;
|
180 |
function openApp(){tm=umgm();wnds.init();Menu.init();TextInput.init();TextOutput.init();Rag.init();document.querySelector(".menu-btn").checked=!1;release()}function release(){document.querySelector(".release").innerHTML=VERS}const op0=async function(a){a=await requestGet("./help1.html");wnds.wdiv.show(a)};function showQuery(a){wnds.wpre.show(`\n${Rag.ragQuery}`)}function showRagResponse(a){wnds.wpre.show(`\n${Rag.ragAnswer}`)}function showThread(a){a=ThreadMgr.getThread();wnds.wpre.show(a)}
|
181 |
function elencoRisposte(a){a=[...Rag.answers];0==a.length&&(a=UaDb.readArray(ID_RESPONSES));0!=a.length&&(a=a.map((b,c)=>`\n[${c+1}]\n ${b.trim()}`).join("\n"),wnds.wpre.show(a))}function showContesto(a){wnds.wpre.show(`${Rag.ragContext}`)}function elencoDati(a){var b=UaDb.getAllIds();a=[];for(var c of b)b=UaDb.read(c).length,a.push(`${c} (${b})`);c=a.join("\n ");wnds.wpre.show(c)}const showT=a=>{wnds.wpre.show(DataMgr.docs[a])};
|
182 |
function elencoDocs(){DataMgr.readDbDocs();DataMgr.readDbDocNames();var a=DataMgr.doc_names,b=UaJtfh();let c=0;b.append("<ul>");for(const g of a){a=b;var d=a.append,e=g,f=c++;d.call(a,`
|
|
|
211 |
closeAll(){UaWindowAdm.close("id_w0");UaWindowAdm.close("id_w1");UaWindowAdm.close("id_out")}},Menu={init(){const a=document.querySelector("#id-menu-btn");a.addEventListener("change",()=>{document.querySelector("body").classList.toggle("menu-open",a.checked)});const b=document.getElementById("id_log");UaLog.callHide=()=>{b.classList.contains("active")&&b.classList.remove("active")};UaLog.callShow=()=>{b.classList.contains("active")||b.classList.add("active")};UaLog.setXY(54,13).setZ(111).new();UaLog.log_show("")},
|
212 |
close(){const a=document.querySelector("#menu-toggle");document.querySelector("body").classList.remove("menu-open",a.checked);document.querySelector(".menu-btn").checked=!1},async help(){const a=await requestGet("./help0.html");wnds.wdiv.show(a)},upload(){RagUpload.open()},uploadDir(){RagUpload.openDir()},async load(){alert("load")},log(){UaLog.toggle()}},TextInput={wnd:null,init(){this.inp=document.querySelector(".text-input");document.addEventListener("keydown",a=>{document.activeElement!==this.inp&&
|
213 |
("F1 F2 F3 F4 F5 F6 F7 F8 F9 F10 F11 F12 Control Alt Shift Meta CapsLock Escape PrintScreen ScrollLock Pause Insert Delete Home End PageUp PageDown ArrowLeft ArrowRight ArrowUp ArrowDown".split(" ").includes(a.key)||a.ctrlKey||a.metaKey||a.preventDefault())});document.querySelector(".clear-button").addEventListener("click",()=>{this.inp.value="";this.inp.focus()});this.inp.addEventListener("keydown",a=>this.handleEnter(a));document.querySelector(".send-input").addEventListener("click",()=>this.send());
|
214 |
+
document.querySelector(".send2-input").addEventListener("click",()=>this.send2());document.querySelector(".clear-input").addEventListener("click",()=>this.clear())},handleEnter(a){"Enter"===a.key&&!a.shiftKey&&Rag.returnOk()&&(a.preventDefault(),this.send2())},async send(){if(this.inp.value){if(Rag.ragContext&&!confirm("Vuoi iniziare una nuova elabrazione ?"))return"";showSpinner();setOutText("");var a=this.inp.value.trim();try{let b=await Rag.requestDocsRAG(a);b=cleanOut(b);setOutText(b);this.inp.value=
|
215 |
+
"";UaLog.close()}catch(b){a=`send\n${b}`,console.error(a),alert(a),setOutText(a)}hideSpinner()}else alert("Ricorda di scrivere la Query ")},async send2(){if(this.inp.value){showSpinner();ThreadMgr.isFirst()&&setOutText("");var a=this.inp.value.trim();try{let b=await Rag.requestContext(a);if(""==b){hideSpinner();return}b=cleanOut(b);setOutText(b);this.inp.value=""}catch(b){a=`send2\n${b}`,console.error(a),alert(a),setOutText(a)}hideSpinner()}else alert("Ricorda di scrivere la Query ")},clear(){confirm("Confermi cancellazione conversazione? ")&&
|
216 |
(this.inp.value="",setOutText(""),ThreadMgr.init())}},setOutText=a=>{var b=document.getElementById("id-text-out");b.innerHTML='<pre class="pre-text"></pre>';b=b.querySelector(".pre-text");b.textContent=a;b.scrollTop=b.scrollHeight};
|
217 |
TextOutput={init(){this.copyBtn=document.querySelector(".copy-output");this.copyBtn.addEventListener("click",()=>this.copy());document.querySelector(".clear-output").addEventListener("click",()=>this.clear());document.querySelector(".wnd-output").addEventListener("click",()=>this.openWnd())},openWnd(){const a=document.getElementById("id-text-out").textContent;wnds.wout.show(a)},async copy(){const a=document.getElementById("id-text-out").querySelector("pre");if(a){var b=a.textContent;a.classList.add("copied");
|
218 |
this.copyBtn.classList.add("copied");try{await navigator.clipboard.writeText(b)}catch(c){console.error("Errore ",c)}setTimeout(()=>{this.copyBtn.classList.remove("copied");a.classList.remove("copied")},5E3)}},clear(){document.getElementById("id-text-out").textContent=""}};const RagUpload={open(){const a=UaWindowAdm.create("id_upload");a.drag();a.setZ(12);a.vw_vh().setXY(16.5,10,-1);a.setHtml('\n <div class="window-text">\n <div class="btn-wrapper">\n <button class="btn-close" title="chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>\n </div> \n <div class="upload"> \n <h4>Upload file Text / PDF</h4> \n <form id="uploadForm">\n <input class="file" type="file" id="id_fileupload" > \n <button type="button" onclick="RagUpload.upload();">Upload and Convert</button>\n </form>\n <div id="result" class="result"></div>\n </div>\n </div>\n ');
|