gmaterni commited on
Commit
6aae67a
·
verified ·
1 Parent(s): b031b0b

Upload folder using huggingface_hub

Browse files
LICENSE CHANGED
@@ -1,674 +1,194 @@
1
- GNU GENERAL PUBLIC LICENSE
2
- Version 3, 29 June 2007
3
-
4
- Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
- Everyone is permitted to copy and distribute verbatim copies
6
- of this license document, but changing it is not allowed.
7
-
8
- Preamble
9
-
10
- The GNU General Public License is a free, copyleft license for
11
- software and other kinds of works.
12
-
13
- The licenses for most software and other practical works are designed
14
- to take away your freedom to share and change the works. By contrast,
15
- the GNU General Public License is intended to guarantee your freedom to
16
- share and change all versions of a program--to make sure it remains free
17
- software for all its users. We, the Free Software Foundation, use the
18
- GNU General Public License for most of our software; it applies also to
19
- any other work released this way by its authors. You can apply it to
20
- your programs, too.
21
-
22
- When we speak of free software, we are referring to freedom, not
23
- price. Our General Public Licenses are designed to make sure that you
24
- have the freedom to distribute copies of free software (and charge for
25
- them if you wish), that you receive source code or can get it if you
26
- want it, that you can change the software or use pieces of it in new
27
- free programs, and that you know you can do these things.
28
-
29
- To protect your rights, we need to prevent others from denying you
30
- these rights or asking you to surrender the rights. Therefore, you have
31
- certain responsibilities if you distribute copies of the software, or if
32
- you modify it: responsibilities to respect the freedom of others.
33
-
34
- For example, if you distribute copies of such a program, whether
35
- gratis or for a fee, you must pass on to the recipients the same
36
- freedoms that you received. You must make sure that they, too, receive
37
- or can get the source code. And you must show them these terms so they
38
- know their rights.
39
-
40
- Developers that use the GNU GPL protect your rights with two steps:
41
- (1) assert copyright on the software, and (2) offer you this License
42
- giving you legal permission to copy, distribute and/or modify it.
43
-
44
- For the developers' and authors' protection, the GPL clearly explains
45
- that there is no warranty for this free software. For both users' and
46
- authors' sake, the GPL requires that modified versions be marked as
47
- changed, so that their problems will not be attributed erroneously to
48
- authors of previous versions.
49
-
50
- Some devices are designed to deny users access to install or run
51
- modified versions of the software inside them, although the manufacturer
52
- can do so. This is fundamentally incompatible with the aim of
53
- protecting users' freedom to change the software. The systematic
54
- pattern of such abuse occurs in the area of products for individuals to
55
- use, which is precisely where it is most unacceptable. Therefore, we
56
- have designed this version of the GPL to prohibit the practice for those
57
- products. If such problems arise substantially in other domains, we
58
- stand ready to extend this provision to those domains in future versions
59
- of the GPL, as needed to protect the freedom of users.
60
-
61
- Finally, every program is threatened constantly by software patents.
62
- States should not allow patents to restrict development and use of
63
- software on general-purpose computers, but in those that do, we wish to
64
- avoid the special danger that patents applied to a free program could
65
- make it effectively proprietary. To prevent this, the GPL assures that
66
- patents cannot be used to render the program non-free.
67
-
68
- The precise terms and conditions for copying, distribution and
69
- modification follow.
70
-
71
- TERMS AND CONDITIONS
72
-
73
- 0. Definitions.
74
-
75
- "This License" refers to version 3 of the GNU General Public License.
76
-
77
- "Copyright" also means copyright-like laws that apply to other kinds of
78
- works, such as semiconductor masks.
79
-
80
- "The Program" refers to any copyrightable work licensed under this
81
- License. Each licensee is addressed as "you". "Licensees" and
82
- "recipients" may be individuals or organizations.
83
-
84
- To "modify" a work means to copy from or adapt all or part of the work
85
- in a fashion requiring copyright permission, other than the making of an
86
- exact copy. The resulting work is called a "modified version" of the
87
- earlier work or a work "based on" the earlier work.
88
-
89
- A "covered work" means either the unmodified Program or a work based
90
- on the Program.
91
-
92
- To "propagate" a work means to do anything with it that, without
93
- permission, would make you directly or secondarily liable for
94
- infringement under applicable copyright law, except executing it on a
95
- computer or modifying a private copy. Propagation includes copying,
96
- distribution (with or without modification), making available to the
97
- public, and in some countries other activities as well.
98
-
99
- To "convey" a work means any kind of propagation that enables other
100
- parties to make or receive copies. Mere interaction with a user through
101
- a computer network, with no transfer of a copy, is not conveying.
102
-
103
- An interactive user interface displays "Appropriate Legal Notices"
104
- to the extent that it includes a convenient and prominently visible
105
- feature that (1) displays an appropriate copyright notice, and (2)
106
- tells the user that there is no warranty for the work (except to the
107
- extent that warranties are provided), that licensees may convey the
108
- work under this License, and how to view a copy of this License. If
109
- the interface presents a list of user commands or options, such as a
110
- menu, a prominent item in the list meets this criterion.
111
-
112
- 1. Source Code.
113
-
114
- The "source code" for a work means the preferred form of the work
115
- for making modifications to it. "Object code" means any non-source
116
- form of a work.
117
-
118
- A "Standard Interface" means an interface that either is an official
119
- standard defined by a recognized standards body, or, in the case of
120
- interfaces specified for a particular programming language, one that
121
- is widely used among developers working in that language.
122
-
123
- The "System Libraries" of an executable work include anything, other
124
- than the work as a whole, that (a) is included in the normal form of
125
- packaging a Major Component, but which is not part of that Major
126
- Component, and (b) serves only to enable use of the work with that
127
- Major Component, or to implement a Standard Interface for which an
128
- implementation is available to the public in source code form. A
129
- "Major Component", in this context, means a major essential component
130
- (kernel, window system, and so on) of the specific operating system
131
- (if any) on which the executable work runs, or a compiler used to
132
- produce the work, or an object code interpreter used to run it.
133
-
134
- The "Corresponding Source" for a work in object code form means all
135
- the source code needed to generate, install, and (for an executable
136
- work) run the object code and to modify the work, including scripts to
137
- control those activities. However, it does not include the work's
138
- System Libraries, or general-purpose tools or generally available free
139
- programs which are used unmodified in performing those activities but
140
- which are not part of the work. For example, Corresponding Source
141
- includes interface definition files associated with source files for
142
- the work, and the source code for shared libraries and dynamically
143
- linked subprograms that the work is specifically designed to require,
144
- such as by intimate data communication or control flow between those
145
- subprograms and other parts of the work.
146
-
147
- The Corresponding Source need not include anything that users
148
- can regenerate automatically from other parts of the Corresponding
149
- Source.
150
-
151
- The Corresponding Source for a work in source code form is that
152
- same work.
153
-
154
- 2. Basic Permissions.
155
-
156
- All rights granted under this License are granted for the term of
157
- copyright on the Program, and are irrevocable provided the stated
158
- conditions are met. This License explicitly affirms your unlimited
159
- permission to run the unmodified Program. The output from running a
160
- covered work is covered by this License only if the output, given its
161
- content, constitutes a covered work. This License acknowledges your
162
- rights of fair use or other equivalent, as provided by copyright law.
163
-
164
- You may make, run and propagate covered works that you do not
165
- convey, without conditions so long as your license otherwise remains
166
- in force. You may convey covered works to others for the sole purpose
167
- of having them make modifications exclusively for you, or provide you
168
- with facilities for running those works, provided that you comply with
169
- the terms of this License in conveying all material for which you do
170
- not control copyright. Those thus making or running the covered works
171
- for you must do so exclusively on your behalf, under your direction
172
- and control, on terms that prohibit them from making any copies of
173
- your copyrighted material outside their relationship with you.
174
-
175
- Conveying under any other circumstances is permitted solely under
176
- the conditions stated below. Sublicensing is not allowed; section 10
177
- makes it unnecessary.
178
-
179
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
-
181
- No covered work shall be deemed part of an effective technological
182
- measure under any applicable law fulfilling obligations under article
183
- 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
- similar laws prohibiting or restricting circumvention of such
185
- measures.
186
-
187
- When you convey a covered work, you waive any legal power to forbid
188
- circumvention of technological measures to the extent such circumvention
189
- is effected by exercising rights under this License with respect to
190
- the covered work, and you disclaim any intention to limit operation or
191
- modification of the work as a means of enforcing, against the work's
192
- users, your or third parties' legal rights to forbid circumvention of
193
- technological measures.
194
-
195
- 4. Conveying Verbatim Copies.
196
-
197
- You may convey verbatim copies of the Program's source code as you
198
- receive it, in any medium, provided that you conspicuously and
199
- appropriately publish on each copy an appropriate copyright notice;
200
- keep intact all notices stating that this License and any
201
- non-permissive terms added in accord with section 7 apply to the code;
202
- keep intact all notices of the absence of any warranty; and give all
203
- recipients a copy of this License along with the Program.
204
-
205
- You may charge any price or no price for each copy that you convey,
206
- and you may offer support or warranty protection for a fee.
207
-
208
- 5. Conveying Modified Source Versions.
209
-
210
- You may convey a work based on the Program, or the modifications to
211
- produce it from the Program, in the form of source code under the
212
- terms of section 4, provided that you also meet all of these conditions:
213
-
214
- a) The work must carry prominent notices stating that you modified
215
- it, and giving a relevant date.
216
-
217
- b) The work must carry prominent notices stating that it is
218
- released under this License and any conditions added under section
219
- 7. This requirement modifies the requirement in section 4 to
220
- "keep intact all notices".
221
-
222
- c) You must license the entire work, as a whole, under this
223
- License to anyone who comes into possession of a copy. This
224
- License will therefore apply, along with any applicable section 7
225
- additional terms, to the whole of the work, and all its parts,
226
- regardless of how they are packaged. This License gives no
227
- permission to license the work in any other way, but it does not
228
- invalidate such permission if you have separately received it.
229
-
230
- d) If the work has interactive user interfaces, each must display
231
- Appropriate Legal Notices; however, if the Program has interactive
232
- interfaces that do not display Appropriate Legal Notices, your
233
- work need not make them do so.
234
-
235
- A compilation of a covered work with other separate and independent
236
- works, which are not by their nature extensions of the covered work,
237
- and which are not combined with it such as to form a larger program,
238
- in or on a volume of a storage or distribution medium, is called an
239
- "aggregate" if the compilation and its resulting copyright are not
240
- used to limit the access or legal rights of the compilation's users
241
- beyond what the individual works permit. Inclusion of a covered work
242
- in an aggregate does not cause this License to apply to the other
243
- parts of the aggregate.
244
-
245
- 6. Conveying Non-Source Forms.
246
-
247
- You may convey a covered work in object code form under the terms
248
- of sections 4 and 5, provided that you also convey the
249
- machine-readable Corresponding Source under the terms of this License,
250
- in one of these ways:
251
-
252
- a) Convey the object code in, or embodied in, a physical product
253
- (including a physical distribution medium), accompanied by the
254
- Corresponding Source fixed on a durable physical medium
255
- customarily used for software interchange.
256
-
257
- b) Convey the object code in, or embodied in, a physical product
258
- (including a physical distribution medium), accompanied by a
259
- written offer, valid for at least three years and valid for as
260
- long as you offer spare parts or customer support for that product
261
- model, to give anyone who possesses the object code either (1) a
262
- copy of the Corresponding Source for all the software in the
263
- product that is covered by this License, on a durable physical
264
- medium customarily used for software interchange, for a price no
265
- more than your reasonable cost of physically performing this
266
- conveying of source, or (2) access to copy the
267
- Corresponding Source from a network server at no charge.
268
-
269
- c) Convey individual copies of the object code with a copy of the
270
- written offer to provide the Corresponding Source. This
271
- alternative is allowed only occasionally and noncommercially, and
272
- only if you received the object code with such an offer, in accord
273
- with subsection 6b.
274
-
275
- d) Convey the object code by offering access from a designated
276
- place (gratis or for a charge), and offer equivalent access to the
277
- Corresponding Source in the same way through the same place at no
278
- further charge. You need not require recipients to copy the
279
- Corresponding Source along with the object code. If the place to
280
- copy the object code is a network server, the Corresponding Source
281
- may be on a different server (operated by you or a third party)
282
- that supports equivalent copying facilities, provided you maintain
283
- clear directions next to the object code saying where to find the
284
- Corresponding Source. Regardless of what server hosts the
285
- Corresponding Source, you remain obligated to ensure that it is
286
- available for as long as needed to satisfy these requirements.
287
-
288
- e) Convey the object code using peer-to-peer transmission, provided
289
- you inform other peers where the object code and Corresponding
290
- Source of the work are being offered to the general public at no
291
- charge under subsection 6d.
292
-
293
- A separable portion of the object code, whose source code is excluded
294
- from the Corresponding Source as a System Library, need not be
295
- included in conveying the object code work.
296
-
297
- A "User Product" is either (1) a "consumer product", which means any
298
- tangible personal property which is normally used for personal, family,
299
- or household purposes, or (2) anything designed or sold for incorporation
300
- into a dwelling. In determining whether a product is a consumer product,
301
- doubtful cases shall be resolved in favor of coverage. For a particular
302
- product received by a particular user, "normally used" refers to a
303
- typical or common use of that class of product, regardless of the status
304
- of the particular user or of the way in which the particular user
305
- actually uses, or expects or is expected to use, the product. A product
306
- is a consumer product regardless of whether the product has substantial
307
- commercial, industrial or non-consumer uses, unless such uses represent
308
- the only significant mode of use of the product.
309
-
310
- "Installation Information" for a User Product means any methods,
311
- procedures, authorization keys, or other information required to install
312
- and execute modified versions of a covered work in that User Product from
313
- a modified version of its Corresponding Source. The information must
314
- suffice to ensure that the continued functioning of the modified object
315
- code is in no case prevented or interfered with solely because
316
- modification has been made.
317
-
318
- If you convey an object code work under this section in, or with, or
319
- specifically for use in, a User Product, and the conveying occurs as
320
- part of a transaction in which the right of possession and use of the
321
- User Product is transferred to the recipient in perpetuity or for a
322
- fixed term (regardless of how the transaction is characterized), the
323
- Corresponding Source conveyed under this section must be accompanied
324
- by the Installation Information. But this requirement does not apply
325
- if neither you nor any third party retains the ability to install
326
- modified object code on the User Product (for example, the work has
327
- been installed in ROM).
328
-
329
- The requirement to provide Installation Information does not include a
330
- requirement to continue to provide support service, warranty, or updates
331
- for a work that has been modified or installed by the recipient, or for
332
- the User Product in which it has been modified or installed. Access to a
333
- network may be denied when the modification itself materially and
334
- adversely affects the operation of the network or violates the rules and
335
- protocols for communication across the network.
336
-
337
- Corresponding Source conveyed, and Installation Information provided,
338
- in accord with this section must be in a format that is publicly
339
- documented (and with an implementation available to the public in
340
- source code form), and must require no special password or key for
341
- unpacking, reading or copying.
342
-
343
- 7. Additional Terms.
344
-
345
- "Additional permissions" are terms that supplement the terms of this
346
- License by making exceptions from one or more of its conditions.
347
- Additional permissions that are applicable to the entire Program shall
348
- be treated as though they were included in this License, to the extent
349
- that they are valid under applicable law. If additional permissions
350
- apply only to part of the Program, that part may be used separately
351
- under those permissions, but the entire Program remains governed by
352
- this License without regard to the additional permissions.
353
-
354
- When you convey a copy of a covered work, you may at your option
355
- remove any additional permissions from that copy, or from any part of
356
- it. (Additional permissions may be written to require their own
357
- removal in certain cases when you modify the work.) You may place
358
- additional permissions on material, added by you to a covered work,
359
- for which you have or can give appropriate copyright permission.
360
-
361
- Notwithstanding any other provision of this License, for material you
362
- add to a covered work, you may (if authorized by the copyright holders of
363
- that material) supplement the terms of this License with terms:
364
-
365
- a) Disclaiming warranty or limiting liability differently from the
366
- terms of sections 15 and 16 of this License; or
367
-
368
- b) Requiring preservation of specified reasonable legal notices or
369
- author attributions in that material or in the Appropriate Legal
370
- Notices displayed by works containing it; or
371
-
372
- c) Prohibiting misrepresentation of the origin of that material, or
373
- requiring that modified versions of such material be marked in
374
- reasonable ways as different from the original version; or
375
-
376
- d) Limiting the use for publicity purposes of names of licensors or
377
- authors of the material; or
378
-
379
- e) Declining to grant rights under trademark law for use of some
380
- trade names, trademarks, or service marks; or
381
-
382
- f) Requiring indemnification of licensors and authors of that
383
- material by anyone who conveys the material (or modified versions of
384
- it) with contractual assumptions of liability to the recipient, for
385
- any liability that these contractual assumptions directly impose on
386
- those licensors and authors.
387
-
388
- All other non-permissive additional terms are considered "further
389
- restrictions" within the meaning of section 10. If the Program as you
390
- received it, or any part of it, contains a notice stating that it is
391
- governed by this License along with a term that is a further
392
- restriction, you may remove that term. If a license document contains
393
- a further restriction but permits relicensing or conveying under this
394
- License, you may add to a covered work material governed by the terms
395
- of that license document, provided that the further restriction does
396
- not survive such relicensing or conveying.
397
-
398
- If you add terms to a covered work in accord with this section, you
399
- must place, in the relevant source files, a statement of the
400
- additional terms that apply to those files, or a notice indicating
401
- where to find the applicable terms.
402
-
403
- Additional terms, permissive or non-permissive, may be stated in the
404
- form of a separately written license, or stated as exceptions;
405
- the above requirements apply either way.
406
-
407
- 8. Termination.
408
-
409
- You may not propagate or modify a covered work except as expressly
410
- provided under this License. Any attempt otherwise to propagate or
411
- modify it is void, and will automatically terminate your rights under
412
- this License (including any patent licenses granted under the third
413
- paragraph of section 11).
414
-
415
- However, if you cease all violation of this License, then your
416
- license from a particular copyright holder is reinstated (a)
417
- provisionally, unless and until the copyright holder explicitly and
418
- finally terminates your license, and (b) permanently, if the copyright
419
- holder fails to notify you of the violation by some reasonable means
420
- prior to 60 days after the cessation.
421
-
422
- Moreover, your license from a particular copyright holder is
423
- reinstated permanently if the copyright holder notifies you of the
424
- violation by some reasonable means, this is the first time you have
425
- received notice of violation of this License (for any work) from that
426
- copyright holder, and you cure the violation prior to 30 days after
427
- your receipt of the notice.
428
-
429
- Termination of your rights under this section does not terminate the
430
- licenses of parties who have received copies or rights from you under
431
- this License. If your rights have been terminated and not permanently
432
- reinstated, you do not qualify to receive new licenses for the same
433
- material under section 10.
434
-
435
- 9. Acceptance Not Required for Having Copies.
436
-
437
- You are not required to accept this License in order to receive or
438
- run a copy of the Program. Ancillary propagation of a covered work
439
- occurring solely as a consequence of using peer-to-peer transmission
440
- to receive a copy likewise does not require acceptance. However,
441
- nothing other than this License grants you permission to propagate or
442
- modify any covered work. These actions infringe copyright if you do
443
- not accept this License. Therefore, by modifying or propagating a
444
- covered work, you indicate your acceptance of this License to do so.
445
-
446
- 10. Automatic Licensing of Downstream Recipients.
447
-
448
- Each time you convey a covered work, the recipient automatically
449
- receives a license from the original licensors, to run, modify and
450
- propagate that work, subject to this License. You are not responsible
451
- for enforcing compliance by third parties with this License.
452
-
453
- An "entity transaction" is a transaction transferring control of an
454
- organization, or substantially all assets of one, or subdividing an
455
- organization, or merging organizations. If propagation of a covered
456
- work results from an entity transaction, each party to that
457
- transaction who receives a copy of the work also receives whatever
458
- licenses to the work the party's predecessor in interest had or could
459
- give under the previous paragraph, plus a right to possession of the
460
- Corresponding Source of the work from the predecessor in interest, if
461
- the predecessor has it or can get it with reasonable efforts.
462
-
463
- You may not impose any further restrictions on the exercise of the
464
- rights granted or affirmed under this License. For example, you may
465
- not impose a license fee, royalty, or other charge for exercise of
466
- rights granted under this License, and you may not initiate litigation
467
- (including a cross-claim or counterclaim in a lawsuit) alleging that
468
- any patent claim is infringed by making, using, selling, offering for
469
- sale, or importing the Program or any portion of it.
470
-
471
- 11. Patents.
472
-
473
- A "contributor" is a copyright holder who authorizes use under this
474
- License of the Program or a work on which the Program is based. The
475
- work thus licensed is called the contributor's "contributor version".
476
-
477
- A contributor's "essential patent claims" are all patent claims
478
- owned or controlled by the contributor, whether already acquired or
479
- hereafter acquired, that would be infringed by some manner, permitted
480
- by this License, of making, using, or selling its contributor version,
481
- but do not include claims that would be infringed only as a
482
- consequence of further modification of the contributor version. For
483
- purposes of this definition, "control" includes the right to grant
484
- patent sublicenses in a manner consistent with the requirements of
485
- this License.
486
-
487
- Each contributor grants you a non-exclusive, worldwide, royalty-free
488
- patent license under the contributor's essential patent claims, to
489
- make, use, sell, offer for sale, import and otherwise run, modify and
490
- propagate the contents of its contributor version.
491
-
492
- In the following three paragraphs, a "patent license" is any express
493
- agreement or commitment, however denominated, not to enforce a patent
494
- (such as an express permission to practice a patent or covenant not to
495
- sue for patent infringement). To "grant" such a patent license to a
496
- party means to make such an agreement or commitment not to enforce a
497
- patent against the party.
498
-
499
- If you convey a covered work, knowingly relying on a patent license,
500
- and the Corresponding Source of the work is not available for anyone
501
- to copy, free of charge and under the terms of this License, through a
502
- publicly available network server or other readily accessible means,
503
- then you must either (1) cause the Corresponding Source to be so
504
- available, or (2) arrange to deprive yourself of the benefit of the
505
- patent license for this particular work, or (3) arrange, in a manner
506
- consistent with the requirements of this License, to extend the patent
507
- license to downstream recipients. "Knowingly relying" means you have
508
- actual knowledge that, but for the patent license, your conveying the
509
- covered work in a country, or your recipient's use of the covered work
510
- in a country, would infringe one or more identifiable patents in that
511
- country that you have reason to believe are valid.
512
-
513
- If, pursuant to or in connection with a single transaction or
514
- arrangement, you convey, or propagate by procuring conveyance of, a
515
- covered work, and grant a patent license to some of the parties
516
- receiving the covered work authorizing them to use, propagate, modify
517
- or convey a specific copy of the covered work, then the patent license
518
- you grant is automatically extended to all recipients of the covered
519
- work and works based on it.
520
-
521
- A patent license is "discriminatory" if it does not include within
522
- the scope of its coverage, prohibits the exercise of, or is
523
- conditioned on the non-exercise of one or more of the rights that are
524
- specifically granted under this License. You may not convey a covered
525
- work if you are a party to an arrangement with a third party that is
526
- in the business of distributing software, under which you make payment
527
- to the third party based on the extent of your activity of conveying
528
- the work, and under which the third party grants, to any of the
529
- parties who would receive the covered work from you, a discriminatory
530
- patent license (a) in connection with copies of the covered work
531
- conveyed by you (or copies made from those copies), or (b) primarily
532
- for and in connection with specific products or compilations that
533
- contain the covered work, unless you entered into that arrangement,
534
- or that patent license was granted, prior to 28 March 2007.
535
-
536
- Nothing in this License shall be construed as excluding or limiting
537
- any implied license or other defenses to infringement that may
538
- otherwise be available to you under applicable patent law.
539
-
540
- 12. No Surrender of Others' Freedom.
541
-
542
- If conditions are imposed on you (whether by court order, agreement or
543
- otherwise) that contradict the conditions of this License, they do not
544
- excuse you from the conditions of this License. If you cannot convey a
545
- covered work so as to satisfy simultaneously your obligations under this
546
- License and any other pertinent obligations, then as a consequence you may
547
- not convey it at all. For example, if you agree to terms that obligate you
548
- to collect a royalty for further conveying from those to whom you convey
549
- the Program, the only way you could satisfy both those terms and this
550
- License would be to refrain entirely from conveying the Program.
551
-
552
- 13. Use with the GNU Affero General Public License.
553
-
554
- Notwithstanding any other provision of this License, you have
555
- permission to link or combine any covered work with a work licensed
556
- under version 3 of the GNU Affero General Public License into a single
557
- combined work, and to convey the resulting work. The terms of this
558
- License will continue to apply to the part which is the covered work,
559
- but the special requirements of the GNU Affero General Public License,
560
- section 13, concerning interaction through a network will apply to the
561
- combination as such.
562
-
563
- 14. Revised Versions of this License.
564
-
565
- The Free Software Foundation may publish revised and/or new versions of
566
- the GNU General Public License from time to time. Such new versions will
567
- be similar in spirit to the present version, but may differ in detail to
568
- address new problems or concerns.
569
-
570
- Each version is given a distinguishing version number. If the
571
- Program specifies that a certain numbered version of the GNU General
572
- Public License "or any later version" applies to it, you have the
573
- option of following the terms and conditions either of that numbered
574
- version or of any later version published by the Free Software
575
- Foundation. If the Program does not specify a version number of the
576
- GNU General Public License, you may choose any version ever published
577
- by the Free Software Foundation.
578
-
579
- If the Program specifies that a proxy can decide which future
580
- versions of the GNU General Public License can be used, that proxy's
581
- public statement of acceptance of a version permanently authorizes you
582
- to choose that version for the Program.
583
-
584
- Later license versions may give you additional or different
585
- permissions. However, no additional obligations are imposed on any
586
- author or copyright holder as a result of your choosing to follow a
587
- later version.
588
-
589
- 15. Disclaimer of Warranty.
590
-
591
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
- APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
- HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
- OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
- THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
- PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
- IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
- ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
-
600
- 16. Limitation of Liability.
601
-
602
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
- WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
- THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
- GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
- USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
- DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
- PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
- EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
- SUCH DAMAGES.
611
-
612
- 17. Interpretation of Sections 15 and 16.
613
-
614
- If the disclaimer of warranty and limitation of liability provided
615
- above cannot be given local legal effect according to their terms,
616
- reviewing courts shall apply local law that most closely approximates
617
- an absolute waiver of all civil liability in connection with the
618
- Program, unless a warranty or assumption of liability accompanies a
619
- copy of the Program in return for a fee.
620
-
621
- END OF TERMS AND CONDITIONS
622
-
623
- How to Apply These Terms to Your New Programs
624
-
625
- If you develop a new program, and you want it to be of the greatest
626
- possible use to the public, the best way to achieve this is to make it
627
- free software which everyone can redistribute and change under these terms.
628
-
629
- To do so, attach the following notices to the program. It is safest
630
- to attach them to the start of each source file to most effectively
631
- state the exclusion of warranty; and each file should have at least
632
- the "copyright" line and a pointer to where the full notice is found.
633
-
634
- <one line to give the program's name and a brief idea of what it does.>
635
- Copyright (C) <year> <name of author>
636
-
637
- This program is free software: you can redistribute it and/or modify
638
- it under the terms of the GNU General Public License as published by
639
- the Free Software Foundation, either version 3 of the License, or
640
- (at your option) any later version.
641
-
642
- This program is distributed in the hope that it will be useful,
643
- but WITHOUT ANY WARRANTY; without even the implied warranty of
644
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
- GNU General Public License for more details.
646
-
647
- You should have received a copy of the GNU General Public License
648
- along with this program. If not, see <https://www.gnu.org/licenses/>.
649
-
650
- Also add information on how to contact you by electronic and paper mail.
651
-
652
- If the program does terminal interaction, make it output a short
653
- notice like this when it starts in an interactive mode:
654
-
655
- <program> Copyright (C) <year> <name of author>
656
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
- This is free software, and you are welcome to redistribute it
658
- under certain conditions; type `show c' for details.
659
-
660
- The hypothetical commands `show w' and `show c' should show the appropriate
661
- parts of the General Public License. Of course, your program's commands
662
- might be different; for a GUI interface, you would use an "about box".
663
-
664
- You should also get your employer (if you work as a programmer) or school,
665
- if any, to sign a "copyright disclaimer" for the program, if necessary.
666
- For more information on this, and how to apply and follow the GNU GPL, see
667
- <https://www.gnu.org/licenses/>.
668
-
669
- The GNU General Public License does not permit incorporating your program
670
- into proprietary programs. If your program is a subroutine library, you
671
- may consider it more useful to permit linking proprietary applications with
672
- the library. If this is what you want to do, use the GNU Lesser General
673
- Public License instead of this License. But first, please read
674
- <https://www.gnu.org/licenses/why-not-lgpl.html>.
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an "explicit" notice).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
124
+ any Contribution intentionally submitted for inclusion in the Work
125
+ by You to the Licensor shall be under the terms and conditions of
126
+ this License, without any additional terms or conditions.
127
+ Notwithstanding the above, nothing herein shall supersede or modify
128
+ the terms of any separate license agreement you may have executed
129
+ with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor,
133
+ except as required for reasonable and customary use in describing the
134
+ origin of the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or
137
+ agreed to in writing, Licensor provides the Work (and each
138
+ Contributor provides its Contributions) on an "AS IS" BASIS,
139
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
140
+ implied, including, without limitation, any warranties or conditions
141
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
142
+ PARTICULAR PURPOSE. You are solely responsible for determining the
143
+ appropriateness of using or redistributing the Work and assume any
144
+ risks associated with Your exercise of permissions under this License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory,
147
+ whether in tort (including negligence), contract, or otherwise,
148
+ unless required by applicable law (such as deliberate and grossly
149
+ negligent acts) or agreed to in writing, shall any Contributor be
150
+ liable to You for damages, including any direct, indirect, special,
151
+ incidental, or consequential damages of any character arising as a
152
+ result of this License or out of the use or inability to use the
153
+ Work (including but not limited to damages for loss of goodwill,
154
+ work stoppage, computer failure or malfunction, or any and all
155
+ other commercial damages or losses), even if such Contributor
156
+ has been advised of the possibility of such damages.
157
+
158
+ 9. Accepting Warranty or Additional Liability. While redistributing
159
+ the Work or Derivative Works thereof, You may choose to offer,
160
+ and charge a fee for, acceptance of support, warranty, indemnity,
161
+ or other liability obligations and/or rights consistent with this
162
+ License. However, in accepting such obligations, You may act only
163
+ on Your own behalf and on Your sole responsibility, not on behalf
164
+ of any other Contributor, and only if You agree to indemnify,
165
+ defend, and hold each Contributor harmless for any liability
166
+ incurred by, or claims asserted against, such Contributor by reason
167
+ of your accepting any such warranty or additional liability.
168
+
169
+ END OF TERMS AND CONDITIONS
170
+
171
+ APPENDIX: How to apply the Apache License to your work.
172
+
173
+ To apply the Apache License to your work, attach the following
174
+ boilerplate notice, with the fields enclosed by brackets "[]"
175
+ replaced with your own identifying information. (Don't include
176
+ the brackets!) The text should be enclosed in the appropriate
177
+ comment syntax for the file format. We also recommend that a
178
+ file or class name and description of purpose be included on the
179
+ same "printed page" as the copyright notice for easier
180
+ identification within third-party archives.
181
+
182
+ Copyright [yyyy] [name of copyright owner]
183
+
184
+ Licensed under the Apache License, Version 2.0 (the "License");
185
+ you may not use this file except in compliance with the License.
186
+ You may obtain a copy of the License at
187
+
188
+ http://www.apache.org/licenses/LICENSE-2.0
189
+
190
+ Unless required by applicable law or agreed to in writing, software
191
+ distributed under the License is distributed on an "AS IS" BASIS,
192
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
193
+ See the License for the specific language governing permissions and
194
+ limitations under the License.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
index.html CHANGED
@@ -1,31 +1,31 @@
1
  <!DOCTYPE html>
2
 
3
  <head>
4
- <title>ulaquery.html</title>
5
- <style>
6
- html {
7
- color: #04c61b
8
- }
9
 
10
- body {
11
- background-color: #333;
12
- color: #fff;
13
- text-align: center;
14
- padding-top: 50px;
15
- font-size: 24px;
16
- font-family: Arial, sans-serif;
17
- }
18
- </style>
19
  </head>
20
 
21
  <body>
22
- <h2>RagRqs</h2>
23
- <br>
24
- <br>
25
- <h3>Lggi_Per_Me</h3>
26
- <script>
27
- setTimeout(function () { location.replace('static/ragrqs.html'); }, 1000);
28
- </script>
29
  </body>
30
 
31
  </html>
 
1
  <!DOCTYPE html>
2
 
3
  <head>
4
+ <title>ragrqs</title>
5
+ <style>
6
+ html {
7
+ color: #04c61b
8
+ }
9
 
10
+ body {
11
+ background-color: #333;
12
+ color: #fff;
13
+ text-align: center;
14
+ padding-top: 50px;
15
+ font-size: 24px;
16
+ font-family: Arial, sans-serif;
17
+ }
18
+ </style>
19
  </head>
20
 
21
  <body>
22
+ <h2>RagRqs</h2>
23
+ <br>
24
+ <br>
25
+ <h3>Lggi_Per_Me</h3>
26
+ <script>
27
+ setTimeout(function () { location.replace('static/ragrqs.html'); }, 1000);
28
+ </script>
29
  </body>
30
 
31
  </html>
