def createGui(self):
		# self.chatBox = self.createChatBox()
		self.messageWindow = self.createMessageWindow()
		headerDiv = Div(text="<link rel='stylesheet' type='text/css' href='templates/styles.css'>")

		self.createKeyboardCoordinates()

		self.englishInput = AutocompleteInput(value = "",title = "English:",completions = ["bath","bathtub"])
		self.englishInput.on_change("value",self.englishBoxCallback)

		self.text_input = TextInput(value="", title="Message:",width = self.keyboardWidth - 300)
		self.text_input.on_change("value",self.textBoxcallback)

		sendButton = Button(label="↩",button_type = "primary")
		sendButton.on_click(self.sendMessage)
		self.suggestedCategoryRow = self.createEmojiFigure("Row","Suggested")
		self.suggestedCategoryRow.on_event(Tap,self.suggestedSelectCallback)

		self.suggestedCategoryRow.title.text = "💡"
		self.suggestedCategoryRow.title.text_font_size = "20pt"

		mainCategoryFigure = self.createEmojiFigure("Column","Main")
		mainCategoryFigure.title.text = "🐘📦"
		mainCategoryFigure.title.text_font_size = "30pt"
		mainCategoryFigure.on_event(Tap,self.mainCategorySelectCallback)
		mainCategoryFigure.js_on_event(DoubleTap,self.playSound)

		subCategoryFigure = self.createEmojiFigure("Column","Sub")
		subCategoryFigure.title.text = "🥖📦"
		subCategoryFigure.title.text_font_size = "30pt"
		subCategoryFigure.name = "sub"
		subCategoryFigure.on_event(Tap,self.subCategorySelectCallback)

		self.emojiKeyboard = self.createMainEmojiWindow()
		self.emojiKeyboard.title.text = "⌨"
		self.emojiKeyboard.title.text_font_size = "30pt"
		self.gui = column(
			headerDiv,
			self.messageWindow,
			row(self.englishInput,self.text_input,sendButton),
			self.suggestedCategoryRow,
			row(self.emojiKeyboard,subCategoryFigure,mainCategoryFigure)
		)
Ejemplo n.º 2
0
split = Dropdown(label="Split button", button_type="danger", menu=split_menu)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"],
                               active=[0, 1])

radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)

checkbox_button_group = CheckboxButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])

radio_button_group = RadioButtonGroup(
    labels=["Option 1", "Option 2", "Option 3"], active=0)

text_input = TextInput(placeholder="Enter value ...")

autocomplete_input = AutocompleteInput()

select = Select(options=["Option 1", "Option 2", "Option 3"])

multi_select = MultiSelect(options=["Option %d" % (i + 1) for i in range(16)],
                           size=6)

slider = Slider(value=10, start=0, end=100)

range_slider = RangeSlider()

#date_range_slider = DateRangeSlider(value=(date(2016, 1, 1), date(2016, 12, 31)))

date_picker = DatePicker()

paragraph = Paragraph(text="some text")
Ejemplo n.º 3
0
    RadioButtonGroup(
        labels=["Radio Option 1", "Radio Option 2", "Radio Option 3"],
        button_type="default",
        active=0),
    RadioButtonGroup(
        labels=["Radio Option 4", "Radio Option 5", "Radio Option 6"],
        button_type="primary",
        active=1),
    RadioButtonGroup(
        labels=["Radio Option 7", "Radio Option 8", "Radio Option 9"],
        button_type="success",
        active=2),
    TextInput(placeholder="TextInput 1"),
    TextInput(placeholder="TextInput 2"),
    TextInput(placeholder="TextInput 3"),
    AutocompleteInput(placeholder="AutocompleteInput 1 ...",
                      completions=["aaa", "aab", "aac", "baa", "caa"]),
    AutocompleteInput(placeholder="AutocompleteInput 2 ...",
                      completions=["AAA", "AAB", "AAC", "BAA", "CAA"]),
    AutocompleteInput(placeholder="AutocompleteInput 3 ...",
                      completions=["000", "001", "002", "100", "200"]),
    DatePicker(value=date(2018, 9, 1)),
    DatePicker(value=date(2018, 9, 2)),
    DatePicker(value=date(2018, 9, 3)),
)

#Slider(value=10, start=0, end=100, step=0.5),
#RangeSlider(value=[20, 30], start=0, end=100, step=0.5),
#DateSlider(value=date(2018, 9, 1), start=date(2018, 1, 1), end=date(2018, 12, 31)),
#DateRangeSlider(value=(date(2018, 9, 1), date(2018, 9, 30)), start=date(2018, 1, 1), end=date(2018, 12, 31)),

#CheckboxGroup(labels=["Checkbox Option 1", "Checkbox Option 2", "Checkbox Option 3"], active=[0, 1]),
Ejemplo n.º 4
0
def mapping_sentences_words(input_file):
    output_file(filename="../dashboards/sentences_words.html", title="Intermediate representations")

    ###################################################
    # PREPARING DATA
    ###################################################

    index = 0
    id_sentence = list()
    id_word = list()
    x = list()
    y = list()
    sentences = list()
    language_sentence = list()
    language_word = list()
    words = list()
    x_words = list()
    y_words = list()
    links = dict()
    with open(input_file, 'r') as file:
        array = json.load(file)
        data = array['content']
        for idx, translations in data.items():
            nbr_lang = len(translations)
            for lang, info in translations.items():
                id_sentence.append(idx)
                language_sentence.append(lang)
                sentences.append(info['sentence'])
                x.append(info['embedding'][0])
                y.append(info['embedding'][1])
                for word, emb in info['words'].items():
                    id_word.append(idx)
                    language_word.append(lang)
                    words.append(word)
                    x_words.append(emb[0])
                    y_words.append(emb[1])
            for i in range(nbr_lang):
                links[index + i] = [index + j for j in range(nbr_lang) if j != i]
            index += nbr_lang

        source_sentence_dict = {
            "id": id_sentence,
            "x": x,
            "y": y,
            "lang": language_sentence,
            "sentence": sentences
        }

        source_word_dict = {
            "id": id_word,
            "x": x_words,
            "y": y_words,
            "lang": language_word,
            "word": words
        }

    source_sentences = ColumnDataSource(source_sentence_dict)
    source_words = ColumnDataSource(source_word_dict)
    source_words_visible = ColumnDataSource(source_word_dict)

    ###################################################
    # SET UP SENTENCE FIGURE
    ###################################################

    tools = "hover, tap, box_select, reset, help"
    p = figure(plot_width=800, plot_height=700, tools=tools, title='Intermediate representations')

    cr = p.circle('x', 'y',
                  size=6, alpha=0.6,
                  hover_color='yellow', hover_alpha=1.0,
                  source=source_sentences,
                  color=factor_cmap('lang',
                                    palette=['red', 'blue', 'green'],
                                    factors=['en', 'fr', 'es']),
                  legend='lang',
                  name="sentences")

    ###################################################
    # SET UP LINKS BETWEEN TRANSLATIONS
    ###################################################

    source = ColumnDataSource({'x0': [], 'y0': [], 'x1': [], 'y1': []})
    sr = p.segment(x0='x0', y0='y0', x1='x1', y1='y1', color='black', alpha=0.6, line_width=1, source=source)

    code = """
    var links = %s;
    var data = {'x0': [], 'y0': [], 'x1': [], 'y1': []};
    var cdata = circle.data;
    var indices = cb_data.index['1d'].indices;
    for (var i = 0; i < indices.length; i++) {
        var ind0 = indices[i]
        for (var j = 0; j < links[ind0].length; j++) {
            var ind1 = links[ind0][j];
            data['x0'].push(cdata.x[ind0]);
            data['y0'].push(cdata.y[ind0]);
            data['x1'].push(cdata.x[ind1]);
            data['y1'].push(cdata.y[ind1]);
        }
    }
    segment.data = data;
    """ % links

    ###################################################
    # ADD LINKS IN HOVERTOOL
    ###################################################

    callback = CustomJS(args={'circle': cr.data_source,
                              'segment': sr.data_source}, code=code)
    p.add_tools(HoverTool(callback=callback, renderers=[cr]))
    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [
        ("sentence", "@sentence"),
    ]
    hover.names = [
        "sentences"
    ]

    ###################################################
    # SET UP WORD FIGURE
    ###################################################

    p_w = figure(title='Words', tools="reset")
    p_w.circle('x', 'y',
               size=6, alpha=0.6,
               hover_color='yellow', hover_alpha=1.0,
               selection_color='yellow',
               nonselection_color='white',
               source=source_words_visible,
               color=factor_cmap('lang',
                                 palette=['red', 'blue', 'green'],
                                 factors=['en', 'fr', 'es']),
               legend='lang',
               name="words")

    hover_word = HoverTool(tooltips=[('word', '@word')],
                           names=['words'])
    p_w.add_tools(hover_word)

    source_sentences.selected.js_on_change('indices', CustomJS(args=dict(sentences=source_sentences,
                                                                         words=source_words,
                                                                         words_visible=source_words_visible),
                                                               code="""
            var inds = cb_obj.indices;
            var sentences = sentences.data;
            var words = words.data;
            var words_visible = words_visible.data
            
            words_visible.id = []
            words_visible.x = []
            words_visible.y = []
            words_visible.lang = []
            words_visible.word = []
            
            console.log(sentences.id[inds])
            for (var i = 0; i < words.x.length; i++) {
                if (words.id[i] == sentences.id[inds]) {
                    words_visible.id.push(words.id[i])
                    words_visible.x.push(words.x[i])
                    words_visible.y.push(words.y[i])
                    words_visible.lang.push(words.lang[i])
                    words_visible.word.push(words.word[i])
                }
            }
            words_visible.change.emit();
        """)
                                           )

    text_input = AutocompleteInput(title='Search a sentence', completions=sentences)

    ###################################################
    # CREATION OF THE LAYOUT
    ###################################################

    # window = layout([p, words], sizing_mode='stretch_both')
    window = row(p, column(p_w, text_input))
    show(window)
Ejemplo n.º 5
0
                source_words_visible_dict['lang'].append(
                    source_words.data['lang'][idx])
                source_words_visible_dict['word'].append(
                    source_words.data['word'][idx])
    source_words_visible.data = source_words_visible_dict

    # source_words_visible.selected.indices = indices


source_sentences.selected.on_change('indices', update_words)

###################################################
# ADD TEXT INPUT
###################################################

