healthcare-io.py 17 KB

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