const removeChars=a=>{a=a.replace(/[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g,"");return a=Array.from(a).filter(b=>!/^C/.test(b.codePointAt(0))).join("")},replaceChars=a=>{a=a.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g," ");a=a.replace(/ +/g," ");return a.trim()},removeTag=a=>a=a.replace(/<<<|>>>|<<|>>/g,""); function cleanDoc(a){try{return a=removeTag(a),a=removeChars(a),a=replaceChars(a),a=a.replace(/\n/g," "),a=a.replace(/\t/g," "),a=a.replace(/ +/g," "),a=a.replace(/\n\s*\n/g,"\n"),a=a.replace(/[\u201c\u201d]/g,'"'),a=a.replace(/[\u2018\u2019]/g,"'"),a=a.replace(/[\u00ab\u00bb\u201e\u201c]/g,'"'),a=a.replace(/[\u2013\u2014]/g,"-"),a=a.replace(/\\[nrt]/g,""),a=a.replace(/[^\w\s\u00e0\u00e8\u00e9\u00ec\u00f2\u00f9\u00c0\u00c8\u00c9\u00cc\u00d2\u00d9\u00e1\u00e9\u00ed\u00f3\u00fa\u00c1\u00c9\u00cd\u00d3\u00da\u00e4\u00eb\u00ef\u00f6\u00fc\u00c4\u00cb\u00cf\u00d6\u00dc\u00e2\u00ea\u00ee\u00f4\u00fb\u00c2\u00ca\u00ce\u00d4\u00db\u00e7\u00c7\u00f1\u00d1.,;:!?'"()-]/g, ""),a.trim()}catch(b){return xerror(b),"Errore di codifica nel documento"}} function cleanResponse(a){try{return a=removeChars(a),a=replaceChars(a),a=a.replace(/\t/g," "),a=a.replace(/ +/g," "),a=a.replace(/\n\s*\n/g,"\n"),a=a.replace(/[\u201c\u201d]/g,'"'),a=a.replace(/[\u2018\u2019]/g,"'"),a=a.replace(/[\u00ab\u00bb\u201e\u201c]/g,'"'),a=a.replace(/[\u2013\u2014]/g,"-"),a=a.replace(/\\[nrt]/g,""),a=a.replace(/[^\w\s\u00e0\u00e8\u00e9\u00ec\u00f2\u00f9\u00c0\u00c8\u00c9\u00cc\u00d2\u00d9\u00e1\u00e9\u00ed\u00f3\u00fa\u00c1\u00c9\u00cd\u00d3\u00da\u00e4\u00eb\u00ef\u00f6\u00fc\u00c4\u00cb\u00cf\u00d6\u00dc\u00e2\u00ea\u00ee\u00f4\u00fb\u00c2\u00ca\u00ce\u00d4\u00db\u00e7\u00c7\u00f1\u00d1.,;:!?'"()-]/g,""), a.trim()}catch(b){return xerror(b),"Errore di codifica nela risposta"}} function cleanOutput(a){try{return a=removeChars(a),a=replaceChars(a),a=a.replace(/\t/g," "),a=a.replace(/ +/g," "),a=a.replace(/\n\s*\n/g,"\n"),a=a.replace(/[\u201c\u201d]/g,'"'),a=a.replace(/[\u2018\u2019]/g,"'"),a=a.replace(/[\u00ab\u00bb\u201e\u201c]/g,'"'),a=a.replace(/[\u2013\u2014]/g,"-"),a=a.replace(/\\[nrt]/g,""),a=a.replace(/[^\w\s\u00e0\u00e8\u00e9\u00ec\u00f2\u00f9\u00c0\u00c8\u00c9\u00cc\u00d2\u00d9\u00e1\u00e9\u00ed\u00f3\u00fa\u00c1\u00c9\u00cd\u00d3\u00da\u00e4\u00eb\u00ef\u00f6\u00fc\u00c4\u00cb\u00cf\u00d6\u00dc\u00e2\u00ea\u00ee\u00f4\u00fb\u00c2\u00ca\u00ce\u00d4\u00db\u00e7\u00c7\u00f1\u00d1.,;:!?'"()-]/g,""), a.trim()}catch(b){return xerror(b),"Errore di codifica nell'output"}}function list2text(a){const b={};for(var c of a){a=(a=c.match(/<<<(.*?)>>>/))?a[1]:null;const d=c.replace(/<<<.*?>>>/,"");b[a]=a in b?b[a]+`\n ${d}`:d}c=[];for(let [d,e]of Object.entries(b))c.push(`Documento: ${d}.\n${e}`);return c.join("\n\n")}function subResponseDOcTag(a){return a.replace(/<<<(.*?)>>>/,(b,c)=>`Documento: ${c}`)};const UaDb={create(a,b){localStorage.getItem(a)?xerror(`ID ${a} already exists.`):localStorage.setItem(a,b)},read(a){const b=localStorage.getItem(a);return null===b?(xlog(`UaDb.read ${a} not found.`),""):b},update(a,b){localStorage.getItem(a)?localStorage.setItem(a,b):xlog(`UaDb.update ${a} not found.`)},delete(a){localStorage.getItem(a)?localStorage.removeItem(a):xerror(`ID ${a} not found.`)},save(a,b){localStorage.setItem(a,b)},getAllIds(){const a=[];for(let b=0;ba.map(b=>atob(b).split("").map(c=>String.fromCharCode((c.charCodeAt(0)-5+256)%256)).join("")).join(""),tm=umgm(arr); async function requestGet(a){try{var b=await fetch(a,{method:"GET",headers:{"Content-Type":"text/plain;charset=UTF-8"}});if(!b.ok)throw Error(`HTTP error! status: ${b.status}`);const c=await b.arrayBuffer();return(new TextDecoder("utf-8")).decode(c)}catch(c){throw xerror(c),b="AbortError"===c.name?"Request was aborted":c.message.includes("HTTP error! status")?c.message:"An error occurred",alert(`requestGet()\nurl: ${a}\n${b}`),c;}} const ERROR_TOKENS="ERROR_TOKENS",TIMEOUT_ERROR="TIMEOUT_ERROR",HfRequest={controller:null,isCancelled:!1,baseUrl:"https://api-inference.huggingface.co/models",async post(a,b=3E4){this.isCancelled=!1;this.controller=new AbortController;try{const c=setTimeout(()=>{this.controller.abort()},b),d=await fetch(`${this.baseUrl}/${model_name}`,{method:"POST",headers:{Authorization:`Bearer ${tm}`,"Content-Type":"application/json"},body:JSON.stringify(a),signal:this.controller.signal});clearTimeout(c);if(this.isCancelled)return null; const e=await d.json();if(!d.ok){const g=this.checkError(d.status,e),l=this.createErrorInfo(d.status,d.statusText,e.error,g);throw Error(l);}const f=this.isInvalidResponse(e);if("string"===typeof f){const g=this.createErrorInfo(d.status,d.statusText,e.error,f);throw Error(g);}return e[0].generated_text.trim()}catch(c){if(this.isCancelled)return null;if("AbortError"===c.name)throw a=this.createErrorInfo(0,"Timeout","La richiesta \u00e8 scaduta",TIMEOUT_ERROR),Error(a);throw c;}},cancelRequest(){this.controller&& (this.isCancelled=!0,this.controller.abort())},checkError(a,b){return 500<=a?"SERVER_ERROR":400<=a&&500>a?"object"===typeof b&&"validation"===b.error_type?b.error.includes("tokens")?ERROR_TOKENS:"ERROR_VALIDATION":"CLIENT_ERROR":"UNKNOWN_ERROR"},isInvalidResponse(a){return a&&Array.isArray(a)&&0!==a.length?a[0].generated_text?null:"MISSING_GENERATED_TEXT":"INVALID_DATA"},createErrorInfo(a,b,c,d){return JSON.stringify({status:a,statusText:b,errorType:d,message:c||"Errore sconosciuto"})}};/* rag_rqs Copyright (C) 2024 [Il tuo nome] This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ const MAX_PROMPT_LENGTH=87040,PROMPT_DECR=2048,Rag={ragContext:"",ragQuery:"",ragResponse:"",responses:[],prompts:[],doc:"",doc_part:"",init(){this.readRespsFromDb();this.readFromDb()},saveToDb(){UaDb.saveJson("id_rag",{context:this.ragContext,ragquery:this.ragQuery,ragresponse:this.ragResponse});UaDb.saveArray("id_thread",ThreadMgr.rows)},readFromDb(){const a=UaDb.readJson("id_rag");this.ragContext=a.context||"";this.ragQuery=a.ragquery||"";this.ragResponse=a.ragresponse||"";ThreadMgr.rows=UaDb.readArray("id_thread")}, saveRespToDb(){UaDb.saveArray("id_responses",this.responses)},readRespsFromDb(){this.responses=UaDb.readArray("id_responses")},addPrompt(a){this.prompts.push(a)},responsesLength(){return this.responses.reduce((a,b)=>a+b.length,0)},ragLog(a,b,c){const d=MAX_PROMPT_LENGTH,e=this.responsesLength();xlog(`${a} mx:${d} lft:${b} rgt:${c} arr:${e}`);UaLog.log(`${a}${"      "}${b}${"      "}${c}${"      "}${e}`)},truncInput(a, b){return a.substring(0,a.length-b)},getPartSize(a,b,c){c=MAX_PROMPT_LENGTH-c;a.length+b.lengthc+100&&(a=c),c=a);return c},getPartDoc(a,b){const c=a.substring(0,b);a=a.substring(b).trim();return[c,a]},errorInfo(a){return JSON.parse(a.message)},errorTotext(a){a=JSON.parse(a.message);return`Errore: Stato: ${a.status} Descrizione stato: ${a.statusText} Tipo di errore: ${a.errorType} Messaggio: ${a.message}`},async requestDocsRAG(a){DataMgr.deleteJsonDati();DataMgr.readDbDocNames();DataMgr.readDbDocs();this.ragQuery=a;var b=0;try{for(let c=0;cq)break;[k,m]=this.getPartDoc(d,q);this.ragLog(`${b},${g+1}`,k.length,m.length);h=promptDoc(k, a);const r=getPayloadDoc(h);let n;try{if(n=await HfRequest.post(r),!n)return""}catch(p){if(this.errorInfo(p).errorType===ERROR_TOKENS){UaLog.log(`Error tokens.1 ${k.length}`);xerror(`Error tokens. ${h.length}`);l+=PROMPT_DECR;continue}else throw xerror(p),this.errorTotext(p);}g++;d=m;this.responses.push(`<<<${e}>>>\n${n}`)}}}catch(c){alert("requestDocsRAG(1)\n"+c),xerror(c)}this.ragContext=list2text(this.responses);this.saveToDb();b="";try{let c=promptWithContext(this.ragContext,a);const d=getPayloadWithContext(c); try{if(b=await HfRequest.post(d),!b)return""}catch(e){this.errorInfo(e);const f=this.errorTotext(e);xerror(e);throw f;}this.ragResponse=b;this.saveRespToDb();ThreadMgr.init();this.saveToDb();UaLog.log(`Risposta (${c.length},${b.length})`)}catch(c){throw b=c,xerror(c),alert("requestDocsRAG(3)\n"+c),c;}finally{return b=cleanOutput(b)}},async requestContext(a){if(!this.ragContext&&!await confirm("Contesto vuoto. Vuoi continuare?"))return"";if(ThreadMgr.isFirst()){var b="";ThreadMgr.init();try{var c= this.ragContext,d=ThreadMgr.getThread();prompt=promptThread(c,d,a);var e=getPayloadThread(prompt);try{var f=await HfRequest.post(e);if(!f)return""}catch(g){throw this.errorInfo(g).errorType===ERROR_TOKENS?UaLog.log(`Error tokens.4 ${prompt.length}`):alert(g),xerror(g),g;}ThreadMgr.add(a,f);b=ThreadMgr.getOutText();UaLog.log(`Inizio Conversazione (${prompt.length},${f.length})`)}catch(g){throw xerror(g),b=g,g;}finally{return b=cleanOutput(b)}}else{c="";try{b=this.ragContext;let g=ThreadMgr.getThread(); e=d="";for(f=0;;){g=this.truncInput(g,f);d=promptThread(b,g,a);const l=getPayloadThread(d);try{if(e=await HfRequest.post(l),!e)return""}catch(h){const k=this.errorInfo(h);if(k.errorType===ERROR_TOKENS){UaLog.log(`Error tokens.5 ${d.length}`);xerror(`Error tokens. ${d.length}`);f+=PROMPT_DECR;continue}else throw xerror(h),k.errorType;}break}ThreadMgr.add(a,e);c=ThreadMgr.getOutText();UaLog.log(`Conversazione (${d.length},${e.length})`)}catch(g){throw alert("requestContext(2) \n"+g),xerror(g),c= g,g;}finally{return c=cleanOutput(c)}}}},LLM="Assistant:",USER="User:",ThreadMgr={rows:[],init(){this.rows=[];Rag.ragResponse?this.add(Rag.ragQuery,Rag.ragResponse):this.add("","")},add(a,b){this.rows.push([a,b]);UaDb.saveArray("id_thread",ThreadMgr.rows)},getOutText(){const a=[];for(const b of this.rows){const c=b[0].trim(),d=b[1].trim();a.push(`\n${USER}\n${c}\n${LLM}\n${d}\n\n`)}return a.join("").trim()},getThread(){const a=[];for(const b of this.rows){const c=b[0].trim(),d=b[1].trim();a.push(`${USER}\n${c}\n${LLM}\n${d}\n\n`)}return a.join("").trim()}, isFirst(){return 2>this.rows.length}};function promptDoc(a,b,c){return` SYSTEM: Sei un assistente AI specializzato nell'analisi di documenti. Rispondi sempre in italiano. TASK: Analizzare il documento ${c} ed estrarre le informazioni rilevanti per rispondere alla domanda fornita. INSTRUCTIONS: 1. Analizza attentamente il documento. 2. Identifica le informazioni pertinenti alla domanda. 3. Estrai i concetti chiave e fai inferenze ragionevoli. 4. Organizza le informazioni in modo logico. 5. Prepara una risposta completa ma concisa. 6. Includi un'introduzione breve, sviluppa l'analisi, presenta le inferenze e concludi con una sintesi. 7. Cita il documento quando \u00e9 utile per chiarire informazioni o inferenze. 8. Mantieni un tono oggettivo e uno stile fluido e coerente. DOCUMENT: <<>> ${a} <<>> QUESTION: ${b} OUTPUT_FORMAT: - Inizia la tua risposta direttamente con il contenuto, senza etichette o introduzioni. - Fornisci la tua risposta come testo continuo diviso in paragrafi. - Non usare elenchi puntati o numerati. - Evita qualsiasi tipo di etichetta o marcatori speciali. RESPONSE: `}function promptWithContext(a,b){return` SYSTEM: Sei un assistente AI specializzato nell'analisi e nell'elaborazione di informazioni contestuali. Rispondi sempre in italiano. TASK: Elaborare la risposta alla domanda sulla base del contesto fornito. INSTRUCTIONS: 1. Analizza attentamente il contesto fornito. 2. Identifica le informazioni pertinenti alla domanda. 3. Estrai i concetti chiave e fai inferenze ragionevoli. 4. Prepara una risposta completa ma concisa. 5. Struttura la risposta in paragrafi logici. 6. Includi un'introduzione breve, sviluppa l'analisi, presenta le inferenze e concludi con una sintesi. 7. Se la domanda richiede di citare le fonti, fai riferimento al documento fornito distinguendolo chiaramente da eventuali altre fonti citate all'interno del documento stesso. 8. Mantieni un tono oggettivo e uno stile fluido e coerente. CONTEXT: <<>> ${a} <<>> QUESTION: ${b} OUTPUT_FORMAT: - Inizia la tua risposta direttamente con il contenuto, senza etichette o introduzioni. - Fornisci la tua risposta come testo continuo diviso in paragrafi. - Evita di usare elenchi puntati o numerati. - Evita qualsiasi tipo di etichetta o marcatori speciali. RESPONSE: `}function promptThread(a,b,c){return` SYSTEM: Sei un assistente AI versatile progettato per gestire conversazioni dinamiche e adattarti a varie richieste. Rispondi sempre in italiano. INSTRUCTIONS: 1. Analizza il contesto, la conversazione precedente e la richiesta attuale. 2. Interpreta l'intento dell'utente senza limitarti a categorie predefinite. 3. Adatta la tua risposta in base all'intento percepito, sia esso una domanda, una richiesta di azione, un'istruzione specifica o altro. 4. Mantieni la coerenza con il contesto della conversazione. 5. Adatta tono e stile in base all'interazione, rimanendo professionale ma amichevole. 6. Fai riferimento a informazioni precedenti quando pertinente. 7. Se l'intento non \u00e8 chiaro, chiedi gentilmente chiarimenti. 8. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza. 9. Mantieni un tono oggettivo e uno stile fluido e coerente. CONTEXT: <<>> ${a} <<>> <<>> ${b} <<>> REQUEST: ${c} OUTPUT_FORMAT: - Inizia la tua risposta direttamente con il contenuto, senza etichette o introduzioni. - Fornisci la tua risposta come testo continuo diviso in paragrafi. - Evita di usare elenchi puntati o numerati. - Evita qualsiasi tipo di etichetta o marcatori speciali. RESPONSE: `}function getPayloadDoc(a){return{inputs:a,parameters:{task:"text2text-generation",max_new_tokens:512,num_return_sequences:1,temperature:.5,top_k:50,top_p:.7,do_sample:!0,no_repeat_ngram_size:4,num_beams:5,repetition_penalty:1.4,return_full_text:!1,details:!1,max_time:90,seed:42},options:{use_cache:!1,wait_for_model:!0}}} function getPayloadWithContext(a){return{inputs:a,parameters:{task:"text-generation",max_new_tokens:1024,num_return_sequences:1,temperature:.6,top_k:50,top_p:.7,do_sample:!0,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}}} function getPayloadThread(a){return{inputs:a,parameters:{task:"text-generation",max_new_tokens:1024,num_return_sequences:1,temperature:.6,top_k:50,top_p:.7,do_sample:!0,no_repeat_ngram_size:43,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.40 (28-07-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)}; function openApp(){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.ragResponse}`)}function showThread(a){a=ThreadMgr.getOutText();wnds.wpre.show(a)} function elencoRisposte(a){a=[...Rag.responses];0==a.length&&(a=UaDb.readArray("id_responses"));0!=a.length&&(a=a.map((b,c)=>{b=subResponseDOcTag(b);return`\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)} async function elencoDocs(a){DataMgr.readDbDocNames();a=DataMgr.doc_names.join("\n");wnds.wpre.show(a)} function calcQuery(){DataMgr.readDbDocs();DataMgr.readDbDocNames();var a=[];let b=0,c=0;a.push("Documento Num.Parti");a.push("==================");for(const d of DataMgr.docs){const e=DataMgr.doc_names[c];c+=1;const f=Math.ceil(d.length/MAX_PROMPT_LENGTH);b+=f;a.push(`${e}   [${f}]`)}a.push("==================");a.push(`Totale num. Parti: ${b}`);a=a.join("\n");wnds.wpre.show(a)} function deleteDati(a){confirm("Confermi cancellazione dati?")&&(DataMgr.deleteJsonDati(),wnds.wdiv.close(),wnds.wpre.close(),TextOutput.clear())}function deleteSttorage(a){confirm("Confermi cancellazione documenti & dati?")&&(DataMgr.deleteJsonDati(),localStorage.clear(),wnds.wdiv.close(),wnds.wpre.close(),TextOutput.clear(),DataMgr.docs=[],DataMgr.doc_names=[])}async function help1(a){a=await requestGet("./data/help_test.html");wnds.wdiv.show(a)} function loadTestoEsempio(a){DataMgr.loadDoc(`data/${a}`);wnds.wdiv.close()}async function help2(a){a=await requestGet("./help2.html");wnds.wdiv.show(a)}function showPrompts(a){0!=Rag.prompts.length&&(a=Rag.prompts.map((b,c)=>`[${c+1}]${b}\n`).join("\n"),wnds.wpre.show(a))}function showTesti(a){DataMgr.readDbDocs();a=DataMgr.docs.join("\n");wnds.wpre.show(a)};const WndPre=a=>({w:UaWindowAdm.create(a),out:null,show(b){wnds.closeAll();b=`
${b}
`;this.w.drag();this.w.setZ(12);this.w.vw_vh().setXY(16.5,10,-1);this.w.setHtml(b);this.w.show();this.w.getElement().querySelector(".btn-copy").addEventListener("click",()=>this.copy())},close(){this.w.close()},async copy(){const b=this.w.getElement().querySelector(".pre-text").textContent;try{await navigator.clipboard.writeText(b)}catch(c){xerror("Errore ",c)}}}),WndDiv=a=>({w:UaWindowAdm.create(a),out:null,show(b){wnds.closeAll();b=`
${b}
`;this.w.drag();this.w.setZ(12);this.w.vw_vh().setXY(16.5,10,-1);this.w.setHtml(b);this.w.show();this.w.getElement().querySelector(".btn-copy").addEventListener("click",()=>this.copy())},close(){this.w.close()},async copy(){const b=this.w.getElement().querySelector(".div-text").textContent;try{await navigator.clipboard.writeText(b)}catch(c){xerror("Errore ",c)}}}),wnds={wdiv:null,wpre:null,wout:null,init(){this.wdiv=WndDiv("id_w0");this.wpre=WndPre("id_w1");this.wout=WndPre("id_out")},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(64,13).setZ(111).new();UaLog.log_show("Buon Lavoro")},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&&("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());document.querySelector(".send2-input").addEventListener("click",()=>this.send2());document.querySelector(".clear-input").addEventListener("click",()=>this.clear())},handleEnter(a){"Enter"!==a.key||a.shiftKey||(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{const b=await Rag.requestDocsRAG(a);setOutText(b);this.inp.value="";UaLog.close()}catch(b){a=`send\n${b}`,xerror(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{const b= await Rag.requestContext(a);if(""==b){hideSpinner();return}setOutText(b);this.inp.value=""}catch(b){a=`send2\n${b}`,xerror(a),alert(a),setOutText(a)}hideSpinner()}else alert("Ricorda di scrivere la Query ")},clear(){confirm("Confermi cancellazione conversazione? ")&&(this.inp.value="",setOutText(""),ThreadMgr.init())}},setOutText=a=>{var b=document.getElementById("id-text-out");b.innerHTML='
';b=b.querySelector(".pre-text");b.textContent=a;b.scrollTop=b.scrollHeight};
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");
this.copyBtn.classList.add("copied");try{await navigator.clipboard.writeText(b)}catch(c){xerror("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      
\n
\n \n
\n
\n

Upload file Text / PDF

\n
\n \n \n
\n
\n
\n
\n '); a.show()},async upload(){const a=document.getElementById("id_fileupload").files[0];if(a){var b=a.name;if(DataMgr.doc_names.includes(b))alert("Il file \u00e8 gi\u00e0 in archivio");else{var c=document.getElementById("result"),d=a.name.split(".").pop().toLowerCase();showSpinner();try{let e;if("pdf"===d){const f=new PdfHandler;await f.loadPdfJs();e=await f.extractTextFromPDF(a);f.cleanup()}else if("txt"===d)e=await readTextFile(a);else{alert("Formato file non supportato.");return}DataMgr.addDoc(b,e); c.innerHTML=`

${b}

caricato e salvato nella memoria locale`}catch(e){xerror("Error:",e),alert("Errore durante l'estrazione del testo dal file.")}finally{hideSpinner()}}}else alert("Nessun file selezionato.")},openDir(){const a=UaWindowAdm.create("id_upload");a.drag();a.setZ(12);a.vw_vh().setXY(16.5,10,-1);a.setHtml('\n
\n
\n \n
\n
\n

Upload files Text / PDF

\n
\n \n \n
\n
\n
\n
\n '); a.show()},async uploadDir(){var a=document.getElementById("id_fileupload").files;if(a&&0!=a.length){var b=[];showSpinner();try{for(const c of a){const d=c.name;UaLog.log_show(d);if(DataMgr.doc_names.includes(d)){UaLog.log_shw(d+" : \u00e8 gi\u00e0 in archivio");continue}const e=c.name.split(".").pop().toLowerCase();let f;if("pdf"===e){const g=new PdfHandler;await g.loadPdfJs();f=await g.extractTextFromPDF(c);g.cleanup()}else if("txt"===e)f=await readTextFile(c);else{alert("Formato file non supportato."); return}DataMgr.addDoc(d,f);b.push(`${d}`)}}catch(c){xerror("Error:",c),alert("Errore durante l'estrazione del testo dal file.")}finally{hideSpinner()}a=document.getElementById("result");b=b.join("
");a.innerHTML=b}else alert("Nessun file selezionato.")}}; class PdfHandler{constructor(){this.workerScriptElement=this.scriptElement=this.pdfjsLib=null}async loadPdfJs(){window.pdfjsLib||(this.scriptElement=document.createElement("script"),this.scriptElement.src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.min.js",document.body.appendChild(this.scriptElement),await new Promise(a=>{this.scriptElement.onload=()=>{this.workerScriptElement=document.createElement("script");this.workerScriptElement.src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js"; document.body.appendChild(this.workerScriptElement);this.workerScriptElement.onload=a}}));this.pdfjsLib=window["pdfjs-dist/build/pdf"];this.pdfjsLib.GlobalWorkerOptions.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.6.347/pdf.worker.min.js"}async extractTextFromPDF(a){a=await a.arrayBuffer();a=await this.pdfjsLib.getDocument({data:a}).promise;let b="";for(let c=1;c<=a.numPages;c++){const d=(await (await a.getPage(c)).getTextContent()).items.map(e=>e.str).join(" ");b+=d+"\n"}return b}cleanup(){this.scriptElement&& (document.body.removeChild(this.scriptElement),this.scriptElement=null);this.workerScriptElement&&(document.body.removeChild(this.workerScriptElement),this.workerScriptElement=null);this.pdfjsLib=null;window.gc&&window.gc()}} async function readTextFile(a){if(!a||"text/plain"!==a.type)throw Error("Invalid file type. Please select a text file.");return new Promise((b,c)=>{const d=new FileReader;d.onload=e=>b(e.target.result);d.onerror=e=>c(Error("Error reading file: "+e.message));d.readAsText(a)})};const nodrag_tds=["input","select","a"],nodrag_cls="nodrag"; var UaDrag=function(a){return function(b){let c=0,d=0,e=0,f=0;const g=function(h){h=h||window.event;h.preventDefault();c=e-h.clientX;d=f-h.clientY;e=h.clientX;f=h.clientY;b.style.top=b.offsetTop-d+"px";b.style.left=b.offsetLeft-c+"px"},l=function(){document.onmouseup=null;document.onmousemove=null};b.onmousedown=function(h){h=h||window.event;let k=h.target;!(k=k||null)||nodrag_tds.includes(k.tagName.toLowerCase())||k.classList.contains(nodrag_cls)||(h.preventDefault(),e=h.clientX,f=h.clientY,document.onmouseup= l,document.onmousemove=g)}}(a)};const UaJtfh=()=>({rows:[],init(){this.rows=[];return this},insert(a){this.rows.unshift(a);return this},append(a){this.rows.push(a);return this},text(a=""){return this.rows.join(a)},html(a=""){return this.rows.join(a).replace(/\s+|\[rn\]/g," ")}});var UaLog={callHide:function(){},callShow:function(){},active:!1,wind:null,x:null,y:null,z:null,max_length:2E3,msg_id:"ualogmsg_",new:function(){null==this.wind&&(this.wind=UaWindowAdm.create("ualog_"),this.wind.drag());this.wind.setHtml('\n \n \n
');this.wind.setStyle({width:"auto",minWidth:"300px",maxWidth:"400px", height:"auto",textAlign:"center",padding:"2px 2px 2px 2px",margin:"5px 0 0 0",background:"#333333",color:"#ffffff",fontSize:"15px",fontWeight:"normal",borderRadius:"9px",border:"1px solid #999999"});var a=document.getElementById(this.msg_id);const b={width:"auto",textAlign:"left",fontSize:"16px",fontFamily:"monospace",paddingTop:"2px ",marginTop:"2px",color:"#ffffff",background:"#000000",maxHeight:"400px",overflow:"auto",scrollbarColor:"#027876 #454444",scrollbarWidth:"auto"};for(const d in b)a.style[d]= b[d];const c={background:"#444444",color:"#ffffff",padding:"5px 5px 5px 5px",margin:"0 5px 0 5px",fontSize:"16px",fontWeight:"bold",border:"1px solid #ffffff",borderRadius:"10px"};a=document.querySelectorAll("#ualog_ button");for(const d of a){for(const e in c)d.style[e]=c[e];d.addEventListener("mouseover",e=>{e.target.style.cursor="pointer";e.target.style.color="#000000";e.target.style.background="#aaaaaa"});d.addEventListener("mouseout",e=>{for(const f in c)e.target.style[f]=c[f]})}this.x?this.wind.vw_vh().setXY(this.x, this.y,-1):this.wind.setCenter(-1);this.z&&this.wind.setZ(this.z);return this},setXY(a,b){this.x=a;this.y=b;return this},setZ(a){this.z=a;return this},prn_(...a){a=a.join("
");let b=document.getElementById(this.msg_id);b.innerHTML=b.innerHTML+a+"
"},print(...a){null!=this.wind&&this.active&&this.prn_(...a)},log(...a){null!=this.wind&&this.prn_(...a)},log_show(...a){null!=this.wind&&(this.active||this.toggle(),this.prn_(...a))},cls(){if(null!=this.wind)return document.getElementById(this.msg_id).innerHTML= "",this},close(){null!=this.wind&&(this.wind.hide(),this.active=!1,this.callHide())},toggle(){null!=this.wind&&(this.active?(this.active=!1,this.wind.hide(),this.callHide()):(this.active=!0,this.wind.show(),this.callShow()))}};var UaWindowAdm={ws:{},create(a,b=null){let c=document.getElementById(a);c||(c=document.createElement("div"),b?document.getElementById(b).appendChild(c):document.body.appendChild(c),c.id=a,c.setAttribute("data-name","ua-window"),b=this.newUaWindow(c),this.ws[a]=b);a=this.ws[a];c.style.display="none";return a},get(a){return this.ws[a]?this.ws[a]:null},show(a){this.ws[a]&&this.ws[a].show()},close(a){this.ws[a]&&this.ws[a].close()},toggle(a){this.ws[a]&&this.ws[a].toggle()},hide(a){this.ws[a]&&this.ws[a].hide()}, closeThis(a){a=a.closest('[data-name="ua-window"]').id;this.ws[a].close()},showAll(){for(let a in this.ws)this.ws[a].show()},hideAll(){for(let a in this.ws)this.ws[a].hide()},closeAll(){for(let a in this.ws)this.ws[a].close()},remove(a){this.ws[a]&&(document.getElementById(a).remove(),this.ws[a]=null,delete this.ws[a])},removeAll(){for(let a in this.ws)this.remove(a);this.ws={}},newUaWindow(a){let b={initialize(c){this.w=c;this.wy=this.wx="0px";this.isVisible=this.isOpen=!1;this.firstShow=!0;this.wz= this.pos=0;this.vh=this.vw="px"},vw_vh(){this.vw="vw";this.vh="vh";return this},addClassStyle(c){this.w.classList.contains(c)||this.w.classList.add(c);return this},removeClassStyle(c){this.w.classList.contains(c)&&this.w.classList.remove(c);return this},getWindow(){alert("getWindow => ??");return this.w},getElement(){return this.w},getId(){return this.w.id},setStyle(c){for(const d in c)this.w.style[d]=c[d];return this},setHtml(c){this.w.innerHTML=c;return this},getHtml(){return this.w.innerHTML}, setXY(c,d,e=0){this.wx=c;this.wy=d;this.pos=e;return this},setCenterY(c,d){this.setXY((window.innerWidth-this.w.clientWidth)/2,c,d);return this},setCenter(c){this.setXY((window.innerWidth-this.w.clientWidth)/2,(window.innerHeight-this.w.clientHeight)/2,c);return this},linkToId(c,d,e,f){c=document.getElementById(c);this.linkToElement(c,d,e,f);return this},linkToElement(c,d,e,f){d=c.offsetLeft+c.offsetWidth+d;c=c.offsetTop+e;0>c&&(c=0);this.setXY(d,c,f);return this},setZ(c){this.wz=c;return this},reset(){this.firstShow= !0;return this},toggle(){this.isVisible?this.hide():this.show();return this},show(){if(this.firstShow||1==this.pos||0===this.pos&&!1===this.isVisible)this.w.style.position="absolute",this.w.style.marginLeft=0,this.w.style.marginTop=0,this.w.style.top=`${this.wy}${this.vh}`,0<=this.wx?this.w.style.left=`${this.wx}${this.vw}`:this.w.style.right=-`${this.wx}${this.vw}`,0