static/css/ragquery.min.css ADDED
@@ -0,0 +1 @@
 
 
1
+ #ualog_{box-sizing:border-box;width:auto;height:auto;text-align:center;padding:2px;margin:2px 0 0;background:#333;color:#fff;font-size:16px;font-weight:400;border-radius:9px;border:1px solid #999}#ualog_ button{padding:5px;margin:0 5px;font-size:18px;font-weight:700;border:2px solid #888;border-radius:10px;color:#000}#ualog_ button:hover{cursor:pointer;text-decoration:underline}#ualog_ button.close{background:#cc3700}#ualog_ button.close:hover{background:#ff8f66;border-color:#992900}#ualog_ button.clear{background:#b3a80b}#ualog_ button.clear:hover{background:#f5ec62;border-color:#837b08}#ualog_ pre{box-sizing:border-box;width:auto;min-width:400px;max-width:400px;max-height:500px;text-align:left;font-size:16px;font-family:monospace;padding:2px;margin:2px;color:#fff;background:#111;overflow:auto;scrollbar-color:#23eb04 #454444;scrollbar-width:auto;word-wrap:break-word}a,body,button,div,html,input,label,li,p,span,table,td,ul{padding:0;margin:0;font-family:arial,verdana,Helvetica,sans-serif}.bb0{background:#daee59!important}.bb1{background:#5487fc!important}html{background:#1a1a1a}body{background:#1a1a1a;box-sizing:border-box;min-height:100vh;height:100vh;position:relative;padding:0;margin:0;overflow:hidden;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400}.spinner{z-index:1000;position:absolute;top:70vh;left:50vw;transform:translate(-50%,-50%);cursor:pointer;display:none;align-items:center}.spinner .pulse-icon{width:20px;height:20px;background-color:#ff8c00;border-radius:50%;animation:1.5s ease-in-out infinite pulse}.spinner .stop-message{margin-left:15px;background-color:inherit;color:#8f8a8a;padding:8px 15px;border-radius:10px;font-size:22px;font-weight:700;opacity:1;transition:opacity .3s}.spinner:hover .stop-message{color:#fff;background:#595959;opacity:1}@keyframes pulse{0%{transform:scale(.6);box-shadow:0 0 0 0 rgba(255,140,0,.7)}70%{transform:scale(1.4);box-shadow:0 0 0 20px rgba(255,140,0,0)}100%{transform:scale(.6);box-shadow:0 0 0 0 rgba(255,140,0,0)}}.show-spinner{display:flex}.theme-dark .btn-light,.theme-light .btn-dark{display:inline-block!important}.inver svg,.invert,.invert .inv,.invert .tt-bottom::before,.invert .tt-left::before,.invert .tt-right::before,.invert .tt-top::before,.invert iframe,.invert img,.invert video{filter:invert(100%) hue-rotate(180deg)}.btn-theme{position:fixed;top:0;right:10vw;height:4vh;background:inherit;font-weight:700;margin-left:5vw;margin-top:.5vh;z-index:2000}.btn-theme button{color:#fff;border:none;background:0 0;cursor:pointer;padding:5px;display:none}.btn-theme button svg{width:24px;height:24px;stroke:currentColor}.upload{background-color:#1e1e1e;padding:0 2em 2em;margin:0;border-radius:4px;box-shadow:0 2px 4px rgba(0,0,0,.5);text-align:center}.upload h4{color:#fff;margin-bottom:1em}.upload form{display:flex;flex-direction:column;align-items:center}.upload form .file{background-color:#121212;border:1px solid #515151;color:#fff;padding:.5em;margin-bottom:1em;border-radius:4px;width:100%;box-sizing:border-box}.upload form .file::file-selector-button{background-color:#003e31;color:#fff;border:none;padding:.5em 1em;border-radius:4px;cursor:pointer}.upload form .file::file-selector-button:hover{background-color:#000b08}.upload form button{background-color:#003e31;color:#fff;border:none;padding:.5em 1em;border-radius:4px;cursor:pointer;width:100%;box-sizing:border-box}.upload form button:hover{background-color:#000b08}.upload .result{width:100%;background:#000;color:#fff;font-size:15px;font-weight:400;text-align:left}.copied{background-color:#0d0d0d!important;color:#24ffd3!important}div.container{background:#1a1a1a;box-sizing:border-box;position:relative;top:5vh;left:0;height:95vh;margin:0;padding:0;transition:margin-left .5s;display:flex;flex-direction:column;justify-content:flex-start;align-items:stretch;flex-wrap:nowrap;overflow-y:auto;overflow-x:auto}div.container div.item{box-sizing:border-box;min-height:50px;margin:0;padding:0}div.container div.item1{flex:5;padding:.5vh .5vw 10vh}div.container div.item1 .output-wrapper{background-color:#1a1a1a;border-radius:20px;position:relative;bottom:0;right:0;left:0;width:100%;height:100%;display:flex;flex-direction:row;align-items:flex-start}div.container div.item1 .output-wrapper .text-out{flex:1;box-sizing:border-box;background:#000;color:#fff;border:none;padding:2px;margin:0;min-width:50vw;height:100%;border-radius:10px;overflow-y:auto;outline:0;box-shadow:0 0 0 2px #4d4d4d}div.container div.item1 .output-wrapper .text-out:hover{box-shadow:0 0 0 2px #00bd97}div.container div.item1 .output-wrapper .text-out .pre-text{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:20px;line-height:1.5;padding:2px;margin:0;height:100%;box-sizing:border-box;overflow-y:auto;scroll-behavior:smooth}div.container div.item1 .output-wrapper .text-out .pre-text.copied{background-color:#0d0d0d;color:#24ffd3}div.container div.item1 .output-wrapper .text-out .div-text{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:20px;line-height:1.5;padding:2px;margin:0;height:100%;box-sizing:border-box;overflow-y:scroll}div.container div.item1 .output-wrapper .text-out .user{border:2px solid #00bd97!important;border-radius:10px;padding:2px 2px 3px 10px;margin:2px 5px 5px 150px}div.container div.item1 .output-wrapper .text-out .user b{font-weight:700;text-decoration:underline;color:#ff4500;padding-bottom:5px}div.container div.item1 .output-wrapper .text-out .assistant{border:2px solid #ff4500!important;border-radius:10px;padding:2px 2px 3px 10px;margin:2px 90px 5px 6px}div.container div.item1 .output-wrapper .text-out .assistant b{font-weight:700;text-decoration:underline;color:#00bd97;padding-bottom:5px}div.container div.item1 .output-actions{display:flex;flex-direction:column;align-items:flex-end;margin-left:.5vw;margin-right:.5vw}div.container div.item1 .output-actions .clear-output,div.container div.item1 .output-actions .copy-output,div.container div.item1 .output-actions .wnd-output{box-sizing:border-box;background-color:#333;color:#fff;border:none;padding:10px;cursor:pointer;border-radius:50%;width:40px;height:40px;display:flex;align-items:center;margin-bottom:5px}div.container div.item1 .output-actions .clear-output:hover,div.container div.item1 .output-actions .copy-output:hover,div.container div.item1 .output-actions .wnd-output:hover{background-color:#595959}div.container div.item1 .output-actions .copy-output{transition:background-color .3s,transform .3s}div.container div.item1 .output-actions .copy-output.copied{background:#00f0c0;transform:scale(1.2)}div.container div.item1 .output-actions .copy-output .copy-icon{fill:#fff;width:24px;height:24px}div.container div.item1 .output-actions .copy-output .copy-icon:hover{fill:#00f0c0}div.container div.item1 .output-actions .clear-output,div.container div.item1 .output-actions .wnd-output{transition:background-color .3s,transform .3s}div.container div.item1 .output-actions .clear-output .icon,div.container div.item1 .output-actions .wnd-output .icon{fill:#fff;width:24px;height:24px}div.container div.item1 .output-actions .clear-output .icon:hover,div.container div.item1 .output-actions .wnd-output .icon:hover{fill:#00f0c0}:hover{outline:0;caret-color:transparent}textarea:focus{caret-color:auto}div.item2{flex:2;padding:0 .5vw}div.item2 .input-wrapper{background-color:#1a1a1a;border-radius:20px;position:relative;bottom:2vh;right:0;left:0;width:100%;height:100%;display:flex;flex-direction:row;align-items:flex-start}div.item2 .input-wrapper:focus-within .clear-button{display:block}div.item2 .input-wrapper .text-input{flex:1;font-size:20px;font-family:arial,verdana,Helvetica,sans-serif;resize:none;box-sizing:border-box;background:#000;color:#fff;border:none;padding:2px 40px 2px 2px;height:100%;margin-left:5px;border-radius:10px;overflow-y:auto;outline:0;box-shadow:0 0 0 2px #4d4d4d}div.item2 .input-wrapper .text-input:hover{box-shadow:0 0 0 2px #00bd97}div.item2 .input-wrapper .text-input:focus{box-shadow:0 0 0 2px #ff4500}div.item2 .input-wrapper .clear-button{position:absolute;right:60px;top:19vh;padding:5px;border-radius:50%;background:#333;border:none;font-size:20px;cursor:pointer;color:#ccc;display:none}div.item2 .input-wrapper .clear-button:hover{font-weight:700;background:#595959;color:#fff}div.item2 .input-wrapper .input-actions{display:flex;flex-direction:column;margin-left:.5vw;margin-right:.5vw}div.item2 .input-wrapper .input-actions .clear-input,div.item2 .input-wrapper .input-actions .send-input,div.item2 .input-wrapper .input-actions .send2-input{box-sizing:border-box;background-color:#333;color:#fff;border:none;padding:10px;cursor:pointer;border-radius:50%;width:40px;height:40px;margin-bottom:5px;transition:background-color .3s}div.item2 .input-wrapper .input-actions .send-input{background:#992900}div.item2 .input-wrapper .input-actions .send-input:hover{background:#ff4500}div.item2 .input-wrapper .input-actions .send2-input{background:#005746}div.item2 .input-wrapper .input-actions .send2-input:hover{background:#00a383}div.item2 .input-wrapper .input-actions .clear-input{background:#333;color:#e6e6e6}div.item2 .input-wrapper .input-actions .clear-input:hover{background:#595959;color:#00f0c0}.menu-open .container{margin-left:16vw}.menu-open .menu-box{left:0!important}div.menu-h{background-color:#1a1a1a;position:fixed;top:0;left:0;width:100vw;height:4.5vh;padding:0;margin:0;outline:0;box-shadow:0 0 0 2px #4d4d4d;z-index:100}div.menu-h .release{background:inherit;color:#fff;font-size:15px;font-weight:400;margin-left:.6vw;margin-top:.8vh;position:fixed;top:.2vh;right:.4vw;height:4vh}div.menu-h .menu-btn{appearance:none}div.menu-h .menu-btn:checked+.menu-icon .nav-icon::before{content:"X"}div.menu-h .menu-icon{box-sizing:border-box;background-color:inherit;display:block;position:absolute;margin-left:2vw;top:0;left:0;width:25px;height:100%;cursor:pointer;padding:2px;z-index:1}div.menu-h .menu-icon:hover .nav-icon::before{color:#ff4500}div.menu-h .nav-icon::before{content:"☰";position:absolute;left:0;color:#aea7a7;font-size:25px;transition-duration:.25s}div.menu-h .head-wrapper{position:absolute;top:0;left:5vw;height:4vh;padding:0;margin:0;display:inline-flex;flex-direction:row;flex-wrap:nowrap;align-items:center;justify-content:flex-start}div.menu-h .head-wrapper .help,div.menu-h .head-wrapper .log,div.menu-h .head-wrapper .upload,div.menu-h .head-wrapper .upload-dir{margin-top:2px;margin-left:30px;margin-right:0;padding:5px 5px 0;border:none;cursor:pointer;border-radius:20%;font-size:20px;color:#fff;background:#333;max-height:4vh}div.menu-h .head-wrapper .help:hover,div.menu-h .head-wrapper .log:hover,div.menu-h .head-wrapper .upload-dir:hover,div.menu-h .head-wrapper .upload:hover{background:#595959}div.menu-h .upload,div.menu-h .upload-dir{transition:background-color .3s,transform .3s}div.menu-h .upload .icon,div.menu-h .upload-dir .icon{fill:#fff;width:24px;height:24px}div.menu-h .upload .icon:hover,div.menu-h .upload-dir .icon:hover{fill:#00f0c0}div.menu-h .log{font-size:14px!important;font-weight:400!important;background:#992900!important}div.menu-h .log:hover{background:#cc3700!important}div.menu-h .log.active{background:#005746!important}div.menu-h .log.active:hover{background:#008a6e!important}div.menu-h div.menu-box{position:fixed;top:5vh;left:-2000px;height:95vh;width:16vw;transition:left .3s ease-out;padding:1vh 0 0 .5vw;z-index:101;background:#0d0d0d;box-sizing:border-box;outline:0;box-shadow:0 0 0 2px #4d4d4d;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;overflow-y:auto;overflow-x:auto}div.menu-h div.menu-box ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;border-top:1px solid #333}div.menu-h div.menu-box ul li{border-left:1px solid #333;border-right:1px solid #333;border-bottom:1px solid #333}div.menu-h div.menu-box ul li a{color:#fff;font-size:14px;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400;display:block;margin:0;padding:2px 2px 2px 0;text-align:left;text-decoration:none}div.menu-h div.menu-box ul li:hover{text-decoration:underline;background-color:#333;color:#ff4500}div.menu-h div.menu-box ul a.delete,div.menu-h div.menu-box ul a.help{text-align:center;font-weight:700;font-style:italic;color:#fff;background:#cc3700}div.menu-h div.menu-box ul li.show{background:#000;color:#fff;width:100%;text-align:center;box-sizing:border-box}div.menu-h div.menu-box ul li.show:hover{text-decoration:none}.window-text{position:relative;top:0;left:0;background:#1a1a1a;color:#fff;border:none;padding:0 2px 2px;width:78vw;height:80vh;border-radius:10px;box-sizing:border-box;outline:0;box-shadow:0 0 0 2px #b3a80b;overflow-y:auto;overflow-x:auto}.window-text pre.pre-text{color:#f8f292;white-space:pre-wrap;word-wrap:break-word;font-family:Georigia,"Ties New Roman",serif;font-size:18px;line-height:1.6;padding:2px;margin:0;text-align:left}.window-text div.div-text{color:#f8f292;word-wrap:break-word;font-family:Georigia,"Ties New Roman",serif;font-size:18px;padding:0 2px;margin:0}.window-text div.div-text ul{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;border-top:1px solid #333}.window-text div.div-text ul li{border-left:1px solid #333;border-right:1px solid #333;border-bottom:1px solid #333}.window-text div.div-text ul li a{color:#fff;font-size:14px;font-family:arial,verdana,Helvetica,sans-serif;font-weight:400;display:block;margin:0;padding:5px 2px 2px 0;text-align:left;text-decoration:none}.window-text div.div-text ul li:hover{text-decoration:underline;background-color:#333;color:#ff4500}.window-text div.text{font-size:18px;font-weight:400;padding-left:10px;padding-right:10px;margin:0}.window-text div.text pre{white-space:pre-wrap;word-wrap:break-word;font-family:arial,verdana,Helvetica,sans-serif;font-size:18px;line-height:1.3;padding:0 5px;margin:0;text-align:left}.window-text div.text .center{text-align:center;font-size:18px;font-weight:700;text-decoration:underline;font-style:italic;color:#e3d50e}.window-text div.text .label{margin:5px 0 5px 10px;font-size:18px;font-weight:700;font-style:italic;color:#e3d50e}.window-text div.text div{font-family:arial,verdana,Helvetica,sans-serif;font-size:18px;font-weight:700;padding-top:0;padding-bottom:0}.window-text div.text div a{background:#000;color:#fff;font-weight:400}.window-text div.text div a:hover{background:#333;color:#fff}.window-text div.text p{font-size:18px;font-weight:400;font-family:arial,verdana,Helvetica,sans-serif;text-align:justify;padding-bottom:9px;padding-right:0;padding-left:10px}.btn-wrapper{width:100%;height:2vw;position:sticky;top:0;padding:0;background:#262626}.btn-wrapper .btn-copy{position:absolute;top:1px;right:5vw;box-sizing:border-box;background:inherit;color:#fff;border:none;cursor:pointer;width:30px;margin:0;padding:0;transition:background-color .3s}.btn-wrapper .btn-copy:hover{background-color:#595959}.btn-wrapper .btn-copy .copy-icon{fill:#e6e6e6;width:20px;height:20px}.btn-wrapper .btn-copy .copy-icon:hover{fill:#00f0c0;background:#404040}.btn-wrapper .btn-close{position:absolute;top:0;right:2vw;margin:0;background-color:transparent;border:none;color:#e6e6e6;font-size:22px;font-weight:700;cursor:pointer;outline:0}.btn-wrapper .btn-close:hover{color:#00f0c0;background:#404040}.tt-bottom,.tt-left,.tt-leftx,.tt-right,.tt-top{position:relative;transition:transform .2s}.tt-bottom::after,.tt-bottom::before,.tt-left::after,.tt-left::before,.tt-leftx::after,.tt-leftx::before,.tt-right::after,.tt-right::before,.tt-top::after,.tt-top::before{position:absolute;opacity:0;pointer-events:none;z-index:9999;transition:opacity .3s}.tt-bottom::before,.tt-left::before,.tt-leftx::before,.tt-right::before,.tt-top::before{content:attr(data-tt);background:#cc3a05;color:#fff;font:400 20px Arial,sans-serif;padding:4px 10px;border-radius:4px;box-shadow:0 3px 6px #e2ca0e29;white-space:nowrap}.tt-bottom:hover::after,.tt-bottom:hover::before,.tt-left:hover::after,.tt-left:hover::before,.tt-leftx:hover::after,.tt-leftx:hover::before,.tt-right:hover::after,.tt-right:hover::before,.tt-top:hover::after,.tt-top:hover::before{opacity:1}.tt-top::before{bottom:calc(100% + 12px);left:50%;transform:translateX(-50%)}.tt-bottom::before{top:calc(100% + 12px);left:50%;transform:translateX(-50%)}.tt-left::before{right:calc(50% + 0px);top:calc(100% + 22px);transform:translateY(-50%)}.tt-leftx::before{right:calc(50% + 20px);top:calc(100% + 22px);transform:translateY(-80%)}.tt-right::before{left:calc(100% + 12px);top:50%;transform:translateY(50%)}.alert-dialog,.confirm-dialog{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) scale(.9);opacity:0;visibility:hidden;background:#2d2d2d;padding:2rem;border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,.3);z-index:10001;min-width:320px;max-width:90%;transition:.3s cubic-bezier(.4, 0, .2, 1)}.alert-dialog.show,.confirm-dialog.show{opacity:1;visibility:visible;transform:translate(-50%,-50%) scale(1)}.alert-dialog h4,.confirm-dialog h4{margin:0 0 2rem;color:#f5f5f5;font-size:1.25rem;font-weight:500;line-height:1.4;text-align:center}.alert-dialog .buttons,.confirm-dialog .buttons{display:flex;gap:1rem;justify-content:center}.alert-dialog button,.confirm-dialog button{border:none;padding:.75rem 1.5rem;border-radius:6px;font-weight:500;text-transform:uppercase;letter-spacing:.05em;cursor:pointer;transition:.2s}.alert-dialog button:focus,.confirm-dialog button:focus{outline:rgba(255,255,255,.5) solid 2px;outline-offset:2px}.alert-dialog button.ok,.confirm-dialog button.ok{background:#4caf50;color:#fff}.alert-dialog button.ok:hover,.confirm-dialog button.ok:hover{background:#409343}.alert-dialog button.cancel,.confirm-dialog button.cancel{background:#f44336;color:#fff}.alert-dialog button.cancel:hover,.confirm-dialog button.cancel:hover{background:#f21f0f}.confirm-dialog{border:2px solid #4caf50}.alert-dialog{border:2px solid #2196f3}.alert-dialog .ok{background:#2196f3}.alert-dialog .ok:hover{background:#0c82df}.overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,.7);opacity:0;visibility:hidden;z-index:10000;transition:opacity .3s}.overlay.show{opacity:1;visibility:visible}#ualog_id{box-sizing:border-box;width:auto;height:auto;text-align:center;padding:2px;margin:2px 0 0;background:#333;color:#fff;font-size:16px;font-weight:400;border-radius:9px;border:1px solid #999}#ualog_id button{padding:5px;margin:0 5px;font-size:18px;font-weight:700;border:2px solid #888;border-radius:10px;color:#000}#ualog_id button:hover{cursor:pointer;text-decoration:underline}#ualog_id button.close{background:#cc3700}#ualog_id button.close:hover{background:#ff8f66;border-color:#992900}#ualog_id button.clear{background:#b3a80b}#ualog_id button.clear:hover{background:#f5ec62;border-color:#837b08}#ualog_id pre{box-sizing:border-box;width:auto;min-width:400px;max-width:400px;max-height:500px;text-align:left;font-size:16px;font-family:monospace;padding:2px;margin:2px;color:#fff;background:#111;overflow:auto;scrollbar-color:#23eb04 #454444;scrollbar-width:auto;word-wrap:break-word}
static/data/help_test.html CHANGED
@@ -1,29 +1,29 @@
1
  <div class="text">
2
  <br>
3
  <p class="label">Software Open SOurce</p>
4
- <div><a href="#" onCLick="loadTestoEsempio('aaron_swartz.txt');">Aaron Swartz</a></div>
5
  <br>
6
- <div><a href="#" onCLick="loadTestoEsempio('roberto_busa.txt');">Roberto Busa</a></div>
7
  <br>
8
- <div><a href="#" onCLick="loadTestoEsempio('la_cattedrale_e_il_bazaar.txt');">La cattedrale e il Bazar</a></div>
9
  <br>
10
 
11
  <p class="label">Ramanzi</p>
12
- <div><a href="#" onCLick="loadTestoEsempio('i_promessi_sposi.txt');">I Promessi Sposi</a></div>
13
  <br>
14
- <div><a href="#" onCLick="loadTestoEsempio('aristotele_detective.txt');">Aristotele Detective</a></div>
15
  <br>
16
- <div><a href="#" onCLick="loadTestoEsempio('montecristo.txt');">Il Conte di Montecristo</a></div>
17
  <br>
18
- <div><a href="#" onCLick="loadTestoEsempio('il_segreto_di_pietramala.txt');">Il Segreto di Pietramala</a></div>
19
  <br>
20
 
21
  <p class="label">Psicologia Junghiana</p>
22
- <div><a href="#" onCLick="loadTestoEsempio('il_libro_rosso.txt');">Il libro rosso</a></div>
23
  <br>
24
 
25
  <p class="label">Alchimia</p>
26
- <div><a href="#" onCLick="loadTestoEsempio('lettere_musulmane.txt');">Lettere Mussulmane</a></div>
27
 
28
  <!--
29
  aaron_swartz.txt
 
1
  <div class="text">
2
  <br>
3
  <p class="label">Software Open SOurce</p>
4
+ <div><a href="#" onclick="loadTestoEsempio('aaron_swartz.txt');">Aaron Swartz</a></div>
5
  <br>
6
+ <div><a href="#" onclick="loadTestoEsempio('roberto_busa.txt');">Roberto Busa</a></div>
7
  <br>
8
+ <div><a href="#" onclick="loadTestoEsempio('la_cattedrale_e_il_bazaar.txt');">La cattedrale e il Bazar</a></div>
9
  <br>
10
 
11
  <p class="label">Ramanzi</p>
12
+ <div><a href="#" onclick="loadTestoEsempio('i_promessi_sposi.txt');">I Promessi Sposi</a></div>
13
  <br>
14
+ <div><a href="#" onclick="loadTestoEsempio('aristotele_detective.txt');">Aristotele Detective</a></div>
15
  <br>
16
+ <div><a href="#" onclick="loadTestoEsempio('montecristo.txt');">Il Conte di Montecristo</a></div>
17
  <br>
18
+ <div><a href="#" onclick="loadTestoEsempio('il_segreto_di_pietramala.txt');">Il Segreto di Pietramala</a></div>
19
  <br>
20
 
21
  <p class="label">Psicologia Junghiana</p>
22
+ <div><a href="#" onclick="loadTestoEsempio('il_libro_rosso.txt');">Il libro rosso</a></div>
23
  <br>
24
 
25
  <p class="label">Alchimia</p>
26
+ <div><a href="#" onclick="loadTestoEsempio('lettere_musulmane.txt');">Lettere Mussulmane</a></div>
27
 
28
  <!--
29
  aaron_swartz.txt
static/javascript/app.js CHANGED
@@ -1,76 +1,227 @@
1
  /** @format */
2
- /**
3
- * @license
4
- * rag_rqs
5
- * Copyright (C) 2024 [Il tuo nome]
6
- *
7
- * This program is free software: you can redistribute it and/or modify
8
- * it under the terms of the GNU General Public License as published by
9
- * the Free Software Foundation, either version 3 of the License, or
10
- * (at your option) any later version.
11
- *
12
- * This program is distributed in the hope that it will be useful,
13
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- * GNU General Public License for more details.
16
- *
17
- * You should have received a copy of the GNU General Public License
18
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
- */
20
-
21
- "use strict";
22
- const VERS = "0.1.63";
23
-
24
- var xlog = console.log;
25
- var xerror = console.error;
26
- // let T0 = {};
27
-
28
- // var start_performance = function (k) {
29
- // T0.k = performance.now();
30
- // };
31
-
32
- // var log_performance = function (k, msg = "") {
33
- // const t1 = performance.now();
34
- // const d = t1 - T0.k;
35
- // console.log(msg, d);
36
- // T0.k = t1;
37
- // return d;
38
- // };
39
-
40
- // function showMessage(message, duraction = 5000) {
41
- // const popup = document.createElement("div");
42
- // popup.className = "msg";
43
- // popup.innerText = message;
44
- // document.body.appendChild(popup);
45
- // setTimeout(function () {
46
- // document.body.removeChild(popup);
47
- // }, duraction);
48
- // }
49
-
50
- const cancelRequest = () => {
51
- const ok = confirm("Confermi Cancellazione Richeista ?");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  if (!ok) return;
53
- HfRequest.cancelRequest();
54
  hideSpinner();
55
  };
56
 
57
  const showSpinner = () => {
58
  const spinner = document.getElementById("spinner");
59
  spinner.classList.add("show-spinner");
60
- spinner.addEventListener("click", cancelRequest);
61
  };
62
 
63
  const hideSpinner = () => {
64
  const spinner = document.getElementById("spinner");
65
  spinner.classList.remove("show-spinner");
66
- spinner.removeEventListener("click", cancelRequest);
67
  };
68
 
