MatteoScript commited on
Commit
ed5749a
1 Parent(s): dce909d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +99 -73
app.py CHANGED
@@ -13,8 +13,6 @@ import requests
13
  from langchain_community.vectorstores import Chroma
14
  from langchain_community.embeddings import HuggingFaceEmbeddings
15
  import json
16
- from audio_recorder_streamlit import audio_recorder
17
- import speech_recognition as sr
18
  from googlesearch import search
19
  from bs4 import BeautifulSoup
20
  import PyPDF2
@@ -24,14 +22,40 @@ from youtube_transcript_api import YouTubeTranscriptApi
24
  import webbrowser
25
  from streamlit_javascript import st_javascript
26
  import datetime
 
27
 
28
  load_dotenv()
 
29
  URL_APP_SCRIPT = os.getenv('URL_APP_SCRIPT')
30
  URL_PROMPT = URL_APP_SCRIPT + '?IdFoglio=1cLw9q70BsPmxMBj9PIzgXtq6sm3X-GVBVnOB5wE8jr8'
31
  URL_DOCUMENTI = URL_APP_SCRIPT + '?IdSecondoFoglio=1cLw9q70BsPmxMBj9PIzgXtq6sm3X-GVBVnOB5wE8jr8'
32
  SYSTEM_PROMPT = ["Sei BonsiAI e mi aiuterai nelle mie richieste (Parla in ITALIANO)", "Esatto, sono BonsiAI. Di cosa hai bisogno?"]
