healthcare-io.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. #!/usr/bin/env python3
  2. """
  3. (c) 2019 Claims Toolkit,
  4. Health Information Privacy Lab, Vanderbilt University Medical Center
  5. Steve L. Nyemba <steve.l.nyemba@vanderbilt.edu>
  6. Khanhly Nguyen <khanhly.t.nguyen@gmail.com>
  7. This code is intended to process and parse healthcare x12 837 (claims) and x12 835 (remittances) into human readable JSON format.
  8. The claims/outpout can be forwarded to a NoSQL Data store like couchdb and mongodb
  9. Usage :
  10. Commandline :
  11. python edi-parser --scope --config <path> --folder <path> --store <[mongo|disk|couch]> --<db|path]> <id|path>
  12. with :
  13. --scope <claims|remits>
  14. --config path of the x12 to be parsed i.e it could be 835, or 837
  15. --folder location of the files (they must be decompressed)
  16. --store data store could be disk, mongodb, couchdb
  17. --db|path name of the folder to store the output or the database name
  18. Embedded in Code :
  19. import edi.parser
  20. import json
  21. file = '/data/claim_1.x12'
  22. conf = json.loads(open('config/837.json').read())
  23. edi.parser.get_content(filename,conf)
  24. """
  25. from healthcareio.params import SYS_ARGS
  26. from transport import factory
  27. import requests
  28. from healthcareio import analytics
  29. from healthcareio import server
  30. from healthcareio.parser import get_content
  31. import os
  32. import json
  33. import sys
  34. import numpy as np
  35. from multiprocessing import Process
  36. import time
  37. PATH = os.sep.join([os.environ['HOME'],'.healthcareio'])
  38. OUTPUT_FOLDER = os.sep.join([os.environ['HOME'],'healthcare-io'])
  39. INFO = None
  40. URL = "https://healthcareio.the-phi.com"
  41. if not os.path.exists(PATH) :
  42. os.mkdir(PATH)
  43. import platform
  44. import sqlite3 as lite
  45. # PATH = os.sep.join([os.environ['HOME'],'.edi-parser'])
  46. def register (**args) :
  47. """
  48. :email user's email address
  49. :url url of the provider to register
  50. """
  51. email = args['email']
  52. url = args['url'] if 'url' in args else URL
  53. folders = [PATH,OUTPUT_FOLDER]
  54. for path in folders :
  55. if not os.path.exists(path) :
  56. os.mkdir(path)
  57. #
  58. #
  59. store = args['store'] if 'store' in args else 'sqlite'
  60. headers = {"email":email,"client":platform.node(),"store":store,"db":args['db']}
  61. http = requests.session()
  62. r = http.post(url,headers=headers)
  63. #
  64. # store = {"type":"disk.DiskWriter","args":{"path":OUTPUT_FOLDER}}
  65. # if 'store' in args :
  66. # store = args['store']
  67. filename = (os.sep.join([PATH,'config.json']))
  68. info = r.json() #{"parser":r.json(),"store":store}
  69. info = dict({"owner":email},**info)
  70. info['store']['args']['path'] =os.sep.join([OUTPUT_FOLDER,'healthcare-io.db3']) #-- sql
  71. info['out-folder'] = OUTPUT_FOLDER
  72. file = open( filename,'w')
  73. file.write( json.dumps(info))
  74. file.close()
  75. #
  76. # Create the sqlite3 database to
  77. def log(**args):
  78. """
  79. This function will perform a log of anything provided to it
  80. """
  81. pass
  82. def init():
  83. """
  84. read all the configuration from the
  85. """
  86. filename = os.sep.join([PATH,'config.json'])
  87. info = None
  88. if os.path.exists(filename):
  89. file = open(filename)
  90. info = json.loads(file.read())
  91. if not os.path.exists(info['out-folder']) :
  92. os.mkdir(info['out-folder'])
  93. if info['store']['type'] == 'disk.SQLiteWriter' and not os.path.exists(info['store']['args']['path']) :
  94. conn = lite.connect(info['store']['args']['path'],isolation_level=None)
  95. for key in info['schema'] :
  96. _sql = info['schema'][key]['create']
  97. # r = conn.execute("select * from sqlite_master where name in ('claims','remits')")
  98. conn.execute(_sql)
  99. conn.commit()
  100. conn.close()
  101. return info
  102. #
  103. # Global variables that load the configuration files
  104. def parse(**args):
  105. """
  106. This function will parse the content of a claim or remittance (x12 format) give the following parameters
  107. :filename absolute path of the file to be parsed
  108. :type claims|remits in x12 format
  109. """
  110. global INFO
  111. if not INFO :
  112. INFO = init()
  113. if args['type'] == 'claims' :
  114. CONFIG = INFO['parser']['837']
  115. elif args['type'] == 'remits' :
  116. CONFIG = INFO['parser']['835']
  117. else:
  118. CONFIG = None
  119. if CONFIG :
  120. # CONFIG = CONFIG[-1] if 'version' not in args and (args['version'] < len(CONFIG)) else CONFIG[0]
  121. CONFIG = CONFIG[int(args['version'])-1] if 'version' in SYS_ARGS and int(SYS_ARGS['version']) < len(CONFIG) else CONFIG[-1]
  122. SECTION = CONFIG['SECTION']
  123. os.environ['HEALTHCAREIO_SALT'] = INFO['owner']
  124. return get_content(args['filename'],CONFIG,SECTION)
  125. def apply(files,store_info,logger_info=None):
  126. """
  127. :files list of files to be processed in this given thread/process
  128. :store_info information about data-store, for now disk isn't thread safe
  129. :logger_info information about where to store the logs
  130. """
  131. if not logger_info :
  132. logger = factory.instance(type='disk.DiskWriter',args={'path':os.sep.join([info['out-folder'],SYS_ARGS['parse']+'.log'])})
  133. else:
  134. logger = factory.instance(**logger_info)
  135. writer = factory.instance(**store_info)
  136. for filename in files :
  137. if filename.strip() == '':
  138. continue
  139. # content,logs = get_content(filename,CONFIG,CONFIG['SECTION'])
  140. #
  141. try:
  142. content,logs = parse(filename = filename,type=SYS_ARGS['parse'])
  143. if content :
  144. writer.write(content)
  145. if logs :
  146. [logger.write(dict(_row,**{"parse":SYS_ARGS['parse']})) for _row in logs]
  147. else:
  148. logger.write({"parse":SYS_ARGS['parse'],"name":filename,"completed":True,"rows":len(content)})
  149. except Exception as e:
  150. logger.write({"parse":SYS_ARGS['parse'],"filename":filename,"completed":False,"rows":-1,"msg":e.args[0]})
  151. # print ([filename,len(content)])
  152. #
  153. # @TODO: forward this data to the writer and log engine
  154. #
  155. def upgrade(**args):
  156. """
  157. :email provide us with who you are
  158. :key upgrade key provided by the server for a given email
  159. """
  160. url = args['url'] if 'url' in args else URL+"/upgrade"
  161. headers = {"key":args['key'],"email":args["email"],"url":url}
  162. if __name__ == '__main__' :
  163. info = init()
  164. if 'out-folder' in SYS_ARGS :
  165. OUTPUT_FOLDER = SYS_ARGS['out-folder']
  166. if set(list(SYS_ARGS.keys())) & set(['signup','init']):
  167. #
  168. # This command will essentially get a new copy of the configurations
  169. # @TODO: Tie the request to a version ?
  170. #
  171. email = SYS_ARGS['signup'].strip() if 'signup' in SYS_ARGS else SYS_ARGS['init']
  172. url = SYS_ARGS['url'] if 'url' in SYS_ARGS else 'https://healthcareio.the-phi.com'
  173. store = SYS_ARGS['store'] if 'store' in SYS_ARGS else 'sqlite'
  174. db='healthcareio' if 'db' not in SYS_ARGS else SYS_ARGS['db']
  175. register(email=email,url=url,store=store,db=db)
  176. # else:
  177. # m = """
  178. # usage:
  179. # healthcareio --signup --email myemail@provider.com [--url <host>]
  180. # """
  181. # print (m)
  182. elif 'upgrade' in SYS_ARGS :
  183. #
  184. # perform an upgrade i.e some code or new parsers information will be provided
  185. #
  186. pass
  187. elif 'parse' in SYS_ARGS and info:
  188. """
  189. In this section of the code we are expecting the user to provide :
  190. :folder location of the files to process or file to process
  191. :
  192. """
  193. files = []
  194. if 'file' in SYS_ARGS :
  195. files = [SYS_ARGS['file']] if not os.path.isdir(SYS_ARGS['file']) else []
  196. if 'folder' in SYS_ARGS and os.path.exists(SYS_ARGS['folder']):
  197. names = os.listdir(SYS_ARGS['folder'])
  198. files += [os.sep.join([SYS_ARGS['folder'],name]) for name in names if not os.path.isdir(os.sep.join([SYS_ARGS['folder'],name]))]
  199. else:
  200. #
  201. # raise an erro
  202. pass
  203. #
  204. # @TODO: Log this here so we know what is being processed or not
  205. SCOPE = None
  206. if files and ('claims' in SYS_ARGS['parse'] or 'remits' in SYS_ARGS['parse']):
  207. # _map = {'claims':'837','remits':'835'}
  208. # key = _map[SYS_ARGS['parse']]
  209. # CONFIG = info['parser'][key]
  210. # if 'version' in SYS_ARGS and int(SYS_ARGS['version']) < len(CONFIG) :
  211. # CONFIG = CONFIG[ int(SYS_ARGS['version'])]
  212. # else:
  213. # CONFIG = CONFIG[-1]
  214. logger = factory.instance(type='disk.DiskWriter',args={'path':os.sep.join([info['out-folder'],SYS_ARGS['parse']+'.log'])})
  215. if info['store']['type'] == 'disk.DiskWriter' :
  216. info['store']['args']['path'] += (os.sep + 'healthcare-io.json')
  217. elif info['store']['type'] == 'disk.SQLiteWriter' :
  218. # info['store']['args']['path'] += (os.sep + 'healthcare-io.db3')
  219. pass
  220. if info['store']['type'] == 'disk.SQLiteWriter' :
  221. info['store']['args']['table'] = SYS_ARGS['parse'].strip().lower()
  222. else:
  223. #
  224. # if we are working with no-sql we will put the logs in it (performance )?
  225. info['store']['args']['doc'] = SYS_ARGS['parse'].strip().lower()
  226. _info = json.loads(json.dumps(info['store']))
  227. _info['args']['doc'] = 'logs'
  228. logger = factory.instance(**_info)
  229. writer = factory.instance(**info['store'])
  230. #
  231. # we need to have batches ready for this in order to run some of these queries in parallel
  232. # @TODO: Make sure it is with a persistence storage (not disk .. not thread/process safe yet)
  233. # - Make sure we can leverage this on n-cores later on, for now the assumption is a single core
  234. #
  235. BATCH_COUNT = 1 if 'batch' not in SYS_ARGS else int (SYS_ARGS['batch'])
  236. #logger = factory.instance(type='mongo.MongoWriter',args={'db':'healthcareio','doc':SYS_ARGS['parse']+'_logs'})
  237. # schema = info['schema']
  238. # for key in schema :
  239. # sql = schema[key]['create']
  240. # writer.write(sql)
  241. files = np.array_split(files,BATCH_COUNT)
  242. procs = []
  243. index = 0
  244. for row in files :
  245. row = row.tolist()
  246. logger.write({"process":index,"parse":SYS_ARGS['parse'],"file_count":len(row)})
  247. proc = Process(target=apply,args=(row,info['store'],_info,))
  248. proc.start()
  249. procs.append(proc)
  250. index = index + 1
  251. while len(procs) > 0 :
  252. procs = [proc for proc in procs if proc.is_alive()]
  253. time.sleep(2)
  254. # for filename in files :
  255. # if filename.strip() == '':
  256. # continue
  257. # # content,logs = get_content(filename,CONFIG,CONFIG['SECTION'])
  258. # #
  259. # try:
  260. # content,logs = parse(filename = filename,type=SYS_ARGS['parse'])
  261. # if content :
  262. # writer.write(content)
  263. # if logs :
  264. # [logger.write(dict(_row,**{"parse":SYS_ARGS['parse']})) for _row in logs]
  265. # else:
  266. # logger.write({"parse":SYS_ARGS['parse'],"name":filename,"completed":True,"rows":len(content)})
  267. # except Exception as e:
  268. # logger.write({"parse":SYS_ARGS['parse'],"filename":filename,"completed":False,"rows":-1,"msg":e.args[0]})
  269. # # print ([filename,len(content)])
  270. # #
  271. # # @TODO: forward this data to the writer and log engine
  272. # #
  273. pass
  274. elif 'analytics' in SYS_ARGS :
  275. PORT = int(SYS_ARGS['port']) if 'port' in SYS_ARGS else 5500
  276. DEBUG= int(SYS_ARGS['debug']) if 'debug' in SYS_ARGS else 0
  277. SYS_ARGS['context'] = SYS_ARGS['context'] if 'context' in SYS_ARGS else ''
  278. #
  279. #
  280. # PATH= SYS_ARGS['config'] if 'config' in SYS_ARGS else os.sep.join([os.environ['HOME'],'.healthcareio','config.json'])
  281. e = analytics.engine(os.sep.join([PATH,'config.json'])) #--@TODO: make the configuration file globally accessible
  282. e.apply(type='claims',serialize=True)
  283. SYS_ARGS['engine'] = e
  284. pointer = lambda : server.app.run(host='0.0.0.0',port=PORT,debug=DEBUG,threaded=False)
  285. pthread = Process(target=pointer,args=())
  286. pthread.start()
  287. elif 'export' in SYS_ARGS:
  288. #
  289. # this function is designed to export the data to csv
  290. #
  291. format = SYS_ARGS['format'] if 'format' in SYS_ARGS else 'csv'
  292. format = format.lower()
  293. if set([format]) not in ['xls','csv'] :
  294. format = 'csv'
  295. else:
  296. msg = """
  297. CLI Usage
  298. healthcare-io.py --register <email> --store <sqlite|mongo>
  299. healthcare-io.py --parse claims --folder <path> [--batch <value>]
  300. healthcare-io.py --parse remits --folder <path> [--batch <value>]
  301. parameters :
  302. --<[signup|init]> signup or get a configuration file from a parsing server
  303. --store data store mongo or sqlite
  304. """
  305. print(msg)
  306. pass
  307. # """
  308. # The program was called from the command line thus we are expecting
  309. # parse in [claims,remits]
  310. # config os.sep.path.exists(path)
  311. # folder os.sep.path.exists(path)
  312. # store store ()
  313. # """
  314. # p = len( set(['store','config','folder']) & set(SYS_ARGS.keys())) == 3 and ('db' in SYS_ARGS or 'path' in SYS_ARGS)
  315. # TYPE = {
  316. # 'mongo':'mongo.MongoWriter',
  317. # 'couch':'couch.CouchWriter',
  318. # 'disk':'disk.DiskWriter'
  319. # }
  320. # INFO = {
  321. # '837':{'scope':'claims','section':'HL'},
  322. # '835':{'scope':'remits','section':'CLP'}
  323. # }
  324. # if p :
  325. # args = {}
  326. # scope = SYS_ARGS['config'][:-5].split(os.sep)[-1]
  327. # CONTEXT = INFO[scope]['scope']
  328. # #
  329. # # @NOTE:
  330. # # improve how database and data stores are handled.
  331. # if SYS_ARGS['store'] == 'couch' :
  332. # args = {'url': SYS_ARGS['url'] if 'url' in SYS_ARGS else 'http://localhost:5984'}
  333. # args['dbname'] = SYS_ARGS['db']
  334. # elif SYS_ARGS ['store'] == 'mongo':
  335. # args = {'host':SYS_ARGS['host']if 'host' in SYS_ARGS else 'localhost:27017'}
  336. # if SYS_ARGS['store'] in ['mongo','couch']:
  337. # args['dbname'] = SYS_ARGS['db'] if 'db' in SYS_ARGS else 'claims_outcomes'
  338. # args['doc'] = CONTEXT
  339. # TYPE = TYPE[SYS_ARGS['store']]
  340. # writer = factory.instance(type=TYPE,args=args)
  341. # if SYS_ARGS['store'] == 'disk':
  342. # writer.init(path = 'output-claims.json')
  343. # logger = factory.instance(type=TYPE,args= dict(args,**{"doc":"logs"}))
  344. # files = os.listdir(SYS_ARGS['folder'])
  345. # CONFIG = json.loads(open(SYS_ARGS['config']).read())
  346. # SECTION = INFO[scope]['section']
  347. # for file in files :
  348. # if 'limit' in SYS_ARGS and files.index(file) == int(SYS_ARGS['limit']) :
  349. # break
  350. # else:
  351. # filename = os.sep.join([SYS_ARGS['folder'],file])
  352. # try:
  353. # content,logs = get_content(filename,CONFIG,SECTION)
  354. # except Exception as e:
  355. # if sys.version_info[0] > 2 :
  356. # logs = [{"filename":filename,"msg":e.args[0]}]
  357. # else:
  358. # logs = [{"filename":filename,"msg":e.message}]
  359. # content = None
  360. # if content :
  361. # writer.write(content)
  362. # if logs:
  363. # logger.write(logs)
  364. # pass
  365. # else:
  366. # print (__doc__)