Download scripts/dev/seed_database.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 16.2 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/dev/seed_database.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/scripts/dev/seed_database.py
-
curl -L -o seed_database.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/scripts/dev/seed_database.py
16.2 kB
| #!/usr/bin/env python3 | |
| """ | |
| YAZ Care Platform - Database Seeder | |
| Seed database with sample data for development and testing | |
| """ | |
| import argparse | |
| import asyncio | |
| import sys | |
| from datetime import datetime, timedelta | |
| from pathlib import Path | |
| from typing import Any, Dict, List | |
| from uuid import uuid4 | |
| sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) | |
| class DatabaseSeeder: | |
| """Seed database with sample data""" | |
| def __init__(self, environment: str = "development"): | |
| self.environment = environment | |
| self.seeded_data: Dict[str, List[Any]] = {} | |
| async def seed_all(self): | |
| """Seed all data""" | |
| print(f"\n🌱 Seeding database for: {self.environment}") | |
| print(f"⏰ Started at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n") | |
| try: | |
| # Seed in dependency order | |
| await self.seed_tenants() | |
| await self.seed_users() | |
| await self.seed_patients() | |
| await self.seed_providers() | |
| await self.seed_encounters() | |
| await self.seed_surgeries() | |
| await self.seed_lab_orders() | |
| await self.seed_prescriptions() | |
| print(f"\n✅ Database seeding completed successfully!") | |
| self._print_summary() | |
| except Exception as e: | |
| print(f"\n❌ Seeding failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| sys.exit(1) | |
| async def seed_tenants(self): | |
| """Seed tenant data""" | |
| print("📊 Seeding tenants...") | |
| tenants = [ | |
| { | |
| "id": str(uuid4()), | |
| "name": "General Hospital", | |
| "subdomain": "general", | |
| "settings": { | |
| "timezone": "America/New_York", | |
| "locale": "en-US" | |
| }, | |
| "is_active": True | |
| }, | |
| { | |
| "id": str(uuid4()), | |
| "name": "Children's Medical Center", | |
| "subdomain": "children", | |
| "settings": { | |
| "timezone": "America/Los_Angeles", | |
| "locale": "en-US" | |
| }, | |
| "is_active": True | |
| }, | |
| { | |
| "id": str(uuid4()), | |
| "name": "University Hospital", | |
| "subdomain": "university", | |
| "settings": { | |
| "timezone": "America/Chicago", | |
| "locale": "en-US" | |
| }, | |
| "is_active": True | |
| } | |
| ] | |
| self.seeded_data["tenants"] = tenants | |
| print(f" ✓ Created {len(tenants)} tenants") | |
| async def seed_users(self): | |
| """Seed user data""" | |
| print("👥 Seeding users...") | |
| users = [] | |
| roles = ["admin", "doctor", "nurse", "lab_tech", "pharmacist"] | |
| for i, tenant in enumerate(self.seeded_data["tenants"]): | |
| for role in roles: | |
| user = { | |
| "id": str(uuid4()), | |
| "username": f"{role}{i+1}", | |
| "email": f"{role}{i+1}@{tenant['subdomain']}.com", | |
| "full_name": f"{role.title()} User {i+1}", | |
| "role": role, | |
| "tenant_id": tenant["id"], | |
| "is_active": True | |
| } | |
| users.append(user) | |
| self.seeded_data["users"] = users | |
| print(f" ✓ Created {len(users)} users") | |
| async def seed_patients(self): | |
| """Seed patient data""" | |
| print("🏥 Seeding patients...") | |
| first_names = ["John", "Mary", "Michael", "Sarah", "David", "Emily", "James", "Jennifer", "Robert", "Linda"] | |
| last_names = ["Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis", "Rodriguez", "Martinez"] | |
| patients = [] | |
| for tenant in self.seeded_data["tenants"]: | |
| for i in range(50): # 50 patients per tenant | |
| patient = { | |
| "id": str(uuid4()), | |
| "medical_record_number": f"MRN{tenant['subdomain'][:3].upper()}{i+1:05d}", | |
| "first_name": first_names[i % len(first_names)], | |
| "last_name": last_names[i % len(last_names)], | |
| "date_of_birth": (datetime.now() - timedelta(days=365 * (20 + i % 60))).date().isoformat(), | |
| "gender": ["male", "female"][i % 2], | |
| "email": f"patient{i+1}@example.com", | |
| "phone": f"+1-555-{i:04d}", | |
| "tenant_id": tenant["id"], | |
| "created_at": datetime.now().isoformat() | |
| } | |
| patients.append(patient) | |
| self.seeded_data["patients"] = patients | |
| print(f" ✓ Created {len(patients)} patients") | |
| async def seed_providers(self): | |
| """Seed provider/practitioner data""" | |
| print("👨⚕️ Seeding providers...") | |
| specialties = [ | |
| "Internal Medicine", | |
| "General Surgery", | |
| "Pediatrics", | |
| "Cardiology", | |
| "Orthopedics", | |
| "Anesthesiology", | |
| "Emergency Medicine", | |
| "Family Medicine" | |
| ] | |
| providers = [] | |
| for tenant in self.seeded_data["tenants"]: | |
| for i, specialty in enumerate(specialties): | |
| provider = { | |
| "id": str(uuid4()), | |
| "npi": f"1{tenant['subdomain'][:3].upper()}{i+1:06d}", | |
| "first_name": f"Dr. {['James', 'Sarah', 'Michael', 'Emily'][i % 4]}", | |
| "last_name": f"{['Smith', 'Johnson', 'Williams', 'Brown'][i % 4]}", | |
| "specialty": specialty, | |
| "tenant_id": tenant["id"], | |
| "is_active": True | |
| } | |
| providers.append(provider) | |
| self.seeded_data["providers"] = providers | |
| print(f" ✓ Created {len(providers)} providers") | |
| async def seed_encounters(self): | |
| """Seed encounter data""" | |
| print("📋 Seeding encounters...") | |
| encounter_types = ["outpatient", "inpatient", "emergency", "virtual"] | |
| encounters = [] | |
| for tenant in self.seeded_data["tenants"]: | |
| tenant_patients = [p for p in self.seeded_data["patients"] if p["tenant_id"] == tenant["id"]] | |
| tenant_providers = [p for p in self.seeded_data["providers"] if p["tenant_id"] == tenant["id"]] | |
| for i in range(100): # 100 encounters per tenant | |
| patient = tenant_patients[i % len(tenant_patients)] | |
| provider = tenant_providers[i % len(tenant_providers)] | |
| encounter_date = datetime.now() - timedelta(days=i) | |
| encounter = { | |
| "id": str(uuid4()), | |
| "patient_id": patient["id"], | |
| "provider_id": provider["id"], | |
| "encounter_type": encounter_types[i % len(encounter_types)], | |
| "scheduled_date": encounter_date.isoformat(), | |
| "status": ["scheduled", "in-progress", "completed"][i % 3], | |
| "chief_complaint": [ | |
| "Annual physical", | |
| "Follow-up visit", | |
| "New patient consultation", | |
| "Routine checkup" | |
| ][i % 4], | |
| "tenant_id": tenant["id"], | |
| "created_at": encounter_date.isoformat() | |
| } | |
| encounters.append(encounter) | |
| self.seeded_data["encounters"] = encounters | |
| print(f" ✓ Created {len(encounters)} encounters") | |
| async def seed_surgeries(self): | |
| """Seed surgical procedure data""" | |
| print("🔪 Seeding surgeries...") | |
| procedures = [ | |
| ("47562", "Laparoscopic cholecystectomy"), | |
| ("27447", "Total knee arthroplasty"), | |
| ("27130", "Total hip arthroplasty"), | |
| ("43280", "Laparoscopic fundoplication"), | |
| ("49505", "Inguinal hernia repair") | |
| ] | |
| surgeries = [] | |
| for tenant in self.seeded_data["tenants"]: | |
| tenant_patients = [p for p in self.seeded_data["patients"] if p["tenant_id"] == tenant["id"]] | |
| tenant_providers = [p for p in self.seeded_data["providers"] | |
| if p["tenant_id"] == tenant["id"] and "Surgery" in p.get("specialty", "")] | |
| if not tenant_providers: | |
| continue | |
| for i in range(20): # 20 surgeries per tenant | |
| patient = tenant_patients[i % len(tenant_patients)] | |
| provider = tenant_providers[i % len(tenant_providers)] | |
| procedure = procedures[i % len(procedures)] | |
| surgery_date = datetime.now() + timedelta(days=i+1) | |
| surgery = { | |
| "id": str(uuid4()), | |
| "patient_id": patient["id"], | |
| "surgeon_id": provider["id"], | |
| "procedure_code": procedure[0], | |
| "procedure_name": procedure[1], | |
| "scheduled_date": surgery_date.isoformat(), | |
| "estimated_duration_minutes": 90 + (i * 30) % 180, | |
| "operating_room": f"OR-{(i % 5) + 1}", | |
| "status": "scheduled", | |
| "priority": ["elective", "urgent"][i % 2], | |
| "tenant_id": tenant["id"], | |
| "created_at": datetime.now().isoformat() | |
| } | |
| surgeries.append(surgery) | |
| self.seeded_data["surgeries"] = surgeries | |
| print(f" ✓ Created {len(surgeries)} surgeries") | |
| async def seed_lab_orders(self): | |
| """Seed laboratory order data""" | |
| print("🧪 Seeding lab orders...") | |
| test_panels = [ | |
| ("CBC", "Complete Blood Count"), | |
| ("CMP", "Comprehensive Metabolic Panel"), | |
| ("LIPID", "Lipid Panel"), | |
| ("HBA1C", "Hemoglobin A1C"), | |
| ("TSH", "Thyroid Stimulating Hormone") | |
| ] | |
| lab_orders = [] | |
| for tenant in self.seeded_data["tenants"]: | |
| tenant_encounters = [e for e in self.seeded_data["encounters"] if e["tenant_id"] == tenant["id"]] | |
| for i in range(50): # 50 lab orders per tenant | |
| encounter = tenant_encounters[i % len(tenant_encounters)] | |
| test = test_panels[i % len(test_panels)] | |
| order = { | |
| "id": str(uuid4()), | |
| "patient_id": encounter["patient_id"], | |
| "encounter_id": encounter["id"], | |
| "test_code": test[0], | |
| "test_name": test[1], | |
| "status": ["ordered", "collected", "processing", "completed"][i % 4], | |
| "priority": ["routine", "urgent", "stat"][i % 3], | |
| "tenant_id": tenant["id"], | |
| "created_at": datetime.now().isoformat() | |
| } | |
| lab_orders.append(order) | |
| self.seeded_data["lab_orders"] = lab_orders | |
| print(f" ✓ Created {len(lab_orders)} lab orders") | |
| async def seed_prescriptions(self): | |
| """Seed prescription data""" | |
| print("💊 Seeding prescriptions...") | |
| medications = [ | |
| ("Lisinopril", "10mg", "tablet"), | |
| ("Metformin", "500mg", "tablet"), | |
| ("Atorvastatin", "20mg", "tablet"), | |
| ("Omeprazole", "20mg", "capsule"), | |
| ("Levothyroxine", "50mcg", "tablet") | |
| ] | |
| prescriptions = [] | |
| for tenant in self.seeded_data["tenants"]: | |
| tenant_encounters = [e for e in self.seeded_data["encounters"] | |
| if e["tenant_id"] == tenant["id"] and e["status"] == "completed"] | |
| for i in range(30): # 30 prescriptions per tenant | |
| if not tenant_encounters: | |
| break | |
| encounter = tenant_encounters[i % len(tenant_encounters)] | |
| medication = medications[i % len(medications)] | |
| prescription = { | |
| "id": str(uuid4()), | |
| "patient_id": encounter["patient_id"], | |
| "encounter_id": encounter["id"], | |
| "prescriber_id": encounter["provider_id"], | |
| "medication_name": medication[0], | |
| "dosage": medication[1], | |
| "form": medication[2], | |
| "route": "oral", | |
| "frequency": "once daily", | |
| "duration_days": 90, | |
| "quantity": 90, | |
| "refills": 3, | |
| "status": "active", | |
| "tenant_id": tenant["id"], | |
| "created_at": datetime.now().isoformat() | |
| } | |
| prescriptions.append(prescription) | |
| self.seeded_data["prescriptions"] = prescriptions | |
| print(f" ✓ Created {len(prescriptions)} prescriptions") | |
| def _print_summary(self): | |
| """Print seeding summary""" | |
| print(f"\n📊 Seeding Summary:") | |
| print(f"{'='*50}") | |
| for category, items in self.seeded_data.items(): | |
| print(f" {category.title():20s}: {len(items):5d} records") | |
| total = sum(len(items) for items in self.seeded_data.values()) | |
| print(f"{'='*50}") | |
| print(f" {'Total':20s}: {total:5d} records") | |
| print(f"\n⏰ Completed at: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") | |
| async def export_seed_data(self, output_file: str): | |
| """Export seed data to JSON file""" | |
| import json | |
| output_path = Path(output_file) | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| with open(output_path, 'w') as f: | |
| json.dump(self.seeded_data, f, indent=2) | |
| print(f"\n💾 Seed data exported to: {output_path}") | |
| def main(): | |
| """Main CLI entry point""" | |
| parser = argparse.ArgumentParser( | |
| description="YAZ Care Platform - Database Seeder", | |
| formatter_class=argparse.RawDescriptionHelpFormatter, | |
| epilog=""" | |
| Examples: | |
| # Seed development database | |
| python seed_database.py | |
| # Seed with specific environment | |
| python seed_database.py --environment staging | |
| # Export seed data to file | |
| python seed_database.py --export data/seeds/sample_data.json | |
| # Clear database before seeding | |
| python seed_database.py --clear | |
| """ | |
| ) | |
| parser.add_argument( | |
| "--environment", | |
| default="development", | |
| choices=["development", "staging", "testing"], | |
| help="Target environment" | |
| ) | |
| parser.add_argument( | |
| "--export", | |
| help="Export seed data to JSON file" | |
| ) | |
| parser.add_argument( | |
| "--clear", | |
| action="store_true", | |
| help="Clear existing data before seeding" | |
| ) | |
| parser.add_argument( | |
| "--tenants-only", | |
| action="store_true", | |
| help="Seed only tenant data" | |
| ) | |
| parser.add_argument( | |
| "--users-only", | |
| action="store_true", | |
| help="Seed only user data" | |
| ) | |
| args = parser.parse_args() | |
| if args.clear: | |
| response = input("⚠️ This will clear existing data. Continue? (y/N): ") | |
| if response.lower() != 'y': | |
| print("❌ Seeding cancelled") | |
| return | |
| seeder = DatabaseSeeder(environment=args.environment) | |
| try: | |
| asyncio.run(seeder.seed_all()) | |
| if args.export: | |
| asyncio.run(seeder.export_seed_data(args.export)) | |
| except KeyboardInterrupt: | |
| print("\n\n❌ Seeding interrupted by user") | |
| sys.exit(1) | |
| except Exception as e: | |
| print(f"\n❌ Seeding failed: {e}") | |
| import traceback | |
| traceback.print_exc() | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() | |