Example #1
0
def add_prices(csvtext, drug_dict):
    # adds prices from a CSV file (the date is the str csvtext arg) to each drug in a given drug dictionary.
    # for drugs in the dictionary but not in the file, the function adds None as the price.
    # this function passes on drugs in the CSV but not in the drug_dict.
    date = csvtext[-8:]
    count = 1
    headers = which_headers(date)
    drug_list = [drug for drug in drug_dict]
    with open(csvtext+".csv", "r") as drugcsv:
        drugreader = csv.reader(drugcsv)
        for line in drugreader:
            if count < 5:
                pass
            else:
                drug = {}
                for i in range(len(headers)):
                    drug[headers[i]] = line[i]
                price = drug["Price"]
                if drug["NDC"] in drug_dict:
                    Drug.add_price(drug_dict[drug["NDC"]], date, price)
                    drug_list.remove(drug["NDC"])
                else:
                    pass
            count += 1
        drugcsv.close()
    for drug in drug_list:
        Drug.add_price(drug_dict[drug], date, None)
    return drug_dict
Example #2
0
def builder(csvtext):
    # The function that takes a given CSV filename/date and creates a dictionary of drugs.
    # Their key is the drug NDC, and their value is the Drug object.

    date = csvtext[-8:]
    drug_dict = {}
    count = 1
    headers = which_headers(date)
    with open(csvtext+".csv", "r") as drugcsv:
        drugreader = csv.reader(drugcsv)
        for line in drugreader:
            if count < 5:
                pass
            else:
                drug = {}
                for i in range(len(headers)):
                    drug[headers[i]] = line[i]
                price = drug["Price"]
                this_drug = Drug(drug["Name"], drug["NDC"], drug["Pricing Unit"],
                                    drug["OTC or Not"], drug["Brand or Generic"], "NADAC")
                Drug.add_price(this_drug, date, price)
                drug_dict[drug["NDC"]] = this_drug
            count += 1
        drugcsv.close()
    return drug_dict
Example #3
0
def mine_drug_register():
    drugs = []
    print("Fetching drug data...")
    response = requests.get(DRUG_REGISTER_URL)
    print("Done.")
    if not response.ok:
        print("Failed to fetch data.")
        return

    print("Setting up data...")
    drug_register_html = response.content
    drug_register = BeautifulSoup(drug_register_html, 'html.parser')

    for line_break in drug_register.find_all('br'):
        line_break.extract()

    data_table = drug_register.find(id="tablepress-42").tbody
    rows = data_table.find_all('tr')
    print("Done.")
    print("Parsing...")
    for row in rows:
        data = [str(item.string) for item in row.find_all('td')]
        drug = Drug(*data)
        drugs.append(drug)
    print("Done.")
    print("Writing to file...")

    drug_data = '\n'.join([drug.to_csv() for drug in drugs])
    headers = "identifier, nda_reg_number, license_holder, local_technical_rep, name_of_drug, manufacturer, country_of_manufacture, dosage_form, pack_size"
    drug_data = headers + "\n" + drug_data
    with open("data/drugs.csv", 'w') as file:
        file.write(drug_data)
    print("Done.")
    print("Complete!")
    print("\n")
Example #4
0
def update(csvtext, drug_dict):

    # accesses a one-date CSV file (date given as str csvtext) and adds prices for drugs in the given drug dictionary.
    # if a drug is not in the drug dict, this function adds the drug and its info to the dictionary.

    date = csvtext[-8:]
    count = 1
    headers = which_headers(date)
    with open(csvtext+".csv", "r") as drugcsv:
        drugreader = csv.reader(drugcsv)
        for line in drugreader:
            if count < 5:
                pass
            else:
                drug = {}
                for i in range(len(headers)):
                    drug[headers[i]] = line[i]
                price = drug["Price"]
                if drug["NDC"] in drug_dict:
                    Drug.add_price(drug_dict[drug["NDC"]], date, price)
                else:
                    if int(date) < 20130215:
                        drug["Pricing Unit"] = "Unknown"
                        drug["Brand or Generic"] = "Unknown"
                    this_drug = Drug(drug["Name"], drug["NDC"], drug["Pricing Unit"],
                                     drug["OTC or Not"], drug["Brand or Generic"], "NADAC")
                    Drug.add_price(this_drug, date, price)
                    drug_dict[drug["NDC"]] = this_drug
            count += 1
        drugcsv.close()
    return drug_dict
