MatteoScript commited on
Commit
12e2c64
1 Parent(s): daa1f07

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +219 -94
app.py CHANGED
@@ -1,5 +1,10 @@
1
  import streamlit as st
2
  from chat_client import chat
 
 
 
 
 
3
  import time
4
  import os
5
  from dotenv import load_dotenv
@@ -8,27 +13,67 @@ import requests
8
  from langchain_community.vectorstores import Chroma
9
  from langchain_community.embeddings import HuggingFaceEmbeddings
10
  import json
11
- from audio_recorder_streamlit import audio_recorder
12
- import speech_recognition as sr
13
  from googlesearch import search
14
  from bs4 import BeautifulSoup
15
  import PyPDF2
16
  import pytesseract
17
  from PIL import Image
18
  from youtube_transcript_api import YouTubeTranscriptApi
 
 
 
 
19
 
20
  load_dotenv()
 
21
  URL_APP_SCRIPT = os.getenv('URL_APP_SCRIPT')
22
  URL_PROMPT = URL_APP_SCRIPT + '?IdFoglio=1cLw9q70BsPmxMBj9PIzgXtq6sm3X-GVBVnOB5wE8jr8'
23
  URL_DOCUMENTI = URL_APP_SCRIPT + '?IdSecondoFoglio=1cLw9q70BsPmxMBj9PIzgXtq6sm3X-GVBVnOB5wE8jr8'
24
  SYSTEM_PROMPT = ["Sei BonsiAI e mi aiuterai nelle mie richieste (Parla in ITALIANO)", "Esatto, sono BonsiAI. Di cosa hai bisogno?"]
