#!/usr/bin/python import cgi import zipfile import re import urllib import urllib2 import sys # allow debugging? import cgitb; cgitb.enable() # edit # exact # entity="name" # (use "index" for all items) # whether this is for the smanohar.com website or homphysiology.org IS_SMANOHAR = False if IS_SMANOHAR: scriptPath = "http://www.smanohar.com/cgi-bin/MedicineReader.py" allow_edits = False else: scriptPath = 'http://www.homphysiology.org/cgi-bin/MedicineReader.py' editPath = 'http://www.homphysiology.org/cgi-bin/MedicineEdit.py' jsonQueryURL = 'http://www.homphysiology.org/cgi-bin/MedicineEntityNameJsonQuery.py' allow_edits = False # display options to edit the database dataFile = "data/submit_medicine.zip" introScreen="Sanjay Manohar's Medical Browser

Sanjay Manohar's Medical Browser

" # document header print "Content-type: text/html" print "Access-Control-Allow-Origin: *" print "" print "" print urllib.urlopen("http://www.smanohar.com/headcontents.php").read() print "" print "" if IS_SMANOHAR: # this is for the smanohar.com site! print "
" ''' search database and output any entities that match the query options: "entity": the text to match in the entity's name or synonyms "exact": match the entity's name exactly. Used internally to direct to other entities. ''' def printQueryForm(): print "
" % scriptPath print "Type item name: " print "
" return def printItemOnDefinitionString(edef): #prints entity html to stdout, given the definition text. defmatch=re.search("([^{]*)\{\s*" , edef, re.IGNORECASE) entityname=defmatch.group(1).strip() print "%s - Sanjay Manohar's Medical Browser" %entityname print "

%s
" %entityname print "external" % (urllib.quote(entityname)) print "

    " i=defmatch.end() # character index into definition while i

    %s

      " % secname tokens=[] while i=len(edef): break tokmatch=re.search("[^{},]+",edef[i:]) token=tokmatch.group(0).strip() tokens.append(token) i+=tokmatch.end() if (secname=="Synonyms") | (secname=="Description"): print "
    • %s
    • " % token else: if token[-1]=="%": # percentage indicates probability here. percentindex = token.rfind(" ") percent=token[percentindex+1:] # extract the percentage from the end token=token[:percentindex] # remove the percentage from token else: percent="" print "
    • %s%s
    • " % \ (scriptPath,urllib.quote(token),token, percent) if(edef[i]=='}'): i+=1 break print "
    " #end of section print "
" return def merge(d1,d2): '''merge two dictionaries''' merged={} merged.update(d1) merged.update(d2) return merged def dictToHiddenInputs(d): """ Convert a dict to HTML form tags """ return "".join(["" % (x,y) for (x,y) in d.items() ]) allSections = ["Causes", "Effects", "Parents", "Children", "Synonyms"] def printEditableItemOnDefinitionString(edef): #prints entity html to stdout, given the definition text. #but also allow editing defmatch=re.search("([^{]*)\{\s*" , edef, re.IGNORECASE) entityname=defmatch.group(1).strip() print "%s - Sanjay Manohar's Medical Browser" %entityname print "

%s
" %entityname print "external" % (urllib.quote(entityname)) print "

    " i=defmatch.end() # character index into definition secnamesFound = [] while i

    %s

      " % secname tokens=[] while i=len(edef): break tokmatch=re.search("[^{},]+",edef[i:]) token=tokmatch.group(0).strip() tokens.append(token) i+=tokmatch.end() edit_query = {"entity": entityname, "section": secname, "listitem": token} if secname=="Synonyms": if not allow_edits: print "
    • %s
    • " % token else: edit_query["command"] = "remove" print "
    • %s Remove" % (token, editPath, urllib.urlencode(edit_query)) elif secname=="Description": if not allow_edits: print "
    • %s
    • " % token else: edit_query["command"] = "edit" del edit_query["listitem"] # no need to send previous description data when editing submit_loc = editPath+("?%s"%(urllib.urlencode(edit_query))) print "
    • " % (submit_loc, token) else: if token[-1]=="%": # percentage indicates probability here. percentindex = token.rfind(" ") percent=token[percentindex+1:] # extract the percentage from the end token=token[:percentindex] # remove the percentage from token else: percent="" if not allow_edits: print "
    • %s%s
    • " % \ (scriptPath,urllib.quote(token),token, percent) else: print "
    • %s
      " % (scriptPath,urllib.quote(token),token) submit_prob = merge(edit_query, {"command": "updatepercent"}) # query to update probability print "
      %s%%
      " \ % (editPath, dictToHiddenInputs(submit_prob), percent) submit_remove = editPath+("?%s" % urllib.urlencode(merge(edit_query, {"command": "remove"}))) # query to update probability print "
      " % submit_remove print "
    • " if(edef[i]=='}'): i+=1 if allow_edits: # add an item to the list? if "listitem" in edit_query: del edit_query["listitem"] # leave entity and section in dictionary edit_query["command"]="add" # Add secname: [........] print "
      Add %s: %s
      " \ % (editPath, dictToHiddenInputs(edit_query), secname) break print "
    " #end of section if allow_edits: print "
    " for x in allSections: # addition to a new section? if x in secnamesFound: continue add_query = {"entity":entityname, "section":x, "command":"add"} cls = "" if (x is "Synonyms") else "autocomplete" # don't use autocomplete on synonyms # Add secname: [.......] print "
      Add %s:
      %s
    " \ % (x, editPath, dictToHiddenInputs(add_query), cls) print "
" return def itercat(*iterators): """Concatenate several iterators into one.""" for i in iterators: for x in i: yield x lucky = True # whether to have an I'm feeling lucky google link ## Main program params=cgi.FieldStorage() if(params.has_key("exact")): exact=True else: exact=False if params.has_key("edit"): allow_edits=True if params.has_key("entity") : entity=urllib.unquote(params["entity"].value) zf=zipfile.ZipFile(dataFile, "r") data=zf.read("Medical.txt") #look for definition of entity: # entity { s2 { s3,s4, s5 } s6 {s7,s8}} if entity.lower() == "index": # index: return a list of all entity names entitymatches = re.findall("^([^{}]*)\s*\{([^{}]*\{[^{}]*\})*\s*\}", data, re.MULTILINE ) print "

Medical Entity Index

    " entitymatches = sorted(entitymatches) for match in entitymatches: entityname = match[0] print "
  • %s
  • " % (scriptPath, urllib.quote(entityname), entityname) print "
" else: # create an interator that finds entities that match the query entityDataIter=re.finditer("^%s\s*\{([^{}]*\{[^{}]*\})*\s*\}" % entity, data, re.MULTILINE | re.IGNORECASE) if not exact: #items whose name contains the search string entityDataIter=itercat(entityDataIter, re.finditer("[^{},]*%s[^{},]*\s*\{([^{}]*\{[^{}]*\})*\s*\}" % entity, data, re.IGNORECASE | re.MULTILINE)) #items that are synonyms of the search string entityDataIter=itercat(entityDataIter, re.finditer("[^{},]*\{\s*Synonyms\s*\{[^{}]*%s[^{}]*\}([^{}]*\{[^{}]*\})*\s*\}" % entity, data, re.IGNORECASE | re.MULTILINE)) print findcount=0 foundEntities=[] for entityData in entityDataIter: # for each matching item, call printItemOnDefinitionString edef=entityData.group().strip() if not edef in foundEntities: foundEntities.append(edef) printEditableItemOnDefinitionString(edef) findcount+=1 if findcount==0: print introScreen print "No entity '%s' found" % entity #entity not found else: #no entity parameter print introScreen printQueryForm() print "
2006
" if IS_SMANOHAR: # this is for the smanohar.com site! print "
" # JQUERY - autocomplete the text boxes print '' print '' print '' print "" print ""