Example #5
0
def get_desired_data(filename):
    with open(filename, encoding="utf-8") as f:
        parser = BeautifulSoup(f.read(), "html.parser")

    drug = parser.find("drug")
    if drug:
        id = drug.find("drugbank-id")

        # Gradaully setting Drug db object...
        new_drug = Drug(id=(id.string or ""))
        
        name = drug.find("name")
        # setting up drug db object
        new_drug.name = name.string or ""

        groups_wrapper = drug.find("groups")
        if groups_wrapper is not None:
            groups = groups_wrapper.find_all("group")
            gp_str = ""
            for group in groups:
                gp_str += (group.string or "")
                # setting up drug db object
                new_drug.group = gp_str
        
        toxicity = drug.find("toxicity")
        if toxicity:
            # setting up drug db object
            new_drug.toxicity = (toxicity.string or "")
            db.session.add(new_drug)
        
        external_identifiers_wr = drug.find("external-identifiers")
        if external_identifiers_wr:
            external_identifiers = external_identifiers_wr.find_all("external-identifier")
            for ext_id in external_identifiers:
                resource = (ext_id.find("resource").string or "")
                identifier = (ext_id.find("identifier").string or "")
                # setting up ExternalIdentifier db object
                new_external_identifier = ExternalIdentifier(resource=resource, name=identifier, drug_id=new_drug.id)
                db.session.add(new_external_identifier)

        food_interactions_wrapper = drug.find("food-interactions")
        if food_interactions_wrapper:
            food_interactions = food_interactions_wrapper.find_all("food-interaction")
            for food_int in food_interactions:
                food_interaction_description = (food_int.string or "")
                # Setting up FoodInteraction db object
                new_food_interaction = FoodInteraction(drug_id=new_drug.id, description=food_interaction_description)
                db.session.add(new_food_interaction)
        
        # Commit all changes to DB!
        db.session.commit()
Example #6
0
def create_network():
    p = create_test_protein()
    cancer = Cancer(name='Ovarian', code='OV')

    known_interactor_of_x = create_test_kinase('Kinase Y', 'NM_0009')

    kinase_mutation = Mutation(position=1,
                               alt='T',
                               meta_MC3=[MC3Mutation(cancer=cancer)])

    known_interactor_of_x.protein.mutations = [kinase_mutation]

    drug = Drug(
        name='Drug targeting ' + known_interactor_of_x.name,
        drug_bank_id='DB01',
        target_genes=[known_interactor_of_x.protein.gene],
        # by default only approved drugs are shown
        groups={DrugGroup(name='approved')})

    group = KinaseGroup(name='Group of kinases', )
    s = Site(position=1,
             type='phosphorylation',
             residue='T',
             kinases=[known_interactor_of_x],
             kinase_groups=[group])
    s2 = Site(position=2,
              type='phosphorylation',
              residue='R',
              kinase_groups=[group])
    p.sites = [s, s2]

    predicted_interactor = create_test_kinase('Kinase Z', 'NM_0002')

    protein_mutation = Mutation(position=2,
                                alt='T',
                                meta_MC3=[MC3Mutation(cancer=cancer)],
                                meta_MIMP=[
                                    MIMPMutation(
                                        pwm=known_interactor_of_x.name,
                                        effect='loss',
                                        site=s,
                                        probability=0.1,
                                        position_in_motif=1),
                                    MIMPMutation(pwm=predicted_interactor.name,
                                                 effect='gain',
                                                 site=s,
                                                 probability=0.1,
                                                 position_in_motif=1)
                                ])

    p.mutations = [protein_mutation]
    db.session.add_all([p, drug, predicted_interactor])
    db.session.commit()

    # a new cancer was added, reload is necessary (this should not happen during normal app usage)
    from website.views.filters import cached_queries
    cached_queries.reload()
Example #7
0
def addStock(drugNum):
    # 判断用户是否登录
    user_id = session.get('user_id')
    if user_id:
        user = User.query.filter(User.id == user_id).first()
        if user:
            # 判断是否是POST
            if request.method == 'GET':
                drug = Drug.query.filter(Drug.num == drugNum).first()
                return render_template('addStock.html', drug=drug)
            else:
                num = request.form.get('num')
                name = request.form.get('name')
                type = request.form.get('type')
                count = request.form.get('count')
                price = request.form.get('price')
                desc = request.form.get('desc')

                try:
                    count = int(count)
                except Exception:
                    raise ValueError('count value is error!')

                # 查找数据库类别表
                drugType = DrugType.query.filter(DrugType.name == type).first()
                if drugType:
                    drugTypeId = drugType.id
                    for index in range(0, count):
                        drug = Drug(num=num,
                                    name=name,
                                    desc=desc,
                                    stockPrice=price,
                                    drugTypeId=drugTypeId)
                        drug.drugType = drugType
                        db.session.add(drug)
                        db.session.flush()  # 主要是这里,写入数据库,但是不提交
                db.session.commit()

                return redirect(url_for('addStockHome'))
    return redirect(url_for('login'))
