Spaces:
Runtime error
Runtime error
Delete google_function.py
Browse files- google_function.py +0 -278
google_function.py
DELETED
|
@@ -1,278 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
from dotenv import load_dotenv
|
| 3 |
-
import os.path
|
| 4 |
-
from google.auth.transport.requests import Request
|
| 5 |
-
from google.oauth2.credentials import Credentials
|
| 6 |
-
from google_auth_oauthlib.flow import InstalledAppFlow
|
| 7 |
-
from googleapiclient.discovery import build
|
| 8 |
-
from googleapiclient.errors import HttpError
|
| 9 |
-
import base64
|
| 10 |
-
from email.message import EmailMessage
|
| 11 |
-
from bs4 import BeautifulSoup
|
| 12 |
-
import webbrowser
|
| 13 |
-
import datetime
|
| 14 |
-
from streamlit_javascript import st_javascript
|
| 15 |
-
import streamlit as st
|
| 16 |
-
import time
|
| 17 |
-
|
| 18 |
-
SCOPES = ["https://www.googleapis.com/auth/gmail.compose",
|
| 19 |
-
"https://www.googleapis.com/auth/gmail.modify",
|
| 20 |
-
"https://mail.google.com/",
|
| 21 |
-
"https://www.googleapis.com/auth/calendar.readonly",
|
| 22 |
-
"https://www.googleapis.com/auth/documents.readonly",
|
| 23 |
-
"https://www.googleapis.com/auth/forms.body",
|
| 24 |
-
"https://www.googleapis.com/auth/spreadsheets.readonly",
|
| 25 |
-
"https://www.googleapis.com/auth/drive"]
|
| 26 |
-
|
| 27 |
-
#---------------------------------------------------------- LETTURA EMAIL ---------------------------------------------------------
|
| 28 |
-
def converti_email_txt(body):
|
| 29 |
-
try:
|
| 30 |
-
soup = BeautifulSoup(body, 'html.parser')
|
| 31 |
-
body_content = soup.find('body').get_text() if soup.find('body') else body
|
| 32 |
-
body = body_content
|
| 33 |
-
except:
|
| 34 |
-
body = body
|
| 35 |
-
return body
|
| 36 |
-
|
| 37 |
-
def leggi_gmail(max_results=10, data_inizio = None, data_fine = None):
|
| 38 |
-
links = []
|
| 39 |
-
service = build("gmail", "v1", credentials=st.session_state.creds)
|
| 40 |
-
start_date_str = data_inizio.strftime("%Y/%m/%d")
|
| 41 |
-
end_date_str = data_fine.strftime("%Y/%m/%d")
|
| 42 |
-
query = f"is:unread after:{start_date_str} before:{end_date_str}"
|
| 43 |
-
results = service.users().messages().list(userId="me", labelIds=["INBOX"], q=query, maxResults=max_results).execute()
|
| 44 |
-
messages = results.get("messages", [])
|
| 45 |
-
testo_email = ''
|
| 46 |
-
if not messages:
|
| 47 |
-
print("You have no New Messages.")
|
| 48 |
-
else:
|
| 49 |
-
message_count = 0
|
| 50 |
-
for message in messages:
|
| 51 |
-
msg = service.users().messages().get(userId="me", id=message["id"]).execute()
|
| 52 |
-
message_count = message_count + 1
|
| 53 |
-
email_data = msg["payload"]["headers"]
|
| 54 |
-
for values in email_data:
|
| 55 |
-
name = values["name"]
|
| 56 |
-
if name == "From":
|
| 57 |
-
from_name = values["value"]
|
| 58 |
-
subject = [j["value"] for j in email_data if j["name"] == "Subject"]
|
| 59 |
-
elif name == "Date":
|
| 60 |
-
received_date = values["value"]
|
| 61 |
-
body = ""
|
| 62 |
-
if "parts" in msg["payload"]:
|
| 63 |
-
for part in msg["payload"]["parts"]:
|
| 64 |
-
if part["mimeType"] == "text/plain":
|
| 65 |
-
body = base64.urlsafe_b64decode(part["body"]["data"]).decode("utf-8")
|
| 66 |
-
body = converti_email_txt(body)
|
| 67 |
-
break
|
| 68 |
-
elif part["mimeType"] == "multipart/alternative":
|
| 69 |
-
for subpart in part["parts"]:
|
| 70 |
-
if subpart["mimeType"] == "text/plain":
|
| 71 |
-
body = base64.urlsafe_b64decode(subpart["body"]["data"]).decode("utf-8")
|
| 72 |
-
body = converti_email_txt(body)
|
| 73 |
-
break
|
| 74 |
-
else:
|
| 75 |
-
if "data" in msg["payload"]["body"]:
|
| 76 |
-
body = base64.urlsafe_b64decode(msg["payload"]["body"]["data"]).decode("utf-8")
|
| 77 |
-
body = converti_email_txt(body)
|
| 78 |
-
testo_email += 'Data Ricezione: ' + received_date[5:] + '\nMittente: ' + from_name + '\nOggetto: ' + ', '.join(subject) + '\nTesto Email: ' + body + '\n---------------------------------------------------\n'
|
| 79 |
-
links.append(('Mittente: ' + from_name, 'Data: ' + received_date[5:] + '\n\nOggetto: ' + ', '.join(subject)))
|
| 80 |
-
if testo_email == '':
|
| 81 |
-
testo_email = 'Non sono presenti email nell intervallo di date specificate! Riprova con altre date'
|
| 82 |
-
return testo_email, links
|
| 83 |
-
|
| 84 |
-
#---------------------------------------------------------- SCRITTURA BOZZA EMAIL ---------------------------------------------------------
|
| 85 |
-
def scrivi_bozza_gmail(testo):
|
| 86 |
-
draft_url = 'https://mail.google.com/mail/u/0/#drafts'
|
| 87 |
-
try:
|
| 88 |
-
service = build("gmail", "v1", credentials=st.session_state.creds)
|
| 89 |
-
message = EmailMessage()
|
| 90 |
-
message.set_content(testo)
|
| 91 |
-
message["To"] = "[email protected]"
|
| 92 |
-
message["From"] = "[email protected]"
|
| 93 |
-
message["Subject"] = "Automated draft"
|
| 94 |
-
encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
|
| 95 |
-
create_message = {"message": {"raw": encoded_message}}
|
| 96 |
-
draft = (service.users().drafts().create(userId="me", body=create_message).execute())
|
| 97 |
-
print(f'Draft id: {draft["id"]}\nDraft message: {draft["message"]}')
|
| 98 |
-
draft_id = draft["id"]
|
| 99 |
-
draft_details = service.users().drafts().get(userId="me", id=draft_id).execute()
|
| 100 |
-
print(draft_details)
|
| 101 |
-
except HttpError as error:
|
| 102 |
-
print(f"An error occurred: {error}")
|
| 103 |
-
return draft_url
|
| 104 |
-
|
| 105 |
-
#---------------------------------------------------------- CREA DOCUMENTO GOOGLE ---------------------------------------------------------
|
| 106 |
-
def crea_documento_google(testo):
|
| 107 |
-
drive_service = build('drive', 'v3', credentials=st.session_state.creds)
|
| 108 |
-
docs_service = build('docs', 'v1', credentials=st.session_state.creds)
|
| 109 |
-
file_metadata = {'name': 'Documento di Bonsi AI', 'mimeType': 'application/vnd.google-apps.document'}
|
| 110 |
-
new_document = drive_service.files().create(body=file_metadata).execute()
|
| 111 |
-
document_id = new_document['id']
|
| 112 |
-
|
| 113 |
-
title_text = "Documento di Bonsi AI"
|
| 114 |
-
title_index = 1
|
| 115 |
-
bold_title_request = {
|
| 116 |
-
"insertText": {
|
| 117 |
-
"location": {
|
| 118 |
-
"index": title_index,
|
| 119 |
-
},
|
| 120 |
-
"text": title_text
|
| 121 |
-
}
|
| 122 |
-
}
|
| 123 |
-
bold_request = {
|
| 124 |
-
"updateTextStyle": {
|
| 125 |
-
"range": {
|
| 126 |
-
"startIndex": title_index,
|
| 127 |
-
"endIndex": title_index + len(title_text)
|
| 128 |
-
},
|
| 129 |
-
"textStyle": {
|
| 130 |
-
"bold": True,
|
| 131 |
-
"fontSize": {
|
| 132 |
-
"magnitude": 20,
|
| 133 |
-
"unit": "PT"
|
| 134 |
-
}
|
| 135 |
-
},
|
| 136 |
-
"fields": "bold,fontSize"
|
| 137 |
-
}
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
normal_text = "\n\n" + testo
|
| 141 |
-
normal_text_index = title_index + len(title_text)
|
| 142 |
-
normal_text_request = {
|
| 143 |
-
"insertText": {
|
| 144 |
-
"location": {
|
| 145 |
-
"index": normal_text_index,
|
| 146 |
-
},
|
| 147 |
-
"text": normal_text
|
| 148 |
-
}
|
| 149 |
-
}
|
| 150 |
-
normal_request = {
|
| 151 |
-
"updateTextStyle": {
|
| 152 |
-
"range": {
|
| 153 |
-
"startIndex": normal_text_index,
|
| 154 |
-
"endIndex": normal_text_index + len(normal_text)
|
| 155 |
-
},
|
| 156 |
-
"textStyle": {
|
| 157 |
-
"bold": False,
|
| 158 |
-
"fontSize": {
|
| 159 |
-
"magnitude": 12,
|
| 160 |
-
"unit": "PT"
|
| 161 |
-
}
|
| 162 |
-
},
|
| 163 |
-
"fields": "bold,fontSize"
|
| 164 |
-
}
|
| 165 |
-
}
|
| 166 |
-
|
| 167 |
-
docs_service.documents().batchUpdate(documentId=document_id, body={
|
| 168 |
-
'requests': [bold_title_request, bold_request, normal_text_request, normal_request]
|
| 169 |
-
}).execute()
|
| 170 |
-
return 'https://docs.google.com/document/d/' + document_id
|
| 171 |
-
|
| 172 |
-
#---------------------------------------------------------- LEGGI GOOGLE CALENDAR ---------------------------------------------------------
|
| 173 |
-
def leggi_calendario_google(max_results=10, data_inizio = None, data_fine = None):
|
| 174 |
-
try:
|
| 175 |
-
service = build("calendar", "v3", credentials=st.session_state.creds)
|
| 176 |
-
calendar_list_result = service.calendarList().list().execute()
|
| 177 |
-
calendars = calendar_list_result.get('items', [])
|
| 178 |
-
descrizione_eventi = ''
|
| 179 |
-
links = []
|
| 180 |
-
timeMin = datetime.datetime.combine(data_inizio, datetime.time()).isoformat() + 'Z'
|
| 181 |
-
timeMax = datetime.datetime.combine(data_fine, datetime.time(23, 59, 59)).isoformat() + 'Z'
|
| 182 |
-
for calendar in calendars:
|
| 183 |
-
events_result = (service.events().list(calendarId=calendar['id'], timeMin=timeMin, timeMax = timeMax, maxResults=max_results, singleEvents=True, orderBy="startTime", ).execute())
|
| 184 |
-
events = events_result.get("items", [])
|
| 185 |
-
for event in events:
|
| 186 |
-
start = event["start"].get("dateTime", event["start"].get("date"))
|
| 187 |
-
end = event["end"].get("dateTime", event["end"].get("date"))
|
| 188 |
-
descrizione = ''
|
| 189 |
-
calendario = ''
|
| 190 |
-
if 'description' in event:
|
| 191 |
-
descrizione = event['description'].replace('\n', '. ')
|
| 192 |
-
if 'displayName' in event['organizer']:
|
| 193 |
-
calendario = event['organizer']['displayName']
|
| 194 |
-
else:
|
| 195 |
-
calendario = 'Principale'
|
| 196 |
-
descrizione_eventi += f'Calendario: {calendario} --- '
|
| 197 |
-
descrizione_eventi += f'Data Inizio: {start.replace("T", " ").replace("Z", " ")} - Data Fine: {end.replace("T", " ").replace("Z", " ")}: '
|
| 198 |
-
descrizione_link = f'Data: {start.replace("T", " ").replace("Z", " ")} \n\n Titolo: {event["summary"]}'
|
| 199 |
-
if descrizione != '':
|
| 200 |
-
descrizione_eventi += f'{event["summary"]} ({descrizione})'
|
| 201 |
-
descrizione_link += f'\n\nDescrizione: {event["summary"]} ({descrizione})'
|
| 202 |
-
else:
|
| 203 |
-
descrizione_eventi += f'{event["summary"]}'
|
| 204 |
-
descrizione_eventi += '\n'
|
| 205 |
-
links.append((f'Calendario: {calendario}', descrizione_link))
|
| 206 |
-
except HttpError as error:
|
| 207 |
-
print(f"An error occurred: {error}")
|
| 208 |
-
if descrizione_eventi == '':
|
| 209 |
-
descrizione_eventi = 'Non sono presenti eventi nel calendario per le date specificate. Riprova con altre date!'
|
| 210 |
-
return descrizione_eventi, links
|
| 211 |
-
|
| 212 |
-
#---------------------------------------------------------- CONNESSIONE ACCOUNT GOOGLE ---------------------------------------------------------
|
| 213 |
-
def local_storage_get(key):
|
| 214 |
-
return st_javascript(f"localStorage.getItem('{key}');")
|
| 215 |
-
|
| 216 |
-
def local_storage_set(key, value):
|
| 217 |
-
return st_javascript(f"localStorage.setItem('{key}', '{value}');")
|
| 218 |
-
|
| 219 |
-
def connetti_google():
|
| 220 |
-
load_dotenv()
|
| 221 |
-
json_variable_str = os.getenv("JSON_GOOGLE")
|
| 222 |
-
URL_REDIRECT = os.getenv('URL_REDIRECT')
|
| 223 |
-
with open("./credentials.json", "w") as f:
|
| 224 |
-
f.write(json_variable_str)
|
| 225 |
-
flow = InstalledAppFlow.from_client_secrets_file("./credentials.json", SCOPES, redirect_uri=URL_REDIRECT)
|
| 226 |
-
token = local_storage_get("token")
|
| 227 |
-
print('------------1------------------')
|
| 228 |
-
print(token)
|
| 229 |
-
if token and token != '':
|
| 230 |
-
print('------------2------------------')
|
| 231 |
-
flow.fetch_token(code=token)
|
| 232 |
-
st.session_state.creds = flow.credentials
|
| 233 |
-
print(st.session_state.creds)
|
| 234 |
-
st.session_state.login_effettuato = True
|
| 235 |
-
else:
|
| 236 |
-
print('------------3------------------')
|
| 237 |
-
auth_code = st.query_params.get("code")
|
| 238 |
-
if auth_code:
|
| 239 |
-
local_storage_set("token", auth_code)
|
| 240 |
-
time.sleep(2)
|
| 241 |
-
print('**************************************************************')
|
| 242 |
-
print(auth_code)
|
| 243 |
-
nav_script = """<meta http-equiv="refresh" content="0; url='%s'">""" % (URL_REDIRECT)
|
| 244 |
-
st.write(nav_script, unsafe_allow_html=True)
|
| 245 |
-
else:
|
| 246 |
-
print('------------4------------------')
|
| 247 |
-
col1, col2, col3 = st.columns([1, 3, 1])
|
| 248 |
-
with col2:
|
| 249 |
-
authorization_url, state = flow.authorization_url(include_granted_scopes="true",)
|
| 250 |
-
st.write('# Bonsi A.I.')
|
| 251 |
-
st.markdown(f'<h3><a href="{authorization_url}" target="_self">Login Google</a></h3>', unsafe_allow_html=True)
|
| 252 |
-
st.write("")
|
| 253 |
-
st.write("")
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
def connetti_google_2():
|
| 257 |
-
load_dotenv()
|
| 258 |
-
json_variable_str = os.getenv("JSON_GOOGLE")
|
| 259 |
-
print(json_variable_str)
|
| 260 |
-
with open("./credentials.json", "w") as f:
|
| 261 |
-
f.write(json_variable_str)
|
| 262 |
-
if os.path.exists("./credentials.json"):
|
| 263 |
-
print('ESISTE')
|
| 264 |
-
else:
|
| 265 |
-
print('NON ESISTE')
|
| 266 |
-
creds = None
|
| 267 |
-
if os.path.exists("./token.json"):
|
| 268 |
-
creds = Credentials.from_authorized_user_file("token.json", SCOPES)
|
| 269 |
-
if not creds or not creds.valid:
|
| 270 |
-
if creds and creds.expired and creds.refresh_token:
|
| 271 |
-
creds.refresh(Request())
|
| 272 |
-
else:
|
| 273 |
-
flow = InstalledAppFlow.from_client_secrets_file("./credentials.json", SCOPES, redirect_uri=URL_REDIRECT)
|
| 274 |
-
#creds = flow.run_local_server(port=8501, open_browser=False)
|
| 275 |
-
creds = flow.run_console()
|
| 276 |
-
with open("token.json", "w") as token:
|
| 277 |
-
token.write(creds.to_json())
|
| 278 |
-
return creds
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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