text_input = AutocompleteInput(title='Select a sentence',
                               completions=sentences)


def update_sentences(attr, old, new):
    sentence = text_input.value
    ind = [
        j for j, sent in enumerate(source_sentences.data['sentence'])
        if sent == sentence
    ]
    source_sentences.selected.indices = ind


text_input.on_change('value', update_sentences)

###################################################
# ADD RESET BUTTON
Ejemplo n.º 6
0
    of "minus line" will be returned first. Result will be used for unpacking values to line figures.
    :param provider: str in ["emhi", "yrno"]
    :return: [{"y": ..., "x": ..., "source": ..., "color": ...}, same]
    """
    global source
    defaults = {"x": "start", "source": source}
    y_and_color_based_on_plus_dominance = {
        True: {"1y": "minus", "1c": "#48AFE8", "2y": "plus", "2c": "firebrick"},  # True if plus dominates
        False: {"1y": "plus", "1c": "firebrick", "2y": "minus", "2c": "#48AFE8"},  # False if plus does not dominate
    }
    vmap = y_and_color_based_on_plus_dominance[temp_plus_dominates[provider]]
    return [{"y": "temp_{}_{}".format(provider, vmap["1y"]), "color": vmap["1c"], **defaults},
            {"y": "temp_{}_{}".format(provider, vmap["2y"]), "color": vmap["2c"], **defaults}]


city_picker = AutocompleteInput(value="Tartu", title="\n",
                                completions=list(CITY_MAP))
city_picker.on_change("value", lambda attr, old, new: update())

source = ColumnDataSource(
    data=dict(
        start=[],  # Python datetime objects
        temp_emhi=[],  # All EMHI temperatures - needed for the positioning of cloud-symbols.
        temp_emhi_plus=[],  # EMHI temperatures above 0.
        temp_emhi_minus=[],  # EMHI temperatures below 0.
        precipitation_emhi=[],
        temp_yrno=[],
        temp_yrno_plus=[],
        temp_yrno_minus=[],
        precipitation_yrno=[],
        symbol_yrno=[],  # Cloud-symbols
        symbol_emhi=[]
class emojiPicker:

	def __init__(self):
		self.setupVariables()
		self.createGui()

		self.loadEmojis()

	def setupVariables(self):
		self.keyboardHeight = 650
		self.keyboardWidth = 1200

		self.categoryClickIndex = 0

		self.colWidth = 100
		self.colHeight = self.keyboardHeight
		self.rowHeight = 120

		self.rowWidth = self.keyboardWidth + 2 * self.colWidth

		#keyboard spacing variables
		self.midRowXOffset = .2
		self.keyboardYOffset = .5

		self.keyboardYSpacing = 1
		self.keyBoardXSpacing = 1

		self.TOOLTIPS = """<div>@names</div>"""
		self.TOOLTIPS =  """<div class="btn-group">
			  <button>@names 🔊</button>
			  <button>Schadenfreude 🔊</button>
			  <button>⻄⻇ 🔊</button>
			</div> """

		# var audio = new Audio('emojiMessenger/static/audio.mp3');
		self.filename = "audio.mp3"
		self.playSound = CustomJS(args=dict(filename = self.filename), code = 
			"""
			var audio = new Audio('emojiMessenger/static/'.concat(filename));
			audio.play();
			"""
			)

	def loadEmojis(self):
		self.sessionId = emojiDber.getSessionId()
		self.friendId = emojiDber.checkForUnmatchedFriendId(self.sessionId)

		#main category
		self.mainCategoryNames = emojiDber.getMasterCategories()[1:]
		mainCategoryIcons = emojiDber.getSubCategoriesIcons("MASTER",self.mainCategoryNames)
		self.updateEmojiFigure("Main","Column",mainCategoryIcons)

		#pick the first main category
		self.activeMainCategory = self.mainCategoryNames[0]
		subCategories = emojiDber.getSubCategories(self.activeMainCategory)
		subCategoryIcons = emojiDber.getSubCategoriesIcons(self.activeMainCategory,subCategories)
		self.updateEmojiFigure("Sub","Column",subCategoryIcons)

		#pick the first subcategory
		self.activeSubCategory = subCategories[0]

		#get suggested emojis
		suggestedEmojis = emojiDber.getRelevantEmojis(self.activeMainCategory)
		self.updateEmojiFigure("Suggested","Row",suggestedEmojis)

		#get emojis to display on the keyboars
		subCategoryEmojis = emojiDber.getCategoryTopEmojis(self.activeSubCategory)

		#fill in the difference with main cateogry emojis
		numSubEmojis = len(subCategoryEmojis)
		mainCategoryEmojies = emojiDber.getCategoryTopEmojis(self.activeMainCategory,NUM_TO_GET = 26 - numSubEmojis)
		keyboardEmojisDict = {**subCategoryEmojis,**mainCategoryEmojies}

		self.updateKeyboardFigure(keyboardEmojisDict)

	def updateEmojiFigure(self,figureName,figureType,emojisDict):
		newData = self.createCategoryGlyphSource(emojisDict,figureType)
		self.gui.select_one({"name":figureName}).data = newData

	def updateKeyboardFigure(self,emojisDict):
		newNames = list(emojisDict.keys())
		newEmojis = list(emojisDict.values())

		numEmojis = len(newNames)
		if numEmojis < 26:
			diff = 26 - numEmojis
			newNames += [""] * diff
			newEmojis += [""] * diff

		keyboardSourceDict = (self.emojiKeyboard.select_one({"name":"emojis"})).data_source.data
		keyboardSourceDict["names"] = newNames
		keyboardSourceDict["text"] = newEmojis
		(self.emojiKeyboard.select_one({"name":"emojis"})).data_source.data = keyboardSourceDict

	def createCategoryGlyphSource(self,categoriesDict,figureType):
		categoryEmojies = list(categoriesDict.values())
		categoryNames = list(categoriesDict.keys())
		numCategories = len(categoriesDict.keys())
		indices = range(1,1+numCategories)

		categoryFills = [0] * numCategories

		categoryXs = [0] * numCategories
		categoryYs = range(numCategories)
		if figureType == "Row":
			categoryXs, categoryYs = categoryYs,categoryXs
		else:
			categoryFills[-1] = 1

		categoryGlyphSourceDict = dict(x=categoryXs, y=categoryYs, text=categoryEmojies,names = categoryNames,fills = categoryFills,indices=indices)
		return categoryGlyphSourceDict

	def createEmojiFigure(self,figureType,name):
		#creates either a row or column to display emojies in
		numCategories = 10
		if figureType == "Column":
			height = self.colHeight
			width = self.colWidth
			xRange = (-.5,.5)
			yRange = (-.5,numCategories-.5)
			yOffset = 20

		else:
			height = self.rowHeight
			width = self.rowWidth
			xRange = (-.5,numCategories-.5)
			yRange = (-.4,.6)
			yOffset = 20

		categoriesFigure = figure(title = "Title",
			plot_height = height, plot_width = width,
			x_range=xRange,y_range=yRange,
			toolbar_location = None,tools = "")

		categoriesFigure.axis.visible = False
		categoriesFigure.grid.visible = False

		categorySourceDict = dict(x=[], y=[], text=[],names = [],fills = [],indices=[])

		# categorySourceDict = self.createCategoryGlyphSource(categoriesDict,figureType)
		categorySource = ColumnDataSource(categorySourceDict,name = name)

		#text glyph to display emojies
		categoriesGlyph = Text(x="x", y="y", text="text", angle=0,y_offset=yOffset,
			text_color="black",text_alpha = 1,
			text_font_size='35pt',text_align = "center")

		categoriesFigure.add_glyph(categorySource, categoriesGlyph)

		if figureType == "Row":
			categoryIndexText =  Text(x="x", y="y", text="indices", angle=0,y_offset=-10,x_offset= -50,
				text_color="black",text_alpha = 1,
				text_font_size='20pt',text_align = "center")
			categoriesFigure.add_glyph(categorySource,categoryIndexText)

		#hidden circle glyph used to allow hovertool to work to show tooltips
		categoryCircleGlyph = Circle(x="x", y="y",radius=.45,fill_alpha = 0,line_alpha = "fills")
		circleGlyph = categoriesFigure.add_glyph(categorySource, categoryCircleGlyph, name = "circles")
		#create hover tool and add it to figure
		categoryHoverer = HoverTool(renderers=[circleGlyph], tooltips=self.TOOLTIPS)
		categoriesFigure.add_tools(categoryHoverer)

		return categoriesFigure

	def mainCategorySelectCallback(self,event):
		self.categoryClickIndex += 1
		x,y = (event.x, event.y)
		index = int(y)

		selectedCategory = self.mainCategoryNames[index]
		self.activeMainCategory = selectedCategory

		#update the selected category indicator		
		newFills = [0] * len(self.mainCategoryNames)
		newFills[index] = 1
		self.gui.select_one({"name":"Main"}).data["fills"] = newFills

		#update sub categories
		subCategories = emojiDber.getSubCategories(self.activeMainCategory)
		subCategoryIcons = emojiDber.getSubCategoriesIcons(selectedCategory,subCategories)
		self.updateEmojiFigure("Sub","Column",subCategoryIcons)

		#pick the first new subcategory
		self.activeSubCategory = subCategories[0]
		subCategoryEmojis = emojiDber.getCategoryTopEmojis(self.activeSubCategory)

		#fill in the difference with main cateogry emojis
		numSubEmojis = len(subCategoryEmojis)
		mainCategoryEmojies = emojiDber.getCategoryTopEmojis(self.activeMainCategory,NUM_TO_GET = 26 - numSubEmojis)
		keyboardEmojisDict = {**subCategoryEmojis,**mainCategoryEmojies}

		self.updateKeyboardFigure(keyboardEmojisDict)

	def subCategorySelectCallback(self,event):
		#keep track of how many categories clicked throiugh until an answer found
		self.categoryClickIndex += 1

		x,y = (event.x, event.y)
		index = int(y)
		subCategoryDict = self.gui.select_one({"name":"Sub"}).data

		#update the selected category indicator		
		newFills = [0] * len(subCategoryDict["fills"])
		newFills[index] = 1
		self.gui.select_one({"name":"Sub"}).data["fills"] = newFills

		#change the active categroy abd get the emojis belonging to it
		self.activeSubCategory = subCategoryDict["names"][index]
		subCategoryEmojis = emojiDber.getCategoryTopEmojis(self.activeSubCategory)

		numSubEmojis = len(subCategoryEmojis.keys())

		mainCategoryEmojies = emojiDber.getCategoryTopEmojis(self.activeMainCategory,NUM_TO_GET = 26 - numSubEmojis)
		keyboardEmojisDict = {**subCategoryEmojis,**mainCategoryEmojies}

		self.updateKeyboardFigure(keyboardEmojisDict)

	def suggestedSelectCallback(self,event):
		x,y = (event.x, event.y)
		index = int(x)
		suggestedEmojis = self.gui.select_one({"name":"Suggested"}).data["text"]

		clickedEmoji = suggestedEmojis[index]

		self.text_input.remove_on_change("value",self.textBoxcallback)
		self.text_input.value += (clickedEmoji)
		self.text_input.on_change("value",self.textBoxcallback)

		self.analyzeNgram(self.text_input.value,"tapped")

	def xyCoordsToKeyboardKey(self,x,y):
		"""given an (X,Y) cooridnate, returns the key pressed
		on a qwerty keyboard"""

		rowIndex = int(y/(self.keyboardYSpacing))
		colIndex = (x-(rowIndex*self.midRowXOffset))/self.keyBoardXSpacing
		clickedLetter = self.letters[int(rowIndex)][int(colIndex)]
		return clickedLetter


	def emojiDoubleTapCallback(self,event):
		#called when an emoji keyboard is double tapped
		#updates the suggested categories, but doesn't add it to the textbox
		print (1)

	def emojiTapCallback(self,event):
		#called when an emoji on the keyboard window is single tapped
		x,y = (event.x, event.y)
		index = int(x) + int(y)
		selectedChar = self.xyCoordsToKeyboardKey(x,y)

		emojiSourceData = (self.emojiKeyboard.select_one({"name":"emojis"})).data_source.data
		letterIndex = emojiSourceData["letters"].index(selectedChar)
		selectedEmoji = emojiSourceData["text"][letterIndex]

		self.text_input.remove_on_change("value",self.textBoxcallback)
		self.text_input.value += (selectedEmoji)
		self.text_input.on_change("value",self.textBoxcallback)

		self.filename = "cats.wav"

		self.analyzeNgram(self.text_input.value,"tapped")


	def analyzeNgram(self,ngram,methodOfEntry):
		#get the current category structure
		heirarchy = [self.activeMainCategory,self.activeSubCategory]

		emojiDber.addEnteredString(
			ENTERED_STRING = ngram,
			ENTRY_METHOD = methodOfEntry,
			CLICK_INDEX = self.categoryClickIndex,
			CATEGORY_STRUCTURE = heirarchy,
			SESSION_ID = self.sessionId)

		#reset category click index
		self.categoryClickIndex = 0

		#get new suggestions
		#split the currently entered string
		splitNgram = list(ngram)
		newSuggestionsDict = {}
		for emoji in splitNgram:
			suggestions = emojiDber.getRelevantEmojisFromEmoji(emoji)
			newSuggestionsDict = {**newSuggestionsDict,**suggestions}

		#get suggested emojis
		self.updateEmojiFigure("Suggested","Row",newSuggestionsDict)

	def createMainEmojiWindow(self):
		plot = figure(title="", plot_width=self.keyboardWidth, plot_height=self.keyboardHeight,
			x_range= (-.5,10-.5),y_range = (0,3*self.keyboardYSpacing),
		    h_symmetry=False, v_symmetry=False, min_border=0,
		    toolbar_location=None,tools = "")

		plot.grid.visible = False
		plot.axis.visible = False

		emojiGlyph = Text(x="x", y="y", text="text", angle=0, 
			text_color="black",text_alpha = 1,text_font_size='65pt',text_align = "center")

		source = self.createKeyboardCoordinates()

		plot.add_glyph(source, emojiGlyph,name = "emojis")

		circleGlyph = Circle(x="x", y="y",radius=.5,fill_alpha = 0,line_alpha = 0)
		circGlypher = plot.add_glyph(source, circleGlyph)

		emojiLetterText =  Text(x="x", y="y", text="letters", angle=0,y_offset=-80,x_offset= -40,
			text_color="black",text_alpha = 1,
			text_font_size='20pt',text_align = "center")
		plot.add_glyph(source,emojiLetterText)

		hoverer = HoverTool(renderers=[circGlypher], tooltips=self.TOOLTIPS)
		plot.add_tools(hoverer)

		plot.on_event(Tap,self.emojiTapCallback)
		# plot.on_event(DoubleTap,self.emojiDoubleTapCallback)

		return plot

	def englishBoxCallback(self,attr,old,new):
		#called when someone types something into the english box,
		#gets the suggested emojis and updates the list

		#check if the new value is drastically longer than the old one (indicating autocomplete)
		if (len(new) - len(old)) > 4:
			print ("CLICKED")
			clickedEmoji = new[-1]

			self.text_input.value += (clickedEmoji)
			self.englishInput.value = ""
			return

		suggestedEmojis = emojiDber.getRelevantEmojis(new)
		emojisList = []
		for name,emoji in suggestedEmojis.items():
			entry = name.replace("_"," ") + "   " + emoji
			emojisList.append(entry)

		self.englishInput.completions = emojisList

	def textBoxcallback(self,attr,old,new):
		if (len(old) > len(new)):
			return
		if not new:
			return

		newChar = new[-1]
		if newChar == " ":
			return

		if newChar.isdigit():
			newEmojiIndex = int(newChar)-1
			newEmoji = (self.gui.select_one({"name":"Suggested"})).data["text"][newEmojiIndex]
			self.text_input.remove_on_change("value",self.textBoxcallback)
			self.text_input.value = new[:-1] + newEmoji
			self.text_input.on_change("value",self.textBoxcallback)

		if newChar.isalpha():
			newCharStr = newChar.lower()
			emojiSourceData = (self.gui.select_one({"name":"emojis"})).data_source.data
			typedEmojiIndex = emojiSourceData["letters"].index(newCharStr)
			newEmoji = emojiSourceData["text"][typedEmojiIndex]
			self.text_input.remove_on_change("value",self.textBoxcallback)
			self.text_input.value = new[:-1] + newEmoji
			self.text_input.on_change("value",self.textBoxcallback)

		self.analyzeNgram(self.text_input.value,"typed")

	def createKeyboardCoordinates(self):
		#rectangle window

		topRowXs, topRowYs = list(range(10)),[2*self.keyboardYSpacing + self.keyboardYOffset]*10
		topRowLetters = ["q","w","e","r","t","y","u","i","o","p"]

		midRowXs, midRowYs = list(np.linspace(self.midRowXOffset,9-self.midRowXOffset,9)), [self.keyboardYSpacing + self.keyboardYOffset]*9
		midRowLetters = ["a","s","d","f","g","h","j","k","l"]

		lowRowXs, lowRowYs = list(np.linspace(2*self.midRowXOffset,7-3*self.midRowXOffset,7)),[self.keyboardYOffset]*7
		lowRowLetters = ["z","x","c","v","b","n","m"]
		self.letters = [lowRowLetters,midRowLetters,topRowLetters]
		xCoords = topRowXs + midRowXs + lowRowXs
		yCoords = topRowYs + midRowYs + lowRowYs
		letters = topRowLetters + midRowLetters + lowRowLetters

		self.numCoords = len(xCoords)

		emojis = [""] * self.numCoords
		names = [""] * self.numCoords
		source = ColumnDataSource(dict(x=xCoords, y=yCoords, text=emojis,names = names,letters = letters))
		return source

	###CHAT BOX 

	def createChatBox(self):
		#creates a datatable to show messages
		data = dict(sender=[],message=[])
		source = ColumnDataSource(data)

		columns = [
		        TableColumn(field="sender", title="From"),
		        TableColumn(field="message", title="Message"),
		    ]

		chatBox = DataTable(source=source, columns=columns,
			width=self.keyboardWidth, height=200)
		return chatBox

	def createMessageWindow(self):
		messageWindow = column([],css_classes=["message-box"],width = self.keyboardWidth - 300,height = 400)
		return messageWindow

	def sendMessage(self):
		#posts a message to the db and clears the text box, updates the chat window
		currentMessage = self.text_input.value

		emojiDber.postEnteredMessage(MESSAGE = currentMessage,SESSION_ID = self.sessionId)
		self.updateChatBox("You",currentMessage)

	def createSentDiv(self,message):
		return Div(text=message,height=30,width=self.keyboardWidth-400,css_classes = ["sent-speech-bubble"])

	def createReceivedDiv(self,message):
		return Div(text=message,height=30,width=self.keyboardWidth-400,css_classes = ["received-speech-bubble"])

	def updateChatBox(self,sender,newMessage):
		if sender == "You":
			newDiv = self.createSentDiv(newMessage)
		else:
			newDiv = self.createReceivedDiv(newMessage)

		self.messageWindow.children.append(newDiv)

		# chatBoxSource = self.chatBox.source.data
		# chatBoxSource["sender"].append(sender)
		# chatBoxSource["message"].append(newMessage)
		# self.chatBox.source.data = chatBoxSource



		self.text_input.value = ""



	def getReceivedMessages(self):
		#check if there's a friend id
		self.friendId = emojiDber.checkForUnmatchedFriendId(self.sessionId)

		#if its not found, return and try again later
		if not self.friendId: return

		unreadMessages = emojiDber.getUnreadMessages(SESSION_ID = self.friendId)

		for message in unreadMessages:
			messageText = message["MESSAGE"]
			messageTime = message["TIMESTAMP"]
			self.updateChatBox("Them",messageText)

			emojiDber.incrementMessageRead(SESSION_ID=self.friendId,TIMESTAMP = messageTime)

	def createGui(self):
		# self.chatBox = self.createChatBox()
		self.messageWindow = self.createMessageWindow()
		headerDiv = Div(text="<link rel='stylesheet' type='text/css' href='templates/styles.css'>")

		self.createKeyboardCoordinates()

		self.englishInput = AutocompleteInput(value = "",title = "English:",completions = ["bath","bathtub"])
		self.englishInput.on_change("value",self.englishBoxCallback)

		self.text_input = TextInput(value="", title="Message:",width = self.keyboardWidth - 300)
		self.text_input.on_change("value",self.textBoxcallback)

		sendButton = Button(label="↩",button_type = "primary")
		sendButton.on_click(self.sendMessage)
		self.suggestedCategoryRow = self.createEmojiFigure("Row","Suggested")
		self.suggestedCategoryRow.on_event(Tap,self.suggestedSelectCallback)

		self.suggestedCategoryRow.title.text = "💡"
		self.suggestedCategoryRow.title.text_font_size = "20pt"

		mainCategoryFigure = self.createEmojiFigure("Column","Main")
		mainCategoryFigure.title.text = "🐘📦"
		mainCategoryFigure.title.text_font_size = "30pt"
		mainCategoryFigure.on_event(Tap,self.mainCategorySelectCallback)
		mainCategoryFigure.js_on_event(DoubleTap,self.playSound)

		subCategoryFigure = self.createEmojiFigure("Column","Sub")
		subCategoryFigure.title.text = "🥖📦"
		subCategoryFigure.title.text_font_size = "30pt"
		subCategoryFigure.name = "sub"
		subCategoryFigure.on_event(Tap,self.subCategorySelectCallback)

		self.emojiKeyboard = self.createMainEmojiWindow()
		self.emojiKeyboard.title.text = "⌨"
		self.emojiKeyboard.title.text_font_size = "30pt"
		self.gui = column(
			headerDiv,
			self.messageWindow,
			row(self.englishInput,self.text_input,sendButton),
			self.suggestedCategoryRow,
			row(self.emojiKeyboard,subCategoryFigure,mainCategoryFigure)
		)

	def showGui(self):
		curdoc().add_root(self.gui)
		curdoc().add_periodic_callback(self.getReceivedMessages,1000)
		curdoc().on_session_destroyed(self.destroySession)
		curdoc().title = "Emoji Messenger"
		show(self.gui)

	def destroySession(self,session_context):
		emojiDber.deactivateSessionId(self.sessionId,self.friendId)
		print ("Session closed")
Ejemplo n.º 8
0
    def create_widget(self, dim, holomap=None, editable=False):
        """"
        Given a Dimension creates bokeh widgets to select along that
        dimension. For numeric data a slider widget is created which
        may be either discrete, if a holomap is supplied or the
        Dimension.values are set, or a continuous widget for
        DynamicMaps. If the slider is discrete the returned mapping
        defines a mapping between values and labels making it possible
        sync the two slider and label widgets. For non-numeric data
        a simple dropdown selection widget is generated.
        """
        label, mapping = None, None
        if holomap is None:
            if dim.values:
                if dim.default is None:
                    default = dim.values[0]
                elif dim.default not in dim.values:
                    raise ValueError(
                        "%s dimension default %r is not in dimension values: %s"
                        % (dim, dim.default, dim.values))
                else:
                    default = dim.default
                value = dim.values.index(default)

                if all(isnumeric(v) for v in dim.values):
                    values = sorted(dim.values)
                    labels = [unicode(dim.pprint_value(v)) for v in values]
                    if editable:
                        label = AutocompleteInput(value=labels[value],
                                                  completions=labels,
                                                  title=dim.pprint_label)
                    else:
                        label = Div(text='<b>%s</b>' %
                                    dim.pprint_value_string(labels[value]))
                    widget = Slider(value=value,
                                    start=0,
                                    end=len(dim.values) - 1,
                                    title=None,
                                    step=1)
                    mapping = list(enumerate(zip(values, labels)))
                else:
                    values = [(v, dim.pprint_value(v)) for v in dim.values]
                    widget = Select(title=dim.pprint_label,
                                    value=values[value][0],
                                    options=values)
            else:
                start = dim.soft_range[0] if dim.soft_range[0] else dim.range[0]
                end = dim.soft_range[1] if dim.soft_range[1] else dim.range[1]
                dim_range = end - start
                int_type = isinstance(dim.type, type) and issubclass(
                    dim.type, int)
                if dim.step is not None:
                    step = dim.step
                elif isinstance(dim_range, int) or int_type:
                    step = 1
                else:
                    step = 10**((round(math.log10(dim_range)) - 3))

                if dim.default is None:
                    default = start
                elif (dim.default < start or dim.default > end):
                    raise ValueError(
                        "%s dimension default %r is not in the provided range: %s"
                        % (dim, dim.default, (start, end)))
                else:
                    default = dim.default

                if editable:
                    label = TextInput(value=str(default),
                                      title=dim.pprint_label)
                else:
                    label = Div(text='<b>%s</b>' %
                                dim.pprint_value_string(default))
                widget = Slider(value=default,
                                start=start,
                                end=end,
                                step=step,
                                title=None)
        else:
            values = (dim.values if dim.values else list(
                unique_array(holomap.dimension_values(dim.name))))
            if dim.default is None:
                default = values[0]
            elif dim.default not in values:
                raise ValueError(
                    "%s dimension default %r is not in dimension values: %s" %
                    (dim, dim.default, values))
            else:
                default = dim.default
            if isinstance(values[0], np.datetime64) or isnumeric(values[0]):
                values = sorted(values)
                labels = [dim.pprint_value(v) for v in values]
                value = values.index(default)
                if editable:
                    label = AutocompleteInput(value=labels[value],
                                              completions=labels,
                                              title=dim.pprint_label)
                else:
                    label = Div(text='<b>%s</b>' %
                                (dim.pprint_value_string(labels[value])))
                widget = Slider(value=value,
                                start=0,
                                end=len(values) - 1,
                                title=None,
                                step=1)
            else:
                labels = [dim.pprint_value(v) for v in values]
                widget = Select(title=dim.pprint_label,
                                value=default,
                                options=list(zip(values, labels)))
            mapping = list(enumerate(zip(values, labels)))
        return widget, label, mapping
Ejemplo n.º 9
0
    "#c7c7c7",
    "#1CE6FF",
    "#336600",
]  # these last ones were added

# load data
anndat = load_h5ad()
#pca = anndat.obsm['X_pca']
pca = anndat.obsm['X_draw_graph_fa']
tsne = anndat.obsm['X_tsne']
umap = anndat.obsm['X_umap']

# set up widgets
#stats = PreText(text='', width=500)
symbol = AutocompleteInput(completions=anndat.var_names.tolist(),
                           title="Enter Gene Name (e.g. POU5F1 ):",
                           value="AFP")
select = Select(title="Legend:",
                value="stage_group",
                options=[
                    "clusters", "stage", "stage_group", "donor", "Donor",
                    "group", "res.0.6"
                ])  #options=anndat.obs_keys())
# message box
message = Div(text="""Input Gene Name:\n Legend Option: """,
              width=200,
              height=100)

## setup data
dd = select.value
umis = get_umi(anndat, symbol.value)
Ejemplo n.º 10
0
groups = widgetbox(Paragraph(text="The bokeh groups"), checkbox_group, radio_group, checkbox_button_group, radio_button_group, sizing_mode=sizing_mode)

# Markups
div = Div(text="Some custom <strong>bold</strong> text")
paragraph = Paragraph(text="this is a paragraph")
pretext_1 = PreText(text="This is pre. I could put a bunch of code in here perhaps\nOr maybe something else")
pretext_2 = PreText(text="This is pre")
pretext_3 = PreText(text="This is pre it's a bit longer and i'm going to constrict it.", width=150)
markups = widgetbox(Paragraph(text="The bokeh markups"), div, paragraph, pretext_1, pretext_2, pretext_3, sizing_mode=sizing_mode)

# Inputs
#daterangeslider = DateRangeSlider()  # Known broken
slider = Slider(title="Slider", start=0, end=10, width=100)
multiselect = MultiSelect(options=['1', '2', '3'])
select = Select(options=['1', '2', '3'])
textinput = TextInput()
autocomplete = AutocompleteInput(completions=['one', 'two', 'three'])
#datepicker = DatePicker()
inputs = widgetbox(Paragraph(text="The bokeh inputs"), slider, multiselect, select, textinput, autocomplete, sizing_mode=sizing_mode)

plot = figure(sizing_mode=sizing_mode)
plot.circle(x=[1, 2], y=[2, 3])

l = layout([
    [buttons, groups],
    [markups, inputs],
    [plot],
], sizing_mode=sizing_mode)

show(l)
Ejemplo n.º 11
0

def update_simulation_sample_size(attr, old, new):
    update()


# configure Bokeh Inputs, data sources, and plots
autocomplete_station_names = list(STATIONS_DF['Station Name'])
peak_source = ColumnDataSource(data=dict())
peak_flagged_source = ColumnDataSource(data=dict())
distribution_source = ColumnDataSource(data=dict())
qq_source = ColumnDataSource(data=dict())


station_name_input = AutocompleteInput(
    completions=autocomplete_station_names, title='Enter Station Name (ALL CAPS)',
    value=IDS_TO_NAMES['08MH016'], min_characters=3)

simulation_number_input = Spinner(
    high=1000, low=1, step=1, value=50, title="Number of Simulations",
)

sample_size_input = Spinner(
    high=200, low=2, step=1, value=10, title="Sample Size for Simulations"
)

ffa_info = Div(
    text="Mean of {} simulations of a sample size {}.".format('x', 'y'))

error_info = Div(text="", style={'color': 'red'})
Ejemplo n.º 12
0
                options=[x[0] for x in collections.Counter(ptree.leaf_cds.data['superkingdom']).most_common()],\
                width=200,height=70)
kms.on_change('value',lambda attr,old,new:kmsfunc())

sfms=MultiSelect(title='Subfams',\
                options=[x[0] for x in collections.Counter(ptree.leaf_cds.data['subfamstr']).most_common()],\
                width=150,height=70)
sfms.on_change('value',lambda attr,old,new:sfmsfunc())

tcb=Button(label='CalcTC',width=80,height=40)
tcb.on_click(tcbfunc)
#splist=list(set(ptree.leaf_cds.data['species']))
#splist.sorted(key=ptree.leaf_cds.data['species'])
#acw=AutocompleteInput(title='Organism name',completions=list(set(ptree.leaf_cds.data['species'])),width=200,height=50)
acw=AutocompleteInput(title='Organism name',\
    completions=[x[0] for x in collections.Counter(ptree.leaf_cds.data['species']).most_common()],\
    width=200,height=50)
acw.on_change('value',lambda attr,old,new:acfunc())

accacw=AutocompleteInput(title='Accession',\
    completions=ptree.leaf_cds.data['gbacc'][:],width=200,height=50)
accacw.on_change('value',lambda attr,old,new:accacfunc())


if len(sys.argv)>3:
    preselfpath=os.path.join(os.environ['SCIENCEDIR'],'GHSeqs',ghfam.upper(),sys.argv[3])
    with open(preselfpath,'r') as f:
        preselections=[x.strip() for x in f.readlines()]
        print(preselections)
else:
    preselections=[]
Ejemplo n.º 13
0
def bokehGUI(ScoreBoard,
             MakerDictionary,
             offlineboard='None',
             curMeme="sustainability",
             curInfluencer='zbattiz',
             ApiRequest=False):

    MD = MakerDictionary
    SB = ScoreBoard
    if offlineboard: SB.import_board(offlineboard)
    BI = BokehControler(SB, MD)

    names = [k for k, v in SB.get_names().items()]
    category_codes = MD.categories.values()
    print(category_codes)

    # make this more generic:
    if not curInfluencer: curInfluencer = 'zbattiz'
    if not curMeme: curMeme = 'sustainability'

    BI.populateInfluencers(names, category_codes)
    BI.populateBoards(category_codes)
    BI.setActiveBoard(curMeme, BI.Boards.data.keys())
    BI.setActiveInfluencer(curInfluencer, BI.Influencers.data.keys())

    boards = BI.Boards
    board = BI.ActiveBoard
    influencers = BI.Influencers
    influencer = BI.ActiveInfluencer

    boardatr = ColumnDataSource(data=dict(legend=[curMeme]))
    influenceratr = ColumnDataSource(data=dict(legend=[curInfluencer]))

    #for k in BI.Boards.data.keys(): print(k, BI.Boards.data[k])

    # Drawing:::::::::::::

    ## Commom Tools::
    TOOLS = "tap,pan,wheel_zoom,reset,save"

    ## The Influencer Canvas::
    title = "Influencer"
    fig_influencer = figure(plot_width=700,
                            plot_height=500,
                            title=title,
                            tools=TOOLS,
                            toolbar_location="above",
                            toolbar_sticky=True,
                            active_drag="pan",
                            active_tap='tap',
                            active_scroll='wheel_zoom',
                            responsive=True)

    fig_influencer.axis.visible = False
    fig_influencer.border_fill_color = "whitesmoke"
    fig_influencer.border_fill_alpha = 0.3
    fig_influencer.min_border_top = 30
    fig_influencer.outline_line_width = 4
    fig_influencer.outline_line_alpha = 0.2
    fig_influencer.outline_line_color = "navy"
    fig_influencer.xgrid.visible = False
    fig_influencer.ygrid.visible = False

    ### Legend:::
    fig_influencer.circle(0,
                          0,
                          alpha=0.8,
                          color='olive',
                          legend='legend',
                          source=influenceratr)
    fig_influencer.legend.location = "top_left"
    fig_influencer.legend.label_text_font_size = "8pt"
    fig_influencer.legend.label_text_color = "red"

    ### Data:::
    fig_influencer.multi_line('xsegments',
                              'ysegments',
                              color="colors",
                              alpha=0.5,
                              line_width=2,
                              line_dash="dashed",
                              source=influencer)
    fig_influencer.circle('x',
                          'y',
                          color='colors',
                          size='sizes',
                          alpha=1,
                          source=influencer)
    labels = LabelSet(x='x',
                      y='y',
                      text='memes',
                      text_font_size='9pt',
                      level='glyph',
                      x_offset="offsets",
                      y_offset=0,
                      source=influencer,
                      render_mode='canvas')
    fig_influencer.add_layout(labels)

    ### Hover Tool:::
    infhover = HoverTool(
        tooltips=[("Score",
                   "@scores{0,0.000}"), ("Type",
                                         "per_tweet"), ("Ntweets", "@tweets")])
    fig_influencer.add_tools(infhover)

    ## The Board Canvas:::

    #for k in BI.ActiveBoard.data.keys(): print(k, BI.ActiveBoard.data[k])

    title_board = "Community Spirometer"
    fig_board = figure(plot_width=900,
                       plot_height=550,
                       title=title_board,
                       tools=TOOLS,
                       toolbar_location="above",
                       toolbar_sticky=True,
                       active_drag="pan",
                       active_tap='tap',
                       active_scroll='wheel_zoom',
                       responsive=True)
    fig_board.axis.visible = False
    fig_board.border_fill_color = "whitesmoke"
    fig_board.border_fill_alpha = 0.2
    fig_board.min_border_top = 30
    fig_board.outline_line_width = 6
    fig_board.outline_line_alpha = 0.2
    fig_board.outline_line_color = "navy"

    ### Legend:::
    fig_board.circle(0,
                     0,
                     alpha=0.8,
                     color='turquoise',
                     legend='legend',
                     source=boardatr)
    fig_board.legend.location = "top_left"
    fig_board.legend.label_text_font_size = "9pt"
    fig_board.legend.label_text_color = "red"

    ### Data:::
    fig_board.line('x',
                   'y',
                   alpha=0.4,
                   line_width=1,
                   line_dash="dashed",
                   source=board)
    fig_board.circle('x',
                     'y',
                     color='black',
                     size='levels',
                     alpha=1,
                     source=board)
    fig_board.circle('x',
                     'y',
                     color='colors',
                     size='sizes',
                     alpha=0.8,
                     source=board)
    labels = LabelSet(x='x',
                      y='y',
                      text='names',
                      text_font_size='7pt',
                      level='glyph',
                      x_offset='offsets',
                      y_offset=0,
                      source=board,
                      render_mode='canvas')
    fig_board.add_layout(labels)

    ### Hover Tool:::
    boardhover = HoverTool(tooltips=[("Name", "@names"), (
        "Phase",
        "@clusters"), ("Score",
                       "@scores{0,0.000}"), (
                           "Scoring type",
                           "per_tweet"), ("Number of tweets probed",
                                          "@tweets")])
    fig_board.add_tools(boardhover)

    # JavaScript Callbacks:::

    board.callback = CustomJS(args=dict(source=influencers,
                                        display=influencer,
                                        atr=influenceratr),
                              code="""
        var inds = cb_obj.selected['1d'].indices;
        var d1 = cb_obj.data;
        var d2 = source.data;
        var d3 = display.data;
        var d4 = atr.data;
        
        var ind = inds[0];
        console.log(ind);
        if (ind != null){
            d3['x'] = [];
            d3['y'] = [];
            d3['sizes'] = [];
            d3['scores'] = [];
            d3['names'] = [];
            d3['memes'] = [];
            d3['colors'] = [];
            d3['offsets'] = [];
            d3['xsegments'] = [];
            d3['ysegments'] = [];
            d3['tweets'] = [];
            d3_tags = [];
            
            var name = d1['names'][ind];
            console.log(name);
            d4['legend'] = [];
            d4['legend'].push(name);
            
            
            var start = d2['names'].indexOf(name);
            var end = d2['names'].lastIndexOf(name);
            
            console.log(start);
            console.log(end);

            for (var i = start; i <= end; i++) {
                d3['x'].push(d2['x'][i]);
                d3['y'].push(d2['y'][i]);
                d3['sizes'].push(d2['sizes'][i]);
                d3['scores'].push(d2['scores'][i]);
                d3['names'].push(d2['names'][i]);
                d3['memes'].push(d2['memes'][i]);
                d3['offsets'].push(d2['offsets'][i]);
                d3['colors'].push(d2['colors'][i]);
                d3['tweets'].push(d2['tweets'][i]);
                d3['xsegments'].push(d2['xsegments'][i]);
                d3['ysegments'].push(d2['ysegments'][i]);
            }
        }
        display.change.emit();
        atr.change.emit();
         """)

    influencer.callback = CustomJS(args=dict(source=boards,
                                             display=board,
                                             atr=boardatr),
                                   code="""
        var inds = cb_obj.selected['1d'].indices;
        var d1 = cb_obj.data;
        var d2 = source.data;
        var d3 = display.data;
        var d4 = atr.data;
        
        var ind = inds[0];
        console.log(ind)

        if (ind != null){
            d3['x'] = [];
            d3['y'] = [];
            d3['sizes'] = [];
            d3['scores'] = [];
            d3['levels'] = [];
            d3['clusters'] = [];
            d3['names'] = [];
            d3['memes'] = [];
            d3['offsets'] = [];
            d3['colors'] = [];
            d3['tweets'] = [];
            
            var meme = d1['memes'][ind];
            d4['legend'] = [];
            d4['legend'].push(meme)
            console.log(meme)
            
            var name = d1['names'][ind];
            var color = d1['colors'][ind]
            
            var start = d2['memes'].indexOf(meme);
            var end = d2['memes'].lastIndexOf(meme);
            
            console.log(start);
            console.log(end);
            
            for (var i = start; i <= end; i++) {
                d3['x'].push(d2['x'][i]);
                d3['y'].push(d2['y'][i]);
                d3['sizes'].push(d2['sizes'][i]);
                d3['scores'].push(d2['scores'][i]);
                d3['levels'].push(d2['levels'][i]);
                d3['clusters'].push(d2['clusters'][i]);
                d3['names'].push(d2['names'][i]);
                d3['memes'].push(d2['memes'][i]);
                d3['offsets'].push(d2['offsets'][i]);
                d3['tweets'].push(d2['tweets'][i]);
                if (d2['names'][i] == name){
                    d3['colors'].push(color);
                }
                else {
                    d3['colors'].push(d2['colors'][i]);
                }
            }
        }
        display.change.emit();
        atr.change.emit();
         """)

    # Adding additional Widgets and their events:::::

    ## Info Box::
    div_title = Div(text="""
                <h2> Sustainable Finance Spirometer</h2>
                <p><b>This Sprirometer infographics is one of the ways to observe opionion leaders and influencers,
                those who promote or debate on issues relevant to sustainable finance. </b>
                
                <p>Influential actors are placed rather outer branches of the spiral. See the lower interactive panel.
                An infleuncer's spiral profile, as of his/her contribution to the related debates,
                can be seen via the upper interactive panel.</p>
                
                <p>The data is collected from the tweets that are in the public domain.
                The latest tweets in English of an infleuncer is used for the analysis and visualizations. 
                The nodes on the spirometer (the lower panel) are resized according to the number of tweets
                by the corresponding influencer.</p>
                
                 <p>Influencers are clustered according to their sphere of influence. 
                 There are 4 or more distinct clusters/phases on each spiral.
                 Number of clusters and cluster membership is algorithmically generated from the data.
                 
                 The sequence of nodes with/without an inner circle denotes membership to the same cluster.
                <br/> <br/>
                </p> 
                """,
                    width=850,
                    height=220)
    title_box = widgetbox(div_title, sizing_mode='scale_both', responsive=True)

    ## Tips Box::
    div_tips = Div(text="""
            <p>Hover over the nodes in order to see the details. <b>Ntweets</b>
             denotes the number of tweeters collected for the profiling, <b>per_tweet</b>
             denotes that scores are computed per tweet.</p>
      
            <p>A new influencer can be added. Address bar can be used to query an influencer
            whose profile is not analyzed yet. Note that a twitter user name is the part after @ sign.
            For instance, the Twitter user <i>@bulentozel</i> can be added by appending <b>bulentozel</b> to the URL:
            <i>BASE_URL/gui/bulentozel</i>
            </p>
            <p>To query the users whose profiling has already been included, the search bar below can be used. </p>
            """,
                   width=200,
                   height=350)
    tips_box = widgetbox(div_tips, sizing_mode='scale_both', responsive=True)

    ## Query Box::

    callback_search = CustomJS(args=dict(boardWin=board,
                                         infList=influencers,
                                         infWin=influencer,
                                         atr=influenceratr),
                               code="""
        var bWin = boardWin.data;
        var iWin = infWin.data;
        var iL = infList.data;
        var query = cb_obj.value;
        var d4 = atr.data;
        
        console.log(query);
        
        var ind = iL['names'].indexOf(query);
        if (ind >= 0){
            var start = ind;
            var end = iL['names'].lastIndexOf(query);
            
            iWin['x'] = [];
            iWin['y'] = [];
            iWin['sizes'] = [];
            iWin['scores'] = [];
            iWin['names'] = [];
            iWin['memes'] = [];
            iWin['colors'] = [];
            iWin['offsets'] = [];
            iWin['xsegments'] = [];
            iWin['ysegments'] = [];
            iWin['tweets'] = [];
            
            for (var i = start; i <= end; i++) {
                iWin['x'].push(iL['x'][i]);
                iWin['y'].push(iL['y'][i]);
                iWin['sizes'].push(iL['sizes'][i]);
                iWin['scores'].push(iL['scores'][i]);
                iWin['names'].push(iL['names'][i]);
                iWin['memes'].push(iL['memes'][i]);
                iWin['offsets'].push(iL['offsets'][i]);
                iWin['colors'].push(iL['colors'][i]);
                iWin['tweets'].push(iL['tweets'][i]);
                iWin['xsegments'].push(iL['xsegments'][i]);
                iWin['ysegments'].push(iL['ysegments'][i]);
            }
            
            ind = bWin['names'].indexOf(query);
            if (ind > 0){
                var blength = bWin['colors'].length;
                bWin['colors'] = []
                for (i = 0; i < blength; i++) {
                    bWin['colors'].push('turquoise');
                }
                bWin['colors'][ind] = 'olive'
            }
            d4['legend'] = [];
            d4['legend'].push(query);
        }
        boardWin.change.emit();
        infWin.change.emit();
        atr.change.emit();
    """)
    text_input = AutocompleteInput(completions=names,
                                   title="Search an influencer:")
    text_input.js_on_change('value', callback_search)
    query_box = widgetbox(text_input,
                          sizing_mode='stretch_both',
                          responsive=True)

    # Tabular Data

    ## Info Box::
    div_scorebord_info = Div(text="""
                    <h3>Spirometer Details</h3>
                    <p>Tap to column names in order to sort accordingly.
                    </p>
                    """,
                             width=750,
                             height=50)
    title_table = widgetbox(div_scorebord_info,
                            sizing_mode='scale_both',
                            responsive=True)

    Nformatter = NumberFormatter()
    Nformatter.format = "0,0.000"
    columns = [
        TableColumn(field="names", title="Name"),
        TableColumn(field="memes", title="Category"),
        TableColumn(field="scores", title="Score", formatter=Nformatter),
        TableColumn(field="tweets", title="Number of Tweets")
    ]
    data_table = DataTable(source=boards,
                           columns=columns,
                           width=820,
                           height=500)
    table_box = widgetbox(data_table,
                          sizing_mode='stretch_both',
                          responsive=True)

    # Figures only layout::::
    if ApiRequest:
        layoutAPI = column(fig_influencer, fig_board)
        return (layoutAPI)

    # Overall Layout::::
    layout = column(title_box, row(fig_influencer,
                                   column(tips_box, query_box)), fig_board,
                    title_table, table_box)

    return (layout)
Ejemplo n.º 14
0
def cHow():
    if byButton:
        return rs_update()
    else:
        return byRow(source.data['ID'].iloc[source.selected.indices[0]])
        
    

menu = [('Publication Paper', 'pub'), ('Dataset', 'data'), ('All', '')]
nmenu = RadioButtonGroup(labels=['Publication', 'Dataset', 'Keyword'], active=0)
how = ['Jaccard', 'Cosine', 'Hopcroft', 'Adamic-Adar']
nhow = RadioButtonGroup(labels=['Jaccard', 'Cosine', 'Hopcroft', 'Adamic-Adar'], active=0)
nhow.on_change('active', lambda attr, old, new: cHow())

search = TextInput(title="Search Archive")
rs_search = AutocompleteInput(title="Recommend by Keyword", completions=all_keywords)

button = Button(label="Search", button_type="warning")
button.on_event(ButtonClick, update)
rs_button = Button(label="Recommend", button_type="success")
rs_button.on_event(ButtonClick, rs_update)

columns = [
    TableColumn(field="ID", title="ID", width=20),
    TableColumn(field="title", title="Title", width=300, formatter=HTMLTemplateFormatter(template=template)),
    TableColumn(field="description", title="Description", width=200, formatter=HTMLTemplateFormatter(template=template))
]
data_table = DataTable(source=source, columns=columns, width=800)
rs_columns = [
    TableColumn(field="data_set_id", title="Data ID", width=20),
    TableColumn(field="rs_score", title="RS Score", width=20),
Ejemplo n.º 15
0
def recommender_tab_simple(recommender):

    # create a list of divs
    def make_div_list(textlist, max_lines, fmt_str="""%s""", **attribs):
        """create a list of divs containing text to display"""
        divs = []
        for i in range(max_lines):
            if len(textlist) > i:
                divs.append(Div(text=fmt_str % (textlist[i]), **attribs))
            else:
                divs.append(Div(text=fmt_str % (' '), **attribs))
        return divs

    def make_rec_list(titles, max_lines):
        """create a recommendation list of games,
        with a thumbnail, game title, info and Amazon buy links"""
        global games_by_title
        fmt_str1 = """
            <div class="rec-post-container">                
                <div class="rec-post-thumb"><img src="%s" /></div>
                <div class="rec-post-content">
                    <h3 class="rec-post-title">%s<br>
                    <a href="%s" target="_blank">Info</a><span>&nbsp;&nbsp;</span>
                    <a href="%s" target="_blank">Buy on Amazon</a> </h3>
                </div>
            </div>"""
        fmt_str2 = """"""
        divs = []
        for i in range(max_lines):
            # there is a title available for this list slot
            if len(titles) > i:
                divs.append(
                    Div(text=fmt_str1 %
                        (games_by_title['pic_url'].loc[titles[i]], titles[i],
                         'https://boardgamegeek.com/boardgame/' +
                         str(games_by_title['id'].loc[titles[i]]),
                         'https://www.amazon.com/s?k=' +
                         titles[i].replace(' ', '+') + '&i=toys-and-games')))
            # there no title available for this list slot
            else:
                divs.append(Div(text=fmt_str2))
        return divs

    # update the 'liked games' list UI elements
    def update_liked_list(titlelist):
        global max_liked
        ctl_liked_games.children = make_div_list(titlelist,
                                                 max_liked,
                                                 fmt_str=liked_list_fmt,
                                                 render_as_text=False)

    # update the 'recommended games' list UI elements
    def update_recommended_list(titlelist):
        global n_recommendations
        ctl_recommended_games.children = make_rec_list(titlelist,
                                                       n_recommendations)

    def show_searching_message():
        ctl_recommended_games.children = [
            Div(text='<h1>Searching for recommendations...</h1>')
        ]

    # called when a control widget is changed
    def update_preflist(attr, old, new):
        global liked_games
        liked_games.append(ctl_game_entry.value)
        liked_games = list(filter(None, set(liked_games)))
        # get control values
        update_liked_list(liked_games)
        ctl_game_entry.value = ''

    # clear out the list of preferred games
    def reset_preferred_games():
        global liked_games
        liked_games = []
        update_liked_list(liked_games)

    # user wants some recommendations (clicked the rec button)
    def recommend_games():
        global liked_games, recommended_games
        global games_all, n_recommendations, title_list
        global title_list_lower

        # display a "Searching for recommendations..." message
        # Note: Bokeh doesn't do redraw while inside handlers
        show_searching_message()

        # get some default filter parameters:
        weight = []
        minrating = 6.5
        categories = ['Any category']
        mechanics = ['Any mechanism']
        for title in liked_games:
            idx = (np.array(title_list_lower) == title.lower()).nonzero()[0][0]
            info = games_all.iloc[idx, :]
            weight.append(info['weight'])
            categories += info['categories'].split(',')
            mechanics += info['mechanics'].split(',')

        # select a range of weights around the liked game weights
        weightrange = [
            max(1,
                np.min(weight) - 0.25),
            min(5,
                np.max(weight) + 0.25)
        ]

        # get game IDs for titles
        liked_ids = recommender.get_item_title_id(liked_games)

        # select games to search from based on filters:
        recommended_games = recommender.recommend_items_by_pref_list(
            liked_ids,
            num2rec=n_recommendations,
            weightrange=weightrange,
            minrating=minrating,
            categories_include=categories,
            categories_exclude=['Expansion for Base-game'],
            mechanics_include=mechanics,
            mechanics_exclude=[])

        update_recommended_list(recommended_games)

    # NOTE: I'm using globals because I'm running into variable scope
    #  problems with the bokeh handlers. Easiest to declare globals
    global liked_games, recommended_games, games_all
    global n_recommendations, max_liked, title_list, title_list_lower
    global games_by_title

    # layout params
    n_recommendations = 10
    max_liked = 8

    # Format to use for liked list.
    # This needs to be changed to work like rec list
    liked_list_fmt = """<div style="font-size : 14pt; line-height:14pt;">%s</div>"""

    # variables used by the tab
    liked_games = []
    recommended_games = []
    weight_range = [1, 5]
    games_all = recommender.item_data  # use all games for search
    games_by_title = recommender.item_data.set_index('name')

    # list of all game titles
    title_list = games_all['name']
    title_list_lower = [s.lower() for s in title_list]

    # preferred game entry text control
    ctl_game_entry = AutocompleteInput(completions=list(title_list) +
                                       list(title_list_lower),
                                       min_characters=1,
                                       title='Enter some game names you like:')
    ctl_game_entry.on_change('value', update_preflist)

    # reset liked game list button
    ctl_reset_prefs = Button(label='Reset game list',
                             width_policy='min',
                             align='end')
    ctl_reset_prefs.on_click(reset_preferred_games)

    # liked list title
    ctl_liked_list_title = Div(
        text=
        """<div style="font-size : 18pt; line-height:16pt;">Games you like:</div>"""
    )

    # liked game entries
    ctl_liked_games = WidgetBox(
        children=make_div_list(liked_games, max_liked, fmt_str=liked_list_fmt))

    # recommended list title
    ctl_recommended_list_title = Div(
        text=
        """<div style="font-size : 18pt; line-height:16pt;">Games we recommend:</div>"""
    )

    # recommended games list widget
    ctl_recommended_games = WidgetBox(
        children=make_rec_list(recommended_games, n_recommendations))

    # Recommend games button
    ctl_recommend = Button(label='Recommend some games!', width_policy='min')
    ctl_recommend.on_click(recommend_games)

    # controls to select preferred games
    pref_controls = WidgetBox(ctl_liked_list_title, ctl_liked_games,
                              Spacer(min_height=20),
                              ctl_game_entry, ctl_reset_prefs,
                              Spacer(min_height=40), ctl_recommend)

    # recommendation results
    results_controls = WidgetBox(ctl_recommended_list_title,
                                 ctl_recommended_games)

    # Create a row layout
    layout = row(pref_controls, results_controls)

    # Make a tab with the layout
    tab = Panel(child=layout, title='Simple Game Recommender')

    return tab
Ejemplo n.º 16
0
def update_simulated_msmt_error(val):
    update()


# configure Bokeh Inputs, data sources, and plots
autocomplete_station_names = list(STATIONS_DF['Station Name'])
peak_source = ColumnDataSource(data=dict())
peak_flagged_source = ColumnDataSource(data=dict())
distribution_source = ColumnDataSource(data=dict())
qq_source = ColumnDataSource(data=dict())
datatable_source = ColumnDataSource(data=dict())
hist_source = ColumnDataSource(data=dict())

station_name_input = AutocompleteInput(
    completions=autocomplete_station_names,
    title='Enter Water Survey of Canada STATION NAME (USE ALL CAPS)',
    value=IDS_TO_NAMES['08MH016'],
    min_characters=3)

simulation_number_input = Spinner(
    high=5000,
    low=100,
    step=1,
    value=500,
    title="Number of Simulations",
)

sample_size_input = Spinner(high=200,
                            low=2,
                            step=1,
                            value=10,
Ejemplo n.º 17
0
menu = [("Item 1", "item_1_value"), ("Item 2", "item_2_value"), None, ("Item 3", "item_3_value")]

dropdown = Dropdown(label="Dropdown button", button_type="warning", menu=menu)
dropdown_split = Dropdown(label="Split button", button_type="danger", menu=menu, split=True)

checkbox_group = CheckboxGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
radio_group = RadioGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)

checkbox_button_group = CheckboxButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=[0, 1])
radio_button_group = RadioButtonGroup(labels=["Option 1", "Option 2", "Option 3"], active=0)

text_input = TextInput(placeholder="Enter value ...")

completions = ["aaa", "aab", "aac", "baa", "caa"]
autocomplete_input = AutocompleteInput(placeholder="Enter value (auto-complete) ...", completions=completions)

select = Select(options=["Option 1", "Option 2", "Option 3"])

multi_select = MultiSelect(options=["Option %d" % (i+1) for i in range(16)], size=6)

slider = Slider(value=10, start=0, end=100, step=0.5)

range_slider = RangeSlider(value=[10, 90], start=0, end=100, step=0.5)

date_slider = DateSlider(value=date(2016, 1, 1), start=date(2015, 1, 1), end=date(2017, 12, 31))

date_range_slider = DateRangeSlider(value=(date(2016, 1, 1), date(2016, 12, 31)), start=date(2015, 1, 1), end=date(2017, 12, 31))

spinner = Spinner(value=100)
Ejemplo n.º 18
0
index_select = Select(value='000001', title='指数代码', options=sorted(index_codes), height=50)
index_type_select = Select(value='牛熊股比', title='数据类型', options=sorted(index_type_list), height=50)
# DatePciekr
dt_pckr_start = DatePicker(title='开始日期', value = date.today() - timedelta(days = 200), min_date = date(2004,1,1), max_date = date.today())
dt_pckr_end = DatePicker(title='结束日期', value = date.today(), min_date = date(2004,1,1), max_date = date.today())

index_select_row = row(index_select, index_type_select, dt_pckr_start, dt_pckr_end)
index_layout = column(index_select_row, create_index_figure_column(index_select.value, index_type_select.value, dt_pckr_start.value, dt_pckr_end.value))

index_select.on_change('value', update_index)
index_type_select.on_change('value', update_index)
dt_pckr_start.on_change('value', update_index)
dt_pckr_end.on_change('value', update_index)

# Add Stock Analysis
stock_auto_input = AutocompleteInput(value = '601318', completions = initializer.update_code_list(), title = '股票代码')
# DatePciekr
stock_pckr_start = DatePicker(title='开始日期', value = date.today() - timedelta(days = 100), min_date = date(2000,1,1), max_date = date.today())
stock_pckr_end = DatePicker(title='股票日期', value = date.today(), min_date = date(2000,1,1), max_date = date.today())

stock_select_row = row(stock_auto_input, stock_pckr_start, stock_pckr_end)
stock_layout = column(stock_select_row, create_stock_figure_column(stock_auto_input.value, stock_pckr_start.value, stock_pckr_end.value))

stock_auto_input.on_change('value', update_stock)
stock_pckr_start.on_change('value', update_stock)
stock_pckr_end.on_change('value', update_stock)

# Market Data
# DatePciekr
market_title = Div(text="整体市场概况", width=120, height=40, margin=[25, 0, 0, 0], style={'font-size': '150%', 'color': 'blue'})
market_pckr_start = DatePicker(title='开始日期', value = date.today() - timedelta(days = 100), min_date = date(2000,1,1), max_date = date.today())
Ejemplo n.º 19
0
def recommender_tab_advanced(recommender):
    def make_div_list(textlist, max_lines, fmt_str="""%s""", **attribs):
        """create a list of divs containing text to display"""
        divs = []
        for i in range(max_lines):
            if len(textlist) > i:
                divs.append(Div(text=fmt_str % (textlist[i]), **attribs))
            else:
                divs.append(Div(text=fmt_str % (' '), **attribs))
        return divs

    def make_rec_list(titles, max_lines):
        """create a recommendation list of games,
        with a thumbnail, game title, info and Amazon buy links"""
        global games_by_title
        fmt_str1 = """
            <div class="rec-post-container">                
                <div class="rec-post-thumb"><img src="%s" /></div>
                <div class="rec-post-content">
                    <h3 class="rec-post-title">%s<br>
                    <a href="%s" target="_blank">Info</a><span>&nbsp;&nbsp;</span>
                    <a href="%s" target="_blank">Buy on Amazon</a> </h3>
                </div>
            </div>"""
        fmt_str2 = """"""
        divs = []
        for i in range(max_lines):
            # there is a title available for this list slot
            if len(titles) > i:
                divs.append(
                    Div(text=fmt_str1 %
                        (games_by_title['pic_url'].loc[titles[i]], titles[i],
                         'https://boardgamegeek.com/boardgame/' +
                         str(games_by_title['id'].loc[titles[i]]),
                         'https://www.amazon.com/s?k=' +
                         titles[i].replace(' ', '+') + '&i=toys-and-games')))
            # no title, so fill with blank
            else:
                divs.append(Div(text=fmt_str2))
        return divs

    # update the 'liked games' list UI elements
    def update_liked_list(titlelist):
        global max_liked
        ctl_liked_games.children = make_div_list(titlelist,
                                                 max_liked,
                                                 fmt_str=liked_list_fmt,
                                                 render_as_text=False)

    # update the 'recommended games' list UI elements
    def update_recommended_list(titlelist):
        global n_recommendations
        ctl_recommended_games.children = make_rec_list(titlelist,
                                                       n_recommendations)

    # called when a control widget is changed
    def update_filters(attr, old, new):
        global category_includes, mechanics_includes
        global category_excludes, mechanics_excludes

        category_includes = [
            ctl_category_selection1.labels[i]
            for i in ctl_category_selection1.active
        ]
        category_includes += [
            ctl_category_selection2.labels[i]
            for i in ctl_category_selection2.active
        ]

        mechanics_includes = [
            ctl_mechanics_selection1.labels[i]
            for i in ctl_mechanics_selection1.active
        ]
        mechanics_includes += [
            ctl_mechanics_selection2.labels[i]
            for i in ctl_mechanics_selection2.active
        ]

        # NOTE: this will need to be changed if I ever implement exclude selections!
        if ctl_include_expansions.active:
            category_excludes = []
        else:
            category_excludes = ['Expansion for Base-game']

    # called when a control widget is changed
    def update_preflist(attr, old, new):
        global liked_games
        liked_games.append(ctl_game_entry.value)
        liked_games = list(filter(None, set(liked_games)))
        # get control values
        update_liked_list(liked_games)
        ctl_game_entry.value = ''

    # reset preferred games list
    def reset_preferred_games():
        global liked_games
        liked_games = []
        update_liked_list(liked_games)

    # recommend some games
    def recommend_games():
        global liked_games, recommended_games
        global games_all, n_recommendations, title_list
        global category_includes, mechanics_includes

        # get game IDs for titles
        liked_ids = recommender.get_item_title_id(liked_games)

        # select games to search from based on filters:
        recommended_games = recommender.recommend_items_by_pref_list(
            liked_ids,
            num2rec=n_recommendations,
            weightrange=ctl_game_weight.value,
            minrating=ctl_game_min_rating.value,
            categories_include=category_includes,
            categories_exclude=category_excludes,
            mechanics_include=mechanics_includes,
            mechanics_exclude=mechanics_excludes)

        # show the recommended games
        update_recommended_list(recommended_games)

    # NOTE: I'm using globals because I'm running into variable scope
    #  problems with the bokeh handlers. Easiest to declare globals
    global liked_games, recommended_games, games_all
    global n_recommendations, max_liked, title_list, title_list_lower
    global category_includes, mechanics_includes
    global category_excludes, mechanics_excludes
    global games_by_title

    # layout params
    n_recommendations = 10
    max_liked = 8
    num_check_options = 20

    # Format to use for liked list.
    # This needs to be changed to work like rec list
    liked_list_fmt = """<div style="font-size : 14pt; line-height:14pt;">%s</div>"""

    # variables used by the tab
    games_all = recommender.item_data  # use all games for search
    liked_games = []
    recommended_games = []
    weight_range = [1, 5]
    category_includes = []
    mechanics_includes = []
    category_excludes = []
    mechanics_excludes = []

    # list of all game titles
    title_list = games_all['name']
    title_list_lower = [s.lower() for s in title_list]
    games_by_title = recommender.item_data.set_index('name')

    # preferred game entry text control
    ctl_game_entry = AutocompleteInput(completions=list(title_list) +
                                       list(title_list_lower),
                                       min_characters=1,
                                       title='Enter some game names you like:')
    ctl_game_entry.on_change('value', update_preflist)

    # reset liked game list button
    ctl_reset_prefs = Button(label='Reset game list',
                             width_policy='min',
                             align='end')
    ctl_reset_prefs.on_click(reset_preferred_games)

    # liked list title
    ctl_liked_list_title = Div(
        text=
        """<div style="font-size : 18pt; line-height:16pt;">Games you like:</div>"""
    )

    # liked game entries
    ctl_liked_games = WidgetBox(
        children=make_div_list(liked_games, max_liked, fmt_str=liked_list_fmt))

    # recommended list title
    ctl_recommended_list_title = Div(
        text=
        """<div style="font-size : 18pt; line-height:16pt;">Games we recommend:</div>"""
    )

    # recommended games list widget
    ctl_recommended_games = WidgetBox(
        children=make_rec_list(recommended_games, n_recommendations))

    # Recommend games button
    ctl_recommend = Button(label='Recommend some games!',
                           width_policy='min',
                           align='center')
    ctl_recommend.on_click(recommend_games)

    # game weight slider
    ctl_game_weight = RangeSlider(
        start=1,
        end=5,
        value=(1, 5),
        step=.1,
        title='Game weight range',
        width_policy='min',
    )
    ctl_game_weight.on_change('value', update_filters)

    # min game rating slider
    ctl_game_min_rating = Slider(start=1,
                                 end=10,
                                 value=7,
                                 step=.1,
                                 title='Minimum average rating',
                                 width_policy='min')
    ctl_game_min_rating.on_change('value', update_filters)

    # collect all category and mechanics labels from recommender data
    categories, mechanics = recommender.get_categories_and_mechanics()

    # game category selection
    category_list = ['Any category'] + list(categories['tag'].values)
    ctl_category_selection1 = CheckboxGroup(
        labels=category_list[:int(num_check_options / 2)],
        width_policy='min',
        active=[0])
    ctl_category_selection1.on_change('active', update_filters)
    ctl_category_selection2 = CheckboxGroup(
        labels=category_list[int(num_check_options / 2):num_check_options],
        width_policy='min')
    ctl_category_selection2.on_change('active', update_filters)

    # game mechanism checkbox group
    mechanics_list = ['Any mechanism'] + list(mechanics['tag'].values)
    ctl_mechanics_selection1 = CheckboxGroup(
        labels=mechanics_list[:int(num_check_options / 2)],
        width_policy='min',
        active=[0])
    ctl_mechanics_selection1.on_change('active', update_filters)
    ctl_mechanics_selection2 = CheckboxGroup(
        labels=mechanics_list[int(num_check_options / 2):num_check_options],
        width_policy='min')
    ctl_mechanics_selection2.on_change('active', update_filters)

    # select whether to include expansions
    ctl_include_expansions = CheckboxGroup(labels=['Include game expansions'],
                                           width_policy='min')

    ctl_include_expansions.on_change('active', update_filters)
    # controls to select preferred games
    pref_controls = WidgetBox(
        ctl_liked_list_title,
        ctl_liked_games,
        Spacer(min_height=20),
        ctl_game_entry,
        ctl_reset_prefs,
        Spacer(min_height=5),
    )

    ctl_liked_list_title = Div(
        text=
        """<div style="font-size : 18pt; line-height:16pt;">Game Categories:</div>"""
    )

    filter_controls = WidgetBox(
        row(ctl_game_weight, Spacer(min_width=50), ctl_game_min_rating),
        row(ctl_include_expansions),
        column(
            row(
                Div(text=
                    """<div style="font-size : 18pt; line-height:16pt;">Game Categories:</div>"""
                    ), Spacer(min_width=50), ctl_recommend),
            row(ctl_category_selection1, ctl_category_selection2),
            Spacer(min_height=5),
            Div(text=
                """<div style="font-size : 18pt; line-height:16pt;">Game Mechanics:</div>"""
                ),
            row(ctl_mechanics_selection1, ctl_mechanics_selection2),
        ))

    # recommendation results
    results_controls = WidgetBox(
        ctl_recommended_list_title,
        ctl_recommended_games,
        Spacer(min_height=10),
    )

    # Create a row layout
    layout = row(column(pref_controls, filter_controls), Spacer(min_width=50),
                 results_controls)

    # Make a tab with the layout
    tab = Panel(child=layout, title='Advanced Game Recommender')

    return tab
Ejemplo n.º 20
0
    plot_height=PLOT_HEIGHT,
    plot_width=PLOT_WIDTH,
    tools=TOOLS,
    x_range=[1, 50],
    y_range=[0, 1],
)
plot.yaxis.axis_label = "Transmission fraction"
plot.xaxis.axis_label = "Energy [keV]"
plot.line("x", "y", source=source, line_width=3, line_alpha=0.6)
plot.title.text = f"{response}"
plot.add_tools(custom_hover)
# Set up the inputs
ylog_checkbox = CheckboxGroup(labels=["y-log"], active=[0])

# materials in the path
material_input = AutocompleteInput(title="Material (lowercase)",
                                   value=DEFAULT_MATERIAL[0])
material_input.completions = all_materials
material_thickness_input = TextInput(title="thickness",
                                     value=str(DEFAULT_THICKNESS[0]))
material_density_input = TextInput(title="density",
                                   value=str(this_material.density.value))

air_thickness_input = TextInput(title="air path length",
                                value=str(DEFAULT_AIR_THICKNESS))
air_pressure_input = TextInput(title='air pressure',
                               value=str(DEFAULT_AIR_PRESSURE))
air_temperature_input = TextInput(title='air temperature',
                                  value=str(DEFAULT_AIR_TEMPERATURE))

detector_material_input = AutocompleteInput(title='Detector',
                                            value=DEFAULT_DETECTOR_MATERIAL)
Ejemplo n.º 21
0
def beliebtheitsermittler(df,actorList, productionList , directorList, writersList, genreList,df_merged, ratingQuantile ):

    text =  "Füllen Sie die Felder aus und drücken auf den Start-Button um den Film zu bewerten."
    actorList = list(set(actorList))
    productionList = list(set(productionList))
    directorList = list(set(directorList))
    writersList = list(set(writersList))
    genreList = list(set(genreList))
    
    
    output_notebook()
    
    # Set up widgets
    actor1 = AutocompleteInput(completions=actorList, placeholder = 'Required',title='Schauspieler 1')
    actor2 = AutocompleteInput(completions=actorList, placeholder = 'Required',  title='Schauspieler 2')
    actor3 = AutocompleteInput(completions=actorList, placeholder = 'Required',  title='Schauspieler 3')
    actor4 = AutocompleteInput(completions=actorList, placeholder = 'Required',  title='Schauspieler 4')
    production = AutocompleteInput(completions=productionList, placeholder = 'Required', title='Production')
    director = AutocompleteInput(completions= directorList, placeholder = 'Required', title='Regie')
    autor = AutocompleteInput(completions= writersList, placeholder = 'Required', title='Autor')
    genre = Select(title = 'Auswahl des Hauptgenre',height = 50,value = 'Comedy',  options = genreList)
    
    select = Select(title = 'Auswahl der Metric',height = 50,value = 'Metascore',   options = ['Metascore', 'imdbRating', 'TomatoRating'])
    answer = Button(height = 100, width = 600,disabled = True,margin = [10,10,10,10],background = 'white', label = text)
    button = Button(margin = [23,0,0,200], width = 100, button_type = 'primary', label = 'Start')
    paragraph2 = Paragraph(margin = [40,0,0,10])
    paragraph2.text = "Ergebnis:"
    
    
    def doOnClick():
        metric = select.value
        columns = df_merged.columns.tolist()
        columns.remove('Category')
        
        if  (actor1.value in actorList) and (actor2.value in actorList) and (actor3.value in actorList) and (actor4.value in actorList) and (production.value in productionList) and (director.value in directorList) and (autor.value in writersList):
            filename = 'models/'+ metric + '_model.sav'
            
            model = pickle.load(open(filename, 'rb'))
            d = pd.DataFrame(0,index=np.arange(1), columns=columns)
            
            d['Actors_' + actor1.value] = 1
            d['Actors_' + actor2.value] = 1
            d['Actors_' + actor3.value] = 1
            d['Actors_' + actor4.value] = 1
            d['Genre_' + genre.value] = 1
            d['Director_' + director.value] = 1
            d['Writer_' + autor.value] = 1
            d['Production__'+ production.value]  = 1  
            
            result = model.predict(d)[0]

            if ('Gut' in result):
                answer.background = 'green'

            elif('Schlecht' in result):
                answer.background = 'red'
    
            else:
                answer.background = 'yellow'

             
            answer.label = result
        else:
            answer.label = text
            answer.background = 'white'
        
          
    button.on_click(doOnClick)
    
    
        
    layout = [row(widgetbox(actor1 , actor2, actor3, actor4, genre),
                  widgetbox( production, director,autor, select, button ))]
    
    def modify_doc(doc):

        doc.add_root(row(layout))
        doc.add_root(column(widgetbox(paragraph2,answer)))
    
    handler = FunctionHandler(modify_doc)
    app = Application(handler)
    show(app)