analytics.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. import pandas as pd
  2. import numpy as np
  3. import os
  4. import io
  5. import json
  6. from multiprocessing import Process
  7. import transport
  8. import sqlite3 as lite
  9. import numpy as np
  10. import transport
  11. import matplotlib.pyplot as plt
  12. import re, base64
  13. # from weasyprint import HTML, CSS
  14. COLORS = ["#fbd1a2","#00b2ca","#1d4e89","#4682B4","#c5c3c6","#4c5c68","#1985a1","#f72585","#7209b7","#3a0ca3","#4361ee","#4cc9f0","#ff595e","#ffca3a","#8ac926","#1982c4","#6a4c93"]
  15. class stdev :
  16. def __init__(self) :
  17. self.values = []
  18. def step(self,value):
  19. if value : #and type in [np.int64, np.int32,np.float64,np.float32, int]:
  20. self.values.append(value)
  21. def finalize(self):
  22. return np.std(self.values) if self.values else None
  23. # conn = lite.connect("/home/steve/healthcare-io/healthcare-io.db3")
  24. # conn.create_aggregate("stdev",1,stdev)
  25. # df = pd.read_sql("select count(distinct (json_extract(data,'$.patient_id'))) as patient_count, avg(json_array_length(data,'$.procedures')) mean, stdev(json_array_length(data,'$.procedures')) stdev from claims",conn)
  26. ROOT_FOLDER = 'stats'
  27. # plt.gcf().subplots_adjust(bottom=0.15)
  28. # from matplotlib import rcParams
  29. # rcParams.update({'figure.autolayout': True})
  30. class Chart :
  31. @staticmethod
  32. def remove_borders(axes,wedges,labels,item) :
  33. # plt.axes()
  34. axes.spines["top"].set_visible(False)
  35. # plt.axes().
  36. axes.spines["right"].set_visible(False)
  37. axes.legend(wedges, labels #,title=item['label']
  38. ,loc="upper right",fontsize=12,bbox_to_anchor=(1, 0, 0.5, 1),fancybox=True,framealpha=0.2)
  39. # plt.axes().
  40. # axes.spines["left"].set_visible(False)
  41. if 'axis' in item['chart'] :
  42. axes.set_ylabel(item['chart']['axis']['y'])
  43. axes.set_xlabel(item['chart']['axis']['x'])
  44. @staticmethod
  45. def donut(item,**args) :
  46. df = item['data']
  47. x = item['chart']['x'] #args['x']
  48. labels = item['chart']['y']
  49. labels = df[labels]
  50. # figure = plt.figure()
  51. figure, axes = plt. subplots()
  52. # wedges, texts = plt.pie(df[x],labels=labels)
  53. colors = COLORS[:len(labels)] #np.random.choice(COLORS,len(labels),replace=False)
  54. wedges = axes.pie(df[x],labels=labels,wedgeprops=dict(width=0.3),colors=colors,autopct=lambda pct: "{:.2f}%\n({:.0f})".format(pct,int((pct/100)*df[x].sum() ))) #,autopct=lambda pct: func(pct, df[x].values))
  55. # my_circle=plt.Circle( (0,0), 0.7, color='#ffffff',fill=True)
  56. # p=plt.gcf()
  57. # p.gca().add_artist(my_circle)
  58. # plt.legend(wedges, labels,title=item['label'],loc="upper right",bbox_to_anchor=(1, 0, 0.5, 1))
  59. # axes.legend(wedges[0], labels,title=item['label'],loc="upper right",bbox_to_anchor=(1, 0, 0.5, 1),framealpha=0,edgecolor='#CAD5E0',
  60. # )
  61. # x = plt.show()
  62. Chart.remove_borders(axes,wedges[0],labels,item)
  63. plt.close()
  64. return figure
  65. @staticmethod
  66. def barh(item,**args):
  67. """
  68. This function will return/render a bar chart (horizontal) which is conducive to showing distributions of things like diagnosis codes
  69. """
  70. # figure = plt.figure()
  71. figure, axes = plt. subplots()
  72. y_labels = item['chart']['y'][0]
  73. x_labels = item['chart']['x'] #[args['x']] if type(args['x']) == str else args['x']
  74. df = item['data'].iloc[:9].copy()
  75. # odf = item['data'].iloc[9:].copy().mean().to_frame().T
  76. # odf[y_labels] = 'Other'
  77. # df = df.append(odf)
  78. wedges = []
  79. # COLORS = ['#003f5c','#7a5195','#374c80','#bc5090','#ef5675','#ff764a','#ffa600']
  80. for x_ in x_labels:
  81. index = x_labels.index(x_)
  82. color = COLORS[index]
  83. w = axes.barh(df[y_labels],df[x_],align='edge',label='counts' ,color=color)
  84. wedges += [w]
  85. # labels = [name.replace('_',' ') for name in x_labels]
  86. # axes.legend(wedges,[name.replace('_',' ') for name in x_labels],
  87. # title=item['label'],
  88. # framealpha=0,
  89. # edgecolor='#CAD5E0',
  90. # loc="upper right",bbox_to_anchor=(1, 0, 0.5, 1)
  91. # )
  92. Chart.remove_borders(axes,wedges,[name.replace('_',' ') for name in x_labels],item)
  93. plt.close()
  94. return figure
  95. @staticmethod
  96. def spline(item,**args):
  97. """
  98. """
  99. df = item['data']
  100. # figure = plt.figure()
  101. figure, axes = plt. subplots()
  102. wedges = []
  103. item['chart']['x'] = [item['chart']['x']]if type(item['chart']['x']) == str else item['chart']['x']
  104. # COLORS = ['#003f5c','#7a5195','#374c80','#bc5090','#ef5675','#ff764a','#ffa600']
  105. for xl in item['chart']['x'] :
  106. x = df[xl]
  107. index = 0
  108. for yl in item['chart']['y'] :
  109. y = df[yl]
  110. color = COLORS[index]
  111. if 'scatter' in args :
  112. w = plt.plot(x,y,'o',color=color)
  113. else:
  114. w = plt.plot(x,y,color=color,marker='o')
  115. wedges += w
  116. index += 1
  117. # print (item['chart']['x'])
  118. # if 'axis' in item :
  119. # axes.set_ylabel(item['axis']['y'])
  120. # axes.set_xlabel(item['axis']['x'])
  121. # plt.title(item['label'])
  122. # axes.legend(wedges,[name.replace('_',' ') for name in item['chart']['y']],
  123. # title=item['label'],
  124. # framealpha=0,
  125. # edgecolor='#CAD5E0',
  126. # loc="upper right",bbox_to_anchor=(1, 0, 0.5, 1)
  127. # )
  128. axes.grid(b=False,which='major',axis='x')
  129. Chart.remove_borders(axes,wedges,[name.replace('_',' ') for name in item['chart']['y']],item)
  130. plt.close()
  131. return figure
  132. @staticmethod
  133. def scatter(item,**args):
  134. return Chart.spline(item,scatter=True)
  135. class Apex :
  136. """
  137. This class will format a data-frame to work with Apex charting engine
  138. """
  139. @staticmethod
  140. def apply(item,theme={'mode':'light','palette':'palette6'}):
  141. pointer = item['chart']['type']
  142. if hasattr(Apex,pointer) :
  143. pointer = getattr(Apex,pointer)
  144. options = pointer(item)
  145. if 'apex' in options and 'colors' in options['apex'] :
  146. del options['apex']['colors']
  147. if 'apex' in options :
  148. options['apex']['theme'] = theme
  149. options['responsive']= [
  150. {
  151. 'breakpoint': 1,
  152. 'options': {
  153. 'plotOptions':item['plotOptions'] if 'plotOptions' in item else None,
  154. }
  155. }
  156. ]
  157. return options
  158. else:
  159. print ("Oops")
  160. pass
  161. @staticmethod
  162. def radial(item):
  163. df = item['data']
  164. x = item['chart']['axis']['x']
  165. y = item['chart']['axis']['y']
  166. labels = df[y].tolist()
  167. values = [float(np.round(value,2)) for value in df[x].tolist()]
  168. chart = {"type":"radialBar","height":200}
  169. option = {"chart":chart,"series":values,"labels":labels,"plotOptions":{"radialBar":{"hollow":{"size":"70%"}}}}
  170. return {'apex':option}
  171. @staticmethod
  172. def scatter(item):
  173. options = Apex.spline(item)
  174. options['apex']['chart']['type'] = 'scatter'
  175. return options
  176. @staticmethod
  177. def scalar(item):
  178. _df = item['data']
  179. value = '0'
  180. unit = ''
  181. html = '<div class="scalar"><div class="value">:value</div><div class="label">:label</div></div>'
  182. if _df.shape[0] > 0 :
  183. print (_df)
  184. print ('_____________________________________')
  185. name = _df.columns.tolist()[0]
  186. value = _df[name].values[0]
  187. if value > 999 and value < 1000000 :
  188. value = " ".join([str(np.divide(value,1000).round(2)),"K"])
  189. elif value > 999999 :
  190. #@ Think of considering the case of a billion ...
  191. value = " ".join([str(np.divide(value,1000000).round(2)),"M"])
  192. else:
  193. value = str(value)
  194. unit = name.replace('_',' ') if 'unit' not in item else item['unit']
  195. return {'html':html.replace(':value',value).replace(":label",unit)}
  196. @staticmethod
  197. def column(item):
  198. df = item['data']
  199. N = df.shape[0] if df.shape[0] < 10 else 10
  200. axis = item['chart']['axis']
  201. x = axis['x']
  202. if type(x) == list :
  203. x = x[0]
  204. axis['y'] = [axis['y']] if type(axis['y']) != list else axis['y']
  205. series = []
  206. for y in axis['y'] :
  207. series += [{"data": df[y].values.tolist()[:N],"name":y.upper().replace('_',' ')}]
  208. xtitle,ytitle = Apex.get_labels(item)
  209. options = {"chart":{"type":"bar"},"plotOptions":{"bar":{"horizontal":False,"width:":2,"color":["transparent"]}},"dataLabels":{"enabled":False},"legend":{"position":"right"}}
  210. options['xaxis'] = {"categories":df[x].values.tolist()[:N],"title":xtitle['title']}
  211. options['yaxis'] = ytitle
  212. options['series'] = series
  213. options['colors'] = COLORS[:df[x].size]
  214. return {"apex":options}
  215. # options = Apex.barh(item)
  216. # options['chart']['type'] = 'column'
  217. # options['plotOptions']['bar'] = {'horizontal':False,'columnWidth':'55%'}
  218. # options['stroke']={'show':True,'width':2,'colors':['transparent']}
  219. # return {"apex":options}
  220. @staticmethod
  221. def get_labels(item):
  222. xtitle = ytitle = ""
  223. if "labels" not in item['chart'] :
  224. xtitle = item['chart']['axis']['x']
  225. ytitle = item['chart']['axis']['y']
  226. else:
  227. xtitle = item['chart']['labels']['x']
  228. ytitle = item['chart']['labels']['y']
  229. xtitle = xtitle if type(xtitle) != list else xtitle[0]
  230. ytitle = ytitle if type(ytitle) != list else ytitle[0]
  231. return {"title":{"text":xtitle.lower().replace('_',' '),"style":{"fontWeight":"lighter"}}},{"title":{"text":ytitle.lower().replace('_',' '),"style":{"fontWeight":"lighter"}}}
  232. @staticmethod
  233. def bar(item):
  234. return Apex.barh(item)
  235. @staticmethod
  236. def barh(item):
  237. """
  238. rendering a horizontal bar chart assuming for now that only one series is involved
  239. @TODO: alias this with bar (!= column)
  240. """
  241. df = item['data']
  242. N = df.shape[0] if df.shape[0] < 10 else 10
  243. axis = item['chart']['axis']
  244. y = axis['y']
  245. if type(y) == list :
  246. y = y[0]
  247. axis['x'] = [axis['x']] if type(axis['x']) != list else axis['x']
  248. # if not set(axis['x']) & set(df.columns.tolist()) :
  249. # print (set(axis['x']) & set(df.columns.tolist()))
  250. # print (axis['x'])
  251. # print (df.columns)
  252. # df.columns = axis['x']
  253. series = []
  254. _min=_max = 0
  255. for x in axis['x'] :
  256. series += [{"data": df[x].values.tolist()[:N],"name":x.upper().replace('_',' ')}]
  257. _min = df[x].min() if df[x].min() < _min else _min
  258. _max = df[x].max() if df[x].max() > _max else _max
  259. xtitle , ytitle = Apex.get_labels(item)
  260. options = {"chart":{"type":"bar"},"plotOptions":{"bar":{"horizontal":True}},"dataLabels":{"enabled":False},"legend":{"position":"right"}}
  261. options['xaxis'] = {"categories":df[y].values.tolist()[:N],"title":xtitle['title']}
  262. options['yaxis'] = ytitle
  263. options['series'] = series
  264. options['colors'] = COLORS[:df[x].size]
  265. return {"apex":options}
  266. @staticmethod
  267. def spline(item):
  268. series = []
  269. df = item['data']
  270. N = df.shape[0] if df.shape[0] < 10 else 10
  271. axis = item['chart']['axis']
  272. x = axis['x']
  273. _min=_max = 0
  274. for y in axis['y'] :
  275. series += [{"data":df[y].values[:N].tolist(),"name":y.upper().replace('_',' ')}]
  276. _min = df[y].min() if df[y].min() < _min else _min
  277. _max = df[y].max() if df[y].max() > _max else _max
  278. colors = COLORS[:len(axis['y'])]
  279. options = {"chart":{"type":"line"},"series":series,"stroke":{"curve":"smooth"},"colors":colors,"legend":{"position":"right"}}
  280. xtitle , ytitle = Apex.get_labels(item)
  281. options['xaxis'] = {"categories":df[x].values[:N].tolist(),"title":xtitle['title']}
  282. options['yaxis'] = ytitle
  283. return {"apex":options}
  284. @staticmethod
  285. def donut(item):
  286. """
  287. :pre data must have more than one item otherwise just make it a scalar
  288. here we will use the key as labels and the values as the values (obviously)
  289. labels are y-axis
  290. values are x-axis
  291. """
  292. df = item['data']
  293. if df.shape [0]> 1 :
  294. y_cols,x_cols = item['chart']['axis']['y'],item['chart']['axis']['x']
  295. labels = df[y_cols].values.tolist()
  296. values = df[x_cols].values.round(2).tolist()
  297. else:
  298. labels = [name.upper().replace('_',' ') for name in df.columns.tolist()]
  299. # df = df.astype(float)
  300. # values = df.values.round(2).tolist()[0] if df.shape[1] > 1 else df.values.round(2).tolist()
  301. values = df[[name for name in df.columns if df[name].dtype in [float,int]] ].values.round(2).tolist()
  302. colors = COLORS[:len(values)]
  303. options = {"series":values,"colors":colors,"labels":labels,"dataLabels":{"enabled":True,"style":{"colors":["#000000"]},"dropShadow":{"enabled":False}},"chart":{"type":"donut","width":200},"plotOptions":{"pie":{"customScale":.9}},"legend":{"position":"right"}}
  304. return {"apex":options}
  305. pass
  306. class engine :
  307. """
  308. This engine is designed to load the configuration and run the queries given they are remittance or claims
  309. @TODO:
  310. - make sure the readers of the queries are configurable i.e use data-transport
  311. """
  312. def __init__(self,path) :
  313. """
  314. Loading configuration file from a designated location ...
  315. """
  316. f = open(path) ;
  317. _config = json.loads(f.read())
  318. self.store_config = _config['store']
  319. self.info = _config['analytics']
  320. _args = self.store_config
  321. if 'type' not in self.store_config :
  322. #
  323. # This is the newer version of data-transport
  324. self.store_config['context'] = 'read'
  325. self.store_config = _args ;
  326. def filter (self,**args):
  327. """
  328. type: claims or remits
  329. filter optional identifier claims, procedures, taxonomy, ...
  330. """
  331. _m = {'claim':'837','claims':'837','remits':'835','remit':'835'}
  332. table = _m[ args['type']]
  333. _analytics = self.info[table]
  334. if 'index' in args :
  335. index = int(args['index'])
  336. _analytics = [_analytics[index]]
  337. _info = list(_analytics) #if 'filter' not in args else [item for item in analytics if args['filter'] == item['id']]
  338. # conn = lite.connect(self.store_config['args']['path'],isolation_level=None)
  339. # conn.create_aggregate("stdev",1,stdev)
  340. DB_TYPE = 'mongo' if (type(self.reader) == transport.mongo.MongoReader) else 'sql'
  341. # if DB_TYPE == 'mongo' :
  342. # self.store_config['args']['doc'] = args['type']
  343. self.reader = transport.factory.instance(**self.store_config)
  344. r = []
  345. for row in _info :
  346. pipeline = row['pipeline']
  347. index = 0
  348. for item in pipeline:
  349. if not item[DB_TYPE] :
  350. continue
  351. query = {DB_TYPE:item[DB_TYPE]}
  352. df = pd.DataFrame(self.reader.read(**query)) #item)
  353. df = df.fillna('N/A')
  354. # item['data'] = df
  355. chart = item['chart']
  356. pipe = {"data":df,"chart":chart}
  357. for key in list(item.keys()) :
  358. if key not in ["chart","data","mongo","sql","couch"] :
  359. pipe[key] = item[key]
  360. r.append(pipe)
  361. self.reader.close()
  362. return {"id":_info[0]['id'],'pipeline':r}
  363. def apply (self,**args) :
  364. """
  365. type: claims or remits
  366. filter optional identifier claims, procedures, taxonomy, ...
  367. """
  368. _m = {'claim':'837','claims':'837','remits':'835','remit':'835'}
  369. # key = '837' if args['type'] == 'claims' else '835'
  370. table = _m[ args['type']]
  371. _analytics = self.info[table]
  372. if 'index' in args :
  373. index = int(args['index'])
  374. _analytics = [_analytics[index]]
  375. _info = list(_analytics) if 'filter' not in args else [item for item in analytics if args['filter'] == item['id']]
  376. self.reader = transport.factory.instance(**self.store_config)
  377. DB_TYPE = 'mongo' if self.store_config ['provider'] in ['mongodb','mongo'] else 'sql'
  378. r = []
  379. for row in _info :
  380. pipeline = row['pipeline']
  381. index = 0
  382. for item in pipeline:
  383. # item['data'] = pd.read_sql(item['sql'],conn)
  384. # query = {DB_TYPE:item[DB_TYPE]}
  385. query = item[DB_TYPE]
  386. if not query :
  387. continue
  388. if DB_TYPE == 'sql' :
  389. query = {"sql":query}
  390. else:
  391. query = {DB_TYPE:query}
  392. _df = self.reader.read(**query) #item)
  393. print (query)
  394. print (self.reader)
  395. if 'serialize' in args :
  396. # item['data'] = json.dumps(item['data'].to_dict(orient='record')) if type(item['data']) == pd.DataFrame else item['data']
  397. item['data'] = json.dumps(_df.to_dict(orient='record'))
  398. else:
  399. # item['data'] = (pd.DataFrame(item['data']))
  400. item['data'] = _df
  401. pass
  402. print (_df.head())
  403. break
  404. pipeline[index] = item
  405. index += 1
  406. #
  407. #
  408. row['pipeline']= pipeline
  409. # if 'info' in item:
  410. # item['info'] = item['info'].replace(":rows",str(item["data"].shape[0]))
  411. # conn.close()
  412. self.reader.close()
  413. return _info
  414. def _html(self,item) :
  415. figure = None
  416. df = item['data']
  417. label = ['<div class="label">',item['label'],'</div>']
  418. text = ['<div class="grid">',df.describe().iloc[:].round(2).to_html().replace('_',' '),'</div>']
  419. info = ['<div class="info">',item['info'],'</div>'] if 'info' in item else []
  420. if item['chart']['type'] in ['pie','donut','doughnut'] :
  421. figure = Chart.donut(item)
  422. text = ['<div class="grid">',df.to_html(index=False).replace('_',' '),'</div>']
  423. elif item['chart']['type'] == 'scatter' :
  424. figure = Chart.scatter(item)
  425. elif item['chart']['type'] == 'spline' :
  426. figure = Chart.spline(item)
  427. elif item['chart']['type'] in ['barh','hbar'] :
  428. figure = Chart.barh(item)
  429. elif item['chart']['type'] == 'scalar' :
  430. figure = (item['data'].apply(lambda col: '<div class="scalar"><div class="value bold">'+str(col.values[0].round(2))+'</div><div class="value-text">'+col.name.replace('_', ' ')+'</div></div>' ).tolist())
  431. label = text = []
  432. pass
  433. if figure and item['chart']['type'] != 'scalar':
  434. stream = io.BytesIO()
  435. figure.savefig(stream,format='png',dpi=300,quality=95, bbox_inches = "tight",transparent=True)
  436. stream.seek(0)
  437. stream = base64.b64encode(stream.getvalue()).decode("utf-8")
  438. stream = "data:image/png;base64,"+stream
  439. figure = ['<div class="figure"><img src="'+stream+'">',"</div>"]
  440. # figure.canvas.draw()
  441. # figure = "".join( map(chr,figure.canvas.tostring_argb())) #--bytes
  442. # else:
  443. # figure = [ ]
  444. if item['chart']['type'] != 'scalar':
  445. return ['<div class="frame"><div class="chart '+ item['chart']['type']+'">'] + [ " ".join(row) for row in [label,figure,text,info] if row] + ["</div></div>"]
  446. else:
  447. return [ " ".join(row) for row in [label,figure,text,info] if row]
  448. pass
  449. def _csv(self,item):
  450. pass
  451. def export(self,item,format):
  452. """
  453. We have a pipeline here and we should attempt to build a figure using seaborn within an html template using jinja2
  454. This is considered a page (or an item) of an analysis where we will have both data and rendering information with accompanying text
  455. """
  456. html = []
  457. for row in item['pipeline'] :
  458. p = [ "<h2>",row['label'].replace('_',' '),"</h2>"]
  459. y_label = [name for name in row['data'].columns if 'count' in name]
  460. x_label = list(set(row['data'].columns) - set(y_label))
  461. N = row.shape[0]
  462. if 'info' in row :
  463. p += ["<div class='info'>",row['info'],'</div>']
  464. pass
  465. class LogAnalytics :
  466. def __init__(self,path):
  467. logs = open(path).read().split('\n')
  468. logs = [json.loads(row) for row in logs if row.strip() != '']
  469. self.remits = {
  470. "completed": np.sum([1 for row in logs if row['completed'] == True]),
  471. "files":len(logs)
  472. }
  473. # m = LogAnalytics('/home/steve/healthcare-io/remits.log')
  474. css = """
  475. <meta charset="utf-8">
  476. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  477. <title>HealthcareIO - :title </title>
  478. <style>
  479. body{
  480. padding:8px;
  481. padding-left:4%;
  482. padding-right:4%;
  483. }
  484. .pane{
  485. padding:4px;
  486. display:grid;
  487. gap:16px;
  488. grid-template-columns:repeat(2,1fr) ;
  489. }
  490. .numbers {
  491. display:grid;
  492. grid-template-columns:repeat(2,1fr);
  493. gap:16px;
  494. /*padding:2px;*/
  495. /*border:1px solid #CAD5E0;*/
  496. }
  497. .numbers .scalar {
  498. padding:8px;
  499. background-image: linear-gradient(to bottom, #f3f3f3,#d3d3d3, #ffffff);
  500. border:1px solid #CAD5E0;
  501. font-family:sans-serif;
  502. text-transform:capitalize;
  503. text-align:right;
  504. font-size:12px;
  505. display:grid;
  506. grid-template-rows:auto 28px; gap:2px;
  507. }
  508. .numbers .scalar .value-text {
  509. border-top:1px solid #CAD5E0;
  510. padding:8px;
  511. font-weight:bold;
  512. align-items:center;
  513. font-size:14px;
  514. display:grid;
  515. }
  516. .numbers .scalar .value {
  517. display:grid;
  518. color:#004b79;
  519. align-content:center;
  520. font-size:48px; text-align:right; font-weight:bold;}
  521. .frame {
  522. background-image: linear-gradient(to bottom, #f3f3f3,#d3d3d3, #ffffff);
  523. padding:2px;
  524. border:1px solid #CAD5E0;
  525. }
  526. .figure {grid-area:figure; width:500px; height:350px; display:grid; align-items:center}
  527. .info {height:28px; width:100%; grid-area:info;
  528. display:grid;
  529. align-items:center;
  530. text-align:center; text-transform:capitalize; padding:4px; font-size:12px; font-family:sans-serif; border-top:1px solid #CAD5E0;}
  531. .grid {grid-area:grid; }
  532. .label {grid-area:label; font-weight:bold; font-size: 22px; text-align:center; text-transform:capitalize}
  533. .chart {
  534. padding:4px;
  535. padding:8px;
  536. display:grid; grid-template-areas:
  537. "label label label"
  538. "figure grid grid"
  539. "info info info" ;
  540. gap:2px;
  541. }
  542. img {height:auto; max-width:100% ;}
  543. table {width:100%; border-collapse: collapse;}
  544. table , TH, TD{ font-size:14px; padding:8px; font-family:sans-serif; border:1px; border:1px solid #CAD5E0;}
  545. table thead, tbody th { padding:4px; text-transform:capitalize; background-color:#4682B4; color:#ffffff; text-align:center}
  546. table thead tr th {text-align:center}
  547. table tbody td {text-align:right; font-weight: lighter}
  548. table tbody tr:nth-child(odd) {background: #95bce0}
  549. table tbody tr:nth-child(even) {background: #c8e5ff}
  550. </style>
  551. """
  552. # folder = '/home/steve/.healthcareio/config.json'
  553. # e = engine(path=folder)
  554. # p = e.apply(type='claims')
  555. # values = []
  556. # html = [css]
  557. # for row in p :
  558. # frame = []
  559. # for item in row['pipeline'] :
  560. # if row['pipeline'].index(item) == 0 :
  561. # if item['chart']['type'] != 'scalar' :
  562. # # frame = ['<div class="frame">']
  563. # pass
  564. # else:
  565. # frame = ['<div><div class="numbers">']
  566. # frame += e._html(item) #p[3]['pipeline'][0])
  567. # frame += ['</div></div>'] if item['chart']['type'] == 'scalar' else []
  568. # html += frame
  569. # html = '<div class="pane">' + "\n".join(html) + "</div></div>"
  570. # f = open('out.html','w')
  571. # f.write(html.replace(":title","Claims"))
  572. #
  573. # HTML(string=html).write_pdf('out.pdf',stylesheets=[CSS(string=css)])
  574. # x.write_pdf('./out.pdf')
  575. # print (p[2]['pipeline'][0]['data'])
  576. # e.export (p[0])
  577. # features = ['diagnosis.code']
  578. # split(folder = folder, features=features)