Spaces:
Sleeping
Sleeping
Download src/training_donations.py from ConsulawTechnologies/NarratifAI: direct link, hf CLI and curl.
- Browser
- Download file 5.13 kB
-
https://huggingface.co/spaces/ConsulawTechnologies/NarratifAI/resolve/main/src/training_donations.py
- Command line
-
hf download hf://spaces/ConsulawTechnologies/NarratifAI/src/training_donations.py
-
curl -L -o training_donations.py https://huggingface.co/spaces/ConsulawTechnologies/NarratifAI/resolve/main/src/training_donations.py
5.13 kB
| """Opt-in recording donations for improving Yoruba, Igbo and Hausa transcription. | |
| A finished cloud transcription is kept only when its owner turned on "Help | |
| improve NarratifAI" (user_profiles.training_opt_in_at). The copy is compressed | |
| 16 kHz mono Opus audio plus the transcript, in the private training-donations | |
| bucket. Turning the option off or deleting the account removes it | |
| (training-consent function, account deletion). Nothing here may affect the job. | |
| """ | |
| import json | |
| import logging | |
| import os | |
| import subprocess | |
| import tempfile | |
| from typing import Callable, Optional | |
| logger = logging.getLogger(__name__) | |
| BUCKET = "training-donations" | |
| MAX_AUDIO_BYTES = 50 * 1024 * 1024 # the bucket's file limit | |
| def opted_in(uid: str, supabase_request: Callable) -> bool: | |
| rows = supabase_request("GET", "/rest/v1/user_profiles", | |
| params={"firebase_uid": f"eq.{uid}", "select": "training_opt_in_at"}) | |
| return bool(isinstance(rows, list) and rows and rows[0].get("training_opt_in_at")) | |
| def compress(content: bytes, filename: str) -> Optional[bytes]: | |
| """Speech-quality copy: 16 kHz mono Opus at 32 kbit/s (about 14 MB an hour).""" | |
| suffix = os.path.splitext(filename or "")[1][:8] or ".bin" | |
| with tempfile.TemporaryDirectory() as tmp: | |
| src, out = os.path.join(tmp, "in" + suffix), os.path.join(tmp, "out.ogg") | |
| with open(src, "wb") as f: | |
| f.write(content) | |
| done = subprocess.run(["ffmpeg", "-hide_banner", "-nostdin", "-y", "-i", src, "-vn", "-ac", "1", | |
| "-ar", "16000", "-c:a", "libopus", "-b:a", "32k", "-f", "ogg", out], | |
| capture_output=True, timeout=600) | |
| if done.returncode != 0 or not os.path.exists(out): | |
| return None | |
| with open(out, "rb") as f: | |
| return f.read() | |
| def donate(uid: str, job_id: str, content: bytes, filename: str, result: dict, | |
| supabase_request: Callable, storage: Callable) -> bool: | |
| """storage(method, path, data, content_type) -> bool talks to Supabase Storage.""" | |
| try: | |
| if not uid or not opted_in(uid, supabase_request): | |
| return False | |
| audio = compress(content, filename) | |
| if not audio or len(audio) > MAX_AUDIO_BYTES: | |
| return False | |
| transcript = json.dumps({ | |
| "job_id": job_id, | |
| "language": result.get("language"), | |
| "model_used": result.get("model_used"), | |
| "audio_duration": result.get("audio_duration"), | |
| "speakers": result.get("speakers"), | |
| "result": result.get("result"), | |
| }, ensure_ascii=False).encode() | |
| audio_path, transcript_path = f"{uid}/{job_id}.ogg", f"{uid}/{job_id}.json" | |
| stored = [] | |
| for path, data, kind in ((audio_path, audio, "audio/ogg"), (transcript_path, transcript, "application/json")): | |
| if not storage("POST", path, data, kind): | |
| raise RuntimeError("upload failed") | |
| stored.append(path) | |
| row = supabase_request("POST", "/rest/v1/training_donations", payload={ | |
| "firebase_uid": uid, "job_id": job_id, "language": result.get("language"), | |
| "duration_sec": result.get("audio_duration"), "audio_path": audio_path, | |
| "transcript_path": transcript_path}) | |
| # Turned off while we were saving: the withdrawal's cleanup may already | |
| # have run, so remove this copy ourselves. | |
| if row is None or not opted_in(uid, supabase_request): | |
| if row is not None: | |
| supabase_request("DELETE", "/rest/v1/training_donations", params={"job_id": f"eq.{job_id}"}) | |
| raise RuntimeError("not kept") | |
| return True | |
| except Exception as e: | |
| logger.warning(f"Training donation skipped: {type(e).__name__}") | |
| for path in locals().get("stored", []): | |
| try: | |
| storage("DELETE", path, None, None) | |
| except Exception: | |
| pass | |
| return False | |
| RETENTION_DAYS = 5 * 365 # privacy policy: donated recordings kept at most five years | |
| def purge_expired(supabase_request: Callable, storage: Callable, now: Optional[float] = None) -> int: | |
| """Delete donations older than RETENTION_DAYS (files first, then rows).""" | |
| import time | |
| from datetime import datetime, timezone | |
| cutoff = datetime.fromtimestamp((now or time.time()) - RETENTION_DAYS * 86400, timezone.utc).isoformat() | |
| rows = supabase_request("GET", "/rest/v1/training_donations", | |
| params={"created_at": f"lt.{cutoff}", "select": "job_id,audio_path,transcript_path", | |
| "limit": "200"}) | |
| removed = 0 | |
| for row in rows if isinstance(rows, list) else []: | |
| try: | |
| if all(storage("DELETE", p, None, None) for p in (row["audio_path"], row["transcript_path"])): | |
| supabase_request("DELETE", "/rest/v1/training_donations", params={"job_id": f"eq.{row['job_id']}"}) | |
| removed += 1 | |
| except Exception as e: | |
| logger.warning(f"Donation purge skipped one: {type(e).__name__}") | |
| return removed | |