{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Using custom HTML templates"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:48:07.476401Z",
     "start_time": "2022-09-23T15:48:04.343150Z"
    }
   },
   "outputs": [],
   "source": [
    "import tslumen\n",
    "import pandas as pd\n",
    "import os"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:48:08.146767Z",
     "start_time": "2022-09-23T15:48:08.143181Z"
    },
    "nbsphinx": "hidden"
   },
   "outputs": [],
   "source": [
    "# patch it\n",
    "_read_csv = pd.read_csv\n",
    "pd.read_csv = lambda fpath, *args, **kwargs: _read_csv(fpath.split('/')[-1], *args, **kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:48:17.263039Z",
     "start_time": "2022-09-23T15:48:08.706268Z"
    }
   },
   "outputs": [],
   "source": [
    "df = pd.read_csv(\n",
    "    'https://datahub.io/core/gdp/r/gdp.csv', \n",
    "    parse_dates=[2], \n",
    "    date_parser=lambda dt: pd.to_datetime(f'{dt}-12-31'),\n",
    ")\n",
    "df = df[df['Country Code'].isin(['WLD', 'EUU', 'USA', 'HIC', 'MIC', 'LIC'])]\\\n",
    "    .set_index(['Year', 'Country Code'])['Value'].unstack(1)\n",
    "\n",
    "pr = tslumen.DefaultProfiler().profile(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Customizing a single Section"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "HTML generation is performed with the help of [Jinja](https://palletsprojects.com/p/jinja/). All templates are included in the package but can be easily overriden simply by creating the custom version locally. The way it works is first it tries to find the template in some pre-defined local directories, defaulting to the packaged ones if a local version is not found."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:48:41.674924Z",
     "start_time": "2022-09-23T15:48:41.669387Z"
    }
   },
   "outputs": [],
   "source": [
    "tslumen.report.html.base.JINJA_FILE_SEARCHPATHS"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above are the directories where `tslumen` searches for the templates, in order of precedence.\n",
    "\n",
    "Let's start by generating the pre-canned *Features* section and then create our own HTML template."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:48:43.507125Z",
     "start_time": "2022-09-23T15:48:43.019184Z"
    }
   },
   "outputs": [],
   "source": [
    "sf = tslumen.report.html.sections.SectionTSFeatures(pr, {}, df)\n",
    "sf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:49:16.930536Z",
     "start_time": "2022-09-23T15:49:16.926468Z"
    }
   },
   "outputs": [],
   "source": [
    "for attr in dir(sf):\n",
    "    if not attr.startswith('_'):\n",
    "        print(f'{attr:12s}', type(getattr(sf, attr)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "These are the class attributes we can use in our Jinja template. Obviously for an even more advanced customization you might want to create your own section and report classes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:49:33.444839Z",
     "start_time": "2022-09-23T15:49:33.440586Z"
    }
   },
   "outputs": [],
   "source": [
    "os.makedirs('./templates/html', exist_ok=True)\n",
    "with open('./templates/html/SectionTSFeatures.html', 'w') as fp:\n",
    "    fp.write('''\\\n",
    "{% from '_macros.html' import render_dataframe %}\n",
    "<h1>My Custom SectionTSFeatures</h1>\n",
    "{{ render_dataframe('FTS', obj.df_fts) }}\n",
    "''')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:49:34.713948Z",
     "start_time": "2022-09-23T15:49:34.611391Z"
    }
   },
   "outputs": [],
   "source": [
    "tslumen.report.html.sections.SectionTSFeatures(pr, {}, df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "As you may have noticed, the template makes use of a macro defined elsewhere. Without going into the details of Jinja's templating engine, there is a hierarchical structure implied in tslumen's templates, as well as some useful filters and macros. Refer to the source code for more details.\n",
    "\n",
    "If we render the full report, the *Features* sections will now look different."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:49:45.442729Z",
     "start_time": "2022-09-23T15:49:39.402567Z"
    }
   },
   "outputs": [],
   "source": [
    "tslumen.HtmlReport(df, result=pr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "## Creating a custom HTML Report"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We will now create a custom section and a custom report along with their HTML templates.  \n",
    "The report will include the new section and 2 of tslumen's default ones, where for one of them we have redefined the template locally (previous chapter)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:49:52.367926Z",
     "start_time": "2022-09-23T15:49:52.362604Z"
    }
   },
   "outputs": [],
   "source": [
    "with open('./templates/html/SectionExecution.html', 'w') as fp:\n",
    "    fp.write('''\\\n",
    "{% extends \"_section.html\" %}\n",
    "{% from '_macros.html' import render_dataframe %}\n",
    "{% block section_content -%}\n",
    "{{ render_dataframe('10 slowest profiling function executions', obj.top10) }}\n",
    "{%- endblock %}''')\n",
    "    \n",
    "\n",
    "class SectionExecution(tslumen.report.html.base.HtmlBlock):\n",
    "    _id = \"exec\"\n",
    "    _title = \"Execution\"\n",
    "\n",
    "    def __init__(self, result, meta, df, scheduler):\n",
    "        self.top10 = result.result.exec_details\\\n",
    "            .sort_values('Duration', ascending=False)\\\n",
    "            .reset_index(drop=True).head(10)[['Profiler', 'Scope', 'Target', 'Duration']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:49:54.975471Z",
     "start_time": "2022-09-23T15:49:54.971033Z"
    }
   },
   "outputs": [],
   "source": [
    "with open('./templates/html/MyReport.html', 'w') as fp:\n",
    "    fp.write('''\\\n",
    "{% block content -%}\n",
    "<a class=\"anchor-pos\" id=\"top\"></a>\n",
    "{%  for section in obj.sections -%}\n",
    "  {{ section|html }}\n",
    "{%- endfor %}\n",
    "{%- endblock content %}''')\n",
    "\n",
    "\n",
    "class MyReport(tslumen.HtmlReport):\n",
    "    SECTIONS = [\n",
    "        tslumen.report.html.sections.SectionTSFeatures,\n",
    "        tslumen.report.html.sections.SectionRelations,\n",
    "        SectionExecution,\n",
    "    ]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:50:01.851946Z",
     "start_time": "2022-09-23T15:49:58.168565Z"
    }
   },
   "outputs": [],
   "source": [
    "MyReport(df, result=pr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-09-23T15:50:02.650161Z",
     "start_time": "2022-09-23T15:50:02.644799Z"
    },
    "nbsphinx": "hidden"
   },
   "outputs": [],
   "source": [
    "# cleanup\n",
    "os.remove('./templates/html/MyReport.html')\n",
    "os.remove('./templates/html/SectionExecution.html')\n",
    "os.remove('./templates/html/SectionTSFeatures.html')\n",
    "os.removedirs('./templates/html')"
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Edit Metadata",
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": false,
   "skip_h1_title": true,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
