Spaces:
Runtime error
Runtime error
File size: 5,568 Bytes
d646f8a | 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 | """
Initialize database - create tables and add sample data
"""
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config.database import engine, Base, SessionLocal
from database.models import *
from datetime import datetime, date, timedelta
import hashlib
def create_tables():
"""Create all database tables"""
print("Creating database tables...")
Base.metadata.create_all(bind=engine)
print("✅ Tables created successfully!")
def add_sample_data():
"""Add sample data for testing"""
db = SessionLocal()
try:
# Check if data already exists
existing_users = db.query(User).first()
if existing_users:
print("⚠️ Database already has data. Skipping sample data.")
return
print("Adding sample data...")
# Create sample therapist user
therapist_user = User(
email="therapist@example.com",
username="dr_smith",
hashed_password=hashlib.sha256("password123".encode()).hexdigest(),
first_name="Sarah",
last_name="Smith",
role=UserRole.THERAPIST,
is_verified=True
)
db.add(therapist_user)
db.flush()
# Create therapist profile
therapist = Therapist(
user_id=therapist_user.id,
license_number="SLP12345",
specialization="Stuttering and Fluency",
clinic_name="Speech Wellness Center",
phone="555-0100",
bio="Specialized in stuttering therapy with 10 years of experience"
)
db.add(therapist)
db.flush()
# Create sample patient users
patient_user1 = User(
email="patient1@example.com",
username="john_doe",
hashed_password=hashlib.sha256("password123".encode()).hexdigest(),
first_name="John",
last_name="Doe",
role=UserRole.PATIENT,
is_verified=True
)
db.add(patient_user1)
db.flush()
# Create patient profile
patient1 = Patient(
user_id=patient_user1.id,
therapist_id=therapist.id,
date_of_birth=date(2000, 5, 15),
age=24,
gender="Male",
diagnosis="Developmental stuttering",
severity_level="Moderate",
therapy_goals=["Reduce stuttering frequency", "Improve fluency in conversations"],
preferred_technique="prolonged_speech"
)
db.add(patient1)
db.flush()
# Create sample assignment
assignment = Assignment(
therapist_id=therapist.id,
patient_id=patient1.id,
title="Daily Conversation Practice",
description="Practice conversational speech using prolonged speech technique",
practice_type="conversation",
technique="prolonged_speech",
target_sessions=5,
target_duration_minutes=10,
parameters={"topic": "hobbies", "difficulty": "intermediate"},
due_date=datetime.now() + timedelta(days=7)
)
db.add(assignment)
# Create a sample completed session
session = PracticeSession(
patient_id=patient1.id,
assignment_id=assignment.id,
practice_type="conversation",
technique="prolonged_speech",
duration_seconds=300,
prompt_text="Tell me about your favorite hobby",
transcribed_text="I really enjoy playing guitar in my free time",
total_words=10,
words_per_minute=120,
is_completed=True,
completed_at=datetime.now()
)
db.add(session)
db.flush()
# Create analysis for the session
analysis = SessionAnalysis(
session_id=session.id,
stutter_analysis={"total_stutters": 2, "types": {"repetition": 1, "block": 1}},
fluency_analysis={"prolongation_percentage": 75, "consistency": 0.8},
total_stutters=2,
stutter_frequency_percent=5.0,
fluency_score=75,
rushed_speech_severity="minimal",
struggled_phonemes=["g", "t"],
patient_feedback="Good use of prolonged speech technique. Keep practicing smooth transitions."
)
db.add(analysis)
db.commit()
print("✅ Sample data added successfully!")
except Exception as e:
print(f"❌ Error adding sample data: {e}")
db.rollback()
finally:
db.close()
def reset_database():
"""Drop all tables and recreate"""
print("⚠️ Dropping all tables...")
Base.metadata.drop_all(bind=engine)
create_tables()
add_sample_data()
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Database initialization")
parser.add_argument("--reset", action="store_true", help="Drop and recreate all tables")
parser.add_argument("--sample-data", action="store_true", help="Add sample data")
args = parser.parse_args()
if args.reset:
response = input("⚠️ This will DELETE all data. Are you sure? (yes/no): ")
if response.lower() == "yes":
reset_database()
else:
print("Cancelled.")
else:
create_tables()
if args.sample_data:
add_sample_data() |