Example #8
0
def addDrug():
    # 判断用户是否登录
    user_id = session.get('user_id')
    if user_id:
        user = User.query.filter(User.id == user_id).first()
        if user:
            if request.method == 'GET':
                return render_template('addDrug.html')
            else:
                # 当前时间
                nowDate = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                num = request.form.get('num')
                name = request.form.get('name')
                type = request.form.get('type')
                count = request.form.get('count')
                price = request.form.get('price')
                desc = request.form.get('desc')

                try:
                    count = int(count)
                except Exception:
                    raise ValueError('count value is error!')

                # 查找数据库类别表
                drugType = DrugType.query.filter(DrugType.name == type).first()
                if drugType:
                    drugTypeId = drugType.id
                    for index in range(0, count):
                        drug = Drug(num=num,
                                    name=name,
                                    desc=desc,
                                    stockDate=nowDate,
                                    stockPrice=price,
                                    drugTypeId=drugTypeId)
                        drug.drugType = drugType
                        db.session.add(drug)
                        db.session.flush()  # 主要是这里,写入数据库,但是不提交
                else:
                    drugType = DrugType(name=type)
                    db.session.add(drugType)
                    db.session.commit()
                    drugTypeId = drugType.id
                    for index in range(0, count):
                        drug = Drug(num=num,
                                    name=name,
                                    desc=desc,
                                    stockDate=nowDate,
                                    stockPrice=price,
                                    drugTypeId=drugTypeId)
                        drug.drugType = drugType
                        db.session.add(drug)
                        db.session.flush()  # 主要是这里,写入数据库,但是不提交

                db.session.commit()
                return redirect(url_for('home'))
    return redirect(url_for('login'))
Example #9
0
def create_tables():
    db.create_all()
    for a in drug_classes.keys():
        new_drug_class = Drugclass(name=a,
                                   beers_criteria=drug_classes[a][0],
                                   stopp_start_criteria=drug_classes[a][1])
        try:
            db.session.add(new_drug_class)
            db.session.commit()
        except:
            pass
    for a in medications.keys():
        new_med = Drug(name=a,
                       beers_criteria=medications[a][0],
                       stopp_start_criteria=medications[a][1],
                       drug_class_id=medications[a][2])
        try:
            db.session.add(new_med)
            db.session.commit()
        except:
            pass
Example #10
0
def add_FDA_info(drug_dict):

    # this function supplies drug and vendor names via NDCs from the FDA's official database.
    # sadly the FDA and NADAC have a slightly different format for NDCs, so it's not perfect.
    # It is very unlikely to assign an incorrect NDC -- rather, it will pass on drugs it cannot find a match for.

    name_file = "FDA-20160118.csv"
    headers = ["PRODUCTID", "PRODUCTNDC", "PRODUCTTYPENAME", "PROPRIETARYNAME", "PROPRIETARYNAMESUFFIX",
               "NONPROPRIETARYNAME", "DOSAGEFORMNAME", "ROUTENAME", "STARTMARKETINGDATE", "ENDMARKETINGDATE",
               "MARKETINGCATEGORYNAME", "APPLICATIONNUMBER", "LABELERNAME", "SUBSTANCENAME",
               "ACTIVE_NUMERATOR_STRENGTH", "ACTIVE_INGRED_UNIT", "PHARM_CLASSES", "DEASCHEDULE"]
    count = 1
    current_list = [key for key in drug_dict]
    with open(name_file, "r") as namecsv:
        csvreader = csv.reader(namecsv)
        for line in csvreader:
            if count == 1:
                pass
            else:
                drug = {}
                for i in range(len(headers)):
                    if headers [i] == "PRODUCTNDC":
                        drug["NDC"] = line[i].translate(None,"-")
                        templist = line[i].split("-")
                        templist[0] = templist[0] + "0"
                        drug["NDC2"] = "".join(templist)
                    else:
                        drug[headers[i]] = line[i]
                findings = [item for item in current_list if ( drug["NDC"] in item ) or ( drug["NDC2"] in item )]
                if len(findings) == 1:
                    this_drug = drug_dict[findings[0]]
                    Drug.add_vendor(this_drug, drug["LABELERNAME"])
                    Drug.add_sci_name(this_drug, drug["NONPROPRIETARYNAME"])
                    Drug.add_desc(this_drug, drug["PHARM_CLASSES"])
                    current_list.remove(findings[0])
                    print "%i drugs left to ID..." % len(current_list)
                elif len(findings) == 0:
                    pass
                else:
                    findings_as_drugs = [drug_dict[key] for key in findings] #converts list of keys into list of Drugs
                    findings = multiple_results(drug, findings_as_drugs) #list of Drugs
                    for finding in findings: #finding is a Drug
                        Drug.add_vendor(finding, drug["LABELERNAME"])
                        Drug.add_sci_name(finding, drug["NONPROPRIETARYNAME"])
                        Drug.add_desc(finding, drug["PHARM_CLASSES"])
                        current_list.remove(finding.id)
                        print "%i drugs left to ID..." % len(current_list)

                            # BECAUSE THE FDA NDCS ARE ONLY EIGHT DIGITS LONG, THIS SEARCH OFTEN RETURNS 2+ RESULTS.
                            # TODO: write a function to check other info to figure out which is the correct one.
                            # or, worst-case scenario, prompt user to choose which looks right, maybe?
            count += 1

    return drug_dict
