Spaces:
Sleeping
Sleeping
Download backend/shared.py from NeonatalDAO/askneo: direct link, hf CLI and curl.
- Browser
- Download file 19.3 kB
-
https://huggingface.co/spaces/NeonatalDAO/askneo/resolve/main/backend/shared.py
- Command line
-
hf download hf://spaces/NeonatalDAO/askneo/backend/shared.py
-
curl -L -o shared.py https://huggingface.co/spaces/NeonatalDAO/askneo/resolve/main/backend/shared.py
19.3 kB
| import json | |
| import sqlite3 | |
| import time | |
| import jwt | |
| from datetime import date, datetime, timedelta, timezone | |
| from enum import Enum | |
| # pyrefly: ignore [missing-import] | |
| from argon2 import PasswordHasher | |
| # pyrefly: ignore [missing-import] | |
| from fastapi import Depends, HTTPException, Request, APIRouter | |
| # pyrefly: ignore [missing-import] | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| # pyrefly: ignore [missing-import] | |
| from pydantic import BaseModel, Field, EmailStr | |
| # pyrefly: ignore [missing-import] | |
| from sqlalchemy import Column, Integer, String, Text, cast, create_engine, select | |
| # pyrefly: ignore [missing-import] | |
| from sqlalchemy.orm import Session, declarative_base, sessionmaker | |
| # pyrefly: ignore [missing-import] | |
| from sqlalchemy.types import TypeDecorator | |
| # Constants | |
| SERVER_ERROR_MESSAGE = "We couldn't handle your request at this time - kindly contact support or try again much later" | |
| import os | |
| # Load the repo-root .env so DATABASE_URL / JWT_SECRET_KEY / API keys are honored | |
| # locally too (in production these come from the real container environment). | |
| # Only fills vars that aren't already set in the real environment. Public name | |
| # (`load_repo_env`) so other backend modules reuse it instead of copy-pasting. | |
| def load_repo_env() -> None: | |
| root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) | |
| env_path = os.path.join(root, ".env") | |
| if not os.path.exists(env_path): | |
| return | |
| try: | |
| with open(env_path, encoding="utf-8") as fh: | |
| for line in fh: | |
| line = line.strip() | |
| if not line or line.startswith("#") or "=" not in line: | |
| continue | |
| key, val = line.split("=", 1) | |
| key, val = key.strip(), val.strip().strip('"').strip("'") | |
| if key and val and key not in os.environ: | |
| os.environ[key] = val | |
| except Exception: | |
| pass | |
| load_repo_env() | |
| # SQLite file path — used when DATABASE_URL is unset, and kept defined either way | |
| # because other modules import DB_PATH. | |
| DB_PATH = os.environ.get("DB_PATH") | |
| if not DB_PATH: | |
| DB_PATH = "/content/drive/MyDrive/neonatal/database.db" | |
| if not os.path.exists("/content/drive/MyDrive/neonatal"): | |
| DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "database.db") | |
| # Database URL precedence: DATABASE_URL (production: Neon Postgres) > SQLite file. | |
| DATABASE_URL = os.environ.get("DATABASE_URL") | |
| if DATABASE_URL: | |
| # Normalize the "postgres://"/"postgresql://" forms to the psycopg (v3) | |
| # driver SQLAlchemy expects. | |
| if DATABASE_URL.startswith("postgres://"): | |
| DATABASE_URL = "postgresql+psycopg://" + DATABASE_URL[len("postgres://"):] | |
| elif DATABASE_URL.startswith("postgresql://"): | |
| DATABASE_URL = "postgresql+psycopg://" + DATABASE_URL[len("postgresql://"):] | |
| SQLALCHEMY_DATABASE_URL = DATABASE_URL | |
| else: | |
| SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_PATH}" | |
| # JWT Configuration | |
| # JWT_SECRET_KEY signs auth tokens, so it MUST be a strong, private value in | |
| # production. A committed fallback would let anyone forge a token for any uid, so | |
| # there is none: in production a missing key is a hard boot failure, and in | |
| # development we mint a random per-process key (tokens simply don't survive a | |
| # restart — acceptable locally, never a shared secret). | |
| # | |
| # "Production" is inferred from an explicit APP_ENV/ENVIRONMENT flag or from the | |
| # presence of DATABASE_URL (the managed Postgres only exists in deployed envs). | |
| def _is_production() -> bool: | |
| env = (os.environ.get("APP_ENV") or os.environ.get("ENVIRONMENT") or "").strip().lower() | |
| if env in ("production", "prod", "staging"): | |
| return True | |
| if env in ("development", "dev", "local", "test"): | |
| return False | |
| # No explicit flag: treat a configured managed database as production. | |
| return bool(os.environ.get("DATABASE_URL")) | |
| def _resolve_secret_key() -> str: | |
| key = os.environ.get("JWT_SECRET_KEY") | |
| if key: | |
| return key | |
| if _is_production(): | |
| raise RuntimeError( | |
| "JWT_SECRET_KEY is not set. Refusing to start in production with an " | |
| "insecure signing key — set JWT_SECRET_KEY (Space secret / container env)." | |
| ) | |
| # Development: use a machine-local, gitignored key file. It is generated once | |
| # and reused, so it is stable across restarts (a fresh random key every boot | |
| # would invalidate every issued token and silently log the developer out). | |
| # It is never committed and never used in production. | |
| import secrets | |
| key_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), ".dev_jwt_secret") | |
| try: | |
| if os.path.exists(key_path): | |
| existing = open(key_path, encoding="utf-8").read().strip() | |
| if existing: | |
| return existing | |
| generated = secrets.token_urlsafe(64) | |
| with open(key_path, "w", encoding="utf-8") as fh: | |
| fh.write(generated) | |
| print( | |
| "[shared] No JWT_SECRET_KEY set; generated a local dev key at " | |
| "backend/.dev_jwt_secret (gitignored, stable across restarts). " | |
| "Set JWT_SECRET_KEY to override." | |
| ) | |
| return generated | |
| except OSError: | |
| # Read-only filesystem etc. — fall back to an ephemeral key (tokens won't | |
| # survive a restart, but the server still boots). | |
| print( | |
| "[shared] WARNING: could not persist a dev JWT key; using an ephemeral " | |
| "one. Set JWT_SECRET_KEY for stable sessions." | |
| ) | |
| return secrets.token_urlsafe(64) | |
| SECRET_KEY = _resolve_secret_key() | |
| ALGORITHM = "HS256" | |
| ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 * 7 | |
| # Database Setup | |
| if SQLALCHEMY_DATABASE_URL.startswith("sqlite"): | |
| engine = create_engine( | |
| SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} | |
| ) | |
| else: | |
| # Neon (and managed Postgres generally) drop idle connections; pre-ping | |
| # discards a dead connection instead of handing it out from the pool. | |
| engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True) | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| Base = declarative_base() | |
| # Columns below were defined as String but receive bools/ints (and epoch-int | |
| # dates) at write time. SQLite coerces these silently; Postgres rejects them. | |
| # CoercedString restores the loose behavior by stringifying on write — bools as | |
| # "1"/"0" to match how SQLite previously stored them. | |
| class CoercedString(TypeDecorator): | |
| impl = String | |
| cache_ok = True | |
| def process_bind_param(self, value, dialect): | |
| if value is None: | |
| return None | |
| if isinstance(value, bool): | |
| return "1" if value else "0" | |
| if isinstance(value, Enum): | |
| # Store the underlying value ("high"), not str(member) which renders | |
| # as "EnergyLevel.high" for a (str, Enum). Native sqlite persisted the | |
| # value (str subclass); explicit str() here would otherwise corrupt | |
| # every enum column (energy, flow_intensity, urine_protein, …). | |
| return str(value.value) | |
| return str(value) | |
| # All model String columns below use the coercing variant. | |
| String = CoercedString | |
| # Models | |
| class UserTable(Base): | |
| __tablename__ = "users" | |
| id = Column(Integer, primary_key=True, autoincrement=True) | |
| name = Column(String(255), nullable=False) | |
| email = Column(String(255), nullable=False) | |
| password = Column(String(255), nullable=False) | |
| class PatientInfoTable(Base): | |
| __tablename__ = "patient_info" | |
| id = Column(Integer, primary_key=True, autoincrement=True) | |
| uid = Column(String(50), nullable=False) | |
| stage = Column(String(255), nullable=False) | |
| due_date = Column(String(100), nullable=False) | |
| baby_dob = Column(String(100), nullable=False) | |
| invite_code = Column(String(100), nullable=False) | |
| partner_stage = Column(String(255), nullable=False) | |
| partner_due_date = Column(String(100), nullable=False) | |
| partner_baby_dob = Column(String(100), nullable=False) | |
| emergency_contacts = Column(Text, nullable=False) | |
| goals = Column(Text, nullable=False) | |
| sub_goals = Column(Text, nullable=False) | |
| birth_intention = Column(String(255), nullable=False) | |
| feeding_intention = Column(String(255), nullable=False) | |
| personal_intentions = Column(Text, nullable=False) | |
| ttc_start_date = Column(String(100), nullable=False) | |
| known_conditions = Column(Text, nullable=False) | |
| irregular_cycles = Column(String(100), nullable=False) | |
| # Doctor / visit profile fields. Added after the table first shipped, so an | |
| # existing DB needs run_migrations() (below) to ALTER them in; fresh DBs get | |
| # them from create_all(). Defaults keep them populated for old rows/inserts. | |
| doctor_name = Column(String(255), nullable=False, default="", server_default="") | |
| doctor_phone = Column(String(100), nullable=False, default="", server_default="") | |
| last_visit_date = Column(String(100), nullable=False, default="", server_default="") | |
| next_appointment_date = Column(String(100), nullable=False, default="", server_default="") | |
| visit_prep_questions = Column(Text, nullable=False, default="[]", server_default="[]") | |
| class CycleLogTable(Base): | |
| __tablename__ = "cycle_logs" | |
| id = Column(Integer, primary_key=True, autoincrement=True) | |
| uid = Column(String(50), nullable=False) | |
| date_key = Column(String(100), nullable=False) | |
| is_period_start = Column(String(100), nullable=False) | |
| is_period_flow = Column(String(100), nullable=False) | |
| flow_intensity = Column(String(100), nullable=False) | |
| bbt_temp = Column(String(100), nullable=False) | |
| cm_type = Column(String(100), nullable=False) | |
| # OPK and HPT results can be string versions of Enums | |
| opk_result = Column(String(100), nullable=False) | |
| hpt_result = Column(String(100), nullable=False) | |
| had_sex = Column(String(100), nullable=False) | |
| used_protection = Column(String(100), nullable=False) | |
| mood = Column(Text, nullable=False) | |
| symptoms = Column(Text, nullable=False) | |
| notes = Column(Text, nullable=False) | |
| class ANCVisitsTable(Base): | |
| __tablename__ = "anc_visits" | |
| id = Column(Integer, primary_key=True, autoincrement=True) | |
| uid = Column(String(50), nullable=False) | |
| visit_date = Column(String(100), nullable=False) | |
| gestational_week = Column(String(100), nullable=False) | |
| weight = Column(String(100), nullable=False) | |
| blood_pressure_sys = Column(String(100), nullable=False) | |
| blood_pressure_dia = Column(String(100), nullable=False) | |
| fundal_height = Column(String(100), nullable=False) | |
| baby_heart_rate = Column(String(100), nullable=False) | |
| urine_protein = Column(String(100), nullable=False) | |
| urine_glucose = Column(String(100), nullable=False) | |
| pcv = Column(String(100), nullable=False) | |
| malaria_test = Column(String(100), nullable=False) | |
| blood_group = Column(String(100), nullable=False) | |
| hiv_status = Column(String(100), nullable=False) | |
| hbs_ag = Column(String(100), nullable=False) | |
| vdrl = Column(String(100), nullable=False) | |
| genotype = Column(String(100), nullable=False) | |
| class_topics = Column(Text, nullable=False) | |
| prescriptions = Column(Text, nullable=False) | |
| concern_flagged = Column(String(100), nullable=False) | |
| referred_to_doctor = Column(String(100), nullable=False) | |
| next_appointment_date = Column(String(100), nullable=False) | |
| notes = Column(Text, nullable=False) | |
| added_at = Column(String(100), nullable=False) | |
| class DailyLogTable(Base): | |
| __tablename__ = "daily_logs" | |
| id = Column(Integer, primary_key=True, autoincrement=True) | |
| uid = Column(String(50), nullable=False) | |
| date_key = Column(String(100), nullable=False) | |
| last_updated = Column(String(100), nullable=False) | |
| stage = Column(String(100), nullable=False) | |
| mood = Column(String(100), nullable=False) | |
| energy = Column(String(100), nullable=False) | |
| symptoms = Column(Text, nullable=False) | |
| symptom_severity = Column(String(100), nullable=False) | |
| medications = Column(Text, nullable=False) | |
| sleep_hours = Column(String(100), nullable=False) | |
| sleep_quality = Column(String(100), nullable=False) | |
| kick_count = Column(String(100), nullable=False) | |
| baby_feedings = Column(String(100), nullable=False) | |
| baby_nappies = Column(String(100), nullable=False) | |
| baby_sleep_hours = Column(String(100), nullable=False) | |
| baby_mood = Column(String(100), nullable=False) | |
| baby_symptoms = Column(Text, nullable=False) | |
| baby_symptom_severity = Column(String(100), nullable=False) | |
| water_glasses = Column(String(100), nullable=False) | |
| notes = Column(Text, nullable=False) | |
| created_at = Column(String(100), nullable=False) | |
| updated_at = Column(String(100), nullable=False) | |
| # Shared Enums and Schemas | |
| class PregnancyStage(str, Enum): | |
| ttc = "ttc" | |
| pregnancy = "pregnancy" | |
| newmom = "newmom" | |
| partner = "partner" | |
| class PartnerStage(str, Enum): | |
| ttc = "ttc" | |
| pregnancy = "pregnancy" | |
| newmom = "newmom" | |
| class BirthIntentions(str, Enum): | |
| natural = "natural" | |
| caesarean = "caesarean" | |
| undecided = "undecided" | |
| class FeedingIntentions(str, Enum): | |
| breast = "breast" | |
| formula = "formula" | |
| undecided = "undecided" | |
| class EmergencyContact(BaseModel): | |
| name: str | |
| phone: str | |
| relation: str | |
| id: str | |
| # Helper Functions | |
| pass_hash = PasswordHasher() | |
| def get_db(): | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |
| # Columns added to patient_info after it first shipped. Each entry is the | |
| # portable DDL for an additive ALTER (valid on both SQLite and Postgres). Kept | |
| # next to run_migrations() so the two stay in sync with the model above. | |
| _PATIENT_INFO_ADDED_COLUMNS = [ | |
| ("doctor_name", "VARCHAR(255) NOT NULL DEFAULT ''"), | |
| ("doctor_phone", "VARCHAR(100) NOT NULL DEFAULT ''"), | |
| ("last_visit_date", "VARCHAR(100) NOT NULL DEFAULT ''"), | |
| ("next_appointment_date", "VARCHAR(100) NOT NULL DEFAULT ''"), | |
| ("visit_prep_questions", "TEXT NOT NULL DEFAULT '[]'"), | |
| ] | |
| def run_migrations() -> None: | |
| """Additive, idempotent schema migrations. | |
| Base.metadata.create_all() creates missing TABLES but never adds COLUMNS to | |
| a table that already exists, so columns introduced after a table was first | |
| created must be added by hand. This adds any patient_info columns the model | |
| declares but the live table is missing. Safe to run on every boot and on | |
| both SQLite and Postgres (no Alembic dependency). | |
| """ | |
| from sqlalchemy import inspect as sa_inspect, text | |
| inspector = sa_inspect(engine) | |
| if "patient_info" not in inspector.get_table_names(): | |
| return # fresh DB: create_all already built it with every column | |
| existing = {c["name"] for c in inspector.get_columns("patient_info")} | |
| missing = [(n, ddl) for n, ddl in _PATIENT_INFO_ADDED_COLUMNS if n not in existing] | |
| if not missing: | |
| return | |
| with engine.begin() as conn: | |
| for name, ddl in missing: | |
| conn.execute(text(f"ALTER TABLE patient_info ADD COLUMN {name} {ddl}")) | |
| def dateToEpoch(d: date | None): | |
| if d is None: | |
| return "" | |
| return int(time.mktime(d.timetuple())) | |
| def createAccessToken(data: dict): | |
| to_encode = data.copy() | |
| expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES) | |
| to_encode.update({"exp": expire}) | |
| return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) | |
| def verifyPassword(saved_hash: str, test_pass: str): | |
| try: | |
| return pass_hash.verify(saved_hash, test_pass) | |
| except: | |
| return False | |
| def formatReturnedUserData(data: dict): | |
| ret_data = {} | |
| date_cols = ["due_date", "baby_dob", "partner_due_date", "partner_baby_dob", "ttc_start_date", | |
| "last_visit_date", "next_appointment_date"] | |
| ignore = ["id"] | |
| json_columns = ["emergency_contacts", "goals", "sub_goals", "known_conditions", "personal_intentions", | |
| "visit_prep_questions"] | |
| for key, val in data.items(): | |
| if key in date_cols: | |
| # Unset dates are stored as "" (see dateToEpoch); keep them null | |
| # instead of crashing on float(""). | |
| if val is None or val == "": | |
| ret_data.update({key: None}) | |
| else: | |
| # Return ISO YYYY-MM-DD — the format the client (and API_SPEC) | |
| # expects. A human-readable string like "1 September 2026" can't | |
| # be parsed back by the app, so dueDate/babyDOB/ttcStartDate were | |
| # silently dropped on login (after logout clears the local cache), | |
| # blanking the profile and the dashboard content derived from them. | |
| dt = datetime.fromtimestamp(float(val)) | |
| ret_data.update({key: dt.strftime("%Y-%m-%d")}) | |
| elif key in json_columns: | |
| ret_data.update({key: json.loads(val) if val else []}) | |
| elif key not in ignore: | |
| ret_data.update({key: val}) | |
| return ret_data | |
| # Auth Dependency | |
| security_scheme = HTTPBearer() | |
| async def checkUserValidity(request: Request, db: Session = Depends(get_db), token: HTTPAuthorizationCredentials = Depends(security_scheme)): | |
| jwt_cred = token.credentials | |
| try: | |
| payload = jwt.decode(jwt_cred, SECRET_KEY, algorithms=[ALGORITHM]) | |
| uid = payload.get("sub") | |
| if uid and uid.strip().isdigit(): | |
| patient_cols = [ | |
| col for col in PatientInfoTable.__table__.columns | |
| if col.name != "id" | |
| ] | |
| # users.id is Integer but patient_info.uid is a String holding the | |
| # same value; Postgres won't compare the two without an explicit cast | |
| # (SQLite does it implicitly). | |
| stm = select( | |
| UserTable.id, UserTable.email, UserTable.name, *patient_cols | |
| ).join( | |
| PatientInfoTable, UserTable.id == cast(PatientInfoTable.uid, Integer) | |
| ).where(UserTable.id == int(uid)) | |
| res = db.execute(stm).first() | |
| if res: | |
| user_data = formatReturnedUserData(res._asdict()) | |
| return { | |
| "status": "success", | |
| "data": user_data | |
| } | |
| else: | |
| return {"status": "error"} | |
| except jwt.ExpiredSignatureError: | |
| raise HTTPException(status_code=401, detail="Token has expired") | |
| except jwt.PyJWTError: | |
| raise HTTPException(status_code=401, detail="Could not validate credentials") | |
| return {"status": "error"} | |
| auth_router= APIRouter(prefix= "/auth", tags= ["Authentication"]) | |
| user_router= APIRouter( | |
| prefix= "/user", | |
| tags= ["Users"], | |
| dependencies= [Depends(checkUserValidity)] | |
| ) |