Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 57 additions & 36 deletions flexp/browser/browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
Options:
-h --help Show this screen.
"""

from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
Expand All @@ -23,17 +24,16 @@
import tornado.ioloop
import tornado.web

from flexp.browser.html.generic import DescriptionToHtml, FilesToHtml, ImagesToHtml, FlexpInfoToHtml, CsvToHtml, TxtToHtml, StringToHtml
from flexp.browser.html.generic import DescriptionToHtml, FilesToHtml, \
ImagesToHtml, FlexpInfoToHtml, CsvToHtml, TxtToHtml, StringToHtml
from flexp.browser.html.to_html import ToHtml
from flexp.flow import Chain
from flexp.utils import import_by_filename
from flexp.browser.utils import setup_logging
from flexp.utils import get_logger


log = get_logger(__name__)


default_html = [
FlexpInfoToHtml(),
ImagesToHtml(),
Expand All @@ -45,11 +45,12 @@
default_html_chain = Chain(default_html)


def run(port=7777, chain=list()):
"""Run the whole browser with optional own `port` number and `chain` of ToHtml modules."""
def run(port=7777, chain=list(), experiments_dir=os.getcwd()):
"""Run the whole browser with optional own `port` number and `chain` of
ToHtml modules. """

MainHandler.experiments_folder = os.getcwd()
AjaxHandler.experiments_folder = os.getcwd()
MainHandler.experiments_folder = experiments_dir
AjaxHandler.experiments_folder = experiments_dir

# append new modules to the default chain
if isinstance(chain, ToHtml):
Expand All @@ -68,9 +69,12 @@ def run(port=7777, chain=list()):
here_path = os.path.dirname(os.path.abspath(__file__))
app = tornado.web.Application([
(r"/", MainHandler),
(r'/(favicon.ico)', tornado.web.StaticFileHandler, {"path": path.join(here_path, "static/")}),
(r"/file/(.*)", NoCacheStaticHandler, {'path': MainHandler.experiments_folder}),
(r"/static/(.*)", tornado.web.StaticFileHandler, {'path': path.join(here_path, "static")}),
(r'/(favicon.ico)', tornado.web.StaticFileHandler,
{"path": path.join(here_path, "static/")}),
(r"/file/(.*)", NoCacheStaticHandler,
{'path': MainHandler.experiments_folder}),
(r"/static/(.*)", tornado.web.StaticFileHandler,
{'path': path.join(here_path, "static")}),
(r"/ajax", AjaxHandler)],
{"debug": True}
)
Expand Down Expand Up @@ -162,12 +166,14 @@ class MainHandler(tornado.web.RequestHandler):

def get(self):
experiment_folder = self.get_argument("experiment", default="")
log.info("experiment folder {}".format(self.experiments_folder))
experiment_path = path.join(self.experiments_folder, experiment_folder)

if not path.isdir(experiment_path):
experiment_folder = ""

navigation_html = html_navigation(self.experiments_folder, experiment_folder)
navigation_html = html_navigation(self.experiments_folder,
experiment_folder)
header_html = ""
scripts_html = ""

Expand All @@ -181,14 +187,17 @@ def get(self):
# Use custom chain, if present
if os.path.exists(experiment_path + "/custom_flexp_chain.py"):
try:
custom_flexp_chain = import_by_filename('custom_flexp_chain',
experiment_path + "/custom_flexp_chain.py")
custom_flexp_chain = import_by_filename(
'custom_flexp_chain',
experiment_path + "/custom_flexp_chain.py")
html_chain = custom_flexp_chain.get_chain()
html_chain = Chain(html_chain)
except:
html_chain = Chain([StringToHtml("<h2>Error processing custom chain. {}</h2>"
.format(traceback.format_exc().replace("\n", "</br>")),
title="Error in custom chain")] + self.html_chain.modules)
html_chain = Chain([StringToHtml(
"<h2>Error processing custom chain. {}</h2>"
.format(
traceback.format_exc().replace("\n", "</br>")),
title="Error in custom chain")] + self.html_chain.modules)
finally:
if "custom_flexp_chain" in sys.modules:
del sys.modules["custom_flexp_chain"]
Expand All @@ -201,7 +210,8 @@ def get(self):
title_html = "<h1>{}</h1>".format(experiment_folder)
content_html = u"\n".join(data['html'])
navigation_html = html_anchor_navigation(
experiment_path, experiment_folder, html_chain) + navigation_html
experiment_path, experiment_folder,
html_chain) + navigation_html

header_html = u"\n".join(u"\n".join(html_lines)
for head_section, html_lines
Expand Down Expand Up @@ -247,15 +257,18 @@ def post(self):
# print(action, value, new_name)
folder = os.path.join(self.experiments_folder, value)
new_folder = os.path.join(self.experiments_folder, new_name)
if os.path.exists(folder) and not os.path.exists(new_folder) and "/" not in value and "/" not in new_name:
if os.path.exists(folder) and not os.path.exists(
new_folder) and "/" not in value and "/" not in new_name:
os.rename(folder, new_folder)
else:
self.send_error(500, reason="Rename folder not successful. Check old and new name.")
self.send_error(500,
reason="Rename folder not successful. Check old and new name.")

if action == "change_file_content":
new_content = self.get_argument('new_content')
file_name = self.get_argument('file_name')
with open(os.path.join(self.experiments_folder, value, file_name), "w") as file:
with open(os.path.join(self.experiments_folder, value, file_name),
"w") as file:
file.write(new_content)


Expand All @@ -275,8 +288,10 @@ def html_table(base_dir):
"<td>{exp_dir}</td>"
"<td>{description}</td>"
"</tr>".format(exp_dir=exp_dir,
description=DescriptionToHtml.get_description_html(exp_path))
for exp_dir, exp_path, date_changed in list_experiments(base_dir)),
description=DescriptionToHtml.get_description_html(
exp_path))
for exp_dir, exp_path, date_changed in
list_experiments(base_dir)),
""" </tbody>
</table>"""))

Expand Down Expand Up @@ -314,7 +329,8 @@ def html_navigation(base_dir, selected_experiment=None):
<a class=\"{classes} left-margin\" href=\"?experiment={exp_dir}\" title=\"{title}\" style='padding-left:2px'>{exp_dir}</a>
</div>""".format(
exp_dir=exp_dir,
title=DescriptionToHtml.get_description_html(exp_path, replace_newlines=False),
title=DescriptionToHtml.get_description_html(exp_path,
replace_newlines=False),
classes=" ".join(classes)))
return header + "\n".join(items)

