Skip to content
Snippets Groups Projects
Commit 6f384a88 authored by Benedikt's avatar Benedikt
Browse files

changed to page class based strukture like in https://gitlab1.ptb.de/TBruns/stosz/

parent dc810383
Branches
Tags
No related merge requests found
from bokeh.models import TabPanel, Tabs,FileInput, Dropdown
from bokeh.models import ColumnDataSource, DataTable,TableColumn
from bokeh.models import ColumnDataSource, DataTable,TableColumn,Div
from bokeh.layouts import column,row
from bokeh.plotting import figure, show, output_file,curdoc
from base64 import b64decode
from io import BytesIO
import pandas as pd
from openpyxl import load_workbook
sheetNames=[]
controalDict={}
dataDf=pd.DataFrame()
import logging
##FileUploadSide
import os
from datetime import datetime
class Page():
def __init__(self):
self.sheetNames=[]
self.controalDict={}
self.dataDf=pd.DataFrame()
self.busyCount=0
####GUI Elements
##Common
self.clock = Div(text="""<h2 style="color:#eeeeee";>This is a test</h2> """, width=400, height=50)
##Tab 1 File upload
self.dataFileInput = FileInput(title="Select Data files:", accept=".csv,.xls,.xlsx,.odf")
self.controalFileImput = FileInput(title="Optional select conversion control file:", accept=".json")
self.sheetSelectDropDown = Dropdown(label="Dropdown button", button_type="warning", menu=self.sheetNames,disabled=True)
self.dataFileInput.on_change('filename', self.dataFileUploadCallback)
self.sheetSelectDropDown.on_click(self.sheetSelectionCallBack)
self.tab1 = TabPanel(child=column(self.dataFileInput,self.controalFileImput,self.sheetSelectDropDown), title="File Upload")
###Tab 2 Data Selection
self.data_table = DataTable(
columns=[TableColumn(field=Ci, title=Ci) for Ci in self.dataDf.columns],
source=ColumnDataSource(self.dataDf),
height=1050,
width=1680
)
self.tab2 = TabPanel(child=row(self.data_table), title="TableView",disabled=False)#TODO deactivate as default
# put the button and plot in a layout and add to the document
self.page=column([self.clock,Tabs(tabs=[self.tab1, self.tab2])])
def dataFileUploadCallback(self,attr, old, new):
xlsData = b64decode(self.dataFileInput.value)
dataXLSFile=BytesIO(xlsData)
try:
os.mkdir("./tmp")
except:
pass
try:
os.mkdir("./tmp/"+str(curdoc().session_context.id))
except:
pass
path="./tmp/"+str(curdoc().session_context.id)+'/'+new
with open(path,'wb') as xlsFile:
xlsFile.write(xlsData)
wb = load_workbook(dataXLSFile,'wb')
self.controalDict['tmpFilePath'] = path
active_ws = wb.active
self.sheetNames=wb.sheetnames
self.sheetSelectDropDown.disabled=False
self.sheetSelectDropDown.menu=self.sheetNames
print("XLS upload Succeeded")
print(self.sheetNames)
def sheetSelectionCallBack(self,event):
self.controalDict['Sheet']=event.item
self.sheetSelectDropDown.label=str(self.controalDict['Sheet'])
self.sheetSelectDropDown.button_type='success'
#tab2.disabled=False# we have uplaoded an file and chosed a sheet so we can activate the next tab TODO fix this
self.tab2.update(disabled=False)
self.overAllTabs.active=1# switch to tabel view tab
self.overAllTabs.update()
self.dataDf=pd.read_excel(self.controalDict['tmpFilePath'], self.controalDict['Sheet'], engine='openpyxl')
self.data_table.source.data=self.dataDf
self.data_table.columns=[TableColumn(field=Ci, title=Ci) for Ci in self.dataDf.columns]
self.data_table.update()
print("Test")
# set time and date in the GUI (once per second)
def p_callback(self):
if self.busyCount == 0:
text = """<h3 style="background-color:powderblue;">%s</h3>""" % datetime.now().strftime("%d. %b %Y &nbsp&nbsp %H:%M:%S")
self.clock.text = text
else:
text = """<h3 style="background-color:coral;">%s BUSY! </h3>""" % datetime.now().strftime("%d. %b %Y &nbsp&nbsp %H:%M:%S")
self.clock.text = text
def make_doc(doc):
LOG_FORMAT = "%(levelname)s %(asctime)s - %(message)s"
file_handler = logging.FileHandler(filename='./bokeh.log', mode='w')
file_handler.setFormatter(logging.Formatter(LOG_FORMAT))
logger = logging.getLogger(__name__)
logger.addHandler(file_handler)
logger.setLevel(logging.DEBUG)
logger.info('This is bokeh_tableTool ...')
myPage = Page()
doc.add_root(myPage.page)
doc.title = "DCC table Tool"
doc.add_periodic_callback(myPage.p_callback, 500)
'''
Now the server part
'''
from tornado.ioloop import IOLoop
from bokeh.application.handlers import FunctionHandler
from bokeh.application import Application
from bokeh.server.server import Server
def main():
"""Launch the server and connect to it.
"""
print("Preparing a bokeh application.")
io_loop = IOLoop.current()
bokeh_app = Application(FunctionHandler(make_doc))
server = Server({"/": bokeh_app},
io_loop=io_loop,
http_server_kwargs={'max_buffer_size': 900000000},
websocket_max_message_size=500000000,
port = 5003,
allow_websocket_origin = ['*']
)
server.start()
print("Opening Bokeh application on http://localhost:5003/")
io_loop.add_callback(server.show, "/")
io_loop.start()
# This is run when called as python-script (python this_here.py)
if __name__ == '__main__':
main()
dataFileInput = FileInput(title="Select Data files:", accept=".csv,.xls,.xlsx,.odf")
controalFileImput = FileInput(title="Optional select conversion control file:", accept=".json")
sheetSelectDropDown = Dropdown(label="Dropdown button", button_type="warning", menu=sheetNames,disabled=True)
def dataFileUploadCallback(attr, old, new):
xlsData = b64decode(dataFileInput.value)
dataXLSFile=BytesIO(xlsData)
try:
os.mkdir("./tmp")
except:
pass
try:
os.mkdir("./tmp/"+str(curdoc().session_context.id))
except:
pass
path="./tmp/"+str(curdoc().session_context.id)+'/'+new
with open(path,'wb') as xlsFile:
xlsFile.write(xlsData)
wb = load_workbook(dataXLSFile,'wb')
controalDict['tmpFilePath'] = path
active_ws = wb.active
sheetNames=wb.sheetnames
sheetSelectDropDown.disabled=False
sheetSelectDropDown.menu=sheetNames
#sheetnamesDropDownMenue=[]
#for sName in sheetNames:
# sheetnamesDropDownMenue.append((sName,sName))
print("XLS upload Succeeded")
print(sheetNames)
def sheetSelectionCallBack(event):
controalDict['Sheet']=event.item
sheetSelectDropDown.label=str(controalDict['Sheet'])
sheetSelectDropDown.button_type='success'
#tab2.disabled=False# we have uplaoded an file and chosed a sheet so we can activate the next tab TODO fix this
tab2.update(disabled=False)
overAllTabs.active=1# switch to tabel view tab
overAllTabs.update()
dataDf=pd.read_excel(controalDict['tmpFilePath'], controalDict['Sheet'], engine='openpyxl')
data_table.source.data=dataDf
data_table.columns=[TableColumn(field=Ci, title=Ci) for Ci in dataDf.columns]
data_table.update()
print("Test")
dataFileInput.on_change('filename', dataFileUploadCallback)
sheetSelectDropDown.on_click(sheetSelectionCallBack)
tab1 = TabPanel(child=column(dataFileInput,controalFileImput,sheetSelectDropDown), title="File Upload")
###DataViewSide
data_table = DataTable(
columns=[TableColumn(field=Ci, title=Ci) for Ci in dataDf.columns],
source=ColumnDataSource(dataDf),
height=1050,
width=1680
)
tab2 = TabPanel(child=row(data_table), title="TableView",disabled=False)#TODO deactivate as default
# put the button and plot in a layout and add to the document
overAllTabs=Tabs(tabs=[tab1, tab2])
curdoc().add_root(overAllTabs)
\ No newline at end of file
# This is run when called by bokeh (bokeh serve --show --port 5003 this_here.py)
make_doc(curdoc())
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment