"""fda_dolma.py OUT.json.gz ZIP... (10-27) - openFDA drug labels (public domain; research/health.md #5) -> dolma json.gz for dolma_chunk.py doc. Human prescription labels only, one per (generic name, brand, route), the newest effective_time wins (many generics repeat the same text). One doc per label section, titled "FDA label: Brand (generic) - Section" so the model can see which drug a number belongs to (the near-miss problem). Health: local only.""" import sys, json, gzip, zipfile, os dst, zips = sys.argv[1], sys.argv[2:] SEC = ["boxed_warning", "indications_and_usage", "dosage_and_administration", "dosage_forms_and_strengths", "contraindications", "warnings_and_cautions", "warnings", "adverse_reactions", "drug_interactions", "use_in_specific_populations", "pregnancy", "mechanism_of_action", "pharmacodynamics", "pharmacokinetics", "clinical_studies", "description", "how_supplied", "overdosage"] best = {} for z in zips: with zipfile.ZipFile(z) as zf: for name in zf.namelist(): for r in json.load(zf.open(name))["results"]: o = r.get("openfda") or {} if "HUMAN PRESCRIPTION DRUG" not in (o.get("product_type") or []): continue g = ", ".join(o.get("generic_name") or [])[:120]; b = ", ".join(o.get("brand_name") or [])[:80] key = (g.lower(), b.lower(), ",".join(o.get("route") or []).lower()) t = r.get("effective_time") or "" if key not in best or t > best[key][0]: best[key] = (t, {s: " ".join(r[s]) for s in SEC if r.get(s)}, b, g, ", ".join(o.get("manufacturer_name") or [])[:60]) print(z, "labels kept so far", len(best), flush=True) n = 0 with gzip.open(dst + ".tmp", "wt") as f: for i, (t, secs, b, g, m) in enumerate(best.values()): name = f"{b} ({g})" if b and g and b.lower() != g.lower() else (b or g) for s, txt in secs.items(): if len(txt.split()) >= 15: f.write(json.dumps({"id": f"fda-{i}-{s}", "text": txt, "metadata": {"title": f"FDA label: {name} [{t[:4]}] - {s.replace('_', ' ')}"[:160]}}) + "\n"); n += 1 os.replace(dst + ".tmp", dst) print("labels", len(best), "section docs", n, flush=True)