Expand Down Expand Up @@ -344,19 +360,20 @@ def html_anchor_navigation(base_dir, experiment_dir, modules):
))


# , '{exp_dir}'


def list_experiments(base_dir):
"""Return list of tuples(experiment_directory, experiment_absolute_path).
"""Return list of tuples(experiment_directory, experiment_absolute_path,
last modified time) sorted by modification time.

:param base_dir: parent folder in which to look for an experiment folders
:return: list[tuple[str, str]]
:return: list[tuple[str, str, int]]
"""
return sorted([(exp_dir, path.join(base_dir, exp_dir), os.path.getmtime(exp_dir))
for exp_dir in os.listdir(base_dir)
if path.isdir(path.join(base_dir, exp_dir))],
key=lambda x: x[2], reverse=True)
return sorted([
(exp_dir,
path.join(base_dir, exp_dir),
os.path.getmtime(path.join(base_dir, exp_dir)))
for exp_dir in os.listdir(base_dir)
if path.isdir(path.join(base_dir, exp_dir))],
key=lambda x: x[2], reverse=True)


class NoCacheStaticHandler(tornado.web.StaticFileHandler):
Expand All @@ -366,12 +383,16 @@ def should_return_304(self):
return False


@click.command()
@click.option('--port', '-p', default=7777, help='Port where to run flexp browser')
def main(port):
@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--port', '-p', default=7777,
help='Port where to run flexp browser')
@click.option('--experiments_dir', '-d', default=os.getcwd(),
help='path to directory with experiments')
def main(port, experiments_dir):
"""Console entry point launched by flexp-browser command."""
setup_logging("info")
run(port)
run(port=port,
experiments_dir=experiments_dir)


if __name__ == "__main__":
Expand Down