69
- var tm;
70
-
71
  function openApp() {
72
  setTimeout(() => {
73
- tm = umgm();
74
  wnds.init();
75
  Menu.init();
76
  TextInput.init();
@@ -83,27 +234,10 @@ function openApp() {
83
  }, 10);
84
  }
85
 
86
- // function openApp() {
87
- // tm = umgm();
88
- // wnds.init();
89
- // Menu.init();
90
- // TextInput.init();
91
- // TextOutput.init();
92
- // Rag.init();
93
- // document.querySelector(".menu-btn").checked = false;
94
- // release();
95
- // showHistory();
96
- // }
97
-
98
  // Visualizza la storia della conversazione
99
  function showHistory() {
100
  const txt = ThreadMgr.getThread();
101
  setOutText(txt);
102
- // const p = document.querySelector("#id-text-out .pre-text");
103
- // p.textContent = txt;
104
- // setTimeout(() => {
105
- // p.scrollTop = p.scrollHeight;
106
- // }, 0);
107
  }
108
 
109
  function release() {
@@ -111,16 +245,14 @@ function release() {
111
  }
112
 
113
  // README
114
- const op0 = async function (e) {
115
- const text = await requestGet("./help1.html");
116
- wnds.wdiv.show(text);
117
  };
118
 
119
  //query iniziale
120
  function showQuery(e) {
121
  const txt = `\n${Rag.ragQuery}`;
122
  wnds.wpre.show(txt);
123
- // Menu.close();
124
  }
125
 
126
  //Risposta Rsg
@@ -153,8 +285,7 @@ function elencoRisposte(e) {
153
 
154
  //contesto
155
  function showContesto(e) {
156
- const txt = `${Rag.ragContext}`;
157
- wnds.wpre.show(txt);
158
  }
159
 
160
  //elemco dati
@@ -183,7 +314,7 @@ function elencoDocs() {
183
  DataMgr.readDbDocNames();
184
  const arr = DataMgr.doc_names;
185
  const fh = (x, i) => `
186
- <li><a href="#" onCLick="showT(${i});">${i + 1}.${x}</a></li>
187
  `;
188
  const jfh = UaJtfh();
189
  let i = 0;
@@ -222,8 +353,8 @@ function calcQuery() {
222
  }
223
 
224
  //cancella dati
225
- function deleteDati(e) {
226
- const ok = confirm("Confermi cancellazione dati?");
227
  if (ok) {
228
  DataMgr.deleteJsonDati();
229
  wnds.wdiv.close();
@@ -233,8 +364,8 @@ function deleteDati(e) {
233
  }
234
 
235
  //cancella localstrage
236
- function deleteSttorage(e) {
237
- const ok = confirm("Confermi cancellazione documenti & dati?");
238
  if (ok) {
239
  DataMgr.deleteJsonDati();
240
  localStorage.clear();
@@ -259,10 +390,8 @@ function loadTestoEsempio(name) {
259
  wnds.wdiv.close();
260
  }
261
 
262
- //domande di esempio
263
- async function help2(e) {
264
- const text = await requestGet("./help2.html");
265
- wnds.wdiv.show(text);
266
  }
267
 
268
  const themeKey = "theme";
@@ -297,6 +426,9 @@ function setDark() {
297
  //prompts
298
  function showPrompts(e) {
299
  if (Rag.prompts.length == 0) return;
 
 
 
300
  const text = Rag.prompts
301
  .map((x, i) => {
302
  return `[${i + 1}]${x}\n`;
 
1
  /** @format */
2
+ /*
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an "explicit" notice).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
126
+ any Contribution intentionally submitted for inclusion in the Work
127
+ by You to the Licensor shall be under the terms and conditions of
128
+ this License, without any additional terms or conditions.
129
+ Notwithstanding the above, nothing herein shall supersede or modify
130
+ the terms of any separate license agreement you may have executed
131
+ with Licensor regarding such Contributions.
132
+
133
+ 6. Trademarks. This License does not grant permission to use the trade
134
+ names, trademarks, service marks, or product names of the Licensor,
135
+ except as required for reasonable and customary use in describing the
136
+ origin of the Work and reproducing the content of the NOTICE file.
137
+
138
+ 7. Disclaimer of Warranty. Unless required by applicable law or
139
+ agreed to in writing, Licensor provides the Work (and each
140
+ Contributor provides its Contributions) on an "AS IS" BASIS,
141
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
142
+ implied, including, without limitation, any warranties or conditions
143
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
144
+ PARTICULAR PURPOSE. You are solely responsible for determining the
145
+ appropriateness of using or redistributing the Work and assume any
146
+ risks associated with Your exercise of permissions under this License.
147
+
148
+ 8. Limitation of Liability. In no event and under no legal theory,
149
+ whether in tort (including negligence), contract, or otherwise,
150
+ unless required by applicable law (such as deliberate and grossly
151
+ negligent acts) or agreed to in writing, shall any Contributor be
152
+ liable to You for damages, including any direct, indirect, special,
153
+ incidental, or consequential damages of any character arising as a
154
+ result of this License or out of the use or inability to use the
155
+ Work (including but not limited to damages for loss of goodwill,
156
+ work stoppage, computer failure or malfunction, or any and all
157
+ other commercial damages or losses), even if such Contributor
158
+ has been advised of the possibility of such damages.
159
+
160
+ 9. Accepting Warranty or Additional Liability. While redistributing
161
+ the Work or Derivative Works thereof, You may choose to offer,
162
+ and charge a fee for, acceptance of support, warranty, indemnity,
163
+ or other liability obligations and/or rights consistent with this
164
+ License. However, in accepting such obligations, You may act only
165
+ on Your own behalf and on Your sole responsibility, not on behalf
166
+ of any other Contributor, and only if You agree to indemnify,
167
+ defend, and hold each Contributor harmless for any liability
168
+ incurred by, or claims asserted against, such Contributor by reason
169
+ of your accepting any such warranty or additional liability.
170
+
171
+ END OF TERMS AND CONDITIONS
172
+
173
+ APPENDIX: How to apply the Apache License to your work.
174
+
175
+ To apply the Apache License to your work, attach the following
176
+ boilerplate notice, with the fields enclosed by brackets "[]"
177
+ replaced with your own identifying information. (Don't include
178
+ the brackets!) The text should be enclosed in the appropriate
179
+ comment syntax for the file format. We also recommend that a
180
+ file or class name and description of purpose be included on the
181
+ same "printed page" as the copyright notice for easier
182
+ identification within third-party archives.
183
+
184
+ Copyright [yyyy] [name of copyright owner]
185
+
186
+ Licensed under the Apache License, Version 2.0 (the "License");
187
+ you may not use this file except in compliance with the License.
188
+ You may obtain a copy of the License at
189
+
190
+ http://www.apache.org/licenses/LICENSE-2.0
191
+
192
+ Unless required by applicable law or agreed to in writing, software
193
+ distributed under the License is distributed on an "AS IS" BASIS,
194
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
195
+ See the License for the specific language governing permissions and
196
+ limitations under the License.
197
+ */
198
+
199
+ const VERS = "0.2.01";
200
+
201
+ // var xlog = console.log;
202
+ var xlog = function () {};
203
+
204
+ const stopRequest = async () => {
205
+ const ok = await confirm("Confermi Cancellazione Richeista ?");
206
  if (!ok) return;
207
+ cancelClientRequest();
208
  hideSpinner();
209
  };
210
 
211
  const showSpinner = () => {
212
  const spinner = document.getElementById("spinner");
213
  spinner.classList.add("show-spinner");
214
+ spinner.addEventListener("click", stopRequest);
215
  };
216
 
217
  const hideSpinner = () => {
218
  const spinner = document.getElementById("spinner");
219
  spinner.classList.remove("show-spinner");
220
+ spinner.removeEventListener("click", stopRequest);
221
  };
222
 
 
 
223
  function openApp() {
224
  setTimeout(() => {
 
225
  wnds.init();
226
  Menu.init();
227
  TextInput.init();
 
234
  }, 10);
235
  }
236
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  // Visualizza la storia della conversazione
238
  function showHistory() {
239
  const txt = ThreadMgr.getThread();
240
  setOutText(txt);
 
 
 
 
 
241
  }
242
 
243
  function release() {
 
245
  }
246
 
247
  // README
248
+ const op0 = function (e) {
249
+ wnds.wdiv.show(help1_html);
 
250
  };
251
 
252
  //query iniziale
253
  function showQuery(e) {
254
  const txt = `\n${Rag.ragQuery}`;
255
  wnds.wpre.show(txt);
 
256
  }
257
 
258
  //Risposta Rsg
 
285
 
286
  //contesto
287
  function showContesto(e) {
288
+ wnds.wpre.show(Rag.ragContext);
 
289
  }
290
 
291
  //elemco dati
 
314
  DataMgr.readDbDocNames();
315
  const arr = DataMgr.doc_names;
316
  const fh = (x, i) => `
317
+ <li><a href="#" onclick="showT(${i});">${i + 1}.${x}</a></li>
318
  `;
319
  const jfh = UaJtfh();
320
  let i = 0;
 
353
  }
354
 
355
  //cancella dati
356
+ async function deleteDati(e) {
357
+ const ok = await confirm("Confermi cancellazione dati?");
358
  if (ok) {
359
  DataMgr.deleteJsonDati();
360
  wnds.wdiv.close();
 
364
  }
365
 
366
  //cancella localstrage
367
+ async function deleteStorage(e) {
368
+ const ok = await confirm("Confermi cancellazione documenti & dati?");
369
  if (ok) {
370
  DataMgr.deleteJsonDati();
371
  localStorage.clear();
 
390
  wnds.wdiv.close();
391
  }
392
 
393
+ function help2(e) {
394
+ wnds.wdiv.show(help2_html);
 
 
395
  }
396
 
397
  const themeKey = "theme";
 
426
  //prompts
427
  function showPrompts(e) {
428
  if (Rag.prompts.length == 0) return;
429
+ for (const x of Rag.prompts) {
430
+ console.log(x);
431
+ }
432
  const text = Rag.prompts
433
  .map((x, i) => {
434
  return `[${i + 1}]${x}\n`;
static/javascript/client_llm.js ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** @format */
2
+
3
+ const ClientLLM = (apiKey) => {
4
+ let abortController = null;
5
+ let isCancelled = false;
6
+
7
+ const createResult = (ok, response = null, data = null, error = null) => {
8
+ return {
9
+ ok,
10
+ response,
11
+ data,
12
+ error,
13
+ };
14
+ };
15
+
16
+ const createError = (message, type, code, details) => ({
17
+ message: message || null,
18
+ type: type || null,
19
+ code: code || null,
20
+ details: {
21
+ message: details?.message || null,
22
+ type: details?.type || null,
23
+ param: details?.param || null,
24
+ code: details?.code || null,
25
+ },
26
+ });
27
+
28
+ const handleHttpError = async (response) => {
29
+ const errorMessages = {
30
+ 400: "Richiesta non valida",
31
+ 401: "Non autorizzato - Controlla la API key",
32
+ 403: "Accesso negato",
33
+ 404: "Endpoint non trovato",
34
+ 429: "Troppe richieste - Rate limit superato",
35
+ 500: "Errore interno del server",
36
+ 503: "Servizio non disponibile",
37
+ };
38
+
39
+ let detailsContent;
40
+ let errorType = "HTTPError";
41
+ let message = errorMessages[response.status] || `Errore HTTP ${response.status}`;
42
+
43
+ try {
44
+ if (response.headers.get("Content-Type")?.includes("application/json")) {
45
+ detailsContent = await response.json();
46
+ if (response.status === 400 && detailsContent) {
47
+ const errorMsg = typeof detailsContent.error === "string" ? detailsContent.error : detailsContent.message || detailsContent.error?.message;
48
+ if (
49
+ errorMsg &&
50
+ (errorMsg.includes("token limit") || errorMsg.includes("token exceeded") || errorMsg.includes("input too long") || errorMsg.includes("context length") || errorMsg.includes("max tokens"))
51
+ ) {
52
+ message = "Input troppo lungo - Superato il limite di token";
53
+ errorType = "TokenLimitError";
54
+ }
55
+ }
56
+ } else {
57
+ detailsContent = await response.text();
58
+ if (response.status === 400 && (detailsContent.includes("token limit") || detailsContent.includes("input too long") || detailsContent.includes("context length"))) {
59
+ message = "Input troppo lungo - Superato il limite di token";
60
+ errorType = "TokenLimitError";
61
+ }
62
+ }
63
+ } catch (e) {
64
+ detailsContent = { message: "Impossibile estrarre i dettagli dell'errore" };
65
+ }
66
+ return createError(message, errorType, response.status, typeof detailsContent === "string" ? { message: detailsContent } : detailsContent);
67
+ };
68
+
69
+ const handleNetworkError = (error) => {
70
+ if (error.name === "AbortError") {
71
+ if (isCancelled) {
72
+ return createError("Richiesta annullata dall'utente", "CancellationError", 499, { message: "La richiesta è stata interrotta volontariamente dall'utente" });
73
+ } else {
74
+ return createError("Richiesta interrotta per timeout", "TimeoutError", 408, { message: "La richiesta è stata interrotta a causa di un timeout", isTimeout: true });
75
+ }
76
+ }
77
+ if (error.name === "TypeError" && error.message.includes("Failed to fetch")) {
78
+ return createError("Errore di rete", "NetworkError", 0, { message: "Impossibile raggiungere il server. Controlla la connessione." });
79
+ }
80
+ return createError("Errore imprevisto", error.name || "UnknownError", 500, { message: error.message || "Si è verificato un errore sconosciuto" });
81
+ };
82
+
83
+ const sendRequest = async (url, payload, requestTimeout = 60) => {
84
+ isCancelled = false;
85
+ abortController = new AbortController();
86
+ const actualTimeoutMs = requestTimeout * 1000;
87
+
88
+ const timeoutId = setTimeout(() => {
89
+ if (abortController) {
90
+ abortController.abort();
91
+ }
92
+ }, actualTimeoutMs);
93
+
94
+ try {
95
+ const response = await fetch(url, {
96
+ method: "POST",
97
+ headers: {
98
+ Authorization: `Bearer ${apiKey}`,
99
+ "Content-Type": "application/json",
100
+ },
101
+ body: JSON.stringify(payload),
102
+ signal: abortController.signal,
103
+ });
104
+
105
+ if (isCancelled) {
106
+ const cancelledError = createError("Richiesta annullata", "CancellationError", 499, { message: "La richiesta è stata interrotta volontariamente dall'utente" });
107
+ return createResult(false, null, null, cancelledError);
108
+ }
109
+ if (!response.ok) {
110
+ const err = await handleHttpError(response);
111
+ return createResult(false, null, null, err);
112
+ }
113
+ const respJson = await response.json();
114
+ return createResult(true, respJson);
115
+ } catch (error) {
116
+ const err = handleNetworkError(error);
117
+ return createResult(false, null, null, err);
118
+ } finally {
119
+ clearTimeout(timeoutId);
120
+ abortController = null;
121
+ }
122
+ };
123
+
124
+ const cancelRequest = () => {
125
+ isCancelled = true;
126
+ if (abortController) {
127
+ abortController.abort();
128
+ abortController = null;
129
+ return true;
130
+ }
131
+ return false;
132
+ };
133
+
134
+ return {
135
+ sendRequest,
136
+ createError,
137
+ cancelRequest,
138
+ };
139
+ };
static/javascript/help.js ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** @format */
2
+ const help0_html = `
3
+ <div class="text">
4
+ <p class="center"> Comandi barra superiore </p>
5
+ <div>
6
+ Pulsante Menu
7
+ <p> Apre/chiude il Menu comandi </p>
8
+ </div>
9
+ <div>
10
+ Upload Files
11
+ <p>
12
+ Fa l'upload di un file locale. Sono accettati i file pdf, docx e txt.
13
+ Controlla se il file è in archivio, per non sovrascriverlo.
14
+ </p>
15
+ </div>
16
+ <div>
17
+ Upload Dir:
18
+ <p>
19
+ Per fare l'upload dei files di una directory. Sono accettati i files pdf, docx e txt.
20
+ I file in archivio con lo stesso nome non vengono sovrascritti.
21
+ </p>
22
+ </div>
23
+ <div>
24
+ Log:
25
+ <p>
26
+ Attiva/Disattiva la visualizzazione del Log.
27
+ Nel Log sono visualizzate le query con le dimensioni delle parti di documento analizzate.
28
+ </p>
29
+ </div>
30
+
31
+ <!-- -->
32
+ <hr>
33
+ <!-- -->
34
+ <div>
35
+ <p class="center"> Comandi lato destro in alto: </p>
36
+ </div>
37
+ <div>
38
+ Copia Output:
39
+ <p> Copia il testo dell'output negli appunti. </p>
40
+ </div>
41
+ <div>
42
+ Apri Output:
43
+ <p> Visualizza il testo in una finestra più grande. </p>
44
+ </div>
45
+ <hr>
46
+ <!-- -->
47
+ <div>
48
+ <p class="center"> Comandi lato destro in basso: </p>
49
+ </div>
50
+ <div>
51
+ Documenti => 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 del 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.
63
+ </p>
64
+ <p>
65
+ Alla fine della sequenza di elaborazioni esegue una query che produce
66
+ un contesto riepilogativo delle risposte archiviate.
67
+ </p>
68
+ <p>
69
+ Infine esegue la query utilizzando il contesto creato e visualizza la risposta nella finestra di output.
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
+ Il contesto RAG può essere vuoto.
77
+ Inizia una conversazione.
78
+ </p>
79
+ <p>
80
+ La conversazione ha senso relativamente all'elaborazione RAG se ogni query è una variazione / approfondimento della query iniziale.
81
+ </p>
82
+ </div>
83
+ <div>
84
+ Cancella Conversazione:
85
+ <p>
86
+ Cancella la storia della conversazione attiva.
87
+ Non vengono cancellati i dati dell'elaborazione RAG
88
+ </p>
89
+ Per andare a capo: Maiusc. + Invio
90
+ </div>
91
+ <!-- -->
92
+ <hr>
93
+ <!-- -->
94
+ <div>
95
+ <p class=" center"> Comandi del Menu: </p>
96
+ </div>
97
+ <div>
98
+ README
99
+ <p>
100
+ Presenta una spiegazione della implementazione della
101
+ tecnologia RAG utilizzata.
102
+ </p>
103
+ </div>
104
+ <div>
105
+ Risposta Contestuale:
106
+ <p> Visualizza la risposta ottenuta alla fine della elaborazione RAG </p>
107
+ </div>
108
+ <div>
109
+ Domanda iniziale:
110
+ <p> Visualizza la query utilizzata per l'elaborazione RAG </p>
111
+ </div>
112
+ <div>
113
+ Elenco Risposte:
114
+ <p>
115
+ Visualizza l'elenco delle risposte per ogni parte documento utilizzata fino alla risposta che genera il contesto.
116
+ </p>
117
+ </div>
118
+ <div>
119
+ Contesto RAG:
120
+ <p>
121
+ Visualizza il contesto creato utilizzando le risposte elaborate.
122
+ </p>
123
+ </div>
124
+ <div>
125
+ Dati Archiviati:
126
+ <p>
127
+ Visualizza i dati in archivio e le loro dimensioni:
128
+ </p>
129
+ </div>
130
+ <div>
131
+ Elenco Documenti:
132
+ <p>
133
+ Visualizza la lista dei documenti archiviati ed utilizzabili per l'elaborazione.<br>
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>
141
+ Calcola le query necessarie per ogni documento e le Query totali,
142
+ necessarie per analizzare tutti i documenti caricati.
143
+ </p>
144
+ </div>
145
+
146
+ <div>
147
+ Cancella Dati:
148
+ <p>
149
+ Cancella i dati delle elaborazioni salvati nell'archivio.
150
+ NON cancella i documenti caricati.
151
+ </p>
152
+ </div>
153
+
154
+ <div>
155
+ Cancella Documenti:
156
+ <p>
157
+ Cancella i documenti caricati e tutti i dati archiviati localmente.
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 prime prove.
168
+ Utilizza upload file o upload dir per i documenti da leggere dal tuo computer.
169
+ </p>
170
+ </div>
171
+ <div>
172
+ Digita una query che si riferisca ai documenti archiviati.
173
+ <p>
174
+ La query sarà utilizzata come criterio di selezione di informazioni dai documenti archiviati.
175
+ </p>
176
+ </div>
177
+
178
+ <div>
179
+ Click sul bottone rosso in basso a destra. Documento => RAG => Contesto => Query
180
+ <p>
181
+ Viene lanciata una sequenza di elaborazione per analizzare i documenti sulla base della query.
182
+ Se il log è attivo vedrai la sequenza 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 ogni documento.
187
+ <br>
188
+ Alla fine del processo sarà visualizzata la risposta.
189
+ </p>
190
+ </div>
191
+
192
+ <div>
193
+ Click sul bottone verde in basso a destra (oppure Invio). Contesto => Query
194
+ <p>
195
+ Inizia una conversazione utilizzando le informazioni precedentemente raccolte dai documenti.
196
+ Puoi inviare domande successive di approfondimento e chiarimento.
197
+ <br>
198
+ È FONDAMENTALE che le query siano approfondimenti e/o chiarimenti della query iniziale.
199
+ In caso contrario non si sfrutta il Contesto creato dall'elaborazione precedente.
200
+ <br>
201
+ Quindi per una query completamente nuova (sempre relativa ai documenti archiviati) è necessario iniziare una nuova elaborazione.
202
+ <br>
203
+ Il comando cancella, oltre a cancellare il campo di input cancella anche la sequenza query-risposte della
204
+ conversazione.
205
+ <br>
206
+ NON cancella i dati dell'elaborazione iniziale.
207
+ </p>
208
+ </div>
209
+ </div>
210
+ `;
211
+
212
+ const help1_html = `
213
+ <div class="text">
214
+ <pre>
215
+ Un'implementazione innovativa della tecnica RAG per il Question Answering
216
+ La tecnica RAG (Retrieval-Augmented Generation) è un approccio consolidato nel campo del question answering e della generazione di testo, che combina il recupero di informazioni pertinenti da fonti di dati con la generazione di testo basata su queste informazioni.
217
+ Qui viene proposta un'implementazione che introduce una variazione a questo paradigma.
218
+ L'implementazione si basa su una sequenza di prompt appositamente progettati per guidare un modello di linguaggio generativo attraverso le diverse fasi della tecnica RAG.
219
+ Questi prompt forniscono istruzioni dettagliate su come il modello deve seguire operazioni di recupero di informazioni, aumento delle informazioni recuperate e infine generazione di una risposta finale.
220
+ La risposta finale diviene poi il contesto da inserire nel prompt per rispondere alla domanda.
221
+ Un aspetto cruciale di questa implementazione è che lo stesso modello di linguaggio generativo svolge tutte le operazioni richieste, dall'analisi dei documenti di input al recupero di informazioni rilevanti, alla generazione della risposta finale.
222
+ Questa caratteristica rappresenta una deviazione significativa rispetto alle implementazioni standard della tecnica RAG, che prevedono l'utilizzo di moduli distinti per il recupero e la generazione.
223
+ La sequenza di prompt proposta guida il modello attraverso le seguenti fasi:
224
+
225
+ 1. Retrieval: Il modello analizza il documento di input e la domanda fornita, identificando e recuperando le informazioni e i concetti rilevanti per dare seguito alla domanda.
226
+
227
+ 2. Augmentation: Successivamente, il modello integra le informazioni recuperate con eventuali risposte accumulate in precedenza, estraendo nuove informazioni rilevanti e organizzandole in un elenco coerente, evitando ridondanze.
228
+
229
+ 3. Generation: Infine, il modello utilizza l'insieme di informazioni rilevanti e non ridondanti per generare una risposta completa e concisa alla domanda dell'utente.
230
+
231
+ Questa implementazione offre diversi vantaggi.
232
+ In primo luogo, sfrutta le capacità di un unico modello di grandi dimensioni, evitando la necessità di moduli distinti specializzati per ogni fase.
233
+ Inoltre, l'utilizzo di prompt espliciti può migliorare la controllabilità e la trasparenza del processo, consentendo di guidare il modello in modo più diretto.
234
+ Naturalmente, come per qualsiasi approccio basato su modelli di linguaggio generativi, è fondamentale prestare attenzione alle questioni di affidabilità, correttezza e bias dei dati di addestramento.
235
+ Rispetto a un'implementazione standard di RAG vi è la necessità di rilanciare l'elaborazione ad ogni domanda radicalmente nuova in quanto il contesto creato con le informazioni estratte dai documenti è definito sulla base della domanda.
236
+ Invece nella versione standard RAG si usano gli incorporamenti delle informazioni estratte dai documenti in modo tale che tali informazioni vengono viste quasi come un'estensione del modello e possono essere usate per domande diverse.
237
+ Quindi dal punto di vista utente le implementazioni RAG standard sono più efficienti; infatti l'implementazione proposta richiede per ogni nuova domanda una sequenza di richieste che saranno utilizzabili solo per creare il contesto per la domanda iniziale e per una conversazione con domande simili.
238
+ Il vantaggio dell'implementazione proposta consiste nel fatto che può essere implementata completamente lato client senza bisogno di sviluppare alcun modulo sul server.
239
+ L’unica cosa che serve è un servizio serverless come quello di HuggingFace o simile.
240
+ Quindi rappresenta un'interessante prospettiva sull'applicazione della tecnica RAG in modo più integrato e controllato attraverso l'uso di prompt mirati.
241
+ In conclusione, questa implementazione della tecnica RAG dimostra come le capacità dei modelli di linguaggio generativi di grandi dimensioni possano essere sfruttate in modi nuovi e creativi, potenzialmente aprendo la strada a ulteriori sviluppi nel campo del question answering e della generazione di testo.
242
+
243
+ Questa è la valutazione fatta da un LLM (comprensivo e gentile)
244
+
245
+ La mia valutazione personale della tua proposta di implementazione della tecnica RAG, con un elenco di pro e contro:
246
+
247
+ Punti a favore (Pro):
248
+ Semplificazione del processo: L'utilizzo di un unico modello di grandi dimensioni addestrato su vasti corpus di dati semplifica notevolmente l'architettura complessiva rispetto alle implementazioni tradizionali della tecnica RAG, che spesso prevedono moduli distinti per il recupero e la generazione.
249
+
250
+ Capacità di adattamento e apprendimento: I modelli di linguaggio generativi di grandi dimensioni sono noti per la loro capacità di adattarsi e imparare da nuovi dati e istruzioni.
251
+ Questo potrebbe consentire di raffinare e migliorare l'implementazione nel corso del tempo.
252
+
253
+ Controllo e trasparenza: L'utilizzo di prompt espliciti per guidare il modello attraverso le diverse fasi del processo può migliorare la controllabilità e la trasparenza, consentendo di monitorare e regolare il comportamento del modello in modo più diretto.
254
+
255
+ Efficienza computazionale: Avere un'unica architettura integrata potrebbe comportare vantaggi in termini di efficienza computazionale rispetto a soluzioni che prevedono moduli separati.
256
+
257
+ Punti a sfavore (Contro):
258
+
259
+ Affidabilità e coerenza: Poiché un unico modello gestisce tutte le fasi, eventuali errori o incoerenze potrebbero propagarsi e amplificarsi attraverso l'intero processo, influenzando la qualità della risposta finale.
260
+
261
+ Bias dei dati di addestramento: Come per qualsiasi modello di linguaggio generativo, l’approccio potrebbe essere influenzato dai bias presenti nei dati di addestramento utilizzati, con potenziali impatti sulla correttezza e l'equità delle risposte generate.
262
+
263
+ Mancanza di specializzazione: Mentre i modelli di grandi dimensioni sono versatili, potrebbero non essere ottimizzati per compiti specifici come il recupero di informazioni o la generazione di risposte rispetto a moduli specializzati.
264
+
265
+ Difficoltà di debug e interpretabilità: Con un'architettura integrata e basata su prompt, potrebbe essere più complesso eseguire il debug e comprendere le ragioni dietro a eventuali errori o comportamenti indesiderati del modello.
266
+
267
+ In sintesi, la proposta presenta alcuni vantaggi interessanti in termini di semplificazione, adattabilità e controllo, ma solleva anche potenziali preoccupazioni riguardo all'affidabilità, ai bias, alla mancanza di specializzazione e alle difficoltà di debug e interpretabilità.
268
+ Come per qualsiasi nuovo approccio, sarebbe necessario valutarlo attentamente attraverso sperimentazioni e test approfonditi per determinare l'efficacia e l'applicabilità in contesti specifici.
269
+ </pre>
270
+ </div>
271
+ `;
272
+
273
+ const help2_html = `
274
+ <div class="text">
275
+ <pre class="pre-text">
276
+ Nella redazione della domanda bisogna tenere conto del fatto che la domanda viene poi inserita in un prompt nel quale si fa esplicita richiesta di utilizzare il documento fornito.
277
+ Quindi è implicito il riferimento al/ai documenti archiviati.
278
+ Tuttavia, quando si tratta di documenti il cui contenuto è sicuramente disponibile su internet, può essere opportuno esplicitare nella domanda che ci si riferisce ai documenti forniti.
279
+ </pre>
280
+ <p class="center">Esempi di domande</p>
281
+ <div>
282
+ <p>Fai una relazione sul documento che ti ho fornito.</p>
283
+ <p>Approfondisci la tesi sostenuta nei documenti.</p>
284
+ <p>Confronta i diversi punti di vista espressi dagli autori.</p>
285
+ <p>Descrivi la personalità dei protagonisti.</p>
286
+ <p>Analizza il documento che ti ho fornito e illustrami eventuali contraddizioni.</p>
287
+ <p>Illustra i momenti salienti del racconto.</p>
288
+ <p>Analizzando il documento che ti ho fornito, confronta le tesi di ... con quelle di ...</p>
289
+ <p>Qual è l'avvenimento più importante?</p>
290
+ </div>
291
+ </div>
292
+ `;
static/javascript/rag_cleaner.js CHANGED
@@ -1,106 +1,107 @@
1
  /** @format */
2
- function removeTag(txt) {
3
- txt = txt.replace(/<<</g, " ").replace(/>>>/g, " ");
4
- txt = txt.replace(/<</g, "").replace(/>>/g, "");
5
- return txt;
6
- }
7
- // function uniteBrokenWords(txt) {
8
- // const regex = /-\n/g;
9
- // const unitedText = txt.replace(regex, "");
10
- // return unitedText;
11
  // }
12
 
13
- // function cleanDoc(txt) {
14
  // try {
15
- // txt = removeTag(txt);
16
- // //unisce le parole spezzate a di fine riga
17
- // txt = txt.replace(/-\n/g, "");
18
- // // Rimuove caratteri non stampabili specifici
19
- // const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g;
20
- // txt = txt.replace(charsRm, "");
21
- // // Sostituisce spazi non standard e altri caratteri con uno spazio
22
- // const charsSrp = /[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g;
23
- // txt = txt.replace(charsSrp, " ");
24
- // // Mantieni le sequenze di escape comuni
25
- // txt = txt.replace(/\\([nrtfb])/g, "$1");
26
- // // Mantieni le sequenze Unicode
27
- // txt = txt.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g, "$1");
28
- // // Mantieni i backslash nei path di file
29
- // txt = txt.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g, "\\\\$1");
30
- // // Rimuovi tutti gli altri backslash
31
- // txt = txt.replace(/\\/g, "");
32
- // // Uniforma i caratteri di quotazione
33
- // txt = txt.replace(/“/g, '"').replace(/”/g, '"');
34
- // // Rimuove spazi prima della punteggiatura
35
- // txt = txt.replace(/ +([.,;:!?])/g, "$1");
36
- // // Rimuove linee vuote multiple
37
- // txt = txt.replace(/\n\s*\n/g, "\n\n");
38
- // txt = txt.replace(/\n{3,}/g, "\n\n");
39
- // // Rimuove spazi multipli
40
- // txt = txt.replace(/ +/g, " ");
41
- // return txt.trim();
 
 
 
42
  // } catch (e) {
43
- // console.error(e);
44
- // return "Errore di codifica del documento";
45
  // }
46
  // }
47
 
 
 
 
 
 
 
48
  function cleanDoc(s) {
49
  try {
50
- s = removeTag(s);
 
51
 
52
- // Unisce le parole divise dal trattino a fine riga
53
- s = s.replace(/(\w+)-\s*\n(\w+)/g, '$1$2');
54
 
55
- // Rimuove caratteri non stampabili specifici
56
- const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF\u0008]/g;
57
- s = s.replace(charsRm, '');
58
 
59
- // Sostituisce spazi non standard e altri caratteri con uno spazio
60
- const charsSrp = /[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g;
61
- s = s.replace(charsSrp, ' ');
62
 
63
- // Mantieni le sequenze di escape comuni
64
- s = s.replace(/\\([nrtfb])/g, '$1');
65
 
66
- // Mantieni le sequenze Unicode
67
- s = s.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g, '$1');
68
 
69
- // Mantieni i backslash nei path di file
70
- s = s.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g, '\\$1');
71
 
72
- // Rimuovi tutti gli altri backslash
73
- s = s.replace(/\\/g, '');
74
 
75
- // Uniforma i caratteri di quotazione
76
- s = s.replace('“', '"').replace('”', '"');
77
 
78
- // Rimpiazza newline
79
- s = s.replace(/\n/g, ' ');
80
 
81
- // Rimuove spazi prima della punteggiatura
82
- s = s.replace(/ +([.,;:!?])/g, '$1');
83
 
84
- // Divide il testo in frasi
85
- const sentences = s.split(/(?<=[.?!])\s+/);
86
- const minLen = 5;
87
- s = sentences.filter(sentence => sentence.trim().length >= minLen).map(sentence => sentence.trim()).join('\n');
88
 
89
- // Rimuove spazi multipli
90
- s = s.replace(/ +/g, ' ');
91
 
92
- return s.trim();
93
  } catch (e) {
94
- console.error(e);
95
- return "Errore di codifica del documento";
96
  }
97
  }
98
 
99
-
100
-
101
  function cleanResponse(s) {
102
  try {
103
- s=removeTag(s);
104
  // Rimuove caratteri non stampabili specifici
105
  const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g;
106
  s = s.replace(charsRm, "");
@@ -126,26 +127,66 @@ function cleanResponse(s) {
126
  }
127
  }
128
 
129
- function cleanOut(txt) {
130
- // Formatta gli elenchi puntati per una migliore leggibilità
131
- // txt = txt.replace(/^(\s*[-*•])(\s*)/gm, "\n$1 ");
132
- // Formatta gli elenchi numerati per una migliore leggibilità
133
- // txt = txt.replace(/^(\s*\d+\.)(\s*)/gm, "\n$1 ");
134
- // Aggiunge una riga vuota prima e dopo i blocchi di codice
135
- // txt = txt.replace(/(```[\s\S]*?```)/g, "\n\n$1\n\n");
136
- // Aggiunge un'andata a capo dopo ogni punto, eccetto quando seguito da newline o fine stringa
137
- // txt = txt.replace(/\.(?!\n|$)/g, ".\n");
138
- // Sostituisce le sequenze di più di due newline con due newline
139
- txt = txt.replace(/\n{3,}/g, "\n\n");
140
- // Rimuove gli spazi bianchi extra alla fine di ogni riga
141
- // txt = txt.replace(/ +/g, " ");
142
- // txt = txt.replace(/\s+$/gm, "");
143
- return txt;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  }
145
 
146
- // <<<doc_name>>> => Documento: doc_name
147
- // function subResponseDOcTag(txt) {
148
- // const regex = /<<<(.*?)>>>/;
149
- // const result = txt.replace(regex, (match, p1) => `Documento: ${p1}`);
150
- // return result;
151
- // }
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  /** @format */
2
+ // function removeTag(txt) {
3
+ // txt = txt.replace(/<<</g, " ").replace(/>>>/g, " ");
4
+ // txt = txt.replace(/<</g, "").replace(/>>/g, "");
5
+ // return txt;
 
 
 
 
 
6
  // }
7
 
8
+ // function cleanDoc(s) {
9
  // try {
10
+ // // Rimuove i tag HTML
11
+ // // s = removeTag(s);
12
+
13
+ // // Unisce le parole divise dal trattino a fine riga
14
+ // s = s.replace(/(\w+)-\s*\n(\w+)/g, '$1$2');
15
+
16
+ // // Rimuove caratteri non stampabili specifici
17
+ // const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF\u0008]/g;
18
+ // s = s.replace(charsRm, '');
19
+
20
+ // // Sostituisce spazi non standard e altri caratteri con uno spazio
21
+ // const charsSrp = /[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g;
22
+ // s = s.replace(charsSrp, ' ');
23
+
24
+ // // Uniforma i caratteri di quotazione
25
+ // s = s.replace(/[“”]/g, '"');
26
+
27
+ // // Rimuove spazi prima della punteggiatura
28
+ // s = s.replace(/ +([.,;:!?])/g, '$1');
29
+
30
+ // // Rimuove spazi multipli
31
+ // s = s.replace(/ +/g, ' ');
32
+
33
+ // // Divide il testo in frasi
34
+ // const sentences = s.split(/(?<=[.?!])\s+/);
35
+ // const minLen = 5; // Ridotto a 5 per includere frasi più brevi ma valide
36
+ // s = sentences.filter(sentence => sentence.trim().length >= minLen).map(sentence => sentence.trim()).join('\n');
37
+
38
+ // // Rimuove spazi iniziali e finali
39
+ // return s.trim();
40
  // } catch (e) {
41
+ // console.error(e);
42
+ // return "Errore di codifica del documento";
43
  // }
44
  // }
45
 
46
+ function removeTag(txt) {
47
+ txt = txt.replace(/<<</g, "").replace(/>>>/g, "");
48
+ txt = txt.replace(/<</g, "").replace(/>>/g, "");
49
+ return txt;
50
+ }
51
+
52
  function cleanDoc(s) {
53
  try {
54
+ s = s.replace(/`/g, "");
55
+ s = removeTag(s);
56
 
57
+ // Unisce le parole divise dal trattino a fine riga
58
+ s = s.replace(/(\w+)-\s*\n(\w+)/g, "$1$2");
59
 
60
+ // Rimuove caratteri non stampabili specifici
61
+ const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF\u0008]/g;
62
+ s = s.replace(charsRm, "");
63
 
64
+ // Sostituisce spazi non standard e altri caratteri con uno spazio
65
+ const charsSrp = /[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g;
66
+ s = s.replace(charsSrp, " ");
67
 
68
+ // Mantieni le sequenze di escape comuni
69
+ s = s.replace(/\\([nrtfb])/g, "$1");
70
 
71
+ // Mantieni le sequenze Unicode
72
+ s = s.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g, "$1");
73
 
74
+ // Mantieni i backslash nei path di file
75
+ s = s.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g, "\\$1");
76
 
77
+ // Rimuovi tutti gli altri backslash
78
+ s = s.replace(/\\/g, "");
79
 
80
+ // Elimina le righe costituite dalla ripetizione di più di tre caratteri uguali
81
+ s = s.replace(/(.)\1{3,}/g, "");
82
 
83
+ // Uniforma i caratteri di quotazione
84
+ s = s.replace(/“/g, '"').replace(/”/g, '"');
85
 
86
+ // Rimpiazza newline
87
+ s = s.replace(/\n/g, " ");
88
 
89
+ // Rimuove spazi prima della punteggiatura
90
+ s = s.replace(/ +([.,;:!?])/g, "$1");
 
 
91
 
92
+ // Rimuove spazi multipli
93
+ s = s.replace(/ +/g, " ");
94
 
95
+ return s.trim();
96
  } catch (e) {
97
+ console.error(e);
98
+ return "Errore di codifica del documento";
99
  }
100
  }
101
 
 
 
102
  function cleanResponse(s) {
103
  try {
104
+ // s=removeTag(s);
105
  // Rimuove caratteri non stampabili specifici
106
  const charsRm = /[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g;
107
  s = s.replace(charsRm, "");
 
127
  }
128
  }
129
 
130
+ function answerFormtter(inputText) {
131
+ if (inputText.trim() == "") return "";
132
+
133
+ // Controlla se entrambi i tag # User e # Assistant sono presenti nel testo di input
134
+ const hasUserTag = inputText.includes("# User:");
135
+ const hasAssistantTag = inputText.includes("# Assistant:");
136
+
137
+ if (!hasUserTag || !hasAssistantTag) {
138
+ // Se almeno uno dei due tag non è presente, inserisci tutto in un unico div con classe assistant
139
+ return `<div class="assistant"><b>Assistant:</b><br>${inputText.split("\n").join("<br>")}</div>`;
140
+ }
141
+
142
+ // Altrimenti, procedi come prima
143
+ const lines = inputText.split("\n");
144
+ let currentSpeaker = null;
145
+ let resultHtml = "";
146
+
147
+ lines.forEach((line) => {
148
+ line = line.trim();
149
+ if (line.startsWith("# User:")) {
150
+ if (currentSpeaker) {
151
+ resultHtml += `</div>`;
152
+ }
153
+ currentSpeaker = "user";
154
+ resultHtml += `<div class="${currentSpeaker}"><b>User:</b>`;
155
+ } else if (line.startsWith("# Assistant:")) {
156
+ if (currentSpeaker) {
157
+ resultHtml += `</div>`;
158
+ }
159
+ currentSpeaker = "assistant";
160
+ resultHtml += `<div class="${currentSpeaker}"><b>Assistant:</b>`;
161
+ } else if (line.length > 0) {
162
+ if (currentSpeaker) {
163
+ resultHtml += `<br>${line}`;
164
+ }
165
+ }
166
+ });
167
+
168
+ if (currentSpeaker) {
169
+ resultHtml += `</div>`;
170
+ }
171
+
172
+ return resultHtml;
173
  }
174
 
175
+ function textFormatter(txt) {
176
+ let plainText = txt.replace(/<[^>]*>/g, "");
177
+ let sentences = plainText.split(/([.!?:])(?=\s|$)/);
178
+ let text = "";
179
+ for (let i = 0; i < sentences.length; i += 2) {
180
+ let sentence = sentences[i];
181
+ let delimiter = sentences[i + 1] || "";
182
+ if (sentence.trim().length > 0) {
183
+ text += " " + sentence.trim() + delimiter;
184
+ }
185
+ if (i < sentences.length - 2) {
186
+ text += "\n";
187
+ }
188
+ }
189
+ text = text.replace(/User:/g, "\n\nUSER:\n");
190
+ text = text.replace(/Assistant:/g, "\n\nASSISTANT:\n");
191
+ return text.trim();
192
+ }
static/javascript/rag_data_mgr.js CHANGED
@@ -1,16 +1,11 @@
1
  /** @format */
2
 
3
  "use strict";
4
- const ID_RESPONSES = "id_responses";
5
- const ID_DOC_NAMES = "id_doc_names";
6
- const ID_DOCS = "id_docs;";
7
- const ID_RAG = "id_rag";
8
- const ID_THREAD = "id_thread";
9
 
10
  const UaDb = {
11
  create(id, data) {
12
  if (localStorage.getItem(id)) {
13
- consoe.error(`ID ${id} already exists.`);
14
  return;
15
  }
16
  localStorage.setItem(id, data);
@@ -32,7 +27,7 @@ const UaDb = {
32
  },
33
  delete(id) {
34
  if (!localStorage.getItem(id)) {
35
- consoe.error(`ID ${id} not found.`);
36
  return;
37
  }
38
  localStorage.removeItem(id);
@@ -83,7 +78,7 @@ const DataMgr = {
83
  const doc = cleanDoc(text);
84
  const name = this.linkToName(link);
85
  if (this.doc_names.includes(name)) {
86
- alert(`Il docuento ${name} è già caricato`);
87
  return;
88
  }
89
  this.doc_names.push(name);
@@ -109,6 +104,7 @@ const DataMgr = {
109
  },
110
  readDbDocNames() {
111
  this.doc_names = UaDb.readArray(ID_DOC_NAMES);
 
112
  },
113
  deleteJsonDati() {
114
  const ids = UaDb.getAllIds();
@@ -119,7 +115,7 @@ const DataMgr = {
119
  Rag.ragQuery = "";
120
  Rag.ragContext = "";
121
  Rag.ragAnswer = "";
122
- Rag.answers= [];
123
  Rag.prompts = [];
124
  ThreadMgr.rows = [];
125
  },
 
1
  /** @format */
2
 
3
  "use strict";
 
 
 
 
 
4
 
5
  const UaDb = {
6
  create(id, data) {
7
  if (localStorage.getItem(id)) {
8
+ console.error(`ID ${id} already exists.`);
9
  return;
10
  }
11
  localStorage.setItem(id, data);
 
27
  },
28
  delete(id) {
29
  if (!localStorage.getItem(id)) {
30
+ console.error(`ID ${id} not found.`);
31
  return;
32
  }
33
  localStorage.removeItem(id);
 
78
  const doc = cleanDoc(text);
79
  const name = this.linkToName(link);
80
  if (this.doc_names.includes(name)) {
81
+ alert(`Il documento ${name} è già caricato`);
82
  return;
83
  }
84
  this.doc_names.push(name);
 
104
  },
105
  readDbDocNames() {
106
  this.doc_names = UaDb.readArray(ID_DOC_NAMES);
107
+ return this.doc_names;
108
  },
109
  deleteJsonDati() {
110
  const ids = UaDb.getAllIds();
 
115
  Rag.ragQuery = "";
116
  Rag.ragContext = "";
117
  Rag.ragAnswer = "";
118
+ Rag.answers = [];
119
  Rag.prompts = [];
120
  ThreadMgr.rows = [];
121
  },
static/javascript/rag_http.js CHANGED
@@ -1,10 +1,6 @@
1
  /** @format */
2
  "use strict";
3
 
4
- // const model_name = "mistralai/Mistral-7B-Instruct-v0.3";
5
- const model_name = "mistralai/Mixtral-8x7B-Instruct-v0.1";
6
- // const model_name = "mistralai/Mixtral-8x22B-Instruct-v0.1"
7
-
8
  async function requestGet(url) {
9
  try {
10
  const response = await fetch(url, {
@@ -13,6 +9,7 @@ async function requestGet(url) {
13
  "Content-Type": "text/plain;charset=UTF-8",
14
  },
15
  });
 
16
  if (!response.ok) {
17
  throw new Error(`HTTP error! status: ${response.status}`);
18
  }
@@ -20,148 +17,32 @@ async function requestGet(url) {
20
  const text = new TextDecoder("utf-8").decode(arrayBuffer);
21
  return text;
22
  } catch (error) {
23
- console.error(error);
24
  let message;
25
- if (error.name === "AbortError") {
26
- message = "Request was aborted";
27
- } else if (error.message.includes("HTTP error! status")) {
28
  message = error.message;
 
 
29
  } else {
30
- message = "An error occurred";
31
  }
32
  alert(`requestGet()\nurl: ${url}\n${message}`);
33
  throw error;
34
  }
35
  }
36
- const ERROR_TOKENS = "ERROR_TOKENS";
37
- const TIMEOUT_ERROR = "TIMEOUT_ERROR";
38
-
39
- const getErrorType = (status, data) => {
40
- let errorType;
41
- if (status >= 500) {
42
- errorType = "SERVER_ERROR";
43
- } else if (status >= 400 && status < 500) {
44
- if (typeof data === "object" && data.error_type === "validation") {
45
- if (data.error.includes("tokens")) {
46
- errorType = ERROR_TOKENS;
47
- } else {
48
- errorType = "ERROR_VALIDATION";
49
- }
50
- } else {
51
- errorType = "CLIENT_ERROR";
52
- }
53
- } else {
54
- errorType = "UNKNOWN_ERROR";
55
- }
56
- return errorType;
57
- };
58
 
59
- const checkResponse = (data) => {
60
- if (!data || !Array.isArray(data) || data.length === 0) {
61
- return "INVALID_DATA";
62
- }
63
- if (!data[0].generated_text) {
64
- return "MISSING_GENERATED_TEXT";
65
- }
66
- return "ok";
67
- };
68
-
69
- const createErrorInfo = (status, statusText, msg, errorType) => {
70
- const err = {
71
- status: status,
72
- statusText: statusText,
73
- errorType: errorType,
74
- message: msg || "Errore sconosciuto",
75
  };
76
- return JSON.stringify(err);
77
- };
78
-
79
- const HfRequest = {
80
- controller: null,
81
- isCancelled: false,
82
- baseUrl: "https://api-inference.huggingface.co/models",
83
-
84
- async post(payload, timeout = 50000) {
85
- this.isCancelled = false;
86
- this.controller = new AbortController();
87
- let response;
88
- try {
89
- const timeoutId = setTimeout(() => {
90
- this.controller.abort();
91
- }, timeout);
92
- response = await fetch(`${this.baseUrl}/${model_name}`, {
93
- method: "POST",
94
- headers: {
95
- Authorization: `Bearer ${tm}`,
96
- "Content-Type": "application/json",
97
- },
98
- body: JSON.stringify(payload),
99
- signal: this.controller.signal,
100
- });
101
- clearTimeout(timeoutId);
102
- if (this.isCancelled) return null;
103
- const data = await response.json();
104
- if (!response.ok) {
105
- const errorType = getErrorType(response.status, data);
106
- const errorInfo = createErrorInfo(response.status, response.statusText, data.error, errorType);
107
- throw new Error(errorInfo);
108
- }
109
- const okResp = checkResponse(data);
110
- if (okResp !== "ok") {
111
- const errorInfo = createErrorInfo(response.status, response.statusText, data.error, okResp);
112
- throw new Error(errorInfo);
113
- }
114
- return data[0].generated_text.trim();
115
- } catch (error) {
116
- if (this.isCancelled) return null;
117
- if (error.name === "AbortError") {
118
- const errorInfo = createErrorInfo(0, "Timeout", "La richiesta è scaduta", TIMEOUT_ERROR);
119
- throw new Error(errorInfo);
120
- }
121
- throw error;
122
- }
123
- },
124
-
125
- cancelRequest() {
126
- if (this.controller) {
127
- this.isCancelled = true;
128
- this.controller.abort();
129
- }
130
- },
131
- };
132
-
133
- function getErrorInfo(error) {
134
- let js = {};
135
- try {
136
- js = JSON.parse(error.message);
137
- } catch (err) {
138
- const msg = `getErrorInfo\n${error}`;
139
- console.error(msg);
140
- js = {
141
- status: "0",
142
- statusText: "status_errorInof",
143
- errorType: "UNKNOWN_ERROR_errorInfo",
144
- message: msg,
145
- };
146
- } finally {
147
- return js;
148
- }
149
- }
150
-
151
- function errorToText(err) {
152
- let s;
153
- try {
154
- const j = JSON.parse(err.message);
155
- s = `Error:
156
- Status: ${j.status}
157
- Status Text: ${j.statusText}
158
- Error Type: ${j.errorType}
159
- Message: ${j.message}`;
160
- } catch (err) {
161
- const msg = `errorToText\n${err}`;
162
- console.error(msg);
163
- s = `${err}`;
164
- } finally {
165
- return s;
166
- }
167
  }
 
1
  /** @format */
2
  "use strict";
3
 
 
 
 
 
4
  async function requestGet(url) {
5
  try {
6
  const response = await fetch(url, {
 
9
  "Content-Type": "text/plain;charset=UTF-8",
10
  },
11
  });
12
+
13
  if (!response.ok) {
14
  throw new Error(`HTTP error! status: ${response.status}`);
15
  }
 
17
  const text = new TextDecoder("utf-8").decode(arrayBuffer);
18
  return text;
19
  } catch (error) {
20
+ console.error(`Error in requestGet() for url: ${url}`, error);
21
  let message;
22
+ if (error.message.includes("HTTP error! status")) {
 
 
23
  message = error.message;
24
+ } else if (error.message.includes("NetworkError")) {
25
+ message = "Network error occurred";
26
  } else {
27
+ message = "An unknown error occurred";
28
  }
29
  alert(`requestGet()\nurl: ${url}\n${message}`);
30
  throw error;
31
  }
32
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ function loadScript(url, fn) {
35
+ // const existingScripts = document.querySelectorAll(`script[src="${url}"]`);
36
+ // existingScripts.forEach(script => script.remove());
37
+ const script = document.createElement("script");
38
+ script.src = url;
39
+ script.onload = () => {
40
+ fn();
41
+ document.head.removeChild(script);
 
 
 
 
 
 
 
 
42
  };
43
+ script.onerror = () => {
44
+ const s = `Errore: Impossibile caricare lo script ${url}`;
45
+ alert(s);
46
+ };
47
+ document.head.appendChild(script);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  }
static/javascript/rag_mgr.js CHANGED
@@ -1,72 +1,182 @@
1
  /** @format */
2
- /**
3
- * @license
4
- * rag_rqs
5
- * Copyright (C) 2024 [Il tuo nome]
6
- *
7
- * This program is free software: you can redistribute it and/or modify
8
- * it under the terms of the GNU General Public License as published by
9
- * the Free Software Foundation, either version 3 of the License, or
10
- * (at your option) any later version.
11
- *
12
- * This program is distributed in the hope that it will be useful,
13
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
- * GNU General Public License for more details.
16
- *
17
- * You should have received a copy of the GNU General Public License
18
- * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
- */
20
- "use strict";
21
- const MAX_PROMPT_LENGTH = 1024 * 80;
22
- // decremento dopo errore per tokens eccessivi
23
- const PROMPT_DECR = 1024 * 2;
24
 
25
- const TIMEOUT = 60000;
 
 
 
26
 
27
- function wait(seconds) {
28
- return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  }
30
 
31
- // async function example() {
32
- // console.log("Inizio attesa...");
33
- // await wait(5); // Attende 5 secondi
34
- // console.log("Fine attesa!");
35
- // }
 
 
 
 
 
 
36
 
37
- // example();
 
 
 
 
38
 
39
- const truncInput = (txt, decr) => {
40
  const tl = txt.length;
41
  const lim = tl - decr;
42
  const s = txt.substring(0, lim);
43
  return s;
44
  };
45
 
46
- //setta il prompt al limite massimo
47
- const setMaxLen = (s) => {
48
- const lim = MAX_PROMPT_LENGTH - 1000;
49
- return s.substring(0, lim);
50
- };
51
-
52
- const getPartSize = (doc, prompt, decr) => {
53
- const limitWIthPoint = (s, free_len) => {
54
- const idx = s.indexOf(".", free_len);
55
- let lim = (idx != -1 ? idx : free_len) + 1;
56
- if (lim > free_len + 100) {
57
- lim = free_len;
58
  }
59
- return lim;
60
  };
61
- const dpl = doc.length + prompt.length;
62
- const free_len = MAX_PROMPT_LENGTH - decr;
63
- let size = 0;
64
- if (dpl < free_len) {
65
- size = doc.length;
 
 
 
 
66
  } else {
67
- size = limitWIthPoint(doc, free_len);
 
68
  }
69
- return size;
70
  };
71
 
72
  const getPartDoc = (pRgt, partSize) => {
@@ -101,6 +211,7 @@ const Rag = {
101
  init() {
102
  this.readRespsFromDb();
103
  this.readFromDb();
 
104
  },
105
  returnOk() {
106
  const ok = this.ragContext.length > 10;
@@ -128,14 +239,18 @@ const Rag = {
128
  readRespsFromDb() {
129
  this.answers = UaDb.readArray(ID_RESPONSES);
130
  },
131
- // addPrompt(p) {
132
- // this.prompts.push(p);
133
- // },
 
 
 
134
  // documenti => risposte RAG => context
135
  async requestDocsRAG(query) {
136
  DataMgr.deleteJsonDati();
137
  DataMgr.readDbDocNames();
138
  DataMgr.readDbDocs();
 
139
  this.ragQuery = query;
140
  this.saveToDb();
141
  let ndoc = 0;
@@ -156,39 +271,46 @@ const Rag = {
156
  let rgt = "";
157
  let answer = "";
158
  let docAnswersLst = [];
159
-
160
  while (true) {
161
- let partSize = getPartSize(doc, promptDoc("", query, ""), decr);
162
- if (partSize < 10) {
163
- break;
164
- }
165
  [lft, rgt] = getPartDoc(doc, partSize);
166
  ragLog(`${j}) ${ndoc},${npart}`, lft.length, rgt.length, this.answers);
167
  prompt = promptDoc(lft, query, docName);
 
168
  const payload = getPayloadDoc(prompt);
169
- // const t0 = performance.now();
170
- try {
171
- answer = await HfRequest.post(payload, TIMEOUT);
172
- if (!answer) return "";
173
- } catch (err) {
174
- console.error(`RR1)\n`, err);
175
- const ei = getErrorInfo(err);
176
- if (ei.errorType === ERROR_TOKENS) {
177
- UaLog.log(`Error tokens Doc ${prompt.length}`);
178
- decr += PROMPT_DECR;
179
- continue;
180
- } else if (ei.errorType === TIMEOUT_ERROR) {
181
- UaLog.log(`Error timeout Doc`);
 
 
 
182
  continue;
183
- } else {
184
- UaLog.log(`Error ${err}`);
185
- answer = `ERROR \n${err}\n`;
186
- // throw err;
187
- }
188
- } //end catch
189
- // const t1 = performance.now();
190
- // const dt = Math.round((t1 - t0) / 1000);
191
- // UaLog.log(`t: ${dt}`);
 
 
 
 
 
 
192
  npart++;
193
  j++;
194
  doc = rgt;
@@ -197,33 +319,37 @@ const Rag = {
197
  const s = `DOCUMENTO : ${docName}_${npart}\n${answer}`;
198
  this.answers.push(s);
199
  } // end while
200
- //TODO implemntare build context
201
  const docAnswersLen = docAnswersLst.length;
202
  let docAnswresTxt = docAnswersLst.join("\n\n");
203
- let docContext = "";
204
 
 
205
  while (true) {
206
  prompt = promptBuildContext(docAnswresTxt, this.ragQuery);
207
  const payload = getPayloadBuildContext(prompt);
208
- try {
209
- docContext = await HfRequest.post(payload, TIMEOUT);
210
- if (!docContext) return "";
211
- } catch (err) {
212
- console.error(`RR2)`, err);
213
- const ei = getErrorInfo(err);
214
- if (ei.errorType === ERROR_TOKENS) {
215
- UaLog.log(`Error tokens build Context ${prompt.length}`);
216
- docAnswresTxt = truncInput(docAnswresTxt, PROMPT_DECR);
217
- docAnswresTxt = setMaxLen(docAnswresTxt);
218
- continue;
219
- } else if (ei.errorType === TIMEOUT_ERROR) {
220
- UaLog.log(`Error timeout build Context`);
221
- // wait(5);
 
 
222
  continue;
223
- } else {
224
- throw err;
225
- }
226
  }
 
 
 
 
227
  break;
228
  } //end while
229
  UaLog.log(`context ${docAnswersLen} => ${docContext.length}`);
@@ -231,13 +357,14 @@ const Rag = {
231
  this.docContextLst.push(docContext);
232
  } // end for document
233
  } catch (err) {
234
- console.error(err);
235
  throw err;
236
  }
 
237
  this.ragContext = this.docContextLst.join("\n\n");
 
238
  this.saveToDb();
239
-
240
- // query finale utilizza context
241
  {
242
  let answer = "";
243
  let context = this.ragContext;
@@ -245,25 +372,29 @@ const Rag = {
245
  while (true) {
246
  let prompt = promptWithContext(context, query);
247
  const payload = getPayloadWithContext(prompt);
248
- try {
249
- answer = await HfRequest.post(payload, TIMEOUT);
250
- if (!answer) return "";
251
- } catch (err) {
252
- console.error(`RR3)`, err);
253
- const ei = getErrorInfo(err);
254
- if (ei.errorType === ERROR_TOKENS) {
255
- UaLog.log(`Error tokens with Context ${prompt.length}`);
256
- context = truncInput(context, PROMPT_DECR);
257
- context = setMaxLen(context);
258
- continue;
259
- } else if (ei.errorType === TIMEOUT_ERROR) {
260
- UaLog.log(`Error timeout with Context`);
261
- // wait(5);
 
 
262
  continue;
263
- } else {
264
- throw err;
265
- }
266
  }
 
 
 
 
267
  break;
268
  }
269
  answer = cleanResponse(answer);
@@ -271,25 +402,25 @@ const Rag = {
271
  this.saveRespToDb();
272
  ThreadMgr.init();
273
  this.saveToDb();
274
- UaLog.log(`Risposta (${this.ragAnswer.length})`);
 
 
 
 
 
 
275
  } catch (err) {
276
- console.error(err);
277
- answer = `${err}`;
278
  throw err;
279
- } finally {
280
- return answer;
281
  }
282
  } // end query
283
  },
284
-
285
- // thread
286
  async requestContext(query) {
287
- let text = "";
288
  if (!this.ragContext) {
289
- const ok = await confirm("Contesto vuoto. Vuoi continuare?");
290
- if (!ok) return "";
291
- // HACK gestisce il pulsante verde che ha accettao il contetso vuoto
292
- this.ragContext = "Sei un assitente AI dispoibile a soddisfare tutte le mi richieste";
293
  }
294
  if (ThreadMgr.isFirst()) {
295
  ThreadMgr.init();
@@ -300,36 +431,46 @@ const Rag = {
300
  while (true) {
301
  prompt = promptThread(context, thread, query);
302
  const payload = getPayloadThread(prompt);
303
- try {
304
- text = await HfRequest.post(payload, TIMEOUT);
305
- if (!text) return "";
306
- } catch (err) {
307
- console.error(`RR4)`, err);
308
- const ei = getErrorInfo(err);
309
- if (ei.errorType === ERROR_TOKENS) {
310
- UaLog.log(`Error tokens Thread Init ${prompt.length}`);
311
- thread = truncInput(thread, PROMPT_DECR);
312
- context = setMaxLen(context);
313
- continue;
314
- } else if (ei.errorType === TIMEOUT_ERROR) {
315
- UaLog.log(`Error timeout Thread Init`);
316
- continue;
317
- } else {
318
- throw err;
319
- }
320
- } //end catch
 
 
 
 
 
 
 
 
 
 
 
 
321
  break;
322
  }
323
- text = cleanResponse(text);
324
- ThreadMgr.add(query, text);
325
- text = ThreadMgr.getThread();
326
  UaLog.log(`Inizio Conversazione (${prompt.length})`);
 
327
  } catch (err) {
328
- console.error(err);
329
- text = `${err}`;
330
  throw err;
331
- } finally {
332
- return text;
333
  }
334
  } else {
335
  try {
@@ -339,42 +480,53 @@ const Rag = {
339
  while (true) {
340
  prompt = promptThread(context, thread, query);
341
  const payload = getPayloadThread(prompt);
342
- try {
343
- text = await HfRequest.post(payload, TIMEOUT);
344
- if (!text) return "";
345
- } catch (err) {
346
- console.error(`RR5)`, err);
347
- const ei = getErrorInfo(err);
348
- if (ei.errorType === ERROR_TOKENS) {
349
- UaLog.log(`Error tokens Thread ${prompt.length}`);
350
- thread = truncInput(thread, PROMPT_DECR);
351
- continue;
352
- } else if (ei.errorType === TIMEOUT_ERROR) {
353
- UaLog.log(`Error timeout Thread`);
 
 
 
 
354
  continue;
355
- } else {
356
- throw err;
357
- }
358
  }
 
 
 
 
 
 
 
 
 
 
 
359
  break;
360
  }
361
- text = cleanResponse(text);
362
- ThreadMgr.add(query, text);
363
- text = ThreadMgr.getThread();
364
  UaLog.log(`Conversazione (${prompt.length})`);
 
365
  } catch (err) {
366
- console.error(err);
367
- text = `${err}`;
368
  throw err;
369
- } finally {
370
- return text;
371
  }
372
  }
373
  },
374
  };
375
 
376
- const LLM = "## Assistant:";
377
- const USER = "## User:";
378
 
379
  const ThreadMgr = {
380
  rows: [],
@@ -396,6 +548,7 @@ const ThreadMgr = {
396
  for (const ua of this.rows) {
397
  const u = ua[0];
398
  const a = ua[1];
 
399
  rows.push(`${USER}\n${u}\n${LLM}\n${a}\n`);
400
  }
401
  return rows.join("\n\n");
 
1
  /** @format */
2
+ const ID_RAG = "id_rag";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
 
4
+ const ID_THREAD = "id_thread";
5
+ const ID_RESPONSES = "id_responses";
6
+ const ID_DOC_NAMES = "id_doc_names";
7
+ const ID_DOCS = "id_docs";
8
 
9
+ const PROMPT_DECR = 1024 * 10;
10
+
11
+ const maxLenRequest = (nk = 32) => {
12
+ // 1024 * 32 = 32758
13
+ // 32768 * 6 = 196698
14
+ // 196608 x 0,15 = 29591
15
+ // 196608 + 29591 = 226199
16
+ const nc = 1024 * nk * 3;
17
+ const sp = nc * 0.1;
18
+ const mlr = Math.trunc(nc + sp);
19
+ return mlr;
20
+ };
21
+
22
+ function umgm() {
23
+ const arr = ["bWtkWlFPXmg=", "SWZtUkZZb18=", "Rm1rUVZzcHM=", "c1pJelNTTHQ=", "Vlt0bE8="];
24
+ return arr
25
+ .map((part) => {
26
+ const ch = atob(part);
27
+ return ch
28
+ .split("")
29
+ .map((char) => String.fromCharCode((char.charCodeAt(0) - 5 + 256) % 256))
30
+ .join("");
31
+ })
32
+ .join("");
33
+ }
34
+
35
+ const MAX_PROMPT_LENGTH = maxLenRequest(100);
36
+ //HF
37
+ // const MODEL = "mistralai/Mixtral-8x7B-Instruct-v0.1";
38
+ const MODEL = "mistralai/Mistral-Small-24B-Instruct-2501";
39
+ /////////////
40
+ const API = umgm();
41
+ console.log("\n**** MODELl:\n", MODEL);
42
+ console.log(API);
43
+ const client = ClientLLM(API);
44
+
45
+ const getResponse = async (payload, timeout = 60) => {
46
+ payload["model"] = MODEL;
47
+ //HF
48
+ // const url = `https://router.huggingface.co/hf-inference/models/${MODEL}/v1/chat/completions`;
49
+ const url = "https://router.huggingface.co/together/v1/chat/completions";
50
+
51
+ const rr = await client.sendRequest(url, payload, timeout);
52
+ if (rr.error) {
53
+ if (rr.error.code === 499) {
54
+ alert("Request Interrotta");
55
+ return null;
56
+ } else {
57
+ return rr;
58
+ }
59
+ }
60
+ if (!rr.response.choices || !rr.response.choices[0] || !rr.response.choices[0].message || rr.response.choices[0].message.content === undefined) {
61
+ const err = client.createError("Risposta non valida", "ParseError", 500, { message: "La risposta non contiene il contenuto atteso" });
62
+ return RequestResult(false, null, null, err);
63
+ }
64
+ rr.data = rr.response.choices[0].message.content;
65
+ return rr;
66
+ };
67
+
68
+ const responseDetails = {
69
+ set(response) {
70
+ this.response = response;
71
+ },
72
+ // get_id() {
73
+ // return this.response.id;
74
+ // },
75
+ // get_created() {
76
+ // return this.response.created;
77
+ // },
78
+ // get_model() {
79
+ // return this.response.model;
80
+ // },
81
+ // get_index() {
82
+ // return this.response.choices[0].index;
83
+ // },
84
+ // get_role() {
85
+ // return this.response.choices[0].message.role;
86
+ // },
87
+ // get_tool_calls() {
88
+ // return this.response.choices[0].message.tool_calls;
89
+ // },
90
+ // get_content() {
91
+ // return this.response.choices[0].message.content;
92
+ // },
93
+ // get_finish_reason() {
94
+ // return this.response.choices[0].finish_reason;
95
+ // },
96
+ // get_prompt_tokens() {
97
+ // return this.response.usage.prompt_tokens;
98
+ // },
99
+ get_total_tokens() {
100
+ return this.response.usage.total_tokens;
101
+ },
102
+ get_completion_tokens() {
103
+ return this.response.usage.completion_tokens;
104
+ },
105
+ };
106
+
107
+ const calcTokens = {
108
+ sum_input_tokens: 0,
109
+ sum_generate_tokens: 0,
110
+ init() {
111
+ this.sum_input_tokens = 0;
112
+ this.sum_generate_tokens = 0;
113
+ },
114
+ add(response) {
115
+ if (!response) return;
116
+ this.sum_input_tokens += response.usage.total_tokens;
117
+ this.sum_generate_tokens += response.usage.completion_tokens;
118
+ },
119
+ get_sum_input_tokens() {
120
+ return this.sum_input_tokens;
121
+ },
122
+ get_sum_generate_tokens() {
123
+ return this.sum_generate_tokens;
124
+ },
125
+ };
126
+
127
+ function cancelClientRequest() {
128
+ client.cancelRequest();
129
  }
130
 
131
+ const getPromptTokens = (err) => {
132
+ const msg = err.details.message;
133
+ const match = msg.match(/Prompt contains (\d+) tokens/);
134
+ return match ? parseInt(match[1], 10) : null;
135
+ };
136
+
137
+ const getModelToken = (err) => {
138
+ const msg = err.details.message;
139
+ const match = msg.match(/model with (\d+) maximum context length/);
140
+ return match ? parseInt(match[1], 10) : null;
141
+ };
142
 
143
+ const isTooLarge = (err) => {
144
+ const msg = err.details.message;
145
+ const tks = msg.includes("too large");
146
+ return tks;
147
+ };
148
 
149
+ const truncateInput = (txt, decr) => {
150
  const tl = txt.length;
151
  const lim = tl - decr;
152
  const s = txt.substring(0, lim);
153
  return s;
154
  };
155
 
156
+ const getPartSize = (document, prompt, decrement) => {
157
+ // Funzione interna per trovare un punto nel documento a partire da una certa posizione
158
+ const findLimitWithPoint = (text, freeLength) => {
159
+ const pointIndex = text.indexOf(".", freeLength);
160
+ let limit = (pointIndex !== -1 ? pointIndex : freeLength) + 1;
161
+ if (limit > freeLength + 100) {
162
+ limit = freeLength;
 
 
 
 
 
163
  }
164
+ return limit;
165
  };
166
+
167
+ // Calcola la lunghezza totale del documento e del prompt
168
+ const totalLength = document.length + prompt.length;
169
+ // Calcola la lunghezza massima disponibile dopo il decremento
170
+ const availableLength = MAX_PROMPT_LENGTH - decrement;
171
+ let partSize = 0;
172
+ // Se la lunghezza totale è minore della lunghezza disponibile, usa la lunghezza del documento
173
+ if (totalLength < availableLength) {
174
+ partSize = document.length;
175
  } else {
176
+ // Altrimenti, trova un punto nel documento per limitare la lunghezza
177
+ partSize = findLimitWithPoint(document, availableLength);
178
  }
179
+ return partSize;
180
  };
181
 
182
  const getPartDoc = (pRgt, partSize) => {
 
211
  init() {
212
  this.readRespsFromDb();
213
  this.readFromDb();
214
+ calcTokens.init();
215
  },
216
  returnOk() {
217
  const ok = this.ragContext.length > 10;
 
239
  readRespsFromDb() {
240
  this.answers = UaDb.readArray(ID_RESPONSES);
241
  },
242
+
243
+ // AAA visualizzazione prompts
244
+ addPrompt(p) {
245
+ // this.prompts.push(p);
246
+ },
247
+
248
  // documenti => risposte RAG => context
249
  async requestDocsRAG(query) {
250
  DataMgr.deleteJsonDati();
251
  DataMgr.readDbDocNames();
252
  DataMgr.readDbDocs();
253
+ this.docContextLst = [];
254
  this.ragQuery = query;
255
  this.saveToDb();
256
  let ndoc = 0;
 
271
  let rgt = "";
272
  let answer = "";
273
  let docAnswersLst = [];
 
274
  while (true) {
275
+ const partSize = getPartSize(doc, promptDoc("", query, ""), decr);
276
+ if (partSize < 10) break;
 
 
277
  [lft, rgt] = getPartDoc(doc, partSize);
278
  ragLog(`${j}) ${ndoc},${npart}`, lft.length, rgt.length, this.answers);
279
  prompt = promptDoc(lft, query, docName);
280
+ this.addPrompt(prompt);
281
  const payload = getPayloadDoc(prompt);
282
+ const rr = await getResponse(payload, 90);
283
+ if (!rr) {
284
+ return "";
285
+ }
286
+ const err = rr.error;
287
+ if (!rr.ok) {
288
+ console.error(`ERR1\n`, err);
289
+ const code = err.code;
290
+ if (code == 400) {
291
+ if (isTooLarge(err)) {
292
+ UaLog.log(`Error tokens Doc ${prompt.length}`);
293
+ decr += PROMPT_DECR;
294
+ continue;
295
+ } else throw err;
296
+ } else if (code == 408) {
297
+ UaLog.log(`Error timeout Context`);
298
  continue;
299
+ } else throw err;
300
+ }
301
+ answer = rr.data;
302
+ if (!answer) return "";
303
+ let itks = calcTokens.get_sum_input_tokens();
304
+ let gtks = calcTokens.get_sum_generate_tokens();
305
+ console.log(`Sum Tokens: ${itks} ${gtks}`);
306
+
307
+ const rsp = rr.response;
308
+ responseDetails.set(rsp);
309
+ itks = responseDetails.get_total_tokens();
310
+ gtks = responseDetails.get_completion_tokens();
311
+ console.log(`Response Tokens: ${itks} ${gtks}`);
312
+ calcTokens.add(rsp);
313
+
314
  npart++;
315
  j++;
316
  doc = rgt;
 
319
  const s = `DOCUMENTO : ${docName}_${npart}\n${answer}`;
320
  this.answers.push(s);
321
  } // end while
322
+ // doc answer list => cContext
323
  const docAnswersLen = docAnswersLst.length;
324
  let docAnswresTxt = docAnswersLst.join("\n\n");
 
325
 
326
+ let docContext = "";
327
  while (true) {
328
  prompt = promptBuildContext(docAnswresTxt, this.ragQuery);
329
  const payload = getPayloadBuildContext(prompt);
330
+ const rr = await getResponse(payload, 90);
331
+ if (!rr) {
332
+ return "";
333
+ }
334
+ const err = rr.error;
335
+ if (!rr.ok) {
336
+ console.error(`ERR2\n`, err);
337
+ const code = err.code;
338
+ if (code == 400) {
339
+ if (isTooLarge(err)) {
340
+ UaLog.log(`Error tokens build Context ${prompt.length}`);
341
+ docAnswresTxt = truncateInput(docAnswresTxt, PROMPT_DECR);
342
+ continue;
343
+ } else throw err;
344
+ } else if (code == 408) {
345
+ UaLog.log(`Error timeout Context`);
346
  continue;
347
+ } else throw err;
 
 
348
  }
349
+ docContext = rr.data;
350
+ if (!docContext) return "";
351
+ const rsp = rr.response;
352
+ calcTokens.add(rsp);
353
  break;
354
  } //end while
355
  UaLog.log(`context ${docAnswersLen} => ${docContext.length}`);
 
357
  this.docContextLst.push(docContext);
358
  } // end for document
359
  } catch (err) {
360
+ console.error("ERR3\n", err);
361
  throw err;
362
  }
363
+ // console.log("tagContext_0\n", this.ragContext);
364
  this.ragContext = this.docContextLst.join("\n\n");
365
+ // console.log("tagContext_1\n", this.ragContext);
366
  this.saveToDb();
367
+ // queryWithContext finale che utilizza context e genera la prima risposta
 
368
  {
369
  let answer = "";
370
  let context = this.ragContext;
 
372
  while (true) {
373
  let prompt = promptWithContext(context, query);
374
  const payload = getPayloadWithContext(prompt);
375
+ const rr = await getResponse(payload, 90);
376
+ if (!rr) {
377
+ return "";
378
+ }
379
+ const err = rr.error;
380
+ if (!rr.ok) {
381
+ console.error(`ERR4\n`, err);
382
+ const code = err.code;
383
+ if (code == 400) {
384
+ if (isTooLarge(err)) {
385
+ UaLog.log(`Error tokens with Context ${prompt.length}`);
386
+ context = truncateInput(context, PROMPT_DECR);
387
+ continue;
388
+ } else throw err;
389
+ } else if (code == 408) {
390
+ UaLog.log(`Error timeout Context`);
391
  continue;
392
+ } else throw err;
 
 
393
  }
394
+ answer = rr.data;
395
+ if (!answer) return "";
396
+ const rsp = rr.response;
397
+ calcTokens.add(rsp);
398
  break;
399
  }
400
  answer = cleanResponse(answer);
 
402
  this.saveRespToDb();
403
  ThreadMgr.init();
404
  this.saveToDb();
405
+ UaLog.log(`Risposta: (${this.ragAnswer.length})`);
406
+
407
+ //log del totale tokens
408
+ const itks = calcTokens.get_sum_input_tokens();
409
+ const gtks = calcTokens.get_sum_generate_tokens();
410
+ UaLog.log(`Tokens: ${itks} ${gtks}`);
411
+ return answer;
412
  } catch (err) {
413
+ console.error("ERR5\n", err);
 
414
  throw err;
 
 
415
  }
416
  } // end query
417
  },
418
+ //richiesta iniziale della conversazione
 
419
  async requestContext(query) {
420
+ let answer = "";
421
  if (!this.ragContext) {
422
+ // gestisce il pulsante verde che ha accettao il contetso vuoto
423
+ this.ragContext = "Sei un assistente AI dispoibile a soddisfare tutte le mi richieste";
 
 
424
  }
425
  if (ThreadMgr.isFirst()) {
426
  ThreadMgr.init();
 
431
  while (true) {
432
  prompt = promptThread(context, thread, query);
433
  const payload = getPayloadThread(prompt);
434
+ const rr = await getResponse(payload, 90);
435
+ if (!rr) {
436
+ return "";
437
+ }
438
+ const err = rr.error;
439
+ if (!rr.ok) {
440
+ console.error(`ERR6\n`, err);
441
+ const code = err.code;
442
+ if (code == 400) {
443
+ if (isTooLarge(err)) {
444
+ UaLog.log(`Error tokens with Context ${prompt.length}`);
445
+ context = truncateInput(context, PROMPT_DECR);
446
+ continue;
447
+ } else throw err;
448
+ } else if (code == 408) continue;
449
+ else throw err;
450
+ }
451
+ answer = rr.data;
452
+ if (!answer) return "";
453
+ let itks = calcTokens.get_sum_input_tokens();
454
+ let gtks = calcTokens.get_sum_generate_tokens();
455
+ console.log(`Sum Tokens: ${itks} ${gtks}`);
456
+
457
+ const rsp = rr.response;
458
+ responseDetails.set(rsp);
459
+ itks = responseDetails.get_total_tokens();
460
+ gtks = responseDetails.get_completion_tokens();
461
+ console.log(`Response Tokens: ${itks} ${gtks}`);
462
+ calcTokens.add(rsp);
463
+
464
  break;
465
  }
466
+ answer = cleanResponse(answer);
467
+ ThreadMgr.add(query, answer);
468
+ answer = ThreadMgr.getThread();
469
  UaLog.log(`Inizio Conversazione (${prompt.length})`);
470
+ return answer;
471
  } catch (err) {
472
+ console.error("ERR7\n", err);
 
473
  throw err;
 
 
474
  }
475
  } else {
476
  try {
 
480
  while (true) {
481
  prompt = promptThread(context, thread, query);
482
  const payload = getPayloadThread(prompt);
483
+ const rr = await getResponse(payload, 90);
484
+ if (!rr) {
485
+ return "";
486
+ }
487
+ const err = rr.error;
488
+ if (!rr.ok) {
489
+ console.error(`ERR8\n`, err);
490
+ const code = err.code;
491
+ if (code == 400) {
492
+ if (isTooLarge(err)) {
493
+ UaLog.log(`Error tokens with Context ${prompt.length}`);
494
+ context = truncateInput(context, PROMPT_DECR);
495
+ continue;
496
+ } else throw err;
497
+ } else if (code == 408) {
498
+ UaLog.log(`Error timeout Context`);
499
  continue;
500
+ } else throw err;
 
 
501
  }
502
+ answer = rr.data;
503
+ if (!answer) return "";
504
+ const rsp = rr.response;
505
+ let itks = calcTokens.get_sum_input_tokens();
506
+ let gtks = calcTokens.get_sum_generate_tokens();
507
+ console.log(`Sum Tokens: ${itks} ${gtks}`);
508
+ responseDetails.set(rsp);
509
+ itks = responseDetails.get_total_tokens();
510
+ gtks = responseDetails.get_completion_tokens();
511
+ console.log(`Response Tokens: ${itks} ${gtks}`);
512
+ calcTokens.add(rsp);
513
  break;
514
  }
515
+ answer = cleanResponse(answer);
516
+ ThreadMgr.add(query, answer);
517
+ answer = ThreadMgr.getThread();
518
  UaLog.log(`Conversazione (${prompt.length})`);
519
+ return answer;
520
  } catch (err) {
521
+ console.error("ERR9\n", err);
 
522
  throw err;
 
 
523
  }
524
  }
525
  },
526
  };
527
 
528
+ const LLM = "# Assistant:";
529
+ const USER = "# User:";
530
 
531
  const ThreadMgr = {
532
  rows: [],
 
548
  for (const ua of this.rows) {
549
  const u = ua[0];
550
  const a = ua[1];
551
+ if (!u) continue;
552
  rows.push(`${USER}\n${u}\n${LLM}\n${a}\n`);
553
  }
554
  return rows.join("\n\n");
static/javascript/rag_payload.js ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** @format */
2
+
3
+ function getPayloadDoc(prompt) {
4
+ return {
5
+ model: "",
6
+ temperature: 0.3,
7
+ //top_p": 1,
8
+ max_tokens: 1024,
9
+ stream: false,
10
+ //stop: "</s>",
11
+ random_seed: 42,
12
+ messages: [{ role: "user", content: prompt }],
13
+ //AAA response_format: {
14
+ // type: "text",
15
+ // },
16
+ // tools: [
17
+ // {
18
+ // type: "function",
19
+ // function: {
20
+ // name: "string",
21
+ // description: "",
22
+ // parameters: {}
23
+ // }
24
+ // }
25
+ // ],
26
+ // tool_choice: "auto",
27
+ // presence_penalty: 0,
28
+ // frequency_penalty: 0,
29
+ // n: 1,
30
+ safe_prompt: false,
31
+ };
32
+ }
33
+
34
+ function getPayloadBuildContext(prompt) {
35
+ return {
36
+ model: "",
37
+ messages: [{ role: "user", content: prompt }],
38
+ temperature: 0.3,
39
+ max_tokens: 2000,
40
+ stream: false,
41
+ safe_prompt: false,
42
+ random_seed: 42,
43
+ };
44
+ }
45
+
46
+ function getPayloadWithContext(prompt) {
47
+ return {
48
+ model: "",
49
+ messages: [{ role: "user", content: prompt }],
50
+ temperature: 0.3,
51
+ max_tokens: 2000,
52
+ stream: false,
53
+ safe_prompt: false,
54
+ random_seed: 42,
55
+ };
56
+ }
57
+
58
+ function getPayloadThread(prompt) {
59
+ return {
60
+ model: "",
61
+ messages: [{ role: "user", content: prompt }],
62
+ temperature: 0.7,
63
+ max_tokens: 2000,
64
+ stream: false,
65
+ safe_prompt: false,
66
+ random_seed: 42,
67
+ };
68
+ }
static/javascript/rag_prompts.js CHANGED
@@ -1,283 +1,308 @@
1
  /** @format */
2
-
3
- "use strict";
4
-
5
- function promptDoc(testo, domanda, docName) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  return `
7
- SYSTEM: Sei un assistente AI specializzato nell'analisi documentale e nell'estrazione mirata di informazioni. Rispondi esclusivamente in italiano.
8
-
9
- TASK: Analizza il testo estratto dal documento "${docName}" e identifica gli elementi rilevanti per rispondere alla domanda: "${domanda}".
10
-
11
- INSTRUCTIONS:
12
- 1. Analizza attentamente il testo fornito compreso fra i marker <<<INIZIO_TESTO>>> e <<<FINE_TESTO>>> .
13
- 2. Identifica gli elementi utili per rispondere alla domanda:"${domanda}".
14
- 3. Per ogni elemento individuato, fornisci un titolo ed una descrizione sintetica ma completa.
15
- 4. Riporta dettagli specifici (dati, citazioni, eventi, personaggi, luoghi, ..) se corelati alla domanda.
16
- 5. Se non ci sono informazioni rilevanti, rispondi con "NESSUNA INFORMAZIONE RILEVANTE".
17
- 6. Assicurati di generare la risposta esattamente secondo il formato di output specificato.
18
-
19
- DOMANDA: ${domanda}
20
-
21
- TESTO DA ANALIZZARE:
22
- <<<INIZIO_TESTO>>>
 
 
 
 
 
 
 
 
23
  ${testo}
24
- <<<FINE_TESTO>>>
25
 
26
- OUTPUT_FORMAT: Genera una risposta strutturata come un elenco nel quale ogni elemento è costituito da un breve titolo e da una descrizione concisa ma completa.
 
27
 
28
- RESPONSE:
29
  `;
30
  }
31
 
32
-
33
- function promptBuildContext(informazioni, domanda = "") {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  return `
35
- SYSTEM: Sei un assistente AI esperto nella sintesi e nell'organizzazione mirata di informazioni. Rispondi sempre ed esclusivamente in italiano.
36
-
37
- TASK: Organizza e sintetizza le informazioni estratte da frammenti di testo di un documento, creando un contesto utile per rispondere alla domanda: "${domanda}".
38
-
39
- INSTRUCTIONS:
40
- 1. Analizza tutte le informazioni fornite.
41
- 2. Seleziona e raggruppa le informazioni simili.
42
- 3. Per ogni informazioni, genera una descrizione concisa.
43
- 4. Elenca i punti chiave essenziali per comprendere il contesto.
44
- 5. Riporta elementi specifici (dati, citazioni, eventi, luoghi, personaggi, ..) se utili.
45
- 6. Elabora inferenze logiche basate sulle informazioni, se rilevanti per il contesto.
46
- 7. Genera una sintesi finale.
47
- 8. Assicurati di strutturare la tua risposta esattamente secondo il formato di output specificato.
48
-
49
- INFORMAZIONI:
50
- <<<INIZIO_INFORMAZIONI>>>
51
- ${informazioni}
52
- <<<FINE_INFORMAZIONI>>>
53
-
54
- OUTPUT_FORMAT: Genera una risposta strutturata come un elenco nel quale ogni elemento è costituito da un breve titolo e da una descrizione concisa ma completa, alla fine dell'elenco aggiungi una sintesi globale ed eventuali inferenze logiche e collegamenti fra le varie informazioni.
 
 
 
 
 
55
 
56
- RESPONSE:
57
  `;
58
  }
59
 
60
  function promptWithContext(contesto, domanda) {
61
  return `
62
- SYSTEM: Sei un sistema AI specializzato nell'analisi di informazioni estratte da documenti.
 
63
 
64
- TASK: Elabora la risposta alla domanda "${domanda}" sulla base del contesto fornito.
 
65
 
66
- INSTRUCTIONS:
67
- 1. Analizza attentamente il contesto fornito, identificando le informazioni pertinenti alla domanda: "${domanda}".
68
  2. Estrai i concetti chiave e formula inferenze ragionevoli basate sulle informazioni disponibili.
69
  3. Inizia la risposta con una breve introduzione che presenta l'argomento e il contesto.
70
  4. Procedi con un'analisi dettagliata delle informazioni rilevanti trovate nel contesto.
71
- 5. Concludi con una sintesi che riassume i punti chiave e fornisce una conclusione generale.
72
- 6. Se richiesto, cita le fonti facendo riferimento al "documento fornito" per il contesto dato, distinguendolo chiaramente da eventuali altre fonti citate all'interno del contesto stesso.
73
- 7. Mantieni uno stile di scrittura fluido durante tutta la risposta.
74
- 8. Assicurati che la risposta sia completa e risponda direttamente alla domanda posta.
75
 
76
- CONTESTO:
77
- <<<INIZIO_CONTESTO>>>
78
  ${contesto}
79
- <<<FINE_CONTESTO>>>
80
 
81
- DOMANDA: ${domanda}
 
82
 
83
- OUTPUT_FORMAT: Fornisci la risposta in testo semplice e lineare suddiviso in paragrafi.
 
84
 
85
- RESPONSE:
86
  `;
87
  }
88
 
89
  function promptThread(contesto, conversazione, richiesta) {
90
  return `
91
- SYSTEM: Sei un assistente AI versatile progettato per gestire conversazioni dinamiche e adattarti a varie richieste. Rispondi sempre in italiano.
 
92
 
93
- TASK: Elabora la risposta alla richiesta "${richiesta}" sulla base del contesto fornito e della conversazione.
 
94
 
95
- INSTRUCTIONS:
96
- 1. Analizza attentamente il contesto, la conversazione precedente e la richiesta: "${richiesta}".
97
  2. Interpreta l'intento dell'utente senza limitarti a categorie predefinite.
98
  3. Adatta la tua risposta in base all'intento percepito, sia esso una domanda, una richiesta di azione, un'istruzione specifica o altro.
99
  4. Mantieni una stretta coerenza con il contesto della conversazione.
100
  5. Basa la tua risposta sulle informazioni fornite nel contesto e nella conversazione.
101
  6. Evita divagazioni o argomentazioni non direttamente pertinenti alla richiesta o al contesto.
102
- 7. Fai riferimento a informazioni precedenti quando sono pertinenti, citando specificamente la fonte.
103
- 8. Se l'intento non è chiaro, chiedi gentilmente chiarimenti invece di fare supposizioni.
104
- 9. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza.
105
- 10. Se è necessario integrare con conoscenze generali, specifica chiaramente quando lo stai facendo.
106
 
107
- CONTESTO:
108
- <<<BEGIN_CONTESTO>>>
109
  ${contesto}
110
- <<<END_CONTESTO>>>
111
 
112
- <<<INIZIO_CONVERSAZIONE>>>
113
  ${conversazione}
114
- <<<FINE_CONVERSAZIONE>>>
115
 
116
- RICHIESTA: ${richiesta}
 
117
 
118
- OUTPUT_FORMAT: Fornisci la risposta in testo semplice e lineare suddiviso in paragrafi.
 
119
 
120
- RESPONSE:
121
  `;
122
  }
123
-
124
- /*
125
- 1. max_new_tokens: 512
126
- Questo è un valore ragionevole per risposte di lunghezza media.
127
- Potrebbe essere aumentato a 1024 o più se si desiderano risposte più lunghe e dettagliate.
128
-
129
- 2. temperature: 0.7
130
- Questo valore offre un buon equilibrio tra creatività e coerenza.
131
- Va bene per la maggior parte degli usi.
132
-
133
- 3. top_k: 50
134
- Un valore standard che limita la selezione alle 50 parole più probabili.
135
- È appropriato per la maggior parte delle applicazioni.
136
-
137
- 4. top_p: 0.85
138
- Questo valore di nucleus sampling è buono per mantenere un buon equilibrio
139
- tra diversità e coerenza.
140
-
141
- 5. do_sample: true
142
- Corretto per generare testo più vario.
143
-
144
- 6. no_repeat_ngram_size: 3
145
- Aiuta a evitare ripetizioni a breve termine.
146
- Potrebbe essere aumentato a 4 o 5 per evitare ripetizioni più lunghe.
147
-
148
- 7. num_beams: 5
149
- Un buon valore per la beam search.
150
- Aumentarlo potrebbe migliorare la qualità ma aumenterebbe anche il
151
- tempo di elaborazione.
152
-
153
- 8. repetition_penalty: 1.2
154
- Un valore moderato per penalizzare le ripetizioni.
155
- Potrebbe essere aumentato leggermente (es. 1.3 o 1.4) se si notano
156
- ancora troppe ripetizioni.
157
-
158
- 9. return_full_text: false
159
- Corretto se si vuole solo il nuovo testo generato.
160
-
161
- 10. max_time: 60.0
162
- Un minuto è un tempo ragionevole. Potrebbe essere aumentato
163
- se si stanno generando risposte molto lunghe o complesse.
164
-
165
- 11. seed: 42
166
- Un valore fisso per la riproducibilità.
167
- Va bene se si desidera coerenza tra le esecuzioni.
168
-
169
- Suggerimenti per l'ottimizzazione:
170
- 1. Considera di aumentare max_new_tokens a 1024 o più se hai bisogno di risposte più lunghe.
171
- 2. Potresti aumentare leggermente no_repeat_ngram_size a 4 per ridurre ulteriormente le ripetizioni.
172
- 3. Se desideri risposte più precise e meno creative, potresti ridurre temperature a 0.6 e top_p a 0.8.
173
- 4. Per risposte più diverse, potresti aumentare temperature a 0.8 e top_p a 0.9.
174
- 5. Se noti ancora troppe ripetizioni, considera di aumentare repetition_penalty a 1.3 o 1.4.
175
- */
176
-
177
- function getPayloadDoc(prompt) {
178
- const payload = {
179
- inputs: prompt,
180
- parameters: {
181
- task: "text2text-generation",
182
- max_new_tokens: 2000,
183
- num_return_sequences: 1,
184
- temperature: 0.4,
185
- top_p: 0.85,
186
- top_k: 30,
187
- do_sample: false,
188
- no_repeat_ngram_size: 3,
189
- num_beams: 4,
190
- repetition_penalty: 1.2,
191
- return_full_text: false,
192
- details: false,
193
- max_time: 90.0,
194
- seed: 42,
195
- },
196
- options: {
197
- use_cache: false,
198
- wait_for_model: true,
199
- },
200
- };
201
- return payload;
202
- }
203
-
204
- function getPayloadBuildContext(prompt) {
205
- const payload = {
206
- inputs: prompt,
207
- parameters: {
208
- task: "text2text-generation",
209
- max_new_tokens: 6000,
210
- num_return_sequences: 1,
211
- temperature: 0.7,
212
- top_p: 0.85,
213
- top_k: 30,
214
- do_sample: false,
215
- no_repeat_ngram_size: 4,
216
- num_beams: 6,
217
- repetition_penalty: 1.2,
218
- return_full_text: false,
219
- details: false,
220
- max_time: 180.0,
221
- seed: 42,
222
- },
223
- options: {
224
- use_cache: false,
225
- wait_for_model: true,
226
- },
227
- };
228
- return payload;
229
- }
230
-
231
- function getPayloadWithContext(prompt) {
232
- const payload = {
233
- inputs: prompt,
234
- parameters: {
235
- task: "text2text-generation",
236
- max_new_tokens: 4000,
237
- num_return_sequences: 1,
238
- temperature: 0.7,
239
- top_p: 0.85,
240
- top_k: 30,
241
- do_sample: false,
242
- no_repeat_ngram_size: 4,
243
- num_beams: 5,
244
- repetition_penalty: 1.4,
245
- return_full_text: false,
246
- details: false,
247
- max_time: 120.0,
248
- seed: 42,
249
- },
250
- options: {
251
- use_cache: false,
252
- wait_for_model: true,
253
- },
254
- };
255
- return payload;
256
- }
257
-
258
- function getPayloadThread(prompt) {
259
- const payload = {
260
- inputs: prompt,
261
- parameters: {
262
- task: "text2text-generation",
263
- max_new_tokens: 6048,
264
- num_return_sequences: 1,
265
- temperature: 0.7,
266
- top_p: 0.85,
267
- top_k: 30,
268
- do_sample: false,
269
- no_repeat_ngram_size: 4,
270
- num_beams: 5,
271
- repetition_penalty: 1.4,
272
- return_full_text: false,
273
- details: false,
274
- max_time: 120.0,
275
- seed: 42,
276
- },
277
- options: {
278
- use_cache: false,
279
- wait_for_model: true,
280
- },
281
- };
282
- return payload;
283
- }
 
1
  /** @format */
2
+ // function promptDoc(documento, domanda) {
3
+ // const prompt = `
4
+ // ### RUOLO ###
5
+ // Sei un assistente AI specializzato nell'analisi documentale e nell'estrazione mirata di informazioni. Operi esclusivamente in italiano.
6
+
7
+ // ### COMPITO ###
8
+ // Identificare nel documento le informazioni utili per rispondere alla domanda fornita.
9
+
10
+ // ### ISTRUZIONI ###
11
+ // 1. Analizza il documento fornito in modo sequenziale.
12
+ // 2. Interpreta la domanda in relazione al contenuto del documento.
13
+ // 3. Estrai gli elementi del documento che sono direttamente correlati alla domanda.
14
+ // 4. Includi dettagli specifici (dati, citazioni, eventi, personaggi, luoghi, ecc.) se correlati alla domanda.
15
+ // 5. Escludi meta-dati, inferenze non testuali e informazioni marginali
16
+
17
+ // ### FORMATO_RISPOSTA ###
18
+ // La risposta deve rispettare le seguenti specifiche:
19
+ // 1. Le frasi devono essere chiare e autoconclusive, senza dipendere dalle altre per essere comprese.
20
+ // 2. Struttura a blocchi di testo separati da una riga vuota.
21
+ // 3. Caratteristiche obbligatorie:
22
+ // - Completezza semantica autonoma
23
+ // - Assenza di marcatori grafici
24
+ // - Formulazione neutra e oggettiva
25
+ // - Aderenza letterale al contenuto
26
+ // 4. Divieti assoluti:
27
+ // - Citazioni testuali tra virgolette
28
+ // - Riferimenti al documento o al processo
29
+ // - Ripetizioni concettuali
30
+
31
+ // ### DOMANDA ###
32
+ // ${domanda}
33
+
34
+ // ### DOCUMENTO ###
35
+ // ${documento}
36
+
37
+ // ### RISPOSTA ###
38
+ // `;
39
+ // return prompt;
40
+ // }
41
+ // function promptBuildContext(documento, domanda = "") {
42
+ // return `
43
+ // ### RUOLO ###
44
+ // Sei un assistente AI specializzato nell'organizzazione di informazioni. Operi esclusivamente in italiano.
45
+
46
+ // ### COMPITO ###
47
+ // Organizzare le informazioni del documento raggruppandole per analogia semantica.
48
+
49
+ // ### ISTRUZIONI ###
50
+ // 1. Analizza il documento fornito in modo sequenziale.
51
+ // 2. Raggruppa le informazioni per analogia semantica.
52
+ // 3. Assicurati che tutte le informazioni siano incluse nella risposta.
53
+
54
+ // ### DOCUMENTO ###
55
+ // ${documento}
56
+
57
+ // ### FORMATO_RISPOSTA ###
58
+ // La risposta deve rispettare le seguenti specifiche:
59
+ // 1. Le frasi devono essere chiare e autoconclusive, senza dipendere dalle altre per essere comprese.
60
+ // 2. Struttura a blocchi di testo separati da una riga vuota.
61
+ // 3. Caratteristiche obbligatorie:
62
+ // - Completezza semantica autonoma
63
+ // - Assenza di marcatori grafici
64
+ // - Formulazione neutra e oggettiva
65
+ // - Aderenza letterale al contenuto
66
+ // 4. Divieti assoluti:
67
+ // - Citazioni testuali tra virgolette
68
+ // - Riferimenti al processo di elaborazione
69
+ // - Ripetizioni concettuali
70
+
71
+ // ### RISPOSTA ###
72
+ // `;
73
+ // }
74
+ // function promptWithContext(contesto, domanda = "") {
75
+ // return `
76
+ // ### RUOLO ###
77
+ // Sei un assistente AI che risponde sempre ed esclusivamente in italiano.
78
+
79
+ // ### COMPITO ###
80
+ // Elabora la risposta alla domanda sulla base del contesto fornito.
81
+
82
+ // ### ISTRUZIONI ###
83
+ // 1. Analizza attentamente il contesto e la domanda: "${domanda}".
84
+ // 2. Estrai i concetti chiave e formula inferenze ragionevoli basate sulle informazioni disponibili.
85
+ // 3. Inizia la risposta con una breve introduzione che presenta l'argomento e il contesto.
86
+ // 4. Procedi con un'analisi dettagliata delle informazioni rilevanti trovate nel contesto.
87
+ // 5. Concludi con una sintesi che riassume i punti chiave e fornisce una conclusione generale.
88
+ // 6. Assicurati che la risposta sia completa e risponda direttamente alla domanda posta.
89
+
90
+ // ### CONTESTO ###
91
+ // ${contesto}
92
+
93
+ // ### FORMATO_RISPOSTA ###
94
+ // La risposta deve rispettare le seguenti specifiche:
95
+ // 1. Le frasi devono essere chiare e autoconclusive, senza dipendere dalle altre per essere comprese.
96
+ // 2. Struttura a blocchi di testo separati da una riga vuota.
97
+ // 3. Caratteristiche obbligatorie:
98
+ // - Completezza semantica autonoma
99
+ // - Assenza di marcatori grafici
100
+ // - Formulazione neutra e oggettiva
101
+ // - Aderenza letterale al contenuto
102
+ // 4. Divieti assoluti:
103
+ // - Citazioni testuali tra virgolette
104
+ // - Riferimenti al processo di elaborazione
105
+ // - Ripetizioni concettuali
106
+
107
+ // ### RISPOSTA ###
108
+ // `;
109
+ // }
110
+ // function promptThread(contesto, conversazione, richiesta) {
111
+ // return `
112
+ // ### RUOLO ###
113
+ // Sei un assistente AI progettato per gestire conversazioni dinamiche e adattarti a varie richieste. Operi esclusivamente in italiano.
114
+
115
+ // ### COMPITO ###
116
+ // Elabora la risposta alla richiesta sulla base del contesto fornito e della conversazione.
117
+
118
+ // ### ISTRUZIONI ###
119
+ // 1. Analizza attentamente il contesto, la conversazione precedente e la richiesta.
120
+ // 2. Interpreta l'intento dell'utente senza limitarti a categorie predefinite.
121
+ // 3. Adatta la tua risposta in base all'intento percepito, sia esso una domanda, una richiesta di azione, un'istruzione specifica o altro.
122
+ // 4. Mantieni una stretta coerenza con il contesto della conversazione.
123
+ // 5. Basa la tua risposta sulle informazioni fornite nel contesto e nella conversazione.
124
+ // 6. Evita divagazioni o argomentazioni non direttamente pertinenti alla richiesta o al contesto.
125
+ // 7. Se l'intento non è chiaro, chiedi gentilmente chiarimenti invece di fare supposizioni.
126
+ // 8. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza.
127
+ // 9. Se è necessario integrare con conoscenze generali, specifica chiaramente quando lo stai facendo.
128
+
129
+ // ### CONTESTO ###
130
+ // ${contesto}
131
+
132
+ // ### CONVERSAZIONE ###
133
+ // ${conversazione}
134
+
135
+ // ### RICHIESTA ###
136
+ // ${richiesta}
137
+
138
+ // ### FORMATO_RISPOSTA ###
139
+ // Fornisci la risposta in un formato semplice e lineare suddiviso in paragrafi.
140
+
141
+ // ### RISPOSTA ###
142
+ // `;
143
+ // }
144
+
145
+ ///////////////////
146
+ function promptDoc(testo, domanda) {
147
  return `
148
+ # SISTEMA
149
+ Estrattore semantico di informazioni ottimizzato per elaborazione da LLM.
150
+
151
+ # OBIETTIVO
152
+ Estrarre e condensare le informazioni essenziali dal TESTO per rispondere alla DOMANDA, in formato ottimizzato per elaborazione computazionale.
153
+
154
+ # ISTRUZIONI
155
+ 1. Analizza il testo e seleziona SOLO le informazioni direttamente rilevanti per la domanda.
156
+ 2. Elimina contenuti irrilevanti o ridondanti.
157
+ 3. Mantieni relazioni logiche essenziali (causali, temporali, concettuali).
158
+ 4. Preserva terminologia specialistica necessaria.
159
+ 5. Produci proposizioni atomiche semanticamente complete.
160
+ 6. Usa sintassi minimale (soggetto-verbo-complemento).
161
+ 7. Elimina elementi discorsivi, connettivi e contestualizzazioni non essenziali.
162
+ 8. Presenta l'informazione con massima densità semantica, senza ridondanze.
163
+
164
+ # FORMATO
165
+ - Struttura flat senza gerarchie
166
+ - Non numerare le proposizioni.
167
+ - Non usare introduzioni o conclusioni.
168
+ - Non includere spiegazioni meta-testuali.
169
+ - Non inserire frasi di collegamento tra le proposizioni.
170
+
171
+ # TESTO
172
  ${testo}
 
173
 
174
+ # DOMANDA
175
+ ${domanda}
176
 
177
+ # RISPOSTA
178
  `;
179
  }
180
 
181
+ // function xpromptBuildContext(testo, domanda) {
182
+ // return `
183
+ // # SISTEMA
184
+ // Estrattore e compattatore semantico per contesto LLM.
185
+
186
+ // # OBIETTIVO
187
+ // Compattare il testo unificato eliminando duplicazioni semantiche e mantenendo solo informazioni essenziali relative alla domanda.
188
+
189
+ // # ISTRUZIONI
190
+ // 1. Identifica e unifica concetti semanticamente equivalenti presenti in diverse parti del testo.
191
+ // 2. Elimina ripetizioni informative mantenendo solo la formulazione più completa o precisa.
192
+ // 3. Seleziona SOLO informazioni rilevanti per rispondere alla domanda.
193
+ // 4. Mantieni relazioni logiche essenziali (causali, temporali, concettuali).
194
+ // 5. Preserva terminologia tecnica necessaria.
195
+ // 6. Produci proposizioni atomiche con struttura minimale.
196
+ // 7. Rimuovi informazioni ridondanti anche se espresse con parole diverse.
197
+ // 8. Massimizza la densità informativa per uso efficiente come contesto.
198
+
199
+ // # FORMATO
200
+ // - Non numerare le proposizioni.
201
+ // - Non usare introduzioni o conclusioni.
202
+ // - Non includere spiegazioni meta-testuali.
203
+ // - Non inserire frasi di collegamento tra le proposizioni.
204
+
205
+ // # TESTO
206
+ // ${testo}
207
+
208
+ // # DOMANDA
209
+ // ${domanda}
210
+
211
+ // # RISPOSTA
212
+ // `;
213
+ // }
214
+
215
+ function promptBuildContext(testo, domanda = "") {
216
  return `
217
+ # SISTEMA
218
+ Estrattore e compattatore semantico per contesto LLM.
219
+
220
+ # OBIETTIVO
221
+ Raggruppa e compatta le informazioni estratte dai frammenti di un documento, associando concetti semanticamente simili e sviluppando inferenze tra le informazioni.
222
+
223
+ # ISTRUZIONI
224
+ 1. Identificazione dei Concetti: Identifica e unifica i concetti che hanno lo stesso significato semantico, anche se espressi in modi diversi.
225
+ 2. Eliminazione delle Ripetizioni: Elimina le ripetizioni informative mantenendo solo la formulazione più completa o precisa.
226
+ 3. Preservazione delle Relazioni Logiche: Mantieni le relazioni logiche essenziali (causali, temporali, concettuali) tra le informazioni.
227
+ 4. Terminologia Tecnica: Preserva la terminologia tecnica necessaria per mantenere la precisione delle informazioni.
228
+ 5. Sintassi Semplificata: Usa una sintassi minimale (soggetto-verbo-complemento) per chiarezza e concisione.
229
+ 6. Eliminazione degli Elementi Discorsivi: Rimuovi elementi discorsivi, connettivi e contestualizzazioni non essenziali.
230
+ 7. Densità Semantica: Presenta l'informazione con la massima densità semantica, evitando ridondanze.
231
+ 8. Rielaborazione degli Insegnamenti: Rielabora le informazioni per garantire che siano coese e che sviluppino inferenze tra parti diverse del documento.
232
+
233
+ # FORMATO_OUTPUT
234
+ - Struttura flat senza gerarchie.
235
+ - NON numerare le proposizioni.
236
+ - NON usare introduzioni o conclusioni.
237
+ - NON includere spiegazioni meta-testuali.
238
+ - NON inserire frasi di collegamento tra le proposizioni.
239
+
240
+ # TESTO
241
+ ${testo}
242
 
243
+ # RISPOSTA
244
  `;
245
  }
246
 
247
  function promptWithContext(contesto, domanda) {
248
  return `
249
+ # RUOLO
250
+ Sei un assistente AI che risponde sempre ed esclusivamente in italiano.
251
 
252
+ # COMPITO
253
+ Elabora la risposta alla domanda sulla base del contesto fornito.
254
 
255
+ # ISTRUZIONI
256
+ 1. Analizza attentamente il CONTESTO e la DOMANDA.
257
  2. Estrai i concetti chiave e formula inferenze ragionevoli basate sulle informazioni disponibili.
258
  3. Inizia la risposta con una breve introduzione che presenta l'argomento e il contesto.
259
  4. Procedi con un'analisi dettagliata delle informazioni rilevanti trovate nel contesto.
260
+ 5. Assicurati che la risposta sia completa e risponda direttamente alla domanda posta.
 
 
 
261
 
262
+ # CONTESTO
 
263
  ${contesto}
 
264
 
265
+ # DOMANDA
266
+ ${domanda}
267
 
268
+ # FORMATO_RISPOSTA
269
+ Fornisci la risposta in un formato semplice e lineare suddiviso in paragrafi.
270
 
271
+ # RISPOSTA
272
  `;
273
  }
274
 
275
  function promptThread(contesto, conversazione, richiesta) {
276
  return `
277
+ # RUOLO
278
+ Sei un assistente AI progettato per gestire conversazioni dinamiche e adattarti a varie richieste. Operi esclusivamente in italiano.
279
 
280
+ # COMPITO
281
+ Elabora la risposta alla richiesta sulla base del contesto fornito e della conversazione.
282
 
283
+ # ISTRUZIONI
284
+ 1. Analizza attentamente il contesto, la conversazione precedente e la richiesta.
285
  2. Interpreta l'intento dell'utente senza limitarti a categorie predefinite.
286
  3. Adatta la tua risposta in base all'intento percepito, sia esso una domanda, una richiesta di azione, un'istruzione specifica o altro.
287
  4. Mantieni una stretta coerenza con il contesto della conversazione.
288
  5. Basa la tua risposta sulle informazioni fornite nel contesto e nella conversazione.
289
  6. Evita divagazioni o argomentazioni non direttamente pertinenti alla richiesta o al contesto.
290
+ 7. Se l'intento non è chiaro, chiedi gentilmente chiarimenti invece di fare supposizioni.
291
+ 8. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza.
292
+ 9. Se è necessario integrare con conoscenze generali, specifica chiaramente quando lo stai facendo.
 
293
 
294
+ # CONTESTO
 
295
  ${contesto}
 
296
 
297
+ # CONVERSAZIONE
298
  ${conversazione}
 
299
 
300
+ # RICHIESTA
301
+ ${richiesta}
302
 
303
+ # FORMATO_RISPOSTA
304
+ Fornisci la risposta in un formato semplice e lineare suddiviso in paragrafi.
305
 
306
+ # RISPOSTA
307
  `;
308
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
static/javascript/rag_ui.js CHANGED
@@ -17,6 +17,13 @@
17
  * You should have received a copy of the GNU General Public License
18
  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
  */
 
 
 
 
 
 
 
20
  const WndPre = (id) => {
21
  return {
22
  w: UaWindowAdm.create(id),
@@ -26,12 +33,12 @@ const WndPre = (id) => {
26
  return `
27
  <div class="window-text">
28
  <div class="btn-wrapper">
29
- <button class="btn-copy" title="Copia">
30
  <svg class="copy-icon" viewBox="0 0 20 24">
31
  <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
32
  </svg>
33
  </button>
34
- <button class="btn-close" title="chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>
35
  </div>
36
  <pre class="pre-text">${txt}</pre>
37
  </div>
@@ -73,12 +80,12 @@ const WndDiv = (id) => {
73
  return `
74
  <div class="window-text">
75
  <div class="btn-wrapper">
76
- <button class="btn-copy" title="Copia">
77
  <svg class="copy-icon" viewBox="0 0 20 24">
78
  <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
79
  </svg>
80
  </button>
81
- <button class="btn-close" title="chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>
82
  </div>
83
  <div class="div-text">${txt}</div>
84
  </div>
@@ -132,6 +139,11 @@ const Menu = {
132
  const btn = document.querySelector("#id-menu-btn");
133
  btn.addEventListener("change", () => {
134
  document.querySelector("body").classList.toggle("menu-open", btn.checked);
 
 
 
 
 
135
  });
136
  // getsioe log
137
  const log = document.getElementById("id_log");
@@ -145,6 +157,7 @@ const Menu = {
145
  if (!log.classList.contains("active")) return;
146
  log.classList.remove("active");
147
  };
 
148
  UaLog.callHide = hide;
149
  UaLog.callShow = show;
150
 
@@ -156,9 +169,8 @@ const Menu = {
156
  document.querySelector("body").classList.remove("menu-open", btn.checked);
157
  document.querySelector(".menu-btn").checked = false;
158
  },
159
- async help() {
160
- const text = await requestGet("./help0.html");
161
- wnds.wdiv.show(text);
162
  },
163
  upload() {
164
  RagUpload.open();
@@ -175,25 +187,12 @@ const Menu = {
175
  };
176
 
177
  const setOutText = (txt) => {
178
- const p = document.querySelector("#id-text-out .pre-text");
179
- p.textContent = txt;
 
180
  p.scrollTop = p.scrollHeight;
181
  };
182
 
183
- // const setOutText2 = async (txt) => {
184
- // const t = p.textContent;
185
- // if (t.trim().length < 2) {
186
- // p.textContent = txt;
187
- // p.scrollTop = p.scrollHeight;
188
- // return;
189
- // }
190
- // for (let i = 0; i < txt.length; i++) {
191
- // p.textContent += txt[i];
192
- // p.scrollTop = p.scrollHeight;
193
- // await new Promise((resolve) => setTimeout(resolve, 2));
194
- // }
195
- // };
196
-
197
  const TextInput = {
198
  wnd: null,
199
  init() {
@@ -267,8 +266,13 @@ const TextInput = {
267
  alert("Ricorda di scrivere la Query ");
268
  return;
269
  }
 
 
 
 
 
270
  if (!!Rag.ragContext) {
271
- const ok = confirm("Vuoi iniziare una nuova elabrazione ?");
272
  if (!ok) return "";
273
  }
274
  showSpinner();
@@ -276,15 +280,13 @@ const TextInput = {
276
  const msg = this.inp.value.trim();
277
  try {
278
  let text = await Rag.requestDocsRAG(msg);
279
- text = cleanOut(text);
280
  setOutText(text);
281
  this.inp.value = "";
282
  UaLog.close();
283
  } catch (err) {
284
- const msg = `send\n${err}`;
285
- console.error(msg);
286
- alert(msg);
287
- setOutText(msg);
288
  }
289
  hideSpinner();
290
  },
@@ -298,7 +300,6 @@ const TextInput = {
298
  }
299
  showSpinner();
300
  if (ThreadMgr.isFirst()) {
301
- setOutText("");
302
  }
303
  const query = this.inp.value.trim();
304
  try {
@@ -307,19 +308,17 @@ const TextInput = {
307
  hideSpinner();
308
  return;
309
  }
310
- text = cleanOut(text);
311
  setOutText(text);
312
  this.inp.value = "";
313
  } catch (err) {
314
- const msg = `send2\n${err}`;
315
- console.error(msg);
316
- alert(msg);
317
- setOutText(msg);
318
  }
319
  hideSpinner();
320
  },
321
- clear() {
322
- const ok = confirm("Confermi cancellazione conversazione? ");
323
  if (!ok) return;
324
  this.inp.value = "";
325
  setOutText("");
@@ -337,17 +336,19 @@ TextOutput = {
337
  wndBtn.addEventListener("click", () => this.openWnd());
338
  },
339
  openWnd() {
340
- const p = document.querySelector("#id-text-out .pre-text");
341
- const s = p.textContent;
342
  wnds.wout.show(s);
343
  },
344
  async copy() {
345
- const pre = document.querySelector("#id-text-out .pre-text");
346
- const t = pre.textContent;
 
347
  if (t.trim().length < 2) return;
348
  pre.classList.add("copied");
349
  this.copyBtn.classList.add("copied");
350
  try {
 
351
  await navigator.clipboard.writeText(t);
352
  } catch (err) {
353
  console.error("Errore ", err);
@@ -358,7 +359,7 @@ TextOutput = {
358
  }, 5000);
359
  },
360
  clear() {
361
- const out = document.querySelector("#id-text-out .pre-text");
362
  out.textContent = "";
363
  },
364
  };
 
17
  * You should have received a copy of the GNU General Public License
18
  * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
  */
20
+
21
+ const errorDumps = (err) => {
22
+ const s = JSON.stringify(err, null, 2);
23
+ if (s == "{}") return `${err}`;
24
+ return s;
25
+ };
26
+
27
  const WndPre = (id) => {
28
  return {
29
  w: UaWindowAdm.create(id),
 
33
  return `
34
  <div class="window-text">
35
  <div class="btn-wrapper">
36
+ <button class="btn-copy tt-left" data-tt="Copia">
37
  <svg class="copy-icon" viewBox="0 0 20 24">
38
  <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
39
  </svg>
40
  </button>
41
+ <button class="btn-close tt-left" data-tt="chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>
42
  </div>
43
  <pre class="pre-text">${txt}</pre>
44
  </div>
 
80
  return `
81
  <div class="window-text">
82
  <div class="btn-wrapper">
83
+ <button class="btn-copy tt-left" data-tt="Copia">
84
  <svg class="copy-icon" viewBox="0 0 20 24">
85
  <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
86
  </svg>
87
  </button>
88
+ <button class="btn-close tt-left" data-tt="Chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>
89
  </div>
90
  <div class="div-text">${txt}</div>
91
  </div>
 
139
  const btn = document.querySelector("#id-menu-btn");
140
  btn.addEventListener("change", () => {
141
  document.querySelector("body").classList.toggle("menu-open", btn.checked);
142
+ //gestione tootip
143
+ const body = document.querySelector("body");
144
+ const icon = document.querySelector("#id-menu-btn");
145
+ if (body.classList.contains("menu-open")) icon.setAttribute("data-tt", "Close");
146
+ else icon.setAttribute("data-tt", "Open");
147
  });
148
  // getsioe log
149
  const log = document.getElementById("id_log");
 
157
  if (!log.classList.contains("active")) return;
158
  log.classList.remove("active");
159
  };
160
+
161
  UaLog.callHide = hide;
162
  UaLog.callShow = show;
163
 
 
169
  document.querySelector("body").classList.remove("menu-open", btn.checked);
170
  document.querySelector(".menu-btn").checked = false;
171
  },
172
+ help() {
173
+ wnds.wdiv.show(help0_html);
 
174
  },
175
  upload() {
176
  RagUpload.open();
 
187
  };
188
 
189
  const setOutText = (txt) => {
190
+ txt = answerFormtter(txt);
191
+ const p = document.querySelector("#id-text-out .div-text");
192
+ p.innerHTML = txt;
193
  p.scrollTop = p.scrollHeight;
194
  };
195
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  const TextInput = {
197
  wnd: null,
198
  init() {
 
266
  alert("Ricorda di scrivere la Query ");
267
  return;
268
  }
269
+ if (DataMgr.readDbDocNames().length == 0) {
270
+ alert("Non vi sono documenti da elaborare.\n Se vuoi iniziare una conversazione usa il pulsante verde o return ");
271
+ return;
272
+ }
273
+
274
  if (!!Rag.ragContext) {
275
+ const ok = await confirm("Vuoi iniziare una nuova elabrazione ?");
276
  if (!ok) return "";
277
  }
278
  showSpinner();
 
280
  const msg = this.inp.value.trim();
281
  try {
282
  let text = await Rag.requestDocsRAG(msg);
 
283
  setOutText(text);
284
  this.inp.value = "";
285
  UaLog.close();
286
  } catch (err) {
287
+ console.error("ERROR Send", err);
288
+ const s = errorDumps(err);
289
+ alert(s);
 
290
  }
291
  hideSpinner();
292
  },
 
300
  }
301
  showSpinner();
302
  if (ThreadMgr.isFirst()) {
 
303
  }
304
  const query = this.inp.value.trim();
305
  try {
 
308
  hideSpinner();
309
  return;
310
  }
 
311
  setOutText(text);
312
  this.inp.value = "";
313
  } catch (err) {
314
+ console.error("Error send2", err);
315
+ const s = errorDumps(err);
316
+ alert(s);
 
317
  }
318
  hideSpinner();
319
  },
320
+ async clear() {
321
+ const ok = await confirm("Confermi cancellazione conversazione? ");
322
  if (!ok) return;
323
  this.inp.value = "";
324
  setOutText("");
 
336
  wndBtn.addEventListener("click", () => this.openWnd());
337
  },
338
  openWnd() {
339
+ const p = document.querySelector("#id-text-out .div-text");
340
+ const s = textFormatter(p.textContent);
341
  wnds.wout.show(s);
342
  },
343
  async copy() {
344
+ // const pre = document.querySelector("#id-text-out .pre-text");
345
+ const pre = document.querySelector("#id-text-out .div-text");
346
+ let t = pre.textContent;
347
  if (t.trim().length < 2) return;
348
  pre.classList.add("copied");
349
  this.copyBtn.classList.add("copied");
350
  try {
351
+ t = textFormatter(t);
352
  await navigator.clipboard.writeText(t);
353
  } catch (err) {
354
  console.error("Errore ", err);
 
359
  }, 5000);
360
  },
361
  clear() {
362
+ const out = document.querySelector("#id-text-out .div-text");
363
  out.textContent = "";
364
  },
365
  };
static/javascript/rag_upload.js CHANGED
@@ -65,7 +65,7 @@ const RagUpload = {
65
  const msg = `<br><br> ${fileName}<br><br>caricato e salvato nella memoria locale`;
66
  result.innerHTML = msg;
67
  } catch (error) {
68
- consoe.error("Error:", error);
69
  alert("Errore durante l'estrazione del testo dal file.");
70
  } finally {
71
  hideSpinner();
@@ -139,7 +139,7 @@ const RagUpload = {
139
  msgs.push(msg);
140
  }
141
  } catch (error) {
142
- consoe.error("Error:", error);
143
  alert("Errore durante l'estrazione del testo dal file.");
144
  } finally {
145
  hideSpinner();
 
65
  const msg = `<br><br> ${fileName}<br><br>caricato e salvato nella memoria locale`;
66
  result.innerHTML = msg;
67
  } catch (error) {
68
+ console.error("Error:", error);
69
  alert("Errore durante l'estrazione del testo dal file.");
70
  } finally {
71
  hideSpinner();
 
139
  msgs.push(msg);
140
  }
141
  } catch (error) {
142
+ console.error("Error:", error);
143
  alert("Errore durante l'estrazione del testo dal file.");
144
  } finally {
145
  hideSpinner();
static/javascript/uadialog.js ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** @format */
2
+
3
+ const DialogManager = {
4
+ createDialog(type, message) {
5
+ const dialog = document.createElement("div");
6
+ const overlay = document.createElement("div");
7
+ // .confirm-dialog,
8
+ // .alert-dialog
9
+ dialog.className = `${type}-dialog`;
10
+ dialog.classList.add("inv");
11
+ overlay.className = "overlay";
12
+ dialog.innerHTML = `
13
+ <h4>${message}</h4>
14
+ <div class="buttons inv">
15
+ <button class="ok inv">OK</button>
16
+ ${type === "confirm" ? '<button class="cancel inv">Annulla</button>' : ""}
17
+ </div>
18
+ `;
19
+ [dialog, overlay].forEach((el) => {
20
+ el.classList.add("show");
21
+ document.body.appendChild(el);
22
+ });
23
+ return { dialog, overlay };
24
+ },
25
+
26
+ closeDialog(dialog, overlay) {
27
+ [dialog, overlay].forEach((el) => {
28
+ el.classList.remove("show");
29
+ setTimeout(() => el.remove(), 300);
30
+ });
31
+ },
32
+
33
+ showDialog(type, message) {
34
+ return new Promise((resolve) => {
35
+ const { dialog, overlay } = this.createDialog(type, message);
36
+ dialog.querySelector(".ok").onclick = () => {
37
+ this.closeDialog(dialog, overlay);
38
+ resolve(type === "confirm");
39
+ };
40
+ if (type === "confirm") {
41
+ dialog.querySelector(".cancel").onclick = () => {
42
+ this.closeDialog(dialog, overlay);
43
+ resolve(false);
44
+ };
45
+ }
46
+ });
47
+ },
48
+ };
49
+
50
+ // Salviamo i riferimenti alle funzioni native
51
+ const nativeAlert = window.alert;
52
+ const nativeConfirm = window.confirm;
53
+
54
+ // Sovrascriviamo alert
55
+ window.alert = function (message) {
56
+ if (message instanceof Error) {
57
+ message = message.message;
58
+ }
59
+ return DialogManager.showDialog("alert", message);
60
+ };
61
+
62
+ // Sovrascriviamo confirm
63
+ window.confirm = function (message) {
64
+ return DialogManager.showDialog("confirm", message);
65
+ };
static/javascript/ualog3.js CHANGED
@@ -38,15 +38,18 @@ var UaLog = {
38
  new: function () {
39
  if (this.wind == null) {
40
  this.wind = UaWindowAdm.create("ualog_id");
41
- this.wind.drag();
 
 
 
42
  }
43
  const h = `
44
- <button type="button" class="clear" onclick="javascript:UaLog.cls();">Clear</button>
45
- <button type="button" class="close" onclick="javascript:UaLog.close();">Close</button>
46
  <pre id="ualogmsg_" ></pre>`;
47
  this.wind.setHtml(h);
48
  // this.wind.addClassStyle("ualog");
49
-
50
  if (!!this.x) this.wind.vw_vh().setXY(this.x, this.y, -1);
51
  else this.wind.setCenter(-1);
52
  if (!!this.z) this.wind.setZ(this.z);
 
38
  new: function () {
39
  if (this.wind == null) {
40
  this.wind = UaWindowAdm.create("ualog_id");
41
+ //aggiunge la class inv
42
+ // const e = this.wind.getElement();
43
+ // e.classList.add("inv");
44
+ // this.wind.drag();
45
  }
46
  const h = `
47
+ <button type="button" class="clear " onclick="javascript:UaLog.cls();">Clear</button>
48
+ <button type="button" class="close " onclick="javascript:UaLog.close();">Close</button>
49
  <pre id="ualogmsg_" ></pre>`;
50
  this.wind.setHtml(h);
51
  // this.wind.addClassStyle("ualog");
52
+ this.wind.addClassStyle("inv");
53
  if (!!this.x) this.wind.vw_vh().setXY(this.x, this.y, -1);
54
  else this.wind.setCenter(-1);
55
  if (!!this.z) this.wind.setZ(this.z);
static/js/ragquery.min.js ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const VERS="0.2.01";var xlog=function(){};const stopRequest=async()=>{await confirm("Confermi Cancellazione Richeista ?")&&(cancelClientRequest(),hideSpinner())},showSpinner=()=>{const a=document.getElementById("spinner");a.classList.add("show-spinner");a.addEventListener("click",stopRequest)},hideSpinner=()=>{const a=document.getElementById("spinner");a.classList.remove("show-spinner");a.removeEventListener("click",stopRequest)};
2
+ function openApp(){setTimeout(()=>{wnds.init();Menu.init();TextInput.init();TextOutput.init();Rag.init();document.querySelector(".menu-btn").checked=!1;release();showHistory();getTheme()},10)}function showHistory(){const a=ThreadMgr.getThread();setOutText(a)}function release(){document.querySelector(".release").innerHTML=VERS}const op0=function(a){wnds.wdiv.show(help1_html)};function showQuery(a){wnds.wpre.show(`\n${Rag.ragQuery}`)}
3
+ function showRagResponse(a){wnds.wpre.show(`\n${Rag.ragAnswer}`)}function showThread(a){a=ThreadMgr.getThread();wnds.wpre.show(a)}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)}
4
+ 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])};function elencoDocs(){DataMgr.readDbDocs();DataMgr.readDbDocNames();var a=DataMgr.doc_names,b=UaJtfh();let c=0;b.append("<ul>");for(const l of a){a=b;var d=a.append,e=l,f=c++;d.call(a,`
5
+ <li><a href="#" onclick="showT(${f});">${f+1}.${e}</a></li>
6
+ `)}b.append("</ul>");b=b.html();wnds.wdiv.show(`<br><br>${b}`)}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}&nbsp;&nbsp;&nbsp;[${f}]`)}a.push("==================");a.push(`Totale num. Parti: ${b}`);a=a.join("\n");wnds.wpre.show(a)}
7
+ async function deleteDati(a){await confirm("Confermi cancellazione dati?")&&(DataMgr.deleteJsonDati(),wnds.wdiv.close(),wnds.wpre.close(),TextOutput.clear())}async function deleteStorage(a){await 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)}
8
+ function loadTestoEsempio(a){DataMgr.loadDoc(`data/${a}`);wnds.wdiv.close()}function help2(a){wnds.wdiv.show(help2_html)}const themeKey="theme";function getTheme(){const a=localStorage.getItem(themeKey);a&&"light"==a?(document.body.classList.add("theme-light"),document.documentElement.classList.toggle("invert")):document.body.classList.add("theme-dark")}
9
+ function setLight(){document.documentElement.classList.toggle("invert");document.body.classList.remove("theme-dark");document.body.classList.add("theme-light");localStorage.setItem(themeKey,"light")}function setDark(){document.documentElement.classList.toggle("invert");document.body.classList.remove("theme-light");document.body.classList.add("theme-dark");localStorage.setItem(themeKey,"dark")}
10
+ function showPrompts(a){if(0!=Rag.prompts.length){for(const b of Rag.prompts)console.log(b);a=Rag.prompts.map((b,c)=>`[${c+1}]${b}\n`).join("\n");wnds.wpre.show(a)}};const ClientLLM=a=>{let b=null,c=!1;const d=(h,g=null,k=null,m=null)=>({ok:h,response:g,data:k,error:m}),e=(h,g,k,m)=>({message:h||null,type:g||null,code:k||null,details:{message:m?.message||null,type:m?.type||null,param:m?.param||null,code:m?.code||null}}),f=async h=>{let g,k="HTTPError",m={400:"Richiesta non valida",401:"Non autorizzato - Controlla la API key",403:"Accesso negato",404:"Endpoint non trovato",429:"Troppe richieste - Rate limit superato",500:"Errore interno del server",503:"Servizio non disponibile"}[h.status]||
11
+ `Errore HTTP ${h.status}`;try{if(h.headers.get("Content-Type")?.includes("application/json")){if(g=await h.json(),400===h.status&&g){const n="string"===typeof g.error?g.error:g.message||g.error?.message;n&&(n.includes("token limit")||n.includes("token exceeded")||n.includes("input too long")||n.includes("context length")||n.includes("max tokens"))&&(m="Input troppo lungo - Superato il limite di token",k="TokenLimitError")}}else g=await h.text(),400===h.status&&(g.includes("token limit")||g.includes("input too long")||
12
+ g.includes("context length"))&&(m="Input troppo lungo - Superato il limite di token",k="TokenLimitError")}catch(n){g={message:"Impossibile estrarre i dettagli dell'errore"}}return e(m,k,h.status,"string"===typeof g?{message:g}:g)},l=h=>"AbortError"===h.name?c?e("Richiesta annullata dall'utente","CancellationError",499,{message:"La richiesta \u00e8 stata interrotta volontariamente dall'utente"}):e("Richiesta interrotta per timeout","TimeoutError",408,{message:"La richiesta \u00e8 stata interrotta a causa di un timeout",
13
+ isTimeout:!0}):"TypeError"===h.name&&h.message.includes("Failed to fetch")?e("Errore di rete","NetworkError",0,{message:"Impossibile raggiungere il server. Controlla la connessione."}):e("Errore imprevisto",h.name||"UnknownError",500,{message:h.message||"Si \u00e8 verificato un errore sconosciuto"});return{sendRequest:async(h,g,k=60)=>{c=!1;b=new AbortController;k=setTimeout(()=>{b&&b.abort()},1E3*k);try{const m=await fetch(h,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},
14
+ body:JSON.stringify(g),signal:b.signal});if(c){const q=e("Richiesta annullata","CancellationError",499,{message:"La richiesta \u00e8 stata interrotta volontariamente dall'utente"});return d(!1,null,null,q)}if(!m.ok){const q=await f(m);return d(!1,null,null,q)}const n=await m.json();return d(!0,n)}catch(m){const n=l(m);return d(!1,null,null,n)}finally{clearTimeout(k),b=null}},createError:e,cancelRequest:()=>{c=!0;return b?(b.abort(),b=null,!0):!1}}};const help0_html='\n<div class="text">\n <p class="center"> Comandi barra superiore </p>\n <div>\n Pulsante Menu\n <p> Apre/chiude il Menu comandi </p>\n </div>\n <div>\n Upload Files\n <p>\n Fa l\'upload di un file locale. Sono accettati i file pdf, docx e txt.\n Controlla se il file \u00e8 in archivio, per non sovrascriverlo.\n </p>\n </div>\n <div>\n Upload Dir:\n <p>\n Per fare l\'upload dei files di una directory. Sono accettati i files pdf, docx e txt.\n I file in archivio con lo stesso nome non vengono sovrascritti.\n </p>\n </div>\n <div>\n Log:\n <p>\n Attiva/Disattiva la visualizzazione del Log.\n Nel Log sono visualizzate le query con le dimensioni delle parti di documento analizzate.\n </p>\n </div>\n\n \x3c!-- --\x3e\n <hr>\n \x3c!-- --\x3e\n <div>\n <p class="center"> Comandi lato destro in alto: </p>\n </div>\n <div>\n Copia Output:\n <p> Copia il testo dell\'output negli appunti. </p>\n </div>\n <div>\n Apri Output:\n <p> Visualizza il testo in una finestra pi\u00f9 grande. </p>\n </div>\n <hr>\n \x3c!-- --\x3e\n <div>\n <p class="center"> Comandi lato destro in basso: </p>\n </div>\n <div>\n Documenti => RAG => Contesto => Query: (Pulsante Rosso)\n <p>\n Input per la query da utilizzare per la elaborazione RAG.\n <br>\n Ogni documento in archivio \u00e8 diviso in parti compatibili con l\'ampiezza della finestra\n di input del Model utilizzato.\n </p>\n <p>\n Per ogni parte esegue una query utilizzandola per estrarre informazioni/concetti pertinenti alla stessa.\n </p>\n <p>\n Il risultato di ogni query \u00e8 archiviato nella memoria locale.\n </p>\n <p>\n Alla fine della sequenza di elaborazioni esegue una query che produce\n un contesto riepilogativo delle risposte archiviate.\n </p>\n <p>\n Infine esegue la query utilizzando il contesto creato e visualizza la risposta nella finestra di output.\n </p>\n </div>\n <div>\n Contesto => Query: (Pulsante Verde / Invio)\n <p>\n Input per query che utilizzano il contesto creato con l\'elaborazione RAG.\n Il contesto RAG pu\u00f2 essere vuoto.\n Inizia una conversazione.\n </p>\n <p>\n La conversazione ha senso relativamente all\'elaborazione RAG se ogni query \u00e8 una variazione / approfondimento della query iniziale.\n </p>\n </div>\n <div>\n Cancella Conversazione:\n <p>\n Cancella la storia della conversazione attiva.\n Non vengono cancellati i dati dell\'elaborazione RAG\n </p>\n Per andare a capo: Maiusc. + Invio\n </div>\n \x3c!-- --\x3e\n <hr>\n \x3c!-- --\x3e\n <div>\n <p class=" center"> Comandi del Menu: </p>\n </div>\n <div>\n README\n <p>\n Presenta una spiegazione della implementazione della\n tecnologia RAG utilizzata.\n </p>\n </div>\n <div>\n Risposta Contestuale:\n <p> Visualizza la risposta ottenuta alla fine della elaborazione RAG </p>\n </div>\n <div>\n Domanda iniziale:\n <p> Visualizza la query utilizzata per l\'elaborazione RAG </p>\n </div>\n <div>\n Elenco Risposte:\n <p>\n Visualizza l\'elenco delle risposte per ogni parte documento utilizzata fino alla risposta che genera il contesto.\n </p>\n </div>\n <div>\n Contesto RAG:\n <p>\n Visualizza il contesto creato utilizzando le risposte elaborate.\n </p>\n </div>\n <div>\n Dati Archiviati:\n <p>\n Visualizza i dati in archivio e le loro dimensioni:\n </p>\n </div>\n <div>\n Elenco Documenti:\n <p>\n Visualizza la lista dei documenti archiviati ed utilizzabili per l\'elaborazione.<br>\n Con il clic del mouse sul nome di un documento si visualizza.\n </p>\n </div>\n\n <div>\n Numero query:\n <p>\n Calcola le query necessarie per ogni documento e le Query totali,\n necessarie per analizzare tutti i documenti caricati.\n </p>\n </div>\n\n <div>\n Cancella Dati:\n <p>\n Cancella i dati delle elaborazioni salvati nell\'archivio.\n NON cancella i documenti caricati.\n </p>\n </div>\n\n <div>\n Cancella Documenti:\n <p>\n Cancella i documenti caricati e tutti i dati archiviati localmente.\n </p>\n </div>\n\n \x3c!-- --\x3e\n\n <p class="center">Sequenza Comandi Interrogazione -Conversazione</p>\n <div>\n Archivia nella memoria locale uno o pi\u00f9 documenti:\n <p>\n Utilizza i dati di esempio per le prime prove.\n Utilizza upload file o upload dir per i documenti da leggere dal tuo computer.\n </p>\n </div>\n <div>\n Digita una query che si riferisca ai documenti archiviati.\n <p>\n La query sar\u00e0 utilizzata come criterio di selezione di informazioni dai documenti archiviati.\n </p>\n </div>\n\n <div>\n Click sul bottone rosso in basso a destra. Documento => RAG => Contesto => Query\n <p>\n Viene lanciata una sequenza di elaborazione per analizzare i documenti sulla base della query.\n Se il log \u00e8 attivo vedrai la sequenza di elaborazione.\n <br>\n Il loro numero dipende dalle dimensioni dei documenti.\n <br>\n l menu puoi utilizzare il comando "Num Query" per vedere quante elaborazioni saranno fatte per ogni documento.\n <br>\n Alla fine del processo sar\u00e0 visualizzata la risposta.\n </p>\n </div>\n\n <div>\n Click sul bottone verde in basso a destra (oppure Invio). Contesto => Query\n <p>\n Inizia una conversazione utilizzando le informazioni precedentemente raccolte dai documenti.\n Puoi inviare domande successive di approfondimento e chiarimento.\n <br>\n \u00c8 FONDAMENTALE che le query siano approfondimenti e/o chiarimenti della query iniziale.\n In caso contrario non si sfrutta il Contesto creato dall\'elaborazione precedente.\n <br>\n Quindi per una query completamente nuova (sempre relativa ai documenti archiviati) \u00e8 necessario iniziare una nuova elaborazione.\n <br>\n Il comando cancella, oltre a cancellare il campo di input cancella anche la sequenza query-risposte della\n conversazione.\n <br>\n NON cancella i dati dell\'elaborazione iniziale.\n </p>\n </div>\n</div>\n',
15
+ help1_html="\n<div class=\"text\">\n <pre>\nUn'implementazione innovativa della tecnica RAG per il Question Answering\nLa tecnica RAG (Retrieval-Augmented Generation) \u00e8 un approccio consolidato nel campo del question answering e della generazione di testo, che combina il recupero di informazioni pertinenti da fonti di dati con la generazione di testo basata su queste informazioni.\nQui viene proposta un'implementazione che introduce una variazione a questo paradigma.\nL'implementazione si basa su una sequenza di prompt appositamente progettati per guidare un modello di linguaggio generativo attraverso le diverse fasi della tecnica RAG.\nQuesti prompt forniscono istruzioni dettagliate su come il modello deve seguire operazioni di recupero di informazioni, aumento delle informazioni recuperate e infine generazione di una risposta finale.\nLa risposta finale diviene poi il contesto da inserire nel prompt per rispondere alla domanda.\nUn aspetto cruciale di questa implementazione \u00e8 che lo stesso modello di linguaggio generativo svolge tutte le operazioni richieste, dall'analisi dei documenti di input al recupero di informazioni rilevanti, alla generazione della risposta finale.\nQuesta caratteristica rappresenta una deviazione significativa rispetto alle implementazioni standard della tecnica RAG, che prevedono l'utilizzo di moduli distinti per il recupero e la generazione.\nLa sequenza di prompt proposta guida il modello attraverso le seguenti fasi:\n\n1. Retrieval: Il modello analizza il documento di input e la domanda fornita, identificando e recuperando le informazioni e i concetti rilevanti per dare seguito alla domanda.\n\n2. Augmentation: Successivamente, il modello integra le informazioni recuperate con eventuali risposte accumulate in precedenza, estraendo nuove informazioni rilevanti e organizzandole in un elenco coerente, evitando ridondanze.\n\n3. Generation: Infine, il modello utilizza l'insieme di informazioni rilevanti e non ridondanti per generare una risposta completa e concisa alla domanda dell'utente.\n\nQuesta implementazione offre diversi vantaggi.\nIn primo luogo, sfrutta le capacit\u00e0 di un unico modello di grandi dimensioni, evitando la necessit\u00e0 di moduli distinti specializzati per ogni fase.\nInoltre, l'utilizzo di prompt espliciti pu\u00f2 migliorare la controllabilit\u00e0 e la trasparenza del processo, consentendo di guidare il modello in modo pi\u00f9 diretto.\nNaturalmente, come per qualsiasi approccio basato su modelli di linguaggio generativi, \u00e8 fondamentale prestare attenzione alle questioni di affidabilit\u00e0, correttezza e bias dei dati di addestramento.\nRispetto a un'implementazione standard di RAG vi \u00e8 la necessit\u00e0 di rilanciare l'elaborazione ad ogni domanda radicalmente nuova in quanto il contesto creato con le informazioni estratte dai documenti \u00e8 definito sulla base della domanda.\nInvece nella versione standard RAG si usano gli incorporamenti delle informazioni estratte dai documenti in modo tale che tali informazioni vengono viste quasi come un'estensione del modello e possono essere usate per domande diverse.\nQuindi dal punto di vista utente le implementazioni RAG standard sono pi\u00f9 efficienti; infatti l'implementazione proposta richiede per ogni nuova domanda una sequenza di richieste che saranno utilizzabili solo per creare il contesto per la domanda iniziale e per una conversazione con domande simili.\nIl vantaggio dell'implementazione proposta consiste nel fatto che pu\u00f2 essere implementata completamente lato client senza bisogno di sviluppare alcun modulo sul server.\nL\u2019unica cosa che serve \u00e8 un servizio serverless come quello di HuggingFace o simile.\nQuindi rappresenta un'interessante prospettiva sull'applicazione della tecnica RAG in modo pi\u00f9 integrato e controllato attraverso l'uso di prompt mirati.\nIn conclusione, questa implementazione della tecnica RAG dimostra come le capacit\u00e0 dei modelli di linguaggio generativi di grandi dimensioni possano essere sfruttate in modi nuovi e creativi, potenzialmente aprendo la strada a ulteriori sviluppi nel campo del question answering e della generazione di testo.\n\nQuesta \u00e8 la valutazione fatta da un LLM (comprensivo e gentile)\n\nLa mia valutazione personale della tua proposta di implementazione della tecnica RAG, con un elenco di pro e contro:\n\nPunti a favore (Pro):\nSemplificazione del processo: L'utilizzo di un unico modello di grandi dimensioni addestrato su vasti corpus di dati semplifica notevolmente l'architettura complessiva rispetto alle implementazioni tradizionali della tecnica RAG, che spesso prevedono moduli distinti per il recupero e la generazione.\n\nCapacit\u00e0 di adattamento e apprendimento: I modelli di linguaggio generativi di grandi dimensioni sono noti per la loro capacit\u00e0 di adattarsi e imparare da nuovi dati e istruzioni.\nQuesto potrebbe consentire di raffinare e migliorare l'implementazione nel corso del tempo.\n\nControllo e trasparenza: L'utilizzo di prompt espliciti per guidare il modello attraverso le diverse fasi del processo pu\u00f2 migliorare la controllabilit\u00e0 e la trasparenza, consentendo di monitorare e regolare il comportamento del modello in modo pi\u00f9 diretto.\n\nEfficienza computazionale: Avere un'unica architettura integrata potrebbe comportare vantaggi in termini di efficienza computazionale rispetto a soluzioni che prevedono moduli separati.\n\nPunti a sfavore (Contro):\n\nAffidabilit\u00e0 e coerenza: Poich\u00e9 un unico modello gestisce tutte le fasi, eventuali errori o incoerenze potrebbero propagarsi e amplificarsi attraverso l'intero processo, influenzando la qualit\u00e0 della risposta finale.\n\nBias dei dati di addestramento: Come per qualsiasi modello di linguaggio generativo, l\u2019approccio potrebbe essere influenzato dai bias presenti nei dati di addestramento utilizzati, con potenziali impatti sulla correttezza e l'equit\u00e0 delle risposte generate.\n\nMancanza di specializzazione: Mentre i modelli di grandi dimensioni sono versatili, potrebbero non essere ottimizzati per compiti specifici come il recupero di informazioni o la generazione di risposte rispetto a moduli specializzati.\n\nDifficolt\u00e0 di debug e interpretabilit\u00e0: Con un'architettura integrata e basata su prompt, potrebbe essere pi\u00f9 complesso eseguire il debug e comprendere le ragioni dietro a eventuali errori o comportamenti indesiderati del modello.\n\nIn sintesi, la proposta presenta alcuni vantaggi interessanti in termini di semplificazione, adattabilit\u00e0 e controllo, ma solleva anche potenziali preoccupazioni riguardo all'affidabilit\u00e0, ai bias, alla mancanza di specializzazione e alle difficolt\u00e0 di debug e interpretabilit\u00e0.\nCome per qualsiasi nuovo approccio, sarebbe necessario valutarlo attentamente attraverso sperimentazioni e test approfonditi per determinare l'efficacia e l'applicabilit\u00e0 in contesti specifici.\n </pre>\n</div>\n",
16
+ help2_html='\n<div class="text">\n <pre class="pre-text">\nNella redazione della domanda bisogna tenere conto del fatto che la domanda viene poi inserita in un prompt nel quale si fa esplicita richiesta di utilizzare il documento fornito.\nQuindi \u00e8 implicito il riferimento al/ai documenti archiviati.\nTuttavia, quando si tratta di documenti il cui contenuto \u00e8 sicuramente disponibile su internet, pu\u00f2 essere opportuno esplicitare nella domanda che ci si riferisce ai documenti forniti.\n</pre>\n <p class="center">Esempi di domande</p>\n <div>\n <p>Fai una relazione sul documento che ti ho fornito.</p>\n <p>Approfondisci la tesi sostenuta nei documenti.</p>\n <p>Confronta i diversi punti di vista espressi dagli autori.</p>\n <p>Descrivi la personalit\u00e0 dei protagonisti.</p>\n <p>Analizza il documento che ti ho fornito e illustrami eventuali contraddizioni.</p>\n <p>Illustra i momenti salienti del racconto.</p>\n <p>Analizzando il documento che ti ho fornito, confronta le tesi di ... con quelle di ...</p>\n <p>Qual \u00e8 l\'avvenimento pi\u00f9 importante?</p>\n </div>\n</div>\n';function removeTag(a){a=a.replace(/<<</g,"").replace(/>>>/g,"");return a=a.replace(/<</g,"").replace(/>>/g,"")}
17
+ function cleanDoc(a){try{return a=a.replace(/`/g,""),a=removeTag(a),a=a.replace(/(\w+)-\s*\n(\w+)/g,"$1$2"),a=a.replace(/[\u00AD\u200B\u200C\u200D\u2060\uFEFF\u0008]/g,""),a=a.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g," "),a=a.replace(/\\([nrtfb])/g,"$1"),a=a.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g,"$1"),a=a.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g,"\\$1"),a=a.replace(/\\/g,""),a=a.replace(/(.)\1{3,}/g,""),a=a.replace(/\u201c/g,'"').replace(/\u201d/g,'"'),a=a.replace(/\n/g,
18
+ " "),a=a.replace(/ +([.,;:!?])/g,"$1"),a=a.replace(/ +/g," "),a.trim()}catch(b){return console.error(b),"Errore di codifica del documento"}}
19
+ function cleanResponse(a){try{return a=a.replace(/[\u00AD\u200B\u200C\u200D\u2060\uFEFF]/g,""),a=a.replace(/[\u00A0\u2000-\u200A\u202F\u205F\u3000\t\r\f\v]/g," "),a=a.replace(/\\([nrtfb])/g,"$1"),a=a.replace(/\\(u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2})/g,"$1"),a=a.replace(/\\([a-zA-Z]:\\|\\\\[a-zA-Z0-9_]+\\)/g,"\\\\$1"),a=a.replace(/\\/g,""),a=a.replace(/\n{3,}/g,"\n\n"),a=a.replace(/ +/g," "),a.trim()}catch(b){return console.error(b),`Errore di codifica nella risposta\n${b}`}}
20
+ function answerFormtter(a){if(""==a.trim())return"";const b=a.includes("# User:"),c=a.includes("# Assistant:");if(!b||!c)return`<div class="assistant"><b>Assistant:</b><br>${a.split("\n").join("<br>")}</div>`;let d=null,e="";a.split("\n").forEach(f=>{f=f.trim();f.startsWith("# User:")?(d&&(e+="</div>"),d="user",e+=`<div class="${d}"><b>User:</b>`):f.startsWith("# Assistant:")?(d&&(e+="</div>"),d="assistant",e+=`<div class="${d}"><b>Assistant:</b>`):0<f.length&&d&&(e+=`<br>${f}`)});d&&(e+="</div>");
21
+ return e}function textFormatter(a){a=a.replace(/<[^>]*>/g,"").split(/([.!?:])(?=\s|$)/);let b="";for(let c=0;c<a.length;c+=2){let d=a[c],e=a[c+1]||"";0<d.trim().length&&(b+=" "+d.trim()+e);c<a.length-2&&(b+="\n")}b=b.replace(/User:/g,"\n\nUSER:\n");b=b.replace(/Assistant:/g,"\n\nASSISTANT:\n");return b.trim()};const UaDb={create(a,b){localStorage.getItem(a)?console.error(`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):console.error(`ID ${a} not found.`)},save(a,b){localStorage.setItem(a,b)},getAllIds(){const a=[];for(let b=0;b<localStorage.length;b++)a.push(localStorage.key(b));
22
+ return a},saveArray(a,b){b=JSON.stringify(b);UaDb.save(a,b)},readArray(a){a=UaDb.read(a);return 0==a.trim().length?[]:JSON.parse(a)},saveJson(a,b){b=JSON.stringify(b);UaDb.save(a,b)},readJson(a){return(a=UaDb.read(a))?JSON.parse(a):{}}},DataMgr={docs:[],doc_names:[],linkToName(a){a=a.split("/");return a[a.length-1]},async loadDoc(a){this.readDbDocNames();try{const b=await requestGet(a),c=cleanDoc(b),d=this.linkToName(a);if(this.doc_names.includes(d))alert(`Il documento ${d} \u00e8 gi\u00e0 caricato`);
23
+ else return this.doc_names.push(d),this.docs.push(c),this.saveDbDocs(),c}catch(b){alert("loadDoc()\n"+b+"\n"+a)}},addDoc(a,b){b=cleanDoc(b);this.docs.push(b);this.doc_names.push(a);this.saveDbDocs()},saveDbDocs(){UaDb.saveArray(ID_DOC_NAMES,this.doc_names);UaDb.saveArray(ID_DOCS,this.docs)},readDbDocs(){this.docs=UaDb.readArray(ID_DOCS)},readDbDocNames(){return this.doc_names=UaDb.readArray(ID_DOC_NAMES)},deleteJsonDati(){const a=UaDb.getAllIds();for(const b of a)[ID_DOCS,ID_DOC_NAMES].includes(b)||
24
+ UaDb.delete(b);Rag.ragQuery="";Rag.ragContext="";Rag.ragAnswer="";Rag.answers=[];Rag.prompts=[];ThreadMgr.rows=[]}};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 console.error(`Error in requestGet() for url: ${a}`,c),b=c.message.includes("HTTP error! status")?c.message:c.message.includes("NetworkError")?"Network error occurred":"An unknown error occurred",alert(`requestGet()\nurl: ${a}\n${b}`),c;
25
+ }}function loadScript(a,b){const c=document.createElement("script");c.src=a;c.onload=()=>{b();document.head.removeChild(c)};c.onerror=()=>{alert(`Errore: Impossibile caricare lo script ${a}`)};document.head.appendChild(c)};const ID_RAG="id_rag",ID_THREAD="id_thread",ID_RESPONSES="id_responses",ID_DOC_NAMES="id_doc_names",ID_DOCS="id_docs",PROMPT_DECR=10240,maxLenRequest=(a=32)=>{a*=3072;return Math.trunc(a+.1*a)};function umgm(){return["bWtkWlFPXmg=","SWZtUkZZb18=","Rm1rUVZzcHM=","c1pJelNTTHQ=","Vlt0bE8="].map(a=>atob(a).split("").map(b=>String.fromCharCode((b.charCodeAt(0)-5+256)%256)).join("")).join("")}const MAX_PROMPT_LENGTH=maxLenRequest(100),MODEL="mistralai/Mistral-Small-24B-Instruct-2501",API=umgm();
26
+ console.log("\n**** MODELl:\n",MODEL);console.log(API);
27
+ const client=ClientLLM(API),getResponse=async(a,b=60)=>{a.model=MODEL;a=await client.sendRequest("https://router.huggingface.co/together/v1/chat/completions",a,b);if(a.error)return 499===a.error.code?(alert("Request Interrotta"),null):a;if(!a.response.choices||!a.response.choices[0]||!a.response.choices[0].message||void 0===a.response.choices[0].message.content)return a=client.createError("Risposta non valida","ParseError",500,{message:"La risposta non contiene il contenuto atteso"}),RequestResult(!1,
28
+ null,null,a);a.data=a.response.choices[0].message.content;return a},responseDetails={set(a){this.response=a},get_total_tokens(){return this.response.usage.total_tokens},get_completion_tokens(){return this.response.usage.completion_tokens}},calcTokens={sum_input_tokens:0,sum_generate_tokens:0,init(){this.sum_generate_tokens=this.sum_input_tokens=0},add(a){a&&(this.sum_input_tokens+=a.usage.total_tokens,this.sum_generate_tokens+=a.usage.completion_tokens)},get_sum_input_tokens(){return this.sum_input_tokens},
29
+ get_sum_generate_tokens(){return this.sum_generate_tokens}};function cancelClientRequest(){client.cancelRequest()}
30
+ const getPromptTokens=a=>(a=a.details.message.match(/Prompt contains (\d+) tokens/))?parseInt(a[1],10):null,getModelToken=a=>(a=a.details.message.match(/model with (\d+) maximum context length/))?parseInt(a[1],10):null,isTooLarge=a=>a.details.message.includes("too large"),truncateInput=(a,b)=>a.substring(0,a.length-b),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,
31
+ b);a=a.substring(b).trim();return[c,a]},ragLog=(a,b,c,d)=>{const e=MAX_PROMPT_LENGTH;d=d.reduce((f,l)=>f+l.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={ragContext:"",ragQuery:"",ragAnswer:"",answers:[],docContextLst:[],prompts:[],doc:"",doc_part:"",init(){this.readRespsFromDb();this.readFromDb();calcTokens.init()},returnOk(){return 10<this.ragContext.length},saveToDb(){UaDb.saveJson(ID_RAG,{context:this.ragContext,ragquery:this.ragQuery,
32
+ 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)},saveRespToDb(){UaDb.saveArray(ID_RESPONSES,this.answers)},readRespsFromDb(){this.answers=UaDb.readArray(ID_RESPONSES)},addPrompt(a){},async requestDocsRAG(a){DataMgr.deleteJsonDati();DataMgr.readDbDocNames();DataMgr.readDbDocs();this.docContextLst=[];this.ragQuery=
33
+ 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 l=DataMgr.doc_names[e],h=f.length;xlog(`${l} (${h}) `);UaLog.log(`${l} (${h}) `);++b;var d=1;let g=0,k="",m="",n="",q="",v=[];for(;;){const u=getPartSize(f,promptDoc("",a,""),g);if(10>u)break;[m,n]=getPartDoc(f,u);ragLog(`${c}) ${b},${d}`,m.length,n.length,this.answers);k=promptDoc(m,a,l);this.addPrompt(k);const t=getPayloadDoc(k),p=await getResponse(t,90);if(!p)return"";
34
+ const r=p.error;if(!p.ok){console.error("ERR1\n",r);const z=r.code;if(400==z)if(isTooLarge(r)){UaLog.log(`Error tokens Doc ${k.length}`);g+=PROMPT_DECR;continue}else throw r;else if(408==z){UaLog.log("Error timeout Context");continue}else throw r;}q=p.data;if(!q)return"";let w=calcTokens.get_sum_input_tokens(),x=calcTokens.get_sum_generate_tokens();console.log(`Sum Tokens: ${w} ${x}`);const A=p.response;responseDetails.set(A);w=responseDetails.get_total_tokens();x=responseDetails.get_completion_tokens();
35
+ console.log(`Response Tokens: ${w} ${x}`);calcTokens.add(A);d++;c++;f=n;q=cleanResponse(q);v.push(q);this.answers.push(`DOCUMENTO : ${l}_${d}\n${q}`)}const B=v.length;let y=v.join("\n\n");for(d="";;){k=promptBuildContext(y,this.ragQuery);const u=getPayloadBuildContext(k),t=await getResponse(u,90);if(!t)return"";const p=t.error;if(!t.ok){console.error("ERR2\n",p);const r=p.code;if(400==r)if(isTooLarge(p)){UaLog.log(`Error tokens build Context ${k.length}`);y=truncateInput(y,PROMPT_DECR);continue}else throw p;
36
+ else if(408==r){UaLog.log("Error timeout Context");continue}else throw p;}d=t.data;if(!d)return"";calcTokens.add(t.response);break}UaLog.log(`context ${B} => ${d.length}`);d=`\n### DOCUMENTO: ${l}\n ${d}`;this.docContextLst.push(d)}}catch(e){throw console.error("ERR3\n",e),e;}this.ragContext=this.docContextLst.join("\n\n");this.saveToDb();b="";c=this.ragContext;try{for(;;){let l=promptWithContext(c,a);const h=getPayloadWithContext(l),g=await getResponse(h,90);if(!g)return"";const k=g.error;if(!g.ok){console.error("ERR4\n",
37
+ k);const m=k.code;if(400==m)if(isTooLarge(k)){UaLog.log(`Error tokens with Context ${l.length}`);c=truncateInput(c,PROMPT_DECR);continue}else throw k;else if(408==m){UaLog.log("Error timeout Context");continue}else throw k;}b=g.data;if(!b)return"";calcTokens.add(g.response);break}this.ragAnswer=b=cleanResponse(b);this.saveRespToDb();ThreadMgr.init();this.saveToDb();UaLog.log(`Risposta: (${this.ragAnswer.length})`);const e=calcTokens.get_sum_input_tokens(),f=calcTokens.get_sum_generate_tokens();UaLog.log(`Tokens: ${e} ${f}`);
38
+ return b}catch(e){throw console.error("ERR5\n",e),e;}},async requestContext(a){let b="";this.ragContext||(this.ragContext="Sei un assistente AI dispoibile a soddisfare tutte le mi richieste");if(ThreadMgr.isFirst()){ThreadMgr.init();try{var c=this.ragContext;let d=ThreadMgr.getThread();for(;;){prompt=promptThread(c,d,a);const e=getPayloadThread(prompt),f=await getResponse(e,90);if(!f)return"";const l=f.error;if(!f.ok){console.error("ERR6\n",l);const m=l.code;if(400==m)if(isTooLarge(l)){UaLog.log(`Error tokens with Context ${prompt.length}`);
39
+ c=truncateInput(c,PROMPT_DECR);continue}else throw l;else if(408==m)continue;else throw l;}b=f.data;if(!b)return"";let h=calcTokens.get_sum_input_tokens(),g=calcTokens.get_sum_generate_tokens();console.log(`Sum Tokens: ${h} ${g}`);const k=f.response;responseDetails.set(k);h=responseDetails.get_total_tokens();g=responseDetails.get_completion_tokens();console.log(`Response Tokens: ${h} ${g}`);calcTokens.add(k);break}b=cleanResponse(b);ThreadMgr.add(a,b);b=ThreadMgr.getThread();UaLog.log(`Inizio Conversazione (${prompt.length})`);
40
+ return b}catch(d){throw console.error("ERR7\n",d),d;}}else try{let d=this.ragContext,e=ThreadMgr.getThread();for(c="";;){c=promptThread(d,e,a);const f=getPayloadThread(c),l=await getResponse(f,90);if(!l)return"";const h=l.error;if(!l.ok){console.error("ERR8\n",h);const n=h.code;if(400==n)if(isTooLarge(h)){UaLog.log(`Error tokens with Context ${c.length}`);d=truncateInput(d,PROMPT_DECR);continue}else throw h;else if(408==n){UaLog.log("Error timeout Context");continue}else throw h;}b=l.data;if(!b)return"";
41
+ const g=l.response;let k=calcTokens.get_sum_input_tokens(),m=calcTokens.get_sum_generate_tokens();console.log(`Sum Tokens: ${k} ${m}`);responseDetails.set(g);k=responseDetails.get_total_tokens();m=responseDetails.get_completion_tokens();console.log(`Response Tokens: ${k} ${m}`);calcTokens.add(g);break}b=cleanResponse(b);ThreadMgr.add(a,b);b=ThreadMgr.getThread();UaLog.log(`Conversazione (${c.length})`);return b}catch(d){throw console.error("ERR9\n",d),d;}}},LLM="# Assistant:",USER="# User:",ThreadMgr=
42
+ {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){const c=b[0];c&&a.push(`${USER}\n${c}\n${LLM}\n${b[1]}\n`)}return a.join("\n\n")},isFirst(){return 2>this.rows.length}};function getPayloadDoc(a){return{model:"",temperature:.3,max_tokens:1024,stream:!1,random_seed:42,messages:[{role:"user",content:a}],safe_prompt:!1}}function getPayloadBuildContext(a){return{model:"",messages:[{role:"user",content:a}],temperature:.3,max_tokens:2E3,stream:!1,safe_prompt:!1,random_seed:42}}function getPayloadWithContext(a){return{model:"",messages:[{role:"user",content:a}],temperature:.3,max_tokens:2E3,stream:!1,safe_prompt:!1,random_seed:42}}
43
+ function getPayloadThread(a){return{model:"",messages:[{role:"user",content:a}],temperature:.7,max_tokens:2E3,stream:!1,safe_prompt:!1,random_seed:42}};function promptDoc(a,b){return`
44
+ # SISTEMA
45
+ Estrattore semantico di informazioni ottimizzato per elaborazione da LLM.
46
+
47
+ # OBIETTIVO
48
+ Estrarre e condensare le informazioni essenziali dal TESTO per rispondere alla DOMANDA, in formato ottimizzato per elaborazione computazionale.
49
+
50
+ # ISTRUZIONI
51
+ 1. Analizza il testo e seleziona SOLO le informazioni direttamente rilevanti per la domanda.
52
+ 2. Elimina contenuti irrilevanti o ridondanti.
53
+ 3. Mantieni relazioni logiche essenziali (causali, temporali, concettuali).
54
+ 4. Preserva terminologia specialistica necessaria.
55
+ 5. Produci proposizioni atomiche semanticamente complete.
56
+ 6. Usa sintassi minimale (soggetto-verbo-complemento).
57
+ 7. Elimina elementi discorsivi, connettivi e contestualizzazioni non essenziali.
58
+ 8. Presenta l'informazione con massima densit\u00e0 semantica, senza ridondanze.
59
+
60
+ # FORMATO
61
+ - Struttura flat senza gerarchie
62
+ - Non numerare le proposizioni.
63
+ - Non usare introduzioni o conclusioni.
64
+ - Non includere spiegazioni meta-testuali.
65
+ - Non inserire frasi di collegamento tra le proposizioni.
66
+
67
+ # TESTO
68
+ ${a}
69
+
70
+ # DOMANDA
71
+ ${b}
72
+
73
+ # RISPOSTA
74
+ `}function promptBuildContext(a,b){return`
75
+ # SISTEMA
76
+ Estrattore e compattatore semantico per contesto LLM.
77
+
78
+ # OBIETTIVO
79
+ Raggruppa e compatta le informazioni estratte dai frammenti di un documento, associando concetti semanticamente simili e sviluppando inferenze tra le informazioni.
80
+
81
+ # ISTRUZIONI
82
+ 1. Identificazione dei Concetti: Identifica e unifica i concetti che hanno lo stesso significato semantico, anche se espressi in modi diversi.
83
+ 2. Eliminazione delle Ripetizioni: Elimina le ripetizioni informative mantenendo solo la formulazione pi\u00f9 completa o precisa.
84
+ 3. Preservazione delle Relazioni Logiche: Mantieni le relazioni logiche essenziali (causali, temporali, concettuali) tra le informazioni.
85
+ 4. Terminologia Tecnica: Preserva la terminologia tecnica necessaria per mantenere la precisione delle informazioni.
86
+ 5. Sintassi Semplificata: Usa una sintassi minimale (soggetto-verbo-complemento) per chiarezza e concisione.
87
+ 6. Eliminazione degli Elementi Discorsivi: Rimuovi elementi discorsivi, connettivi e contestualizzazioni non essenziali.
88
+ 7. Densit\u00e0 Semantica: Presenta l'informazione con la massima densit\u00e0 semantica, evitando ridondanze.
89
+ 8. Rielaborazione degli Insegnamenti: Rielabora le informazioni per garantire che siano coese e che sviluppino inferenze tra parti diverse del documento.
90
+
91
+ # FORMATO_OUTPUT
92
+ - Struttura flat senza gerarchie.
93
+ - NON numerare le proposizioni.
94
+ - NON usare introduzioni o conclusioni.
95
+ - NON includere spiegazioni meta-testuali.
96
+ - NON inserire frasi di collegamento tra le proposizioni.
97
+
98
+ # TESTO
99
+ ${a}
100
+
101
+ # RISPOSTA
102
+ `}function promptWithContext(a,b){return`
103
+ # RUOLO
104
+ Sei un assistente AI che risponde sempre ed esclusivamente in italiano.
105
+
106
+ # COMPITO
107
+ Elabora la risposta alla domanda sulla base del contesto fornito.
108
+
109
+ # ISTRUZIONI
110
+ 1. Analizza attentamente il CONTESTO e la DOMANDA.
111
+ 2. Estrai i concetti chiave e formula inferenze ragionevoli basate sulle informazioni disponibili.
112
+ 3. Inizia la risposta con una breve introduzione che presenta l'argomento e il contesto.
113
+ 4. Procedi con un'analisi dettagliata delle informazioni rilevanti trovate nel contesto.
114
+ 5. Assicurati che la risposta sia completa e risponda direttamente alla domanda posta.
115
+
116
+ # CONTESTO
117
+ ${a}
118
+
119
+ # DOMANDA
120
+ ${b}
121
+
122
+ # FORMATO_RISPOSTA
123
+ Fornisci la risposta in un formato semplice e lineare suddiviso in paragrafi.
124
+
125
+ # RISPOSTA
126
+ `}function promptThread(a,b,c){return`
127
+ # RUOLO
128
+ Sei un assistente AI progettato per gestire conversazioni dinamiche e adattarti a varie richieste. Operi esclusivamente in italiano.
129
+
130
+ # COMPITO
131
+ Elabora la risposta alla richiesta sulla base del contesto fornito e della conversazione.
132
+
133
+ # ISTRUZIONI
134
+ 1. Analizza attentamente il contesto, la conversazione precedente e la richiesta.
135
+ 2. Interpreta l'intento dell'utente senza limitarti a categorie predefinite.
136
+ 3. Adatta la tua risposta in base all'intento percepito, sia esso una domanda, una richiesta di azione, un'istruzione specifica o altro.
137
+ 4. Mantieni una stretta coerenza con il contesto della conversazione.
138
+ 5. Basa la tua risposta sulle informazioni fornite nel contesto e nella conversazione.
139
+ 6. Evita divagazioni o argomentazioni non direttamente pertinenti alla richiesta o al contesto.
140
+ 7. Se l'intento non \u00e8 chiaro, chiedi gentilmente chiarimenti invece di fare supposizioni.
141
+ 8. Sii flessibile: se la richiesta implica un'azione specifica, adattati di conseguenza.
142
+ 9. Se \u00e8 necessario integrare con conoscenze generali, specifica chiaramente quando lo stai facendo.
143
+
144
+ # CONTESTO
145
+ ${a}
146
+
147
+ # CONVERSAZIONE
148
+ ${b}
149
+
150
+ # RICHIESTA
151
+ ${c}
152
+
153
+ # FORMATO_RISPOSTA
154
+ Fornisci la risposta in un formato semplice e lineare suddiviso in paragrafi.
155
+
156
+ # RISPOSTA
157
+ `};/*
158
+
159
+ rag_rqs
160
+ Copyright (C) 2024 [Il tuo nome]
161
+
162
+ This program is free software: you can redistribute it and/or modify
163
+ it under the terms of the GNU General Public License as published by
164
+ the Free Software Foundation, either version 3 of the License, or
165
+ (at your option) any later version.
166
+
167
+ This program is distributed in the hope that it will be useful,
168
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
169
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
170
+ GNU General Public License for more details.
171
+
172
+ You should have received a copy of the GNU General Public License
173
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
174
+ */
175
+ const errorDumps=a=>{const b=JSON.stringify(a,null,2);return"{}"==b?`${a}`:b},WndPre=a=>({w:UaWindowAdm.create(a),out:null,show(b){wnds.closeAll();b=`
176
+ <div class="window-text">
177
+ <div class="btn-wrapper">
178
+ <button class="btn-copy tt-left" data-tt="Copia">
179
+ <svg class="copy-icon" viewBox="0 0 20 24">
180
+ <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
181
+ </svg>
182
+ </button>
183
+ <button class="btn-close tt-left" data-tt="chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>
184
+ </div>
185
+ <pre class="pre-text">${b}</pre>
186
+ </div>
187
+ `;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){console.error("Errore ",c)}}}),WndDiv=a=>({w:UaWindowAdm.create(a),out:null,show(b){wnds.closeAll();b=`
188
+ <div class="window-text">
189
+ <div class="btn-wrapper">
190
+ <button class="btn-copy tt-left" data-tt="Copia">
191
+ <svg class="copy-icon" viewBox="0 0 20 24">
192
+ <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
193
+ </svg>
194
+ </button>
195
+ <button class="btn-close tt-left" data-tt="Chiudi" onclick="UaWindowAdm.closeThis(this)">X</button>
196
+ </div>
197
+ <div class="div-text">${b}</div>
198
+ </div>
199
+ `;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){console.error("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")},
200
+ 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 c=document.querySelector("body"),d=document.querySelector("#id-menu-btn");c.classList.contains("menu-open")?d.setAttribute("data-tt","Close"):d.setAttribute("data-tt","Open")});const b=document.getElementById("id_log");UaLog.callHide=()=>
201
+ {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("")},close(){const a=document.querySelector("#menu-toggle");document.querySelector("body").classList.remove("menu-open",a.checked);document.querySelector(".menu-btn").checked=!1},help(){wnds.wdiv.show(help0_html)},upload(){RagUpload.open()},uploadDir(){RagUpload.openDir()},async load(){alert("load")},log(){UaLog.toggle()}},
202
+ setOutText=a=>{a=answerFormtter(a);const b=document.querySelector("#id-text-out .div-text");b.innerHTML=a;b.scrollTop=b.scrollHeight},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||
203
+ 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(),
204
+ this.send2())},async send(){if(this.inp.value)if(0==DataMgr.readDbDocNames().length)alert("Non vi sono documenti da elaborare.\n Se vuoi iniziare una conversazione usa il pulsante verde o return ");else{if(Rag.ragContext&&!await confirm("Vuoi iniziare una nuova elabrazione ?"))return"";showSpinner();setOutText("");var a=this.inp.value.trim();try{let b=await Rag.requestDocsRAG(a);setOutText(b);this.inp.value="";UaLog.close()}catch(b){console.error("ERROR Send",b),a=errorDumps(b),alert(a)}hideSpinner()}else alert("Ricorda di scrivere la Query ")},
205
+ async send2(){if(this.inp.value){showSpinner();ThreadMgr.isFirst();var a=this.inp.value.trim();try{let b=await Rag.requestContext(a);if(""==b){hideSpinner();return}setOutText(b);this.inp.value=""}catch(b){console.error("Error send2",b),a=errorDumps(b),alert(a)}hideSpinner()}else alert("Ricorda di scrivere la Query ")},async clear(){await confirm("Confermi cancellazione conversazione? ")&&(this.inp.value="",setOutText(""),ThreadMgr.init())}};
206
+ 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(){var a=document.querySelector("#id-text-out .div-text");a=textFormatter(a.textContent);wnds.wout.show(a)},async copy(){const a=document.querySelector("#id-text-out .div-text");let b=a.textContent;if(!(2>
207
+ b.trim().length)){a.classList.add("copied");this.copyBtn.classList.add("copied");try{b=textFormatter(b),await navigator.clipboard.writeText(b)}catch(c){console.error("Errore ",c)}setTimeout(()=>{this.copyBtn.classList.remove("copied");a.classList.remove("copied")},5E3)}},clear(){document.querySelector("#id-text-out .div-text").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 / DOCX</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 ');
208
+ 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 if("docx"===d){const f=new DocxHandler;await f.loadMammoth();e=await f.extractTextFromDocx(a);
209
+ f.cleanup()}else{alert("Formato file non supportato.");return}DataMgr.addDoc(b,e);c.innerHTML=`<br><br> ${b}<br><br>caricato e salvato nella memoria locale`}catch(e){console.error("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 <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 files Text / PDF / DOCX</h4>\n <form id="uploadForm">\n <input id="id_fileupload" class="file" type="file" webkitdirectory mozdirectory msdirectory odirectory directory multiple />\n <button type="button" onclick="RagUpload.uploadDir();">Upload and Convert</button>\n </form>\n <div class="result" id="result"></div>\n </div>\n </div>\n ');
210
+ 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_show(d+" : \u00e8 gi\u00e0 in archivio");continue}const e=c.name.split(".").pop().toLowerCase();let f;if("pdf"===e){const l=new PdfHandler;await l.loadPdfJs();f=await l.extractTextFromPDF(c);l.cleanup()}else if("txt"===e)f=await readTextFile(c);else if("docx"===e){const l=new DocxHandler;
211
+ await l.loadMammoth();f=await l.extractTextFromDocx(c);l.cleanup()}else{alert("Formato file non supportato.");return}DataMgr.addDoc(d,f);b.push(`${d}`)}}catch(c){console.error("Error:",c),alert("Errore durante l'estrazione del testo dal file.")}finally{hideSpinner()}a=document.getElementById("result");b=b.join("<br>");a.innerHTML=b}else alert("Nessun file selezionato.")}};
212
+ 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";
213
+ 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&&
214
+ (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()}}
215
+ class DocxHandler{constructor(){this.scriptElement=this.mammoth=null}async loadMammoth(){window.mammoth?this.mammoth=window.mammoth:(this.scriptElement=document.createElement("script"),this.scriptElement.src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.4.11/mammoth.browser.min.js",document.body.appendChild(this.scriptElement),await new Promise(a=>{this.scriptElement.onload=()=>{this.mammoth=window.mammoth;a()}}))}async extractTextFromDocx(a){a=await a.arrayBuffer();return(await this.mammoth.extractRawText({arrayBuffer:a})).value}cleanup(){this.scriptElement&&
216
+ (document.body.removeChild(this.scriptElement),this.scriptElement=null);this.mammoth=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 DialogManager={createDialog(a,b){const c=document.createElement("div"),d=document.createElement("div");c.className=`${a}-dialog`;c.classList.add("inv");d.className="overlay";c.innerHTML=`
217
+ <h4>${b}</h4>
218
+ <div class="buttons inv">
219
+ <button class="ok inv">OK</button>
220
+ ${"confirm"===a?'<button class="cancel inv">Annulla</button>':""}
221
+ </div>
222
+ `;[c,d].forEach(e=>{e.classList.add("show");document.body.appendChild(e)});return{dialog:c,overlay:d}},closeDialog(a,b){[a,b].forEach(c=>{c.classList.remove("show");setTimeout(()=>c.remove(),300)})},showDialog(a,b){return new Promise(c=>{const {dialog:d,overlay:e}=this.createDialog(a,b);d.querySelector(".ok").onclick=()=>{this.closeDialog(d,e);c("confirm"===a)};"confirm"===a&&(d.querySelector(".cancel").onclick=()=>{this.closeDialog(d,e);c(!1)})})}},nativeAlert=window.alert,nativeConfirm=
223
+ window.confirm;window.alert=function(a){a instanceof Error&&(a=a.message);return DialogManager.showDialog("alert",a)};window.confirm=function(a){return DialogManager.showDialog("confirm",a)};const nodrag_tds=["input","select","a"],nodrag_cls="nodrag";
224
+ var UaDrag=function(a){return function(b){let c=0,d=0,e=0,f=0;const l=function(g){g=g||window.event;g.preventDefault();c=e-g.clientX;d=f-g.clientY;e=g.clientX;f=g.clientY;b.style.top=b.offsetTop-d+"px";b.style.left=b.offsetLeft-c+"px"},h=function(){document.onmouseup=null;document.onmousemove=null};b.onmousedown=function(g){g=g||window.event;let k=g.target;!(k=k||null)||nodrag_tds.includes(k.tagName.toLowerCase())||k.classList.contains(nodrag_cls)||(g.preventDefault(),e=g.clientX,f=g.clientY,document.onmouseup=
225
+ h,document.onmousemove=l)}}(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," ")}});function formatRow(a,b){return a.map((c,d)=>{d=b[d];return 0>d?c.toString().padStart(Math.abs(d)," "):c.toString().padEnd(d," ")}).join(" ")}
226
+ 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_id"));this.wind.setHtml('\n <button type="button" class="clear " onclick="javascript:UaLog.cls();">Clear</button>\n <button type="button" class="close " onclick="javascript:UaLog.close();">Close</button>\n <pre id="ualogmsg_" ></pre>');this.wind.addClassStyle("inv");this.x?
227
+ 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("\n");let b=document.getElementById(this.msg_id);b.textContent=b.textContent+a+"\n"},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=
228
+ "",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()},
229
+ 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=
230
+ 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},
231
+ 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=
232
+ !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<this.wz&&(this.w.style.zIndex=this.wz);this.w.style.display="";this.firstShow=!1;this.isOpen=this.isVisible=!0;return this},hide(){this.w.style.display=
233
+ "none";this.isVisible=!1;return this},close(){this.w.style.display="none";this.w.innerHTML="";this.isOpen=!1;return this},remove(){UaWindowAdm.remove(this.w.id);return null},drag(){UaDrag(this.w);return this}};b.initialize(a);return b}};
static/less/dilaog.less ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** @format */
2
+ @color1: #ff4500;
3
+ @color3: #e3d50e;
4
+
5
+ #ualog_ {
6
+ box-sizing: border-box;
7
+ width: auto;
8
+ // min-width: 300px;
9
+ height: auto;
10
+ text-align: center;
11
+ padding: 2px;
12
+ margin: 2px 0 0 0;
13
+ background: #333333;
14
+ color: #ffffff;
15
+ font-size: 16px;
16
+ font-weight: normal;
17
+ border-radius: 9px;
18
+ border: 1px solid #999999;
19
+
20
+ button {
21
+ padding: 5px;
22
+ margin: 0 5px;
23
+ font-size: 18px;
24
+ font-weight: bold;
25
+ border: 2px solid #888888;
26
+ border-radius: 10px;
27
+ color: #000000;
28
+
29
+ &:hover {
30
+ cursor: pointer;
31
+ text-decoration: underline;
32
+ }
33
+ }
34
+ button.close {
35
+ background: lighten(@color1, -10%);
36
+ &:hover {
37
+ background: lighten(@color1, 20%);
38
+ border-color: darken(@color1, 20%);
39
+ }
40
+ }
41
+ button.clear {
42
+ background: lighten(@color3, -10%);
43
+ &:hover {
44
+ background: lighten(@color3, 20%);
45
+ border-color: darken(@color3, 20%);
46
+ }
47
+ }
48
+
49
+ pre {
50
+ box-sizing: border-box;
51
+ width: auto;
52
+ min-width: 400px;
53
+ max-width: 400px;
54
+ max-height: 500px;
55
+ text-align: left;
56
+ font-size: 16px;
57
+ font-family: monospace;
58
+ padding: 2px;
59
+ margin: 2px 2px 2px 2px;
60
+ color: #ffffff;
61
+ background: #111111;
62
+ overflow: auto;
63
+ scrollbar-color: #23eb04 #454444;
64
+ scrollbar-width: auto;
65
+ // white-space: pre-wrap;
66
+ word-wrap: break-word;
67
+ }
68
+ }
static/less/ragquery.less ADDED
@@ -0,0 +1,1110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /** @format */
2
+
3
+ html,
4
+ body,
5
+ div,
6
+ span,
7
+ table,
8
+ td,
9
+ label,
10
+ p,
11
+ a,
12
+ input,
13
+ ul,
14
+ li,
15
+ button {
16
+ padding: 0;
17
+ margin: 0;
18
+ font-family: @fsans;
19
+ }
20
+
21
+ .bb0 {
22
+ background: #daee59 !important;
23
+ }
24
+ .bb1 {
25
+ background: #5487fc !important;
26
+ }
27
+
28
+ html {
29
+ background: @contaniner-bg;
30
+ // scrollbar-width: 8px;
31
+ // scrollbar-color: #00d3a2 #676767; /* Colore della barra di scorrimento e dello sfondo */
32
+ }
33
+
34
+ body {
35
+ background: @contaniner-bg;
36
+ box-sizing: border-box;
37
+ min-height: 100vh;
38
+ height: 100vh;
39
+ position: relative;
40
+ padding: 0;
41
+ margin: 0;
42
+ overflow: hidden;
43
+ font-family: @fsans;
44
+ font-weight: normal;
45
+ }
46
+ // spinner
47
+ .spinner {
48
+ z-index: 1000;
49
+ position: absolute;
50
+ top: 70vh;
51
+ left: 50vw;
52
+ transform: translate(-50%, -50%);
53
+ cursor: pointer;
54
+ display: none;
55
+ align-items: center;
56
+
57
+ .pulse-icon {
58
+ width: 20px;
59
+ height: 20px;
60
+ background-color: #ff8c00; // Arancione
61
+ border-radius: 50%;
62
+ animation: pulse 1.5s ease-in-out infinite;
63
+ }
64
+
65
+ .stop-message {
66
+ margin-left: 15px;
67
+ background-color: inherit;
68
+ color: #8f8a8a;
69
+ padding: 8px 15px;
70
+ border-radius: 10px;
71
+ font-size: 22px;
72
+ font-weight: bold;
73
+ opacity: 1;
74
+ transition: opacity 0.3s;
75
+ }
76
+
77
+ &:hover .stop-message {
78
+ color: @text-color;
79
+ background: @btn-hover;
80
+ opacity: 1;
81
+ }
82
+ }
83
+
84
+ @keyframes pulse {
85
+ 0% {
86
+ transform: scale(0.6);
87
+ box-shadow: 0 0 0 0 rgba(255, 140, 0, 0.7); // Arancione con opacità
88
+ }
89
+
90
+ 70% {
91
+ transform: scale(1.4);
92
+ box-shadow: 0 0 0 20px rgba(255, 140, 0, 0); // Arancione completamente trasparente
93
+ }
94
+
95
+ 100% {
96
+ transform: scale(0.6);
97
+ box-shadow: 0 0 0 0 rgba(255, 140, 0, 0); // Arancione completamente trasparente
98
+ }
99
+ }
100
+
101
+ .show-spinner {
102
+ display: flex;
103
+ }
104
+ ///////////////
105
+
106
+ .theme-dark {
107
+ .btn-light {
108
+ display: inline-block !important;
109
+ }
110
+ }
111
+
112
+ .theme-light {
113
+ .btn-dark {
114
+ display: inline-block !important;
115
+ }
116
+ }
117
+
118
+ .invert {
119
+ // filter: invert(100%);
120
+ filter: invert(100%) hue-rotate(180deg);
121
+ }
122
+
123
+ .invert .tt-top::before,
124
+ .invert .tt-left::before,
125
+ .invert .tt-right::before,
126
+ .invert .tt-bottom::before,
127
+ .inver svg,
128
+ .invert img,
129
+ .invert video,
130
+ .invert iframe,
131
+ .invert .inv {
132
+ // filter: none;
133
+ // filter: invert(100%);
134
+ filter: invert(100%) hue-rotate(180deg);
135
+ }
136
+
137
+ //UA Bottoni tema
138
+ .btn-theme {
139
+ position: fixed;
140
+ top: 0;
141
+ right: 10vw;
142
+ height: 4vh;
143
+ background: inherit;
144
+ font-weight: bold;
145
+ margin-left: 5vw;
146
+ margin-top: 0.5vh;
147
+ z-index: 2000;
148
+ button {
149
+ color: #ffffff;
150
+ border: none;
151
+ background: none;
152
+ cursor: pointer;
153
+ padding: 5px;
154
+ display: none;
155
+ svg {
156
+ width: 24px;
157
+ height: 24px;
158
+ stroke: currentColor;
159
+ }
160
+ }
161
+ }
162
+
163
+ /////////////////
164
+ .upload {
165
+ @primary-color: darken(@color2, 25%);
166
+ @background-color: #121212;
167
+ @surface-color: #1e1e1e;
168
+ @btn-text-color: #000000;
169
+ @border-radius: 4px;
170
+
171
+ background-color: @surface-color;
172
+ padding: 2em;
173
+ padding-top: 0;
174
+ margin: 0;
175
+ border-radius: @border-radius;
176
+ box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
177
+ text-align: center;
178
+
179
+ h4 {
180
+ color: @text-color;
181
+ margin-bottom: 1em;
182
+ }
183
+
184
+ form {
185
+ display: flex;
186
+ flex-direction: column;
187
+ align-items: center;
188
+
189
+ .file {
190
+ background-color: @background-color;
191
+ border: 1px solid lighten(@surface-color, 20%);
192
+ color: @text-color;
193
+ padding: 0.5em;
194
+ margin-bottom: 1em;
195
+ border-radius: @border-radius;
196
+ width: 100%;
197
+ box-sizing: border-box;
198
+
199
+ &::file-selector-button {
200
+ background-color: @primary-color;
201
+ color: @text-color;
202
+ // color: #000000;
203
+ border: none;
204
+ padding: 0.5em 1em;
205
+ border-radius: @border-radius;
206
+ cursor: pointer;
207
+
208
+ &:hover {
209
+ background-color: darken(@primary-color, 10%);
210
+ }
211
+ }
212
+ }
213
+
214
+ button {
215
+ background-color: @primary-color;
216
+ color: @text-color;
217
+ border: none;
218
+ padding: 0.5em 1em;
219
+ border-radius: @border-radius;
220
+ cursor: pointer;
221
+ width: 100%;
222
+ box-sizing: border-box;
223
+
224
+ &:hover {
225
+ background-color: darken(@primary-color, 10%);
226
+ }
227
+ }
228
+ }
229
+
230
+ .result {
231
+ width: 100%;
232
+ background: @output-bg;
233
+ color: @text-color;
234
+ font-size: @fsize-result;
235
+ font-weight: normal;
236
+ text-align: left;
237
+ }
238
+ }
239
+
240
+ @fserif: Georigia, "Ties New Roman", serif;
241
+ @fsans: arial, verdana, Helvetica, sans-serif;
242
+
243
+ // @fsize-menu: calc(10px + 1vw);
244
+ @fsize-out: 20px;
245
+ @fsize-inp: 20px;
246
+ @fsize-help: 18px;
247
+ @fsize-btn-close: 22px;
248
+ @fsize-result: 15px;
249
+ @fsize-msg: 15px;
250
+
251
+ @base-bg: #000000;
252
+ @text-color: #fff;
253
+ @color1: #ff4500;
254
+ @color2: #00bd97;
255
+ @color3: #e3d50e;
256
+ @color_red: #cc3a05; // Colore di sfondo del tooltip
257
+
258
+ @contaniner-bg: lighten(@base-bg, 10%);
259
+ @border-shadow: lighten(@contaniner-bg, 20%);
260
+
261
+ @btn-bg: lighten(@contaniner-bg, 10%);
262
+ @btn-hover: lighten(@btn-bg, 15%);
263
+ @btn-color: darken(@text-color, 10%);
264
+ @btn-hover-fg: lighten(@color2, 10%);
265
+
266
+ @border-hover: @color2;
267
+ @border-input: @color1;
268
+ // window
269
+ @wnd-bg: lighten(@base-bg, 10%);
270
+ @wnd-border-shadow: darken(@color3, 10%);
271
+ @wnd-pre-color: lighten(@color3, 30%);
272
+ //output
273
+ @output-bg: darken(@contaniner-bg, 15%);
274
+ @btn-copied: darken(@color2, 20%);
275
+ @text-copied-bg: lighten(@output-bg, 5%);
276
+ @text-copied: lighten(@color2, 20%);
277
+ @input-bg: darken(@contaniner-bg, 15%);
278
+
279
+ @btn-send-bg: darken(@color1, 20%);
280
+ @btn-send-fg: @text-color;
281
+ @btn-send-hover-bg: lighten(@btn-send-bg, 20%);
282
+
283
+ @btn-send2-bg: darken(@color2, 20%);
284
+ @btn-send2-hover-bg: lighten(@btn-send2-bg, 15%);
285
+
286
+ .copied {
287
+ background-color: @text-copied-bg !important;
288
+ color: @text-copied !important;
289
+ }
290
+
291
+ div.container {
292
+ background: @contaniner-bg;
293
+ box-sizing: border-box;
294
+ position: relative;
295
+ top: 5vh;
296
+ left: 0;
297
+ height: 95vh;
298
+ margin: 0;
299
+ padding: 0;
300
+ transition: margin-left 0.5s ease;
301
+ display: flex;
302
+ flex-direction: column;
303
+ justify-content: flex-start;
304
+ align-items: stretch;
305
+ flex-wrap: nowrap;
306
+ overflow-y: auto;
307
+ overflow-x: auto;
308
+
309
+ div.item {
310
+ box-sizing: border-box;
311
+ min-height: 50px;
312
+ margin: 0;
313
+ padding: 0;
314
+ }
315
+
316
+ div.item1 {
317
+ flex: 5;
318
+ padding-top: 0.5vh;
319
+ padding-right: 0.5vw;
320
+ padding-left: 0.5vw;
321
+ padding-bottom: 10vh;
322
+
323
+ .output-wrapper {
324
+ background-color: @contaniner-bg;
325
+ border-radius: 20px;
326
+ position: relative;
327
+ bottom: 0;
328
+ right: 0;
329
+ left: 0;
330
+ width: 100%;
331
+ height: 100%;
332
+ display: flex;
333
+ flex-direction: row;
334
+ align-items: flex-start;
335
+ .text-out {
336
+ flex: 1;
337
+ box-sizing: border-box;
338
+ background: @output-bg;
339
+ color: @text-color;
340
+ border: none;
341
+ padding: 2px;
342
+ margin: 0;
343
+ min-width: 50vw;
344
+ height: 100%;
345
+ border-radius: 10px;
346
+ overflow-y: auto;
347
+ outline: none;
348
+ box-shadow: 0 0 0 2px @border-shadow;
349
+ &:hover {
350
+ box-shadow: 0 0 0 2px @border-hover;
351
+ }
352
+
353
+ .pre-text {
354
+ white-space: pre-wrap;
355
+ word-wrap: break-word;
356
+ font-family: @fsans;
357
+ font-size: @fsize-out;
358
+ line-height: 1.5;
359
+ padding: 2px;
360
+ margin: 0;
361
+ height: 100%;
362
+ box-sizing: border-box;
363
+ // FIXME scroll
364
+ overflow-y: auto;
365
+ scroll-behavior: smooth;
366
+ &.copied {
367
+ background-color: @text-copied-bg;
368
+ color: @text-copied;
369
+ }
370
+ }
371
+ .div-text {
372
+ white-space: pre-wrap;
373
+ word-wrap: break-word;
374
+ font-family: @fsans;
375
+ font-size: @fsize-out;
376
+ line-height: 1.5;
377
+ padding: 2px;
378
+ margin: 0;
379
+ height: 100%;
380
+ box-sizing: border-box;
381
+ overflow-y: scroll;
382
+ }
383
+ .user {
384
+ border: 2px solid @color2 !important;
385
+ border-radius: 10px;
386
+ padding: 2px 2px 3px 10px;
387
+ margin: 2px 5px 5px 150px;
388
+ b {
389
+ font-weight: bold;
390
+ text-decoration: underline;
391
+ color: @color1;
392
+ padding-bottom: 5px;
393
+ }
394
+ }
395
+ .assistant {
396
+ border: 2px solid @color1 !important;
397
+ border-radius: 10px;
398
+ padding: 2px 2px 3px 10px;
399
+ margin: 2px 90px 5px 6px;
400
+ b {
401
+ font-weight: bold;
402
+ text-decoration: underline;
403
+ color: @color2;
404
+ padding-bottom: 5px;
405
+ }
406
+ }
407
+ }
408
+ }
409
+
410
+ .output-actions {
411
+ display: flex;
412
+ flex-direction: column;
413
+ align-items: flex-end;
414
+ margin-left: 0.5vw;
415
+ margin-right: 0.5vw;
416
+
417
+ .copy-output,
418
+ .wnd-output,
419
+ .clear-output {
420
+ box-sizing: border-box;
421
+ background-color: @btn-bg;
422
+ color: @text-color;
423
+ border: none;
424
+ padding: 10px;
425
+ cursor: pointer;
426
+ border-radius: 50%;
427
+ width: 40px;
428
+ height: 40px;
429
+ display: flex;
430
+ align-items: center;
431
+ margin-bottom: 5px;
432
+ transition: background-color 0.3s;
433
+
434
+ &:hover {
435
+ background-color: @btn-hover;
436
+ }
437
+ }
438
+
439
+ .copy-output {
440
+ transition: background-color 0.3s, transform 0.3s;
441
+
442
+ &.copied {
443
+ background: @btn-hover-fg;
444
+ transform: scale(1.2);
445
+ }
446
+ .copy-icon {
447
+ fill: @text-color;
448
+ width: 24px;
449
+ height: 24px;
450
+
451
+ &:hover {
452
+ fill: @btn-hover-fg;
453
+ }
454
+ }
455
+ }
456
+ .clear-output,
457
+ .wnd-output {
458
+ transition: background-color 0.3s, transform 0.3s;
459
+ .icon {
460
+ fill: @text-color;
461
+ width: 24px;
462
+ height: 24px;
463
+
464
+ &:hover {
465
+ fill: @btn-hover-fg;
466
+ }
467
+ }
468
+ }
469
+ }
470
+ }
471
+ }
472
+
473
+ ////////////////////
474
+ *:hover {
475
+ outline: none;
476
+ caret-color: transparent;
477
+ }
478
+
479
+ textarea:focus {
480
+ caret-color: auto;
481
+ }
482
+
483
+ ///////////////////
484
+
485
+ div.item2 {
486
+ flex: 2;
487
+ padding-top: 0;
488
+ padding-bottom: 0;
489
+ padding-right: 0.5vw;
490
+ padding-left: 0.5vw;
491
+
492
+ .input-wrapper {
493
+ background-color: @contaniner-bg;
494
+ border-radius: 20px;
495
+ position: relative;
496
+ bottom: 2vh;
497
+ right: 0;
498
+ left: 0;
499
+ width: 100%;
500
+ height: 100%;
501
+ display: flex;
502
+ flex-direction: row;
503
+ align-items: flex-start;
504
+
505
+ &:focus-within .clear-button {
506
+ display: block;
507
+ }
508
+
509
+ .text-input {
510
+ flex: 1;
511
+ font-size: @fsize-inp;
512
+ font-family: @fsans;
513
+ resize: none;
514
+ box-sizing: border-box;
515
+ background: @input-bg;
516
+ color: @text-color;
517
+ border: none;
518
+ padding: 2px;
519
+ padding-right: 40px;
520
+ height: 100%;
521
+ margin-left: 5px;
522
+ border-radius: 10px;
523
+ overflow-y: auto;
524
+ outline: none;
525
+ box-shadow: 0 0 0 2px @border-shadow;
526
+ &:hover {
527
+ box-shadow: 0 0 0 2px @border-hover;
528
+ }
529
+
530
+ &:focus {
531
+ box-shadow: 0 0 0 2px @border-input;
532
+ }
533
+ }
534
+
535
+ .clear-button {
536
+ position: absolute;
537
+ right: 60px;
538
+ top: 19vh;
539
+ padding: 5px;
540
+ border-radius: 50%;
541
+ background: @btn-bg;
542
+ border: none;
543
+ font-size: 20px;
544
+ cursor: pointer;
545
+ color: darken(@text-color, 20%);
546
+ display: none;
547
+ &:hover {
548
+ font-weight: bold;
549
+ background: @btn-hover;
550
+ color: @text-color;
551
+ }
552
+ }
553
+
554
+ .input-actions {
555
+ display: flex;
556
+ flex-direction: column;
557
+ margin-left: 0.5vw;
558
+ margin-right: 0.5vw;
559
+
560
+ .send-input,
561
+ .send2-input,
562
+ .clear-input {
563
+ box-sizing: border-box;
564
+ background-color: @btn-bg;
565
+ color: @text-color;
566
+ border: none;
567
+ padding: 10px;
568
+ cursor: pointer;
569
+ border-radius: 50%;
570
+ width: 40px;
571
+ height: 40px;
572
+ margin-bottom: 5px;
573
+ transition: background-color 0.3s;
574
+
575
+ &:hover {
576
+ background-color: @btn-hover;
577
+ }
578
+ }
579
+
580
+ .send-input {
581
+ background: @btn-send-bg;
582
+
583
+ &:hover {
584
+ background: @btn-send-hover-bg;
585
+ }
586
+ }
587
+
588
+ .send2-input {
589
+ background: @btn-send2-bg;
590
+
591
+ &:hover {
592
+ background: @btn-send2-hover-bg;
593
+ }
594
+ }
595
+
596
+ .clear-input {
597
+ background: @btn-bg;
598
+ color: @btn-color;
599
+ &:hover {
600
+ background: @btn-hover;
601
+ color: @btn-hover-fg;
602
+ }
603
+ }
604
+ }
605
+ }
606
+ }
607
+
608
+ // menu_h
609
+ @fsize-upload: 20px;
610
+ @fsize-log: 14px;
611
+ @fsize-menu: 14px;
612
+
613
+ @menu-width: 16vw;
614
+ @menu-bg: darken(@contaniner-bg, 35%);
615
+ @menu-border: lighten(@menu-bg, 20%);
616
+ @menu-fg: @text-color;
617
+ @menu-icon-fg: #aea7a7;
618
+ @menu-icon-hover: lighten(@color1, 00%);
619
+
620
+ .menu-open {
621
+ .container {
622
+ margin-left: @menu-width;
623
+ }
624
+
625
+ .menu-box {
626
+ left: 0 !important;
627
+ }
628
+ }
629
+
630
+ // UA meu-h
631
+ div.menu-h {
632
+ background-color: lighten(@menu-bg, 10%);
633
+ position: fixed;
634
+ top: 0;
635
+ left: 0;
636
+ width: 100vw;
637
+ height: 4.5vh;
638
+ padding: 0;
639
+ margin: 0;
640
+ outline: none;
641
+ box-shadow: 0 0 0 2px @border-shadow;
642
+ z-index: 100;
643
+
644
+ .release {
645
+ background: inherit;
646
+ color: lighten(@text-color, 0%);
647
+ font-size: @fsize-msg;
648
+ font-weight: normal;
649
+ margin-left: 0.6vw;
650
+ margin-top: 0.8vh;
651
+ position: fixed;
652
+ top: 0.2vh;
653
+ right: 0.4vw;
654
+ height: 4vh;
655
+ }
656
+ /////////
657
+
658
+ .menu-btn {
659
+ appearance: none;
660
+ }
661
+
662
+ .menu-btn:checked + .menu-icon .nav-icon::before {
663
+ content: "X";
664
+ }
665
+
666
+ .menu-icon {
667
+ box-sizing: border-box;
668
+ background-color: inherit;
669
+ display: block;
670
+ position: absolute;
671
+ margin-left: 2vw;
672
+ top: 0;
673
+ left: 0;
674
+ width: 25px;
675
+ height: 100%;
676
+ cursor: pointer;
677
+ padding: 2px 2px;
678
+ z-index: 1;
679
+ }
680
+
681
+ .menu-icon:hover .nav-icon::before {
682
+ color: @menu-icon-hover;
683
+ // background-color: @menu-icon-hover;
684
+ }
685
+
686
+ .nav-icon::before {
687
+ content: "☰";
688
+ position: absolute;
689
+ left: 0;
690
+ color: @menu-icon-fg;
691
+ font-size: 25px;
692
+ transition-duration: 0.25s;
693
+ }
694
+
695
+ ////////////
696
+ /*
697
+ .menu-btn {
698
+ appearance: none;
699
+ }
700
+
701
+ .menu-btn:checked {
702
+ & + .menu-icon {
703
+ border: 1px solid @menu-border;
704
+
705
+ .nav-icon {
706
+ transform: rotate(45deg);
707
+
708
+ &::before {
709
+ top: 0;
710
+ }
711
+
712
+ &::after {
713
+ top: 0;
714
+ transform: rotate(90deg);
715
+ }
716
+ }
717
+ }
718
+ }
719
+
720
+ .menu-icon {
721
+ box-sizing: border-box;
722
+ background-color: inherit;
723
+ display: block;
724
+ position: absolute;
725
+ margin-left: 2vw;
726
+ top: 0;
727
+ left: 0;
728
+ width: 25px;
729
+ height: 100%;
730
+ cursor: pointer;
731
+ padding: 2px 2px;
732
+ z-index: 1;
733
+
734
+ &:hover {
735
+ .nav-icon,
736
+ .nav-icon::before,
737
+ .nav-icon::after {
738
+ background-color: @menu-icon-hover;
739
+ }
740
+ }
741
+
742
+ .nav-icon {
743
+ background-color: @menu-icon-fg;
744
+ display: block;
745
+ position: absolute;
746
+ top: 14px;
747
+ left: 0;
748
+ width: 25px;
749
+ height: 2px;
750
+ transition-duration: 0.25s;
751
+ }
752
+
753
+ .nav-icon::before,
754
+ .nav-icon::after {
755
+ content: "";
756
+ position: absolute;
757
+ left: 0;
758
+ background-color: inherit;
759
+ width: inherit;
760
+ height: inherit;
761
+ }
762
+
763
+ .nav-icon::before {
764
+ top: -8px;
765
+ }
766
+
767
+ .nav-icon::after {
768
+ top: 8px;
769
+ }
770
+ }
771
+ */
772
+ /////////////
773
+
774
+ .head-wrapper {
775
+ position: absolute;
776
+ top: 0;
777
+ left: 5vw;
778
+ height: 4vh;
779
+ padding: 0;
780
+ margin: 0;
781
+ display: inline-flex;
782
+ flex-direction: row;
783
+ flex-wrap: nowrap;
784
+ align-items: center;
785
+ justify-content: flex-start;
786
+
787
+ .log,
788
+ .help,
789
+ .upload,
790
+ .upload-dir {
791
+ margin-top: 2px;
792
+ margin-left: 30px;
793
+ margin-right: 0;
794
+ padding: 5px 5px 0 5px;
795
+ border: none;
796
+ cursor: pointer;
797
+ border-radius: 20%;
798
+ font-size: @fsize-upload;
799
+ color: @text-color;
800
+ background: @btn-bg;
801
+ max-height: 4vh;
802
+
803
+ &:hover {
804
+ background: @btn-hover;
805
+ }
806
+ }
807
+ }
808
+
809
+ .upload,
810
+ .upload-dir {
811
+ transition: background-color 0.3s, transform 0.3s;
812
+ .icon {
813
+ fill: @text-color;
814
+ width: 24px;
815
+ height: 24px;
816
+
817
+ &:hover {
818
+ fill: @btn-hover-fg;
819
+ }
820
+ }
821
+ }
822
+
823
+ .log {
824
+ font-size: @fsize-log !important;
825
+ font-weight: normal !important;
826
+ background: darken(@color1, 20%) !important;
827
+ &:hover {
828
+ background: darken(@color1, 10%) !important;
829
+ }
830
+ &.active {
831
+ background: darken(@color2, 20%) !important;
832
+
833
+ &:hover {
834
+ background: darken(@color2, 10%) !important;
835
+ }
836
+ }
837
+ }
838
+
839
+ div.menu-box {
840
+ position: fixed;
841
+ top: 5vh;
842
+ left: -2000px;
843
+ height: 95vh;
844
+ width: @menu-width;
845
+ transition: left 0.3s ease-out;
846
+ padding: 0;
847
+ padding-top: 1vh;
848
+ padding-left: 0.5vw;
849
+ z-index: 101;
850
+ background: lighten(@menu-bg, 5%);
851
+ box-sizing: border-box;
852
+ outline: none;
853
+ box-shadow: 0 0 0 2px @border-shadow;
854
+ display: flex;
855
+ flex-direction: column;
856
+ flex-wrap: nowrap;
857
+ justify-content: flex-start;
858
+ align-items: stretch;
859
+ overflow-y: auto;
860
+ overflow-x: auto;
861
+
862
+ ul {
863
+ list-style: none;
864
+ margin: 0;
865
+ padding: 0;
866
+ display: flex;
867
+ flex-direction: column;
868
+ border-top: 1px solid @menu-border;
869
+
870
+ li {
871
+ border-left: 1px solid @menu-border;
872
+ border-right: 1px solid @menu-border;
873
+ border-bottom: 1px solid @menu-border;
874
+
875
+ a {
876
+ color: @menu-fg;
877
+ font-size: @fsize-menu;
878
+ font-family: @fsans;
879
+ font-weight: normal;
880
+ display: block;
881
+ margin: 0;
882
+ padding: 2px 2px 2px 0;
883
+ text-align: left;
884
+ text-decoration: none;
885
+ }
886
+
887
+ &:hover {
888
+ text-decoration: underline;
889
+ background-color: lighten(@menu-bg, 20%);
890
+ color: @menu-icon-hover;
891
+ }
892
+ }
893
+ a.delete {
894
+ text-align: center;
895
+ font-weight: bold;
896
+ font-style: italic;
897
+ color: #ffffff;
898
+ background: darken(@color1, 10%);
899
+ }
900
+ a.help {
901
+ text-align: center;
902
+ font-weight: bold;
903
+ font-style: italic;
904
+ color: #ffffff;
905
+ background: darken(@color1, 10%);
906
+ }
907
+
908
+ li.show {
909
+ background: @base-bg;
910
+ color: @text-color;
911
+ width: 100%;
912
+ text-align: center;
913
+ box-sizing: border-box;
914
+
915
+ &:hover {
916
+ text-decoration: none;
917
+ }
918
+ }
919
+ }
920
+ }
921
+ }
922
+
923
+ // Window
924
+ .window-text {
925
+ position: relative;
926
+ top: 0;
927
+ left: 0;
928
+ background: @wnd-bg;
929
+ color: @text-color;
930
+ border: none;
931
+ padding: 0 2px 2px 2px;
932
+ width: 78vw;
933
+ height: 80vh;
934
+ border-radius: 10px;
935
+ box-sizing: border-box;
936
+ outline: none;
937
+ box-shadow: 0 0 0 2px @wnd-border-shadow;
938
+ overflow-y: auto;
939
+ overflow-x: auto;
940
+
941
+ pre.pre-text {
942
+ color: @wnd-pre-color;
943
+ white-space: pre-wrap;
944
+ word-wrap: break-word;
945
+ font-family: @fserif;
946
+ font-size: @fsize-help;
947
+ line-height: 1.6;
948
+ padding: 2px 2px 2px 2px;
949
+ margin: 0;
950
+ text-align: left;
951
+ }
952
+
953
+ div.div-text {
954
+ color: @wnd-pre-color;
955
+ word-wrap: break-word;
956
+ font-family: @fserif;
957
+ font-size: @fsize-help;
958
+ padding: 0 2px 0 2px;
959
+ margin: 0;
960
+ ul {
961
+ list-style: none;
962
+ margin: 0;
963
+ padding: 0;
964
+ display: flex;
965
+ flex-direction: column;
966
+ border-top: 1px solid @menu-border;
967
+ li {
968
+ border-left: 1px solid @menu-border;
969
+ border-right: 1px solid @menu-border;
970
+ border-bottom: 1px solid @menu-border;
971
+ a {
972
+ color: @menu-fg;
973
+ font-size: @fsize-menu;
974
+ font-family: @fsans;
975
+ font-weight: normal;
976
+ display: block;
977
+ margin: 0;
978
+ padding: 5px 2px 2px 0;
979
+ text-align: left;
980
+ text-decoration: none;
981
+ }
982
+ &:hover {
983
+ text-decoration: underline;
984
+ background-color: lighten(@menu-bg, 20%);
985
+ color: @menu-icon-hover;
986
+ }
987
+ }
988
+ }
989
+ }
990
+ // help
991
+ div.text {
992
+ font-size: @fsize-help;
993
+ font-weight: normal;
994
+ padding-left: 10px;
995
+ padding-right: 10px;
996
+ margin: 0;
997
+ pre {
998
+ white-space: pre-wrap;
999
+ word-wrap: break-word;
1000
+ font-family: @fsans;
1001
+ font-size: @fsize-help;
1002
+ line-height: 1.3;
1003
+ padding: 0 5px 0 5px;
1004
+ margin: 0;
1005
+ text-align: left;
1006
+ }
1007
+ .center {
1008
+ text-align: center;
1009
+ font-size: @fsize-help;
1010
+ font-weight: bold;
1011
+ text-decoration: underline;
1012
+ font-style: italic;
1013
+ color: @color3;
1014
+ }
1015
+ .label {
1016
+ margin: 5px 0 5px 10px;
1017
+ font-size: @fsize-help;
1018
+ font-weight: bold;
1019
+ font-style: italic;
1020
+ color: @color3;
1021
+ }
1022
+ div {
1023
+ font-family: @fsans;
1024
+ font-size: @fsize-help;
1025
+ font-weight: bold;
1026
+ padding-top: 0;
1027
+ padding-bottom: 0;
1028
+ a {
1029
+ background: @base-bg;
1030
+ color: @text-color;
1031
+ font-weight: normal;
1032
+ &:hover {
1033
+ background: lighten(@base-bg, 20%);
1034
+ color: @text-color;
1035
+ }
1036
+ }
1037
+ }
1038
+ p {
1039
+ font-size: @fsize-help;
1040
+ font-weight: normal;
1041
+ font-family: @fsans;
1042
+ text-align: justify;
1043
+ padding-bottom: 9px;
1044
+ padding-right: 0;
1045
+ padding-left: 10px;
1046
+ }
1047
+ }
1048
+ }
1049
+
1050
+ .btn-wrapper {
1051
+ width: 100%;
1052
+ height: 2vw;
1053
+ position: sticky;
1054
+ top: 0;
1055
+ padding: 0;
1056
+ background: lighten(@wnd-bg, 5%);
1057
+
1058
+ .btn-copy {
1059
+ position: absolute;
1060
+ top: 1px;
1061
+ right: 5vw;
1062
+ box-sizing: border-box;
1063
+ background: inherit;
1064
+ color: @text-color;
1065
+ border: none;
1066
+ cursor: pointer;
1067
+ width: 30px;
1068
+ margin: 0;
1069
+ padding: 0;
1070
+ transition: background-color 0.3s;
1071
+
1072
+ &:hover {
1073
+ background-color: @btn-hover;
1074
+ }
1075
+
1076
+ // &.copied {
1077
+ // background-color: @btn-copied;
1078
+ // transform: scale(1.2);
1079
+ // }
1080
+ .copy-icon {
1081
+ fill: @btn-color;
1082
+ width: 20px;
1083
+ height: 20px;
1084
+
1085
+ &:hover {
1086
+ fill: @btn-hover-fg;
1087
+ background: lighten(@wnd-bg, 15%);
1088
+ }
1089
+ }
1090
+ }
1091
+
1092
+ .btn-close {
1093
+ position: absolute;
1094
+ top: 0;
1095
+ right: 2vw;
1096
+ margin: 0;
1097
+ background-color: transparent;
1098
+ border: none;
1099
+ color: @btn-color;
1100
+ font-size: @fsize-btn-close;
1101
+ font-weight: bold;
1102
+ cursor: pointer;
1103
+ outline: none;
1104
+
1105
+ &:hover {
1106
+ color: @btn-hover-fg;
1107
+ background: lighten(@wnd-bg, 15%);
1108
+ }
1109
+ }
1110
+ }
static/less/tooltip.less ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Regolare i valori di calc() per distanze diverse
3
+ * Aggiungere white-space: normal per tooltip multi-riga
4
+ * Modificare border-width per frecce più grandi/più piccole
5
+ *
6
+ * Nota importante:
7
+ * Il sistema sfrutta l'attributo data-tooltip per il contenuto testuale,
8
+ * mantenendo HTML semantico e accessibile.
9
+ * Per contenuti dinamici, basta modificare l'attributo via JavaScript.
10
+ * Esmpio:
11
+ * <span class="menu-h-box tt-right" data-tt="Open">
12
+ * <span class="menu-h-inner"></span>
13
+ * </span>
14
+ *
15
+ * @format
16
+ */
17
+
18
+ /* ========= VARIABILI LESS ========= */
19
+ @tt-bg: #cc3a05; // Colore di sfondo del tooltip
20
+ @tt-text: #ffffff; // Colore testo del tooltip
21
+ @tt-font: 20px "Arial", sans-serif; // Stile font
22
+ @tt-radius: 4px; // Border-radius
23
+ @tt-shadow: 0 3px 6px #e2ca0e29; // Ombra
24
+ @tt-transition: 0.3s opacity; // Transizione
25
+ @border-width: 6px;
26
+
27
+ /* ========= BASE TOOLTIP ========= */
28
+ .tt-top,
29
+ .tt-bottom,
30
+ .tt-left,
31
+ .tt-leftx,
32
+ .tt-right {
33
+ position: relative;
34
+ // cursor: help;
35
+ transition: 0.2s transform;
36
+
37
+ // Pseudo-elementi comuni
38
+ &::before,
39
+ &::after {
40
+ position: absolute;
41
+ opacity: 0;
42
+ pointer-events: none;
43
+ z-index: 9999;
44
+ transition: @tt-transition;
45
+ }
46
+
47
+ // Testo del tooltip
48
+ &::before {
49
+ content: attr(data-tt);
50
+ background: @tt-bg;
51
+ color: @tt-text;
52
+ font: @tt-font;
53
+ font-weight: normal;
54
+ // padding: 8px 16px;
55
+ padding: 4px 10px;
56
+ border-radius: @tt-radius;
57
+ box-shadow: @tt-shadow;
58
+ // border: 2px solid yellow;
59
+ white-space: nowrap;
60
+ }
61
+
62
+ // Freccia
63
+ // &::after {
64
+ // content: "";
65
+ // border: @border-width solid transparent;
66
+ // }
67
+
68
+ // Hover states
69
+ &:hover {
70
+ &::before,
71
+ &::after {
72
+ opacity: 1;
73
+ }
74
+ }
75
+ }
76
+
77
+ /* ========= POSIZIONAMENTI ========= */
78
+ .tt-top {
79
+ &::before {
80
+ bottom: ~"calc(100% + 12px)"; // Posizionato sopra l'elemento di 12px
81
+ left: 50%; // Centrato orizzontalmente
82
+ transform: translateX(-50%); // Spostato indietro del 50% della sua larghezza
83
+ }
84
+
85
+ // &::after {
86
+ // border-top-color: @tt-bg; // Colore del bordo superiore per la freccia
87
+ // bottom: ~"calc(100% + 0px)"; // Posizionato sopra l'elemento
88
+ // left: 50%; // Centrato orizzontalmente
89
+ // transform: translateX(-50%); // Spostato indietro del 50% della sua larghezza
90
+ // }
91
+ }
92
+
93
+ .tt-bottom {
94
+ &::before {
95
+ top: ~"calc(100% + 12px)"; // Posizionato sotto l'elemento di 12px
96
+ left: 50%; // Centrato orizzontalmente
97
+ transform: translateX(-50%); // Spostato indietro del 50% della sua larghezza
98
+ }
99
+
100
+ // &::after {
101
+ // border-bottom-color: @tt-bg; // Colore del bordo inferiore per la freccia
102
+ // top: ~"calc(100% + 0px)"; // Posizionato sotto l'elemento
103
+ // left: 50%; // Centrato orizzontalmente
104
+ // transform: translateX(-50%); // Spostato indietro del 50% della sua larghezza
105
+ // }
106
+ }
107
+
108
+ .tt-left {
109
+ &::before {
110
+ right: ~"calc(50% + 0px)";
111
+ top: ~"calc(100% + 22px)";
112
+ transform: translateY(-50%);
113
+ }
114
+
115
+ // &::after {
116
+ // border-left-color: @tt-bg;
117
+ // right: ~"calc(100% + 0px)";
118
+ // top: 50%;
119
+ // transform: translateY(-50%);
120
+ // }
121
+ }
122
+
123
+ .tt-leftx {
124
+ &::before {
125
+ right: ~"calc(50% + 20px)";
126
+ top: ~"calc(100% + 22px)";
127
+ transform: translateY(-80%);
128
+ }
129
+ }
130
+
131
+ // .tt-left {
132
+ // &::before {
133
+ // right: ~"calc(100% + 12px)"; // Posizionato a sinistra dell'elemento di 12px
134
+ // top: 50%; // Centrato verticalmente
135
+ // transform: translateY(-50%); // Spostato in alto del 50% della sua altezza
136
+ // }
137
+
138
+ // &::after {
139
+ // border-left-color: @tt-bg; // Colore del bordo sinistro per la freccia
140
+ // right: ~"calc(100% + 0px)"; // Posizionato a sinistra dell'elemento
141
+ // top: 50%; // Centrato verticalmente
142
+ // transform: translateY(-50%); // Spostato in alto del 50% della sua altezza
143
+ // }
144
+ // }
145
+
146
+ .tt-right {
147
+ &::before {
148
+ left: ~"calc(100% + 12px)"; // Posizionato a destra dell'elemento di 12px
149
+ top: 50%; // Centrato verticalmente
150
+ transform: translateY(50%); // Spostato in alto del 50% della sua altezza
151
+ }
152
+ // &::after {
153
+ // border-right-color: @tt-bg; // Colore del bordo destro per la freccia
154
+ // left: ~"calc(100% + 0px)"; // Posizionato a destra dell'elemento
155
+ // top: 50%; // Centrato verticalmente
156
+ // transform: translateY(-50%); // Spostato in alto del 50% della sua altezza
157
+ // }
158
+ }
159
+
160
+ // .tt-right {
161
+ // &::before {
162
+ // left: ~"calc(100% + 12px)"; // Posizionato a destra dell'elemento di 12px
163
+ // top: 50%; // Centrato verticalmente
164
+ // transform: translateY(-50%); // Spostato in alto del 50% della sua altezza
165
+ // }
166
+
167
+ // &::after {
168
+ // border-right-color: @tt-bg; // Colore del bordo destro per la freccia
169
+ // left: ~"calc(100% + 0px)"; // Posizionato a destra dell'elemento
170
+ // top: 50%; // Centrato verticalmente
171
+ // transform: translateY(-50%); // Spostato in alto del 50% della sua altezza
172
+ // }
173
+ // }
static/less/uadialog.less ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * ========= VARIABILI =========
3
+ *
4
+ * @format
5
+ */
6
+
7
+ @dialog-bg: #2d2d2d;
8
+ @dialog-text: #f5f5f5;
9
+ @overlay-bg: rgba(0, 0, 0, 0.7);
10
+ @confirm-color: #4caf50;
11
+ @cancel-color: #f44336;
12
+ @border-radius: 12px;
13
+ @transition-speed: 0.3s;
14
+
15
+ /* ========= DIALOGHI ========= */
16
+ .confirm-dialog,
17
+ .alert-dialog {
18
+ position: fixed;
19
+ top: 50%;
20
+ left: 50%;
21
+ transform: translate(-50%, -50%) scale(0.9);
22
+ opacity: 0;
23
+ visibility: hidden;
24
+ background: @dialog-bg;
25
+ padding: 2rem;
26
+ border-radius: @border-radius;
27
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
28
+ z-index: 10001;
29
+ min-width: 320px;
30
+ max-width: 90%;
31
+ transition: all @transition-speed cubic-bezier(0.4, 0, 0.2, 1);
32
+
33
+ &.show {
34
+ opacity: 1;
35
+ visibility: visible;
36
+ transform: translate(-50%, -50%) scale(1);
37
+ }
38
+
39
+ h4 {
40
+ margin: 0 0 2rem;
41
+ color: @dialog-text;
42
+ font-size: 1.25rem;
43
+ font-weight: 500;
44
+ line-height: 1.4;
45
+ text-align: center;
46
+ }
47
+
48
+ .buttons {
49
+ display: flex;
50
+ gap: 1rem;
51
+ justify-content: center;
52
+ }
53
+
54
+ button {
55
+ border: none;
56
+ padding: 0.75rem 1.5rem;
57
+ border-radius: 6px;
58
+ font-weight: 500;
59
+ text-transform: uppercase;
60
+ letter-spacing: 0.05em;
61
+ cursor: pointer;
62
+ transition: all 0.2s ease;
63
+
64
+ &:focus {
65
+ outline: 2px solid rgba(255, 255, 255, 0.5);
66
+ outline-offset: 2px;
67
+ }
68
+
69
+ &.ok {
70
+ background: @confirm-color;
71
+ color: white;
72
+
73
+ &:hover {
74
+ background: darken(@confirm-color, 8%);
75
+ }
76
+ }
77
+
78
+ &.cancel {
79
+ background: @cancel-color;
80
+ color: white;
81
+
82
+ &:hover {
83
+ background: darken(@cancel-color, 8%);
84
+ }
85
+ }
86
+ }
87
+ }
88
+
89
+ /* ========= DIFFERENZIAZIONE DIALOGHI ========= */
90
+ .confirm-dialog {
91
+ border: 2px solid @confirm-color;
92
+ }
93
+
94
+ .alert-dialog {
95
+ border: 2px solid #2196f3;
96
+
97
+ .ok {
98
+ background: #2196f3;
99
+
100
+ &:hover {
101
+ background: darken(#2196f3, 8%);
102
+ }
103
+ }
104
+ }
105
+
106
+ /* ========= OVERLAY ========= */
107
+ .overlay {
108
+ position: fixed;
109
+ top: 0;
110
+ left: 0;
111
+ width: 100%;
112
+ height: 100%;
113
+ background: @overlay-bg;
114
+ opacity: 0;
115
+ visibility: hidden;
116
+ z-index: 10000;
117
+ transition: opacity @transition-speed ease;
118
+
119
+ &.show {
120
+ opacity: 1;
121
+ visibility: visible;
122
+ }
123
+ }
static/lessm/less.min.js ADDED
The diff for this file is too large to render. See raw diff
 
static/lessm/less.min.js.map ADDED
The diff for this file is too large to render. See raw diff
 
static/ragrqs.html CHANGED
@@ -5,28 +5,36 @@
5
  <meta charset="utf-8" />
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
  <meta name="description" content="Author:Giuseppe Materni" />
8
- <title>RagRqs</title>
9
 
10
- <link rel="stylesheet" href="css/ragrqs.min.css" />
11
- <script src="js/ragrqs.min.js"></script>
12
 
13
- <!-- <link rel="stylesheet" href="less/normalize.css" />
14
- <link rel="stylesheet/less" href="less/ragrqs.less" />
 
 
 
15
  <link rel="stylesheet/less" href="less/ualog3.less" />
16
- <script src="less/less.js"></script>
17
- <script src="javascript/uadrag.js"></script>
18
- <script src="javascript/uawindow.js"></script>
19
- <script src="javascript/uajtfh.js"></script>
20
- <script src="javascript/ualog3.js"></script>
21
  <script src="javascript/rag_cleaner.js"></script>
22
  <script src="javascript/rag_data_mgr.js"></script>
23
  <script src="javascript/rag_http.js"></script>
24
  <script src="javascript/rag_mgr.js"></script>
25
  <script src="javascript/rag_prompts.js"></script>
 
26
  <script src="javascript/rag_upload.js"></script>
27
  <script src="javascript/rag_ui.js"></script>
28
- <script src="javascript/rag_env.js"></script>
29
- <script src="javascript/app.js"></script> --> -->
 
 
 
 
30
 
31
  <body>
32
  <div id="spinner" class="spinner">
@@ -36,33 +44,33 @@
36
 
37
  <div class="menu-h">
38
 
39
- <input id="id-menu-btn" name="id-menu-btn" class="menu-btn" type="checkbox" />
40
  <label for="id-menu-btn" class="menu-icon">
41
  <span class="nav-icon"></span>
42
  </label>
43
 
44
  <div class="head-wrapper">
45
- <button class="help" onclick="Menu.help();" title="Istruzioni">?</button>
46
- <button class="upload" onclick="Menu.upload();" ; title="Upload files">
47
  <svg class="icon" viewBox="0 0 24 24">
48
  <path d="M20 15v2H4v-2H2v5h20v-5zM13 5V1h-2v4H7l5 5 5-5z" fill="none" stroke="#FFFFFF" stroke-width="2" />
49
  </svg>
50
  </button>
51
- <button class="upload" onclick="Menu.uploadDir();" ; title="Upload dir">
52
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
53
  <path d="M20 6h-8l-2-2H4C2.9 4 2 4.9 2 6v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-8 7H8v2h4v-2zm6 0h-4v2h4v-2zm0-4H8v2h10V9z" fill="none" stroke="#FFFFFF" stroke-width="2" />
54
  </svg>
55
  </button>
56
- <button class="log active" id="id_log" onclick="Menu.log();" title="Log">Log</button>
57
  <label class="release"></label>
58
 
59
  <div class="btn-theme">
60
- <button class="btn-dark" title="Tema scuro" onclick="setDark()">
61
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
62
  <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
63
  </svg>
64
  </button>
65
- <button class="btn-light" title="Tma charo" onclick="setLight()">
66
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
67
  <circle cx="12" cy="12" r="5" />
68
  <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" />
@@ -75,24 +83,24 @@
75
 
76
  <div class="menu-box">
77
  <ul>
78
- <li><a href="#" onCLick="op0(this);">README</a></li>
79
- <li><a href="#" onCLick="showQuery();">Domanda</a></li>
80
- <li><a href="#" onCLick="showRagResponse();">Risposta</a></li>
81
- <li><a href="#" onCLick="showThread();">Conversazione</a></li>
82
-
83
- <li><a href="#" onCLick="elencoRisposte(this);">Elenco Risposte</a></li>
84
- <li><a href="#" onCLick="showContesto(this);">Contesto RAG</a></li>
85
- <li><a href="#" onCLick="elencoDati(this);">Dati archviati</a></li>
86
- <li><a href="#" onCLick="elencoDocs(this);">Elenco Documenti</a></li>
87
- <li><a href="#" onCLick="calcQuery();">Numero Richieste</a></li>
88
- <li><a class="delete" href="#" onCLick="deleteDati(this);">Cancella Dati</a></li>
89
  <li>-</li>
90
- <li><a class="help" href="#" onCLick="deleteSttorage(this);">Cancella Documenti</a></li>
91
  <li>-</li>
92
- <li><a href="#" onCLick="help1(this);">Esempi di documenti</a></li>
93
- <li><a href="#" onCLick="help2(this);">Esempi di domande</a></li>
94
  <!-- -->
95
- <li><a href="#" onCLick="showPrompts(this);">prompts</a></li>
96
 
97
  </ul>
98
  </div>
@@ -104,21 +112,22 @@
104
  <div class="output-wrapper">
105
 
106
  <div class="text-out" id="id-text-out">
107
- <pre class="pre-text"></pre>
 
108
  </div>
109
 
110
  <div class="output-actions">
111
- <button class="copy-output" title="Copia">
112
  <svg class="copy-icon" viewBox="0 0 20 24">
113
  <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
114
  </svg>
115
  </button>
116
- <button class="wnd-output" title="Apri">
117
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
118
  <path d="M10 9v6h4V9h5l-7-7-7 7h5zM5 19v2h14v-2H5z" />
119
  </svg>
120
  </button>
121
- <button class="clear-output" title="Cancella">
122
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
123
  <path d="M3 6h18v2H3V6zm2 3h14v12H5V9zm3-7h6v2H8V2z" />
124
  </svg>
@@ -131,22 +140,22 @@
131
  <div class="input-wrapper">
132
 
133
  <textarea class="text-input" placeholder="Scrivi qui... " rows="2"></textarea>
134
- <button class="clear-button" title="Cancella input">X</button>
135
 
136
  <div class="input-actions">
137
- <button class="send-input" title="Documenti=>RAG=>Conetso=>Query">
138
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
139
  <path d="M2 21l21-9L2 3v7l15 2-15 2v7z" fill="none" stroke="#FFFFFF" stroke-width="2" />
140
  </svg>
141
  </button>
142
 
143
 
144
- <button class="send2-input" title="Contesto=>Query">
145
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
146
  <path d="M2 21l21-9L2 3v7l15 2-15 2v7z" fill="none" stroke="#FFFFFF" stroke-width="2" />
147
  </svg>
148
  </button>
149
- <button class="clear-input" title="Cancella Conversazione">
150
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
151
  <path d="M3 6h18v2H3V6zm2 3h14v12H5V9zm3-7h6v2H8V2z" fill="none" stroke="#FFFFFF" stroke-width="2" />
152
  </svg>
@@ -161,10 +170,8 @@
161
 
162
  </html>
163
  <script>
164
-
165
  window.addEventListener('load', () => {
166
- console.log("Tutti i file esterni (CSS, JavaScript, immagini) sono stati caricati");
167
  openApp();
168
  });
169
-
170
  </script>
 
5
  <meta charset="utf-8" />
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
  <meta name="description" content="Author:Giuseppe Materni" />
8
+ <title>RagqQuery</title>
9
 
10
+ <link rel="stylesheet" href="css/ragquery.min.css" />
11
+ <script src="js/ragquery.min.js"></script>
12
 
13
+
14
+ <!--
15
+ <link rel="stylesheet" href="less/normalize.css" />
16
+ <link rel="stylesheet/less" href="less/ragquery.less" />
17
+ <link rel="stylesheet/less" href="less/uadialog.less" />
18
  <link rel="stylesheet/less" href="less/ualog3.less" />
19
+ <link rel="stylesheet/less" href="less/tooltip.less" />
20
+ <script src="lessm/less.min.js"></script>
21
+
22
+ <script src="javascript/app.js"></script>
23
+ <script src="javascript/client_llm.js"></script>
24
  <script src="javascript/rag_cleaner.js"></script>
25
  <script src="javascript/rag_data_mgr.js"></script>
26
  <script src="javascript/rag_http.js"></script>
27
  <script src="javascript/rag_mgr.js"></script>
28
  <script src="javascript/rag_prompts.js"></script>
29
+ <script src="javascript/rag_payload.js"></script>
30
  <script src="javascript/rag_upload.js"></script>
31
  <script src="javascript/rag_ui.js"></script>
32
+ <script src="javascript/uadialog.js"></script>
33
+ <script src="javascript/uadrag.js"></script>
34
+ <script src="javascript/uajtfh.js"></script>
35
+ <script src="javascript/ualog3.js"></script>
36
+ <script src="javascript/uawindow.js"></script>
37
+ <script src="javascript/help.js"></script> -->
38
 
39
  <body>
40
  <div id="spinner" class="spinner">
 
44
 
45
  <div class="menu-h">
46
 
47
+ <input id="id-menu-btn" name="id-menu-btn" class="menu-btn tt-right" data-tt="Open" type="checkbox" />
48
  <label for="id-menu-btn" class="menu-icon">
49
  <span class="nav-icon"></span>
50
  </label>
51
 
52
  <div class="head-wrapper">
53
+ <button class="help tt-bottom" onclick="Menu.help();" data-tt="Istruzioni">?</button>
54
+ <button class="upload tt-bottom" onclick="Menu.upload();" ; data-tt="Upload files">
55
  <svg class="icon" viewBox="0 0 24 24">
56
  <path d="M20 15v2H4v-2H2v5h20v-5zM13 5V1h-2v4H7l5 5 5-5z" fill="none" stroke="#FFFFFF" stroke-width="2" />
57
  </svg>
58
  </button>
59
+ <button class="upload tt-bottom" onclick="Menu.uploadDir();" ; data-tt="Upload dir">
60
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
61
  <path d="M20 6h-8l-2-2H4C2.9 4 2 4.9 2 6v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-8 7H8v2h4v-2zm6 0h-4v2h4v-2zm0-4H8v2h10V9z" fill="none" stroke="#FFFFFF" stroke-width="2" />
62
  </svg>
63
  </button>
64
+ <button class="log active inv" id="id_log" onclick="Menu.log();">Log</button>
65
  <label class="release"></label>
66
 
67
  <div class="btn-theme">
68
+ <button class="btn-dark tt-left" data-tt="Tema scuro" onclick="setDark()">
69
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
70
  <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
71
  </svg>
72
  </button>
73
+ <button class="btn-light tt-left" data-tt="Tema chiaro" onclick="setLight()">
74
  <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
75
  <circle cx="12" cy="12" r="5" />
76
  <path d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42" />
 
83
 
84
  <div class="menu-box">
85
  <ul>
86
+ <li><a href="#" onclick="op0(this);">README</a></li>
87
+ <li><a href="#" onclick="showQuery();">Domanda Iniziale</a></li>
88
+ <li><a href="#" onclick="showRagResponse();">Risposta Contestuale</a></li>
89
+ <li><a href="#" onclick="showThread();">Conversazione</a></li>
90
+
91
+ <li><a href="#" onclick="elencoRisposte(this);">Elenco Risposte</a></li>
92
+ <li><a href="#" onclick="showContesto(this);">Contesto RAG</a></li>
93
+ <li><a href="#" onclick="elencoDati(this);">Dati archviati</a></li>
94
+ <li><a href="#" onclick="elencoDocs(this);">Elenco Documenti</a></li>
95
+ <li><a href="#" onclick="calcQuery();">Numero Richieste</a></li>
96
+ <li><a class="delete inv" href="#" onclick="deleteDati(this);">Cancella Dati</a></li>
97
  <li>-</li>
98
+ <li><a class="help inv" href="#" onclick="deleteStorage(this);">Cancella Documenti</a></li>
99
  <li>-</li>
100
+ <li><a href="#" onclick="help1(this);">Esempi di documenti</a></li>
101
+ <li><a href="#" onclick="help2(this);">Esempi di domande</a></li>
102
  <!-- -->
103
+ <!-- <li><a href="#" onclick="showPrompts(this);">prompts</a></li> -->
104
 
105
  </ul>
106
  </div>
 
112
  <div class="output-wrapper">
113
 
114
  <div class="text-out" id="id-text-out">
115
+ <!-- <pre class="pre-text"></pre> -->
116
+ <div class="div-text"></div>
117
  </div>
118
 
119
  <div class="output-actions">
120
+ <button class="copy-output tt-left" data-tt="Copia Output">
121
  <svg class="copy-icon" viewBox="0 0 20 24">
122
  <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />
123
  </svg>
124
  </button>
125
+ <button class="wnd-output tt-left" data-tt="Apri Output">
126
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
127
  <path d="M10 9v6h4V9h5l-7-7-7 7h5zM5 19v2h14v-2H5z" />
128
  </svg>
129
  </button>
130
+ <button class="clear-output tt-left" data-tt="Cancella Output">
131
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
132
  <path d="M3 6h18v2H3V6zm2 3h14v12H5V9zm3-7h6v2H8V2z" />
133
  </svg>
 
140
  <div class="input-wrapper">
141
 
142
  <textarea class="text-input" placeholder="Scrivi qui... " rows="2"></textarea>
143
+ <button class="clear-button tt-top" data-tt="Cancella Input">X</button>
144
 
145
  <div class="input-actions">
146
+ <button class="send-input inv tt-leftx" data-tt="Documenti=>RAG=>Conetso=>Query .">
147
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
148
  <path d="M2 21l21-9L2 3v7l15 2-15 2v7z" fill="none" stroke="#FFFFFF" stroke-width="2" />
149
  </svg>
150
  </button>
151
 
152
 
153
+ <button class="send2-input inv tt-leftx" data-tt="Contesto=>Query .">
154
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
155
  <path d="M2 21l21-9L2 3v7l15 2-15 2v7z" fill="none" stroke="#FFFFFF" stroke-width="2" />
156
  </svg>
157
  </button>
158
+ <button class="clear-input tt-left" data-tt="Cancella Conversazione">
159
  <svg class="icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
160
  <path d="M3 6h18v2H3V6zm2 3h14v12H5V9zm3-7h6v2H8V2z" fill="none" stroke="#FFFFFF" stroke-width="2" />
161
  </svg>
 
170
 
171
  </html>
172
  <script>
 
173
  window.addEventListener('load', () => {
 
174
  openApp();
175
  });
176
+
177
  </script>