Spaces:
Sleeping
Sleeping
Mirror run logs to Google Drive
Browse files- .env.example +2 -0
- README.md +17 -0
- google_drive_logs.py +88 -0
- requirements.txt +2 -0
- scripts/test_silicon_logs.py +55 -0
- silicon_logs.py +41 -7
.env.example
CHANGED
|
@@ -1,3 +1,5 @@
|
|
| 1 |
OPENAI_API_KEY=
|
| 2 |
SILICON_LLM_MODEL=gpt-4o-mini
|
| 3 |
SILICON_LLM_MAX_AGENTS=3000
|
|
|
|
|
|
|
|
|
| 1 |
OPENAI_API_KEY=
|
| 2 |
SILICON_LLM_MODEL=gpt-4o-mini
|
| 3 |
SILICON_LLM_MAX_AGENTS=3000
|
| 4 |
+
GOOGLE_SERVICE_ACCOUNT_JSON=
|
| 5 |
+
GOOGLE_DRIVE_FOLDER_ID=
|
README.md
CHANGED
|
@@ -41,6 +41,23 @@ This repo is configured as a Docker Space. Set `OPENAI_API_KEY` as a Space secre
|
|
| 41 |
|
| 42 |
The app listens on port `7860`.
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
## Optional Nemotron Dataset
|
| 45 |
|
| 46 |
The app works with fallback distributions if the local dataset is not present. To enable local Nemotron-Personas-Korea metadata and sampling:
|
|
|
|
| 41 |
|
| 42 |
The app listens on port `7860`.
|
| 43 |
|
| 44 |
+
## Logs
|
| 45 |
+
|
| 46 |
+
Every completed silicon-sampling run is logged anonymously. By default logs are written to SQLite:
|
| 47 |
+
|
| 48 |
+
- `/data/silicon_logs.sqlite3` if a persistent Space volume is mounted
|
| 49 |
+
- `runs/silicon_logs.sqlite3` locally
|
| 50 |
+
- `/app/runs/silicon_logs.sqlite3` on a default Hugging Face Docker Space without persistent storage
|
| 51 |
+
|
| 52 |
+
Google Drive mirroring is optional. To enable it, create a Google Cloud service account with Drive API access, share one Drive folder with the service account email as an editor, then set these Space secrets:
|
| 53 |
+
|
| 54 |
+
```text
|
| 55 |
+
GOOGLE_SERVICE_ACCOUNT_JSON=<raw service account JSON or base64-encoded JSON>
|
| 56 |
+
GOOGLE_DRIVE_FOLDER_ID=<target Drive folder ID>
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
When enabled, each run also writes one JSON file to that Drive folder. The JSON includes respondent settings, question definitions, and aggregate result summaries; raw LLM responses are not mirrored.
|
| 60 |
+
|
| 61 |
## Optional Nemotron Dataset
|
| 62 |
|
| 63 |
The app works with fallback distributions if the local dataset is not present. To enable local Nemotron-Personas-Korea metadata and sampling:
|
google_drive_logs.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import io
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
from typing import Any
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
DRIVE_SCOPE = "https://www.googleapis.com/auth/drive.file"
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def drive_log_status() -> dict[str, Any]:
|
| 14 |
+
folder_id = google_drive_folder_id()
|
| 15 |
+
credentials = None
|
| 16 |
+
error = ""
|
| 17 |
+
if os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip() or os.getenv("GOOGLE_SERVICE_ACCOUNT_FILE", "").strip():
|
| 18 |
+
try:
|
| 19 |
+
credentials = load_service_account_info(raise_on_error=True)
|
| 20 |
+
except RuntimeError as exc:
|
| 21 |
+
error = str(exc)
|
| 22 |
+
return {
|
| 23 |
+
"enabled": bool(folder_id and credentials),
|
| 24 |
+
"folderIdSet": bool(folder_id),
|
| 25 |
+
"credentialsSet": bool(credentials),
|
| 26 |
+
"clientEmail": credentials.get("client_email") if isinstance(credentials, dict) else None,
|
| 27 |
+
"error": error,
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def upload_run_log_to_drive(run_document: dict[str, Any]) -> dict[str, Any]:
|
| 32 |
+
folder_id = google_drive_folder_id()
|
| 33 |
+
credentials_info = load_service_account_info(raise_on_error=True)
|
| 34 |
+
if not folder_id:
|
| 35 |
+
raise RuntimeError("GOOGLE_DRIVE_FOLDER_ID is required for Google Drive log upload")
|
| 36 |
+
if not credentials_info:
|
| 37 |
+
raise RuntimeError("GOOGLE_SERVICE_ACCOUNT_JSON or GOOGLE_SERVICE_ACCOUNT_FILE is required for Google Drive log upload")
|
| 38 |
+
|
| 39 |
+
from google.oauth2 import service_account
|
| 40 |
+
from googleapiclient.discovery import build
|
| 41 |
+
from googleapiclient.http import MediaIoBaseUpload
|
| 42 |
+
|
| 43 |
+
credentials = service_account.Credentials.from_service_account_info(credentials_info, scopes=[DRIVE_SCOPE])
|
| 44 |
+
service = build("drive", "v3", credentials=credentials, cache_discovery=False)
|
| 45 |
+
filename = drive_log_filename(run_document)
|
| 46 |
+
encoded = json.dumps(run_document, ensure_ascii=False, indent=2, sort_keys=True).encode("utf-8")
|
| 47 |
+
media = MediaIoBaseUpload(io.BytesIO(encoded), mimetype="application/json", resumable=False)
|
| 48 |
+
file_metadata = {"name": filename, "parents": [folder_id], "mimeType": "application/json"}
|
| 49 |
+
uploaded = service.files().create(body=file_metadata, media_body=media, fields="id,name,webViewLink").execute()
|
| 50 |
+
return {
|
| 51 |
+
"enabled": True,
|
| 52 |
+
"uploaded": True,
|
| 53 |
+
"fileId": uploaded.get("id"),
|
| 54 |
+
"name": uploaded.get("name") or filename,
|
| 55 |
+
"webViewLink": uploaded.get("webViewLink"),
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def google_drive_folder_id() -> str:
|
| 60 |
+
return os.getenv("GOOGLE_DRIVE_FOLDER_ID", "").strip()
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def load_service_account_info(*, raise_on_error: bool) -> dict[str, Any] | None:
|
| 64 |
+
raw = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON", "").strip()
|
| 65 |
+
file_path = os.getenv("GOOGLE_SERVICE_ACCOUNT_FILE", "").strip()
|
| 66 |
+
try:
|
| 67 |
+
if raw:
|
| 68 |
+
return parse_service_account_json(raw)
|
| 69 |
+
if file_path:
|
| 70 |
+
with open(os.path.expanduser(file_path), encoding="utf-8") as file:
|
| 71 |
+
return json.load(file)
|
| 72 |
+
except Exception as exc: # noqa: BLE001
|
| 73 |
+
if raise_on_error:
|
| 74 |
+
raise RuntimeError(f"invalid Google service account credentials: {exc}") from exc
|
| 75 |
+
return None
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def parse_service_account_json(raw: str) -> dict[str, Any]:
|
| 79 |
+
if raw.startswith("{"):
|
| 80 |
+
return json.loads(raw)
|
| 81 |
+
decoded = base64.b64decode(raw).decode("utf-8")
|
| 82 |
+
return json.loads(decoded)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def drive_log_filename(run_document: dict[str, Any]) -> str:
|
| 86 |
+
created = str(run_document.get("createdAt") or "unknown").replace(":", "-")
|
| 87 |
+
run_id = str(run_document.get("runId") or "run")
|
| 88 |
+
return f"{created}_{run_id}.json"
|
requirements.txt
CHANGED
|
@@ -1,2 +1,4 @@
|
|
| 1 |
openai>=1.0.0
|
| 2 |
duckdb>=1.0.0
|
|
|
|
|
|
|
|
|
| 1 |
openai>=1.0.0
|
| 2 |
duckdb>=1.0.0
|
| 3 |
+
google-api-python-client>=2.0.0
|
| 4 |
+
google-auth>=2.0.0
|
scripts/test_silicon_logs.py
CHANGED
|
@@ -8,12 +8,14 @@ import sqlite3
|
|
| 8 |
import sys
|
| 9 |
import tempfile
|
| 10 |
import unittest
|
|
|
|
| 11 |
from pathlib import Path
|
| 12 |
|
| 13 |
|
| 14 |
ROOT = Path(__file__).resolve().parents[1]
|
| 15 |
sys.path.insert(0, str(ROOT))
|
| 16 |
|
|
|
|
| 17 |
from silicon_logs import log_status, record_run, recent_runs # noqa: E402
|
| 18 |
|
| 19 |
|
|
@@ -52,8 +54,10 @@ class SiliconLogTests(unittest.TestCase):
|
|
| 52 |
client={"userAgent": "unit-test"},
|
| 53 |
)
|
| 54 |
self.assertTrue(info["runId"].startswith("run_"))
|
|
|
|
| 55 |
self.assertTrue(path.exists())
|
| 56 |
self.assertEqual(log_status()["runCount"], 1)
|
|
|
|
| 57 |
rows = recent_runs()
|
| 58 |
self.assertEqual(len(rows), 1)
|
| 59 |
self.assertEqual(rows[0]["sampleSize"], 2)
|
|
@@ -68,6 +72,57 @@ class SiliconLogTests(unittest.TestCase):
|
|
| 68 |
else:
|
| 69 |
os.environ["SILICON_LOG_DB"] = old
|
| 70 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
if __name__ == "__main__":
|
| 73 |
unittest.main(verbosity=2)
|
|
|
|
| 8 |
import sys
|
| 9 |
import tempfile
|
| 10 |
import unittest
|
| 11 |
+
import base64
|
| 12 |
from pathlib import Path
|
| 13 |
|
| 14 |
|
| 15 |
ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
sys.path.insert(0, str(ROOT))
|
| 17 |
|
| 18 |
+
from google_drive_logs import drive_log_filename, parse_service_account_json # noqa: E402
|
| 19 |
from silicon_logs import log_status, record_run, recent_runs # noqa: E402
|
| 20 |
|
| 21 |
|
|
|
|
| 54 |
client={"userAgent": "unit-test"},
|
| 55 |
)
|
| 56 |
self.assertTrue(info["runId"].startswith("run_"))
|
| 57 |
+
self.assertEqual(info["googleDrive"], {"enabled": False, "uploaded": False})
|
| 58 |
self.assertTrue(path.exists())
|
| 59 |
self.assertEqual(log_status()["runCount"], 1)
|
| 60 |
+
self.assertIn("googleDrive", log_status())
|
| 61 |
rows = recent_runs()
|
| 62 |
self.assertEqual(len(rows), 1)
|
| 63 |
self.assertEqual(rows[0]["sampleSize"], 2)
|
|
|
|
| 72 |
else:
|
| 73 |
os.environ["SILICON_LOG_DB"] = old
|
| 74 |
|
| 75 |
+
def test_record_run_can_mirror_json_document_to_google_drive_uploader(self) -> None:
|
| 76 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 77 |
+
path = Path(tmp) / "logs.sqlite3"
|
| 78 |
+
old = os.environ.get("SILICON_LOG_DB")
|
| 79 |
+
os.environ["SILICON_LOG_DB"] = str(path)
|
| 80 |
+
uploaded: list[dict] = []
|
| 81 |
+
|
| 82 |
+
def fake_uploader(document: dict) -> dict:
|
| 83 |
+
uploaded.append(document)
|
| 84 |
+
return {"enabled": True, "uploaded": True, "fileId": "drive_file_123", "name": drive_log_filename(document)}
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
info = record_run(
|
| 88 |
+
{
|
| 89 |
+
"config": {
|
| 90 |
+
"sampleSize": 1,
|
| 91 |
+
"genders": [{"id": "female", "enabled": True, "weight": 1}],
|
| 92 |
+
"ages": [{"id": "40s", "enabled": True, "weight": 1}],
|
| 93 |
+
"locations": [{"id": "busan", "enabled": True, "weight": 1}],
|
| 94 |
+
"locationOptions": [{"id": "busan", "label": "부산", "parentRegion": "busan", "level": "sido"}],
|
| 95 |
+
"questions": [{"id": "q_cat", "title": "선택 문항", "kind": "categorical", "options": [{"id": "a", "label": "A"}]}],
|
| 96 |
+
}
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"respondents": [{"id": "R0001"}],
|
| 100 |
+
"likertAnswers": [],
|
| 101 |
+
"categoricalAnswers": [{"questionId": "q_cat"}],
|
| 102 |
+
"openAnswers": [],
|
| 103 |
+
"questionStats": [{"questionId": "q_cat"}],
|
| 104 |
+
"regionStats": [],
|
| 105 |
+
"llmTrace": {"calls": 1, "rawResponses": ["not mirrored"]},
|
| 106 |
+
},
|
| 107 |
+
drive_uploader=fake_uploader,
|
| 108 |
+
)
|
| 109 |
+
self.assertEqual(info["googleDrive"]["fileId"], "drive_file_123")
|
| 110 |
+
self.assertEqual(len(uploaded), 1)
|
| 111 |
+
self.assertEqual(uploaded[0]["questions"][0]["kind"], "categorical")
|
| 112 |
+
self.assertEqual(uploaded[0]["respondentSettings"]["locations"][0]["label"], "부산")
|
| 113 |
+
self.assertNotIn("rawResponses", uploaded[0]["resultSummary"]["llmTrace"])
|
| 114 |
+
finally:
|
| 115 |
+
if old is None:
|
| 116 |
+
os.environ.pop("SILICON_LOG_DB", None)
|
| 117 |
+
else:
|
| 118 |
+
os.environ["SILICON_LOG_DB"] = old
|
| 119 |
+
|
| 120 |
+
def test_service_account_json_can_be_plain_or_base64(self) -> None:
|
| 121 |
+
raw = '{"type":"service_account","client_email":"bot@example.iam.gserviceaccount.com"}'
|
| 122 |
+
self.assertEqual(parse_service_account_json(raw)["client_email"], "bot@example.iam.gserviceaccount.com")
|
| 123 |
+
encoded = base64.b64encode(raw.encode("utf-8")).decode("utf-8")
|
| 124 |
+
self.assertEqual(parse_service_account_json(encoded)["client_email"], "bot@example.iam.gserviceaccount.com")
|
| 125 |
+
|
| 126 |
|
| 127 |
if __name__ == "__main__":
|
| 128 |
unittest.main(verbosity=2)
|
silicon_logs.py
CHANGED
|
@@ -6,7 +6,9 @@ import sqlite3
|
|
| 6 |
import uuid
|
| 7 |
from datetime import datetime, timezone
|
| 8 |
from pathlib import Path
|
| 9 |
-
from typing import Any
|
|
|
|
|
|
|
| 10 |
|
| 11 |
|
| 12 |
APP_DIR = Path(__file__).resolve().parent
|
|
@@ -30,16 +32,28 @@ def log_status() -> dict[str, Any]:
|
|
| 30 |
"exists": path.exists(),
|
| 31 |
"storage": "persistent_bucket" if str(path).startswith("/data/") else "local_ephemeral",
|
| 32 |
"runCount": count_runs(path) if path.exists() else 0,
|
|
|
|
| 33 |
}
|
| 34 |
|
| 35 |
|
| 36 |
-
def record_run(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
path = default_log_path()
|
| 38 |
ensure_schema(path)
|
| 39 |
run_id = f"run_{uuid.uuid4().hex[:16]}"
|
| 40 |
created_at = datetime.now(timezone.utc).isoformat()
|
| 41 |
config = payload.get("config", {}) if isinstance(payload.get("config"), dict) else {}
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
with sqlite3.connect(path) as conn:
|
| 44 |
conn.execute(
|
| 45 |
"""
|
|
@@ -57,13 +71,33 @@ def record_run(payload: dict[str, Any], result: dict[str, Any], client: dict[str
|
|
| 57 |
run_id,
|
| 58 |
created_at,
|
| 59 |
int(config.get("sampleSize") or len(result.get("respondents", [])) or 0),
|
| 60 |
-
json.dumps(
|
| 61 |
-
json.dumps(
|
| 62 |
-
json.dumps(
|
| 63 |
json.dumps(client or {}, ensure_ascii=False, sort_keys=True),
|
| 64 |
),
|
| 65 |
)
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
|
| 69 |
def recent_runs(limit: int = 20) -> list[dict[str, Any]]:
|
|
|
|
| 6 |
import uuid
|
| 7 |
from datetime import datetime, timezone
|
| 8 |
from pathlib import Path
|
| 9 |
+
from typing import Any, Callable
|
| 10 |
+
|
| 11 |
+
from google_drive_logs import drive_log_status, upload_run_log_to_drive
|
| 12 |
|
| 13 |
|
| 14 |
APP_DIR = Path(__file__).resolve().parent
|
|
|
|
| 32 |
"exists": path.exists(),
|
| 33 |
"storage": "persistent_bucket" if str(path).startswith("/data/") else "local_ephemeral",
|
| 34 |
"runCount": count_runs(path) if path.exists() else 0,
|
| 35 |
+
"googleDrive": drive_log_status(),
|
| 36 |
}
|
| 37 |
|
| 38 |
|
| 39 |
+
def record_run(
|
| 40 |
+
payload: dict[str, Any],
|
| 41 |
+
result: dict[str, Any],
|
| 42 |
+
client: dict[str, Any] | None = None,
|
| 43 |
+
drive_uploader: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
|
| 44 |
+
) -> dict[str, Any]:
|
| 45 |
path = default_log_path()
|
| 46 |
ensure_schema(path)
|
| 47 |
run_id = f"run_{uuid.uuid4().hex[:16]}"
|
| 48 |
created_at = datetime.now(timezone.utc).isoformat()
|
| 49 |
config = payload.get("config", {}) if isinstance(payload.get("config"), dict) else {}
|
| 50 |
+
run_document = build_run_document(
|
| 51 |
+
run_id=run_id,
|
| 52 |
+
created_at=created_at,
|
| 53 |
+
config=config,
|
| 54 |
+
result=result,
|
| 55 |
+
client=client or {},
|
| 56 |
+
)
|
| 57 |
with sqlite3.connect(path) as conn:
|
| 58 |
conn.execute(
|
| 59 |
"""
|
|
|
|
| 71 |
run_id,
|
| 72 |
created_at,
|
| 73 |
int(config.get("sampleSize") or len(result.get("respondents", [])) or 0),
|
| 74 |
+
json.dumps(run_document["respondentSettings"], ensure_ascii=False, sort_keys=True),
|
| 75 |
+
json.dumps(run_document["questions"], ensure_ascii=False, sort_keys=True),
|
| 76 |
+
json.dumps(run_document["resultSummary"], ensure_ascii=False, sort_keys=True),
|
| 77 |
json.dumps(client or {}, ensure_ascii=False, sort_keys=True),
|
| 78 |
),
|
| 79 |
)
|
| 80 |
+
info = {"runId": run_id, "createdAt": created_at, "storage": log_status()["storage"], "path": str(path)}
|
| 81 |
+
uploader = drive_uploader or upload_run_log_to_drive
|
| 82 |
+
if drive_uploader or drive_log_status()["enabled"]:
|
| 83 |
+
try:
|
| 84 |
+
info["googleDrive"] = uploader(run_document)
|
| 85 |
+
except Exception as exc: # noqa: BLE001
|
| 86 |
+
info["googleDrive"] = {"enabled": True, "uploaded": False, "error": f"{type(exc).__name__}: {exc}"}
|
| 87 |
+
else:
|
| 88 |
+
info["googleDrive"] = {"enabled": False, "uploaded": False}
|
| 89 |
+
return info
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def build_run_document(run_id: str, created_at: str, config: dict[str, Any], result: dict[str, Any], client: dict[str, Any]) -> dict[str, Any]:
|
| 93 |
+
return {
|
| 94 |
+
"runId": run_id,
|
| 95 |
+
"createdAt": created_at,
|
| 96 |
+
"respondentSettings": build_respondent_settings(config),
|
| 97 |
+
"questions": build_question_log(config),
|
| 98 |
+
"resultSummary": build_result_summary(result),
|
| 99 |
+
"client": client,
|
| 100 |
+
}
|
| 101 |
|
| 102 |
|
| 103 |
def recent_runs(limit: int = 20) -> list[dict[str, Any]]:
|