Upload 2 files
Browse files50 unmodified lines51525354555657585945 unmodified lines10510610710810911011111211311411550 unmodified lines| Variable | Default | Purpose ||----------|---------|---------|| `MOS_DATA_DIR` | `./data` | Where the SQLite DB, audio, and exports live. Point at your persistent mount (e.g. `/data` on a Space bucket). || `ADMIN_CODE` | `plotweaver-admin` | Entered on the signup form to create an admin account. **Override this.** || `MOS_JOURNAL_MODE` | `DELETE` | SQLite journal mode. Leave as `DELETE` on a bucket/network mount; set `WAL` only on a real local disk for extra concurrency. || `PORT` | `7860` | Port the app binds to. |---45 unmodified linesNotes:- The app already calls `launch(allowed_paths=[MOS_DATA_DIR])`, so Gradio is permitted to serve theaudio files stored on the bucket. Without this, the audio player can't load clips from `/data`.- Buckets are object storage mounted as a filesystem (FUSE). SQLite's **WAL** mode relies on sharedmemory that doesn't work on such mounts, which is why the default journal mode is `DELETE`. At afew dozen reviewers this is comfortable; the only risk is a small chance of DB corruption if theSpace is killed mid-write. For a bulletproof setup, keep the DB on local disk and sync periodicbackups to the bucket (not built in — easy to add if you need it).### Self-hosted (AlmaLinux / AWS, behind nginx)50 unmodified lines5152535455565758596045 unmodified lines10610710810911011111211311411511611711811950 unmodified lines| Variable | Default | Purpose ||----------|---------|---------|| `MOS_DATA_DIR` | `./data` | **Persistent** location for audio files, exports, and the DB backup. Point at your bucket mount (e.g. `/data`). || `MOS_LOCAL_DIR` | system temp `/…/mos_live` | Fast **local** disk where the live SQLite DB runs. It is backed up to `MOS_DATA_DIR` after every change and restored on startup. Usually leave as default. || `ADMIN_CODE` | `plotweaver-admin` | Entered on the signup form to create an admin account. **Override this.** || `MOS_SECRET` | derived from `ADMIN_CODE` | Secret used to sign browser session tokens (keeps a refreshed page logged in). Set a stable value in production. || `PORT` | `7860` | Port the app binds to. |---45 unmodified linesNotes:- The app already calls `launch(allowed_paths=[MOS_DATA_DIR])`, so Gradio is permitted to serve theaudio files stored on the bucket. Without this, the audio player can't load clips from `/data`.- **Database on buckets:** the live SQLite database does **not** run directly on the bucket, becauseobject-store/FUSE mounts don't provide reliable file locking and writes can silently fail toappear on later reads (causing "my ratings/files disappeared"). Instead the live DB runs on fastlocal disk (`MOS_LOCAL_DIR`) and is atomically backed up to the bucket (`MOS_DATA_DIR/mos.db`)after every change, then restored on startup. Audio files live on the bucket (static, write-once,no locking issues). This survives Space restarts as long as the bucket stays mounted.- **Staying logged in:** a signed token is stored in the browser (`gr.BrowserState`) so a pagerefresh keeps you signed in. Set a stable `MOS_SECRET` in production.### Self-hosted (AlmaLinux / AWS, behind nginx)
27 unmodified lines2829303132333435363 unmodified lines404142434445464748495051525354123 unmodified lines17817918018118218337 unmodified lines2212222232242252266 unmodified lines23323423523623723817 unmodified lines25625725825926026117 unmodified lines27928028128228328428528628728828929018 unmodified lines309310311312313314103 unmodified lines41841942042142242342442533 unmodified lines459460461462463464148 unmodified lines6136146156166176186196206216225 unmodified lines62862963063163263363463563663763863964064164264364464511 unmodified lines657658659660661662663664178 unmodified lines84384484584684784814 unmodified lines86386486586686786886987087187287387427 unmodified linesimport osimport reimport sqlite3import hashlibimport secretsimport datetime as dtimport shutil3 unmodified lines# --------------------------------------------------------------------------- ## Configuration# --------------------------------------------------------------------------- #DATA_DIR = os.environ.get("MOS_DATA_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "data"))AUDIO_DIR = os.path.join(DATA_DIR, "audio")EXPORT_DIR = os.path.join(DATA_DIR, "exports")DB_PATH = os.path.join(DATA_DIR, "mos.db")ADMIN_CODE = os.environ.get("ADMIN_CODE", "plotweaver-admin")for d in (DATA_DIR, AUDIO_DIR, EXPORT_DIR):os.makedirs(d, exist_ok=True)# The 7 MOS criteria, in the order they appear on the evaluation form.# (db_column, display_label, short_definition)CRITERIA = [123 unmodified linesuid = cur.lastrowidfor lid in (language_ids or []):conn.execute("INSERT OR IGNORE INTO user_languages (user_id, language_id) VALUES (?,?)", (uid, lid))return uid37 unmodified linesconn.execute("INSERT INTO languages (code, name, created_at) VALUES (?,?,?)", (code, name, now_iso()))except sqlite3.IntegrityError:raise ValueError(f"Language code '{code}' already exists.")def list_languages():6 unmodified linesconn.execute("DELETE FROM user_languages WHERE user_id = ?", (uid,))for lid in language_ids:conn.execute("INSERT OR IGNORE INTO user_languages (user_id, language_id) VALUES (?,?)", (uid, lid))# --------------------------------------------------------------------------- #17 unmodified lines(language_id, sample_name, (model_name or "unspecified").strip(), dst,1 if is_reference else 0, (transcript or "").strip(), now_iso()),)def list_samples(language_id=None):17 unmodified linesexcept OSError:passconn.execute("DELETE FROM samples WHERE id = ?", (sample_id,))def set_sample_transcript(sample_id, transcript):with get_conn() as conn:conn.execute("UPDATE samples SET transcript = ? WHERE id = ?",((transcript or "").strip(), sample_id))def get_sample_transcript(sample_id):18 unmodified linesf"comments=excluded.comments, updated_at=excluded.updated_at",[user_id, sample_id, *vals, (comments or "").strip(), now_iso()],)def get_rating(user_id, sample_id):103 unmodified linesinit_db()print("=" * 64)print("Plotweaver AI — TTS MOS Evaluation Platform")print(f"Data directory : {DATA_DIR}")print(f"Database : {DB_PATH}")print(f"Admin code : {ADMIN_CODE} (use on signup to create an admin)")print("=" * 64)33 unmodified linescss=CSS) as demo:session = gr.State(None) # logged-in user session dictcurrent_sample = gr.State(None) # sample id currently being ratedgr.Markdown("# 🎧 Plotweaver AI — TTS MOS Evaluation", elem_id="app-title")gr.Markdown("Rate synthesised speech on 7 quality criteria, by language.", elem_id="app-sub")148 unmodified lines# keep typed credentials so the user can correct themreturn (gr.update(), gr.update(), None, "❌ Invalid username or password.",gr.update(), gr.update(), gr.update(), gr.update(),gr.update(), gr.update())sess = user_session(user["id"])is_admin = sess["role"] == "admin"rl = reviewer_lang_choices(sess)return (gr.update(visible=False), # auth_colgr.update(visible=True), # app_col5 unmodified linesgr.update(choices=rl, value=None), # rate_langgr.update(value=""), # li_user (clear)gr.update(value=""), # li_pw (clear))li_btn.click(do_login, [li_user, li_pw],[auth_col, app_col, session, li_msg, greeting, reviewer_tabs, admin_panel,rate_lang, li_user, li_pw],)li_pw.submit( # allow Enter-to-logindo_login, [li_user, li_pw],[auth_col, app_col, session, li_msg, greeting, reviewer_tabs, admin_panel,rate_lang, li_user, li_pw],)def do_signup(username, email, password, lang_id, code):role = "admin" if (code and code == ADMIN_CODE) else "reviewer"11 unmodified lines[su_msg, su_user, su_email, su_pw, su_lang, su_code])def do_logout():return (gr.update(visible=True), gr.update(visible=False), None, "")logout_btn.click(do_logout, None, [auth_col, app_col, session, greeting])# ---- Rating flow ----def load_samples_for_lang(sess, language_id):178 unmodified lineswith get_conn() as conn:conn.execute("UPDATE users SET role=?, is_active=? WHERE id=?",(role, 1 if active == "yes" else 0, int(uid)))return f"✅ Updated user {int(uid)}.", _users_table()update_user_btn.click(admin_update_user, [session, promote_id, role_choice, active_choice],[user_admin_msg, users_tbl])14 unmodified linesreturn export_results(language_id)export_btn.click(admin_export, [session, res_lang], [res_file])# Populate admin tables + sample pickers right after an admin logs in.li_btn.click(lambda s: (_languages_table(), _samples_table(), _users_table(),gr.update(choices=_sample_delete_choices()),gr.update(choices=_sample_delete_choices()))if s and s["role"] == "admin" else ([], [], [], gr.update(choices=[]), gr.update(choices=[])),[session], [langs_tbl, samples_tbl, users_tbl, del_sample, tr_sample])# Refresh language-dependent choices on every page load, so newly added# languages appear in the signup form (and admin dropdowns) without a restart.27 unmodified lines28293031323334353637383 unmodified lines42434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116123 unmodified lines24024124224324424524637 unmodified lines2842852862872882892906 unmodified lines29729829930030130230317 unmodified lines32132232332432532632717 unmodified lines34534634734834935035135235335435535635735818 unmodified lines377378379380381382383103 unmodified lines48748848949049149249349449533 unmodified lines529530531532533534535148 unmodified lines6846856866876886896906916926936946956966976986997007015 unmodified lines70770870971071171271371471571671771871972072111 unmodified lines733734735736737738739740178 unmodified lines91992092192292392492514 unmodified lines94094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497527 unmodified linesimport osimport reimport hmacimport sqlite3import hashlibimport secretsimport tempfileimport datetime as dtimport shutil3 unmodified lines# --------------------------------------------------------------------------- ## Configuration# --------------------------------------------------------------------------- ## DATA_DIR is the *persistent* location (e.g. a Hugging Face Storage Bucket at# /data). Audio files and the database BACKUP live here.DATA_DIR = os.environ.get("MOS_DATA_DIR", os.path.join(os.path.dirname(os.path.abspath(__file__)), "data"))AUDIO_DIR = os.path.join(DATA_DIR, "audio")EXPORT_DIR = os.path.join(DATA_DIR, "exports")ADMIN_CODE = os.environ.get("ADMIN_CODE", "plotweaver-admin")# The LIVE database runs on fast LOCAL disk. SQLite needs real POSIX file# locking, which FUSE/object-store mounts (like a bucket) do not provide# reliably — running it directly on the bucket causes writes to silently not# appear on later reads. So we keep the working DB local and atomically back it# up to the bucket after every change (and restore it on startup).LOCAL_DIR = os.environ.get("MOS_LOCAL_DIR") or os.path.join(tempfile.gettempdir(), "mos_live")DB_PATH = os.path.join(LOCAL_DIR, "mos.db") # live (local disk)DB_BACKUP = os.path.join(DATA_DIR, "mos.db") # persistent copy (bucket)for d in (DATA_DIR, AUDIO_DIR, EXPORT_DIR, LOCAL_DIR):os.makedirs(d, exist_ok=True)# Restore the live DB from the persistent backup on startup (first boot / after# the container is recycled), so prior data survives restarts.if os.path.abspath(DB_BACKUP) != os.path.abspath(DB_PATH) \and os.path.exists(DB_BACKUP) and not os.path.exists(DB_PATH):try:shutil.copyfile(DB_BACKUP, DB_PATH)except OSError:pass# Secret used to sign browser session tokens (keeps a refreshed page logged in).SESSION_SECRET = os.environ.get("MOS_SECRET") or hashlib.sha256(("mos-session::" + ADMIN_CODE).encode()).hexdigest()def backup_db():"""Atomically copy the live DB to the persistent backup on the bucket."""if os.path.abspath(DB_BACKUP) == os.path.abspath(DB_PATH):returntry:src = sqlite3.connect(DB_PATH)dst = sqlite3.connect(DB_BACKUP)with dst:src.backup(dst)src.close()dst.close()except Exception: # noqa — best-effort backup; never break a writepassdef make_token(user_id):sig = hmac.new(SESSION_SECRET.encode(), str(user_id).encode(), hashlib.sha256).hexdigest()[:32]return f"{user_id}.{sig}"def verify_token(token):"""Return the user_id if the signed token is valid and the user is active."""if not token or "." not in str(token):return Noneuid_str, sig = str(token).rsplit(".", 1)try:uid = int(uid_str)except ValueError:return Nonegood = hmac.new(SESSION_SECRET.encode(), str(uid).encode(), hashlib.sha256).hexdigest()[:32]if not hmac.compare_digest(sig, good):return Nonewith get_conn() as conn:row = conn.execute("SELECT id, is_active FROM users WHERE id=?", (uid,)).fetchone()return uid if (row and row["is_active"]) else None# The 7 MOS criteria, in the order they appear on the evaluation form.# (db_column, display_label, short_definition)CRITERIA = [123 unmodified linesuid = cur.lastrowidfor lid in (language_ids or []):conn.execute("INSERT OR IGNORE INTO user_languages (user_id, language_id) VALUES (?,?)", (uid, lid))backup_db()return uid37 unmodified linesconn.execute("INSERT INTO languages (code, name, created_at) VALUES (?,?,?)", (code, name, now_iso()))except sqlite3.IntegrityError:raise ValueError(f"Language code '{code}' already exists.")backup_db()def list_languages():6 unmodified linesconn.execute("DELETE FROM user_languages WHERE user_id = ?", (uid,))for lid in language_ids:conn.execute("INSERT OR IGNORE INTO user_languages (user_id, language_id) VALUES (?,?)", (uid, lid))backup_db()# --------------------------------------------------------------------------- #17 unmodified lines(language_id, sample_name, (model_name or "unspecified").strip(), dst,1 if is_reference else 0, (transcript or "").strip(), now_iso()),)backup_db()def list_samples(language_id=None):17 unmodified linesexcept OSError:passconn.execute("DELETE FROM samples WHERE id = ?", (sample_id,))backup_db()def set_sample_transcript(sample_id, transcript):with get_conn() as conn:conn.execute("UPDATE samples SET transcript = ? WHERE id = ?",((transcript or "").strip(), sample_id))backup_db()def get_sample_transcript(sample_id):18 unmodified linesf"comments=excluded.comments, updated_at=excluded.updated_at",[user_id, sample_id, *vals, (comments or "").strip(), now_iso()],)backup_db()def get_rating(user_id, sample_id):103 unmodified linesinit_db()print("=" * 64)print("Plotweaver AI — TTS MOS Evaluation Platform")print(f"Persistent dir : {DATA_DIR}")print(f"Live database : {DB_PATH}")print(f"DB backup : {DB_BACKUP}")print(f"Admin code : {ADMIN_CODE} (use on signup to create an admin)")print("=" * 64)33 unmodified linescss=CSS) as demo:session = gr.State(None) # logged-in user session dictcurrent_sample = gr.State(None) # sample id currently being ratedauth_token = gr.BrowserState("") # signed token persisted in the browser (survives refresh)gr.Markdown("# 🎧 Plotweaver AI — TTS MOS Evaluation", elem_id="app-title")gr.Markdown("Rate synthesised speech on 7 quality criteria, by language.", elem_id="app-sub")148 unmodified lines# keep typed credentials so the user can correct themreturn (gr.update(), gr.update(), None, "❌ Invalid username or password.",gr.update(), gr.update(), gr.update(), gr.update(),gr.update(), gr.update(), gr.update(),gr.update(), gr.update(), gr.update(), gr.update(), gr.update())sess = user_session(user["id"])is_admin = sess["role"] == "admin"rl = reviewer_lang_choices(sess)if is_admin:lt, st, ut = _languages_table(), _samples_table(), _users_table()dch = _sample_delete_choices()du, tu = gr.update(choices=dch), gr.update(choices=dch)else:lt, st, ut = [], [], []du, tu = gr.update(), gr.update()return (gr.update(visible=False), # auth_colgr.update(visible=True), # app_col5 unmodified linesgr.update(choices=rl, value=None), # rate_langgr.update(value=""), # li_user (clear)gr.update(value=""), # li_pw (clear)make_token(user["id"]), # auth_token (persist login)lt, st, ut, du, tu, # admin tables + pickers)LOGIN_OUTPUTS = [auth_col, app_col, session, li_msg, greeting, reviewer_tabs, admin_panel,rate_lang, li_user, li_pw, auth_token,langs_tbl, samples_tbl, users_tbl, del_sample, tr_sample]li_btn.click(do_login, [li_user, li_pw], LOGIN_OUTPUTS)li_pw.submit(do_login, [li_user, li_pw], LOGIN_OUTPUTS) # Enter-to-logindef do_signup(username, email, password, lang_id, code):role = "admin" if (code and code == ADMIN_CODE) else "reviewer"11 unmodified lines[su_msg, su_user, su_email, su_pw, su_lang, su_code])def do_logout():return (gr.update(visible=True), gr.update(visible=False), None, "", "")logout_btn.click(do_logout, None, [auth_col, app_col, session, greeting, auth_token])# ---- Rating flow ----def load_samples_for_lang(sess, language_id):178 unmodified lineswith get_conn() as conn:conn.execute("UPDATE users SET role=?, is_active=? WHERE id=?",(role, 1 if active == "yes" else 0, int(uid)))backup_db()return f"✅ Updated user {int(uid)}.", _users_table()update_user_btn.click(admin_update_user, [session, promote_id, role_choice, active_choice],[user_admin_msg, users_tbl])14 unmodified linesreturn export_results(language_id)export_btn.click(admin_export, [session, res_lang], [res_file])# Restore the session on page load (so a refresh keeps you signed in).def restore_session(token):uid = verify_token(token)if not uid:# stay logged out; leave the UI at its default (auth visible)return (gr.update(), gr.update(), None, gr.update(), gr.update(), gr.update(),gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update())sess = user_session(uid)is_admin = sess["role"] == "admin"rl = reviewer_lang_choices(sess)if is_admin:lt, st, ut = _languages_table(), _samples_table(), _users_table()dch = _sample_delete_choices()du, tu = gr.update(choices=dch), gr.update(choices=dch)else:lt, st, ut = [], [], []du, tu = gr.update(), gr.update()return (gr.update(visible=False), # auth_colgr.update(visible=True), # app_colsess, # sessiongr.update(value=f"Signed in as **{sess['username']}** · {sess['role']}"), # greetinggr.update(visible=not is_admin), # reviewer_tabsgr.update(visible=is_admin), # admin_panelgr.update(choices=rl, value=None), # rate_langlt, st, ut, du, tu, # admin tables + pickers)demo.load(restore_session, [auth_token],[auth_col, app_col, session, greeting, reviewer_tabs, admin_panel, rate_lang,langs_tbl, samples_tbl, users_tbl, del_sample, tr_sample])# Refresh language-dependent choices on every page load, so newly added# languages appear in the signup form (and admin dropdowns) without a restart.
README.md+11-7
app.py+124-23