Spaces:
Build error
Build error
Download database.py from Gaurav22332/vaani-voice-api: direct link, hf CLI and curl.
- Browser
- Download file 2.09 kB
-
https://huggingface.co/spaces/Gaurav22332/vaani-voice-api/resolve/main/database.py
- Command line
-
hf download hf://spaces/Gaurav22332/vaani-voice-api/database.py
-
curl -L -o database.py https://huggingface.co/spaces/Gaurav22332/vaani-voice-api/resolve/main/database.py
2.09 kB
| """ | |
| Storage for voiceprint embeddings — deliberately kept in its OWN datastore, | |
| separate from the Next.js app's Prisma database. This isolates biometric | |
| data from transactional/business data, which is good practice for a real | |
| payments system (different retention rules, different access controls). | |
| Defaults to a local SQLite file. Point VOICE_DATABASE_URL at a hosted | |
| Postgres instance (with the pgvector extension, ideally, for production-scale | |
| nearest-neighbour search) to go fully online — no code changes required | |
| beyond the connection string, since this uses SQLAlchemy Core. | |
| """ | |
| import json | |
| import os | |
| from datetime import datetime, timezone | |
| from sqlalchemy import ( | |
| create_engine, | |
| Column, | |
| String, | |
| Text, | |
| DateTime, | |
| MetaData, | |
| Table, | |
| select, | |
| insert, | |
| update, | |
| ) | |
| DATABASE_URL = os.environ.get("VOICE_DATABASE_URL", "sqlite:///./voiceprints.db") | |
| engine = create_engine( | |
| DATABASE_URL, | |
| connect_args={"check_same_thread": False} if DATABASE_URL.startswith("sqlite") else {}, | |
| ) | |
| metadata = MetaData() | |
| voiceprints = Table( | |
| "voiceprints", | |
| metadata, | |
| Column("id", String, primary_key=True), | |
| Column("embedding_json", Text, nullable=False), # JSON list[float], mean of enrollment samples | |
| Column("sample_count", String, nullable=False), | |
| Column("created_at", DateTime, default=lambda: datetime.now(timezone.utc)), | |
| ) | |
| def init_db(): | |
| metadata.create_all(engine) | |
| def save_voiceprint(voiceprint_id: str, embedding: list[float], sample_count: int): | |
| with engine.begin() as conn: | |
| conn.execute( | |
| insert(voiceprints).values( | |
| id=voiceprint_id, | |
| embedding_json=json.dumps(embedding), | |
| sample_count=str(sample_count), | |
| ) | |
| ) | |
| def get_voiceprint(voiceprint_id: str) -> list[float] | None: | |
| with engine.begin() as conn: | |
| row = conn.execute( | |
| select(voiceprints.c.embedding_json).where(voiceprints.c.id == voiceprint_id) | |
| ).first() | |
| if not row: | |
| return None | |
| return json.loads(row[0]) | |