25
- CHAT_BOTS = {"Mixtral 8x7B v0.1" :"mistralai/Mixtral-8x7B-Instruct-v0.1"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  option_personalizzata = {'Personalizzata': {'systemRole': 'Tu sei BONSI AI, il mio assistente personale della scuola superiore del Bonsignori. Aiutami in base alle mie esigenze',
27
  'systemStyle': 'Firmati sempre come BONSI AI. (scrivi in italiano)',
28
  'instruction': '',
29
  'tipo': '',
30
  'RAG': False}
31
  }
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  # ----------------------------------------------------------- Interfaccia --------------------------------------------------------------------
34
  st.set_page_config(page_title="Bonsi A.I.", page_icon="🏫")
@@ -49,6 +94,9 @@ def init_state() :
49
  if "repetion_penalty" not in st.session_state :
50
  st.session_state.repetion_penalty = 1
51
 
 
 
 
52
  if "chat_bot" not in st.session_state :
53
  st.session_state.chat_bot = "Mixtral 8x7B v0.1"
54
 
@@ -73,14 +121,38 @@ def init_state() :
73
  if "numero_generazioni" not in st.session_state:
74
  st.session_state.numero_generazioni = 1
75
 
 
 
 
 
 
 
 
 
 
76
  if "testo_documenti" not in st.session_state:
77
  st.session_state.testo_documenti = ''
78
 
79
  if "uploaded_files" not in st.session_state:
80
  st.session_state.uploaded_files = None
81
 
 
 
 
82
  if "urls" not in st.session_state:
83
  st.session_state.urls = [""] * 5
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  if "tbs_options" not in st.session_state:
86
  st.session_state.tbs_options = {
@@ -91,17 +163,26 @@ def init_state() :
91
  "Ultimo giorno": "qdr:d"
92
  }
93
 
94
- if not st.session_state.loaded_data:
 
95
  place=st.empty()
96
  with place:
97
  with st.status("Caricamento in corso...", expanded=True) as status:
98
  st.write("Inizializzazione Ambiente")
99
  time.sleep(1)
100
  st.write("Inizializzazione Prompt")
101
- options = requests.get(URL_PROMPT).json()
 
 
 
102
  st.write("Inizializzazione Documenti")
103
- documenti = requests.get(URL_DOCUMENTI).json()
104
- st.session_state.options = {**option_personalizzata, **options}
 
 
 
 
 
105
  st.session_state.documenti = documenti
106
  st.session_state.loaded_data = True
107
  status.update(label="Caricamento Completato", state="complete", expanded=False)
@@ -124,6 +205,24 @@ def read_text_from_file(file):
124
  st.write(f"Non è possibile leggere il testo dal file '{file.name}'.")
125
  return text
126
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  def sidebar():
128
  def retrieval_settings() :
129
  st.markdown("# Impostazioni Prompt")
@@ -134,14 +233,23 @@ def sidebar():
134
  st.session_state.selected_documento_key = st.selectbox('Documento', list(st.session_state.documenti.keys()))
135
  st.session_state.selected_documento = st.session_state.documenti.get(st.session_state.selected_documento_key, {})
136
  st.session_state.instruction = st.session_state.selected_documento.get('instruction', '')['Testo']
137
- 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')
138
  else:
139
  st.session_state.instruction = st.session_state.selected_option.get('instruction', '')
140
 
 
 
141
  st.session_state.systemRole = st.session_state.selected_option.get('systemRole', '')
142
  st.session_state.systemRole = st.text_area("Descrizione", st.session_state.systemRole, help='Ruolo del chatbot e descrizione dell\'azione che deve svolgere')
143
  st.session_state.systemStyle = st.session_state.selected_option.get('systemStyle', '')
144
  st.session_state.systemStyle = st.text_area("Stile", st.session_state.systemStyle, help='Descrizione dello stile utilizzato per generare il testo')
 
 
 
 
 
 
 
 
145
  st.session_state.rag_enabled = st.session_state.selected_option.get('tipo', '')=='RAG'
146
  if st.session_state.selected_option_key == 'Decreti':
147
  st.session_state.top_k = st.slider(label="Documenti da ricercare", min_value=1, max_value=20, value=4, disabled=not st.session_state.rag_enabled)
@@ -169,49 +277,35 @@ def sidebar():
169
  st.markdown("---")
170
 
171
  def model_settings():
172
- st.markdown("# Impostazioni Modello")
173
- st.session_state.chat_bot = st.sidebar.radio('Modello:', [key for key, value in CHAT_BOTS.items() ])
 
 
 
 
 
 
174
  st.session_state.numero_generazioni = st.slider(label="Generazioni", min_value = 1, max_value=10, value=1)
175
  st.session_state.enable_history = st.toggle("Storico Messaggi", value=True)
176
  st.session_state.temp = st.slider(label="Creatività", min_value=0.0, max_value=1.0, step=0.1, value=0.9)
177
- st.session_state.max_tokens = st.slider(label="Lunghezza Output", min_value = 2, max_value=2048, step= 32, value=1024)
 
 
 
 
 
 
 
 
 
178
 
179
  with st.sidebar:
180
  retrieval_settings()
181
  model_settings()
 
 
182
  st.markdown("""> **Creato da Matteo Bergamelli **""")
183
 
184
- def audioRec():
185
- st.session_state.audio_bytes = audio_recorder(text='', icon_size="3x")
186
- if st.session_state.audio_bytes:
187
- with open("./AUDIO.wav", "wb") as file:
188
- file.write(st.session_state.audio_bytes)
189
- wav = sr.AudioFile("./AUDIO.wav")
190
- with wav as source:
191
- recognizer_instance = sr.Recognizer()
192
- recognizer_instance.pause_threshold = 3.0
193
- audio = recognizer_instance.listen(source)
194
- print("Ok! sto ora elaborando il messaggio!")
195
- try:
196
- text = recognizer_instance.recognize_google(audio, language="it-IT")
197
- print(text)
198
- js = f"""
199
- <script>
200
- var chatInput = parent.document.querySelector('textarea[data-testid="stChatInput"]');
201
- var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
202
- nativeInputValueSetter.call(chatInput, "{text}");
203
- var event = new Event('input', {{ bubbles: true}});
204
- chatInput.dispatchEvent(event);
205
- var sendChat = parent.document.getElementsByClassName("st-emotion-cache-1621d17")[0]
206
- sendChat.click();
207
- var x = parent.document.querySelector('[title="st.iframe"]');
208
- x.style.display = "none";
209
- </script>
210
- """
211
- st.components.v1.html(js)
212
- except Exception as e:
213
- print(e)
214
-
215
  def header() :
216
  st.title("Bonsi A.I.", anchor=False)
217
  with st.expander("Cos'è BonsiAI?"):
@@ -307,9 +401,9 @@ def gen_online_prompt(prompt, top_k) :
307
  links.append((str(i) + '. ' + result['title'], result['description'] + '\n\n' + result['url']))
308
  return context, links
309
 
310
- def generate_chat_stream(prompt) :
311
- chat_stream = chat(prompt, st.session_state.history,chat_client=CHAT_BOTS[st.session_state.chat_bot] ,
312
- temperature=st.session_state.temp, max_new_tokens=st.session_state.max_tokens)
313
  return chat_stream
314
 
315
  def inserisci_istruzioni(prompt_originale):
@@ -322,6 +416,14 @@ def inserisci_istruzioni(prompt_originale):
322
  with st.spinner("Ricerca nei Decreti...."):
323
  time.sleep(1)
324
  st.session_state.instruction, links = gen_augmented_prompt(prompt=prompt_originale, top_k=st.session_state.top_k)
 
 
 
 
 
 
 
 
325
  with st.spinner("Generazione in corso...") :
326
  time.sleep(1)
327
  #st.session_state.instruction = instruction_originale + '\n----------------------------------------------\n' + st.session_state.instruction
@@ -330,9 +432,13 @@ def inserisci_istruzioni(prompt_originale):
330
  def stream_handler(chat_stream, placeholder) :
331
  full_response = ''
332
  for chunk in chat_stream :
333
- if chunk.token.text!='</s>' :
334
- full_response += chunk.token.text
335
- placeholder.markdown(full_response + "▌")
 
 
 
 
336
  placeholder.markdown(full_response)
337
  return full_response
338
 
@@ -342,11 +448,6 @@ def show_source(links) :
342
  reference, testo = link
343
  st.info('##### ' + reference.replace('_', ' ') + '\n\n'+ testo)
344
 
345
- init_state()
346
- sidebar()
347
- header()
348
- chat_box()
349
-
350
  def split_text(text, chunk_size):
351
  testo_suddiviso = []
352
  if text == '':
@@ -357,44 +458,68 @@ def split_text(text, chunk_size):
357
  testo_suddiviso.append(text[i:i+chunk_size])
358
  return testo_suddiviso
359
 
360
- if prompt := st.chat_input("Chatta con BonsiAI..."):
361
- prompt_originale = prompt
362
- links = inserisci_istruzioni(prompt_originale)
363
- st.session_state.instruction+= ' \n\n' + st.session_state.testo_documenti
364
- instruction_suddivise = split_text(st.session_state.instruction, st.session_state.split*2000)
365
- ruolo_originale = st.session_state.systemRole
366
- ruoli_divisi = ruolo_originale.split("&&")
367
- parte=1
368
- i=1
369
- risposta_completa = ''
370
- for ruolo_singolo in ruoli_divisi:
371
- for instruction_singola in instruction_suddivise:
372
- for numgen in range(1, st.session_state.numero_generazioni+1):
373
- if i==1:
374
- st.chat_message("user").markdown(prompt_originale + (': Parte ' + str(parte) if i > 1 else ''))
375
- i+=1
376
- prompt = formattaPrompt(prompt_originale, ruolo_singolo, st.session_state.systemStyle, instruction_singola)
377
- print('------------------------------------------------------------------------------------')
378
- print(prompt)
379
- st.session_state.messages.append({"role": "user", "content": prompt_originale})
380
- chat_stream = generate_chat_stream(prompt)
381
- with st.chat_message("assistant"):
382
- placeholder = st.empty()
383
- full_response = stream_handler(chat_stream, placeholder)
384
- if st.session_state.rag_enabled or st.session_state.cerca_online:
385
- show_source(links)
386
- if st.session_state.options.get(st.session_state.selected_option_key, {})["tipo"]=='DOCUMENTO':
387
- with st.expander("Mostra Documento") :
388
- st.info('##### ' + st.session_state.selected_documento_key + ' (Parte ' + str(parte) +')'+ '\n\n\n' + instruction_singola)
389
- parte+=1
390
- st.session_state.messages.append({"role": "assistant", "content": full_response})
391
- risposta_completa = risposta_completa + '\n' + full_response
392
-
393
- if st.session_state.enable_history:
394
- st.session_state.history.append([prompt_originale, full_response])
395
- else:
396
- st.session_state.history.append(['', ''])
397
- st.success('Generazione Completata')
398
- payload = {"domanda": prompt_originale, "risposta": risposta_completa}
399
- json_payload = json.dumps(payload)
400
- response = requests.post(URL_APP_SCRIPT, data=json_payload)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
  from chat_client import chat
3
+ from google_function import leggi_gmail
4
+ from google_function import scrivi_bozza_gmail
5
+ from google_function import leggi_calendario_google
6
+ from google_function import connetti_google
7
+ from google_function import crea_documento_google
8
  import time
9
  import os
10
  from dotenv import load_dotenv
 
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
19
  import pytesseract
20
  from PIL import Image
21
  from youtube_transcript_api import YouTubeTranscriptApi
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': '',
62
  'tipo': '',
63
  'RAG': False}
