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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
Created on Tue Nov 9 15:17:01 2021
|
| 5 |
+
|
| 6 |
+
@author: benjaminull
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import streamlit as st
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import base64
|
| 13 |
+
import streamlit.components.v1 as components
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
# from modules.quill.streamlit_quill import quill
|
| 16 |
+
from streamlit_quill import st_quill
|
| 17 |
+
import smtplib
|
| 18 |
+
import email.message
|
| 19 |
+
from streamlit_tags import st_tags
|
| 20 |
+
from st_aggrid import AgGrid
|
| 21 |
+
from st_aggrid.shared import GridUpdateMode
|
| 22 |
+
from st_aggrid.grid_options_builder import GridOptionsBuilder
|
| 23 |
+
from sqlalchemy import create_engine
|
| 24 |
+
from datetime import datetime
|
| 25 |
+
from datetime import date
|
| 26 |
+
import json
|
| 27 |
+
from streamlit_timeline import timeline
|
| 28 |
+
import ast
|
| 29 |
+
from logs_portal import log
|
| 30 |
+
import boto3
|
| 31 |
+
from Data.credentials import credentials_s3 as creds3
|
| 32 |
+
from Data.credentials import credentials_postgresql as credpost
|
| 33 |
+
from Data.credentials import credentials_mailer as credmail
|
| 34 |
+
from streamlit_lottie import st_lottie
|
| 35 |
+
|
| 36 |
+
def leer_ultima_nota(empresa):
|
| 37 |
+
url = credpost["POSTGRESQL"]
|
| 38 |
+
engine = create_engine(url, echo=False)
|
| 39 |
+
data = pd.read_sql_query("""SELECT Nota FROM notas_analistas
|
| 40 |
+
where empresa ='{Empresa}'
|
| 41 |
+
order by Date_nota Desc""".format(
|
| 42 |
+
Empresa=empresa), con=engine)
|
| 43 |
+
if len(data) > 0:
|
| 44 |
+
nota = data.iloc[0]["nota"]
|
| 45 |
+
else:
|
| 46 |
+
nota = 0
|
| 47 |
+
return nota
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def style_title():
|
| 51 |
+
style = """
|
| 52 |
+
<style>
|
| 53 |
+
.ql-toolbar.ql-snow {
|
| 54 |
+
position: fixed !important;
|
| 55 |
+
bottom: 0 !important;
|
| 56 |
+
}
|
| 57 |
+
</style>
|
| 58 |
+
"""
|
| 59 |
+
st.markdown(style, unsafe_allow_html=True)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@st.experimental_memo
|
| 63 |
+
def leer_notas():
|
| 64 |
+
url = credpost["POSTGRESQL"]
|
| 65 |
+
engine = create_engine(url, echo=False)
|
| 66 |
+
data = pd.read_sql_query(
|
| 67 |
+
"Select Id_quant, Nota from notas_analistas ORDER BY date_nota desc",
|
| 68 |
+
con=engine)
|
| 69 |
+
data.columns = ["Id_Quant", "Nota"]
|
| 70 |
+
data = data.drop_duplicates("Id_Quant")
|
| 71 |
+
return dict(zip(list(data["Id_Quant"]), list(data["Nota"])))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def load_image(image_file):
|
| 75 |
+
img = Image.open(image_file)
|
| 76 |
+
return img
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def img_to_bytes(img_path):
|
| 80 |
+
img_bytes = Path(img_path).read_bytes()
|
| 81 |
+
encoded = base64.b64encode(img_bytes).decode()
|
| 82 |
+
return encoded
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def display_table(df: pd.DataFrame):
|
| 86 |
+
# Configure AgGrid options
|
| 87 |
+
gb = GridOptionsBuilder.from_dataframe(df)
|
| 88 |
+
gb.configure_selection('single')
|
| 89 |
+
return AgGrid(
|
| 90 |
+
df, gridOptions=gb.build(),
|
| 91 |
+
update_mode=GridUpdateMode.MODEL_CHANGED,
|
| 92 |
+
enable_enterprise_modules=True,
|
| 93 |
+
height=400)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def display_table2(df: pd.DataFrame):
|
| 97 |
+
# Configure AgGrid options
|
| 98 |
+
gb = GridOptionsBuilder.from_dataframe(df)
|
| 99 |
+
gb.configure_selection(selection_mode="single", use_checkbox=True,)
|
| 100 |
+
return AgGrid(
|
| 101 |
+
df, gridOptions=gb.build(),
|
| 102 |
+
update_mode=GridUpdateMode.SELECTION_CHANGED,
|
| 103 |
+
enable_enterprise_modules=True)
|
| 104 |
+
|
| 105 |
+
def write_s3(key, secret_key, new_file, bucket, path):
|
| 106 |
+
s3 = boto3.resource('s3', aws_access_key_id=key,
|
| 107 |
+
aws_secret_access_key=secret_key)
|
| 108 |
+
s3object = s3.Object(bucket, path)
|
| 109 |
+
s3object.put(Body=(bytes(json.dumps(new_file).encode('UTF-8'))))
|
| 110 |
+
|
| 111 |
+
# @st.experimental_memo
|
| 112 |
+
def read_s3(key, secret_key, bucket, path):
|
| 113 |
+
s3_client = boto3.client('s3', aws_access_key_id=key,
|
| 114 |
+
aws_secret_access_key=secret_key)
|
| 115 |
+
response = s3_client.get_object(Bucket=bucket, Key=path)
|
| 116 |
+
data2 = response["Body"].read().decode()
|
| 117 |
+
return data2
|
| 118 |
+
|
| 119 |
+
import streamlit_modal as modal
|
| 120 |
+
import streamlit.components.v1 as components
|
| 121 |
+
|
| 122 |
+
import extra_streamlit_components as stx
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def is_open():
|
| 127 |
+
return st.session_state.get('modal_is_open', False)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def open_():
|
| 131 |
+
st.session_state.modal_is_open = True
|
| 132 |
+
st.experimental_rerun()
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def close():
|
| 136 |
+
st.session_state.modal_is_open = False
|
| 137 |
+
st.experimental_rerun()
|
| 138 |
+
|
| 139 |
+
@st.experimental_memo
|
| 140 |
+
def get_noticias_df():
|
| 141 |
+
key = creds3["S3_KEY_ID"]
|
| 142 |
+
secret_key = creds3["S3_SECRET_KEY"]
|
| 143 |
+
bucket = creds3["S3_BUCKET"]
|
| 144 |
+
path = 'noticias.json'
|
| 145 |
+
data2 = read_s3(key, secret_key, bucket, path)
|
| 146 |
+
eventos = list(ast.literal_eval(data2).values())
|
| 147 |
+
eventos2 = []
|
| 148 |
+
empresas = []
|
| 149 |
+
paises = []
|
| 150 |
+
lv1s = []
|
| 151 |
+
analistas =[]
|
| 152 |
+
text=[]
|
| 153 |
+
titulo = []
|
| 154 |
+
fecha = []
|
| 155 |
+
indice = []
|
| 156 |
+
notas = []
|
| 157 |
+
noticias = pd.DataFrame()
|
| 158 |
+
for i, eve in enumerate(eventos):
|
| 159 |
+
|
| 160 |
+
try:
|
| 161 |
+
year = int(eve["start_date"]["year"])
|
| 162 |
+
month = int(eve["start_date"]["month"])
|
| 163 |
+
day = int(eve["start_date"]["day"])
|
| 164 |
+
indice.append(i)
|
| 165 |
+
fecha.append(date(day=day, month=month, year=year))
|
| 166 |
+
analistas.append(eve["analista"])
|
| 167 |
+
text.append(eve["text"]["text"])
|
| 168 |
+
titulo.append(eve["text"]["headline"])
|
| 169 |
+
notas.append(eve["notas"])
|
| 170 |
+
except Exception as exc:
|
| 171 |
+
st.write(exc)
|
| 172 |
+
pass
|
| 173 |
+
id_text_dict = dict(zip(indice, text))
|
| 174 |
+
id_notas_dict = dict(zip(indice, notas))
|
| 175 |
+
|
| 176 |
+
noticias["Fecha"] = fecha
|
| 177 |
+
noticias["Analista"]= analistas
|
| 178 |
+
noticias["Titulo"] = titulo
|
| 179 |
+
noticias["ID"] = indice
|
| 180 |
+
return noticias, id_text_dict
|
| 181 |
+
|
| 182 |
+
# def
|
| 183 |
+
|
| 184 |
+
# @log
|
| 185 |
+
def ver_mails():
|
| 186 |
+
|
| 187 |
+
chosen_id = stx.tab_bar(data=[
|
| 188 |
+
stx.TabBarItemData(id=1, title="Tabla de noticias", description=""),
|
| 189 |
+
stx.TabBarItemData(id=2, title="Linea del tiempo", description=""),
|
| 190 |
+
], default=1)
|
| 191 |
+
# timeline2 = st.checkbox("Linea de tiempo")
|
| 192 |
+
data = pd.pandas.read_excel("Data/Company_Base_Definitivo.xlsx",
|
| 193 |
+
sheet_name="Compilado", engine="openpyxl")
|
| 194 |
+
if chosen_id =='2':
|
| 195 |
+
|
| 196 |
+
key = creds3["S3_KEY_ID"]
|
| 197 |
+
secret_key = creds3["S3_SECRET_KEY"]
|
| 198 |
+
bucket = creds3["S3_BUCKET"]
|
| 199 |
+
path = 'noticias.json'
|
| 200 |
+
data2 = read_s3(key, secret_key, bucket, path)
|
| 201 |
+
eventos = list(ast.literal_eval(data2).values())
|
| 202 |
+
eventos2 = []
|
| 203 |
+
empresas = []
|
| 204 |
+
paises = []
|
| 205 |
+
lv1s = []
|
| 206 |
+
analistas = []
|
| 207 |
+
for eve in eventos:
|
| 208 |
+
try:
|
| 209 |
+
empresas = empresas + list(eve["notas"].keys())
|
| 210 |
+
paises = paises + list(eve["tags"]["paises"])
|
| 211 |
+
lv1s = lv1s + list(eve["tags"]["LV1"])
|
| 212 |
+
analistas.append(eve["analista"])
|
| 213 |
+
eventos2.append(eve)
|
| 214 |
+
except Exception as exc:
|
| 215 |
+
st.write(exc)
|
| 216 |
+
pass
|
| 217 |
+
|
| 218 |
+
empresas = sorted(list(set(empresas)))
|
| 219 |
+
analistas = sorted(list(set(analistas)))
|
| 220 |
+
empresas_dict =dict(zip(data['ID_Quant'], data["Short_Name"]))
|
| 221 |
+
empresas = sorted([empresas_dict[int(i)] for i in empresas])
|
| 222 |
+
paises = sorted(list(set(paises)))
|
| 223 |
+
lv1s = sorted(list(set(lv1s)))
|
| 224 |
+
col1, col2 = st.columns(2)
|
| 225 |
+
Dict = {
|
| 226 |
+
"title": {
|
| 227 |
+
"media": {
|
| 228 |
+
},
|
| 229 |
+
"text": {
|
| 230 |
+
"headline": "Noticias Equity Latam",
|
| 231 |
+
"text": " "
|
| 232 |
+
}
|
| 233 |
+
}}
|
| 234 |
+
filtro = col1.selectbox("Filtrar por",
|
| 235 |
+
["-", "Analista", "Empresa", "Pais", "LV1"])
|
| 236 |
+
|
| 237 |
+
if filtro != "-":
|
| 238 |
+
eventos2 = []
|
| 239 |
+
if filtro == "Empresa":
|
| 240 |
+
emp = col2.selectbox("", empresas)
|
| 241 |
+
for eve in eventos:
|
| 242 |
+
if emp in list(eve["notas"].keys()):
|
| 243 |
+
eventos2.append(eve)
|
| 244 |
+
elif filtro == "Analista":
|
| 245 |
+
an = col2.selectbox("", analistas)
|
| 246 |
+
for eve in eventos:
|
| 247 |
+
if eve["analista"] == an:
|
| 248 |
+
eventos2.append(eve)
|
| 249 |
+
elif filtro == "Pais":
|
| 250 |
+
pais = col2.selectbox("", paises)
|
| 251 |
+
for eve in eventos:
|
| 252 |
+
if pais in eve["tags"]["paises"]:
|
| 253 |
+
eventos2.append(eve)
|
| 254 |
+
elif filtro == "LV1":
|
| 255 |
+
lv1 = col2.selectbox("", lv1s)
|
| 256 |
+
for eve in eventos:
|
| 257 |
+
if lv1 in eve["tags"]["LV1"]:
|
| 258 |
+
eventos2.append(eve)
|
| 259 |
+
Dict["events"] = eventos2
|
| 260 |
+
timeline(Dict, height=800)
|
| 261 |
+
else:
|
| 262 |
+
|
| 263 |
+
noticias, id_text_dict = get_noticias_df()
|
| 264 |
+
placeh = st.empty()
|
| 265 |
+
empresas_dict =dict(zip(data['ID_Quant'], data["Short_Name"]))
|
| 266 |
+
col1, col2, col3= st.columns((3,0.5,5))
|
| 267 |
+
with col1:
|
| 268 |
+
select = display_table2(noticias)
|
| 269 |
+
|
| 270 |
+
a = select["selected_rows"].copy()
|
| 271 |
+
if len(a)==1:
|
| 272 |
+
# ver = col2.button('Ver mail')
|
| 273 |
+
# col3.title(" ")
|
| 274 |
+
# col3.write(" ")
|
| 275 |
+
# emp_nota_dict = id_notas_dict[select["selected_rows"][0]["ID"]]
|
| 276 |
+
# for emp in emp_nota_dict.keys():
|
| 277 |
+
# col2.write(empresas_dict[int(emp)])
|
| 278 |
+
# col3.write(str(emp_nota_dict[emp]))
|
| 279 |
+
# # if ver:
|
| 280 |
+
|
| 281 |
+
# # modal.open()
|
| 282 |
+
|
| 283 |
+
# if modal.is_open():
|
| 284 |
+
with col3:
|
| 285 |
+
st.title(select["selected_rows"][0]["Titulo"])
|
| 286 |
+
text = id_text_dict[select["selected_rows"][0]["ID"]]
|
| 287 |
+
components.html(text, height=900, scrolling=True)
|
| 288 |
+
# else:
|
| 289 |
+
# s = 0
|
| 290 |
+
# col1, col2, col3, col4 = st.columns(4)
|
| 291 |
+
# an = col1.selectbox("Analista", ["-"] + analistas)
|
| 292 |
+
# emp = col2.selectbox("Empresa", ["-"] + empresas)
|
| 293 |
+
# pais = col3.selectbox("Pais", ["-"] + paises)
|
| 294 |
+
# lv1 = col4.selectbox("LV1", ["-"] + lv1s)
|
| 295 |
+
# for evento in eventos:
|
| 296 |
+
# if emp in list(evento["notas"].keys()) or emp == '-':
|
| 297 |
+
# if evento["analista"] == an or an == '-':
|
| 298 |
+
# if lv1 in evento["tags"]["LV1"] or lv1 == '-':
|
| 299 |
+
# if pais in evento["tags"]["paises"] or pais == '-':
|
| 300 |
+
# col1, col2, col3 = st.columns((1, 1, 3))
|
| 301 |
+
# col1.write(evento["start_date"]["year"] + "-"
|
| 302 |
+
# + evento["start_date"]
|
| 303 |
+
# ["month"] + "-"
|
| 304 |
+
# + evento["start_date"]["day"])
|
| 305 |
+
# col2.write(evento["analista"])
|
| 306 |
+
# with col3.expander(evento["text"]["headline"]):
|
| 307 |
+
# st.title(evento["text"]["headline"])
|
| 308 |
+
# components.html(evento["text"]["text"],
|
| 309 |
+
# height=800, scrolling=True)
|
| 310 |
+
# s += 1
|
| 311 |
+
|
| 312 |
+
@st.experimental_memo
|
| 313 |
+
def read_cb():
|
| 314 |
+
cb = pd.pandas.read_excel("Data/Company_Base_Definitivo.xlsx",
|
| 315 |
+
sheet_name="Compilado", engine="openpyxl")
|
| 316 |
+
return cb
|
| 317 |
+
|
| 318 |
+
# @log
|
| 319 |
+
def escribir_mails2():
|
| 320 |
+
if "value" not in st.session_state:
|
| 321 |
+
st.session_state.value = ""
|
| 322 |
+
cols1, cols2= st.sidebar.columns((3,1))
|
| 323 |
+
name = st.session_state["name"]
|
| 324 |
+
cargo = st.session_state["cargo"]
|
| 325 |
+
place = cols2.empty()
|
| 326 |
+
notas_d = leer_notas()
|
| 327 |
+
key = creds3["S3_KEY_ID"]
|
| 328 |
+
secret_key = creds3["S3_SECRET_KEY"]
|
| 329 |
+
bucket = creds3["S3_BUCKET"]
|
| 330 |
+
path = 'noticias.json'
|
| 331 |
+
# st.sidebar.subheader("Borradores")
|
| 332 |
+
cols1, cols2, cols3 = st.columns((5,5,5))
|
| 333 |
+
data2 = read_cb()
|
| 334 |
+
dic_emp_ticker = dict(zip(list(data2["Short_Name"]), list(data2["Ticker"])))
|
| 335 |
+
dic_emp_pais = dict(zip(list(data2["Short_Name"]), list(data2["Country"])))
|
| 336 |
+
dic_emp_lv1 = dict(zip(list(data2["Short_Name"]), list(data2["LV1"])))
|
| 337 |
+
industrias = []
|
| 338 |
+
for a in list(set(data2["LV1"])):
|
| 339 |
+
for b in list(set(data2["Country"])):
|
| 340 |
+
industrias.append(a + " - " + b)
|
| 341 |
+
empresa = cols1.multiselect("Seleccione empresas o industrias",
|
| 342 |
+
sorted(list(data2["Short_Name"]) + industrias))
|
| 343 |
+
w = 0
|
| 344 |
+
notas = {}
|
| 345 |
+
to_tags = []
|
| 346 |
+
placeholder = ""
|
| 347 |
+
dic_emp = dict(zip(list(data2["Short_Name"]), list(data2["ID_Quant"])))
|
| 348 |
+
value = ""
|
| 349 |
+
|
| 350 |
+
if st.sidebar.checkbox("Ver Borradores"):
|
| 351 |
+
with st.sidebar:
|
| 352 |
+
json_file = open('Data/borradores.json','r')
|
| 353 |
+
json_obj = json.load(json_file)
|
| 354 |
+
eventos = json_obj[st.session_state.key]
|
| 355 |
+
borr = pd.DataFrame.from_dict(eventos, orient='index').reset_index()
|
| 356 |
+
borr.columns = ["Borradores", "html"]
|
| 357 |
+
dict_html = dict(zip(list(borr["Borradores"]), list(borr["html"])))
|
| 358 |
+
a = display_table(borr[["Borradores"]].iloc[::-1])
|
| 359 |
+
b = a["selected_rows"]
|
| 360 |
+
if len(b) > 0:
|
| 361 |
+
b = b[0]
|
| 362 |
+
st.session_state.value = dict_html[b["Borradores"]]
|
| 363 |
+
|
| 364 |
+
col1, col2, col3, col4 = st.columns((3, 1, 1, 10))
|
| 365 |
+
col2.markdown('<p style="margin-top:0px""> </p>', unsafe_allow_html=True)
|
| 366 |
+
col3.markdown('<p style="margin-top:0px""> </p>', unsafe_allow_html=True)
|
| 367 |
+
for emp in empresa:
|
| 368 |
+
try:
|
| 369 |
+
tick = dic_emp_ticker[emp]
|
| 370 |
+
except:
|
| 371 |
+
tick = emp
|
| 372 |
+
pass
|
| 373 |
+
col1.markdown(
|
| 374 |
+
'<p style="font-size:14px; margin-top:8px">Empresa</p>',
|
| 375 |
+
unsafe_allow_html=True)
|
| 376 |
+
col1.markdown('<h4 style="margin-top:2px; padding:6px; margin-bottom:7px">' + tick + "</h4>",
|
| 377 |
+
unsafe_allow_html=True)
|
| 378 |
+
try:
|
| 379 |
+
ult_nota = notas_d[dic_emp[emp]]
|
| 380 |
+
except Exception:
|
| 381 |
+
ult_nota = 0
|
| 382 |
+
col2.markdown(
|
| 383 |
+
'<p style="font-size:14px; margin-bottom:3px">Ultima nota</p>',
|
| 384 |
+
unsafe_allow_html=True)
|
| 385 |
+
col2.markdown(f'<h4 style="margin-top:8px; padding:8px; margin-bottom:15px"">{ult_nota}</h4>',
|
| 386 |
+
unsafe_allow_html=True)
|
| 387 |
+
if emp in industrias:
|
| 388 |
+
notas[emp] = col3.selectbox("Nota de la noticia" + " " * w,
|
| 389 |
+
[1, 2, 3, 4, 5])
|
| 390 |
+
to_tags.append(emp)
|
| 391 |
+
else:
|
| 392 |
+
notas[dic_emp[emp]] = col3.selectbox("Nota noticia" +
|
| 393 |
+
" "*w,
|
| 394 |
+
[1, 2, 3, 4, 5])
|
| 395 |
+
to_tags.append(dic_emp_pais[emp])
|
| 396 |
+
to_tags.append(dic_emp_lv1[emp])
|
| 397 |
+
placeholder = placeholder + "<p>" + emp + ":<br> Nota Empresa " + \
|
| 398 |
+
str(ult_nota) + "<br> Nota noticia:" + str(notas[dic_emp[emp]])+ "</p>"
|
| 399 |
+
w += 1
|
| 400 |
+
placeholder = '<b><h3>' + name+'</h3></b>' + placeholder
|
| 401 |
+
mail_destino = cols2.selectbox("To:", ['[email protected]',
|
| 402 |
+
'[email protected]',
|
| 403 | |
| 404 |
+
])
|
| 405 |
+
cc = cols3.text_input("CC")
|
| 406 |
+
|
| 407 |
+
with col4:
|
| 408 |
+
asunto = st.text_input("Asunto")
|
| 409 |
+
st.write("")
|
| 410 |
+
st.markdown(placeholder, unsafe_allow_html=True)
|
| 411 |
+
# if value == "" or len(b) == 0:
|
| 412 |
+
# content = quill.st_quill(html=True, key="quill")
|
| 413 |
+
# else:
|
| 414 |
+
content = st_quill(html=True, value=st.session_state["value"])
|
| 415 |
+
content = content.replace("\\", "")
|
| 416 |
+
# attach = st.file_uploader("Añade archivos",
|
| 417 |
+
# accept_multiple_files=True)
|
| 418 |
+
st.write(len(content))
|
| 419 |
+
tags = st_tags(
|
| 420 |
+
value=to_tags,
|
| 421 |
+
label='Tags:',
|
| 422 |
+
text='Añadir Tags',
|
| 423 |
+
suggestions=sorted(
|
| 424 |
+
list(data2["Short_Name"])+list(set(data2["Country"])) +
|
| 425 |
+
list(set(data2["LV1"]))),
|
| 426 |
+
key='1')
|
| 427 |
+
button = st.button("Enviar")
|
| 428 |
+
button2 = st.button("Guardar borrador")
|
| 429 |
+
|
| 430 |
+
if button:
|
| 431 |
+
if content[0] == '"':
|
| 432 |
+
content = content[1:]
|
| 433 |
+
if content[-1] == '"':
|
| 434 |
+
content = content[:-1]
|
| 435 |
+
empresas = list(notas.keys())
|
| 436 |
+
paises = [dic_emp_pais.get(key) for key in empresas]
|
| 437 |
+
lv1s = [dic_emp_lv1.get(key) for key in empresas]
|
| 438 |
+
analista = st.session_state.key
|
| 439 |
+
server = smtplib.SMTP('smtp.gmail.com:587')
|
| 440 |
+
email_content = placeholder + content
|
| 441 |
+
msg = email.message.Message()
|
| 442 |
+
msg['Subject'] = asunto
|
| 443 |
+
rcpt = cc.split(",") + [mail_destino]
|
| 444 |
+
msg['To'] = mail_destino
|
| 445 |
+
msg['Cc'] = cc
|
| 446 |
+
msg.add_header('Content-Type', 'text/html')
|
| 447 |
+
msg.set_payload(email_content)
|
| 448 |
+
s = smtplib.SMTP('smtp.gmail.com: 587')
|
| 449 |
+
s.starttls()
|
| 450 |
+
a_file = read_s3(key, secret_key, bucket, path)
|
| 451 |
+
json_object = json.loads(a_file)
|
| 452 |
+
eventos = list(json_object.values())
|
| 453 |
+
fecha = {
|
| 454 |
+
"year": str(date.today().year),
|
| 455 |
+
"month": str(date.today().month),
|
| 456 |
+
"day": str(date.today().day)
|
| 457 |
+
}
|
| 458 |
+
contenido = {
|
| 459 |
+
"headline": asunto,
|
| 460 |
+
"text": email_content
|
| 461 |
+
}
|
| 462 |
+
otros_tags = []
|
| 463 |
+
tags_pais = []
|
| 464 |
+
tags_lv1 = []
|
| 465 |
+
if type(tags) is str:
|
| 466 |
+
tags = ast.literal_eval(tags)
|
| 467 |
+
for i in tags:
|
| 468 |
+
if i in list(set(dic_emp_pais.values())):
|
| 469 |
+
tags_pais.append(i)
|
| 470 |
+
elif i in list(set(dic_emp_lv1.values())):
|
| 471 |
+
tags_lv1.append(i)
|
| 472 |
+
else:
|
| 473 |
+
otros_tags.append(i)
|
| 474 |
+
nueva_not = {
|
| 475 |
+
"start_date": fecha,
|
| 476 |
+
"text": contenido,
|
| 477 |
+
"notas": notas,
|
| 478 |
+
"analista": analista,
|
| 479 |
+
"tags": {"LV1": tags_lv1,
|
| 480 |
+
"paises": tags_pais,
|
| 481 |
+
"otros": otros_tags}
|
| 482 |
+
}
|
| 483 |
+
indice =int(list(json_object.keys())[-1])+1
|
| 484 |
+
json_object[indice] = nueva_not
|
| 485 |
+
write_s3(key, secret_key, json_object, bucket, path)
|
| 486 |
+
msg['From'] = credmail['EMAILSENDER']
|
| 487 |
+
password = credmail['EMAILPASS']
|
| 488 |
+
s.login(msg['From'], password)
|
| 489 |
+
s.sendmail(msg['From'], rcpt,
|
| 490 |
+
msg.as_string().encode('utf-8'))
|
| 491 |
+
# st.markdown(placeholder + content, unsafe_allow_html=True)
|
| 492 |
+
st.experimental_memo.clear()
|
| 493 |
+
st.success("Mail enviado correctamente")
|
| 494 |
+
if len(content)>0:
|
| 495 |
+
with open('Data/borradores.json', 'r') as json_file:
|
| 496 |
+
json_object = json.load(json_file)
|
| 497 |
+
if content[0] == '"':
|
| 498 |
+
content = content[1:]
|
| 499 |
+
if content[-1] == '"':
|
| 500 |
+
content = content[:-1]
|
| 501 |
+
|
| 502 |
+
event = json_object[st.session_state.key]
|
| 503 |
+
title = date.today().strftime('%Y-%m-%d ' + asunto)
|
| 504 |
+
event[title] = content
|
| 505 |
+
json_object[st.session_state.key] = event
|
| 506 |
+
path_b='borradores.json'
|
| 507 |
+
with open('Data/borradores.json', 'w') as outfile:
|
| 508 |
+
json.dump(json_object, outfile)
|
| 509 |
+
outfile.close()
|
| 510 |
+
# st.write(attach)
|
| 511 |
+
# st.write(type(attach[0]))
|
| 512 |
+
st.info("borrador guardado")
|
| 513 |
+
place.empty()
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
# src='https://app.powerbi.com/reportEmbed?reportId=296fa839-a397-4238-bf82-c0729edb1bde&autoAuth=true&ctid=c174949a-fefa-49fe-842c-3f378af3a546&config=eyJjbHVzdGVyVXJsIjoiaHR0cHM6Ly93YWJpLXNvdXRoLWNlbnRyYWwtdXMtcmVkaXJlY3QuYW5hbHlzaXMud2luZG93cy5uZXQvIn0%3D'
|
| 517 |
+
# st.components.v1.iframe(src, width=None, height=700, scrolling=False)
|