File size: 16,717 Bytes
1d09b8f e9170b7 1d09b8f 005ba6a e9170b7 005ba6a e9170b7 005ba6a 1d09b8f 005ba6a 1d09b8f 005ba6a 1d09b8f 005ba6a 1d09b8f 005ba6a 1d09b8f 005ba6a 1d09b8f 005ba6a 1d09b8f 005ba6a 1d09b8f e9170b7 1d09b8f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
import os
import json
import uuid
import math
import re
import shutil
import asyncio
import pdfplumber
from typing import List, Dict, Optional, Any
from fastapi import FastAPI, HTTPException, UploadFile, File, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(BASE_DIR, 'data', 'uploaded')
MASTER_INDEX_PATH = os.path.join(BASE_DIR, 'data', 'master_index.json')
os.makedirs(DATA_DIR, exist_ok=True)
_MASTER_INDEX_CACHE = {}
# --- CATEGORY DEFINITIONS ---
# Ordered by specificity. "Whole word" matching will apply to these keywords.
CATEGORY_DEFINITIONS = {
"Pharmaceuticals & Biologics": [
"tablet", "tab", "capsule", "cap", "syrup", "suspension", "susp", "injection", "inj", "vial", "ampoule", "amp",
"drops", "gtt", "inhaler", "vaccine", "insulin", "dose", "drug", "medication", "ointment", "cream", "gel",
"lotion", "suppository", "supp", "antibiotic", "antiviral", "analgesic", "anesthetic", "hormone", "steroid",
"vitamin", "mineral", "supplement", "lozenge", "patch", "solution", "powder for suspension", "elixir", "serum",
"antitoxin"
],
"Surgical Products": [
"scalpel", "forceps", "retractor", "clamp", "suture", "stapler", "surgical mesh", "hemostatic", "sealant",
"surgical drape", "surgical gown", "laparoscopic", "robotic surgery", "electrosurgical", "surgical laser",
"surgical blade", "trocar", "surgical clip", "surgical scissor", "needle holder"
],
"Orthopedic & Spine": [
"orthopedic", "spine", "joint replacement", "trauma fixation", "bone plate", "bone screw", "intramedullary rod",
"bone nail", "spinal implant", "spinal fusion", "bone graft", "orthopedic brace", "cast", "arthroscopy",
"fixator", "prosthesis", "bone drill", "bone saw"
],
"Cardiovascular Products": [
"cardiac stent", "pacemaker", "defibrillator", "icd", "heart valve", "vascular graft", "cardiac catheter",
"guidewire", "cardiac balloon", "ablation", "coronary", "angioplasty", "introducer sheath"
],
"Medical Imaging Equipment": [
"mri", "ct scanner", "x-ray", "ultrasound", "mammography", "fluoroscopy", "pet scanner", "c-arm",
"medical imaging", "transducer", "x-ray film", "contrast media", "lead apron"
],
"Diagnostic Products": [
"diagnostic", "test kit", "glucose test", "reagent", "immunoassay", "chemistry analyzer", "hematology",
"microbiology", "culture media", "pregnancy test", "covid", "rapid test", "urinalysis", "penlight",
"specula", "otoscope", "ophthalmoscope", "lancet", "glucometer strips", "test strip"
],
"Patient Monitoring Equipment": [
"vital signs", "ecg", "ekg", "pulse oximeter", "blood pressure monitor", "sphygmomanometer",
"medical thermometer", "capnography", "fetal monitor", "telemetry", "spo2 sensor", "bp cuff", "temperature probe"
],
"Respiratory & Anesthesia": [
"ventilator", "anesthesia machine", "oxygen concentrator", "nebulizer", "cpap", "bipap", "respiratory",
"endotracheal", "tracheostomy", "spirometer", "oxygen mask", "breathing circuit", "nasal cannula",
"resuscitator", "laryngoscope"
],
"Infusion & Vascular Access": [
"infusion pump", "syringe pump", "iv set", "iv catheter", "venous", "picc", "iv port", "dialysis catheter",
"administration set", "extension set", "stopcock", "giving set", "saline", "dextrose", "ringer",
"sodium chloride", "water for injection"
],
"Wound Care & Tissue Management": [
"wound dressing", "bandage", "gauze", "medical tape", "plaster", "adhesive", "wound foam", "alginate",
"hydrocolloid", "compression bandage", "ostomy", "skin substitute", "negative pressure"
],
"Dialysis & Renal Care": [
"hemodialysis", "peritoneal", "dialyzer", "blood line", "fistula needle", "dialysis concentrate", "bicarbonate"
],
"Ophthalmic Products": [
"intraocular", "intraocular lens", "phaco", "vitrectomy", "lasik", "contact lens", "viscoelastic",
"ophthalmic solution", "eye drops"
],
"Dental Products": [
"dental implant", "orthodontic", "dental bracket", "dental wire", "dental drill", "dental handpiece",
"dental cement", "dental composite", "amalgam", "impression material", "teeth whitening", "dental chair"
],
"Neurology & Neurosurgery": [
"neurostimulation", "spinal cord stimulator", "neuro coil", "flow diverter", "cranial", "shunt",
"neuro electrode", "eeg", "emg"
],
"Laboratory Equipment & Supplies": [
"microscope", "lab centrifuge", "incubator", "autoclave", "pipette", "glassware", "test tube", "petri dish",
"flask", "beaker", "microscope slide", "cover glass", "fume hood", "biosafety cabinet"
],
"Personal Protective Equipment (PPE)": [
"ppe", "n95", "face shield", "safety eyewear", "goggles", "protective apron", "shoe cover", "head cover",
"coverall", "isolation gown", "hazmat", "surgical mask"
],
"Sterilization & Disinfection": [
"sterilization", "disinfectant", "antiseptic", "povidone", "iodine", "chlorhexidine", "alcohol swab",
"hand sanitizer", "medical soap", "enzymatic cleaner", "detergent", "washer disinfector", "sterilizer",
"sterilization indicator"
],
"Hospital Furniture & Equipment": [
"hospital bed", "examination table", "stretcher", "medical trolley", "medical cart", "medical cabinet",
"bedside locker", "overbed table", "iv pole", "wheelchair"
],
"Rehabilitation & Physical Therapy": [
"rehabilitation", "physiotherapy", "walker", "walking cane", "crutch", "exercise band", "traction",
"electrotherapy", "massage table", "orthosis"
],
"Home Healthcare Products": [
"home care", "blood glucose meter", "hearing aid", "mobility aid", "bathroom safety", "commode"
],
"Emergency & Trauma Care": [
"emergency kit", "trauma kit", "first aid", "aed", "defibrillator", "manual resuscitator", "suction unit",
"immobilizer", "cervical collar", "splint", "tourniquet", "crash cart"
],
"Maternal & Neonatal Care": [
"maternal", "neonatal", "infant incubator", "infant warmer", "phototherapy", "breast pump", "obstetric",
"birthing bed", "fetal doppler", "umbilical"
],
"Urology Products": [
"urology", "foley catheter", "urine bag", "urinary drainage", "ureteral stent", "stone basket"
],
"Gastroenterology & Endoscopy": [
"endoscope", "gastroscope", "colonoscope", "biopsy forceps", "polypectomy snare", "gastric balloon", "ercp"
],
"Oncology Products": [
"oncology", "chemotherapy", "radiotherapy", "brachytherapy", "port-a-cath", "cancer diagnostic"
],
"Pain Management": [
"pain management", "pca pump", "epidural", "nerve block", "tens unit"
],
"Sleep Medicine": [
"sleep apnea", "cpap mask", "bipap mask", "sleep tubing", "polysomnography"
],
"Telemedicine & Digital Health": [
"telemedicine", "telehealth", "remote monitor", "medical software", "health app"
],
"Blood Management": [
"blood bag", "blood transfusion", "blood bank", "blood warmer", "apheresis"
],
"Mortuary & Pathology": [
"mortuary", "autopsy", "body bag", "morgue fridge", "dissection table", "microtome", "tissue processor"
],
"Environmental Control": [
"medical gas", "medical vacuum", "medical air plant", "gas manifold", "gas outlet", "gas alarm"
],
"Mobility & Accessibility": [
"patient lift", "patient hoist", "wheelchair ramp", "stair lift", "transfer board"
],
"Bariatric Products": [
"bariatric bed", "bariatric wheelchair", "heavy duty scale"
],
"Medical Textiles": [
"hospital linen", "bed sheet", "pillow case", "medical blanket", "towel", "privacy curtain", "medical uniform",
"scrub suit", "lab coat"
],
"Infection Control Products": [
"waste bin", "sharps container", "biohazard bag", "spill kit", "air purifier"
],
"Medical Gases & Cryogenics": [
"gas cylinder", "oxygen regulator", "flowmeter", "liquid oxygen", "nitrogen tank"
],
"Nutrition & Feeding": [
"enteral feeding", "clinical nutrition", "nasogastric tube", "feeding pump", "feeding set", "peg tube"
],
"Specimen Collection & Transport": [
"specimen container", "sample collection", "transport media", "transport swab", "urine container",
"stool container", "cool box", "transport bag"
],
"Medical Software & IT": [
"emr", "ehr", "pacs", "ris", "lis", "his", "hospital information system"
],
"Aesthetics & Dermatology": [
"dermatology", "aesthetic laser", "ipl", "dermal filler", "botulinum", "botox", "chemical peel",
"microdermabrasion"
],
# Catch-all for basic items not caught above
"Medical Supplies & Consumables": [
"syringe", "needle", "glove", "examination glove", "disposable", "consumable", "cotton wool", "alcohol prep",
"urinal", "bedpan", "underpad", "tongue depressor", "applicator", "lubricant jelly", "cannula"
# Note: Cannula is here as fallback if not specific nasal/iv
]
}
def load_master_index():
global _MASTER_INDEX_CACHE
if _MASTER_INDEX_CACHE: return _MASTER_INDEX_CACHE
if os.path.exists(MASTER_INDEX_PATH):
with open(MASTER_INDEX_PATH, 'r', encoding='utf-8') as f:
_MASTER_INDEX_CACHE = json.load(f)
return _MASTER_INDEX_CACHE
def clean_text(text: Optional[str]) -> str:
return text.replace('\n', ' ').strip() if text else ""
def is_garbage_row(row_text: str) -> bool:
blacklist = [
"click or tap",
"enter text",
"rfq reference",
"signature",
"date:",
"authorized by",
"page ",
"payment terms"
]
t = row_text.lower()
return any(bad in t for bad in blacklist)
def determine_item_type(description: str, form: str) -> str:
"""
Determines the category of the item based on its description and form/unit.
Uses regex for whole-word matching to prevent substring errors (e.g. 'fusion' in 'infusion').
"""
text = (description + " " + form).lower()
for category, keywords in CATEGORY_DEFINITIONS.items():
for k in keywords:
# \b matches word boundaries.
# This ensures "fusion" matches "spinal fusion" but NOT "infusion".
# It ensures "coat" matches "lab coat" but NOT "coated".
# We escape the keyword to handle any special characters safely.
pattern = r'\b' + re.escape(k) + r'\b'
if re.search(pattern, text):
return category
# Fallback default
return 'Medical Supplies & Consumables'
async def delete_file_safety_net(file_path: str, delay: int = 600):
await asyncio.sleep(delay)
try:
if os.path.exists(file_path):
os.remove(file_path)
except Exception:
pass
def parse_pdf_file(file_path: str) -> List[Dict[str, Any]]:
extracted_items = []
with pdfplumber.open(file_path) as pdf:
for page in pdf.pages:
tables = page.extract_tables()
for table in tables:
for row in table:
cleaned_row = [clean_text(cell) for cell in row if cell is not None and clean_text(cell) != ""]
if not cleaned_row: continue
row_text = " ".join(cleaned_row)
if is_garbage_row(row_text): continue
if "description" in row_text.lower() and "qty" in row_text.lower(): continue
try:
qty = 1
qty_idx = -1
# Attempt to find the Quantity column (usually a number towards the end)
for i in range(len(cleaned_row) - 1, -1, -1):
val = cleaned_row[i].replace(',', '').replace('.', '')
if val.isdigit() and int(val) < 1000000:
qty = int(val)
qty_idx = i
break
if qty_idx == -1: continue
# Attempt to find Description
desc_idx = 0
# If first col is just a number (Item No), skip it
if re.match(r'^\d+\.?$', cleaned_row[0]) and len(cleaned_row) > 1:
desc_idx = 1
description = cleaned_row[desc_idx]
if re.match(r'^\d+$', description): continue
if is_garbage_row(description): continue
# Attempt to find Unit/Form
unit = "Unit"
if qty_idx > 0 and qty_idx > desc_idx:
# Usually the column before Qty is Unit
potential_unit = cleaned_row[qty_idx - 1]
if len(potential_unit) < 20 and potential_unit != description:
unit = potential_unit
# Determine Category
item_type = determine_item_type(description, unit)
extracted_items.append({
"inn_name": description,
"quantity": qty,
"form": unit,
"dosage": "",
"type": item_type
})
except Exception:
continue
return extracted_items
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.on_event("startup")
def startup():
load_master_index()
@app.post("/api/upload")
async def upload_document(background_tasks: BackgroundTasks, file: UploadFile = File(...)):
doc_id = str(uuid.uuid4())
filename = f"{doc_id}.pdf"
file_path = os.path.join(DATA_DIR, filename)
with open(file_path, "wb") as buffer:
shutil.copyfileobj(file.file, buffer)
background_tasks.add_task(delete_file_safety_net, file_path, 600)
return {"document_id": doc_id, "message": "Upload successful"}
@app.post("/api/parse/{document_id}")
async def parse_document(document_id: str):
file_path = os.path.join(DATA_DIR, f"{document_id}.pdf")
if not os.path.exists(file_path):
raise HTTPException(status_code=404, detail="File not found")
try:
items = parse_pdf_file(file_path)
if os.path.exists(file_path):
os.remove(file_path)
return {
"document_id": document_id,
"data": { "line_items": items }
}
except Exception as e:
if os.path.exists(file_path):
os.remove(file_path)
raise HTTPException(status_code=500, detail="Parsing failed")
class MatchRequest(BaseModel):
items: List[Dict[str, Any]]
preferences: List[str] = []
@app.post("/api/match-all")
async def match_all(req: MatchRequest):
index = load_master_index()
vendors = index.get('vendors', [])
results = []
for item in req.items:
name = item.get('inn_name') or 'Unknown'
qty = int(item.get('quantity', 1))
matches = []
for v in vendors:
# Simplified matching logic for demonstration
matches.append({
'vendor_id': v.get('vendor_id'),
'name': v.get('legal_name'),
'country': (v.get('countries_served') or ['Unknown'])[0],
'landedCost': v.get('landedCost', 10),
'deliveryDays': v.get('deliveryDays', 5),
'availableQty': v.get('availableQty', 1000),
'qualityScore': v.get('confidence_score', 80) / 10.0,
'reliabilityScore': 5,
'score': 9.5
})
results.append({
"medicine": name,
"quantity": qty,
"top_vendor": matches[0] if matches else None,
"other_vendors": matches[1:5] if len(matches) > 1 else []
})
return {"matches": results}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=5001) |