64
  }
65
+ option_leggiemail = {'Leggi Gmail': {'systemRole': 'Tu sei BONSI AI, il mio assistente personale della scuola superiore del Bonsignori. Effettua l operazione richiesta sulla base delle seguenti email: ',
66
+ 'systemStyle': 'Firmati sempre come BONSI AI. (scrivi in italiano)',
67
+ 'instruction': '',
68
+ 'tipo': 'EMAIL',
69
+ 'RAG': False}
70
+ }
71
+ option_leggicalendar = {'Leggi Calendar': {'systemRole': 'Tu sei BONSI AI, il mio assistente personale della scuola superiore del Bonsignori. Effettua l operazione richiesta sulla base dei seguenti eventi di calendario: ',
72
+ 'systemStyle': 'Firmati sempre come BONSI AI. (scrivi in italiano)',
73
+ 'instruction': '',
74
+ 'tipo': 'CALENDAR',
75
+ 'RAG': False}
76
+ }
77
 
78
  # ----------------------------------------------------------- Interfaccia --------------------------------------------------------------------
79
  st.set_page_config(page_title="Bonsi A.I.", page_icon="🏫")
 
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
 
 
121
  if "numero_generazioni" not in st.session_state:
122
  st.session_state.numero_generazioni = 1
123
 
