'The forecasts presented on the page are the result of experimental research.', size='14px', align='center') doc.add_text('You use (or do not use) them at your own risk.', size='14px', align='center') doc.add_text(f'zeptogame.com | {str(utc_dt_now.date())}', size='14px', align='center') doc.add_text( 'model ver. beta 2020.01S.02', size='14px', align='center') # ver. format year_of_model_creation.model_ver.terms_ver output_filepath = f'daily_forecasts/{TODAY}_main_page.html' to_server_output_filepath = f'{TODAY}_main_page.html' doc.write(output_filepath) doc.write(to_server_output_filepath) print(f'{output_filepath} has been saved successfully!') print(f'{to_server_output_filepath} has been saved successfully!') if to_the_telegram: if len(today_champs) > 0: for i in range(len(today_predictions)): today_predictions[i]['df']['CHAMP_NAME'] = today_predictions[i][ 'champ_full_name'] final_df = today_predictions[0]['df'] for j in range(1, len(today_predictions)): final_df = pd.concat([final_df, today_predictions[j]['df']], ignore_index=True, axis=0)
# Embed pandas DataFrame document.add_header('table section') num_rows = 5 num_cols = 10 df = pd.DataFrame( data=np.random.randn(num_rows, num_cols), index=pd.date_range('19700101', periods=num_rows), columns=[f'c{i}' for i in range(num_cols)], ) df['col_str'] = 'value_str' document.add_table(df) # Enforce page break (useful when printing HTML to PDF in the browser) document.add_header('page break example') for i in range(15): document.add_text('mhm') document.add_text('before page break') document.add_page_break() document.add_header('after page break') # Add image link (filepath or URL) document.add_header('image from the Internet') image_url = 'https://spacecenter.org/wp-content/uploads/2020/01/KSC-20200117-PH-SPX01_0001_medium.jpg' document.add_image_link(image_url, width='100%') # Write to file output_filepath = 'first_document.html' document.write(output_filepath) print(f'{output_filepath} has been saved successfully!')
def test_HTMLDocument(): document = HTMLDocument() assert document.style != '' document.set_title(title='title') document.add_header(header='header', level='h2', align='left') document.add_text(text='text', size='15px', indent='0', align='left') document.add_line_break() document.add_page_break() document.add_table(df=_get_df()) try: document.add_table(df=[_get_df()]) except Exception as e: assert isinstance(e, TypeError) assert str( e ) == "df is of type <class 'list'>, but it should be of type <class 'pandas.core.frame.DataFrame'>." document.add_image(image=_get_image_array(), title='title', height=320, width=480, pixelated=False) document.add_image(image=_get_PIL_Image()) _create_test_image() document.add_image(image=_TEST_IMAGE_PATH) document.add_image_link(image_link=_TEST_IMAGE_PATH, title='title', width='100%') document.add_image(image=pathlib.Path(_TEST_IMAGE_PATH)) document.add_image_link(image_link=pathlib.Path(_TEST_IMAGE_PATH)) _remove_test_image() try: document.add_image(image=_get_image_array().astype(np.float32)) except Exception as e: assert isinstance(e, RuntimeError) assert str(e) == 'image.dtype is float32, but it should be uint8.' try: document.add_image( image=np.random.randint(0, 256, size=(1, 200, 200, 3)).astype(np.uint8)) except Exception as e: assert isinstance(e, RuntimeError) assert str(e) == 'image.ndim is 4, but it should be 2 or 3.' try: document.add_image(image=[_get_image_array()]) except Exception as e: assert isinstance(e, TypeError) assert str( e ) == "image is of type <class 'list'>, but it should be one of: <class 'numpy.ndarray'>, <class 'PIL.Image.Image'>, <class 'pathlib.Path'> or <class 'str'>." try: document.add_image_link(image_link=_get_image_array()) except Exception as e: assert isinstance(e, TypeError) assert str( e ) == "image_link is of type <class 'numpy.ndarray'>, but it should be <class 'pathlib.Path'> or <class 'str'>." document.write(_TEST_DOCUMENT_PATH) assert os.path.exists(_TEST_DOCUMENT_PATH) _remove_test_document()
class HTML_Report: def __init__(self, name, title=None): self.name = name self.document = HTMLDocument() self.document.set_title(title if title is not None else name) self.footer = '' self.document.style = ( \ """ body { max-width: 1060px; margin: auto; padding-bottom: 20px; font-family: "Lato", sans-serif; } p{ font-family: sans-serif; overflow-x: hidden; color: var(--gray90); font-family: "Lato", sans-serif; font-size: 1.5rem; line-height: 1.5rem; font-size:16px; text-indent: 0; text-align: left } div.pandas-dataframe { overflow: auto; } table.dataframe { border-collapse: collapse; border: none; } table.dataframe td { background-color: #fffef4; font-size: 14px; text-align: center; white-space: nowrap; margin: 0; padding-top: 0.4em; padding-bottom: 0.4em; padding-left: 0.5em; padding-right: 0.5em; border: 1px solid #d7d7d7; } table.dataframe th { background-color: #f9f9f9; font-size: 12px; text-align: center; white-space: nowrap; padding-left: 1em; padding-right: 1em; padding-top: 0.5em; padding-bottom: 0.5em; border: 1px solid #e0e0e0; } table.dataframe tr:nth-child(even) td { background: #fff2e4; } table.dataframe tr:nth-child(odd) td { background: #ffffe8; } table.dataframe tr:hover td { background-color: #ddeeff; } table.dataframe tbody th { font-weight: normal; } h4{ background-color: #F8F7F7 } h3{ background-color: #FDF2E9 } h2{ background-color: #FAE5D3 } h1{ background-color: #FDF2E9 } """) def add_header(self, header, level: int = 1): self.document.add_header(header, level=f'h{level}', align='center') print('##' + '>>' * (5 - level) + ' ' + header + ' ' + (5 - level) * '<<' + '##') def add_text(self, text): self.document.add_text( text) # defaults: size='16px', indent='0' alight='left' def add_html(self, text): self.document.body += text def add_line_break(self): self.document.add_line_break() def add_fig(self, fig, close=True): self.document.body += mpld3.fig_to_html(fig) if close: plt.close(fig) def add_df(self, df): self.document.add_table(df) def add_dict(self, dic): self.add_df(pd.Series(dic).to_frame().T) def add_img(self, image_url, title='', width_percent=100): self.document.add_image_link(image_url, title=title, width=f'{width_percent}%') def save(self, open=True): htmlfile = ProjectPaths.html_dir / f'{self.name} {uuid.uuid1()}.html' self.document.add_text(self.footer) self.document.write(htmlfile) print(f'{htmlfile} has been saved successfully!') if open: webbrowser.open_new_tab(htmlfile) def __exit__(self, exc_type, exc_val, exc_tb): try: self.save() except Exception as e: print(f'Can\'t save html. {e})') def __enter__(self): return self @staticmethod def __test__(): with HTML_Report('test') as doc: doc.add_header("Test report") doc.add_text('this is text ' * 20) doc.add_line_break() import numpy as np, datetime ts = pd.Series(np.random.randn(1000)) ts = ts.cumsum() plot = ts.plot() fig = plot.get_figure() doc.add_fig(fig) arrays = [ np.array( ['bar', 'bar', 'baz', 'baz', 'foo', 'foo', 'qux', 'qux']), np.array( ['one', 'two', 'one', 'two', 'one', 'two', 'one', 'two']) ] df = pd.DataFrame(np.random.randn(8, 4), index=arrays) doc.add_df(df) timestr = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") doc.add_text(f'Created at {timestr}') def add_footer(self, text): self.footer += text
) fig.update_layout( title={ 'text': parsed.title[0], 'x': 0.5, 'xanchor': 'center' }, xaxis={'title': x_label}, yaxis={'title': y_label}, height=parsed.height[0] * 96, width=parsed.width[0] * 96, legend={'title': None}, ) document.add_plotly_figure(fig) # Write to file document.write(plotfilename) show_timing(f"plot saved to {plotfilename}") if parsed.debug: print("------------") else: fig = plt.figure() for dataname in plot_data.keys(): show_timing(f"start plotting {dataname}") if dataname[-4:] == "_std": plt.fill_between(plot_data[dataname][0].index, plot_data[dataname][0], plot_data[dataname][1], color=clr[dataname], alpha=.3) else: plot_data[dataname].plot(label=dataname,