33
- CHAT_BOTS = {"Mixtral 8x7B v0.1" :"mistralai/Mixtral-8x7B-Instruct-v0.1",
34
- "Mistral 7B v0.2" :"mistralai/Mistral-7B-Instruct-v0.2"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  option_personalizzata = {'Personalizzata': {'systemRole': 'Tu sei BONSI AI, il mio assistente personale della scuola superiore del Bonsignori. Aiutami in base alle mie esigenze',
36
  'systemStyle': 'Firmati sempre come BONSI AI. (scrivi in italiano)',
37
  'instruction': '',
@@ -70,6 +94,9 @@ def init_state() :
70
  if "repetion_penalty" not in st.session_state :
71
  st.session_state.repetion_penalty = 1
72
 
 
 
 
73
  if "chat_bot" not in st.session_state :
74
  st.session_state.chat_bot = "Mixtral 8x7B v0.1"
75
 
@@ -109,6 +136,9 @@ def init_state() :
109
  if "uploaded_files" not in st.session_state:
110
  st.session_state.uploaded_files = None
111
 
 
 
 
112
  if "urls" not in st.session_state:
113
  st.session_state.urls = [""] * 5
114
 
@@ -133,7 +163,7 @@ def init_state() :
133
  "Ultimo giorno": "qdr:d"
134
  }
135
 
136
- if not st.session_state.loaded_data and st.session_state.login_effettuato == True:
137
  place=st.empty()
138
  place=st.empty()
139
  with place:
@@ -149,7 +179,10 @@ def init_state() :
149
  documenti = {}
150
  if URL_REDIRECT != "http://localhost:8501/":
151
  documenti = requests.get(URL_DOCUMENTI).json()
152
- st.session_state.options = {**option_personalizzata, **option_leggiemail, **option_leggicalendar, **options}
 
 
 
153
  st.session_state.documenti = documenti
154
  st.session_state.loaded_data = True
155
  status.update(label="Caricamento Completato", state="complete", expanded=False)
@@ -200,9 +233,11 @@ def sidebar():
200
  st.session_state.selected_documento_key = st.selectbox('Documento', list(st.session_state.documenti.keys()))
201
  st.session_state.selected_documento = st.session_state.documenti.get(st.session_state.selected_documento_key, {})
202
  st.session_state.instruction = st.session_state.selected_documento.get('instruction', '')['Testo']
203
- st.session_state.split = st.slider(label="Pagine Suddivisione", min_value=1, max_value=30, value=30, help='Se il documento ha 100 pagine e suddivido per 20 pagine elaborerà la risposta 5 volte. Più alto è il numero e meno volte elaborerà ma la risposta sarà più imprecisa')
204
  else:
205
  st.session_state.instruction = st.session_state.selected_option.get('instruction', '')
 
 
 
206
  st.session_state.systemRole = st.session_state.selected_option.get('systemRole', '')
207
  st.session_state.systemRole = st.text_area("Descrizione", st.session_state.systemRole, help='Ruolo del chatbot e descrizione dell\'azione che deve svolgere')
208
  st.session_state.systemStyle = st.session_state.selected_option.get('systemStyle', '')
@@ -243,11 +278,17 @@ def sidebar():
243
 
244
  def model_settings():
245
  st.markdown("# Modello")
246
- st.session_state.chat_bot = st.sidebar.radio('Modello:', [key for key, value in CHAT_BOTS.items() ])
 
 
 
 
 
 
247
  st.session_state.numero_generazioni = st.slider(label="Generazioni", min_value = 1, max_value=10, value=1)
248
  st.session_state.enable_history = st.toggle("Storico Messaggi", value=True)
249
  st.session_state.temp = st.slider(label="Creatività", min_value=0.0, max_value=1.0, step=0.1, value=0.9)
250
- st.session_state.max_tokens = st.slider(label="Lunghezza Output", min_value = 2, max_value=2048, step= 32, value=1024)
251
  st.markdown("---")
252
 
253
  def export_settings():
@@ -261,40 +302,10 @@ def sidebar():
261
  with st.sidebar:
262
  retrieval_settings()
263
  model_settings()
264
- export_settings()
 
265
  st.markdown("""> **Creato da Matteo Bergamelli **""")
266
 
267
- def audioRec():
268
- st.session_state.audio_bytes = audio_recorder(text='', icon_size="3x")
269
- if st.session_state.audio_bytes:
270
- with open("./AUDIO.wav", "wb") as file:
271
- file.write(st.session_state.audio_bytes)
272
- wav = sr.AudioFile("./AUDIO.wav")
273
- with wav as source:
274
- recognizer_instance = sr.Recognizer()
275
- recognizer_instance.pause_threshold = 3.0
276
- audio = recognizer_instance.listen(source)
277
- print("Ok! sto ora elaborando il messaggio!")
278
- try:
279
- text = recognizer_instance.recognize_google(audio, language="it-IT")
280
- print(text)
281
- js = f"""
282
- <script>
283
- var chatInput = parent.document.querySelector('textarea[data-testid="stChatInput"]');
284
- var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
285
- nativeInputValueSetter.call(chatInput, "{text}");
286
- var event = new Event('input', {{ bubbles: true}});
287
- chatInput.dispatchEvent(event);
288
- var sendChat = parent.document.getElementsByClassName("st-emotion-cache-1621d17")[0]
289
- sendChat.click();
290
- var x = parent.document.querySelector('[title="st.iframe"]');
291
- x.style.display = "none";
292
- </script>
293
- """
294
- st.components.v1.html(js)
295
- except Exception as e:
296
- print(e)
297
-
298
  def header() :
299
  st.title("Bonsi A.I.", anchor=False)
300
  with st.expander("Cos'è BonsiAI?"):
@@ -390,9 +401,9 @@ def gen_online_prompt(prompt, top_k) :
390
  links.append((str(i) + '. ' + result['title'], result['description'] + '\n\n' + result['url']))
391
  return context, links
392
 
393
- def generate_chat_stream(prompt) :
394
- chat_stream = chat(prompt, st.session_state.history,chat_client=CHAT_BOTS[st.session_state.chat_bot] ,
395
- temperature=st.session_state.temp, max_new_tokens=st.session_state.max_tokens)
396
  return chat_stream
397
 
398
  def inserisci_istruzioni(prompt_originale):
@@ -421,9 +432,13 @@ def inserisci_istruzioni(prompt_originale):
421
  def stream_handler(chat_stream, placeholder) :
422
  full_response = ''
423
  for chunk in chat_stream :
424
- if chunk.token.text!='</s>' :
425
- full_response += chunk.token.text
426
- placeholder.markdown(full_response + "▌")
 
 
 
 
427
  placeholder.markdown(full_response)
428
  return full_response
429
 
@@ -444,17 +459,17 @@ def split_text(text, chunk_size):
444
  return testo_suddiviso
445
 
446
  init_state()
447
- if st.session_state.login_effettuato == False:
448
  connetti_google()
449
 
450
- if st.session_state.login_effettuato == True:
451
  st_javascript("localStorage.removeItem('token');")
452
  init_state()
453
  sidebar()
454
  header()
455
  chat_box()
456
 
457
- if prompt := st.chat_input("Chatta con BonsiAI..."):
458
  prompt_originale = prompt
459
  links = inserisci_istruzioni(prompt_originale)
460
  st.session_state.instruction+= ' \n\n' + st.session_state.testo_documenti
@@ -464,6 +479,8 @@ if st.session_state.login_effettuato == True:
464
  parte=1
465
  i=1
466
  risposta_completa = ''
 
 
467
  for ruolo_singolo in ruoli_divisi:
468
  for instruction_singola in instruction_suddivise:
469
  for numgen in range(1, st.session_state.numero_generazioni+1):
@@ -474,26 +491,35 @@ if st.session_state.login_effettuato == True:
474
  print('------------------------------------------------------------------------------------')
475
  print(prompt)
476
  st.session_state.messages.append({"role": "user", "content": prompt_originale})
477
- chat_stream = generate_chat_stream(prompt)
478
- with st.chat_message("assistant"):
479
- placeholder = st.empty()
480
- full_response = stream_handler(chat_stream, placeholder)
481
- if st.session_state.rag_enabled or st.session_state.cerca_online or st.session_state.selected_option["tipo"]=='EMAIL' or st.session_state.selected_option["tipo"]=='CALENDAR':
482
- show_source(links)
483
- if st.session_state.options.get(st.session_state.selected_option_key, {})["tipo"]=='DOCUMENTO':
484
- with st.expander("Mostra Documento") :
485
- st.info('##### ' + st.session_state.selected_documento_key + ' (Parte ' + str(parte) +')'+ '\n\n\n' + instruction_singola)
486
- parte+=1
487
- st.session_state.messages.append({"role": "assistant", "content": full_response})
488
- risposta_completa = risposta_completa + '\n' + full_response
489
-
490
- st.session_state.ultimo_messaggio = full_response
491
- st.session_state.tutti_messaggi += '\n\n' + full_response
492
- if st.session_state.enable_history:
493
- st.session_state.history.append([prompt_originale, full_response])
494
- else:
495
- st.session_state.history.append(['', ''])
496
- st.success('Generazione Completata')
497
- payload = {"domanda": prompt_originale, "risposta": risposta_completa}
498
- json_payload = json.dumps(payload)
499
- response = requests.post(URL_APP_SCRIPT, data=json_payload)
 
 
 
 
 
 
 
 
 
 
13
  from langchain_community.vectorstores import Chroma
14
  from langchain_community.embeddings import HuggingFaceEmbeddings
15
  import json
 
 
16
  from googlesearch import search
17
  from bs4 import BeautifulSoup
18
  import PyPDF2
 
22
  import webbrowser
23
  from streamlit_javascript import st_javascript
24
  import datetime
25
+ from openai import OpenAI
26
 
27
  load_dotenv()
28
+ EFFETTUA_LOGIN_GOOGLE = os.getenv('EFFETTUA_LOGIN_GOOGLE')=="1"
29
  URL_APP_SCRIPT = os.getenv('URL_APP_SCRIPT')
30
  URL_PROMPT = URL_APP_SCRIPT + '?IdFoglio=1cLw9q70BsPmxMBj9PIzgXtq6sm3X-GVBVnOB5wE8jr8'
31
  URL_DOCUMENTI = URL_APP_SCRIPT + '?IdSecondoFoglio=1cLw9q70BsPmxMBj9PIzgXtq6sm3X-GVBVnOB5wE8jr8'
32
  SYSTEM_PROMPT = ["Sei BonsiAI e mi aiuterai nelle mie richieste (Parla in ITALIANO)", "Esatto, sono BonsiAI. Di cosa hai bisogno?"]
33
+ CHAT_BOTS = {
34
+ "Mixtral 8x7B v0.1": {
35
+ "model": "mistralai/Mixtral-8x7B-Instruct-v0.1",
36
+ "description": "Un modello avanzato di chatbot con architettura 8x7B sviluppato da Mistral AI. Supporta fino a 30 pagine di input e costa zero",
37
+ "pagine_contesto": 30,
38
+ "richiede_api_key": False
39
+ },
40
+ "Mistral 7B v0.2": {
41
+ "model": "mistralai/Mistral-7B-Instruct-v0.2",
42
+ "description": "Una versione più leggera del modello Mistral, con architettura 7B, sviluppato da Mistral AI. Supporta fino a 8 pagine di input e costa zero",
43
+ "pagine_contesto": 8,
44
+ "richiede_api_key": False
45
+ },
46
+ "Gpt 3.5 Turbo": {
47
+ "model": "gpt-3.5-turbo",
48
+ "description": "Una versione ottimizzata e performante del modello GPT-3.5 di OpenAI. Supporta 16 Pagine di input e costa 2$ ogni 1000 Pagine",
49
+ "pagine_contesto": 16,
50
+ "richiede_api_key": True
51
+ },
52
+ "Gpt 4 Turbo": {
53
+ "model": "gpt-4-turbo",
54
+ "description": "Una versione avanzata e potenziata del famoso modello GPT-4 di OpenAI, ottimizzata per prestazioni superiori. Supporta fino a 120 Pagine di input e costa 30$ ogni 1000 Pagine",
55
+ "pagine_contesto": 120,
56
+ "richiede_api_key": True
57
+ }
58
+ }
59
  option_personalizzata = {'Personalizzata': {'systemRole': 'Tu sei BONSI AI, il mio assistente personale della scuola superiore del Bonsignori. Aiutami in base alle mie esigenze',
60
  'systemStyle': 'Firmati sempre come BONSI AI. (scrivi in italiano)',
61
  'instruction': '',
 
94
  if "repetion_penalty" not in st.session_state :
95
  st.session_state.repetion_penalty = 1
96
 
97
+ if "api_key" not in st.session_state :
98
+ st.session_state.api_key = ""
99
+
100
  if "chat_bot" not in st.session_state :
101
  st.session_state.chat_bot = "Mixtral 8x7B v0.1"
102
 
 
136
  if "uploaded_files" not in st.session_state:
137
  st.session_state.uploaded_files = None
138
 
139
+ if "client" not in st.session_state:
140
+ st.session_state.client = None
141
+
142
  if "urls" not in st.session_state:
143
  st.session_state.urls = [""] * 5
144
 
 
163
  "Ultimo giorno": "qdr:d"
164
  }
165
 
166
+ if not st.session_state.loaded_data and (st.session_state.login_effettuato == True or EFFETTUA_LOGIN_GOOGLE == False):
167
  place=st.empty()
168
  place=st.empty()
169
  with place:
 
179
  documenti = {}
180
  if URL_REDIRECT != "http://localhost:8501/":
181
  documenti = requests.get(URL_DOCUMENTI).json()
182
+ st.session_state.options = {**option_personalizzata, **options}
183
+ if EFFETTUA_LOGIN_GOOGLE:
184
+ st.session_state.options.update(option_leggiemail)
185
+ st.session_state.options.update(option_leggicalendar)
186
  st.session_state.documenti = documenti
187
  st.session_state.loaded_data = True
188
  status.update(label="Caricamento Completato", state="complete", expanded=False)
 
233
  st.session_state.selected_documento_key = st.selectbox('Documento', list(st.session_state.documenti.keys()))
234
  st.session_state.selected_documento = st.session_state.documenti.get(st.session_state.selected_documento_key, {})
235
  st.session_state.instruction = st.session_state.selected_documento.get('instruction', '')['Testo']
 
236
  else:
237
  st.session_state.instruction = st.session_state.selected_option.get('instruction', '')
238
+
239
+
240
+
241
  st.session_state.systemRole = st.session_state.selected_option.get('systemRole', '')
242
  st.session_state.systemRole = st.text_area("Descrizione", st.session_state.systemRole, help='Ruolo del chatbot e descrizione dell\'azione che deve svolgere')
243
  st.session_state.systemStyle = st.session_state.selected_option.get('systemStyle', '')
 
278
 
279
  def model_settings():
280
  st.markdown("# Modello")
281
+ st.session_state.chat_bot = st.sidebar.selectbox('Tipo', list(CHAT_BOTS.keys()))
282
+ if CHAT_BOTS[st.session_state.chat_bot]["richiede_api_key"] == True:
283
+ st.session_state.api_key = st.text_input('Api Key', type = 'password', label_visibility='collapsed', placeholder='Inserisci la chiave API')
284
+ st.session_state.client = OpenAI(api_key=st.session_state.api_key)
285
+ print('xxxxxxx')
286
+ st.write(CHAT_BOTS[st.session_state.chat_bot]["description"])
287
+ st.session_state.split = st.slider(label="Pagine Suddivisione", min_value=1, max_value=CHAT_BOTS[st.session_state.chat_bot]["pagine_contesto"], value=CHAT_BOTS[st.session_state.chat_bot]["pagine_contesto"], help='Se il documento ha 100 pagine e suddivido per 20 pagine elaborerà la risposta 5 volte. Più alto è il numero e meno volte elaborerà ma la risposta sarà più imprecisa')
288
  st.session_state.numero_generazioni = st.slider(label="Generazioni", min_value = 1, max_value=10, value=1)
289
  st.session_state.enable_history = st.toggle("Storico Messaggi", value=True)
290
  st.session_state.temp = st.slider(label="Creatività", min_value=0.0, max_value=1.0, step=0.1, value=0.9)
291
+ st.session_state.max_tokens = st.slider(label="Lunghezza Output", min_value = 2, max_value=4096, step= 32, value=1024)
292
  st.markdown("---")
293
 
294
  def export_settings():
 
302
  with st.sidebar:
303
  retrieval_settings()
304
  model_settings()
305
+ if EFFETTUA_LOGIN_GOOGLE:
306
+ export_settings()
307
  st.markdown("""> **Creato da Matteo Bergamelli **""")
308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  def header() :
310
  st.title("Bonsi A.I.", anchor=False)
311
  with st.expander("Cos'è BonsiAI?"):
 
401
  links.append((str(i) + '. ' + result['title'], result['description'] + '\n\n' + result['url']))
402
  return context, links
403
 
404
+ def generate_chat_stream(prompt):
405
+ chat_stream = chat(prompt, st.session_state.history,chat_client=CHAT_BOTS[st.session_state.chat_bot]["model"],
406
+ temperature=st.session_state.temp, max_new_tokens=st.session_state.max_tokens, client_openai = st.session_state.client)
407
  return chat_stream
408
 
409
  def inserisci_istruzioni(prompt_originale):
 
432
  def stream_handler(chat_stream, placeholder) :
433
  full_response = ''
434
  for chunk in chat_stream :
435
+ if CHAT_BOTS[st.session_state.chat_bot]["model"][:3] == 'gpt':
436
+ if chunk.choices[0].delta and chunk.choices[0].delta.content:
437
+ full_response += chunk.choices[0].delta.content
438
+ else:
439
+ if chunk.token.text!='</s>' :
440
+ full_response += chunk.token.text
441
+ placeholder.markdown(full_response + "▌")
442
  placeholder.markdown(full_response)
443
  return full_response
444
 
 
459
  return testo_suddiviso
460
 
461
  init_state()
462
+ if not st.session_state.login_effettuato and EFFETTUA_LOGIN_GOOGLE:
463
  connetti_google()
464
 
465
+ if st.session_state.login_effettuato or not EFFETTUA_LOGIN_GOOGLE:
466
  st_javascript("localStorage.removeItem('token');")
467
  init_state()
468
  sidebar()
469
  header()
470
  chat_box()
471
 
472
+ if prompt := st.chat_input("Chatta con BonsiAI..."):
473
  prompt_originale = prompt
474
  links = inserisci_istruzioni(prompt_originale)
475
  st.session_state.instruction+= ' \n\n' + st.session_state.testo_documenti
 
479
  parte=1
480
  i=1
481
  risposta_completa = ''
482
+ full_response = ''
483
+ errore_generazione = False
484
  for ruolo_singolo in ruoli_divisi:
485
  for instruction_singola in instruction_suddivise:
486
  for numgen in range(1, st.session_state.numero_generazioni+1):
 
491
  print('------------------------------------------------------------------------------------')
492
  print(prompt)
493
  st.session_state.messages.append({"role": "user", "content": prompt_originale})
494
+ try:
495
+ chat_stream = generate_chat_stream(prompt)
496
+ with st.chat_message("assistant"):
497
+ placeholder = st.empty()
498
+ full_response = stream_handler(chat_stream, placeholder)
499
+ if st.session_state.rag_enabled or st.session_state.cerca_online or st.session_state.selected_option["tipo"]=='EMAIL' or st.session_state.selected_option["tipo"]=='CALENDAR':
500
+ show_source(links)
501
+ if st.session_state.options.get(st.session_state.selected_option_key, {})["tipo"]=='DOCUMENTO':
502
+ with st.expander("Mostra Documento") :
503
+ st.info('##### ' + st.session_state.selected_documento_key + ' (Parte ' + str(parte) +')'+ '\n\n\n' + instruction_singola)
504
+ parte+=1
505
+ st.session_state.messages.append({"role": "assistant", "content": full_response})
506
+ risposta_completa = risposta_completa + '\n' + full_response
507
+ except Exception as e:
508
+ print(str(e))
509
+ errore_generazione = True
510
+ if CHAT_BOTS[st.session_state.chat_bot]["model"][:3] == 'gpt':
511
+ st.error('Inserisci una CHIAVE API valida e controlla il CREDITO residuo: https://platform.openai.com/api-keys')
512
+ else:
513
+ st.error('Modello AI attualmente non disponibile')
514
+
515
+ if errore_generazione == False:
516
+ st.session_state.ultimo_messaggio = full_response
517
+ st.session_state.tutti_messaggi += '\n\n' + full_response
518
+ if st.session_state.enable_history:
519
+ st.session_state.history.append([prompt_originale, full_response])
520
+ else:
521
+ st.session_state.history.append(['', ''])
522
+ st.success('Generazione Completata')
523
+ payload = {"domanda": prompt_originale, "risposta": risposta_completa}
524
+ json_payload = json.dumps(payload)
525
+ response = requests.post(URL_APP_SCRIPT, data=json_payload)