Example #11
0
def addDrug():
    # 判断用户是否登录
    user_id = session.get('user_id')
    if user_id:
        user = User.query.filter(User.id == user_id).first()
        if user:
            if request.method == 'GET':
                return render_template('addDrug.html')
            else:
                num = request.form.get('num')
                name = request.form.get('name')
                type = request.form.get('type')
                count = request.form.get('count')
                price = request.form.get('price')
                desc = request.form.get('desc')
                # 首先查找药品是否存在
                drug = Drug.query.filter(Drug.num == num).first()

                # 如果存在
                if drug:
                    # 库存量增加
                    Drug.query.filter(Drug.id == drug.id).update(
                        {Drug.count: int(drug.count) + int(count)})
                    stock = Stock(stockPrice=price,
                                  stockCount=count,
                                  stockMoney=int(count) * float(price),
                                  drugId=drug.id,
                                  userId=user_id)
                    db.session.add(stock)
                    db.session.commit()
                else:
                    # 判断类别
                    drugType = DrugType.query.filter(
                        DrugType.name == type).first()
                    # 存在
                    if drugType:
                        drug = Drug(num=num,
                                    name=name,
                                    count=count,
                                    price=price,
                                    desc=desc,
                                    drugTypeId=drugType.id)
                    else:
                        drugType = DrugType(name=type)
                        db.session.add(drugType)
                        db.session.commit()
                        drugType = DrugType.query.filter(
                            DrugType.name == type).first()
                        drug = Drug(num=num,
                                    name=name,
                                    count=count,
                                    price=price,
                                    desc=desc,
                                    drugTypeId=drugType.id)

                    db.session.add(drug)
                    db.session.commit()
                    drug = Drug.query.filter(Drug.num == num).first()
                    stock = Stock(stockPrice=price,
                                  stockCount=count,
                                  stockMoney=int(count) * float(price),
                                  drugId=drug.id,
                                  userId=user_id)
                    db.session.add(stock)
                    db.session.commit()
                return redirect(url_for('home'))

    return redirect(url_for('login'))
Example #12
0
from app import app
from models import db, Drug, Pharmacy

db.drop_all()
db.create_all()


def create_drugs():
    """Function for creating drugs for database"""
    drug_list = []
    for num in range(232):
        print(f'd{num} = (name="{TOP_200[num]}"", price={prices[num]})')


d0 = Drug(name="Lexapro", price=5)
d1 = Drug(name="Vicodin", price=65)
d2 = Drug(name="Prinivil", price=55)
d3 = Drug(name="Qbrelis", price=89)
d4 = Drug(name="Zocor", price=80)
d5 = Drug(name="Synthroid", price=7)
d6 = Drug(name="Amoxil", price=70)
d7 = Drug(name="Trimox", price=15)
d8 = Drug(name="Zithromax", price=69)
d9 = Drug(name="Microzide", price=8)
d10 = Drug(name="Aquazide", price=20)
d11 = Drug(name="Norvasc", price=66)
d12 = Drug(name="Xanax", price=43)
d13 = Drug(name="Glucophage", price=34)
d14 = Drug(name="Lipitor", price=22)
d15 = Drug(name="Prilosec", price=94)
d16 = Drug(name="Cipro", price=87)