from sseclient import SSEClient as EventSource
import json
from collections import defaultdict
import threading

from ipywidgets import interact

from bokeh.io import push_notebook, show, output_notebook
from bokeh.plotting import figure
output_notebook()


def events(url):
    return (json.loads(event.data) for event in EventSource(url) 
            if event.event == 'message' and event.data)


wikis = {'enwiki': 0, 'dewiki': 1, 'eswiki': 2, 'ruwiki': 3}
wikiWhitelist = wikis.keys()

url = 'https://stream.wikimedia.org/v2/stream/recentchange'
eventsByWiki = defaultdict(int)

p = figure(plot_height=300, plot_width=800)
r = p.vbar(x=[1,2,3,4], width=0.5, bottom=0, top=[0,0,0,0], legend="Edits per wiki (enwiki, dewiki, eswiki, ruwiki)")
show(p, notebook_handle=True)


def updateData(wiki, value):
    r.data_source.data['top'][wikis[wiki]] = value

def updatePlot():
    push_notebook()
    threading.Timer(1, updatePlot).start()

updatePlot()

edits = (e for e in events(url) if e['type'] == 'edit')
for edit in edits:
    wiki = edit['wiki']
    if wiki in wikiWhitelist:
        eventsByWiki[wiki] += 1
        updateData(wiki, eventsByWiki[wiki])
Loading BokehJS ...