124
+ if "numero_elementi" not in st.session_state:
125
+ st.session_state.numero_elementi = 5
126
+
127
+ if "data_inizio" not in st.session_state:
128
+ st.session_state.data_inizio = None
129
+
130
+ if "data_inizio" not in st.session_state:
131
+ st.session_state.data_inizio = None
132
+
133
  if "testo_documenti" not in st.session_state:
134
  st.session_state.testo_documenti = ''
135
 
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
+
145
+ if "creds" not in st.session_state:
146
+ st.session_state.creds = None
147
+
148
+ if "login_effettuato" not in st.session_state:
149
+ st.session_state.login_effettuato = False
150
+
151
+ if "ultimo_messaggio" not in st.session_state:
152
+ st.session_state.ultimo_messaggio = ""
153
+
154
+ if "tutti_messaggi" not in st.session_state:
155
+ st.session_state.tutti_messaggi = ""
156
 
157
  if "tbs_options" not in st.session_state:
158
  st.session_state.tbs_options = {
 
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:
170
  with st.status("Caricamento in corso...", expanded=True) as status:
171
  st.write("Inizializzazione Ambiente")
172
  time.sleep(1)
173
  st.write("Inizializzazione Prompt")
174
+ URL_REDIRECT = os.getenv('URL_REDIRECT')
175
+ options = {}
176
+ if URL_REDIRECT != "http://localhost:8501/":
177
+ options = requests.get(URL_PROMPT).json()
178
  st.write("Inizializzazione Documenti")
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)
 
205
  st.write(f"Non è possibile leggere il testo dal file '{file.name}'.")
206
  return text
207
 
208
+ def open_new_tab(url):
209
+ placeholder = st.empty()
210
+ with placeholder:
211
+ placeholder.empty()
212
+ new_tab_js = f'''<script type="text/javascript">window.open("{url}", "_blank");</script>'''
213
+ st.components.v1.html(new_tab_js, height=1)
214
+ time.sleep(0.3)
215
+ placeholder.empty()
216
+
217
+ def esporta_testo(tipo, ultimo_messaggio):
218
+ testo = st.session_state.ultimo_messaggio if ultimo_messaggio else st.session_state.tutti_messaggi
219
+ if tipo == 'Bozza Email':
220
+ url = scrivi_bozza_gmail(testo)
221
+ open_new_tab(url)
222
+ if tipo == 'Google Documenti':
223
+ url = crea_documento_google(testo)
224
+ open_new_tab(url)
225
+
226
  def sidebar():
