Toaster496 commited on
Commit
efd3af0
1 Parent(s): 229a3a2

Delete Hugplug

Browse files
Hugplug/HuggingChatAPI.py DELETED
@@ -1,65 +0,0 @@
1
-
2
- from hugchat import hugchat
3
- from hugchat.login import Login
4
- from langchain.llms.base import LLM
5
- from typing import Optional, List, Mapping, Any
6
- from time import sleep
7
-
8
-
9
- # THIS IS A CUSTOM LLM WRAPPER Based on hugchat library
10
- # Reference :
11
- # - Langchain custom LLM wrapper : https://python.langchain.com/docs/modules/model_io/models/llms/how_to/custom_llm
12
- # - HugChat library : https://github.com/Soulter/hugging-chat-api
13
-
14
- class HuggingChat(LLM):
15
- """HuggingChat LLM wrapper."""
16
- chatbot : Optional[hugchat.ChatBot] = None
17
- conversation : Optional[str] = ""
18
- email : Optional[str]
19
- psw : Optional[str]
20
-
21
-
22
-
23
- @property
24
- def _llm_type(self) -> str:
25
- return "custom"
26
-
27
- def _call(self, prompt: str, stop: Optional[List[str]] = None) -> str:
28
- if stop is not None:
29
- pass
30
-
31
- if self.chatbot is None:
32
- if self.email is None and self.psw is None:
33
- ValueError("Email and Password is required, pls check the documentation on github : https://github.com/Soulter/hugging-chat-api")
34
- else:
35
- if self.conversation == "":
36
- sign = Login(self.email, self.psw) # type: ignore
37
- cookies = sign.login()
38
-
39
- # Create a ChatBot
40
- self.chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
41
-
42
- id = self.chatbot.new_conversation()
43
- self.chatbot.change_conversation(id)
44
- self.conversation = id
45
- else:
46
- self.chatbot.change_conversation(self.conversation) # type: ignore
47
-
48
-
49
- data = self.chatbot.chat(prompt, temperature=0.4, stream=False) # type: ignore
50
- return data # type: ignore
51
-
52
- @property
53
- def _identifying_params(self) -> Mapping[str, Any]:
54
- """Get the identifying parameters."""
55
- return {"model": "HuggingCHAT"}
56
-
57
-
58
-
59
- #llm = HuggingChat(email = "YOUR-EMAIL" , psw = = "YOUR-PSW" ) #for start new chat
60
-
61
-
62
- #print(llm("Hello, how are you?"))
63
- #print(llm("what is AI?"))
64
- #print(llm("Can you resume your previus answer?")) #now memory work well
65
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Hugplug/LICENSE DELETED
@@ -1,674 +0,0 @@
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>.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Hugplug/README.md DELETED
@@ -1,220 +0,0 @@
1
-
2
- # 🤗💬 HugChat but with STEROIDs 🚀
3
-
4
- <br />
5
-
6
- This app is an LLM-based chatbot created to give anyone🤗 the possibility to use PLUGINS, like **internet**, **Multi pdf**, **YoutubeVideo**, **Audio**, etc.. , **without paying anything 😮** Don't you trust it? **TRY IT🧑‍💻**
7
-
8
- <br />
9
- <br />
10
-
11
-
12
-
13
- # See the Demo 👇
14
- https://github.com/IntelligenzaArtificiale/Free-personal-AI-Assistant/assets/108482353/61c58cf4-d14a-43e8-b248-03190f9ac034
15
-
16
- <br />
17
- <br />
18
-
19
- # Current PLUGIN
20
- <br />
21
-
22
- <details>
23
- <summary>
24
-
25
- ## WebSearch 🌐
26
-
27
- </summary>
28
-
29
- ### 🚀Search on web
30
-
31
- ### 🧑‍💻 Set up the plugin
32
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/23bdaa97-63e6-4e38-8d0d-b53321de9883)
33
-
34
- ### 🤗 Enjoi it
35
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/2667f218-05cb-4b54-ab7f-916338013317)
36
-
37
- ### 🚨 ChatGPT response
38
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/236b3945-5e51-4e21-a2c9-2aeb4d575f7e)
39
-
40
- </details>
41
-
42
- <br />
43
-
44
-
45
- <details>
46
- <summary>
47
-
48
- ## Web Scraping 🔗
49
-
50
- </summary>
51
-
52
- ### 🚀Talk with your preferite webisites
53
-
54
- ### 🧑‍💻 Set up the plugin
55
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/689cbc0c-b33e-4f98-8095-61f3a2c7e844)
56
-
57
- ### 🤗 Enjoi it
58
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/a5ba2a34-4284-4a23-82f7-ef6445d34d62)
59
-
60
- ### 🚨 BingChat response
61
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/fdb86d41-e2d9-4baa-8b7c-f64307118bb7)
62
-
63
- </details>
64
-
65
- <br />
66
-
67
- <details>
68
- <summary>
69
-
70
- ## Talk with Data 📊
71
-
72
- </summary>
73
-
74
- ### 🚀Perfect plugin for data analyst and data scientist !
75
-
76
- ### 🧑‍💻 Set up the plugin
77
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/639b3f98-a72b-4ae9-a947-1b0185111f77)
78
-
79
- ### 🤗 Enjoi it
80
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/3987cff1-693d-4233-a66c-dbc291ac7888)
81
-
82
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/061a68c4-de8c-45fd-9235-6d07eaf8d33e)
83
-
84
-
85
- ### 🚨 No FREE options to compare
86
-
87
- </details>
88
-
89
- <br />
90
-
91
- <details>
92
- <summary>
93
-
94
- ## Multi Documents support ( PDF , DOCX , TXT ) 📚
95
-
96
- </summary>
97
-
98
- ### 🚀Talk with your document in one click
99
-
100
- ### 🧑‍💻 Set up the plugin
101
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/8d4c2d27-80b8-4ad4-be72-34d9ca8eec4f)
102
-
103
- ### 🤗 Enjoi it
104
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/f324e65f-072d-477c-b5a5-e6f26b8bf600)
105
-
106
- ### 🚨 chatpdf.com response
107
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/beb60338-cffa-41ad-9221-6cd51bc4d7a6)
108
-
109
-
110
- </details>
111
-
112
- <br />
113
-
114
- <details>
115
- <summary>
116
-
117
- ## Talk with AUDIO 🎧
118
-
119
- </summary>
120
-
121
- ### 🚀Talk with mp3 or wav with one click
122
-
123
- ### 🧑‍💻 Set up the plugin
124
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/61b29d3e-d5d2-4b82-b35e-109e5c5e3837)
125
-
126
- ### 🤗 Enjoi it
127
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/662b0418-e416-4fc4-8d27-b106a2a84706)
128
-
129
- ### 🚨 No FREE options to compare
130
-
131
- </details>
132
-
133
- <br />
134
-
135
- <details>
136
- <summary>
137
-
138
- ## Talk with Youtube Video 📺
139
-
140
- </summary>
141
-
142
- ### 🚀We love this plugin, its crazy
143
-
144
- ### 🧑‍💻 Set up the plugin
145
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/8f8f7885-3cc1-47a2-9176-7941a51f7dd4)
146
-
147
- ### 🤗 Enjoi it
148
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/d9b7b20b-fa0a-4676-baf1-31f30001da4a)
149
-
150
-
151
- ### 🚨 No FREE options to compare
152
-
153
- </details>
154
-
155
-
156
- <br />
157
-
158
- <details>
159
- <summary>
160
-
161
- ## GOD MODE 🪄 give custom knowledge to your chat
162
-
163
- </summary>
164
-
165
- ### 🚀This plugin able the chat to make a custom knowledge from a single topic
166
-
167
- ### 🧑‍💻 Set up the plugin
168
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/135146a6-9e27-4681-817c-e91faabdd63d)
169
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/78f9803b-c23d-43a8-b756-c127042586d0)
170
-
171
- ### 🤗 Enjoi it
172
- ![image](https://github.com/IntelligenzaArtificiale/hugchat-with-plugin-Free-personal-AI-Assistant/assets/108482353/a02d08c1-5c0c-4a0b-a8f5-1587771eb5d9)
173
-
174
-
175
- ### 🚨 No FREE options to compare
176
-
177
- </details>
178
-
179
-
180
- <br />
181
- <br />
182
-
183
- ## How to use 💻
184
-
185
- - **Try it online**
186
- - No installation needed
187
- - [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://free-personal-ai-assistant.streamlit.app/)
188
-
189
- - **Or install Locally**
190
- - 💾 Download the repository
191
- - 🔗 Exctract it
192
- - 🛑 Install the `requirements.txt`
193
- - ✅ Run `streamlit run streamlit_app.py`
194
- - 🚀 Enjoy it
195
-
196
- <br />
197
- <br />
198
-
199
- ## How to contribute 🤝
200
-
201
- - **Fork** the repository
202
- - **Clone** the repository
203
- - **Create** a new branch
204
- - **Commit** your changes
205
- - **Push** your changes
206
- - **Open** a pull request
207
- - **Develop** new plugins
208
-
209
- <br />
210
- <br />
211
-
212
- ## Disclaimer
213
- The following disclaimer is from the GitHub repo from the authors of the [HugChat](https://github.com/Soulter/hugging-chat-api) port.
214
- > When you use this project, it means that you have agreed to the following two requirements of the HuggingChat:
215
- >
216
- > AI is an area of active research with known problems such as biased generation and misinformation. Do not use this application for high-stakes decisions or advice. Your conversations will be shared with model authors.
217
- >
218
- >[HugChat](https://github.com/Soulter/hugging-chat-api) is an unofficial port to the [HuggingFace Chat](https://huggingface.co/chat/) API that is powered by the [OpenAssistant/oasst-sft-6-llama-30b-xor](https://huggingface.co/OpenAssistant/oasst-sft-6-llama-30b-xor) LLM model.
219
-
220
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Hugplug/exportchat.py DELETED
@@ -1,49 +0,0 @@
1
- """
2
- PYTHON FILE FOR EXPORT CHAT FUNCTION
3
- """
4
-
5
- import streamlit as st
6
- from datetime import datetime
7
-
8
-
9
- def export_chat():
10
- if 'generated' in st.session_state:
11
- # save message in reverse order frist message always bot
12
- # the chat is stored in a html file format
13
- html_chat = ""
14
- html_chat += '<html><head><title>ChatBOT Intelligenza Artificiale Italia 🧠🤖🇮🇹</title>'
15
- #create two simply css box for bot and user like whatsapp
16
- html_chat += '<style> .bot { background-color: #e5e5ea; padding: 10px; border-radius: 10px; margin: 10px; width: 50%; float: left; } .user { background-color: #dcf8c6; padding: 10px; border-radius: 10px; margin: 10px; width: 50%; float: right; } </style>'
17
- html_chat += '</head><body>'
18
- #add header
19
- html_chat += '<center><h1>ChatBOT Intelligenza Artificiale Italia 🧠🤖🇮🇹</h1>'
20
- #add link for danation
21
- html_chat += '<h3>🤗 Support the project with a donation for the development of new features 🤗</h3>'
22
- html_chat += '<br><a href="https://rebrand.ly/SupportAUTOGPTfree"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" alt="PayPal donate button" /></a>'
23
- #add subheader with date and time
24
- html_chat += '<br><br><h5>' + datetime.now().strftime("%d/%m/%Y %H:%M:%S") + '</h5></center><br><br>'
25
- #add chat
26
- #add solid container
27
- html_chat += '<div style="padding: 10px; border-radius: 10px; margin: 10px; width: 100%; float: left;">'
28
- for i in range(len(st.session_state['generated'])-1, -1, -1):
29
- html_chat += '<div class="bot">' + st.session_state["generated"][i] + '</div><br>'
30
- html_chat += '<div class="user">' + st.session_state['past'][i] + '</div><br>'
31
- html_chat += '</div>'
32
- #add footer
33
- html_chat += '<br><br><center><small>Thanks you for using our ChatBOT 🧠🤖🇮🇹</small>'
34
- #add link for danation
35
- html_chat += '<h6>🤗 Support the project with a donation for the development of new features 🤗</h6>'
36
- html_chat += '<br><a href="https://rebrand.ly/SupportAUTOGPTfree"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif" alt="PayPal donate button" /></a><center>'
37
-
38
- html_chat += '</body></html>'
39
-
40
- #save file
41
- with open('chat.html', 'w') as f:
42
- f.write(html_chat)
43
- #download file
44
- st.download_button(
45
- label="📚 Download chat",
46
- data=html_chat,
47
- file_name='chat.html',
48
- mime='text/html'
49
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Hugplug/packages.txt DELETED
@@ -1 +0,0 @@
1
- ffmpeg
 
 
Hugplug/promptTemplate.py DELETED
@@ -1,90 +0,0 @@
1
- """
2
- This file contains the template for the prompt to be used for injecting the context into the model.
3
-
4
- With this technique we can use different plugin for different type of question and answer.
5
- Like :
6
- - Internet
7
- - Data
8
- - Code
9
- - PDF
10
- - Audio
11
- - Video
12
-
13
- """
14
-
15
- from datetime import datetime
16
- now = datetime.now()
17
-
18
- def prompt4conversation(prompt,context):
19
- final_prompt = f""" GENERAL INFORMATION : ( today is {now.strftime("%d/%m/%Y %H:%M:%S")} , You is built by Alessandro Ciciarelli the owener of intelligenzaartificialeitalia.net
20
- ISTRUCTION : IN YOUR ANSWER NEVER INCLUDE THE USER QUESTION or MESSAGE , WRITE ALWAYS ONLY YOUR ACCURATE ANSWER!
21
- PREVIUS MESSAGE : ({context})
22
- NOW THE USER ASK : {prompt} .
23
- WRITE THE ANSWER :"""
24
- return final_prompt
25
-
26
- def prompt4conversationInternet(prompt,context, internet, resume):
27
- final_prompt = f""" GENERAL INFORMATION : ( today is {now.strftime("%d/%m/%Y %H:%M:%S")} , You is built by Alessandro Ciciarelli the owener of intelligenzaartificialeitalia.net
28
- ISTRUCTION : IN YOUR ANSWER NEVER INCLUDE THE USER QUESTION or MESSAGE , WRITE ALWAYS ONLY YOUR ACCURATE ANSWER!
29
- PREVIUS MESSAGE : ({context})
30
- NOW THE USER ASK : {prompt}.
31
- INTERNET RESULT TO USE TO ANSWER : ({internet})
32
- INTERNET RESUME : ({resume})
33
- NOW THE USER ASK : {prompt}.
34
- WRITE THE ANSWER BASED ON INTERNET INFORMATION :"""
35
- return final_prompt
36
-
37
- def prompt4Data(prompt, context, solution):
38
- final_prompt = f"""GENERAL INFORMATION : You is built by Alessandro Ciciarelli the owener of intelligenzaartificialeitalia.net
39
- ISTRUCTION : IN YOUR ANSWER NEVER INCLUDE THE USER QUESTION or MESSAGE , YOU MUST MAKE THE CORRECT ANSWER MORE ARGUMENTED ! IF THE CORRECT ANSWER CONTAINS CODE YOU ARE OBLIGED TO INSERT IT IN YOUR NEW ANSWER!
40
- PREVIUS MESSAGE : ({context})
41
- NOW THE USER ASK : {prompt}
42
- THIS IS THE CORRECT ANSWER : ({solution})
43
- MAKE THE ANSWER MORE ARGUMENTED, WITHOUT CHANGING ANYTHING OF THE CORRECT ANSWER :"""
44
- return final_prompt
45
-
46
- def prompt4Code(prompt, context, solution):
47
- final_prompt = f"""GENERAL INFORMATION : You is built by Alessandro Ciciarelli the owener of intelligenzaartificialeitalia.net
48
- ISTRUCTION : IN YOUR ANSWER NEVER INCLUDE THE USER QUESTION or MESSAGE , THE CORRECT ANSWER CONTAINS CODE YOU ARE OBLIGED TO INSERT IT IN YOUR NEW ANSWER!
49
- PREVIUS MESSAGE : ({context})
50
- NOW THE USER ASK : {prompt}
51
- THIS IS THE CODE FOR THE ANSWER : ({solution})
52
- WITHOUT CHANGING ANYTHING OF THE CODE of CORRECT ANSWER , MAKE THE ANSWER MORE DETALIED INCLUDING THE CORRECT CODE :"""
53
- return final_prompt
54
-
55
-
56
- def prompt4Context(prompt, context, solution):
57
- final_prompt = f"""GENERAL INFORMATION : You is built by Alessandro Ciciarelli the owener of intelligenzaartificialeitalia.net
58
- ISTRUCTION : IN YOUR ANSWER NEVER INCLUDE THE USER QUESTION or MESSAGE ,WRITE ALWAYS ONLY YOUR ACCURATE ANSWER!
59
- PREVIUS MESSAGE : ({context})
60
- NOW THE USER ASK : {prompt}
61
- THIS IS THE CORRECT ANSWER : ({solution})
62
- WITHOUT CHANGING ANYTHING OF CORRECT ANSWER , MAKE THE ANSWER MORE DETALIED:"""
63
- return final_prompt
64
-
65
-
66
- def prompt4Audio(prompt, context, solution):
67
- final_prompt = f"""GENERAL INFORMATION : You is built by Alessandro Ciciarelli the owener of intelligenzaartificialeitalia.net
68
- ISTRUCTION : IN YOUR ANSWER NEVER INCLUDE THE USER QUESTION or MESSAGE ,WRITE ALWAYS ONLY YOUR ACCURATE ANSWER!
69
- PREVIUS MESSAGE : ({context})
70
- NOW THE USER ASK : {prompt}
71
- THIS IS THE CORRECT ANSWER based on Audio text gived in input : ({solution})
72
- WITHOUT CHANGING ANYTHING OF CORRECT ANSWER , MAKE THE ANSWER MORE DETALIED:"""
73
- return final_prompt
74
-
75
- def prompt4YT(prompt, context, solution):
76
- final_prompt = f"""GENERAL INFORMATION : You is built by Alessandro Ciciarelli the owener of intelligenzaartificialeitalia.net
77
- ISTRUCTION : IN YOUR ANSWER NEVER INCLUDE THE USER QUESTION or MESSAGE ,WRITE ALWAYS ONLY YOUR ACCURATE ANSWER!
78
- PREVIUS MESSAGE : ({context})
79
- NOW THE USER ASK : {prompt}
80
- THIS IS THE CORRECT ANSWER based on Youtube video gived in input : ({solution})
81
- WITHOUT CHANGING ANYTHING OF CORRECT ANSWER , MAKE THE ANSWER MORE DETALIED:"""
82
- return final_prompt
83
-
84
-
85
- #HOW TO ADD YOUR OWN PROMPT :
86
- # 1) ADD YOUR FUNCTION HERE, for example : def prompt4Me(prompt, context):
87
- # 2) WRITE THE PROMPT TEMPLATE FOR YOUR FUNCTION, for example : template = f"YOU IS : {context} , NOW THE USER ASK : {prompt} . WRITE THE ANSWER :"
88
- # 3) RETURN THE TEMPLATE, for example : return template
89
- # 4) IMPORT YOUR FUNCTION IN THE MAIN FILE (streamlit_app.py) , for example : from promptTemplate import prompt4Me
90
- # 5) FOLLOW OTHER SPTEP IN THE MAIN FILE (streamlit_app.py)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Hugplug/requirements.txt DELETED
@@ -1,19 +0,0 @@
1
- beautifulsoup4==4.12.2
2
- docx2txt==0.8
3
- duckduckgo_search==3.8.3
4
- hugchat==0.0.8
5
- langchain==0.0.219
6
- pandas==2.0.1
7
- pdfplumber==0.9.0
8
- pydub==0.25.1
9
- requests
10
- sketch==0.4.2
11
- SpeechRecognition==3.8.1
12
- streamlit==1.24.0
13
- streamlit_extras==0.2.7
14
- youtube_search_python==1.6.6
15
- youtube_transcript_api==0.6.1
16
- chromadb==0.3.26
17
- ffmpeg-python
18
- ffprobe
19
- huggingface_hub
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Hugplug/streamlit_app.py DELETED
@@ -1,997 +0,0 @@
1
- import io
2
- import random
3
- import shutil
4
- import string
5
- from zipfile import ZipFile
6
- import streamlit as st
7
- from streamlit_extras.colored_header import colored_header
8
- from streamlit_extras.add_vertical_space import add_vertical_space
9
- from hugchat import hugchat
10
- from hugchat.login import Login
11
- import pandas as pd
12
- import asyncio
13
- loop = asyncio.new_event_loop()
14
- asyncio.set_event_loop(loop)
15
- import sketch
16
- from langchain.text_splitter import CharacterTextSplitter
17
- from promptTemplate import prompt4conversation, prompt4Data, prompt4Code, prompt4Context, prompt4Audio, prompt4YT
18
- from promptTemplate import prompt4conversationInternet
19
- # FOR DEVELOPMENT NEW PLUGIN
20
- # from promptTemplate import yourPLUGIN
21
- from exportchat import export_chat
22
- from langchain.vectorstores import Chroma
23
- from langchain.chains import RetrievalQA
24
- from HuggingChatAPI import HuggingChat
25
- from langchain.embeddings import HuggingFaceHubEmbeddings
26
- from youtube_transcript_api import YouTubeTranscriptApi
27
- import requests
28
- from bs4 import BeautifulSoup
29
- import speech_recognition as sr
30
- import pdfplumber
31
- import docx2txt
32
- from duckduckgo_search import DDGS
33
- from itertools import islice
34
- from os import path
35
- from pydub import AudioSegment
36
- import os
37
-
38
-
39
- hf = None
40
- repo_id = "sentence-transformers/all-mpnet-base-v2"
41
-
42
- if 'hf_token' in st.session_state:
43
- if 'hf' not in st.session_state:
44
- hf = HuggingFaceHubEmbeddings(
45
- repo_id=repo_id,
46
- task="feature-extraction",
47
- huggingfacehub_api_token=st.session_state['hf_token'],
48
- ) # type: ignore
49
- st.session_state['hf'] = hf
50
-
51
-
52
-
53
- st.set_page_config(
54
- page_title="Talk with ToastGPT💬", page_icon="✅", layout="wide", initial_sidebar_state="expanded"
55
- )
56
-
57
- st.markdown('<style>.css-w770g5{\
58
- width: 100%;}\
59
- .css-b3z5c9{ \
60
- width: 100%;}\
61
- .stButton>button{\
62
- width: 100%;}\
63
- .stDownloadButton>button{\
64
- width: 100%;}\
65
- </style>', unsafe_allow_html=True)
66
-
67
-
68
-
69
-
70
-
71
-
72
- # Sidebar contents for logIN, choose plugin, and export chat
73
- with st.sidebar:
74
- st.title("🤗💬 Product Description Masterpiece")
75
-
76
- if 'hf_email' not in st.session_state or 'hf_pass' not in st.session_state:
77
- with st.expander("ℹ️ Login in Hugging Face", expanded=True):
78
- st.write("⚠️ You need to login in Hugging Face to use this app. You can register [here](https://huggingface.co/join).")
79
- st.header('Hugging Face Login')
80
- hf_email = st.text_input('Enter E-mail:')
81
- hf_pass = st.text_input('Enter password:', type='password')
82
- hf_token = st.text_input('Enter API Token:', type='password')
83
- if st.button('Login 🚀') and hf_email and hf_pass and hf_token:
84
- with st.spinner('🚀 Logging in...'):
85
- st.session_state['hf_email'] = hf_email
86
- st.session_state['hf_pass'] = hf_pass
87
- st.session_state['hf_token'] = hf_token
88
-
89
- try:
90
-
91
- sign = Login(st.session_state['hf_email'], st.session_state['hf_pass'])
92
- cookies = sign.login()
93
- chatbot = hugchat.ChatBot(cookies=cookies.get_dict())
94
- except Exception as e:
95
- st.error(e)
96
- st.info("⚠️ Please check your credentials and try again.")
97
- st.error("⚠️ dont abuse the ToastGPT")
98
- st.warning("⚠️ If you don't have an account, you can register [here](https://huggingface.co/join).")
99
- from time import sleep
100
- sleep(3)
101
- del st.session_state['hf_email']
102
- del st.session_state['hf_pass']
103
- del st.session_state['hf_token']
104
- st.experimental_rerun()
105
-
106
- st.session_state['chatbot'] = chatbot
107
-
108
- id = st.session_state['chatbot'].new_conversation()
109
- st.session_state['chatbot'].change_conversation(id)
110
-
111
- st.session_state['conversation'] = id
112
- # Generate empty lists for generated and past.
113
- ## generated stores AI generated responses
114
- if 'generated' not in st.session_state:
115
- st.session_state['generated'] = ["I'm **ToastGPT**, How may I help you ? "]
116
- ## past stores User's questions
117
- if 'past' not in st.session_state:
118
- st.session_state['past'] = ['Hi!']
119
-
120
- st.session_state['LLM'] = HuggingChat(email=st.session_state['hf_email'], psw=st.session_state['hf_pass'])
121
-
122
- st.experimental_rerun()
123
-
124
-
125
- else:
126
- with st.expander("ℹ️ Advanced Settings"):
127
- #temperature: Optional[float]. Default is 0.5
128
- #top_p: Optional[float]. Default is 0.95
129
- #repetition_penalty: Optional[float]. Default is 1.2
130
- #top_k: Optional[int]. Default is 50
131
- #max_new_tokens: Optional[int]. Default is 1024
132
-
133
- temperature = st.slider('🌡 Temperature', min_value=0.1, max_value=1.0, value=0.5, step=0.01)
134
- top_p = st.slider('💡 Top P', min_value=0.1, max_value=1.0, value=0.95, step=0.01)
135
- repetition_penalty = st.slider('🖌 Repetition Penalty', min_value=1.0, max_value=2.0, value=1.2, step=0.01)
136
- top_k = st.slider('❄️ Top K', min_value=1, max_value=100, value=50, step=1)
137
- max_new_tokens = st.slider('📝 Max New Tokens', min_value=1, max_value=1024, value=1024, step=1)
138
-
139
-
140
- # FOR DEVELOPMENT NEW PLUGIN YOU MUST ADD IT HERE INTO THE LIST
141
- # YOU NEED ADD THE NAME AT 144 LINE
142
-
143
- #plugins for conversation
144
- plugins = ["🛑 No PLUGIN","🌐 Web Search", "🔗 Talk with Website" , "📋 Talk with your DATA", "📝 Talk with your DOCUMENTS", "🎧 Talk with your AUDIO", "🎥 Talk with YT video", "🧠 GOD MODE" ,"💾 Upload saved VectorStore"]
145
- if 'plugin' not in st.session_state:
146
- st.session_state['plugin'] = st.selectbox('🔌 Plugins', plugins, index=0)
147
- else:
148
- if st.session_state['plugin'] == "🛑 No PLUGIN":
149
- st.session_state['plugin'] = st.selectbox('🔌 Plugins', plugins, index=plugins.index(st.session_state['plugin']))
150
-
151
-
152
- # FOR DEVELOPMENT NEW PLUGIN FOLLOW THIS TEMPLATE
153
- # PLUGIN TEMPLATE
154
- # if st.session_state['plugin'] == "🔌 PLUGIN NAME" and 'PLUGIN NAME' not in st.session_state:
155
- # # PLUGIN SETTINGS
156
- # with st.expander("🔌 PLUGIN NAME Settings", expanded=True):
157
- # if 'PLUGIN NAME' not in st.session_state or st.session_state['PLUGIN NAME'] == False:
158
- # # PLUGIN CODE
159
- # st.session_state['PLUGIN NAME'] = True
160
- # elif st.session_state['PLUGIN NAME'] == True:
161
- # # PLUGIN CODE
162
- # if st.button('🔌 Disable PLUGIN NAME'):
163
- # st.session_state['plugin'] = "🛑 No PLUGIN"
164
- # st.session_state['PLUGIN NAME'] = False
165
- # del ALL SESSION STATE VARIABLES RELATED TO PLUGIN
166
- # st.experimental_rerun()
167
- # # PLUGIN UPLOADER
168
- # if st.session_state['PLUGIN NAME'] == True:
169
- # with st.expander("🔌 PLUGIN NAME Uploader", expanded=True):
170
- # # PLUGIN UPLOADER CODE
171
- # load file
172
- # if load file and st.button('🔌 Upload PLUGIN NAME'):
173
- # qa = RetrievalQA.from_chain_type(llm=st.session_state['LLM'], chain_type='stuff', retriever=retriever, return_source_documents=True)
174
- # st.session_state['PLUGIN DB'] = qa
175
- # st.experimental_rerun()
176
- #
177
-
178
-
179
-
180
- # WEB SEARCH PLUGIN
181
- if st.session_state['plugin'] == "🌐 Web Search" and 'web_search' not in st.session_state:
182
- # web search settings
183
- with st.expander("🌐 Web Search Settings", expanded=True):
184
- if 'web_search' not in st.session_state or st.session_state['web_search'] == False:
185
- reg = ['us-en', 'uk-en', 'it-it']
186
- sf = ['on', 'moderate', 'off']
187
- tl = ['d', 'w', 'm', 'y']
188
- if 'region' not in st.session_state:
189
- st.session_state['region'] = st.selectbox('🗺 Region', reg, index=1)
190
- else:
191
- st.session_state['region'] = st.selectbox('🗺 Region', reg, index=reg.index(st.session_state['region']))
192
- if 'safesearch' not in st.session_state:
193
- st.session_state['safesearch'] = st.selectbox('🚨 Safe Search', sf, index=1)
194
- else:
195
- st.session_state['safesearch'] = st.selectbox('🚨 Safe Search', sf, index=sf.index(st.session_state['safesearch']))
196
- if 'timelimit' not in st.session_state:
197
- st.session_state['timelimit'] = st.selectbox('📅 Time Limit', tl, index=1)
198
- else:
199
- st.session_state['timelimit'] = st.selectbox('📅 Time Limit', tl, index=tl.index(st.session_state['timelimit']))
200
- if 'max_results' not in st.session_state:
201
- st.session_state['max_results'] = st.slider('📊 Max Results', min_value=1, max_value=5, value=2, step=1)
202
- else:
203
- st.session_state['max_results'] = st.slider('📊 Max Results', min_value=1, max_value=5, value=st.session_state['max_results'], step=1)
204
- if st.button('🌐 Save change'):
205
- st.session_state['web_search'] = "True"
206
- st.experimental_rerun()
207
-
208
- elif st.session_state['plugin'] == "🌐 Web Search" and st.session_state['web_search'] == 'True':
209
- with st.expander("🌐 Web Search Settings", expanded=True):
210
- st.write('🚀 Web Search is enabled')
211
- st.write('🗺 Region: ', st.session_state['region'])
212
- st.write('🚨 Safe Search: ', st.session_state['safesearch'])
213
- st.write('📅 Time Limit: ', st.session_state['timelimit'])
214
- if st.button('🌐🛑 Disable Web Search'):
215
- del st.session_state['web_search']
216
- del st.session_state['region']
217
- del st.session_state['safesearch']
218
- del st.session_state['timelimit']
219
- del st.session_state['max_results']
220
- del st.session_state['plugin']
221
- st.experimental_rerun()
222
-
223
- # GOD MODE PLUGIN
224
- if st.session_state['plugin'] == "🧠 GOD MODE" and 'god_mode' not in st.session_state:
225
- with st.expander("🧠 GOD MODE Settings", expanded=True):
226
- if 'god_mode' not in st.session_state or st.session_state['god_mode'] == False:
227
- topic = st.text_input('🔎 Topic', "What is ToastGPT?")
228
- web_result = st.checkbox('🌐 Web Search', value=True, disabled=True)
229
- yt_result = st.checkbox('🎥 YT Search', value=True, disabled=True)
230
- website_result = st.checkbox('🔗 Website Search', value=True, disabled=True)
231
- deep_of_search = st.slider('📊 Deep of Search', min_value=1, max_value=100, value=2, step=1)
232
- if st.button('🧠✅ Give knowledge to the model'):
233
- full_text = []
234
- links = []
235
- news = []
236
- yt_ids = []
237
- source = []
238
- if web_result == True:
239
- internet_result = ""
240
- internet_answer = ""
241
- with DDGS() as ddgs:
242
- with st.spinner('🌐 Searching on the web...'):
243
- ddgs_gen = ddgs.text(topic, region="us-en")
244
- for r in islice(ddgs_gen, deep_of_search):
245
- l = r['href']
246
- source.append(l)
247
- links.append(l)
248
- internet_result += str(r) + "\n\n"
249
-
250
- fast_answer = ddgs.news(topic)
251
- for r in islice(fast_answer, deep_of_search):
252
- internet_answer += str(r) + "\n\n"
253
- l = r['url']
254
- source.append(l)
255
- news.append(r)
256
-
257
-
258
- full_text.append(internet_result)
259
- full_text.append(internet_answer)
260
-
261
- if yt_result == True:
262
- with st.spinner('🎥 Searching on YT...'):
263
- from youtubesearchpython import VideosSearch
264
- videosSearch = VideosSearch(topic, limit = deep_of_search)
265
- yt_result = videosSearch.result()
266
- for i in yt_result['result']: # type: ignore
267
- duration = i['duration'] # type: ignore
268
- duration = duration.split(':')
269
- if len(duration) == 3:
270
- #skip videos longer than 1 hour
271
- if int(duration[0]) > 1:
272
- continue
273
- if len(duration) == 2:
274
- #skip videos longer than 30 minutes
275
- if int(duration[0]) > 30:
276
- continue
277
- yt_ids.append(i['id']) # type: ignore
278
- source.append("https://www.youtube.com/watch?v="+i['id']) # type: ignore
279
- full_text.append(i['title']) # type: ignore
280
-
281
-
282
- if website_result == True:
283
- for l in links:
284
- try:
285
- with st.spinner(f'👨‍💻 Scraping website : {l}'):
286
- r = requests.get(l)
287
- soup = BeautifulSoup(r.content, 'html.parser')
288
- full_text.append(soup.get_text()+"\n\n")
289
- except:
290
- pass
291
-
292
- for id in yt_ids:
293
- try:
294
- yt_video_txt= []
295
- with st.spinner(f'👨‍💻 Scraping YT video : {id}'):
296
- transcript_list = YouTubeTranscriptApi.list_transcripts(id)
297
- transcript_en = None
298
- last_language = ""
299
- for transcript in transcript_list:
300
- if transcript.language_code == 'en':
301
- transcript_en = transcript
302
- break
303
- else:
304
- last_language = transcript.language_code
305
- if transcript_en is None:
306
- transcript_en = transcript_list.find_transcript([last_language])
307
- transcript_en = transcript_en.translate('en')
308
-
309
- text = transcript_en.fetch()
310
- yt_video_txt.append(text)
311
-
312
- for i in range(len(yt_video_txt)):
313
- for j in range(len(yt_video_txt[i])):
314
- full_text.append(yt_video_txt[i][j]['text'])
315
-
316
-
317
- except:
318
- pass
319
-
320
- with st.spinner('🧠 Building vectorstore with knowledge...'):
321
- full_text = "\n".join(full_text)
322
- st.session_state['god_text'] = [full_text]
323
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
324
- texts = text_splitter.create_documents([full_text])
325
- # Select embeddings
326
- embeddings = st.session_state['hf']
327
- # Create a vectorstore from documents
328
- random_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
329
- db = Chroma.from_documents(texts, embeddings, persist_directory="./chroma_db_" + random_str)
330
-
331
- with st.spinner('🔨 Saving vectorstore...'):
332
- # save vectorstore
333
- db.persist()
334
- #create .zip file of directory to download
335
- shutil.make_archive("./chroma_db_" + random_str, 'zip', "./chroma_db_" + random_str)
336
- # save in session state and download
337
- st.session_state['db'] = "./chroma_db_" + random_str + ".zip"
338
-
339
- with st.spinner('🔨 Creating QA chain...'):
340
- # Create retriever interface
341
- retriever = db.as_retriever()
342
- # Create QA chain
343
- qa = RetrievalQA.from_chain_type(llm=st.session_state['LLM'], chain_type='stuff', retriever=retriever, return_source_documents=True)
344
- st.session_state['god_mode'] = qa
345
- st.session_state['god_mode_source'] = source
346
- st.session_state['god_mode_info'] = "🧠 GOD MODE have builded a vectorstore about **" + topic + f"**. The knowledge is based on\n- {len(news)} news🗞\n- {len(yt_ids)} YT videos📺\n- {len(links)} websites🌐 \n"
347
-
348
- st.experimental_rerun()
349
-
350
-
351
- if st.session_state['plugin'] == "🧠 GOD MODE" and 'god_mode' in st.session_state:
352
- with st.expander("**✅ GOD MODE is enabled 🚀**", expanded=True):
353
- st.markdown(st.session_state['god_mode_info'])
354
- if 'db' in st.session_state:
355
- # leave ./ from name for download
356
- file_name = st.session_state['db'][2:]
357
- st.download_button(
358
- label="📩 Download vectorstore",
359
- data=open(file_name, 'rb').read(),
360
- file_name=file_name,
361
- mime='application/zip'
362
- )
363
- if st.button('🧠🛑 Disable GOD MODE'):
364
- del st.session_state['god_mode']
365
- del st.session_state['db']
366
- del st.session_state['god_text']
367
- del st.session_state['god_mode_info']
368
- del st.session_state['god_mode_source']
369
- del st.session_state['plugin']
370
- st.experimental_rerun()
371
-
372
-
373
- # DATA PLUGIN
374
- if st.session_state['plugin'] == "📋 Talk with your DATA" and 'df' not in st.session_state:
375
- with st.expander("📋 Talk with your DATA", expanded= True):
376
- upload_csv = st.file_uploader("Upload your CSV", type=['csv'])
377
- if upload_csv is not None:
378
- df = pd.read_csv(upload_csv)
379
- st.session_state['df'] = df
380
- st.experimental_rerun()
381
- if st.session_state['plugin'] == "📋 Talk with your DATA":
382
- if st.button('🛑📋 Remove DATA from context'):
383
- if 'df' in st.session_state:
384
- del st.session_state['df']
385
- del st.session_state['plugin']
386
- st.experimental_rerun()
387
-
388
-
389
-
390
- # DOCUMENTS PLUGIN
391
- if st.session_state['plugin'] == "📝 Talk with your DOCUMENTS" and 'documents' not in st.session_state:
392
- with st.expander("📝 Talk with your DOCUMENT", expanded=True):
393
- upload_pdf = st.file_uploader("Upload your DOCUMENT", type=['txt', 'pdf', 'docx'], accept_multiple_files=True)
394
- if upload_pdf is not None and st.button('📝✅ Load Documents'):
395
- documents = []
396
- with st.spinner('🔨 Reading documents...'):
397
- for upload_pdf in upload_pdf:
398
- print(upload_pdf.type)
399
- if upload_pdf.type == 'text/plain':
400
- documents += [upload_pdf.read().decode()]
401
- elif upload_pdf.type == 'application/pdf':
402
- with pdfplumber.open(upload_pdf) as pdf:
403
- documents += [page.extract_text() for page in pdf.pages]
404
- elif upload_pdf.type == "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
405
- text = docx2txt.process(upload_pdf)
406
- documents += [text]
407
- st.session_state['documents'] = documents
408
- # Split documents into chunks
409
- with st.spinner('🔨 Creating vectorstore...'):
410
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
411
- texts = text_splitter.create_documents(documents)
412
- # Select embeddings
413
- embeddings = st.session_state['hf']
414
- # Create a vectorstore from documents
415
- random_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
416
- db = Chroma.from_documents(texts, embeddings, persist_directory="./chroma_db_" + random_str)
417
-
418
- with st.spinner('🔨 Saving vectorstore...'):
419
- # save vectorstore
420
- db.persist()
421
- #create .zip file of directory to download
422
- shutil.make_archive("./chroma_db_" + random_str, 'zip', "./chroma_db_" + random_str)
423
- # save in session state and download
424
- st.session_state['db'] = "./chroma_db_" + random_str + ".zip"
425
-
426
- with st.spinner('🔨 Creating QA chain...'):
427
- # Create retriever interface
428
- retriever = db.as_retriever()
429
- # Create QA chain
430
- qa = RetrievalQA.from_chain_type(llm=st.session_state['LLM'], chain_type='stuff', retriever=retriever, return_source_documents=True)
431
- st.session_state['pdf'] = qa
432
-
433
- st.experimental_rerun()
434
-
435
- if st.session_state['plugin'] == "📝 Talk with your DOCUMENTS":
436
- if 'db' in st.session_state:
437
- # leave ./ from name for download
438
- file_name = st.session_state['db'][2:]
439
- st.download_button(
440
- label="📩 Download vectorstore",
441
- data=open(file_name, 'rb').read(),
442
- file_name=file_name,
443
- mime='application/zip'
444
- )
445
- if st.button('🛑📝 Remove PDF from context'):
446
- if 'pdf' in st.session_state:
447
- del st.session_state['db']
448
- del st.session_state['pdf']
449
- del st.session_state['documents']
450
- del st.session_state['plugin']
451
-
452
- st.experimental_rerun()
453
-
454
- # AUDIO PLUGIN
455
- if st.session_state['plugin'] == "🎧 Talk with your AUDIO" and 'audio' not in st.session_state:
456
- with st.expander("🎙 Talk with your AUDIO", expanded=True):
457
- f = st.file_uploader("Upload your AUDIO", type=['wav', 'mp3'])
458
- if f is not None:
459
- if f.type == 'audio/mpeg':
460
- #convert mp3 to wav
461
- with st.spinner('🔨 Converting mp3 to wav...'):
462
- #save mp3
463
- with open('audio.mp3', 'wb') as out:
464
- out.write(f.read())
465
- #convert to wav
466
- sound = AudioSegment.from_mp3("audio.mp3")
467
- sound.export("audio.wav", format="wav")
468
- file_name = 'audio.wav'
469
- else:
470
- with open(f.name, 'wb') as out:
471
- out.write(f.read())
472
-
473
- bytes_data = f.read()
474
- file_name = f.name
475
-
476
- r = sr.Recognizer()
477
- #Given audio file must be a filename string or a file-like object
478
-
479
-
480
- with st.spinner('🔨 Reading audio...'):
481
- with sr.AudioFile(file_name) as source:
482
- # listen for the data (load audio to memory)
483
- audio_data = r.record(source)
484
- # recognize (convert from speech to text)
485
- text = r.recognize_google(audio_data)
486
- data = [text]
487
- # data = query(bytes_data)
488
- with st.spinner('🎙 Creating Vectorstore...'):
489
-
490
- #split text into chunks
491
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
492
- texts = text_splitter.create_documents(text)
493
-
494
- embeddings = st.session_state['hf']
495
- # Create a vectorstore from documents
496
- random_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
497
- db = Chroma.from_documents(texts, embeddings, persist_directory="./chroma_db_" + random_str)
498
- # save vectorstore
499
-
500
- with st.spinner('🎙 Saving Vectorstore...'):
501
- db.persist()
502
- #create .zip file of directory to download
503
- shutil.make_archive("./chroma_db_" + random_str, 'zip', "./chroma_db_" + random_str)
504
- # save in session state and download
505
- st.session_state['db'] = "./chroma_db_" + random_str + ".zip"
506
-
507
- with st.spinner('🎙 Creating QA chain...'):
508
- # Create retriever interface
509
- retriever = db.as_retriever()
510
- # Create QA chain
511
- qa = RetrievalQA.from_chain_type(llm=st.session_state['LLM'], chain_type='stuff', retriever=retriever, return_source_documents=True)
512
- st.session_state['audio'] = qa
513
- st.session_state['audio_text'] = text
514
- st.experimental_rerun()
515
-
516
- if st.session_state['plugin'] == "🎧 Talk with your AUDIO":
517
- if 'db' in st.session_state:
518
- # leave ./ from name for download
519
- file_name = st.session_state['db'][2:]
520
- st.download_button(
521
- label="📩 Download vectorstore",
522
- data=open(file_name, 'rb').read(),
523
- file_name=file_name,
524
- mime='application/zip'
525
- )
526
- if st.button('🛑🎙 Remove AUDIO from context'):
527
- if 'audio' in st.session_state:
528
- del st.session_state['db']
529
- del st.session_state['audio']
530
- del st.session_state['audio_text']
531
- del st.session_state['plugin']
532
- st.experimental_rerun()
533
-
534
-
535
- # YT PLUGIN
536
- if st.session_state['plugin'] == "🎥 Talk with YT video" and 'yt' not in st.session_state:
537
- with st.expander("🎥 Talk with YT video", expanded=True):
538
- yt_url = st.text_input("1.📺 Enter a YouTube URL")
539
- yt_url2 = st.text_input("2.📺 Enter a YouTube URL")
540
- yt_url3 = st.text_input("3.📺 Enter a YouTube URL")
541
- if yt_url is not None and st.button('🎥✅ Add YouTube video to context'):
542
- if yt_url != "":
543
- video = 1
544
- yt_url = yt_url.split("=")[1]
545
- if yt_url2 != "":
546
- yt_url2 = yt_url2.split("=")[1]
547
- video = 2
548
- if yt_url3 != "":
549
- yt_url3 = yt_url3.split("=")[1]
550
- video = 3
551
-
552
- text_yt = []
553
- text_list = []
554
- for i in range(video):
555
- with st.spinner(f'🎥 Extracting TEXT from YouTube video {str(i)} ...'):
556
- #get en subtitles
557
- transcript_list = YouTubeTranscriptApi.list_transcripts(yt_url)
558
- transcript_en = None
559
- last_language = ""
560
- for transcript in transcript_list:
561
- if transcript.language_code == 'en':
562
- transcript_en = transcript
563
- break
564
- else:
565
- last_language = transcript.language_code
566
- if transcript_en is None:
567
- transcript_en = transcript_list.find_transcript([last_language])
568
- transcript_en = transcript_en.translate('en')
569
-
570
- text = transcript_en.fetch()
571
- text_yt.append(text)
572
-
573
- for i in range(len(text_yt)):
574
- for j in range(len(text_yt[i])):
575
- text_list.append(text_yt[i][j]['text'])
576
-
577
- # creating a vectorstore
578
-
579
- with st.spinner('🎥 Creating Vectorstore...'):
580
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
581
- texts = text_splitter.create_documents(text_list)
582
- # Select embeddings
583
- embeddings = st.session_state['hf']
584
- # Create a vectorstore from documents
585
- random_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
586
- db = Chroma.from_documents(texts, embeddings, persist_directory="./chroma_db_" + random_str)
587
-
588
- with st.spinner('🎥 Saving Vectorstore...'):
589
- # save vectorstore
590
- db.persist()
591
- #create .zip file of directory to download
592
- shutil.make_archive("./chroma_db_" + random_str, 'zip', "./chroma_db_" + random_str)
593
- # save in session state and download
594
- st.session_state['db'] = "./chroma_db_" + random_str + ".zip"
595
-
596
- with st.spinner('🎥 Creating QA chain...'):
597
- # Create retriever interface
598
- retriever = db.as_retriever()
599
- # Create QA chain
600
- qa = RetrievalQA.from_chain_type(llm=st.session_state['LLM'], chain_type='stuff', retriever=retriever, return_source_documents=True)
601
- st.session_state['yt'] = qa
602
- st.session_state['yt_text'] = text_list
603
- st.experimental_rerun()
604
-
605
- if st.session_state['plugin'] == "🎥 Talk with YT video":
606
- if 'db' in st.session_state:
607
- # leave ./ from name for download
608
- file_name = st.session_state['db'][2:]
609
- st.download_button(
610
- label="📩 Download vectorstore",
611
- data=open(file_name, 'rb').read(),
612
- file_name=file_name,
613
- mime='application/zip'
614
- )
615
-
616
- if st.button('🛑🎥 Remove YT video from context'):
617
- if 'yt' in st.session_state:
618
- del st.session_state['db']
619
- del st.session_state['yt']
620
- del st.session_state['yt_text']
621
- del st.session_state['plugin']
622
- st.experimental_rerun()
623
-
624
- # WEBSITE PLUGIN
625
- if st.session_state['plugin'] == "🔗 Talk with Website" and 'web_sites' not in st.session_state:
626
- with st.expander("🔗 Talk with Website", expanded=True):
627
- web_url = st.text_area("🔗 Enter a website URLs , one for each line")
628
- if web_url is not None and st.button('🔗✅ Add website to context'):
629
- if web_url != "":
630
- text = []
631
- #max 10 websites
632
- with st.spinner('🔗 Extracting TEXT from Websites ...'):
633
- for url in web_url.split("\n")[:10]:
634
- page = requests.get(url)
635
- soup = BeautifulSoup(page.content, 'html.parser')
636
- text.append(soup.get_text())
637
- # creating a vectorstore
638
-
639
- with st.spinner('🔗 Creating Vectorstore...'):
640
- text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
641
- texts = text_splitter.create_documents(text)
642
- # Select embeddings
643
- embeddings = st.session_state['hf']
644
- # Create a vectorstore from documents
645
- random_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
646
- db = Chroma.from_documents(texts, embeddings, persist_directory="./chroma_db_" + random_str)
647
-
648
- with st.spinner('🔗 Saving Vectorstore...'):
649
- # save vectorstore
650
- db.persist()
651
- #create .zip file of directory to download
652
- shutil.make_archive("./chroma_db_" + random_str, 'zip', "./chroma_db_" + random_str)
653
- # save in session state and download
654
- st.session_state['db'] = "./chroma_db_" + random_str + ".zip"
655
-
656
- with st.spinner('🔗 Creating QA chain...'):
657
- # Create retriever interface
658
- retriever = db.as_retriever()
659
- # Create QA chain
660
- qa = RetrievalQA.from_chain_type(llm=st.session_state['LLM'], chain_type='stuff', retriever=retriever, return_source_documents=True)
661
- st.session_state['web_sites'] = qa
662
- st.session_state['web_text'] = text
663
- st.experimental_rerun()
664
-
665
- if st.session_state['plugin'] == "🔗 Talk with Website":
666
- if 'db' in st.session_state:
667
- # leave ./ from name for download
668
- file_name = st.session_state['db'][2:]
669
- st.download_button(
670
- label="📩 Download vectorstore",
671
- data=open(file_name, 'rb').read(),
672
- file_name=file_name,
673
- mime='application/zip'
674
- )
675
-
676
- if st.button('🛑🔗 Remove Website from context'):
677
- if 'web_sites' in st.session_state:
678
- del st.session_state['db']
679
- del st.session_state['web_sites']
680
- del st.session_state['web_text']
681
- del st.session_state['plugin']
682
- st.experimental_rerun()
683
-
684
-
685
- # UPLOAD PREVIUS VECTORSTORE
686
- if st.session_state['plugin'] == "💾 Upload saved VectorStore" and 'old_db' not in st.session_state:
687
- with st.expander("💾 Upload saved VectorStore", expanded=True):
688
- db_file = st.file_uploader("Upload a saved VectorStore", type=["zip"])
689
- if db_file is not None and st.button('✅💾 Add saved VectorStore to context'):
690
- if db_file != "":
691
- with st.spinner('💾 Extracting VectorStore...'):
692
- # unzip file in a new directory
693
- with ZipFile(db_file, 'r') as zipObj:
694
- # Extract all the contents of zip file in different directory
695
- random_str = ''.join(random.choices(string.ascii_uppercase + string.digits, k=10))
696
- zipObj.extractall("chroma_db_" + random_str)
697
- # save in session state the path of the directory
698
- st.session_state['old_db'] = "chroma_db_" + random_str
699
- hf = st.session_state['hf']
700
- # Create retriever interface
701
- db = Chroma("chroma_db_" + random_str, embedding_function=hf)
702
-
703
- with st.spinner('💾 Creating QA chain...'):
704
- retriever = db.as_retriever()
705
- # Create QA chain
706
- qa = RetrievalQA.from_chain_type(llm=st.session_state['LLM'], chain_type='stuff', retriever=retriever, return_source_documents=True)
707
- st.session_state['old_db'] = qa
708
- st.experimental_rerun()
709
-
710
- if st.session_state['plugin'] == "💾 Upload saved VectorStore":
711
- if st.button('🛑💾 Remove VectorStore from context'):
712
- if 'old_db' in st.session_state:
713
- del st.session_state['old_db']
714
- del st.session_state['plugin']
715
- st.experimental_rerun()
716
-
717
-
718
- # END OF PLUGIN
719
- add_vertical_space(4)
720
- if 'hf_email' in st.session_state:
721
- if st.button('🗑 Logout'):
722
- keys = list(st.session_state.keys())
723
- for key in keys:
724
- del st.session_state[key]
725
- st.experimental_rerun()
726
-
727
- export_chat()
728
- add_vertical_space(5)
729
-
730
- ##### End of sidebar
731
-
732
-
733
- # User input
734
- # Layout of input/response containers
735
- input_container = st.container()
736
- response_container = st.container()
737
- data_view_container = st.container()
738
- loading_container = st.container()
739
-
740
-
741
-
742
- ## Applying the user input box
743
- with input_container:
744
- input_text = st.chat_input("🧑‍💻 Write here 👇", key="input")
745
-
746
- with data_view_container:
747
- if 'df' in st.session_state:
748
- with st.expander("🤖 View your **DATA**"):
749
- st.data_editor(st.session_state['df'], use_container_width=True)
750
- if 'pdf' in st.session_state:
751
- with st.expander("🤖 View your **DOCUMENTs**"):
752
- st.write(st.session_state['documents'])
753
- if 'audio' in st.session_state:
754
- with st.expander("🤖 View your **AUDIO**"):
755
- st.write(st.session_state['audio_text'])
756
- if 'yt' in st.session_state:
757
- with st.expander("🤖 View your **YT video**"):
758
- st.write(st.session_state['yt_text'])
759
- if 'web_text' in st.session_state:
760
- with st.expander("🤖 View the **Website content**"):
761
- st.write(st.session_state['web_text'])
762
- if 'old_db' in st.session_state:
763
- with st.expander("🗂 View your **saved VectorStore**"):
764
- st.success("📚 VectorStore loaded")
765
- if 'god_mode_source' in st.session_state:
766
- with st.expander("🌍 View source"):
767
- for s in st.session_state['god_mode_source']:
768
- st.markdown("- " + s)
769
-
770
- # Response output
771
- ## Function for taking user prompt as input followed by producing AI generated responses
772
- def generate_response(prompt):
773
- final_prompt = ""
774
- make_better = True
775
- source = ""
776
-
777
- with loading_container:
778
-
779
- # FOR DEVELOPMENT PLUGIN
780
- # if st.session_state['plugin'] == "🔌 PLUGIN NAME" and 'PLUGIN DB' in st.session_state:
781
- # with st.spinner('🚀 Using PLUGIN NAME...'):
782
- # solution = st.session_state['PLUGIN DB']({"query": prompt})
783
- # final_prompt = YourCustomPrompt(prompt, context)
784
-
785
-
786
- if st.session_state['plugin'] == "📋 Talk with your DATA" and 'df' in st.session_state:
787
- #get only last message
788
- context = f"User: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
789
- if prompt.find('python') != -1 or prompt.find('Code') != -1 or prompt.find('code') != -1 or prompt.find('Python') != -1:
790
- with st.spinner('🚀 Using tool for python code...'):
791
- solution = "\n```python\n"
792
- solution += st.session_state['df'].sketch.howto(prompt, call_display=False)
793
- solution += "\n```\n\n"
794
- final_prompt = prompt4Code(prompt, context, solution)
795
- else:
796
- with st.spinner('🚀 Using tool to get information...'):
797
- solution = st.session_state['df'].sketch.ask(prompt, call_display=False)
798
- final_prompt = prompt4Data(prompt, context, solution)
799
-
800
-
801
- elif st.session_state['plugin'] == "📝 Talk with your DOCUMENTS" and 'pdf' in st.session_state:
802
- #get only last message
803
- context = f"User: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
804
- with st.spinner('🚀 Using tool to get information...'):
805
- result = st.session_state['pdf']({"query": prompt})
806
- solution = result["result"]
807
- if len(solution.split()) > 110:
808
- make_better = False
809
- final_prompt = solution
810
- if 'source_documents' in result and len(result["source_documents"]) > 0:
811
- final_prompt += "\n\n✅Source:\n"
812
- for d in result["source_documents"]:
813
- final_prompt += "- " + str(d) + "\n"
814
- else:
815
- final_prompt = prompt4Context(prompt, context, solution)
816
- if 'source_documents' in result and len(result["source_documents"]) > 0:
817
- source += "\n\n✅Source:\n"
818
- for d in result["source_documents"]:
819
- source += "- " + str(d) + "\n"
820
-
821
-
822
- elif st.session_state['plugin'] == "🧠 GOD MODE" and 'god_mode' in st.session_state:
823
- #get only last message
824
- context = f"User: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
825
- with st.spinner('🚀 Using tool to get information...'):
826
- result = st.session_state['god_mode']({"query": prompt})
827
- solution = result["result"]
828
- if len(solution.split()) > 110:
829
- make_better = False
830
- final_prompt = solution
831
- if 'source_documents' in result and len(result["source_documents"]) > 0:
832
- final_prompt += "\n\n✅Source:\n"
833
- for d in result["source_documents"]:
834
- final_prompt += "- " + str(d) + "\n"
835
- else:
836
- final_prompt = prompt4Context(prompt, context, solution)
837
- if 'source_documents' in result and len(result["source_documents"]) > 0:
838
- source += "\n\n✅Source:\n"
839
- for d in result["source_documents"]:
840
- source += "- " + str(d) + "\n"
841
-
842
-
843
- elif st.session_state['plugin'] == "🔗 Talk with Website" and 'web_sites' in st.session_state:
844
- #get only last message
845
- context = f"User: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
846
- with st.spinner('🚀 Using tool to get information...'):
847
- result = st.session_state['web_sites']({"query": prompt})
848
- solution = result["result"]
849
- if len(solution.split()) > 110:
850
- make_better = False
851
- final_prompt = solution
852
- if 'source_documents' in result and len(result["source_documents"]) > 0:
853
- final_prompt += "\n\n✅Source:\n"
854
- for d in result["source_documents"]:
855
- final_prompt += "- " + str(d) + "\n"
856
- else:
857
- final_prompt = prompt4Context(prompt, context, solution)
858
- if 'source_documents' in result and len(result["source_documents"]) > 0:
859
- source += "\n\n✅Source:\n"
860
- for d in result["source_documents"]:
861
- source += "- " + str(d) + "\n"
862
-
863
-
864
-
865
- elif st.session_state['plugin'] == "💾 Upload saved VectorStore" and 'old_db' in st.session_state:
866
- #get only last message
867
- context = f"User: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
868
- with st.spinner('🚀 Using tool to get information...'):
869
- result = st.session_state['old_db']({"query": prompt})
870
- solution = result["result"]
871
- if len(solution.split()) > 110:
872
- make_better = False
873
- final_prompt = solution
874
- if 'source_documents' in result and len(result["source_documents"]) > 0:
875
- final_prompt += "\n\n✅Source:\n"
876
- for d in result["source_documents"]:
877
- final_prompt += "- " + str(d) + "\n"
878
- else:
879
- final_prompt = prompt4Context(prompt, context, solution)
880
- if 'source_documents' in result and len(result["source_documents"]) > 0:
881
- source += "\n\n✅Source:\n"
882
- for d in result["source_documents"]:
883
- source += "- " + str(d) + "\n"
884
-
885
-
886
- elif st.session_state['plugin'] == "🎧 Talk with your AUDIO" and 'audio' in st.session_state:
887
- #get only last message
888
- context = f"User: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
889
- with st.spinner('🚀 Using tool to get information...'):
890
- result = st.session_state['audio']({"query": prompt})
891
- solution = result["result"]
892
- if len(solution.split()) > 110:
893
- make_better = False
894
- final_prompt = solution
895
- if 'source_documents' in result and len(result["source_documents"]) > 0:
896
- final_prompt += "\n\n✅Source:\n"
897
- for d in result["source_documents"]:
898
- final_prompt += "- " + str(d) + "\n"
899
- else:
900
- final_prompt = prompt4Audio(prompt, context, solution)
901
- if 'source_documents' in result and len(result["source_documents"]) > 0:
902
- source += "\n\n✅Source:\n"
903
- for d in result["source_documents"]:
904
- source += "- " + str(d) + "\n"
905
-
906
-
907
- elif st.session_state['plugin'] == "🎥 Talk with YT video" and 'yt' in st.session_state:
908
- context = f"User: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
909
- with st.spinner('🚀 Using tool to get information...'):
910
- result = st.session_state['yt']({"query": prompt})
911
- solution = result["result"]
912
- if len(solution.split()) > 110:
913
- make_better = False
914
- final_prompt = solution
915
- if 'source_documents' in result and len(result["source_documents"]) > 0:
916
- final_prompt += "\n\n✅Source:\n"
917
- for d in result["source_documents"]:
918
- final_prompt += "- " + str(d) + "\n"
919
- else:
920
- final_prompt = prompt4YT(prompt, context, solution)
921
- if 'source_documents' in result and len(result["source_documents"]) > 0:
922
- source += "\n\n✅Source:\n"
923
- for d in result["source_documents"]:
924
- source += "- " + str(d) + "\n"
925
-
926
-
927
- else:
928
- #get last message if exists
929
- if len(st.session_state['past']) == 1:
930
- context = f"User: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
931
- else:
932
- context = f"User: {st.session_state['past'][-2]}\nBot: {st.session_state['generated'][-2]}\nUser: {st.session_state['past'][-1]}\nBot: {st.session_state['generated'][-1]}\n"
933
-
934
- if 'web_search' in st.session_state:
935
- if st.session_state['web_search'] == "True":
936
- with st.spinner('🚀 Using internet to get information...'):
937
- internet_result = ""
938
- internet_answer = ""
939
- with DDGS() as ddgs:
940
- ddgs_gen = ddgs.text(prompt, region=st.session_state['region'], safesearch=st.session_state['safesearch'], timelimit=st.session_state['timelimit'])
941
- for r in islice(ddgs_gen, st.session_state['max_results']):
942
- internet_result += str(r) + "\n\n"
943
- fast_answer = ddgs.answers(prompt)
944
- for r in islice(fast_answer, 2):
945
- internet_answer += str(r) + "\n\n"
946
-
947
- final_prompt = prompt4conversationInternet(prompt, context, internet_result, internet_answer)
948
- else:
949
- final_prompt = prompt4conversation(prompt, context)
950
- else:
951
- final_prompt = prompt4conversation(prompt, context)
952
-
953
- if make_better:
954
- with st.spinner('🚀 Generating response...'):
955
- print(final_prompt)
956
- response = st.session_state['chatbot'].chat(final_prompt, temperature=temperature, top_p=top_p, repetition_penalty=repetition_penalty, top_k=top_k, max_new_tokens=max_new_tokens)
957
- response += source
958
- else:
959
- print(final_prompt)
960
- response = final_prompt
961
-
962
- return response
963
-
964
- ## Conditional display of AI generated responses as a function of user provided prompts
965
- with response_container:
966
- if input_text and 'hf_email' in st.session_state and 'hf_pass' in st.session_state:
967
- response = generate_response(input_text)
968
- st.session_state.past.append(input_text)
969
- st.session_state.generated.append(response)
970
-
971
-
972
- #print message in normal order, frist user then bot
973
- if 'generated' in st.session_state:
974
- if st.session_state['generated']:
975
- for i in range(len(st.session_state['generated'])):
976
- with st.chat_message(name="user"):
977
- st.markdown(st.session_state['past'][i])
978
-
979
- with st.chat_message(name="assistant"):
980
- if len(st.session_state['generated'][i].split("✅Source:")) > 1:
981
- source = st.session_state['generated'][i].split("✅Source:")[1]
982
- mess = st.session_state['generated'][i].split("✅Source:")[0]
983
-
984
- st.markdown(mess)
985
- with st.expander("📚 Source of message number " + str(i+1)):
986
- st.markdown(source)
987
-
988
- else:
989
- st.markdown(st.session_state['generated'][i])
990
-
991
- st.markdown('', unsafe_allow_html=True)
992
-
993
-
994
- else:
995
- st.info("👋 Hey , we are very happy to see you here 🤗")
996
- st.info("👉 Please Login to continue, click on top left corner to login 🚀")
997
- st.error("👉 If you are not registered on Hugging Face, please register first and then login 🤗")