227
  def retrieval_settings() :
228
  st.markdown("# Impostazioni Prompt")
 
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', '')
244
  st.session_state.systemStyle = st.text_area("Stile", st.session_state.systemStyle, help='Descrizione dello stile utilizzato per generare il testo')
245
+ if st.session_state.selected_option["tipo"]=='EMAIL':
246
+ st.session_state.numero_elementi = st.slider(label="Numero Email", min_value=1, max_value=100, value=10)
247
+ st.session_state.data_inizio = st.date_input("Email dal", value=datetime.date.today()-datetime.timedelta(days=7), format='DD/MM/YYYY')
248
+ st.session_state.data_fine = st.date_input("Email al", value=datetime.date.today(), format='DD/MM/YYYY')
249
+ if st.session_state.selected_option["tipo"]=='CALENDAR':
250
+ st.session_state.numero_elementi = st.slider(label="Numero Eventi Calendario", min_value=1, max_value=100, value=10)
251
+ st.session_state.data_inizio = st.date_input("Eventi dal", value=datetime.date.today(), format='DD/MM/YYYY')
252
+ st.session_state.data_fine = st.date_input("Eventi al", value=datetime.date.today()+datetime.timedelta(days=7), format='DD/MM/YYYY')
253
  st.session_state.rag_enabled = st.session_state.selected_option.get('tipo', '')=='RAG'
254
  if st.session_state.selected_option_key == 'Decreti':
255
  st.session_state.top_k = st.slider(label="Documenti da ricercare", min_value=1, max_value=20, value=4, disabled=not st.session_state.rag_enabled)
 
277
  st.markdown("---")
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():
295
+ st.markdown("# Esportazione")
296
+ st.session_state.export_type = st.selectbox('Tipologia', ('Non Esportare', 'Google Documenti', 'Bozza Email'), help='Seleziona la tipologia di esportazione del testo generato')
297
+ st.session_state.export_all = st.toggle("Considera tutte le chat", value=False)
298
+ if st.button("Esporta", type="primary", use_container_width=True):
299
+ esporta_testo(st.session_state.export_type, st.session_state.export_all)
300
+ st.markdown("---")
301
 
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):
 
416
  with st.spinner("Ricerca nei Decreti...."):
417
  time.sleep(1)
418
  st.session_state.instruction, links = gen_augmented_prompt(prompt=prompt_originale, top_k=st.session_state.top_k)
419
+ if st.session_state.selected_option["tipo"]=='EMAIL':
420
+ with st.spinner("Ricerca nelle Email...."):
421
+ time.sleep(1)
422
+ st.session_state.instruction, links = leggi_gmail(max_results=st.session_state.numero_elementi, data_inizio = st.session_state.data_inizio, data_fine = st.session_state.data_fine)
423
+ if st.session_state.selected_option["tipo"]=='CALENDAR':
424
+ with st.spinner("Ricerca nel Calendario...."):
425
+ time.sleep(1)
426
+ st.session_state.instruction, links = leggi_calendario_google(max_results=st.session_state.numero_elementi, data_inizio = st.session_state.data_inizio, data_fine = st.session_state.data_fine)
427
  with st.spinner("Generazione in corso...") :
428
  time.sleep(1)
429
  #st.session_state.instruction = instruction_originale + '\n----------------------------------------------\n' + st.session_state.instruction
 
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
 
 
448
  reference, testo = link
449
  st.info('##### ' + reference.replace('_', ' ') + '\n\n'+ testo)
450
 
 
 
 
 
 
451
  def split_text(text, chunk_size):
452
  testo_suddiviso = []
453
  if text == '':
 
458
  testo_suddiviso.append(text[i:i+chunk_size])
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
476
+ instruction_suddivise = split_text(st.session_state.instruction, st.session_state.split*2000)
477
+ ruolo_originale = st.session_state.systemRole
478
+ ruoli_divisi = ruolo_originale.split("&&")
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):
487
+ if i==1:
488
+ st.chat_message("user").markdown(prompt_originale + (': Parte ' + str(parte) if i > 1 else ''))
489
+ i+=1
490
+ prompt = formattaPrompt(prompt_originale, ruolo_singolo, st.session_state.systemStyle, instruction_singola)
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)